text
stringlengths 180
608k
|
---|
[Question]
[
[Pascal's Pyramid](http://en.wikipedia.org/wiki/Pascal%27s_pyramid) is an extension of Pascal's Triangle to the third dimension. Starting with a 1 as the apex, the elements of each successive layer can be determined by summing the three numbers that are above it. The nth layer contains the coefficients of `(a + b + c)^(n-1)`.
You are to create a program that, given an input n, outputs the first n layers of Pascal's Pyramid. There must be two newlines between the different layers, and they must be in order. Within each layer, each row must be on a separate line, with the elements separated by spaces. Apart from that, you may format the pyramid however you like.
Your code should be reasonably fast generating a pyramid with 10 layers.
For example, your program, when given 4 as input, should output something like this:
```
1
1
1 1
1
2 2
1 2 1
1
3 3
3 6 3
1 3 3 1
```
May the shortest code win!
[Answer]
## Python, 110
```
l=1
exec"print;n=1;r=0;exec\"c=0;exec'print n,;n*=r-c;c+=1;n/=c;'*r;print n;r+=1;n=n*l/r-n;\"*l;l+=1;"*input()
```
Original, ungolfed solution:
```
for layer in range(1, input() + 1):
print
n = 1
for row in range(1, layer + 1):
for col in range(1, row):
print n,
n *= row - col
n /= col
print n
n *= layer - row
n /= row
```
[Answer]
## Mathematica (112)
```
For[j = 0, j < 11, j++, For[i = 0, i <= j, i++, Print[Row[Array[Binomial[i, # - 1] &, i + 1], " "]]]; Print[""]]
```
Older method(166):
```
b = "stdout"; For[k = 0, k < 11, k++, For[i = 0, i <= k, i++, For[j = 0, j <= i, j++, WriteString[b, Binomial[i, j], " "]]; WriteString[b, "\n"]]; WriteString[b, "\n"]]
```
The following prints it in a different format, but is only 94 characters:
```
For[i = 0, i < 11, i++, Print[Column[Table[Binomial[n, k], {n, 0, i}, {k, 0, n}]]]; Print[""]]
```
[Answer]
## Mathematica ~~65~~ 64
```
c=Column;c[c@Table[n~Binomial~k,{n,0,p},{k,0,n}]~Table~{p,0,#}]&
```
Usage
```
c=Column;c[c@Table[n~Binomial~k,{n,0,p},{k,0,n}]~Table~{p,0,#}]&@5
```
[Answer]
## Python (~~134~~ 128)
Factorials are probably more space-efficient, but I wanted to be fancy.
```
for n in range(1,input()+1):
a=r=1.
while a:
b=a;j=1.;a*=(n-r)/r
while b:print int(b),;b*=(r-j)/j;j+=1
print;r+=1
print
```
Uses the ratio property of Pascal's Triangle.
e.x. `1 4 6 4 1`, `1:4, 4:6, 6:4, 4:1` = `1:4, 2:3, 3:2, 4:1`
```
for n in range(1,input()+1): #Generate layers
a=r=1. #a is the first value of a row in a layer; r represents the row
while a: #when a is 0, there are no more rows in the pyramid.
b=a;i=1.;a*=(n-r)/r #b will calculate the values of that row
#use ratio property to determine next value of a
#i is a counter representing the ith item in row r
while b:print int(b),;b*=(r-i)/i;i+=1 #Output values using ratio property
print;r+=1 #increment row; loop
print
```
[Answer]
**k 31**
```
q)k)f:{,/{x**|x}{x{0+':x,0}\1}@'!x}
q)f 4
1
1
1 1
1
2 2
1 2 1
1
3 3
3 6 3
1 3 3 1
```
[Answer]
```
q)k)f:{,/{p**|p:x{0+':x,0}\1}'!x}
q)f 4
1
1
1 1
1
2 2
1 2 1
1
3 3
3 6 3
1 3 3 1
```
] |
[Question]
[
Ok, I found myself with a nice little problem:
you will get from `stdin` a string. In this string you will find some hex colors (like `#ff00dd`). You must return the string with the colors inverted (`#ff00dd` inverted is `#00ff11`).
A sample input/output could be:
```
ascscasad #ff00ff csdcas dcs c#001122 #qq5500
ascscasad #00ff00 csdcas dcs c#ffeedd #qq5500
```
As I am proficient in Haskell, I tackled the problem with it. Came up with this code, and I think it's the best I can do. Do you see any way to improve it / a completely different way to make it shorter?
```
import Text.Regex.Posix ( (=~) )
main = getLine >>= putStrLn . f
f [] = []
f x = let (b, q, p) = x =~ "#[0-f]{6}"
c = '#' : ['0'..'f'] ++ "#"
a = zip c (reverse c)
r = map ( (maybe '@' id) . (flip lookup $ a) ) q
in b ++ r ++ f p
```
I am also interested to compare other languages to Haskell, so post in other languages are welcome, too!
[Answer]
# Perl, 44 chars
Two different tweaks can get it to this length, one suggested by Primo:
```
s/#\K[\da-f]{6}/sprintf"%06x",~hex ff.$&/eg
```
Another one by playing around with the `/ee` modifier:
```
s/#\K[\da-f]{6}/"sprintf'%06x',~0xff$&"/eeg
```
Requires -p command line switch (1 char included in count).
Works for lower-case hex numbers (as in example). An `i` switch added to the regex would make it work for upper-case as well (though not preserving the case of the original number).
[Answer]
## APL 86
Index origin zero. Takes either a single colour hex string or multiple space separated colour strings as screen input via ←⍞
```
,' ',h[⊃16,¨,¨⍉¨(⊂16 16)⊤¨255-16⊥¨⍉¨(⊂3 2)⍴¨(⊂h←'0123456789abcdef#')⍳¨(c≠' ')⊂c←⍞~'#']
input: #ff00dd output: #00ff22
input: #ff00dd #00ff22 output: #00ff22 #ff00dd
```
[Answer]
# Ruby, 46 bytes
```
gets.gsub(/#(\h+)/){"#%06x"%(0xffffff^$1.hex)}
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 8 years ago.
[Improve this question](/posts/1279/edit)
Some time ago, I found this unused hash function (written in Java) in our codebase:
```
long hashPassword(String password)
{
password = password.toUpperCase();
long hash = 0;
int multiplier = 13;
for (int i = 0; i < password.length(); i++)
{
hash += hash * multiplier + (short)password.charAt(i);
multiplier++;
}
hash = Math.abs(hash);
hash <<= hash % 11;
hash = Math.abs(hash);
return hash;
}
```
I am very happy that it was unused, because it is beyond broken. Not only is this hash function very weak with an ouput of only 8 bytes, but it is also reversible, and it collides very easily: there are many similar inputs that will generate the same hash. A friend and I worked on the problem, and we managed to create a C# program that does just that: take a hash, and show the reasonable inputs that could have generated this hash.
Now is your turn. Write a program, in any language, that accepts a numeric hash as its sole parameter, and yields all possible inputs (made of 5+ characters with only printable ASCII characters) that would produce the given hash if passed to the function above, each on a new line. You don't need to handle any specific kind of error, as long as it works for any given numeric hash.
On your post, please include the hash of a word of your choice, and five possible inputs that have this hash (though your program must not be limited to finding only five).
Most elegant solution wins, and elegance is defined as algorithmic elegance (in other words, brute-force won't win). I'll accept an answer on March 13.
Example input and output (UNIX shell optional):
```
$ ./hashbreaker 224443104
ZNEAK
Y^4Q]
\2'!'
ZMUB9
Y_%AK
[and many, many, many more results...]
```
[Answer]
Another partial answer:
```
using System;
using System.Collections.Generic;
namespace Sandbox {
class Launcher {
public static int Main(string[] args) {
long h4;
if (args.Length != 1 || !long.TryParse(args[0], out h4)) {
Console.Error.WriteLine("Usage: Sandbox.exe <hash>");
return -1;
}
// TODO Handle 15-char or longer solutions. 15 chars is the point at which simple mod breaks because the multipliers wrap.
for (int len = 5; len < 15; len++)
foreach (long h3 in invAbs(h4))
foreach (long h2 in h3Toh2(h3))
foreach (long h1 in invAbs(h2))
foreach (string soln in solveH1Inner(h1, new char[len], len - 1, 1, 13 + len))
Console.WriteLine(soln);
return 0;
}
private static IEnumerable<string> solveH1Inner(long rem, char[] chs, int off, long mul, long mod) {
if (off < 0) {
if (rem == 0) yield return new string(chs);
yield break;
}
long mask = (mul & -mul) - 1;
if ((rem & mask) != 0) yield break;
foreach (char ch in " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_{|}~") {
if ((ch * mul) % mod == rem % mod) {
chs[off] = ch;
foreach (string soln in solveH1Inner(rem - mul * ch, chs, off - 1, mul * mod, mod - 1))
yield return soln;
}
}
yield break;
}
private static IEnumerable<long> invAbs(long h4) {
if (h4 < 0 && h4 != long.MinValue) throw new ArgumentException();
yield return h4;
if (h4 != long.MinValue) yield return -h4;
}
private static IEnumerable<long> h3Toh2(long h3) {
// h3 = h2 << (h2 % 11)
// where h2 is either long.MinValue or non-negative.
// long.MinValue << (long.MinValue % 11) = 0
if (h3 == 0) yield return long.MinValue;
for (int shift = 0; shift < 11; shift++) {
if (shift == 0 && h3 < 0) continue;
long mask = (1L << shift) - 1;
if ((h3 & mask) != 0) break;
long inc = shift == 0 ? 0 : 1L << (64 - shift);
long maskBottom = inc - 1;
long bottom = (h3 >> shift) & maskBottom;
long top = 0;
do {
if ((top + bottom) % 11 == shift) yield return (top + bottom);
top += inc;
} while (top > 0);
}
}
}
}
```
There are some minor optimisations which could be done, but I think it's more legible like this. (Arguably I should eliminate the enumerators and push the WriteLine in too, but hey).
Example of collisions for 199681664
```
PETER
OTTER
R(DER
Q6SVR
R*&$@
```
[Answer]
I got more than enough answers without reversing both `abs` calls, so I skipped that. They'd be trivial to add back if *really* needed. I'm not even taking `long` overflow into account, but that'd let you insert most any word you like in the greater hashes. As if that was needed to get collisions.
```
import Data.Char
import Data.Bits
import Control.Monad
printables = [32..95]
reverseModShift11 x = do
let zeros = head $ filter (testBit x) [0..]
b <- [0 .. zeros]
let h = x `shiftR` b
guard $ (h `mod` 11) == (fromIntegral b)
return h
reverseBase p m n | m < 13 = []
| n < 0 = []
| n == 0 && m == 13 = return p
| otherwise = do
let r = n `mod` m
c <- filter (\x -> x `mod` m == r) printables
reverseBase (chr c:p) (m-1) ((n-c) `div` m)
reverseBases = join . ap (map (reverseBase "") [14..29]) . return
breakHash = reverseModShift11 >=> reverseBases
```
Sample use:
```
*Main> breakHash 224443104
["]#'!'","\\2'!'","[A'!'","ZP'!'","Y_'!'",
(...)
"[?EAK","ZNEAK","Y]EAK",
(...)
"] TQ]","\\/TQ]","[>TQ]","ZMTQ]","Y\\TQ]"]
```
[Answer]
# JavaScript 224 LOC
This function will calculate all results of a given length, optionally limited to results starting with a given string, that is if it's done within the 1 second that I have allotted. If no results exist it is done virtually instantly. The function rely heavily on a very slow custom built 64 bit integer library, an equivalent C function would probably be 100 to 1000 times faster. I might set up a nice web interface.
```
<html>
<head>
<title>Break Hash</title>
</head>
<body>
<pre id="out"></pre>
<script>
function to64(inp){
var res=[]
res[0]=inp%(256*256*256)
inp=Math.floor(inp/(256*256*256))
res[1]=inp%(256*256*256)
inp=Math.floor(inp/(256*256*256))
res[2]=inp%(256*256)
return res
}
function add64(inp1,inp2){
var res=[]
res[0]=inp1[0]+inp2[0]
res[1]=inp1[1]+inp2[1]+Math.floor(res[0]/(256*256*256))
res[2]=(inp1[2]+inp2[2]+Math.floor(res[1]/(256*256*256)))&(256*256-1)
res[0]&=(256*256*256-1)
res[1]&=(256*256*256-1)
return res
}
function neg64(inp){
var res=[]
res[0]=inp[0]^(256*256*256-1)
res[1]=inp[1]^(256*256*256-1)
res[2]=inp[2]^(256*256-1)
return add64(res,[1,0,0])
}
function abs64(inp){
if(inp[2]>=(256*128)){
return neg64(inp)
}
return inp
}
function mul64(inp1,inp2){
var res=[]
res[0]=inp1[0]*inp2[0]
res[1]=inp1[1]*inp2[0]+inp1[0]*inp2[1]+Math.floor(res[0]/(256*256*256))
res[2]=inp1[2]*inp2[0]+inp1[1]*inp2[1]+inp1[0]*inp2[2]+Math.floor(res[1]/(256*256*256))
overflow=(res[2]>=(256*256)) //Global shortcut
res[2]&=(256*256-1)
res[0]&=(256*256*256-1)
res[1]&=(256*256*256-1)
return res
}
function mod64(inp1,inp2){ //64,float -> float
var res=inp1[2]%inp2
res=(res*(256*256*256)+inp1[1])%inp2
return (res*(256*256*256)+inp1[0])%inp2
}
function div64(inp1,inp2){ //64,float -> 64
var res=[]
res[2]=Math.floor(inp1[2]/inp2)
var mem1=inp1[1]+(inp1[2]%inp2)*(256*256*256)
res[1]=Math.floor(mem1/inp2)
res[0]=Math.floor((inp1[0]+(mem1%inp2)*(256*256*256))/inp2)
return add64(res,[0,0,0])
}
function cmp64(inp1,inp2){
for(var a=2;a>=0;a--){
if(inp1[a]>inp2[a]){
return 1
}
if(inp1[a]<inp2[a]){
return -1
}
}
return 0
}
function string64(inp){
var res=""
while(cmp64(inp,[0,0,0])){
res=mod64(inp,10)+res
inp=div64(inp,10)
}
return res||"0"
}
function hashPassword(password){
var i
password=stringtoarray(password)
var hash = to64(0);
var multiplier = to64(13);
for (i = 0; i < password.length; i++){
multiplier = add64(multiplier,[1,0,0])
hash = add64(mul64(hash,multiplier),to64(password[i]));
}
hash = abs64(hash);
hash = mul64(hash,to64(Math.pow(2,mod64(hash,11))));
hash = abs64(hash);
return string64(hash)
}
function stringtoarray(password){
var i
if((typeof password)=="string"){
var password2 = password.toUpperCase();
password=[]
for(i=0;i<password2.length;i++){
password[i]=password2.charCodeAt(i)
}
}
return password
}
function reverse(hash,start,len){
var maxtime=(+new Date())+1000
var m1=neg64(to64(1))
start=stringtoarray(start)
var multipliers=[]
var multipliersum=[]
var max=[]
var min=[]
var firstlimit=0
multipliers[len-1]=[1,0,0]
multipliersum[len-1]=[1,0,0]
max[len-1]=[126,0,0]
min[len-1]=[32,0,0]
for(var a=len-2;a>=0;a--){
multipliers[a]=mul64(multipliers[a+1],to64(15+a))
multipliersum[a]=add64(multipliers[a],multipliersum[a+1])
min[a]=mul64(multipliersum[a],[32,0,0])
max[a]=mul64(multipliersum[a],[126,0,0])
if(overflow && !firstlimit){
firstlimit=a+1
}
}
var startvalue=[0,0,0]
for(var a=0;a<start.length;a++){
startvalue=add64(startvalue,mul64(to64(start[a]),multipliers[a]))
}
startvalue=neg64(startvalue)
allowed=[]
for(a=0;a<32;a++){
allowed[a]=false
}
for(a=32;a<97;a++){
allowed[a]=true
}
for(a=97;a<123;a++){
allowed[a]=false
}
for(a=123;a<127;a++){
allowed[a]=true
}
for(a=127;a<256;a++){
allowed[a]=false
}
var results=[]
function arrtostring(arr){
str=""
for(var a=0;a<arr.length;a++){
//str+=String.fromCharCode(arr[a])
str+="&#"+arr[a]+";"
}
return str
}
function makepwd(ihash){ //This is where clock cycles go to die
ihash=add64(ihash,startvalue)
stringarr=[]
for(var a=0;a<start.length;a++){
stringarr[a]=start[a]
}
function addrest(ihash,startfrom){
if(maxtime<(+new Date())){
return
}
var a
var jhash
if(startfrom==len){
if(cmp64(ihash,[0,0,0])==0){
results[results.length]=arrtostring(stringarr)
}
}
else if(startfrom<firstlimit || ((cmp64(ihash,min[startfrom])!=-1) && (cmp64(ihash,max[startfrom])!=1))){
for(a=32;a<127;a++){
if(allowed[a]){
jhash=add64(ihash,neg64(mul64(to64(a),multipliers[startfrom])))
stringarr[startfrom]=a
addrest(jhash,startfrom+1)
}
}
}
}
addrest(ihash,start.length)
}
function reversemod(ihash){
if(ihash[2]<(128*256)){
if(mod64(ihash,11)==0){
makepwd(ihash)
makepwd(neg64(ihash))
}
}
var modresult=1
var a
var addlim
var jhash
while(mod64(ihash,2)==0){
ihash=div64(ihash,2)
addlim=Math.pow(2,modresult-1)
for(a=0;a<addlim;a++){
jhash=add64(to64(a*Math.pow(2,64-modresult)),ihash)
if(mod64(jhash,11)==modresult){
makepwd(jhash)
makepwd(neg64(jhash))
}
}
modresult++
}
}
reversemod(hash)
reversemod(neg64(hash))
return results
}
document.getElementById("out").innerHTML=reverse(to64(224443104),"ebusiness",22).join("<br>")
//document.getElementById("out").innerHTML=hashPassword("EBUSINESS\"XUWL]NHHHF{I")
</script>
</body>
</html>
```
Some collisions for 224443104
```
EBUSINESS"XUWL]NHHHF{I
EBUSINESS"XUWL]NHHHF|&
EBUSINESS"XUWL]NHHHGYI
EBUSINESS"XUWL]NHHHGZ&
EBUSINESS"XUWL]NHHHH7I
```
] |
[Question]
[
**This question already has answers here**:
[Zeroes at the end of a factorial](/questions/79762/zeroes-at-the-end-of-a-factorial)
(62 answers)
Closed 7 years ago.
Write a function which takes n as a parameter, and returns the number of trailing zeros in n!.
## Input Constraints
0 <= n <= 10^100
## Output Constraints
Should be return the result in less than 10 seconds.
## Test Input
```
1
213
45678
1234567
78943533
4567894123
121233112233112231233112323123
```
## Test Output
```
0
51
11416
308638
19735878
1141973522
30308278058278057808278080759
```
Shortest code by character count wins.
[Answer]
# Python ~~50~~ 47 Characters
```
n=input()
x=5
s=0
while n/x:s+=n/x;x*=5
print s
```
[Answer]
# Python, 36 Chars
Ripped from my earlier [answer](https://codegolf.stackexchange.com/questions/694/last-non-zero-digit-of-n/697#697)
```
f=lambda n:n//5+(n//5>0and f(n//5)or 0) #Py3k #39 Chars
f=lambda n:n/5+(n/5>0and f(n/5)or 0) #Before 3.0 #36 Chars
```
[Answer]
# J, 26
```
! `f=:3 :'+/<.y%5^(1+i.144x)'`
```
eg
```
f 121233112233112231233112323123x
30308278058278057808278080759
f 4567894123
1141973522
f 0
0
f 10^100x
2499999999999999...99999999999999999982
```
in less than a second for all input examples
[Answer]
# Haskell, 63 bytes
```
f i=length$filter(\x->x`mod`5/=0)[1..i];main=interact$show.f.read
```
[Answer]
# Ruby, 52 43
```
n=gets.to_i;a=0;i=1
a+=n/i*=5while i<n
p a
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 1 year ago.
[Improve this question](/posts/251491/edit)
If you consider the following PHP+C polyglot snippet, there is a problem regarding class property access in the printf call:
```
#include <stdio.h>
#include <stdlib.h>
#define class struct
#define function
class Point {
#define public int
public $x;
public $y;
};
int
function main()
{
struct Point*
$p = alloca(sizeof(struct Point));
printf("%d", $p->x); // PHP expects $p->x, but C expects $p->$x
return 0;
}
```
My question is, how to resolve this in a neat manner? Possible solutions:
1. Remove all `$` via sed before compiling with gcc
2. Define `public $x` as `int x` using `#if __PHP__`
3. Edit: Use getters, maybe? (works in C by passing self as first argument with function pointers)
Trying to define dollar sign as empty space does not work:
```
#define $
```
Any other ideas? I am also considering using m4 in the C Makefile. Thank you. :)
[Answer]
You can add `#define x $x` with the other `#define`s at the top. Now `$p->x` should also work in C.
] |
[Question]
[
Your task is to write a program that performs case conversion from plain text, and other case formats, into one of the specified formats below. Inputs will be either plain lowercase text, or one of the detailed cases below. You must remove non-alphabetic characters except (space), `_` (underscore) and `-` (hyphen), then split the string into words by the locations of /`_`/`-` and places where two adjacent characters have different cases (e.g. `bA`). Then change the capitalization of each word and join the words on some delimiting character. The specifics of capitalization and delimiter depend on the case conversion chosen.
Your program must be a polyglot in at least two different languages. For example, running your code in Python 2 transforms input to `snake_case`, running it in JavaScript transforms to `kebab-case`, Ruby transforms to `PascalCase` and 05AB1E transforms to `camelCase`.
## Tasks
The following case conversions can be completed:
| Case | Capitalization | Delimiter |
| --- | --- | --- |
| camelCase | First word should be all lowercase; the rest should be all lowercase except for the first letter, which should be uppercase. | None |
| PascalCase | The first letter of each word should be uppercase, the rest lowercase. | None |
| snake\_case | Words should be all lowercase. | `_` |
| UPPER\_SNAKE\_CASE | Words should be all uppercase. | `_` |
| kebab-case | Words should be all lowercase. | `-` |
### camelCase
```
this is a test thisIsATest
camelCaseTest camelCaseTest
PascalCaseTest pascalCaseTest
snake_case_test snakeCaseTest
kebab-case-test kebabCaseTest
testing!!one!!!1!!! testingOne1
aBCDef aBCDef
ABCDef aBCDef
a_b_c_def aBCDef
a-b-c-def aBCDef
```
[Try it online!](https://tio.run/##RYvdCoJAEIXvfYpdkFBkGQy66qqfBwgKgtSW0aaSNpXGCKJnb9u1IJjDnG/mnI5uZmItQ5ZvdZGAgNM0YNiL5CWSEH6UzdSugNyEI39IH@fakGCIMlTPIo6GdwxhKlxk/O2IKF/HkN/D1LG1m3PNwg2KnrgPKrySWSDTxtMKucI/coMX0pVDPYQvVGKpPKuBfahuTlK2DUkpU6cA54slHYPZd6EudaUP3inXVM69266v24at6swH "Perl 5 – Try It Online")
### PascalCase
```
this is a test ThisIsATest
camelCaseTest CamelCaseTest
PascalCaseTest PascalCaseTest
snake_case_test SnakeCaseTest
kebab-case-test KebabCaseTest
testing!!one!!!1!!! TestingOne1
aBCDef ABCDef
ABCDef ABCDef
a_b_c_def ABCDef
a-b-c-def ABCDef
```
[Try it online!](https://tio.run/##RYvdCoJAEIXvfYpdkFBkGQy66qqfBwgKgtSW0aaSNpXGCKJnb9u1IJhhznfmnI5uZmItQ5ZvdZGAgNM0YNiL5CWSEH6UzdSugNyEI2@kj3NtSDBEGapnEUfDO4YwFS4y/nai/UvEUb6OIb8PnrWbc83CDYqeuA8qvJJZINPG0wq5wj9ygxfSlUM9hC9UYqk8q4F9qG5OUrYNSSlTtwHOF0s6BrPvQV3qSh@8Uq6pnHq3XV@3DVvVmQ8 "Perl 5 – Try It Online")
### snake\_case
```
this is a test this_is_a_test
camelCaseTest camel_case_test
PascalCaseTest pascal_case_test
snake_case_test snake_case_test
kebab-case-test kebab_case_test
testing!!one!!!1!!! testing_one_1
aBCDef a_b_c_def
ABCDef a_b_c_def
a_b_c_def a_b_c_def
a-b-c-def a_b_c_def
```
[Try it online!](https://tio.run/##RYvdCoJAEIXvfYpdkDBkGQy66qqfB@hCCFJbRptM3FQaIYievW3XgmAOc76Zcwa6m6W1DFl@0EUMAupVwHAS8UvEIfwoW6tjAbkJZ/6QPK6NIcEQZaiexTya3nMIE@Eii29HgHbG2vTasHCDYiQegwpvZLbIlHraI1f4R@6wJV051FO4pRJL5VlN7ENNV0vZdySlTJwC3Gx3dAnW34W61JU@e6dcUzn37oex6Tu2ajAf "Perl 5 – Try It Online")
## UPPER\_SNAKE\_CASE / SCREAMING\_SNAKE\_CASE
```
this is a test THIS_IS_A_TEST
camelCaseTest CAMEL_CASE_TEST
PascalCaseTest PASCAL_CASE_TEST
snake_case_test SNAKE_CASE_TEST
kebab-case-test KEBAB_CASE_TEST
testing!!one!!!1!!! TESTING_ONE_1
aBCDef A_B_C_DEF
ABCDef A_B_C_DEF
a_b_c_def A_B_C_DEF
a-b-c-def A_B_C_DEF
```
[Try it online!](https://tio.run/##RYvBCsIwEETv/YoEiiglLBU8iYeqH@BBEKw1bOOqxdgWtyKI325MqiDssPN2Z1q62YlzDPluo4sEBJymEcNeJC@RxPCjPFPbAnY2HoRD@jhXlgTDMEf1LEbD/j2COBU@Mv52BOhgYj27G@e6c8XCD4qOuIsMXskukGkdaIVs8I9c44W08aj78IVKLFVg1XMIVfVJyqYmKWXqFeF8saRjlH0X6lIbfQhO@aby7t20XdXU7FRrPw "Perl 5 – Try It Online")
### kebab-case
```
this is a test this-is-a-test
camelCaseTest camel-case-test
PascalCaseTest pascal-case-test
snake_case_test snake-case-test
kebab-case-test kebab-case-test
testing!!one!!!1!!! testing-one-1
aBCDef a-b-c-def
ABCDef a-b-c-def
a_b_c_def a-b-c-def
a-b-c-def a-b-c-def
```
[Try it online!](https://tio.run/##RYvdCoJAEIXvfYpdkDBkGQy66qqfB@hCCFJbRptM3FQaIYievW3XgmAOc76Zcwa6m6W1DFl@0EUMAupVwHAS8UvEIfwoW6tjAbkJZ/6QPK6NIcEQZaiexTya3nMIE@Eii29HgHLG2vTasHCDYiQegwpvZLbIlHraI1f4R@6wJV051FO4pRJL5VlN7ENNV0vZdySlTJwC3Gx3dAnW34W61JU@e6dcUzn37oex6Tu2ajAf "Perl 5 – Try It Online")
## Rules
* Your code should produce the same output as the linked examples.
* Entries with the most conversions in each language win, with code length being a tie-breaker.
[Answer]
## Java, [Retina](https://github.com/m-ender/retina/wiki/The-Language), [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/blob/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b/docs/info.txt), [2sable](https://github.com/Adriandmen/2sable/blob/master/Info.txt), 166 characters
```
//'_UðX:'-X:AuDSX«í‡X¡õKDтнi™Jć„ul®dè.VìëXýu}q
s->s.replaceAll("[A-Z]","-$0").toLowerCase().replaceAll(" |_","-").replaceAll("^-","")/*
[A-Z]
_$0
T`L`l
|-
_
^_
\*/
```
[Try it online in Java](https://tio.run/##VZHNSgMxEMfveYohCO1qs/XcolDtSWsRrLL4FdM01W3TbN1kK6IFEcG3EPQk@IEXj166PoC@Ql@kZutuoRDCzI//JP@Z6bABI0FfqE6rO@GSaQ1bzFdXCMBXRoRtxgXUkxRgx4S@OgWeTwPtlC0fIntpw4zPoQ4KVibFYo7uxh9eKUe8UiWq7nijl/htfPPojR7jz83q7@3Plz@@e9r4vh/fPERy9N6Kn929@DV@8eKvaHiONFnVbij60v5ekTKPDypk/wgXMFlYxo5rglpwIcJ1pkXemdPBNU1UeJ4eEwuxU1xE03cQXVhGjZPaiURwTRBFxxShw8UimpSTXvpRU9pe0pYGgd@Cnh1J2vXBEXP@x9EOwmwSRmiTuIESKHEBmfIKmzNfgz1sKsEFwJz1hEy0jRRsM83ZHNGKdQXlltCsqiuarEkSRDLE1tarop1ElVnEaJNy2koTYitIkgydqWG7wUttRM8NIuP2rUUjVT6zvoRLgJeUy2fESdc7nPwB): `kebab-case`
[Try it online in Retina](https://tio.run/##K0otycxLNPyvquGe8F9fXz0@9PCGCCt13Qgrx1KX4IhDqw@vfdSwMOLQwsNbvV0uNl3Ym/moZZHXkfZHDfNKcw6tSzm8Qi/s8JrDqyMO7y2tLeQq1rUr1itKLchJTE51zMnRUIp21I2KVdJR0lUxUNLUK8n3yS9PLXJOLE7V0ERRp1ATD1KlhCoapwsUVNLU1@ICm8MVr2LAFZLgk5DDpVCjyxXPFRfPxRWjpc/1/39JRmaxAhAlKpSkFpdwJSfmpuaArAkB8QISi5MTEdzivMTs1PhkIDcerDg7NSkxSRfE1wXzE52cXVLTuBwhVGJ8UnxyfAqIpQtUpQtkAQA): `snake_case`
[Try it online in 05AB1E](https://tio.run/##XZDNSsNAEMfv8xRDKPSDbtJzKS2x1YMWFKwS/Oh2s1lpaGxqN6WXFoqI3n0AoZ6E@nXx2EvXB9BXyIvEJBWkwsDMb/jPMP@xmexGnAVYRe47Qvcls12BlQpu7@9ATcPw9h61WmQYWXqk3q1yllhlc9Q4tFYL9RLO5tZqrj72Gt/XX0s3vHnc/bwLZw8jb/XqqCf9WD2rhaWWo2nxCiSpSn0oBh7jwvS8nHZqkpNzraiRTEnL64Hf9MdiWGdS5PIbOpzQRKVtdtskbmp5owDpHqCZErQ6zY4HOCFAoU0BzgoGRFP1VoTEDYy7ridwKJiDbh8cHxCF5EN3EKDhDwJjbf43/ftHBTPpTF9EQdeVGAfDQMgAOLsUXnJ2K6EDJjn7Q9lnPUF5jDQV94TNbJIwSZlt1RviAsx1YtSmnDpJRWIVSaof): `PascalCase`
[Try it online in 05AB1E (legacy)](https://tio.run/##XZDNSsNAEMfv8xTLUugH3aQiXkppia0etKBgleBHt5tkJaExqd2UUmihiOjdBxDqSahfF4@9dH0AfYW8SEzSg1QYmPn9@c8wMwYTdmSyAFWR6Vtc8QUzHI4qFbRzsAs1jMK7B4Rrkapm6bH80MtZope1QeNIX87lazid6cuZ/Nxv/Nx8L5zw9mnv6z6cPg7c5Zsln5UT@SLnulwMJsVrEKQqlD7vuczkmuvm8JlGTi9wEZNMCeeVwG/6Q96vM8Fz@TUfGtPEhdfVNolFnFcLkM4BmilBq9PsuIDGBCi0KcB5QYVoIt@LkFwDQ9txOepzZiHHA8sHhHqjwPa9TaT6vUAtbTFjg6urHyi90b@XVFAmbfN4FNiOQHEwFHARgMmuuJts3krokAmT/aHwWJdTM0aamrvcYAZJmKTMtusNfgnaKjFqUJNaSUViF0mqXw): `camelCase`
[Try it online in 2sable](https://tio.run/##XZDNSsNAEMfv8xTLUugH3aTorZSW2OpBCwpWCX50u0lWEhqT2E0pQgtFRO8@gFBPQv26eOyl6wPoK@RFYhIFqTAw8xv@M8x/DCbs2GQhqiPTt7jiC2Y4HNVqaHN3CxoYRTd3CDdiVc3TA/mmV/NEr2rD1r6@nMvnaDrTlzP5vtP6uvpcONH1w/bHbTS9H7rLF0s@KofySc51uRhOyhcgSF0oAx64zOSa6xbwsUaOTnEZk1wFF5XQb/sjPmgywQvFFR0a01SFV7tdkjRxUS1BtgdorgKdXrvnAhoToNClACclFeKJfC1D6gZGtuNyNODMQo4Hlg8IBZeh7XvrSPWDUF1LzLv8NynB5b@X1FAuG/N4HNqOQEkwFHIRgsnOuZte3klpjwmT/aHwWJ9TM0GaifvcYAZJmWTMNpotfgbaT2LUoCa10ookKpJW3w): `SCREAMING_SNAKE_CASE`
**Explanation:**
***Java:***
```
//... // No-op comment
s-> // Method with String as both parameter and return-type
s.replaceAll( // Regex-replace all:
"[A-Z]", // Uppercase letters
"-$0") // To the same uppercase letter with a prepended "-"
.toLowerCase() // Then convert it to lowercase
.replaceAll( // Then regex-replace all:
" |_", // Spaces or "_"
"-") // To "-"
.replaceAll("^-","") // And remove a potential leading "-"
/*...*/ // No-op comment
// No-op newline
```
***Retina:***
```
//A...™Jq
s->...)/*
```
Replace the first line to the second in the (implicit) input-string; which is basically a no-op replacement.
```
[A-Z]
_$0
```
Prepend a `_` in front of each uppercase letter.
```
T`L`l
```
Convert everything to lowercase.
```
|-
_
```
Replace any space or `-` to `_`.
```
^_
```
Remove a potential leading `_`.
```
\*/
```
No-op replacement to close the Java comment.
***05AB1E / 05AB1E (legacy) / 2sable:***
Let's start with a bit of history of these three versions. The development of 05AB1E started at the start of 2016 (or actually, the very first git-commit was on December 21st, 2015). This new codegolf language was being built in Python as backend. Mid 2016 2sable was branched of that current 05AB1E version (July 7th, 2016 to be exact), and the strength of 2sable in comparison to that old 05AB1E version was added: implicit inputs. Later on implicit input was also added to 05AB1E, and 2sable became obsolete and basically a forgotten version right after it was created on that day July 7th, 2016.
Then in mid-2018, a new 05AB1E version was being started, this time completely rewritten in Elixir instead of Python, with loads of new builtins added and some builtins changed or even removed.
So, let's go over the code and see what it does in each of the three versions:
```
/ # Divide the (implicit) input-string with itself, which is a no-op
# for strings
/ # And again
'_ '# Push string "_"
U # Pop and store it in variable `X`
ðX: # Replace all spaces with "_"
'-X: '# Replace all "-" with a "_" as well
Au # Push the uppercase alphabet
D # Duplicate it
S # Convert the copy to a list of characters
X« # Append "_" to each
í # Reverse each so "_" is prepended instead
# (2sable lacks prepend-builtin `ì`, hence the `«í` instead)
‡ # Transliterate, basically prepending a "_" before each uppercase
# letter in the input-string
X¡ # Then split on "_"
õK # Remove all empty strings, in case the input started with an
# uppercase letter
D # Duplicate the current list of strings
т # 05AB1E / 05AB1E (legacy): push 100
# 2-sable: no-op
н # Pop and push the first character:
# 05AB1E / 05AB1E (legacy): pops 100, pushes 1
# 2-sable: pops the string: pushes its first character
i # If this is 1 (continue for 05AB1E / 05AB1E (legacy)):
™ # Titlecase each inner string
J # Join it together
ć # Extract the first character
„ul # Push string "ul"
® # Push -1
d # 05AB1E: check if it's a non-negative (>=0) integer: pop -1, push 0
# 05AB1E (legacy): check if it's an integer: pop -1, push 1
è # Use that to index into the "ul" string
.V # Execute it as 05AB1E code
# 05AB1E: uppercase the letter
# 05AB1E (legacy): lowercase the letter
ì # Prepend it back to the string
ë # Else (continue for 2sable):
Xý # Join the list with "_" delimiter
u # Uppercase the letters in the string
} # (for all three again): close the if-else statement
q # Exit the program, making everything after it no-ops
# (after which the result is output implicitly)
```
Minor note: `®dilëu` would have been shorter than `„ul®dè.V`, but unfortunately 2sable doesn't deal very well with nested if-else statements.
[Answer]
# [Ruby & J](https://www.ruby-lang.org/), 189 bytes
```
NB.x rescue puts$<.read.split(/(?=[A-Z])|[^a-zA-Z]+/).map{_1.downcase.gsub(/[^a-z]/,'')}*"_"
#]exit'']echo tolower(,'-'&,)&:>/a:-.~(<@(-.-.&AlphaNum_j_)@u:;.1~1:0}<&97+.>&122)&(3&u:)(1!:1)3
```
[Ruby (snake)](https://ato.pxeger.com/run?1=LY9NUsIwAEb3nqJBJz_SpAYWaqwIdc_KlUztpCXQOqXJNMmAIlzETRd6DA_CbfzBxZv5Fu9bvPeP1ucvXffp3YJeHb6mCdsErbKFV4Hxzp7FrFVyzqypK4cjfHc7m9DHlLzNniR9_Z39iLCVNNuMs7leN4W0ii2tz3H0p6RRiBDZnfey3slpqjaVQyhVRakDp2u9Vi0OEUUwJFCMIiko2-N4jCmjDE5qU8qpX2XPGRl7ccP4nouLXQyvL_tsBPlgQCAeQi8I5kBwMjxG_Ld0B_ygrKuaJQC6UQAA_sMkuV9oncg2KKsgV8okWpvj4Rs)
[J (kebab)](https://tio.run/##HcpNT8IwGMDxu59iRdMXWZ9ZOBjrRDbvnDxJ5lLGIxsZa7Ougajw1efL4Z/8Dv/9OK5yOEU9@ipg5MLgb1Lo0WzBu7YZeMKfn9aZfCvE9/rdyM8/ThMBB@O@SgVbe@wq4xF2Pmx48r8UScyYON9OysnVdYGnZmCswKq20WBbe8Sex0wyGguqF4nREi48XXIJEmjWutqswqHcl2IZ9COoi9J355Q@3E9hQdVsJiif06AFV0QrMR/HV/RD0@0IsR0SQtRvWf7yYW1u@qhuog2iy611Pw "J – Try It Online")
These are really terrible as golfs, and I was hoping to get at least one more lang, but this was all I could manage for tonight...
* `NB.` is the J comment prefix, and `NB.x` is valid ruby code for attempting to invoke the method `x` on the constant `NB`. It will fail since `NB` is undefined, but we can then just `rescue` that error and proceed as normal.
* `#` is a ruby comment, and a J verb. It gets ignored when J runs because J executes right to left, and we `exit` before it gets interpreted.
] |
[Question]
[
The **Zany Car Game** is a tile matching game. You are given a number of tiles, with coloured cars split into a top and bottom half. To win the game, you need to find a square arrangement of the tiles so that only whole, correctly coloured cars are formed at each tile join , like the image below.
[](https://i.stack.imgur.com/XIjWi.jpg)
## Challenge
Given a square set of mixed tiles, output any solution of correctly ordered tiles. If there is no solution, output nothing. You can choose how to input the tiles. You may either output the tiles in your input format, or output the required rearranged position of the tiles and their rotations from the input (see the example).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins
## Example
Take each tile as a flat list, of the form `[UP, RIGHT, DOWN, LEFT]`. The colour-half combinations are represented by numbers as follows
```
Red top = 1
Red bottom = 8
Green top = 2
Green bottom = 7
Blue top = 3
Blue bottom = 6
Yellow top = 4
Yellow bottom = 5
```
So that the top and bottom of any given colour add to 9 (similar to how a die is arranged).
For this example we will use the following arrangement of tiles that needs solving:
```
-------
2 | 3
6 1|1 5
5 | 7
-------
7 | 2
6 4|4 8
1 | 6
-------
```
Which can be represented as a 2D list or a flattened list:
```
input = [
[[2,1,5,6],[3,5,7,1],],
[[7,4,1,6],[2,8,6,4],],
]
or
input = [[2,1,5,6],[3,5,7,1],[7,4,1,6],[2,8,6,4]]
```
The solution for this example can either be given as the rearranged tiles or the new position of each tile in the flattened list, with the rotation for each tile given as `0=0°, 1=90°, 2=180°, 3=270°`
```
output = [[6, 4, 2, 8], [7, 1, 3, 5], [7, 4, 1, 6], [6, 2, 1, 5]]
or
positions = [3, 1, 2, 0]
rotations = [2, 2, 0, 3]
```
Either of these should correspond to the solution:
```
-------
6 | 7
8 4|5 1
2 | 3
-------
7 | 6
6 4|5 2
1 | 1
-------
```
A python script solving this example can be found [here](https://ato.pxeger.com/run?1=hVVLbtswEN0VEE_BaiXajBHbaZIK8DZAVy2K7lTCUCQqYSuJKkWhTlJfIFfoJpv2UD1Nhx9Lcuy0ECCQ82bmzY_kz9_Nnb6V9dPTr04XJ5d_Xj2KqpFKY6G50lKWLfKCKtW3KOcFbpSo9VqLkreR_ZMYBW2TZnyt5He8wuFJOInOJiWvHZ6cMnIyJygopMJGRdTYAmAXaNnszH6Esy9S1FFShPjBKIDhFofYmJmtsQNVBp6CSuR5yY9YOsMlGLrVnG2Pe7iWWsvqZe7Fi9y2AFGf8SDyuQyCIcpBNvCC7MCVKXBRpjoqRavXi5zEGAWK607VOIGeVDaitrs2uAnK61mxxUHmYWa9dfXgz6xMtzYrGx10dNZ-UwBCqwYFQgbKXpqIySaO4DfdEObYbE3S-oZHILJc2S3Pvq5TZaUVNyXpB0Tc8yOsDif7w-GcGgsYGzMkBstk2VX1PmzBQBRunBIwnxjx1Oky6OH0GbIHn7LXq7cx9rlepWXL0Ytco1AOwvxfHPODOBwynTMY1SNB-N0n1XFbWCV1qrmtFsVAW1pKr2XH1QpjhqduG9u964pUOVeu0v0EmDQarqoO_AppU-1P_GwEtM_sfP5HrZTMu0xHySmd0wVdMqp4w1O96vvsx2tXrMNpUdzv8vWNEnm8Sv6RW382fUVMNPeiiUbR0z5Uwkh8J3iZ42ccdKy-00ZI1E3nLzm4HhIE3wLSekPPGUXJEhYXdA5Ls0PJBT0D0EILeknP6ZmDGELuhIfvjL84JGh8e45IyE7xcw1K7oxnGW_bo_GZVF1X7dke-zHV9a7ed9qTBmNWfyF4_6S_hYrwCuS4hck0HDF-8CrbcKTzQbbCDgbgyQH7TNQ539huk727c5QF2_P30acE7nbZbUNqy-CeJP8y7V6ovw).
## Test Cases
It's worth noting that each unique solution will have 4 solutions,
1 for each rotation of the whole grid. Only one orientation will be given here.
Input 1:
```
[[2,1,5,6],[3,5,7,1],[7,4,1,6],[2,8,6,4]]
```
Output 1:
```
[[6,4,2,8],[7,1,3,5],[7,4,1,6],[6,2,1,5]]
or
positions = [3, 1, 2, 0]
rotations = [2, 2, 0, 3]
```
Input 2:
```
[[1,2,3,4],[2,3,4,1],[3,4,2,1],[4,1,2,3]]
```
Output 2:
No solution
Input 3:
```
[[4,8,7,3],[1,2,5,7],[6,2,1,5],[2, 8, 6, 4]]
```
Output 3:
```
[[7,3,4,8],[4,2,8,6],[5,7,1,2],[1,5,6,2]]
or
Positions = [0, 3, 1, 2]
Rotations = [2, 3, 2, 2]
```
Input 4:
```
[[7,1,3,5],[1,6,7,4],[4,8,7,3],[1,5,6,2],[2,8,6,4],[2,5,6,1],[2,5,7,1],[3,5,7,1],[4,3,8,6]]
```
Output:
```
[[1,5,6,2],[1,6,7,4],[4,8,7,3],[3,5,7,1],[2,8,6,4],[2,5,6,1],[2,5,7,1],[8,6,4,3],[3,5,7,1]]
or
Positions = [8, 1, 2, 0, 4, 5, 6, 3, 7]
Rotations = [2, 0, 0, 0, 0, 0, 0, 0, 2]
```
[Answer]
# Python3, 408 bytes:
```
lambda s:(q:=int(len(s)**0.5))and[j for k in next(f([[0]*q]*q,[(x//q,x%q)for x in R(q**2)],s),[])for j in k]
R=range
v=lambda x,L,A,B:all(all(0 in[i[j],i[j+1]]or 9==i[j][A]+i[j+1][B]for j in R(L-1))for i in x)
def f(b,M,s):
if[]==s:yield b
x,y=M[0]
for O in s:
for j in R(4):
B=eval(str(b));B[x][y]=O[j:]+O[:j]
if v(B,L:=len(b),1,3)and v(zip(*B),L,2,0):yield from f(B,M[1:],[i for i in s if i!=O])
```
[Try it online!](https://tio.run/##XVHLbtswELzrK7aHAqS8aayHLZcFD9EhJxsGfGV5kGCpoaLIlmQYcn/e3aWNJA2gB2d2ZmdJHi@nl0OXrI7D9Vn/vrbFW7kvYFSiV9p1J9FWnRhlGM5/LKQsur1poD4M8Aqug66aTqIWxsxt2NODRkyPjz1O33vJoolFO9GHYSwtjhKN9XzD/KsNdnoouj9VcNb32AnX@IS5KtpW8DsnoXGmsUifWWQtmX9qzYx5srMbaXL73nQn1g@R9CGO8SSDfVVDLUrc0AAqAFcbq/WoLq5q91AGlHnRG9pB4Pe1ZddIOvjUM2UjQK6rc9GK8TSIUspfuZmsuVi9NY2ys61RjWWVq@EsclwrzUdXSoww4YMj9q87ijCXtMkY5/I@Qj0c3mjAHDcmUhaNg/fpR27mvumtldfjwLfxTIcdU8cFLkma0D/DiFYZpsQyF@MKl5haK2Xw4YkoMSGW6wlrvTslllfsJf6LJ6VOGbHo3ZREqyX6dN8HVghLhK9RGUKEkCCQCsjKmoxlhFJvIpTcawtfjhl9anhDt1r0gbI7Sv5DqQ9jKw9y/Qc)
[Answer]
# [Python 3](https://docs.python.org/3/), 204 bytes
```
f=lambda a,*i:[z for b in a for c in f(a-{b},1)or[[]]for n in(0,1,2,3)for z in[c+[b[n:]+b[:n]]]if{p[2-b]+q[b*3]for b in(0,1)for p,q in zip(z,z[b or int(len(z)**.5):])if z.index(q)**2%len(z)-b+1}=={9}or i]
```
[Try it online!](https://tio.run/##VVDRbsIwDHznKyJNk5LWoLUN7VaJL7HykECrRYIQWCdtQXx7ZwfQtrzkfL47O4nf0/sxNPM8bvb24HZWWCh8j0mMx7NwwgdhM9wyHKVdXtwVKnU8IxrDjUAN@QIV1NAoJhIRuC3RYehN6bAPxhg/XiLWS2fKE7qiMY90dmZXhBNPSD7KBAmdIM6HSe6HIJMqitVa9Ub5UaSVD7vhS56IrJ9v7aUrq@tmc3m7ssvMHGg5fYFY02praA1gQ3cHFaEONLHM1fAKLWhjgKT5DVQw3bAkmzSxjPTtjTepJl9HBWQT5RJqIc/6n/qENK2iuHXWtuTSOezXT9tB/cfFiLnqjrr7Ig@kKY2UnK76hRDxzB81yo9hkgcb5fQZ9wNYRWf@AQ "Python 3 – Try It Online")
Recursively tries every possible permutation and returns the valid ones. This is a brute-force approach and times out for the last test case. It should work in principle, though.
] |
[Question]
[
Black Box is a board game, Your task is to reveal all clues.
## What is black box
Black box is a board game with hidden atoms, Your task is given input, All atoms, reveal all clues.
## I/O
### Input
The atoms can be any 1-char that is not newline (Used for separator) Like this.
```
O....
...O.
..O..
.....
....O
```
### Output
When the code reveals all clues (See Below) the output of The given input above can be:
```
HRHH1
H 1
R H
H H
2 R
H H
H2HRH
```
or
```
[["H", "R", "H", "H", "1"], ["1", "H", "H", "R", "H"], ["H", "R", "H", "2", "H"], ["H", "2", "H", "R", "H"]]
```
Ignore the number, This doesn't mean anything, the number must be non-unique and must work with >9 detours
## Task
### Hit
Atoms interact with rays in three ways. A direct impact on an atom by a ray is a "hit".
```
.........
.........
.O.....O.
.........
.........
...O.....H 1
.........
.......O.
```
Thus, ray 1 fired into the box configuration at left strikes an atom directly, generating a "hit", designated by an "H". A ray which hits an atom does not emerge from the box.
### Deflection
The interaction resulting from a ray which does not actually hit an atom, but which passes directly to one side of the ball is called a "deflection". The angle of deflection for this ray/atom interaction is 90 degrees. Ray 2 is deflected by the atom at left, exiting the box as shown.
```
2
.........
.........
.O.....O.
.........
.........2
...O.....
.........
.......O.
```
#### Explanation in ASCII art:
```
2
....^....
....^....
.O..^..O.
....^....
....\<<<<2
...O.....
.........
.......O.
```
### Reflection
The final type of interaction of a ray with an atom is a "reflection", designated by an "R". This occurs in two circumstances. If an atom is at the edge of the grid, any ray which is aimed into the grid directly beside it causes a reflection.
```
.........
.........
.O.....O.
.........
.........
...O.....
.........
.......O.
RHR
354
```
Rays 3 and 4 at left would each generate a reflection, due to the atom at the edge. Ray 5 would be a hit on the atom.
### Double deflection
The other circumstance leading to a reflection is when two deflections cancel out. In the grid at left, ray 6 results in a reflection due to its interaction with the atoms in the grid.
```
6
R
.....
..O.O
.....
.....
.....
```
### Detour
Rays that don't result in hits or reflections are called "detours". These may be single or multiple deflections, or misses. A detour has an entry and an exit location, while hits and reflections only have an entry location for a hit, and a single entry/exit location for a reflection.
```
8 8
.........
.........
.O.....O.
.........9
.........
...O.....
.........9
.......O.
```
Of course, more complex situations result when these behaviors interact. Ray 8 results in two deflections, as does ray 9.
Some rays travel a twisted course, like ray 1 at left.
```
.........
.........
.O.....O.
.........
1.........
...O.....
.........
.......O.
1
```
Notice that this complex set of five deflections above looks exactly like a single deflection, as shown by ray 2 at left. Things are not always as simple as they seem within a black box.
```
.........
.........
.........
.....O...
1.........
.........
.........
.........
1
```
Reflections and hits can be more complex, too. Ray 2 gets deflected by the first atom, reflected by the next two atoms and again deflected by the original atom, yielding a reflection.
```
.O...
.....R 2
.....
.O.O.
.....
```
Ray 3 below gets deflected by the first atom, then by the second atom, and then hits the third atom, yielding a hit.
```
...O.
O....
.....
3 H.....
...O.
```
#### Explanation in ASCII Art:
```
8 8
..v...^..
..\>>>/.
.O.....O.
......../9
........v
...O....v
........\9
.......O.
.........
.........
.O.....O.
../>>>\..
1>>/...v..
...O..v..
..../</..
....v..O.
1
.........
.........
.........
.....O...
1>>>>\....
....v....
....v....
....v....
1
```
## Test cases
```
O....
...O.
..O..
.....
....O
->
HRHH1
H 1
R H
H H
2 R
H H
H2HRH
O
->
H
H H
H
OOO
O O
OOO
->
HHH
H H
H H
H H
HHH
..O..
O...O
..O..
->
HRHRH
R R
H H
R R
HRHRH
...
...
...
->
123
4 4
5 5
6 6
123
....
O...
...O
....
->
H1HH
R 1
H R
R H
2 R
HH2H
```
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~171~~ 141 bytes
```
≔⁺⁺ψ⭆θ ψη⊞υηWS⊞υ⪫ ιυη≔⁰ζF⊕LυFLη«Jκι¿⁼ KK«≔⁻⁶⊗⌕KVωδM✳δW⁼KK.«≔⊗E²№KD²✳⁺δ⁺²×⁴μOε≧⁺⊗⌈εδM✳δ≧⁻↨ε±¹δ»≡KKO≔Hδ¿∧⁼ⅈκ⁼ⅉι≔Rδ«≔Iζδδ≦⊕ζ»Jκιδ»»J¹¦¹UOLθ⊖Lυ
```
[Try it online!](https://tio.run/##dVNRb5swEH6GX3HiyZZctEzTHpqnrtm0VUsTddW0PrpwAStgErCbtVN@OztjE7KqQzrwne@@z9/5yErZZo2s@v6q61Sh2bqynX89C/hhWqWLpdyxvYAEEs4FPJOVfB6vbVcy69eHUlUI7JveWeNrGOcwZtw0SrMEIBGguKukBMPsaeUQAvs7AS/kbZrWoWUt1qgN5uw76sIQGCfYYTMESvL/xNGNrXf3Dds6gnkcqQ2wz3srq45oiXWNuGXcp0aBaak0afwoYNHYx4ooviidM5f5s9G3aGupNSOpB@5E5w42WjZPyBaqxcyoRrOcD9EgPhB6LupWmgTCkXEkcu18L@C6saTdpU@IFJ6c4RJyOr370s69qrFjHwTUnA@HSlbJ8MXhGBHheqY7VZRmKJ/ULeVvVdua4aTmP3Je4wyNEvBJdshQwC0W0iCbTThHsu6gTFZCUO91Z1ThzngJoQHJ12SsyXEjbWUuwV3VFTU@dO@Xa92WLPgPzlfu6kaMuxNGhBURDB0eW3wtO8NeJoWRH7DROyk7ny0/cZHX4ezVMJ1jHONjHLZnAmYUWj1WDU17GMc9US/wrbH1v8@879NV6p84TU8rH1v9Eztfrd6IhYr@4qn6Cw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation:
```
≔⁺⁺ψ⭆θ ψη⊞υη
```
Create a header row.
```
WS⊞υ⪫ ι
```
Read the grid and pad the sides.
```
υη
```
Output the grid and a footer.
```
≔⁰ζ
```
Start with no rays.
```
F⊕LυFLη«
```
Loop over all of the squares.
```
Jκι¿⁼ KK«
```
Is this an entry point?
```
≔⁻⁶⊗⌕KVωδ
```
Work out which direction the ray leaves this entry point.
```
M✳δ
```
Move onto the grid.
```
W⁼KK.«
```
Repeat while the current cell is empty.
```
≔⊗E²№KD²✳⁺δ⁺²×⁴μOε
```
Check the neighbours for `O`s.
```
≧⁺⊗⌈εδ
```
If there are any then reverse direction so that the next move takes a step back. (This also handles the case of an `O` at the edge of the grid.)
```
M✳δ
```
Take one step.
```
≧⁻↨ε±¹δ
```
Adjust the direction if there was only one adjacent `O`.
```
»≡KKO≔Hδ
```
Did we hit an atom?
```
¿∧⁼ⅈκ⁼ⅉι≔Rδ
```
Were we reflected?
```
«≔Iζδδ≦⊕ζ»
```
Otherwise, output the next ray number at the exit point we just reached.
```
Jκιδ
```
Output the result of the ray at its entry point.
```
»»J¹¦¹UOLθ⊖Lυ
```
Clear out the grid.
[Answer]
# Python3, 935 bytes:
```
E=enumerate
S=lambda b,x:(x+1==len(b)or x==0)*[1,-1][x>0]
def F(b,C,v,x,y,q,w,c=0):
if int==type(b[x][y])and c:b[x][y]=[v,'R'][C==(x,y)];return
if b[x][y]=='O':b[C[0]][C[1]]='H';return
T=[]
for i in[1,-1]:
X=x+(i*(q==0)+(q!=0)*q);Y=y+(i*(w==0)+(w!=0)*w)
if X>=0 and Y>=0:
try:T+=[i]*(b[X][Y]=='O')
except:1
T*=b[x+q][y+w]=='.'
if not c and T:b[C[0]][C[1]]='R';return
if T:
Q,W=0,0
if len(T)==2:Q=q-1*(q!=0)*q;W=w-1*(w!=0)*w
else:Q=(q==0)*T[0]*-1;W=(w==0)*T[0]*-1
F(b,C,v,x,y,Q,W,c+1);return
F(b,C,v,x+q,y+w,q,w,c+1)
def g(b):
for x,j in E(b):
for y,k in E(j):
if k and type(k)==int:F(b,t:=(x,y),b[x][y],*t,S(b,x),S(b[0],y))
return b
K=lambda b:'\n'.join(''.join(map(str,[[j,' '][y in[0,len(a)-1]]for y,j in E(a)]if i in[0,len(b)-1]else[[' ',j][y in[0,len(a)-1]]for y,j in E(a)]))for i,a in E(b))
f=lambda b,c=0:K(g((A:=[[0]+[(c:=c+1)for _ in b[0]]+[0]])+[[(M:=(c:=c+1))]+i+[M]for i in b]+eval(str(A))))
```
[Try it online!](https://tio.run/##jVPvT6QwEP18/BU9v9BC3YA/kgumJsZ4ucTcEXUTNb3GwG7XY0Vgobrw13szLbt6Zj8cCVBe30zfmxmawfypq8NvTfv2diF09fKs28xo70aU2XM@z0jO@4T2YSxEqSuas7olvRARC2TM92Ml@9NIeXO9IN9pzs/5K@/5wFd8zWdASjxSLEhRGSHM0Giay17JQbGsmpNZMn4J@cr9a1/JcyEoRDN10mrz0lY2eEMSfupDxLmMFDBlrJTwf/hb5lRI5ZEFqCvgPKcNTid3og9pEdAVag7p6itKX7GTezFYfO3wtcXXDCLgzLtTERHUeA8LzEJMOyTTUMhCBWDiTsl7pwgDiO5nujFJDCoCAXrDFSgO18iY@NZEVRsysxmnnz1c@x/dTvG0K34rIh45LVj1KRPiILkSq/042Fg4uRVr/ByVA1mXnQaSsxpM4ZBgPwaa87gBgPixU3AWn4Ux24rYboYrDiZcK4Fge/wIA5C4Mvd8CYUmFw6x0MCfHLS0EKp/sqZt75/ABExCggeYxHWaj93lgeE3gPcMXyAU9qC0ThPJvcvtNCb@78qfLOuiov74fs4a2pmWS7nkPoE5GnACIo6VyxjMgXLiRr0ZUziT75wcOVg8KSGcL/8jAWN20ni2KQHzFu8/DEx@ckkfKT1LhAQzoaSzRGARMeoBY9Aj4PBgoZT0J9RjpDAVFqH8qTajTHIV6tesRIv0jMH11om9vb10ApcHd4rP1K3HZwr7Xhdbml0e2GWaeimBO3XgIYIuFJOlLo3dOnJbNhveFjweQUf3xhC3icNh6oe8zto5nUP7v4y9k2XRGVqw7a9JFkVpdEt/1ZXmZD7pmrIwFLsK1j2bqKvLF1PU1T@JFvRDfhZigNe0MFB0S@@gDZ@heAd2sAM73IEd7cCOof5/AQ)
] |
[Question]
[
In [Conway's Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life), there is an infinite square grid of cells, each of which is alive or dead. The pattern changes each "generation". A dead cell with exactly 3 live neighbors (orthogonal or diagonal) becomes a live cell. A live cell only lives to the next generation if it has 2 or 3 live neighbors. These simple rules lead to very complex behaviors. The most well-known pattern is the [glider](https://en.wikipedia.org/wiki/Glider_(Conway%27s_Life)), a pattern that moves diagonally one cell every 4 generations and looks like this:

## The Challenge
Your task is to create two patterns which will eventually result in an empty board when by themselves (a.k.a. a diehard), but when combined in a certain non-bordering and non-overlapping arrangement, eventually spawn a single glider and nothing else.
## Rules and Scoring
* Each of the lone diehards must fit all live cells within a 100x100 cell box and may not contain more than 100 live cells.
* The combination glider synthesizer must contain both diehards such that their bounding boxes surrounding all live cells are separated by at least one dead cell.
* It does not matter which direction the single glider is facing
* Your score is the sum of the number of generations it takes to reach an empty board from the initial states for the diehards, plus the number of generations it takes to reach a state where there is exactly one glider and nothing else (i.e. there are *exactly* 5 live cells on the board in a glider pattern) for the combined glider synthesizer. **Highest score wins**.
[Answer]
# Total Score ~~669~~ ~~683~~ 753
**[Pattern 1](http://copy.sh/life/?gist=394688150f8f97c60a21bfc3fe4e3798) (379 steps)**:
```
x = 100, y = 94
97b2o$96bo2bo$97bobo$98bo$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$3o$2bo$bo!
```
**[Pattern 2](http://copy.sh/life/?gist=2709d20f0ab706a8c3831505c7638655) (126 steps)**:
```
x = 11, y = 2
o5b2obo$3bo$2b2o2bo2b2o!
```
**[Pattern 1 + Pattern 2](http://copy.sh/life/?gist=5f0ae3474489bf1e6861ac7985f41099) (248 steps)**:
```
x = 112, y = 94
97b2o$96bo2bo$97bobo$98bo2bo5b2obo$104bo$103b2o2bo2b2o$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$3o$2bo$bo!
```
Pattern 1 is a self-destructing glider + loaf combination where the glider and loaf are spaced as far apart as possible.
Pattern 2 is the result of searching for random disappearing patterns which can be placed next to pattern 1 to destroy the loaf, giving a valid solution to the puzzle. I generated a large number and took the one with the best score.
I'm sure its possible to do better by adding an independent diehard to the far corner of pattern 2 (or even pattern 1), but I'm done for now.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/186118/edit).
Closed 4 years ago.
[Improve this question](/posts/186118/edit)
Your task is to modify the original Plan 9 cat tool for UNIX, in order to make it a fully turing complete language interpreter. You may make use of [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) and the backspace character (\x08) to aid in this.
You must submit:
* A modified version of the Plan 9 cat tool
* A hexdump of the turing machine that can be run like so: `cat turing_machine` where `turing_machine` is the file you wrote.
Your score is the number of bytes you changed in the Plan 9 cat source code (where replacing a character counts as two bytes because you have to remove it and then replace it).
Here is the Plan 9 cat source code, taken from [here](https://github.com/brho/plan9/blob/89d43d2262ad43eb4b26c2a8d6a27cfeddb33828/sys/src/cmd/cat.c).
```
#include <u.h>
#include <libc.h>
void
cat(int f, char *s)
{
char buf[8192];
long n;
while((n=read(f, buf, (long)sizeof buf))>0)
if(write(1, buf, n)!=n)
sysfatal("write error copying %s: %r", s);
if(n < 0)
sysfatal("error reading %s: %r", s);
}
void
main(int argc, char *argv[])
{
int f, i;
argv0 = "cat";
if(argc == 1)
cat(0, "<stdin>");
else for(i=1; i<argc; i++){
f = open(argv[i], OREAD);
if(f < 0)
sysfatal("can't open %s: %r", argv[i]);
else{
cat(f, argv[i]);
close(f);
}
}
exits(0);
}
```
The headers in the above source are [u.h](https://github.com/brho/plan9/blob/master/amd64/include/u.h) and [libc.h](https://github.com/brho/plan9/blob/master/sys/include/libc.h). Your code must conform to the C99 standard.
[Answer]
# ~~266~~ ~~256~~ ~~250~~ ~~245~~ 149 bytes (probably)
Thanks to @someone for suggesting using a cyclic tag system (originally I was using a modified version of Brainfuck).
Real computers aren't actually Turing-complete, because they have a finite amount of memory, whereas a Turing-machine has an infinite amount of memory. This is an implementation of a [cyclic tag system](https://en.wikipedia.org/wiki/Tag_system#Cyclic_tag_systems) with 9999 bytes of memory (although you could very easily change that), and with an initial word of `1` (I'm not entirely sure if cyclic tag systems with a fixed initial word are Turing-complete, but they probably are). The length of the program must be ≤8192, in this format:
```
00 (the first byte is ignored)
01 01 02 00 (first rule: 001 (null character to mark end))
02 02 02 01 02 00 (second rule: 11101)
03 (marks end of program)
```
There is no I/O. The added code should be C99-compliant (provided the input code doesn't use more than 9999 bytes of memory at once), but I'm pretty sure [you can't (portably) declare `main` as `void` in C99](http://c-faq.com/ansi/voidmain.html).
```
#include <u.h>
#include <libc.h>
void
cat(int f, char *s)
{
char buf[8192],m[9999];
long n;
while((n=read(f, buf, (long)sizeof buf))>0){char m[9999],*M=m+9998,*s=m,*e=m+1,*i=buf;*m=2;m[1]=0;do{for(i++;*i;i++){if(*i>2)i=buf+1;if(*s>1){*e++=*i;if(e>M)e=s;}}if(++s>M)s=m;}while(*s);
/*if(write(1, buf, n)!=n)
sysfatal("write error copying %s: %r");*/}
if(n < 0)
sysfatal("error reading %s: %r", s);
}
void
main(int argc, char *argv[])
{
int f, i;
argv0 = "cat";
if(argc == 1)
cat(0, "<stdin>");
else for(i=1; i<argc; i++){
f = open(argv[i], OREAD);
if(f < 0)
sysfatal("can't open %s: %r", argv[i]);
else{
cat(f, argv[i]);
close(f);
}
}
exits(0);
}
```
Slightly de-golfed, and printing each step:
```
#include <u.h>
#include <libc.h>
void
cat(int f, char *s)
{
char buf[8192];
size_t n;
while((n=read(f, buf, (long)sizeof buf))>0) {
char mem[9999];
*mem=2;mem[1]=0;
char* mem_end = &mem[9998];
char*start=mem,*end=mem+1,*i=buf;
do {
for (char* p = start; p < end; p++) {
printf("%d",*p - 1);
}
printf("\n");
for (i++;*i;i++) {
if(*i>2)i = buf+1;
if (*start > 1){
*end++=*i;
if (end > mem_end)
end = mem;
}
}
if (++start>mem_end)start=mem;
} while (*start);
/*if(write(1, buf, n)!=n)
sysfatal("write error copying %s: %r");*/
}
if(n < 0)
sysfatal("error reading %s: %r", s);
}
void
main(int argc, char *argv[])
{
int f, i;
argv0 = "cat";
if(argc == 1)
cat(0, "<stdin>");
else for(i=1; i<argc; i++){
f = open(argv[i], OREAD);
if(f < 0)
sysfatal("can't open %s: %r", argv[i]);
else{
cat(f, argv[i]);
close(f);
}
}
exits(0);
}
```
The following Python script converts any cyclic tag system into code which is accepted by this program:
```
productions = [[0,0,1],
[0],
[0,0],
[0,1,1,1]]
f = open("turing_machine","w")
f.write("\0") # First byte is ignored
for production in productions:
for c in production:
f.write(chr(c+1))
f.write("\0")
f.write("\3")
f.close()
```
When you run the output of this program with the de-golfed version, you get:
```
1
001
01
1
0111
111
110
1000
0000111
000111
00111
0111
111
11001
10010
001000
01000
1000
0000
000
00
0
```
] |
[Question]
[
Matlab has a useful command for visualizing data: [`plot`](https://uk.mathworks.com/help/matlab/ref/plot.html). It draws data points using "markers" in 2-D space, connecting them with lines; however, for this challenge, let's ignore the lines and use only markers. In fact, only one marker.
Input: one of Matlab's marker symbols: `.` `o` `x` `+` `*` `s` `d` `v` `^` `<` `>` `p` `h`
Output: corresponding image for that marker, which is one of the following 13 icons: [](https://i.stack.imgur.com/9VmfO.png)
To make it clearer, here are the same icons enlarged, so the pixels can be easily seen:
[](https://i.stack.imgur.com/6h4yk.png)
* Take the input as a string, a `char`, an integer ASCII code, or anything equivalent
* Produce the output by displaying the image, returning it as a function's return value, saving it to a file, etc
* The image should have pixels of two different colours in it. I used blue on white, because this is what Matlab uses by default, but any other colour scheme is OK, e.g. white on black.
* The image can have padding of background colour of any size
* The pixels can be enlarged by any integer ratio, e.g. instead of the original 11-by-9 image for the triangle, you can output a 110-by-72 image, in which 10-by-8 blocks represent the original pixels
+ As a corollary of the above, you can output text with glyphs like `█` instead of an image, if you can print this text properly (i.e. without gaps between glyphs) on the same system which runs the code
---
For quick reference, here are the bitmaps for each input:
* `.`
```
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 1 1 1 0 0 0 0
0 0 0 1 1 1 1 1 0 0 0
0 0 0 0 1 1 1 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
```
* `o`
```
0 0 0 0 1 1 1 0 0 0 0
0 0 1 1 0 0 0 1 1 0 0
0 0 1 0 0 0 0 0 1 0 0
0 1 0 0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 0 1 0 0
0 0 1 1 0 0 0 1 1 0 0
0 0 0 0 1 1 1 0 0 0 0
```
* `x`
```
0 0 1 0 0 0 0 0 1 0 0
0 0 0 1 0 0 0 1 0 0 0
0 0 0 0 1 0 1 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 1 0 1 0 0 0 0
0 0 0 1 0 0 0 1 0 0 0
0 0 1 0 0 0 0 0 1 0 0
```
* `+`
```
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 1 1 1 1 1 1 1 1 1 0
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
```
* `*`
```
0 0 0 0 0 1 0 0 0 0 0
0 0 1 0 0 1 0 0 1 0 0
0 0 0 1 0 1 0 1 0 0 0
0 0 0 0 1 1 1 0 0 0 0
0 1 1 1 1 1 1 1 1 1 0
0 0 0 0 1 1 1 0 0 0 0
0 0 0 1 0 1 0 1 0 0 0
0 0 1 0 0 1 0 0 1 0 0
0 0 0 0 0 1 0 0 0 0 0
```
* `s`
```
0 1 1 1 1 1 1 1 1 1 0
0 1 0 0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0 0 1 0
0 1 1 1 1 1 1 1 1 1 0
```
* `d`
```
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 1 0 1 0 0 0 0
0 0 0 1 0 0 0 1 0 0 0
0 0 0 1 0 0 0 1 0 0 0
0 0 1 0 0 0 0 0 1 0 0
0 1 0 0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 0 1 0 0
0 0 0 1 0 0 0 1 0 0 0
0 0 0 1 0 0 0 1 0 0 0
0 0 0 0 1 0 1 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
```
* `v`
```
1 1 1 1 1 1 1 1 1 1 1
0 1 0 0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 1 0 0 0
0 0 0 0 1 0 1 0 0 0 0
0 0 0 0 1 0 1 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
```
* `^`
```
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 1 0 1 0 0 0 0
0 0 0 0 1 0 1 0 0 0 0
0 0 0 1 0 0 0 1 0 0 0
0 0 1 0 0 0 0 1 0 0 0
0 0 1 0 0 0 0 0 1 0 0
0 1 0 0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0 0 1 0
1 1 1 1 1 1 1 1 1 1 1
```
* `<`
```
0 0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 1 1 1 0 0
0 0 0 0 1 1 0 0 1 0 0
0 0 0 1 0 0 0 0 1 0 0
0 1 1 0 0 0 0 0 1 0 0
1 0 0 0 0 0 0 0 1 0 0
0 1 1 0 0 0 0 0 1 0 0
0 0 0 1 1 0 0 0 1 0 0
0 0 0 0 0 1 0 0 1 0 0
0 0 0 0 0 0 1 1 1 0 0
0 0 0 0 0 0 0 0 1 0 0
```
* `>`
```
0 0 1 0 0 0 0 0 0 0 0
0 0 1 1 1 0 0 0 0 0 0
0 0 1 0 0 1 1 0 0 0 0
0 0 1 0 0 0 0 1 0 0 0
0 0 1 0 0 0 0 0 1 1 0
0 0 1 0 0 0 0 0 0 0 1
0 0 1 0 0 0 0 0 1 1 0
0 0 1 0 0 0 1 1 0 0 0
0 0 1 0 0 1 0 0 0 0 0
0 0 1 1 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0
```
* `p`
```
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 1 1 0 0 0 0 0
0 1 1 1 1 1 1 1 1 0 0
0 0 1 0 0 0 0 1 0 0 0
0 0 0 1 0 0 1 0 0 0 0
0 0 0 1 0 1 1 0 0 0 0
0 0 1 1 1 0 1 1 0 0 0
0 0 1 0 0 0 0 1 0 0 0
```
* `h`
```
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 1 1 0 0 0 0 0
0 0 1 1 1 0 1 1 1 0 0
0 0 1 0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 1 0 0 0
0 0 1 0 0 0 0 1 0 0 0
0 0 1 1 1 0 1 1 1 0 0
0 0 0 0 1 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
```
Any padding with zeros which exists in these bitmaps is optional. So e.g. for the `.` input, a 5x5 image would be sufficient.
[Answer]
# [Node.js](https://nodejs.org), 310 bytes
Takes the ASCII code of the symbol as input.
```
n=>Buffer(`~A<<13)$$"~"6+'?'+6"~'81<<<18'~/973202459/~"$$)31<<A~"%;3)3;%"~~ !&(=@=-#! ~""""?""""~"%>3*,:3~~"$))1<1))$"~"'.'"~?<<<<<<<?~1)$"$)1`.split`~`[n*7%86%17]).map(c=>s+=(g=n=>n--?' █'[[...Buffer('$8$$L0$,4$(8(4T(!#""0($,|T8$F'),290,280,34,38,1051].map(c=>p+=c-32,p=0)[c-32]>>n&1]+g(n):`
`)(11),s='')&&s
```
[Try it online!](https://tio.run/##NVHNUoMwEL77FDQNJCkhJYS2tCVgdfTksbeKA5OWVqcCA7XjwcnZJ/ABfZEaRv1mdmf/v93Zl@JcdKp9bk5eVW93l1JeKpncvJXlrsW5XsUxFwRCoMHURSlyp0CjiMcmHCE9ns9E4AfhZD7WAEIiTGKlgb0URCxtoLU1cLC8lt5wYGlgkPbKFCRiRBdCmyZCeMwJ6QkQQ0Cn8S9SzU0QEp6zrjk@n3Kdb6rRzI6mNp9lhL0WDVYy6VyJ99JsXHleiqzvr0@02TDG/g5AMILwwYc0hDjC4RoPhgD4GNKPdQTvEaHB3KdB5FMRUhFR7k949j@6caXyREAb6ZNNb2VJUjk8c/e4Iov8KieYc0I7iRBxnO6y7HkBq9/dUbc9P8VJcwAZK@v2rlAHrCyZWKquuvq4Y8d6jxFAlmspIwgsHqveKbFi6lC0t@YRqxMmBpcf "JavaScript (Node.js) – Try It Online")
### How?
All symbols can be generated by combining \$34\$ distinct binary patterns.
Each pattern is identified with a character \$C\$ (from space to "A").
The patterns are ordered from lowest to highest, using their decimal representation \$N\$. What's actually stored is the difference \$d\$ between two consecutive patterns, plus \$32\$.
```
ID | C | pattern | N | d | d+32
----+-----+-------------+------+------+------
0 | ` ` | 00000000100 | 4 | 4 | 36
1 | `!` | 00000011100 | 28 | 24 | 56
2 | `"` | 00000100000 | 32 | 4 | 36
3 | `#` | 00000100100 | 36 | 4 | 36
4 | `$` | 00001010000 | 80 | 44 | 76
5 | `%` | 00001100000 | 96 | 16 | 48
6 | `&` | 00001100100 | 100 | 4 | 36
7 | `'` | 00001110000 | 112 | 12 | 44
8 | `(` | 00010000100 | 132 | 20 | 52
9 | `)` | 00010001000 | 136 | 4 | 36
10 | `*` | 00010010000 | 144 | 8 | 40
11 | `+` | 00010101000 | 168 | 24 | 56
12 | `,` | 00010110000 | 176 | 8 | 40
13 | `-` | 00011000100 | 196 | 20 | 52
14 | `.` | 00011111000 | 248 | 52 | 84
15 | `/` | 00100000000 | 256 | 8 | 40
16 | `0` | 00100000001 | 257 | 1 | 33
17 | `1` | 00100000100 | 260 | 3 | 35
18 | `2` | 00100000110 | 262 | 2 | 34
19 | `3` | 00100001000 | 264 | 2 | 34
20 | `4` | 00100011000 | 280 | 16 | 48
21 | `5` | 00100100000 | 288 | 8 | 40
22 | `6` | 00100100100 | 292 | 4 | 36
23 | `7` | 00100110000 | 304 | 12 | 44
24 | `8` | 00110001100 | 396 | 92 | 124
25 | `9` | 00111000000 | 448 | 52 | 84
26 | `:` | 00111011000 | 472 | 24 | 56
27 | `;` | 00111011100 | 476 | 4 | 36
28 | `<` | 01000000010 | 514 | 38 | 70
29 | `=` | 01100000100 | 772 | 258 | 290
30 | `>` | 01111111100 | 1020 | 248 | 280
31 | `?` | 01111111110 | 1022 | 2 | 34
32 | `@` | 10000000100 | 1028 | 6 | 38
33 | `A` | 11111111111 | 2047 | 1019 | 1051
```
The 29 first values \$d+32\$ can be directly converted to ASCII characters and stored as a Buffer. The last 5 ones are stored as number literals.
```
[...Buffer('$8$$L0$,4$(8(4T(!#""0($,|T8$F'),290,280,34,38,1051]
```
Using the characters \$C\$ defined above, we can encode each symbol as a string.
*Example:*
```
..█........ 00100000000 --> '/'
..███...... 00111000000 --> '9'
..█..██.... 00100110000 --> '7'
..█....█... 00100001000 --> '3'
..█.....██. 00100000110 --> '2'
..█.......█ --> 00100000001 --> '0' --> '/973202459/'
..█.....██. 00100000110 --> '2'
..█...██... 00100011000 --> '4'
..█..█..... 00100100000 --> '5'
..███...... 00111000000 --> '9'
..█........ 00100000000 --> '/'
```
All symbols are stored in a single string, delimited with `~`. We use a hash function to convert the input ASCII code into the position of the symbol in the list.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~163~~ ~~154~~ 152 bytes
```
≔█η≡θo«G→↘→²η‖O↘¬»d«G↘³↓²↘³η‖O¬»h«GH↖↑→→↑↗↓↘→→↙↓²η‖O↓».GX³ηpG↑²↙⁴↖²→⁸↙³↓³→²↓²↖³↙²←³↓²↗²↑³ηsB⁹η¿№x+*θ«F¬⁼θ+PX×⁴ηF¬⁼θxP+×⁵η»«GH←←←←←↘↓↘↓↘↘↓↘²η‖O⟲⊗⌕v>^<θ
```
[Try it online!](https://tio.run/##fVJLTsMwFFwnp7C8cmjoIi0SBIQEFMSCnyoqsUIKidNYMnESO20Q6p4TcApOwVG4SHC@jUPKyk/vM2/eeNzASVzm0Dw/45wsQwR/Pj@gCQLjWOdrItwAoNgA77rrcAwgg7aMtQdG35YsRPacLANhAnvG1mET169VgWhz7FPsivsVTqgTIaX1@0t2bGpsr4fdaZzUK0rUXmFwiQIcKMDXjFK2RvYiusF@QWIRbUm3b5lcRN37hs9UJKgRW6o7BeiwG0t27c1Ze1JVjLrFgpOlbJqWJKvY2nI5VJq24k2U3@ko2mBMlMGi0oewurJYtVAKZS4pn7MMHVVJD/tOSoWta8QH6IKloUAwG@1Jj8VGYSxN81kC0B0T6DJOHcpRbAI4goas3spJEiVEzthPJngkr5ijaQFcCDs4mP0ZHDWDB83gRtcwlVyL5T1X1D/439M1wYAvdqR2lxuf9I1S5ZhwBEYzlr5Q7KErEnoIrk6fTyr9ymM2eT7O91f0Fw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔█η
```
Get the `█` character into a variable. As @ASCII-only explains, a properly encoded Charcoal file would use three bytes to express this character, so it needs to be in a variable as it gets used a lot. (But it's still 2 bytes shorter than the previous approach.)
```
≡θ
```
Use a switch statement for the six easy characters.
```
o«G→↘→²η‖O↘¬»
```
Handle the `o` by drawing one eighth of the figure and mirroring it three times.
```
d«G↘³↓²↘³η‖O¬»
```
Handle the `d` by drawing one quarter of the figure and mirroring it twice.
```
h«GH↖↑→→↑↗↓↘→→↙↓²η‖O↓»
```
Handle the `h` by drawing the top half and mirroring it.
```
.GX³η
```
Handle the `.` by drawing a diamond.
```
pG↑²↙⁴↖²→⁸↙³↓³→²↓²↖³↙²←³↓²↗²↑³η
```
Handle the `p` by drawing it manually.
```
sB⁹η
```
Handle the `s` by drawing a hollow rectangle. (This one is the last of the six because `Box` can take 3 parameters but the following `¿` isn't legal as a parameter.)
```
¿№x+*θ«F¬⁼θ+PX×⁴ηF¬⁼θxP+×⁵η»
```
Handle the `x`, `+` and `*`, the latter by overlapping the former.
```
«GH←←←←←↘↓↘↓↘↘↓↘²η‖O⟲⊗⌕v>^<θ
```
Draw the left half of the `v`, then mirror it, then rotate it if the character happens to be `>`, `^` or `<`.
[Answer]
# MATL, 9 bytes
```
1w&XG7lZG
```
Cheating? Maybe. Try it on [MATL Online](https://matl.io/?code=1w%26XG7lZG&inputs=%27.%27&version=20.10.0).
Literal translation of the MATLAB code `plot(1,input(''));axis off` (26 bytes). The online version compresses the image, but on a local machine it will simply use the MATLAB plot defaults.
[Answer]
# Python, 58 bytes
```
from matplotlib.pyplot import*
plot(0,input())
axis('off')
```
Fun to take advantage of matplotlib doing all the heavy lifting.
] |
[Question]
[
*(thanks to @JonathanFrech for the title)*
## Challenge
Write a program or function that, given a collection of positive integers \$S\$ and a positive integer \$n\$, finds as many non-overlapping subcollections \$T\_1, T\_2, ..., T\_k\$ of \$S\$ as possible, such that the sum of every \$T\_m\$ is equal to \$n\$.
### Example
Given \$S=\lbrace1,1,2,2,3,3,3,5,6,8\rbrace\$ and \$n=6\$, you could take the following subcollections to get \$k=3\$:
* \$T\_1=\lbrace1,1,2,2\rbrace\$
* \$T\_2=\lbrace3,3\rbrace\$
* \$T\_3=\lbrace6\rbrace\$
And the remaining elements \$\lbrace3,5,8\rbrace\$ are not used. However, there is a way to get \$k=4\$ separate subcollections:
* \$T\_1=\lbrace1,2,3\rbrace\$
* \$T\_2=\lbrace1,5\rbrace\$
* \$T\_3=\lbrace3,3\rbrace\$
* \$T\_4=\lbrace6\rbrace\$
This leaves \$\lbrace2,8\rbrace\$ unused. There is no way to do this with 5 subcollections1, so \$k=4\$ for this example.
### Input
Input will be a collection of positive integers \$S\$, and a positive integer \$n\$. \$S\$ may be taken in any reasonable format: a comma- or newline-separated string, an actual array/list, etc. You may assume that \$S\$ is sorted (if your input format has a defined order).
### Output
The output may be either:
1. the maximal number of subcollections \$k\$; or
2. any collection which has \$k\$ items (e.g., the list of subcollections \$T\$ itself), in any reasonable format.
Note that there is not guaranteed to be any subcollections with sum \$n\$ (i.e. some inputs will output `0`, `[]`, etc.)
### Test cases
```
n, S -> k
1, [1] -> 1
1, [2] -> 0
2, [1] -> 0
1, [1, 1] -> 2
2, [1, 1, 1] -> 1
3, [1, 1, 2, 2] -> 2
9, [1, 1, 3, 3, 5, 5, 7] -> 2
9, [1, 1, 3, 3, 5, 7, 7] -> 1
8, [1, 1, 2, 3, 4, 6, 6, 6] -> 2
6, [1, 1, 2, 2, 3, 3, 3, 5, 6, 8] -> 4
13, [2, 2, 2, 2, 3, 3, 4, 5, 5, 6, 8, 9, 9, 11, 12] -> 5
22, [1, 1, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 7, 7, 7, 8, 9, 9, 10, 13, 14, 14, 17, 18, 18, 21] -> 10
```
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **the shortest program in bytes in each language wins**. Good luck!
---
1. Mini-proof: the \$8\$ is obviously useless, but when you remove it, the total sum of \$S\$ becomes \$26\$; therefore, it can only contain up to \$4\$ non-overlapping subcollections whose sums are \$6\$.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17 11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 Thanks to Dennis (use count to remove the need to tie atoms together with any [quick](https://github.com/DennisMitchell/jellylanguage/wiki/Quicks))
```
Œ!ŒṖ€§Ẏċ€Ṁ
```
A dyadic link accepting a list and an integer which yields the maximal count, \$k\$.
**[Try it online!](https://tio.run/##y0rNyan8///oJMWjkx7unPaoac2h5Q939R3pBrIe7mz4//9/tKGOoY4REBrrmOgYx/43AQA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///oJMWjkx7unPaoac2h5Q939R3pBrIe7mz4f3i5gz6Q@f9/dLShjkK0YWwslw6YZQRmGaGIAbEhQhjIgfGN4XygDESnJVzIGIxMwcgcl5w5RC4WAA "Jelly – Try It Online") -- it's too slow for the larger test cases :(
### How?
```
Œ!ŒṖ€§Ẏċ€Ṁ - Link: list L, integer I
Œ! - all permutations
ŒṖ€ - for €ach: all partitions (all ways to slice up each permutation)
§ - sum each (vectorises at depth 1, so this gets the sums of the parts of
- each of the partitions for each permutation)
Ẏ - tighten (to get a list of the sums of the parts of each possible partition)
ċ€ - for €ach count occurrences of I
Ṁ - maximum
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
Œ!ŒṖ€ẎŒP€Ẏ§;EɗƇẈṀ
```
[Try it online!](https://tio.run/##y0rNyan8///oJMWjkx7unPaoac3DXX1HJwVAGIeWW7uenH6s/eGujoc7G/7//x9tqKMAREZAFPvfGAA "Jelly – Try It Online")
Outputs \$k\$ if there is a \$T\$, \$0\$ otherwise. Very slow.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
œ€.œOQOZ
```
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/174921/52210).
[Try it online.](https://tio.run/##yy9OTMpM/f//6ORHTWv0jk72D/SP@v8/2lDHCAiNgdAklssEAA) NOTE: Extremely slow, so times out for most test cases beyond the size of 6..
**Explanation:**
```
œ # All permutations of the (implicit) input-list
€.œ # Take all partitions of each permutation
O # Sum each
Q # Check for each if it's equal to the (implicit) integer-input
O # Then sum each
Z # And take the maximum (implicitly flattens the list of lists)
# (and output implicitly)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 115 bytes
```
k=>f=([i,...s])=>i?Math.max(...[i,...s].map((_,j)=>(e[j]=~~e[j]+i,_=f(s),e[j]-=i,_))):e.filter(_=>_==k).length;e=[]
```
[Try it online!](https://tio.run/##dY3BCoJAEIbvPYXHGVqX1CJMxm7eegIREVt11VRciU6@uq1LdYiCbxn@nY9/6uyeqXyUw2R3/VUsES0NhQVBLBnnXCVIoTxfsqnit@wB@uu90HkASFmtDRBxndA8r2MrWUoFKGRrsklHRDwJXsh2EiOkFKZEDfJWdOVUBYLiZAk2ed@pvhW87UuIwEOIHWZpXE2C@C34H8EzHAzHP6bPrBc/BGc95pqWvWlxdvqt5ebw8gQ "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
Make an upside down triangle of **positive** integers. Every number in the triangle must be **distinct**. Each number is the **summation** of its two parents (similar to how Pascal's triangle is constructed, but upside-down). Construct it in such a way that the bottom number is **minimized**.
For example, for input `n = 4`, here is a possible solution:
```
4 1 2 7
5 3 9
8 12
20
```
A reversal of the top numbers, such as `7 2 1 4`, would also work.
For input `n = 5`, here is a possible solution:
```
7 2 1 4 6
9 3 5 10
12 8 15
20 23
43
```
The solution for `n = 2` is rather boring:
```
1 2
3
```
The sequence of bottom numbers is described in [OEIS A028307](http://oeis.org/A028307).
### Challenge
Given an input integer `n > 0` describing how many elements are in the first row, output the corresponding minimal triangle as explained above. Output can be as ASCII-art of the triangle, a list-of-lists or matrix, to STDOUT as one row per line, etc.
## Rules
* If applicable, you can assume that the input/output will fit in your language's native Integer type.
* The input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963).
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
!*ṗµ+ƝÐĿ€FQƑ$Ðf-ị$ÞḢ
```
[Try it online!](https://tio.run/##AS4A0f9qZWxsef//ISrhuZfCtSvGncOQxL/igqxGUcaRJMOQZi3hu4skw57huKL///8y "Jelly – Try It Online")
It's trivial to prove that there exists a solution which all elements on the first row are in range `[1,n!n]`.
Be careful as this computes an array of 10'077'696 3-element arrays for `n=3`.
---
Proof:
Let `x` be on the `k`th layer (`1 ≤ k ≤ n`, and there are `a` numbers to the left of `x`. Let `b0, b1, ..., bn-1` be the numbers on the first line.
Then:
`x = ba × (k-1 choose 0) + ba+1 × (k-1 choose 1) + ... + ba+k-1 × (k-1 choose k-1)`
It can be proven that all of the coefficients are non-negative and less than `n!` (except when `n=1`, in that case the algorithm gives correct result anyway), and two different numbers have two different set of coefficients.
So if the first line are chosen to be the powers of `n!` with exponent `0,1,2,...,n-1`, the value of each cell uniquely determines the set of coefficients, and thus is unique.
---
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
!*r1œcµ_ƝÐĿ€FQƑ$ÐfṪ
```
[Try it online!](https://tio.run/##ASkA1v9qZWxsef//ISpyMcWTY8K1X8adw5DEv@KCrEZRxpEkw5Bm4bmq////Mg "Jelly – Try It Online")
Output format: Columns, upside down.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~251~~ ~~239~~ 230 bytes
-9 bytes thanks to @Mr.Xcoder
Outputs list of lines of triangle, bottom to top.
```
def F(s,d):
if-~d==len(s):
u=sum(s,[])
if len(u)==len(set(u)):print s;g
else:
for j in range(s[d][0]):
s[d+1]=[j]
for i in s[d]:j=i-j;s[d+1]+=j,
if min(s[d+1])>=0:F(s,d+1)
i,I=1,input()
while i:F(eval(`[[i]]*I`),0);i+=1
```
[Try it online!](https://tio.run/##LY5BC8IwDIXP9lfk2LgKm@BlIx4Ff0MpKKzTlFnHuile/OszVW/v5X3Jy/Carve4XZbWd3DQybRYK@Bu826Jeh91Er@aKc03Ca1DteIOcjDjH/CTaKyHkeMEqbko8H3ystXdRwjAEcZzvHidbOts6fI9EF1UjmxwYjLHmctEHYg3ofkBBQUjgDTeOOrfDPdU1t9PiwoVmyNVhuMwTxrV88q9B5bYP869PlnLzq2PJzQlNlxQtSy7Dw "Python 2 – Try It Online")
Bruteforce-ish solution.
For all i in [1 .. ] generate all possbile triangles starting from the bottom, until one with all different numbers is found.
] |
[Question]
[
If Abe goes, then Beth and Diana go. If Beth goes, then Catherine goes. If Catherine goes, then Diana goes. If Diana goes, then Ezra goes. Only three people go. Who goes?
# Challenge
Given a list of several pairings of people, such that in each pairing the second person goes if the first person goes, and a positive integer number of people who go, determine one or all possibilities of who goes. You may output either, as long as the output is consistent.
The example above may be represented in input by `[(A,B),(A,D),(B,C),(C,D),(D,E)],3`, which can be represented as a graph visually as:
```
A -> B -> C -> D -> E
⤷-------------⤴
```
If A goes, then everyone must go, so at least 5 people go, which cannot be 3 people.
If B goes, then C, D, and E must go, so at least 4 people go, which cannot be 3 people.
Thus we are left with C, D, and E going, yielding a final output of `[C,D,E]`.
The input `[(0,1),(0,3),(1,2),(2,3),(3,4)],3` represents the same situation and is the format given in the test cases (with output `[2,3,4]`).
We assume that no people other than the people in at least one pairing should be considered. For example, there is no person `5` or `F` in this example.
# I/O
Your program/function **must** input `g`, the list of pairings which represents a directed graph, and `n`, the number of people who will go. Input `g` may be taken in any format (such as an adjacency matrix) which does not encode additional information and can encode at least **25** people to consider (the example considered 5 people).
You may also (optionally) input `p`, the list of people, and/or `c`, the number of people to consider. [List of people `p` given `g` (sorted).](https://tio.run/##y0rNyan8/98t8OHORf///4/WMNAx1NTRMNQxApJGOsZg0hRImuqYAUkzsIiZjjmQNNcx0YwFAA "Jelly – Try It Online") (append `L` to end to get number of people `c`).
Your program/function does not have to handle if:
* the integer input is greater than the number of people considered.
* the integer input is not positive
* repeat pairings
* reflexive pairings (e.g. `(A,A)` or `(0,0)`)
* impossible situations (e.g. `[(A,B),(B,A)],1`)
The output should be in any format which can represent a list from 1 to 24 people.
# Test Cases
If the output of a test case has an `OR` in it, your program may return any *one* or all of the choices.
```
[(0,1),(1,2),(2,3),(2,5),(5,6),(6,3),(6,7),(7,4)], 1 => [3] OR [4]
[(0,1),(1,2)], 1 => [2]
[(0,1),(1,2),(2,3),(3,4),(4,5),(5,6),(6,7)], 1 => [7]
[(1,2),(2,3)], 2 => [2,3]
[(1,2),(3,4)], 2 => [1,2] OR [3,4] OR [2,4]
[(0,1),(1,2),(1,8),(2,3),(3,4),(4,11),(5,4),(5,6),(6,13),(13,20),(13,12),(12,19),(20,19),(4,19),(19,18),(11,10),(10,3),(10,2),(10,9),(9,8),(8,1),(8,7),(18,17),(18,24),(17,24),(24,23),(17,16),(16,23),(24,18),(16,15),(23,22),(22,15),(22,21),(21,14),(14,15)], 1 => [7] OR [15]
[(0,1),(1,0),(0,2),(1,3)], 1 => [2] OR [3]
[(0,1),(1,0),(0,2),(1,3)], 2 => [2,3]
[(0,1),(1,2)], 3 => [0,1,2]
[(0,1),(1,2),(2,3),(3,5),(3,6),(3,7),(5,7),(6,4),(7,9),(8,4),(9,8)], 4 => [8,9,4,7]
[(0,1),(1,0),(0,2),(1,3)], 4 => [0,1,2,3]
[(0,1),(1,2),(2,3),(2,5),(5,6),(6,3),(6,7),(7,4)], 5 => [3,4,5,6,7]
[(0,1),(1,2),(2,3),(3,5),(3,6),(3,7),(5,7),(6,4),(7,9),(8,4),(9,8)], 5 => [4,5,7,8,9]
[(0,1),(1,2),(2,3),(3,4),(4,5),(5,6),(6,7)], 6 => [2,3,4,5,6,7]
[(0,1),(1,2),(2,3),(3,4),(4,5),(5,6),(6,7)], 7 => [1,2,3,4,5,6,7]
[(0,1),(1,2),(2,3),(3,5),(3,6),(3,7),(5,7),(6,4),(7,9),(8,4),(9,8)], 7 => [3,4,5,6,7,8,9]
[(0,1),(1,2),(2,3),(3,5),(3,6),(3,7),(5,7),(6,4),(7,9),(8,4),(9,8)], 8 => [2,3,4,5,6,7,8,9]
[(0,1),(1,2),(2,3),(3,5),(3,6),(3,7),(5,7),(6,4),(7,9),(8,4),(9,8)], 9 => [1,2,3,4,5,6,7,8,9]
[(0,1),(1,2),(1,8),(2,3),(3,4),(4,11),(5,4),(5,6),(6,13),(13,20),(13,12),(12,19),(20,19),(4,19),(19,18),(11,10),(10,3),(10,2),(10,9),(9,8),(8,1),(8,7),(18,17),(18,24),(17,24),(24,23),(17,16),(16,23),(24,18),(16,15),(23,22),(22,15),(22,21),(21,14),(14,15)], 9 => [14,15,16,17,18,21,22,23,24]
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~14~~ 10 bytes
```
~f`öΠFf†€Ṗ
```
Takes three inputs: number of people to go, 2-row matrix of the constraints, and list of all people involved, in this order.
Returns all possible lists of people who go.
If you want to output only one list, replace the leftmost `f` by `ḟ`.
[Try it online!](https://tio.run/##yygtzv7/vy4t4fC2cwvc0h41LHjUtObhzmn///83/h8dbahjrGMcqxNtomOoYxIb@x8oYAQUMokFAA "Husk – Try It Online")
## Explanation
The idea is to loop over the size-`n` subsets of `p` and keep those that satisfy the condition imposed by `g`: if the first person in a pair goes, then the second person must go too.
```
~f`öΠFf†€Ṗ Implicit inputs, say n=3, g=[[1,3,3],[4,1,4]] and p=[1,2,3,4]
Ṗ All n-element subsets of p: [[1,2,3],[2,3,4],[1,3,4],[1,2,4]]
~f Keep those subsets (say q=[1,2,4]) for which
`ö this function gives a truthy (nonzero) result:
† Deep map over g:
€ index in q, or 0 if doesn't occur: [[1,0,0],[3,1,3]]
Ff Fold by select (filter second row by truthiness on first row): [3]
Π Product: 3
```
This program is one of those where it's really hard to explain how the program arguments are passed to the correct functions, but I'll try.
First, `n` is the first argument, so it can be given to `Ṗ` directly, making it a function that takes a list and returns its `n`-subsets.
The next two inputs are `g` and `p`, and the program's shape at this point is `~(f)(`öΠFf†€)(Ṗn)` with parentheses added for clarity.
The operator `~` gives `g` to ``öΠFf†€` and `p` to `Ṗn`, and combines the results with `f`.
`Ṗnp` is just the `n`-subsets of `p`, so that's simple.
The operator ``` causes `öΠFf†€` to take its arguments in the reverse order, so `g` is actually the *second* argument of this function.
The first argument is an element `q` of `Ṗnp`, which is extracted by `f` (filter).
We give `q` as an argument to `€`, which becomes a function for testing membership in `q`, and deep map *that* over the second argument, which is `g`.
Then `ΠFf` are applied to the result.
The role of `ö` is just to compose `ΠFf†€` into one function, which we can then pass on to ``` and `~f`.
[Answer]
# Python 2, 100 98 bytes
```
g,n=input()
v=k=0
while bin(v).count("1")^n:k=v=k+1;exec"for a,b in g:v|=(v>>a&1)<<b\n"*25
print v
```
I assume that the people are numbered from 0 to n. `g` is a list of pairs just like in the question. The output is a number where the `i`th bit is set if the `i`th person goes.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~62~~ 55 bytes
```
Select[g=#;#2~Subsets~{#3},#==g~VertexOutComponent~#&]&
```
[Try it online!](https://tio.run/##TYw7C4MwGEX3/o1Ap/uB8TmIAR@dWxC6iIOV1ApVi0YoiPnrady6HM4d7hka9ZJDo/q2Mc91TEwp37JVVZewmLm6XB@LVIvemLeDJUmn73JW8ntdVT4Nn2mUo9LsXJ/Nbe5HVdlEtaUkMlgUyEjkyA8rSFx2bCky5Chg3avr@PT3ckhwcBIuXBLegQABiRDhMS0iRCR8G3HA4cKDjwAhoh3cpswP "Wolfram Language (Mathematica) – Try It Online")
### I/O
Takes as input the following three arguments:
* list of she-goes-I-go pairs, as rules (`x->y`). The first example in the question would be encoded as `{A->B,A->D,B->C,C->D,D->E}`. Can also take a Mathematica `Graph` object.
* list of people involved. E.g., `{A,B,C,D,E}`.
* number of people we want to go. E.g., `3`.
The output is a list of *all* subsets of people of the right size who could go.
### How it works
The older version was fancier, and contained the expression `#|##&@@#` which I'm very proud of, but this one just uses a built-in. `VertexOutComponent` computes the set of everyone else who must go, given a group of people who are going; we just `Select` the `Subsets` of the given size whose `VertexOutcomponent` is the same set and no bigger.
*-7 bytes: the built-in.*
[Answer]
# [Python 3](https://docs.python.org/3/), 97 95 bytes
```
lambda g,n,c:[k for k in range(2**c)if-1<bin(k).count("1")-n<all(k>>s&1for f,s in g if k>>f&1)]
```
[Try it online!](https://tio.run/##TY7LDoJADEX3fEXjgkxNNQwvH0F@BFkM6OBkcCCAC78ey6zcnDTtvekZv8trcMmqb/e1V@/moaAjR@21sqCHCSwYB5Ny3VPE@32LRh9k0RgnLB7b4eMWsZM7PLhC9b2wZTmHcqtpmrdiB0YDb3UosV6HzwI30KISEUkkISlmxpQwE8o8c88TM/PMKWWe6MI8@/lCZ6wJUgIZYRCMk2GJqjJe1/zpZrh9V26GsuRDCLL2mW3DKbapcf0B "Python 3 – Try It Online")
Takes `g` as a list of pairs, as in the question, and additionally takes the number of people `c`. Returns all solutions in form `n` where bit `i` of `n` corresponds to whether or not person `i` attends.
] |
[Question]
[
Based on [this challenge](https://codegolf.stackexchange.com/questions/142066/output-the-trinity-hall-prime) and [this Math.SE question](https://math.stackexchange.com/questions/2420488/what-is-trinity-hall-prime-number). Idea originally come from [a Numberphile video](https://www.youtube.com/watch?v=fQQ8IiTWHhg). The goal is to reproduce the *logic* of Professor McKee when he builds this prime.
Your task is to build the Trinity Hall Prime, at a much lower scale. You are given a single number N greater than 2, representing the length of the prime we need.
# Rules
* N is decomposed into a rectangle W(idth) x H(eight). W and H must be close, so 12 is 4x3 and 16 is 4x4 with W >= H
* The first line got only 8's
* The next lines have 8's in the outer and 1's in the middle
* Each lines have 2 more 1's and 2 less 8's than the previous, except if W is odd, then the second line have only one 1 in the middle
* Once you got your emblem, find the first prime greater than the emblem.
* 2 <= N <= 16
* This is [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'"), so newlines must be part of the output.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code, in bytes, wins.
# Test cases:
```
I Emblem O
================
2 88 89
3 888 907
4 88 88
11 19
6 888 888
818 827
8 8888 8888
8118 8133
9 888 888
818 818
111 159
10 88888 88888
88188 88213
16 8888 8888
8118 8118
1111 1111
1111 1159
```
[Answer]
# [Python 3](https://docs.python.org/3/), 194 bytes
```
n=int(input())
R=range
w=n//max(i*(i*i<=n>1>n%i)for i in R(1,n))
m=0
for i in R(n):m=m*10+1+7*(abs(i%w*2-w+1)//2*w>i-w)
while any(m%p<1for p in R(2,m)):m+=1
m=str(m)
while m:print(m[:w]);m=m[w:]
```
[Try it online!](https://tio.run/##TY5BCoMwFET3niIbIYmKxkIL1ngIt@IiBVs/9H@DpqSePo2UQmFWw8ybsbubFzqFQBrIcSD7clyIpNeroceUeE1liebNQUZBq6lTHaUg7svKgAGxnqucYgN1lfyZJBrUKFWVqewiubltHFIv68JnSpRlLX0HhReJn@E5MUM7x9S26iDYL6HOUURIplVkb27l@EtjY9fjLQ6NH8U17gy@GUM4fwA "Python 3 – Try It Online")
too slow for most inputs, especially `x > 8`
-6 bytes thanks to Jonathan Frech
-98 bytes thanks to Leaky Nun
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~57~~ 56 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒgṖḊ$€2¦j8
Æd:2‘ịÆDðL€©8,8jÇÐĿḊ€ḣ€⁸Ṛ;®ẋ€⁸¤ḣ:@ðFḌÆnDṁ⁸Gḟ⁶
```
A monadic link taking a number and returning a list of characters. As a full program it prints the result.
**[Try it online!](https://tio.run/##y0rNyan8///opPSHO6c93NGl8qhpjdGhZVkWXIfbUqyMHjXMeLi7@3Cby@ENPkCZQystdCyyDrcfnnBkP1AxUOThjsVA8lHjjoc7Z1kfWvdwVzeEe2gJUMbK4fAGt4c7eg635bk83NkIFHZ/uGP@o8Zt////NzYzAAA "Jelly – Try It Online")**
### How?
```
ŒgṖḊ$€2¦j8 - Link 1, previous 8-padded-row builder: list current 8-padded-row
- e.g. [8,8 , 1,1,1 , 8,8]
Œg - group runs of equal elements [[8,8],[1,1,1],[8,8]]
¦ - sparse application:
2 - ...to indices: 2
$€ - ...do: last two links as a monad for €ach:
Ṗ - pop [[8,8],[1,1 ],[8,8]]
Ḋ - dequeue [[8,8],[ 1 ],[8,8]]
j8 - join with eights [8,8, 8, 1, 8, 8,8]
- (note: from ...818... this yields an extra 8 - dealt with by ḣ€ in Main)
Æd:2‘ịÆDð... - Main link: number, N
Æd - divisor count of N
:2 - integer divided by 2
‘ - increment
ÆD - divisors of N
ị - index into (yields W)
ð - start a new dyadic chain with W on the left and N on the right...
...L€©8,8jÇÐĿḊ€ḣ€⁸Ṛ;®ẋ€⁸¤ḣ:@ð... - Main link (continued): W, N
L€ - length of €ach of implicit range(W) = list of W 1s
© - (copy to register for later reuse)
8,8 - literal [8,8]
j - join -> [8,1,1,...,1,8] with W 1s
ÐĿ - collect inputs until fixed point:
Ç - call the last link (1) as a monad
Ḋ€ - dequeue €ach (remove the leading 8 from each)
⁸ - chain's right argument, N
ḣ€ - head €ach to index (remove the trailing 8(s))
Ṛ - reverse
¤ - nilad followed by link(s) as a nilad:
® - recall the [1,1,...W times...,1] from the register
⁸ - chain's left argument, W
ẋ€ - repeat €ach (making W more rows of W 1s)
; - concatenate
:@ - integer division (sw@p arguments) = N:W = H
ḣ - head to index (gets the first H rows - the mask, M)
ð - start a new dyadic chain with arguments M, N
...FḌÆnDṁ⁸Gḟ⁶ - Main link (continued): M, N
F - flatten M
Ḍ - from decimal list to number
Æn - next prime
D - to decimal list
⁸ - chain's left argument, M
ṁ - mould like (reshape like the mask)
G - format as a grid (all digits to characters, add spaces and newlines)
⁶ - literal space character
ḟ - filter discard (Gḟ⁶ instead of Y as single row results are possible)
- as a full program: implicit print
```
] |
[Question]
[
### Taking in Input
Define a function `f` as follows:
```
IF x < 0:
f(x) = -√|x|
ELSE:
f(x) = √x
```
In your programs/functions, each point `(x, y)` given as input will correspond to the point `(f(x), f(y))`. For example, if the points `(4, -2)` and `(-1, 5)` are given as input, your program will be dealing with the points `(2, -√2)` and `(-1, √5)`. From now on, we will be referring to points in this format, rather than points in the format given in the input.
You will take in a set/list of points as input which will then be converted to Cartesian points with the function `f`.
### Balanced Sets of Points
Denote by `PQ` the Euclidean distance from point `P` to point `Q`.
A set of points `S` is *balanced* if, and only if, for all pairs of distinct points `A` and `B` in `S`, there exists a point `C` in `S` such that `AC = BC`. For example, the set of points `{(0, 2), (-√3, -1), (√3, -1)}` is balanced because the points in this set are the vertices of an equilateral triangle. Note that this set of points would be taken as input by the program/function as `{(0, 4), (-3, -1), (3, -1)}`.
### Centre-Free Sets of Points
Again, denote by `PQ` the Euclidean distance from point `P` to point `Q`.
A set of points `S` is *centre-free* if, and only if, for all triples of distinct points `A`, `B` and `C` in `S`, there *does not exist* a point `P` in `S` such that `AP = BP = CP`. For example, the set of points `{(0, 2), (-√3, -1), (√3, -1)}` is centre-free, but if you add the point `(0, 0)` to this set, it is no longer centre-free.
### Formatting the Output
The output will be in the form of a two-digit binary number. Suppose we are given the set of points `S`. After having applied the function `f` to each point (see section "Taking in Input"), the first digit of this binary number will indicate whether this set of points is balanced and the second digit of this binary number will indicate whether this set of points is centre-free. For example, `10` will indicate that the given set of points is balanced, but not centre-free.
Also note that the digits `1` and `0` may be replaced with any truthy and falsy values. As opposed to strings, arrays and ordered pairs are also acceptable.
### Test Cases
```
> {(0, 4), (-3, -1), (3, -1)}
11
> {(0, 4), (3, 1), (3, -1), (0, -4), (-3, -1), (-3, 1)}
01
> {(0, 4), (-3, -1), (3, -1), (0, 0)}
00
> {(0, 4), (-3, -1), (3, -1), (0, -4), (0, 0)}
00
> {(0, 16), (-3, 1),(-12, -4), (0, -4), (12, -4), (3, 1)}
10
```
### Winning Criterion
Make your code as short as possible.
### Credits
This was inspired by Problem 1 from [IMO 2015](https://artofproblemsolving.com/community/c105780_2015_imo). (Great problem, by the way!)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 36 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ạþE€Ṁ
®Œc瀮Ạ
A½×Ṡ×1,ıSµ€©œc3ñ€®Ṁ¬¢,
```
A full program printing the representation of a list of two ones/zeros.
This relies on theoretical infinite-precision floating point arithmetic, which is, of course, not the case. So here is a (43 byte) version which uses a **1e-10** leeway for the pair-wise distance comparisons it makes:
```
ạþI€×ȷ10ỊẠ€Ṁ
®Œc瀮Ạ
A½×Ṡ×1,ıSµ€©œc3ñ€®Ṁ¬¢,
```
**[Try It Online!](https://tio.run/##y0rNyan8///hroWH93k@alpzePqJ7YYGD3d3Pdy1AMh9uLOB69C6o5OSDy8H8g6tA4pyOR7ae3j6w50LDk831DmyMfjQVpDMyqOTk40Pb4Qo2tlwaM2hRTr///@PjjbQMYnViTbUMQaSxjqGQNJExwDM1jUES@iCZAx0dEHKdKFcXaisLkStLkSjLsiUWAA "Jelly – Try It Online")**
### How?
(I'll include the replacement code used in place of `E` - equals to allow the leeway here)
```
ạþI€×ȷ10ỊẠ€Ṁ - Link 1: any all-equal distance complex numbers?: list of lists; list
ạþ - outer-product with absolute difference
I€ - incremental differences for €ach
×ȷ10 - multiply by 10^10
Ị - insignificant (abs(z)<=1) (vectorises)
Ạ€ - all? for €ach
Ṁ - maximum
®Œc瀮Ạ - Link 2: isBalanced? no-arguments (requires register to be populated - see Main)
® - recall from register (the points as a list of complex numbers)
Œc - pairs
® - recall from register (the points as a list of complex numbers)
ç€ - call the last link (1) as a dyad for €ach pair
Ạ - all truthy?
A½×Ṡ×1,ıSµ€©œc3ñ€®Ṁ¬¢, - Main link: list of (x, y) inputs
µ€ - for €ach (x,y) pair, p:
A - absolute value of p (vectorises)
½ - square root (vectorises)
Ṡ - sign of p (vectorises)
× - multiply (vectorises)
1,ı - literal [1, 0+1i]
× - multiply (vectorises)
S - sum
© - (copy the result to the register)
œc3 - combinations of length 3
® - recall from register
ñ€ - call the next link (1) as a dyad for €ach triple
Ṁ - maximum (1 if any triple has a centre)
¬ - not (0 if any triple has a centre - hence isCentreFree?)
¢ - call the last link as a nilad
, - pair with the calculated isCentreFree?
- implicit print
```
[Answer]
# [Python 2](https://docs.python.org/2/), 303 302 bytes
**Edit:** -1 byte thanks to [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)
```
lambda x,y:f((x[0]-y[0])**2+(x[1]-y[1])**2)
f=lambda x:x<0and-f(-x)or x**.5
v=lambda a,b,p:abs(d(a,p)-d(b,p))<1e-9
def e(k):k=[(f(a),f(b))for a,b in k];print+all(any(v(a,b,c)for c in k)for a in k for b in k if a!=b),1-any(any(v(a,b,p)*v(b,c,p)for p in k)*len({a,b,c})>2for a in k for b in k for c in k)
```
[Try it online!](https://tio.run/##jZBNboMwEIXX8SmmuxliV5j@SKWhF6GoMmCrKJSggCJQ1bNTGyuBRF10Y72Z@d6zPe3Yfx6aaCqT96lWX3mpYOBjbBCHNMzEaA8KgmhrS@lKOZfETHKm42EXqqYUBsVAhyMMQXD/xE7nueI5b2OVd1ii4i2JEm2DaCe1eGGlNqBxT/E@SdGgIm4wJzI2xxqhamCfvbbHqum3qq5RNSOe0EUWM1PMhMdnCU56H1QG1F2SE5fC@RZvS8HJPqKwwuGtDwlq3eD3nP1Db9HfmatLp153/UehOt1BAinbpBhyeCQOKB44COmUFxlfT21vNbPCDsSNT8zQte821TvDf1E@/xqXz8tNHIWMVpgXS8s/h2XA3AYuP3ebWNYQs43GS0nTLw)
] |
[Question]
[
A [Woodall Prime](https://oeis.org/A050918) is a prime which can be calculated, given a positive integer `n`, with `n * 2^n - 1`.
Your task is to, given a integer `k`, generate a Woodall Prime with `k` digits. If no such Woodall Prime exists, you must generate a Woodall Prime with the closest amount of digits. If two primes exist with the same digit count difference, you may use either.
You may assume that there exists no two Woodall Primes with the same amount of digits.
There is no time complexity limit, and you must be able to handle at least the first ten Woodall Primes (you can see them in the OEIS link at the start of the question)
You may write a full program or a function, and you may print or return the output.
### Examples:
```
1 -> 7
4 -> 383
0 -> 7
-100 -> 7
7 -> 383 or 32212254719 (you may pick either of these)
8 -> 32212254719
```
As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), that shortest code wins!
(there are only nine Woodall Primes on the linked OEIS sequence, so you might want to look at this for more Woodall Primes: <https://oeis.org/A002234>)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~28~~ 26 bytes
```
:K≜+ℕ~lṗ.+₁~×[İ,J]h:2^₍J≜∧
```
[Try it online!](https://tio.run/nexus/brachylog2#@2/l/ahzjvajlql1OQ93TtfTftTUWHd4evSRDTpesRlWRnGPmnq9gCoedSz//z/e0MDgfxQA "Brachylog – TIO Nexus")
This is too slow for TIO for inputs bigger than 4.
### Explanation
```
:K The list [Input, K]
≜ Assign a value to K (0, then 1, then -1, then 2, etc.)
+ℕ Input + K >= 0
~l . Output is a number of length (Input + K)
ṗ. Output must be a prime number
+₁ Output + 1...
~×[İ,J] ... = İ × J, İ being an integer...
h:2^₍J ... and J = 2^İ
≜∧ Check that it is possible to find a value for İ that satisfies
all of those constraints. If not, go back to the beginning
and try another value for K through backtracking.
```
We use a common trick in Brachylog for "find the closest X to Y": labeling a completely free variable (which we do when we use `≜` on the list `[Input, K]` will label it with this pattern: `0, 1, -1, 2, -2, 3, ...`. Therefore, when backtracking if the value `Input + K` doesn't work as the number of digits, the next choice we will try will be the next possible closest choice.
[Answer]
# Mathematica, 72 bytes
```
Nearest@<|Thread[w->IntegerLength[w=# 2^#-1&~Array~999~Select~PrimeQ]]|>
```
Pure function taking an integer as input and returning the set of Woodall primes whose lengths are closest to the input. For example, applying this function to `6` results in `{383}`, while applying it to `7` yields `}{383,32212254719}`.
`w=# 2^#-1&~Array~999~Select~PrimeQ` constructs a list of the first 15 Woodall primes, by testing all numbers of the form n\*2^n-1 with n up to 999. `<|Thread[w->IntegerLength[w]]|>` creates an association taking the number of digits of each of these Woodall primes to the primes themselves. Then `Nearest` picks out the Woodall primes whose numbers-of-digits are closest to the input.
[Answer]
# [Perl 6](https://perl6.org), ~~71~~ 68 bytes
```
->\k{({$/ if is-prime $/=2**++$*++$-1}...*.chars>k).min:{abs k-.chars}}
```
[Try it](https://tio.run/nexus/perl6#RY7NboMwEITvfopRFTUQYhNI2qRB0D5Ej1wcZ6NYhB9hqIoQj91zaiBVD6td73wz3tYQvl6Filhrp08yTcTyDs@qPBPiO0/SrHf6hQ99gTa8qnVOWPhxuFp53mIsHgxCiJVQV1mbJHNFrotjL08GGZ@Xw3C3kR@NDUeMmy7IOBaT1RHWVuYnx1/y5TvSs@e7EatusoA34RG7lPXDyRM4qS6qtll79F2RaujsomeADU9rMu1tjJ8On7DIStpgVtb48whZdGs89RMzIE7Qz8jwFLHhHowf7dlubNvDlm3mNw82j2n/UGAv24ZhEIYvu33wBqcrW@SyQ6VVBtLNlWqUF9huyGWHyfbP/xQlV1Jd6Rc "Perl 6 – TIO Nexus")
```
{({$/ if is-prime $/=2**++$*++$-1}...*.comb>$^k).min:{abs $k-.comb}}
```
[Try it](https://tio.run/nexus/perl6#RY7NboMwEITvfopRhBoIsQkkbdIg0j5Ej6gScTaKxa8wVEWIx@45NZCqh9Wud74Zb6sJXy9Chqw10wfpJmR5hydZXgjRvbd7y4O6Qmle1SonWF4UrFaua43F/UEIsRKyzM8n6zN1RK6KY5@cNayUT@thuJu898YkI0KmCtK2wZLqiNlne0u@fEN8cT0nZFWWFHAnPGTXsn44@Ql2rIqqbdYufVckG7o46BlgwuOadJuN8dPVExYaSWnMyhp/HpEU3RqLfmIGRCf0MzIsQjbc/fGjPduNbXvYss385v7mMe0fCsxl2yDwg@B5t/dfYXdlizzpUCmZglRzoxrlFaZrcthhsv3zP0XJZSJv9As "Perl 6 – TIO Nexus")
## Expanded:
```
{ # bare block lambda with parameter 「$k」
( # sequence of possible candidates
{
$/ # use the Woodall number
if # but only if
is-prime( # this is prime
$/ = # store the Woodall number in $/
2 ** # 2 to the power of
++$ # n ( preincrement of anon state variable )
* # times
++$ # n ( preincrement of anon state variable )
-1 # -1
)
}
... # keep generating Woodall primes until:
*.comb > $^k # it has more digits than 「$k」 (declare 「$k」 as a parameter)
).min: { abs $k - .comb } # find the nearest one
}
```
] |
[Question]
[
A histogram is an array of integers that counts the number of times a symbol occurs. For example, for the string `"aaabbbabbdebabbbebebdbaaabbabaaaaeebeaabaaba"` a histogram is `a: 18, b: 18, c: 0, d: 2, e: 6`, or `[18, 18, 0, 2, 6]` in short.
If we were to pick a random character out of this string, what would the chance be that it is a particular character? We can calculate a probability table using the histogram. Simply divide every number by the sum of the histogram. So we have a 18/44 chance to get `a`.
Probability tables are used in compression algorithms. But compression algorithms have to be fast and always do the same computation on every machine. We can't use ratios, as they're slow and get big (1248148/13468235) and we can't use floating point as rounding errors differ from machine to machine. So we use... fixed point probability!
A 15-bit fixed point probability is a 15-bit integer representing a probability. If `n` is the integer, then it represents the real probability `n / 0x7fff`. So `0` is never, `0x7fff` is always, and `0x3fff` is (nearly) 50%.
So, the challenge is to compute a 15-bit fixed point probability table, given a histogram. But there are a few assumptions that the output must fulfill:
* Every symbol in the histogram has a respective 15-bit fixed point probability in the probability table.
* A symbol with count 0 in the histogram must have zero probability.
* A symbol with count > 0 in the histogram may not have zero probability.
* The cumulative probability must be 1: the probability table must sum to `0x7fff`.
---
Your score for a certain histogram will be the sum of squared differences between the real probabilities and the 15-bit fixed point approximations.
The score for your answer will be the sum of scores you get on the set of histograms generated by the following Python (2 or 3) program:
```
import random
random.seed(0)
for _ in range(100):
l = 1 + min(int(random.expovariate(1/100.)), 1000)
print([int(random.expovariate(1/10.)) for _ in range(l)])
```
Alternatively, you can [view the test set here](https://gist.githubusercontent.com/orlp/394c1986bad4b05633ce/raw/d98b51470c517ca18dcb25fa04ca67d3b531fcc4/gistfile1.txt). I may change the test set in the future, do not optimize for this particular one.
If you write your probability tables in a Python list format, one per line, the following Python program can score your answer in one fell swoop using `python score.py hist.txt prob.txt`:
```
from __future__ import division
import sys
scores = []
with open(sys.argv[1]) as hist, open(sys.argv[2]) as prob:
skip_empty_lines = lambda it: filter(lambda s: s.strip(), it)
for hist_l, prob_l in zip(skip_empty_lines(hist), skip_empty_lines(prob)):
hist, prob = eval(hist_l), eval(prob_l)
scores.append(sum((p/0x7fff - h/sum(hist))**2 for h, p in zip(hist, prob)))
print(sum(scores))
```
**Lowest score wins, ties broken by asymptotic complexity before first answer.**
[Answer]
## Python, score 8.682671033510566e-07, O(n \* log(n))
```
#!/usr/bin/env python
from __future__ import division
from ast import literal_eval
from fractions import Fraction
from operator import itemgetter
from sys import argv
import fileinput
def model(hist):
TOTAL_FINAL = 0x7fff
TOTAL_INIT = sum(hist)
SCALE = Fraction(TOTAL_FINAL, TOTAL_INIT)
hist_probs = [Fraction(x, TOTAL_INIT) for x in hist]
res = [max(int(x*SCALE),1) if x > 0 else 0 for x in hist]
adjust = TOTAL_FINAL - sum(res)
res_probs = [Fraction(x,TOTAL_FINAL) for x in res]
diffs = [(x-y)**2 for x,y in zip(hist_probs, res_probs)]
d2 = [(x-y) for x,y in zip(hist_probs, res_probs)]
if adjust > 0:
idx, vals = zip(*list(filter(lambda x:x[1]>0, sorted(((i,x) for (i,x) in enumerate(d2) if hist[i]), key=itemgetter(1), reverse=True))))
i = 0
while i < adjust:
res[idx[i%len(idx)]] += 1
i += 1
else:
idx, vals = zip(*list(filter(lambda x:x[1]<0,sorted(((i,x) for (i,x) in enumerate(d2) if hist[i]), key=itemgetter(1)))))
i = 0
while i < adjust:
res[idx[i%len(idx)]] -= 1
i += 1
return res
if __name__ == '__main__':
for line in fileinput.input():
print(model(literal_eval(line)))
```
This takes input as a file (or sequence of files) with one Python-list-format histogram per line, with the filename(s) provided on the command line (like `python prog.py hist.txt`).
The general strategy here is to make a (decent) initial guess at the best probability representation, by doing integer scaling of the input histogram to 15 bits. This almost always gets the resultant list just shy of 32767 total. To adjust the probabilities, the items with the largest squared differences from the input histogram get incremented. If the result is too high initially, the largest value in the array is decreased by the excess, instead.
### Time Complexity
`O(n * log(n))`, based on the sorting, which is the most time-consuming operation for each histogram.
] |
[Question]
[
Take as input 3 floating point numbers, which represent the x, y, z coordinates of a point. Return a truthy or falsey value indicating whether the point is inside the regular icosahedron centred at the origin, with top and bottom vertices at (0, 0, 1) and (0, 0, -1), and with one of the upper ring of middle vertices in the +X+Z quarterplane. Input/output formats can be anything reasonable. To allow for rounding error, Your code does not have to give correct answers for points within 10^-6 units of the boundary
Example inputs / outputs:
```
0, 0, 0 => true
1, 1, 1 => false
0.7, 0.5, -0.4 => true
-0.152053, -0.46797, 0.644105 => false
-0.14609, -0.449618, 0.618846 => true
```
To be absolutely clear on the orientation of the icosahedron, the coordinates of the vertices are approximately
```
{{0., 0., -1.},
{0., 0., 1.},
{-0.894427190999916, 0., -0.447213595499958},
{0.894427190999916, 0., 0.447213595499958},
{0.723606797749979, -0.5257311121191336, -0.447213595499958},
{0.723606797749979, 0.5257311121191336, -0.447213595499958},
{-0.723606797749979, -0.5257311121191336, 0.447213595499958},
{-0.723606797749979, 0.5257311121191336, 0.447213595499958},
{-0.27639320225002106, -0.85065080835204, -0.447213595499958},
{-0.27639320225002106, 0.85065080835204, -0.447213595499958},
{0.27639320225002106, -0.85065080835204, 0.447213595499958},
{0.27639320225002106, 0.85065080835204, 0.447213595499958}}
```
Scoring is standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the fewest bytes wins.
[Answer]
# Ruby,87
```
->c,z{a=g=3-5**0.5
10.times{x=(c*="i".to_c**0.4).real
z=-z
a&&=z<1+x*g&&x*4>g-4+g*z}
a}
```
An anonymous function taking the x and y coordinates as a complex number and the z coordinate as a real. (The question says "any reasonable" format which is a bit vague. If the format is not acceptable I can change it.)
**Explanation**
Below you can see a view looking down the z axis at the icosahedron's vertices. (for simplicity I have just drawn 2 pentagons that are perpendicular to the z axis.)
I have labelled all the points with positive z with their approximate coordinates. I have given the exact coordinates `sqrt 0.8, 0, sqrt 0.2` for the point with positive z that lies in the xz plane (y=0), and I have also labelled the opposing point.
It can be seen that there is an edge parallel to the y axis whose equation is approximately `z=0.4472, x=-0.7236`. This edge is common to two faces of the icosahedron. I will describe these as a polar face and an equatorial face.
The equation of the polar face is `z=1+x*g` where `g=3-sqrt(5)` (this value was arrived at by studying Wikipedia and Wolfram Alpha, plus a bit of my own maths.) So z must be less than `1+x*g` if the point is inside the icosahedron.
The equation of the equatorial face is `x*4=g-4+g*z` so x\*4 must be greater than
`g-4+g*z` if the point is inside the icosahedron.
We could rotate these faces through 72 degrees to test if the point is inside the icosahedron, but it is easier to rotate the point about the origin. In order to cover both the top and bottom of the icosahedron, the symmetry operation applied to the point is a rotation of 36 degrees combined with a reflection in the xy plane (flip the z axis.) This operation is applied 10 times to cover all possibilities.
[](https://i.stack.imgur.com/50jlS.png)
**Ungolfed in test program**
```
f=->c,z{
a=g=3-5**0.5 #g is slope of polar face. It is truthy, so can also be used to initialize a
10.times{ #generate 10 images of the point
x=(c*="i".to_c**0.4).real #rotate the point 36 degrees, assign the real value to x
z=-z #flip the z axis
a &&= z<1+x*g && x*4>g-4+g*z #check the point is inside the two test planes and update a if necessary
}
a} #return a true or false
p f["0+0i".to_c,0] #true
p f["1+i".to_c,1] #false
p f["-0.152053-0.46797i".to_c,0.644105]#false
p f["-0.14609-0.449618i".to_c,0.618846]#true
p f["-0.8944+0i".to_c,-0.4472] #true, just inside vertex
p f["-0.8944+0i".to_c,0.4472] #false, outside midpoint of an edge
p f["-0.8945+0i".to_c,-0.4473] #false, just outside vertex
```
] |
[Question]
[
# Topping the Charts
You are a record label company. Your goal is to get 4 of your signed bands in the top 4 positions in the charts. However, its recently been noted that bands currently in the charts influence who is going to be in the charts the next day.
In this challenge, each player will control 5 bands (instances of your code), each of them placed in alternating order in one of the 11 spots of the scoreboard, with the 11th spot open. Each band will have a unique, hidden ID (from 0-9), and a unique, visible name (a randomly generated integer).
Each turn, the band with the open spot below them in the charts will call an ID. The bot instance with that ID will move to that spot, creating a new open spot. If spot #1 is open, then the 11th bot will be the one to name an ID.
The game is over when spots 1-4 are all held by your bands, giving you 3 points. If a particular band ordering is created more than 3 times, then both labels will tie and be given 1 point. The player with the most points after facing each other player twice (to ensure both labels start with a band in the #1 position) wins.
# I/O
Bots will be stay alive between turns. Information will be passed back and forth via STDIO. When multiple pieces of information is passed, it will be comma separated. Each instance of your bot **MUST NOT** communicate with each other (nor with the other team).
At the beginning of the game, your will be passed three integers, your ID, position, and name, and then you will be passed a list of names of the current positions, with 0 being the open position.
On your turn, you will be passed a list of names of the current positions, with 0 being the open position. You must return the ID you wish to place in the spot below you.
If you get switched, you will be be passed two integers, the name of the person that switched you, and your new position (from 0-10).
If you win, you will be passed 0, at which, you must end your program
The controller can be found here: <https://github.com/nathanmerrill/ScoreboardKoTH>
[Answer]
# Random Bot
If you couldn't guess, this bot picks a number randomly. Run with `python random_bot.py`
```
import sys
import random
def get_data():
data = sys.stdin.readline().strip()
if data == "0":
exit()
return [int(x) for x in data.split(",")]
def startup():
global _id, position, name
all_data = get_data()
player_names = all_data[3:]
_id, position, name = all_data[:3]
def switched(switcher, new_position):
global position
position = new_position
def call_id(player_names):
return random.randrange(10)
_id = -1
position = -1
name = -1
startup()
while True:
data = get_data()
if len(data) == 1:
break
elif len(data) == 2:
switched(*data)
else:
print str(call_id(player_names=data))
sys.stdout.flush()
```
[Answer]
# Self Mover Bot
This bot always moves itself. Run with:
```
javac SelfMover.java
java SelfMover
```
Code:
```
import java.util.Scanner;
public class SelfMover {
private Scanner stdIn;
private final int id, name;
private int position;
public static void main(String[] args) {
new SelfMover();
}
public SelfMover() {
stdIn = new Scanner(System.in);
Integer[] data = getData();
id = data[0];
position = data[1];
name = data[2];
mainLoop();
}
private void mainLoop() {
while(true){
Integer[] data = getData();
if (data.length == 1){
return;
} else if (data.length == 2){
switched(data[0], data[1]);
} else {
System.out.println(callID(data));
}
}
}
private Integer[] getData(){
String data = stdIn.nextLine().trim();
if (data.equals("0")){
System.exit(0);
}
String[] strData = data.split(",");
Integer[] intData = new Integer[strData.length];
for (int i = 0; i < strData.length; i++){
intData[i] = Integer.parseInt(strData[i]);
}
return intData;
}
private void switched(int switcher, int newPosition){
position = newPosition;
}
private int callID(Integer[] players){
return id;
}
}
```
[Answer]
# Unswitcher bot
This bot mistakenly assumes that its new position is the ID of the bot that switched it, and tries to unswitch.
Run with `python unswitcher_bot.py`
```
import sys
last_switched = -1
def get_data():
data = sys.stdin.readline().strip()
if data == "0":
exit()
return [int(x) for x in data.split(",")]
def startup():
global _id, position, name
try:
all_data = get_data()
except:
raise NameError
player_names = all_data[3:]
_id, position, name = all_data[:3]
def switched(switcher, new_position):
global position, last_switched
position = new_position
last_switched = switcher
def call_id(player_names):
return min(position, 9)
_id = -1
position = -1
name = -1
startup()
while True:
data = get_data()
if len(data) == 1:
break
elif len(data) == 2:
switched(*data)
else:
print call_id(player_names=data)
sys.stdout.flush()
```
] |
[Question]
[
**Format**
The format is a 64 bit value **x** representing a IEEE-754 double-precision binary floating-point number (a.k.a "a double"). **x** is assumed to represent a real number (not a NaN or Infinity).
**Goal**
The goal is to print/output the shortest string containing a decimal representation for which **x** is the closest IEEE 754 representation. Scientific notation is allowed. You can choose whether or not to allow a missing 0 in front of the ".".
x = 0x4000CCCCCCCCCCCD could be represented as "2.10000000000000008881784197001" but also as "2.1", which is much shorter. x = 0x3DDB7CDFD9D7BDBB can be represented as "1e-10" which is much shorter than alternative representation "1.0000000000000000364321973155E-10"
**Rules**
In addition to being correct, the program must run in a reasonable amount of time on a modern CPU, ruling out some forms of exhaustive search.
This being code-golf entries should be judged by concision, but voters should feel free to attribute points based on a discretionary judgment of elegance, and efficiency.
**A few test cases**
In these test cases, I represent the input as an hexadecimal number to make it clear that a IEEE 754 double 64 is passed. You can pass it as a double if the language supports it, or as a 64 bit integer, at your convenience.
```
f(0x4000CCCCCCCCCCCD) == "2.1"
f(0x3DDB7CDFD9D7BDBB) == "1e-10"
f(0x40934A456D5CFAAD) == "1234.5678" // N.B. not 1.2345678e3
f(0x3FEFFFFFFAA19C47) == "0.99999999"
f(0xC088A8CF13CEE9DD) == "-789.101112"`
```
[Answer]
# C - ~~47~~ 45 characters
Counting just the function `f`, and not including `#include`s and `main`.
In C, the `%g` `fprintf` specifier will always choose the shortest format. Add a precision specifier equal to the usual maximum precision of `double` and a bit of casting hocus-pocus to coerce `int64` to `double` and Bob's your uncle.
```
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
// The following line is what I'm counting...
f(int64_t u){printf("%.14g\n",*(double*)&u);}
int main()
{
assert(sizeof(int64_t) == sizeof(double));
f(0x4000CCCCCCCCCCCD);
f(0x3DDB7CDFD9D7BDBB);
f(0x40934A456D5CFAAD);
f(0x3FEFFFFFFAA19C47);
f(0xC088A8CF13CEE9DD);
return 0;
}
```
Output is as per specs:
```
2.1
1e-10
1234.5678
0.99999999
-789.101112
```
Summary: `C` rocks!
[Answer]
## Common Lisp - 138 bytes
```
(ql:quickload'(ieee-floats cl-ppcre))(lambda(x)(#1=ppcre:regex-replace"e0$"(#1#"\\.?d"(format()"~a"(ieee-floats:decode-float64 x))"e")""))
```
(138 = 101 for the actual function + 37 for quickload'ing libraries)
## Ungolfed
The default representation of floating-points in CL is already quite close to the requested output. However, there are some discrepancies. For example, double-precisions numbers are written with a `d` exponent character (e.g., `2.10d0`).
That is why I modify the output of the formatted string with regexes:
```
(ql:quickload '(ieee-floats cl-ppcre))
(lambda (x)
(cl-ppcre:regex-replace ; remove "e0" at end of string
"e0$"
(cl-ppcre:regex-replace ; change ".d" and "d" to "e"
"\\.?d"
(format nil "~a" (ieee-floats:decode-float64 x))
"e")
""))
```
## Example
```
;; NB: * is set by the REPL to the last returned value.
;; Here, we store the previously defined lambda:
(defparameter *fun* *)
;; Test cases
(defparameter *sample*
'(#x4000CCCCCCCCCCCD
#x3DDB7CDFD9D7BDBB
#x40934A456D5CFAAD
#x3FEFFFFFFAA19C47
#xC088A8CF13CEE9DD))
;; Default representation
(mapcar #'ieee-floats:decode-float64 *sample*)
=> (2.1d0 1.d-10 1234.5678d0 0.99999999d0 -789.101112d0)
;; Custom conversion
(mapcar *fun* *sample*)
=> ("2.1" "1e-10" "1234.5678" "0.99999999" "-789.101112")
```
## Round-trip
Here, we convert the printed representations back to IEEE-754 doubles.
```
;; read values as double-precision numbers
(let ((*read-default-float-format* 'double-float))
(mapcar #'read-from-string *))
=> (2.1 1.e-10 1234.5678 0.99999999 -789.101112)
;; Encode
(mapcar #'ieee-floats:encode-float64 *)
=> (4611911198408756429 4457293557087583675 4653144502051863213 4607182418709945415 13873524259458836957)
;; Check
(equal * *sample*)
=> T
```
[Answer]
# Julia, 20 characters
```
r(h)=hex2num(hex(h))
```
Function to test the results for correctness:
```
function decrep()
tests=[0x4000CCCCCCCCCCCD 0x3DDB7CDFD9D7BDBB 0x40934A456D5CFAAD 0x3FEFFFFFFAA19C47 0xC088A8CF13CEE9DD]
results=[2.1 1e-10 1234.5678 0.99999999 -789.101112]
for i=1:length(tests)
println("input : $(hex(tests[i]))")
println("result : $(r(tests[i]))")
println("expected: $(results[i])")
println("$(r(tests[i]) == results[i])")
end
end
```
Executing the test function:
```
julia> decrep()
input : 4000cccccccccccd
result : 2.1
expected: 2.1
true
input : 3ddb7cdfd9d7bdbb
result : 1.0e-10
expected: 1.0e-10
true
input : 40934a456d5cfaad
result : 1234.5678
expected: 1234.5678
true
input : 3feffffffaa19c47
result : 0.99999999
expected: 0.99999999
true
input : c088a8cf13cee9dd
result : -789.101112
expected: -789.101112
true
```
If the output absolutely has to be a string, then the solution would be:
```
s(h)=string(hex2num(hex(h)))
```
with 28 characters.
```
julia> h=0x4000cccccccccccd
0x4000cccccccccccd
julia> s(h)=string(hex2num(hex(h)))
s (generic function with 1 method)
julia> s(h)
"2.1"
```
Summary: Julia rocks, too ;)
] |
[Question]
[
The goal of this challenge is to write a program which takes a string (of any length) as input and displays anagrams (see [these examples](http://en.wikipedia.org/wiki/Anagram#Pseudonyms) of anagrams) of this string, made by taking words in a dictionary (either individually or in pairs), but the anagrams don't need to be perfect.
An anagram is the result of a rearrangement of a set of characters:
* `ABCD` and `CADB` are perfect anagrams, all the characters are present in both strings
* `ABCD` and `CADBEF` are imperfect anagrams because the characters `ABCD` are present in both strings but the characters `EF` only exist in the second string
The dictionary contains 1949 words:
```
ability
able
aboard
etc.
```
By taking each word and each pair of distinct words we generate a list of candidates to compare against the input:
```
ability
ability able
ability aboard
ability ...
able
able aboard
able ...
...
```
The program must display only the strings from the previous list which are anagrams of the input string. In other words, the program needs to filter the candidates down to the imperfect anagrams of the input.
# Examples
## Input
Sample:
```
> your_program 85 "Meta Code Golf" ./dict.txt
```
You may take input from any method you like, be it command line arguments or stdin.
## Expected output
```
ExCLAiMED FOOT
FrEEDOM LOCATe
```
(if I didn't make any mistake in my code)
# Rules
## Input:
```
n string filepath
```
(You may take input from any method you like, be it command line arguments or stdin)
* The first input will be an integer `n`. This is a threshold to define the minimum percentage of characters which must be present in the `string` input and the anagrams. `n` will be between `0` and `100`, inclusive
* The second input will be a string (a string with one or more words)
* The path to a file containing one word per line. The dictionary to use is available [here](http://pastebin.com/SgnN76Rn) (\*\*), it contains 1949 common words ([source](http://preshing.com/20110811/xkcd-password-generator/)). You have to save this file without the comments to keep one word per line
\*\*: I chose to use only 1949 common words because the dictionaries like [wamerican package](https://askubuntu.com/q/149125/229365) (with Ubuntu it adds the `/usr/share/dict/american-english` file) contains about 100,000 words, this would lead to 10,000,000,000 possible combinations of 2 words. It may take to much time to compute in the context of code golfing. But a program which works with 2,000 words may still work with 100,000 words if someone wants to use all the words from a complete dictionary.
## Output:
* One matching anagram string per line. The matching letters between the input string and the anagram must be displayed in uppercase, and the non-matching letters must be lowercase. In the example, only 2 of the 3 `e` are in uppercase, because there are only 2 `e` in `Meta Code Golf`
* You must not display the same anagram twice (eg. `ExCLAiMED FOOT` and `FOOT ExCLAiMED` are both valid but they are only the result of a swap between the 2 words)
## Other rules:
* Comparison between input string and anagrams:
+ Lower and upper-case characters are considered as the same character when searching the anagrams
+ Non-letter characters (space), `-`, etc. are considered as one character
* [Standard “loopholes”](http://meta.codegolf.stackexchange.com/q/1061/10619) are forbidden
* Shortest code wins
# Similarity index and threshold
## Similarity index:
The similarity index (**SI**) is calculated by counting the number of times each character from a string appear in another string. So we have to compute 2 SIs if the 2 strings have different lengths.
### Examples
`ABCD` and `CADB` are perfect anagrams, the characters are identical, the SI is 100%
`ABCD` and `CADBEF`:
- `ABCD` in `CADBEF`: the SI is 100% because all the characters of the first string exist in the second string
- `CADBEF` in `ABCD`: the SI is 4/6 because `ABCD` are present in the second string (and not `E` and `F`)
You have to ensure that you compare the input with the word **and** the word with the input, otherwise the word `AAABBBCCCDDDEEE (etc.)` may match the vast majority of the words. So we have to check that the 2 SIs are greater or equal than the threshold in order to *accept* an anagram.
### Example of SI function (pseudo-code):
```
function SI(a, b) {
s_i = 0
foreach (character in a) {
if (character exists in b) {
remove the character in b /* avoid to find several times "AAAA" in "A" */
s_i++
}
}
return(s_i / length(a))
}
```
## Threshold
The threshold acts as a filter to display only the anagrams which SI is greater or equal than the threshold.
To apply the threshold, we must use this function twice:
```
if ((SI(input, candidate) >= threshold) && (SI(candidate, input) >= threshold)) {/* anagram is ok */}
```
### Examples:
**Threshold = 100**
```
> program 100 "explanation" ./dict.txt
EXPLANATION
```
There is only one result because there is no perfect anagram for *Explanation*, except the word itself.
**Threshold = 90**
```
> program 90 "explanation" ./dict.txt
ALONE PAINT
EXPLAIN NOT
EXPLANATION
NATION PALE
```
**Threshold = 75**
```
> program 75 "explanation" ./dict.txt
AbLE cONTAIN
AbLE NATION
AbOuT EXPLAIN
AcT EXPLAIN
AcTION ALoNE
AcTION ANgLE
...
```
**Threshold = 0**
```
> program 0 "Meta Code Golf" ./dict.txt
AbILiTy
AbILiTy AblE
AbILiTy AbOard
AbILiTy AbOut
...
```
It will display all the words and all the combination of words from the dictionary (because all the SIs are greater or equal than the threshold).
## Random example
```
> program 85 "Beyonce Knowles" ./dict.txt
BEtWEEN COLONY
COWBOY SENtENcE
```
---
I was inspired by a french TV program named *Le Complot* where they make funny correlations between two unrelated persons, ideas, etc. For example, they showed that the soccer player [*Pastore*](http://youtu.be/DtKh8hcC1G4?t=1m25s) is an anagram of *Apotres* (the french word for *Apostles*) in order to link Zlatan Ibrahimovic to Catholic Church.
[Answer]
# Python 2, ~~375~~ ... 313
```
S=lambda a,b:1.*len([b.remove(q)for q in a if q in b])/len(a)
T=lambda a,b:min(S(a,b[:]),S(b,a[:]))
t,s,d=input()
d=open(d).read().split()
for x in{' '.join(sorted([a,b]))for a in d for b in d}|set(d):
q=list(s.lower())
if T(list(x),q)*100>=t:print''.join([w,w.upper()][q.count(w)and not q.remove(w)]for w in x)
```
This expects slightly different input; like so: `90, "explanation", "dict.txt"`. If that's not allowed, I'll fix it.
Sample run, with stdin `90, "explanation", "dict.txt"`:
```
EXPLANATION
NATION PALE
EXPLAIN NOT
ALONE PAINT
```
This works by iterating through a set of all the possibilities, checking them. This is what makes it so slow.
```
S=lambda a,b:1.*len([b.remove(q)for q in a if q in b])/len(a) # define the SI function
lambda a,b: # define a lambda with 2 inputs
b.remove(q)for q in a if q in b # for q in a, if q is in b, remove q from b
len([ ]) # list.remove returns None, so collect all the removes and the resulting list will have len of the number of times we removed things
1.*len([b.remove(q)for q in a if q in b])/len(a) # 1.* converts the len to a float, so that when we divide by len(a), we get a float
T=lambda a,b:min(S(a,b[:]),S(b,a[:])) # Determine the min SI for both possibilities
S(a,b[:]), # run S with a and a copy of b; since b gets removes called in S
S(b,a[:]) # run S with b and a copy of a
min(S(a,b[:]),S(b,a[:])) # get the min of those values
t,s,d=input()
d=open(d).read().split() # read the dict file and split it on newlines, creating a list of words
for x in{' '.join(sorted([a,b]))for a in d for b in d}|set(d): # iterate over possible word choices
[a,b] for a in d for b in d # create all possible pairs of words
sorted( ) # sort the list, making it so that ['exclaimed', 'foot'] and ['foot', 'exclaimed'] make the same element
' '.join( ) # combine the words with a space between
{ } # turn into set; this is a set comprehension
|set(d) # take the union of that set and the set of single words.
for x in : # this is what we iterate over
q=list(s.lower()) # we want to convert our string to lowercase, but we also want it as a list of characters because str doesn't have a remove function.
if T(list(x),q)*100>=t: # decide if the element of the set matches the threshold
print''.join([w,w.upper()][q.count(w)and not q.remove(w)]for w in x) # it does; now we print the correct output
[w,w.upper()] for w in x) # consider both the lower/uppercase versions of the char in the string
[q.count(w)and not q.remove(w)] # if w appears at least once in the target string, we remove it from the target string, and do a logical negation on the None, resulting in True ie 1, so we choose uppercase
''.join( ) # join these elements back into a string
print # print the result
```
[Answer]
# Python 3 - 447
Again, this is one of these programs that takes a long time to test, but I'll add one of the test cases once it's done.
```
from sys import*
l=argv
e=''
t=[]
v=list
n='\n'
g=open(l[3]).read()
def s(a,b):
m=0;a=list(a)
for i in a:
if i in b:b.remove(i);m+=1
return m/len(a)*100
for i in g.split(n):
for j in(n+g).split(n):
a=i+' '+j if j!=''else i
b=l[2].lower();c='';d=v(b);w=set(b.split(' '))
t=l[1]
if(s(a,d)>=t)and(s(d,v(a))>=t):
if not w in t:
for k in a:
if k in d:d.remove(k);c+=k.upper()
else:c+=k
t.append(w)
e+=c+n
print(e)
```
## Edit
The latest edit accounts for the rule that states that you must not print different arrangements of the two words.
[Answer]
# Perl 5 - 166 158 146 143
4 of the new line characters are added for clarity (those following a semicolon).
```
$s.=lc"+s/$_/uc\$&/e"for($i=pop)=~/[a-z]| (?!.* )/ig;
$/=pop;
$_=<>;
s!.+!"$&".join"
$& ",$'=~/^|.+/g!ge;
100*eval$s<$/*length($_|$i)||print"$_
"for split'
'
```
The array based candidate generation actually proved to be shorter than my original string substitution one. Kept the previous 153 version as its output order is exactly as in the examples (though it is not required).
```
$s.=lc"+s/$_/uc\$&/e"for($i=pop)=~/[a-z]| (?!.* )/ig;
$z=pop;
100*eval$s<$z*length($_|$i)||print"$_
"for map{map$&." $_"x!/^$&$/,@s=(@s,/.+/g)}<>
```
Usage:
```
perl ./a.pl 90 "explanation" <dict.txt
```
## Edit
This version should conform to the specification with regard to non letter characters.
[Answer]
# R - 512 (= 29!)
```
v=function(a){unlist(strsplit(tolower(a),""))}
s=function(a,b){
s=0;for(l in a){if(l%in%b){b=b[-(which(l==b)[1])];s=(s+1)}};s/length(a)}
r=function(v,j){p=c();for(l in v){if(l%in%j){j=j[-(which(l==j)[1])]
o=toupper(l)}else{o=tolower(l)};p=c(p,o)};cat(p,"\n",sep="")}
a=commandArgs(T);j=v(a[2]);k=(as.integer(a[1])/100);
d=scan(a[3],what='raw',sep="\n",quiet=T);
for(w in d){t=v(w);if((s(t,j)>=k)&&(s(j,t)>=k)){r(t,j)};
for(x in d[-1]){w2=paste(w,x,sep=" ");t=v(w2)
if((s(t,j)>=k)&&(s(j,t)>=k)){r(t,j)}};d=d[-1]}
```
## Ungolfed
```
get_array = function (a) {unlist(strsplit(tolower(a),""))}
# calculate similarity index of 2 strings
get_s = function (a, b) {
s = 0
for (letter in a) {
if (letter %in% b) {
b = b[-(which(letter == b)[1])]
s = (s + 1)
}
}
return(s / length(a))
}
# output
get_result = function (var_string, input) {
output = c()
for (letter in var_string) {
if (letter %in% input) {
input = input[-(which(letter == input)[1])]
o = toupper(letter)
}
else
{
o = tolower(letter)
}
output = c(output, o)
}
cat(o, "\n",sep="")
}
# get arguments
a = commandArgs(T)
input = get_array(a[2])
threshold = (as.integer(a[1]) / 100)
dict = scan(a[3], what='raw', sep="\n", quiet=T)
# iterate through all the words from the dictionary
for (w in dict)
{
t = get_array(w)
# the word only
if (
(get_s(t, input) >= threshold)
&&
(get_s(input, t) >= threshold)
)
{
get_result(t, input)
}
# the word + another word
for (x in dict[-1]) {
w2 = paste(w, x, sep=" ")
t = get_array(w2)
if (
(get_s(t, input) >= threshold)
&&
(get_s(input, t) >= threshold)
)
{
get_result(t, input)
}
}
dict = dict[-1] # remove the word once it has be permuted with all the other words
}
```
] |
[Question]
[
Consider 3 dimensional space which has been partitioned by at least two planes which go through the origin. If there are `n` planes then the number of distinct pyramidal regions this creates is exactly [`2 - n + n^2`](http://www.austms.org.au/Gazette/2006/Sep06/HoZ.pdf) as long as they are in "general position", a term I make specific below.
>
> The challenge is write code that will return one point per pyramidal region. That is to return `2 - n + n^2` points in 3d space, each of which is in a different pyramidal region.
>
>
>
Notice that a plane through the origin can be defined by a single vector starting at the origin which is orthogonal to the plane.
Your code should take a list of planes in as input, each plane being described by a vector from the origin which is orthogonal to it. The vector itself is just represented as a space separated list of three numbers. Your should output a list of `2 - n + n^2` points. You can assume the planes are in general position, that is that no three of the vectors defining the planes are coplanar.
I will verify that the points are really all in different pyramidal regions using the following code.
Let us assume the variable `planes` contains an array of vectors, each one of which defines the plane. For example, let n = 4, the `planes` could equal
```
[[ 0.44060338 -0.55711491 -0.70391167]
[ 0.15640806 0.89972402 0.40747172]
[-0.48916566 0.86280671 0.12759912]
[ 0.25920378 -0.94828262 0.18323068]]
```
We can then choose a number of points and put them in a 2d array called `testpoints`. To determine if they are all in distinct pyramidal regions we can call the following Python function which just looks to see which side of each plane the points are on and checks that each point is on at least one different side from every other point.
```
def all_in_distinct_pyramidal_regions(testpoints, planes):
signs = np.sign(np.inner(testpoints, hyperplanes))
return (len(set(map(tuple,signs)))==len(signs))
```
You can create some random test planes by first sampling points on a sphere and then using those points to define the hyperplanes. Here is a Python function that does this sampling.
```
import numpy as np
def points_on_sphere(N, norm=np.random.normal):
"""
http://en.wikipedia.org/wiki/N-sphere#Generating_random_points
"""
normal_deviates = norm(size=(N, 3))
radius = np.sqrt((normal_deviates ** 2).sum(axis=0))
points = normal_deviates / radius
return points
```
You can use any language you choose for which there is a free and easy way to run the code in Linux. You can use any standard libraries of that language. I will however want to test your code so please give full instructions for how to run it.
Code to produce 10 random points on a sphere can be run using <http://ideone.com/cuaHy5> .
Here is a picture of the 4 planes described above along with 2 - 4 + 16 = 14 points, one in each of the pyramidal regions created by the planes.

A valid output for this instance would therefore be the 14 points.
```
0.96716439 0.21970818 0.12775507
-0.84226594 -0.37162037 -0.39049504
0.60145419 0.58557551 -0.54346497
-0.4850864 0.26433373 -0.83355796
-0.69380885 -0.62124759 0.36425364
0.09880807 -0.09275638 0.99077405
0.19131628 -0.97946254 -0.06364919
-0.98100047 0.17593773 -0.08175574
-0.76331009 0.63554838 -0.11591362
0.89104146 0.34728895 0.29229352
-0.61696755 -0.26411912 0.74134482
0.18382632 -0.03398322 -0.98237112
-0.44983933 -0.18244731 0.87427545
0.8391045 0.18244157 -0.51246338
```
[Answer]
# Python, ~~423~~ ~~376~~ 353
```
S=sum
from numpy import*
C=cross
e=1e-15
def P(N,I,M):
if M:v=M[0];L=[C(n,v)for m in N for n in-m,m if all(dot(N,C(n,v))<e)];[P(N+[u*v],[i for i in I if all(dot(N+[u*v],i)<e)]+L,M[1:])for u in-1,1]if L else P(N,I,M[1:])
else:
for u in-1,1:print list(u*S(I))
N=map(array,input())
a,b=N[:2]
c=C(a,b)
for u in-1,1:P([a,u*b],[c,-c,C(a,c)+u*C(b,c)],N[2:])
```
Reads a list of comma-separated triplets from STDIN and writes a list of triplets to STDOUT.
Assumes at least two planes are given.
## Example
```
$ python cone.py <<< [0.44060338,-0.55711491,-0.70391167],[0.15640806,0.89972402,0.40747172],[-0.48916566,0.86280671,0.12759912],[0.25920378,-0.94828262,0.18323068]
[0.50892804716566153, 0.17353382779474077, -1.1968194626314141]
[-0.50892804716566153, -0.17353382779474077, 1.1968194626314141]
[0.1422280331828244, -0.62348456475000202, -0.24583080842150512]
[-0.1422280331828244, 0.62348456475000202, 0.24583080842150512]
[-1.2182327603643608, 0.1230166261435828, -1.5722574943149592]
[1.2182327603643608, -0.1230166261435828, 1.5722574943149592]
[-1.5849327743471977, -0.67400176640115994, -0.62126884010505024]
[1.5849327743471977, 0.67400176640115994, 0.62126884010505024]
[2.0938608215128593, 0.84753559419590085, -0.5755506225263638]
[-2.0938608215128593, -0.84753559419590085, 0.5755506225263638]
[1.7271608075300224, 0.050517201651157972, 0.37543803168354511]
[-1.7271608075300224, -0.050517201651157972, -0.37543803168354511]
[0.36670001398283714, 0.79701839254474283, -0.95098865420990886]
[-0.36670001398283714, -0.79701839254474283, 0.95098865420990886]
```
## How it works
Note that when three planes (whose normals are non-coplanar) partition the space, each of the eight resulting regions is bounded by (subsets of) all three planes.
If we added a plane, it would divide some of the regions in two, resulting, again, in a pair of subregions bounded by at least three planes.
Any cross-section of such a region is a polygon, whose vertices lie on the lines of intersection of the planes bounding the region.
Moreover, since these planes extend to infinity (as planes usually do), the polygon is necessarily convex, the upshot of which is that the region is closed under addition.
In particular, if we take one vector along each line of intersection of a pair of bounding planes that lies within the region, the sum of these vectors is also within the region and not on any of the planes (and, hence, not in any other region.)
The program recursively partitions the space by incrementally adding planes and subdividing the currently-explored region, while keeping a track of vectors along the lines of intersection and eventually taking their sum.
This method breaks if only two planes are given, since then there's only one line of intersection. We treat this as a special case and return the sum of a pair of vectors, each of which lies on a different plane, taking the four different sign combinations.
] |
[Question]
[
Your program will receive an ascii shape consisting of only underscores `_`, pipes `|`, spaces and newlines `\n`, which, together, represent a horizontally-aligned, right-angled shape. Together with this shape, on a new line, you will also receive either a positive or a negative integer, whose absolute value will be either one of `45`, `135`, `225` or `315` — signifying the degree that the original image should rotate. For instance:
```
_
| |_
|___|
-45
```
Your program's job is to rotate this shape the provided amount of degrees. Following are the example outputs, for all possible degrees, given the above provided example shape:
1. for 45° or -315°:
```
/\
/ /
\ \
\/
```
2. for 135° or -225°:
```
/\
/ \
\/\/
```
3. for 225° or -135°:
```
/\
\ \
/ /
\/
```
4. for 315° or -45°:
```
/\/\
\ /
\/
```
Remember though: the original shape above is just an example. Your program should be able to handle any shape constructed with said characters (within reason, of course — let's say: with a maximum of 100 x 100 characters).
The output of your program should be the rotated image, constructed with forward slashes `/`, backward slashes `\`, spaces and newlines.
Shortest code, after one week, wins.
Note: although this challenge offers many similarities with these [[1]](https://codegolf.stackexchange.com/q/20154/7657) [[2]](https://codegolf.stackexchange.com/q/5194/7657) two challenges, I think this one offers just enough variation (because the original image is not supposed to be rotated at 90° angles) for it to generate interesting new results.
[Answer]
# Python 2 - 285
```
import sys
l=list(sys.stdin)
L=len;R=range
r=L(l)-2
c=L(max(l,key=L))-2
k=r+c+1
d=int(l[-1])/90%4
a=d/2;x=a^d%2
z=1-x*2;t=1-a*2
m=[k*[' ']for i in R(k)]
for i in R(r+1):
for j in R(L(l[i])-1):m[a*c+x*r+z*i+t*j][r-a*r+x*c-t*i+z*j]=' \/'[ord(l[i][j])/40^d%2]
for s in m:print''.join(s)
```
I strongly suspect it can be golfed more, tips are welcome.
Examples:
```
% python r45.py <<< "||
_____
45"
/
\ /
\
\
\
\
% python r45.py <<< " _
| |_
|___|
-45"
/ \
/ \ /
/
\ /
\
```
If the 2nd one looks misaligned, that's because of some issues with the question:
First, the underscore is at the bottom of the character "cell", while the pipe, slash and backslash are all in the middle. It would be fairer to use a dash (-) instead of underscore.
Second, with the rotation of the heart in the question, you couldn't represent it in any reasonable way if the first line was `___` (3 underscores) instead of
`_`, as the 1st and 3rd underscore would be "capping" the pipes in the 2nd line.
Here's a better heart:
```
% python r45.py <<< " _
| |
| _
| |
___
-45"
/ \ / \
\ /
\ /
\ /
```
[Answer]
# Mathematica <225> 27
## Second Version
Strange as it may seem, both the input and output are ASCII,
"constructed with forward slashes /, backward slashes \, spaces and newlines"!
The command works by `Rotate`ing the text within the Mathematica environment, while leaving the string in ASCII. The output is directly editable, as is, with no additional keystrokes or commands required. However, it will not export directly as ASCII. It can, however be exported directly as an image, as I have done here.
```
inputString =
" _
| |_
|___|";
```
The following works by rotating the ASCII string on-screen.
```
s_~f~d_ := Rotate[s, -d Degree]
```
---
## Test Cases
```
f[s, 45]
f[s, -315]
```

---
```
f[s, 135]
f[s, -225]
```

---
```
f[s, -135]
f[s, 225]
```
## p3
```
f[s, 315]
f[s, -45]
```

---
[Answer]
**HTML/CSS/Javascript**
FIDDLE : <http://jsfiddle.net/c5h2d/1/>
```
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
function rotate(){
var x = document.querySelector("#i").value, y = document.querySelector("#t").value; document.querySelector("#a").innerHTML = y ;
document.getElementById("a").style.transform = "rotate("+x+"deg)"
}
</script>
<style type="text/css">
#a{
transform:rotate(45deg);
position:absolute;
top:50%;
left:50%
}
</style>
</head>
<body>
<pre id="a"></pre>
<textarea id=t cols="30" rows="10"></textarea>
<input type="text" id=i /><button onclick='rotate()'>Rotate</button>
</body>
</html>
```
] |
[Question]
[
An undecidable set is a set for which determining whether an object is an element of the set is an [undecidable problem](http://en.wikipedia.org/wiki/Undecidable_problem)
Write a program which runs forever, printing the elements of any undecidable set, each element appearing on its own line. For any element in the set, there must be a finite amount of time after which your program will print that element. Each element should only be printed once.
Since you have to enumerate the elements, the set you choose will be [RE](http://en.wikipedia.org/wiki/RE_%28complexity%29).
Some examples of undecidable sets which are RE:
* Programs of any Turing-complete language which halt.
* [Post correspondence problem](http://en.wikipedia.org/wiki/Post_correspondence_problem) instances with solutions.
* Sets of [Wang tiles](http://en.wikipedia.org/wiki/Wang_tile) which can't tile the plane.
[Answer]
### Haskell, 404 characters
This Haskell program prints all [FRACTRAN](https://en.wikipedia.org/wiki/FRACTRAN) programs which halt when given the input `2`. (The syntax of a FRACTRAN program is a list of positive rational numbers.)
```
import Data.Ratio
import Data.List
import Data.Either
r=do
z<-[1..]
let r=repeat z
(p,q)<-zip r[1..z]++zip[1..z]r
if gcd p q==1 then[p%q]else[]
o l=d[map(:xs)r|xs<-l]
e p n=n:maybe[](e p)(find((==1).denominator)$map(*n)p)
h p=map Left(e p 2)++[Right p]
main=mapM print$rights$d$map h$d$iterate o[[]]
d=concat.s
s[]=[]
s([]:b)=s b
s((x:a):b)=[x]:z a(s b)
z[]b=b
z a[]=map(:[])a
z(x:a)(y:b)=(x:y):z a b
```
I have made no great effort to compress this program. Furthermore, the GCD test in the definition of `r` is purely an optimization (it avoids duplicates).
(Also, If you are interested in running it, be sure to compile it, perhaps with optimization; I found that running it in `ghci` quickly consumed gigabytes of memory.)
It operates by successively constructing infinite lists of infinite lists and then flattening them in a diagonal order: the list of all positive rational numbers, the list of all lists of positive rational numbers (all programs), and the list of all evaluation states (including “halted”) of all programs. We then print only the halted states (which are annotated with the program which halted).
Here is the uncompressed and commented version:
```
import Data.Ratio
import Data.List
import Data.Either
-- List of all positive rational numbers
rationals = do
limit <- [1..]
let r = repeat limit
(p,q) <- zip r [1..limit] ++ zip [1..limit] r
if gcd p q == 1 then [p%q] else []
-- List of all lists of positive rational numbers (all FRACTRAN programs)
programs = diagonal $ iterate oneMore [[]]
oneMore l = diagonal [map (:xs) rationals | xs <- l]
-- FRACTRAN evaluator
evalStep p n = find ((== 1) . denominator) $ map (* n) p
evaluation p n = n : maybe [] (evaluation p) (evalStep p n)
evaluationWithHaltMarker p = map Left (evaluation p 2) ++ [Right p]
-- All evaluation states of all programs
evaluations = diagonal $ map evaluationWithHaltMarker programs
-- All halting programs
haltingPrograms = rights evaluations
main = mapM_ print haltingPrograms
-- from http://stackoverflow.com/questions/7141287/haskell-cartesian-product-of-infinite-lists
diagonal :: [[a]] -> [a]
diagonal = concat . stripe
where
stripe [] = []
stripe ([]:xss) = stripe xss
stripe ((x:xs):xss) = [x] : zipCons xs (stripe xss)
zipCons [] ys = ys
zipCons xs [] = map (:[]) xs
zipCons (x:xs) (y:ys) = (x:y) : zipCons xs ys
```
The `Left` values are never actually looked at since we don't care about non-halting states; it's just the shortest way I saw to carry through the incremental evaluation.
Some “future work” if one were trying to write a practical implementation to generate interesting programs, rather than golfing, would be to reduce the needed work by restricting the set of programs under consideration to those which:
* do not have a statically obvious loop (e.g. an integer).
* are unique under “register renaming”; e.g. [3/2, 5/3] is the same as [7/2, 5/7].
* have no dead code under the assumption that the input is 2; e.g. in [5/3, 7/2], 5/3 is dead code because no 3s are in numerators.
* have no dead code due to preceding code; e.g. in [3/2, 5/2], 3/2 will always take precedence over 5/2.
I mention these cases in particular because (other than the looping one) they form the majority of the output. As far as I've run it, it has not produced any output program of length greater than 2.
[Answer]
### Haskell, 232 characters (with line breaks removed)
This Haskell program prints all solvable Post correspondence problems over the alphabet {A, B}. (Actually, it prints only the ones that actually use every tile at least once. But this shouldn't affect the undecidability of the set.) Each set of tiles is sorted (using Haskell's `sort` function; I don't know how that works on lists of tuples of strings, but it does) and de-duplicated (using `nub`), and the entire list of solutions is de-duplicated as well.
It works by generating all strings, and then, for each string and for each number `n` up to twice the length of the string plus one, generating all pairs of ways to break the string into `n` pieces. The `d` function generates all ways to break a string `s` into a number `n` of pieces. The program takes advantage of the fact that in Haskell, `do` notation on lists simulates non-deterministic choice.
(If I'm not mistaken, "twice the length of the string plus one" is the greatest number of distinct tiles a string can serve as a solution string for. For example, "AB" is a solution string for ("","A"), ("","B"), ("A",""), ("B",""), ("","").)
The `sequence` command, as used right after `s <-` (but not as used right after `main =`), returns all ways of selecting one element from each of a list of lists; for example, `sequence ["abc", "123"]` is `["a1", "a2", "a3", "b1", "b2", "b3", "c1", "c2", "c3"]`.
```
import Data.List;
main=sequence.map print.nub$do{
n<-[1..];
s<-sequence$replicate n"AB";
p<-[1..n];
u<-d p (s*2+1);
v<-d p (s*2+1);
return.nub.sort$zip u v
};
d 0""=[[]];
d 0_=[];
d n s=do
f<-[0..length s];
c<-d(n-1)(drop f s);
return(take f s:c)
```
With the line breaks, this is 246 characters, but all of the line breaks can be removed.
] |
[Question]
[
The cow and chicken problem is a traditional problem for introducing young students to the concept of systems of equations. It goes as follows:
>
> A farmer raises cows and chickens on his farm. His animals have a total of 24 heads and 68 legs. How many cows and how many chickens does he have?
>
>
>
The numbers of heads `h` and legs `l` can vary, but the idea of the problem is the same. This problem can't be solved by plugging in a one-variable formula; both variables (the number of cows `k`, and the number of chickens `x`) will always be involved in each formula that you can derive directly.
That being said, for this version of the problem, there is a formula `k = l/2 - h` that you can readily use to obtain the solution of `10` cows and `14` chickens, so it's not *too* interesting.
Here's a slightly different problem, this time involving cows and chickens who can have a different number of heads and legs.
Your task is to build a program that takes the following inputs (all positive integers):
* hk, the number of heads a cow has.
* lk, the number of legs a cow has.
* hx, the number of heads a chicken has.
* lx, the number of legs a chicken has.
* h, the total number of heads.
* l, the total number of legs.
: and output `k` and `x`, how many cows and chickens the farmer has.
However, depending on the input given, the problem has several states of solvability:
1. There is a solution in the nonnegative integers. The input `1 4 1 2 24 68` (which is the problem above) has the solution `10 14`.
2. There is no solution in the nonnegative integers, but there is one in the nonnegative fractional numbers. The input `1 4 1 2 24 67` is an example of this, with a solution of `9.5 14.5`.
3. There is no solution in the nonnegative numbers, but one in the integers in general. The input `1 4 1 2 24 36` is an example of this, with a solution of `-6 30`.
4. There is no solution in either the nonnegative fractional numbers or the integers in general, but one in the real numbers in general. The input `1 4 1 2 24 97` is an example of this, with a solution of `24.5 -0.5`.
5. There is no solution at all. The input `2 4 1 2 24 68` is an example of this.
6. There are multiple solutions in the positive integers (and therefore infinitely many solutions in the real numbers). The input `2 4 1 2 24 48` is an example of this. If there is exactly one solution in the positive integers but infinitely many solutions in the real numbers (as is the case with the input `6 9 4 6 10 15` with a solution of `1 1`), your solution can treat it as a case of this state.
Your program, given the inputs, must first output which state of solvability the problem has. Only if the problem is in the *first* state of solvability should you output how many cows and chickens there are, as any other solution is considered an "invalid problem".
The shortest code to do all of the above in any language wins.
[Answer]
## Python 2, 138
```
a,A,b,B,h,l=input()
d=a*B-b*A
k=B*h-b*l
c=a*l-A*h
if d:K=k/d;C=c/d;z=K>=0<=C;print[[3,[1,K,C]][z],4-2*z][k%d+c%d!=0]
else:print(0==c==k)+5
```
Expects comma seperated input. The inputs
```
1, 4, 1, 2, 24, 68
7, 14, 9, 6, 25, 18
1, 4, 1, 2, 24, 67
1, 4, 1, 2, 24, 36
1, 4, 1, 2, 24, 97
2, 4, 1, 2, 24, 68
2, 4, 1, 2, 24, 48
```
yield the (admittedly not very nicely formatted) answers
```
[1, 10, 14]
2
2
3
4
5
6
```
[Answer]
# Mathematica ~~359~~ 314
About 200 characters went into determining which condition applies.
```
f@{a_, b_, c_, d_, i_, l_} :=
Module[{s, t, z = "invalid problem", y = IntegerQ},
t@n_ := y@n \[And] (n > 0);
p@n_ := n \[Element] Rationals \[And] n > 0;
q@n_ := n \[Element] Reals;
w = Flatten@Quiet@Solve[{d*x + b*k == l, c*x + a*k == i}, {k, x}];
s = {k, x} /. w;
Which[w == {}, {5, z},
Length[w] != 2, {6, z},
True, If[And @@ (t /@ s), {1, s},
Which[
And @@ (p /@ s), {2, z},
And @@ (y /@ s), {3, z},
And @@ (q /@ s), {4, z},
3 == 3, {7, z}]]]]
f[{1, 4, 1, 2, 24, 68}]
f[{7, 14, 9, 6, 25, 18}]
f[{1, 4, 1, 2, 24, 67}]
f[{1, 4, 1, 2, 24, 36}]
f[{1, 4, 1, 2, 24, 97}]
f[{2, 4, 1, 2, 24, 68}]
f[{2, 4, 1, 2, 24, 48}]
f[{1, 4, 1, 2, -23, (3 + I)^2/(5 - I)}]
f[{6, 9, 4, 6, 10, 15}]
```
>
> {1, {10, 14}}
>
> {2, "invalid problem"}
>
> {2, "invalid problem"}
>
> {3, "invalid problem"}
>
> {4, "invalid problem"}
>
> {5, "invalid problem"}
>
> {6, "invalid problem"}
>
> {7, "invalid problem"}
>
> {6, "invalid problem"}
>
>
>
**How it works**
The equations `d*x+b*k==l`and `c*x+a*k==i` express the constraints in the general cow and chickens problem,where
>
> a is "the number of heads per cow"
>
> b is "the number of legs per cow"
>
> c is "the number of heads per chicken"
>
> d is "the number of legs per chicken"
>
> i is "the number of heads"
>
> l is "the number of legs"
>
> k is "the number of cows"
>
> x is "the number of chickens".
>
>
>
`Solve` returns the real - valued solutions, if any exist, for the cows and chickens, as a list of 2 substitution rules, e.g.
`{k->10, x-> 14}`
If no solutions exist, an empty list is returned.
If the data cannot be processed, Solve will return a different number of elements.
The tests are performed in the following order.
* If there are 0 solutions, condition 5 is satisfied
* If the list of "solution"s has anything other than 2 elements, then condition 6 is satisfied .
* If there are 2 solutions, then
+ if function t yields True, the solution is a pair of non-negative integers, and condition 1 is satisfied.
+ if function p yields True, the solution is a pair of non negative rationals and condition 2 is satisfied.
+ if function q yields True, the solution is a pair of non negative rationals and condition 3 is satisfied.
+ if function y yields True, the solution is a pair of integers and condition 4 is satisfied.
+ Otherwise, condition 7 is satisfied.
**Minor Variant of f**
```
g@{a_, b_, c_, d_, i_, l_} :=
Module[{s, t, z = "invalid problem", y = IntegerQ},
t@n_ := y@n \[And] (n > 0);
p@n_ := n \[Element] Rationals \[And] n > 0;
q@n_ := n \[Element] Reals;
w = Flatten@Quiet@Solve[{d*x + b*k == l, c*x + a*k == i}, {k, x}];
s = {k, x} /. w;
Which[w == {}, {5, z, w}, Length[w] != 2, {6, z, w}, True,
If[And @@ (t /@ s), {1, s, w},
Which[And @@ (p /@ s), {2, z, w}, And @@ (y /@ s), {3, z, w},
And @@ (q /@ s), {4, z, w}, 3 == 3, {7, z, w}]]]]
```
`g` is f` with the additional property that it returns the output of Solve.
```
g[{1, 4, 1, 2, 24, 68}]
g[{7, 14, 9, 6, 25, 18}]
g[{1, 4, 1, 2, 24, 67}]
g[{1, 4, 1, 2, 24, 36}]
g[{1, 4, 1, 2, 24, 97}]
g[{2, 4, 1, 2, 24, 68}]
g[{2, 4, 1, 2, 24, 48}]
g[{1, 4, 1, 2, -23, (3 + I)^2/(5 - I)}]
g[{6, 9, 4, 6, 10, 15}]
```
>
> {1, {10, 14}, {k -> 10, x -> 14}}
>
> {2, "invalid problem", {k -> 1/7, x -> 8/3}}
>
> {2, "invalid problem", {k -> 19/2, x -> 29/2}}
>
> {3, "invalid problem", {k -> -6, x -> 30}}
>
> {4, "invalid problem", {k -> 49/2, x -> -(1/2)}}
>
> {5, "invalid problem", {}}
>
> {6, "invalid problem", {x -> 24 - 2 k}}
>
> {7, "invalid problem", {k -> 615/26 + (19 I)/26, x -> -(1213/26) - (19 I)/26}}
>
> {6, "invalid problem", {x -> 5/2 - (3 k)/2}}
>
>
>
Problems falling under condition 6 have multiple solutions, as evidence by the equations. The problem that falls under condition 5 returns an empty set (no solutions).
Note: `element` and `and` are single characters in Mathematica.
[Answer]
### GolfScript, 105 101 characters
```
{](=}+1360222640 6base%4/{~*@@*-}%.2=0<{{~)}%}*).{1${1$%0>}%~|2${0<}%~|.++.)p!{{/}+%p}*;;}{;~|!5+p}if
```
A first (and rather clumsy) approach using GolfScript.
The test cases ([see online](http://golfscript.apphb.com/?c=ewoKe10oPX0rMTM2MDIyMjY0MCA2YmFzZSU0L3t%2BKkBAKi19JS4yPTA8e3t%2BKX0lfSopLnsxJHsxJCUwPn0lfnwyJHswPH0lfnwuKysuKXAhe3svfSslcH0qOzt9ezt%2BfCE1K3B9aWYKCn06QzsKCjsKIjEgNCAxIDIgMjQgNjgiICI%2BICIxJCtwdXRzIEMgIiJwdXRzCiIxIDQgMSAyIDI0IDY3IiAiPiAiMSQrcHV0cyBDICIicHV0cwoiMSA0IDEgMiAyNCAzNiIgIj4gIjEkK3B1dHMgQyAiInB1dHMKIjEgNCAxIDIgMjQgOTciICI%2BICIxJCtwdXRzIEMgIiJwdXRzCiIyIDQgMSAyIDI0IDY4IiAiPiAiMSQrcHV0cyBDICIicHV0cwoiMiA0IDEgMiAyNCA0OCIgIj4gIjEkK3B1dHMgQyAiInB1dHMKCg%3D%3D&run=true)):
```
> 1 4 1 2 24 68
1
[10 14]
> 1 4 1 2 24 67
2
> 1 4 1 2 24 36
3
> 1 4 1 2 24 97
4
> 2 4 1 2 24 68
5
> 2 4 1 2 24 48
6
```
[Answer]
# J - 124 characters
(excluding the assignment)
Reduced the "invalid problem reporting" clutter (154 -> 124).
```
chico =: ((>:@],(#"1~-.@*))#.@(0&>,&(>./)(~:<.)) ::({&0 4 5@#))~@(({:%.}:)@; ::(":@(11-#@~.@;@:(%/&.>))))@(((0 2,:1 3);4 5)&({&.>;~))
```
tests:
```
t =: ,. 1 4 1 2 24 68;1 4 1 2 24 67;1 4 1 2 24 36 ;1 4 1 2 24 97;2 4 1 2 24 68;2 4 1 2 24 48
chico &.> t
NB. outputs:
+-----------------+
|1 10 14 |
+-----------------+
|2 |
+-----------------+
|3 |
+-----------------+
|4 |
+-----------------+
|5 |
+-----------------+
|6 |
+-----------------+
```
un-golfed version + comments
```
NB. Print case and the solution if the state is 0.
print =: (>:@],(#"1~-.@*))
NB. 0 1 2 3 considering binary coding based on positivity and fractionality of
NB. all (>./) elements of the solution. If error caused by a string, then choose 4
NB. or 5 based on length of the string passed.
case =: #.@(0&> ,&(>./) (~:<.)) :: ({&0 4 5@#)
NB. Solve, if error, determine whether multiple solutions exist, then output
NB. '10' else output '9' (just for having length 1 or 2 strings)
solve =: ({:%.}:)@; ::(":@(11-#@~.@;@:(%/&.>)))
NB. Parse input list to obtain matrix and rhs of the system to solve.
format =: (((0 2,:1 3);4 5)&({&.>;~))
NB. Piece the bricks together:
chico_ng =: (print case)~ @ solve @ format
NB. testcases and solutions:
t=: (,.1 4 1 2 24 68;1 4 1 2 24 67;1 4 1 2 24 36;1 4 1 2 24 97;2 4 1 2 24 68;2 4 1 2 24 48)
sols =: ,. 1 10 14 ; (1$2) ; (1$3) ;(1$4) ;(1$5);(1$6)
(sols -: chico_ng each t) # 'fail','pass'
+----+
|pass|
+----+
```
[Answer]
# C - ~~181~~ 177 characters
```
a,b,c,d,e,f,g,j;main(){scanf("%d%d%d%d%d%d",&a,&b,&c,&d,&e,&f);g=b*c-a*d;a=b*e-a*f;b=c*f-d*e;j=g?2*(b*g<0||a*g<0)+(b%g&&a%g):b||a?4:5;putchar(j+49);j||printf(" %d %d",b/g,a/g);}
```
Just a rough sketch, I should be able to get it down to around 150 characters with some massage.
] |
[Question]
[
Your program reads from standard input and prints to standard output.
The first thing you'll be receiving on stdinput will be the ruleset for your firewall (until you encounter a double newline).
We'll start explaining **the ruleset** itself with some sample input:
```
/* header abbreviations added for demonstration purposes only */
/> Allow (A) or Block (B)
|
| /> Source (incl. mask)
| |
| | /> Destination (incl. mask)
| | |
| | | /> Source port(s)
| | | |
| | | | /> Destination port(s)
| | | | |
A 192.168.1.0/24 0.0.0.0/0 1024:65536 80
A 0.0.0.0/0 192.168.1.0/24 80 1024:65536
A 192.168.1.1/32 0.0.0.0/0 80 1024:65536
A 0.0.0.0/0 192.168.1.1/32 1024:65536 80
B 0.0.0.0/0 0.0.0.0/0 * *
```
* Rules are processed in cascading order. Once you find a matching rule, determine the outcome and stop processing.
* If a packet does not match any given rule, block it (sane defaults).
* Elements of a rule are single-space delimited.
* Source and destination adresses will provide a netmask. Be sure to filter accordingly.
* The specification of the source and destinations ports must support the following syntax:
1. Single ports: e.g. "80"
2. Inclusive port ranges: e.g. "1024:65536"
3. All ports: e.g. "\*"
* You may assume input to be well-formed.
After the double newline, you'll receive (one or more) newline seperated **input packets** to test according to the ruleset you've now acquired.
Some sample input for the packets to clarify:
```
/* header abbreviations added for demonstration purposes only */
/> Source
|
| /> Source port
| |
| | /> Destination
| | |
| | | /> Destination port
| | | |
192.168.1.18 1036 157.136.122.5 22
157.136.108.8 2400 192.168.1.1 80
```
You'll examine these input packets and determine the outcome of filtering according to the rules.
The above sample input (ruleset + packets) should thus yield the following output:
```
BLOCK 192.168.1.18 1036 157.136.122.5 22
ALLOW 157.136.108.8 2400 192.168.1.1 80
```
The output is basically no more than 'BLOCK' or 'ALLOW' followed by a space and the verbatim input line.
**Some varia:**
* This is code golf, the shortest (source code, by byte count) solution wins. Have fun!
* You are not allowed to use specific IP address handling features of your language.
* Specialized languages for routing or firewalling will be excluded from contending for first place (if they exist).
* If any part of the question is ambiguous or in need of further clarification, feel free to comment.
[Answer]
## Haskell, 356 characters
```
main=interact$f.break null.lines;f(r,_:p)=unlines$map(foldr(g.w)(j"B"++)r)p
g[r,s,d,a,b]n x|and$zipWith3($)(cycle[k.('/'#),q.(':'#)])[s,a,d,b]$w x=j r++x|t=n x
k[y,z]x=y%z==x%z;y%z=foldl((.r).(+).(*256))0('.'#y)`div`2^(32-r z)
q["*"]x=t;q[y]x=x==y;q[a,b]x=r x>=r a&&r x<=r b
d#x=w$map(d?)x;d?x|d==x=' '|t=x;j"A"="ALLOW ";j"B"="BLOCK ";t=1<3;r=read;w=words
```
[Answer]
# Perl 561
First try. Any tips?
```
[gary@phoenix ~]$ cat test | perl f2.pl
BLOCK 192.168.1.18 1036 157.136.122.5 22
ALLOW 157.136.108.8 2400 192.168.1.1 80
sub r{($i,$j)=split'/',shift;$j eq 0?'*':map$h.=sprintf("%.8b",$_),split/\./,$i;
substr$h,0,$j}sub s{$_[0]=~/(\d+):(\d+)/?$1<$_[1]&& $_[1]<$2:$_[0]==$_[1]}sub
t{chomp;($a,$b,$c,$d,$e)=split/ /}sub o{$_[0]eq'*'or$_[0] eq
substr&r($_[1].'/32'),0,length$_[0]}sub p{$_[0]eq'*'or&s($_[0],$_[1])}
map((/^[AB]/?(t,push@f,join' ',($a,&r($b),&r($c),$d,$e)):push@g,$_),<STDIN>);
push@f,"B * * * *\n";for $q(@g){if($q=~/[0-9]/){($k,$l,$m,$n)=split/ /,$q;
for(@f){&t;$a=$a=~/^A/?'ALLOW':'BLOCK';&o($b,$k)&& &o($c,$m)&& &p($d,$l)&&
&p($e,$n)?print"$a $q":next;last}}}
```
[Answer]
# Ruby (384)
Not sure it's 100% correct, but works at least for the given example inputs. Propably could be made a bit shorter too.
```
$ wc gc4907-firewall.rb
9 15 384 gc4907-firewall.rb
$ cat fwinput| ruby gc4907-firewall.rb
BLOCK 192.168.1.18 1036 157.136.122.5 22
ALLOW 157.136.108.8 2400 192.168.1.1 80
```
```
q=->x{x.gsub(/(\d+)\.?/){'%02x'%$1}.hex}
w=->x{u=x.scan(/[\d.]+\/\d+/)
p=$'.split.map{|z|z=="*"?->y{1}:(z=eval z.sub(?:,'..');->y{z===y.to_i})}
f=u.map{|z|a,m=z.split ?/;a=q[a]>>(m=32-m.to_i);->y{a==q[y]>>m}}.zip(p).flatten
->y{f.zip(y.split).all?{|z,c|z[c]}&&x[0]}}
s=[]
while gets=~/./;s<<w[$_];end
s<<->x{0}
$<.map{|p|s.map{|f|(f=f[p])&&(puts (f=="A"?"ALLOW ":"BLOCK ")+p;break)}}
```
$' seems to confuse both brace matching in emacs, and syntax highlight here.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/4773/edit).
Closed 3 years ago.
[Improve this question](/posts/4773/edit)
A program that randomly generates a Sudoku game board with varying degrees of difficulty (however you decide to measure difficulty). Sudoku requires that there is only one solution, so your program should too. Input and output can be any form or method of your choosing.
**Judging**
Fastest code. Tested on a quad-code Windows 7 machine with freely or easily available compiler. Provide link if necessary.
[Answer]
# Scheme
Why should I be constrained on the platform used? Especially on such a developer-unfriendly platform as Windows! Anyways... doesn't matter since this code compiles on all Scheme implementations that provide the standard libraries srfi-1, srfi-27 and srfi-43 (that means almost all of them), on virtually (pun intended) every platform. The only non-portable-across-all-implementatons construct I use is "import", but I might as well have used "use" or "require" among others. This minor incompatibility between implementations will be fixed this year, don't worry.
Because of the holy wars pertaining to the Lisp family of languages on the matters of minimalism, the last standard in final status (R6RS) was rejected by most implementors, prefering instead to stick to R5RS until the steering comitee broke up. They came up with the idea to split the language in two, the first being a minimalistic core (assigned to working group 1). The second will be a superset of the first which will better suit daily usage. Both will form R7RS, which will be released this year. This will solve many incompatibilities between implementations.
```
;; Sudoku generator (v0.2)
;; list ops randomness vector ops
(import srfi-1) (import srfi-27) (import srfi-43)
(define rand (random-source-make-integers
default-random-source))
(define (shuffle! vec)
(let swap! ([n (vector-length vec)])
(let* ([i (rand n)] [n (- n 1)])
(when (> n 1) (vector-swap! vec n i) (swap! n)))))
(define (make-row)
(let ([row (vector-unfold (lambda (i) (+ i 1)) 9)])
(shuffle! row) row))
(define (make-rows)
(let f ([i 8] [r (make-row)])
(cons r
(if (zero? i) (list)
(f (- i 1) (vector-copy r 1 10 (vector-ref r 0)))))))
(define (split-in ls n)
(let ([n (quotient (length ls) n)])
(let f ([ls ls])
(if (null? ls) ls (cons (take ls n) (f (drop ls n)))))))
(define (make-grid)
(let ([g (list->vector
(map list->vector
(zip (split-in (make-rows) 3))))])
(shuffle! g) (vector-for-each shuffle! g)
(vector-concatenate (vector->list g))))
```
Difficulty: none
I felt the code was too complicated so I rewrote it from scratch. For clue pruning, I am currently working on encoding the board in CNF notation. Since I have access to the original grid, testing for uniqueness is easier. Pruning is done by priority (we prefer to prune cells who maximize the number of possibilities in its surroundings).
So far, this only generates a valid complete grid using only a vector of numbers from 1 to 9 that swaps each index with a random index. This random row is used to derive the other rows by successive rotation. This works because there are only 8 other possible rows, given one sudoku row.
Thus, so far we have ensured there are no row or column conflicts possible. As a matter of fact, the sudoku is based on latin squares which are roman grids of size n\*n (a square) which must have unique numbers on every row and column in the range 1 to n. A sudoku is a latin square of size 9\*9, with an added constraint: regions.
The next step is to split the list of rows in 3, which now looks like this, given an initial row of (1 2 3 4 5 6 7 8 9):
```
;; this is a latin square
(((1 2 3 4 5 6 7 8 9)
(2 3 4 5 6 7 8 9 1)
(3 4 5 6 7 8 9 1 2))
((4 5 6 7 8 9 1 2 3)
(5 6 7 8 9 1 2 3 4)
(6 7 8 9 1 2 3 4 5))
((7 8 9 1 2 3 4 5 6)
(8 9 1 2 3 4 5 6 7)
(9 1 2 3 4 5 6 7 8)))
```
Given a grid like that, I can "zip" the lists (perform matrix transposition) so that it now looks like this:
```
;; this is now a sudoku
(((1 2 3 4 5 6 7 8 9)
(4 5 6 7 8 9 1 2 3)
(7 8 9 1 2 3 4 5 6))
((2 3 4 5 6 7 8 9 1)
(5 6 7 8 9 1 2 3 4)
(8 9 1 2 3 4 5 6 7))
((3 4 5 6 7 8 9 1 2)
(6 7 8 9 1 2 3 4 5)
(9 1 2 3 4 5 6 7 8)))
```
Magic! No row, column or region conflicts! What needs to be done next is to shuffle the three lists of rows, and the three rows within them. To do that, we convert all lists to vectors, then reuse the same shuffle procedure used with the first row. The last step is to collapse everything back to a grid of 9 rows.
I will post updates later. I am currently more advanced than this, but the rest is still in development (I promise you the cleverness and simplicity of my algorithms will surprise you). This was not done in one day, but with great amounts of research for optimal algorithms.
] |
[Question]
[
A program should take an input on stdin, and guess what a word might be. It should run as a session. One example session is shown below. Characters are fed to it, with a \* for a letter not revealed; it should remember letters already revealed. It shows possible words in a list if the total number words found is less than 20, otherwise it shows the count of words.
I recommend `/usr/share/dict/words` on any Linux/Unix for the list of words, or your favourite word list on other platforms.
**Example session (yours may vary):**
```
>>> *****
6697 matches
>>> G****
312 matches
>>> *u***
Trying Gu***
35 matches
>>> Gu**s
Gus's
Guy's
guess
gulfs
gulls
gulps
gum's
gun's
gurus
gusts
gut's
guy's
12 matches
>>> **e**
Trying Gue*s
Is it "guess"?
```
[Answer]
## Bash (171)
```
#!/bin/bash
s=`cat /dev/stdin | sed 's/\*/\./g'`;o=`cat /usr/share/dict/words | grep -x $s`;w=`echo "$o" | wc -l`;if [ $w -lt '20' ]; then echo "$o";fi;echo "$w match(es)"
```
[Answer]
## Perl, 170 chars
```
open W,'</usr/share/dict/words';@D=<W>;
while(<>){@W=split//,$w;$w&&s/\*/$W[$-[0]]/ge;y/*/./;$w=$_;
($r=@R=grep/^$w$/i,@D)<20&&map{print}@R;print$r." matches\n";$r<2&&last}
```
Added (not counted) newlines for clarity.
[Answer]
## PHP, 302
```
<?system('stty -icanon');$i=0;$s=explode(PHP_EOL,file_get_contents('/usr/share/dict/words'));while(1){$q.=fread(STDIN,1);system('clear');$x=0;$a='';$i++;for($j=0;$j<count($s);$j++){if(!strncasecmp($q,$s[$j],$i)){$x++;$a.="\n$s[$j]";}}echo str_pad($q,20,'*');echo$x<=20?"\n$a":'';echo"\n$x matches\n";}
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/200354/edit).
Closed 3 years ago.
[Improve this question](/posts/200354/edit)
**[ CODE GOLF]**
---
# BAM! - Fire and Smoke
**Your Oscilloscope has exploded from one too many waves.**
---
Re-create these waves assuming the following:
* All waves are **Sine Waves**
* An amplitude of **`1`** spans **`3 lines`** (*Therefore and amplitude of `2` would span `5 lines`*) *[Vertically]*
* We want to see **`100`** characters worth of sine (*Can be any char*) *[Horizontally]*
* **`12`** characters per Period is a frequency of **`1Hz`**
```
[Amplitude of 1 and Frequency of 1Hz with a Span of 45 Characters]
>SinASCII('a1','f1')
... ... ... >
... ... ... ... ... ... ... >[cont. for 100 char]
... ... ... >
```
---
# Inputs
Inputs can be in any format but must be explicitly stated if different from standard (*below*) and must contain:
* Amplitude
* Frequency
**Test inputs:** `[('a2', 'f0.5'), ('a4', 'f1'), ('a6', 'f2'), ('a1','f0.25')]`
---
## This is a CODE GOLF Challenge
**Some Clarification**
Because sine is a continuous function, the values must be discretized:
For the case of `amplitude of 1` and `frequency of 1Hz` the "Crest" of the sine wave must be on `line 1` and the "Trough" of the sine wave must be on `line 3`.
To achieve the intermediate points, the wave points are set corresponding to ranges associated to the sections of the wave and these ranges will be relative to the amplitude.
[Wikipedia - Crest and Trough](https://en.wikipedia.org/wiki/Crest_and_trough "Crest N Trough")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21? 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
[21 bytes](https://tio.run/##ATMAzP9qZWxsef//w5fisa7ItzLDlzMwwrDDhlPDlysxLuG4nivEllXFkuG5rFn///8wLjQy/zQ "Jelly – Try It Online") if we may use a non-space character for the background.
```
×Ɱȷ2×30°ÆS×+1.Ḟ+Ṭ€o⁶z⁶Y
```
A full program accepting frequency (a float) and amplitude (an integer) which prints the result using `1` as the wave and as the background.
Note: Since there is no mention of phase I have assumed we may pick any (I also asked for clarification).
**[Try it online!](https://tio.run/##ATgAx/9qZWxsef//w5fisa7ItzLDlzMwwrDDhlPDlysxLuG4nivhuazigqxv4oG2euKBtln///8uNDL/NA "Jelly – Try It Online")**
[Answer]
# [Python 3](https://docs.python.org/3/), ~~128~~ \$\cdots\$ ~~107~~ 103 bytes
Added a byte to fix and error kindly pointed out by [blueteeth](https://codegolf.stackexchange.com/users/34766/blueteeth).
Saved ~~23~~ 27 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!!!
Added a byte to fix a fudge kindly pointed out by [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
```
lambda a,f:[[' .'[~j<=a*sin(f*i*pi/6)+.5<-j]for i in range(100)]for j in range(~a,a)]
from math import*
```
[Try it online!](https://tio.run/##lY27DoIwGEZ3nqJbL5YKGggh8CTI8BsttKGX1C4uvHoVY6KjrifnfJ@/x9nZY5r6U1rAnC@AgMt2GDASeFh11wO7KUskU8yrfU13oupyPUoXkELKogB2upKyKOiL6Q9bgQMdMxmcQQbijJTxLkSWNm/ZvIk0vBCHirY@KBsJxkK759lCafYmOWbbdvbV1Lz8Lyh/CVJKDw "Python 3 – Try It Online")
Inputs an integral amplitude and a float for frequency.
Uses a period of 12 characters for 1Hz.
Returns a list of lists of characters.
] |
[Question]
[
[Surreal Numbers](https://en.wikipedia.org/wiki/Surreal_number) are one way of describing numbers using sets. In this challenge you will determine the value of a surreal number.
# Intro
A surreal number consists of two sets: a left and right. The value of the surreal number must be greater than all numbers in the left set and less than all numbers in the right set. We define 0 as having nothing in each set, which we write as `{|}`. Each surreal number also has a birth date. 0 is born on day 0. On each successive day, new surreal numbers are formed by taking the numbers formed on previous days and placing them in the left/right sets of a new number. For example, `{0|} = 1` is born on day 1, and `{|0} = -1` is also born on day 1.
To determine the value of a surreal number, we find the number "between" the left and right sets that was born earliest. As a general rule of thumb, numbers with lower powers of 2 in their denominator are born earlier. For example, the number `{0|1}` (which is born on day 2 by our rules) is equal to `1/2`, since 1/2 has the lowest power of 2 in its denominator between 0 and 1. In addition, if the left set is empty, we take the largest possible value, and vice versa if the right set is empty. For example, `{3|} = 4` and `{|6} = 5`.
*Note that `4` and `5` are just symbols that represent the surreal number, which just happen to align with our rational numbers if we define operations in a certain way.*
Some more examples:
```
{0, 1|} = {1|} = {-1, 1|} = 2
{0|3/4} = 1/2
{0|1/2} = 1/4
{0, 1/32, 1/16, 1/2 |} = 1
```
# Input
A list/array of two lists/arrays, which represent the left and right set of a surreal number. The two lists/arrays will be sorted in ascending order and contain either dyadic rationals (rationals with denominator of 2^n) or other surreal numbers.
# Output
A dyadic rational in either decimal or fraction form representing the value of the surreal number.
# Examples
```
Input -> Output
[[], []] -> 0
[[1], []] -> 2
[[], [-2]] -> -3
[[0], [4]] -> 1
[[0.25, 0.5], [1, 3, 4]] -> 0.75
[[1, 1.5], [2]] -> 1.75
[[1, [[1], [2]]], [2]] -> 1.75
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins.
[Answer]
# [Python 3.7](https://www.python.org/), ~~228~~ ~~197~~ 184 bytes
Thanks to @LyricLy and friends for helping me golf this down a lot
`1e999` stolen from @Quintec's solution
```
m=1e999
g=lambda p:[f(*x)if[]==x*0else x for x in p]
def f(l,h):
h=min(g(h+[m]));l=max(g(l+[-m]));s=1
while h-l<=1:l*=2;h*=2;s*=2
return-(-h//1+1)/s if h<=0else l*h>=0and(l//1+1)/s
```
[Try it online!](https://tio.run/##fY3BToUwEEX3/YpZtkDlVTQR3ht/pOkCQ/vaZCgNYISvx4pxY6Kbk9w592bSvvopNjLtaT@OEZVt25bdkfrxbeghddrxYhPBaYO4FRdLi4UN3DRnhgjJsME6cJwqLzoGHscQ@Z37Uo9GiCvh2G85U6nleVhQMfjwgSx4STdUHRX4ePVfWDIYzHZ9n6Pk0te1KpWoFwgO/A2/n1PhX/HSx4HTjz/SHOLKHU19JtdNpXVjKv1kzEkhBPtVkS/ZPP9pZPOPejh3xyc "Python 3 – Try It Online")
[Answer]
# [Python](https://docs.python.org/2/), ~~371~~ ~~362~~ ~~261~~ ~~251~~ ~~248~~ ~~241~~ ~~236~~ ~~234~~ 231 bytes
*-122 bytes thanks to @ASCII-only*
```
def f(s):
if s<[]:return s
a=map(f,s[1]+[1e999,-1e999]+s[0]);m,n,u=a[-1],a[0],1
while n-m<=1:m*=2;n*=2;u/=2.
x,y=abs(m)-1,abs(n)-1;s=m>0>n or m<0<n;r=[[m-x*s,m+x*s][m<0]+1,[n-y*s,n+y*s][n<0]-1][x>y];return u*int([0,r][`r`<"m"])
```
[Try it online!](https://tio.run/##hY/dboIwFIDveYoTr0BOWYuwiVBf5KSJLINoslbTSiZPz1pntgxddnN68n3nr6fxvD@afJreuh762CWbCA49uIbUxnbnwRpwEbRSt6e4R0dCpSS6qqqQXR@VOuIqqTUaHGRLTChsPUERwcf@8N6BYbqRYqOXMq9NCMOTzLMILjjK9tXFOmECQ2J8Ujupt3xr4GhBN7wxtZVEml2WDnXqoyKPVSqQDBs9NOkYoPHQr6bLdlT17e5heTDnmDhaRTu7axZ6oZLpZAPtYyKFpFSSRD@EZf568uE39hDmpQGxfAZ5oMV8aBEon5dmeYnAszJIgbBCmDd6Kr58fm9uV3nzqICt/T/KO1i8ZKW/htarIiufZ/oK/5JM/O2q6jZW8Iet32vZ@j8fsqCnTw "Python 2 – Try It Online")
] |
[Question]
[
Non-associative operators (for example the subtraction-operator) often are either left- or right associative, such that one has to write less parentheses. Consider for example the following:
$$
a-b-c
$$
Probably everybody read that as \$(a-b)-c\$, by default (usually) subtraction is left-associative.
Now let us consider some operation \$\diamond: X \times X \to X\$, the only thing we know about it is that it is not associative. In this case the following is ambiguous:
$$
a \diamond b \diamond c
$$
It could either mean \$(a \diamond b) \diamond c\$ or it could mean \$a \diamond (b \diamond c)\$.
## Challenge
Given some possibly parenthesised expression that is ambiguous, your task is to parenthesise it such that there is no ambiguity. You can chooose freely whether the operator should be left- or right associative.
Since there is only one operation the operator is only implied, so for the above example you'll get `abc` as input. For left-associative you'll output `(ab)c` and for right-associative you'll output `a(bc)`.
## Input / Output
* Input will be a string of at least 3 characters
+ the string is guaranteed to be ambiguous (ie. there are missing parentheses)
+ you're guaranteed that no single character is isolated (ie. `(a)bc` or `a(bcd)e` is invalid input)
+ the string is guaranteed to only contain alphanumeric ASCII (ie. `[0-9]`, `[A-Z]` and `[a-z]`) and parentheses (you may choose `()`, `[]` or `{}`)
* Output will be a minimally1 parenthesized string that makes the string unambiguous
+ as with the input you may choose between `()`, `[]`, `{}` for the parentheses
+ output may **not** contain whitespace/new-lines, except for leading and trailing ones (finite amount)
## Test cases
These use `()` for parentheses, there is a section for each associativity you may choose (ie. left or right):
### Left associative
```
abc -> (ab)c
ab123z -> ((((ab)1)2)3)z
ab(cde)fo(0O) -> ((((ab)((cd)e))f)o)(0O)
(aBC)(dE) -> ((aB)C)(dE)
code(Golf) -> (((co)d)e)(((Go)l)f)
(code)Golf -> ((((((co)d)e)G)o)l)f
```
### Right associative
```
abc -> a(bc)
ab123z -> a(b(1(2(3z))))
ab(cde)fo(0O) -> a(b((c(de))(f(o(0O)))))
(aBC)(dE) -> (a(BC))(dE)
code(Golf) -> c(o(d(e(G(o(lf))))))
(code)Golf -> (c(o(de)))(G(o(lf)))
```
---
1: Meaning removing any pair of parentheses will make it ambiguous. For example `a(b(c))` or `(a(bc))` are both not minimally parenthesised as they can be written as `a(bc)` which is not ambiguous.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 61 bytes
```
+1`(\(((\()|(?<-3>\))|[^()])+(?(3)$)\)|[^()]){2}(?=[^)])
($&)
```
[Try it online!](https://tio.run/##NYlBCsIwFET3OUeVGYpgm60aqEiXHqCxNE1SEKQBcaX17PF34WJ4jzfP@LrPLm/QDrmsBlhAxgXmsNMnSy5dD95YwkCzoP2HT/2FOXa9qEKxZc5u9MqNVa3fAvgQOSXsr3K75kyEC5VPIaJNj0ni6lz9Bw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: I'd really like to use a recursive regex `(([^()]|\((?1)\)){2})(?=[^)])` here, but .NET only has balancing groups, so it's a bit verbose.
```
+1`
```
Repeatedly replace the first match each time. This ensures left-associativity.
```
( Either
\( Match outer `(`
( Either
(\() Capture a `(` into $3
| Or
(?<-3>\)) A `)` if it matched an earlier `(`
| Or
[^()] Something else
)+ Match as much of the above as possible
(?(3)$) But don't leave `(`s unmatched
\) Match outer `)`
| Or
[^()] Match something else
){2} Match the above twice
(?=[^)]) Followed by a non-`)`
```
Either, a `(` followed by a string containing balanced `()`s, followed by a `)`, or a non-`()`, twice, followed by a non-`)`. This represents an ambiguous match.
```
($&)
```
Wrap the match in disambiguating parentheses.
[Answer]
# JavaScript (ES6), 128 bytes
```
f=([a,...s],c=q=p="",$=")")=>s[1]?a<$?s.map(t=>c||(t<$?++p:t>$||p--||(c=f(q),q=""))?q+=t:0)&&q?a+c+$+a+f(q)+$:c:a+"("+f(s)+$:a+s
```
Recognizes `()` as parentheses, and outputs a right-associative expression. Test cases additionally include nested parentheses.
[Try it online!](https://tio.run/##jZFNb9swDIbv/hWEYdQU5KRNe3OrBNgw7DJsO/RW9EDLcust9YcoF1iR/57Rrtcs3Qeqi82XDynx5Td6JLa@7sKiaUu331cGbyhbLpd8m1nTm87EcZaYWMXKrPlmdbuhq2TDywfqMJi13e0wiKB1l4d1stt1i4VI1lTYq6yXYqU2vTYhP1MnJ/2GtNWJJj2mdZLbnHSMsYQ8hqR5f3oKn9vgcvhE9ju0FVADxOx8qNsGnPeth7opa0vBMfBgrWOOIts2HGYQDHjXD7V3mD4rqbqciTGJnIFTYNYzj@P1YIwR9TKK5AVffftYl64EuSOAJXYcgZwgDQubZpASFlaNbV/k1fnF05zBFZ7jxZOSc4SgLZ2qWjz7on6RaFE0JU@Y5FclSO/eKyw/TDgSSvQcHhAra8OP7baaGCttShRBviL90W@k1UhPDSdablcHPp0duJbBGSoxu5E/caIj7xqWbZRQDdvtDyhrpoeivhtoTNdNNwQ@GhVdpe7uXyaVQXGUULTXzvwt/bay35z@r/f/sPpNW6Bi4oqjxRTqIO5/Ag "JavaScript (Node.js) – Try It Online")
## Explanation
Recursively disambiguates sub-expressions within parentheses given in the input.
To track nesting depth, it increments the variable `p` upon encountering a left
paren (following the initial opening paren). A right paren decrements the
counter, and if `p = 0` prior to decrementing, the function recurs on the
accumulated sub-expression. A quick visual:
```
(ab(cd(ef)gh)ij)
0 1 2 1 0 = 0, so call function
```
When handling parentheses in inputs, i.e. the first character is a `(`, it
partitions the input into the enclosed sub-expression and everything following
the matching paren, e.g. `(cd)ef` splits into `cd`, which is fed back into the
function, and `ef`, both of which are subsequently wrapped in parentheses. If an
enclosed sub-expression has no trailing characters, the result of recurring on
it isn't wrapped in parentheses. `(cd)ef` -> `(cd)(ef)` but `(cd)` -> `cd`
**Ungolfed:**
```
f = (
[a, ...s], // destructure string, e.g. "abc" => "a", ["b", "c"]
c = q = p = "",
$ = ")"
) =>
s[1] ? // if input length > 2 ...
a < $ // if first char is ( ...
? s.map(t =>
c // stores disambiguated sub-expression
|| ( // if sub-expression not yet found...
t < $ // if char is ( ...
? ++p
: t > $
|| p-- // if char is ) and p = 0, e.g. outer closing paren found...
|| (c = f(q), q = "") // reset q to accumulate characters following the closing paren
) // this expression returns a truthy value if should append current char (i.e. if t is not the final closing paren)
? q += t
: 0
)
&& q
? a + c + $ + a + f(q) + $ // a = "(", guaranteed by the conditional check
: c
: a + "(" + f(s) + $
: a+s // since s has length 1, appending it simply appends its first value
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/162652/edit).
Closed 5 years ago.
[Improve this question](/posts/162652/edit)
# Challenge
A simple challenge: given two or more strings, output all of the substrings that are in each string.
# Rules
* Input is always a comma separated list of strings
* Strings should be outputted from longest to shortest length without duplicates
* Strings should preserve whitespace
# Examples
```
Input: aaa,aa
Output:
aa
a
Input: ababa,aba
Output:
aba
ab
ba
a
b
Input: Hello\, world!, Hello world!
Output:
world!
world!
world
worl
world
orld!
Hello
orld
rld!
ello
wor
Hell
worl
ell
rld
wo
ld!
llo
wor
orl
Hel
d!
ll
w
lo
rl
wo
or
He
el
ld
o
l
r
H
e
d
!
w
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
€Œ.»ÃÙéR»
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UdOao5P0Du0@3Hx45uGVQYd2//8fre6RmpOTr6NQnl@Uk6KorgPhI7gQtnosAA "05AB1E – Try It Online")
**Explanation**
```
€Œ # get the substrings of each
.»Ã # reduce by intersection
Ù # remove duplicates
é # sort by length
R # reverse
» # join on newline
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
Ẇ€f/QṚ
```
[Try it online!](https://tio.run/##y0rNyan8///hrrZHTWvS9AMf7pz1/3B75P//SolJQKikowBiKAEA "Jelly – Try It Online")
```
Ẇ€f/QṚ Main Link
€ For each string
Ẇ Get all substrings
/ Reduce this list of lists by
f Filter (intersection)
Q Remove duplicates
Ṛ Reverse
```
[Answer]
# Pyth, 8
```
_{@Fm.:d
```
## Explanation
```
Q # Implicit input list of 2 strings
m.:d # get lists of all substrings of each input string
@F # intersection
{ # deduplicate
_ # reverse
```
[Online test](https://pyth.herokuapp.com/?code=_%7B%40Fm.%3Ad&input=%5B%22ababa%22%2C%22aba%22%5D&test_suite=1&test_suite_input=%5B%22aaa%22%2C%22aa%22%5D%0A%5B%22ababa%22%2C%22aba%22%5D%0A%5B%22Hello%2C+world%21%22%2C+%22Hello+world%21%22%5D&debug=0).
] |
[Question]
[
In the context of quines, an intron (or payload) is a part of a quine that serves no purpose in producing output, but is still included in the data section. For example:
```
function quine() {
const data = "function quine() {\n const data=\"@\";\n // Arr! This be an intron!\n return data.replace(\"@\", JSON.stringify(data));\n}";
// Arr! This be an intron!
return data.replace("@", JSON.stringify(data));
}
```
My challenge is to write a quine that will *normally* run as a standard quine, but if an argument is passed in, then it returns a new quine with the argument placed somewhere in it. If that new quine is called with an argument, it should do the same. For example:
```
function quine(intron="") {
const data = "function quine(intron=\"\0\") {\n const data = \"%%%\";\n //\0\n return data.replace(/\u0000/g, intron).replace(\"%%%\", JSON.stringify(data));\n}";
//
return data.replace(/\u0000/g, intron).replace("%%%", JSON.stringify(data));
}
```
A few statements:
* If you have no input, then the output should be identical to the source code. If you *have* input, then the output only needs to:
+ Be in the same language
+ Contain the input
+ Be a solution to this challenge in its own right
* Quines only need to contain the latest intron. Introns from the program that generated it are optional.
* If your program already contains the input, then the same program is fine. For example, if it's called with the same input twice.
* The input can be assumed to be printable ASCII only.
* The shortest program in bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 70 bytes
```
def f(x=''):s='def f(x=%r):s=%r;print s%%(x,s,x)#%s';print s%(x,s,x)#
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNo8JWXV3TqthWHcZVLQJxVYusC4oy80oUilVVNSp0inUqNJVVi9XhgjAxrv9pGuoxQCP@AwA "Python 2 – Try It Online")
A weird extension of the usual python quine `s="s=%r;print s%%s";print s%s`. This adds an extra `%s` after a comment, to output the data, and a `%r` in the default string to push the original string as default instead of an empty string.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 11 bytes
```
ñéÑvu"qpx:"
```
[Try it online!](https://tio.run/##K/v///DGwysPTywrVSosqLBS@v/fIzUnJx8A "V – Try It Online")
Hexdump:
```
00000000: f1e9 d176 7522 7170 783a 22 ...vu"qpx:"
```
This is a simple modification of [the standard V quine](https://codegolf.stackexchange.com/a/100426/31716). Given the input:
```
Hello
```
this program will output:
```
ñéÑvu"qpx:"Hello
```
Which outputs:
```
ñéÑvu"qpx:"Hello
```
This works because the input is automatically appended to the end of `ñéÑvu"qpx`, and `:"` is a comment (essentially)
[Answer]
# [Python 3](https://docs.python.org/3/), 77 bytes
```
t='';s='t=input()or t;print(f"t={repr(t)};s={repr(s)};exec(s)#{t}")';exec(s)#
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8RWXd262Fa9xDYzr6C0REMzv0ihxLqgKDOvRCNNqcS2uii1oEijRLMWqAjCLgayUytSk4EM5eqSWiVNdTj3///EpGR1JXUuAA "Python 3 – Try It Online")
Full programs. Input must be terminated with a newline, and output a trailing newline.
Equivalent Python 2 would be 76 bytes (I think).
] |
[Question]
[
The goal is to make a two frame animation with ASCII art of a hammer smacking a table.
Trailing white-space is allowed and the frames need to repeat continuously. The program should iterate over both frames with a time of 0.5 seconds between frames.
Lowest byte count wins for each language!
**Sample:**
Animation Frames:
```
Frame 1:
-------------------
| |
| |
| |
-------------------
/ /
/ /
/ /
/ /
/ /
/ /
/ /
/ /
/ /
\ /
---------------------------
| |
Frame 2:
----------
| |
| |
| |
--------------------------------------| |
| | |
--------------------------------------| |
| |
| |
| |
----------
-------------------------------
| |
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~337~~ ~~331~~ 319 bytes
-12 bytes thanks to Amphibological
```
import os,time
t,e,q,p='- \n|'
j=e+t*19+q
L=p+e*19+p+q
l=j+3*L+j
for i in range(9):l+=e*(9-i)+'/ /'+q
l+=' \\ /'+3*q+e*24+t*27+q+e*23+p+27*e+p+q
c=39*e
C=p+10*e+p+q
m=10*t+q
R=e+38*t+C
f=(c+C)*3
r=q+c+e+m+f+R+p+38*e+C+R+f+c+e+m+34*e+31*t+q+32*e+p+32*e+q
b=0
while 1:print([r,l][b]);time.sleep(.5);os.system('cls');b=~b
```
[Try it online!](https://tio.run/##LZA9b4MwEIZ3/wpvNj5CAk6VEuSJNVPWJENBR2PEh8GWqkhV/zo9UKZ77tWr5yy7V3iOg14W27txDnz0cbA9shBjPMXOiB2/D7@CtQYhqDSHiV2MA1zR0dKZFrS6QMuaceaW24HPX8M3yjw6d2BQyXxnIxB7zvdi7YMR/H5fF60m8mRH8mYn2FiTMzsp3NS10blCVtK59PDOekMYCK70Hv1JWLLGyBrKSGk2mwlqQOihgSv1qYBQEjbvWB8p0OlqAJ1tzm1MrDIH9vO0HfL07GY7BHmb4@5xqx5RsX5I4jtEJ5OPqBh94l8@YC9F3XkRFZX5q5blHw "Python 3 – Try It Online")
It uses 'cls', so will only work on Windows, use 'clear' for Linux with +2 bytes.
Will add a gif later.
[Answer]
## [Perl 5](https://www.perl.org/ "Perl 5"), 391 355 293 286 296 bytes
Whack whack whack, golfing those chars off, down to 296 b :)
.5s sleep as per the question specs.
This also requires perl -E
```
$r="| 19|n"x 3;$p="| 10|n";$R=" 39$p"x 3;$T=" -38$p";$t=" 40-10n";$m=" -19n$r -19n 9H 8H 7H 6H 5H 4H 3H 2H 2\\ /n3 24-27n 23| 27|n";$M="$t$R$T| 38$p$T$R$t 34-30n 33| 30|n";for($m){say"\033[2J";map{s:H:/ /n:;y!n!\n!;print$1x($2?$2:1)if/(\D+)(\d*)/}(split/(.\d*)/);($m,$M)=($M,$m);select$v,$V,$v,.5;redo}
```
Explanation/comments:
```
# initial vars build strings that the print will understand later
$r="| 19|n"x 3;
$p="| 10|n";
$R=" 39$p"x 3;
$T=" -38$p";
$t=" 40-10n";
# set $_ to first frame
$_=" -19n$r -19n 9H 8H 7H 6H 5H 4H 3H 2H 2\\ /n3 24-27n 23| 27|n";
# M is second frame
$M="$t$R$T| 38$p$T$R$t 34-30n 33| 30|n";
# main loop
{
# clear screen
say"\033[2J";
# or windows, -1b
# system"cls";
# start map...
map{
# sed replace H for / /n
s:H:/ /n:;
# tr replace n for newline
y!n!\n!;
# parens around ?: necessary due to x operator precedence
# if/regex/ prints $1 $2 times
print$1x($2?$2:1)if/(\D+)(\d*)/
# map runs on char followed by a number or not
}(split/(.\d*)/);
# rotate frames
($_,$M)=($M,$_);
# sleep for 1 second would be shorter, but perl does
# not deal with integer sleep without time::hires
# sleep 1;
# select for decimal second sleep
select$v,$v,$v,.5;
# do the current block again
redo
}
```
GIF of original in action:

[Answer]
# [Python 3.6](https://www.python.org/), [413 bytes](https://ethproductions.github.io/bytes/?e=ascii&t=from%20os%20import%2A%0Afrom%20time%20import%2A%0As%2Cy%3D%27%20-%27%3Bb%3Dy%2A19%3Bd%3Db%2Bb%3Bf%3Dy%2A10%3Bi%3Dy%2A26%3Bg%3Ds%2A9%3Bc%3Ds%2Bg%3Bh%3Ds%2A26%3Bj%3Ds%2A32%3Ba%3Dc%2Bg%3Be%3Da%2Ba%3Bp%3Dprint%3Bk%3Df%27%5Cn%7C%7Ba%7D%7C%27%3Bt%2Cv%3Dsystem%2Csleep%3Bz%3D%27cls%27%0Awhile%201%3A%0A%20t%28z%29%3Bp%28f%27%20%7Bb%7D%20%7Bk%2A3%7D%5Cn%20%7Bb%7D%27%29%0A%20for%20x%20in%20range%289%29%3Ap%28f%27%7Bg%5Bx%3A%5D%7D%2F%20%20%2F%27%29%0A%20p%28f%27%20%5C%5C%20%2F%5Cn%20%7Ba%7D%20%7Bi%7D%5Cn%20%7Ba%7D%7C%7Bh%7D%7C%27%29%3Bv%281%29%3Bt%28z%29%3Bp%28f%27%20%7Be%7D%20%7Bf%7D%27%29%0A%20for%20w%20in%20range%287%29%3Ap%28f%27%20%7Be%7D%7C%7Bc%7D%7C%27%29if%20w!%3D3else%20p%28f%27%20%7Bd%7D%7C%7Bc%7D%7C%5Cn%7C%7Be%7D%7C%7Bc%7D%7C%5Cn%20%7Bd%7D%7C%7Bc%7D%7C%27%29%0A%20p%28f%27%20%7Be%7D%20%7Bf%7D%5Cn%20%7Bj%7D%20%7Bi%7D%5Cn%20%7Bj%7D%7C%7Bh%7D%7C%27%29%3Bv%281%29)
```
from os import*
from time import*
s,y=' -';b=y*19;d=b+b;f=y*10;i=y*26;g=s*9;c=s+g;h=s*26;j=s*32;a=c+g;e=a+a;p=print;k=f'\n|{a}|';t,v=system,sleep;z='cls'
while 1:
t(z);p(f' {b} {k*3}\n {b}')
for x in range(9):p(f'{g[x:]}/ /')
p(f' \\ /\n {a} {i}\n {a}|{h}|');v(1);t(z);p(f' {e} {f}')
for w in range(7):p(f' {e}|{c}|')if w!=3else p(f' {d}|{c}|\n|{e}|{c}|\n {d}|{c}|')
p(f' {e} {f}\n {j} {i}\n {j}|{h}|');v(1)
```
Doesn't work on TIO, so here's a GIF:
[](https://i.stack.imgur.com/g8Fxw.gif)
Not the prettiest thing in the world, but I'm pretty proud of it. Suggestions on golfing it further are welcome!
P.S.: I used a 1 second delay because it looked better to me, but you can replace `1` with `.5` to change that, at +2 bytes.
P.P.S: This will only work on Windows, to try on Unix, change `cls` to `clear` at +2 bytes.
] |
[Question]
[
You will create a program that generates the stereographic projection of polyhedra.
In particular, to keep things simple, we'll only focus on n-[chamfered](https://en.wikipedia.org/wiki/Chamfer_(geometry)) [dodecahedron](https://en.wikipedia.org/wiki/Regular_dodecahedron).
Given a natural number `n` as input, and also a natural number `d` your program will output an `d` pixels by `d` pixels image which is the [stereographic projection](https://en.wikipedia.org/wiki/Stereographic_projection) of the dodecahedron which has been chamfered `n` times. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program wins!
## Examples
* `0` -> [](https://commons.wikimedia.org/wiki/File:Dodecahedron_stereographic_projection.png) (the regular dodecahedron)
## Notes
* You must select a color for the background, edges, and vertices. The color of the edges and vertices may coincide, but the color of the background must coincide with neither.
* You may treat the polyhedra either [spherically](https://en.wikipedia.org/wiki/Spherical_polyhedron) or straight edged.
* The center of the image must be the center of a pentagon.
* Since stereographic projection results in an infinitely large image, you only need to have at least 75% of the vertices in the image.
* EDIT: Since I never specified you can chamfer by any non-trivial amount. That being said, it would be nice if it looked like the images of chamfering below (i.e. almost regular).
## Smiley Bonus
The n-chamfered dodecahedron is the $GP(2^n,0)$ goldberg polyhedron (where $GP(x,y)$ means a polyhedron consisting of hexagons and pentagons where if you start at one pentagon and move x spaces one direction, turn 60 degrees clockwise, and y spaces in that direction, you end up at another pentagon). Therefore, it might be easier to just calculate $GP(x,y)$ for arbitrary $x$ and $y$. If you do, you get a Smiley bonus (I can't award points since the challenge has already started).
# Background
A dodecahedron is polyhedron with 12 sides, each pentagons. It looks like this
[](https://en.wikipedia.org/wiki/File:Dodecahedron.gif)
When you chamfer a shape, you replace each face with a smaller face, and each edge with a hexagonal face. For instance, here is what happens when you chamfer a dodecahedron (note, this is not the same [shape](https://en.wikipedia.org/wiki/Truncated_icosahedron) as a soccer/football)
[](https://commons.wikimedia.org/wiki/File:Truncated_rhombic_triacontahedron.png)
Here is what it looks like when you chamfer it again (i.e. n=2) [polyHédronisme](http://levskaya.github.io/polyhedronisme/?recipe=A10ccD&palette=%23ff7777%20%23dddddd) (sorry, the image export doesn't seem to be working).
Stereographic projection means that vertices of the polyhedron on a sphere. Place a plane tangent to it, and point on the opposite side of the sphere (called the view point). Then, draw a line between each point of the polyhedron and the view point. Extend this line to the plane, and map that point there. Do this for all the points. See above for an example of the stereographic projection of the dodecahedron.
[Answer]
# 837 Bytes : Javascript/HTML + [d3.js](https://d3js.org/) + [d3-delaunay](https://github.com/d3/d3-delaunay) + [d3-geo-voronoi](https://github.com/Fil/d3-geo-voronoi)\*
I believe I have a solution for this challenge. It relies on d3's geographic features: projections and pathing along great circles, d3-delaunay (a voronoi generator) and d3-geo-voronoi (a geographical voronoi extension to d3-delaunay).
The approach I've taken is fairly simple:
1. Take the centers of the faces of a regular dodecahedron (as lat/long pairs).
2. Create a spherical voronoi diagram of the centers (replicating the dodecahedron, contained in a sphere)
3. If more chamfering is needed, calculate the midpoint of each edge of the spherical voronoi diagram, add these to the list of centers, go back to step 2.
4. Project and draw
Using the midpoint from each edge as a new face center creates a new face for every edge when running through the voronoi generator. This chamfering is fairly regular, the midpoint of each edge should be in the middle of a new face when chamfering. This does not mean the hexagons are regular, hexagons cannot be regular when chamfering twice or more (if I'm not mistaken).
Here's the implementation in 837 bytes:
```
<input><input><p>d</p><canvas><script src="https://d3js.org/d3.v4.js"></script><script src="https://unpkg.com/d3-delaunay@2"></script><script src="https://unpkg.com/d3-geo-voronoi"></script><script>_="canvas",O=d3,$=O.select,$("p").on("click",()=>{N=O.selectAll("*").nodes(),w=N[3].value,n=N[4].value,$(_).attr("width",w).attr("height",w),a=31.71801,b=58.28198,c=121.71801,C=[[0,a],[180,-a],[-90,b],[90,-b],[0,-a],[180,a],[90,b],[-90,-b],[-b,0],[-c,0],[c,0],[b,0]],s=$(_).node().getContext("2d"),p=O.geoStereographic().scale(60/960*w).rotate([-b,0]).translate([w/2,w/2]).clipAngle(170),P=O.geoPath(p,s),s.clearRect(0,0,w,w),D=C=>O.geoVoronoi()(C),M=v=>v.mesh().coordinates.map((c)=>O.geoInterpolate(c[0],c[1])(0.5)),v=D(C);for(i=0;i<n;i++){C.push(...M(v)),v=D(C)}v.polygons().features.forEach(f=>(s.beginPath(),P(f),s.stroke()))})</script>
```
Input is in the form of two html input fields, first one is the size of the drawing, the second one is the number of times to chamfer, clicking "d" will draw).
And in snippet form (with some minor interface changes: input s is size, input n is times to chamfer, click "draw" to draw):
```
_="canvas",O=d3,$=O.select,$("p").on("click",()=>{N=O.selectAll("input").nodes(),w=N[0].value,n=N[1].value,$(_).attr("width",w).attr("height",w),a=31.71801,b=58.28198,c=121.71801,C=[[0,a],[180,-a],[-90,b],[90,-b],[0,-a],[180,a],[90,b],[-90,-b],[-b,0],[-c,0],[c,0],[b,0]],s=$(_).node().getContext("2d"),p=O.geoStereographic().scale(60/960*w).rotate([-b,0]).translate([w/2,w/2]).clipAngle(170),P=O.geoPath(p,s),s.clearRect(0,0,w,w),D=C=>O.geoVoronoi()(C),M=v=>v.mesh().coordinates.map((c)=>O.geoInterpolate(c[0],c[1])(0.5)),v=D(C);for(i=0;i<n;i++){C.push(...M(v)),v=D(C)}v.polygons().features.forEach(f=>(s.beginPath(),P(f),s.stroke()))})
```
```
s<input>n<input><p>draw</p><canvas><script src="https://d3js.org/d3.v4.js"></script><script src="https://unpkg.com/d3-delaunay"></script><script src="https://unpkg.com/d3-geo-voronoi"></script>
```
*slightly modified for snippet view as noted, also as there are other nodes in the snippet to navigate, so there is a change there*
If rendered as 3d, this produces something along the lines of (chamfered five times):
[](https://i.stack.imgur.com/eAVjH.png)
Original pentagons are in orange - they are separated by 31 hexagons.
An example with the sterographic (chamfered 6 times):
[](https://i.stack.imgur.com/kqkA1.png)
## \*Note
The above may not conform to scoring rules very well. Without using new (relative to challenge) updates to dependecies, but replacing those with poor and incomplete minimization:
### 4454 Bytes : [d3.js](https://d3js.org/) (v4) + [d3-delaunay](https://github.com/d3/d3-delaunay) (v2)
d3-geo-voronoi *has* been altered since the challenge has been posted in a way that enables the above solution. While it wasn't altered by me, nor to address this challenge, I'll include the longer solution that relies on only d3.js and d3-delaunay (versions that predate the challenge) and incorporates the necessary parts of d3-geo-voronoi:
```
<input><input><p>draw</p><canvas></canvas><script src="https://d3js.org/d3.v4.js"></script><script src="https://unpkg.com/d3-delaunay@2"></script><script>A=Math,d3.S=d3.geoStereographic,$=180,_="canvas";!function(n,t){"object"==typeof exports&&a!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(n.d3,n.d3,n.d3,n.d3)}(this,function(n,t,e,r){function o(n){return n>1?E:-1>n?-E:A.asin(n)}u=(n,t)=>{return n[0]*t[0]+n[1]*t[1]+n[2]*t[2]};function i(n,t){return[n[1]*t[2]-n[2]*t[1],n[2]*t[0]-n[0]*t[2],n[0]*t[1]-n[1]*t[0]]}function a(n,t){return[n[0]+t[0],n[1]+t[1],n[2]+t[2]]}function c(n){var t=w(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);return[n[0]/t,n[1]/t,n[2]/t]}function f(n){return[j(n[1],n[0])*b,o(N(-1,k(1,n[2])))*b]}function s(n){var t=n[0]*C,e=n[1]*C,r=q(e);return[r*q(t),r*O(t),O(e)]}function l(n){return n=n.map(n=>s(n)),u(n[0],i(n[2],n[1]))}function h(n){let t=p(n),e=g(t,n.length),r=d(e,n),o=m(e,n.length),u=y(e,n),{P:i,C:a}=v(u,e,n);return{delaunay:t,E:r,triangles:e,C:a,nb:o,P:i,m:_(i)}}function p(n){let r=e.geoRotation(n[0]),o=e.S().translate([0,0]).scale(1).rotate(r.invert([$,0])),u=[0];let i=1;for(let t=1,e=(n=n.map(o)).length;e>t;t++){let e=n[t][0]*n[t][0]+n[t][1]*n[t][1];isNaN(e)&&u.push(t),e>i&&(i=e)}let a=1e6*w(i);u.forEach((t,e)=>n[e]=[a/2,0]);for(let t=0;4>t;t++)n.push([a*q(t/2*x),a*O(t/2*x)]);let c=t.Delaunay.from(n);return c.projection=o,c}function d(n,t){let e={};return 2===t.length?[[0,1]]:(n.forEach(n=>{if(0>l(n.map(n=>t[n])))return;for(let t,o=0;3>o;o++)t=(o+1)%3,e[r.extent([n[o],n[t]]).join("-")]=!0}),Object.keys(e).map(n=>n.split("-").map(Number)))}function g(n,t){if(!n.triangles)return[];let e=n.triangles.slice().map(n=>t>n?n:0),r=[];for(let n=0,t=e.length/3;t>n;n++){let t=e[3*n],o=e[3*n+1],u=e[3*n+2];t!==o&&o!==u&&u!==t&&r.push([t,u,o])}return r}function y(n,t){return n.map(n=>{let e=n.map(n=>t[n]).map(s),r=a(a(i(e[1],e[0]),i(e[2],e[1])),i(e[0],e[2]));return f(c(r))})}function m(n,t){let e=[];return n.forEach((n,t)=>{for(let t=0;3>t;t++){let r=n[t],o=n[(t+1)%3];e[r]=e[r]||[],e[r].push(o)}}),0===n.length&&(2===t?(e[0]=[1],e[1]=[0]):1===t&&(e[0]=[])),e}function v(n,t,e){function r(n){let e=-1;return u.slice(t.length,1/0).forEach((r,o)=>{r[0]===n[0]&&r[1]===n[1]&&(e=o+t.length)}),0>e&&(e=u.length,u.push(n)),e}let o=[],u=n.slice();if(0===t.length){if(2>e.length)return{P:o,C:u};if(2===e.length){let n=s(e[0]),t=s(e[1]),l=c(a(n,t)),h=c(i(n,t)),p=i(l,h),d=[l,i(l,p),i(i(l,p),p),i(i(i(l,p),p),p)].map(f).map(r);return o.push(d),o.push(d.slice().reverse()),{P:o,C:u}}}return t.forEach((n,t)=>{for(let e=0;3>e;e++){let r=n[e],u=n[(e+1)%3],i=n[(e+2)%3];o[r]=o[r]||[],o[r].push([u,i,t,[r,u,i]])}}),{P:o.map(n=>{let t=[n[0][2]];let o=n[0][1];for(let e=1;e<n.length;e++)for(let e=0;e<n.length;e++)if(n[e][0]==o){o=n[e][1],t.push(n[e][2]);break}if(t.length>2)return t;if(2==t.length){let o=M(e[n[0][3][0]],e[n[0][3][1]],u[t[0]]),i=M(e[n[0][3][2]],e[n[0][3][0]],u[t[0]]),a=r(o),c=r(i);return[t[0],c,t[1],a]}}),C:u}}function M(n,t,e){n=s(n),t=s(t),e=s(e);let r=S(u(i(t,n),e));return f(c(a(n,t)).map(n=>r*n))}function _(n){let t=[];return n.forEach(n=>{if(!n)return;let e=n[n.length-1];for(let r of n)r>e&&t.push([e,r]),e=r}),t}function P(n){let t=n=>{return t.de=null,t._data=n,t.points=t._data.map(n=>[t._vx(n),t._vy(n)]),t.de=h(t.points),t};return t.x=n=>{return t._vx=n,t},t.y=n=>{return t._vy=n,t},t.p=n=>{return void 0!==n&&t(n),!!t.de&&(0===t._data.length?null:t.de.P.map((n,e)=>({type:"Feature",geometry:n?{type:"Polygon",coordinates:[[...n,n[0]].map(n=>t.de.C[n])]}:null})))},t.m=n=>{return void 0!==n&&t(n),!!t.de&&t.de.E.map(n=>[t.points[n[0]],t.points[n[1]]])},n?t(n):t}var x=A.PI,E=x/2,b=$/x,C=x/$,j=A.atan2,q=A.cos,N=A.max,k=A.min,O=A.sin,S=A.sign||function(n){return n>0?1:0>n?-1:0},w=A.sqrt;n.gV=P,Object.defineProperty(n,"__esModule",{value:!0})});d3.select("p").on("click",()=>{N=d3.selectAll("input").nodes(),W=N[0].value,Q=N[1].value,d3.select(_).attr("width",W).attr("height",W),a=31.71801891,b=58.28198108,c=121.71801891,C=[[0,a],[$,-a],[-90,b],[90,-b],[0,-a],[$,a],[90,b],[-90,-b],[-b,0],[-c,0],[c,0],[b,0]],s=d3.select(_).node().getContext("2d"),p=d3.S().scale(60/960*W).rotate([-b,0]).translate([W/2,W/2]).clipAngle(170),P=d3.geoPath(p,s),s.clearRect(0,0,W,W),D=C=> d3.gV().x(a=>a[0]).y(a=>a[1])(C),M=v=>v.m().map((c)=>d3.geoInterpolate(c[0],c[1])(0.5)),v=D(C);for(i=0;i<Q;i++){C.push(...M(v)),v=D(C)}v.p().forEach(f=>(s.beginPath(),P(f),s.stroke()))})</script></script><script src="https://unpkg.com/d3-delaunay@2"></script><script>A=Math,d3.S=d3.geoStereographic,$=180,_="canvas";!function(n,t){"object"==typeof exports&&a!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(n.d3,n.d3,n.d3,n.d3)}(this,function(n,t,e,r){function o(n){return n>1?E:-1>n?-E:A.asin(n)}u=(n,t)=>{return n[0]*t[0]+n[4]*t[4]+n[5]*t[5]};function i(n,t){return[n[4]*t[5]-n[5]*t[4],n[5]*t[0]-n[0]*t[5],n[0]*t[4]-n[4]*t[0]]}function a(n,t){return[n[0]+t[0],n[4]+t[4],n[5]+t[5]]}function c(n){var t=w(n[0]*n[0]+n[4]*n[4]+n[5]*n[5]);return[n[0]/t,n[4]/t,n[5]/t]}function f(n){return[j(n[4],n[0])*b,o(N(-1,k(1,n[5])))*b]}function s(n){var t=n[0]*C,e=n[4]*C,r=q(e);return[r*q(t),r*O(t),O(e)]}function l(n){return n=n.map(n=>s(n)),u(n[0],i(n[5],n[4]))}function h(n){let t=p(n),e=g(t,n.length),r=d(e,n),o=m(e,n.length),u=y(e,n),{P:i,C:a}=v(u,e,n);return{delaunay:t,E:r,triangles:e,C:a,nb:o,P:i,m:_(i)}}function p(n){let r=e.geoRotation(n[0]),o=e.S().translate([0,0]).scale(1).rotate(r.invert([$,0])),u=[0];let i=1;for(let t=1,e=(n=n.map(o)).length;e>t;t++){let e=n[t][0]*n[t][0]+n[t][4]*n[t][4];isNaN(e)&&u.push(t),e>i&&(i=e)}let a=1e6*w(i);u.forEach((t,e)=>n[e]=[a/2,0]);for(let t=0;4>t;t++)n.push([a*q(t/2*x),a*O(t/2*x)]);let c=t.Delaunay.from(n);return c.projection=o,c}function d(n,t){let e={};return 2===t.length?[[0,1]]:(n.forEach(n=>{if(0>l(n.map(n=>t[n])))return;for(let t,o=0;3>o;o++)t=(o+1)%3,e[r.extent([n[o],n[t]]).join("-")]=!0}),Object.keys(e).map(n=>n.split("-").map(Number)))}function g(n,t){if(!n.triangles)return[];let e=n.triangles.slice().map(n=>t>n?n:0),r=[];for(let n=0,t=e.length/3;t>n;n++){let t=e[3*n],o=e[3*n+1],u=e[3*n+2];t!==o&&o!==u&&u!==t&&r.push([t,u,o])}return r}function y(n,t){return n.map(n=>{let e=n.map(n=>t[n]).map(s),r=a(a(i(e[4],e[0]),i(e[5],e[4])),i(e[0],e[5]));return f(c(r))})}function m(n,t){let e=[];return n.forEach((n,t)=>{for(let t=0;3>t;t++){let r=n[t],o=n[(t+1)%3];e[r]=e[r]||[],e[r].push(o)}}),0===n.length&&(2===t?(e[0]=[4],e[4]=[0]):1===t&&(e[0]=[])),e}function v(n,t,e){function r(n){let e=-1;return u.slice(t.length,1/0).forEach((r,o)=>{r[0]===n[0]&&r[4]===n[4]&&(e=o+t.length)}),0>e&&(e=u.length,u.push(n)),e}let o=[],u=n.slice();if(0===t.length){if(2>e.length)return{P:o,C:u};if(2===e.length){let n=s(e[0]),t=s(e[4]),l=c(a(n,t)),h=c(i(n,t)),p=i(l,h),d=[l,i(l,p),i(i(l,p),p),i(i(i(l,p),p),p)].map(f).map(r);return o.push(d),o.push(d.slice().reverse()),{P:o,C:u}}}return t.forEach((n,t)=>{for(let e=0;3>e;e++){let r=n[e],u=n[(e+1)%3],i=n[(e+2)%3];o[r]=o[r]||[],o[r].push([u,i,t,[r,u,i]])}}),{P:o.map(n=>{let t=[n[0][5]];let o=n[0][4];for(let e=1;e<n.length;e++)for(let e=0;e<n.length;e++)if(n[e][0]==o){o=n[e][4],t.push(n[e][5]);break}if(t.length>2)return t;if(2==t.length){let o=M(e[n[0][5][0]],e[n[0][5][4]],u[t[0]]),i=M(e[n[0][5][5]],e[n[0][5][0]],u[t[0]]),a=r(o),c=r(i);return[t[0],c,t[4],a]}}),C:u}}function M(n,t,e){n=s(n),t=s(t),e=s(e);let r=S(u(i(t,n),e));return f(c(a(n,t)).map(n=>r*n))}function _(n){let t=[];return n.forEach(n=>{if(!n)return;let e=n[n.length-1];for(let r of n)r>e&&t.push([e,r]),e=r}),t}function P(n){let t=n=>{return t.de=null,t._data=n,t.points=t._data.map(n=>[t._vx(n),t._vy(n)]),t.de=h(t.points),t};return t.x=n=>{return t._vx=n,t},t.y=n=>{return t._vy=n,t},t.p=n=>{return void 0!==n&&t(n),!!t.de&&(0===t._data.length?null:t.de.P.map((n,e)=>({type:"Feature",geometry:n?{type:"Polygon",coordinates:[[...n,n[0]].map(n=>t.de.C[n])]}:null})))},t.m=n=>{return void 0!==n&&t(n),!!t.de&&t.de.E.map(n=>[t.points[n[0]],t.points[n[4]]])},n?t(n):t}var x=A.PI,E=x/2,b=$/x,C=x/$,j=A.atan2,q=A.cos,N=A.max,k=A.min,O=A.sin,S=A.sign||function(n){return n>0?1:0>n?-1:0},w=A.sqrt;n.gV=P,Object.defineProperty(n,"__esModule",{value:!0})});d3.select("p").on("click",()=>{N=d3.selectAll("input").nodes(),W=N[0].value,Q=N[4].value,d3.select(_).attr("width",W).attr("height",W),a=31.71801891,b=58.28198108,c=121.71801891,C=[[0,a],[$,-a],[-90,b],[90,-b],[0,-a],[$,a],[90,b],[-90,-b],[-b,0],[-c,0],[c,0],[b,0]],s=d3.select(_).node().getContext("2d"),p=d3.S().scale(60/960*W).rotate([-b,0]).translate([W/2,W/2]).clipAngle(170),P=d3.geoPath(p,s),s.clearRect(0,0,W,W),D=C=> d3.gV().x(a=>a[0]).y(a=>a[4])(C),M=v=>v.m().map((c)=>d3.geoInterpolate(c[0],c[4])(0.5)),v=D(C);for(i=0;i<Q;i++){C.push(...M(v)),v=D(C)}v.p().forEach(f=>(s.beginPath(),P(f),s.stroke()))})</script>
```
Lastly, here's an animated ungolfed snippet to show the workings:
```
var n = 3; // chamfer this many times.
var a = 31.71801891964135;
var b = 58.28198108035894;
var c = 121.71801891964117;
var centroids = [[0,a],[180,-a],[-90,b],[90,-b],[0,-a],[180,a],[90,b],[-90,-b],[-b,0],[-c,0],[c,0],[b,0]];
var getDiagram = function(centroids) {
return d3.geoVoronoi()
.x(function(a) {
return a[0]
})
.y(function(a) {
return a[1]
})
(centroids);
}
var getCenters = function(v) {
return v.mesh().coordinates.map(function(c) {
return d3.geoInterpolate(c[0],c[1])(0.5);
})
}
// Starting voronoi:
var voronoi = getDiagram(centroids);
for (var i = 0; i < n; i++) {
centroids.push(...getCenters(voronoi));
voronoi = getDiagram(centroids);
}
var canvas = document.getElementsByTagName("canvas")[0];
var context = canvas.getContext("2d");
var projection = d3.geoStereographic().scale(60).clipAngle(170).translate([480,480])
var path = d3.geoPath().projection(projection).pointRadius(1).context(context);
// animate:
d3.interval(function(elapsed) {
projection.rotate([ -elapsed / 200, 0 ]);
context.clearRect(0,0,960,960);
voronoi.polygons().features.forEach(function(d) {
context.beginPath();
path(d)
context.stroke();
})
}, 50);
```
```
<canvas width="960" height="960"></canvas>
<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://unpkg.com/d3-delaunay@4"></script>
<script src="https://unpkg.com/d3-geo-voronoi@1"></script>
```
] |
[Question]
[
Everyone loves slicing in python, as in `array[5]` to access the fifth element or `array[:5]` to access the zero through fourth element or `array[::-1]` to reverse an array. However, these all have seemingly distinct notations. When and where should the colons and integers be placed?
# Task
Your task is to change any valid slice syntax into a slice with as many colons and integers as possible. To help with that, we will make some definitions. Valid slice syntax is anything directly after "Given a slice" in this section.
Define `<POS>` to be any positive integer, that is any digit `1-9` followed by any amount of digits `0-9`.
Define `<NEG>` to be any negative integer, that is a `-` followed by `<POS>`
Define `<INT>` to be `<POS>`, `<NEG>`, or `<ZERO>`
Define `sgn(a)` to be the sign of `a`: 1 for positive `a`, -1 for negative `a`, and 0 for `a=0`.
For all of the following, `a` and `b` are `<INT>` and `c` is `<POS>` or `<NEG>` unless otherwise specified.
* Given a slice `[]`, your program may have undefined behavior.
* Given a slice `[a]`, your program or function must return `[a:a+k:c]` for some `<POS>` or `<NEG>` value of `c` and `0 < abs(k) <= abs(c)` and (`a+k < 0` if `c < 0`) and (`a+b > 0` if `c > 0`)
* Given a slice `[:]`, your program must return `[0::1]`.
* Given a slice `[a:]`, your program must return `[a::1]`.
* Given a slice `[:b]`, your program must return `[0:b:1]`.
* Given a slice `[a:b]` where `a < b` and `sgn(a)+sgn(b) != 0` your program must return `[a:b:1]`.
* Given a slice `[::]`, your program must return `[0::1]`.
* Given a slice `[a::]`, your program must return `[a::1]`.
* Given a slice `[:b:]`, your program must return `[0:b:1]`.
* Given a slice `[::c]`, your program must return `[0::c]` if `c` is `<POS>` and `[-1::c]` otherwise.
* Given a slice `[a:b:]` where `a < b` and `sgn(a)+sgn(b) != 0`, your program must return `[a:b:1]`.
* Given a slice `[a::c]`, your program must return `[a::c]`.
* Given a slice `[:b:c]`, your program must return `[0:b:c]` if `c` is `<POS>` and `[-1:b:c]` otherwise.
* Given a slice `[a:b:c]` your program must return `[a:b:c]`.
# Example
The "slice" `[5]` gives the fifth element of an array.
Your program or function can output `[5:6:1]` or `[5:7:2]` or `[5:1000:1000]` or `[5:4:-1]` or `[5:0:-5]`.
The program **cannot** output `[5:7:1]` or `[5:-6:1]` or `[5:-6:-1]` or `[5:6:-1]`.
# Test Cases
```
Input Output
[1] [1:2:1] [Output may vary]
[-1] [-1:-2:-1] [Output may vary]
[:] [0::1]
[1:] [1::1]
[-1:] [-1::1]
[0:3] [0:3:1]
[-3:-1] [-3:-1:1]
[::] [0::1]
[0::] [0::1]
[:5:] [0:5:1]
[::2] [0::2]
[::-2] [-1::-2]
[2:4:] [2:4:1]
[2::3] [2::3]
[:2:1] [0:2:1]
[:2:-1] [-1:2:-1]
[1:2:3] [1:2:3]
```
# Rules
* You do not have to do any input validation.
* The output and input may include or exclude the brackets `[]`.
* The output and input may be a 3-tuple instead of a `:`-delimited string.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code **in each language** wins.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~101~~ ~~96~~ ~~90~~ ~~85~~ 82 bytes
```
def f(r):l=len(r);b=r[l>1]+'1'*(l<2);c=(r+[0,b])[2]or'1';print r[0]or~-('.'<c),b,c
```
[Try it online!](https://tio.run/##VZBNDoMgEEb3noKNGahoBNuNfxchbLSa2hg01IXd9Op0Gi21Ccm8N/NNCMzP5TYZ6dy160lPLcvHauwMQtFUVo210BEIONGxlKxoK2ojlfJGMyX1ZHFSzHYwC7EqRX/FFBIoW8Yb3rp@smQlgyEqUJjUHEu8V@CwgfAU/zBFyvZuhnzcOma8IFyOgkceJd5NIp99UG7DzCc/DfFn35vF7pjVeUC2R4MKHxpCyCG5T4OhK8OFGniAP7ky9wY "Python 2 – Try It Online")
**Explanation:**
Basically a golfed version of:
```
f(r):
if len(r)==1:return [r[0],r[0]+'1',r[0]+'1'] # [a, a1, a1] where a1 is further from 0 than a
if len(r)==2:return [r[0]or'0',r[1],'1'] # [a or 0, b, 1]
if len(r)==3:return [r[0]or -1*(r[2]<0),r[1],r[2]or'1'] # [a or 0|-1, b, c or 1]
```
[Answer]
# [Python 3](https://docs.python.org/3/), 268 bytes
```
import re
w='([^:]*)'
def f(x):
(a,b,c,d,e)=re.findall('\[%s(?:(:)%s(?:(:)%s)?)?\]'%(w,w,w),x)[0]
g=int(a)if a else(-1if e and int(e)<0else 0)
return'[%s:%s:%s]'%(g,c if c else(g+(1if g>0else-1)if not(b or d)else''),e if e else((1if g>0else-1)if not(b or d)else 1))
```
[Try it online!](https://tio.run/##hZHBboMwDIbP5Sl8qWJvoSKwXaxRHoQyiZbAkFqoQqZ2qvrsXUKBHadE8hc7/x8nOf/Yr75LHo/2dO6NBaODSyow/@TihURQ6RpqvBIHKyzlXh5kJTWlRm/qtqvK4xHFLl8PmDEy/UXKKNsVYo0X6QbJK@VREayatO0sltTWUII@DhpD5VhD2VXgS5o@Ip@HiIKV0fbbdMLZ8zi9XyMP4BSHp7p5Ra9vtqMoVN646y3uoTdQkU8KQVLDeMgo@VcAiuhRu6XVg3VNAYpcFUKCyMMp8jMontMTRJxMmYSXvUttAn6fgeMZwolifuOZZi@OWS00uyrHru6/5Wz8w4lbdE@3N3UXG9f7qbTo25fu73wkd6Vf "Python 3 – Try It Online")
[Answer]
# Kotlin ~~354~~ 330 bytes
## Submission
```
fun f(i:List<Int?>):List<Int?>?{
val N=null
val Z=mutableListOf(0,N,1)
if(i.none{it!=N})return Z
val v:Int=i[0]?:0
val z:Int=if(i.size==3)i[2]?:1 else 1
val p=if(v<0)-1 else 1
return when(i.size){1->listOf(v,v+p,p)
2->listOf(v, i[1], z)
3->{if(i[0]==N&&i[2]!=N&&i[2]!!<0)Z[0]=-1
return i.zip(Z).map{it.first?:it.second}}
else->N}}
```
## Beautified
```
fun f(input: List<Int?>): List<Int?> {
if (input.none { it != null }) return listOf(0, null, 1)
val item0: Int = input[0] ?: 0
val step: Int = if (input.size == 3) input[2] ?: 1 else 1
val direction = if (item0 < 0) -1 else 1
return when (input.size) {
1 -> listOf(item0, item0 + direction, direction)
2 -> {
listOf(item0, input[1], step)
}
3 -> {
val D = mutableListOf(0, null, 1)
if (input[0] == null && input[2] != null && input[2]!! < 0) D[0] = -1
return input.zip(D).map { it.first ?: it.second }
}
else -> listOf()
}
}
```
## TryItOnline
[Link](https://tio.run/##pVXRatswFH33V9yWUiwimdheX0ydvGSDQkkL62CQ9cFr5E7MUYwtZxDjb8@upNhJTLa6myCJfHTPvcdX0snPtcqE3O3SSkLqiuhelOr2TqrphBzN602SwRxikFWWOQIDPbmWvBbqIoZ5QwquqkJChoSH1B3TOfWJozmbCPmxWIyfp9HYIFuL6BSl2HKIYwiJWAQY4APPSg6@ict1zOZ2TFgH76v8@sHlnk1qn032VTd0M8ppTpyATeoOEwv/mW5J44TMvsUsXlUq@Z7x@xOxIgVXy4zj@fW1lnPRTS5QxEwvsU6C8LYid2fEWyU5NsFLRVGqaYSzkr@s5bJpjGQ2aVtCmsZxlolK4CVLyhKeeKlm@OhqSULmlYrg0G4KGl5XqocTx9H7tEqERGKRFK@AnzKCz6oQ8pVA7QAOk1PxVYkbtq9v8HZ0xfeLPqFtnE8hoOATQv/KYEcUhhyGJPYmSx8eao7QgT22wICafp/qD6ZqiT0yG85GieGJ4HBIydB05FDPPA8gGlH/16ku8l8TmLCbM/yb971AcKZ48A4@C85tGHszBZ7GD331FvMHUG2V8ITaYkO0mwt0/OLB0K4FvTNjbyMbcjWCE8UtQAwNbUP/pOsCPQ59AQ3H@kNrGK1poOOgZaQmyDOuRLp1bZBmPTZcz7rTcQY9cvQhlUn3cjQaPaLR8WX0TeL8bg5wVR/yNgZ9@PLUojadhT9@fYQrBC7J2dwHtLH/DH@QwBj7lIjMSMD5GQmImlo9CQgbZYMkOPa72e1@Aw)
] |
[Question]
[
These are the hosts of the "Weekend Update" news segment on *Saturday Night Live*, with the years they hosted and their initials:
```
Chevy Chase 1975-1976 CC
Jane Curtain 1976-1980 JC
Dan Aykroyd 1977-1978 DA
Bill Murray 1978-1980 BM
Charles Rocket 1980-1981 CR
Gail Matthius 1981 GM
Brian Doyle-Murray 1981-1982 BD
Mary Gros 1981-1982 MG
Christine Ebersole 1982 CE
Brad Hall 1982-1984 BH
Christopher Guest 1984-1985 CG
Dennis Miller 1985-1991 DM
Kevin Nealon 1991-1994 KN
Norm MacDonald 1994-1997 NM
Colin Quinn 1998-2000 CQ
Jimmy Fallon 2000-2004 JF
Tina Fey 2000-2006 TF
Amy Poehler 2004-2008 AP
Seth Meyers 2006-2014 SM
Cecily Strong 2013-2014 CS
*Colin Jost 2014-pres CJ
*Michael Che 2014-pres MC
*At the time of this writing, present is 2017.
```
I got most of the years [this website](http://www.saturday-night-live.com/history/weekendupdate.html), but later ones I got from [Wikipedia](https://en.wikipedia.org/wiki/Weekend_Update#Timeline).
The task is simple. Given a range of years, output the initials of the person who was host during the most years in that time period. If there is a tie, output the initials of all the hosts that tied. Note that sometimes "Weekend Update" only has 1 host and sometimes it has 2.
For example, if the input is `1984-1985`, output `CG` because he was the only person to host during both of those years.
# Specifics
* Input is flexible, but it will always consist of a start year and a later end year. Also you don't need to include the first two digits of the year: `95-05` is fine for `1995-2005`.
* Assume all ranges are inclusive: `1982-1984` means `1982,1983,1984`.
* For input, the earliest start year is `1975` and the latest end year is `2017`
# Examples
* `1983-1987` => `DM` (he hosted '85,'86,'87`)
* `1999-2001` => `CQ JF TF` [`CQJFTF` also ok] (all hosted during two of those years)
* `1975-2017` => `SM` (has 9 years!)
* `1990-2000` => `KN NM` (both have 4 years)
* `2013-2015` => `SM CS CJ MC` (all have 2 years)
[Answer]
# [Python 2](https://docs.python.org/2/), 291 bytes
```
def f(b,e):
s=''.join('A AB BC BCD BD BDE EFGH GHJ J JK KL L L L L L LM M M MN N N N O O OPQ PQ PQ PQ PQR QR QRS RS RS S S S S ST STUV UV UV UV'.split()[b-1975:e-1974]);C=s.count;return''.join({'CJDBCGBMCBCDKNCJTASCCMCCAMRMDGEHGMNMQFFPMSJC'[ord(h)-65::22]for h in s if C(h)==max(map(C,s))})
```
[Try it online!](https://tio.run/##VZBNb4JAEIbv/oq5wSZIAEspGA4wfAW6VMX2YjxohUBTgQAmNU1/O100VprnyWzyznuYbH3u8qpU@v6QZpDxeyElxgRak@PEj6ooec4CywYbmQ7Ygy64nh@AH4TAiCB6hhEULsRw5WVgsYSRK7iYwNU/1szXN7jJiW39WXQ82eynsq6pRjo8D1syR7MV36tT2c2btDs15e3Ubw5Dx0bfpsiOjWIM11aCSBEtuqKO7wY@jenS8xY0CZHbVM2Bz8n0UTUMRdlmVQM5FCW0UGSAbGOax90Xf9zVPAotIT@kr5ui7NgvyfrTTGBDI5N7pOuCIknyONJUFsn/W9LQku4RK8yGlkr6Xw "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 325 bytes
```
def f(x,y):a=sum([s.split(',')for s in('CC CC,JC JC,DA JC,DA,BM JC,BM JC,BM,CR CR,GM,BD,BD BD,MG,CE,BH BH BH,CG CG,'+'DM '*6+'DM,KN KN KN KN,'+'NM '*4+'CQ CQ CQ,'+'JF,TF '*4+'JF,TF,AP TF,AP TF,AP,SM AP,SM AP,'+'SM '*5+'SM,CS SM,CS,'+'CJ,MC '*4).split()[x-1975:y-1974]],[]);c=a.count;print{s for s in a if c(s)==max(map(c,a))}
```
[Try it online!](https://tio.run/##TZBBa4NAEIXv/RVz291mGjSJtSZ4iJPGYjG0sTfJYbGVCtVI1kBC6W83jqml8Phm3nvLwm59bj731aRt3z9yyOUJz2qufXMsZWrGpv4qGilQqHx/AANFJQUREGFEEBGulldiEPMyEGkLtMUwxmDVCTrGIdIjBk/QCykEClGMxCoGcXvPE583MIibDTezkaBX6MVZtMa39TXuV1y@wD9iEsMfu@MJX@HwREqgJ8cUYUx8i/p9oEpPd7bnOvMzj9luh@lOLTJfj7P9sWoW9aGomm8DwyeAhiKHTBrl@6U@yVLXMkOt1E@bS9t7mGIHV92w8TycWJZ9Na7TGXtoLG4sNl045cZR7QU "Python 2 – Try It Online")
### 284 bytes, but more boring:
```
def f(x,y):a=sum([s.split(',')for s in'eJx1z9sJwzAUBNFWtoBpwlrZCgrX+NV/LVEiHBxMYDjs79qyqVY1eeiS4j1O8SZvlCDllppR8Eh66BMuciGHbvGcdcYc+ua1R504Jv2RYdFF9tDV3/DexZVov26+ACfwONE='.decode('base64').decode('zip').split()[x-1975:y-1974]],[]);c=a.count;print{s for s in a if c(s)==max(map(c,a))}
```
[Try it online!](https://tio.run/##PY9Nb4JAFEX3/RXsmIlUGeRDNCxE1MZUTTSlReNiHIaKQRgZQLDpb6cQYzfv5tyzuY9V2SmJlbr2aSAEoJQqOMQWzy9gz7ucRWEGREmEQZIKXAhjkS5KdDf54nYff9ir2WeW2OwWpbvJd/rVWbm9d3cavtnl0nPO3DCv1dX1EKXhVj2j9WC7K6KJE0WMbQbTk67by5yE87djMSc@8Ugnx2ijyeqiUDaeP5uZmeP2ew4td25SKHpnPAlu69XUErs@JYlPgXjEnOqqCP@Le8gaeuyG@/IVmYY2rNpQDwdpf4AjYuEuSfI4G7E0jLMfLjx/E7AQBgIBHFrWBZfgghkgEobwtw4AMgd9qTkGfGnBNCVFltEDDK0B9DRya@QWmrLfGg3Wfw "Python 2 – Try It Online")
[Answer]
## JavaScript (ES6), ~~201~~ ~~200~~ 199 bytes
Takes the year range in currying syntax `(a)(b)`. Returns a string made of concatenated initials.
```
a=>b=>"MCCJCSSMAPTFJFCQNMKNDMCGBHCEMGBDGMCRBMDAJCCC".match(/../g).reduce((o,c,n)=>(s=(a<(x-='0017240243612010012111'[n])?x:a)-(b<(y=+'3318464233612011012141'[n]+x)?b:y))>m?o:s<m?(m=s,c):c+o,m=x=2014)
```
### Test cases
```
let f =
a=>b=>"MCCJCSSMAPTFJFCQNMKNDMCGBHCEMGBDGMCRBMDAJCCC".match(/../g).reduce((o,c,n)=>(s=(a<(x-='0017240243612010012111'[n])?x:a)-(b<(y=+'3318464233612011012141'[n]+x)?b:y))>m?o:s<m?(m=s,c):c+o,m=x=2014)
console.log(f(1983)(1987)) // => DM
console.log(f(1999)(2001)) // => CQ JF TF
console.log(f(1975)(2017)) // => SM
console.log(f(1990)(2000)) // => KN NM
console.log(f(2013)(2015)) // => SM CS CJ MC
```
] |
[Question]
[
Write a program that can validate a PNG file. Your program should follow the [PNG spec](https://www.w3.org/TR/PNG/) and must validate the PNG signature and the 4 critical chunks: `IHDR`, `IDAT`, `PLTE` and `IEND`. Your program must not validate the contents of ancillary chunks, except for their CRC checksums.
Your program must validate the presence of the `PLTE` chunk (that is, `This chunk shall appear for colour type 3, and may appear for colour types 2 and 6; it shall not appear for colour types 0 and 4. There shall not be more than one PLTE chunk.` [ref](https://www.w3.org/TR/PNG/#11PLTE))
Your program must validate chunk order.
Your program must validate CRC checksums.
Your program must validate the compressed data.
You may use runtime code generation+execution (e.g. compress the program itself, or algorithmically write the program itself a la kolmogorov complexity). If any binary blobs are used, their source code will be considered when calculating size.
External library source code size counts towards program size. This is to discourage image-parsing external libraries while allowing e.g. a CRC32 library. Libraries defined in the language specification (aka "standard libraries") don't count as external.
No regex.
You must specify how to input the file. Your program must output to stdout "true" or "false" to answer the question "is the file a valid PNG?".
Failing test files:
```
This file is false.
```
(Yes, that's a plaintext file. Newline-terminated.)
Passing test files:

[Answer]
# Java - 1220 chars
```
import java.io.*;import java.util.zip.*;interface Q{static int i(byte[]b,int i){return java.nio.ByteBuffer.wrap(b).getInt(i);}static boolean v(int x,int...a){return java.util.stream.IntStream.of(a).anyMatch(y->x==y);}static void main(String[]a){byte[]b={-119,80,78,71,13,10,26,10},c={0,0,0,0},d=b.clone();OutputStream I=new InflaterOutputStream(new ByteArrayOutputStream());int l,k,i,t,r=k=i=l=0,H=1229472850,D=1229209940,P=1347179589,E=1229278788,L=8192;DataInputStream in=new DataInputStream(System.in);boolean v;CRC32 C=new CRC32();try{for(v=(in.read(b)>7&&java.util.Arrays.equals(b,d));v=v&&(l=in.readInt())>=0&&in.read(c)>3;){C.update(c);for(byte B:c)v&=(B|32)<123&&(B|32)>96;for(r=0;v&&(t=in.read(b=new byte[l-r>L?L:l-r]))>0;r+=t){C.update(b);if(i(c,0)==D)if(v=v(i,2,3))I.write(b);if(i(c,0)==H&&r==0)if(v=i==0&&t==13){v=i(b,0)>0&&i(b,4)>0&&b[10]==0&&b[11]==0&&v(b[12],0,1)&&((k=b[9])==0&&v(b[8],1,2,4,8,16))||(v(k,2,4,6)&&v(b[8],8,16))||(k==3&&v(b[8],1,2,4,8));i=(v&&k==3)?1:v?k&2:3;}}v&=(k=in.readInt())==(int)C.getValue();C.reset();if(v&(t=i(c,0))==P){v=v(i,1,2)&&l<=768&&l%3==0;i=3;}if(v&t==E){v=l==0;break;}if((t&L)!=0||((t&L<<16)==0&&!v(t,P,H,E,D)))v=0>1;}}catch(IOException e){v=0>1;}System.out.println(v);}}
```
Input is from stdin.
] |
[Question]
[
What's great about golfing is not having to deal with errors. Except this time you won't get off so lightly! I need to do some arithmetic with certain limitations, and I wan't to know what goes wrong if anything.
# Challenge
Given a list of signed integer values `[n1..n11]`, give the following result *or* the first error that occurred.
```
(((((((((n1+n2)-n3)^n4)/n5)*n6)+n7)-n8)^n9)/n10)*n11
```
The same in reverse polish notation:
```
n1 n2 + n3 - n4 ^ n5 / n6 * n7 + n8 - n9 ^ n10 / n11 *
```
The operators have the following limitations:
* `0^0` → error `0^0 is undefined`
* `0^a` when `a<0` → error `Negative exponent`
* `a/0` → error `Division by zero`
* `a/b` when `mod a b != 0` → error `Uneven division`
* for any operator: `result < 0` → error `Integer underflow`
* for any operator: `result > 99` → error `Integer overflow`
* for any operator: either input value or result == 13 → error `13 is bad luck!`
Errors occur left to right, so `13/0` = error `13 is bad luck!`.
## Scoring
The shortest code in bytes wins. To encourage readability string literals used for errors won't count towards the score.
The output format isn't strict but all seven errors plus a correct value must be distinguishable. Your program/function must retain control flow until the end, so e.g. any exceptions must be caught.
Standard loopholes are disallowed.
# Examples
```
[6,7,14,2,0,1,2,3,4,0,6] → error `13 is bad luck!`
[6,6,14,2,0,1,2,3,4,0,6] → error `Integer underflow`
[6,6,12,0,0,1,2,3,4,0,6] → error `0^0 is undefined`
[6,6,12,2,0,1,2,3,4,0,6] → error `Division by zero`
[6,6,10,6,12,1,2,3,4,0,6] → error `Uneven division`
[6,6,10,6,8,17,2,13,4,0,6] → error `Integer overflow`
[6,6,10,6,8,7,99,13,4,0,6] → error `Integer overflow`
[6,6,10,6,8,7,9,99,4,0,6] → error `Integer underflow`
[6,6,10,6,8,7,9,55,-2,0,0] → error `Negative exponent`
[6,6,10,6,8,7,9,56,2,0,8] → error `Division by zero`
[6,6,10,6,8,7,9,56,2,9,12] → error `Integer overflow`
[6,6,10,6,8,7,9,56,2,9,11] → 99
```
[Answer]
## Haskell, ~~190~~ ~~186~~ 185 bytes
311 bytes total, 185 bytes without the string literals.
```
e=Left
0#0=e"0^0 is undefined"
b#_|b<0=e"Negative exponent"
b#a=t$a^b
0!a=e"Division by zero"
b!a|mod a b>0=e"Uneven division"
b!a=t$div a b
t 13=e"13 is bad luck!"
t x|x<0=e"Integer underflow"|x>99=e"Integer overflow"|1<2=Right x
f(x:y)=foldl(>>=)(t x)$zipWith id(cycle[q(+),q(-),(#),(!),q(*)])y
q=((t.).).flip
```
This wraps the error handling in the `Either e` monad, i.e. the result is either `Left <ErrorMsg>` or `Right <Number>`, for example:
```
*Main> f [6,6,10,6,8,7,9,56,2,9,11]
Right 99
*Main> f [6,6,10,6,8,7,9,56,2,0,8]
Left "Division by zero"
```
How it works: define custom versions for operators with individual error handling, i.e. `#` for `^` and `!` for `/` (resp. `div` as it is called in Haskell) and lift the others (`+`, `-`, `*`) via `q` into the monad. The main function `f` creates a list of unary function form the numbers (without the first one) and the list of the operators in order, e.g. `[+6, -10, #6, !8, ...]` and reduces this list by feeding the first number into a chain of `>>=`.
Edit: @Angs found a bug. Fixing it saved 4 bytes.
] |
[Question]
[
*Hey guys, first time poster here. I went on Coderoulette recently and some guy posted this question. I looked around online but it doesn't seem to be anywhere. I figured I would post it here for anyone who is a fan of these types of problems. Enjoy!*
---
Alexa is a druid who loves Mathematics! She lives in the land of Alfa, taking care of a tea plantation.
The plantation has N plants and the height of the ith plant is Hi.
Alexa has developed a recent interest in palindromes. She wants to crop the plants so the height of the plants forms a palindrome (without any reordering). She has 2 spells in her arsenal- the 'Growlith' spell will increase the height of a plant by 1 unit, the 'Shrinkooza' spell will decrease the height of a plant by 1 unit. The 'Growlith' and 'Shrinkooza' spells cost A and B units of magic respectively. Help Alexa find the minimum units of magic, that shall enable her to fulfill her objective.
### Input Format
First line contains an integer T. T testcases follow.
First line of each test case consists of 3 space-separated integers N, A and B.
Next line consists of N space-separated integers, the initial height of the plants.
### Output Format
Print the answer to each test case on a new line.
### Constraints
1 <= T <= 10
1 <= N <= 105
0 <= A, B <= 108
1 <= Hi <= 103
---
## Example
### Input
```
1
5 2 2
1 6 2 3 4
```
### Output
```
12
```
### Explanation
She can use the 'Growlith' spell on the first plant 3 times and the 'Shrinkooza' spell on the second plant 3 times to form 4 3 2 3 4.
### Challenge
Write code that will create a palindrome using the least units of magic possible for N plants.
### Scoring
This is code golf. The shortest code in bytes wins.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 20 bytes
```
WU|vy#‚ø€¥˜Ä2ä`OX*,
```
**Explanation**
```
WU # store minimum cost in X
|v # for each testcase
y# # convert to list split on spaces
‚ø # zip with its own reverse
€¥ # deltas of each pair
˜Ä # deep flatten and take absolute value
2ä # split into 2 pieces
` # flatten (leaves the smaller piece on top of the stack)
O # sum
X* # multiply with minimum cost
, # print
```
[Try it online!](http://05ab1e.tryitonline.net/#code=V1V8dnkjw4LigJrDuOKCrMKly5zDhDLDpGBPWCos&input=WzIsIDJdCjEgNiAyIDMgNAoxIDIgMyAyIDEKNSAyIDMgMiAxCjEgNCAyIDcgMw)
[Answer]
## Julia, 88 Bytes
```
f(l,A,B)=reduce(+,map(abs,map(sum,[zip(-l,reverse(l))...][1:fld(end,2)])))*min([A,B]...)
```
**Explained:**
If I am not mistaken, all we have to do is either grow all necessary plants or shrink them (depending on which operations is less expensive)
1. zip input list with a reverse of itself (align corresponding heights)
2. only look at first half of the list (floor when length is odd)
3. sum the differences
4. multiply with minimum cost (A or B)
**Example**
```
f([1,6,2,3,4],1,2) -> 6 (grow plant 1 and 4, yields [4,6,2,6,4])
f([1,6,2,3,4],3,2) -> 12 (shrink plant 2 and 5, yields [1,3,2,3,1])
```
**Note:**
As there is still a discussion about the input format, I disregarded it for the moment.
**Update:**
Updated to output energy, as I think that outputing the actual palindrome is more challenging I attach my previous code here (76 Bytes):
```
f(l,A,B)=reduce(hcat,map(x->sort([x...]),[zip(l,reverse(l))...]))[A>B?1:2,:]
```
[Answer]
## JavaScript (ES6), 70 bytes
```
f=(a,g,s)=>a.reduce((t,h,i)=>t+Math.abs(a[a.length+~i]-h),0)*(g>s?s:g)/2
```
Double-counts the differences, but we only need to make half the changes, which is achieved by dividing by 2 at the end.
] |
[Question]
[
## Challenge
Output the person on PPCG who has cast the most upvotes and the person who has cast the most downvotes.
## Voters
You should only look at the people who have cast more than 1000 votes in total.
To find the person who upvotes the most, you should the find the person with the highest `upvotes/total votes` value. Similarly, the person who downvotes the most has the highest `downvotes/total votes` value.
## Rules
Your output should be the two users' id (the number found in the URL of the user's page). You must put the upvoter first.
In the case of a tie, you must choose the user whose id is the lowest.
The Stack Exchange API is allowed, but entries in T-SQL using the Stack Exchange Data Explorer are disallowed.
## Winning
The shortest code in bytes wins.
[Answer]
# Java, 1106 bytes
```
import java.io.*;import java.util.regex.*;()->{String u="",y="",z="",s,t;float h=0,a,l=0,d;int i=-1,k=-1;Matcher m;Pattern p=null;while(i<=k){try(BufferedReader g=new BufferedReader(new InputStreamReader(new java.net.URL("https://codegolf.stackexchange.com/users"+(k==-1?"?tab=NewUsers&sort=creationdate":"/"+i+"/?tab=topactivity")).openStream()));){while((s=g.readLine())!=null){Integer v=0;if(k==-1&s.contains("users/")&!s.contains("profile-me")){m=p.compile("(?<=users/)(\\d+)").matcher(s);if(m.find()){k=v.parseInt(m.group());break;}}if(s.contains("User")){m=p.compile("(?<=User )(.*)(?= - P)").matcher(s);if(m.find())u=m.group();}if(s.contains("Cast")){m=p.compile("(?<=\\>\\().*(?=\\)\\<)").matcher(s);if(m.find()&&(v=v.parseInt(m.group().replace(",","")))>1000){while(1>0){s=g.readLine();m=p.compile("(\\d*,?\\d+)(?=\\<.*\\>)").matcher(s);if(m.find()){if((t=g.readLine()).contains("up")&&(a=0f+v.parseInt(m.group().replace(",",""))/v)>h){y=""+u;h=a;}if(t.contains("down")){if((d=0f+v.parseInt(m.group().replace(",",""))/v)>l){z=""+u;l=d;}break;}}}}}}}catch(Exception e){}}System.out.print(y+"\n"+z);}
```
As a full class:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.*;
public class C {
public static void main(String[] args) throws Exception {
String u="", y="", z="", s, t;
float h = 0, a, l = 0, d;
int i = -1, k = -1;
Matcher m;
Pattern p = null;
while (i < k) {
// System.out.println(i);
try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL("https://codegolf.stackexchange.com/users" + (k == -1 ? "?tab=NewUsers&sort=creationdate" : "/" + i + "/?tab=topactivity")).openStream()));) {
while ((s = br.readLine()) != null) {
Integer v = 0;
if (k == -1 && s.contains("users/") && !s.contains("profile-me")) {
m = p.compile("(?<=users/)(\\d+)").matcher(s);
if (m.find()) {
k = v.parseInt(m.group());
break;
}
}
if (s.contains("User")) {
m = p.compile("(?<=User )(.*)(?= - P)").matcher(s);
if (m.find())
u = m.group();
}
if (s.contains("Cast")) {
m = p.compile("(?<=\\>\\().*(?=\\)\\<)").matcher(s);
if (m.find() && (v = v.parseInt(m.group().replace(",",""))) > 1000) {
while (true) {
s = br.readLine();
m = p.compile("(\\d*,?\\d+)(?=\\<.*\\>)").matcher(s);
if (m.find()) {
if ((t = br.readLine()).contains("up") && (a = 0f + v.parseInt(m.group().replace(",",""))/v)>h) {
y = ""+u;
h = a;
}
if (t.contains("down")) {
if ((d=0f + v.parseInt(m.group().replace(",",""))/v)>l) {
z = ""+u;
l = d;
}
break;
}
}
}
}
}
}
} catch (Exception e) {}
}
System.out.print(y+"\n"+z);
}
}
```
One word: Damn.
I mean, I've always wanted to do a challenge like this, but boy was it a doozy.
I didn't use the Stack Exchange API (don't know what it is, where to access it, or how to use it :P), so I basically had to do everything on my own; having the program crawl through each of the nearly 60,000 PPCG users' profile pages for the right data, looking up the HTML scripts and accounting for how the vote totals were laid out differently for different users1, and debugging (which was, perhaps unsurprisingly, a *huge* pain). And let me just say, this code could probably use some *serious* optimization. It takes well over two hours for the program to finish running on my machine, though most of the time is probably used opening the connections to the sites.
So here's a quick rundown of how it works:
1. Create `String` variables to hold the upvotingest and downvotingest users on PPCG.
2. Figure out the total number of active (and deleted/nonexistent) user accounts there are on the site. The program visits <https://codegolf.stackexchange.com/users?tab=NewUsers&sort=creationdate> and looks for the first user on the page, who happens to be the most recent addition to the community, and as such has the highest ID number. This ID number is set to be the total number of iterations for the loop.
3. Start at ID 1 and visit <https://codegolf.stackexchange.com/users/#>, where the pound symbol represents the ID. Parse the HTML code ([with regex͠,̰ nőͣ l͇̪e̐̃s̸͖̚͜͝s̡͍̲̫̋ͯ](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)) and collect the user's username, vote total, upvote total, and downvote total.
4. Check to see if the upvotes to total votes ratio is larger than the current largest ratio, and set the current ratio to the new ratio if necessary. Do the same for the downvotes to total votes ratio, and also set the upvotingest and downvotingest user names when needed.
5. Do steps 3 and 4 another (near) 60,000 times, incrementing the ID each time. (This takes care of the event when there is a tie.) If the user doesn't exist, either nothing matches or an Exception is thrown, and move on.
6. Print the upvotingest and downvotingest users.
Yes, there are quite a few places where I can shave off a few bytes (especially on the strings where I use the `contains` method), but I'll save that for later... maybe.
If you decide to run this program, be prepared to wait a couple hours for it to finish execution.
Here's a screenshot of the output:
[](https://i.stack.imgur.com/iE6gY.png)
In case it's difficult to read, at the bottom it says...
```
gnat
Peter Taylor
```
...and the total time it took for the program to finish: a whopping two hours, forty-eight minutes, and twenty-three seconds!
---
1 The instance on which this occurred had to do with how recently the user voted. If the user voted at least once within the past week or month, two(?) additional stats showing how many times they voted over the past week or month appear on their activity page.
] |
[Question]
[
Wikipedia has [several restrictions](https://en.wikipedia.org/wiki/Wikipedia:Naming_conventions_%28technical_restrictions%29) on an article's title. I summarize them here:
* It may not be empty.
* It may not begin with a lowercase letter. A character is considered lowercase if it has an `Ll` after its name in [UnicodeData.txt](ftp://ftp.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt).
* It may not contain any of the characters: `# < > [ ] | { } _`
* It may not be `.` or `..`
* It may not begin with `./` or `../`.
* It may not contain `/./` or `/../`.
* It may not end with `/.` or `/..`.
* It may not contain any space character (a character is considered a space if it has `Zs` after its name in UnicodeData.txt) except for `U+0020 SPACE`.
* It may not contain more than one consecutive space.
* It may not consist entirely of spaces.
* It may not begin with a colon.
* It may not begin with the language prefix of any of the [292 language editions of Wikipedia](https://en.wikipedia.org/wiki/List_of_Wikipedias) followed by a colon. This includes `en:` for English.
* It may not begin with the prefix of [another Wikimedia Foundation project](https://en.wikipedia.org/wiki/Help:Interwiki_linking) or its shortcut followed by a colon.
* It may not contain the character `%` followed by two hexadecimal digits.
* It may not contain a named [HTML character entity](https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references). Numbered entities are already forbidden through `#`.
* It must contain no more than 256 bytes when encoded in UTF-8.
Write a function that takes in a string (or whatever data type your language normally uses to manipulate text) and outputs a boolean indicating whether the string is a valid Wikipedia article title. You are permitted to use networking libraries to download and read from any page that I linked in this question.
[Answer]
# Retina, 1221 bytes
```
^(?=...:|\w|(^|.*/)\.\.?(/.*|$)|.*([#<>\[\]|{}]| |__|%[0-9a-fA-F]{2}|&#(\d{4}|[0-9a-fA-F]{4}|a(mp|pos)|(l|g|quo)t);|~~~)|[ _]*$|.{257,}).*
no
^(?!no$).+
yes
```
where `...` is:
```
(w(ik(i(s(pecies|ource)|v(ersity|oyage)|([mp]edi|dat)a|(book|new)s|quote|tech)|t(ionary)?)|m(i[dlnt]|c[ahz]|a[ru]|b[de]|d[ek]|h[ku]|n[lo]|r[su]|u[ak]|fi?|mk|pl|se|tw)|ar?|uu|o)?|m(e(dia(wikiwiki|zilla)|t(awikipedi)?a)|a(p-bms|i)|[klnr]|[ghi]|[iz]n|[st]|yv?|df|hr|rj|us|wl)|s([degh]|t(rategy|q)|i(mple)?|[klmnoqr]|c(n?|o)|pecies|[uvw]|[st]|ah?|rn|zl)|b(a(t-smg|r?)|ug(zilla)?|e-tarask|[eghi]|[mno]|[rs]|cl|jn|py|xr)|t([aghw]|e(stwiki|t)?|[iklno]|oollabs|[rst]|yv?|pi|um)|c(o(mmons)?|h[ory]?|[es]b?|bk-zam|[uvy]|rh?|do|kb|a)|p(habricator|a[gmp]?|n[bt]|[st]|f?l|ih?|cd|dc|ms)|n(ds(-nl)?|[glno]|a[hp]?|[vy]|ew?|ov|rm|so)|a([afkm]|r[cz]?|[vyz]|ng?|st?|z?b|ce|dy|ls)|k([gijklmnor]|[uvwy]|a[ab]?|sh?|bd|oi|rc)|z(h(-(classical|min-nan|yue))?|e?a|u)|f([afijory]|oundation|iu-vro|r[pr]|ur)|l([gi]|[no]|ad?|be?|tg?|ez|ij|mo|rc|v)|r([nw]|o(a-(tara|rup))?|my?|ue?)|g(a[gn]?|[dln]|o[mt]|[uv]|lk)|h([eiortu]|a[kw]?|[yz]|if|sb)|i([adegikostu]|ncubator|lo)|v(e(c?|p)|oy?|ls|i)|d([vz]|[ae]|iq|sb)|e([elnostu]|ml|xt)|u([gz]|[kr]|dm)|j([av]|bo)|x(al|mf|h)|[nbqsvcdm]|o[cmrs]|y[io]|qu|)
```
(I used [this regex optimizer](https://myregextester.com/index.php) and manutally typed in all the data)
[Try it online without the `...`!](http://retina.tryitonline.net/#code=Xig_PVthLXo6XXwoXnwuKi8pXC5cLj8oLy4qfCQpfC4qKFsjPD5cW1xdfHt9XXwgIHxfX3wlWzAtOWEtZkEtRl17Mn18JiMoXGR7NH18WzAtOWEtZkEtRl17NH18YShtcHxwb3MpfChsfGd8cXVvKXQpO3x-fn4pfFsgX10qJHwuezI1Nyx9KS4qCm5vCl4oPyFubyQpLisKeWVz&input=QWJjJiMyNTYzOw)
] |
[Question]
[
I have a new programming language called Brussels-Sprout. Brussels-Sprout functions in an array of 256 boolean values, all initialized to zero, has one instruction pointer, and one "bit index".
After each (non-branching) instruction is executed, the instruction pointer is incremented by one. If the instruction pointer goes off the right side of the instruction array, the program terminates. Going off the left side is undefined behavior.
If the bit index is outside the bounds of the array, it should be reset to 0.
Brussels-Sprout uses the following keywords, which are always lowercase:
`chew` - Invert the value in the array at the bit index. (flip the bit at the bit index)
`swallow` - Increment the bit index.
`vomit` - Decrement the bit index.
`complain` - Output the bit at the bit index to stdout, or equivalent output log.
`feedtodog` - If the bit at the bit index is 0, skip the next instruction. Otherwise, increment instruction pointer by 1.
`playwithfood` - If the bit at the bit index is 1, jump backwards 2 instructions. Otherwise, increment instruction pointer by 1.
If an instruction not on this list is executed, undefined behavior occurs.
I'm sure that this sounds like a very certain other turing-tarpit programming language. But since this programming language operates in boolean values and not bytes, I think it is different.
Test cases:
```
chew complain -> 1
swallow chew swallow chew swallow vomit complain playwithfood -> 11
chew complain swallow chew complain swallow chew complain swallow complain -> 1110
chew feedtodog undefinedbehaviour complain -> 1
```
Your challenge is to write an interpreter for Brussels-Sprout. This is code golf, so shortest program wins!
[Answer]
# Python ~~3~~ 2, ~~200~~ ~~187~~ ~~149~~ ~~146~~ 136 bytes
*-9bytes thanks to Cyoce*
```
def f(n,a=[0]*256,x=0,z=0):
while 1:y=a[z];exec'a[z]^=~1 z+=1 z-=1 print-y/2 if~y:x+=1 if~~y:x-=3'.split()["wlipdy".find(n[x][3])];x+=1
```
Input as list, exits by error. Bonus feature: you can specify start array, start IP, and start DP in that very exact order.
[Answer]
# SpecBAS (modern Sinclair BASIC interpreter) 202 Bytes
```
1 INPUT a$:DIM b(256)BASE 0,i$(),a$(SPLIT a$," "):DO 6:READ b,i$(b):LOOP:b=0,i=1:DO:c=b(b):EXECUTE i$(CODE a$(i,4)-99):b&=255,i+=1:LOOP:DATA 20,"b(b)=1-c",9,"b+=1",6,"b-=1",13,"?c;",1,"i+=c",22,"i-=3*c"
```
Or to make it a little clearer:
```
1 INPUT a$:
DIM b(256) BASE 0,i$(),a$(SPLIT a$," "):
DO 6:
READ b,i$(b):
LOOP:
b=0,i=1:
DO:
c=b(b):
EXECUTE i$(CODE a$(i,4)-99):
b&=255,i+=1:
LOOP:
DATA 20,"b(b)=1-c",9,"b+=1",6,"b-=1",13,"?c;",1,"i+=c",22,"i-=3*c"
```
Uses some features that weren't available in the 80s, so there's that. Also shameless rips off some of the techniques in other entries. Sorry about that!
Input is from the user at runtime. Execution ends with an error "Subscript wrong".
[Answer]
# Java 8
## 1. Relaxed version (~~301~~ ~~283~~ ~~280~~ ~~277~~ 275 bytes)
Golfed as this:
```
class C{static int i,j,x,b[]=new int[256];public static void main(String[]z){Runnable[]r=new Runnable[26];r[20]=()->b[i]=-~x;r[9]=()->i++;r[6]=()->i--;r[13]=()->System.out.print(x);r[1]=()->j+=x;r[22]=()->j-=3*x;for(;;){x=b[i];r[z[j].charAt(3)-99].run();i*=~(i>>8)&1;j++;}}}
```
Somewhat ungolfed version (whitespaces and comments added):
```
class C {
// Declared as static so they may be changed inside the lambdas without the compiler complaining about that.
// i is the bit index and j is the instruction pointer.
// x is just to avoid refering to b[i] in order to save 3 bytes.
// b is our array. Uses ints instead of booleans to save bytes and use some clever math tricks.
static int i, j, x, b[] = new int[256];
public static void main(String[] z) {
// An array of lambdas. The index is the ascii code of 4th letter of the command name subtracted from 99.
// Thanks for CatsAreFluffy for telling about the 4th letter trick.
Runnable[] r = new Runnable[26];
r[20] = () -> b[i] = -~x; // chew
r[9] = () -> i++; // swallow
r[6] = () -> i--; // vomit
r[13] = () -> System.out.print(x); // complain
r[1] = () -> j += x; // feedtodog. It is 1 or 0 instead of 2 and 1 due to the j++ down there.
r[22] = () -> j -= 3 * x; // playwithfood. It is -3 or 0 instead of -2 and +1 due to the j++ down there.
// This is the interpreter itself. Runs forever (or until an exception is raised).
for (;;) {
x = b[i];
// Fetch an instruction and runs it. May throw an exception or execute some arbitrary instruction if the instruction name is unknown or was mistyped.
r[z[j].charAt(3) - 99].run();
// Resets the bit index if out of range.
i *= ~(i >> 8) & 1;
// Next instruction. No special treatment for branching needed because they already considers this.
j++;
}
}
}
```
We surely should have testcases. I am not sure if there is some bug hiding out there.
Anyway I run it with that (input is given as command line arguments):
```
chew complain swallow chew complain swallow chew complain swallow complain
```
And here is the output:
```
1110
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at C.main(C.java:1)
```
The `ArrayIndexOutOfBoundsException` is the standard way to finish the program, it is not a bug!
BTW, this answer abuses the fact that the 4th char of each command is different than each other (thanks CatsAreFluffy). This means that `whew` is interpreted as `chew` and that `yellow` is interpreted as `swallow`.
## 2. Strict version (~~354~~ ~~337~~ ~~334~~ ~~331~~ 329 bytes)
If strict conformance to command names are required (and just looking for the 4th letter in command's name is not enough), then I have this alternative similar answer with 329 bytes:
```
import java.util.*;class C{static int i,j,x,b[]=new int[256];public static void main(String[]z){List o=Arrays.asList("chew","swallow","vomit","complain","feedtodog","playwithfood");Runnable[]r={()->b[i]=-~x,()->i++,()->i--,()->System.out.print(x),()->j+=x,()->j-=3*x};for(;;){x=b[i];r[o.indexOf(z[j])].run();i*=~(i>>8)&1;j++;}}}
```
Somewhat ungolfed version (whitespaces and comments added):
```
// Needed for java.util.List and java.util.Arrays.
import java.util.*;
class C {
// Declared as static so they may be changed inside the lambdas without the compiler complaining about that.
// i is the bit index and j is the instruction pointer.
// x is just to avoid refering to b[i] in order to save 3 bytes.
// b is our array. Uses ints instead of booleans to save bytes and use some clever math tricks.
static int i, j, x, b[] = new int[256];
public static void main(String[] z) {
// Declared as a list so we can use the indexOf method further down. Screw up the generics.
List o = Arrays.asList("chew", "swallow", "vomit", "complain", "feedtodog", "playwithfood");
// An array of lambdas.
Runnable[] r = {
() -> b[i] = -~x, // chew
() -> i++, // swallow
() -> i--, // vomit
() -> System.out.print(x), // complain
() -> j += x, // feedtodog. It is 1 and 0 instead of 2 and 1 due to the j++ down there.
() -> j -= 3 * x // playwithfood. It is -3 and 0 instead of -2 and +1 due to the j++ down there.
};
// This is the interpreter itself. Runs forever (or until an exception is raised).
for (;;) {
x = b[i];
// Fetch an instruction and runs it. Throws an exception on unknown or mistyped instructions.
r[o.indexOf(z[j])].run();
// Resets the bit index if out of range.
i *= ~(i >> 8) & 1;
// Next instruction. No special treatment for branching needed because the branching instructions already considers this.
j++;
}
}
}
```
[Answer]
# Ruby 2, 151 bytes
Saw this because of another golf challenge and was amused enough by it to write it up in Ruby, and was happy to see it got very close to the Python answer (Ruby usually doesn't golf compress quite as well as Python).
```
b=[n=i=0]*256
r=''
(x=b[i=b[i]?i:0]
eval({?w=>'b[i]=1-x',?l=>'i+=1',?i=>'i-=1',?p=>'r<<x.to_s',?d=>'n+=-x',?y=>'n+=x*-3'}[c[n][3]])
n+=1)while(c[n])
r
```
You can put this in a function def that takes 'c' as a list of the commands, and it returns 'r' as the last line which is the result string.
Runs the testcases properly (if the second one is updated to actually output 110 instead of 11 as it currently incorrectly claims is the right answer - see my comment above).
] |
[Question]
[
Your goal is to map a piece of text to a sine curve of the form:
# a sin ( mx - b )
Where *a* and *m* are non-zero rational numbers, *b* is a rational number, and the calculations are in radians.
It doesn't really matter where the origin of your graph is, as long as you fit all the letters in your output. Also, it must be ASCII art, no graphical output.
You can take the equation input in as a string OR you can have a separate input for each parameter: *a*, *m*, and *b*.
Also
### Examples:
Input: "A-well-a", "3sin(x)" or (3,1,0)
Output:
```
-w
a
A e
-
l
l
```
Explanation:
The index of the character is the x-value, and each line represents one y-value. So we take 3sin(x) of the appropriate indices and round them to the nearest integer to get our values:
```
'A' : 3sin(0) = 0 => (0,0)
'-' : 3sin(1) = 2.5244 => (1,3)
'w' : 3sin(2) = 2.7279 => (2,3)
etc. , to give you the rest of the word.
```
---
Input: "Everybody's", "3.5sin(x-2)" or (3.5,1,2)
Calculations:
>
> **3.5sin(x-2)**, x = 0,1,2,3,...,10
> -3.1815,-2.9435,0,2.9435,3.1815,0.4935,-2.6495,-3.3565,-0.9765,2.2995,3.4615,
>
>
>
Output:
```
ry s
'
e b
y
Ev od
```
---
Input: "heard", "4sin(2x)" or (4,2,0)
**4sin(2x)** [0-4] = 0,3.636,-3.028,-1.116,3.956,
Output:
```
e d
h
r
a
```
---
Input: "about","-5sin(x+1)" or (-5,1,-1)
**-5sin(x+1)** [0-4] : -4.205,-4.545,-0.705,3.785,4.795,
Output:
```
t
u
o
a
b
```
---
Input: "the word", "-2.4sin(0.5x-1.2)" or (-2.4,0.5,1.2)
**-2.4sin(0.5x-1.2)** [0-7] : 2.2368,1.5456,0.4776,-0.7104,-1.7208,-2.3136,-2.3376,-1.7904
Output:
```
th
e
word
```
[See also](https://youtu.be/2WNrx2jq184)
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 37 bytes
```
{⍉↑v⌽¨⍵↑¨⍨v←(-∘1-⌈/)⌊.5+⎕×1○⎕-⍨⎕×⍳≢⍵}
```
Takes text as right argument, and then prompts for *m*, *b*, and *a*.
[Answer]
## Python 2, ~~190~~ ~~159~~ 171 bytes
```
import math
a,b,c,d=input()
q=len(a)
s=""
m=int(abs(b)+.5)
for i in range(2*m*q+q):s+=""if i%q else"\n";s+=a[i%q]if i/q==-int(round(b*math.sin(i%q*c-d)))+m else" " print s
```
Example usage:
```
$ python2 surfin2.py
"about",-5,1,-1
t
u
o
a
b
```
~~This can probably be golfed further, but I can't see how at the moment. I just wanted to see this question get at least one answer.~~
EDIT: Decently golfed once I saw how to do it in one pass. May have extra leading and trailing lines, but such was expressly allowed: "It doesn't really matter where the origin of your graph is, as long as you fit all the letters in your output."
] |
[Question]
[
In a preference ballot there are many ways to decide who won. One of which is the [Borda count method](https://en.wikipedia.org/wiki/Borda_count), where we give everyone point based on their places on the ballot.
For example, in these results:
```
10 5 7 2
_____________
1 a d a c
2 b a d b
3 c c b a
4 d b c d
```
The results are
```
1: a : 87
2: d : 60
3: b : 55
4: c : 45
```
Because
```
4*10 is 40
5*3 is 15
7*4 is 28
2*2 is 4
40 + 15 + 28 + 4 is 87
```
Or is words:
We give first place 4 points , second 3, third 2, etc.
So `a` is in first place 17 times, so they get 68 points then they get 15 points for being in second 5 times and 4 points for being in third 2 times for a total of 87 points.
Because this process is a pain, I need you write a program that finds the results for me, but since I have limited space on my PC, your program will have to be as small as possible.
## Your Challenge
Write a program or function the takes an input in this format
```
Number of Ballots : placings, Number of Ballots : placings, Etc...
```
and will output the results in this format:
```
1: a: 90
2: b: 80
Etc...
```
Rules:
This is Code Golf, so the shortest answer that does the task wins
[Standard Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) Apply
Example:
```
Input:
3: A B C, 2: C B A, 1: C A B
Output:
1: A: 13
2: C: 12
3: B: 11
```
This is my first challenge, so please give me all the criticism you so desire, I won't take it offensively.
[Answer]
# Python 2, 248 bytes
```
x={}
for a,b in[y.split(':')for y in raw_input().split(', ')]:
for d,e in[(c,(len(b)/2-i)*int(a)) for i,c in enumerate(b[1::2])]:x[d]=x.setdefault(d,0)+e
for i,(f,g) in enumerate(sorted(x.items(),key=lambda t:-t[1]),1):print '%d: %s : %d'%(i,f,g)
```
Reads the from the standard input (for example, `echo '3: A B C, 2: C B A, 1: C A B' | python borda.py`).
[Answer]
# CJam, 78 bytes
```
q", "%{S%}%_0=,1-:L;{(1<i*}%e_W%L/L{)}%:C;{C.*}%e_$e`$W%C.+{W%{": "}%e_W(<N+}%
```
[Try it Online.](http://cjam.aditsu.net/#code=q%22%2C%20%22%25%7BS%25%7D%25_0%3D%2C1-%3AL%3B%7B(1%3Ci*%7D%25e_W%25L%2FL%7B)%7D%25%3AC%3B%7BC.*%7D%25e_%24e%60%24W%25C.%2B%7BW%25%7B%22%3A%20%22%7D%25e_W(%3CN%2B%7D%25&input=3%3A%20A%20B%20C%2C%202%3A%20C%20B%20A%2C%201%3A%20C%20A%20B)
Holy crap! How did I do this?
When I saw that CJam had a [run length encode/decode](http://cjam.readthedocs.org/en/latest/0.6.5.html#e-and-e-run-length-encode-decode) function, I wondered why someone would use it. Today I found out. Essentially, what this program does is create a string containing each letter once for each vote. Then it sorts the string and uses run length encode to find out how many votes each letter got, and then formats the data.
[Answer]
# Perl 5, 131 bytes
```
for(split/, /,$ARGV[0]){($n,@v)=split/:? /;$s{$v[@v-$_]}+=$n*$_ for 1..@v}$,=": ";map{say++$i,"$_ ",$s{$_}}sort{$s{$b}<=>$s{$a}}@v
```
Use as `perl -E'the string above' 'the input string'`
] |
[Question]
[
Given a matrix M all of whose entries are 0 or 1, we want to known whether there exists a non-zero vector **v** with each element in {-1, 0, 1}, such that M**v** = **0**.
An easy way to do this is just to try all possible vectors v. The M is m by n then there are 3n - 1 such vectors. But of course this is PPCG, so we don't want to do anything so simple!
Instead, this task is to convert the problem into an instance of [Boolean satisfiability problem](https://en.wikipedia.org/wiki/Boolean_satisfiability_problem).
**Input**
An m by n matrix M written out with one row per line each space separated. The first list has m and n on it, space separated. For example this 3 by 4 matrix M.
```
3 4
1 1 0 1
0 1 1 0
0 0 1 1
```
In this case there **does not** exist a non-zero vector v, all of whose entries are -1,0 or 1 such that Mv = 0.
**Output**
An instance of [3-SAT](https://en.wikipedia.org/wiki/Boolean_satisfiability_problem#3-satisfiability) in simplified DIMACS format.
The instance of 3-SAT that you output should be satisfiable if and only if there exists a non-zero vector v, all of whose entries are -1,0 or 1 such that Mv = 0.
The file format will be in a simplified version of the DIMACS format using this specification taken from <http://www.satcompetition.org/2009/format-benchmarks2009.html>
---
```
c
c start with comments
c
c
p cnf 5 3
1 -5 4 0
-1 5 3 4 0
-3 -4 0
```
The file can start with comments, that is lines begining with the character c.
Right after the comments, there is the line p cnf nbvar nbclauses indicating that the instance is in CNF format; nbvar is the exact number of variables appearing in the file; nbclauses is the exact number of clauses contained in the file.
Then the clauses follow. Each clause is a sequence of distinct non-null numbers between -nbvar and nbvar ending with 0 on the same line; it cannot contain the opposite literals i and -i simultaneously. Positive numbers denote the corresponding variables. Negative numbers denote the negations of the corresponding variables.
---
**Score**
I will test your code on a 20 by 40 matrix and the score will be the total number of non-comment lines in your 3-SAT instance. Smaller is better.
**Running time of your code**
Your code should take less than 1 minute to run. I don't want to restrict the languages used but I will attempt to test any code I can run otherwise I will just trust the timing you give. For small instances you could of course just compute the answer but this won't work for matrices of the size I will test.
**More examples**
Your 3-SAT instances for the following matrices should be unsatisfiable.
```
1 1 0 1
0 1 1 0
0 0 1 1
1 1 0 1 0
0 1 1 0 1
0 0 1 1 0
0 0 0 1 1
1 0 0 1 0 1 1 0 0
1 1 0 0 1 0 1 1 0
0 1 1 0 0 1 0 1 1
0 0 1 1 0 0 1 0 1
0 0 0 1 1 0 0 1 0
0 0 0 0 1 1 0 0 1
1 1 0 1 0 0 1 1 1 0 0 1
1 1 1 0 1 0 0 1 1 1 0 0
0 1 1 1 0 1 0 0 1 1 1 0
0 0 1 1 1 0 1 0 0 1 1 1
0 0 0 1 1 1 0 1 0 0 1 1
0 0 0 0 1 1 1 0 1 0 0 1
0 0 0 0 0 1 1 1 0 1 0 0
```
Your 3-SAT instances for the following matrices should be satisfiable.
```
1 1 0 1 1 1 0
1 1 1 0 1 1 1
0 1 1 1 0 1 1
0 0 1 1 1 0 1
0 0 0 1 1 1 0
1 0 1 0 0 1 0 0 0
0 1 0 1 0 0 1 0 0
0 0 1 0 1 0 0 1 0
0 0 0 1 0 1 0 0 1
0 0 0 0 1 0 1 0 0
0 0 0 0 0 1 0 1 0
1 0 0 1 1 1 0 1 0 0 1 1
0 1 0 0 1 1 1 0 1 0 0 1
0 0 1 0 0 1 1 1 0 1 0 0
0 0 0 1 0 0 1 1 1 0 1 0
0 0 0 0 1 0 0 1 1 1 0 1
0 0 0 0 0 1 0 0 1 1 1 0
0 0 0 0 0 0 1 0 0 1 1 1
```
---
**A possible short cut for the busy programmer**
One possibly easier route to tacking this problem could be to output Pseudo-Boolean Constraints. See page 6 of <http://www.cril.univ-artois.fr/PB12/format.pdf> for example. There are then different open source tools and libraries which will convert that to 3-SAT.
[Answer]
# OCaml, ≤ 475318
After defining the basic logic gates (I ended up using only AND and OR), I compose them to make a variable for each of the possible partial sums of a row of M and v. A total of *O(mn2)* variables/clauses are used. This is an initial effort that doesn't make any attempt to simplify the formula. In the worst case (a matrix with no zeroes), it generates 475,318 clauses for a 20x40 matrix.
```
let rec genlist f n =
match n with
| 0 -> []
| n -> let e = f() in e :: genlist f (n-1)
;;
let numvars = ref 0 ;;
type var = V of int | Const of bool;;
let mkv () = incr numvars; V !numvars;;
type clause = Cl1 of var | Cl2 of var*var | Cl3 of var*var*var ;;
let clauses = ref [] ;;
let req (x:clause) = if x <> Cl1(Const true) then clauses := x :: !clauses ;;
let deref = (!);;
let (!) = function
| V x -> V (-x)
| Const c -> Const (not c)
;;
let mkeq (a:var) (b:var) = match a,b with
| Const true, b -> b
| Const false, b -> !b
| a, Const true -> a
| a, Const false -> !a
| a,b -> let v = mkv() in
req@@Cl3 ( !v, a, !b ) ;
req@@Cl3 ( !v, !b, a ) ;
req@@Cl3 ( v, a, b ) ;
req@@Cl3 ( v, !a, !b );
v
;;
let mkxor a b = ! (mkeq a b) ;;
let mkor (a:var) (b:var) = match a,b with
| Const false, b -> b
| Const true, _ -> Const true
| _, Const true -> Const true
| a, Const false -> a
| a,b -> let v = mkv() in
req@@Cl2 ( v, !a ) ;
req@@Cl2 ( v, !b ) ;
req@@Cl3 ( !v, a, b ) ;
v
;;
let mkand a b = ! (mkor !a !b) ;;
let mkorl l =
let rec mkorl_ = function
| a::b::tl -> mkor (mkor a b) (mkorl_ tl)
| a::[] -> a
| [] -> Const false
in mkorl_ (List.filter (function | Const false -> false | _ -> true) l)
;;
let nextsums sums (minus1, zero, plus1) =
let rec nextsums_ prev sums (minus1, zero, plus1) =
match sums with
| cur::next::tl ->
( mkorl [mkand minus1 next; mkand zero cur; mkand plus1 prev] ) ::
( nextsums_ cur (next::tl) (minus1, zero, plus1) )
| cur::_ ->
(mkor (mkand zero cur) (mkand plus1 prev)) ::
( nextsums_ cur [] (minus1, zero, plus1) )
| _ -> [mkand plus1 prev]
in
(mkand minus1 (List.hd sums)) ::
nextsums_ (Const false) sums (minus1, zero, plus1)
;;
let rec entry_zero row v sums maxsum =
if row=[] then List.nth sums maxsum else
if List.hd row = 0 then entry_zero (List.tl row) (List.tl v) sums maxsum else
let (a,b,c) = List.hd v in
let elemv = if List.hd row = -1 then (c,b,a) else (a,b,c) in
entry_zero (List.tl row) (List.tl v) (nextsums sums elemv) (maxsum+1)
;;
let req1of3 (a,b,c) =
req@@Cl2(!a, !b);
req@@Cl2(!a, !c);
req@@Cl2(!b, !c);
req@@Cl3(a, b, c);;
let rdint () = Scanf.bscanf Scanf.Scanning.stdin " %d" (fun x -> x) ;;
let m = rdint();;
let n = rdint();;
let vec = genlist (fun () -> (mkv(), mkv(), mkv()) ) n;;
List.iter req1of3 vec;;
let mat = genlist (fun () -> genlist rdint n) m;;
List.iter (fun row -> req@@Cl1 (entry_zero row vec [Const true] 0) ) mat;;
let nonzeros = List.map (function _,z,_ -> !z) vec ;;
req@@Cl1 (mkorl nonzeros) ;;
exception Bug of string;;
let str_clause (cl:clause) = match cl with
| Cl1(V a) -> Printf.sprintf "%d 0" a
| Cl2(V a,V b) -> Printf.sprintf "%d %d 0" a b
| Cl3(V a,V b,V c) -> Printf.sprintf "%d %d %d 0" a b c
| _ -> raise @@ Bug "there seems to be";;
let (!) = deref;;
Printf.printf "p cnf %d %d\n" !numvars (List.length !clauses) ;;
List.iter (fun cl -> print_endline (str_clause cl)) !clauses ;;
```
[Answer]
# Python, n/a
Not a full answer, but this turns matrices into PBS instances that can be transformed into 3-SAT instances by standard tools:
```
import fileinput
def pos_vec(i): return "x" + str(1 + 2*i)
def neg_vec(i): return "x" + str(1 + 2*i+1)
def print_pseudo(M):
print(" ".join("1 x" + str(i) for i in range(1, len(M[0])*2 + 1)) + " > 0;")
for v in range(len(M[0])):
print("1 {} 1 {} < 2;".format(pos_vec(v), neg_vec(v)))
for r in range(len(M)):
terms = []
for c in range(len(M[0])):
if M[r][c]:
terms.append("1 {}".format(pos_vec(c)))
terms.append("-1 {}".format(neg_vec(c)))
print(" ".join(terms) + " = 0;")
M = [[int(b) for b in line.split()] for line in fileinput.input()]
print_pseudo(M)
```
] |
[Question]
[
**Overview:**
Your challenge is to write a program that will play minesweeper optimally, giving the best move in any position. Moreover, you must do this on the largest board possible.
**Game details:** Minesweeper is a one player game, played on a rectangular board. At the beginning of the game, a specified number of mines are randomly distributed over the board, at most one to a cell. Each possible placement of the mines is equally likely. The mines' positions are hidden from the player.
On each of the player's turns, he or she chooses a square on the board to reveal. If the square contains a mine, the player loses the game. Otherwise, the number of mines in Moore neighborhood of the chosen square (orthogonally or diagonally adjacent) is revealed to the player.
The player repeats this until either a mine is revealed, or the number of unrevealed squares is equal to the number of mines. If the latter occurs, the player wins.
**Program specification:** Your program must take as input a board position, which should specify the locations and values of the revealed and unrevealed squares, as well as the number of mines on the board. It must return at least one move which has a maximal likelihood of winning if followed by optimal play. Returning more moves is allowed, as long as they all have the same, maximal, win rate.
In addition, the program must return the maximal number of possibilities that can be won under optimal play and the total number of possibilities for this revealed board state. From these values, the exact probability of winning under optimal play is known.
**Examples:**
Input (in any format you prefer):
```
4 mines
____
____
____
____
```
Output:
```
Best moves are [(0, 1), (0, 2), (1, 0), (1, 3), (2, 0), (2, 3), (3, 1), (3, 2)].
961 wins out of 1820 possibilities.
```
Input:
```
5 mines
_____
_1___
_3___
_____
```
Output:
```
Best moves are [(0, 2)].
285 wins out of 360 possibilities.
```
**Challenge specification:** Your challenge is to run your program on the initial position of a board of one of the following types:
* n x n board, n mines.
* n x n+1 board, n mines.
* n x n+1 board, n+1 mines.
Your program must find an optimal move on your machine at least as fast as the reference implementation solves the 4x5 board, 5 mines case on your machine. That case takes 6 minutes on my computer, for reference.
To run that instance of the reference implementation with timing, run `python3 Minesweeper-challenge.py <<< "(4,5), 5, '____________________'"`
The program that correctly identifies the optimal moves and exact number of possibilities that can be won with perfect play, on the initial position of the largest board of the above type, tiebreaker most mines, in the given time limit, wins the contest.
I will select a winner in two weeks, on July 24th.
Since writing a program like this is a big task, I will be awarding a bounty of 150 reputation, starting tomorrow and ending on the 18th.
Edit/bump: Well, that was a waste of 250 rep.
[Answer]
# Python, 4x5 board, 5 mines.
This is the reference implementation, I just thought I'd put it here to help give people ideas.
This implementation uses dynamic programming to prevent duplication of work, exploits mirror symmetries, and maintains a fist of all possible boards with a given revealed square status to check for guaranteed safe squares.
```
# Minesweeper solver
# Class just contains partially revealed boards that all look the same
# from the outside
# This is a branch, that uses strings.
# Boards have every cell revealed.
# Revealed is partially revealed. Boards must match revealed on every
# cell that is revealed.
# Meanings:
# '0'-'8': Safe square with that # of surrounding mines
# '*' : Mine
# '_' : Unrevealed
import copy
import itertools
import time
import pickle
import random
import math
import cProfile
import sys
class Position:
def __init__(self, dimensions, revealed, boards):
self.dim_r,self.dim_c=dimensions
self.rev=revealed
self.boards=boards
assert len(revealed)==self.dim_r*self.dim_c
def click(self,loc):
# Takes a location, returns all possible revealed positions, with boards
# split up accordingly
try:
assert self.rev[loc]=='_'
except AssertionError:
print(self,loc,self.rev)
assert self.rev[loc]=='_'
# Create all possible new boards, split up by revealed item.
board_dict={}
for board in self.boards:
clicked_cell=board[loc]
if clicked_cell in board_dict:
board_dict[clicked_cell].append(board)
else:
board_dict[clicked_cell]=[board]
new_positions=[]
for rev_cell in board_dict.keys():
# Make the new board without copying
new_rev=''.join([self.rev[:loc],rev_cell,self.rev[loc+1:]])
new_pos=Position((self.dim_r,self.dim_c),new_rev,board_dict[rev_cell])
new_positions.append(new_pos)
return new_positions
def someBestClick(self):
click_list=[]
# Set of boards is all we know when outputting, may be smaller than
# complete set
# If we've clicked on a bomb, no way to win, no best click.
if '*' in self.rev:
return 0,[]
unrevealed = [loc for loc in range(len(self.rev)) if self.rev[loc]=='_']
# If there is only 1 possible board, you're done. The click list is every
# unrevealed square on the board without a bomb under it.
if len(self.boards)==1:
return 1,[loc for loc in unrevealed if self.boards[0][loc]!='*']
# If there is an unrevaled locaiton on the board that is bomb free in
# every sub-board, use it.
for loc in unrevealed:
if all(board[loc]!='*' for board in self.boards):
return sum(pos.memoBestClick()[0] for pos in self.click(loc)),[loc]
# The broadest test - try everywhere.
click_list=[]
most_wins=0
for loc in unrevealed:
wins=sum(pos.memoBestClick()[0] for pos in self.click(loc) if pos.rev[loc]!='*')
if wins>=most_wins:
if wins>most_wins:
click_list=[]
most_wins=wins
click_list.append(loc)
return most_wins,click_list
def memoBestClick(self):
global memo
global memo_counter
memo_counter +=1
if not self.rev in memo:
# These lines check for mirror images of the board being in the memo table
vert_reversed_memo_str= \
''.join([self.rev[y*self.dim_c:(y+1)*self.dim_c]
for y in range(self.dim_r)][::-1])
if vert_reversed_memo_str in memo:
vert_reversed_output=memo[vert_reversed_memo_str]
return vert_reversed_output[0], \
[(self.dim_r-1-loc//self.dim_c)*self.dim_c+loc%self.dim_c
for loc in vert_reversed_output[1]]
horiz_reversed_memo_str= \
''.join(self.rev[y*self.dim_c:(y+1)*self.dim_c][::-1]
for y in range(self.dim_r))
if horiz_reversed_memo_str in memo:
horiz_reversed_output=memo[horiz_reversed_memo_str]
return horiz_reversed_output[0], \
[(loc//self.dim_c)*self.dim_c+
both_reversed_memo_str=self.rev[::-1]
if both_reversed_memo_str in memo:
both_reversed_output=memo[both_reversed_memo_str]
return both_reversed_output[0], \
[len(self.rev)-1-loc
for loc in both_reversed_output[1]]
global restart_counter
global restart_memo
if len(self.rev)-self.rev.count('_') <= restart_max:
restart_memo[self.rev]=self.someBestClick()
memo[self.rev]=restart_memo[self.rev]
return restart_memo[self.rev]
# Needed because of memory issues
if len(memo)>5*10**6:
memo=copy.deepcopy(restart_memo)
restart_counter+=1
memo[self.rev]=self.someBestClick()
return memo[self.rev]
def makeBlankPosition(dimensions,mines):
dim_r,dim_c=dimensions
# Makes all locations on the board
all_loc=itertools.product(range(dim_c),range(dim_r))
# Makes all possible distributions of mines
all_mine_layouts=itertools.combinations(all_loc,mines)
boards=[]
for mine_layout in all_mine_layouts:
boards.append(makeBoardFromMines(dimensions,mine_layout))
return Position(dimensions, '_'*dim_c*dim_r, boards)
def makeBoardFromMines(dimensions,mine_layout):
dim_r,dim_c=dimensions
def mineNum(loc):
if (loc%dim_c,loc//dim_c) in mine_layout:
return '*'
return str(sum(((loc%dim_c+dif[0],loc//dim_c+dif[1]) in mine_layout) for dif in
[(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]))
return ''.join(map(mineNum,(loc for loc in range(dim_r*dim_c))))
def makePosition(dimensions,mines,revealed):
blank_pos=makeBlankPosition(dimensions,mines)
boards_subset=[]
for board in blank_pos.boards:
if all(revealed[cell_num]==board[cell_num] or revealed[cell_num]=='_' for cell_num in range(len(board))):
boards_subset.append(board)
return Position(dimensions, revealed, boards_subset)
def winRate(dimensions,mines,revealed):
pos=makePosition(dimensions,mines,revealed)
global memo
memo={}
wins=pos.memoBestClick()
return wins[0],len(pos.boards),wins[1],memo
global memo_counter
memo_counter=0
global restart_counter
restart_counter=0
global restart_memo
restart_memo={}
global restart_max
restart_max=6
dimensions, mines, revealed = eval(input())
start_time=time.clock()
wins, total_boards, moves, memo = winRate(dimensions, mines, revealed)
move_points=[(move//dimensions[1],move%dimensions[1]) for move in moves]
print("""Best moves are %s.\n%i wins out of %i boards. Ratio of %f. %i
positions searched.\n%f seconds taken."""%(move_points, wins, total_boards,
wins/total_boards, len(memo),time.clock()-start_time))
```
] |
[Question]
[
Some time ago I came across a game called [Ubongo](http://en.wikipedia.org/wiki/Ubongo). The player got four shapes and has to put them together in a way, that the shapes form the shape of the board. One example is this:

Note that the shapes can be turned or rotated.
Your goal is to write a programm that takes the board and the 4 shapes as parameter (command line or user input, handle it your way) and prints the solution (a graphical solution or a **human-readable** solution).
**Example (same as above):**
Input (board size, board information (0 for nothing, 1 for board field), 4x shape size and shape information (same as board information)):
```
>myprogram
5 5
11000
11000
11101
11111
00111
2 4
10
10
11
10
1 2
1
1
2 3
01
11
01
2 3
01
11
11
```
Output:
```
12000
12000
11304
13344
00344
```
(0 stands for nothing, 1 for the first shape given in the input, 2 for the second shape etc.)
Note that the choice of input and output is completely free, it should just be easy to understand.
The winner will be crowned two weeks from when the question was posted. The winner will be the person with the least code length.
**EDIT :**
You can assume that there is a solution to the given board and pieces. If there is no solution, your program does not have to work (but it would be nice if it prints an error message). For those, who need more tests, I found solutions to several puzzles with several boards and pieces [here](http://www.kosmos.de/_files_media/mediathek/downloads/spieleloesungen/1160/ubongo_das_duell_1.pdf).
[Answer]
# Python 2.x - 679 543 443 417 406 383 372 361 bytes
I'm actually pretty sad about this one. I am sure I missed something obvious. I'll be looking at this again later. Starting to feel good about this one.
```
543 - Edit 1: Discarding efficiency in favor of code length.
443 - Edit 2: Made the algorithm a lot simpler, fixed it (it couldn't handle flips) and
removed ungolfed code because it wasn't relevant anymore.
417 - Edit 3: Rotate was only being used once anymore. Inlined it. Something else too.
406 - Edit 4: Made it accept only four shapes, as the spec says. Also reduced efficiency again.
383 - Edit 5: Ultimate abuse of exec. Shorter code and longer execution time!
372 - Edit 6: Every recursion now makes a copy of the current board, which is removed if
the pieces don't fit. No more master board and no more emptying placed pieces.
361 - Edit 7: Removed unnecessary stuff. Also added the byte counts to changelog.
```
---
```
(q,g),O,s=input()
O=[x*6for x in sum(O,[])]
A='z,k=s[i];'+('z,k=z[::-1],zip(*k[::-1]);r=r or c(i+1,z,k,O);'*4+'k=map(reversed,k);')*2
def c(i,(w,h),p,o,r=0):
for x in range(g*q):O=o[:];f=1;I=0;exec"P=x+I/w*q+I%w;exec('f=0','O[P]=i')[g*q>P>=0and O[P]>4]*p[I/w][I%w];I+=1;"*w*h;exec(i<4*f)*A;r=O*(i*f>3)or r
return r
i=r=0;exec A+'print`r[i:i+q]`[1::3];i+=q;'*g
```
It takes the input in an array format. Example:
```
In: [5,5],[[1,1,0,0,0],[1,1,0,0,0],[1,1,1,0,1],[1,1,1,1,1],[0,0,1,1,1]],[[[2,4],[[1,0],[1,0],[1,1],[1,0]]],[[1,2],[[1],[1]]],[[2,3],[[0,1],[1,1],[0,1]]],[[2,3],[[0,1],[1,1],[1,1]]]]
Out: 12000
12000
11304
13344
00344
In: [6,5],[[0,1,1,1,1,0],[1,1,1,1,1,0],[1,1,1,1,1,0],[0,1,1,1,1,0],[0,0,1,1,1,1]],[[[2,4],[[1,0],[1,0],[1,1],[1,1]]],[[3,3],[[1,1,0],[0,1,1],[0,1,1]]],[[3,3],[[0,0,1],[1,1,1],[1,0,0]]],[[2,4],[[0,1],[1,1],[0,1],[0,1]]]]
Out: 033110
223110
223310
022410
004444 (thanks, edc65)
```
Quick explanation, if you can't read it. The function checks every possible position for a piece. Whenever the piece fits, it recursively checks that all other pieces fit too. When all pieces fit, the board is filled (pieces are placed on the board when checking) and it can be outputted straight away.
[Answer]
### GolfScript, 210 characters
```
n%{(~\;/(\[]:f*}5*;].,,]zip{~{.!+`\1`/*n*~]}+%}%(:b{,:^1,*}%]({^,{[^1,*:e.@<\]`{\*^<}+1$%:a;b,:h,{[[e]h*.@<\]a*h<}/}%{.zip{.-1%.zip}3*}%.&`{{[[f*1$f*]zip{~+}%b f*]zip{~*}%^/}%~}+@%{1$f*0-.@f*@0={=}+,=},\;}/0=n*
```
This is a first attempt using GolfScript. Input must be given on STDIN in the same format as the example in the question. The output format results from an implementation error (using ascii values instead of numerics) but I left it in this form because it is short and looks nice.
```
☺☻
☺☻
☺☺♥ ♦
☺♥♥♦♦
♥♦♦
```
[Answer]
# Javascript (E6) 316 ~~350 392 487 537 590~~
Board size limited to 6x6 to save runtime. With the same character count the limit could be 9x9. Any number of pieces
```
F=(d,b,h)=>{R=s=>[...s].reverse(),Q=(n,i,k)=>{h[n]&&[t=h[n][1],t[0].map((c,i)=>t.map(r=>r[i]))].map(e=>[e,R(e),e.map(R),R(e).map(R)].map(s=>{for(i=36;i--;)k=b.map(x=>[...x]),s.some((u,q)=>!(w=b[~~(i/6)+q])||u.some((v,p)=>(c=i%6+p,v&&!(v=w[c]!=1)&&!(w[c]=n+2)||v)))||Q(n+1),b=k}))||console.log(b.join('\n'))},Q(0)}
```
---
**History**
*316* - Slooower! The board is copied again for each recursive call. (Ab)using slower functions chosen for shorter names. The main loop on board rows and colums coalesced into one for. Also put a limit for board size up to 6x6 (not for short code, but for acceptable runtime)
*350* - Golfed using more array traversing function and less loops
*392* - Algorithm not changed: try to place a piece, if ok try next, recursive, but
use arrays only and not strings and use a single global board and not copy it during recursion (so it must be able to put a piece AND to remove it)
...
**Ungolfed** a bit
```
F = (d,b,h)=>{
R = s => [...s].reverse(), // ... instead of slice that is faster
Q = (n,i,k) => // Recursive function, fake param i to avoid vars
{
h[n] && // If there is still a piece to place, try to place it
[t=h[n][1], t[0].map((c,i) => t.map(r => r[i]))]
.map(e => // for e in :piece, transposed piece
[e, R(e), e.map(R), R(e).map(R)]
.map(s =>
{ // for s in : base piece, reversed, mirrored, diagonal
for(i = 36; i--;) // 6x6: could be higher but slows down
k = b.map(x=>[...x]), // save copy of board (again ... instead of slice)
s.some( (u,q) => // traverse with 'some' to exit early if invalid position
!(w=b[~~(i/6)+q])
|| u.some((v,p) => (c=i%6+p, v && !(v=w[c]!=1) && !(w[c]=n+2)||v))
) || Q(n+1), // if piece place, recurse
b=k // recover the board from the copy
}
)) // if no more pieces, output result
|| console.log(b.join('\n' /** ,Q=_=>0 **/)) // remove comment to stop at first solution found
},
Q(0) // First call
}
```
**Usage**
Test in javascript console (Firefox)
Input parameters as array.
Time to finish is 50 sec on my PC, so Firefox will complain...
```
F(
[5,5],
[[1,1,0,0,0],[1,1,0,0,0],[1,1,1,0,1],[1,1,1,1,1],[0,0,1,1,1]],
[
[[2,4],[[1,0],[1,0],[1,1],[1,0]]],
[[1,2],[[1],[1]]],
[[2,3],[[0,1],[1,1],[0,1]]],
[[2,3],[[0,1],[1,1],[1,1]]]
])
```
Another test case:
```
F(
[6,5],
[[0,1,1,1,1,0],[1,1,1,1,1,0],[1,1,1,1,1,0],[0,1,1,1,1,0],[0,0,1,1,1,1]],
[
[[2,4],[[1,0],[1,0],[1,1],[1,1]]],
[[3,3],[[1,1,0],[0,1,1],[0,1,1]]],
[[3,3],[[0,0,1],[1,1,1],[1,0,0]]],
[[2,4],[[0,1],[1,1],[0,1],[0,1]]]
]
)
```
Output / 2+2 solutions found, firefox console skip repeated console output
```
0,2,2,2,2,0
3,3,4,2,2,0
3,3,4,4,4,0
0,3,3,5,4,0
0,0,5,5,5,5
```
---
```
0,4,4,2,2,0
3,3,4,2,2,0
3,3,4,4,2,0
0,3,3,5,2,0
0,0,5,5,5,5
```
] |
[Question]
[
Implement the [Pigeonhole sort](http://en.wikipedia.org/wiki/Pigeonhole_sort). This is a variant of the Bucket sort, and its logic is very simple: index your items (by a given function) and then return all non-empty indexes' items.
Your program/function should get an array of items in the most comfortable way for your language of choice, (i.e. a parameter, stdin, etc.), and in any format you like (for example: JSON). It should return/output a sorted array.
Do not modify the given array.
The second parameter that will be given to your program/function will be the "sort-by function". For exmaple, in JavaScript it will be something like `function(item){return item.id;}`.
For simplicity, you can assume this function returns a **unique positive Integer** for each item in the given array.
Shortest code wins. Only ASCII is allowed.
[Answer]
# Ruby, 43
```
def s a,*b,&f
a.map{|x|b[f[x]]=x}
b-[p]
end
```
Calling looks like
```
p s(["a","ccc","bb","eeeee"],&:length)
-> ["a", "bb", "ccc", "eeeee"]
```
Tricks: `*b` in the arg list creates an empty output array (so long as you don't, y'know, pass any args). `&f` creates a lambda reference to the passed-in block that can be called via `f[]` (normal Ruby convention is to use `yield`). `a.map` iterates over the input array without modifying it and is one character shorter than `a.each`. `b-[p]` strips out the nil values, equivalent to `b.compact`.
[Answer]
## J (39)
```
f=:1 :'y{~z i.g#~+/z=/g=.i.>:>./z=.u y'
```
Explanation:
* `z=.u y`: apply the function `u` to the argument `y`. The function should distribute over the array.
* `g=.i.>:>./z`: Make the 'holes' (in the range `[0..max(u(y))]`).
* `+/z=/g`: for each hole, get how many elements it contains.
* `g#~`: replicate each hole coordinate by how many elements it contains (so if holes 3 and 5 had 1 element, and hole 8 had 3, we get `3 5 8 8 8`).
* `z i.`: look up the position of each value in `z`. For example, if `u y` is 5 for the 3rd element of `y`, this gives `3` for `5`.
* `y{~z`: look up the matching elements in the starting array
Examples:
```
f=:1 :'y{~z i.g#~+/z=/g=.i.>:>./z=.u y'
NB. functions and data
ascii=:a.&i.
text=:'here is some text to sort'
length=:#&>
arrays=:1 2;3;4 5 6 7;8 9 10 NB. these will be sorted by length
NB. show effect of functions
ascii text
104 101 114 101 32 105 115 32 115 111 109 101 32 116 101 120 116 32 116 111 32 115 111 114 116
length arrays
2 1 4 3
NB. sort
ascii f text
eeeehimooorrsssttttx
length f arrays
┌─┬───┬──────┬───────┐
│3│1 2│8 9 10│4 5 6 7│
└─┴───┴──────┴───────┘
```
[Answer]
# Python 2 - 98 92 bytes
```
def p(l,f):
x=[None]*max(map(f,l))
for e in l:x[f(e)-1]=e
return[i for i in x if i!=None]
```
`l` is the list to sort, `f` is the sort-by function.
Ungolfed (a bit):
```
def pigeonhole(list, sort_function):
max_value = max(map(sort_function, list)) # Find how big the final list has to be
sorted_list = [None] * max_value # Create a list of that many Nones
for element in list:
sorted_list[sort_function(element) - 1] = element # Subtract one because sort_function returns positive ints and lists are 0-indexed
return [element for element in sorted_list if element is not None] # Filter out Nones and return
def return_same(x):
return x # This sort function will make the pigeonhole sort ints normally. There's no reason it has to be this function, it just has to return positive ints.
print pigeonhole([8, 4, 5, 9, 11, 3], return_same) # [3, 4, 5, 8, 9, 11]
```
[Answer]
## Groovy - 135 chars
Using Groovy 2.2.1, inspired by [undergroundmonorail's answer](https://codegolf.stackexchange.com/a/26991/21004), though here input data and sort function are specified in files:
```
e={new GroovyShell().evaluate(new File(args[it]))}
l=e(0)
f=e(1)
s=new Object[l.max{f(it)}]
l.each{s[f(it)-1]=it}
println s.findAll{it}
```
As an assist to the reader, `l` = list of items (from file), `f` = sort function (from file), `s` = sorted list, and `e` = simple convenience function to evaluate data as code.
An example command-line looks like:
```
groovy P.groovy data.txt f.txt
```
where data.txt is:
```
[8,4,5,9,11,3]
```
and f.txt is:
```
{ x -> x }
```
[Answer]
# JavaScript - 92
I believe this is what is asked for.
```
function s(a,b){c=[];a.map(function(e){c[b(e)]=e});return c.filter(function(f){return !!f})}
```
Test:
```
console.log(s([{id:3},{id:5},{id:7},{id:1}],function(x){return x.id}));
```
returns:
```
[1: Object, 3: Object, 5: Object, 7: Object]
1: Object
id: 1
3: Object
id: 3
5: Object
id: 5
7: Object
id: 7
```
EDIT: fixed as per @Jacob's comments.
[Answer]
# C++14, 154 bytes
As unnamed lambda:
```
#include<map>
#include<vector>
[](auto&v,auto f){std::map<int,int>m;for(int c:v)m[f(c)]=c;std::vector<int>r;for(auto p:m)r.push_back(p.second);return r;}
```
Assumes `v` to be a container like `vector<int>`, could also be `int[]`
Ungolfed:
```
auto f =
[](auto&v, auto f){
std::map<int,int> m;
for(int c:v)
m[f(c)]=c;
std::vector<int> r;
for(auto p:m)
r.push_back(p.second);
return r;
};
```
Usage:
```
int main() {
std::vector<int> v={5,2,1,3,4};
auto w = f(v, [](int x){return x;});
for (auto c:w) std::cout << c << ", ";
std::cout << "\n";
}
```
] |
[Question]
[
# The task
The task is to write a program that turns a list of IPv6 addresses into a shortest possible list of CIDR masks, such that everything but those IPs is matched.
# CIDR masks
A CIDR mask matches IPs by a prefix. `::/19` matches all IPs whose first 19 bits are zero, i.e. `0:0000-1fff:*:*:*:*:*:*`. Similarly, `55aa::/16` matches all IPs that start with `0101010110101010` bit sequence, i.e. `55aa:*:*:*:*:*:*:*`.
A `/128` always matches only one IP. A `/0` matches all IPs.
# Input
Input is a list of IP addresses in full form: eight 4-digit hexadecimal groups separated by `:` in network order (most significant first). For example, `0000:0000:0000:0000:0000:0000:0000:0000`.
You're free to choose any separation character for the input list, might it be newline, space, comma, `\0`, etc. You can also rely on `a-f` being in a particular case.
# Output
Output is the shortest list of CIDR masks that cover all IP addresses except those listed in input.
Again you're free to choose any separation character.
The CIDR should be formatted as any representation of an IP followed by `/` and amount of bits in the prefix (in decimal). For example, `0243:F6A8:885A:308D:3131:98A2:0000:0000/112`.
You are not required to shorten the IP at all, as in above example. However `243:f6a8:885a:308d:3131:98a2::/112` is not invalid.
The order of masks doesn't matter. If there are multiple representations using equal amount of masks - either will suffice.
# Examples
I'm not posting complete outputs, since coming up with an algorithm is a part of the task :)
Instead I'm specifying how much masks does it take, according to my own calculations. If you find a mistake, or a shorter masklist, please report.
```
>>> 0000:0000:0000:0000:0000:0000:0000:0000
[128 masks]
>>> 0000:0000:0000:0000:0000:0000:0000:0000 0000:0000:0000:0000:0000:0000:0000:0001
[127 masks]
>>> ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 0000:0000:0000:0000:0000:0000:0000:0000
[254 masks]
>>> 0000:0000:0000:0000:0000:0000:0000:ffff 0000:0000:0000:0000:0000:0000:0000:0000
[142 masks]
>>> 0123:4567:89ab:cdef:fedc:ba98:7654:3210 0246:8ace:1357:9bdf:0246:8ace:1357:9bdf
[248 masks]
>>> 0000:0000:0000:0000:0000:0000:0000:0000 0000:0000:0001:0000:0000:0000:0000:0000 0000:0000:0002:0000:0000:0000:0000:0000 0000:0000:0003:0000:0000:0000:0000:0000 0000:0000:0004:0000:0000:0000:0000:0000 < snip > 0000:0000:00ff:0000:0000:0000:0000:0000
(256 IPs)
[20520 masks]
>>> 0000:0000:0000:0000:0000:0000:0000:0000 0000:0000:0000:0000:0000:0000:0000:0001 0000:0000:0000:0000:0000:0000:0000:0002 0000:0000:0000:0000:0000:0000:0000:0003 0000:0000:0000:0000:0000:0000:0000:0004 < snip > 0000:0000:0000:0000:0000:0000:0000:0fff
(4096 IPs)
[116 masks]
```
# Scoring
Amount of characters in the code, UTF-8 characters are counted as one, if you must.
### Bonus points
* **-16** Cover the case of empty input list.
* **-32** Output shortened IPs: strip leading zeros, replace sequential zero groups with `::`, etc. See [this Wikipedia article](http://en.wikipedia.org/wiki/IPv6_address#Presentation).
+ **-32** Do not use the v4-in-v6 form (`dead::beef:1.2.3.4`).
* **-64** Permit shortened IPs in input.
[Answer]
### GolfScript, 120 (136 characters - 16 bonus)
```
n%{':'-{48^71%}%16base}%-1+2.7??:W+${\)1$1$-{}{129,-1%{2\?.2$)<3$@%!&}?:~2$W+16base(;{.48+\9>39*+}%4/':'*'/'+128@-+puts\2~?+\2~?-}/;;}*;
```
Assumes the addresses as separate lines on STDIN. A considerable amount of the code is actually used to input/output in the correct format. The algorithm itself is quite simple and described [here](https://codegolf.stackexchange.com/a/15509/1490).
[Answer]
# Python 3: 128 points
(240 characters - (16 + 32 + 64) bonus points)
Yay, Python!
(I used the standard library instead of actually writing my own algorithm. Is that cheating?)
```
from ipaddress import *
import sys
def e(x,a):
b=[]
for i in a:
try: b+=i.address_exclude(ip_network(x))
except ValueError: b+=[i]
return b
a=[ip_network('::/0')]
for h in sys.stdin:
for i in h.split(): a=e(i,a)
for i in a: print(i)
```
It accepts a list of addresses on stdin, separated by any (ASCII) whitespace you like (no commas, though).
If stdin is empty (or has only whitespace), it will print `::/0` (-16 points). It also prints (-32) and handles (-64) shortened IPs.
You can save 12 characters by replacing the stdin loop with `for i in sys.stdin: a=e(i.strip(),a)`. The `strip()` is necessary to get rid of a trailing newline anyway, though, so I figured I'd use `split()` and another `for` loop and allow any whitespace.
You can probably save a few more characters by moving the code out of that pesky function. I didn't because I figured I was already confusing myself enough.
[You can also make it work for IPv4 instead by changing only one line.](https://codegolf.stackexchange.com/a/22577/13547)
## Ungolfed version:
```
#!/usr/bin/env python3
import ipaddress
import sys
def exclude(address, networks):
new_networks = []
for network in networks:
try:
new_networks.extend(network.address_exclude(ipaddress.ip_network(address)))
except ValueError:
new_networks.append(network)
except TypeError:
pass
return new_networks
networks = [ipaddress.IPv6Network('::/0'), ipaddress.IPv4Network('0.0.0.0/0')]
for line in sys.stdin:
for address in line.split():
networks = exclude(line, networks)
for network in networks:
print(network)
```
This one has the added benefit of working for IPv4 *and* IPv6, no tweaking necessary. :)
] |
[Question]
[
Objective:
>
> The task is to create two programs using the same or different
> programming languages. The sourcecodes will be combined in two
> different ways and the resulting sourcecodes can be in any programming
> languages. The four programs (original two + the two combinations)
> should output different things.
>
>
>
Rules:
1. Your programs (all four) should not take any input (from user, filename, network or anything).
2. The first program should output exactly `Hello`, nothing else.
3. The second program should output exactly `world`, nothing else.
4. The first combinated program should output `Hello human!`, nothing else.
5. The second combinated program should output `Hello computer!`, nothing else.
Here is how the two combinated programs may be created:
**First combined program**:
* Choose **two** numbers (equal or different) between 1 and 6 (that is: 2, 3, 4 or 5), the two numbers are called: `n1` and `n2`.
* Copy `n1` number of characters from the first program and paste into the combined sourcecode
* Copy `n1` number of characters from the second program and paste into the combined sourcecode
* Copy `n2` number of characters from the first program and paste into the combined sourcecode
* Copy `n2` number of characters from the second program and paste into the combined sourcecode
* Next, start over copy `n1` number of characters again and so on. Copy from start to end from the sourcecodes, paste from start to end into the combined sourcecode.
**Second combined program**:
* The sourcecode is the reverse of the first combined program sourcecode above. You may replace up to 3 characters at any place afterwards (optional). You can replace the up to 3 characters with any other characters. Replacing means 1 char for 1 char at up to 3 different positions on the sourcecode. The final sourcecode size in characters should therefor be exactly the same size as the first combined program size.
**Example** creating the combinated programs using numbers 3 and 4:
```
First program: {'Hello'}:p
Second program: /* */ console.log ("World");
First combinated program: {'H/* ello '}: */ console.log ("World");
Second combinated program: ;)"dlroW"( gol.elosnoc /* :}' olle */H'}
```
Be sure to declare all four programming languages that you use (even if they are all the same) and what numbers you have used when creating the first combinated sourcecode.
This is code-golf, shortest code in bytes for the two sourcecodes wins! Good luck, have fun!
[Answer]
### Befunge-93 x4; n1=5, n2=5; 100 75 chars
I put the 4 programs into 1 file for debugging: (it outputs a random one of the four programs)
```
vv |2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|23
>??#@"oll""eH" >:#0#,_ @ #
|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|23
>? #@"dlr""ow" >:#0#,_ @0"!namuh olleH">:#,_@#:>"Hello computer!"
|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|23
> #@"oll""dlr""eH" "ow" >:# 0#,_ >:#@ 0#,_ #@0"!namuh olleH">:#,_@#:>"Hello computer!"
|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|2345|23
>#@"!retupmoc olleH">:#,_@#:>"Hello human!"0@# _,#0 @#:> _,#0 #:> "wo" "He""rld""llo"
```
The separate programs are: (one per line)
```
"oll""eH" >:#0#,_ @ #
"dlr""ow" >:#0#,_ @0"!namuh olleH">:#,_@#:>"Hello computer!"
"oll""dlr""eH" "ow" >:# 0#,_ >:#@ 0#,_ #@0"!namuh olleH">:#,_@#:>"Hello computer!"
"!retupmoc olleH">:#,_@#:>"Hello human!"0@# _,#0 @#:> _,#0 #:> "wo" "He""rld""llo"
```
Edit: This time, I took advantage of the replacement rule and replaced two characters in the second combination.
[Answer]
## Befunge-98 × 4, 69 chars
Following @user12551's lead, I went with 4× Befunge (although -98 rather than -93). Program code is reversed on byte-level, line ending is `LF`, program #1 has no terminating newline.
**Program 1**:
```
"!namolleH"4k,@
```
**Program 2**:
```
"vdlrow"4k,@
>"uh olleH"bk,@,ke"Hello computer!"
```
**Combined 1** (*n₁ = 5*, *n₂ = 2*):
```
"!nam"volleHdl"4k,@row"4k,@
>"uh olleH"bk,@,ke"Hello computer!"
```
**Combined 2** (has a bunch of trailing spaces):
```
"!retupmoc olleH"ek,@,kb"Hello hu">
@,k4"wor@,k4"ldHellov"man!"
```
[Answer]
## Windows Command script x4; n1=2; n2=2 - 92 Bytes
1st script (marked eol and eof):
```
%: !rupc leoh %\r\n
% eo llhun!% \r\n
%echo Hello\eof
```
2nd script (marked eol and eof):
```
%&&etmoolH ce %\r\n
%chHeo ma% % \r\n
echo world% \eof
```
Results in:
```
% %: &&!retupmoc olleH ohce % %
% % echo Hello human!% % %
%ecechoho w Horelldlo%
```
And reversed:
```
%oldlleroH w ohohcece%
% % %!namuh olleH ohce % %
% % echo Hello computer!&& :% %
```
] |
[Question]
[
You are given a graph represented through an adjacency list. For example, the input
```
1-2 2-3 3-4 4-1
```
would correspond to the graph with nodes *1*, *2*, *3* and *4*, where *1* is connected to *2*, *2* is connected to *3*, *3* is connected to *4*, and *4* is connected to *1* (forming a square).
The task is to determine the number of of connected components of the graph represented by an inputted adjacency list. A "connected component" is a set of nodes from which there is no path to any other node that is not in the set.
Example:
>
> Intput: `1-2 2-3 4-5`
>
> Output: `2`
>
>
>
---
Language of your choice - shortest code possible.
[Answer]
### Ruby, 77 characters
```
gets;0while$_.sub!(/\b(\d+)\b(.*) (\1-\d+|\d+-\1)\b/,'\3\2');p$_.count(" ")+1
```
A first plain attempt in Ruby. It collects the sub-graphs using a regular expression until no more connections can be made.
Examples:
```
> 1-2 2-3 3-4 4-1
1
> 1-2 2-3 4-5
2
> 1-2 3-4 8-9 1-6 5-7 7-4 10-9
3
```
[Answer]
# Mathematica 126
With `x` holding the input string,
```
t = ToExpression;
Length@ConnectedComponents@Graph[Characters /@ ImportString[x, "Table"][[1]] /.
{a_, "-", b_} :> UndirectedEdge[t@a, t@b]]
```
---
If `x` is input instead as a list of undirected edges, in standard Mathematica format, the solution can be reduced to 34 chars:
```
Length@ConnectedComponents@Graph@i
```
Example:

[Answer]
## Sage, 77
```
len(Graph([t.split('-')for t in raw_input().split()]).connected_components())
```
[Answer]
# Golfscript, ~~67~~ 62 characters
This can probably be golfed down a little more but...
~~`" "/{"-"/{~}%}%0\{.}{(:^;{.{^&},.{+}*}{.@\-\{+}*:^;}while\)\}while;`~~
```
'-'%{~}%2/0\{.}{(:^;{.{^&},.{+}*}{.@\-\{+}*:^;}while\)\}while;
```
Important note: this ONLY works on the ruby interpreter for golfscript (from golfscript.com), NOT on the online golfscript app, because the online app incorrectly handles nested while loops. Here's the commented code:
~~`" "/{"-"/{~}%}% # parse into array of number pairs`~~
```
'-'%{~}%2/ # parse into array of number pairs
0\ # push the counter under the current set
{.} # copy top for the condition pop
{
(:^; # grab leftmost pair
{
.{^&}, # grab any matching the left pair, make a copy for the
.{+}* # condition, and merge the copy's elements together
}{
.@\-\ # remove the matches from remaining set
{+}*:^; # merge matches together & assign to '^'
}while
\)\ # update the counter underneath
}while;
```
] |
[Question]
[
A polynomial over a variable *x* is a function of the form
>
> p(x) = anxn + an-1xn-1 + ... + a1x + a0
>
>
>
where *a0 ... an* are the *coefficients*. In the simplest
case, the coefficients are integers, e.g.
>
> p1(x) = 3x2 + 4x + 1
>
>
>
By allowing the coefficients to be polynomials over another variable, we can define
polynomials over multiple variables. For example, here is a polynomial over *x* whose coefficients are
polynomials over *y* with integer coefficients.
>
> p2(x,y) = (2y + 1)x2 + (3y2 - 5y + 1)x + (-4y + 7)
>
>
>
However, we often prefer to write these fully expanded as
>
> p2(x,y) = 2x2y + x2 + 3xy2 - 5xy + x - 4y + 7
>
>
>
Your task is to write a program that will pretty-print a given polynomial in this format.
### Input
Your program will receive a single line on standard input\* describing a polynomial over multiple variables
in the following format.
```
<name> <variables> <coefficients>
```
* `<name>` is one or more arbitrary non-whitespace characters.
* `<variables>` is one or more characters between `a` and `z` inclusive, each representing a variable. There are no duplicates, but note that the order is significant, as it affects how the terms should be ordered in the output.
* `<coefficients>` is one or more coefficients, separated by spaces, in order of increasing degree.
Each coefficient is either an integer in the usual base 10 notation, or another list of coefficients between
square brackets. The different variables correspond to the nesting level of the coefficients, with the
"outermost" list corresponding to the first variable and so on. The number of nesting levels will never
exceed the number of variables.
For example, the polynomials *p1* and *p2* above can be represented as follows.
```
p1 x 1 4 3
p2 xy [7 -4] [1 -5 3] [1 2]
```
Since constant polynomials can be interpreted as polynomials over any set of variables, some polynomials
may be written in multiple ways. For example, the coefficients of *p3(x,y,z) = 4* can be written as `4`, `[4]`
or `[[4]]`.
### Output
Your program should pretty-print the input polynomial on standard output\* in the following format.
```
<name>(<variables>) = <terms>
```
* `<name>` is the name of the polynomial as received.
* `<variables>` is the list of variables in the order received, interspersed with commas.
* `<terms>` are the terms of the fully expanded polynomial, formatted according to the rules below.
* Each term is an integer coefficient followed by powers of each variable in the order defined in the input,
all separated by a single space. The general format is `<variable>^<exponent>`.
* The terms are sorted by the exponents of the variables in decreasing lexicographical order. For example, `3 x^2 y^4 z^3` should come before `9 x^2 y z^13` because `2 4 3 > 2 1 13` lexicographically.
* Omit terms where the integer coefficient is zero, unless the whole polynomial is zero.
* Omit the integer coefficient if its absolute value is one, i.e. write `x` instead of `1 x`, unless this is a constant term.
* When the exponent of a variable in a term is zero, omit the variable from that term.
* Similarly, when the exponent of a variable is one, omit the exponent.
* The terms should be separated by `+` or `-` signs, with a space on each side, according to the sign of
the integer coefficient. Similarly, include the sign in front of the first term if it's negative.
### Examples
```
Input Output
================================ =======================================================
p1 x 1 4 3 p1(x) = 3 x^2 + 4 x + 1
p2 xy [7 -4] [1 -5 3] [1 2] p2(x,y) = 2 x^2 y + x^2 + 3 x y^2 - 5 x y + x - 4 y + 7
p3 xyz [4] p3(x,y,z) = 4
foo bar [0 2 [0 1]] [[3] [5 -1]] foo(b,a,r) = - b a r + 5 b a + 3 b + a^2 r + 2 a
quux y 0 0 0 0 0 1337 quux(y) = 1337 y^5
cheese xyz [[0 1]] cheese(x,y,z) = z
zero x 0 zero(x) = 0
```
### Winning criteria
This is code golf. The shortest program wins. Standard code golf rules apply.
### Bonus challenge
Write another program which does the reverse operation, i.e. takes the pretty-printed output of your original program and gives you back one of the possible corresponding inputs. This is purely for bragging rights and has no effect on
your score.
\* If your chosen programming language doesn't support standard input/output, you may specify how I/O is handled.
[Answer]
Mathematica:
```
Expand[Input[]] // TraditionalForm
```
will produce the expanded form.
Example input:
```
(2y + 1)x^2 + (3y^2 - 5y + 1)x + (-4y + 7)
```
Into the input prompt, click OK. Observe pretty output.
[Answer]
## Python, 323 chars
```
I=raw_input().split()
print'%s(%s) ='%(I[0],','.join(I[1])),
def P(L,p,f):
if type(L)==list:
for i in range(len(L))[::-1]:P(L[i],p+[i],f);f=0
elif L or f:A=abs(L);print'+-\0-'[2*f+(L<0)]+[(' %d '%A)[f:],' '][A==1and sum(p)>0]+' '.join([v,v+'^%d'%e][e>1]for v,e in zip(I[1],p)if e),
P(eval('['+','.join(I[2:])+']'),[],1)
```
[Answer]
## Python, 252 460 chars
Significantly longer than Keith Randall's, but matches the specifications better.
I copied `type(o)==list` from Keith. There are other similarities, but they were reached independently.
Sensitive to whitespace in the input. Particularly, space after `[` or before `]` breaks it.
```
e=lambda o,v,p:type(o)==list and[x for y in [e(c,v[1:],p+[(v[0],i)])for i,c in enumerate(o)]for x in y]or[(o,p)]
def f(x,y):z=" ".join(("%s^%d"%(a,b),a)[b<2]for a,b in y if b);return "+-"[x<0]+(" %d "%abs(x)," ")[z>"" and abs(x)==1]+z
l=raw_input().split()
t=" ".join(f(*x)for x in sorted(e(eval("["+",".join(l[2:])+"]"),l[1],[]),key=lambda x:[-dict(x[1]).get(a,0)for a in l[1]])if x[0])or'0'
print"%s(%s) = %s"%(l[0],",".join(l[1]),t[2*(t[0]=='+'):])
```
Logic:
Build a list of numbers/lists by replacing whitespace with commas and using `eval` (so `1 [2 3]` becomes `eval("[1,[2,3]]"`).
`e` converts the nested lists to a single list, with elements list `(3,[('x',2),('y',1)])` (for `3 x^2 y`).
I sort the list, with a key function that converts `('x',2),('y',1)` to `2,1`, by lexicographical order.
`f` prints each element in the list, preceded with `+`/`-`, and considering ones and zeros.
Just before printing, a preceding `+` is removed.
] |
[Question]
[
**This question already has answers here**:
[Base Conversion With Strings](/questions/69155/base-conversion-with-strings)
(9 answers)
Closed 8 years ago.
## Create a function 'baseXtoY' which:
converts an integer or string `n`, which is a base `x` number (hexadecimal, binary, etc)
into a base `y` number, reliably, including numbers like `10e50` or higher, using the least bytes possible, and using the following constraints:
* Provide built-in support for bases up to 64 using the following
sequence: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ=/
* Provide support for bases higher than 64 by allowing a different sequence to be used in the input
* Provide support for multi-byte sequences eg ('aa','bb','cc'...) in cases rally high value bases are needed (could also support unicode instead)
* You cannot have a base less than 2. Show an error
* You cannot use any built-in functions that convert base to base for you
* You need not worry about floating point
parameters should be:
* `n` - any number, as a string
* `x` - the base of `n`, integer
* `y` - the base of the return value
* `s1` - the sequence the given number's base uses
* `s2` - the sequence the desired base uses
* `b` - the bytesize of the digits in `s1`
* return value should be a string
example inputs:
using '88888'
base 10 to 2: `baseXtoY('88888',10,2) >>> '10101101100111000'`
base 2 to 5: `baseXtoY('10101101100111000',2,5) >>> '10321023'`
base 5 to 32: `baseXtoY('10321023',5,32) >>> '2mpo'`
base 32 to 10, using a new sequence, s=the above 64bit sequence, a=the alphabet: `baseXtoY('2mpo',32,10,s,a) >>> 'hhhhh'`
base 5 to 10, input base uses more than 1 byte per digit: `baseXtoY('bbaaddccbbaaccdd',5,10,('aa','bb','cc','dd','ee'),'0123456789',2))` > '88888'`
you do not have to inlude the character length of the testing or input code, just the
function(s).
edit: I've given up trying to shorten my Python code lower than the answers, so I'll just show what I have. 585 characters python 2.7
```
r=range
def b1(n,x,s):
if n==0:return s[0]
if x<=1:raise
l=[];p=n;i=0
while 1:
y=x**i;l.append(y)
if y>p:break
else:i+=1
l.reverse();f=[]
for p in l:h=int(n//p);f.append(h);n-=h*p
while f[0]==0:f.pop(0)
q=''
for p in r(len(f)):q+=s[f[p]]
return q
def b2(n,x,s,b):
n=list(str(n));l=[]
while n:
a=''
for p in r(b):a+=n.pop(0)
l.append(a)
m=0;q=0
while l:c=s.index(l.pop());q+=c*(x**m);m+=1
return q
s=''.join(map(chr,r(48,58)+r(97,123)+r(65,91)))+'=/'
def baseXtoY(n,x=10,y=2,s1=s,s2=s,b=1):return n if x==y else b2(n,x,s1,b)if y==10 else b1(b2(n,x,s1,b),y,s2)
```
test cases:
32 10 5 >>> 112
112 5 2 >>> 100000
100000 2 10 >>> 32
88888 10 5 0123456789 ('aa', 'bb', 'cc', 'dd', 'ee') 1 >>> bbaaddccbbaaccdd
bbaaddccbbaaccdd 5 10 ('aa', 'bb', 'cc', 'dd', 'ee') 0123456789 2 >>> 88888
[Answer]
### GolfScript, 139 130 128 characters
```
~]{.,5<{[10,""*26,{[97+]}%""*.{32-}%"=/"+++]+}*}2*.,6<{1+}*~:B;.""?!{1/}*:T;.""?!{B/}*:S;:Y;:X;B/0\{S?\X*+}%;""\{.Y%T=@+\Y/.}do;
```
Most of the characters come from reading and converting parameters and adding the optional ones. The actual conversion is only few chars.
The example inputs are processed as expected:
```
'88888' 10 2 # 10101101100111000
'10101101100111000' 2 5 # 10321023
'10321023' 5 32 # 2mpo
'2mpo' 32 10 # 88888
'88888' 10 5 '0123456789' ['aa' 'bb' 'cc' 'dd' 'ee'] 1
# bbaaddccbbaaccdd
'bbaaddccbbaaccdd' 5 10 ['aa' 'bb' 'cc' 'dd' 'ee'] '0123456789' 2
# 88888
```
*Edit 1:* some minor improvements, esp. coding the digits sequence.
*Edit 2:* this was an easy one: `0=` can be replaced by `!` two times in the conversion of the base parameters.
[Answer]
### scala: 399 365 chars:
```
type S=String
type I=Int
def t(l:List[I],b:I):I=l match{
case x::y=>(x%b)+b*t(y,b)
case Nil=>0}
def f(d:I,b:I):List[I]=if(d==0)List()else f(d/b,b):::List(d%b)
val c=(('0'to'9')++('a'to'z')++('A'to'Z')++Seq('=','/')).map(""+_)
def baseXtoY(a:S,g:I,r:I,i:Seq[S]=c,o:Seq[S]=c,w:I=1):S={
f(t(a.sliding(w,w).toList.map(i.indexOf(_)).reverse,g),r).map(o(_)).mkString("")}
```
testing code:
```
baseXtoY ("88888", 10, 2) //"10101101100111000"
baseXtoY ("10101101100111000", 2, 5) // "10321023"
baseXtoY ("10321023", 5, 32) // "2mpo"
baseXtoY ("2mpo", 32, 10) // "88888"
baseXtoY ("88888", 10, 5,"0123456789".map ("" + _).toSeq, "aabbccddee".sliding (2, 2).toSeq, 1) // "bbaaddccbbaaccdd"
baseXtoY ("bbaaddccbbaaccdd", 5, 10, "aabbccddee".sliding (2,2).toSeq, "0123456789".map ("" + _).toSeq, 2) // "88888"
```
result:
```
scala> baseXtoY ("88888", 10, 2) //"10101101100111000"
res218: S = 10101101100111000
scala> baseXtoY ("10101101100111000", 2, 5) // "10321023"
res219: S = 10321023
scala> baseXtoY ("10321023", 5, 32) // "2mpo"
res220: S = 2mpo
scala> baseXtoY ("2mpo", 32, 10) // "88888"
res221: S = 88888
scala> baseXtoY ("88888", 10, 5,"0123456789".map ("" + _).toSeq, "aabbccddee".sliding (2, 2).toSeq, 1) // "bbaaddccbbaaccdd"
res222: S = bbaaddccbbaaccdd
scala> baseXtoY ("bbaaddccbbaaccdd", 5, 10, "aabbccddee".sliding (2,2).toSeq, "0123456789".map ("" + _).toSeq, 2) // "88888"
res223: S = 88888
```
and ungolfed:
```
def todez (li: List[Int], base: Int): Int = li match {
case x :: xs => (x % base) + base * todez (xs, base)
case Nil => 0}
def fromdez (dez: Int, base: Int): List[Int] =
if (dez == 0) List () else fromdez (dez /base, base) ::: List (dez % base)
def fromTo (li: List[Int], in: Int, out: Int) = fromdez (todez (li.reverse, in), out)
val coding=(('0'to'9')++('a'to'z')++('A'to'Z')++Seq('=','/')).map(""+ _)
def baseXtoY (in: String, f: Int, t: Int, inCoding: Seq[String] = coding, outCoding: Seq[String] = coding, width: Int=1): String = {
val is = in.sliding (width, width).toList
val li = is.map (inCoding.indexOf (_))
val tmp = fromTo (li, f, t)
tmp.map(outCoding(_)).mkString ("")
}
```
[Answer]
Scheme type conversions take care of this. The numerical tower too:
```
(define (f n b) (number->string n b))
```
Floating points, exceptions... Everything is taken care of. Just put a number and a base and it gets converted to whichever base.
] |
[Question]
[
## The challenge
Create a program that mimics a chessboard.
## The datails
The chessboard must be surrounded by the labels of each row and column, being the columns labeled from 'a' to 'h' and the rows labeled from '1' to '8'. Also, place the default position for each chess piece (blacks are on the top). Each piece is represented by the first letter of his name:
```
King = K
Queen = Q
Rook = R
Bishop = B
Knight = N
Pawn = P
```
Also by his colour
```
W = White
B = Black
```
So any given piece is recognized by his name and colour. E.G: NB = Black Knight. Empty squares are represented by a hyphen (-).
The program must show the chess board with the pieces. Then it should ask the user to make a move with the message "Move". The program must read user input by console or equivalent. We don't care if the move is legal or not. The program must reprint the chess board with the piece moved, deleting any piece it was on that square. The move is represented `origin square destination square`. E.g:
```
2c 5d = Moves the piece in square 2c to square 5d
```
If the program detects there is not piece in the origin square or an invalid input, it must show the message "Invalid move" and ask again for another move. If the program detects the final square is occuped by another piece it must show the message "[Name of the moving piece] x [Name of the captured piece]". Eg:
```
PB x KW
```
The program is intended to run in a loop, so after each user input the program will ask again for another move. There is no exit clause for the loop.
Example of a initial chessboard and first user's input and program's output:
```
- a b c d e f g h -
8 RB NB BB QB KB BB NB RB 8
7 PB PB PB PB PB PB PB PB 7
6 - - - - - - - - 6
5 - - - - - - - - 5
4 - - - - - - - - 4
3 - - - - - - - - 3
2 PW PW PW PW PW PW PW PW 2
1 RW NW BW QW KW BW NW RW 1
- a b c d e f g h -
Move
2a 4a
- a b c d e f g h -
8 RB NB BB QB KB BB NB RB 8
7 PB PB PB PB PB PB PB PB 7
6 - - - - - - - - 6
5 - - - - - - - - 5
4 PW - - - - - - - 4
3 - - - - - - - - 3
2 - PW PW PW PW PW PW PW 2
1 RW NW BW QW KW BW NW RW 1
- a b c d e f g h -
Move
```
[Answer]
## Perl, 211 characters
```
y/W/B/for@8=@1=map$_.W,split//,RNBQKBNR;@b{$_.1..$_.9}=(@$_,/2/?PW:/7/?PB:"- ")x8for@r=reverse 1..8;$c=join" ","",a..h;do{y/a-h\n/1-8/d;/ /;@b{$',$`}=@b{$`,19};say$c;say"$_ @b{$_.1..$_.8} $_"for@r;say$c}while<>
```
Nothing very unusual about this first attempt, except maybe the use of a `do`..`while` loop in golf. Uses `say`, so you need to run this with `perl -M5.01`. The input parsing is really klugy and fragile; in particular, excess whitespace will kill it. On the other hand, you're not constrained to use 1-8 for rows and a-h for columns, either will do. End the program with Ctrl-C or by ending the input (Ctrl-D in Unix).
I assumed I don't need to match the whitespace in the sample output exactly — I prefer a more compact board anyway. (I did keep the board orientation, even though flipping it upside down would save me eight chars.) A sample game session might look something like this:
```
a b c d e f g h
8 RB NB BB QB KB BB NB RB 8
7 PB PB PB PB PB PB PB PB 7
6 - - - - - - - - 6
5 - - - - - - - - 5
4 - - - - - - - - 4
3 - - - - - - - - 3
2 PW PW PW PW PW PW PW PW 2
1 RW NW BW QW KW BW NW RW 1
a b c d e f g h
2f 3f
a b c d e f g h
8 RB NB BB QB KB BB NB RB 8
7 PB PB PB PB PB PB PB PB 7
6 - - - - - - - - 6
5 - - - - - - - - 5
4 - - - - - - - - 4
3 - - - - - PW - - 3
2 PW PW PW PW PW - PW PW 2
1 RW NW BW QW KW BW NW RW 1
a b c d e f g h
7e 5e
a b c d e f g h
8 RB NB BB QB KB BB NB RB 8
7 PB PB PB PB - PB PB PB 7
6 - - - - - - - - 6
5 - - - - PB - - - 5
4 - - - - - - - - 4
3 - - - - - PW - - 3
2 PW PW PW PW PW - PW PW 2
1 RW NW BW QW KW BW NW RW 1
a b c d e f g h
2g 4g
a b c d e f g h
8 RB NB BB QB KB BB NB RB 8
7 PB PB PB PB - PB PB PB 7
6 - - - - - - - - 6
5 - - - - PB - - - 5
4 - - - - - - PW - 4
3 - - - - - PW - - 3
2 PW PW PW PW PW - - PW 2
1 RW NW BW QW KW BW NW RW 1
a b c d e f g h
8d 4h
a b c d e f g h
8 RB NB BB - KB BB NB RB 8
7 PB PB PB PB - PB PB PB 7
6 - - - - - - - - 6
5 - - - - PB - - - 5
4 - - - - - - PW QB 4
3 - - - - - PW - - 3
2 PW PW PW PW PW - - PW 2
1 RW NW BW QW KW BW NW RW 1
a b c d e f g h
^C
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 1 year ago.
[Improve this question](/posts/3018/edit)
A woman works at a lottery ball factory. She's instructed to open up a lottery ball creation kit composed of 1 red rubber ball and *n* strips of digits from 0 through 9.
She's instructed to do the following:
1. Starting with 1, write the current number on the ball using the digits available on the *n* strips.
2. Put unused digits into a bowl where they can be used later for when she runs out of available digits in step 1.
3. Open up another lottery ball creation kit and continue to step 1 for the next number.
The question is, at what number will she arrive at before she runs out of digits to write the number? **Edited**: Given *n* where *n* is the number of digit strips from 0 through 9 provided in each lottery ball creation kit, write a program that can solve this (not trivially) in the least amount of time.
**Edit**: Additional notes - 6 and 9 are different numbers. Assume there are no limits to the number of digits that can be pasted on the ball.
**Hint**: If she counted in base 2 rather than base 10, how would that change the result and would that be easier to calculate? What could you derive from solutions in base 2?
[Answer]
**edit 2: fixed**
General solution for n > 1:
```
-- lottery2.hs
import System
import Control.Monad
import Data.Maybe
main = mapM_ print . map (solve . read) =<< getArgs
rdigits 0 = []
rdigits n = (n `mod` 10) : rdigits (n `div` 10)
digits = reverse . rdigits
undigits = foldl ((+) . (10*)) 0
c1 = c . digits
c [] = 0
c [0] = 0
c [_] = 1
c (0:xs) = c xs
c (1:xs) = d xs + c xs + undigits xs
c (x:xs) = c xs + x * (d xs - 1) + 10 ^ length xs
d xs = ds !! length xs
ds = map d' [0..]
where d' n = c1 (10 ^ n - 1) + 1
maxVal n =
fst . head . filter (uncurry $ (<) . (*n))
. map (liftM2 (,) undigits c . (1:) . flip replicate 9) $ [0..]
search f p q a b = s f (uncurry p) q (a, f a) (b, f b)
where
s f p q a b
| not (p a) = Nothing
| fst a + 1 == fst b = guard (not $ p b) >> return (fst a)
| a >= b = Nothing
| q a b = maybe (s f p q k b) Just (s f p q a k)
| otherwise = Nothing
where k = ((fst a + fst b) `div` 2, f (fst k))
solve n = fromJust $ search c1 ((>=) . (*n)) q 1 m
where
m = maxVal n
q (a, fa) (b, fb) = (a * n) - fa <= fb - fa
```
There seems to be a pattern here:
```
$ ghc -O --make lottery2.hs
Linking lottery2 ...
$ time ./lottery 1 2 3 4 5 6
199990
1999919999999980
19999199999999919999999970
199991999999999199999999919999999960
1999919999999991999999999199999999919999999950
19999199999999919999999991999999999199999999919999999940
real 0m3.580s
user 0m3.508s
sys 0m0.020s
$ time ./lottery 7 8 9 10 11 12
199991999999999199999999919999999991999999999199999999919999999930
1999919999999991999999999199999999919999999991999999999199999999919999999920
19999199999999919999999991999999999199999999919999999991999999999199999999919999999918
199991999999999199999999919999999991999999999199999999919999999991999999999199999999919999999917
1999919999999991999999999199999999919999999991999999999199999999919999999991999999999199999999919999999916
19999199999999919999999991999999999199999999919999999991999999999199999999919999999991999999999199999999919999999915
real 1m10.855s
user 1m3.868s
sys 0m0.324s
```
[Answer]
# awk (109)
brute force solution
```
yes|awk -F "" '{c("0123456789",1);c(NR,-1)}function c(C,m,i){for($0=C;NF-i++;)if((t[$i]+=m)<0){print NR-1;exit}}'
```
The `awk` does not count in the character count if I understand the rules correctly.
The trick with `yes|` + `NR` is a shorter way to define a loop counter than a `BEGIN` + `while` or `for` clause.
Replace `,1` with `,`[value of n]. With 1 it returns `199990`, with 2 it is still trying to find the answer.
Could write it as:
```
yes|awk -F "" -v n=1 '{c("0123456789",n);c(NR,-1)}function c(C,m,i){for($0=C;NF-i++;)if((t[$i]+=m)<0){print NR-1;exit}}'
```
And replace `n=1` with `n=`[whatever value] (now a parameter of the program, for an extra 6 characters plus the number of characters for the value of n. But like I said since it is still trying to compute for n=2, there may be no need to parameterise this version.
I'm sure there must be a much more clever algorithm than plain increment and count. Like a bit of algebra. No time for this... I'll leave that to someone else.
[Answer]
# C
Here's a non-golf brute force solution in C which seems to give the right answer for 1 strip, but I haven't had the patience to let it run long enough to see if it gets to a solution for 2 strips (in fact if I extrapolate the progress output I'm not sure it will finish within my life-time !).
```
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
const int MAX_DIGITS = 24;
char buff[MAX_DIGITS + 1];
int num_strips = 1;
int64_t digits[10] = { 0 };
int64_t i;
if (argc > 1)
{
num_strips = atoi(argv[1]);
if (num_strips < 1 || num_strips > 2)
{
fprintf(stderr, "num_strips must be 1 or 2\n");
exit(1);
}
}
memset(buff, ' ', MAX_DIGITS - 1);
buff[MAX_DIGITS - 1] = '1';
buff[MAX_DIGITS] = '\0';
for (i = 1 ; ; ++i)
{
int d;
// add 2 to each remaining digit count
for (d = 0; d < 10; ++d)
{
digits[d] += num_strips;
}
// update counts of remaining digits based on current i
for (d = MAX_DIGITS - 1; d >= 0; --d)
{
char ch = buff[d];
if (ch != ' ')
{
int digit = ch - '0';
digits[digit]--;
}
else
{
break;
}
}
// check to see whether we found solution
for (d = 0; d < 10; ++d)
{
if (digits[d] < 0)
{
printf("Found solution at i = %s, digits = { %24lld %24lld %24lld ... %24lld }\n", buff, digits[0], digits[1], digits[2], digits[9]);
goto done;
}
}
// log progress when i == 2^n
if ((i & (i - 1)) == 0)
{
printf("i = %s, digits = { %24lld %24lld %24lld ... %24lld }\n", buff, digits[0], digits[1], digits[2], digits[9]);
}
// increment "i"
for (d = MAX_DIGITS - 1; d >= 0; --d)
{
char ch = buff[d];
switch (ch)
{
case ' ':
buff[d] = '1';
break;
case '9':
buff[d] = '0';
continue;
break;
default:
buff[d] = ch + 1;
break;
}
break;
}
}
done:
return 0;
}
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 9 years ago.
[Improve this question](/posts/266/edit)
A friend sent me this puzzle. I'm pretty sure solving it will require some programming. Can anyone crack it? The original is [here](http://www.otit.fi/mystery.txt) in case of encoding issues in the past below.
```
Did you know that...
List of prime numbers include 2 as only even number, but not 1 which is equally not divisible by any other number than itself and 1?
Indexes in most of the programming languages start from 0?
Random mess is often considered as just "life"?
Prime bits of life include open position in Nokia?
Start here:
QnšmzFyN\�Li�B§TJ�vhgUEg�XbDMb¯o�ag�wUF�Iv¶u²nGTbf�vFc�]n¡vbD^Q@utJjMthn wŸ�B�CiŸ`yuftlyF]^Qvfh¹ºK[fF�wXuHdojG�YftvTP�OwmU�gzF�zuYQ�Z[gEn�wjU�MmŽ`FDtœPC�Sw`�Raw^»DuFlVvUdEa@uiluigJQhgtc[ŒGVcBSUL�OtnouŠ�KwGTI hEtwžgtEAtl§wuZoE�Qvvc[wZ@¢Pu\T�fo[RXtGVU¶wCdySwU[{w��wGX\�\v^ŽBFS_v^^@yXPmctvPcoWvHlfBwI�FJGu�AbWcnuªOv@[j�tu@GwBNB[tX�USioimTC¶KQŸbv\iiYK£DQ�[Ich`Oš[vcwaOyJ\RoŸP�tMQvtEvLKºWbwBvtvQžf�kXv°A\TA¬�PPwU�eTT[NAIAFhvti{WOga{`H�tRJ{a`BMHUI[ZI`lIDb\BA�fa`mtd€gK\@BwCTeR�³ww�NFDCGvfQSz£t`FBZ¬wMevA^Rv¢^iSct¢Bk�\zjNBv¢tRbIwNv\¹E³tiBHxwCH«\mtt`xgNBu@hJŸkeZbQŠaaF^o_YEcLii£F`tKjU_wHt��w®wDvO^²¶[DDvAvP�uk»gAOtx]JHRuWvcu�dQmŠn_\guZD]DlHh[€DGvfb@_X¬TMt^Xun@F«twOMTIv�]ZjvKSTwdRicvxG\K�¯mStILhUvOjwb^t�xi_VJUuRwh§v`Wg]W{JoŽh]uvIdw�@QXZ]«ŽinWJ�R_ZtwB¶Vu_JStI@UUMxT`²VYyuV�l\eW]lOghv]²NP\i�xySiuJvZG±ut�`\jMEtVZuv�twv±o_Awu�vn�oŽzYTM^fEt\bWH�M�lGilw�BI²tPgTvaE`h±e�x\aafvBNmt[RŠn£hjOBEUtmhNHtAuVHP�va_uOn�\UKnuBAHW_waFwH{WLu\ZRvT[nmvv«B]Yj�JbF¹BgyDNcv^`@iAwwlweFYlwe�§fk@mnPNh�Fg\`Di[�{j¬enk�Jw{Wh^[�cYO]`MWu®�oclQTg`X�VbnXlK\\ŠMuvAw]_^®SvTA�ZSmwB`PUwYw�»\utCnl[JGcuWVTXo€¬M¡aoPuvjR[jvV[�C_zM�nUn�wP«t¿IMVtuhwFJXvº@t^UEtIhGbCXt]bVSE€CMuZktmH_uvtwuIt¹vtKy{wNC«YivUM[BG�ntCJ^aBBFdhfNlPoBE@kuTe�VC�kRwwhZdTtfnt�^v^mg�cPeh�§Au°^BtND�Jd[f\th§`jNwRvFHLu@MNwvuSR`CdSE]vaaw_wPIvRjw^HXDi°fQ�wIfNTS`ttSA¢jv XX�EP@lbDALWdzkuG€_VQvmjIX�EkTummeC³iuZokw�]uQfMcBu�SXH_Whtuv^SjyejxoEtœwStoD�xVeaOA�jtJBa_KDPwtK^\ounwfZKDDuL@[vhIDI»tvvJc\cµvWe�FPvv�beWKUtaOtvA�DMTLcPh]nDD[Qfc�R�vwštAvhfWEv^hEZPuvaCNDBQtwdvuaw@�D@dPCG�wIdttYMKvau²wQnm^mOuvaZNB�viKBvkuDj¶BuVb_§hGtkEZvSc�tttµ_GxwvGwŒ]U�[{KJcv�h�ŒKv¯vRQIPHOivFG©LtXvtljuIB\^v�zDiPBgtcm�@tUdetwYhQuvK§¥t[�HONFwcXDxH�w`t_J`�tcHXM`vO°wkQQttw§@t£uvI[TTRgvŠbf¡AJoWoRfT�dP�g�wi�S{wYYh¢uleHR@\�KnK³u\vNcx{FHkvwTMEwP�gngEvutdGOE[teWDµwKOdG�G^�wEGARcNYutf�tvmdutv@TvvF�QHkX�]tPbvšlwvVJwuKu�So@o©]LNLx�btvXGDdlLz@eVzCltvwvt�Vb£L²wPXh_viyOw[XEkSvEJdIvmVJuw�@VGTw�tjKhjv�uWmEUhI®TtwRiuŒFZ�lYtuH\\F�Ufšn®YSu�dšOk�xuVdDgmOIEBUdw@]kvtEYAt^�NutW®®ebtMhv\kfljk@±nLgEB[�fImIKt[[�jo¯OnMtwcfgKcŒuEEªvvN\�tEw`GvNQ[gUK_euho�oY[�WTKMBatvl^twJ¿cK^lAaHw�M_uFK�DvtfNªKw€šKnIv@FiI�vj°S±Ru@wid»Qt\uRvZDvZjkwuFQVH\�zW[�hMUUkNe^�famV�TGw[hJovbtugIw`t`BDwl�tlVwQmtQ^YnOA¡StuCiv�]µ€BJj`n�]BeYi[PLtY@mAoPxHxI�SwIiJ�LA±uMhPm[oPG¯OUHuKvlIbwNttX�w_k]gwmL_`m�Ef]AVvwuPiwNT±Œfw¢`XAAKuwBvkLVXNix®]lVGSo�b]XS�[foSn�]Hu®md[Lf�QJcY�ZtkŸBtjtvPH�MfYBFnLYty_dBTQzdwT@W�[uvFwama[oj@Zh�IBmYtPJEie¹�Bw]\wOwŠNdfNul^zSwwYuOu^u]`nm¬vBBvmDP^ZGRgtIxcZYbn�Dn\D¥`otŽi^E_BvD]_w u\w�EvimvuPGwH�ST^otQ¥u]�KU¥W[CR¯l@vjt€^ATNu¥HVªTvC�ifzwteG[[`gtFJŠK¡tjt�MNbkuSuMDU£lt^[E�tiLc{ZhFu`RX]tdXvYuXuTdAKvuaxPXfi[Wg]wAeukeQkuP�utvvVBExOjgi{ad`HtaiŒuvo^u@lN©Awbub\kDWµ\»WYuRYZFHR{QvojtyNbtvwDOIv_YnAu^wttunyu[VCOQWE^dTuwtuYUwl^�VXlGž�NNFk��``KQV\NWHG] ^RNkRVQw\JAO@@wdV�ev«tc[vLAZNMoYZQk�H�uFBOdt]c]ADKDfvfC[�u`®\tSX�vUDE^vu_e�JwOhmd]EMwiRHmUH]\W°vtHzWµ\@j]^mh{MAxnAPu\QuvQuekthoµRTwNX`uTcŸS_Bc�SZwJJwe_cye^ªNtwv�Wuu�ev�IQ¹B�Xt]Q_gbVkmXwh_XUL±»tvvId`wAgX�]bžmVumB«DlJ_G�D@egUoPtu�@i[S¥e\ŽFIMFweI`ut_wIOD«vZ[_wiGuVZKFk±PDG�Aw@^`vAoS{nvw``kXUSuuZWù
```
[Answer]
## Python - 132 chars
Data is read from stdin, starting from the "Qn..."
```
I=raw_input()
print("%X"%int("".join(`ord(I[x/8])>>(7-x%8)&1`*all(x%f for f in range(2,x))for x in range(2,24024)),2)).decode('hex')
```
] |
[Question]
[
**This question already has answers here**:
[Stackable sequences](/questions/144201/stackable-sequences)
(27 answers)
Closed 2 months ago.
Given a list of non-negative integers the function \$f\$ replaces every integer with the number of identical integers preceding it (not necessarily contiguously). So
```
f [1,1,2,2,1,3,3] = [1,2,1,2,3,1,2]
```
We will say that a list, \$X\$, is *in a loop* if there is some positive integer \$n\$ such that \$f^n X = X\$. That is you can apply the function to \$X\$ some number of times to arrive at \$X\$.
Your task is to take a list as input and determine if that list is in a loop. You should output one of two consistent values, one if it is in a loop and the other if it is not.
This is code-golf. The goal is to minimize the size of your source code as measured in bytes.
---
A note: There are other ways to formulate this condition.
## Test cases
```
[2,2] -> False
[1,1] -> True
[1,2] -> True
[1,1,2,2,3,3] -> True
[1,2,3,1,4,2,5,3] -> True
[1,2,1,3,1,2] -> True
[1,2,1,3,1,3,4,6] -> False
[1,2,2,3] -> False
```
[Answer]
# [J](http://jsoftware.com/), 14 bytes
```
-:(1#.]=]\)^:2
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/da00DJX1Ym1jYzTjrIz@a3KlJmfkK6iHFJWWZFSqQ3hpCoYKhgimEZKoghEQGisYI8kCuYYKJkDaFFXYECwB1azulphTjDDfCNlQmFJjoClmyMJAo/8DAA "J – Try It Online")
This uses the fact I conjectured in the comments, which WheatWizard confirmed is true:
>
> It looks like the true ones all have a cycle length of 2, and the false ones converge to something with a cycle length of 2 also, just not including the original input.
>
>
>
So, we simply apply the transformation twice, and check if the result matches the input.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ċṪ‘ƊƤ⁺⁼
```
[Try it online!](https://tio.run/##y0rNyan8//9I98Odqx41zDjWdWzJo8Zdjxr3/H@4c5/1o4Y5Crp2Co8a5lofbgcKqHA93L3l4Y5ND3csCjvW9ahpzeF2IBH5/3@0kY5RLEipW2JOcSpXtKGOIZgbUlQK5hmh8IB8IDTWMUZVAxQx1DEB0qYYMoZgOSOsosZAPWaoloONRwj9BwA "Jelly – Try It Online")
A monadic link taking a list of integers and returning 1 if a loop and 0 if not. Uses @Jonah’s observation that we only need to apply the transformation twice and check whether we get back to where we started.
## Previous solution, 9 bytes
```
ċṪ‘ƊƤ⁺ÐL⁼
```
[Try it online!](https://tio.run/##y0rNyan8//9I98Odqx41zDjWdWzJo8Zdhyf4PGrc8//hzn3WjxrmKOjaKTxqmGt9uB0ooML1cPeWhzs2PdyxKOxY16OmNYfbgUTk///RRjpGsSClbok5xalc0YY6hmBuSFEpmGeEwgPygdBYxxhVDVDEUMcESJtiyBiC5YywihoD9ZihWg42HiH0HwA "Jelly – Try It Online")
A monadic link taking a list of integers and returning 1 if a loop and 0 if not.
## Explanation
```
ċṪ‘ƊƤ | For each prefix, count the number of times the popped tail appears and then increment by 1
⁺ÐL | Repeat this again until a value is seen for the second time, returning the last value that has not been seen before
⁼ | Check whether equal to the original argument
```
[Answer]
# Python3, 115 bytes
```
def f(a):
q=[a]
while(l:=[sum(k==j for k in q[-1][:i+1])for i,j in enumerate(q[-1])])not in q:q+=[l]
return l==a
```
[Try it online!](https://tio.run/##bZBBT8QgEIXP8ismvRSyrAmta0wTPHr05A17YLPTLLuUUqAaf32lJMZsNBzIe/Pxhhn/lc6Ta598WNcTDjBQzToCs1S6J/B5Nhap7aSKy0ivUl5gmAJcwTiY1V70qjM70bPNNPyy2eiWEYNOSAvAeuamVPhu3kllc2rAtAQHVkq9RpBQVZVqeNPD/hletI1IlOCiyLewFNXcqKzzaXl7y2RH8Id8H/5URKk1/7ptfvN427zE/1r5g4SUGbdBBmMTBvo6OeQQ76O3JtH63dUsb@5OczjmmUbtKX5oy8H8EFtcZjISI4ZUVg1SwpEQH4zLRMKYIvitfqrZ@g0)
[Answer]
# JavaScript (ES6), 59 bytes
Naive implementation. Returns a Boolean value.
```
a=>(g=a=>g[a]?a+""==b:g(g[a]=a.map(p=v=>p[v]=-~p[v])))(b=a)
```
[Try it online!](https://tio.run/##jc9BC4IwFAfwe59CPG00lc3qEDy79Qm6iYen6SjMDS2PffU1NUFCww32GPu9P3t3bLHJ6pt@epW65qYAgxARCfaUMSYn3LouQHqUpLsC@g/UREMLkY7bBLx3VyilJAWkJlNVo8rcL5UkBYkFE/bNma4gcM5YNvnmh3LGZ@ilfs1IsVpaa3fIwrFjOdMqzna27gf9R/LeihWZgwxt7uGbuTB8/83pWCM1Hw "JavaScript (Node.js) – Try It Online")
### Commented
```
a => ( // a[] = input array
g = // g is a recursive function taking ...
a => // ... the current state a[] of the array
g[a] ? // if we've encountered a[] before:
a + "" == b // stop and return true if this is the original array
: // else:
g( // do a recursive call:
g[a] = // mark a[] as encountered
a.map(p = // p is on object used to count 'preceding' values
v => // for each value v in a[]:
p[v] = -~p[v] // increment p[v]
) // end of map()
) // end of recursive call
)(b = a) // initial call to g with a[] saved in b[]
```
---
# JavaScript (ES6), 45 bytes
Optimized version using [Jonah's conjecture](https://codegolf.stackexchange.com/a/268547/58563).
```
a=>a+""==(g=a=>a.map(p=v=>p[v]=-~p[v]))(g(a))
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RW0nJ1lYj3RbE1stNLNAosC2ztSuILou11a0DUZqaGukaiZqa/5Pz84rzc1L1cvLTNdI0oo10jIByCshAX1/BLTGnOJULTamhjiEWpSFFpVhUGhGtEqgWCI11jGE6cJsJVGWoYwKkTSGq8ag0BKs1IsJMiEpjoLlmUDNxeB7sTGRvwZT@BwA "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 41 bytes
Further optimized, knowing that we're actually looking for a [stackable sequence](https://codegolf.stackexchange.com/questions/144201/stackable-sequences) as pointed out by [xnor](https://codegolf.stackexchange.com/users/20260/xnor). This is basically a 1-indexed version of my answer to the other challenge.
```
a=>a.every(k=>a[a[-k]=-~a[-k--],-k]--|!k)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RL7UstahSIxvIjE6M1s2OtdWtA9G6urE6QJ6ubo1itub/5Py84vycVL2c/HSNNI1oIx2jWE1NBWSgr6/glphTnMqFptRQxxCL0pCiUiwqjYhWCVQLhMY6xjAduM0EqjLUMQHSphDVeFQagtUaEWEmRKUx0FwzqJk4PA92JrK3YEr/AwA "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
Let's introduce a simplified variant of the well known Spider Solitaire.
From Wikipedia:
>
> The main purpose of the game is to remove all cards from the table, assembling them in the tableau before removing them. Initially, 54 cards are dealt to the tableau in ten piles, face down except for the top cards. The tableau piles build down by rank, and in-suit sequences can be moved together. The 50 remaining cards can be dealt to the tableau ten at a time when none of the piles are empty. A typical Spider layout requires the use of two decks. The Tableau consists of 10 stacks, with 6 cards in the first 4 stacks, with the 6th card face up, and 5 cards in the remaining 6 stacks, with the 5th card face up. Each time the stock is used it deals out one card to each stack.
>
>
>
[](https://i.stack.imgur.com/Ft67C.png)
For the purpose of this challenge, you will receive a standard Spider Solitaire tableau with only a single suit and no extra stock, where you know the rank of all the cards, including the ones that normally could have been covered.
The task is to determine if a tableau is stale, i.e. the game can not be won/cleared from this position. This may happen because there are no moves, or there are moves, but they lead to repeating positions and do not ultimately end up with the whole rank sequence being taken off the board.
## Examples
The following tableau is stale (0 - king, 1 - queen, 2 - jack, etc..., all down to the ace):
```
3 9 5 3 9 10
1 2 10 12 8 4
10 5 5 4 5
11 1 3 0 1 2
0 6 2 10 10 11 12
1 5 6 4 4 5
3 6 9 3 8
4 8
2 3 8 9 10
6 5 1 5 1 2
```
Not stale:
```
0 1 2
3 4
11
9
5
10
12
8
6
7
```
Not stale either:
```
0 1 2
3 4
11 11
0 9 12
5 10
1 10 9
12 5
2 8 8
6 7
3 4 7 6
```
## Scoring criterion
Code size in bytes in a particular language.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 112 bytes
```
Iœr€1Ẉ‘rẈżị¥";@€"JȦƇẎW;ⱮṪẹ@¥ɗ€0ịⱮa‘$€Ɗ}Ẏɗ;pṆ€Tḣ1Ʋ}¥ɗị@œṖ@©ƭƒ@ḢWɗ1ị$}¦;€Fɼị@Wʋṛ¦ƭƒ€µœṣ13R¤F))Ṣ€
W©;Ç€ẎQ$ḟɗɼ$ÐLẸ€Ạ
```
[Try it online!](https://tio.run/##TY6xSsNQFIb3PMUhZOnW29TWkuVOBcVFETM7uEgH6eYQkA5GLIhYMIKD0tpARQWLQm7a6YaEXt/i5EXiHyene/7vfD/nnp4MBudVtZNPhuXoTXB6VV48DPHka16N9dz2JLi9u4mLkNMb3ys/P1i9cqqknpsIuyY8wGP0HMTiOoBnIu@M1SXyISczUSyD2oYp8wmre6kXxXtxJzmZ@iYS4E6gYw9639R3pf8zZvWo49oC1d91bSbcA/3SbzRYTQEtXy@8LMSEg/sOJ08mMmsnu93jNPmjzxWvvjhZIhxhXX82C6vKtm1BLXKtHm1T12rTFnWoi7lHoklCkGiRcK0OeJtcmML6x9H@BQ "Jelly – Try It Online")
A pair of links which are called monastically using a list of lists of integers as the starting tableau. Expects cards to be numbered from 1 (King) to 13 (Ace). Returns 1 if the tableau is stale and 0 if non-stale. Times out on TIO for more complex tableaux. This has taken a rather long time to get to this point but I will post an detailed explanation in due course. Removing the `Ṣ€` at the end of the first link should also work and saves two bytes, but it times out on even simpler examples like the one in the TIO link.
## Top-level explanation
1. Start with a list of current tableaux (on first iteration will be a single one).
2. For each tableau:
* Work out which runs there are at the end of stacks.
* Work out which of those runs can be moved to the end of another stack.
* Also add the possibility of moving any run (including single cards) into the first empty stack.
* Create new tableaux based on all of the moves identified above
3. Join the new tableaux created in step 2 into a single list
4. Remove any complete suits (from 1 to 13)
5. Filter out any we’ve seen before
6. Append to the list of all possibilities
7. Stop when this list is unchanged (i.e. no new possible tableaux were generated); otherwise feed the new tableaux back into step 1.
8. Determine whether all of the possible tableaux are non-empty
] |
[Question]
[
The aim of this post is to gather all the tips that can often be applied to [radiation-hardening](/questions/tagged/radiation-hardening "show questions tagged 'radiation-hardening'") challenges.
Please only post answers which can apply to a large number of languages, and one tip per answer.
[Answer]
# Create a path on the right hand side
In a 2D programming language, and with radiation that deletes or inserts bytes, a useful pattern is to create a path on the right hand side of the program, and get the pointer there quickly.
This is because deleting or adding a character will always change the length of a line and disturb this path. This lets you detect and adjust based on the disruption.
For example you can use this to avoid damaged lines, or intentionally execute them.
Here's an example where I've used this strategy: [Construct a Geiger counter in Klein](https://codegolf.stackexchange.com/a/226071/56656)
[Answer]
# Trivial Tips
## Redundancy
This is a fairly obvious one, but redundancy can help.
For example, if you have a program in a string/function written multiple times, and then a small "core" program near the end that checks for the longest program, the program can likely survive a random hit, or even a few.
] |
[Question]
[
# Challenge
You just entered a room. Here's how it looks (you are the X):
```
|\ /|
| \/ |
| X |
| |
|----|
```
You challenge yourself to see if you can reach where you started by following the walls. You go right until you find a wall. Then, you turn clockwise until you are facing parallel to the wall.
For example, if you hit a `\` while going down, you will go up-left.
After that, you continue and repeat. In this visualisation, you will leave a trail. Here is how the example above would progress:
```
|\ /|
| \/ |
| Sxx|
| X|
|----|
```
You continue following this pattern.
```
|\ /|
|X\/ |
|xSxx|
|xxxx|
|----|
```
And yes, you reached the starting point.
```
|\ /|
|x\/ |
|xXxx|
|xxxx|
|----|
```
However, if there was a hole, you could get lost:
```
|\ /|
| \/ |
| SxxX
| |
|----|
```
## Input
As input, in any reasonable format, your program must recieve the room you are in, which consists of walls (|/-), spaces and your starting point (the X) (the starting direction is always right).
## Output
As output, your program needs to output a truthy or falsy value representing if you got to your starting point.
# Test cases
The format here is input -> output (reason for being false).
```
/-\
|X| -> true
\-/
```
```
X -> false (hits boundary)
```
```
X |
-> true
\
```
```
X |
-
| -> false (trapped in endless loop)
|
- -
```
# Scoring
This is code-golf, so the program with the least bytes wins!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 94 bytes
```
WS⊞υι≔⪫υ¶θPθ…θ⌕θX≔⟦⟧η≔⁰ζW∧KK∧¬№η⟦ⅈⅉζ⟧∨φ⁻XKK«⊞η⟦ⅈⅉζ⟧¿№ X⊟KD²✳ζ«M✳ζ≔⁰φ»≔&⁷⁻ζ&³⁻ζ⌕-/|⊟KD²✳ζζ»T¹¦¹
```
[Try it online!](https://tio.run/##jVDLTsMwEDzHX7HyyZZcQeHAoadShARSIBIcgtoequDUK4Kd5tGK0H57WIdAihASe1jvjDWzj8SsisStsrbdGcw0iBub19VDVaBdCykhqksjagUoJ2xalri24tah9RRfWC4VbOgnrLMKc9JUwsOoq2ZvSaZnxuVio@Aa7bN/ecylHLzmSwVmgKcKGkL9KFOSRFq/COri6ztHpq4ma6NgHnv6yadmKSnfFyJVEKKtS0FdFHxKu4B3FnSb/BJOWIAp9LYcOh1N7LVXWOikQmfFmYIBNN@OQei2Wvz4Ibtg2CX1@MACnZUaevoSqx2W2u9z8TVuo@CIPj@iu7Px0cn@v3P5S/gTHthjga9irGAsJ20bA8WeQRd/Pwtg7WibfQA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a rectangular array of newline-terminated strings and outputs `X` if you reach the starting point. Explanation:
```
WS⊞υι
```
Input the map.
```
≔⪫υ¶θPθ…θ⌕θX
```
Write the map to the canvas and start at the `X`.
```
≔⟦⟧η
```
Prepare to detect an infinite loop.
```
≔⁰ζ
```
Start moving horizontally.
```
W∧KK∧¬№η⟦ⅈⅉζ⟧∨φ⁻XKK«
```
Repeat until the cursor moves out of bounds, repeats itself, or moves back on to the X.
```
⊞η⟦ⅈⅉζ⟧
```
Remember the current position for loop detection.
```
¿№ X⊟KD²✳ζ«
```
If the next step is out of bounds, empty or the start, then...
```
M✳ζ
```
... move to that square, and...
```
≔⁰φ
```
... remember that a step was taken.
```
»≔&⁷⁻ζ&³⁻ζ⌕-/|⊟KD²✳ζζ
```
Otherwise, rotate clockwise appropriately to the new direction.
```
»T¹¦¹
```
Output the final square.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 197 ~~199~~ ~~205~~ ~~208~~ bytes
>
> Gained some bytes by improving solution, but lost some by fixing a bug regarding "bonus case 2"
>
> Gained 8 bytes after analyzing suggestions from *ceilingcat* !
>
>
>
Interesting challenge!
The input is a single string, with line breaks at the end of each row. Each row must have the same length. Returns `true` if we can reach the starting point `X`, and `false` otherwise.
```
s=>{i=(d=(p,q)=>p.indexOf(q))(s,"X");l=~d(s,`
`);try{(g=(x,y)=>{d(`X `,c=s[z=i+x-y*l]||" ")+1?i=z:0;g([0,x,-y,0,-x|-y,t=x|-y][a=d(`X -|/\\`,c)],[0,y,0,x,x|y,t][a])})(1,0)}catch(e){}return"X"==s[i]}
```
[Try it online!](https://tio.run/##hVLBbhMxEL3vV4z25CV2NwUkUCu3EhJnLhwidSPF2cymC453aztlQ1xu3PgE@Ln@SBh7W7WVKPVGGY/85s3z83xR18rVtu29MN0KD408OHm2byVbSdbzq0Ke9UetWeHwqWFXRcEcz2d5carljxXtF9miOPV2t2dryQa@I/h@xRYzWPBauovvsp0MYvdKz0PIIS8mx@et/H4yPV2ziykfuNjxKRdDoOhlDPMLJVO9CGVVEUkx54SMsIEPgWCEmBc3BTvm0@KmVr6@ZFjsbyz6rTUkTVLbdn5zUM6h9ZL51mvkrem3nuPQY@1xRSrrzrhO45Hu1iyvTGVkXJBPEn6SQ8ork08Ys@i22suGJZaioIN7pvP89vdPyE/y2z@/4v1G6CQx5pMRn2WjFpZ/HNSm1wi1cggngKbWncMVuF7VmPNsEaoKoAxZgKoqIcYZpAApCFohW2QcvN0iPGL@jM6PtMdE7Py2/grKg79ESpT10HQWr9HGJqWoqizMQlZVonyB7TWxmQ66JbHUOmmcpZJGafdMzRuqWSoS4LsHAalyvAak9XwgD15Q9ZY6tKZpTesRdNf1j9nFPRG5NjoXM0Hfv4V/6MzWPXiHrlY90qWtvxSoqKVqPFpYbjd9a9bUl671Dr4prV1yM8p94ub/OkQ/O6N39IfQ226pcaN8Wz91OLzIEz22WNvOOVA0P1i3DbGkQYL34NsNJnXRBhFopMgEElhVAUKZnIk2068cfRIi2kcn4t6zZGAmwvgiIiZ0Xt6VUZYq08COuPilQ5GlPU1rBI4J3D1O3MUpJqsikuL4QI/e@/AX "JavaScript (Node.js) – Try It Online")
---
This solution uses recursive calls of the `g()` function and catching exceptions to end an infinite loop (particularly useful for test cases 1 and 4)
Our position is the single int `i` corresponding to the index in our one-dimensional string. To go up or down, we substract or add the length `l` of the first row. This works only if all lines have the same length, which is a prerequisite for this code.
In each call we check the cell where we are supposed to go with our current direction (expressed with the `x` and `y` parameters of the `g()` function. These 2 parameters can only have the values `[-1, 0, 1]`) :
* if it's a `space`, we change our position to this cell and keep the same direction, then proceed to the next call
* if it's an `X` or a `line break` or if our target cell is outside of the string (`undefined`), we change our position to the index of this cell, and change our direction to `[0,0]`, then proceed to the next call. This allow to "stuck" our cursor on the target cell, and never move while we provoke an infinite loop to end the algorithm
* if we encounter a wall, we don't move but we determine the resulting direction for the next call, and we proceed with this call. For this part i created **[this tool](https://tio.run/##fZO9bsIwEMd3niK6LrFig8OIZJi60qEDQ/CAggtUKEEkoCBl7VapU7e2e1@LF0nPcQyEJB1857uf7@7vfLwujosk3G92KYvipSrWonBDmtETEeNQCGAwCdiJcjnSUY4Rp5kJBhplOdIsP5nUfI65VJTJVI7gAYpFkqh9KtxNtDukPi3dkKpsp8JULeleJYdtKtZ1HnBpd74kWkocJfFW9bfxynVNjQcghO2DwQTOX28OjOD8/e4A8bDkiJNN4yHxwDn/fDrgwRzAM9PMHsHHLwJbYNoT0qsSojwsxgFMgcL0EY1ez6XRa4ZGr@kMZBAAp8zHyLeOl1bveWmZbx03Ds/J/iZaquzpxcjF6xDZ65ln5@JLoAEWSRroIklqgHcB1lmiR0rtmr06AKuV3L6N67n8olJLus/zjjxrL2C2E2shvJOwm6J2lYOLmnLEPfDbAe8ClRq/rmZQe2Ss2e2WtOvEX8kKrU@tQNWhQfg/pLoDa6Drp9LK@JUVfw)** to help golfing it separately of the whole "mess".
* At the end we check the final position we've reached. If it's `X`, it's truthy.
* `d()` function is a shortened `indexOf` (because we use it more than 2 times)
* in the core mechanism, i used a lot of arrays combined with the already shortened `indexOf` because i throught it's the shortest way of doing a switch case?
[Answer]
# Python3, 484 bytes:
```
E=enumerate
def f(b):
r,X,Y,F=[(x,y)for x,r in E(b)for y,c in E(r)if'X'==c],0,1,0
x,y=r.pop(0)
while 1:
if F==4 or(r and(x,y)==r[0][:2]):return 1
if(len(r)>1 and(x,y,X,Y)in r)or any([(j:=x+X)<0,j>=len(b),(k:=y+Y)<0,k>=len(b[0])]):return
B,U,I=b[j][k],X,Y
if'|'==B:X,Y=[-1,1][Y>0],0
if'-'==B:X,Y=0,[1,-1][X>0]
if'\\'==B:X,Y=[1,-1][max(X,Y)>0],[1,-1][max(X,Y)>0]
if'/'==B:X,Y=[-1,1][min(X,Y)<0],[-1,1][min(X,Y)<0]
if(X,Y)==(U,I):r+=[(x,y,U,I)];x,y=j,k;F=0
else:F+=1
```
[Try it online!](https://tio.run/##dVHBbqMwED2vv2KUC/bGFEjSakXrHCo10l72Uq1EhNEqaYxKQgAZqg0S/56OMUmzbdaX8bz35s2MXbXNa1lMf1T6eHwSqnjbK71qFNmoFFK6ZiEBzSO@5AsR0wNvWVpqOHANWQFPyJu05S821SxLncgR4iXhPg@4T1DaCn1TlRX1GYG/r1muIEBTyFJYCDGDUlMNq2LTmwuhYz@Jw0nCQq2aN11A0Gtprgq0nwcnqZmJYVPNSlPe0phuQ3EYR@zB59u5MPo143QXina8NOBuALEBO9uj@SP/zX@KdbxN4l1ibPuGTodrPIaYitgNeJDEy7mfmI0M6Z5Jn8cBd5GOkLaklB@lltuvDtTMaxy@QrbK@9xvnxW94sEUfYHsq5hECIoL4EJj@0NmHZbcm4ff8t39QpiZVV6rcDEWwdF8bFP@WZcrvaHP@L/fhoeOv6dZ3ihNf5WF4vB8U1d51lBHFg5jCSF1AAJGoxHppATwOtKBlB6YGEEfoA8uno4YYT0ZKjxXStJFHZHS9Sw1HajIprNTak2gP/8PaNeX3Q1lBvMuVacrzvIvit62x4B2l@aDuLvwON2Rsi1vP0169u8@5Ji64Pb6SmdFQ1N6fvI6YIxdgSfX4el1eHYdvr0O3yF8fAc)
[Answer]
# [Java (JDK)](http://jdk.java.net/), 282 ~~283~~ ~~287~~ ~~292~~ bytes
>
> -2 and -1 bytes thanks to *ceilingcat* !
>
> -7 bytes with some optimizations
>
>
>
Not bad for Java!
The input is a single string, with line breaks at the end of each row. Each row must have the same length. Returns `true` if we can reach the starting point `X`, and `false` otherwise.
In this solution, we take advantage of the thinness of the boundary between `char` and `int` in Java.
```
s->{int i=s.indexOf(88),l=~s.indexOf(10),x=1,y=0,z,a,c=0,d[],r=2;for(var t=s.toCharArray();r>1;y=d[z+5])x=(d=new int[]{x,-y,0,-x|-y,a=x|-y,y,0,x,x|y,a,r=(z=i+x-y*l)<0|z>=s.length()||(c=t[z])==10|c==40?0:t[i=c>31&c<41?z:i]++>0&c==88|t[i]>95?1:2})[z="-|/\\".indexOf(c)+1];return r>0;}
```
[Try it online!](https://tio.run/##jVTNjts2EL7nKaY6BFIl@mezQV0r9KItckvQQ3pYwPKBpse2EpoSSHoj23JvvfXYW9uX2xfZDmnZiw2KxVKARsOZ@Wb4zVCfxZ1gnxdfHurtXJUSpBLWwkdRaji8egVQaodmKSTCB9oAWvOqUig0LONPzpR6BTbJyXD03tYJRyAfQAF/sGxyoHAoue2VeoHNr8t4NEoyxX9/3BgOkqzhw2zHB9k@E5kkuZjOMsOv8mVl4jthwBGAq35ZC/OTMWIXJ7mZDPMdX0z36dtZ0vB4wTV@9bVOZ4cmY7tskLGmJSl4EH6jyZqWNgg53vMybdjue5W8G7T7CcEr1Cu3jpO2jSV30/0s4Xw4aCXn14ObwdhNSy4nb4av5bvr4c1@XM7SdDJ4TebRqCXjbPLj25vh@OqYTPc8Ym2/KKLLEWWSDme5Qbc1GsxkkB8fck9Wx3jH2V1VLgDvhNoKh2dqXekUZtBptTBik10agE2N0uEi@aYxBu1WOeDw3dkjD3ZndoeLTfWWccBL8qMUTq7j943E2pUVASeHYEp5VOj7v/@CKMXeCt1HtFasME7SCGi70IWO8mPA/rSzDje9aut6NdXqlI4jb@d@UXw4CIUFncLS@FQJ5@cab6L7f/6AaBzd//snREl6sqcBJUq7Us9z9j/UbWhkO9qmMxBmZZPTBMMjq9H7RmxqhSCFRRgDaqkqiwuwNU14lEHUFgVAvy10C0XRh/BxCycJJ8lokSRvZ7YISf5tkt/QulOGIeWwbiu/gHDg1ugLNg5orvEOjc/XZ0VBmLcEWBSs/zLYK4LVFVRzgpMq1H0bIpdC2edD31DoXFBBrnosKAB0x4OwnpfE0csKvaZspV6WunQIqqrqJ5nYBbH1sr1kYPQ8e56fK721jxSjlaJGosS4NUNB2cWS/low325qf29oHiv4Ab4KpWwgPRzgKekvSOVpr7Ta0QuhNtVc4SbM35NGtC@F860wKE1F/1tBE4iyXPqZ9qMII7r6GwzVen5YS0PpyaF6i6KFtn/iLLSigH5HIWOeXLKxC5@BXbK0p8axoJFLvwv1aggPk9@5@ieYGfkGlTHv22lw7qD/9NfBc@i96aNr4tPpoDt7fPgP "Java (JDK) – Try It Online")
---
This solution transforms the input string into an array of characters, and our cursor "increases" the ASCII values of the characters it passes through.
An infinite path is detected if we pass strictly more than **8 times** through the same cell, which would return a `false`. But if this cell also happens to be our starting point `X`, then it returns a `true`.
If we aren't in an infinite loop at all, reaching the `X` or a `\n` or having an index outside of the string will return a `true` or `false` accordingly.
`r` is the result and is kind of a ternary boolean: as long as it has the value `2`, the algorithm must continue. `0` and `1` are the falsy and truthy values before normalization.
Note:
1. I reused my "wall direction conversion system", and 1-dimensional string indexing from [my JavaScript solution](https://codegolf.stackexchange.com/a/264729/116582).
2. For debugging purpose, we can visualize the path drawn by the cursor (via increase of the ASCII values of the characters) : to do so, move `var t=s.toCharArray()` with a `;` before the `for`, and add `System.out.println(t);` just before the `return`.
] |
[Question]
[
Your regex will receive a string of the form
```
!XX!
#<extra>
```
where `X` is any hexadecimal digit (0-9 and A-F **capital letters only**), and `<extra>` is a character sequence to your choosing. (perhaps something like `0123456789ABCDEF0` could be useful?)
You may use any regex flavour.
Scoring will be calculated as: find regex length + replace length + custom string length. lowest score wins.
Your submission must include which flavour you are using, the find regex, the replace string, and your extra string, all of their lengths, and the total length.
**test cases:**
```
!00!
#<extra>
```
Expected output:
```
!01!
#<extra>
```
---
```
!AC!
#<extra>
```
Expected output:
```
!AD!
#<extra>
```
---
```
!2F!
#<extra>
```
Expected output:
```
!30!
#<extra>
```
---
```
!FF!
#<extra>
```
Expected output:
```
!00!
#<extra>
```
---
[Answer]
# [Perl 5](https://www.perl.org/), ~~58~~ score: 21 + 2 + 17 = 40 bytes
Using PCRE substitution
```
s/(\w)(?=F?.
#.*?\1(.))/$2/g
```
with extra
```
0123456789ABCDEF0
```
[Try it online!](https://tio.run/##K0gtyjH9/79YXyOmXFPD3tbNXo9LWU/LPsZQQ09TU1/FSD/9/39FAwNFLmUDQyNjE1MzcwtLRydnF1c3Ay5FR2fs4kZu2MXdsIv/yy8oyczPK/6va2Bubl4AAA "Perl 5 – Try It Online")
First solution overcomplicated
```
s/(\w)(F)?(?=.
#.*?\1(.).*(?(2)F(.)))/$3$4/g
```
with extra
```
0123456789ABCDEF0F0
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 20 + 2 + 17 = 39 bytes
```
(\w)(?=F*!¶¶.*\1(.))
$2
```
[Try it online!](https://tio.run/##K0otycxL/K@qkaDCdWjboW3KBoZGxiamZuYWlo5Ozi6ubgb/NWLKNTXsbd20FEEK9LRiDDX0NDW5VIz@G7on/Fc0MFDkUjQwBBKOziDCBUgYuQEJY5CEG4gFVAIA "Retina 0.8.2 – Try It Online") Linked test suite automatically adds and removes the extra string.
[Answer]
# [Perl 5](https://www.perl.org/), 3+25+0 = 28
```
s/\w+/sprintf"%02X",1+hex$&&255/e
```
[Try it online!](https://tio.run/##K0gtyjH9/79YP6ZcW7@4oCgzryRNSdXAKEJJx1A7I7VCRU3NyNRUP/X/f0UDA0UuZS5FR2cwZeQGptxA1L/8gpLM/Lzi/7oG5ubmBQA "Perl 5 – Try It Online")
3 chars in `\w+`.
25 in `sprintf"%02X",1+hex$&&255` where `$&` is the found input hex number.
0 extra chars after `#`.
] |
[Question]
[
Write a program that takes two lists of strings and generates a javascript regex that fully matches all the strings in the first list and matches none of the strings in the second list.
To be specific when for all stings in the first list `str.match(/[your-output]/)` must produce a match for the full string and for all strings in the second list `str.match(/[your-output]/)` must produce no matches.
# Scoring
Your score is the average length of the regexes you produce not the length of your program. Your regexes should be tested against this file: <https://pastebin.com/9iNZvGJC>. Take the file in blocks of 20 lines and run your program with the first ten lines to match and the second ten to not match. Average the lengths of your program's output for all of the blocks in the file. This is your score.
# Rules
Do not output the / for the regex
[Answer]
# JavaScript (ES7), Score: 767 / 50 = 15.34
This code is rather ugly and implements only one strategy. (I did try negative lookaheads, but it was not worth the effort and is disabled here.)
It could probably shave off a few more bytes with a higher maximum branching factor and/or a more clever pattern scoring function. For instance, `/.*[LObcln]o.*/` and `/.*(Y|o[otvy]).*/` are better solutions for the first 2 test cases which are currently not found.
The TIO link only includes the first 40 lines.
```
const MAX_PAT_LEN = 2;
const MAX_BF = 8;
const ESC = ".^$*+?()[{\\|";
let list = require("fs").readFileSync(0).toString().split("\n");
let block = [];
for(let n = 0; list[n]; n += 20) {
block.push([list.slice(n, n + 10), list.slice(n + 10, n + 20)]);
}
let score = 0;
block.forEach(([A, B]) => {
let res = process(A, B, false);
console.log(res.length.toString().padStart(2) + " /" + res + "/");
if(
A.some(s => (s.match(RegExp(res)) || [])[0] != s) ||
B.some(s => s.match(RegExp(res)))
) {
throw "Failed";
}
score += res.length;
});
console.log(score);
function process(A, B, neg) {
let chr = [...new Set([...A, ...B].join(''))]
.map(c => ~ESC.indexOf(c) ? "\\" + c : c);
let set = new Set;
A.forEach(s => {
for(let n = 1; n <= MAX_PAT_LEN; n++) {
choose(chr, n).forEach(a => {
let pat = a.join(''),
regex = RegExp(pat);
if(regex.test(s) && !B.some(s => regex.test(s))) {
set.add(pat.toString());
}
});
}
});
function score(A, pat) {
return A.reduce((p, s) => p + RegExp(pat).test(s), 0);
}
let solution = [];
function search(A, expr) {
if(!A.length) {
let c = compress(expr);
solution.push(neg ? "^(?!.*" + c + ").*" : ".*" + c + ".*");
return;
}
let patList = [...set].filter(a => score(A, a))
.sort((a, b) => score(A, b) - score(A, a));
patList.slice(0, MAX_BF).forEach(pat => {
search(A.filter(s => !RegExp(pat).test(s)), [...expr, pat]);
});
}
search(A, []);
return solution.sort((a, b) => a.length - b.length)[0];
}
function choose(list, n) {
let sz = list.length;
let max = sz ** n;
let res = [];
for(let k = 0; k < max; k++) {
let sel = [];
for(let i = 0; i < n; i++) {
sel.push(list[Math.floor(k / sz ** i) % sz]);
}
res.push(sel);
}
return res;
}
function compress(list) {
let maxW = Math.max(...list.map(s => s.length)),
res = [];
list.sort();
for(let w = 1; w <= maxW; w++) {
let subList = list.filter(s => s.length == w);
for(let i = 0; i < w; i++) {
let trunc = {};
subList.forEach(s => {
let key = s.slice(0, i) + s.slice(i + 1);
trunc[key] = (trunc[key] || '') + s[i];
});
Object.keys(trunc).forEach(k => {
let s0 = trunc[k].length + 2 + w,
s1 = trunc[k].length * (w + 1);
if(s0 <= s1) {
res.push(k.slice(0, i) + '[' + trunc[k] + ']' + k.slice(i));
list = list.filter(s =>
s.length != w || s.slice(0, i) + s.slice(i + 1) != k
);
}
});
}
}
list = [...list, ...res];
return list.length > 1 ? "(" + list.join('|') + ")" : list.join('|');
}
```
[Try it online!](https://tio.run/##jVhrc9u4Ff3OX3GlaVekrTD2znRmG6/XI3WdSabZuFOndXds7Q5EQiIsCuASoGUlcf96ei5ASpSbPjRjiwCB@zjn3AvY9@JB2KxWlXuhTS6/jBorybpaZW509iUz2jr6afKPX/8y@fDru8v3dE7fnkX76elrzHzXzVxe/wnDYfrL746OL@Lk9tPd3efhWRSV0lGpsOCcavlbo2oZDxd2mKS1FPlrVcrrrc7ikyR15hqu9TJOUluVysXDOz1MzryBeWmyFSzczmBxYeqYJzUmTs688Vs9O8P4GBGeJPQporAjrRpbxLe8IrWlymSsx7yMTk@SMfWn/Vx4BwszuH0KodvM1NI7iqJgE@4vRVbE8e1kTNNZQuc/eI@8upYWa6vaZNLamN@PaSFKK2EQSxgpU8q0NMsYS9NS6qUr@plXIr92onbxtwlCGdLLIb7YKgYvh8GKWsT4TTRJrVnL2HIAsU3XwiGqv8rl5WPF1pOEPn8GYsntyYwG52R57DdOexu/ti/BqoAikStqs6HhawGmcvBJ9MQxBFiOmdMuDUDG8fVz9Kt4ctHozCmjn0Gj5TLZYZcVNTOcpqmWG7qWLuZnLMTv6Sy9N0rHo1GSzHxc3QfhV3HGmfwTCkyVzuXj1SLOErqg4d0dw5fRK8qSs9aNlSzF1oXHc7Kj1HZcEvVFdsra@v68XwuYOT7uMAKxhTFWxkgBSSU7e2Jvjz9srxLsXuzSGR9kU8ulfMT7lg0sDpSHD4j3C1InrYvB5zff0KBP5sHbJOm5Js47FXnONnuC87CEz1P79NTO8fgpuN/R5wll8jiy1nwtXVNroFjLvEEtxdWYtYZwKoDfy6QLbEwnyU5InhJTNt58W@B9h1LUABIe5WNVdy4BxGDSym6fpRcRbGRmXdUsMr9lh1/nJTQFSI8V8kt8MUiPgkpQYgk/v0IX20/hcQdSSLWDJ@px@i50OFYsgJ6lC1U6WQcB7EATvrKef8Af6j0WY5onB8sxfHGwuU2ldde2LnSt0Iz3svMa2wuvw7ALyktl8BViwAwnwLB5hmedEvZ07fm4nYV4Wvp36D7LRrQ0IZV5xxgaku@vO5bb8uGGzPWzawn2IzD1bbprMWF@LbhI8PboiPTZQe/tBNSW7yqcESv6njfhYV@1oRmU@z37XSrsUtil8dWvdOwIAvLHzk8C7XtRGuxb0cs2IpXQ7/E469UR@T7p98FAC@cOO7x7hkenYHayhwMZ3CAy7xTPMbjy4HALbJt5i/CurRyAEg485ic5AGkTetyGexz7wOMzmJp5K3Bvoq@jziWdn9Mm@c84bp7hyK9djYSx5NPTvkiDp6915G7XSm6Z/L38FR@V3VjxSd7rat7HLfbMsCnujXA2ov3yzls1O@v1vvbxan4vM5dirQ3b9vW1@veg7AnMt9ZnHSS4S@Bnc9ji7elXVh5RvGkD73d7WAUl9vSwk@@ktHqGweh2hN@dbZ6Y8US3TPW7PXWXsueMHgbbBYj7w4Yh@@@w87JVz8D/Ol06UbadM9Q/HpDhrN9cei2AfqBTbtwxN2g/H07Sz57LYcLt@3AapfXlyyRDH81x5JEzJMqSVtpsYFhsLJkFiQcluPLGuO9IXGyUpUgb2ogtCZpL3IoL05Q5HknMS8lGFuU2pbfO0gZWLQnsipwxZNdsHguWXAB4vxB8AXYO2@Ym38Ldgr3QsjaNjvKUPmAAH2MOJDNNbfG4KBUqV@gthzCXmeCrORZZyiOjRzjo2OGmgO2iWQttYVLpFQeu1pWxViHMlH6WZWlYgPNS4Orajf@PYYTxlSnad4gkp61/PaB30o0sEBErAOWoqYARJxixx6mo6@2AprjdrxYC1CIivulj7sqsAdWA3gjQgC4nyEYS10VA8IZNX@CM8Nv5YZKLNX9fCU1b0yB3IPIA5KOCc7RUiKqSGgZ51VvgAVRAyAjgVwoR86amSumdMdGKiUfANcZ/A5AMv3VC1RZJA3HmCLzjzFM5LY3JKVobjT6DisdinE0pXRtExg7WuIpkykkfdi1HtmUzEnkjHFbeyBG4eZD1lq@7Tc68IhrcinA80oQqWS/QWgBLVKEZM5X52ItyOkJAf99tTNHqB8htaRzAYoKXFC0Nf7FKUySO6P3rUmnHmG59Ns3Hj/zyCmR9KETEdK3lADM34sGLt7EDDhMuoWiFEwh3/NPT78YnJye8cRptsdxzMYZ/ZyD9kIEzFSufQ8A2ThyFYdl2BDSwmnljE37gLfDoLYMErXJkKIzSM0xRKAtgW8lMiZJygU3L2gPJdwl6D8o9A82ycMA@j3BAedlx2dQoTGyxfgsY5WtEySW8e1GoZRG1L3gHmKQNF7jYrDaA/cBKZsoSF2hwHIHkZSlyn7uB@nmBr4FC4Y@lQq1kjopH/eYBA/UQSS8lyqEgHN8oVi6bXC0WcKedh0T1EJnULlKSszXcQOBi3UCSWSEvWLIr63UYkBQ1uo5pHL2OaqFXSjJ8P0tR7BXQdjYOBrcIWQsP8XszpogVqyERvyilSxamb0TcAi1z6qsDMUPyY@Y5QtxI50ffaDYoYl/noWL5L/gadyC6brICE4WBT5FHKeu0wZ0F0uQuBsUULLZ7ZMUKdVITp2BC80Nb81tKw4L0Ja3RoVEPwoeDqhcARK6BHcqyRmfTzkTE8gYXzJtgWW@KLQil3IeqJWh5EJkXDypparZofYgYCaCNK@@9wt0KRwyBOy8tRKvqrFkDfI0/TVNW8g3aUZAy1GSYe/jghotwGPMbP@KCmkr5ApORpxQP3N2gorK5F8WArl2TIwHL/wTImtJB3bnyeDcqsoXMfUvHXbuUwiuz9NL5USL9KUoFEyX3Ez8NKt/jr9Y3CohdKbfdFQrgykph@SDjxPDzx1enfwgQRfw/h6xEGNZjl0GNaG2KE51o9r9UODx82@AjBZBEqNM3kMIjvdV5w/8OktwtFJoFUPC9FavvzTxAcwEWI0igziESMOIJN9ikXVvEEHBu0YsHvl@ykaVJI/qzlFVwXKCyrC8voaETLVgNVuWhUbtarAkxiYjPVbX2HNGN8fz5ExB@QycrUZihtbQH7r8A "JavaScript (Node.js) – Try It Online")
### Full output
```
14 /.*(an|la|ts).*/
17 /.*( n|Y|o[otv]).*/
19 /.*(J|ca|go|e[dy]).*/
16 /.*(j|ns|s,|t').*/
19 /.*(ke|wh|i[,dgl]).*/
12 /.*( c|W|p).*/
16 /.*(e'|j|nn|ve).*/
18 /.*(B|T|op|r,|un).*/
12 /.*a[ btuy].*/
16 /.*('s|3|r[ i]).*/
13 /.*(H|ar|po).*/
14 /.*(I |ie|nd).*/
16 /.*(sa|[nrs]\.).*/
17 /.*(Ye|ay|it|wh).*/
13 /.*("|nt|we).*/
16 /.*( f|A|He|am).*/
17 /.*(ce|id|ma|r ).*/
16 /.*(nk|o[bfpw]).*/
13 /.*( r|T|fl).*/
14 /.*(y |[1SW]).*/
18 /.*('l|un|[btw]e).*/
14 /.*(L| [Obe]).*/
15 /.*( p|-|eb|j).*/
13 /.*(H|ma|se).*/
10 /.*[clt]e.*/
15 /.*(G|ne|ry|x).*/
16 /.*(J|S|o[dos]).*/
16 /.*(Al|W|oo|w ).*/
16 /.*(T|j|['cn]t).*/
16 /.*(s\.|r[osy]).*/
18 /.*(E|il|[Inrs]s).*/
16 /.*(S|n'|su|uc).*/
16 /.*( w|s[!emo]).*/
15 /.*(!|K|ea|rr).*/
16 /.*(D|Yo|h,|si).*/
11 /.*[dhlr]i.*/
17 /.*(ll|st| [rv]).*/
15 /.*(!|H|a[ds]).*/
16 /.*( f|F|ic|wa).*/
16 /.*(ev|[abgu]r).*/
17 /.*(ti|ul|[AFS]).*/
16 /.*(ed| [RYly]).*/
14 /.*(ea|a[ b]).*/
18 /.*(Oa|k |['be]l).*/
15 /.*(\? |ni|ot).*/
13 /.*("|al|ta).*/
11 /.*(f |pa).*/
15 /.*(L|Re|W|nk).*/
18 /.*(fl|ly|[enr]t).*/
17 /.*('t|om|[dt]e).*/
```
[Answer]
# Python3, Score: 762/50 = 15.24 in ~30.51 seconds
```
import collections, re, random
def test_data():
with open('inp_d.txt') as f:
while True:
l1 = [j.strip('\n') for _ in range(10) if (j:=next(f, None))]
l2 = [j.strip('\n') for _ in range(10) if (j:=next(f, None))]
if len(l1) < 10: return
yield l1, l2
if len(l2) < 10: return
def substrings(l1, l2):
C = collections.defaultdict(set)
C1 = collections.defaultdict(set)
for I, l in enumerate(l1):
for i in range(len(l)):
for j in range(i+1, len(l)):
L = l[i:j]
if all(L not in k for k in l2):
C[j-i].add(L)
C1[L].add(I)
return {a:sorted(b) for a,b in C.items()}, {a:sorted(b) for a, b in C1.items()}
def to_regexp(k):
return ['', '['+''.join(k[0])+']'][k[0]!=tuple()]+k[1]+['', '['+''.join(k[2])+']'][k[2]!=tuple()]
def full_regexp(regexp):
return regexp[0] if len(regexp) == 1 else '('+'|'.join(regexp)+')'
def merges(d, d1, depth = 2):
for D in range(1, depth + 1):
b = d[D]
results = collections.defaultdict(dict)
for x in range(D+1):
for y in range(x+1, D+1):
for i, a in enumerate(b):
if a[x:y] not in results[(x, y)]:
results[(x, y)][a[x:y]] = [i]
else:
results[(x, y)][a[x:y]].append(i)
for (x, y), vals in results.items():
for base, options in vals.items():
for i, a in enumerate(options):
queue = [(options[i+1:], {*b[a][:x]}, base, {*b[a][y:]}, d1[b[a]])]
while queue:
r_options, l, base, r, o = queue.pop(0)
yield (tuple(sorted(filter(None, l))), base, tuple(sorted(filter(None, r)))), o
if r_options:
queue.append((r_options[1:], l, base, r, o))
n_b = b[r_options[0]]
if any(j not in o for j in d1[n_b]):
queue.append((r_options[1:], {*l, n_b[:x]}, base, {*r, n_b[y:]}, {*o, *d1[n_b]}))
def solutions(l1, l2, depth = 2):
d, d1 = substrings(l1, l2)
merge = dict(merges(d, d1))
scores = collections.defaultdict(dict)
for a, b in merge.items():
T = to_regexp(a)
if tuple(b) not in scores[10 - len(b)]:
scores[10 - len(b)][tuple(b)] = [T]
else:
scores[10 - len(b)][tuple(b)].append(T)
new_scores = {}
vals = []
for a, b in scores.items():
subscores = {}
for j, k in b.items():
subscores[j] = min(k, key=len)
vals.append((j, min(k, key=len)))
new_scores[a] = subscores
def contains(j, k, nj, nk):
if nj == nk:
return False
return all(J in nj for J in j) and len(k) > len(nk)
scores = {a:{j:k for j, k in b.items() if not any(contains(j, k, nj, nk) for nj, nk in vals)} for a, b in new_scores.items()}
r_score, r_regexp = None, None
queue = [(score, {*vals}, [regexp]) for score, container in sorted(scores.items(), key=lambda x:x[0]) for vals, regexp in container.items()]
seen = []
while queue:
score, vals, regexp = queue.pop(0)
if r_score is not None:
if len(full_regexp(regexp)) >= r_score:
continue
if not score:
if r_score is None:
r_score, r_regexp = len(T:=full_regexp(regexp)), T
elif len(T:=full_regexp(regexp)) < r_score:
r_score, r_regexp = len(T), T
continue
remainder_vals = {*range(10)} - vals
full_options = []
for score, options in scores.items():
for _vals, r_o in options.items():
if any(i in remainder_vals for i in _vals) and len(r_o) <= len(regexp[-1]) and tuple(P:=sorted(regexp + [r_o])) not in seen:
if r_score is None or len(full_regexp(regexp + [r_o])) < r_score:
full_options.append(({*_vals} - {*vals}, _vals, r_o))
for _, _vals, r_o in sorted(full_options, key=lambda x:len(x[0]), reverse=True)[:5]:
seen.append(tuple(P:=sorted(regexp + [r_o])))
queue.append((len(remainder_vals - {*_vals}), {*vals, *_vals}, regexp + [r_o]))
return r_score + 4, '.*'+r_regexp+'.*'
if __name__ == '__main__':
import time
T = time.time()
s, c = 0, 0
for l1, l2 in test_data():
a, b = solutions(l1, l2)
s += a
c += 1
print(b)
print(time.time() - T)
print(s, c, s/c)
```
Rather long solution, but more optimized for speed and regexp length minimization.
] |
[Question]
[
## Background
[Supplementary reading 1](https://blog.functorial.com/posts/2017-08-05-Embedding-Linear-Lambda-Calculus.html), [Supplementary reading 2](https://doisinkidney.com/posts/2020-10-17-ski.html)
Linear lambda calculus is a limited form of lambda calculus, where every bound variable must be used exactly once. For example, `\a b c d e -> a b (d c) e` is a valid term in linear lambda calculus. When embedded as a logic system, this enforces each input to be consumed exactly once. The equivalents in logic/type/language theory are called linear logic, linear type, and linear language respectively.
Ordered lambda calculus is a more limited version: it requires the variables to be used in the order they are introduced. `\a b c d e -> a (b c) (d e)` is such an example.
Affine and relevant lambda calculi are relaxed versions of linear lambda calculus.
* Affine: each variable must be used at most once. `\a b c d e -> a (d c) e`
* Relevant: each variable must be used at least once. `\a b c d -> a (c b) (d c)`
If omitting and duplicating a variable are both allowed, we get plain lambda calculus.
These have interesting relationship with BCKW combinator calculus:
* Ordered lambda calculus can be represented using just B and I combinators. (I is needed to represent `\a -> a`.)
```
\a b c d e -> a (b c) (d e)
\a b c d -> B (a (b c)) d
\a b c -> B (a (b c))
\a b -> B B (B a b)
\a -> B (B B) (B a)
B (B (B B)) B
```
* Linear lambda calculus can be represented using B and C combinators. (I is equal to BCC, and is used only for simplicity.)
```
\a b c d e -> a b (d c) e
\a b c d -> a b (d c)
\a b c -> B (a b) (C I c)
\a b -> B (B (a b)) (C I)
\a -> C (B B (B B a)) (C I)
C (B C (B (B B) (B B))) (C I)
```
* Affine lambda calculus can be represented using BCK. K allows to delete unused variables.
```
\a b c d e -> a (d c) e
\a b c d -> a (d c)
\a b c -> B a (C I c)
\a b -> B (B a) (C I)
\a -> K (B (B a) (C I))
B K (C (B B B) (C I))
```
* Relevant lambda calculus can be represented using BCW. W allows to duplicate variables.
```
\a b c d -> a (c b) (d c)
\a b c -> B (a (c b)) (C I c)
\a b -> W (\c1 c2 -> B (a (c1 b)) (C I c2))
\a b -> W (\c1 -> B (B (a (c1 b))) (C I))
\a b -> W (C (B B (B B (B a (C I b)))) (C I))
...
```
* BCKW forms a complete basis for the plain lambda calculus.
## Challenge
Given a lambda term in the format below, classify it into one of five categories (ordered, linear, affine, relevant, none of these). The output should be the most restrictive one the input belongs to.
The input is a lambda term that takes one or more terms as input and combines them in some way, just like all the examples used above. To simplify, we can eliminate the list of input variables, and simply use the number of variables and the "function body", where each variable used is encoded as its index in the list of arguments. `\a b c d e -> a b (d c) e` is encoded to `5, "1 2 (4 3) 5"`. (Note that it is different from de Bruijn indexes.)
The function body can be taken as a string or a nested structure of integers. The "variable index" can be 0- or 1-based, and you need to handle indexes of 10 or higher.
For output, you can choose five consistent values to represent each of the five categories.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
length, "body" (lambda term it represents) => answer
1, "1" (\a -> a) => Ordered
2, "1 2" (\a b -> a b) => Ordered
2, "2 1" (\a b -> b a) => Linear
2, "1" (\a b -> a) => Affine
2, "2 (1 2)" (\a b -> b (a b)) => Relevant
2, "1 1" (\a b -> a a) => None
3, "1 3 (2 3)" (\a b c -> a c (b c)) => Relevant
4, "1 3 (2 3)" (\a b c d -> a c (b c)) => None
10, "1 (2 (3 4) 5) 6 7 8 (9 10)" => Ordered
10, "5 (2 (6 10) 1) 3 7 8 (9 4)" => Linear
10, "5 (2 (6 10) 1) (9 4)" => Affine
10, "1 5 (2 (3 6 10) 1) 3 7 8 (10 9 4)" => Relevant
10, "1 (2 (4 10) 1) 5 (9 4)" => None
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 15 bytes
```
F⁻ȧċⱮɗR}Ṃ;ṀƊ«Ø½
```
[Try it online!](https://tio.run/##y0rNyan8/9/tUePuE8uPdD/auO7k9KDahzubrB/ubDjWdWj14RmH9v5/uHOf9aOGOQq6dgqPGuZaH16uDxTRebij5eHu7kNLT04HyjmmpWXmpQIZfvlgygfISywCMoJSc1LLEvNKgEwg8i9KSS1KTQGakgUyUAPIOLYJaPZcTa7D7Y@a1kT@/x/NFW2oo2AYq8MVDWIYxYIxkGMEFoVwDJEEIRy4MkMkZSCOMVAFUJUxSIUxNkETmCDYMGOwgIIpEJvpKJjrKFgABS2BZhqA1AJJkGJTqGIziAjYQmNk1SYEFKOrAdpuinAAdmMNDXQUMLWB9ZggaTBFNZ0rFgA "Jelly – Try It Online")
A dyadic link taking a nested list of integers on the left and the number of parameters on the right. Returns the following:
```
[0,0] - Ordered
[0,1] - Affine
[0,2] - None
[1,1] - Linear
[1,2] - Relevant
```
The TIO footer adds textual representations of each answer as well.
## Explanation
```
F ɗR} | Using the flattened list of integers as the left argument and a range of 1..n as the right argument:
⁻ | - Not equal
ȧ | - Logical and
ċⱮ | - The count of each of 1..n in the flattened list
Ṃ;ṀƊ | Min concatenated to max
«Ø½ | Min of [1,2] and this (vectorises, so 1 is matched to the min and 2 to the max)
```
Note this is similar (though not identical) to my R answer, if that helps in understanding it.
[Answer]
# JavaScript, 71 bytes
```
a=>g=i=>i&&(h=j=>~a.flat(1/0).indexOf(i,-j),h(p=h())?5:p?i<-p:3)|g(i-1)
```
[Try it online!](https://tio.run/##hZBPa4MwHIbv/RQ9lQR@/okx3dY2lt3HCrsWD6EmGhEVK2WHsa/uTGmZM9bdn/d5X95cXMT51Oi6dcoqkZ3ineBRyjWP9GqFMp7z6Fu4qhAtIp6PXV0m8vOgkAYnx5ChmmcI4z3b1Hu9c@oNxV8p0g7B3akqz1Uh3aJKkUJHEmNEMN4uPW95aBLZyGQxRiDooWAeCoAMoDddStEsJrruxKtSPWNbrm0D7kMW8iLK1h41tL1XtosAhV5IjY3@a/tlw1mnmUghjIHFsIYneIbjCxDfBIk/fxG7hteG7sf3jbd0@Cc8fd0oa6Wm7yTAboPHrcSHseLxN0YR3gXMLjdPdT8 "JavaScript (Node.js) – Try It Online")
Input a nested integer array (1-indexed), and the number of operand. Assume the input is always valid. Output a number.
* 0 - Ordered
* 1 - Linear
* 3 - Affine
* 5 - Relevant
* 7 - None
[Answer]
# [R](https://www.r-project.org/) >= 4.1, 81 bytes
```
\(x,n)identical(u<-unlist(x,T),r<-1:n+0)+pmin(1:2,range(sapply(r,\(y)sum(u==y))))
```
[Try it online!](https://tio.run/##hZHBboQgEIbvPgXxBNkxEdFtu9G36M31YLdoSFxqQJr69HbArrXtJiVhMvPnm38IY5aOlMnSOX2Z1JumH6CZepV6Upd2oK5MnB6UnVB/ZmDKhJ/0IWWH8ao05acMTKt7SW07jsNMDWw@M7PuSl1VzQzPInuLY4h8R9OxNVbSqeqte6Hx@VzHQOIwBJOb2HiR@VBHNQfCG4hqn2RNuFhkQV0LvhPXYsP4DvOFQAIp4QlxT8xvYjATQSAF3iOQByCPKD6hZ@pZjB4uvuDjqoSBYk/n/8C/GZxefD/gvi1PgfxtCz35rqH46R41sd9INKwrw8UA2bYme0Y6jOjkcZ/gT@L@PgE "R – Try It Online")
A function that takes a nested list of integers `x` and the number of parameters `n`. Returns a length 2 vector:
```
[0,1] - Affine
[0,2] - None
[1,1] - Linear
[1,2] - Relevant
[2,2] - Ordered
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
≔I⪪ΦS›@ι θ≔EN№θιη¿⁼θEηκO¿⁼¹⌈η§AL⌊η¿⌊ηR
```
[Try it online!](https://tio.run/##TY7LTsMwEEX3/Yorr8ZSkGqerdgQVQVVooDoMsrCFNNYddwktlH/3tii0KxGOnPu3Nk2ctgepImxdE7vLC2k87TpjPb0qI1XA61sF/zGD9ruiBd4GpTMmD2wAponwsDy6Pn95HRkLbvf2EtoP5KbtotDsJ76U6RJrv4CLfsgjcs4R5oCe8453lKXJ/bKkqWMUxipIqtH3YaWmrNb@pX9VEdi5XP6aq3tvzC6MMJ/Fe@pIsYbVJeobiGmNUSNK9xhhmqO6xrTiRDx4tv8AA "Charcoal – Try It Online") Link is to verbose version of code. Takes the string (with `[]` delimiters) as the first input and the number of 0-indexed variables as the second input. Explanation:
```
≔I⪪ΦS›@ι θ
```
Input the string, filter out the `[]`s, split on spaces, and cast to integer.
```
≔EN№θιη
```
Count the number of occurrences of each variable.
```
¿⁼θEηκO
```
If the flattened list of terms equals the list of variables then output `O`, otherwise...
```
¿⁼¹⌈η§AL⌊η
```
... if there is at most one of each variable then output `L` if there is (at least) one of each variable or `A` if there is at least one missing variable, otherwise...
```
¿⌊ηR
```
... if there is at least one of each variable then output `R` otherwise output nothing.
] |
[Question]
[
Suppose you have a string \$s\_0\$ and someone else has a hidden string \$s\_1\$. You don't know what \$s\_1\$ is but they tell you that they can get from your string, \$s\_0\$, to their string by making a certain number of moves \$d\$. Each move can be one of the following:
* Insertion : Add a character anywhere in the string
* Deletion : Remove a character from anywhere in the string
* Replacement : Replace one character with another anywhere in the string
* Transposition : swap any two adjacent characters.
(this is [Damerau-Levenshtein distance](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)).
The question is how many moves do you need to get from \$s\_0\$ to \$s\_1\$ *without using the transposition move* (this is [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance))?
Your task is to write a program or function that takes a string (list of positive integers is fine too) representing \$s\_0\$ and a positive integer representing \$d\$ and output the minimal number of moves required to guarantee you can get to \$s\_1\$ without transposition in the worst-case scenario.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") your answer will be scored in bytes with fewer bytes being better.
# Test cases
## Using Strings
```
"Hello", 3 -> 4
"World", 2 -> 4
"aaaaa", 1 -> 1
"aaaaa", 2 -> 2
"abaaa", 3 -> 4
"Krypyp", 3 -> 5
"", 5 -> 5
"Hello", 0 -> 0
```
## Using Integer lists
```
[1,2,3,3,4], 3 -> 5
[1,2,3,4,5], 2 -> 4
[1,1,1,1,1], 1 -> 1
[1,1,1,1,1], 2 -> 2
[1,2,1,1,1], 3 -> 4
[1,2,3,4,3,4], 3 -> 4
[], 5 -> 5
[1,2,3,3,4], 0 -> 0
```
[Answer]
# [Haskell](https://www.haskell.org/), 186 bytes
```
-- f :: [Int] -> Int -> Int
f s k|let a=pure<$>0:s;d#(x:z)|let w(y:z)|d>0=[y:x:z];w _=[]=[c++y++z|c<-[]:a,y<-[]:[[x]]]++w z++map(x:)(d#z);_#_=a;d%i=iterate((++)<*>((d#)=<<))[s]!!i=[i|i<-[k..],all(`elem`0%i)$1%k]!!0
```
Simple brute force solution. `f` takes a list of positive integers, and the DL-distance `k`.
This generates all strings up to the DL-distance limit `k`, and searches for the smallest L-distance that contains all of those strings (also by generating those strings). This saves bytes by using the same generator code for both types of distances.
[Try it online!](https://tio.run/##bY9Ra4MwEMff9ymutIVkSYvV9kWN73sY@wAh2KDpFkxdMY5W8bPP3dwYFpY7yP3vl/sfedO@Ms6N4wk8VIMzLWhx@WhMusqC2Cflktzink7gSrrvsswCIbsY2yq5Qi6kErJgrGOsH4p0I1WseTfdUt6UUoxdoWfsrC9oRUm57GmSL3Ohk3JthW1No1tDCGM0fcwIcirSlFLp1WJhhbSDRbNqu1VcO0eOxpnzMVhbutqtK3wSjGdtaxCAC55zuDS2bkEC8XEsn@pWcag4kOl7HPy7qymFATH/05BuQD4AHiJ3POQRxh7nQg4R5Xdgzw8/YD8Dv4Fgh/kvwIlwboWtaG6C@oBJJ6nU@FmcnH714@Yl/AI "Haskell – Try It Online") Note that this is too slow for some of the test cases, so the TIO version uses reduced test cases.
### Pregolfed
Ungolfed version. Unlike the golfed version, this one removes duplicate strings during the generation, so it's also much faster:
```
import qualified Data.Set as S
import Data.List (sortBy)
import Data.Ord (comparing)
snub x = S.toList $ S.fromList x
f' s k =
let -- 0 = any other symbol not in s
alphabet = snub $ toEnum 0 : s
-- all strings with L-distance 1 (if d, DL-distance)
gen1 d s@(x:xs) = snub $ del ++ ins ++ sub ++ swap xs ++ map (x:) (gen1 d xs)
where del = [xs]
ins = map (:s) alphabet
sub = map (:xs) alphabet
swap (y:ys) | d = [y:x:ys]
swap _ = []
gen1 _ _ = map (:[]) alphabet
-- as gen1, but distance <= i
genAll d i = iterate (\x->snub $ x ++ (gen1 d =<< x)) [s] !! i
-- strings with DL-distance <= k
sDL = S.fromAscList $ genAll True k
in head [ (i, worstStrings)
| -- sL = genAll False i
-- zip obtains sL' = genAll False (i-1) for calculating worstStrings
((_, sL'), (i, sL))
<- zip <*> tail $ (,) <*> (S.fromAscList . genAll False) <$> [max 0(k-1)..],
-- require that sL covers sDL
sDL `S.isSubsetOf` sL,
-- also show some maximal examples
let interestingness t = length (filter (==toEnum 0) t) + abs (length t - length s)
worstStrings =
take 5 $ sortBy (comparing interestingness) $
S.toList (sL `S.intersection` sDL `S.difference` sL')
]
```
[Try it online!](https://tio.run/##fVRNj9MwEL33VzxWK2GzacWCuFTNCtDChaI9lFuJdt3G2Vp1Psi4NEX8dsrYSbtNF@FL4vGb92bG41kpWmtr93uTV2Xt8GOjrMmMTnGrnBrNtIMizAbdcTBODTkI4v3Hneyd3NUpxLLMK1Wb4lEOBlRsFmgQYzZyZfC75N@sLvOwaQaD7CUIa8QDwLLYcIjXDFfFDqVb6Rq0yxelRVE6mALEML@UrVZqwfgYQeISrvxUbHJ2Hh9BzKWsBTkfDGFr3ArTYcrCqlhqXEOYDGmE2yej7FwfdXGNFPReNOOG5JNMqi2urjgU8h9im/9sVYUmWHL@Yx8J0VGwd8cJbDkhHShizBtKjgft8qRxyzBmzUOOZyiveUA1/4H5mMRuvGPIb46DFXfjhrfJv4D3/jw5Tf4@2FqZefJMxteWAjLCYuNwrOokhnni@cD1T2GYyThdK6chvjfDm66Yja/YoVDxZIJGSswpwYsXRxIW6l3gyWV5rXUHo9tp6DLfWh9o2bVaF8G3eqMDkjtopVWKOV99hG1Zk5u15PKkKr@DqOfr/D8rS/oY0TGuX6ZCuXDK3xtNX57jhRleS2RljaWyy41VjoV6oj1CIe4jTyOjEBxNpTy7qUkrOXl1Axa1nJ@IZNiKfuKjXiAMubzBPFcNXos1xzQaJdF5LrX@sTHcnG6lnM99Wf7UNfmy9pC@zA@zkaHZZkHa3WUPDH5GxqolaFVuQWWuuYkakysL3ai8srqftn/0puDm0OTrU2gi@GdtdfHI1y0yY/kQIo4PL1zCSVxBLQiiQ/HcODjQedXQK3kYNOfLqbXGO65nO9NORth5aBKX//A/DjdBbXm8E@mlM2XxcKhZarKMqbhvH8I193iSfc5t1D64r/eoWNv5LqUI6wjtjPTvOBik74R58BcXK57e5UWEtzLqLJyuTdny5mhRfrHl@pnlBLNoLQee4VBcfKl31a7qkfPmXRt6kuz/LDOrHmk/vHvzFw "Haskell – Try It Online") This uses the full testcases but `Krypyp` still times out on TIO (it takes a few minutes to solve). Also, it prints some of the strings that have maximal Levenshtein distance. Testcase solutions:
```
"hello", 3 -> 4 e.g. "eeeol","eehol","eeool","ehheo","ehhho"
"world", 2 -> 4 e.g. "owrdl"
"aaaaa", 1 -> 1 e.g. "_aaaa","a_aaa","aa_aa","aaa_a","aaaa"
"aaaaa", 2 -> 2 e.g. "__aaa","_a_aa","_aa_a","_aaa","_aaa_"
"abaaa", 3 -> 4 e.g. "aabbb","aab_b","aabb_","_aabab","_aabba"
"Krypyp", 3 -> 5 e.g. "rKyKppy","rKyppKy","rKyppry","rpKyppy","r_Kyppy"
"", 5 -> 5 e.g. "_____"
```
[Answer]
# Java 11, ~~790~~ ~~764~~ 760 bytes
```
import java.util.*;t->n->{var S=new HashSet<String>();int m=n;for(;m>0;)p(S,"",t+"x".repeat(m--));for(var s:(HashSet<String>)S.clone())for(m=s.length()-n;m-->1;)S.add(s.substring(m));S.removeIf(s->d(1,s,t)!=n);for(var s:S)m=Math.max(d(0,s,t),m);return m;}void p(Set S,String p,String s){int l=s.length(),i=0;if(l<1)S.add(p);for(;i<l;)p(S,p+s.charAt(i),s.substring(0,i)+s.substring(++i));}int d(int f,String s,String t){int l=s.length()+1,L=t.length()+1,d[][]=new int[l][L],i=l,j,c,q,A,B;for(;i-->0;)d[i][0]=i;for(j=0;++j<L;)for(d[i=0][j]=j;++i<l;B=t.charAt(j-1),c=A==B?0:1,d[i][j]=q=Math.min(Math.min(d[i-1][j]+1,d[i][j-1]+1),d[i-1][j-1]+c),d[i][j]=f>0&i>1&j>1&&A==t.charAt(j-2)&s.charAt(i-2)==B?Math.min(q,d[i-2][j-2]+c):q)A=s.charAt(i-1);return d[l-1][L-1];}
```
Will golf it down (substantially I hope) from here.
[Try it online.](https://tio.run/##fVTNjpswEL7vU7gcIrsYFlL10CVQZQ/VrpqVKnHogXJw@NmYGkOwk260ynUfoI/YF0nHhKRsWhUJMz/fzDcztqnYljlV/v3A67bpNKpAdzeaC/dtgND1NfrCwNqUSK8KtNzpwsmajdQI2/6HXlfkKhNMKfTAuHy@QqMM5UZmmjfS/TQIs1h3XD7S/2LupS4ei46iQYgiVKLwoJ1IOtHzlnUoDmXxA90xtYoLPeSMMAk41FWHMiibDgd15AWkxTG1LKpt68lyu6ItmMa14xDSY0wudYMvEpHYzUQjC0yIAdWhckUhH/UKE0cGEB35AWBYnmPlqs1S9WG4hqQxcNTNtrgvsXKiHPtUUU3ehHLMF5M6fGB65dbsCefY6zG0JkFX6E0nUR3sg23DcwTFFxrF9FgXak@CIs@mUzEqjPLQC3iJxcwfSmuPlAGfieMYWlu52Yp1c405oePKPcqJPTbYNodm9oYkx2Ytz9QnQf9dg@3TRajHap6kSdrvFWATkSaLFAoVtKIZXdM5vR1KhJHCXuUJTxMvDXlvraAh265mi6DfBXCGXppUaViB2TR1C1xDP5XjE5qF8zC8/ejdGF7eQ9fDnLnEZwF8jm@89gkHqg3xJ4dRM3LOUUbehEf@pIJ3Agwj0imZ/BkpaIb@zLPuE05NwqlJeLMm83AE98/7nSfCEC9gCfYHhNrNUvAMKc00fPqTUMPVwsfJJylixFwzhODuaWzdFUI0Fn1HgpHxa9OJ3KLTV0ZmHov6/zJeIJe98XXOz92u3bWXVou@vwiF2OUlaijS6437K1jG7fWY8wkz50oOLcY7pYvabTbabcGthcTWN8uylQ0fxGSOLFvaFvr18tNIcNLMXwgTt3RZ24odVmQQJBm494ff)
### Explanation:
**General approach:**
Input-String = `t` and input-integer = `n` in the explanation below.
1. Generate all permutations of `t` with up to `n` added characters, and add them to a Set
2. For each permutation, add a substring with up to `n` removed characters to the Set as well
3. Remove any String from this Set that does not have a Damerau-Levenshtein distance of `n` in comparison to `t`
4. Calculate the Levenshtein distance of each remaining String in comparison to `t`
5. Take the maximum, which is our result
**Code explanation:**
```
import java.util.*; // Required import for the Set and HashSet
t->n->{ // Method with String and integer parameters and integer return-type
var S=new HashSet<String>(); // Create a String-Set
int m=n;for(;m>1;) // Loop `m` in the range [input-integer, 0):
p(S,"",t // Determine all permutations of the input-String
+"x".repeat(m--)); // With up to `m` additional "x" added
for(var s:(HashSet<String>)S.clone())
// Loop over all generated permutations:
for(m=s.length()-n;m-->1;) // Inner loop `m` in the range [permutation-length - input-integer, 1]:
S.add(s.substring(m)); // Add the permutation with the first `m` characters removed to the Set as well
// (NOTE: After these loops, `m` is 0 which we'll re-use later on)
S.removeIf(s-> // Now remove any permutation from this Set which:
d(1,s,t)!=n); // Does not have a DL-distance equal to the input-integer
for(var s:S) // Loop over all remaining Strings:
m=Math.max(d(0,s,t),m); // Determine the maximum L-distance
return m;} // And return that maximum L-distance as result
// Separated recursive method to get all permutations from a String
void p(Set S,String p,String s){ // Method with Set and two String parameters and no return-type
int l=s.length(), // Get the length of the input-String `s`
i=0; // Index-integer `i`, starting at 0
if(l<1) // If the length is 0:
S.add(p); // Add the prefix-String `p` to the Set
for(;i<l;) // Loop `i` in the range [0, length):
p(S,p+s.charAt(i), // Append the `i`'th character to the prefix-String `p`
s.substring(0,i)+s.substring(++i));}
// Remove the `i`'th character from the String `s`
// And do a recursive call
// Separated method to determine the DL or L distance of two Strings
int d(int f,String s,String t){ // Method with integer and two String parameters and String return-type
int l=s.length()+1, // Length `l` of the source-String + 1
L=t.length()+1, // Length `L` of the target-String + 1
d[][]=new int[l][L], // Create an integer matrix of those dimensions
i=l,j, // Index-integers
c,q,A,B; // Temp integers
for(;i-->0;) // Loop `i` in the range (`l`, 0]:
d[i][0]=i; // Set the `i,0`'th cell to `i` in the matrix
for(j=0;++j<L;) // Loop `j` in the range [0, `L`):
for(d[i=0][j]=j; // Set the `0,j`'th cell to `j` in the matrix
++i<l // Inner loop `i` in the range [0, `l`):
; // After every iteration:
B=t.charAt(j-1), // Set `B` to the `j-1`'th character of the target-String
c=A==B? // If the characters `A` and `B` are the same:
0 // Set `c` to 0
: // Else:
1, // Set `c` to 1
d[i][j]= // Set the `i,j`'th value to:
q=Math.min( // The minimum of:
Math.min( // The minimum of:
d[i-1][j]+1, // The `i-1,j`'th value + 1
d[i][j-1]+1), // And the `i,j-1`'th value + 1
d[i-1][j-1]+c), // And the `i-1,j-1`'th value + `c`
d[i][j]= // Then, set the `i,j`'th value to:
f>0 // If the given DL-flag is 1
&i>1&j>1 // And both `i` and `j` are at least 2
&&A // And the character `A`
==t.charAt(j-2)// equals the `j-2`'th character in the target-String
&s.charAt(i-2) // And the `i-2`'th character in the source-String
==B? // equals the character `B`:
Math.min( // Set the `i,j`'th value to the minimum of:
q, // The `i,j`'th value
d[i-2][j-2]+c) // And the `i-2,j-2`'th value + `c`
: // Else (the given DL-flag is 0):
q) // Leave the `i,j`'th value the same
A=s.charAt(i-1); // Set `A` to the `i-1`'th character of the source-String
return d[l-1][L-l];} // Return the `l-1,L-1`'th value as result
```
] |
[Question]
[
Using FTP's ASCII mode to transfer binary files is a bad idea. It is likely to corrupt your data. Badly. Let's simulate this corruption!
Your task is to write a program which takes a file as input and outputs the corrupted version of the file. Because how exactly your file gets corrupted is dependent on both the FTP client and server and their systems/implementations, for this challenge, we will use the following rules for corruption, in this order:
* Clear the high bit in each byte of the file. (Masking with 0x7F is an option here)
* When encountering escape (0x1b) followed by `[`, delete from the escape character through the next letter character (`A`-`Z` and `a`-`z`), inclusive.
* Escape followed by any other character should remove both the escape and the character following it.
* All control codes (characters in the range 0x00-0x1F, inclusive, and 0x7F) other than tab (0x09) and linefeed (0x0a) should be removed.
## Other rules
* Input and output can be in any convenient format. You do not need to use actual files.
* Shortest code wins, of course.
* Standard rules and loopholes apply.
[Answer]
# [Perl 5](https://www.perl.org/), ~~62~~ 53 bytes
```
y/\x80-\xff/\0-\c?/;s/\e(\[.*?[a-z]|.)|[^\t\n -~]//gi
```
[Try it online!](https://tio.run/##K0gtyjH9/79SP6bCwkA3piItTT8GSCfb61sX68ekasRE62nZRyfqVsXW6GnWRMfFlMTkKejWxerrp2f@/394@uHt//ILSjLz84r/6xYAAA "Perl 5 – Try It Online") No, I don't know how to input nonprinting characters, particularly illegal UTF-8 sequences, into TIO. Edit: Saved 10 bytes thanks to @NahuelFouilleul.
[Answer]
## x86 assembly, 85 bytes
Bytecode:
```
8d0c244289deb00331dbcd803c0175418024247f8a042401f375203c1b0f94c374e23c09740c3c0a
74083c1f7ed83c7f74d4b00431db43cd80ebcb3c5b75014380e3fe0c203c617cbb3c7a7fb731dbeb
b3b001cd80
```
Source (with explanation in comments):
```
.section .text
.globl _start
_start:
leal (%esp), %ecx # read to (%esp)
incl %edx # read one byte
loop:
movl %ebx, %esi # save previous %ebx
loopnosave:
movb $3, %al # read
xorl %ebx, %ebx # stdin
int $0x80
cmpb $1, %al # exit if we didn't get exactly one byte
jne quit
andb $0x7f, (%esp)
movb (%esp), %al # moving byte into %al saves bytes later on
addl %esi, %ebx # restore previous value of %ebx (currently 0)
# we use add instead of mov here to update flags
jnz ignore # check if we're in the middle of an esc-sequence
cmpb $0x1b, %al # check for esc
sete %bl # if it is esc, set the "ignore" flag...
je loop # ... and skip the output
cmpb $0x09, %al # explicitly output tabs and newlines
je out
cmpb $0x0a, %al
je out
cmpb $0x1f, %al # don't output control characters
jle loopnosave
cmpb $0x7f, %al
je loopnosave
out:
movb $4, %al # write
xorl %ebx, %ebx
incl %ebx # stdout
int $0x80
jmp loopnosave # we clobbered %ebx, so we don't want to keep it
ignore:
cmpb $'[', %al # check if it's [
jne ok # skip next instruction if not
incl %ebx # set %ebx to anything but 1
ok:
andb $0xfe, %bl # clear lowest bit on %ebx
orb $0x20, %al # uppercase to lowercase
cmpb $'a', %al
jl loop
cmpb $'z', %al
jg loop
xorl %ebx, %ebx # clear ignore flag if letter found
jmp loop
quit:
movb $1, %al
int $0x80
```
[Try it online!](https://tio.run/##fVVtT9swEP7uX3EaoGwSzVoK20Bov2MbSMh2Lq1X185shxq0/87OTmgcNi1SmuZennvuzRHcb18kD/CV1x5ubyu0bfVSe5RBWQN1wBhYvdFWaHjwgbvA2PC8YUCXRq7h/Rn67sM5nKGMACfgkDcQ7CjPdspITfomwvEa7axBEE8BGdPWdgPq3j4maxETpleDteePCJ3DR2V7n7XZw9ikOPoJOF2TF7Eqo2RttG5CFXFEDY0yI8UAp8v4Zcnyq9x3hLWaY2FUAVQLB4RGNaYKsMFAUi6DfppSScY/6eVXrwKbmB3rlBFPklCZTXZJ0W1WpGx8lnnQPKAj2AzBTSMSwc/tkRNBcL@bApD4/LXqg0/T6FzCMmWHPlhX1PKR6x7BtoPNe9k7hyYltBya94/rJJWg95giEHcfcivbRAO2SOCUTd81xB9azTd@LMkzqI1JsSccuUW5G2pauVQHCFuEvSLmmRM3gF4uPP7q0Ugsm7OMK1HUYkBqrUsO2cwjxT8TekacQqUm@mR1nkxywHcDsXeZbl3XA2GENGLzxEmZegF@p7rsavvQ9WFObHldEMPYaSVVHpFsC4ELn0EMHrQy6F/DkX6OwzNOqZ4XoByGxqaJHENIa4KzmqrCHY0nujGGHnIa1maGNQ5WmfloxQiz3LDL@VYcnBqH/s2KlasvZqtPa/ea6pu9@7nvitDTsEk6gwRNVjPie5u3MKd84IRBE7dD7CCt3NDMmyK96q6aSBdTp0Ll4e64sXb3Zsxzlw2dgnnKXT@ci@RobPhPejRVWUakuHkK27zn1JUVs7ub2Tq3eP46okSLzlNH6R9oRUHQmFKsYyGtyw4XyzKRvuvQSe7zxiXH/FImzquirTrXtlQ/l@rNpP7naTnwG3c4bUqqhMaQjqnW9qaZtZCxdACWg7OaYh3b/kKfHMa4h8VifQHpM7SgotWW6QYWe9Ttg1p/@ZQkWcEYyq2Fr4q4h1Sm@9he3ke8ouc6/SfBckX3Bd0kWF7TzekWcI@rizX9fvv@g37v6OXyKj49k8O1uI@NIAEXshojbDE2PWVCZ5AyXVqAGOmsy8q/LIalu2H1Rw63Cn4D2b78AQ) (with testcases)
Overview / general explanation:
* The program reads one byte at a time. `%al` holds the input byte, `%ebx` holds a flag that gets set when an ESC character is encountered. Since we need `%ebx` to call `sys_read` and `sys_write`, `%esi` is used as a temporary storage space for its previous value.
* The `%ebx` flag is `0` ordinarily, `1` if the previous character was ESC, and `2` or greater if an `ESC[` was found. On every loop, the program first tests if the flag is zero. If it is, we either set the flag (if the next character is ESC) or print the next character and move on.
If it's nonzero, we don't print the character, but instead unset the least significant bit of the flag. This has the effect of zeroing it if it's `1`, but it will remain nonzero if it's any other positive integer (signifying a preceding `ESC[`). Then we set it to zero (by xoring it with itself) if the current character is a letter, terminating the `ESC[` sequence.
* One trick I'd like to point out: it's a little miraculously convenient that the file descriptor for STDIN happens to be `0`. This allows us to postpone moving `%esi` back to `%ebx` until the first time we have to check the flag, which happens to be checking whether it's zero. A `movl` instruction would not update flags, but `addl` does, and since `%ebx` was previously set to zero to read from STDIN, the add instruction happens to be equivalent.
* Uses many of the same tricks as in [my cat program](https://codegolf.stackexchange.com/a/178108/3808).
[Answer]
## 16/32-bit x86 assembly code, 47 bytes
Bytes:
```
AC247F3C7F74253C0974203C0A741C3C1B7514497418AC3C5B7511497410AC24DF2C403C1A77F43C1F7601AAE2D2C3
```
Disassembly:
```
l1: lodsb ;fetch a byte
and al, 7fh ;clear bit 7
cmp al, 7fh
je l5 ;skip 0x7F
cmp al, 9
je l4 ;accept 0x09
cmp al, 0ah
je l4 ;and 0x0A
cmp al, 1bh
jne l3 ;branch if not ESC
dec ecx
je l6 ;exit if out of characters
lodsb ;fetch a byte
cmp al, '['
jne l5 ;skip if not '['
l2: dec ecx
je l6 ;exit if out of characters
lodsb ;fetch a byte
and al, 0dfh ;clear bit 6 so lowercase -> uppercase
sub al, 40h ;convert potential uppercase to 0x00-0x1A range
;(lesser values will wrap around)
cmp al, 1ah ;check for 'Z'
jnbe l2 ;loop if not less or equal
l3: cmp al, 1fh
jbe l5 ;ignore all other values less or equal to 0x1F
l4: stosb ;store surviving character
l5: loop l1 ;loop while characters remain
l6: ret
```
Input: (E)SI is pointer to input text, (E)DI is pointer to output buffer, (E)CX is length of input.
Replace ECX with CX for 16-bit code. Code size is not affected.
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 164 bytes
Escape sequences counted as one byte each, since they're valid code but not valid UTF-8
(so TIO and SE don't like them)
```
import StdEnv
?[]=[]
?['\33':t]= ?(drop 1((if(t%(0,0)==['['])(dropWhile(not o isAlpha))id)t))
?[h:t]|h<' '&&h<>' '&&h<>'
'||h>'\176'= ?t=[h: ?t]
```
#
```
?o map(\e|e<'\177'=e=e-'\200')
```
[Try it online!](https://tio.run/##PY7BTsMwEETP5Ct8oWtLVEoaRBHErZBAUODWAwfbB9dxsKXEjhIXBSnfjnErxOmtdmdnRrVautj5@thq1Enrou16PwS0D/WT@8q2TFAmEoCXJdwFQdEW14PvUYGxbXC4xPlVTihlwECQ8@nD2FZj5wPyyI4PbW8kIbYmgZBkZJLJbCpAsFiYagMXf8xgns0GeLG@gRQSaFImiNgcnQrWO5S2PnXsMdezrk7KNVBN9RL4Ks@BZPsgU3OK/j8YyAOfigNTtT7znkP5/HIad69vfLq95pNc8YE7HkDEH9W08nOMy917fPx2srNq/AU "Clean – Try It Online")
[Answer]
## Python 3, ~~186~~ ~~100~~ 84 bytes
```
lambda s:re.sub(b"␛\[.*?[A-Za-z]|␛.|[^ -~\n␉]",b"",bytes(b&127for b in s))
import re
```
Applies each filter in turn, with filters 2, 3 and 4 being implemented by a regular expression. (Diagram not to scale.)
-15 bytes thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer)
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYqihVr7g0SSNJSTomWk/LPtpRNypRtyq2RlqvJjpOQbcuJo8zVkknSQmIK0tSizWS1AyNzNPyixSSFDLzFIo1Nbkycwvyi0oUilL/FxRl5pVopAENS0yKqTBMik5OSQXT1urG7h4glqeXd0yFhUlMRaJRTFFMXkyJkqbmfwA "Python 3 – Try It Online")
## Test cases
I assume that my program's doing the right thing here.
1. ```
f(b"ab\x1b[cde\x1b[;'3GH\x1bIJK\x84\xa2\r\n\t") => b'abdeHJK"\n\t'
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 116 112 bytes
This program assumes that a second `ESC` in a row matches as a non-`[` (e.g. "`ESC` `ESC` `[0a`" -> "`[0a`".) So that I can send `NUL` characters to the function, I provide a counted string to it instead of a standard string.
Thanks to @ceilingcat for the suggestions.
```
f(t,c,i,s)char*t;{for(s=0;i=*t++&127,c--;)s?s=2*!(s-1?isalpha(i):i-91):i-27?i-9u<2|i>31&&i<127&&putchar(i):s++;}
```
[Try it online!](https://tio.run/##bVFNT8MwDL33V5ggVf1IpX5smkbWTQhxQsAFJGBFU5u1WyRox5yistLfXhxOHFD0np/t2EkcGeykHMfK0VxyxdGV@/zoadFXzdHBNBQq9bTv21E84zIIhIsrTGPvzMEgWinM3w773FHuhQrmkeF4tiLZLuJvtUwi21YLqrTtQ6tNY7MTfV8M4/m2rFRdwu3lzfXm6v7x7sFBF3rkqE5lU5EzWKiPrdQgm7bWG3JUvYMeTB/wUICqKSdgEJZl5HuuauezUVtqYwH8V4zr19Tk4O@xTJeoIQtpddUk68op2cRoyLowIsQECoRzQk4oICujOCF@en4hzsp1LCguP8hZU2Yy7b5OVD0vsm5bMEahrJtVjOWFZC7/vUE/kBk40KwtUmbcOqVX6WBp2PfpGUDfQi43QekKoCmiwxipwRrGHw "C (gcc) – Try It Online")
] |
[Question]
[
Chinese Hearts, also known as Gong Zhu (拱猪, Chase the Pig), is a variance of the Hearts game. It is a 4 player card game with the aim to earn the highest amount of points. You may read more about it on [Wikipedia](https://en.wikipedia.org/wiki/Gong_Zhu). This time, we want implement a program (full or function) to calculate ones score.
## Scoring
The player who plays the highest-value card of the suit that is led wins all cards in this round. And after the game, the score is calculated by these cards:
* ♥2, ♥3, ♥4 = 0 points for each;
* ♥5, ♥6, ♥7, ♥8, ♥9, ♥10 = -10 points for each;
* ♥J = -20 points;
* ♥Q = -30 points;
* ♥K = -40 points;
* ♥A = -50 points;
* ♠Q = -100 points; ♠Q known as the Pig (猪)
* ♦J = +100 points; ♦J known as the Goat / Sheep (羊)
* ♣10 = +50 points along, and x2 with other cards; ♣10 known as the Double / Transformer (变压器)
Special rules:
* If a player collects only ♣10, it is worth +50 points. But if a player collects ♣10 together with any other non-zero point cards, it doubles the other cards' points.
* If a player collects all hearts ♥2 ~ ♥A (全红), ♥2 ~ ♥A count as +200 points instead of -200 points.
* If a player collects all hearts plus ♠Q and ♦J, ♠Q counts as +100 points instead of -100 points.
Scoring rules may vary from place to place. Note that this challenge does not include "sell" (卖/明牌) which would make it more complex.
## Input / Output
Input would be a string (or a list of characters).
* `23456789TJQKA` for `♥2` ~ `♥A`
* `P` for `♠Q`
* `G` for `♦J`
* `D` for `♣10`
All other cards are ignored from input. You won't get characters out of this list. We use one deck of cards (52 cards) in this challenge. So, there won't be duplicate cards in the input.
Output as an integer, the score of these cards.
## Examples and Testcases
```
Input Output
234 0
56789T -60
T -10
J -20
Q -30
K -40
A -50
TJQK -100
P -100
G 100
TJQKP -200
PG 0
2468TQKG 0
D 50
234D 50
GD 200
PGD 0
TJQKGD 0
23456789TJQK -150
3456789TJQKA -200
23456789TJQKA 200
23456789TJQKAP 100
23456789TJQKAG 300
23456789TJQKAPG 400
2356789TJQKAPD -600
23456789TJQKAPGD 800
DP2A45968TJK7QG3 800
DP24 -200
G2P6D4 -20
```
## Rule
* This is code-golf, shortest codes in bytes win.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061) are forbidden.
---
Note: Some details of scoring rules may be differ from game to game. Some rules allow all hearts plus ♠Q count as +300 points, regardless whether ♦J is collected or not. Some rules apply ♥2, ♥3, ♥4 to ♣10, and collecting ♥2, ♥3, ♥4 together with ♣10 is 0 points instead of +50 points. However, your answer have to follow the rule described in this post.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 107 bytes
```
≔”A↘⊟T“{»aS¡I⁷”ζ≔×χΣΦ”)⊟≡GO∧”№θ§ζκηF¬⌊E…⮌ζ¹³№θι≦±ηF№θG≧⁺¹⁰⁰η¿⌊Eζ№θι≧⁺¹⁰⁰ηF№θP≧⁻¹⁰⁰ηF№θD¿Φ…ζ¹²№θκ≧ײη≧⁺⁵⁰ηIη
```
[Try it online!](https://tio.run/##hZFfa4MwFMXf9ymCT1fIINp1f@iTtEzWYrGtX0DaWw2N2ppYhl8@i05GKsLua875nXNvjnlaH6tUaB1IybMSnDgMNrt18vH@9jp/mfkOJa27eBpeE16gBI9RcmgK@ORCYQ0OY53S68fol1VTKrhREqiv8oTf0FJycbuhJDesc1UT2FYKIl7ywnCi9ApRJU6wxzvWEqE1Sm/mWije@4lRDk22mKUKLeCf1AkdW7nnWa4gFo00TMZ@HfxMHtLbcdQ/fhQSySg2nog1GQ@@kWXVWbouwyX7I5gunm/vfpno038EJb5VZ7LxfAiOa25gy1QqyF13oXWy3m3ClX6@ix8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔”A↘⊟T“{»aS¡I⁷”ζ
```
Save the string `PGAKQJT98765432` for later. In particular, this string ends with the 13 Hearts and starts with the 12 scoring cards.
```
≔×χΣΦ”)⊟≡GO∧”№θ§ζκη
```
Loop over the string `005432111111`. Keep the digits corresponding to the cards from the saved string that appear in the input, then take the sum and multiply by 10.
```
F¬⌊E…⮌ζ¹³№θι≦±η
```
If at least one of the Hearts does not appear in the input then negate the total.
```
F№θG≧⁺¹⁰⁰η
```
Add 100 for each Goat.
```
¿⌊Eζ№θι≧⁺¹⁰⁰η
```
If the Goat and all of the Hearts are present then add 100 for the Pig,
```
F№θP≧⁻¹⁰⁰η
```
otherwise subtract 100 for each Pig.
```
F№θD¿Φ…ζ¹²№θκ≧ײη≧⁺⁵⁰η
```
For each Transformer, if any of the scoring cards a present then double the total otherwise add 50.
```
Iη
```
Output the total.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~183~~ 180 bytes
```
H=set(input())
a=len(H-set('PGD'))>12
s=sum('TJQKA'.find(c)+1or'4'<c<':'for c in H)*(1|-a)-10*[0,1,-1,2*a][('G'in H)+2*('P'in H)]
print-10*[s,[-5,2*s][any(H-set('D234'))]]['D'in H]
```
[Try it online!](https://tio.run/##ZVBNa4QwFLz7K8TLS1wta/zYtawFaUoWPVTBm3gQ61KhjaIudKH/3SZqYVkPw3szb/IySXcbP1tOptd3@hZomjadg6EeUcO764gwVsrgq@bobEoREkYB4xeLKEMwXL8RZFEah/B0afgHqvDOantw4FSd4Bkuba9WasPVM9aR9WuW2LT2er43LMO0DKKXRY6AwWzYEV0sX/pC6fqGj7N5MHLTFd6hyEt@@09Bie2IGEWRA53PFJMIrtQ/daXKZ@jEn0B6FHC9w9HPRCMRCaQCsUAoNRFelESArVT2iSTE8Y5ZGsuWSmo7sjA6z@nqZutouWXZdsfCh@mGJ48C2zgW5U6gW4uUaEJCx/VF6Cg@pMxeJPkFjCQedeAP "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), ~~160~~ ~~156~~ ~~146~~ ~~143~~ 135 bytes
*Saved 10 bytes thanks to @tsh*
Takes input as an array of characters.
```
a=>(a.map(c=>(i='GPDTJQKA'.search(c))>2|c?t-=h--*c?c>4:i-2:m|=1<<i,m=t=0,h=13),t+=!h*40+(m&2)*(m&!h?5:-5)+m%2*10,t+=m&4?t|m&3?t:5:0)*10
```
[Try it online!](https://tio.run/##fZPLjoIwFED3fkU1GaVKEUrxQSzEhIRENpC4m8yCdHRwImKEzMp/Z0CmPKQOC0I4h/vovXyHP2HKbqdrhi7J5yE/0jyklhQqcXiVWPF0ohPXd/a7wNtOlPQQ3lgkMQgtfGd2hmiE0JTZzCLmCWEzvlNtsznJMc2oKkdU06GczegwmhJ1JsVjDKfFfRjZhokMOIvf8FRTSyMeEzu7x2PdzkzDVGHxOs8OaQYoSAG1AEsuaXI@KOfkS0plMEHImsjgKL0ripJ@QDgYlLY0wjoZQdC55nMA1D9sLJar9b5jFBgtON8/f1xxjfOdmGPOAzHXOffEnHC@FXOjrq8Yw5NS1ccF/1UDXHCFAmiEMsVTlKrFOkU/RPuIMVms9oHXltrYEeevOywG6PQ7bLjrCLO3y3P@24CyvSejU71Oqh1pDvpxfnX@Ft@2hCY/7hvdAjtCddLdCXQEtxb0FxEeRimQltDiDo9QrPmLCKVSRljVguPjLTHWxSh33jJwdZFABJvYtOlif@GQ3q@G1fwX "JavaScript (Node.js) – Try It Online")
### Commented
```
a => ( // a[] = input array
a.map(c => // for each card c in a[]:
(i = // convert c into an index i (-1 to 7)
'GPDTJQKA'.search(c) // in the string 'GPDTJQKA'
) > 2 // if c is a heart symbol (TJQKA)
| c ? // or c is numeric (2-9):
t -= // update t (total number of points / 10):
h-- // decrement h (number of hearts)
* c ? // if c is numeric:
c > 4 // decrement t if c is greater than 4
: // else:
i - 2 // subtract 1 (for Ten) to 5 (for Ace) from t
: // else:
m |= 1 << i, // update the bitmask m of special cards (G=1, P=2, D=4)
m = t = 0, h = 13 // start with m = 0, t = 0 and h = 13
), // end of map()
t += // update t (pass #1):
!h * 40 + // add 40 to t if we have all hearts (-(-200) + 200)
(m & 2) * ( // if we have the Pig:
m & !h ? // if we have all hearts and the Goat:
5 // add 10 to t (the Pig is worth +100)
: // else:
-5 // subtract 10 from t (the Pig is worth -100)
) + //
m % 2 * 10, // add 10 to t if we have the Goat (the Goat is worth +100)
t += // update t (pass #2):
m & 4 ? // if we have the Double:
t | m & 3 ? // if t is non-zero or we have either the Pig or the Goat:
t // double t by adding it to itself
: // else:
5 // add 5 to t (the Double alone is worth +50)
: // else:
0 // leave t unchanged
) * 10 // multiply the final result by 10
```
] |
[Question]
[
I have recently thought of a wonderful relatively old mobile game, called Tower Bloxx. Alhough I'm not really old myself, but it reminded me of childhood and school :)
So this my challenge is a kind of a *reference* to that good game!
I have (hopefully) looked into any tower question on PPCG and this won't be a dupe.
---
## Definition
Given `N` - number of blocks, build a tower of N blocks with the following pattern. The horizontal coordinate is changed with every block.
In order to avoid misinterpretations, here's the "table" of correlations between the n-th block and its horizontal coordinate.
There're no random things there, the coordinate for each block is strictly defined.
These horizontal coordinates are all listed relative to the first block and they are in fact just for readability of the following test cases.
```
N X (coord)
------
1 0
2 2
3 -2
4 0
5 -2
6 2
7 goto N=1
```
On top of the last block, you must smash a roof.
---
## Input
Positive integer (`N`).
## Output:
`N` blocks stacked on top of each other and the roof. Each block is horizontally moved compared to the first block (to either -2, 0, or 2 points), as described in the table.
The block structure:
```
*********
* ----- *
* | | *
* | | *
* ----- *
*********
```
Once they are stacked together, the top of the lower block intersects with the bottom of the higher block:
```
*********
* ----- *
* | | *
* | | *
* ----- *
***********
* ----- *
* | | *
* | | *
* ----- *
*********
```
The roof that should be stacked on top of the last, n-th block is:
```
*
***
** **
** **
```
The block with the roof atop looks like this:
```
*
***
** **
** **
*********
* ----- *
* | | *
* | | *
* ----- *
*********
```
## Test cases below.
Input: `1`. Output:
```
*
***
** **
** **
*********
* ----- *
* | | *
* | | *
* ----- *
*********
```
---
Input: `2`. Output:
```
*
***
** **
** **
*********
* ----- *
* | | *
* | | *
* ----- *
***********
* ----- *
* | | *
* | | *
* ----- *
*********
```
---
Input: `3`. Output:
```
*
***
** **
** **
*********
* ----- *
* | | *
* | | *
* ----- *
*************
* ----- *
* | | *
* | | *
* ----- *
***********
* ----- *
* | | *
* | | *
* ----- *
*********
```
---
Input: `4`. Output:
```
*
***
** **
** **
*********
* ----- *
* | | *
* | | *
* ----- *
***********
* ----- *
* | | *
* | | *
* ----- *
*************
* ----- *
* | | *
* | | *
* ----- *
***********
* ----- *
* | | *
* | | *
* ----- *
*********
```
---
Input: `10`. Output:
```
*
***
** **
** **
*********
* ----- *
* | | *
* | | *
* ----- *
***********
* ----- *
* | | *
* | | *
* ----- *
*************
* ----- *
* | | *
* | | *
* ----- *
***********
* ----- *
* | | *
* | | *
* ----- *
***********
* ----- *
* | | *
* | | *
* ----- *
*************
* ----- *
* | | *
* | | *
* ----- *
***********
* ----- *
* | | *
* | | *
* ----- *
***********
* ----- *
* | | *
* | | *
* ----- *
*************
* ----- *
* | | *
* | | *
* ----- *
***********
* ----- *
* | | *
* | | *
* ----- *
*********
```
## Scoring
Code golf, shortest wins!
---
Trailing invisible stuff is allowed.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes
```
FN«M×X±¹ιI§224ι←B⁹±⁶*↗↗↑↓²→⁵↖↑²←⁵↖»GH<⁵*M⁷←GH<⁴*
```
[Try it online!](https://tio.run/##fY/NCoJAFIXX@hSDqzthi6SSpjb9LAoqJOoBrCYVxrliUxbRs0@jGBVFiwuXc75zf3ZxmO8wFFofMCcwk9lJLU/pludAKbnZ1gLPHNZJyo8QYGHkJY9CxaFFXZKYGodHBUM1k3t@Acfz2k6pU@OwOT8o2retEV6g55I62DWW03BKo5rNNtkqiWL1Vyj7IE@kAjbBQrrEe1Mq2iWd98Bzd41sss9Iaf9O3O0AxTVCOUUhsAA2MNzz4or1X699o@0a1drXzbN4AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FN«
```
Draw `N` Blox.
```
M×X±¹ιI§224ι←
```
Adjust the horizontal position before drawing each Blox.
```
B⁹±⁶*
```
Draw the outer wall of the Blox.
```
↗↗↑↓²→⁵↖↑²←⁵↖»
```
Draw the inner wall of the Blox.
```
GH<⁵*M⁷←GH<⁴*
```
Raise the roof.
[Answer]
# JavaScript (ES6), 206 bytes
*Saved 2 bytes thanks to @kamoroso94*
```
f=(n,k=0)=>n--?f(n,k+1)+`${n?`
`:23456}0110`.replace(/./g,c=>' '.repeat('240204'[k%6])+'* ----- ,* | | , , **, ** *, ** *,********'.split`,`[c]+`*
`)+(k%6<2?' ':'')+'*'.repeat(k?k%3<2?11:13:9):''
```
[Try it online!](https://tio.run/##PY3bisJADIbvfYpcKJlT60xbBYu1DyLClNmpuC3TYos3us/ezYj4k3w5/JD8No9mcvfbOCdh@PFLW1GwoLpK8@oUkqRu4yQNl3b9DLVd2TLLi93@TxujbXr3Y984z7bp9qpcdULAuPPNzDArdKYLPHeb/YVLFJBEgRLwAqBUxDeEUBFAhUitEh9hOo39bbbKnt1FWrGyXDK6d8xqBMASMR7@vuzqbpOTZ0xp8vLAyV/cEKah92k/XFnLjOZ8@Qc "JavaScript (Node.js) – Try It Online")
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 53 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
ø.∫"│“3─wι«@*ο"²¹EiΕbK⁷‘╬$.F=?"¦○⌠Q°‘5nΓ;+}┼JGKh╬8;++
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JUY4LiV1MjIyQiUyMiV1MjUwMiV1MjAxQzMldTI1MDB3JXUwM0I5JUFCQColdTAzQkYlMjIlQjIlQjlFaSV1MDM5NWJLJXUyMDc3JXUyMDE4JXUyNTZDJTI0LkYlM0QlM0YlMjIlQTYldTI1Q0IldTIzMjBRJUIwJXUyMDE4NW4ldTAzOTMlM0IrJTdEJXUyNTNDSkdLaCV1MjU2QzglM0IrKw__,inputs=MTA_,v=0.12)
[Answer]
# [Python 2](https://docs.python.org/2/), 258 bytes
```
n=input()
l=[[4,2,4,0,2,0][(n-i)%6]for i in[0]+range(n)+[n-1]]
for i,v in enumerate(l[:-1]):s=v*' ';a,b=s+'* ----- *',s+'* | | *';x,y=sorted([l[i+1],v]);print'\n'.join(([a,b,b,a]if i else[s+' *',s+' ***',s+' ** **',s+' ** **'])+[' '*x+'*'*(9+y-x)])
```
[Try it online!](https://tio.run/##NY7RasMwDEXf@xV@GbZlZ6SlFNbgL1H1kDF3c8mU4Lghgf57ppRVQuKKC0d3WMpPz4d15ZB4uBdjd11APPqDP/padk1ouEr27UTXPqukEmNNLrf8HQ1bh1ztiXZPz0/iqsj335jbEk2HZzHteQwTaKWb1n@G0WlQ1VYKtH9eD6VkQDezX8LY5xK/DHaY3J78RLYZcuKiL6zfb31iY1A40i2lq@SJ3RhROAL5J24CXhJAvbTI7dYkqSUOzPJcg/lwSzVbsut6@gM "Python 2 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 238 bytes
```
n=>{for(l=n>2&&2,s=i="";i<n;l=A)
s=(y=(p=" "[r="repeat"](A="240204"[i++%6]-(n<3)*2))+`* ----- *
`)+(x=p+`* | | *
`)+x+y+" "[r](l>A?A:l)+"*"[r](9+Math.abs(A-l))+`
`+s
return p+` *
${p} ***
${p} ** **
${p} ** **
${p}*********
`+s}
```
[Try it online!](https://tio.run/##VY/fSsMwFMbv@xSHoCPJWUetQ9D2VPoAPsEoNJutRkJakiobc89ek0Iv/ODw/bn4wflSP8qfnB6n1A7v3dzTbKm69oPjhmyVbzb51pMmxgpd2sJQLRJP/EJ8JAbs4Ii5buzUxBpeE8v3WZ7t2UEj3j81Kbflo5C5ENhKSKNAJq1AfqYxTr8A4ZbpjBdcgA03Vf1avxiBTC79Gd/U9LlTR8/r1ERY0qJPXDd9OwsBFCgBcncdbzHINUoJaw4R1iJXRcptjq9qIHgoQJfBsuCIIjkN1g@m25nhg2ux/df7sIj5Dw "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
This challenge is similar [to my previous one](https://codegolf.stackexchange.com/questions/144053/distances-to-coordinates), but has a twist that makes it significantly more difficult.
There are *n* people on a 2D plane. Using distances between them we're going to find their positions. You may make four assumptions:
1. There are at least 3 people.
2. The first person is at position (0, 0).
3. The second person is at position (x, 0) for some x > 0.
4. The third person is at position (x, y) for some y > 0.
However, **all distances are floored to integers**! For example, if the actual distance between two people is 4.7 units, your program will see the distance 4 as input instead.
So your challenge is to write a program or function that given a 2D array of **floored** distances (where `D[i][j]` gives the distance between person `i` and `j`) returns a list of their coordinates.
The challenge here is that you have incomplete information, and must try to extract as much precision as possible. Therefore this challenge is not a code golf, instead it's a code challenge, and the winner is the answer that returns the most accurate results.
---
# Scoring
I will provide a series of arrays of coordinates. It is up to you to turn these arrays into 2D distance matrices **and flooring each element in these matrices** (if I were to do that here this question would get way too large).
For a certain input use your answer to predict the coordinates of each person. Then, for each person calculate the squared distance between the prediction and actual position. Sum all these and divide by the number of people in the input. That is your score for this input.
The total score of your answer is the average score you get for all of the following inputs:
```
[(0, 0), (0.046884, 0), (-4.063964, 0.922728), (-3.44831, -6.726776), (-0.284375, -0.971985)]
[(0, 0), (0.357352, 0), (-1.109721, 1.796241), (-7.894467, -3.086608), (-3.74066, -1.528463)]
[(0, 0), (6.817717, 0), (-6.465707, 0.705209), (-2.120166, 3.220972), (-2.510131, 8.401557)]
[(0, 0), (0.394603, 0), (-4.097489, 0.957254), (-5.992811, 1.485941), (-2.724543, -3.925886)]
[(0, 0), (6.686748, 0), (6.088099, 0.22948), (8.211626, -4.577765), (-1.98268, -4.764555)]
[(0, 0), (2.054625, 0), (0.75308, 0.497376), (6.987932, -5.184446), (0.727676, -5.065224)]
[(0, 0), (6.283741, 0), (-1.70798, 5.929428), (2.520053, 6.841456), (-2.694771, -1.816297)]
[(0, 0), (1.458847, 0), (5.565238, 7.756939), (-4.500271, 4.443), (-0.906575, 3.654772)]
[(0, 0), (0.638051, 0), (-2.37332, 0.436265), (-8.169133, -0.758258), (-7.202891, -2.804207)]
[(0, 0), (1.101044, 0), (-1.575317, 6.717197), (-2.411958, -7.856072), (-4.395595, 2.884473)]
[(0, 0), (7.87312, 0), (-0.320791, 2.746919), (-1.4003, 0.709397), (-0.530837, -0.220055), (-3.492505, -7.278485), (2.401834, 2.493873), (0.911075, -5.916763), (4.086665, -5.915226), (2.801287, 5.409761)]
[(0, 0), (0.304707, 0), (-1.709252, 0.767977), (-0.00985, -0.356194), (-2.119593, 3.353015), (1.283703, 9.272182), (6.239, -0.455217), (7.462604, 1.819545), (0.080977, -0.026535), (-0.282707, 6.55089)]
[(0, 0), (3.767785, 0), (0.133478, 0.19855), (-0.185253, -5.208567), (-6.03274, 6.938198), (5.142727, -1.586088), (0.384785, 0.532957), (3.479238, -1.472018), (3.569602, 8.153945), (-0.172081, 2.282675)]
[(0, 0), (0.445479, 0), (-3.3118, 8.585734), (0.071695, -0.079365), (2.418543, 6.537769), (1.953448, 0.511852), (-1.662483, -5.669063), (0.01342, 0.097704), (0.919935, 1.697316), (2.740839, -0.041325)]
[(0, 0), (3.281082, 0), (-6.796642, 5.883912), (-3.579981, -2.851333), (-1.478553, 6.720389), (3.434607, -9.042404), (7.107112, 2.763575), (-4.571583, 1.100622), (-1.629668, 1.235487), (-3.199134, 0.813572)]
[(0, 0), (5.278497, 0), (-4.995894, 3.517335), (-0.012135, 3.444023), (0.364605, -0.49414), (1.73539, 1.265443), (-7.289383, -3.305504), (-7.921606, 5.089785), (-1.002743, -0.554163), (-8.99757, -3.572637)]
[(0, 0), (2.331494, 0), (1.83036, 2.947165), (-5.520626, 1.519332), (5.021139, -4.880601), (-0.318216, -0.063634), (-5.204892, -5.395327), (-0.92475, -0.090911), (-0.19149, -2.188813), (-0.035878, 0.614552)]
[(0, 0), (2.981835, 0), (-3.909667, 2.656816), (-0.261224, -2.507234), (-7.35511, -3.65201), (1.198829, 5.328221), (-5.139482, -4.320811), (-3.253523, 2.367497), (6.254513, 1.565134), (3.13451, 4.595651)]
[(0, 0), (1.059838, 0), (-0.849461, 7.87286), (2.108681, 0.717389), (-0.065587, -0.007163), (2.818824, 5.529878), (2.413443, 4.102863), (-3.050506, -2.541446), (-1.215169, -4.818011), (-1.671743, 2.539397)]
[(0, 0), (5.036602, 0), (-1.627921, 1.813918), (-9.285855, 1.277063), (2.271804, -0.51118), (-7.070704, 2.252381), (6.125956, -4.278879), (1.000949, -1.38177), (-0.67657, -2.747887), (2.820677, -5.718695)]
[(0, 0), (0.733516, 0), (6.619559, 1.368964), (-0.047351, 0.545139), (-4.518243, -7.506885), (3.31011, -4.329671), (3.885474, -1.535834), (-3.952488, -1.94899), (1.402441, 7.538954), (2.385809, 4.042365), (-6.403547, 3.623895), (3.742502, 0.025475), (1.944868, -2.972475), (-0.514566, -1.015531), (-0.08634, 5.140751)]
[(0, 0), (2.374024, 0), (-1.016305, 1.31073), (2.176473, -1.357629), (0.181825, 2.107476), (-0.978214, -3.436398), (0.828254, -0.39516), (2.981311, -6.761157), (1.517599, 5.009197), (8.063442, 0.930487), (4.628231, 7.749696), (3.810604, 4.671208), (1.158015, 2.914197), (-9.230353, -0.473591), (-9.031469, -4.206725)]
[(0, 0), (5.733822, 0), (1.394054, 1.432354), (1.556614, 5.691443), (3.665168, 7.199478), (-0.670337, 0.396217), (4.144468, 2.959243), (-6.129783, -7.048069), (-3.230162, 3.116924), (-6.365913, 3.727042), (-0.174385, 0.253418), (-0.454495, -4.415929), (5.815488, 1.443031), (-4.288448, 0.619174), (1.957015, 0.784202)]
[(0, 0), (6.550779, 0), (-8.592692, 1.728506), (-6.460692, 2.344509), (8.359129, 4.578714), (3.593451, -4.172634), (8.697976, -2.379752), (4.27242, 5.296418), (2.920394, -4.520174), (0.662004, 2.171769), (1.879771, -1.873537), (0.769374, 3.570321), (-3.438699, -3.255416), (3.23342, -3.220256), (-0.002136, -5.646753)]
[(0, 0), (5.013665, 0), (-0.543516, 9.981648), (8.378266, 5.33164), (4.759961, -2.007708), (2.88554, 1.069445), (-6.110542, -6.253516), (0.292062, -0.052982), (-4.869896, -1.251445), (1.61841, 7.980471), (-0.313257, 0.515709), (8.673848, -2.269644), (-0.446207, -0.568228), (3.015721, -2.819861), (1.160386, -5.897356)]
[(0, 0), (0.437257, 0), (-3.127834, 8.941175), (0.785858, 1.99155), (2.005894, -6.723433), (1.332636, -6.214795), (3.149412, 7.17296), (-5.350834, -5.106189), (1.447561, 0.910621), (3.032259, -7.977927), (1.520669, 5.121877), (-1.075969, 0.098313), (1.015673, -5.244922), (3.575391, 5.270148), (-9.160492, 2.943283)]
[(0, 0), (3.63663, 0), (5.448045, 8.287277), (1.314494, -0.164441), (-1.941398, 4.223086), (5.025181, 0.495811), (-8.466786, -2.933392), (-0.139755, 0.730451), (-0.098497, -0.587856), (-3.337111, -1.238969), (2.142947, 2.521078), (0.352537, 5.4194), (-4.49191, 5.261929), (2.198984, -3.781113), (3.525393, 1.150581)]
[(0, 0), (4.540155, 0), (-7.248917, 2.368607), (2.434071, 1.763899), (3.990914, 1.135211), (-5.422214, -5.785259), (0.526037, -0.888364), (-0.370255, 8.515669), (0.77125, 4.48859), (3.9838, -2.3101), (-2.993973, -0.775446), (-1.731491, -1.028441), (-0.184254, 0.281876), (0.048732, 0.222435), (0.108646, -0.344878)]
[(0, 0), (4.934251, 0), (7.472259, 4.693888), (0.057108, -0.038881), (-0.276457, -0.157808), (-6.745232, -0.357168), (5.979037, -0.653591), (-3.969328, -6.050715), (4.19821, -1.883165), (-4.294607, -0.407446), (-6.11544, 0.480539), (1.193587, -1.028919), (-0.387421, 2.036394), (5.78394, 1.333821), (4.178077, 4.286095)]
[(0, 0), (7.547164, 0), (0.989783, 1.074185), (0.192979, 0.210046), (6.528904, 0.400088), (5.602168, 5.791553), (4.058506, 3.995028), (-1.033977, -5.44405), (5.767663, -6.702417), (4.401684, -3.097193), (-0.821263, 4.624133), (6.031465, 6.544092), (7.188866, 1.599597), (5.327328, 3.51571), (1.305662, 7.488827)]
[(0, 0), (0.638053, 0), (7.279348, 5.416438), (-6.495944, -1.385692), (5.348119, 6.89312), (-5.145817, -5.640294), (2.909321, -3.139983), (7.052144, 3.902919), (2.467506, 1.362787), (3.469895, -7.977336), (7.598683, -5.947955), (-0.679492, 9.140908), (-3.310304, 3.134427), (-0.83399, 5.797306), (4.08935, 0.830119), (-7.764758, -4.403114), (5.183087, -8.528744), (-0.75072, 6.163092), (-0.692329, -0.225665), (2.0628, -2.008365)]
[(0, 0), (9.468635, 0), (2.005581, 2.669352), (3.416536, 6.9941), (-3.293394, 0.864229), (-1.044833, 2.243219), (6.011018, 4.014313), (-0.959567, 9.620265), (-1.855409, 1.890371), (-0.629015, -1.383614), (4.087875, -2.203917), (3.286183, -7.748879), (-7.781181, -5.295325), (3.28653, -0.930535), (3.973893, -1.784441), (-7.7541, 4.355823), (1.522453, -1.960952), (5.085025, -1.511887), (8.401342, -2.139507), (-1.727888, 0.7952)]
[(0, 0), (8.617779, 0), (-7.012573, 5.883927), (-3.508725, -6.838323), (6.676063, 6.884947), (8.297052, -0.134775), (7.416737, 5.915766), (-5.10108, -7.183776), (-4.651823, 5.434926), (-1.099239, -0.238062), (-0.313045, 0.354853), (-7.592061, 5.408053), (0.566482, 0.652099), (-3.551817, -3.365006), (8.514655, 4.653756), (-4.249357, -2.130864), (1.181348, -1.22839), (2.469081, 1.110794), (1.831897, -1.552467), (-5.892299, -1.919411)]
[(0, 0), (2.407206, 0), (-6.771008, 0.810524), (-3.840048, -0.152269), (7.109171, -5.609477), (-7.391481, 5.639112), (-8.670299, 2.742321), (0.586435, 4.542551), (-0.442438, 0.107817), (4.31145, -1.409808), (-4.534678, -1.504437), (4.680038, -3.080315), (-4.973063, 5.638478), (6.127056, -7.491446), (2.291953, -2.357609), (3.510856, -9.171005), (3.971143, -8.515823), (0.049413, -5.842664), (1.058161, -0.21883), (7.093364, -3.604422)]
[(0, 0), (6.969461, 0), (4.338403, 5.197497), (0.369553, -0.770371), (8.882643, 1.450294), (2.124852, -1.210185), (-3.046623, -4.395661), (7.716904, 4.60951), (-0.83271, -0.854575), (-2.333383, -0.308884), (-6.347966, 3.124373), (0.832848, -1.892136), (1.446553, 1.613845), (-2.241092, -6.53878), (5.004282, 5.401177), (3.31202, 0.432188), (0.164548, 1.23087), (9.860844, -0.125136), (0.133559, -0.202543), (2.686551, 1.013555)]
[(0, 0), (9.107655, 0), (5.455882, 3.54979), (-0.681513, 2.950275), (7.369848, 4.050426), (5.320211, -8.288623), (-5.315311, 4.632769), (-2.801207, -3.00623), (2.502035, -2.085464), (-0.645319, -4.854856), (3.639806, -8.669185), (-0.732853, 2.379454), (-8.722855, 2.483643), (-0.03048, 1.845021), (-6.904949, -2.596416), (0.685437, 1.042775), (-5.182001, -2.617796), (1.595501, 0.885512), (-8.567463, -0.607195), (-5.456613, 5.81163)]
[(0, 0), (1.669656, 0), (-3.385149, 6.655961), (-1.501983, -0.746686), (1.962876, -0.780073), (0.51437, -4.130592), (1.825567, 0.531272), (-4.188001, 0.514048), (-5.894689, 1.726502), (-1.429067, -3.558197), (4.605078, 2.060605), (1.670708, -8.99749), (5.44004, -5.315796), (-0.619392, 1.785159), (-2.854087, 1.696694), (4.974886, 6.291052), (-0.699939, -5.930564), (-2.35508, -0.057436), (-0.804635, -0.687497), (2.289458, 1.946817)]
[(0, 0), (3.626795, 0), (5.048495, 1.581758), (0.154465, 3.132534), (-4.862419, 7.051311), (3.927243, -0.408956), (-7.41798, -0.313768), (1.987639, -7.957834), (-1.100923, -1.442563), (1.949075, -0.382901), (5.696638, 3.400352), (-1.121574, 1.315934), (-4.37434, 4.937007), (-1.244524, -7.36647), (9.138938, 4.035956), (-0.207342, -4.257523), (-1.298235, 5.950812), (2.17008, 1.116468), (-1.410162, 4.861598), (4.69532, 2.076335)]
[(0, 0), (9.787264, 0), (-4.65872, 0.957699), (-2.813155, -1.174551), (-0.445703, 0.362518), (2.920405, 0.914672), (-1.63431, 0.048213), (-0.534393, -2.389697), (-0.105639, -1.589822), (-0.100723, 8.648806), (-6.894891, 4.8257), (7.417014, 2.868825), (-0.84031, -0.322606), (-0.802219, 1.209803), (7.808668, 1.700949), (-3.270161, -3.463587), (-1.118415, 0.713057), (4.130249, 0.824635), (4.664258, 5.993324), (2.575522, -1.031243)]
[(0, 0), (6.514721, 0), (-2.2931, 3.6007), (3.388059, 1.102576), (-1.777694, -2.809783), (3.431761, 6.534511), (-8.13158, -2.940151), (-4.856169, 2.834183), (-0.706068, -0.93294), (-0.393184, -4.989653), (4.480243, -4.107001), (1.681165, 0.611419), (4.442544, -0.536704), (4.90654, -7.356498), (-8.722645, 1.203365), (-2.067292, -4.134382), (-3.002458, 7.891842), (1.398419, -1.279873), (0.237866, 0.010691), (6.879955, -2.882286)]
[(0, 0), (1.421587, 0), (-0.615169, 0.286873), (0.848122, -2.730297), (0.220832, 0.89274), (4.588547, 8.497067), (-5.079677, -8.428552), (-3.170092, 2.418608), (1.309388, -3.658275), (1.639533, -2.364448), (-1.327656, 1.006565), (-0.475542, 0.298309), (5.430131, -8.343581), (8.430933, 4.118178), (-2.090712, -0.470172), (1.146227, -6.664852), (-0.542811, 1.909997), (0.439509, 6.112737), (0.343281, 0.630898), (-3.673348, 5.101854), (-0.072445, 5.784645), (4.895027, -7.960275), (-9.633185, -1.688371), (8.059592, -5.178718), (-2.334299, 1.217686)]
[(0, 0), (5.456611, 0), (0.181969, 2.084064), (0.89351, -2.507042), (1.570701, 1.202458), (0.814632, 1.883803), (2.790854, 5.8582), (0.699228, 2.377369), (-0.463356, 5.162464), (1.166769, 4.739348), (-4.652182, 5.553297), (-1.123396, 4.186443), (-0.327375, 0.45977), (-0.395646, -4.122381), (0.652084, -0.696313), (0.716396, 2.005553), (0.73846, -7.361414), (-1.912492, 3.937217), (-0.162445, -2.681668), (-0.133005, -0.910646), (2.194447, -4.169833), (-3.132339, -3.079166), (-3.078943, -1.410719), (-1.365236, -4.103878), (2.044671, -0.831881)]
[(0, 0), (1.382529, 0), (5.031547, 7.747151), (-0.49526, 0.019819), (-7.918566, -1.919355), (1.046601, -4.397131), (3.113731, 8.325339), (-1.700401, 1.511139), (-2.699135, -5.052298), (3.434862, -2.609676), (-4.506703, -0.424842), (0.154899, 3.782215), (1.373067, 4.412563), (4.548762, 2.096691), (-0.0275, -2.604761), (4.462809, 1.533662), (-2.016089, -3.481723), (7.024583, 6.980284), (0.254207, -7.964855), (-2.055224, -1.374547), (-3.185323, -3.753214), (-0.479636, -7.476727), (2.208698, -6.374003), (0.24381, -0.620774), (-0.551312, -3.796487)]
[(0, 0), (3.442359, 0), (-5.045461, 1.685484), (0.072923, 1.158112), (-1.347292, 2.626515), (1.982477, 4.374474), (-3.188879, -4.020849), (-0.430788, 0.118491), (0.725544, 1.992762), (-2.893352, -4.311321), (-6.871016, -2.359638), (1.406456, 1.734539), (2.029903, 6.151807), (7.565244, 1.948656), (-6.420158, 0.698035), (-4.873019, 3.593625), (9.548917, -0.45405), (-8.701737, -1.872887), (-7.941202, -1.4121), (-5.995713, 0.555241), (-5.704163, -2.868896), (-2.677936, -1.924243), (-3.460593, -8.679839), (0.631064, -0.433745), (1.18902, -1.496815)]
[(0, 0), (6.537782, 0), (-6.75348, 0.404049), (-5.348818, 5.082766), (-3.738518, -7.824984), (4.513721, -7.740162), (-7.707575, 3.393118), (-0.11626, 0.439479), (0.12586, -2.885467), (4.952966, 5.673672), (2.56597, -0.333544), (-4.60141, 2.716012), (-1.865207, 1.826155), (3.234169, -0.966176), (-5.977172, 1.660029), (-7.968728, 0.889721), (-0.028198, 0.153274), (-5.427989, 8.150441), (-3.708225, -0.777001), (3.513778, 0.529579), (6.309027, 0.399666), (0.542878, 1.900558), (-0.633748, -4.971474), (5.340487, -2.474143), (-0.805431, -8.633636)]
[(0, 0), (0.211756, 0), (3.03609, 1.381372), (1.472087, 3.505701), (-0.198393, -0.284868), (4.290257, -7.630449), (-0.120326, -0.047739), (3.167345, -1.144179), (7.791272, 6.043579), (6.125765, -6.3722), (-0.178091, 9.313027), (-4.177894, -0.704969), (-2.950708, 1.716094), (-0.016133, -0.105582), (-5.962467, 6.088385), (0.901462, 0.58075), (2.063274, -0.221478), (-0.430464, 0.9548), (4.824813, -4.037669), (0.863528, 8.321907), (2.693996, -0.380075), (0.879924, 4.243756), (-7.759599, -2.81635), (2.58409, -2.225758), (5.515442, -7.445861)]
[(0, 0), (0.958126, 0), (-0.566246, 3.074569), (2.666409, -4.784584), (-5.490386, 1.820646), (0.505378, 0.261745), (-0.122648, -9.791207), (0.569961, 1.044212), (-8.917451, -1.667965), (-7.374214, -1.193314), (-4.559765, -2.486695), (2.367622, 1.707526), (0.762113, -5.553413), (-9.62438, -2.077561), (-0.072526, -0.072188), (-2.051266, -5.410767), (-6.656983, -1.824092), (1.170361, 2.019313), (2.689391, -3.998207), (1.814094, 1.782214), (0.498034, -9.437937), (0.87507, 0.670687), (-8.114628, 4.823256), (2.693849, 6.952855), (-0.005543, -0.01139)]
[(0, 0), (1.703854, 0), (1.091391, 2.171906), (5.559313, -0.310439), (-0.396107, -0.771272), (-5.136147, 7.769235), (8.969736, 0.885092), (3.541436, -6.530927), (-0.461503, -5.877802), (-6.108795, -5.163834), (3.698654, 3.749293), (8.049228, 2.056624), (-6.022241, -0.657227), (-8.701763, 4.803845), (1.225822, -2.070325), (2.099514, 5.191076), (0.500653, -0.104261), (-0.581698, -5.755634), (-5.150133, -8.269633), (2.559925, 6.839805), (-0.149545, 4.456742), (1.43855, 1.865402), (3.439778, -4.954683), (-4.18711, 7.244959), (0.640683, 0.907557)]
[(0, 0), (6.577004, 0), (0.042196, 0.025522), (8.61361, -0.689878), (5.407545, 1.709241), (-4.724503, 3.123675), (4.329227, -5.283993), (-1.238506, -1.104368), (-0.758244, 1.882281), (3.851691, -0.571509), (-0.229269, 7.452942), (2.833834, -6.742377), (-8.49992, 1.912219), (3.102788, -9.456966), (-0.420271, 2.449342), (4.123196, -0.512152), (5.893872, -3.689055), (-3.801056, -3.486555), (-3.576364, 3.448325), (-0.397213, -0.010559), (-4.519186, 4.525627), (2.720825, 6.0414), (0.918962, -0.430301), (2.217531, -3.056907), (0.912148, -1.487924)]
[(0, 0), (0.170063, 0), (1.088807, 2.795493), (5.884358, -1.914274), (9.333625, -0.111168), (7.168328, 4.042127), (2.558513, -0.146732), (-8.011882, -2.358709), (-0.374469, -6.591334), (2.495474, 1.011467), (0.094949, -0.351228), (7.0753, 1.26426), (6.614842, 4.664073), (-2.777323, 7.287667), (3.280189, -6.811248), (-7.254853, -1.472779), (7.147915, 1.932636), (-3.431701, 3.030416), (-0.863222, -1.177363), (0.512901, -0.258635), (-5.614965, 0.462802), (3.452843, -6.869839), (7.475845, -0.353582), (0.067355, 0.298013), (4.39831, -8.5387)]
```
**It's not allowed to optimize specifically for this set of inputs. I may change these inputs to any others at my discretion.**
Lowest score wins.
[Answer]
# [R](https://www.r-project.org/), score = 4.708859
```
require(vegan)
solve_mmds<-function(dpf,noise=0,wgs=rep(1,nrow(dpf))){
#MMDS
v = wcmdscale(dpf+noise,2,add=TRUE,w=wgs)
#center on first point
v = sweep(v,2,v[1,])
#rotate to adjust second point
alpha = atan2(v[,2],v[,1])
alpha_rot = alpha - alpha[2]
radius = sqrt(apply(v^2,1,sum))
v = cbind(cos(alpha_rot), sin(alpha_rot))*radius
#flip to adjust third point
if(v[3,2]<0){
v[,2]=-v[,2]
}
#return
v
}
N_input = length(input_data)
err_runs = rep(0,N_input)
for(i_input in c(1:N_input)){
p = matrix(input_data[[i_input]],ncol=2,byrow=TRUE)
n = nrow(p)
dp = as.matrix(dist(p,upper=TRUE,diag=TRUE))
dpf = floor(dp)
v = solve_mmds(dpf)
err_runs[i_input] = mean(apply( (p-v)^2, 1, sum))
cat("test #", i_input," MSE:", err_runs[i_input],"\n")
}
cat("Average error: ", mean(err_runs)," \n")
```
[Try it online](https://tio.run/##dVvLbl3ZcZ3rK4j2hEyoi/1@GNYgQDx0BnmMOu0GLVJtBmqSpih1nMDf3lmPOnTrOgYaaOree87Zu3bVqlWr6jz/fP/w9Pnl@9ubl5uLdxcf7z@9XL65uHh/ma4v@N8ptbFW0z/etlMadQ/@67RLmWXhw3pqbdWMv8ZpljHnwJ/pVFars@vPPfNe/er6q/vWPmsvvm8@5bRnwT3yae5RGu82T2u3NqYekdYYyU@bLY2hizqeMepX9x2nlefM0/cdpzb6TPzXaaZe0saH5ZRLyrxFPZXC5@rDnlPmLtappdz7PF/ubiPVVzPs2daWGfosHQZ52097l5W1h7b61h4KLNJ6q1r4Ln2tcbbcsQZuFf9Ia6Wt25ay@ek6lZxHGXpon7Bt1873KmPpwzla71/btpxSb6P0WPnslZZLp7Zn5eEMXD53LVp0Xg1G1u/KHDq7jlPupbSzlZZVJzflA4NVN@6KXWOl9ANYsKTUq86g5daH9j92w3nokoWd7K/tClPBJs3H1U8dz62418Six67b206p8A4NflbtT1gfXaueRsfdy9lRjbpSj4WWU52VW8X2KwxJ861THjtX32v2hWORu5VU1vaprdRKOl8qHCS1dhgAK6j0Mzh9hn9PXddy3nG31UeSazX4Tu@700TYa5tfeyx@OWuOQICf4blcBDynYZVbz2pJrgejwyhTv@OhVv9ZaPfuSISPpe7dzAU35I3gz6s2/bUrHia3zTkpOnGAGcdeaV8G2Tg@hAcMLTnlsiZPp8HrRz6Pi9QcYOEVWICsDV/a0@tLaS8DQe0j7@YYhKF25RlWbCV3Gpgexo1uLL7kVeR18gKcXu@F5p4I6TJS4@8X7tG6QApxczwNh1x7QFDR2sap97T2VyuvXOFcR5DAHdpUlBCqfHlevdCfYY6ScJxTiJJqmU1BVPF8hUBuWO@0VyzAlO5T4da6PY6qACX4yDa3/JtHOgFCix/C00cqjPXcgTLxbHy95AbYxJjn4NkAKnPb6rBgzsKKvoCpAuc04eK@E9ypDvsBNtQUn70CSTZNuHttgh/gH/ertQ0g8PLGx0CwyWOAjk0nS0snp4C8d9XJDUBLHvZa@KWPLLVcSz@zOiAyrXLAM8B@8K4dkVE3owDb6XPvFXHYcTA1DIZz0ephmkrwhT0rQJmG33hYaVzVRJjOzDthLaMKJ4SduXNLjOI0Suyz4PFLnld7W8402FO2EVfG5V@DS1dY7XnkgY1op0Nj0Rk4ExbPJVfBE6A1FVmvDqzUXzekBrkv8l/VIcBjDW2I2gW3crqoCGruCJ/ukkcafDzcWF6F1RMWAxB7b5mnBGjbe/YZZiyjzrPMUGtuuwWgrZqqDg0YnSPwAeLKN3DlvIWceCiSUIAxEtRI2cGMCM3O9XCRUVtEChKjUwtgrxYH5S4tuEDaaWffIG@sxWCwFozt72tfDsSRGfNn64djrNoPx8e9BsMSaaaPFYspIyN5OacDgatNWHvXY5kzSlKWRvSusrnBiiAj@2A@RAiugG2GoK8BDnQeJAyIdL2FKUj7PculkLbkMnCe2rpSFfAeH54lkNT3qutAevhRG9kJoCydA0Jj0PMTc4p8XMbtfR1IOnXOCAyYjJvkgW0ZjPFd5UYN98EN7UUJ@SA5FcNJlOrhOyX3POJEMxDeCXrgqU23h2PWs1QNN6hDQJUieABm2TCM0F2KwrK60BNPAEh4qUjeS34sjMnOjgnAnJSTClN@pkFzodW0KETZmoqNhOzRnAUrqZ3ug4TVnXBn4y9lETiuvu4w3gL6nUEmw5MeYtaVmZJ5/zqWCK3wChEp6@tkg33AyyM2Yce1FNc122T0kT1ITioiA5DcnATgw3I7eGgHlBrx4VdbjwQmtKaD7zjjLitUGI7stBHIhNckrwiGpsQxCn@prNWQ4Y3DcMApW4MmL9FBxMd8jbRODubjJqGtDjp4WG1OWiAA@RweJhd3HDFYck16AjY8dZgZfHMakAGOo4isZvhQ6XZgHMgI0g94sBHAvOpWTC8EWre1gQ7OGAjpmqN8GDnzYAk@s2/FJs5f7GoRZZpT0Abr4Kk3GGaVKlsiLJFIdRI5iSA0OnRJAnigv0gGHpeb2Rq8FfjXDTs8enE/ZBJAZMQGXeosg3U60iolQhpokbrQvFUmEa0dZs@yMQicIhIHCDQYYrbIL2IacuNU63R1McRuELqk4wpn8CN7HiMD1rQTYuNJq6tcPhi1YAfBLMgb8GfsQ48EJUk0l9hEq@YiALKWVzCq1razY8t4lqy9cpe/ZpLtVO3khbQ1MHnn2UwcpgyKwFrgyuWsWEDqmgdBATHZZTApIOcBIQRHLM2SPoTXgc7Q@deJh1AUBn2umZ1Zt0EVC8lMaY0/BOHYcwTBR8orvAYszGQCQaldwojgCmKcjZlNa0/kN8ngA@YeRGiRrkadwsTsmhFFyPQicFQlhzcDXeIElHhFa6rY0VuVlKVHWkTirK6okP5RL5wDKr4d/cgH4GaKiM2IGK7@KoJoKPEjcQ/5NONimB0hHcy0XFd0@x5M2prRAwy/a01D6UvYB8swv3t1zBzOdNjQ2pEZABvNnA6loSJrA77nkfPB6KbpIkyiMxvIVM3og1MezeENLy4pSpWBeBHVhceoyiezQ/YdTsOoq5etBHKDEuGc69bpZ5qeITXYBUCj8gwPRNaR04K7dUU5KiIRM2kStVXladCZUe18gKZpQCUfIl2c9K7tdVSUC8FngCV5GbYBrCOb98KGAn04RWEeIUeDvxdjF0w8FE0ggmu6MADY7rHNn1c1b4A5xowCA7FYij0NyTebaqbcnFdho@ZY2cCZVc9INXY1ajgVIjXxABfCFhAwDd9NrI9QgANqORJSFiwjcAAly/wS528GAmww@1mI1DGXgw2UsO4AFTCEbvsDjnukl216zGMHLVEgIF9WUHI/lImMdiismnabFg6QN1w0seJysZkjbBvg3@YA@BRfCW9dTi0TazTc8cpthg/Ks77ObIh@qTr2ItBs5OI8zeeWSojCYiJNS1CjKlUjfZOtKrDA6Es2RWylOLN1ep7OH7tFURr1OMhsDUqBerZ0HQbiZfj8ATNMltgZotZPESsklOXk6NikXyFQzH6wtknybjOC4PkYmX2bcirrXbjbsGgHECsWkpBEdEokl83AxJpvrjMLAWZLyCaT5ak2hhyKgsQVbUIRlVawdDJ2020qUN44onvpBwi6BlpXouifSn0dIbIPG7FG38ZTuEMtvgpUdWbZBkdcAo0RLcNpquwo9@CdIBptBM51qTKwZ4qCCpWLKbMMZRWFFTnIk2rqREKiDA0w2c3YUPVEJpmVpnIxSHQ645HgbKyVWmDTXk7MjG@W1xYQkK0t4qHWbBLcOlbhmrmB0C5ZA1w67DKJWlZgutMjPQ80z8QRJGEHs2VB2XUJKPAwOYCLNXMHuPiIuEjUXO1A2FaxvkNhtaqEFsfpWhnuuA1/ONLhyg8P39OF0ayGbuK9ggOMcAxdAP9dZf5/4lsNW6FEqG05nEerPmQAy24tGH0XBcCDGgJ5SzvcUsMIvQ1hPCN9prKVsRGQRyIGAG0afzKV5aY8vfG7LJBgwk3DFB85w/oL81w/4LoyF@BAkYhC7dhMCj242RbibhLlHdIz4rOmo9BrUdsuHM/2MQIIh4W07ZhDha1t4YEkzt2aLXh9NkFEMZvkqIsuMiN3zi7lEK4N/h1oCzvVskPv68OKDtLQCiYAyPnaUzd2C67fD0k4oYqU8wOGJLxXHkqvFoQtV4O9AOC31Y8BnHPhlSjwu5ZD9vExYV/Sr7DZ3GoU75sF3OSzkfxLaNWkJskci@Fv1EDlIPooJ6iiyzQbzqmbSYC25WnBCAnY3Hc2V4X8E@6yDMeFMkOPnwadR4HQLcFs1tEuWOaK1Ed5uSnWK4xSXMMDJ7t/txn1Fj4QjcWrpDy2ZrQHzPUKPbAn48xkySqYhAt9zYZBkVC4Hmx4Uh/qBHeLXiXUGmy@mLghG9SiMEWQq4geFI6VLJHVNzsZkYHbpL0mT3I6bwJK5hhBXQzXDO3qtgwwgAWtHo58t0vUh3sfOivy80EQcarJ8irVsR5FMAlkthwckQ6CN6SZJGkrwY07iYT3BtdMDAxmQcCOAB4nNY9iv8EhZxiUSUoQjqqwGf9AHmuE9JYomsltp3Eb2WHt0F5Ra48ZRBK@a@cFHIAontW5SB8ljVcVEnnNLRKUjr0YQReQuq3Ia6Uwd1NbhFfa7eAkTag8Ub2Bp8kmSCvSHt@SFictgRpFEWSREg0lY9IR8IIcTLkIGpmh5zKSEx96SP/bORXXVGzPJukIyeoCeKVUV/TIgCvOlEKi6hUtlZssIuE4Qwtu20oQ4gzm0ckW1fNpG@uTmdtmgZRSBBLWZI0RuWBZ1kwkz8ZOsJDhoyP7GkEOEDRGaODKsGFBZYEsZ/UiSIDEMDERpOKWtHpU6lZb4UO794MRGUYWoqKMVt1GOhJEBrcLHbsQotwYQR4eXLK7McO6G0XyEAoQ8TnQvARErd56oFElO/DD4aBqh7LUbpSvlQ1wgu6r4PIVbgsfVPXHymFo7aypsLVAuJaN7ZTjpeBR62hlFQdXltjFnFNS9K9oTfkJGFcL3VrpY5/YdojsAXTRc9XUkMrFg6BaJAhHUpDnsfyo563DTR8cwZM7my5ruSpp4jRE7pUle1KgSMXwg8PRrklgsAUXrCWVqB8KiEWxl8BBJfbA5DD02NFty64VcU5pWGfFvVO1peCMLfg0Nl5z6JbEpOHqByEyHHRj5@g1kbh0S7aAColOCyhdlgvERo5@SM7J1lz0IitRm57t1XWKCbLnYP9EBRU2OaN9BjhNwdoJ8zsYVO9JIc/KPBABqbENPxI0Nm9fT5EuOxvkfNbNZitmjz5eGz2rSzJHZsDBjhxYkHc4J@4/lhawwQxCiAOdTXZOXCz63Yiz3YLMAg4NV/TwtGhYws@Sl49LjILEVBCKbRFnSIMkPCGPR4ue/GIbk8jjlwlKGlYQBwXfdbQo2napKhnGbiHLvZXEVEMrwm57eAgoxJruNMEkilm24JfYC0DsSIljb/eNuzjAaAFt/Shc@mzVD0KZPKJjM5Zhht02@IqlBOw2z/NCuwzJBpZv2pKAxq5fFrdjqmgi1mSI1NpCXkGwbxNVa50cBpgl/A9b2wcwZ3XVnXyne1MbB1lDY@gWPzQwAfSIzhhyyahe806h/qKa2ck5CRar4vBsIwc05gKLu/DJFNiMjLCNTYu6NXhNac0ZkVE@msAmk1I53GtI9kSYaVqEhA7cjLVRYqqqWIAWy225PFOIsgCyEe3QbC2TxsKClivPXnUBIAlIdgZUoIplvM6lDNR7JeYxrM5RYqoq@bld1KOv6bbPFD05ih2hEqquorSDHBvdwdpqjmK6BMHFiUpkoE9Rx4i6F45Wd/R/t8Rhfcruk@hfWytEz8UugPBvSdTSkaeszIUyRDK6ekMp9PoK6pEOhy0i37AqSYHy6mLPXsacR6OkSjgaIVaO10o4U8@zXsPwt9pcUTxuK/OOBpgSxL@7XmcDUEvDgfZommJhcNxzuTc3CXseuUARIR8fciLCFpiiC3OkoRliBlvQLfDfVTS11TxHdou69UgfPMboblDEyQH/I1tHWlS0A/@INysqgLKPRgMooh2cKqcL7QZjNvMBZLzkhuAgAnfr3FkR2xRckVhRK03TBQ6gHG3F0fY6csuwcorM5RYOAXCWHaAK31klslwRynDEifKNOwmrxbgHyuYY0yh1qiZnUzmNLcugBHKRStkX@WycT9QgtNc8VOURnT6qQyPuilydiysY8MRiglUKakiFEIjL1Da7elqqeVB0BLUG8XafDZ8ymXpHjGkLlDiM4fBG7VrXip7rKu5VDXaFI4IoRTr8yQX6cL8Pf0SjHE7nfg9QpCanjOopLTwd5lRFu/jhrm58suaIkhhQmEvcKOUpIyO6S/EcB2uWSBp4SgxubVQvNkdjaadUC0I/o0tD7TVb5QBmx9ZmDY1DbDNaibNIRafA1OQV8FjxJeP4MHMCwQay5WjoI/yD1yJaejTRM/sgoQ4CX91BLIiSs3MPIpGPeRbkYocHeGHyxB5FiXz0xZO9jtNxdv4SPskiCFBgcoBSNIlDzZ20N9CAHqUeakbPfaG2rCOmdAjUon9A8xaV3Bgieg3OZjlIeO0Bnw7aUEsUcLnUuiWgwIeOYS9KUJb5Wz9mfEjhm4tHOHKNM0HtuYIm7iFJglA3dEsLIC5X2a8YkdGyZjFUJhbpPZXJT704ieU@RnI71DQBLaDVKWY52AlwIYUqs7UgV2DDtYZExS055ufW0KH@RBqoR96bEfWVw2@xqVSjp584AXlUJqBl5yMFQJRe9muDPiteqZTMfOS73UsgyF6hRZEkR2t4Uyvt5rTDox0skWY2hGfQEE9Fks5EkkOsNzsNG/p1x6Df1tQLIQK5Yq8Y0FnDSIMSa4QG0dNQCubqUK05xtl4tOg@OYzhtjPLWEub2RyHlTP4kGkBqWC0HUpUaigulUAax8SWZSese8QikBfT8nkAA5WeQcro@NVzkdTV3SdtLkkYrG0F3iZmwZAuZ5OtecioM4rPe@KvHA0w4GQNVjeH5sMoa7HV5upxHlN9LP8PVSzNGcmGTNHYOrmCcyaKvFR7SEqkor2NyGEwUMyAlV2iIbKsSmTWrMU4zWFIWxmMpVnwxpo8w1ClBk9XWolxFfFd4bsmushb26Mq7IK6J4zEEYYG1phqSsuoUVUBylKOri3ql@pGM0LI2A8C2a30UDpJOhK48UryaQ6HxnPgVD2ayCVlo9YgJbL6gTSX8o7esQZhN91mR1TDVslzoMwLdUbTt0jf44E3l9wKzxgLQsqdRpROmckfAkQ9dmXutmPidXLizsFVWonhX45/7RrK0JagxTSSU1S2rdKjrHzt4@mbxfY51QLc/mKArld35lGmpebCB5@sbD0BWTcwZ7J2jMlUIN1ygs/V/Vgihgk4/0QN4fFaUqeYFogxZCVGjx5SaIiuIHmC4xRgs92wRl4Uky48uCDKFU7RTMUANc1jrgjJcM5FCJ@uSoeoOxvrLUdywY1zDCizV@@MDsxKJVBtLE2ks@j2NLmQwVOaBBhPbqqDhyPYHrlMLaRvlKcl6De4qShhlYXcmuwc4hQhANtQImcewpqGJ4aKEJsUgkq7w5lnukKQy4osno5nVzgtPFuOLAeC3ILX4CoAx1lbpbDXPSL2Ux1GNuBGtRk4TuoeR099pmPAbtVoAlGVGu717qTKAwYDi2kR2PD4WsYxBjWrooeicsiQubE0VWrZlgkGfljDIhS0Y2YJ6zlmTgC/maFHHblEapxzBS1H8OzQfyiimzLSGeJ7ljAxo51pUdMhvhwwZszKx0wL6tw2ivVVlb@k3XHW5LX5mLcBerV4eaFbrkIoePCQpeyMBi27JsXjF6i33BzmNHoIFJV6irs7YOJFgUT9L0r4Se52FKAqqRABq8WrB4W1sWKzUypwwIFjrL8ZrGb7vYzX4RDO5ErtSoAJMzu4nm/byDL7Ct/eHqfImojzaD98otqLEVfzGDFmveLxAp6p35LArbcTCVXaEK4489NjRBDgNdxBq@ymhhixOVfq3I5Yj9oHHjc89g4k0MytXhsIOoJPckjHnUNJ1XTYWjhz7fS4hdl0P5xzWgRVMs4lOh1kUTGejcRgNYz7d2uT5T9Cxp1fLDWHDrrr0YFGBgzcYbPPw7nLTX4SKCSWptXhlLdLgTW7DQYmM6KDl@mG4VZVM0Dym2XFDsh4DJYTIQ7tkfzpjNNhseLanhndufp9AL5l4CFg2PjouCGBtOjcgOfm6I5zxGBG/UCOa07IFqJmEShcWCEGcKcdAm9uMRvT2XSMVAkYTqHvI3ST9eoMqAn1Eh6@PPoKs6so5ojiLlvCB4dWXCOoaWzZPHEkIfhOny7HnIpN8GDtFXU0EkzUqYnzVw5tpOJonm4eu/07HZ2/TP05xwBKNtlCpu79GFDGhowrS@NK7mvCoruoH74oJkeANL9e0FhaTddLnKPT2rjZ5C4qu/OB8kiDK1QFcB01GTjZ4xERRKu@JWLN8zeMBl/vkRwab10BekaMeUp6YRexxs7gu9Ex4BCnjcVXL5rpO985StWNCYSetoAiy6bufM1iR0sUtZPH8SjN4PzX6zsxZloSGDzeShkh7IraIh2t6B2dsdb5HpD1GLuEpkBKPbQCFNayIKCmmJzlVEQmGVh8CWJEReDXfYAfbUtRZJFXc6Bvp3LpNwb4MosZMuxxvAGzUk4xdUSWGJ8iPan95HfVIstXkoQjDJM7JeREqI5UhHbEsGk7k6vdI7Ucrz6A7pUjq9TkVzXy9Jgtx67HNkBgvzlUDuT9ffZaVZJyEsNbmUltOeEgwNqOJjGFjijWmtLaJpMasQ2UYMdo6VjVAET38dKROXtsktJmNaIndrNLEPE14zRJ/5WS4Yx8QSreGfJcM/tFublVQKUxiEPFgRQ9HZ5Y/TaDOkAcsnZtJ0lRLQgKTiAXLrvYoBjR4k@asWOFkNm/84zW0XQWu5lmHxzbi6rlGOazaphiHi@1eA0AWbyEZJkpUEQHxKo4Xbd7OoKtXES6dT8VjY5qvlzoARuWbNVOjshox6tMNYQQVKjVc3AoelMWhtW9gs2xt3f15urNz893f/p8/3x3@eXuh5uHqzefHj9@ufv@xx9vP/3m7YfPD@9f7h8fLm@fPlw/PN5/unuXrn/64dO757uny3z98Pz4E7@6urr6X7jOr373u3/@N/z/y8W7i5/e4wbvbz7e8ft/1KXX5frm9vbdv//rf/z2@qd3uMsVfsvL3t89vNw9Xzw@XHy4f/70cvH0eP/wEvf59NMdHvUF1375Nl9/d1zy/Phy83J38fJ4cXP7X59xzae7948Pt6@X3nx8@iPfGr15uXkol1@@vS7f4QbXWTfQl9/jFvyBfvjW//@2fIevn29u7z9/4rP/9PxyefP09PHPl19@X67z9afPP15dxcLe/@H@4fby/eOny9fbXV1ffLp/@MW/r/7B94pFf/h4//SLJb/88f75ryu@/4BlVqzzN0nGxFO46ndv9T988Jdj63cvn58fuIo3f3nz5s2/fK/XZPmG7N3DDy9/vPzrW7NXb@6en79//vzAzfDE0nX8Gqd8/z9/55sfb17@zjdvPjw@X97H8@4fABX518eXWjP@e8JluMPz/X//YiHffhtXfffd9cP7x4/vyvUf/gzfkS/QoA@4Ss70FAd8y/vcfDrFrW758u/T9eenp7tnO9Dt/c0PvvxKP/@A33/4@IgF3h73kPu8OrP8FJ8eJnldEhd8d/MQB31x@fT2y9XvmRBwmjpvguLNy@U3L3c4tF99c30RV15/c/G7f/vtr/HB39zz@pv/fPjmiuejK//py93zzQ93/N3j868vcIWeeFx2hTvx9z///H8 "R – Try It Online")
The core of the program is based on the [Metric Multi-Dimensional Scaling (MDS)](https://en.wikipedia.org/wiki/Multidimensional_scaling) approach, which solves precisely the problem described by the OP. The idea is to start from a collection of dissimilarities between entities and infer the coordinates of the system. Some post-processing is required to rotate, translate and flip the solution.
There are at least three functions available in R to perform MDS. There is also one in sklearn in Python, in case. In the code above I settled for the weighted mds variant (function wcmdscale), mostly due to the possibility to add weights and to a slightly better performing correction for negative eigenvalues. There is a core function in R, called cmdscale, which could be used instead, and would result in a score of 5.77.
The code provided is predisposed to accept weights, as well as noise in the floored distance matrix. After testing, it seemed best to not use any of these options.
~~Sadly, the package "vegan" is not available on TIO. So, no live demonstration: my apologies for this inconvenience.~~ Works on TIO like a charm.
Interestingly, the program significantly underperforms on the last two examples. Adding noise can help, but it worsens the performance on every other test case. It would be interesting to find out what makes these two test cases particularly difficult.
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), score = 5.94258
```
#ifndef _GLIBCXX_DEBUG
#define NDEBUG
#endif // _GLIBCXX_DEBUG
#include <iostream> //{ and more includes
#include <vector>
#include <string>
#include <sstream>
#include <array>
#include <cstdio>
#include <cmath>
#include <random>
#include <cassert>
#include <limits>
//}
template <typename T>
struct point { //{
T x, y;
point () {};
point (T x1, T y1) : x (x1), y (y1) {};
point operator+(point p) const { return point(x+p.x, y+p.y); }
void operator+=(point p) { x+=p.x; y+=p.y; }
point operator-(point p) const { return point(x-p.x, y-p.y); }
void operator-=(point p) { x-=p.x; y-=p.y; }
point operator*(T a) const { return point(x*a, y*a);}
void operator*=(T a) { x *= a; y *= a; }
T norm() const { return x * x + y * y; }
T dot (point p) const { return x*p.x + y*p.y; }
T cross(point p) const { return x*p.y - y*p.x; }
bool operator==(point<T> p1) const { return x==p1.x && y==p1.y;}
bool operator!=(point<T> p1) const { return ! (*this == p1);}
bool operator<(point<T> p1) const {
if (x != p1.x) return x < p1.x;
return y < p1.y;
}
template <typename T1>
operator point<T1> () const {
return point<T1>(x, y);
}
};
template <typename T>
std::istream& operator>> (std::istream& str, point<T>& pt) {
str >> pt.x >> pt.y;
return str;
}
template <typename T>
std::ostream& operator<< (std::ostream& str, point<T> pt) {
str << "(" << pt.x << ", " << pt.y << ")";
return str;
}//}
typedef point<double> pt;
//{ Additional functions, for point<real_type> only (specialize for double here)
double angle(pt p) {
return std::atan2(p.y, p.x);
}
pt rotate(pt p, double angle) {
double sin = std::sin(angle), cos = std::cos(angle);
return pt(p.x * cos - p.y * sin, p.x * sin + p.y * cos);
}
pt normalize(pt p) {
return p * (1/std::sqrt(p.norm()));
}
//}
std::array<bool, 0x80> const valid_double_start = [](){
std::array<bool, 0x80> valid_double_start;
for (size_t i = 0; i < valid_double_start.size(); ++i)
valid_double_start[i] = false;
for (char c = '0'; c <= '9'; ++c)
valid_double_start[c] = true;
valid_double_start['-'] = valid_double_start['.'] = true;
// there are also 'e' and probably 'p' but they are not at
// the begin of a double value string representation
return valid_double_start;
}();
double score(std::vector<pt>const& pts1, std::vector<pt>const& pts2) {
double result = 0;
for (size_t i = 0; i < pts1.size(); ++i)
result += (pts1[i] - pts2[i]).norm();
return (result / pts1.size());
}
std::vector<std::vector<double>> distmatrix (std::vector<pt>const& pts) {
std::vector<std::vector<double>> result (pts.size(), std::vector<double>(pts.size()));
for (size_t i = 0; i < pts.size(); ++i) {
for (size_t j = 0; j < i; ++j)
result[i][j] = result[j][i] =
std::floor(std::sqrt((pts[i] - pts[j]).norm()));
// result[i][i] = 0; // implicit when initialize 'result' vector
}
return result;
}
std::vector<pt> normalize (std::vector<pt> pts) {
for (size_t i = 1; i < pts.size(); ++i) pts[i] -= pts[0];
pts[0] = {0, 0};
double angle = - ::angle(pts[1]);
for (size_t i = 1; i < pts.size(); ++i) pts[i] = rotate(pts[i], angle);
pts[1].y = 0;
if (pts[2].y < 0)
for (size_t i = 2; i < pts.size(); ++i) pts[i].y = -pts[i].y;
return pts;
}
unsigned nDiff (std::vector<std::vector<double>> mat1, std::vector<std::vector<double>> mat2, double eps = 1e-10) {
unsigned result = 0;
assert(mat1.size() == mat2.size());
for (size_t i = 1; i < mat1.size(); ++i)
for (size_t j = 0; j < i; ++j)
result += std::abs(mat1[i][j] - mat2[i][j]) > eps;
return result;
}
std::vector<pt> pts; // use global variable to print progress
int constexpr n_iteration = 200;
std::vector<pt> solve_with_seed (
std::vector<std::vector<double>>const& distmatrix, int seed
) {
std::mt19937 engine (seed);
std::vector<pt> result; result.reserve(distmatrix.size());
std::uniform_real_distribution<double> dist (-100, 100);
for (size_t i = 0; i < distmatrix.size(); ++i)
result.emplace_back(dist(engine), dist(engine));
for (int iteration = 0; iteration < n_iteration; ++iteration) {
#ifndef NDEBUG
if (iteration % 10 == 0) {
auto norm_result = normalize(result);
std::clog << "Iteration " << iteration << "; "
<< "score = " << score(norm_result, pts) << '\n';
std::clog << "[";
for (pt p : norm_result) std::clog << p << ", ";
std::clog << "\b\b]";
std::clog << " (nDiff = " << nDiff(distmatrix, ::distmatrix(norm_result)) << ")\n";
}
#endif
for (size_t i = 1; i < pts.size(); ++i)
for (size_t j = 0; j < i; ++j) {
pt vec_IJ = result[j] - result[i];
double dist = std::sqrt(vec_IJ.norm()),
floor_expected = distmatrix[i][j];
double ndist = (dist + (floor_expected + .5)) / 2;
ndist = std::max(floor_expected, ndist);
ndist = std::min(floor_expected + 1, ndist);
double delta_dist = (dist - ndist) / 2;
vec_IJ = normalize(vec_IJ) * delta_dist;
result[i] += vec_IJ;
result[j] -= vec_IJ;
// std::clog << "Numerical error = " << std::sqrt((result[i] - result[j]).norm()) - ndist << '\n';
}
}
return normalize(result);
}
std::vector<pt> solve (
std::vector<std::vector<double>>const& distmatrix
) {
// just going to try some random values of seed.
std::vector<pt> result; int minDiff = std::numeric_limits<int>::max();
for (int seed : {123456789,987654321,69850,68942,4162,12012}) {
std::vector<pt> r = solve_with_seed(distmatrix, seed);
int d = nDiff(distmatrix, ::distmatrix(r));
if (d < minDiff) {
minDiff = d;
result = r;
}
}
return result;
}
int main() {
std::string str;
double sumscore = 0; unsigned ntest = 0;
while (std::getline(std::cin, str)) {
if (str.empty()) break;
std::stringstream sst (str);
std::vector<double> values;
while (true) {
int c = sst.peek();
while (c != EOF && !valid_double_start[c]) {
sst.get();
c = sst.peek();
}
if (c == EOF ) break;
double val;
if (!(sst >> val)) {
std::clog << "Invalid input. Stop reading.\n";
break;
}
values.push_back(val);
}
if (values.size() % 2 != 0) {
std::clog << "Number of double values is odd: " << values.size()
<< ". Assuming the last value (" << values.back() << ") is redundant.\n";
values.pop_back();
}
pts.resize(values.size() / 2);
for (size_t i = 0; i < pts.size(); ++i) {
pts[i].x = values[2*i];
pts[i].y = values[2*i+1];
}
if (pts.size() < 3) {
std::clog << "Need at least 3 points. Ignore input.\n";
continue;
}
auto distmatrix = ::distmatrix(pts);
std::vector<pt> result_pts = solve(distmatrix);
double score = ::score(pts, result_pts);
std::cout << "Test #" << ++ntest << " score: " << score << ", "
<< "number of difference in distance matrix: " << nDiff(distmatrix, ::distmatrix(result_pts)) << '\n';
sumscore += score;
}
std::cout << "Final score = " << (sumscore / ntest) << '\n';
}
```
[Try it online!](https://tio.run/##nXtpb1xXkuVn8Vc8u9AlUhJTd1@sBeieXlCNQc@H8QANuAyBIlNyuqgkm5l0SWPot1efExH35SLKrhkDMjNfvneXuBEnTizv8vb2/P3l5d/@9ofVu/XV8t305t/@55/@6X/853@@@ed/@af/828nf8C11Xo5/Yd9Xa6vVu@m58@P7zv5w2p9eX1/tZxerm4227vlxYfXuO3X6WJ9NX24uVtO9vtm785flpfbm7vXe1fw5Gr9/uCKDbZ36eLu7uLT/oXLzfZqdXNw5cPF9qf9C3dYx83BKJcXm83ybrt/6Xr1YbXdvD55/vzzycl2@eH2@mKLy9tPt8v1xYfl9P3rE6zm/nI73d6s1tvpV@7wZMJ/308fn02fXshn/e30bPr188EF3OOf4c5P/mz6bvo4nX70Z3hoOuWFw3tvbpd3FxDN01P9fns2Xd6sN5zxbrm9v1vrfacfn94uODH@fDp7MX2WIX65WV3tRni1G0L/@3X6@PQVHnuBx/D303jscObz35v5XGc@/@rM5w/NfG4zn3995icQ1IU@8vDMTy4w75OLsxcPTPrk1e7pedLpyavpApPa3892Yuubuw@n@7dOD02Kp/HvKZ@ePu0evrrZTtPxBr98@Am2y4ef7G33@@ny7maz@bse/jSdy8Mfx8Nvb26u592@MhG//P71dOu/OKmPr17desz/xz9On@TjpxcPDPLNbw/yzXT6ZPvTajO9esWfHxrh5eEAY4STsS8AxunH6Rs@v/h4thPsS7nwYr7PfvikP5g16XwPGaN/LT@NVUy2CP@atne8hn0V4j2nVN6zMQWM76v2fvXddyvFoD/Oc73GHIe/4O@zMfrrP0632zObHD9MuP12i4PQv7YxWxF@f3Hy@Tenvzme/uVLm/7mwemPZsfd355@yz@yCH59No3vn@T72bcPrElREIuhW9Cxr27u314vOQEERnT/x6ur1XZ1s764nt7dry/5cfNsejefBlZ3/YZjvJ5u1tfAus3t8nJ1cb36v0u5SwecflreLc9O7MvF@v318vRWTOPXk0fzmrDfi@3FOpzCLLBZqJIIDjfe3WwhOXnk2bQ/igxgFzar9fRKh8HHU/39GRRlMy7jo11@MU97uz2lCT@R@84nWuQTDiUL0I@wb72MW@YlEVxkm19s5BZ3nvrnupD/uuP4ikRn8rBIXTdLN/eSlvZsch@be21K/QvGvXqju3qz2V7cbbGBH348PcMcX3nwy0ewQ8r/dIMlvtlOKwzhXuDPywfuXfCmU6D806ers5NHj76844fVjxjg3cX1ZjkGvvzp4m66xNXH7vELfHiJT/0xx7j8yhiXHAPulUM88PPj88e84aFfFo/3HgU32VKfpgv@u97cTI@Xj4WG3N7dvL14Cy18fPt4enu/5X2f5LY10PxiO56d3i7f41hv3k0XQ5sw6/1yUnYCK7m9W26Waygd9H0@2IeE/BliOxmKvbkED1LDVebz8nb7Ws6UgLEBOfjqb2FfkzH5/fVWTuyrp8jxjs/Nnnv6Co4LP/PQzmVwfDozJdxp/qnd/nx/LNXv/WXufzZ4eD1dARfBwO5WH6ev71e29LtD2Sq4YlvDoZjsxr3fucjfEMuBVLiEg3t/1nt/xr0r3vIzBWeSg5h@@JmaZl9//lH0njfIit5d39zcne4Mm2uahYy7z/YM/fnz/VHFfDAt9G8FN7C6XG2nv/60XIM0A14VLh/r7Y8n3fjJo8/zUekvXxwNpL3DoS8OYj6CY1H5r4hq7OaVfHI/Qsr6Ac/86gA18KKP9tEX188nwJHh@eYH/@NDR/M7873awTu/P5tmiNYhAb1qCaQZvBR46eXkzo6OlnOF35xLhjofn/edwEaEe7/erN6vl1fT@p9X794dSvRB5YUNHFn1124Ls@Na3tIh@eW5d3I886QHZq/ByyknsJ2QoHGgnaV@TdJ7D83Y8PfaANFDnczbjcxuRnEuc@uXs@k1d/Hi79FPipZqf79ZTu@vgc/XwNG71QUlsb0BZAtHvrt5jzE2Jyf8Jgiy/Hh7N63frLZkREBhnq2DYI7H39xc/7J889fV9qc3myWEePr7kGMItcOwZxOn5eMnPBEb4cPW9x7rtFy/Z4B8yt8p9OMV2Obt74Ke4@6X5elu@L0Dk2fv1yucxoc3wp14290Kzgp7nOkXL06nUBBYHf73G3j3xSxHzmAhrPNy@ebtxeVfZE2nuh@g7P43ejGdg6LYlzonmr@@3D8SmWp8UaQdSQbLJjwSm909/g/YDdVYFf/Ro4t7qMBaZWG6v@NVeol7N/i9vL55L2z2T/OAwnL3locfX0zf8gl@FH@MMeUudc57kz1TgMRPj/@8fvzAND98KxdFKiR5COr3Hj@bDu6@Hbz7gYH@/PbPb3/8lhI@/mU6VaSxNcqX033F/O673bf9xZ@dKa//81om/EzZS@rmAUz8Cv7Oe/sqKughAYbpkt786d/3PSMAYXZvsuXhGUR3Bw@nl9Rnh2t8JveKJ30DG4cZwWhf7emxQszBkGsbUyQDNn569PjTaZEhkOdAf3lsvb@GDxcfj@5/pgOePXQzAocvBve7Bw42urzeXrw5WNq53bhbyiy4nV7rpTNECbsR9OZZoARhve3gh5/FOY8fhGIcK9R/3H9Y3q0ugbLLuzsc7lD@HWfZTXK@O82ZuYwtHJjF530u8oCBPgD7Asv/X2AsEEyi/vM9lvH@hoQcKLG9@4RBETRrok8J@4Ycnri8@DosE89wrGZmctdahfRG04Evccdr1ZMZaIc/gMn/6kNMudTWn/VWS04x@Gelt@yeldZTeJZ8Cc98cD58Vov5YiWc99BNHdj4cCyPOCuN4Xdg4O5M7wa0XtHb6@bMWndbvXqx59VhuYYTD7JKEdIFlH/H2S0WklTBHGLffxiYCqTYsaXtcjN4y19/Wl0PLvp@ub2Gc9Evl4ypMdqZLnQl9OqO/mn7iYr3Fu7wLy@G@HR2zX5MG3pDPvriSLrDX6oy8FebnqGiCUQYBU9gs13cLpd/OVW7txsvmbb6l//1r8yhffNgzDpQkM9jQ/b4oweG/CzTveOgr3TQvV092gWaL8Z935xyZ69l/WfzPIeubi2Lghbf3m8X0//e3tzi3C6uIJyFYf@jR7tJZAkqjcXt/eYndfscfngJzms3GK38hylQCMMnf4Enb5d3NLP9QHkzrWB6V1ffKbocjDec72L6xw30RcwXIff1hWY2EGWf7j8kCzRnxlHvllf366uL9Xbe3tjOza3uxrZyQse0Id0SUD3YEuBX7vp/CRIfWVjwUXMQGO2H8MR82170sPvpqf9xXomFJmP@l1N8WJqElIvtdL2kNKLm0DaL6U/v11pB4SGPfQMZt6u1pDx0EmFLe5H3q0NYIJsRD/UwEr7B7wOI9rBFH9lPYMi4ypbwyLO9x3f2d3lzLy7i2@9p@X@QA336VHFAeI08/90e8xr06ES1Y73TK6DV8m65vuT@ZXsX/Kyr@@7v4kV7KzzgczNcMabhhxcnIsnDLfzritnNA654Oj/5XMFtb1gM8Le//XDKeBgc@tQtXCqtJft6nhauxF74fdFDqKHJ5bhIqUUwifOyqKHUWuSyW4SWYs24jturh1s5@/Fkf/SYa8xhjO4X3vUKBzT5Re0lJC@X6wKeKJWKYeLCtVLcmLUmVwou@0XGTCUejF4Wzdfq6xi9LFLJ1fH7orocXJfLYUHvxmHiIgTOb5ezd557aovkfM71eOk9FRf3BNNrghelYHINOcnlvOg9NC87Si1321GAlBJ8reyoh9xaOVp6aQXDzV9da67L4CH0JNtvi@Dhm7n9tMgVMs8mxN5CaXK5lpTzoczDwuVUQp73UXN0nGiReo16cAVD1B5xLtiAbwnCt3tDLbXIZVdyCOlo1aHFmvzuOCHtjrEhBaxadQVyRaSbsXWcT/LgHiaR0hNOSw6zYV/9UN4QH6SUxmHmRcb8EWNXbKD02O0UsnOBoyRoZDQl7FgrlTAuwG8qzvfwIEtsLs@LDotYI7cOgUSIV4XaFr50H6Nocs0NR2aqGVxoncsOi@ZScMfLhhK5lHYiwUoidRKG4mER1SZN3vfMQ4Oy5@JMCRO0LOeOtWN0nEM91HDcW6OfzQc6ifm5GOhXwnq7zZmcKCqOA4Kqdi@PPVbZUOCJ5GHJ0EeXZSWhNiitnhpsoMXEoVOPmFZl1713Yt84Yg/VkMtJjLSMy9CTomM0sMhWqQ8J1lL8sUW5pOY5aw@WIicBret1LNw54IisO@biexpWDAH2yFOO2JrPKn5qJDffsZngWzA9jV0GgHUEX1WUMIriEg21YaSUDf5gd1Wl5KAMMc/AFmStZZGza/1gJ5HrrW1nYlCcVMXGCIFjCN9yoB1ASMHh0KuhlIuhJo4MOeN@VXefsP6qUNcAgM1EBpOQiXCcAbij06faxTZ49BXg1vQy7KS4QEDzGeg1rwO3NFEabKrUY4hOAKrax6lAut43jpEbsDuZlCrMQ88EChjL0BlsMYml5wh86nokPcck0AaEpQzstAvwvqk4SoHJmoYBg5PoAM/BpaF2vcfMsyoALW/qBW/Q7GBd8jHko1MBELsWdu4ALqZw7Azbit0H22CuvTez6Iyji8OKIGnFLQgstm6yjnADPJiOSUPSFVaYffW0TKyqwMnlAU/VZ26SuOBKmPcesJTGyyHm1KqtBLv0UXxt8xjkELiymGevOw/UgSA90QKyB4aN84XR@SjwByB3weQaC9atR5bglpKeDbwxJYh1ACoNQIEDDaqozioCKHSPuN6DL65QgDCB2ob/IQQnhcqcET9Gg9Dea1Ynjr2UWI/8Uow@9TQDZ4suFgoQfsEbDGc6D/F5MAPfgdMqCQdXKCefcJSuOD/wEBbvi2pEiSUOpxwcXLW6NwAs7G14ipCMrbjugG3DQjpWJgrhW8NRDMHG3NSsiyeSHO0HStRi3hkORiwkMXB1uTQ/U6Ti4Uhl9Azcj0O4MWfyhnN6raA78sSPFjolHmGswdt@sPlEzabDoDF7mxL4Ai/JKSPohEI/0A/o5kUJ4US9TghliymL44S/weUjN@Zyb7HtPA00LxVP99tAAs0AYV6FluPo28xCRPQ5N8NQIkU0bwBhcuM8VPCNNjAD6BC5Dg/ParoD2gefRFWjlKCtSkiga8FnQI@evId/8cOisIIkO4dCxyMyAYWJRaDQzQYIyPQK/oACde7wGQ0oJzgTAD5j4SAYjZ7iXBDMDybg4BCceMhAauJV2D5QnrJA2CtolckTXkx0ygPD/ezb4ELFRAhmvNskBaUXJ5Qh2AakPYJoGjvVfHBHT9LAVcfSQNbHMYA@CM9ZyPnPjAk2ItZaoX/g@lnVIYK4eNOoDmnqVfyc6JzohqD9pqzQ7QzwVo8DTey2SaBNSqIkGdqglBiqCKG6zhMGYJqvIDmHOZHfQd8D7zZPmsBGFP@httW8OsKBJhQXVlaDXZbjAJ/UgICUPQ4Dhl5G0TSfQFf8MfBULnSnDIgGopNThxCqHboHl65RDyxXALa5dmhdEH6GW9Mc9wANg09ivWCRsZu7bjDarJoD3Bl@C0ARvQVPxXv14gS4mrvYOnTFmGIjjiV1iB18STUkQWQtRJE0zBxu3k7LO6E0ieYQNGoChkD8XpYMWBsMFLoOvM2K2lSU7u26AyybhVENj7xqpvIBiWagABK5LDQqRToz2wuOxcsJgJaaY8FBA2eKcHh4uqQIIEbgYpQwDaGm8TPAAcOQJsvOwOloauMRKTRVX4jDKckg9IEDlkB1QpSE@@126Fv3whJBp6B/MwdKUXkUIDP5sRJQnyS8BuGEx6xdt9x8Fm33DDKcaRnEQ4pu/qBjxEF3qogbZtoQH4SjkAnutO7oFWhVD4WuCb4Y6OPKHLo6uQxtBSHT0LUteExBTCnXVr0hOWiwQDmW5Olok94MqtSrQmjEJyVeRKWgJAhmbjuHiMFw6IuJD3A@1XgXOJpTiEPsMhO6RnJukRsJRDVUQlhWlY7gQMPwSRB0oVqLeyI9MHIWheedSxAecpnJPsiLRpwgLIidjoEcv5a880vgmwKFnVZVRqQcYY5FiApIhgIigmNYV1GeB7dUnW0dEKf6C4GnNNAJcU6W9RVxqt4C4tDJR9S10YuNsA1bBPKKSAJAKRluFQTTYqUdDqTuWAq4alVCDFHZ2RZ40KQYB40oacA4rCA49aagESEYuYeOSeaErBUsoQzCUEBVVX6gaAiYjtl9rDr3oJxwUoRKsDWEpNWioEo/KAoPRpqN3SNmFLopOZ@YlCcDACJUrqikPCIHA3JyOxLiSp1UgCL7QvDE6chhHKQzHAcgvYir6rgczPlAiQL9GpknbCYMnMQRFMFJEN1mrhTHh/MtXSOHFr2tDmIq1YIu2LYy8ChROQNnkmrn0/D/kF5Sq@tAsxaPAgrss8RZFWH7LmWKDkFuqLY6oKewWoIMDjENggJpROZGYICAKmVQJLJwx16zMXnwuAbrL7Wp6YL0xj7DFphNVmyBM8izu@saGFBFQKzMmODTI4ISNVS6WLXfwNiyJyGmiIZdHaElo1MN1keQDRSEI1IxAeLCeB663tTZVazZG7rz@a6xDshbO/S6wBXJqg3NQ5AB3uCrclVEuEZ9EF65qgnBEo1YgG6QnYuRIrIJftDgFIJ63UyNha7oTjICe8t0gL7HmRDFCnHLgcHuSrG7AWV06NgrkGDMJ9yXwOndyOB10kpLCNW8Y6SVYYwKGQR2HDiZQhLfz9wB1LSM9CogM2hiD07N7I1EOmncwlgZR3IoOwB8mFNWlUG@GAb8PAK1kRtwCDaZ2ZNIhXHLCDiYFVRxADOaJVNhxAm0NVhiBTTdMg/wGkN6zH/0geNQH5iE2DmoedWES6IyBPMFsLoyAt/QLUyGZoMopTLjapbsGKTtcuwjyokaMIgIRx6L2Q7QQclUOJKqZASkiasi8oCJeFsGNkbKTK9c3BFjBh9lTJlmFOxNSQRRg0kLOwVoeNWkK6L1ZKnRjBU5XTJIfDMpIZoQKoPlECFHHiw3iVqosaCxbUATTNj4PEPybPsA@Sec8CjARwfvgZkUsy7HHPqIPrHVUCRQYqJc0bcoW8uScsHIChRVwtaiUTMWopSPIWSVE4zid8xhgPmWIjgN/W@hPpQsjbMcETbF1BQkCjz7YCuYJCWLbnLpFqbjVu@7ZH57tHwLOTnAoZqLd6FbmAATj0EDYMAcLFBnhJv1SVhFx73eIIjUwBUNeeDBRh6MXjgPhxFjscOHe7RMU6eDyjPv7IL2nWFCn4sMsPnoZEaGpnOuoOEQux44wLeMxKfkpfgrwqdu0MbQIWtGHlGO96a4HjeJmjcqVZ09fGUegFJiHDJjPaQYQ7d8Lc5oeOESmnGYxmBq/7g6JIDIJ@9S/w6RuBgQ4C5mc344ukyPXaClaU4dwNF0zT0V4OpIJTsWeiSuDmwV6KZ1oEdenBmcZ5wTJJ2hb6VAQVnCXJ8gwXISnzZCy8AlxFRClEVpYvFpiBTnmZUHgZT6OpJ5oAvK@2sacTW/QMUke0dCm5kEHLdbcIOwydK4UCFmKTSoq212ziwpJEmFRIgrxEEzQsp6byeijNQTLDzoqpnObBamJctbMmeEUM8NVlKZBJAYofajjBEon697sUBl5i7TxWiCMoy0IDhTlSlhR5BUMNMHfLiidRVmZ2whgDCXFdWxoqqMrvLMq3p3wBVwZ9iiU5dByIijjAeEYZJAFgJ/3MNwda73kUkHn4Am7gitMCE6ktTySCNmkmWv6X@iiHnnUiR35STP1Uf8lkmENFsItXZqYPTUgDdxzzjPmscCQ4I6VxM3nac5EkTWSdMSIMpxBosuCW9PVl97GvlG0E/LsOeQLB1P2gzt10wN4Aak@Ch7AHcWXNnLKsPrakEN4XcOI0PS4C1SM68bgrIN5omh0aquUKpk7LUi8gULFVnB0XnDSgYFThbD/FCwmIokD9grQkGMkmcaCLBKUcsOYHXDnxB/VF9hhMP748mILauoMow8jsRCc064DyuvwK7hzwXzoq6vWejOYBzKVkR/Uh9ZOtgtBCemEyR34oxVZc@yh6TOPYU2GyVWGBUW/bA/MiVSZo1kEqK5NBKTiPO86iDMb3gJoFdRpwkKD/w6irpBXiR9aXwKxCE52Y3vI0/KFHnPeTC8AVQN1hVKErKAQHx2Vx78VeyMOUlnHIJSA3en6Wgtr2hcBoTxpVtqBljiZ58ixUt@ymlUDZgZj5p/Z40M8DEnMxJLGOKZcNKjJodBmik9dNer12NMVWQ3jEKx3TE2uIPrGtjmaFlYZpxSaEFN1Vt6kp4wOKuMUtbGksAmk9UunMJfX7BElSzqAVONZS6ESWaSh8V8nuXW4KRyFoMEah4XrDu1t8yRQmbRrjXJ7GQc1eCGpXlJajM95MKAORyhyIJUDFsqg/iwYCAaFkCMVMMYjfosiTgcCg6ijP4Ali2ddR84u5vJergj9UtQ4zRHFRBH9JaRJvqVESvC2IrMCd879IOBW2hZU/SAImsbaPATQTLPwBdGLLuSg1NZN@qeNz3otA0tUGQmcUzahdW3KmIFbamjhAIod04zBXQ43fQDvjo7CT2ZAZkRBw48FdU9EHjfxyhMtHr1Td4fdV6wmNdLLntFw5alhAIvBQUoIwjGhN0UG7OUZkvp4DRVwx/QeDcUG0NIIJKI8VmJESQBxCuaPYF@zoVz6KfT7eAxZxE90RyUqGt6DW5lFOAQATtrMCFD6gP9GNlIztHBt7qRxWGiv8lRdsLFCP8lNaZqZFI9l1RgtHweZJBnnQIFalUrmBCWcR22kDRhYoBMl3fUj8GmElby81Hyjqw9W/KppjimbMCcqGWs0gacsboL/dIkDmTg63EyI4D/7qwMIpPUJ@vNvuZh7Ax0s3JhZkrndBdgpDNocJm5bANyphYtowxibM6a3EO6QpQo1GJpabafRsvu5DpKC1Io7UF5F4A8lzhKAN1ZrQ5RX9ewPIs0o8Q0bHqYi8s@4Ew0SPRMj47uCkhNQLjH6maOFhIi4SQrifAzBmmeVFGhJOY@JyiBDEr0QEKA2GFUi5kM5CFk4lFTc2LaVLgBmQcC/BEPAoIlV01BYnnNlI/0VXQPgonHoAhSHMpeX1ZBxBys@6j0Wc1wGlm9vUd8v0cNctWeEMRLeS/rm1zWtBvYwFydjimKJUEnwkzucfqS3qEeMpc04iLorZ4jNQdCmHNVjtVNZlvA99qc2G6sFwnmwpBHK4ZnEk6aXgqgPs81RxfVO0YQKLdT9xC8Fq1JaIwBNPagiKirlNpGWIORi0aVNJI2ztwzM6uZNILLqDlEBOKSAWiBt9vBICDK2tbEErQRABx@DkoAsEwWKI4S/T5Jgna0GSHA8lLtMsUjSIIVd20OgCzmhBJbJ5J1GDFPMRoPfOVO6LdTnlOFPHCrjDHBNmoT8ENSJ8UYrG@MQ6zEtWZxkXEZKU6BDGv6n3nskc5IEHVSLgOf7EZRutADZK17sKJkNzPdZVXSWKx1I0kzltkWgEx1Xf1dSVppdXEUBQm7NfRgmA8yO3o0HBaSpXIE5WkpjNpTExii@QFiht8IsUr2g60QrnQrzCJk7Fn9d2MavRz3mwEyWt1VFopVmpm/K/PYYBc@aJwHRhwGdQwB0biYIyhYta1nqZ5KQyGCsjnAQAii1V1cp9MfeyRWaPIZB1ZG9S46pvisL6CFUREt7GMwa2SaeUALeUyWxAioSy7DlBKUVauIwKnohguL2vGIlUDYuRnhTZxTS/KMydo4GwCwD1YwdL7aIQA5gnQqFRpKm50Y5rNGyI4obwgqMTgWYoAgp47SUWS2XSCngFP2kYlByGrZJmHYc2G7ErElFdPAw8xKm/BA9SdlMEKEGsBS3xQSAS4zq4flZWsJ8ayltZl7J4m4SOtrOdISo0F@1@kF7qBmBv7ripXNmBTyo8PDDW1lL6rzqvLUZrsX8ovCF7A4QzPoVifHFLaV1QiEFYTQlDnWWAYRTnQWUuuCT0lzJFxKLZIirpEpu9lrsClOejDYQDajYYiR5SvSqLJrpGTCsIqhp7zrx2NYk7TDAaZgjQ8azTe1fzhlSwoRXosMrcmokQRgrauYx/XWjSQBd5CMXKSDtkqwFFL0wMlgEf2VNpdDorOeJtaNRviJqD0lI46IB@LoKQGFiVErkWybLKNMAsrXkzEO9nGN3Fdky6lt1MW5Y8WxN9miNqhWO26dAWrl0PdaT7ygAPNW1e88cs/BMKq3OXPIQMEaGjqz4mbtDCqddWcgXI5GuDzolHYsk5zFPvdRwq177Znyo/GDDbdd@sIIQfBcvc0Nba0ooiE0LXMOKLsilIFrRaybwswIG@2DtR/4YVtgZHpA0u/JD87G7AQ4nlIakt65XBUsv4dQvRZL4ANFmiYJsZNSRlM2vLdremZA3hpGvE8DktwXGEBoZndwQBq4EQLS6LxkB3TWlisulO2NQyEQiQXtc6v45OeSKxA6WlqjwiMNQu1Y5hWkYwuJG@4GfkrVgYXaOgbJZMZa4a5czTH/hr@MeU7@kYBnSVF4iePa3GkZhA1LG8fIC3lmAoL6CrYsj1MA@0paBMH6Uk3zNpkvFe1xtNEZOSI0X/NF8Kndj57vLH6ctV84k3EQwDTp3D@XjFKcY1FAp/PWZYBIL7bRCgRgFj8EupxHJo7JLCfHBkNozugfW7ttRqhinlsgghNqQzwBMI5MFFyx86KAIPZFyWKnqkk1UZs43Ojipp@K1VoVgmVrqR5JUxti8nNbHQhC9cKSM1OC4zIg3Bf1teSnfe5gr@x9VWMNabSokGg66UyW/F23NCRdGzFKlxiphyNn2cdKOpMaxzQSYH/QxJqj9pwgyHV2lFJpab5pZ2aoM7JVxuHWZQ5kbYOY@Ki9A8QkhiIjDY4ISxvnSQjnrhh77UCcd6qjEQqUuBibypY9TewL69p4Ad9tEUXgAVt5OkKJ0ojGAGlJm9dh5LNqNzoSiZRbKNZ8wHaRpH1/gHp44DoS2OxEqeI@gZAuzDhaeNya3OAbJjPysFdCNJ5doGmuI@OYujZKuzSXRBD0h5AtHzjobxTpaRtoZgu2lUTAmYR@0D9ihZaSIQmqGoNLLWZwS56/FogA52apPEWWh0WouOZnP4wwIRlPw5OApqMiXWDnRpmRxcWiSApcioOmsTG8SbtdduxQmltdm0Z18u5OKxaLIsCWNhGIEowszZABq4nBGmwBNdEyuywuWJLZJ4b7lvTsTNDQ3B3o5ZAUixwlG4zuwsUK@PesHbGaYLUP1nVrs3YKmGGfc3QssWhkTeWZAxkGe/bWhqe8R82RLxcVad93pFlW8O2O5FVOEmA0F9i0H1/qbn7XpQa0TPYiVE4mJhhV8xoguVjnlgLW4EJTv@z7aG3gWyvdivzMctkiGJcESUowpzsnTSr5abf@HgtFYUlNKmkMJ5l9sOxtZpomqL@CX/ziRQu2loSy1zTF3nvJIzvA0GgLgdLq4Im8OrfZOrq2FHnpSx2vBkGLoloBrLTuXi5gXNckx8/Td3UUfbT3SgqKYU42smsua/cA@Gq3cKXSfWljh/QGRD8QIwNHinIH6GrpJhUgTQmac4NYw3h5qbBLXPhOZpNfHAGBVknICyrbjnZRRR6qXUe6W8iDl14ySoKZ6fHaBhyV5jIpl1F6Z9oF5qc9C1i6nzPeXfqN2EcBL@2sWaix8Jw0WRiMf5Aawt0lkSE0oo8gqbFOLO4QwaR5MiAWVbhpPiVaH53oWtP8KxB59woKMcgydE6Y4SFzxdIl6hg94N1HfbuIby45S6bjDKK34oSHXc/NGjhg6/hgS02dy/1k@Mp/WdLOGn4xgRSLZZ9NeFFava2XLLMUXucYB8BstSAAgqVxC/tmJIfJaUA9Rms7DkaSDmwn7kE7KBoLShY/ScvDKKo4NuIYf8vAo7pHHbTfAqfRhreG2TWL/x27HAdogDpov6vvVJJhI25UoT2rEUPVWMISIglukfPuNQVsUtGrSQtgHJUHAEGQHo/GosJsaomvLQnnZtJ@4Hy0DnaKwI2KP/tPzN/AWVs6iNFe9dKfyN640T4FFJB2CeJjPX4PsvDVQ0l8z@@LAuKKNWxnhXNWtqMV6aD5c5WJzdia9OGrXmnkqvhupIta1oqlWjyP8FTzCpkvdfU@J1qj9thIqhja0uYuimYsUtI7o4GdSRxdCd/FcUNbEf@EIhnslPmuovWCsu5mLY6g53XoQupdc/qANGuCiEzaCX2mmfJVq5GfZNNvFbOBUGOytltszRv6Z2anrZ2AOeaqUQIktXsrrzmvlVXGPSXP1@E6pdCpb@DOqdJIkjMMG6Psmv0RUUpgn4ENI5AhFVCFcsnPr1iB2Fp2J7qoBCEwCZKjAhfW0weeQw7eao5gLP3oxVAnuay5VdLT6TYnvX4w16RHySYHJp0s2E1Gxzo5YjHahfDV@tIqDLxFBTqq3NgKfHy2jTOFHYdncezNCBaWtDqfOwMj4ZFQZL7gaclcmpLWCxwB1XbJPHLq1iHnrfWWL35oXRWeLpTxCgYjZKkkwnw0WcgUISgSoze@UgV6MLeyON90DQzp0vxqqTRPjNf46mBRbKr1YjVdWm3nvmov6aQoRcL59SJwj2Bpac800VxLY81EWU1uxifYhAAU0VyuBOADL/h6tbamMeSNffQdghWMVzHjnJhC5B@1KzUAnrwF/7E346ysM0M//hs "C++ (gcc) – Try It Online")
The main part of the code is the `solve` function, which is given a floored distance matrix (as a 2D vector of `double`) and output a vector of `point<double>`. The rest of the code are score-calculator.
Idea: Start with a (seeded) random set of points, loop `n_iteration = 200` times the operation: For each pairs of point, get their current distance and expected distance (which is estimated to be equal to the distance in the floored input matrix `+ 0.5`), and then change the position of those two points to an appropriate position nearer to the expected distance.
For this program, the new length is calculated as `min(max((old_length + expected_length) / 2, expected_length + 0.5), expected_length - 0.5`, which is twice closer to the `expected_length` if the `old_length` is sufficiently close, and force it to change such that the absolute difference between new length and `expected_length` is no more than `1` if `old_length` is more than `2` units apart from the `expected_length`.
It also tries multiple seeds, and then pick the seed which gives least error in the resulting distance matrix.
] |
[Question]
[
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]
# [Python 2](https://docs.python.org/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!](https://tio.run/##XYyxDoMwDER3voIxpkY4jJH6JVEGN4gUqQkRYqBLfz01MKB2sGXfu7v8Xp9z6ksJ9xfHx8A1mzgltQ8DzEv7CSpyVidtvNmfyBsqQrh5a1rt0KO32jjARjLVeFUFKen6kpcprfWorNUo9mM7qC6ZUCMdiJD@rh@j2E4kcvkC "Python 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]
# Octave, 26 bytes
```
@(a)max(bwdist(a,"ch")(:))
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNRMzexQiOpPCWzuEQjUUcpOUNJU8NKU/N/mq1CYl6xNRdXmka0oYIhl4KCApCK1QQLGADZBhBBAzBEZkLVAFVABWM1/wMA "Octave – Try It Online")
Explanation:
Computes maximum of the chessboard distance transform of the binary matrix.
[Answer]
# 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"`
[Answer]
# 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.
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/123878/edit).
Closed 6 years ago.
[Improve this question](/posts/123878/edit)
## Overview
Given a 2 dimensional array of values with a filled in rectangle, find the position and size of the rectangle. Do it in the fewest array accesses as possible.
## Requirements
* The `x` and `y` values in the output must be 0-indexed. The top left corner is `(0, 0)`.
* The output should be the 4-tuple `(x, y, width, height)`.
* This is a [fastest-algorithm](/questions/tagged/fastest-algorithm "show questions tagged 'fastest-algorithm'") challenge, so do it in as few array accesses as possible. An "array access" is the use of `abc[x][y]`, `.indexOf`, or `.contains`. Getting the bounds of the array is free.
* You may not copy the array to another format.
* You may not store any information about the inputs into your program ahead of time. That's cheating. It should be completely general. The inputs are fixed so everyone is on an equal playing field, and so your program isn't given a bad score from simple bad luck.
* While not strictly a requirement, to keep track of "array accesses", you can have a counter that is incremented after every access.
## Example Inputs and Outputs
Given the following 2D array
```
((0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 1, 1, 1, 1, 1, 0, 0),
(0, 0, 0, 1, 1, 1, 1, 1, 0, 0),
(0, 0, 0, 1, 1, 1, 1, 1, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
```
Your program should return `(3, 2, 5, 3)`, specifying that the rectangle starts at x=3 and y=2 and is 5 units wide and 3 units tall.
Input:
```
((1, 1, 1, 0, 0, 0, 0, 0, 0, 0),
(1, 1, 1, 0, 0, 0, 0, 0, 0, 0),
(1, 1, 1, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
```
Output: `(0, 0, 3, 3)`
Input:
```
((0, 0, 0, 0, 0, 1, 1, 1, 1),
(0, 0, 0, 0, 0, 1, 1, 1, 1),
(0, 0, 0, 0, 0, 1, 1, 1, 1),
(0, 0, 0, 0, 0, 1, 1, 1, 1),
(0, 0, 0, 0, 0, 1, 1, 1, 1))
```
Output: `(5, 0, 4, 5)`
Input:
```
((0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 1, 1, 0, 0),
(0, 0, 0, 0, 0, 0, 1, 1, 0, 0),
(0, 0, 0, 0, 0, 0, 1, 1, 0, 0),
(0, 0, 0, 0, 0, 0, 1, 1, 0, 0))
```
Output: `(6, 2, 2, 4)`
Input:
```
((0, 0, 0, 0, 0, 0),
(0, 1, 1, 1, 1, 0),
(0, 1, 1, 1, 1, 0),
(0, 1, 1, 1, 1, 0),
(0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0))
```
Output: `(1, 1, 4, 3)`
Input:
```
((0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 1, 0, 0, 0, 0))
```
Output: `(3, 7, 1, 1)`
## Scoring
Your program's score is determined by the sum of the number of array accesses it takes to solve all 6 of those examples. For example, if it takes 20 accesses to solve the first 5, and 15 for the last, your program's score will be 115. Lower score is better.
[Answer]
# JavaScript, 40 operations
```
function findRect(arr) {
var found = false;
var c = 0;
for (i = 0; i < arr.length; i++) {
if (!found) {
first = arr[i].indexOf(1);
c++;
if (~first) {
found = true;
x = first;
y = i;
}
}
if (found) {
last = arr[i].lastIndexOf(1);
c++;
if (~last) {
width = last - x + 1;
height = i - y + 1;
} else {
console.log(c);
return [x,y,width,height];
}
}
}
console.log(c);
return [x,y,width,height];
}
```
```
var globalC = 0;
function findRect(arr) {
var found = false;
var c = 0;
for (i = 0; i < arr.length; i++) {
if (!found) {
first = arr[i].indexOf(1);
c++;
if (~first) {
found = true;
x = first;
y = i;
}
}
if (found) {
last = arr[i].lastIndexOf(1);
c++;
if (~last) {
width = last - x + 1;
height = i - y + 1;
} else {
console.log(c);
globalC += c;
return [x,y,width,height];
}
}
}
console.log(c);
globalC += c;
return [x,y,width,height];
}
console.log(findRect([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]));
console.log(findRect([[1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]));
console.log(findRect([[0, 0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 1, 1, 1, 1]]));
console.log(findRect([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 0, 0]]));
console.log(findRect([[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]]));
console.log(findRect([[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0]]));
console.log(globalC);
```
[Answer]
## PowerShell, ~~34~~ 50 Operations
I was doing some string manipulation earlier. I removed any string manipulation, as it was clarified as forbidden, at the cost of some extra operations.
```
function Get-SquareCoordinates{
param(
[array]$array
)
$count = 0 # Record the count
$flag = $false # Loop exit flag
$rowIndex = -1 # Row location in array
# Find the top left corner
do{
$rowIndex++
# Check if this row contains 1
$result = $array[$rowIndex].IndexOf(1)
# If there is no 1 then -1 would be in $result
if($result -ge 0){$x,$y=$result,$rowIndex;$flag=$true}
# Increase the counter
$count++
} while(!$flag)
# Start from the back of the array and find the last index of 1
$w,$h = 0,0 # To store the width and height of the rectangle
$flag = $false # Loop exit flag
$rowIndex = $array.Count # Row location in array
# Find the bottom right corner
# Start checking the rows backwards
do{
$rowIndex--
# Check if this row contains 1 and add the count of all the ones to the index of the first one found
$result = $array[$rowIndex].IndexOf(1) + ($array[$rowIndex]-match1).Count - 1
# If there is no 1 then -1 would be in $result
if($result -ge 0){
$w,$h= ($result-$x+1),($rowIndex-$y+1)
$flag=$true
}
# Increase the counter by 2. First to find the one and the second to count the 1's on the line
$count=$count+2
} while(!$flag)
Write-Host "Determined using $count array operations" -ForegroundColor Green
$x,$y,$w,$h
}
```
Using the inputs exactly as in the questions, where each is saved as a variable it would net me the answers as an array of integers and spit out a console line containing the amount of operations it took to find the dimensions.
```
$array1, $array2, $array3,$array4,$array5,$array6 | ForEach-Object{
(Get-SquareCoordinates $_) -join ", "
}
Determined using 9 array operations
3, 2, 5, 3
Determined using 11 array operations
0, 0, 3, 3
Determined using 3 array operations
5, 0, 4, 5
Determined using 5 array operations
6, 2, 2, 4
Determined using 12 array operations
1, 1, 4, 3
Determined using 10 array operations
3, 7, 1, 1
```
] |
[Question]
[
This is much like my [earlier challenge](https://codegolf.stackexchange.com/questions/103105/number-of-straight-chain-alknes-of-given-length), except, this time, order *doesn't* matter.
A straight-chain alk\*ne is defined as a sequence of carbon atoms connected by single (alkane), double (alkene), or triple bonds (alkyne), (implicit hydrogens are used.) Carbon atoms can only form 4 bonds, so no carbon atom may be forced to have more than four bonds. A straight-chain alk\*ne can be represented as a list of its carbon-carbon bonds.
These are some examples of valid (not necessarily distinct) straight-chain alk\*nes:
```
[] CH4 Methane
[1] CH3-CH3 Ethane
[2] CH2=CH2 Ethene
[3] CH≡CH Ethyne
[1,1] CH3-CH2-CH3 Propane
[1,2] CH3-CH=CH2 Propene
[1,3] CH3-C≡CH Propyne
[2,1] CH2=CH-CH3 Propene
[2,2] CH2=C=CH2 Allene (Propadiene)
[3,1] CH≡C-CH3 Propyne
[1,1,1] CH3-CH2-CH2-CH3 Butane
...
```
While these are not, as at least one carbon atom would have more than 4 bonds:
```
[2,3]
[3,2]
[3,3]
...
```
Two straight-chain alk\*nes, `p` and `q` are considered equivalent if `p` is `q` reversed, or `p` is `q`.
```
[1] = [1]
[1,2] = [2,1]
[1,3] = [3,1]
[1,1,2] = [2,1,1]
[1,2,2] = [2,2,1]
```
Your task is to create a program/function that, given a positive integer `n`, outputs/returns the **number** of valid straight-chain alk\*nes of exactly `n` carbon atoms in length.
# Specifications/Clarifications
* You must handle `1` correctly by returning `1`.
* Alk\*nes like `[1,2]` and `[2,1]` are *NOT* considered distinct.
* Output is the *length* of a list of all the possible alk\*nes of a given length.
* You do *not* have to handle `0` correctly.
# Test Cases:
```
1 => 1
2 => 3
3 => 4
4 => 10
5 => 18
6 => 42
```
This is code golf, so the lowest byte count wins!
[Answer]
# JavaScript (ES6), 107 bytes
```
A=n=>n>9?2*A(n-1)+3*A(n-2)+3*A(n-7)+A(n-8)-5*A(n-3)-A(n-4)-2*A(n-6)-A(n-9):[0,1,3,4,10,18,42,84,192,409][n]
```
Recursive solution, using the recurrence relation that was pointed out in the comments of the question. Execution time rises much quicker than the input (complexity of `O(9^N)` if I'm not mistaken), so be careful with values higher than 20.
[Answer]
# MMIX, ~~108~~ 92 bytes (~~27~~ 23 instrs)
Works mod \$2^{63}\$, because it uses the two-part recurrence instead of the one-part, due to the two-part recurrence being much easier to compute.
(jxd)
```
00000000: e3010001 e3020001 e3030003 e3040001 ẉ¢¡¢ẉ£¡¢ẉ¤¡¤ẉ¥¡¢
00000010: e3050003 e3060006 67050002 67060005 ẉ¦¡¤ẉ©¡©g¦¡£g©¡¦
00000020: 27000001 28ff0302 26ffff01 c1010200 '¡¡¢(”¤£&””¢Ḋ¢£¡
00000030: c1020300 c103ff00 28ff0605 26ffff04 Ḋ£¤¡Ḋ¤”¡(”©¦&””¥
00000040: 66040005 66050006 660600ff 5b00fff5 f¥¡¦f¦¡©f©¡”[¡”ṫ
00000050: 22000104 3f000001 f8010000 "¡¢¥?¡¡¢ẏ¢¡¡
```
Disassembly and explanation:
```
alkns SET $1,1 // a(0)
SET $2,1 // a(1)
SET $3,3 // a(2)
SET $4,1 // b(0)/b(1)
SET $5,3 // b(2)
SET $6,6 // b(4)
CSOD $5,$0,2 // b(3), use if n is odd
CSOD $6,$0,5 // b(5), use if n is odd
0H SUBU $0,$0,1 // loop: n--
2ADDU $255,$3,$2 // a(n+1) = 2a(n) + a(n-1)
SUBU $255,$255,$1 // - a(n-2)
SET $1,$2 // and shift
SET $2,$3 // values of a
SET $3,$255 // down
2ADDU $255,$6,$5 // b(n+2) = 2b(n) + b(n-2)
SUBU $255,$255,$4 // - b(n-4)
CSOD $4,$0,$5 // shift values of b down
CSOD $5,$0,$6 // if n is odd
CSOD $6,$0,$255 // (happens once if n started at 2 or 3)
PBNZ $0,0B // if(n) goto loop
ADDU $0,$1,$4 // r(n) = (a(n) + b(n))
SRU $0,$0,1 // ÷ 2
POP 1,0 // return r(n)
```
] |
[Question]
[
What general tips do you have for golfing in [S.I.L.O.S](http://rjhunjhunwala.github.io/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](http://silos.tryitonline.net).
[Answer]
# 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!](http://silos.tryitonline.net/#code=YT05NwpkZWYgcSBwcmludCB6IGJvdHRsZSB2IGJlZXIgTCBMaW5lIGcgd2FsbCB4IEludE5vTGluZSBoIHRoZSBjIGFyb3VuZApxTCA5OSB6cyBvZiB2IG9uIGggZywgOTkgenMgb2Ygdi4KbGJscwpxIFRha2Ugb25lIGRvd24gYW5kIHBhc3MgaXQgYywgCmErMQpxeCBhCnFMICB6cyBvZiB2IG9uIGggZy4KcXggYQpxICB6cyBvZiB2IG9uIGggZywgCnF4IGEKcUwgIHpzIG9mIHYuCmEtMgppZiBhIHMKcUwgVGFrZSBvbmUgZG93biBhbmQgcGFzcyBpdCBjLCAxIHogb2YgdiBvbiBoIGcuCnFMIDEgeiBvZiB2IG9uIGggZywgMSB6IG9mIHYuCnEgR28gdG8gaCBzdG9yZSBhbmQgYnV5IHNvbWUgbW9yZSwgOTkgenMgb2YgdiBvbiBoIGcu&input=&args=)
[Answer]
# ~~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](https://github.com/rjhunjhunwala/S.I.L.O.S), 50 bytes
```
readIO
if i b
print -1
GOTO c
lblb
printInt i
lblc
```
[Try it online!](https://tio.run/##K87MyS/@/78oNTHF058rM00hUyGJq6AoM69EQdeQy90/xF8hmSsnKQcq6AkUzwTxk////28MAA "S.I.L.O.S – Try It Online")
However, that is far from optimal. The "superior" solution would be this.
# [S.I.L.O.S](https://github.com/rjhunjhunwala/S.I.L.O.S), 33 bytes
```
readIO
j=i
i/i
j=j+i-1
printInt j
```
[Try it online!](https://tio.run/##K87MyS/@/78oNTHF058ryzaTK1M/E0hnaWfqGnIVFGXmlXjmlShk/f//3xQA "S.I.L.O.S – Try It Online")
SILOS will quietly ignore the division by 0, which results in a no-op.
[Answer]
# 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
```
] |
[Question]
[
In this challenge we'll compute an infinite minimal admissible sequence.
The sequence for this challenge starts with `a(1) = 1`.
We continue this sequence by finding `a(n)` as the smallest possible number such that `a(n) > a(n-1)` and for every prime `p`, the set `{a(i) mod p : 1 ≤ i ≤ n}` has at most `p-1` elements.
Write a program or function that takes positive integer `n` and outputs `a(n)`. Shortest code in bytes wins.
---
Example:
`a(6)` is `19`, rather than, say `17` because `[1,3,7,9,13,19]` (the previous terms) is admissible while `[1,3,7,9,13,17]` is not.
`[1,3,7,9,13,17]` is not admissible, because for the base `3`, after taking the modulo of each term with `3`, we obtain `[1,0,1,0,1,2]` which contains every non-negative number smaller than `3`, our chosen base.
For `[1,3,7,9,13,19]` however, it would be impossible to come up with a base such that the list after modulo contains every non-negative integer smaller than such base.
---
Reference:
* [OEIS A020498](https://oeis.org/A020498)
---
Testcases:
```
a(1) = 1
a(2) = 3
a(3) = 7
a(4) = 9
a(5) = 13
a(6) = 19
a(7) = 21
a(8) = 27
a(9) = 31
a(10) = 33
a(100) = 583
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 44 bytes
```
-:[1]r:[1]cit.
t<gX=:?rc.'(l:2eLg:.rz:%adlL)
```
[Try it online!](http://brachylog.tryitonline.net/#code=LTpbMV1yOlsxXWNpdC4KdDxnWD06P3JjLicobDoyZUxnOi5yejolYWRsTCk&input=MTA&args=Wg)
`100` takes about a minute here, so be patient if you want to try `100`.
### Predicate 0 (main predicate)
```
-:[1]r:[1]cit.
-:[1]r:[1]c create array [[1], input-1, 1]
i iterate: [1] as input, iterate (input-1) times, predicate 1
t. last element is the output
```
### Predicate 1 (auxiliary predicate)
```
t<gX=:?rc.'(l:2eLg:.rz:%adlL)
t< last element of input < Temp
gX [Temp] = X
X= Assign a value to X, which assigns
a value to Temp
X :?rc. [Input,X] concatenated is output
.'( ) The following about the output cannot
be proven:
l:2eL L is a number between 2 and length
of output, inclusive
Lg:.rz:%a every element of output, taken modulo L,
dlL after removing duplicates, has length L
```
[Answer]
## ES6, 91 bytes
```
(n,a=[i=1])=>a[n]||f(n,a.every((_,j)=>(j+=2)>new Set(b.map(e=>e%j)).size,b=[...a,+++])?b:a)
```
Zero-indexed. Due to its recursive nature, only works for the first 450 terms, but computes a(99)=583 almost instantly.
] |
[Question]
[
[You've received a coded message](https://codegolf.stackexchange.com/q/89062/47581) from your ally that you know is encoded with the [VIC cipher](https://en.wikipedia.org/wiki/VIC_cipher). As you know that the VIC cipher is notoriously convoluted, you want to write a program that will decode the VIC cipher but is small enough to hide from the enemy if you are captured, and thus uses as few bytes as possible.
Your instructions are as follows:
**The information you have**
* The encoded message. For this example, we'll use the message we encrypted in the "VIC cipher encoder" challenge: `71431 14842 71192 58619 04185 22614 14745 49924 32826 13348 02189 38641 70140 40252 44820 64522 43982 47921 71283 22694 94443 80642 14521`
* A keyword with the most common letters of your chosen alphabet.
* A key phrase, such a quote or song lyric
* A date (or another number that is six digits or more)
* A personal agent number
In practice, these last four should be agreed upon beforehand by the sender and the recipient, including whether the agent number of the sender or the recipient is used in encoding.
What you and your ally agreed to use in your encoding is the following: the keyword `SENATORI`, the key phrase "The first principle is that you must not fool yourself — and you are the easiest person to fool.", and the date `3172016`, and the recipient's agent number, `9`.
**Summary of steps**
1. Derive the intermediate keys for use in the following steps and extract the message identifier from the encoded message.
2. Construct and apply the second (disrupted) transposition table in reverse.
3. Construct and apply the first transposition table in reverse.
4. Construct and apply the straddling checkerboard in reverse.
5. Finalize the decoding removing nulls and by starting the message at the "message begin" mark.
**Submechanisms**
Two more things to explain before we get into the meat of the matter: the processes of chain addition and sequentializing.
Chain addition, also known as a lagged Fibonacci generator, works by taking a starting digit sequence, adding the first two digits without adding and appending the result to the end. For example:
```
79081
7 + 9 = 6
790816
9 + 0 = 9
7908169
0 + 8 = 8
79081698
8 + 1 = 9
790816989
1 + 6 = 7
7908169897
... and so on
```
Sequentializing is essentially taking a sequence of letters or digits and labeling them by their alphabetical/numerical order. Duplicates are labelled left to right. For example:
```
E X A M P L E
0 A
1 0 2 Es
1 0 3 2 L
1 0 4 3 2 M
1 0 4 5 3 2 P
1 6 0 4 5 3 2 X
3 3 0 5 8 4 2 0 4 7 5 4 8 1
1 2 0s
1 2 3 1
1 4 2 3 2
5 6 1 4 2 3 3s
5 6 1 7 4 2 8 9 3 4s
5 6 1 10 7 4 2 8 11 9 3 5s
5 6 1 10 7 4 2 8 12 11 9 3 7
5 6 1 10 12 7 4 2 8 12 11 9 14 3 8s
```
I use zero-indexing here, but index however you like.
**1. Intermediate Keys**
Firstly, you need to retrieve the message identifier `M` from the message. The last digit of the date `3172016` is `6`, so you know that the message identifier was placed sixth from the last in the message.
```
The encoded message =
71431 14842 71192 58619 04185 22614 14745 49924 32826 13348 02189 38641
70140 40252 44820 64522 43982 47921 71283 22694 94443 80642 14521
Message id = 47921
```
Split the first 20 letters of the key phrase into two groups of 10 and sequentialize each individually, which we will call `S1` and `S2`.
```
THEFIRSTPR
S1: 8201357946
INCIPLEIST
S2: 2603751489
```
Subtract, without borrowing, the first five digits of the key date `3172016` from `M`:
```
M 47921
date - 31720
= 16201
```
Chain add the result until you have ten digits:
```
1620178218
```
Add these digits to `S1`, without carrying, to obtain `G`:
```
1620178218
S1 + 8201357946
G = 9821425154
```
Above `S2`, write the sequence 0123456789. Locate each digit of `G` in the sequence 0123456789 and replace it with the digit directly below it in `S2`. The result is `T`.
```
0123456789
S2 2603751489
G 9821425154
T 9806705657
```
Use chain addition to expand `T` by 50 digits. These digits, in five rows of ten, form the `U` block.
```
T 9806705657
U 7863751124
5490262369
9392885958
2210634430
4316978734
```
The last two non-equal digits of the `U` block are individually added to the agent's personal number to give the widths of the two transpositions, `p` and `q`.
```
9 + 3 = 12 (p, first transposition width)
9 + 4 = 13 (q, second transposition width)
```
Sequentialize `T` and use this sequence to copy off the columns of the `U` block, from top to bottom, into a new row of digits, `V`.
```
T 9806705657
seqT 9804612537
U 7863751124
5490262369
9392885958
2210634430
4316978734
V 69911 56837 12548 26533 30206 13947 72869 49804 84323 75924
```
Sequentialize the first `p` digits to get the key for the first transposition `K1`, and the following `q` digits for the key for the second `K2`.
```
First 12 6 9 9 1 1 5 6 8 3 7 1 2
K1 6 10 11 0 1 5 7 9 4 8 2 3
Next 13 5 4 8 2 6 5 3 3 3 0 2 0 6
K2 8 7 12 2 10 9 4 5 6 0 3 1 11
```
Finally, sequentialize the final row of the `U` block to get `C`, the column headers for the straddling checkerboard:
```
U5 4316978734
C 3105968724
```
**2. Reverse the Second Transposition**
We fill a transposition table with the message by columns in order of the column headings, `K2`. The message has 110 digits in 13 columns, leaves 8 full rows and six digits in a final row.
```
71431 14842 71192 58619 04185 22614 14745 49924 32826 13348 02189 38641
70140 40252 44820 64522 43982 47921 71283 22694 94443 80642 14521
starts off with
K2 8 7 12 2 10 9 4 5 6 0 3 1 11
8 7 4
6 1 2
1 4 7
9 3 1
0 1 1
4 1 9
1 4 2
8 8 5
5
resulting in
K2 8 7 12 2 10 9 4 5 6 0 3 1 11
0 6 0 8 2 6 4 2 8 7 2 4 9
2 4 6 6 7 4 5 8 0 1 2 2 4
5 1 4 1 1 5 4 2 2 4 6 7 9
2 7 2 9 2 2 9 6 1 3 1 1 4
4 0 1 0 8 2 9 1 8 1 4 1 4
4 1 4 4 3 4 2 3 9 1 1 9 4
8 4 5 1 2 3 4 3 3 4 4 2 3
2 0 2 8 2 9 3 4 8 8 7 5 8
0 4 1 5 6 8
```
Taking the rows one at a time, and stopping at the disrupted parts
```
K2 8 7 12 2 10 9 4 5 6 0 3 1 11
7 2 4 9 stop at 0
2 2 4
7 9
4
go all the way down until you run out of row
4 1 4 4 3 4 2 3 9 1 1 9 4
8 4 5 1 2 3 4 3 3 4 4 2 3
2 0 2 8 2 9 3 4 8 8 7 5 8
0 4 1 5 6 8
Result so far: 060826428 2466745801 51411542246 272922961311 4010829181414
```
The continue to avoid disrupted bits until the end...
```
K2 8 7 12 2 10 9 4 5 6 0 3 1 11
7 2 4 9 stop at 0
2 2 4
7 9
4
go all the way down until you run out of row
9 4 restart until 1
3
5 6 8 restart until 2
Result so far: 060826428 2466745801 51411542246 272922961311 4010829181414
41443423911 845123433442 2028293488758 041
```
Then grab the rest:
```
Result: 060826428 2466745801 51411542246 272922961311 4010829181414
41443423911 845123433442 2028293488758 041 7249 224 79 4 94 3 568
```
**3. Reverse the First Transposition**
As before, create the transposition table by filling in columns in order of the column headings, `K1`. With 110 digits and 12 columns, we have 9 full rows and 2 digits in a final row.
```
K1 6 10 11 0 1 5 7 9 4 8 2 3
0
6
0
8
2
6
2
4
8
resulting in
K1 6 10 11 0 1 5 7 9 4 8 2 3
4 0 7 0 2 0 1 2 9 3 1 2
4 4 9 6 4 8 1 9 6 3 5 4
1 1 4 0 6 2 8 3 1 4 1 6
4 7 9 8 6 9 4 4 3 4 4 2
4 2 4 2 7 1 5 8 1 2 1 7
3 4 3 6 4 8 1 8 1 2 1 2
4 9 5 4 5 1 2 7 4 0 5 9
2 2 6 2 8 4 3 5 0 2 4 2
3 2 8 8 0 1 4 8 1 8 2 2
9 4
```
Reading of the rows in order, with no disruptions this time, we obtain:
```
407020129312 449648196354 114062831416 479869443442 424271581217
343648181212 495451274059 226284350242 328801481822 94
```
**4. Reversing the Straddling Checkerboard**
The heading for the checkerboard is `C = 3105968724`. We fill in the first row with the keyword `SENATORI` and the rest of the alphabet is filled in as follows:
```
3 1 0 5 9 6 8 7 2 4
S E N A T O R I
2 B D G J L P U W Y .
4 C F H K M Q V X Z #
```
To decode we simply look up the each number in the checkerboard as we read them. First, `4` must be a row heading, so we move to `40` which is H. `7` is I. `0` is N. `2` is a row heading, so we move to `20` which is G. Continuing in this way, we reveal the original message:
```
HINGELSE.MOVETOSAFEHOUSEFOXTROT#3#..
WEAREDISCOVERED.TAKEWHATYOUCAN.BURNEVERYT?
```
The question mark at the end is from the final `4`. As this is a row heading, there should be another number after this, but this is end of the message. Thus, we conclude that this is a null, and discard it.
```
HINGELSE.MOVETOSAFEHOUSEFOXTROT#3#..
WEAREDISCOVERED.TAKEWHATYOUCAN.BURNEVERYT
```
**5. Finalize the Decryption**
The program does not need to reinsert spaces and punctuation, but if there is a set convention for where the message originally began (here we used `..`), cycle through the message until the message beginning is at the beginning.
The final decrypted message is:
```
WEAREDISCOVERED.TAKEWHATYOUCAN.
BURNEVERYTHINGELSE.MOVETOSAFEHOUSEFOXTROT#3#..
```
Notes for this challenge:
* You are given a minimum of five inputs: the message, the letter keyword, the key phrase, the date, and a personal number.
* You may assume all inputs are valid, with the correct number of digits and letters (5-digit message identifier, at least 20 digits for the key phrase, and so on). You may assume that the keyword and key phrase have already had all punctuation and spaces removed except for those that you allow in your version, and that numbers are denoted with number signs correctly.
* The encoded message should be either a string of space-separated five-digit groups, a list of five-digit integers, one long string without spaces, or something similar.
* I used zero-indexing and `0123456789` in my example. You may use 1-indexing and `1234567890`, or some other system in your answer, as long as you specify what you used.
As always, if the problem is unclear, please let me know. Good luck and good golfing!
[Answer]
# Python 3, 1446 bytes
This is even longer than my encoder. Golfing suggestions very welcome.
As this is a counter to my encoder, this also uses the uppercase Latin alphabet with additional characters `.` and `#`. The decoder also uses 0-indexing and `0123456789` when converting `g` to `t`.
```
I=int;L=list;E=len;R=range;B=str;J=''.join
def H(s,e):
for i in R(e-E(s)):s+=chr(48+(ord(s[i])+ord(s[i+1]))%32%10)
return s
def Q(s):
r=[0]*E(s);s=L(s);a=R(E(s))
for z in a:b=min(a,key=lambda i:s[i]);r[b]=z;s[b]="~"
return r
def T(x,k):
u=E(x);v=E(k);g=R(v);c=[x[i::v]for i in g];s=[0]*v
for f in g:s[k[f]]=c[f]
return J(s)
def U(x,k,d=0):
c=[];w=[];u=E(x);v=E(k);g=R(v);n=u//v+1;l=u%v or v;e=0
for j in g:c+=[[]]
for j in g:i=k.index(j);c[i]+=L(x[e:e+n-(i>=l)]);e+=n-(i>=l)
for z in R(n):
w+=[[]]
for j in c:w[z]+=j[z:z+1]
if d:
u=[];r=y=0;i=k.index(y)
while r<n:
u+=w[r][:i];w[r]=w[r][i:];i+=1;r+=1
if i>v:y=(y+1)%v;i=k.index(y)
for j in w:u+=j
return J(u)
else:return J(J(i)for i in w)
def C(m,s,w):
t={s[-2:]:".",s[-1]*2:"#"};x=64;r='';j=z=n=0;e=-1;h=''
while x<90:
x+=1;v=chr(x)
if v in w:t[s[w.index(v)]]=v
else:t[s[z-2]+s[j]]=v;j+=z;z=(z+1)%2
for j in R(E(m)):
if(e>=0)*(j<e+2):continue
else:e=-1
if n:e=m.index(s[-1]*2,j+1);r+=m[j:e]+"#";n=0
else:
k=m[j]
if h:r+=t[h+k];n=t[h+k]=="#";h=''
elif k in s[:-2]:r+=t[k]
else:h=k
b=r.index("..")+2
return r[b:]+r[:b]
def D(m,w,P,d,A):j=-I(d[-1]);m=m.split();M=m[j];m=J(m[:j]+m[j+1:]);t=J(B(Q(P[10:20])[I(J(B((I(H(J(B((I(M[i])-I(d[i]))%10)for i in R(5)),10)[i])+Q(P[:10])[i])%10)for i in R(10))[i])])for i in R(10));u=H(t,60)[10:];p=A+I(u[-2]);v=T(u,Q(t));return C(U(U(m,Q(v[p:p+A+I(u[-1])]),1),Q(v[:p])),J(B(i)for i in Q(u[40:])),w)
```
**Ungolfing:**
```
def chain_add(seq, end):
for i in range(end - len(seq)):
seq += chr(48+(ord(seq[i])+ord(seq[i+1]))%32%10)
return seq
def sequent(seq):
res = [0]*len(seq);seq=list(seq)
for z in range(len(seq)):
b = min(range(len(seq)),key=lambda i:seq[i])
res[b] = z
seq[b] = "~"
return res
def transpose(text, keys):
columns = ['']*len(keys)
for t in range(len(text)):
columns[t%len(keys)] += text[t]
res = [0]*len(keys)
for index in range(len(keys)):
res[keys[index]] = columns[index]
return''.join(res)
def untranspose(text, keys, disrupt=False):
columns = []
for j in range(len(keys)):
columns += [[]]
num_rows, len_last = divmod(len(text),len(keys))
num_rows += 1
if len_last == 0:
len_last = len(keys)
text_index = 0
for j in range(len(keys)):
ind = keys.index(j)
columns[ind] += list(text[text_index:text_index+num_rows-(ind>=len_last)])
text_index += num_rows-(ind>=len_last)
rows = []
for k in range(num_rows):
rows += [[]]
for j in columns:
rows[k] += j[k:k+1]
if disrupt:
undisrupt = []
current_row = 0
stop_key = 0
stop_index = keys.index(stop_key)
while current_row < num_rows:
undisrupt += rows[current_row][:stop_index]
rows[current_row] = rows[current_row][stop_index:]
stop_index += 1
current_row += 1
if stop_index > len(keys):
stop_key = (stop_key + 1) % len(keys)
stop_index = keys.index(stop_key)
for i in rows:
undisrupt += i
return ''.join(undisrupt)
else:
return ''.join(''.join(i) for i in rows)
def uncheckerboard(message, seq, word):
trans = {seq[-2:]:".", seq[-1]*2:"#"};x=64;res='';j=z=0
while x<90:
x += 1
v = chr(x)
if v in word:
trans[seq[word.index(v)]] = v
else:
trans[seq[z-2] + seq[j]] = v
j += z
z = (z+1) % 2
num = False
end = -1
h = ''
for j in range(len(message)):
if end>=0 and j<end+2:
continue
else:
end = -1
if num:
end = message.index(seq[-1]*2,j+1)
res += message[j:end]+"#"
num = 0
else:
k = message[j]
if h:
res += trans[h+k]
if trans[h+k] == "#":
num = 1
h = ''
elif k in seq[:-2]:
res += trans[k]
else:
h = k
begin = res.index("..") + 2
return res[begin:] + res[:begin]
def decode(message, keyword, phrase, date, agent):
mkey = -int(date[-1])
message = message.split()
m_id = message[mkey]
message = ''.join(message[:mkey] + message[mkey+1:])
s1 = sequent(phrase[:10])
s2 = sequent(phrase[10:20])
b = ''.join(str((int(m_id[i])-int(date[i]))%10) for i in range(5))
a = chain_add(b, 10)
g = ''.join(str((int(a[i])+int(s1[i]))%10) for i in range(10))
t = ''.join(str(s2[int(g[i])]) for i in range(10))
u = chain_add(t,60)[10:]
p = agent+int(u[-2])
q = agent+int(u[-1])
seqT = sequent(t)
v = transpose(u,seqT)
k1 = sequent(v[:p])
k2 = sequent(v[p:p+q])
c = ''.join(str(i)for i in sequent(u[40:]))
z = untranspose(message,k2,1)
y = untranspose(z,k1)
x = uncheckerboard(y,c,keyword)
return x
```
] |
[Question]
[
Previously, we computed the [Bit-Reversal Permutation](https://codegolf.stackexchange.com/q/83373/6710) where we found how the order of indices would be permuted. In that case, we received an input *n* which was the order of the permutation of the indices where the length was 2*n*. However, this time, we are given a string of length *m* = 2*k* for some *k*. Now we want to apply the permutation indices of order *k* to a string.
## Task
Your goal is to create a function or program that given a string where the length is a power of 2, output the permutation of it using bit-reversal.
As an example, the string `'codegolf'` has length 8 which is a power of 2, that is 8 = 23. We learned in the previous challenge that the bit-reversal permutation of order 3 is `[0, 4, 2, 6, 1, 5, 3, 7]` which means that we select the characters from the input string using that order of indices.
```
Input Output
0 1 2 3 4 5 6 7 0 4 2 6 1 5 3 7
c o d e g o l f c g d l o o e f
```
This is one possible method of solving this task. Since we do not require the order of indices as output, there may be shorter algorithms which avoid generating the indices and rely on permuting characters only.
## Test Cases
```
Input = Output
"z" = "z"
"cg" = "cg"
"code" = "cdoe"
"golf" = "glof"
"codegolf" = "cgdlooef"
"aaaazzzz" = "azazazaz"
"LynngDaie dneers" = "Legendary Dennis"
"hieroglyphically" = "hpoaeillihglrcyy"
"Programming Puzzles N' Code-Golf" = "PliorNPGosgem zlrenda'uog -mCzf"
"super spectacular dazzling dream" = "srenrzcrpdt sllau cg zueeaadpiam"
```
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins.
* Builtins are allowed.
* The input string will only be in ASCII. The length of the input string will always be a power of 2.
[Answer]
# Pyth, 9 bytes
```
hu+M.Tc2G
```
[Try it online](https://pyth.herokuapp.com/?code=hu%2BM.Tc2G&test_suite=1&test_suite_input=%22z%22%0A%22cg%22%0A%22code%22%0A%22golf%22%0A%22codegolf%22%0A%22aaaazzzz%22%0A%22LynngDaie+dneers%22%0A%22hieroglyphically%22%0A%22Programming+Puzzles+N%27+Code-Golf%22%0A%22super+spectacular+dazzling+dream%22)
### How it works
```
u Q fixed point: let G = input, and repeatedly replace G with
c2G chop G into two equal pieces
.T justified transpose
+M map concatenate
until a duplicate is found
h take the first (only) element of the resulting list
```
[Answer]
## Haskell, 72 bytes
This is "permuting characters only", but is it shorter than a different approach?
```
s(a:b:c)|(x,y)<-s c=(a:x,b:y)
s n=(n,n)
r a|[_]<-a=a|(x,y)<-s a=r x++r y
```
`s` is a helper function to seperate the characters from even and odd positions, `r` is the bit reversal permutation function:
```
Prelude> r "codegolf"
"cgdlooef"
```
[Answer]
# Python 3.5, ~~112~~ 111 bytes:
```
from math import*;lambda d:''.join([d[int(bin(i)[2:].zfill(int(log2(len(d))))[::-1],2)]for i in range(len(d))])
```
You really start to appreciate the all in one power and compactness of Python once you start using languages like `C` and `Java`. Anyways, this is an anonymous function that you call by first naming it, and then calling it like a normal function wrapped inside the `print()` function.
[Try It Online! (Ideone)](http://ideone.com/2Xo7XM)
] |
[Question]
[
# Intro
[Cookie Clicker](http://orteil.dashnet.org/cookieclicker/) is a popular browser game in which the player has to click a cookie to gain... Cookies!
The player can buy upgrades which will automatically farm cookies for you. Sometimes a golden cookie will enter the screen, which will provide a bonus upon clicking it.
# Challenge
This challenge will not be about clicking a cookie. It will be about automating the cookie.
The player starts off with 0 cookies, and will gain cookies on every game tick. The goal of the challenge is to calculate the amount of ticks it takes to reach a certain amount of cookies.
# Input
Your program or function will have 2 input parameters.
The first parameter is the **goal**, which is simply the amount of cookies you need to finish.
The second parameter is a list of upgrades the player can buy. The format of the list will be explained in further detail in the paragraph **Upgrades - List format**.
For sake of convenience, you may assume that the input is always in the correct format. You don't have to deal with bad input.
# Output
Your program or function should *print or return* the amount of ticks it takes before the player has reached the goal amount of cookies.
# Upgrades
Every game-tick will earn the player some cookies. These are based on the upgrades of the player. If a player has no upgrades, the cookie production will be 1 cookie per tick. Once the player reaches enough cookies to buy an upgrade, he will automatically purchase it (before the next tick happens).
When the player has enough cookies after a tick to buy multiple upgrades, he will attempt to buy all possible upgrades, starting with the cheapest.
### List format
`[[100, '+', 1],[1000, '*', 2],[10000, '*', 10]`
This is an unordered list which contains 3 upgrades. The first parameter of an upgrade is the **price** of the upgrade. The second parameter is the **effect** of the upgrade and the third parameter is the **effect amount**.
The input list will contain no upgrades with the same price.
The only possible effects are `+` (addition) and `*` (multiplication).
`[100, '+', 1]` means that the cookie production will increase by 1 at a cost of 100 cookies.
# Golden cookies
Every 1000 ticks, the player will find a golden cookie. When this happens, the player will receive a bonus of 10% (rounded down) of his cookie amount. If the player has 1000 cookies at tick 1000, he will have 1100 cookies before tick 1001 happens.
# Order of events
After every tick a couple of actions can occur.
1. If the player has enough cookies, end the game
2. If the player has enough cookies, purchase upgrades
3. If the amount of ticks is a multiple of 1000; Golden cookie
# Example input + output
```
(0 , []) -> 0
(100 , []) -> 100
(1 , [[10, '+', 1]]) -> 1
(10 , [[10, '+', 1]]) -> 10
(1000 , [[100, '*', 2], [10, '+', 1]]) -> 310
(10000, [[10, '+', 1], [100, '*', 2]]) -> 2263
```
# Detailed example
```
(1000 , [[100, '*', 2], [10, '+', 1]]) -> 310
ticks: 8, cookies: 8, production: 1
ticks: 9, cookies: 9, production: 1
ticks: 10, cookies: 0, production: 2
ticks: 11, cookies: 2, production: 2
ticks: 58, cookies: 96, production: 2
ticks: 59, cookies: 98, production: 2
ticks: 60, cookies: 0, production: 4
ticks: 61, cookies: 4, production: 4
ticks: 70, cookies: 40, production: 4
ticks: 80, cookies: 80, production: 4
ticks: 260, cookies: 800, production: 4
ticks: 280, cookies: 880, production: 4
ticks: 300, cookies: 960, production: 4
ticks: 309, cookies: 996, production: 4
ticks: 310, cookies: 1000, production: 4 -- done
```
# Disclaimer
I will not be held responsible for any addictions caused by this challenge.
Happy golfing!
[Answer]
# Python2, 177 Bytes
```
def f(g,u):
c=t=0;r=1
while c<g:
c+=r;t+=1
if c>=g:break
u=sorted(u)
if u[0][0]<=c:
h=u.pop(0);c-=h[0]
exec('r'+h[1]+'=h[2]')
if t%1000<1:c+=c//10
return t
```
[Answer]
# CJam, 66
```
q~1$aa+$0{_W$<{{_2$0=0=<!}{\(~X@~:X;@\-}wT):T1e3%{_A/+}|X+}0?}h];T
```
[Try it online](http://cjam.aditsu.net/#code=q%7E1%24aa%2B%240%7B_W%24%3C%7B%7B_2%240%3D0%3D%3C!%7D%7B%5C(%7EX%40%7E%3AX%3B%40%5C-%7DwT)%3AT1e3%25%7B_A%2F%2B%7D%7CX%2B%7D0%3F%7Dh%5D%3BT&input=10000%20%5B%5B100%20%27*%202%5D%5B10%20%27%2B%201%5D%5D)
**Explanation:**
```
q~ read and evaluate the input (the goal and the array of upgrades)
1$aa+ append a dummy upgrade with the cost equal to the goal
(to avoid the array becoming empty)
$ sort the upgrades lexicographically (so first by cost)
0 push 0, the initial number of cookies
{…}h do-while loop, checking the last value as the condition
_W$< duplicate the number of cookies and check if it's smaller
than the goal (at the bottom of the stack)
{…} if true… ("<condition><then part><else part>?" is an if statement)
{…} while… ("{condition}{block}w" is a while loop)
_2$ duplicate the number of cookies and the array of upgrades
0=0= get the cost (first item) of the first upgrade
<! check if the number of cookies is not smaller than it
{…} do…
\( bring the array of upgrades to the top and take out the first upgrade
~ dump the price, effect (operator) and amount onto the stack
X@ push X (cookie production) and bring the operator to the top
~:X; evaluate the operator and store the result back in X
@\- subtract the price from the number of cookies
w (end) while
T):T increment T (the number of ticks, initially 0)
1e3% calculate T % 1000
{…}| if false (0) then…
_A/+ add cookies/10 to the number of cookies (A=10)
X+ add X (cookie production, initially 1) to the number of cookies
to go to the next step
since the result is not 0, the do-while loop continues
0 else (if we reached the goal) push 0 to exit the loop
? (end) if
]; pop everything left on the stack after the do-while loop
T push T, the final number of ticks
```
[Answer]
## Lua, 220 Bytes
Can't think of a way to golf it down for the moment, it's still pretty long mostly because lua doesn't let you use loops carelessly regarding the bit count ^^'
```
function f(g,u)c=0t=0r=1while(c<g)do c=c+r t=t+1if(c>=g)then break end
for i=1,#u do x=u[i]if(c>=x[1])then c=c-x[1]r=x[2]=="+"and r+x[3]or r*x[3]table.remove(u,i)break
end end c=t%1000<1 and c+c/10or c end return t end
```
### Ungolfed
```
function f(g,u)
c=0 -- cookie counter
t=0 -- tick counter
r=1 -- cookie gain rate
while(c<g) -- iterate while cookie < goal
do -- prevent returning 1 tick when the goal is 0
c=c+r -- gain cookies
t=t+1 -- increment the tick counter
if(c>=g)then break end -- if we have enough cookies, exit
for i=1,#u -- iterate over the upgrades
do
x=u[i] -- alias the current upgrade
if(c>=x[1]) -- if we can, afford it
then
c=c-x[1] -- deduce its price from our cookies
r=x[2]=="+" -- if it was an additive bonus
and r+x[3] -- add its value to the rate
or r*x[3] -- else multiply the rate by it
table.remove(u,i) --remove it from the list of upgrades
break -- exit the shop :D
end
end
c=t%1000<1 -- every thousand ticks
and c+c/10 -- get a golden cookie
or c -- every other ticks does nothing
end
return t -- return the number of ticks it took
end
```
### Test Suite
You can copy paste the following code into [this online compiler](http://www.lua.org/cgi-bin/demo) to run all the test cases.
```
function f(g,u)c=0t=0r=1while(c<g)do c=c+r t=t+1if(c>=g)then break end
for i=1,#u do x=u[i]if(c>=x[1])then c=c-x[1]r=x[2]=="+"and r+x[3]or r*x[3]table.remove(u,i)break
end end c=t%1000<1 and c+c/10or c end return t end
print(f(0,{}))
print(f(100,{}))
print(f(1,{{10,'+',1}}))
print(f(10,{{10,'+',1}}))
print(f(1000,{{10,'+',1},{100,'*',2}}))
print(f(10000,{{10,'+',1},{100,'*',2}}))
```
[Answer]
# Javascript ES6, 138 bytes
```
f=(g,s,p=1,c=-1,t=0)=>(c+=p)<g?f(g,s[b=0]?s.slice(b=(z=s.sort()[0])[0]<=c):s,b?eval(`p${z[1]}${z[2]}`):p,(b?c-z[0]:c)*(t%1e3?1:1.1),t+1):t
```
Ungolfed:
```
p = 1; // production
c = -1; // cookies, -1 to account for the first tick
t = 0; // ticks
f = function(g, s, p, c, t) { // goal, upgrades, production, cookies, ticks
c += p; // add production to cookies
if (c < g) { // cookies < goal
b = 0; // reset buy flag to false
var upgradeArray;
if (s[0]) { // our upgrade array isn't empty
var sortedArray = s.sort();
var upgrade = sortedArray[0];
b = upgrade[0] <= c; // price <= cookies
upgradeArray = s.slice(b); // if we buy something, we remove the upgrade from the array because [1,2,3].slice(1) -> [2,3]
} else { // our upgrade list is empty
upgradeArray = s;
}
var newProduction;
if (b) { // we buy something
newProduction = eval('p' + upgrade[1] + upgrade[2]) // evaluate p+10 for example
} else {
newProduction = p; // production is unchanged
}
var newCookies;
if (b) { // we buy something
newCookies = c - upgrade[0]; // substract price from cookies
} else {
newCookies = c;
}
if (t % 1e3 == 0) { // ticks % 1000 == 0
newCookies *= 1.1; // golden cookie
}
return f( // recursive call
g, // the goal doesn't change
upgradeArray,
newProduction,
newCookies,
t+1 // add a tick
)
} else { // we have enough cookies, so we
return t; // return the amount of ticks
}
}
```
Try it here
```
f=(g,s,p=1,c=-1,t=0)=>(c+=p)<g?f(g,s[b=0]?s.slice(b=(z=s.sort()[0])[0]<=c):s,b?eval(`p${z[1]}${z[2]}`):p,(b?c-z[0]:c)*(t%1e3?1:1.1),t+1):t
D.innerHTML= [
f(0 , []),
f(100 , []),
f(1 , [[10, '+', 1]]),
f(10 , [[10, '+', 1]]),
f(1000 , [[100, '*', 2], [10, '+', 1]]),
f(10000, [[10, '+', 1], [100, '*', 2]])
].join(`<br>`)
```
```
<div id=D>
```
] |
[Question]
[
At some point, I bumped into an SO question asking how to implement Perl's trivial hash-of-hashes data structure in Java.
For those who don't know Perl, the hash value can be a scalar or another hash, or technically speaking hash reference. Arbitrary depth. Additional feature offered by Perl is autovivification - assigning an element 4 layers deep will automatically create correct hashes with proper keys 4 levels deep, without Java's need to assign hash object on level 1, then hash object on level 2 (being added to the first hash as a value) etc...
So, Perl code to assign a value to N-level hash at a known depth is
```
my $myHash; # initialization isn't required due to autovivification
$myHash->{$key1}->{$key2}->{$key3}->{$key4} = $value;
```
And to retrieve it
```
my $value = $myHash->{$key1}->{$key2}->{$key3}->{$key4};
```
The more generic code to assign a hash by arbitrary set of keys can be implemented by 5-10 line subroutine done properly; or 2-3 lines golf hack with eval.
Not being anywhere near a Java expert, my SO answer was ~30 lines of code that implemented a fixed-depth 3 level hash of hash of hashes.
Your mission, should you choose to accept it, **is to produce the smallest code in a strongly typed language which implements Perl equivalent data structure which is a hashmap of hashmaps of ...; of arbitrary and non-uniform depth** (basically, a tree); with hasmap keys being of String type; and leaf-level values String or Integer. The code should support 100% of what the Perl hash-of-hashes code does, including:
* Retrieving a value based on a list of keys
* Assigning a value based on a list of keys
+ As part of this, you should be able to replace a scalar leaf level node with an internal hashmap node, if your list of keys leads to that.
E.g. `set("val1","k1","k2");set("val2","k1","k2","k3")` basically erases `"val1"` from existence after second call as it's replaced by a 3rd level hashmap.
The code should be resilient, e.g. no null exceptions etc... even for the bad input (simply return NULL)
You can use any strongly typed language other than Java, though I would personally prefer Java answers due to how/why this question originated.
Caveat: using some 3rd party library that implements equivalent of Perl hashes is NOT acceptable. 100% of the code must be using only the native core capabilities of the language.
[Answer]
# C#, 215 bytes
```
class A:System.Collections.Generic.Dictionary<string,object>{public void B(string a,object b){if(ContainsKey(a))this[a]=b;else Add(a,b);}public dynamic C(string a){if(!ContainsKey(a))Add(a,new A());return this[a];}}
```
The class is named `A`. Use `hash.B("key", "val");` to set a value, and `hash.C("key");` to get a value. Nested keys can be achieved through, e.g., `hash.C("k1").C("k2").C("k3").B("k4", "value");`.
[Answer]
# Scala, ~~231~~ ~~214~~ ~~199~~ 193 bytes
Immutability always wins! (turns out the long package name of `collection.mutable.Map` wasn't worth the hassle...)
```
class A{var a=Map[String,Any]()
def g(s:String*):Any={val y=s(0);if(s.size>1)g(y).asInstanceOf[A].g(s.drop(1):_*)else if(a.contains(y))a(y)else{a+=y->new A;a(y)}}
def s(s:String,v:Any)=a+=s->v}
```
Only thing that's problematic is the need to cast back to A... but having another method entirely that'd return `a.type` is actually longer (and `with` cannot be used).
Example:
```
val a = new A()
a.g("hey").asInstanceOf[A].s("foo", "bar")
a.g("hey").asInstanceOf[A].s("int", 3)
println(a.g("hey").asInstanceOf[A].g("foo"))
println(a.g("hey", "foo"))
println(a.g("hey", "int"))
a.s("hey", 42)
println(a.g("hey"))
```
Output:
```
bar
bar
3
42
```
[Answer]
# [Go](https://go.dev), 136 bytes
```
type S=string
type A struct{m map[S]any}
func(a*A)g(k S)any{if _,o:=a.m[k];!o{a.m[k]=N()};return a.m[k]}
func(a*A)s(k S,v any){a.m[k]=v}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=pVBNSsQwFMalOcUzC8kbahfqQmboohcYhC6HQWJpYukkKW06UEL33sFNETyER9HTmDQKIrNzlbz3_SYvr9LM7y0vGy4rULzWpFat6WxKhbL0bbDi6u7j2Y5tBUXW267WkixTDn4aSuuUl7W7Ys_1OBEx6JLxVY6SNVCg37lawENi1hlP1a7Zby6Mi7dsy3DadJUdOg1x9UvfB31yBO-AP4LjFPt8np0HHniDVe6iw2XuFG8qFrrEmqEQThNZPJenMQRHOKyzoCQ8lYw-VSPFlPnAtGdUGEMToI-8oyfxWluP3yC59wH2oNlfjowe-E9GyMHQoI9IArfXpwRIvn9knuP5BQ)
Challenge specification does not specify constructors; this implementation does not include them. An implementation with a constructor is below:
### [Go](https://go.dev), with constructor, 174 bytes
```
type S=string
type A struct{m map[S]any}
func N()*A{return&A{make(map[S]any)}}
func(a*A)g(k S)any{if _,o:=a.m[k];!o{a.m[k]=N()};return a.m[k]}
func(a*A)s(k S,v any){a.m[k]=v}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=pVDNSsQwEL7nKcYcJFlqDupBdumhLyBCj8sisSSx1CQlTRdK6JN4KYJX7z6KB9_FZLOKyN48TWa-n3wzzy_KLu89bzquBGjeGtTq3jrPsNQev45eXtx8vPmpF1CXg3etUejQVRC7sfFBR1m_rXfcTDOSo2ngltBVFZzwozPnVdC8E-SHQ-fMInxVUUU6qGmchlbCfWHXJWd62-02ZzbkVxnN5k32gjz6pR-SvthD8v0W7Odj6s9DmLQToRAQh3WZoiHOFMGPYsKUkejBBoKltbgA_MAdPom3xkf8iqK7eAD_ZMhfjsoe9J-M9A9NCYaMFHB9eUpA0XHJZcn1Cw)
] |
[Question]
[
You **love** watching the snow falling outside, but you know it won't be snowing much longer. You could take a video, but decide to make a snow animation because ... um ... you need to practice your animation skills!
## Snow
Snow is simply the `*` symbol here. Half of the snow moves at `1` char per frame, while the other half moves at `0.5` chars per frame. The program ends when all the snow reaches the bottom of the screen. The viewing area you will be using is `80x25`. You will have 100 snow flakes to output, half fast, and half slow.
Every frame you will dispense 4 flakes, 2 fast and 2 slow ones, at random locations at the top of the viewing area, until you have used all 100. The slow flakes can move either move the first frame, stay still the next, or stay still the first frame, and move the next, it doesn't matter. Overlapping flakes don't have anything special, just the `*` like the rest.
## Other notes
* You must make a full program, no functions here.
* Your program must run close to 10fps (+-1 frame per sec).
* You can assume the console is the same size as the viewing area.
* Each frame you must remove the previous output, either by pushing all previous output off the top of the console, or by clearing the output completely.
# Example
To make this shorter this just outputs 2 flakes per frame (1 fast, 1 slow), only 20 flakes will be outputted, and the viewing area is `20x5`.
```
Frame 1:
* *
Frame 2:
* * *
*
Frame 3:
* * *
* *
*
Frame 4:
* * *
* **
*
*
Frame 5:
* * *
* * *
**
*
Frame 6:
* **
* * *
* * *
*
Frame 7:
* **
* **
* * *
* *
Frame 8:
* **
* * *
* * *
* *
Frame 9:
* * *
***
* * *
* * *
Frame 10:
* **
* * *
* * *
* * *
Frame 11:
*
* * *
** *
* * *
Frame 12:
* *
* * *
* * *
Frame 13:
*
* *
** *
Frame 14:
* *
* *
Frame 15:
*
* *
Frame 16:
* *
Frame 17:
*
```
If you want some snow/rain confusion and clean code, go [here](https://codereview.stackexchange.com/questions/118538/how-clean-is-my-snow)
[Answer]
# Octave, 179 bytes
```
A=' *';C=D=E=zeros(25,80);B=[i=1,1,(1:78)*0];do if i++>25 B=B&0;end
C=[B(randperm(80));C(1:24,:)];D=[B(randperm(80));D(1:24,:)];F=D;D=E;E=F;pause(.1);disp(A((F|=C|D)+1))
until(~F)
```
## Ungolfed
```
A=' *'; % Index with 1,2 to translate to ' ','*'
% A([2 1 2 2 1]) => '* ** '
C=D=E=zeros(25,80); % Locations of fast snowflakes,
% slow ones moving on frame 1,3,5...
% and slow ones moving on 2,4,6...
B=[1,1,zeros(1,78)]; % Line with two snowflakes in it.
% Will be added on top each frame.
i=1;
do
if i++>25 % We push 4 snowflakes per iteration.
B=B&0; % Stop new input after 25 iterations.
end
C=[B(randperm(80));C(1:24,:)]; % Shift fast snowflakes down
% and add randomly permuted input line.
D=[B(randperm(80));D(1:24,:)]; % Shift one set of slow snowflakes down
% and add randomly permuted input line.
F=D;D=E;E=F; % Swap the two sets of slow snowflakes.
pause(.1);
disp(A((C|D|E)+1)) % Print '*' where either of the matrices
% is set, ' ' otherwise.
until(~(C|D|E)) % Loop until the matrices are all zero
```
[Answer]
# JavaScript (ES6), 370 bytes
```
(S=(n,o,r="")=>{for(i=0;i<w;i++)o[i][0].pop(),o[i][0].unshift(0),Math.abs(n/4%2)&&(o[i][1].pop(),o[i][1].unshift(0));if(n>0)for(i=0;i<4;i++)o[Math.random()*w|0][i%2][0]++;for(j=0;j<h;j++){for(i=0;i<w;i++)r+=o[i][0][j]+o[i][1][j]>0?"*":" ";r+=`
`}console.log(r),n>2*-t&&setTimeout(g=>S(n-4,o),t)})(t=100,[...new Array(w=80)].map(i=>[0,0].map(i=>new Array(h=25).fill(0))))
```
Simulates with a multidimensional array, then plays it out. Could probably be golfed more.
Here's a slightly less compressed version:
```
(S=(c,v,o='')=>{
for(i=0;i<w;i++){
v[i][0].pop();v[i][0].unshift(0);
if(Math.abs(c/4%2)){
v[i][1].pop();v[i][1].unshift(0)
}
}
if(c>0){for(i=0;i<4;i++){v[Math.random()*w|0][i%2][0]++}}
for(j=0;j<h;j++){
for(i=0;i<w;i++){
o+=v[i][0][j]+v[i][1][j]>0?'*':' ';
}
o+=`
`}
console.log(o);
if(c>-t*2){setTimeout(g=>S(c-4,v),t)}
})(t=100,[...new Array(w=80)].map(a=>[0,0].map(b=>new Array(h=25).fill(0))))
```
[Answer]
# C, ~~295~~ 282 bytes
```
#include <stdlib.h>
main(){int z=25,q=100,h=50,w=30,m[q][w],s=0,a[q],b[q],x,y;for(;s<q;s++){memset(m,32,sizeof m);system("cls");a[s]=rand()%w;b[s]=rand()%w;for(x=0,y=s;y&&x<h;)m[y/2][b[x]]=m[--y][a[x++]]=42;for(x=0;x<z;x++){for(y=0;y<w;y++)putchar(m[x][y]);printf("\n");}sleep(1);}}
```
I've used Dev-C++/Windows to run.
Ungolfed version:
```
#include <stdlib.h>
main(){
int z=25, // number of rows
q=100, // number of flakes
h=50, // number of flakes/2
w=30, // number of columns
m[q][w], // matrix to print
s=0, // counter
a[q], // fast flakes
b[q], // slow flakes
x,y; // aux
for(;s<q;s++){ // until the last slow flake takes the floor
memset(m,32,sizeof m); // clear the matrix (' '==32(ascii))
system("cls"); // clear windows console
a[s]=rand()%w; // random (s*2-1)º fast flake position
b[s]=rand()%w; // random (s*2)º slow flake position
for(x=0,y=s;y&&x<h;){ // set each flake position in matrix:
m[y/2][b[x]]=94; // slow flakes ('^'==94(ascii))
m[--y][a[x++]]=42; // fast flakes ('*'==42(ascii))
} //
printf("Frame %i:\n",s); // print frame number (step order)
for(x=0;x<z;x++){ // for each row in matrix
printf("%02i:",x); // print the row index
for(y=0;y<w;y++) // for each column in row
putchar(m[x][y]); // print slow/fast flake or space
printf("\n"); // for each row follows a new line
} // then
sleep(1); // wait one second till next step
}
}
```
Notes:
1. Maybe you'll need to maximize the console.
2. In the **ungolfed** code I did some extra prints for better visualization. Also used `^` for slow flakes.
] |
[Question]
[
This challenge is a slightly different kind of Code Golf challenge. Rather than coding to match IO, you code to match an interface.
### Background
[Finite state machines](https://en.wikipedia.org/wiki/Finite-state_machine) are very useful design models for modeling event-based programming. A state machine is defined by a set of states and tranitions between them. The machine can be in one and only one state at any given time: the *current state*. Naturally, the machine has an *initial state*. When an event occurs, it may change it's state to another state; this is called a *transition*. A [Moore machine](https://en.wikipedia.org/wiki/Moore_machine) is simply a FSM which can produce output; each state can produce an output.
For example, consider the following state machine which models a turnstile:
[](https://i.stack.imgur.com/FnkAzs.jpg "This is a turnstile - Image from Wikipedia")
[](https://en.wikipedia.org/wiki/File:Turnstile_state_machine_colored.svg)
The `Locked` state is the initial state of the machine. Whenever the turnstile is `Push`ed from this state, we do nothing (go back to the `Locked` state). However, if we receive a `Coin`, we transition to the `Un-locked` state. Extra `Coin`s do nothing, but a `Push` puts us back into the `Locked` state. It's not explicitly stated, but this FSM does have output: the `Locked` state has an output that tells the turnstile to lock it's arms, wheras the `Un-locked` state has an output that allows the turnstile to turn.
### Task
You must implement a state machine class. This means that only languages with objects can compete. If there is an accepted alternative to objects in your language, that is valid (e.g. C can use structs with member functions). You must be able to access the functions of the object via `obj.function` or `obj->function` or whatever the accessor character for your language is. You are allowed to use a state machine library if it exists for your language, but you aren't allowed to use a class from the library "as your own" (don't just point at a premade class and say that that's your solution).
You must implement the following methods with exactly the specified names and signatures. However, you may capitalize the first letter or switch to `snake_case` (e.g. `mapOutput`, `MapOutput`, or `map_output` are all valid). Additionally, you may take an explicit *this* parameter as the first parameter:
* `map(State from, Event event, State to)` Defines a transition from `from` to `to` on the event `event`. If `from` and `event` have both been previously passed to this method before, you may do anything at all.
* `mapOutput(State state, Output output)` Assigns the given output to the given state. If `state` has been previously passed to this method before, you may do anything at all.
* `processEvent(Event event)` Advances the state machine according to the transitions defined via `map`. Basically, if the current state of the state machine is `from`, then `event` sets the current state to the state defined by a previously called `map(from, event, to)`. Throws an exception or fails violently if there is no mapping for the current state and given event.
* `getOutput()` Gets the output for the current state, as defined via `mapOutput`. Returns `null` or equivalent if there is no output defined for the given state. This may be an `Optional` type or similar if your language has one.
* Some sort of initial-state setting. This may be done in the constructor for your class, you may require `State` to have a default constructor, or you may provide some other way of setting the initial state.
The idea of `State`, `Event`, and `Output` is that they are generic types. You don't have to support generics per se, but this means that the user of your state machine will only pass in the type `State` for states, the type `Event` for events, and the type `Output` for outputs. However, the state machine is expected to be "generic" in that it should be possible to use any type as a `State`, any type as an `Event`, and any type as an `Output`.
Additionally, you map implement the `map` and `mapOutput` methods in a separate builder class, but I don't foresee that saving any bytes.
## Test cases
Note: don't trust my code. It's untested. It's intended mostly to give an idea of what you state machine will be used like
Java, classname `StateMachine`, initial-state passed via constructor:
```
// States are ints, Events are chars, Outputs are ints
StateMachine machine = new StateMachine(0);
machine.map(0, '0', 1);
machine.map(0, '1', 2);
machine.map(0, '2', 3);
machine.map(1, '3', 0);
machine.map(1, '4', 2);
machine.map(2, '5', 0);
machine.map(2, '6', 1);
machine.map(2, '7', 2);
machine.mapOutput(1, 1);
machine.mapOutput(2, 10);
machine.mapOutput(3, 0);
// At this point, there should be absolutely no errors at all.
System.out.println(machine.getOutput()); // Should output `null`
machine.processEvent('0'); // Don't count on reference equality here...
System.out.println(machine.getOutput()); // Should output `1`
machine.processEvent('4');
System.out.println(machine.getOutput()); // Should output `10`
machine.processEvent('7');
System.out.println(machine.getOutput()); // Should output `10`
machine.processEvent('6');
System.out.println(machine.getOutput()); // Should output `1`
machine.processEvent('3');
System.out.println(machine.getOutput()); // Should output `null`
machine.processEvent('1');
System.out.println(machine.getOutput()); // Should output `10`
machine.processEvent('5');
System.out.println(machine.getOutput()); // Should output `null`
machine.processEvent('2');
System.out.println(machine.getOutput()); // Should output `0`
// Now any calls to processEvent should cause an exception to be thrown.
machine.processEvent('0'); // Throws an exception or crashes the program.
```
Ruby, classname `SM`, initial-state through `attr_writer` on `i`:
```
sm = SM.new
sm.i = :init # All states will be symbols in this case.
[
[:init, [], :init],
[:init, [1], :state1],
[:init, [2, 3], :state2],
[:state1, [], :init],
[:state1, [1], :state1],
[:state1, [2, 3], :state2],
[:state2, [], :init],
[:state2, [1], :state1],
[:state2, [2, 3], :state2]
].each { |from, trigger, to| sm.map(from, trigger, to) }
sm.mapOutput(:state1, [1])
sm.mapOutput(:state2, [[2, 3], 4, 5])
p sm.getOutput # => nil
sm.processEvent []
p sm.getOutput # => nil
sm.processEvent [1]
p sm.getOutput # => [1]
sm.processEvent [1]
p sm.getOutput # => [1]
sm.processEvent [2, 3]
p sm.getOutput # => [[2, 3], 4, 5]
sm.processEvent [2, 3]
p sm.getOutput # => [[2, 3], 4, 5]
sm.processEvent []
p sm.getOutput # => nil
sm.processEvent [2, 3]
p sm.getOutput # => [[2, 3], 4, 5]
sm.processEvent [1]
p sm.getOutput # => [1]
sm.processEvent []
p sm.getOutput # => nil
```
Note that even though there are only a few test cases, you must support arbitrary input to these functions.
[Answer]
# JavaScript (ES6), ~~132 125 121~~ 109
```
M=c=>(s={},r={},{map:(f,e,t)=>s[f+e]=t,mapOutput:(s,o)=>r[s]=o,processEvent:e=>c=s[c+e],getOutput:x=>r[c]})
```
*Thanks to [edc65](https://codegolf.stackexchange.com/users/21348/edc65) for his suggestion of avoiding the full-fledged constructor approach!*
Here's a test snippet that works in Chrome and Firefox:
```
M=c=>(s={},r={},{map:(f,e,t)=>s[f+e]=t,mapOutput:(s,o)=>r[s]=o,processEvent:e=>c=s[c+e],getOutput:x=>r[c]})
var sm = M('Locked');
var output = '';
var print = t => { output += t + "\n"; }
print(sm.getOutput() || 'not defined (there are no outputs currently defined)');
sm.map('Locked', 'Coin', 'Unlocked');
sm.map('Unlocked', 'Coin', 'Unlocked');
sm.map('Unlocked', 'Push', 'Locked');
sm.map('Locked', 'Push', 'Locked');
sm.mapOutput('Locked', 'Insert coin!');
sm.mapOutput('Unlocked', 'You can pass now.');
function event(name){
print(' >> ' + name);
sm.processEvent(name);
}
print(sm.getOutput());
event('Push');
print(sm.getOutput());
event('Coin');
print(sm.getOutput());
event('Coin');
print(sm.getOutput());
event('Push');
print(sm.getOutput());
alert(output);
```
[Answer]
# OCaml, 217
This is an anonymous function which takes the initial state as its sole parameter and returns a newly constructed object. The function/object are polymorphic in the state, event, and output types.
```
fun i->Hashtbl.(object
val o=create 9
val t=create 9
val mutable s=i
method map a b c=add t(a,b)c
method mapOutput a b=add o a b
method getOutput=try Some(find o s)with _->None
method processEvent e=s<-find t(s,e)end)
```
For a 200+-byte program, there seemed to be remarkably few opportunities for golfing.
Example usage:
```
let k =
fun i->Hashtbl.(object
val o=create 9
val t=create 9
val mutable s=i
method map a b c=add t(a,b)c
method mapOutput a b=add o a b
method getOutput=try Some(find o s)with _->None
method processEvent e=s<-find t(s,e)end)
;;
let pr optint = match optint with
| Some x -> Printf.printf "%d\n" x
| None -> Printf.printf "None\n" ;;
let machine = k 0;;
machine#map 0 '0' 1 ;;
machine#map 0 '1' 2 ;;
machine#map 0 '2' 3 ;;
machine#map 1 '3' 0 ;;
machine#map 1 '4' 2 ;;
machine#map 2 '5' 0 ;;
machine#map 2 '6' 1 ;;
machine#map 2 '7' 2 ;;
machine#mapOutput 1 1 ;;
machine#mapOutput 2 10 ;;
machine#mapOutput 3 0 ;;
pr machine#getOutput ;;
machine#processEvent '0' ;;
pr machine#getOutput ;;
machine#processEvent '4' ;;
pr machine#getOutput ;;
machine#processEvent '7' ;;
pr machine#getOutput ;;
machine#processEvent '6' ;;
pr machine#getOutput ;;
machine#processEvent '3' ;;
pr machine#getOutput ;;
machine#processEvent '1' ;;
pr machine#getOutput ;;
machine#processEvent '5' ;;
pr machine#getOutput ;;
machine#processEvent '2' ;;
pr machine#getOutput ;;
(* causes exception *)
machine#processEvent '0'
```
[Answer]
# C# (LinqPad) 318 Bytes
### Golfed Version
```
class S<T,K> where K:Hashtable,new(){public T c;K m=new K(),o=new K();public void Map(T f,char e,T t){if(!m.Contains(f))m.Add(f,new K());((K)m[f]).Add(e,t);}public void MapOutput(int t,object r){o.Add(t,r);}public void ProcessEvent(char e){c=(T)((K)m[c])[e];}public object GetOutput(){return o.Contains(c)?o[c]:null;}}
```
### Ungolfed Version
```
class S<T,K> where K:Hashtable,new()
{
public T c;
K m=new K(),o=new K();
public void Map(T f,char e,T t){if(!m.Contains(f))m.Add(f,new K());((K)m[f]).Add(e,t);}
public void MapOutput(int t,object r){o.Add(t,r);}
public void ProcessEvent(char e){c=(T)((K)m[c])[e];}
public object GetOutput(){return o.Contains(c)?o[c]:null;}
}
```
### Initialization:
```
var m = new S<int,Hashtable>();
```
### Setting initial State:
```
m.c = 0 // or whatever
```
If you don't use it in LinqPad you've got to add another "using System.Collections;" in front (+25 Bytes)
[Answer]
# Ruby, 174 bytes
```
class M
def initialize i
@c=@i=i
@s={}
@o={}
end
def map f,e,t
@s[[f,e]]=t
end
def mapOutput s,o
@o[s]=o
end
def processEvent e
@c=@s[[@c,e]]
end
def getOutput
@o[@c]
end
end
```
I think the code is pretty self-explanatory. This challenge is not challenging in Ruby.
] |
[Question]
[
## Introduction
Classes have started! And so does the boredom. I decided to doodle in my notebook and started to draw some dots in (IMO) an aesthetically pleasing way. I came up with these numbers:
[](https://i.stack.imgur.com/3Me2Z.png)
based on these conditions:
Given (n, m)
1) There must be *n* dots
2) All dots must lie on an *m* by *m* lattice
3) The position of the dots must minimize the spread\* from the top left corner
4) The configuration of the dots must be diagonally symmetric as pictured:
[](https://i.stack.imgur.com/m75KH.png)
\*Spread (in this context) is defined as the sum of the distances from the top left dot position (whether or not there is a dot there). For example, the spread of the example above is 0 + 1 + 2 + 1 + √2 + 2 + 2√2 = 6 + 3√2
## The Challenge
Come up with an algorithm using that uses *natural numbers* n and m (where it will always be that n <= m^2) to *generate* a configuration of dots that follow all the rules above.
**Input** can be received via STDIN, command-line argument, or function parameter.
**Output** the pattern to STDOUT or return a string with newlines. Any two different characters may be used in the output.
(e.g.
```
110
100
000
```
is the same as
```
**-
*--
---
```
**Shortest Code in Bytes Wins**
## Example
STDIN: `6 3`
STDOUT:
```
***
**_
*__
```
# The Challenge has Ended!!!
After seven days I decided to declare the winner, but first some special awards!
Fastest code goes to... orlp with his submission in Pyth !
Slowest code goes to... orlp with his submission in Pyth !
Most straightforward code goes to... orlp with his submission in Pyth !
Most confusing code goes to... orlp with his submission in Pyth !
Longest Code goes to... orlp with his submission in Pyth !
## And last but not least
**Shortest code goes to......... orlp with his submission in Pyth !**
Congratulations!
[Answer]
# Pyth, 37 bytes
```
jc:*d*QQiRQhos.aMNf.Am}_dTT.c^UQ2vzNQ
```
Slow solution. Generates all possible pairs of [0, m), generate all possible n-combinations of those pairs (without repetition). Filter each combination of pairs such that if P is in the combination, so is `reverse(P)`. This guarantees diagonal symmetry. Sort by the sum of distances to the origin. Decode the pairs of numbers as base-m numbers, giving a list of indices. Create a string of spaces except for those indices, putting quotation marks instead. Finally chop into m pieces and join by newlines. Creates outputs like such:
```
""""
"""
""
"
```
] |
[Question]
[
**This question already has answers here**:
[Calculate π with quadratic convergence](/questions/47912/calculate-%cf%80-with-quadratic-convergence)
(5 answers)
Closed 8 years ago.
Compute 30000 digits of the mathematical constant π, with the fastest code.
Implement in any computer programming language that I can run in my 64 bit Linux machine. You should provide your compiler optimization options if any. I am ready to install a new compiler or language runtime to run your code, given that I am not spending any money.
The code that finishes calculation and prints the output in the shortest time wins! I will measure the running time with the `time` command.
note 1: The program should be single threaded.
note 2: With 3.14, the number of digits is 3; with 3.1415, 5, and so on.
note 3: Hard coding π is not allowed.
note 4: Now you can use any number form in your code, not only integer.
note 5: Your output, which should be in decimal digits, need not contain the `.`. Just print out the numbers.
note 6: Your last digit should **not** be rounded up. If the next digit after the last is 5 or more, you should ~~round up your last digit~~ still leave the last digit as is.
*Since this question was marked as duplicate, to [this](https://codegolf.stackexchange.com/questions/47912/calculate-%CF%80-with-quadratic-convergence) question. I should explain that this is a 'fastest-code' question not 'code-golf' and thus not a dupliate. The 'code-golf' answers are not well suited as an answer to this question; they are not the 'fastest'.*
[Answer]
# Python 2 (Spigot Algorithm)
This is just Jeremy Gibbon's [algorithm](http://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/spigot.pdf) implemented in python. Definitely will be faster once someone else implements this in another language. Other methods might be faster too since I started working on this when the rules stated that I could only use integers. I originally tried doing this without string conversion and joining, but it was actually slower..
```
def p():
q,r,t,j=1,180,60,2
while True:
u,y=3*(3*j+1)*(3*j+2),(q*(27*j-12)+5*r)//(5*t);yield y;q,r,t,j=10*q*j*(2*j-1),10*u*(q*(5*j-2)+r-y*t),t*u,j+1
p=p()
print''.join(str(p.next())for x in[1]*30000)
```
Completes on my work machine in about 53 seconds.
] |
[Question]
[
The [Vigenère cipher](http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher) is a substitution cipher where the encryption of each letter of the plaintext depends on a different character in a keyword. This stops you using simple methods of frequency analysis to guess the correct substitution. However, the keyword is repeated if it is shorter than the plaintext. This is a weakness. If the length of the keyword is known (n, say), however, and is much shorter than the message, then you can decompose the message into separate sections by taking every nth letter. You can then use frequency analysis on these.
The [Kasiski examination](http://en.wikipedia.org/wiki/Kasiski_examination) is a method to work out the most likely key lengths. It does this by considering identical substrings which happen to be a multiple of the key length apart. They are therefore encrypted in the same way. Turning this round, identical substrings in the ciphertext are likely to be a multiple of the key length apart. If you identify these distances, then the key length is likely to be a common factor of all these distances.
Your job is to write a function or program that can guess the most likely length of the keyword, given some encrypted text. To be precise, the function or program (just called function below) will satisfy the following:
* Inputs consist of a string representing the ciphertext and a positive integer (**len**, for the purposes of this spec) representing the shortest common substring to look at.
* The ciphertext will consist of upper case A-Z characters only. Any length is permitted.
* You can assume valid inputs without checking.
* The inputs may be passed in, or read from stdin.
* The function will identify all pairs of identical substrings in the ciphertext which have a length of *at least* **len**.
* Substrings in each pair may not overlap but substrings in different pairs can overlap.
* The function will return, or write to stdout, the highest common factor of the distances between the starts of these identical pairs.
* If there are no identical substrings then the function will return 0.
For example:
"AAAAAAAAAAAAAAAAAA", n returns 1 for any n from 1 to 8, 9 for n = 9 (as the only possible non-overlapping substrings of length 9 happen to be the same) and 0 otherwise.
"ABCDEFGHIJKL", n returns 0 for any n
"ABCDEABCDE", n returns 5 for n<=5 and 0 otherwise
"ABCABABCAB", 2 returns 1 because "AB" pairs are separated by 2,3,5 & 8
"ABCABABCAB", 3 returns 5
"**VHVS**SP*QUCE*MRVBVBBB**VHVS**URQGIBDUGRNICJ*QUCE*RVUAXSSR", 4 returns 6 because the repeating "VHVS" are 18 characters apart, while "QUCE" is separated by 30 characters
Naturally, lowest byte count wins and avoid standard loopholes.
[Answer]
# CJam, 67 bytes
Definitely still room for improvement, but I'll post what I have so far.
[Try it online](http://cjam.aditsu.net/#code=0r%3AT%2C%2Cri%3E%7BT%2CL(-%2C_m*%7B~%3AXT%3EL%3CT%40LX%2Be%3E%2C%7B0t%7D%2FX%3E%5C%23_W%3E%5C2%24%3F%7B%5C1%24_!%2B%25%7Dh%3B%7D%2F%7DfL)
```
0r:T,,ri>{T,L(-,_m*{~:XT>L<T@LX+e>,{0t}/X>\#_W>\2$?{\1$_!+%}h;}/}fL
```
[Answer]
# JavaScript (ES6) 117
```
F=(s,n,G=(a,b)=>b?G(b,a%b):a)=>(i=>{
for(f=i;s[(j=i+n)-1];i++)
for(;p=~s.indexOf(s.substr(i,n),j++);)
f=G(~p-i,f)
})(0)|f
```
**Ungolfed**
```
F=(s,n)=>
{
var G = (a,b) => b ? G(b,a%b) : a; // GCD function
var p,w,i,j, f = 0; // f starting divisor
for(i = 0; s[i + n - 1]; ++i) // scan s for each substring of lenght n
{
w = s.substr(i,n);
for (j=i+n; (p = s.indexOf(w,j)) != -1; ++j) // find all occurrencies of substring in the rest f the string
f = G(p - i, f); // p-i is the distance between pairs
}
return f
}
```
**Test** In Firefox/FireBug console
```
;["AAAAAAAAAAAAAAAAAA","ABCDEFGHIJKL","ABCDEABCDE","ABCABABCAB",
"VHVSSPQUCEMRVBVBBBVHVSURQGIBDUGRNICJQUCERVUAXSSR"]
.forEach(s=>{
for(o=[],i=1;i<=10;i++) o.push(i+':'+F(s,i));
console.log(s+' '+o)
})
```
*Output*
```
AAAAAAAAAAAAAAAAAA 1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:1,9:9,10:0
ABCDEFGHIJKL 1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0
ABCDEABCDE 1:5,2:5,3:5,4:5,5:5,6:0,7:0,8:0,9:0,10:0
ABCABABCAB 1:1,2:1,3:5,4:5,5:5,6:0,7:0,8:0,9:0,10:0
VHVSSPQUCEMRVBVBBBVHVSURQGIBDUGRNICJQUCERVUAXSSR 1:1,2:1,3:6,4:6,5:0,6:0,7:0,8:0,9:0,10:0
```
] |
[Question]
[
I've created a new language called "EasyFlow." Your task is to simplify writing [BrainFlow](https://codegolf.stackexchange.com/q/36995/23550) programs by compiling EasyFlow to BrainFlow. That is, you take an EasyFlow program and output a BrainFlow program which does the same thing. EasyFlow is defined as follows:
* The program starts out with a list of variables. A variable is anything that matches `[a-zA-Z][a-zA-Z0-9]*`. The variables are separated by commas and the list is followed by a semicolon.
* The program then has zero or more statements. All statements are followed by a `;`. Each statement consists of
+ A print statement `print(<variable>);`
+ An input statement, which copies the next input byte into the variable: `input(<variable>);`.
+ An assignment: `<variable> = <expression>;`. An expression consists of an `<integer>` from 0 to 255 inclusive (but see bonuses for more).
+ An increment `<variable> += <expression>` or decrement `<variable> -= <expression>`.
+ Control statements
- `if(<variable>) { <statement>*; };` An if statement, which has a body of one or more if statements. Notice the semicolon at the end of the if statement.
- `while(<variable>) { <statement>*; };` A while statement.
Comments are denoted with `//` and, you must ignore everything for the rest of the line.
Spaces can be put anywhere except between variables (so `a b` is invalid and not equivalent to `ab`), between integers, and between `input`s and `print`s. Invalid syntax/statements, however, is undefined behavior.
**Input**:
Input can be taken from anywhere (file, HTML `<textarea>` element etc.)
Example input (doubles the char code of the input and outputs it as a character):
```
// Define variables
inputNumber, total;
// Get input
input(inputNumber);
// Set total to inputNumber * 2
// Reduce inputNumber and add 2 to total until inputNumber is 0
while (inputNumber) {
inputNumber -= 1;
total += 2;
};
print(total);
```
**Output**:
The output should be a valid BrainFlow program which does the same thing as the input program. However, you can use a shorthand notation `<command><number>` which indicates `<command>` repeated `<number>` times. This can only be applied to `+ - > <` commands. Note that this version of BrainFlow overflows numbers at 256, which is also the length of the tape. You do not have to worry about too many slots being taken up, the program is guaranteed to have less than or equal to 100 bytes as variables. In addition, there won't be anything extreme like `a[a[a[a ... repeat 50 times ]]]] = 6`.
```
[ The variable inputNumber is at location 0
and the variable total is at location 1 ]
, Get input for inputNumber
[
- Subtract 1
> Move to location of total
+2 Add two
< Move to location of inputNumber
]
>. Print the number
```
**Bonuses**:
There are a wide variety of bonuses you can earn. Your final score is your character count multiplied by all the bonuses that you earn. The bonuses are:
* *0.9*: Instead of invalid syntax/statements being undefined behavior, fail to compile, printing the line number of the invalid syntax. This means your program should fail to compile on `a b = 5;` or `c = 3 5;` or `prin t(a);`. (The error message can read `E:<line>`
* *0.9*: Allow declarations of arrays as `<variable>[<integer]`. All arrays must have a fixed length. Allow access from arrays using `<variable>[<expression>]`. Assigning `<variable> = <expression>` is an invalid statement if `<variable>` is an array. In addition `LEN(<variable>)` should return the (constant) length of `<variable>`.
* *0.7*: Allow `<expression>` to also be a `<variable>`. That is, the following should correctly compile: `a = b;`, `a[a[0]] = c;`, `b[a[a[b]]] = c;` and so on. (Of course, the array part only applies if you took that bonus).
+ These bonuses are obtainable after getting the previous bonus.
+ *0.7*: Allow `<expression>` to be addition and subtraction. That is, we have `<expression> + <expression>` or `<expression> - <expression>`.
+ *0.7*: Allow `<expression>` to include `==, !, &&, ||` operators
+ *0.6*: Allow `<expression>` to include `<, <=, >, >=` operators
+ *0.5*: Allow multiplication. This must follow the order of operations e.g. `<epxression> + <expression> * <expression>`.
* *0.00000000000001*: Compile C to BrainFlow. (Please don't actually do this)
Example with a few bonuses:
**Input**: (Calculates the last one-based index of a given number in the string "141592" or 0 if it doesn't exist).
```
pi[6], inputNumber, index, finalIndex; // An array with 6 slots and input number
pi[0] = 1;
pi[1] = 4;
pi[2] = 1;
pi[3] = 5;
pi[4] = 9;
pi[5] = 2;
input(inputNumber);
inputNumber -= 48; // Get inputNumber as a digit
index = LEN(pi); // evaluates to index = 6
while (index) {
index -= 1;
if (inputNumber == pi[index]) {
finalIndex = index + 1;
index = 0; // break the loop
};
};
finalIndex += 48; // Hack to convert to character if finalIndex < 10
print(finalIndex);
```
You can find an interpreter for brainflow written in coffeescript [here](http://goo.gl/A0In9H) (along with the compiled version of the above program).
This is code golf. The answer with the lowest score wins.
Here is my attempt in ES6 javascript function at a whopping 561 characters if white space and comments are removed and with no bonuses:
```
// Defines a function called `compile`
compile = a => {
h = a => {
for (; a;) {
// Create a copy of the input string
var c = a;
// Replace print statements with "."
a = a[R](l, (a, d) => {
e(d);
b += ".";
return ""
})[R](m, (a, d) => { // Replace input statements with ","
e(d);
b += ",";
return ""
})[R](n, (a, d, c, g) => { // Replace equal to, increment, and decrements
e(d);
b += (c || "[-]+") + g;
return ""
})[R](p, (a, c, f, g) => { // Replace if and while loops
e(f);
b += "[";
h(g);
"if" == c ? b += "[>]^" : e(f);
b += "]";
return ""
});
// If the copy is the same as the input string
// i.e. no changes were made in replacing, we've reached the end, break
if (c == a) break
}
};
// A function which moves to the variable location
e = a => {
// Go to zeroth position
b += "[>]^";
// f[a] is where the variable is located, move there
b += ">" + f[a]
};
var b = "",
R = "replace";
// Remove comments and whitespace
a = a[R](/\/\/.*?\n/g, "")[R](/[\s\n\t]+|/g, "");
// Regexes
var l = /^print\((.*?)\);/, // Print statements
m = /^input\((.*?)\);/, // Input statements
n = /^([a-zA-Z0-9]+)([\+\-]?)=(\d+);/, // Assignments
p = // If and while statements
/(if|while)\((.*?)\)\{(.*?)\};/,
k = a.split(";")[0].split(","); // Get the variables
a = a.slice(a.indexOf(";") + 1); // Strip variables from program
// Assign each variable a unique index
for (var f = {}, c = 0; c < k.length; ++c) f[k[c]] = c;
// Compile
h(a);
return b // Return
};
```
I'm sure many people can do better!
[Answer]
# Javascript ES6 - 366 bytes
Minified:
```
C=a=>(R="replace",e=a=>"[>]^>"+C[a],h=a=>a[R](/(if|while)\((.*?)\)\{(.*?)\};/g,(a,c,f,g)=>e(f)+"["+h(g)+(c[2]?e(f):"[>]^")+"]")[R](/print\((.*?)\);/g,(a,d)=>e(d)+".")[R](/input\((.*?)\);/g,(a,d)=>e(d)+",")[R](/([a-z\d]+)(\W?)=(\d+);/ig,(a,d,c,g)=>e(d)+(c||"[-]+")+g),[,k,a]=/(.*?);(.*)/.exec(a[R](/\/\/.*?\n/g,'')[R](/\s+/g,'')),k.split(",").map((a,b)=>C[a]=b),h(a))
```
Expanded:
```
C = a => (
R = "replace",
e = a => "[>]^>" + C[a],
h = a =>
a[R]( /(if|while)\((.*?)\)\{(.*?)\};/g,
(a, c, f, g) => e(f) + "[" + h(g) + (c[2] ? e(f) : "[>]^") + "]" )
[R]( /print\((.*?)\);/g,
(a, d) => e(d) + "." )
[R]( /input\((.*?)\);/g,
(a, d) => e(d) + "," )
[R]( /([a-z\d]+)(\W?)=(\d+);/ig,
(a, d, c, g) => e(d) + (c || "[-]+") + g ),
[,k,a] = /(.*?);(.*)/.exec( a[R]( /\/\/.*?\n/g, '' )[R]( /\s+/g, '' ) ),
k.split(",").map( (a,b) => C[a] = b ),
h(a)
)
```
This is simply a tweaked, refactored, and re-golfed version of the reference implementation in the OP. Most of the saved bytes occur through regex optimizations, elimination of loops, and switching from a push (i.e. `b += ...`) architecture to an inline architecture.
My apologies for the lack of creativity, but it's all I had time for. Hopefully it will inspire a few more intrepid souls to take the plunge. ;)
] |
[Question]
[
Imagine you are given two lists of numbers which are to be interpreted as points on a circle of circumference 1000. Let us say
```
circleA = [10, 24, 44, 175, 321, 579, 618, 841, 871, 979]
circleB = [270, 283, 389, 406, 435, 457, 612, 684, 692, 732]
```
To measure the distance between these two circles we do the following.
For the first point in circleA, starting from the left, we find the next biggest point in circleB. So 10 finds 270 and is matched up with it. Now, using 270, we skip to the next biggest point in circle A which is 321. We then use 321 to find 389 and match up 321 and 389 and repeat until the end of circleA or we can't find a matching pair.
This gives us a list of pairs as follows.
```
[(10,270), (321, 389), (579,612), (618,684)]
```
We say the distance between circleA and circleB is just the average difference between pairs. That is (270-10 + 389-321+612-579+684-618)/4 = 106.75
Now comes the tricky part. As the point are on a circle, we can rotate circleB and recompute this distance. The task is to compute the following value.
>
> For arbitrary inputs circleA and circleB, the task is to compute the
> average distance between circleA and all rotations of circleB.
>
>
>
In order to make it interesting I am setting this as fastest-code challenge. I will test with increasing size circles created using (in python)
```
import random
circumference = 1024
numberpoints = circumference/64
circleA = sorted(random.sample(range(circumference),numberpoints))
circleB = sorted(random.sample(range(circumference),numberpoints))
```
I will just double the size of circumference until the code takes more than 1 minute to run on my computer. You output should be accurate to machine precision.
Please provide full instructions for how to compile and run your code on a linux machine.
---
A rotation simply means adding an offset modulo `circumference` and then resorting. In python
```
rotatedcircleB = sorted([(c+offset)%circumference for c in circleB])
```
[Answer]
This algorithm is basically the same as [@fredtantini](https://codegolf.stackexchange.com/users/18720/fredtantini)'s. The main difference is I keep a rolling sum instead of creating a list to hold the differences. I also forgo the list slicing as it is **[an O(k) operation](https://wiki.python.org/moin/TimeComplexity)**.
```
from __future__ import division
from bisect import bisect_left
import timeit
def circular_distance(circle_a, circle_b):
total = 0
count = 0
value_on_a = circle_a[0]
value_on_b = 0
while 1:
try:
insertion_point = bisect_left(circle_b, value_on_a)
value_on_b = circle_b[insertion_point]
total += value_on_b - value_on_a
count += 1
value_on_a = circle_a[bisect_left(circle_a, value_on_b+1)]
except IndexError:
break
return total/count
def rotate(circle, offset, circumference=1024):
return sorted((point + offset) % circumference for point in circle)
def get_average_distance(circle_a, circle_b, circumference=1024):
total = 0
for iteration_num in xrange(circumference):
total += circular_distance(circle_a, rotate(circle_b, iteration_num))
return total/circumference
```
These changes resulted in about a 64% improvement for 10,000 iterations on my machine:
```
+------------------+-------------------------+
| List and slicing | Rolling sum and average |
+--------------------+------------------+-------------------------+
| Per Iteration (ms) | 0.0128661600274 | 0.00821646809725 |
+--------------------+------------------+-------------------------+
| Total (s) | 128.661600274 | 82.1646809725 |
+--------------------+------------------+-------------------------+
```
[Answer]
My first try at a `fatest-code` question. Problem is, I didn't try any optimization…
If the rotation part isn't correct, please tell me.
Also, I don't know how to time test the code, so I tried to use `timeit` module to run 1000 times in order to have a correct timing. I am not sure if I have to do that, or if it is your part :þ
Anyway, here is my code:
```
import random
circumference = 1024
numberpoints = circumference/64
circleA = sorted(random.sample(range(circumference),numberpoints))
circleB = sorted(random.sample(range(circumference),numberpoints))
####
from bisect import bisect_left
def find_next(a, x):
i = bisect_left(a, x)
if i != len(a):
return i, a[i]
raise ValueError
def dist1(cA, cB):
l = []
p = cA[0]
cA = cA[1:]
while True:
try:
(i, n) = find_next(cB, p)
l.append(n-p)
cB = cB[(i+1):]
(i, p) = find_next(cA, n)
cA = cA[(i+1):]
except:
break
return (sum(l)/len(l))
def rotate(circleB,i):
return sorted([(c+i)%circumference for c in circleB])
def distAll(circleA, circleB):
l = [dist1(circleA, rotate(circleB,i)) for i in xrange(circumference)]
return sum(l)/circumference
if __name__ == '__main__':
import timeit
print(timeit.timeit("distAll(circleA,circleB)", setup="from __main__ import *", number=1000))
```
[Answer]
# C
The first argument is a filename which the program expects to read for input. The first line of the file contains the circumference and the number of points each of circle a and circle b. Then the values for circle a follow, one per line; then the values of circle b, one per line.
The time spent reading the input is a huge portion of the overall running time, but I wasn't sure how to get so much input into the program without resorting to file I/O. If anyone has a better solution to that (or any suggestions in general) please feel free to chime in.
Compile it with -O3 for extra speed!
```
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
static inline void rotateB(int_fast32_t* const, int_fast32_t, int_fast32_t, int_fast32_t);
static inline void getDistances(const int_fast32_t* const, const int_fast32_t* const, int_fast32_t, int_fast32_t, int_fast32_t* const, int_fast32_t* const);
static inline int comparePoints(const void*, const void*);
static inline int_fast32_t getNextIndex(const int_fast32_t* const, int_fast32_t, int_fast32_t, int_fast32_t);
int main(int argc, char* argv[]) {
int_fast32_t counter;
int_fast32_t *circleA;
int_fast32_t *circleB;
int_fast32_t CIRCUMFERENCE;
int_fast32_t lengthOfA;
int_fast32_t lengthOfB;
FILE *fp = fopen(argv[1], "r");
fscanf(fp, "%d %d %d\n", &CIRCUMFERENCE, &lengthOfA, &lengthOfB);
circleA = malloc(sizeof(int_fast32_t)*lengthOfA);
circleB = malloc(sizeof(int_fast32_t)*lengthOfB);
for(counter = 0; counter < lengthOfA; counter++)
fscanf(fp, "%d\n", &(circleA[counter]));
for(counter = 0; counter < lengthOfB; counter++)
fscanf(fp, "%d\n", &(circleB[counter]));
fclose(fp);
int_fast32_t totalDistance = 0;
int_fast32_t numberOfPairs = 0;
for(counter = 0; counter < CIRCUMFERENCE; counter++) {
rotateB(circleB, counter, lengthOfB, CIRCUMFERENCE);
getDistances(circleA, circleB, lengthOfA, lengthOfB, &totalDistance, &numberOfPairs);
}
printf("%f\n", ((double)totalDistance)/((double)numberOfPairs));
free(circleA);
free(circleB);
return 0;
}
static inline void rotateB(int_fast32_t* const circleB, int_fast32_t offset, int_fast32_t length, int_fast32_t CIRCUMFERENCE) {
int_fast32_t counter;
for(counter = 0; counter < length; counter++)
circleB[counter] = (circleB[counter] + offset) % CIRCUMFERENCE;
qsort(circleB, length, sizeof(int_fast32_t), comparePoints);
}
static inline int comparePoints(const void* a, const void* b) {
return (*((int_fast32_t*)a)) - (*((int_fast32_t*)b));
}
static inline void getDistances(const int_fast32_t* const circleA, const int_fast32_t* const circleB, int_fast32_t lengthOfA, int_fast32_t lengthOfB, int_fast32_t* const totalDistance, int_fast32_t* const numberOfPairs) {
int_fast32_t currentAIndex = 0;
int_fast32_t currentBIndex = getNextIndex(circleB, circleA[currentAIndex], 0, lengthOfB);
while((currentAIndex < lengthOfA) && (currentBIndex < lengthOfB)) {
*totalDistance += circleB[currentBIndex] - circleA[currentAIndex];
*numberOfPairs += 1;
currentAIndex = getNextIndex(circleA, circleB[currentBIndex], currentAIndex, lengthOfA);
currentBIndex = getNextIndex(circleB, circleA[currentAIndex], currentBIndex, lengthOfB);
}
}
static inline int_fast32_t getNextIndex(const int_fast32_t* const targetCircle, int_fast32_t otherValue, int_fast32_t currentIndex, int_fast32_t length) {
int_fast32_t lowerBound = currentIndex;
int_fast32_t upperBound = length-1;
int_fast32_t guess;
if(targetCircle[upperBound] <= otherValue)
return length;
while(1) {
if(upperBound - lowerBound < 4) {
while(targetCircle[lowerBound] <= otherValue)
lowerBound++;
return lowerBound;
}
guess = (lowerBound + upperBound) >> 1;
if(targetCircle[guess] > otherValue)
upperBound = guess;
else
lowerBound = guess;
}
return lowerBound;
}
```
] |
[Question]
[
## Short version
[`RC4`](https://en.wikipedia.org/wiki/RC4), designed in 1987, is one of the most famous stream ciphers. This question asks you to practically demonstrate its [2nd byte bias](https://en.wikipedia.org/wiki/RC4#Biased_outputs_of_the_RC4) (for a theoretical proof, see section 3.2 of this [paper](http://www.wisdom.weizmann.ac.il/~itsik/RC4/Papers/bc_rc4.ps)).
## Long version
OK, here I try to elaborate it for non-cryptographers. As you have noted, `RC4` is a very popular cipher in the cryptographic domain, mainly because of its simplicity. It consists of a *register* (i.e., array) of length 256, each element of this register can hold up to 8 bits.
Here's a quick overview of how stream ciphers commonly work: a secret `key` is taken, a **Key-scheduling algorithm (KSA)** is performed (which takes the `key` as input), followed by a **Pseudo-random generation algorithm (PRGA)** (which outputs a sufficiently long random-looking `key-stream`). To *encrypt* (resp. *decrypt*), one has to bit-wise XOR this `key-stream` with the `plaintext` (resp. `ciphertext`).
For `RC4`, the `key` is of length 1 to 256. The **KSA** and **PRGA** are performed on the 256 byte register `S` as follows:
**KSA**
```
for i from 0 to 255
S[i] := i
endfor
j := 0
for i from 0 to 255
j := (j + S[i] + key[i mod keylength]) mod 256
swap values of S[i] and S[j]
endfor
```
**PRGA**
```
i := 0, j := 0
while GeneratingOutput:
i := (i + 1) mod 256
j := (j + S[i]) mod 256
swap values of S[i] and S[j]
K := S[(S[i] + S[j]) mod 256]
output K
endwhile
```
These `K`'s constitute the `key-stream`. After getting first 256 bytes of the `key-stream`, you need to count the frequency of each number from 0 to 255 in the `key-stream`, occuring in each position for a given `key`.
The interesting thing is that, even if the `key`s are taken at random, you will notice the `key-stream` is far from random - "the frequency of the second byte is zero" is nearly double of what it actually should be (if it were truly random). This is known as [distinguishing attack](https://en.wikipedia.org/wiki/Distinguishing_attack).
Your task is to:
1. Take *as much as you can* random `key` of 16 bytes
2. Generate the `key-stream` of first 2 bytes for each `key`
3. Count the number of times zero appears at the 2nd byte of each the `key-stream`s
You program should be capable of taking at least 2^19 - 2^20 `key`s, *and make the code run as fast as you can*.
Here's a quick try of me in Python:
```
def ksa(S):
key = range(256)
j = 0
for i in range(256):
j = (j + key [i] + S [i % len(S)]) % 256
key [i], key [j] = key [j], key [i]
return key
def prga (key):
i = 0; j = 0
while True:
i = (i + 1) % 256
j = (j + key [i]) % 256
key [i], key [j] = key [j], key [i]
yield key [(key [i] + key [j]) % 256]
def encrypt_or_decrypt (text, S):
alt_text = []
key = ksa (S)
prga_generator = prga(key)
for byte in text:
alt_text.append (prga_generator. next())
return tuple (alt_text)
if __name__ == '__main__':
from time import time
stime = time ()
import sys
rounds = int (sys.argv [1]); text_length = 256; key_length = 16
text = [0 for x in range(text_length)]
out = list ()
import random, numpy as np
for r in range (rounds):
S = [random.randint(0, 255) for x in range (key_length)]
out.append (encrypt_or_decrypt (text, S))
print str (range (256)) [1:-1]
for o in np.transpose (out):
temp = list(np.bincount (o))
while len (temp) < 256:
temp.append (0)
print str (temp)[1:-1]
print time () - stime
```
Pipe the output to a CSV file and note the content of A3 cell, after opening it with an office package *(it should be nearly double of each of the other cells)*.
This one is of 524288 `key`s (it took 220.447999954s of my i5 processor, 4 GB RAM):

***BONUS:*** Create the whole 256 by 256 frequency matrix, where rows indicate the frequency of a number (in 0 to 255) and columns indicate the corresponding byte position (from 1 to 256).
# Winning conditions
---
* Fastest in terms of # iterations/ second in my computer
* Single-threaded execution only (multi-threaded versions are also welcome here, but not as a participant)
* For tie (or nearly tie) cases, popularity and capability of more iterations will be considered (though I suppose there will be no such situation)
* No need for *true* random numbers, *pseudo* random numbers will suffice, as it is not a cryptographic contest
**Update**
In my computer, here are the results (2^24 iterations):
1. bitpwner The 256 \* 256 matrix in 50.075s
2. Dennis The bias 19.22s
Since, there seems no more answer coming in, I declare Dennis as the winner. *bitpwner did really good with the big matrix.*
[Answer]
## C
Takes about 111 secs to run on my Macbook Air for 2^24 = 16777216 trials.
To compile: `gcc -o rc4 rc4.c`
To pipe the output to a csv: `./rc4 > rc4out.csv`
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdlib.h>
#include <sys/time.h>
#define KEY_LENGTH 16
#define ITERATIONS 16777216
void ksa(unsigned char state[], unsigned char key[]) {
int i,j=0,t;
for (i=0; i<256; ++i)
state[i] = i;
for (i=0; i<256; ++i) {
j = (j + state[i] + key[i % KEY_LENGTH]) % 256;
t = state[i];
state[i] = state[j];
state[j] = t;
}
}
void prga(unsigned char state[], unsigned char out[]) {
int i=0,j=0,x,t;
unsigned char key;
for (x=0; x<256; ++x) {
i = (i + 1) % 256;
j = (j + state[i]) % 256;
t = state[i];
state[i] = state[j];
state[j] = t;
out[x] = state[(state[i] + state[j]) % 256];
}
}
void makeRandomKey(unsigned char key[]) {
int i;
for (i=0; i<KEY_LENGTH; ++i)
key[i] = rand() % 256;
}
int main(int argc, char *argv[]) {
struct timeval time_started, time_now, time_diff;
gettimeofday(&time_started, NULL);
unsigned char state[256];
unsigned char out[256];
unsigned char key[KEY_LENGTH];
int occurances[256][256];
int i,j,bytePosition,charOccurance;
for (i=0; i<256; ++i)
for (j=0; j<256; ++j)
occurances[i][j] = 0;
srand(time(NULL));
for (i=0; i<ITERATIONS; ++i) {
makeRandomKey(key);
ksa(state, key);
prga(state, out);
for (j=0; j<256; ++j)
++occurances[j][out[j]];
}
for (bytePosition=0; bytePosition<256; ++bytePosition) {
printf("%d,", bytePosition);
}
printf("\n");
for (charOccurance=0; charOccurance<256; ++charOccurance) {
for (bytePosition=0; bytePosition<256; ++bytePosition) {
printf("%d,", occurances[charOccurance][bytePosition]);
}
printf("\n");
}
gettimeofday(&time_now, NULL);
timersub(&time_now, &time_started, &time_diff);
printf("Time taken,%ld.%.6ld s\n", time_diff.tv_sec, time_diff.tv_usec);
return 0;
}
```
Results for 16777216 trials.

Multithreaded version [here](http://pastebin.com/YLcTyXrS). Compile with `gcc -o rc4 rc4.c -pthreads`.
[Answer]
# C (1,432,725 keys / second)
```
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define RAND_64() *Ks = rand(), Ks++, *Ks = rand(), Ks++, *Ks = rand(), Ks++, *Ks = rand()
#define KSA_1() t = *s, j += t + *k, *s = S[j], S[j] = t, s++
#define KSA_4() KSA_1(); k++; KSA_1(); k++; KSA_1(); k++; KSA_1()
#define KSA_16() KSA_4(); k++; KSA_4(); k++; KSA_4(); k++; KSA_4(); k = K
#define KSA_64() KSA_16(); KSA_16(); KSA_16(); KSA_16()
int main(int argc, char *argv[])
{
int i, m = atoi(argv[1]), r = 0;
uint8_t j, K[16], *k = K, S[256], *s, S0[256], t;
uint16_t *Ks;
for(i = 0; i < 256; i++) S0[i] = i;
srand(time(NULL));
for(i = 0; i < m; i++)
{
Ks = (uint16_t *) K, RAND_64(), Ks++, RAND_64();
memcpy(S, S0, 256); s = S, j = 0;
KSA_64(); KSA_64(); KSA_64(); KSA_64();
j = S[1], S[1] = S[j], S[j] = j;
t = S[2], j += t, S[2] = S[j], S[j] = t, t += S[2];
r += (S[t] == 0);
}
printf("%u\n", r);
}
```
### Benchmarking
```
$ gcc -Ofast rc4bias-rand.c && time ./a.out $[2**24]
130924
Real 11.71
User 11.71
Sys 0.00
$ bc <<< '2^24 / 11.71'
1432725
```
Tested on an Intel i7-3770 running Fedora 20.
] |
[Question]
[
From [Wikipedia](http://en.wikipedia.org/wiki/PESEL):
>
> **PESEL** is the
> national identification number used in Poland since 1979. It always
> has 11 digits, identifies just one person and cannot be changed to
> another one.
>
>
> It has the form of YYMMDDZZZXQ, where YYMMDD is the date of birth
> (with century encoded in month field), ZZZ is the personal
> identification number, X denotes sex (even number for females, odd
> number for males) and Q is a control digit, which is used to verify
> whether a given PESEL is correct or not.
>
>
> Having a PESEL in the form of ABCDEF GHIJK, one can check the
> vailidity of the number by computing the following expression:
>
>
> A\*1 + B\*3 + C\*7 + D\*9 + E\*1 + F\*3 + G\*7 + H\*9 + I\*1 + J\*3
>
>
> Then the last digit of the result should be subtracted from 10. If the
> result of the last operation is not equal to the last digit of a given
> PESEL, the PESEL is incorrect. This system works reliably well for
> catching one-digit mistakes and digit swaps.
>
>
>
Provide **a short program to generate random, valid PESEL number**:
1. It has to be a PESEL a person born in either 20th or 21st century
2. The birth birth date has to be random but doesn't have to validate leap years or number of days in a month (i.e. the numbers representing the day number have to be between `01` and `31`)
3. All valid PESELs in this date range (01.01.1990-31.12.2099) must be possible
4. The shortest code (i.e. complete program code), in bytes, wins.
[Answer]
# Perl, 162 bytes
```
@a=map{$==rand 10}0..9;$"='';$a[5]%=2if($a[4]%=4)==3;"@a[4,5]"||$a[5]++;$a[3]=($a[2]%=4)%2?$a[3]%3:1+$a[3]%9;$f=9;for(@a){$x+=$f*$_;$f-=$f%10==7?4:2}print@a,$x%10
```
## Ungolfed:
```
# Array with random digits
# ------------------------
@a = map { $= = rand 10} 0..9;
# do not insert a space, if arrays are interpolated into strings
$" = ''; #"
# Day correction
# --------------
# The day must be in the range of "01" to "31":
# * map first digit to "0" to "3": $a[4] %= 4
# * map second digit to "0" to "1" if first digit is "3"
$a[5] %= 2 if ($a[4] %= 4 ) == 3;
# * set day to "01" if day is "00"
"@a[4,5]" || $a[5]++;
# Month correction
# ----------------
# The month must be in the range "01" to "12" or "21" to "32"
# to get a valid month and century:
# * map the month to "00" to "39"
# * if the first digit is odd (catching both centuries at once)
# * then map the second digit to "0" to "2" (for months: 10..12)
# * otherwise map the second digit to "1" to "9" (for months: 01-09)
$a[3] = ($a[2] %= 4) % 2 ? $a[3] % 3: 1 + $a[3] % 9;
# Calculate the control digit
# ---------------------------
# Because of the modulo 10 operations, the formula for the calculation
# of the control digit is rewritten from
# Q = (10 - ((A + 3B + 7C + 9D + E + 3F + 7G + 9H + I + J) % 10)) % 10
# to
# Q = (9A + 7B + 3C + D - E - 3F -7G - 9H - 11I - 11J) % 10
$f = 9;
for (@a) {
$x += $f * $_;
$f -= $f % 10 == 7 ? 4 : 2
}
# Print the result and control digit
print @a, $x % 10
# TEST section
# ------------
;$Q = $x % 10; # remember control digit in $Q
# Pretty print PESEL
print "\n\n",
"YY MM DD ZZZ X Q\n",
"@a[0,1] @a[2,3] @a[4,5] @a[6,7,8] $a[9] $Q\n";
print "\n";
# Pretty print the date
$month = "@a[2,3]";
$century = "??";
$century = "19" if $month >= 1 and $month <= 12;
$century = "20" if $month >= 21 and $month <= 32;
printf "Date: $century@a[0,1]-%02d-@a[4,5]\n", $month % 20;
print "\n";
# Pretty print the gender
print "Gender: ", $a[9] % 2 ? "male" : "female", "\n";
print "\n";
# Calculate the control date the official way
print "Control digit:\n";
$sum = 0;
$f = 0;
for (my ($i, $f) = (0, 1); $i<10; $i++, $f+=2) {
$f %= 10;
$f += 2 if $f == 5;
printf " $a[$i] * $f = %2d\n", $a[$i] * $f;
$sum += $a[$i] * $f;
}
print " ", "-" x 10, "\n";
printf " %10d\n", $sum;
printf " $Q = (10 - ($sum % 10)) % 10 = %d\n", (10 - ($sum % 10)) % 10;
```
## Examples
```
83102570819
YY MM DD ZZZ X Q
83 10 25 708 1 9
Date: 1983-10-25
Gender: male
Control digit:
8 * 1 = 8
3 * 3 = 9
1 * 7 = 7
0 * 9 = 0
2 * 1 = 2
5 * 3 = 15
7 * 7 = 49
0 * 9 = 0
8 * 1 = 8
1 * 3 = 3
----------
101
9 = (10 - (101 % 10)) % 10 = 9
```
```
20233143600
YY MM DD ZZZ X Q
20 23 31 436 0 0
Date: 2020-03-31
Gender: female
Control digit:
2 * 1 = 2
0 * 3 = 0
2 * 7 = 14
3 * 9 = 27
3 * 1 = 3
1 * 3 = 3
4 * 7 = 28
3 * 9 = 27
6 * 1 = 6
0 * 3 = 0
----------
110
0 = (10 - (110 % 10)) % 10 = 0
```
[Answer]
# Mathematica ~~247~~ 270
A bit long but there are many details to take into consideration:
* Allow any valid birth date between Jan. 1, 1900 and Dec. 31, 2099; Feb. 29 included in leap years.
* Pad all numbers left with zeros: e.g. Month 3 becomes "03" so any PESEL will have exactly 11 digits.
* Add 20 to month if in 21st century (2000-2099)
## Ungolfed
Below the components are named for convenience.
```
g:=Module[{year,month,day,centuryIncrement,id,controlDigit,pesel},
{year,month,day}=DatePlus[{1900,1,1},RandomInteger[73048]];
centuryIncrement=20*Boole[year>= 2000];
Print[Row@{{year,month,day}," ",DateString[{year,month,day},{"MonthName"," ","Day",", ","Year"}]},
"\ncentury increment: ",centuryIncrement,
"\nID: ",id=PadLeft[IntegerDigits@RandomInteger[999],3],
"\nsex: ",sex=RandomInteger[1]];
f=Flatten[{{IntegerDigits@year,PadLeft[IntegerDigits[month+centuryIncrement],2],
PadLeft[IntegerDigits@day,2]},id,sex}][[3;;12]];
Print["control digit: ",controlDigit=Mod[10-IntegerDigits[Tr@Thread[Times[f,{1,3,7,9,1,3,7,9,1,3}]]][[-1]],10],
"\nPESEL: ",""<>ToString/@PadLeft[Append[f,controlDigit]]]]
```
## Examples
```
g
```
>
> {1931,2,9} February 09, 1931
>
> century increment: 0
>
> ID: {0,8,8}
>
> sex: 0
>
> control digit: 9
>
> PESEL: 31020908809
>
>
>
---
```
g
```
>
> {2067,6,27} June 27, 2067
>
> century increment: 20
>
> ID: {9,0,8}
>
> sex: 0
>
> control digit: 1
> PESEL: 67262790801
>
>
>
---
```
g
```
>
> {1967,9,5} September 05, 1967
>
> century increment: 0
>
> ID: {5,0,0}
>
> sex: 0
>
> control digit: 2
>
> PESEL: 67090550002
>
>
>
---
## Golfed
```
g:=Module[{y,m,d,i=IntegerDigits,p=PadLeft,r=RandomInteger},{y,m,d}=DatePlus[{1900,1,1},r[73048]];
f=Flatten[{{i@y,p[i[m+20*Boole[y>= 2000]],2],p[i@d,2]},p[i@r[999],3],r[1]}][[3;;12]];
""<>ToString/@p[Append[f,Mod[10-i[Tr@Thread[Times[f,{1,3,7,9,1,3,7,9,1,3}]]][[-1]],10]]]]
```
[Answer]
# PHP, 151
```
echo($n=date("ymd",rand(-2e9,4e9)).rand(101,999).rand()%10).(10-($n[0]+3*$n[1]+7*$n[2]+9*$n[3]+$n[4]+3*$n[5]+7*$n[6]+9*$n[7]+$n[8]+3*$n[9])%10);
```
See it in action: <http://ideone.com/DYeXf9>
[Answer]
# Mathematica, 220
This generates random date between 1900-01-01 and 2099-12-31, but it does not check whether the number of days in the month is valid.
Value for gender ranges from 0 - 9.
This is as few characters as I could get it:
```
r=RandomInteger;a=r@9;b=r@9;m=r@11+1+r@1*20;c=Floor[m/10];d=m~Mod~10;n=r@30+1;e=Floor[n/10];f=n~Mod~10;g=r@9;h=r@9;i=r@9;j=r@9;k=Mod[10-Mod[a+3b+7c+9d+e+3f+7g+9h+i+3j,10],10];StringJoin[ToString/@{a,b,c,d,e,f,g,h,i,j,k}]
```
## Sample output:
```
04020506179
```
```
34230487249
```
```
26321891950
```
```
45260298217
```
## Ungolfed:
```
r=RandomInteger;
a=r@9; (*year*)
b=r@9;
month=r@11+1+r@1*20;
c=Floor[month/10];
d=month~Mod~10;
day=r@30+1;
e=Floor[day/10];
f=day~Mod~10;
g=r@9; (*personal ID*)
h=r@9;
i=r@9;
j=r@9; (*gender*)
k=Mod[10-Mod[a+3b+7c+9d+e+3f+7g+9h+i+3j,10],10]; (*control digit*)
StringJoin[ToString/@{a,b,c,d,e,f,g,h,i,j,k}]
```
[Answer]
# Mathematica, 157 chars
```
""<>ToString/@Join[#,{Mod[-#.{1,3,7,9,1,3,7,9,1,3},10]}]&@Flatten@{IntegerDigits[#,10,2]&/@RandomChoice@DateRange[{1990,1,1},{2099,12,31}],9~RandomInteger~4}
```
[Answer]
## Matlab, 156 bytes
```
a=datestr(693961+randi(73049),'yyyymmdd');a(5)=a(5)+2*(a(1)>49);A=a(3:8)-48;b=randi(10,1,4);[[A b mod(10-mod(sum(('1379137913'-48).*[A b]),10),10)]+48 '']
```
Ungolfed with some explanation:
```
a=datestr(693961+randi(73049),'yyyymmdd');
-- generates date serial number in desired range and converts do string
a(5)=a(5)+2*(a(1)>49);
-- modifies the first digit of the month if year >= 2000 (first digit >1)
A=a(3:8)-48;
-- gets the "YYMMDD" part and converts from string to array of numbers
b=randi(10,1,4)-1;
-- gets remaining 4 random digits ("ZZZX")
[[A b mod(10-mod(sum(('1379137913'-48).*[A b]),10),10)]+48 '']
-- computes the last digit and converts the whole thing to string
```
] |
[Question]
[
In The Art of Computer Programming, Knuth describes an algorithm to compute short addition chains. The algorithm works by computing a tree known as the Power Tree. The tree is rooted at 1, and each level is computed from the previous. Suppose we've computed level *k*. Then, for each node (*n*) in level *k*, and each ancestor (or self) *a = 1, 2, ..., n* of *n*, add the node *n+a* to level *k+1* if it is not already in the tree; the parent of *n+a* is *n*.
Three important things to note:
* nodes should be visited in the order that they are created
* levels are to be computed one at a time (not recursively)
* traverse the ancestors from smallest to largest (or you end up a familiar, but less optimal tree)
**A picture of the tree**
Perhaps drawing this tree would be fun to golf? Hmm. At the least, the result would probably be a better-drawn tree. FWIW, `10` has 4 children.
```
1
|
2
/ \
3 4
/\ \
/ \ \
5 6 8
/ \ \\ \
/ | \\ \
/ | \\ \
7 10 9 12 16
/ / /\ \ \ \ \\
/ / / \ \ \ \ \\
14 11 13 15 20 18 24 17 32
```
**Naive Python Implementation**
Since my verbose description of the tree seems to be lacking, here's a naive Python implementation. I store the tree as a dictionary here, `parent(x) := tree[x]`. There's lots of fun optimization to be had here.
```
def chain(tree,x):
c = [x]
while x!=1:
x=tree[x]
c.append(x)
return c[::-1]
tree = {1:None}
leaves = [1]
levels = 5
for _ in range(levels):
newleaves = []
for m in leaves:
for i in chain(tree,m):
if i+m not in tree:
tree[i+m] = m
newleaves.append(i+m)
leaves = newleaves
```
**Requirements**
Your program should take one argument *n*, compute the complete tree with all integer nodes *i* with *0 <= i <= n*, and then take input from the user. For each input, print out the path from the root to that input. If an input isn't an integer between 0 and *n* (inclusive), behavior is undefined. Terminate if the user inputs zero.
**Example Session**
```
./yourprogram 1000
?1000
1 2 3 5 10 15 25 50 75 125 250 500 1000
?79
1 2 3 5 7 14 19 38 76 79
?631
1 2 3 6 12 24 48 49 97 194 388 437 631
?512
1 2 4 8 16 32 64 128 256 512
?997
1 2 3 5 7 14 28 31 62 124 248 496 501 997
?0
```
[Answer]
### Ruby, 172 148 139 137 characters
```
P={1=>[1]}
a=->k{P[k].map{|t|P[k+t]||=P[k]+[k+t]}}
P.keys.map{|v|a[v]}until(1..$*[0].to_i).all?{|u|P[u]}
STDIN.map{|l|p P[l.to_i]||break}
```
Most of the code is for input and output. Building the tree is only a few chars (lines 1-2). The tree is represented by a hash where key is the node and value its path to root. Since a tree of size `n` may not contain all numbers up to `n` we continuously add more levels until all numbers up to `n` are present in the tree.
For the example given above:
```
>1000
[1, 2, 3, 5, 10, 15, 25, 50, 75, 125, 250, 500, 1000]
>79
[1, 2, 3, 5, 7, 14, 19, 38, 76, 79]
>631
[1, 2, 3, 6, 12, 24, 48, 49, 97, 194, 388, 437, 631]
>512
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
>0
```
*Edit 1:* Now the hash contains the path for each node as value already and therefore there is no need to build the path each time.
*Edit 2:* Changed the break condition for the final loop.
*Edit 3:* Changed the condition for the build-loop.
[Answer]
## Haskell, 174 185 195 characters
```
(%)=lookup
t(n,w)=map(\m->(n+m,n+m:w))w
_#0=return()
k#n=maybe(foldr(\e@(i,_)r->maybe(e:r)(\_->r)$i%r)k(k>>=t)#n)((>>main).print.reverse)$n%k
main=getLine>>=([(1,[1])]#).read
```
This version actually totally ignores the argument, and calculates the tree incrementally on demand.
```
1000
[1,2,3,5,10,15,25,50,75,125,250,500,1000]
79
[1,2,3,5,7,14,19,38,76,79]
631
[1,2,3,6,12,24,48,49,97,194,388,437,631]
512
[1,2,4,8,16,32,64,128,256,512]
997
[1,2,3,5,7,14,28,31,62,124,248,496,501,997]
0
```
Oh look! There wasn't any requirement to output a prompt. So now the code doesn't.
---
* Edit (195 → 185): combined `main` and `i`
* Edit (185 → 174): removed prompt
---
## Ungolf'd
Here is an expanded version of the core computation:
```
type KPTree = [(Int, [Int])]
-- an association from numbers to their ancester chains
-- ancester chains are stored biggest to smallest
-- the associations are ordered as in the tree, reading right to left,
-- from the lowest level up
kptLevels :: [KPTree]
kptLevels = [(1,[1])] : map expand kptLevels
-- a list of successive KPTrees, each one level deeper than the last
where
expand tree = foldr addIfMissing tree (concatMap nextLeaves tree)
addIfMissing e@(n,_) tree = maybe (e:tree) (const tree) $ lookup n tree
nextLeaves (n,w) = map (\m -> (n+m, n+m:w)) w
kptPath :: Int -> [Int]
kptPath n = findIn kptLevels
-- find the ancestor chain for a given number
where
findIn (k:ks) = maybe (findIn ks) id $ lookup n k
```
To illustrate the strangeness of how to apply the pre-computation requirement to a lazy language, consider this version of `main`:
```
kptComputeAllTo :: Int -> [[Int]]
kptComputeAllTo n = map kptPath [1..n]
-- compute all the paths for the first n integers
main :: IO ()
main = do
n <- (read . head) `fmap` getArgs
go $ kptComputeAllTo n
where
go preComputedResults = loop
where
loop = getLine >>= process . read
process 0 = return ()
process i = (print $ reverse $ preComputedResults !! (i - 1)) >> loop
```
Even thought it builds an array of the results for the first `n` integers, only those that are used are ever actually computed! Here's how fast it runs with 50 million as an argument:
```
> (echo 1000; echo 0) | time ./3177-PowerTree 50000000
[1,2,3,5,10,15,25,50,75,125,250,500,1000]
0.09 real 0.07 user 0.00 sys
```
] |
[Question]
[
*This is the cops thread of this cops and robbers challenge. The robbers thread is [here](https://codegolf.stackexchange.com/questions/264164/hashers-and-crashers-robbers).*
[Related, but hashes numbers instead of strings and uses a different scoring system.](https://codegolf.stackexchange.com/q/51068/117478)
## Definitions
A hash collision is when two different strings produce the same hash.
## Summary
In this challenge, the cops will make a hash function, with a collision they know of. Then, the robbers will try to crack it by finding a hash collision in the cop's hash algorithm. To crack an answer, the hash collision the robber finds does not have to be the intended solution.
If a cop submission is not cracked for 7 days, it is safe, so mark it as such and reveal the intended crack and the score.
If a cop submission is cracked, mark it as such and edit in a link to the crack.
## Rules
* Cryptographic functions are allowed only if you know a collision in them. If it is a famous and secure hash algorithm like SHA-256, you must post the hashes of each string in a different, specified hash algorithm (ideally also in a secure hash algorithm), like Keccak-512.
## Format
A cop answer has to **contain the language and the source code**.
## Scoring
The score of a safe cop answer is **the sum of the number of bytes of the two strings with the hash collision, with the *lower* score being better**.
## The winner
With robbers and cops being ranked separately, the winner is the person with the best scoring answer.
## Example
Cop:
>
> ### Python
>
>
>
> ```
> from hashlib import*
> def singlecharhash(x):
> a = blake2b(digest_size=1)
> a.update(x)
> return a.hexdigest()
>
> ```
>
>
Robber:
>
> ### 4 Points, Cracks cop's answer
>
>
> `¯` and `É`, both 2 bytes.
>
>
>
## Pinboard
I am thinking of changing the scoring system to make it the minimum of the two strings. Any thoughts?
[Answer]
# Python 3, [Cracked](https://codegolf.stackexchange.com/a/264187/73054)
```
import hmac
def my_hash(x):
assert type(x) == bytes
return hmac.digest(x, b'good luck', 'sha256')
```
Function takes bytes. There are no typing/Python tricks here, it's a pure crypto challenge.
] |
[Question]
[
Slope fields or direction fields, are a graphical representation of the solutions to a first-order differential equation of a scalar function. A slope field shows the slope of a differential equation at certain vertical and horizontal intervals on the cartesian plane, and can be used to determine the approximate tangent slope at a point on a curve, where the curve is some solution to the differential equation. For example consider the differential equation:
$$
\frac{dy}{dx} = \frac{y-4x}{x-y}
$$
The corresponding slope field will look like:
[](https://i.stack.imgur.com/MWhDy.gif)
Another example with this differential equation:
$$
\frac{dy}{dx} = \frac{x-y}{x-2y}
$$
[](https://i.stack.imgur.com/VkK7m.gif)
Your task is to generate such slope fields in the console with characters of text. You are to print the following for each coordinate pair:
* `/` If the differential equation evaluated at the point \$(x, y)\$ is positive.
* `\` If the differential equation evaluated at the point \$(x, y)\$ is negative.
* `-` If the differential equation evaluated at the point \$(x, y) = 0\$.
* `|` If the differential equation evaluated at the point \$(x, y)\$ is undefined.
The inputs are a string and a number consisting of:
* Expression string that can be evaluated (or parsed if you have to).
* A number that outlines the radius of the plot from \$(0, 0)\$.
The expression string can use any built-in mathematical function and will only either \$x\$ or \$y\$ as variables. Any combination of logarithms, (inverse and/or hyperbolic) trigonometric functions, or functions like `sqrt(), pow(), exp(), abs()` may be used in the expression. The plot radius may also be 0, which means only print one character containing the slope at the origin. A sample input may look something like:
```
plotRadius = 10
expression = "(x - y) / (x - 2 * y)"
```
Notice how both the boundaries of the plot follow: \$ -\text{plotRadius} \leq x, y \leq \text{plotRadius}\$. This results in the following slope field being displayed:
```
/ / / / / / / / / / / / / / / / / / / / —
/ / / / / / / / / / / / / / / / / / / — \
/ / / / / / / / / / / / / / / / / / — \ \
/ / / / / / / / / / / / / / / / / — \ \ \
/ / / / / / / / / / / / / / / / — \ \ \ \
/ / / / / / / / / / / / / / / — \ \ \ \ |
/ / / / / / / / / / / / / / — \ \ \ | / /
/ / / / / / / / / / / / / — \ \ | / / / /
/ / / / / / / / / / / / — \ | / / / / / /
/ / / / / / / / / / / — | / / / / / / / /
/ / / / / / / / / / | / / / / / / / / / /
/ / / / / / / / | — / / / / / / / / / / /
/ / / / / / | \ — / / / / / / / / / / / /
/ / / / | \ \ — / / / / / / / / / / / / /
/ / | \ \ \ — / / / / / / / / / / / / / /
| \ \ \ \ — / / / / / / / / / / / / / / /
\ \ \ \ — / / / / / / / / / / / / / / / /
\ \ \ — / / / / / / / / / / / / / / / / /
\ \ — / / / / / / / / / / / / / / / / / /
\ — / / / / / / / / / / / / / / / / / / /
— / / / / / / / / / / / / / / / / / / / /
```
Please separate each point with a space.
[Answer]
# [Julia 1.0](http://julialang.org/), 90 bytes
```
N\~=-(r=-N:N).|>y->println(join(r.|>x->abs(x~y)<Inf ? "\\-/"[Int(sign(x~y))+2] : "|"," "))
```
[Try it online!](https://tio.run/##JYm9DoIwEIB3n@Jy01U5EUZC68zSF7AOGIIpIdUUTNqE8Oq10e37mT6z7auQkja7ZPKSdaPFeVOR1dtbt86Oppd15HMLrPrHQmGPou3cCFdAY7jEW@dWWuzT/ZY41XdoADcsEFCINIwUiihAAgVgyFT@qYZjtkN1McOYvg "Julia 1.0 – Try It Online")
takes `plotRadius\df`, where `df` is a black-box function and prints the plot
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), ~~71~~ 62 bytes
```
pes1Jngjr@sajJ<>cpm{%1!{{@0.<}'\{@0.>}'/{@0==}'-{1}'|}cn}jcosp
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/ILXY0CsvPavIoTgxy8vGLrkgt1rVULG62sFAz6ZWPQZE29Wq6wNpW9tadd1qw1r1mtrkvNqs5Pzigv//DQ24quMKuEpSlCqUissUgHQlkOYC8tLLFIBsIKmni8I10tMCiujp1wIA "Burlesque – Try It Online")
First stab, still some optimisation to be done
```
pes1 # Parse function and save
J # Dup
ng # Negate
jr@ # Range -n..n
sa # Get length for chunking later
jJ<>cp # Transform to -n..n x -n..n
m{ # Map
%1! # Call function
{
{@0.<}'\ # If <0 \
{@0.>}'/ # If >0 /
{@0==}'- # If ==0 -
{1}'| # else |
}cn # Condition
}
jco # Chunks of len
sp # Pretty output
```
[Answer]
# Python 2, 122 bytes
```
def g(r,e):
q=range(-r,r+1)
for x in q:
l=""
for y in q:
try:l+="-/\\"[cmp(e(-x,y),0)]+" "
except:l+="| "
print l
```
[Try it online!](https://tio.run/##NYxBDoIwFETXcopJV62UCCwxnEQNQWm1CbTlWw1NvDtWEnczk/fGx/Bwtl41uQldp1/hRarrYCbvKGAwb/M0zq6D0tCcpBJNhrml3t4VL0hSXokM2hEWGIu5yXZjy1i2@03xPyFQbMa8ZcXhfGan2@R5shcZhSzFJWdgxwSp5aZ82LgP0oUnYwPGVfOqlGM/XYceyWn4ggJR4IAt1dinJtYv "Python 2 – Try It Online")
Takes an integer and a function as input, prints the result.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/241404/edit).
Closed 2 years ago.
[Improve this question](/posts/241404/edit)
# Fourward (Introduction)
I have an unhealthy obsession with the number 4. I love it so much, in fact, that seeing any other digit is frustrating to me. I therefour wish to create a 'Fourier Transformation': a way to represent any integer value with an expression that uses only the digit 4.
# Fourmat (Challenge)
I wish to automate this process so I can use it everywhere. Your code must take any integer and output an expression that evaluates to that integer but which uses no digit other than '4'.
Four example, you might render the natural numbers as follows:
```
(4-4)
(4/4)
((4/4) + (4/4))
((4) - (4/4))
(4)
((4) + (4/4))
etc.
```
Any mathematical operation is allowed: you may use addition, multiplication, exponents, roots, logs, or even logical expressions such as AND or bitmasking--so long as no digit other than 4 appears in the output!
The parentheses aren't necessary; you may fourmat the output in whatever way you like, so long as it's readable. Also, because I'm not all that intelligent, the end result must be in base ten (or as I like to call it, base `4+4+(4/4)+(4/4)`.
# Perfourmance (Criteria)
It is vitally important that the expressions each be as efficient as possible; I love the number 4, but I don't want to get sick of it. Submissions will thus be judged on the following, in order:
* Efficiency of expressions (i.e. that the expression produced is as short as possible while still following the rules)
* Efficiency of code (i.e. that your code is as short as possible)
* Beauty of code (this is a tiebreaker; I won't be seeing the code itself so I don't mind non-four digits in there, but between two otherwise equal answers, I will prefer the code that uses the fewest non-four digits)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 26 bytes
```
f=n=>n?f(--n)+'+4/4':'4-4'
```
[Try it online!](https://tio.run/##BcFRCoAgDADQ46jIKsJ@stVZxDQWsoVG17f37vCFFis9L7CcqfeMjDsfWQOwscq60alVOXCqZ6macPK04bx4stZE4SYlDUUunTUZ038 "JavaScript (Node.js) – Try It Online")
Quite simple and self explanatory. uses \$2n+2\$ 4's for any number \$n\$
] |
[Question]
[
# Background
I want to display *rich, vibrant images* on my theoretical fancy custom display, but due to budget constraints, it displays everything in 3-bit colour! Whilst [Regular Dithering](https://codegolf.stackexchange.com/questions/26554/dither-a-grayscale-image) would work, I don't want to sacrifice resolution, so I would like my images to be dithered through time!
# Specs
Provided an Input Image, I would like you to show me several 3-bit color versions of that image, such that the average colour of all images is the original image.
## I/O
You must take an image as input.
You may either animate the image (Return a GIF, Video, or on the screen), or take time as an additional input. If time is taken as input, the output must be Deterministic for a given image and time, and must return as a static image.
## Example

*From [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Johannes_Vermeer_(1632-1675)_-_The_Girl_With_The_Pearl_Earring_(1665).jpg)*
>
>  
>
>
>
*A lot of quality was lost between recording the output and converting it to a gif, thus a still has also been provided*
## Victory
The victory condition is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), as per previously stated budget constraints.
# Final Notes
Please consider the risk of photo-sensitivity when uploading an answer, and keep images to either external links, or wrapped in a spoiler. Videos of your solution running are not required, but are welcome.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes
```
Sign[#-Mod[1##,1]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v@T9pIWeuYnpqQ5BibkFDsGZ6XnRyrq@@SnRJco6hrGxag5aYGmXxJLE//8B "Wolfram Language (Mathematica) – Try It Online")
Input `[image,time]`, where `image` is a 3-channel RGB `Image`, and outputs a frame.
A fairly straightforward approach: output whenever the floor of the accumulated value increases. Mathematica's `Image`s support arithmetic and can contain values of any size, but are clamped between 0 and 1 when displayed.
For the image in OP, a GIF output of t=1,2,...,255 can be viewed [here](https://drive.google.com/file/d/1yg92Ehh1AhFyzlYAS8ZcoYqWpQ1IF1WA/view) (caution: blocks of flashing colors).
Averaging the frames:
[](https://i.stack.imgur.com/t7NSN.png)
[Answer]
# [Perl 5](https://www.perl.org/) -ap, 110 bytes
```
srand($F[3]=1);
$_=(map{splice@b,rand@b,1}@b=((1)x($o=int$_*8/256),(0)x(8-$o)))[$ENV{F}]for@F[4..$#F];
$_="@F\n"
```
[Can't try it online!](https://tio.run/##K0gtyjH9/7@4KDEvRUPFLdo41tZQ01ol3lYjN7GgurggJzM51SFJByQNpAxrHZJsNTQMNSs0VPJtM/NKVOK1LPSNTM00dTQMgIIWuir5mpqa0SqufmHVbrWxaflFDm7RJnp6KspusSBTlRzcYvKU/v//l19QkpmfV/xfN7EAAA "Perl 5 – Try It Online")
...but instead you can create an 8 frames animated GIF image with:
```
echo 'srand(7);$F[3]=1;$_=(map{splice@b,rand@b,1}@b=((1)x($o=int$_*8/256),(0)x(8-$o)))[$ENV{F}]for@F[4..$#F];$_="@F\n"' > program.pl
wget -N -O img.jpg "https://upload.wikimedia.org/wikipedia/commons/thumb/6/66/Johannes_Vermeer_%281632-1675%29_-_The_Girl_With_The_Pearl_Earring_%281665%29.jpg/335px-Johannes_Vermeer_%281632-1675%29_-_The_Girl_With_The_Pearl_Earring_%281665%29.jpg"
convert -compress none img.jpg img.ppm
perl -i -pe's/\n/ /' img.ppm
for f in {0..7};do cat img.ppm|F=$f perl -ap program.pl > img-frame$f.ppm;done #~10sec
convert -delay 1 -loop 0 img-frame*.ppm img-animated.gif
xdg-open img-animated.gif
```
The `program.pl` reads the one line input (the example image of this challenge converted to the Plain PPM format) from STDIN and the frame number 0-7 (the time) from the environment variable F. The above commands works with `bash` shell, `wget`, the `convert` program from ImageMagick and `xdg-open` or any image viewer capable of viewing animated GIF images. To change to 16 frames, replace 7 with 15 and the two 8's with 16. Animated GIF image: <https://drive.google.com/file/d/1s5WDGjwKLowdmildkYxUWGOWpRjS-Av6/view?usp=sharing>
] |
[Question]
[
Create a program that interprets the programming language Bucket.
Bucket works on two buckets: the first can hold A and the second can hold B units of liquid. The things you can do with these buckets are:
f: fill bucket A
F: fill bucket B
e: empty bucket A
E: empty bucket B
p: pour units of liquid from A to B until one is empty or the other is full, whichever happens first
P: same as the command p, but from B to A
o: output the value of bucket A
O: output the value of bucket B
These examples assume A is less than or equal to B in the tuple (A,B), which is the main tuple determining which variant of the language is to be interpreted. A is the lesser-or-equal value of a bucket here and B is the larger-or-equal value: substitute as you need.
Your program should ask for 3 inputs:
1. the element A in the tuple (A,B):
2. the element B in (A,B):
3. the program to interpret.
The tuple (A,B) determines which variant of the language Bucket is interpreted.
As a general rule, make sure the first two inputs can range from 0 to 2,147,483,647.
Any characters in the third input other than fFeEpPoO do not need to be handled. Assume no characters other than these will be in the source.
Any commands equal to pouring more liquid in any bucket than it can hold do not need to be handled.
Assume the program will never try to pour liquid from an empty bucket.
This is code golf, so the shortest solution wins.
Any programs made before I changed the specifications to be correct are now non-competing.
[Answer]
# [Perl 5](https://www.perl.org/), 194 bytes
```
$x='if(e>$B-E){e-=$B-E;E=$B}l{E+=e;e=0}';$y=y/eEAB/EeBA/r;($A,$B,$_)=<>;s/[^fepo]//gi;s/e/$&=0;/gi;s/o/say$&|0;/gi;s/F/O=$B;/g;s/f/o=$A;/g;s/p/$x/g;s/P/$y/g;s'e|o'$a'g;s'E|O'$b'g;s/l/else/g;eval
```
[Try it online!](https://tio.run/##zZE9C8IwEIZ3f8dhFFuvHRwkRmghbhJ3UalwlUIwwYpYrH/dmPoxqotDuSHPA0l4787SQY@cg7NgRd6jKaSh7F8oFA1w6Y@rvsiBIE4iujIOlaiQZJKipDTBA@9BEkAawKYvJlNe4nKdkzUrxF3hjRC6IuJPMVhmFXTrt89Q@f@9eM7RCEiebBHOD1ggVA0wqg2DjDUoa8Vg2yBqJF2Sv0CnTDsXd@J43Mltu0r97al6uVpQG@pjDNW2FfyY8of86muzbVnCzdhjYfalC@ejYRRHdw "Perl 5 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~212~~ ~~170~~ ~~166~~ ~~164~~ ~~159~~ ~~157~~ ~~155~~ 153 bytes
```
A_~J~B_=Fold[Switch[{a,b}=#;#2,3,Echo@a;#,4,#+Min[a,B-b]z,5|6,{#2A-5A,b},7,Echo@b;#,8,#-Min[b,A-a]z,_,{a,#2B-9B}]&,z={-1,1};0z,ToCharacterCode@#~Mod~12]&
```
[Try it online!](https://tio.run/##VcxLC4JAFAXgfT/DATfdgXz1QAQf5EKQgtoNg9xRQyGbECHQ9K/bRLRwd885H7fBriob7Ooc5znIpmQKMy@W94JdXnWXV2xAEKNHXGKCBce8kj66BGwg67R@MISQCt6D897CQMyAOoHisPtJoeQeCP1KAQFFJTNQH4kZ0kM4ch16b6AGGKO76eEqowpbzLuyjWRR@mRKZTEZJtfnhFlgc6adNL763/F5mcrzsrk9F7sK8wc "Wolfram Language (Mathematica) – Try It Online")
Calling `J[A,B]` returns an interpreter for the (A,B)-bucket system, which can be applied to a program with `J[A,B]["prog"]`. The "o" and "O" commands print using [`Echo`](https://reference.wolfram.com/language/ref/Echo.html), and the return value of the program is the final bucket state.
The program is a big `Switch` statement folded over the character codes (modulo 12) of the program, step-wise updating the contents of the buckets. Dispatching the `Switch` takes a shortcut by defaulting to E|F (9|10), as the spec says that there are no characters to be expected other than "fFeEpPoO".
Debugging is done by replacing `Fold` with `FoldList`, so that the return value of the program becomes the sequence of bucket states traversed during program execution. Un-golfed version:
```
J[A_,B_][prog_] :=
FoldList[ (* debug version *)
Switch[{a,b}=#; (* initialize a and b to the current bucket contents *)
#2, (* switch as a function of the next character in the program *)
"f", {A,b}, (* f: fill first bucket, leave second bucket unchanged *)
"F", {a,B}, (* F: fill second bucket, leave first bucket unchanged *)
"e", {0,b}, (* e: empty first bucket, leave second bucket unchanged *)
"E", {a,0}, (* E: empty second bucket, leave first bucket unchanged *)
"p", {a,b}+{-1,1}*Min[a,B-b], (* p: pour first bucket into second bucket *)
"P", {a,b}+{1,-1}*Min[b,A-a], (* P: pour second bucket into first bucket *)
"o", Echo@a;{a,b}, (* o: print contents of first bucket *)
"O", Echo@b;{a,b}]&, (* O: print contents of second bucket *)
{0,0}, (* start with both buckets empty *)
Characters[prog]] (* fold over the characters in the program string *)
```
[Try it online!](https://tio.run/##ldTPb5swFAfw0y79K56oNK2pkZp2p1SVmk7hMG0KUo8IRTaYYI3YyDbdjyh/e/owMAJJq8YHoiDyed@Y97yhNucbakVC9/vv0XxFnlZxVGq1XsUwe7gACFSR/hDGRjBaXyaQclat4YVrI5SEc9bk6qL@eP4tbJJHW0rY7uHy/oAWUlhBC/GPAwUqU2DwySrAtJBUWnNpgVXJL24hUdLiVzO223V5S8axjasK1CCdVTKxdXqVOVzyP0jmVNPEco0x3N16QzTd9LSXeQS2c4xNBnQ2g0wUBV606RISKDh94WA4Rk272Fg3p3LN03FqL6hpSp5GdNDSA6azD@u9Q/OavjlKzWfAN6X9e37snl40qW9G9KKjz47d02VDs9311p@S6W7yU8gIN8hnMXFFyhmUqtJDTkjsl2H4ow7xwp6eEr@lGZn7tKXDlh5Czh5UO6YV0oskV4/03lUgzYYoBDX@vu9b7LyT1Bszg/Syo1lDx59JTS9P0ad34DSNrTF4fwcjY6m2gHOTA1P1xXGmfbcfmPRv3UgZd7rEcT8yeMCAwkOkGe7/z41nz1j8b@shjUfWHfkaR14Q8jAI1dKL93vfbcIr "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 50 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╖z≈]Y`Zîú¬♣↑e█■X▲håR⌐├~@»3é±óè♂╓_§8F|╢╖r╥ë$%6Æ▲¡↓!
```
[Run and debug it](https://staxlang.xyz/#p=b77af75d59605a8ca3aa051865dbfe581e688652a9c37e40af3382f1a28a0bd65f1538467cb6b772d289242536921ead1921&i=4+7+%22fpfpEpfpO%22&a=1)
Unpacked and ungolfed it looks like this. You can nearly see some kind of structure in it even if you don't know stax. It loops over the program, and dispatches to a block based on the index of the instruction in the literal `"fFeEpPo"`. Capital O gives an index of -1.
```
sYdZZF
"fFeEpPo"I
{xs}
{dy}
{Z}
{d0}
{+cyG}
{+cxGs}
{nP}
{Q}
8l@!
}tc~-,
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 184 bytes
```
\d+
$*1,
[^FfEePpOo](?=.*$)
{`(1+),1*¶((.+¶)f|F)
$1,$1¶$3
,1*¶((.+¶)e|E)
,¶$2
(1?)(¶\1(1*)1*,\3)¶p
$2$1¶
^((1*)(1?)1*,\2)(¶1+,1*)\3¶P
$1$3$4¶
}s`,(1*)(¶(.+¶)o|¶O)(.*)
,$1$3¶$4¶$.1
3A`
```
[Try it online!](https://tio.run/##TY0xDsIwEAT7e8cVd45l6WwoEaJI2rjHREEikWhIBHSEb/kB/liwU9Huzu48h/f9cV3XcKsAlWg4d81YD35upwsdD0YhA3x6koq1qBSJTJUij0vDgKJRUkQH/9Ww1Aw6xxZIjkwpBiFRLEoHxynOgLbMoKMSF6ZUtpBS5ScOLkWf39HhLnPfV683Mis2w7Sk2DIZlT2Fyq7MoRFwp35dLeyh8d4Pvv0B "Retina 0.8.2 – Try It Online") Implements the variant of Bucket specified in the question. For the original version, the `?`s can be changed to `*`s for the same byte count:
```
\d+
$*1,
[^FfEePpOo](?=.*$)
{`(1+),1*¶((.+¶)f|F)
$1,$1¶$3
,1*¶((.+¶)e|E)
,¶$2
(1*)(¶\1(1*)1*,\3)¶p
$2$1¶
^((1*)(1*)1*,\2)(¶1+,1*)\3¶P
$1$3$4¶
}s`,(1*)(¶(.+¶)o|¶O)(.*)
,$1$3¶$4¶$.1
3A`
```
[Try it online!](https://tio.run/##TY0xDsIwDEV3n8NDnEaRnMCIEEO7NjuhKhKtxEIrYKNcKwfIxUICHdgs//ffvw/P6@2ckr9UgJIVHLtmrAc3t9NJ7HdaIgG8esEVKZYxCKGrGGhcGgJkhRwDWviPhqUmUPltQLAkEYPncrBU3lIMM6ApNejEN18jU0iusom8jcFlO1rcZO796NVq@i1MSwwtCS3zTqHyVuZQM9hDn5KBLTRucO0H "Retina 0.8.2 – Try It Online") Explanation:
```
\d+
$*1,
```
Convert the sizes to unary and add separators to provide space for the current values.
```
[^FfEePpOo](?=.*$)
```
Delete unrecognised commands.
```
{`
}
```
Loop over the commands.
```
(1+),1*¶(F|(.+¶)f)
$1,$1¶$3
```
For `f` or `F`, fill the appropriate bucket by copying its size.
```
,1*¶((.+¶)e|E)
,¶$2
```
For `e` or `E`, empty the appropriate bucket.
```
(1*)(¶\1(1*)1*,\3)¶p
$2$1¶
```
For `p`, pour from the first bucket to the second, taking care not to overflow it. `$1` = amount to pour, `$3` = amount already in second bucket.
```
^((1*)(1*)1*,\2)(¶1+,1*)\3¶P
$1$3$4¶
```
For `P`, pour from the second bucket to the first, taking care not to overflow it. `$2` = amount already in first bucket, `$3` = amount to pour.
```
}s`,(1*)(¶(.+¶)o|¶O)(.*)
,$1$3¶$4¶$.1
```
For `o` or `O`, convert the appropriate bucket to decimal and append it to the end.
```
3A`
```
Delete the input at the end of the loop.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 66 bytes
```
NθNηF⁺eES≡ιf≔θζF≔ηεe≔⁰ζE≔⁰εpF∧ζ‹εη«≦⊖ζ≦⊕ε»PF∧η‹ζθ«≦⊖ε≦⊕ζ»o⟦Iζ⟧O⟦Iε
```
[Try it online!](https://tio.run/##hZCxasMwEIZn6ykOTydQoRS6tFNoEwgkjaBj6aAql8jgyLYkt@CQZ1dtx6RKh3Y8Pv7/uzttlNOVKmNc2roNL@3hgxw2/JGls@nnXeUAZdl6zGmeCxj5a3CF3SPnHPxXEbQBLDgcmVaeIN/lDyybeV/sLTYCur7lDBYJMALoAigBt2lifg1@EvUAxt1mdoudgBV5jyTADEsdWZatVT0Fn0k7OpANtD13p3BpEzj0Z6dJIa8UZlL0quYfBf2l6FJFNShk/8uAb0/KB@z4@@XEzW9IIzzFeMfu2UJKSXITbz7Lbw "Charcoal – Try It Online") Link is to verbose version of code. Implements the variant of Bucket specified in the question. For the original version, the `F`s can be changed to `W`s for the same byte count:
```
NθNηF⁺eES≡ιf≔θζF≔ηεe≔⁰ζE≔⁰εpW∧ζ‹εη«≦⊖ζ≦⊕ε»PW∧η‹ζθ«≦⊖ε≦⊕ζ»o⟦Iζ⟧O⟦Iε
```
[Try it online!](https://tio.run/##hdBBa8IwFMDxc/MpHj29QAdD2GU7yaYgzBnYceyQxacJ1LRN0gkVP3vWanGZh3kMP977J1FaOlXJMsaFrdvw1u6@yGHDn1h61v15UzlAUbYec5rlBZz8PThjt8g5B783QWlAw@HAlPQE@SZ/ZNnUe7O12BTQ9VvOME9AF0AXoATu04nZX/idqAfYa1MS4NSusSvglbxHKkAP1zqwLFvKehx9IeVoRzbQ@rw9xYVNcChkxzEiriJ6jPSx5kaE/ot0aaQaIqL/z4Afz9IH7Pjn5Zmra6QTHmOcsAc2FyRW8e67/AE "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input the sizes of the buckets.
```
F⁺eES
```
Loop over the commands, but prepend `eE` so that the buckets are in a known state.
```
≡ι
```
Switch over the current command.
```
f≔θζ
```
If `f` then fill the first bucket.
```
F≔ηε
```
If `F` then fill the second bucket.
```
e≔⁰ζ
```
If `e` then empty the first bucket.
```
E≔⁰ε
```
If `E` then empty the second bucket.
```
pW∧ζ‹εη«≦⊖ζ≦⊕ε»
```
If `p` then pour a unit from the first bucket to the second until the first becomes empty or the second becomes full. (Interestingly this seems to be the golfiest way to express the concept in Charcoal.)
```
PW∧η‹ζθ«≦⊖ε≦⊕ζ»
```
If `P` then pour a unit from the second bucket to the first until the second becomes empty or the first becomes full.
```
o⟦Iζ⟧
```
If `o` then output the first bucket on its own line.
```
O⟦Iε
```
If `O` then output the second bucket on its own line. (The `⟧` is implicit, as is the skipping of unrecognised characters in the input.)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~194~~ 152 bytes
```
def f(A,B,s,a=0,b=0):
while s:c='fFeEoOpP'.find(s[0]);W='a,b,A,B=b,a,B,A;'*c;exec W+['a=A','a=0','print a','v=min(a,B-b);a-=v;b+=v'][c/2]+';'+W;s=s[1:]
```
[Try it online!](https://tio.run/##LYuxDoIwFEV3vqLbo/JQNDExNG/ARFbYGAhDC20gUWgsQf36WhOXk3tv7rGfdVzmk/eDNszEBV7RoaQMFWU8j9hrnO6aubwnMKW@LZWtYW@meYhdm3VcNAQSFQaPFMpgFwJ2vdBv3bMmaUFSARiYBdrnNK9MhrTRY5rjcE8VFzKlTaiENuja/nDqEhCQNMKRa4955018xgtCWeu6rJcKePRfjDX21/0X "Python 2 – Try It Online")
`c` is even when the command deals with the `A` bucket (`feop`) and odd when it deals with the `B` bucket (`FEOP`). So `W` creates a string which, when `exec`'d, swaps the roles of `A` and `B` either an even number of times (i.e., no effect), or an odd number of times (same as a single swap).
This allows the code to only list the commands once instead of twice - if needed, we swap `A` and `B` then execute the `A` based command, and then swap again if needed, to get both `A` and `B` functionalities.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 129 bytes
Takes input as `([b, a])(code)` where `code` is a string. Returns an array of output values.
```
B=>c=>Buffer(c).map(h=j=>(i=j>>5&1,k=j&3)?k>2?o.push(b[i]):b[i]=~-k*B[i]:b[i]&&b[k=i^1]<B[k]&&h(j,b[i]--,b[k]++),b=[0,0],o=[])&&o
```
[Try it online!](https://tio.run/##zVOxboMwEN35CiZjN8YKrSK1Tc@RiJQVpI6WKwHBAZxgZJKO/XVq0i4ZSJcO6CTfPd876Xzn12SfWV/YujuHrdmXg4IhBl4Ajy9KlRYXhJ2yDlfQAMc1NJyvUEQ1NOiJbDR/3BjWXfoK56KW5HU84SvUD7ELrgihXGioPyL5FgvtYIUbOibC0DktFwtCcxBLupTUgJAEITMUpu3NsWRHc8AKi2fqryTBwS4t011qkoAQb4KiOtX9EBxjX/rgX6/mZMm/lSa/OHFzmYFNtpHMbQV/THmi/@TuY@eyhGDtedb9eyeKKHqhfuRkMUqBrL0b0dhbDb2fbd0emLLmtK0yu3UVmDFmCRm@AQ "JavaScript (Node.js) – Try It Online")
### Commented
```
B => c => // B = [b, a]; c = code string
Buffer(c) // turn c into a buffer
.map(h = j => // for each ASCII code j:
( i = j >> 5 & 1, // i = 1 for lower case, 0 for upper case
k = j & 3 // k = 0 for 'p', 1 for 'e', 2 for 'f', 3 for 'o'
) ? // if k is not 0:
k > 2 ? // if k = 3:
o.push(b[i]) // push b[i] in o[]
: // else:
b[i] = ~-k * B[i] // set b[i] to B[i] if k = 2, or 0 if k = 1
: // else (k = 0):
b[i] && // if b[i] is not empty
b[k = i ^ 1] < B[k] // and the other bucket b[k] is not full:
&& h( // do recursive calls
j, // to pour as much as possible,
b[i]--, // decrementing b[i]
b[k]++ // and incrementing b[k] at each iteration
), //
b = [0, 0], // start with b = [0, 0]
o = [] // and initialize o[] to an empty array
) && o // end of map(); return o[]
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/187996/edit).
Closed 4 years ago.
[Improve this question](/posts/187996/edit)
Given two numbers in tape location #0 and tape location #1 in Brainfuck, compute their product into another tape location (specify with answer). Optimize for the least amount of time-units used, where the interpretation of any command uses one time-unit. As example, here is a quick C++ program to determine the number of time-units used by a Brainfuck program:
```
#include <iostream>
#include <fstream>
#include <stack>
#include <algorithm>
#define MEMORY 10000
#define DATATYPE uint32_t
#define ALWAYSPOSITIVE true
DATATYPE tape[MEMORY];
int loc, instp;
int main(int argc, char* argv[]) {
std::string infile = "a.bf";
bool numeric = false;
bool debug = false;
std::string flag;
for(int i=1; i<argc; i++) {
std::string arg = argv[i];
if(arg[0] == '-') flag = arg;
else {
if(flag == "-i" || flag == "--in") infile = arg;
}
if(flag == "-n" || flag == "--numeric") numeric = true;
if(flag == "-d" || flag == "--debug") debug = true;
}
if(infile == "") {
std::cerr << "Fatal: no input file specified. Usage: ./pp2bf -i <file> [-n] [-d]" << std::endl;
return 1;
}
std::ifstream progf(infile);
std::string prog; std::string line;
std::stack<int> loop;
while(progf >> line) prog += line;
instp = 0; uint64_t instc = 0, ptmove = 0, mchange = 0;
int maxaccessedmem = 0;
while(instp != prog.size()) {
char inst = prog[instp];
if(debug) {
std::cout << inst << " #" << instp << " @" << loc;
for(int i=0; i<=maxaccessedmem; i++)
std::cout << " " << tape[i];
std::cout << "\n";
}
if(inst == '[') {
if(!tape[loc]) { // automatically advance to matching ]
int n = 1;
for(int i=instp+1;;i++) {
if(prog[i] == '[') n++;
if(prog[i] == ']') n--;
if(n == 0) {
instp = i+1;
break;
}
}
continue;
}
loop.push(instp);
} else if(inst == ']') {
if(tape[loc]) {
instp = loop.top() + 1;
continue;
} else {
loop.pop();
}
} else if(inst == '>') {
loc++;
maxaccessedmem = std::max(maxaccessedmem, loc);
ptmove++;
if(loc == MEMORY) {
std::cerr << "Fatal: Pointer out of bounds (try increasing memory) @ instruction " << instp << std::endl;
return 1;
}
} else if(inst == '<') {
loc--;
ptmove++;
if(loc == -1) {
std::cerr << "Fatal: Pointer out of bounds @ instruction " << instp << std::endl;
return 1;
}
} else if(inst == '+') {
mchange++;
tape[loc]++;
} else if(inst == '-') {
mchange++;
if(tape[loc] == 0) {
if(ALWAYSPOSITIVE) {
std::cerr << "Fatal: Negative tape value at " << loc << " @ instruction " << instp << std::endl;
return 1;
} else {
std::cerr << "Warning: Tape value at " << loc << " @ instruction " << instp << std::endl;
}
}
tape[loc]--;
} else if(inst == '.') {
mchange++;
if(numeric) {
std::cout << (DATATYPE)(tape[loc]) << std::endl;
} else {
std::cout << (char)(tape[loc]);
}
} else if(inst == ',') {
mchange++;
if(numeric) {
int inp; std::cin >> inp;
tape[loc] = inp;
} else {
char inp; std::cin >> inp;
tape[loc] = inp;
}
}
instp++;
instc++;
}
std::cout << "\nTerminated after " << instc << " time-units." << \
"\nMoved pointer " << ptmove << " times." << \
"\nChanged a memory location " << mchange << " times." << std::endl;
}
```
Note: In this implementation the tape is allotted 10K locations and each tape is an unsigned 32-bit integer - not the 8 bits used in a standard Brainfuck implementation.
For starters, here's mine:
```
,>,[<[>>+>+<<<-]>>>[<<<+>>>-]<<-]>.<<
```
When you compile the C++ program as `rbf`, save the Brainfuck program as `mult.bf`, run `./rbf -i mult.bf -n`, and type `1000` followed by pressing Enter twice, the following output appears:
```
1000000
Terminated after 17011009 time-units.
Moved pointer 12006004 times.
Changed a memory location 5001003 times.
```
Your goal is to minimize the first value (i.e. `17011009`). In case of ties minimize the second (`12006004`) and then the third (`5001003`).
The standard test case is
```
1000
1000
```
However, your code shouldn't be optimized for this test case only, but expend minimal time-units for any two numbers.
EDIT: For well-formedness, and not hardcoding an answer, take the sum of the expended time units in all test cases
```
x
x
```
where x = 900...1000 inclusive to get the final time units expended.
[Answer]
# 7,009,011 timesteps for \$1000\*1000\$
```
>>,>,[<[-<+<+>>]>-[<<[-<+>>+<]]>[>->]<]<<<.
```
[Try It Online!](https://tio.run/##vVdbb9s2FH7Xrzh1H2JFli/dsAdLFhpsGVBgWYM1WxG4QkFLlE1UpgSJypa2/u3ZISVZtC5puhbzgy0dnvPx3L5DOkhTO4gJ3z48PGc8iIuQgsuSXGSU7D2jkUVdUS5I8EEXkHibZEzspFZII8YpXF1evf7jFhZz/ByFv1zcXNzcXl9Cwbj44cV7cVy5@O3txe2b69dvXt28@usSRFZQwziqC5LSdYnoOwbaQpwEE2A8F6ljKMGeMD6WDyTb4lKwI9m5fL5b@yZ8MgA/uQiXS4yG8S2kWbKFVamwQMz2OuMRiylqjMh0E41KhU2SxMCLPc1YgEvSSW0hpJtCYkYkzlE@O@@ARjHZlgZRkiln2WrhAHOlz/hrWbWrbUtUqL1llbfyw6IxytZzH1YrOLPPTLVFqdloUfRHw60MS00M0GYj@PwZmneb8ZE5kK0G9WAYvWi8jVYlDCFbqYN@gLANoBKL5nWCm7wfjMq6Lhfqjzo5DGiWgevC6FciSLwEnmB500KAsslTGrCI0XAKf@ZkS5cwnaXpi00ENsPuRxUP1jb38Sv0RxJHgVIexk0yMiqKjMOidut8ph5mM6XLKg6pPNbOmo6uoiXaOUl9jOw4aU@knout4yEFkrTG@HuHiGMFD56njMyyatZKg1CEwQzOHcXAn358L5RMlmQ@gVTskztaPu@RQXyrXmpbSbJ/SBDQPKfhnu6btXL7Ev3ZSm08zdlHOjb1YkhOqu2gVFkrg9N2VjU2W91aVjHBimH2FYCsJjwf1e9pKXipBDganBPzhmxzSbbVaRQl704MOnuOQCGrMaTzr6v4jo90imiRlYEjTddnZpeNzxQ2ui6nFRYUSCGSPREsIHF8DyS8IzygIBKsgQh2sjP8js8ySI7JXTidpSYHKl/WwnFa46blUFkg/@gxtyznKbq@1LXtQV0uteZDG@tNyqyFM6i0QT596F8@GF@WBAkXjNdjpF9P8muaFvmubGxTq2s5UvWi@n1F1WtqDIWpthFJOjbB6qvcgKt9U73xWsINxdbjvdfxHr1uF7xDftX5KB2frkykcWv3crK0EdEFVJUelGd7X5p6J/h1gr1MM5CsSyI8fgse5jAW2T2mNcDWyCVB0Jckuzfhpcp1VgSCJRxOh0bPLO@f6U/Ko9uXxzYZvpQLe/GNefj/4rU68VbHRju6IxP0hR5A@6mAOrsGJwoqnd4rh8ZOb3J/p1ucv3geyo3gjsQFBSKgPmOqI@e/5Xo434@Su@vrW5Jx7PUl3Hx/Jw@PDMdj8vXu7ino9CsKWl0Ph7u/OmTH9f8CU5@ww7EMpvMUVV5PdMSv4MHk@0SpDmieVhfAgHF5l5OCjqbW@12FwXirC9i3b9B3w1HXCi1cda@sBQej76p0Q7M940TQEEgk59ixNavGFWxP7YIzkU/V0rsuIxDmCsdpCGk1C5VidZM9gjxq/7MqFfpQnRiSOKShSn0TboNp3XZ4eJB/dA359eB5E2@ydte2a7mW5/mevXbVm@dZru97a8/2fNd3XXf6Lw)
This increases the counter on both the initial transfer and the second transfer back to the original position. This makes it almost the same efficiency for both orderings of the input, for example, \$100\*1000\$ is \$709011\$ steps, while \$1000\*100\$ is \$700911\$ steps.
I'm not really sure I want to attempt calculating sum of the given test cases.
] |
[Question]
[
A store is having a big sale.
If your price reaches $199 or more, you can reduce it by $100.
**You can buy each product only once.**
Here's an example list of products: (in order to simplify, the names of the products are represented by letters)
```
+------+-------+
| name | price |
+------+-------+
| A | 26.9 |
| B | 24.9 |
| C | 49.9 |
| D | 28.9 |
| E | 14.9 |
| F | 16.9 |
| G | 19.9 |
| H | 19 |
| I | 14.9 |
| J | 14.9 |
| K | 26.9 |
+------+-------+
```
### Input
* A list of product price, such as the above example.
* `N` the item list size `10 <= N <= 100`
* `X` a price
### Output
The best shopping strategy to save money. Find out the least expensive purchase list with a total price of more than `X`,
and output:
* The most appropriate total price (before deduction), for the data above, `X` = $199, and the most appropriate total price is `199.2`
### Notes
* Your code can be a function (method) or a full working program.
* Make your algorithm **as fast as possible** (less time complexity)!
* If codes have the same time complexity, the one which uses less space wins.
[Answer]
# Python 2, \$O(2^{n/2})\$
```
import sys
def subsetsum(nums, target):
# totalsum = sum(nums)
# if(totalsum == target):
# return target
# if(totalsum < target):
# return -1
sumsA = {}
sumsB = {}
for n in nums[::2]:
for k,v in sumsA.items() + [(0,[])]:
newsum = k + n
if newsum not in sumsA:
sumsA[newsum] = v + [n]
if newsum == target:
print "target found in sumsA loop: "
return target
minsum = sys.maxsize
for n in nums[1::2]:
for k,v in sumsB.items() + [(0,[])]:
newsum = k + n
if newsum not in sumsB:
sumsB[newsum] = v + [n]
if newsum == target:
print "target found in sumsB loop: "
return target
for a in sumsA:
combsum = a + newsum
if combsum == target:
print "target found in combined sumsA and sumsB loop: "
return target
if combsum > target and combsum < minsum:
minsum = combsum
print "target",target,"not found, so return the closest alternative: "
return minsum
# Test cases:
print subsetsum([26.9, 24.9, 49.9, 28.9, 14.9, 16.9, 19.9, 19, 14.9, 14.9, 26.9], 199)
print subsetsum([47.5, 1.0, 19.6, 16.7, 21.8, 5.6, 40.4, 31.8, 25.4, 21.9,
21.7, 17.6, 48.4, 17.4, 41.1, 8.9, 12.2, 25.6, 28.5, 26.3,
21.3, 35.1, 37.8, 45.1, 28.5, 47.6, 33.9, 21.5, 34.3, 14.2,
40.9, 17.9, 44.9, 44.2, 20.5, 30.8, 43.0, 24.5, 20.1, 46.7,
49.6, 42.1, 19.8, 3.8, 0.2, 38.3, 21.3, 15.3, 11.2, 36.0], 1000)
print subsetsum([47.5, 1.0, 19.6, 16.7, 21.8, 5.6, 40.4, 31.8, 25.4, 21.9,
21.7, 17.6, 48.4, 17.4, 41.1, 8.9, 12.2, 25.6, 28.5, 26.3,
21.3, 35.1, 37.8, 45.1, 28.5, 47.6, 33.9, 21.5, 34.3, 14.2,
40.9, 17.9, 44.9, 44.2, 20.5, 30.8, 43.0, 24.5, 20.1, 46.7,
49.6, 42.1, 19.8, 3.8, 0.2, 38.3, 21.3, 15.3, 11.2, 36.0], 555.5)
```
[Try it online.](https://tio.run/##7VTBjtowEL3nKyx6IaprxYkDJNqtVL6hN8QhC6YbLXFQbGhp1W@nM@MQlk2WtlLVXuqDcWbeezPzbLE7usfaxKdTWe3qxjF7tMFab5jdP1jt7L4am31lOXNF80m7MA/eMFiudsUWkuyenSGhz5Sb8SV5/4KGq9Fu35g20efcvU55J4MAPwFmP0Dlb9@7z/nlc1M3zLDSMGxqkefxMg/OQph74gfMkogona7sOGRv2WIc8cUyfAbGZfRnP@UTQMxVqtycs6Z2neI1vet24aFLUDpgMbPs4S56nW19MVy7pjSOjTwERtqbdVeebet6l7PRIPHaeYxUpWkv8WhFVXyx5Vc9YKK86eL8j7s4H3Zx/pdcnP@mi88XelPceA24VnX14P0o0A9qdxAIw3TY29PcmAgVSqPX7QMpzPoXhvz5oC/6e9/iSP8cvGsf2Os9dw@wpQS9QUbc//IRPhCaijNbd909arba1lZbKL11ujGFKw/6PFeL8mUC@Ef5iMBVAfg88HUuf3SLeCIyzmKFu8roPMNdUkRSVmZ@76K0I3OJ4Szsy6qpSCEnImJPSGkKHClmnKUYUJFQnCUUiFM8QzLjfdsgDEw5JdIMgXCGXUkhOfPNxiImlQm1n1JzybBWAkVTZCZTLK3o7EmKaiQJTScxkijEw7zxgBhMkFEzaJ1qd@wjImpE8glaAPamFIdSCo0YECOXVIwQcAyoCW4RCiYz7ML3LlPaJcUnIsIbiKLo/xX80ytI01Sk4en0Aw)
My Python skills are a bit rusty, so if you see any issues, let me know. Also, I think this can be improved in code for sure with some binary searches or something along those lines.
The program uses the [Knapsack Meet-in-the-middle approach](https://en.wikipedia.org/wiki/Knapsack_problem#Meet-in-the-middle). It first uses all even-indexed items to get a set of all possible sums for the powerset of these even-indexed items. Then it does the same for all odd-indexed items, and simultaneously determines the minimum sum using the sums of these two sets.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes, Score \$O(2^n)\$
```
ŒPS€>Ƈ199Ṃ
```
[Try it online!](https://tio.run/##y0rNyan8///opIDgR01r7I61G1paPtzZ9P//fyMzPUsdIxMgYWIJYlkACUMQ1xAkYWgJJqAiIAKkHgA "Jelly – Try It Online")
Input is a list of prices for items. Output is the minimum possible price greater than 199. Note this outputs 199.20000000000002 due to floating point rounding. Also note as it stands that it will about the least total price greater than 199 (rather than greater than or equal to).
Time used scales exponentially and is approximately proportional to 2^n where n is the number of items. On TIO, 19 items takes approx. 14.5 seconds.
] |
[Question]
[
You are given a list, L, with the length N. L contains N random positive integer values. You are only able to select from the outer edges of the list (left/right), and after each selection every value in the remaining list increase by a factor of the current selection. The goal is to maximize the total sum of the selection you make until the list is empty.
An example of L where N = 3, [1,10,2].
Starting list [1,10,2], factor = 1.
1. Chosen path left
New list [10 \* factor, 2 \* factor] => [20, 4], where factor = 2
2. Chosen path right
New list [10 \* factor] => [30], where factor = 3
Total value = 1 + 4 + 30 => 35.
Output: should be the total sum of all selections, and the list of all the directions taken to get there. 35 (left, right, left). Keep in mind that the the most important part is the total sum. There may exist more than one path that leads to the same total sum, for example 35 (left, right, right).
Test case 1
[3,1,3,1,1,1,1,1,9,9,9,9,2,1] => 527
(right left left left left left left left left right left left left left)
Test case 2
[1,1,4,1,10,3,1,2,10,10,4,10,1,1] => 587
(right left left right left left left left left left right right left right)
Rules
This is code-golf, shortest codes in bytes win.
Standard loopholes are forbidden.
[Answer]
# [k](https://en.wikipedia.org/wiki/K_(programming_language)), ~~48~~ ~~43~~ 38 bytes
-5 bytes thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn).
```
{a@*>*+a:x{(+/x*1+<y*|!#x;y)}/:+!2|-x}
```
[Try it online!](https://tio.run/##y9bNz/7/P82qOtFBy05LO9GqolpDW79Cy1DbplKrRlG5wrpSs1bfSlvRqEa3ovZ/mrqGsY6hDgjDoCUUGukYWoP4JiBRA7ASIxADiEzAtI6h5n8A "K (oK) – Try It Online") It simply tries all possibilities, and chooses the first one with the maximum value. Left/right encoded as `0`/`1`.
```
{ } /functions accepts x
+!2|-x /all possible selections
{ +/x*1+<y*|!#x } /calculate the total sum
( ;y) /also record the selection with each sum
x /: /map over all selections
a@*>*+a: /choose the one with max total sum
```
This can probably be golfed further.
[Answer]
# Haskell, ~~91 90~~ 89 bytes
Encoding the left/right decision as `0`/`1`:
```
(1%)
f%l@(h:t)|x<-f+1,(a,b)<-x%t,(c,d)<-x%init l=max(a+f*h,0:b)(c+f*last l,1:d)
_%l=(0,l)
```
[Try it online!](https://tio.run/##bYvBDoIwEETvfEUPNmllSShygdDE/1BjSrHSuCCRHjj47daWyM2dnewkO69X8@OG6I08eyYoTwzFI@trx99Lk5lUAFPQ8iZbqAOmoVujHa0jKAe1MJWafQ953XKmQ0Q1hw@IuuPJlaJkOSD3g7IjkaR7JmSb6WVHR3bEkNMBBERvqn4qQFz@ArFUxmq@ckUMYcv1Bsh/tEF1n32mp@kL "Haskell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 120 bytes
```
->l{[*(w=[0,1]).product(*[w]*~-s=l.size).map{|x|a,b=l.clone,0;[x,x.sum{|c|(b+=1)*(c>0?a.pop: a.shift)}]}].max_by &:last}
```
[Try it online!](https://tio.run/##NY5BCoMwEEX3PYWromkMat3UEnuQEEqSKhViDUZRa@zV00Ra/gx/@PMYph/5Ymts41KuBIQTJglMaYRU3z1GMYSATBR8Yo0l0s27ilDL1GpmwyB3kZDdq4LJlcxwRnpsVyNMyE84jUAoyuTGkOpUETCkn009RBvdqDsw3/kSHAvJ9LBZFdSEnGEKff91@Slzv9DDjvg498tkJzM/uMp395j9Ag "Ruby – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[L€€CH€$! D€AṬH ỊṢ ṢOOṄ! (Length Mapping)](/questions/139049/l%e2%82%ac%e2%82%acch%e2%82%ac-d%e2%82%aca%e1%b9%ach-%e1%bb%8a%e1%b9%a2-%e1%b9%a2oo%e1%b9%84-length-mapping)
(9 answers)
Closed 5 years ago.
# Challenge
Given a positive integer \$n\$, output the \$n\$-dimensional pyramidal list.
# Example
---
\$n = 1\$:
[](https://i.stack.imgur.com/lHF9C.png)
Objects arranged in a 1D pyramid (line) with side length 1 is just by itself.
So, the output is `{1}`.
---
\$n = 2\$:
[](https://i.stack.imgur.com/fnzId.png)
Objects arranged in a 2D pyramid (a triangle) with side length 2 would have one on the first row (cyan), and two on the second row (magenta).
Note, the first row is a 1D pyramid with side length 1 (`{1}`), and the second row is a 1D pyramid with side length 2 (`{1, 1}`).
So, the output is `{{1}, {1, 1}}`.
---
\$n = 3\$:
[](https://i.stack.imgur.com/CkgHP.png)
Objects arranged in a 3D pyramid with side length 3 would have 3 layers:
* The first layer (cyan) is a 2D pyramid with side length 1. It has one row, which has one object. (`{{1}}`)
* The second layer (magenta) is a 2D pyramid with side length 2; It has two rows: the first row with one object and the second row with two objects. (`{{1}, {1, 1}}`)
* The third layer (yellow) is a 2D pyramid with side length 3; it has three rows: the first row with one object, second with two, and third with three. (`{{1}, {1, 1}, {1, 1, 1}}`)
So, the output is `{{{1}}, {{1}, {1, 1}}, {{1}, {1, 1}, {1, 1, 1}}}`.
---
\$n = k\$
This is a \$k\$ dimensional pyramid with side length \$k\$. Each "layer" would be a \$k-1\$ dimensional pyramid, whose side length is its index (1-indexed).
---
## Sample Outputs
```
n output
1 {1}
2 {{1},
{1, 1}}
3 {{{1}},
{{1}, {1, 1}},
{{1}, {1, 1}, {1, 1, 1}}}
4 {{{{1}}},
{{{1}}, {{1}, {1, 1}}},
{{{1}}, {{1}, {1, 1}}, {{1}, {1, 1}, {1, 1, 1}}},
{{{1}}, {{1}, {1, 1}}, {{1}, {1, 1}, {1, 1, 1}},
{{1}, {1, 1}, {1, 1, 1}, {1, 1, 1, 1}}}}
```
## Rules
* No [standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/60043) as always.
* The innermost values of your list may be anything (does not need to be consistent for all elements), as long as they are not lists.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest submissions in *each* language win!
---
Note: Graphics generated using Mathematica
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 16 bytes
[Ha!](https://chat.stackexchange.com/transcript/message/46032216#46032216) Of course it is biased towards Mathematica!
```
Nest[Range,#,#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y@1uCQ6KDEvPVVHWUc5Vu1/QFFmXolDmoPJfwA "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[Decode the Void](/questions/119994/decode-the-void)
(7 answers)
Closed 5 years ago.
We define a *tree-like list*, or *trist* for short, as the empty list or a list containing only previously constructed trists.
The *natural numbers* can either include 0 or not, according to your preference.
The task is to create a pair of functions or complete programs `f` and `g` (they don't have to be named like this or even named at all) that implement a bijection between trists and the natural numbers. In other words:
* `f` must be able to turn any trist into a natural number
* `g` must be able to turn any natural number into a trist
* `f(g(n))` must equal `n` for any natural number `n`
* `g(f(l))` must be equivalent to `l` for any trist `l`
You can assume that all arguments and results fit in the usual numeric type for your language.
Alternatively, instead of the numeric type you could represent a natural number as a list of binary digits, either consistently little- or consistently big-endian.
The shortest solution per language wins. If your functions are recursive, you [must name them](https://codegolf.meta.stackexchange.com/questions/13225/byte-count-for-named-recursive-lambda-expressions-in-c-answers). If your language requires a statement separator or a newline between the two functions/programs, you *don't* have to count it.
This is a sample algorithm in Python3 (you are free to implement the bijection in any way you like):
```
def f(x):
r = 0
for y in x:
r = (2 * r + 1) * 2**f(y)
return r
def g(n):
r = []
while n:
m = 0
while n % 2 == 0:
n //= 2
m += 1
n //= 2
r = [g(m)] + r
return r
tests = [
[],
[[]],
[[],[]],
[[[]],[],[[[]],[]]],
[[[[[]]]]],
]
for l in tests: print(g(f(l)) == l)
for n in range(20): print(f(g(n)) == n)
```
It uses the following representation:
\$
\begin{array}{|l}
f([~])=0\\
f([a\_0,a\_1,\ldots,a\_{n-1}])=\overline{
1\underbrace{0\ldots0}\_{f(a\_0)\\\text{zeroes}}~
1\underbrace{0\ldots0}\_{f(a\_1)\\\text{zeroes}}~
\ldots~
1\underbrace{0\ldots0}\_{f(a\_{n-1})\\\text{zeroes}}}
{}\_{(2)}
\end{array}
\$
Challenge inspired by @LeakyNun's [question](https://chat.stackexchange.com/transcript/message/45917001#45917001) in chat.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~118~~ ~~114~~ ~~109~~ ~~105~~ ~~103~~ ~~97~~ 94 bytes
```
f=lambda x:x>[]and f(x[:-1])*2+1<<f(x[-1])
g=lambda n:[g(len(w))for w in bin(n).split('1')[1:]]
```
[Try it online!](https://tio.run/##TU7NDoIwDL7vKXpjVTSO4yK@yLLDCDBJZiGwBHz6SREjvfT7ab6vwzs@eypSasvgXlXtYNHLw1hHNbRyMfqiLJ6Ks7rfmTIT/ndK2ngZGpIzYtuPMENHUHUkCa/TELooM5WhUdraFJspTlCCEbCOsfl3G/tH@YEwZGUHB4OVjVvBnYE7t3ANw9hRBC9bGRChLCEIsWn7AhfCavr1v80m4ATihNGRb2RxQ0wf "Python 2 – Try It Online")
Same encoding as the example...
] |
[Question]
[
[Quarterstaff repo here with additional quarterbf interpreter](https://github.com/Destructible-Watermelon/Quarterstaff): rather bereft of documentation, however, but it does contain the two interpreters
you can go to <https://tio.run/#quarterstaff> to run quarterstaff programs online. however, the TIO BF implementation seems to have limited cells, according to the documentation
---
The title is rather descriptive, except that it doesn't describe what Quarterstaff and BF are. For this challenge, I have created two languages: Quarterstaff, and a dialect of BF that probably already existed in its exact form, but I wanted to be certain, especially with the I/O format, that it would work, called QuarterBF. In this challenge, you will compile a program written Quarterstaff to QuarterBF (but the underlying conversion should work for any generic BF dialect with byte cells and an infinite tape and such).
I have created interpreters for both of these. However, should you find the spec for one of them here conflicts with the interpreter, the spec is prioritised for the challenge (the interpreters should just be helping you out here)
First, the QuarterBF spec, since it will be easier to explain some of the Quarterstaff concepts afterwards (I cribbed some of this from the esolangs page for Brainf\*\*\*):
## BF spec
Brainfuck operates on an array of memory cells, also referred to as the tape, each initially set to zero. These memory cells can each hold an integer between 0 and 255, inclusive, and the tape extends infinitely to the right (some implementations will use a limited number of cells, hence I made my own to be sure / make an appropriate interpreter easy to find). There is a pointer, initially pointing to the first memory cell. There are no cells to the left of the first memory cell, and attempting to move further left is undefined behaviour. The commands are:
```
> : move the pointer to the right
< : move the pointer to the left
+ : increment the cell under the pointer, unless the cell is 255, in which case set cell to 0
- : decrement the cell under the pointer, unless the cell is 0, in which case set cell to 255
, : input a character code into the cell under the pointer (described more below)
. : output the character that the integer in the cell under the pointer represents
[ : Jump past the matching ] if the cell under the pointer is 0
] : Jump back to the matching [ if the cell under the pointer is nonzero
```
In QuarterBF input is interactive. The exact mechanism this works by could be gleaned by reading the source if you wanted, but it's not totally necessary. The important points: it sets a cell to the character code of an input character, sets to 0 on EOF, and to 10 for end of line newlines (which is the newline charcode)
Either way, you don't have to worry so much about how input works, because the values of `?` and `!` translate essentially perfectly to the values `,` and `.` anyway.
## Quarterstaff spec:
Quarterstaff's memory consists of registers. one of these registers is called "value", and the others are named variables. variables are case sensitive. Variables can be referenced before assignment and are initially zero (alternately, referencing a variable before assignment does nothing, because if it hasn't been assigned yet, it means it has a value of zero, therefore adding zero has no effect).
```
[a string of digits] : add the number those digits represent to the value
[a string of letters not preceded by >] : add the variable that the name represents to value
[a string of letters preceded by >] : set the variable to the current value, set value to 0
. : set value to zero
- : multiply value by -1
? : add to value the amount that the underlying bf implementation would set a cell to when , is executed
! : output the character with the charcode corresponding to value.
[ : Jump past the matching ] if value is 0
] : Jump back to the matching [ if value is nonzero
([...] is a while loop)
{ : Jump past the matching } if value is nonzero
} : Jump back to the matching { if value is 0
({...} is a while-not loop)
(, |, ): part of an if else construct...
[any characters not mentioned here] separator between commands; doesn't execute anything, but separates variables or numbers
```
### Explanation of if:
if-style 1:
```
when coming to this paren, check if value is zero or not
v
(...)
^ if value was nonzero, execute the commands within
either way, then continue execution after the )
```
if-style 2:
```
when coming to this paren, check if value is zero or not
v
(...|...)
A B
if the value is nonzero, execute the subprogram designated A. else execute the one designated B.
then, continue execution after the closing )
```
`(...)` is equivalent to `(...|)`
# The challenge
Taking a quarterstaff program as input, compile it to BF; output a program which functions the same, but in BF.
i.e.
* it halts if and only if the inputted program halts
* outputs the exact same text as it.
* if it doesn't halt, it should print the text that the original program prints in finite time, in finite time (it shouldn't put output into a buffer and then print it when it stops executing or something)
### Allowances and some restrictions:
* you may assume that input to the outputted program is always in printable ASCII and ASCII whitespace (and EOF. Basically, no need to worry about any characters >255 overflowing or whatever), and that the quarterstaff program will never try to output anything other than printable ASCII and ASCII whitespace.
* you may assume the inputted program is only ascii printables and ascii whitespace
* you may **not** assume that the variables and values only go up to 255. you need to implement **infinite** variables and accumulator
* basically, you don't get to limit anything (except possible i/o characters). your bf spec has infinite cells, you can use them!
* you may assume that the Quarterstaff program has fully matched brackets, and does not invoke undefined behaviour (e.g. trying to output non-ASCII like I mentioned earlier)
* you should **not** invoke undefined behaviour in your outputted bf program. just because I included an interpreter doesn't mean you get to exploit any bugs or lack of exceptions for undefined behaviour. When the spec in this question and implementation differ, follow the question spec. This includes when the interpreter technically could suffer from recursing too deep. doesn't mean you get to assume that a program never recurses that much.
Scoring is by the length of the program, shorter is better; [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") (this is not metagolf, the length of your bf programs does not matter, as long as they work)
### test cases:
prime tester (slightly different from my answer on the prime challenge; a space was replaced with a newline):
```
10-?[-38a a a a a a a a a a>a10-?]a>b
b[>b>d a>c c[1>c1d>d b d(.>e|>d1>e)c]e f>f1b]2-f(.|1)48!
```
cat (prints each line after you input it, then exits on EOF)
```
?[!?]
```
prints a newline
```
10!
```
also prints a newline
```
5 5!
```
truth machine:
```
49-?{49!}49!
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 769 bytes
```
import base64,zlib
exec(zlib.decompress(base64.b85decode('c$|e(O>dkq5WVv&NG^sQ59(GuRK#}Fdv=dG)b#;{MMCnD$WWA)xWB#6EcrN8>cx!5<2TRq9{u_0F--aRYn0)X-RUJ}NBuc_(1O`p??iUc`>fZ(TQ;OzP-HE8guxkB&RDAgS--{(feY*i#mIVtV^(BvOJt)Kq%1RAA_5p7)CPe{;BX-10FW+u3dSkV4A4M;_<vo>uMN==IgxdbA%B*$9OOCghdi9Bt{>XQ`$81vwk&MJzrXQ!N99ZLqfM)IHZH|WS>0Z-D}}^Zs&Q)jp$ey_Ey}Xa^1jRG`l!#%b8(b=D&|_>RpV)DPhIoVPsJ>cWm(?L@?HxicC!=)>rJC)>V)OxK7#!+M<?k1rq!JYc4?xqYUv}=lnU5kyj%8?N^e3|;i1bIFUlk;&-Df|N6Ri1VzjS!oB_%|4=~YpjG;cP&pF7U*8MOQ1Ng77OTQbU1<1#i=ep787@UHXD@-ty#%}E@Dq{~_p%Bzk7vh0jD%eza$i3<01$tQk;y4jbpI3TP1jWW08<M3Q-oHABlXH?2E)Y0O^P-diDbU*b(AEcAmvB`wp8@s<7csy4$ir*tl6z}j880LTVI*oG5cqx=hipi=w+Ptp@%k$OA{iXS2pkfF4fs-I)5cj*@zt$c;!7!3gBIt~W%&c?HhT(5j!u~6I?(m*5D^$cbd1YG6x9@(Vf4*(Dwh4HuQmTU?%+AO-+#HpM#QrG3m~&3+y')))
```
[Try it online!](https://tio.run/##Jcptk2IAAMDx9/cpzqBD54ZFNEKkol2JQnVz1XqoUJtQq8evvjc39@4/v/lnl3J7@KC4LP/6ivfZIS@/@@9F1KB/Xnex/y2qogD5V7/CKDjsszwqCuT/8MvnmH8YRsiPALpHiCmG6ZHx3HNt2F8UFtNE@if7FXz0wrMQ9lEf5G@G0flQIc@T0cpTwEY3yIecGFQA03qZ2Mfm7bQkejj@bs8@CHSK287gMVROwRIhzVUmSbETrMT1HJlYvHkd4VqX25yqVKnZqrwZ4/gNWUczLAb3ulu6C0Q5m4MSfT3CpC3LSyZj0c4ouvHKFCeJnlc/UeE4dWmZNvhl63wQT8ZQEPRNFfoyrGBQ0zQ7m20YN5XyJk6tFcSR58@0Zgyu@dQChs3m/O24NlBdm2t3bywSc1x9PBbzomahSQZFl2X38pi@L8jE7q92AAj7HOILau2@FO3MRdXRVj@4o2IgBt4ekd7aklbFQQcQUDEfdFDRRc3qlQWButGSUjI/AoNZQEvVceacH8Luw2HSSwJz0nARUXc@Jn295@xSvoar6/uwYceke03GwEFZwndaeM6ypM8Ho1rWYx2MM0yLHG5Y1pxYvkO2SDAWoozl2LajTdU2Xl5A@NFtq8fbc5nByjVlz1siUeHo@g7FVIsgodJK@Qud@JlOTUZk4nkE1zIoCz9osrKbatJLF50R5mKEh7HqO5iPyN1A3p@V1WfGtYsWGxQXGopzrNw1ro@E44i3iatjhz4THCthG2ex8FkflVkbTiFTvsXT8UuWrnv0usB1lAkSrH0toYAHWIDaKHr59OBaIGnbCcIkwOnZ0CVkjzHqAgr8kJz1G1WzjbhrGkPUzy2tnaz9xJHgumzidVDLDNDK@9T@WaPqlx8oin59Sb8B6c9f "Python 3.8 (pre-release) – Try It Online") [Test suite (also executes brainfuck)](https://tio.run/##tVhpX6pKGH/vpxjXAyr8pDTtJJqmpZ3jWmrlMUIYdFyAAEvbvnp3wCUXtDr3Xl64zDzP/9nmWYY2r3ffBd4A8Xi2dAoS4H7EawbU2hKtThzCgNd1UJkupU/zMv5SNYg/fzoAfkQoAY5DMjI4jtDhQAoCVVM6Gj8kpwTmg4aqohlAg4uVGQ1g8SKtj9qE5mreBv5Q8QQd/NP802q5gsDl@sBaMJoiaCSrIwPzFhUZ2uxgdUQ4xvuh1U2oSHjxlB/oa1zaSLZ0p1Ve0yExFxoEzVArCELkwtLp/oqZnG5oSO4sW8t@yLUYRM6kxaKbrcXGYxcNIEAgDgZQJrZiWXjSmqwmagGWBa6ga5VwTSDNqyqURSJEblAhEGABs7IMB1vl0F@Tw/wbOUgGrgCViNuIgpIEBUPH/nt@3dhUJEmHxkqsv@RiwMuijRqyYliqNFu0nXd3hiOwhWHGNNMUo88M2k69ZHVzytbadOSqU3X4PbhtaDuOAfW/2kf91/ZR3zYwscPAmXWBv/Bb/HPYrcYje4mSooHep66e@6TX8rJ7kYOv5DARCpIBYIzUASRm7DQy4FAnSBIEADHVN0iSjq8Wj6aN9QNFUTEZ7ik4TiiwaZ8uKCq0PaPTpJ7uJ0BoS4oGWOZ7udvcEaOpsL@JfOtTVNvA28WFCZr@32xSc4kfLv2JWuSnlRh38JEmzwK9JG8WV7PXzZviotMFgcGrcPrJqQoyR4GlVmWeSWSeyRn5RhNDpk9sIoa35u3Z3l2mwOay1Ba7We23l4g5/nRqQLo1NmwPjKFNdpealRHE@ibI7ZVrLEDVAHiyymqaon0BGbuBBZfaCH5dCaGrmV3@c@unkxHLmg3xY5XccUp3DVU7dVqZzT6PKOZQNJFw/ZFdJHAzIcf324AtqIX6oVhz3aAW@XXbrQzarHvWuWZsRiScmAZhxmZTMzKIsxqr53KRNoB47NySK2aSCXAw4IQuL3egmW6oyfykmJa9X0xanZM0ZchpqNM1A0OYwTeVISliWSdcXhiS3HaGloSa2iU2kHfHhYZjw6xjmNdPrGJR60jblVhWN7CKEg9tV0DjkQ5B1spEpMhfqzFr@NYAtrzEtHZpuRsqwQLcj79xktcRKNt@vhpNXJualI2Wa340lVmciO31dyWAy/zUgjlgd3zWpcXBXwZqJTNssm06GGxm2naTVjsZzozFXdBMqZZtu3NsdNANGof5IPNWLPNDyHHWJMBxQx7JHDcbCGYXYl7rWL3Xsej6phrzVTqldUZDKBtla4cQoS5oyPIM61pcxIHRhR/3czDAR2TEd@CsrkxBaV4UOX6GRrhmDRpfr4fQ4B94jV1aMiYqZPFQEQRdOFDxDm90gaFYYuZUU2y7lwIEHmpkYibV@jLl4umRnl@qaQ3yIp4mHbglOhxd/AdQAh7WQTzuyhYzLrO0KEMVBxMDTN5nnmrzOjwIB58GqO2AYygQ5i9ahCapBnWdmBLQ7VjEXBQh8UPwvECilBD795FG/cFXPLvVK5FD4mxU/eV@PRUfWPGMbLuPnguFEznjaTRS5LiRdh9kBa0YSwhjZyS@d1m9P3wecaFTiuKr13KIvKKqtfPXYnokcARTulOTSVQT7hLSDXFZOSo9lalcNtYZjftpXzWT6lxQ1DMhwWs/cg/zdaN@S6QfSucG@evey1RTKS6iRsmTMnw@Sl9RTOi0ERjtixf9ejgVLhxx8QclMSoUWTbfGYvtlDft9xyWSiedrogO08Zz4qpy54kxD499X@H8SbuqOIuHhze/76UCmc/d5F4aF4nQDZV5fb290X0Vsqd64ITLTl6v@FumVz27Gzjd3naMaLMZ3wuXqKp1MlPu5pV6WT9PCI0hkfx9nMyNkXDiZMmEdn5CJupkafwr6nYGCvFkn9HunefXQjg5vr@uPbyyA7kW6U963liyeAv3X44Q086f1gb9Ix@VkV6KB1XE1J96F04lzXlfwuzbtdo7OxLKPvU0WvPHCqUKU@xEo6XLSrvGxBk3YqEajUWPa7mrzDFlTNze1@xx5v75jVO96ad@9KEb6mW88In3oP14iPEYlf7RJNxrq/n9yzLTazRCsXhhv0IpuVR6cJVL7mXJ61DptkyJKNOu@dtEKiukhg/pu0c1dqzHo4I@CXuQ5jcGB0@vvVgs9PuynvcrZxHhfsx2kYrYx0DZUI@9fU8p9YyuLvbUvnQalnQqT0aEnv/4yfAIR86oc7@TzhtvDa9PSOa6l0Sk5xy9HeSTxNAfydx6hLbIXJ8djA@PiboU9hOZx244N6oML2tJbyBVogLunFpwV7Sz/eGbbz8w@UGS5DtOCodDnRhdRd6nY8vJYaWKCOm25HBAoauAhG/P4XgUzISabUyXPjatX5QMXB7GBV6AgYb4DqKCOXx05eXfHOQ92XTSydZ7efbSbjridRSo4xqhQcc/)
OK, so this is a version following the specifications, but the rules seem to be missing that `!` resets the value to 0. So, at a cost of two bytes, here is a fixed version:
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 771 bytes
```
import base64,zlib
exec(zlib.decompress(base64.b85decode('c$|e(O>dkq5WVv&NG^sQ59(GuRK#}Fdv=dG)b#;{MMCnD$WWA)xWB#6EcrN8>cx!5<2TRq9{u_0F--aRYn0)X-RUJ}NBuc_(1O`p??iUc`>fZ(TQ;OzP-HE8guxkB&RDAgS--{(feY*i#mIVtV^(BvOJt)Kq%1RAA_5p7)CPe{;BX-10FW+u3dSkV4A4M;_<vo>uMN==IgxdbA%B*$9OOCghdi9Bt{>XQ`$81vwk&MJzrXQ!N99ZLqfM)IHZH|WS>0Z-D}}^Zs&Q)jp$ey_Ey}Xa^1jRG`l!#%b8(b=D&|_>RpV)DPhIoVPsJ>cWm(?L@?HxicC!=)>rJC)>V)OxK7#!+M<?k1rq!JYc4?xqYUv}=lnU5kyj%8?N^e3|;i1bIFUlk;&-Df|N6Ri1VzjS!oB_%|4=~YpjG;cP&pF7U*8MOQ1Ng77OTQbU1<1#i=ep787@UHXD@-ty#%}E@Dq{~_p%Bzk7vh0jD%eza$i3<01$tQk;y4jbpI3TP1jWW08<M3Q-oHABlXH?2E)Y0O^P-diDbU*b(AEcAmvB`wp8@s<7csy4$ir*tl6z}jB~D&Q%)&^NK_gK9FcI01aBmUd-{bXf07~*WxDjY15*zlV$fk|6qT;Jtx5SrHtR5}SrOWaM(rxw>k|Lcj%XOgZ-60|{gy<NThbXEkG{fkd=~OKHPhV^PbKJppa=-s_iH(S5nf(R5Kqbo')))
```
[Try it online!](https://tio.run/##JcrZrpoIAIDh@3mKGsGCHRqoIhgFBFFRD6uy6GREWVTAhU0Pivjqp2l69@fLHz/y4/XSIuP06ys4x9c0/@bsMr/T/vd5Cpx//MJ3oT/10/Pd6zlO/SyD/g4/HRL/g54PfXeBlw/JtBcluGncG9Jkk6l4F5rctHm9Gnt3ypvATr1XiuLwwgOmycKFydU7IzeVSNotanj/11JLuuXNRscIstNWFxS2EE2fVRJ3c20Ik7cxwwS6u6X3a2ip9uSngggj8nArIq6h8exhgSAltPdXzaB@nhq5sYG4uzzL4XkCYhrL2nhMwEPFL3uchWDo2Pxxa3mLyGizbbFn9@9X@iZKFDU9FJ7DglwT6Mry8HD0gi6Xl7SlbgESu39GDXH2TC21JnW7649kL8JTYS28zAWNrhG@qjbrrKHCYQz4D3v0qKzdBgu1yfZUq4MOCTkU33jZtBYbMK8cp1dDyWa0a54h5mPACEXgDmsUTKezIUwbsFzMiXrth9hnIixNarOV22aKZKXfK@p00fHoEYIkI2381qsXYM50rJ@iXgPh9y@powWY8QwXtStng6829V7F4aTnKo14TOhNUpRVTDoQhLxUHR3rY/WA8mOCJAa6YPEDJH/UwWo04JPybccg94yI@xENedB/7oCg1UcxIFej3qMdOvG0tVSw0DRRsi@2VOQqsNzJEphfI3iFyhsF8QLe0ZsOxI5c9nzntp8xOcj6hJs92kCQNvNT51mF3JtvqCDc2Ehz@zDvjt0piu24s@4hpWPtUeLdNAs@XGF483kygH306iTL3iwv8EUq5BpeLVLZ3IlQWnzS0evDDUFLPqyRDvoqD4@@tDw61iialPvIo97yXFCOxkZx5rM43lFIZgcCtMAve0jD54lz/Q7D8NcX81@N@f83 "Python 3.8 (pre-release) – Try It Online") [Test suite (also executes brainfuck)](https://tio.run/##tVhrX6pKF3/vp5hMPZDiD3aZthNM07LaXstLuY24DIoiIGBpal@9M@AlTbT2Ps/DCy8za/3XbdZl4Dmz/S5wFojHM4ULwID@gDMsaPBSWB95BIUzTVCaLaUurlT0pRsQff70APSIUAIsK6uyxbKYCRUpBHRDaxlcD58R2I/c0zXDAgZcrsxpAI0Ww@aAxwxv4zH4m4gz4dDvxu9m0xsCXu8H1pLRFhGWVX1gId68pkKXHaSOCIdon1zfhJqEFi84xfzEZQxUR/ewzhkmxBZCQ6BBNkOAxJeWzvbXzGRNy5DV1qq19Idch0FkbVokutFcbry0ZQUCGcSBAlVsK5aDJ32S1ZCbgKaBN@RdJ/wkMMzpOlRFjMQ3qGQQpAG1tgyVrXLC35ND/Rc5sgq8QYKJu4iCkgQFy0T@G083NjVJMqG1FutvuRhwquiihqpZjiqNZtjNuzvDEdzCMGeaa4rQ5wZtp16xujFja246ct2pJvwzuG1oO44B8X@1j/hf20f8sYHMDgPn1gX/wm/xr2G3Gi@7S5Q0A3S@dPXCJ52mn/4ROf5ODmNkCA8Ca6ArEJuzh2UL9kwMx0EQYDN9Qzju@W7xaLhYr2iajshQT0FxkoOb9pmCpkPXMzpL6tk@A8gtKRqkqT/L3caOGM2E/U3km1@iugbeLS5UyPb/ZpNaSPxw6U@5iX9ZiVEHHxjqPNAr8uZxtXvdoikuO10IWJwOZ5@srsn2KLDSquwzKdtnck6@0cRk2ycuEUNbi/bs7i5bYGNVapPerPbbS8QCfzY1yKYzNmwPjGWMdpeatRHE@cbw7ZVrKEDdAmiyyhiGZnwDGbmBBnfGAH5fCaFt2F3@a@tnkxFN2w3xYxXfcUp3DVU7dVqbzb6OKOLQDBHz/la9ONinSM@ftwFXUAf1Q7HGZ4Oa@PdtdzJos@4555pyGZFQYlqYHZtNzfAQymqknteLuwCisXNLrthJJkBFYYU2p7agnW5yg/pJUE13v9i0JisZWo815FbbDgxmB99WBiewVZ1QeaFwfNsZWhFqa8dsIO@OSxgOLbuOId4DbB2L@Iy0XYlVdYPrKHFyuwIGJ5sQZJxMlDX1ezXmE74zgK0uUc1dWu6GYmiA@vEfnOTPCIRrP1@PJqpNDcJFy09@tJVZnojt9XctgKv8xJI56HZ8PkuLg78M1FpmuGTbbDDYzLTtJq13MpQZy7ugnVJN13bn2eigGzQe@5HtW7HK9SDLOpMAy/Y4WWXZ@UAwvxBzRsvpvZ5l17fVWKyGk0Zr0IOqVXR2MBGagiE7nqG9y4s4sNrw434OFHREBlwLzuvKDDTMiSLLzdEw77xBo@t1D1rcM2fQK0vWSIc0GipCoA0VHe1wVhtYmiNmQTXDdnspgKGhRsXmUp0vWy6aHsOLS3XYgJyIpkkPaokeTxv9AYSAhnUQj3sz@bTXLi1aT0fBRACj97mneM6Ex0ehV0XmPXAIBcz@FRahTWpA08RmBGE@FrEXRYj9I/gmECswYrcfqVWfA/nLR7MUOcEuB@Wb/emF@EyLlzi/fzrO5c7VtK9WS@LDWmr/OCMY@RgjDPci8R935f7JeMCSFwTBle9VEq8T5cr1NJ8aCCxGFZ70REKuCE@M9IDdlU4Lr0Uim4m1BsNuKlBOJ1u3BDHGJHh/IO/3rqpW9RFLPReuLfym76fKySQb0aP4eRGOT1N1giIvasHBoXjbrR4lj3KnbPxZYwa5PE1ftYYin/SnDnwnhcJ5qy3KJylrzNRLT74Y9fzSDeSuX416aS9/cvLwqy/l8KvsQ3ZSu2XIByI9nT4@mIES3tF9cMRmRtM690h1ypdPyt6@n49hPJ0OTFimrFfxdLF9pVWL5jUj1HpY4tdZIjuUhfM9GmeM63OcqeKF4U10fy@Yiye6lNHfu74XjhLD/n3leUoraiXSHXX8sUT@ER5OTmWKv7qoKN3TAJGWJvnjskxVXzu3e1qK9U@O6Ld7vXN5KhQD@kW0chDLFUpUvhWNFu5KfIWKU/syDfVoLHpWydbTZ4Q12vdPM2fp/viN1f2p1270uU120n74yvnkwzhJ@axS93R01OH1q8O7ItWp1chYPHdYIrRsMqXUs4kfGfyeLDwWCVFO85UDHktmhGTvOfX0osfOzHhUMEdHPtk4sJTj12kn9ZYOlPx44DF/w7ZuTi6EK5LiUr2KSIz5ukRG3w5qw3TnnoocvCpVn9SdHPfvTq@tYeTWyFrlyPTWKNS4HGYMX5ju5JfQ8dcLrQfimJyMW6N4/q7N1zPdy7HUFem3wk222K4@Fvmba13naMJk5Sx2G1ElrBy56fPaPziOv6O08Hj0kdXW1MNwbDU9nGQRYZiXPB4otDXABH54PC@CnVLzjdnSx6bzi1CB10d5wQRYcg/dQnSwgI@uvf5bgLwnGnuJ5ntx/tZuNuO1NGiiImFAz78)
] |
Subsets and Splits