title: T minus time to ransom!

text:
# Question
Title: T minus time to ransom!
The WannaCrypt ransomware has struck and it is attacking networks right, left and center. A network is defined by an m\*n binary matrix (a), which has a a\[i\]\[j\] = 1 if a computer is infected and a\[i\]\[j\] = 0 if it is not. At the end of each hour, all computers that are a neighbour (which shares a side or a corner with) of an infected computer are infected by the ransomware..

Your job is to calculate the time after which all computers in the network will be infected by the virus.

Also, do keep in mind that the shortest code wins.

## Input

The first 2 lines contains the values of m and n respectively. The next m lines contain a binary string of length n corresponding to the computers of the network.

## Output

An integer which is equal to the mumber of hours after which the whole network will be infected by the ransomware.

## Input Constraints

1 \<= m,n \<= 1000

# Sample Test Cases

## Test Case 1

Sample Input

```
2
2
11
11

```

Sample Output

```
0

```

## Test Case 2

Sample Input

```
3
4
0101
0001
0001

```

Sample Output

```
2

```

## Test Case 3

Sample Input

```
2
2
10
00

```

Sample Output

```
1

```

P.S: Take input in any format that doesn't violate the ordering of \[m,n,matrix\] P.P.S: m and n are optional inputs. The only compulsory input is the matrix.

# Answer
> 0 votes
# Octave, 26 bytes

```
@(a)max(bwdist(a,"ch")(:))

```

Try it online!

Explanation:

Computes maximum of the chessboard distance transform of the binary matrix.

# Answer
> 3 votes
# Python 2, 90 bytes

```
g=lambda a:min(min(a))or-~g(map(lambda*c:map(max,(0,)+c[:-1],c,c[1:]),*a))
lambda a:g(a)/2

```

Try it online!

Accepts a matrix as a list of lists of 0 and 1.

### How it works

```
g=lambda a:min(min(a))or…

```

If the smallest element of the matrix is 1 (it is completely infected), return 1; otherwise…

```
                        -~g(…                                            )

```

return 1 plus the recursive result on the following modified matrix…

```
                            map(lambda*c:…                           ,*a)

```

for each old *column* `c`

```
                                         map(max,(0,)+c[:-1],c,c[1:])

```

produce a new *row* by zipping `max` over the down-shifted, original, and up-shifted versions of `c`. (`map` fills in the gap at the end of `c[1:]` with `None`, which is falsy and smaller than both `0` and `1`.)

Each iteration of `g` computes all vertical infections, then transposes the matrix. This way, every 2 iterations of `g` compute all horizontal, vertical, and diagonal infections.

```
lambda a:g(a)/2

```

Because the base case of `g` with a fully infected matrix gave 1 rather than 0, the parity works out such that floored division by 2 always gives the correct result.

# Answer
> 0 votes
# R, 127 bytes

```
function(x,y,m){a=which(m);b=cbind(a%/%x+1,(a-1)%%x+1);for(i in 1:x)for(j in 1:y)m[i,j]=min(apply(abs(b-c(i,j)),1,max));max(m)}

```

For each clean computer (`0`), checks what the closest infected computer is. Outputs the maximum value, because that is how long it would take for the infection to reach it.

It is a function that takes the number of rows `x`, the number of columns `y` and the matrix `m` as input. More explanation follows when I get home.

```
function(x,y,m){                     A function taking 3 arguments
  a=which(m)                         Take the indices of matrix m containing 1 (TRUE). This
                                     implicitly turns m into a vector, so a contains all
                                     the wrapped indices.
  b=cbind(a%/%x+1,(a-1)%%x+1)        Turn a back into i and j indices for 1s in m.
  for(i in 1:x)                      Loop over all rows
    for(j in 1:y)                    Loop over all columns
      m[i,j]=                        Assign in m[i,j] the following:
      min(                           Take the lowest value of the vector created below v
      apply(abs(b-c(i,j)),1,max));   Take the absolute difference between (i,j) and all
                                     (x,y) where m[x,y] == 1. Take the rowwise maximum
                                     to find the distance between (i,j) and all the 1s in m
  max(m)}                            Return the maximum distance.

```

# Answer
> 0 votes
# Python 2, 181 bytes

```
import numpy as n,scipy.ndimage.filters as s
g=lambda m=n.asarray(list(map(int,list(i))for i in input().split())),i=0:g(s.maximum_filter(m,3),i+1)if n.count_nonzero(m)<m.size else i

```

Recursively calls itself until each element is 1 and returns the iteration count. Accepts input as a string: `"0101\n0001\n0001"`

---
Tags: code-golf
---


title: The sum of some parts

text:
# Question
Title: The sum of some parts
## Challenge

Given a list of keys and values, and a target `n`, return all sets of keys where the sum of their values equals or exceeds `n`.

## Input

Input will be like this:

```
[["Part 1", 20], ["Part 2", 15], ["Part 3", 14.75], ["Part 4", 3]], 30

```

Input consists of a list with keys (which can be any kind of string) and values (which can be any kind of decimal). Also, a number `n` is supplied as the target.

You may take these inputs in any format you like, in any order etc. It needs to support strings, numbers (with decimal precision and possibly negative).

The target might be positive, negative or zero. The list will always contain at least 1 KV-pair.

Each key is guaranteed to be unique. Each value \<\> 0. Different keys can have the same value. It is not guaranteed that a list holds a satisfactory combination.

## Output

The expected output is a list of lists with all keys that have a combined value `>=n`. Each set that manages to satisfy this condition needs to be shown in a clearly distinguishable group, for example by separating them with brackets or newlines.

Sample output for the above input:

```
Part 1, Part2
Part 1, Part 3
Part 1, Part2, Part 3
Part 1, Part2, Part 4
Part 1, Part3, Part 4
Part 1, Part2, Part 3, Part 4
Part2, Part 3, Part 4

```

Note that each combination needs to be unique. The output doesn't need to be sorted, but `part 1, part 2` is considered a duplicate of `part 2, part 1` and should not be shown twice.

## Additional rules

* Standard loopholes are forbidden
* Answer must be a full program or a function, not a snippet or a REPL-entry.
* , shortest answer in bytes wins.

# Answer
> 4 votes
# 05AB1E, 10 bytes

```
æʒø`O²‹_i,

```

Try it online!

**Explanation**

```
æ           # compute powerset of input
 ʒ          # filter out falsy values (we don't actually filter, it just saves a byte)
  ø         # zip into a list of keys and a list of values
   `        # push separately to the stack
    O       # sum values
     ²‹_i   # if not less than input_2
         ,  # print list of keys

```

# Answer
> 3 votes
# Mathematica, ~~45~~ 43 bytes

<sup>*Saved 2 bytes due to alephalpha.*</sup>

```
Keys/@Cases[Subsets@#,a_/;Tr@Values@a>=#2]&

```

Anonymous function. Takes a list of rules (e.g., `{"Part 1"->20,"Part 2"->15}`) and a number as input and returns a list of lists of strings as output.

# Answer
> 2 votes
# Japt, ~~15~~ ~~14~~ 12 bytes

*Saved 2 bytes thanks to @obarakon*

```
à f_xÅ¨VÃm®g

```

Test it online! Output is a nested array, but it's rather hard to tell so the `-R` flag has been added to put each item on its own line.

### Explanation

```
 à f_  xÅ  ¨ VÃ m®   g
Uà fZ{Zxs1 >=V} mmZ{Zg}
                         // Implicit: U = input array, V = input number
Uà                       // Take all combinations of U.
   fZ{        }          // Filter to only the combinations Z where this is true:
      Zxs1               //   The sum of each [item of Z]'s item at index 1
           >=V           //   is greater than or equal to V.
                m        // Map each combination in the result by
                 mZ{  }  //   mapping each array Z in that to
                    Zg   //     the first item in Z.
                         // This replaces each key-value pair with its key.
                         // Implicit: output result of last expression

```

An interesting thing to note is the use of `Å` (or `s1` ) instead of `g1` . `s1`  on an array simply returns everything but the first item. Since each array only has two items (a key and a value), this returns an array containing the value. `x` then uses JS's native coercion to convert this into a number, and on an array containing one number, this happens to return that number.

# Answer
> 2 votes
## JavaScript (ES6), ~~127~~ 123 bytes

Takes the list `l` and the target `n` in currying syntax `(l)(n)`. Returns an array of arrays.

```
l=>n=>l.reduceRight((p,c)=>[...p,...p.map(x=>[c,...x])],[[]]).filter(x=>x.map(x=>s+=x[1],s=0)&&s>=n).map(x=>x.map(x=>x[0]))

```

### Demo

```
let f =

l=>n=>l.reduceRight((p,c)=>[...p,...p.map(x=>[c,...x])],[[]]).filter(x=>x.map(x=>s+=x[1],s=0)&&s>=n).map(x=>x.map(x=>x[0]))

console.log(
  f([["Part 1", 20], ["Part 2", 15], ["Part 3", 14.75], ["Part 4", 3]])(30)
)
```

# Answer
> 2 votes
## Haskell, 60 bytes

```
n#l=[map fst=<<e|e<-mapM(\p->[[],[p]])l,sum(map snd=<<e)>=n]

```

Usage example: `3 # [("Part 1",1), ("Part 2",1.5),("Part 3",2)]` -\> `[["Part 2","Part 3"],["Part 1","Part 3"],["Part 1","Part 2","Part 3"]]`.

Try it online!

How it works:

```
      mapM(\p->[[],[p]])l         -- turn every element p from the input list l
                                  -- into a list [[],[p]], i.e. [<empty list>, <singleton list p>]
                                  -- and make a list of all combinations there by
                                  -- picking either [] or [p]
                                  -- e.g. [1,2] -> [[[],[]], [[],[2]], [[1],[]], [[1],[2]]]
    e<-                           -- keep all elements e from this list where
          sum(map snd=<<e)>=n     -- the second elements of the pairs are >= n
[map fst=<<e |         ]          -- and extract the first elements of the pairs from it

```

# Answer
> 1 votes
# , 97 bytes

```
function(l,v){z=c()
k=combn
for(i in 1:length(l))z=c(z,lapply(k(l,i,,F)[k(l,i,sum)>=v],names))
z}

```

This is an anonymous function which takes the input in as a named list of values `l` (where the names are the parts) and a value `v`, and returns a list of vectors of names. Returns a list with value `NULL` if no matches are found.

The function `combn(x,m)`generates all elements of `x` taken `m` at a time with some options to simplify and aggregate. Hence the code iteratively generates the subsets of size `i`, `k(l,i,,F)`, subsets those whose sum `k(l,i,sum)` is at least `v`, and then applies the `names` function to to each of those to extract the part names.

A different input scheme might lead to golfier code.

Try it online!

# Answer
> 1 votes
# PHP, 134 bytes

```
function f($a,$n){$r=$n>0?[]:[[]];if([$k,$v]=each($a)){unset($a[$k]);$r=f($a,$n);foreach(f($a,$n-$v)as$t){$t[]=$k;$r[]=$t;}}return$r;}

```

Test it online.

---
Tags: code-golf
---


title: Find Subset Factors

text:
# Question
Title: Find Subset Factors
Let's imagine we have a finite set of positive integers. This set can be represented as a line of dots where each integer present in the set is filled in like a scantron or punch card. For example the set `{1,3,4,6}` could be represented as:

```
*.**.*

```

`*` represents a member of our set and `.` represents an integer that is not a member oft he set.

These sets have "factors". Loosely x is a factor of y if y can be built out of copies of x. More rigorously our definition of factor is as follows:

* x is a factor of y if and only if y is the union of a number of *disjoint* sets, all of which are x with an offset.

We would call `*.*` a **factor** of `*.**.*` because it is quite clearly made up of two copies of `*.*` put end to end.

```
*.**.*
------
*.*...
...*.*

```

Factors don't have to be end to end, we would also say that `*.*` is a factor of `*.*.*.*`

```
*.*.*.*
-------
*.*....
....*.*

```

Factors can also overlap. This means `*.*` is also a factor of `****`

```
****
----
*.*.
.*.*

```

However a number cannot be covered by a factor more than once. For example `*.*` is *not* a factor of `*.*.*`.

---

Here is a more complicated example:

```
 *..*.**..***.*.*

```

This has `*..*.*` as a factor. You can see that below where I have lined up the three instances of `*..*.*`.

```
*..*.**..***.*.*
----------------
*..*.*..........
......*..*.*....
..........*..*.*

```

# Task

Given a set by any reasonable representation output all the sets that are factors of the input.

You may index by any value, (that is you may select a smallest number that can be present in the input). You may also assume that the input set will always contain that smallest value.

This is a question so you should aim to do this in as few bytes as possible.

# Test Cases

*These test cases were done by hand, there may be a mistake or two on the larger ones*

```
*                -> *
*.*.*            -> *, *.*.*
*.*.*.*          -> *, *.*, *...*, *.*.*.*
******           -> *, **, *..*, ***, *.*.*, ******
*..*.**..***.*.* -> *, *..*.*, *.....*...*, *..*.**..***.*.*
*...*****.**.**  -> *, *...**.**, *.....*, *...*****.**.**

```

# Answer
> 3 votes
## Mathematica, ~~71~~ 68 bytes

```
#&@@@Cases[(s=Subsets)@s@#,x_/;Sort[Join@@x]==#&&Equal@@(#&@@@x-x)]&

```

Input as `{1,3,5,7}` (sorted) and output as `{{1, 3, 5, 7}, {1, 3}, {1, 5}, {1}}`. The function will throw a bunch of messages.

This is **O(22Nope)** (where **N** is the length of the input and **o=p=e=1**...). It generates all subsets of subsets, then selects those that result in the input send when joined together (ensuring we're only considering partitions) and where all elements are the same if we subtract the smallest value of each subset).

# Answer
> 2 votes
# Jelly, 12 bytes

```
;÷@DỊȦ
ÆDçÐf

```

Input and output use `1` and `0` instead of `*` and `.`.

Try it online!

### How it works

```
ÆDçÐf   Main link. Argument: n (integer with decimal digits 1 and 0)

ÆD      Compute all divisors of n.
  çÐf   Filter; call the helper link with left argument d and right argument n for
        all divisors d of n. Return the array of d's for which the helper link
        returns a truthy value.

;÷@DỊȦ  Helper link. Left argument: d. Right argument: n

 ÷@     Divide n by d.
;       Concatenate, yielding [d, n÷d].
   D    Decimal; convert both integers in the pair to base 10.
    Ị   Insignificant; map 1 and 0 to 1, all other positive integers to 0.
     Ȧ  All; return 1 iff the result contains no zeroes.

```

---
Tags: code-golf, combinatorics, set-partitions, set-theory
---


title: Interpret the interpreted

text:
# Question
Title: Interpret the interpreted
# Task

You must write a program in Language A that will output the source code for a program in Language B which will then output the source code for a program in Language C and so on and so forth. The final program must output the `x root y` where `x` and `y` are the inputs e.g. in Python:

```
print(int(input()) ** (1/int(input())))

```

Your score is `L / N` where `L` is the total length of all your programs and `N` is the number of languages.

`N` must be greater or equal to 3 to allow for a proper challenge.

Different versions don't count as different languages

As usual, lowest score wins.

# Example submission

```
# C++/brainfuck/Python, 223 points

## C++

    #include <iostream>

    int main() {
      printf("+[------->++<]>++.++.---------.+++++.++++++.+[--->+<]>+.-----[->+++<]>.+++++.++++++.+[--->+<]>+.-----[->+++<]>.+++++.++.+++++.-.+[--->+<]>+.+..---------.++++++++++..----------.++++++++.+++++++++.--.[--->+<]>++++.+++++.++++++.+[--->+<]>+.-----[->+++<]>.+++++.++.+++++.-.+[--->+<]>+.+....");
    }

## brainfuck

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

## Python

    print(int(input()) ** (1/int(input())))

```

# Answer
# 05AB1E/GolfScript/Jelly ~~11~~ 6 bytes / 3 languages = 2

```
"'İ*@'

```

Both 05AB1E and GolfScript have the nice property that they do implicit prints of strings, so we only lose 3 bytes on them (because 05AB1E doesn't need the closing quote).

Also, my first 05AB1E, GolfScript, and Jelly programs.
> 1 votes

---
Tags: math, code-challenge
---


title: Wardialing in the Modern World

text:
# Question
Title: Wardialing in the Modern World
# Introduction

Wardialing was a very interesting way to try to hack people back in the '80s and '90s. When everyone used dial-up, people would dial huge amounts of numbers to search for BBS's, computers, or fax machines. If it was answered by a human or answering machine, it hung up and forgot the number. If it was answered by a modem or a fax machine, it would make note of the number.

"Of course, you realize this means War...dialing?" \<--- Pun made by @Shaggy

# Challenge

Your job is to make a URL wardialer. Something that tests and checks if it's a valid website from one letter of the alphabet.

# Constraints

* Program must take user input. This input has to be a letter of the alphabet, no numbers. Just one letter of the alphabet and form multiple URLs that start with the letter. **Input letter will be lowercase, not uppercase.**
* Standard loopholes apply.
* You must make 8 URLs from 1 letter, and test to see if it is a valid site.
* If you hit an error (not a response code), instead of leaving it blank, go ahead and return a 404
* If you hit a redirect (3xx), return a 200 instead.
* **You may output the results in any reasonable format, as long as it includes the website name, status codes for all the websites and the redirects.**
* This is , so shortest amount of bytes wins.

# What counts as a URL for this challenge?

http://{domain-name}.{com or net or org}

For this challenge, the domain name should only be 4 letters long, no more, no less.

# What should I test?

For each 4 letter domain name, test it against three top-level domains (.com, .net, .org). Record all the response codes from each URL, remember from the constraints that any (3xx) should return 200 and be recorded as a redirect in the output and any error getting to the website should result in a 404.

# Input

> a

# Output

```
+---------+------+------+------+------------+
| Website | .com | .net | .org | Redirects? |
+---------+------+------+------+------------+
| ajoe    | 200  | 200  | 200  | .com, .net |
+---------+------+------+------+------------+
| aqiz    | 200  | 404  | 404  | no         |
+---------+------+------+------+------------+
| amnx    | 200  | 503  | 404  | .com       |
+---------+------+------+------+------------+
| abcd    | 200  | 404  | 200  | .com       |
+---------+------+------+------+------------+
| ajmx    | 200  | 503  | 404  | no         |
+---------+------+------+------+------------+
| aole    | 200  | 200  | 200  | .com       |
+---------+------+------+------+------------+
| apop    | 404  | 200  | 200  | .net       |
+---------+------+------+------+------------+
| akkk    | 200  | 200  | 200  | .com       |
+---------+------+------+------+------------+

```

# Answer
# Bash, 90 bytes

```
for i in $1{100..104}.{com,net,org};{ echo $i;(curl -IL $i 2>:||echo HTTP 404)| grep HTTP;}

```

Sample output:

```
b100.com
HTTP/1.1 301 Moved Permanently
HTTP/1.1 200 OK
b100.net
HTTP/1.1 301 Moved Permanently
HTTP/1.1 200 OK
b100.org
HTTP 404
b101.com
HTTP/1.1 301 Moved Permanently
HTTP/1.1 200 OK
b101.net
HTTP/1.1 406 Not Acceptable
b101.org
HTTP/1.1 406 Not Acceptable
b102.com
HTTP/1.1 200 OK
b102.net
HTTP 404
b102.org
HTTP 404
b103.com
HTTP/1.1 301 Moved Permanently
HTTP/1.1 200 OK
b103.net
HTTP 404
b103.org
HTTP 404
b104.com
HTTP/1.1 301 Moved Permanently
HTTP/1.1 200 OK
b104.net
HTTP/1.1 301 Moved Permanently
HTTP/1.1 200 OK
b104.org
HTTP 404

```
> 0 votes

# Answer
# Python 2 + requests, ~~198~~ 191 bytes

```
from requests import*
def f(c):
 for i in range(24):
	u='http://'+c+`i/3`*3+'.'+'cnooermtg'[i%3::3]
	try:a=get(u,allow_redirects=0).status_code
	except:a=404
	if a/100==3:a='200 R'
	print u,a

```

---

Sample output for `a`:

```
http://a000.com 404
http://a000.net 404
http://a000.org 404
http://a111.com 200
...
http://a666.org 502
http://a777.com 403
http://a777.net 200 R
http://a777.org 200

```
> 1 votes

# Answer
# Ruby, 145 + 10 = 155 bytes

\+ 10 bytes for command line arguments.

Probably not winning any beauty contests with this:

```
x=[*$<.getc+?a*3..?z*4]
24.times{|i|r=Net::HTTP.get_response(URI(p"http://#{x[i/3]}."+'comnetorg'[i*3%9,3])).code rescue"404"
p r=~/^3/?"200R":r}

```

Run with `ruby -rnet/http wardialing.rb`

Example:

```
$ ruby -rnet/http wardialing.rb <<< g
"http://gaaa.com"
"200R"
"http://gaaa.net"
"200"
"http://gaaa.org"
"200"
"http://gaab.com"
"200"
"http://gaab.net"
"200"
"http://gaab.org"
"200"
"http://gaac.com"
"404"

(etc)

```
> 1 votes

# Answer
# NodeJS, ~~249~~ 246 bytes

-3 bytes thanks to @ASCII-only.

```
c=>{r=_=>Math.random().toString(36).slice(-3),o="",q=i=>(u=`http://${n=i%3?n:c+r()}.`+["com","net","org"][i%3],o+=u+" ",d=r=>(o+=(/^3/.test(s=r.statusCode||404)?"200R":s)+`
`,--i?q(i):console.log(o)),require("http").get(u,d).on("error",d)),q(24)}

```

Creates random three-letter strings from 1-9 and a-z for each domain. Redirects are shown as `200R`.

Try it online
(Note: may take a minute or two to complete all requests)

### Sample output

```
http://a9k9.com 200
http://a9k9.net 404
http://a9k9.org 404
http://a529.com 200
http://a529.net 404
http://a529.org 404
http://asor.com 200R
http://asor.net 404
http://asor.org 404

```

## Longer version with table output, 278 bytes

```
c=>{r=_=>Math.random().toString(36).slice(-3),o=h=`name .com    .net    .org
`,q=i=>(i%3||(n=c+r(),o+=n+`    `),u=`http://${n}.`+h.substr(6+i%3*5,3),d=r=>(o+=(/^3/.test(s=r.statusCode||404)?"200R":s)+(++i%3?` `:`
`),i<24?q(i):console.log(o)),require("http").get(u,d).on("error",d)),q(0)}

```

Whitespace in `name .com .net .org` and `n+` `` are literal tab characters.

### Sample table output

```
name    .com    .net    .org
aa4i    200     200     200
a66r    404     404     404
anmi    200     200     403
aaor    403     200R    200R

```
> 0 votes

# Answer
# PHP, 221 bytes

```
for($c=8;$c--;){$u=$argv[1];for($i=3;$i--;)$u.=chr(rand(97,122));for($z=0;$z<3;){$r="$u.".['com','net','org'][$z++];$h=get_headers("http://$r");$s=$h?substr($h[0],9,3):404;$t=(3==intval($s/100))?"200R":$s;echo"$r $t\n";}}

```

With CRs and indentation

```
for($c=8;$c--;){
    $u=$argv[1];
    for($i=3;$i--;)$u.=chr(rand(97,122));
    for($z=0;$z<3;){
        $r="$u.".['com','net','org'][$z++];
        $h=get_headers("http://$r");
        $s=$h?substr($h[0],9,3):404;
        $t=(3==intval($s/100))?"200R":$s;
        echo"$r $t\n";
    }
}

```

Sample output on 'b':

```
bnjz.com 404
bnjz.net 200
bnjz.org 404
bkxw.com 200
bkxw.net 200
bkxw.org 403
biak.com 200
biak.net 403
biak.org 200R
bpzb.com 200
bpzb.net 200
bpzb.org 404
bigr.com 404
bigr.net 200
bigr.org 200
bcei.com 404
bcei.net 200R
bcei.org 200
bexc.com 200
bexc.net 200
bexc.org 404
bset.com 404
bset.net 200
bset.org 200

```
> 0 votes

# Answer
# q/kdb+, ~~392~~ ~~378~~ ~~300~~ 276 bytes

**Solution:**

```
t:{
  w:y,($:)x;
  r:@[{"J"$-3#12#(`$":http://",x)y}[w;];"GET / HTTP/1.1\r\nHost:",w,4#"\r\n";404];
  (x,`w`r)!(r;`$y;$[(r>299)&r<400;[r:200;x];`])
  }
f:{
  R:(`w,x,`r)xcols(,/)each(x)t\:/:{x,/:3 cut 24?.Q.a}y;
  (`Website,x,`$"Redirects?")xcol update r:`No from R where r=`
  }[`.com`.org`.net;]

```

**Example:**

```
q)f"a"
Website .com .org .net Redirects?
---------------------------------
amik    200  200  200  .net
abjl    200  200  503  No
afuw    403  200  200  No
agby    200  200  200  No
afen    200  200  200  .net
ajch    200  404  200  No
aaro    200  200  200  No
ajsr    200  404  503  No

```

**Notes:**

Current solution is fairly hefty... Half the code is trying to fetch a URL, the other half is presenting the results nicely, unsure how much further I can golf this.

**Explanation:**

Function t

```
w:y,($:)x       // convert suffix (`.com) to string, prepend host and save in w
@[x;y;404]      // try function x with parameter y, on error return 404
"GET /..."      // HTTP GET request in shortest form
`:http://x y    // open web connection to x, send request y
-3#12#          // truncate output to 12 chars, take last 3 chars
"J"$            // cast result to long
$[x;y;z]        // if x then y, else z
(x)!(y)         // create a dictionary with x as keys, y as values

```

Function f

```
24?.Q.a         // take 24 random characters from a-z
x,/:3 cut       // cut into 3-character lists, prepend input 'x'
t\:/:           // call function t with each combination of left and right
(,/) each       // raze (reduce) each result
xcols           // re-order columns into output format
xcol            // rename columns

```
> 0 votes

---
Tags: code-golf, internet
---


title: Decode the chmod

text:
# Question
Title: Decode the chmod
## Challenge

Given a three digit octal permissions number, output the permissions that it grants.

## chmod

On UNIX OSes file permissions are changed using the `chmod` command. There are few different ways of using chmod, but the one we will focus on today is using octal permissions.

The three digits in the permissions number represent a different person:

* The first digit represents the permissions for the **user**
* The second digit represents the permissions for the **group**
* The last digit represents the permissions for **others**

Next, each digit represents a permission as shown below in:

```
Key: number | permission

7 | Read Write and Execute
6 | Read and Write
5 | Read and Execute
4 | Read only
3 | Write and Execute
2 | Write only
1 | Execute only
0 | None

```

## Input

The input will be the three digit number as a string, e.g.:

```
133

```

or

```
007

```

This will be passed either via STDIN or via function arguments.

## Output

Your output should be the different permissions for each of the user, the group and the others. You must display this information like so:

```
User:   ddd
Group:  ddd
Others: ddd

```

Where there are three spaces after `User`, two spaces after `Group` and one space after `Others`. You replace `ddd` with the permissions information.

Your output may be to STDOUT or as a returned string.

## Examples

**Input:** 666

**Output:**

```
User:   Read and Write
Group:  Read and Write
Others: Read and Write

```

---

**Input:** 042

**Output:**

```
User:   None
Group:  Read only
Others: Write only

```

---

**Input:** 644

**Output:**

```
User:   Read and Write
Group:  Read only
Others: Read only

```

## Winning

The shortest code in bytes wins.

# Answer
> 3 votes
# 05AB1E, ~~89~~ 87 bytes

```
”‚Ý:‚Ù:ˆ†:”ð¡v”Šª0ÍÃ20‡í20‡í1ÍÃ0‚Ø20‚Ø1ÍÃ0‚Ø1‡í0‚Ø‡í1ÍÃ”2ð'€É«:1ð'€ƒ«:0ð«¡¹Nèèð3N-×ìyì,

```

~~Summons the **Cthulhu** encoding.~~ Uses the **CP-1252** encoding. Try it online!

# Answer
> 14 votes
## Javascript (ES6), ~~165~~ 161 bytes

```
n=>[0,1,2].map(i=>(s='User:  3Group: 68Others:58None576Read48Write476Execute475and4576only'.split(/(\d+)/))[i*2]+s[n[i]*2+1].replace(/./g,c=>' '+s[c*2])).join`
`

```

*Edit: +1 byte to fulfill the "no tab" rule*

### Examples

```
let f =
n=>[0,1,2].map(i=>(s='User:  3Group: 68Others:58None576Read48Write476Execute475and4576only'.split(/(\d+)/))[i*2]+s[n[i]*2+1].replace(/./g,c=>' '+s[c*2])).join`
`
console.log(f("666"));
console.log(f("042"));
console.log(f("644"));
console.log(f("137"));
```

# Answer
> 13 votes
## GNU sed, ~~187 163~~ 158 (157+1) bytes

Run with *-r* (ERE regexp). File contains no trailing newline.

```
s/(.)(.)/User:   \1\nGroup:  \2\nOthers: /g
s/[4-7]/Read &/g
s/[2367]/Write &/g
s/[1357]/Execute &/g
s/(\w) (\w+) [1-7]/\1 and \2/g
s/[1-7]/only/g
s/0/None/g

```

# Answer
> 6 votes
# Jelly, ~~100 91~~ 85 bytes

<sup>~~Almost certainly golfable - 91 bytes, what?!~~</sup> **8 months and 6 wisdom bytes!**
\- 1. more string compression;
\- 2. remove the post-ordinal decrement by 48 since indexing is modular;
\- 3. use better tacit chaining).

-9 bytes with the kind help of @Lynn running string compressions for me

```
,“£ɱ~»
Ñ
ṖK,“ and”,Ṫ
LĿK
7RBUT€Uị“ØJƓ“¥Ị£“¤/¡»Ç€“¡*g»ṭ
“ṖŒhJ"ỵd¡»ḲðJ4_⁶ẋ⁸,"j€”:ż⁹Oị¢¤Y

```

Test it at **TryItOnline**

How?

```
,“£ɱ~» - Link 1: pair with the string "Only"

Ñ - Link 2: call next link

ṖK,“ and”,Ṫ - Link 3: insert " and" between the last two elements of x
Ṗ           - x[:-1]
 K          - join with spaces
   “ and”   - the string " and"
          Ṫ - x[-1]
  ,      ,  - pair

LĿK - Link 4: call appropriate link and add missing spaces
L   - length
 Ŀ  - call link at that index
  K - join the result with spaces

7RBUT€Uị“ØJƓ“¥Ị£“¤/¡»Ç€“¡*g»ṭ - Link 5: construct all 8 cases
7R                            - range of 7: [1,2,3,4,5,6,7]
  B                           - binary (vectorises): [[1],[1,0],[1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]
   U                          - reverse (vectorises): [[1],[0,1],[1,1],[0,0,1],[1,0,1],[0,1,1],[1,1,1]]
    T€                        - indexes of truthy values for each: [[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
      U                       - reverse (vectorises): [[1],[2],[2,1],[3],[3, 1],[3,2],[3,2,1]]
        “ØJƓ“¥Ị£“¤/¡»         - list of strings: ["Execute","Write","Read"]
       ị                      - item at index (vectorises): [["Execute"],["Write"],["Write","Execute"],["Read"],["Read","Execute",["Read","Write"],["Read","Write","Execute"]]
                     Ç€       - call the previous link for each
                       “¡*g»  - the string "None"
                            ṭ - tack (Jelly is 1-based so the 8th item will be indexed as 0)

“ṖŒhJ"ỵd¡»ḲðJṚ⁶ẋ⁸,"j€”:ż⁹Oị¢¤Y - Main Link: parse input and make the result. e.g.: "042"
“ṖŒhJ"ỵd¡»                     - dictionary compression of "User Group Others"
          Ḳ                    - split at spaces -> ["User","Group","Others"]
           ð                   - dyadic chain separation, call that g (input as right)
            J                  - range of length of g -> [1,2,3]
             Ṛ                 - reverse -> [3,2,1]
              ⁶                - literal space
               ẋ               - repeat -> ["   ","  "," "]
                ⁸              - chain's left argument, g
                  "            - zip with:
                 ,             -   pair -> [["User","   "],["Group","  "],["Others"," "]]
                     ”:        - literal ':'
                   j€          - join for €ach -> ["User:   ","Group:  ","Others: "]
                            ¤  - nilad followed by link(s) as a nilad:
                        ⁹      - chain's right argument, the input string -> "042"
                         O     -   cast to ordinal (vectorises) -> [48, 52, 50]
                           ¢   -   call last link (5) as a nilad  -> ["Execute Only","Write Only","Write and Execute","Read Only","Read and Execute","Read and Write","Read Write and Execute","None"]
                          ị    -   index into (1-based & modular) -> ["None","Read Only","Write Only"]
                       ż       - zip together -> [["User:   ","None"],["Group:  ","Read Only"],["Others: ","Write Only"]]
                             Y - join with line feeds -> ["User:   ","None",'\n',"Group:  ","Read Only",'\n',"Others: ","Write Only"]
                               - implicit print:
                                             >>>User:   None
                                             >>>Group:  Read Only
                                             >>>Others: Write Only

```

# Answer
> 6 votes
# C# 214 Bytes

```
string h(string y){string e="Execute ",r="Read ",w="Write ",O="Only",a="and ";var z=new[]{"None",e+O,w+O,w+a+e,r+O,r+a+e,r+a+w,r+w+a+e};return$"User:   {z[y[0]-'0']}\nGroup:  {z[y[1]-'0']}\nOthers: {z[y[2]-'0']}";}

```

# Answer
> 4 votes
# Octave, 185 bytes

```
@(n)fprintf('User:   %s\nGroup:  %s\nOthers: %s',{'Read Write and Execute','Read and Write','Read and Execute','Read only','Write and Execute','Write only','Execute only','None'}{56-n})

```

Create anonymous function that takes the input as a string: '042'. Convert it to an array: `(56-'042)' = [0 4 2]`. Use this as multiple cell indices to index the cell array with `Read Write and Execute','Read and Write', ...`. Uses `fprintf` to output the three strings, with the appropriate categories: `User:` , `Group:`  and `Others:` .

I tried finding a way to store `Execute`, `Write`, `Read` as separate words and concatenate as needed, but this turned out longer than the naive approach.

**Examples:**

```
1> f('000')
User:   None
Group:  None
Others: None
2> f('042')
User:   None
Group:  Read only
Others: Write only

```

**Try it online.**

# Answer
> 4 votes
## PowerShell v2+, ~~189~~ 168 bytes

```
[char[]]$args[0]|%{('User','Group','Others')[$i++]+":`t"+('None','Read','Write','Execute','only','and')[(0,(3,4),(2,4),(2,5,3),(1,4),(1,5,3),(1,5,2),(1,2,5,3))[$_-48]]}

```

Loops through the input `$args[0]` as a `char`-array. Each iteration, we index into an array with `$i++` (defaults to `0`) to select `User`, `Group`, or `Others`, concatenate that with a colon and a tab, and concatenate that with another array index.

Here's the magic. We implicitly cast the `char` to an `int` and subtract `48` (i.e., turning ASCII `48` (`"0"`) into `0`), choosing the appropriate wording as an array of `int`s. That array is subsequently used as the index into the `'None','Read','Write','Execute','only','and'` array. Since the default `$ofs` (Output Field Separator) is a space, this correctly inserts spaces between the array elements when stringified (which happens when it concatenates to the left).

These three strings are left on the pipeline, and output via implicit `Write-Output` happens at program completion.

### Example

```
PS C:\Tools\Scripts\golfing> .\decode-the-chmod.ps1 '123'
User:   Execute only
Group:  Write only
Others: Write and Execute

```

# Answer
> 3 votes
## Straw, 193 bytes

```
((01234567)((None)(Execute only)(Write only)(Write and Execute)(Read only)(Read and Execute)(Read and Write)(Read Write and Execute)))::~<:{-¢(User:   ),+>
>}:{-¢(Group:  ),+>
>}-¢(Others: ),+>

```

Try it online

Push 3 times a conversion table on the first stack, switch to the second stack, convert each number using the conversation table and print.

# Answer
> 2 votes
**PHP, ~~169~~ 159 bytes**

```
foreach([User,Group,Others]as$i=>$u){echo"
$u: ";for($n=[5,33,34,66,35,67,131,531][$i]];$n;$n>>=3)echo["and",Execute,Write,Read,only,None][$n&7]," ";}

```

takes string as command line argument: `php -r '<code>' <argument>`,
prints a leading newline instead of a trailing one

Thanks to Jörg for pointing out my bugs - and for the `\t`.

# PHP, 169 bytes

with the new restriction: (tab character forbidden)

```
foreach(['User:  ','Group: ','Others:']as$i=>$u){echo"
$u";for($n=[5,33,34,66,35,67,131,531][$argv[1][$i]];$n;$n>>=3)echo' ',['and',Read,Write,Execute,only,None][$n&7];}

```

This is 1 byte shorter than with `str_pad`, because of the additional blank it would require.

**breakdown**

```
foreach([User,Group,Others]as$i=>$u)
{
    echo"\n$u:\t";                      // print newline, who, blanks
    for($n=[5,33,34,66,35,67,131,531]   // octal values for words indexes
        [$argv[1][$i]]                  // (last word=highest digit)
        ;$n;$n>>=3)                     // while value has bits left
        echo['and',Execute,Write,Read,only,None][$n&7]," "; // print that word
}

```

To create the array for `$n`, use this:

```
$b=[[5],[1,4],[2,4],[2,0,1],[3,4],[3,0,1],[3,0,2],[3,2,0,1]];
foreach($b as$i=>$a){for($v=$j=0;$a;$j+=3)$v+=array_shift($a)<<$j;echo"$v,";}

```

# Answer
> 2 votes
# Haskell, 186 Bytes

```
s=zip(words"7654 6 7632 753 7531 0 421")(words"Read and Write and Execute None only")
m c=mapM_(\(x,y)->putStrLn(x++unwords[b|(a,b)<-s,elem y a]))$zip["User:   ","Group:  ","Others: "]c

```

Example:

```
Prelude> :r
[1 of 1] Compiling Main             ( decCh.hs, interpreted )
Ok, modules loaded: Main.
*Main> m "654"
User:   Read and Write
Group:  Read and Execute
Others: Read only

```

Only Prelude used. Am I doing this right?

Ungolfed:

```
s = zip (words "7654 6 7632 753 7531 0 421")
        (words "Read and Write and Execute None only")

ps y = unwords [b|(a,b)<-s,elem y a] -- build permissions string
pp (x,y) = putStrLn $ x ++ ps y -- print user + permission

m c =   let up = zip ["User:   ","Group:  ","Others: "] c -- pair user and permission
        in mapM_ pp up --print each

```

# Answer
> 2 votes
# Python 2, ~~190~~ 185 bytes

```
def f(i):
 r,w,a,x,o,g="Read ","Write ","and ","Execute ","only",["User:  ","Group: ","Others:"];p=["None",x+o,w+o,w+a+x,r+o,r+a+x,r+a+w,r+w+a+x]
 for z in 0,1,2:print g[z],p[int(i[z])]

```

Leaves a trailing space if Execute or Write are at the end of the line but I didn't see that this wasn't allowed.

**EDIT** Saved 5 bytes by changing range(3) to 0,1,2 and checking byte count on my Linux laptop instead of my Windows one (\n = \r\n or the other way round. I can never remember which).

# Answer
> 2 votes
# Python 2, ~~240~~ ~~239~~ ~~238~~ ~~237~~ 228 bytes

I thought I’d finally give this cold golf thing a go. ~~Hopefully trailing whitespace is allowed.~~ (fixed, and in the process saved a byte)

```
i=0
def a(b):
 for d in 4,2,1:
    if b&d:yield('Execute','Write','Read')[d/2]
for k in raw_input():
 b,q=list(a(int(k))),' and';e=len(b)
 if e:b[~e/2]+=(' only',q,q)[e-1]
 print'UGOsrteohrue:pr :s  :'[i::3],' '.join(b)or None;i+=1

```

# Answer
> 2 votes
# bash - ~~221~~ 213 bytes

`GNU bash, version 4.3.46`

```
l=("User:   " "Group:  " "Others: ")
o=\ only;a=" and ";x=Execute;w=Write;r=Read
b=(None "$x$o" "$w$o" "$w$a$x" "$r$o" "$r$a$x" "$r$a$w" "$r $w$a$x")
for c in `echo $1|grep -o .`;{ echo "${l[$((z++))]}${b[$c]}";}

```

Unclear if this can be condensed any further, at least not without fundamentally changing the approach here (splitting up input and using it as an index to the array `${b}` that holds the corresponding strings).

# Answer
> 1 votes
# Javascript, 213 209 208 188 186 bytes

```
function(d){a=" and ";r="Read";w="Write";e="Execute";v=";";o=" only";c=["None",e+o,w+o,w+a+e,r+o,r+a+e,r+a+w,r+" "+w+a+e];return"User: "+c[d[0]]+"\nGroup: "+c[d[1]]+"\nOthers: "+c[d[2]]}

```

Saved 20 bytes thanks to Dada!

# Answer
> 1 votes
# Groovy, ~~217~~ ~~207~~ 205 bytes

```
def c(m){def i=0,e='Execute',w='Write',r='Read',o=' only',a=' and ';m.each{println(['User:   ','Group:  ','Others: '][i++]+['None',"$e$o","$w$o","$w$a$e","$r$o","$r$a$e","$r$a$w","$r $w$a$e"][it as int])}}

```

ungolfed:

```
def c(m) {
  def i=0,e='Execute',w='Write',r='Read',o=' only',a=' and ';
  m.each{
    println(['User:   ','Group:  ','Others: '][i++]+['None',"$e$o","$w$o","$w$a$e","$r$o","$r$a$e","$r$a$w","$r $w$a$e"][it as int])
  }
}

```

# Answer
> 1 votes
# Java 7, ~~300~~ 284 bytes

```
String c(String s){char[]a=s.toCharArray();return"User:   "+f(a[0])+"Group:  "+f(a[1])+"Others: "+f(a[2]);}String f(int i){return new String[]{"None","Execute only","Write only","Write and Execute","Read only","Read and Execute","Read and Write","Read Write and Execute"}[i%48]+"\n";}

```

Direct approach for now. Will try to come up with a more generic approach to reuse the words.

**Ungolfed & test cases:**

Try it here.

```
class M{
  static String c(String s){
    char[] a = s.toCharArray();
    return "User:   " + f(a[0]) + "Group:  " + f(a[1]) + "Others: " + f(a[2]);
  }

  static String f(int i){
    return new String[]{ "None", "Execute only", "Write only", "Write and Execute", "Read only", "Read and Execute", "Read and Write", "Read Write and Execute" }
      [i % 48] + "\n";
  }

  public static void main(String[] a){
    System.out.println(c("666"));
    System.out.println(c("042"));
    System.out.println(c("644"));
  }
}

```

**Output:**

```
User:   Read and Write
Group:  Read and Write
Others: Read and Write

User:   None
Group:  Read only
Others: Write only

User:   Read and Write
Group:  Read only
Others: Read only

```

# Answer
> 1 votes
# C#, 322 337 348 bytes

That's for sure not the shortest version, but I tried solving this problem using bitwise operators since the `chmod` values are actually bit flags. Also C# is probably not the best golfing language :D

```
string P(string s){Func<int,string>X=p=>{var a=new List<string>();if((p&4)>0)a.Add("Read");if((p&2)>0)a.Add("Write");if((p&1)>0)a.Add("Execute");return a.Count>1?string.Join(" ",a.Take(a.Count-1))+" and "+a.Last():a.Count>0?a.First()+" only":"none";};return string.Join("\n",(new[]{"User:   ","Group:  ","Others: "}).Select((c,i)=>c+X(s[i]-'0')));}

```

ungolfed: (with comments)

```
string P(string s)
{
    // Function that determines the permissions represented by a single digit (e.g. 4 => "Read only")
    Func<int, string> X = p =>
    {
        var a = new List<string>();         // temporary storage for set permissions
        if ((p & 4) > 0) a.Add("Read");     // Read bit set
        if ((p & 2) > 0) a.Add("Write");    // Write bit set
        if ((p & 1) > 0) a.Add("Execute");  // Execute bit set

        // actually just Output formatting ... Takes a lot of bytes *grr*
        return a.Count > 1
            ? string.Join(" ", a.Take(a.Count - 1)) + " and " + a.Last()
            : a.Count > 0
                ? a.First() + " only"
                : "none";
    };

    // Actual result:
    return string.Join("\n", (new[] { "User:   ", "Group:  ", "Others: " })
        .Select((c, i) => c + X(s[i] - '0'))); // Map "User, .." to its permissions by using above function
}

```

This is my first time code golfing, so please tell me, if I did anyting wrong :)

# EDIT 1:

Saved some bytes by replacing `s[i]-'0'` by `s[i]&7` (at the very end) and saving list count into variable:

```
string P(string s){Func<int,string>X=p=>{var a=new List<string>();if((p&4)>0)a.Add("Read");if((p&2)>0)a.Add("Write");if((p&1)>0)a.Add("Execute");var c=a.Count;return c>1?string.Join(" ",a.Take(c-1))+" and "+a.Last():c>0?a[0]+" only":"none";};return string.Join("\n",(new[]{"User:   ","Group:  ","Others: "}).Select((c,i)=>c+X(s[i]&7)));}

```

# EDIT 2:

Changed to lambda expression:

```
s=>{Func<int,string>X=p=>{var a=new List<string>();if((p&4)>0)a.Add("Read");if((p&2)>0)a.Add("Write");if((p&1)>0)a.Add("Execute");var c=a.Count;return c>1?string.Join(" ",a.Take(c-1))+" and "+a.Last():c>0?a[0]+" only":"none";};return string.Join("\n",(new[]{"User:   ","Group:  ","Others: "}).Select((c,i)=>c+X(s[i]&7)));}

```

# Answer
> 1 votes
# Mathematica, 211 bytes

```
{r,w,e,o,a}={"Read ","Write ","Execute ","only ","and "};""<>Transpose@{{"User:   ","Group:  ","Others: "},"None"[{e,o},{w,o},{w,a,e},{r,o},{r,a,e},{r,a,w},{r,w,a,e}][[#]]&/@IntegerDigits[#,10,3],"\n"&~Array~3}&

```

A straightforward implementation (probably easily beatable): doesn't compute anything, just hard-codes each possible output. Input is an integer; outputs each line with a trailing space, and a trailing newline overall.

`IntegerDigits[#,10,3]` gives the three digits of the input (even if there are leading zeros). Each digit indicates an argument of the "function"

```
"None"[{e,o},{w,o},{w,a,e},{r,o},{r,a,e},{r,a,w},{r,w,a,e}]

```

with 0 indicating the function name itself. `""<>` concatenates all the strings in a list (of lists). `"\n"&~Array~3` produces the three newlines.

# Answer
> 1 votes
# C# ~~307~~ ~~241~~ 210 bytes

`string X(string s){var z="User: ,Group: ,Others:,5,34,14,123,04,023,021,0123,Read,Write,and,Execute,only,None".Split(',');return string.Join("\n",s.Zip(z,(a,b)=>b+z[a-45].Aggregate("",(x,y)=>x+" "+z[y-37])));}`

Formatted

```
string X(string s)
{
    var z = "User:  ,Group: ,Others:,5,34,14,123,04,023,021,0123,Read,Write,and,Execute,only,None".Split(',');
    return string.Join("\n", s.Zip(z, (a, b) => b + z[a - 45].Aggregate("", (x, y) => x + " " + z[y - 37])));
}

```

# Answer
> 1 votes
# Java 7, 278

Golfed:

```
String f(String i){String o="";for(int n=0;n<i.length();)o+=(n<1?"User:   ":n<2?"Group:  ":"Others: ")+new String[]{"None","Execute only","Write only","Write and Execute","Read only","Read and Execute","Read and Write","Read Write and Execute"}[i.charAt(n++)-48]+"\n";return o;}

```

Ungolfed:

```
  String f(String i) {
    String o = "";
    for (int n = 0; n < i.length();)
      o += (n < 1 ? "User:   " : n < 2 ? "Group:  " : "Others: ")
        + new String[] { "None", "Execute only", "Write only", "Write and Execute", "Read only", "Read and Execute",
            "Read and Write", "Read Write and Execute" }[i.charAt(n++) - 48]
        + "\n";
    return o;
  }

```

Output:

```
User:   Read and Write
Group:  Read and Write
Others: Read and Write

User:   None
Group:  Read only
Others: Write only

User:   Read and Write
Group:  Read only
Others: Read only

```

# Answer
> 1 votes
# Python 3.5, 3.6 - 235 232 228 216 bytes

(should work on all Python 3.x)

So the input is on STDIN here (saves an import ☺).

```
a=input()
r=range
for i in r(3):
 p=int(a[i]);x=[["Read","Write","Execute"][j]for j in r(3)if 4>>j&p]
 if x[1:]:x[-1:-1]="and",
 if len(x)==1:x+="only",
 print(["User:  ","Group: ","Others:"][i]," ".join(x)or"None")

```

Making use of tuples, omitting spaces where possible and operator precedence where you would normally put parentheses to make your intentions clear.

Sample usage:

```
$ echo -n '666' | python3 golf2.py
User:   Read and Write
Group:  Read and Write
Others: Read and Write
$ echo -n '644' | python3 golf2.py
User:   Read and Write
Group:  Read only
Others: Read only
$ echo '042' | python3 golf2.py
User:   None
Group:  Read only
Others: Write only
$ echo '123' | python3 golf2.py
User:   Execute only
Group:  Write only
Others: Write and Execute
$ echo -n '777' | python3 golf2.py
User:   Read Write and Execute
Group:  Read Write and Execute
Others: Read Write and Execute

```

Un-golfed:

```
input_perms = list(map(int, input()))

entities = ["User", "Group", "Others"]
perm_names = ["Read", "Write", "Execute"]

for i in range(3):
    bits = input_perms[i]
    perms = [
        perm_names[j]
        for j in range(3)
        if (1 << (2-j)) & bits
    ]

    if len(perms) > 1:
        perms.insert(-1, "and")
    if len(perms) == 1:
        perms.append("only")

    print("{:7} {}".format(
        entities[i]+":",
        " ".join(perms) or "None"
    ))

```

# Answer
> 1 votes
## Batch, 280 bytes

```
@echo off
set/pc=
call:l "User:   " %c:~0,1%
call:l "Group:  " %c:~1,1%
call:l "Others: " %c:~2,1%
exit/b
:l
for %%s in (None.0 Execute.1 Write.2 "Write and Execute.3" Read.4 "Read and Execute.5" "Read and Write.6" "Read Write and Execute.7") do if %%~xs==.%2 echo %~1%%~ns

```

Hardcoding the strings was 47 bytes shorter than trying to piece them together. Would have been 267 bytes if tabs were legal.

# Answer
> 1 votes
# Visual Basic, 606 Bytes

```
imports System.Collections
module h
sub main()
Dim i As String=console.readline()
Dim s=new Stack(new String(){"Others: ","Group:  ","User:   "})
for each j as Char in i
dim t=new Stack()
if((asc(j) MOD 2)=1)then t.push("Execute")
if(asc(j)=50 or asc(j)=51 or asc(j)=54 or asc(j)=55)then t.push("Write")
if(asc(J)>51)then t.push("Read")
if t.count=3 then
w(s.pop+t.pop+" "+t.pop+" and "+t.pop)
else
if t.count=2 then
w(s.pop+t.pop+" and "+t.pop)
else
if t.count=0 then
w(s.pop+"None")
else
w(s.pop+t.pop+" only")
end if
end if
end if
next
end sub
sub w(s As String)
console.writeline(s)
end sub
end module

```

# Answer
> 1 votes
# Crystal, 200 194 Bytes

```
def m(y)y=y.chars.map &.to_i
a=" and "
o=" only"
r="Read"
w="Write"
x="Execute"
c=["None",x+o,w+o,w+a+x,r+o,r+a+x,r+a+w,r+" "+w+a+x]
"User:   "+c[y[0]]+"
Group:  "+c[y[1]]+"
Others: "+c[y[2]]end

```

returns the resulting string for a given octal-sequence as a string. e.g.: `m("670")` results to: `User: Read and Write\nGroup: Read Write and Execute\nOthers: None`.

Try it online.

# Answer
> 0 votes
# C#, 371 bytes

```
public String[] a = {"none","Execute only","Write only","Write and Execute","Read only","Read and Execute","Read and Write","Read Write and Execute"};
public String pA(int i){return a[i];}
public int d(int n,int i){
  n=n/Math.pow(10,i);
  return n%=10;
}
public void main(int i){
  Console.Write("User:\t{0}\nGroup:\t{1},Others:\t{2}",pA(d(i,0)),pA(d(i,1)),pA(d(i,2));
}

```

# Answer
> 0 votes
# PHP ,199 Bytes

```
foreach([User,Group,Others]as$i=>$u){$a=[];foreach([Read,Write,Execute]as$k=>$s)if($argv[1][$i]&4>>$k)$a[]=$s;$a[]=($x=array_pop($a))?$a?"and $x":"$x only":None;echo str_pad("\n$u:",9).join(" ",$a);}

```

PHP ,189 Bytes with \t

```
foreach([User,Group,Others]as$i=>$u){$a=[];foreach([Read,Write,Execute]as$k=>$s)if($argv[1][$i]&4>>$k)$a[]=$s;$a[]=($x=array_pop($a))?$a?"and $x":"$x only":None;echo"\n$u:\t".join(" ",$a);}

```

# Answer
> 0 votes
## Python 3.5 - ~~370~~ ~~294~~ 243 bytes

Golfed:

```
import sys
a=lambda o: [print(('User:  ','Group: ','Others:')[n],('None','Execute only','Write only','Write and Execute','Read only','Read and Execute','Read and Write','Read Write and Execute')[int(o[n])]) for n in range(0,3)]
a(sys.argv[1])

```

Size check:

```
$ du -b OctalToHuman.py
243     OctalToHuman.py

```

Un-golfed:

```
#!/usr/bin/env python3
from sys import argv as ARGS

types = ('User:  ', 'Group: ', 'Others:')
perms = ('None','Execute only','Write only','Write and Execute','Read only','Read and Execute','Read and Write','Read Write and Execute')

def convert(octal_string):
    for n in range(0,3):
        print(types[n], perms[int(octal_string[n])])

if __name__ == '__main__':
    convert(ARGS[1])

```

Sample output:

```
$ python ./OctalToHuman.py 666
User:   Read and Write
Group:  Read and Write
Others: Read and Write

```

```
$ python ./OctalToHuman.py 042
User:   None
Group:  Read only
Others: Write only

```

```
$ python ./OctalToHuman.py 644
User:   Read and Write
Group:  Read only
Others: Read only

```

# Answer
> 0 votes
# Sinclair BASIC - ~~263~~ 257 bytes

I did one version using the same approach as everyone else (load of string variables put into array) in 227 bytes, so going to post this one as a different way of doing it.

EDIT - As pointed out, there were some extraneous "and" appearing, this is now resolved

```
1 p=0,z$="and ": INPUT c$
2 FOR EACH a$ IN ["User:   ","Group:  ","Others: "]
3 p+=1,n=VAL c$(p),r=(n & 4)>0,w=(n & 2)>0,x=(n & 1)>0,t=r+w+x
4  ?a$;("Read "*r)+(z$*(r AND (t=2)))+("Write "*w)+(z$*(w AND x))+("Execute "*x)+("only"*(t=1))+("None"*(t=0))
5 NEXT a$

```

Uses bitwise-AND `&` operation to see if the number has 4,2 or 1 bits set and then prints the different permissions. Adding "and" in between multiple values took up most of the space.

Screenshot shows example for 670 as input

# Answer
> 0 votes
# F#, ~~204~~ 203 Bytes

*my first golf, so do please forgive any mistakes ;)*
The golfed version (based 1:1 on pinkfloydx33's answer):

```
fun(y:string)->let e,r,w,o,a="Execute ","Read ","Write ","only","and ";let z=["None";e+o;w+o;w+a+e;r+o;r+a+e;r+a+w;r+w+a+e;];let(!-)a=z.[int y.[a]-48];sprintf"User:   %s\nGroup:  %s\nOthers: %s"!-0!-1!-2

```

The ungolfed version:

```
fun (y : string) ->
    let e, r, w, o, a = "Execute ", "Read ", "Write ", "only", "and "
    let z = [
                "None";
                e + o;
                w + o;
                w + a + e;
                r + o;
                r + a + e;
                r + a + w;
                r + w + a + e;
            ]
    let (!-) a = z.[int(y.[a]) - 48]
    sprintf "User:   %s\nGroup:  %s\nOthers: %s" !-0 !-1 !-2

```

Example usage:

```
let k =  ...... // function definition goes here

printf"%s"<|k"755"
printf"%s"<|k"042"
// etc ...

```

---

**This is solely to check, whether I could 'improve' pinkfloydx33's answer \- I do not take any credit for the algorithm**

# Answer
> 0 votes
# Python 3, 191 bytes

```
def d(n):a,b,c,d,e=' and ',' only',"Execute","Write","Read";l=["None",c+b,d+b,d+a+c,e+b,e+a+c,e+a+d,e+" "+d+a+c];y,u,i=map(int,n);return"User:   %s\nGroup:  %s\nOthers: %s\n"%(l[y],l[u],l[i])

```

ungolfed

```
def d(n):
    a,b,c,d,e=' and ',' only',"Execute","Write","Read"
    l=["None",c+b,d+b,d+a+c,e+b,e+a+c,e+a+d,e+" "+d+a+c]
    y,u,i=map(int,n)
    return"User:   %s\nGroup:  %s\nOthers: %s\n"%(l[y],l[u],l[i])

```

# Answer
> 0 votes
## Javascript (ES6), 159 bytes

```
a=>`User:  ${(b=[' None',(c=' Execute')+(d=' only'),(e=' Write')+d,f=e+(g=' and')+c,(h=' Read')+d,h+g+c,h+g+e,h+f])[a[0]]}\nGroup: ${b[a[1]]}\nOthers:`+b[a[2]]

```

---

Example:

```
(a=>`User:  ${(b=[' None',(c=' Execute')+(d=' only'),(e=' Write')+d,f=e+(g=' and')+c,(h=' Read')+d,h+g+c,h+g+e,h+f])[a[0]]}\nGroup: ${b[a[1]]}\nOthers:`+b[a[2]])("042")

```

# Answer
> 0 votes
## Perl -p, 149 (148+1) bytes

This is a port to Perl of Firefly's sed answer.

```
s/(.)(.)/User:   \1
Group:  \2
Others: /;s/[4-7]/Read $&/g;s/[2367]/Write $&/g;s/[1357]/Execute $&/g;s/0/None/g;s/\w \K(\w+) \d/and $1/g;s/\d/only/g

```

Compared to *sed*:

* Perl uses `$&` instead of `&` *(+ 3 bytes)*.
* Perl has `\d`, which we use instead of `[1-7]` *(-6 bytes)*.
* Perl has `\K` *(-3 bytes)*.
* Perl allows literal newlines in the replacement part of `s///` *(-2 bytes)*.

---
Tags: code-golf, parsing
---


title: Tips for golfing in S.I.L.O.S

text:
# Question
Title: Tips for golfing in S.I.L.O.S
What general tips do you have for golfing in S.I.L.O.S? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to S.I.L.O.S (e.g. "remove comments" is not an answer).

Please post one tip per answer.

S.I.L.O.S can be run here.

# Answer
> 2 votes
# Abuse the preprocessor

All SILOS programs can optionally have a macro statement on the **second line**

Consider the following program... One of my favorite SILOS submissions by betseg.

```
a=97
def q print z bottle v beer L Line g wall x IntNoLine h the c around
qL 99 zs of v on h g, 99 zs of v.
lbls
q Take one down and pass it c,
a+1
qx a
qL  zs of v on h g.
qx a
q  zs of v on h g,
qx a
qL  zs of v.
a-2
if a s
qL Take one down and pass it c, 1 z of v on h g.
qL 1 z of v on h g, 1 z of v.
q Go to h store and buy some more, 99 zs of v on h g.

```

Look at that savings Try it out!

# Answer
> 1 votes
# ~~Never~~ sometimes divide by 0.

Consider a challege where we should output the input if it is not 0 and output -1 otherwise. We could do the following.

# S.I.L.O.S, 50 bytes

```
readIO
if i b
print -1
GOTO c
lblb
printInt i
lblc

```

Try it online!

However, that is far from optimal. The "superior" solution would be this.

# S.I.L.O.S, 33 bytes

```
readIO
j=i
i/i
j=j+i-1
printInt j

```

Try it online!

SILOS will quietly ignore the division by 0, which results in a no-op.

# Answer
> 0 votes
# Never declare variables

There is no need to declare a variable. All variables are automa~~t~~gically initialized to 0.
Hence, this-

```
a=0
a=97
printInt a

```

Is the same as this

```
a=97
printInt a

```

---
Tags: code-golf, tips
---


title: Fastest Approximate Common Divisor

text:
# Question
Title: Fastest Approximate Common Divisor
**Overview**

In this challenge, you will be given two numbers which are both a small offset larger than a multiple of a medium-size number. You must output a medium-sized number that is almost a divisor of both of the numbers, except for a small offset.

The size of the numbers involved will be parameterized by a difficulty parameter, `l`. Your objective is to solve the problem for the largest possible `l` in under 1 minute.

---

**Setup**

In a given problem, there will be a secret number, `p`, which will be a random `l^2` (`l*l`) bit number. There will be two multipliers, `q1, q2`, which will be random `l^3` bit numbers, and there will be two offsets, `r1, r2`, which will be random `l` bit numbers.

The input to your program will be `x1, x2`, defined as:

```
x1 = p * q1 + r1
x2 = p * q2 + r2

```

Here's a program to generate test cases, in Python:

```
from random import randrange
from sys import argv

l = int(argv[1])

def randbits(bits):
    return randrange(2 ** (bits - 1), 2 ** bits)

p = randbits(l ** 2)
print(p)
for i in range(2):
    q_i = randbits(l ** 3)
    r_i = randbits(l)
    print(q_i * p + r_i)

```

The first line of output is a possible solution, while the second and third lines are the input that your program will be given.

---

**Your Program**

Given `x1`, `x2` and `l`, you must find a `l^2` bit number `p'` such that `x1 % p'` and `x2 % p'` are both `l` bit numbers. `p` will always work, though there may be other possibilities. Here's a function to verify a solution:

```
def is_correct(x1, x2, l, p_prime):
    p_prime_is_good = p_prime >> (l**2 - 1) and not p_prime >> l ** 2
    x1_is_good = (x1 % p_prime) >> (l-1) and not (x1 % p_prime) >> l
    x2_is_good = (x2 % p_prime) >> (l-1) and not (x2 % p_prime) >> l
    return bool(p_prime_is_good and x1_is_good and x2_is_good)

```

---

**Example**

Suppose `l` is 3. The generator program picks a 9-bit number for `p`, which in this case is `442`. The generator picks two `3` bit numbers for `r1, r2`, which are `4, 7`. The generator picks two `27` bit numbers for `q1, q2`, which are `117964803, 101808039`. Because of these choices, `x1, x2` are `52140442930, 44999153245`.

Your program would be given `52140442930, 44999153245` as input, and must output a 9-bit number (in the range `[256, 511]`) such that `52140442930` and `44999153245` modulo that number give 3 bit numbers (in the range `[4, 7]`). `442` is the only such value in this case, so your program would have to output `442`.

---

**More examples**

```
l = 2
x1 = 1894
x2 = 2060
p = 11
No other p'.

l = 3
x1 = 56007668599
x2 = 30611458895
p = 424
No other p'.

l = 6
x1 = 4365435975875889219149338064474396898067189178953471159903352227492495111071
x2 = 6466809655659049447127736275529851894657569985804963410176865782113074947167
p = 68101195620
I don't know whether there are other p'.

l = 12
x1 = 132503538560485423319724633262218262792296147003813662398252348727558616998821387759658729802732555377599590456096450977511271450086857949046098328487779612488702544062780731169071526325427862701033062986918854245283037892816922645703778218888876645148150396130125974518827547039720412359298502758101864465267219269598121846675000819173555118275197412936184329860639224312426860362491131729109976241526141192634523046343361089218776687819810873911761177080056675776644326080790638190845283447304699879671516831798277084926941086929776037986892223389603958335825223
x2 = 131643270083452525545713630444392174853686642378302602432151533578354175874660202842105881983788182087244225335788180044756143002547651778418104898394856368040582966040636443591550863800820890232349510212502022967044635049530630094703200089437589000344385691841539471759564428710508659169951391360884974854486267690231936418935298696990496810984630182864946252125857984234200409883080311780173125332191068011865349489020080749633049912518609380810021976861585063983190710264511339441915235691015858985314705640801109163008926275586193293353829677264797719957439635
p = 12920503469397123671484716106535636962543473
I don't know whether there are other p'.

l = 12
x1 = 202682323504122627687421150801262260096036559509855209647629958481910539332845439801686105377638207777951377858833355315514789392768449139095245989465034831121409966815913228535487871119596033570221780568122582453813989896850354963963579404589216380209702064994881800638095974725735826187029705991851861437712496046570494304535548139347915753682466465910703584162857986211423274841044480134909827293577782500978784365107166584993093904666548341384683749686200216537120741867400554787359905811760833689989323176213658734291045194879271258061845641982134589988950037
x2 = 181061672413088057213056735163589264228345385049856782741314216892873615377401934633944987733964053303318802550909800629914413353049208324641813340834741135897326747139541660984388998099026320957569795775586586220775707569049815466134899066365036389427046307790466751981020951925232623622327618223732816807936229082125018442471614910956092251885124883253591153056364654734271407552319665257904066307163047533658914884519547950787163679609742158608089946055315496165960274610016198230291033540306847172592039765417365770579502834927831791804602945514484791644440788
p = 21705376375228755718179424140760701489963164

```

---

**Scoring**

As mentioned above, your program's score is the highest `l` that the program completes in under 1 minute. More specifically, your program will be run on 5 random instances with that `l`, and it must output a correct answer on all 5, with an average time under 1 minute. A program's score will be the highest `l` that it succeeds on. Tiebreaker will be average time on that `l`.

To give you an idea of what scores to aim for, I wrote a very simple brute-force solver. It got a score of 5. I wrote a much fancier solver. It got a score of 12 or 13, depending on luck.

---

**Details**

For perfect comparability across answers, I will time submissions on my laptop to give canonical scores. I will also run the same randomly chosen instances on all submissions, to alleviate luck somewhat. My laptop has 4 CPUs, i5-4300U CPU @ 1.9 GHz, 7.5G of RAM.

Feel free to post a provisional score based on your own timing, just make it clear whether it's provisional or canonical.

---

May the fastest program win!

# Answer
# Rust, L=13

### `src/main.rs`

```
extern crate gmp;
extern crate rayon;

use gmp::mpz::Mpz;
use gmp::rand::RandState;
use rayon::prelude::*;
use std::cmp::max;
use std::env;
use std::mem::swap;

// Solver

fn solve(x1: &Mpz, x2: &Mpz, l: usize) -> Option<Mpz> {
    let m = l*l - 1;
    let r = -1i64 << l-2 .. 1 << l-2;
    let (mut x1, mut x2) = (x1 - (3 << l-2), x2 - (3 << l-2));
    let (mut a1, mut a2, mut b1, mut b2) = (Mpz::one(), Mpz::zero(), Mpz::zero(), Mpz::one());
    while !x2.is_zero() &&
        &(max(a1.abs(), b1.abs()) << l-2) < &x1 &&
        &(max(a2.abs(), b2.abs()) << l-2) < &x2
    {
        let q = &x1/&x2;
        swap(&mut x1, &mut x2);
        x2 -= &q*&x1;
        swap(&mut a1, &mut a2);
        a2 -= &q*&a1;
        swap(&mut b1, &mut b2);
        b2 -= &q*&b1;
    }
    r.clone().into_par_iter().map(|u| {
        let (mut y1, mut y2) = (&x1 - &a1*u + (&b1 << l-2), &x2 - &a2*u + (&b2 << l-2));
        for _ in r.clone() {
            let d = Mpz::gcd(&y1, &y2);
            if d.bit_length() >= m {
                let d = d.abs();
                let (mut k, k1) = (&d >> l*l, &d >> l*l-1);
                while k < k1 {
                    k += 1;
                    if (&d%&k).is_zero() {
                        return Some(&d/&k)
                    }
                }
            }
            y1 -= &b1;
            y2 -= &b2;
        }
        None
    }).find_any(|o| o.is_some()).unwrap_or(None)
}

// Test harness

fn randbits(rnd: &mut RandState, bits: usize) -> Mpz {
    rnd.urandom(&(Mpz::one() << bits - 1)) + (Mpz::one() << bits - 1)
}

fn gen(rnd: &mut RandState, l: usize) -> (Mpz, Mpz, Mpz) {
    let p = randbits(rnd, l*l);
    (randbits(rnd, l*l*l)*&p + randbits(rnd, l),
     randbits(rnd, l*l*l)*&p + randbits(rnd, l),
     p)
}

fn is_correct(x1: &Mpz, x2: &Mpz, l: usize, p_prime: &Mpz) -> bool {
    p_prime.bit_length() == l*l &&
        (x1 % p_prime).bit_length() == l &&
        (x2 % p_prime).bit_length() == l
}

fn random_test(l: usize, n: usize) {
    let mut rnd = RandState::new();  // deterministic seed
    for _ in 0..n {
        let (x1, x2, p) = gen(&mut rnd, l);
        println!("x1 = {}", x1);
        println!("x2 = {}", x2);
        println!("l = {}", l);
        println!("p = {}", p);
        println!("x1 % p = {}", &x1 % &p);
        println!("x2 % p = {}", &x2 % &p);
        assert!(is_correct(&x1, &x2, l, &p));
        let p_prime = solve(&x1, &x2, l).expect("no solution found!");
        println!("p' = {}", p_prime);
        assert!(is_correct(&x1, &x2, l, &p_prime));
        println!("correct");
    }
}

// Command line interface

fn main() {
    let args = &env::args().collect::<Vec<_>>();
    if args.len() == 4 && args[1] == "--random" {
        if let (Ok(l), Ok(n)) = (args[2].parse(), args[3].parse()) {
            return random_test(l, n);
        }
    }
    if args.len() == 4 {
        if let (Ok(x1), Ok(x2), Ok(l)) = (args[1].parse(), args[2].parse(), args[3].parse()) {
            match solve(&x1, &x2, l) {
                None => println!("no solution found"),
                Some(p_prime) => println!("{}", p_prime),
            }
            return;
        }
    }
    println!("Usage:");
    println!("    {} --random L N", args[0]);
    println!("    {} X1 X2 L", args[0]);
}

```

### `Cargo.toml`

```
[package]
name = "agcd"
version = "0.1.0"
authors = ["Anders Kaseorg <andersk@mit.edu>"]

[dependencies]
rayon = "0.7.1"
rust-gmp = "0.5.0"

```

### To run

```
cargo build --release
target/release/agcd 56007668599 30611458895 3
target/release/agcd --random 13 5

```
> 3 votes

# Answer
# Mathematica, L=5

here is a quick 5 solution

```
(l = #3;
a = #1 - Range[2^(l - 1), 2^l];
b = #2 - Range[2^(l - 1), 2^l];
Last@Intersection[
Flatten[Table[Select[Divisors@a[[i]], # < 2^l^2 &], {i, Length@a}],
 1],
Flatten[Table[Select[Divisors@b[[i]], # < 2^l^2 &], {i, Length@b}],
 1]]
) &

```

**Input**
\[x1,x2,L\]

in order that anybody can test this, here is the key generator

```
l = 5;
a = RandomInteger[{2^(l^2 - 1), 2^(l^2)}]
b = RandomInteger[{2^(l^3 - 1), 2^(l^3)}];
c = RandomInteger[{2^(l - 1), 2^l - 1}];
f = RandomInteger[{2^(l^3 - 1), 2^(l^3)}];
g = RandomInteger[{2^(l - 1), 2^l - 1}];
x = a*b + c
y = a*f + g

```

choose the L value run, the code and you will get three numbers.
place the last two along with L as input, and you should get the first one
> 2 votes

# Answer
# Python, L=15, average time 39.9s

```
from sys import argv
from random import seed, randrange

from gmpy2 import gcd, mpz
import gmpy2

def mult_buckets(buckets):
    if len(buckets) == 1:
        return buckets[0]
    new_buckets = []
    for i in range(0, len(buckets), 2):
        if i == len(buckets) - 1:
            new_buckets.append(buckets[i])
        else:
            new_buckets.append(buckets[i] * buckets[i+1])
    return mult_buckets(new_buckets)

def get_products(xs, l):
    num_buckets = 1000
    lower_r = 1 << l - 1
    upper_r = 1 << l
    products = []
    bucket_size = (upper_r - lower_r)//num_buckets + 1
    for x in xs:
        buckets = []
        for bucket_num in range(num_buckets):
            product = mpz(1)
            for r in range(lower_r + bucket_num * bucket_size,
                           min(upper_r, lower_r + (bucket_num + 1) * bucket_size)):
                product *= x - mpz(r)
            buckets.append(product)
        products.append(mult_buckets(buckets))
    return products

def solve(xs, l):
    lower_r = 2**(l - 1)
    upper_r = 2**l
    lower_p = 2**(l**2 - 1)
    upper_p = 2**(l**2)

    products = get_products(xs, l)
    overlap = gcd(*products)
    candidate_lists = []
    for x in xs:
        candidates = []
        candidate_lists.append(candidates)
        for r in range(lower_r, upper_r):
            common_divisor = gcd(x-r, overlap)
            if common_divisor >= lower_p:
                candidates.append(common_divisor)
    to_reduce = []
    for l_candidate in candidate_lists[0]:
        for r_candidate in candidate_lists[1]:
            best_divisor = gcd(l_candidate, r_candidate)
            if lower_p <= best_divisor < upper_p:
                return best_divisor
            elif best_divisor > upper_p:
                to_reduce.append(best_divisor)
    for divisor in to_reduce:
        cutoff = divisor // lower_p
        non_divisors = []
        for sub_divisor in range(2, cutoff + 1):
            if any(sub_divisor % non_divisor == 0 for non_divisor in non_divisors):
                continue
            quotient, remainder = gmpy2.c_divmod(divisor, sub_divisor)
            if remainder == 0 and lower_p <= quotient < upper_p:
                return quotient
            if quotient < lower_p:
                break
            if remainder != 0:
                non_divisors.append(sub_divisor)

def is_correct(x1, x2, l, p_prime):
    p_prime_is_good = p_prime >> (l**2 - 1) and not p_prime >> l ** 2
    x1_is_good = (x1 % p_prime) >> (l-1) and not (x1 % p_prime) >> l
    x2_is_good = (x2 % p_prime) >> (l-1) and not (x2 % p_prime) >> l
    return bool(p_prime_is_good and x1_is_good and x2_is_good)

if __name__ == '__main__':
    seed(0)

    l = int(argv[1])
    reps = int(argv[2])

    def randbits(bits):
        return randrange(2 ** (bits - 1), 2 ** bits)

    for _ in range(reps):
        p = randbits(l ** 2)
        print("p = ", p)
        xs = []
        for i in range(2):
            q_i = randbits(l ** 3)
            print("q", i, "=", q_i)
            r_i = randbits(l)
            print("r", i, "=", r_i)
            x_i = q_i * p + r_i
            print("x", i, "=", x_i)
            xs.append(x_i)

        res = solve(xs, l)
        print("answer = ", res)
        print("Correct?", is_correct(xs[0], xs[1], l, res))

```

This code is based on the fact that the product of x1 - r for all possible values of r must be a multiple of p, and the product of x2 - r must be as well. Most of the time is spent taking the gcd of the two products, each of which has about 60,000,000 bits. The gcd, which only has about 250,000 bits, is then compared to each of the x-r values once again, to extract p' candidates. If they're a bit too large, trial division is used to reduce them to the appropriate range.

This is based on the gmpy2 library for Python, which is a thin wrapper for the GNU MP library, which in particular has a really good gcd routine.

This code is single-threaded.
> 2 votes

# Answer
# Mathematica, L=12

```
ClearAll[l, a, b, k, m];
(l = #3;
a = #1 - Range[2^(l - 1), 2^l];
b = #2 - Range[2^(l - 1), 2^l];
k = Length@a;
m = Length@b;
For[i = 1, i <= k, i++,
For[j = 1, j <= m, j++, If[2^(l^2 - 1) < GCD[a[[i]], b[[j]]],
 If[GCD[a[[i]], b[[j]]] > 2^l^2,
  Print@Max@
    Select[Divisors[GCD[a[[i]], b[[j]]]],
     2^(l^2 - 1) < # < 2^l^2 &]; Abort[],
  Print[GCD[a[[i]], b[[j]]]];
  Abort[]]]]]) &

```

**input** \[x1,x2,L\]

in order that anybody can test this, here is the key generator

```
l = 12;
a = RandomInteger[{2^(l^2 - 1), 2^(l^2)}]
b = RandomInteger[{2^(l^3 - 1), 2^(l^3)}];
c = RandomInteger[{2^(l - 1), 2^l - 1}];
f = RandomInteger[{2^(l^3 - 1), 2^(l^3)}];
g = RandomInteger[{2^(l - 1), 2^l - 1}];
x = a*b + c
y = a*f + g

```

choose the L value, run the code and you will get three numbers.
place the last two along with L as input, and you should get the first one
> 1 votes

---
Tags: number-theory, fastest-code
---


title: Reflective binary ordering

text:
# Question
Title: Reflective binary ordering
The reverse of an *n*-bit number is just its *n* binary digits in reverse order:

> 001010010 → 010010100

Given a number *n*, generate all *n*-bit integers (\[*0, 2n-1*\]) in an arbitrary order, with only one restriction: there must be a splitting point such that the reverse of an integer is on the opposite side of the splitting point. Integers which are their own reverse must come before the splitting point.

Other than this single splitting point there are no restrictions, all the integers before or after it may come in whatever order you desire.

Example for 4 bits (you don't have to generate this order):

```
0000, 0001, 0010, 0011, 0101, 0110, 0111, 1001, 1011, 1111,
0100, 1000, 1010, 1100, 1101, 1110

```

You may output the integers as their binary digits or just as integers. You don't have to explicitly output the splitting point.

# Answer
> 3 votes
## JavaScript (ES6), ~~129~~ 114 bytes

```
f=n=>[...Array(p=1<<n)].map((_,i)=>(p+i).toString(2).slice(1)).sort((a,b)=>g(a)-g(b),g=a=>[...a].reverse().join``<a)

```

I appear to have stumbled on the code that happens to generate the given example for 4 bits. Edit: Saved 15 bytes thanks to @ConorO'Brien.

# Answer
> 2 votes
# Jelly, 13 bytes

```
2ṗ’µżUṢ€QZ;/Q

```

Try it online!

Group with their reflections, uniquify and sort, then zip.

# Answer
> 2 votes
## PHP, 80 Bytes

Make 2 Groups in a 2D Array

After the first Group is the splitting point

In the first group are the integers with their own reverse and the integers that are lower than their reverse

```
for(;$i<1<<$argn;)$r[strrev($b=sprintf("%0{$argn}b",$i++))<$b][]=$b;print_r($r);

```

Try it online!

## PHP\>=7.0, 82 Bytes

Make 3 Groups in a 2D Array

After the second Group is the splitting point

In the first group are the integers with their own reverse

In the second group are the integers that are lower than their reverse

Use the Spaceship Operator

```
for(;$i<2**$argn;)$r[strrev($b=sprintf("%0{$argn}b",$i++))<=>$b][]=$b;print_r($r);

```

Try it online!

# Answer
> 1 votes
# Mathematica, 51 bytes (Windows ANSI encoding)

```
±n_:=SortBy[{0,1}~Tuples~n,(#-Reverse@#).Range@n!&]

```

Defines a unary function `±` taking a positive integer argument and returning a list of lists of 0s and 1s. For example, `±4` returns

```
{{1, 1, 0, 0}, {1, 0, 0, 0}, {1, 1, 1, 0}, {1, 0, 1, 0}, {0, 1, 0, 0},
 {1, 1, 0, 1}, {0, 0, 0, 0}, {0, 1, 1, 0}, {1, 0, 0, 1}, {1, 1, 1, 1},
 {0, 0, 1, 0}, {1, 0, 1, 1}, {0, 1, 0, 1}, {0, 0, 0, 1}, {0, 1, 1, 1},
 {0, 0, 1, 1}}

```

`SortBy[{0,1}~Tuples~n,...]` takes the set of all length-n lists of 0s and 1s and sorts them according to the values that the function `...` takes on each such list. It suffices to find a function whose values on a list and its reverse are negatives of each other and whose value is 0 *only* if the list is its own reverse. Taking the dot product of (the list minus its reverse) and (a sufficiently unbalanced vector, such as `Range@n!` which is `{1!, 2!, ..., n!}`) does the trick.

# Answer
> 1 votes
# Pyth, 14 bytes

```
o&NcNijN2 .5^2

```

Try it online

### How it works

Sort by *x* / *f*(*x*), where *f*(x0⋅20 \+ x1⋅21 \+ x2⋅22 \+ …) = x0⋅0.50 \+ x1⋅0.51 \+ x2⋅0.52 \+ … (for binary digits xi ∈ {0, 1}). Interestingly, this same ordering works for all *n*, but with different splitting points. If *x* is less than or equal to its *n* bit reversal, then *x* / *f*(*x*) ≤ 2*n* − 1, otherwise *x* / *f*(*x*) \> 2*n* − 1.

```
o           ^2Q   sort values [0, …, 2**n-1] by this key:
 &N                 if value is 0, key is 0
   cN               else, key is value divided by
     i    .5          the base 0.5 number whose digits are
      j 2             the base 2 digits of
       N              value

```

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


title: Evaluate modular power towers

text:
# Question
Title: Evaluate modular power towers
Given two numbers n and m, evaluate the infinite power tower:

> n^(n+1)^(n+2)^(n+3)^(n+4)^... mod m

Keep in mind that ^ is right-associative. So 2^3^4 = 2^(3^4). Now how can you possibly assign a value to an infinite sequence of right-associative operators?

Define f(n,m,i) as the power tower containing the first i terms of the infinite power tower. Then there is some constant C such that for every i \> C, f(n,m,i) = f(n,m,C). So you could say the infinite power tower converges on a certain value. We're interested in that value.

---

Your program must be able to compute n = 2017, m = 10^10 in under 10 seconds on a reasonable modern PC. That is, you should implement an actual algorithm, no bruteforcing.

You may assume that *n \< 230* and *m* \< 250 for the numerical limits in your programming language, but your algorithm must theoretically work for any size *n*, *m*. However your program **must** be correct for inputs within these size limits, intermediate value overflows are **not** excused if the inputs are within these limits.

Examples:

```
2, 10^15
566088170340352

4, 3^20
4

32, 524287
16

```

# Answer
# Pyth, 23 bytes

```
M&tG.^HsgBu-G/GH{PGGhHG

```

Defines a function `g`, taking *m* and *n* in that order.

Try it online

### How it works

```
M&tG.^HsgBu-G/GH{PGGhHG
M                         def g(G, H):
 &tG                        0 if G == 1, else …
                 PG         prime factors of G
                {           deduplicate that
          u-G/GH   G        reduce that on lambda G,H:G-G/H, starting at G
                              (this gives the Euler totient φ(G))
        gB          hH      bifurcate: two-element list [that, g(that, H + 1)]
       s                    sum
    .^H               G     H^that mod G

```

# Python 2, ~~109~~ 76 bytes

```
import sympy
def g(n,m):j=sympy.totient(m);return m-1and pow(n,j+g(n+1,j),m)

```

Try it online!

# Why it works

We use the following generalization of Euler’s theorem.

**Lemma.** *n*2φ(*m*)*n*φ(*m*) (mod *m*) for all *n* (whether or not *n* is coprime to *m*).

*Proof:* For all prime powers *p**k* dividing *m*,

* If *p* divides *n*, then because *φ*(*m*) ≥ *φ*(*p**k*) = *p**k* − 1(*p* − 1) ≥ 2*k* − 1*k*, we have *n*2φ(*m*) ≡ 0 ≡ *n*φ(*m*) (mod *p**k*).
* Otherwise, because *φ*(*p**k*) divides *φ*(*m*), Euler’s theorem gives *n*2φ(*m*) ≡ 1 ≡ *n*φ(*m*) (mod *p**k*).

Therefore, *n*2φ(*m*)*n*φ(*m*) (mod *m*).

**Corollary.** If *k* ≥ φ(*m*), then *n**k**n*φ(*m*) + (*k* mod φ(*m*)) (mod *m*).

*Proof:* If *k* ≥ 2φ(*m*), the lemma gives *n**k* = *n*2φ(*m*)*n**k* \- 2φ(*m*)*n*φ(*m*)*n**k* \- 2φ(*m*) = *n**k* \- φ(*m*) (mod *m*) and we repeat until the exponent is less than 2φ(*m*).
> 7 votes

# Answer
# Haskell, 156 bytes

`(?)` takes two `Integer`s and returns an `Integer`, use as `(10^10)?2017` (reversed order compared to OP.)

```
1?n=0
m?n=n&m$m#2+m#2?(n+1)
1#_=1
n#p|m<-until((<2).gcd p)(`div`p)n=m#(p+1)*1`max`div(n*p-n)(p*m)
(_&_)0=1
(x&m)y|(a,b)<-divMod y 2=mod(x^b*(mod(x*x)m&m)a)m

```

Try it online! (I put the cases to test in the header this time, since they use exponentiation notation.)

Curiously the slowest test case isn't the one with a speed limit (that's almost instant), but the `524287 ? 32` one, because `524287` is a much larger prime than appears in the factors of the other test cases.

# How it works

* `(x&m)y` is `x^y `mod` m`, or power mod, using exponentiation by squaring.
* `n#p` is the Euler totient function of `n`, assuming `n` has no smaller prime factors than `p`.
    + `m` is `n` with all `p` factors divided out.
    + If there are `k` such factors, the totient should itself get a corresponding factor `(p-1)*p^(k-1)`, which is calculated as `div(n*p-n)(p*m)`.
    + `1`max`...` handles the case where `n` wasn't actually divisible by `p`, which makes the other argument of `max` equal to `0`.
* The main function `m?n` uses that when `y` is large enough, `n^y `mod` m` is the same as `n^(t+(y`mod`t)) `mod` m`, when `t` is the totient of `m`. (The `t+` is needed for those prime factors `n` and `m` have in common, which all get maximized.)
* The algorithm stops because iterated totient functions eventually hit 1.
> 5 votes

# Answer
# Mathematica, 55 bytes

```
n_~f~1=0;n_~f~m_:=PowerMod[n,(t=EulerPhi@m)+f[n+1,t],m]

```

Examples:

```
In[1]:= n_~f~1=0;n_~f~m_:=PowerMod[n,(t=EulerPhi@m)+f[n+1,t],m]

In[2]:= f[2, 10^15]

Out[2]= 566088170340352

In[3]:= f[4, 3^20]

Out[3]= 4

In[4]:= f[32, 524287]

Out[4]= 16

In[5]:= f[2017, 10^10]

Out[5]= 7395978241

```
> 2 votes

# Answer
# Pari/GP, 56 bytes

```
f(n,m)=if(m-1,lift(Mod(n,m)^((t=eulerphi(m))+f(n+1,t))))

```

Try it online!
> 2 votes

---
Tags: code-golf, arithmetic
---


title: Four-Four-Four-Four!

text:
# Question
Title: Four-Four-Four-Four!
This is the sequel to one of my previous challenges, Three-Three-Three!

---

Write a program (or function, or snippet) that takes no input and produces an output according to the following four Conditions.

> Both the program and the output must be written such that:
>
> 1. At least 16 distinct characters appear (since 16 = 4 × 4).
> 2. The number of occurrences of each character is a multiple of 4.
>
> Also:
>
> 3. The program and the output must not be the same (because programs consisting of a single literal like `1111222233334444` are quite boring).
>
> Finally, the program:
>
> 4. Cannot be written as a string repeated 4 times (e.g. `f();f();f();f();`, `1234123412341234`).

It's ! In anticipation of a multi-way tie for 64 bytes, the first submission whose *output* also satisfies Condition 4 will be the winner.

## Notes

# Answer
> 0 votes
# CJam, 16 bytes

```
4,4,4,4,@@@@\\\\

```

Try it online!

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


title: More efficient US state codes

text:
# Question
Title: More efficient US state codes
Abbreviate that US state! was fun, but we learnt that efficiently abbreviating US state names is hard with the current system. Let's come up with an alternative state code scheme for efficient golfing.

Your task:

> Write a function (or program) which, given a valid US state name (only the 50 normal states required), returns a unique two-letter code in uppercase identifying it. The code must meet these requirements:
>
> * The first letter must be the same as the first letter of the state.
> * The second letter must be one of the other letters of the state (not a space).
> * It must always give the same output for the same input, and must never give the same output for two different valid inputs.

For instance, given "Alabama", your function could return "AL", "AA", "AB" or "AM" - as long as it doesn't return that value for any of Alaska, Arkansas, etc. ("AA" is only possible because "A" appears more than once in the state name.)

Standard loopholes forbidden. Standard input/output are ok. This is code golf, so shortest solution, in bytes, wins.

The complete list of possible inputs is here:

```
Alabama
Alaska
Arizona
Arkansas
California
Colorado
Connecticut
Delaware
Florida
Georgia
Hawaii
Idaho
Illinois
Indiana
Iowa
Kansas
Kentucky
Louisiana
Maine
Maryland
Massachusetts
Michigan
Minnesota
Mississippi
Missouri
Montana
Nebraska
Nevada
New Hampshire
New Jersey
New Mexico
New York
North Carolina
North Dakota
Ohio
Oklahoma
Oregon
Pennsylvania
Rhode Island
South Carolina
South Dakota
Tennessee
Texas
Utah
Vermont
Virginia
Washington
West Virginia
Wisconsin
Wyoming

```

# Answer
> 7 votes
# Jelly,  ~~13~~  12 bytes

```
907ị;⁸Qḣ2ṢŒu

```

A monadic link taking and returning lists of characters.

**Try it online!** or see a test suite

### How?

```
907ị;⁸Qḣ2ṢŒu - Monadic link: list of characters, state    e.g. Alabama   or   Kansas
907          - literal 907
   ị         - index into state                                b              K
     ⁸       - link's left argument, state
    ;        - concatenate                                     bAlabama       KKansas
      Q      - de-duplicate (unique by 1st appearance)         bAlam          Kans
       ḣ2    - head to index 2                                 bA             Ka
         Ṣ   - sort                                            Ab             Ka
          Œu - convert to uppercase                            AB             KA

```

Indexing in Jelly is 1-indexed and modular, so the 907th index of something of length L is the (907-modulo-L)th item. For example for "Alabama" the length is 7 so the item at index 907 is the (907-modulo-7)th, and 907-modulo-7 is 4 (907 = 129 * 7 + **4**), so the item at index 907 is 'b'.

907 is the first positive index at which the state abbreviations using index 1 and that index over all of the 50 states become unique.

State names, including their spaces, are of length 4 through 14 inclusive, and 907-modulo-6 is 1 (whereas for all other lengths the value is not 1). This means that if we were to use the 1st and 907th characters for the abbreviations that Alaska, Hawaii, Kansas, Nevada, and Oregon would be AA, HH, KK, NN, and OO respectively - this is not acceptable for Hawaii, Kansas, or Nevada; so an adjustment needs to be made; this is the reason for the concatenation, de-duplication, head to index 2 and sort, this makes Alaska, Hawaii, Kansas, Nevada, and Oregon become AL, HA, KA, NA and OR respectively and does not collide with existing state abbreviations.

# Answer
> 3 votes
# Ruby, 34 bytes

```
->s{s[0]+(s[1,8]*999)[445].upcase}

```

I started off with `s[0]+s*99999[x].upcase` and found many values of x up to x=100000 which returned unique codes for all 50 states. Unfortunately they all had cases where the second letter of the abbreviation was the first letter of the state duplicated, which is not allowed (unless the letter appears twice in the state name.) So I decided to use the expression `s[0]+s[1,8]*999[x]` and found the smallest value of x that worked was 445.

**Commented in test program, and output**

```
f=->s{s[0]+            #Return character 0 of the input. Then..
(s[1,8]*999)[          #Concatenate 999 copies of the 8 characters starting at character 1 (or till end of name if state has less than 9 characters)
   445].upcase         #Return character 445 of the result, converted to uppercase.
}
"Alabama
Alaska
Arizona
Arkansas
California
Colorado
Connecticut
Delaware
Florida
Georgia
Hawaii
Idaho
Illinois
Indiana
Iowa
Kansas
Kentucky
Louisiana
Maine
Maryland
Massachusetts
Michigan
Minnesota
Mississippi
Missouri
Montana
Nebraska
Nevada
New Hampshire
New Jersey
New Mexico
New York
North Carolina
North Dakota
Ohio
Oklahoma
Oregon
Pennsylvania
Rhode Island
South Carolina
South Dakota
Tennessee
Texas
Utah
Vermont
Virginia
Washington
West Virginia
Wisconsin
Wyoming".split($/).map{|i|p [f[i],i]}

["AA", "Alabama"]
["AL", "Alaska"]
["AI", "Arizona"]
["AS", "Arkansas"]
["CR", "California"]
["CA", "Colorado"]
["CT", "Connecticut"]
["DA", "Delaware"]
["FO", "Florida"]
["GO", "Georgia"]
["HA", "Hawaii"]
["IA", "Idaho"]
["IO", "Illinois"]
["ID", "Indiana"]
["IW", "Iowa"]
["KA", "Kansas"]
["KC", "Kentucky"]
["LA", "Louisiana"]
["MI", "Maine"]
["MA", "Maryland"]
["MH", "Massachusetts"]
["MG", "Michigan"]
["MO", "Minnesota"]
["MS", "Mississippi"]
["MU", "Missouri"]
["MN", "Montana"]
["NS", "Nebraska"]
["NE", "Nevada"]
["NM", "New Hampshire"]
["NR", "New Jersey"]
["NX", "New Mexico"]
["NO", "New York"]
["NC", "North Carolina"]
["ND", "North Dakota"]
["OI", "Ohio"]
["OO", "Oklahoma"]
["OR", "Oregon"]
["PL", "Pennsylvania"]
["RI", "Rhode Island"]
["SC", "South Carolina"]
["SD", "South Dakota"]
["TS", "Tennessee"]
["TX", "Texas"]
["UA", "Utah"]
["VR", "Vermont"]
["VN", "Virginia"]
["WG", "Washington"]
["WI", "West Virginia"]
["WS", "Wisconsin"]
["WO", "Wyoming"]

```

# Answer
> 3 votes
# Python 2, 39 bytes

```
lambda s:s[0]+s[906%len(s)or 1].upper()

```

Try it online!

## Python 2, 39 bytes

```
lambda s:s[0]+s[306%len(s)or-3].upper()

```

Try it online!

# Answer
> 2 votes
## JavaScript (ES6), 46 bytes

```
s=>s[0]+s[(s>'M')+1153%s.length].toUpperCase()

```

### Demo

```
let f =

s=>s[0]+s[(s>'M')+1153%s.length].toUpperCase()

;[
  'Alabama',      'Alaska',   'Arizona',       'Arkansas',    'California','Colorado','Connecticut','Delaware',     'Florida',      'Georgia',
  'Hawaii',       'Idaho',    'Illinois',      'Indiana',     'Iowa',      'Kansas',  'Kentucky',   'Louisiana',    'Maine',        'Maryland',
  'Massachusetts','Michigan', 'Minnesota',     'Mississippi', 'Missouri',  'Montana', 'Nebraska',   'Nevada',       'New Hampshire','New Jersey',
  'New Mexico',   'New York', 'North Carolina','North Dakota','Ohio',      'Oklahoma','Oregon',     'Pennsylvania', 'Rhode Island', 'South Carolina',
  'South Dakota', 'Tennessee','Texas',         'Utah',        'Vermont',   'Virginia','Washington', 'West Virginia','Wisconsin',    'Wyoming'
]
.map(
  s => console.log(f(s), s)
)
```

# Answer
> 1 votes
# Retina, ~~49~~ 46 bytes

```
\B.*(?=[A-Zflmpxz])|\B.*(?=[hru])

T`l`L
!`^..

```

Try it online! If the state contains a second uppercase letter, or one of the letters `flmpxz`, then that becomes the second letter of the code. Otherwise, if it contains one of the letters `hru`, then that becomes the second letter of the code, otherwise just use the first two letters of the state.

# Answer
> 0 votes
# JavaScript (ES6), 52 bytes

```
s=>s[0]+(s=s.slice(2,9))[146%s.length].toUpperCase()

```

```
f=
s=>s[0]+(s=s.slice(2,9))[146%s.length].toUpperCase()

states = `Alabama
Alaska
Arizona
Arkansas
California
Colorado
Connecticut
Delaware
Florida
Georgia
Hawaii
Idaho
Illinois
Indiana
Iowa
Kansas
Kentucky
Louisiana
Maine
Maryland
Massachusetts
Michigan
Minnesota
Mississippi
Missouri
Montana
Nebraska
Nevada
New Hampshire
New Jersey
New Mexico
New York
North Carolina
North Dakota
Ohio
Oklahoma
Oregon
Pennsylvania
Rhode Island
South Carolina
South Dakota
Tennessee
Texas
Utah
Vermont
Virginia
Washington
West Virginia
Wisconsin
Wyoming`.split('\n')

states.forEach(state => console.log(f(state), state))
```

---

# JavaScript (ES6), 52 bytes

```
s=>s[0]+(s[8]||s[s[1]=='o'?5:4]||s[2]).toUpperCase()

```

```
f=
s=>s[0]+(s[8]||s[s[1]=='o'?5:4]||s[2]).toUpperCase()

states = `Alabama
Alaska
Arizona
Arkansas
California
Colorado
Connecticut
Delaware
Florida
Georgia
Hawaii
Idaho
Illinois
Indiana
Iowa
Kansas
Kentucky
Louisiana
Maine
Maryland
Massachusetts
Michigan
Minnesota
Mississippi
Missouri
Montana
Nebraska
Nevada
New Hampshire
New Jersey
New Mexico
New York
North Carolina
North Dakota
Ohio
Oklahoma
Oregon
Pennsylvania
Rhode Island
South Carolina
South Dakota
Tennessee
Texas
Utah
Vermont
Virginia
Washington
West Virginia
Wisconsin
Wyoming`.split('\n')

states.forEach(state => console.log(f(state), state))
```

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