text
stringlengths 180
608k
|
---|
[Question]
[
For a given n, count the total number of zeros in the decimal representation of the positive integers less than or equal to n. For instance, there are 11 zeros in the decimal representations of the numbers less than or equal to 100, in the numbers 10, 20, 30, 40, 50, 60, 70, 80, 90, and twice in the number 100. Expect n to be as large as 10^10000.
Your task is to write a program to count zeros. Most efficient algorithm wins (Big O complexity)
**EDIT:** post your code and your answer for n = 9223372036854775807.
[Answer]
Python O(1):
Since the challenge has been specified to be using Big O. I concluded that the best way to do it(since the upper bound is limited by a constant) is to just to create a giant look-up array.
However, this program would be too big to post here, so I made a program that generates it:
```
def zeroesUpToN(n):
zeros = 0
for i in range(n):
s = str(i+1)
zeros += s.count('0')
return zeros
s = "print(["
for i in range(10^10000):
s += str(zeroesUpToN(i+1)) + ",";
s = s[:-1] + "][int(input())])"
print(s)
```
So, this will ALWAYS take a long time to run(I mean the resulting program, not the generating program. The generating program would take even longer). But, how long it takes to run will not depend on n. Therefore, by definition it is an O(1) solution.
Here is an actual program that works for smaller outputs(up to 200):
```
print([0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,11,12,13,14,15,16,17,18,19,20,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,31][int(input())])
```
The real one is obviously much bigger.
P.S This is the problem with Big O problems.
EDIT: Oops, I forgot to give credit to @user2509848 whom I actually stole the code for generating each N.
[Answer]
Some thoughts up front:
```
f[i]: number of zeros in [10^i, 2*10^i)
g[i]: number of zeros in [10*10^i, 11*10^i)
h[i]: number of zeros in [0, 10^i)
i f g h
1 1* 10* *
2 1** 10** **
3 1*** 10*** ***
4 1**** 10**** ****
f[i] = 9*f[i - 1] + g[i - 1]
g[i] = f[i] + 10^i
h[i] = h[i - 1] + 9*f[i - 1]
```
Now the code:
```
def zeros(n):
s = str(n)
f = [0]
g = [1]
h = [0]
for i in range(1, len(s) + 1):
f.append(9*f[-1] + g[-1])
g.append(f[-1] + 10**i)
h.append(h[-1] + 9*f[-2])
k = len(s) - 1
a = h[k] # all numbers with fewer digits
a += (int(s[0]) - 1)*f[k] # same number of digits but first digit less
s = s[1:]
while s:
if s[0] == '0':
a += int(s) + 1
else:
a += int(s[0])*f[len(s) - 1] + 10**(len(s) - 1)
s = s[1:]
return a
```
For n = 9223372036854775807 the result is 16577013372932555466. This is different from [the currently accepted answer](https://codegolf.stackexchange.com/a/18112/13683) by @user14325, but I have more trust in it since starting at n=1000, @user14325 disagrees from the [naive implementation](https://codegolf.stackexchange.com/a/18102/13683) suggested by @user2509848 in which I have a lot of trust due to its simplicity.
Complexity of my code is O(log n), at least if you assume uniform cost for arithmetic operations. Taking bit cost into account, it will probably be O(log(n)3log log(n)) or something like that, depending on how Python does its big integers and the exponentiation on them. If you care about the constants, then there is a lot of room for optimizations. Converting between numbers and strings all the time is hardly efficient. But as long as you only care for asymptotic behavior, I'll leave it at
that.
[Answer]
Java:
```
public class ZeroCount {
static final int max = 65498;
public static void main(String[] args) {
int res = 0;
for (int i = 10; i <= max; i*=10) {
res += max/i + max/(10*i) * (i-1);
res -= (max % (10*i) < i) ? (i-1) - (max % i) / (i/10) : 0;
}
System.out.println(res);
}
}
```
Should be *O(log(n))*
**Edit:**
For n=9223372036854775807
I decided to use Python instead of Java since 9223372036854775807 is Long.MAX\_VALUE in Java and I didn't want to use BigInt
```
def zeros(n):
res = 0
i = 10
while i <= n:
res += (n // i) + n // (10 * i) * (i - 1)
res -= (i - 1) - (n % i) if n % (10 * i) < i else 0
i *= 10
return res
print(zeros(9223372036854775807))
> 16577013372932555466
```
[Answer]
# Python 3
```
n = int(input())
zeros = 0
for i in range(n):
s = str(i+1)
zeros += s.count('0')
print(zeros)
```
Fast up to 10,000,000. It gets slower when I bring it to 100,000,000.
[Answer]
# Haskell - O(n) for 10^n input
```
import Data.Char
import Data.List
p n = (10^n-10)`div`9 -- number of padded zeroes below 10^n
t n = n*10^(n-1) -- number of zeroes below 10^n with padded
digsToInt = foldl1 (\x y -> x*10+y)
-- number of zeroes below n
f :: Integer -> Integer
f n = h ds (len - 1) - p len
where
ds = map (fromIntegral . digitToInt) $ show n
len = genericLength ds
h [x] _ = 0
h (x:ys) n | x == 0 = 1 + digsToInt ys + h ys (n-1)
| otherwise = t (n+1) - (10-x) * t n + h ys (n-1)
```
Answer for 9223372036854775807 is 16577013372932555466.
[Answer]
# C# O(log n):
```
using System;
namespace Zeroes
{
class program
{
static void Main(string[] a)
{
int n = int.Parse(a[0]);
int result = 0;
for (int i = 1; i < Math.Log(n); i++)
result += n/(int)Math.Pow(10, i);
Console.Write(result);
}
}
}
```
Only works for integers, of course, but the logic's sound. I have a feeling there's a better algorithm to be found, though. Nope, there's a bug in this.
[Answer]
## Python *O(log10 n)*
```
def zerosA(n):
'''finds the number of zeros from [1, 10**n]'''
if n < 1: return 0
return 10*zerosA(n-1) + 10**(n-1) - 9*(n-1)
def zerosB(n):
'''finds the number of zeros from (10**n, 2*10**n]'''
if n < 1: return 0
return 10**n + n*10**(n-1) - 1
def zerosC(n):
'''finds the number of zeros from (2*10**n, 3*10**n]'''
if n < 1: return 0
return n*10**(n-1)
def count_zeros(n):
p = z = 0
while n >= 10:
n, r = divmod(n, 10)
if r > 0:
z += zerosB(p) + zerosC(p)*(r-1) + `n`.count('0')*r*10**p
p += 1
z += zerosA(p) + zerosC(p)*(n-1)
return z
if __name__ == "__main__":
print count_zeros(9223372036854775807)
```
Output:
```
16577013372932555466
```
For the number *12345*, for example, this works in the following manner:
[*12341*, *12345*] โ *0*
[*12301*, *12340*] โ *13*
[*12001*, *12300*] โ *159*
[*10001*, *12000*] โ *1599*
[*1*, *10000*] โ *2893*
For a total sum of *4664*. No more than *log10 n* iterations are needed to reach the final answer.
] |
[Question]
[
## Challenge
>
> Consider a square matrix of order N(N
> rows and N columns). At each step you
> can move one step to the right or one
> step to the top. How many
> possibilities are to reach (N,N) from
> (0,0)?
>
>
>
## Constraints
* Assume input will be a positive integer N satisfying 1 <= N <= 125
* No special characters, only 0-9
* Output should be in a separate line for ever test-case.
**Sample test Cases:**
**Input:**
```
32
99
111
98
101
69
23
56
125
115
```
**Output:**
```
1832624140942590534
22750883079422934966181954039568885395604168260154104734000
360523470416823805932455583900004318515997845619425384417969851840
5716592448890534420436582360196242777068052430850904489000
360401018730232861668242368169788454233176683658575855546640
23623985175715118288974865541854103729000
8233430727600
390590044887157789360330532465784
91208366928185711600087718663295946582847985411225264672245111235434562752
90678241309059123546891915017615620549691253503446529088945065877600
```
## Good luck!
The `shorter` an answer is, the better!
[Answer]
**PARI GP**
```
n->binomial(2*n,n)
```
**Mathematica**
```
Binomial[2#,#]&
```
[Answer]
## J, 8
```
(!+:)~x:
```
* `x:` forces arbitrary precision
* `+:` doubles its argument
* `!` is the binomial
* `a !+: b` is the binomial of a out of 2\*b
* `(!+:)~ b` is the binomial of b out of 2\*b
[Answer]
## C# (203 chars)
```
using System;using i=System.Numerics.BigInteger;class X{static void Main(){Func<i,i>f=null;f=n=>n<2?1:n*f(n-1);try{i p=i.Parse(Console.In.ReadLine());Console.WriteLine(f(2*p)/f(p)/f(p));Main();}catch{}}}
```
Readable:
```
using System;
using i = System.Numerics.BigInteger;
class X
{
static void Main()
{
Func<i, i> f = null;
f = n => n < 2 ? 1 : n * f(n - 1);
try
{
i p = i.Parse(Console.In.ReadLine());
Console.WriteLine(f(2 * p) / f(p) / f(p));
Main();
}
catch { }
}
}
```
Tricks I used:
* Using try/catch instead of an explicit end condition for the main loop
* Calling `Main()` recursively is slightly shorter than `for(;;){`...`}` or `x:`...`goto x;`
[Answer]
## Ruby, 48 characters
```
#!ruby -n
s=1;1.upto(l=$_.to_i){|a|s+=s*l/a};p s
```
[Answer]
**Python ~~67~~ 57 Characters**
```
while 1:s=i=1;n=input();exec"s=s*(n+i)/i;i+=1;"*n;print s
```
[Answer]
## DC -- 27 character
```
?d2*[d1-d1<F*]dsFxrlFxd*/pq
```
Invoke it like
```
echo 125 | dc -e '?d2*[d1-d1<F*]dsFxrlFxd*/pq'
```
or
```
echo 23 | dc -f
```
The bit in the brackets is a recursive factorial, `?` reads the standard input, and the rest is stack management and operations.
[Answer]
## PARI/GP -- 14 bytes
```
n->(2*n)!/n!^2
```
Shorter than the built-in
```
n->binomial(2*n,n)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes
```
d$ฦ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiZCTGiCIsIiIsIjJcbjNcbjRcbjUiXQ==)
Port of all the other answers
```
ฦ # Binomial coefficient of...
d # Double input
$ # Input
```
[Answer]
## [Golf-Basic 84](http://timtechsoftware.com/?page_id=1261 "Golf-Basic 84"), 37 characters
```
l`A:1_S:1_Ii`N:(S*(N+I)/I:I++I)N_Sd`S
```
I can't test this right now, but I think that the the `:` and/or the multiplying of the result of `I++I` and an integer result from `S*(N+I)/I` will cause it to return `ERR:UNDEFINED`
] |
[Question]
[
## Background
In the game [stick ranger](https://dan-ball.jp/en/javagame/ranger/), there is an item which grants the character the ability to get critical hits.
Each time a projectile hits an enemy, it has some probability to be a critical hit (crit). For most weapons this is calculated independently each time, but for one class (the angel) things work differently. The angel throws multiple rings per volley, and each has a chance to crit. But, (and apparently this is not a bug) once a ring crits, that crit multiplier stays. And in fact if one is lucky enough for a second ring to crit in the same volley, the crits will multiply. So if the first crit is 10X the original damage, the second will be 100X. All crits persist until the next volley is reached. This is great, but I want to know what my damage per second is given a particular set up. I know the base damage and hit rate, but this crit multiplier business is tricky, and I could use a short program to help me out.
## The challenge
You will be given three inputs: the crit probability, the crit multiplier, and the number of rings. We'll assume each ring hits some enemy exactly once. You must then output the average damage per ring (or per volley) gained by having the crit applied.
Standard I/O rules apply, the inputs and output may be in any logical format including fractions, decimals, and percentages. You may assume \$0<\text{odds}<1\$, \$1<\text{multiplier}\$, and \$0<\text{hits}\$. The output from your program must be within \$0.1\%\$ of the true value at least \$90\%\$ of the time.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
## Worked example
Let's work through the answer with a crit chance of 0.2, multiplier of 6, and 2 rings. For this example all I/O uses decimals, and I'll find the average damage per ring. There are four distinct outcomes
```
outcome damage probability weighted
no crits 1 + 1 = 2 0.8 * 0.8 = 0.64 2 * 0.64 = 1.28
no crit then crit 1 + 6 = 7 0.8 * 0.2 = 0.16 7 * 0.16 = 1.12
crit then no crit 6 + 6 = 12 0.2 * 0.8 = 0.16 12 * 0.16 = 1.92
two crits 6 + 36 = 42 0.2 * 0.2 = 0.04 42 * 0.04 = 1.68
----
total 6.00
```
Thus our answer is `6/2 = 3` average damage per ring. This is much higher than what a simple crit system would yield
`1*0.8 + 6*0.2 = 2`
## Test cases
```
odds, multiplier, hits -> output
0.2, 6, 2 -> 3
0.3, 5, 3 -> 5.896
0.5, 2, 4 -> 3.046875
0.2, 7, 5 -> 18.529984
0.15, 10, 5 -> 24.6037391875
```
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
๏ผฎฮธ๏ผฉโฮฃ๏ผธโร๏ผฎโ๏ผฎโฆยทยนฮธฮธ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RMMlsywzJVUjuDRXIyC/HCjvmZdclJqbmleSmqIRkpmbWqyBrFtTR8ElFaEARQoIdBSA2nNKizPLUoMS89JTNQx1FArB4iDS@v9/Iy4DPSMus/@6ZTkA "Charcoal โ Try It Online") Link is to verbose version of code. Takes the number of rings as the first parameter, then the odds and multiplier. Explanation: Each ring has a `p` chance of dealing `m` times as much damage as the previous ring and a `1-p` chance of dealing the same damage as the previous ring. The expected damage of the ring is therefore `1-p+pm` times the expected damage of the previous ring and each ring's expected damage is therefore the `n`th power of that. It then remains to take the average of these values.
```
๏ผฎฮธ Number of rings as an integer
๏ผฎ Odds as a number
ร Multiplied by
๏ผฎ Multiplier as a number
โ Decremented
โ Incremented
๏ผธ Vectorised raise to power
โฆยท Inclusive range from
ยน Literal integer `1` to
ฮธ Number of rings
ฮฃ Take the sum
โ Divide by
ฮธ Number of rings
๏ผฉ Cast to string
Implicitly print
```
[Answer]
# [Python 3](https://docs.python.org/3.8/), 40 bytes
```
lambda p,m,n:((c:=1-p+p*m)**n-1)/(n-n/c)
```
[Try it online!](https://tio.run/##LYzBDoMgEAXvfsXeBAsIggom9kt6sdZGE0Wi2KZfb9H2OLPz1n18P1up3bI/69s@NtP90YAjE7EVQm1VC@ouLplwklgqcIostWmL93c/jB2IKoKVwLx5qGGwbvMIs9WNg0cx0CvEOPr9qrtXM6L1wGWwHj3RqTHeOcsIFASyo5cRZ5JATkAemDNtiqACh0idBeOq0GUenbsytIcVmuWZMVoFLUIt@P@QKVZwWUojwuYL "Python 3.8 (pre-release) โ Try It Online")
A formula I derived. With crit probability \$p\$, multiplier \$m\$, and \$n\$ hits, the average damage per hit is
$$ \frac{c}{n} \frac{c^n-1}{c-1}, \text{ where } c=1-p+pm$$
*Thanks to dingledooper for -2 bytes.*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
<*>ILmร
A
```
Inputs in the order *critDamageMultiplier* (\$m\$), *critProbability* (\$p\$), *amountOfRings* (\$n\$).
Port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/262686/52210), so make sure to upvote him as well!
[Try it online](https://tio.run/##yy9OTMpM/f/fRsvO0yf3cKvj//9mXAZ6RlxGAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCaPF/Gy27CJ/cw62O/3X@R0eb6RjoGekYxepEmwJZxjrGQJYRkGWqYwJkmYNlTYEsQwMg09AUyI4FAA).
**Explanation:**
Uses the formula:
$$a(m,p,n)=\frac{\sum\_{i=1}^n{(p(m-1)+1)^i}}{n}$$
```
< # Decrease the first (implicit) input-integer (the multiplier) by 1
* # Multiply it to the second (implicit) input-decimal (the probability)
> # Increase it by 1
IL # Push a list in the range [1, third input-integer (the amount of rings)]
m # Take the earlier value to the power of each of these integers
ร
A # Pop and get the average of this list
# (after which it is output implicitly as result)
```
[Answer]
# JavaScript (ES7), 96 bytes
Naive implementation of the algorithm.
```
(p,m,n)=>eval("for(t=0,i=2**n;i--;t+=d*q)for(q=x=1,d=0,j=n;j--;d+=x)q*=i>>j&1?(x*=m,p):1-p;t/n")
```
[Try it online!](https://tio.run/##bc3bjoIwFIXhe59ix4tJW0vpgXKQbHwWIjCBYAtKDG@PnTjxQr1eX/411Pf6dr720xI537RbhxuZ@IU7ilV7r0ey7/yVLCh5j5oxV/ZRVC4HbNhM/5YZV1S8CfuArhzC2BxwpTPDvqqGH3UiK8MLn@hRRVO5xG5Pt7N3Nz@2YvS/pCMgheYAKQdNKcQxmN0HMAFYDuYJrMiL9BMFAKGU/FeETNI8s7uvbxkH@3QqF1YXRZ68QSlUCCr5gjoRqTSZKVSobg8 "JavaScript (Node.js) โ Try It Online")
[Answer]
# [Arturo](https://arturo-lang.io), 34 bytes
```
$[p m n][c:+1-p p*m(-c^n 1)/n-n/c]
```
[Try it!](http://arturo-lang.io/playground?1NPZsG)
Port of xnor's [Python answer](https://codegolf.stackexchange.com/a/262684/97916).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 56 bytes
```
p=>m=>g=(h,w=1/h)=>h--&&(1-p)*(g(h,w)+w)+p*(g(h,w*=m)+w)
```
[Try it online!](https://tio.run/##bc3ZCsIwEAXQd78iTyWpJs3e5CH9l1K7KF2CFf38mNCCYIXhwgyHO/f6Va/N4@afeF6ubehc8K6aXNU7OFzejhUDctWAcZZBhj3KYZ/u6BzH70vuprSHZpnXZWzJuPSwg4ASjiAAOgZHCBQFEKcDEYmoGGIjihirjywJkOrk3kSo1KZUp/8/yxhqk8wQxa018odSwlIpo1/KJdFUlMKy2Bw@ "JavaScript (Node.js) โ Try It Online")
Recursive fork possibility
# [JavaScript (Node.js)](https://nodejs.org), 35 bytes
```
(p,m,n)=>((c=1-p+p*m)**n-1)/(n-n/c)
```
[Try it online!](https://tio.run/##bc1LDoIwFEDROat4wxb7/9EOcC8EwWigbcS4/doE40Ccn9x7H17DNj5u@Uljukxl7gvKZCUR92eExl7SfMrtits2Uok5ijTyEZcxxS0tE1vSFc0IBFMEwBFQGAPnoJsD0BVYAnoHlvngjqgCqCXzqTBhnO9s8/fWEbC7k55ZFYI3P1AwWYNSfKEyzAnd6SBrtbwB "JavaScript (Node.js) โ Try It Online")
Port of formula
] |
[Question]
[
Your program must take an alpha/numeric input string and print it sideways (rotated 90 degrees clockwise). So for example, HI, would become:
```
#####
#
#####
#####
```
**Rules:**
The shortest code wins. For the sake of objectivity [this](http://www.identifont.com/samples/core/Pixelette.gif) will be the standard font. The input still only has to be alpha-numeric. Capitalization does not matter.
[Answer]
## C 550 503
```
#define L putchar('\n');
c,b,i,j,m[]={0xe9d72e,0x10fd25,0x9ace29,0x556b5,0x4fd184,0x16ad6bd,0x156ae,0xc5e10,0x556aa,0x756a8,0,0,0,0,0,0,0,0xfa51e0,0xaad7e0,0x118c5c0,0xe8c7e0,0x15ad7e0,0x14a53e0,0x16ac5c0,0x1f213e0,0xf8000,0x1e08440,0x11513e0,0x1087e0,0x1f4111f,0x1f223e0,0xe8c62e,0x8a53e0,0xd9462e,0x5d29f,0x12ad6a9,0x1087e10,0xf043e,0x18304d8,0x1c1f07c,0xd909b,0xf14bd,0xcd6b3};main(){for(;;){c=getchar();c=c<48?11:c>90?c-80:c-48;b=0;for(i=0;i<5;i++){for(j=0;j<5;j++)putchar(m[c]&(1<<b++)?35:32);L}L}}
```
(Incorporated BrainSteel's tips and optimized a bit more)
Here's the non-obfuscated code:
```
#include <stdio.h>
int map[]
={
// 0 - 9
0xe9d72e, 0x10fd25, 0x9ace29, 0x556b5, 0x4fd184, 0x16ad6bd, 0x156ae, 0xc5e10, 0x556aa, 0x756a8,
// Other stuff
0,0,0,0,0,0,0,
// A - Z
0xfa51e0, 0xaad7e0, 0x118c5c0, 0xe8c7e0, 0x15ad7e0, 0x14a53e0, 0x16ac5c0, 0x1f213e0, 0xf8000, 0x1e08440, 0x11513e0, 0x1087e0, 0x1f4111f, 0x1f223e0, 0xe8c62e, 0x8a53e0, 0xd9462e, 0x5d29f, 0x12ad6a9, 0x1087e10, 0xf043e, 0x18304d8, 0x1c1f07c, 0xd909b, 0xf14bd, 0xcd6b3
};
int main()
{
for(;;)
{
int c = getchar();
c = c < '0' ? 11 : c > 'Z' ? c - ('0' + 'a' - 'A') : c - '0';
int bit = 0;
for(int i=0; i<5; i++)
{
for(int j=0; j<5; j++)
putchar(map[c] & (1 << bit++) ? '#' : ' ');
putchar('\n');
}
putchar('\n');
}
}
```
I've encoded the characters the following way: I wrote a C "script" that takes a 5x5 area of characters from STDIN, changes "space" to 0 and anything else to 1, rotates the whole area by 90 degrees and finally puts every cell of the area in one bit of a 32-bit integer (the hex numbers in 'map').
That's how the "script" looks like:
```
#include <stdio.h>
int main()
{
int array[5][5];
for(int i=0; i<5; i++)
{
for(int j=0; j<5; j++)
array[j][i] = (getchar() != ' ');
getchar();
}
int res = 0;
int bit = 0;
for(int j=0; j<5; j++)
{
for(int i=0; i<5; i++)
res = res | (array[j][4-i] << bit++);
}
printf("0x%x\n", res);
return 0;
}
```
I am pretty sure there are FAR smaller programs possible (for example in Perl or Ruby), but this is the best I can come up with right know.
[Answer]
# Mathematica ~~120~~ 119
This should work.
```
g@t_:=GraphicsGrid[Transpose@Reverse@ImageData@Binarize@Rasterize@Style[t,{12,FontFamily->"Pixelette"}] /.{1 ->" ",0-> "#"}]
```
The function `g` takes the input text, converts to Pixelette font, rasterizes it, flips it (Reverse and Transpose), examines the array of `1`s and `0`s, and outputs the ASCII text (as text, not as an image or graphic).
`GraphicsArray` conveniently displays the ASCII output in a table.
I used "HELLO" as the input because each letter in "HI" is horizontally and vertically symmetric, hence HI is a bad choice to use for testing.
```
g["HELLO"]
```

[Answer]
# Python 2, ~~376~~ ~~364~~ ~~361~~ 315
This is my first attempt at code golf.
The font is encoded as a single large integer in which each character takes up 25 bits - 5 columns of 5 pixels each. It reads its input from stdin as a Python string (including the quotes).
Updated three times to reduce size. The third update incorporates changes suggested by Sp3000.
```
for c in input().upper():
c=ord(c)-48
if c>9:c-=7
s,l='',int('17vhur2t4cze6tuj2ja3e1i8luj1b1frxdf9pg8dxjw7ian4517nliqqn8tdogkck15rn5n6vz3l5zf1u10cv5trc4n49xtznzx7egrjllrn8e1nlgyjp3z481ffsqmiw3pj3a538wnhwydpp85o9j85kzqxfl3qop50sokgcvwfn2',36)>>25*c
for i in range(25):
s+=' #'[l&1];l/=2
if i%5>3:print s;s=''
```
[Answer]
# C,335
Score excludes whitespace, which is unnecessary and only included for clarity.
In the absence of further info from the OP, I have assumed exactly one blank space is required between characters. If padding is required, backtick (ASCII 96) can be used (not sure how that character will display here.)
After converting to uppercase with `c-c/91*32`, I search the big string for the required character, and set a pointer to the character after it. This makes it easy to handle the variable width font. It also avoids the need to unite the ASCII ranges for letters and numbers.
The font data is contained, column by column, in the big string. As only 5 bits are required, only ASCII codes 95 and over are used. The next code below 90 signals the end of the character.
The program tends to segfault on characters outside the alphanumeric range.
```
char*p,s[99],c,i,j,k;
main(){
for(scanf("%s",&s);c=s[i];i++){
p=strchr("A~ee~B_uujCnqqqD_qqnE_uuF_eeGnqu}H_dd_I_JhppoK_djqL_ppM_bdb_N_bd_OnqqnP_eebQnqivR_emrSruuiTaa_aaUoppoVclplcWgxgxgX{dd{YwttoZyuus0nyusn1r_p2ryur3quuj4ljk_5wuum6nuuh7aa}c8juuj9buun",c-c/91*32)+1;
for(;*p>90;p++)for(k=5;k--;k||puts(""))putchar(*p>>k&1?35:32);
puts("");
}
}
```
[Answer]
# Java 8 - 404
First time posting here. This program takes a single argument on the command line. Java 8 is required (Java 7 can be used at a cost of 3 additional characters).
```
class A{public static void main(String[]a){a[0].chars().forEach(c->{String o="";c-=c>57?c>90?87:55:48;for(char d:">AA>09O1009CE90AEE:06:BO0MEEF0>EE20@@GH0:EE:08EE>0?DD?0OEE:0>AAA0OAA>0OEE00ODD00>AEG0O44O0O0000211N0O4:A0O1100O848OO84O0>AA>0ODD80>AB=0ODF909EEB0@@O@@N11N0H616HL3L3LK44K0M55N0CEEI0".substring(c*=5, c+5).toCharArray()){for(d-=48;d>0;d/=2)o+=d%2==1?'#':32;o+="\n";}System.out.println(o);});}}
```
Unobfuscated version:
```
class A {
public static void main(String[] a) {
a[0].chars().forEach(
c -> {
String o = "";
c -= c > 57 ? c > 90 ? 87 : 55 : 48;
for (char d: (">AA>09O1009CE90AEE:06:BO0MEEF0>EE20@@GH0:EE:08EE>0?DD?0"
+ "OEE:0>AAA0OAA>0OEE00ODD00>AEG0O44O0O0000211N0O4:A0O1100O848O"
+ "O84O0>AA>0ODD80>AB=0ODF909EEB0@@O@@N11N0H616HL3L3LK44K0M55N0"
+ "CEEI0").substring(c *= 5, c + 5).toCharArray())
{
for (d -= 48; d > 0; d /= 2)
o += d % 2 == 1 ? ' ' : 32;
o += "\n";
}
System.out.println(o);
}
);
}
}
```
Each row of pixels is encoded in the 5 least significant bits of a byte in the long string, and ASCII '0' is added to make the string contain only printable characters. The code simply translates each character in the input string to an index into the string, iterating through the 5 bytes representing the respective character, and decoding them using the reverse process. There are more compact encodings, but they would be more complex to decode and would probably inflate the code size too much to be worthwhile.
] |
[Question]
[
# Challenge :
Your job is to find the given number `N`.
---
# Input :
You will be given a string in the following form:
```
dN ยฑ Y = X
```
Where:
```
d, N, X, Y are all numbers with d , X , Y being integers (not decimals).
```
---
# Output :
Solve the equation and output the value of `N` rounded. Round up if decimal is greater than or equal to `0.5` and round down if less than `0.5`
---
# Examples :
```
Input Output
N + 1 = 3 ---> 2
N - 1 = 5 ---> 6
2N + 1 = 3 ---> 1
2N + 1 = 4 ---> 2
```
---
# Winning criteria :
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in each language wins.
---
# Notes :
* Answer must be rounded it cannot be a float
* Whitespace do not matter. You can have every element in the string separated by white space if you want or if you don't want leave it as it is.
* You do not need to check for invalid input. i.e. All inputs will be strings in the given format.
---
[Answer]
# [Python 2](https://docs.python.org/2/), ~~88~~ ~~74~~ 70 bytes
-14 bytes thanks to [Chas Brown](https://codegolf.stackexchange.com/users/69880/chas-brown).
-4 bytes thanks to [Sunny Patel](https://codegolf.stackexchange.com/users/58557/sunny-patel).
```
d,w,Y,_,X=input().split()
print round((int(X)-int(w+Y))/float(d[:-1]))
```
[Try it online!](https://tio.run/##K6gsycjPM/qfnJ@SaqukpPQ/RadcJ1InXifCNjOvoLREQ1OvuCAnE0hzFRRl5pUoFOWX5qVoaACZGhGauiCqXDtSU1M/LSc/sUQjJdpK1zBWU/M/0CgurtSK1GQFkMlaJv@VDP0UtBUMFWwVjJW4QBxdMMcUyDFCloFzTJQA "Python 2 โ Try It Online")
[Answer]
under the assumption (according to comments) that we deal only with digits
# [JavaScript (Node.js)](https://nodejs.org), 30 bytes
\*thanks for @Rick Hitchcock for pointing out i can use 1 instead of space (reduces 13 bytes
```
x=>(x[3]+x[5]-x[9])/-x[0]+.5|0
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1k6jIto4Vrsi2jRWtyLaMlZTH0gZxGrrmdYY/E/OzyvOz0nVy8lP10jTUDL0U9BWMFSwVTBW0rS1NdLkwpTXBcubguTNMOSNUPQbairgVGACseA/AA "JavaScript (Node.js) โ Try It Online\"e")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~64~~ 63 bytes
Using [`eval`](https://docs.python.org/2/library/functions.html#eval)
```
d,w,Y,_,X=input().split()
print-eval('('+w+Y+'-'+X+')/'+d[:-1])
```
[Try it online!](https://tio.run/##K6gsycjPM/qfnJ@SaqukpPQ/RadcJ1InXifCNjOvoLREQ1OvuCAnE0hzFRRl5pXoppYl5mioa6hrl2tHaqvrqmtHaKtr6qtrp0Rb6RrGav4HmsGVWpGarAAyUcvkv5Khn4K2gqGCrYKxEheIowvmmAI5RsgycI6JEgA "Python 2 โ Try It Online")
Saved 1 byte thanks to [Keyu Gan](https://codegolf.stackexchange.com/users/59292/keyu-gan)
[Answer]
# Java 10, ~~111~~ 94 (or 92) bytes
```
s->{var a=s.split("N|=");return(int)((new Float(a[2])-new Float(a[1]))/new Float(a[0])+.5);}
```
Input is in the format `dNยฑY=X` (without any spaces) instead of `dN ยฑ Y = X`.
[Try it online.](https://tio.run/##jU@xbsIwEN35ilMmn1DchpYpMiNbszCiDFfjVgbjRPYlFYJ8e@qGDExtpbvhvXt6792ResqPh9OoHcUIb2T9dQFgPZvwQdpA9QMnArTYcbD@EyKWiRzSpolMbDVU4EHBGPPNtacApKKMrbMssuqmMiyD4S54kXxQCG@@YOsaYkH7VY35Iy5qxKdH4rnGpVxjOYzlPbHt3l1KnIP7xh7gnHrP7fY14b3z7hLZnGXTsWzThZ0XXmqRFdWyUC8ZTl/8JssLtf5Ttvqf2yR7nWXDYhi/AQ)
2 more bytes could be saved if the numbers are never outside the `[-128, 127]` range, in which case the last and one of the two first `Float` can be changed to `Byte`.
[Try it online.](https://tio.run/##jU8xbsMwDNzzCsKTiMBqnTaToQ4dutVLxsADq6iBUkU2JNpFkPrtruJ4yJQWIIc7Hu6OB@opP@y@Ru0oRngn688LAOvZhE/SBqoLnAjQYsPB@j1ELBM5pE0TmdhqqMCDgjHmL@eeApCKMrbOssiqH5VhGQx3wYvkg0J48w1vriEWtF3VmF/w64lNgkWN@HCDH2tcyjWWw1he89ruw6W8ObZv7A6OqfXcbVsTXhtvTpHNUTYdyzZd2HnhpRZZUS0L9ZTh9MM9WV6o9Z@y1f/cJtnzLBsWw/gL)
**Explanation:**
```
s->{ // Method with String parameter and integer return-type
var a=s.split("N|="); // And split by "N" or "=" to a String-array
return(int)((new Float(a[2]) // Return the third number (after the equal sign),
-new Float(a[1])) // minus the second number (including leading +/-),
/new Float(a[0]) // divided by the first number
+.5);} // Rounded by using `(int)(R + 0.5)`
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
q/N|=/ f
o!-Uo)r!รท r
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=cS9OfD0vIGYKbyEtVW8pciH3IHI&input=IjJOKzE9NCI)
```
q/N|=/ f\no!-Uo)r!รท r :Implicit input of string U
: e.g. "2N+1=4" "N+1=4"
q :Split on
/N|=/ : "N" or "="
> ["2","+1","4"] ["","+1","4"]
f :Filter (removes the first element if the string started with "N")
> ["2","+1","4"] ["+1","4"]
\n :Reassign to U
Uo :Pop last element (X)
> "4" "4"
o :Modify last element (Y)
!- :X-Y
> ["2",3] [3]
r :Reduce by
!รท : Inverse division
> 1.5 3
r :Round
> 2 3
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~54~~ 46 bytes
```
Round[ToExpression[""<>(#/."="->"-")]~Root~1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Pyi/NC8lOiTftaKgKLW4ODM/L1pJycZOQ1lfT8lWSddOSVdJM7YuKD@/pM4wVu1/QFFmXkl0WnS1kpGSjpIfEGsDsSEQ2wKxiVJtbOx/AA "Wolfram Language (Mathematica) โ Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 44 bytes
```
x=>([m,a,r]=x.split(/N|=/),r-a)/(+m||1)+.5|0
```
[Try it online!](https://tio.run/##fc27DoMgGEDhvU/BJoSb0NKl@X0EXqDpQKw2NigGjHHg3enSwaSX/cs5T7e61MZhXvgU7l3poWzQ4OvIHIs32ESa/bBgaTNIwiJ3RGI65qwIFSbXpQ1TCr4TPjxwjytkqYJjRRAAII3I5fABuALzBucvQO8L6hc4/Vmo2lID2uxIeQE "JavaScript (Node.js) โ Try It Online")
Or, for only single-digit numbers:
# [JavaScript (Node.js)](https://nodejs.org), 36 bytes
```
([m,,o,a,,r])=>-(o+a-r)/(+m||1)+.5|0
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@18jOldHJ18nUUenKFbT1k5XI187UbdIU19DO7emxlBTW8@0xuB/cn5ecX5Oql5OfrpGmoa6gp@2oa2xuqaCra2tgpGCpjUXhgJdQ1tTqAIzLAqMkE0wxKXABMmK/wA "JavaScript (Node.js) โ Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), 133 bytes
```
N,d,y,x,a[9],o;f(*s){sscanf(s," %[0-9N] %c %d = %d",a,&o,&y,&x);d=!sscanf(a,"%d",&d)?1:d;N=(x-(o>43?-y:y))*2/d;printf("%d",N/2+N%2);}
```
[Try it online!](https://tio.run/##bY/vboIwFMW/9ynuukBabMcfYYsy9A14AeOHppVJwsBQSCDGZ2eATtDYD@3N75x7ciq5zET@072nucxqdYBvXam0@Dhuupgp1rKGid1qz4owIZamZ62lyBOiGQZj5/BVvAdDgqEg6i/MBDMLZrbMbGioorebWzA8iKaiW3etwjgiDSfFxl9uebtuKbU8W4WnMs2rhIzO2PYWseHR8NJJkWUJkUdRglVJCnBGcLdquB3O@QYAM@gtIYKEXN9TXWmCcT9eEOp34FekOaFDxjUXQwwLcPv2y8E1o3ykwZx6L7136s/p8p@6D@ZgwMEQ4cyx@@Xcs313UFB5qOoyB2esbltoKvrwZw9NXR@ET@S93nBhUvynLMtG3R8 "C (clang) โ Try It Online")
This handles all spaces except between `d` and `N`.
[Removed wrong answer that rounds down]
[Answer]
# [Befunge-93 (FBBI)](https://github.com/catseye/FBBI), ~~34~~ 26 bytes
```
&~$~90p0&X&-2*\/-:2%\2/+.@
```
[Try it online!](https://tio.run/##S0pNK81LT9W1NNZNS0rK/P9frU6lztKgwEAtQk3XSCtGX9fKSDXGSF9bz@H/fxM/bQNbYwA "Befunge-93 (FBBI) โ Try It Online")
If we didnโt need to bother with rounding correctly, it could be much smaller:
```
&~$~90p0&X&-\/-.@
```
[Try it online!](https://tio.run/##S0pNK81LT9W1NNZNS0rK/P9frU6lztKgwEAtQk03Rl9Xz@H/fzM/bUtbEyMA "Befunge-93 (FBBI) โ Try It Online")
`-\/-`
[Answer]
# [Yabasic](http://www.yabasic.de), 142 bytes
An anonymous function that takes input as a string and outputs to the console.
```
Line Input""s$
dim n$(5)
k=token(s$,n$())
n$=n$(1)
If n$="N"n$=("1N")
?Int((Val(n$(5))-Val(n$(2)+"1")*Val(n$(3)))/Val(Left$(n$,Len(n$)-1))+.5)
```
[Try it online!](https://tio.run/##Rc7BCsIwDAbge58ihB4atymd27F4EwajJ/E@tYMy7cRV0KevcQy9hC8/Ccm7O3WTP6f9@ABvQMNhhCq1Pjhowv0ZEScpLv4GQaqaxGDiOLigJplzQCSCNAxNoul5xKBFrgq1RRK7JkSljt1VzctULCwpQ420WtotEW2@bl0fJSd5yxeCpEITZeuaknWvmMBCxv8Z2ApmMbMW5T/9sfoA "Yabasic โ Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 110 bits1, 13.75 [bytes](https://github.com/Vyxal/Vyncode/blob/main/README.md)
```
โNx*\=/ฦโqh.1+แน
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJ+PSIsIiIsIuKAm054KlxcPS/GkuKIhnFoLjEr4bmZIiwiIiwiISguKikgKy0tLT4gKFxcZCspXG4gTiArIDEgPSAzICAgICAgICAtLS0+IDJcbiBOIC0gMSA9IDUgICAgICAgIC0tLT4gNlxuMk4gKyAxID0gMyAgICAgICAgLS0tPiAxIFxuMk4gKyAxID0gNCAgICAgICAgLS0tPiAyIl0=)
Python rounding is a little goofy hence the `.1+แน` at the end.
Could be [9.125 bytes: `โNx*\=/ฦโq`](https://vyxal.pythonanywhere.com/?v=1#WyJ+PSIsIiIsIuKAm054KlxcPS/GkuKIhnEiLCIiLCIhKC4qKSArLS0tPiAoXFxkKylcbiBOICsgMSA9IDMgICAgICAgIC0tLT4gMlxuIE4gLSAxID0gNSAgICAgICAgLS0tPiA2XG4yTiArIDEgPSAzICAgICAgICAtLS0+IDEgXG4yTiArIDEgPSA0ICAgICAgICAtLS0+IDIiXQ==) if it wasn't for rounding.
## Explained
```
โNx*\=/ฦโqh.1+แน
โNx* # Replace all N with x
\=/ # split on equal sign
ฦโq # and solve the equation for x. Yes. There's a built in for it.
h.1+ # add 0.1 to the result to account for the fact that python seems to round down if <= 0.5 instead of < 0.5
แน # round the answer as required
```
[Answer]
# [Scala 3](https://www.scala-lang.org/), 168 bytes
```
import java.lang._
import scala.util.chaining._
val c:String=>Int=_.split("N|=").pipe(a=>(new Float(a(2))-new Float(a(1)))/new Float(a(0))).pipe(x=>math.round(x).toInt)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bY5BTsMwEEX3PcUoK49QDGlBQkiOxAapi3bDGlWD61JXrm0lkzZS4SRssgFxBY7CbTBJFxWwGv3358-f1_dak6NJ9xkeN0YzzMh6MC0bv6zhNkY4vDW8yq-_Puw2hophQzuSjvyTXIyOqD8hG7ZO6nXK297ckQN9c89VkqqcelYLWUdnWWTzZ5WhjDYaQaoU3uzhzgViQWKMmJ_qAhHPT8FFAkO0VeWWeC2r0PilaFFySC14_PcBIKZqdl5okRXzs0JNMsTRL5wX6uoPHv-_3ePLH_wylHTdML8B)
[Answer]
# [Matlab], 91 bytes
this is the most resilient version.
assuming that s is the input string.
```
syms N;v=str2double(regexp(s,'(?<!\d)(\d)+(?!\d)','match'));round(solve(v(1)*N+v(2)==v(3)))
```
# [Matlab], 74 bytes
```
syms N;round(solve(str2double(s(1))*N+str2double(s(4))==str2double(s(6))))
```
but doesnt really work if for example Y was 2 digits (ie 10). I'll try to improve it a bit.
# [Matlab], 29 bytes
if the input was just the numbers and not a string
```
sym N;round(solve(d*N+Y==X))
```
[Answer]
# [Convex](https://github.com/GamrCorps/Convex), 19 bytes
```
S-ยฎ-?\d+"รด:d~\-\/mo
```
[Try it online!](https://tio.run/##S87PK0ut@P8/WPfQOl37mBRtpcNbrFLqYnRj9HPz////r2Tkp6CtYKhgq2CiBAA "Convex โ Try It Online")
[Answer]
# PHP, 45 bytes
```
<?=round((($s=$argn)[3].$s[5]-$s[9])/-$s[0]);
```
Run with `echo '<input>' | php -nF <filename>` or [Try it online](https://tio.run/##K8go@P/fxr4go4BLJbEoPU/BVkHd0E9BW8EQyDJWt1bQ11fwLy0pKC1RMNLjAnKQVemCVZmiqDJDVWWE3SxDHKpM0G20t@Oysbctyi/NS9HQ0FAptgXr0Yw2jtVTKY42jdUFkpaxmvog2iBW05rr/38A).
This requires that `d` always be given, and that the string is the same length each time, e.g.:
* `N + 1 = 3` *won't* work, but `1N + 1 = 3` *will* work.
* `1N +1 =3` *won't* work, but `1N + 1 = 3` *will* work.
[Answer]
# J, 26 Bytes
```
<.({.%~{:-1&{)".>0 2 4{cut
```
Note that the result for N is floored (not rounded), so for the last test case it returns 1 instead of 2. If this is unacceptable I will change the answer.
Input should be of the form `'d N +-Y = X'`
### Explanation:
```
cut '10 N +2 = 23' NB. Split on whitespace
โโโโฌโโฌโโโฌโโฌโโโ
โ10โNโ+2โ=โ23โ
โโโโดโโดโโโดโโดโโโ
0 2 4{cut '10 N +2 = 23' NB. Choose relevant portions
โโโโฌโโโฌโโโ
โ10โ+2โ23โ
โโโโดโโโดโโโ
".>0 2 4{cut '10 N +2 = 23' NB. Eval each
10 2 23
({.%~{:-1&{)".>0 2 4{cut'10 N +2 = 23' NB. Compute (x-y)/d
2.1
<.({.%~{:-1&{)".>0 2 4{cut'10 N +2 = 23' NB. Floor
2
```
[Answer]
## C# (149 Bytes)
```
s=>(int)Math.Round(((s=s.Replace(" ",""))[s.Length-1]-48-((s.Contains("-")?-1:1)*(s.Split(new[]{'+','-'})[1][0]-48)))/(decimal)(s[0]=='N'?1:s[0]-48))
```
Craptacular bloated C# solution. Guess I could've ported the Java solution but I try not to look at others' stuff before posting mine, so here we are.
[Try it Online](https://tio.run/##jY4xT8MwEIXn@FecvMSmcSBQJNSQdkBiaivUDqiKMhjHSi0lTpRzQKjqbw9uRQcW4C2ne/fd3VMoVNvrcUBjK9h@otNNSoKTSDe81UaBqiUivPRt1cuGHEjw7aOTzpf31pSwksYyTgI/DZ4Hqx7R9f5gBMa6OewggxGzOfMdX0m3jzftYEvGGGYYb3RXS6UZBRpRynmO8VLbyu1FUojpg/BU/NRa518go4LyhUhmCb/y9rarjWNWf@TFIZyEUSjCI8@TIr85bXLOr1mplWlkzRl6M8vCdbhIZngBxjQgcJb/gG2t49feOL00VrMdo2uYQOLD3/lY6e@gOIP3f4G3P07Cv9DpBT2S4/gF "Try it Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 66 bytes
```
->s{a,_,b,_,c=s.split.map &:to_f;((s[?+]?c-b:c+b)/(a+0**a)).round}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664OlEnXicJiJNti/WKC3IyS/RyEwsU1KxK8uPTrDU0iqPttWPtk3WTrJK1kzT1NRK1DbS0EjU19YryS/NSav8XKKRFK/kpaCsYKtgqGCvFckEFdMECpjABIwwlcBETpdj/AA "Ruby โ Try It Online")
[Answer]
# awk, 48 bytes
```
awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'
```
Use cases:
```
echo "N + 1 = 3" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'
echo "N - 1 = 5" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'
echo "2N + 1 = 3" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'
echo "2N + 1 = 4" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'
```
Extra case:
```
echo "3N + 1 = 11" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'
```
Output: 3
[Answer]
## PHP, 83 Bytes
[Try it online](https://tio.run/##K8go@G9jX5BRoKCSWJReZqtk5KegrWCoYKtgomRtbweUsy3KL81L0dBQSbZNrSjIyU9J1VBSUNIBK9fUjDaJ1QVKRRvG6gFJo1hNTX0Q1yDW1tbP3tCquDSpuKQIIqJjoKNrqKlp/f8/AA)
[Try it online2](https://tio.run/##K8go@G9jX5BRoKCSWJReZqtk5KegrWCoYKtgomRtbweUsy3KL81L0dDQUEm2Ta0oyMlPSdVQUlDSAavX1Iw2idUFSkUbxuoBSaNYTU19ENcg1tbWz97Qqrg0qbikCCKiY6Cja6ipqWOgaf3/PwA)
For some reason **`round`** does not round to the closest integer on tio run, on this version the solution has some extra bytes **(87 Bytes)**
**Code**
```
<?=round(($c=explode(" ",$argv))[4]-($c[1].$c[2]))/($c[0]==N?1:substr($c[0],0,-1));
```
**Explanation**
```
//ecuation structure xN sign c = m
//array structure like ["xN","sign", "c", "=", "m"]
round( //round the result
( //first element of the ecuation
$c=explode(" ",$argv))[4] //explode the string and get the 4th value
- //substract, php accepts (1-(-1)) so,
//it can ve solved like this
($c[1].$c[2]) //concat the sign with c
)
/ //divide by x
($c[0]==N?1:substr($c[0],0,-1) //if the first element xN it's N
//divide by 1, else remove N and divide
);
```
**Question**
About negative numbers, my code should work for an equation like `-xN +- c = m`, but when you are considering a `x = -1`, the input will be `-N +- c = m` or `-1N +- c = m`?
[Answer]
# [R](https://www.r-project.org/), 90 bytes
```
-round(eval(parse(t=gsub("=","-",gsub("\\dN","",s<-scan(,"")))))/(gsub("N.*$","",s):1)[1])
```
[Try it online!](https://tio.run/##K/r/X7covzQvRSO1LDFHoyCxqDhVo8Q2vbg0SUPJVklHSVdJB8KJiUnxA/KVdIptdIuTE/M0gGxNENDXgCjw09NSgSjQtDLUjDaM1fyvZOGnoK1gqWCrYKLE9R8A "R โ Try It Online")
Assumes `d` is present as per the spec.
Probably not the shortest option - I am sure there are better regex.
[Answer]
`awk` : safe division without branching ternary condition
```
echo 'N + 1 = 3' |
gawk '$__=sprintf("%.f",($5-($2$3))/(_+=$_)^!!_)'
mawk '{printf("%.f",($5-($2$3))/(_+=$_)^!!_)}'
```
---
```
2
```
---
```
echo '2N + 1 = 4' |
nawk '$!NF=sprintf("%.f",($5-($2$3))/(_+=$!_)^!!_)'
```
---
```
2
```
] |
[Question]
[
I just started reading about [friendly numbers](http://en.wikipedia.org/wiki/Friendly_number) and I think they sound great.
>
> In number theory, **friendly numbers** are two or more natural numbers with a common **abundancy**, the ratio between the sum of divisors of a number and the number itself. Two numbers with the same abundancy form a **friendly pair**; *n* numbers with the same abundancy form a **friendly *n*-tuple**.
>
>
>
So, how small a program can you write to output a list of the first 20 friendly numbers.
Assuming I've understood everything I've read correctly the output of your program should be:
```
6,28
30,140
80,200
40,224
12,234
84,270
66,308
78,364
102,476
6,496
28,496
114,532
240,600
138,644
120,672
150,700
174,812
135,819
186,868
864,936
222,1036
246,1148
```
I'd also like to add that the program must calculate the answers and not use any external resources or hard coded answers (thanks Peter).
[Answer]
## APL (50)
```
โโ,/{g/โจ{=/{โตรทโจ+/z/โจ0=โต|โจzโโณโต}ยจโต}ยจgโโตโ.,โณโต-1}ยจโณ936
```
The list is slightly different but [oeis.org](http://oeis.org/A050972) [agrees with me.](http://oeis.org/A050973)
Output:
```
28 6
140 30
200 80
224 40
234 12
270 84
308 66
364 78
476 102
496 6
496 28
532 114
600 240
644 138
672 120
700 150
812 174
819 135
868 186
936 864
```
[Answer]
# Ruby, 90 characters
```
h={}
1.upto(1150){|n|s=0
1.upto(n){|x|s+=x if n%x<1}
r=s/n.to_r
p [h[r],n] if h[r]
h[r]=n}
```
[Answer]
# C (132)
```
x=1,e;float d(a,b){return b?1.f*(a%b==0)*b/a+d(a,--b):0;}main(){while(x<1148)for(e=x++;--e;)d(x,x)-d(e,e)||(printf("%d,%d\n",e,x));}
```
Thanks to shiona for the ideas on shorter code.
And Felix Eve for the Code(counting down makes more sense if you only search pairs).
With the added Pairs even shorter.
Readable Version:
```
x=1,e;
float d(a,b)
{
return b?1.f*(a%b==0)*b/a+d(a,--b):0;
}
main()
{
while(x<1148)
for(e=x++;--e;)
d(x,x)-d(e,e)||(printf("%d,%d\n",e,x));
}
```
[Answer]
# Mathematica ~~114 112 99~~ 90
**Numbers having same abundancy.** (90 chars)
This displays integers with a common abundancy. Notice that 6, 28, and 496 have the same abundancy, which means that (6,28), (6,496) and (28, 496) are friendly number pairs. Likewise, 84, 270, 1488, 1638 have the same abundancy.
Because, as Peter Taylor noted, there is no method suggested for total ordering, it is unclear which pairs constitute the "first 20" friendly number pairs.
```
Grid@Cases[GatherBy[{k, 1~DivisorSigma~k/k}~Table~{k, 2000}, Last], x_ /; Length@x > 1
:> x[[All, 1]]]
```

[Answer]
## Mathematica ~~62~~ ~~58~~ 55
```
Grid@Cases[GatherBy[Range[6!],Tr@Divisors@#/#&],{_,__}]
6 28 496
12 234
30 140
40 224
66 308
78 364
80 200
84 270
102 476
114 532
120 672
138 644
150 700
240 600
```
You may go up to `9!` without affecting the char count
[Answer]
Using awk (303, uncompressed)
```
awk 'BEGIN{for (i=1;i<=1150;i++)
{ for (j=1;j<=int(i/2);j++)
if (i%j=="0") a[i]+=j
v=sprintf("%.10f",(a[i]+i)/i)
#print v,i
b[v]=b[v] FS i
}
for (i in b) {l=split(b[i],x,FS);if (l>1) print b[i]}}' file|sort -n
6 28 496
12 234
30 140
40 224
66 308
78 364
80 200
84 270
102 476
114 532
120 672
135 819
138 644
150 700
174 812
186 868
222 1036
240 600
246 1148
864 936
```
[Answer]
## C - 188
I assume someone will do this with a language that supports literal newlines and requires less boilerplate.
```
main(){puts("6,28\n30,140\n80,200\n40,224\n12,234\n84,270\n66,308\n78,364\n102,476\n114,532\n240,600\n138,644\n120,672\n150,700\n174,812\n135,819\n186,868\n864,936\n222,1036\n246,1148");}
```
[Answer]
# PHP - 260
```
$x=1;while($i<20){$d=0;$y=$x;for($y=$x;$y>0;$y--){if($x%$y==0)$d+=$y;}$f=$d/$x.'';$s[$f][]=$x;if(count($s[$f])>1) {$i++;if(count($s[$f])>2){$o[]=$s[$f][0].','.$s[$f][2];$o[]=$s[$f][1].','.$s[$f][2];}else $o[]=implode(',',$s[$f]);}$x++;}echo implode('<br>',$o);
```
Uncompressed:
```
$x=1;
$o = array();
while($i<20) {
$d = 0;
$y = $x;
for($y=$x;$y>0;$y--) {
if($x%$y==0) $d += $y;
}
$f = $d / $x.' ';
$s[$f][] = $x;
if(count($s[$f])>1) {
$i++;
if(count($s[$f])>2) {
$o[] = $s[$f][0].','.$s[$f][2];
$o[] = $s[$f][1].','.$s[$f][2];
} else {
$o[] = implode(',', $s[$f]);
}
}
$x++;
}
echo implode('<br>', $o);
```
This answer is longer than my other answer but works properly (doesn't skip any numbers and only has 2 numbers per row) so I'm more happy with this one.
[Answer]
C#: 208
```
public class A{static double D(int n){return 1f*Enumerable.Range(1,n).Where(i=>n%i==0).Sum()/n;}static void Main(){for(int j,i=1;i++<865;)for(j=1;j++<1000;)if(A.D(i)==A.D(j)&&i<j)Console.WriteLine(i+" "+j);}}
```
] |
[Question]
[
United States senators are sorted into [three classes](https://en.wikipedia.org/wiki/Classes_of_United_States_senators), based on what year their six-year term starts. Since each state has two senators, each state has a senator in two of the three classes.
Given a full state name and a class number (1, 2, or 3), output truthy if that state has a senator of that class, and falsey if that state does not have a senator of that class.
States with Class 1 senators:
>
> Arizona, California, Connecticut, Delaware, Florida, Hawaii, Indiana, Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana, Nebraska, Nevada, New Jersey, New Mexico, New York, North Dakota, Ohio, Pennsylvania, Rhode Island, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia, Wisconsin, Wyoming
>
>
>
States with Class 2 senators:
>
> Alabama, Alaska, Arkansas, Colorado, Delaware, Georgia, Idaho, Illinois, Iowa, Kansas, Kentucky, Louisiana, Maine, Massachusetts, Michigan, Minnesota, Mississippi, Montana, Nebraska, New Hampshire, New Jersey, New Mexico, North Carolina, Oklahoma, Oregon, Rhode Island, South Carolina, South Dakota, Tennessee, Texas, Virginia, West Virginia, Wyoming
>
>
>
States with Class 3 senators:
>
> Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana, Maryland, Missouri, Nevada, New Hampshire, New York, North Carolina, North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, South Carolina, South Dakota, Utah, Vermont, Washington, Wisconsin
>
>
>
### Test Cases
```
"Rhode Island", 1 -> true
"Rhode Island", 2 -> true
"Rhode Island", 3 -> false
"California", 1 -> true
"California", 2 -> false
"California", 3 -> true
"South Dakota", 1 -> false
"South Dakota", 2 -> true
"South Dakota", 3 -> true
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~67~~ 63 bytes
```
lambda s,l:0x764d5443a33628366/3**(hash(s)%4560%1502%43)%3+1!=l
```
[Try it online!](https://tio.run/##XZJfb9owEMDf@RTeQwR0SAMS2ITEw0S1lbWUqt1WTV0fjsSQU4wP@ZxC9uWZYyetNsmSf@f7f75DZXPS4/N2/vusYL/JQPBAzYanj9MkmyRJDHE8HX@Kp9MP8cVFLwfOe9yPksl0GI0mw3GUxP0ofj96N1dntmAli7l46n5WsIE9dAeiRi4CGfxDusECNAPXvACFWzIavWZBigxkFFhrmVpMS1uLl1LBEYys@Yuzwsx7fJVkdsH5yukRa1pmkPsYS6VQE/pMS50hhAKWdPT39WsZ11LbMi2qmm@oRG5NV4BaBjCVAp0FZoY0L1la691XmOa4Ax3Y1c1kgzsy1@dwwFak0gQmbZskt3Jj2jndyhfIGjqKK9gfOMfQdv3wTRqWVSut5AlTaqVfZArPZGwuFmDIdQ9vL5dQNGWtc/Re60K5SYWvWhu5I9/BndSaK/UCza/c55RJseS2/Qcq/4sfXt7if5f1DFjKIJzCkH9YyOv7pzR717xHdL/XpHl064V6Z0MRj5Kt@EeNnJJmDNqK9s62@9zpuO0RKFALA3one6OBSPqzjhAHg9q6NXIbyCLKxIPUYMnwrCsiga8GT35xRR0lkIvU7DJuxbbneYD959bj/Bc "Python 2 โ Try It Online")
The states can be sorted into three disjoint categories, based on what class of senators they don't have. `hash(s)%4560%1502%43` generates a number \$0 \le k \le 42 \$ without mixing up the categories. This number is then used to get a single base-3 digit out of `0x764d5443a33628366`.
[Answer]
# JavaScript (ES6), ~~98 ... 83~~ 79 bytes
A regex solution.
Returns a non-zero value if the state has a senator of the given class.
```
s=>n=>n^=/Oh|gt|N.*D|t$|yl|[UYfv]|[Wdir]i/.test(s)?2:/^I|[ACGHKLOS]/.test(s)||3
```
[Try it online!](https://tio.run/##jZJRb9owEMff@yksNAkydaDCWys6IdBKRiHTug5VjErXxCTXGB@yHWimfHfmxEk79rJKlvy7O9/fd/Y9wx50qHBnPkmK@HEzPOrhtbTrcdgLkiI2xaL7cVKYD0UuitX9w2a/LlbLCNUae13Dtelo73P/svfoF6vR@GY6uw3u1q@RohgcR2zIVq2RgCfYQuuclahTRwp/k6wxBalBlzwGgRtSEqvImAQpiMixlDw0GGamNCdcwAEUL/mLPYVRlXHDScUueWrjiCX5ESSVhi8ESsLqJl9GCK4Anw7VPnstY8alycI0L/mWMtTN0Tmg5A5ULkBGjrWGMMk0N6ZKn2OYYAzSsa1bk3HpqHW5djtsTMqUY5KmvmTBn1TzTgu@h6imA5vCdqcTdG2Xjq9caZ431py/YEiN9UAqrZiUSdgYFNnu4c0zgbQuK0iwygpSYV/KfVWgeExVB9@4lDoXe6h/5Xtix4X5umn/jrJ/9J3nTf8HL99Ac@6MF/fI9waScv/J1dY2XyHa36uvWYLtVMbGFbG0U8VOwqhDkhpdNKetPdtaX52dlV4SvCso7rTHduA0u7hse1eMsb9Do@4GheGqo9nwmm3sxHYuPK/7TCg77XPW9rxTpV/SafUrrf8o9d@jNHiP0uBU6fgH "JavaScript (Node.js) โ Try It Online")
### How?
The first regular expression matches the states with **class 1** and **class 3** senators:
```
pattern | states
------------+---------------------------------------------------------------------------
Oh | Ohio
gt | Washington
N.*D | North Dakota
t$ | Connecticut, Vermont
yl | Maryland, Pennsylvania
[UYfv] | California, Nevada, New York, (Pennsylvania), Utah
[Wdir]i | Arizona, Florida, Hawaii, Indiana, Missouri, Wisconsin
```
The second regular expression matches the states with **class 2** and **class 3** senators:
```
pattern | states
------------+---------------------------------------------------------------------------
^I | Idaho, Illinois, (Indiana1), Iowa
[ACGHKLOS] | Alabama, Alaska, (Arizona1), Arkansas, (California1), Colorado,
| (Connecticut1), Georgia, (Hawaii1), Kansas, Kentucky, Louisiana,
| New Hampshire, North Carolina, (Ohio1), Oklahoma, Oregon, South Carolina,
| South Dakota
```
*1: These states belong to the first group. But if they've already been identified as such by the first regular expression, this one will not be executed anyway.*
The states with **class 1** and **class 2** senators are matched by neither of them:
```
Maine, Nebraska, Massachusetts, Michigan, Delaware, Minnesota, New Jersey, Tennessee,
West Virginia, Mississippi, Virginia, Wyoming, Montana, Rhode Island, New Mexico, Texas
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 79 bytes
Returns a non-zero value if the state has a senator of the given class.
```
s=>n=>0x3A27C2823007F077n.toString(3)[parseInt(s[8]+5+s,35)%462%255%113%56]^~-n
```
[Try it online!](https://tio.run/##jZLbbtpAEIbv8xSrSAhbIQjsEqJGICGiNDQlVE3bqKJUmtiLPbHZQTtrDr3oq1PbazelN41kab@Z2fl3Dn6GDXCgcW3OFYXysBwceDBUg2Fn54@8/ti79PxOp3/T6fdV29CD0agix3fna9AsJ8o4PL9cnPXOuOX33MabC6/h9XqNbtdv9C4WP36dq8NIDMT8dJTCE6zgtCUK5MSSxp@kKkxAMXDBY0hxSVphGRlTShpCsqyUDAwGmSnMa5nCFrQs@Ca/hWGZ8U6SjmzybR5HLGgSQlxqTNIUFWH50kSFCLaACW3L8@5PGXdSmSxI9gV/oAy5vjoFVNKC3qegQsvMEMQZS2PK9CkGMUagLOd1MxmbjszFt15jbVKmLZMy1SP38knXc7qXGwgr2opbWK05Rtt24Xgv813sa2sqdxhQbX0jnZRM2sRiDJry7uHFcw1JVdYsxjJrlqT5pOyqZlpGVHbwUSrF@3QD1VY@xfnvIiZct/9A2T/61vOi/1kWM2AprbGzQ/5iIC7Or1Kv8uZLxHx71TOPkHeqImOLeJRsxFEYOSDFaKN7WuV3TxdXJyeFl1LZTilymuP8h2PRfdt0r4QQf4dG7SWmRmqHxWAolg67Ttd128@Eymm2RNN1j5W@K6vllVr/UfJeo@S/Rsk/Vjr8Bg "JavaScript (Node.js) โ Try It Online")
The method used to transform the input string is similar to the one [described in my answer](https://codegolf.stackexchange.com/a/204553/58563) to [this related challenge](https://codegolf.stackexchange.com/q/75125/58563). Its purpose is to solve the 3 problems we have in JS:
* no built-in hash function
* `parseInt()` breaks on non-alphanumeric characters
* only 52 bits of mantissa for Numbers (i.e. 2 distinct strings sharing the same prefix may be parsed the same way)
] |
[Question]
[
Given a necklace with color stones (yellow, white, brown, etc.) of at least two different colors, we describe that necklace using letters that correspond to each color, choosing an arbitrary starting point.
We try to answer these questions:
* How many distinct colors does the necklace have?
* What's the length of the longest segment of contiguous stones of the same color?
* If necklace can be cut at any position, removing all contiguous stones of the same color immediately to the left and to the right of the cutting point, what's the biggest amount of stones which could be taken?
Note that the necklace is considered cyclical. Therefore, letters at the start and end of the given input string can form a single sequence (see second test case below).
### Test cases
```
aaaab -> 2 4 5
aabaa -> 2 4 5
uamaaauumaummuauamumummmmua -> 3 4 5
```
What's the shortest code to achieve this? Any language is welcome.
[Answer]
# Pyth, 20 bytes
```
l{zeSJhCr+zz8eS+VJtJ
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=l%7BzeSJhCr%2Bzz8eS%2BVJtJ&input=uamaaauumaummuauamumummmmua&debug=0)
### Explanation
```
implicit: z = input string
{z set of z
l len and print
+zz z + z (because cyclic)
r 8 run-length-encoding
hC zip and only use the first column (quantities)
J store in J
S sort
e take the maximal element and print
+V vectorized add of
JtJ J and J[1:]
eS sort and print maximal element
```
[Answer]
# CJam, 28 bytes
```
r__&,a\2*e`0f=_2ew::+]::e>S*
```
[Try it online.](http://cjam.aditsu.net/#code=r__%26%2Ca%5C2*e%600f%3D_2ew%3A%3A%2B%5D%3A%3Ae%3ES*&input=uamaaauumaummuauamumummmmua)
### How it works
```
r e# Read a whitespace-separated token from STDIN.
__ e# Push two copies.
& e# Intersect two of the copies (removes duplicates).
,a e# Calculate the length and wrap it in an array.
\ e# Swap the array with the input string.
2* e# Repeat the input string two times.
e` e# Perform run-length encoding.
0f= e# Keep only the repetitions.
_2ew e# Copy and push the overlapping slices of length two.
::+ e# Add the integers in the resulting slices.
] e# Wrap the entire stack in an array.
::e> e# Compute the maximum of each of the three arrays.
S* e# Join, separating by spaces.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 90 bytes
-2 bytes thanks to [Sสจษ ษ an](https://codegolf.stackexchange.com/users/92689/s%ca%a8%c9%a0%c9%a0an)
```
->a{[(a&a*=2).size,(c=a.slice_when{_1!=_2}.map &:size).max,c.each_cons(2).map(&:sum).max]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3o3TtEqujNRLVErVsjTT1ijOrUnU0km0T9YpzMpNT48szUvOq4w0VbeONavVyEwsU1KxASjSB7AqdZL3UxOSM-OT8vGINI5BQgQZQujQXLBtbC7VBt0DBLVqpNDE3MTGxtDQ3sTQ3tzQRyC0FwlwQW0kvOSOxqDhWryQ_PhGiacECCA0A)
[Answer]
# Haskell, ~~141~~ 137 bytes
```
import Data.List
l=length
m=maximum
v#w=l$v$group w
f n=(l$nub n,m$map l$group n,m[last#take i n+head#drop i n|i<-[1..l n-1]])
p n=f$n++n
```
Usage example:
```
*Main> map p ["aaaab","aabaa","uamaaauumaummuauamumummmmua"]
[(2,4,5),(2,4,5),(3,4,5)]
```
How it works: Like the other answers I deal with the cycle by working on the input string concatenated to itself.
* distinct colors: length of the list where duplicates are removed
* longest segment of the same color: group consecutive colors, get length of each group, take maximum
* split and take left and right segments: for each index `i`: split into left and right part at `i`, group consecutive colors in each part, add length of the last group of the left part and length of first group of the right part. Take maximum of the sums.
[Answer]
## JavaScript (ES6), ~~203~~ 199 bytes
Credit goes to [this answer on Code Review SE](https://codereview.stackexchange.com/a/83718/21165) for the array unique function.
```
f=w=>{for(x=Math.max,z=[],o=[[...w+=w].filter((x,p)=>w.search(x)==p).length],i=w.length-(c=1);i;)c=(w[i]!=w[--i]?(z.push(c)&0):c)+1;o.push(x.apply(0,z),x.apply(0,z.map((v,i)=>v+=z[i+1]|0)));return o}
```
### Demo
ES6, so Firefox only for now.
```
f = w => {
for (x = Math.max, z = [], o = [
[...w += w].filter((x, p) => w.search(x) == p).length
], i = w.length - (c = 1); i;)
c = (w[i] != w[--i] ? (z.push(c) & 0) : c) + 1;
o.push(x.apply(0, z), x.apply(0, z.map((v, i) => v += z[i + 1] | 0)));
return o
}
// DEMO
console.log = x => document.body.innerHTML += x + "<br>";
console.log(f('aaaab'));
console.log(f('aabaa'));
console.log(f('uamaaauumaummuauamumummmmua'));
```
[Answer]
# [Perl 5](https://www.perl.org/) `-n`, 96 bytes
```
$_.=$_;@k{/./g}++;/(.)\1+(.)\2+/;say for 0+keys%k,length$&,(sort{$b-$a}map y///c,/((.)\2+)/g)[0]
```
[Try it online!](https://tio.run/##JctLDsIgFEDRrTBAU8LnUZOOGhM34ArUNLRUNK1AgAlpunWxjWdwZ9ePYW5KwZ044669TAsIMCulLVSC3Gu690ShjSqjpwtI0mnM8TCxebQmvfCRVdGFtOCeY7V@lEcZAAYG1f8kYMhNPkpRm36j9bDT@ut8ejsbC782QtaycPsD "Perl 5 โ Try It Online")
Changed the output order:
```
Number of unique colors
Longest after cutting
Longest contiguous string of one color
```
[Answer]
# [Python 2](https://docs.python.org/2/), 124 bytes
```
from itertools import*
I=input()*2
r=[len(list(g))for _,g in groupby(I)]
print len(set(I)),max(r),max(map(sum,zip(r,r[1:])))
```
[Try it online!](https://tio.run/##JU5LCoMwEN3nFLNLIm5qdwUP4BlEymijDThJGDOgvbyNLW/xvouXjvyOoTmn@HLQgtb6nDkS@Ow4x7hu4ClFzpXqWh@SZGOrRnHbry6Y1W/ZLNbOkeFZL@ADLBwljYfp7KAS@5DhGm4ul8TWhLvhPxEmswnVH58M19zfHoO19iwHlHK7m@B6VN1PLUiIKEIoRILFSgFdWitdKhx/PCLqLw "Python 2 โ Try It Online")
] |
[Question]
[
You are given a certain number of cups (`n`). You are tasked with stacking these cups into a pyramid, with each row having one more cup than the row above it. The number you are given may or may not be able to be perfectly stacked. You must write a function that takes the total number of cups (`n`), and returns the following values. `t`, which is the total number of cups in the pyramid, and `b`, which is the number of cups on the bottom row. Your answer must be returned in the format of a string, as `b,t`.
* `n` is a randomly generated, positive, finite, whole number.
* `b` and `t` must also be positive, finite, and whole.
* You may not use any libraries that aren't already built into your language of choice.
* The pyramid is two dimensional, so instead of expanding out, it is linear, with each row adding only a single cup more than the last, instead of one with a square or triangular base.
In some potential cases:
* If `n=4`, `b=2` and `t=3`.
* If `n=13`, `b=4` and `t=10`.
* If `n=5000`, `b=99` and `t=4950`.
A verbose example in JavaScript:
```
var pyramid = function(n){
var i;
var t = 0;
var b;
for(i=0;i<=(n-t);i++){
t += i;
b = i;
}
console.log(b + ',' + t);
}
```
And a tiny example too:
`p=function(n){for(t=i=0;i<=(n-t);i++){t+=i;b=i}return b+','+t}`
Good luck!
[Answer]
# Haskell, 64 ~~68~~
This works out the base directly by inverting the triangular number formula, `t = (b^2+b)/2`, and calculating `b = (sqrt(8*t+1) - 1) / 2`.
```
f n=init.tail$show(b,div(b^2+b)2)where b=floor$(sqrt(8*n+1)-1)/2
```
And rather than constructing the string-based answer as `show b++","++show t`, it simply chops the brackets off the shown tuple.
Edit: calculating the new triangular number in place instead of declaring a new variable, `t`, saves 4 characters.
[Answer]
# [GNU dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 25 bytes
dc does not really have functions, but the closest thing is a macro. This defines a macro which is stored in register `m`. This pops the input `n` from the top of the stack (idiomatic for dc), and prints `b,t` to stdout as per the spec:
```
# 25 byte macro definition
[8*1+v1-2/ddn44P1+*2/p]sm
# Some test cases
4 lmx
9 lmx
10 lmx
11 lmx
13 lmx
5000 lmx
```
### Output:
```
$ dc 2dpyr.dc
2,3
3,6
4,10
4,10
4,10
99,4950
$
```
### Explanation:
This uses the same inverse of the triangle function used in some of the other numbers. The triangle number `n` for base length `b` is given by:
```
n = b(b+1)/2
```
Rearranging into a quadratic in terms of `b`:
```
bยฒ + b - 2n = 0
```
Plugging the coefficients {A=1, B=1, C=-2} into the [quadratic formula](http://en.wikipedia.org/wiki/Quadratic_formula) gives:
```
b = (-(1) ยฑ sqrt((1)ยฒ-4(1)(-2n))) / 2(1)
b = (-(1) ยฑ sqrt(1+8n)) / 2
```
This translates to `dc` as follows:
```
[ # Start a macro definition
8* # Push 8 to the stack and multiply by n
# (n is assumed to be next value on the stack)
1+ # Push 1 to the stack and add to 8n
v # Take the square root
1- # Push 1 to the stack and subtract from the square root
2/ # Push 2 to the stack and divide to get the value of `b`
dd # Duplicate top of stack twice (value of `b`)
n # Pop top of stack and print value of with no newline
44P # Push ASCII value of ',' (comma) and print with no newline
1+ # Push 1 to the stack and add 1 to `b`
* # Multiply b by (b+1)
2/ # Push 2 the stack and divide to get the value of `t`
p # Print value of `t` with a newline
] # End macro definition
sm # Store macro in `m` register
```
Note the quadratic formula introduces a ยฑ, but the + root always gives us the answer we need.
Note also that `dc`'s default precision is 0 decimal places, and positive numbers are always rounded down to the nearest whole number, which is exactly the rounding we need.
[Answer]
# ES6 41
This is based on the comperendinous' formula:
**Edit:** Thanks to edc65's suggestions:
```
p=n=>''+[b=~-Math.sqrt(8*n+1)>>1,b++*b/2]
```
[Answer]
# Java
It's pretty simple to find triangle numbers. Here are three ways in Java, all under 90 chars, including a loopless version:
### 67
```
String x(int n){int t=0,b=0;for(;b<=n-t;t+=b++);return(b-1)+","+t;}
```
### 78
```
String y(int n){int b=1,t=1;for(;t<=n*2;t=b*b+b++);return(--b-1)+","+(t/2-b);}
```
### 89
```
String z(int n){int b=(int)Math.sqrt(n*2),t=(b*b+b)/2;return(t>n?b-1:b)+","+(t>n?t-b:t);}
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 29
```
DAbKJ0W>b+JK~K1~JK)R++`K","`J
```
If the output format `b, t` instead of `b,t` is OK, then it's 28 characters:
```
DAbKJ0W>b+JK~K1~JK)R:`,KJ1_1
```
If `(b, t)` is OK, it's 23 characters:
```
DAbKJ0W>b+JK~K1~JK)R,KJ
```
Explanation:
```
def A(b):
K=J=0
while gt(b,plus(J,K)):
K+=1
J+=K
return plus(plus(repr(K),","),repr(J))
```
Test run - (input, output):
```
DAbKJ0W>b+JK~K1~JK)R++`K","`Jj"\n"m,dAdL11
(0, '0,0')
(1, '1,1')
(2, '1,1')
(3, '2,3')
(4, '2,3')
(5, '2,3')
(6, '3,6')
(7, '3,6')
(8, '3,6')
(9, '3,6')
(10, '4,10')
```
[Answer]
# Javascript ES6 - 39 41 43
Thought I'd try some recursion in hopes that it'd be smaller than the for loop.
```
f=(n,b=0,t=0)=>(n>b)?f(n-++b,b,t+b):b+','+t
```
Tried to shrink it by calculating the total rather than passing it but ended up the same length
```
f=(n,b=0)=>(n>b)?f(n-++b,b):b+','+(b+b*b)/2
```
**Edit**: Dropped another 2 with core1024's suggestion
```
f=(n,b=0,t=0)=>n>b?f(n-++b,b,t+b):b+','+t
```
**Edit**: In principal, I agree with edc65 about the 'right' answer and almost didn't try to a recursive loop assuming it would be have to be longer. So I hate to take his improvement, but I will :) Nice spy there!
```
f=(n,b=0)=>n>b?f(n-++b,b):b+','+b++*b/2
```
[Answer]
# JavaScript (ES6) โ 47
```
p=n=>{for(t=i=0;i+t<n;)t+=i++;return i-1+','+t}
```
For now only works on Firefox. The following works on any recent browser at **55 bytes**:
```
p=function(n){for(t=i=0;i+t<n;)t+=i++;return i-1+','+t}
```
This is derived from the example provided by the OP.
[Answer]
## PHP 145
```
<?$n=$argv[1];for($b=ceil($n/2);$b>0;$b--){for($k=$b-1;$k>0;$k--){$v=array_sum(range($k,$b));if($v>$n)continue 2;if($v==$n){echo "$b,$k";exit;}}}
```
Expanded:
```
<?
$n=$argv[1];
for($b=ceil($n/2);$b>0;$b--){
for($k=$b-1;$k>0;$k--){
$v=array_sum(range($k,$b));
if($v>$n)continue 2;
if($v==$n){
echo "$b,$k";
exit;
}
}
}
```
[Answer]
**PYTHON: 76**
```
def r(x,b,t):
x-=b+1
return r(x,b+1,t+b) if x>=0 else str(b)+','+str(t+b)
```
] |
[Question]
[
For this challenge, you must accept input as a comma-separated list (columns) of a run (rows) of the first letters of any of the colors `red`, `orange`, `yellow`, `green`, `blue`, or `purple`, and output (to stdout) the HTML for a table of those colors.
This is fairly hard to understand, so I'll just give a simple example.
Input:
```
rgb,gbr,grb
```
Output (with example screenshot):
```
<html>
<head>
</head>
<body>
<table>
<tbody>
<tr>
<td style="background-color: red" width="50" height="50"></td>
<td style="background-color: green" width="50" height="50"></td>
<td style="background-color: blue" width="50" height="50"></td>
</tr>
<tr>
<td style="background-color: green" width="50" height="50"></td>
<td style="background-color: blue" width="50" height="50"></td>
<td style="background-color: red" width="50" height="50"></td>
</tr>
<tr>
<td style="background-color: green" width="50" height="50"></td>
<td style="background-color: red" width="50" height="50"></td>
<td style="background-color: blue" width="50" height="50"></td>
</tr>
</tbody>
</table>
</body>
</html>
```

Note that the HTML you output need not be valid; it just has to work. By "work", I mean that your output will be pasted into a `.html` file and viewed in the latest (currently, 9/28/13) Chrome (v 29.0.1547.76). The squares must be 50 pixels width and height. You may have whatever padding between them as you want (Chrome automatically uses 1 pixel of padding, even when you specify `padding: 0px`, so I can't control that).
Input will always be valid (letters will be one of `roygbp`), but the rows are not guaranteed to have equal amounts of squares in them. For example, `roygbp,ooo` is valid and should output

This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins.
[Answer]
# Perl: ~~153~~ ~~126~~ ~~124~~ ~~116~~ 114 characters
```
s!\w!'<td bgcolor=#'.substr(ff00f90707,yrbxoxgp=~$&&&@-[0],3).' width=50 height=50>'!ge;s!,!<tr>!g;$_="<table>$_"
```
Sample run:
```
bash-4.1$ perl -p table.pl <<< 'rgb,oyp'
<table><td bgcolor=#f00 width=50 height=50><td bgcolor=#070 width=50 height=50><td bgcolor=#00f width=50 height=50><tr><td bgcolor=#f90 width=50 height=50><td bgcolor=#ff0 width=50 height=50><td bgcolor=#707 width=50 height=50>
```
Sample output:
```
bash-4.1$ perl -p table.pl <<< 'yrryyryyryyyrrr,ryyyryryryyyryy,ryryryryryyyrry,yrryyryyrrryryy'
```

[Answer]
## Razor Leaf, 136
```
table for r in prompt().split(",")
tr for x in r
td bgcolor:"##{"rf00of90yff0g070b00fp707".match(x+"(...)")[1]}"width:"50"height:"50"
```
[Razor Leaf](https://github.com/charmander/razorleaf). The indentation is tabs, by the way.
You might have some trouble running this in a browser, so try Node.js and define `global.prompt` to return a fixed output. :)
```
var fs = require("fs");
var razorleaf = require("razorleaf");
global.prompt = function() {
return "rgb,byp";
};
console.log(razorleaf.compile(fs.readFileSync("test.leaf", "utf-8"))());
```
Using other peopleโs tricks is 126, but thatโs no good.
```
table cellpadding:"26"for r in prompt().split(",")
tr for x in r
td bgcolor:"##{"rf00rof90oyff0yg070gb00fbp707".split(x)[1]}"
```
[Answer]
# Mathematica ~~148~~ 139
```
d_~f~n_:=Export[n,Grid@ToExpression@Characters@d/.{r->Red,o->Orange,y->Yellow,g->Green,
b->Blue,p->Purple}/.{x_RGBColor:>Graphics@{x,Rectangle[]}}]
```
---
`f`, defined above, is a simple function that takes the color strings as input and outputs an HTML file.
**Usage**
```
f[{"rgb","gbr","grb"}, "ColorfulTable.html"]
```
The HTML code that is output to file "ColorfulTable.html":
```
< ?xml version="1.0" encoding="UTF-8"?>
< ! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN"
"HTMLFiles/xhtml-math11-f.dtd" >
< ! --Created by Wolfram Mathematica 9.0 : www.wolfram.com-- >
< html xmlns = "http://www.w3.org/1999/xhtml" >
< head >
< title > Untitled
< /title >
< link href = "HTMLFiles/ColorfulTable.css" rel = "stylesheet" type = "text/css"/ >
< /head >
< body >
< p class = "Output" >
< img src = "HTMLFiles/ColorfulTable.gif" alt = "ColorfulTable.gif" width = "360" height = "360"
style = "vertical-align:middle"/ >
< /p >
< div style = "font-family:Helvetica; font-size:11px; width:100%; border:1px none #999999; border-top-style:solid; padding-top:2px; margin-top:20px;" >
< a href = "http://www.wolfram.com/products/mathematica/" style = "color:#000; text-decoration:none;" >
< img src = "HTMLFiles/spikeyIcon.png" alt = "Spikey" width = "20" height = "21" style = "padding-right:2px; border:0px solid white; vertical-align:middle;"/ >
< span style = "color:#555555" > Created with < /span > Wolfram < span style = "font-style: italic;" > Mathematica < /span > 9.0
< /a >
< /div >
< /body >
< /html >
```
**HTML rendering in Chrome**

[Answer]
# JavaScript, ~~203~~ 146
```
for(h='<table cellpadding=26>',p=prompt(),i=0;c=p[i++];)
h+=","==c?"<tr>":'<td bgcolor=#'+'rF00roFA0oyFF0yg080gb00Fbp808'.split(c)[1]+'>';
alert(h)
```
Credit to @C5H8NNaO4 for the single loop & cellpadding ideas. I'm using a split string to find the right color. (the line breaks were added for readability)
Input:
```
rgb,bgroyp
```
Output:
```
<table cellpadding=26><td bgcolor=#F00><td bgcolor=#080><td bgcolor=#00F><tr><td bgcolor=#00F><td bgcolor=#080><td bgcolor=#F00><td bgcolor=#FA0><td bgcolor=#FF0><td bgcolor=#808>
```
[Here's the JSFiddle](http://jsfiddle.net/33qpU/4/)
Does anyone know how to use unicode characters in JSFiddle? I could shave a few more characters off, but some characters wouldn't paste in correctly.
[Answer]
## GolfScript, ~~154~~ ~~144~~ 119
```
'<table><tr>'\{:^44='<tr>'{"<td bgcolor="['red''orange''yellow''green''blue''purple']{0=^=}?" width=50 height=50>"}if}%
```
[Online test](http://golfscript.apphb.com/?c=OyJyZ2IsZ2JyLGdyYiIKJzx0YWJsZT48dHI%2BJ1x7Ol40ND0nPHRyPid7Ijx0ZCBiZ2NvbG9yPSJbJ3JlZCcnb3JhbmdlJyd5ZWxsb3cnJ2dyZWVuJydibHVlJydwdXJwbGUnXXswPV49fT8iIHdpZHRoPTUwIGhlaWdodD01MD4ifWlmfSU%3D)
With credit to @bendytree for introducing the no-close-tags trend which allowed me to cut 25 chars.
[Answer]
# Python 3 (158)
```
print('<table>',*['<tr>'+''.join('<td width=50 height=50 bgcolor=#%03x>'%dict(r=3840,o=3984,y=4080,g=96,b=15,p=1799)[c]for c in r)for r in input().split(',')])
```
Cool things:
* This uses the `*` operator to pass multiple arguments to `print`, saving 6 characters compared to `''.join`.
* The colors are stored in decimal, then rendered as hex in the HTML. I found this to be much shorter than using string literals directly.
[Answer]
# ECMAScript 6: 148 characters
```
alert('<table>'+prompt().replace(/./g,x=>x==','?'<tr>':'<td bgcolor='+'red green orange yellow blue purple'.match(x+'\\w+')+' width=50 height=50>'))
```
(Just to exercise the fat arrow syntax.)
[Answer]
# Javascript, ~~199~~ ~~183~~ ~~173~~ ~~171~~ ~~167~~ ~~164~~ ~~159~~ ~~158~~ 154
```
h="<table cellpadding=26>";p=prompt();for(i=0;c=p[i++];)h+=","==c?"<tr>":'<td bgcolor=#'+{r:"F00",o:"FA0",y:"FF0",g:"080",b:"00F",p:"808"}[c]+'>';alert(h)
```
*just realized i don't need an opening `<tr>` tag*
*stupid me, i of course do **not** need to split the input string to access single chars*
*... as well as i of course do not need to initialise `c`*
*inlined the lookup object*
*you can actually leave out the px for width and height*
*changed width and height to cellpadding 26px*
*replaced `</tr>` with `<tr>`*
*removed the `'` around 26 at the cellpadding and from the bgcolor*
*Changin the `for` to a `for .. in` loop would save only one character, so i keep the for*
[Example Output](http://jsfiddle.net/CcQEz/5) for `roygbp,ooo`
```
<table cellpadding=26><td bgcolor=#F00><td bgcolor=#FA0><td bgcolor=#FF0><td bgcolor=#080><td bgcolor=#00F><td bgcolor=#808><tr><td bgcolor=#FA0><td bgcolor=#FA0><td bgcolor=#FA0>
```

[Answer]
## PHP, ~~182~~ ~~164~~ 163 characters
Example input:
```
<?php $x = 'roygbp,ooo'; ?>
```
*Update 1; if you silence (or just ignore) E\_NOTICE you can remove the quotes around strings that start with letters, shaving off another 18 characters*
*Update 2; trimmed 1 character!*
```
<?php echo'<table cellpadding=50><tr>';$a=[r=>f00,g=>'080',b=>blue,o=>fa0,p=>'808',y=>ff0];foreach(str_split($x)as$b){echo$b==','?'<tr>':"<td bgcolor=#$a[$b]>";}?>
```
[Answer]
## PHP, 277 characters
```
<style>div div{display:inline-block;width:50px;height:50px}<?foreach(array(red,orange,yellow,green,blue,purple)as$c){echo".$c[0]{background-color:$c}";}?></style><?foreach(split(",",fgets(STDIN))as$r){?><div><?foreach(str_split($r)as$c)echo"<div class='$c'></div>"?></div><?}?>
```
Input:
```
rgb,bgr,gbr
```
Output:
```
<style>div div{display:inline-block;width:50px;height:50px}.r{background-color:red}.o{background-color:orange}.y{background-color:yellow}.g{background-color:green}.b{background-color:blue}.p{background-color:purple}</style><div><div class='r'></div><div class='g'></div><div class='b'></div></div><div><div class='b'></div><div class='g'></div><div class='r'></div></div><div><div class='g'></div><div class='b'></div><div class='r'></div></div>
```
Hmmm... the stylesheet is killing me here. I don't have time now, but I'll come back to have a look at this later.
And yes, I'm deliberately not using tables for layout. ;-)
[Answer]
# Python 2.7 (176)
```
I=raw_input().split(",")
h="<table>"
c=dict(r=3840,o=3984,y=4080,g=96,b=15,p=1799)
for r in I:
h+="<tr>"
for x in r:h+="<td width=50 height=50 bgcolor='#%03x'>"%c[x]
print h
```
I pinched the use of dict and the insertion of Hex values from @Lambda Fairy
And for good measure, here is a [jsfiddle with an example output](http://jsfiddle.net/WZkwM/)
[Answer]
# Ruby, ~~221~~ 187
I am presenting my own solution first, as always:
```
$><<'<table>'+gets.chop.split(?,).map{|r|'<tr>'+r.chars.map{|t|"<td bgcolor=#{'red green orange yellow blue purple'.match(t+'\w+')[0]} width=50 height=50></td>"}*''+'</tr>'}*''+'</table>'
```
] |
[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 8 years ago.
[Improve this question](/posts/11261/edit)
You've probably heard of the classic Eight Queens Puzzle. For those of you who haven't it goes something like this:
>
> Position 8 queens on an 8ร8 chessboard so that no two queens threaten
> each other (no two queens appear on the same row, column or diagonal
> as each other).
>
>
>
Here is one answer that is very close:
```
X - - - - - - -
- - - - X - - -
- X - - - - - -
- - - - - X - -
- - X - - - - -
- - - - - - X -
- - - X - - - -
- - - - - - - X
```
As you can see, two queens appear on the long diagonal between the top left corner and the bottom right corner.
Your task is to solve the Eight Queens Puzzle (using any programming language) in a unique or obfuscated manner. The first answer to 15 up-votes wins (the number may be subject to change depending on the popularity of this question).
Your output must be like the example above (empty squares represented by `-`, queens represented by `X` and a space between each `X` or `-`). Good luck!!
[Answer]
# Mathematica
The following implementation challenges the player to find one or more solutions to the eight queens problem. (It was too easy to simply have the program output the answers.)
Clicking on any of the squares in the chessboard toggles between "queen" and .
When `show attacks` is checked, any attacks between queens are highlighted.
The following picture `queenImg`.

In the board below, no queen attacks another:

Placing a fourth queen on a conflicting square results in two reciprocal attacks.

The following is one of the solutions.

```
DynamicModule[{qns = ConstantArray[0, {8, 8}]},
Manipulate[
ClickPane[
Dynamic[ArrayPlot[
Array[Boole[(Mod[#1, 2] == 0 \[And]
Mod[#2, 2] == 0) \[Or] (Mod[#1, 2] == 1 \[And]
Mod[#2, 2] == 1)] &, {w, w}],
ColorRules -> {1 -> White, 0 -> LightBrown}, Mesh -> True,
Epilog -> {Red, Thickness[.005],
If[attacks,
Line[Cases[
Tally@Flatten[z[##] & /@ (Reverse /@ Position[qns, 1]),
1], {a_, n_} /; n > 1][[All, 1]]], {}],
Table[Inset[queenImg, p, Automatic, 10/w], {p,
Position[qns, 1] - .5}]}]], (qns = flip[qns, Ceiling@#]) &],
{{attacks, True, "show attacks"}, {True, False}},
Initialization -> (w = 8;
z[{r_, c_}] := {row[r], col[c], diag1[r, c], diag2[r, c]};
row[r_] := {{0, r - .5}, {8, r - .5}};
col[c_] := {{c - .5, 0}, {c - .5, 8}};
diag1[r_, c_] := {{0, r - c}, {8 - (r - c), 8}};
diag2[r_, c_] := {{0, c + r - 1}, {c + r - 1, 0}};
flip[a_, pos_] := MapAt[(# - 1)^2 &, a, pos])]]
```
[Answer]
# dc
```
[sSdlS*]sw[d252-lwx26482+lwx1504824-lwx50051569+lwx982283196-lwx10821394332+lwx58071763728-lwx99637122816+]sa10 0:d0[laxd*453%;d1100.8*11552+P1+d8%;dPd64>s]dssx
```
Also at 160 characters it's decently short.
[Answer]
# **Ruby >=1.9**
```
queens = %w[Anne-Marie Mary Elizabeth Victoria Maleficent Gertrude Alexandra Latifa]
SQUARES_ON_A_CHESSBOARD = 64
queens.permutation.find do |succession|
i = SQUARES_ON_A_CHESSBOARD
[-1,1].map{ |m| succession.map{ |queen| queens.index(queen) + m*i+=1}}.map(&:uniq).map(&:size).inject(&:*) == SQUARES_ON_A_CHESSBOARD
end.each do |queen|
r=queens.map{queens[SQUARES_ON_A_CHESSBOARD & 1][SQUARES_ON_A_CHESSBOARD % 10]}
r[queens.index(queen)]=(queens*SQUARES_ON_A_CHESSBOARD.to_s)[SQUARES_ON_A_CHESSBOARD]
puts r.join(" ").upcase
end
```
Outputs one solution in the required format.
[Answer]
### Ruby
```
Q=8;$><<[*0...Q].permutation.select{|u|u.each_with_index.map{|a,b|[a-b,a+b]}.transpose.map{|z|z.uniq.size}==[Q,Q]}.map{|s|s.map{|f|(["-"]*(Q-1)+["X"]).rotate(f)*"\040"}*$/}*($/*2)
```
A not so much obfuscated but unique code - it contains function uniq ;-) but not a single whitespace! Prints all solutions to console. Maybe I'll start to obfuscate it somehow.
[Answer]
## Haskell
```
import Data.List
import Control.Monad
import Control.Applicative
q8 = (sequence_ . (<$> (head.(foldM.flip.const)
(\_' -> join<$>sequence [(:[])<$>(((\_''-> [_''|
foldr (\(_''',_')->( (((==)<*>(\\[0,_''',-_''']))[_''-_']) &&))
(((/=)<*>((\\)>>=id)) [_']) $ zip [1..] _'])<$>[1..8])>>=id),
[_'] ]) [] $ [1..8])))
(\_' -> putStrLn$concat$replicate(_'-1)" -"++[" X"]++replicate(8-_')" -")
```
Output:
```
- - - X - - - -
- X - - - - - -
- - - - - - X -
- - X - - - - -
- - - - - X - -
- - - - - - - X
- - - - X - - -
X - - - - - - -
```
[Answer]
Here is my solution in Python. This outputs every possible solution to the problem.
```
from itertools import permutations
def board(vector):
print ("\n".join('- ' * i + 'X ' + '- ' * (8-i-1) for i in vector) + "\n\n= = = = = = = =\n")
cols = range(8)
for vector in permutations(cols):
if 8 == len(set(vector[i]+i for i in cols)) \
== len(set(vector[i]-i for i in cols)):
board (vector)
```
Here is a short sample of the output.
```
X - - - - - - -
- - - - X - - -
- - - - - - - X
- - - - - X - -
- - X - - - - -
- - - - - - X -
- X - - - - - -
- - - X - - - -
= = = = = = = =
X - - - - - - -
- - - - - X - -
- - - - - - - X
- - X - - - - -
- - - - - - X -
- - - X - - - -
- X - - - - - -
- - - - X - - -
= = = = = = = =
X - - - - - - -
- - - - - - X -
- - - X - - - -
- - - - - X - -
- - - - - - - X
- X - - - - - -
- - - - X - - -
- - X - - - - -
```
[Answer]
# k
Relatively trivial solutions, For 32 characters:
```
-1'"-X"@0b\:'0x1002200140088004;
```
Slightly better (more painful to read than obfuscated):
```
((-).*:'(c;i))'@'[(*i)#,:(*i)#10h$45i;2/:'i#(*/(i:8 4))_0b\:*/c:7 129790099;:;10h$88i];
```
[Answer]
## Q
Obfuscation through hideousness
```
nq:{
f:{[]
b:.[;;:;"X"]/[-1_'16 cut 128#"- ";flip (til 8;2*neg[8]?8)];
v:{"X" in (x[;first where y="X"] each (til 8) except z)}[b]'[b;til 8];
d:{"X" in x ./:{$[null r:1+last where raze (1#'x)=7;enlist -1 -1;x til r]}raze 1_{x,/:y}'[rotate[z;til 8];flip@[;(first where y="X")]@/:((+;neg@-)@\:2*til 8)]}[b]'[b;til 8];
e:{"X" in x ./:{$[null r:1+last where raze (1#'x)=0;enlist -1 -1;x til r]}raze 1_{x,/:y}'[reverse rotate[z+1;til 8];flip@[;(first where y="X")]@/:((+;neg@-)@\:2*til 8)]}[b]'[b;til 8];
(not any v,d,e;b)};
while[not first q:f[];];
-1 last q;
}
```
.
```
q)nq[]
- - - X - - - -
- - - - - - - X
- - - - X - - -
- - X - - - - -
X - - - - - - -
- - - - - - X -
- X - - - - - -
- - - - - X - -
```
[Answer]
**Python, Obfuscation through Complexity**
Though you would see magic numbers in my code, they are not the hard-coded solution. On running the code, you would get the list of all possible positions of the queens
```
from itertools import*
from math import*
def foo():
def bar(x):
k1,k2,k4 = 6148914691236517205L,3689348814741910323L,1085102592571150095L
x = ((x >> 1) & k1) | ((x & k1) << 1)
x = ((x >> 2) & k2) | ((x & k2) << 2)
x = ((x >> 4) & k4) | ((x & k4) << 4)
return x
op = [(9259542123273814144L,4,1,0),(9241421688590303745L,7,1,8),(9241421688590303745L,7,-1,-8)]
for o in op:
d=o[0]
m=18446744073709551615L
for n in range(o[1]):
yield d
yield bar(d)&18446744073709551615L
m=(m<<o[3] if o[3]>0 else m>>-o[3])&18446744073709551615L
d=(d>>o[2] if o[2]>0 else d<<-o[2])&(m)
for e in (int(''.join("{0:08b}".format(n) for n in p),2) for p in permutations((2**n for n in range(8)),8)):
if all((round(log(m & e)/log(2),8)).is_integer() for m in foo() if m&e):
print '\n'.join(''.join(e) for e in zip(*[iter("{0:064b}".format(e))]*8))
print '-'*8
```
[Answer]
# โดScript (rhoScript)
You wanted obfuscated, well...
```
๏ฟฝ๏ฟฝห o๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ}๏ฟฝ๏ฟฝ๏ฟฝe๏ฟฝ๏ฟฝ๏ฟฝ
```
Hexdump, for obvious reasons:
```
00000000: a991 cba0 6f87 c1fb e97d 82c1 cd65 e2f8 ....o....}...e..
00000010: 90
```
In less-obfuscated form:
```
8 range permutations
(with-index
(sum) map uniq arg-a with-index
(*exploding subtract) map uniq concatenate length)
keep-maxes-by
```
Yeah, I don't really know what it does either.
] |
[Question]
[
Convert JSON (key/value pairs) to two native arrays, one array of keys and another of values, in your language.
```
var X = '{"a":"a","b":"b","c":"c","d":"d","e":"e","f":"f9","g":"g2","h":"h1"}';
```
The value array could be an array of strings or integers.
So we need two functions **keys** & **vals**, returning native arrays on input of JSON string.
In above example the output would be:
```
keys : ["a", "b", "c", "d", "e", "f", "g", "h"]
vals : ["a", "b", "c", "d", "e", "f9", "g2", "h1"]
```
Here is my attempt at this using javascript:
**keys** : (53 Chars)
```
function keys(X){return X.match(/[a-z0-9]+(?=":)/gi)}
```
**vals** : (56 Chars)
```
function vals(X){return X.match(/[a-z0-9]+(?="[,}])/gi)}
```
Can other languages challenge this??
[Answer]
### Python, 27/30
To actually comply with the rules:
```
keys=lambda x:list(eval(x))
vals=lambda x:eval(x).values()
```
### Python, 30
Just using one function:
```
lambda x:zip(*eval(x).items())
```
This will separate the keys from the values and return them in a list.
### Python, 7
If returning a dictionary is allowed, then this is all you need:
```
eval(x)
```
[Answer]
## APL 32
Index origin 1. If you will accept the keys and values being returned as a two row array then a simple one liner will do the job in APL. This takes screen input via โรรชโรงรป
```
โรงรข((.5โรณโรงยฅj),2)โรงยฅjโรรช(~jโร รค'{":;,}')โรครjโรรชโรงรป
```
Taking the given example as input:
```
{"a":"a","b":"b","c":"c","d":"d","e":"e","f":"f9","g":"g2","h":"h1"};
a b c d e f g h
a b c d e f9 g2 h1
```
[Answer]
## Perl 28 bytes
Instead of 2 separate functions to return keys and values, I'm returning both in the form of a `hash`.
```
sub j2h{eval pop=~y/:"/,/dr}
```
Sample usage:
```
$_='{"a":"a","b":"b","c":"c","d":"d","e":"e","f":"f9","g":"g2","h":"h1"}';
%h=j2h($_);
print $h{f}; # prints f9
print $h{g}; # prints g2
```
It even works for arbitrarily deeply nested variables:
```
$_='{"a":{"b":{"c":"c3","d":"d4"},"c":"c5"},"b":"b6"}';
%h=j2h($_);
print $h{a}{b}{d}; # prints d4
print $h{a}{c}; # prints c5
```
[Answer]
# Tcl 69,69
first attempt 132 keys+vals
```
proc j {x n} {
regsub -all {(".*?"):(".*?")} $x "\[lappend o \\$n\]" x
subst $x
set o $o
}
proc keys x {j $x 1}
proc vals x {j $x 2}
```
second try 69 keys, 69 values
```
proc keys x {regsub -all {(".*?"):(".*?").} $x {\1 } x
lindex $x\} 0}
proc vals x {regsub -all {(".*?"):(".*?").} $x {\2 } x
lindex $x\} 0}
```
[Answer]
# K, 22
```
{+`$":"\:'","\:1_-1_x}
```
The double quotes in the input string have to be escaped
```
k){+`$":"\:'","\:1_-1_x} "{\"a\":\"a\",\"b\":\"b\",\"c\":\"c\",\"d\":\"d\",\"e\":\"e\",\"f\":\"f9\",\"g\":\"g2\",\"h\":\"h1\"}"
"a" "b" "c" "d" "e" "f" "g" "h"
"a" "b" "c" "d" "e" "f9" "g2" "h1"
```
For the same bytecount you could just read from stdin
```
+`$":"\:'","\:1_-1_0:0
```
.
```
k)+`$":"\:'","\:1_-1_0:0
{"a":"a","b":"b","c":"c","d":"d","e":"e","f":"f9","g":"g2","h":"h1"}
"a" "b" "c" "d" "e" "f" "g" "h"
"a" "b" "c" "d" "e" "f9" "g2" "h1"
```
[Answer]
## PHP, 56/58
Pssh, PHP has functions for this stuff (although it won't win the shortest answer award).
```
function keys($j){return array_keys(json_decode($j,1));}
function vals($j){return array_values(json_decode($j,1));}
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function. Prints list of keys, then returns list of values.
```
'โรงรฉยฌยฎโรฉรฏโรรชโรฉรฏNLยฌร2'โรงรฉโรงยฎโรฉรฏJSON
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X/1Rb9@hFY/6pj5qmwAk/XwOrTcCiT3qBQl6Bfv7/U8DSQFF@qZ6@j/qaj603vhR20QgLzjIGUiGeHgG/09Tr1ZKVLICYh2lJCCdBKSTgXQykE4B0ilAOhVIpwLpNCCdZglkpAMZ6UZARgaQkWGoVKsOAA "APL (Dyalog Unicode) โรรฌ Try It Online")
`โรฉรฏJSON`โรรconvert JSON string to APL namespace object
`'`โรยถ`'โรงรฉโรงยฎ`โรรin that namespace, execute the following code:
โรร`โรฉรฏNLยฌร2`โรรname list for all all variables
โรร`โรฉรฏโรรช`โรรprint that list
โรร`โรงรฉยฌยฎ`โรรexecute each name
[Answer]
# PowerShell, ~~34/36~~ 28/28 bytes
-14 bytes total thanks to @mazzy!
To fetch the keys:
```
&(gcm *F*son)"$args" -a|% k*
```
[Try it online!](https://tio.run/##DcZBDkAwFEXRrTQ/KA0DZizAPtqqNlEqOjDA2r83uDn3TLe7cnAxMle1t7tQs8rpaKjQl88kOv2WYlPMLB/SNKGWDDTQQgsXuEAHHVzhOmI8xg@YgAk9ffIH "PowerShell โรรฌ Try It Online")
To fetch the values:
```
&(gcm *F*son)"$args" -a|% v*
```
[Try it online!](https://tio.run/##DcZBDkAwFEXRrTQ/KA0DZizAPtqqdlAqmjDA2r83uDn3SLc7c3AxMle1t5tQs8ppb6jQp88kOv2W4lLMLB/SNKGWDDTQQgsXuEAHHVzhOmI8xg@YgAk9ffIH "PowerShell โรรฌ Try It Online")
Kinda cheap, as it uses the built-in method `ConvertFrom-Json -AsHashtable` to convert the data from JSON.
[Answer]
# ECMAScript
I'm surprised no one has proposed a better ECMAScript solution, so here's my simple attempt:
**keys**: (29 chars)
```
X=>Object.keys(JSON.parse(X))
```
**values**: (31 chars)
```
X=>Object.values(JSON.parse(X))
```
[Answer]
# [jq](https://stedolan.github.io/jq/), 11โรรฌโร รป bytes
[Try it online!](https://tio.run/##Fck7CoAwEEXRrcjUQdDObCWkyD@ojQQFkaxdr8W8c2HW432fLd1N/6OGy@1natqMxtrOS5xoTolHjwEDRoyYMGHGvBCFKDNRiTpJ/wA)
This answer will take some refining, as I'm not yet clear on the rules. It states that two functions are required, but jq doesn't have functions and I don't know how much of our current meta consensus applies to such old posts
The essence is in two snippets:
* keys: `keys`
* values: `[.[]]`
These are both valid jq programs that each give their respective piece. Counted like this we have 11 bytes. We can also do:
```
# Return an array of arrays as [keys, values]
[keys, [.[]]]
```
```
# Return another nice JSON as {"keys": keys, "values": values}
{keys:keys, values:[.[]]}
```
I'll add a bit more explanation when the final entry is clearer.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 103 bytes
```
char*b[99],**o,*l;f(s,n)char*s;{for(o=b;*s++;l=*s-34?l:++n%4?s+1:(*o++=strndup(l,s-l)));*o=0;return b;}
```
[Try it online!](https://tio.run/##hZBda4MwFIbv/RUhMJYPBdv1onqQ/o1BKUVTP8KyWIx2DPGvz504KZQxdq6e8@Y9eZOjolqpeVZN3onimCSnUIg2FAYq5kLLF93BWLUda7MChJMSTCZc9LI7mFRK@7Q7OLlJmWilzFzf2ctwZSZ0keGcg2izGLqyHzpLCphmbXvynmvLeDAGBMsHEG2vQ3/cx/EJFrEue8cWkUOwKIiO0bfy06WUw31SCOI1kpHqxx@S7XqMLyZs9Wg0eB8QoYFoKfliuV8s9GPOLTdD@SsJ1Yek@I8k7/s/aV1KDME033AHrzj5PNKcpjTf0JAWCIUHhaA8XBAuHsozfgab8oxR2FfIVYKFXCPXW4QGodnQ6UtVJq/dHH18Aw "C (gcc) โรรฌ Try It Online")
Usage:
`f(input, 2)` returns an array with the keys
`f(input, 0)` returns an array with the values
# [C (clang)](http://clang.llvm.org/), 67 bytes
```
*l;f(*s,n){for(;*s++;l=*s-34?l:++n%4?s+1:printf("%.*ls\n",s-l,l));}
```
Writes the output to stdout instead of returning arrays.
[Try it online!](https://tio.run/##bY9BTsMwEEX3OYVlFNV2kqot3RBTegEOgERQ5Tp2YmHcKk6KUJSrE9yxugAxi9G8rz/2H1lIK1wzz8xyTZjPHR31qSOc@Szjdsd8cb/d2zLLXLrd@2xdnjvjek1wumTWVw7nvrC5pZRP851x0g61Qo@@r81p2T4lvyRrjlctCQ@gD2EcocmYoFBXwbjz0L@@oR16xhfRoZcwLcYKiwqXoa8rnFf4CHCMIAFkhBqgjqAO7@oLBHW4CAuaBtYPoYAb4GYD0AK0YXtaYA6ZbndCrpAljdfGnJQn0TT0nmAWfvOsxDRuagKeHG3@2EKUQf1nXN2MneqHzqEVT6b5W2orGj8Xnz8 "C (clang) โรรฌ Try It Online")
[Answer]
## **Ruby, 19**
`eval X.gsub':','=>'`
Similar, unsurprisingly, to the Perl solution. The Ruby 1.9 literal for a `Hash` would be identical to the input form if it weren't for the quoted keys; as it is we just need to convert the colons to `=>`.
[Answer]
# CoffeeScript:
```
vals = []
keys = []
vals.push(v) and keys.push(k) for own k, v of JSON.parse(X)
```
[Answer]
# Lua
```
function keys(x)return loadstring("return"..x:gsub(':".-"',''))()end
function vals(x)return loadstring("return"..x:gsub('"[^"]*":',''))()end
```
68 and 71 chars
[Answer]
## Tcl 8.6, 82
```
package r json;lmap keys [dict k [set d [json::json2dict $X]]] vals [dict v $d] {}
```
The Tcl core is (unlike php) very small.
This requires the tcllib, which is available as package for most linux distributions.
I use this library because too much languages have a json\_parse build in.
[Answer]
# [PHP 7.4+](https://www.php.net/), 39/41 bytes
([demo](https://3v4l.org/b7nDL))
The keys via closure with PHP7.4 arrow function syntax: 39 bytes
```
(fn()=>array_keys(json_decode($X,1)))()
```
The values via closure with PHP7.4 arrow function syntax: 41 bytes
```
(fn()=>array_values(json_decode($X,1)))()
```
[Answer]
**Python 3 (Total 35 characters)**
*Input JSON String*
```
X = '{"a":"a","b":"b","c":"c","d":"d","e":"e","f":"f9","g":"g2","h":"h1"}'
```
**Get Keys(16 characters)**
```
k=eval(X).keys()
```
**Get Values(18 characters)**
```
v=eval(X).values()
```
[Try online](https://tio.run/##PchNCoAgGIThfacQNylEUK0KukdbrS8No6IfQaKz20DQYnheZgunXZcqdqxl6c0Vb7CMa6hhD3s4wAESJDjCsUYYhCkRFmEL/qTRteTVLDqZOwqHkIn/D3ARrrjt03IKJ5MvvIwv)
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 12 bytes
```
'";;:an2cou[
```
[Try it online!](https://tio.run/##DcYxDoAgEAXRq5BtaGikE@I9TKxgWaAwGjVUxrOvv5i8yePe5bmGqFqKMaTD8zk21dUsxr6UKCBHGWbIkGGBBQoUWGGdMQ3TPKZj@kSf/QE "Burlesque โรรฌ Try It Online")
```
'";; # Split by "s
:an # Filter by alphanumeric
2co # Group in pairs
u[ # Unzip giving array of vals and array of keys
```
] |
[Question]
[
Write a program which accepts a sentence into stdin, and writes that sentence to stdout in pig latin.
Here are some test cases which your program should handle:
```
Input:
Read your script
Output:
ead-Ray our-yay ipt-scray
```
Hyphenation is mandatory. Note that multiple consonants at the start of the word must all be moved to the end. Capitalization of the output does not matter; `Ead-ray` or `ead-ray` are also valid translations of `Read`
```
Input:
An utterance is allowed an opening vowel
Output:
An-way utterance-way is-way allowed-way an-way opening-way owel-vay
```
Words starting with vowels have `-way` appended in their pig latin form (don't forget to handle capital opening vowels)
```
Input:
sky
-skyay
```
Words consisting entirely of consonants should have a hyphen prepended, and `ay` appended
Punctuation is undefined; I don't care if leading or trailing punctuation ends up inside the pig latin word.
This is code golf; the shortest program by character count wins. I've written a solution myself which handles all these cases which I shall post as a response.
[Answer]
## Python, 89
```
import re
print re.sub('-a','-wa',re.sub('(?i)([^aeiou ]*)(\w*)',r'\2-\1ay',raw_input()))
```
[Answer]
## Perl, 41 excluding switches
A simple modification of [Timwi's answer](https://codegolf.stackexchange.com/questions/8797/ode-cay-olf-gay/8908#8908). Runs with `perl -p`. Does not meet the spec for 'sky', but the original doesn't either.
```
s/(\S*?)([aeiou]\S*)/"$2-".($1||w).ay/ige
```
[Answer]
# Perl (53)
```
s/(.*?)([aeiou].*)/$1||=w;print"$2-$1ay "/iefor split
```
[Answer]
## Perl (60)
Use `perl -n`. The -n switch is counted (as two characters).
```
s/(.*?)([aeiou].*)/print"$2-$1"."w"x!$1."ay "/iefor split
```
[Answer]
### Python - ~~122~~ 85 characters
```
import re
print re.sub("-a","-wa",re.sub("([^aeiou ]*)(\w*)",r"\2-\1ay",raw_input()))
```
122 -> 85: Improved use of regexes; running regex on whole sentence rather than individual words, and doing all the processing with regexes rather than a conditional expression. This ended up making it pretty similar to grc's answer
[Answer]
**Cojure - 376 characters**
Obviously not winning this one, but figured I'd take a shot at it.
Minified:
```
(defn n [a b] (reduce #(and % %2) (map #(= (.indexOf a %) -1) (map string/lower-case (rest b)))))
(defn t [a] (let [vowels ["a" "e" "i" "o" "u"] x "ay"] (if (> (.indexOf vowels (string/lower-case (first a))) -1) (str a "-way") (if (n vowels a) (str a x) (str (reduce str (rest a)) "-" (first a) x)))))
(defn ay-ya [a] (reduce str (map #(str (t %) " ") (string/split a #" "))))
```
Actual:
```
(defn no-vowel [a b]
(reduce #(and % %2) (map #(= (.indexOf a %) -1) (map string/lower-case (rest b)))))
(defn transform [text]
(let [vowels ["a" "e" "i" "o" "u"]]
(if (> (.indexOf vowels (string/lower-case (first text))) -1)
(str text "-way")
(if (no-vowel vowels text)
(str text "ay")
(str (reduce str (rest text)) "-" (first text) "ay")))))
(defn ay-ya [text]
(reduce str
(map #(str (transform %) " ")
(clojure.string/split text #" "))))
```
[Answer]
# [Perl 6](http://perl6.org), ~~78~~ 66 bytes
```
put get.words.map: {samecase S:i/(.*?)(<[aeiou]>.*)|(.*)/$1-{~$0||'w'}ay/, $_}
put get.words.map: {~S:i/(.*?)(<[aeiou]>.*)|(.*)/$1-{~$0||'w'}ay/}
```
( You would use the `samecase` one if you cared about capitalization )
```
$ perl6 -e 'put get.words.map: {~S:i/(.*?)(<[aeiou]>.*)|(.*)/$1-{~$0||"w"}ay/}'
Read your script
ead-Ray our-yay ipt-scray
$ perl6 -e 'put get.words.map: {~S:i/(.*?)(<[aeiou]>.*)|(.*)/$1-{~$0||"w"}ay/}'
An utterance is allowed an opening vowel
An-way utterance-way is-way allowed-way an-way opening-way owel-vay
$ perl6 -e 'put get.words.map: {~S:i/(.*?)(<[aeiou]>.*)|(.*)/$1-{~$0||"w"}ay/}'
sky
-skyay
```
[Answer]
## K, 95
```
" "/:{$[&/~x in v:v,_v:"AEIOU";"-",x,"ay";("-"/:|_[;x]0,*&t),$[*t:x in v;"way";"ay"]]}'" "\:0:0
```
[Answer]
## Clojure - 113 chars
```
(clojure.string/replace(read-line)#"([^aeiouAEIOU ]*)(\w*)"(fn[[a c r]](if(=""a)""(str r"-"(if(=""c)\w c)"ay"))))
```
[Answer]
**Ruby 1.9, 68**
```
puts ARGV.map{|w|w[/^([^aeiou]+)(.*)/i]?$2+"-"+$1+"ay":w+"-way"}*" "
```
[Answer]
# C, 134 bytes
```
char w[99],*p;c;main(l){for(;c^10;c=getchar())scanf("%s",w),p=strpbrk(w,"aeiouAEIOU"),l=p-w,printf("%s-%.*say ",p?p:"",l+!l,l?w:"w");}
```
[Answer]
# [Lexurgy](https://www.lexurgy.com/sc), 116 bytes
```
p:
([]+)$1 *=>$1 \-way/$ {a,e,i,o,u} _
({b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z}+)$1 ([]*)$2 => $2 \- $1 ay/$ _
```
+52 bytes if you want case-insensitive support.
] |
[Question]
[
The program must print the following block of text of LED numbers exactly.
```
+-----------------------------------------------------------------+
| |
| 000 1 222 333 4 4 555 666 777 888 999 AAA B CCC D EEE FFF |
| 0 0 1 2 3 4 4 5 6 7 8 8 9 9 A A B C D E F |
| 0 0 1 222 333 444 555 666 7 888 999 AAA BBB C DDD EEE FFF |
| 0 0 1 2 3 4 5 6 6 7 8 8 9 A A B B C D D E F |
| 000 1 222 333 4 555 666 7 888 999 A A BBB CCC DDD EEE F |
| |
+-----------------------------------------------------------------+
```
Notice the 1-char padding inside the borders.
The trailing newlines, and the types of the newlines are not significant.
However, the whitespaces are the spaces you get when you press spacebars (ASCII 32).
Shortest code wins. Using data encoding (base64, gzip), or compressing with other Unicode characters is discouraged. You cannot use programs like `cat` or `gzip` since they are not programming languages.
The character count *must* be less than 600 to qualify.
[Answer]
## Golfscript, 142 137 chars
Unfortunately some of the characters are control codes, so I'm going to have to post a hexdump and a link rather than a direct copy of the source:
```
00000000 27 2b 27 3a 28 27 2d 27 36 35 2a 3a 5e 28 6e 27 |'+':('-'65*:^(n'|
00000010 7c 27 3a 29 27 20 27 3a 7c 36 34 2a 3a 40 27 20 ||':)' ':|64*:@' |
00000020 7c 0a 7c 20 27 3a 76 5b 27 77 12 5d 5b 3a 6b 6f ||.| ':v['w.][:ko|
00000030 52 7f 7b 7e 2f 65 1f 6d 6c 27 7b 7d 2f 5d 3a 24 |R.{~/e.ml'{}/]:$|
00000040 2c 2c 7b 3a 78 3b 5b 27 60 40 50 20 00 10 2c 08 |,,{:x;['`@P ..,.|
00000050 1a 04 00 02 05 01 03 27 7b 7d 2f 5d 7b 24 78 3d |.......'{}/]{$x=|
00000060 26 21 5b 34 38 78 2e 31 30 2f 37 2a 2b 2b 5d 7c |&![48x.10/7*++]||
00000070 2b 3d 7d 25 33 2f 7d 25 7a 69 70 7b 7c 2a 7d 25 |+=}%3/}%zip{|*}%|
00000080 76 2a 76 40 29 6e 28 5e 28 |v*v@)n(^(|
```
[leds.gs](http://www.cheddarmonk.org/codegolf/leds.gs)
Note that all of the characters are 7-bit values and legal Unicode code points, so the number of characters is the same as the number of bytes in UTF-8.
Basically there are two hard-coded arrays. The first is a 15-element bitmap indicating which of the 7 segments control each grid cell. The second is the 7-segment encoding of the 16 characters. Then it's just a case of using bitwise and to work out which segments are turned on and doing some string manipulation.
[Answer]
## Python, 216 chars
```
S=' '
E='|\n| '
H=B='+'+'-'*65+'+\n|'+S*65+E
X='%(x)X'
M=[X+S+S,S+S+X,X+S+X,X+X+X]
for i in range(5):
for n in range(16):H+=M[0xcf33ed703ec2bbdefbb55fb3dcd7addf37557ab>>10*n+2*i&3]%{'x':n}+S
H+=E
print H+B[-6::-1]
```
[Answer]
## Java, 302 characters
```
class A{public static void main(String[]a){String d="w$]m.k{%o?zS|[#!% \" $ :(L 0 @ p` ",s="";for(int y=0;y<9;y++){s+=y%8==0?"+-":"| ";for(int x=0;x<64;x++)s+=y%8==0?"-":y!=1&&y!=7&&((d.charAt(8+x%4+y*4)-32)&d.charAt(x/4))>0?(char)((x<40?48:55)+x/4):" ";s+=y%8==0?"+\n":"|\n";}System.out.println(s);}}
```
Expanded :
```
public class A {
public static void main(String[] args) {
String d = "w$]m.k{%o?zS|[#!% \" $ :(L 0 @ p` ", s = "";
for (int y = 0; y < 9; y++) {
s += y % 8 == 0 ? "+-" : "| ";
for (int x = 0; x < 64; x++)
s += y % 8 == 0 ? "-" :
y != 1 && y != 7 && ((d.charAt(8 + x % 4 + y * 4) - 32) & d.charAt(x / 4)) > 0 ?
(char) ((x < 40 ? 48 : 55) + x / 4) : " ";
s += y % 8 == 0 ? "+\n" : "|\n";
}
System.out.println(s);
}
}
```
The digits shapes are encoded in a byte with the following pattern:
```
1 1 1
2 4
2 4
2 4
8 8 8
16 32
16 32
16 32
646464
```
e.g number 5 is 1|2|8|32|64 = 107
When outputting the text, each "pixel" (character) is set only if some "lines" of digits are enabled. For example, the upper-left character of a digit is set only if the line 1 or 2 are enabled. The lower-down character is set only if lines 32 or 64 are enabled.
[Answer]
For the sheer fun of it...
**BrainFuck** *611*
Note: Can probably be golfed further.
`++[------>+<]>.++.................................................................--.>++++++++++.>--[-->+++<]>-.[---->+<]>+.................................................................-[->++++<]>.>++++++++++.>--[-->+++<]>-.[---->+<]>+.[-->+++<]>...[--->++<]>...[-->+++<]>+.-[--->++<]>.[-->+++<]>++...--[--->++<]>.++[-->+++<]>...[--->++<]>--.++[-->+++<]>+.-[--->++<]>--.++[-->+++<]>+.-[--->++<]>--.-----[->++<]>-...--[--->++<]>--.-----[->++<]>...[-->+<]>+++++.----[->++<]>-...+[-->+<]>++++.----[->++<]>...[-->+<]>++++.---[->++<]>-...+[-->+<]>+++.[->++<]>+...-[-->+<]>.+[->++<]>.[-->+<]>-...+[->++<]>+...-[-->+<]>-...++[->++<]>.[-->+<]>--.++[->++<]>+...-[-->+<]>--.+++[->++<]>...[-->+<]>---.-[->++++<]>.>++++++++++.>--[-->+++<]>-.[---->+<]>+.[-->+++<]>.[--->++<]>.[-->+++<]>.[--->++<]>...[-->+++<]>+.-[--->++<]>...[-->+++<]>++.--[--->++<]>...++[-->+++<]>.[--->++<]>--.++[-->+++<]>+.-[--->++<]>--.++[-->+++<]>+.-[--->++<]>--.-----[->++<]>-.--[--->++<]>--...-----[->++<]>.[-->+<]>+++++.....----[->++<]>-.+[-->+<]>++++.----[->++<]>.[-->+<]>++++.----[->++<]>.[-->+<]>++++.---[->++<]>-.+[-->+<]>+++.---[->++<]>-.+[-->+<]>+++.[->++<]>+.-[-->+<]>.[->++<]>+.-[-->+<]>.+[->++<]>.[-->+<]>-...+[->++<]>+.-[-->+<]>-.....++[->++<]>.[-->+<]>--.++[->++<]>+.-[-->+<]>--...+++[->++<]>.[-->+<]>---...-[->++++<]>.>++++++++++.>--[-->+++<]>-.[---->+<]>+.[-->+++<]>.[--->++<]>.[-->+++<]>.[--->++<]>...[-->+++<]>+.-[--->++<]>.[-->+++<]>++...--[--->++<]>.++[-->+++<]>...[--->++<]>--.++[-->+++<]>+...-[--->++<]>--.-----[->++<]>-...--[--->++<]>--.-----[->++<]>...[-->+<]>+++++...----[->++<]>-.+[-->+<]>++++.----[->++<]>...[-->+<]>++++.---[->++<]>-...+[-->+<]>+++.[->++<]>+...-[-->+<]>.+[->++<]>...[-->+<]>-.+[->++<]>+.-[-->+<]>-...++[->++<]>...[-->+<]>--.++[->++<]>+...-[-->+<]>--.+++[->++<]>...[-->+<]>---.-[->++++<]>.>++++++++++.>--[-->+++<]>-.[---->+<]>+.[-->+++<]>.[--->++<]>.[-->+++<]>.[--->++<]>...[-->+++<]>+.-[--->++<]>.[-->+++<]>++.--[--->++<]>.....++[-->+++<]>.[--->++<]>--...++[-->+++<]>+.-[--->++<]>--...-----[->++<]>-.--[--->++<]>--.-----[->++<]>.[-->+<]>+++++.-----[->++<]>.[-->+<]>+++++...----[->++<]>-.+[-->+<]>++++.----[->++<]>.[-->+<]>++++.----[->++<]>.[-->+<]>++++...---[->++<]>-.+[-->+<]>+++.[->++<]>+.-[-->+<]>.[->++<]>+.-[-->+<]>.+[->++<]>.[-->+<]>-.+[->++<]>.[-->+<]>-.+[->++<]>+.-[-->+<]>-...++[->++<]>.[-->+<]>--.++[->++<]>.[-->+<]>--.++[->++<]>+.-[-->+<]>--...+++[->++<]>.[-->+<]>---...-[->++++<]>.>++++++++++.>--[-->+++<]>-.[---->+<]>+.[-->+++<]>...[--->++<]>...[-->+++<]>+.-[--->++<]>.[-->+++<]>++...--[--->++<]>.++[-->+++<]>...[--->++<]>--...++[-->+++<]>+.-[--->++<]>--.-----[->++<]>-...--[--->++<]>--.-----[->++<]>...[-->+<]>+++++...----[->++<]>-.+[-->+<]>++++.----[->++<]>...[-->+<]>++++.---[->++<]>-...+[-->+<]>+++.[->++<]>+.-[-->+<]>.[->++<]>+.-[-->+<]>.+[->++<]>...[-->+<]>-.+[->++<]>+...-[-->+<]>-.++[->++<]>...[-->+<]>--.++[->++<]>+...-[-->+<]>--.+++[->++<]>.[-->+<]>---...-[->++++<]>.>++++++++++.>--[-->+++<]>-.[---->+<]>+.................................................................-[->++++<]>.>++++++++++.+[->++++<]>-.++.................................................................--.`
[Answer]
### Scala, 267 characters, with bitwise encoding since everything else is worse.
```
val a="+"+"-"*65+"+"
(a+:(""+:BigInt("sbnatrnet3het8h2l21ala42h2hetrn2trn8trl2g8ha58laha4e5rhesbnatrn8",32).toString(2).grouped(64).map(x=>x.indices.map(i=>if(x(i)=='0')" "else"%X".format((i/4)%16)).mkString).toSeq:+"").map(s=>"|%65s|".format(s)):+a).foreach(println)
```
[Answer]
## JavaScript 327 characters
It's the best I can do here...
`_='console.log("?;%0*K , 77&A:!CCC!/!2!3KK 5!6J7@@ 9 H :!C! < *K4,!&A:BI!DD/ 2J3!4!5 6 6!7@@!H : I!D<0*!,!& :BICC DD>!|;|G?")J #====-$!!!!!!!%|G| 0&7@88 99H*0!1 222 333,4 555 666/>FF % 0!1:A B;G|$$$ < D E!F!%=--->D EEE F?+#####+@ 8G\\nH9 AIB CJ! K 4';for(Y in $='KJIHG@?>=<;:/,*&%$#!')with(_.split($[Y]))_=join(pop());eval(_)`
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~279~~ ~~269~~ 273 bytes
Too many printf()s; too many for loops.
```
(*P)()=printf;f(i,j,k,h){char*t="ckoOc;P5Z5UlolOoB0RXI=??_o7",u[66]={0};P("+%s+\n|%66c\n",memset(u,45,65),'|');for(h=0,i=5;i--;P("|\n"))for(P("| "),j=0;j<16;j++,P(" "),h=h>2?t++,0:h+2)for(k=3;k--;)P("X XX XXXX"[k+((*t-48>>h)&3)*3]^88?" ":"%X",j);P("|%66c\n+%s+",'|',u);}
```
[Try it online!](https://tio.run/##JZDdaoNAEIVfRRZsdtwRbIxWsl2F3vUqUggsTdIiErv@F6NXmme3u@kwN/PNmZnD5G7eZN3PulInBQridyi7seAFLbHCGhXMucoGZxQkr/tDztPgMzg2fXPo37wP@S6S5Lt/ITidwvAiZu/OU0qYfWPnbrHDMD93BNtre7uOdMJdgGEAuFk2wIt@oEp4WIqAl65rxhYtBjANU1gEsBIer16fQ14xhhoapoSKt8mogbdXbPvQ18LntV4CWiMtHVLqlJKcakapM7q7KI4VPPng@JevKEr0pj2xJcEKHpf/rRrfxNjDCfh91Y@w2qzsKMwFNeAP "C (clang) โ Try It Online")
[Answer]
**Perl, 486 characters, obviously not even trying hard.**
```
sub p {print @_};p("+",'-'x65,"+\n");p('|',' 'x65,"|\n");
p("| 000 1 222 333 4 4 555 666 777 888 999 AAA B CCC D EEE FFF |\n");
p("| 0 0 1 2 3 4 4 5 6 7 8 8 9 9 A A B C D E F |\n");
p("| 0 0 1 222 333 444 555 666 7 888 999 AAA BBB C DDD EEE FFF |\n");
p("| 0 0 1 2 3 4 5 6 6 7 8 8 9 A A B B C D D E F |\n");
p("| 000 1 222 333 4 555 666 7 888 999 A A BBB CCC DDD EEE F |\n");
p('|',' 'x65,"|\n");p("+",'-'x65,"+\n");
```
] |
[Question]
[
Today marks the 15th anniversary of Garry Kasparov's defeat against [Deep Blue](https://secure.wikimedia.org/wikipedia/en/wiki/IBM_Deep_Blue). Speaking of chess...
Input is a string that represents an 8x8 chess board containing only empty squares (`.`) and [queens](https://secure.wikimedia.org/wikipedia/en/wiki/Queen_(chess)) (`Q`). Output the number of squares that any queen can move to the next move. Queens can move any number of squares vertically, horizontally or diagonally.
Write either a program or a function. Shortest code wins, but most inventive solution gets the most upvotes.
## Examples
Input:
```
Q.......
........
.Q......
........
........
........
........
........
```
Output:
```
37
```
Input:
```
QQQQQQQQ
QQQQQQQQ
QQQQQQQQ
QQQQ.QQQ
QQQQQQQQ
QQQQQQQQ
QQQQQQQQ
QQQQQQQQ
```
Output:
```
1
```
[Answer]
## APL, 40 characters
```
โขโธa<โจ/(โณ8 8)โ.{โจ/โ=/(โข,+/,-/)ยจโบโต}โธaโ'Q'=
```
โธaโ'Q'= transforms the matrix in a nested vector whose elements are the coordinates of the given queens.
(โข,+/,-/) returns for every cell: the coordinates, their sum, their difference.
{โจ/โ=/(โข,+/,-/)ยจโบ โต} returns 1 if cells โบ & โต share one coordinate, the coordinates sum or the coordinates difference; that is gives 1 if a queen can move orizontally, vertically or diagonally from โบ to โต.
โตโ.{โจ/โ=/(โข,+/,-/)ยจโบโต}โณ8 8 applies the previous function to each queen and each cell in the chessboard.
โจโฟ returns the boolean matrix of cell reachable from some queens
โขโธa< counts the cell reachable by the queens and not already occupied by queens.
[Answer]
## Python - 125 chars
```
import os
s=os.read(0,99)
print sum(any('*'<s[i]!='Q'in s[i::j].split()[0]for j in(-10,-9,-8,-1,1,8,9,10))for i in range(71))
```
[Answer]
## APL, 37 chars
```
{โขt~โจโธโจ/(=/โ|โจ0โโ)ยจ(โณ8 8)โ.-tโโธ'Q'=โต}
```
* `'Q'=โต` gives boolean mask of queens
* `โธ` gives vector of coordinates (row, column) of queens
* `tโ` stores the result in var t
* `(โณ8 8)โ.-` outer product: gives "distances" (โrow, โcolumn) between all grid cells and queen cells
* `0โโ` checks if either โrow or โcolumn is 0
* `=/โ|` checks if โrow = +/- โcolumn
* `(=/โ|โจ0โโ)ยจ` checks both conditions for all "distances"
* `โจ/` checks if at least one of those checks return true
* `โธ` gives vector of coordinates (row, column) of reachable cells
* `t~โจ` removes original queens' positions
* `โข` count
[Answer]
**Java Solution**
```
public class NewQueenProblem {
public static int countMoves(String input){
int moves=0;
class Board{
char data;
boolean visited;
}
Board[][] board=new Board[8][8];
int x=0;
for (int i=0; i< 64; i++){
board[x%8][i%8] = new Board();
board[x%8][i%8].data=input.charAt(i);
if ((i+1)%8==0)
x++;
}
for (int i=0; i< 8; i++){
for (int j=0; j< 8; j++){
if (board[i][j].data == 'Q'){
for (int row=0; row<8; row++)
if (board[i][row].data != 'Q' && !board[i][row].visited)
{ moves++; board[i][row].visited=true;}
for (int col=0; col<8; col++)
if (board[col][j].data != 'Q' && !board[col][j].visited)
{ moves++; board[col][j].visited=true;}
int posX=i, posY=j;
while (posX < 8 && posY < 8){
if (board[posX][posY].data != 'Q' && !board[posX][posY].visited)
{ moves++; board[posX][posY].visited=true;}
posX++; posY++;
}
posX=i; posY=j;
while (posX > 0 && posY > 0){
if (board[posX][posY].data != 'Q' && !board[posX][posY].visited)
{ moves++; board[posX][posY].visited=true;}
posX--; posY--;
}
posX=i; posY=j;
while (posX > 0 && posY < 8){
if (board[posX][posY].data != 'Q' && !board[posX][posY].visited)
{ moves++; board[posX][posY].visited=true;}
posX--; posY++;
}
posX=i; posY=j;
while (posX < 8 && posY > 0){
if (board[posX][posY].data != 'Q' && !board[posX][posY].visited)
{ moves++; board[posX][posY].visited=true;}
posX++; posY--;
}
}
}
}
return moves;
}
public static void main(String[] args) {
int moves = countMoves("Q................Q..............................................");
//int moves = countMoves("QQQQQQQQQQQQQQQQQQQQQQQQQQQQ.QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ");
System.out.println(moves);
}
}
```
[Answer]
## APL, 50 chars
```
{โข(b~x)โฉ,(xโ(,'Q'=โต)/bโ,โณ8 8)โ.+(โณ8)โ.รโ.,โจ1 0 ยฏ1}
```
In English:
* `โ.,โจ1 0 ยฏ1`: computes all the pairs composed by -1, 0 or 1, i.e.: (0 0)(0 1)(0 -1)(1 0) and so on;
* `(โณ8)โ.รโ.,โจ1 0 ยฏ1`: multiply all the pairs computed by all the number from 1 to 8, obtaining all the possible offsets of movement of the queen;
* `(xโ(,'Q'=โต)/bโ,โณ8 8)`: puts is `x` the coordinates of the given queens;
* `โ.+`: compute yet another outer sum, combining the position of the given queens with all the possible displacement offsets. This gives a multidimensional array of coordinate pairs of all the possible place where each of the queens might end up, including outside the board (whose valid coordinate pairs is in `b`)
* `(b~x)โฉ,`: removes from the list `b` all the coordinates taken by the queens in the given (`x`) and intersects it with flattened array of pairs of all the possible positions of the queens
* `โข`: count the remaining pairs
[Try online sample 1](http://tryapl.org/?a=%7B%u2262%28b%7Ex%29%u2229%2C%28x%u2190%28%2C%27Q%27%3D%u2375%29/b%u2190%2C%u23738%208%29%u2218.+%28%u23738%29%u2218.%D7%u2218.%2C%u23681%200%20%AF1%7D8%208%u2374%27Q................Q..............................................%27&run).
[Try online sample 2](http://tryapl.org/?a=%7B%u2262%28b%7Ex%29%u2229%2C%28x%u2190%28%2C%27Q%27%3D%u2375%29/b%u2190%2C%u23738%208%29%u2218.+%28%u23738%29%u2218.%D7%u2218.%2C%u23681%200%20%AF1%7D%208%208%u2374%27QQQQQQQQQQQQQQQQQQQQQQQQQQQQ.QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ%27&run)
[Answer]
# JavaScript 140 bytes
```
f=a=>a.split`
`.map((r,y,G)=>[...r].map((c,x)=>A+=c<"Q"&&G.some((R,Y)=>[...R].some((C,X)=>C>"."&&((d=X-x)*(D=Y-y)==0||d**2==D**2)))),A=0)&&A
console.log(f(`Q.......
........
.Q......
........
........
........
........
........`)==37)
console.log(f(`QQQQQQQQ
QQQQQQQQ
QQQQQQQQ
QQQQ.QQQ
QQQQQQQQ
QQQQQQQQ
QQQQQQQQ
QQQQQQQQ`)==1)
```
[Answer]
# [Perl 5](https://www.perl.org/), 172 + 3 (`-pF`) bytes
```
push@a,[@F]}{for$i(0..7){O:for$j(0..7){for$x(-1..1){for$y(-1..1){if($x|$y){$r=$i;$c=$j;$a[$i][$j]ne Q&&$a[$r][$c]eq Q&&++$\&&next O while(($r+=$x)^7)<8&&(($c+=$y)^7)<8}}}}}
```
[Try it online!](https://tio.run/##hchBC4IwGMbxe5/Cw8vYMIcexMgET95CPJtByMSJqE2jifnVWw6rS4ee0//3dEzUrlLdrS/DyzYNo2yeilYAxzalHpnivVb1lm6JLYdSZ8X4AS8wyAeMZAIRAPchD6Dy4ZICz1KosoYZCULaYnGesau2acIJoYbJwYiNe8lrhjEIMwBJzh457BBanC8eV896SiV03YZ@I/l5/sez7QbeNr2yji61HVtZXfQC "Perl 5 โ Try It Online")
There's got to be a better way to do it, but this at least works.
] |
[Question]
[
# Goal
You will be given a positive integer number less than 10^20. You must convert it to Korean.
For example, if the input is `12345`, the output should be `์ผ๋ง์ด์ฒ์ผ๋ฐฑ์ฌ์ญ์ค`.
# Technical details (Small)
Let's starts with simple numbers.
```
// 1 - 9
1 -> ์ผ
2 -> ์ด
3 -> ์ผ
4 -> ์ฌ
5 -> ์ค
6 -> ์ก
7 -> ์น
8 -> ํ
9 -> ๊ตฌ
// 10, 100, 1000
10 -> ์ญ
100 -> ๋ฐฑ
1000 -> ์ฒ
```
You can concatenate `2` ~ `9` front of `10`, `100`, `1000`.
However, you should not concatenate `1` front of `10`, `100`, `1000`.
```
// 20 = 2 * 10
20 -> ์ด์ญ
// 300 = 3 * 100
300 -> ์ผ๋ฐฑ
// 9000 = 9 * 1000
9000 -> ๊ตฌ์ฒ
// 1000 is just 1000
1000 -> ์ฒ
```
For integer less than 10000, below rule is used for pronunciation.
```
// 1234 = 1000 + 200 + 30 + 4
1234 -> ์ฒ์ด๋ฐฑ์ผ์ญ์ฌ
// 1002 = 1000 + 2
1002 -> ์ฒ์ด
// 2048 = 2000 + 40 + 8
2048 -> ์ด์ฒ์ฌ์ญํ
// 510 = 500 + 10
510 -> ์ค๋ฐฑ์ญ
// 13 = 10 + 3
13 -> ์ญ์ผ
```
# Technical details (Large)
Now let's go to the hard part.
First, you need to know some parts used in larger numbers:
```
1 0000 -> ๋ง
1 0000 0000 -> ์ต
1 0000 0000 0000 -> ์กฐ
1 0000 0000 0000 0000 -> ๊ฒฝ
```
When Koreans pronounce big numbers
1. Cut it with width 4
2. Convert each of them using methods for less than 10000
3. Combine them with default form of big numbers
Here is some detailed examples. (I added some space to korean for readability)
```
// 12345678 = 1234 5678
// 1234 -> ์ฒ์ด๋ฐฑ์ผ์ญ์ฌ
// 5678 -> ์ค์ฒ์ก๋ฐฑ์น ์ญํ
12345678 -> ์ฒ์ด๋ฐฑ์ผ์ญ์ฌ ๋ง ์ค์ฒ์ก๋ฐฑ์น ์ญํ
// 11122223333 = 111 2222 3333
// 111 -> ๋ฐฑ์ญ์ผ
// 2222 -> ์ด์ฒ์ด๋ฐฑ์ด์ญ์ด
// 3333 -> ์ผ์ฒ์ผ๋ฐฑ์ผ์ญ์ผ
11122223333 -> ๋ฐฑ์ญ์ผ ์ต ์ด์ฒ์ด๋ฐฑ์ด์ญ์ด ๋ง ์ผ์ฒ์ผ๋ฐฑ์ผ์ญ์ผ
// 10900000014 = 109 0000 0014
// 109 -> ๋ฐฑ๊ตฌ
// 0000 -> (None)
// 0014 -> ์ญ์ฌ
10900000014 -> ๋ฐฑ๊ตฌ ์ต ์ญ์ฌ
// 100000000 -> 1 0000 0000
// 1 -> ์ผ
// 0000 -> (None)
// 0000 -> (None)
100000000 -> ์ผ ์ต
```
[Here](https://pastebin.com/p528RuTL) are some more examples.
# Rule
You can make your program gets input from `stdin` and output to `stdout`, or make a function that gets string/integer and returns string.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so answers will be scored in bytes with fewer bytes being better.
[Answer]
# [Aheui](https://aheui.github.io/), 1555 bytes
```
์ด๋ฐฆ๋ฐ๋ฐ๋ฐ๋ฐ๋น ๋ฐ๋ฐฆ๋ฐ๋ค๋น ๋ฐ๋ค๋น ๋ฐ๋น ๋ฐ๋ฐ๋ค๋น ๋ฐ๋ฐ๋ฐ๋ฐ๋
์ํฐ๋๋ ๋ฒ๋ฒ๋ ๋ป๋๋ฒ๋ ๋ป๋ฒ๋ปํฐํฐ๋ ๋ฒ๋ฒ๋ ๋ป๋ ๋ฒ๋ฒ๋ป๋
๋ฐฉ๋บ์ฐ์ฐจ๋น ๋ฐ๋ฐ๋ค๋น ๋ฐ๋น ๋
์ฐ๋
ธ์ฌ๋๋ป๋ ๋ป๋๋ฒ๋ฒ์ช๋ฌ
์ฆ์ฐ์น์ด
์์ณ๋ถ
ใ
์์ญ๋บ์ฐ์ฐจ๋น ๋ถ
ใ
์ ์ด์ฐ์ฌ๋ ค๋๋ฒ
ใ
์ใ
๋น ๋ฐ๋ฐํํธ์ฐ์ฒ์ณ๋บ์ฐ์ฒ๋ฐ๋ฐค๋
ใ
ใ
์ฐ์จ์ฌํ
จ์ฌ๋ณ์ฌ๋์ฌ๋ผ์ฌ๋๋ฒ
๋ ๋ฒ
ใ
์์์ญ๋บ์ฐ์ฐจ์ณ๋น ๋ฐํธ์ ์ฒ๋ฐ๋ถ
ใ
ใ
์ฐ์ดใ
์ฌ๋ฐ๋ฑ๋ณ๋ํ
จ๋ฒ๋ ๋ป๋
ใ
์ใ
์ฐ์ด์ค์ฌ๋์ฌ๋ณ์ฌ์ด
ใ
ใ
ใ
๋น ๋ฐคํธ์ฐ์ฒ๋ฐฃ๋น ๋ฐ๋ฐ๋ค๋ฟ
ใ
์ใ
์ฐ์ด์ค์ฌ๋๋ฒ๋๋ ๋ฒ๋ฒ๋
ใ
ใ
ใ
๋น ๋ฐฆํธ์ฐ์ฒ๋ฐ๋ฐฆ๋ฐ๋น ๋
ใ
๋จใ
์์ด์ค์ฌ๋๋ฒ๋ ๋ฒ
ํฐ๋ฒ
ใ
ใ
ใ
๋น ๋ฐํธ์ฐ์ฒ๋ฐ๋ฐค๋ฐ๋ฐฃ๋ฐ๋ถ
ใ
๋ดใ
์ฐ์ด์ฌ์ฌํ
จ๋๋ฒ๋ฒ๋ ๋ป๋
ใ
ใ
ใ
๋น ๋ฐํธ์ฐ์ฒ๋ฐฃ๋ฐ๋ค๋น ๋ฐ๋ถ
ใ
๋ตฌใ
์ฐ์ด์ฌ์ฌ๋๋ ๋ฒ๋ฒ๋ ๋ปํฐ
ใ
ใ
ใ
๋น ๋ฐคํธ์ฐ์ฒ๋ฐฃ๋ฐ๋ค๋น ๋ฐ๋ถ
ใ
๋ตฌใ
์ฐ์ด์ฌ์ฌ๋๋ ๋ฒ๋ฒ๋ ๋ปํฐ
ใ
ใ
ใ
๋น ๋ฐํธ์ฐ์ฒ๋ฐฃ๋ฐ๋ค๋น ๋ฐ๋ฟ
ใ
๋ฌใ
์ฐ์ด์ฌ์ฌ๋๋ ๋ฒ๋๋ฒ๋ฒ๋
ใ
ใ
ใ
๋น ๋ฐฆํธ์ฐ์ฒ๋ฐฃ๋ฐ๋ค๋น ๋ฐ๋น ๋
ใ
์ฝใ
์ฐ์ด์ฌ์ฌ๋๋ ๋ฒ๋๋ฒ๋ ๋ป๋ฒ
ใ
ใ
ใ
๋น ๋ฐํธ์ฐ์ฒ๋ฐ๋ฐ๋ฐ๋น ๋ฐ๋ถ
ใ
๋ดใ
์ฐ์ด์ฌ์ฌ๋๋ฒ๋๋๋ฒ๋ ๋ป
ใ
ใ
ใ
๋น ๋ฐฃํธ์ฐ์ฒ๋ฐ๋ฐ๋ฐ๋ฐ๋ฐ๋ถ
ใ
๋ตฅใ
์ฐ์ด์ฌ์ฌ๋๋ฒ๋๋ฒ๋ ๋ฒ๋
ใ
ใ
ใ
๋น ๋ฐํธ์ฐ์ฒ๋ฐ๋ฐ๋ฐ๋น ๋ฐ๋ถ
ใ
์์ด์ด์ด์ค์ฌ๋๋ฒ๋ ๋ฒ๋ ๋ฒ๋
ใ
๋ง์ฌ์ฐ์น์ฅ์ฐํ๋บ๋ฌด์ฐจํ์จ
ใ
ใ
์ค์ ์ฌ์ด์ ์ฌใ
๋ฉฐใ
ใ
์ฐ
์คใ
ใ
ใ
ใ
ใ
ใ
ใ
ใ
ใ
ใ
ใ
์ด
์ฐใ
ใ
์ดใ
ใ
์ด์ด
์จํฌ๋งฃ์ด
```
**[Try it online!](https://tio.run/##lZRdbtpAEIDffaMcpw@V0gP0PY1xsYRNSDGOC4Yg4RASudLWOFbSH/UwfZz1GcjM7Hr9E4wUhEaz3tlvZudnP5x//PzpcJCXOYgtiBgCAWJJ8mXNOn8cJXqpFLGqdhf1Fp5Sx68nlnSjciDADyBcQzaCbErK7wl9yUKtZz5KNCNLMvPqLX1qrI5YIB7gVyTnQood@49bQaGcxxZug/Msb1K4iTRDO0SwJ/1HuE0taW8JM3qRYW7J2UBe7qG4sP47Q178aLkpXN6I12hMXxG9ThSRN@YBSo5nASIq7YvSfia7LCKsImURJyahCNGajwl5vUNY6ZCE/UjFTPKPS3KMATucg6n20wmO8OR2Rg4xPHIS63C1hzAnBWGYn58h7L9iAOiQclqluL6DOiDHifLOUQ1QUpIUsrpoYq4IYlMVfkWl@Of18LAa6LTdCh3qtkFdUcuZopLFcEdI93sXSTyHmicLO7xZg8fJpyg3JIsvjJzkdZR@qmrBhZ02W7VDXbTujmDTgMWQqU9ph0qVpCh9Q8VwT2b0PVTvBDXupao6QRr1UMfVyISn69SmmmrJ4d8e8FQnWA9/t2bLdg@s6ieo@Ha8ZtwGTCWwr8Ad6qZBjavnLW5Qn@6OUVUSAh33mzzctvsrbsR6xUlwbeKpfzVV@u66cQPdX3DvSjvVb5J9h0rpeTjokOY46KjjW1GNdZTQsPNYKoXOPwgz9BZamED7/vzwzYVZGIU37F25TOF@g4vD4ezIz3oF "Aheui (esotope) โ Try It Online")** (trailing new line for input is necessary)
Why not?
Hours of coding, and another hours of packing and layouting. I think it can be golfed furthermore, but it already took so much effort. I really wanted to pack it into a rectangle.
Because 10^20 is larger than 2^64, not every implementation of Aheui will not support ๊ฒฝ-scale numbers.
Luckily, Python and [pyaheui](https://github.com/aheui/pyaheui) implementation (which is used on TIO) uses much-larger precision numbers, so it can support not only ๊ฒฝ, but more than [ํด, ์, ์, ๊ตฌ, ๊ฐ, ์ , ์ฌ, ๊ทน](https://en.wikipedia.org/wiki/Korean_numerals#Numerals_(Cardinal)).
And my code can be *easily* extended to use more larger unit suffixes.
This code will not terminate on input `0`, but this spec was not defined in the question (which should output `์`).
# Explanation-ish Unpacked Code
```
ใ
ฃPush unit suffixes (๋ง, ์ต, ์กฐ, ๊ฒฝ) to stack ใน
ใ
ฃ
์
๋ฐฆ๋ฐ๋ฐ๋ฐ๋ฐ๋น ๋ฐ๋ฐฆ๋ฐ๋ค์ฐ
์ฐใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
๋น ๋ฐ๋ค๋น ๋ฐ๋น ๋ฐ๋ฐ๋ค๋น ๋ฐ๋ฐ๋ฐ๋ฐ๋ค๋ค์ฐ
์ฐใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
๋น ๋ฐ๋ฐ๋ฐ๋น ๋ฐ๋ฐฆ๋ฐ๋ฐํํ์ฐ
์ฐใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
๋น ๋ฐ๋น ๋ฐ๋ฐฆ๋ค๋น ๋ฐ๋ฐฃ๋ฐ๋ฐ๋คํ์ฐ
์ฐใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
ใ
ฃ
ใ
ฃGet input as number
ใ
ฃ
์ฌ๋ฐฉ์ฐ
์ฐใ
ก์ด
ใ
ฃ
ใ
ฃSplit input by four digits
ใ
ฃ
ใ
ฃใ
ฃIf input is zero, end the loop
์์๋บ์ฐ์ฐจ์ฐ
์ฐใ
ใ
ก์ดใใ
ฃ
ใ
ฃใ
ฃ์ฐใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃTake mod 10000 to stack ใฒ
ใ
ฃใ
ฃ๋น ๋ฐ๋ฐ๋ค๋น ๋ฐ๋น ๋ฐ๋ผ์บ์ฐ
ใ
ฃใ
ฃ์ฐใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃDivide by 10000
ใ
ฃใ
ฃ๋ฐ๋ฐ๋ค๋น ๋ฐ๋น ๋ฐ๋์ฐ
ใ
ฃ์คใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
ใ
ฃ
ใ
ฃReverse stack ใฒ to stack ใฑ
ใ
ฃ
์ฆ์ฐ์น์ด
์ฐ์ด
ใ
ฃ
ใ
ฃProcess four digits
ใ
ฃ
์์ฐใ
ฃUse ใท stack for index (0, 2, 4, 6)
ใ
ฃ์์ณ๋ฐ์ฐ
ใ
ฃ์ฐใ
กใ
ก์ด
ใ
ฃใ
ฃ
ใ
ฃใ
ฃใ
ฃConvert four digits into korean
ใ
ฃ์์์
ใ
ฃใ
ฃใ
ฃใ
ฃIf current multiplier is zero, escape
ใ
ฃใ
ฃใ
ฃ๋บ์ฐ์ฐจ์ฐ
ใ
ฃ์ฐใ
ใ
ก์ดใใ
ฃ
ใ
ฃใ
ฃใ
ฃ์ฐใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃใ
ฃTake mod 10
ใ
ฃใ
ฃใ
ฃ๋น ๋ฐ๋ฐ๋ค๋ผ์ฐ
ใ
ฃใ
ฃใ
ฃ์ฐใ
กใ
กใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃใ
ฃIf remainder - 1 is 0 (remainder is 1) and index is 0 (ones digit), push ์ผ on stack ใด
ใ
ฃใ
ฃใ
ฃ๋น ๋ฐ๋ฐํํธ์ฐ์ฒ์ณ๋บ์ฐ์ฒ๋ฐ๋ฐค๋ฐ๋ฐฃ๋ฐ๋ฐ๋ค๋น ๋ฐ๋ฐฃํ์ผ์ฐ
ใ
ฃใ
ฃใ
ฃ์ฐใ
กใ
กใ
กใ
ก์ดใ
กใ
กใ
ก์ดใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃใ
ฃIf remainder is not 0
ใ
ฃใ
ฃใ
ฃ์ญ๋บ์ฐ์ฐจ์ฐ
ใ
ฃใ
ฃใ
ฃ์ฐใ
ก์ดใใ
ฃ
ใ
ฃใ
ฃใ
ฃใ
ฃ์ฐใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃใ
ฃ์
ใ
ฃใ
ฃใ
ฃใ
ฃใ
ฃIf index is [2, 4, 6], push [์ญ, ๋ฐฑ, ์ฒ] on stack ใด
ใ
ฃใ
ฃใ
ฃใ
ฃ๋น ๋ฐํธ์ฐ์ฒ๋ฐ๋ฐ๋ฐ๋น ๋ฐ๋ฐํ๋ฐ๋ฐ๋ฐ๋ฐ๋ฐ๋ค์ผ์ฐ
ใ
ฃใ
ฃใ
ฃใ
ฃ์ฐใ
กใ
ก์ดใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃใ
ฃ๋น ๋ฐคํธ์ฐ์ฒ๋ฐฃ๋น ๋ฐ๋ฐ๋ค๋น ๋ฐ๋ฐฃ๋ฐ๋ฐ๋ค๋ฐ๋ฐ์ผ์ฐ
ใ
ฃใ
ฃใ
ฃใ
ฃ์ฐใ
กใ
ก์ดใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃใ
ฃ๋น ๋ฐฆํธ์ฐ์ฒ๋ฐ๋ฐฆ๋ฐ๋น ๋ฐ๋ฐฆํ๋ฐ๋ฐ๋ฐ๋ฐ์ผ์ฐ
ใ
ฃใ
ฃใ
ฃใ
ฃ์ฐใ
กใ
ก์ดใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃใ
ฃใ
ฃ
ใ
ฃใ
ฃใ
ฃใ
ฃใ
ฃIf remainder is [2 ... 9], push [์ด ... ๊ตฌ] on stack ใด
ใ
ฃใ
ฃใ
ฃใ
ฃ์
ใ
ฃใ
ฃใ
ฃใ
ฃ๋น ๋ฐํธ์ฐ์ฒ๋ฐ๋ฐค๋ฐ๋ฐฃ๋ฐ๋ฐ๋ค๋น ๋ฐ๋ฐฃ๋ฐฃ๋คํ์ผ์ฐ
ใ
ฃใ
ฃใ
ฃใ
ฃ์ฐใ
กใ
ก์ดใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃใ
ฃ๋น ๋ฐํธ์ฐ์ฒ๋ฐฃ๋ฐ๋ค๋น ๋ฐ๋ฐํ๋น ๋ฐ๋ฐฃ๋ฐ๋ฐ๋ค์ผ์ฐ
ใ
ฃใ
ฃใ
ฃใ
ฃ์ฐใ
กใ
ก์ดใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃใ
ฃ๋น ๋ฐคํธ์ฐ์ฒ๋ฐฃ๋ฐ๋ค๋น ๋ฐ๋ฐํ๋น ๋ฐ๋ฐฃ๋ฐ๋ฐ๋ค์ผ์ฐ
ใ
ฃใ
ฃใ
ฃใ
ฃ์ฐใ
กใ
ก์ดใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃใ
ฃ๋น ๋ฐํธ์ฐ์ฒ๋ฐฃ๋ฐ๋ค๋น ๋ฐ๋น ๋ฐ๋ฐฆ๋ฐ๋ค๋ฐ๋ฐ๋ค์ผ์ฐ
ใ
ฃใ
ฃใ
ฃใ
ฃ์ฐใ
กใ
ก์ดใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃใ
ฃ๋น ๋ฐฆํธ์ฐ์ฒ๋ฐฃ๋ฐ๋ค๋น ๋ฐ๋น ๋ฐ๋ฐฆ๋น ๋ฐ๋ฐฃ๋ค๋ฐฃ๋ฐ๋ค์ผ์ฐ
ใ
ฃใ
ฃใ
ฃใ
ฃ์ฐใ
กใ
ก์ดใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃใ
ฃ๋น ๋ฐํธ์ฐ์ฒ๋ฐ๋ฐ๋ฐ๋น ๋ฐ๋ฐฆ๋น ๋ฐ๋ฐ๋ค๋ค๋ฐฃ๋ฐ์ผ์ฐ
ใ
ฃใ
ฃใ
ฃใ
ฃ์ฐใ
กใ
ก์ดใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃใ
ฃ๋น ๋ฐฃํธ์ฐ์ฒ๋ฐ๋ฐ๋ฐ๋ฐ๋ฐ๋ฐฆ๋ฐ๋ฐฃ๋ฐ๋ฐค๋ค๋ฐ๋ฐ์ผ์ฐ
ใ
ฃใ
ฃใ
ฃใ
ฃ์ฐใ
กใ
ก์ดใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃใ
ฃ๋น ๋ฐํธ์ฐ์ฒ๋ฐ๋ฐ๋ฐ๋น ๋ฐ๋ฐฃ๋ค๋ฐค๋ฐ๋ฐ๋ฐ๋ฐฃ๋ค์ผ์ฐ
ใ
ฃใ
ฃใ
ฃ์ฐใ
กใ
กใ
ก์ดใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃใ
ฃ
ใ
ฃใ
ฃใ
ฃใ
ฃIncrease index, move onto next digit
ใ
ฃใ
ฃใ
ฃ์ณ๋ฐ๋ค์ญ๋ง๋ฐ๋ฐ๋ค๋์ฐ
ใ
ฃใ
ฃ์คใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก์ด
ใ
ฃใ
ฃ
ใ
ฃใ
ฃใ
ฃPop zero
ใ
ฃ์๋ฌด
ใ
ฃใ
ฃใ
ฃ
ใ
ฃใ
ฃใ
ฃใ
ฃMove one suffix to stack ใฑ
ใ
ฃใ
ฃใ
ฃใ
ฃIf all suffix has been used, escape
ใ
ฃใ
ฃ์์ฌ์ฐ์น์ญ์ฐ
ใ
ฃ์ฐใ
ใ
ก์ดใใใ
ฃ
ใ
ฃใ
ฃใ
ฃ์ฐใ
กใ
กใ
ก์ด
ใ
ฃใ
ฃใ
ฃใ
ฃIf next multiplier is zero, discard next multiplier and suffix, then check next
ใ
ฃใ
ฃใ
ฃใ
ฃIf next multipler is not zero, move suffix to stack ใด and continue
ใ
ฃใ
ฃใ
ฃใ
ฃIf all multiplier has been processed, escape
ใ
ฃใ
ฃใ
ฃ์ผ์ฐํ๋บ์ฐ์ฐจํ์ผ์ฐ
์คใ
ใ
ใ
กใ
ใ
กใ
กใ
ใ
กใ
กใ
ก์ด
์ฐ์ดใ
ใ
ก์ดใ
กใ
กใ
ฃ
ใ
ฃใ
ก์คใ
กใ
ก๋จธ๋จธ์ด
์จํฌ๋งฃ์ด
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 147 bytes
```
^
0๊ฒฝ0์กฐ0์ต0๋ง
\G0?\D?
0์ฒ0๋ฐฑ0์ญ$&
+`0(\D)(\d+)(\d)
$2$1$3
0(์ฒ0๋ฐฑ0์ญ0.?|์ฒ|๋ฐฑ|์ญ)
1(์ฒ|๋ฐฑ|์ญ)
$1
T`d`_์ผ์ด์ผ์ฌ์ค์ก์น ํ๊ตฌ
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP47L4NWmvQZvFm4weDNtq8Hr5T1cMe4G9jEu9lwGbzbNMXi9YaPBm@61Kmpc2gkGGjEumhoxKdogQpNLxUjFUMWYy0ADSZ2Bnn0NkFsD5NYAuZpcXIYaKHwVQ66QhJSE@Ddz97yZu@VN0543TWvezFjyZs7CNzsXvO2Z8mrrmv//DY2MTUzNzC24DA0NjYDAGAi4DA0sDcDA0ATIhgIA "Retina 0.8.2 โ Try It Online") Link includes test cases. Explanation:
```
^
0๊ฒฝ0์กฐ0์ต0๋ง
```
Insert the symbols for powers of 10,000.
```
\G0?\D?
0์ฒ0๋ฐฑ0์ญ$&
```
Insert the thousands, hundreds and tens symbols.
```
+`0(\D)(\d+)(\d)
$2$1$3
```
Replace the zeros between the symbols with the input digits.
```
0(์ฒ0๋ฐฑ0์ญ0.?|์ฒ|๋ฐฑ|์ญ)
```
Delete zero thousands, hundreds or tens, or a whole power of 10,000.
```
1(์ฒ|๋ฐฑ|์ญ)
$1
```
Delete the 1 of one thousand, one hundred or one ten.
```
T`d`_์ผ์ด์ผ์ฌ์ค์ก์น ํ๊ตฌ
```
Transliterate the remaining digits, deleting any remaining zeros.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~96 95 94~~ 92 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
โฤฟ|ฤฟtฤแปดฤแธฤฐ$ฤฟ!แนช`แบกรแธlฤแธฃแปด1แนฦแปคแนแธขแปแนpแธแบโs2แธ
โนแป
bศท4DUยตลผโยขยฝยฟโฌโแน$แนลlโฌ1Pโฌ0ยฆแบ รfFยตโฌแนยต;"โยกรรรรโแนLโ$รfFแธ0แปยข
```
A monadic link taking a positive integer and returning a list of characters.
**[Try it online!](https://tio.run/##y0rNyan8//9Rw5wj@2uO7C850vVw9xYgsaPlyAaVI/sVH@5clfBw18LD8x7u6Mk5Mu3hjsVAecOHO2cc63i4ewmQfrhj0cPdPQ93NhQA9TzcNelRw4xio4c7Wh817gSKcyWd2G7iEnpo69E9QCsOLTq099D@R01rgIoe7mxUebhz1tHJOUC@YQCQMDi07OGuBYcnpLkd2grkAiUPbbVWAmlbeLjtcPvhCYcngvXN8nnUMFMFpO7hjvkGD3d3H1r0//9/QwNLAzAwNAEA "Jelly โ Try It Online")** or see a [test-suite](https://tio.run/##ZU09S8RAEO39F0rKKXY3Ob3DVmy0sLGwE0ELSSFoI1jkRD3RK04FOQ9RL4qFWFgY3E1OArsb8W/M/pE4GytxmK/35j1mezOO9@vaJbe2PLDlnj3D4p2aPLJvgS2nUb2sYz42dyj7sb1G@Uh3jmr4dYrFE02UKRZ9VMkOeTC/dMlwV6A8dl1F/NTG90e0sKqzakIvdKo/dekOX0mEqhugGlVXMWG@Qo3pZ8wfzGBrUWcE6aiz@RlvG5sT0zMDc9H4RssuuQm8DuU9w@Jcp3U1MT3yLFGt1TUHASFE0IJZmIM2dIAzyqYYCAYhjY7fuQgjzwpioza0vC5sZL9i9nf7j3z8AA "Jelly โ Try It Online") (numbers referenced in the OP)
...or see assertion of the pastebin values [here](https://tio.run/##pVNNb9NAEL33V4CVYw676ziNxRVx4sCFUxQJIcEB5YAEl0ockgoooj6UD1WhCpCEqpVQkdIoFnbiKpLtIv7G@tiW32Bmd70fjc2JlbyZeTuz82b25cmjbncrz7PeMF29SFfP07d0OYcteJlOa@nqJg2/P6CLcfKFBl433afBNzjHNBz8ekOXh/BLgwldejTsPYUcunif9QbPCA1eZf0Q8I2Hv382bt@P/fMISsST@CxeZdsnEETDfo2GB@cfuuDje7Ch@IguRsne4zuxDy4cxv4ti6WNk9fJTrKXvON5B3ez3qcai6PBV0SXu/EkBxbJTtaPgC5PzvN2G9etq8@R1alv3GgTZs@FbYO9XeANZp8I2wF7cCjsJtjDsbA3wQ5Hwm7VrT/eR2G7devCL3IxgqDdH4WDuaOKY1L4BQFsC1@SIJzp3EwhroRUCRtx3qqKgzhf5bstzgd8zdCVkEEU0i6np9Ij3NPUsDg2esESMPpBMkvHEWxgRqhtwqpjxgIwRYRgBegrEY@aDVWOiDGQRksi8Ipm5wTrYLMINkA9bIxsE5cs3dZmUwxwNoSb2VE4Ym1IZTCGvEx0eexpCEvIHANyNCoIR@xCKThiN5ymGAFEwDPzlkREqWQx6@Iuc9xwjJl2xBwhQM1eKwBKITnaYuRcVqyeaoMHceFWBZlqdl3ksk9OCnaIZvuxt4bIBLFKCYJlOW1Nv2LxaV7t@9dhLOFrI0HYSGCPDB1IETEm@s7KyqqKa6x/x/5PV7qz8VTLHpndzeFIS9euOhXyMYeA1havcTE7K9dAyHHEXweOQXxKgloY61@VSFhyCWTcyiB/kgqNlUCr0/kL "Jelly โ Try It Online")
### How?
Constructs the parts-characters required as indexes of the list:
```
[1,2,3,4,5,6,7,8,9,10,100,1000,10000,100000000,1000000000000,10000000000000000]
i.e.: ์ผ์ด์ผ์ฌ์ค์ก์น ํ๊ตฌ์ญ๋ฐฑ์ฒ๋ง์ต์กฐ๊ฒฝ
```
and indexes into the list. Thus `30210` would become `[3,13,2,11,10]` and then `์ผ๋ง์ด๋ฐฑ์ญ`
```
โฤฟ|ฤฟtฤแปดฤแธฤฐ$ฤฟ!แนช`แบกรแธlฤแธฃแปด1แนฦแปคแนแธขแปแนpแธแบโs2แธ
โนแป - Link 1, get part-characters: no arguments
โฤฟ|ฤฟtฤแปดฤแธฤฐ$ฤฟ!แนช`แบกรแธlฤแธฃแปด1แนฦแปคแนแธขแปแนpแธแบโ - code-page indices = [199,124,199,116,192,188,192,172,198,36,199,33,206,96,211,20,173,108,194,237,188,49,204,156,185,204,197,181,200,112,172,189]
s2 - split into twos = [[199,124],[199,116],[192,188],[192,172],[198,36],[199,33],[206,96],[211,20],[173,108],[194,237],[188,49],[204,156],[185,204],[197,181],[200,112],[172,189]]
แธ
โน - convert from base 256 = [51068,51060,49340,49324,50724,50977,52832,54036,44396,49901,48177,52380,47564,50613,51312,44221]
แป - cast to characters = "์ผ์ด์ผ์ฌ์ค์ก์น ํ๊ตฌ์ญ๋ฐฑ์ฒ๋ง์ต์กฐ๊ฒฝ"
bศท4DUยตลผโยขยฝยฟโฌโแน$แนลlโฌ1Pโฌ0ยฆแบ รfFยตโฌแนยต;"โยกรรรรโแนLโ$รfFแธ0แปยข - Main link: integer, n e.g. 102031
ศท4 - 10^4 = 10000
b - convert (n) to base (10000) [10,2031]
D - convert (each) to base 10 [[1,0],[2,0,3,1]]
U - reverse each [[0,1],[1,3,0,2]]
ยต ยตโฌ - monadic chain for โฌach:
$ - last two links as a monad:
โยขยฝยฟโฌโ - code-page indices = [1,10,11,12]
แน - mould like e.g. [1,10] or [1,10,11,12]
ลผ - zip [[0,1],[1,10]] or [[1,1],[3,10],[0,11],[2,12]]
แน - reverse [[1,10],[0,1]] or [[2,12],[0,11],[3,10],[1,1]]
ลlโฌ1 - left-strip ones [[10],[0,1]] or [[2,12],[0,11],[3,10],[]]
Pโฌ0ยฆ - product @ index 0 [[10],0] or [[2,12],[0,11],[3,10],1] (Note: the empty product is 1)
แบ รf - filter keep if any [[10]] or [[2,12],[3,10],1]
F - flatten [10] or [2,12,3,10,1]
แน - reverse [[2,12,3,10,1],[10]]
ยต - new monadic chain
โยกรรรรโ - code-page indices = [0,13,14,15,16]
;" - zip with concatenation [[2,12,3,10,1,0],[10,13],14,15,16]
แน - reverse [16,15,14,[10,13],[2,12,3,10,1,0]]
รf - filter keep if:
$ - last two links as a monad:
L - length 1 1 1 2 6
โ - decrement 0 0 0 1 5
- i.e. [[10,13],[2,12,3,10,1,0]]
- (This also removes any 0-sized 10K parts e.g. the [13] from 200001234 -> [16,15,[2,14],[13],[12,2,11,3,10,4,0]])
F - flatten [10,13,2,12,3,10,1,0]
แธ0 - filter discard zeros [10,13,2,12,3,10,1] (Note: not there for multiples of 10000 so cann't simply pop with แน)
ยข - call the last link as a nilad "์ผ์ด์ผ์ฌ์ค์ก์น ํ๊ตฌ์ญ๋ฐฑ์ฒ๋ง์ต์กฐ๊ฒฝ"
แป - index into "์ญ๋ง์ด์ฒ์ผ์ญ์ผ"
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 158 bytes
This task has been haunting me for a few days, but after several iterations of tinkering with the code and gaining max 1-2 bytes at a time, I think it isn't going to become much shorter than this, unless somebody points out a conceptually different approach.
```
->n{i=0;n.digits.map{|d|'-๋ง์ต์กฐ๊ฒฝ'[i%4>0?'':i/4]+'์ฒ-์ญ๋ฐฑ'[(i+=1)%4]+'0์ผ์ด์ผ์ฌ์ค์ก์น ํ๊ตฌ'[d]}.join.reverse.gsub /(0.){4}.|0.|์ผ(?!-)|-/,''}
```
[Try it online!](https://tio.run/##AaYAWf9ydWJ5//8tPm57aT0wO24uZGlnaXRzLm1hcHt8ZHwnLeunjOyWteyhsOqyvSdbaSU0PjA/Jyc6aS80XSsn7LKcLeyLreuwsSdbKGkrPTEpJTRdKycw7J287J207IK87IKs7Jik7Jyh7Lmg7YyU6rWsJ1tkXX0uam9pbi5yZXZlcnNlLmdzdWIgLygwLil7NH0ufDAufOydvCg/IS0pfC0vLCcnff// "Ruby โ Try It Online")
## Explanation
Takes input as integer and extracts the digits (listed from the least to most significant) using the convenient built-in available since Ruby 2.4.
Then, we combine the corresponding Korean digits with position markers and where necessary, 104 block markers. `-` is a placeholder for the missing markers of lower digits.
`์ฒ-์ญ๋ฐฑ` has such strange ordering because it is rotated by one place to compensate for the fact that we are also incrementing the counter `i` in the same step.
Finally, we reverse the resulting string back to normal direction and remove some redundant stuff with RegEx replacements:
* `(0.){4}.` : 4 \* (0+marker) + another marker = a completely empty 104 block.
* `0.` : zeroes at any single position
* `์ผ(?!-)` : ones followed by any meaningful (non-placeholder) markers
* `-` : finally, get rid of the placeholders themselves
## Alternative
Interestingly, a similar approach, but working with string input is just 1 byte longer:
```
->s{i=s.size;s.chars.map{|c|'0์ผ์ด์ผ์ฌ์ค์ก์น ํ๊ตฌ'[c.to_i]+'-์ญ๋ฐฑ์ฒ'[(i-=1)%4]+'-๋ง์ต์กฐ๊ฒฝ'[i%4>0?'':i/4]}.join.gsub /(0.){4}.|0.|์ผ(?!-)|-/,''}
```
[Try it online!](https://tio.run/##AacAWP9ydWJ5//8tPnN7aT1zLnNpemU7cy5jaGFycy5tYXB7fGN8JzDsnbzsnbTsgrzsgqzsmKTsnKHsuaDtjJTqtawnW2MudG9faV0rJy3si63rsLHsspwnWyhpLT0xKSU0XSsnLeunjOyWteyhsOqyvSdbaSU0PjA/Jyc6aS80XX0uam9pbi5nc3ViIC8oMC4pezR9LnwwLnzsnbwoPyEtKXwtLywnJ33//w "Ruby โ Try It Online")
[Answer]
# Wolfram Language 23 bytes
Mathematica has a built-in for this. (What a surprise!)
```
IntegerName[#,"Korean"]&
```
To save one byte...
```
#~IntegerName~"Korean"&
```
[Answer]
# [Haskell](https://www.haskell.org/), 270 bytes
```
(0#_)_=""
(n#1)_=[" ์ผ์ด์ผ์ฌ์ค์ก์น ํ๊ตฌ"!!fromInteger n]
(n#b)(c:r)|d<-div n b=[k |d>1,k<-d#1$r]++[c |d>0]++(mod n b#div b 10)r
t=10^4
(n%1)_=f n
(n%b)(c:r)|d<-div n b=[k |d>0,k<-f d++[c]]++(mod n b%div b t)r
f n|n<t=n#1000$"์ฒ๋ฐฑ์ญ"|1>0=n%(t^4)$"๊ฒฝ์กฐ์ต๋ง"
```
[Try it online!](https://tio.run/##nVXLbtpAFN3zFZOBSLZwpRkbEhzF2VdqV@0OkQhi56GAQbbTdsEq22ZZVVkQKUiRsiESRWQRif5Q4n4DvXcetgtk05FsnTn3@tzHXIazdnwRdLvLpcHKR@aRR2nJCMscUJOS9HaR3s7Tq0V6NUlv7tPROH2@@3P94@VpQre2TqJ@732YBKdBRMIWftYxjeO9yBz6@@/88y8kJB2veUGG/gG3LoAq80rUqlabx0gxQEav76NXGb07hDMzKiUeZ4c1UNvGJE5IiPBNYYbCJ8RH1VZBcVsqJiAIEsNwP/GgKsZYhaaz0ev0V/r9kQ75AfPCbSM5rJkV@jL7nY6n6c@n14drugy@tXuDbhCTvT3SNFSZFvmUROfhqdkqZXYPzNyi0CpqWoaNaI7IAXQluBqiCaI6oJt7RDuARmNEu4Ce7xA1LAq9ReRaFFsMiDMwQ6oIuYAqELfVTgTjjtzJgLbIZ547264mlKzDRHZKuc5EXmrnNkR02OlsXE1kScEH0EOJbYF1Ilyaspy53mZ5M@2vfWxeYDI3p0iqujAuMCq0zbOtlmLCYzZS3tKe7WsNvcd5zuqzee6YS/MCpdvImVNkZVZuY3dHNmg2AkU0PN9h0vJ8MSchv8C5UgTXRF4uq@ecTHGBUnJcbKdW35HFgh0OTpQg7SuhVDeVTt5QMHKcA9ktMGfd1acKQZhuoGqrGBGMpFIXLmL0Nrnk8@i6zMVH9wXe4Ivvh@sVRrrLteYus1v/6J9ZlEt0D369RZJrstAExgvOeJCQtxwQzCBX2xhR6buF9bbn/9eS1zOe6lFmxZrmeFOpoXQ22eSI5IWzlSXU4cZbVWesXpc/BrwOb@6zEdPHv/psGgX8dI3ErNZJcQQbJmmNpHDn9trnIdy3fr9EYHWDhCRBnBihFZtDuOU9L/aiILmMQmKY4m4PoqgfkQqJz/pf4V@hWiUU8WXXJ50AMBDCFEtT2E9y0gBFUwTqtQcfj0Qoom99wQ8uE/g7@BBCAPoZrDEZtOM48Lfo8i8 "Haskell โ Try It Online")
This could probably be improved as there is a bit of duplication but I can't think of a good way of unifying the `#` and `%` operators.
Both of those operators work in a similar way but `#` is for `n<10^4` and `%` is for big numbers. They take the number `n`, the current "base" `b` and a list of characters representing the relevant powers of ten in decreasing order. First I divide `n` by `b` to get `d` and stick it's korean representation in front if it's greater than 1 (in the case of numbers less than ten thousand) or 0 (otherwise). Then I insert the representation of the power itself (which should correspond to `c`) if `d>0`. Then we just recur by modding `n` by `b` and dividing b down to get the base corresponding to the next character.
When we reach `n==1` in `#` We know it's down to a one digit number so we just index into a list (I need `fromInteger` because `Int` isn't large enough to store numbers as large as `10^20`). When `n==1` in `%` then `n` is now `<10^4` so we recur to `#` (via `f`) to do the rest of the number.
] |
[Question]
[
Given a "T" shape on an x \* y number grid, with length W on the top bar and H on the stem of the T, with the bottom of the T on the square numbered n: calculate the total of all of the numbers in the T shape. W must be an odd number and all must be positive integers.
Here are some examples of valid T's on a 9\*9 grid:
[](https://i.stack.imgur.com/u3pMQ.png)
Looking at the T where `n=32, W=3 & H=4`, you can see that the total is:
`4 + 5 + 6 + 14 + 23 + 32 = 84`.
# The Challenge
Your challenge is to create a program which, when given five positive integers, x, y, W, H and n, output the total of the T with those values (W must be odd, given an even number the program can output anything or even crash). The numbers may be inputted in any reasonable format. If the T does not fit on the given grid, then any output is acceptable.
# Example Code (Python 3.6.2)
```
x = int(input())
y = int(input())
W = int(input())
H = int(input())
n = int(input())
total = 0
#"Stem" of the T
for i in range(H - 1):
total += n - (x * i) #Decrease increment by length of row each time
#Top of the T
for i in range(-W//2 + 1, W//2 + 1): #Iterate over the width offset so that the center is zero
total += (n - (x * (H - 1))) + i #Add the top squares on the T, one less to the left and one more to the right
print(total)
```
As with most challenges here this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer with the shortest code in bytes wins.
[Answer]
## JavaScript (ES6), ~~32~~ 30 bytes
*Saved 2 bytes thanks to @Shaggy*
```
(w,h,x)=>Q=n=>--h?n+Q(n-x):n*w
```
Takes input in a curried format: `f(W,H,x,y)(n)`
```
let f =
(w,h,x)=>Q=n=>--h?n+Q(n-x):n*w;
console.log(
f(3, 4, 9, 9)(32)
);
```
### How?
First we note that the sum of the T starting at **n** with height **H** can be broken down into two sums:
* **n**
* The sum of the T starting one row higher with height **H - 1**
By repeatedly adding **n** to the total, moving one row up, and subtracting **1** from **H** until it reaches **1**, we end up summing the vertical stem of the T. Moving one row up is accomplished by subtracting **x** from **n**, since it can be observed that the difference between any cell and the one above is **x**.
When **H** reaches **1**, we now have only the crossbar of width **W** left to sum. At this point **n** represents the center of the crossbar. We *could* sum the crossbar recursively as we did with the stem, but instead we take advantage of a fairly simple formula:
```
sum(n - a : n + a) = (n - a) + (n - (a-1)) + ... + n + ... + (n + (a-1)) + (n + a)
= (n - a) + (n + a) + (n - (a-1)) + (n + (a-1)) + ... + n
= 2n + 2n + ... + n
= n * (2a + 1)
```
In this case, our **a** is **(W - 1) / 2**, which makes
```
n * (2a + 1) = n * (((W - 1) / 2) * 2 + 1)
= n * ((W - 1) + 1)
= n * W
```
which is the sum of the crossbar.
[Answer]
# [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~64~~ 52 bytes
```
(x,y,W,H,n)=>{for(y=0;H-->1;n-=x)y+=n;return y+W*n;}
```
[Try it online!](https://tio.run/##bcyxCsIwEIDh2TxFxsReRa1LiekiiINOFjqHeEpAr9JLxVD67BUHN/n51t9z7tlPPQe6yXPiiA8jyD2Qn86jjIPwd8csI@IgOLoYvNz35LeBIvxRyVraSb0hQQMHIG2r4dp2KtmlOeR5tTKU27dOmSXTYew7kilr5mTGyfz@rzZc5MkFUnoQs11L3N5x0XQh4jEQqlqVUEIBGyjWWhsxfps@ "C# (Visual C# Compiler) โ Try It Online")
The non-recursive answer did indeed turn out significantly shorter. Gross misuse of for loops and the fact that `y` is officially a mandatory input even though it's not used.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
:q*-t0)iq*hs
```
Inputs are: `H`, `x`, `n`, `W`.
[**Try it online!**](https://tio.run/##y00syfn/36pQS7fEQDOzUCuj@P9/Ey5LLmMjLmMA "MATL โ Try It Online")
### Explanation
```
: % Implicit input: H. Push [1, 2, ..., H]
q % Subtract 1. Gives [0, 1, ..., H-1]
* % Implicit input: x. Multiply. Gives [0, x, ..., x*(H-1)]
- % Implicit input: n. Subtract. Gives [n-0, n-x, ..., n-x*(H-1)]. This is
% the stem, bottom to top
t % Duplicate
0) % Get last element, that is, n-x*(H-1). This is the center top of the "T"
i % Input: W
q % Subtract 1
* % Multiply. Gives n-x*(H-1)*(w-1). This is the sum of the vertical bar
% excluding its center, which is already accounted for in the stem
h % Concatenate into a row vector
s % Sum of vector. Implicit display
```
[Answer]
# [Python 3](https://docs.python.org/3/), 38 bytes
```
lambda x,W,H,n:~-H*(x*(1-H/2-W)+n)+W*n
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCJ1zHQyfPqk7XQ0ujQkvDUNdD30g3XFM7T1M7XCvvf0FRZl6JRpqGpY6xjomOsZGm5n8A "Python 3 โ Try It Online")
-4 bytes thanks to Jonathan Allan
-4 bytes thanks to Kevin Cruijssen/Ayb4btu
[Answer]
# [Perl 5](https://www.perl.org/), 52 bytes
```
($x,$y,$w,$h,$n)=<>;say$h*($n+$x*(.5-$h/2-$w))+$w*$n
```
[Try it online!](https://tio.run/##FcJLCoAgFAXQeeu4A/@V4UD67KBFNAgMQqMCc/O9iHOO9dwdEcOjUBSyQlCIfBym/loKgmCIEo9gxmmE2mpkziWyQCTyla@6n33TcW8pXqRnZ5q2@QA "Perl 5 โ Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18 16~~ 15 [bytes](https://github.com/DennisMitchell/jelly)
-1 byte thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) (use of chain separator)
```
Sโรโต_รฐc2แธข+โธโPยคร
```
A full program taking `[H,W]`, `x`, `n` in that order (you can add `y` to the arguments if you like, it's not used).
**[Try it online!](https://tio.run/##ATEAzv9qZWxsef//U@KAmcOX4oG1X8OwYzLhuKIr4oG44oCZUMKkw5f///9bNCwzXf85/zMy "Jelly โ Try It Online")**
### How?
The total is:
* `n` multiplied by the number of squares used in the **T** (which is `W+H-1`)
* minus the width of the grid, `x`, times the triangle number of the
height (`1+2+3+...+h`) to account for the lack as we go up the stem
* minus the width of the grid, `x`, times one less that the height (`H-1`)
times one less that the width (`W-1`) to account for the lack at the
top of the **T**, excluding the lack we already accounted for at the top of the stem.
That is:
```
(W + H - 1) * n - ((H - 1) * (W - 1) + Triangle(H)) * x
```
The triangle number of `H` is its binomial with **2** A.K.A. `H-choose-2`.
```
c2แธข+โธโPยคร - Link 1: the x * (Triangle(H) + (H-1)*(W-1)): [H,W]; x
Sโรโต_รฐc2แธข+โธโPยคร - Main link: [H,W], x
S - sum H+W
โ - decrement H+W-1
โต - program's fifth argument (3rd input) n
ร - multiply (H+W-1)*n
รฐ - dyadic chain separation
c2 - choose-2 (vectorises) [Triangle(H), Triangle(W)]
แธข - head Triangle(H)
ยค - nilad followed by link(s) as a nilad:
โธ - chain's left argument [H,W]
โ - decrement (vectorises) [H-1,W-1]
P - product (H-1)*(W-1)
+ - add (H-1)*(W-1)+Triangle(H)
ร - multiply (by chain's right arg, x) ((H-1)*(W-1)+Triangle(H))*x
_ - subtract (H+W-1)*n-((H-1)*(W-1)+Triangle(H))*x
```
[Answer]
# [Python 3](https://docs.python.org/3/), 38 bytes
```
lambda x,W,H,n:~-H*(n-x*(W-1+H/2))+n*W
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCJ1zHQyfPqk7XQ0sjT7dCSyNc11DbQ99IU1M7Tyv8f0FRZl6JRpqGpY6xjomOMVD4PwA "Python 3 โ Try It Online")
[HyperNeutrino's arithmetic expression](https://codegolf.stackexchange.com/a/141921/20260) with improved grouping.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 49 37 bytes
```
(x,y,W,H,n)=>~-H*(x*(1-H/2d-W)+n)+W*n
```
[Try it online!](https://tio.run/##hcw9C4JAGMDxufsUN97pYy/am5guQTgUBAnOdh5xYM@Bd4Yi9tWNhpaGGv7bj78wntC1HBuj8EYvnbHyHhFRFcbQc0@MLawS9NCg2Cm08F2pm2slE5rRmI6shQ5ySAF5nDy91GGtwxZeOvNLL@cucjd3cIzI5/rQqqSnQiHjpCeTvUajKznNa2XlUaFkGQshhACWEPicR79IAOvVH7KB7fxNBjKMLw "C# (.NET Core) โ Try It Online")
A direct formula avoiding the need for looping or recursion. Unfortunately I had to use `2d` otherwise it was going to do integer division and truncate the fractional component. The `y` param is completely redundant and could be removed.
### Explanation
```
(n-x*(H-1))*W // Calculates the Top of the T
```
`(n-x*(H-1))` gets the cell index by subtracting from `n` the number of rows to go up multiplied by the grid width. Multiplying this by `W` gets the sum of the top bar of the T.
```
n*(H-1)-x*(H-2)*(H-1)/2 // Calculates the Stem of the T
```
I got this by using mathematical induction by trying to calculate the sum of *1, 10, 19, 28* where `n=28, H=4, x=9`. Which can be written as:
```
28 + (28-9) + (28-9-9) + (28-9-9-9)
28-9*0 + 28-9*1 + 28-9*2 + 28-9*3
28*4 -9*(0+1+2+3)
n*H -x*(1+2+3)
n*H -x*(3*(3+1)/2)
n*H -x*((H-1)*((H-1)+1)/2)
n*H -x*((H-1)*H/2)
```
but because we don't want to include the top cell of the stem (included in the formula for the Top of the T), `H` needs to be `H-1`. Making the formula
```
n*(H-1)-x*((H-2)*(H-1)/2)
```
Combining these two formulas gives
```
(n-x*(H-1))*W + n*(H-1)-x*((H-2)*(H-1)/2)
```
and simplifying it gives the formula used for the answer (though how it is rearranged can change how it looks).
### Acknowledgements
Saved 12 bytes thanks to Kevin Cruijssen. Though I'm not sure if the `;` should be included or not.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
A construction technique, which ends up much like [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/141923/53748)
```
แธถรแบกโตยตแนชรโถ+S
```
A full program taking `H`, `x`, `n`, `W` in that order (`y` may be appended if one so wishes).
**[Try it online!](https://tio.run/##ASkA1v9qZWxsef//4bi2w5fhuqHigbXCteG5qsOX4oG2K1P///80/zn/MzL/Mw "Jelly โ Try It Online")**
### How?
```
แธถรแบกโตยตแนชรโถ+S - Main link: H, x
แธถ - lowered range [0,1,2,...,H-2,H-1]
ร - multiply (vectorises) [0,x,2x,...,(H-2)x,(H-1)x]
โต - program's 5th argument (3rd input) n
แบก - absolute difference (vectorises) [n,n-x,n-2x,...,n-(H-2)x,n-(H-1)x]
- (note: for an in-range T n>(H-1)x) (cells of the stem)
ยต - monadic chain separation (call this stem)
แนช - tail (pop from AND modify stem) n-(H-1)x
- (cell at intersection of stem and top)
โถ - program's 6th argument (4th input) W
ร - multiply Wn-W(H-1)x
- (total value of the top)
S - sum (the modified stem) n+n-x+n-2x+...+n-(H-2)x
- (total value of the stem w/o top cell)
+ - add (add top to the stem w.o top cell)
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 23 bytes
```
+-*KEQ**JEQctQ2*tE-K*Jt
```
**[Try it here!](https://pyth.herokuapp.com/?code=%2B-%2aKEQ%2a%2aJEQctQ2%2atE-K%2aJt&input=4%0A32%0A9%0A3&debug=0)** (note the order of the inputs)
# How?
```
+-*KEQ**JEQctQ2*tE-K*Jt Full program. Q is input, E is evaluated input (reads a new line)
*KEQ The second input * the first input.
*JEQ The third input * the first input.
ctQ2 Float division of the the first input decremented by 1, by 2.
* Product.
- Difference.
tE The fourth input.
*Jt The product of the third input and the first input decremented by 1...
-K ... Subtracted from the second input
* Product.
+ Sum.
Output implicitly.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 14 bytes
I tried a few different solutions based on [ETH's observations](https://codegolf.stackexchange.com/a/141915/58974) but the shortest I've come up with (so far) is a straight port.
Takes input in the order `n,H,W,x`.
```
ยดVยฉรXnU)+UยชU*W
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=tFap31huVSkrVapVKlc=&input=MzIsNCwzLDk=)
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~100~~ ~~99~~ ~~96~~ 91 bytes
```
x->W->H->n->{int t=n,i=0,j=-W/2;for(;++i<H;t+=n-x*i);for(;j<W/2;t+=n-x*~-H+j++);return-~t;}
```
[Try it online!](https://tio.run/##nY89T8MwFEX3/AqPcR27qLAgJxlROjB16IAYTJpGzyS25bxU/VD614MLBjH3TVfnXj3paHVQ3LrG6N3nDL2zHokOTIwIndiPpkawRixkkrjxo4Oa1J0aBvKqwJBLQuINqDB0L3Gfrw02beOzO0kMZThyJsV85OWWlxUvDS8vYJBgYTIoHjJd8O1yJffWp5IxyCuJrDD8uAD6A3V@6yO88oppxqj0DY7e8CvKaQ5mN4NoF0UOFnakD47pBj2Y9u2dKN8O9J/y5jRg0ws7onBhgulZKOe6U/pMY3j8DU9/ZEWp/P4wJdP8BQ "Java (OpenJDK 8) โ Try It Online")
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 32 bytes
```
[0,:-1|i=:-(a*:)โg=g+i}?i*:+g-i
```
This takes parameters in the order `h, n, x, w`, and `y` is ignored.
## Explanation
Each time a variable is read from the cmd line in QBIC, using the `:` command, it is assigned a letter (a-z). For clarity, I will use `h, n, x, w` in the explanation instead of the `b,c,d,e` they would be assigned (`a` gets taken by the FOR-loop).
```
First, we want to know the total of the stem
[0,h-1| FOR a = 0 to the height - 1
i=n-(a*x) helper i holds an increment value: this is n, minus the
grid-width once for every row we go up.
g=g+i helper g is incremented by i for each row
} NEXT
? PRINT
i*w the center on the top bar times the width (ie the average)
-i corrected for that ione i we already counted in the stem
+g plus the stem itself
```
[Answer]
# Java 8, 35 bytes
```
(x,W,H,n)->~-H*(x*(1-H/2d-W)+n)+W*n
```
Port of [*@Ayb4btu* .Net C# answer](https://codegolf.stackexchange.com/a/141978/52210), after I golfed it a bit.
[Try it here.](https://tio.run/##LY4/D4IwEMV3P8WNLbQYwcUQnVlkYWAwDrVUU4SDQCEYg18dy5/k7pdc3r28l4te8KpWmGfvSRaibeEqNH53ABqNap5CKojnEyCrukehQBKrwMBmpgujhUhD@zbatdMaYbSEGBDOMJGBpSxiSPnlxyOHDA458GjvZzylLlI3dXAKV2NtM6xx8/eVzqC0hUhiGo2v2x0EXdskn9ao0qs649VWMgUS9CQ5sYAdWeDTrc04/QE)
---
If `y` is a mandatory input-parameter, it will be **37 bytes** instead ([Try it here](https://tio.run/##LY5PD4IwDMXvfooeN@gw/rkQomcucvHAwXiYY5ohFiLDQIx@9TmQpP0lzetrXylfUtSNprK4O1XJtoWDNPReABiy@nmVSkM2jgBF3V0qDYp5BXocOUzMJ6YTiSd@@ePbV2ulNQoyINiBYz0OmGOKxMX@K9KA9QFbiXS5LkTOQ@JhHpBL/tbG//LW@cKrNgU8fDB2tE9Dt9MZJP@nOg6t1Y@o7mzUeMlWxChSLMYYN7jFzZrPiT7uBw)):
```
(x,y,W,H,n)->~-H*(x*(1-H/2d-W)+n)+W*n
```
If outputting a double isn't allowed, it will be **40 bytes** instead ([Try it here](https://tio.run/##LY47D4IwFIV3f8UdW2gxgoshOrPIwsBgHGpBU4QLgUIwBv96LY/k3i@5j3NyCjEIXjc5FtnbyFJ0HVyFwu8OQKHO26eQOcTzuCxAkpkjm5kujBYiDe3PZNtWp4VWEmJAOIMhI0tZxJDyy49HDhmd2YOSA4/2fsZT6iJ1UwdNuKqb/lFa9WYy1CqDykYiiW4Vvm53EHTNk3w6nVde3WuvsSddIkFPkhML2JEFPt0iTeYP)):
```
(x,W,H,n)->~-H*(x*(int)(1-H/2d-W)+n)+W*n
```
If having a function instead of a full program isn't allowed, it will be **160 bytes** instead ([Try it here](https://tio.run/##TYyxDoIwFEV/pWMLFhVYDGHHwYmhA@nQ0CcphFcCFWMI/nrt4EDudE5Obq9Wxe0E2OvBe4MO5qdqgTy2xSlnWrJao8moDNLazQa7Riq23UPXwUxEifAmf6KqSSU7VaVINLRWQxBZEHgUuWRF/VkcjIl9uWQKl45@eRXRQ3SRLKJXXp1TzQWLkcUiQlbsu/f@Fpb53GfpDw)):
```
interface M{static void main(String[]a){Integer W=new Integer(a[2]),H=W.decode(a[3]),n=W.decode(a[4]);System.out.print(~-H*(W.decode(a[0])*(1-H/2d-W)+n)+W*n);}}
```
] |
[Question]
[
In [this question](https://codegolf.stackexchange.com/q/85108/53394) Tom learned that, in general, there are many motivations to choose to include case sensitivity in his programming language, because the possible combinations for a variable name are much more than what's possible with a case insensitive programming language for a name of the same length.
But, as a more meticulous person than him pointed out, even with case sensitivity, many combinations like `A_18__cDfG` are wasted anyway because no one will ever use them, so Tom decided to be an even more meticulous person and to redo the calculation of the difference of possibilities of variable names between a case sensitive programming language and a case insensitive programming language only counting the variable names that are likely to be used.
# The Challenge
Write a function (or a full program if your language doesn't support them) that takes an input `n` and returns (or outputs) the difference between the number of possible, **valid** combinations for a variable name of length `n` with case sensitivity and a variable name of the same length without case sensitivity.
# Valid names
You must only count names in which:
* The first character is either an alphabet letter or an underscore, but never a digit;
* If there are digits, they must appear at the end of the name, so that `x1` and `arraysize12` are valid but `iam6feettall` isn't;
* If underscores are present, they must appear at the beginning of the name, like in `__private` and `_VERSION` but unlike in `__init__` or `some_variable`;
* For case sensitive names, variables like `HeLlObOyS` aren't counted. A name must be either all uppercase (`HELLOBOYS`) or all lowercase (`helloboys`);
* There must be at least one alphabetic character. This means `_________a9999999999` is valid but `__` or `_4` arent't.
# Rules
* Regexs are, of course, allowed;
* Blame Tom's meticulousness.
# Testcases
```
Input (lenght of the varable name) -> Output (differences in valid combinations)
0 -> 0 (no combinations for both cases: 0 - 0 = 0)
1 -> 26
2 -> 962
3 -> 27898
4 -> 754234
5 -> 19898970
6 -> 520262106
```
# Scoring
It's again code golf. Shortes program in bytes wins.
# Reference, non-competing Lua implementation
Since the test cases may be wrong, I've been asked to include it, so here it is:
```
local case = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789"
local function isvalid(s) --checks if a string s is valid AND only suitable for case sensitive
if s:upper() == s then --if the string is all uppercase, it's also valid for case unsensitive
return false
end
return (s:match"^_*[%w]+[%d]*$" --checks if it matchs the underscore-character-digit sequence
and s:lower() == s) --checks if it's all lowercase
and true --trasforms to boolean value
end
local function each(s, n) --recursive function called for character at position 2..n
if n == 0 then
if isvalid(s) then
return 1
end
return 0
else
local total = 0
for i = 1, #case do
total = total + each(s..case:sub(i, i), n - 1)
end
return total
end
end
local function diff(n) --the actual function
local total = 0
if n > 0 then
for s = 1, #case - 10 do --loops for character at position 1, which can't be a digit
total = total + each(case:sub(s, s), n - 1)
end
end
print(string.format("%.0f", total)) --prints the result in non-scientific notation
end
```
[Answer]
# Haskell, 41 bytes
```
d n=sum[26^a*10^k|a<-[1..n],k<-[0..n-a]]
```
Runtime: O(k\*nยฒ), where k depends on the size of the resulting numbers.
## Results
```
ghci> forM_ [0..100] $ \n -> printf "%3d: %d\n" n (d n)
0: 0
1: 26
2: 962
3: 27898
4: 754234
5: 19898970
6: 520262106
7: 13555703642
8: 352737183578
9: 9174055661914
10: 238554336098650
11: 6202701627453786
12: 161273131202687322
13: 4193130300158759258
14: 109021676693016629594
15: 2834566482907321258330
16: 73698757444479241605466
17: 1916167982445349170631002
18: 49820370432467967325294938
19: 1295329660133056039346557274
20: 33678571452348345911899378010
21: 875642860649945882598272717146
22: 22766714405787481836443979534682
23: 591934574839363416636432356790618
24: 15390298948712337721436130165444954
25: 400147772695409669646228273190457690
26: 10403842090369540299690823991840788826
27: 270499894352496936680850312676749398362
28: 7032997253193809242590997018484373246298
29: 182857928583327929196254811369482593292634
30: 4754306143169415047991513984495436314497370
31: 123611959722433680136668252485770233065820506
32: 3213910952783564572442263453518914948600222042
33: 83561684772375567772387738680380677552494661978
34: 2172603804081793650970970094578786505253750100314
35: 56487698906126923814134111347937338025486391497050
36: 1468680171559302908056375783935259677551535067812186
37: 38185684460541904498354659271205640505228800652005722
38: 992827795974089805846110029940235542024837705841037658
39: 25813522695326337840887749667335012981534669240755867994
40: 671151590078484812751970380239599226408790289148541456730
41: 17449941342040605420440118775118468775517436406750966763866
42: 453698474893055743820331977041969077052342235464414024749402
43: 11796160347219449368217520291980084892249787010963653532373338
44: 306700169027705683862544416480371096087383351173943880730595674
45: 7974204394720347783315043717378537387160856019411429787884376410
46: 207329314262729042395080025540730860955071145393586063373882675546
47: 5390562170830955102560969552947891273720738669122126536609838453082
48: 140154616441604832669474097265534062005628094286064178840744688669018
49: 3644020027481725649435215417792774501035219340326557538748250794283354
50: 94744520714524866885604489751501025915804591737379384896343409540256090
51: 2463357538577646539028605622427915562699808274060752896193817536935547226
52: 64047296003018810014772635072014693519083904014468464189928144849213116762
53: 1665229696078489060384377400761270920385070393265068957827020654968429924698
54: 43295972098040715569996701308681932818900719113780681792391425918068066931034
55: 1125695274549058604819943122914619142180307585847186615491065962758658629095770
56: 29268077138275523725318810084668986585576886120915740891656603920614013245378906
57: 760970005595163616858291951090282540113887928032698152071960590824853233268740442
58: 19785220145474254038315619617236234931849975017739040842759864250335072953876140378
59: 514415723782330604996206398937030997116988239350103950800645359397600785689668538714
60: 13374808818340595729901369261251694813930583111991591609705668233226509316820270895450
61: 347745029276855488977435629681432954051084049800670270741236262952778131126215932170586
62: 9041370761198242713413326660606145694217074183706315928161031725661120298170503125324122
63: 235075639791154310548746496064648676938532817665253103021075713756078016641321970147316058
64: 6111966634570012074267408926569754489290742148185469567436857446546917321563260112719106394
65: 158911132498820313930952632379702505610448184741711097642247182499108739249533651819585655130
66: 4131689444969328162204768444761154034760541692173377427587315633865716109376763836198115922266
67: 107423925569202532217323979592678893792662972885396702006159095369397507732684748630039902867802
68: 2793022064799265837650423469698540127498126183909203141049025368493224089938692353269926363451738
69: 72618573684780911778911010215050932203840169670528170556163548469712715227294890073906974338634074
70: 1888082915804303706251686265620213126188733300322621323349141149101419484798556030810470221693374810
71: 49090155810911896362543842906414430169795954697277043295966558765525795493651345689961114652916633946
72: 1276344051083709305426139915569664073303583711018092014584019416792559571723823876827877869864721371482
73: 33184945328176441941079637804840154794782065375359281268073393725495437753708309686413713505371644547418
74: 862808578532587490468070582926132913553222588648230201858797125751770270485304940735645440028551647121754
75: 22433023041847274752169835156082344641272676193742874137217614158434915921506817348015670329631231714054490
76: 583258599088029143556415714058169849561978469926203616456546857008196702848066139937296317459300913454305626
77: 15164723576288757732466808565512704977500329106970182916759107171102003162938608527258593142830712638700835162
78: 394282812983507701044137022703333218303897445670113644724625675337540971125292710597612310602487417495110603098
79: 10251353137571200227147562590286692564790222476311843651729156447664954138146499364426808964553561743761764569434
80: 266535181576851205905836627347454295573434673272996823833846956528177696480697872363985921967281494226694767694170
81: 6929914720998131353551752311033814573798190393986806308568909758621508997387033570352522860038207738782952848937306
82: 180177782745951415192345560086879207807641839132545852911680542613048122820951761718054483249882290097245662961258842
83: 4684622351394736795000984562258859691887576706335081064592582996828140082233634693558305453385828431417276125881618778
84: 121800181136263156670025598618730354877965883253600996568296046806420531026963390921404830676920428105738068161810977114
85: 3166804709542842073420665564086989255716001853482514799664586105855822695589937052845414486488820019638078661095974293850
86: 82336922448113893908937304666261720937504937079434273680168127641140278974227252262869665537598209399478934077384220528986
87: 2140759983650961241632369921322804747264017252954180004573260207558536142218797447723500192866442333275341174900878622642522
88: 55659759574924992282441617954392923457753337465697569007793654285410828586577622529699893903416389554047759436311733077594458
89: 1447153748948049799343482066814216010190475662997025683091523900309570432139907074661086130377715017294130634232993948906344794
90: 37625997472649294782930533737169616267841256126811556649268510296937720124526472830077128278709479338536285378946731560453853530
91: 978275934288881664356193877166410022992761548185989361769870156609269612126577182470894224135335351690832308741503909460689080666
92: 25435174291510923273261040806326660598100689141724612294905512960729898804179895633132138716407608032850528916167990534866804986202
93: 661314531579284005104787060964493175553506806573728808556432225867866257797566175350324495515486697743002640709256642795425818530138
94: 17194177821061384132724463585076822564420065859805837911356126761453411591625609447997325772291543030206957547329561601569960170672474
95: 447048623347595987450836053211997386675210601243840674584148184686677590271154734536819358968469007674269785119457490529707853326373210
96: 11623264207037495673721737383511932053558364521228746428076741690742506235938911986846192222069083088419903301994783642661293075374592346
97: 302204869382974887516765171971310233392546366440836296018884172848194051023300600546889886662685049187806374740753263598082508848628289882
98: 7857326603957347075435894471254066068206494416350632585379877382941934215494704503108025942118700167771854632148473742439034118953224425818
99: 204290491702891023961333256252605717773371743714005336108765700845379178491751205969697563383975093250957109324749206192303775981672723960154
100: 5311552784275166622994664662567748662107694225453027627716797110868747529674420244101025536872241313413773731332368249888787064412379711852890
(0.72 secs, 632,190,360 bytes)
```
## Ungolfed
```
difference :: Integer -> Integer
difference n = sum [ 26 ^ alpha * 10 ^ digits
| alphas <- [1 .. n]
, digits <- [0 .. n - alphas]
]
```
## Explanation
All valid names have the structure, namely `[underscore]alpha[alpha][digit]`. We have at least one alphabet letter, arbitrary many underscores, and arbitrary many digits (as long as the resulting string has the correct length). The position of those is fixed by Tom's rules.
The number of valid case-insenstive combinations can be calculated as follows (`a` is the number of alphabet letters, `u` the number of underscores):
```
$$
c(n) = \sum_{a=1}^n \sum_{u=0}{n-a} 26^a \cdot 10^{n - a - u}
$$
```
[](https://i.stack.imgur.com/ofLBw.gif)
The number of valid case-sensitive combinations can be calculated similarly, we just add `\sum_{\{L,U\}}`:
```
$$
C(n) = \sum_{\{L,U\} \sum_{a=1}^n \sum_{u=0}{n-a} 26^a \cdot 10^{n - a - u} \\
= 2 \sum_{a=1}^n \sum_{u=0}{n-a} 26^a \cdot 10^{n - a - u}
$$
```
[](https://i.stack.imgur.com/GIhvo.gif)
The difference `C(n) - c(n)` isโฆ `c(n)`:
[](https://i.stack.imgur.com/zGWPs.gif)
So all we have to do is to find out is the count of case-insensitive variants.
[Answer]
## JavaScript (ES7), 55 bytes
```
n=>[...Array(n)].reduce(r=>r+26**++i*(10**n---1)/9,i=0)
```
I get the same results as @Zeta does. I started along similar lines although I simplified `sum(10**[0..n-i])` to `(10**(n+1-i)-1)/9`.
[Answer]
# Pyth, ~~25~~ ~~18~~ 16 bytes
```
sm*^26ds^LTh-QdS
```
[Try it online.](http://pyth.herokuapp.com/?code=sm*%5E26ds%5ELTh-QdS&input=5&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=sm*%5E26ds%5ELTh-QdS&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5&debug=0)
I also get the same results as @Zeta.
[Answer]
## 05AB1E, ~~18~~ 14 bytes
```
Lv1ยนy->ร26ym*O
```
**Explanation**
```
Lv # for each n in range(1,input)
1ยนy->ร # push 1 repeated (input-n+1) nr of times
26ym # 26^n
* # multiply the ones by the power of 26
O # sum and implicitly print
```
[Try it online](http://05ab1e.tryitonline.net/#code=THYxwrl5LT7DlzI2eW0qTw&input=Ng)
[Answer]
## Racket, ~~91~~ 82 Bytes
Old solution (based off @Zeta's solution):
```
(ฮป(n)(for*/sum([i(in-range 1(+ 1 n))][j(in-range(+ 1(- n i)))])(*(expt 26 i)(expt 10 j))))
```
New solution (thanks to Neil's solution):
```
(ฮป(n)(for/sum([i(in-range 1(+ 1 n))])(*(expt 26 i)(/(-(expt 10(-(+ n 1)i))1)9))))
```
[Answer]
# Emacs lisp, 106 bytes
```
(defmath f(n)(let((r 0))(for((k 1(1+ n)))(setq r(+ r(*(^ 26 k)(/(1-(^ 10(- n k -1)))9)))))(calc-eval r)))
```
Creates a function called `calcFunc-f`. Pretty much the first (Emacs) lisp I've written, uses Neil's optimization.
] |
[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 10 months ago.
[Improve this question](/posts/18506/edit)
~~I would like to propose a new kind of challenge: Anti Code Golf! (as anti-golf, not anti-code). The idea is to write the longest program you can write to do something.~~
That would be Code Bowling, as pointed out by ProgramFOX.
# Rules
* No ridiculously unnecessary whitespace (e.g. 3 lines between each statement, etc. indentation is OK, just don't overuse).
* Score is awarded by number of bytes used **to work** \* (in source code, input data or output data) memory usage doesn't count.
* Highest score wins. In the event of a tie, most upvoted wins. In the event of a voting tie a [randomly](http://xkcd.com/221/) chosen answer wins.
* You may not read from a external resource, such as a file or web service, except (when possible) the program's own source code and/or a file/service provided by the program itself.
* The program must run in a reasonable time (< 5 minutes) except where otherwise specified.
.\* Comments do not count for length.
---
Now, onto the challenge itself:
>
> Write a program that prints the full date of tomorrow to stdout (or equivalent) in ASCII encoding. It may or not receive any arguments, but the current date must not be input directly by the user.
>
>
>
[Answer]
# C# - ~500Kb -
Don't you love nested if's?
Used to work only for 2014 dates, but successfully refactored to work for any date :)
Cannot post code here, I just receive an error...
<http://pastebin.com/azGr3JSz>
(Will probably hang your browser, sorry)
[Answer]
# JavaScript, 2015 chars (all reasonably useful)
I believe this is in the spirit of the question. ;)
Based on [one of my previous answers](https://codegolf.stackexchange.com/a/12175/3808)
```
// we all know that OOP == good
function TomorrowManager() {
// constants == good too
this.values = {
ERROR: 1, // value on error
UNINITIALIZED: 2, // value when not initialized yet
OK: 0 // desired value
}
this.consts = {
HOURS_IN_DAY: 24,
MINUTES_IN_HOUR: 60,
SECONDS_IN_MINUTE: 60,
MILLISECONDS_IN_SECOND: 1000
}
this.value = this.values.UNINITIALIZED
}
TomorrowManager.prototype.setValue = function(num) {
if (typeof num !== 'number') throw new Error('cannot set value to non-number')
if (!this.value) this.value = this.values.ERROR // oh noes
else this.value = num
}
// initialize the value
TomorrowManager.prototype.initialize = function() {
this.setValue(this.values.OK) // set the value to ONE
return true // return true for success
}
// get the value
TomorrowManager.prototype.getValue = function() {
if (this.value == this.values.ERROR) { // if the value is ERROR
throw new Error('value not initialized')
} else return this.value // return the value
}
TomorrowManager.prototype.getTomorrow = function() {
return new Date(new Date().getTime() + this.consts.HOURS_IN_DAY * this.consts.MINUTES_IN_HOUR * this.consts.SECONDS_IN_MINUTE * this.consts.MILLISECONDS_IN_SECOND)
}
function TomorrowManagerFactory() {}
TomorrowManagerFactory.prototype.getTomorrowManager = function() {
return new TomorrowManager()
}
function getTomorrow() {
var m = new TomorrowManagerFactory().getTomorrowManager() // make a TomorrowManager
var success = m.initialize() // initialize the value
if (success) {
if (m.getValue() === m.values.OK) {
return m.getTomorrow()
} else {
throw new Error('bad value')
}
}
else {
// there was an error in the initialization
var retVal = m.values.ERROR // we will return an error
delete m // maybe it's corrupted
throw new Error('corrupted TomorrowManager')
return retVal // return an error in case the throw didn't work
}
}
alert(getTomorrow())
```
[Answer]
# Lua - 7159
```
-- Let's begin by implementing OOP
-- Lua does not have OOP but it has the tools to implement it
local class = {}
function class:inherit()
local class = {}
class.class = class
class.__index = self
class.ancestor = self
return setmetatable(class, class)
end
function class:new(initializer)
local object = initializer or {}
object.__index = self
setmetatable(object, object)
if self.__init then
self.__init(object)
end
return object
end
function class:super(meth, ...)
local ancestor = self.ancestor
local class = self.class
local __index = self.__index
self.__index = class.ancestor
self.class = class.ancestor
self.ancestor = class.ancestor.ancestor
return (function(...)
self.ancestor = ancestor
self.class = class
self.__index = __index
return ...
end)(self[meth](self, ...))
end
-- Now let's create a few classes used for counting
local counter = class:inherit()
counter.value = 1
function counter:setValue(value)
self.value = value
end
function counter:getValue()
return self.value
end
function counter:increment()
self:setValue(self:getValue() + 1)
end
local boundedCounter = counter:inherit()
counter.maxbound = 1
counter.minbound = 1
function boundedCounter:setMaxbound(value)
self.maxbound = value
end
function boundedCounter:getMaxbound()
return self.maxbound
end
function boundedCounter:setMinbound(value)
self.minbound = value
end
function boundedCounter:getMinbound()
return self.minbound
end
function boundedCounter:increment()
self:super"increment"
if self:getValue() > self:getMaxbound() then
self:setValue(self:getMinbound())
end
end
local signalingBoundedCounter = boundedCounter:inherit()
counter.signal = function() end
function signalingBoundedCounter:setSignal(value)
self.signal = value
end
function signalingBoundedCounter:getSignal()
return self.signal
end
function signalingBoundedCounter:setUservalue(value)
self.uservalue = value
end
function signalingBoundedCounter:getUservalue()
return self.uservalue
end
function signalingBoundedCounter:increment()
self:super"increment"
if self:getValue() == 0 then
self:getSignal()(self:getUservalue())
end
end
-- Other miscelaneous classes we will need
local formatStringBuilder = class:inherit()
formatStringBuilder.string = ""
function formatStringBuilder:appendString(string)
self.string = self.string .. string:gsub("%%", "%%%%")
end
function formatStringBuilder:appendFormat(specifier, length, decimals)
length = tonumber(length)
decimals = tonumber(decimals)
specifier = tostring(specifier)
local format = "%"
if length then
if length < 0 then
format = format .. "0" .. -length
else
format = format .. length
end
end
if decimals then
format = format .. "." .. decimals
end
format = format .. specifier
self.string = self.string .. format
end
function formatStringBuilder:getString()
return self.string
end
function formatStringBuilder:format(...)
return self.string:format(...)
end
local applicationFunction = class:inherit()
function applicationFunction:__call()
return self.callback(unpack(self.arguments))
end
function applicationFunction:__init()
self.__call = self.__call -- DO NOT REMOVE OR IT WILL NOT WORK
end
local case = class:inherit()
function case:__init()
self.cases = {}
self.handlers = {}
end
function case:addCase(case, handler)
self.cases[#self.cases + 1] = case
self.handlers[#self.handlers + 1] = handler
end
function case:execute(value)
for iterator, case in ipairs(self.cases) do
if case == value then
self.handlers[case]()
break
end
end
end
-- The main code:
local yearsFormat = formatStringBuilder:new()
yearsFormat:appendFormat"Y"
local monthsFormat = formatStringBuilder:new()
monthsFormat:appendFormat"m"
local daysFormat = formatStringBuilder:new()
daysFormat:appendFormat"d"
local todaysYear = tonumber(os.date(yearsFormat:getString()))
local todaysMonth = tonumber(os.date(monthsFormat:getString()))
local todaysDay = tonumber(os.date(daysFormat:getString()))
-- Let's store the year as a four-digit number
local thousandsOfYearsCounter = counter:new()
thousandsOfYearsCounter:setValue(0)
local hundredsOfYearsCounter = signalingBoundedCounter:new()
hundredsOfYearsCounter:setMaxbound(9)
hundredsOfYearsCounter:setMinbound(0)
hundredsOfYearsCounter:setValue(0)
hundredsOfYearsCounter:setSignal(thousandsOfYearsCounter.increment)
hundredsOfYearsCounter:setUservalue(thousandsOfYearsCounter)
local tensOfYearsCounter = signalingBoundedCounter:new()
tensOfYearsCounter:setMaxbound(9)
tensOfYearsCounter:setMinbound(0)
tensOfYearsCounter:setValue(0)
tensOfYearsCounter:setSignal(hundredsOfYearsCounter.increment)
tensOfYearsCounter:setUservalue(hundredsOfYearsCounter)
local yearsCounter = signalingBoundedCounter:new()
yearsCounter:setMaxbound(9)
yearsCounter:setMinbound(0)
yearsCounter:setValue(0)
yearsCounter:setSignal(tensOfYearsCounter.increment)
yearsCounter:setUservalue(tensOfYearsCounter)
for interator = 1, todaysYear do
yearsCounter:increment()
end
local monthsCounter = signalingBoundedCounter:new()
monthsCounter:setMaxbound(12)
monthsCounter:setMinbound(1)
monthsCounter:setValue(0)
monthsCounter:setSignal(yearsCounter.increment)
monthsCounter:setUservalue(yearsCounter)
for interator = 1, todaysMonth do
monthsCounter:increment()
end
local daysCounter = signalingBoundedCounter:new()
-- Depending on the months, there's different amount of days
local monthDaysCase = case:new()
monthDaysCase:addCase(1, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 31}})
monthDaysCase:addCase(2, function()
if todaysYear % 4 == 0 then
if todaysYear % 100 == 0 then
if todaysYear % 400 == 0 then
daysCounter:setMaxbound(29)
else
daysCounter:setMaxbound(28)
end
else
daysCounter:setMaxbound(29)
end
else
daysCounter:setMaxbound(28)
end
end)
monthDaysCase:addCase(3, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 31}})
monthDaysCase:addCase(4, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 30}})
monthDaysCase:addCase(5, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 31}})
monthDaysCase:addCase(6, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 30}})
monthDaysCase:addCase(7, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 31}})
monthDaysCase:addCase(8, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 31}})
monthDaysCase:addCase(9, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 30}})
monthDaysCase:addCase(10, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 31}})
monthDaysCase:addCase(11, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 30}})
monthDaysCase:addCase(12, applicationFunction:new{callback = daysCounter.setMaxbound, arguments = {daysCounter, 31}})
monthDaysCase:execute(todaysMonth)
daysCounter:setMinbound(1)
daysCounter:setValue(0)
daysCounter:setSignal(monthsCounter.increment)
daysCounter:setUservalue(monthsCounter)
for interator = 1, todaysDay do
daysCounter:increment()
end
daysCounter:increment()
local tomorrowsYear = thousandsOfYearsCounter:getValue() * 1000 + hundredsOfYearsCounter:getValue() * 100 + tensOfYearsCounter:getValue() * 10 + yearsCounter:getValue()
local tomorrowsMonth = monthsCounter:getValue()
local tomorrowsDay = daysCounter:getValue()
local dateFormat = formatStringBuilder:new()
dateFormat:appendFormat"d"
dateFormat:appendString"/"
dateFormat:appendFormat("d", -2)
dateFormat:appendString"/"
dateFormat:appendFormat("d", -2)
local tomorrowsDateString = dateFormat:format(tomorrowsYear, tomorrowsMonth, tomorrowsDay)
print(tomorrowsDateString)
```
Scoring: `perl -pe 's/--.*\n//g;s/\s/ /mg;s/ */ /g;s/(\W) (\S)/$1$2/g;s/(\S) (\W)/$1$2/g;' < nextday.lua|wc -c` (basically remove all whitespace that can be removed)
Also do not remove the `DO NOT REMOVE` marked line, it really will not work
[Answer]
## C#: 33,053 characters
I had to post the code on Pastebin because it was too long to post here in an answer:
<http://pastebin.com/SwwB30Jy>
How it works: the byte array actually contains the following code:
```
using System;namespace GetDateOfTomorrow{public static class Tomorrow{public static string GetDateOfTomorrow(){ return DateTime.Today.AddDays(1).ToShortDateString();}}}
```
Then, you compile that code to a new assembly and execute the `GetDateOfTomorrow()` method.
[Answer]
# Mathematica 958
The following returns tomorrow's date, including the day of week.
```
date = "Date";
command1 = ToExpression[date <> ToString[Head["Calendar"]]]
ClearAll[a, b, c, d]
TreeForm[a + b^2 + c^3 + d]
command2 = ToExpression[date <> ToString[Part[%, 0]]]
months = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"}
command3 = ToExpression[date <> ToString[Head[months]]]
daysOfTheWeek = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"}
days = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
command4 =
ToExpression[
StringJoin[
Take[Characters[
Part[daysOfTheWeek[[RandomInteger[{1, 7}]]]]], -3] /. {char1_,
char2_, char3_} :>
StringJoin["", {ToUpperCase[char1], char2, char3}],
ToString[Head[days]]]]
AstrologicalSigns = {"Aries", "Taurus", "Gemini", "Cancer", "Leo",
"Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius",
"Pisces"}
```
## Testing
```
command1[command2[command3[TimeZone -> $TimeZone],
Fibonacci[7] - Length[AstrologicalSigns]], {"DayName", ", ",
"MonthName", " ", "Day", ", ", "Year"}]
```
>
> "Wednesday, January 15, 2014"
>
>
>
[Answer]
# JAVA (~~2910~~ 4406 characters)
```
import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.Date;
public class Tomorrow {
private static class DayOfMonth {
private int value;
public DayOfMonth(int value) {
this.value = value;
}
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
@Override
public String toString() {
return Integer.toString(value);
}
}
private static class MonthOfYear {
private int value;
public MonthOfYear(int value) {
this.value = value;
}
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
@Override
public String toString() {
return new DateFormatSymbols().getMonths()[this.getValue()];
}
}
private static class YearOfEverything {
private int value;
public YearOfEverything(int value) {
this.value = value;
}
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
@Override
public String toString() {
return new StringBuilder("").append(Math.abs(value)).append(' ').append((value < 0) ? "BCE" : (value == 0) ? "" : "CE").toString();
}
}
private static class DateManager {
private DayOfMonth day;
private MonthOfYear month;
private YearOfEverything year;
public DateManager() {
this.day = null;
this.month = null;
this.year = null;
}
public void setDayOfMonth(int day) {
this.day = new DayOfMonth(day);
}
public void setMonthOfYear(int month) {
this.month = new MonthOfYear(month);
}
public void setYearOfEverything(int year) {
this.year = new YearOfEverything(year);
}
public DayOfMonth getDayOfMonth() {
return day;
}
public MonthOfYear getMonthOfYear() {
return month;
}
public YearOfEverything getYearOfEverything() {
return year;
}
@Override
public String toString() {
return new StringBuilder("").append(this.getMonthOfYear().toString()).append(' ').append(this.getDayOfMonth().toString()).append(", ").
append(this.getYearOfEverything().toString()).toString();
}
}
public static final int MONTHS_PER_YEAR = 12;
public static boolean isLeapYear(YearOfEverything year) {
int yearNum = year.getValue();
if ((yearNum % 4 == 0) && (yearNum % 100 != 0))
return true;
else if (yearNum % 400 == 0)
return true;
else
return false;
}
public static int getDaysInMonth(MonthOfYear month, YearOfEverything year) {
if (month.getValue() == 1) {
if (isLeapYear(year))
return 29;
else
return 28;
} else if ((month.getValue() == 3) || (month.getValue() == 5) || (month.getValue() == 8) || (month.getValue() == 10)) {
return 30;
} else {
return 31;
}
}
public static void main(String[] args) {
DateManager manager = new DateManager();
Calendar calendar = Calendar.getInstance();
manager.setDayOfMonth(calendar.get(Calendar.DATE));
manager.setMonthOfYear(calendar.get(Calendar.MONTH));
manager.setYearOfEverything(calendar.get(Calendar.YEAR));
manager.getDayOfMonth().setValue(manager.getDayOfMonth().getValue() + 1);
if (manager.getDayOfMonth().getValue() > getDaysInMonth(manager.getMonthOfYear(), manager.getYearOfEverything())) {
manager.setDayOfMonth(1);
manager.getMonthOfYear().setValue(manager.getMonthOfYear().getValue() + 1);
if (manager.getMonthOfYear().getValue() >= MONTHS_PER_YEAR) {
manager.setMonthOfYear(1);
manager.getYearOfEverything().setValue(manager.getYearOfEverything().getValue() + 1);
}
}
System.out.println(manager.toString());
}
}
```
[Answer]
# Hippopotomonstrosesquipedalian 2, ~66.6MB
[Code (Your browser ***WILL*** hang)](https://gist.github.com/PlaceReporter99/267b8a9de71416bfbba40c585f7102ab)
[Compiler](https://gist.github.com/PlaceReporter99/d3c18f6edeac87aebf62a92b8629c2e9)
] |
[Question]
[
You will write a Program which writes the Second Program.
Each program has one Input; which may be a command line argument, or be read from stdin. A Input is a single word made up of upper and/or lowercase letters (a-z)
Each program has Output; which may be to a file, or to stdout.
The Program (which you post here)
* accepts the Input Greeting, e.g. "Hello"
* the Output contains the source code of another program, which is described below
The Second Program
* accepts a Input of Name, e.g. "John"
* MUST NOT contain the Greeting in a format that could be read by an average computer programmer
* when executed makes the Output in the format of `{Greeting} {Name}`, e.g. "Hello John"
* MUST NOT use an encoding library or function, including but not limited to
+ base64/base32/baseN (unless manually implemented)
+ cryptography (unless manually implemented)
*"not be read by an average computer programmer"* is ambiguous, but here are some examples for the Greeting "Hello". Use common sense, and I'll downvote if you do one of those *Well he didn't say "He" + "ll" + "o" was against the rules*
* Good
+ "Dqkta"
+ [9,3,5,1,6,1,5]
+ โโโง
+ a^|12..7
+ ..--..--!!--.--.----.-,,--.
* Bad
+ "Hello"
+ "hEllo"
+ "h3110"
+ "He" + "llo"
+ ["H", "e", "l", "l", "o"]
+ "H\_e\_l\_l\_o"
---
Scoring:
* usual codegolf, least bytes wins
* addition command line arguments cost the usual 1 point
+ no command line arguments allowed for the Second Program
* scoring only applies to the first Program (the one you post here)
Please also include an example generated program and a description. If you're confused, see my example answer bellow.
[Answer]
## APL(Dyalog), 16/20
Losing to GS again...
```
'โ,โจโโUCS',โUCSโ
```
This may break the "no cryptography" rule. `โUCS` is a function to convert characters to unicode code points and back.
**Example**
First input: `Hello`
First output: `โ,โจโโUCS 72 101 108 108 111`
Second input: `John`
Second output: `Hello John` (Note the space before "Hello")
---
```
'โAV[','],โโ',โจโAVโณโ
```
Similar idea with the cryptography is manually implemented: Convert to/from index of some pre-defined character array (`โAV`) which includes all upper and lower alphabets.
[Answer]
## Tcl, 111
```
puts "binary scan [join [lmap a [split $argv {}] {format %c [expr [scan $a %c]+256]}] {}]ฤ \$argv a* a;puts \$a"
```
Exploits the way how Tcl converts strings to bytearrays.
The output for `Howdy` is
```
binary scan ลลฏลทลคลนฤ $argv a* a;puts $a
```
[Answer]
# Brainfuck ~~122 120 109~~ 106
```
+++++++[>++++++>+++++++++++++>++++<<<-]>+<,[[>.<-]>+++.>.<-.>++.--<--<,]>....>>[<<.>>-]<<+++.>.<--.++.>++.
```
[Answer]
## R ~~113~~ ~~109~~ 97 characters
```
cat(unlist(sapply(utf8ToInt(scan(,"",n=1)),function(x)c(rep("+",x),".>"))),rep("+",32),".>+[,.]")
```
Takes an input as stdin and output a BrainF\*\*k program that prints the input of the first program, a space and then takes a second input and output it, character by character, until an EOF character (or an empty input depending on the BF interpreter used).
Example output with first input `Salut`:
```
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .>+[,.]
```
which you can test [here](http://brainfuck.tk/).
Initial input can include printable ASCII characters from `!` onwards (spaces don't work because by default `scan()` uses spaces as separators). Example for `$!"ยง&`:
```
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .>+[,.]
```
[Answer]
### GolfScript, 15 / 11 characters
```
{)}%`'{(}%" "@'
```
Performs the same obfuscation as the example program. The resulting code for input `Howdy` is then
```
"Ipxez"{(}%" "@
```
For both programs input must be supplied on STDIN while output goes to STDOUT.
If it's ok to convert the string to codes only you can also take the 11 character solution
```
{}/32]`'\+'
```
(Thanks to Peter for an idea to save two more characters).
[Answer]
Here's a simple example. It's not competitive, but shows how it should work. This is JavaScript which runs on Node.js
```
var i, charCode, Greeting = process.argv[2], obfuscated = '';
// We're just doing a regular upshift of characters
// a becomes b, etc.
for ( i = 0; i < Greeting.length; i++ ) {
charCode = Greeting.charCodeAt(i);
obfuscated += String.fromCharCode(charCode + 1);
}
// You'll want to compress this somehow
var code = [
"var i, deObfuscated = '';", "var Name = process.argv[2];", "var Greeting = '" + obfuscated + "';",
"for (i=0; i<Greeting.length; i++) {", "charCode = Greeting.charCodeAt(i);",
"deObfuscated += String.fromCharCode(charCode - 1);}", "console.log(deObfuscated + ' ' + Name)"];
console.log(code.join('\n'));
```
I'll call this file Program.js. It can be tested like so:
```
$ node Program.js Howdy > Second.js
$ node Second.js Partner
Howdy Partner
```
Second.js contains this. Notice how "Howdy" doesn't appear visibly in this code.
```
var i, deObfuscated = '';
var Name = process.argv[2];
var Greeting = 'Ipxez';
for (i=0; i<Greeting.length; i++) {
charCode = Greeting.charCodeAt(i);
deObfuscated += String.fromCharCode(charCode - 1);}
console.log(deObfuscated + ' ' + Name)
```
[Answer]
## Ruby, 63
```
$><<"puts ''<<"+gets.chop.each_codepoint.to_a*'<<'+"<<' '+gets"
```
Output for `Hello`:
```
puts ''<<72<<101<<108<<108<<111<<' '+gets
```
Output for `asdfASDF1234!@#$<>,.`:
```
puts ''<<97<<115<<100<<102<<65<<83<<68<<70<<49<<50<<51<<52<<33<<64<<35<<36<<60<<62<<44<<46<<' '+gets
```
[Answer]
# PHP, 58 ~~61~~ ~~64~~ ~~74~~ Bytes
```
<?=0?~0 ." $argv[1]":strtr(file(__FILE__)[0],[~$argv[1]]);
```
The script replaces all `0` in its own source code with the inverted greeting. If run as `php greeter.php Hello`, the output is:
```
<?=รรรดรดร?~รรรดรดร ." $argv[1]":strtr(file(__FILE__)[รรรดรดร],[~$argv[1]]);
```
If you run this as `php greeter2.php John`, the output with full error reporting is
```
PHP Notice: Use of undefined constant รรรดรดร - assumed 'รรรดรดร'
PHP Notice: Use of undefined constant รรรดรดร - assumed 'รรรดรดร'
Hello John
```
otherwise, just `Hello John`
] |
[Question]
[
You are given an array A of non-negative integers. You can pick any non-empty subset, S from the array A. The score of a subset S is the sum of the elements in S raised to the power of K, i.e. for a subset S={s1,s2,โฆ,sm}, the score of S is (s1+s2+โฆ,sm)K. Output the sum of scores over all possible non-empty subsets of A modulo 998244353.
**Input**
The first line consists of two integers N (1โโคโNโโคโ1000) and K (1โโคโKโโคโ300), Then N integers follow: a1,a2โฆ,an (1โโคโaiโโคโ109)
**Examples**
Input:
```
3 2
1 2 4
```
Output:
```
140
```
**Note**
There are 7 possible non empty subsets:
{1}, 12=1
{2}, 22=4
{4}, 42=16
{1,2}, 32=9
{1,4}, 52=25
{2,4}, 62=36
{1,2,4}, 72=49
The total of all of them is 140.
**Test Case 1**
Input:
```
200 33
586675996 834662638 582661564 801031252 368588510 481535057 299143636 154810868 748560222 444723881 594265644 271475209 483236369 825333010 838212251 941340273 181680951 475018532 725610690 980879808 290253341 255300094 222425864 305836905 309362719 673795903 526752784 272885696 498600892 541576513 293569958 586502788 546400101 932614930 922795145 738713347 627678736 854811027 599387102 172776156 368969197 453280296 317871960 878976720 860453033 510602497 926525753 419146537 830612914 980672268 468005306 166335891 911567226 922140110 434524807 424093053 590300567 371183659 721172742 600311592 210722614 317227418 793158971 401617057 449556863 501677314 892013630 839176022 524835881 940550248 839561467 764011513 989141930 192333644 484181005 785400847 674841029 209630134 964257438 941649848 836682055 640053044 493288668 662886952 142491554 659229917 884165257 346190427 135295371 636702497 710634145 170177475 893751212 553144583 498928648 173846992 274295496 676101828 165556726 499077801 920844845 446218268 371964528 518465222 701401156 687218925 309703289 579304688 823881043 802733954 252512484 579282959 844367812 695500833 748122407 825455122 386300070 502934300 179547526 934792800 783118124 441360402 356559179 327130654 998543269 475814368 713846691 788491645 617178564 384577123 166216557 684039923 651593797 821711021 704057885 243187642 943485338 885996539 369725079 504573341 230128629 304769483 940749404 725863600 460266942 378887332 700635348 115095533 583723838 352744521 560578526 984014856 678045467 988770077 470484548 380200831 349213692 849092703 695155761 125390576 970541165 842717904 202532794 848261409 892205344 324076314 401291603 958139378 960397596 669808951 333662236 895479878 866907097 938228867 851281251 333564143 552098658 371049021 356458887 441896629 907071903 336678292 857795316 302950189 898249304 663033041 993067004 494024812 140930107 733086617 107029928 909953444 616400129 799844902 322302802 644050662 253833551 636316553 633766994 300303396
```
**Scoring**
The goal for this challenge is the produce the fastest algorithm (i.e, the algorithm with the smallest asymptotic complexity), and as such you should include an short analysis of your algorithm alongside your code.
[Answer]
# [Python](https://www.python.org), \$\mathcal O(NK^2)\$
```
from math import comb
from functools import lru_cache
M = 998244353
rec=lru_cache(None)(
lambda n,a,*A:(pow(a,n,M)+(len(A)and rec(n,*A)+sum(rec(n-j,*A)*pow(a,j,M)*comb(n,j)for j in range(n+1))))%M)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZZPbps3EMW3hU6hTQHJYQDOPw5ZIIsA3aYXKIpCcewmhi0Zjo2iZ-kmm_YqPUN7mv5GRgI0NWBBH_lx-PjmvUf9_uf9b4_vT8dPn_54erx-Of_-6_rhdLe9Ozy-3364uz89PG4vT3dvN-fR66fj5ePpdPvx89Ttw9PPl4fL91ebzZvtq-1aU90tbLN5uLp89WV298PpeLXfbW4Pd2_fHbbHdmgXr7_b3Z9-3R3asb3Zv9jdXh13r_eH47stK3dH5vcvPj7d7c5PL2_q-eL5_RvevyhMvHWzvz49bG-2H47bh8Pxl6vd8YXs-fv2zf75OP988_39w4fj47mOtosfpWnzn_b7zf-H7b_D9nn46_cXE9akOf_x1ZpaFHOMjLVGm-Zj6LDZYuoYEsPb7NJNNCg8ZswZ0ptPCYse2XQtcRs2mgSjfY7Z0meMrgpw91Sbk32X66CcN03xDO2LKqa1dLWpYWZsBIKpohrSlot51wT5lDH7YoyFXWaYttQY0sfqbc0-sz7A0quOQ0KE9d4Xu6m6ckBv1mOyVw--LRvAWG2k5YrVrYVCgeYsfMohB2z4mqP3ubSFS-QIMfYw5lYUQyOAN_nmwzvgwWw6xJeBSpXK4tHSZgqosrHnyJlwNYsrYTW8rJrv2iQ1sygvntdYsrI5R51dwWLCSlkDhnIu6ijfRueFTg_pCYQ7KxYsa2QgAqEzIyzhtA9RnoorVio9chjtLKZvY5jFXKAXdq_pQi_epTptHuqzg0Ud3ljTijAWj2yWIpAai35IHcC1QZlRCNZUelVjX9DDhwvaWCZslvSyy5AsDbmviDEHlRnLNFbAehfEUYpYkiWnVkBAOksbPSDfZ80iBAdLjkJcPVochtOzVpaiq1KdT3YXULeEfLpa_cgahd6GGtkKvbU1kEs6DkB_AwWc9xhjKju26jOkVT1aPfHNbBiGLwt_CBQtifAGI1rOgHt2OHekYS1Z3em5WOiiMdIQfz73DQkMlIte4EQyUTocWIZgh4acxR39liaXIufJezYdKcIztK9wVDIQEAZRZkdENbNUvHrmLHUqx-bIAeNDeQ30VqKixahYKBflWgCcqaTepK9sePZMdo68WtDCjnzg5Wzt7kZG4FM6gXs4q9AYr_d0ggt3E7EIn3NAU8A9ioV6bO7oCu97sIZ8QQK4Njs6wGfOA6ekKs5Ek1iIiozlRGAspwtkBCbAPbgyAsJXM5yNrsFCuofjyFW5MSum0J8Ua7iLKpNucfaGDHFXZR1zkSlq5QotDlHJ9G7QbHQVWRMYhZklKIcq7B6UiqZuMhGhohwjAQ0NMU6shoFqLCKrgy8wbT6nFJKjl-gPQnMs1F3KTufDK-HgAzfh1U4YE6B0a04CpPKvo5ew0oEE2RiVAtMqbdkXgSV6AR9BDLwzf5xDKplRyQRDeWZRjUqJBzkIh6ee0czqkaDYpfCLwmCqL0UA1UEUjswaV4KRpkllXOwCW7wH-YnKcRTTRCBO9lkZQN4jJFxkuMeq86N8DiaSaVCZTBWDXpzH4-JCAumoYK_kLxsP1crOEsQiBck_4jx7pR63RrmQzqAkpPG8gpbSddyDv0nrs9o7R4GXmosiszRE3FYXqhh2AEttloiXk6MHvCokMJqs26fOwa-GMgH4Kn47vSTGidbeKxm8kkkqDyowCUHuAONmRGeNJ-qgY3bjGoEMqsj5_gBBIlkvgDCEOir7yRwU1gGIt2iu4ZXKDSt10g-zhIZV91svMGvUDf_8Y-Lzb6R_AQ)
\$\mathcal O(NK^2)\$ (length of list times exponent squared) assuming that binomial coefficients and powers are O(1) (which is not true for general random access but can be achieved when the values to compute are nearby because then one can be computed from a neighbouring cheaply, cf. comment by @Bubbler. To be clear, I did *not* implement this optimisation because I didn't find it worth the clutter.) and the overhead of memoisation is negligible.
Does the large testcase in a second or so.
Additional testcases taken from @bsoelch.
### How?
Let \$f(K,S)\$ denote the desired quantity for exponent K and set (or multiset) S. I write \$2^S\$ for the power set. The recursion formula is obtained by choosing an element \$a\in S\$ and separating the subsets into those that contain \$a\$ and those that do not.
$$f(K,S) = \sum\_{C \in 2^S}\left(\sum\_{x \in C}x\right)^K = \sum\_{C \in 2^{S-\{a\}}}\left(\sum\_{x \in C}x\right)^K + \sum\_{C \in 2^{S-\{a\}}}\left(a+\sum\_{x \in C} x\right)^K \\ = f(K,S-\{a\}) + \sum\_{C \in 2^{S-\{a\}}}\left(a+\sum\_{x \in C} x\right)^K \\ = f(K,S-\{a\}) + \sum\_{C \in 2^{S-\{a\}}}\sum\_{j=0}^K \begin{pmatrix} K\\j \end{pmatrix}a^j \left(\sum\_{x \in C} x\right)^{K-j} \\ = f(K,S-\{a\}) + \sum\_{j=0}^K \begin{pmatrix} K\\j \end{pmatrix}a^j \sum\_{C \in 2^{S-\{a\}}} \left(\sum\_{x \in C} x\right)^{K-j} \\ =f (K,S-\{a\}) + \sum\_{j=0}^K \begin{pmatrix} K\\j \end{pmatrix}a^j f(K-j,S-\{a\})
$$
[Answer]
# [Python](https://www.python.org), \$O(N K \log K)\$
```
from functools import lru_cache
from sympy.discrete.convolutions import convolution_ntt
MOD = 998244353
@lru_cache(maxsize=None)
def factorial(n):
return n * factorial(n - 1) % MOD if n else 1
@lru_cache(maxsize=None)
def inverse_factorial(n):
return pow(factorial(n), -1, MOD)
def r(A, K):
if len(A) == 0:
return [1] + [0] * K
p1 = r(A[1:], K)
p2 = [pow(A[0], i, MOD) * inverse_factorial(i) % MOD for i in range(K + 1)]
p = convolution_ntt(p1, p2, MOD)[:K + 1]
rv = [(a + b) % MOD for a, b in zip(p1, p)]
return rv
def f(A, K):
return r(A, K)[-1] * factorial(K) % MOD
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hZbdbttFEMUlrpCf4n-DZMO22pnZ2Y9KlajEXQU8QBRFaWpTS4ltOU6hfRVuegMPxdPwGzstBoqo1Mjej_k4c85Z__r77t3hzXbz4cNvD4fVk_7HF-9W--3dtHrY3By229v7aX232-4P0-3-4erm-ubNcva4cFjfLWfHs_fv7nbvnr5e39_sl4fl05vt5u329uGw3m4-3T5bu9ocDrPZ9z9-Nz2fxuhairnNZrNvP2WY313_cr9-v3z-w3azXMxeL1fT6ppq9uvr2_lm8Ww28Y9UD_vNtJm-Pt-cnkyymL6aIvx6xe7y9n45yf-FX2_eLvf3y6v_TLPb_jw_30zTE0mRZUHoiLCfv0jTy8dLZL5dbuYvFtPz51M-rZ0Fu5DL6ZvpIl9S-8vj5k4AgxAX8uwywpwWlcWLyPyCs2lanxJy6d_lrj82vdrupzUHpv315qfl_CWJZHF5ike4f8xhvqOLnZ4CXzw7nj4d3r-N5PNrVl6dx75O06sI_369O11-DP7Y2v7tIx6rczw-bp7WLp7I5d-m9vIxwSMDvzzs9uvNYb6aX5CA4grN62IxO1vWZJ9dTHHWzpctSSr8dzYGG4eAOrj7dLfcr65utg-bw3I_P7vhvdbmY9TUrdSq1XryrrWK15J6lmyiTrLavXeXnEoXN8_eko4hxarVJM5q7rWnVrrXrKqplNLUeqeaUbQSriRtUpprHkQxjasjdXUzIxEVdBVVlzSKWMna6KdL7XmwxsUs3U1TU6-S68hp9Nxb_KGWHHEKwLhbznmQTbUoDZZk2Tu5svNpWKWMkWqzNnxkS65AoK1HfUqTFTTK6DXnPjR5EW_Vxchh7A0PhKpTXudTqSVTPDWbVinDqEqVyFI8NetNqKolctbWG1j1wEq4DS4j9rMmadpaQB44jzpktFRotWelFhNuyqgg1PogjvKpZg5ko3qgyFq4MUBZvTnEECZT3RqY5irKt8CKm8qMCohmLjO3Ws28D6oXssd2VC8lS0zaimvpmVq0gBt3UgDG5dqSNRFA9cE8JBoomoDMCARqKjmikZfqwaMI3BgmJGvMMkuVFhwqZbjXXonMWmvGDVDPAjmCEUNa0ClFIVTagxvZAb_02IUIhVpajYpjRoNm6J67MhReBetKJ7tQdWqAz1RjHi1WgTfBRlLBtzQqdGkFBcC_CgOOOWrtSsYUcwa0iMeoO7rpCcHwYaAPAaIh7iWBiIYywJ4Mx4kkpCUjF2Yu5joYjCTI305zgwIV5sIXMJHWYDoYWHNBDgk6SynwNzg5FDp3zlkvUBGcgX14gSUVAiEQZbe6xzCDxSO31oOdStu07CBelWNUb0EqRgyLhXAeqqWAI5TE68yVhEfNtEzLIzkjzNAHXI7SzsXwCHTKJFAPvQqDKXFOO3Whbl48iE8fwORgD2OBHpkXeIX2i3MHf4ECqLZleIDOCl_okqgoE04iISKy1joE4zpTwCMQAepBle4APpKhbHhNLTy2XlDkCN_oYVPwTwI11EWUzrToPUFD1BVex563JmqhCg0MYUkv2YDZmCq0xjCiZq7AHKKQ3QnlSYtJh4QKcwwHNDjEOrbqRlV1YFmZ-hzRtpNLQTlmCf8AtNUBu4PZrfCnhMOBB2pCqxkzxkCZVu8YSPhfhi9uwQNxvNHDBbqF25IXgjX4Qn0YMeUd8aMPCWeGJZ0aQjODaERqaJBGaJ54xjBjRgJjh4IvDAOpPBQCxARhODRLPAmGmzYio-IioMU5wG-wHEWxjQWi5NLDA_B7iISKDPVYTL6GzqkJZ6pExlPFgBfl8XXwIFFpDWMP5w8ZV9XwziDEwAXxP-y85XA9Xo1QIZOBSVDjdIORMnXUg75x6yPbM62AS-x5gBkcwm5jChEMOVBLJGuQl87hA1oVHBhOxusTffAjLkRAfWG_mVli41hrzuEMJZxJwg_CMDFB3gDjZYRniW_Egcdk4xkBDKLI8f2gggZlSxQIQrAjvB_PgWGZAtEWwzW0Er5hwU7mYdaAYcT7lqOYUeMHwV-_CD7z8vOb8SCL04-Pjz-D_wQ)
Continuing from [@loopy walt's recursion](https://codegolf.stackexchange.com/a/266507/92727), we have $$f(K, S) = f(K, S - \{a\}) + \sum\_{j=0}^K {k! \frac{a^j}{j!} \frac{f(K-j, S-\{a\})}{(K-j)!}} $$
so we look at the EGF \$f(S) = \sum\_{k=0}^{\infty} {f(k, S) \frac{x^k}{k!}}\$ and we have \$f(S) = (1 + e^{a x}) f(S - \{a\})\$, so we evaluate this using NTT, cutting off the terms greater than \$x^K\$. We do \$N\$ convolutions on arrays of length \$K\$, so the time complexity is \$O(N K \log K)\$.
[Answer]
# [Python](https://www.python.org), 428 bytes, \$O(m^{k+1})\$
*Ignores the input format requirements, `f` takes input `(l,k)` with `l` being the array and `k` being the power.
If it is really necessary I can add a parsing function (see 1), to the code, but this will not impact the total complexity and make it harder to check multiple cases at once*
```
from itertools import product
from math import comb
M=998244353
def prod(l): ## product over the list l
P=1
for x in l:
P*=x
if M:
P%=M ## only need result modulo M, so take mod M to make numbers smaller
return P
def f(l,k):
n=len(l)
S=0
for P in product(range(n),repeat=k):
S+=prod(l[i] for i in P)*pow(2,(n-len(set(P))),M)
if M:
S%=M ## only need result modulo M, so take mod M to make numbers smaller
return S
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fZZNbhtHEIWRXcBTDGAkIJU20FXV1T8BuM1OhgAtDS9km7IJUaRAUYhzlmy8SVa5SK6Q0-QrUv5RYGQhajjTVf361Xtv-Pufd78d3u-2Hz_-8XC4ft7_-e6v6_3udlofVvvDbre5n9a3d7v9Ybrb794-vDnMjk9vrw7vPz14s7t9Pc1m58sxupZibrPZ29X1sWC-Wfw8m6aLpfB5vdtPH6b1dtrEvenibPkh_q-vp_PjDW79sDznar86POy308Wpz_V8k26ObbbLzWpLSy4vl_mx40V0fAQ3319t363m20Xar-5WV4flqW66_Gl5QvNy_epYtI6ii8XZ3e7Xuab59nk0vl8d5heLxSKdL_6D6_IJrssTrtf7h8Pql93-zeozwC-oXsQGJzR6dnaC_RnL_cPtEcpnJKeFj6vY98WPUbVeLM7Obv4fyuPQvv97drdfbw_z6_lLSZrKq6SL9BXCL3cXT1faN1fat1ZGvX1j7en-YvZluSVJhT9_lcbTgidPvi7xXmvzMWrqVmrVaj1511rFa0k9SzZRZ7favXeXnEoXN8_eko4hxarVJM7d3GtPrXSvWZVTl9LUemfTUbTSriRtUpprHnQxjdKRurqZsREIuoqqSxpFrGRtwO5Sex7cozBLd9PU1KvkOnIaPfcWH2DJ0afAjLvlnAe7qRblgCVZ9s5e2bkaVoExUm3Who9syRUKtPXApxyywkYZvebchyYv4q26GHsYz4YHQ9WB17kqtWTAg9m0ShkGKlU6S_HUrDcBVUvsWVtvcNWDK6EaXkY8z5qkaWtBefA86pDRUuGoPStYTKiUUWGo9UEf5apmFmQDPVRkLVQMWFZvjjKEyVS3Bqe5ivItuKJSmVGB0Uwxc6vVzPsAvbB7PA70UrLEpK24lp7BogXeqElBGMW1JWsikOqDeUgcoGiCMqMRrKnk6Ma-oIePImhjmLBZY5ZZqrTQUCnDvfZKZ-61ZlTAehbEEYoY0kJOKYCAtIc2skN-6fEUIRSwtBqIY0aDw3B6amUougrVlc7uAurUIJ-pxjxa3IXehBrZCr2lUZFLKzgA_VUUcNyj1q7smGLOkBb9GHXHNz1hGC4G_hAoGuJeEoxoOAPu2eE4kYS1ZOTCzMVcB4ORhPjbaW5IoKJc9AIn0hpKhwNrLtghIWcpBf2GJoci58466wUpwjO0Dy-opCIgDKI8re4xzFDxyK31UKdybI7sMF6VZaC3EBUjRsVCOw_XAuBIJf06c2XDo2da5sgjOSPMyAdejtbOxcgIfMokcA9nFQZTYp12cOFu3kwIn3NAk8M9ioV6bF7QFd4vTg35ggRwbcvoAJ8VvnBKuuJMNImF6Mi91hEY5UyBjMAEuAdXukP4SIaz0TVYeCl6wZEjcqNHTKE_CdZwF1060-LsCRnirsg6nnlrohau0OAQlfSSDZqNqSJrAiMwU4Jy6MLuTitPWkw6IlSUYySgoSHuE6tuoKqDyMrgc0zbTimF5Jgl-oPQVgfqDmW3wkeJhIMP3IRXM2FMgDKt3gmQyL-MXtxCB-Jko0cKdIu0ZV8E1tAL-Ahi4B354xwSyYxKOhjCM4NudGp4kINwePoZw4wZCYodCr8oDKbyUAQQE0ThyCzxSjDStNEZFxeBLdZBfkPlOIrHRCBOLj0ygLxHSLjIcI_F5Gv4HEwkU6UzmSoGvTiPr4MXEkhrBHskf9i4qkZ2hiAGKUj-EectR-rx1ggXMhmUhDROFYyUqeMe_E1aH9WeOQq8xDMPMkNDxG1MIZphB7DEZg3xcnL0gFeFBEaT8faJc_BjK0wAvojfzCyJcaI150iGEskkkQcRmIQg7wDjzYjOEt_og47ZjdcIZNBFju8PEDQkWwIgDKGOyH4yB4VlAOIthmt4JXLDQp3Mw6xBw4j3Ww4wox5_EUzTs2eT2XS4ulndT4fdtNlt301X99P9bvNwWO-20_p-Wn24221X28P6ahM_hW5Ov2g-_Rz9Fw) (runs for ~30 seconds)
## Explanation
Idea: using the generalized binomial formula split the term for each subset into summands and count how often each combination of elements appears in the final sum.
Example:
```
{x,y,z}, 2 ->
0
x -> xยฒ
y -> yยฒ
x,y -> xยฒ yยฒ 2xy
z -> zยฒ
x, z -> xยฒ zยฒ 2xz
y,z -> yยฒ zยฒ 2yz
x,y,z -> xยฒ yยฒ zยฒ 2xy 2xz 2yz
```
Each term appears (counting different orderings multiple times) \$2^{len(l)-|\{\text{different elements in term}\}|}\$ times (the number of subsets a term appears in halves with each unique letter used in the term). So we can get the total sum by summing up the term multiplied by their frequencies.
## Running time
Let \$m\$ be the length of the list and \$k\$ be the exponent.
The program checks \$O(m^{k})\$ different terms, for each of terms the computation can be done in \$O(m)\$ elementary calculations. As each elementary computation modulo `998244353` can be done in \$O(1)\$ this gives a total running time of \$O(m^{k+1})\$
Combining all terms using the same elements and multiplying by the number of permutations would not reduce the running time as there are still \${m \choose k} \in O(m^k)\$ different terms
---
1parsing function:
```
def parse():
_,k=[*map(int,input().split())]
l=[*map(int,input().split())]
return l,k
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3o1NS0xQKEouKUzU0rbgUFOJ1sm2jtXITCzQy80p0MvMKSks0NPWKC3IygbRmLFBFDgH5otSS0qI8hRydbIgV6wqKgEo1oHZoQgQXrDRWMOIyVDBSMIEIAAA)
[Answer]
# [Rust](https://www.rust-lang.org/), \$\mathcal{O}(NK^2)\$
A port of [@loopy walt's Python answer](https://codegolf.stackexchange.com/a/266507/110802) in Rust.
---
### `src/main.rs`
```
use cached::proc_macro::cached;
use num::integer::binomial;
// use num::pow::pow;
const M: i64 = 998244353;
fn pow_mod(base: i64, exp: usize, m: i64) -> i64 {
let mut result = 1;
let mut base = base % m;
let mut exp = exp;
while exp > 0 {
if exp % 2 == 1 {
result = (result * base) % m;
}
exp >>= 1;
base = (base * base) % m;
}
(result+m)%m
}
#[cached]
fn rec(n: u32, a: Vec<i64>) -> i64 {
if a.is_empty() {
return 0;
}
let mut result: i64 = pow_mod(a[0], n as usize, M);
if a.len() > 1 {
let mut rest = a.clone();
rest.remove(0);
result = ( result+ rec(n, rest))%M;
for j in 0..=n {
let mut rest_j = a.clone();
rest_j.remove(0);
result = (result + (rec(n - j, rest_j) * pow_mod(a[0] as i64, j as usize, M)%M * binomial(n, j) as i64 %M))%M;
}
}
(result + M)% M
}
fn main() {
println!("{}", rec(2, vec![1, 2, 4]));
println!("{}", rec(2, vec![1, 2, 3]));
println!("{}", rec(3, vec![1, 2, 3, 4]));
println!("{}", rec(9, vec![3, 1, 4, 1, 5]));
println!("{}", rec(33, vec![586675996,834662638,582661564,801031252,368588510,481535057,299143636,154810868,748560222,444723881,594265644,271475209,483236369,825333010,838212251,941340273,181680951,475018532,725610690,980879808,290253341,255300094,222425864,305836905,309362719,673795903,526752784,272885696,498600892,541576513,293569958,586502788,546400101,932614930,922795145,738713347,627678736,854811027,599387102,172776156,368969197,453280296,317871960,878976720,860453033,510602497,926525753,419146537,830612914,980672268,468005306,166335891,911567226,922140110,434524807,424093053,590300567,371183659,721172742,600311592,210722614,317227418,793158971,401617057,449556863,501677314,892013630,839176022,524835881,940550248,839561467,764011513,989141930,192333644,484181005,785400847,674841029,209630134,964257438,941649848,836682055,640053044,493288668,662886952,142491554,659229917,884165257,346190427,135295371,636702497,710634145,170177475,893751212,553144583,498928648,173846992,274295496,676101828,165556726,499077801,920844845,446218268,371964528,518465222,701401156,687218925,309703289,579304688,823881043,802733954,252512484,579282959,844367812,695500833,748122407,825455122,386300070,502934300,179547526,934792800,783118124,441360402,356559179,327130654,998543269,475814368,713846691,788491645,617178564,384577123,166216557,684039923,651593797,821711021,704057885,243187642,943485338,885996539,369725079,504573341,230128629,304769483,940749404,725863600,460266942,378887332,700635348,115095533,583723838,352744521,560578526,984014856,678045467,988770077,470484548,380200831,349213692,849092703,695155761,125390576,970541165,842717904,202532794,848261409,892205344,324076314,401291603,958139378,960397596,669808951,333662236,895479878,866907097,938228867,851281251,333564143,552098658,371049021,356458887,441896629,907071903,336678292,857795316,302950189,898249304,663033041,993067004,494024812,140930107,733086617,107029928,909953444,616400129,799844902,322302802,644050662,253833551,636316553,633766994,300303396]));
}
```
### `Cargo.toml`
```
[package]
name = "rust_hello"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
cached = "0.26.2"
num = "0.4.0"
[profile.release]
lto = "y"
panic = "abort"
rand = "0.8.0"
```
### Build and run
```
$ cargo build --release
$ cargo run --release
140
100
3800
554473082
856382558
```
] |
[Question]
[
I honestly don't know what the point of this sort of calculation would be, but it should make fun golfing. Shortest code wins.
## Input (in no particular order)
* An array of integers, `a` (All elements will be integers less than the length of the array.)
* An index therein, `i`
* An iteration count, `n`
## Processing
* Store a number `x` with initial value of `0`.
* Do the following steps `n` times:
1. Add the current value of `i` to `x`.
2. Decrement `a[i]`.
3. If `a[i]` is negative, increment it by the length of `a`.
4. Set `i` to `a[i]`.
* After the iterations, add the final value of `i` to `x`.
## Output
After doing the above process, your program should output the final value of `x`.
## Example (n=5)
```
a i x
2,0,0,5,5,6,7,5,8,5 0 0
1,0,0,5,5,6,7,5,8,5 1 0
1,9,0,5,5,6,7,5,8,5 9 1
1,9,0,5,5,6,7,5,8,4 4 10
1,9,0,5,4,6,7,5,8,4 4 14
1,9,0,5,3,6,7,5,8,4 3 18
```
The program outputs `21`.
## Test Case Generator
```
function newTestCase() {
var a = Array(Math.floor(Math.random() * 50) + 25).fill(0);
a = a.map(Math.random).map(e => e * a.length).map(Math.floor);
var i = Math.floor(Math.random() * a.length);
for (var x = 0, n = 0, aa = [...a], ii = i; Math.random() * a.length >= .5;) {
n++;
x += ii;
aa[ii]--;
if (aa[ii] < 0) aa[ii] += a.length;
ii = aa[ii];
}
return {a, i, n, shouldOutput: x + ii};
}
```
```
<button type="button" onclick="console.log(newTestCase());">Generate</button>
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~54~~ 53 bytes
```
->a,i,n{i+(1..n).map{i=a[i]+=a[i]<1?a.size-1:-1}.sum}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ1MnrzpTW8NQTy9PUy83saA60zYxOjNWG0zaGNon6hVnVqXqGlrpGtbqFZfm1v4vKC0pVkiLjjbSMQBCUyA00zEHkhY6prEggdj/AA)
[Answer]
# [Python 2](https://docs.python.org/2/), 71 bytes
```
def f(a,i,n):x=0;exec"x+=i;a[i]+=len(a)*(a[i]<1)-1;i=a[i];"*n;print x+i
```
[Try it online!](https://tio.run/##FYdBCsMgEAC/Ijlp3IIGbEo2viR4kFbpQthKyMG@3hgGhpnyP78/nlr7pCyyjEDAaqneYKrpPVTtCeNGQfs9sYxqlPetVj0skr8bh5GxHMSnqJpaltsEpuM6T5i7X@ACCAPCqXYB "Python 2 โ Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), ~~86~~ 82 bytes
```
{a,i,n->var x=0;var y=i;(0..n).map{x+=y;a[y]+=if(a[y]<1)a.size-1 else-1;y=a[y]};x}
```
[Try it online!](https://tio.run/##LY4xC4MwEIV3f8WNCUbRgm0xRujYqUPH0uEGI6GaSkzFVPztNpHeg/e944Z3r7ftlN4m7ECW5KrtxRh0DHzajUJSB4LYFmSK6aSe0MAsMh7ohOIkS1NN0x6HZY6F4/hwz1goSUKocorpqL5NkkPTjR7ciXBY@bxu8qOhR6UJmnYsYe@u7tYo3dYUlgj8DH6znSaSqP93N0kOLPMqvI7s5P3MCsogY1BQGq3bDw "Kotlin โ Try It Online")
---
## Ungolfed
```
{a, i, n ->
var x=0
var y=i
(0..n).map{
x+=y
a[y]+=if(a[y]<1) a.size -1 else -1
y=a[y]
}
x
}
```
[Answer]
# [R](https://www.r-project.org/), ~~95~~ 83 bytes
```
function(a,i,n){for(j in 1:n){F=i+F-1
i=(a[i]=a[i]-1+(a[i]-1<0)*sum(a|1))+1}
F+i-1}
```
[Try it online!](https://tio.run/##JcdBCoMwEIXhvafIcqaZgFOwlWK2uYS4CEJgBCNYXVXPHqfID9/jrSWZzpW053GTJUMkoYy/tKwwGcmGP/qCFxscV@Ih9jL4P44t3NvV@PjuM8SDES2fVbDi@CwJRnhSrTXai95qSw0SK@UC "R โ Try It Online")
Takes `i` as a 1-based index, so it requires some adjustment to account for that.
[Answer]
# JavaScript (ES6), ~~57~~ ~~56~~ 55 bytes
*Saved one byte thanks to @Lynn.*
```
a=>n=>g=(i,x=0)=>n--?g(a[i]-=a[i]?1:1-a.length,x+i):x+i
```
Takes input in currying syntax in the format `f(a)(n)(i)`.
## Test Cases
```
f=
a=>n=>g=(i,x=0)=>n--?g(a[i]-=a[i]?1:1-a.length,x+i):x+i
;
console.log( /*21*/ f([2,0,0,5,5,6,7,5,8,5])(5)(0) )
console.log( /*2066*/ f([18,26,9,26,58,53,35,28,0,47,44,6,24,11,66,48,63,64,3,19,67,55,59,35,37,22,41,8,51,44,3,58,58,9,31,29,20,63,43,19,53,28,40,70,20,46,3,69,34,63,49,29,42,69,26,49,37,26,41,62,7,3,66,55,27,59,9,2,36,24,61,6,7])(63)(26) )
console.log( /*1182*/ f([58,3,43,19,8,8,50,24,31,10,8,17,23,2,8,19,19,45,9,46,7,4,6,31,33,19,8,18,37,11,57,28,35,20,22,35,42,38,7,2,48,28,5,17,54,35,5,35,29,9,22,39,27,49,62,40,0,48,52,42,40,24,26])(46)(39) )
```
[Answer]
# C, ~~66~~ 63 bytes
The first argument is the length of the array.
*Thanks to [Justin Mariner](https://codegolf.stackexchange.com/users/69583/justin-mariner) for saving 3 bytes.*
```
f(l,a,i,n,x)int*a;{for(x=i;n--;x+=i=a[i]+=l*!a[i]-1);return x;}
```
Getting negative after decrement means it is zero before that.
[Try it online!](https://tio.run/##FYtRCoMwEES/zSm2QiHRDWjBtrDkJNaPkDZlQdMSLATEs6eRB48ZmHH67VzOXs5okTFgUhzWxtLmP1Em01HQmtjYkafWzM3pCLpXqTVM8bX@YoDUMu253GCxHKQSm6iO5sYJDGwX7ApD4Yq34jsOO4nqG8vGy/r8fIQawcu@Q3AIxYNSJPb8Bw)
[Answer]
# [Python 2](https://docs.python.org/2/), 59 bytes
```
def f(a,i,n):x=i;exec"a[i]=i=~-a[i]%len(a);x+=i;"*n;print x
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI1EnUydP06rCNtM6tSI1WSkxOjPWNtO2ThfEUM1JzdNI1LSu0AZKK2nlWRcUZeaVKFT8T9OINtIxAEJTIDTTMQeSFjqmsToKBjoKppr/AQ "Python 2 โ Try It Online")
Similar to XCoder's, but makes use of simultaneous assignment, and python's delightful negative modulus, plus re-ordering some instructions to eliminate the extra addition.
[Answer]
# Java, 87 bytes
I went with a recursive method for this
```
int r(int[]a,int i,int n){return n>0?(i=a[i]>0?--a[i]:(a[i]=a.length-1))+r(a,i,--n):0;}
```
[see IDEone here](https://ideone.com/MoY6kE)
] |
[Question]
[
Write a [proper quine](https://codegolf.meta.stackexchange.com/questions/4877/what-counts-as-a-proper-quine?answertab=votes#tab-top) **containing at least one newline/linefeed** whose every unfurling is either itself a proper quine or outputs the original quine. Your answer can mix and match outputting itself and outputting the original quine.
# Unfurlings
Unfurlings consist of:
1. Appending spaces to make the input a rectangle.
2. Taking all lines above the bottom one and rotating them a quarter-turn clockwise about the lower-right corner so that the right edge is on the same level as the bottom edge.
3. Repeat step (2) until the string is a single line to find all unfurlings.
For example, the first unfurling of
```
GFE
HID
ABC
```
is
```
HG
IF
ABCDE
```
and the rest are
```
HG
IF
ABCDE
IH
ABCDEFG
I
ABCDEFGH
ABCDEFGHI
```
This process is automated with [this program](https://tio.run/##MzBNTDJM/f//0LZDC/Wcol0Or9VzOrz20G4dJV0FMFTSObQkNOjQsnPbju5NiDi8RvP/fyUlJW8uRycgBQA "05AB1E โ Try It Online") adapted from Emigna's answer [here](https://codegolf.stackexchange.com/a/139967/68261),where each step of unfurling in the output is delimited by a dashed line.
# Example
For example, if you have a program
```
K
AB
```
(no trailing spaces)
then it must be a proper quine and print itself(`'K\nAB'`, where `\n` represents a linefeed/newline).
According to the output of the unfurling program, we see that the next step in unfurling is
```
K
AB
```
(note trailing space)
This must either print itself(`' K\nAB '`) or the original program (`'K\nAB'`).
The next step in the unfurling is
```
AB K
```
This must either print itself (`'AB K'`), or the original program(`'K\nAB'`).
The byte-count of this program is `4` (`K`, `\n`, `A`, `B`).
# Score
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply, as usual.
[Answer]
# [Python 3](https://docs.python.org/3/), 48 bytes
```
_='\n_=%r;print(_%%_,end="")';print(_%_,end="")
```
[Try it online!](https://tio.run/##K6gsycjPM/7/nyveVj0mL95Wtci6oCgzr0QjXlU1Xic1L8VWSUlTHS4GF/r/HwA "Python 3 โ Try It Online")
I mean, it works :p
[Answer]
# [Python 3](https://docs.python.org/3/), 42 bytes
```
_='\n_=%r;print(end=_%%_)';print(end=_%_)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/nyveVj0mL95Wtci6oCgzr0QjNS/FNl5VNV5THUUgXvP/fwA "Python 3 โ Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 32 bytes
```
_="\n_=%p;print _%%_";print _%_
```
[Try it online!](https://tio.run/##KypNqvz/nyveVikmL95WtcC6oCgzr0QhXlU1XgnOjv//HwA)
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 11 bytes
OK, let's go with the obvious trivial solution. At least it's shorter than the Python and Ruby solutions that use the same trick.
```
{N\"_~"}_~
```
This code begins with a newline, which is ignored by the CJam interpreter. All the actual code is on the last line, which is not changed by the unfurling process. The extra spaces and newlines introduced by unfurling the empty first line are also ignored by the interpreter.
Otherwise this is just a trivial tweak of a (or perhaps *the*) standard CJam quine. `{N\"_~"}` defines a code block, `_~` makes a copy of it and executes it. Inside the code block, `N\` pushes a newline before the copy of the block on the stack and `"_~"` pushes the string `_~` after it. When the program ends, the CJam interpreter automatically prints everything on the stack, i.e. the newline, the code block and the `_~`.
[Try it online!](https://tio.run/##S85KzP3/n6vaL0Ypvk6pNr7u/38A "CJam โ Try It Online")
] |
[Question]
[
*this challenge was based on a sandboxed post by @dmckee*
Old fashioned cell phones were and are used heavily as texting platforms, unfortunately the keyboard has only 12 + a few buttons, and is therefor ill-suited to naive text entry.
Common solutions make use of the traditional telephone coding (generally with a modest extension for 'q' and 'z'):
```
2: a,b,c
3: d,e,f
4: g,h,i
5: j,k,l
6: m,n,o
7: p(,q),r,s
8: t,u,v
9: w,x,y(,z)
```
In this case we are interested in the one-press-per-letter schemes that offer up words matching words on a frequency basis. That is if the user type "4663" the phone will offer up words like "good", "home", "gone", "hood", "hoof", etc that code to 4663 in order of their frequency.
Your task is to read one or more input files and generate a frequency sorted dictionary that could be used to implement this scheme.
## Inputs
* All input will be plain ASCII text.
* You may accept input from named files, the standard input, or other conventional source supported by your implementation language, but there *must* be some mechanism to process several files in a single run.
* Non-letter, non-whitespace characters should be stripped from the input, this means that contractions will be coded *without* their apostrophe: `"don't" --> "dont" --> 3668`
* Words are a sequence of letters separated surrounded by whitespace
* All whitespace (space, tab, newline, beginning-of-file, end-of-file) is equivalent.
* Input will be all lowercase or caps your preference.
## Output
* The output consists of a ASCII text stream
* You may direct this to a file, the standard output, or any other conventional destination supported by your implementation language
* The output should consist of one line for each string of digits corresponding to at least one word in the input.
* Each line should consist of the digit string and a list of all corresponding words sorted by frequency with the most frequent coming first. A sample line of output would be
```
4663 good home gone hood hoof
```
* Tokens (digit strings and corresponding words) should be separated by a single space.
* Equally frequent words may be sorted in any order.
The winner is the shortest code.
## Test Cases
```
potato, potato, damd, fjefje, djfaejri
Top 1000 words used.
The potato was a down goat goat down game gill pont pint point.
```
More actual test cases will be given in about a week to prevent any sort of hard-coding action.
[Answer]
## Mathematica, 202 bytes
```
{g[#],##}~r~" "&@@@GatherBy[#&@@@SortBy[Tally@StringReplace[StringSplit@#,x_/;!LetterQ@x->""],-Last@#&],g=""<>ToString/@(\[LeftFloor]If[#<113,(#-91)/3,(#-88.2)/3.4]\[RightFloor]&/@ToCharacterCode@#)&]~(r=Riffle)~"
"<>""&
```
Note that `\[LeftFloor]` and `\[RightFloor]` are 3 bytes each.
[Answer]
## C++, ~~566~~ 533 bytes
-33 bytes thanks to Zacharรฝ ( about 20 bytes ) and user202729 ( about 12 bytes )
```
#include<map>
#include<string>
#include<fstream>
#include<regex>
#include<set>
using namespace std;using s=string;struct z{s d;int f;int operator<(z a)const{return f<=a.f&&d<a.d;}};regex r("[^a-z]");void g(){fstream e("a"),o("d",ios::out);map<s,int>m;while(!e.eof()){s t;e>>t;t=regex_replace(t,r,"");++m[t];}map<s,set<z>>t;for(auto a:m){s k;for(auto c:a.first)k+="22233344455566677778889999"[c-97];t[k].insert({a.first,a.second});}for(auto&a:t){o<<'\n'<<a.first<<' ';for(auto m=a.second.rbegin();m!=a.second.rend();++m)o<<m->d<<' ';}}
```
Uses a set to ensure that the words in the `z` struct are ordered, so a reverse iterator loop can be done.
[Answer]
# [Perl 5](https://www.perl.org/), 123 bytes + 1 (`-a`) = 124 bytes
```
y/A-Z//dc&$k{y/A-Z/22233344455566677778889999/r}{$_}++for@F}{$,=$";say$_,sort{$k{$_}{$b}-$k{$_}{$a}}keys%{$k{$_}}for keys%k
```
[Try it online!](https://tio.run/##NY1fT4MwFMXf@RSNqb5syATKMMbETsqfSVsdm@heFtSZGIwssBdC@tWtbWX34eb0nF/PPezbbyRl72B76zgf7xewHv4frut6nuf7PkIoCIK5mjAMr9U4rRjgTkwmn017Fys9vYVnN13Vw920a9rjoDpUPsA3YZ9kJUS977vzMRPqKzBGLWXCeQRSTgkocQESzgjIGMDK4rG1TgmgmGlHy1SzGsN5wQ1rZbFJTIsmKeaGUOaK6M2skm/yaDQWI6oPqpoEZ8zCi3sSxUmaLR9yyvjj06pYb57Ll9ftb3M4fjU/nbQpupxdzaRd/QE "Perl 5 โ Try It Online")
Takes input as uppercase.
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~245~~ ... ~~214~~ 210 bytes
```
import StdEnv
r=removeDup
$s=toString[48+min((toInt c-91-toInt c/113)/3)9\\c<-:s]
?f=foldr(\s-> \l=[(a+if(s==b)1 0,b)\\(a,b)<-l])(zip([0,0..],r f))f
@f=r[(s,reverse(map snd(sort(?[l\\l<-f| $l==s]))))\\s<-map$f]
```
[Try it online!](https://tio.run/##VVBNS8QwFLz3VzzqHhLauLvoQaVx97Aiggdhj03BbJOsgXyUJF1Q/O3WdBXBHGYyyePNe9Mbyd1kvRiNBMu1m7QdfEiwT@LBnYpAg7T@JHfjUCwiTX6fgnbH9vqmstohlPyTS9CT2zX5vS7X6yu8vMK3jPUNuYtdsVFUeSMCYpHcAzO0RbzSCkVKD3gNq/qAGUM8U0NMh9GHHlC7qleXl10dQGGsiq2ioUWxDvIkQ5TI8gGiEyjmUdGmNYyZhqhPWBhKY4fzYSw2JJctVDftE88bLZfAjYH0piMILyNk7ueX1@0rcCdA@WB5ygUSgoyjScWFdsOYgEJbyrKGUvwH9QdHz9Mvn2a28uj/sdC27AoKyvBktMvurQre/qQJCOaADCDm5oRidnRVVZVQZowY3GhB6D4BBsYAZVmfNYaGwBbOU3bTV5@7H@NEnp6n3bvjVvc/4iWbzsudxaN0Mpx/Dt8 "Clean โ Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~42~~ 41 bytes
```
>โq+91N+O:3ยซ9ยตโฌแธโ0x
ฤ@รยณแนQยตรโฌโธแนญ"Zแธโฌ0ฤแน/รf
```
[Try it online!](https://tio.run/##y0rNyan8/9/uUcPcQm1LQz9tfyvjQ6stD2191LTm4Y6eRw0zDSq4jnQ7HJ53aPPDnbMCD2093A6UetS44@HOtUpRD3fMB/IMjkx7uHO2/uEJaf8Ptz/c1eetAhSM/P9fKVVJR0EpBZVIgxPp@YklULoMROempuej0CmZuUoA "Jelly - Try it online")
Monadic link take a list of strings as argument.
The footer is for formatting the output to a form suitable for outputting. Without it, the monadic link returns:
```
[[3, ["d", "f", "e"]], [4628, ["goav", "goat"]], [6346, ["mego", "mdim"]]]
```
(that is, a list, each has the format `[number, list of words]`).
The `"Zแธโฌ0` idea was taken from [this answer](https://codegolf.stackexchange.com/a/145266).
---
Explanation:
The first link, which given a string and output its telephone number, is mostly a port from my Python answer.
```
>โq+91N+O:3ยซ9ยตโฌแธโ0x Link.
Implicit input, call it (st).
ยตโฌ Monadic link map for each character (ch):
>โq Larger than character 'q'? If yes, get 1, else get 0.
+91N add 91, and then negate. Current value = -((ch>'q')+91)
+O Add the ord (ASCII value) of ch. Get ch-(ch>'q')-91.
:3 Integer division by 3.
ยซ9 If the result is larger than 9, set it to 9. (ยซ : min)
With the list of digits obtained by
mapping the previous chain to characters:
แธ Convert from decimal digits to number.
โ Decrement.
0x Repeat that many digits of zero.
```
Then, the second link:
```
ร Sort by...
ฤ@ count. (frequency)
ยณ I have no idea what is this used for.
แน Reverse. (so that words with max count appear first)
Q Unique.
ยต With that value,
ร Map the previous link over this word list.
แนญ" Vectorize tack with...
โธ the word list.
Z Zip (transpose).
แธโฌ0 Filter out 0 from each element.
ฤ Enumerate.
รf Filter, keep elements with truthy...
แน/ last element.
```
[Answer]
# [Rรถda](https://github.com/fergusq/roda), 218 bytes
```
{g={|n|chars n|[("2223334445556667777888999"/"")[ord(_)-97]]|concat}m=new map
replace`[^\w\s]|_`,""|(_/`\s+`)|sort|count|m[g(_)]+=[-_,_1]if m[g(_1)]=[]unless[m[g(_1)]?]
keys m|sort|{|k|[k];m[k]|sort|_|[` $_2`];[`
`]}_}
```
[Try it online!](https://tio.run/##NZDdjoMgEEbvfQpieqFpm6b@VdOYfRBkgVWqjQINaMxGfHYXbJeLCTkcvhlQsqEbp08Blm1py8UIU3dUaSAMDPwoiuI4TpIkTdMsy2525XleFIV/8f0QStUEODwXN4RMLUVNx5WXgs2A05en2GugNSPwu5orjQwmJ983Ab6QSh9JaLRUo701idFw2NocdCzhGZ/wFT0fYEfXEJUQTWJgWsN/8oW8nv1qwN8Ji@kN7NGd2/Im2EACDjgi6A6JR9CK123dWikb0EnOwEw1aKVgwD6aWiQf3tgxO7NwxG075zqNDlrurmdHcid7ijM5lbthoWKuCm@W09B8wM9HdQ1tTGs/@A8 "Rรถda โ Try It Online")
[Answer]
# PHP, 273 bytes
```
<?$f=str_split;$w=explode(" ",preg_replace(['/\s+/','/[^a-z ]/is'],[' ',''],$argv[1]));$l=$f('22233344455566677778889999');foreach($w as$x){$z='';foreach($f($x)as$y){$z.=$l[ord($y)-97];}$a[$z][$x]++;}foreach($a as$n=>$b){arsort($b);echo$n." ".join(" ",array_keys($b))."
";}
```
[Try it online!](https://tio.run/##RVLbbpwwEH33V4xWSLAK2VWTzU10mw@h28jgAbsxtmWbEBLl17sdQ9Lygj2XM2fOsZPufP7@mHXHEP1TcFrFKpuO@Oq0FVhsYFM6j/2TR6d5i0Wd73@Gi31e5vv6F798g9NehfxU1jlQjA4Z9/1L/e203VaZPmZdkV9dXV1fXx8Oh5ubm9vb2zv67u/vH@jLt1VnPfJWFtkEPGSv2/fs7Zjn/8NdQUHKzCmzO2a6tl4UdL18uDtVHxmvs7dTnb2eLi6qj39dPIGZ44@s2b5zH6yPBR0rbKXNzI6W2v22yizbce/5/PSMc0gl292GbaqP8/k82CjRg0PTKo0COGiMkSLWIAg@Mz8O1sPEA0TJI8x2hEH1MkKIlOXQWyuARDMwcIHADWFoTRfnCM6OkUVpx16CKmE0YfRYgQLJ0yhhxyayYaYOGmcwBOg9TkwB3Xtqp03TRMY@aXoc@ErTrIGVLBNKEKjgHqFD1JSeoVlSjwQ2cRVTTwRph5XiyimC7Rb8FJqsEeipTnWUVrSvGjAXhAPRj8iozieitluIhkiLJ3AVJDUlXSY7asHY15w0OLYpOdgXhQRoAXlAoIUDlVKzWVQqqTRodLEEmRYxJI20GqmApgyuBGdHQ2VB86FcJjuYJAlBiURamZ6pZRPokgYTkgMJhn4L7Yl/lQ30EIjRpJICi50sKUYp4gSNpkWZT9MWtJbTHp8vAZoZWslNi8mxlUSnV/ZJf7JzSaa@Z2MnSBYlXNI4@aE//Zg8eQtcCE8yPtJLeMH1VSHplgoaMl8sGq@uMytLaPxy/mNdVNaE86X5Cw)
[Answer]
# Java 8, 480 + 19 = 499 bytes
A `Runnable` lambda. Byte count includes lambda and required import. Input and output are as specified through standard in/out. Input is in all lowercase. Dictionary items are not printed in any particular order.
```
import java.util.*;
```
```
()->{Map<String,Integer>f=new HashMap();new Scanner(System.in).useDelimiter("\\s+").forEachRemaining(n->f.put(n=n.replaceAll("[^a-z]",""),f.getOrDefault(n,0)+1));Map<String,Set>n=new HashMap();f.forEach((k,v)->{String c=k;for(int i=0;i<8;)c=c.replaceAll("["+"abc def ghi jkl mno pqrs tuv wxyz".split(" ")[i]+"]",++i+1+"");n.putIfAbsent(c,new HashSet());n.get(c).add(k);});n.forEach((k,v)->System.out.println(v.stream().sorted((y,z)->f.get(z)-f.get(y)).reduce(k,(y,z)->y+" "+z)));}
```
[Try It Online](https://tio.run/##XZJRa9swEMef408h/BJptkX7NnAdKGSwPpRB85hmIMtyolg@eZKcLin57NmpTmENByfpr@P0u9PtxUEUdlCwb7qL7gfrAtmjxsegDf9WJskw1kZLIo3wnjwLDeQ9mV1FH0TApdUgDHkZAURtFNmqsNQyaAvCHUl1oaxYvD@L4WEVnIZt/gRBbZVbtBWoN/JT@B1eUlbG00oKAOXo6uiD6rkGxkevlsroXgfU09dXn6WMt9b9EHL3onokwqQUikXLhzFQqIA7NRgh1aMxNF3/FsVpk@ZpyvKWI9svt1StGA2G5ncsu2es/A9upcICbsDaz@co7fJDrGYKJrLqSryiGgLR1V2pH76XTFbyK0CapaKWpFEt2e402XeG9GDJ8Md5EsYDeft7PKXcD0YHmpKUrfUmS5E4y3R2nyF3CbGyp/ax9goClfknHsJSFq@xLCoZF01DO1aeo3SDfG2oHQMfkD0YoAfug1Oip4x7/HfVUHrMTyw2MubD3bQ5MoYFNaNUmOsacsyQNDsxfP18meGY3IzEweqGxL@hU6vWGyLc1rM4PLMvA8LdCNjjZHZOzhdB6g@TkyXJXnS2TnqL/eptYYH0hUUPk4sCzC0azImNTS0mH5e5/ZD@AQ)
## Ungolfed lambda
```
() -> {
Map<String, Integer> f = new HashMap();
new Scanner(System.in)
.useDelimiter("\\s+")
.forEachRemaining(
n -> f.put(
n = n.replaceAll("[^a-z]", ""),
f.getOrDefault(n, 0) + 1
)
)
;
Map<String, Set> n = new HashMap();
f.forEach((k, v) -> {
String c = k;
for (int i = 0; i < 8;)
c = c.replaceAll(
"[" + "abc def ghi jkl mno pqrs tuv wxyz".split(" ")[i] + "]",
++i + 1 + ""
);
n.putIfAbsent(c, new HashSet());
n.get(c).add(k);
});
n.forEach((k, v) ->
System.out.println(
v.stream()
.sorted((y, z) -> f.get(z) - f.get(y))
.reduce(k, (y, z) -> y + " " + z)
)
);
}
```
`f` is my frequency map, and `n` collects words based on their numeric encoding. As usual with programs this long, this is probably far from optimal. Improvements are welcome.
I could have replaced `++i+1+""` in the number encoding step with `""+-~++i` for the same number of bytes. But I respect you all too much to do that.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~179~~ ~~156~~ 155 bytes
Thanks *[Rod](https://codegolf.stackexchange.com/users/47120/rod)* for -23 bytes!
Thanks [anonymous user suggestion](https://codegolf.stackexchange.com/review/suggested-edits/45688) for -1 byte!
```
def f(l):
d={}
for w in l:k=(*[min(27,ord(x)-91-(x>'q'))//3for x in w],);d[k]=k in d and{w}|d[k]or{w}
for k in d:print(k,sorted(d[k],key=l.count)[::-1])
```
[Try it online!](https://tio.run/##LY7NCoMwEITP@hS5ZVP8wXooTbEvIh6kiTYkJjamVbE@uzVYFoad3Y9h@tk9jc63jfEGNaAIDQNWLGsYNMaiEQmNFJUFnMpOaDhfImMZTCS@ZjFMd/zChKRp7tnJs2MVkRsrZVVIbxmqNVvG9etPxu7bkXs8aW@FdiCjwVjHGXgoknwuVPIwb@1ISWmcVWRrAPM9y89eErWmdl4@qOOt@QsTHU6GXgkHGO2tth8 "Python 3 โ Try It Online")
] |
[Question]
[
**Input:**
The input will be a string of any characters.
**Output:**
the output will be an emojified (discord emojis) version of the input string. The way it will work is as so:
**Letters:** a-z (case insensitive) will become ':regional\_indicator\_**lowercase letter here**:'
e.g 'A' will become ':regional\_indicator\_a:'
**Digits:** any digits (0-9) will become the word version of the digit like so ':**digit**:'
e.g '0' will become ':zero:'
**Whitespace:** any whitespace character that's matched with the regex: /\s/ will become ':white\_large\_square:'
e.g ' ' will become ':white\_large\_square:'
**Important notes:**
* The ':' surrounding the emoji's are necessary or else it won't display correctly in discord.
* Each emoji needs to be separated by 1 space or else it won't display correctly in discord.
* Trailing whitespace is allowed in the final output.
* Any other characters that it comes across should not be in the final output and will be ignored.
**Examples:**
**#1:** Input:
```
this is a test string 0123456789
```
output:
```
:regional_indicator_t: :regional_indicator_h: :regional_indicator_i: :regional_indicator_s: :white_large_square: :regional_indicator_i: :regional_indicator_s: :white_large_square: :regional_indicator_a: :white_large_square: :regional_indicator_t: :regional_indicator_e: :regional_indicator_s: :regional_indicator_t: :white_large_square: :regional_indicator_s: :regional_indicator_t: :regional_indicator_r: :regional_indicator_i: :regional_indicator_n: :regional_indicator_g: :white_large_square: :zero: :one: :two: :three: :four: :five: :six: :seven: :eight: :nine:
```
**#2:** input:
```
!?#$YAY 1234
```
output:
```
:regional_indicator_y: :regional_indicator_a: :regional_indicator_y: :white_large_square: :one: :two: :three: :four:
```
**#3:** input:
```
lots of spaces
```
output:
```
:regional_indicator_l: :regional_indicator_o: :regional_indicator_t: :regional_indicator_s: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :regional_indicator_o: :regional_indicator_f: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :white_large_square: :regional_indicator_s: :regional_indicator_p: :regional_indicator_a: :regional_indicator_c: :regional_indicator_e: :regional_indicator_s:
```
Examples as shown in discord:
[](https://i.stack.imgur.com/f8JX7.png)
**This is codegolf so the shortest code wins!**
[Answer]
# Python 2, ~~275~~ ~~268~~ 267 bytes
```
d=['']*256
d[48:58]='zero one two three four five six seven eight nine'.split()
d[9]=d[10]=d[32]='white_large_square'
d[65:90]=d[97:122]=map(lambda c:'regional_indicator_'+chr(c),range(97,122))
print' '.join((':%s:'%d[ord(c)])*(d[ord(c)]!='')for c in input()).strip()
```
It creates a large list of strings, iterates through the input string's characters and gets the string from the list using the character's `ord` value.
Works for ascii characters only. Replaces space, tab and newline only; any other whitespace will be discarded.
It did leave whitespaces in front so I had to strip it in the end.
I also tried doing it with regex, turned out to be longer (286 bytes):
```
import re
print re.sub('([ \t\n])|([a-z])|(\d)',lambda m:':'+['white_large_square','regional_indicator_'+m.group(m.lastindex),'zero one two three four five six seven eight nine'.split()[(ord(m.group(m.lastindex))-68)%10]][m.lastindex-1]+': ',re.sub('[^a-z0-9 \t\n]','',input().lower()))
```
[Answer]
## [C#](http://csharppad.com/gist/c6123ab5a87e52f51d562a2c69cfdac3), ~~296~~ 273 bytes
---
### Data
* **Input** `String` `i` The string to be converted
* **Output** `String` The input converted
---
### Golfed
```
(string i)=>{var o="";foreach(var c in i){var k=c|32;var t=k>96&&k<123?"regional_indicator_"+(char)k:char.IsWhiteSpace(c)?"white_large_square":c>47&&c<58?new[]{"zero","one","two","three","four","five","six","seven","eight","nine"}[c-48]:"";o+=t!=""?$":{t}: ":t;}return o;};
```
---
### Ungolfed
```
( string i ) => {
var o = "";
foreach( var c in i ) {
var k = c | 32;
var t = k > 96 && k < 123
? "regional_indicator_" + (char) k
: char.IsWhiteSpace( c )
? "white_large_square"
: c > 47 && c < 58
? new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }[ c - 48 ]
: "";
o += t != ""
? $":{ t }: "
: t;
}
return o;
};
```
---
### Ungolfed readable
```
// Receives a string to be converted
( string i ) => {
// Initializes a var to store the output
var o = "";
// Cycle through each char in the string
foreach( var c in i ) {
// Creates a temp int to check for 'a' - 'z'
var k = c | 32;
// Creates a temp string that checks if the char is a lowercase letter
var t = k > 96 && k < 123
// If so, "builds" a Discord letter
? "regional_indicator_" + (char) k
// Otherwise, checks if the char is a whitespace
: char.IsWhiteSpace( c )
// If so, "builds" a Discord white square
? "white_large_square"
// Otherwise, checks if the char is a digit
: c > 47 && c < 58
// If so, gets the digit name
? new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }[ c - 48 ]
// Otherwise, builds nothing
: "";
// Checks if the temp string is empty or not
o += t != ""
// If so, format it properly -- capsulate with ':' and add a space at the end
? $":{ t }: "
// Otherwise, add the temp string, it's empty, so won't do anything
: t;
}
// Return the converted string
return o;
};
```
---
### Full code
```
using System;
using System.Collections.Generic;
namespace Namespace {
class Program {
static void Main( String[] args ) {
Func<String, String> f = ( string i ) => {
var o = "";
foreach( var c in i ) {
var k = c | 32;
var t = k > 96 && k < 123
? "regional_indicator_" + (char) k
: char.IsWhiteSpace( c )
? "white_large_square"
: c > 47 && c < 58
? new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }[ c - 48 ]
: "";
o += t != ""
? $":{ t }: "
: t;
}
return o;
};
List<String>
testCases = new List<String>() {
"this is a test string 0123456789",
"!?#$YAY 1234",
"lots of spaces",
};
foreach( String testCase in testCases ) {
Console.WriteLine( $" Input: {testCase}\nOutput: {f( testCase )}\n" );
}
Console.ReadLine();
}
}
}
```
---
### Releases
* **v1.1** - `-23 bytes` - Implemented [pinkfloydx33](https://codegolf.stackexchange.com/questions/122427/discord-large-text-generator/122490?noredirect=1#comment300610_122490) suggestions.
* **v1.0** - `296 bytes` - Initial solution.
---
### Notes
* None
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 75 bytes
```
ลพKโฆ
ยฉยซรlvyaiyโโนยฌ_รรฌ_รฟโ}ydiyโยกรโฌยตโโขโรญโ รฌหรลลกรฏยฟลธยฏยฅล โ#รจ}ยฎyรฅiโโยธ_โฆร_รฏยฉโ}โฆ:รฟ:รฐJ
```
[Try it online!](https://tio.run/nexus/05ab1e#@390n/ejhmUKnFyHVh5afbg5p6wyMbPyUcPMRw07D62JP9x0GEjsB/JrK1NA4nMOLTw8/VHTmkNbHzXMetSw6FHDvMNrHzUsOLzmdNvhjqOTji48vP7Q/qM7Dq0/tPToAqB65cMrag@tqzy8NBNs6LxDO@KB9h1uiweqWwkyF8izOrzf6vAGr///Fe2VVSIdKxUMjYxNAA "05AB1E โ TIO Nexus")
**Explanation**
```
ลพKโฆ<space><tab><newline>ยฉยซร # remove any character that isn't in [A-Za-z0-9<whitespace>]
lv # loop over each character converted to lowercase
yai # if it is a letter
yโโนยฌ_รรฌ_รฟโ} # interpolate into string "regional_indicator_<letter>"
ydi # if it is a digit
yโยกรโฌยตโโขโรญโ รฌหรลลกรฏยฟลธยฏยฅล โ#รจ} # extract it from a list of digits as words
ยฎyรฅi # if it is whitespace
โโยธ_โฆร_รฏยฉโ} # push the string "large_white_square"
โฆ:รฟ: # interpolate in string ":<emoji>:"
รฐ # push a space
J # join stack to one string
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 142 bytes
```
T`w ยถp`_dll%%%_
.
:$&:
[a-z]
regional_indicator_$&
%
white_large_square
0
zero
1
one
2
two
3
three
4
four
5
five
6
six
7
seven
8
eight
9
nine
```
Really wish there was an easier way to replace the digits.
[Try it online!](https://tio.run/nexus/retina#BcFLDoIwFAXQsXcVGCkzjfz8MDHuwQkxpjTygJc0rZYChoW5ADeG5yy3alr9vq9K1loLISR2KMKoCHBX2/kBRy1bo7RkU/NTeetkGEFg6tiT1Mq1JPv3oBxhj5mcRQxrCAn8ZJHCd44IGRo7OORoeCQc0PMHR/Q0ksEJxG3ncYZhQ8uyvmzC8loGcZJmfw "Retina โ TIO Nexus")
### Explanation
```
T`w ยถp`_dll%%%_
```
(Note the tab before the `ยถ`) This is a transliteration stage with changes all letters to lowercase, all whitespace to `%`, and deletes every other character.
```
.
:$&:
```
Next, every character gets wrapped in colons and followed by a space.
```
[a-z]
regional_indicator_$&
```
Next, letters are replaced with regional indicators.
```
%
white_large_square
```
And `%`, which were previously whitespace, are replaced with `white_large_square`.
```
0
zero
1
one
.......
```
And finally, the digits are replaced with their respective emojis.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 184 bytes
```
->x{[x.chars.map{|c|[?:,': ']*(c==$;?'white_large_square':c=~/\d/?%w[zero one two three four five six seven eight nine][c.to_i]:c=~/[A-Z]/i?'regional_indicator_%s'%c.downcase: 0)}]*''}
```
[Try it online!](https://tio.run/nexus/ruby#TYz9SsNAEMT/9ylWbDgtNqnfGomhj1HPIxyXTbIQ7@LtpQm29dVjFSoOAzMMP0Zn0@Jl3MoxNo32HL/rbrszO5mnlyIFoebnJstmz7kYGgpYtNrXWPBHrz2K1GRfyVuZ5NEgP9E7cBYhDA5C4xGhcr2HijYITCMwbtACUt0EsGRRSRMHV5D6fZGrxatKKBcea3JWtwXZkowOzhcRi8jEpRus0YwpLC/2ai7Efur6wKClOM3PZuvVGq6ub26FOjnOoSGGgzUE5AAcPNkalj/U3f3D49M/tHWHPMpVf5U7bZCFmr4B "Ruby โ TIO Nexus")
[Answer]
# [V](https://github.com/DJMcMayhem/V), 141 bytes
```
รรก/:regional_indicator_&:
รรค/ยฝ':'.split('zero one two three four five six seven eight nine')[submatch(0)].':'
รรณ/:white_large_square:
ร::/: :
```
[Try it online!](https://tio.run/nexus/v#FY1LDoIwFAD3nuKtLGws/rVXMaap@KAvwVbbBxiv4QlMvIFrN3IwhGR2k8z03bN7SRWwJO9MpcmdKTfsg56qyeDe8vcVSszitSJOxAODB@8QuPXANiBC4esABTUIke4QsUEHSKVlcORQpIdYny6Gc5tk6XE2tMbsR6rWEqOuTChRx1ttAo5DpaQC1fdsKcKAAcbIEDmQKyGbL5ar9Wa72/8B "V โ TIO Nexus")
[Answer]
# PHP>=7.0, 202 Bytes
```
for(;a&$c=$argn[$i++];)echo($e=[0,"",ctype_alpha($c)=>regional_indicator_.lcfirst($c),ctype_space($c)=>white_large_square,ctype_digit($c)=>strtolower(substr(IntlChar::charName("$c"),6))][1])?":$e: ":"";
```
It exists no Online Interpreter which contains [IntlChar::charName](http://php.net/manual/de/intlchar.charname.php)
## PHP, 211 Bytes
is the nearest way to solve this without [IntlChar::charName](http://php.net/manual/de/intlchar.charname.php)
```
for(;a&$c=$argn[$i++];)echo($e=[0,"",ctype_alpha($c)=>regional_indicator_.lcfirst($c),ctype_space($c)=>white_large_square,ctype_digit($c)=>[zero,one,two,three,four,five,six,seven,eight,nine][$c]][1])?":$e: ":"";
```
[Try it online!](https://tio.run/nexus/php#LY2xTsMwFEX3fkUxFk3UB6LAFBMihDqwwMJSRZFluS/xkyLbvLgtMPDXzCHQrveeo3NfRRdnyBxYM8bAiXyXfa/1y@vb89M6VzNpuPPl4qw6l5vHzXx1c3u3UGMbOFPmQtry/68lLZeNytG6kEks62sQAmz6jKhNH53JpM3LB8aOgje9Jr8la9IUveptSzykP@AkDNFYPAoHRwl1PyWm@X1nGE/MljpKR6b@Qg4QPEI6BEiOEaENO4aW9ggDfcCAe/SA1LkEnjw2tbRNU6@avBKFxGIuCiHUOP74cGmNdfgL "PHP โ TIO Nexus")
# PHP>=7.0, 220 Bytes
Regex Based
```
<?=preg_replace_callback("#(\pL)|(\d)|(\s)|.#",function($t){$r=!$t[1]?!$t[2]?!$t[3]?"":white_large_square:strtolower(substr(IntlChar::charName("$t[2]"),6)):regional_indicator_.lcfirst($t[1]);return$r?":$r: ":"";},$argn);
```
It exists no Online Interpreter which contains [IntlChar::charName](http://php.net/manual/de/intlchar.charname.php)
## PHP, 229 Bytes
is the nearest way to solve this without [IntlChar::charName](http://php.net/manual/de/intlchar.charname.php)
```
<?=preg_replace_callback("#(\pL)|(\d)|(\s)|.#",function($t){$r=!$t[1]?!$t[2]?!$t[3]?"":white_large_square:[zero,one,two,three,four,five,six,seven,eight,nine][$t[2]]:regional_indicator_.lcfirst($t[1]);return$r?":$r: ":"";},$argn);
```
[Try it online!](https://tio.run/nexus/php#JY9PT4MwGMbvfIqtNFlJ6pJtnmDYGLODidGLl4URUrsXaGxafCmb0em39swAL8/v9PzbiqZuAkB0WCA0Dr22FfvdFc8vr48PuygJqMTKpou5COn@fj9brTe3iyQQd/1WpA1CNdqMVFAoacybVO@MhOzQPEUXdjiO0kaXZUh42VnltbOM@uibYjqnPlvlYsT6H5tcEBKfa@2hMEMrFO1HJxHi7AvQcWeB@7PjvkYAXroOealPwFv9yVs4geWgq9pzqy3k2RSbx8PAoVOaQtujVtIPN5dGlRpbz6YBUYLgO7QUBYkpxjMSE5L88Ol2lPT9n3U3Sqoarg "PHP โ TIO Nexus")
[Answer]
# [Python](https://docs.python.org/3/), ~~212~~ 205 bytes
```
lambda s:''.join('/'<c<':'and':'+'zero one two three four five six seven eight nine'.split()[int(c)]+': 'or'`'<c<'{'and':regional_indicator_'+c+': 'or':white_large_square: '*(c in' \n')for c in s.lower())
```
[Try it online!](https://tio.run/nexus/python3#NU7LSsRAEDzvX7Qo9IyBiI9TWBE/Y3EljklP0jJ2x57JRvTj16zipaAeVFW83x9TeH/tA@QGsX5TFodXuO222GCQfsUKv8gUVAjKolBGI4Kos0HkA0HmT8h0IAHiYSwgLIR1nhIX559Yiuv8c4UNoBq@/DZ//zUbDawSUsvScxeKWotV9x9tlpELtSnYQG3@mIPRaly6DlgQNntBH9XgRCHXSRcy5/1xstNkdCzTvB5YlbOH84vd424D1ze3dz8 "Python 3 โ TIO Nexus")
[Answer]
# PowerShell, ~~200~~ 197 Bytes
-3 because the `[A-Za-z]` regex isn't needed in the default case-insensitive regex matches.
```
$a=switch -R ([char[]]"$args"){
"[0-9]"{(-split'zero one two three four five six seven eight nine')["$_"]}
"[a-z]"{"regional_indicator_"+"$_"|% *l*r}
"\s"{"white_large_square"}};":$($a-join': :'):"
```
Would like to find:
a way around using `$a` - wrapping a switch statement in brackets causes it to not work at all for some reason, and any other method is longer than just using a variable.
[Try it online!](https://tio.run/nexus/powershell#Fc1BTsMwEEDRPacYjYySFFliS1AXvQEqrAiRZYVpPMiy07HTQEvOHsz@6f9N2X1aOA8O9BHqbnBWur5HxWGaMza3O@we9VOPt1qnyXOuriQRYiDIS4TshAhOcRY48YUg8TckulAA4tFlCByoajpUBvu1pA763eprqaHQyDFYbzh88mBzFIMP/@73HnZ@J0V/pOIWx5mMtzKSSefZCuG6PmOramX1V@RQtdBWTYvb9lrGYj28UJw8wUEI3n4mDuMf "PowerShell โ TIO Nexus") - input whatever you want and get the result easily.
[](https://i.stack.imgur.com/HGiQU.png)
[Answer]
# JavaScript (ES6), ~~197~~ 199 bytes
Fixed underscores not being handled properly thanks to @Neil.
```
s=>s.toLowerCase().replace(/_|(\d)|(\w)|(\s)|./g,(c,d,a,w)=>a||d||w?`:${a?"regional_indicator_"+c:d?"zero one two three four five six seven eight nine".split` `[c]:"white_large_square"}: `:"").trim()
```
## Cleaned up
```
s => s.toLowerCase().replace( /_|(\d)|(\w)|(\s)|./g, (c, d, a, w) => {
if(a || d || w) {
let out;
if (a) out = "regional_indicator_" + c;
else if (d) out = "zero one two three four five six seven eight nine".split(" ")[c];
else out = "white_large_square";
return `:${out}: `;
}
else {
return "";
}
}).trim()
```
## Test Snippet
```
f=
s=>s.toLowerCase().replace(/_|(\d)|(\w)|(\s)|./g,(c,d,a,w)=>a||d||w?`:${a?"regional_indicator_"+c:d?"zero one two three four five six seven eight nine".split` `[c]:"white_large_square"}: `:"").trim()
```
```
<input id="I" type="text" size="50" oninput="O.innerHTML=f(I.value)">
<pre id="O" style="width:90vw;white-space:pre-wrap">
```
] |
[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/35628/edit).
Closed 6 years ago.
[Improve this question](/posts/35628/edit)
### Idea
From a **given** word dictionary (containing only plain letters, i.e: no accent or other special chars), with a **given** fixed word length, find every *same* when a **given** number letters are missing.
For sample: `un--ed` could match: `united, untied or unused`
>
> Using my dictionnary: */usr/share/dict/american-english*, searching for *same* 6 letters words, having 2 letters missing let me find:
>
>
> * 19242 different possible combination (shapes),
> * The most matching shape is `-a-ing`, that will match `saving, gaming, hating` and more than 80 other words
> * There is 11209 matching shapes for which only two words match, like `-hre-d` that would only match `shrewd` or `thread`.
>
>
>
The goal of this challenge is to write the most efficient algorithm (and implement them in any language) for
1. extract all given fixed length words from a dictionnary
2. find all possible multiple words that could be match same shape containing a given fixed number of missing letter.
3. Sort and present output from the *most matching shape* to the *less matching shape*.
There are 3 variables:
1. Dictionnary file name (could be *STDIN*)
2. Fixed words length
3. Number of missing chars
This could be transmitted in any way you may find usefull.
### Samples
A quick sample could better explain: Searching for same shape of 18 letters, having 2 missing letters give only one match:
```
same /usr/share/dict/american-english 18 2
electrocardiogra--: electrocardiograms,electrocardiograph
```
or
```
same /usr/share/dict/american-english 8 2
17: --ddling: coddling,cuddling,diddling,fiddling,fuddling,huddling,meddling,middling,muddling,paddling,peddling,piddling,puddling,riddling,saddling,toddling,waddling
17: -us-iest: bushiest,cushiest,duskiest,dustiest,fussiest,fustiest,gushiest,gustiest,huskiest,lustiest,mushiest,muskiest,mussiest,mustiest,pushiest,pussiest,rustiest
16: --tching: batching,bitching,botching,catching,ditching,fetching,hatching,hitching,latching,matching,notching,patching,pitching,retching,watching,witching
15: sta--ing: stabbing,stabling,stacking,staffing,staining,stalking,stalling,stamping,standing,stapling,starling,starring,starting,starving,stashing
15: --ttered: battered,bettered,buttered,fettered,guttered,lettered,littered,mattered,muttered,pattered,pottered,puttered,tattered,tittered,tottered
...
2: -e-onate: detonate,resonate
2: c-mmune-: communed,communes
2: trou-le-: troubled,troubles
2: l-t-rals: laterals,literals
2: sp-ci-us: spacious,specious
2: -oardi-g: boarding,hoarding
2: pre-ide-: presided,presides
2: blen-he-: blenched,blenches
2: sw-llin-: swelling,swilling
2: p-uc-ing: plucking,pouching
```
or
>
> The shape `---l-` match `hello` and `world` as well as 297 other words.:
>
>
>
> ```
> same /usr/share/dict/american-english 5 4 |
> sed -ne '/hello/{s/^ *\([0-9]*: [a-z-]*\):.*,world,.*$/\1/p}'
> 299: ---l-
>
> ```
>
>
### Test file
For testing, I've posted this 62861 length [extract from my dict file](http://cartou.ch/sharedstuff/testdict.txt) in plain ascii, useable from *jsfiddle*, *jsbin* or even from your filesystem (because of the directive *access-control-allow-origin*) ( sample: [@edc65 answer](http://jsfiddle.net/38cUH/2/), with *score* count ).
### Ranking
This is a *fastest algorithm* challenge.
The goal of this is to find quickest way for building shape, making comparissions and sorting list.
But the natural speed of language have to not be matter. So if a solution using [bash](/questions/tagged/bash "show questions tagged 'bash'") is slower, but simplier, using more efficient algorithm than another [c](/questions/tagged/c "show questions tagged 'c'") based solution, the simplier (maybe slower) have to win.
The score is the number of logical steps required by the whole job, using any dictionary file (my personal english dictionary: `wc -l /usr/share/dict/american-english -> 99171`) and different combinations of word length and number of missing letters.
The lowest score win.
[Answer]
# C++11
Excuse the variable names.
Calculates hamming distance between each pair of words then tries replacing characters in words with '-', and calculates hamming distance between the word with '-' and the words without (that had a low enough hamming distance). See comments for details.
```
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <fstream>
#include <ios>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
// Calculates hamming distance between a and b, both of which are length m
inline int fries(const std::string &a, const std::string &b, int m){
int c = 0;
for(int i = 0; i < m; ++i)
a[i]==b[i] || ++c;
return c;
}
using namespace std;
int main(int eggs, char **bagels){
ios_base::sync_with_stdio(false);
// make sure proper number of arguments are passed
assert(eggs == 4);
int m, k;
// read in m (word length) and k (number of '-'s)
sscanf(bagels[2], "%i", &m);
sscanf(bagels[3], "%i", &k);
// bacon will store all words that are of length m
vector<string> bacon;
bacon.reserve(500000);
// Save only words that are of length m
ifstream milk(bagels[1]);
{
string toast;
while(getline(milk, toast))
if(toast.length() == m)
bacon.push_back(toast);
}
// ham[i] will store the indices of strings with a hamming distance from bacon[i] that is at most k
vector<vector<int>> ham(bacon.size());
// Calculate hamming distance, if <=k, add to ham.
for(int i = 0, sz = bacon.size(); i < sz; ++i){
// Uses i+1 to ensure each PAIR is only checked once
for(int j = i+1; j < sz; ++j){
unsigned strip = fries(bacon[i], bacon[j], m);
if(strip && strip <= k)
ham[i].push_back(j);
}
}
// cereal[string], where string is the matching shape, and the vector is a vector of indices of strings that are matched by string
map<string, vector<int>> cereal;
for(int i = 0, sz = ham.size(); i < sz; ++i){
// skip words that are not similar enough to other words
if(ham[i].size() == 0) continue;
// Iterate through all versions of bacon[i] with k '-'s
// THIS ONLY ITERATES THROUGH COMBINATIONS NOT PERMUTATIONS
vector<bool> cream(m);
fill(cream.begin()+k,cream.end(),true);
do{
std::string juice = bacon[i];
// Add in '-'s
for(int i = 0; i < m; ++i){
if(!cream[i]) juice[i] = '-';
}
// Ensure that this pattern has not yet been processed
if(!cereal.count(juice)){
// For each of the words with hamming distance<=k, check hamming distance with the matching shape
// If hamming distance == k, then it matches, so save to cereal
for(int j = 0, ssz = ham[i].size(); j < ssz; ++j){
if(fries(juice, bacon[ham[i][j]], m) == k)
cereal[juice].push_back(ham[i][j]);
}
// In the case that there ARE matches, put the index of the original string at the end
if(cereal.count(juice))
cereal[juice].push_back(i);
}
}while(next_permutation(cream.begin(), cream.end()));
}
// Sorts all the matching shapes by number of matches
vector<pair<string, vector<int>>> orange_juice;
copy(cereal.begin(), cereal.end(), back_inserter(orange_juice));
sort(orange_juice.begin(), orange_juice.end(), [](const pair<string, vector<int>> &a, const pair<string, vector<int>> &b){
return a.second.size() > b.second.size();
});
// Iterate through sorted matching shapes, print
for(auto cake:orange_juice){
// bacon[cake.second.back()] is the original string from which the pattern was derived
cout << cake.second.size() << ": " << cake.first << ": " << bacon[cake.second.back()];
// do not print original string twice
cake.second.pop_back();
// print other strings
for(auto coffee:cake.second){
cout << "," << bacon[coffee];
}
cout << "\n";
}
return 0;
}
```
[Answer]
## C++, enter image description here
*Where **l** is the word length, **m** is the number of "wildcards" (or dashes) and **n** is the number of words (of length **l**.)*
Skimming over the submissions, it seems that they're all either inherently quadratic with the number of words or are *very* liberal with their use of resources, while there is a very straight-forward O(n log n) solution:
For every possible pattern (l choose m), sort the word list (n log n) while ignoring the masked-out letters (l - m).
Now all the words that compare equal (modulo masked-out letters) are grouped together and can be collected with a linear scan.
This not only scales better but is also very easy to parallelize over different patterns.
Another thing worth noting, I bet most of the submissions spend a significant amount of time just doing I/O.
Buffer more and avoid I/O like the plague.
Compile with: `g++ wildcards.cpp -owildcards -std=c++11 -pthread -O3`.
Run with: `./wildcards <word-list> <l> <m>`.
```
#define THREAD_COUNT 2
#define WILDCARD '-'
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
#include <utility>
#include <thread>
#include <atomic>
#include <sstream>
#include <cstdlib>
#include <cstddef>
using namespace std;
/* Writes an integer to a string. */
template <typename String, typename T>
void write_int(String& str, T n) {
if (n < 0) {
str += '-';
n = -n;
}
int p10 = 1;
for (T m = n; m; m /= 10, p10 *= 10);
if (p10 > 1) p10 /= 10;
for (; p10; p10 /= 10) str += '0' + (n / p10 % 10);
}
/* Function object that lexicographically compares a starting segment of two
* containers. */
struct fixed_size_lexicographical_compare {
/* Starting segment size. */
size_t size;
explicit fixed_size_lexicographical_compare(size_t size): size(size) {}
/* If we ever actually need a generic version... */
template <typename Container>
bool operator()(const Container& x, const Container& y) const = delete;
/* Fast specialized case for strings. */
bool operator()(const char* x, const char* y) const {
for (size_t i = 0; i < size; ++i) {
int c = x[i] - y[i];
if (c) return c < 0;
}
return false;
}
};
/* A pattern is an array of boolean values (avoiding the dreaded vector<bool>)
* where a truth value represensts a wildcard. */
typedef vector<char> pattern_type;
typedef vector<pattern_type> patterns_type;
/* We ues a buffer of type `word_data_type` to hold all the word data in one big
* chunk, and a separate array of type `words_type` to point to individual words
* in the buffer. */
typedef vector<char> word_data_type;
typedef vector<const char*> words_type;
/* The result type. */
struct result {
/* The pattern and matching set of words. */
const pattern_type* pattern;
const words_type* word_list;
/* Index range into word_list. */
pair<size_t, size_t> words;
words_type::const_iterator begin() const {
return next(word_list->begin(), words.first);
}
words_type::const_iterator end() const {
return next(word_list->begin(), words.second);
}
size_t size() const { return words.second - words.first; }
/* Write the result to a string. */
void write(string& str) const {
size_t word_length = pattern->size();
write_int(str, size());
str += ": "; {
const char* w = *begin();
for (size_t i = 0; i < word_length; ++i)
str += (*pattern)[i] ? WILDCARD : w[i];
}
str += ':';
for (const char* w : *this) {
str += ' ';
copy(w, w + word_length, back_inserter(str));
}
str += '\n';
}
};
typedef vector<result> results_type;
/* Thread context. */
struct context {
size_t word_length, wildcards;
const patterns_type* patterns;
atomic<size_t>* next_pattern;
const word_data_type* word_data;
results_type results;
words_type result_words;
};
void thread_proc(context& ctx) {
const char* ctx_word_data = &ctx.word_data->front();
const size_t ctx_word_data_size = ctx.word_data->size();
const size_t word_length = ctx.word_length, wildcards = ctx.wildcards;
const size_t masked_word_length = word_length - wildcards;
const size_t word_count = ctx_word_data_size / word_length;
/* For each pattern, we make a copy of the word data buffer without the
* masked out letters. We can already allocate space for the buffer and
* initialize the array of pointers into the buffer. */
word_data_type word_data(word_count * masked_word_length);
words_type words;
words.reserve(word_count);
for (auto i = word_data.begin(); i != word_data.end(); i += masked_word_length)
words.push_back(&*i);
while (true) {
/* Grab a pattern. */
size_t pattern_index; {
pattern_index = (*ctx.next_pattern)++;
if (pattern_index >= ctx.patterns->size())
break;
}
const pattern_type& pattern = (*ctx.patterns)[pattern_index];
/* Copy the word data while skipping the wildcards. */
for (size_t i = 0, j = 0; i < ctx_word_data_size; ++i) {
if (!pattern[i % word_length])
word_data[j++] = ctx_word_data[i];
}
/* Sort the words. */
sort(
words.begin(), words.end(),
fixed_size_lexicographical_compare(masked_word_length)
);
/* Traverse the list of words while ... */
for (auto i = words.begin(); i != words.end(); ) {
/* ... looking for adjacent words that compare equal (when
* masked.) */
auto j = find_if(
next(i), words.end(),
bind(
fixed_size_lexicographical_compare(masked_word_length),
*i, placeholders::_1
)
);
/* If more than one word compares equal, add a result. */
if (j != next(i)) {
size_t begin_index = ctx.result_words.size();
for (; i != j; ++i)
/* Make sure to index the word from the global word buffer,
* not the local copy. */
ctx.result_words.push_back(
ctx_word_data +
(*i - &word_data.front()) / masked_word_length * word_length
);
/* Sort the words alphabetically (not really part of the
* algorithm, just for neatness.) */
sort(
next(ctx.result_words.begin(), begin_index), ctx.result_words.end(),
fixed_size_lexicographical_compare(word_length)
);
ctx.results.push_back(
{&pattern, &ctx.result_words, {begin_index, ctx.result_words.size()}}
);
} else
i = j;
}
}
}
int main(int argc, const char* argv[]) {
ios_base::sync_with_stdio(false);
if (argc != 4) {
cerr << "Wrong number of arguments" << endl;
return 1;
}
int word_length = atoi(argv[2]), wildcards = atoi(argv[3]);
if (word_length <= 0 || wildcards <= 0 || word_length < wildcards) {
cerr << "Invalid arguments" << endl;
return 1;
}
/* Generate all possible patterns. */
patterns_type patterns; {
pattern_type pattern(word_length);
fill_n(pattern.begin(), wildcards, true);
do
patterns.push_back(pattern);
while (prev_permutation(pattern.begin(), pattern.end()));
}
/* Read the word list. */
clog << "Reading word list..." << endl;
word_data_type word_data; {
string word;
ifstream file(argv[1]);
if (!file.is_open()) {
cerr << "Failed to open `" << argv[1] << "'" << endl;
return 1;
}
while (getline(file, word)) {
if (word.size() == word_length)
/* Add the word to the end of the buffer. */
move(word.begin(), word.end(), back_inserter(word_data));
}
}
context ctx[THREAD_COUNT];
thread threads[THREAD_COUNT];
results_type results;
atomic<size_t> next_pattern(0);
/* Run the threads. */
clog << "Searching..." << endl;
for (int i = 0; i < THREAD_COUNT; ++i) {
ctx[i].word_length = size_t(word_length);
ctx[i].wildcards = size_t(wildcards);
ctx[i].patterns = &patterns;
ctx[i].next_pattern = &next_pattern;
ctx[i].word_data = &word_data;
threads[i] = thread(thread_proc, ref(ctx[i]));
}
/* Collect the results. */
for (int i = 0; i < THREAD_COUNT; ++i) {
threads[i].join();
results.reserve(results.size() + ctx[i].results.size());
move(ctx[i].results.begin(), ctx[i].results.end(), back_inserter(results));
results_type().swap(ctx[i].results);
}
sort(
results.begin(), results.end(),
[] (const result& r1, const result& r2) { return r1.size() > r2.size(); }
);
/* Print the results. */
clog << "Writing results..." << endl; {
string str;
for (const result& r : results) {
r.write(str);
if (str.size() >= (1 << 20)) {
cout << str;
str.clear();
}
}
cout << str;
}
}
```
[Answer]
Because this needs more Java Streaming:
Running the unofficial 351k word list at 11, 3 in ~7 seconds, beating the JavaScript version by only 4 minutes and 3 seconds. ;)
**My secret:** instead of comparing every possible strike-out combination for each word, I just calculate the word distance (amount of different letters) between each two words, generate a strike-out word for that match if applicable and add it to an incremental map. In this way only those strike-out words are generated that actually have at least one match.
**Input:** *wordListFile wordSize wordDistanceLimit*
```
public class WordList {
static boolean acceptableWordDistance(final String a, final String b, final int maxWordDistance) {
int result = 0;
for (int i = a.length() - 1; i >= 0; --i) {
if (a.charAt(i) != b.charAt(i)) {
++result;
if (result > maxWordDistance) {
return false;
}
}
}
return (result > 0);
}
public static void main(String[] args) throws IOException {
// args = new String[]{"wordlist.txt", "11", "3"};
final String fileName = args[0];
final int wordLength = Integer.parseInt(args[1]);
final int maxWordDistance = Integer.parseInt(args[2]);
final List<String> allWords = Files.lines(Paths.get(fileName)).parallel()
.filter(s -> s.length() == wordLength)
.distinct()
.collect(Collectors.toList());
final HashMap<String, Set<String>> result = new HashMap<>();
allWords.parallelStream()
.forEach(a -> {
allWords.stream()
.filter(b -> acceptableWordDistance(a, b, maxWordDistance))
.forEach(b -> {
final StringBuilder buildA = new StringBuilder(a);
for (int i = b.length() - 1; i >= 0; --i) {
if (buildA.charAt(i) != b.charAt(i)) {
buildA.replace(i, i + 1, "-");
}
}
result.merge(buildA.toString(), new TreeSet<>(Arrays.asList(b)), (list, v) -> {
list.addAll(v);
return list;
});
});
});
result.entrySet().parallelStream()
.sorted((a, b) -> -Integer.compare(a.getValue().size(), b.getValue().size()))
.forEachOrdered(e -> System.out.println(e.getKey() + ": " + Arrays.toString(e.getValue().toArray())));
}
}
```
[Answer]
# JavaScript ~~(E6)~~ + HTML or C# console or C++ console
**Edit 3** At last, here is the C++ version. It's not exactly C++11 as it compiles with Visual Studio 2010, but requires -std=c++11 with gcc.
Compiled with max optimization and 64bit is marginally faster than C#. Time for 11,3 is ~7 sec
Sorry, no funny variable names, but on the other hand it's at least 10 times faster of the other C++ answer.
Side note: many C++ libraries have weak hashing functions, that cause more collisons and bad performance using hash tables. I included in the C++ source one of the better hashing functions freely available.
**Edit 2** Added an implementation in C# - same algorithm, no parallelism - Time for 11,3 is ~11.5 sec
**Edit** Removed dependencies on EcmaScript 6, Chrome is *really* faster:
For 18,2 found 965 in 80sec
```
chlorophylli-e-ous:3:chlorophylliferous,chlorophylligenous,chlorophylligerous
intercommunicati--:3:intercommunicating,intercommunication,intercommunicative
non--structiveness:3:nondestructiveness,noninstructiveness,nonobstructiveness
oversentimentali--:3:oversentimentalism,oversentimentality,oversentimentalize
transubstantiati--:3:transubstantiating,transubstantiation,transubstantiative
...
```
Using a hashtable (a javascript object). It is quite fast beeing a scripting language.
The score ... uuu ... help!!!
Time for 11,3 with my huge 351k word list is 4min 10sec

Problems (for javascript version)
1. needs to load the dictionary from local storage, so I can't make a jsfiddle. It works locally opening the file with any compatible browser (even a recent MSIE will do well)
2. hits the time limit for javascript execution in some browser (that I already keep high to 1 minute)
Next time I'll try in C++
**Javascript Code**
```
<!DOCTYPE html>
<html>
<head>
<title>Same word when missing letters</title>
</head>
<body>
Load dictionary<input type="file" id="dictinput" /><span id="spWords"></span><br>
Word size: <input id="tbWordSize"><br>
Missing letters: <input id="tbLetters"><br>
<button id="gobutton" onclick="go()">GO</button><br>
<div id="Info" style="width:95%"></div>
<pre id="Output" style="width:95%; height: 600px; overflow: auto; border: 1px solid #000"></pre>
<script type="text/javascript">
var words
function readWordFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
words = e.target.result.match(/[a-z]+/gi)
console.log( "Got the file " + f.name + "\nWords " + words.length);
document.getElementById('spWords').innerHTML = 'Words: ' + words.length;
}
r.readAsText(f);
} else {
console.log ("Failed to load file");
}
}
function bitcount(u) {
for (var n=0; u; ++n, u=u&(u-1));
return n;
}
function elab(word, mask, wordSize, letters, store)
{
var chars, p, bit
for (; --mask;)
{
if (bitcount(mask) == letters)
{
chars='';
for (bit=1, p = 0; p < wordSize; p++, bit+=bit)
{
chars += bit & mask ? '-' : word[p];
}
if (!store[chars]) store[chars] = [];
store[chars].push(word);
}
}
}
function go()
{
document.getElementById('Output').innerHTML = '...';
document.getElementById('Info').innerHTML = '...running...';
store = {};
setTimeout( function() {
var tstop, tstart = new Date;
var wordSize = document.getElementById('tbWordSize').value;
var letters = document.getElementById('tbLetters').value;
var result, found, i, mask;
console.log(tstart);
console.log(wordSize, letters, words.length);
mask = 1<<wordSize;
for (i = 0; i < words.length; i++)
{
if (words[i].length == wordSize)
elab(words[i], mask, wordSize, letters, store);
}
keys = Object.keys(store);
keys.sort(function(a,b) { return store[b].length - store[a].length});
tstop = new Date;
console.log(tstop);
console.log('Time to scan (ms) '+ (tstop-tstart));
found = 0;
result = keys.map(function(key) { return store[key][1] ? (found++, key + ':' + store[key].length + ':' + store[key] + '\n'): ''});
document.getElementById('Output').innerHTML = result.join('');
tstop = new Date;
console.log(tstop);
console.log('Total ' + found + ' time (ms) ' + (tstop-tstart));
document.getElementById('Info').innerHTML = "#Found " + found + " in time (ms) " + (tstop-tstart);
}, 100);
}
document.getElementById('dictinput').addEventListener('change', readWordFile, false);
</script>
</body>
</html>
```
**C# Code**
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace SameWord
{
class Program
{
Dictionary<String, List<String>> store = new Dictionary<string, List<string>>(100000); // start big
string wordfile;
int wordsize;
int letters;
int tmask;
Program(string[] args)
{
wordfile = args[0];
wordsize = Convert.ToInt32(args[1]);
letters = Convert.ToInt32(args[2]);
tmask = 1 << wordsize;
}
void Dowork()
{
DateTime start = DateTime.UtcNow;
String word;
using (StreamReader input = new StreamReader(wordfile))
{
while ((word = input.ReadLine()) != null)
{
if (word.Length == wordsize)
{
Elab(word);
}
}
}
var results = store
.Where(x => x.Value.Count > 1)
.OrderByDescending(x => x.Value.Count)
.Select(x => new { x.Key, x.Value });
int found = 0;
using (StreamWriter output = new StreamWriter(wordfile + "." + wordsize + "." + letters + ".txt"))
{
foreach (var line in results)
{
found++;
output.WriteLine(line.Key + ":" + line.Value.Count + ":" + String.Join(",", line.Value));
}
}
Console.WriteLine("Time {0}. Found {1}", DateTime.UtcNow - start, found);
}
int BitCount(int u)
{
int n;
for (n = 0; u > 0; ++n, u = u & (u-1));
return n;
}
void Elab(string word)
{
for(int mask = tmask; --mask > 0; )
{
if (BitCount(mask) == letters)
{
int p, bit;
var chars = word.ToCharArray();
for (bit = 1, p = 0; bit <= mask; p++, bit += bit)
{
if ((bit & mask) != 0) chars[p] = '-';
}
string key = new String(chars);
List<String> wordskey;
if (!store.TryGetValue(key, out wordskey))
{
store.Add(key, wordskey = new List<String>());
}
wordskey.Add(word);
}
}
}
static void Main(string[] args)
{
new Program(args).Dowork();
}
}
}
```
**C++ Code**
```
#include <stdio.h>
#include <stdint.h>
#include <string>
#include <unordered_map>
#include <forward_list>
#include <list>
#include <vector>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <ctime>
using namespace std;
// SuperFastHash by Paul Hsieh 2008
#define get16bits(d) (*((const uint16_t *) (d)))
uint32_t SuperFastHash (const char * data, int len) {
uint32_t hash = len, tmp;
int rem;
if (len <= 0 || data == NULL) return 0;
rem = len & 3;
len >>= 2;
/* Main loop */
for (;len > 0; len--) {
hash += get16bits (data);
tmp = (get16bits (data+2) << 11) ^ hash;
hash = (hash << 16) ^ tmp;
data += 2*sizeof (uint16_t);
hash += hash >> 11;
}
/* Handle end cases */
switch (rem) {
case 3: hash += get16bits (data);
hash ^= hash << 16;
hash ^= ((signed char)data[sizeof (uint16_t)]) << 18;
hash += hash >> 11;
break;
case 2: hash += get16bits (data);
hash ^= hash << 11;
hash += hash >> 17;
break;
case 1: hash += (signed char)*data;
hash ^= hash << 10;
hash += hash >> 1;
}
/* Force "avalanching" of final 127 bits */
hash ^= hash << 3;
hash += hash >> 5;
hash ^= hash << 4;
hash += hash >> 17;
hash ^= hash << 25;
hash += hash >> 6;
return hash;
}
size_t fast_hash( const string & value )
{
return SuperFastHash(value.data(), value.length());
}
typedef unordered_map<string, vector<string>, decltype(&fast_hash)> MyStore;
MyStore store(100000, fast_hash);
int wordSize, letters;
int BitCount(int u)
{
int n;
for (n = 0; u; ++n, u = u & (u-1));
return n;
}
void Elab(string word)
{
char chars[100];
for(int mask = 1<<wordSize; --mask; )
{
if (BitCount(mask) == letters)
{
int p, bit;
const char *wdata = word.data();
for (bit = 1, p = 0; p < wordSize; p++, bit += bit)
{
chars[p] = bit & mask ? '-' : wdata[p];
}
vector<string> &wordsKey = store[string(chars, wordSize)];
wordsKey.push_back(word);
}
}
}
bool mycomp (const pair<const string,vector<string>> &a, const pair<const string,vector<string>> &b)
{
return (a.second.size() > b.second.size());
}
int main(int argc, char **argv)
{
string wordFile = argv[1];
sscanf(argv[2], "%d", &wordSize);
sscanf(argv[3], "%d", &letters);
ifstream infile(wordFile);
{
string word;
while(getline(infile, word))
if(word.length() == wordSize)
Elab(word);
}
forward_list<pair<const string,vector<string>>> results;
int found = 0;
for (MyStore::iterator it = store.begin(); it != store.end(); ++it)
{
if (it->second.size() > 1)
{
found++;
results.push_front(*it);
}
}
cerr << "Found " << found << "\n";
results.sort(mycomp);
stringstream sf;
sf << wordFile << '.' << wordSize << '.' << letters << ".txt";
ofstream outfile(sf.str());
for(forward_list<pair<const string,vector<string>>>::iterator it = results.begin(); it != results.end(); ++it)
{
int size = it->second.size();
outfile << it->first << ':' << size << ':' << it->second[0];
for(size_t i = 1; i < size; ++i)
{
outfile << ',' << it->second[i];
}
outfile << '\n';
}
}
```
[Answer]
# Python
This is an exceptionally naive approach. Runtime is abysmal for even moderate use cases.
n = number of words of length l
l = length of words
m = number of missing letters (ish)
I think my runtime complexity is O(n\*n\*l\*l\*m).
The slowest internal function is the string masking. I'm not sure of the optimal way to do that in Python. I tried representing words and masks as strings, as lists, and ended up with the method below where words are strings and masks are a list of integer positions.
The algorithm itself could be sped up by filtering out words more effectively than comparing them for every mask.
```
#!/usr/bin/env python
import sys
import itertools
if len(sys.argv)!=4:
print "Usage: same.py dictionaryfile wordlength missingletters"
exit(1)
dictionaryfile = sys.argv[1]
wordlength = int(sys.argv[2])
missingletters = int(sys.argv[3])
words = [line.strip() for line in open(dictionaryfile) if line==line.lower() and len(line.strip())==wordlength]
# print words
def mask_string(string,mask):
new_string = ""
for i in range(len(string)):
if i in mask:
new_string += "-"
else:
new_string += string[i]
return new_string
masks = itertools.permutations(range(wordlength),missingletters)
results = {}
for mask in masks:
patterns = set()
for word in words:
masked_word = mask_string(word,mask)
if masked_word in patterns:
continue
results[masked_word] = set()
results[masked_word].add(word)
patterns.add(masked_word)
for word2 in words:
masked_word2 = mask_string(word2,mask)
if masked_word2 == masked_word and word2 != word:
# print word + " and " + word2 + " match with mask " + "".join(mask)
results[masked_word].add(word2)
for k,v in sorted(results.items(), key=lambda x: (-len(x[1]),x[0])):
if len(v)>1:
print str(len(v)) + ": " + k + ": " + ",".join(v)
```
Sample output for 3,1 (1.8 seconds):
```
19: -at: bat,cat,eat,fat,gat,hat,kat,lat,mat,nat,oat,pat,rat,sat,tat,vat,wat,yat,zat
19: ta-: taa,tab,tad,tae,tag,tai,taj,tal,tam,tan,tao,tap,tar,tat,tau,tav,taw,tax,tay
...
2: zi-: zig,zip
2: zo-: zoa,zoo
```
And for 3,2 (0.5 seconds):
```
237: -a-: aal,aam,baa,bac,bad,bae,bag,bah,bal,bam,ban,bap,bar,bas,bat,baw,bay,cab,cad,cag,cal,cam,can,cap,car,cat,caw,cay,dab,dad,dae,dag,dah,dak,dal,dam,dan,dao,dap,dar,das,daw,day,ean,ear,eat,fad,fae,fag,fam,fan,far,fat,fay,gab,gad,gag,gaj,gal,gam,gan,gap,gar,gas,gat,gau,gaw,gay,gaz,had,hag,hah,hak,ham,han,hao,hap,hat,hau,haw,hay,iao,jab,jag,jam,jap,jar,jaw,jay,kai,kan,kat,kay,lab,lac,lad,lag,lai,lak,lam,lan,lap,lar,las,lat,law,lax,lay,mac,mad,mae,mag,mal,man,mao,map,mar,mas,mat,mau,maw,may,naa,nab,nae,nag,nak,nam,nan,nap,nar,nat,naw,nay,oaf,oak,oam,oar,oat,pac,pad,pah,pal,pam,pan,pap,par,pat,pau,paw,pax,pay,rab,rad,rag,rah,raj,ram,ran,rap,ras,rat,raw,rax,ray,saa,sab,sac,sad,sag,sah,sai,saj,sal,sam,san,sao,sap,sar,sat,saw,sax,say,taa,tab,tad,tae,tag,tai,taj,tal,tam,tan,tao,tap,tar,tat,tau,tav,taw,tax,tay,vag,van,vas,vat,vau,wab,wad,wae,wag,wah,wan,wap,war,was,wat,waw,wax,way,yad,yah,yak,yam,yan,yap,yar,yas,yat,yaw,zac,zad,zag,zak,zar,zat,zax
198: -o-: boa,bob,bod,bog,bom,bon,boo,bop,bor,bot,bow,boy,cob,cod,coe,cog,col,con,coo,cop,cor,cos,cot,cow,cox,coy,coz,dob,doc,dod,doe,dog,dom,don,dop,dor,dos,dot,dow,eon,fob,fod,foe,fog,foo,fop,for,fot,fou,fow,fox,foy,goa,gob,god,gog,goi,gol,gon,goo,gor,gos,got,goy,hob,hod,hoe,hog,hoi,hop,hot,how,hox,hoy,ion,job,joe,jog,jot,jow,joy,koa,kob,koi,kon,kop,kor,kos,kou,loa,lob,lod,lof,log,loo,lop,lot,low,lox,loy,mob,mog,mon,moo,mop,mor,mot,mou,mow,moy,noa,nob,nod,nog,non,nor,not,now,noy,pob,pod,poe,poh,poi,pol,pom,pon,pop,pot,pow,pox,poy,rob,roc,rod,roe,rog,roi,rot,row,rox,sob,soc,sod,soe,sog,soh,sok,sol,son,sop,sot,sou,sov,sow,soy,toa,tod,toe,tog,toi,tol,ton,too,top,tor,tot,tou,tow,tox,toy,voe,vog,vol,vow,wob,wod,woe,wog,won,woo,wop,wot,wow,woy,yoe,yoi,yok,yom,yon,yor,yot,you,yow,yox,yoy,zoa,zoo
...
2: -x-: axe,oxy
2: q--: qua,quo
```
And for 4,2 (39 seconds):
```
146: -a-e: babe,bade,bake,bale,bane,bare,base,bate,baze,cade,cage,cake,came,cane,cape,care,case,cate,cave,dace,dade,dale,dame,dare,date,daze,ease,eave,face,fade,fage,fake,fame,fare,fate,faze,gade,gage,gale,game,gane,gape,gare,gate,gave,gaze,hade,haje,hake,hale,hame,hare,hate,have,haze,jade,jake,jane,jape,kale,kame,lace,lade,lake,lame,lane,late,lave,laze,mace,made,mage,make,male,mane,mare,mate,maze,nace,nake,name,nane,nape,nave,naze,pace,page,pale,pane,pape,pare,pate,pave,race,rage,rake,rame,rane,rape,rare,rase,rate,rave,raze,sabe,sade,safe,sage,sake,sale,same,sane,sare,sate,save,tade,take,tale,tame,tane,tape,tare,tate,tave,vade,vage,vale,vane,vare,vase,wabe,wace,wade,wage,wake,wale,wame,wane,ware,wase,wave,yade,yaje,yale,yare,yate
121: -i-e: aide,aile,aire,bice,bide,bike,bile,bine,bite,cine,cise,cite,cive,dice,dike,dime,dine,dire,dite,dive,fice,fide,fife,fike,file,fine,fire,fise,five,gibe,give,hide,hike,hipe,hire,hive,jibe,jive,kibe,kike,kipe,kite,life,like,lile,lime,line,lire,lite,live,mice,mide,mike,mile,mime,mine,mire,mise,mite,nice,nide,nife,nine,oime,pice,pike,pile,pine,pipe,pise,pize,ribe,rice,ride,rife,rile,rime,rine,ripe,rise,rite,rive,sice,side,sife,sike,sile,sime,sine,sipe,sire,sise,site,size,tice,tide,tige,tile,time,tine,tipe,tire,tite,vice,vile,vine,vire,vise,vive,wice,wide,wife,wile,wime,wine,wipe,wire,wise,wite,wive,yite
...
2: z-z-: zizz,zuza
2: zy--: zyga,zyme
```
[Answer]
# Same shape when missing letters
My approach was to build lists of shapes for counting matches.
There is 3 version of same prototype: [perl](/questions/tagged/perl "show questions tagged 'perl'") first, [bash](/questions/tagged/bash "show questions tagged 'bash'") was usefull to build *charWalk* and a [javascript](/questions/tagged/javascript "show questions tagged 'javascript'") with a link to *JSFIDDLE*.
If execution time differ, all this version have to reach same score.
## perl version
There is my 1st perl version:
```
#!/usr/bin/perl -w
use strict;
use Time::HiRes qw|time|;
my $dict="/usr/share/dict/american-english";
my $fixLen=8;
my $numBlank=2;
$dict = $ARGV[0] if $ARGV[0] && -f $ARGV[0];
$fixLen=$ARGV[1] if $ARGV[1] && $ARGV[1] > 1 && $ARGV[1] <100;
$numBlank=$ARGV[2] if $ARGV[2] && $ARGV[2] > 0 && $ARGV[2] < $fixLen;
my %array;
my $cword;
my %counters;
my $started=time();
sub charWalk {
my ( $word, $cnt, $lhs ) = @_;
if ( $cnt gt 1 ) {
my $ncnt=$cnt-1;
for my $i ( 0 .. length($word) - $cnt ) {
charWalk( substr( $word, $i + 1 ), $ncnt,
$lhs . substr( $word, 0, $i ) . "-" );
};
} else {
for my $i ( 0 .. length($word) - $cnt ) {
push @{ $array{ $lhs. substr( $word, 0, $i ).
"-". substr( $word, $i + 1 ) } },
$cword;
};
};
}
open my $fh,"<".$dict or die;
while (<$fh>) {
$counters{'words'}++;
chomp;
$cword = $_;
charWalk( $cword, $numBlank,"" ) if $cword=~/^[a-z]{$fixLen}$/ &&
$counters{'matchlen'}++;
}
map {
$counters{'found'}++;
printf "%2d: %s: %s\n", 1+$#{$array{$_} }, $_, join ",", @{ $array{$_} };
} sort {
$#{ $array{$b} } <=> $#{ $array{$a} }
} grep {
$#{ $array{$_} } > 0
} keys %array;
print "Counters: ".join(", ",map {sprintf "%s: %s",$_,$counters{$_}} keys %counters).". Time: ".(time()-$started)."\n";
```
## bash proto for *charWalk*
For the [bash](/questions/tagged/bash "show questions tagged 'bash'") version, I've used an unreasonable small dictionary file by dropping 90% of my smallest dictionary file:
```
sed -e 'p;N;N;N;N;N;N;N;N;N;d' <testdict.txt >tiny-dict.txt
```
Well, there it is:
```
#!/bin/bash
file=${1:-tiny-dict.txt}
wsiz=${2:-11}
mltr=${3:-3}
charWalk () {
local word=$1 wlen=${#1} cnt=${2:-1} lhs=$3 pnt;
[ $cnt -gt $wlen ] && return;
if [ $cnt -gt 1 ]; then
for ((pnt=0; pnt<=wlen-cnt; pnt++))
do
charWalk ${word:pnt+1} $[cnt-1] $lhs${word:0:pnt}-;
done;
else
for ((pnt=0; pnt<=wlen-cnt; pnt++))
do
store[$lhs${word:0:pnt}-${word:pnt+1}]+=" $cword";
done;
fi
}
declare -A store=();
while read cword ;do
charWalk $cword $mltr
done < <(
grep "^[a-z]\{$wsiz\}$" <$file
)
count=0
for i in ${!store[@]};do
if [ ${#store[$i]} -gt $[1+wsiz] ];then
w=(${store[$i]})
((count+=1))
echo ${#w[@]} $i : ${w[@]}
fi
done > >( sort -rn )
echo "Found: $count matchs."
```
## javascript
Seeing @edc65 post, I've taked some part of his script to build a [JSFIDDLE](http://jsfiddle.net/2x4pjnfL/6/).
Mainly 3 parts (+HTML):
### charWalk for building all possible pattern
```
function charWalk(word,cnt,lhs) {
if (cnt>1) {
var ncnt=cnt-1;
for (var k=0;k<=word.length-cnt;k++) {
charWalk(word.substr(k+1),ncnt,lhs+word.substr(0,k)+"-");
};
} else {
for (var k=0;k<=word.length-cnt;k++) {
if (typeof(gS.shapes[lhs+word.substr(0,k)+"-"+word.substr(k+1)])
== 'undefined') {
gS.shapes[lhs+word.substr(0,k)+"-"+word.substr(k+1)]=[];
};
gS.shapes[lhs+word.substr(0,k)+"-"+
word.substr(k+1)].push(gS.currentWord);
};
};
}
```
### Main loop.
```
function go() {
var wordSize = document.getElementById('tbWordSize').value;
var letters = document.getElementById('tbLetters').value;
gS.shapes={};
for (var i = 0; i < gS.words.length; i++) {
if (gS.words[i].length == wordSize) {
gS.currentWord=gS.words[i];
charWalk(gS.currentWord, letters, "" );
};
};
var keys = Object.keys(gS.shapes).
filter(
function(i){
return gS.shapes[i][1];
}
).sort(
function(a,b) {
return gS.shapes[b].length - gS.shapes[a].length;
}
);
var intLen=gS.shapes[keys[0]].length.toFixed(0).length;
gS.result = keys.map(
function(key) {
return gS.shapes[key].length.toFixed(0)+ ' : '+
key +' : '+ gS.shapes[key];
});
document.getElementById('Output').innerHTML = gS.result.join('\n');
};
```
### Init part
```
var gS={sharedDictUrl:'http://cartou.ch/sharedstuff/testdict.txt'};
window.onload=function() {
var zrequest = new XMLHttpRequest();
zrequest.open('GET',gS.sharedDictUrl,false);
zrequest.onload = loadWords; zrequest.send(null);
document.getElementById('gobutton').addEventListener('click',go);
}
function loadWords(e) {
gS.words = e.target.responseText.match(/[a-z]+/g);
document.getElementById('spWords').innerHTML = "Shared dict loaded: " +
gS.words.length + ' words.)';
};
```
### HTML part
```
<!DOCTYPE html>
<html>
<head>
<title>Same word when missing letters</title>
</head>
<script type="text/javascript" src="same-missing.js"></script>
<body><button id="gobutton">GO</button>
<span id="spWords">Loading dictionary...</span><br>
Word size: <input id="tbWordSize" size="3" value="11">
Missing letters: <input id="tbLetters" size="3" value="3">
<br>
<div id="Info">---</div>
<pre id="Output"></pre>
</body>
</html>
```
[Answer]
# Haskell
Time complexity is O(C(**n**, **m**) \* **m** \* **L** \* **n** + **k** log(**k**)), where
* C(n, m) = n ! / ((n - m)! \* m !)
* **n**: number of words with length **L**
* **m**: mask count
* **L**: word length
* **k**: number of results
## Steps
* Read and filter words
* Generate all masks, each looks like "0011000"
* For each mask, apply it to all words. For example, applying mask "00110" for word "masks" results in "mas--s".
* Group the words by first applying mask on them and then group by a hashmap.
* For each group, process it and get a result.
* Concat , sort and then print all results.
## Usage
Name the file `wordcalc.hs` and then compile it with
```
ghc -O3 wordcalc.hs
```
Then run it with
```
./wordcalc testdict.txt 11 3
```
Or without arguments, that's profiling
```
./wordcalc
```
## Performence
Tested on my four years old i3 laptop with Archlinux.
```
testdict.txt 11 3 -> Time: 1.639882s Count: 31695
testdict.txt 11 5 -> Time: 5.328377s Count: 217138
wordlist.txt 11 3 -> Time: 18.316671s Count: 323347
wordlist.txt 11 5 -> Time: 63.536398s Count: 2069632
```
## Code
```
import Control.Monad
import Data.Function
import Data.Time.Clock
import Data.List
import qualified Data.HashMap.Strict as Map
import System.Environment
import System.IO
type Dict = [String]
type Mask = [Bool]
data Result = Result Int String [String]
instance Show Result where
show (Result count mask words) = concat $ [show count, ": ", mask, ": ", concat $ intersperse "," words]
main = do
args <- getArgs
if length args == 3 then
let [dictPath, wordLen, maskCount] = args
in mapM_ print =<< run dictPath (read wordLen) (read maskCount)
else
profile [
("testdict.txt", 11, 3)
, ("testdict.txt", 11, 5)
, ("wordlist.txt", 11, 3)
, ("wordlist.txt", 11, 5)
]
profile :: [(FilePath, Int, Int)] -> IO ()
profile cases = do
forM_ cases $ \(path, n, m) -> do
handle <- openFile ".profile-tmp" WriteMode
t0 <- getCurrentTime
results <- run path n m
mapM_ (hPrint handle) results
hClose handle
t1 <- getCurrentTime
putStrLn . unwords $ [
path, show n, show m, "->", "Time:", show $ diffUTCTime t1 t0, "Count:", show $ length results]
run :: FilePath -> Int -> Int -> IO [Result]
run dictPath wordLen maskCount = do
words <- readWords wordLen dictPath
let sort = sortBy (compare `on` (\(Result c _ _) -> -c))
let masks = genMasks wordLen maskCount
return . sort $ calc masks words
readWords :: Int -> FilePath -> IO [String]
readWords n path = return . filter ((==n) . length) . lines =<< readFile path
calc :: [Mask] -> [String] -> [Result]
calc masks words = do
mask <- masks
let group = Map.elems . Map.fromListWith (++)
words' <- group [(applyMask' mask w, [w]) | w <- words]
let count = length words'
if count > 1 then
return $ Result count (applyMask mask . head $ words') words'
else
fail ""
genMasks :: Int -> Int -> [Mask]
genMasks n m
| n < m = []
| m == 0 = [replicate n False]
| otherwise = map (True:) (genMasks (n-1) (m-1)) ++ map (False:) (genMasks (n-1) m)
applyMask, applyMask' :: Mask -> String -> String
applyMask = zipWith (\b c -> if b then '-' else c)
applyMask' mask word = [c | (b, c) <- zip mask word, not b]
```
---
## CoffeeScript Version
Try it on [jsfiddle](http://jsfiddle.net/70rgdjj7/2/).
```
MASK_CHAR = '-'
output = (text) ->
div = $('#output')
div.html(div.html() + text + '\n')
clear = () ->
$('#output').html('')
compare = (a, b) ->
if a < b then return -1
if a > b then return 1
return 0
class Result
constructor: (@mask, @words) ->
@count = @words.length
toString: () ->
@count + ': ' + @mask + ': ' + @words.join ','
calc = (words, wordLen, maskCount) ->
words1 = words.filter (w) -> w.length == wordLen
results = []
for mask in genMasks(wordLen, maskCount)
calcForMask(words1, mask, results)
results.sort (r1, r2) -> - compare(r1.count, r2.count)
return results.filter (r) -> r.count > 1
applyMask = (mask, word) ->
((if mask[i] != MASK_CHAR then word[i] else MASK_CHAR) for i in [0..mask.length-1]).join ''
calcForMask = (words, mask, results) ->
resultMap = {}
for word in words
maskedWord = applyMask(mask, word)
if not resultMap[maskedWord]?
resultMap[maskedWord] = [word]
else
resultMap[maskedWord].push(word)
for maskedWord, words of resultMap
results.push(new Result(maskedWord, words))
genMasks = (n, m) ->
if n < m then return []
if m == 0
if n == 0 then return [[]]
return [('x' for i in [1..n])]
use = genMasks(n - 1, m - 1)
notUse = genMasks(n - 1, m)
for x in use
x.push(MASK_CHAR)
for x in notUse
x.push('x')
return use.concat notUse
run = (dictURL, wordLen, maskCount, onStart, onFinish) ->
$.ajax
method: 'get'
url: dictURL
dataType: 'text'
.success (data) ->
output('File size: ' + data.length)
words = data.match(/[a-z]+/g)
output('Calculating...')
onStart(words)
results = calc(words, wordLen, maskCount)
onFinish(results)
.fail (error) ->
output('Failed to fetch words')
output('Error: ' + arguments)
profile = (dictURL, wordLen, maskCount) ->
timer = {}
clear()
# output(('-' for i in [1..120]).join '')
output('Fetching words...')
onStart = (words) ->
output('Got ' + words.length + ' words')
timer.timeStart = new Date()
onFinish = (results) ->
timer.timeEnd = new Date()
timer.time = timer.timeEnd - timer.timeStart
output('Time used: ' + (timer.time / 1000).toFixed(3) + ' sec')
output('Count: ' + results.length)
if $('#output_result').is(':checked')
output((r.toString() for r in results).join '\n')
output('Finished')
run(dictURL, wordLen, maskCount, onStart, onFinish)
$ () ->
$('#button').click () ->
profile($('#url').val(), parseInt($('#word_len').val()), parseInt($('#mask_count').val()))
# $('#button').click()
```
---
## Another version with same algorithm: Python 3
```
import sys
import itertools
from collections import defaultdict
def calc(words, n, m):
words = [w for w in words if len(w) == n]
results = []
for mask in itertools.combinations(range(n), m):
groups = defaultdict(list)
for word in words:
word1 = list(word)
for i in mask:
word1[i] = '-'
word1 = ''.join(word1)
groups[word1].append(word)
for word1, words1 in groups.items():
if len(words1) > 1:
results.append((len(words1), word1, words1))
results.sort(key=lambda x: -x[0])
return results
def main():
path, n, m = sys.argv[1:]
words = list(map(str.rstrip, open(path)))
for c, w, ws in calc(words, int(n), int(m)):
print('{}: {}: {}'.format(c, w, ','.join(ws)))
main()
```
[Answer]
# C++11
Not quite sure how to define a "logical operation" so I may be a little more/less strict than you'd like, but I gave it a shot.
```
#include <algorithm>
#include <fstream>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
static size_t _g_score = 0;
typedef vector<char> WordMask;
typedef vector<WordMask> WordMaskList;
typedef list<string const *> WordSet;
struct ScoredString : public string
{
ScoredString(string s) : string(s) { }
bool operator <(ScoredString const rhs) const
{
_g_score++;
return strcmp(c_str(), rhs.c_str()) < 0;
}
};
typedef map<ScoredString, WordSet *> WordMaskMap;
struct WordDatabase
{
vector<string *> wordList;
WordMaskMap maskMap;
};
static WordMaskList makeMaskList(int wordLen, int numBlanks);
static WordDatabase createWordDatabase(ifstream &file, int wordLen, WordMaskList const &masks);
int main(int argc, char **argv)
{
if (argc < 4)
{
cout << "Usage: perms <dict_file> <word_len> <num_blanks>";
return 1;
}
ifstream file(argv[1]);
if (!file.is_open())
{
cerr << "Failed to open dictionary file: [" << argv[1] << "]!" << endl;
return 1;
}
int wordLen = atoi(argv[2]);
// generate all mask permutations
WordMaskList masks = makeMaskList(wordLen, atoi(argv[3]));
// read file and create the database of words and their mappings
WordDatabase db = createWordDatabase(file, wordLen, masks);
// iterate the mapping database and created a priority (sorted) queue
// using the desired sorting criteria
struct QueueData
{
string const *mask;
WordSet const *ws;
size_t wsSz;
bool operator <(QueueData const rhs) const
{
_g_score++;
if (wsSz == rhs.wsSz)
{
return strcmp(mask->c_str(), rhs.mask->c_str()) < 0 ? false : true;
}
return wsSz < rhs.wsSz;
}
};
priority_queue<QueueData> q;
for (auto i = db.maskMap.begin(); i != db.maskMap.end(); ++i)
{
if (i->second->size() > 1)
{
QueueData qd = {&i->first, i->second, i->second->size()};
q.push(qd);
_g_score++;
}
}
// and emit the queue by removing items from it
while (!q.empty())
{
QueueData qd = q.top();
cout << qd.wsSz << ": " << *(qd.mask) << ": { ";
for(auto i = qd.ws->begin(); i != qd.ws->end(); ++i)
{
cout << *(*i) << " ";
}
cout << "}" << endl;
q.pop();
_g_score++;
}
cout << endl << "Score: " << _g_score << endl;
return 0;
}
static WordMaskList makeMaskList(int wordLen, int numBlanks)
{
WordMaskList masks;
WordMask mask(wordLen);
fill_n(mask.begin(), numBlanks, true);
do
{
masks.push_back(mask);
} while (prev_permutation(mask.begin(), mask.end()));
return masks;
}
static void mapMaskedWord(WordMaskMap &mapInto, string const &word, WordMask const &mask)
{
string mword;
int i = 0;
for (auto j=mask.begin(); j != mask.end(); ++j, ++i)
{
mword += *j ? '-' : word[i];
}
auto wsi = mapInto.find(mword);
WordSet *ws;
if (wsi != mapInto.end())
{
ws = wsi->second;
}
else
{
ws = new WordSet();
mapInto.insert(make_pair(mword, ws));
}
ws->push_back(&word);
_g_score++;
}
static WordDatabase createWordDatabase(ifstream &file, int wordLen, WordMaskList const &masks)
{
WordDatabase db;
string word;
while (getline(file, word))
{
db.wordList.push_back(new string(word));
if (word.size() == wordLen)
{
for (auto mi = masks.begin(); mi != masks.end(); ++mi)
{
mapMaskedWord(db.maskMap, *(db.wordList.back()), *mi);
}
}
}
return db;
}
```
The algoirthm is pretty straight-forward; I create a map of ("mask", word set) pairs as I read the dictionary file. Each word in the dictionary file having a matching length is inserted into the map's sets once per mask permutation. Then I iterate the entire map to create a sorted queue to print. This is filtered by only those map entries whose set has > 1 element.
I define an operation as:
* any comparison performed by the map/queue to add elements
* any insertion/deletion/iteration
Like I said, I may have been a little more/less lenient. To be honest, I'd prefer just to count the comparisons as that's what you're trying to limit most during the execution.
[Answer]
## Counter draft (Not an answer!)
I would try to use this as draft for final counting.
### Scoreboard
There is a score tab where some try was counter or evaluated, by using shared dictionary file and the pairs (word length , missing chars): (4,1 5,2 11,3 11,9)
```
Test pairs โฏ4,1 5,2 11,3 11,9
```
* **1?** [F.Hauri](https://codegolf.stackexchange.com/a/35965/9424) - charwalk + hash [Fiddle](http://jsfiddle.net/2x4pjnfL/6/)
```
105โฏ564 289โฏ575 3โฏ329โฏ871 2โฏ849โฏ711
```
* **1?** [Ray](https://codegolf.stackexchange.com/a/36128/9424) - *`O(C(n, m) * m * L * n * log(n))`* - [Fiddle](http://jsfiddle.net/70rgdjj7/2/)
```
94 418 467 888 18 231 225 3 572 406
```
* **1?** [DarwinBot](https://codegolf.stackexchange.com/a/36063/9424) - *n log n* based - no fiddle no score.
```
TODO...
```
* **2?** [edc65](https://codegolf.stackexchange.com/a/35671/9424) - bitcount + hash [Fiddle](http://jsfiddle.net/38cUH/2/)
```
258 457 992 807 83 344 443 70 071 001
```
* **2?** [DreamWarrior](https://codegolf.stackexchange.com/a/36151/9424) - filtered sorted queue - no fiddle
```
322 239 1 563 388 55 460 636 8 471 745
```
* **3** [es1024](https://codegolf.stackexchange.com/a/35712/9424) - eggs, fries milk and cream - [Fiddle](http://jsfiddle.net/3avL5k2d/2/)
```
14โฏ299โฏ352 75โฏ187โฏ045 aborted not tried
```
* **4** [TwoThe](https://codegolf.stackexchange.com/a/35685/9424) - parallelStream acceptableWordDistance - [Fiddle](http://jsfiddle.net/0cyvj5je/1/)
```
22โฏ991โฏ392 112โฏ794โฏ153 aborted not tried
```
* **5** [Sparr](https://codegolf.stackexchange.com/a/35644/9424) - *exceptionally naive approach* - (no fiddle)
```
70 234 852 1 081 946 020 aborted not tried
```
Nota: There is a big difference between two 1st classified answer:
While pairs using small number seem present @Ray's solution a lot quicker than mine, for big numbers, this become totaly reversed:
```
pairs 2,1 3,2 9,4 18,2 18,8
F.Hauri 63โฏ353 69โฏ279 6โฏ706โฏ593 73โฏ772 4โฏ623โฏ416
Ray 598 7 490 23 065 888 73 416 26 075 903
```
@Ray seem using same aproach than @DarwinBot, but I don't already understand hot it work... I have a lot to work all around, in order to finalize this scoreboard... :-b
### Masks generations
This challenge do contain a strong step: mask or pattern generation.
Now, if 4 answer, there is already 3 (maybe 4, i'm not totally sure) different meaning:
* @Sparr seem doing approx same than @es1024: doing base mask containing *WordLengt*-*missing* letters concatenated with *missing* number of `_`, than iterate over all possible combinations.
* @edc65 use binary based constructions, searching for shapes containing correct number of *missing*
* @TwoThe use a totaly different method where words pairs are knowns and from one pair we just have to search for differences.
If I rightly count, taking for sample `8` char length and `3` missing chars:
* Iterate over 8 chars implie `8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 40320` steps to be *unified*, regardless of missing number chars.
* Building binary masks for 8 chars generate 256 shapes to be filtered for having *missing* number of `0` (or `1` depending on how routine work): 256 shapes + 256 tests + 28 mask creation = 540 steps (et least).
Where, for 8 chars, having 2 missing, there are 28 different *masks*.
In a 1'st day comment @sparr was right when saying *it looks like you already have a solution* ;-)
For comparission, my 1st prototype algoritm was [bash](/questions/tagged/bash "show questions tagged 'bash'") writed. I'ts really easy for counting steps (using `set -x`). So for 8 char length, and
* 1 missing -> 8 masks, 32 steps
* 2 missing -> 28 masks, 148 steps
* 3 missing -> 56 masks, 392 steps
* 4 missing -> 70 masks, 658 steps
* 5 missing -> 56 masks, 728 steps
* 6 missing -> 28 masks, 532 steps
* 7 missing -> 8 masks, 248 steps
Note: Using `set -x` is very strict for counting steps, as each comparission, test or assing is counted as one step.
### Word iteration
There is mainly two different method:
Where @es1024, @ThoThe and @Sparr use double iteration for making comparission,
@edc65 use only one iteration over all words for storing counters based on *shape*.
The second method seem more efficient for a big direcory file. (they was the one I've used in my first try;)
### Algorithm improvement
1. Instead of:
```
for () { if () { ... } else { ... } }
```
prefer to write:
```
if () { for () { ... } } else { for () { ... } }
```
whenever possible
2. Same as previous: do filtering over results **before** sorting!
prefer
```
keys.filter(match).sort().map( printout )
```
than:
```
keys.sort().map( if (match) { ... } )
```
... if you can.
] |
[Question]
[
A [subsequence](http://en.wikipedia.org/wiki/Subsequence) is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
Given three strings A, B and C (note the order) as input, find the length of the longest string S such that:
* **Condition 1:** S is a subsequence of A
* **Condition 2:** S is a subsequence of B
* **Condition 3:** C is a substring of S
.
```
Testcase #1
```
**Input:**
ABCDEF
CDEFAB
B
**Output:**
2
```
Testcase #2
```
**Input:**
HELLO
WORLD
SUCKS
**Output:**
0
```
Testcase #3
```
**Input:**
ABCXD
BCDEF
CD
**Ouput:**
3
```
Testcase #4
```
**Input:**
X
Y
Z
**Ouput:**
0
**Note:**
* The empty string is regarded as a subsequence as well as a substring of every string.
* Assume all input strings are in uppercase.
* Return 0 as output if any of the first two conditions (Condition 1 and Condition 2) is not going to be satisfied using Condition 3.
**Constraints:**
* Assume the lengths of A, B and C will always be between 1 and 3000 (both inclusive)
**Winner:**
One with the shortest code.
[Answer]
## APL (45)
```
โ/0,โดยจm/โจโจ/ยจโโโทยจmโโโฉ/{/โโตยจโโ(z/2)โคโณ2*zโโดโต}ยจโโ
```
Explanation:
* `ยจโโ`: read two lines. For each of them:
+ `โณ2*zโโดโต`: get the numbers from `1` up to `2^length`.
+ `(z/2)โค`: encode each number as bits
+ `โโ`: separate each string of bits into its own array
+ `/โโตยจ`: and use each of them as a bitmask on the string, giving the subsequences
* `mโโโฉ/`: take the intersection of the two arrays of subsequences, store in `m`
* `โจ/ยจโโโทยจ`: read a third line, and see in which subsequences it occurs
* `m/โจ`: select those elements from `m` that contained the third line
* `โดยจ`: get the length of each remaining subsequence
* `0,`: add a zero entry in case the resulting list is empty
* `โ/`: get the highest number in the list
Test cases:
```
โ/0,โดยจm/โจโจ/ยจโโโทยจmโโโฉ/{/โโตยจโโ(z/2)โคโณ2*zโโดโต}ยจโโ
ABCDEF
CDEFAB
B
2
โ/0,โดยจm/โจโจ/ยจโโโทยจmโโโฉ/{/โโตยจโโ(z/2)โคโณ2*zโโดโต}ยจโโ
HELLO
WORLD
SUCKS
0
โ/0,โดยจm/โจโจ/ยจโโโทยจmโโโฉ/{/โโตยจโโ(z/2)โคโณ2*zโโดโต}ยจโโ
ABCXD
BCDEF
CD
3
โ/0,โดยจm/โจโจ/ยจโโโทยจmโโโฉ/{/โโตยจโโ(z/2)โคโณ2*zโโดโต}ยจโโ
X
Y
Z
0
```
[Answer]
# SWI-Prolog, 166
```
s(A,[H|R]):-(A=[H|T],s(T,R);s(A,R)).
s([],[]).
r(A,B,C,O):-(r(A,B,C,0,O),!;O=0).
r(A,B,C,M,O):-s(S,A),s(S,B),append([_,C,_],S),length(S,L),L>M,!,(r(A,B,C,L,O),!;L=O).
```
Usage:
```
?- r("abcxd","bcdef","cd",O).
O = 3.
```
[Answer]
**Python (181)**
Will probably be beat soundly by more operator rich languages, but since I so far have nothing to beat... :)
**EDIT: I originally read substring where it said subsequence, this is the subsequence version;**
```
from itertools import*
def f(a,b,c):
f=lambda x:set(''.join(z)for y in range(len(x))for z in combinations(x,y))
return max(len(x)for x in f(a).intersection(f(b))if c in x or not x)
```
What it does is basically to create 2 sets of all possible subsequences of the string `a` and the string `b`, intersecting them to find the common ones.
It then simply finds all resulting strings that contain the string `c` and prints the length of the longest matching string.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes, language postdates challenge
```
kโแต=h.s~t?โจ0
```
[Try it online!](https://tio.run/nexus/brachylog2#@5/9qKv94dYJthl6xXUl9o86Vhj8/x@t5OgU5Ojs6AKilHQUgFxnF1c3dxDTyUUp9n8UAA "Brachylog โ TIO Nexus")
This is a function. The TIO link uses a command-line argument that allows functions to be run like full programs.
## Explanation
```
kโแต=h.s~t?โจ0
k Take the input, apart from the last element.
โแต Find the longest subsequence of each element
= such that those subsequences are equal
h and that subsequence
s has a substring
~t? that's the last element of the input.
. If you can, return the subsequence.
โจ0 If all else fails, return 0.
```
[Answer]
### GolfScript, 45 characters
```
n/)`{?)}+\{['']\1/{`{1$\+}+%}/}/&\,{,}%0+$-1=
```
Takes input as three lines on STDIN. Take a test run [here](http://golfscript.apphb.com/?c=OyJBQkNERUYKQ0RFRkFCCkIiCgpuLylgez8pfStce1snJ11cMS97YHsxJFwrfSslfS99LyZcLHssfSUwKyQtMT0KCg%3D%3D&run=true).
*Short explanation of the code:*
```
n/ # split the input at newline into three strings
)` # take the last one and stringify it
{?)}+ # and build a code block to filter for any string
# which has that one as a substring (for later use)
\{ # now loop over the remaining two strings and
# build their subsequences
[''] # start with the set of the empty string
\1/{ # loop over each character of the string
`{ # apply code block to each member of the set
1$\+ # copy member and add the current character
}+% # -> set is updated with latest character
}/
}/
& # take the common subsequences
\, # apply the filter block from above
{,}% # from each string take length
0+ # add zero (if empty set was returned)
$-1= # sort and take last element (largest)
```
[Answer]
# Haskell, 90 81
Haskell provides everything you need in Data.List:
```
s=subsequences
f a b c=maximum$map length$filter(isInfixOf c)$intersect(s a)(s b)
```
If only the function names were shorter :)
[Answer]
# Mathematica ~~150~~ 125
```
f[{a_,b_,c_}]:=({z=Subsets[Characters@#]&,s};s=Select[""<>#&/@(z@aโz@b),!StringFreeQ[#,c]&];
If[s=={},0,StringLength[s[[-1]]]])
```
* `Characters` converts a string into a list of characters.
* `Subsets` finds all the subsequences (held as lists of characters).
* `s` refers to the list of ALL common subsequences (not the same a S).
* `s[[-1]]` is the last (and largest) common subsequence; it is equal to S as defined in the question.
**Test Cases**
```
f[{"ABCDEF", "CDEFAB", "B"}]
```
>
> 2
>
>
>
---
```
f[{"HELLO", "WORLD", "SUCKS"}]
```
>
> 0
>
>
>
---
```
f[{"ABCXD", "BCDEF", "CD"}]
```
>
> 3
>
>
>
---
```
f[{"X", "Y", "Z"}]
```
>
> 0
>
>
>
[Answer]
## **Perl, 122**
```
chomp(($A,$B,$C)=<>);$A=~s/(.)/($1)?.*?/g;$_=join'',map{$$_}1..$#-and/$C/&&$%<($-=length)and$%=$-while$B=~/.*?$A/g;print$%
```
The program expects 3 strings on STDIN and prints a number to STDOUT. Here it is re-written as sub for easier testing:
```
use feature 'say';
sub L{
($A,$B,$C,$%)=(@_,0);
$A=~s/(.)/($1)?.*?/g;
$_=join'',map{$$_}1..$#-and/$C/&&$%<($-=length)and$%=$-while$B=~/.*?$A/g;
$%
}
say L(qw/ABCDEF CDEFAB B/);
say L(qw/HELLO WORLD SUCKS/);
say L(qw/ABCXD BCDEF CD/);
say L(qw/X Y Z/);
```
and
```
perl LCSoTS.pl
2
0
3
0
```
So, **122** even with ugly byte-consuming chomping at the start. I hope no bugs crept in while I golfed it to this size. And not sure about scalability, but let it be the question of hardware :-).
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes
```
~c~gแตโจโแตsโฉl|โง
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmJiBXoyQjVaG4NKk4tbA0NS85VSGzGC7fUq6kqfRwV2ftw60T/tcl16U/3Dr90fwVj7raH26dXfxo/sqcmkcdy7HKgCSU8vJLFAryi4szk3JSFUryFZLz84pLikqTS5T@R0crOTo5u7i6KekogShHJyDDSSlWJ1rJw9XHxx/IC/cP8nEB0sGhzt7BYBmgjgiQCEIjWDgCyIwE4igwz7m0uCQ/V6EktbhEITmxOBUokZcJ9FdiXopCTn55ahFUMBVIQ7RHRkWBtANpsEEgMRNLQzAwMgAKGesZmhiaWhoBmSZGSrEA "Brachylog โ Try It Online")
I didn't bother scrolling down far enough to notice that ais had already answered in Brachylog before I wrote this, but it looks like his answer doesn't actually output the length. It's way shorter doing what it does (it could be golfed down to the 10-byte `kโแต.s~t?โจ` with the verify metapredicate and by leaving the output in case of failure to simply default to 0, and then every other integer), but if you try to get it to output the length it ends up tying this (while still making a lot more sense than anything that handles a set number of arguments with `~c`!): [`kโแตXs~t?โงXl.โจ`](https://tio.run/##RY/PSsNAEMZfZZmThRhMjIdeLPlTFQwUWsQ0oYckLjYYs5rdEET0UMFWT959AHv00otvk7xIOptGXVi@b37DN8xEeRjPH1J2rTePJZD9YwLloH79rhcLLPfEnBJeRJzeFzSLKUn4X/@lhB5UP29P1eajuanfl9Xm0@PPYlCvvrxUrVfrX6ru6BoyJsgd4zyJUkoEIzHLuMiLWEATBGBatjM8AQWkmBYaC2ZKAGdD1x1hdTkauw7q5MI@n7QdTHiS/Adb7KGd4vfbyi64YLdEUC5IHHKKjSzBU8LsiqSspHkHKeouPvV9GUdtB0lm9LX26QeIDlXN0I76OlpD7xYZm7bpSAGFdJecSmvhSrMt)
A remarkably confusing explanation of my original solution:
```
~c A partition of
the input
แต such that its last element
~g is a list containing one element
~gแต which is replaced with that element
โจ โฉ is a list of two elements
l such that the implicit variable the length of which
| is the output
โจโแต โฉ is a subsequence of both elements of the first element of the partition
โจ sโฉ and has the last element of the partition as a substring.
| If it's not possible to find such a subsequence,
โง leave the output variable unconstrained, so it will default to 0.
```
`~chแตโจโแตsโฉl|โง` is one byte shorter, but provides an incorrect output when the second element of the input is a substring of a subsequence of the first, like [this](https://tio.run/##SypKTM6ozMlPN/r/vy454@HW6Y/mr3jU1f5w6@ziR/NX5tQ86lj@/3@0UkhGYol6sUKiQnFpUnFJUWZeukJ@mkJJRmaxko4SkiiQF5xZpOCXX6KbWFCQmggS083M0wWp1E3LzMlViv0fBQA) or [this](https://tio.run/##SypKTM6ozMlPN/r/vy454@HW6Y/mr3jU1f5w6@ziR/NX5tQ86lj@/3@0krOjs5Ozko6SI5h0Vor9HwUA). `~ctแตโจโแตsโฉl|โง` [completely disregards the second element of the input](https://tio.run/##SypKTM6ozMlPN/r/vy655OHW6Y/mr3jU1f5w6@ziR/NX5tQ86lj@/3@0krOjs5Ozko6SS35qsUJefolCcn5eSWJmnkJyYkFmSWKOQrJCYolCYk6OIlCRs1Ls/ygA).
] |
[Question]
[
The Brits aren't exactly known for being good at memorizing stuff. [That's why scientists need newspaper articles to find those who are](https://www.dailymail.co.uk/health/article-12041039/Are-super-memoriser-Scientists-release-game-hunt-Brits-exceptional-memory.html), and that's why it shouldn't be a surprise that [they forget more than a 1000 things per year](https://www.thesun.co.uk/news/uknews/18830375/brits-forget-more-than-one-thousand-things-each-year/), including phone numbers, addresses, birthdays and more. Now, it is your duty to help the Brits remember their numbers.
In a [2010 video by the BBC](https://youtu.be/IlCYGeA2Ne0?si=i9yYbnusbR0R86e7&t=32) (from 0:32 to 1:10), a trick is explained on how to do just that:
First, the base-10 string of the number is partitioned into several smaller non-overlapping parts, which then individually fit into one of four categories (three in the video, including one residual category for this challenge). No part of the partition is allowed to start with a `0`, except individual digits (This makes the challenge fairer for languages that only work with numbers and not with strings). Each category then has an associated cost. Your goal is to find the partition of the string such that the total cost is minimal, and output that partition. The four categories are:
---
##### 1. Addition or multiplication:
Three or four digits in which the first two add or multiply to the third or, in case of a carry, the third and fourth digit.
Examples:
```
112 # 1 + 1 = 2
347 # 3 + 4 = 7
549 # 5 + 4 = 9
5510 # 5 + 5 = 10
606 # 6 + 0 = 6
9817 # 9 + 8 = 17
111 # 1 * 1 = 1
3412 # 3 * 4 = 12
5420 # 5 * 4 = 20
5525 # 5 * 5 = 25
600 # 6 * 0 = 0
9872 # 9 * 8 = 72
```
Cost:
* Addition without carry: `2`
* Addition with carry: `3`
* Multiplication without carry: `3`
* Multiplication with carry: `5`
##### 2. Relation to a year:
Four digits that form an year considered to contain an important date. For the sake of this challenge, this is every year in which a [British monarch](https://en.wikipedia.org/wiki/List_of_British_monarchs) died.
Exhaustive list:
```
1714, 1727, 1760, 1820, 1830, 1837, 1901, 1910, 1936, 1952, 1972, 2022
```
Cost:
* 18th and 19th century: `4`
* 20th century: `2`
* 21st century: `1`
##### 3. Similarity to a symbol:
A sequence of numbers that look like a symbol. Since Unicode is too vast and symbols are ill-defined, we will instead use any sequence of four digits that is a British word if [typed on a 7-segment display calculator](https://en.wikipedia.org/wiki/Calculator_spelling) that is then rotated 180ยฌโ.
Exhaustive list (taken from [this](http://mathsquad.com/calculatorwords.pdf) file, filtered by whether there is a C1-level [Oxford Dictionary](https://www.oxfordlearnersdictionaries.com) entry of the same exact name):
```
3215, 3507, 3573, 3705, 5507, 5508, 5537, 7105, 7108, 7718, 7735, 7738
```
Cost: `3`
##### 4. Residual digit
Any digit not part of such a pattern will be treated as a residual digit and be assigned a cost of `2`.
### Challenge
In this challenge, you will be given a non-negative number as input and will output the partition of the number such that it is as easy to remember as possible for a Brit, minimizing the total cost. If multiple equivalent partitions exit, you may choose arbitrarily.
You may take the input as a 64-bit (or wider) integer, a string containing the decimal representation or a list of decimal digits. You may output the partition as a list of numbers, or, if your language doesn't support lists, a [Gโโdel-encoded list](https://codegolf.stackexchange.com/questions/259960/g%C3%B6del-encoding-part-i) or similar. You may additionally output the cost, but this is neither required nor beneficial (I'd assume).
If your language has a builtin for generating optimal partitions for Brits to remember numbers, usage of it is not discouraged.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code (as measured in bytes) wins.
### Test cases
Note that the test case's outputs are only examples and you might output a different output with the same cost. Note that if you calculate a partition with a different cost, your solution is most likely faulty.
| Input | Output | Cost | Cost explanation | Explanation |
| --- | --- | --- | --- | --- |
| 1972 | [1972] | 2 = 2 | Monarch died 20th century | Death of Edward VIII |
| 19729 | [1972, 9] | 4 = 2 + 2 | Monarch died 20th century + Single digit | Death of Edward VIII followed by a 9 |
| 1972022 | [1, 9, 7, 2022] | 7 = 2 + 2 + 2 + 1 | Single digit x3 + Monarch died 21st century | Lone 1, 9 and 7 followed by the death of Elizabeth II |
| 92183721 | [9218, 3721] | 10 = 5 + 5 | Multiplication with carry x2 | 9 \* 2 = 18, 3 \* 7 = 21 |
| 123 | [123] | 2 = 2 | Addition without carry | 1 + 2 = 3 |
| 44812 | [4, 4812] | 5 = 2 + 3 | Single digit + Addition with carry | 4 followed by 4 + 8 = 12 |
| 48123 | [4812, 3] | 5 = 3 + 2 | Addition with carry + Single digit | 4 + 8 = 12 followed by 3 |
| 1820224610 | [1, 8, 2022, 4610] | 8 = 2 + 2 + 1 + 3 | Single digit x2 + Monarch died 21st century + Addition with carry | 1 and 8 followed by the death of Elizabeth II and 4 + 6 = 10 |
| 4312370550707 | [4312, 3705, 5, 0, 707] | 14 = 5 + 3 + 2 + 2 + 2 | Multiplication with carry + British word + Single digit x2 + Addition without carry | 4 \* 3 = 12, then the word 'sole', a five, a zero and 7 + 0 = 7 |
| 54202243215 | [5420, 224, 3215] | 10 = 5 + 2 + 3 | Multiplication with carry + Addition without carry + British word | 5 \* 4 = 20, 2 + 2 = 4, and the word 'size' |
| 171419012022 | [1714, 1901, 2022] | 7 = 4 + 2 + 1 | Monarch died 18th-19th century + Monarch died 20th century + Monarch died 21st century | The death of every female British monarch |
| 171450119010112022 | [1714, 5, 0, 1, 1901, 0, 1, 1, 2022] | 19 = 4 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 1 | Monarch died 18th-19th century + Single digit x3 + Monarch died 20th century + Single digit x3 + Monarch died 21st century | The death of every female British monarch, interrupted by 5, 0, 1 in the first and 0, 1, 1 in the second position |
| 99819918182022 | [9981, 9918, 1, 8, 2022] | 13 = 5 + 3 + 2 + 2 + 1 | Multiplication with carry + Addition with carry + Single digit x2 + Monarch died 21st century | 9 \* 9 = 81, 9 + 9 = 18, lone 1 and 8 followed by the death of Elizabeth II |
| 1248163264128 | [1, 248, 1, 6, 326, 4, 1, 2, 8] | 20 = 2 + 3 + 2 + 2 + 3 + 2 + 2 + 2 + 2 | Single digit + Multiplication without carry + Single digit x2 + Multiplication without carry + Single digit x4 | |
| 123512351235 | [1, 235, 1, 235, 1, 235] | 12 = 2 + 2 + 2 + 2 + 2 + 2 | Single digit + Addition without carry + Single digit + Addition without carry + Single digit + Addition without carry | |
| 23550877187738 | [2, 3, 5508, 7718, 7738] | 13 = 2 + 2 + 3 + 3 + 3 | Single digit x2 + British word x3 | 2 and 3, 'boss', 'bill', 'bell' |
| 732133933917141760 | [7321, 339, 339, 1714, 1760] | 19 = 5 + 3 + 3 + 4 + 4 | Multiplication with carry + Multiplication without carry x2 + Monarch died 18th-19th century x2 | |
### Computer-readable test cases without explanations
```
1972 -> [1972]
19729 -> [1972, 9]
1972022 -> [1, 9, 7, 2022]
92183721 -> [9218, 3721]
123 -> [123]
44812 -> [4, 4812]
48123 -> [4812, 3]
1820224610 -> [1, 8, 2022, 4610]
4312370550707 -> [4312, 3705, 5, 0, 707]
54202243215 -> [5420, 224, 3215]
171419012022 -> [1714, 1901, 2022]
171450119010112022 -> [1714, 5, 0, 1, 1901, 0, 1, 1, 2022]
99819918182022 -> [9981, 9918, 1, 8, 2022]
1248163264128 -> [1, 248, 1, 6, 326, 4, 1, 2, 8]
123512351235 -> [1, 235, 1, 235, 1, 235]
23550877187738 -> [2, 3, 5508, 7718, 7738]
732133933917141760 -> [7321, 339, 339, 1714, 1760]
```
I express my deepest gratitude for your unwavering support during these challenging times faced by Great Britain. Your contributions to assisting impoverished, forgetful Britons are truly cherished and immensely valued. May God save the King! ๏ฃฟรผรกยจ๏ฃฟรผรกร ๏ฃฟรผรกยจ๏ฃฟรผรกร ๏ฃฟรผรกยจ๏ฃฟรผรกร ๏ฃฟรผรกยจ๏ฃฟรผรกร ๏ฃฟรผรกยจ๏ฃฟรผรกร
[Answer]
# JavaScript (ES7), 274 bytes
Expects a string and returns the partition as an array of integers.
```
f=([v,...a],p=[],s=q=0,c="",[w,x,y,z]=c)=>(v&&!z&&f(a,p,s,c+v),c?f(a,[...p,c++],s+=x?/1(bn|c0|cx|el|ev|f2|gu|h3|ht|i9|it|k7)|2(hc|pg|ra|uy)|49[01u]|5(he|hh|y[fwz])/.test(c.toString(36))?w>2?3:1<<16/x:[w-+-x]==(y+=+w?[z]:f)?3-!z:[w*x]==y?z?5:3:1/0:2,v):v||q&&s>q?o:(q=s,o=p))
```
[Try it online!](https://tio.run/##dVLbsqIwEHzfr@DwYJElai5ACHUiH7GPFA8uq@KuJSqIl8q/uxOUc9SoJUHT09Mz0/N32k7rYrfcNMN19Wd2ucyVl7V4NBpNc7xRWY5rtVUEF8p1cXbAR3zC51wVSE28djD4OA8Gc2@KN7jGhd8iXKTmbwb8DVz4QPfVMR1T7/daF0QXRz1b6Vmr50wv9rrkumz0Uuplo/8JpJlXFnqz0Lup3p@QDmRG6D7XoVfOdFnqUzY/nHM0HjWzuvGKUVP9anbL9cLjEULpYcJSntDPTxqNj0l2GPrDY66Ud/KVf0izc57MUcqHH2fAfhrklJ7TMAHKmCQMtyhptd4OBvVkm1aJt1U1rtQGoUtRretqNRutqoU399yQktB1Hj4IOeOxk4XYodgh2AnzH08kKgV7TTLIy3DpvgvHjnzJIOxBo2dAOHYEdgxu8SSjMReMuhbPINgxmC3G@FMzX2KMW9FBEFP2spkAOwazGbGl0DMAgaLsimLTXRBR4trtx9feQQxwW4yDmCBhSAQR7oMY78QAA0s7YyHC4odBJ80Z/VqLfh8AAWkGbRrULlrQgEpC74zriwYElgmwN7aZgJBQEwFnl@CBei2X9jluv9/tgIyplDS@DtG93wFAYH2k2YTvQb7YB/Al4iwKKIvdp@kD1pEjMwU4gmshkO3VXoX94z67CHdX5vfbSgB3IYmFoPDw@L4TYySMBVBwUdDu5HYFAoziXMK3M0dEpJ@rQSAHl7fjZhFE5Jf/ "JavaScript (Node.js) โรรฌ Try It Online")
This gives alternate solutions for a few test cases.
## Scoring method
We make sure that each part \$c\$ is made of at most 4 characters and split them into \$[w,x,y,z]\$.
* If \$x\$ is not defined: this is a single digit โรปรน the score is \$2\$.
* We test all special patterns at once with the following regular expression applied to the base-36 representation of \$c+1\$:
```
/1(bn|c0|cx|el|ev|f2|gu|h3|ht|i9|it|k7) // 1715 to 2023
|2(hc|pg|ra|uy) // 3508 to 3706
|49[01u] // 5508 to 5538
|5(he|hh|y[fwz])/ // 7106 to 7739
```
If a match is found:
+ If \$w>2\$, this is a 'symbol' โรปรน the score is \$3\$.
+ Otherwise the score is given by the expression `1<<16/x` (\$1\$ for `2**0**23`, \$2\$ for `1**9**xx`, \$4\$ for `1**7**xx` or `1**8**xx`).
* If \$w\neq0\$:
+ If `[w-+-x]==y+[z]`, the score is either \$2\$ or \$3\$.
+ If `[w*x]==y+[z]`, the score is either \$3\$ or \$5\$.
* If none of the above worked out, the score is \$\infty\$.
Below is the corresponding code:
```
x ?
/1(bn|c0|cx|el|ev|f2|gu|h3|ht|i9|it|k7)|2(hc|pg|ra|uy)|49[01u]|5(he|hh|y[fwz])/
.test(c.toString(36)) ?
w > 2 ?
3
:
1 << 16 / x
:
[w - +-x] == (y += +w ? [z] : f) ?
3 - !z
:
[w * x] == y ?
z ?
5
:
3
:
1 / 0
:
2
```
## Main function
```
f = ( // f is a recursive function taking:
[v, ...a], // v = next digit, a[] = remaining digits
p = [], // p[] = list of parts
s = // s = score
q = 0, // q = best score so far, or 0 if not defined
c = "", // c = current part
[w, x, y, z] = c // (w, x, y, z) = the 4 characters in c
) => ( //
v && !z && // if v is defined and z is undefined,
f(a, p, s, c + v), // do a recursive call where v is added to c
c ? // if c is not empty:
f( // do another recursive call:
a, // pass a[]
[...p, c++], // append c (coerced to an integer) to p[],
// then increment c
s += ..., // update the score (see above)
v // set c = v
) // end of recursive call
: // else:
v || // if v is defined
q && s > q ? // or q != 0 and s > q:
o // leave the final output o unchanged
: // else:
(q = s, o = p) // update q to s and o to p
) //
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 114 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.โรฌDลยตลยตgโรชViยฌโโยด5;โโiโรยขโโลยฉโรjnโรโยฑ8โยง{5pqโรญลยฉ&โรยข l
&5โรญZtโโโโ โรรโยฉ~ลยชโยฃโรนลยฑBโรยฐ~hqโรยขโรฆEโโคykยฌยฉ(iyยฌยจ_iโยดR3โยงโโ ยฌยฉ`+QY<*D_i\ยฌร`*QYD4Q+*D_I*+}โยดยฌรโฮฉลโโรโซโรรโโค@O]OWkโยฎ
```
[Try it online](https://tio.run/##AbsARP9vc2FiaWX//y7Fk0TOtc61Z8OQVmnCt8OrNTvDt2nigKLQuM6pw4VqbsODw7E4w6R7NXBxxZLOqSbihKIgbAomNcaSWnTDuMOg4oKGw6l@zrvDo8OdzrFC4oChfmhx4oCixb5F0LJ5a8KpKGl5wqxfacOrUjPDpMOtwqlgK1FZPCpEX2lcwq5gKlFZRDRRKypEX0kqK33Dq8Kuxb3OtuKAuuKCgtCyQE9dT1drw6j//zU0MjAyMjQzMjE1) or [verify almost all test cases](https://tio.run/##NYzBSgJRFIb3PYW4kNCLzLlzr/cOBUZMazHItBItiJqMSopgiESsXIetgzIXDVOCgilFLeYwLQefYV5kmlFa/B@c8/N/p@e7e8Z@cGlm4zG/3YnFs6a@EQ/S7oPujbzRAd4XDGeMNl/CseE3u9OJZ@Hd0Qne4EBi74qf1d2OZyX8227seCHBfztbFzjBJ7/VRqvhfeELPnqDVb/53Dish3v3Z206NGuOtWiYzlvFKKK9rmIP3x2rmsqXlpN6xdhx@tVkvqSzfCo8i8nUNdpO3/32Pvzmp99qTYcrObSL5dxmDV@DeLpAgm3QBCURtBkVSolGQaqCAgGqEsYkUBJBJSCjnmVAIUwNH0LhXBGKIJzNCpUCJyCAgabAXKVJ0DSQ82UoDEUZlWYYUBnp@X9IGK5IISCMKst/) (the largest two are omitted because they'll timeout on TIO).
**Explanation:**
```
.โรฌ # Get all partitions of the (implicit) input
D # Duplicate it
ลยต # Map over each partition:
ลยต # Inner map over each part:
g # Pop and push the length of the part
โรช # Triplicate this length
V # Pop one copy, and store it in variable `Y`
i # Pop another copy, and if it's 1:
ยฌโ # Double the length to 2
โยด # Else (the length is >=2):
5; # Push 2.5 (halve 5)
โโ # Integer-divide the length by this 2.5
i # If this is 1 (aka the length was 3 or 4):
โรยขโโลยฉโรjnโรโยฑ8โยง{5pqโรญลยฉ&โรยข l\n&5โรญZtโโโโ โรรโยฉ~ลยชโยฃโรนลยฑBโรยฐ~hqโรยข
# Push compressed integer 2059679753934118777767891051414020721847227706932308941504785260793787677550089063849770927917
โรฆEโโค # Convert it to base-8192 as list: [2022,1901,1910,1936,1952,1972,3215,3507,3573,3705,5507,5508,5537,7105,7108,7718,7735,7738,1714,1727,1760,1820,1830,1837]
yk # Get the index of the current part in this list
# (or -1 if it's not in this list)
ยฌยฉ # Store this index in variable `ยฌร` (without popping)
(i # If the index is -1:
y # Push the current part again
ยฌยจ # Push its leading digit (without popping)
_i # If this leading digit is a 0:
# (use the current part implicitly)
โยด # Else:
R # Reverse the part
3โยง # Split it into three parts
โโ # Reverse each part
# (converts the part to a triplet: ABCโรรญ[C,B,A] and ABCDโรรญ[CD,B,A])
ยฌยฉ # Store this triplet in variable `ยฌร` (without popping)
` # Pop and push the parts to the stack
+ # Add the top two (B+A)
Q # Check if its equal to the other integer (C or CD)
Y< # Push the part's length - 1
* # Multiply it to the check
D # Duplicate it
_i # Pop and if it's 0:
\ # Discard the duplicated part
ยฌร # Push triplet `ยฌร` again
`*Q # B*A this time
YD4Q+ # Push the part's length + (length==4)
* # Multiply it to the check
D # Duplicate it
_ # Pop and check whether its 0
I* # Multiply it to the input
+ # Add it to the earlier value
} # Close this if-statement
# (implicit else: use the duplicated value)
โยด # Else (the index was not -1):
ยฌร # Push the index again from variable `ยฌร`
โฮฉลโโรโซ # Push compressed integer 17749
โรรโโค # Convert it to base-26 as list: [1,0,6,17]
@ # Check for each whether it's >= the index
O # Sum those checks together
# (implicit else: the length is 2 or >=5)
# (implicitly use the implicit input-integer)
] # Close all if-else statements and the nested maps
O # Sum each inner list together
W # Push the minimum of the sums (without popping the list)
k # Get the (first) index of this minimum in the list of sums
โยฎ # Use that to index into the list of partitions
# (after which this partition is output implicitly as result)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compressed integers and lists work.
[Answer]
# Haskell, 560 bytes
```
i x=read[x]
r x c=(\(a,b)->(a+c,x:b)).f
m(a:b:c:l)|i a+i b==i c&&a/='0'=r[a,b,c]2l
|i a*i b==i c&&a/='0'=r[a,b,c]3l
m(a:b:c:d:l)|i a+i b==read[c,d]&&a/='0'&&c/='0'=r[a,b,c,d]3l
|i a*i b==read[c,d]&&a/='0'&&c/='0'=r[a,b,c,d]5l
m _=(maxBound::Int,[])
y(a:b:c:d:l)|elem[a,b,c,d]$words"1714 1727 1760 1820 1830 1837"=r[a,b,c,d]4l
|elem[a,b,c,d]$words"1901 1910 1936 1952 1972"=r[a,b,c,d]2l
|[a,b,c,d]=="2022"=r[a,b,c,d]1l
|elem[a,b,c,d]$words"3215 3507 3573 3705 5507 5508 5537 7105 7108 7718 7735 7738"=r[a,b,c,d]3l
y(x:l)=r[x]2l
f[]=(0,[])
f l=min(m l)$y l
```
Ungolfed version:
```
import Data.Char
import Control.Arrow
type Partition = [String]
badResult :: (Int, Partition)
badResult = (maxBound, [])
optimalMemorization :: String -> (Int, Partition)
optimalMemorization [] = (0, [])
optimalMemorization xs = minimum $ map ($ xs) [math, relation]
recurse :: String -> String -> Int -> (Int, Partition)
recurse prefix rest cost = ((+ cost) *** (prefix :)) (optimalMemorization rest)
math :: String -> (Int, Partition)
math (a:b:c:xs)
| digitToInt a + digitToInt b == digitToInt c && a /= '0' = recurse [a, b, c] xs 2
| digitToInt a * digitToInt b == digitToInt c && a /= '0' = recurse [a, b, c] xs 3
math (a:b:c:d:xs)
| digitToInt a + digitToInt b == read ([c, d]) && a /= '0' && c /= '0' = recurse [a, b, c, d] xs 3
| digitToInt a * digitToInt b == read ([c, d]) && a /= '0' && c /= '0' = recurse [a, b, c, d] xs 5
math _ = badResult
relation :: String -> (Int, Partition)
relation (a:b:c:d:xs)
| [a, b, c, d] `elem` ["1714", "1727", "1760", "1820", "1830", "1837"] = recurse [a, b, c, d] xs 4
| [a, b, c, d] `elem` ["1901", "1910", "1936", "1952", "1972"] = recurse [a, b, c, d] xs 2
| [a, b, c, d] == "2022" = recurse [a, b, c, d] xs 1
| [a, b, c, d] `elem` ["3215", "3507", "3573", "3705", "5507", "5508", "5537", "7105", "7108", "7718", "7735", "7738"] = recurse [a, b, c, d] xs 3
relation (x:xs) = recurse [x] xs 2 -- Residual option
```
We pass around `(Int, Partition)`s where the `Int` is the cost and `Partition` is the answer. As we go, we take a `min` of these. `min` on tuples compares the first element first, so we always take a minimum cost element using the default Haskell comparison.
In terms of branching, we only have to check `math` (`m` in the golfed version) and `relation` (resp. `y`). `relation` checks the year condition and the symbol condition, which are mutually exclusive and hence safe to check together. `math` checks the four mathematical conditions in order: 3-digit sum, 3-digit product, 4-digit sum, 4-digit product. This order will always produce an optimal mathematical result.
Proof: If 3-digit sum succeeds, then 3-digit product just costs more and is not optimal. 4-digit sum cannot succeed since two numbers cannot add up to two different results simultaneously, and 4-digit product is not optimal because it's worse than just taking the 3-digit sum and treating the fourth digit as residual (`2 + 2` vs. `5`). If 3-digit product succeeds, then 4-digit sum must fail (sums are not larger than products), and 4-digit product must fail since the product can't be two different numbers. Finally, if 4-digit sum succeeds, it's better than 4-digit product by cost alone. โร รฉ
So implement our main function `optimalMemorization` (resp. `f`) recursively. If the string is empty, cost is zero. Else, try `math` and `relation` and take the minimum cost between the two (if the cost is the same, we choose the string that would appear first in the dictionary, which is a harmless tiebreaker).
`recurse` (resp. `r`) is a helper function, since we always combine our results in the same way, so it's better to give this helper a name. `i` in the golfed version is just `Data.Char.digitToInt`, but it's shorter to write it ourselves rather than importing.
Our `badResult` is just the "failure" case (since the math rules might not even apply at all) and produces a memorization string with the worst possible cost. Unfortunately, in the golfed version, we need a `::Int` here. It didn't have to be here, but we had to put a type annotation somewhere, because without specifying that our math is being done with integers, all Haskell can tell is that our math is being done with some `(Num a, Bounded a, Ord a) => a` type, and it's ambiguous which one.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 111 bytes
```
โรรบโยฑJโร โรซโร
โรยจยฌยตlฦรฃ~vยทยชรงยทโซรฌโฆรฌโโโรรบยฌยฉ3โรรบยฌรธยทโซฯโรรด,โรรบยฌยฐยฌโขโรกโยถยฌฮฉXยทฯรถยทยชรฅยฌยขโรรบ?โรรบยฌยถยทโรงโรรดยทโร;@โโ /โรยจโรFfยทโรฅ:ยปโ2ยฌยด21ยทยชรฃโร
ฮฉโร
ยตยปโขDยฌยง
3โรฌยทฯรฑS,PโรคDโร
ยบโรยจโฆรณ/โรณ2,3โรณLH_.โโคฦรค;โรกoยปโยทฯรยฌยตLยทโยง$aL$ยทโยข>2โโค?โรยจS
โรญยทฯรฑโรกโรปยทโยข
```
[Try it online!](https://tio.run/##RVFda9RAFH3PrxiWPo42M5PsTFxofSgisg9CQZRSxAd9kAXfBF9ktwqRbfugCy6KCvYLRH2wuGzStQqZNmx/xuSPxHOTbgOZj3vuOffeM3n6uNd7UZZF/5P9dSd/k7/NB8XWj2zSO9t@@dzNdt3J6GJkp8hn3xTt/9xJWvQ/cLp/zQ7z2B5lp/dd@tHNdrI9oKuUOXLJLlguedW5mf9cRkn7@tYTl@zcmE9l9l0KN9suBqfFYDI/XMsOPHU@cun7dX43H64Vgz/gX4yX7VhyZcfd2w@v58dnw46Nn82nLt3KJl2XHCw96i65ZG9F5ser4K975@9Qwsb2C9CygynYtRVW9D937tnYpX/zoUdN9psEeDb23Oy3jVHgQVm2Wi0RaUnpDbpsMo@O6ArgLLrEfHlJA8SZ5owQ5CIpjNJSVEkKOKOQVFLVCqkQBYERdYWAM7oTZhYcukFIKkOFg7bwF@1M3QsqgKRSUGk/DH3t61qtKjUwzvD5mM/XYIZBVUtJEVY8ilFMYgLCqJsWgYh80dgDwBlBjcPIiCgSpp6s9gkI7xCR22bCyjOctJVsB0KahQFgFa1NbbEFVYSJTf1K4WJdCVRYU5oTTOyhb7QWWKouTq5hGTAsa1Htymzit/4H "Jelly โรรฌ Try It Online")
A monadic link that takes either an integer or a list of decimal digits and returns a list of lists of digits with the optimal score. If the output needs to be a list of integers, this can be done at the cost of one byte (`ยทโรฅ`) at the end of the main link.
## Explanation
```
โรรบโยฑJโร โรซโร
โรยจยฌยตlฦรฃ~vยทยชรงยทโซรฌโฆรฌโโโรรบยฌยฉ3โรรบยฌรธยทโซฯโรรด,โรรบยฌยฐยฌโขโรกโยถยฌฮฉXยทฯรถยทยชรฅยฌยขโรรบ?โรรบยฌยถยทโรงโรรดยทโร;@โโ /โรยจโรFfยทโรฅ:ยปโ2ยฌยด21ยทยชรฃโร
ฮฉโร
ยตยปโขDยฌยง # โรรฉโร
ยฐHelper link 1: takes a list of digits and returns a score based on the two types of fixed four-digit integers, or zero if no match
โรรบโยฑJโร โรซโร
โรยจยฌยตlฦรฃ~vยทยชรงยทโซรฌโฆรฌโโโรรบยฌยฉ3โรรบยฌรธยทโซฯโรรด,โรรบยฌยฐยฌโขโรกโยถยฌฮฉXยทฯรถยทยชรฅยฌยขโรรบ?โรรบยฌยถยทโรงโรรด # โรรฉโร
ยขCompressed integer list of lists: [[105435108560611884151247538639414029, 1802, 3215], [15599387739683358002, 64, 1714]]
โรยจ # โรรฉโร
ยฃFor each list:
โโ / # โรรฉโร
ยง- Reduce by doing the following alternately
ยทโร # โรรฉโร
ยขโร
ยฐ - Convert to bijective base
;@ # โรรฉโร
ยขโร
ยข - Concatenate, in reverse order
โร # โรรฉโร
ยขโร
ยฃCumulative sum
F # โรรฉโร
ยขโร
ยงFlatten
fยทโรฅ # โรรฉโร
ยฃโร
ยฐKeep only those that match the helper linkโรรดs argument (after itโรรดs been converted to an integer from decimal digits)
:ยปโ2 # โรรฉโร
ยฃโร
ยขInteger divide by 100
ยฌยด21 # โรรฉโร
ยฃโร
ยฃMin of this and 21
ยทยชรฃโร
ฮฉโร
ยตยปโขDยฌยง # โรรฉโร
ยฃโร
ยงIndex into 3,4,4,2,1 (โร
ฮฉโร
ยตยปโข encoded 34421 which is then split into decimal digits)
3โรฌยทฯรฑS,PโรคDโร
ยบโรยจโฆรณ/โรณ2,3โรณLH_.โโคฦรค;โรกoยปโยทฯรยฌยตLยทโยง$aL$ยทโยข>2โโค?โรยจS # โรรฉโร
ยงโร
ยฐHelper link 2: takes a list of lists of digits and works out the score for each sublist before summing them
โรยจ # โรรฉโร
ยงโร
ยขFor each list:
โโค? # โรรฉโร
ยงโร
ยฃ- If the following is true:
aL$ # โรรฉโร
ยงโร
ยง - And list with its length (handles voiding lists that start with zero)
ยทโยข # โรรฉโร
ยขโร
ยฐโร
ยฐ - Head
>2 # โรรฉโร
ยขโร
ยฐโร
ยข - Is greater than 2
ยฌยต # โรรฉโร
ยขโร
ยฐโร
ยฃ- Then:
3โรฌยทฯรฑ # โรรฉโร
ยขโร
ยฐโร
ยง - Split before third list member
โฆรณ/ # โรรฉโร
ยขโร
ยขโร
ยฐ - Reduce this list using the following:
S,Pโรค # โรรฉโร
ยขโร
ยขโร
ยข - Sum paired with product
D # โรรฉโร
ยขโร
ยขโร
ยฃ - Convert to decimal digits
โร
ยบโรยจ # โรรฉโร
ยขโร
ยขโร
ยง - Check whether each equal to second half of list
โรณ2,3 # โรรฉโร
ยขโร
ยฃโร
ยฐ - Multiply by 2 (for addition) and 3 (for multiplication)
โรณ โโค # โรรฉโร
ยขโร
ยฃโร
ยข - Multiply by the following
LH # โรรฉโร
ยขโร
ยฃโร
ยฃ - Half the length of the list
_. # โรรฉโร
ยขโร
ยฃโร
ยง - Minus 0.5
ฦรค # โรรฉโร
ยขโร
ยงโร
ยฐ - Ceiling
;โรก # โรรฉโร
ยขโร
ยงโร
ยข - Concatenate to result of running helper link 1 on the original list
oยปโ # โรรฉโร
ยขโร
ยงโร
ยฃ - Or with 1000 (replaced zeros with 1000)
ยทฯร # โรรฉโร
ยขโร
ยงโร
ยง - Minimum
Lยทโยง$ # โรรฉโร
ยฃโร
ยฐโร
ยฐ- Else: double the length of the list
S # โรรฉโร
ยฃโร
ยฐโร
ยขSum
โรญยทฯรฑโรกโรปยทโยข # โรรฉโร
ยฃโร
ยฐโร
ยฃMain link: takes an integer or a list of decimal digits and returns a list of lists of digits with the lowest score
โรญยทฯรฑ # โรรฉโร
ยฃโร
ยฐโร
ยงPartitions of list
โรกโรป # โรรฉโร
ยฃโร
ยขโร
ยฐSort by results of helper list 2 on each partition
ยทโยข # โรรฉโร
ยฃโร
ยขโร
ยขHead
๏ฃฟรผรญรฉ
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 315 bytes
```
g=([a,b,c,d,...x],v=W=0,L='')=>a?g(x,v+((0x148b65742d80bb478d07e4dd77f38b367e2a48dcc61f5efd8a935817bd574741de37e99f5b1b08aan+a).match(/..../g).includes(P=a+b+c+d)?a<2?b<9?2:4:a<3||3:[a- -b]==c+d?3:[a*b]==c+d?5:9),L+P+' ')+g([d,...x],v+(c-a-b?c-a*b?9:3:2,L+a+b+c+' '))&&g([b,c,d,...x],v+2,L+a+' '):v<W|!W?(W=v,R=L):R
```
[Try it online!](https://tio.run/##dZDLboMwEEX3/Yp0E@zYELAhfgjXP5BFlA0LlIVf0FQpVE2Kssi/U1DUSpXSzUj3zpm5mnkzgzm7z@PHJe56H8ZGja0CtcEWO@xxkiTXAx5UpVK8VVEE1YvRLbjiAQGQXrOc203BcuJ5am3OuE9ZyL1nrKHc0g0LxOTcO7fJmiI0nhtBC54x66chlmc@UBaEaAqb2ZQb0yEDk3dzca9gPUUn6xYmx86dvnw4g50yyCKHPNSmJNqWQhOZS1PS243K2sSL2B6UmgA9y9WPKKSAeIt2KFpEELWg/j0LAReb2OqprqwWkkoygfeUGYbL5YT/@QS6E3NXDmV1e640qNSA92oL5X50fXfuTyE59S1oQJQJRqY1Tw9s8Y@fkocThM7u@A0 "JavaScript (Node.js) โรรฌ Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 268 bytes
Old answer, doesn't output solution and faultfully
```
f=([c,...x],s='')=>c?Math.min(f(x,s+=c),f(x)+('171417271760182018301837190119101936195219722022321535073573370555075508553771057108771877357738'.match(/..../g).includes([A,B,C,D,E]=s)?s<1900?4:s<3e3?3-A:3:B?!+A|E?1/0:A- -B==C+[D]?D?3:2:A*B==C+[D]?D?5:3:1/0:2)):s?1/0:0
```
[Try it online!](https://tio.run/##dY/NTsMwEITvPAWcEhPH8XrrOrFqrPTnyBNUPURu@oPaBOGAeuDdw4YTh3L4pNHsrHbnrflqYvg4vw951@/bcTy4dBu4EOK249ElCXMvwb82w0lcz116SG88Zi4wToplaQIGZmCUATOXUCoCJwxUEqACCRXOodIKKqOUVAoVaNTSoDaIRmpNmii1RmNAaqIkQVDCYJmIazOEU1rQR6I4MnHuwuVz38Z0W/MlX/E13@xcZD4u6KT0MxsX2KLHvLZol/4pq783Hgpp6/wxXzq3yrbrnV97tMrWz38MTfkppxiz8XdDjqHvYn9pxaU/UvVkKpEw9nDHrv7xqfK9icLJHX8A "JavaScript (Node.js) โรรฌ Try It Online")
f(string left, to encode)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 156 bytes
```
โรขรฎโรผยถโรผยถโร
โรยบโฅโรผรโรผรลโรยบยถลโยฌยดโรขรฎโรครผลฯลโยฌรธลโรยบยถโรครปรยบรโร
โซรยบโขโโขโขโรรน)ยฌโโรขรฏโร
โโร ยฎโรรU:.โร4โรณรลโ -โรครดโร
ยตzโรโซโรรบDลฮฉqโยจยงโรณรโรขยถrรยบโฅ=โรขยถ:nรยบโโรรญNรยบโขEโรครฏลโTลยฃโรบรaรยบยฎโรผโคโรรบโรโยฌรธ!โรยฅpโรรฒYโรรนโร
ยตโโขโขลโซโร
ยฅรยบโขโร รโรโซลโ1โรผยถลยฃโรยถลโยฌโคลโ โรยถลโยฌโคโรผรโรผยถโร
โซโรยถลโยฌโคลโซโรณโรครฏลยชรยบยจลโซโรผรโรผยถโรยถลโยฌฯ2โรผรรยบยถยฌยจโรฅรฏลโยฌรลโซโร
โโรครปลโโร
โซรยบโขลฯโรฉรกลฮฉลยบโร
โซลยฃโรครผลโซลยบโรผยถโรยถลโรยบยจยฌรลโซโร
โโรบรลโรยบยจยฌรลโซโร
โโรผรโรครปลรลฯยฌยชโรบรโรฅรคลรยฌฯ
```
[Try it online!](https://tio.run/##dVJNi9swED1vfoXwaQQu6CNeZdlTWGgJdFtDegs5GEcbi9iyI8ulS@lvd5@S7KG71KCHNW8@3oymbqpQ91U7z@txdEdPu53I2cYPU9zG4PyR@H6fszN/XLz0gdGZs9@Lu5tv2Q/keM4asHfuhVHD2cWrnMbm@2BDFftAZTuN9FwNtB1aFymTRi6X0igDuBdLuVIJ9AVgexBSyQcpAPoeUCiAUUoJ/GglC60LYQA42ohCF@kKWAG00UbCBkAykzKCS7DSWc4KiL2qOOVsyXFLutb@QF@CraIN1OQskxmI3Xbq6Om1bu1TgzZhV8m/DP1hquMHZp9CLp2@Y3J2wvnhOjvSxtfBdtZHe6AW1q/WH2NDpxSe4v8JlbBkKgNznem3PtJnB6ng1nHjD/ZX6kJwfCwNnM6Q9zZrh5o2@Cq8ks9Zd2NST@nRTqlcxz8WvSl6lx9Da11t/@8AkdgA2472qmTKmYPlz6LECkW6Rj877zoImHhqjj/Oc9qEQsj05MD0wPOnn@1f "Charcoal โรรฌ Try It Online") Link is to verbose version of code. Gives alternative results for two of the inputs. Explanation:
```
โรขรฎโรผยถโรผยถโร
โรยบโฅโรผรโรผรลโรยบยถลโยฌยด
```
Perform a breadth first search over partitions starting with no partitions yet and a score of zero.
```
โรขรฎโรครผลฯลโ
```
Get the next unpartitioned suffix.
```
ยฌรธลโ
```
If it wasn't empty:
```
รยบยถโรครปรยบรโร
โซรยบโขโโขโขโรรน...โรรนโร
ยตโโขโขลโซโร
ยฅรยบโขโร รโรโซลโ1โรผยถลยฃโรยถลโยฌโคลโ โรยถลโยฌโคโรผรโรผยถโร
โซโรยถลโยฌโคลโซโรณโรครฏลยชรยบยจลโซโรผรโรผยถโรยถลโยฌฯ2โรผร
```
Loop over three lists: a) A list of years and symbols, with their scores b) If the suffix does not begin with `0`, then a list of additions and products, with their scores c) A list of the first digit with a score of `2`.
```
รยบยถยฌยจโรฅรฏลโยฌรลโซโร
โ
```
If the suffix starts with this potential partition, then...
```
โรครปลโโร
โซรยบโขลฯโรฉรกลฮฉลยบโร
โซลยฃโรครผลโซลยบโรผยถโรยถลโรยบยจยฌรลโซโร
โโรบรลโรยบยจยฌรลโซโร
โโรผร
```
Push the updated partition and score to the search list.
```
โรครปลรลฯ
```
But if it was empty, then collect the completed partition in the predefined empty list.
```
ยฌยชโรบรโรฅรคลรยฌฯ
```
Output the partition with the lowest score, tied by shortest length of the first different substring.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-nl`, 380 bytes
Probably the wrong approach to use. Creates a recursive function that checks the input against a gigantic regex sequence, cutting off valid pieces and comparing the scores to find the smallest one. Then, feed input from STDIN into that function and print the result.
```
r=(r=*1..9).product([0]+r)
f=->i,*k{i=~/(2022)|19(01|10|36|52|72)|18(20|30|37)|(3215|3507|3573|3705|550[78]|5537|710[58]|7718|773[58])|17(14|27|60)|(#{r.map{|a,b|[a,b,a+b]*''}*?|})|(#{r.map{|a,b|[a,b,a*b]*''}*?|})|(.)/
k=*$&;l=$&.size/4
s=$6?2+l:$7?3+2*l:[p,$1,$2||$8,$4,$3||$5].index{_1}
(n,v=f[$'];k+=n;s+=v)if$'[0]
i[1]&&(n,v=f[i[1..]];s>v+2&&[[i[0]]+n,v+2])||[k,s]}
p f[$_][0]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVJLbtswEEW71CmEVLD1oWV-RJGKoWTVUwhEYDcxYNh1DTsO2pruRbrpIkVXvVBO0zeiHaNFAWnIeTNvyHnD78_b_ezLr-5qtF5dud-7_Swdx2U-ZsNh9nP_OB_Zlzd-26bbNhdl2WTlZvvpfv_hMe24K7ZZNG9HNwuWLw-L9ts4lVzKzIsm5cIL7lXttfSGIIuYV_hM5lMlhfZKcwNjFDCuvda8M9ZhVcYbwTsNxxhhYRQ5KGJSUXlpfM1R5N1hW36cbg5-yma-g2HTYuby4fCY3_rj_xPyvxLKbBwt2zwZTFZtMih3i68P4yratUl9K4vVdWJuVSHz1XW3YYlgifQ-sSypWKKw065crO8fPh_uxDFK1-ypnXfJ0E2WRbue7Ir2KVvMkyFUihadcIPBKQVOWTo32d08FXIw6ABw5woEC4kWfbdkO3eMNjGq3TnEwhB-nJaXt-9FY2Q8uok72rg4oqV5BVjcnDCMIqCAWGxYTAhijRRWGSn6IDksJpdYUgWGVPCqyopQoWIx7Qmz5xzagUgsS4WrWvDzcTacBRZAYimwMGMMnJvAVj0bGIvxcdyPG2Tqqq9F76PPIx_FJG5AGJ1mRCUaLi7tAWAxQa8dEqS5IAz2n8xwnDhTTvuLOo0VTSNs6CpoBAgaNqTUpbteL6hQK1lXQtpz88D6tJquDFOF6uAFhfX5fyUoHVIuKzJhNbf0_vH8Q3FSDPcHDLmM6K2iqgbaKNXg69UxdZgEwaCo5mROSiHs4vCc_gA)
] |
[Question]
[
# Input
A binary string \$s\$ of length \$n\$ and a positive integer \$k \leq n\$.
# Output
The number of binary strings with [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) exactly \$k\$ from the string \$s\$.
# Example outputs
Each example gives the largest possible output for the given \$(n, k)\$ pair.
```
k=1, s=1010, output=14
k=2, s=1010, outupt=55
k=3, s=1101, output=112
k=4, s=1001, output=229
k=1, s=1010101010, output=32
k=2, s=1010110101, output=362
k=3, s=1010110101, output=2016
k=4, s=1011001101, output=6538
k=5, s=1011001101, output=16223
k=6, s=1001100110, output=37620
k=7, s=1001100110, output=85028
k=8, s=1001100110, output=187667
k=9, s=1001100110, output=406183
k=10, s=1001100110, output=864793
k=1, s=101010101010, output=38
k=2, s=101010010101, output=533
k=3, s=101010010101, output=3804
k=4, s=101001100101, output=15708
k=5, s=101100110010, output=45717
```
# Score
The score will be the highest \$n, k\$ pair your code outputs the correct answer for on my Ubuntu desktop in one minute. The order should be (1,1), (2,1), (2,2), (3,1),(3,2), (3,3), (4,1), (4,2), (4,3), (4,4), (5,1) etc. The time is the total running time and not just for the last pair.
Your code should work for all strings but I will time it using random binary strings.
As always, this is a competition *per* language so Python coders don't need to worry about C competitors.
# Leaderboard
* **(28, 23)** in Rust by **Anders Kaseorg**
* **(12, 11)** in Rust by **corvus\_192**.
* **(12, 10)** in Pypy by **Jonathan Allen**.
* **(11, 10)** in Pypy by **Value Ink**.
* **(11, 9)** in Python by **Value Ink**.
* **(11, 9)** in Python by **Jonathan Allen**.
* **(7,6)** in Charcoal **by Neil**.
# Edit
I noticed this [related question](https://mathoverflow.net/questions/238580/neighbourhood-of-a-word-and-levenshtein-distance) which has a link that suggests there is a fast algorithm
[Answer]
# Rust, score โ (28, 23)
The number of strings at distance \$k\$ from \$s\$ with some given prefix \$p\$ is a function of \$s\$, \$k\$, and the last column of the [WagnerโFischer table](https://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm) of \$s\$ and \$p\$. We use a recursive search on prefixes \$p\$, caching results based on this last column.
Build with `cargo build --release`, run with `target/release/levenshtein-neighborhood <s> <k>`.
**`Cargo.toml`**
```
[package]
name = "levenshtein-neighborhood"
version = "0.1.0"
edition = "2021"
[dependencies]
hashbrown = "0.14.0"
rustc-hash = "1.1.0"
typed-arena = "2.0.2"
```
**`src/main.rs`**
```
use hashbrown::hash_map::HashMap;
use rustc_hash::FxHasher;
use std::env;
use std::hash::{BuildHasher, BuildHasherDefault};
use typed_arena::Arena;
type Count = u64; // For n + k > 64, change this to u128
type Cache<'a> = HashMap<&'a [u8], Count, BuildHasherDefault<FxHasher>>;
fn count_state<'a>(
target: &[bool],
distance: u8,
arena: &'a Arena<u8>,
cache: &mut Cache<'a>,
state: &mut [u8],
) -> Count {
let hash = cache.hasher().hash_one(&state);
if let Some((_, &count)) = cache.raw_entry().from_key_hashed_nocheck(hash, state) {
count
} else {
let new_state = state;
let state = arena.alloc_extend(new_state.iter().copied());
let mut count = Count::from(state[target.len()] == distance);
for symbol in [false, true] {
let mut z = state[0].min(distance) + 1;
new_state[0] = z;
for (((o, &c), &x), &y) in new_state[1..]
.iter_mut()
.zip(target)
.zip(&state[..state.len() - 1])
.zip(&state[1..])
{
z = (x + u8::from(symbol != c)).min(y.min(z).min(distance) + 1);
*o = z;
}
count += count_state(target, distance, arena, cache, new_state);
}
cache
.raw_entry_mut()
.from_hash(hash, |_| false)
.insert(state, count);
count
}
}
fn count(target: &[bool], distance: u8) -> Count {
let arena = Arena::new();
let state = arena.alloc_extend((0..=target.len()).map(|i| (i as u8).min(distance + 1)));
let mut cache = Cache::default();
cache.insert(
&arena.alloc_extend((0..=target.len()).map(|_| distance + 1))[..],
0,
);
count_state(target, distance, &arena, &mut cache, state)
}
fn main() {
if let [_program, target, distance] = &Vec::from_iter(env::args())[..] {
let target = Vec::from_iter(target.chars().map(|c| c == '1'));
let distance = distance.parse().unwrap();
println!("{}", count(&target, distance));
} else {
panic!("usage: levenshtein-neighborhood <s> <k>");
}
}
```
[Answer]
# [Python](https://www.python.org), (11, 8); with Python PyPy (12, 10)
New version of [Value Ink's answer](https://codegolf.stackexchange.com/a/265287/53748) using bit twiddling in place of string manipulation.
```
from collections import deque
def countFixedDistance(s: str, k: int) -> int:
n = int('1' + s, 2)
distances: dict[int, int] = {n: 0}
queue = deque(((n, len(s)),))
valid: set[int] = set()
while len(queue) > 0:
current, bit_count = queue.popleft()
next_dist = distances[current] + 1
next_bit_count = bit_count - 1
for next_gen in (
((current >> e + 1 << e) + current % (1 << e) for e in range(bit_count)),
(current ^ (1 << e) for e in range(bit_count)),
(((current >> e << 1 | b) << e) + current % (1 << e) for b in (0, 1) for e in range(bit_count + 1)),
):
for next in next_gen:
if next in distances: continue
distances[next] = next_dist
if next_dist < k:
queue.append((next, next_bit_count))
else:
valid.add(next)
next_bit_count += 1
return len(valid)
```
**[Attempt This Online!](https://ato.pxeger.com/run?1=nVRBbtswEDz05lfsJRAJy4ZU9BAItk9FX9Cb4Qa2tIoJK5RCUm6Kti_pJZfmI31F-5rukpIsGy4KhBdJ3J3ZWXJWP16aL25f6-fnn60rZ7d_3vwqTf0AeV1VmDtVawvqoamNgwIfW5xMCiwp2mr3QT1h8V5Zt9U5CpuBdSaGQwZKOwmzFT-zCdDSsOQPEaURTMHG8Fb6_aIDE7ZQuVtTTsyJG8r_qjNIvvs0KtsibXkBQggdQ4VaWCljGYiO20oVJAA9B8PpVYTY572q0AM8j4QVJEEWr7w1BrnsTrk73xaBfeK8qZsKy57G94FP7o5Fs5he-7qj2FBr6XnqmPP0PhullbUJqfeoqXMQQ4SXEB03rFaAzA-LBVAL01433IDoN5kLmcRs9T2KoSAd0zlrj_30CuyFJEKn8A128n_Cdr67JIb038W4wXFBmY1q9yfFuP7EsjNtAKocUkbWymvtlCbrniefLpAx7Jnheq_ThptfkMMv4oNH59umQV2QQyk9vvCAlBcwrCxeo_Jmnm-LwtOMURemmi47Jxl0rdHe4x4swyz_frHUVZREkyM9k0mYhI-m7crykR5O95D2YzVNRyffGJ5cESLxQcZXh98Hyqq1-yXzB9GWFUZpmiTR-njzbhNG9SQ7UNtObf8H-gs)**
---
With a lot of tweaks to do fewer operations, it does get further but still not to completion of (11, 9) on ATO, so it may also be worth benchmarking too:
```
from collections import deque
def countFixedDistance(s: str, k: int) -> int:
n = int('1' + s, 2)
distances: dict[int, int] = {n: 0}
queue = deque(((n, len(s)),))
valid: set[int] = set()
while len(queue) > 0:
current, bit_count = queue.popleft()
next_dist = distances[current] + 1
for e in range(bit_count):
left = current >> e
left_1 = left << 1
pow = 1 << e
right = current % pow
bp1 = bit_count + 1
for next, next_bit_count in (
((left >> 1 << e) | right, bit_count - 1),
(current ^ pow, bit_count),
((left_1 << e) | right, bp1),
(((left_1 | 1) << e) | right, bp1),
):
if next in distances: continue
distances[next] = next_dist
if next_dist < k:
queue.append((next, next_bit_count))
else:
valid.add(next)
for next in (
pow << 2 | current,
3 << bit_count ^ current,
):
if next in distances: continue
distances[next] = next_dist
if next_dist < k:
queue.append((next, bit_count + 1))
else:
valid.add(next)
return len(valid)
```
**[Attempt This Online!](https://ato.pxeger.com/run?1=nVRBbtswEDz05lfsJRAJy4ZU9BAItk9FX9Cb4Qa2tIoJK5RCUm6Kti_pJZfmI31F-5rukpIsGy4KhBdJ3J3ZWXJWP16aL25f6-fnn60rZ7d_3vwqTf0AeV1VmDtVawvqoamNgwIfW5xMCiwp2mr3QT1h8V5Zt9U5CpuBdSaGQwZKOwmzFT-zCdDSsOQPEaURTMHG8Fb6_aIDE7ZQuVtTTsyJG8r_qjNIvvs0KtsibXkBQggdQ4VaWCljGYiO20oVJAA9B8PpVYTY572q0AM8j4QVJEEWr7w1BrnsTrk73xaBfeK8qZsKy57G94FP7o5Fs5he-7qj2FBr6XnqmPP0PhullbUJqfeoqXMQQ4SXEB03rFaAzA-LBVAL01433IDoN5kLmcRs9T2KoSAd0zlrj_30CuyFJEKn8A128n_Cdr67JIb038W4wXFBmY1q9yfFuP7EsjNtAKocUkbWymvtlCbrniefLpAx7Jnheq_ThptfkMMv4oNH59umQV2QQyk9vvCAlBcwrCxeo_Jmnm-LwtOMURemmi47Jxl0rdHe4x4swyz_frHUVZREkyM9k0mYhI-m7crykR5O95D2YzVNRyffGJ5cESLxQcZXh98Hyqq1-yXzB9GWFUZpmiTR-njzbhNG9SQ7UNtObf8H-gs)**
[Answer]
# Rust, (12, 11)
This is basically a line-by-line port of Jonathan Allan's answer, with is already very good. Thanks! I wrote this to practice some Rust.
It uses the [nohash-hasher](https://crates.io/crates/nohash-hasher) crate for extremely fast HashMap lookups, with take up the vast majority of the time.
[Try it online on rustexplorer.com](https://www.rustexplorer.com/b#LyoKW2RlcGVuZGVuY2llc10Kbm9oYXNoLWhhc2hlciA9ICIwLjIuMCIKKi8KCiMhW3dhcm4oY2xpcHB5OjphbGwpXQoKdXNlIHN0ZDo6Y29sbGVjdGlvbnM6Omhhc2hfbWFwOjpFbnRyeTsKdXNlIHN0ZDo6Y29sbGVjdGlvbnM6OlZlY0RlcXVlOwp1c2Ugc3RkOjp0aW1lOjpJbnN0YW50OwoKdXNlIG5vaGFzaF9oYXNoZXI6OntJbnRNYXAsIEludFNldH07CgpmbiBjb3VudF9maXhlZF9kaXN0YW5jZShzOiAmc3RyLCBrOiB1MzIpIC0+IHVzaXplIHsKICAgIGxldCBuID0gaTMyOjpmcm9tX3N0cl9yYWRpeCgmZm9ybWF0ISgiMXtzfSIpLCAyKS51bndyYXAoKTsKICAgIGxldCBtdXQgZGlzdGFuY2VzID0KICAgICAgICBJbnRNYXA6OndpdGhfY2FwYWNpdHlfYW5kX2hhc2hlcigxIDw8IChzLmxlbigpICsgayBhcyB1c2l6ZSksIERlZmF1bHQ6OmRlZmF1bHQoKSk7CiAgICBkaXN0YW5jZXMuaW5zZXJ0KG4sIDApOwogICAgbGV0IG11dCBxdWV1ZSA9IFZlY0RlcXVlOjpmcm9tKFsobiwgcy5sZW4oKSldKTsKICAgIC8vIGNhcGFjaXR5IGlzIGp1c3QgZXhwZXJpbWVudGF0aW9uCiAgICBsZXQgbXV0IHZhbGlkID0gSW50U2V0Ojp3aXRoX2NhcGFjaXR5X2FuZF9oYXNoZXIoMSA8PCAoayArIDEpLCBEZWZhdWx0OjpkZWZhdWx0KCkpOwogICAgd2hpbGUgbGV0IFNvbWUoKGN1cnJlbnQsIGJpdF9jb3VudCkpID0gcXVldWUucG9wX2Zyb250KCkgewogICAgICAgIGxldCBuZXh0X2Rpc3QgPSBkaXN0YW5jZXMuZ2V0KCZjdXJyZW50KS51bndyYXAoKSArIDE7CiAgICAgICAgbGV0IG11dCBwb3cgPSAwOwogICAgICAgIGZvciBlIGluIDAuLmJpdF9jb3VudCB7CiAgICAgICAgICAgIGxldCBsZWZ0ID0gY3VycmVudCA+PiBlOwogICAgICAgICAgICBsZXQgbGVmdF8xID0gbGVmdCA8PCAxOwogICAgICAgICAgICBwb3cgPSAxIDw8IGU7CiAgICAgICAgICAgIGxldCByaWdodCA9IGN1cnJlbnQgJSBwb3c7CiAgICAgICAgICAgIGxldCBicDEgPSBiaXRfY291bnQgKyAxOwogICAgICAgICAgICBmb3IgKG5leHQsIG5leHRfYml0X2NvdW50KSBpbiBbCiAgICAgICAgICAgICAgICAoKGxlZnQgPj4gMSA8PCBlKSB8IHJpZ2h0LCBiaXRfY291bnQgLSAxKSwKICAgICAgICAgICAgICAgIChjdXJyZW50IF4gcG93LCBiaXRfY291bnQpLAogICAgICAgICAgICAgICAgKChsZWZ0XzEgPDwgZSkgfCByaWdodCwgYnAxKSwKICAgICAgICAgICAgICAgICgoKGxlZnRfMSB8IDEpIDw8IGUpIHwgcmlnaHQsIGJwMSksCiAgICAgICAgICAgIF0gewogICAgICAgICAgICAgICAgbWF0Y2ggZGlzdGFuY2VzLmVudHJ5KG5leHQpIHsKICAgICAgICAgICAgICAgICAgICBFbnRyeTo6VmFjYW50KHZlKSA9PiB7CiAgICAgICAgICAgICAgICAgICAgICAgIHZlLmluc2VydChuZXh0X2Rpc3QpOwogICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICBFbnRyeTo6T2NjdXBpZWQoXykgPT4gY29udGludWUsCiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICBpZiBuZXh0X2Rpc3QgPCBrIHsKICAgICAgICAgICAgICAgICAgICBxdWV1ZS5wdXNoX2JhY2soKG5leHQsIG5leHRfYml0X2NvdW50KSk7CiAgICAgICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgICAgICAgIHZhbGlkLmluc2VydChuZXh0KTsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgIH0KCiAgICAgICAgZm9yIG5leHQgaW4gW3BvdyA8PCAyIHwgY3VycmVudCwgMyA8PCBiaXRfY291bnQgXiBjdXJyZW50XSB7CiAgICAgICAgICAgIG1hdGNoIGRpc3RhbmNlcy5lbnRyeShuZXh0KSB7CiAgICAgICAgICAgICAgICBFbnRyeTo6VmFjYW50KHZlKSA9PiB7CiAgICAgICAgICAgICAgICAgICAgdmUuaW5zZXJ0KG5leHRfZGlzdCk7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICBFbnRyeTo6T2NjdXBpZWQoXykgPT4gY29udGludWUsCiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgbmV4dF9kaXN0IDwgayB7CiAgICAgICAgICAgICAgICBxdWV1ZS5wdXNoX2JhY2soKG5leHQsIGJpdF9jb3VudCArIDEpKTsKICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICAgIHZhbGlkLmluc2VydChuZXh0KTsKICAgICAgICAgICAgfQogICAgICAgIH0KICAgIH0KICAgIHZhbGlkLmxlbigpCn0KCmZuIG1haW4oKSB7CiAgICBsZXQgc3RhcnQgPSBJbnN0YW50Ojpub3coKTsKICAgIGxldCBtdXQgcyA9IFN0cmluZzo6d2l0aF9jYXBhY2l0eSgzMik7CiAgICBzLnB1c2goJzAnKTsKICAgIGxldCBtdXQgdiA9IDA7CiAgICB3aGlsZSBzLmxlbigpIDw9IDEyIHsKICAgICAgICAvLyBhcHByb3ggMiBtaW51dGVzIGZvciBwcm9maWxpbmcKICAgICAgICBmb3IgayBpbiAxLi4ocy5sZW4oKSArIDEpIHsKICAgICAgICAgICAgcHJpbnRsbiEoInt9IHt9IHt9Iiwgcy5sZW4oKSwgaywgY291bnRfZml4ZWRfZGlzdGFuY2UoJnMsIGsgYXMgdTMyKSk7CiAgICAgICAgfQogICAgICAgIHMucHVzaChbJzEnLCAnMScsICcwJywgJzAnXVt2ICUgNF0pOwogICAgICAgIHYgKz0gMTsKICAgICAgICBwcmludGxuISgie30iLCBzKQogICAgfQogICAgcHJpbnRsbiEoInt9IHNlY29uZHMiLCBzdGFydC5lbGFwc2VkKCkuYXNfc2Vjc19mMzIoKSk7Cn0K). Runs an unoptimized debug build, so don't rely on it for measurements.
I have a [github repo](https://github.com/jendrikw/levenshtein-neighbourhood) with build instructions.
```
#![warn(clippy::all)]
use std::collections::VecDeque;
use std::collections::hash_map::Entry;
use std::time::Instant;
use nohash_hasher::{IntMap, IntSet};
fn count_fixed_distance(s: &str, k: u32) -> usize {
let n = i32::from_str_radix(&format!("1{s}"), 2).unwrap();
let mut distances = IntMap::with_capacity_and_hasher(1 << (s.len() + k as usize), Default::default());
distances.insert(n, 0);
let mut queue = VecDeque::from([(n, s.len())]);
// capacity is just experimentation
let mut valid = IntSet::with_capacity_and_hasher(1 << (k + 1), Default::default());
while let Some((current, bit_count)) = queue.pop_front() {
let next_dist = distances.get(¤t).unwrap() + 1;
let mut pow = 0;
for e in 0..bit_count {
let left = current >> e;
let left_1 = left << 1;
pow = 1 << e;
let right = current % pow;
let bp1 = bit_count + 1;
for (next, next_bit_count) in [
((left >> 1 << e) | right, bit_count - 1),
(current ^ pow, bit_count),
((left_1 << e) | right, bp1),
(((left_1 | 1) << e) | right, bp1)
] {
match distances.entry(next) {
Entry::Vacant(ve) => {
ve.insert(next_dist);
}
Entry::Occupied(_) => continue,
}
if next_dist < k {
queue.push_back((next, next_bit_count));
} else {
valid.insert(next);
}
}
}
for next in [pow << 2 | current, 3 << bit_count ^ current] {
match distances.entry(next) {
Entry::Vacant(ve) => {
ve.insert(next_dist);
}
Entry::Occupied(_) => continue,
}
if next_dist < k {
queue.push_back((next, bit_count + 1));
} else {
valid.insert(next);
}
}
}
valid.len()
}
fn main() {
let start = Instant::now();
let mut s = String::with_capacity(32);
s.push('0');
let mut v = 0;
while s.len() <= 12 { // approx 2 minutes for profiling
for k in 1..(s.len() + 1) {
println!("{} {} {}", s.len(), k, count_fixed_distance(&s, k as u32));
}
s.push(['1', '1', '0', '0'][v % 4]);
v += 1;
println!("{}", s)
}
println!("{} seconds", start.elapsed().as_secs_f32());
}
```
[Answer]
# [Python](https://www.python.org), ~(11,6)
Direct adaptation of my answer on [Pick a random string at a fixed edit distance](https://codegolf.stackexchange.com/a/264954/52194) with a minor optimization of generating the sets inline instead of each one being a function call. ATO seems to flip-flop between (11,6) and (11,7) for me right now.
```
from collections import deque
def countFixedDistance(s: str, k: int) -> int:
if k <= 0: return s
chars: set[str] = set('01')
distances: dict[str,int] = {s: 0}
queue = deque((s,))
valid: set[str] = set()
while len(queue) > 0:
current = queue.popleft()
nextdist = distances[current] + 1
for nxt in {current[:i] + c + current[i:] for c in chars for i in range(len(s)+1)} \
| {current[:i] + c + current[i+1:] for c in chars for i in range(len(s)) if c != s[i]} \
| {current[:i] + current[i+1:] for i in range(len(s))}:
if nxt in distances: continue
distances[nxt] = nextdist
if nextdist < k:
queue.append(nxt)
else:
valid.add(nxt)
return len(valid)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVNLbtswEF10R6B3mKwkwrIhZVUIcVZBTtCdqoVAUTFhhVT4SR0kPkk32bS7Hqg9TWco2g6atAgBQeDMmzeP8_n2Y3rwG6Ofn78HPyw__f7wcbDmFoQZRym8MtqBup2M9dDLuyAZ6-WA3qD9tdrJ_ko532khc1eD87aAbQ1Kew7LS_rXDEANsIWLNZQ1WOmD1eAYmsWmsxQkfYOBLRzPmmx5VlYZR1ifEiC0VyJiCyRuEfaItnKPGNQVJLxx1rPoPHcFJ7L7blT9v3Ny0vV1o0YJo9R5pOVwicoZgUSwVmqP4OhZTWYa5UBh5NVy50ksJT1oblJICwuoImowFvTOY23gMTmbWpFf0Jcsqm4jUhAuFipeFV1tp29kTvocX1R8D1_YX69--i_1ononOafOCTjD2jSqfVeeVzlek-7rRIPkqRAvWiyM9krjmM2YUyERSi0_FPkFx6HsFzh6R4Vzg7ppkrrPMZYnjxydPKHiOKy6PkHQngaUtEYnn7fi10-HybMyY3E53MNxKZzvTfBsHprPNhA7PXx7enhVwLFblHuyOL95qkex5cWb64QOEj3zr4YxuA0NmoMFCqmqsswaonHN8rxuCzjnLUvMLok-rPQf)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 81 bytes
```
โฯ
ฮทโโฆฮทยนโฆฮถ๏ผฆ๏ผฎยซโฯ
ฮตโโฆโงฯ
๏ผฆฮต๏ผฆฮฃโบ๏ผฅฮบโฆโญฮบยฌโผ๏ผฉฮฝโผฮผฮพโญฮบโโผฮผฮพฯฮฝโง๏ผฅยฒ๏ผฅโ๏ผฌฮบโบโบโฮบโฐฮฝยนฮปโฮบฮฝยฟยฌยงฮถฮปยซโฯ
ฮปยงโฮถฮปยนยปยป๏ผฉ๏ผฌฯ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVG9TsMwEBZj8xSnTmfJlRLEgOhUIYZIUEUKW5UhTZ0f1XGKf6C0yspLsHQAwcQD8TTY-ZHKSfb58333-e78_p2VqcyalJ9On0bns-vfi7fIqBINhZLMvYVSVSHwWN5A0FI42Ku8kYCh2Bm9NPWaSSQEjt5kYNo8ZkkjXCUUjMNdFiPQ-djUGHGj8CHd4ZbCKtayEsWAlo3GuyeTcoW3qdIoCIUB1xT2xBqFfxmPTIpUvuI5i8ILBUFIYk-Odtm7UGSS1UxotsF7Jgpd4tbpdeV0W8yrjDlV3-ZTCGyQuwfHa0F6gyoHdLUudCg2bI8HR-yHMbR_HnFKdg6TcbrcodZrvcg2ovtOh4KMVZl_qHWmhk_5Wk1nz3ya_Fx5gR_4fuCWH_TBPw) Link is to verbose version of code. Can handle results of up to about `20000` on ATO, so `5 1011001101` or `4 101001100101`. Explanation:
```
โฯ
ฮท
```
Start with one string of distance `0`.
```
โโฆฮทยนโฆฮถ
```
Start with one string found so far.
```
๏ผฆ๏ผฎยซ
```
Loop `k` times.
```
โฯ
ฮตโโฆโงฯ
๏ผฆฮต
```
Start collecting strings of distance `i+1`.
```
๏ผฆฮฃโบ๏ผฅฮบโฆโญฮบยฌโผ๏ผฉฮฝโผฮผฮพโญฮบโโผฮผฮพฯฮฝโง๏ผฅยฒ๏ผฅโ๏ผฌฮบโบโบโฮบโฐฮฝยนฮปโฮบฮฝ
```
Loop over all strings of edit distance `1` from the current string of distance `i`.
```
ยฟยฌยงฮถฮปยซโฯ
ฮปยงโฮถฮปยนยป
```
If this string is new then mark it as seen and add it to the list of strings of edit distance `i+1`.
```
ยป๏ผฉ๏ผฌฯ
```
Output the count of strings of edit distance `k`.
] |
[Question]
[
Inspired by [this SO answer](https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/46680769#46680769) about peak detection.
## Background
Persistent homology is a fancy term for a fancy math concept, but in this case all we care about is how it can be used for peak detection. In the case of a 1-dimensional array we can describe the algorithm as follows:
We are given an array as input. We begin by sorting it, while maintaining references to the original indices for each value. We also create some kind of data structure to group points together into peaks. We then loop over each point in the sorted array. For each point we have three cases:
* If it is not adjacent to any points in existing groups, a new group is created with a "position" of the point's original index and given a "birth time" equal to that point's value.
* If it is adjacent to one point that is in a group, it is added to said group.
* If it is adjacent to two points in different groups, the younger group is given a "death time" equal to that point's value, and all its points are given to the older group.
At the end, the single group which remains is given a death time of the final value.
Now we have a list of groups, each of which have a position that corresponds to a local maximum, and a persistence which is equal to their "birth time" minus their "death time".
## The challenge
Given a 1-dimensional sequence of inputs which support comparison and subtraction, and an integer \$n \geq 1\$, your task is to output the indices of the \$n\$ most persisent peaks, sorted by their persistence.
Your program does not need to follow the algorithm exactly as I've described it, nor does it need to be as efficient. You only need to support one class of inputs for the sequence (ie. integers, floats, etc.) and any reasonable format for I/O is allowed so long as it is consistent. You may assume that \$n\$ is less than or equal to the number of local maxima.
In the case that two local maxima to be merged have the same "birth time", the behavior for which one persists is undefined, and either is considered valid for this challenge. In the case that two or more maxima have the same persistence, they may appear in any order in the output.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
## Worked example
Let's look at `[1, 2, 1, 2, 3, 2, 1]`. First we'll enumerate and sort `[0:1, 1:2, 2:1, 3:2, 4:3, 5:2, 6:1]` to
`[4:3, 1:2, 3:2, 5:2, 0:1, 2:1, 6:1]` then we iterate over this. I'll show for each iteration what the aforementioned "group" data structure might look like, in this case simply a list of point indices, birth time and death time
```
[[[4], 3, None]]
[[[4], 3, None], [[1], 2, None]]
[[[4, 3], 3, None], [[1], 2, None]]
[[[4, 3, 5], 3, None], [[1], 2, None]]
[[[4, 3, 5], 3, None], [[1, 0], 2, None]]
[[[4, 3, 5, 1, 0, 2], 3, None], [[1, 0], 2, 1]]
[[[4, 3, 5, 1, 0, 2, 6], 3, 1], [[1, 0], 2, 1]]
```
this gives us the a peak at 4 with persistence 3-1=2 and a peak at 1 with persistence 2-1=1 thus our sorted list of peaks is [4,1]
## Test cases
Outputs here are 0-indexed.
```
[1, 2, 1, 2, 3, 2, 1, 2, 3, 4, 3, 2, 1]
2
->
[9, 4]
[1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 6, 7, 6, 5, 4, 3, 4, 5, 6, 5, 4, 5, 4, 3, 2, 1]
3
->
[7, 19, 12]
[93, 92, 89, 88, 89, 88, 87, 87, 88, 88, 90, 89, 88, 87, 86, 90, 89, 89, 88, 88, 86, 82, 76, 69, 61, 52, 44, 38, 33, 30, 27, 24, 22, 21, 18, 15, 10, 6, 2, 0, 0, 2, 2, 1, 2, 5, 8, 10, 13, 16]
4
->
[0, 49, 15, 10]
```
More information about persistent homology in general can be found on [wikipedia](https://en.wikipedia.org/wiki/Persistent_homology) and this [more detailed write-up](https://www.sthu.org/blog/13-perstopology-peakdetection/index.html) by the author of the SO answer.
[Answer]
# Python3, 350 bytes:
```
S=sorted
def f(s,n):
r,R={},0
for i,v in S(enumerate(s),key=lambda x:-x[1]):
R+=1
if(K:=[r.pop(I)for I in[*r]if i+1in r[I][2]or i-1in r[I][2]]):
*a,b=S(K,key=lambda x:x[0])
if a:r[R]=[a[0][0]-v,a[0][1],[]];b[2]+=a[0][2]+[i];R+=1;r[R]=b
else:b[2]+=[i];r[R]=b
else:r[R]=[v,i,[i]]
return[r[i][1]for i in S(r,key=lambda x:-r[x][0])][:n]
```
[Try it online!](https://tio.run/##XVDLjoMwDLzzFTkmrbsi4VGg4gOq3tpjlAOoQYu2BRRoRbXab2edsA9aKY6dGXvsuHsM720TJJ2ZplPet2bQZ@@sK1LRHhqWecTAMf/8At8jVWtIDXdSN@REdXO7alMMmvYMPvQjvxTX8lyQMduMkitbSY7rnKOrK3rIcmneuraje2Zl9igiV0bVFanXHAWN3CsplO2wWbxnHbIqoMxP9PDcaJS@YpZGlSIz8qhyWSCGZ3MHF3EFUqldiVLr3CEYyFrt7Gg7V1JaBX3pdTZnWfaPcPisfIcakFO4ET3cTCMNvrCB28q8E/OyCCNHOwxTMmvU1Jm6GWhFJQcigMx38ByHf4gCwZj3UjNnREBiIFsgibvjBTLH4XNm9Bsv1YOleopwiniSoiULv/2xZLbUf@HiBZb@51k8Qb0t@hjxGMeP8B3aCZAPsF@AdQI1BGICOYE5HDmOg3LfDY6o745YbCly/7YZHFV4rCBkbPoG)
[Answer]
# JavaScript (ES10\*), 215 bytes
*\* ES10 guarantees a stable sort, but the OP has since clarified that this is not a strict requirement.*
(or [214 bytes](https://ato.pxeger.com/run?1=bVDLTsMwEBRXviJHG22i2EnTBOHyIZYPaUlKqjRO-jr1T7hUCH4JCb6GSVwgBSTba8_M7s766aWxD8XpuVSv-13pp-9vuZo1asas0oYH67xlAHItDeXDix2o4mqmEcBv7WbHlorp3JCeGxBzP3dpzElQSrfUGWXPYh6UVb0rNq6uMIDXBVtBt_JVxW9Wd5Jz6o5HpUkbQy2_73TbC9v99pEFQdDhARPU6dD46kDCwOutdTy66sr0nTns1dWiYCE13E33cdUtbLO1dRHUdslKpgV5kjx3Rpf3-BsxnMHT9b-pTjghLyFvSl46nMkIcff4Ujn5ul80if42ycBmoNMMOx3F6XmnbmfhLy4ZYdmPrsdT1JsiJsATTDHBO-6NgI_QL0KeRA0JTIKT0AhwAn5FOPgHGg5Ljv5sMozfKwSqiAQTxfz886eTi58) in ES12, but ATO doesn't seem to be working right now)
Expects `(array)(n)`.
```
a=>n=>(o=[]).map(a=>a[2],a.map((v,i)=>[v,i]).sort(g=([a],[b])=>b-a).map(([v,i])=>([p,q]=o.sort(g).filter(a=>a[1].some(j=>(j-=i)*j<2)),q=q||[,[]],p)?q[p[1].push(...q[1],i),q[0]-=v,1]=[]:o.push([v,[i],i]))).slice(0,n)
```
[Try it online!](https://tio.run/##bVBdU4MwEHz3V/CYOAdDwkfBMfWHZPIQK60wlECpfep/x4VUpeoMl9ztbu72aOzFjrtT3Z/Dzr1V015NVm07tWVOacOjo@0ZAKulIbtU7EI1V1uNC/zoTmd2UExbQ/rVgHgNrX/GvAStdE@DUe4m5tG@bs/VyfcVBvCxYg10Tahq/tg8S85pUMP1qkkbQz1/GXQ/K/uP8Z1FUTSggAsadGxCdSFhYPbJeR5jdW3m0Rz@2npXsZg6Pu1cN7q2ilp3YHumBQWSAn8m93n6jRjOYObh36demFGQU7ChoFjOfIX4PL1XZl/53ZDk75ASbAm6KBHF6t7covBRxr@4fIWVP7oZL9BvgzsHnmOLDHU6GwGfYF6CdxI9JDAJTkIjwAn4FfHiH2i8fHL1z7Jl/Vkh0EXk2CjlfPoE "JavaScript (Node.js) โ Try It Online")
### Commented
```
a => // outer function taking a[]
n => // inner function taking n
(o = []) // o[] = array of [ value, group, index ] tuples
.map(a => // once o[] is finalized ...
a[2], // ... keep only the original indices
a.map((v, i) => [ v, i ]) // we first turn a[] into an array of
// [ value, index ] pairs
.sort(g = ([a], [b]) => // and sort them ...
b - a // ... from highest to lowest value
) //
.map(([v, i]) => // for each pair [ value, index ]:
( [p, q] = o.sort(g) // sort o[] by decreasing 'birth time'
.filter(a => // and keep only the tuples ...
a[1].some(j => // ... whose groups contain a value
(j -= i) * j < 2 // adjacent to the current value
) //
), // save at most 2 tuples in [ p, q ]
q = q || [, []], // force a default dummy value for q
p // test p
) ? // if p is defined:
q[ //
p[1].push( // append to the group of p:
...q[1], // the values from the group of q
i // followed by i
), //
q[0] -= v, // subtract the 'dead time' from the
1 // 'birth time' of q
] = [] // and clear the group of q
: // else:
o.push([v, [i], i]) // create a new tuple
) // end of inner map()
) // end of outer map()
.slice(0, n) // return only the n first elements
```
[Answer]
# Python, 322 307 298 279 272 bytes
```
def P(l,n,*o):
L=len(l);*u,S=1,*[0]*L,1,sorted
for i in S(range(L),key=lambda x:-l[x]):*r,d=0,0,1;exec('k,c=i,sum(u[i-(d<0)::d])<2\nwhile~-u[k+1]:r[c]=max(r[c],l[i]-l[k]);k+=d\nd=-1;'*2);o+=((-r[0]or-r[1],i),)*(1>i%~-L*sum(u[i:i+3]));u[i+1]=1
return[*zip(*S(o))][1][:n]
```
Using different algorithm than the one in the question:
1. Sort descending
2. For each value, if it's a peak (immediate left and right have not been visited) iterate left and iterate right, record max diff until encountering a previously visited value or end of array. Give priority to encountering previously visited value. Store them.
3. Sort and return
[Try it online!](https://tio.run/##XVDLTsMwELz3K3xBeN2NFDttmgfmC3pA6tH4UBoDVlKnMo0oHPj1sm15BKSsdzI7O55k97Z/7kNW7OLx2LhHdsc7DCh6qCZsqTsXeAe1GHClJQqTWrFEiS993Ltmwh77yDzzga14XIcnx5eArXvT3Xr70KzZoUo6c7BQiYiNTjFFWbuD2/DrFjfa48uw5YPxCW9uUqiqxsKNug@vz75zH8lg2qm0VTQbq7frAz8B7Iy35NlaqNupbu5DoxNZXwsFdT/VnCeRIvaRmrToAUFweeuvPpKl@Lqs8tPMAtQEyV7LCYtuP8RgxLvfcbHiPYClbVMFe9xFH/b8jhuJTCG7nNlfPPthLCqAyb@di2KOLEe2QFacz3zEXPDsr3L@jcfu2di9JLokviipilFffFVxqTL9N8tHXPmrO/EF@S2o58TnFH9O77NTAppndF9Ge4o8FHGKZoo0kmaSgsr0HJzY9Pyo0V@an7/7pJDkInOLM4DjJw)
-9 bytes thanks to UnrelatedString
-19 bytes thanks to AnttiP and Kevin
-7 bytes thanks to AnttiP
[Answer]
# [Python](https://www.python.org), 153 bytes
```
lambda a,n:sorted(r:=range(N:=len(a)),key=lambda j:max((g:=lambda s,k:g(s,k+s)if k in r and a[k]<=a[j]else min(a[j:k%-N:s]or[0]))(1,j),g(-1,j))-a[j])[:n]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XVBdTsMwDBavPUVekJKRSk3_1kaUE0y7QIhQ0NrSv7RqC2LcBPEyCcGd4DQ47QYdUhLbnz9_tvP22e3Hh1Yf3rPk9uNxzOzo67VWzf1OIUU1H9p-THe450mvdJ7iLU_qVGNFCK3SfXJklrxRzxjn_AQMtOI5hvdqIEWGKlRo1COld0iJSl4nSpQyrYcUNQWIiZJXl_aWD7LthSMJwYyWhObYNpbYhk0E1_I4oMjaHm2M5kvR4VWwwm0HQzmEEsItMze9oy29QwnazGELbqM6nD6pmuIJIcRCXV_ocQ5pZiwhc4vD94UWjCKXovn1zn3_F5GWa9k3logBlJYllpSAopCiNUXR9IYLZPb9c2Zw8pfy3iQPJQxaMNf0iCEZQzYCJIoWdn280Xxj518uXGDxH8_gEeitwYaAh7BEALFv5oC8B_08qHNBwwXMhZwLHAY5BuMyZxofUGc67uKzgml7w2CgwkJp-dNCAPjxqRyWmv_9Bw)
Expects a sequence of positive integers (other positive numbers should work, too).
How?
I'm using the following algorithm which I think is equivalent to OP's:
For each position p find the nearest position with larger value and take the smallest value in between. Do this on the left and the right and keep the larger of the two minima minus the value at p. Sort positions by this quantity.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes
```
๏ผต๏ผญฮธโฆโปโ๏ผฅโฆโฎโฆฮธโฮบโฮธฮบโงโจโโฆฮปโ๏ผฅฮปโบฮฝฮนยนยฆโฐฮนฮบโง๏ผฆฮทโฯ
โโปฮธฯ
๏ผฉ๏ผฅฯ
โฮน
```
[Try it online!](https://tio.run/##XZBBa4QwEIXv@ytyTCAFE11X2aPQ0oNU2qN4CG4Wgxpt1KX99fYZW3Yp5GV03ptvxLpRrh5Ut665GrOh75W90E9OytzYZaK5@jL90qOOtHzXN@0mTbPvutNZM4xb8NXWTvfazvpCW8YYJx@dqfVmtazi5M1RoDzkPtdx8mywaMPi@cVpNWtHLSdmIwjPCfxtoLZi58N1cIQ2jBTL1NCFkz/q/qFYtyB/PhTO2Jlmapo9HcECC4GFua5lmYacpJKTJIWSh3r6VbIrDf558UMvvee2fgLeCTVGPxacHPEeRZyE8EPsCzEnwZDoSXgSGQFPHCF4GEU38Ef6I/wNO9kTAhQR43dG1fp0634A "Charcoal โ Try It Online") Link is to verbose version of code. Explanation: Port of @Albert.Lang's Python answer, because it's the only post here I could understand.
```
๏ผต๏ผญฮธโฆโปโ๏ผฅโฆโฎโฆฮธโฮบโฮธฮบโงโจโโฆฮปโ๏ผฅฮปโบฮฝฮนยนยฆโฐฮนฮบโง
```
For each element of the input array, get the reversed prefix and suffix, truncate each at the first element greater than the current element, then take the minimum, or zero if the list is empty, subtract the current element from the larger of the two, and pair it with the current index.
```
๏ผฆฮทโฯ
โโปฮธฯ
```
Get the persistence and index of the `n` most persistent peaks.
```
๏ผฉ๏ผฅฯ
โฮน
```
Output the indices.
[Answer]
# [Scala](http://www.scala-lang.org/), ~~516~~ 511 bytes
Port of [@Ajax1234's Python answer](https://codegolf.stackexchange.com/a/262270/110802) in Scala.
Saved many bytes thanks to the comment of [@Aiden Chow](https://codegolf.stackexchange.com/users/96039/aiden-chow)
---
Golfed version. [Try it online!](https://tio.run/##dVDLjpswFN3nK7y0hbECJAQmJVIrdRGl00W66KIaRSYxHTdgKHbRpJl8e3oNYQbajuT78LnnPvWe5/wqi6qsDdL2w/Zlnou9kaVixS/D01xMJmX6AyB0z6VC4skIddDofVWh8/UgMpRhffdF/Py2VuaBqjswJDk3PEd1cqvA7nllwxRbZaXnkwdMlg2v0TaZLrOyxrihkrxzNfstq6/SPK7VQTwxDfN9OOFGJivkNpLtPELaFpukZkdx0iyTuRE1XicrUITtAlhEGRhYY@l45Pn5X9iFIqzgVZvEalGUjbCk78IQZkoYse@7sw2XMsMbpkr1sajMqW2POU1JAqhU0tANy7k2ZLl1Es@S@YBcOwneuivAHgU/QDm3ob3v088yJ7e8npgCh6Y2CCpwnJ4MLgyGJSHkInItzm8lvLA62qg43Ji@xpe3E45WPtpL1/hI7OrtlaQ9rYS/D9fhR4EVuVwRqmqpTK5whj9JbbBHkU9Rp4OxP3tBCBhCJm8kd9Q5RSFFC4qiVocDpPNnY@a890dtgv@1iSEeAyGKQaKBXdwk6iSe/hULB1j8yrN4BPUWYEPAQ9hjDv@ZHQXiAfQLIM@HGj5gPsR84HgQ82Bib9puAOi0ff7gbvP2AJbhQRUvhJ1msNPl@gc)
```
def f(s:Seq[Int],n:Int)={val r=mutable.Map[Int,(Int,Int,Seq[Int])]();var R=0;for((v,i)<-s.zipWithIndex.sortBy(vi=> -vi._1)){val K=r.keys.filter(I=>r(I)._3.contains(i+1)||r(I)._3.contains(i-1)).map(I=>r.remove(I).get).toSeq.sortBy(_._1);if(K.nonEmpty){val(a,b)=(K.init,K.last);R+=1;if(a.nonEmpty){r+=(R->(a.head._1-v,a.head._2,Nil));R+=1;r+=(R->(b._1,b._2,b._3++a.head._3++Seq(i)))}else{r+=(R->(b._1,b._2,b._3++Seq(i)))}}else{R+=1;r+=(R->(v,i,Seq(i)))}};r.keys.toSeq.sortBy(k=> -r(k)._1).map(i=>r(i)._2).take(n)}
```
Ungolfed version. [Try it online!](https://tio.run/##bVJNj9owEL3zK@Zoi2CR8L0qK7VSD4huD/TQQ7VCBpyuu8FJExctZfnt9NkhKUGR4o@ZefP8ZibFVibyovdZmlsqnCG2aZKordWpEfs/Vm4S1emkm19w0ZPUhtSbVWZX0Mcso9Nlp2KKWfHwTf3@sTD2OTAPOPj81CE6yIRymtOVRjzJzGECYn73W5XHnxn3KTmtkNLHPU5zYuwQkOb0oUesEH919l3bl4XZqTdRQPKnI51oKwtFV9z8kXqHM@fk3i8VLEGXi1d1LLyLSMQ6sSpnC4fGwcV6gKqNRXUF09SlkNP7e1uohxCvaPYyu3KIXO3Tg3L4n8rWAJuiusoo5bK1WIclQMfElsKk5vM@s8dKcamZyYA2qMYhtNHo01IksqipV9SdU3g1HJFsISI0HzC2ot6jQ7woucPrKAK9qswooK86qYu6o25SbJANXT4J@4C63ZrHGyiXaV6TnUklGE2rnna2e4JOC01D4K089wcETQpH4FY5/3Ig1STg8b9L7m7cjcVPVJd/hYYn4sLKV8UM75wvRFmujU0Mi9kXXVgG8VBe7oPmfVh7OA6vpTW5hI4CGgc0CWjq9/GNp7wPm8hRdW88M2h7Zob4DIDpDGt6c06ua1quWf8uNr7xzf7jnH8KvgnOMfxj1DGCPXRSEB/gvQHyInBE8EWIRcCEiIVQHPZ9BfD2/Rfd9G3kG@AQIVjCMWoactf5fw)
```
def f(s:Seq[Int],n:Int)={
val r = mutable.Map[Int, (Int, Int, Seq[Int])]()
var R = 0
for ((v, i) <- (s.zipWithIndex.sortBy { case (v, i) => -v})) {
val K = r.keys
.filter(I => r(I)._3.contains(i + 1) || r(I)._3.contains(i - 1))
.map(I => r.remove(I).get)
.toSeq
.sortBy(_._1)
if (K.nonEmpty) {
val (a, b) = (K.init, K.last)
R += 1
if (a.nonEmpty) {
r += (R -> (a.head._1 - v, a.head._2, Nil))
R += 1
r += (R -> (b._1, b._2, b._3 ++ a.head._3 ++ Seq(i)))
} else {
r += (R -> (b._1, b._2, b._3 ++ Seq(i)))
}
} else {
R += 1
r += (R -> (v, i, Seq(i)))
}
}
r.keys.toSeq.sortBy(key => -r(key)._1).map(i => r(i)._2).take(n)
}
```
] |
[Question]
[
Spirals are cool , so are numbers, and number spirals are even cooler. But what if I want a specific number, in a specific place using xy coordinates...
**Challenge**
Using an infinite spiral moving down first, curling in a counterclockwise manner
ex:
```
6 5 4
7 0 3
8 1 2
9 10 11
```
1. Take negative and positive inputs(integers) in the form of (x, y)
2. When given those coordinates return the number at that position in the spiral
3. The integer inputs must be the maximum that your language can use
ex:
```
6 5 4
7 0 3
8 1 2
9 10 11
input : (0,0)
output : 0
input : (1,1)
output : 4
input : (-1,-1)
output : 8
input : (5,5)
output : 100
input : (-5, -6)
output : 121
input : (2, -5)
output : 87
input : (-9, 2)
output : 349
input : (-7, 8)
output : 271
input : (-5, -7)
output : 170
```
**Scores**
This is a codegolf, so smallest code wins!!!
[Answer]
# JavaScript (ES7), 50 bytes
This is using a slightly modified version of the formula that I've used and explained [in this post](https://codegolf.stackexchange.com/a/179158/58563).
```
x=>y=>(i=4*(x*x>y*y?x:y)**2)-(x<y||-1)*(i**.5-x-y)
```
[Try it online!](https://tio.run/##XYxBCoMwEEX3PYXLzEA0CaYtpUnPIlZLihippSTg3dNR6qIZ3qwe7z@bTzO3Lze9@ejvXepNCsZGY5kzNbKAwUaMt3CJgKiAs3CNy8IlIHOIpeaBR0itH2c/dOXgH6xnAggo6KqqEId/KYHYZZ1J2l0fNnnOpAZiL6XIh/mRWv1rpZK5plxt@Tp9Sl8 "JavaScript (Node.js) โ Try It Online")
or [Try a version that displays the spiral](https://tio.run/##dZBBasNADEX3PoV2I81EhoSklDrjrHKCbrsxcVwcgifYJoyIc3ZH0xZKS7uSkL7@f@hUXavh0LeXkbtQH@fGz@LL6Ets/dpitLEUK7v4ImTtihjjVqaJl2SxtTbfcGShuQk9DmMPHgwATGYBUXt@KrRuPaTqHMEtA0gy5wEjODCG8ktVv45VP@Kaiuyefa3NW8fMzqT1vqtx87wAw0YlWcoS@DAVKD9ThPmHu54b9Vfdr5AVpYkSFipOTv9yfpM2GAmF/uIFuCvzIXRDOB/zc3hPX6BifgA).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ยทnร DtIO-I`โบยท<*-
```
Port of [*@Arnauld*'s JavaScript (ES7) answer](https://codegolf.stackexchange.com/a/179982/52210).
And -3 bytes thanks to *@Arnauld* as well.
My answer uses the formula:
$$T=\max((2\*x)^2, (2\*y)^2)$$
$$P=\begin{cases}
1&\text{if }y>x\\
-1&\text{if }y\le x
\end{cases}$$
$$T - (\sqrt{T} - (x+y)) \* P$$
Which saves bytes with some of 05AB1E's convenient builtins, in comparison to the similar but slightly different formula *@Arnauld* uses in his answer.
[Try it online](https://tio.run/##yy9OTMpM/f//0Pa8wwtcSjz9dT0THjXsOrTdRkv3//9oXVMdXbNYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRf@f/Q9rzDC1xKKv11KxMeNew6tN1GS/e/zv/oaAMdg1idaEMdQyCpa6ijC6JNdUxBPFMdXTMgbaSjaxobCwA).
**Explanation:**
```
ยท # Double both values in the (implicit) input-list
n # Then square both values
ร # Take the maximum of the two
Dt # Duplicate it, and take its square-root
IO- # Subtract the sum of the input-list
I`โบ # Check if y is larger than x (1 if truthy; 0 if falsey)
ยท< # Double it, and decrease it by 1 (1 if 1; -1 if 0)
* # Multiply both
- # Subtract them from each other (and output the result implicitly)
```
[Answer]
# Perl 5, 55 bytes
From @Arnauld's formula
```
/ /;$_=($i=2*max abs$`,abs$')**2-($`<$'||-1)*($i-$`-$')
```
[TIO](https://tio.run/##FY2xCsIwFEX3fMUbHrQNXtoE4lDNH@jobCo4BKINTQaHfrvPuJzlHDj5uSUnMtJ44rvvOXqrX8uHlkfhcPizG7S26Dmcudt3mEG3ChzQjMhEkzJkFAzBKEdO4UhodGS/a65xfRdBToLrJZY6z7cak2@HHw)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
แธคยฒแนยฉยฝ_Sร>/แธคโฦยฎ_
```
[Try it online!](https://tio.run/##y0rNyan8///hjiWHNj3c2XBo5aG98cGHp9vpA0UeNcw81nVoXfz///@NdIwB "Jelly โ Try It Online")
Port of [@KevinCruijssenโs version](https://codegolf.stackexchange.com/a/180076/42248) of [@Arnauldโs formula](https://codegolf.stackexchange.com/a/179982/42248) so be sure to upvote them.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 45 bytes
```
(For[i=j=0,ReIm@i!=#,i+=I^โ2โ++jโI];j)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X8Mtvyg60zbL1kAnKNUz1yFT0VZZJ1Pb1jPuUU@H0aOOWdraWY96Oj1jrbM01f4HFGXmlThopek7VHNVG@gY1OpwVRvqGIIoXUMdXTDDVMcUzDfV0TUDMYx0dCECljpGYNpcxwKmwLyWq/Y/AA "Wolfram Language (Mathematica) โ Try It Online")
Generates the spiral up to the desired point
] |
[Question]
[
Forget BIDMAS! Write a program that takes an equation *and* an operator precedence order, and prints the result.
Example input format:
```
1.2+3.4*5.6/7.8-9.0 */+-
```
Rules & guidelines:
* The only operators that are defined are addition (+), subtraction (-), multiplication (\*), and division (/). No parentheses, no exponentiation.
* Associativity is always left-to-right. For example, `10/4/2` is to be interpreted as `(10/4)/2` with a result of 1.25, rather than `10/(4/2)`.
* The input format is as follows:
+ An equation, followed by a space, followed by the operator precedence specification (or two string arguments, one for the equation and the other for the precedence).
+ The equation comprises base-10 decimal numbers separated by operators, with no spaces. Integer values do not have to contain a period character, i.e. both `5` and `5.0` are to be accepted values.
+ For simplicity, negative numbers may not be included in the input, e.g. `6/3` is valid but `6/-3` is not. Input also may not contain a leading or trailing operator, so `-6/3` isn't considered valid, nor is `6-3+`.
+ The precedence specification string is always 4 characters long and always contains the characters `+`, `-`, `/`, and `*` once each. Precedence is read as left-to-right, e.g. `*/+-` specifies multiplication with the highest precedence, division next, then addition, and finally subtraction. **EDIT:** It is acceptable to take the precedence string in reverse order (lowest to highest) as long as you specify this in your answer.
* Input is a string to be taken via command line arguments, STDIN, or the default input format in programming languages that do not support these input methods.
* You are free to assume that the given input will be in the correct format.
* Output is via STDOUT or your language's normal output method.
* The printed result should be in base-10 decimal.
* Results must be computed to at least 4 decimal points of accuracy when compared to a correct implementation that uses double precision (64-bit) floating point arithmetic. This degree of freedom is designed to allow for the use of fixed-point arithmetic in languages that have no floating-point support.
* Divide by zero, overflow, and underflow are undefined behaviour. Your code is free to assume that no inputs will be given that will trigger these cases.
* You may not call out to any external services (e.g. Wolfram Alpha)
* You may not call out to any programs whose primary function is to solve these types of problems.
Test cases:
1. `6.3*7.8` followed by any operator precedence specification prints 49.14
2. `2.2*3.3+9.9/8.8-1.1 */+-` is parsed as `((2.2*3.3)+(9.9/8.8))-1.1` and should print 7.285
3. `2.2*3.3+9.9/8.8-1.1 +*/-` is parsed as `((2.2*(3.3+9.9))/8.8)-1.1` and should print 2.2
4. `10/2+5-1 +-/*` is parsed as `10/((2+5)-1)` and the printed result should be 1.6666666...
5. `2147480/90+10*5 +/-*` is parsed as `(2147480/(90+10))*5` and the printed result should be 107374
6. `3*55-5/8/4+1 -/+*` is parsed as `3*((((55-5)/8)/4)+1)` should print 7.6875
7. An input containing one thousand instances of the number `1.015` separated by multiplier operators (i.e. the expanded multiplicative form of `1.015^1000`), followed by any operated precedence specification, should print a number within 0.0001 of 2924436.8604.
Code golf, so shortest code wins.
[Answer]
# JavaScript (ES6), 94 bytes
Not particularly short, but fun. Adding parentheses all over the place...
```
s=>([e,o]=s.split` `,[...o].map(x=>e=e.split(x).join((a+=')')+x+(b+='(')),a=b=''),eval(b+e+a))
```
### Test cases
```
let f =
s=>([e,o]=s.split` `,[...o].map(x=>e=e.split(x).join((a+=')')+x+(b+='(')),a=b=''),eval(b+e+a))
console.log(f("6.3*7.8 +-*/")) // 49.14
console.log(f("2.2*3.3+9.9/8.8-1.1 */+-")) // 7.285
console.log(f("2.2*3.3+9.9/8.8-1.1 +*/-")) // 2.2
console.log(f("10/2+5-1 +-/*")) // 1.6666
console.log(f("2147480/90+10*5 +/-*")) // 107374
console.log(f("3*55-5/8/4+1 -/+*")) // 7.6875
```
### Historical note
A similar method was used in early FORTRAN compilers. Here is a [link from archive.org](https://archive.org/stream/bitsavers_computersA_13990695/196212#page/n9/mode/2up) to a relevant article written by [Donald E. Knuth](https://en.wikipedia.org/wiki/Donald_Knuth) in a 1962 book called *Computers and automation*.
### Examples
Let's consider the expression `2.2*3.3+9.9/8.8-1.1`.
With operator precedence `*/+-`, it will expand to:
```
((((2.2)*(3.3)))+(((9.9))/((8.8))))-((((1.1))))
```
With operator precedence `+*/-`, it will now expand to:
```
((((2.2))*((3.3)+(9.9)))/(((8.8))))-((((1.1))))
```
Removing all redundant parentheses, we get:
```
((2.2*3.3)+(9.9/8.8))-1.1 = 7.285
```
and:
```
((2.2*(3.3+9.9))/8.8)-1.1 = 2.2
```
[Answer]
## JavaScript (ES6), 59 bytes
```
f=(s,[o,...a])=>eval(o?s.split(o).map(e=>f(e,a)).join(o):s)
```
Port of my golf of @HyperNeutrino's Python answer. Takes lowest precedence first.
[Answer]
## JavaScript (ES6), ~~174~~ 133 bytes
Saved 41 bytes thanks to Arnauld.
```
i=>([e,o]=i.split` `,e=e.split(/([+*/-])/),[...o].map(x=>{while(~(b=e.indexOf(x)))e.splice(--b,3,eval(e.slice(b,b+3).join``))}),e[0])
```
First golf! This is probably terribly unoptimized.
### Ungolfed:
```
f = input => {
[equation, output] = input.split(" ");
equation = equation.split(/([+*/-])/);
[...output].map(x => {
while (~(b = equation.indexOf(x))) {
equation.splice(--b, 3, eval(equation.slice(b, b + 3).join("")));
}
});
return equation[0];
};
```
This splits the input equation into tokens of numbers and operators, then iterates through operators in the specified order and collapses pairs of numbers using `eval()` until there's only one left.
JavaScript rounding error trash means that test case 3 results in `2.1999...` instead of `2.2`. I'm not sure if that disqualifies this answer, but oh well.
### Test cases:
```
f=i=>([e,o]=i.split` `,e=e.split(/([+*/-])/),[...o].map(x=>{while(~(b=e.indexOf(x)))e.splice(--b,3,eval(e.slice(b,b+3).join``))}),e[0])
console.log(f("6.3*7.8 +-/*"));
console.log(f("2.2*3.3+9.9/8.8-1.1 */+-"));
console.log(f("2.2*3.3+9.9/8.8-1.1 +*/-"));
console.log(f("10/2+5-1 +-/*"));
console.log(f("2147480/90+10*5 +/-*"));
console.log(f("3*55-5/8/4+1 -/+*"));
console.log(f((new Array(1000)).fill("1.015").join("*") + " +-*/"));
```
[Answer]
# [Python 3](https://docs.python.org/3/), 77 bytes
```
f=lambda a,b:eval(b and b[0].join(str(f(A,b[1:]))for A in a.split(b[0]))or a)
```
[Try it online!](https://tio.run/##FcpLCsMgEADQqwyuZhrzsaWbQBY5R8hiJJVa7ChGCj29SbaPl/7lHeVRq5sCf@3GwNqOrx8HtMCygV2GtftEL7iXjA5nbRczrkQuZpjBC3C3p@ALXpPoVKaaspdybmWG/t48W6M0qFvfNoqoHg "Python 3 โ Try It Online")
-23 bytes thanks to Neil (takes operator precedence in reverse)
-1 byte thanks to Mr. Xcoder
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
แนฃโนแธแนชยครฑโฌโนแนยคjโนแธแนชยคลVยตยนโน?
```
[Try it online!](https://tio.run/##y0rNyan8///hzsWPGnc@3NH1cOeqQ0sOb3zUtAbE3znt0JIsJImjk8IObT20Eyhi////fyUjPSMtYz1jbUs9S30LPQtdQz1Dpf9K2lr6ukoA "Jelly โ Try It Online")
# Explanation
```
แนฃโนแธแนชยครฑโฌโนแนยคjโนแธแนชยคลVยตยนโน? Main Link
? Ternary:
โน If the right argument is truthy:
แนฃ Split it by
แธแนช The last element of
โน ยค The right argument
โฌ For each element
รฑ Call the next link as a dyad (wraps around so this calls the current link as a dyad)
โนแนยค With right argument as `right_argument[:-1]`
j Join with
แธแนช The last element of
โน ยค The right argument
ลV Evaluate as Python code
ยต Start a new monadic chain. If the right argument is falsy:
ยน Identity: Return the left argument unmodified
```
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 87 bytes
```
x=>y=>eval((f=b=>a=>b?"(#{e.join(map(f(b[to-1]),a.split(e=b[-1])))})":a)(y)(x)).evalf()
```
[Try it online!](https://tio.run/##FcxBCsIwEAXQu4ybP9akRnAjTDxIcZFAUiK1CTVIi3j2SLdv8cqSa57bKG0Vu4kNHzcBUbxYJ9bfCYdv0M@cZrxcQYQfalbmwSen32VKFUH8sAPzj@nmGBtjZdb7FMGtLGmuGEHm3F@6qzLEoE71R2Jufw "Proton โ Try It Online")
+19 bytes to accommodate for the unnecessarily restrictive output format. seriously? the restriction is actually making the answers *less* accurate because now instead of precise fractional output it's giving inaccurate IEEE floating points... think about it...
[Answer]
# [Perl 5](https://www.perl.org/), 64 + 1 (`-p`) = 65 bytes
```
s/ .*//;for$i(map"\\$_",$&=~/./g){s/[\d.]*$i[0-9.]*/$&/ee&&redo}
```
[Try it online!](https://tio.run/##DcZBCsIwEAXQq5QyBE2b/BQdsIhH8ASNiNAogWpC4k706I6@1cuhLCxS0VgN7K@pUFzdL7n1ns5tT@rwgcVt/aqY/GxPmuLkzPgPSCEEpUqY01tko5kNY4dtNzQGnf6m/IzpUcUc2brBick/ "Perl 5 โ Try It Online")
[Answer]
# JavaScript (ES6), 96 bytes
```
f=(o,s)=>o?f(o.slice(s!=(s=s.replace(eval(['/','\\'+o[0],'/'].join`(\\d+\\.?\\d*)`),eval))),s):s
```
A non-recursive attempt was first made for this technique, but it came up at 101:
```
(s,o)=>[...o].map(x=>[...s].map(_=>s=s.replace(eval(['/','\\'+x,'/'].join`(\\d+\\.?\\d*)`),eval)))&&s
```
[Answer]
## Clojure, 167 bytes
```
(defn f [i O](eval(read-string(or(first(filter some?(for[o O](let[[x y](clojure.string/split i(re-pattern(str \\ o))2)](when y(str" ("o\ (f x O)\ (f y O)")"))))))i))))
```
Whoa, long function names strike again! Operation precedence `O` is taken in "reverse" order.
[Answer]
# C (gcc) , 276 bytes
```
A,B,u,i,j,k;double g(){double a,b,f[1000];char o[999],p[5];for(i=k=0;o[i++]^32&&scanf("%lf%c",&f[i],&o[i]););for(gets(p);k<4;k++)for(A=B=0;B<i;A=B){for(;!f[B++]&&i/B;);if(A&&o[--A]==p[k])u=p[k],a=f[A],b=f[--B],f[B]=u^42?u^43?u^45?a/b:a-b:a+b:a*b,f[A]=0,o[A]=o[B++];}a=f[i-1];}
```
[Try it online](https://tio.run/##7dDNbqMwEADgO0/BRirCP4NtfhpYF1XwGqwrERpSl2yI0kaqFOXZs0O6x73tdQ7@ZhhrxjYD7IbhdmtkK8/Sy3c52df5vNlvw13MLn/TXm7k2BmttbPDW38K566qKiePXeHsOJ9iX0@1tnPnhXAvWRpFH0N/GOPVw358GFYyGjvvZIT7jll279htPz/iI7PTU24nIdhSa@oWp7RP3mLGLkvJ/hi7FodGkVcttvoxbiIcBNC4uj52k2Pne5B9PXaNkxsMAK3D@7auPr/k6TOSLRTPvdr87AGXwMWXN@EULeclzPdz7HWZ48Fgdvvd@0P8fQ9/@Ay/6rX9ArDsEhxPWPh@36/DSuKvYja4Xm@PScbXSRkqATxIk5RnSSaqpFJlUoJJTMhx558bgisIjFapKAC/QGG/ydd5qVWlhdG8CIXCoRkvCihUqXJhQlCCBybRpuAkSZIkSZIkSZIkSZIkSZIkSf6HoQCu/gA)
[Slightly longer solution using NAN](https://tio.run/##7dDLjpswFAbgvZ8CpRoEvmCbSwN16AgeYF6AeiSgQ@IyAZSLNFKVZ08PmS676/Ys/HE4xj@2e7Hv@/v9izsu8@myO7aXQ3T4Tipe8yt3/Bcfzc/52r2/efsg/E3@1i3v@NBopZQ1pD@0J29uiqKwfGky6AzzKXDlWCozN44x@5rEvn/u22kINk/vw1O/4f7QOMt9mLehCT@X7N8u52AJzbhLzchY@GhWZQ059c4ZqGAHa8@489ROwdDUEB76vpP1muGGoPIhUojKluXSjDYk18eTt@XQVJZ38BCitpzAWlteX9P4GUhWsudWdt9aAYPBoN36EQS9VC98Xov58TtDbmRNc0Kv9f3Yuglu5nHk6eJ9lFvzIYSBnS4naHye@Me04XB/sMfb7f41Sug2yj3JBCVxFNMkSlgRFTKPcqEj7VGY@ecEo1IQrWTMMgFvQsJ6nW7TXMlCMa1o5jEJoQnNMpHJXKZMe0IySnSkdEZRFEVRFEVRFEVRFEVRFEVRFP0PPSao/AM)
] |
[Question]
[
Given a text and a number `N`, output, in a human readable format, the set of the character [N-grams](http://en.wikipedia.org/wiki/N-gram) with their respective percentages.
**The smallprint**
* The text can be read from a file, stdin, passed as string parameter to a function or any other common way i forgot to mention
* The number `N` can be hardcoded, but only if it needs to be changed in one single place to change the functionality, the number counts as one byte regardless of the number of digits (`T=input();N=100;f(T,N)` would count as 20 bytes, not 22)
* No case sensitivity and all non-letter characters are treated the same. Inputs `Abra Cadabra!` and `aBRa#caDAbrA5` should produce the same output. The character for non-letter can be any printable non-letter, not necessarily contained in the input
* You may assume `N < text.length`
* Output can be written to a file or displayed on screen. If you use a function you can `return` the result instead of printing as long as it is human readable (a JSON object or array like in the examples below is fine, a custom class or a sparse matrix with `27^N` entries - not so much)
**Examples** with `text = 'Abra Kadabra!'`
`N = 1`
```
a 0.385
b 0.154
r 0.154
_ 0.154
k 0.076923
d 0.076923
```
`N = 12`
```
abra_kababra 0.5
bra_kadabra_ 0.5
```
`N = 2` (dont worry about number format or rounding as long as it sums up to `0.99 < x < 1.01`)
```
ab 0.1666666
br 0.16666
ra 0.1666
a. 0.166667
.k 0.0833333
ka 0.0833333
ad 8.33333e-2
da 0.0833333
```
a tree structure is fine too
```
{'a':{'b':0.166, '.':0.166, 'd': 0.0833},
'b':{'r':0.166},
'r':{'a':0.166},
'.':{'k':0.0833},
'k':{'a':0.0833},
'd':{'a':0.0833}}
```
or a list of lists
```
[['A', 'B', 0.166], ['B', 'R', 0.166], ...]
```
[Answer]
# Pyth, ~~40~~ ~~35~~ 27 character
```
KCm>m?k}kGNrz0dQ{m,bc/KblKK
```
Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=KCm%3Em%3Fk%7DkGNrz0dQ%7Bm%2Cbc%2FKblKK&input=Abra+Kadabra!%0A2&debug=0)
For the input `Abra Kadabra!`, `2` it prints something like (the order is each time different, because of the behavior of set):
```
{(('d', 'a'), 0.08333333333333333), (('r', 'a'), 0.16666666666666666), (('b', 'r'), 0.16666666666666666), (('"', 'k'), 0.08333333333333333), (('a', 'b'), 0.16666666666666666), (('k', 'a'), 0.08333333333333333), (('a', '"'), 0.16666666666666666), (('a', 'd'), 0.08333333333333333)}
```
I use `"` as special character.
## Explanation
```
m?k}kGNrz0 implicit: z = raw_input() # input_string
m rz0 map each character k of z.lower() to:
k N k '"'
? }kG if k in "a-z" else
We call the result X.
KCm>XdQ implicit: Q = input() # number N
m Q map each d in [0, 1, 2, ..., Q - 1] to:
>Xd X[d:] # all characters of X starting at position d
C zip - creates all N-grams
K store the results in variable K
{m,bc/KblKK
m K map each b in K to:
,b the pair (b, )
/Kb K.count(b)
c lK / len(K)
{ set - remove duplicates
```
# Printing in a 'human readable format': 35 character
```
KCm>m?k}kG\_rz0dQjbo_eN{m,sbc/KblKK
```
Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=KCm%3Em%3Fk%7DkG%5C_rz0dQjbo_eN%7Bm%2Csbc%2FKblKK&input=Abra+Kadabra!%0A2&debug=0)
For the input: `Abra Kadabra!`, `2` it prints:
```
('a_', 0.16666666666666666)
('ab', 0.16666666666666666)
('ra', 0.16666666666666666)
('br', 0.16666666666666666)
('ka', 0.08333333333333333)
('da', 0.08333333333333333)
('_k', 0.08333333333333333)
('ad', 0.08333333333333333)
```
## Explanation (differences)
```
\_ instead of N in m?k}kGNrz0
Uses '_' instead of '"'
s in {m,sbc/KblKK
This combines the individual characters
jbo_eN
o order the elements N by:
_eN the value -N[-1] (by the negative percentage)
jb join by newlines - prints each pair in row
```
[Answer]
## J, ~~57~~ ~~55~~ 48 characters.
As a dyadic verb, N goes left, text goes right.
```
[:((a.{~97+~.);"#:#/.~%#)((u:97+i.26)i.tolower)\
```
Example
```
2 ([:((a.{~97+~.);"#:#/.~%#)((u:97+i.26)i.tolower)\) 'Abra Kadabra!'
```
yields:
```
โรฎรฅโรฎรโรฎรโรฎยจโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรช
โรฎรabโรฎร0.166667 โรฎร
โรฎรบโรฎรโรฎรโรฎยบโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎยง
โรฎรbrโรฎร0.166667 โรฎร
โรฎรบโรฎรโรฎรโรฎยบโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎยง
โรฎรraโรฎร0.166667 โรฎร
โรฎรบโรฎรโรฎรโรฎยบโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎยง
โรฎรa{โรฎร0.166667 โรฎร
โรฎรบโรฎรโรฎรโรฎยบโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎยง
โรฎร{kโรฎร0.0833333โรฎร
โรฎรบโรฎรโรฎรโรฎยบโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎยง
โรฎรkaโรฎร0.0833333โรฎร
โรฎรบโรฎรโรฎรโรฎยบโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎยง
โรฎรadโรฎร0.0833333โรฎร
โรฎรบโรฎรโรฎรโรฎยบโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎยง
โรฎรdaโรฎร0.0833333โรฎร
โรฎรฎโรฎรโรฎรโรฎยฅโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรฒ
```
Thanks to randomra for a nine character improvement.
### Explanation
This is the solution with spaces inserted in the appropriate places:
```
[: ((a. {~ 97 + ~.) ;"#: #/.~ % #) ((u: 97 + i. 26) i. tolower)\
```
First, observe that `"#:` is shorthand for `"1 0` and that `u: 97 + i. 26` is just `'abcdefghijklmnopqrstuvwxyz'`, so without these two tricks we get
```
[: ((a. {~ 97 + ~.) ;"1 0 #/.~ % #) ('abcdefghijklmnopqrstuvwxyz' i. tolower)\
```
And this is how this works. In the following explanation, `x` and `y` are the left and right arguments, `u` and `v` are verbs, and `m` and `n` are nouns.
1. `[: u v`โรรฎa *capped fork,* `x ([: u v) y` is equal to `u (x v y)`. This is used instead of `u@v` because `v` is an adverbial phrase and parentheses were needed. In this code, `u` is `(a. {~ 97 + ~.) ;"#: #/.~ % #` and `v` is `((u: 97 + i. 26) i. tolower)\`.
2. `x u\ y`โรรฎapply `u` to each *infix* of `y` of length `x`. For example, `3 ]\ 'abcdefg'` where `]` is the identity function yields
```
abc
bcd
cde
def
efg
```
3. `n u v`โรรฎa fork with a noun as the left argument. `(n u v) y` is equal to `n u (v y)`. This is used multiple times in the code.
4. `tolower y`โรรฌconvert all upper case letters in `y` to lower case.
5. `x i. y`โรรฌfind the *index* of `y`, which is in this case for each item in `y` the lowest index into `x` at which that item can be found or the number of items in `x` if such an item does not exist. In our use case, `x` is the lower case alphabet. `('abcdefghijklmnopqrstuvwxyz' i. tolower) y` translated each (upper case or lower case) letter in `y` into a number from 0 to 25. Non-letters are translated into 26. Notice that the character immediately following `z` in ASCII is `{`.
6. `x u/. y`โรรฌapplies `u` to `y` *keyed* by `x`. That is, `u` is applied to groups of items of `y` with the same key in `x`. Noticeably, if `x` and `y` are equal, `y u/. y` applies `u` to groups of equal items of `y` and can be used to generate frequency statistics.
7. `# y`โรรฌthe *tally* of `y`, that is, the number of items in `y`.
8. `u~`โรรฌthe *reflexive* of `u`, that is, `u~ y` is equal to `y u y`.
9. `u v w`โรรฌa *fork,* `(u v w) y` is equal to `(u y) v (w y)`. This, too, is used multiple times in the code.
10. `x % y`โรรฌ`x` *divided by* `y`.
11. `#/.~ % #`โรรฌthe frequency count we want sans what we count.
12. `~. y`โรรฌthe *nub* of `y`, that is, each distinct item of `y`. For instance, `~. 1 2 3 3 4 6 6 6` yields `1 2 3 4 6`.
13. `(a. {~ 97 + ~.) y`โรรฌthe *nub* of `y` converted from indices into the alphabet back to letters; 26 is converted into `{` implicitly.
14. `x ; y`โรรฌ`x` *linked* to `y`, that is, both put into boxes and the boxes concatenated. For instance, `'abc' ; 1 2 3 4` yields
```
โรฎรฅโรฎรโรฎรโรฎรโรฎยจโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรช
โรฎรabcโรฎร1 2 3 4โรฎร
โรฎรฎโรฎรโรฎรโรฎรโรฎยฅโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรฒ
```
This is needed because in J, arrays are homogeneous; all items in an array need to have same type. A box hides what is in it and turns heterogeneous arrays into arrays of boxes.
15. `u"n`โรรฌ`u` *ranked* `n`. Rank is a slightly complex concept so I won't explain it here, but in this case, `x ;"1 0 y` (for which `x ;"#: y` is just a shorthand) applies `;` to each string in `x` and the corresponding number in `y` as opposed to the entire of `x` and the entire of `y`. This is the difference between
```
โรฎรฅโรฎรโรฎรโรฎยจโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรช
โรฎรabโรฎร0.166667 0.166667 0.166667 0.166667 0.0833333 0.0833333 0.0833333 0.0833333โรฎร
โรฎรbrโรฎร โรฎร
โรฎรraโรฎร โรฎร
โรฎรa{โรฎร โรฎร
โรฎร{kโรฎร โรฎร
โรฎรkaโรฎร โรฎร
โรฎรadโรฎร โรฎร
โรฎรdaโรฎร โรฎร
โรฎรฎโรฎรโรฎรโรฎยฅโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรโรฎรฒ
```
and the correct output shown above.
[Answer]
# CJam, 53 bytes
```
q~el_'{,97>-'_er_,,\f>1$(W*<f<:L__&_@f{\a/,(}L,df/]z`
```
Without having a look at the other CJam answer, here is a shorter one.
Input goes like:
```
2 "Abra Kadabra!"
```
Output is like:
>
> [["ab" 0.16666666666666666] ["br" 0.16666666666666666] ["ra" 0.16666666666666666] ["a\_" 0.16666666666666666] ["\_k" 0.08333333333333333] ["ka" 0.08333333333333333] ["ad" 0.08333333333333333] ["da" 0.08333333333333333]]
>
>
>
Explanation soon.
[Try it online here](http://cjam.aditsu.net/#code=q~el_'%7B%2C97%3E-'_er_%2C%2C%5Cf%3E1%24(W*%3Cf%3C%3AL__%26_%40f%7B%5Ca%2F%2C(%7DL%2Cdf%2F%5Dz%60&input=2%22Abra%20Kadabra!%22)
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 56 bytes
```
"A[a{"โรคโโรงรฃโรคโ({2|๏ฃฟรนรฏยฎ?๏ฃฟรนรฏยฉ+16โรณยฌยจ๏ฃฟรนรฏยฎ;'_'}ยฌยฎ)โรคโ{uโรฃร รรฒ(โรขโ s)โโรรบ+ยฌยฅรรฒโรงโโรผรบ๏ฃฟรนรฏยฎรรฒuโรรชโรงโsโรรช๏ฃฟรนรฏยฉโรรฏ๏ฃฟรนรฏยฎ}
```
Anonymous function that takes a string on the left and the number N on the right. It returns a 2-D array, in which each row contains a length-N substring and a 0-D array containing the substring's frequency. [Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgIkFbYXsi4oq44o2L4oq4KHsyfPCdlag/8J2VqSsxNsOXwqzwnZWoOydfJ33CqCniirh7deKLiMuYKOKJoHMpw7fLnCvCtMuY4o234p+c8J2VqMuYdeKGkOKNt3PihpDwnZWp4oaV8J2VqH0KCiJBYnJhIEthZGFicmEhIiBGIDI=)
### Explanation
*Wow* this is ugly--and not just because of BQN's total lack of character/string primitives.
The first half normalizes the string argument by converting lowercase letters to uppercase and non-letters to underscores:
```
"A[a{"โรคโโรงรฃโรคโ({2|๏ฃฟรนรฏยฎ?๏ฃฟรนรฏยฉ+16โรณยฌยจ๏ฃฟรนรฏยฎ;'_'}ยฌยฎ)
"A[a{"โรคโโรงรฃ Classify the characters: 0 if < 'A', 1 if >= A but
< '[', and so forth (meaning, in particular, 1 for
uppercase letters and 3 for lowercase letters)
โรคโ( ) With that as the left argument and the original
string as the right argument,
{ }ยฌยฎ call this function on each number-character pair:
2|๏ฃฟรนรฏยฎ? If the number is odd (1 or 3):
ยฌยจ๏ฃฟรนรฏยฎ 1 minus the number
16โรณ times 16
๏ฃฟรนรฏยฉ+ plus the character
;'_' Else, underscore
```
Now the actual meat of the function:
```
โรคโ{uโรฃร รรฒ(โรขโ s)โโรรบ+ยฌยฅรรฒโรงโโรผรบ๏ฃฟรนรฏยฎรรฒuโรรชโรงโsโรรช๏ฃฟรนรฏยฉโรรฏ๏ฃฟรนรฏยฎ}
โรคโ{ } Pass the left argument through the above function
before calling this function:
๏ฃฟรนรฏยฉโรรฏ๏ฃฟรนรฏยฎ Get all length-(right arg) substrings of (left arg)
sโรรช Save that 2D array of characters as s
โรงโ Deduplicate
uโรรช Save that 2D array of characters as u
โรงโโรผรบ๏ฃฟรนรฏยฎรรฒ For each row of u, find all occurrences of that
substring in the left arg; mark the beginning of
an occurrence with a 1, all other positions with a 0
+ยฌยฅรรฒ Sum each row, giving a list of occurrence counts
โโรรบ Divide each by
(โรขโ s) the length of s
โรฃร รรฒ Pair each with
u the corresponding unique substring
```
[Answer]
# CJam, ~~61~~ 59 bytes
I think the input transformation is quite nifty, but the actual tallying needs work.
```
l~qeu'~),_el&'_er_,,2$f{2$@><\}\W*<:L__&\f{1$a/,(L,d/][};]`
```
Reads `N` on the first line and then treats the remainder of STDIN as the text:
```
2
Abra Kadabra!
```
The result is printed as a nested CJam-style array with upper case letters and `_` for non-letters:
```
[["AB" 0.16666666666666666] ["BR" 0.16666666666666666] ["RA" 0.16666666666666666] ["A_" 0.16666666666666666] ["_K" 0.08333333333333333] ["KA" 0.08333333333333333] ["AD" 0.08333333333333333] ["DA" 0.08333333333333333]]
```
[Test it here.](http://cjam.aditsu.net/#code=l~%3ANqeu'~)%2C_el%26'_er%5C%2C%5Cf%7B%3EN%2F%7B%2CN%3D%7D%2C~%7D%3AL__%26%5Cf%7B1%24a%2F%2C(L%2Cd%2F%5D%5B%7D%3B%5D%60&input=2%0AAbra%20Kadabra!)
[Answer]
# Haskell, 164 bytes
```
import Data.Char
import Data.List
l=genericLength
c c|isAlpha c=toLower c|1<2='_'
n%i=[(s!!0,l s/l p)|s<-group p]where p=sort[take n s|s<-tails$map c i,length s>=n]
```
Usage: `12 % "Abra Kadabra!"` -> `[("abra_kadabra",0.5),("bra_kadabra_",0.5)]`
This is longer than I thought. Does anyone know a shorter version of a "split list into sublists of length n" function (my attempt: `[take n s|s<-tails$ i,length s>=n]`)?
How it works:
* map all characters in the input list to lowercase or '\_' if not a letter
* split into a list of substrings of length n
* sort, name the list `p`
* group equal elements (e.g. for n=2 -> `[["_k"],["a_","a_"],["ab","ab"],["ad"],["br","br"],["da"],["ka"],["ra","ra"]]`
* for each sublist take one of it's elements and pair it with the length divided by the length of p
[Answer]
# [Clip 10](http://esolangs.org/wiki/Clip), 53
```
\[tm[b{(b/)b)mlxt`}q[bm[juj+jtb}R)mlbt]a[!cA}m.U`xS]n
```
Example:
```
C:\Users\~~~~~\Documents>java -jar Clip10.jar ngram.clip
Abra Kadabra!
2
{{"AB", 0.166666666666666}, {"A ", 0.166666666666666}, {"RA", 0.166666666666666}, {"BR", 0.166666666666666}, {"DA", 0.083333333333333}, {" K", 0.083333333333333}, {"KA", 0.083333333333333}, {"AD", 0.083333333333333}}
```
## Explanation
```
[t ]n .- Assign the second input to t -.
m.U`x .- Convert the input to upper case -.
a[!cA} S .- Replace all non-alphabetic characters with spaces -.
[b ] .- Assign the modified string to b -.
m[juj+jtb}R)mlbt .- All substrings of length t -.
q .- Frequencies (in the form {"A", 1} )-.
m[b{(b/)bmlxt`} .- Use proportional frequencies
\ .- Make the array pretty -.
```
[Answer]
# Mathematica, ~~124~~ 119 bytes
Could probably golf further.
```
#[[1]]->#[[2]]&/@#/Length@#&@Tally@Partition[Characters@StringReplace[ToLowerCase@#,Except@LetterCharacter->"_"],#2,1]&
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/) with MiServer's [`Strings.lc`](https://github.com/Dyalog/MiServer/blob/master/Utils/Strings.dyalog#L15), 30 bytes
Prompts for text, then for `N`. Prints N-grams and frequencies.
```
(โร โข,โรคยขโร รฒโรขยขโรฉรฏU2338โโโรขยข)โรฉรฏ,/'\W'โรฉรฏR'_'lcโรงรป
```
[Try it online!](https://tio.run/nexus/apl-dyalog-classic#pVNZUxNBEH7fX9EpHpJUQbaAsgrzxqnIaQLiWdZsMpuMbnbXnQkxWloqCOEI4oGFB5aiKOIth4r61P9k/gh2FnlAHp2H6elvunu@PiaZ5hklPBe6@wYHUkPQlRrog7xSvkyaZk6ofNFKZLyC2VFmjpcz@0SaB6M8MC3Hs8wCk4rOw0o40kyrQLg5mciGlnW9hwwDaOnKJAR6Yt7xSjxodfw8s7gCXV2CAstyYGAX3V0G0gOhIMNcsDgku92MU8zyaDaMAmGMKLMyWW7n8uLCRafgev6lQKriaOly@Qq@wGV8iW9wFdfwHb7HD/gRP@Fn/IrruIGb@AO38Sf@xuf4ClfwNb7FL7iF3/FXdI/mfr5F3/9/vq1t7R2dXUeOdh/r6e3rHxg8nkoPDZ8YOXnqNN7EWziGk1jBaZzBWaziHN7BebyH9/EBLuAjfIxPcAlv4Djexgmcwrv4EBfx6T987cArKI8eu@rSpqsbjXp6LKbAjofqNuiZcbiuK6umRYCrp1YESVtX1yXJel3dTMrQJmaZsuajzlimOLcLUTgyiJOQ18Ia1F5rUB5lLanZYLsGoZFIBPoTbYkkCBf2JgTqEuFcJNJcFf12r@AzJSzhCFWGknAc8MioFAjFQeW55ASqPMRaGg/r2a04CLsGU0AaMD/gtIOklniBklT1MHMnc2Cs9jVNVxZ3ixMy/9sgZjkcemtODbUcbJFhYTM9G6Qo@HTJgoCVDSPZ6Wb3/w3DoKLbOzFdWavX08sUXk8t67mF4abm5hb8RkqctHozenYkSodU9HyUKFaf7ZDbjm20WgGDHkYMAhYxGo0DSNMBqOkP "APL (Dyalog Classic) โรรฌ TIO Nexus")
Only 25 characters (but 44 bytes) in [Dyalog Unicode](https://tio.run/nexus/apl-dyalog#pVNZU9NQFH7PrzgdHtrOQDMw44z2jVURCtiCuI5z0ybt1TSJyS21OjoqCGUp4oKDC46iKOIui4j69P2T@0fwNsgD8mge7rn5cpbvnO8kmTGzgrsOdacG@tOD1JXuT1FBCC9I6nqei0LJSGTdot5RYbab11M8Y/ojpq8btmvoRRYIdR8S3A70jPC5kw8SudCzofeQppF6ZHWCfDk@Z7tl02@1vQIzTEGytkhFljOJkVVydhkELnFBWeaQYVKy28napZwZzYVZKMwRZUY2Z1r5Ar94yS46rnfZD0RppHylchUvsYRXeIsVrOI9PuAjPuEzvuAb1rCODfzANn7iN17gNZbxBu/wFZvYwq/oHs39fEue9/98W9vaOzq7jh7rPt7Tm@rrHziRzgwOnRw@dfoMbuE2RjGBKqYwjRnUMIu7mMN9PMBDzOMxnuApFnETY7iDcUziHh5hAc/@4Wv5blG4qtg1Rx2ytt4sp0Zjgqx4@LpNcnqMbsjqim4owJGTy1xZS9bWAmUbZW0jGYQ@MUMP6jHirKHz87uQSqcc4soE18MZ1Ks1CVd1HSixyXI0hUYiEepLtCWSxB3a2xBqSIR7kciYouS1u0WPCW5wm4sKlbltk6ucyj4XJomCGZgKFAWKHW4@Imc248StOqwSqgXzfFOdFChJXF8Eauph53b2wFrtE01WF3aHEzL/KxAzbJN660FN9R4snmWhmK5FAS966iPzfVbRtGSnk9v/b2iaGrq1E5PV1UY5taTSy8klObOF78rG5ex8ox49NxxVl3T0QlSxqz3fURE7ltZq@Ix6mCrus4jWrB1AWg5ALX8A "APL (Dyalog Unicode) โรรฌ TIO Nexus"):
```
(โร โข,โรคยขโร รฒโรขยขโรฅโโโโรขยข)โรฉรฏ,/'\W'โรฉรฏR'_'lcโรงรป
```
โรยถ because `โรฅโ` โรกรฎ `โรฉรฏU2338`, but is not included in the Classic character set.
### Explanation
`โรงรป`โรรget text input
`lc`โรร**l**ower**c**ase
`'\W'โรฉรฏR'_'`โรรPCRE **R**eplace non-word characters with underscores
`,/`โรรconcatenate the characters in each possible position of a sliding window of size
`โรฉรฏ`โรรnumber-input
`(`โรยถ`)`โรรapply the following anonymous tacit function on that (the N-grams):
โรร`โร โข`โรรthe unique (N-grams)
โรร`,`โรรfollowed by
โรร`โรคยขโร รฒโรขยขโรฅโ`โรรthe number occurrences for each unique element (of the N-grams)
โรร`โโ`โรรdivided by
โรร`โรขยข`โรรthe tally (of N-grams)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 86 bytes
```
->s,n{s.upcase.gsub(/[^A-Z]/,?_).chars.each_cons(n).tally.map{[_1,_2/(s.size-n+1.0)]}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3w3TtinXyqov1SguSE4tT9dKLS5M09KPjHHWjYvV17OM19ZIzEouK9VITkzPik_PzijXyNPVKEnNyKvVyEwuqo-MNdeKN9DWK9Yozq1J187QN9Qw0Y2trIaZvL1Bwi1ZyTCpKVPBOTEkE0opKOgpGsRDZBQsgNAA)
[Answer]
# [Python](https://www.python.org), 92 bytes
```
lambda s,k:(b:=1+len(s)-k)//b*(a:=[s[i:i+k]for i in range(b)])and{t:a.count(t)/b for t in a}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=JY1BDoIwEAC_0nDqCtjoyTThJcBhF6g2xULKciDGl3ghMfoBX-NvlPQ0h5lkHu9x4cvg16cpqtfMJj99qx6v1KKYMqcl6eKQ9p2XE-QOlKKdRF2UU2m1TV1thiCssF4E9OdOEtSAvr2xxn0zzJ4lgyKxVbxVeI-PzxjsXxqZIBI1SXYEiGZdI38)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
โรรปโยบโรธUโยฐโยบSยฌยฐ'_โฮฉlDX.VโรดDโโ ยฌยขDO/โโ
```
Inputs in the order `N, text`. Outputs as a list of [string, decimal] pairs. A trailing `ยฌยช` (+1 byte) could be added to pretty-print them to STDOUT.
[Try it online](https://tio.run/##AT0Awv9vc2FiaWX//@KAnsO8w79Vw6HQvFPCoSdfw71sRFguVsOZRMWgwqJETy/DuP//MgpBYnJhIEthZGFicmEh) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipeBnq2RfqcOl5F9aAuQXWykAuf8fNcw7vOfw/tDDCy/sCT60UD3@8N4clwi9sMMzXY4uOLTIxV//8I7/tkoBRaklJZW6BUWZeSWpKQr5YCOAJugc2q1zaJv9/2hDHUMjHaNYLsekokQF78SURCCtCAA).
**Explanation:**
```
โรรปโยบโรธ # Push string "โยบโรธ", where `โรธ` is automatically replaced with the first
# (implicit) input-integer
U # Pop and store this string in variable `X`
โยฐ # Only keep all letters of the second (implicit) input-string
โยบ # Remove all those letters from the second (implicit) input-string
S # Convert the remaining string of characters to a list
ยฌยฐ # Split the second (implicit) input-string on those characters
'_โฮฉ '# Join it with "_" delimiter
l # Convert this string to lowercase
D # Duplicate the string
X # Push string `X` we created earlier
.V # Evaluate and execute it as 05AB1E code,
# creating overlapping substrings of size `N`
โรด # Uniquify this list
D # Duplicate the unique substrings
โโ # Triple-swap from a,b,b to b,a,b
ยฌยข # Pop the string and list, and count how many times each string occurs
D # Duplicate the list of counts
O # Sum it together
/ # Divide the individual counts by the sum
โโ # And pair it with the substrings we've duplicated
ยฌยช # (Optional) join each pair by spaces, and then each string by newlines
# (after which the result is output implicitly)
```
] |
[Question]
[
This is a successor to a [previous challenge](https://codegolf.stackexchange.com/questions/264102/iterate-over-all-non-equivalent-strings).
# Input
An integer \$1 \leq n \leq 5\$.
# Task
Your code should produce all strings that satisfy the following properties:
* Your string should contain exactly two each of the first \$n\$ letters of the alphabet.
* It should not contain the same letter twice in a row
* It must start with the letter `a`.
* If there is a letter at index `i` in the string, all the letters earlier in the alphabet must occur somewhere at the indices `1..i-1`. This means, for example, that the first `c` can't come before the first `b`.
* It must contain exactly \$2n\$ zeros.
* For each zero there must exist a pair of identical letters so that one of the pair is somewhere to its left and one of the pair is somewhere to its right in the string.
* It must not contain anything other than zeros and the lower case letters.
# Examples
```
n=1,`a00a` is the only valid output.
n=2,`a0ab000b`and `ab0000ab` are both valid outputs. `a0bab000` and `a0a0b00b` are not valid.
n=3,`a0bc0b0a000c` and `a0b000ca0b0c` are both valid outputs. ` a0cb0b0a000c` and `a0b000ba0c0c` are not valid.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 61 bytes
```
๏ผฎฮธโฯ
ฯ๏ผฆรโดฮธโฮฃ๏ผฅฯ
โบฮบโบ๏ผฅโงโนโฮบ0โฮธโฮฒโผยนโฮบฮผ0ฮฆโชชโฆฮฒฮธยนโงโปฮผฮฆโฎฮบยฌฯโงโนโฮบฮผยฒโฌคโฆฮฒฮฝโฮบฮพฯ
ฯ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VZDNSgMxEMfx6lOEPU0gBVs8iJ6WVUGwpVhv4mE_Ujc0X7uTqfZZvFRQ9Jl8GhO7FptLZub3n5k_8_pVt2Vfu1Jvtx8UlqOz76PzG-spzMhUsoeOXxzPCVsgwZ5jvHQ9g3tlJMKpYB3nLEdUTxYWZGBa-qSba0JYDX-q5baBW4kIhSMbEspOMi7YpaNKyyYuiUluN1AJdtVRqRHGgu3FhvMk2PVcKx2ir4XXKkCxqbUsWudTZxfp-HdQA1Nl426zl9_JtexRwirymQvgOR-Uh75MrE4S0fpwuOX_DL3wvycYpQP1KoIYvWNV43DIz4dstNbZ49tkl_8A) Link is to verbose version of code. Explanation: Based on my answer to [Iterate over all non-equivalent strings](https://codegolf.stackexchange.com/q/264102/).
```
๏ผฎฮธ
```
Input `n`.
```
โฯ
ฯ
```
Start with an empty string.
```
๏ผฆรโดฮธ
```
Loop `4n` times.
```
โฮฃ๏ผฅฯ
โบฮบโบ๏ผฅโงโนโฮบ0โฮธโฮฒโผยนโฮบฮผ0ฮฆโชชโฆฮฒฮธยนโงโปฮผฮฆโฎฮบยฌฯโงโนโฮบฮผยฒโฌคโฆฮฒฮฝโฮบฮพฯ
```
For each string so far, create strings with zero and all of the first n lowercase letters appended to it, but exclude those that fail to satisfy the criteria.
```
ฯ
```
Output the final strings.
There are two criteria that are checked before a zero can be appended:
* There must be fewer than `2n` zeros already in the string.
* There must be a letter that appears exactly once in the string.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 139 bytes
*The criterion on 0's is borrowed from [Neil's answer](https://codegolf.stackexchange.com/a/264194/58563). ("There must be a letter that appears exactly once" before a zero.)*
Prints the strings.
```
f=(n,s='',m=1,q=0,p,g=i=>~i&&g(i-1,(b=1<<i*4,i?i!=p:q&1118480&&n)*2>q/b%16&&f(n,s+"0abcde"[i],m+(i==m&m<n),q+b,i)))=>s[4*n-1]?print(s):g(m)
```
[Try it online!](https://tio.run/##TY3NboMwEITvfQo3ah0bLw3bogolLHmQKFKAAtoKmx@jXKL01anTU0@fNPNp5ru8lr6eeVzia7auLSkHnrZbsIQwUQIjdMRU/LCUneIYQVWEec5RCnzkZxr3k0TELM0SKZ2O3otpV73ip5TtY8pskrKqv5rNic9gjWIiK23uNEymAtZaU@FPaeRiPB/Hmd2ivN53yuq1HWbVN4twggQeAnISH4HGaHF7EqIenB/65q0fOnV5SC83d7/oQ6jC9R//KyG4r78 "JavaScript (V8) โ Try It Online")
[Hacked version](https://tio.run/##bY/NboMwEITvfYpt1Do2mARHKEKBdR4EIQUoUEdgfoxyQeTVqeHc07eaHY1mntkrM8Wo@sl7hWtTTmCmbAKEeYmgH5XebgModz0xp6bU9fQLUsIltS/v/Y8erRVSzQ0ej7xFwQf0ec9rVCjfipCaKk9wmqOIY@UEXN3VJ/a3gQghwiD0CdHMucjhnH@LKyHVFuUe/CwvfspDolLeulQhtqSNNeODm3PFGENpksDRnkjve29q2K2mLVurbqTbMG3risgiRggsXZfB/AFg81lkWXTadE15arqaPjbz16wX8KTlvlGny8Mal/UP) printing the number of solutions up to \$n=4\$
### How?
Because we have \$n\le5\$ and because a character may not appear more than \$10\$ times, we can store the character counts in a bitmask \$q\$ of \$6\times4\$ bits:
```
0000 0000 0000 0000 0000 0000
\__/ \__/ \__/ \__/ \__/ \__/
e d c b a 0
```
The 4-bit width is actually only required for 0's. The possible values for letter nibbles are **0000**, **0001** and **0010**.
When inserting a zero, we need to test whether there's at least one letter that appears exactly once. This is achieved by doing a bitwise AND of \$q\$ with:
```
0001 0001 0001 0001 0001 0000 = 1118480
```
All in all, this is shorter and faster than [my previous method](https://codegolf.stackexchange.com/revisions/264206/8) that was using an array.
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
s = '', // s = output string
m = 1, // m = upper character bound
q = 0, // q = bitmask keeping track of char. counts
p, // p = previous character index
g = i => // g is a recursive function taking a counter i
~i && g( // unless i = -1, do a recursive call to g:
i - 1, // decrement i
( // compute the max. count for this character:
b = 1 << i * 4, // b = LSB of the character nibble
i ? // if this is a letter:
i != p // the max. count is 2 if i != p
: // else (this is a zero):
q & 1118480 // the max. count is 2n if it's preceded
&& n // by a letter appearing exactly once
) * 2 > q / b % 16 // abort if this char. appeared too many times
&& f( // otherwise, do a recursive call to f:
n, // pass n unchanged
s + "0abcde"[i], // append the new character to s
m + // increment m if ...
(i == m & m < n), // ... i = m and m < n
q + b, // update the bitmask
i // set the previous character index to i
) // end of recursive call
) // end of recursive call
) => //
s[4 * n - 1] ? // if the target length is reached:
print(s) // print s
: // else:
g(m) // call g to generate more characters
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 40 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Aยฃยฉรรรฌ2รลรสรกรยฎQ}สรรกg;Q}สS>ฦถยฉรพฮตยฎsยก`รกรgฤ}P
```
Brute-force, so very slow. Is able to output the result for \$n=2\$ in about 20 seconds on TIO.
[Try it online.](https://tio.run/##yy9OTMpM/f/f8dDiQysP9x2efniN0eHpRycfnnlq0uGFh2ceWhdYC2RNObww3RrECrY7tg2ocN@5rYfWFR9amABU05x@pKE24P9/o/@6unn5ujmJVZUA)
**Explanation:**
Step 1: Create a string with the correct characters, to comply to the first and sixth rules ("*Your string should contain exactly two each of the first \$n\$ letters of the alphabet.*" and "*It must contain exactly \$2n\$ zeros.*"), and get all its unique permutations:
```
A # Push the lowercase alphabet
ยฃ # Pop and leave the (implicit) input amount of leading characters
ยฉ # Store it in variable `ยฎ` (without popping)
ร # Push 0 and the input-integer
ร # Pop both, and push a string with the input amount of 0s
รฌ # Prepend it to the string
2ร # Double the entire string
ล # Pop and push a list of all its permutations
ร # Uniquify this list
```
[Try just step 1 online.](https://tio.run/##AScA2P9vc2FiaWX//0HCo8Kpw47Dl8OsMsOXxZPDmf//Mv8tLW5vLWxhenk)
Step 2: Verify the fifth rule ("*If there is a letter at index `i` in the string, all the letters earlier in the alphabet must occur somewhere at the indices `1..i-1`.*"):
```
ส } # Filter this list of strings by:
รก # Only keep its letters, removing the 0s
ร # Uniquify it
ยฎQ # Check whether it's equal to string `ยฎ` of step 1
```
[Try the first two steps online.](https://tio.run/##ATEAzv9vc2FiaWX//0HCo8Kpw47Dl8OsMsOXxZPDmcqSw6HDmcKuUX3//zL/LS1uby1sYXp5)
Step 3: Verify the second rule ("*It should not contain the same letter twice in a row*"):
```
ส } # Filter it again by:
ร # Connected uniquify its characters
รก # Then remove all 0s again by keeping letters
g; # Pop and push its length, and halve it
Q # Check if halve this length equals the (implicit) input-integer
```
[Try the first three steps online.](https://tio.run/##ATsAxP9vc2FiaWX//0HCo8Kpw47Dl8OsMsOXxZPDmcqSw6HDmcKuUX3KksOUw6FnO1F9//8y/y0tbm8tbGF6eQ)
Step 4: Verify the seventh rule ("*For each zero there must exist a pair of identical letters so that one of the pair is somewhere to its left and one of the pair is somewhere to its right in the string.*"), which implicitly also verifies the third and fourth rules at the same time ("*It must start with the letter `a`.*" and "*It must end with a letter*"), and output the result:
```
ส # Filter it once more:
S # Convert the string to a list of characters
> # Increase all 0s to 1s (and keep the letters unchanged)
ฦถ # Multiply all values by their 1-based index
ยฉ # Store this list as new variable `ยฎ` (without popping)
รพ # Pop and keep just its digits, removing the letters
ฮต # Map over this list of integers:
ยฎ # Push list `ยฎ`
s # Swap so the current integer is at the top
ยก # Split list `ยฎ` by the current integer, leaving a pair of lists
` # Pop and push both lists to the stack
รก # Only keep the letters of the second string
ร # Only keep the letters from the first string that are also in the second
gฤ # Check if what remains is NOT empty
}P # After the map: product to check if all are truthy
# (after which the result is output implicitly)
```
[Answer]
# [Haskell](https://www.haskell.org), 215 bytes
```
import Data.List
f n|c<-"__">>take n['a'..]=[x|x<-permutations$c++(c>>"0"),x!!0=='a',all(\i->not$isInfixOf[i,i]x)c,all((\(f,z:s)->last$(any(>z)$intersect f s):[all(`elem`z:f)['a'..z]|z>'0']).(`splitAt`x))[0..4*n-1]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NZJNaoQwFMfp1lNkRDDpqKRDF-0wCoVuCoUewJHxxSoNo1FMhlqZm3Qzm9IjlfY0NYm6-vn_eCRPP7_fQB7Lur5cvk6qCu9-f3jTtb1Cj6AgeuZSORUS52IXuoeDmyQKjiUSqQ9-FGVxOpyHXdiVfXNSoHgrpFes17hIEpe6JBhWKxrHUzaAusZ7HiaiVR6XT6Liw0uV8oBnAymMi_e4CsatJGFSg1QeBvGBk5F4XKiyl2WhUIUk2aY6nJd12eTjtiL2JGN2HhOf-hmJcC67mqsHlQ-EpDSKbq9FeJNl9np_V_eyrTcoRu9t_yqRC3R6GDCkARi1wCgswMACWGuKWGB0zmgBLMBiTWgAbFiXDDA6t4wAFmCxbEuPmRVtagBb1yVTZ3Sum3mLZepm3qzYuplnFROfwF7adZwGuJh20fXTkpGHxIkhLPXXxxXaEILiGJlXvTPHbnD5Uf4B)
[Answer]
# [Perl 5](https://www.perl.org/), 238 bytes
```
sub{$_=substr(10**$_[0].abcdefghij,1,2*pop)x2;my%r;1while s/^(.*)(.)(.*)(.)(??{$t="$1$4$3$2$'";my%a;$t=~m,(\D).*(0).*\1(??{$a{$-[2]}++;X}),;y|||c!=2*keys%a||$t=~m,(\D)(\1|.*(\D).*\3(??{$1lt$3})),||$r{$t}++;$s{$t}++||''})/$1$4$3$2/;keys%r}
```
[Try it online!](https://tio.run/##VZzBjl5HboXX0VP80bQjtazIpyUPEEhQ7EV2ATKbLAJYjkHSrbETS/K02pgxLM2re/q/VeT55IXdbNZlsVhV5LmH1/3z9c1Pf/z94vXL39//kr9dfPfy7j/vb28eXunRo4vvvtG3TyLr@@vXf/7hx/97fPX46aOf3/18@benL978@tnNi6u//vDjT9en91/878Mnjy4fPrns/3z11W8Xty/vX1xdfHnx7OLpxYP75wfixd0v//7m8cNX/3H55NFD3f3r1dUxNn67@Ndvnn778fPPX/zPx8vHL3798OFD/fPLp4/@//rX95/Fhw9@8OGrqw93Dx8mXj07nr766fbi2cfLy8d3427uJj6buXi/fvjw4cGDj5dftCdfvDgs3nz8/cW91@9uHt473f3zzenq9PLfT3/568OQ4vL07eP966f@tZSRp/MPkVo/pKJ/yFg/xFLdDVk/pPaY8y9i/RCtuvvx@CHW4PNDxw@p/dTxi1g/RKvWU2cz@zdn5fmHWI@fHzoeT@3HD3utOh4/7O3frMcPe@s3x/C7H9aiEY1njMZ5jso6bSGDQsUnQqWFu4EQKrZwN68N3D2tT4QxcJ5Trbnz2c/kMdEI8OAsjIHzNBxmD@7WC2vHrCPAnbNga0F3Spi0hElLmPRsLCxUYFilNYFJKzBpBSc9OzfCOSQQMM95eRZKW3M@AbPs8@bPss@TKCm0B8deeVgJw0oYVvpk2Dh67GJrzudvPEhhG89jIim06cNpDpuIns8xrGEbz6FRUrA1bGOu8zJCwMCxqRA86bFBLeAcHILnwTlY0Q0Lcw5WqK0JeI1zcJxxTOpzcGwP5kk4inNwnP4@B@fb7rgFzsH5ASWF8SBwDnLtfQs4FIfgZ3AojuDKGhyKEoJYQhBLCOIxTVhwEI85rUEQSwhiCUEsIYglBPFw2tYQxBKCWMfeQ4AHFTBd6WcCoapAqM5PCBr4FgzVEewWjusEwV4fV8MCvD42f4TS1hz1og/FUSr6UBzTKylUWkgP86E4Ugie8aFYmYbDeqUr04ymBAMlGCjBQAkGSp8YmFCtHLQ1R8nrlaaQhI4xkRQqLSSH9Uk8qiusOQkdm6OkYGtOQikkoRSSUApJaO9IWAgPcxJagudxEtq7GBYqMKzvz3GK4LWT0MrQmHTuzzoGmCfhqJPQyt1qDZLQgZO8bCShJYwHSEIpJKEjxeMZn7dVCTjMXiMJ5V7RCNiFldchzOJWjh5YCHdWGoPgZ0rBYQ7ISghbQE5cwqwHOXHfsrDgPUVOPBYgWMOeIieudcoa7Cly4qpseAZ7ipy4rzY0AdOTE48QwrfAziEnrkjbQGDnkBNXCrHXicAjJ646aQ@SgXdOPFDxnNFATjweUFJorwM5cdVWCzijgZy4qi6HzUoDOTF3HtwCEuQSxhoS5DqUsiZpwHELJsgSDl8Jh6@Ew7ccCAtz@JY31vjwlXD4Sjh8JRy@Eg7fWo6t@fCVcPhKOHxr1dAETPvwlXD4Sjh8x40RNPANh6@Ew1fC4VuhDgvwGoevhMNXwuGrlQMgJDRYTwnrqYA7lbYWOC4VOC7HE4LGKw0clwoclwoel3UUt7DKK4SJwSqVFhyDVQxGQAzWFWyhtDXrfXdfzfWqu6/mckxJodJCethczQVq8MxczY19OKz81j9Xc2OfEXw1tzDWfDU3KpI1SQMd642KWlOC6RJMl2C6BNMlmC7BdOkT07ONGy8tzeIYdqxTAExrTCSFSgvJYTtTLH4C1gYwrYOjpGBrA5hSAEwpAKYUAFOfibAQHjaAaQueZwBTn6OwUIFhldYEvB7AtNEkJu38tg8i5kk4OoBp40y1xoBpUURetgHTFsYDA6YUANOCo3hmTvxGrRxmrw2YUgBMKQCmFABTCoApBcCUAmBKATD1zQwLwWEOiAHTurPeUwOmfbUDGu@pAVNfemuwpwZMG2tjUuypAVNnDVvDnhow7XwCD0rwoAKmu2YtSA7fAjtnwLSRuw0Eds6AaScxe50IvAHTxvT2IBn4qVmLV5wzCsC0ErySQnsNwLTfAyzgjAIw7TcEDpuVAjClAJjWS4GtOSvvdwcOszVn5f3uYE3a9L7dI/gu7DMCocO7d2jY4YI13IWN6i0Eh82WbOS8hcCyN4CDMNZKsFaCtVLQgDd4Q4clACduoSMKnNjVMCzMnQNOXIsWrPnOASfu2Mga3zngxP2WhGd854ATuwRDEzDtOwecuAX7hjsHnLjfrKDx2QFO7LofFuA17hxw4n7nsqaE9ZSwnhLWMzhxv41Bk7YWuCXAifs9TdB4pYFbApy439OsGYCxQc3EIHEsgRP3G5ysQQwSxxI4cb/Bud3ijBTAiesBJYW90gBO3G99FpyRAjhxvw9yWEcngBP3@@AIyEgBnLjfFDnM1pCRAjhxvym2ZmPDJQA0bqHnAWjcSUPWJA14HoDG/Q45GoDGEpJDCcmhhOSwXQsLnRy2n9ZMcighOZSQHEpIDiUkh71QW5vkUEJyKCE57HhAEzA9yaGE5FBCclgZTdDANyeHEpJDCclhb0JYgNdODiUkhxKSQwnJYe8iNFiPk0MJyaGE5FBCcighOaz8KGi8UiSHEpJDCcmhhORQQnLYxy0sOAZIDiUkhxKSQwnJoYTkULuCQUhoHJ0SolNCdEqITgWWUOl5AhewAhewAhewAhewAhewAhdwZVtrELfgBdzXfgn7JQ5CR3S/kFmYiO5XjhEc0Q30WkBEd8Ldwrr33e7uRLyb1SsRb5eVFCotpId1It6v9XimE3G//XNYueHeibjf/keYRNzCWJtE3LyArEkaKDf2JxE3L9CCE3ELPY8TcTMGsiZpwPM4ETdjMJr0pCVMWsKkJUxawqQlTFrCpCVMWsKkpU8mncPXXMKhWT9tMiEFMmGPiaRQaSE5bFWMdagFa00m7OOupGBrTSakQCakQCakQCbMeQ0L4WFNJrTgeZpMmDMeFiowrNKagNdNJjTTgkl3netLgnkSjjaZ0ByMWjNkwv5gxMseMqGF8WDIhBTIhE3V4Jm@jc3ocJi9HjIhBTIhBTIhBTIhBTIhBTIhBTIhBTJhskZYCA5zQIZM2PnEezpkQqedgMZ7OmTCJCRrsKdDJjQPhUmxp0MmTEazNezpkAmd6@BBCR5UwHSlnwns3JAJzWoJGvgW2LkhEzrB2utE4IdMaL7LHiQD39hlFR@fUZMJuywpKbTXJhOaI7OAM2oyodkzDpuVmkxIgUzYhJmtTcVoXo3DbG0qRvNq1qRNm0xIgUxIgUxIgUxIgUxIgUxIgUxIgUxIgUxIgUxIgUxIgUxIgUyYChoWgsNsbciEFMiEFMiEXXXnzplM6OIc0MydM5kwZdsa3zmTCc0TYlLfOZMJU/dtzXfOZEIjAnjgO2cyoblFP4M7ZzKhWUdBA99w50wmNAyx17hzJhOaj7QHuHMmExrHeD0lrKeE9ZSwngq40@8Lm5z0SgO3xGRCc5iyBisN3BKTCc1hjiZxLE0mNLspaByDxLE0mdDspjWNbhfonYwEMmHDYSWFvVKQCc2IWnBGApnQXCmHdXRAJjRXOgIyEsiEZlE5zNaQkUAmNIvaGmPYTZzOPMawza9y2MxjDNv8qjVJ095TkAk5iGeEyYldNyHsre@qNZ/NFqw5J/ZNtRAc1selT@kWkBOb@YQw1pATm3ccIWhgDl9zbksIBL5JFAg9TwnzlDBPCfOUME8paNqHvF9QDwEsTgt7t8HizHtNWOisDBZnB0qwNlkZLE7HU9ZMVgaL0xwznpmsDBZnXqagCZierAwWpwX75qwMFqd5aWjmXIPFmTe4sACvnZXB4jRjbY2zMlicPlOCButxVgaLs4@eV4qsDBanT6iswUqRlcHiNMs9GmRlsDjNfwsaxwBZGSxO89/W@MCCxZnXYGgcnRKiU0J0hsVpZtya9DyBzAcWpzlzQTNxC2Q@sDjNmVuDuAUyH1icfq3viCZSAFicZtNljSOaSAFgcZpNHw1TgFmc9euugAEWZz@gpLCiE2BxMsDibNIdz0wFDLA4zc3LmrQBV8AAi9PCWHMFDLA4zdpD0/sTYHGatW8BFTDA4jSfz2EzDypggMVpPt@aOQcBFieHuTkEUDotbA9A6XTxkDVJA@MBKJ1m@keTnNQnMUjplFAkSigSJRSJdjos7CLRK7Cmi0QJRaKEIlFCkSihSHQIbK2LRAlFooQi0ZGCJmC6i8QqWfBtisSubIIGvk2RKKFIlFAkenvCAryeIlFCkSihSJRQJHp/ocF6pkiUUCRKKBKrAHqlLhK7Tgoar9RFooQiUUKRKKFIlFAk@iCGBcfARaKEIlFCkSihSJRQJEooEn3GoXF0XCRKKBIlFIkSikQJRWKV04kbisSuuoJm4oYiUUKR2FXXGsQNRaKEIlFCkegLHBYmoigSJRSJEopECUWihCJRQpEooUhUo0YICc3EuoRYlxDrEmJdQqxLiPWuyFtIexBIkBVIkBVIkBVIkBVIkBVIkBVIkBVIkBVIkBVIkBVMkJ2wD6EpcAh7f5rOttD704TtCLM/TZO14P3p19UtYH@6jC9hZ@z9vxA2OZ8COb@FRc6PUGkhOezI8XuZgrVNzncAlBRsbZPzKZDzKZDzKZDzKZDzKZDzO7aC15ucbwFeb3K@hQoMq7Qm4PUm56dzgUlXZepmBRzd5Pz0NPDMqkz7ECBuTc738VBSGA@anE@BnO/WB57ZIGs6JBxmr5ucT4GcT4GcT4GcT4GcT4GcT4GcT4GcT4GcT4GcT4GcT4Gc37cCe9rkfAve0ybnW/CeNjnfd0ywhj1tcn76OrIGe9rk/HR88Az2tMn5EeBBBUxX@pnAzjU5P10iQQPfAjvX5Hw3huB1IvBNzk//yB4kA7/Rxk5HPqNDzneiUlJor4ecn56TBZzRIeenG8Vhs9Ih51Mg57sBZWv9IjB9Kg6ztX4RmD6VNWnTQ86nQM6nQM6nQM6nQM6nQM6nQM6nQM6nQM6nQM6nQM6nQM6nQM6nQM6nQM6nQM6nQM6nQM6nQM7veuM7N@R8C3PnhpxvYe7ckPNdvQRrvnNDzk/fTdb4zg05Px05POM7N@T8CPDAd27I@W7PwTfcuSHnp4tnA7hzQ8534w5e484NOT/9PXuAOzfkfLf0sJ4S1lPCekpYTwXcqbS1wC0Zcn56goLGKw3ckiHnpydoTfnvEww5P8LEIHEsh5yfbiE0iEHyWDbC3zBoMpLJ@QZISgp7pSbnp8NowRnJ5Pz0Hjmso2NyfnqPIyAjmZyfriSH2Royksn56Uq2ZqiJbkTOPENNTL@Sw2aeoSamX2lN0rT31OR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuR8CuT8xvqTlU3Ot9BZ2eR8C52VTc73m4NgbbKyyfnpzMqaycom56dni2cmK5ucHwEeTFY2Od8NXPjmrGxyfvq8NuCsbHK@W7vw2lnZ5Px0gO2Bs7LJ@W76Yj3OyibnpzeMZwLuOCubnB9hVoqsbHJ@usbQYKXIyibnu1HsGCArm5yffrKsQQyQlU3OTz95NCVEp4TolBCdEqJTQnRKiE4FltC8SzeXJ26BzGdyfnrQssZxC2Q@k/PTgx4NMp/J@W47T0QTKcDk/HSnZY0jmkgBJuenOz0apoDhXfbrfldAkPNNBCgprOiAnJ@OtoWpgCDnp9fNYTuiIOen1z2CKyDI@emCc5ituQKCnJ8ueGtQAUHOj9DzoAKCnJ/@ODSeBxUQ5Pz0x7fG5Hy3xNsDk/PTOeew9sDk/HTOrUmatgcm56dz3pq0O8NHjNDVed5qIawDO@@U8weiCtamOg@OthActg/5YMgtuDpPNYEw1lydJ5OOEDTQV2Zu9xJQnadzDaHnQXWevvEIQQOeB9V5uo9b8NWcxsxpPgJuD0rwoAQPSvCgBA9K8KAED0rwoBSc1MlhaNBTf3ncyAEdmxY2ckDHpoWNHNCx6eAK1ho5oGMzeyBrGjmgYzPfFeCZRg7o2IwADxo5oGPT2wvfBjmgYzOnwAYGOaBj058fwOtBDujYzFcK9mCQAzo2fdqwnkEO6NjM9wt4JuDOIAd0bEaYlRo5oGMzXzZAg5UaOaBj0x8zOAZGDujYzDcPsgYxMHJAx2a@eRiNkQM6NnMXBU3iGUTHyAEdm/kaojVADujYzHcSgmbiBuSAjs18J2EN4gbkgI5NfxoxEQVyQMdmvqCQNY4okAM6NvMFxWgCHgA5oGMzQkIzsS4h1iXEuoRYlxDr6djMtxWjSXsQqJro2MxXF4KmdyFQNdGxma8urPEuBKomOjbz1UVrpmPTH1r0/iSSNzo28z2GrJn9SSRvdGzme4zRYH8SyRsdm/kew3@1sTGf/67gCBvzhYD5QsB8/vNpLTTmCwHzhYD5QsB8IWA@/@2XLQzmCwHzhYD5QsB8IWC@EDBfCJjP/3vgEoz5QsB8IWC@EDBfCJgvBMwXAuYLAfOFgPn81cIhAPOFgPlCwHwhYL4QMF8ImC8EzBcC5gsB84WA@ULAfA1Hl1CCb61IC8lh27cSfCvBtxJ8K8G3EnwrwbdS0h3frAaqh6YEUFICKCkBlMxywsICJbM2azYoKQGUlABKSgAlJYCSCY6tbVBSAigpAZRMDKEJmN6gZEMk@NagpJGUoIFvDUpKACUlgJLZuLAArxuUlABKSgAlJYCS2XlosJ4GJSWAkhJAyQZcXumAksZlgsYrHVBSAigpAZSUAEpKACVzRMOCYzCgpARQUgIoKQGUlABKSgAlc/qhcXQGlJQASkoAJSWAkhJAyYZvEzeDkkZ5gmbiZlBSAihplGcN4mZQUgIoKQGUzNUOCxNRg5ISQEkJoKQEUFICKCkBlJQASkoAJZNPoJlYG5SUAEpKACUlgJISQEkJoKQEULLBYO8CQEljRkHTuwBQUgIoacxojXcBoKQEUFICKCkBlJQASibBhoXeH4CSEkBJCaCkBFBSAigpAZSUAEpKACUlgJKa90sICU3vXCeoEWbn@tq24J3r47cF7FwvfAmBUDWAOwuBcliBcliBcliBcliBcliBcliBcliBcliBcliBcliBcliBcljBcjiF@zT/A@3e7fkAx8Le7fnIZYTe7flUooXZ7WnobsG7PU2FJWC3hzQ4hIDXU7mPvyT@h/WnxL/cf0r8/LvTH@rdL29vn5@u/k1XXz47xevb65vTm3c316fbH@Lt6ZlOb358@8vt9ft@@o@fPP1k/XPv8rez9vTm14cXbx9/ff23ny9ffn3x3Yt765df//nd7cv3725uT/9y8fpuxOVS/Hzz49vb1/c/e386vX1@unh7/t1257PvXx3inaXrur3@/vnpbHT97s7Y82O209nuq7f3H9/7p/tn9f3T9V9O98@/vH/66vTgT//54PT89ODRo0f/9af/Pt1Jj0/6/Kx9ce/jvd//AQ "Perl 5 โ Try It Online")
Returns arrays of 1, 28, 1816, 180143 strings for n = 1,2,3,4. Spent more than half an hour for n=4.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 114 bytes
```
.+
*
Y`\_`l
.+
<$&>$&$.&*2*0
/>./+Lrv$`(?(2)(\3.+))<(.+)?([a-z])|(\6.*)<(.+([a-z]).*)(0)\b
$%`$1$4$3$7<$2$5$%'
<>
```
[Try it online!](https://tio.run/##LYjNCsIwEAbv@xxf426C2zb15xLSF/AFxIhpwYMgHop4EN89BvEyzMxyfd4eU1@KOrJ0zOmS71Q9wEQYqLHedtRGbd1heSHzyF44DepEAleOfJrW77N8OO3U/t7/1OJO0kxoMnpsMGAf4LFFs6IQqRT/BQ "Retina โ Try It Online") Explanation: Based on my answer to [Iterate over all non-equivalent strings](https://codegolf.stackexchange.com/q/264102/).
```
.+
*
Y`\_`l
```
Generate the first `n` lowercase letters.
```
.+
<$&>$&$.&*2*0
```
Make a duplicate set, wrap the first set in `<` and `>`, and also append `2n` `0`s to the second set.
```
Lrv$`(?(2)(\3.+))<(.+)?([a-z])|(\6.*)<(.+([a-z]).*)(0)\b
$%`$1$4$3$7<$2$5$%'
```
For each string, make new strings by either a) moving the first letter from the first set or b) moving a letter from the second set that was moved from the first set but not in the immediately previous iteration c) moving the last zero, if there is a letter still in the second set that was moved from the first set.
```
/>./+`
```
Repeat until the second set is empty for all strings.
```
<>
```
Remove the `<>` markers.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 35 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
รaแธฃx2;ล!แธQแนขฦษฦษJ$โผฦรแนแนฃโฑฎf/ฦฦยฅฦแธคOnaฦQ
```
A monadic Link that accepts \$n\$ and yields a list of lists of characters.
**[Try it online!](https://tio.run/##AU4Asf9qZWxsef//w5hh4bijeDI7xZIh4bifUeG5osaRyZfGh8mXSiTigbzGncOQ4bmC4bmj4rGuZi/Gh8aRwqXGh@G4pE9uYcaKUf/Dh1n//zI "Jelly โ Try It Online")** (Will time out for anything above two though!)
### How?
Constructs all strings fulfilling the conditions with natural numbers in the place of zeros by filtering all permutations of the letters and numbers that, when deduplicated have their letters in order, maps the numbers back to zeros, and then deduplicates.
```
รaแธฃx2;ล!แธQแนขฦษฦษJ$โผฦรแนแนฃโฑฎf/ฦฦยฅฦแธคOnaฦQ - Link: n
รa - alphabet
แธฃ - head to {n}
x2 - times two -> "aabb..."
$ - last two links as a monad f(Letters):
J - indices -> [1..2n]
ษ - last three links as a dyad - f(Letters, Indices)
; - {Letters} concatenate {Indices} -> e.g. ['a','a','b','b',1,2,3,4]
ล! - all permutations
ฦ - keep those {Permuations} for which:
ษ - last three links as a dyad - f(Permutation, indices)
แธ - {Permutation} filter-discard {indices}
Q - deduplicate
ฦ - is invariant under:
แนข - sort
รแน - keep those {Alphabet-Increaing-Permutations} minimal under:
ฦ - for neighbouring pairs:
โผ - equal?
ฦ - keep those {Alphabet-Increasing-Adjacency-Different-Permutations} for which:
ยฅ แธค - last two links as a dyad - f(Permutation, 2n):
โฑฎ - map across {i in [1..2n]} with:
แนฃ - split {Permutation} at occurrence of {i}
ฦ - is that list of Splits invariant under?:
ฦ - filter keep {Splits} for which:
/ - reduce {Split=[L,R]} by:
f - {L} filter keep {R}
ฦ - last three links as a monad - f(Valid-Permutations):
O - cast {ValidPermutations} to ordinals (a no-op for integers) -> Ords
n - {Ords} not equal {ValidPermutations} (vectorises) -> Mask
a - {Mask} logical AND {ValidPermutations} (vectorises)
Q - deduplicate
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 148 bytes
```
n=>(g=(i,j,t,s=[])=>s.map(_=>g(i,j,t+_,s.filter(r=>r!=_)),s+s&&j&&g(i,j-1,t+0,s),i<n?g(i+1,j,t+(c='abcde'[i]),[...s,c]):j||s+s||print(t)))(0,2*n,'')
```
[Try it online!](https://tio.run/##TYzBToQwEIbvPkVNDMzY2WbRi3F38EEIYbECKcFCOs1eln12rHjx9CXffP@M7bUVG9wSD9e3refNcwkDg6ORIglXNXIp5rtdoOFy@PO6ITG9m2IXIHAZHrlBJNGSZWOW7dGhSNmRBMmd/UdSutiXYDlvP@1Xl1euRqqMMUK2xvdxXdODdV2C8xEiIsKRXp495Tlu/Rxg6qLyilVxSjizek3UGtXtQSk7e5mnzkzzAJff6Onm7xc8pVMPfuf/JIn79gM "JavaScript (V8) โ Try It Online")
As comparison to the 139 one
] |
[Question]
[
To celebrate the island's next Founder's Day, colored filters (fuchsia, chartreuse, and aquamarine\*) have been installed in every lighthouse. All lighthouses begin operation with their fuchsia filter, and they are all on the same color cycle: FCA, FCA, ... Each lighthouse changes its color filter *after every ON blink,* whether long or short. In addition, each starts the cycle anew with fuchsia each time its code begins.
Other than the addition of color, lighthouse operation is identical to that in the original challenge, [**Blinking Lighthouses**](https://codegolf.stackexchange.com/questions/231261/blinking-lighthouses).
**Challenge:**
Input is identical to the original challenge: the codes for each of n lighthouses in the form of strings of (only) L's and S's.
Output now consists of *four* lines, one line per color, plus a "totals" line. The top line has the total times that 0...n fuchsia lights were simultaneously on; the second line chartreuse; and the third line aquamarine. Thus the third number in the second line is the total seconds that exactly two chartreuse lights were simultaneously on *regardless of what other colors were on during those seconds*. The fourth line has the totals for 0...n lights simultaneously on regardless of color (this line is identical to the output of the original challenge).
***Unfortunately***, Chief of Lighthouse Operations Marie Lumenix has reported a glitch during filter testing. For some reason, if *all* lighthouses have simultaneously blinked aquamarine at the same time for a *total* of 5 seconds after the start of operation (the last item in line 3 of output), the electronic color filter system *immediately* fails and all lighthouses continue their schedules for the rest of the hour blinking white. This glitch will not affect the last, "totals", line of output, but may affect the first three rows, *which each total the number of seconds only for the period that filters were working*.\*\*
**Rules**
The rules are otherwise the same as in the original challenge. Shortest code in bytes wins.
*Just for clarification*: the first number in the last row is the total seconds that all lighthouses were off regardless of color. The last row should sum to 3600 sec as in the original challenge, or 1 hr of lighthouse operation. The sums for each row, 1 to 3, should match, whether or not they each total 3600. *These three rows stop counting after a glitch.*
**Test Cases for the broken system**
```
(Input -> Output)
['SLS', 'SLL', 'SSS', 'LSL'] ->
[1178, 360, 90, 40, 5]
[998, 470, 165, 40, 0]
[1178, 165, 270, 55, 5]
[1125, 890, 652, 590, 343]
['SLS', 'LLS', 'SSSL'] ->
[2121, 1158, 288, 33]
[2155, 1219, 226, 0]
[2957, 579, 64, 0]
[1254, 1125, 577, 644]
(The color schedules, in seconds, for the 3 lighthouses in test case #2 case are:
F-CCC-A------- [repeat]
FFF-CCC-A------- [repeat]
F-CCC-A-FFF------- [repeat]
each lighthouse begins the FCA color cycle anew each time its code repeats.)
['SSSLLLSSS', 'LLSSSLLSSLS', 'LSLSLL', 'SSLLL', 'SLLSSSL'] ->
[1334, 1115, 548, 223, 57, 8]
[1560, 1047, 463, 163, 44, 8]
[1591, 950, 525, 184, 30, 5]
[484, 653, 657, 553, 553, 700]
```
---
\*The colors of Lighthouse Island's flag, chosen by a referendum held at Aloisius' Tavern and Gift Shop.
\*\*Marie feels absolutely terrible about this and promises to get things shipshape by Founder's Day.
[Answer]
# [J](http://jsoftware.com/), 129 bytes
```
<@(0,#\)(<:@(#/.~@,+/))&>[:(<@(+/),~]<@({.&.|:"2)~[:{:5{.!._[:>:@I.*/@{:)1 2 3=/(3600$(6$0),~&;[:(*&.>1 2 3$~$)19<@#:@|14+3&u:)&>
```
[Try it online!](https://tio.run/##bVBNa9tAEL3rV0xio5USWd5Pybt1jKBQKOype1RFDCWh7aWXFgoO/uvum5Wc5NDDzs68Nzvv7fy8@JtgeppI0iOf4rYVz/QQSFCDOuBsWvr4JX667IdKNquvdbUPQ7Xatuehud/WdXkYQwUOeXOekJzasn0Jt7o@j@EU3Km9aR/HcAjD5/ZuO5xCrUiTedhWppNyXXVriYflB0y5K9tDJtfnda38fliF4UXZe1P@CdC51MXTt@@/6JlSTMcU4zGldIwpzrDYbMT7hshN6b8sULAp93Cecj9Cnhk5zkzx9PfHbyGKUYAUDeGK@Uq5wgMx0eZQEBWjUv2uIXyqIY9jcdxUjN4DtT0q1bkZltO1O0OaSefmdqU0sh1P6JwGxpmxZiKIQObNSlwcpTcTbEMrrTBYOYzXO3bEbwGzAjgPWHdsglHvemj0ADu7YDBgeQD7cH3PjAWela@LW/Svu1t28bqcuCRzy@wOg43JgxUPtmxPG5bAd7Ou49UpaQHYzvByEKx9pT3@5R3viq2pHRiTlwzWctU5w4F/xFkOvZTT5R8 "J โ Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 52 bytes
Based on [my answer](https://codegolf.stackexchange.com/a/231265/64121) to the previous challenge.
```
ฮตโฌC9%ร
10.รฝห7ร
0ยซDฮท_O3%>*60nโ}รธร3QP.ยฅ5โนร3LฮดQรธs<dยชฮตOZรยข
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3NZHTWucLVUPtxoa6B3ee3qO@eFWg0OrXc5tj/c3VrXTMjPIe9TRW3t4x@EJxoEBeoeWmj5q2Hm439jn3JbAwzuKbVIOrTq31T/q8NxDi/7HHtr9P1opODjYx8cHSCrpKCiBGSDCB8IF0j4@IBZYEZgBUaIU@19XNy9fNyexqhIA "05AB1E โ Try It Online")
```
ฮตโฌC9%ร
10.รฝห7ร
0ยซ 60nโ} # see my previous answer
Dฮท # push all prefixes of the signal
_O # count the number of 0's (how often the signal was off)
3%> # modulo 3, add 1
* # multiply each value in the signal list (0 or 1) with this
# this replaces all 1's with the correct color: (1=F, 2=C, 3=A)
รธร # tranpose the list (n ร 3600 -> 3600 ร n) and push the result three times
3QP # on the first copy, check for each second if all lighthouses are aquamarine
.ยฅ # take the sums of prefixes of this list,
# this keeps track of how many times all lighthouses were aquamarine so far
5โน # for each second: is this value less than 5?
ร # take the lighthouse for all seconds where this was true
3L # push the range [1, 2, 3]
ฮดQรธ # for each of those numbers (colors) compare the lighthouse colors to it
s<dยช # append a boolean matrix of activations in any color (>0)
ฮต # for each of those 4 boolean matrices:
O # sum each row / second
Zร # get the range [0 .. maximum]
ยข # and count all these values
```
The first half of this can be used to visualize the color pattern: [Try it online!](https://tio.run/##yy9OTMpM/f//3NZHTWucLVUPtxoa6B3ee3qO@eFWg0OrXc5tj/c3VrXT8nzU0VurpODm7KhUfHiF16Hd//9HKwX7BCvpKCj5QKjg4GAfpVguQwOD/7q6efm6OYlVlQA "05AB1E โ Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 55 bytes
```
ลปIยป0รโ%3โร
ร0ลแปลปแนร<5a
O%9รแนฌ;รแปตยฌรแนโฝยฝc)Zฤรพ3Sแนญ$=รพ@Lลป$แนชแนญรฦยง
```
[Try it online!](https://tio.run/##PYw9C4JAHMZ3P4WDIoGBIQ1hRWt00HBThUNES/gF2iwEoaYIyqDmIGxsOI4U/Gvf4@6LXNeLTs/bj2cx97ylEAXtZ9SCgPsn3eZ@BEcFIqvYM7otKCMHCNrNqTLUWxAwEjsQMfrIYtgxsuKrZ/ac1cb5FhIbM3LXOpD0UEE1Rm4yQvjaZFfRyFNl4HD/rNa7Kvcvjp2njCSaAiFfxyMhJhMDI2yYqhT0FfxNCCPDNdVqRX8IV710ssTl@om4hKWWb@hvfojhum8 "Jelly โ Try It Online")
A full program taking a list of strings and printing a list of lists of integers.
The first part (converting from Ss and Ls to the sequence dir each lighthouse was derived from [@JonathanAllanโs answer to the previous challenge](https://codegolf.stackexchange.com/a/231267/42248).
## Explanation
## Helper link 1
Convert a list of 0s and 1s to a list of 0s, 1s, 2s and 3s
```
ลป | Prepend 0
I | Increments
ยป0 | Max of 0 and this (i.e. replace -1 with 0)
ร | Cumulative sum
โ | Add 1
%3 | Mod 3
โ | Subtract 1
ร | Times the input
```
## Helper link 2
Replace all of the values in the lists of F, C and A with 0 once the last list of the list list provided as the argument.
Argument referred to as x.
```
ร0ลแป | x[0][0]
ลป | Prepend 0
แน | Remove last item
ร | Cumulative sum
<5 | Less than 5
a | Logical and with x (vectorises)
```
## Main link
```
) | For each lighthouse list:
O | - Convert each character to UTF8 codepoints
%9 | - Mod 9
ร | - Cumulative sum
แนฌ | - Untruthy
;รแปต | - Append "aeiouy"
ยฌ | - Logical not
ร | - Call helper link 1
แนโฝยฝc | - Mould to 3600
Z | Transpose
ฤรพ3 | Outer function using count and the numbers [1,2,3]
$ | Following as a monad:
S | - Sum (because of vectorisation, will add the F, C and A values together)
แนญ | - Tag onto the end of the F,C,A list
=รพ@Lลป$ | Outer function using equals (with arguments reversed) and using [0,1,..,n] as the right argument
ฦ | Following as a monad:
แนช | - Tail
แนญ | - Tag onto:
ร | - Result of calling helper link 2 on the remaining lists
ยง | Sum of innermost lists
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~203~~ 200 bytes
```
E=enumerate
l=input()
t=eval(`[[0]*-~len(l)]*4`)
for i in range(3600):
for y,q in E(t):q[sum(y==((sum([~ord(w)%5*[j%3]+[3]for j,w in E(c)],[])+[3]*6)*450)[i]for c in l)^0-y/3]+=y*y|5>t[2][-1]
print t
```
[Try it online!](https://tio.run/##TVBLb4MgAL7zK7g0PKaZa2sPJuzWmzd2Iyw1jq40iJbhnMnSv@7Ex9IL35sQmt5farsduos2Cr65VmVQ/agSIoSGI1O2rZQrvAKGadu0HhPgmfouDD4JkUga342y2BBJ9ycCzrWDGmoLXWE/Fd4dkoRkAAa7j24hOGJPspv4aivcM4ZxIOJeuw/ckU1KxXWzk09iJ8PkGnXzpCQyEpIEnx4I3acJEXqqlKFgyHsS98/jkPW0/01fvdhKEb9I0DhtPfTD2dUVbGalq6Z2flFgOScYnwYe3fAFAvGcowiOkE/AJ5XzHEnwH@ZLh6/2SEaPr2GQfO2OuN6VL2SuIPkH "Python 2 โ Try It Online")
Building the pattern with strings instead of lists of digits comes out at the same length and is a bit faster: [Try it online!](https://tio.run/##TZA7b4MwFIV3/wovkR9AS0PIgES3bGxms1wRUUcxAkNcU2qpyl9PeVZZfO4537mW5c7Za6v3j@Gqaglz08sEyh9ZQoTQ45RK3TfSnK0Edap011tMgE3l97nGBeehoMG9lhrXRNBDQcClNVD5OVQanjCKEI2OYUgSACfg/NsCLElu/KtvcOGKNMUYoZeqVRrfW/OJB7KLaVHtosLL57XKH5a1khAvp0dCD3FIuBITLCdUk48wcK@R8FJH3W/8bvle8OBNgM4obaF9XEzbwG5xqulaY1cH1nOW8WHgOZ2@gCOWMeTDUbJZ2OwyliEB/mG2dtgWj8OYsQ1Olm3dUbe7snVYKkj8AQ "Python 2 โ Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 51 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
แบ&/ร<5Sโx3ษBSZแธแธฃ"
O%9แนฌโฌ;รแปตยฌa"โยตยฆยคโแน$+โดFแนโฝยฝc)รฤโฑฎโฌLลป$
```
A monadic Link that accepts the list of patterns and yields the list of lists of counts.
**[Try it online!](https://tio.run/##y0rNyan8///hrklq@odbbEyDHzXMqDA@OdkpOOrhjq6HOxYrcfmrWj7cueZR0xrrwzMe7t56aE2i0qOGOYe2Hlp2aAlQ9cOdjSrajxq3uAEZjxr3HtqbrHm4/Uj3o43rgFp8ju5W@f//f7R6cHCwj48PkFTXUVAHM0CED4QLpH18QCywIjADokQ9FgA "Jelly โ Try It Online")**
### How?
```
แบ&/ร<5Sโx3ษBSZแธแธฃ" - Link 1: list of lists of colours at each second, L
where F=25, C=21, A=19, and off=16
แบ - is prime? (i.e. is Aquamarine?)
/ - reduce using:
& - bitwise AND -> 1 if all Aquamarine else 0
ร - cumulative sums
<5 - less than five?
S - sum
โ - increment -> second, s, when filtering breaks (or 3601)
x3 - repeat (that) three times -> [s,s,s]
ษ - new dyadic chain, f(L, [s,s,s]):
B - convert (L) to binary i.e. each number -> [1, F?, C?, A?, on?]
S - sum columns
Z - transpose
แธ - dequeue (discard the leading-bit result)
" - (that) zip ([s,s,s]) with:
แธฃ - head to index (this leaves the fourth list intact)
O%9แนฌโฌ;รแปตยฌa"โยตยฆยคโแน$+โดFแนโฝยฝc)รฤโฑฎโฌLลป$ - Main Link: list of patterns
) - for each pattern:
O%9แนฌโฌ - convert 'S' to [0,1] and 'L' t [0,0,0,1]
;รแปต - concatenate "aeiouy"
ยฌ - logical NOT -> unflattend on/off seconds, U
$ - last two links as a monad, f(pattern):
โยตยฆยคโ - [9,5,3]
แน - mould like (patten) - e.g. 'SLSS' -> [9,5,3,9]
" - (U) zip (that) with:
a - logical AND -> 1s become 9 (F), 5 (C), or 3 (A)
+โด - add 16 -> 25 (F), 21 (C), 19 (A), or 16 (off)
F - flatten
แนโฝยฝc - mould like [1..3600]
ร - call last Link (Link 1) as a monad, f(that)
$ - last two links as a monad, f(patterns):
L - length
ลป - zero-range -> [0..length(patterns)]
ฤโฑฎโฌ - for each map with count occurrences
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~282~~ ~~276~~ 241 bytes
I managed to get the byte count under 300, I'm quite happy with that :).
**Edit:**
*-6 bytes thanks to @ovs:* rewritten ternary `if ... else`.
*-10 bytes:* `m.append` replaced by `+=[]`, and including the `x+=`. `range(4)` replaced by a list of 4 elemensts.
*-15 bytes:* shortened the creation of list `m` of translated codes: `m` built with list comprehension, string built with `join`.
*-10 bytes:* the creation of translated list `m` is moved directly into the loop of counter. Used 2 variables to unpack the `zip`.
```
def f(h):
t=[[0]*-~len(h)for i in[0]*4]
for i in range(3600):
for n in'0123'[3*(t[2][-1]>4):]:t[int(n)][[c[i]for c in[(''.join(q*(p>'L'or 3)+'3'for p,q in zip(w,'012'*len(w)))+'3'*6)*450 for w in h]].count(n)]+=1
print(t[:3],t[3][::-1])
```
[Try it online!](https://tio.run/##TY4xbsMwDEV3n0IbJcUJ7MjNICA5gTaNBIfCtRsFhewYKox26NVd0YmBTCT/f@Tn@JOuQzTL8tH1opdXZQuRzogV6f3fVxez0g@TCCJE1hoqxDaL6T1@dtKcqoq3Vj1mHar6aACNlgmPhPuaLo2yZBOGmGRUhNhiIMZbPisBDrchRHnXcryAg2wYtQMDjIzlnbN@wyjnkk@D5rdmpVZEn5Ru3qo1fGbwSnRoh@9H0u5cF2KcODehNVQmNITW5p/U0ksE7zyUIhe3Fr9OzjsgVbz47on5Fyf3Wfabz6Pf8Fy3i@7ZPJC8vfwD "Python 3 โ Try It Online")
---
***Original code explanation** (at least I tried to explain)*
* `def f(h):`
Function definition, takes as input the list with the lighthouses' codes.
* `m,t=[],[[0]*-~len(h)for i in range(4)]`
Initialize the empty list `m` that will contain the translated codes.
Initialize the list of counters: 4 lists (1 for each color and 1 for the total), each with n+1 lighthouses elements.
* `for w in h:`
Loop on the code of each lighthouse to translate into color codes.
* `x=''`
Initialize empty string for the translated code.
* `for q in zip(w,'012'*len(w)):x+=q[1]*(1if q[0]>'L'else 3)+'3'`
Translate the `'SL'` sequences into color codes and the corresponding duration.
`zip(w,'012'*len(w))` zips the the `'SL'` code with the corresponding repeated color sequence ('0'=F, '1'=C, '2'=A).
For each `'S'`, `'L'`: replace with the color code (repeated for the seconds of short or long duration) and the off separation period ('3'=OFF); `x += lenght of color + 1s off`
* `x+='3'*6;m.append(x*450)`
Add the long off period (6s since 1s is already present) and extend the translated sequence for at least 1h.
* `for i in range(3600):`
Loop for 1h: for each second...
* `for n in'0123'[3*(t[2][-1]>4):]:t[int(n)][[c[i]for c in m].count(n)]+=1`
For each color and for the off (`in '0123'`)...
`'0123'[3*(t[2][-1]>4):]` count only the off periods (indexed last item of the string) if we get 5s of color A on all lighthouses at the same time.
`[c[i]for c in m]` status of each lighthouse at second *i*.
`count(n)` gives how many lighthouses have that status `n`; the count corresponds to the index in the list of the corresponding status; and increment the counter.
To summarize: `t[index of color][index of how many are ON] += 1`
* `print(t[:3],t[3][::-1])`
Print the counter for the colors and the total ON period: this list must be reversed since in the previous step we counted the OFF periods.
] |
[Question]
[
Inspired by: [Find an Unrelated Number](https://codegolf.stackexchange.com/q/122442/38183)
---
## Challenge
Given two positive integers as input, output the mathematical operations that can be used on those inputs to generate every number from `1` to `n` inclusive where `n` is the smallest prime greater than the sum of the two inputs. If the number cannot be generated using the list of mathematical operations below, the output for that number should indicate that it is "unrelated".
For example, for the inputs `2` and `3`, `n=7` so one valid output would be
`Subtraction, Modulus, Bitwise OR, Unrelated, Addition, Multiplication, Unrelated`
(see Output section below for clarification on valid outputs)
(If [Erik the Outgolfer's answer](https://codegolf.stackexchange.com/a/122445/38183) is valid, the last term will always be `unrelated`.)
Operations that must be considered are:
```
Addition (a + b)
Subtraction (a - b) and (b - a)
Multiplication (a * b)
Division (a / b) and (b / a)
Modulus (a % b) and (b % a)
Bitwise OR (a | b)
Bitwise XOR (a ^ b)
Bitwise AND (a & b)
```
In cases where an operation would lead to a non-integer (such as `2/3`), always floor. So `2/3=0` and `3/2=1`.
Exponentiation is not included because it is never *required*. `a**b` and `b**a` will always be larger than `2(a+b)-2` (which is ([probably](https://en.wikipedia.org/wiki/Bertrand%27s_postulate)) the largest possible `n`) *except* for the cases `a=1|b=1` or `a=b=2`. The cases `a=b=1` and `a=b=2` have valid solutions that do not use exponents: `*` and `/|U+U`, respectively. For the rest of the cases where `a=1,b>1`, `a**b=1` which can also be found with `a%b` and `b**a=b` which can also be found with `b*a`.
Concatenation is not included because [it was shown](https://codegolf.stackexchange.com/questions/122582/#comment300709_122582) to always be larger than `n`.
## Input
2 positive integers.
[Standard I/O methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) are accepted. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
You can assume the input will always be within a valid range for your given language.
## Output
A list or array of the mathematical operations that can be used with the inputs to generate every number from `1` to `n` inclusive where `n` is the smallest prime larger than the sum of the two inputs. (You do not need to output the value of `n`.)
Output can be in any format valid for your language so long as it is clearly understood. For instance, it can be an array where each value is a separate operation, a string with a delimiter between each value, or even just a solid string where each character is a different value.
You can use any character(s) so long as each possible result has a unique representation. For instance, `+-*/%|^&U` will work and so will `123456789`, `UNRELATID`, and `CODEgolf!`. You are advised to include a legend or explanation of how the output can be read.
If more than one operation can be used to generate a given number, you may output any one of them. Do not output all of them.
## Testcases
```
Input | n | Example Valid Output
-----------------------------------------
2, 3 | 7 | Subtraction, Modulus, Bitwise OR, Unrelated, Addition, Multiplication, Unrelated
2, 3 | 7 | -%|U+*U
2, 3 | 7 | 2579139
1, 1 | 3 | [*,+,U]
6, 6 | 13 | ["/","U","U","U","U","&","U","U","U","U","U","+","U"]
6,12 | 19 | U/U&U-UUU^UUU|UUU+U
12,6 | 19 | U/U&U-UUU^UUU|UUU+U
7,11 | 19 | /U&-UU%UUUU^UU|UU+U
7,15 | 23 | %/UUUU%-UUUUUU|UUUUUU+U (2nd value is a floor divide)
```
(I can easily add more test cases if someone finds an interesting one.)
I *think* the test case outputs are all valid but I've been known to mistakes. Please tell me if you spot one.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes wins!
[Answer]
# JavaScript (ES6), 134 bytes
```
(a,b)=>eval("for(t=a+b,i=0;i=i<t;)for(++t;t%++i;);for(q=n='';n++<t;)[...'+-*/%^&|>'].every(o=>n^eval(a+(p=o)+b)&&n^eval(b+o+a)),q+=p")
```
Using the standard symbols for operations in JavaScript, except for `unrelated` that is `>`
*Less golfed*
```
(a,b)=>
{
// find the smallest prime greater than the sum of a and b
for (t = a + b, i = 0; i < t; )
for(i=1, ++t; t % ++i; );
// loop from 1 to t
// accumulate output in q
for(q='', n = 0; n++ < t; )
{
// try all binary operators
// to avoid error in 'eval', I need a binary operator for 'unrelated', so I choose '>'
[...'+-*/%^&|>'].every( // every terminates early if the result is false
o => (
p = o,
n ^ eval(a+o+b) && n ^ eval(b+o+a)
)
// using xor to check for equality, the result is cast to integer
// eventually flooring the division result
)
q += p
}
return q
}
```
**Test**
```
F=
(a,b)=>eval("for(t=a+b,i=0;i=i<t;)for(++t;t%++i;);for(q=n='';n++<t;)[...'+-*/%^&|>'].every(o=>n^eval(a+(p=o)+b)&&n^eval(b+o+a)),q+=p")
console.log(2,3,F(2,3))
console.log(1,1,F(1,1))
console.log(6,6,F(6,6))
console.log(6,12,F(6,12))
console.log(7,15,F(7,15))
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~131~~ 129+7 = ~~138~~ 135 bytes
Uses the `-rprime` flag.
`C` for concatenation and `U` for unrelated.
```
->a,b{(1..Prime.find{|i|i>a+b}).map{|i|("C+-*/%|^&".chars+["**",""]).find{|o|o.tr!?C,'';eval([a,b]*o)==i||eval([b,a]*o)==i}||?U}}
```
[Try it online!](https://tio.run/nexus/ruby#LYxLDoIwAET3nKLUD1BKDRjDwgALLuDGFaIpCNIEhBTUGNqzIyCbSd7LzKxU/kq@wOINZ1Wm5N5lsHyKk163CTlNjuTsee8FE8ynZiINUtFmQh2GpoV2G3HdQpIWlLdmBBGCGMLYWEa1qEnH1SDEmnbM3rTUo/E7RrXheUyIv0kwXYwUIjhLOTQgJyktS4DmxvpmgE/Bygw8sq4dIgfvYyWy8WFOe0wX2zM42I1/ "Ruby โ TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 37 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
โพรฐษ;@โฌโโน;โฌโ+แบกรd|^&โjโ,ยคvโฌโธF
+รni@โฌยข%8
```
**[Try it online!](https://tio.run/nexus/jelly#@/@ocd/hDScnWzs8alrzqGHuo8ad1mDWHO34w9NTauLUgIJZQKxzaEkZSKJxhxuX9uG2vEyQhkOLVC3@H17@cHc3VI@ulr4qUE8oUMP//@b/DU0B)** (footer formats the output from the native list of numbers to print a representation using the operation symbols from the question)
### How?
Ignores checking of string concatenation and exponentiation as they are unnecessary.
Creates two (similar) links of Jelly code and evaluates them to evaluate to find the values of applying each of the **9** dyadic operations with the arguments in both orders. Flattens this into a single list and finds the index at which each value in the range `[1,p]` is first found, or **0**. Takes the result modulo **8** to collapse the two values for each of reversed subtraction, reversed `div` and reversed `mod` to a single values.
```
โพรฐษ;@โฌโโน;โฌโ+_รd|^&โjโ,ยคvโฌโธF - Link 1: evaluate all operations: number a, number b
โพรฐษ - literal "รฐษ"
โโน - literal 'โน'
;@โฌ - concatenate for โฌach -> ["โนรฐ","โนษ"]
ยค - nilad followed by link(s) as a nilad:
โ+_รd|^&โ - literal "+_รd|^&"
โ, - literal ','
j - join -> "+,_,ร,d,|,^,&"
;โฌ - concatenate for โฌach -> ["โนรฐ+,_,ร,d,|,^,&","โนษ+,_,ร,d,|,^,&"]
โธ - link's left argument, a
vโฌ - evaluate โฌach with argument a:
- 1 โนรฐ+,_,ร,d,|,^,&
- โน - right argument, b
- รฐ - dyadic chain separation
- , , , , , , - pair results (yields a list like [[[[[[a+b,aแบกb],aรb],adb],a|b],a^b],a&b])
- + - addition
- _ - subtraction
- ร - multiplication
- d - divmod (returns a pair of values)
- | - bitwise-or
- ^ - bitwise-xor
- & - bitwise-and
-
- 2 โนษ+,_,ร,d,|,^,& - just like above except:
- ษ - dyadic chain separation
- - ...with argument reversal
-
F - flatten the two into one list
+รni@โฌยข%8 - Main link: number a, number b
+ - addition -> a+b
รn - next prime
ยข - call last link (1) as a dyad -> Link(1)(a, b) = [b+a,b-a,b*a,b/a,b%a,b|a,b^a,b&a,a+b,a-b,a*b,a/b,a%b,a|b,a^b,a&b]
i@โฌ - first index for โฌach (e.g. if a=8, b=3 and n=5 the first index of 5 is 10, a-b)
%8 - modulo 8 (... 10%8 = 2, aligning with b-a. Same goes for / and %)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~52~~ ~~49~~ 35 bytes
```
:;%;แบก;+;ร;|;^;&;:@;%@
ยณรงi
+รnRรง@โฌ%8
```
[Try it online!](https://tio.run/nexus/jelly#M7BSCM0rSs1JLElN4TK0UnDJLMsszszP4zKyUvDNTynNKS3mMrZSCC5NKilKTC4ByZhYKTimpGSC2aZAVaU5JZkFOZnJiWARMysFp8yS8sziVAX/IC5zBC8CyLVAcB39XP5bWataP9y10Frb@vB06xrrOGs1aysHa1UHrkObDy/P5NI@3JYXdHi5w6OmNaoW/w8vf7i7@1HDHH3VOG0t3Zo4tdBHDXP//zf/b2gKAA "Jelly โ TIO Nexus")
**Explanation**
```
:;%;แบก;+;ร;|;^;&;:@;%@ - helper link 0, finds related numbers
:;%;แบก;+;ร;|;^;&;:@;%@ - just lists all of the operations, separated by
`;` which appends each result to the previous
results. Uses `@` to reverse args on : and %
ยณรงi - helper link 1, saves a byte in control flow
รง - helper link 0, called on
ยณ - first program input and
(implicit) second program input
i - find the index of the input whole number in
the output list from helper link 0
+รnRรง@โฌ%8
+รn - find the nearest prime greater than the sum
R - all whole numbers less than or equal to the prime
รง@โฌ - for each whole number, call helper link 1
with first argument second program input and
second argument the whole number
%8 - modulo 8 each index: Maps the reversed argument
functions to the non-reversed functions
```
[Answer]
# [Haskell](https://haskell.org), ~~163~~ 162 bytes
```
import Data.Bits
f a b=[last$0:[n|(n,(#))<-zip[1..][(+),(-),(*),div,mod,(^),(.|.),(.&.),xor],a#b==c||b#a==c]|c<-[1..head[p|p<-[a+b+1..],all((>0).mod p)[2..p-1]]]]
```
Output is given as a list of integers, which correspond to operations as follows:
0 = Unrelated
1 = Addition
2 = Subtraction
3 = Multiplication
4 = Division
5 = Modulo
6 = Exponentiation
7 = Bitwise OR
8 = Bitwise AND
9 = Bitwise XOR
It will never output concatenation, since I've [proven that it will never occur](https://pastebin.com/EsR9AXNr).
-1 byte by replacing `/=` with `>` in the primality test.
[Answer]
# Python 2, ~~175~~ ~~173~~ 172 bytes
This doesn't handle exponentiation or concatenation, because I don't think there will ever be a case where they are necessary. ``a`+`b`` should always be greater than `n`. Same with `a**b`. If someone proves this one way or another, let me know.
```
a,b=input()
n=a+b+1
while 0 in[n%m for m in range(2,n)]:n+=1
for i in range(n):
for o in'+-*/%|^&':
x='a'+o+'b==i+1'
if eval(x)+eval(x[::-1]):print o;break
else:print 0
```
[**Try it online**](https://tio.run/nexus/python2#RY5BDoIwFETX/FM0JNjWlmgxYVHSkxBMiinaCB8CqCy8OyKSuJhMZt4sZjBhGM5WlsZj9xgZBzRWlELB6@ZrR47EY45RQ6q2J80SSG/x6lgikRcahVHwJf5PkGtY1@3SURHvD9H7vKMagslQS0UraGmMF4pC4CvinrZmExc/z7WOVcF113scSZuVvbN3IK4e3NYd5@Xwdk5pN7kLG3i2sjmRJ1BSQSrTRSr5AA)
Prints the operator for a solution, or `0` if unrelated.
[Answer]
## JS (ES6), ~~249~~ ~~194~~ 188 bytes
```
(a,b)=>{
p=n=>{for(i=n;n%--i;);return i-1}; // return 0 if n is prime, non-zero otherwise
for(n=a-~b;p(n);)n++; // increment n until it is prime
for(z=Array(n).fill(0), // set all to 'unrelated' (0) and ...
o="+-*/%|^&",c=0;h=o[c];c++) // loop through the various operators
for(v="ab",q=2;q--;) // try both a?b and b?a
i=~~eval(v[q]+h+v[1-q]), // calc the value and floor it
i>n||i>0&&(z[i-1]=h); // if within limits, record it
return z
}
```
This is a complete overhaul of my original answer which was a 249 byte solution.
Technically this does potentially include exponentiation and concatenation, but since they never show up in the answers, I culled out the code. Heh.
A single line answer:
```
(a,b)=>{p=n=>{for(i=n;n%--i;);return i-1};for(n=a-~b;p(n);)n++;for(z=Array(n).fill(0),o="+-*/%|^&",c=0;h=o[c];c++)for(v="ab",q=2;q--;)i=~~eval(v[q]+h+v[1-q]),i>n||i>0&&(z[i-1]=h);return z}
```
```
f=
(a,b)=>{p=n=>{for(i=n;n%--i;);return i-1};for(n=a-~b;p(n);)n++;for(z=Array(n).fill(0),o="+-*/%|^&",c=0;h=o[c];c++)for(v="ab",q=2;q--;)i=~~eval(v[q]+h+v[1-q]),i>n||i>0&&(z[i-1]=h);return z}
console.log(f(2,3))
console.log(f(1,1))
console.log(f(6,6))
console.log(f(6,12))
console.log(f(7,15))
```
Recently, switched to stack snippet instead of tio.run and changed `console.log(z)` to `return z`. I was returning at first then switched to console.log because I though returning was against the rules. Its never quite clear to me when I'm allowed to return values rather than outputting them directly, but I see other golfers do it this way.
Also, [Try it online!](https://tio.run/##bc7BSsQwFAXQvV8hhSl5JhmbiuPi8Qp@R6mQxtZGStJmxoC101@vHReCjJu7OJcL911HfTTBDifp/GuztrQyLWqg4msgt2XrA7Pk0O2ktAgYmtNHcLdWqjNeOkdaLjUOzAGC4/wHJ3oOQX9utm9t37MMhKeEy7v73fySJsJQhh350lRoOIfLJFKi60SMlOMoJYKlZWmi7lksx4p3PJZKjhUIW7h5tkWWpmwqtxcVdb@npvNqvDv6vtn3/o21LBcPADd/TQl1ZQdx@MdUfoVPQj0CrN8 "JavaScript (Node.js) โ Try It Online") (redundant, I know, but I finally figured out tio.run.)
] |
[Question]
[
## Challenge
Given three numbers \$a\$, \$b\$, and \$n\$, you must expand \$(a + bx)^n\$ in ascending powers of \$x\$ up to \$x^3\$.
## Binomial Expansion
***Note that this method is an approximation***
The binomial expansion works like so:
```
(a + bx)^n = a^n(1 + bx/a)^n
= a^n(1 + n(bx/a) + n(n -1)(bx/a)^2/2! + n(n-1)(n-1)(bx/a)^3/3!)
```
Or, more readable:
$$\begin{align}
(a+bx)^n &= a^n\left(1+\frac{b}{a}x\right)^n\\
&\approx a^n\left(1 + n\left(\frac{b}{a}x\right)+ \frac{n(n-1)}{2!}\left(\frac{b}{a}x\right)^2 + \frac{n(n-1)(n-2)}{3!}\left(\frac{b}{a}x\right)^3\right)
\end{align}$$
Which simplifies down to an expression in the form
$$\alpha + \beta x + \gamma x^2 + \delta x^3$$
Where \$\alpha\$, \$\beta\$, \$\gamma\$ and \$\delta\$ are constants which you must calculate.
These constants should be given to at least 3 decimal places where appropriate (i.e. 1.2537 should be output instead of 1.25, but 1.2 can be output if the answer is exactly 1.2).
You must then output these four constants in a list (in order as they appear in the final equation). This list may be separated however you wish.
# Input
The inputs \$a\$ and \$b\$ will be integers in the range -100 to 100 inclusive where \$a \neq 0\$.
\$n\$ will be given to one decimal place and will be in the range \$-2 \leq n \leq 2\$
# Examples
## `a = 1, b = 6, n = -1.0`
```
1, -6, 36, -216
```
## `a = 3, b = 2, n = 2.0`
```
9, 12, 4, 0
```
## `a = 5, b = 4, n = 0.3`
```
1.621, 0.389, -0.109, 0.049
```
# Winning
The shortest code in bytes wins.
[Answer]
## Mathematica, ~~45~~ 37 bytes
It turns out that `Binomial` threads over lists!
```
Binomial[#3,r={0,1,2,3}]#2^r#^(#3-r)&
```
Each of `Binomial[#3,r={0,1,2,3}]`, `#2^r` and `#^(#3-r)` returns a length-4 list, which are implicitly multiplied together term-by-term, giving the binomial coefficients.
---
Old solution (45 bytes):
```
FoldList[#~D~x/#2&,(#+#2x)^#3,Range@3]/.x->0&
```
And a 43-byte solution that works except when `n = 0`:
```
Series[(#+#2x)^#3,{x,0,3}][[3]]~PadRight~4&
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~80 74 64 63~~ 62 bytes
I've tried many more sophisticated approaches, but they all were longer than the straightforward approach. (In meantime golfed down a bit.)
Thanks for -1 byte @Laikoni!
```
(a#b)n|c<-b/a=(*a**n)<$>1:c*n:map(n*(n-1)*c*c*)[1/2,c*(n-2)/6]
```
[Try it online!](https://tio.run/nexus/haskell#Zc69CsMgEADgvU8hJIMeFdFAB0n6BN06hgynSzvEhjSlS9899WIi/UE4udP77qTkWDgRmhYBwj4GHqQW4HJiKAEDIb0os9arpV5t9fRVHbqd3EgSLQWF5NkeBx6y70C024Rv9F@iTiBJlNo6Aj8xhcsAAnWUMqCwmxPw8rV0CpsVqcujtv5nIx9PAnzeYO7xGljDhsd0nsZTYCW7X27PePGqMMLMbw "Haskell โ TIO Nexus")
[Answer]
# [Haskell](https://www.haskell.org/), 46 bytes
```
(a%b)n=scanl(*)(a**n)[(n-i+1)/i*b/a|i<-[1..3]]
```
[Try it online!](https://tio.run/nexus/haskell#BcExDoAgDADAr3TQpK0BJOgmLyEMxamJNkYd/TvedZSxkeVnFzuQCYXZqKA5nSIF5Rbk082V6H2qtZ@iBhmuW@2FARDXcaHZJ@o/ "Haskell โ TIO Nexus")
Expresses the ratios of consecutive terms, and uses them to recover the terms by `scanl(*)` starting with the first term `a*n`. The ratios have form `(n-i+1)/i*b/a`.
[Answer]
# Casio BASIC, 144 bytes
```
?โA
?โB
?โN
BรทAโB
A^NโA
A((N(N-1))รท2!รBยฒ)โS
A((N(N-1)(N-2)รท3!รBยณ)โT
NรBรAโN
ClrText
Locate 1,1,A
Locate 1,2,N
Locate 1,3,S
Locate 1,4,T
```
Output is in a line like so:
```
34.5
20
11
56.85
```
[Answer]
# JavaScript, ~~55~~ ~~53~~ 50 bytes
```
(a,b,n)=>[s=a**n,s*=n*(b/=a),s*=--n*b/2,s*--n*b/3]
```
```
~~(a,b,n)=>a?[s=a\*\*n,s\*=n\*(b/=a),s\*=--n\*b/2,s\*--n\*b/3]:(t=[0,0,0,0])|n>3?t:(t[n]=b\*\*n,t)~~
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 30 bytes
```
^li1G/3:"t@^2G@:q-HM/p*w]x4$h*
```
[Try it online!](https://tio.run/##y00syfn/Py4n09Bd39hKqcQhzsjdwapQ18NXv0CrPLbCRCVD6/9/Qy5dQy4zAA "MATL โ Try It Online")
Input in `a`, `n`, `b` order.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 29 bytes
```
(a,b,n)->Vec((a+b*x)^n)[1..4]
```
[Try it online!](https://tio.run/##JcdBCsIwEEbhq/x0NaOT0Njqzh7DTYgwLVYKIQzFhZ4@RoS3eJ/pvrmn1RVXVFKZpbCbbo@FSI/z4c33wjF4P6aqZvlDBjfB9q282nY/dFg0Z1oFxiyIMQguAhd8nxoHwan1x1kwCno/pMT1Cw "Pari/GP โ Try It Online")
[Answer]
# Axiom, 80 bytes
```
h(a,b,n)==(v:=series((a+b*x)^(n::Fraction INT));[coefficient(v,i)for i in 0..3])
```
exercises
```
(91) -> h(1,6,-1.0)
...
(91) [1,- 6,36,- 216]
Type: List Expression Integer
(92) -> h(3,2,2.0)
(92) [9,12,4,0]
Type: List Expression Integer
(93) -> h(5,4,0.3)
10+-+3 10+-+3 10+-+3
10+-+3 6 \|5 42 \|5 476 \|5
(93) [ \|5 ,-------,- --------,---------]
25 625 15625
Type: List Expression Integer
(94) -> map(numeric, %)
(94)
[1.6206565966 927624351, 0.3889575832 0626298443, - 0.1089081232 9775363564,
0.0493716825 6164831482 4]
Type: List Float
```
] |
[Question]
[
**This question already has answers here**:
[Stack Exchange Vote Counter](/questions/82609/stack-exchange-vote-counter)
(15 answers)
Closed 6 years ago.
I'm a narcissist. (Not Really)
I'm also very lazy... (Not Really)
So I want to know the score of this question, and how many people have viewed it.
But I'm too lazy to check myself...
# Challenge
Your challenge is to output the score of this question, and how many views there are. No input may be taken, and output may be given as pretty much anything as long as it's clear where the two numbers are outputted. So, all of the following are valid:
```
[1, 1]
score 1, 1 view
1 1
1, 1
1........1
HELLO1WORLD1
```
Note that pluralization matters, so "1 views" is invalid output.
I am very lazy, so I want this code to be as short as possible.
You may assume that there is an internet connection.
You may want to use the SE API. For reference, this question has id 111115.
# Rules
No URL shorteners are allowed.
You may assume that votes are not expanded (for users below 1000 rep: users with at least 1000 rep can click on the score of a post to see the upvotes and downvotes individually. You may assume that this was not done).
# Scoring
This is a code-golf challenge, so the shortest valid submission by March 14th (Pi Day) wins! Happy golfing!
[Answer]
### T-SQL, 49 bytes
According to the [FAQ](https://data.stackexchange.com/help#faq) the database will be updated on Sunday 0300 UTC so this is when you'll get your result. So I'm hoping you're a patient lazy (not really) narcissist (not really).
```
select Score,ViewCount
from Posts
where Id=111115
```
<https://data.stackexchange.com/codegolf/query/632441/tell-me-about-my-question>
[Answer]
# JavaScript + jQuery, 109 bytes
```
$.get('//api.stackexchange.com/questions/111115?site=codegolf',x=>alert([(a=x.items[0]).view_count,a.score]))
```
```
<!-- Click run | below! -->
<!-- v --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
```
Same strategy as [my answer on a related question](https://codegolf.stackexchange.com/a/82610/48922).
[Answer]
# Javascript (ES6), 128 bytes
```
fetch('//api.stackexchange.com/questions/111115?site=codegolf').then(x=>x.text()).then(x=>alert([(x=x.match(/\d+/g))[10],x[8]]))
```
[Answer]
## JavaScript, 129 105 bytes
Non-API solution.
```
f=(v,n)=>document.getElementsByClassName(v)[n].innerText;alert([f("vote-count-post",0),f("label-key",3)])
```
You should be able to run this in your browser's developer tools.
[Answer]
## Bash + curl, ~~82~~ ~~90~~ ~~99~~ ~~95~~ ~~90~~ 89 bytes
*Edit 1:* I had to do better searches to omit the keywords from my own answer, hence more bytes.
*Edit 2:* Using sed magic I got the byte count down again
```
curl -L codegolf.stackexchange.com/q/111115>f
grep -m1 t-post f
sed -n '/key.>\r/{n;p}' f
```
When curl accesses that short URL format, it receives a 302 redirection page that has this question's URL in the body section, so the -L option is needed to follow it. After that, it downloads the source code of this html page to a file named `f`. Then I search the keywords associated with the statistics wanted and print the answer on STDOUT.
**Test:** I redirect STDERR just for clarity (stats at the time of this posting)
```
me@LCARS:/PPCG$ ./Q_stats.sh 2> /dev/null
<span itemprop="upvoteCount" class="vote-count-post ">7</span>
<b>398 times</b>
```
The output is pretty verbose, but the syntax of both lines is basically `junk text>VALUE<more junk text`, which should be allowed according to the challenge description.
[Answer]
# Python 3 + requests, ~~150~~ 143 bytes
```
(__import__("requests").get("http://api.stackexchange.com/questions/111115?site=codegolf").json()['items'][0][k]for k in('score','view_count'))
```
7 bytes shorter thanks to notjagan.
Output: `[4, 270]`
[Answer]
# Powershell, 119 Bytes
```
,"-po.+?>(.+?)<","(\d+) times<"|%{[Regex]::Match((irm codegolf.stackexchange.com/questions/111115),$_).Groups[1].Value}
```
Outputs like
[](https://i.stack.imgur.com/UypTa.png)
Shortest regex I could get to match exactly the vote count and nothing else, could make it shorter but then you would need to use `Matches` instead of `Match`
`irm` is short for `Invoke-RestMethod` and returns the raw page as text, then we just regex match the line
```
<span itemprop="upvoteCount" class="vote-count-post " title="View upvote and downvote totals" style="cursor: pointer;">4</span>
```
by looking for `-po` in `count-post`, up to the next `>`, then everything between that and the next `<` is captured and retrieved.
using basic request web parsing in powershell requires calls to things like `getElementsByClassName` which aren't very golf friendly, so the `irm` method seems to be shortest.
] |
[Question]
[
In the fewest bytes, generate the dictionary of keypresses for any letter (as described in <https://code.google.com/codejam/contest/351101/dashboard#s=p2>)
In Python, the dictionary literal itself:
```
{'a':2,'c':222,'b':22,'e':33,'d':3,'g':4,'f':333,'i':444,'h':44,'k':55,'j':5,'m':6,'l':555,'o':666,'n':66,'q':77,'p':7,'s':7777,'r':777,'u':88,'t':8,'w':9,'v':888,'y':999,'x':99,'z':9999}
```
is 187 bytes so it needs to be less than that. (The values can be strings or ints, ie you can have 'a':'2' or 'a':2 it's up to you)
NOTE: This is not asking you to solve the referenced GCJ problem, it's just asking you to generate a particular dictionary which is related to that problem.
EDIT: You may solve this in any language which has a dictionary-like type (ie hashmap, associative array etc.)
[Answer]
# perl, 49 48 bytes
Using a different algorithm than my previous answer, we can lose another 12 bytes. The basic idea is that you usually just add the digit from the last letter's solution over again. We handle the other cases (detected by a short regex) by starting with a single instance of the last digit + 1.
```
{map{$d++,$t=""if/[dgjmptw]/;$_,$t.=$d||=2}a..z}
```
With output:
```
ski@anito:~/src$ perl -MData::Dumper -e '$Data::Dumper::Sortkeys=1; $d=2;print Dumper {map{$d++,$t=""if/[dgjmptw]/;$_,$t.=$d}a..z}'
$VAR1 = {
'a' => '2',
'b' => '22',
'c' => '222',
'd' => '3',
'e' => '33',
'f' => '333',
'g' => '4',
'h' => '44',
'i' => '444',
'j' => '5',
'k' => '55',
'l' => '555',
'm' => '6',
'n' => '66',
'o' => '666',
'p' => '7',
'q' => '77',
'r' => '777',
's' => '7777',
't' => '8',
'u' => '88',
'v' => '888',
'w' => '9',
'x' => '99',
'y' => '999',
'z' => '9999'
};
```
[Answer]
# Golfscript, 68 characters
```
"{'"26,{.[.",'"''if\97+"':"]''+\..11-
7/.0>*-.3/2[+]\3%)@18=+*}/"9}"
```
What's this, you say? [It outputs the correct Python dict literal](http://golfscript.apphb.com/?c=InsnIjI2LHsuWy4iLCciMGlmXDk3KyInOiJdJycrXC4uMTEtCjcvLjA%2BKi0uMy8yWytdXDMlKUAxOD0rKn0vIjl9Ig%3D%3D):
```
{'a':2,'b':22,'c':222,'d':3,'e':33,'f':333,'g':4,'h':44,'i':444,'j':5,'k':55,'l':555,'m':6,'n':66,'o':666,'p':7,'q':77,'r':777,'s':7777,'t':8,'u':88,'v':888,'w':9,'x':99,'y':999,'z':9999}
```
That is,
```
$ echo print `ruby golfscript.rb phonetyp.gs` | python
{'a': 2, 'c': 222, 'b': 22, 'e': 33, 'd': 3, 'g': 4, 'f': 333, 'i': 444, 'h': 44, 'k': 55, 'j': 5, 'm': 6, 'l': 555, 'o': 666, 'n': 66, 'q': 77, 'p': 7, 's': 7777, 'r': 777, 'u': 88, 't': 8, 'w': 9, 'v': 888, 'y': 999, 'x': 99, 'z': 9999}
```
[Answer]
# Python (83)(87)
```
c,d=97,{}
for i in range(2,10):
for j in range(1,4+(i>6)*i%2):d[chr(c)],c=j*str(i),c+1
```
The dictionary is stored in `d`. The condition check `(i>6)*i%2` saves two chars from `(i in[7,9])`.
## Edit:
```
c=97;d={}
for i in range(8):
for j in range(1,4+(i|2>6)):d[chr(c)]=j*str(i+2);c+=1
```
Shaved 4 characters. With `i` shifted down by 2, we recognize the special cases of 7 and 9 by checking if `i` is 5 or 7 using `i|2>6`.
[Answer]
# Python, 86 characters
Alternate Python solution:
```
d={}
for a in range(26):n=a-max(0,(a-11)/7);d[chr(a+97)]=`n/3+2`*(n%3+1+(a in(18,25)))
```
[Answer]
# J - 57 char
The closest analogue to the dictionary datatype in J is a table of boxes: each row is an entry, containing the key on the left and the data on the right. It's not really unordered, but whenever you need a dictionary type of record, you would use something like this.
```
_2]\;n(;&.><\)/@|:/.n,.~u:97+i.#n=.,":"0(#~3+e.&7 9)2+i.8
```
`n` is the string `'22233344455566677778889999'`, which we create by taking the list `2 3 4 5 6 7 8 9` and taking three of 4 of each element, depending on whether the element is 7 or 9. Then we just convert each item to a string and run them together into a single string.
Then we make the alphabet, attach the digits to the alphabet with `,.~`, and then group them by the digits (this is `/.` at work). Within each group, we pair off the letter with the corresponding prefix of the string of same digits.
Finally, we run things together: `;` to take off the effects of the earlier grouping and `_2]\` to put it into the proper table shape.
```
_2]\;n(;&.><\)/@|:/.n,.~u:97+i.#n=.,":"0(#~3+e.&7 9)2+i.8
+-+----+
|a|2 |
+-+----+
|b|22 |
+-+----+
|c|222 |
+-+----+
|d|3 |
+-+----+
|e|33 |
+-+----+
|f|333 |
+-+----+
|g|4 |
+-+----+
|h|44 |
+-+----+
|i|444 |
+-+----+
|j|5 |
+-+----+
|k|55 |
+-+----+
|l|555 |
+-+----+
|m|6 |
+-+----+
|n|66 |
+-+----+
|o|666 |
+-+----+
|p|7 |
+-+----+
|q|77 |
+-+----+
|r|777 |
+-+----+
|s|7777|
+-+----+
|t|8 |
+-+----+
|u|88 |
+-+----+
|v|888 |
+-+----+
|w|9 |
+-+----+
|x|99 |
+-+----+
|y|999 |
+-+----+
|z|9999|
+-+----+
```
[Answer]
# perl, 61 bytes
Examine the mod3 and div3 of a counter $t to determine the base digit and number of repetitions. Handle the special cases of s and z separately.
```
$t=5;{map{$b=++$t%3+1;$b=4,--$t if/s|z/;$_,int($t/3)x$b}a..z}
```
With string output:
```
perl -MData::Dumper -e '$Data::Dumper::Sortkeys=1; $t=5;print Dumper {map{$b=++$t%3+1;$b=4,--$t if/s|z/;$_,int($t/3)x$b}a..z}'
$VAR1 = {
'a' => '2',
'b' => '22',
'c' => '222',
'd' => '3',
'e' => '33',
'f' => '333',
'g' => '4',
'h' => '44',
'i' => '444',
'j' => '5',
'k' => '55',
'l' => '555',
'm' => '6',
'n' => '66',
'o' => '666',
'p' => '7',
'q' => '77',
'r' => '777',
's' => '7777',
't' => '8',
'u' => '88',
'v' => '888',
'w' => '9',
'x' => '99',
'y' => '999',
'z' => '9999'
};
```
And here's a more readable version of the code:
```
{
map {
my $reps = (++$pos % 3) + 1;
if($_ =~ /s|z/) {
--$pos;
$reps=4;
}
my $digit = int( $pos/3 );
$_ => $digit x $reps
} ('a'..'z')
}
```
We start with $pos = 5 so that int(++$pos/3) starts off at 2.
We handle the case of s and z separately since they are the only exceptions to the modulo 3 rule.
[Answer]
# JavaScript (*ES5*) 88 86 85 bytes
```
for(o={},a=c=2,b=96;a-10;a=a<(c%9%7?b:1e3)?a+[c]:++c)o[String.fromCharCode(++b)]=+a;o
```
**Result:**
```
{"a":2,"b":22,"c":222,"d":3,"e":33,"f":333,"g":4,"h":44,"i":444,"j":5,"k":55,"l":555,"m":6,"n":66,"o":666,"p":7,"q":77,"r":777,"s":7777,"t":8,"u":88,"v":888,"w":9,"x":99,"y":999,"z":9999}
```
If mixed types are allowed, it can be reduced by 1 byte.
# 86 84 bytes:
```
for(o={},a=c=2,b=96;a-10;a=a<(c%9%7?b:1e3)?a+[c]:++c)o[String.fromCharCode(++b)]=a;o
```
**Result:**
```
{"a":2,"b":"22","c":"222","d":3,"e":"33","f":"333","g":4,"h":"44","i":"444","j":5,"k":"55","l":"555","m":6,"n":"66","o":"666","p":7,"q":"77","r":"777","s":"7777","t":8,"u":"88","v":"888","w":9,"x":"99","y":"999","z":"9999"}
```
[Answer]
# Mathematica, 168
This is the longest answer here... I'm sure there's a better way to do this.
```
(k=#2[[1]]+1;Append[{},{#->StringJoin@ConstantArray[ToString@k,#2]}]&~MapIndexed~#)&~MapIndexed~Characters@{"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}~Flatten~3
```
Output:
```
{"a" -> "2", "b" -> "22", "c" -> "222", "d" -> "3", "e" -> "33",
"f" -> "333", "g" -> "4", "h" -> "44", "i" -> "444", "j" -> "5",
"k" -> "55", "l" -> "555", "m" -> "6", "n" -> "66", "o" -> "666",
"p" -> "7", "q" -> "77", "r" -> "777", "s" -> "7777", "t" -> "8",
"u" -> "88", "v" -> "888", "w" -> "9", "x" -> "99", "y" -> "999",
"z" -> "9999"}
```
[Answer]
# Bash + coreutils, 91 bytes
```
p="printf %s\n"
paste <($p {a..z}) <($p {2..9} {22..99..11} {222..999..111} 7777 9999|sort)
```
Generates a tab-delimited table, which is a natural structure for a shell script - not sure if that meets the specs or not:
```
a 2
b 22
c 222
d 3
...
r 777
s 7777
t 8
u 88
v 888
w 9
x 99
y 999
z 9999
```
---
# Pure Bash, 137 bytes
Not very good.
```
declare -A a
b=({X..z})
for n in {9..33};do
c=${b[n]}
((n>26?n--:n))
printf -vk %$[n%3+1]s
a[$c]=${k// /$[n/3-1]}
done
a[s]+=7
a[z]=9999
```
This populates a bash associative array.
Crudely display it as follows:
```
$ for c in ${!a[@]}; do echo -n $c:${a[$c]},;done; echo
a:2,b:22,c:222,d:3,e:33,f:333,g:4,h:44,i:444,j:5,k:55,l:555,m:6,n:66,o:666,p:7,q:77,r:777,s:7777,t:8,u:88,v:888,w:9,x:99,y:999,z:9999,
$
```
[Answer]
# Python 2 (97)
I used a single dictionary comprehension:
```
{zip(*[(chr(i)for i in range(65,91))]*3)[i][k]:str(i+2)*(k+1)for k in range(3)for i in range(8)}
```
Unfortunately it's missing the `z` because on number 9 there are 4 letters.
[Answer]
## Clojure, 91 bytes
```
(zipmap(map char(range 97 123))(for[i(range 2 10)r(range 1(get{7 5 9 5}i 4))](repeat r i)))
```
`for` is ideal for generating these kinds of sequences. Output looks like this:
```
{\a (2), \b (2 2), \c (2 2 2), \d (3), ...
```
] |
[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/11404/edit).
Closed 2 years ago.
[Improve this question](/posts/11404/edit)
The goal is to display a bรฉzier curve in any classical browser (except maybe old IE versions, because... are they really browsers?) **client side**.
**Rules:**
* You must provide one or more files (or their content). These files must contain all the code.
* The code must work offline, no imports from a remote source. No installation should be needed on the computer (except a vanilla browser).
* This is a Javascript contest. A very simple way would be to use `SVG` files that can be read with browsers. Don't!
* No need to pass the W3C validator test, you can omit the doctype and the surrounding tags (`html`, `head`, `body`, ...)
* The input can take any form: GET, POST, written in the code, etc.
* The quadratic bรฉzier must be implemented. (2nd degree bรฉzier: starting point, ending point and 1 intermediate point). It means 3 points (= 6 coordinates) must be given in whatever format you prefer (XML, JSON, ...).
* If you don't know what a bรฉzier curve is, you should! Check on **[Wikipedia](http://en.wikipedia.org/wiki/B%C3%A9zier_curve)** to know about it.
**Scoring:**
* In his great kindness, OP offers you 10'000 point just by posting a valid answer.
* The sum of the sizes of the files in bytes will give negative points. 1 byte = -1 point\*.
* Implementing the cubic bรฉzier curve **instead of** the quadratic multiplies your points by 120%.
* Implementing n-th degree bรฉzier curve **instead of** the quadratic or cubic double your points. (Which means implementing both the cubic and the n-th degree is useless, pointless and very dumb).
* Implementing filled bรฉzier (with inner color) will double your points again.
* There is no limit in the number of files or libraries you use, just remember adding jQuery, for example, already gives you about -26'000 points.
The contestant with the highest score wins. *(duh!)*
\*A 10'000 characters answer gives you 0 points.
[Answer]
## 39240 points (190 chars)
```
<script>P='<svg><path stroke=red d=M'+X[n]+','+Y[n]
for(t=N=99;t--;P+='L'+x+','+y)for(x=y=i=0,z=Math.pow(1-t/N,n);i<=n;z*=t/(N-t)*(n-i)/++i)x+=z*X[i],y+=z*Y[i]
document.write(P+'>')</script>
```
Input is supplied in three variables: `X` and `Y` hold the coordinates, and `n` holds the degree of the polynomial. If more coordinates are supplied than are needed, the surplus ones are ignored. The line is stroked in red and filled in black.
This example draws substantially from the existing ones, but with an improvement of 40% in character count over the current best character count I think it's worth a separate answer.
Demo: <http://jsfiddle.net/MBCGJ/7/>
This is stretching the flexibility of the rules too far IMO, but three characters can be saved by making `N` a "fineness" parameter which must be initialised along with the input coordinates and degree.
Also, Chrome at least doesn't care about closing the `path` element at all, which allows saving the 4 chars `+'>'`, so if that works cross-platform and the fineness parameter abuse is allowed this can go down to 183 chars.
---
The preferred way of rendering Bรฉzier curves is, of course, adaptive subdivision using the de Casteljau algorithm. Unfortunately this uses more characters because it's necessary to do a test to decide whether to subdivide and then to do a moderate amount of work for the subdivision itself. Currently I'm at **371 chars**, although I think this could be reduced with an explicit stack.
```
<script>P='<svg><path stroke=red d=M'+X[0]+','+Y[0]
function Z(A,B,E,F){function d(p,q){return(t=A[p]-A[q])*t+(t=B[p]-B[q])*t}for(e=i=0;++i<n;e|=b+c-d(n,0)+Math.sqrt(3.9*b*c)>0)b=d(i,0),c=d(n,i)
for(E=[],F=[i=-1];e?i++<n||Z(E,F)|Z(A,B):0;)for(E[i]=A[0],F[i]=B[j=0];j<n-i;B[j]=(B[j]+B[++j])/2)A[j]=(A[j]+A[j+1])/2
P+='L'+A[n]+','+B[n]}Z(X,Y)
document.write(P+'>')</script>
```
The figure 3.9 in the middle there is the quality parameter, which must be less than 4 to avoid infinite recursion. The closer it gets to 4, the better the quality.
<http://jsfiddle.net/FrJLn/2/>
[Answer]
### 38,716 points (321 chars)
```
<canvas id="c"></canvas><script>function c(n,k){return k<1||c(n-1,k-1)*n/k}function b(p,f){d=document.getElementById('c').getContext('2d')
for(t=0;t<1.009;t+=0.01){n=p.length-1
x=y=i=0
e=Math.pow
for(;i<=n;z=c(n,i)*e(1-t,n-i)*e(t,i),x+=z*p[i][0],y+=z*p[i][1],i++);d.lineTo(x,y)}d.stroke()
d.fillStyle=f
d.fill()}</script>
```
Given an array of points and the desired fill colour, the `b` function draws an n-th degree bรฉzier curve onto the canvas. It uses the binomial theorem to calculate the location of 101 different points along the curve, and then joins them together with straight lines.
[Example](http://jsfiddle.net/grc4/jkndt/1/)
[Answer]
# 716 Chars - 37136 points
```
<script>function f(n){return n<1||n*f(n-1)}function c(n,k){return f(n)/(f(k)*f(n-k))}U=")*Math.pow(",G="createElementNS",$="setAttribute",d=document,w="appendChild",y=["",j=""];window.onload=function(){v=d.getElementById("s");q=prompt().split(" ");e=q.length-1;for(z=0;z<=e;z++){q[z]=q[z].split(",");p=q[z]={x:q[z][0],y:q[z][1]};_=d[G]("http://www.w3.org/2000/svg","circle");_[$]("cx",p.x);_[$]("cy",p.y);_[$]("r",5);_[$]("fill","red");v[w](_);for(u=0;u<2;u++)y[u]+="(c("+e+","+z+U+"1-t,"+(e-z)+U+"t,"+z+")*q["+z+"]."+"xy"[u]+")"+(z^e?"+":"")}for(t=0;t<=1.01;t+=0.01)j+=eval(y[0])+","+eval(y[1])+" ";l=d[G]("http://www.w3.org/2000/svg","polyline");l[$]("points",j);l[$]("stroke","red");v[w](l)}</script><svg id="s"/>
```
[Try it in this JFiddle](http://jsfiddle.net/4cGFH/)
You will be prompted to provide your points in the following format:
`x1,y1 x2,y2 x3,y3 x4,y4 x5,y5`
## Check list
* n-degree handled
* beziers are filled
* no external libraries
* plots control points
An example output of a 34th degree curve (non filled):

# 441 Chars - 38236 points
This doesn't plot the control points and it, shamelessly, uses grc's n-choose-k function. so it's not my real submission
```
<script>function c(n,k){return k<1||c(n-1,k-1)*n/k}V=Math.pow,$="setAttribute",d=document,window.onload=function(){A=prompt().split(" ");e=A.length-1,j="";for(t=0;t<=1.01;t+=0.01){x=y=0;for(z=0;z<=e;z++)p=A[z].split(","),f=c(e,z)*V(1-t,e-z)*V(t,z),x+=f*p[0],y+=f*p[1];j+=x+","+y+" "}l=d.createElementNS("http://www.w3.org/2000/svg","polyline");l[$]("points",j);l[$]("stroke","red");d.getElementById("s").appendChild(l)}</script><svg id="s"/>
```
[Answer]
# 186 bytes (39256 points?)
```
<script>function m(a,j,l){return l?m(a,j,--l)*(1-i)+m(a,j+1,l)*i:a[j]}P='<svg><path stroke=red d='
for(i=0;i<=1;i+=1/64)P+='ML'[i&&1]+m(X,0,n)+','+m(Y,0,n)
document.write(P+'>')</script>
```
Usage is exactly the same as Peter Taylor's solution. Also credits to Peter for the svg path approach (I wanted to use a canvas but it turns out to be longer). I would normally delete the "stroke=red" part (to get 175 bytes) but I kept it for having a fair comparison.
] |
[Question]
[
**This question already has answers here**:
Closed 11 years ago.
>
> **Possible Duplicate:**
>
> [Integer to string with given radix](https://codegolf.stackexchange.com/questions/536/integer-to-string-with-given-radix)
>
>
>
This question is inspired by Pythons builtin `int` function. `int` is used to convert other numbers or strings into integers. If you are converting a string you can provide the additional parameter `base`, that contains the base that your number is represented in within the string:
```
>>> int('137')
137
>>> int('137',base=8)
95
>>> int('ff',base=16)
255
>>> int('1AZ',base=36)
1691
```
Unfortunately Python doesn't provide a function for the reverse case, where you want to convert a number into a string in a specific base.
Your task is to write such a function.
* the function may return the value or print it
* you must provide support for all bases between 2 and 36
* digits to use are `0123456789abcdefghijklmnopqrstuvwxyz`
* all languages are allowed
* built in functions for this purpose are boring and thus forbidden
* shortest code wins
[Answer]
## C, 68
```
c(n,b,r){char*p=1+&r;for(r=0;n;n/=b)*--p=n%b+48+(n%b>9)*39;puts(p);}
```
testing:
```
main(){
c(65,2);
c(100,30);
c(57005, 16);
}
```
output:
```
1000001
3a
dead
```
issues:
* 0 is printed as empty string.
* potential buffer overflows due to abuse of 'int' as a char array...
* works with Apple clang v4.0 - your milage may vary with other compilers.
[Answer]
## Befunge, 17x4 = 68 characters
```
1-&00p&>:!#v_:00v
v-10< ^/g00\%g <
< >:^@_.# #$v#:!`
"_^#`9::$ <<,+"W
```
Online interpreter: <http://www.bedroomlan.org/tools/befunge-93-playground>
First input is base, second is number.
Similar to other solutions here this does not output anything when the number is 0. I may look at fixing this at some point.
[Answer]
## APL (25)
```
{(โD,โA)[1+โตโคโจโบโดโจโโบโโต+1]}
```
The left argument is the base, and the right argument is the number.
i.e.
```
16{(โD,โA)[1+โตโคโจโบโดโจโโบโโต+1]}1234
4D2
```
[Answer]
## PHP, 92 Bytes
Quite new to code-golf, so probably can do better than this (suggestions would be very welcome!)
```
function b($n,$b){while($n>0){$r=$n%$b;$n=floor($n/$b);$s=($r>9?chr(87+$r):$r).$s;}echo$s;}
```
With (some) whitespaces:
```
function b($n,$b)
{
while ($n>0)
{
$r=$n%$b;
$n=floor($n/$b);
$s=($r>9?chr(87+$r):$r).$s;
}
echo $s;
}
```
[Answer]
## Python, 81 58 bytes
```
x=lambda n,b:(n/b and x(n/b,b)or'')+chr(48+n%b+39*(n%b>9))
```
Usage:
`x(100,30)` returns `'3a'`, which is 100 in base 30.
[Answer]
# C, 48 chars
```
i(n,b){n?i(n/b,b),putchar(n%b+48+(n%b>9)*39):0;}
```
* input of 0 produces empty string
# C, 77 49 chars, prints `0` for zero
```
I(n,b){putchar(n?i(n/b,b),48+n%b+(n%b>9)*39:48);}
```
[To run, call i for first version, I for second.](http://ideone.com/UhR2E)
[Answer]
## C# โ 85 characters
```
string F(int n,int b){var s="";for(;n>0;n/=b)s=(char)(n%b+(n%b>9?87:48))+s;return s;}
```
[Answer]
## VBA, 99
(70 if you take out the function/endfunction lines)
```
Function F(a,b)
F="":q=a:Do:c=q Mod b:F=Chr(c+48-39*(c>9))&F:q=Int(q/b):Loop Until q=0
End Function
```
fixed for case when **a=0**
[Answer]
# Ocaml, 98 or 120
It prints out a leading zero, though. Usage: `16-0xBEEF`
```
let rec(-)b=function|0->"0"|n->b-n/b^String.make 1(Char.chr(n mod b+if n mod b>9 then 55 else 48))
```
Unfortunately a lot of characters are spent on converting to char then to string :/
This one is correct.
```
let rec(-)b=function|0->"0"|n->(if 0=n/b then""else b-n/b)^String.make 1(Char.chr(n mod b+if n mod b>9 then 55 else 48))
```
The strong typing in ocaml is sometimes unfortunate when golfing. Partial application and such somewhat make up for it, though.
[Answer]
## CoffeeScript (98 92)
```
z=(i,b)->a=parseInt(i)%b;return''if 1>i;(z i/b,b)+if a>9then String.fromCharCode(a+87)else a
```
The compiled (and readable) javascript for the interested:
```
z = function(i, b) {
var a;
a = parseInt(i) % b;
if (1 > i) {
return '';
}
return (z(i / b, b)) + (a > 9 ? String.fromCharCode(a + 87) : a);
};
```
What can I say? Unnecessary recursion gets me hot.
This could have been far shorter if I knew a shorter way to floor or convert from ASCII in Coffee-/Javascript. Tips would be greatly appreciated.
**Edited** to include "parseInt" to save a couple of characters on "Math.floor" and with some rearranging to reduce the "if ... then ..."s. Unfortunately, I don't think there even is a shorthand if in CoffeeScript ( "... ? ... : ..." doesn't work).
] |
[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/5522/edit).
Closed 5 years ago.
[Improve this question](/posts/5522/edit)
In the spirit of [a question on math.se](https://math.stackexchange.com/questions/130547/getting-the-sequence-1-0-1-0-1-0-1-0-without-trig): given an integer `n`, return the integer in position `n` of the sequence [1, 0, -1, 0, 1, 0, -1, 0, ...]. Assume `n >= 0`.
Rules:
1. You may only use the operations -x, x+y, x-y, x\*y, x/y, and xy, whatever their representations are in the language you choose.
2. Your function must be called `a`.
3. Your function must run in constant time for all `n`.
Example:
```
a=lambda n:((-1)**(n*n-n)//2)+(-1)**(n*n+n)//2))//2
```
Non-example (uses list subscripting operation and modulo operator):
```
a=lambda n:[1,0,-1,0][n%4]
```
Non-example (uses cos operation):
```
from math import *;a=lambda n:int(cos(n*pi/2))
```
Non-example (does not run in constant time and uses if operation):
```
a=lambda n:-a(n-2) if n>1 else 0 if n>0 else 1
```
**Clarifications:** Both integer and float division are allowed. Your solution may return either an integer or a float (or complex number, I suppose, since some answers already used it). If your solution returns a float: your solution should, if it were to theoretically be carried out to infinite precision, give the exact answer.
[Answer]
### Ruby, 26 characters
```
a=->n{1-(k=n-n/4*4)+k/3*2}
```
Example:
```
> p (0..10).map{|n| a[n]}
[1, 0, -1, 0, 1, 0, -1, 0, 1, 0, -1]
```
Note: This solution assumes that integer division `/` is an allowed operation.
[Answer]
## C, 36 chars
```
a(n){return(1-n+n/2*2)*(1-n+n/4*4);}
```
The same function used by Peter Taylor.
[Answer]
## Python, 29 chars
```
a=lambda n:(1j**n+(-1j)**n)/2
```
Kind of cheating, but fun.
## Edit:
Now that we can return complex numbers, this is competitive and no longer cheating (with Howard's suggestion).
[Answer]
## Python, 36 chars
```
a=lambda n:(-1)**(n/2)*(1+(-1)**n)/2
```
[Answer]
## J, 18 characters
```
a=:[:{.[:+._1^2%~]
```
Works, but is probably cheating by the rules set out above.
Calculates -1 to the power of the given integer divided by 2 which gives `0j1` for any odd number. The `{.` and the `+.` return the real part so that the odd numbers give 0.
Usage:
```
a 1
0
a 6
_1
```
Edit: After feeling a bit smug about this I've just looked properly at Keith's answers and realized I've done essentially the same thing.
[Answer]
## GolfScript (20 19 chars)
```
{.4/4*-.3/2*)\-}:a;
```
This is a port of [Howard](https://codegolf.stackexchange.com/users/1490/howard)'s [solution](https://codegolf.stackexchange.com/questions/5522/generate-the-list-1-0-1-0-1-0-1-0/5524#5524).
If, in addition to division, the remainder operation were permitted, this could be improved substantially (by 6 5 chars):
```
{.2%(\4%(*}:b;
```
Mathematically that's
```
x => (x%2 - 1) (x%4 - 1)
```
I can't see any logic behind excluding remainder, since it's *defined* in terms of permitted operations.
[Answer]
**Python, 34 chars**
Poor man's modulus... saves a whopping 2 chars over Keith Randall's solution. Take that! ;)
```
a=lambda n:(n-1-n/2*2)*(n-1-n/4*4)
```
edit: on reading others' solutions, this is the same as Peter Taylor's
[Answer]
## bc: 28 chars
```
echo 'a=4;(1-a+a/2*2)*(1-a+a/4*4)' | bc
```
[Answer]
# Python, 49 chars
```
a=lambda n:(lambda x:(x**3-3*x*x-x+3)/3)(n-n/4*4)
```
Note: In Python3 you'll have to replace n/4 with n//4 at the end.
[Answer]
**8086 Assembler** (14 bytes of machine code):
```
; ax holds the index into the sequence
; returns the sequence value in ax
a: inc al
shl al,6
sar al,6
cbw
xor al,ah
add al,ah
cbw
ret
```
[Answer]
# TI-Basic, 12 bytes
```
i^Ans+i^-Ans
Ans/2
```
Store in `prgmA` and run with `5:prgmA`, with the input in place of `5`.
TI-Basic implicitly returns the last evaluated value.
[Answer]
# [Python 2](https://docs.python.org/2/), 28 bytes
```
a=lambda n:(n/2*2-n+1)*1j**n
```
[Try it online!](https://tio.run/##DcpBDsIgEEbhfU/xJ24AMQruTLyFFxgtWkw7TNph0dNTli/fk12nwrE1es60vEcCPwxfo4sXPgfrwt85bie8poRv5Y/mwsgbFhJJI3oQtMrctazQtGnm3zDImllNnwz5zFLVWGubuXkEj@hxtwc "Python 2 โ Try It Online")
Proof of validity for those who don't know Python:
The expression is `(n/2*2-n+1)*1j**n`. If you add parentheses, it becomes `((((n/2)*2)-n)+1)*(1j**n)`. `/` is integer division, since both `n` and `2` are integers in this case, `*` is multiplication, `-` is subtraction, `+` is addition and `**` is exponentiation.
[Answer]
# Java 8, 21 bytes
```
n->1-(n-=n/4*4)+n/3*2
```
Port of [*@Howard*'s Ruby answer](https://codegolf.stackexchange.com/a/5524/52210).
[Try it online.](https://tio.run/##LY7BDoIwEETvfMWGU0sFRLkh/oFcOBoPtYApwkJoITGGb68tcnnJzsxmpuULD9vqbUTHlYIbl/j1ACTqemq4qKFw5yaAII5IM6usnoXSXEsBBSDkYDC8JiHBMMc4DVLKMD4HJ5O54Dg/Oxvc88sgK@htEyn1JPF1fwCn/5pmmLYSmR8zkJfEkTG6eQDlR@m6j4ZZR6N91AQju4ky/wD@vmo1Pw)
] |
[Question]
[
I have string \$s\$ of length \$n\$ and some constant integer \$k\$ which is at most \$n\$. Give the fastest algorithm to sample a random string with [Levenshtein](https://en.m.wikipedia.org/wiki/Levenshtein_distance) distance \$k\$ from \$s\$ uniformly.
Your algorithm should output any of the strings with edit distance exactly \$k \leq n\$ from the input string \$s\$ with the same probability. You should assume that only the characters in the string \$s\$ are used.
For example, if \$s\$ = "1111011010" the number of strings with distance \$k\$ [is](https://codegolf.stackexchange.com/q/37979/116117)
```
k | # of results
0 1
1 28
2 302
3 1652
4 5533
5 14533
6 34808
7 80407
8 180663
9 395923
```
If \$k\$ = 9 you should output one of the 395923 possible output strings chosen uniformly at random.
[Answer]
# [Python](https://www.python.org), 3453 bytes
```
import random
def skip():pass
class State:
states = []
def __init__(self, accepting=False):
self.n = len(State.states)
State.states.append(self)
self.accepting = accepting
self.transitions = {}
def __repr__(self):
return f'q_{self.n}'
def add(self, c, s):
self.transitions.setdefault(c, set()).add(s)
def __eq__(self, o):
return self.n == o.n
def __hash__(self):
return hash((State, self.n))
def epsilon_helper(self):
z = {self}
if '' in self.transitions:
for s in self.transitions.pop(''):
z.update(s.epsilon_helper())
self.epsilon_helper = lambda:z
return z
def remove_epsilon(self):
self.remove_epsilon = skip
for a in self.epsilon_helper():
a.remove_epsilon()
for x, S in a.transitions.items():
for b in list(S):
b.remove_epsilon()
for c in b.epsilon_helper():
self.add(x, c)
c.remove_epsilon()
def freeze(self):
self.freeze = lambda:None
for c, s in self.transitions.items():
for x in s:
x.freeze()
self.transitions[c] = frozenset(s)
def count_accepting(self):
x = self.accepting + sum(s.count_accepting() for S in self.transitions.values() for s in S)
self.count_accepting = lambda:x
return x
def accept(self, w):
if w == '': return self.accepting
return any(s.accept(w[1:]) for s in self.transitions.get(w[0],()))
def pick(self, i):
if self.accepting:
if i == 0: return ''
i -= 1
for j, s in self.transitions.items():
s = min(s)
x = s.count_accepting()
if i < x:
return j + s.pick(i)
i -= x
raise IndexError
def levenshtein(w, n):
A = set(w)
W = len(w)
states = [[State(j <= i) for j in range(len(w),-1,-1)] for i in range(n,-1,-1)]
for i, c in enumerate(w):
for j in range(n):
s = states[j][i]
for x in A:
s.add(x, states[j+1][i])
if x != c:
s.add(x, states[j+1][i+1])
s.add('', states[j+1][i+1])
s.add(c, states[j][i+1])
states[n][i].add(c, states[n][i+1])
for j in range(n):
s = states[j][W]
for x in A:
s.add(x, states[j+1][W])
s = states[0][0]
s.remove_epsilon()
s.freeze()
return s
def union(states):
d = {}
accepting = False
for s in states:
for c, S in s.transitions.items():
d[c] = d.get(c, frozenset()) | S
if s.accepting:
accepting = True
return d, accepting
def difference(q0, q1, D = None):
if D is None:
return difference(frozenset([q0]), frozenset([q1]), {})
if (q0, q1) in D:
return D[q0, q1]
d0, a0 = union(q0)
d1, a1 = union(q1)
Q0 = State(a0 and not a1)
D[q0, q1] = Q0
for i in set(d0) | set(d1):
Q0.transitions[i] = frozenset([difference(d0.get(i, frozenset()), d1.get(i, frozenset()), D)])
return Q0
def exact(w, n):
if n == 0: raise ValueError
return difference(levenshtein(w, n), levenshtein(w, n-1))
def f(w, n):
s = exact(w, n)
return s.pick(random.randrange(s.count_accepting()))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=lVfNbuM2EL4b6DuwuUjEKoIM9NAa68MCaYFeCgQumoMgGLRExczKlCxSieM0T9LLXtp32n2aDn8skZI22wqGLZMzw28-znyU_vqneZb7mn_69Hcny-sfv3z3yg5N3UrUEl7Uh8WioCUSH1kT4lVDhFgs8gp-0EYSSVcLBJdQtwKtUZrp_8pju2Wcye02FLQqI0TynDaS8fv1L6QSFBtH7QzzMQfnivJQB41NPNybuKMxaRrKCx0W-0H6NSBYf--bSEhKMMlqruC-vDpwW9q0Fq6DrqWyazkqg-P2xSB9DXonUhQ2vTxCYpyTs1YsqAQH0lUyVKZUhhjH2h07EOix56ueYrgQtUZ1zB2vPRH7rwJXk6GhNbIR8LAkbQSrar7d06qh7TjEWVGkxl77IVaiIECMTzIcvNRV1i0Sc2ZxUzdhEGDfXC8Wd00BKEMRj1Dh0Tb706pwyGFXkNV5nPsZ9Ym29FA_0q11HSeqw_omEFbVfG-iMiJ9RmOEfjpkFCvEE3JOEdqoaMQjh0l6EONoF5edsq-YkOFmxkJdu7fXdYPlKtjuG3m4l2kwKFhAns_HVVc-D0FtQdlSeqaz1JupYSd_qzn1mFc9M1tOs4xpgrX5NJ-TXWzEzThwmmcAp2zrM-WqW502zeuOy22vL-OETqpyfDV6h0R3gLoee2KNdDOb2COpOiqsic59M2qDUbSBvdO4D06DYGlrKzFPDmro6yelLEGw8uRmKqN2lvBnyMjGe0qXqwy_0fX3VBklWQTNPDDZsPyjxcJ8LP7a_i7CNFNQkx5pEPgG6HqNll79PPyv-lFHw4HxUPg1ond2uolTcO_RaVp4FuuDqoZYZ87wFLazd4QJin7lBT393LZ1a87hij5CQe4lBXhPEeIW-QdddMCxCXlnT1P7dzieU30QhA_o_RooN9QoXoCRexoal-h6CR-c6Vk2zPLLxOLCKouMjlDeHWirArslNQrOZ0g2wNKHLGXZfAd_mBIpLjJ08X63VP5TTYK9OKHv1yifV7X5OPA1UgZtFgT_zS6P3KQ8IzvOFdiRLXdt3-DN5-wu87ie42s2xzu7kBMtyeBjBucFXPiyeZEIU5QdZ-pMNQ9tBkAxPF25CqWf_fosTUtqN79scns6im_3amGUutASA36DZGOM_kQbT1W-JikuxN_bjro5Fs6zq0m3YGVJW8pzGh6TCB2XEboBR3VoWXCw1g1iQg9Nnsgc9wFsekwy7KJPj0s18PKKLxHtYlgRczOJepOaafsADvckAVBma46JFV2ASpbD8NIM3ypLowzgBE_9iNcSDM1sHxmMbpOh-Y2eyrBIFNH6bulszm3inafMP09Th4Ui0ZvH_M2LAO38-A3OvCoEUHpf6Ink0lVFII1fTgqtpn-oQ9Wo6fyGTOQ1miguKCA265XuWqqZHABelxi5N69TsfoxnT1zlkBo8xb2edO0jMuwDK-WcCXqk1xFP4FBPyH3FB07CI12bf0E7yj1CT10h0Yg6N8WqemKnJ9RUd9fRegHjE3oy4vevw)
My attempt at implementing user1502040's idea of sampling the DFA.
The algorithm runs in basically three stages:
* First it generates NFAs for `s,k` and `s,k-1` (where each accepts words with at most `k` or `k-1` errors respectively)
+ The NFAs have \$O(|s|\cdot k)\$ states, and building them takes time proportional to that (also proportional to the size of the alphabet)
* Then it uses the algorithm outlined in [this](https://cs.stackexchange.com/a/20053) cs.se answer to find a DFA for the difference of two NFAs
+ This takes the majority of the time, but I'm not sure of the actual complexity. Given that the algorithm is basically the powerset construction, it's worst case exponential, but it appears to do better than that. (I found an algorithm that can find a DFA for a given word with `<=k` errors that takes time linear with respect to the length of the word (for fixed k). See Schulz and Mihov (2002)).
+ I tried graphing the number of states in the DFA for `s="1111011012"` and `k` from `1` to `30` and it appeared linear (especially for `k>10`), but I also tried `s="the quick brown fox jumps over the lazy dog"` and `k` from `1` to `7` and it appeared exponential. \*\*
* It counts the number of states, and picks a random index and chooses the path with that index in a preorder traversal of the DFA. (am I using my jargon right?)
+ This takes time linear in the size of the DFA (using dynamic programming).
In practice, the program appears to run quite quickly; it takes about 5 seconds for `s="the quick brown fox jumps over the lazy dog"` and `k=5`.
\*\* For some reason the image feature isn't working for me, so here is the data: `[35, 101, 228, 436, 722, 1080, 1464, 1833, 2184, 2519, 2844, 3162, 3480, 3798, 4116, 4434, 4752, 5070, 5388, 5706, 6024, 6342, 6660, 6978, 7296, 7614, 7932, 8250, 8568]` and `[172, 669, 2579, 10226, 40094, 155722, 606044]`
[Answer]
# [Python](https://www.python.org), 932 bytes, \$O(4^k\cdot n^{2k+2})\$
```
import random
def levenshteinDistance(s,t):
m=len(s);
n=len(t);
d=[(n+1)*[0]for _ in range(m+1)]
for i in range(m+1):
d[i][0]=i
for j in range(n+1):
d[0][j]=j
for j in range(n):
for i in range(m):
if s[i] == t[j]:
substitutionCost = 0
else:
substitutionCost = 1
d[i+1][j+1] = min(d[i][j+1] + 1, # deletion
d[i+1][j] + 1, # insertion
d[i][j] + substitutionCost) # substitution
return d[m][n]
def build(s,k,i0=0):
if k==0:
yield s;return
for i in range(i0,len(s)+1):
t=s[:i]+s[i+1:]
for q in build(t,k-1,i):
yield q
for c in set(s):
t=s[:i]+c+s[i+1:]
for q in build(t,k-1,i):
yield q
t=s[:i]+c+s[i:]
for q in build(t,k-1,i):
yield q
def f(s,k):
return random.choice([t for t in set(build(s,k))if levenshteinDistance(s,t)==k])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=lZPBTsMwDIYP3PoUFrs0rKBU4oA25QRvUUUI1pR5a9PRuEg8C5cdgGfgWXganKYtMAYTUVWl9u_PiV0_vW4eaVnb7falpeL04v3oGatN3RA0Nzavqyg3BZTmwVi3JIP2Ch3d2IWJXUJiFgFUqjQ2dmLOe9vtqdvnKovtNBUnmdRF3cA1oPXMOxNXbNYs8Wb8bvZEjs1Qc5jCXrT6FNkvIqmzlVarPaJespugNwNgAY5zgFJAzBjMAK69dYTUEtb2snYECmTvNKUzfwrT3smnn6Z8NH6xtUIbd_fpvqeQJrCzJpCb0nhQtOsa18DcS5jwFZ1pDhL6-N2jC0_4amRIY6htLAdVOrM66v6C2xbLnPu-TlAq2dWS67hWSoayPKIpc3DzEPuzvyiT8KuMLSTlshnqqfO3m-mxZ_c-KKSjZH2aJjh0LuS4H5ULr3SGmDr0ZoAuvmEPgUc07MP8FxIKVvhidb6-nGGkzhbLGnmCMupwNFxhrK8Q-PvMKbXWIgrD-rZp0FJcxMcpL-kfeZycCxHcw0x_AA)
Runs in \$O(n(n+k)(2n(n+k))^k\$
Generates all possible strings reachable with k edits, then pick a random string with edit distance k.
The filtering by edit distance is necessary to filter out combinations of edits the can be expressed by a shorter edit sequence
(e.g. `Hello` -> `HHello` -> `Heello` -> `Hello`), I did not find any generation rule that reliably avoids every possible way to generate a shorter edit sequence.
## Running time:
*I am not that familiar with estimating the exact running time of recursive functions, so there might be a mistake in my calculations*
`levenshteinDistance(s,t)` runs in \$O(|s||t|)\$
setting \$n=|s|\$
`build(s,k,i)` runs in \$b(l,k,i)=O(\sum\_{j=i}^{l}\*(b(l-1,k-1,j)+n(b(l+1,k-1,j)+b(l,k-1,j)))\$
\$=\sum\_{j=i}^{l}\*O((2n+1)\*b(l+1,k-1,j))=O(((n+k)\*(2n+1))^k)\$
`f` runs in \$O(((n+k)\*(2n+1))^k)\*O(n(n+k))=O(n(n+k)(2n(n+k))^k)\$
or assuming \$k\le n\$ \$O(n(n+n)(2n(n+n))^k)=O(4^k\cdot n^{2k+2})\$
[Answer]
# [Python](https://www.python.org), \$\mathcal{O}((n+k)^{2k})\leq\mathcal{O}(4^k n^{2k})\$
```
from random import choice
from collections import deque
from sys import stderr
def randomWithFixedDistance(s: str, k: int) -> str:
if k <= 0: return s
chars: set[str] = set(s)
distances: dict[str,int] = {s: 0}
queue = deque((s,))
valid: set[str] = set()
while len(queue) > 0:
current = queue.popleft()
nextdist = distances[current] + 1
for nxt in insertions(current, chars) | substitutions(current, chars) | removals(current):
if nxt in distances: continue
distances[nxt] = nextdist
if nextdist < k:
queue.append(nxt)
else:
valid.add(nxt)
print(f"DEBUG: Found {len(valid)} possible strings", file=stderr)
return choice(list(valid))
def insertions(s: str, chars: set[str]) -> set[str]:
result = set()
for i in range(len(s)+1):
result.update(s[:i] + c + s[i:] for c in chars)
return result
def substitutions(s: str, chars: set[str]) -> set[str]:
result = set()
for i in range(len(s)):
result.update(s[:i] + c + s[i+1:] for c in chars if c != s[i])
return result
def removals(s:str) -> set[str]:
return set(s[:i] + s[i+1:] for i in range(len(s)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=rVRLbtswEN10pVNMsokIK669a4UoiyJNT1B0YWihkKOYiEyqJNU6SHOQopts2js1p-nwI9lNYqCLEjIMcd7MPL554o9f_a1ba_Xw8HNw7embx1ffW6M3YBol6E9uem0c8LWWHLMQ4brrkDuplR3DAj8PKWpvp13rBBqTZQLbVO6TdOtLuUVxIa1rFMfclgQzBdyUIJVjcHru38sMQLZwA2cVLEow6AajwGa0zdeN8UnoVgSsYVqV38stI4xI1QknJA_AgqrXhLmjvcU9YYjwgPDCquJp8twWzBf70nRSHG7IPKmva9khdKjyUJbBOdHOPIgPxqByBA6Rea_7Dluf5qMKt86T9U1HzquUUsMMlgHVagNq60ggeiyaIH2eYEVUhME3sMOVddINh-IGN5pOM4VYpBikTvX3lONaOalorBGz40dQr-TIfa_GeJozGmc2yhTP3fQ9KpFTLksR7CzuUEHleSMShPZ7QyPL2-OL9-8-fijhUg9KwJ3XOGDZPfTaWnlFwtNcpLq2xwW0NIcq-s73ScaJ7s074paSWXTlnpyjEZ_4KzoyvZShpB06Nw0_Tkd67cji19SECFo2WyZxI3w-9KJx5PZVKf1cOf3sSpZ1yOY-O05pxzkmRpp_D_b_Mv0XnrPlM6Z-3hyOKh-uD9Ce_GZL4vQCv_hV-6829dvv9ZwpizfU79fRGoeulJMlrYV_FicFvB3TxgvuDw)
Uses BFS to construct the sampling list, by using the principles of how Levenshtein distance is calculated to walk through the set of insertions, substitutions and deletions necessary. The process used actually looks somewhat similar to bsolech's answer, but without the need to check the Levenshtein distance of every resulting string at the end, since it keeps track of the growing distances while building the list. I believe this makes it faster than their answer by an order of about \$O(n^2)\$, although it's still nowhere near close to gsitcia's answer. Oh well.
Efficiency reasoning is as follows:
1. \$f(s,1)\$ looks at up to \$n\times(n+1)\$ insertions, which is \$\mathcal{O}(n^2)\$. Substitutions and deletions are always fewer than insertions, being \$n\times(n-1)\$ and \$n\$ respectively, so they get wrapped into this big-O.
2. \$f(s,k)\$, for each of the strings from \$f(s,k-1)\$, looks at a number of strings on the order of \$\mathcal{O}((n+k)^2)\$, so \$\mathcal{O}((n+k)^2 \times f(s,k-1))\$.
3. This means the entire function is \$\mathcal{O}(\prod\_{i=1}^k (n+i)^2) = \mathcal{O}((n+k)^{2k})\$. And since \$k\leq n\$ this can also be expressed as the (IMO) cleaner \$\mathcal{O}((2n)^{2k}) = \mathcal{O}(2^{2k} n^{2k}) = \mathcal{O}((2^2)^k n^{2k}) = \mathcal{O}(4^k n^{2k})\$.
] |
[Question]
[
## Introduction
In the prisoner's dilemma, two partners in crime are being interrogated, and have the choice to either *betray* their partner or stay silent.
* If both prisoners betray each other, they both get 2 years in prison.
* If neither betrays (both stay silent), they both get 1 year in prison.
* If only one betrays and the other stays silent, then the betrayer gets no prison time, but the other gets 3 years in prison.
In the *iterated* version of the dilemma, this situation is repeated multiple times, so the prisoners can make decisions based on the outcomes of previous situations.
## Challenge
Imagine that you are a player participating in this dilemma against an opponent.
Your opponent is described by a function \$f: M \mapsto m\$, where \$m = \{s,b\}\$ is the set of "moves" player can make (stay silent or betray) and \$M = [(m\_{1o}, m\_{1p}), (m\_{2o}, m\_{2p}), \ldots]\$ is a list of all the previous moves that your opponent and you made. In other words, given all the moves made in the game so far, the function outputs a new move.
(Note that this is *deterministic*; also, the opponent's move can depend on its own previous moves as well as the player's.)
Your code should take as input the opponent's function \$f\$ and some number \$n\$ and return the maximum reward which the optimal player can receive within \$n\$ iterations (i.e. the minimum number of years that the optimal player will stay in jail). You can output this as either a positive or negative integer.
You can use any two distinct symbols to represent the two moves, and the input format for the function is flexible (e.g. it could also take in two different lists for the opponents and player's previous moves.)
Standard loopholes are forbidden. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code wins.
## Examples
(All the code examples will be in JavaScript; I will use `0` for the "stay silent" move and `1` for the "betray" move.)
If your opponent always stays silent, i.e. they are defined by the function
```
opponentFunc = (opponentMoves, playerMoves) => 0
```
Then it is in your best interest to always betray, so
```
playerFunc(opponentFunc, 1) //=> [1], reward=0
playerFunc(opponentFunc, 3) //=> [1,1,1], reward=0
```
---
Suppose your opponent employs the "tit for tat" strategy: stay silent on the first move, then does whatever the player did on the previous move.
In other words, they are defined by the function
```
opponentFunc = (opponentMoves, playerMoves) => (playerMoves.length==0) ? 0 : playerMoves[playerMoves.length-1]
```
In that case the best actions to take are to stay silent until the final turn, where you betray; i.e.
```
playerFunc(opponentFunc, 1) //=> [1], reward = 0
playerFunc(opponentFunc, 3) //=> [0,0,1], reward = -2
```
Here is a recursive reference implementation in JavaScript:
```
reward = (opponentMove, playerMove) => [[-1,0],[-3,-2]][opponentMove][playerMove]
playerReward = (oppFunc, n, oppMoves=[], plaMoves=[], oppNextMove = oppFunc(oppMoves,plaMoves)) =>
(n==0) ? 0 : Math.max(
reward(oppNextMove,0)+playerReward(oppFunc, n-1, oppMoves+[oppNextMove], plaMoves+[0]),
reward(oppNextMove,1)+playerReward(oppFunc, n-1, oppMoves+[oppNextMove], plaMoves+[1])
)
//Testing
opponentFunc = (opponentMoves, playerMoves) => (playerMoves.length==0) ? 0 : playerMoves[playerMoves.length-1]
console.log(reward(opponentFunc, 5)) //=> -4
```
```
[Answer]
# [Haskell](https://www.haskell.org), ~~96~~ 89 bytes
```
a#b=3-b-2*a
(f%l)0=0
(f%l)t=min(f l#0+(f%((f l,0):l))(t-1))((f l#1+(f%((f l,1):l))(t-1)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWNyMTlZNsjXWTdI20Erk00lRzNA1sDSCMEtvczDyNNIUcZQNtoIAGiKljoGmVo6mpUaJrCCTBkoYISUMkSU2oBebpCjkKtgoGXBlg2pArNzEzD8jQKCjKzCtR0UhXjY7VNNa0s4MJZEAEINph7gQA)
-1 byte by Kevin Cruijssen
[Answer]
# JavaScript (ES6), ~~96 92~~ 90 bytes
Expects `(opponentFunc)(n)`, where `opponentFunc` takes a flat array of moves \$[m\_{1o},m\_{1p},m\_{2o},m\_{2p},\dots]\$ with \$0\$ for *silent* and \$1\$ for *betray*. Returns a positive integer.
```
F=>m=g=(n,i)=>i>>n?m:g(n,-~i,(h=M=>s=n--&&!(p=i>>n&1)+h([...M,M=F(M),p])+M*2)([])>m?0:m=s)
```
[Try it online!](https://tio.run/##pY4xD4IwFIR3f0VdyHtKG9CN5JWNrb@AMBisgKGvjUVH/zoik4subnf3XS53PT1Osb0NYZLsz3a@0FyRdtQRcDog6UFrLl3RLVY@hxR6MqQjsZRJsoVAb57kuO@hVkqZ1FAFBtPQ4N7sDgh1g9qVWeEo4uxD8Gx5qu7cChLg/MNGFKRFtmk9Rz9aNfoOLvDZRMgRf/Ljwjffx7erVKPlbupFKTJRiDWqP4HMm39PzC8 "JavaScript (Node.js) โ Try It Online")
### Encoding
Using \$0\$ for *silent* and \$1\$ for *betray*, the outcome is defined by the following table:
| p (player) | o (opponent) | years in prison (for the player) |
| --- | --- | --- |
| 0 | 0 | 1 |
| 0 | 1 | 3 |
| 1 | 0 | 0 |
| 1 | 1 | 2 |
which is \$o\times2+(1-p)\$, or `o * 2 + !p` as JS code.
### Commented
```
F => // F = opponent function
m = // m = maximum outcome, initially non-numeric
g = (n, i) => // g is the outer recursive function,
// trying all possible move sequences
i >> n ? // if i has reached the upper bound 2**n:
m // stop and return m
: // else:
g( // do a recursive call:
n, // pass n unchanged
-~i, // increment i
( h = M => // h is the inner recursive function,
// testing a specific move sequence
s = // save the final score in s
n-- && // if n is not 0 (decrement afterwards):
!(p = // compute the player's move p,
i >> n & 1 // which is the n-th bit of i
) + // add not(p)
h( // add the result of a recursive call:
[ ...M, // update M[]
M = F(M), // by adding the opponent's move
// (reuse M to store it)
p // and the player's move
] //
) + // end of recursive call
M * 2 // add twice the opponent's move
)([]) // initial call to h with M[] = []
> m ? 0 : m = s // update m to min(m, s)
) // end of recursive call
```
[Answer]
# [Python](https://www.python.org), 148 bytes
```
lambda g,n:max(product((0,1),repeat=n),key=lambda i:sum([1,3,0,2][k*2+l]for k,l in zip(i,[g(i[:j])for j in range(len(i))])))
from itertools import *
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bY5NTsMwEIX3nMLLmTBVk3QBihQu4noxUDu48Z9cR6I9R3dsIiG4E7eBqNnB6knvR997_0rn8hrD_GH6_edUzObx--rYPx9YDBQ6z2-QcjxMLwWgpgYp66S59AFp1Od-rdruNHmQDe2oplbJsWrvnTIxi5GcsEFcbAJLcgAru6PCJTkufuYwaHA6gEVUiHhncvTCFp1LjO4krE8xF1Gt3_Yp21DAwArmTtZUsZKbRtHud_4nr_-3l7-MTwuZcbtt6QHxxpjnm_4A)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 86 bytes
```
If[#2==0,0,Min@Table[2 #1[#3]-i+1+#0[#1,#2-1,Append[#3,{i,#1[#3]}]],{i,0,1}]]&[##,{}]&
```
[Try it online!](https://tio.run/##XY0xa8MwEIV3/4pHBF58Bkslo0oydiiUUOhwvcFxZSJojFBMFuPf7p6SrTe947733bWfL@Haz3Hot9FvbyMb531HHb3H6fDZn38DOxjL5kXa2NjGdGwsGddaOqYUph@90BLpiawiZenIaqrZGFpWqbePHKeZq5GLH95jWZWBYVYNrChL2Ath9z3t6D/3FecLLxkerlScCNoStIcGFtpN/uHS74M/nm9sNKNeqQKgrsyncA/5Fg5J8OqROemz9HARBn6mMirbSyXbHw "Wolfram Language (Mathematica) โ Try It Online")
Full version:
```
ClearAll;
reward[moves_List] := 2 moves[[2]] - moves[[1]] + 1;
(*Tit-For-Tat*)
oppFuncTFT[moves_List] := If[moves == {}, 0,
moves[[-1, 1]]];
(*Win-Stay,Lose-Switch*)
oppFuncWSLS[moves_List] := If[moves == {}, 0,
With[{prev = moves[[-1]], switch = Abs[# - 1] &},
If[reward[Reverse@prev] >= reward[prev], prev[[2]],
switch[prev[[2]]]]
]
];
totalPlayerReward[oppFunc_Symbol, n_Integer, moves_List: {}] :=
With[{oppNextMove = oppFunc[moves]},
If[n == 0, 0,
Min[
reward[{#, oppNextMove}] +
totalPlayerReward[oppFunc, n - 1,
Append[moves, {#, oppNextMove}]]
& /@ {0, 1}
]
]
];
```
[Answer]
# [Python](https://www.python.org), 68 bytes
```
f=lambda o,n,*M:n and min(3**o(M)-p+f(o,n-1,*M,o(M),p)for p in[0,1])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3XdJscxJzk1ISFfJ18nS0fK3yFBLzUhRyM_M0jLW08jV8NXULtNM0gJK6hkBpHZCIToFmWn6RQoFCZl60gY5hrCbUrI6Cosy8Eo00DaiJiVYGOsaamlwYwkBdWonRhlZWRrGx0bqGsUSqMsWmqrg0VyNR0y4nNQ9I6esb6ZhrQt0D8yMA)
The opponent function uses the same interleaved moves format as [@Arnauld's answer](https://codegolf.stackexchange.com/a/257103/113573), outputs a positive number. I used [pysearch](https://github.com/lynn/pysearch) to find a compact expression for determining the reward.
] |
[Question]
[
The [**least** weird fact about the US presidency](https://xkcd.com/2046/) right now is that there have been two unrelated presidents whose last names start with T-R-U-M.
That made me think, how many US presidents share other combinations of characters? There are obviously two presidents that share the characters "BUSH", and "ROOSEVELT". But did you know there are four presidents who share the characters "BU" (Buchanan, Buren, Bush and Bush), three presidents who share "CL" (Cleveland, Cleveland and Clinton), but only one president whose name starts with an "E" (Eisenhower).
---
# Challenge:
Take a non-empty string as input, and output how many presidents have names starting at those letters. **You may assume that the string will match at least one president**.
That means, you may get inputs such as "J" (Jackson, Jefferson, Johnson and Johnson), "TA" (Taft and Taylor) and "Nixon" (Nixon). You will **not** get inputs such as "Z", "RANT" and "RUMP".
---
### Rules
* The input is on any convenient format, with optional upper or lower case.
* The output should be an integer in the range **1 ... 5**.
* Shortest code in bytes in each language wins
### Test cases
There are three strings that should return 5 (C, H, T), two strings that should return 4 (BU, J), five strings that should return 3 (A, CL, HAR, M, R). There are many strings that should return 2. Where there are parentheses, it means both AD, ADA, ADAM and ADAMS should all return 2, as well as TR, TRU and TRUM. You will not get "TRUT" as input, since that doesn't match a president.
```
5: C, H, T
4: BU, J,
3: A, CL, HAR, M, R
2: AD (ADAMS), BUS (BUSH), CLE (CLEVELAND), F, G, HARR (HARRISON), JO (JOHNSON), P, RO (ROOSEVELT), TA, TR (TRUM), W
1: Every other valid string
```
### Alphabetical list of surnames
```
Adams, Adams, Arthur, Buchanan, Buren, Bush, Bush, Carter, Cleveland, Cleveland, Clinton, Coolidge, Eisenhower, Fillmore, Ford, Garfield, Grant, Harding, Harrison, Harrison, Hayes, Hoover, Jackson, Jefferson, Johnson, Johnson, Kennedy, Lincoln, Madison, McKinley, Monroe, Nixon, Obama, Pierce, Polk, Reagan, Roosevelt, Roosevelt, Taft, Taylor, Truman, Trump, Tyler, Washington, Wilson
-------- Same list (obviously) -----------
'Adams', 'Adams', 'Arthur', 'Buchanan', 'Buren', 'Bush', 'Bush', 'Carter', 'Cleveland', 'Cleveland', 'Clinton', 'Coolidge', 'Eisenhower', 'Fillmore', 'Ford', 'Garfield', 'Grant', 'Harding', 'Harrison', 'Harrison', 'Hayes', 'Hoover', 'Jackson', 'Jefferson', 'Johnson', 'Johnson', 'Kennedy', 'Lincoln', 'Madison', 'McKinley', 'Monroe', 'Nixon', 'Obama', 'Pierce', 'Polk', 'Reagan', 'Roosevelt', 'Roosevelt', 'Taft', 'Taylor', 'Truman', 'Trump', 'Tyler', 'Washington', 'Wilson'
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~179~~ ~~175~~ 173 bytes
```
lambda s:sum(any(s==X[:len(s)]for X in x.split())for x in[A,B,'A CL HAR M R '+B,'ADAMS BUSH CLEVELAND F G HARRISON JOHNSON P ROOSEVELT TA TRUM W M',s])
A='C H T';B='BU J '+A
```
[Try it online!](https://tio.run/##jVNRb9owEH7Pr7g3J8KqtD0y5SGQQkYJoBBGJcqDSxxi1djINh1I@@/MdqB061TtIbrPd9@dz5f79ifTSPH1XMdPZ052zxUB3dWHXUjEKdRx/LjqcipCHa1rqeARmIDjnd5zZsIocq6jda0S3MMogf4YsqSAHApAHedJk3wOvcU8s6H7H/fjZJLCAIaOVXyfTycwmmYTZ2dQTKdzRymhTKAsFjksIUdYr6MgiVEfMijRt16MegsY2erJmcQrfXfY76kKI3CdaNcJSiqy0wjDO6BMc1AO9Q6bhggiWqzoBejmve0TZain9zl9pZyI6h8HJoz06X0pOau21OF7pqlo5M82fcA430nlIwOpfOKQqJpR3mJFhHEgI6piYnuBium28p/4RP1jMilf2/Ijsnm5REe0rqm6HmQjPsIHKgStTg6OmdhI7r05qa435JsHJjj1jFwKJX3fE3Zsw9NnsiMOzBhVGx@bSf7ibEHJtp1pIaV2UzIfDiWpL/bEpW@/VIddm@XQ3oMTb5@2JLqxA7lMeMm463G9DoKK1jALNU6jbgAmXq0D/@eZW0s7zS0N22V1YTjGetVlnS@WBKy2iyqkccS0azrx6mjd1mu6sFf2Z4LGnGkTamrCOjy@rTaYKMIBpL9iFzFREKQeRcF15VAfYZTZr0T21ra7wNdETwLdaL2F5Yw@5dhdxVYp2OkDQ46hQBetuTlEn5b3WsNebPimNgwDDEP8Jjh8VRyGGb5pDlvRYa86DMv/vhPIX9Hzbw "Python 2 โ Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~141~~ ~~140~~ ~~111~~ ~~106~~ 97 bytes
Input is in title case, [114 bytes](https://tio.run/##HY1Bi8IwEIXv/RWDUJKyroJbD1twQQsqwsIiBQ/qITUNjaQTSVJBxN/enXiY973hDfNuj9Ba/BrU4jQY0dVSABZcjZZSdH7V@7Y0zb0xAuV6sxXOaW9xZ1sk/O2t9TEMlahc3x2eWOT5a1kaOvzdx@37tep35bYaTZzSKDlOgg6m4VmWTeezj9kQGh88LODILmzMWppAU0cvSC6GRMhor1QaYyqKeBh2ThJlHcQXoPFNXyQAN6cxcJbmHj5/IJUMUuAxHYN6k9qHfw) with lowercase input.
-5 bytes thanks to [Value Ink](https://codegolf.stackexchange.com/users/52194/value-ink).
```
lambda n:(f"AdamsBushCleveFGHarriJohnsPRooseTaTrumW{0:31}AClHarMR{0:36}BuJCHT".rfind(n[:5]))/39+2
```
[Try it online!](https://tio.run/##VY1Ra8IwFIXf@ysuQknKtG5WBQsKteBEEIYUfHA@RJPQSJpIkg5k@NuzxLdduOeewwf33B@u1arwfPntJekulIAqMR9UlHR23du2luyHbT63xBix062yXwetLWtIY/ru@PteFh/PqpaB7w8xzZ/rfldvm0FuuFAUq1M5O2fZuFi8Tbxj1llYwgld0RC1YV3YS/QkyFUGITTaW6iKOJS8qDExPSQ6JwnXBuInEOp1bZkA3I1QDqN0amG0gpQiSAFHmjvhJMPZEPi/HMb/AQ "Python 3 โ Try It Online")
[Answer]
# JavaScript (ES6), ~~109~~ ~~105~~ 102 bytes
Expects the input string in title case.
```
s=>-~"CHT4BuHaJ3AClHarMR2AdamsBushCleveFGHarriJohnsPRooseTaTrumW1".match(s.slice(0,5)+'.*?(\\d)|1')[1]
```
[Try it online!](https://tio.run/##PZFbb9owFIDf@RVWX5IMsMZuD0PpVKLSiI4VISQegIdT54S4OHZlJ3TR2v115ku6F5/vXH0uT3AGwzR/bsZSFXgp04tJr8d/r7J882XW5rD4fJOJHPRy/emmgNrMWlNlAs84v7NWzReqkma1VsrgBja6rbeTK1pDw6rYUCM4w/jj6GsyjOiHH/F@XySvkyjZTQ6X6Y5EvmI0sqCbqtWOZi2rQIIMrLEHUzmZgW7Qh/kWBMgiKFw2ykdmSgleHNHxLTcoK/USMuZciFpp75kr7RPvQJccRWANsnFgxyq4PPaouQmVc@jQ95ordQ4lF8BOvXeBZYn6XXE7CXiPUmLROfzJJVPCW5dQvJddsnsuBfqIpZJa@QZ/8d/B/fAINThYcdTM@1ZKnJxcIxzDnvz27Tp8@xsoe9kJ5dt0VwmBjp49dCKMsAVT2WH77W25cG2Rw4CWSt@COyJJr8mOUmoO/23M2U7Y7QwZpoQdSEomI2IjSRQlI@ex@OctGQxsRiyt8m1KxmM5TQhTdjMCqVBH6xiS6Pve/jckD49PyBpqU01sn4SWXNhTh@/L2CQkTYlMXIZNSC7/AA "JavaScript (Node.js) โ Try It Online")
### How?
We use a lookup string holding prefixes between 1 and 5 characters, along with digits describing the corresponding number of occurrences:
```
"CHT4BuHaJ3AClHarMR2AdamsBushCleveFGHarriJohnsPRooseTaTrumW1"
{5-}{4---}{3------}{2-------------------------------------}
```
We use the following regular expression on this string and apply `-~` on the second entry returned by `.match()`:
```
/**PREFIX**.*?(\d)|1/
\____/\_/\__/\/
| | | |
the 5 first characters of the input ----+ | | |
the shortest possible string (lazy match) ---+ | |
a digit (captured) -----------------------------+ |
fallback: look for '1' instead (last character) ---+
```
*Examples:*
* `"C"` โ `['CHT4', '4']` โ `-~'4' = 5`
* `"Har"` โ `['HarMR2', '2']` โ `-~'2' = 3`
* `"Lincoln"` โ `['1', undefined]` โ `-~undefined = 1`
[Answer]
# [R](https://www.r-project.org/), 156 bytes
```
function(k)max(which(mapply(grepl,z<-paste('',k),c(z,' ADAMS BUSH CLEVELAND F G HARRISON JOHNSON P ROOSEVELT TA TRUM W',' A CL HAR M R',' BU J',' C H T'))))
```
[Try it online!](https://tio.run/##dVI9b9swEN31Kw7oIAlQhgxZgnSwnQ/XiT8gO80QZKDpk0WYItUj5Vgp8tsdkpKBtGm13Du@d8fj6dGx@H4sGsWt0CrZpRU7JK@l4GVSsbqWbbIlrGX2dnVWM2MxieNsl2Y8ectiGFwPpksYPi7HMHq4@XnzMJhdwy3cwXiQ5z@W8xlM5uOZjwvI5/Oll6xgNYBV/jiFp9i3cJVeDlPIfT58hImPIxjDKk7dd/wGllqhtsCkhFobI9ZCItSEhTigAauBl8h3IAqwJQKhaaQFYYBrIuQWosiVzljlxFdnTt/UNVLCk3iwYZWJM/gEyJYNeTRseMkUUx0m7IEpP8cRI4tBPpK4R8nU5h@JUFaH8pHWUmy26PGNMKhK/dqV3wopK02BudUUCu8YFQJlh4kp68GY0cYto4ckTNf5T9xieMxY633XfsL4rmcnWBRIp0SX6iu8R6Vw03r4IBTXMpxO2eZ0w5TfCyUxKKZakQ5zz8Sho@drVjEPFgKJB26h5c7HHNm222mutfFbsl@SFSv62Eodxl9RU3VVHtUBtLJ72hMzpVtIv@EnIf2MaRpFnUGG7Zzzhsj/eYM2uCDZO1doSmIpjLvpIs3OLy/SqHBHyvEgFJwMk/6OADwh/On5pXKm6FRpoKD3YWjfrI3tyOw8E2mgtb/ds0XSK9NPZafpnp@D7uXFKxslfjXo/PkfTXZq5Du9R@/@qc5if8nT4wc "R โ Try It Online")
Inspired by @TFeld Python 2 solution
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~132 100~~ 92 bytes
```
->s{1+"AdamsBushCleveFGHarriJohnsPRooseTaTrumWAClHarMMRBuBuJJCCHHTT".scan(/#{s[0,5]}/).size}
```
[Try it online!](https://tio.run/##bZHBTsJAEIbvPgXBAxqx4MGjJtAITbFKSBMOpIehndIN21ncbZEKPHtld0uCwdN8039nOvOPLJdVnb7Uj69q//TQHiSQq2GpMpfjFkdjD6RkvshITWdCKAwhlGU@H7j8pATBbFgOS993Xc8Lw7ajYqC73u1eLfrd5@jYu3cU@8FjveiYvp1u6wJkkZVS07CMMyAgyxIbUNlldEEWaJ6byThQ8k/CqBCm3BWCs2SFmt@YQsrEty0fMc5zIY0yEtIUjkGmDLllCVRoOC2YMFo1KJmynf9yhWYZT4itbe9DvG5UH9MU5TnRHl7hBIkwqTS@M4oFN18DSM5/COIJI47mRSBICjP3B9tZ@XMJOWiYMpSx0aaCr3WcIaysp@ZwJ5eKqySEtIkVF2Z8fV1bpWljoOJ2tTmo7GRI4/CccT1j5JTEvpwcNvvD7nCzMxd3Cpaj2h/osGktdou@41DUbaVnjKLjzbH@BQ "Ruby โ Try It Online")
] |
[Question]
[
A recent [question](https://mathematica.stackexchange.com/questions/38076/how-to-plot-a-figure-like-this) showed how Mathematica could be used to make a beautiful optical lattice clock image. The image looks like this.

This challenge is to reproduce this image as closely as possible using as short code as possible using only easily available open source tools (and without just downloading the image or parts of it).
**Rules** As it is not reasonable to ask for a pixel by pixel reproduction this is a popularity contest. However, please up-vote code that is a short (in the style of code-golf) and which produces an accurate and beautiful reproduction of the image.
[Answer]
### [POV-Ray](http://www.povray.org/), 512 characters
Here's my try. I didn't manage to replicate the lighting, so I've decided to keep the variation of highlight positions rather than to put the lights further away to keep the background brighter.
The area shadow is rather low-quality. I might as well turn it off completely (and save precious characters), but if someone is willing to donate some computing power and crank up the shadow quality and/or the dither quality, I'll gladly accept.
```
#include"functions.inc"
camera{location<-3,5,-6>right x look_at 0 focal_point 0 aperture 1 blur_samples 9}
#macro s(p)sphere{pi*p+y/3 1 pigment{rgb<2,8,2>/9}finish{phong .5 phong_size 5 specular 1 roughness .001}}#end
#macro l(p,c)light_source{p c/8 area_light 9*x,9*z,3,3}#end l(<6,6,0>,<8,4,8>)l(<0,6,0>,<4,8,8>)
isosurface{function{y/3+pow(cos(x)*cos(z),2)/2}contained_by{box{-9,100}}pigment{tiling 1 color_map{[.9 rgb 1][1 rgb 0]}scale .5/pi}}
s(0)s(<0,0,-1>)s(<-1,0,0>)s(<0,0,2>)s(<2,0,1>)s(<2,0,3>)
```
### Result:

### ungolfed:
```
#version 3.7;
#include "functions.inc"
global_settings{assumed_gamma 1}
camera{
location <-3,5,-6>
right x //set the aspect ratio
look_at 0
focal_point 0 aperture 1 blur_samples 9
}
#macro l(p,c) // position, color
light_source{
p c/8
area_light 9*x,9*z,3,3
}
#end
l(<6,6,0>,<8,4,8>)
l(<0,6,0>,<4,8,8>)
isosurface{
function{y/3+pow(cos(x)*cos(z),2)/2}
contained_by{box{-9,100}}
pigment{
tiling 1
color_map{[.9 rgb 1][1 rgb 0]}
scale .5/pi
}
}
#macro s(p) //position
sphere{
pi*p+y/3 1
pigment{rgb<2,8,2>/9}
//phong for the wide highlights, specular for the small ones.
finish{phong .5 phong_size 5 specular 1 roughness .001}
}
#end
s(0)
s(<0,0,-1>)
s(<-1,0,0>)
s(<0,0,2>)
s(<2,0,1>)
s(<2,0,3>)
```
P.S.: I've only counted the five line-breaks to round the character count to a perfectly round number.
] |
[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/8405/edit).
Closed 6 years ago.
[Improve this question](/posts/8405/edit)
## Calculate the determinant of an n x n matrix.
### Rules
* read matrix from standard input
* write to standard output
* do not use ready solutions from library or language
* input: columns separated by any space char
* input: lines separated by cr and/or lf
### Winner
* The shortest code :)
[Answer]
## GolfScript, 58 chars
```
n%{~]}%{[.!{(.,,0\{:^2$=-1^?*3${.^<\^)>+}%d*+}/}or])\;}:d~
```
A straightforward recursive algorithm using [Laplace expansion](http://en.wikipedia.org/wiki/Laplace_expansion).
Example input (random 5 ร 5 matrix):
```
-562 40 43 -586 347
-229 177 305 -367 50
-434 343 241 -365 -86
-3 -384 -351 61 -214
-400 96 -339 25 -116
```
Output: `282416596900` ([Online demo](http://golfscript.apphb.com/?c=OycKLTU2MiAgIDQwICAgNDMgLTU4NiAgMzQ3Ci0yMjkgIDE3NyAgMzA1IC0zNjcgICA1MAotNDM0ICAzNDMgIDI0MSAtMzY1ICAtODYKLTMgICAtMzg0IC0zNTEgICA2MSAtMjE0Ci00MDAgICA5NiAtMzM5ICAgMjUgLTExNgonCm4le35dfSV7Wy4heyguLCwwXHs6XjIkPS0xXj8qMyR7Ll48XF4pPit9JWQqK30vfW9yXSlcO306ZH4%3D); [Verify with Wolfram Alpha](http://www.wolframalpha.com/input/?i=det+[[-562%2C+40%2C+43%2C+-586%2C+347]%2C+[-229%2C+177%2C+305%2C+-367%2C+50]%2C+[-434%2C+343%2C+241%2C+-365%2C+-86]%2C+[-3%2C+-384%2C+-351%2C+61%2C+-214]%2C+[-400%2C+96%2C+-339%2C+25%2C+-116]]))
The code consists of three parts:
* `n%{~]}%` parses the input,
* `{[.!{(.,,0\{:^2$=-1^?*3${.^<\^)>+}%d*+}/}or])\;}:d` defines a recursive subroutine to calculate the determinant, and
* the final `~` applies the subroutine to the input.
I'm sure there's room for improvement in this code, but at least I beat [Gareth](https://codegolf.stackexchange.com/a/8407) by three chars. Also, `{:^2$=` is a pretty nice GS smiley. :)
[Answer]
## Haskell, ~~139~~ 131
```
(a:r)%0=r;(a:r)%n=a:r%(n-1)
d[]=1;d(f:r)=foldr(\(j,x)->(x*d(map(%j)r)-))0$zip[0..]f
main=interact$show.d.map(map read.words).lines
```
[Answer]
# Python 233
```
def d(x):
l=len(x)
if l<2:return x[0][0]
return sum([(-1)**i*x[i][0]*d(m(x,i))for i in range(l)])
def m(x,i):y=x[:];del(y[i]);y=zip(*y);del(y[0]);return zip(*y)
x=[input()]
for i in (len(x[0])-1)*[1]:x+=[input()]
print d(x)
```
### Ungolfed:
```
def det(x):
l = len(x)
if l == 1:
return x[0][0]
return sum([(-1)**i*x[i][0]*det(minor(x,i+1,1)) for i in range(l)])
def minor(x,i,j):
y = x[:]
del(y[i-1])
y=zip(*y)
del(y[j-1])
return zip(*y)
def main():
x = [input()]
for i in range(len(x[0])-1):
x += [input()]
print det(x)
if __name__ == '__main__':
main()
```
## Usage
As requested, input is on stdin and output is to stdout.
I interpreted columns separated by any space char to mean that I can use comma delimited numbers. If this is not the case, I will rework my solution.
This could be about 30 characters shorter if I could specify my input matrix in the form [[a,b,c],[d,e,f],[g,h,i]].
```
./det.py
1,-4,9
-6,7,3
1,2,3
```
Result
```
-240
```
The determinant is found using [Laplace Expansion](http://en.wikipedia.org/wiki/Laplace_expansion)
[Answer]
# Python, 369
This is ridiculously long, but I thought I'd provide a solution that implements the [Leibniz formula](http://en.wikipedia.org/wiki/Determinant#n-by-n_matrices).
```
def f(l):
if len(l)==1:return [l]
a=[]
for s in l:
for p in f(list(set(l)-set([s]))):a+=[[s]+p]
return a
def s(a):
n=1
for i in range(len(a)):n*=(-1)**(a[i]>i);a[a.index(i)]=a[i];a[i]=i
return n
m=[map(int,w.split(','))for w in raw_input().split(' ')]
r=range(len(m))
print sum([reduce(lambda x,y:x*y,[m[p[i]][i] for i in r],1)*s(p) for p in f(r)])
```
Values are read from stdin in a format like `1,2,-3 7,0,4 -1,-3,0` with a single space between columns. I wouldn't have posted this, but it was fun to write and contains a couple interesting sub-problems. The function f generates all permutations of n elements, and the function s determines the parity of those permutations.
[Answer]
## Python, 198
This also uses the Liebniz formula. I'm using a heavily-modified version of [ugoren's permutation solution](https://codegolf.stackexchange.com/a/5058/2180) to generate permutations and their inversion counts simultaneously. (edit: now correct!)
```
t=input()
e=enumerate
p=lambda t:t and((b+[a],j+i)for i,a in e(t)for b,j in p(t[:i]+t[i+1:]))or[([],0)]
print sum(reduce(lambda t,(i,r):t*r[i],e(p),1-i%2*2)for p,i in p([t]+[input()for x in t[1:]]))
```
[Answer]
## J, 61 characters
```
-/>([:+/#(([{.<:@[}.])[:*//._2,\2#])])&.>(|.;])".];._2[1!:1[3
```
A big ugly bit of code that takes its input from stdin (if you're running this on Windows you may need to change `".];._2[1!:1[3` to `".}:@];._2[1!:1[3` to ensure both character return and line feed are removed).
```
-/>([:+/#(([{.<:@[}.])[:*//._2,\2#])])&.>(|.;])".];._2[1!:1[3
1 8 5
2 7 3
9 9 4
_72
-/>([:+/#(([{.<:@[}.])[:*//._2,\2#])])&.>(|.;])".];._2[1!:1[3
_2 2 3
_1 1 3
2 0 _1
6
```
Of course, no-one using J would ever bother to do this. They'd just use:
```
(-/ .*)".];._2[1!:1[3
```
making use of the `.` [determinant](http://www.jsoftware.com/help/dictionary/d300.htm) verb.
[Answer]
# Dyalog APL, 53 ~~58~~ ~~59~~ characters
```
{1=โขโต:โโตโ-/โต[1;]รโยจ{w[f~1;f~โต]}ยจfโโณโโดwโโต}Uโชโ{โ}ยจ1โโณโดUโโ
```
I'm pretty late to the party here.
**Please**, alert me if there are any issues with this code!
Takes negatives as input via ยฏ (the APL negative sign). I *think* values by default go to STDOUT in APL, but I may be wrong.
Uses Laplace expansion to find the determinant of the matrix.
This program is separated into three main parts: an input section, and the case of a 1x1 matrix, and the actual recursive function.
Input program:
```
Uโชโ{โ}ยจ1โโณโดUโโ
โ - Takes evaluated input, space separated numbers are vectors in APL.
Uโ - Stores the input into variable `U`.
โณโด - The array of integers from 1 to the length of `U` (inclusive).
1โ - Drops the first element of the result.
{โ}ยจ - Receives a new input for each element in the vector. (Result is a vector of vectors)
โ - Transforms the vector vector into a 2D-array.
Uโช - The original line was stored then used for its length, so we stick it on top of the new array.
```
1x1 case:
```
{1=โขโต:โโตโ...}
โต - The input
โ - The first element of the input
: - Return that if and only if ...
โขโต - The largest dimension of the input matrix
1= - Has equality with 1.
โ - Statement separator
{ } - Function enclosure brackets.
```
Actual determinant program:
```
{...-/โต[1;]รโยจ{w[f~1;f~โต]}ยจfโโณโโดwโโต}
wโโต - The input stored in `w`
โด - The dimensions of `w`
โ - The first dimension
โณ - 1 to the result of last operation
fโ - Store the result in `f`
{ }ยจ - Do what is inside the brackets to each member of `f`
w[f~1;f~โต] - Return the minor matrix.
โยจ - Find determinant of each element (recursive)
โต[1;]ร - Multiply elementwise by the first row of the input matrix
-/ - Reduction using subtraction, since APL evaluates right to left, it comes out to be + - + - ...
```
[Answer]
## Python, 181 characters
Late to the party, but here's a simple 181 character implementation of Laplace:
```
l,r=len,range
d=lambda A:sum((-1)**i*A[0][i]*d([[A[x][y]for x in r(1,l(A))]for y in r(i)+r(1+i,l(A))])for i in r(l(A)))if len(A)>1 else A[0][0]
print d(map(eval,iter(raw_input,'')))
```
This meets the specs if "any space character" includes commas, which seems to be the norm here. Otherwise,
```
l,r=len,range
d=lambda A:sum((-1)**i*A[0][i]*d([[A[x][y]for x in r(1,l(A))]for y in r(i)+r(1+i,l(A))])for i in r(l(A)))if len(A)>1 else A[0][0]
print d(map(lambda x:map(int,x.split(' ')),iter(raw_input,'')))
```
is 207 characters.
Input is terminated by entering a blank line.
[Answer]
# [Jq 1.5](https://stedolan.github.io/jq/), 171 bytes
This is a golf-ed version of `det` from rosettacode [Matrix arithmetic - jq](http://rosettacode.org/wiki/Matrix_arithmetic#jq).
```
def d:if[paths]==[[0],[0,0]]then.[0][0]else. as$m|reduce range(length)as$i(0;.+({"0":1}["\($i%2)"]//-1)*$m[0][$i]*($m|reduce del(.[0])[]as$r([];.+[$r|del(.[$i])])|d))end;d
```
Original
```
def except(i;j):
reduce del(.[i])[] as $row ([]; . + [$row | del(.[j]) ] );
def det:
def parity(i): if i % 2 == 0 then 1 else -1 end;
if length == 1 and (.[0] | length) == 1 then .[0][0]
else . as $m
| reduce range(0; length) as $i
(0; . + parity($i) * $m[0][$i] * ( $m | except(0;$i) | det) )
end ;
```
Alterations:
* replace base case condition with `[paths]==[[0],[0,0]]`
* replace `parity($i)` with `({"0":1}["\($i%2)"]//-1)`
* replace `except(0;$i)` with inline definition
* replace `det`,`row` with `d`,`r` and remove whitespace
[Try it online!](https://tio.run/##bY9dT4MwFIbv9ysagkk7KaMFnW7ZL6m9ILYbNawgH/FC/OviW8f0ZklP0nPepw@ct/dZESUSInWyIkTlCSk0rhhyiWlCeH5JOCAcsrQhypCKhf7NZMhRxcIUuD@gHlHbZbbF/Qn1DF12mQmIRNDjvcivQgxvSv@EV9EtCWrhBXgBXoAX4MXCS/AyLB7WBC@x92qajT0Ss3NH1ZZD1evDQSn8pcqSTOuhsj5Fi2Pr3qak7OPz1FkzvlrSlf5kaW39aagYAkezfXpPP6Ms2okvFb3Q2N1JFunNhgu2js9BFDu9pv8OY2saPsCUhqGjSkOh4m66BKCZZpNhzHqzN/P83bSDa3w/c@7HuubOt@OApis/eDMOaH4A "jq โ Try It Online")
] |
[Question]
[
## Task
>
> Given a list of integers *a1, a2, โฆ, ak* (*k* โฅ 2) and a positive integer *m*, write a function or a complete program that calculates the next *m* numbers of the list. Assume that *ai = P(i)* where
>
>
> *P(x) = bk-1 xk-1 + bk-2 xk-2 + โฆ + b0*
>
>
> is the unique polynomial of minimum order which fits the points.
>
>
>
## Description
### Input
If the code is a function, input is given by an integer *k*, an array *a1, a2, โฆ, ak* and an integer *m*.
If the code is a program, input (through stdin) is given by space-separated *k a1 a2 โฆ ak m*.
You can assume that *k* โฅ 2 and *m* > 0.
### Calculation
(Of course, the code can calculate the result in different way, but the result should be same.)
Find the polynomial *P(x)* which satisfies *ai = P(i)* for all 1 โค *i* โค k and has a degree of (no more than) *k*ย -ย 1. For example, if a list is `1,2,3,4,5`, then *P(x) = x*. If a list is `1,4,9,16,25`, then *P(x) = x2*.
Then, calculate *ak+1 = P(k+1), ak+2 = P(k+2), โฆ, ak+m = P(k+m)*. These are the results.
### Output
If the code is a function, return an array [*ak+1, ak+2, โฆ, ak+m*].
If the code is a full program, print those numbers to stdout, separated by an any character you want.
[Answer]
## Golfscript, 46 42 40 38 chars
```
~])\({[{.@-\}*])\}*;]-1%){0\{+.}/p]}*;
```
This uses a simple difference table approach, which is described in more [detail](http://www.cheddarmonk.org/golfscriptblog/2011/12/code-dissection-polynomial-extrapolation.html) on my GolfScript blog.
[Answer]
## Maple, 41 chars
```
c:=(k,a,m)->interp([$1-k..0],a,x)$x=1..m;
```
For example, `c(3, [1, 2, 4], 4)` returns `7, 11, 16, 22`.
This function interprets the spec literally, taking both `k` and `a` as separate arguments. If the list `a` does not have exactly `k` elements, an error occurs. For convenience, here's a 45-char version that omits `k` from the argument list:
```
c:=(a,m)->interp([$1-nops(a)..0],a,x)$x=1..m;
```
I was first thinking of trying this in Perl, but hell, let's use the right tool for the job.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes, language postdates challenge
```
Iร;@แธข+\รธแนโนยตL?
รงUแธฃU
```
[Try it online!](https://tio.run/nexus/jelly#ASsA1P//ScOfO0DhuKIrXMO44bmB4oG5wrVMPwrDp1XhuKNV////WzEsMiw0Xf80 "Jelly โ TIO Nexus")
Jelly's functions only support up to two arguments, so I don't take in *k* (which is redundant) as an argument. I hope that's acceptable. The program defines a function `2ล` that obeys the specification in the question.
## Explanation
**Helper function** `1ล` (takes input ฮป, ฯ, and expands ฮป by ฯ elements):
```
Iร;@แธข+\รธแนโนยตL?
รธ ยต ? If
L {ฮป} is nonempty,
then:
I take differences of consecutive elements of {ฮป};
ร call 1ล recursively on this value and {ฯ};
;@ prepend
แธข the first element of {ฮป};
+\ and take the cumulative sum {and return it}.
Otherwise:
แนโน {return} {0} repeated ฯ times.
```
This is fairly magical in the way in which Jelly happens to pick out the exactly values I need it to operate on at every stage. Some of it is the result of me manipulating things; in particular, the unusual choice `รธ` for the separator (rather than the more usual `ยต`) means that all implicit arguments are set to 0, which is fairly handy in this case. However, I have no idea why `;@แธข` parses the way it does, but it seems to workโฆ
**Main function** `2ล` (takes input ฮป, ฯ, and returns the next ฯ elements of ฮป):
```
รงUแธฃU
รง Call 1ล on {ฮป} and {ฯ};
U reverse it;
แธฃ take the first {ฯ} elements;
U and reverse it {and return that value}.
```
This is just massaging the output into the form requested (if we were allowed to return the terms we were already given, that would remove a whole 5 bytes). Jelly doesn't have a "last n elements" function; of the various ways to synthesize it out of other functions, `UแธฃU` is convenient here because it happens to pick up ฯ as a default argument.
[Answer]
### Golfscript, 51 characters
Similar approach to Peter's one.
```
~])\-1%[{(.@{.@\-}%\;.,}do;]-1%\[0]\*\{\{+.}%\;}%;p
```
When run on input
```
2 3 12 35 78
4
```
it yields the result
```
[147 248 387 570]
```
There are still possible places where the solution might be golfable further.
[Answer]
# Scala, 128 bytes
```
m=>Stream.iterate(_)(a=>a.tail.lazyZip(a)map(_-_)).takeWhile(Nil!=).:\(Seq.fill(m)(0))((a,b)=>b.scanLeft(a(0))(_+_))takeRight(m)
```
[Try it online!](https://scastie.scala-lang.org/O7mS7rrXSMCrvzTttt4L8w)
] |
[Question]
[
When you roll a die, you have a 6:1 chance of any given option.
There's a bookmaker taking bets on die rolls. He owns ยฃ20 at the start of the game.
The bookmaker offers odds of 4:1, but gamblers take it, because there's money on offer.
There are 10 gamblers. A, B, C, D, E, F, G, H, I, and J. Each gambler owns 10 pounds sterling.
Each round, the 10 gamblers each bet ยฃ1 on a die roll, if they have any money left.
* If they win their bet, ยฃ4 is transferred from the bookmaker to the gambler.
* If they lose, ยฃ1 is transferred from the gambler to the bookmaker.
The game ends in either of these conditions:
* The bookmaker runs out of money, or is in debt.
* All of the gamblers have run out of money.
We should see the result presented as a series of tables, like so:
```
Turn 1
Roll: 2
| | Bookie | A | B | C | D | E | F | G | H | I | J |
| Start money | 20 | 10 | 10 | 10 | 10 | 10 | 10 | 10 | 10 | 10 | 10 |
| Bet | n/a | 1 | 3 | 2 | 1 | 2 | 4 | 6 | 5 | 2 | 4 |
| Balance change | -2 | -1 | -1 | +3 | -1 | +3 | -1 | -1 | -1 | +3 | -1 |
| End money | 18 | 9 | 9 | 13 | 9 | 13 | 9 | 9 | 9 | 13 | 9 |
Turn 2
Roll: 4
| | Bookie | A | B | C | D | E | F | G | H | I | J |
| Start money | 18 | 9 | 9 | 13 | 9 | 13 | 9 | 9 | 9 | 13 | 3 |
| Bet | n/a | 1 | 2 | 3 | 4 | 5 | 6 | 1 | 2 | 3 | 4 |
| Balance change | +2 | -1 | -1 | -1 | +3 | -1 | -1 | -1 | -1 | -1 | +3 |
| End money | 20 | 8 | 8 | 12 | 8 | 12 | 8 | 8 | 8 | 12 | 12 |
```
When a gambler runs out of money, they can't bet any more. Their bet is 0.
turn 20
roll: 5
```
| | Bookie | A | B | C | D | E | F | G | H | I | J |
| Start money | 180 | 3 | 1 | 12 | 4 | 0 | 1 | 3 | 6 | 23 | 1 |
| Bet | n/a | 1 | 2 | 3 | 4 | 0 | 6 | 1 | 2 | 3 | 4 |
| Balance change | +2 | -1 | -1 | -1 | +3 | 0 | -1 | -1 | -1 | -1 | +3 |
| End money | 20 | 8 | 8 | 12 | 8 | 0 | 8 | 8 | 8 | 12 | 12 |
```
---
Write some code to model this game, and display the results in a table:
* Use any language
* The gamblers can change their bet each turn, always bet on the same number, all bet on the same number. As long as each turn they bet on one number from 1 to 6.
* The die roll must be a random integer from 1 to 6. Use a typical, vernacular definition of random.
* The end money from one turn is the start money of the next turn.
* The balance change for the bookie is the sum of the other balance changes.
* Each turn your program should output:
+ Which turn we are on
+ The resulting die roll
+ The starting balance, die roll, balance change, and ending balance for the bookie and all ten gamblers, as an ascii table.
* Attempt to do so in the fewest bytes.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~548~~ ~~516~~ ~~511~~ ~~485~~ ~~453~~ ~~397~~ ~~396~~ ~~392~~ ~~372~~ ~~325~~ ~~323~~ 260 bytes
```
f=(i=!(b=20,p=10))=>b*p>0?`T:${++i} R:${(r=0|Math.random()*6)+1}
| |Book|A |B |C |D |E |F |G |H |I |J |
|Stt${(d=(n,s)=>`|${n}`.padEnd(5)+`|${s}`.padEnd(3).repeat(10)+`|
`)(b,p)}|Bet${d('n/a',1)}|Chg${d(u=r?'+10':-40,v=r?-1:'+4')}|End`+d(b+=+u,p+=+v)+f(i):''
```
[Try it online!](https://tio.run/##RY7NTsMwDIDvfQojTYqzpKWFwaFSNrEx/iQuwAM0XdqtMJKo7XqZ@@wlO3Hxz2frs7/1oLtd2/g@ts5U01QrbNQVluomlV5lKedqWc79Ml0VX/nsLEQzwkcosFUpvev@kLTaGveLfH7PRTZGBAC0du6HHkIG2gA9Am2BnoCegV6AXoHegCL67PvgMQqt7MKVgmZnOxaJ12ZrDd5xcSHdP7nlSVv5SvcY3grDqOBYSs9HWlfBZJDZa81kFsDmsL@Ak2pXTGQpy@NFKofQxVnOxIKFlWAshMFSKHGSPsSBixobnjM27Zzt3LFKjm6PNXI@/QE "JavaScript (Node.js) โ Try It Online")
*-32 something bytes by shortening row labels. Also fixed the dice roll being 0-5, not 1-6*
*-5 bytes by compacting output format*
*-26 bytes because padding*
*-32 bytes because whitespace is the devil*
*-56 bytes thanks to ASCII-only and Luis Felipe in [chat](https://chat.stackexchange.com/rooms/240/the-nineteenth-byte)*
*-1 byte because `return x` doesn't need to be on a new line*
*-4 bytes thanks to some small refactors from ASCII-only*
*-20 bytes thanks to more collaboration in chat and some changes by Kevin Cruijssen*
*-47 bytes because `y` was the devil and ASCII-only performed an exorcism*
*-2 bytes because ASCII-only is a golfing machine*
*-63 bytes thanks to the work of several people in the comments*
The golf I took was calculated, but man am I bad at golf.
Almost looks like python rather than JS because where possible I used newlines in place of semicolons for readability.
All gamblers always bet on 1, so we only need to store 1 gambler balance (`p`), the bookie's balance is `b`.
## Explanation time
I need to rewrite the explanation to match the 260 byte version, but check the revision history for the lengthy explanation of the 323 byte version.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 248 bytes
```
โยฒโฐฮธโ๏ผฅฯฯฮท๏ผทโงโบฮธโฐโฮทยซTurn: ๏ผฉ๏ผฌโ๏ผฏฯ
ฯโธฟRoll: โโโฝโถฮถ๏ผฉฮถโ{โงด&๏ผคC๏ผบJ๏ผทโบBโจโ๏ผซBgUโโฆโโชซโฆฮฑฯ | ๏นช |โธฟ| Start |%7d |ฮธโชซ๏ผฅฮทโง๏ผฉฮบยณ |โ๏ผฅฮทโงฮบโโฝโถฮตโ{โโงโโโ
โ/s?โจVp2S>โโชซฮต | โโป๏ผฌฮฆฮตฮบรโด๏ผฌฮฆฮตโผฮบฮถฮด |โธฟ| Change |โงโบโฆ+โบฮดโฐฮดโท | โชซ๏ผฅฮตโโผฮบฮถ+3โฮบ-1โบ โฐ | โฆโบฮดฮธ๏นช |โธฟ| End |%7d |ฮธ๏ผต๏ผญฮทโปฮบโงยงฮตฮปโจยฌโผยงฮตฮปฮถยฑยณโชซ๏ผฅฮทโง๏ผฉฮบยณ |ยฆ |โธฟโธฟ
```
[Try it online!](https://tio.run/##lVNfT9swEH8en8KyNOksgkTXaUjjqURsYqJQsT72xaqPJopjt44zoOs@ezjXaZu0vCxPyd359@@ceSbd3ErdNKOqyhcGvlwmbCWuz9rPsVzCgEqDS5GwjOovWa6Rwcgo@OlQenSwSljojuVrXtYlZEII9vfs08TlxgOf1s58Z5yOtpVUVh7u0Sx8BpO6yh6X6KS3DuqEvdDZwySfuSerdXu6VXRn5g5LNB4VPEmjbAnfBNGvjxjWfaCZ27D22bAba4sc6aWr65fNDaRvc41pZpcgW9M8jh3mxlbV2gLVA@ZvL50nzM9Xim14yO4IMSSYJWwi1T0@t9oKwh2KCB6hO3HTcEi3SNjHVsM57HiLOm7QR297kyfesGdmx5ibutqt40euw0JpsAgs07zECr4m7KR9u6qlroLGtYiK1ImiNJNmgcHgvrMLYaKJc2y1An5Ome0ukgoXaYuVsCvRAzwxE5IiIVN0Rro36Aoim@dDfuhRkV8MqLCl5Yxvadr42zQILgay10cy4p/w4dpvjdqm3F87oaS2LGlVYYsx2iKuc@TvjMLXoFkT86ODB@t3so@a66DtARcUCgxF75f4jyvVWcbMhfj@NU1z8Ue/Aw "Charcoal โ Try It Online") Link is to verbose version of code. Explanation:
```
โยฒโฐฮธ
```
The bookie starts with ยฃ20.
```
โ๏ผฅฯฯฮท
```
Create an array of 10 ยฃ10s for the gamblers.
```
๏ผทโงโบฮธโฐโฮทยซ
```
Repeat the rest of the program while the bookie and at least one gambler have any money left.
```
Turn: ๏ผฉ๏ผฌโ๏ผฏฯ
ฯ
```
Print the current turn by pushing a value to the predefined empty list and taking the resulting length.
```
โธฟRoll: โโโฝโถฮถ๏ผฉฮถ
```
Generate and print the next roll.
```
โ{โงด&๏ผคC๏ผบJ๏ผทโบBโจโ๏ผซBgUโโฆโโชซโฆฮฑฯ
```
Print the header row.
```
| ๏นช |โธฟ| Start |%7d |ฮธโชซ๏ผฅฮทโง๏ผฉฮบยณ |
```
Print the starting balances.
```
โ๏ผฅฮทโงฮบโโฝโถฮต
```
Generate the 10 bets (or 0 if the gambler has no money left).
```
โ{โโงโโโ
โ/s?โจVp2S>โโชซฮต |
```
Print the bets.
```
โโป๏ผฌฮฆฮตฮบรโด๏ผฌฮฆฮตโผฮบฮถฮด
```
Calculate the bookie's change in balance.
```
|โธฟ| Change |โงโบโฆ+โบฮดโฐฮดโท | โชซ๏ผฅฮตโโผฮบฮถ+3โฮบ-1โบ โฐ |
```
Print the bookie's and gamblers' changes in balance.
```
โฆโบฮดฮธ๏นช |โธฟ| End |%7d |ฮธ
```
Update and print the bookie's balance.
```
๏ผต๏ผญฮทโปฮบโงยงฮตฮปโจยฌโผยงฮตฮปฮถยฑยณโชซ๏ผฅฮทโง๏ผฉฮบยณ |ยฆ |โธฟโธฟ
```
Update and print the gamblers' balances.
[Answer]
# [Kotlin](https://kotlinlang.org), ~~468~~ 432 bytes
I'm definitely going to try this another way as I'd like it to be around 300. However, it works. Player 1 wins by magically always picking the winning number.
-36 bytes for various golfs I missed last night including @Mayube's fixed bet on 1,
```
{var o=""
val n=Random()
val m=Array(11){10}
m[0]=20
var t=0
val f={d:Int->o+="%3d|".format(d)}
while(m[0]>0){val b=Array(11){1}
b[1]=n.nextInt(6)+1
val c=Array(11){when{it<1||m[it]<1->0
b[1]==b[it]->3
else->-1}}
o+="\nT:${++t} R:${b[1]}\n| |Bok|"
('A'..'J').map{o+=" $it |"}
o+="\n|Stt|"
m.map{f(it)}
o+="\n|Bet|n/a|"
(1..10).map{f(b[it])
c[0]-=c[it]}
o+="\n|Chg|"
(0..10).map{f(c[it])
m[it]+=c[it]}
o+="\n|End|"
m.map{f(it)}}
o}
```
[Try it online!](https://tio.run/##vVhtb9tGEv7OXzEwerBUURQpub5UiAw4ids4OKBBkiIf2n5YUStpz3zRcZdWdJJ@zf2T/rF0Zna5Ei07bQ9FDXRDcXdmZ@Z55oW9K02mis@Dr@FlJYWRM5iXFZil0pCWMwmLMptDuhRZJouFHAdLY1Z6PBjQJu1F2oj0Tn7CI7gfpWU@@E8ttVFloQfJP@Pk2bfBR2HSJeqUMC3LOyVhrYog@LiUBWzKGqoyy0DATMmQfy/FvcTfl@OELi5SCeUcRLGBhbpHkXJFyqMg@LCUlTzXeJTU5uJOouHiThULmEqjoSxIJ6vXEbxGNetCw6//G8YgDJuDtleGtNOPhcil1Xqkr5zPZYWqZjNN5y7GSQjT2tDhaUY7eKEEZfCtTEWtJaliq/KykBuygVU05oLA/5LYy0dwHcKLEF6G8CqEmxC@C@H7EF6HcBuizzN4E8GNwOg5AesDKliVdYE2aSMrxG@B@vlYRa9D9ufoFpC0h0FB7xOySfjIhKDY/Y0LO4bZWp7JuUGtgH@37gTCRg@qIlUh6roApImpRKHRxYq4U5W5B9ohUjbRJVOilsKs1DJkm57S07jttHi1DijCDCQFAk2TimLv4EQk0rKYKSbi2PrRhraqMZJlzfizyyEg8xWrmsmpsaZeIzcPBLHR5EiheEsaLfqIjFqWdTYDLZkIUEldZwZW@K8sKLkE0VXLSknmkxGoUYeQKWSRLtHOD3VVQBK8Q2jGMAyCHTz428ELm0Q7uOZftLyk5RUtN7R8R8v3tLym5ZaWN7igtvdMeQsxa8NssA/Ilz@5AOp7gaRqWVcMhNNHy4iv8D/56YKWS1q@ab0jbSLjhLfVBN/3h05tP2mW3uj06ZFd1HaD@eM9ZRueuYdv/ZKMTp8e2XXADB0wF38DMP@fsRzwPwDM0KNz4ZG4fGL3MWB6p8A8iUl79zFgPAmf@SUZnj492KXF9RHhK8Ujac21JhXFueEaaGtcJSMqCLaYUdrHmMGGQY65Mo7hm78F5dg@jHzw2TdGJW7nEeMzHDXv/jzK8V@Kcgx/JcoxfBnlShkqkbm0cwk2hBz/zeyoQn3A9suZ0qtMbI6qLxd0YUutawQ/atvp0NtFLRbSdwdf4pEtTRR8x7NdlCiCV2VrsdH8tizsLEGtqKjzqaxoO3tiDxu@xr6HM4rQB4WWok4CQ@YO2z6YkLOXkTeyad2Q15oYjc5h65zhSYU9ZvFAzDoLZrNSqcB2fy@rQqR1JirscnNVcIekZLE6DtdIDx@rI6vYVGrVfnZyU45tkIX8ZPjMQcm0zSg7W/o5sFFV542Kklt4W0pbdTc@WDgkVthTy0Ul8qbjYsavajMOmkz4uFTN8bWdusrCb37w5KBhsYlna5vd41HS2hIeTUxt8yzvMFpHpx86SieIEwZLVcOxkIcBpKZOlbL0dCOHMTJfGYJvViLlwY5dMJdrSYBvDIYEgq8HgcpXJYLwb3EvotqoLHrHGAbBYAA3n1b4A0cOBFw7iDO8eiZgXhepnaHxiQKZSq07XZjAlvIDhV/JNKOYMSQcWQxIhQ7a0dLRzZLUSuB5re1uWuMMVzTcWCGelJGUFoQbQWJFfLI8tIs8d7eK1iVrnPCwYOmVQItRa235k5ZZnReQi@rOgrFeqkxakSMQlkI3HcH5zN8JEbxl87ACKf1QyG8meDkCSCOwxIjaZJ1u7Hl8Zq6QHJ4o6NllsC7bHz5MMxSh0dcrH5LHOFLxFa4KJESGe8xSF4kJnJ3xm6xRPQELd6fr3tuAT@C6qsSmkyRd2CbxHjd546f4F9wbxk4tp8YEYieLhM0n25laKKPHt4XpX9l7e5Ozf4xmu7OIDgjTsSe6pJWjDB2v/ArirmUQe3hLpUVk6r@WRpYD@GGEdegOaWmdsJRRVSNUoPOuVkyFxmNl88nhKo379kDHGxEXH7rDrEscpbFQLaWYNR8b5B3FtB2XPe/h@58SCosrzlTB0PnOZbeXeGFnT0t@TUPH1lcMZeA5UmS3c6FW5hd@0b/iANu/5rIJP9ER3B75bZlhocY3/WRvjXOO9RD5n4sP46@2vR6Btod3@GyV7X8uaELZvSjvdmcs1Dm/Po@i8zfn3SgXK9geKYGv0Mzd2d4j9MMhcr7cuY8/DGJ0asTuvTHuHvvNw1cQMzrKdB9VTJFnSDh3W0RwDGiEMDszpfkjaVreY3K8r6f4TZi6vmvFtEOjEWp9cCr67nb/I@IR43FW2uF41AQqiaIk7h654FDpekSsKqJ2f9L8wAOP@nnw6sBg9vuIqfVqJoxs8bmJCr542vCXy0VjdPzQ6INZB7sPHOz9rt2ub30ZdpzkvgQ7wJ6rs6u6VjbYY0fBt67Uck9663o2VrtpJcXdcaHlXpQLVXREtdBjm2zP33PXuer6zvSv01Zxqsrm7QomVuZiNLRd8/OWC@oEKynX0YkvoFw@Jz7BuW7miPwE6yVXy0nMZ@ZYI115PKmMGAkOQYcEr@LulivPsdJ9MMWknRTtOsM15ugY1ZatMs@T3S4n3J4n/avYSk6m9KJ/NQqoWvSvuFaQJb5AuOpwUhvadWFLMr4eWAUuuXPen1tk3c4hc46yBs9MLe9S9Lc/SS3HnIjl7BFf8Xhqj7NTvQfnLcWOL8et/WfG763r1q6e8Dy4Ql6YrOisOt1uwPQj7nz@DQ "Kotlin โ Try It Online")
[Answer]
# **R 417 bytes**
```
g=function(){s=sample
d=10
m=t(matrix(c(20,rep(d,d),NA,s(6,d,T)),11,4,di=list(c("Book",LETTERS[1:d]),c("Stt","Bet","Chg","End"))))
i=1
u=which
while(m[1,1]!=0){
if(m[1,1]==120)break
w=s(6,1)
l=m[1,]!=0
o=m[2,]==0
m[3,u(o&l)]=3
m[3,u(!o&l)]=-1
m[3,u(m[1,]==0)]=0
m[3,1]=-sum(m[3,2:11],na.rm=T)
m[4,]=colSums(m[c(1,3),])
print(kable(m,ca=paste0("T:",i," R:",w),format="pandoc"))
m[1,]=m[4,]
m[2,]=c(NA,s(6,d,T))
i=i+1}}
```
**Explanation:**
*I was going to post a while ago, but my first attempt was at about 600, after some effort, I whittled it down to 500. After more research, I slowly got down to this result. I'm open to advice regarding better methods.*
**NOTE:** R has a package known as knitr which utilizes the kable function to create tables with various formats (Latex, HTML, pandoc, etc). Each player makes a random guess every turn. Most games end between 26 and 200 or so turns, with the bookie winning every game. Also, variable name choice has little reasoning, I just tried to avoid using builtins as variable names.
```
g=function(){s=sample # Abbreviate sample function
d=10 # Store 10
m=t(matrix(c(20,rep(d,d),NA,s(6,d,T)),11,4,di=list(c("Book",LETTERS[1:d]),c("Stt","Bet","Chg","End"))))
# Creates a 11x4 matrix, populates it, names it's columns and rows, and transposes it.
i=1 # Turn Counter
u=which # Abbreviate the which function that tests values to be equivalent to a chosen values
while(m[1,1]!=0){ # While loop with condition on the bookie not having 0 pounds
if(m[1,1]==120)break # Loop stops if bookie reaches 120 pounds, total
w=s(6,1) # Bookie Dice Roll/Winning Die Value
l=m[1,]!=0 # Check if total pounds of each player equals 0
o=m[2,]==w # Check if players choices matches the winning roll
m[3,u(o&l)]=3 # If guess is correct, and current wages is not 0, store 3
m[3,u(!o&l)]=-1 # If guess is incorrect, and current wages is not 0, store -1
m[3,u(m[1,]==0)]=0 # If current wages is 0, store 0
m[3,1]=-sum(m[3,2:11],na.rm=T) # Add up players totals to get the change to the bookies total
m[4,]=colSums(m[c(1,3),]) # Add the old total to the change
print(kable(m,ca=paste0("T:",i," R:",w),format="pandoc")) #Print the table with title
m[1,]=m[4,] # Store last row in first row
m[2,]=c(NA,s(6,d,T)) # Store new guesses in second row
i=i+1}} # Add to the turn counter
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 407 406 397 bytes
Each of the gamblers chooses a random number and then always bets on that value.
Thanks to ceilingcat for the suggestions.
```
#define l(a,b)for(i=11,a;i--;b)
#define p printf
#define q p("%d"s,a[i])
#define z(a)p("\n| "#a s)
#define s"\t| "
a[11],b[11];r,t,i,j,k;f(){l(0,b[i]=i?rand()%6:0)a[i]=10*-~!i;for(t=0;++t;){l(p("\n\nTurn %d\tRoll: %d\n|"s,t,r=rand()%6),p(i?"%c"s:"Book"s,75-i));l(z(Start),q);l(z(Bet),p(i?"%d"s:"-"s,1+b[i]));l(k=!z(Chg),p("%+d"s,i?j:k))k-=j=i?4-5*b[i]!=r:0,*a-=j,a[i]+=j;l(z(End),a[i]||(t=-1))q;}}
```
[Try it online!](https://tio.run/##RVHNb4MgHL37V1AbE6iwaLJuiYw16bJbs8M@TrUHKtqiFi3SHfqxf92BS9cLgfce7/d4ZGSTZf1Yqqw@iBw8GbnL77bP/VjkhVQ5qCHHa1Q0GkoWx5hTSQhdI@/Kt6DVUpniH9iDFvqB8DvMl3J1Ex4hR5ZJ1Rn4Yw66G9P5qbGgx5dxvMJrt1KNDZa4xBUtIDrVMLK4XDE501wJiIKHJELOn8XRhPyMJHUJDYtoGBrqLgyjUvV50AoEIjXvTV0nbqfONprBml2dEG6hnPlB5neJP2@ayvKPUyIRojU8wg/DtUF4/3ea5@aqF05PrDgOXbZBXrHREb5sN07jB6FrQc7KpEKoIqy08e/JdOLUI6aTCE@4RYeeQlYO/q9KoAE4n@1zSIzQnl4uvW0Y7LhU8LuRAoGTB0A35HffBd@@Fgs73oK2LOpd@l8 "C (gcc) โ Try It Online")
] |
[Question]
[
your task is to write a program that uses the Lucas-Lehmer primality test to check whether an input number is prime or not. This prime number candidate has the form `2p-1` with p being prime. (Mersenne prime number)
## The Lucas-Lehmer-test
The n-th Mersenne number is prime if it is a divisor of the (n-1)-th Lucas-Lehmer number (LLN).
You can calculate the LLN, similiar to the Fibonacci numbers, based on a recursive algorithm:
```
L<n> = (L<n-1>)^2 - 2
```
The LLN for 2 is 14. So, for p=3, LLN<3-1>=14
## Evaluation
* You have to submit a function that takes p as input (Remember: `2^p-1`)
* The shortest solution will win.
* Your solution has to use the Lucas-Lehmer test
* The code must be executable.
* Output: boolean value or 1=prime/0=not prime
## Tests:
```
p --> 2^p-1 --> LLN<n-1> --> ?
3 --> 7 --> 14 --> prime
5 --> 31 --> 37634 > prime (1214*31)
```
Good Luck
[Answer]
# [Python 2](https://docs.python.org/2/), 51 bytes
```
p=input()
s=4
exec's=(s*s-2)%(2**p-1);'*(p-2)
s>0>x
```
[Try it online!](https://tio.run/##TYzNCoJAFIX39ykuQsw4IJTVxhg34cKFKeULhF1QKL3MTKRPPzmtWh3O38eL66cx9d30IB1FkWc9jPx2MgarD0AzdcJqaZVN0ngjU6U42cUnoSSvAdh8m89@/cGnH56ErXlTBojOLEEQAwAD/OfYDKND0VzLqhAQ2o7Y4eX@osKYyWT/q3NdNfWtbAvh93D8Ag "Python 2 โ Try It Online")
Output is via exit code
[Answer]
## Mathematica 44 Bytes
```
(s@3=14;s@n_:=Mod[s[n-1]^2-2,2^#-1];s@#==0)&
```
Test:
```
{#, %[#]} & /@ Prime[Range[2, 20]]
```
Too bad we can't use `MersennePrimeExponentQ` (22 bytes) since it doesn't appear to always use the LLT.
[Answer]
# [Haskell](https://www.haskell.org/), ~~47 43~~ 41 bytes
Thanks @Kittsil for saving me 2 bytes!
```
f n=iterate(\v->mod(v^2-2)$2^n-1)4!!n-2<1
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzazJLUosSRVI6ZM1y43P0WjLM5I10hTxSguT9dQ00RRMU/XyMbwf25iZp6CrUJBUWZeiYKKQpqC8X8A "Haskell โ Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 61 bytes
```
l=lambda x:4*(x<3)or l(x-1)**2-2
f=lambda p:not l(p)%(2**p-1)
```
[Try it online!](https://tio.run/##NcrRCgIhEAXQ9/2KYSGYEQ1We5LqD/YjjLIMU3EN7OttCLpwHy73lE975GTGiKfoXperg24PAvvRUK4QsauFhNBKT/4Pik258VVoh1qIwmJ4xiuEBNWl@w2NBL1wyU7ACR49rkS21JAabq3y2tfne2uoScKszrOEH4HxBQ "Python 3 โ Try It Online")
I'd like to note that the Lucas-Lehmer test only applies to ~~odd primes~~ Mersenne numbers of the form 2*p*-1 where *p* is an odd prime. This program uses a recursive function for the Lucas-Lehmer numbers, and then a function that just tests if the *n*-th LLN is divisible by M*n*.
[Answer]
# [PHP](https://php.net/), 58 bytes
```
for($s=4;++$i+1<$argn;)$s=($s**2-2)%(2**$argn-1);echo+!$s;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkrmT9Py2/SEOl2NbEWltbJVPb0AYsZa0JFAIKa2kZ6RppqmoYaWmBxXUNNa1TkzPytRVViq3//wcA "PHP โ Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
o<4IรFnร}sร
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/38bE83CvW97h3triw9P@/zcHAA "05AB1E โ Try It Online")
**Explanation**
```
o< # push 2^p-1
4 # push 4
IรF # p-2 times do:
nร # square and subtract 2
} # end loop
sร # LLN(n) % Mp == 0
```
If we didn't need boolean value output we could save a byte with `4IรFnรIo<%` which returns **0** for prime and non-zero otherwise.
[Answer]
## APL, 28 bytes
```
{0=(ยฏ1+2*โต)|(ยฏ2+รโจ)โฃ(โต-2)โข4}
```
Explanation:
```
โข4 โ to the number 4,
โฃ(โต-2) โ apply this function โต-2 times,
(ยฏ2+รโจ) โ N*N - 2
(ยฏ1+2*โต)| โ modulo 2^โต - 1
0= โ is the result 0?
```
] |
[Question]
[
*I'd like to start a series of challenges for <http://box-256.com/> starting with the first challenge, โBIG SQUARE IIโ. After this one I'll add another for "CHECKERBOARD" and so on.*
[](https://i.stack.imgur.com/RKM5J.png)
**Rules**:
* Complete the BIG SQAURE II challenge in the Box-256 emulator (either on the website or download the program if you run Windows)
* Post back here a screenshot of your working answer
* You **MUST** include the code in plain text so that others can easily copy and very itโs operation.
**Scoring**:
The winner will be the least amount of instructions used (just the instruction calls, either by name or opcode, the arguments to them are not counted as JMP takes one argument but MOD can take three).
I think in the future contests we can add some additional bonus points for use of coding tricks and we could include the argument count too. I wanted to start basic to get the ball rolling.
**Winning**
I think we should put a stake in the ground and say two weeks from today we announce the winner(s, there maybe be mutliple entries with the same instruction count).
[Answer]
# 8 instructions
My smallest solution to the Big Square II challenge is 8 lines of code. There's a simple loop which cycles through a table of 8 pixel locations.
```
; Big Square II in 0x08h instructions
; John Metcalf
PIX @18 002 000
ADD @16 @18 @18
MOV @18 @20 001
MOV @19 @18 008
FLP @16 @17 001
JMP @00 001 010
011 031 021 032
0D3 01D 0E3 01E
```

[Answer]
# 1 instruction
This solution is to illustrate that counting instructions is not a proper way of scoring for BOX-256.
```
JMP 002 072 00C
002 000 013 00C
001 00C 055 002
010 000 000 000
011 012 013 014
015 016 017 018
019 01A 01B 01C
01D 01E 021 022
023 024 025 026
027 028 029 02A
02B 02C 02D 02E
0D1 0D2 0D3 0D4
0D5 0D6 0D7 0D8
0D9 0DA 0DB 0DC
0DD 0DE 0E1 0E2
0E3 0E4 0E5 0E6
0E7 0E8 0E9 0EA
0EB 0EC 0ED 0EE
031 041 051 061
071 081 091 0A1
0B1 0C1 032 042
052 062 072 082
092 0A2 0B2 0C2
03D 04D 05D 06D
07D 08D 09D 0AD
0BD 0CD 0ED 03E
04E 05E 06E 07E
08E 09E 0AE 0BE
0CE 000 000 000
```
[](https://i.stack.imgur.com/lBBai.png)
[Answer]
# 11 instructions, 12 lines
```
PIX 011 002 000
ADD @01 @2C @01
ADD @03 001 @03
JGR 00D @03 @00
MOV 000 @03 000
ADD @06 001 @06
JGR 030 @06 @00
MOV 022 @01 000
MOV 02C @06 000
MOV 00B @0D 000
JMP @00 000 000
001 010 -01 -10
```
Any bonus for self-modification?
(Note the differences between the memory and the command line, specifically in locations `@01` `@06`, `@0D`.)
[](https://i.stack.imgur.com/mg5Dk.png)
[Answer]
I think my answer is probably what you were suggesting @orlp ?
I've used 3 instrutions, PIX, ADD and JMP, the rest are the co-ordinates (however the instructions and coordinates are spaced out below for easier reading):
```
000 000 000 000
000 000 000 000
PIX @2C 002 000
ADD 001 @09 @09
JMP @08 000 000
000 000 000 000
000 000 000 000
000 000 000 000
000 000 000 000
000 000 000 000
000 000 000 000
011 012 013 014
015 016 017 018
019 01A 01B 01C
01D 01E 021 022
023 024 025 026
027 028 029 02A
02B 02C 02D 02E
031 032 03D 03E
041 042 04D 04E
051 052 05D 05E
061 062 06D 06E
071 072 07D 07E
081 082 08D 08E
091 092 09D 09E
0A1 0A2 0AD 0AE
0B1 0B2 0BD 0BE
0C1 0C2 0CD 0CE
0D1 0D2 0D3 0D4
0D5 0D6 0D7 0D8
0D9 0DA 0DB 0DC
0DD 0DE 0E1 0E2
0E3 0E4 0E5 0E6
0E7 0E8 0E9 0EA
0EB 0EC 0ED 0EE
```
[](https://i.stack.imgur.com/Wf3mu.png)
] |
[Question]
[
Problem: given any input string that does not contain null bytes, determine whether or not the input string matches glob as defined below:
```
null is disallowed in both string in glob
* matches zero or more characters
** is disallowed in glob
? matches exactly 1 character
[ch] matches a character class of the specified characters
to include ] in a class, it must be the first character
[^ch] matches a character class of all but specified characters
to include ] in a class, it must be the first character after ^
The empty glob only matches the empty string.
```
The system glob() on the target platform implements glob where \* doesn't match a /, so you can't use it. This has infested all shells. You could try converting to a regex; however this won't be as easy it it looks.
You must specify an encoding for your program. Your program must be valid in that encoding. All bytes including null are allowed in cp437. Your score is the number of characters in your encoding.
Bonus: If your program is expressed in a well-known encoding that uses 6 or fewer bits, your score is multiplied by the number of bits used in the encoding and divided by 7. Your program will be passed its arguments in ASCII in that case.
Your program will receive the string to match or not as the first argument and the glob pattern as the second argument. Your return code must be 0 on match and nonzero on nonmatch.
You may leave it undefined what happens if you get passed a disallowed glob.
Standard loopholes are disallowed; however the following are allowed:
```
You may compress your program but it must work if executed directly.
Binaries are allowed. Submit a disassembly with it so I can read it.
Using two different chars which look the same is allowed.
You may use trigraphs (but I can't see how it helps).
```
Examples:
```
"w*c*d" matches "wildcard" but doesn't match "wildcards"
"ww*w*d" matches "wwwdwd" but doesn't match "wwd"
"ww*[w-c]?*" matches "www-" and "wwcc" but doesn't match "wwc"
"[a-c]" matches "-" but doesn't match "b"
"^[*][^]]" matches "^*[" but doesn't match "^?[" or "^*]" or "**]"
```
[Answer]
## Common Lisp, ~~368~~ 340
Encoding is implementation-dependent, but UTF-8 is generally supported among implementations (see also the set of [standard characters](http://clhs.lisp.se/Body/02_ac.htm) that must be supported).
```
(ql:quickload'cl-ppcre)(lambda(s g)(ppcre:scan(do(e(L(coerce g'list))c p)((not L)`(:sequence,@(reverse e):end-anchor))(push(case(setf c(pop L))(#\*'(:regex".*"))(#\? :everything)(#\[(prog1`(,(or(and(char=(car L)#\^)(pop L):inverted-char-class):char-class),@(subseq L 0(setf p(position #\] L :start 1))))(setf L(nthcdr(1+ p)L))))(t c))e))s))
```
### Pretty-printed
```
(lambda (s g)
(cl-ppcre:scan
(do (e
(l (coerce g 'list))
c
p)
((not l) `(:sequence ,@(reverse e) :end-anchor))
(push
(case (setf c (pop l))
(#\* '(regex".*")
(#\? :everything)
(#\[
(prog1
`(,(if (char= (car l) #\^)
(prog1 :inverted-char-class (pop l))
:char-class)
,@(subseq l 0 (setf p (position #\] l :start 1))))
(setf l (nthcdr (1+ p) l))))
(t c))
e))
s))
```
Converting to regex is not so hard when using non-string representations of regexes. `CL-PPCRE` is a regular expression library by Edi Weitz which accepts two ways of defining such expressions:
* the usual string-based syntax, or
* a more lispy approach using a DSL
Today I [answered](https://softwareengineering.stackexchange.com/questions/298564/is-there-a-specific-reason-for-the-poor-readability-of-regular-expression-syntax/298570#298570) a question about alternative syntaxes for regular expressions, and this challenge is a good example of why a structured format can be useful instead of strings.
### Example
For the following glob, `"ww*[w-c]?*"`, the regular expression being built is described by this form:
```
(:sequence #\w
#\w
(:regex ".*")
(:char-class #\w #\- #\c)
:everything
(:regex ".*"))
```
And we match `"www-"`. The `(:char-class ...)` list takes indiviudal charaters, which does not need escaping like it would if I wrote `"[w-c]"` as a string regex.
### Test suite
```
(loop for (glob match no-match) in
'(("w*c*d" ("wildcard") ("wildcards"))
("ww*w*d" ("wwwdwd") ("wwd"))
("ww*[w-c]?*" ("www-" "wwcc") ("wwc"))
("[a-c]" ("-") ("b"))
("^[*][^]]" ("^*[") ("^?[" "^*]" "**]"))
("w*\\*s" ("wild\\ness") ()))
for matchp = (lambda(s)(funcall *fun* s glob))
always (every matchp match)
never (some matchp no-match))
=> T
```
[Answer]
# MUMPS, ~~397~~ 387 bytes
Note that this code uses features of Cachรฉ ObjectScript (specifically, the `*` designator in a `$EXTRACT` call) and does not conform to the ANSI MUMPS standard.
```
f(g,s) f i=1:1:$L(g) d
. s c=$E(g,i) i 'm s:"*?[]"'[c p=p_"1"""_c_"""" s:c="*" p=p_".E" s:c="?" p=p_"1E"
. i c="]" s p=p_"1"_$E(b,1,*-1)_")" s m=0
. s:c="[" a=$E(g,i+1)="^",m=a+1,b="(",i=i+a
. i m s:$E(g,i+1)="]" d=1 s k=$F(g,"]",i+d)-2+d,r=$E(g,i+1,k),i=k
. f j=1:1:$L(r) s:m=1 b=b_"1"""_$E(r,j)_""","
. i m=2 f j=0:1:127 s:r'[$C(j) b=b_"1"""_$S(j=34:"""""",1:$C(j))_""","
q s?@p
```
Haha, OP! I've foiled your plans! Sure, your glob syntax might be tricky to convert to a regex, but my language *has no regexes*! Instead, it has a crippled form of "pattern matching" ([see docs, section 5.7](http://docs.intersystems.com/documentation/cache/20091/pdfs/GCOS.pdf)) that happens to be pretty much exactly powerful enough to handle these globs.
Basically, what the code does is it converts OP-style globs into a string corresponding to the pattern match, and then evals that string, and tests the input string against the result of that eval. The one tricky point is that MUMPS pattern matches don't have a notion of an inverted character class (`[^abc]`), so we instead have to construct a character class consisting of all the ASCII characters except the ones specified in in the inverted character class.
Here are some correspondences between OP-style globs and MUMPS pattern matches:
```
OP MUMPS
-----------------------------------------------------------
w*c*d 1"w".E1"c".E1"d"
ww*w*d 1"w"1"w".E1"w".E1"d"
ww*[w-c]?* 1"w"1"w".E1(1"w",1"-",1"c")1E.E
[a-c] 1(1"a",1"-",1"c")
^[*][^]] [doesn't print well, because of the inverted character class thing]
```
There is probably room for additional golfing here. Here is an ungolfed version:
```
match(glob,string) ;
; the golfed version assumes a clean symbol table; here, I've explicitly cleaned it.
new i,pattern,char,mode,buffer,range,advance,delta,j,k
for i=1:1:$LENGTH(glob) do
. set char=$EXTRACT(glob,i)
. if ("*?[]"'[char),(mode=0) do
. . set pattern=pattern_"1"""_char_"""" ; 1 of `char`
. if (char="*"),(mode=0) do
. . set pattern=pattern_".E" ; 0+ of any character
. if (char="?"),(mode=0) do
. . set pattern=pattern_"1E" ; 1 of any character
. if (char="]") do
. . set pattern=pattern_"1"_$EXTRACT(buffer,1,$LENGTH(buffer)-1)_")"
. . set mode=0
. if (char="[") do
. . set advance=($EXTRACT(glob,i+1)="^") ; 0 or 1
. . set mode=advance+1 ; 1 = in a char class; 2 = in an inverted char class
. . set buffer="(" ; begin constructing an alternation
. . set i=i+advance
. if (mode'=0) do
. . if ($EXTRACT(glob,i+1)="]") do
. . . set delta=1
. . . set k=$FIND(glob,"]",i+delta)-2+delta
. . . set range=$EXTRACT(glob,i+1,k)
. . . set i=k
. for j=1:1:$LENGTH(range) do
. . if (mode=1) do
. . . set buffer=buffer_"1"""_$EXTRACT(range,j)_"""," ; add a character to the alternation
. if (mode=2) do
. . for j=0:1:127 do
. . . if (range'[$CHAR(j)) do
. . . . set buffer=buffer_"1"""_$SELECT(j=34:"""""",1:$CHAR(j))_""","
quit string?@pattern ; eval `pattern` and test `string` against it, and return the outcome (0 or 1)
```
[Answer]
# Ceylon, ~~3514~~ ~~2586~~ ~~2360~~ ~~2248~~ ~~2228~~ ~~2196~~ ~~2059~~ ~~1882~~ ~~1620~~ ~~1147~~ ~~1130~~ ~~858~~ ~~830~~ ~~693~~ 658 bytes
```
import ceylon.language{B=Boolean,S=String,C=Character,o=false,r=process}shared void g(){B n(B(S)l,B(S)r)(S c)=>any{for(i in 0..c.size)l(c[0:i])&&r(c[i...])};B q(S c)=>c.size==1;B d({C*}s,B n)(S c){if(q(c),exists i=c[0]){return n!=i in s;}return o;}[B(S),S]h(S r){assert(exists s=r[0],exists e=r.firstOccurrence(']'));return[s=='^'then d(r[1..e],true)else d(r[...e],false),r[e+1...]];}B(S)p(S x){if(exists f=x[0]){value r=(f=='*'then[(S c)=>true,x.rest])else(f=='?'then[q,x.rest])else(f=='['then h(x.rest))else[d({f},o),x.rest];return n(r[0],p(r[1]));}else{return S.empty;}}assert(exists x=r.arguments[1],exists c=r.arguments[0]);r.exit(p(x)(c)then 0else 1);}
```
It seemed first that converting the glob to regular expressions is the easiest, but it also means escaping everything which is special in regular expressions but not in our globs ... I might try this in a different answer.
*Due to popular demand I removed most of the the how-I-got-there .. who is interested, can have a look into the history.*
So I build a new (limited) regexp-like matching engine, and a parser to convert our wildcard strings into such strings. (And some boiler plate for command line access and return code generation.)
Here is the same program formatted (i.e. with added whitespace) and with some documentation annotations:
```
import ceylon.language {
B=Boolean,
S=String,
C=Character,
o=false,
r=process
}
"""A glob evaluation program.
Takes two command line arguments, first is a candidate string,
second one is a wildcard expression.
Exits with code 0 if the expression is well-formed and
matches the candidate, otherwise exits with 1.
"""
shared void g() {
"""A string predicate build from a left and a right predicate.
It matches a string if that can be split in two substrings
so the first one is matched by the left expression and
the second one by the right expression.
"""
B n(B(S) l, B(S) r)(S c) =>
any {
for (i in 0..c.size) l(c[0:i]) && r(c[i...])
};
"""An expression which matches any string of length 1 (i.e. a single character).
This corresponds to the question mark (`?`), therefore the name.
"""
B q(S c) => c.size == 1;
"""A character class, i.e. an expression which matches any string of length 1,
as long at it is (or is not) in a given list of characters.
"""
B d(
"The characters to be matched (or excluded)"
{C*} s,
"Is this negated? If true, matches only characters not in the list."
B n)
(
"The candidate string."
S c) {
if (q(c), exists i = c[0]) {
return n != i in s;
}
return o;
}
"""Parses a started character class (i.e. the stuff after the `[`).
Returns a tuple of the constructed matching function
and the remaining string to be parsed for further expressions.
"""
throws (`class AssertionError`, "if the expression is not well-formed, i.e. there is no `]` following.")
[B(S), S] h(S r) {
assert (exists s = r[0], exists e = r.firstOccurrence(']'));
return [s == '^' then d(r[1..e], true) else d(r[...e], false), r[e + 1 ...]];
}
"""Parses an glob expression from a string.
Returns a string predicate.
"""
B(S) p(
"The string with the wildcard expression."
S x) {
if (exists f = x[0]) {
value r = (f == '*' then [(S c) => true, x.rest])
else (f == '?' then [q, x.rest])
else (f == '[' then h(x.rest))
else [d({ f }, o), x.rest];
return n(r[0], p(r[1]));
} else {
return S.empty;
}
}
assert (exists x = r.arguments[1], exists c = r.arguments[0]);
r.exit(p(x)(c) then 0 else 1);
}
```
I'm not sure if this is actually readable enough ... see the history of this answer for the original version with more readable names (and which was using interfaces and objects instead of just functions).
Some used tricks to make this shorter:
* import with alias โ we use `String`, `Boolean` and `Character` quite often, so give them one-letter aliases. When we are already doing this, adding the renaming for `process` (used three times) and `false` (used twice) doesn't take much overhead. (This only helps for stuff used several times โ the ceylon.language stuff is imported automatically, so we have some overhead here.)
* The `possibleMatchLengths` method was an optimization for speed โ not needed when we are code-golfing. (I guess this can make matching quite slow in some extreme cases.)
* the Implementations of the `string` attribute was also removed, it was just there for debugging the initial versions.
* Instead of the implementations of the `Glob` interface in the first versions, we have just functions `Boolean(String)` (or `B(S)` in our short format), which saves quite some braces and `class`/`object`, and some functions returning such functions. Ceylon has a nice syntax for defining functions which return functions, used for the GlobList `g` and the CharacterClass `c` โ simply a function with multiple argument lists.
* I unified the methods for `CharacterClass` and `NegatedCharacterClass`, passing a boolean parameter for `negated`. It is used as `negated != i in chars` (shorter `n!=i in s`) instead of having one function with `i in s` and one with `!i in s` (and both having the remaining conditions twice).
* The object/function emptyGlob was replaced by the static Reference `String.empty` (written `S.empty`, of course).
* Where a function consists of just one return statement, we can write it with the "fat arrow" notation and save the braces and the `return`.
* If such a function is used just once, sometimes we can put it directly where used, as an anonymous function definition. This is used for the `*` implementation.
* The function `q` (for the question mark) is in addition used in the definition of the character class function `d`, as `q(c)` is shorter than `c.size==1`.
* Instead of first defining a value with `value f = ...` or even with type `Character f = ...` and then doing an `if (exists f) {` or `assert(exists f);`, we can move the definition into the `if` or `assert`, saving some characters.
* If we want to pass an iterable constructed from a comprehension to a function (like the `any` function used in the definition of `g`), we can write `any{...}` instead of `any({...})` โ this is the named argument syntax, which converts its last entry, if it's a comprehension, into an iterable, if the function accepts that.
[Answer]
# CJam, 125
```
{AC+:A;}:F;0alqW+:X;{"*?[ _{0=X,,>}& :) 1:T:B;L:A; {X=C=},:)
^] A!B&{0:B;}{F}? A{0:T;{X=A-!B=},:)}{F}? F"N/T=S/(C#=~}fCX,(\-!
```
CJam has no regular expressions (yet), so I just implemented the wildcard matching directly.
The encoding here is plain old ASCII (I might try some compression tricks later).
[Try it online](http://cjam.aditsu.net/#code=%7BAC%2B%3AA%3B%7D%3AF%3B0alqW%2B%3AX%3B%7B%22*%3F%5B%20_%7B0%3DX%2C%2C%3E%7D%26%20%3A)%201%3AT%3AB%3BL%3AA%3B%20%7BX%3DC%3D%7D%2C%3A)%0A%5E%5D%20A!B%26%7B0%3AB%3B%7D%7BF%7D%3F%20A%7B0%3AT%3B%7BX%3DA-!B%3D%7D%2C%3A)%7D%7BF%7D%3F%20F%22N%2FT%3DS%2F(C%23%3D~%7DfCX%2C(%5C-!&input=%5E%5B*%5D%5B%5E%5D%5D%0A%5E*%5B)
**Explanation:**
The idea is to go through the pattern (glob) and keep a list of indices possibly reached so far in the input string. Initial list is `[0]`, `?` advances all indices by 1, `*` goes to all indices from the minimum reached so far to the end of the string, and character sets and other non-special characters just select the indices that match and advance them by 1. At the end, the string matches if the list of indices contains the string length.
Character sets are constructed on the fly and recorded as a string A and a boolean flag B (for positive/negative match), and used when reaching the closing `]`.
```
{โฆ}:F; define a function F
AC+:A; add variable C to variable A (A+=C)
0a push [0] (initial array of indices, let's call it I)
it will be kept and updated on the stack
l read the first input line (containing the pattern)
q read the rest of the input (the string to match)
W+ append the number -1 (as an array element, following the characters)
this is a dummy guard value that avoids costly empty-string checks
:X; save the array in X
{โฆ}fC for each character C in the pattern
"โฆ" push that long string, containing code to handle various cases
N/ split into (two) lines
T= get the T'th line; T is 1 when parsing a character set and 0 otherwise
(T is initially 0 by default)
S/ split by space into an array of strings
( take out the first item (containing special characters to check)
C# find the index of C in that string
= get the corresponding string from the array
(when C is not found, # returns -1 which gets the last array item)
~ execute that string
X,( get the length of X and decrement it
(to get the length of the input string)
\- calculate the set difference between it and I (the list of indices)
the result is empty (false) iff I contained the string length
! negate, to obtain the final 1/0 result
```
Now the long string with various pieces of code. Each line has a few characters to check and then a block for handling each one, and the default case.
First line: `*?[ _{0=X,,>}& :) 1:T:B;L:A; {X=C=},:)`
```
*?[ special characters to look for
######### first block, corresponding to character *
_ duplicate I on the stack
{โฆ}& if I is not empty
0= get the first (smallest) index from I
X, get the length of X (1 longer than the input string)
, make an array [0 1 2 โฆ length(input string)]
> slice the array starting at the smallest index from I
######### second block, corresponding to character ?
:) increment all items of I
######### third block, corresponding to character [
1:T set T=1, causing the next characters to be processed with the 2nd line
:B; also set B=1, the boolean flag signifying positive match
L:A; initialize A (the array of characters) with an empty string/array
######### last block, corresponding to other regular characters
{โฆ}, filter I's items, using the block as a boolean condition
X= get the character from X at the given index (it wraps around)
if the input string was empty, this will be -1 (the dummy value)
C= compare to C (the current character in the pattern)
:) increment the remaining indices
```
Second line (for character sets): `^] A!B&{0:B;}{F}? A{0:T;{X=A-!B=},:)}{F}? F`
```
^] special characters to look for
######### first block, corresponding to character ^
A!B& calculate not(A) & B, which is 1 (true) iff A is empty and B is 1
{โฆ} if true (first character and positive match, i.e. we're at "[^")
0:B; set B=0 (switch to negative match)
{โฆ} else
F call F, which just adds the character C to A
? end if
######### second block, corresponding to character ]
A{โฆ} if A is not empty (it's a closing "]")
0:T; set T to 0, switching back to the first line
{โฆ}, filter I's items, using the block as a boolean condition
X= get the character from X at the given index
if the input string was empty, this will be -1
A- calculate the set difference between it and A
! negate, obtaining 1 if the character was in A and 0 if it was not
B= compare to B (the positive/negative match indicator)
:) increment the remaining indices
{โฆ} else (A is empty, i.e. we're at "[]" or "[^]")
F call F to add the character to A
? end if
######### last block, corresponding to other regular characters
F call F
```
[Answer]
## Python 3, 209 207 bytes
The general strategy is transforming the glob spec into a regex. That's accomplished by a function `r`, passed as the replacement parameter to `re.sub()`, (or `s()` in this case). If no match is found, a run-time error is thrown, causing a positive exit code.
```
import sys,re
_,t,g=sys.argv
s=re.sub
def r(m):a,b,c,d,e=m.groups();return a and s(r"(?=[-\\])",r"\\",a)or b and".*"or c and"."or d and"\\"+d or e
re.match(s(r"(\[\^?.+?\])|(\*)|(\?)|(\W)|(.)",r,g)+"$",t).re
```
The patterns produced for the example globs show how it works.
```
Glob Regex pattern
w*c*d w.*c.*d$
ww*w*d ww.*w.*d$
ww*[w-c]? ww.*[w\-c].$
[a-c] [a\-c]$
^[*][^]] \^[*][^]]$
a[\]b a[\\]b
```
[Answer]
# Perl, 88 bytes
```
$_=pop;s/((\*)|\?)|(\[\^?\]?)(.*?)\]|\W/$1?".$2":$3?qr#$3\Q$4\E]#:"\\$&"/eg/pop=~/^$_\z/
```
The encoding is ASCII. This works by translating to regular expressions with regular expressions. It exits with a division by zero error (hence, nonzero status) on match failure.
Some ideas adapted from [recursiveโs Python solution](https://codegolf.stackexchange.com/a/59217/39242).
] |
[Question]
[
When playing the piano, I realized that to play a chord right, I usually need to remember just which tones of the chord are played on white and which on black keys. The rest is usually handled by the "autopilot".
Let's write a program that given a [7th chord](http://en.wikipedia.org/wiki/Seventh_chord), it outputs which of its tones are to be played on black (character `^`) and which on white keys (character `-`). Each chord name has a root, which is a capital letter `A` to `G`, optionally followed by `b` or `#`, and then by its type, which is one of the following. All 7th chords contain 4 notes, and the formulas are given in integer notation below.
* `7` Dominant (0,4,7,10)
* `M7` Major (0,4,7,11)
* `m7` Minor (0,3,7,10)
* `dim7` Diminished (0,3,6,9)
* `m7b5` Half-Diminished (0,3,6,10)
* `-M7` Minor/Major (0,3,7,11)
Integer notation means that you must play the four notes that are (w,x,y,z) semitones from the root. (w is the root and is therefore always zero.)
So for example for input `Bb-M7` the output would be `^^--` (corresponding to *Bb-Db-F-A*).
The program should either read the chord form stdin and output the result to stdout, or it should be a function that accepts a string and returns a string.
[Answer]
# CJam - 75
```
q('@m2*_6/-\_0="b #"#_){(@+\1>}{;}?1b81*A+H/6%8+2b1>{1$3++}/]2774Ybf="^-"f=
```
Try it at <http://cjam.aditsu.net/>
Brief explanation:
1. `('@m2*_6/-` Convert the first character to a number of semitones (starting from G for convenience)
2. `\_0="b #"#_){(@+\1>}{;}?` Adjust for b or #
3. `1b81*A+H/6%8+2b1>{1$3++}/]` Convert the rest of the chord to a unique number (I used the sum of ASCII codes here) and then do some clever calculations with it to obtain the 4 notes of the chord
4. `2774Ybf="^-"f=` Convert the notes to black/white as 0/1 (binary digits of 2774), then convert 0/1 to ^/-.
[Answer]
# Python3, ~~293~~ 242 bytes
This is my first CodeGolf. I am curious to see how others do this.
```
def f(s):
for j in 4,3,2,1:
try:return ''.join(['-^--^-^--^-^'[('A BC D EF G'.index(s[0])-('b'==s[1])+('#'in s)+i)%12]for i in(0,)+{'7':(4,7,10),'M7':(4,7,11),'m7':(3,7,10),'dim7':(3,6,9),'m7b5':(3,6,10),'-M7':(3,7,11)}[s[-j:]]])
except:pass
```
## Edit on 01.06.15
Thanks to the commenters, we found some tricks to shorten the code. I also discovered that changing to a function is slightly shorter. Old code: <http://ideone.com/j5gmV2>. P.S. I am just copying the code into triple quotes in Python and calling `len` to get the number of bytes.
## Note:
I am assuming that Bb-M7 is Bb Major/Minor, i.e. that there is no delimiter between the note and the chord type, as described in the OP's second paragraph. Thus `Bb-M7` gives `^^--`. If Bb-M7 means Major, then what is Bb Major/Minor? Should it be `Bb--M7`?
[Answer]
# C, ~~154~~ 151 bytes
**Rev 1** eliminated variable `f` by doubling with `p`, and placed formula search inside `for` bracket.
```
char c[9],s[]="d7m+mM-";n;main(p){gets(c);n=*c*2%7+(c[p]&4?0:5+c[p++]%2*2);for(p=strchr(s,c[p])-s<<!!c[p+3]|8;p;p/=2)putchar(45+n%12/7*49),n+=9-p%2*5;}
```
**Rev 0**
```
char c[9],s[]="d7m+mM-";n;f;main(p){gets(c);n=*c*2%7+(c[p]&4?0:5+c[p++]%2*2);f=strchr(s,c[p])-s<<!!c[p+3]|8;for(;f;f/=2)putchar(45+n%12/7*49),n+=9-f%2*5;}
```
**EXPLANTATION**
I've used a bit of music theory to help reduce my score.
**Terminology**
A seventh chord is composed of the 1st, 3rd, 5th and 7th notes of a diatonic scale. These names are also used to describe intervals.
A "3rd" is an interval of 3 or 4 semitones, known as "minor" and "major" 3rds respectivelty.
A "5th" is made by stacking two "3rds", and a "7th" is made by stacking a "5th" and a "3rd."
The standard 5th is the "perfect 5th" (of 3+4 or 4+3 = 7 semitones.) "Diminished" (3+3=6) and "augmented" (4+4=8) 5ths are also possible.
There are two standard 7ths: "minor" (7+3=10) and "major" (7+4=11) and one nonstandard 7th: "diminished" (6+3=9.)
Note that there is no "augmented" 7th interval, because 8+4=12 sums to a whole octave.
**Stacked Thirds**
All of the seventh chords required in this question are based on stacked thirds. That is, the inteval between one note and the next is always three or four semitones. Therefore we can encode the formula for the chord type as a 3-bit binary number as below. (The increments are coded into binary from right to left and the 4th bit is set to 1 to signal the end of the information.)
```
Symbol Name Formula Increments Binary
dim7 Diminished 0,3,6,9 3,3,3 1 000
7 Dominant 0,4,7,10 4,3,3 1 001
m7 Minor 0,3,7,10 3,4,3 1 010
+M7 Augmented/Major* 0,4,8,11 4,4,3 1 011
m7b5 Half-Diminished 0,3,6,10 3,3,4 1 100
M7 Major 0,4,7,11 4,3,4 1 101
-M7 Minor/Major 0,3,7,11 3,4,4 1 110
*The augmented major seventh chord is not required by the question, nor is it implemented correctly, because it clashes with the #/b correction.
```
The binary is obtained from the first character of the chord type by finding its position in the string `"d7m+mM-"`. There is a problem with the m7b5 chord, because there are two `m`'s in the string and `strchr` will always find the first one. To fix this, the binary is leftshifted one place whenever the chord type has more than 3 characters.
**Circle of fifths**
Instead of organising the notes as `A A#/Bb B C` etc, I use an imporant alternate representation called the Circle of fifths. In this we start at F and count 7 semitones each time, giving the following sequence:
```
F C G D A E B F#/Gb C#Db G#/Ab D#/Eb A#/Bb
```
As can be seen, all the white notes come first, followed by all the black notes. This is no coincidence: the fifth (7 semitones, frequency ratio 3/2) is the most important musical interval after the octave (12 semitones, ratio 2/1). The familiar scale of 7 out of the 12 available notes is constructed by stacking these "fifths."
The input note letter can be converted to its position in the circle of 5ths by `ASCII code*2%7`, then 5 is added for a flat or 7 for a sharp.
In the domain of fifths, a minor third is nine fifths (minus five octaves): `9*7=63, 63%12=3` and a major third is four fifths (minus two octaves): `4*7=28, 28%12=4`.
For output, any number below 7 is a white note, any number 7 and above is a black note.
**REV 0 UNGOLFED CODE**
```
char c[9],s[]="d7m+mM-";n;f; //array c is filled with zeroes
main(p){ //if no arguments are given, p initialised to 1
gets(c);
n=*c*2%7 //convert character zero to its position in cycle of fifths, then correct for #/b in the next line
+(c[p]&4?0:5+c[p++]%2*2); //# and b are the only characters in position 1 whose ASCII codes have the 4's bit clear.
f=strchr(s,c[p])-s<<!!c[p+3]|8; //find binary representation of stacked 3rds, correct for m7b5, and OR with 8
for(;f;f/=2) //at end of iteration, rightshift f. loop will end when f=0 (when 8's bit shifted out)
putchar(45+n%12/7*49), //if n%2<7, put ASCII 45='-', else put ASCII 45+49='^'
n+=9-f%2*5; //increment n by a minor third (9 fifths) or major third (4 fifths)
}
```
[Answer]
### C# 468
```
string f(string p){var x=new Dictionary<char,int>{{'C',1},{'D',3},{'E',5},{'F',6},{'G',8},{'A',10},{'B',12}};var y=new Dictionary<string,string>{{"7","0,4,7,10"},{"M7","0,4,7,11"},{"m7","0,3,7,10"},{"dim7","0,3,6,9"},{"m7b5","0,3,6,10"},{"-M7","0,3,7,11"}};var m="--^-^--^-^-^-";var r="";int j=1,i=0,k=0;if(p[1]=='b')i--;if(p[1]=='#')i++;if(i!=0)j=2;i=i+x[p[0]];var a=y[p.Substring(j)].Split(new char[]{','});for(;k<a.Length;k++)r+=m[(int.Parse(a[k])+i)%12];return r;}
```
For me it looks ok. I tested it but who knows ;)
I also think that for
```
Bb-M7
```
you should get
```
^^--
```
[Answer]
# Java ~~513~~ 492 characters
This is my first time entering as well. Hope I'm doing this right.
```
public class W{String n="C D EF G A B",a="b_#",w="-^-^--^-^-^-";
public String z(String h){int r=0,i=0;char k=h.charAt(i);int p=n.indexOf(k);char l=h.charAt(++i);
if(a.contains(String.valueOf(l))){i++;r=a.indexOf(l)-1;}
p=(p+r)%12;String q=h.substring(i);q="q"+q.replace("-","_");
C c=C.valueOf(q);int[] s=c.s;String y="";
for(int j:s){int t=(j+p)%12;y+=w.charAt(t);}return y;}
enum C{q7(0,4,7,10),qM7(0,4,7,11),qm7(0,3,7,10),qdim7(0,3,6,9),qm7b5(0,3,6,10),q_M7(0,3,7,11);
int[] s;C(int...a){s=a;}}}
```
# Ungolfed
```
public class BlackWhiteKeys
{
String noteNames = "C D EF G A B";
String accidentals = "b_#";
final String blackWhite = "-^-^--^-^-^-";
public String analyze( String chordName )
{
int index = 0;
char tonic = chordName.charAt( index );
int pitch = noteNames.indexOf( tonic );
char alteration = chordName.charAt( ++index );
int transpose = 0;
if ( accidentals.contains( String.valueOf( alteration ) ) )
{
index++;
transpose = accidentals.indexOf( alteration ) - 1;
}
pitch = ( pitch + transpose ) % 12;
String quality = "q" + chordName.substring( index ).replace( "-" , "_" );
Chord c = Chord.valueOf( quality );
int[] semitones = c.semitones;
String pattern = "";
for ( int i : semitones )
{
int tone = ( i + pitch ) % 12;
pattern += blackWhite.charAt( tone );
}
return pattern;
}
enum Chord
{
q7(0, 4, 7, 10),
qM7(0, 4, 7, 11),
qm7(0, 3, 7, 10),
qdim7(0, 3, 6, 9),
qm7b5(0, 3, 6, 10),
q_M7(0, 3, 7, 11);
int[] semitones;
Chord( int... semitones )
{
this.semitones = semitones;
}
}
}
```
[Answer]
# Mathematica 296
```
f[s_]:=StringJoin[Mod[#3+#1+Switch[#2,"",0,"b",-1,"#",1],12]&@@StringSplit[s,Join[Thread@Rule[Characters["C D EF G A B"],Range[0,11]],{"7"->{0,4,7,10},"M7"->{0,4,7,11},"m7"->"0,3,7,10","dim7"->{0,3,6,9},"m7b5"->{0,3,6,10},"-M7"->{0,3,7,11}}]]/.Thread@Rule[Range[0,11],Characters["-^-^--^-^-^-"]]]
```
For Cdim7 (<-my favourite one)
```
In:= f["Cdim7"]
Out= -^^-
```
[Answer]
# Java - 247
```
String j(String s){int i=2,t=0,x=s.charAt(0)*2-128,c=s.charAt(1);x-=x/6+(c==98?1:c==35?-1:(i=1)-1);while(i<s.length())t+=s.charAt(i++);int[]a={0,t%11>0?3:4,t%9>0?7:6,(t%9-t%5)/3+10};s="";for(i=0;i<4;)s+=(1717&1<<(x+a[i++])%12)>0?"-":"^";return s;}
```
Basically a translation of my CJam solution :)
Executable program with better formatting:
```
public class J {
String j(String s) {
int i = 2, t = 0, x = s.charAt(0) * 2 - 128, c = s.charAt(1);
x -= x / 6 + (c == 98 ? 1 : c == 35 ? -1 : (i = 1) - 1);
while (i < s.length())
t += s.charAt(i++);
int[] a = { 0, t % 11 > 0 ? 3 : 4, t % 9 > 0 ? 7 : 6, (t % 9 - t % 5) / 3 + 10 };
s = "";
for (i = 0; i < 4;)
s += (1717 & 1 << (x + a[i++]) % 12) > 0 ? "-" : "^";
return s;
}
public static void main(final String... args) {
System.out.println(new J().j("D#m7"));
}
}
```
Output:
```
^^^^
```
] |
[Question]
[
A [Euler Brick](http://en.wikipedia.org/wiki/Euler_brick) is a cuboid where the length of all the edges are integers and all of the diagonals of the faces are integers as well. All sides must also be different.

Your program has to find as many different Euler Bricks where the sides are less than L within the time M (L and M will be defined later).
All of your calculated bricks have to be unique. This means that if your dimensions are the same, just in a different order, it must not be counted.
To calculate a brick means to find the lengths of the edges and the lengths of the diagonals of the faces of a valid Euler Brick.
Your bricks must also be indivisible by each other. In the same way that the Pythagorean triplet `6, 8, 10` is divisible by `3, 4, 5`, your bricks must ***not*** be divisible by each other.
To test your program, I will need to the following:
1. The language your code is written in
2. A command to run your code
3. Your code
Your score will be the average number of bricks your program calculates (running the program five times). To do this, I will run your program and end it after M minutes have elapsed. Once you have submitted your answer, I will add a comment on your answer telling what your score is. If you make an edit to your code, please notify me directly so I can find your score again.
For that reason, I need your program to print the number of bricks either at throughout the running or at the end. This can be done like so (in Python it would help if people told me how to do this in other languages for this example):
```
try:
# Calculation goes here
except KeyboardInterrupt: # I will use Ctrl-C
print(numberofbricks)
exit()
```
For this challenge `L=10^30` and `M=2 minutes`. In the event of a tie, the actual time taken to calculate all of the bricks will be used. The lower time wins.
I will find your time using the script below. All programs will be tested on the same machine.
```
import time, subprocess
command = # How do you run your program?
s=time.time()
subprocess.Popen(command, shell=True)
e=time.time()
print(e-s)
```
## Leaderboard
```
1. Peter Taylor - 5731679685.5 bricks per minute
2. Steve Verrill - 680262303 bricks per minute
3. Beta Decay - 0.5 bricks per minute
```
[Answer]
## C using Saunderson's parameterisation and Berggren's tree
In 1740, Saunderson found the parameterisation that if `(a, b, c)` is a Pythagorean triple (i.e. `a^2 + b^2 = c^2`) then `(a(2b-c)(2b+c), b(2a-c)(2a+c), 4abc)` is a *rational cuboid* (this was before Euler studied them) with diagonals `(c^3, a(5b^2+a^2), b(5a^2+b^2))`. This doesn't generate all Euler bricks. Note that if the brick is primitive iff the Pythagorean triple is primitive.
If `(x, y, z)` is an Euler brick then so is `(xy, xz, yz)`. Applying this once to a Saunderson brick creates a new brick which isn't Saunderson and which can be made primitive with division by `ab`. Applying the same transformation a second time gives the non-primitive `xyz(x, y, z)`.
In 1934, Berggren discovered that the primitive Pythagorean triples form a ternary tree rooted at `(3, 4, 5)` which can be generated by a simple matrix multiplication and which contains each triple precisely once.
This implementation generates primitive Pythagorean triples and stores them in a stack, limiting the memory usage to 1.5GB. An earlier version used a circular buffer, but the stack gives much better results. This is probably a combination of fewer values being discarded and better cache locality.
Thanks to [Steve Verrill](https://codegolf.stackexchange.com/users/15599/steveverrill) for pointing out some bugs and for suggesting the use of a stack instead of a circular buffer. I've also followed him in removing the conjugate bricks for speed: previously the search space (minus the discarded branches) was exhausted within the two minutes, and there was value in spending time to get a few conjugates. But the new version can easily run for 5 minutes (as I discovered in the process of learning the value of the `volatile` keyword!), and most of the conjugates overflow, so on average the tests are wasted time.
```
#include <stdlib.h>
#include <inttypes.h>
#include <stdio.h>
#include <signal.h>
#include <string.h>
// Stack size. This is 1.5GB of memory.
#define N 33554432
typedef unsigned __int128 scalar;
typedef struct {
scalar a, b, c;
} triple;
// Stack operations
#define take(st) st[--stp];
#define offer(A,B,C) if (stp < N) { st[stp].a=(A); st[stp].b=(B); st[stp].c=(C); stp++; }
volatile sig_atomic_t stop;
void handler(int sig, siginfo_t *siginfo, void *context) {
stop = 1;
}
int main(int argc, char **argv) {
// Register interrupt handler
stop = 0;
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_sigaction = &handler;
act.sa_flags = SA_SIGINFO;
if (sigaction(SIGINT, &act, NULL) < 0) return 1;
// L = 10^30
const scalar L = ((scalar)0xc9f2c9cd0UL << 64) + 0x4674edea40000000UL;
const scalar T = (scalar)1 << 64; // used in an anti-overflow test
// To avoid the optimiser removing the calculation of the bricks.
int writeToStdOut = argc > 1;
triple *st = (triple *)malloc(N * sizeof(triple));
if (!st) return 2;
uint32_t stp = 1; // Index of first empty space in stack
st[0].a = 3; st[0].b = 4; st[0].c = 5;
uint64_t count = 0;
while (stp > 0) {
if (stop) break;
triple t = take(st);
// Extend queue of Pythagorean triples
offer(t.a + ((t.c - t.b) << 1), ((t.a + t.c) << 1) - t.b, ((t.a - t.b + t.c) << 1) + t.c)
offer(t.a + ((t.c + t.b) << 1), ((t.a + t.c) << 1) + t.b, ((t.a + t.b + t.c) << 1) + t.c)
offer(-t.a + ((t.c + t.b) << 1), ((-t.a + t.c) << 1) + t.b, ((-t.a + t.b + t.c) << 1) + t.c)
// Saunderson brick
scalar x = t.b * ( ((t.a << 1) >= t.c) ? ((t.a << 1) - t.c) : (t.c - (t.a << 1)) ) * ((t.a << 1) + t.c);
scalar y = t.a * ((t.b << 1) - t.c) * ((t.b << 1) + t.c);
scalar z = t.a * t.b * t.c << 2;
scalar u = t.c * t.c * t.c;
scalar v = t.b * (t.b * t.b + 5 * t.a * t.a);
scalar w = t.a * (t.a * t.a + 5 * t.b * t.b);
count++;
if (writeToStdOut) {
printf("Sides: 0x%016"PRIx64"%016"PRIx64, (uint64_t)(x >> 64), (uint64_t)x);
printf(", 0x%016"PRIx64"%016"PRIx64, (uint64_t)(y >> 64), (uint64_t)y);
printf(", 0x%016"PRIx64"%016"PRIx64, (uint64_t)(z >> 64), (uint64_t)z);
printf("; diags 0x%016"PRIx64"%016"PRIx64, (uint64_t)(u >> 64), (uint64_t)u);
printf(", 0x%016"PRIx64"%016"PRIx64, (uint64_t)(v >> 64), (uint64_t)v);
printf(", 0x%016"PRIx64"%016"PRIx64"\n", (uint64_t)(w >> 64), (uint64_t)w);
}
}
printf("%ld\n", count);
return 0;
}
```
Compiles with `gcc -O3 euler_brick.c -o euler_brick` and handles `SIGINT` (Ctrl-C). On my computer the earlier circular buffer version ran out of usably small Pythagorean triples after 85 seconds having found `843035517` (0.843 thousand million) Euler bricks. The new version runs to the two minutes (tested with `timeout -sINT 2m ./euler_brick`) and finds about 9.1 thousand million bricks. Exact numbers vary from run to run; the highest I've observed is `9113459216`.
Note that this is single-threaded code. The process is embarrassingly parallel - just start each thread going down a different branch of the tree - and so the limitation to scaling it to multicore would be the shared memory bus.
[Answer]
# C using Saunderson's parameterisation and a different tree generation method.
This is heavily influenced by Peter Taylor's answer, and by the following page: <https://sites.google.com/site/tpiezas/0021>. For consistency, my variable naming convention largely follows Peter's.
Instead of using a buffer, I use recursion to generate the three children of each node of the tree. The tree I generate is equivalent to Berggren's tree, but I use a two-parameter method (mainly for interest and variation.) The parameters `p` and `q` for all integers generate a pythagorean triple `a=p^2-q^2, b=2pq, c=p^2+q^2`. If we want to limit this to primitive triples only, we start with the vector (2,1) and multiply by the 2x2 matrices below. This is equivalent to Berggren's / Barning's method, in which we start with the vector (3,4,5) and multiply by the 3x3 matrices below. See <http://en.wikipedia.org/wiki/Tree_of_primitive_Pythagorean_triples> .
```
Barning's matrices 2x2 matrices
1 -2 2 1 2 2 -1 2 2 2 -1 2 1 1 2
2 -1 2 2 1 2 -2 1 2 1 0 1 0 0 1
2 -2 3 2 2 3 -2 2 3
```
It can be seen from Barning's matrices that the hypotenuse `c` of the second child of each node will be between 3 and 7 times larger than that of its parent (more advanced treatment would narrow this range.) the growth rates of the other branches are rather slower.
In practice it was necessary to limit the depth of recursion in order to avoid stack overflow (segmentation fault.) However, it seems likely that only a few bricks were lost. Peter's program runs on my machine in about 6 minutes and generates `843035517` Euler bricks. My program takes just over twice as long and generates `1688135295` bricks with recursion depth limited to `5000`, or `1671621046` bricks with depth limited to `1000`. Therefore the rate of generation is about the same. With depth limited to `40`, `1134616080` bricks are generated, of which 1131433861 are Saunderson and only 3182219 are conjugate. And the program runs about twice as fast with the code for generating conjugate bricks commented out!
Instead of generating the conjugate brick of `(x,y,z)` as `(yz,xz,xy)` I generate a conjugate brick `ab` times smaller. To do this intermediate values `x',y',u',v'` are stored during the calculation of `x,y,z,u,v,w`.
```
#include <inttypes.h>
int writeStdOut,count=0;
typedef __int128 scalar;
scalar L=(scalar)1000000*1000000*1000000*1000000*1000000,T=(scalar)1<<124;
f(scalar p, scalar q, int depth){
scalar p2,q2,
a,b,c,a2,b2,c2,
uprime,vprime,u,v,w,
xprime,yprime,x,y,z;
p2=p*p;q2=q*q;
a=p2-q2;b=p*q<<1;c=p2+q2;
z=a*b*c<<2;
if(z<L){
a2=a*a;b2=b*b;c2=c*c;
xprime=(b2<<2)-c2;yprime=(a2<<2)-c2;
if(xprime<0)xprime=-xprime;if(yprime<0)yprime=-yprime;
x=a*xprime;y=b*yprime;
uprime=b2*5+a2;vprime=a2*5+b2;
u=a*uprime;v=b*vprime; w=c2*c;
count++;
if (writeStdOut) {
printf("Sides: 0x%016"PRIx64"%016"PRIx64, (uint64_t)(x >> 64), (uint64_t)x);
printf(", 0x%016"PRIx64"%016"PRIx64, (uint64_t)(y >> 64), (uint64_t)y);
printf(", 0x%016"PRIx64"%016"PRIx64, (uint64_t)(z >> 64), (uint64_t)z);
printf("; diags 0x%016"PRIx64"%016"PRIx64, (uint64_t)(u >> 64), (uint64_t)u);
printf(", 0x%016"PRIx64"%016"PRIx64, (uint64_t)(v >> 64), (uint64_t)v);
printf(", 0x%016"PRIx64"%016"PRIx64"\n", (uint64_t)(w >> 64), (uint64_t)w);
}
if(T/a/c>xprime && T/b/c>yprime){
x=a*c*xprime<<2;y=b*c*yprime<<2; if(x<0 | y<0)puts("overflow");
if(x<L && y<L){
z=xprime*yprime;
u=uprime*yprime;v=vprime*xprime;w=c2*c2<<2;
count++;
if (writeStdOut) {
printf("SIDES: 0x%016"PRIx64"%016"PRIx64, (uint64_t)(x >> 64), (uint64_t)x);
printf(", 0x%016"PRIx64"%016"PRIx64, (uint64_t)(y >> 64), (uint64_t)y);
printf(", 0x%016"PRIx64"%016"PRIx64, (uint64_t)(z >> 64), (uint64_t)z);
printf("; diags 0x%016"PRIx64"%016"PRIx64, (uint64_t)(u >> 64), (uint64_t)u);
printf(", 0x%016"PRIx64"%016"PRIx64, (uint64_t)(v >> 64), (uint64_t)v);
printf(", 0x%016"PRIx64"%016"PRIx64"\n", (uint64_t)(w >> 64), (uint64_t)w);
}
}
}
if(depth<40){f((p<<1)-q,p,depth+1);f((p<<1)+q,p,depth+1);f(p+(q<<1),q,depth+1);}
}
}
main(int argc, char **argv){
writeStdOut=argc>1;
f(2,1,0);
printf(" %d bricks",count);
}
```
[Answer]
# Python 3 - Brute forcing it
## Edit: This produces a measly 0.5 bricks per minute...
To get the ball rolling again, I decided to write a simple entry. As always with brute force methods, it's extremely slow.
```
def mult(x,y):
c=0
for i in range(len(x)):
if y[i]%x[i]==0:c+=1
if c==3:return True
return False
pyth=lambda x,y:True if (x**2+y**2)**0.5==int((x**2+y**2)**0.5) else False
prev=[]
ymax=245
zmax=269
try:
for x in range(44,10**30):
for y in range(117,ymax):
ymax+=1
for z in range(240,zmax):
zmax+=1
curr=[x,y,z]
eq=0
ml=0
for i in range(3):
for j in range(3):
if i!=j:
if curr[i]==curr[j]:
eq+=1
for k in prev:
if mult(curr, k):
ml+=1
if eq==0 and ml==0:
f=pyth(curr[0],curr[1])
s=pyth(curr[0],curr[2])
b=pyth(curr[1],curr[2])
if f and s and b:
prev.append(curr)
except KeyboardInterrupt:
print('\n\n'+str(len(prev)))
```
] |
[Question]
[
I want you to write a program that outputs a trigonometry circle like the one below. I also want you to animate this circle, having the sine line move along the circumference with the other lines move around it. **The minimum number of *unique* frames is 5. Any lower and your entry will not be counted.**

The lines you will need are:
* Sine (Both)
* Cosine (Both)
* Secant
* Cosecant
* Tangent
* Cotangent
* OA (on diagram)
## Edit: No longer a limit
This is a code golf challenge, but I want you to get your code to **below** my code which is written in BBC BASIC.
*Note:* I will remove this requirement if the challenge is too hard.
### My code: BBC BASIC - 185 bytes, 232 characters (Thanks Steve)
```
a=0:REPEAT:CLS:a+=0.005:CIRCLE600,500,300:s=300*SIN(a)+500:c=300*COS(a)+600:sc=300*1/COS(a)+600:cs=300*1/SIN(a)+500:MOVE600,500:DRAWc,s:DRAWc,500:DRAW600,500:DRAWsc,500:DRAWc,s:MOVE600,500:DRAW600,cs:DRAWc,s:DRAW600,s:WAIT 1:UNTIL0
```

[Answer]
## Mathematica, 142 bytes
```
Graphics[{Circle[],Line/@{{{c=Cos@t,0},{c,s=Sin@t},{0,s}},{{0,0},{1/c,0},{0,1/s},{0,0},{c,s}}},},PlotRange->{r={-2,2},r}]~Animate~{t,0.01,2Pi}
```
I'm plotting for angles between `0.01` and `2ฯ` which conveniently skips any angles where one of the lines would become actually infinite. You can make a GIF from it by replacing `Animate` with `Table`, adding a step width of `0.1` say and then using `Export` on the result:

So I got a bit bored and thought I'd give the full-blown thing a go (with all lines and colours). I omitted the labels, because they are really annoying to position and just clutter everything up.
```
Animate[
c = Cos@t;
s = Sin@t;
h = Sign@c;
v = Sign@s;
i = .1 h;
j = .1 v;
Graphics[{
Thick,
Circle[],
Line /@ {{{c, -s}, {0, 0}, {c, s}}, {{-i, 0}, {-i, j}, {0,
j}}, {{-i + c, 0}, {-i + c, j}, {c, j}}, {{c - .1 s,
s + .1 c}, {1.1 c - .1 s, 1.1 s + .1 c}, 1.1 {c, s}}},
Circle[{0, 0}, 0.1, {t, Round[t, Pi]}],
Blue,
Line /@ {{{0, 0}, {c, 0}}, {{0, s}, {c, s}}},
Red,
Line /@ {{{0, 0}, {0, s}}, {{c, 0}, {c, s}}},
Darker@Green,
Line[{{c, 0}, {h, 0}}],
Cyan,
Line[{{0, s}, {0, v}}],
Lighter@Lighter@Magenta,
Line[{{h, 0}, {1/c, 0}}],
Darker@Darker@Green,
Line[{{0, v}, {0, 1/s}}],
Orange,
Line[{{0, 1/s}, {c, s}}],
Lighter@Brown,
Line[{{1/c, 0}, {c, s}}],
Gray,
Line[{{c, 0}, {c, -s}}],
Lighter@Gray,
Line[{{c, s}, {h, 0}}],
Lighter@Pink,
Line /@ {{{-.45 h, 0}, {-.55 h, 0}}, {{-.45 h, 1/s}, {-.55 h,
1/s}}},
Arrowheads[{-.05, .05}],
Arrow[{{-.5 h, 0}, {-.5 h, 1/s}}],
Darker@Cyan,
Line /@ {{{0, -.45 v}, {0, -.55 v}}, {{1/c, -.45 v}, {1/
c, -.55 v}}},
Arrow[{{0, -.5 v}, {1/c, -.5 v}}],
Dashed,
Black,
Line[{{c, s}, 1.3 {c, s}}],
Lighter@Pink,
Line /@ {{{0, 0}, {-.5 h, 0}}, {{0, 1/s}, {-.5 h, 1/s}}},
Darker@Cyan,
Line /@ {{{0, 0}, {0, -.5 v}}, {{1/c, 0}, {1/c, -.5 v}}}
}, PlotRange -> {r = {-2, 2}, r}],
{t, 0.01, 2 Pi}
];
```
Enjoy!

And because this is still a code-golf question I golfed this down as well, to see how short I could get it. Currently, **719 bytes**:
```
Graphics[{Thick,Arrowheads@{-.05,.05},(z=Circle)[],(n=Line)/@{{p={c=Cos@t,s=Sin@t},o={0,0},{c,-s}},{-{i=.1(h=Sign@c),0},{-i,j=.1(v=Sign@s)},{0,j}},{{-i+c,0},{-i+c,j},{c,j}},{p+(q={-.1s,.1c}),1.1p+q,1.1p}},z[o,0.1,{t,Round[t,Pi]}],{e=Dashed,n[{p,1.3p}]},Blue,n/@{{o,a={c,0}},{b={0,s},p}},Red,n/@{{o,b},{a,p}},g=(d=Darker)@Green,n@{a,{h,0}},y=Cyan,n@{b,{0,v}},(l=Lighter)@l@Magenta,n@{{h,0},f={1/c,0}},d@g,n@{{0,v},u={0,1/s}},Orange,n@{u,p},l@Brown,n@{f,p},r=Gray,n@{a,{c,-s}},l@r,n@{p,{h,0}},l@Pink,n/@{q={{-.45h,0},{-.55h,0}},{u,u}+q},Arrow@{q={-.5h,0},u+q},{e,n/@{{o,q},{u,u+q}}},d@y,n/@{q={{0,-.45v},{0,-.55v}},{f,f}+q},Arrow@{q={0,-.5v},f+q},{e,n/@{{o,q},{f,f+q}}}},PlotRange->{r={-2,2},r}]~Animate~{t,0.01,2Pi,0.05}
```
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 125 bytes
```
P5.sizeโ2โฟ300
tโ0
gโP5.G
zโ0 0
P5.drawโ{g.bgยฏ1
g.circle 3โฟ90
g.ln aโ90ร1+z,2 1โt
g.rect a
g.ln 90ร1+z,(รท2โt),z,z,โจรท1โt
t+โ.1}
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfz/P8BUrzizKvVR2wSjRz37jQ0MuEqAbAOudCAJlHPnqgJxFQy4gJyUosRyIK86XS8p/dB6Q650veTMouScVAVjoFZLoB69nDyFRKAKS4PD0w21q3SMFAwfTe8uAUoUpSaXKCRCVMBkNQ5vNwJJa@pUAeGj3hWHt0OUl2gDzdAzrP3/HwA "APL (dzaima/APL) โ Try It Online")
Displays it at the top left corner:
[](https://i.stack.imgur.com/Il3Jw.gif)
## Explanation
`P5.sizeโ2โฟ300` make a 300x300 canvas
`tโ0` set angle \$\theta=0.\$
`gโP5.G` shorten drawing namespace
`zโ0 0` save [0,0] in `z`
`P5.drawโ{` Do the following repeatedly:
`g.bgยฏ1` Draw a white background
`g.circle 3โฟ90` draw a circle of radius 90 at \$(90, 90)\$
`g.ln aโ90ร1+z,2 1โt` Line from \$(90,90)\$ to \$(90cos\theta, 90sin\theta)\$ for angle
`g.rect a` rectangle using the same coordinates
`g.ln 90ร1+z,(รท2โt),z,z,โจรท1โt` triangle with the points \$(90, 90),(90,90/cos\theta),(90/sin\theta,90)\$
`t+โ.1` increment angle \$\theta\$
] |
[Question]
[
# Challenge
Display Inky the ghost from Pac-Man using only [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code).
[](https://i.stack.imgur.com/IF6yj.png)
Here's a text representation of the image
```
B B B B B C C C C B B B B B
B B B C C C C C C C C B B B
B B C C C C C C C C C C B B
B C W W C C C C W W C C C B
B W W W W C C W W W W C C B
B E E W W C C E E W W C C B
C E E W W C C E E W W C C C
C C W W C C C C W W C C C C
C C C C C C C C C C C C C C
C C C C C C C C C C C C C C
C C C C C C C C C C C C C C
C C B C C C B B C C C B C C
C B B B C C B B C C B B B C
```
| Code | ANSI Escape Code | Background Color |
| --- | --- | --- |
| B | "\x1b[40m" | Black |
| C | "\x1b[46m" | Cyan |
| W | "\x1b[47m" | White |
| E | "\x1b[44m" | Blue |
# ANSI Intro
This C [example](https://godbolt.org/z/qhjj96YqG) shows the use of ANSI escape codes to print [](https://i.stack.imgur.com/tWDHC.png)
# Disclaimer
No Inky's were harmed in the making of this challenge. [](https://i.stack.imgur.com/9apip.png)
[Answer]
# JavaScript (ES6), 146 bytes
NB: The actual code contains the unprintable character `\x1b`.
```
f=(x=n=0)=>n<195?(x>13?`
`:`\x1b[4${"6074"[[5301,4781,4097,p=2731,p,2861,130,,,,,748,2458][y=n/15|0]*3>>x&1|7800/"52225"[y-3]>>x&2]}m `)+f(++n%15):""
```
[Try it online!](https://tio.run/##FcjdCoIwGIDh826hkxgVW67atx@3oq0LGYJiGoVNyQiluvZV78Fz8F6LZ9GX90v3WIf2VMVYWzzYYBmxLhxgp454cCCO@STf51Mv5y@UMi2R90owoFKbH2ynaWe5FkA7yk0KFASj/7Q0lEtlMj/asAX1ZtlKODcs4a0NY1ukOOcK@XEtsv/m2ec2y0lS4yQJC1Bkj1As29C3TbVp2jOuMSHxCw "JavaScript (Node.js) โ Try It Online")
Or [148 bytes](https://tio.run/##FcjdCoIwGIDh826hkxgVW67atx83pc0LGYJRGYVNyQijuvaV78Fz8F73z31/uF@6xzq0x1OMtcWDDZYR68IOsrTAgwNRVJMqr6Zezt8oZVoi75VgQKU2f1imaWe5FkA7yk0KFASjY1oayqUyFEr/smEL6sPKlXBuWMJHG8a2SHHOFfKvtSjHzcvvbVaRpMZJEhagSI5QPLShb5vTpmnPuMaExB8) to restore a black background.
### Output
[](https://i.stack.imgur.com/VypqX.png)
### Encoding
| y | black/blue layer | decimal | / 3 | white/blue layer | decimal |
| --- | --- | --- | --- | --- | --- |
| 0 | 11111000011111 | 15903 | 5301 | 00000000000000 | 0 |
| 1 | 11100000000111 | 14343 | 4781 | 00000000000000 | 0 |
| 2 | 11000000000011 | 12291 | 4097 | 00000000000000 | 0 |
| 3 | 10000000000001 | 8193 | 2731 | 00001100001100 | 780 |
| 4 | 10000000000001 | 8193 | 2731 | 00011110011110 | 1950 |
| 5 | 10000110000111 | 8583 | 2861 | 00011110011110 | 1950 |
| 6 | 00000110000110 | 390 | 130 | 00011110011110 | 1950 |
| 7 | 00000000000000 | 0 | 0 | 00001100001100 | 780 |
| 8 | 00000000000000 | 0 | 0 | 00000000000000 | 0 |
| 9 | 00000000000000 | 0 | 0 | 00000000000000 | 0 |
| 10 | 00000000000000 | 0 | 0 | 00000000000000 | 0 |
| 11 | 00100011000100 | 2244 | 748 | 00000000000000 | 0 |
| 12 | 01110011001110 | 7374 | 2458 | 00000000000000 | 0 |
[Answer]
# Commodore C64, using PETSCII graphics, ~392 BASIC bytes
The simplest way to do this is to use the reverse character mode to print out white spaces, but changing the colours as necessary. These are [Control characters](https://www.c64-wiki.com/wiki/control_character) in Commodore BASIC, similar to escaped characters in a C or PHP string. We will use a string array `B$`, and then a `FOR/NEXT` loop to output to the C64 screen. All colours in this listing are accessed by the control (often referred to as `CTRL`) key, by pressing the following key combinations:
```
{BLACK} is CTRL + 1
{WHITE} is CRTL + 2
{CYAN} is CTRL + 4
{BLUE} is CRTL + 7
{REVERSE ON} is CTRL + 9
```
To make the listing clearer and easier to type in, `{SPACE x 5}` indicates 5 spaces following the control character, as looking at the listing in Commodore BASIC might not be very clear.
Here is the listing:
```
0DIMB$(12):B$(.)="{BLACK}{SPACE x 5}{CYAN}{SPACE x 4}{BLACK}{SPACE x 5}":B$(1)="{BLACK}{SPACE x 3}{CYAN}{SPACE x 8}{BLACK}{SPACE x 3}"
1B$(2)="{BLACK}{SPACE x 2}{CYAN}{SPACE x 10}{BLACK}{SPACE x 2}":B$(3)="{BLACK}{SPACE}{CYAN}{SPACE}{WHITE}{SPACE x 2}{CYAN}{SPACE x 4}{WHITE}{SPACE x 2}{CYAN}{SPACE x 3}{BLACK}{SPACE}"
2B$(4)="{BLACK}{SPACE}{WHITE}{SPACE x 4}{CYAN}{SPACE x 2}{WHITE}{SPACE x 4}{CYAN}{SPACE x 2}{BLACK}{SPACE}":B$(5)="{BLACK}{SPACE}{BLUE}{SPACE x 2}{WHITE}{SPACE x 2}{CYAN}{SPACE x 2}{BLUE}{SPACE x 2}{WHITE}{SPACE x 2}{CYAN}{SPACE x 2}{BLACK}{SPACE}"
3B$(6)="{CYAN}{SPACE}{BLUE}{SPACE x 2}{WHITE}{SPACE x 2}{CYAN}{SPACE x 2}{BLUE}{SPACE x 2}{WHITE}{SPACE x 2}{CYAN}{SPACE x 3}":B$(7)="{CYAN}{SPACE x 2}{WHITE}{SPACE x 2}{CYAN}{SPACE x 4}{WHITE}{SPACE x 2}{CYAN}{SPACE x 4}"
4B$(8)="{CYAN}{SPACE x 14}":B$(9}=B$(8):B$(10)=B$(8):B$(11)="{CYAN}{SPACE x 2}{BLACK}{SPACE}{CYAN}{SPACE x 3}{BLACK}{SPACE x 2}{CYAN}{SPACE x 3}{BLACK}{SPACE}{CYAN}{SPACE x 2}"
5B$(12)="{CYAN}{SPACE}{BLACK}{SPACE x 3}{CYAN}{SPACE x 2}{BLACK}{SPACE x 2}{CYAN}{SPACE x 2}{BLACK}{SPACE x 3}{CYAN}{SPACE}":FORI=.TO12:PRINT"{REVERSE ON}"B$(I):NEXT
```
Some notes: be careful when entering line 4 as it is 80 characters in length (the maximum number of characters in a logical C64 line). Cursor up so that the flashing cursor is over one of the characters on the line and press the return key. Or, enter this into a Commodore C128, which allows for 160 characters in a logical line; this will work in C64 or C128 mode. I typed this in again from the listing above to check that the number of spaces and control characters are correct, and it seems fine. Best viewed with `POKE 53280, 0: POKE 53281, 0: RUN`.
By using C128 BASIC, and with the 160 PETSCII character per logical line, this can be crunched further as you will be able to reduce the line numbers. Some bytes could also be saved by removing some of the control characters, for instance, where `B$(0)` ends with `{BLACK}` there is no need to start `B$(1)` with `{BLACK}`. I will try to crunch this further to save some more bytes.
And here is how things look on a C64 (at least a C64 emulator):
[](https://i.stack.imgur.com/ZLhZN.png)
[](https://i.stack.imgur.com/5y2Ei.png)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 151 bytes
*-3 thanks to [@vengy](https://codegolf.stackexchange.com/users/119544/vengy)*
*-28 thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
Essentially a port of my JS answer.
```
n;y;main(x){for(;n<195;printf(x>13?"\n":"[4%cm ","6074"[L"ใธใ ใโโโฦ\0\0\0\0เฃแณ"[y=n++/15]>>x&1|(y>2&y<8)*7800/(~y&3?2:5)>>x&2]))x=n%15;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/PutI6NzEzT6NCszotv0jDOs/G0NLUuqAoM68kTaPCztDYXikmT8lKSTraRDU5V0FJR8nMwNxEKdpH6fGO@Y8XtD9uaH7U0AhCbe3H2mIMIPDB4paHm/uUoitt87S19Q1NY@3sKtQMazQq7YzUKm0sNLXMLQwM9DXqKtWM7Y2sTDVB0kaxmpoVtnmqhqbWtf///0tOy0lML/6vWw4A "C (gcc) โ Try It Online")
### Output
[](https://i.stack.imgur.com/W9dVW.png)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 147 bytes
```
i=182;main(){for(;i--;)printf("\e[4%cm %s","0674"[3&"ATPATQETQUUUUUUUUUUUUUUUeVeVUzWzGe~e~PiZiJTiUiATUUE@TUU@@PU"[i/3]>>i%3*2],i%14?"":"\e[0m\n");}
```
[Try it online!](https://tio.run/##Vc3NCoJAFEDhV4kLExoO@UdFQ6YLCVopzBikLmQY5UJaaBAY@ehNtewsvu2RtJFSa9w5G5e1FXaG@ayvvcGQUmbeeuzutQGFyn0i2xkZwAJ7tfYh9@YQ8STiacxT8Z/KVCbG03hQk5oSPOORo8CICxGHX8IwEZDj0iuDAIm3cEsLiePvAba/kd0WHZjspfVb1peqGTR9fAA "C (gcc) โ Try It Online")
-4B from ceilingcat
Port like
Assumes that after `...TUU@@PU` there are 2 null bytes
[Answer]
# [Perl 5](https://www.perl.org/) + `-p0513`, 132 bytes
```
s!!5.2B8.4B5.5B3.CLBCLB2.2MB2MB2.,MB,MB.@/L@/L2BM2BM24B.B<.B<B<2.B2.B3..!;s/\d+(.)/$1x$&/ge;s/./ord$&/ge;s/.{14}\K/
/g;s/./.[4$&m /g
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiMDAwMDAwMDA6IDczMjEgMjEzNSAwMDMyIDQyMzggMDAzNCA0MjM1IDAwMzUgNDIzMyAgcyEhNS4yQjguNEI1LjVCM1xuMDAwMDAwMTA6IDAwNDMgNGM0MiA0MzRjIDQyMzIgMDAzMiA0ZDQyIDMyNGQgNDIzMiAgLkNMQkNMQjIuMk1CMk1CMlxuMDAwMDAwMjA6IDAwMmMgNGQ0MiAyYzRkIDQyMDAgNDAyZiA0YzQwIDJmNGMgMzI0MiAgLixNQixNQi5AL0xAL0wyQlxuMDAwMDAwMzA6IDRkMzIgNDI0ZCAzMjM0IDQyMDAgNDIzYyAwMDQyIDNjNDIgM2MzMiAgTTJCTTI0Qi5CPC5CPEI8MlxuMDAwMDAwNDA6IDAwNDIgMzIwMCA0MjMzIDAwMDYgMjEzYiA3MzJmIDVjNjQgMmIyOCAgLkIyLkIzLi4hO3MvXFxkKyhcbjAwMDAwMDUwOiAyZTI5IDJmMjQgMzE3OCAyNDI2IDJmNjcgNjUzYiA3MzJmIDJlMmYgIC4pLyQxeCQmL2dlO3MvLi9cbjAwMDAwMDYwOiA2ZjcyIDY0MjQgMjYyZiA2NzY1IDNiNzMgMmYyZSA3YjMxIDM0N2QgIG9yZCQmL2dlO3MvLnsxNH1cbjAwMDAwMDcwOiA1YzRiIDJmMGEgMmY2NyAzYjczIDJmMmUgMmYxYiA1YjM0IDI0MjYgIFxcSy8uL2c7cy8uLy5bNCQmXG4wMDAwMDA4MDogNmQyMCAyZjY3ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBtIC9nIiwiYXJncyI6Ii1wMDUxMyJ9)
## Explanation
The string of random numbers and symbols is an RLE string that contains the data for all the background colours (only the last digit, as the first digit's always `4`), this is stored in `$_` via the `s///`ubstitution operator. This is decoded to repeated runs of characters and each of those characters is replaced with its `ord`inal value, split into run of `14` characters and has the ANSI escape code string wrapped around each value.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 150 bytes
```
f=(x=182)=>x?`\x1B[4${'0674'[3&Buffer('ATPATQETQUUUUUUUUUUUUUUUeVeVUzWzGe~e~PiZiJTiUiATUUE@TUU@@PU')[--x/3|0]>>x%3*2]}m `+(x%14?'':`\x1b[0m
`)+f(x):''
```
[Try it online!](https://tio.run/##Vc1NC4IwAIDhu7@iQ7YtsTSlwtBUkKCTwVaQCfaxxUIzsmJY@ddXHXsPz/U9bR/ban/ll5t@Lg9USuZC4ZrjAXI9Mc02wgwTu/0ExnBkg8TqhHfG6BWCAMcBXkR4Qf6jS7ok9aqe0YY2MV/zOeaEB5iQyP/i@zEBKNF10bdeRup5QrW6g/RdtDINCtW0pwA4v@suMQolQxqDAjkAyImyL89VmdNeXh4hgwjJDw "JavaScript (Node.js) โ Try It Online")
Hardcode
Arnauld's solution spill color and mine don't. Removing this difference mine is shorter, but Arnauld usen't Buffer
I don't use char `\x1B` since otherwise it's better encode 4 pos in a char
[Answer]
# C (gcc, msvc), 228 bytes
```
#include<stdio.h>
j,i[]={89391445,88080405,83886085,77597185,111684225,132660865,65552000,10488320,0,0,0,4214800,22040660};main(){for(;j<182;j++)printf("\x1B[4%cm%s","6074"[(i[j/14]>>(2*(13-j%14)))&3],j%14==13?" \x1b[0m\n":" ");}
```
NB: The actual code contains the unprintable `ESC` character `\x1b`.
[Try it online!](https://godbolt.org/z/6751ejE5K)
# Output
Windows Command Prompt:
[](https://i.stack.imgur.com/zfQzm.png)
Linux (Ubuntu) Terminal:
[](https://i.stack.imgur.com/Qtfho.png)
] |
[Question]
[
Your task here will be to write a very dumb AI capable of fetching all treasures on a map.
## Map
The map is defined as follow: (`artist-mode`โข-powered)
Basic case:
```
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|P| | | | | | | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | |T| | | | | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | |M|M|M|T| | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | |T| | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
---
Locked up:
```
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|P| | | | |M| | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | |M| | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | |T| | |M| | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M| | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
---
No treasures
```
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|P| | |M|M|M| | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | |M|M|M|M|M|M|M| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | |M| | | | | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | |M|M|M|M| | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
---
No way to move
```
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|P|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
---
The world is a giant treasure
```
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T|T|T|T|T|T|T|T|T|T|T|T|T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T|T|T|T|T|T|T|T|T|T|T|T|T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T|T|T|T|T|T|P|T|T|T|T|T|T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T|T|T|T|T|T|T|T|T|T|T|T|T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T|T|T|T|T|T|T|T|T|T|T|T|T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T|T|T|T|T|T|T|T|T|T|T|T|T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
---
Back alley
```
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|P| | | | | | | | | | | |T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | |M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | |M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | | | | |T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | |M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
---
1x1
```
+-+
|P|
+-+
```
## Cells
* Empty cases are empty
* `M` cells are mountains and cannot be walked on.
* `T` cells are treasures that need to be collected.
## Goal
* You will generate a "path string" describing the movements needed to obtain all the treasures. No extraneous moves after treasures were all collected are allowed.
* Moves can be: "Left" "Right" "Up" "Down".
* Generating a move that'd result in an attempt to clib a mountain (M) or hit a wall (Out Of Bounds) is an error (it's not simply ignored).
## General Rules
* **Map must be read.** (this is not a [compression](/questions/tagged/compression "show questions tagged 'compression'") challenge, there are an infinite possible number of maps).
* There will always be one and only one player, P.
* There will always be a path to go get all the treasures, T.
* Map size may vary, but it'll always be at least `1x1`.
* The AI starts at P, the player.
* There might not be a treasure on the map. In this case, you're allowed to exit any falsy value (that isn't a valid path)
* Your algorithm pick -- it needn't be the most efficient.
* You must solve it before the heat death of the universe
* It is not guaranteed you'll be able to access every non-mountain cell on the map. Just enough to fetch all treasures.
* The AI may see the whole map.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Format
### Input
* You can decide to take inputs as a multi-line string with or without the ASCII separators I included (same for the space between cells)
* Passed via stdio or a function argument or on your program's stack(s)
* You can other identifiers instead of " ",M,P -- so long they are uniquely identifiable and not a separator (you need it specified in your answer)
* You can decide to take an 2-dimensional array, or matrix, or the equivalent in your language, with the cells, as `[['P', ' ', ' '...], [...], [' ', ' ', 'T'...]...]`.
* You are also allowed to take an array of strings, such as `["P ...", ..., " T..."...]`.
* You are allowed to take the length as an extra input (width/height).
### Output
* The output must look like "LLRRUUDD" (Left/Left/Right/Right/Up/Up/Down/Down)
* You can decide to intersperse spaces, newlines, etc, so long they don't mix with your instructions.
* You can other identifiers instead of L,R,U,D -- so long they are uniquely identifiable and not a separator (you need it specified in your answer)
* There might be different solutions (i.e. `DR` vs `RD`), it doesn't matter which you output in this case.
## Scoring
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge.
[Answer]
# [PHP](https://php.net/), ~~385~~ ~~335~~ ~~307~~ ~~270~~ 256 bytes
```
function c(&$m,$x,$r=-1,$d=0){if($r<0)$r=array_search(P,$m);$m[$r]=V;if(!in_array(T,$m))die;foreach([$r%$x?$r-1:-1,$m[$r-$x]?$r-$x:-1,$m[$r+$x]?$r+$x:-1,$r%$x<$x-1?$r+1:-1]as$o=>$n)if($n>=0&$m[$n]!=M&$m[$n]!=V){echo LUDR[$o];c($m,$x,$n,$o);}echo RDUL[$d];}
```
[Try it online!](https://tio.run/##rZBBa8IwFMfP66eI8DYTTLFlt8UobB4VRKqXEiTEuPbQpLw66BA/e9c4kV23eXgk/N7/F95LXdTdZFYXNbGIHndoa4/H0r3ThInu8OHMsfSOGPoEFYeWA8o45bCXCTuVBwo4SVjPNKL@3DVWoynoikPFBFQ5oJJb0ccGpdtdIjQLPbYvrTh4tLpP96lHaGeAcfoSng5aDK2aXY4bGn2j0RUFZwJtnAYWRKUb8HIKjoWx3FQmT8FzaiCXt9uWnawpPFls5uscvBKGXtdyHDwT50t3Pd8sctgrce6i8Zi86qY05E03NoIqJZLk0cNwNeRD8rvqLfIvK/uTtfxR2V0mzO6ylxKRoaT/UU7SZ8JE1H0B "PHP โ Try It Online")
Uses a recursive depth-first search to crawl the map until all treasures are found.
Input is a one-dimensional array map and number of columns, example: `c( $map, 13 );`.
Output is to `STDOUT` as `L,R,U and D`.
Or **242 bytes** to [output as numbers](https://tio.run/##rZBBa4MwFMfP81Ok8FYTGqmy22IqbOdCD9JLEQkxTg8m8uzAUfrZnelK2XVrD4@EX/6/x3vpm35Ks77piUF0WKLpHR5b@0FjJqb60@pj6yzRdAkdh5EDyijhUMmYndqaAqYxm5lCVF/lYBTqhu44dExAdwAs5F7MsUVry0uE5v6NVa0RtUOj5vSceoYxA4ySV9/aaxGMRXY5bmj1g1ZX5J0UxijxzIuFGsDJDVjmx7IbGS@9Z4uF3N5ue3YyunHghKbXfSwHx8T5gitxnoL1mrypodXkXQ0mgC4hkhyCp3AX8pD8rWaL3GXl/7K2vyp/yIT5Q/YqRKApmX@Uk@SFMBFM3w) (but I prefer the letters).
**Ungolfed**
```
function c( &$m, $x, $r=-1, $d=0 ) {
// locate starting room ($r) on first move
if( $r < 0 )
$r = array_search( 'P', $m );
// mark square on map ($m) with V to show it has been visited
$m[ $r ] = 'V';
// end if no more treasures
if ( ! in_array( 'T', $m ) )
exit;
// generate list of adjacent squares
$dirs = [
$r % $x ? $r - 1 : -1, // Left
$m[ $r - $x ] ? $r - $x : -1, // Up
$m[ $r + $x ] ? $r + $x : -1, // Down
$r % $x < $x - 1 ? $r + 1 : -1 // Right
];
// consider valid directions for next move
foreach ( $dirs as $o => $n )
// if not a Wall or Mountain and not Visited
if ( $n >= 0 and $m[ $n ] != 'M' and $m[ $n ] != 'V' ) {
// display the direction
echo 'LUDR'[ $o ];
// and recursively keep crawling
c( $m, $x, $n, $o );
}
// reached a dead end, go back to previous square
echo 'RDUL'[ $d ]; // display the reverse direction
}
```
[Basic Case](https://tio.run/##rZBBa8IwFMfP66eI8DYTTLFlt8UobB4VRKqXEiTEuPbQpLw66BA/e9c4kV23eXgk/N7/F95LXdTdZFYXNbGIHndoa4/H0r3ThInu8OHMsfSOGPoEFYeWA8o45bCXCTuVBwo4SVjPNKL@3DVWoynoikPFBFQ5oJJb0ccGpdtdIjQLPbYvrTh4tLpP96lHaGeAcfoSng5aDK2aXY4bGn2j0RUFZwJtnAYWRKUb8HIKjoWx3FQmT8FzaiCXt9uWnawpPFls5uscvBKGXtdyHDwT50t3Pd8sctgrce6i8Zi86qY05E03NoIqJZLk0cNwNeRD8rvqLfIvK/uTtfxR2V0mzO6ylxKRoaT/UU7SZ8JE1H0B "PHP โ Try It Online")
```
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|P| | | | | | | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | |T| | | | | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | |M|M|M|T| | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | |T| | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
`DDDDDRUUUUURDDRUURDDRUURDDDLDLLLDRRRRURUUUURDDDDDLRRU`
[Locked Up](https://tio.run/##7Zbfb9owEMefx19xlTxI1KCS0l9aSNG6PuwBT6gKfYkiZCWGRIU4cugaVvVvZ3YaWo/xY6TptIc9HET2fX13H5/jJGGy6HSTMAHKOeNDThPGZ1E81lq6tRjdx/4sYjH4Wh1NDZQZiNtN00CT/DewW/pjNNIQ77R0MUM4J/NhSgn3Q61voKluoakrnBH37FtLeB5E8TD30hw5rQcRtUaMUyIELuIfUdZFvGl@kqsLJW@izOvmfy9Dh89Dh8WQ1HRQ1jTlmBR6JEXMvkSxLjOLL@1WvS6FsXdg49fHW/2R@iGD3uD6xkXMs3ytqDAWixqI6dZT7nBzPei5KPCsp0Xt6AiuSBr58IWktIamJtjg1j40@g2jAfuZUMGbVE4pFVbMqSRDp5K6PEvA9TUQTA0w26BbNUm7x/w7GsAgEbCPt8DGpUrBpWDvVuEV0Lh0hu/TRAJ2jvpYRf2NwUwcxPSey85ur4H9tlLwFvu9R/ffon8ddnsF9gOZw4zBlH2XvE8K3ngHqTX2X/VifYX3icrbCSk8MD4JIEqBwDgi8Uxt99MCv1Oc9T2sclX/L8aqXrXEf6rivyL@HXyeTOhcsD4reWk6f3QE1zfS@xz3amKVr2vJ@kxlbWamgHwuIQvES5dz4bL0@EqDMQVMfsjOv1B2Ayu3Hd5wVyofD0XWeMNr21n/mVH01bp11dj41znlZbAtq5W5HbE2rLQSy9lxicFr5z@zvlhux@In)
```
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|P| | | | |M| | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | |M| | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | |T| | |M| | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M| | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | | | | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
`DDRUURDD`
[No Treasure:](https://tio.run/##7Zbfb9owEMefx19xlTxI1KCS0l9aSNG6PuwBV6gKfUERshIDUUkcOXQNq/q3U5uG4rEAI02nPezhILLv67v7@BwnHsfzVjsex0A5Z3zAacz4NIhGWkO35sOHyJsGLAJPq6LQQKmBuF03DTRZ/Pp2Q38KhhrirYYuZgjnZDZIKOHeWOsaKNQtFPaFM@KufWcJz4MgGiy8NEdO635ArSHjlAhBH/HPKG0jXje/yNWFktdR6rYXf29Dh69Dh9mQ1LRQWjflmBS6JEHMvkSRLjOLLu1GtSqFkXtg49Xjnf5EvTGDTu/6to@Ya3laVmEkFjUQ063nhcPtda/TR75rPc8rR0dwRZLAg28koRUUmmBDv/Kp1q0ZNdjPhArepXIKqbBiTikZOqXU5VoCrqeBYGqA2QTdqkjaHebdUx96sYB9vAU2LlQKLgR7twqvgcaFM/yYJlrBPlZh3zCYiqOYPHDZ280c3O8rBm@x37t0/036h3EvYDfXYD@SGUwZhOyH5H2S8cY7SOXYf9WbdRXeJypvZ0zhkfGJD0ECBEYBiaZqu59m@J3stO9hpau6fzFW@aol/lMV/xXx7uHrZEJngvVZwWvT@aMjmN9IH3Pcy4lVvK4l6zOVtZmaAvK5hCwQL13OhcvS4zv1RxQw@Sk7/0LZDazcd3jDbal8PmRZ4w2vbSf/QyPrq7x11dj41znlZbAtq7W5HbE2rLQWy9lxicGq819ZXyy3Y/4C)
```
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|P|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
ย *(no output)*
[No way to move](https://tio.run/##7Zbfb9owEMefx19xlTxI1KCS0l9aSNG6PuwBT6gKfUERshJDokIcOXQNq/q3MxtC8ViAkabTHvZwENn39d19fI4TB/G81Y6DGCjnjA84jRmfhtFIa@jWfPgYedOQReBpVTQxUGogbtdNA40Xv77d0J/DoYZ4q6GLGcI5mQ0SSrgXaF0DTXQLTfrCGXHXvreE51EYDRZemiOndT@k1pBxSoSgj/hHlLYRr5uf5OpCyesodduLv9eh4@XQcTYkNS2U1k05JoUuSRCzr1Gky8yia7tRrUph5B7ZeP14rz9TL2DQ6d3e9RFzLU/LKozEogZiuvWycLi77XX6yHetl3nl5ARuSBJ68IUktIImJtjQr3yodWtGDQ4zoYI3qZxCKqyYU0qGTil1uZaA62kgmBpgNkG3KpJ2h3kP1IdeLGCf7oCNC5WCC8Her8IboHHhDN@nidawT1XY3xhMxVFMHrns7WYO7rcVg3fY7116@Cb9@7ibG7ifyAymDCbsuyR@lhHHe1jl2H/Vq3WXxBe8z1TeTkDhifGxD2ECBEYhiaZqw59n@J3svB9gpau6fzFW@aoV/nMV/w3xHuDzeExngvVFwYvT@aNDmN9I73Pgy4lVvK4V6wuVtZmaAvKlhCwQr1wuhcvK4yv1RxQw@SE7/0rZDazceHjLfal8QGRZ4y0vbif/UyPrq7x11dj41znlZbArq425PbG2rLQRy9lzjcG685esr1bbMf8J)
```
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M|M|M|M|M|M|M|M|M|M|M|P|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
ย *(no output)*
[The world is a giant treasure](https://tio.run/##7Zbfb9owEMefx19xlTxI1KCS0l9aSNG6PuwBT6gKfYkiZCUGokIcObQNq/q3MzsNxWUBRkqnPezhILLv67v7@BwnHsXzVjsexUA5Z7zPacz4NIyGWkO35oP7yJ@GLAJfq6KJgVIDcbtuGmic/QZ2Q38KBxrirYYuZgjnZNZPKOH@SOsaaKJbaOIKZ8Q9@9YSngdh1M@8NEdO60FIrQHjlAiBi/hnlLYRr5tf5OpCyeso9drZ3@vQ4cvQYT4kNS2U1k05JoUeSRCzL1Gky8yiS7tRrUph5B3YePl4qz9Rf8Sg07u@cRHzLF/LK4zEogZiuvWcOdxc9zouCjzreV45OoIrkoQ@fCMJraCJCTa4lU@1bs2owW4mVPAulVNKhRVz9pKhs5e6PEvA9TUQTA0wm6BbFUm7w/w7GkAvFrCPN8DGpUrBpWBvV@EV0Lh0hh/TREvYxyrsHwym4igm91z2drMA9/uKwRvs9y7dfZP@fdzNFdyPZAZTBhP2IImf5MTxFlYF9l/1at03xE9U4s6IwiPj4wDCBAgMQxJN1ZY/zTfAyU/8DrZ3Vfcvxtq/SmxAhv9UxX9F/Dv4Oh7TmWB9VvLqdP7oGBa30scc@f3EKl/XgvWZytpMTQH5XEIWiBcu58Jl4fGdBkMKmPyUnX@h7AZW7jy85sZUPiHyrPGaV7dT/LGR91XRumps/HZOeR1symplbkusNSutxHK2XGSw7PwX1heL7Zj/Ag)
```
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T|T|T|T|T|T|T|T|T|T|T|T|T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T|T|T|T|T|T|T|T|T|T|T|T|T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T|T|T|T|T|T|P|T|T|T|T|T|T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T|T|T|T|T|T|T|T|T|T|T|T|T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T|T|T|T|T|T|T|T|T|T|T|T|T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T|T|T|T|T|T|T|T|T|T|T|T|T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
`LLLLLLUURDRURDRURDRURDDDLLLLLLLDDRURDRURDRURDRURUUUURDDDDDLRRUUUUURDDDDDRUUUUU`
[1x1](https://tio.run/##7Zbfb9owEMefx19xlTxI1KCS0l9aSNG6PuwBV6gKfUERshIDUUkcObQNq/q3MztNi0sDjJROe9jDQWTf13f@3DlOPI7nrXY8joFyzviA05jxaRCNtIZuzYd3kTcNWASeVkWhgVIDcbtuGmiS/fp2Q38MhhrirYYuZgjnZDZIKOHeWOsaKNQtFPaFM@KufWMJz70gGmRemiOndT@g1pBxSoSgj/hXlLYRr5vf5OpCyesoddvZ3@vQ/vPQfj4kNS2U1k05JoUuSRCzz1Gky8yic7tRrUph5O7ZePF4oz9Sb8yg07u87iPmWp6W7zASixqI6dZT5nB92ev0ke9aT/PKwQFckCTw4AdJaAWFJtjQr3ypdWtGDbYzoYIPqZxSKqyYs5MMnZ3sy7UEXE8DwdQAswm6VZG0O8y7pT70YgH7cA1sXGoruBTszSq8BBqXzvBzmmgB@1CFfcVgKo5icsdlbzcLcH9sM3iNve/S7Yv07@NuLuF@IDOYMgjZvSR@lBPHG1gV2H/Vq3XfED9SiTtjCg@MT3wIEiAwCkg0VVv@OC@Ak5/4LWznqu5fjLV71aIAx2oBLoh3C98nEzoTtE9KXp7OHx3E4mb6nEO/m1jl97WgfaLSNlNTYD6VmAVk4ZS5nAqXF4@f1B9RwOSX7P4zpR5YuffwiltT@YzI88YrXt9O8QdH3ltF66qx8ds55ZWwLquluQ2xVqy0FMvZcJnBovufWZ@9lGP@Gw)
```
+-+
|P|
+-+
```
ย *(no output)*
[Back Alley](https://tio.run/##7Zbfb9owEMefx19xlTxI1KCS0l9aSNG6PuwBT6gKfYkiZCWGRCVx5KQtrOrfzmwaisv4MVI67WEPB5F9X9/5c@c4aZhOW@00TIFyznif05TxPEqGWkO3poP7xM8jloCvVVFsoLGBuF03DTSa/QZ2Q3@KBhrirYYuZgjnZNLPKOF@qHUNFOsWil3hjLhn31rC8yBK@jMvzZHTehBRa8A4JULgIv4ZjduI180vcnWh5HU09tqzv9ehw5ehw2JIalpoXDflmBR6JEPMvkSJLjNLLu1GtSqFiXdg48Xjrf5E/ZBBp3d94yLmWb5W7DARixqI6dbzzOHmutdxUeBZz9PK0RFckSzy4RvJaAXFJtjgVj7VujWjBruZUMG7VE4pFVbM2UuGzl725VkCrq@BYGqA2QTdqkjaHebf0QB6qYB9vAE2LrUVXAr2dhVeAo1LZ/gxTbSAfazC/sEgF0cxu@eyt5srcL9vM3iD/d6luxfp38fdXML9SCaQM4jZgyR@UhDHW1itsP@qV@u@IX6iEndCCo@MjwKIMiAwjEiSqy1/WhTAKU78DrZ3Vfcvxtq/alGAU7UAV8S/g6@jEZ0I2mclL0/njw7i6mb6mEO/n1jl9yVoz1ifqazNsSkgn0vIAvHc5Vy4zD2@02BIAZOfsvcvlGpg5dbDa@5M5SOiyBqveXk7qz83is5ata4aG7@dU14Im7JamtsSa81KS7GcLVcZLHr/hfXFvBzTXw)
`DDDDDRUUUUURDDDDDRUUUUURDDDDDRUUUUURDDDDDRUUUUURRRRRLLLLLDDRRRRRLLLLLDDRRRRR`
[Hedge Maze](https://tio.run/##7Zbfb9owEMefx19xlTxI1KCS0l9aSNG6PuwBT6gKfUERshJDopI4cugKq/q3MztLG5cFGCmd9rCHg8i@r@/8uXOcJEiWnW4SJEA5Z3zEacL4LIwnWku3luP72JuFLAZPq6PIQHMDcbtpGmia/fp2S38MxxrinZYuZgjnZDFKKeFeoPUNFOkWiobCGXHXvrWE50EYjzIvzZHTuh9Sa8w4JUIwRPwjmncRb5qf5OpCyZto7nazv5ehw19Dh/mQ1HTQvGnKMSl0SYqYfYliXWYWX9qtel0KY/fAxsXjrf5IvYBBb3B9M0TMtTwt32EsFjUQ062nzOHmetAbIt@1npa1oyO4ImnowReS0hqKTLBhWPvQ6DeMBuxmQgVvUjmVVFgxZy8ZOnvZl2sJuJ4GgqkBZht0qyZp95h3R30YJAL28QbYuNJWcCXY21V4BTSunOH7NFEB@1iF/Y3BTBzF9J7L3m6X4H7bZvAG@71Ldy/Sv4@7vYL7gSxgxiBi3yXxk5w43sKqxP6rXqz/iviJStwJKDwwPvUhTIHAJCTxTG3507wATn7id7C9q/p/Mdb@VUUBTtUCXBHvDj5Pp3QhaJ9VvDydPzqI5c30Pod@P7Gq76ugfabSNuemwHwuMQvIhdO5cHr2@Ur9CQVMfsj@v1AqgpWbD6@5N5UPiTxzvOYF7pR/cuTdVbauGhu/nlNeCpuyWpnbEmvNSiuxnC3XGRT9X8tYXzwXZPkT) (an original creation)
```
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|P|M| |T|M| | | |M| |M|M|T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |M| |M| | |M|T|M|T| | | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T| | |M| |M| |T|M|M|M| |M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M| | | |M| |M|M| | | |M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T| | |M| |M| | | | |M| |M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
|M|M| |T| | |M|M|M|M|M| |T|
+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
`DDRRUURLDDDDLLRRDRRUULRUURURRDDLDDRRRURRUULLUDRRRUDLDDDDR`
[Answer]
# JavaScript (ES6), ~~187 183~~ 173 bytes
Takes input as a matrix of characters. Returns an array of signed integers: **-2** = down, **-1** = right, **1** = left and **2** = up.
```
ff=(m,X,Y,p=[])=>/T/.test(m)?(g=u=>m.some((r,y)=>r.some((c,x)=>(r[o=c=='M'|c>u|(h=X-x)*h+(v=Y-y)*v^c!='P'?0:f(m,x,y,1/X?[...p,h+2*v]:p,r[x]=3-~r[x]),x]=c,o)))?O:g(-~u))``:O=p
```
[Try it online!](https://tio.run/##7VZda9swFH3Pr7h7kpTIytLBHjyUsLK@1WsoHqQIbxWy8tHGlrFsz4bSv56pbUhbaGkanLDBXo6@0NG999x70ZWspFX5Iiu81MR6tZpynNAJvaAZFxHhw37YZ4W2BU7ICM94yYcJsybRGOe0cef5eqVo7VY4F4YrzlGAbtSwvMFzPvFq0p33cMUvvIZ0q5/qA0djNProT91LNW3ooD8ZCcZYRue9o24V@RnNRR3xT97t3UiomytqCCGjM3@GvduSkMtL/4xnqy@iI9CxtAsFSlqNKIgOgAD3AAUEuwJE9IEG2qYJ26EJnkO4P6fCvcWmEzkmgU6NutYxlNkW4gXt@Bm0I977aIIXdAtadOqwib0W77uBItfSlrm2r@rXuqvB2/B61bRefP@4fr9lA4WBxFRP2mewZZhfhi1z/j/NrjB@VPArzBYyLTZl@KhhuGlZu8DGzoPQjP8qaw5Gs9bwWKprkMulbtr5wITv7xNvJOuBu9YerWkxNmv1BvXgqWz3@1GHTU1@ItUcY2EpJBEBPgRlUmuWmi3NDFuWyfgkjfHgM4EeIB8EcqP7FBOWyAzHdxfQt/Nfpz@QiN3JUUTYlVmkGFF0fyNChKz@AA "JavaScript (Node.js) โ Try It Online")
(with the output translated back to **L**, **R**, **U**, **D**)
### How?
This AI:
* Is definitely more artificial than intelligent.
* Rushes like a mad man in the map (i.e. implements a depth-first search).
* Stops as soon as there are no more treasures, but otherwise does not care about the positions of the remaining treasures. This test is done with a regular expression.
```
/T/.test(m)
```
* Compares the [quadrance](https://en.wikipedia.org/wiki/Rational_trigonometry#Quadrance) between its current position \$(X,Y)\$ and a new position \$(x,y)\$ with \$1\$ to know whether it can move there. Or tests if the cell contains `"P"` if its position is not yet defined.
```
(h = X - x) * h + (v = Y - y) * v ^ c != 'P'
```
* Writes \$4N\$ on a cell that has been visited \$N\$ times and uses this threshold combined with an internal counter \$u\$ to decide -- in a sudden flash of lucidity -- whether it should backtrack over already visited cells when everything else failed.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 132 bytes
Saved 16 bytes by having the function ouput `1 0,0 1,ยฏ1 0,0 ยฏ1` instead of `U,L,D,R`. TIO link below decodes output back to letters.
I may write an explanation later, but most of the work is creating a graph in a format that the dfns [path function](https://dfns.dyalog.com/n_path.htm) likes, then using it to find successive shortest paths between the start and all treasures. Quite efficient, but because treasures are pathed left-to-right, top-to-bottom instead of being based on proximity, the answers are not optimal.
```
{zโร`/dโโดโตโgโzโดโโฌโs t mโ(โธโโโต=โข)ยจ'PTM'โfโ{(โตโm)โจ0=โบ:โฌโg[โบ],โโต}โhโ(f`โจ,f)โโฌโกtโฃ{2h`/โตโฃ2h`โฟโต}xโdโดโณz:โฌโโ,/โ,/2-/ยจ{โธx=โต}ยจยจ2(gโpath,)/s,t}
```
[Try it online!](https://tio.run/##tVJBSwJBFL77K@Y2CmubaxkEnupQ0KDodhJBYV09ZAltYC5eLGTbGiki8lpelgg6WBBdgu2fvD9ibzYLV5wliN5hdt6333zve2@m2tpLGsfVvYN6sta2avtGzZhM7A70Lz9uK6qBX@DPwF/g/LSOSUdkbg/4IwKHxCJNBOPAX8EZguMiMQvufcL3aF5nFDkm/rfjQsBxmwlwvOUs8Lf1L4F6CfdlJSjy0kWgIdTMCnBPMROYC9rZnQXuyNYaFVXIuCPcwcW7ONFGuhH4G3emkuCeKGqwaEnV92y01s4Kru/5nhavw0WvVbUaSkI9VKzuxAxqD2Bws53DU/5TGvpXmBULG7jqW9vFiZiBTXd3Ngu0JAzwMdqD/jXwB2w6KRJnuJQVXz7Wyt1YTMyE0DyZCRprijYpWQzqi0DGmC47rss10bdAc0dW68giqXUaM4hJMiSVxkk1Q@7YInm2yN0PGCo2ZbAgftdphFVNblUiz6aVZ2YmGeTf3aUl7ths0NBE/g/Mz7tbkbjTZ@NbKQLM/5oZDYbdrUY9wu8XPX8LoeYj70vKlGmG3WVk7uaJa1NiiqQE7xM "APL (Dyalog Extended) โ Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 233 bytes
```
G=input()
e=enumerate
P=T=M=E=frozenset()
for i,k in e(G):
for j,l in e(k):exec l+'|={(i,j)}'
G={0}
c=-1
while T-G|G&M|G-E-T:
G-=G;e=list(P)[0];x=c=c+1;r=()
while x:m=x%5%4;x/=5;r+=m,;e=~-m%2*~-m+e[0],m%2*(m-2)+e[1];G|={e}
print r
```
[Try it online!](https://tio.run/##JY4xb4MwEIV3/wov1Hax1YCSBetGyxMSA1uVoUIXxQkY5BCVNtC/To244U7fO713N/yM197n62rB@eE5ckEQ0D87DF8jkgpqKMHAJfS/6B@47S99oE7eqfMUuRUFoZtyk@2u3EWBEza0TdkML@7kTSyMWHgdFtKAysj31bVIa2Vn@1bOVhlVxwyrwGqE1j1GXonPw1lP0ECTZjpAPEp311R0MCWn5KinDzjpkEIno@tPdUn@HnuK0Sk34J3KRcTsrG38AxcyBOdHGtaVM1OXhknKKlPW2zRmZxOLiX8 "Python 2 โ Try It Online")
Very slow. Most of the test cases would probably time out.
`MPTLRUD` โ `EMPT1302`. Any other characters should be considered to be prefixes, separators or postfixes.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~766~~ 622 bytes
```
def f(s,W,H):
Z=enumerate;I=[("L",-1),("R",1),("D",1j),("U",-1j)];o="";P,M,T=map(lambda t:{x+y*1jfor y,l in Z(s)for x,c in Z(l)if c==t},'PMT');E=D={c:{t:0}for t,c in Z(T)}
while len(E):
E={}
for m,N in[(c+d,D[c])for c in D for _,d in I if not c+d in M]:
if 0<=m.real<W and 0<=m.imag<H:
T={t:N[t]+1for t in N if not m in D or not t in D[m]}
if any(T)or not m in D:
E[m]=T
for m in E:
if m in D:
D[m].update(E[m])
else:
D[m]=E[m]
for m in P:
if m in D:
for g in D[m]:
while D[m][g]:
for i,d in I:
if m+d in D and D[m+d][g]<D[m][g]:
o+=i;m=m+d;break
return o
```
[Try it online!](https://tio.run/##bVJfa9swEH/3pzj0UqnWQsLYSxy9OdDCHMLwKFTzimsrqTNbDrbCGkI@e6aT7KWB6uX8@3Onu5P3R/PW6q@XS6k2sKE9f@IPbB7As1D60KguNyp6FJKS74R/mTFOyQ/CXYxt3OHHT1R2LItaQUi05glPRZPvaZ03r2UOZn56D4/3s92m7eDIa6g0PNOeIXznhYc1qzZQCGHO/G6dpHcsWopYnIr5ycynZ7Sa0ZqycwB/36paQa00XWK3sBQnywIaG76yRkmLsOSxLDJ3kcuNnf7CSwSPYG/UrQHrQ5xkWAfJ6UI0k07l9eIJcl16XDX5dvHgLJAK29VKmiycuc4wfTWWa/xNlkfktFg22dllWk@uj3aEQfZmXxWW1ibScQpUlmNLH31YbXLYl/ZlKKYwZFXdq6sskA@uddYo3ZZBbTs25zP9ThHL7UA5WzUsbKBcIb@z2O3HZoQl5ixucwHaUFRRI6wcvdqF/gmgU@bQaWgvRvWmyHvVgwAZSLImGceQ@EN4ACT5FAy@NEntDU6CBFAZwHAG34huJO7jlUq9Ox2Oc9u4/gi8kgVZELhXHwbAPfwfxk6@7yptKPmlyWTXVppKMiH3s29ZOJpCSX47hrHRvaGjyPGXHoGcZuyGYIxd/gE "Python 3 โ Try It Online")
Fairly certain after this that I will never win code-golf, but contributing because I enjoyed the exercise.
This version works by building a dictionary of reachable locations, with each entry being a dictionary whose keys are a unique ID for the treasure, and whose value is the shortest distance to that treasure. The code supports multiple values for P: for each one it outputs a path that collects the treasures. No optimization is attempted.. it picks the nearest treasure from its current location until all treasures are collected.
] |
[Question]
[
There has not been a challenge regarding slope fields, as a far as I can tell. So, I might as well make one.
# The challenge
Given:
* A [black box function `f`](https://codegolf.meta.stackexchange.com/questions/1324/standard-definitions-of-terms-within-specifications/13706#13706) which takes two arguments, `x` and `y` (both real numbers) , and returns the value of the slope at point `(x,y)` (also a real number)
* A list of real numbers, `X`, representing the values along the `x` axis,
* Another list of real numbers, `Y`, representing the values along the `y` axis.
* A list of `(x,y)` pairs, `U`, which represents the inputs that `f` is undefined on. This argument can be removed if your language can detect errors.
Output:
* A rectangle with a length of the length `X`, and a height of the length of `Y`. At each combination of row `r` and column `c` in the rectangle, (starting from the bottom left corner), the character that is placed at that position will depend on the sign value of `f` evaluated at `x=c` and `y=r`:
+ If the value is positive, the character is `/`.
+ If the value is zero, the character is `-`.
+ If the value is negative, the character is `\`.
+ If `(x,y)` is not in the domain of `f` (a.k.a. a member of `U`), then the character is . `f` is guaranteed to not error on every combination of `x` within `X` and `y` within `Y` if `U` is utilized.
Since I am horrible at explaining things, here's an example:
Input:
```
f(x,y) = x / y
X=[-1,0,1]
Y=[-1,0,1]
U=[[-1,0],[0,0],[1,0]]
```
Output:
```
\-/
/-\
```
* At `(0,0)` (the bottom left corner), the corresponding `X` and `Y` values are `-1` and `-1` (since `X[0] = -1` and `Y[0] = -1`). `f(-1,-1)=(-1)/(-1)=1`, thus `/` is used.
* At `(1,0)` (the bottom row, middle column): `X[1] = 0, Y[0] = -1`, `f(0,-1)=(0)/(-1)=0`, and `0` is zero (duh), so the character is `-`.
* At `(1,1)` (the center): `X[1] = 0, Y[1] = 0`. `[0,0]` is a member of `U`. Therefore, it corresponds to the character. Or, if done without `U`: `0/0` is undefined, thus the character is .
* At `(2,2)` (the top left): `X[2] = 1, Y[2] = 1, f(1,1)=(1)/(1)=1`, which is positive. Therefore, it corresponds to the `/` character.
* Etc...
# Floating Point
Any value of `f` within the range `[-1e-9,1e-9]` should be considered to have a sign of `0`.
# Winning condition
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte count wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
แนโน,2โถv$แน $eโต$?ยฅรพแปโ/ \-โY
```
[Try it online!](https://tio.run/##y0rNyan8///hzlmPGnfqGD1q3Fam8nDnApXUR41bVewPLT287@Hu7kcNc/QVYnQfNcyN/P//f7SuoY6CgY6CYSwKE8KO1VGINoDSYH7sf/XD2/XVAQ "Jelly โ Try It Online")
Arguments: `Y`, `X`, `U`, `f`
`f` is a Python string containing Jelly code. **Be sure to quote it appropriately**, otherwise you may encounter errors.
Also, **`f` takes a pair `[x, y]` as its argument, not two arguments `x` and `y`**.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~36~~ 34 bytes
*2 bytes saved thanks to @ngn*
```
{oโโบโบโ'\-/ '[โโโบโ.{0::4โ2+รโบoโต}โต]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqfCDxqHcXCHW3qMfo6iuoRz/qmvaotxMk1DFDr9rAysoEKGekfXg6UCj/Ue/WWiCOrf3//9B6QwUDBUMFhWoDW6CQleHh7QZAlUBVh7eDlCmkKUCVcKnb2tqqc2kcWm@i/ah3s7mmgi5Y0hTEs8SUrUGSBQA) (with modified division, since basic APL 0รท0 is 1)
The black box function comes as left operand, `X` as left argument, and `Y` as right argument.
[Answer]
# [Haskell](https://www.haskell.org/), ~~114~~ ~~113~~ 109 bytes
```
z x=last$0:[x|abs x>1e-9]
(x#y)(%)u=reverse[[last$"\\-/"!!floor(1+signum(z$c%r)):[' '|elem(c,r)u]|c<-x]|r<-y]
```
[Try it online!](https://tio.run/##PcrPDoIgAIDxe0@B/yYsUTzmtCeoU0dkjRyVC9SBNnS8O20dvH377Xtz8xFSer8B20hu5phU1Dr@MMCeS4FP7ABttCKYoKXR4iu0EZT@x7BtcREGwVOOo4bl0fSvYVFwi7tEI1TRFKROSKFgl2m0MNfV2DKna7wyr3g/gAYoPl3vYFrm26wvA4gBpLgkeV4SFu2FYIEo7DOCXF/jnZn/AQ "Haskell โ Try It Online")
Fairly straightforward solution. Uses `signum` to index into a string for the right char if the point is defined.
EDIT: Thought of a way to shave off a byte
EDIT 2: Thanks @Laikoni for taking off another 4 bytes!
[Answer]
# [Swift](https://swift.org), 142 bytes
```
func f(X:[Float],Y:[Float]){print(Y.reversed().flatMap{y in X.flatMap{let s=try?b($0,y);return s==nil ?" ":s!>0 ?"/":s!<0 ?"\\":"-"}+["\n"]})}
```
Prints as an array of characters
[Answer]
# [Python 2](https://docs.python.org/2/), 91 bytes
```
f,X,Y,U=input()
for y in Y[::-1]:print''.join('/ \-'[[x,y]in U or~cmp(0,f(x,y))]for x in X)
```
[Try it online!](https://tio.run/##XYuxDsIgGIR3n@I2IP5tqSOJj9GkDTJUTSPGAiE1gcVXx1adnO67y30hLzfvDqVM1NNA3dG68Fy42E0@IsM6DFqpqjUqROsWxuq7t46zBqeKaZ0om/XTwcfXZQ5c0sTXTQiz@Wnze1GKfozz@ToiEbICT9hD1lKgQSboqiVIQmv@@Fs2kr/8dGPe "Python 2 โ Try It Online")
-3 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
Looks like I [can't](https://codegolf.meta.stackexchange.com/a/13708/41024) just [assume `f` to be already assigned to a function](https://codegolf.meta.stackexchange.com/a/13707/41024).
[Answer]
# [Python 2](https://docs.python.org/2/), ~~105~~ ~~103~~ ~~95~~ 92 bytes
```
def f(F,X,Y,U):
for y in Y[::-1]:print''.join('/ \-'[[x,y]in U or~cmp(0,F(x,y))]for x in X)
```
[Try it online!](https://tio.run/##ZUs9DsIgGN09xbcB5qMFRg7QGzRpgwzVSqyx0DQdYPHqCDq6vP@3peMRvMp5vjtwtMMBR@yZPoELOyRYPIxGay6t3vbFH4Q0z7B4Slq4cGJMxGTLpoewv2/rRgV2tGSM2fqP9T@w7OhrWq/zBKXSsjnHNiEYrpBLFChR2X9bvbBoalZIfPGna2FZ/gA "Python 2 โ Try It Online")
---
Error handling version:
# [Python 2](https://docs.python.org/2/), ~~135~~ ~~132~~ 125 bytes
```
def f(F,X,Y):
def g(x,y):
try:return'-\/'[cmp(0,F(x,y))]
except:return' '
for y in Y[::-1]:print''.join(g(x,y)for x in X)
```
[Try it online!](https://tio.run/##fYwxDoMgGEZnOcW/AS1qtRsH8Awa62AVLE1FQmgCp6dq08Gl48v33meCeyy6jHEUEiSpWM0ayhFsOBHPwgqJs4Fb4d5W4/SW43aYDbmwap9phxLhB2HcTwGMQC4WAigNTct5WnTcWKUdxtlzUZp8jzfHb05NoySvfr6PPawDL7KTzwMD2@tJkLRkV3oAivY3dIj8@V8RPw "Python 2 โ Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~70~~ 68 bytes
```
Table["-"["/","\\"][[Sign[x~#~y]]]~Check~" ",{y,Reverse@#3},{x,#2}]&
```
[Try it online!](https://tio.run/##NYlNC4IwGIDv/YrxLjy9w1zHIISgjkZ6mzuYjRzlBzpDGfOvryK6PR91YSpVF0aXhU@VSTqj22YQ62Q03WiQHNv@c7O5U4Ttya9@m9ytzr1ujDj1@kZinxXXpxLAQEAICHkOUohU3xsxLXSZpZTLoVLlYwECaGe8qJfqBxXTrUM7IeVOBp7EMbE0CikPkFjGkUW4wQi5@@qfnfRv "Wolfram Language (Mathematica) โ Try It Online")
In the expression `"-"["/","\\"]`, part 0 is the head (`"-"`), part 1 is `"/"`, and part -1 (the last part) is `"\\"`, so if we try to take the `Sign[f]`-th part of it, we get the appropriate character depending on if `f` is positive, negative, or zero. If none of the above apply, or if evaluating the function causes an error, the `~Check~` will catch the error and return the `" "` character instead.
(It still prints out a bunch of error messages, which should be ignored since we get the right answer at the end.)
We do this for all `x` and `y` values.
] |
[Question]
[
You are to write a program that takes a list of strings as input. For every string in the list you are to determine the smallest **N** such that no other string in the list begins with the same **N** characters as the string in question. Now compose a new list with all these strings. Here is an example, on the left we have the input and on the right we have the output
```
aba aba
aababba aa
abbaaabbb -> abba
bbbbbbabababaaab b
abbbabbaa abbb
```
If a there is a string that is also the beginning of another string you should append a `$` to the end to represent the end of the string. Here is an example where that is the case
```
ababababbabab abababa
ababbbaabababa ababbb
ababb ababb$
bababba -> bababb
bbbabababab bb
bababababbabab bababa
abababbababa abababb
```
## Rules
* Input will only contain alphabetic characters.
* You will not receive a list with the same entry twice.
* You take input in any ordered container.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), you should aim to minimize the byte size of your program.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~14~~ ~~13~~ 12 bytes
```
แน zoโโฒโกแนชโ TT'$
```
[Try it online!](https://tio.run/##yygtzv7//@HOBVX5j9omPpq26VHDwoc7Vz3qXBASoq7y////aKXEJAgEE0o6YD6QAxWGCQBpqCoQKykJpgsmjm4ClJeoFAsA "Husk โ Try It Online")
Less than half the length of the previous best solution!
### Explanation
```
แน zoโโฒโกแนชโ TT'$
TT'$ Pad all strings to equal length by appending dollar signs
โกแนชโ Create a 2D matrix with all pairwise differences between
strings. โ returns the smallest index at wich two lists differ
(or 0, if they are equal)
แน zoโโฒ For each string, take as many characters as the maximum number
in its row of the table.
```
Since my explanation may not be that clear, here's a small worked example:
Starting list: `["abc","abd","b","bcd"]`
Table of differences:
```
abc abd b bcd max
abc 0 3 1 1 3
abd 3 0 1 1 3
b 1 1 0 2 2
bcd 1 1 2 0 2
```
So we take from each string (with added trailing '$') as many characters as stated in the "max" column.
Final result: `["abc","abd","b$","bc"]`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~28 26~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-10 bytes by implementing the algorithm found by Leo in their [brilliant Husk answer](https://codegolf.stackexchange.com/a/131869/53748).
```
iโฌ0แนแธฃ@
;โฌโ$ยต=รพรง"
```
or...
```
;โฌโ$ยต=i0ยตรพโธแนโฌโธแธฃ"
```
A monadic link taking and returning lists of lists of characters.
**[Try it online!](https://tio.run/##y0rNyan8/z/zUdMag4c7Gx7uWOzAZQ3kPGqYq3Joq@3hfYeXK/0/3B75/3@0UmISBIIJJR0wH8iBCsMEgDRUFYiVlATTBRNHNwHKS1SKBQA "Jelly โ Try It Online")** (the footer makes a full program which prints the result split by newlines.)
### How?
```
iโฌ0แนแธฃ@ - helper link, create an entry of the output: equality row, string with trailing '$'
iโฌ0 - first index of zero in โฌach entry of the row
แน - maximum
แธฃ@ - head to index with swapped @rguments (the prefix of the string)
;โฌโ$ยต=รพรง" - link: list of lists of characters (list of "strings")
โ$ - literal '$'
;โฌ - concatenate for โฌach
ยต - monadic chain separation (call that x)
รพ - table of (with x on the left and, implicitly, on the right):
= - equals? (vectorises)
" - zip with (with the table on the left and, implicitly, x on the right)
รง - call the last link as a dyad
```
---
My original:
-2 bytes thanks to Erik the Outgolfer (replace `แธฃJ$` with `;\` and `แบฤรโฌรโฌ$` with `ฤ@โฌโฌแบ$`)
```
NMแธขโนแธฃ;โธแนแบ@โ$ยคแน
;\โฌฤ@โฌโฌแบ$รง"
```
A monadic link taking and returning lists of lists of characters.
**[Try it online!](https://tio.run/##y0rNyan8/9/P9@GORY8adz7csdj6UeOOhzubHu7qdnjUMFfl0JKHO6dxAcW9VB41rTkCFGxaA0QPd/WpHF6u9P9we@T//9FKiUkQCCaUdMB8IAcqDBMA0lBVIFZSEkwXTBzdBCgvUSkWAA "Jelly โ Try It Online")** (the footer makes a full program which prints the result split by newlines.)
I'm ~~almost~~ certain this is beatable, and ~~probably~~ by a decent margin! (although I have attempted to golf the method.)
The same byte count may be achieved without a helper link too, with:
```
แธฃJ$โฌแบฤรโฌรโฌ$รฐNMแธขโนแธฃ;โธแนแบ@โ$ยคแนรฐ"
```
### How?
Note: the reusable link is the second line of code, so start there.
```
NMแธขโนแธฃ;โธแนแบ@โ$ยคแน - helper link, create an entry of the output: prefix counts, string
- ("prefix counts" should be counts of the prefixes of the "string" in
the totality of prefixes of *all* the strings)
N - negate the counts
M - maximal indexes (lengths of prefixes appearing least often, ascending)
แธข - head (finds the minimal length required), call that ml
โน - chain's right argument (prefixes)
แธฃ - head (string) to index ml (gets the minimal length prefix)
ยค - nilad followed by links as a nilad:
โธ - chain's left argument (prefix counts)
แน - minimum (this will either be 1 or 2)
โ$ - literal '$'
แบ@ - repeat with swapped @rguments (either "$" or "$$")
; - concatenate
แน - pop (remove the last "$" - leaving one where the prefix occurs in another
- string's prefixes, and none otherwise)
;\โฌฤ@โฌโฌแบ$รง" - link: list of lists of characters (list of "strings")
โฌ - for โฌach string
\ - cumulative reduce with:
; - concatenation
- (gets a list of lists of prefixes)
$ - last two links as a monad:
แบ - tighten (flatten by one to make a single list of all prefixes)
@ - swap arguments
โฌโฌ - for each prefix in each list of prefixes
ฤ - count occurrences in the tightened list (>=1 since it counts itself)
" - zip with the dyad (right argument is this link's argument):
รง - last link (helper) as a dyad
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~83~~ 79 bytes
```
f l|let h=map(++"$")l;w x|y<-init x,2>sum[1|z<-h,y<=z,y++"{">z]=w y|1<3=x=w<$>h
```
[Try it online!](https://tio.run/##HYpLCsMgFACv8hAXLTGLtMv6vEjIwqQJSlVCY/BT726kmxkYRsnjsxpT6wammNWDQiv3W9cRSu7mFSCWxHvttIfIHuI47TiUzHvFEsfMUht/ROQJA6Qy8CdGDJwKVa3UDhD2r3YeKGwwEjkvb8Ka1J8Ns2xlqhc "Haskell โ Try It Online") Example usage: `f ["abcd","abh","ab","bacd"]` yields `["abc","abh","ab$","b"]`.
Given a list of strings, the function `f` appends a trailing `$` and applies `w` to each string, where `w` iteratively drops the last character of the string (with `init`) until the next application of `init` would lead to the string now longer being a unique prefix.
**Edit:** Three bytes off thanks to รrjan Johansen's shorter prefix test!
[Answer]
# [Haskell](https://www.haskell.org/), ~~109~~ ~~104~~ ~~98~~ ~~97~~ ~~90~~ ~~84~~ 83 bytes
Probably not very good but Hopefully this will kick things off a bit.
```
f s=[[x|x<-map(`take`(a++"$"))[0..],[1]==[1|d<-s,and$zipWith(==)x$d++"$"]]!!0|a<-s]
```
[Try it online!](https://tio.run/##HYrBCoQgFAB/ZRMPShZ1733HHkToqUVSiaweZPHf3dzLwAxzYDy366p1f0WQMpe8DDcGtiY8t5Vh3xNKOJfTOCohZwUg52KXIQr0ln5deLt0MACeqf2/SnXdVPA5VL3ReQgf5xPdJUFtiCDa2IdorG7SgC2p@gM "Haskell โ Try It Online")
[Answer]
## JavaScript (ES6), ~~89~~ 86 bytes
```
a=>a.map(g=(s,i,a,t=s+'$')=>a.some((t,j)=>j-i&&!t.search(s))?t:g(s.slice(0,-1),i,a,s))
```
Edit: Saved 3 bytes thanks to @CraigAyre. (Supporting arbitrary characters would still have saved two bytes using `!t.indexOf(s)`.)
[Answer]
# Mathematica, 141 ~~142~~ bytes
```
g[x_:0,___]:=x;f=#<>""&/@(Thread@h[x=#~PadRight~99&/@(Characters[#<>"$"]&/@#),Max/@Outer[g@@Join@@Position[#-#2,y_/;y!=0]&,x,x,1]]/.h->Take)&
```
I think I can golf it a bit.
The code doesn't work on Mathics so you may use [Wolfram Sandbox](http://sandbox.open.wolframcloud.com) to test.
[Answer]
# PHP, ~~155 129~~ 102 bytes
```
for(;++$k<$argc;$t=!print"$t
")for($i=0;count(preg_grep("_^".($t.=$argv[$k][$i++]?:"$")._,$argv))>1;);
```
expects input to not contain regex special chars and that no argument is `-`.
Run with `php -nr <word> <word> ...` or [try it online](http://sandbox.onlinephpfunctions.com/code/ea18e3bbfcfeff92db61665a5ddc8082e8633128).
**breakdown**
```
for(;++$k<$argc; # loop through arguments
$t=!print"$t\n") # 2. print $t, reset $t
for($i=0; # 1. loop through string:
1<count(preg_grep("_^".( # 2. continue while more than one argument begins with $t
$t.=$argv[$k][$i++]?:"$" # 1. append current character or "$" to $t
)._,$argv)););
```
] |
[Question]
[
## Challenge
Given a list of keys and values, and a target `n`, return all sets of keys where the sum of their values equals or exceeds `n`.
## Input
Input will be like this:
```
[["Part 1", 20], ["Part 2", 15], ["Part 3", 14.75], ["Part 4", 3]], 30
```
Input consists of a list with keys (which can be any kind of string) and values (which can be any kind of decimal). Also, a number `n` is supplied as the target.
You may take these inputs in any format you like, in any order etc. It needs to support strings, numbers (with decimal precision and possibly negative).
The target might be positive, negative or zero. The list will always contain at least 1 KV-pair.
Each key is guaranteed to be unique. Each value <> 0. Different keys can have the same value. It is not guaranteed that a list holds a satisfactory combination.
## Output
The expected output is a list of lists with all keys that have a combined value `>=n`. Each set that manages to satisfy this condition needs to be shown in a clearly distinguishable group, for example by separating them with brackets or newlines.
Sample output for the above input:
```
Part 1, Part2
Part 1, Part 3
Part 1, Part2, Part 3
Part 1, Part2, Part 4
Part 1, Part3, Part 4
Part 1, Part2, Part 3, Part 4
Part2, Part 3, Part 4
```
Note that each combination needs to be unique. The output doesn't need to be sorted, but `part 1, part 2` is considered a duplicate of `part 2, part 1` and should not be shown twice.
## Additional rules
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden
* Answer must be a full program or a function, not a snippet or a REPL-entry.
* [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
รฆสรธ`Oยฒโน_i,
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8LJTkw7vSPA/tOlRw874TJ3//6OjlQISi0oUDJV0FIwMYnUUoHwjIN/QFME3BvFN9MyRhEyAQsaxsVzGBgA "05AB1E โ Try It Online")
**Explanation**
```
รฆ # compute powerset of input
ส # filter out falsy values (we don't actually filter, it just saves a byte)
รธ # zip into a list of keys and a list of values
` # push separately to the stack
O # sum values
ยฒโน_i # if not less than input_2
, # print list of keys
```
[Answer]
# Mathematica, ~~45~~ 43 bytes
*Saved 2 bytes due to [alephalpha](/users/9288).*
```
Keys/@Cases[Subsets@#,a_/;Tr@Values@a>=#2]&
```
Anonymous function. Takes a list of rules (e.g., `{"Part 1"->20,"Part 2"->15}`) and a number as input and returns a list of lists of strings as output.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~15~~ ~~14~~ 12 bytes
*Saved 2 bytes thanks to @obarakon*
```
ร f_xร
ยจVรmยฎg
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=4CBmX3hnMSCoVsNtrmc=&input=W1siUGFydCAxIiwgMjBdLCBbIlBhcnQgMiIsIDE1XSwgWyJQYXJ0IDMiLCAxNC43NV0sIFsiUGFydCA0IiwgM11dLCAzMAotUg==) Output is a nested array, but it's rather hard to tell so the `-R` flag has been added to put each item on its own line.
### Explanation
```
ร f_ xร
ยจ Vร mยฎ g
Uร fZ{Zxs1 >=V} mmZ{Zg}
// Implicit: U = input array, V = input number
Uร // Take all combinations of U.
fZ{ } // Filter to only the combinations Z where this is true:
Zxs1 // The sum of each [item of Z]'s item at index 1
>=V // is greater than or equal to V.
m // Map each combination in the result by
mZ{ } // mapping each array Z in that to
Zg // the first item in Z.
// This replaces each key-value pair with its key.
// Implicit: output result of last expression
```
An interesting thing to note is the use of `ร
` (or `s1` ) instead of `g1` . `s1` on an array simply returns everything but the first item. Since each array only has two items (a key and a value), this returns an array containing the value. `x` then uses JS's native coercion to convert this into a number, and on an array containing one number, this happens to return that number.
[Answer]
## JavaScript (ES6), ~~127~~ 123 bytes
Takes the list `l` and the target `n` in currying syntax `(l)(n)`. Returns an array of arrays.
```
l=>n=>l.reduceRight((p,c)=>[...p,...p.map(x=>[c,...x])],[[]]).filter(x=>x.map(x=>s+=x[1],s=0)&&s>=n).map(x=>x.map(x=>x[0]))
```
### Demo
```
let f =
l=>n=>l.reduceRight((p,c)=>[...p,...p.map(x=>[c,...x])],[[]]).filter(x=>x.map(x=>s+=x[1],s=0)&&s>=n).map(x=>x.map(x=>x[0]))
console.log(
f([["Part 1", 20], ["Part 2", 15], ["Part 3", 14.75], ["Part 4", 3]])(30)
)
```
[Answer]
## Haskell, 60 bytes
```
n#l=[map fst=<<e|e<-mapM(\p->[[],[p]])l,sum(map snd=<<e)>=n]
```
Usage example: `3 # [("Part 1",1), ("Part 2",1.5),("Part 3",2)]` -> `[["Part 2","Part 3"],["Part 1","Part 3"],["Part 1","Part 2","Part 3"]]`.
[Try it online!](https://tio.run/##TcqxCsMgFEDRX3kkGRRMSWJKFs0fFLq/Ogi1NFRFot3y71ah0I7ncp86voy1OfvWSnQ6wCMmKYQ5jOgLL@QW@hVRMQxKUcvi25G6RX@vG12lV9npzYOEsG8@QQd8gBaQNFe9JxgbBtNAGXw9FY/nn3n1fFr@0lwSpyp/AA "Haskell โ Try It Online")
How it works:
```
mapM(\p->[[],[p]])l -- turn every element p from the input list l
-- into a list [[],[p]], i.e. [<empty list>, <singleton list p>]
-- and make a list of all combinations there by
-- picking either [] or [p]
-- e.g. [1,2] -> [[[],[]], [[],[2]], [[1],[]], [[1],[2]]]
e<- -- keep all elements e from this list where
sum(map snd=<<e)>=n -- the second elements of the pairs are >= n
[map fst=<<e | ] -- and extract the first elements of the pairs from it
```
[Answer]
# [R](https://www.r-project.org/), 97 bytes
```
function(l,v){z=c()
k=combn
for(i in 1:length(l))z=c(z,lapply(k(l,i,,F)[k(l,i,sum)>=v],names))
z}
```
This is an anonymous function which takes the input in as a named list of values `l` (where the names are the parts) and a value `v`, and returns a list of vectors of names. Returns a list with value `NULL` if no matches are found.
The function `combn(x,m)`generates all elements of `x` taken `m` at a time with some options to simplify and aggregate. Hence the code iteratively generates the subsets of size `i`, `k(l,i,,F)`, subsets those whose sum `k(l,i,sum)` is at least `v`, and then applies the `names` function to to each of those to extract the part names.
A different input scheme might lead to golfier code.
[Try it online!](https://tio.run/##Lcu9DsIgFEDhnadg497kLlQnExyd3RsHJEVJ@WkobSLGZ8eaun3DOblZ1ewSTXEpgqcV31UZQDYqk8I9MpsyOO4ilyc/xEd5gkf8JZW8nib/gnHbHNEF@13zEvCs1htFHYYZkdVPs2BAXHUuXAolaWcnVPfnYSPSEdsX "R โ Try It Online")
[Answer]
# PHP, 134 bytes
```
function f($a,$n){$r=$n>0?[]:[[]];if([$k,$v]=each($a)){unset($a[$k]);$r=f($a,$n);foreach(f($a,$n-$v)as$t){$t[]=$k;$r[]=$t;}}return$r;}
```
[Test it online](https://repl.it/I2sD/0).
] |
[Question]
[
This question is the inverse of [this one](https://codegolf.stackexchange.com/questions/48117/convert-a-string-to-its-r%C3%B6varspr%C3%A5ket-equivalent) by [James Williams](https://codegolf.stackexchange.com/users/25274/james-williams).
---
## Rรถvarsprรฅket
[Rรถvarsprรฅket](http://en.wikipedia.org/wiki/R%C3%B6varspr%C3%A5ket) is a word game played by Swedish children, from the books about Kalle Blomkvist by Astrid Lindgren.
The basic rules used during encoding are as follows (from Wikipedia):
* Every consonant (spelling matters, not pronunciation) was doubled, and
an o was inserted in-between.
* Vowels were left intact.
A few examples of decoding:
* "hohelollolo" -> "hello"
* "MoMinon sosvovรคvovarore รคror fofulollol momedod รฅlol" -> "Min svรคvare รคr full med รฅl"
Swedish consonants are the same as the English ones, so the program should work with both Swedish and English entries.
The letter "y" is taken as a consonant in this case - as most of the time it is.
---
## Your Task:
Write a program to convert a Rรถvarsprรฅket string of Swedish letters, inputted through a function or through stdin, into its decoded equivalent. Shortest answer in bytes wins!
[Answer]
# [Retina](https://github.com/mbuettner/retina), 19 + 2 = 21 bytes
Retina strikes again! The code for this program consists of two files:
```
i`([b-z-[eiou]])o.
```
```
$1
```
This reads the input on STDIN and prints the output to STDOUT.
If you call the files `pattern.rgx` and `replacement.rpl`, you can run the program simply like
```
echo "hohelollolo" | ./Retina pattern.rgx replacement.rpl
```
## Explanation
[As for the previous answer](https://codegolf.stackexchange.com/a/48120/8478), if Retina is invoked with 2 files it is automatically assumed to operate in "Replace mode", where the first file is the regex and the second file is the pattern.
Retina can be configured (which includes `RegexOptions` and other options) by prepending the regex with ``` and a configuration string. In this case I'm only giving it `i` which is the normal regex modifier for case insensitivity.
The pattern itself is a bit more interesting this time. It still uses .NET's character class subtraction to match any consonant in the ASCII range, but then it also matches the following `o` as well as the character after it (i.e. the copy of the consonant). The replacement then just writes the captured consonant back.
You might be wondering why this is not ambiguous in a case like `lololol -> lol`. The trick is that matches cannot overlap and are always found from left-to-right. So whenever I encounter a consonant, I include the next two character in the match and replace all of them - the search continues after this. It's quite easy to convince yourself that this kind of greedy algorithm will always decode the input correctly. In fact the pattern could even have been
```
i`([b-z-[eiou]])..
```
[Answer]
# Julia, ~~61~~ 43 bytes
```
t->replace(t,r"(?![eiou])[b-z]o."i,s->s[1])
```
This creates an anonymous function which accepts a string as input and returns the inverse Rรถvarsprรฅket transformation of the string. It's the exact inverse of [my Julia answer](https://codegolf.stackexchange.com/a/48135/20469) to the Rรถvarsprรฅket challenge. To call it, give it a name, e.g. `f=t->...`.
The `replace()` function is doing all of the work here. The first argument is the input string, the second is a regular expression pattern (which in Julia is given as a string preceded by `r`), and the third is the replacement.
For the regex, we're matching all pairs of consonants separated by an "o". For the replacement, we're taking the match and extracting only the first character, which is the consonant.
Examples:
```
julia> f("hohelollolo")
"hello"
julia> f("MoMinon sosvovรคvovarore รคror fofulollol momedod รฅlol")
"Min svรคvare รคr full med รฅl"
```
Questions? Just let me know. Suggestions? Very welcome as always!
---
**Edit:** Saved 18 bytes thanks to Martin Bรผttner!
[Answer]
## Sed, 13, 15, 16, 28
```
s/\([^รครถรฅaeiou]\)o\1/\1/g
```
Run it like this:
```
echo MoMinon sosvovรคvovarore รคror fofulollol momedod รฅlol | sed 's/\([^รครถรฅaeiou]\)o\1/\1/g'
```
Output:
```
Min svรคvare รคr full med รฅl
```
[Answer]
# Java, 47
Use as a lambda function. Works the exact same way as [Martin's answer](https://codegolf.stackexchange.com/a/48142/32700).
```
a->a.replaceAll("(?i)([b-z&&[^eiou]])o.","$1");
```
[Try here](http://ideone.com/ROAFLy)
[Answer]
# Pyth, 27
```
VzJ:zZhZpkJ~Zhy}rJ0-G"aeoui
```
[Answer]
# JavaScript (ES6), 46
This turns out to be some language-specific sintax around a regexp.
ES6 is quite short. Too bad we miss [subtraction](http://www.regular-expressions.info/charclasssubtract.html)
```
F=s=>s.replace(/([b-df-hj-np-tv-z])../gi,'$1')
```
[Answer]
# Mathematica, 36 bytes
Roughly uses the strategy in [my previous answer](https://codegolf.stackexchange.com/a/48136/33208).
```
StringReplace[#,a_~~"o"|"O"~~a_:>a]&
```
Explanation:
* `"o"|"O"` matches the lettter O insensitively.
* `a_~~*..*~~a_:>a` matches any character `a` followed by an O followed by `a` again, and replaces it with `a`.
* Finally, `StringReplace[#,*..*]&` creates a pure function applying that rule to every matching sequence in its argument.
[Answer]
# Python, 61
The inverse is conveniently is the same length as the [original](https://codegolf.stackexchange.com/a/48137/34718).
```
import re;g=lambda s:re.sub('(?i)(?![eiou])([b-z])o.',r'\1',s)
```
Or alternatively:
```
import re;g=lambda s:re.sub('(?i)(?![eiou])([b-z])o.','\\1',s)
```
Run it here: <http://repl.it/f3N>
[Answer]
# JavaScript ES6, 108 bytes
```
F=s=>{
for(n='',i=0;i<s.length;n+=c)c=s[i],i+=~'bcdfghjklmnpqrstvwxyz'.indexOf(c.toLowerCase())?3:1
return n
}
```
To make this interesting, I tried to do this entirely without regular expressions, which is why it is so long. It works by iterating over the string, copying each letter over to a new string. If it encounters a consonant, it skips the next two letters, which would be o + that letter. Use the snippet for a GUI alert and ES5.
```
F=function(s){for(n='',i=0;i<s.length;n+=c)c=s[i],i+=~'bcdfghjklmnpqrstvwxyz'.indexOf(c.toLowerCase())?3:1
return n}
alert(F('hohelollolo')+'\n'+F('MoMinon sosvovรคvovarore รคror fofulollol momedod รฅlol'))
```
[Answer]
# JavaScript 65
```
function R(x){return x.replace(/([bcdfghj-np-tv-z])o\1/gi, "$1")}
```
[Answer]
# PHP - 65 66
```
$s=$argv[1];echo preg_replace("/([^aeiou])o([^aeiou])/i","$1",$s);
```
[Answer]
# [QuadR](https://github.com/abrudz/QuadRS), 15 bytes
```
([^aeiou])o.
\1
```
[Try it online!](https://tio.run/##KyxNTCn6/18jOi4xNTO/NFYzX48rxvD//4z8jNSc/BwgyufyzffNzMvPUyjOLy7LLzu8BEgkFuUXpSocXgKkFNLy00ohShVy83NTU/JTFA4vBfK4PPI9XH3yfYDI/78hAA "QuadR โ Try It Online")
PCRE Replaceโฆ
`([^aeiou])o.`โnon-vowel (and call this the first capturing group), "o", any character
โwithโฆ
`\1`โthe first capturing group
] |
[Question]
[
*This code-challenge is related to the code-golf question [Analyzing Collatz-like sequences](https://codegolf.stackexchange.com/questions/47221/analyzing-collatz-like-sequences) but the goal is quite different here.*
*If you are familiar with Collatz-like sequences you can skip to the section "The task".*
We define a [Collatz](http://en.wikipedia.org/wiki/Collatz_conjecture)-like rule with 3 positive integers:
* `d > 1` divisor
* `m > 1` multiplier
* `i > 0` increment
(In the original Collatz sequence `d = 2`, `m = 3` and `i = 1`.)
For a Collatz-like rule and a positive integer `n` starting value we define a sequence `s` in the following manner:
* `s(0) = n`
* if `k > 0` and `s(k-1) mod d = 0` then `s(k) = s(k-1) / d`
* if `k > 0` and `s(k-1) mod d != 0` then `s(k) = s(k-1) * m + i`
An example sequence with `d = 2, m = 3, i = 5` and `n = 80` will be `s = 80, 40, 20, 10, 5, 20, 10, 5, 20, ...`.
Every sequence will either reach higher values than any given bound (i.e. the sequence is divergent) or get into an infinite loop (for some `t` and `u` (`t!=u`) the `s(t) = s(u)` equality will be true).
Two loops are said to be different if they don't have any common elements.
## The task
You should write a program which finds a Collatz-like rule with many different loops. Your score will be the number of found loops. (You don't have to find all of the possible loops and higher score is better.)
The program could be specialized in any manner to produce the best score.
For proof the program should output the values of `d`, `m`, `i` and the smallest values from every found loop.
## Example
```
For d=3 m=7 i=8 the loops are
LOOP 15 5 43 309 103 729 243 81 27 9 3 1
LOOP 22 162 54 18 6 2
LOOP 36 12 4
So a valid proof with a score of 3 could be
d=3 m=7 i=8 min_values=[1 4 2]
```
You can validate your result with [this Python3 code](http://ideone.com/Mpgig4). The program expects a list of space-separated integers `d m i min_value_1 min_value_2 ...` as input.
[Answer]
## GolfScript, arbitrary score
```
~:l 2:m.@?):d\1 l,{m\)?d-*}/abs.{1 m 3$)?-*m@)?d-m(*/}+l,/]' '*
```
This takes an integer on stdin and outputs a sequence with that many loops, in the input format of the Python tester. The [online demo](http://golfscript.apphb.com/?c=Oyc0JwoKfjpsIDI6bS5APyk6ZFwxIGwse21cKT9kLSp9L2Ficy57MSBtIDMkKT8tKm1AKT9kLW0oKi99K2wsL10nICcq) runs it for `l = 4` and produces output `17 2 1755 117 405 1365 26325`; [this fork of the tester](http://ideone.com/IAuDK9) verifies it.
### Explanation
In order to keep it simple, I restricted the analysis to *primitive loops*: ones with only one division.
```
(x -> mx + i)^n = (x -> m^n x + (m^n - 1)/(m-1) i)
```
so this means that I'm looking for solutions to
```
m^n x + (m^n - 1)/(m - 1)i = dx
```
or
```
(m^n - d) x + (m^n - 1)/(m - 1)i = 0
```
When `n > 0, m > 1, m^n - d != 0` this has exactly one solution for `x`. `m - 1 > 0` and `m^n - 1 > 0`, so in order for the solution to be positive we require `m^n - d < 0`, and in order for the solution to be an integer we require `d - m^n` to be a factor of `(m^n - 1)/(m - 1)i`.
The rest may already be obvious. We pick the desired score, `l`. We're going to find primitive loops of length `1` to `l`, so we want `d - m^l > 0`. To get a smallish output we pick `m = 2, d = 2^l + 1`. Then to get an easy guarantee of the divisibility constraints we pick `i` to be the absolute value of `(m - d)(m^2 - d)...(m^l - d)`.
[Answer]
# Python 3, (d = 2, m = 3, i = 96521425) โ Score = 2369
The program below writes the output to `collatz.txt`, and also prints summaries to the shell.
I used the observation that, if `(d, m, i)` had a lot of loops, then in general `(d, m, i*k)` also tended to have a lot of loops for different values of `k`. I started with `(2, 3, 13)`, and eventually worked `i` up like so:
```
13 -> 65 -> 1235 -> 35815 -> 250705 -> 2757755 -> 13788775 -> 96521425
```
before ending up with the lengthy output that can be found [here](http://pastebin.com/65ZPk70E).
The respective scores of the above chain are (using a bound of `10000`):
```
10 -> 16 -> 28 -> 146 -> 304 -> 535 -> 766 -> 1094
```
2369 was obtained by bumping the bound up to `100000`.
This raises a question similar to the one that @orlp has brought up โ if I keep doing this multiplication process, will I always be able to get more and more loops? If anyone can prove that, then they'd probably win :)
```
from collections import defaultdict
import itertools
def f(d, m, i, bound=1000):
D = defaultdict(set)
S = set()
for j in range(1, bound):
A = [j]
B = {j}
for _ in range(bound):
if j > bound**3:
break
if j % d == 0:
j //= d
else:
j = j*m + i
if j in B:
S.add(min(A[A.index(j):]))
break
A.append(j)
B.add(j)
return S
N = 1000
THRESHOLD = 0
BOUND = 10000
MULTIPLIER = 96521425
with open("collatz.txt", "w") as outfile:
for d, m, i in itertools.product([2], [3], range(1, N)):
result = f(d, m, MULTIPLIER*i, bound=BOUND)
if len(result) > THRESHOLD:
print(d, m, MULTIPLIER*i, " ".join(map(str, sorted(result))), file=outfile, flush=True)
print(d, m, MULTIPLIER*i, len(result))
```
---
*(Proof in progress for a possibly different arbitrary score method)*
Pick `d`, `m`, `i` such that `d` and `i` are coprime and suppose we have a loop for `(d, m, i)`:
```
a_0 -> a_1 -> a_2 -> ... -> a_(n-1) -> a_n = a_0
```
Now pick `k` coprime to `i` and `d`, and we want to look at `(d, m, i*k)`. Consider the number `k*a` for some `a`.
* If `d` divides `a` then `d` divides `k*a`, and in this case we map `k*a -> k*a/d = k*(a/d)`.
* Otherwise, `d` can't divide `k*a` since `d` and `k` are coprime, and we map `k*a -> m*(k*a) + i*k = k*(m*a + i)`.
Hence one step for `a` in `(d, m, i)` is equivalent to one step for `k*a` in `(d, m, i*k)`. This forms a bijection between the loop in `(d, m, i)` with the loop
```
k*a_0 -> k*a_1 -> k*a_2 -> ... k*a_(n-1) -> k*a_n = k*a_0
```
in `(d, m, i*k)`.
This means that `(d, m, i*k)` has at least as many loops as `(d, m, i)`. But since `i` is coprime to `d`, we can apply the same reasoning to any loops in `(d, m, k)`.
(This explains why the multiplication method managed to give at least as many loops each time, but the proof is incomplete until I can constrain `i`, `k` such it *always* gives strictly more loops each time).
[Answer]
## Java, arbitrary score with relatively small numbers
In my previous answer, I considered only *primitive loops*. It turns out that there's a massive benefit to be gained by considering more complex loops.
Let the *loop structure* `n_0 ... n_{k-1}` denote a loop which has `n_0` multiply operations, then a division, then `n_1` multiplications, then a division, etc. If we start with `x_0` and loop back to `x_0` then we get the constraint
```
-(d^k - m^n) x + (d^{b_0}m^0 + d^{b_1}m^1 + ... + d^{b_{n-1}}m^{n-1}) i
```
where `n = n_0 + ... + n_{k-1}` and `k > b_0 >= b_1 >= ... >= b_{n-1}` with the transitions at points corresponding to division steps.
The big bonus is the divisibility constraint: `(d^k - m^n) | i` is sufficient for `x` to exist and **doesn't depend on the breakdown of the loop structure**. However, because we have small `d` we have to worry about a new problem.
The map `x -> mx + i (mod d)` is a permutation of `0 .. d-1`, and the length of the cycle which contains `0` places an upper bound on the length of a step in the loop sequence. So we have to pick `d` to satisfy two constraints: `d^k - m^n > 0` and the cycle length of `0` under the permutation `x -> mx - m^n` is greater than `n`.
If we do that, though, the net result is that for much smaller increments than in the primitive case we can get a number of loops whose growth is related to [necklaces](http://en.wikipedia.org/wiki/Necklace_%28combinatorics%29). We have two free variables: in the interests of keeping it simple, we'll pick `n = 2k`. Then the score is OEIS [A082936](http://oeis.org/A082936)`(k+1)`.
This program allows you to specify `k` via the command line. If `k` isn't specified it defaults to `15` (and will take a while to run).
```
import java.math.BigInteger;
import java.util.*;
public class PPCG47835 {
public static void main(String[] args) {
int k = args.length > 0 ? Integer.parseInt(args[0]) : 15;
BigInteger TWO = BigInteger.valueOf(2);
int n = 2 * k;
// We want d to allow steps of up to n without getting a division "too early".
BigInteger d, i;
nd: for (d = BigInteger.valueOf((k + 1) | 1); true; d = d.add(TWO)) {
i = d.pow(k).subtract(BigInteger.ONE.shiftLeft(n));
if (i.signum() < 0) continue;
// Find multiplicative inverse of m and additive inverse of i.
BigInteger half = d.add(BigInteger.ONE).shiftRight(1);
BigInteger negI = d.subtract(i.mod(d));
BigInteger inv = BigInteger.ZERO;
for (int j = 0; j < n; j++) {
inv = inv.add(negI).multiply(half).mod(d);
// If we get a division too early, reject this value of d.
if (inv.signum() == 0) continue nd;
}
break;
}
System.out.print(d); System.out.print(" ");
System.out.print("2 "); // m is hard-coded for optimisation reasons
System.out.print(i); System.out.print(" ");
visit(d, i, new int[k], 0, n);
}
private static long visit(BigInteger d, BigInteger i, int[] a, int off, int unused) {
long count = 0;
if (off == a.length - 1) {
a[off] = unused;
if (canonical(a)) {
BigInteger x0 = BigInteger.ZERO, dj = BigInteger.ONE;
int tail = 0;
for (int step : a) tail += step;
for (int step : a) {
x0 = x0.add(dj.shiftLeft(tail));
tail -= step;
x0 = x0.subtract(dj.shiftLeft(tail));
dj = dj.multiply(d);
}
// Find min element of loop
BigInteger x = x0, min = x0;
for (int step : a) {
x = x.add(i).shiftLeft(step).subtract(i).divide(d);
if (x.compareTo(min) < 0) min = x;
}
System.out.print(min); System.out.print(" ");
count++;
}
}
else {
for (a[off] = 0; a[off] <= unused; a[off]++) {
count += visit(d, i, a, off + 1, unused - a[off]);
}
}
return count;
}
private static boolean canonical(int[] a) {
for (int i = 1; i < a.length; i++) {
// If (a[i], a[i+1], ..., a[n], a[0], ...) < (a[0], a[1], ..., a[n]) then not canonical
int cmp = 0;
for (int j = 0; j < a.length; j++) {
int l = a[(i + j) % a.length];
if (l < a[j]) return false;
if (l > a[j]) { cmp = 1; break; }
}
}
return true;
}
}
```
A table of values for small `k` is
```
k d m i count time*
1 5 2 1 1 < 10 ms
2 9 2 65 3 < 10 ms
3 11 2 1267 10 < 10 ms
4 11 2 14385 43 < 10 ms
5 13 2 370269 201 ~ 20 ms
6 19 2 47041785 1038 ~ 100 ms
7 19 2 893855355 5538 ~ 200 ms
8 19 2 16983497505 30667 ~ 200 ms
9 25 2 3814697003481 173593 ~ 1 s
10 29 2 420707232251625 1001603 ~ 6 s
11 29 2 12200509761511525 5864750 ~ 40 s
12 29 2 353814783188691825 34769374 ~ 5 mins
13 29 2 10260628712891493325 208267320 ~ 30 mins
14 37 2 9012061295994739864233 1258579654 Est. 3 hours
15 37 2 333446267951814233346669 7663720710 Est. 20 hours
16 37 2 12337511914217162067306945 46976034379 Est. 6 days
17 37 2 456487940826035138224277733 289628805623 Est. 40 days
18 53 2 10888439761782913818653903872953 1794932468571 Est. 200 days
19 53 2 577087307374494432392024159626573 11175157356522 Est. 4 years
20 53 2 30585627290848204916790749477648625 69864075597643 Est. 30 years
21 53 2 1621038246414954860589963598385138149 438403736549145 Est. 200 years
22 53 2 85915027059992607611268286218691365993 2760351032959050 Est. 1 millennium
23 53 2 4553496434179608203397220031607758574013 17433869214973754 Est. 7 millennia
24 53 2 241335311011519234780052665123279669128225 110420300879752990 Est. 50 millennia
```
\* Time estimates are for my desktop and do not take into account Moore's law.
By way of comparison, the primitive loop approach gets a count of 256 with `d`, `m`, `i`
```
115792089237316195423570985008687907853269984665640564039457584007913129639937 2 4996849058188708393209580433653885727675741749040256292713620895127148753968909535051831567130140427800536361944311235092312499689373069344185380298878764982917383437888265369150126268883047025906053263153342743077070213629949784932471711300338416949194858514466230930155541835492836976417521462552849829828151439491795769700761089550706865322109309518867509186521661727219794342712894514553528293333583599915855119152660168331477612260053269242986560430234705077330786794787124224746741755491125934611370153892764672649747250985223441107821742903117978482210743310404550821569990627266955020082462512267699612524608382581735872148872953982038291179038736250522214403619052671232809002689864336781865259379354540109842300836162000706609173175964765076778511263709578396744674506156294033696427487493995284581075738371090769692280216054762188589127518138288131520584197574318178660061993972695355899831800150346295612279289467959922359090181529773826032183983550966147639013053021175624446320586810044918343170506220667044512077125761303317073322670474685596439350814220641454677721525315039280131392532890829910170130067697032080409474280439338164759271511930332513867702570766544228541132375928947183068406094583347593832800564280442762290635827452583240997869953843692888192226067947959509118853654668842486758668573945360959090145811442082864634167563985839376502785026822543171326942649658233987139275721859204329035383519806823861212425057613938004931165043698511863564617462708774556582561671940716972894180648939006657896115428862959455238417230946713679067595489816862691644349147486206894779849957639007563773489185825715482918629241874646953393968589973983726055758140509670965131130784257752658746770299522875836967916417558624580056516645025818599746107786811195117610906962007211790873398885705293432124793536210298322552084298766198268069386062880805491599222083299335464318233260051056124578923476991556594627105141325720014597904262975057588563160127983394346337149559451184921223274046166216509923172453297276308866005970640160971974447253640185483049938996290913967990417218968456612292288092879853580526543382454103353323932221761043752650100958510514546836334665301844454632706732579808156076643457344106356663717319952066205422136815584557498274287416306809948333516338059512400285836031768037738728853866655085697835628961745960936579150014030594051099736611730828784952090247925149717088480177586091973077515920163783426873586357930397355117739381823232569393584442921225056292816498946180561941289525969617003960422591677532232581695494422894672826501434835010711144548693232721765524858883501584564131614106232735238273568271942114349829879812549011130627498932140219963787303666392047295347130161879688508390811456457052368641087884244432717695692861740620115568642209009685218970940995823407021508403213061601519833618919914949749932560729944863694408604885641564887722313569259885463824560811629566880766362602001251878207794809291813218122339446821220307765141235472082443011766303980475419934692291649426520786938210383159694818885907272486868034596183096946783948641773659235059865332207369753191701953074271720509354163414366530509110288778295364715304459481419726269591111113033831476467597336278202525638135387380196888108120928929912206592758873036841743174059283561849270589546973518670933574609017862101454211321814429515965605782955938554835763966653656877378114701214179045517832512518725967960474688548845690990403252570685296634735383825030851490757836070848487217727143150630122632582326713524671216431367897967185731901150978978236132858696398878770709085714611339654459381763421454140675234710546006013727311042163280262358576555574729282040697366642435486911563736228978836522862673173566191467315162837086074411440892998371617945050003690500905151896114024752033630148897533096375987946484230945160715581739543058978416964623885861267137072330824183417324312471836674446614010876008133639790379823864589219631550851493405179571521414493906211785716101489937944476318682055254570100577567674090072999567286563538674745272858654739596781140750088726701983063467568688969752541352662724693221773047489453355703592917617778058887059908843599493188178967878700874686452143244797148819513005887246430894552095242775512990445349861622693005347908216081740772797645842440456795027030576763990604473020801003631884917095834474304331601692592643761032130654520685121431539117515315693268225200842406369274142732055972271107516351776707718371533212612732159107013520630354915806085957847820144610680161443643265135769091115735240172475488336530036935621088987529766784704273310482058921733826723504067695303655124057745777998695652339401313417237600545378359269983782826433187502457173228518056004635323567580688340015973984774165661477090769751346736638695310346968397758030501161566303852426217265255722398591191019098351473721903784344165134363589741405888181012065942675147359343871187459103092866244041229108109993223374342699547815386745287202843187962286188829557304121449210276708780549039251488572270756397582413205985221344395421395049635518737128865348093874823841568937983371316576740738343238292513044856549027357915578576351486609801629929304257274357773471790868819355065396024826360103706885509503271843483111154793877823867513746205003482013383254850136869840017475534871341041292138116938828382825397532430891659421647616052007784354323227643272033212980860515552895569482447880644272893241694995323538200266661902496866765672536124101771115793440186119562870934758834332469914211918277126909910234360146175588843031763832160427580321457221813426171147486651090825672350255338379767798338514754852751959160574241424909472012585154994247156991924680323831209172410432330697604053037807192197962786954335219659163031820110755303192625450195020835881326991100974309169765041640005014715611472365781414246402252213122570415919098131699154591884131157350063759621906599381080203854855889032937243962930171652457368664360071406319452806117145761067190083953298084859254519269884722883749501672024090321844650907391589008563802642433197623190708196038351131407100941984178045116842548433308611897954232390312599198017011307546105797911654569868011782976987799416210264128310154756184365567467259009494398551766295947384897146380576382245396793373889241987820479008377997412311743646709894015813359148252258313301283889184299153129793406473881703701222455612590416732744003889932902484617131257634973060004070133252896502711647782061218611361609971662574694749260495926602224366686969990047311150080884201679996728981488118520710812618327278601460444407589606074211213957090080663615502399945386857714651565186614844412314333122014502453392170242543576716974460063320058767295512461357163238790571777214752114070006229765312550718446433992455939743654062732996740413754469311079804912790961953994591151510500261239704038783004705292859762976062678557186460315856835692674588307723297612422300166133365751696449747870026175009924677879030277287245269369336312789151863569206353258519913834278632462377186402279499961899284908021374152125308504639510171715509089393130521332230396542907226274183742848885698573267962797261125062141192512701061184417835613561043220323232109667059963731379596517409877681630411625817233838924488266416159803851815238257256168614277516058271688234585985732462993249956054443736648381983482701419671975145356689595272620256322481331445101492785842934898286002101833342039235462190679296198713921689536883229856906841183201263684674777479749085929473847806660491517425603701157665302860959730777662176570425150785835202311938136354096831249866980993616794259861835845854117418421176199633080854667126344881657631662542895289925905028578142969819415286087518098940882455989952729483779531997327494488649273006455284259053043267370835853418912662050811155900913019657231209352348480112926574039657102095884876087473666194876746198709126894313357133801570373641709683110295796515978000299954297796662679042970878156491109209665444208230699217768702297201937392225784881636876279840090835870138165111806161316770297227301487650691564365317103587821371568348101143269981586519324517595090564942087519294885031922087517288681587330380466542222497060227220537050162604322824602200290170113535161501858277867838006545831844346466194034806442380131576450959271537675724000508658849679726915437056598408013792937927141227114362412743251994338190882597149073139746490596072448773060164660739169347895959901258783428070465053826282687238934378771669572639364962979904839560364235330477757080320919527039947059413194447601787383981298676212538689477485296103049397296570288531280157609024919563855851065941638010910105560384646709196234593097906605084521338045305535792904755345201224219924428502320445234881533236804337154660386556198317895096622709136291150643935368146577340837582641212943711872479814861926352068155910369478195420457604854547683244448751567967214543458990619972188446862489648274259785899336937220855046067999361786359505421559641976378792316247582387949300465521246163335578117055735028548795594763719422736738699541296642630533888082084573026289684348979457301049686869256012474676007298881135557294195958957628784529517718092237567505152960799973511542468237339748060514055177275522546356644920257206379978900361138197232418223002389143614116982750262268484822017613557260859854004910808350180444116054487246697462671921182597328557520007524803709116401564426048826030164139682113612562792469520645274240336666170491422881583407224574691022829015426425872679142823179291411823384404095313173200532655220313944845581946604801116297587452485204102321891653252497296065433728399876167461244675305449764253268435078307801283711986671578586009286264684436204104362390391386544723198597283499456955734637401522715340623369596118953010351715420185046108716197180402241925717122946973480900227708787840964295454123417195858692889460592013320915419763437340308835506518497515860085201589224927986455979719291716573132693989317427092853853143558317091758708333764145267616705007914755045792698149071283036472822428464086088856741228716016631215547783878758671929883834494369906428205847245649225012840917664193773340444209047477429988486280138535299447611565118864241304783363205632689971712792857625784511243647509643143248551095327720912948972426297343335037384023426865187383421370665853949880986733066605013431868825195335391006085327808142899673095309021875360723327143271973297884126573300777596847436767267112917543088798555405098177451024925328691180726442277191831301226870556900673729077861444939050671557156811059380023851226891231720334318965013032070064100330383634381975028412906506295395355678452444790978454696616976724789986813771927545087399922786051808033797228288699479084027079820677015179207462217617550272110189915066586927794642058025609163955724593808278333064797970913248932392125660618277100321658867644590064528488635548641431127485294371207991049014982516104643680773973382964834015483793178102197744049635462238592167275327733292546923339775129043604441714985094750314083684907133240387883917707163358796456835397987686924216534713005695762336730269447397763864097217574109952760268457835103121553543943547809435629310136515867522942680208340806536737128823184478353143242959990851272642608176148916818828051817886303783114083089812006592761176216705594347614441463606055472386957586500346276183094076265319731919678377918297360320560002627772632644557590236386349651266017430679446587855304813232224024918707884564648617086383312268837676930129879648556066226806033264983598737963273870180406008683538066870502765126274643694149707285873677967718824093776882722180691117972650189102761309292934104669089740461036134415668848865221446996078261882182814526768112701706947180226498517853170695663841729344573278342052015046723008301621918433874221983031567612687639198997835055345880467379366931163029451870312801803511726470315829769955289349851591818071593612475202072766757738963248657407567124448621951918781538618159029362973703670269896934671690719204057594745131067952251875023632084626765243936006087054600526620439372647154657850827488036535695318255041120590011100411481633873900916581258214646904494496179596939758195054231831425168836082747331502993013427756287438517441087903599961786008386909298278800359735241068662935677608544425650719657846321454852052691775723834044594400908198292180899716699918508703411274237512220909057452682990580501470394045329054835880578311733770238116671488355288887843321133419538930103375653723136240819806205893624668637029920441525924508186362522801471857468411055709364731167749180173109152381041225890235125798544117424518503287053391388606784967403181422501533367232799113298300727864372488794091791244360066517146347445096119853127523618619989387774603206692805485063047665937622384725651483826289994106221444709113092530279642315850705184264478650016043079571493204867384523409447599619484322542738513532050703204484670544303980247078766728461706977613101261899613130517662043513339271972081972251235975033169859035355418581896198228448669579968354844786628892715151577207655883197361061211662890585360764248729868471541162143928479898407418951997535051386290530730534930560026151165076098324213154184926821609093750026236815995852658556780475134967682821248631118925017104070428898094451499792639954979456465328667490287970095214075242881311028544848657223299380348758074504431568354880277247371024894597317121330481789224710582588443205449648054404983651411380297568908997206645433653230553781879648698609026260609149688803834187259218391934990046249560429146172817143650579761257761859297473226211208667206278219296067860972769736845325013951766102162707890974241524047129069766698283443856433561074909072854715331636193384406654144996118408915969916186204990991034582141123994743281006246363244418773309542583886592219743760099707410621000747013211862289890467215605107191564422488628711780028413401350657998041060773532997666200753434984330930246760070729141021529876137350047762475861743365966029336095856677219758836594787689035185205018357566276403366154452535802171144627987651708319479415527121816151240974774436078840107212343662772776477715750384184775256437358764392331275973111716861241318140661879686519319679801102896769752321160368269922724425799654489764372406675126033400019307966109019867442499204870460048251242797485428868563472867215160396617956075157903885720307310099434050987317396200655657220175043854461242728923453980411119467361181531679041638758618219736521345788670637894340611197427923502661108157340822659596857580786194582953900407596655574826783788262911022735981656978119678641474565730051653303989949385633731442093650471540122475754443009919485973878675046850963401314781483864751375557302581467684573155791505113738005055965951713009435125987311912157727926596987123572005388314736057015170699190571405820344493222475637762501339486181531075750333412119852553171325870456424708803522445329570768027256890943118226300585466680714149071768756747694527967779674199727672292701094055293170775943256111412949493670926505408736539367529535253047072708341003528996780692853657902259275913028150504209018698234804907805247278498919519634797413485241817808178419079783258709888094877304454884720131521205774599179149123429480488010567779651411979379452575644824494229892475387567203397575808735183552481892282847389626644335519279613480902494199703628678924217971582686673640825975034520923481333309984472579382627381171628369255973885103607244595491212035782001761539696741214914762706129512567578375089310609565156381449913286012344158380239320492864404026249849048973815454746164774159434339922030881777546960949887833568228898334821009908230915439944011319029828183428059262552421184297456944791630398161505488763508397021966523608035018748184560985761579560983940241407106479560391909891820608540880959525042610278858310221371500586621282006975924565385523439737751976356817502920348486598579705135746712717373775992030008093742123303056282564663636742981218493378658577006648139426577704533991763882951649263192645696128958302774458682508716744246101462762753202058220999788915511409442209525344771224195365537635614569784596285738942261211014861702664933727291078199115822432678195321951844331080444623554620246999157898423521545573297946974122422428652326029397752834438104210058503652410756274373508416088465697266032715090998725292363530897498227425419187639104200987000860422607318856339760900173127146424909971071243260637473654539790380037614639658460560305522997166440361337061894981570673841422295174773855738308847365869493217478387479172474508265274053896459611097327023936106818279711661859859284005297902040361826173190520353917517593841501624863083979214677771922042330042673675827748971312997591074359693436600146885276393061272831771026848674974205729022674604104645424201757806126867223225784448131465477202766085702005907247381691118142391269089415654084629267909569022341540236203211059369603309522789964417608961538627817072516350216220491674006870237415111869714606032462485914507408954281769975478324758722382027359432279127858218458620792232947441170640486146251825636787536128451810679645949311091213950536391218178448207695073225067871296358597341331335713217531356565288624335529314554032617725078664095663913959361974597416021548340999638956683418152500468890055726969038106218741994537487017672841722456638886422968641806296783800167945888523244989122466691224701449664982262237117972785531364836749230841105558249654340103316289441694362722693442216036899253945726021704607038072621493933499268084713663487463143017774044438279129092669821340462049513896295477618081041499262887546707631694580468041778427628580823381409128006511951571493153746600021153661435963999060487989691871123898267446944425244061342471467727136009454595026124201763052056460442214672653497359790825439605055435122991872440002221158299699341762550894877256756028529939417765550243640288900435922207869547178775845753536267949609817042649185645282912272493053712667874785376191196069398119956793757782916374924356072575695084735734309660711501852285850955866643402275086657805910092044313723744430264679133758691920589232686933475070593762814793474217470400162285461668845768319031659656539982369978254204602854044341058091117550611680881628359376678819883087955697988567021691638648924577844895608406198662696865869262757680429534919253406317207666762722797998847968102286617199947462744384388515717884047800225997384360099073674099453433943926958137304536748624123197669309530015321037461250457783043296559014726071141322691971506241866656077924355900878578960637282033659413457848807209620231088382431141859409964587717237177543239362790004481987073446054038232537259240558114255180028836915328190646296092351956054483011032267954420757123439574864847382818633015646409597401939994336693025660304826515086683839422288515986705637705072643316687613870278218998858470677983202984981673539663144442468543317833948927182919212702863843641663595997542613708928254827365464641379927709913202191911620849647223085328456892605123433695824657504571351274013025428243687082509842033821110474526985064184156983393580296061829689988266546941090944235480994846680714229385404183320871974032123897879201819683832987908391594886931328780757166614327536050682203635249976585377958911420940431267251992093534777694827907246411775988472065876989655661619702364599163656758842666355291842043770616233988089275649544479451040620789894100592626970356486607161374832051953531569240599093218443171550007069330644889550839435299056046839265288195264247406157664954662322998046875
```
] |
[Question]
[
**Task**
You have a row of numbered boxes, with some filled with items and some empty. Your job is to output the number of boxes from the first to the last box, inclusive, minus the number of boxes of the largest gap between two filled boxes.
**Rules**
Your program should handle up to 1000 boxes. Score = size of program in bytes. -50 if you don't use a built-in sorting functionality. -150 if you program in assembly :D All cases will have at least one gap.
Input is a list of n-th boxes that are filled. Standard loop-holes aren't allowed.
**Sample Input**
```
9, 5, 4, 2
```
Functions with a list as input are fine.
**Sample Output**
```
5
```
This is the number of boxes between the 2nd and 9th box, inclusive, subtracted by the number of boxes of the gap between the 5th and 9th box (8 - 3 = 5)
[Answer]
# CJam, ~~-19~~ ~~-22~~ -23 (27 bytes - 50 bonus)
```
Vq~_:+,\&_(+]z{~-~:Xe>}/X+z
```
[Try it online.](http://cjam.aditsu.net/ "CJam interpreter")
### Example run
```
$ cjam box-gap.cjam <<< '[9 5 4 2]'; echo
5
```
### How it works
```
V " V := 0 ";
q~ " Q := eval(input)) ";
_:+, " S := range(sum(Q)) ";
\& " T := S โฉ T # Preserves the order of S. ";
_(+ " U := T[1:] + [T[0]] ";
]z " Z := zip(T, U) ";
{ }/ " for (X,Y) โ Z: ";
:-~:Me> " V := max(V, M := ~(X - Y)) ";
M+z " R := abs(V + M) ";
```
[Answer]
## CJam, -8 (~~43~~ 42 bytes - 50 bonus)
```
l~:A{e>}*A{e<}*-)A{_A\-f{-z}{e<}*}%{e>}*(-
```
Using tips by @Dennis!
[Try it online here](http://cjam.aditsu.net/)
Input is like:
```
[9 5 4 2]
```
[Answer]
## Mathematica, 44 bytes
```
f=Max@#-Min@#-Max[RotateLeft[l=Sort@#]-l]+2&
```
Defines a function that takes one argument in form of a list `{9, 5, 4, 2}`.
[Answer]
## APL (Dyalog 14) (34 - 50 = -16)
```
{โMLโ3โ(1+V-โ/โต)-โ/โขยจโโจ~โตโโจโณVโโ/โต}
```
This is a function that takes a list.
Or, for the same amount of characters:
```
โMLโ3โ(1+V-โ/B)-โ/โขยจโโจ~BโโจโณVโโ/Bโโ
```
This reads the list from the keyboard.
[Answer]
## Python 2 - 54 (~~117~~104-50)
```
x=input()
M=max(x)-min(x)+1
X=['1']*M
for i in x:X[i-min(x)]='0'
print M-len(max("".join(X).split('0')))
```
A program that pretends that the buckets are real, then awkwardly splits them into groups. Takes input like `9,5,4,2`.
] |
[Question]
[
This challenge has been divided into parts.
Your goal is to convert a sentence into a form of 'short-hand'
## For Part 1 these are the rules
1. Take in 1 word
2. Remove all vowels(a,e,i,o,u), except the ones at the beginning and the end
3. If a letter is repeated more than once consecutively, reduce it to only one (e.g. `Hello` -> `Hlo`)
4. Create a function which converts the word into it's corresponding unicode characters based on above given rules, as given in the table
| Letter | Corresponding Unicode Character |
| --- | --- |
| A | ลรต |
| B | L |
| C | ๏ฃฟรชรงรข |
| D | รรดร |
| E | โร รผ |
| F | โรฅฮฉ |
| G | T |
| H | | |
| I | โยฉรณ |
| J | ) |
| K | < |
| L | ( |
| M | ยทยฎร |
| N | ยทรซรฉ |
| O | โรฎยบ |
| P | โรคโข |
| Q | โยฉร
|
| R | \ |
| S | โยถยต |
| T | \_ |
| U | โรฃร |
| V | โรฅยต |
| W | โรฅยต (same as V) |
| X | X |
| Y | โฆโข |
| Z | ยทรญยฃ |
## Test Cases
| English Word | Substituted Word |
| --- | --- |
| A | ลรต |
| Quick | โยฉร
๏ฃฟรชรงรข< |
| Brown | L\โรฅยตยทรซรฉ |
| Fox | โรฅฮฉX |
| Jumps | )ยทยฎร โรคโขโยถยต |
| Over | โรฎยบโรฅยต\ |
| The | \_|โร รผ |
| Lazy | (ยทรญยฃโฆโข |
| Dog | รรดรT |
| Turtle | \_\\_(โร รผ |
| Of | โรฎยบโรฅฮฉ |
| Terror | \_\ |
As this is code-golf, shortest answer wins!
Part 2 has been posted [here](https://codegolf.stackexchange.com/q/246641/106829)
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 86 bytes
```
zzgn"aeiou"XX\\)**97?-"ลรตL๏ฃฟรชรงรขรรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ยทรซรฉโรฎยบโรคโขโยฉร
\โยถยต_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃ"jsi
```
[Try it online!](https://tio.run/##SyotykktLixN/V8d7qIb@7@qKj1PKTE1M79UKSIiJkZTS8vS3F5X6dxsnw8TejtfzWx51DH/Uc/ekJpHK6dr2mg8XNHxcGLfoyl7HnUtfbSyMebRsq3xj7qbH/VsBaKIk0sfTlqslFWc@b823Od/YGlmcjYnUBXIJBsup6L88jxOnxigQqARXG75FZxAgyO4vEpzC1JTODWBRgMNBdrI5V@WWsQJsqNnaw1XSEYqZ3wNl09iVSWnBtD4k0u5XPLTOYHqQgA "Burlesque โรรฌ Try It Online")
```
zz # To lower case
gn # Unique consecutives
"aeiou"XX # Vowels as list
\\ # List diff
)** # Map ord
97?- # Conert to index into alphabet
"ลรตL๏ฃฟรชรงรขรรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ยทรซรฉโรฎยบโรคโขโยฉร
\โยถยต_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃ" # SH as string
jsi # Select indices from SH string
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 99 bytes
```
T`L`l
\B[aeiou]\B
(.)\1+
$1
c
๏ฃฟรชรงรข
T`l`ลรต\L_รรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ยทรซรฉโรฎยบโรคโขโยฉร
\\โยถยต\_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃ
```
[Try it online!](https://tio.run/##K0otycxL/P8/JMEnIYcrxik6MTUzvzQ2xomLS0NPM8ZQm0vFkCuZ68OE3k6ukISchHOzY3ziX81sedQx/1HP3pCaRyuna9poPFzR8XBi36Mpex51LX20sjEm5tGyrTHxj7qbH/VsBaKIk0sfTloMtCQjlSuwNDM5m8upKL88j8stv4LLqzS3oJjLvyy1iAsk7ZNYVcnlkp8OAA "Retina 0.8.2 โรรฌ Try It Online") Link includes test cases. Explanation:
```
T`L`l
```
Change everything to lower case.
```
\B[aeiou]\B
```
Remove all interior vowels.
```
(.)\1+
$1
```
Deduplicate consecutive letters.
```
c
๏ฃฟรชรงรข
```
Convert `c` separately because `T` can only transliterate characters in the BMP.
```
T`l`ลรต\L_รรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ยทรซรฉโรฎยบโรคโขโยฉร
\\โยถยต\_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃ
```
Transliterate the remaining letters.
[Answer]
# [Factor](https://factorcode.org/) + `grouping.extras`, 178 bytes
```
[ >lower 1 cut 1 short cut* swap "aeiou"without glue [ ] group-by values [ members ] map-concat [ 97 mod "ลรตL๏ฃฟรชรงรขรรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ยทรซรฉโรฎยบโรคโขโยฉร
\\โยถยต_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃ"nth ] map ]
```
[Try it online!](https://tio.run/##RZDNShxBFIX3PsWhQTCBEbIxJBEhEhIUMYSMIDgiZc2d6WK6@/bUj@34s5Bk4T8mBERcuAiKPoC75AGy8R2mlq7yBpM7ShCKW4dzvzocqqW0ZztY@Dwz/@E1lNPGoMU2V96bog1H3UCFJvekxmndW@XQIVtQhpbtwXkrsEPbcihF/UckJZVMx3r43jt0KxjGm5GRbrWJT8HoDqYtVwXe8zpmQ15SEx/XyKKeEubURg/vuI16sD4j1MlatpjB2xzbgyVMZVwJ@gI6eJkuZeuH@jlcpUokigyHpDI@ZQHaWSAsYfmxZG21hzUllhMvp3yVrJNdrsqa5kIrL/arl8i5ieTufO7vydHe/dnXuHsRD3/Xt@LN6bPJsf71bv/bcfzxK@5fxpudRiNe3a7Egy/x8FbO4p/L/vefSSE/8JCLZancDHKjtFSyG7ZJksx0CMnohANqU8CoaxSJAKbwLSE15w8kKZ0O/gE "Factor โรรฌ Try It Online")
* `>lower` Convert to lowercase
* `1 cut 1 short cut* swap` Slice the ends off the input (if possible -- that's what `short` is for) and bring the middle to the top of the stack.
* `"aeiou"without glue` Remove vowels and put the ends back on.
* `[ ] group-by values [ members ] map-concat` Consolidate consecutive letters.
* `[ 97 mod "ลรตL๏ฃฟรชรงรขรรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ยทรซรฉโรฎยบโรคโขโยฉร
\\โยถยต_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃ"nth ] map` Map letters to shorthand characters.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 76 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
lฦร
ยฌยฎฦรโรขโ โรโรจโรฆMโยบ}โรฎAโรยข6Eรร2O:ยฌฯVโรซXยฌยฉโรรโรญlยฌยฑโร โรรบvยฌยจBโรญโโ >'ยฌยตโรโโรยฐSโรรบโโซโร
โโคโรโซโรฒIโรนZโรถโรฆโโคยฌยจโยฎโยฅโรจ&โร
ลโ#โรโซยฌยงmโฮฉโรยขโฮฉโรรถdยฌโโโคโรโรยฐ
```
Should have been 74 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) without the `{โร`, but apparently there's a bug in `โรโรจ`.. :/
[Try it online](https://tio.run/##AZwAY/9vc2FiaWX//2zEgcKoxIbiiaB7w4DDhcOPxb5N0Lx9w5RB4oCiNkXLhjJPOsK5VsORWMKp4oKDxZJswrHDiOKAnHbCrELFksWgPifCteKAsOKAoVPigJzDusOBw7LigLrDmEnDnVrDmsO@0LLCrMOow7TDjybDgc64I@KAusKkbdC94oCixb3igJpkwrfQssOn4oCh//9UdXJ0bGU) or [verify all test cases](https://tio.run/##AegAF/9vc2FiaWX/I3Z5PyIg4oaSICI/ef9sxIHCqMSG4omge8OAw4XDj8W@TdC8fcOUQeKAojZFy4YyTzrCuVbDkVjCqeKCg8WSbMKxw4jigJx2wqxCxZLFoD4nwrXigLDigKFT4oCcw7rDgcOy4oC6w5hJw51aw5rDvtCywqzDqMO0w48mw4HOuCPigLrCpG3QveKAosW94oCaZMK30LLDp@KAof8s/0EgUXVpY2sgQnJvd24gRm94IEp1bXBzIE92ZXIgVGhlIExhenkgRG9nIFR1cnRsZSBPZiBUZXJyb3L/LS1uby1sYXp5).
**Explanation:**
```
l # Convert the (implicit) input-string to lowercase
ฦร
# Push a list in the range [1,length] (without popping)
ยฌยฎ # Remove the last item to make the range [1,length)
ฦร # Enclose; append its own head, to have a trailing 1
โรขโ # Check which values are NOT 1
# (we now have a list of 1s with leading/trailing 0 - e.g. [0,1,1,1,0])
{โร # No-op bug-fix: sort the list, and rotate it once towards the left
โรโรจ # Apply to every truthy (==1) character in the string:
โรฆM # Push vowels-constant "aeoiu"
โยบ # Remove those from the current character
}โรฎ # After the apply_on_truthy, connected uniquify the resulting string
A # Push the lowecase alphabet
โรยข6Eรร2O:ยฌฯVโรซXยฌยฉโรรโรญlยฌยฑโร โรรบvยฌยจBโรญโโ >'ยฌยตโรโโรยฐSโรรบโโซโร
โโคโรโซโรฒIโรนZโรถโรฆโโคยฌยจโยฎโยฅโรจ&โร
ลโ#โรโซยฌยงmโฮฉโรยข
'# Push compressed integer 3279490039691721988310819230336479163628492048784374634744299180010706872685131111164709021133012715753321092552746940878765
โฮฉโรรถd # Push compressed integer 33189
ยฌโ # Double it to 66378
# (compressing 66378 directly is a byte longer: โรยข15ลรฌโรยข)
โโค # Convert the large integer to base-66378 as list:
# [923,76,66377,42564,8735,9021,84,124,10839,41,60,40,6664,5198,9532,8869,10817,92,10677,95,8899,9013,9013,88,613,5283]
โร # Convert each integer to a character with that codepoint
โรยฐ # Transliterate the lowercase alphabet to these characters
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `โรยข6Eรร2O:ยฌฯVโรซXยฌยฉโรรโรญlยฌยฑโร โรรบvยฌยจBโรญโโ >'ยฌยตโรโโรยฐSโรรบโโซโร
โโคโรโซโรฒIโรนZโรถโรฆโโคยฌยจโยฎโยฅโรจ&โร
ลโ#โรโซยฌยงmโฮฉโรยข` is `3279490039691721988310819230336479163628492048784374634744299180010706872685131111164709021133012715753321092552746940878765`; `โฮฉโรรถd` is `33189`; `โรยข15ลรฌโรยข` is `66378` ; and `โรยข6Eรร2O:ยฌฯVโรซXยฌยฉโรรโรญlยฌยฑโร โรรบvยฌยจBโรญโโ >'ยฌยตโรโโรยฐSโรรบโโซโร
โโคโรโซโรฒIโรนZโรถโรฆโโคยฌยจโยฎโยฅโรจ&โร
ลโ#โรโซยฌยงmโฮฉโรยขโฮฉโรรถdยฌโโโค` is `[923,76,66377,42564,8735,9021,84,124,10839,41,60,40,6664,5198,9532,8869,10817,92,10677,95,8899,9013,9013,88,613,5283]`.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 151 bytes
```
lambda s:R(r"(.)\1+",r"\1",R("\B[AEIUO]\B","",s.upper())).translate(4*'ยทรซรฉโรฎยบโรคโขโยฉร
\โยถยต_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃลรตL๏ฃฟรชรงรขรรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ')
import re
R=re.sub
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUaHYKkijSElDTzPGUFtJp0gpxlBJJ0hDKcYp2tHVM9Q/NsZJSUdJSadYr7SgILVIQ1NTU6@kKDGvOCexJFXDREv94cS@R1P2POpa@mhlY8yjZVvjH3U3P@rZCkQRJ5c@nLT43GyfDxN6O1/NbHnUMf9Rz96Qmkcrp2vaaDxc0aGuyZWZW5BfVKJQlMoVZFuUqldcmvQ/Lb9IoVwhM08hWj2wNDM5W11H3akovzwPSLvlVwBJr9LcgtQUIMO/LLUISIVkpAJJn8SqSiDlkp8OJD1Sc3LyQVKlRSU5qeqxVlwKCgVFmXklGmka5Zqa/wE "Python 3.8 (pre-release) โรรฌ Try It Online")
-2 thanks to @MarcMush.
-1 thanks to @Steffan
Test harness borrowed from @solid.py
[Answer]
# [Perl 5](https://www.perl.org/), 103 bytes
Pretty standard approach: lowercase the input, remove the inner vowels, remove duplicated chars and transliterate `a-z` to the required chars.
```
$_=lc;s/\B[aeiou]\B//g;s/(.)\1+/$1/g;y;a-z;ลรตL๏ฃฟรชรงรขรรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ยทรซรฉโรฎยบโรคโขโยฉร
\\โยถยต_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃ
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3jYn2bpYP8YpOjE1M780NsZJXz8dKKChpxljqK2vYgjkVVon6lZZn5vt82FCb@ermS2POuY/6tkbUvNo5XRNG42HKzoeTux7NGXPo66lj1Y2xsQ8WrY1/lF386OerUAUcXLpw0mL//8PLM1MzuZyKsovz@Nyy6/g8irNLSjm8i9LLeIKyUjl8kmsquRyyU//l19QkpmfV/xf17e0JM3iv25BDgA "Perl 5 โรรฌ Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 180 bytes
```
lambda w:''.join('ลรตL๏ฃฟรชรงรขรรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ยทรซรฉโรฎยบโรคโขโยฉร
\โยถยต_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃ'[ord(c)%97]for c in(w[0]+re.sub(r'(.)\1+|[aeiou]','',w[1:-1])+(w[-1],'')[len(w)<2]).lower())
import re
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHcSl1dLys/M09D/dxsnw8TejtfzWx51DH/Uc/ekJpHK6dr2mg8XNHxcGLfoyl7HnUtfbSyMebRsq3xj7qbH/VsBaKIk0sfTlqsHp1flKKRrKlqaR6bll@kkKwANLA82iBWuyhVr7g0SaNIXUNPM8ZQuyY6MTUzvzRWXUddXac82tBK1zBWUxuoFEgDhTSjc1KBGjVtjGI19XLyy1OLNDQ1uTJzC/KLShSKUv@DzC4Hmq0Qre4INCKwNDM5G0g7FeWX5wFpt/wKIOlVmltQDKT9y1KLgFRIRiqQ9EmsqgRSLvnpIKHSopIckKh/GoiXWlSUX6Qea8WloFBQlJlXopEGdILmfwA "Python 3 โรรฌ Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 138 bytes
```
~=replace
!s=(lowercase(s)~r"\B[aeiou]\B"=>"")~r"(.)\1*"=>x->["ลรตL๏ฃฟรชรงรขรรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ยทรซรฉโรฎยบโรคโขโยฉร
\\โยถยต_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃ"...][x[1]-'`']
```
[Try it online!](https://tio.run/##FYmxSsNAHIf3/1Okt/QibSC7LRjEQQpFuEHIBT3Sq56ed@GS2ChSEB2qVlERRBwcpGIfoJs@gIvvkBudfIMYf3zL9/32cimYX1TVuGN4IlnMoZF2sNQjbmKWcpy6Y4NoEDIudB7RAHW6CP037LnUX6q1aHdD9P3c@729vvh5OreTFzv9JCd2/ugu4/J9Ut7d2IcPezmz81NK7dtiy16d2emiZvNrVt6/Is/zorAI/ajd3G5G1VAbRzhCOYazgRSKp9gFp15ihMqkwqKFaIZaDeECV4NqBTZyEe9DYPRIwZouYD0/SFLoH3IDZJdDjx0fwareAZKbTHLoD4FwY3T96iwjGjTRhJA/ "Julia 1.0 โรรฌ Try It Online")
Just found out that `~` has the same precedence than assignement (with right associativity so the parenthesis are needed), making it the only operator with lower precendence than `=>`
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 80 bytes
```
โฆฮฉ:ยทโซรจยทโยขยทฯโขยทฯโขโรยฐkvFยฌยฎMฦโ vhยทฯรkaยฌยชโรผรกโรโ โรรชยฌยจย ร
oฦรค โร รก"โรร[ยทโร0ลยตยทโซรยทโโ :โรรกยฌโยทโรลรsfโรขร ลโคโรรญโร ยทโโ โรรตยทฯรยซรญยทฯยฐโรฑยฐโโรรฒรง$โรโคโรรปIโรรกโรครงยซรฎยฌฯeยทฯรHbยทฯยฐโรรต1Lยฌยชยฌยชโรตโร ยฎOยฌยชลรCฦรธ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvTrhuo/huKLhuarhuarigKFrdkbCqE3EoHZo4bmFa2HCu+Kfh+KAoOKGkMKsyoFvxIog4oiHXCLigoRb4biDMM614bqG4bitOuKCh8Kw4biDz4RzZuKJiM6y4oaSxojhuK3ihZvhuYDHkuG5oeKWocO46piNJOKGsuKAnknigofiio3HlMK5ZeG5gEhi4bmh4oCbMUzCu8K7xpviiKhPwrvPhEPEvyIsIiIsIlR1cnRsZSJd)
Port of 05AB1E answer.
## How?
```
โฆฮฉ:ยทโซรจยทโยขยทฯโขยทฯโขโรยฐkvFยฌยฎMฦโ vhยทฯรkaยฌยชโรผรกโรโ โรรชยฌยจย ร
oฦรค โร รก"โรร[ยทโร0ลยตยทโซรยทโโ :โรรกยฌโยทโรลรsfโรขร ลโคโรรญโร ยทโโ โรรตยทฯรยซรญยทฯยฐโรฑยฐโโรรฒรง$โรโคโรรปIโรรกโรครงยซรฎยฌฯeยทฯรHbยทฯยฐโรรต1Lยฌยชยฌยชโรตโร ยฎOยฌยชลรCฦรธ
โฆฮฉ # Lowercase the (implicit) input
: # Duplicate
ยทโซรจ # Get length range [0, length)
ยทโยขยทฯโขยทฯโข # Remove the first item and the last two items
โรยฐkvF # Two element lambda: Remove all vowels from input to lambda
ยฌยฎM # Apply z (the lambda) for each element of x (the lowercased input)
# only at the indices in y (the length range without the first and last two items)
ฦโ # Group consecutive identical items
vh # Get the first item of each (this is removing consecutive duplicates)
ยทฯร # Join by nothing
ka # Push the lowercase alphabet
ยฌยชโรผรกโรโ โรรชยฌยจย ร
oฦรค โร รก"โรร[ยทโร0ลยตยทโซรยทโโ :โรรกยฌโยทโรลรsfโรขร ลโคโรรญโร ยทโโ โรรตยทฯรยซรญยทฯยฐโรฑยฐโโรรฒรง$โรโคโรรปIโรรกโรครงยซรฎยฌฯeยทฯรHbยทฯยฐโรรต1Lยฌยช # Push huge compressed integer 3279490039691721988310819230336479163628492048784374634744299180010706872685131111164709021133012715753321092552746940878765
ยฌยชโรตโร ยฎOยฌยช # Push compressed integer 66378
ลร # Convert the huge compressed integer to base-66378:
# [923,76,66377,42564,8735,9021,84,124,10839,41,60,40,6664,5198,9532,8869,10817,92,10677,95,8899,9013,9013,88,613,5283]
C # Convert that list of codepoints to their corresponding characters
โรยฐ # Transliterate the string made earlier from the lowercase alphabet to these characters
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 143 bytes
```
s=>s.replace(/\B[aeiou]\B|(.)(?=\1)|(.)/gi,(a,b,c)=>c?[..."_ลรตL๏ฃฟรชรงรขรรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ยทรซรฉโรฎยบโรคโขโยฉร
\\โยถยต_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃ"][Buffer(c)[0]%32]:'')
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1q5Yryi1ICcxOVVDP8YpOjE1M780NsapRkNPU8PeNsZQE8TST8/U0UjUSdJJ1rS1S7aP1tPTU4o/N9vnw4TezlczWx51zH/Uszek5tHK6Zo2Gg9XdDyc2Pdoyp5HXUsfrWyMiXm0bGv8o@7mRz1bgSji5NKHkxYrxUY7laalpRZpJGtGG8SqGhvFWqmra/5XCizNTM5WcCrKL89TcMuvUPAqzS1ITVHwL0stUgjJSFXwSayqVHDJT1fSKy7IySzRUFJQ0tRLyy9yTUzO0ChXsLVTSM7PK87PSdXLyU/XKNcrSExxzUvRsNBU0FZQr7NTUAfSaRrlmpqa/wE "JavaScript (Node.js) โรรฌ Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-pl`, 103 bytes
```
gsub(/\B[aeiou]\B/,"").tr_s!"A-Za-z","ลรตL๏ฃฟรชรงรขรรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ยทรซรฉโรฎยบโรคโขโยฉร
\\\\โยถยต_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃ"*2
```
[Try it online!](https://tio.run/##AbUASv9ydWJ5//9nc3ViKC9cQlthZWlvdV1cQi8sIiIpLnRyX3MhIkEtWmEteiIsIs6bTPCQjYnqmYTiiJ/ijL1UfOKplyk8KOGoiOGRjuKUvOKKpeKpgVxcXFziprVf4ouD4oy14oy1WMml4ZKjIioy//9BClF1aWNrCkJyb3duCkZveApKdW1wcwpPdmVyClRoZQpMYXp5CkRvZwpUdXJ0bGUKT2YKVGVycm9y/m9wdGlvbnP/LXBs "Ruby โรรฌ Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 99 bytes
```
โรขรฎลยถโรรลโยฌยจโร รโร รลโซโร
ยชโรครฏลโซรยบยจลโโรรฑaeiouลฯลโโโ รลยถลโยฌยจโร รลโซโร
ยบลฯยฌรลโโรครฑลโซyลรตL๏ฃฟรชรงรขรรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ยทรซรฉโรฎยบโรคโขโยฉร
\โยถยต_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃโรฅรฏลโคลฯ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DLTOnJLVIwye/PLUoObE4VaNQU0fBL79EwzEvBYyzdRR8M/NKizU885KLUnNT80pSgYJART6peeklGUD1mkCOc35pXomGUmJqZn6pko5CpiZYtFDTmiugKBMoE1wCpNJ9EwtgFhYibAHa4FpYmphTrJGpo@BY4pmXkloBkndJRbZQE2IkTF7p3GyfDxN6O1/NbHnUMf9Rz96Qmkcrp2vaaDxc0fFwYt@jKXsedS19tLIxJubRsq3xj7qbH/VsBaKIk0sfTloMdKFbJtDmJIhLrYGhkVeSmZJZnFpckpiUk1mcAbI2sSgzMS@zOPe/blkOAA "Charcoal โรรฌ Try It Online") Link is to verbose version of code. Note that the deverbosifier thinks that the embedded string needs to be quoted (at a cost of three bytes) but I disagree. Explanation:
```
โรขรฎลยถโรรลโยฌยจโร รโร รลโซโร
ยชโรครฏลโซรยบยจลโโรรฑaeiouลฯลโโโ รลยถลโ
```
Lowercase the string and remove interior vowels.
```
ยฌยจโร รลโซโร
ยบลฯยฌรลโโรครฑลโซyลรตL๏ฃฟรชรงรขรรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ยทรซรฉโรฎยบโรคโขโยฉร
\โยถยต_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃโรฅรฏลโคลฯ
```
Deduplicate consecutive letters and translate from lowercase letters to the desired symbols. Note that the symbols take up 3 or 4 bytes each (I'm relying on the deverbosifier calculation here, as it doesn't actually bother generating the appropriate byte sequences).
[Answer]
# [Haskell](https://www.haskell.org), 200 bytes
```
import Data.Char
import Data.List
c[h]=[h]
c(h:t)=h:[c|c<-init t,notElem c"AEIOU"]++[last t]
f=map((cycle"ยทรซรฉโรฎยบโรคโขโยฉร
\\โยถยต_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃลรตL๏ฃฟรชรงรขรรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร "!!).ord.head).group.c.map toUpper
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN09k5hbkF5UouCSWJOo5ZyQWcSEL-GQWl3AlR2fE2gIxV7JGhlWJpm2GVXRyTbKNbmZeZolCiU5efolrTmquQrKSo6unf6hSrLZ2dE5iMVAqlivNNjexQEMjuTI5J1Xp4cS-R1P2POpa-mhlY0zMo2Vb4x91Nz_q2QpEESeXPpy0-Nxsnw8TejtfzWx51DH_Uc_ekJpHK6dr2mg8XNGhpKioqZdflKKXkZqYoqmXXpRfWqCXrAc0XaEkP7SgILUI4p8duYmZebYFRZl5JQoqCmkKSiGlRUUlQMsh0jBvAwA)
[Answer]
# POSIX Issue โรขยง7 Shell + Utilities, 111 characters
```
tr a-z A-Z|sed 's/./&\
/;s/.$/\
&/'|tr A-Z 'ลรตL๏ฃฟรชรงรขรรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ยทรซรฉโรฎยบโรคโขโยฉร
\\โยถยต_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃ/'|sed 2s/[ลรตโร รผโยฉรณโรฎยบโรฃรโฆโข]//g|tr -d \\n|tr -cs 0
```
Fun fact: since XPG3, tr is defined in terms of *characters*, and is defined *exclusively* for characters all the way until SUSv3, which renames -c to -C and adds byte-wise -c.
This is why in present-day POSIX we observe -c which renders the first set the complement of specified values and -C โรรฎ characters, as well as stuff like `[=equivalence classes=]` which IIRC is only vaguely supported by the illumos gate? This is a wide-reaching standards blunder. The status of this in Issue 8 and later is unclear.
Not surprisingly, *nothing* supports this. All implementations behave as-if the data were in the POSIX (C) locale, i.e. they operate on bytes.
For something *actual implementations* accept, substitute the third line for
```
&/;y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/ลรตL๏ฃฟรชรงรขรรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ยทรซรฉโรฎยบโรคโขโยฉร
\\โยถยต_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃ/'|sed 2s/[ลรตโร รผโยฉรณโรฎยบโรฃรโฆโข]//g|tr -d \\n|tr -cs 0
```
this is what the transcript below uses to emulate the answer, but it's also obviously much longer.
```
$ for w in A Quick Brown Fox Jumps Over The Lazy Dog Turtle Of Terror; do echo $w | ./cg; echo; done
ลรต
โยฉร
๏ฃฟรชรงรข<
L\โรฅยตยทรซรฉ
โรฅฮฉX
)ยทยฎร โรคโขโยถยต
โรฎยบโรฅยต\
_|โร รผ
(ยทรญยฃโฆโข
รรดรT
_\_(โร รผ
โรฎยบโรฅฮฉ
_\
```
[Answer]
# [Go](https://go.dev), 289 bytes
```
import."strings"
func f(s string)(O string){o,S:="",ToUpper(s)
for i:=range S{r,L:=S[i:i+1],len(o)
if L>0&&o[L-1:L]==r{continue}
if!Contains("AEIOU",r)||i<1||i>len(s)-2{o+=r}}
for _,r:=range o{O+=string([]rune(`ลรตL๏ฃฟรชรงรขรรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ยทรซรฉโรฎยบโรคโขโยฉร
\โยถยต_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃ`)[r-'A'])}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NVBNi9NAGMbr_IpsDrszdKrWk4TOQv0CJRClXVhIQxNCUodtZ8Ik8SvNQfSwahUVQWQPFqWL-wN6EOwP2Is_wFtz9ORP8J1kC8PMPM-877zP85x8G8vFzyQIj4JxZEwDLhCfJlJll814mpnLPIvb1_9c2tmSaaa4GKcminMRGjFOjYYh2NneCkn7FjNNOpAHSRIpnBIUS2Vwi6lAwJR-oahtsb7LLd7qeHQSCSwJ4rFh71_d3ZWu3e5YtseYKkIpMi7yqITXnZsAQGCKzd7tu86BSRWZzXi3A9u-_iMl7WuFbDFVlvXAEVXbkbJwWqzRh11P5SLC_u8T-9_7t6_-fnlZHX-t5uvBrDr7TLp48-N48-Fd9elX9XpZnT0fVqerUfXmRTVfwTo8X24-fveJq9p7vT2PlEhFWa5EuU3qSh2MDhITo0BhkEapYTFgErcR4DVHgfyeb4EKnyL_Qc7DI0AwT2vqau6Gko8FcPYQ5oIizd2RT3TVfH2o0b18mqSACUjWYk9XmnUeRUoXgYH5aqiZwcMIiNEMfGpoB8-eAsZg5HypiVtyDBiCGNTVucomdcNwhC9anHj747ouiZSSqi4B2KTNaah9Nnk3tgskLRZjTtB9cJxNBObUCKkhYTEWEui8yG2xaM7_)
Golang, once again, doesn't have the luxury of regexp lookaheads, lookbehinds, and backreferences, forcing a "manual" implementation. If you can find a Golang-compatible regexp that solved this challenge, leave a comment.
A regexp-using solution using `\B[AEIOU]\B` is [10 bytes *longer*](https://ato.pxeger.com/run?1=NVBPi9NAHMVrPkXMZWdoWulNsp1D6x9QIlHbhYUkNCFM4rBJJkwSXU17ED2sWkVFENmDRenifoAeBPsB9uIH8NYcPfkR_E2yhYHJe_m937z3Tr9FfPkz84MjP6Jq4rNUYUnGRdHTwqTQVmURdq__udJpSdTT8kKwNMq1_Z4maESPMw0rYZkGaohytf2JkbX7qrg-Noim6ffKvLjBk4zFFHnOyB7eumMduM7Iw72HNIv9gA7jeNyI0IQfZBkVKMe6JrdzoTKDCD8Fh-OKharQTYOMbWawTt_VY5oijvfNQX8247bZ7Rume5WIineImM8b-VQXuwW8sjqkdYdsV5Qp-Pl9av57__bV3y8v65Ov9WIzmdXnn_EAbX-cbD-8qz_9ql-v6vPnTn22ntZvXtSLNZzDi9X243cP26K7N9xz8VwRtChFOt91dq2pRVaKsFopgZ_TXDUIMJndGnDbq1K8oWeAC09XvAclC44AwXvS00ByI8GfpMCZDrwLjiR3mx_LqcXmUKK7ZZLlgDFYlmbP1pK1HlMhhyDAYu1IZvKIAjGdQU4JTf_ZU8AIglysJHGTR4ChiEkzXYoibgTOFF1KrHC3cdOMUCG4aEYAtm0zPZA5277b2JXCDRIihpX7kLiIU8R0NdBVDoeQAIPysrflsr3_Aw) than this solution.
## Explanation
```
// required import
import."strings"
func f(s string)(O string){
// setup
o,S:="",ToUpper(s)
// for each char...
for i:=range S{
// get the current char
r:=S[i:i+1]
// if it's a duplicate char, ignore
if len(o)>0&&o[len(o)-1:len(o)]==r{continue}
// if it's not a vowel, or it's a vowel not at the start/end of the string, add it in
if !Contains("AEIOU",r)||i<1||i>len(s)-2{o+=r}}
// translate to the unicode chars
for _,r:=range o{O+=string([]rune(`ลรตL๏ฃฟรชรงรขรรดรโร รผโรฅฮฉT|โยฉรณ)<(ยทยฎร ยทรซรฉโรฎยบโรคโขโยฉร
\โยถยต_โรฃรโรฅยตโรฅยตXโฆโขยทรญยฃ`)[r-'A'])}
return}
```
] |
[Question]
[
I am trying to push my limits of making a python code as short as possible.
>
> I left the readability part way behind.
>
>
>
I was attempting the [**K-Goodness String** problem](https://codingcompetitions.withgoogle.com/kickstart/round/0000000000436140/000000000068cca3) from Round A of Google Kick Start 2021.
The following was my initial solution:
```
def func(N, K, S):
if not S: return 0
y = 0
for i in range(N//2):
if S[i] != S[N-i-1]:
y += 1
return abs(K - y)
for i in range(int(input())):
N, K = tuple(map(int, input().split(' ')))
S = input()
y = func(N, K, S)
print(f'Case #{i+1}: {y}')
```
Then I shortened it down to the following:
```
def func(N, K, S):
if not S: return 0
for i in range(N//2): K -= S[i] != S[N-i-1]
return abs(K)
[print(f'Case #{_}: {func(*tuple(map(int, input().split())), input())}') for _ in range(1, int(input())+1)]
```
I seriously want to push the limits. Can anyone help me shorten the *for loop* part:
```
for i in range(N//2): K -= 1 if S[i] != S[N-i-1] else 0
```
so that I can make a lambda function out of `func`, like:
`func = lambda N, K, S: 0 if not S else ...` #something
P.S. I can do it the following way, but that is inefficient and involves redundant steps that increase time and space complexity:
```
func = lambda K, S: abs(K - list(map(lambda x: x[0] != x[1], list(zip(S, S[::-1])))).count(True)//2) if S else 0
[print(f'Case #{_}: {func(tuple(map(int, input().split()))[1], list(input()))}') for _ in range(1, int(input())+1)]
```
Please suggest a good way to do the same.
>
> P.S. I know its not a good practice to compress a piece of code beyond readable, but I just wanted to do this for fun.
>
>
>
Sample Input
```
2
5 1
ABCAA
4 2
ABAA
```
Sample Output
```
Case #1: 0
Case #2: 1
```
[Answer]
### 151 bytes by [@user](https://codegolf.stackexchange.com/users/95792/user)
Here is the 151-byte solution presented in [@user's answer](https://codegolf.stackexchange.com/a/237276/88546). I recommend reading through their post for an explanation of how it works.
```
for t in range(int(input())):N,K=map(int,input().split());print(f'Case #{t+1}:',0if not(S:=input())else abs(K-sum(S[i]!=S[N-i-1]for i in range(N//2))))
```
From here, three tricks can be used to shorten it by a significant amount:
* The edge case of having an empty string \$ S \$ is simply unnecessary. According to the constraints in the linked problem, \$ N \$ is always at least 1.
* `S[N-i-1]` gets the `i`th element from the back, but the same can be achieved with `S[~i]`, as mentioned [here](https://codegolf.stackexchange.com/a/41741/88546).
* `input` is used a total of three times. We can assign it to a variable with `I=input`, and reuse `I`.
### 130 bytes
Combining these reduces the solution by 21 bytes:
```
I=input
for t in range(int(I())):N,K=map(int,I().split());S=I();print(f'Case #{t+1}:',abs(K-sum(S[i]!=S[~i]for i in range(N//2))))
```
To go even further, we'll need a slight change in approach. In particular, `sum(S[i]!=S[~i]for i in range(N//2))` can be improved with some clever use of `pop`: `sum(c!=S.pop()for c in S)`. These are logically equivalent; for each character in `S`, we compare it to the last element with `S.pop()`.
### 118 bytes
In total, we save 12 bytes this way. Note that we first need to convert `S` to a list via `*S,=input()`, since strings do not have a `pop` method.
```
I=input
for t in range(int(I())):K=int(I().split()[1]);*S,=I();print(f'Case #{t+1}:',abs(K-sum(c!=S.pop()for c in S)))
```
### 112 bytes
Finally, there is a 6-byte improvement by using `open(0)` instead of `input()`, a shortcut that essentially stores the list of lines from STDIN.
```
_,*a=open(t:=0)
while a:K,(*S,_),*a=a;t+=1;print(f'Case #{t}:',abs(int(K.split()[1])-sum(c!=S.pop()for c in S)))
```
There is a lot to unpack here (no pun intended), so I will note some of the potentially confusing parts of the code.
`_,*a=open(0)` reads all input, and stores it as a list of lines. We unpack it by storing the first line in `_`, and the rest in `a`. `_` contains the number of test cases, but it is not needed for the rest of the program.
`while a:K,(*S,_),*a=a` removes the first two elements from `a`, and stores them in `K` and `S`. If we take another look at the sample input, what this is really doing is storing `5 1` in `K`, and `ABCAA` in `S` (as in the 1st test case).
The weird-looking `(*S,_)` is due to the fact that `open(0)` includes the `\n` at the end of each line, meaning that `S` actually equals `'ABCAA\n'` instead of `'ABCAA'`. The "nested unpacking" solves this by isolating the `\n` in `_`.
The `while` loop terminates when `a` is empty, or equivalently when there is no more input left.
[Answer]
Here's a 176-byter after some trivial changes (based off of [pxeger's comment](https://codegolf.stackexchange.com/questions/237271/pushing-the-limits-to-make-a-piece-of-code-solving-the-k-goodness-string-problem?noredirect=1#comment538397_237271)):
```
def f(N,K,S):
if not S:return 0
for i in range(N//2):K-=S[i]!=S[N-i-1]
return abs(K)
for _ in range(int(input())):print(f'Case #{_+1}:',f(*map(int,input().split()),input()))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY6xCsIwGIT3PMUvDk00tbYoSMAhdix06SilVGw0oGlI00HEJ3HporODL-Pb2NKiw3_8x90Hd3_qiz2WqmketRXu6vPaFwIEjmlEE8IQSAGqtJAwU9jaKJgjEKUBCVKBydWhwLHnBYRF7jrZynTUauxK108RDES-q3BEUEdlf0oq256uLSaEMG06L5wwrwoYX7Opf2MOFXhyznVXpUN1VumT7BD6Y_vdw_zmHaAl-IhvQs7RAoL247zPvg)
* You don't need to name your function `func`
* You can use a normal loop instead of a comprehension
* You can make a range starting at `0` and just add 1 to the case number when printing
* You don't need `tuple` (or even the shorter `list`) because `*` takes care of it
* You can make the result of `f` a separate argument to `print` to get rid of the braces
You're only calling the function once, so we can put that directly into the loop. To get around not being able to `return` from a function, we can try to turn the whole function into a single if expression. If `S` is empty, then it's just 0, but if it's not, we need to turn the for loop to decrement `K` into a single expression. The amount you're decrementing is `sum(S[i]!=S[N-i-1]for i in range(N//2))`, so the else part of the if expression is just `abs(K-<that sum>)`.
Once you do that, use semicolons instead of newlines, and use the walrus for assigning `S`, you get 151 bytes. (I renamed `_` `c` for readability)
```
for c in range(int(input())):N,K=map(int,input().split());print(f'Case #{c+1}:',0if not(S:=input())else abs(K-sum(S[i]!=S[N-i-1]for i in range(N//2))))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3p6flFykkK2TmKRQl5qWnamTmlQBxQWmJhqamppWfjrdtbmIBSFQHKqpXXJCTCZK1LigCKU5Td04sTlVQrk7WNqy1UtcxyExTyMsv0Qi2soWZk5oDVJCYVKzhrVtcmqsRHJ0Zq2gbHO2nm6lrGAuyPxNhv5--vhHQZk2I86CuXLDFiMtUwZDL0cnZ0ZHLRMEIyHJ0hMgBAA)
Someone who knows Python and understands your algorithm can probably do much more, but these are some simple changes you can make. Edit: Yup, [dingledooper golfed it to 112 bytes!](https://codegolf.stackexchange.com/a/237279)
] |
[Question]
[
This challenge was inspired by [Yeah But No But Yeah](https://codegolf.stackexchange.com/q/172036/55735).
---
[maxb](https://codegolf.stackexchange.com/users/79994/maxb)ยดs colleague recently sent him the following piece of JavaScript as a joke:
```
let butScript = (nrOfButs) => {
for(var i = 0; i < nrOfButs; i++){
if(i % 3 == 0){
console.log("Yeah")
}
if(i % 2 == 0){
console.log("But")
}
if(i % 3 == 1){
console.log("No")
}
}
}
```
Since the code is not only overly long but also incorrect, Iยดll suggest to maxbยดs boss to fire that guy and hire one of you folks instead.
I canยดt guarantee anything; but I reckon thereยดll be a decent wage, health insurance and possibly a company car in it. All You have to do is
A) correct the code, so the Number of Buts printed is the same as asked in the parameter
B) correct the grammar. (see below)
C) make it as short as possible.
He might as well block my calls after that because he doesnยดt like pennypickers; but who knows.
## Input
a non-negative integer, in any convenient way
## Output
`Yeah` and `No`, mostly separated by `But`s. The code above and the examples below should clarify the pattern.
Output should never end in a `But`.
And a sentence should always end with a stop (`.`) or exclamation mark; i.e. put one after every `No` that is directly followed by a `Yeah` (without a `But`) and one at the end of the output.
A single trailing "Yeah." may be printed (if you want to think positive), but thatยดs not a must.
You may print the output or return a list of strings.
Trailing blanks are acceptable, as well as a single leading **or** trailing newline.
## examples (input => possible output)
```
input 0:
Yeah.
input 1:
Yeah
But
No.
input 2:
Yeah
But
No
But
Yeah.
input 3:
Yeah
But
No
But
Yeah
But
No.
Yeah! <optional>
...
input 5:
Yeah
But
No
But
Yeah
But
No.
Yeah
But
No
But
Yeah.
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 80 bytes
```
a=>{s='';for(i=0;i<a+1;i++)s+=(i%2==0?'yeah':'no')+(i<a?'\nbut\n':'.');return s}
```
[Try it online!](https://tio.run/##tcxBCsIwEIXhvaeQgkyG0JJW3RjHXqSbWBNNKYkkrSDi2WOXuhXylj@Pb1APFftg71Pp/EUnQ0nR6RUJQBofmCUh7VHxWlrOMXJidtMQiRaeWt3gAM4DcrZcWujceZ46t8QKUAY9zcGt4zv13kU/6mr0V2aYQFx9l6L8e8WvZFid0W4y2tuM9i6jvUdMHw "JavaScript (Node.js) โ Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~105~~ 81 bytes
```
f=lambda n,s=1:(n|s)*' 'and'\nBut\n'.join((['Yeah','No']*2)[:n+1])+'.\n'+f(n-3,0)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIU@n2NbQSiOvplhTS11BPTEvRT0mz6m0JCZPXS8rPzNPQyNaPTI1MUNdR90vXz1Wy0gz2ipP2zBWU1tdD6hGO00jT9dYx0Dzf0FRZl6JQpqGqeZ/AA "Python 2 โ Try It Online")
- 24 bytes, thanks to ovs
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~48~~ 47 bytes
```
.+
*
L$`__?_?|^
Yeah$&.
__
_ยถButยถYeah
_
ยถButยถNo
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS4vLRyUhPt4@3r4mjisyNTFDRU2PKz6eK/7QNqfSkkPbQEJc8VxQnl/@//@mAA "Retina โ Try It Online") Explanation:
```
.+
*
```
Convert to unary.
```
L$`__?_?|^
Yeah$&.
```
Match up to three `_`s at a time. Also handle the zero edge case as a match. Each match results in at least a `Yeah` with a trailing `.`.
```
__
_ยถButยถYeah
```
A match of 2 or 3 `_`s results in a `But` `Yeah` in the second position.
```
_
ยถButยถNo
```
The other `_`s turn into `But` `No`.
52 bytes in Retina 0.8.2:
```
.+
$*
M!`11?1?
%`^.*
Yeah$&.
11
1ยถButยถYeah
1
ยถButยถNo
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYvLVzHB0NDe0J5LNSFOT4srMjUxQ0VNj8vQkMvw0Dan0pJD20BCXIZcUJ5f/v//pgA "Retina 0.8.2 โ Try It Online") Explanation:
```
.+
$*
```
Convert to unary.
```
M!`11?1?
```
Match up to three `1`s at a time.
```
%`^.*
Yeah$&.
```
Add a leading `Yeah` and trailing `.` for each match. The `^.*` allows it to work for the zero case too.
```
11
1ยถButยถYeah
1
ยถButยถNo
```
Add in the `But` `Yeah` and/or `No` as above.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~44~~ ~~42~~ ~~34~~ 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
[Crossed out 44 is no longer regular 44 :)](https://codegolf.stackexchange.com/questions/170188/crossed-out-44-is-still-regular-44)
```
[รd_#3โรรโยฅรฆโฌยธ#sรจ'โฌยณยถ.รธรฝ'.ยซโข,3-
```
Also prints the optional `Yeah.`.
[Try it online](https://tio.run/##AUAAv/9vc2FiaWX//1vDkGRfIzPigJrDn8Od4oCewqXDpuKCrMK4I3PDqCfigqzCs8K2LsO4w70nLsKr4oSiLDMt//81) or [verify all test cases](https://tio.run/##AUoAtf9vc2FiaWX/NUVOw5As/1vDkGRfIzPigJrDn8Od4oCewqXDpuKCrMK4I3PDqCfigqzCs8K2LsO4w70nLsKr4oSiLDMt/33Ctj//NQ).
**Explanation:**
```
[ # Loop indefinitely:
ร # Triplicate the top value
# (which is the implicit input `n` in the first iteration)
d_ # Pop one copy, and if it's negative:
# # Stop the infinite loop
3โร # Take the max `m` of another copy of `n` and 3
รโยฅรฆโฌยธ#sรจ # Create an alternating list of "yeah" and "no" of size `m`
'โฌยณยถ.รธ '# Push "\nbut\n"
รฝ # Join the alternating list with this as delimiter
'.ยซ '# Append a trailing "."
โข # Titlecase each word in this string
, # Pop and print it with trailing newline
3- # Decrease `n` by 3 for the next iteration
```
[See this 05AB1E tips of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `โยฅรฆโฌยธ` is "yeah no" and `'โฌยณ` is "but".
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 82 bytes
```
_=>_>3?f(3)+f(_-3):[...Array(_+1)].map((a,i)=>i%2?'No':'Yeah').join`\nBut\n`+'.\n'
```
[Try it online!](https://tio.run/##tcxBC4IwGIDhez9DiH0f5ke6uggq9QO6R8YcutXENlEL@vXrWtdg7/E9PL18ybmdzLgk1nXK68KLohQlrzRwjDWIhGN@IaLDNMk3iDjFKz3kCCA3BovSrLOKnRzL2VnJO0PqnbFNbY/PpbZNzKi2zLfOzm5QNLgbaNgirr5PlPxd9CtpSAPaWUCbB7R3Ae09ov8A "JavaScript (Node.js) โ Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~80~~ 74 bytes
```
f(a,i){for(i=0;-i>~a;)printf("%s%s\n","YeahNo"+i%2*5,i++<a?"\nBut":".");}
```
-6 bytes thanks to @Jonathan Frech
[Try it online!](https://tio.run/##PY1BCsIwEEVdewoZCWRMKkXopmkVPIB7oRBCm@iATqWtK2mvHlsX7j483vt1Uj8c32IM0mnCT2g7SWVqEjpOzuCrIx6CBNGLvmLQcPXuvrq0oEgcdpkmpQp3gorP7wFy2AOaMW4bH4j9xkr7D1QcpGgwXyIWdZiRWT8d8Tx@p7acUqOULTKDizjGLw "C (clang) โ Try It Online")
] |
[Question]
[
Create a routine to calculate the position of each unit of a clock with an arbitrary number of units (minutes, hours, half-days, days, years, parsecs, quarter-quells, etc), where each unit can be equally sub-divided into an arbitrary number of sub-units; *after* `n` base units have elapsed.
Basically, figure out what a clock would show after `n` seconds given user defined lengths for minutes, hours, days, etc.
For example, after 86,400 seconds on a clock that has 60 seconds in a minute, 60 minutes in an hour, 12 hours per half day, 2 half days per day, and 365 days in a year; you get the following:
`clockFunction(86400,[60,60,12,2,365]) = 0,0,0,0,1`
(Standard Clock)
`clockFunction(86400,[60,60,12,2]) = 0,0,0,0`
(Standard Clock - Rolling Over)
`clockFunction(7430201,[100,100,10,10,3,12]) = 1,2,3,4,1,2`
([French Republican Calendar](https://en.wikipedia.org/wiki/French_Republican_Calendar) [sec / min, min / hr, hrs / day, days / wk, wks / mo, mo / yr])
`clockFunction(2443332,[60,60,24,365]) = 12,42,6,28`
(Standard Clock - Donnie Darko)
`clockFunction(63570500940,[60,60,12,2,365,10000]) = 0, 29, 4, 1, 294, 2015`
(Standard Clock - Back to the Future)
Shortest code that works wins!
Clarifications:
* All Units are integer
* All Units are greater than 0
[Answer]
# Dyalog APL, ~~9~~ ~~7~~ 5 bytes
```
โฝโคโจโโฝ
```
This is a dyadic function train that expects seconds and lengths as left and right arguments. It is equivalent to the following, train-less function:
```
{โฝโบโคโจโฝโต}
```
Verify all test cases at once on [TryAPL](http://tryapl.org/?a=86400%2086400%207430201%202443332%2063570500940%20%28%u233D%u22A4%u2368%u2218%u233D%29%A8%20%2860%2060%2012%202%20365%29%2860%2060%2012%202%29%28100%20100%2010%2010%203%2012%29%2860%2060%2024%20365%29%2860%2060%2012%202%20365%2010000%29&run).
### How it works
```
โฝ Reverse the right argument...
โ and...
โคโจ perform mixed base encoding on the left argument with those bases.
โฝ Reverse the order of the result.
```
[Answer]
# Javascript ES6, 34 bytes
```
F=(q,a)=>a.map(u=>[q%u|0,q/=u][0])
```
Explanation:
```
F=(q,a)=>a.map(u=>
// For each unit
[
q%u|0, // floored remainder of q / u
q/=u // set q to quotient of q / u
][0] // return remainder
)
```
[Answer]
# CJam, 10 bytes
```
{{md\}%W<}
```
Verify all test cases at once in the [CJam interpreter](http://cjam.aditsu.net/#code=qN%2F%7B~%0A%20%20%7B%7Bmd%5C%7D%25W%3C%7D%0A~p%7D%2F&input=86400%20%5B60%2060%2012%202%20365%5D%0A86400%20%5B60%2060%2012%202%5D%0A7430201%20%5B100%20100%2010%2010%203%2012%5D%0A2443332%20%5B60%2060%2024%20365%5D%0A63570500940%20%5B60%2060%2012%202%20365%2010000%5D).
### How it works
```
{ } Define a code block:
{ }% For each unit length:
md Perform modular division with the topmost integers on the stack.
\ Swap quotient and residue.
Collect the results in an array.
W< Discard the last quotient.
```
[Answer]
# C โ 166 ~~176~~ bytes
The *Back to the Future* test case necessitated using `long long` types! The output format is not consistent in the specs, sometimes there are spaces after the comma, sometimes not, I assumed this meant the space was discretionary. ~~Handles units of zero by outputting `-1`.~~
```
#include<stdlib.h>
#include<stdio.h>
int main(int c,char**v){long long x=atoll(*++v),m;while(--c>1){m=atoll(*++v);printf("%lld%c",x%m,c>2?',':'\n');x/=m;}return 0;}
```
To use, save as `units.c`, compile via `gcc -o units units.c`, and run on the command line as follows:
```
$ ./units 63570500940 60 60 12 2 365 10000
0,29,4,1,294,2015
```
Depending on compiler options, you may be able to remove `int` and `return 0;` for 153 bytes.
[Answer]
# MATLAB, 66
```
function a=d(t,L);a=[];for s=L;a=[a mod(t,s)];t=floor(t/s);end;end
```
And an explanation
```
function a=d(t,L)
a=[];
for s=L %For each of the input blocks
a=[a mod(t,s)]; %Append the number in this block
t=floor(t/s); %And divide by the size of this block ignoring the remainder
end
end
```
It's a pretty standard approach. I'll see if I can reduce the length.
It also works with **Octave**, so you can try it [here](http://octave-online.net/).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 47 bytes
```
#~NumberDecompose~Reverse@FoldList[Times,1,#2]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X7nOrzQ3KbXIJTU5P7cgvzi1Lii1LLWoONXBLT8nxSezuCQ6JDM3tVjHUEfZKFbtf0BRZl6JgkN6tJmxqbmBqYGBpYmBjkK1GZAAYUMjHQUgMjYzBbINgKA29v9/AA "Wolfram Language (Mathematica) โ Try It Online")
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 12 bytes
```
:{:}%:nao-{,
```
Expect (units...,seconds) on the stack.
><> has the oddball property of supporting floating point division but not integer division, so the verbous stack shifting `{}` and copying `:` here is in order to subtract the remainder before performing division.
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/16789/edit).
Closed 6 years ago.
[Improve this question](/posts/16789/edit)
True Story: Several years ago while interviewing at an investment advisory firm that managed over a billion dollars in client funds, I was asked a collection of reasonable and bizarre questions by a partner in the firm. An example of a reasonable question would be "What can go wrong with a linear fit?".
But then, things devolved....
Interviewer: "Have you ever written code that modifies itself?"
Job Candidate: "No, can't say that I have"
Interviewer: "We have one guy who writes programs that modify themselves, I think he uses awk"
Job Candidate: "Wow. That's pretty incredible. AWK? "
Now it is your turn to be that one guy that financial houses would kill to hire...
Challenge: Write a self-modifying script of some kind that performs a "useful financial function".
Rules:
1. Use a scripting language, not a language requiring compilation such as C or Java. Perl, Python and the like that will work from a #! are OK. Of course, heroes use awk, but awk is not a requirement.
2. Self-modifying means that the script modifies its own source code. The script must be reusable after it has modified itself. The script might also generate useful user output to STDOUT or some other interface.
3. The definition of "useful financial function" is left to the voters and can be as intriguing or dysfunctional as you prefer. If you need examples for inspiration, here are a few ideas: stock picking, stock trading, prediction and/or fitting, future value of account, Ponzi scheme generator, risk analysis of Nigerian email deals, salary bonus calculator for partners vs employees, etc.
4. Most upvotes wins.
EDIT: I agree with one participant who notes that it is not obvious how to read the current gawk script from within gawk. Here is a solution for Linux-based systems and other O/S that have a /proc filesystem.
```
#!/usr/bin/gawk -f
BEGIN {
pid = PROCINFO["pid"]
commfile = "/proc/"pid"/comm"
print "I will look here for the script file name: " commfile
print "Here is what is in that file:"
getline scriptfilename < commfile
print scriptfilename
print "Here is my script:"
while (getline line < scriptfilename){
print line
}
}
```
[Answer]
# Pseudocode
```
// Set up a cron job to run this script (only) once a day
yesterdays_stock_price = '46.48'
todays_stock_price = curl_google_finance('VTSMX')
print "Difference between yesterday's stock price and today's: "
print todays_stock_price
self = open('self.file')
self.replace( /yesterdays_stock_price = '[0-9\.]+'/, todays_stock_price)
self.save()
```
[Answer]
# gawk (1224 characters, as this is not code golf)
One of reasons why awk shouldn't be used for self-modifying scripts.
```
#!/usr/bin/gawk -f
function download(name, url, service, host, old_rs, old_ors) {
old_rs = RS
old_ors = ORS
RS = ORS = "\r\n"
host = "download.finance.yahoo.com"
url = "http://"host"/d/quotes.csv?s="name"&f=l1"
service = "/inet/tcp/0/"host"/80"
print "GET", url |& service
service |& getline
close(service)
RS = old_rs
ORS = old_ors
return $0
}
function update(value, file, self, result) {
# Do complex stuff in order to find the program itself.
file = "/proc/"PROCINFO["pid"]"/comm"
if (getline < file <= 0) {
print "/proc filesystem not supported." > "/dev/stderr"
exit
}
close(file)
if ($0 ~ /^g?awk$/) {
print "You need to run program directly." > "/dev/stderr"
exit
}
self = $0
result = ""
while (getline < self > 0) {
# Avoid finding this line.
if (/[y]esterday/) gsub(/[0-9]+(\.[0-9]+)?/, value)
result = result $0"\n"
}
printf "%s", result > self
close(self)
}
BEGIN {
yesterday = 1120.71
today = download("GOOG")
update(today)
print "Yesterday:", yesterday
print "Today:", today
print "Difference:", today - yesterday
}
```
[Answer]
Using @jawns317 psueudocode:
# BASH
```
#!/bin/bash
set -e;
google_price_last=1118.79;
current_google_price=`wget -qO- "http://finance.yahoo.com/d/quotes.csv?s=GOOG&f=l1"|tr -d "\r\n"`;
echo "Current Price: $current_google_price";
echo "Last Price: $google_price_last";
echo "Price change: "`echo $current_google_price - $google_price_last | bc -l`;
sed -ri 's/last=[0-9\.]+\;/last='"$current_google_price"';/g' $0;
```
[Answer]
Back at uni I *discovered* (ah-hem) a system which I though would prove fool-proof at the local casino. Bet on red on the roulette wheel, and if you lost double the bet, and so on ...See [Martingale System](http://en.wikipedia.org/wiki/Martingale_%28betting_system%29)
**VBS**
```
Dim objFSO
Dim objTF
Dim strFile
Dim lngBet
lngBet = 5
strFile = "boss.txt"
'spin roulette wheel
Randomize
'18 blacks, 18 reds, 1 green
intnumber = Int(36 * Rnd + 1)
'mofify code to double-down losing bets
Do While intnumber < 18
intnumber = Int(36 * Rnd + 1)
bfound = True
Set objFSO = CreateObject("scripting.filesystemobject")
Set objTF = objFSO.createtextfile(strFile, 2)
objTF.writeline "lngbet=lngbet*2"
objTF.Close
Set objTF = objFSO.opentextfile(strFile, 1)
Execute objTF.ReadAll()
objTF.Close
Loop
If bfound Then objFSO.deletefile (strFile)
wscript.echo "final bet was " & lngBet
```
[Answer]
I have some pseudo code for someone to develop. All it really needs are some functions built to do the text replacement. I feel the function names give a sufficient description that the actual code is probably trivial.
```
Write "You should really give him back his stapler."
Write "No one has noticed an account with $0 ."
Write "Your TPS reports are complete."
Write "You should throw that Piece of * out the window."
$event = Random 1..3
$fireStarter = Random 1..100
$fractions = Random 1..100
switch $event
{
1 - $stapler = $false
2 - $TPSreports = $false
3 - $printerJam = $true
}
if ($stapler = false)
{ Write "I think you have my stapler"
if ( ($times + $fireStarter ) -GreaterThan 100 ) { Function Burn }
$times + 1
$stapler = $true
Function SelfModifyLine1
Function SelfModifyTimes
}
if ( $Fractions -LessThan 50 )
{ $account = $account + $fractions
Function SelfModifyLine2 }
if ( $TPSreports = $false ) { Function SelfModifyLine3 }
Function YellAtPrinter
Out-file $scriptPath
```
] |
[Question]
[
Your task is to output a spaceship of size `n` with shooters/guns and `n` bullets of character `-` (with spaces in between each bullet) for each gun
# Rules
* If `n` is odd, you must output the guns every even numbered row
* If `n` is even, you must output the guns every odd numbered row
* All rows with guns must have `n+1` `#` characters
* The spaceship is 3 characters tall for all inputs
* `n` must be greater than 0
# Testcases
```
1
->
#
## -
#
2
->
### - -
##
### - -
3
->
###
#### - - -
###
```
Trailing spaces are allowed
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
[Answer]
# [J](http://jsoftware.com/), 40 38 36 35 bytes
```
' -#'{~3{.2&||.4$$&2,:2,$&2,0 1$~+:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1RV0ldWr64yr9YzUamr0TFRU1Ix0rIx0QJSBgqFKnbbVf00urtTkjHyFNAVDCENdHSZghC5gjC5g8h8A "J โ Try It Online")
Consider input 2:
* `0 1$~+:` Extends `0 1` to twice the input size:
```
0 1 0 1
```
* `$&2,` Extend `2` to the input size, and prepend it:
```
2 2 0 1 0 1
```
* `2,` Prepend one more two:
```
2 2 2 0 1 0 1
```
* `$&2,:` Extend `2` to the input size, and prepend it as a new table item, with zero fill:
```
2 2 0 0 0 0 0
2 2 2 0 1 0 1
```
* `4$` Extend this new list to 4 elements:
```
2 2 0 0 0 0 0
2 2 2 0 1 0 1
2 2 0 0 0 0 0
2 2 2 0 1 0 1
```
* `2&||.` Rotate it left 0 times for even numbers, 1 time for odd:
```
2 2 0 0 0 0 0
2 2 2 0 1 0 1
2 2 0 0 0 0 0
2 2 2 0 1 0 1
```
* `3{.` Take first 3:
```
2 2 0 0 0 0 0
2 2 2 0 1 0 1
2 2 0 0 0 0 0
```
* `' -#'{~` Convert to ascii:
```
##
### - -
##
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 75 bytes
```
n=>(r=x=>x-3?"#".repeat(n)+(x%2-n%2?"":"#"+" -".repeat(n))+`
`+r(++x):"")``
```
[Try it online!](https://tio.run/##ZclBCoQwDADAu6@QLEJCqGC9CdWvtLhVFEmlivT31ePKXmdWd7ljjMt@KglfnyeTxfQYTTJ9Uu0AH6ij3707UYgxVVpJpQeA7hmGUv00sS0sR2RO1AGQtXkMcoTN11uYccKGqHiL/pOWKN8 "JavaScript (Node.js) โ Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
๏ผฎฮธ๏ผฅยณโบรฮธ#โ๏นชโบฮธฮนยฒฯโบ#ร -ฮธ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDN7FAw1hHISCntFgjJDM3tVijUEdBSVlJU0chJLUoL7GoUsM3P6U0J18DrAQomQmUMgLicqguoGKgWrBWJQVdILtQEwys//83/q9blgMA "Charcoal โ Try It Online") Link is to verbose version of code. Explanation:
```
๏ผฎฮธ First input as an integer
๏ผฅยณ Map over 3 rows
# Literal string `#`
ร Repeated by
ฮธ Input integer
โบ Concatenated with
ฮธ Input integer
โบ Plus
ฮน Current index
๏นช Modulo
ยฒ Literal integer `2`
โ If nonzero then
ฯ Empty string else
# Literal string `#`
โบ Concatenated with
- Literal string ` -`
ร Repeated by
ฮธ Input integer
Implicitly print
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'#รDฤโ -IรยซIFs}Dล ยป
```
[Try it online](https://tio.run/##ASUA2v9vc2FiaWX//ycjw5dExIbigJ4gLUnDl8KrSUZzfUTFoMK7//8z) or [verify some more test cases](https://tio.run/##yy9OTMpM/W/mquSZV1BaYqWgZO@nw6XkX1oC4en4/VdXPjzd5Ujbo4Z5Crp@h6cfWu3nVlzrcnTBod3/dQ5ts/8PAA).
**Explanation:**
```
'#ร '# Repeat "#" the (implicit) input amount of times as string
D # Duplicate this string
ฤ # Enclose; append its own character to increase its size by 1
โ -Iร # Repeat " -" the input amount of times as string
ยซ # Append it to the earlier string
IF } # Loop the input amount of times:
s # Swap the two values on the stack each iteration
# (basically swap for odd values; and not for even)
D # Duplicate the top string
ล # Triple-swap the three values on the stack from a,b,c to c,a,b
ยป # Join the three strings on the stack by newlines
# (after which it is output implicitly as result)
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 66 bytes
```
lambda n:[s:="#"*(n+1-(k:=n%2))+" -"*(1-k)*n,"#"*(n+k)+" -"*k*n,s]
```
Outputs a list of lines, which is [allowed by default I/O method rules](https://codegolf.meta.stackexchange.com/a/17095).
Could 100% be shorter in some way.
[Try it online!](https://tio.run/##PclBDsIgEEDRvaeYYEyYtpiMbgwJJ7EuMIqO1IHQbjw9sqjuft7Pn@WZ5HjKpQY31sm/rzcPYs@zdWqrOi09GR2tk90BsVdgmpGJ2Mmw/rhybDRfakgFGFigeHncNQ1EaDeQC8uiGX@lRlH7V2LRoSn@HesX "Python 3.8 (pre-release) โ Try It Online")
[Answer]
# APL+WIN, 42 bytes
Prompts for n
```
โยฏ3โ(2|n)โฝ4โด(nโด'#')(((n+1)โด'#'),(nโโ)โด'-')
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3t/6Ou5kPrjR@1TdQwqsnTfNSz1@RR7xaNPCChrqyuqaGhkadtqAnl6QDF2yYADQAL6Kpr/gcawfU/jcuQS11BnSuNywhKG3MBAA "APL (Dyalog Classic) โ Try It Online")
[Answer]
# x86-64 machine code, 34 bytes
```
89 F0 D1 E8 99 B0 23 89 F1 F3 AA 72 0A AA 89 F1 66 B8 20 2D 66 F3 AB F5 B0 0A AA FF C2 7B E6 88 37 C3
```
[Try it online!](https://tio.run/##VZJNT8MwDIbP9a8wRZNSVlA3vqSNISG4cuGEtO3QJeka1CYl6SDTtL9OcVs24JLI8vM@jqXwqjpfc940qSuR4UvI4GJdmFVaYAbZJCjNB8rUxyidgsDltq9GEHDxDrYH0iLGxI8vocf5AbeyQlcbt4LgjaOjfF/8pzqD7wxP4@Q39QluEvCSw58ZycNRojRHKTypK4O2h@ZWqGWMIm8tNUQhRlOQvpZWY/gY4u7DKIEZ43lqz9DFqHSNOpruAU7JV2yExDtXC2Uu8nuAtlumSrMIdrQwhdBKtynq@fVovJxCkBmLrHPgDEdTuu5meEv3cBhBQJkgY30ibsdQXVnCMxYO1EIP3EKH1Ih/rC2whyOy0M8pz5WWyI2Qk7Btt7M8zUpi3FIpDO4OOA6S8SvptjPGNtqptZYCu0WjLJr74XBJe@JnrgqJbIsnJPGPl630aGADhattLV3UPcxTc980Xzwr0rVrzsubKzroo8yIl8U3 "C++ (gcc) โ Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string, and takes the number n in ESI.
In assembly:
```
f: mov eax, esi # Set EAX to n.
shr eax, 1 # Shift it right by 1. The low bit goes into CF.
cdq # Set EDX to 0 (as the high bit of EAX is 0).
r: mov al, 0x23 # Set AL to the ASCII code of #.
mov ecx, esi # Set RCX to n (automatic zero extension).
rep stosb # Write AL to the string RCX times, advancing the pointer.
jc s # Jump if CF=1, to skip the guns.
stosb # Write AL to the string one more time, advancing the pointer.
mov ecx, esi # Set RCX to n (automatic zero extension).
mov ax, 0x2D20 # Set AL and AH to the ASCII codes of the space and the hyphen.
rep stosw # Write those to the string RCX times, advancing the pointer.
s: cmc # Invert CF.
mov al, 0x0A # Set AL to the ASCII code of the line feed.
stosb # Write AL to the string, advancing the pointer.
inc edx # Add 1 to EDX, setting the flags except CF.
jpo r # Jump to repeat if the sum of the low 8 bits is odd.
# This is true for 1 (1โ) and 2 (10โ) but not for 3 (11โ).
mov [rdi], dh # Add the second-lowest byte of EDX, which is 0, to the string.
ret # Return.
```
[Answer]
# [Lua](https://www.lua.org), 69 bytes
```
n=...for i=1,3 do b=n+i print(("#"):rep(b%2+n)..(' -'):rep(b%2*n))end
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m704pzRxwYKlpSVpuhY3XfNs9fT00vKLFDJtDXWMFVLyFZJs87QzFQqKMvNKNDSUlJU0rYpSCzSSVI208zT19DTUFXTV4UJaeZqaqXkpEMOgZi6ONo6FMgE)
[](https://i.stack.imgur.com/fNMk9.png)
### Alternate Approaches
```
-- 73 bytes
a,n="#",...r=a.rep for i=1,3 do b=n+i print(r(a,n+b%2)..r(' -',b%2*n))end
```
```
-- 73 bytes as well
a,n="#",...for i=1,3 do b=n+i print(a:rep(n+b%2)..(' -'):rep(n*(b%2)))end
```
```
-- 73 bytes also as well
a,n="#",...for i=1,3 do print(a:rep(n+(n+i)%2)..(' -'):rep(n*(n+i%2)))end
```
```
-- 71 bytes with rearranging
a,n="#",...for i=1,3 do b=n+i print(a:rep(b%2+n)..(' -'):rep(b%2*n))end
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 19 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
)'#*รป -k*+_k<kร\โผรn
```
[Try it online.](https://tio.run/##y00syUjPz0n7/19TXVnr8G4F3Wwt7fhsm@zDLTGPpuw5PD/vf95/Qy4jLmMuEy5TAA)
**Explanation:**
```
) # Increase the (implicit) input-integer by 1
'#* '# Pop and push a string of that many "#"
รป - # Push string " -"
k* # Repeat it the input amount of times as string
+ # Append the two strings together
_ # Duplicate the string
k # Push the input-integer
< # Only leave that many leading characters from the duplicated string
k # Push the input-integer again
ร # Loop that many times, with a single char as inner code-block:
\ # Swap the top two values
# (basically swap for even values; and not for odd)
โผ # Push a copy of the second top item of the stack to the top
ร # Wrap all three values onto a list
n # Join by newlines
# (after which the entire stack is output implicitly)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 36 bytes
```
->n{([?#*-~n+" -"*n,?#*n]*2)[n%2,3]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWiPaXllLty5PW0lBV0krTwfIy4vVMtKMzlM10jGOrf2vYainZ6qpl5tYUF2TV1NQWlKskBadF2sNYtX@BwA "Ruby โ Try It Online")
[Answer]
# [C#](https://www.microsoft.com/net/core/platform), 118 bytes
```
n=>string.Join('\n',new int[3].Select((_,i)=>new string('#',n)+(n%2==i%2?"#"+new string('x',n).Replace("x"," -"):"")))
```
*-5 bytes thanks to Stone\_Red from The Programmers Hangout discord*
Curse you C# and your verbose string repeating *shakes fist*
[Try it on .NETFiddle](https://dotnetfiddle.net/BDZxpZ)
## Explanation
`n` is the size of the spaceship, `i` is the 0-indexed current line being generated.
`Select` is C#'s version of a `map` function. When the provided predicate takes 2 arguments, the first will be the original value in the collection being enumerated, and the second will be the index of that value in the collection.
In our case we don't care about the original value, we're just using it as a shorter `for(int i = 0; i < 3; i++)`. Likewise we don't care about the original type, because `Select` will return a collection of whatever type the provided predicate function returns. In this case the predicate function returns a string, so `Select` will return an `IEnumerable<string>` regardless of the fact that it's enumerating over an `int[]`. `int` was chosen as it's the shortest standard type name in .NET.
Every line of output begins with `new string('#',n)`, which is C#'s way to repeat a char `n` times. Then the following ternary statement handles generating guns:
```
(n%2==i%2?"#"+new string('x',n).Replace("x"," -"):"")
```
The condition here is `n%2==i%2`, which is true if the parity of the size and line number match. If `n`'s parity matches `i`'s parity, it's a gun line (even values for `n` will have a gun on line 0 and 2, odd values will have a gun on line 1).
Guns have one extra `#`, so we start with `"#"+`.
`new string('x',n).Replace("x"," -")` generates a string of `n` `x` characters, then replaces each `x` with `-`, this is the golfiest way I know of to repeat a *string* `n` times, as the `new string('#',n)` method only works for repeating a single char.
Finally the `IEnumerable<string>` returned from `Select` is passed to `string.Join('\n',...)`, which simply concatenates the collection into a single string, with newlines between each line.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 26 bytes
```
'#Xa.('#.'-XaJs)X%aBX^UhJn
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuha71JUjEvU01JX11HUjEr2KNSNUE50i4kIzvPIgCqDqFkcbx0KZAA)
### Explanation
```
'#Xa.('#.'-XaJs)X%aBX^UhJn
h Builtin variable for 100
U Increment to 101
^ Split into [1; 0; 1]
BX Bitwise XOR each with
%a Input mod 2
( )X Repeat the following string that many (0 or 1) times:
'#. Pound sign concatenated to
'-Xa Hyphen repeated (input) times
Js Join on spaces
. Concatenate the following to the beginning:
'#Xa Pound sign repeated (input) times
Jn Join the final list on newlines and autoprint
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 47 bytes
```
.+
$*##$&$*-$&$*__
$
ยถ$`_ยถ$`
#-+(__)+\b|_
-
-
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0VLWVlFTUVLF0TEx3OpcB3appIQDyK4lHW1NeLjNbVjkmriubh0uRR0//835OIy4uIyBgA "Retina 0.8.2 โ Try It Online") Link includes test cases. Explanation:
```
.+
$*##$&$*-$&$*__
```
Assume each row has a gun, so output the right number of `#`s and `-`s appropriately. Also append the same number of `_`s as `#`s for calculation purposes.
```
$
ยถ$`_ยถ$`
```
Triplicate the row but append an extra `_` to the middle row.
```
#-+(__)+\b|_
```
Delete the gun if it's on the wrong row(s).
```
-
-
```
Space out the bullets.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 98 bytes
```
r,d,k;f(n){for(r=4;--r;puts("")){for(k=n+r&1,d=n+k;d--;printf("#"));for(;k&&++d<n;printf(" -"));}}
```
[Try it online!](https://tio.run/##PY1BCsMgEEX3OUVIQUZ0oEJ3Ew9TFMsgtWGaroJnN0ppVx/ee/ADPkJoTWy0mRIUfaSXgPgbIQptn/0Ny6K/NPtiRDkb@2aKiLQJlz3BcukJjYSyUsbEtfzVjMPV2p53LqCPaWRdzewd8equxMboBKzt742m2k4 "C (gcc) โ Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), 68 bytes
```
n=>[1,2,1].map(i=>'#'.repeat(n+(m=n+i&1))+' -'.repeat(m&&n)).join`
`
```
[Try it online!](https://tio.run/##PcxBCoMwEADAe16xUNEsxoC2hYIkt76iCAmibUQ3IYoX8e1pTz0PzGR3u/bRha3aH2lUiZR@1aIRdScXG7hTurgUMg5hsBunki@KSpfXiGUB1R@WPCdEOXlHhpnUst8BjYCrgJuAeydHH5@2/3ACpaH3tPp5kLN/c5MddLJKs@wYOeHJDGKbvg "JavaScript (V8) โ Try It Online")
] |
[Question]
[
# Your task
Given a *simple* regular expression, you have to count how many strings of length `n` have a match of length `n` with the given *simple* regex. This will just be a subset of regexs. Like, no lookaheads or named groups or recursion or whatever weird things regexs have.
# Simple regular expression
For the purposes of this challenge, a regex is said to be *simple* if, for one, it only contains characters in the ASCII range `32-126`. Furthermore, it should only use the following functionalities:
* match literal characters, much like the regex `abc` would only match the string "abc";
* match options, like `abc|def` would match "abc" and "def";
* match exactly 0 or 1 occurrence of something, e.g. `https?` matches "http" and "https";
* match 1 or more occurrences of something, e.g. `ah+` would match "ah", "ahh", "ahhh", "ahhhh", etc;
* match any amount of occurrences of something, e.g. `1*` matches "", "1", "11", "111", "1111", etc;
* match between `n` and `m` occurrences of something, e.g. `lo{1,4}l` matches only "lol", "lool", "loool" and "looool". If `n` is ommited, it matches up to `m` occurrences. If `m` is ommited, it matches at least `n` occurrences. Assume at least one of `n` or `m` is present;
* use `()` to group, e.g. `ab(c|d)ef` would match "abcef" and "abdef" (c.f. 2nd item in this list) or `(10)+` would match "10", "1010", "101010", "10101010", etc;
* use `.` to match any character (in the ASCII range `[32, 126]`), so `ab.` would match "abc", "ab9", "ab)", etc;
* use `\` to escape the special meaning of a character, e.g. `ab?` would match "a" and "ab", while `ab\?` only matches "ab?";
* use `[]` as a group of possible characters. Inside the brackets, all characters lose their special behaviours, except for `-` and `\`. This means that, for one, `ab[cde]` is shorthand for `ab(c|d|e)` and secondly, `ab[?+*]` matches "ab?", "ab+" and "ab\*"; also related to `[]`:
* use `-` to specify a character range within brackets. The ranges you have to support are `a-z`, `A-Z` and `0-9`, as well as their subsets, like `h-z` or `3-8`. E.g., the regex `ab[c-g]` matches "abc", "abd", "abe", "abf" and "abg"; Note that `-` has no special meaning outside of `[]` so `a-z` would only match "a-z".
# Input
The input for your program/function/routine/etc should be a string representing the regex and an integer `n`. For the regex, you can further assume:
* all characters that show up are in the ASCII range `[32, 126]`
* if `{n,m}` is used, then \$n \leq m \$
* if `-` is used inside `[]` then the specified range is well-formed
# Output
The number of strings of length `n` that match the given regex. You only have to account for characters in the ASCII range `[32, 126]`.
# Test cases
```
".*", 0 -> 1
".*", 1 -> 95
".*", 2 -> 9025
".*", 3 -> 857375
".*", 4 -> 81450625
"abc", 2 -> 0
"abc", 4 -> 0
"ab|ac|ad", 2 -> 3
"a(b|c)", 2 -> 2
"hell(o|oo)", 5 -> 1
"https?", 5 -> 1
"ho{1,4}ly", 6 -> 1
"ho{3,}ly", 137 -> 1
"[abcde]{,2}", 2 -> 25
"(10)+", 7 -> 0
"(10)+", 8 -> 1
"ab\?", 3 -> 1
"[t7]h[i1][s5] is c[0o]d[Ee3] g[0oO][l1L]f", 17 -> 432
"\+351 9[1236] [0-9]{3,3} [0-9]{2,2} [0-9][0-9]", 17 -> 40000000
"-", 1 -> 1
"\\", 1 -> 1
"[+?*]", 1 -> 3
"Abc([d-z]*|(.H)+)", 11 -> 5132188812826241
"ab|ab", 2 -> 1
".(.(.(.(.|a))))|hello", 5 -> 7737809375
```
---
This is code [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest solution in bytes, wins. If you like this challenge, consider upvoting it... And happy golfing!
[Answer]
# Java 10, ~~356~~ ~~342~~ ~~284~~ ~~275~~ ~~233~~ ~~225~~ 220 bytes
```
import java.util.*;List S;r->k->{S=new Stack();p("",k);k=0;for(var p:S)k+=(p+"").matches(r.replaceAll("\\{(,\\d+\\})","{0$1"))?1:0;return k;}void p(String p,int k){if(k<1)S.add(p);else for(char i=32;i<127;)p(p+i++,k-1);}
```
Works, but way too slow for \$n\geq4\$.
[Try it online.](https://tio.run/##fVTBcpswEL3nK3Y0nYlkCWyZOG5CbE8O7bQz6fTAETjIIMcKGBiQ07o2135AP7E/4soUpzHOVMzA6u1bvdWuxJN4FtZTnOzVqshLDU9mbq@1Su2eC/0@UH4DOge9lDDfaGlF@TrTF1Eqqgq@CJVtLwAeVKXBa@jjN8jwatHFOou0yjP7Y2vcebpU2SP7L@dzpuWjLBm0xnQKC5jAvrSmiTXdepNMfgNPiyjBxC0wQiwhbjIZuIu8xM@ihOLWIwmd4IIiROyV0NFSVri0S1mkIpL3aYpREGwxC4KYBkFNEEPbwTuOCJnx24FbSr0uM0jc2n3OVQwF/ps2FExlGhKyVQuc3HHi2SKOcUFcmVYSDvLR0uiriTN01R0fjl1SmCwUpSyxOHHrvXthClSs56mKoNJCm08jsTLFbVX8EAQ5FBpAy0pjZPcQGxC3g/AzZHiGOA3S7/9Drk44Yh51wxroNK6BuoE7Ee1EfBaN57uIHNHjAktpKp7v8tx4RqcerYtqdobmW86u6nSD2HXX4bAG5874xIP5gFDE3gTfd1IPgll3i74eh0tf8dCvRiGoCiJ/kIex/0E6ITwa@2vop/whXBjlU40goM6Iw43Ph851CP7AuglNkk7dmkM2bM3m9RJ/TMfqdjIwo4v5dNYLj@BR@X4eYT@2foS9HbY/EWqKy/lZl@bdZti4fXaCmLE7NCc/duBF0PQ8luHWJH@Mrw8n9/WRbZjtxSjNPf3OoL0dzULeptJyZedrbReGo9MMX6JL2jApMluEbIJoQhH8/vkLED1c6sMvBhN7YYuiSDe44ZJ2kpA2jXr/Bw)
**Explanation:**
```
import java.util.*; // Required import for Stack and List
List S; // List on class-level, uninitialized
k->r->{ // Method with integer and String parameter and integer return-type
S=new Stack(); // Create a new List
p("",k); // Put all permutations of length `k` consisting of printable ASCII
// characters in this list
k=0; // Re-use `k` as counter-integer, starting at 0
for(var p:S) // Loop over all permutations in the List:
k+= // Increase the counter by:
(p+"") // Convert the permutation from Object to String
.matches(r // If it matches the input-regex,
.replaceAll("\\{(,\\d+\\})","{0$1"))?
// after we've replaced all {,m} with {0,m}
1 // Increase the counter by 1
: // Else:
0; // Leave the count the same by increasing with 0
return k;} // And return the counter as result
void p( // Separated method with two parameters and no return-type, where:
String p, // `p` is the prefix-String, starting empty
int k){ // `k` is the length the permutations we want to generate
if(k<1) // If `k` is 0:
S.add(p); // Add the current prefix-String to the List
else // Else:
for(char i=32;i<127;)
// Loop over the printable ASCII characters:
p( // And do a recursive call, with:
p+i++, // The prefix-String appended with the current character
k-1);} // And `k` decreased by 1
```
Some notes:
* Java's regex only supports `{n,m}` and `{n,}`, since `{,m}` could be written as `{0,m}`.
* And Java's [`String#matches`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#matches(java.lang.String)) builtin implicitly adds a leading `^` and trailing `$` to check the entire String.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 86 bytes
Another brute-force solution taking input as `(n)(regex)`.
```
n=>g=(p,s='',c=127)=>n*!s[n-1]?--c>>5&&g(p,s+Buffer([c]))+g(p,s,c):!!s.match(`^${p}$`)
```
[Try it online!](https://tio.run/##ddDdaoMwFAfw@z1FLaVN1FiNiNsgCnsNtTQeP7bRRWm63dQ@u4uD0SrJuTz8@J@PT/7DJZw/@gsRXVWPDRsFS1qGeley3c4FFtAYs0TYlswECYqUEEiSaLttJ@K8fTdNfUYZFBg7fy0X8KtlSe@LX@AdHQ@ba3/bHPEInZDdqfZOXYsa5GO09uw1xqt77fer4GnOAj17iRaOGpxPlzLUy@coDmNdKi9hhpX1tWzgMPDq3yoW6hgqB8D3QMWohmVqalUXV9@ltwlPTHcIL/M8fVjP8EEyP9fEclWP0sAyJ7WL@dDQ8JFysdv4Cw "JavaScript (Node.js) โ Try It Online")
### Commented
```
n => // n = target string length
g = ( // g is a recursive function taking:
p, // p = regex pattern
s = '', // s = current string
c = 127 // c = current ASCII code
) => //
n * !s[n - 1] ? // if n is not equal to 0 and s is less than n char. long:
--c >> 5 && // decrement c; if it's greater than or equal to 32:
g( // do a 1st recursive call where:
p, //
s + Buffer([c]) // the character with ASCII code c is added to s
// c is not passed so that it's reset to 127
) + //
g( // do a 2nd recursive call where:
p, s, c // this value of c is discarded
) //
: // else:
!!s.match(`^${p}$`) // return true (1) if s matches p, or false (0) otherwise
```
[Answer]
# Python 3, ~~139~~ ~~[137](https://tio.run/##ZVNRi6MwEH73V4Rw0NjaYoxWW7ZX7uHgHg727TiwObBWW8FGMe7DXvW392bUdMveCJLvy8w3k8ykfm8vlRL3nOzI4V4m1@MpIY2jtvrtynheNUSTQpEzU3aRkyZbXZM2vbCc/rk1/RfqaNu2zrspTm1jSiX4qReelTpj6aVhqb3QBIVSFGoSdc6Y8Bzuhfaz/JKDUnGtq6aFNPc2062GmijYak4d4pLlV8KtEXAEm2BC3oBcz2CBOApCERrGHxjuB@4avZJjasJcg/wH6pK0S07GQQDFjl1qG8Kz6CUrS1Z1VYVkMBV2adta75@J6sYdvy/fgVt/cMIZKS7CiYyhglMmb47XP5JAlYy79gKIcKrM4GgKS46HvTktqrShvMQFl7EOJCk0SWO3kqf4eyYkOcP6VcYl/ylzzD1o@gLOcliIgJNNzD2xliR2lxsJJYp@WnpQ1Lgcfh@x7mgWXZp@QA2HwxOIF/u5NBiu8dsxZfFp@VfOO7b6YS/w8viwGXDh8SiKuBd5a8/nYxeO5jKw62z6usQG67ADlbnrEDoduRtoNw6LrsuiZfSgqG1ZOGE4Sjhkw0htLQJWqFo7pHprYcKQNkGoBmHoMm4WqmWwGqnGIWrgam0CHOPewEYT8@2SywGrKViN2/gmyMuOiDE/Wj5myBm8NvvB1g1GNZ@J/zxyCu/PITfVY803FOvJbfZrhqkQ7Xaoj6@QzH7PevpZgO7oXLj2/R8)~~ 129 bytes
Saved 2 naughty bytes thanks to @Kevin, then 6 thanks to @ovs and then 2 more by rewriting `f`, thanks to @wilkben!
```
lambda r,n:sum(1for s in map(''.join,i.product(map(chr,range(32,127)),repeat=n))if re.match(f"^{r}$",s))
import re,itertools as i
```
You can [try the smaller test cases](https://tio.run/##ZVNNi9swEL37VwhTiJQowbLi2FmaLj0Ueij0VgqOCo5jb1wcyUjawzb2b09HtrVdthMIem@@njWj7sVelOT3Gh3Q8d4W19O5QJrKB/N8xaxWGhnUSHQtOrxYbH6rRtJm02l1fi4tdmx50VQX8qnCPKYsTgmhuuqqwh4kIU2NdLW5Fra84Dr8ddPDh5AaQoLm2iltwUkbW2mrVGtQAZ3utjLWgJYQbLMMKYrQ@hNiwQSYA/tkRvGIothj7nCWpDz1zHZk2DaJdi6qOJU@LfJo@4r6ouyLsw/gQOFTXxJPxEF4qdoWq14pRyazsIu1nXl8S6gbo9uhfQFu94/jdKIYT2cyBwXnStxoPLw2AZWYRWQFRDor8zib04rT8dF/ratiU3HJGyZykwjUGFTmkRLn/EvFBXqC83eRt@ybqF3vseaWw7ccVzxhaJ@zmO8EyqP1XoBEPszHGERNx/HvX240WRCu/TxAw/H4BuSrx6XwGK7x86nE@Xn9Ryx7vPlKVu7y2OhMGI9ZlmUszuJdvGXTFE7@MtzU8fzrCwLWuwkof9cpTDqL9jButyymaxuLw6MMSRC4xXWr5HZ3XKmHAIE1sjMUqWcLG@Zon@SqQZoLmZyNtBhOE6UpkiPXGZ9AfbgGh87Zw5qJEcs5WU5ueAASfTwgPvV3Vk8dagyvjLyynXZZ@j3xX0QdwiOi6CYHp/nmig3otvixcK0cOhxc/ao1FVr8XAzh@wLhIVzyiNz/Ag) online. My solution generates all strings of length `n` with the generator `g` and then tries to match the regex to the whole string. If the test case is the regex `r`, I use the regex `^r$` to force the match to be on the whole string.
[Answer]
# perl -E, 79 bytes
```
($,,$")=@ARGV;@@="";@@=map{$,=$_;map$,.chr,32..126}@@for 1..$,;say~~grep/$"/,@@
```
] |
[Question]
[
Influenced by [Non-discriminating Programming](https://codegolf.stackexchange.com/questions/156967/non-discriminating-programming), I made up an idea of a similar challenge.
Here, we say a string is a Lucas string if the number of appearances of each character is a Lucas number (2, 1, 3, 4, 7, ...), and a string is a Fibonacci string if the number of appearances of each character is a Fibonacci number (1, 2, 3, 5, 8, ...).
Here are some concrete examples:
```
"Programming Puzzles"
Appearance Count: P a e g i l m n o r s u z
1 2 1 1 2 1 1 2 1 1 2 1 1 2
```
All counts are both Lucas numbers and Fibonacci numbers, so this is both a Lucas string and a Fibonacci String
```
"Sandbox for Proposed Challenges"
Appearance Count: C P S a b d e f g h l n o p r s x
3 1 1 1 2 1 2 3 1 1 1 2 2 4 1 2 2 1
```
All counts are Lucas numbers, so this is a Lucas string. However the count of `o` is not a Fibonacci number, so this is not a Fibonacci string.
```
"Here are some concrete examples: "
Appearance Count: : H a c e l m n o p r s t x
5 1 1 2 2 8 1 2 1 2 1 3 2 1 1
```
All counts are Fibonacci, so this is a Fibonacci string. However the counts of and `e` are not Lucas numbers, so this is not a Lucas string.
```
"Non-discriminating Programming"
Appearance Count: - N P a c d g i m n o r s t
1 1 1 1 2 1 1 3 5 3 4 2 3 1 1
```
Since count of `i` is not Lucas number, and count of `n` is not Fibonacci number, so this is neither a Lucas string nor a Fibonacci String.
## Challenge
Write 2 programs, one Lucas program and one Fibonacci program, both accepting a string as input, that:
* The Lucas program checks whether the input is Fibonacci; and
* The Fibonacci program checks whether the input is Lucas,
where the definitions of "Lucas" and "Fibonacci" are as above.
## Rules
* Your programs **can choose to receive input either from STDIN or as function/program argument**.
* Your programs **must output or return one of the 2(TWO) distinct values** at your choice, one for the truthy value and one for the falsy value, and the choice **must be consistent across the programs**, i.e. you cannot have one program returning `0/1` while the other one returning `true/false`.
* Your programs **must output or return a truthy value if the source of each other is inputted**, i.e. your Lucas program must return a truthy value if the source of your Fibonacci program is inputted, and vice versa.
* **It is allowed to have program being both Lucas and Fibonacci.**
* Characters not used are apparently not counted, in case you doubt because 0 is not in the Lucas sequence.
* Number of distinct characters in each program are not restricted to either Lucas or Fibonacci numbers.
* Only full programs or functions allowed. Snippets are not accepted.
* Standard loopholes are apparently forbidden.
## Scoring
The score will be calculated as follows:
* For each program, multiply `the number of distinct characters used` by `the maximum number of appearances of the characters in the source`.
* Add the two values calculated in the previous step up. This is your score.
Example:
```
Lucas code : 20 distinct characters, MAX(appearance of each character)=7
Fibonacci code: 30 distinct characters, MAX(appearance of each character)=5
Score: 20*7 + 30*5 = 140 + 150 = 290
```
## Test cases
```
Input | Output of ...
| Lucas Program | Fibonacci Program
----------------------------------------+---------------------------------------
<Your Lucas program> | True if all appe- | True
(Lucas string by rules) | arance counts are |
| exactly 1, 2 or 3; |
| False otherwise |
----------------------------------------+--------------------+------------------
<Your Fibonacci program> | True | True if all appe-
(Fibonacci string by rules) | | arance counts are
| | exactly 1, 2 or 3;
| | False otherwise
----------------------------------------+--------------------+------------------
"Programming Puzzles" | True | True
(Both Lucas and Fibonacci) | |
----------------------------------------+--------------------+------------------
"Sandbox for Proposed Challenges" | False | True
(Lucas but not Fibonacci) | |
----------------------------------------+--------------------+------------------
"Here are some concrete examples: " | True | False
(Fibonacci but not Lucas) | |
----------------------------------------+--------------------+------------------
"Non-discriminating Programming" | False | False
(Neither Lucas nor Fibonacci) | |
----------------------------------------+--------------------+------------------
"Hello world!" | True | True
(Both Lucas and Fibonacci) | |
----------------------------------------+--------------------+------------------
"18446744073709551616" | False | True
(Lucas but not Fibonacci) | |
----------------------------------------+--------------------+------------------
"Lucas and Fibonacci are IN pair" | True | False
(Fibonacci but not Lucas) | |
----------------------------------------+--------------------+------------------
"Lucas and Fibonacci are in pair" | False | False
(Neither Lucas nor Fibonacci) | |
```
## Winning Criteria
The submission with the lowest score in each language wins.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), score: 10 + 8 = 18
This could be a comment on Kevin's post, but I've developed it independently and the technique is slightly different. Therefore I am posting it myself.
### Fibonacci program that checks Lucas (10 bytes)
```
โฌยขDฤ0ลกร
gรQ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UdOaQ4tcjjQaHF14uDX9cHPg///BiXkpSfkVCmn5RQoBRfkF@cWpKQrOGYk5Oal56anFAA "05AB1E โ Try It Online")
```
โฌยขDฤ0ลกร
gรQ -> Full program
โฌยข -> Count the occurrences of each character in the string. Call this list C.
Dฤ -> Duplicate and yield the range [1 ... len string].
0ลก -> Prepend 0. [0 ... len string].
ร
g -> Nth Lucas number (for each).
ร -> Intersection with C.
Q -> Check equality with C.
```
---
### Lucas program that checks Fibonacci (8 bytes)
```
โฌยขDฤร
fรQ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UdOaQ4tcjjQebk073Bz4/7@SR2pRqkIiEBfn56YqJOfnJRellqQqpFYk5hbkpBZbKSgBAA "05AB1E โ Try It Online")
```
โฌยขDฤร
fรQ -> Full program
โฌยข -> Count the occurrences of each character in the string. Call this list C.
Dฤ -> Duplicate and yield the range [1 ... len string].
ร
f -> Nth Fibonacci number (for each). We don't need the 0th this time!
ร -> Intersection with C.
Q -> Check equality with C.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: ~~19~~ 17 (9x1 + 8x1)
-2 score thanks to *@Emigna*.
### Lucas (~~10~~ 9 bytes):
```
โฌยขZ>ร
GKg_
```
[Try it online (with the Fibonacci program as input).](https://tio.run/##yy9OTMpM/f//UdOaQ4ui7A63ununx8O4h1vdgDwA)
[Verify all test cases.](https://tio.run/##dY@xagJBEIb7e4rRWsHD8y5axEK4RBJESGcjc3uTy8LezrGrKIKNoA@QR7ALBLu8wNr7EL7IuZgiVYqpPv7v/4ctZpLqfjp2X8MmXA@f0By6U335cSfrjtvZ43n/9FLM61Y9NVwYLEupC5guNxtFNnhDnWe8hnc24HnFlnIYfaBSpAvPn8kQoD/LJYFgLQwtCGiNZeXzAwgmrNu5tMJIL8bFXf5X5AVKMazYqLwRhA9RFCdR1Em6Saff64VxGAevS4EW/A5IZcYahZD3xvEEKpTmXy71L7/uvt1xdt6n/ssb)
### Fibonacci (~~9~~ 8 bytes):
```
โฌยขZร
FKg_
```
[Try it online (with the Lucas program as input).](https://tio.run/##yy9OTMpM/f//UdOaQ4uiDre6eafHw3h2h1vdgVwA)
[Verify all test cases.](https://tio.run/##dY@xagJBEIb7e4rRWsHD8y5axEK4RBJESGcjc3uTy8LezrGrKIKNoA@QR7ALBLu8wNr7EL7IuZgiVYqpPv7v/4ctZpLqfjp2X8MmXA@f0By6U335cSfrjtvZeZ@@FPO6VU8NFwbLUuoCpsvNRpEN3lDnGa/hnQ14XrGlHEYfqBTpwvNnMgToz3JJIFgLQwsCWmNZ@fwAggnrdi6tMNKLcXGX/xV5gVIMKzYqbwThQxTFSRR1km7S6fd6YRzGwetSoAW/A1KZsUYh5L1xPIEKpfmXS/3Lr7tvd5w9nvdP/s0b)
Outputs `1` for truthy and `0` for falsey results.
**Explanation:**
```
โฌยข # Count each of the characters in the input
# i.e. "Programming Puzzles" โ [2,2,1,2,2,1,2,2,1,1,2,1,2,1,2,2,1,1,1]
Z # Get the max, without popping the list
# i.e. [2,2,1,2,2,1,2,2,1,1,2,1,2,1,2,2,1,1,1] โ 2
>ร
G # Calculate the Lucas numbers up to and including this max+1
# (Note: the +1 is because `1ร
G` returns `[]` instead of `[1]`)
# i.e. 2 โ [2,1]
ร
F # Calculate the Fibonacci numbers up to and including this max
# i.e. 2 โ [0,1,1,2]
K # Remove all these Fibonacci numbers from the count list
# i.e. [2,2,1,2,2,1,2,2,1,1,2,1,2,1,2,2,1,1,1] and [2,1] โ []
# i.e. [2,2,1,2,2,1,2,2,1,1,2,1,2,1,2,2,1,1,1] and [0,1,1,2] โ []
g_ # Check if the list is not empty
# i.e. [] โ 0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 8ร1+9ร1=17
[code-page](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Lucas Program:
```
ฤ แบfฦJรแธ$
```
**[Try it online!](https://tio.run/##AS4A0f9qZWxsef//xKDhuohmxpFKw4bhuJ4k////IlByb2dyYW1taW5nIFB1enpsZXMi "Jelly โ Try It Online")** Or see [all-tests](https://tio.run/##y0rNyan8///Igoe7OtKOTfQ63PZwxzyV/0f3HG5/1LQmC4gfNczR1bVTeNQwN/L//2glNJVKOlwKCLGjuw@3Hdl/rAssGlCUn16UmJubmZeuEFBaVZWTWgwWD07MS0nKr1BIyy9SAKopyC9OTVFwzkjMyUnNS4eq8UgtSlVIBOLi/NxUheT8vOSi1JJUhdSKxNwCoDlWCmBVfvl5uimZxclFmUBLEkvAFiEshRqUk5OvUJ5flJOiCBYwtDAxMTM3MTEwNzY3sDQ1NTQzNANL@JQmJxYrAN2m4JaZlJ@XmJycCXaBp59CQWJmEV41mXkQNbEA "Jelly โ Try It Online").
Fibonacci Program:
```
ฤ แบfฦJลปรฤฟฦ
```
**[Try it online!](https://tio.run/##y0rNyan8///Igoe7OtKOTfQ6uvtw25H9x7r@//@vBBc83PZwxzwVJQA "Jelly โ Try It Online")** Or see [all-tests](https://tio.run/##y0rNyan8///Igoe7OtKOTfQ6uvtw25H9x7r@H91zuP1R05osIH7UMEdX107hUcPcyP//o5Xgag@3PdwxT0VJh0tBCUM/WDSgKD@9KDE3NzMvXSGgtKoqJ7UYLB6cmJeSlF@hkJZfpABUU5BfnJqi4JyRmJOTmpcOVeORWpSqkAjExfm5qQrJ@XnJRaklqQqpFYm5BUBzrBTAqvzy83RTMouTizKBliSWgC1CWAo1KCcnX6E8vygnRREsYGhhYmJmbmJiYG5sbmBpampoZmgGlvApTU4sVgC6TcEtMyk/LzE5ORPsAk8/hYLEzCK8ajLzIGpiAQ "Jelly โ Try It Online").
### How?
Both work in very similar fashions -- `รแธ` gets the nth Fibonacci number while `รฤฟ` gets the nth lucas number. `ลป` adds a zero to the front of the list of n's to use with `รฤฟ` to cater for the fact that the 0th Lucas number is 2, which we need to test for while 0 is the 0th Fibonacci number, which we do not need to test for. `ฦ` is a quick to chain the last three links together as a monad, while `$` chains the last two links together as a monad...
Lucas Program:
```
ฤ แบfฦJรแธ$ - Link: list of characters, s
ฤ - group indices by value
แบ - length of each
$ - last two links as a monad (f(s))
J - range of length of s
รแธ - nth Fibonacci number (vectorises)
ฦ - is left argument is equal to the result of?:
f - filter - remove items from left that are not in right
- i.e. groupLengths without those Fibonacci numbers
```
Fibonacci Program:
```
ฤ แบfฦJลปรฤฟฦ - Link: list of characters, s
ฤ - group indices by value
แบ - length of each
ฦ - last three links as a monad (f(s))
J - range of length of s
ลป - prepend a zero
รฤฟ - nth Lucas number (vectorises)
ฦ - is left argument is equal to the result of?:
f - filter - remove items from left that are not in right
- i.e. groupLengths without those Lucas numbers
```
[Answer]
# Java 8, score ~~1238~~ 1137 (35x18 + 39x13)
### Lucas:
```
c->c.chars().map(a->c.length()-c.replace(""+(char)a,"").length()).allMatch(a->{int n=2,s=1,m=3;for(;a>m;n=s,s=m)m=n+s;return a>0&a<4|a==m;})//",-..mmnrr
```
[Try it online.](https://tio.run/##jVPbbhMxEH3vVwz7gOwku2loLqWL84KEQEqrSuGN8jBxnKyLL4vtLb3llQ/gE/mR4N1caFoJYWltzcyZ8Tmr42u8wfR6/m3NFXoP5yjNwxGANEG4BXIBkzoEmFmrBBpQZBqcNEvwNI@F1VHcfMAgOUxAAYM1T8c84wU6T2imsSRYJ5Qwy1AQmvLMiVLFySRJ2qTGUewkCd0jaIZKnWPgRd35EJmAYW86nvU6mp3kC@tIjmOdG@ZjUlPNTNvnToTKGcDx8Wt8139ExnS@ot1u0kmzTGvj3DqvuZbVTEWuW8o3Vs5BR81bVV@@AtKN4CB8IMmls0uHWteKL6v7eyV80gjfAaZo5jN7C5EWRHBpvZjD@yJKiHKegz8KJwDj560WwK3hkbYAcYu6jJPP4BB@YU06l547Ge@PfGsOf/k8H62UhR/Wqfmrw0rvtN8fjvr949HJ6PjtYNAb9oaHiEnF0UMUAh/kzBrkXDYsP11AidL9H1iaA3CzdbvwOTaBXEAoxJOGRWV4kNaA9BBcFYq75geGIsabC3aIsydX@3TsD5wl6sTeWX7vrKvkauct0amDf7pLMRIPGpNF5r@7QJANWtjCdp9ubUVUSzGGj@QlNGWnlDZV2vgtjXbLWAwRjSL1ovVKXryWxnqNru2DkqaswtZ80zsfhM5sFbIyFoMypCm3E/j98xckbZWpTYZuB6/WfwA)
### Fibonacci:
```
s->s.chars().map(e->s.length()-s.replace(""+(char)e,"").length()).allMatch(a->{int l=(int)Math.sqrt(a=5*a*a+4);return(l*l==a|(l=(int)Math.sqrt(a-=8))*l==a);})//--...===aaanl((((()))))
```
[Try it online.](https://tio.run/##jVPLbtswELznK7Y6FGRsyXbjPBqVvhQwWqAJAri3poc1RUVM@VBJKs3z2g/oJ/ZHXEqWkzgFihIQhd0dLmcWw0u8wvSy@LbiCr2HE5TmbgdAmiBciVzAvA0BltYqgQZKsghOmgvwNI@Fh524@YBBcphDCQxWPp35jFfoPKGZxpqINqGEuQgVoanPnKhV7EySZEBaHBXDJKGPCJqhUicYeEUwnd1FJqAYiT8ak1Xmv7tAkO3v4i4OpjR3IjTOELWrGMN78jc0ZUeUdlWaP9DRKE2zLGMxRDSKtIu2a5W3UupmqaKUXtGVlQXoOJJe9JevgHQ9jyB8IMmZsxcOtW4Hctbc3irhk24uG8ACTbG011BaBxFcWy8KeF9FhVHtS/AH4QRg/LzVArg1PIoTIK5R17HzMWzDT61JC@m5k/H@yLfl8MTnZWulLPywThWvtiuTo@n04HA6HR/uHY7f7u9PDiYH24hPDUcPUQjM5dIa5Fx2LD@eQo3S/R9Ymi1wt41G8DkeAllCqASsj5aN4UFaA9JDcE2obrrhhSrGTy03qONnV/N0xreMh23i0Xj80XjnyfnGejhsg3@az7A3Q88mQ8328siE5DjTuWE@JjXVzAx870HA2fg1vpveI2O6s9p5Moxm09q4Xvjz59KZq2Pevyhp6ib09lrc@CB0ZpuQ1bEYlCFdeZDA75@/IBmUWbnO0L7xw@oP)
**Explanation (base) Lucas:**
```
s-> // Method with String parameter and boolean return-type
s.chars() // Loop over the characters as integer-stream
.map(c-> // Map each of them to:
s.length()-s.replace(""+(char)c,"").length())
// The occurrence-count of this character in the input
.allMatch(n->{ // Check if all these occurrence-counters are true for:
int a=2,b=1,c=3; // Integer `a`,`b`,`c` starting at 2,1,3 (start of Lucas sequence)
for(;n>c; // Loop as long as the current occurrence-counter is larger than `c`
; // After every iteration:
a=b, // Replace `a` with `b`
b=c) // Replace `b` with `c`
c=a+b; // Replace `c` with `a` + `b`
return // Return whether the occurrence-counter is one of:
n>0&n<4 // 1,2,3,
|n==c;}) // or `c`
```
**Explanation (base) Fibonacci:**
```
s-> // Method with String parameter and boolean return-type
s.chars() // Loop over the characters as integer-stream
.map(c-> // Map each of them to:
s.length()-s.replace(""+(char)c,"").length())
// The occurrence-count of this character in the input
.allMatch(n->{ // Check if all these occurrence-counters are true for:
int r=(int)Math.sqrt(n=5*n*n+4);
// Integer `r`, the square of `5*n*n+4` floored
return r*r==k // Return whether `5*n*n+4` is a perfect square,
|(r=(int)Math.sqrt(n-=8))*r==n;})
// and/or if `5*n*n-4` is a perfect square
```
A number \$n\$ is a Fibonacci number, if either or both of \$5n^2+4\$ or \$5n^2-4\$ is a perfect square [(source)](https://en.wikipedia.org/wiki/Fibonacci_number#Recognizing_Fibonacci_numbers)
**Explanation modifications:**
After these base programs explained above, I've made the following changes:
* Changed the names of variables to only use letters we've already used to reduce amount of distinct characters; and also so the least amount of characters have to be added at the comment to make the occurrence-counts Lucas/Fibonacci numbers;
* Added parenthesis around the return-statement (to get rid of the space as well);
* Put any remaining character we need to increase for it to become a Lucas/Fibonacci number after the trailing comment `//`.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 32\*2 + 33\*2 = ~~171~~ 130
*-41 points thanks to nwellnhof!*
### Lucas Program:
```
{min([values .ordsโe]ยป.&{$_โ(1,1,*+*โฆ0)[0โฆ$_]})}
```
### Fibonacci Program:
```
{min([values .ordsโe]ยป.&{$_โ(2,1,*+*โฆ0)[0โฆ$_]})}
```
[Try it online!](https://tio.run/##nZHPSsNAEMbP5inG0D9JTUOiaastBVEQC1IKHttStpttXdjsxt1E28aCx@LBx/AlvPkofZG6aQ5eRKSHYdjhN9/3MRsTyZq7XbSECoOukUWUW8MnxFKiwBUyVNu3dzL@@nQrWWmy3Wws3/Gd2klt@/rh2UNPt9JkvLbXRq4w@5fC6e8KeYZLLEK91oXqwUGqTvXgCNWOYcyEhJcih2MOpJhLFGm9OQzS1YoRZTpg3iMeTsUCclYjsVAkhOsHxBjh8wK5JZIA0qVERAALjiVJCJAFimKt0oYc6gteD6nCkmoHlOxdfhxNR6swJuBZSBYe66d/HgTNVhB4rbOWd9Fo@E2/mevcpRgp0KHghk4FRxjTvXevDzGi8i@E8gKBzDiKJeXJzDLL9cBTo6RcFNfrpYkDzCpNbAdmebM7xtowFFrqW2AhSXuUaKq4mhuh2MpcLKKpm3L6mBK3x5NaMbhCc7f4GI0t1rar0mj3DQ "Perl 6 โ Try It Online")
Anonymous code blocks that take a string and return a Junction (which can be coerced to truthy/falsey values). Both use the same structure rearranged to get the correct amount of characters.
### Explanation:
```
{min([values .ordsโe]ยป.&{$_โ(1,1,*+*โฆ0)[0โฆ$_]})}
{ # Anonymous code block
min( # Find the minimum of:
[values .ordsโe] # Coerces the string to a list of the number of occurrences
ยป.&{ # Map each value to:
$_โ # Whether the value is an element of:
(1,1,*+*โฆ0) # The sequence
[0โฆ$_] # Truncated to prevent it evaluating infinitely
}
)
}
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 11\*1+12\*1=23 bytes
Both return 0 as truthy, 1 as falsy
Fibonacci test:
```
ฤแปคโนษ2แดลแธ\ลยฑ
```
[Try it online!](https://tio.run/##K6gs@f//yISHu5c8at95corRwy3tR2c@3DEv5mjjoY3//xengkAuAA "Pyt โ Try It Online")
Lucas test:
```
ฤแปคโนษ02แดลฤฟ\ลยฑ
```
[Try it online!](https://tio.run/##K6gs@f//yISHu5c8at95coqB0cMt7UdnHNkfc7Tx0Mb//4tTQSAXAA "Pyt โ Try It Online")
Explanation:
```
Implicit input
ฤ Duplicate the input
แปค Get list of unique characters
โน Swap the top two elements on the stack
ษ Count the number of occurrences of each character in the input
2แดล Push [1,...,100] (should be more than enough)
แธ Get the first 100 Fibonacci numbers
\ Get all character counts that aren't Fibonacci numbers
ล Get the number of such counts
ยฑ Output the sign of the number of such counts
Implicit output
```
ย
```
Implicit input
ฤแปคโนษ get count of occurrences of each character
02แดล Push [0,1,...,100] (should be more than enough)
ฤฟ Get the first 101 Lucas numbers
\ Get all character counts that aren't Lucas numbers
ล Get the number of such counts
ยฑ Output the sign of the number of such counts
Implicit output
```
] |
[Question]
[
**This question already has answers here**:
[Draw an alphabet party hat](/questions/97456/draw-an-alphabet-party-hat)
(51 answers)
Closed 3 years ago.
I know it's 1.5 weeks after Christmas but trying to print an isosceles triangle in a monospaced font makes it look weird.
# Challenge
Print the alphabet from A to Z so that it forms a filled triangle in the output.
For each line in the output, starting from "A", add the next letter.
No inputs, only outputs. Pad the leading edge of the triangle with spaces.
Best answer is the code with the least bytes.
# Output
```
A
AB
ABC
ABCD
ABCDE
ABCDEF
ABCDEFG
ABCDEFGH
ABCDEFGHI
ABCDEFGHIJ
ABCDEFGHIJK
ABCDEFGHIJKL
ABCDEFGHIJKLM
ABCDEFGHIJKLMN
ABCDEFGHIJKLMNO
ABCDEFGHIJKLMNOP
ABCDEFGHIJKLMNOPQ
ABCDEFGHIJKLMNOPQR
ABCDEFGHIJKLMNOPQRS
ABCDEFGHIJKLMNOPQRST
ABCDEFGHIJKLMNOPQRSTU
ABCDEFGHIJKLMNOPQRSTUV
ABCDEFGHIJKLMNOPQRSTUVW
ABCDEFGHIJKLMNOPQRSTUVWX
ABCDEFGHIJKLMNOPQRSTUVWXY
ABCDEFGHIJKLMNOPQRSTUVWXYZ
```
# Sample Java Code (430 bytes)
```
public static void main(String args[]) {
String spaces = "";
String alpha = "";
char A = 'A';
for (int i = 0; i < 26; i++) {
for (int j = 13 - (i/2); j > 0; j--) {
spaces += " ";
}
alpha += (char)(A + i);
System.out.println(spaces + alpha);
spaces = "";
}
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 44 bytes
```
t=''
26.times{|x|puts' '*(12-x/2)+(t<<65+x)}
```
[Try it online!](https://tio.run/##KypNqvz/v8RWXZ3LyEyvJDM3tbi6pqKmoLSkWF1BXUvD0Ei3Qt9IU1ujxMbGzFS7QrP2/38A "Ruby โ Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
Auฮท.c
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fsfTcdr3k//8B "05AB1E โ Try It Online")
**Exlpanation**
```
A # push the alphabet
u # convert to upper case
ฮท # get list of prefixes
.c # centralize, focused to the left
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 8 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
'โธโซZm}ยนโ
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTI3JXUyMDc4JXUyMjJCWm0lN0QlQjkldTI1NUE_,v=0.12)
Explanation:
```
'โธ push 26
โซ } that many times, pushing the counter
Zm mold the alphabet to the counters length
ยน wrap the stack in an array
โ center horizontally
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/learn/what-is-dotnet), 114 + 18 = 132 bytes
[Try It Online!](https://tio.run/##ZU9NT8JAEL3vr5j0NBvqCphwqZAgiAoFK1Xx81CXwWxSd2N3KyGG3163NDEmvtv7mJc30h5JU1BVWqXfId1ZRx8R@8tErPRnxJjMM2shYd8MPKzLnJLwZdQa5pnSyA9yY9aYlFqeWlf4ogFsPIE@VMj7g0YTU@OPghcdhJq2oLR77vZeRUo5SYeoQvLRYHg2Gp9PLi6vprN4vrhObpbp7d396uHxKRBp@dZUYTukVoeLJFvHtHHYOWlhLRx3OedV9LtoZLQ1OYlVoRz5pwjrWcj5/8iSfFed8N7B3LM9q34A)
```
()=>string.Join("\n",new int[26].Select((i,e)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZ".Substring(0,e+1).PadLeft(13+(e+1)/2)))
```
[Answer]
# [J](http://jsoftware.com/), ~~38~~ 36 bytes
```
echo(' '<@#"0~2#i._13),&><\u:65+i.26
```
[Try it online!](https://tio.run/##y/r/PzU5I19DXUHdxkFZyaDOSDlTL97QWFNHzc4mptTKzFQ7U8/I7P9/AA "J โ Try It Online")
This is honestly disgusting.
# 39 bytes
```
echo(2#i._13)(>@],~' '#~[)"0<\u:65+i.26
```
# Explanation
These will be snippets of the code built up from a REPL session. Three spaces means an input, and no spaces means the output from it.
### The alphabet
First we generate the alphabet by making the range [65,90] and converting this to unicode using `u:`.
```
65 + i.10 NB. truncated
65 66 67 68 69 70 71 72 73 74
u: 65 + i.26
ABCDEFGHIJKLMNOPQRSTUVWXYZ
```
Then we generate the `A`, `AB`, etc. sections by taking all of the prefixes of the alphabet and boxing them using `<\`
```
<\ u: 65 + i.5 NB. truncated again
โโโฌโโโฌโโโโฌโโโโโฌโโโโโโ
โAโABโABCโABCDโABCDEโ
โโโดโโโดโโโโดโโโโโดโโโโโโ
```
### The padding
We need to pad the alphabet with 12, 12, 11, 11, etc. spaces. So first we construct this range using `i.` with a negative argument (which makes it go from that value minus 1 to 0, descending).
```
i. _13
12 11 10 9 8 7 6 5 4 3 2 1 0
```
We then copy each value twice
```
2 # i. _13
12 12 11 11 10 10 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 0 0
```
And then copy the space character as many times as specified, boxing it because J would pad the matrix with spaces to fill otherwise.
```
'*' #"0~ 2 # i. _5 NB. truncated, and using '*' so you can see the output
****
****
***
***
**
**
*
*
NB. This line is empty
NB. This line is empty, too
```
### Getting the output
Then we just join the two together using `,` (unboxing first using `&>`) and write to STDOUT using `echo`. There's nothing to show here since it's just the output.
[Answer]
# Excel (VBA), ~~129~~ 82 bytes
Using Immediate Window.ย ~~and cell `[A1]` as output.~~
```
For x=25to 0Step -1:For y=x to 25:b=b &Chr(65+y-x):Next:?Space(x/2.01)&b:b="":Next
```
[Answer]
# [Perl 5](https://www.perl.org/), 32 bytes
```
say$"x(13-++$k/2),A..$_ for A..Z
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVJFqULD0FhXW1slW99IU8dRT08lXiEtv0gByIr6//9ffkFJZn5e8X9dX1M9A0MDAA "Perl 5 โ Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
รAJโHUโถแบลผยนฦคY
```
[Try it online!](https://tio.run/##AR8A4P9qZWxsef//w5hBSuKAmUhV4oG24bqLxbzCucakWf// "Jelly โ Try It Online")
Uses code very similar to the linked question (further evidence that it is most likely a dupe).
-3 bytes thanks to FlipTack and Jonathan Allan (though indirectly)
## Old version, 15 bytes
```
12Rx2UโถแบลผรAยนฦคยคY
```
[Try it online!](https://tio.run/##ASEA3v9qZWxsef//MTJSeDJV4oG24bqLxbzDmEHCucakwqRZ//8 "Jelly โ Try It Online")
[Answer]
# C, ~~84~~ 81 bytes
*Thanks to @ceilingcat for saving three bytes!*
```
f(i,j){for(i=1;i++<27;puts(""))for(j=51;j<63-~i/2;)putchar(j++<64-i/2?32:j+i/2);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI1MnS7M6Lb9II9PW0DpTW9vGyNy6oLSkWENJSVMTJJ5la2ponWVjZqxbl6lvZK0JlEzOSASKA9WamegCxeyNjayytIEMTeva/5l5JQq5iZl5Gppc1VwKQJCmoWnNVfsfAA)
**Unrolled:**
```
f(i, j) // Using the argument list only to declare the variables.
{
for (i=1; i++<27; puts(""))
for (j=51; j<63-~i/2;)
putchar(j++<64-i/2 ? 32 : j+i/2);
}
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 6 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
รธ๏ผบ๏ผปโ๏ฝ๏ฝ
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JUY4JXVGRjNBJXVGRjNCJXUyMjE0JXVGRjVEJXVGRjUy,v=8)
] |
[Question]
[
## Goal
Your goal is to find the *simplest* value in an open interval. In other words, given two values `a,b` with `a<b`, output the simplest `x` with `a<x<b`. This is a code golf, so fewest bytes wins.
## Simplicity
All values in this problem are [dyadic rationals](http://en.wikipedia.org/wiki/Dyadic_rational), which means their binary expansions are finite, or equivalently, are rationals in simplest form `a/2^b` for some integer `a` and non-negative integer `b`. Integers are dyadic rationals with `b=0`.
Being *simpler* means having smaller `b`, tiebroken by smaller absolute value `|a|`.
Equivalently in terms of binary expansions, to find the simpler number:
1. Take the one with a shorter fractional part (fewer binary digits after the point).
2. In case of tie, take the lexicographically earlier one with length the primary sort, ignoring sign.
So, the numbers in simplicity order are
```
0, ยฑ1, ยฑ2, ยฑ3, ยฑ4, ...
ยฑ1/2, ยฑ3/2, ยฑ5/2, ...
ยฑ1/4, ยฑ3/4, ยฑ5/4, ...
ยฑ1/8, ยฑ3/8, ...
ยฑ1/16, ...
...
```
There's no need to say which of `ยฑx` is simpler because any interval that contains both candidates also contains `0`, which is simpler than both.
(A bit of background and motivation: In [combinatorial game theory](http://en.wikipedia.org/wiki/Combinatorial_game_theory), positions in a two-player games have a numerical value representing magnitude of advantage, with the sign saying which player is favored. This value is determined recursively from the two values resulting from the best move of each player. You might guess that one averages them, but in fact it's the simplest value in between.)
## Program requirements
Write, in as few bytes as possible, a *program* or *named function* that takes two dyadic rationals `a,b` and outputs the simplest dyadic rational `x` with `a<x<b`. Input can be function input or STDIN, and output can be function return or printing.
**Input format**
Two dyadic rationals `a,b` in whatever type your languages use for real or finite-precision binary values (float, double, etc). Fraction or rational types that store the value as a numerator and denominator are not acceptable. If you language has no valid type (and only then), you may use binary strings like `101.1101`, or post a comment and we'll work something out.
You are guaranteed that `a,b` are dyadic rationals and `a<b`. Integer values will be given like `3.0`, not `3`.
You can assume you have sufficient precision to store the values, the output, and any intermediate steps exactly. So, you shouldn't worry about precision or overflows. I won't give an explicit bound on inputs, but your algorithm should take a reasonable amount of time on inputs like the test cases.
You may take your two numbers in any reasonable built-in container like pair, tuple, list, array, or set. Structures specifically representing intervals are not allowed though.
**Output**
The simplest dyadic rational strictly between `a` and `b`. The same rules for the input types apply, except outputting `3` rather than `3.0` is OK.
**Test cases**
```
(-1.0, 1.0)
0.0
(0.0, 2.0)
1.0
(0.0, 4.0)
1.0
(0.5, 2.0)
1.0
(-3.25, -2.5)
-3.0
(-4, 1.375)
0.0
(4.5, 4.625)
4.5625
(-1.875, -1.5)
-1.75
```
[Answer]
# Python 2 - 100
I think I revised my entire method for this answer a good 4 or 5 times (which is probably an indication that it's a good code-golf question). I don't know if this answer can be golfed down any more but I do feel as if I'm missing some more clever methodological ways to shorten this.
```
def f(a,b,i=1.):
r=0if a<0 else(a*i+1)//1/i
return-f(-b,-a,i)if b<=0 else r if r<b else f(a,b,i*2)
```
[Answer]
# Haskell, ~~61~~ ~~88~~ ~~75~~ 73
```
p!q|p<0= -(-q)!(-p)|r<q=max r 0|0<1=(2*p)!(2*q)/2where r=toEnum$floor$p+1
```
this checks if there is a whole number between the two, and if yes, return the smallest one. if not, multiply the numbers by 2, apply them recursively, divide by 2 and return.
at least, this is how it works in my mind. the actual code is a bit different.
thanks to xnor for his rounding magic
[Answer]
## Java - ~~157~~ ~~187~~ 186
Probably could be golfed more.
Thanks to Quincunx for a byte.
```
void f(float a,float b){for(float i=1,d;;i*=2){for(d=0;d<i*Math.max(Math.abs(b),Math.abs(a));d++){for(float x:new float[]{d/i,-d/i}){if(x<b&&x>a){System.out.print(x);System.exit(0);}}}}}
```
Brute forces all values of the numerator (positive and negative) while the denominator doubles each time.
[Answer]
# Perl (89)
most probably this can still be golfed
```
sub S{($q,$w)=@_;$m=1,$r=0;until($q<$r&&$r<$w){$r=int$q+1;$r<$w||map$_*=2,$m,$q,$w}$r/$m}
```
[Answer]
## Python 3: 80 bytes
```
g=lambda a,b:-g(-b,-a)if b<=0 else int(a+1)*(a>=0)if-~int(a)<b else g(2*a,2*b)/2
```
Ungofed:
```
def g(a,b):
if b<=0:return -g(-b,-a)
if int(a+1)<b:return int(a+1)*(a>=0)
return g(2*a,2*b)/2
```
Can probably be golfed more by changing the `if/else` structure to `and/or`. The obvious transformation fails due to non-short-circuiting on the Falsey output of `0`, but there's likely a rearrangement that does it.
The space in `b<=0 else` can't be removed as usual because the start letter `e` is parsed as part of number literals like `1e6`.
[Answer]
# ES6, ~~68~~ ~~67~~ 59
```
g=(a,b)=>(x=~~(a+1),b>0?x<b?x*(x>0):g(2*a,2*b)/2:-g(-b,-a))
```
this is a port of xnor's solution (basically, the new thing in it was that it checked for having `0` in the range by `*(a>=0)`. couldn't do this in Haskell because Haskell has a type system :) )
this is the first time I used ES6 ever, so this might still be golfable.
[Answer]
# C, 98 bytes
Using a recursive algorithm (and the fact that f(a,b) = f(2\*a,2\*b)/2).
I also removed some bugs. The right answer is:
```
float n(float a, float b){return (floor(a+1)<ceil(b))?(a<0?(b>0?0:ceil(b-1)):floor(a+1)):n(2*a,2*b)/2;}
```
Which, to meet the prerequisites, is 19 bytes longer than the original one (of 79 bytes)
Full code:
```
#include <stdio.h>
#include <math.h>
float n(float a, float b){return (floor(a+1)<ceil(b))?(a<0?(b>0?0:ceil(b-1)):floor(a+1)):n(2*a,2*b)/2;}
main()
{
float a = -4.0;
float b = -1.4;
printf("%f",n(a,b));
}
```
Just copy-paste it into [a random online c compiler](http://www.compileonline.com/compile_c_online.php) and run it.
] |
[Question]
[
**Input** 5 integers: Landmark `X` & `Y`, Starting Point `X` & `Y`, and View Distance Radius `D`
**Output** 1 double: % chance of coming within `D` of Landmark (`X`,`Y`) ("seeing") when walking straight in a random direction from Starting Point (`X`,`Y`).
Assume that "random direction" shall be a direction uniform on [0,2ฯ], the land is flat, and of course the 'hiker' never turns after he begins moving.
**Example:** If landmark is at (10,10), starting point is (5,5), and view distance is 20 then the output would be 100% as no matter which direction you walk the landmark will be immediately visible.
[Answer]
# Haskell, ~~65~~ 63
```
import Data.Complex
(s,l)%d=100*min(asin(d/magnitude(s-l))/pi)1
```
Use like `(xstart:+ystart, xlandmark:+ylandmark) % distance`. Gives result in percent. Why is it so expensive to load modules in Haskell?!?
Note that there is no if/then/else, pattern matching, etc. in this code, `min` does the magic.
[Answer]
## CJam *-41* *-40* *-39* *-38/35* **31/26**
This seems to work. It is my first attempt at CJam and/or codegolf. Run the code at <http://cjam.aditsu.net/>. In the section called input just place the variables as integers delimited with spaces in the input block in this order: distance D, landmark x, starting x, landmark y, starting y (for example 20 10 5 10 5). I had posted a previous one based on a misunderstanding of the equation that has been resolved. I also had been returning answers as probability ratios rather than percentages. **Note: the second code has only 31 characters** but combines alot from another user's CJam code.
```
ri{riri- 2#}:U;UU+.5#/mSP/:A.5<A1?e2
r{~riri-_*}_~+mq/mSP/:A.5<A1?e2
```
Accuratish one without arcsine being directly called (44 characters):
```
ririri- 2#riri- 2#+ .5#/:A1<AA3#6/+P/1?100*
```
Even more accurate (52 characters):
```
ririri- 2#riri- 2#+ .5#/:A1<AA3#6/+A5#40/3*+P/1?100
```
Update:
The absolute best I've written is 26 characters. I've still learned alot by watching professorfish's attempts but the crux is mine. I assumes (potentially incorrectly) that if you can see the landmark if it is closer (not closer than or equal to) your sight radius.
```
1r{~riri-_*}_~+mq/mSP/e<e2
```
[Answer]
# CJam, ~~44 40 38~~ 37
First CJam script! Uses the method [on the Math.SE answer here](https://math.stackexchange.com/questions/876462/calculation-for-the-chance-of-finding-something-a-given-distance-from-a-starting/876580#876580).
Supports non-integer inputs as well, at no extra character cost.
```
rd{rdrd-_*}:U~U+mq/_1<{mSP/}{;1}?100*
```
[Interpreter at cjam.aditsu.net](http://cjam.aditsu.net).
## Order of inputs
The inputs are given in this order, on STDIN, separated by spaces:
1. View Distance Radius
2. Landmark X
3. Starting Point X
4. Landmark Y
5. Starting Point Y
[Answer]
# Haskell โ ~~72 70 69~~ 68
I think this satisfies the question, but if not please leave a comment and I'll do my best to fix it:
```
w s y l z d|r<d=100|0<1=asin(d/r)/pi*100where r=sqrt$(l-s)^2+(z-y)^2
```
[Answer]
# Python - 73
```
from math import*
f=lambda l,s,d:(abs(l-s)<=d or asin(d/abs(l-s))/pi)*100
```
`l` is a complex number (e.g. `5 + 5j`) describing the landmark position, `s` describes the start position and `d` is the view distance, for the example from the question call `f` as follows: `f(5 + 5j, 10 + 10j, 20)`
] |
[Question]
[
**Puzzle:** Find a deck of *c* cards, each containing *p* pictures, such that no two pictures match on a given card, and exactly 1 picture on each card matches exactly 1 picture on each of the other cards, where the number of unique pictures in the deck is minimized.
**Criteria:** Fastest code for *c* = 31 and *p* = 6.
**Inspiration:** This puzzle was inspired by wondering how the makers of the card game [Spot It!](http://www.blueorangegames.com/spotit/) came up with a deck of cards that differ from each other by only one picture. If it helps, the game's instructions say it contains 31 cards with at least 30 unique pictures.
**Brute-force reference implementation:** (Entirely impractical for use at the scale of the contest judging criteria, but perhaps useful for thinking about the problem.)
```
class Program
{
const int CardCount = 31, PicturesPerCard = 6;
static void Main()
{
for (int pictureLimit = PicturesPerCard; ; ++pictureLimit)
new Solver(pictureLimit).FindValidCards(0, 0);
}
class Solver
{
readonly byte[,] cards = new byte[CardCount, PicturesPerCard];
readonly int pictureLimit;
public Solver(int pictureLimit)
{
this.pictureLimit = pictureLimit;
}
public void FindValidCards(int c, int p)
{
for (; c < CardCount; ++c) {
for (; p < PicturesPerCard; ++p) {
for (int picture = p == 0 ? 0 : cards[c, p - 1] + 1; picture < pictureLimit; ++picture) { // Only consider pictures in numerically increasing sequence, since sequence order is irrelevant.
cards[c, p] = (byte)picture;
if (p < PicturesPerCard - 1) {
FindValidCards(c, p + 1);
} else if (c < CardCount - 1) {
FindValidCards(c + 1, 0);
} else if (AreCardsValid()) {
WriteCards();
System.Environment.Exit(0);
}
}
}
}
}
bool AreCardsValid()
{
for (int c = 0; c < CardCount; ++c)
for (int otherC = c + 1; otherC < CardCount; ++otherC) {
int matchCount = 0;
for (int p = 0; p < PicturesPerCard; ++p)
for (int otherP = 0; otherP < PicturesPerCard; ++otherP)
if (cards[c, p] == cards[otherC, otherP])
++matchCount;
if (matchCount != 1)
return false;
}
return true;
}
/// <summary>
/// Writes to the console all the cards with each unique picture placed in its own column for easier comparison between cards.
/// </summary>
void WriteCards()
{
for (int c = 0; c < CardCount; ++c) {
string cardString = string.Empty;
for (int picture = 0; picture < pictureLimit; ++picture)
for (int p = 0; ; ++p) {
if (p == PicturesPerCard) {
cardString += ' ';
break;
}
if (cards[c, p] == picture) {
cardString += (char)(picture < 26 ? 'A' + picture : 'a' + (picture - 26));
break;
}
}
System.Console.WriteLine(cardString);
}
}
}
}
```
**Edits:** Reworded puzzle to correctly articulate the intent that the goal is to find a deck that matches the constraints. Added the missing constraint that no two pictures on a card may match. Changed contest type from code golf to speed.
[Answer]
This should be a comment rather than an answer, but it's not going to fit in a comment.
One way of looking at this problem is to flip it around:
>
> Given that you have `N` distinct pictures, what's the largest deck of cards you can build each of which has `n` distinct pictures such that the intersection of any two cards is precisely one picture?
>
>
>
Another way of phrasing this flipped-round problem is:
>
> What is the maximal size of binary code of length `N`, constant weight `n` and exact pairwise Hamming distance `2(n-1)`?
>
>
>
This is bounded by the maximal size of binary codes of length `N`, constant weight `n`, and *minimal* Hamming distance `2(n-1)`. The best resource for such bounds appears to be <http://www.win.tue.nl/~aeb/codes/Andw.html> although some values here are extracted from OEIS (specifically [A001839](http://oeis.org/A001839)).
```
N \ n 0 1 2 3 4 5 6 7 8 9
0 1 - - - - - - - - -
1 1 1 - - - - - - - -
2 1 1 1 - - - - - - -
3 1 1 3 1 - - - - - -
4 1 1 3 1 1 - - - - -
5 1 1 4 2 1 1 - - - -
6 1 1 5 4 1 1 1 - - -
7 1 1 6 7 2 1 1 1 - -
8 1 1 7 8 2 1 1 1 1 -
9 1 1 8 12 3 2 1 1 1 1
10 1 1 9 13 5 2 1 1 1 1
11 1 1 10 17 6 2 2 1 1 1
12 1 1 11 20 9 3 2 1 1 1
13 1 1 12 26 13 3 2 2 1 1
14 1 1 13 28 14 4 2 2 1 1
15 1 1 14 35 15 6 3 2 2 1
16 1 1 15 37 20 6 3 2 2 1
17 1 1 16 44 20 7 3 2 2 2
18 1 1 17 48 22 9 4 3 2 2
19 1 1 18 57 25 12 4 3 2 2
20 1 1 19 60 30 16 5 3 2 2
21 1 1 20 70 31 21 7 3 3 2
22 1 1 21 73 37 21 7 4 3 2
23 1 1 22 83 40 23 8 4 3 2
24 1 1 23 88 42 24 9 4 3 3
25 1 1 24 100 50 30 10 5 3 3
26 1 1 25 104 52 30 13 5 4 3
27 1 1 26 117 54 31 14 6 4 3
28 1 1 27 121 63 33 16 8 4 3
29 1 1 28 134 65 ? 20 8 4 3
30 1 1 29 140 ? ? 25 9 5 4
31 1 1 30 155 ? ? 31 9 5 4
32 1 1 31 160 ? ? 31 10 5 4
```
There are some easy to prove properties, but from what I've read so far it seems that in general there's no better method known than brute force.
Note that for `n > 2` these bounds appear to be loose for `N > n^2 - n + 1` (certainly they are for the values of `n` in the table above), and tight for `N <= n^2 - n + 1`.
One useful result which handles the case that most interests you is as follows. (I could also write some code to wrap this up by using special cases and falling back to brute force, but I don't see the point).
>
> If `N = n^2 - n + 1` then there is a nicely structured deck of `N` cards satisfying the required property.
>
>
>
The construction is quite simple:
```
(-1,-1) (x,0) (x,1) ... (x,n-2) for x in 0..n-1
(0,y) (1,y+z % n-1) ... (n-1, y+(n-1)z % n-1) for y in 0..n-2, z in 0..n-2
```
Each element appears in precisely `n` cards, which makes it optimal for decks in which more than one picture repeats.
Call the most frequent picture (selecting arbitrarily in case of a tie) `f`.
### Lemma 1
>
> If `f` appears in more than `n` cards then it must appear in every card, and no other element repeats.
>
>
>
Proof: because each pairwise intersection contains precisely one element, all of the other elements in the cards containing `f` must be distinct. But then a card which doesn't contain `f` must have a non-trivial intersection with more than `n` disjoint sets despite having only `n` elements, which is impossible.
### Corollary
>
> The largest possible deck in which `f` appears in more than `n` cards has size `floor((N-1) / (n-1))`
>
>
>
Excluding `f` from the `N` available pictures we get `N-1` from which to draw disjoint sets of size `n-1` to complete each card.
### Lemma 2
>
> Any deck in which `f` appears in no more than `n` cards has at most `n^2 - n + 1` cards.
>
>
>
Consider an arbitrary card containing `f`. By definition of `f`, none of the `n` elements of that card appears in more than `n` cards, and since each appears in that card the number of other cards is no more than `n(n-1)`. Hence the deck cannot be larger than `n(n-1) + 1`.
### Theorem
>
> The largest possible deck has an upper bound of `max(n^2 - n + 1, floor((N-1) / (n-1)))`.
>
>
>
By combining the corollary and lemma 2.
[Answer]
Because I view this question as primarily a challenge question, I'll describe how an approach can be developed. I'll present the code in ungolfed format in the hopes that it might shed light on how the solution was constructed. Perhaps I'll add a golfed version later.
Throughout I'll illustrate using the example of the deck of 7 cards, each having 3 pictures on it.
### Complete Graph
Whatever the size of the deck, the problem calls for a complete graph. If each vertex or node in the graph represents a distinct card from the deck, there should be a single link or edge between each vertex. This corresponds to the constraint that any pair of cards shares a single picture.

### Adjacency Matrix
Another way to express this it through an adjacency matrix. Rows and Columns correspond to cards. A cell (i,j) with a 1 in it indicates that card i has one picture in common with card j. No cells can contain an integer greater than 1 (that would mean that cards i and j share more than one picture). The diagonal consists of zeros; there are no links from a card to itself.

### Which pictures are in each card?
Below we include additional information that was not in the above diagrams. And in fact this is not the only possible solution. Even if you accept that this constitutes one viable deck of 7 cards and 7 pictures, we might have stumbled upon it by chance. We need an approach that will work for any number of pictures and cards.

### Filling in the Complete Graph
We may as well use the preceding picture to fill in information in the complete graph.
Remember, we haven't solved anything. We're merely explore different ways of thinking about a specific solution, once found.

### Matrix of Cards by Pictures
Let's represent the above illustration in a another matrix. This time, the rows represent cards; the columns represent pictures.

Reading the first row, we see that card 1 contains picture 1, picture 2, and picture 3.
Card 2 contains picture 1 (the picture in common between cards 1 and 2), as well as pictures 4 and 5. And so on.
By studying the distribution of pictures to cards (where the 1's appear in the matrix) we can identify a procedure that will guarantee a full deck. (Be sure to see Peter Taylor's analysis of why *a* pictures per card can produce a maximum deck of *a*(โ*a*โ-1)+1 cards using a total of *a*(โ*a*โ-1)+1 pictures.) In the example, 3 pictures per card suffice to make a deck of 7 cards.
### Steps for making a deck of Spot It! cards.
1. Choose how many pictures per card, *a*. Your deck will have c=*a*(โ*a*โ-1)+1 cards.
2. Make a *c* by *c* null matrix (all zeros). The rows will represent cards. The columns will represent pictures.
3. We will arbitrarily proceed row by row, left to right. We need to distribute three 1's to each row (three distinct pictures per card) such that: (a) there is **at most** one picture from the present card's row that matches a picture from any other card's row and (b) at most *a* copies of picture will be used in the deck. Because of how *a* and *c* were set, It automatically turns out that the proper number of pictures per card will result. (If you desire a slightly smaller deck, simply remove the extra cards. Any one is as good as the other.)
### Code in Mathematica (ungolfed)
```
deck[picsPerCard_]:=
Module[{pics=picsPerCard (picsPerCard-1)+1,cards,matrix,linked,elegible},
(*pics not really needed, but it helps distinguish columns from rows *)
cards=pics;
(*the null matrix *)
matrix=ConstantArray[0,{cards,pics}];
(* cards considered already linked; hence the cell under consideration will not be
elegible for receiving a 1.*)
linked[m_,row1_,row2_]:=row1==row2\[Or]Tr[m[[row1]] m[[row2]]]>0;
(*Checks whether cell (r,c) is elegible for receiving card c *)
elegible[m_,{r_,c_},ppc_]:=Tr[m[[r]]]<ppc\[And](m[[r,c]]==0)\[And]
(Length[(f=Flatten[Position[matrix\[Transpose][[c]],1]])]<ppc)\[And]\[Not]
(Or@@(linked[matrix,r,#]&/@f));
(* Fill in with 1's all elegible cells. Proceed row by row, i.e. card by card *)
Do[If[elegible[matrix,{i,j},picsPerCard], matrix=ReplacePart[matrix,{i,j}->1]],
{i,cards},{j,pics}];
(*return the solution matrix *)
matrix]
```
Examples:
```
deck[3] // MatrixForm
```
>
> 
>
>
>
[Answer]
This is a (correct?) C# implementation of David Carraher's algorithm. I am posting it in case it provides insight into the glitch he discovered. When run with 3 pictures per card, it provides identical output as David's solution. However, for 4 or more pictures per card, it fails for want of more unique pictures across the deck than there are cards in the deck.
**Edit:** Updated to allow creation of additional pictures as needed (so it no longer fails). Also added sample runs.
```
/// <summary>Finds a deck that solves the puzzle.</summary>
/// <returns>An array of cards, where each card is a bit vector and each bit is true only if the corresponding picture is present.</returns>
static long[] FindDeck(int picturesPerCard, out int uniquePicturesCount)
{
// Start with an initially zeroed matrix of rows of cards and columns of picture bits (bit is on if the card contains that picture).
int cardCount = picturesPerCard * (picturesPerCard - 1) + 1;
var deck = new long[cardCount];
var pictureCountsForDeck = new List<int>();
// Go through each card row, and find a valid card for that row:
for (int c = 0; c < cardCount; ++c) { // Single-letter variables are indexes.
var card = deck[c];
int pictureCountForCurrentCard = 0;
// Go through each possible picture, and turn on that picture bit if it is valid:
for (int p = 0; ; ++p) {
var proposedCard = card;
proposedCard |= 1L << p; // Sets the bit for the proposed picture to true.
// Each picture can only be used so often across the entire deck. The cap is the same as the number of pictures per card.
if (pictureCountsForDeck.Count <= p)
pictureCountsForDeck.Add(0);
if (pictureCountsForDeck[p] == picturesPerCard)
continue;
// Check whether the picture bit is valid against the previous picture cards.
for (int checkC = 0; ; ++checkC) {
// If this card has been successfully checked against all previous cards:
if (checkC == c) {
deck[c] = card = proposedCard;
++pictureCountsForDeck[p];
if (++pictureCountForCurrentCard == picturesPerCard)
goto NextCard; // All pictures found for this card. Move to the next card.
break; // Find another picture for this card.
}
// To determine that a picture proposal is invalid, show that there was a previous match or that the new set of matched pictures differs from the previous set. This indicates more than one picture matches.
var checkCard = deck[checkC];
long existingMatch = card & checkCard;
if (existingMatch != 0 && existingMatch != (proposedCard & checkCard))
break; // This picture proposal is invalid. Move on to the next picture.
}
}
NextCard: ;
}
uniquePicturesCount = pictureCountsForDeck.Count;
return deck;
}
```
The results for 4 pictures per card looks good for the square part of the matrix. However, the matrix gets sparse as columns are added:
```
1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0
0 1 0 0 1 0 0 1 0 0 1 0 0 0 0 0 0
0 1 0 0 0 1 0 0 1 0 0 1 0 0 0 0 0
0 1 0 0 0 0 1 0 0 1 0 0 1 0 0 0 0
0 0 1 0 1 0 0 0 1 0 0 0 1 0 0 0 0
0 0 1 0 0 1 0 1 0 0 0 0 0 1 0 0 0
0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0
0 0 0 1 1 0 0 0 0 1 0 1 0 0 0 0 0
0 0 0 1 0 1 0 0 0 0 1 0 0 0 0 1 0
0 0 0 1 0 0 1 1 0 0 0 0 0 0 0 0 1
```
Or is it just an anomaly at that size? The matrix is square and well filled for 5 pictures per card:
```
1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1
0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0
0 1 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0
0 1 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0
0 1 0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1
0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1
0 0 1 0 0 0 1 0 0 1 0 0 0 0 0 0 1 0 0 1 0
0 0 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0
0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 1 0 1 0 0
0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 1 0 1 0 0 0
0 0 0 1 0 0 0 1 0 1 0 0 0 0 1 0 0 0 0 0 1
0 0 0 1 0 0 0 0 1 0 1 0 0 1 0 0 0 0 0 1 0
0 0 0 0 1 1 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0
0 0 0 0 1 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 1
0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 0 1 1 0 0 0
0 0 0 0 1 0 0 0 1 1 0 0 0 0 0 1 0 0 1 0 0
```
On the other hand, at 6 pictures per card (also even), it's back to sparse again at the tail. Have we really minimized the number of unique pictures?
```
01000000100001000010000100001000000000000000000
01000000010000100001000010000100000000000000000
01000000001000010000100001000010000000000000000
00100010000010000010000010000010000000000000000
00100001000100000001000100000001000000000000000
00100000100000101000001000000000100000000000000
00100000010001000100010000000000010000000000000
00100000001000000000000000100000001110000000000
00010010000001000001001000000000001000000000000
00010001000000100010010000000000000100000000000
00010000100100000100000010000000000010000000000
00010000010010001000000100000000000001000000000
00010000001000000000000000010001110000000000000
00001010000000100100000100000000000000100000000
00001001000001001000000010000000000000010000000
00001000100010000001010000000000000000001000000
00001000010100000010001000000000000000000100000
00001000001000000000000000001000000001000011000
00000110000000010000000000010000000101000000000
00000101000000000000100000100000100000100000000
00000100100000000000000001000101001000000000000
00000100010000000000000000001000000010011000000
00000100001100000000000000000000000000000000111
```
] |
[Question]
[
## Overview
As most of y'all who visit chat know, I am Russian by ethnicity[citation not needed]. Recently, I switched from a keyboard that maps the letters 1-to-1 (mnemonic) to Windows' default mnemonic keyboard. Here are the letter mappings:
```
"`" -> "ั"
"q" -> "ั"
"w" -> "ั"
"e" -> "ะต"
"r" -> "ั"
"t" -> "ั"
"u" -> "ั"
"i" -> "ะธ"
"o" -> "ะพ"
"p" -> "ะฟ"
"a" -> "ะฐ"
"d" -> "ะด"
"f" -> "ั"
"g" -> "ะณ"
"h" -> "ั
"
"k" -> "ะบ"
"l" -> "ะป"
"'" -> "ั"
"z" -> "ะท"
"x" -> "ะถ"
"v" -> "ะฒ"
"b" -> "ะฑ"
"n" -> "ะฝ"
"m" -> "ะผ"
```
You may have notcied that s, c, y, and j are missing. This keyboard, unlike the first one I used, has several combining keys (the aforementioned ones) These keys, while also having their own letters mapped to them, can be combined with other keys in sequence to write even more letters. The combinations for those keys are as follows:
```
"sc" -> "ั"
"ch" -> "ั"
"ya" -> "ั"
"ye" -> "ั"
"yo" -> "ั"
"yu" -> "ั"
"ja" -> "ั"
"je" -> "ั"
"jo" -> "ั"
"ju" -> "ั"
```
Note that there are 3 ways to write `ั`: `q`, `ya`, and `ja`.
To type the single letters mapped to them, either press that key and then press space, or type an unrecognised key combination. Here are the single letter mappings for those keys:
```
"s" -> "ั"
"c" -> "ั"
"y" -> "ั"
"j" -> "ะน"
```
For example, if I type in `c` (note the space), it will give me `ั`, while typing in `cy` gives me `ัั`. Typing in `yosc` is `ัั`, and `yq` is `ัั`.
## The task
Your input will be given as all lowercase Russian + ASCII space, and you task is to convert that to a sequence of letters in the US keyboard I'd have to type.
## Testcases
```
"ะพะดะธะฝ" (one) -> "odin"
"ััะฐะฟััะธะดะตัััะธัััั
ัััััะฝัะน" (one hundered fifty three thousandth) -> "stapqtidesqtitryohtysqchnyj" or "stapyatidesyatitryohtysjachnyj" or any variation on the typing of "ั" or "ั"
"ะบะพะด ะณะพะปัั" (code golf) -> "kod gol'f"
"ะธะฒะฐะฝ ััะฑะธั ะดัะพะฒะฐ ะฒะพะฒะฐ ัะพะฟะธั ะฟะตัั" (Ivan is splitting wood, Vova is stoking the stove; a common mnemonic for the six noun cases) -> "ivan rubit drova vova topit pech'"
"ัะฐะทัััะตะฝะฝัะน ััะตั ัะณะพะธััะธัะฝะพ ะฑััั ะฟัััั ะถะตัะดัะผะธ ัััััะพะณะพ ัะตั
ัะพะฒะฐะปััะธะบะฐ" (An enraged narrator selfishly beats with five poles a nimble fencer; a sentence that uses all 33 Russian letters) -> "raz`yarennyj chtec jegoistichno b'yot pqt'yu xerdyami wustrogo fehtoval'scika" (note the double space after "chtec". I used a mixture of "q" and "ya" for "ั" here)
```
## Scoring
As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins.
[Answer]
# JavaScript (ES6), 106 bytes
```
s=>s.replace(/\S/g,c=>"rs tufhc chwsc`y 'yeyuq_yoabvgdexzij klmnop".match(/[scyj]?./g)[c.charCodeAt()%34])
```
[Try it online!](https://tio.run/##bY/NTsJAEMfvPsWmibFNtD3oFYzxETwi0bqUllootgWtp8qHqKCENwEFrWjhFWaeqM4uN8NlZ3Y@/v/fuGbbDHlQa0YHDb9i5dVCHhaKoR5YTc/klmqcnxn2Pi8UlSBkUavqcMad25BfxmwvtuLWzUXsm1dtu2Ld3ddcdu3VG35T0etmxB3VKIU8dsvHumFrJa5zxwxOyeQkUrXdw6OylnO/EfqepXu@rVZVBVYwhxQyRdN2/rXwATswhTWOKaY0tqCKzLGDCU6wT3EoawPIcAjfW0RgKRwYfFD4wRH2ts2k8E5GGSPVLsyEPoM5JrRCdUbPJiHrFaw37TXRDHC0DTshrS98IawEFpBt0BhNd2jnkeGrhEnlealAhxWDGbFNpLA4kT5vDD5pPiGQMfxCyvAJu2JHcpECwx71@xJK4IvrnumUJUyJKv8D "JavaScript (Node.js) โ Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 159 bytes
```
ั
sc
ั
ch
ั
yo
ั
yu
ั
je
ั
ju
T`ัััั`scyj`ั[^ scyjั]|ั[^ scyjั
]|[ะนั][^ scyjะฐะตะพั]
[ัััั]
$&
T`ะฐ-ััั-ัั`abvg\dexzi-pr-uf\hc\w\`y'q
```
[Try it online!](https://tio.run/##NVDNVoJQEN7PU9xFp1a8TTuhg5GlLPrRqOi4IFRM8ef4JlhaaIGvMPNE9N1LbpiZb@b7uXRbj53bZlXJhHoeyZi8NsmKwjuSBYUByZz8lu79gM5deZNEUkndnhf6mBoXSneSOH1JjsPI6Td4J6nzD3DGWy5l4FDjyHfo5FRBjzMLwLtMLZnJ0m1ePt3YV62X145137WCa7vt2c@2G549VBWXvOGcC4JGDMmDLFFzgFsgppdYIlnJCDU12JgLSXlHvNdsxZ8oP3AaEogfECkUGANea67ijUQ4AK7wqRvIlnyo1wc4jWVGuMr4W6YwiPCyojZR2MW4SJTMjVFuguY6BJeK1/BdGRkdFsNC8RfuI9gu@Zdzhf8w0ByTAgpKhtiPTAQdViefIPiesz8 "Retina 0.8.2 โ Try It Online") Link includes test cases. Explanation:
```
ั
sc
ั
ch
ั
yo
ั
yu
ั
je
ั
ju
```
Translate the digraphs.
```
T`ัััั`scyj`ั[^ scyjั]|ั[^ scyjั
]|[ะนั][^ scyjะฐะตะพั]
```
Transliterate any unrecognised pairs starting with `s`, `c`, `y` or `j`.
```
[ัััั]
$&
```
Insert spaces after any other letter that maps to `s`, `c`, `y` or `j`.
```
T`ะฐ-ััั-ัั`abvg\dexzi-pr-uf\hc\w\`y'q
```
Transliterate the rest of the Russian letters.
[Answer]
# [Python](https://www.python.org), 125 bytes
```
lambda s:re.sub('\S',lambda c:re.findall("[scyj]?.","rs tufhc chwsc`y 'yeyuq_yoabvgdexzij klmnop")[ord(c[0])%34],s)
import re
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VZDLTsJAFIbjlqeYNDG0CRoTXRgT49q1SyBaepFiobUXtSYmlYuooIS1GxKja1DQihZe4ZylPo1nWmPCZs7Mf_755zvz8GwHXtmqDR717cKT7-krm98XplwtqTJztxxt1fVLYrawl839iQoXdaOmyqYpCnlXCSrFnVUhJzgu83y9rDClfOoqBwHLBlrgH-8Hllw6OVS1s3Ojwo7Mas2yBSlvOaqo5NeK0vL6RjHnShmjaluOxxwthfhZ2rUdo-aJuijADMYQQSxIUuZfxEuswxDm2KMakWFCSrLHOobYxxbVTqK1IcYOfCxchylPZfBK5RO72FzsRvBC4TGjpAaMeCaDMYZkJp3Rkm7ouRnM0_acCNrYXYQMKeUdbwkihAnEKQgjX53cVwzvEoAoGSbioDBjMCKefhLJB6LDPYM38oeE0IMviBheY4PfSYgogWGT-q0Eh4PziW5oiCkMiSf90cEgrb8)
Port of Arnauld's JS answer.
] |
[Question]
[
Given an input of a string, output the partial fraction in string form.
The partial fraction decomposition of a rational fraction of the form \$\frac{f(x)}{g(x)}\$, where \$f\$ and \$g\$ are polynomials, is its expression as:
$$\frac{f(x)}{g(x)}=p(x)+\sum\_j\frac{f\_j(x)}{g\_j(x)}$$
In this case \$p\$ is 0, because we assume that the numerator is smaller than the denominator.
### Input:
In the form of an a list of the coefficients:
```
[[1, 4], [[1,3], [1,3]]]
```
For `(x+4)/(x+3)^2`.
### Output:
In the form of a list too:
```
[[[1], [1, 3]], [[1], [1, 6, 9]]]
```
For `1/(x+3) + 1/(x+3)^2`.
### Assumptions
* The power of - `x^` can be of any power greater than 1
* The fractions are **factorised whenever possible**
* You can output the elements of a list or the list itself
* You can take the input as a list or separate elements
* The numerator highest degree is always lower than the denominator highest degree
* You can take the input and output in any order
* The input will not be in a way such that the numerator and denominator have a factor in common
* You can assume all inputs take this form:
$$\frac{something}{(something)(something)(...)}$$
* Note there can be multiple fractions e.g.:
$$\frac{x+4}{(x+1)(x-2)(x+3)^2}$$
## Note:
~~This is **not** as easy as it looks~~ This only gets harder. There are multiple cases to follow:
1. Linear factors
$$\frac{N(x)}{(ax+b)(cx+d)}=\frac{A}{ax+b}+\frac{B}{cx+d}$$
2. Repeated linear factors
$$\frac{N(x)}{(ax+b)^2}=\frac{A}{ax+b}+\frac{B}{(ax+b)^2}$$
3. Quadratic factor (non-factorisable)
$$\frac{N(x)}{(ax+b)(x^2+bx+c)}=\frac{A}{ax+b}+\frac{Bx+C}{x^2+bx+c}$$
### Testcases
```
Case 1:
[1,4], [[1,3], [1,2]] -> [[-1], [1,3]], [[2], [1,2]]
```
$$\frac{x+4}{(x+3)(x+2)}=\frac{-1}{x+3}+\frac{2}{x+2}$$
```
Case 2:
[1,4], [[1,3], [1,3]] -> [[1], [1,3]], [[1], [[1,3], [1,3]]]
```
$$\frac{x+4}{(x+3)^2}=\frac{1}{x+3}+\frac{1}{(x+3)^2}$$
```
Case 3:
[2,-1,4], [[1,0], [1,0,4]] -> [[1], [1,0]], [[1,-1], [1,0,4]]
```
$$\frac{2x^2-x+4}{x(x^2+4)}=\frac{1}{x}+\frac{x-1}{x^2+4}$$
[Answer]
# Python3, 1029 bytes:
```
import itertools as I
E=enumerate
U=lambda x:{len(x)-i:a for i,a in E(x,1)}
def G(v,r=[]):
if[]==v:yield r;return
for k in I.product(*[[-1,0,1]for _ in v[0]]):
N=[a+b for a,b in zip(v[0],k)]
if N[0]:yield from G(v[1:],r+[N])
else:yield from G(v[1:],r+[[-1]+N[1:]])
def P(p):
if[]==p:return{0:1}
s=U(p[0])
for e in p[1:]:
n={}
for i,a in E(e,1):
for A in s:n[A+len(e)-i]=n.get(A+len(e)-i,0)+s[A]*a
s=n
return s
T=lambda x:P([eval(i)for j,k in x for i in[j]*k])
H=lambda n,N:[1]+[0]*(max(n)-max(N))
def f(n,d):
S,D,M={*map(str,d)},[],{}
for i in S:Y=d.count(eval(i));D+=[(i,Y)]+[(i,1)]*(Y>1 and len(S)==1);M[i]=max(Y,M.get(i,0))
N=U(n);q,O=[[(a,b,t:=T([(j,M[j])for j in{*M}-{a}]+[(a,M[a]-b)]*(M[a]-b>0)),H(N,t))for a,b in D]],[]
while q:
a=q.pop(0)
O+=[a]
r={}
for *_,p,o in a:
for A,B in P([[*p.values()],o]).items():r[A]=r.get(A,0)+B
if r==N:return[[i[-1],[eval(i[0])]*int(i[1])]for i in a]
for i in G([j[-1]for j in a]):
v=[(A,B,C,z)for (A,B,C,_),z in zip(a,i)]
if v not in O:q+=[v]
```
[Try it online!](https://tio.run/##dVNNT@MwEL3nV/hop9OqgT2sUhkJFgQcGlYCDpVlIZe6i0vrGCftFqr@9u5M0tLlwMmeL897b8bhvX4p/enPEHc7twhlrJmrbazLcl4xU7Hb5Epav1zYaGqbPMq5WYwnhq3zzdx6vhZdlxs2LSNzYJjz7IqvIRPbZGKn7JqvIEqlRZ4wN1VaylX@7ux8wuIg2noZfdKUvlLhbS/EcrJ8rnmqVDeDPmSagk8UXKm@bp5hhVSmM27KDIwp9uECpzi8Co0JbsoKtPaNprFcEA6V5RpiRxVaYI6dV/abBGytOwVZmEkkfvNwxB/yFvemn2fbhFXykQdsJloeluAEqiWkXm4w5as2FrWhWOM9J1@Ve3XeIS0taqml7/2xNT96oC86lTrXqcGySqJiLQJWJQ/HYfzmyq7MnDtBD8@gUXTd9sarmun0FVHeHCo8FLlCoog95Quz5l506ShES3rKPUwI6T1cwlBu0oUJvKojOregNBCzw@PsPh/JSe@5XPqa71GIwWVHKu5gJLAJnpnARqOzjBk/YcTtXkiZicFQIWfqPIJhw5wIo5wFKuvF4A3upFIcJw11Lh@44jMYIpuWJjbfpMNtd2O21MVgyOjumFq1tzN8C254AbUQ/23MpdZIImF/X9zcsjcaiJFvvVAG3qf1uEPshnYpHkeYPkGAkqrNcYBwQQ4UX6Whh8yXtuJCQ6lFDz/RAo084uxkbIdKs7xoVzRKWex3SSlHSwf7CdI66dShlg4nJPSnzA2iT@uaqxmVHYTAcLtZK9QdgcEv@Gg4740nAR@H32LANV@FgKyYL2sK3OVvSHuldyFS8ylXGfzQwBSep3RmcIJ/QiTfx0@/xk@ge0zptyl9dGDS7h8)
[Answer]
# Mathematica, 124 bytes
```
#~CoefficientList~x&/@{Numerator@#,Denominator@#}&/@List@@Apart[First@#~FromDigits~x/Fold[Times,(#~FromDigits~x&)/@Last@#]]&
```
[View it on Wolfram Cloud!](https://www.wolframcloud.com/obj/35dad498-0c80-4233-8ba2-cddd232ad6bc)
`Apart` does the heavy lifting here. The rest of the code allows it to work on the specified input and output format.
] |
[Question]
[
Adapted from [Tips for restricted source in Python](https://codegolf.stackexchange.com/questions/209734/tips-for-restricted-source-in-python)
---
Just like [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") pushes one to exploit quirks and hidden features of the [Powershell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) language. Now, We already have [a place](https://codegolf.stackexchange.com/questions/191/tips-for-golfing-in-powershell) to collect all these [tips](/questions/tagged/tips "show questions tagged 'tips'") for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), those for [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") remain transmitted by word of mouth or hidden deep within the [Powershell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) documentation.
Let's collaborate on this thread to gather the tips for [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") in [Powershell](https://github.com/TryItOnline/TioSetup/wiki/Powershell)!
Please only include 1 tip per answer.
---
## What makes a good tip here?
There are a couple of criteria I think a good tip should have:
1. It should be (somewhat) non obvious.
Similar to the [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") tips it should be something that someone who has golfed in python a bit and read the tips page would not immediately think of. For example "Replace `a + b` with `a+b` to avoid using spaces", is obvious to any golfer since it is already a way to make your code shorter and thus not a good tip.
2. It should not be too specific.
Since there are many different types of source restrictions, answers here should be at least somewhat applicable to multiple source restrictions, or one common source restriction. For example tips of the form **How to X without using character(s) Y** are generally useful since banned characters is a common source restriction. The thing your tip helps to do should also be somewhat general. For example tips of the form **How to create numbers with X restriction** are useful since many programs utilize numbers regardless of the challenge. Tips of the form **How to implement Shor's algorithm with X restriction** are basically just answers to a challenge you just invented and not very helpful to people solving other challenges.
[Answer]
# Alternatives To Single And Double Quotes
```
{A} #Normal Curly Braces; This makes a scriptblock, but the ToString prints the contents
โBโ # Left Single Quotation Mark 0x2018
โCโ # Right Single Quotation Mark 0x2019
โDโ # Single Low-9 Quotation Mark 0x201a
โEโ # Single High-Reversed-9 Quotation Mark 0x201b
โFโ # Left Double Quotation Mark 0x201c
โGโ # Right Double Quotation Mark 0x201d
โHโ # Double Low Quotation Mark 0x201E
```
```
PS C:\> {A}
A
PS C:\> โBโ
B
PS C:\> โCโ
C
PS C:\> โDโ
D
PS C:\> โEโ
E
PS C:\> โFโ
F
PS C:\> โGโ
G
PS C:\> โHโ
H
```
Yes, these work! But What's better? The quotes single quotes and double quotes act as their respective normal quotes, (') and ("), and {} behave like single quotes ('). Thus:
```
$x="A Variable"
โ$xโ
โ$xโ
โ$xโ
โ$xโ
โ$xโ
โ$xโ
โ$xโ
{$x}
```
outputs:
```
$x # โ$xโ
$x # โ$xโ
$x # โ$xโ
$x # โ$xโ
A Variable # โ$xโ
A Variable # โ$xโ
A Variable # โ$xโ
$x # {$x}
```
As a final useful bit; you don't even have to match the starting and ending quotes, so long as they are of the same type (single/double). Meaning these:
```
โ$xโ
โ$x'
โ$xโ
โ$x"
```
Are all perfectly valid, and output like so:
```
$x # โ$xโ
$x # โ$x'
A Variable # โ$xโ
A Variable # โ$x"
```
# Alternative Dashes and Uncommon Whitespace
In addition to the additional quotes characters above, PowerShell recognizes some special dashes as equivalent to the hyphen (-):
```
5โ4 # EN DASH 0x2013 [โ]
3โ2 # EM DASH 0x2014 [โ]
1โ1 # HORIZONTAL BAR 0x2015 [โ]
```
Powershell also recognizes two other uncommon whitespace characters:
```
NoBreakSpace 0x00A0
NextLine 0x0085
```
These were found by @ZaelinGoodman's experiment [here](https://codegolf.stackexchange.com/questions/220236/alphabet-printing-challenge/220244#220244)
If anything changes, or if you want to see the specifics of how these work, you can find the source code for this handling in the [PowerShell Github](https://github.com/PowerShell/PowerShell/blob/master/src/System.Management.Automation/engine/parser/CharTraits.cs)
I made this community wiki, so this list can be freely updated.
[Answer]
# Using variables if $ is forbidden
Use the Get/Set-Variable:
```
Set-Variable myVar 5
Get-Variable myVar
```
And shorter with their aliases:
```
sv myVar 6
gv myVar
```
as `Get-Variable` returns a `PSVariable` object, use the `-v` for `ValueOnly` to get only the value
```
gv myVar -v
```
Note that it works for already defined variables such as `$args` in functions.
[Answer]
# Printing numbers in Restricted source
You can use Boolean or hexadecimal numbers or print numbers in other way, in restricted source.
---
When performing arithmetic operations on Booleans, Powershell treats them as if they are the numbers 1 and 0. Basically, if you cast any undefended variable to `[int]`, it will be considered as `0`.
An example is:
```
PS C:\Users\Administrator> [int]$true
1
PS C:\Users\Administrator> [int]$false
0
PS C:\Users\Administrator> [int]$x #This variable is not defined
0
```
A shorter way is to add/subtract digits to the boolean/non-existent variable:
```
PS C:\Users\Administrator> $true+0
1
PS C:\Users\Administrator> $false+1
1
PS C:\Users\Administrator> $true+$true
2
PS C:\Users\Administrator> ($true+$true)*($true+$true)
4
```
Or just `+$true`, thanks to @mazzy
This especially comes useful if (most) digits are not allowed.
---
Hexadecimal numbers come up useful too, like if you aren't allowed to use `1-9` but have to print `100`, then use `0xa*0xa` (because `0xa=10`)
```
PS C:\Users\Administrator> 0xa
10
PS C:\Users\Administrator> 0xa*0xa
100
```
---
Another tip is you can calculate a string's length (length of `18` `x`s):
```
PS C:\Users\Administrator> 'xxxxxxxxxxxxxxxxxx'.length
18
PS C:\Users\Administrator> 'xxxxxxxxxxxxxxxxxx'|% le*
18
```
use "$args" to cast the arguments to one value. use +"$args" if you need only one value, thanks to @mazzy
] |
[Question]
[
Let's assume we've got an imaginary assembler. The assembler supports numerical labels. An infinite loop example:
```
:1
jmp 1
```
Your task is, to write a preprocessor for this assembler supporting named labels (instead of numerical ones; with up to 8 characters in length), so the label name is replaced to it's numerical value.
The assembler uses a dot (.) to express a character constant, for example:
```
mov dl, .A
```
Will store ASCII(65) - 'A', in the register dl. The assembler supports string constants in double quotes too:
```
:20
db "Hello, world!"
```
So, to sum things up, you need to be aware of character constants, and the fact that you can't perform any substitution inside quote-enclosed strings.
The label declaration character and reference character is up to your choice, but for the sake of completness I will use a `$` to refer to a label, and `@` to denote a label.
The label' number might be any natural number not equal to zero.
**You may assume that assembly on the input is perfectly valid.**
Let's look at a few examples:
```
@loop
jmp $loop
```
```
:1
jmp 1
```
---
```
jmp $skip
mov dl, .@
@skip
cmp dl, .$
```
```
jmp 1
mov dl, .@
:1
cmp dl, .$
```
---
```
@x
db "$a @b"
@a
jmp $a
@b
jmp $b
```
```
:1
db "$a @b"
:2
jmp 2
:3
jmp 3
```
This is a code golf, so the smallest answer wins. Standard rules and loopholes apply.
You can safetly assume that the user won't use numerical labels anymore, and the labels contain just A-Za-z letters.
Label declaration and reference character has to be different.
[Answer]
# JavaScript (ES6), 96 bytes
Uses `@label` for a declaration and `%label` for a reference.
```
s=>s.replace(o=/^\s*@(.+)/gm,(_,s)=>':'+(o[s]=++n),n=0).replace(/".*?"|%(\w+)/g,(s,x)=>x?o[x]:s)
```
[Try it online!](https://tio.run/##nY7NjsIwDITvfQqrUpWEhHTPSIG8BwWU/oBg07jCK@iBdy8ph1arHlZa3zwz39g393BU3a/dzzpg3QxnM5DZkr43nXdVw9Hkx4JWlmsp8kur@EmRMFu2YZLjng5GyiBUMF9iQvJUr3bpK@PFc2QUJ9VHpN/hvj9sSAwVBkLfaI8XfuYJALMesSsCAzluEOfWdpCNKksESGDRFEmyJAH@z35y9H2d6RYfUHsF2k6S/RWoIvIJZH90235i6hLSzIEt07nULR@eJVsu3TLeE8Mb "JavaScript (Node.js) โ Try It Online")
### Commented
*(alternate slash characters are used below to prevent the SE syntax highligter from going mad)*
```
s => // s = input string
s.replace( // 1st pass:
o = // assign the regex object to o; we'll use it to store the labels
โ^\s*@(.+)โgm, // look for [start] + [optional whitespace] + '@' + [label]
(_, s) => // replace with:
':' + // ':' + label ID
(o[s] = ++n), // increment n and store the label in o
n = 0 // start with n = 0
) // end of replace()
.replace( // 2nd pass:
โ".*?"|%(\w+)โg, // look for either ".*?" (non-greedily) or %label
(s, x) => // replace with:
x ? o[x] // o[label] if x is defined,
: s // or the original string otherwise
) // end of replace()
```
[Answer]
# [PHP](https://php.net/) (7.4), ~~148~~ 143 bytes
-5 bytes by stealing RegEx idea from [@Arnauld](https://codegolf.stackexchange.com/a/194123/81663).
```
<?=preg_replace_callback('/".*?"|([@_]\w+)/',fn($m)=>$m[1]?[':'][$m[0][0]>A].($_GET[$w=substr($m[0],1)]?:$_GET[$w]=++$_GET[0]):$m[0],$argv[1]);
```
[Try it online!](https://tio.run/##RYxRC8IgAITf/RUigtrGtl5XbvYQ/YHeTETXWtQW4qr10H83aUTHPdzxHefOLoR1zZ1vO@1b15um1Y3pe2uaKyU5yhY1elMptDpMCctJerpRPDBe4UEuVS1JSZSMuVDR1UZlFOvddi/xxMeHHe@efmG6ZKouf0jxJJlzoVg5D7Dx3TNeslUIQbzA0UKkDRQWAWEAjLoMDmoDhP03@wE "PHP โ Try It Online")
Define labels with `@` and refer to them with `_`.
Captures any `@<label>` or `_<label>` which aren't inside double quotes (`"..."`) and replaces them with a unique number for every unique label, starting from `1`. Also adds the `:` when replacing labels that have `@` before them.
PHP's global variable `$_GET` is used to store and access last used id and unique ids for each label inside the arrow function. `$_GET[0]` holds last used id and `$_GET[<label>]` holds unique id for `<label>`.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 97 bytes
```
ms(1`^@
:@
+`(.*^:(1*).*?^)@
$1:1$2@
^:1*
:$.&
\$(.+?)$(?<=(?=.*^:(\d+)@\1$).+)
$2
^(:\d+).*?$
$1
```
[Try it online!](https://tio.run/##RYxBCgIxDEX3OUUZgiQtFDLL4NAcpJRpGRcKI6Kz8Pa1uvHt/uPznpfjeq@97y@StRioQVgp@qIknqNPhQ1QVHA2KCoeFOMJMlIMiZHSeaG0/P55C2xZkGNgwBkK6VeNBo5C7/aGrbkJq7M2gVVwg9v@cFjB2n@1Dw "Retina 0.8.2 โ Try It Online") Uses the provided symbols (could save 1 byte by using a different symbol). Explanation:
```
ms(
```
Run everything in single multiline mode, where `.` matches newlines and `^` and `$` match at the beginning and end of each line.
```
1`^@
:@
```
Prefix a `:` to the first label.
```
+`(.*^:(1*).*?^)@
$1:1$2@
```
Number the labels in unary.
```
^:1*
:$.&
```
Convert to decimal.
```
\$(.+?)$(?<=(?=.*^:(\d+)@\1$).+)
$2
```
Find all matching references and replace them with the number.
```
^(:\d+).*?$
$1
```
Delete the label names.
[Answer]
# Python 3, 136 117 bytes
New and improved:
```
import re;d={}
f=lambda s:re.sub(r'(".+?")|([@$])(\w+)',lambda m:m[1]or d.setdefault(m[3],f":{m.end()}")[m[2]<='@':],s)
```
[Try it online!](https://tio.run/##PYvdCoMgHMXvfYo/EqgUwdZdW8z3cF4oKmtkhRrbaD17ax/s3JzzO5wzPtJl6Kt1bf04hATBHkwzL8g1nfLaKIh1sGWcNA2E4jI/YfakgmeS0fMtZ6T4zXztxU4OAUwZbTLWqalL1ItKFg7Xsy9tbyhbMBNe7OWxIZzUsohsjdAAxhjxOzIacKaA640Ugk1XP0L2jVx/7N9q9H6Noe0TdTQytr4A "Python 3 โ Try It Online")
Uses the position of the match.end() as the integer for a label.
Old code
```
import re;d={};n=[*range(9999)]
f=lambda s:re.sub(r'(".+?")|([@$])(\w+)',lambda m:m[1]or d.setdefault(m[3],f":{n.pop()}")[m[2]<='@':],s)
```
[Try it online!](https://tio.run/##PYvNbgIhFIX3PMUNmWTu1ckk6sqxpLwHZQGBqRphCGDaxvrs07E1/TbnJ@ekr3qc4m6eTyFNuUL2Bydu90MUapVNfPe4XyDNRnExwToDZci@L1eLuUXer185faOSjSZ8@1hT2z1nYQhqo6cMri@@Oj@a66ViUDvdjXy4xT5NCenOSQW11S@ile2gu0JzAQGccyY/mbPAGwPSLskwWDiHBM2flfZX/lvLHq@UT7HiiIVo/gE "Python 3 โ Try It Online")
Labels start at 9998 and count downward. Some numbers may be skipped. It will handle about 5000 labels, which should be enough for any sane asm program, but the number can be increased at 1 byte for each order of magnitude increase in range.
[Answer]
# [Perl 5](https://www.perl.org/) (`-p`), 57 bytes
```
s/^\s*\K@(\w+)/":".($$1=++$,)/mge;s/".\*?"\K|\$(\w+)/$$1/g
```
[Try it online!](https://tio.run/##RYzLDoIwEEX3/YqmmQUItLBgIyHOnvgHjQkVJCjQxvpa@O1WLFHvZmbOuRnTnofcXaemPUBcOCt20q5khYG8R6Fga8YDgKyMIohDMXZtYQXjqw2T1VPCUpq96JwrPyE4aG0InXMcDQV/kUV5YE@9IaO@0WaIKUeCHuxn5QF8y/ggjaIMaoqKEaz/L5cVlR8/ql7aXHo9WZekqXHJNudp9gY "Perl 5 โ Try It Online")
* `$,` : global variable used as counter
* `s/^\s*\K@(\w+)/":".($$1=++$,)/mge` : replaces labels `"@[label]"` by `":[counter]"`, increment counter and store counter in variable label name's variable
* `".*?"\K|` : regex part used to ignore strings between `""`
* `s/...\$(\w+)/$$1/g` : replaces references by variables value
[Answer]
# Javascript ES6, 71 char
```
s=>s.replace(/(;.*|".*?")|:(:?)(\w+)/gm,(m,s,c,l)=>s||c+parseInt(l,36))
```
Conditions:
* `::` to introduce the label
* `:` to use the label
* Labels are case insensitive
* `;` starts comment till the end of the line
* Quoted strings may not have `"` or linebreak inside
* Charecter constants may not be followed by colon or letter like `.:a` or `.::`
* Classic numeric labels starting from `:` are disallowed
Test:
```
console.log((
s=>s.replace(/(;.*|".*?")|:(:?)(\w+)/gm,(m,s,c,l)=>s||c+parseInt(l,36))
)(`
::loop
jmp :loop
jmp :skip
mov dl, .:
::skip
cmp dl, .:
::x
db ":a ::b"
::a
jmp :a
::b
jmp :b
`))
```
```
.as-console-wrapper.as-console-wrapper{max-height:100vh}
```
] |
[Question]
[
# Introduction
Brainstract, a newly created dialect of [Brainfuck](https://esolangs.org/wiki/Brainfuck) adds a bit more elements to the syntax. In addition to the normal Brainfuck syntax, there are macros. To define a macro:
```
{macro_name ++++}
```
Then use it:
```
{macro_name} Adds 4 to the current cell
```
---
# Challenge
Your challenge is to take a valid Brainstract program as input (command-line-arguments, function arguments, STDIN or file), and output a valid Brainfuck program that is equivalent to the Brainstract program (non-brainfuck characters are allowed in output). You may assume all input will be valid Brainstract.
# Brainstract Spec
Whitespace counts as ANY whitespace (tabs, spaces, etc.)
A macro is defined by an opening brace character (`{`) followed by a macro name which must be made up of any characters except whitespace, brainfuck, and Brainstract characters (anything except whitespace and `{}[]<>+-.,`)
Then, it is followed by any amount of whitespace and a macro definition, made up of macro calls and non-brace characters and finally the macro is closed off with a closing brace (`}`)
A macro call is of the form `{macro_name}` where macro name is the same as above.
---
# Examples
Format: `Input -> Output`
```
{cat ,.} {cat}{cat}{cat} -> ,.,.,.
{add [>+<-]} ++++>+<{add} -> ++++>+<[>+<-]
{recursive ,.{recursive}} -> (undefined behavior)
++++ {decrement -} ++++ {decrement} -> ++++++++-
{a >>>---<<<} {b {a}{a}} {b} -> >>>---<<<>>>---<<<
```
---
# Standard Loopholes apply, and shortest code wins
---
[Answer]
# Java 8, ~~251~~ 242 bytes
~~226~~ 217 bytes of code + 25 bytes for `java.lang.regex.\*` import. I can't lambda this since you can't use recursion in a lambda function (self-reference). This just about ignores recursive macros (the space is removed).
* 9 bytes saved by ceilingcat
```
import java.util.regex.*;
...
String f(String s){var p=Pattern.compile("\\{(\\w+)\\s+(\\W+)\\}");for(var m=p.matcher(s);m.find();)s=s.replace("{"+m.group(1)+"}",m.group(2)).replace(m.group(0),"");return p.matcher(s).find()?f(s):s.replace(" ","");}
```
[Try it online](https://tio.run/##fZCxbsMgEIb3PMWJCeoYtR1rx32CSJUydIgzEIwdUmMjwEkri2d3oXHaLA1C6OO4/@4/juzE0mP1MUmle@PgGO50cLKlRjTikz5kC94ya2HNZDdax5zkMG2ckV0DNZ7BkvGNOSdMB3o1E@W90rIVGJXliMvynJCytEmg90gekWzNHD8IA2qlqbowtiQ7H6JM0Vp2FSbErmwwo1vGQ60RJYo2ph80fiIJ8mh5vT4T8pt2jT2SJQp9jHBDtHbTZC7@Wgd@uakP6EfhJz3s2zDqPPGplxWo8AXzxNsdMNNYAuNi82WdULQfHNXhybUdroNPzhwsqYcI/u9AhGT/SVhVwbZI8nTnIQkrYIzd08Q0GCvBjVCic5BelDeh@x2hKIo0TfM8D073MDIfdsSLzPvpGw)
[Regex source](https://codegolf.stackexchange.com/a/177859/84303)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~113~~ ~~108~~ 102 bytes
*-5 bytes because input will always be valid brainstract*
*-6 bytes thanks to Cows quack for regex function golfs*
```
x=>{while(m=/({\w+)\s+(\W+)}/.exec(x))x=x.replace(eval(`/${m[1]}}/g`),m[2]).replace(m[0],'');return x}
```
[Try it online!](https://tio.run/##hVNRi5tAEH52f8UUCrpEY9vHJgqlUEpLW7g@3EMSuK2OiT11w@565yH@9nR2N2dytFADMjt@M/PtN19@iwehC1UfTdLJEk9VdhqyfHw81A1GbZZG4/Zxwbd6EW1vF3xKlzhgEQ2cD9mwVHhsRIERPogmuktfj@3m7W6a0v0dj9vNux2fEe3mzS4OQ75SaHrVwTCdqr6DDAoaClkOIwvSFG7tWDAHVBhqENCKQkkosaq72tSyg7qzX10VC84khSkO1Ckdo39RtVDObX874MbzgUI0jQYjXTc/5bE2h8uRxvshgWfoTv@/sJ/yoStBYSsf3F2u@VdKtlc3CIK/FWLBxDxV14CIgj4SQr8sBuGGWDVZ8Kzqik2MUe1XfIJak1rH3sRAZHu0Z9kbSjCD2mi6EmkSjoUwEC8nsMF0eYXvIYyX9hfGFibKEjb5Yp3sJljQQ6HNOdz57D87uM3AWGJBKmBnIPFFV6m50D6Jn6Fli9/cLvI8T5JkvV4TL2nt4NMXxHQVvsC4vnP5HIRsWjllPkkFKMgw91YicpPVglVSRTaaM/xsyBsyKRm1sMuzMuu@MaRc5dB2V4T5TJto7JZ/9Xu3FVRKKs2CuoLIPB1RVpGv5PAqyyDURtXdPuQw9/vy88f3pU/X1dMz2rf/eMDiHqjXGU17FBpwOGJhsISo3nfSFgL9HYiVtQp3NPy2z2WMfNxp2eCykfvzgNl76Vane2s@IHru/hv73sUQJnkYw8xnOp3@AA "JavaScript (Node.js) โ Try It Online")
TIO Link includes a test suite of all 4 "valid" test cases provided in the OP.
The invalid recursive macro test was ignored as, given it's undefined behavior and our program can whatever, there's no need to test it; the result is irrelevant.
## Ungolfed Explanation:
```
fun = code => {
// While there's a macro definition in the code
while(match = /{(\w+)\s+(\W+)}/.exec(code)) {
// Replace calls to the macro with the macro's code
code = code.replace(eval(`/${m[1]}}/g`),m[2])
// And remove the definition from the code
.replace(m[0],'');
}
// Remove all spaces from the code and return
return x;
}
```
The entire function relies on the regex: `/{(\w+)\s+(\W+)}/`
This should match any valid macro definition and include the macro name in Capture Group 1, and the macro's code in Capture Group 2.
Due to how JS's `regex.exec()` returns, `m[0]` is the whole matched string (the entire macro definition), `m[1]` is the string matched by Capture Group 1 (the macro name) and `m[2]` is the string matched by Capture Group 2 (the macro's code)
We can then replace all instances of `{m[1]}` with `m[2]`, then remove the first instance of `m[0]` in order to remove the macro definition. This is required in part due to the way brainfuck would interpret the macro definition, and in part due to the way the while loop in this function works (it finds the first definition in the code, if we don't remove the definition after we've processed it, it'll keep finding the first definition over and over)
However, our first capture group `m[1]` also includes the opening brace `{` of the macro definition. This is so that when replacing `{m[1]}` with `m[2]`, we actually only need to replace `m[1]}`, which saves a byte.
Unfortunately including a variable `m[1]` in a RegExp in JS is a bit costly, as we need to `eval` the regex, which adds 6 bytes.
There's probably quite a bit of golfing room in this answer, as there tends to me in my NodeJS answers.
If anybody has any suggestions for golfing, let me know in the comments.
However if your answer involves using an entirely different approach to mine, please post your own answer :)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 33 bytes
```
Wa~`({\S+)(.+?)}`a:$`.$'R$1.'}$2a
```
[Try it online!](https://tio.run/##ZY3BCsIwDIbve4ocCtuoLehxlPoEgijoQYXVruAOc7ObXkp89Zki6MQQwpc/f5Ku7sa9KW4JrGEXCJ9lFo5bnmeSL3MsTcFKydINm8sU2cKMOAZrBphJhAj4LUkwVQUHzZU4IXAKwqjRxDt79339cLT4bRCTaINQOetd464DiPfmRIp3QWsthFBK0dczBIOUEWnYt41bGevbH9NHbYeL85MeJ/jnwxc "Pip โ Try It Online")
Very similar approach to [Xcali's Perl solution](https://codegolf.stackexchange.com/a/177938/16766), though mostly independently derived.\*
```
Wa~`({\S+)(.+?)}`a:$`.$'R$1.'}$2a
a is 1st cmdline argument (implicit)
Wa~` ` While this regex matches in a:
({\S+) First group: { followed by non-whitespace characters
(.+?) Second group: more characters, as few as possible...
} ... followed by }
This matches a macro definition, including all the
whitespace as part of the replacement code
(It doesn't work for macro definitions with macro calls
inside them, but the leftmost definition at any time
will not have a macro call inside it)
So while possible, match the first occurrence, and:
a: Set a to:
$` The portion of the string left of the match
.$' concatenated to the portion right of the match
R In that string, replace
$1.'} match group 1 plus a trailing } (i.e. a macro call)
$2 with match group 2 (the macro's code)
a When the loop exits, output the final value of a
```
\* That is, I saw the Perl solution's byte count, went "How?!...", and finally realized I could assume a few things that made the code a lot shorter.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 74+1 = 75 bytes
Add one byte for the `p` flag.
```
(k=$2;gsub(/#$1( .+?)?\}/){$1?p: k})while~/(\{\w+) (([^{}]|\{\g<2>\})*)\}/
```
[Try it online!](https://tio.run/##VU9RTsMwDP3vKazRj4SurbZPCOkJOME6UJtGazW6RGnLhIz55AAckYMQUvbRYVnWe8/Plu2m@s1b151GiJ8z1ZrermEF359fsPLs@BBv7w/DVLP8Jt4wyJKCFyXlHONNYe/gSPzcdi/6I2cllueEA2O7J6T9e6AHsZUl8VseBrxHVY2wzghmQEuJsGoa2MlEpHuCJESAs0bRTAAbrZzudTgwvfSvpHn6TyOslsywhjQEYb1khIPp9WOlnAEpZWgLIcI1Zmy1u8iLg67gP09Y47Sa3NC96vDNQoh@jB07cxp8an8B "Ruby โ Try It Online")
[Answer]
# [PHP](https://php.net/), ~~197~~ ~~196~~ 186 bytes
```
<?php $p=$argv[$c=1];$m=[];while($c)$p=preg_replace_callback("/\{(\w+)(\s((?0)|[^{])+)?\}/",function($a)use(&$m){return count($a)<3?$m[$a[1]]:[$m[$a[1]]=$a[2],""][1];},$p,-1,$c);echo $p;
```
[Try it online!](https://tio.run/##VY5NbsMgFISvYllPFShYqdtdwfYJegJMI4peQxTbIGw3C8rZKVWl/uxm5pvF563PWQze@gp8Bzqc3yWYrlUc5k4qfrOXCQkYWqgPeD4F9JM2eDJ6ml61uZL6OEYy3g6UjCshwz39kC9R0QMdxnSs2du@mO3iFgKa7iuSO5hpDLjtYamM25ftC4jHAWYJWrZKPcmfWHzkg2J1rUrjiYFnTcuKDEdjXRHmOee4uhmftQmu6vu@aRohRKqi2yyG7/n3kf7Ef5/0CQ "PHP โ Try It Online")
### 185 if only one kind of whitespace is accepted (by changing the regex to `/\{(\w+)( ((?0)|[^{])+)?\}/`) but I'm not sure whether this is valid.
I was tempted to use JavaScript but the RegExp class in JS doesn't support RE recursion...
[Answer]
# [Python 2](https://docs.python.org/2/), 133 bytes
```
import re
s=input()
while'{'in s:x=re.findall('{.*? (?:[^{]|{.+})*?}',s)[0];d,c=x.split(' ',1);s=s.replace(x,'').replace(d,c)
print s
```
[Try it online!](https://tio.run/##VcrfCoMgHIbh867Cs582k22HlXUFu4JoEOVIMBV1rOG89jYY7M/Z93489h5mo4/bJhdrXEBOZJ5Lba8Bk@w2SyUggtTIlyt3gl2kngalMESWtwi3ZXeO/SOyXSJ5m4B60u37aqIjX5m3SgYMCOiBVJ575oRVwyjwSgHIp16YZNZJHZDfNojeLOI0jM6gpmmKoqjrOqFowizc@/6K9DP/TIIn "Python 2 โ Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 47 bytes
*-11 bytes with ideas from @ASCII-only*
```
$s=$2,s/\Q$1}/$s/g while s/(\{\S+)\s+(\S+?)\}//
```
[Try it online!](https://tio.run/##dY0xDoMwDEX3nsIDAwhCoBIbTU/AUHVsOiCIChIQlCB1iHz1pqFIBQY82N/P3/YoVJdZ6@mLd4405TcvRepp@oJ303YCNPW54fcw4Dr0Xb0GHCm11lTlBFGMMAtc08mUdQ0PFubkiRC6cHJmeJobMLWolOjFMAFZ5hvktrXsRVFWSgJjjBCS57n7IadGqAWvDtzInefwzJ/@vMen9j78yHFq5aAtKbI4SRNLxi8 "Perl 5 โ Try It Online")
[Answer]
# [Go](https://go.dev), 249 bytes
```
import."regexp"
func f(C string)string{M,R:=MustCompile,(*Regexp).ReplaceAllString
K:=M(`(.*?){(.*?)\s(.*?)}\s(.*)`).FindAllStringSubmatch(C,-1)
if len(K)<1{return R(M(`\s`),C,"")}
S:=K[0]
U:=R(M(QuoteMeta("{"+S[2]+"}")),S[1]+S[4],S[3])
return f(U)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TVHNSsQwEL7nKYackt20uOpBlrYiC16WBd3iqRY3m03XYpuWNgUh5Em8LIIP4ZOIj-LNtF1_Qpj55psvk5nk5XVfHd5rLp74XkLJc4Xysq4a7eOs1Pit05l38fn1wzVyL59rjLJOCcjIAlrd5GpPR2dWbD0PV12rF1VZ54VkZLIeTlB_LeuCC3lVFPGgRUunJBviTy6pGex9Ozg7eLqh_nWudr_6uNuWXItHsmDejKI8g0IqsqTBzDRSd42CNXH17tsNZQuGMbUonofL5CRFd_Owz912lZYrqTnBBk_j5DSdYospZXEyS118njp0llJ0rJeRO2qPD_AxDNw_D6FgkOCtbGEeQpIeJ8dGcA3Mt9AD-2cww4bvdpBE08BLLUzdcrDn-lwfgtlJ0chSKg3eqPhHjRUgiiLP84IgcDdswXDrdg8ttiirGnhgom-o4cr949ifQTeuN10oIugvxGGEWeYYiiw6jnc4jP4b)
] |
[Question]
[
This time, we want render the count of bytes in a human readable way to user. Let's write a program (a full one or a function or other acceptable formats) to do this.
## Input
An non-negative integer, in range \$0\leq n<2^{31}\$, which means n bytes.
## Output
A string, the human friendly representation of n bytes.
## Convention
* If n is less than 1000, add `B` after n and output; otherwise...
* Convert to a number less than 1000, plus one of these units: KiB, MiB, GiB; round the number to 3 figures
* For more details of conversion, check out these testcases
## Testcases
```
0 -> 0B
1 -> 1B
42 -> 42B
999 -> 999B
1000 -> 0.98KiB
1024 -> 1.00KiB
2018 -> 1.97KiB
10086 -> 9.85KiB
100010 -> 97.7KiB
456789 -> 446KiB
20080705 -> 19.2MiB
954437177 -> 910MiB
1084587701 -> 1.01GiB
1207959551 -> 1.12GiB
2147483647 -> 2.00GiB
```
# Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest bytes win
* Standard loopholes forbidden
* You should output exactly the same to the testcase:
+ No white space or other symbols between number and units;
+ Use `KiB`, not `KB`, `kib`, or `kb`;
+ Leading or trailing white spaces are optional
[Answer]
## JavaScript (ES6), ~~78~~ 74 bytes
```
f=(n,i)=>n<999.5?i?n.toPrecision(n<1^3)+' KMG'[i]+'iB':n+'B':f(n/1024,-~i)
```
```
<input oninput=o.textContent=f(this.value)><pre id=o>
```
Edit: Saved 4 bytes thanks to @Arnauld.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~108~~ 102 bytes
Works as Yimin Rong suggests.
```
f(float i){char*a="GiMiKi"+6;while(i>=999.5)i/=1024,a-=2;printf("%.*f%.2sB",*a&i<100?i<10?2:1:0,i,a);}
```
[Try it online!](https://tio.run/##jVJBTsMwELzzishSURySsHbt2GlIK3HhgPgBFyvg1lIaUFuJQ9WvE@K4KeWAtD7szsoz0ozXTbZumr63sW0/zCFy9NhszC4xNXlyL@7Zkbui@tq49j12y7osy1xSd18z4CI1Wc2rz53rDjYmszyxs5zvH0mamFv3wABWvq74gi0gdamh1anfGtfF9HgTDeeiZPAWZcuIpBHQysZDma5eO0Kr/8jMkxmSLLhn@4qiD0E9f2w4MwCj@dCREi6CxHeUhAPTXhI61pguzs48QKdhlzwMm0jIQunx4SaETAUaFMiQbMK4PUkh5oopNW7rd0Cm1EJqpSD8pKsJJ@egSllKGeRXE3b9c6H1@QcE@Fd46r8b25r1vs/a7Q8 "C (gcc) โ Try It Online")
Unglofed
```
f(float i){
char*a="GiMiKi"+6;
while(i>=999.5)
i/=1024,a-=2;
printf("%.*f%.2sB",*a&i<100?i<10?2:1:0,i,a);
}
```
# [C (gcc)](https://gcc.gnu.org/), ~~108~~ ~~101~~ 99 bytes
Works as O.O.Balance suggests.
```
f(float i){char*a="GiMiKi"+6;while(i>999)i/=1024,a-=2;printf("%.*f%.2sB",*a&i<100?i<10?2:1:0,i,a);}
```
[Try it online!](https://tio.run/##jVJBTsMwELzzishSURySsnbt2GlIK3HhUPEDLlbAraU0oLYSh6pfJ8QxKeGAtD7s7Moz0ozXdbat666zsW3ezSly9FzvzCExFXlyz27jyF1efu5c8xa7VVEU1N1XDLhITVbx8uPg2pONyWye2NmcHx9Jmphb98AA1r6u@ZItIXWpoeWl2xvXxvR8E/XnqmTwGmWriKQR0NLGfRmvXlpCy//IzJMZkiy4Z/uKovuYPX8AnBmAwXxApISLIPGIknBg2ksCYo3p/MeZb9Bp2DUPwyYSMld6eLixQ6YCDQpkSDb2uD1JIRaKKTVs63dAptRCaqUg/KTJhJNzUIUspAzyyYRLzYQSepGLwft0@iu/dF@1bcz22GXN/hs "C (gcc) โ Try It Online")
Unglofed
```
f(float i){
char*a="GiMiKi"+6;
while(i>999)
i/=1024,a-=2;
printf("%.*f%.2sB",*a&i<100?i<10?2:1:0,i,a);
}
```
[Answer]
# [Python3](https://docs.python.org/3.6/), 90 bytes
## (~~76~~ 70 bytes 3-most-significant-digits version)
```
h=lambda v,u=0:v>999.4and h(v/1024,u+2)or"%.*f%sB"%(u and(v<10)+(v<100),v,"KiMiGi"[u-2:u])
```
Version whose outputs are strictly adherent to test cases and author's suggestions.
```
list(map(lambda v: print("{} --> {}".format(v, h(v))), (0, 1, 42, 999, 1000, 124, 2018, 10086, 100010, 456789, 20080705, 954437177, 1084587701, 1207959551, 2147483647, 1023079)))
0 --> 0B
1 --> 1B
42 --> 42B
999 --> 999B
1000 --> 0.98KiB
1024 --> 1.00KiB
2018 --> 1.97KiB
10086 --> 9.85KiB
100010 --> 97.7KiB
456789 --> 446KiB
20080705 --> 19.2MiB
954437177 --> 910MiB
1084587701 --> 1.01GiB
1207959551 --> 1.12GiB
2147483647 --> 2.00GiB
1023079 --> 999KiB
1023488 --> 0.98MiB
1043333 --> 0.99MiB
1043334 --> 1.00MiB
```
[Try it online!](https://repl.it/repls/YummyJumpyDevices)
Here, a version that produces the most 3 significant digits for the test cases.
```
h=lambda v,u=0:v<1e3and("%.3G%sB"%(v,"KiMiGi"[u-2:u]))or h(v/1024,u+2)
```
The original test cases:
```
list(map(lambda v: print("{} --> {}".format(v, h(v))), (0, 1, 42, 999, 1000, 124, 2018, 10086, 100010, 456789, 20080705, 954437177, 1084587701, 1207959551, 2147483647)))
0 --> 0B
1 --> 1B
42 --> 42B
999 --> 999B
1000 --> 0.977KiB
124 --> 124B
2018 --> 1.97KiB
10086 --> 9.85KiB
100010 --> 97.7KiB
456789 --> 446KiB
20080705 --> 19.2MiB
954437177 --> 910MiB
1084587701 --> 1.01GiB
1207959551 --> 1.12GiB
2147483647 --> 2GiB
```
[Try it online!](https://repl.it/repls/ShockedShockedMatrix)
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 60 bytes
```
{'BKMGi'[i,4 0/โจรi],โจvโโจ(3-โขโโvโโตรทiโp)รรiโโต+.โฅ1e3รpโ1024*โณ4}
```
[Try it online!](https://tio.run/##Vc/PS8MwFAfw@/6KHISo2@pLmjaJx112GPsLRKFs7QyWtXRlIrqTImxa8SI7eVAQvIsIXvuf5B@Z6Q9n7aFJPn35vlcvDrvjCy@MJt1R6M1marTRD08q0rePsAnM@xL3BsO@wkeqwxAc6Ow9X6vjjlnnOnsyy67d1cvXYn@/mpsLOvvMv5ReXcd7@drUVtS29PKN@Ha@jg0QoGxfZx9ssSmb4BPUvkLtHWx6JxgHSGfPSE2mUeKj0PfGajpB3nSM0sRTYXE4P1WpP4u9kd9KiyFNB718Scw20Nn3IY7OsL67wYEpxwbM52TRArR9UoShh1vknxAjjDaFUUNSygaZU3ERABpRlhQDVTJljTwLoGQKRDRZ8roahPsXbAnnl4HAlrlVVTPH5UJuJ2NuHQ0CODh1tLTosGDpMGZzwnmVQWBYJQvmCM6B1OORfskUuHSk49RMaMmUMM6E7TJeMDU/U/AP "APL (Dyalog Classic) โ Try It Online")
[Answer]
# Rust, 275 bytes
```
fn h(n:u32)->String{let i=[(30,"Gi"),(20,"Mi"),(10,"Ki"),(0,"")].iter().map(|x| (n as f32/2f32.powi(x.0),x.1)).filter(|y| y.0<999.5).last().unwrap();format!("{}{}B",if n<1000{format!("{}",n)}else{format!("{:.4}",format!("{:.2}",i.0)).trim_right_matches(".").to_string()},i.1)}
```
The basic idea is borrowed from the other answers, but formatting the string to have the proper number of significant digits, not have trailing decimal points, and not have numbers like 423.78 takes over half of the code... and it still rounds wrong (19.1 should be 19.2)
[Answer]
# Java 8, ~~130~~ ~~112~~ 108 bytes
```
n->n<1e3?n+"B":"".format("%.3G"+(n<1e9?n<1e6?"K":"M":"G")+"iB",n<1e9?n<1e6?n/1024.:n/1048576.:n/1073741824.)
```
Uses 3 *significant* figures, as per the original challenge. Try it online [here](https://tio.run/##XVHBjoIwED3jVzRNNoGAbAuFFnXXxMN62HjyaDyAFreuFgPVjTF8OzsVTTZ7aGfy3szrm@k@v@TD6iT1fvvdnc7FQW3Q5pA3DVrkSqPbwFHayLrMNxLNrkY2H1V9zA1AlnOWplZ6h8o76EIpKmyRNx447cB56DUmNxAuldqiI6i6fddqjfJ613h3oX/aRYneUKeH73pCZTzVPp7hEcbh4yH8EsZz7LuWzab2Tqf4EyoWcObY87Ga4eAvq18piVg4spGJhKd9ymPOqADC6xwHTNtpwZc@HwtZN@BByx/UYzcSIBogFgUoyzLICbEIqAYoIlTcEZH2BAWKJSkXmSWJIJwk0JcwFnPKuS0SLBGcE5CkEeFZkiUJ5BFlnIk4Zby1dmDe@1YVWCFjCJOnt/Ag9c58jZHvq36FzvLaGHkMq7MJT7Bgc9BuUT5X9mhbqbVnf8d@Tztou18).
Thanks to [Jakob](https://codegolf.stackexchange.com/users/44945/jakob) for golfing 4 bytes.
Ungolfed:
```
n -> // lambda
n < 1e3 // special case: number of bytes is < 1000
? n + "B" // output the number of bytes
: "".format("%.3G" // otherwise output 3 significant digits
+ (n < 1e9 // if it's less than 1 billion bytes
? n < 1e6 // and it's less than a million bytes
? "K" // output kibibytes
: "M" // else output mebibytes
: "G") // else output gibibytes
+ "iB", // common suffix
n < 1e9 // if it's less than 1 billion bytes
? n < 1e6 // if it's less than 1 million bytes
? n/1024. // convert to kibibytes
: n/1048576. // else convert to mebibytes
: n/1073741824. ) // else convert to gibibytes
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 34 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
รฌโโฦโยฟnโโ.รชNโดโmโ@ร ฮ*ยกIโ '}ยฟรรผzโฅโโ6]
```
[Run and debug it](https://staxlang.xyz/#p=8dddc89fb0a86e12c42e884ec1df6ddd4085ff2aad49f4277da88e817a03ecc0365d&i=0%0A1%0A42%0A999%0A1000%0A1024%0A2018%0A10086%0A100010%0A456789%0A20080705%0A954437177%0A1084587701%0A1207959551%0A2147483647&a=1&m=2)
Writing this, I ran into a bug in stax's log10 operation. Log10 of 1000 yields `2.9999....`, which is particularly unhelpful for this challenge. I ended up using string length instead. Unpacked, ungolfed, and commented, it looks like this.
```
Vk< is input less than 1000?
{ start block one
yp'BP print input followed by "B"
} end block one
{ start block two
x push input as number
y%v3/X push (len(input) - 1) / 3, and store in the X register
A*|2 multiply by 10, then get calculate two-power
:_2j floating point division, rounded to 2 places as a string
p print without trailing newline
"GKM"[[emailย protected]](/cdn-cgi/l/email-protection)+P use x register to index into "GKM" string, then concat "ib" and print
} end block two
? if-else based on initial condition
```
[Run this one](https://staxlang.xyz/#c=Vk%3C+++++++++++%09is+input+less+than+1000%3F%0A%7B+++++++++++++%09start+block+one%0A++yp%27BP+++++++%09print+input+followed+by+%22B%22%0A%7D+++++++++++++%09end+block+one%0A%7B+++++++++++++%09start+block+two%0A++x+++++++++++%09push+input+as+number%0A++y%25v3%2FX++++++%09push+%28len%28input%29+-+1%29+%2F+3,+and+store+in+the+X+register%0A++A*%7C2++++++++%09multiply+by+10,+then+get+calculate+two-power%0A++%3A_2j++++++++%09floating+point+division,+rounded+to+2+places+as+a+string%0A++p+++++++++++%09print+without+trailing+newline%0A++%22GKM%22x%40.iB%2BP%09use+x+register+to+index+into+%22GKM%22+string,+then+concat+%22ib%22+and+print%0A%7D+++++++++++++%09end+block+two%0A%3F+++++++++++++%09if-else+based+on+initial+condition&i=0%0A1%0A42%0A999%0A1000%0A1024%0A2018%0A10086%0A100010%0A456789%0A20080705%0A954437177%0A1084587701%0A1207959551%0A2147483647&a=1&m=2)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~87~~ ~~81~~ ~~80~~ bytes
```
def f(n):
for u in'','Ki','Mi','Gi':
if n<1e3:return"%.3G%sB"%(n,u)
n/=1024
```
[Try it online!](https://tio.run/##HU/LasNADLz3K4TB2AYllfZh7Ya2h15yKP2C0kOhNt1DleDYhxLy7a6cy8BohtHM@W/@Oalf1@9hhLHV7vAA42mCBYo2DTZvxeB9g2NpTIMygj7x4A/TMC@TVvXeH@vLa1W3iktnBn18ZnJh3VLUUuCDkDE4zDkjExkzGR1x2mjq70cmDLGXlE2gREIRcwzBC4uYIYWYRIiRHUmOOUZGx0FC8n2QTyt2norObXW9we4Frrdqb/9/v2ZrdZ/Vdes/ "Python 3 โ Try It Online")
**This does not work, I will need to think about how to fix it.**
-6 bytes from Jo King
-1 bytes from Stewie Griffin
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 135 bytes
```
e;double atof(),x;main(i,v)int**v;{for(x=atof(*++v);x>=999.5;e++)x/=1024;printf(e?"%.*f%ciB":"%.*fB",e?2-(int)log10(x):0,x,".KMG"[e]);}
```
[Try it online!](https://tio.run/##TYpBC4IwGED/SgyEfdu0KXXQYYKXDtEviA62tjGYLsxkEP31lnjqnR68J1MjZYxK3P3r5tSmm7zGwILoOztgy2aww0TILN7ajzjUayeUziDCoS7LMtsLRSmEbZ3zYice4/JrrBqUZEQn0raoWrVFTDVFipcMzpuc4wAVZ4Gh7HQ@oou6gvjEGHP@x1dq15lnTF3/Aw "C (gcc) โ Try It Online")
Quite change from Yimin Rong's solution
[Answer]
# C, 154 ~~165~~ ~~191~~ ~~189~~ bytes (full program)
Big thanks to O.O.Balance and l4m2 for suggestions and providing this [TIO](https://tio.run/##PctBC4IwAAXgvxIDYZvTNquDLBO6dIh@QXRYa7PBdKEmA/Gvt0Si43vvezKppAzh4d53q1aidxrKp2gx4rUwDTRkQEvGAx9/yBcLw3E8IG409HumNujVmqbXEETdERA8L8p2atSuhdwfijzP0x2PY4P8umA02/K/T7GOpJlPWQLnCllXMQo9Ip6AsizPlxO4mhvi0xRCYJTSj9RWVF1IbP0F) and this [TIO](https://tio.run/##PY3BCsIgAIZfJYSBOrd01WHYGnTpED1BdDDTJbgZ2xrC2Ktn0qHr930/v8waKUN4uPfdqpUYnYaIeN4K00FDJiSfosd44rOvfhKn6YS40dDvmdqgV2@6UUOQDEdAcDTKDmrWrofcH6qyLPMdT1OD/LpitNjyf59jnUgTR0UGI0LWNYxCH78JqOv6fDmBq7khviwhBEYp/UhtRTOEzLZf)!
```
double atof(),x;main(i,v)char**v;{x=atof(*++v);if(x<1e3)printf("%sB",*v);else{for(;x>=999.5;++i)x/=1024;printf("%.*f%ciB",2-(int)log10(x),x,"KMG"[i-3]);}}
```
Save as `doit.c`, compile using `gcc -o doit doit.c -lm`, and run:
```
> ./doit 1000
0.98KiB
```
Test cases:
```
> for i in 0 1 42 999 1000 1024 2018 10086 100010 456789 1023079 1023488 20080705 954437177 1084587701 1207959551 2147483647 ; do ./doit $i ; echo; done
0B
1B
42B
999B
0.98KiB
1.00KiB
1.97KiB
9.85KiB
97.7KiB
446KiB
999KiB
0.98MiB
19.2MiB
910MiB
1.01GiB
1.12GiB
2.00GiB
```
] |
[Question]
[
The objective is to print a graph from an array of numbers, of the design below. Printing the X and Y scale exactly as in the "design", with padding, is part of the challenge. The input array of numbers can be of virtually any range of integers in X and Y, but not 0 and not negative - though I would suggest keeping it small considering this is ASCII art! (x < 15, y < 50 or so).
**Specifics**
1) the graph should print the Y scale on the left, padded to the max length of the input, and with a pipe '|' between the number and the first column.
2) the bar should have all empty spaces with periods '.' filled spaces with pipes '|' and the number itself should be an 'o'.
3) there are three "tween" columns between each number that interpolates between the two numbers. These cannot just be a duplication of the previous or next column, but need to interpolate between the values linearly. (Unless two adjacent numbers in the list are only 1 apart or the same.)
4) The bottom of the graph should look: " +---------" to the length of the graph.
5) There should be an X scale padded to the length of the max number, similar to the Y scale. The last digit of the x scale should align with the value (I guess that means we're limited to two digits...)
6) Lastly, there should be an "empty" column in the beginning of the graph and an "empty" column at the end.
**Example**
This:
```
[5, 3, 7, 8, 10, 7, 8, 7, 9, 2]
```
Generates:
```
10|.................o.....................
09|................||...............o.....
08|.............o|||||......o......||.....
07|.........o||||||||||.o|||||..o||||.....
06|........|||||||||||||||||||||||||||....
05|.o.....||||||||||||||||||||||||||||....
04|.||...|||||||||||||||||||||||||||||....
03|.|||.o||||||||||||||||||||||||||||||...
02|.|||||||||||||||||||||||||||||||||||.o.
01|.|||||||||||||||||||||||||||||||||||||.
+---------------------------------------
01 02 03 04 05 06 07 08 09 10
```
Trailing spaces on each line, or trailing newlines at the end are permitted. As long as the output is visually the same.
Here's a working Python3 example, in "long hand" if you wish:
[Try it online!](https://tio.run/##pVXBbqMwEL3zFaPsobgk2aTVXqLN3ve8xyhCBkywFmxkzDZVm2/Pjo0BJ6VRq1pVA/Z7zzNv7KF@1oUUj@dzxnI4MMEU1Sw@KFoX4T9atqwhmwBwFIwfCg1bqOixXzHz8A20rEHmoAsGlmjxTzzTBcJLJnp4EHT4pOVlBlQAVYo@G2oqy7YSjV13z0jd7f2JJa1rJrKw5I0OZy@n2TKXqqL4vJzde7vgwD3qVgPHHSApqfjrNKwcstyrASgqDiy0wbpEzbBSGEEnuevg@2G5plmcoF/b3pVFh7wA0Fz3CsM8CsWNVlwccAlzkFdpOOE5zF67FxQhPvuNEaMiIfCBgdUqeAP4Z8pFU93SsncnGEGprNBBZkF3@okxMewOf6RSz3P4fVeBkHCQEmup8VjoYrlcDhq8ryr89M/AYj26bKvR6laxeNJwiGC9R2/XA4OVDbvJXw2LGc9zpphIzTRNmi4AVPMZo7dcpCUXBjsSvz/62XT8Xxf8y1isTzFFDS70sJ9TJhPQZBoK9/AwBU/fhT@SGxZNhRV9PKzoc2FFl2HdPLx4Ay4vAHLC7kotXNTE3gUz30/g@KJoci2afEUUC@F8uJZNB9kPtDCkXTWxd7uYa6M13noNEiFD5@0Kj40j61rMauh4Sj6N7a4L3Ot3I8PEgP2kh4yuoIDfuvB1s3pB3un0OqSBk1vnND7OjezWSY9CJprjGIvZ0NlDyOXB9baMtr2Hu@N@hwteMzY2hCOWTNqTSK1l9fYz1bGxFpFfDjDlcJHPZ4u@OEOc3R7H2KYQG2/RE5hNu@2XdUzQJ0eGDS@b1cPJ9zJaEy9Gj4DXKleYDU5k@MOrWirt3oLAJmc@n9YXOxmS@/UPYkOLx8AeVmQfXH3z7X9yPv8H "Python 3 โ Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 505, 484, 480 bytes
```
i=list(map(int,input().split(',')))
l=len(i)
r=range
e=enumerate
m=max(*i)
s=len(str(m))
t='%%0%dd'
f=t%s
g=t%len(str(l))
d=[['.']*(l*4+s)for _ in r(m+2)]
for x,y in e(d):y[:s]=f%(m-x);y[s]='|'
d[-2][:]=' '*s+'+'+'-'*(l*4-1)
d[-1][:s+2]=' '*(s+2)
d[-1][s+1:]=['%-4s'%(g%-~x)for x in r(l)]
for x,y in e(i):
n=y
def r(z,o):
for v in d[m-n+(n-y)*z//4+1:m]:v[x*4+s+o]='|'
d[m-y][x*4+s+2]='o';r(0,2)
if x==l-1:break
n=i[x+1];r(3,3);r(2,4);r(1,5)
print('\n'.join(map(''.join,d)))
```
[Try it online!](https://tio.run/##XZHRboQgEEXf@QpezIDC7qrbtLXhS6hpbMQtraIR2uim6a9vB7f70pDAzJ0zcMlMa3gbXXm5WNVbH9jQTMy6IKybPgPjOz/1NjAQwDknveqNY5aTWc2NOxlilHGfg5mbYMighmZhKVb9hvkwswGbgoIkOSRtC6RTIfHkhPsN6BFoldawgzplfXrMPO/Gmb5Q6yj2ZwWvSRQWsUbJsJZXq658rbqEDXLhT6vGBL6BtFoWta4woZD6DOKSsN0qcx7LOZZ9VlwJhtFN9VmOfRoSefSQsFMif5bNx3L10f93YXlFqFMroa3pEDiLMSo0Ql8RafUgXcacXHl63u@P@MBQV196iV/MxqvjjVrrPzH6GuFpZgeBxqjt6KJUL/PqdTbNR3zO6iXLayRKUXI8CnGMRy7uOJlmHBuDZwe799G6bZBwjUWLw7tc7gQtBb0X9EHQ/HCLcH8UtPgF "Python 3 โ Try It Online")
With some help of @kevin-cruijssen
-25 with some cleanup in newlines etc. by me
Could probably be compacted a bit more
[Answer]
# [Python 2](https://docs.python.org/2/), ~~261~~ 246 bytes
```
lambda a:[[" 0"," +-","%02d|."%~-i][min(i,2)]+"".join(s)[3:]+" -."[min(i,2)]for i,s in enumerate(zip(*[list((" %02d"%-~j)[i]+"-"+"o|"[i<3].rjust(a[j-1]+(v-a[j-1])*-~i/4,"|").ljust(max(a),"."))for j,v in enumerate(a)for i in range(4)]))][::-1]
```
[Try it online!](https://tio.run/##VY/dboMwDIVfxbKEFJcko9BpG9qeJM1FpkLnCAICWm0T4tVZ6DZNu/HP8fFnuf@Y3rqQr/XLcW1c@3py4EpjEAAylDGlKqYky0@zxmRRbE3LQbDMyaaI2nexG8kUZWxBafwb190ALEfgAFW4tNXgpkp8ci92puFxEiLSNzAmavFkOAIUptjNaPi5sHrwl@hyxqu9TcVVfVe0UwvfHSTOSLq5WVr3LhxJ1Ei0HfXy@v@ou8m8iYML50ocyBJZU5YRuPYDh0ngMfx8UwtzL6GQ8CDhUcI@@61ifJKQx1VavwA "Python 2 โ Try It Online")
Anonymous lambda returning the list of strings comprising the chart. Performs linear interpolation between points with floor rounding, in 4 steps from `a[i-1]` to `a[i]`.
# [Python 2](https://docs.python.org/2/), ~~271~~ 256 bytes
```
lambda a:[[" 0"," +-","%02d|."%~-i][min(i,2)]+"".join(s)[3:]+" -."[min(i,2)]for i,s in enumerate(zip(*[list((" %02d"%-~j)[i]+"-"+["o".rjust(v,"|"),"|"*(a[j-1]+(v+~a[j-1])*-~i/3)][i<3].ljust(max(a),"."))for j,v in enumerate(a)for i in range(4)]))][::-1]
```
[Try it online!](https://tio.run/##VY9hT4QwDIb/StOEZINtcqBRif6S3T7MHGgXGAQ4oubCX8dyaoxf2r5t36fp8DG/9bHYmufj1vru5eTBV9YiAOSoOGWaU5IXp4vBZNXkbEdRkCqkyxBN6FlN0pYVS9AG/8ZNPwKpCShCHc9dPfq5Fp80iNS2NM1CMH0HY6LXIC0xQGNmsUczhjMvLAovKPeQCm@DPrhMLNn6XcpUr3RTSmfpqXSmvTo6/y48OwxKuZ8Pavl/3l/btDdHH19rcSudZEZVMXIbRoqzwGP8@asR9k5BqeBewYOCQ/5bcXxUULBVbl8 "Python 2 โ Try It Online")
Alternative version that interpolates in the same manner as defined in the OP's reference code. Interpolation occurs in 3 steps from `a[i-1]` to `a[i]-1`. This way, the value of the third 'tween' column is always 1 below the actual data point, and these two columns always have the same number of pipes. This matches the reference code except for zero values, which we are not required to support.
Probably the longest lambda I've ever written to date. Will try to revisit and golf a bit more when I have time.
[Answer]
# PHP, 231 bytes
```
for($e=strlen($y=max($argv));$y>$x=0;$y-=print".
")for(printf("%{$e}d|.",$y);$n=$argv[++$x];print"o.|"[$y<=>$n])while($x>1&&++$k%4)echo".|"[$y<$p+=$n/4-$p/4];echo str_pad(" +",$argc*4-1,"-"),"
";while(++$x<$argc)printf("%4d",$x);
```
## fixed width (y<100), 219 bytes
```
for($y=max($argv)+1;--$y>$x=0;print".
")for(printf("%2d|.",$y);$n=$argv[++$x];print"o.|"[$y<=>$n])while($x>1&&++$k%4)echo".|"[$y<$p+=$n/4-$p/4];echo str_pad(" +",$argc*4-1,"-"),"
";while(++$x<$argc)printf("%4d",$x);
```
requires PHP 7.1 for negative string indexing. Run with `-nr` or [try them online](http://sandbox.onlinephpfunctions.com/code/d5713859e57fe1a423c07b084b89e1adce444295).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 68 bytes
```
J+ศท2Dแธโฌ
x4S4ฦค:4;00;โ|แบโo0ยฆโฌ2ยฆ4รฦคแบzโ.ยตร,"jโฌโ|แนYโทโถโถโ+ยณรjโพ ;ยฉโถโ-แนโทโถโถโถยฎ
```
[Try it online!](https://tio.run/##y0rNyan8/99L@8R2I5eHO7oeNa3hqjAJNjm2xMrE2sDA@lHD3JqHu7qBVL7BoWVAWaNDy0wOTzi25OGuviqgqN6hrYfbdZSygDJgpTtnRT5q3P6ocRsINczVPrT5cHvWo8Z9CgrWh1ZCxHQf7mxEqGncdmjd////o011FIx1FMx1FCx0FAwNYCwgaamjYBQLAA "Jelly โ Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 316 bytes
```
a=>a.map((x,i)=>{d=Math.abs(x-~-(n=a[i+1]))/3
for(i in n?" ":s=" ")for(j in o="|o"[+!+i].padEnd(x>n?x-d*i|0:x+d*i|0,"|")[S="padStart"](m,"."))A[j]+=o[j]},A=Array((m=Math.max(...a))+2).fill(""))&&A.map((x,i)=>x?(m-i+"|.")[S](4,0)+x+".":i>m?s+s+a.map((_,I)=>s+(-~I+s)[S](3,0)).join``:" +".padEnd(a.length*4+2,"-"))
```
[Try it online!](https://tio.run/##lZLLbqMwFIb3PIXrRWXXxjWQNBfJibKYSl3MqkuEiqekrSOwI0AjRuP21TOHksz0Om1/6Tdgf@eGvNE/dXNdm20bWlesd@dqp9VCi0pvCem4oWrxu1DfdXsn9I@GdOFDSKzSqWFRRulpEty4mhhkLLJLjEB43iiMMO33N/2@U9g7nLIjZjKx1cU3W5BuYZddWJwYL@cde3xy7DFNLxUG5LLVdYszUnEsMKWrdJMx5WC95yu1qmv9i5BqaKrSHRFCaEpZTMWNKUuCIeT4ePV0hG5JqtAw7EVfIyMjLinrGGSfm0W1bFjD9iNf8QvgG0bChwvWPMIJwFRsnLF5PocZIWw/hhbl2t62dycjFnMcQt3dtbONK9eidLfknKRjjhKOJhxNOYrk4Q3WGUcx/MDga/zQRZArlUfSi5dy4i0FcvYK9f7N0EBOnx843@tZ9v1nICf@BTawhxD3NzKQZ/5f4Xc1oGO/L@Q/REd@aMZ/jCY96p/2@Q4byNj/P@FhTECjT6EAB3Brws8JUCQjcAxOwCPwGHwGnoCn4BmC24FyuvsD "JavaScript (Node.js) โ Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~110~~ ~~106~~ 103 bytes
```
๏ผกฮธ๏ผต๏ผข.โฎ๏ผฅโฮธโบโบร0โป๏ผฌโฮธ๏ผฌโฮบฮบ|๏ผงโยฒโ๏ผฌโฮธโยฒ โ๏ผฐโบโชซ๏ผฅฮธโงโบร0โป๏ผฌ๏ผฌฮธ๏ผฌโฮบฮบโดฯ โโ๏ผฅโปรโด๏ผฌฮธยณยงฮธรทฮบโดฮธ+๏ผฐโบยฒ๏ผฌฮธโโ๏ผฅฮธโ๏นชฮบโดโบฮนรทร๏นชฮบโดโปยงฮธโบโดฮบฮนโดโบร|โฮนo
```
[Try it online!](https://tio.run/##jZHfT8IwEMff/SuaPnVxGkSMCk8YXmZYQlCeCA/Ldo5mWzu6bkDC/z6v7cSREOPDdbv2fnzue/E2UrGM8rYNRFlrtvMmNx@g36I4S5WsRcLoPcW7heJCsyU0oCpgYVSiHXhRF5jhk0VeV8wen7yAitEB9UnIBV7MQaR624vG8O4uELGCAoSGhGWeZ14yNHqixsGeMj@mUrDxTO6FT4Y@GS95utXnAhdFx6vSxlBieEPZgEs0Tp1rXtoJLOS75MLOsEP0KJnDl/6bvvv8A36EtvcuKValxUZ/WlU8da1dfddwdK5qOzyiTXUgEjgYwkDoGW94Aiwz9fFxd14IvaVX5hv2613BcLlWsE6FT1AiUkcWyqTOpWvUrZX3CRzvZZSbpAds00ZGD3zlXgfdF/iEAs/gV0BuAqg0e5@07Xr9hCL45NknLz55GPz84fmKK95s2rsm/wY "Charcoal โ Try It Online") Link is to verbose version of code. Edit: Saved 3 bytes thanks to @ASCII-only. Explanation:
```
๏ผกฮธ
```
Input the array.
```
๏ผต๏ผข.
```
Set the background of the output to `.`.
```
โฎ๏ผฅโฮธโบโบร0โป๏ผฌโฮธ๏ผฌโฮบฮบ|
```
Print the Y-axis with its labels left padded with zeros.
```
๏ผงโยฒโ๏ผฌโฮธโยฒ โ
```
Blank out the bottom left corner so that it isn't filled with `.`s.
```
๏ผฐโบโชซ๏ผฅฮธโงโบร0โป๏ผฌ๏ผฌฮธ๏ผฌโฮบฮบโดฯ โ
```
Print the X labels.
```
โ๏ผฅโปรโด๏ผฌฮธยณยงฮธรทฮบโดฮธ
```
Repeat the values in the array 4 times (except for the last value).
```
+๏ผฐโบยฒ๏ผฌฮธโโ
```
Print the X-axis.
```
๏ผฅฮธโ๏นชฮบโดโบฮนรทร๏นชฮบโดโปยงฮธโบโดฮบฮนโดโบร|โฮนo
```
Print the graph itself, repeating `|`s with a final `o` for multiples of 4 and interpolating for intermediate values.
] |
[Question]
[
Based on a recent [question in StackOverflow](https://stackoverflow.com/q/37173914/6188402)
Write a program/function that takes in one ARRAY/list and returns the number of pair-values which sums up to a given TOTAL.
### Explaining
```
TOTAL=4, ARRAY=[1,3,7,1,-3] => RESULT=2
```
The result was 2 because `1 + 3` and `7 + -3` are valid pairs which sums up to `TOTAL=4`.
* When one pair is formed, you should not count any of its values again
* Also, you are not allowed to add any value that is not present in the ARRAY.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest in bytes wins
All values will be between your language's int min-max.
### Another cases
```
9, [1,2,3,5,4,6,7,-10] => 3 // [2,7] [3,6] [5,4]
0, [] => 0 //
0, [1,-2,0,-1,2] => 2 // [1,-1] [-2,2]
5, [5,5,5,0,-1,1,-5] => 1 // [5,0]
3, [7,-7,8,3,9,1,-1,5] => 0 //
2, [1,1] => 1 // [1,1]
2, [1,1,1,1,1] => 2 // [1,1] [1,1]
4, [1,3,3,3] => 1 // [1,3]
```
[Answer]
# Pyth, 9 bytes
```
/sM{.cSE2
```
[Test suite](https://pyth.herokuapp.com/?code=%2FsM.c%7BE2&test_suite=1&test_suite_input=9%0A%5B1%2C2%2C3%2C5%2C4%2C6%2C7%2C-10%5D%0A0%0A%5B%5D%0A0%0A%5B1%2C-2%2C0%2C-1%2C2%5D%0A5%0A%5B5%2C5%2C5%2C0%2C-1%2C1%2C-5%5D%0A3%0A%5B7%2C-7%2C8%2C3%2C9%2C1%2C-1%2C5%5D&debug=0&input_size=2)
Takes the number and array newline separated.
**Explanation:**
```
/sM{.cSE2
/sM{.cSE2Q Implicit variable introduction.
Implicit: Q = eval(input())
E Take the array as input.
S Sort the input.
.c 2 Form all ordered pairs.
{ Deduplicate.
sM Map each to its sum.
/ Q Count the number of occurrences of Q in the resulting list.
```
[Answer]
# R, 48 bytes
```
function(x,y)sum(colSums(combn(unique(x),2))==y)
```
[Answer]
# Pyth - 13 bytes
```
l{SMfqQsT.PE2
```
[Test Suite](http://pyth.herokuapp.com/?code=l%7BSMfqQsT.PE2&test_suite=1&test_suite_input=4%0A%5B1%2C3%2C7%2C1%2C-3%5D%0A9%0A%5B1%2C2%2C3%2C5%2C4%2C6%2C7%2C-10%5D%0A0%0A%5B%5D%0A0%0A%5B1%2C-2%2C0%2C-1%2C2%5D%0A5%0A%5B5%2C5%2C5%2C0%2C-1%2C1%2C-5%5D%0A3%0A%5B7%2C-7%2C8%2C3%2C9%2C1%2C-1%2C5%5D&debug=0&input_size=2).
[Answer]
# Julia, 48 bytes
```
x->n->count(p->sum(p)==n,combinations(โช(x),2))
```
This is an anonymous function that accepts an array and an integer and returns an integer. To call it, assign it to a variable and call like `f(x)(n)`.
We get all combinations of size 2 from the unique values in the input array and for each pair test whether the sum is equal to the input integer. We count all such cases and return the result.
[Try it online!](http://julia.tryitonline.net/#code=Zj14LT5uLT5jb3VudChwLT5zdW0ocCk9PW4sY29tYmluYXRpb25zKOKIqih4KSwyKSkKCmZvciB0ZXN0IGluIFsoOSwgWzEsMiwzLDUsNCw2LDcsLTEwXSwgMyksCiAgICAgICAgICAgICAoMCwgW10sIDApLAogICAgICAgICAgICAgKDAsIFsxLC0yLDAsLTEsMl0sIDIpLAogICAgICAgICAgICAgKDUsIFs1LDUsNSwwLC0xLDEsLTVdLCAxKSwKICAgICAgICAgICAgICgzLCBbNywtNyw4LDMsOSwxLC0xLDVdLCAwKV0KICAgIHByaW50bG4oZih0ZXN0WzJdKSh0ZXN0WzFdKSA9PSB0ZXN0WzNdKQplbmQ&input=) (includes all test cases)
[Answer]
## Matlab(38)
```
@(a,b)nnz(sum(nchoosek([b,.5],2)')==a)
```
* the 0.5 part is a dodge for second test case
---
cropped by 2 bytes following Alex' comment.
[Answer]
# JavaScript (ES6), ~~112~~ ~~67~~ ~~59~~ 52 bytes
```
(a,b)=>{c=0;for(i of a)a.map(j=>c+=i+j==b);return c}
```
Because of amazing `for-of` loops of ES6, I was able to shave off **42** bytes from my previous solution!
**Update** : Thanks to @user6188402 for helping me shave off 3 bytes!
**Update** : Thanks to @Bรกlint for helping me shave off 15 bytes!
[Try it Online!](http://jsbin.com/rewerubixu/edit?js,console)
**Note** : *This fails for repeating numbers.*
] |
[Question]
[
Imagine you have an infinite sequence of the alphabet repeated infinitely many times:
```
abcdefghijklmnopqrstuvwxyzabcd...
```
You start at index `0`, which corresponds to the letter `a`, and the `should_write` boolean flag is `False`.
The input is a list or string of single-digit numbers. For each number `n` in the input, you should:
* Print (or add to the return value) the `n-th` item of the list if the `should_write` flag is set to `True`
* If `n` is `0`, swap the `should_write` flag.
* Otherwise move (jump) the index `n` places forward.
At the end of the input, stop (and return the result if using a function).
**Input**
A sequence of digits (list or string).
**Output**
The text that comes out after applying the above procedure.
**Examples**
```
>>> g('99010')
st
>>> g('100')
b
>>> g('2300312')
f
>>> g('390921041912042041010')
mvxyptvab
>>> g('1')
>>> g('1045')
bf
>>> g('33005780')
g
>>> g('100100102')
bcd
>>> g('012')
ab
```
[Answer]
## Python 3, 60
```
i=b=0
for c in input():b and print(chr(97+i%26));b^=c<1;i+=c
```
Takes a list of numbers and prints the chars on separate lines.
Basically just follows the instructions. The index is `i` and the `should_write` flag is `b`. The expression `b and` short-circuits to print only when `b` is true.
[Answer]
# [Pip](http://github.com/dloscutoff/pip), 20 bytes
Takes a string of digits as command-line argument.
```
Fda{IyOz@id?i+:dY!y}
```
This code uses a number of Pip's preinitialized variables. `i` is initially `0`, `y` is initially `""` (falsy) and `z` contains the lowercase alphabet. `a` gets the first command-line arg.
```
Fda{ } For each digit d in a:
IyOz@i If y (the flag) is truthy, output letter of z at index i
Pip's cyclic indexing takes care of the infinite effect
d? If d is truthy (digit is nonzero),
i+:d then increment i by d;
Y!y otherwise, yank !y into y (thus swapping the flag)
```
An alternate way of swapping the flag would be `!:y`, with `!:` being a compute-and-assign operator just like `+:`.
```
C:\Users\dlosc> pip.py -e Fda{IyOz@id?i+:dY!y} 390921041912042041010
mvxyptvab
```
[Answer]
# CJam, 28 bytes
```
0q{~U{1$'a+o}&_!U^:U;+26%}/;
```
[Test it here.](http://cjam.aditsu.net/#code=0q%7B~U%7B1%24'a%2Bo%7D%26_!U%5E%3AU%3B%2B26%25%7D%2F%3B&input=390921041912042041010)
Nothing really special here. Like xnor, I don't have a string of letters but simply a running total (mod 26) which I add to `a` when I need to print it. The `should_write` flag is kept track of in `U`.
[Answer]
# R, 73 bytes
Once I got it sorted in my head:)
```
(letters[cumsum(a<-head(scan()),-1)%%26+1])[which(cumprod(-(a<1)*2+1)<0)]
```
This takes a vector of integers from STDIN and returns a vector of letters.
Ungolfed and explanation
```
a <- head(scan()),-1) # get integers from stdin and drop last one
a <- cumsum(a) %% 26 + 1 # do the cumulative sum of the vector to use as a vector of letter indexes
l <- letters[a] # vector of potential letters
p <- -(a<1)*2+1 # turns 0's into -1 and everything else into 1
p <- cumprod(p) # the cumlative prod then creates a vector of on and off values
f <- which(p<0) # index values of the returned characters
l[f] # return vector of characters
```
Tests
```
> (letters[cumsum(a<-head(scan(),-1))%%26+1])[which(cumprod(-(a<1)*2+1)<0)]
1: 9 9 0 1 0
6:
Read 5 items
[1] "s" "t"
> (letters[cumsum(a<-head(scan(),-1))%%26+1])[which(cumprod(-(a<1)*2+1)<0)]
1: 1 0 0
4:
Read 3 items
[1] "b"
> (letters[cumsum(a<-head(scan(),-1))%%26+1])[which(cumprod(-(a<1)*2+1)<0)]
1: 2 3 0 0 3 1 2
8:
Read 7 items
[1] "f"
> (letters[cumsum(a<-head(scan(),-1))%%26+1])[which(cumprod(-(a<1)*2+1)<0)]
1: 1
2:
Read 1 item
character(0)
> (letters[cumsum(a<-head(scan(),-1))%%26+1])[which(cumprod(-(a<1)*2+1)<0)]
1: 1 0 4 5
5:
Read 4 items
[1] "b" "f"
> (letters[cumsum(a<-head(scan(),-1))%%26+1])[which(cumprod(-(a<1)*2+1)<0)]
1: 0 1 2
4:
Read 3 items
[1] "a" "b"
>
```
[Answer]
# JavaScript (ES6) 76
(note: the fromCharCode function is so lengthy that for lowercase letters it's better a conversion to base 36)
Test running the snippet below in any EcmaScript 6 compliant browser
```
g=l=>l.replace(/./g,n=>[f?(p%26+10).toString(36):'',-n?p-=-n:f=!f][0],p=f=0)
console.log=x=>O.innerHTML+=x+'\n'
;['99010','100','2300312','390921041912042041010','1','1045','33005780','100100102','012']
.forEach(t=>console.log(t+' ['+g(t)+']'))
```
```
<pre id=O></pre>
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 59 bytes
Port of [xnor's Python answer](https://codegolf.stackexchange.com/a/60693/11261).
```
->a{i=0
b=p
a.map{b&&$><<(97+i%26).chr
b=!b if _1<1
i+=_1}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3rXXtEqszbQ24kmwLuBL1chMLqpPU1FTsbGw0LM21M1WNzDT1kjOKgNKKSQqZaQrxhjaGXJnatvGGtbVQI_TcoqONdSx1DIDYSMcQSJsASUsgNgKzjaAiBiAcGwvRtWABhAYA)
] |
[Question]
[
# The Challenge
Create a program that brute-force\* decodes the MD5-hashed string, given here:
`92a7c9116fa52eb83cf4c2919599c24a` which translates to `code-golf`
# The Rules
1. You may *not* use any built-in functions that decode the hash for you if
the language you choose has such.
2. You may *not* use an online service to decode the hash for you.
3. This is code-golf, the program that accomplishes
the task in the shortest amount of *characters* wins.
**Good luck. May the brute-force be with you.**
\*[Brute-Force](http://en.wikipedia.org/wiki/Brute-force_attack) definition: looping from `a`-`zzz..` including `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=[]\;',./~!@#$%^&*()_+{}|:"`<>?` in a string, hashing it, and testing it against the hash given until the correct string that has been hashed has been found. Print the string to the program's output stream.
[Answer]
## Haskell, 101 characters
```
import Data.Hash.MD5
main=interact$ \m->head.filter((==m).md5s.Str)$iterate([' '..'~']:)[]>>=sequence
```
Use it like so:
```
& ghc -O2 -o brute 42043-BruteForce.hs
& echo -n c-g | md5
bc098aea57599de26c8f17a9edbd492e
& echo -n bc098aea57599de26c8f17a9edbd492e | ./brute
c-g
```
This requires the common package `MissingH`.
[Answer]
# PHP (155)
```
<?$a=[];function r($s){for($c=32;$c<127;$c++){$k=$s+chr($c);md5($k)=="92a7c9116fa52eb83cf4c2919599c24a"?die($k):array_push($a,$k)}r(array_shift($a))}r('');
```
Ungolfed:
```
<?
$a=[];
function r($s){
for($c=32;$c<127;$c++){
$k=$s+chr($c);
md5($k)=="92a7c9116fa52eb83cf4c2919599c24a" ? die($k) : array_push($a,$k);
}
r(array_shift($a));
}
r('');
```
What it does is define an empty array $a, which will be our operations-to-do-later array. r is a recursive function and $s is the current string we're working with. We begin with an empty string, and loop through all the characters noted above, which are ASCII 32 to 127, and checking them all. While that happens, all of those are pushed onto the end of the array. Then, when all of the 1-length strings are done and all of them are put into the array, we now call r again with the first element in the array. Then, $s will be set to ASCII 32, and it will loop through 2 character strings that start with that character, checking them all and putting them at the end of the array. Since they are at the end, the next call to r will check ASCII 33 rather than them, since it is now the first one in the array. This prevents an infinite loop from occuring where it checks one ASCII 32 and then 2 ASCII 32's and then 3 ASCII 32's... etc.
[Answer]
# Python (182 characters)
```
import sys,string as c,hashlib as h,itertools as i
m=sys.stdin.read()
j=''.join
print(next(j(v)for n in i.count()for v in i.product(*n*(c.printable,))if h.md5(j(v)).hexdigest()==m))
```
Example:
```
$ echo -n Hi! | md5sum
5360706c803a759e3a9f2ca54a651950 -
$ echo -n 5360706c803a759e3a9f2ca54a651950 | python2.7 decode.py
Hi!
```
The `itertools` module does most of the work, with `.count()` responsible for gradual escalation. The nested generator expression is filtered until we get a match on the MD5 hash.
[Answer]
# bash - about 105 characters, not the greatest at golfing bash scripts!
Requires `makepasswd` and `openssl`.
```
until [ "$Y" = "$3" ]
do
X=($(makepasswd --string=$1 --chars=$2))
Y=($(echo -n $X | md5sum))
done
echo $X
```
You use it by supplying three arguments: *./reverse-md5 character-set length-of-password md5-hash-to-match*, e.g.:
```
$ ./reverse-md5 'ab' 4 54a8723466e5d487247f3d93d51c66bc
abba
```
Hoorah, have found the name of an obscure Swedish pop band!
Note that this is a directed attack in that you have some idea of the characters used and the length of the password.
So you could use the script in a directed attack as follows to complete the challenge:
```
$ ./reverse-md5 'cdefglo-' 9 92a7c9116fa52eb83cf4c2919599c24a
[wait a long time]
code-golf
```
Or as a brute force attack, run in parallel like this:
```
$ for L in `seq 1 20` ; do ./reverse-md5 '!"#$%&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~' $L 92a7c9116fa52eb83cf4c2919599c24a & done
[wait a really long time!]
code-golf
```
Which, depending on the hardware, may give you an answer faster than going sequentially from `'!'` to `'~~~...'`
[Answer]
# [Hassium](http://HassiumLang.com), 138 Bytes
```
use Math;func main(){d=["laptop","code-golf"];p="312f91285e048e09bb4aefef23627994";foreach(l in d){if(Math.hash("md5",l)==p)println(l);}}
```
Expanded: <http://HassiumLang.com/Hassium/index.php?code=77bf67650e57549addd25daf7503db06>
[Answer]
# Perl, 75 + 18 = 93 bytes
This program contains nonprintable characters, so here's a hexdump:
```
00000000: 245f 3d31 3b73 7c30 2a28 2e29 7c24 263d $_=1;s|0*(.)|$&=
00000010: 7e79 3d20 2d7e 3d21 2d7e 203d 722e 3178 ~y= -~=!-~ =r.1x
00000020: 2124 317c 6520 7768 696c 6520 6d64 3528 !$1|e while md5(
00000030: 245f 296e 6527 92a7 c911 6fa5 2eb8 3cf4 $_)ne'....o...<.
00000040: c291 9599 c24a 273b 7361 79 .....J';say
```
This program requires the command line argument `-MDigest::MD5=md5` (an 18 byte penalty, 17 for the argument and 1 for the space separating it from the other arguments).
## Explanation
Here's the program with whitespace and comments added and the binary string replaced with `'โฆ'`:
```
$_ = 1; # $_ is the string to check; start at '1'
s|0*(.)| # replace a string of leading 0s plus 1 character
$& =~ y= -~=!-~ =r # by rotating 1 printable ASCII character forward
. 1 x !$1 # and appending a 1 if the replaced section ends in 0
|e # (the previous two lines are a Perl expression)
while md5($_) ne 'โฆ'; # while it has the wrong md5
say # print out the value of $_ we found
```
The basic trick here is that although we want to check from shortest to longest, there's no particular reason to check the characters in ASCIIbetical order. As a result, we check in the order from `1` to `~` then to `0`. To do this, we repeatedly increment the first character after the leading 0s, and reset the leading 0s back to leading 1s (which we can do by incrementing every character up to and including the character after the leading 0s). If the string consists entirely of 0s, we need to append a new 1 to the end; we do this via checking to see if the string consists entirely of 0s via seeing if the last matched character in the regex is `0` (as the `0*` match is greedy, this will only happen if there are no non-`0` characters in the string).
The reason `1` and `0` are picked as the first and last character in the range is that a) they don't need quoting (the string `"1"` can be written as `1` because Perl doesn't really distinguish between strings and integers), and b) that Perl has a very short way (`!`) of checking a single-character string for equality with `0` (Perl has three falsey values: `undef`, `""`, and `"0"`, with all other values being truthy).
Note that we have no reason to translate the MD5 hash in question into hexadecimal; it's specified in the question, and so we can pack it into binary ourselves and just compare the binary representations directly. Perl's builtin for producing an md5 hash in binary has a shorter name than the hexadecimal equivalent, and the binary representation takes up half the space in the source, so this is a win in two different ways.
## Verification
I tested the program with the hash of the string `abc` inserted into the source code rather than the hash of the string `code-golf`, and it found the correct answer in 1.3 seconds. (It's unlikely to be able to reverse the hash of `code-golf` in a reasonable length of time, due to the need to check a substantial subset of the printable ASCII range.)
] |
[Question]
[
**From now on considering the word "fuck" to be non-profane would be a good idea**
Make the smallest compiler or an interpreter for the Brainfuck variant, Boolfuck. It has to be executable in Windows, DOS, or a Unix operating system (so Linux, Mac, OpenBSD etc). Boolfuck is very similar to Brainfuck, and a complete definition can be found [here](http://samuelhughes.com/boof/).
# Differences from Brainfuck
1. Works with bits not bytes (each cell is a single bit)
2. The output character is `;` not `.`
3. The input is read in little endian mode and reads a single bit at a time.
4. Output is stored to a stream, then outputted in little endian mode
# Rules
1. Use **bits** for the cells, not bytes
2. Support the complete list of operations from the [official definition](http://samuelhughes.com/boof/index.html):
```
+ Flips the value of the bit under the pointer.
, Reads a bit from the input stream, storing it under the pointer.
The end-user types information using characters, though. Bytes
are read in little-endian order; the first bit read from the
character a, for instance, is 1, followed by 0, 0, 0, 0, 1, 1,
and finally 0.
; Outputs the bit under the pointer to the output stream. The bits
get output in little-endian order, the same order in which they
would be input. If the total number of bits output is not a
multiple of eight at the end of the program, the last character
of output gets padded with zeros on the more significant end. If
the end-of-file character has been input, outputs a zero to the
bit under the pointer.
< This moves the pointer left by one bit.
> This moves the pointer right by one bit.
[ If the value under the pointer is zero, jumps forward, just past
the matching ] character.
] Jumps back to the matching [ character.
```
Any character not in the official definition is ignored.
3. The program must start in the middle of the tape, not on an end.
4. The tape must be unbounded in size (infinite in both directions).
Here is a sample Boolfuck program; it outputs `Hello, world!`:
```
;;;+;+;;+;+;
+;+;+;+;;+;;+;
;;+;;+;+;;+;
;;+;;+;+;;+;
+;;;;+;+;;+;
;;+;;+;+;+;;
;;;;;+;+;;
+;;;+;+;;;+;
+;;;;+;+;;+;
;+;+;;+;;;+;
;;+;;+;+;;+;
;;+;+;;+;;+;
+;+;;;;+;+;;
;+;+;+;
```
[Answer]
## Perl - 171 bytes
```
#!perl -0
%h=qw(< --$p > ++$p + $$p^=1 [ while($$p){ ] } ; $o|=$$p<<$g++;$g&=7or$o=!print+chr$o , $f&=7or$_=getc;$$p=1&ord>>$f++);$p=-1e9;eval<ARGV>=~s/./$h{$&};/gr;$g&&print+chr$o
```
Counting the shebang as 1 byte.
This translates the source into perl, and then evaluates the translation. The target program is taken as a command line argument, input sent to the program should be piped via stdin.
Sample usage:
```
$ perl boolf.pl hello.blf
Hello, world!
```
---
**Details**
Each of the commands is translated as follows:
`<` โ `--$p;`
`>` โ `++$p;`
`+` โ `$$p^=1;`
`[` โ `while($$p){`
`]` โ `}`
`;` โ `$o|=$$p<<$g++;$g&=7or$o=!print+chr$o;`
`,` โ `$f&=7or$_=getc;$$p=1&ord>>$f++;`
Negative integers are valid variable names, which is exploited here. `$p`, the cell pointer, is initialized as *-1000000000*, which is approximately at the center of the valid range, *-2147483648 .. -1*.
I've violated the specification in one regard: output is not printed all at once at the end, but rather as soon as a full byte has been collected. It's slightly longer this way, but I think it's more useful, as it allows for interactive scripts. For example, the Rot13 program below can be run in 'interactive mode', terminating the program with an eof char (`^D` on linux, `^Z` on windows).
>
> **Edit - Demonstration of Endianness**
>
>
> There seems to be some doubt as to whether this interpreter reads bits in the proper (little-endian) order. I offer the following Boolfuck program, which reads a total of *8* bits, one at a time, and outputs each value read as its numeric ascii representation (`0` outputs character *48*, `1` outputs character *49*). Each value is output entirely before the next bit is even read.
>
>
>
> ```
> ,;[+];;;+;;+;;
> ,;[+];;;+;;+;;
> ,;[+];;;+;;+;;
> ,;[+];;;+;;+;;
> ,;[+];;;+;;+;;
> ,;[+];;;+;;+;;
> ,;[+];;;+;;+;;
> ,;[+];;;+;;+;;
>
> ```
>
> Sample usage:
>
>
>
> ```
> $ echo a | perl boolf.pl test.blf
> 10000110
>
> ```
>
> From the problem description:
>
> *"Bytes are read in little-endian order; the first bit read from the character `a`, for instance, is 1, followed by 0, 0, 0, 0, 1, 1, and finally 0."*
>
>
> According to this description, the bits are read in the proper order.
>
>
>
---
**Stress Testing**
First, a script to translate Brainfuck programs into Boolfuck:
```
#!perl -n0
%h = (
'+' => '>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<<',
'-' => '>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]<<<<<<<<<',
'<' => '<<<<<<<<<',
'>' => '>>>>>>>>>',
',' => '>,>,>,>,>,>,>,>,<<<<<<<<',
'.' => '>;>;>;>;>;>;>;>;<<<<<<<<',
'[' => '>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]',
']' => '>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]'
);
$o .= $h{$_} for /./g;
$o =~ s/<(?R)?>//g;
print $o
```
---
The Rot13 program from the [Brainfuck Wiki Page](http://en.wikipedia.org/wiki/Brainfuck) translates thusly (with slight modification for null byte eof, rather than 255):
```
,>,>,>,>,>,>,>,>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>+<<<<<<<<+[>+]
<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>>>>>>>>>>>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<
[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]+<<<<<<<<+[
>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>
>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]
>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+
<]>>>>>>>>>[+]<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<
]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[
<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>>[>]+<[+<]>>>>>>>>>[+]>[>]+<[+<]>>>>>>>>>[+]>>
>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]+<<<<<<<<+[>+]<[<]
>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>
>>>>>>>>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<
]>>>>>>>>>]<[+<]>>>>>>>>>>>>>>>>>>>[>]+<[+<]>>>>>>>>>[+]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>
>>>>>>>]<[+<]<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<
<<<+[>+]<[<]>>>>>>>>>]<[+<]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>+<<<<<<<<+
[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>[>]+<[+<]>>>>>>>>>[+]>>>>>>>>>+
<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>
>[+<<<<<<<<[>]+<[+<]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>
>[+<<<<<<<<[>]+<[+<]+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<
[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]
+<[+<]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>>>>>>>
>>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]+<<<<<<<
<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>
>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>
>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>
>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>
>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<
[>]+<[+<]>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>[
+<<<<<<<<[>]+<[+<]>>>>>>>>>>[>]+<[+<]>>>>>>>>>[+]>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]
>>>>>>>>>]<[+<]>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>[>]+<
[+<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]<<<<<<<<[>]+<[+<]>>>>>>
>>>[+]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>>>>>>>
>>>[>]+<[+<]>>>>>>>>>[+]>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]<<<<<<<<<<
<<<<<<<<<<<<<<<<<<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<
[+<]>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]<<<<<<<<
[>]+<[+<]>>>>>>>>>[+]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>
>>]<[+<]>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>+<<<
<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>+<<<
<<<<<+[>+]<[<]>>>>>>>>>[+]<<<<<<<<<<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+
<[+<]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>>>>>>>>
>>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>
>>>[+<<<<<<<<[>]+<[+<]<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]>>>>>>>>>>>>>>>>>>+<<<<<
<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>>>>>>>>>>>>>>>>>>>>>>>>>>>+
<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+
<]<<<<<<<<<<<<<<<<<[>]+<[+<]>>>>>>>>>[+]>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>
[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]+<<<<<<
<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<
<<+[>+]<[<]>>>>>>>>>]<[+<]<<<<<<<<;>;>;>;>;>;>;>;>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<
<<[>]+<[+<]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]+<
<<<<<<<+[>+]<[<]>>>>>>>>>[+]<<<<<<<<,>,>,>,>,>,>,>,>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]
```
On a 26 character string, this runs in approximately 0.17 seconds:
```
$ echo abcdefghijklmnopqrstuvwxyz | timeit perl boolf.pl rot13.blf
nopqrstuvwxyzabcdefghijklm
Elapsed Time: 0:00:00.171
```
---
The `squares.b` from [Daniel Cristofani's site](http://www.hevanet.com/cristofd/brainfuck/):
```
>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<
<<<[>]+<[+<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>>[>]+<
[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]
+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+
]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<
<<<<[>]+<[+<]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[
+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]>>>>>>>>>+<<
<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>[>]+<[+<]>>>>>>>>>[+]<<<
<<<<<<<<<<<<<<[>]+<[+<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>
>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>>[>]+<[+<]>>>>>>
>>>[+]>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<<<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<
+[>+]<[<]>>>>>>>>>]<[+<]>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]>>>>>>>>>>
>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]<<<<<<<<<<<<<<<<<[>]+<[+<]>>>>>
>>>>[+]>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[
+<]>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]
>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>[>]+<[+<]>>>
>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[
>]+<[+<]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>[>]+
<[+<]>>>>>>>>>[+]>>>>>>>>>>>>>>>>>>>[>]+<[+<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>[
+<<<<<<<<[>]+<[+<]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>+<<
<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>[>]+<[+<]>>>>>>>>>[+]<<<
<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<
<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]>>>>>>>>>>>>>>>>>>>>>>>>>>>+
<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]<<<<<<<<<<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<
<<[>]+<[+<]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]<<<<<<<<[>]+<[+<]>>
>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]
>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+
<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<<<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<
<<<<[>]+<[+<]>>>>>>>>>[+]>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>
+]<[<]>>>>>>>>>]<[+<]>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<<<<<<<<<<;>;>;>;>;>;>;>;<<<<<<<<+<
<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>
>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]
>>>>>>>>>[+]<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]+
<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+
<]>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+
<<<<<<<<[>]+<[+<]>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<
<<<<<[>]+<[+<]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<
]>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<
<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<
<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]
<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>
+]<[<]>>>>>>>>>[+]<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]
<[+<]>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]
<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[
+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>
>[+]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>+<<<<<<<<+[>+]<[<
]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]+<<<<<<<<+[>+]<[<]>>>>>>>>
>[+]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>[>]+<[+<
]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]<<<<<<<<<<<<<<<<<<+<<<<<<<
<+[>+]<[<]>>>>>>>>>]<[+<]>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]+<<<<<<<<+[>+]<[<]
>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<<+<<<<<<<<+[>+]<[<
]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>
>>>>>>]<[+<]<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]<
<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>>>>>>>>>+<<<<
<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>;>;>;>;>;>;>;>;<<<<<<<;>;>;>;>;>;>;>;<<<<<<
<;>;>;>;>;>;>;>;>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]
```
Runs in about 2.4s:
```
$ timeit perl boolf.pl out.dat
0
1
4
9
16
25
36
49
64
81
100
121
144
169
196
225
256
289
324
361
400
441
484
529
576
625
676
729
784
841
900
961
1024
1089
1156
1225
1296
1369
1444
1521
1600
1681
1764
1849
1936
2025
2116
2209
2304
2401
2500
2601
2704
2809
2916
3025
3136
3249
3364
3481
3600
3721
3844
3969
4096
4225
4356
4489
4624
4761
4900
5041
5184
5329
5476
5625
5776
5929
6084
6241
6400
6561
6724
6889
7056
7225
7396
7569
7744
7921
8100
8281
8464
8649
8836
9025
9216
9409
9604
9801
10000
Elapsed Time: 0:00:02.421
```
[Answer]
# Python (531 byte compiler)
This is a source-to-source compiler: it compiles Boolfuck to Python. Takes input from a file as its first argument, outputs Python code to file `o` in the current dict.
```
exec"eJxdUs1u8yAQvOcpEBez/lNS9RDZpS+C+CQ3xg5RwlKMmkTV9+5l7bZue2RmZ4YdGAJe2HSfmL14DDFvndy2o0RvnOjC+KZ2Gupgul5A20vFh7/zM2CjCRHxvMI+2UQ5mZh0KJXmuu2LpD9J9WKdwNCLO4Bqdk210wMGdmfWsSn21n3G6dbKS+eFdbE8HLskytWtyLZZfk53u0G1J9mNZCcNwO3AS54OIzPnyXCuN8QfiB8bynY5Z7wQPP6T7/4/zRdcysMyHuuu74UHOzBbe/QCCGYxXeaCbyYxS8C3AJOjJ/OoiWlXxldyR9DTD6hYoOcVuh7t2bDFoSFOrRxPy7tCPrJfMKtmQK/AdjN3ijLL6hOmhqivKYbyqzcEmOtHNTRDsdeMKhkoM3RuNGJbUpcI5T4l0ka47D7XLPbVzKr0QpB4H5LlV9LhGChBvKqGXrB8ACDvV/JGSK89/6A8w2sG9TWkDyKyzae2B/gAiGHBlw".decode('base64').decode('zip')
```
If you really really mind the cheating with the zip and all that, the actual code is 631 bytes long (longer than the original Brainfuck compiler, but shorter than the original False compiler):
```
from sys import*;n=0;g=open(argv[1]).read();d=["from sys import*;from itertools import*;p=0;t=set();o=[]"];d+=["j=[bin(ord(y))[:1:-1]for y in stdin.read()];i=map(int,chain(*[x+'0'*len(x)-8for x in j]))"if","in g else""]
for c in g:d+=[n*" "+("t^={p}"if"+"==c else"t.add(p)if i.pop()else t.remove(p)"if","==c else"o+=[p in t]"if";"==c else"p-=1"if"<"==c else"p+=1"if">"==c else"while p in t:"if"["==c else"")];n+=4 if"["==c else -4 if"]"==c else 0
d+=["o=''.join(map(str,map(int,o)));o=[o[f:f+8] for f in range(0,len(o),8)];o+=[o.pop()+'0'*(8-len(o[-1]))];print''.join(chr(int(q[::-1],2))for q in o)"];open(*'ow').write('\n'.join(d))
```
>
> This is possibly the fugliest python I've ever written, even though the `open(*'ow')` instead of `open('o','w')` made me feel really smart ;)
>
>
>
With a (slightly) better layout:
```
import sys
n = 0
g = open(sys.argv[1]).read()
d = ["from sys import*;from itertools import*;p=0;t=set();o=[]"]
d += [
"j=[bin(ord(y))[:1:-1]for y in stdin.read()];i=map(int,chain(*["
"x+'0'*len(x)-8for x in j]))" if "," in g else ""]
for c in g:
d += [n * " " + (
"t^={p}" if "+" == c
else "t.add(p)if i.pop()else t.remove(p)" if "," == c
else "o+=[p in t]" if ";" == c
else "p-=1" if "<" == c
else "p+=1" if ">" == c
else "while p in t:" if "[" == c
else "")]
n += 1 if "[" == c else -1 if "]" else 0
d += [
"o=''.join(map(str,map(int,o)));o=[o[f:f+8] for f in range(0,len(o),"
"8)];o+=[o.pop()+'0'*(8-len(o[-1]))];print''.join(chr(int(q[::-1],"
"2))for q in o)"]
open(*'ow').write('\n'.join(d))
```
And lastly, the example output for the "Hello World" test you gave:
```
from sys import*;from itertools import*;p=0;t=set();o=[]
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
o+=[p in t]
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o+=[p in t]
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
t^={p}
o+=[p in t]
o=''.join(map(str,map(int,o)));o=[o[f:f+8] for f in range(0,len(o),8)];o+=[o.pop()+'0'*(8-len(o[-1]))];print''.join(chr(int(q[::-1],2))for q in o)
```
A memfiller, `+[>+]` also works really well (and quick, consuming about 2 gigs in 10 seconds):
```
from sys import*;from itertools import*;p=0;t=set();o=[]
t^={p}
while p in t:
p+=1
t^={p}
o=''.join(map(str,map(int,o)));o=[o[f:f+8] for f in range(0,len(o),8)];o+=[o.pop()+'0'*(8-len(o[-1]))];print''.join(chr(int(q[::-1],2))for q in o)
```
[Answer]
# Perl, 325 bytes
```
undef$/;open C,'<',pop;@I=split//,unpack'b*',<>;@C=split//,<C>;while($c<@C){$_=$C[$c];$D=\$D{$d};$$D=!$$D if/\+/;$$D=shift@I if/,/;/</&&$d--;/>/&&$d++;$O.=$$D?1:0if/;/;if(/\[/&&!$$D){$L=1;while($L){$L++if$C[++$c]eq'[';$L--if$C[$c]eq']'}}if(/]/){$L=1;while($L){$L++if$C[--$c]eq']';$L--if$C[$c]eq'['}$c--}$c++}print pack'b*',$O
```
The script `boofuck.pl` is an interpreter for Boolfuck. The argument is a file name that contains a Boolfuck program. It reads STDIN and outputs to STDOUT.
**Remarks:**
* I have ignored the last sentence of the description for operator `;`, because I haven't understood it:
>
> If the end-of-file character has been input, outputs a zero to the
> bit under the pointer.
>
>
>
* The script always reads STDIN, even if the boolfuck program does not contain a `,` operator.
**Ungolfed:**
```
# name conventions:
# "I" for input:
# @I is array with "0" and "1" for the bits in STDIN
# "O" for output:
# $O is output string with "O" and "1" for the output bits
# "C" for code:
# @C is array of code byts
# $c is code pointer
# "D" for data:
# %D is "infinite" data band, hash is used to allow negative indexes
# $d is data pointer
undef $/; # without input line separator <> reads the whole file.
open C, '<', pop; # open program file, given as command line argument
@I = split //, #/# split input bit string into array of (bit) characters
unpack 'b*', # convert input string into bit string with 0 and 1
<>; # get STDIN
@C = split //, #/# split program code string in byte array
<C>; # get program code as string
while ($c < @C) { # finished if the end of the program code is reached
$_ = $C[$c]; # $_ contains operator
$D = \$D{$d}; # $D is a reference to the data bit under the data pointer
# case '+':
$$D = !$$D if /\+/; # flip data bit value under the data pointer
# case ',':
$$D = shift @I if /,/; #/# store input bit to data bit under the pointer
# case ';':
$O .= $$D ? 1 : 0 if /;/;
#/# append current data bit to the output
# case '<':
/</ && $d--; #/# move data pointer to the left
# case '>':
/>/ && $d++; #/# move data pointer to the right
# case '[':
if (/\[/ && !$$D) { # if current data bit is unset,
# jump to the matching ']'
$L = 1; # each '[' increments $L,
# each ']' decrements $L
while ($L) { # $L is zero in case of a matching ']'
$L++ if $C[++$c] eq '[';
$L-- if $C[$c] eq ']'
}
# at the end of the outer loop, the code pointer is automatically increased
# to get right after the matching ']'
}
# case ']':
if (/]/) { # jump back to the matching '['
$L = 1;
while ($L) {
$L++ if $C[--$c] eq ']';
$L-- if $C[$c] eq '['
}
$c-- # at the end of the outer loop the code pointer
# is increased; therefore the code pointer is
# decreased to get right at the matching '['
}
# else:
# ignore other characters
# continue:
$c++ # increment code pointer
}
print pack'b*', $O # convert output bits to bytes and print result
```
**Examples:**
* "Hello World" example from the question
```
perl boolfuck.pl helloworld.boolfuck </dev/null
```
Result (with new line at the end):
```
Hello, world!
```
* Example that reverses the input from the [Boolfuck website](http://samuelhughes.com/boof/):
```
>,>,>,>,>,>,>,>,<<<<<<<<
>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]
>>>>>>>>>
>,>,>,>,>,>,>,>,<<<<<<<<
>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]
<<<<<<<<<
>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]
>;>;>;>;>;>;>;>;<<<<<<<<
<<<<<<<<<
>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]
```
Running it:
```
echo -ne "\nHello World" perl boolfuck.pl reverse.boolfuck
```
Result (with new line at the end):
```
dlroW olleH
```
] |
[Question]
[
Write a program which prints the sequence of prime numbers. The shortest solution wins!
All numbers must have a unary representation (not just in the output, but throughout the entire program). This could be a string of 1s, a list of 1s, Peano-style objects, etc.
No particular output format is required, as long as numbers are recognizable. `111`, `[1, 1, 1]`, and `S(S(S(0)))` are all acceptable representations of `3`, for example.
Examples of permissible operations:
* Appending or prepending a constant value to a string/list
* Deleting a constant number of elements from a string/list
* Comparing something with a constant, such as `"11"`
* Calling `is_empty` on a string/list
Examples of what's not allowed:
* Any operations on non-unary integers or floats, such as `+`, `%`, `==` or `<`
* Built-in functions which operate on multiple strings/lists, like `+` or `==`
* Importing or downloading a library which does unary arithmetic ;-)
Sample programs
* [Java, with Peano numbers](https://gist.github.com/dlubarov/7382360)
* [Python, with strings of 1s](https://gist.github.com/dlubarov/7382357)
[Answer]
## Haskell, 212 135 130 111 104 characters
```
xโก[1]=print x>>p x
xโกs@(_:r)=sโx where[]โ[]=p x;_โ[]=xโกr;[]โy=sโy;(_:t)โ(_:y)=tโy
p x=(1:x)โกx
main=p[1]
```
The sieve was fun to implement, but simple exhaustive remainder checking is smaller. Strictly adheres to the terms. Unary numbers are represented as lists of 1.
First ten primes:
```
& runhaskell 13159-UnaryPrimes.hs | head
[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,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,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,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
```
No library functions are used at all in the computation. In fact, the only library function used is `print`, which you can't get away from since you need some library function to output.
[Answer]
## C, 220 chars
```
o(void**n){putchar(n?33:10);n&&o(*n);}
d(void**a,void**b,void**c){return a?d(*a,b,c?*c:*b):c;}
q(void**a,void**b){return a?q(*a,*b):b;}
p(a,s){return!q(&s,a)||d(a,&s,0)&&p(a,&s);}
z;
e(n){p(&n,&z)&&o(&n);e(&n);}
main(){e(&z);}
```
Explanations:
1. Numbers are represented as linked lists. `NULL` is 0, a pointer to `N` is `N+1`.
2. `e` enumerates numbers by calling itself with `&n`, i.e. with `n+1`. It uses `p` to test for primality and `o` to print.
3. `p(a,s)` tests if `a` is prime, checking divisors starting from `s`.
4. `q(a,b)` returns false if the numbers are equal. It only works for `a<=b`.
5. `d(a,b,0)` returns false if `b` divides `a`. The 3rd parameter is for recursion.
6. `o(n)` prints `n` exclamation marks, followed by a newline.
[Answer]
## Perl 39 bytes
```
$_.=1while/^(11+)\1+$/||print$_||=11,$/
```
Interestingly enough, a well-known Perl primality test actually *relies* on unary logic.
[Answer]
# Mathematica, 81 chars
```
a=s@s@0;b={};While[1<2,Print@a;b~AppendTo~a;While[Or@@((a//.#:>0)==0&/@b),a=s@a]]
```
### Output:
>
> s[s[0]]
>
> s[s[s[0]]]
>
> s[s[s[s[s[0]]]]]
>
> s[s[s[s[s[s[s[0]]]]]]]
>
> s[s[s[s[s[s[s[s[s[s[s[0]]]]]]]]]]]
>
> ......
>
>
>
### Explanation:
Numbers are represented as Peano numbers. For example, `s[s[0]]` means `2`. I use suffix notation in my code. `s@s@0` is just short for `s[s[0]]`.
`a//.#:>0` repeatedly replace the pattern `#` in `a` with `0`. Both `a` and `#` in this expression are Peano numbers. In fact, it is equivalent to `a mod #`. For example, `s[s[s[0]]]]]//.s[s[0]]:>0` returns `s[0]`. So `(a//.#:>0)==0` if and only if `a` is divisible by `#`.
[Answer]
## Action Script 3 | Many bytes
```
var endOfTheWorld:Object = new Object();
var timeToEndOfTheWorld:Number = 1;
while(!endOfTheWorld){
var busted:boolean = false;
timeToEndOfTheWorld++;
for (var k:Object in endOfTheWorld) {
if(timeToEndOfTheWorld % Number(k) == 0){
busted = true;
break;
}
}
if(busted){
continue;
}
timeToEndOfTheWorld[timeToEndOfTheWorld] = timeToEndOfTheWorld;
trace(timeToEndOfTheWorld);
}
```
**P.S**
*If you think I got wrong with the time to end of the world, then prove it ;)*
] |
[Question]
[
In this challenge we are going to consider lists of integers such that for every member \$x\$ at index \$i\$ then the indexes \$i+x\$ and \$i-x\$ have the value \$x+1\$ or are out of bounds for the list. We will call these trampoline lists.
If we play around with these for a while we can notice that if we start a list with a certain value there is a limit on how long the list can be. For example let's start with `3` at the first value.
```
[3,...
```
Now we want to make this as long as possible. If we make it 4 long or longer we know the 4th value has to be `4`.
```
[3,?,?,4,...
```
That tells us that the 8th value (if it exists) has to be `5`
```
[3,?,?,4,?,?,?,5,...
```
That tells us the value at 3 is `6`
```
[3,?,6,4,?,?,?,5,...
```
Which tells us the value at 9 is `7`
```
[3,?,6,4,?,?,?,5,7,...
```
Which tells us the value at 2 is `8`
```
[3,8,6,4,?,?,?,5,7,...
```
Which tells us the value at 10 is `9`
```
[3,8,6,4,?,?,?,5,7,9...
```
Which tells us the value at 1 is `10`. But we already filled in that as `3`. So there can't be a 10th value otherwise things break down. The longest it can ever be is 9. That tells us that the maximal trampoline list starting with 3 looks like:
```
[3,8,6,4,?,?,?,5,7]
```
Where the `?`s can take on multiple values.
# Task
Given a postive integer \$n\$ as input output a maximal valid trampoline list starting with \$n\$.
This is a [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge, see the tag wiki for a description on defaults for IO. This challenge follows the defaults there.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your program's source code as measured in bytes.
# Test cases
In the first column we have the input. In the second we have a template with `?`s where there are multiple possible correct outputs. In the last we have an example of a correct output for the given input.
```
1 [1,2,?] [1,2,1]
2 [2,5,3,?,?,4] [2,5,3,4,2,4]
3 [3,8,6,4,?,?,?,5,7] [3,8,6,4,6,6,3,5,7]
4 [4,11,9,7,5,?,?,?,?,6,8,10] [4,11,9,7,5,7,7,8,4,6,8,10]
5 [5,14,12,10,8,6,?,?,?,?,?,7,9,11,13] [5,14,12,10,8,6,9,9,10,11,5,7,9,11,13]
```
If your answer matches the template *and* is a valid trampoline list it is correct. You should not output the template itself.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ร3แน+รษRแน;$m2;@
```
A monadic Link that accepts a positive integer and yields a longest trampoline as a list of positive integers.
**[Try it online!](https://tio.run/##ASAA3/9qZWxsef//w5cz4bmWK8OXyZdS4bmaOyRtMjtA////NQ "Jelly โ Try It Online")**
### How?
Trampolines are \$3n\$ long, start with \$n\$ and are then filled at the leftmost then rightmost available slots starting at \$3n-1\$ descending until \$n\$ slots are left, which need filling with numbers that will go out of bounds in both directions.
i.e. the template is:
```
[n, 3n-1, 3n-3, ..., <n ?'s>, ..., 3n-4, 3n-2]
```
The code starts with a list from \$1\$ to \$3n-1\$ and adds \$3ni\$ to the entries at indices \$i\leq n\$ (the ones that will end up at the `?`s in the template). It then prefixes this with its reverse, appends the forward version, discards every other element, and prefixes with \$n\$ to give a trampoline.
```
ร3แน+รษRแน;$m2;@ - Link: integer, n e.g. 3
ร3 - multiply (n) by three 9
R - range (n) [1,2,3]
ษ - last three links as a dyad:
แน - pop (3n) [1,2,3,4,5,6,7,8]
ร - (3n) multiply (range n) [9,18,27]
+ - add [10,20,30,4,5,6,7,8]
$ - last two links as a monad:
แน - reverse [8,7,6,5,4,30,20,10]
; - concatenate [8,7,6,5,4,30,20,10,10,20,30,4,5,6,7,8]
2 - two
m - modulo slice [8, 6, 4, 20, 10, 30, 5, 7]
@ - with swapped arguments:
; - (n) concatenate [3,8,6,4,20,10,30,5,7]
```
[Answer]
# JavaScript (ES6), 70 bytes
```
f=(n,i=(a=Array(w=n*3).fill(w),0))=>a[i]?f(n+1,i-n,f(n+1,i+=a[i]=n)):a
```
[Try it online!](https://tio.run/##ZchBCsIwEAXQvSeZ36bFWt0Io3iO4mKojYyESUnF4ukjghvJ7vEe8pJlTDo/G4u3KWfPZE6ZhC8pyZtWtqpH6zUEWuG2AJ9k0OvZk9Wd08bcTzV/nw04Sh6jLTFMbYh38tQBm//ZFdMXsy/mAOQP "JavaScript (Node.js) โ Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
i = ( // i = position, initialized to 0
a = Array( // build an array a[]
w = n * 3 // of w = n * 3 entries
).fill(w), // filled with w
0 //
) //
) => //
a[i] ? // if we're not out of bounds:
f( // do a recursive call:
n + 1, // use n + 1 as the value
i - n, // use i - n as the position
f( // do another recursive call:
n + 1, // use n + 1 as the value
i += // use i + n as the position
a[i] = n // and set a[i] to n
) // end of recursive call
) // end of recursive call
: // else:
a // return a[]
```
[Answer]
# [Python](https://www.python.org), 100 bytes
```
def g(a,n,i):
if len(a)>i>=0:g(a,n+1,i+n);a[i]=n;g(a,n+1,i-n)
def f(n):g(a:=[3*n]*3*n,n,0);print(a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3U1JS0xTSNRJ18nQyNa24FDLTFHJS8zQSNe0y7WwNrMAy2oY6mdp5mtaJ0ZmxtnnWcDHdPE0ukPY0jTxNkEor22hjrbxYLSABNM5A07qgKDOvBGgWxK4daflFCpkKmXkKRYl56akahjpmmlZpGplQaZiTAA)
Uses the same recursive concept as [Arnauld's answer](https://codegolf.stackexchange.com/a/253509/113573).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
4*ลธIยท._ยฆรรฌฮนะฝIโ
```
Inspired by [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/253505/52210).
[Try it online](https://tio.run/##ASIA3f9vc2FiaWX//zQqxbhJwrcuX8Kmw4LDrM650L1J4oCg//8z) or [verify all test cases](https://tio.run/##ATAAz/9vc2FiaWX/NUVOPyIg4oaSICI/TkT/NCrFuE7Cty5fwqbDgsOszrnQvU7igKD/LP8).
**Explanation:**
```
# example input: 3
4* # Multiply the (implicit) input by 4
# STACK: 12
ลธ # Pop and push a list in the range [(implicit) input, 4*input]
# STACK: [3,4,5,6,7,8,9,10,11,12]
Iยท # Push the input doubled
# STACK: [3,4,5,6,7,8,9,10,11,12],6
._ # Rotate the list that many times towards the left
# STACK: [9,10,11,12,3,4,5,6,7,8]
ยฆ # Remove the first value
# STACK: [10,11,12,3,4,5,6,7,8]
ร # Bifurcate it; shorter for Duplicate & Reverse copy
# STACK: [10,11,12,3,4,5,6,7,8],[8,7,6,5,4,3,12,11,10]
รฌ # Prepend the second list to the first
# STACK: [8,7,6,5,4,3,12,11,10,10,11,12,3,4,5,6,7,8]
ฮน # Uninterleave it into two parts
# STACK: [[8,6,4,12,10,11,3,5,7],[7,5,3,11,12,10,4,6,8]]
ะฝ # Pop and only leave the first inner list
# STACK: [8,6,4,12,10,11,3,5,7]
Iโ # Filter the input to the front of the list
# STACK: [3,8,6,4,12,10,11,5,7]
# (after which the result is output implicitly)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
๏ผฎฮธโ๏ผฅฮธโบฮธโฮนฮท๏ผฉโบโบโฎโ๏ผฏโฮทฮธ๏ผฅฮธรยณฮธโฮทยน
```
[Try it online!](https://tio.run/##LUwxDsIwENt5RceLVAaEmDohWDoAEfCBNJxIpDRN7pJ@PyQVg23Zsq2NIr0oV8roQ073PE9IEMWwOzPbr4ebChD7TrrMTa9Lnhx@wAoh@s7UniTrE1wUJ9hKGz1xRWIEmdk8ApJKC8HoNeGMPtW9qetY8b9/2xkZji1rvy9nNYLpu0O1Qymnsl/dDw "Charcoal โ Try It Online") Link is to verbose version of code. Explanation:
```
๏ผฎฮธ
```
Input `n`.
```
โ๏ผฅฮธโบฮธโฮนฮท
```
Create a range from `n` to `3n-2` in steps of 2.
```
๏ผฉโบโบโฎโ๏ผฏโฮทฮธ๏ผฅฮธรยณฮธโฮทยน
```
Increment that range (giving `n+1`, `n+3`, ... `3n-1`), append `n`, reverse the result (giving `n`, `3n-1`, `3n-3`, ... `n+1`), append `n` copies of `3n`, then append the range excluding the first element. This outputs `n`, `3n-1`, `3n-3`, ... `n+1`, `3n`, ... `3n`, `n+2`, ... `3n-2` as desired.
] |
[Question]
[
*This challenge requires integration with C, so you can stop reading if you're not interested.*
Matrix multiplication is a simple operation, but the performance depends a lot on how efficiently the code is written.
Let's compute `m = x * y`. The following code is the implementation of the textbook algorithm.
```
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
float s = 0;
for (int k = 0; k < n; ++k) {
s += x[i * n + k] * y[k * n + j];
}
m[i * n + j] = s;
}
}
```
It looks fine, but actually performs quite bad for various reasons.
Simply reordering the operations to let only row access happen is a significant optimization.
```
//m is zeroed
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
float e = x[i * n + j];
for (int k = 0; k < n; ++k) {
m[i * n + k] += e * y[j * n + k];
}
}
}
```
This version is about *9.5 times* faster than the upper one on my PC. Well, it's quite an optimal environment because in the actual implementation, I gave the compiler a lot of hints to make it auto-vectorize the second version up to the point where I couldn't gain any performance by manually vectorizing. But that's one of the problems of the first version. Column-accessing makes vectorization almost impossible to be done automatically and often not worthy to be done manually.
However, both versions are just the implementation of the most basic algorithm we all might know. I'd like to see what else could be done for a faster matrix multiplication on a restricted x86 environment.
The following restrictions are for *simpler* and *clearer* comparison between the algorithms.
* At most one thread can run during the program.
* The allowed x86 extensions are AVX2 and FMA.
* You must provide a **C interface** with the following prototype.
```
void (*)(void *m, void *x, void *y)
```
It **does not** have to be implemented in C, but you have to provide a way to be called from C.
`m`, `x`, and `y` point to 3 different arrays of `64 * 64 = 4096` `float`s that are aligned on a 32-byte boundary. These arrays represent a 64x64 matrix in row-major order.
You will be given randomly initialized matrices as input. When all outputs are done, first, the time taken will be measured, and then, a simple checksum will be calculated to check the correctness of the operation.
The table shows how much time the two example implementations shown earlier, each named `mat_mul_slow` and `mat_mul_fast`, takes to finish the test.
| `mat_mul_slow` | `mat_mul_fast` |
| --- | --- |
| ~19.3s | ~2s |
The measurement will be done on my machine with an Intel Tiger Lake CPU, but I will not run code that seems to be slower than `mat_mul_fast`.
Built-ins are fine, but it should be open source so that I can dig in their code to see what they've done.
The attached code is the tester and the actual implementation of the examples, compiled by `gcc -O3 -mavx2 -mfma`.
```
#include <stdio.h>
#include <stdalign.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <x86intrin.h>
enum {MAT_N = 64};
typedef struct {
alignas(__m256i) float m[MAT_N * MAT_N];
} t_mat;
static void mat_rand(t_mat *_m, int n) {
unsigned r = 0x55555555;
for (int i = 0; i < n; ++i) {
float *m = _m[i].m;
for (int j = 0; j < MAT_N * MAT_N; ++j) {
r = r * 1103515245 + 12345;
m[j] = (float)(r >> 16 & 0x7fff) / 0x8000p0f;
}
}
}
static unsigned mat_checksum(t_mat *_m, int n) {
unsigned s = 0;
for (int i = 0; i < n; ++i) {
float *m = _m[i].m;
for (int j = 0; j < MAT_N * MAT_N; ++j) {
union {float f; unsigned u;} e = {m[j]};
s += _rotl(e.u, j % 32);
}
}
return s;
}
__attribute__((noinline))
static void mat_mul_slow(void *_m, void *_x, void *_y) {
enum {n = MAT_N};
float *restrict m = __builtin_assume_aligned(((t_mat *)_m)->m, 32);
float *restrict x = __builtin_assume_aligned(((t_mat *)_x)->m, 32);
float *restrict y = __builtin_assume_aligned(((t_mat *)_y)->m, 32);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
float s = 0.0f;
for (int k = 0; k < n; ++k) {
s = fmaf(x[i * n + k], y[k * n + j], s);
}
m[i * n + j] = s;
}
}
}
__attribute__((noinline))
static void mat_mul_fast(void *_m, void *_x, void *_y) {
enum {n = MAT_N};
float *restrict m = __builtin_assume_aligned(((t_mat *)_m)->m, 32);
float *restrict x = __builtin_assume_aligned(((t_mat *)_x)->m, 32);
float *restrict y = __builtin_assume_aligned(((t_mat *)_y)->m, 32);
memset(m, 0, sizeof(t_mat));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
float e = x[i * n + j];
for (int k = 0; k < n; ++k) {
m[i * n + k] = fmaf(e, y[j * n + k], m[i * n + k]);
}
}
}
}
/*static void mat_print(t_mat *_m) {
int n = MAT_N;
float *m = _m->m;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; j += 8) {
for (int k = 0; k < 8; ++k) {
printf("%f ", m[i * n + j + k]);
}
putchar('\n');
}
}
putchar('\n');
}*/
static void test(void (*f)(void *, void *, void *), t_mat *xy, t_mat *z,
int n) {
clock_t c = clock();
for (int i = 0; i < n; ++i) {
f(z + i, xy + i * 2, xy + i * 2 + 1);
}
c = clock() - c;
printf("%u %f\n", mat_checksum(z, n), (double)c / (double)CLOCKS_PER_SEC);
}
#define TEST(f) test(f, xy, z, n)
int main() {
enum {n = 0x20000};
static t_mat xy[n * 2];
static t_mat z[n];
mat_rand(xy, n * 2);
puts("start");
for (int i = 0; i < 2; ++i) {
TEST(mat_mul_slow);
TEST(mat_mul_fast);
}
return 0;
}
```
<https://godbolt.org/z/hE9b9vhEx>
[Answer]
# C (GCC), 2.65โรณ faster than `mat_mul_fast`
(Compiled with `gcc -O3 -mavx2 -mfma`, measured on my Intel Comet Lake i7-10710U.)
```
#include <x86intrin.h>
enum { MAT_N = 64 };
void mat_mul_simd(void *_m, void *_x, void *_y) {
enum { n = MAT_N };
float(*m)[n] = _m, (*x)[n] = _x, (*y)[n] = _y;
for (int i = 0; i < n; ++i) {
__m256 mi[n / 8];
for (int k = 0; k < n / 8; ++k)
mi[k] = _mm256_setzero_ps();
for (int j = 0; j < n; ++j) {
__m256 xij = _mm256_broadcast_ss(&x[i][j]);
for (int k = 0; k < n / 8; ++k)
mi[k] = _mm256_fmadd_ps(xij, _mm256_load_ps(&y[j][k * 8]), mi[k]);
}
for (int k = 0; k < n / 8; ++k)
_mm256_store_ps(&m[i][k * 8], mi[k]);
}
}
```
<https://godbolt.org/z/xxvr45b67>
## C (GCC 11)
This completely auto-vectorized code is very nearly as fast as the above in GCC 11 (`gcc -O3 -mavx2 -mfma`), but regresses significantly in GCC 12. Auto-vectorization is fragile. ๏ฃฟรผรฒรป
```
enum { MAT_N = 64 };
void mat_mul_auto(void *_m, void *_x, void *_y) {
enum { n = MAT_N };
float(*restrict m)[n] = __builtin_assume_aligned(_m, 32);
float(*restrict x)[n] = __builtin_assume_aligned(_x, 32);
float(*restrict y)[n] = __builtin_assume_aligned(_y, 32);
for (int i = 0; i < n; ++i) {
float mi[n] = {};
for (int j = 0; j < n; ++j)
for (int k = 0; k < n; ++k)
mi[k] += x[i][j] * y[j][k];
for (int k = 0; k < n; ++k)
m[i][k] = mi[k];
}
}
```
<https://godbolt.org/z/h4GEqGjGW>
] |
[Question]
[
The narcissist is a program which, given its own source as input, prints a truthy value and, given anything other than that, prints a falsey value. Today, we're reversing this.
Create a program that, given the name of whatever your language's truthy value is (True, true, 1), prints its own source. Given the name of whatever your language's falsey value is (False, false, 0), or any input other than these two, it should output nothing (empty string or array: erroring is acceptable).
Trailing whitespace is only good if your language needs it printed alongside with the code.
You need not account for all truthy and falsey values. You can choose one truthy and one falsey value for input.
For languages without truthy/falsey values, use 1 and 0.
This is code golf so the shortest program wins. Standard loopholes and quine rules apply.
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 8 bytes
```
sP#;H?I"
```
[Try it online!](https://tio.run/##S8/PScsszvj/vzhA2drD3lPp/39DAA "Gol><> โ Try It Online")
Adapted from my comment on [this answer](https://codegolf.stackexchange.com/a/62392/76162).
### Explanation
```
sP Pop and add 17 to the bottom of the stack (default 0)
# Reflect
sP Add 17 again to make 34
" Wrapping string literal to push the source
?I If the input is non-zero
H Halt and output the stack
; Otherwise just halt
```
[Answer]
# Java 10, ~~227~~ 202 bytes (full program)
```
interface N{static void main(String[]a){var s="interface N{static void main(String[]a){var s=%c%s%1$c;if(new Boolean(a[0]))System.out.printf(s,34,s);}}";if(new Boolean(a[0]))System.out.printf(s,34,s);}}
```
-25 bytes thanks to *@ripkoops*.
[Try it online.](https://tio.run/##lctBCsIwEADAr4RiIIFaFL0VL32Alx5LD0u6ka02key2IqVvj36h95kRFjiOwzNnCoLJg0N1X1lAyKkl0qAmoGBaSRQeXQ92XSApvhX7uHaa9fngavIm4Ec1Mb4QgoHu1FvbfllwquIs1fsfxRsuL9eSbb1txf6Sc5Y04w8)
# Java 10, 98 bytes (lambda function)
```
b->{var s="b->{var s=%c%s%1$c;return b?s.format(s,34,s):%1$c%1$c;}";return b?s.format(s,34,s):"";}
```
[Try it online.](https://tio.run/##fY8xa8MwEIX3/IpDxCDRxFDaKSbJlq1Zmi10OCtyq1SWgu5kCMG/3ZVT0y6ly3HH@4733hk7XJ5Pn4N2SAQvaP1tBmA9m9igNrAfT4BXjta/g5Z1CM6gh1pVWehneRAjWw178LCGoV5ubh1GoLX4XQtdUPE411U0nGL@3lLZhNgiS1o8PS9IrUb5jvTiH0qIqh9G50uqXTadvLtgT9Dm8PI76PENUE3Jr8SmLUPi8pIldl6KQ0z8cV2BePCllhyTUfc6f9M7dGR@6Ga81NS@H74A)
**[quine](/questions/tagged/quine "show questions tagged 'quine'") explanation:**
* The `var s` contains the unformatted source code
* `%s` is used to put this String into itself with `s.format(...)`
* `%c`, `%1$c`, and `34` are used to format the double-quotes
* `s.format(s,34,s)` puts it all together
And then a ternary if-else check is added, which prints this source code if truthy, or an empty string if falsey.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 10 bytes
```
`:qp*`:qp*
```
[Try it True!](https://lyxal.pythonanywhere.com?flags=&code=%60%3Aqp*%60%3Aqp*&inputs=1&header=&footer=)
[Try it False!](https://lyxal.pythonanywhere.com?flags=&code=%60%3Aqp*%60%3Aqp*&inputs=0&header=&footer=)
[Answer]
## Haskell, 42 bytes
```
f n|n=putStr<>print$"f n|n=putStr<>print$"
```
[Try it online!](https://tio.run/##y0gszk7NyfmvYWOnaZubWFCQmpfyP00hrybPtqC0JLikyMauoCgzr0RFCavg/9zEzDwFW4U0hZCi0tT/AA "Haskell โ Try It Online")
A simple modification of the [standard quine](https://codegolf.stackexchange.com/a/161036/34531) (current version of the Prelude with `<>` required). Throws an error when given `False`.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 20 bytes
```
โ!1โง"โ!1โง~kgjwโ"gjwโ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HnHEXDRx3LlWCMuuz0rPJHTY1KEOr/f0MA "Brachylog โ Try It Online")
Brachylog doesn't really have truthy or falsy *values*, so this just assumes that 0 and 1 are valid choices regardless of actual truthiness.
```
โ Label the input,
! and discard the resulting choice point.
1 If the input is 1,
โง"โ!1โง~kgjwโ"gjwโ quine.
```
This could be reduced to `1โง"1โง~kgjwโ"gjwโ` if we only had to handle the chosen values, or only integers, or only literals--`โ!` is necessary to handle an empty input or variable input. A lot of different two-byte chunks of code could work in place of `โ!`, such as any one of `023456789\^cxzแบกแธ
แปแธทแนแปฅฤแนแนแบ แธแธแบธแธคแปแธถแนแนขแนฌแนพแบแบฤฤแนศฎแน แนชฯฯ` followed by `|`, but `โ!` seems like the best for specifically catching an unbound input.
[Answer]
# [Python 2](https://docs.python.org/2/), 55 bytes
```
a=input();_='a=input();_=%r;print(_%%_*a)';print(_%_*a)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9E2M6@gtERD0zreVh2Zo1pkXVCUmVeiEa@qGq@VqKkO54J4//8bAgA "Python 2 โ Try It Online")
-10 bytes thanks to milkyway
Takes `1` or `0` as input. Technically you could give another integer but that produces weird behaviour.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
```
*QjN*2]"*QjN*2]
```
[Try it online!](https://tio.run/##K6gsyfj/Xyswy0/LKFYJSv//H1JUmgoA "Pyth โ Try It Online")
Input is either `True` or `False`. is a modification of the standard Pyth quine, `jN*2]"jN*2]`.
```
*QjN*2]"*QjN*2] Implicit: Q=eval(input()), N=quote mark
"*QjN*2] The string "*QjN*2]" - closing quote is inferred
] Wrap in a list
*2 Duplicate
jN Join on "
*Q Multiply by Q - True is evaluated to 1, False to 0
Implicit print
```
---
Technically, a truthy value in Pyth is any value not in the following list: `0, 0.0, "", [], (), {}, set()`, whereas my submission above only works with the strict values for `True` and `False`. If we need to cater for any truthy or falsey value, the following will work for **19 bytes**: `?!QkjN*2]"?!QkjN*2]` ([TIO link](https://tio.run/##K6gsyfj/314xMDvLT8soVgnO@v/fAAA)). This replaces the multiplcation with `?!Qk`, which uses the negation of the truthiness of the input (`!Q`) to select either an empty string (`k`) or the quine string through the ternary operator (`?`).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~21~~ 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"34รงรฌIฮยทร"34รงรฌIฮยทร
```
-3 bytes thanks to *@Grimy*.
[Try it online.](https://tio.run/##yy9OTMpM/f9fydjk8PLDazzPzTi0/fB0VN7//4YA)
**Explanation:**
NOTE: Only `1` is truthy in 05AB1E. Everything else is falsey.
It's based on this base quine: [`"34รงรฌDJ"34รงรฌDJ`](https://tio.run/##yy9OTMpM/f9fydjk8PLDa1y84Iz//w0B) (or to be more correct: [`"34รงรฌ2ร"34รงรฌ2ร`](https://tio.run/##yy9OTMpM/f9fydjk8PLDa4wOT0ew/v83BAA))
```
"34รงรฌIฮยทร" # Push string "34รงรฌIฮยทร"
34รง # Push 34, converted to character '"'
รฌ # Prepend it in front of the string: '"34รงรฌIฮยทร'
I # Push the input
ฮ # Trutify it (==1)
ยท # Double it
ร # And repeat the string that many times
# with truthy input 1: '"34รงรฌIฮยทร"34รงรฌIฮยทร'
# with falsey input: ""
# (after which the result is output implicitly)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 16 bytes
Assuming the only falsey string is the empty one
```
f=_=>_?'f='+f:''
```
[Try it online!](https://tio.run/##ZcxLCoAgEADQfadwN0oUtQ2so4Sl0wdxotGub7QMt2/xTvMYXu/jik0g63JGPetxngA11DgA5JUCk3etp02ijHdySlV/ROO51L6QrhCI@8GCd0reisWJrwel8gs "JavaScript (Node.js) โ Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 19 bytes
Assuming anything different from `true, false, 1, 0` is falsey
```
f=_=>~_+1?'f='+f:''
```
[Try it online!](https://tio.run/##ZcyxCoAgEADQva9wuySKWgPrU8LKS0O66LSxXzdoC9c3vF3fmpfLnaE@aDUpoZrU8ExVNwIqqLAHSAsdTN40nrYSy3BFI2XxR9Sec@0yaTOBYB0LthT9KmYjvgmkTC8 "JavaScript (Node.js) โ Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 bytes
Based on [ETH's original standard quine](https://codegolf.stackexchange.com/a/71932/58974). Expects `0` for falsey and `1` for truthy.
```
"iQ pUร"iQ pUร
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ImlRIHBV0SJpUSBwVdE&input=MQ)
```
"iQ pUร"iQ pUร :Implicit input of integer U
"iQ pUร" :Literal string
i :Prepend
Q : Quotation mark
p :Repeat
Uร : U*2 times
```
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 12 bytes
```
"i1=?;3X4+k@
```
[Try it online!](https://tio.run/##KyrNy0z@/18p09DW3to4wkQ72@H/f0MA "Runic Enchantments โ Try It Online")
If it weren't for the "or any other value" having to print nothing I could save 2 bytes by removing `1=`, but that allows for values like `11` to also print the quine. Note that the ascii character `0x01` implicitly converts to `1` and is effectively also a `true` value. The only way to distinguish it from numerical `1` would be to concatenate it as a string.
### Explanation
The quine portion of this answer is actually pretty boring and straight forward, only `i1=?;` is added to meet challenge specifications:
```
" Begin string mode
i1=?;3X4+k@ Push the string literal i1=?;3X4+k@
" Stop string mode
i1= Read input, compare to 1
? Skip a number of instructions equal to the top of the stack (0 or 1)
; If 0, terminate
3X4+ If 1, push 34
k Convert to character (")
@ Dump stack, top to bottom, to output and terminate.
```
[Answer]
# [lin](https://github.com/molarmanful/lin), 53 bytes
```
in (1g@ dup outln out ) e|
in (1g@ dup outln out ) e|
```
Takes input via STDIN. Truthy value is empty input, falsy value is any other input.
# Explanation
`in (...) e|` only executes whatever is within the parentheses if the input is empty. `1g@` retrieves the second line. `dup outln out` outputs 2 copies of the second line separated by a newline.
This takes advantage of the fact that lin only executes the program's first line (unless told otherwise by commands).
[Answer]
# Perl 5 (`-p`), ~~29~~ 24 bytes
Could save 2 bytes thanks to @Abigail, and some more thanks to this track
```
$_&&=<<''x2
$_&&=<<''x2
```
[TIO](https://tio.run/##K0gtyjH9/18lXk3N1sZGXb3CiAuZ/f@/4b/8gpLM/Lzi/7oFAA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
โยดฮทยดยฟยด๏ผฎยดยซยดยดยดโยด๏ผฆยดฮทยดโบยดยดยดยดยดฮนยดฮทฮทยฟ๏ผฎยซยดโ๏ผฆฮทโบยดยดฮนฮท
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R55RDW85tP7Tl0P5DW97vWQdkrAZiIATLvN@zDCL9qHEXRBgEz@0ECQKF94N0rAarBao8tx2q6tzOc9v//zcEAA "Charcoal โ Try It Online") I can't actually seem specify an input of an arbitrary type (I get some weird zero-length truthy value if I try), so this just inputs numeric values and prints itself for any non-zero value. This is based on the standard Charcoal quine in the linked answer, with the actual printing wrapped inside a conditional (+3 bytes) plus that code then quoted inside the assignment (+6 bytes). Charcoal no longer outputs a trailing newline which saves 1 byte. If an exact match with `1` is required, then for 46 bytes:
```
โยดฮทยดยฟยดยฌยดโยด๏ผฎยดยซยดยดยดโยด๏ผฆยดฮทยดโบยดยดยดยดยดฮนยดฮทฮทยฟยฌโ๏ผฎยซยดโ๏ผฆฮทโบยดยดฮนฮท
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R55RDW85tP7Tl0H4gXnNoy6OuaYe2vN@zDshbDcRACFbyfs8yiLpHjbsgwiB4bidIECi8/9AaoEaQttVgDUDl57ZDlZ7beW77//@GAA "Charcoal โ Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, 46 bytes
Based on the Ruby heredoc quine. Falsy values are `nil` and `false`. Truthy values are basically every other valid Ruby object, including `true`, any number (even zero), any string (even the empty string), and any array (even an empty array).
```
puts <<2*2,2if eval$_
puts <<2*2,2if eval$_
2
```
[Try it online!](https://tio.run/##KypNqvz/v6C0pFjBxsZIy0jHKDNNIbUsMUclngu7qBHX//8G//ILSjLz84r/6@YBAA "Ruby โ Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 108 bytes
```
var s="var s={0}{1}{0};if(bool.Parse(ReadLine())Write(s,'{0}',s);";if(bool.Parse(ReadLine()))Write(s,'"',s);
```
[Try it online!](https://tio.run/##Sy7WTS7O/P@/LLFIodhWCUJVG9RWG9YCSevMNI2k/PwcvYDEouJUjaDUxBSfzLxUDU3N8KLMklSNYh11oCp1nWJNayXcahGKlcBK//8PKSpNBQA "C# (Visual C# Interactive Compiler) โ Try It Online")
The above link demonstrates the truthy case. Below are some alternative inputs:
* [Falsy](https://tio.run/##Sy7WTS7O/P@/LLFIodhWCUJVG9RWG9YCSevMNI2k/PwcvYDEouJUjaDUxBSfzLxUDU3N8KLMklSNYh11oCp1nWJNayXcahGKlcBK//93S8wpTgUA "C# (Visual C# Interactive Compiler) โ Try It Online")
* [Something else (empty string)](https://tio.run/##Sy7WTS7O/P@/LLFIodhWCUJVG9RWG9YCSevMNI2k/PwcvYDEouJUjaDUxBSfzLxUDU3N8KLMklSNYh11oCp1nWJNayXcahGKlcBK//8HAA "C# (Visual C# Interactive Compiler) โ Try It Online")
Based on my [C# quine](https://codegolf.stackexchange.com/a/186915/8340).
Here is a lambda variation:
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 79 bytes
```
b=>{var s="b=>{{var s={0}{1}{0};if(b)Write(s,'{0}',s);}}";if(b)Write(s,'"',s);}
```
[Try it online!](https://tio.run/##Sy7WTS7O/O@YXJKZn2eTlJ@fY5dm@z/J1q66LLFIodhWCcSEsqsNaqsNa4GkdWaaRpJmeFFmSapGsY46UERdp1jTurZWCU1GCSL@35orTaOkqDRV0/o/AA "C# (Visual C# Interactive Compiler) โ Try It Online")
] |
[Question]
[
### Task
Given is a square matrix of any dimension and any integer `n`.
Output all possible matrices(without duplicates) by removing columns and rows from the input matrix such that the determinant of these new matrices is `n`.
### Rules
Output should include original if determinant of original is `n`.
Output should be all the chopped off matrices.
In case no output matrix is possible, return 0 or None or anything similar.
The input matrix will be at least of size 2x2 and all elements will be integers.
If `n=1` empty matrix must also be in the output.
### Test Cases
```
inputs:
[[1,0,5],
[1,0,5],
[1,2,4]],2
[[1, 3, 5],
[1, 3, 5],
[1, 45, 4]],0
[[1, 22, 5, 4],
[1, 3, 5, 5],
[1, 45, 4, 6],
[3, 4, 1, 4]],5
[[1, 22, 5, 4],
[1, -32, 51, 5],
[1, 45, 9, 0],
[3, 4, -1, -6]],-54
[[1, 22, 5, 4],
[1, -32, 51, 5],
[1, 45, 9, 0],
[3, 4, -1, -6]],1
outputs:
[[[2]], [[1, 0], [1, 2]]]
[[[1, 3], [1, 3]], [[1, 5], [1, 5]], [[3, 5], [3, 5]], [[1, 3, 5], [1, 3, 5], [1, 45, 4]]]
[[[5]], [[5, 4], [5, 5]]]
[[[1, 22], [1, -32]], [[9, 0], [-1, -6]]]
[[], [[1]], [[1, 4], [1, 5]]]
```
**The shortest code wins.**
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 16 bytes
```
ZลPZลcLฦโฌแบQรแธโผยฅฦ
```
[Try it online!](https://tio.run/##y0rNyan8/z/q6KSAqKOTk32OdT1qWvNwV1/g4baHO7oeNe45tPRY@//Dy49Oerhzxv//0dGGOgrGOgqmsTpcaEwTUyCOjf1vAAA "Jelly โ Try It Online")
[Challenge finished](https://chat.stackexchange.com/transcript/message/47593014#47593014). Unfortunately, my brain wasn't in its best mood, so Dennis pushed it until I finally managed to get here (you can see how it went). ~1 hour.
[Answer]
# JavaScript (ES6), ~~246~~ ~~238~~ ~~196~~ 192 bytes
*Credits: the function \$D\$ is derived from [this answer](https://codegolf.stackexchange.com/a/147910/58563) by edc65.*
Takes input as `(integer)(matrix)`. Prints the results to the console.
```
d=>g=m=>(F=(a,i)=>a.filter(_=>i--),m.map((_,i)=>m.map((_,j)=>g(F(m,i).map(r=>F(r,j))))),D=m=>m+m?m.reduce((n,[r],i)=>n+(i&1?-r:r)*D(F(m,i).map(r=>F(r,0))),0):1)(m)-d||g[m]||console.log(g[m]=m)
```
[Try it online!](https://tio.run/##rZBda4MwFIbv/RWBwXqyJmL8KLQQe1P8BbsTKUGjWIyWaHflf3cmg9VtXXvT3L1vcp7nkJP4EH2u6/NA266QU8mngscVVzyGhIMgNeaxcMu6GaSGI49rSjFRrhJngKO9/Q6nOVSQgJpr22keJ6Dn3hxyMFC1VnvlallccgnQklRnFtKuoX5le6p3Gr8dbkA8g/DwjmFQmBbjWKUqG8e8a/uukW7TVWAarvC07Fbvsh9QLnqJXtgKOyX4GFIHoZQR5BEUZeRW8AkKMyfDjvMfzLcw7woLlvM/Qhg9pAWWFl1p/ryBHVsS/0AJ2nwVgQ3soSe0HhqFd0w0MA37LdvOX7SUUfN0c18XWR17pmz6BA "JavaScript (Node.js) โ Try It Online")
## How?
### Removing rows and columns
The helper function \$F\$ creates a copy of a given array \$a\$ with the \$i^\text{th}\$ item removed (0-indexed).
```
F = (a, i) => a.filter(_ => i--)
```
### Computing the determinant
The recursive function \$D\$ computes the determinant of a matrix \$m\$, using [Laplace expansion](https://en.wikipedia.org/wiki/Laplace_expansion).
```
D = m => // m = matrix
m + m ? // if the matrix is not empty:
m.reduce((n, [r], i) => // for each value r at (0, i):
n // take the previous sum n
+ (i & 1 ? -r : r) // using the parity of i, either add or subtract r
* D( // multiplied by the result of a recursive call:
F(m, i) // using m with the i-th row removed
.map(r => F(r, 0)) // and the first column removed
), // end of recursive call
0 // start with n = 0
) // end of reduce()
: // else (the matrix is empty):
1 // determinant = 1
```
*Example:*
$$m=\begin{bmatrix}\color{red}1&\color{red}2&\color{red}3\\\color{green}4&\color{green}5&\color{green}6\\\color{blue}7&\color{blue}8&\color{blue}9\end{bmatrix}$$
First iteration:
$$|m|=
\color{red}1\times\left|\begin{bmatrix}\color{green}5&\color{green}6\\\color{blue}8&\color{blue}9\end{bmatrix}\right|
-\color{green}4\times\left|\begin{bmatrix}\color{red}2&\color{red}3\\\color{blue}8&\color{blue}9\end{bmatrix}\right|
+\color{blue}7\times\left|\begin{bmatrix}\color{red}2&\color{red}3\\\color{green}5&\color{green}6\end{bmatrix}\right|$$
which eventually leads to:
$$1\times(5\times9-8\times6)-4\times(2\times9-8\times3)+7\times(2\times6-5\times3) = 0$$
### Main function
We recursively remove rows and columns from the original matrix \$m\$ and invoke \$D\$ on all resulting matrices, printing those whose determinant is equal to the expected value \$d\$.
```
d => // d = expected determinant value
g = m => // g = recursive function taking the matrix m,
( // also used to store valid matrices
m.map((_, i) => // for each i in [0 ... m.length - 1]:
m.map((_, j) => // for each j in [0 ... m.length - 1]:
g( // do a recursive call with:
F(m, i) // the i-th row of m removed
.map(r => F(r, j)) // the j-th column of m removed
) // end of recursive call
) // end of inner map()
), // end of outer map()
D // invoke D ...
)(m) // ... on m
- d // provided that the result is equal to d
|| g[m] // and provided that this matrix was not already printed,
|| console.log(g[m] = m) // print m and store it in the underlying object of g
```
[Answer]
# [R](https://www.r-project.org/), 129 bytes
```
f=function(m,n,o={},z=nrow(m)){for(i in r<-1:z)for(j in r)o=c(o,if(round(det(m))==n)list(m),if(z)f(m[-i,-j,drop=F],n));unique(o)}
```
[Try it online!](https://tio.run/##rY/NTsMwDIDvPEW1ky05UpOmk2DkyhPsBhxGf6RMNIEsFbBpz16cQaFbJU7IkmXH/r4kYRha0/auitY76MiRN4cj7Y0L/g06xEPrA9jMuizcCnmzx9RvTz16U4En20LwvauhbmIijHH4bHepTjMmoLsXlsSW6uBfzN0jOcRV7@xr34DH41BtIizWzS5m@YNb4IqBTQz2HSQVHE8f/BazRlJ5jle/y/J8ueL1nEoasyKNF/yUVnO6OHFfWZcz/OzyYo4rxaT@NowOWnKbDtmmOX5s5dSm/7CJgis5Cq/5d0koeLC8UIpST6Xlv0glDp8 "R โ Try It Online")
Recursive function returning a list of submatrices. Outputs `NULL` for no solution. It is a bit unfortunate that the determinant value has to be explicitly rounded (otherwise some tests fail due to numerical imprecision), but at least we have a built-in for calculating it.
] |
[Question]
[
This is a CC-BY-SA challenge from the [CCSC Mid-South Programming Contest 2018](https://ccsc18.kattis.com/).
**Author(s):** Brent Yorgey
**Source:** Consortium for Computing Sciences in Colleges Mid-South Programming contest 2018
<https://ccsc18.kattis.com/problems/ccsc18.mountainrange>
---
>
> Good news: you have been hired to do all the special effects for a film! One of the scenes will take place outside, on a windswept plain with a towering mountain range in the background. Your job is to turn a description of the mountain range into a rendered image.
>
>
> The bad news: the filmโs producers have an extremely small budget, and so they canโt afford luxuries like rendered 3D graphics made up of pixels. Hence, you will be making your image out of ASCII characters.
>
>
>
Write a function or full program to produce mountain range ASCII art according to the spec below. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); tie breaker is earlier submission.
## Input
You will receive a list of 5-tuples in any standard input format for PPCG and/or your language. Each 5-tuple is the values (x, h, z, t, s) representing one mountain of the range you will draw.
* x is the x-coordinate of the mountain's peak, with 1โคxโค199.
* h is the height of the mountain, with 1โคhโค100.
* z indicates the relative distance of the mountain from the viewer, with 1โคzโคm. The smaller the value of z, the closer the mountain is to the viewer. Closer mountains hide ones that are farther away.
* t is the height of the treeline. The side of the mountain up to the treeline should be filled with trees, represented by the ASCII character `Y`.
* s is the height of the snowline. The side of the mountain above the snowline should be filled with snow, represented by the ASCII character `*`.
The base of each mountain will not extend beyond 0 or 200 horizontally; you may assume that 0โคxโh and x+hโค200. The height of each mountain is no more than 100, so all mountains will fit within a 100x200 grid. The snow and trees will not overlap or exceed the height of the mountain; you may assume that 0โคtโคsโคh. All numbers are non-negative, and all z-values will be unique.
## Output
The output should consist of an ASCII drawing of the specified mountain range. Each mountain is triangular in shape with its sides drawn using `/` and `\` characters. For example, here is a mountain of height 4:
```
/\
/ \
/ \
/ \
```
This mountain has x-coordinate 4, since the horizontal distance from the left margin to its peak is 4 units.
Trees and snow should fill the interior of the mountain but not obscure the sides of the mountain. For example, here is a mountain with height 6, treeline height 2, and snowline height 3:
```
/\
/**\
/****\
/ \
/YYYYYYYY\
/YYYYYYYYYY\
```
That is, the trees extend from the base of the mountain up to a height of 2
units, and the snow starts at a height of 3 units and extends to the top of the mountain.
Mountains with a smaller z-coordinate may hide all or part of a mountain with a larger z-coordinate; see the third sample input/output below.
Leading whitespace is significant, and should be as specified by the x-position and width of the drawn mountains. Leading/trailing newlines are allowed, and any amount of spaces after each line.
## Examples
(8, 5, 1, 2, 3)
```
/\
/**\
/ \
/YYYYYY\
/YYYYYYYY\
```
(2, 2, 1, 0, 1)
```
/\
/ \
```
(8, 5, 2, 2, 3),
(2, 2, 1, 0, 1),
(9, 8, 3, 1, 4),
(17, 4, 4, 4, 4)
```
/\
/**\
/****\
/*/\***\
/ /**\ \ /\
/ / \ \/YY\
/\ /YYYYYY\ \YYY\
/ \YYYYYYYY\YYY\YYY\
```
If you find other interesting examples, please share in your answers!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~194~~ ~~191~~ 186 bytes
```
g=map(list,[' '*200]*100)
for x,h,z,t,s in sorted(input(),key=lambda m:-m[2]):
for i in range(h):g[-h+i][x+~i:x-~i]=['/']+[' *Y'[(i<h-s)-(i>=h-t)]]*2*i+['\\']
for l in g:print''.join(l)
```
[Try it online!](https://tio.run/##PY7dToQwEIXv9ynmrj9MtbAatRHfw3R7gVmWjkIhUBPWi311bDExOZmcfHPmZ7pGP4Zq27p6aCbe0xLRMmCy0trJUmtxuIwzrOjxByMuQAGWcY7tmVOYviMX@NVe674ZPs4NDEYNtnLCHCBPUU7PTeha7oXprPIFObsWNzKrupGrLbtnrkj35DuznF69WoTi9FZ7FYVzspKUuqcTc/sXfd7XmWmmEBm7@xwp8F5sm@XPCI8I1a6jQOB/tkTQqWbwgpBCx509ZFA@JfMv4X4B "Python 2 โ Try It Online")
Prints the whole 100x200 grid.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 133 bytes
```
->a{r=[];a.sort_by{|x|-x[2]}.map{|x,h,z,t,s|h.times{|i|(r[i]||=?\s*200)[x-j=h-i,j*2]=?/+" Y*"[i<t ?1:i<s ?0:2]*~-j*2+?\\}};r.reverse}
```
[Try it online!](https://tio.run/##PYrhasIwFIVf5dJfW73p2rgxp415jnF7kQqVRhAlSUdr0716jQrCx@Gcj2O7/TAf1Cy29WgV8abO3Nn63X4YQx9ET5Kn7FRf4sIWr@jRhTbz5tS4MZjwZslwCEpXLpV5/k69OKpWGDymkpX@WCTwmyZkSg@6WJvSgc7XktN/EQ8LXVXTtLGZbf4a65ppvnTewYGIVghfCPLBkhHoWQuEPOZd/CDE0/LhPu@i@I7lBTPPNw "Ruby โ Try It Online")
Anonymous lambda. Takes input as array of parameter arrays for mountains, returns array of strings.
## Walkthrough
```
->a{ #Input array is a
r=[]; #Initialize the output array
a.sort_by{|x|-x[2]} #Sort by decreasing distance
.map{|x,h,z,t,s| #Loop through the mountains
h.times{|i| #For each mountain fill h lines starting from the ground
(r[i]||=?\s*200) #If we haven't yet been so high, initialize with spaces
[x-j=h-i,j*2]= #Take a slice from x-(h-i) for double length of h-i
?/+" Y*"[i<t ?1:i<s ?0:2]*~-j*2+?\\ #Draw the sides of the mountain (/\),
} #with (h-i-1)*2 of the appropriately selected filler symbols in the middle
};r.reverse #Reverse to the top->bottom order suitable for printing
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 79 bytes
```
๏ผกฮธ๏ผทฮธยซโโฮฆฮธโผยงฮบยฒโ๏ผฅฮธยงฮผยฒฮนโฮฆฮธยฌโผฮบฮนฮธโยงฮนยนฮท๏ผชยงฮนโฐยฑฮทโโฆยงฮนโดโปฮทยงฮนยณฮทโงฮถ๏ผฆY *ยซโโฮถฮต๏ผงโฮตโโฮตโฮตฮบโยป๏ผฐโฮทโโฮท
```
[Try it online!](https://tio.run/##TZFfT8IwFMWf4VM0e7qYmohg1PlEgiYYRxajD2bZw4SyNnTr/nSAGD77vLdItqVZbs/59bS9XcmkWplEt21YqdyCx7zR03CRF42FEqu9VFowLNnvcDCra5XmEJoCXpS2ooKSs@eySXQNM7vI1@IAW85uR5wFyUFlTQZBUhB0cTNy3ceZwvhLZBe3NBb@I7fEEFn2yEuS4myMliTrtcmKD9O3btBaijSxAuSotzrqMVM6psqbGmR3QNQntKWMOTvSwo2pGHhf7MpzLej34IicIGYQGv2Tmhz8udnn7yqVFh3O/DexwWpumm8t1iCQ9z@Lzt@6xYHZCfCdSvPTcBA02qrCvUc/0d31TFMwzcIOOu9FzKltoyh64OwOu@3GBG8TncsxNgf/JDxyhtDEaVMSxvdYuEFiHMft9U7/AQ "Charcoal โ Try It Online") Link is to verbose version of code. Note: Leading space used to force the required indentation. Explanation:
```
๏ผกฮธ๏ผทฮธยซ
```
Loop while the input array is not empty.
```
โโฮฆฮธโผยงฮบยฒโ๏ผฅฮธยงฮผยฒฮน
```
Find the most distant mountain in the array.
```
โฮฆฮธยฌโผฮบฮนฮธ
```
Remove it from the array.
```
โยงฮนยนฮท
```
Get the height of the mountain.
```
๏ผชยงฮนโฐยฑฮท
```
Jump to the top of the mountain.
```
โโฆยงฮนโดโปฮทยงฮนยณฮทโงฮถ
```
Get the snowline, treeline and height.
```
๏ผฆY *ยซ
```
Loop over the trees, bare mountain and snow.
```
โโฮถฮต๏ผงโฮตโโฮตโฮตฮบโยป
```
Draw a trapezium of the desired height.
```
๏ผฐโฮทโโฮท
```
Draw the sides of the mountain.
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~284~~ ~~261~~ ~~257~~ 252 bytes
```
a,b,*z,i,j,k,o;c(*a,*b){return b[2]-a[2];}f(*m,n){qsort(m,n,5*sizeof *m,c);for(i=101;--i>0;puts(""))for(j=0;++j<200;putchar(o))for(o=32,k=0;k<n;z=&m[5*k++],a=z[0]-z[1]+i,b=z[0]-~z[1]-i,o=z[1]/i&&j/a&&b/j?"/\\*Y "[j==a?0:j==b?1:i>z[4]?2:z[3]/i?3:4]:o);}
```
[Try it online!](https://tio.run/##bVLRbqMwEHznK1ZUTWxYLkCC2sNx@I4T4QFIaE2C6QF5IeJ@PbdAUzWnkyzv7szY3lnInfyc6rfbk9L5@XI4wrbtDqr@8b4zHqCzygi7pZih1aPCEk9Yi5xZKVoZvzbH7tJoyGI/cVLaxFAwq0LNr7/buukYpRhYreqPdQFE5FwUdcOU9FxPOI7aueLj0rXMNDkfiVK6wrbLre9ORP6eNqyeqVqufTwRf9pq0ctFFQfWybYTTGUfu4nTx15iK8zm6s9YOgprOSYrtViUq3SxyFZlZK72e@sXmHEpZRq5IYUs8kK16@NNEvlhH6/pQLQON0lYczHcPhqlu6q@6C5Vup39wdUAIBhoJILS2ZUrQMEWNAXbnjVwt7GMl3xUTtISJJC4JHFA4UsM01sFM58Pz62JUMXKCuwyQaAuN5GZgBkSbM43Dd/vV1Jqx4uWe70Mlzi/NdyHK4zBMJ4Ox0LpI9yt5GNkSpOIA2Ns/kyfAF891DRTTljADWN0XdFxNvY8V3FCfq6vCAGCP601Umtz6iG4tMOI/ER4nUgCNxPivVD2tQZhGP@Mu8LHfitObgqC4T@48flDumT49hc "C (clang) โ Try It Online")
# Credits:
**-3** bytes Thanks Kevin Cruijssen
`f()` takes these params:
`m`: array of integers with all mountains' parameters
`n`: number of mountains
`m` should be a flat array of specifying `x, h, z, t` and `s` for mountains with each mountain's parameters appended to this array.
`f()` prints full 100x200 grid of ASCII scenery render.
# Ungolfed:
```
a,b,*z,i,j,k,o;
c(*a,*b){return b[2]-a[2];} //comaprison function for sort by z-order
f(*m,n){
qsort(m,n,5*sizeof(*m),c); //sort mountains by z-order
for(i=100;i>0;i--,puts("")) { //for each row
for(j=1;j<200;j++){ // for each pixel in this row
o=' '; //initialize pixel to background pixel value
for(k=0;k<n;k++) { // for each mountain, in z-order distant to close
z=&m[5*k]; //start pointer for mountain's params
a=z[0]-z[1]+i; //min x limit of mountain on this line
b=1+z[0]+z[1]-i; //max x limit of mountain on this line
o=z[1]/i && j/a && b/j ? "/\\*Y "[j==a?0:j==b?1:i>z[4]?2:z[3]/i?3:4]:o;
//calculate pixel value ovrwriting previous mountain if necessary
}
putchar(o); //print pixel value
}
}
}
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 265 243 229 210 204 203 bytes
```
a=>a.sort((x,y)=>y[2]-x[2]).map(([x,h,,t,s])=>{for(y=h;y--;)for(i=h+x-y;i--;)(d=R[y]=R[y]||[])[i]=i<x-h+y?d[i]||" ":"Y *\\/"[i>x-h+y?i<h+~y+x?y<t?0:y<s?1:2:3:4]},R=[])&&R.map(x=>s=x.join``+`
`+s,s="")&&s
```
[Try it online!](https://tio.run/##ZU/ZboMwEHzPV1g8RBwGB0jUlmD4h7xFxhIoR3GUhihGla3S/jo1NrkUyxrN7K7XM4fqu@KbCzu3/qnZ7vo97iucVQFvLq1tCygdnEkSUV8ocIKv6mzbRMAawhZyqpo/@@ZiS1wvpe8vnUEwXHvCl0s2FOwtXhFJNXQdoQ5hFLNU@LUn860SXWcBK7HWwC0KZBGWmRZLa@9PeiKXaZvPEpnyPEyiJE7m9BeusFo0na60HYEzjkVwaNipLL1yUnoccmxZaoD3m@bEm@MuODaf9t4m5B0uYAgjGFPlHZfAHFQUk5G57pWjAUaB1voYNQotS2fy@gVYQBDpG1MIiKEhBDOFQ@EDAjUU69p8KIRvitzuk7UHb4/mBv5g1VVTd43MpLZ/W4CugTQgE0b17tl0w8RCIx07dxgCvyR@Dmjco@sW9aL/Bw "JavaScript (Node.js) โ Try It Online")
] |
[Question]
[
I'm new to ES6 and code-golfing. Here's the original function:
```
function puzzle(n, x) {
return n * Math.pow(2, x);
}
```
And here's what I have so far:
```
let puzzle=(n,x)=>n*2<<(x-1)
```
But the solution requires lesser characters. I went through the 'Code Golfing with ES6' thread, but couldn't find a better way.
Any help/links would be appreciated.
[Answer]
## 17 bytes:
```
puzzle=n=>x=>n<<x
```
This uses the fact that `2 * 2^n` = `2^(n + 1)`. Also, by our rules, using [currying](https://en.wikipedia.org/wiki/Currying) instead of taking multiple arguments the usual way [is allowed](https://codegolf.meta.stackexchange.com/a/8427/34543). Also, I don't think the `let` is needed.
] |
[Question]
[
Given an integer k and a list of integers A of size n, find the product of all subsets in A of size k and sum them together.
For example,
```
k = 2
n = 4
A = 1 2 3 4
```
The subsets of size 2 and their products are
```
1 2 = 2
1 3 = 3
1 4 = 4
2 3 = 6
2 4 = 8
3 4 = 12
```
which sum together to 35.
Some test cases:
## Input
```
A = 73 36 86 76 5 25 15 95 27 1
n = 10
k = 4
A = 7 16 56 83 14 97 71 24 65 32 75 61 64 73 94 34 10
n = 17
k = 3
```
## Output
```
499369377
87409828
```
The input can be in whatever format suits your language best. You can have, for example, the variables A, n, and k set to the input already. The integers in A are not necessarily unique.
## Constraints
Functions which solve this question are not allowed, as well as functions which generate subsets. Also, to avoid ฮ(n^k) submissions, if a solution is made using a better approach, it will have a -30 character bonus. (-30 is subject to change)
The shortest solution is the winner.
Side Note: It's okay to post solutions which do not follow the rules if it demonstrates the strengths of your language. It just won't be part of the scoring.
For example,
Mathematica (31)
```
Times@@#&/@A~Subsets~{k}//Total
```
[Answer]
## R - 20
Since the OP said:
*Side Note: It's okay to post solutions which do not follow the rules if it demonstrates the strengths of your language. It just won't be part of the scoring.*
```
sum(combn(A,k,prod))
```
[Answer]
### Ruby, O(n\*k), 70 - 30 = 40 characters
```
@r={};r=->a,n,k{@r[[a,n,k]]||=k<1?1:n<1?0:r[a,n-=1,k]+a[n]*r[a,n,k-1]}
```
if the array can be made global and constant (or if we can ask the caller to clean our cache), we can save seven (or thirteen) more characters.
```
r=->n,k{@r[[n,k]]||=k<1?1:n<1?0:r[n-=1,k]+@a[n]*r[n,k-1]}
```
without memoisation, we're at 50 characters, but we don't qualify for the bonus:
```
r->a,n,k{k<1?1:n<1?0:r[a,n-=1,k]+a[n]*r[a,n,k-1]}
```
Spaced apart:
```
r = -> a, n, k {
k<1 ? 1 :
n<1 ? 0 :
r[a, n-1, k] + a[n-1] * r[a, n-1, k-1]
}
```
With memoization, we get to O(n \* k \* cost\_of\_memoization). If the key cannot be hashed well, the cost of memoization quickly grows up. However, a key of the form [[?],#,#] can be hashed quite well, at least in theory. Let's also assume that Ruby arrays cache their hashes, so hashing the same array over and over again takes the same time as hashing it once - linear in size. Also, hash table lookup may be assumed constant-time. So, it is safe to assume that the cost of memoization is constant per lookup, and the initial cost for hashing the array is drowned in the rest of the lookup.
here is the iterative approach:
```
r={};0.upto(k){|k|0.upto(n){|n|r[[n,k]]=k<1?1:n<1?0:r[[n-=1,k]]+a[n]*r[[n,k-1]]}};r[[n,k]]
```
Yay! I've beaten [Daniero's cheating solution](https://codegolf.stackexchange.com/a/12283/7209)
[Answer]
### GolfScript, score 8 0 -3 (27 - 30)
```
1,*1+\{{*\(@+}+1$1>0+%+}/0=
```
Expects list `a` and `k` on the stack and returns the result.
Example ([run online](http://golfscript.apphb.com/?c=WzczIDM2IDg2IDc2IDUgMjUgMTUgOTUgMjcgMV0gNAoKMSwqMStce3sqXChAK30rMSQxPjArJSt9LzA9Cg%3D%3D&run=true)):
```
[73 36 86 76 5 25 15 95 27 1] 4
1,*1+\{{*\(@+}+1$1>0+%+}/0=
# 499369377
```
[Answer]
## APL (31)
This assumes that `A`, `k` and `n` are already set.
```
+/{ร/A[โต]}ยจ({โง/2</โต}ยจโ)/โโ,โณkโดn
```
I.e.:
```
A โ 73 36 86 76 5 25 15 95 27 1
n โ 10
k โ 4
+/{ร/A[โต]}ยจ({โง/2</โต}ยจโ)/โโ,โณkโดn
499369377
```
Explanation:
* `โโ,โณkโดn`: set `โ` to the flattened (`,`) coordinate vector (`โณ`) which is `k`-dimensional with size `n` in each dimension. I.e. if `k=2` and `n=3`, you get `(1 1) (1 2) (1 3) (2 1) (2 2) (2 3) (3 1) (3 2) (3 3)`.
* `({โง/2</โต}ยจโ)/`: select only those coordinates where the value for the *N*-th dimension is larger than the value for the *(N-1)*-th dimension. (I.e. you get `(1 2) (1 3) (2 3)`). When these sets of coordinates are interpreted as lists of indexes into `A`, we get the desired subsets.
* `{ร/A[โต]}ยจ`: for each subset, get the values from `A` and multiply them together.
* `+/`: sum the given values
[Answer]
## Python 2: 64-30=34
```
t=A
exec"t=[sum(t[:i])*A[i]for i in range(n)];"*~-k
print sum(t)
```
Input is expected as
```
A = [73, 36, 86, 76, 5, 25, 15, 95, 27, 1]
n = 10
k = 4
```
Then `499369377` gets printed.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ลcPโฌS
```
[Try it online!](https://tio.run/##y0rNyan8///o5OSAR01rgv///x9tqGOkY6xjEvvfCAA "Jelly โ Try It Online")
Expects \$A\$ and \$k\$ as input.
**Explanation:**
```
ลcPโฌS
ลc Combinations
Pโฌ Product of โฌach
S Sum
```
[Answer]
I'm feeling too lazy to create the subsets on my own, so here's a quick cheating solution.
# Ruby, 48 chars
```
A.combination(k).map{|x|x.inject :*}.inject :+
```
With A and k are predefined, like for instance so
```
A=[7,16,56,83,14,97,71,24,65,32,75,61,64,73,94,34,10]
k=3
```
the result is `87409828`.
[Answer]
## Python 2, 172-30=142
Similar buildup approach
```
r=range
m=[x[:]for x in[[0]*n]*k]
m[0][0]=A[0]
for i in r(1,n):m[0][i]=m[0][i-1]+A[i]
for j in r(1,n):
for i in r(1,k):m[i][j]=m[i][j-1]+m[i-1][j-1]*A[j]
print m[k-1][n-1]
```
[Answer]
# J, 35 bytes
```
[:+/(>@{[:(</.~+/"1)2#:@i.@^#)*/@#]
```
Generates the masks for the powerset of *A* in binary order, selects the masks for *k*, and operates on each subset.
## Usage
```
f =: [:+/(>@{[:(</.~+/"1)2#:@i.@^#)*/@#]
2 f 1 2 3 4
35
4 f 73 36 86 76 5 25 15 95 27 1
499369377
3 f 7 16 56 83 14 97 71 24 65 32 75 61 64 73 94 34 10
87409828
```
## Explanation
```
[:+/(>@{[:(</.~+/"1)2#:@i.@^#)*/@#] Input: k on LHS, A on RHS
# Get the size of A
2 ^ Get 2^len(A)
i.@ Get the range [0, 1, ..., 2^len(A)-1]
#:@ Convert each to binary
[: +/"1 Take the sum of each binary digits
</.~ Partition the list of binary digits by their sum
and box each group
{ Select the box at index k
>@ Unbox it to get the mask for subsets of size k
] Get A
# Copy from A using each mask
*/@ For each subset, reduce using multiplication
[:+/ Reduce the products using addition and return
```
[Answer]
# APL(NARS), 47 chars, 98 bytes
```
{+/ร/ยจ{w[โต]}ยจk/โจ{โง/</ยจยฏ1โ{โต,ยจ1โฝโต}โต}ยจkโ,โณโบโดโขwโโต}
```
I got the idea from "marinus" answer, i don't know if this is ok... test:
```
fโ{+/ร/ยจ{w[โต]}ยจk/โจ{โง/</ยจยฏ1โ{โต,ยจ1โฝโต}โต}ยจkโ,โณโบโดโขwโโต}
2 f 1 2 3 4
35
3 f 7 16 56 83 14 97 71 24 65 32 75 61 64 73 94 34 10
87409828
4 f 73 36 86 76 5 25 15 95 27 1
499369377
```
`{โง/</ยจยฏ1โ{โต,ยจ1โฝโต}โต}` find if index are all < each other for example
```
{โง/</ยจยฏ1โ{โต,ยจ1โฝโต}โต} 1 2 3 4 5
1
{โง/</ยจยฏ1โ{โต,ยจ1โฝโต}โต} 3 2 3 4 5
0
{โง/</ยจยฏ1โ{โต,ยจ1โฝโต}โต} 1 3 2 4 5
0
{โง/</ยจยฏ1โ{โต,ยจ1โฝโต}โต} 1 2 3 4 9
1
```
I would prefer this because this work on indices not on values...possible if some repetitions, for list has one meaning...
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 167 bytes
```
l=>l.Any()?A(l.Skip(1)).Select(x=>l.Take(1).Union(x)).Union(A(l.Skip(1))):new int[][]{new int[]{}};B=(n,l)=>A(l).Where(x=>x.Count()==n).Sum(x=>x.Aggregate((y,z)=>y*z))
```
[Try it online!](https://tio.run/##bVBBTsMwELz3FT56kbEIKQkhOChBICH1VlAPVQ8hsoJV10WJI5JGeXtYF6gK9DDe0ezuzMpFfV7UanxsTHGrjGVkpmrrWMKIe0kWT/bNpwfTbGSVv2r53T5W/naThKREjFokmqemo3CXUs3na/VOPQA@l1oWlrau/ZyvJYr8xaitoS38sOMFuDHyw92zXC1X/YH3wxBnghqmQSQ4D3zxJivpfFt@v22MpSCEwbxm8yWmZVnJMreS0o7tcKs72wGM8WRRKStnykia0UtGXMThJyiQnniMoO4zMiUDwO@F6amFEGf9gJFrRIi4QgOEh4gcD5H/t/JPWuGoc3BuOOBhXoRa6G5CHqCdj8eFWAPUAtRceoTVR3gX@5zxEw "C# (Visual C# Interactive Compiler) โ Try It Online")
```
//returns a list of all the subsets of a list
A=l=>l.Any()?A(l.Skip(1)).Select(x=>l.Take(1).Union(x)).Union(A(l.Skip(1))):new int[][]{new int[]{}};
//filter the subsets of the required size and return the sum of the products of their items
B=(n,l)=>A(l).Where(x=>x.Count()==n).Sum(x=>x.Aggregate((y,z)=>y*z))
```
] |
[Question]
[
[Related](https://codegolf.stackexchange.com/questions/265114/sums-of-sum-of-divisors-in-sublinear-time).
Given a number \$n\$, Euler's totient function, \$\varphi(n)\$ is the number of integers up to \$n\$ which are coprime to \$n\$. That is, no number bigger than \$1\$ divides both of them.
For example, \$\varphi(6) = 2\$, because the only relevant numbers are \$1, 5\$. This is OEIS [A000010](https://oeis.org/A000010).
We can now define the sum of euler's totient function as \$S(n) = \sum\_{i=1}^{n}{\varphi(i)}\$, the sum of \$\varphi(i)\$ for all numbers from \$1\$ to \$n\$. This is OEIS [A002088](https://oeis.org/A002088).
Your task is to calculate \$S(n)\$, **in time sublinear in \$\mathbf{n}\$,** \$o(n)\$.
## Test cases
```
10 -> 32
100 -> 3044
123 -> 4636
625 -> 118984
1000 -> 304192
1000000 (10^6) -> 303963552392
1000000000 (10^9) -> 303963551173008414
```
## Rules
* **Your complexity must be \$o(n)\$**. That is, if your algorithm takes time \$T(n)\$ for input \$n\$, you must have \$\lim\_{n\to\infty}\frac{T(n)}n = 0\$. Examples of valid time complexities are \$O(\frac n{\log(n)})\$, \$O(\sqrt n)\$, \$O(n^\frac57 \log^4(n))\$, etc.
* You can use any reasonable I/O format.
* Note that due to the limited complexity you can't take the input in unary nor output in it (because then the I/O takes \$\Omega(n)\$ time), and the challenge might be impossible in some languages.
* Your algorithm should in theory be correct for all inputs, but it's fine if it fails for some of the big test cases (due to overflow or floating-point inaccuracies, for example).
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
This is code golf, so the shortest answer in each language wins.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~104~~ 100 bytes
Ports the algorithm at <https://oeis.org/A002088>. -4 bytes from Jonathan Allan.
```
A=->n,r=({0=>0}){r[c=n]||(k=n/i=2
(j=n/k+1;c+=(j-i).*2*A[k,r]-1;k=n/i=j)while k>1
r[n]=(n*n-c+i)/2)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWN1McbXXt8nSKbDWqDWztDGo1q4uik23zYmtqNLJt8_QzbY24NLKAjGxtQ-tkbVuNLN1MTT0tIy3H6GydolhdQ2uIqizN8ozMnFSFbDtDrqLovFhbjTytPN1k7UxNfSPNWohdawtKS4oVHKMNDYAgFiIGcwcA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~121~~ ~~99~~ 98 bytes
```
โฯ
๏ผฎโโฆโฆฮท๏ผฆฯ
๏ผฆยฌยงฮทฮนยซโฮนฮถโยฒฮตโรทฮนฮตฮดโโฆโงฮบ๏ผทโบฮดยนยซโโรทฮนฮดฮปยฟยงฮทฮดโงโบรโปฮปฮตโโยงฮทฮดฮถโฮบฮดโฮปฮตโรทฮนฮปฮดยปยฟฮบ๏ผฆโ๏ผฏฮบฮนโฯ
ฮปยงโฮทฮนรทโบโปรฮนฮนฮถฮตยฒยป๏ผฉยงฮทโฯ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZK9bsIwFIWlbuQZOlwx2ZKRClMlJtRIFQM0qrohhpBciIVxIv_Qqogn6cJQ1D5Tn6Z2nIgg4cW6dvzdc-7J129WpCorU3E6na1ZDx7_7u4TqwtiGUxlZc3c7laoCKXjaKI130hyODIoXLkuFRBLod7npSETM5U5fpCCAaeUwiHqNU84g0_3oi1HDLBTTqWJ-Z7n6L9DyiDvXC6WDLa-fi-4QCDPClPjBOUMhqHHBZMp3KE0mF8jc-qYwjN6fA1dme4GZmkVAK98UxiSCKsZvPEdajLj0moigqgYL_i4tCvh9muUb1Pb7KHQCPUYt42bVqRorN_0Llrvx6hWum2G60kvFarUlMoT3XShDan2VfcLxG4IPsIW7301hoI57jlecLA38gkfo0RxachTqq_iTMrKJe3W-FuvMt38Kj-L_mAv-svz8MGtcPYP) Link is to verbose version of code. Explanation: Ports the sublinear Python solution mentioned by @CommandMaster.
```
โฯ
๏ผฎ
```
Input `n`.
```
โโฆโฆฮท
```
Set up a dictionary to cache calculated results.
```
๏ผฆฯ
```
Loop over the values that need to be calculated.
```
๏ผฆยฌยงฮทฮนยซ
```
Verify that this value hasn't actually been calculated.
```
โฮนฮถโยฒฮตโรทฮนฮตฮดโโฆโงฮบ๏ผทโบฮดยนยซโโรทฮนฮดฮปยฟยงฮทฮดโงโบรโปฮปฮตโโยงฮทฮดฮถโฮบฮดโฮปฮตโรทฮนฮปฮดยป
```
Try to calculate the result for this value, but if any dependent values haven't yet been calculated, collect them in a list.
```
ยฟฮบ๏ผฆโ๏ผฏฮบฮนโฯ
ฮป
```
If there were any dependent values that haven't yet been calculated then add them for processing and add the current value for reprocessing.
```
ยงโฮทฮนรทโบโปรฮนฮนฮถฮตยฒ
```
Otherwise actually calculate the result for the current value.
```
ยป๏ผฉยงฮทโฯ
```
Output the result for the initial value, which is always the last value to be calculated.
Edit: Saved 1 byte thanks to @JonathanAllan.
[Answer]
# JavaScript (ES12), 75 bytes
Adapted from the Python code provided on [OEIS](https://oeis.org/A002088).
```
f=(n,j=2,K)=>f[n]||=n>j?f(K=n/j|0)*(j+=J=~(n/K))-j/2+f(n,-J):n&&(n*~-n+j)/2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NU87DoJAEO09xRSE7MggiH_NYGUjRzAkGmQ1GzKb-KkAL2JjoYfyNmLQ5r3i5f3uT7H7_PF4XS_an74TzUrIcEQJcqw3klYVS2yWWiUsgalC7Crj8ZpvSoIE0TdB5OnG469xLq6rpHvzxTMYRL9IWWxCgj5BRDAgGBKMCMYEE4IpwayRvnLYwg__FKadnran1S47KgGOIbNytkXeK-xBbXfKKaVGYHDKZgLWW8RF2_o_9AE)
### Statistics
Assuming the cache is cleared after each call to `f`:
| \$n\$ | total number of calls |
| --- | --- |
| 10 | 15 |
| 100 | 193 |
| 1000 | 1407 |
| 10000 | 9111 |
| 100000 | 55009 |
[Answer]
# [Rust](https://www.rust-lang.org/), 161 bytes
Adapted from the Python code provided on [A002088](https://oeis.org/A002088)
---
Golfed version. [Try it online!](https://tio.run/##LY7NDoIwEITvPEXVyy4/QeqtTX0RYwzUEiGwmlLqgfDsWMA5fNnMTHbXjoNblnEwTJf6ZZ5CfOxbP/pS27cQuyej022f7lFNrAYSzYVjdg2cOuOgHx3T6cp2o0cF55SnlHOU31fTGeavxVpllaLcJ4XUiYIqazEGHtfgMStQtqqSPuSVnIFioOBlOmkx5/MS7vZlQ4BsiljQusuaYewcU@Gj4hyEcos@tiHX0QGO03xM/62QzcsP)(TIO has no `cached` crate, you need to run it locally.)
```
use cached::proc_macro::cached;
#[cached]
fn f(n:i32)->i32{let(mut c,mut j,mut v)=(0,2,n/2);while v>1{let b=n/v+1;c+=(b-j)*(2*f(v)-1);j=b;v=n/b;}(n*(n-1)-c+j)/2}
```
Ungolfed version. [Try it online!](https://tio.run/##dVKxboMwEN35imuGyCQkAbpEpiB169IpH1Ah6hSIcSJslCHi29OzMSm07g3G4r27e3d@bSfV/d5JBlJ9UlqcOWeFqs5CUvqWy/I9vySeJ1XbFQpewzAO93u4eYBR5EXJKFjWS/UcB4BHFni951XNhf/iHwUIdiU@bDI4MH60v3VwpqDp1FAS0rEmpSYhefAMvq2EZK0iYQDhBHs0s1V6g6AU2/uLKbLUTST2DkBQLdaIwe9ES5OrojSk7dDOJAp/QtFxODeMLFsmO658SDMYrsGM9KGBed5sXBw1TP6Fa4Tj/@FThLiAHdR/Odey4kwzMogcAsYydWxLIHMNUeIkFrBOgSB1A7UPKyDxymxH7@UU4QYh8t2ZeoA6dmM/6h2E3jn0sGFMI0LLEKYzHihQK9u5ljV5R2sbEdhCDtED4LmljIZCS6GdmrwSZDTF@CS59WA6unHm4NkMlmq2GIUYlnRpK6G4eCKLW7@YSO3v928)
```
use std::collections::HashMap;
struct A002088 {
cache: HashMap<i32, i32>,
}
impl A002088 {
fn new() -> Self {
let mut cache = HashMap::new();
cache.insert(0, 0);
A002088 { cache }
}
fn get(&mut self, n: i32) -> i32 {
match self.cache.get(&n) {
Some(&result) => result,
_ => {
let mut c = 0;
let mut j = 2;
let mut k1 = n / j;
while k1 > 1 {
let j2 = n / k1 + 1;
c += (j2 - j) * (2*self.get(k1) - 1);
j = j2;
k1 = n / j2;
}
let result = (n * (n - 1) - c + j) / 2;
self.cache.insert(n, result);
result
}
}
}
}
fn main() {
let mut a002088 = A002088::new();
let result = a002088.get(10000);
println!("{}", result);
}
```
] |
[Question]
[
## Task
A *pure mirror checkmate* is a checkmate position, where the mated king is surrounded by **8** empty squares which are attacked or guarded by the winning side ***exactly* once**. You will be given a valid chess position where Black is in mate. Your task is to find if that mate is a *pure mirror checkmate*.
#### Examples (click for larger images)
1. This is a pure mirror mate. Squares f5, g5, are protected by the king only, h5, h6, h7 by the rook only and f6, f7, g7 by the two knights only.
[](https://i.stack.imgur.com/g5Zn9.png)
---
2. This position does not match the criteria. It is a mirror mate, but *it's not pure*, as d7 is guarded by the bishop **and** attacked by the rook.
[](https://i.stack.imgur.com/1IJjB.png)
---
3. This position is not a pure mirror mate as well, since the king is not surrounded by 8 empty squares.
[](https://i.stack.imgur.com/Nlxrf.png)
---
4. This is a pure mate, but not a mirror mate (not all 8 squares surrounding the king are empty), therefore it doesn't meet the criteria:
[](https://i.stack.imgur.com/0pPGe.png)
## Input
As mentioned above, your input will be a **valid** chess position, where black will be in mate. You may take the input as an [FEN](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation) or as a grid/matrix/2D array. From the examples above:
1. first position:
```
4N2N/4q3/6k1/8/5K2/8/8/7R
. . . . N . . N
. . . . q . . .
. . . . . . k .
. . . . . . . .
. . . . . K . .
. . . . . . . .
. . . . . . . .
. . . . . . . R
```
2. second position
```
8/R7/4k3/2P3P1/3K4/7B/8/8
. . . . . . . .
R . . . . . . .
. . . . k . . .
. . P . . . P .
. . . K . . . .
. . . . . . . B
. . . . . . . .
. . . . . . . .
```
3. third position
```
7b/8/8/5N2/8/7k/5N2/7K
. . . . . . . b
. . . . . . . .
. . . . . . . .
. . . . . N . .
. . . . . . . .
. . . . . . . k
. . . . . N . .
. . . . . . . K
```
4. fourth position:
```
2NN4/4k3/1b2NNb1/8/6N1/8/6K1/q6n
. . N N . . . .
. . . . k . . .
. b . . N N b .
. . . . . . . .
. . . . . . N .
. . . . . . . .
. . . . . . K .
q . . . . . . n
```
## Rules
* The chess position will *always* be valid and black will *always* be in mate.
* There will be no double checks (the king won't be attacked twice).
* You can receive input through any of the standard IO methods.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
[Answer]
# [Python](https://www.python.org) + [chess](https://python-chess.readthedocs.io/en/latest/index.html), ~~175~~ ~~166~~ 161 bytes
```
def f(e):b=chess.Board(e);s=b.attacks(k:=b.king(0));b.remove_piece_at(k);return(any(len(b.attackers(1,q))>1or b.piece_at(q)for q in s)or len(s)<8)^1
import chess
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VZBBbsIwEEX3nCJi5ZHaTJ2EOCLQBdtIFuIARXFwSmRwEttU4ixs6KK9U29TJy1IbEZ_Ru_PfM3luzu7fauv16-Tq5-zn8-drIOaSJiLZbWX1oartjQ7P8jtUoSlc2WlLFFz36hGv5MXgFyERh7bD7ntGlnJbemIgtxIdzKalPpMDlKTm1caS-hTD_BKWxOI8G7pofaDPmh0YMGrwWRhkcEbnTTHrjUuGAP9B710ptGO1GSa8Ihj0seYKooZzorI1wzZZgowuVMZbhgmKsZoHa8pxkWCbDWADxQTo3fGhx1MjYIVD0jEeTIuosJLMZxM-VgLin2qPfwX8fbTXw)
-9 bytes thanks to rule clarification by @l4m2
-4 bytes because I realised I could just use `chess.Board` instead of `chess.BaseBoard`
Takes the fen as input and outputs `1` for a pure mirror mate and `0` otherwise. Using the chess library certainly made this easier. Explanation:
```
def f(e):
b=chess.Board(e) # Generates the board with the input fen
k=b.king(0) # Finds the square of the black king
s=b.attacks(k) # Get a generator of all squares surrounding the king by finding the squares he attacks
b.remove_piece_at(k) # Remove the king from the square to allow us to find guarded squares
return(
any( # If any of the following return True
[len(b.attackers(1,q))>1# There is more than one attacker
or b.piece_at(q) # Or there is a piece present
for q in s] # In the squares surrounding the king
)or # or
len(s)<8 # There are less than 8 squares surrounding the king
)^1 # Flip boolean and return
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~381 334~~ 330 bytes
```
B=>(Q=q=>B.some((b,i)=>b.some((R,j)=>q?+q?'*kk'[(K-i)**2+(L-j)**2]==R&&!(Q[++k,[K,L]]^=1):!eval(q,x=I-i,y=J-j)&R=='.'&&Q(1,K=i,L=j):(I=i,J=j,h=(m,n,r=4,p=i+m,q=j+n,x=B[K=p])=>x&&(x[L=q]in{k,'.':0})?Q(1)|h(m,n,r,p+m,q+n):r&&h(n,-m,r-1),z={N:`x*x-5`,P:`-x`,K:`x*x>2`}[R])?Q('y*y+'+z):R in{R,Q}&&h(1,0)||R in{B,Q}&&h(1,1))))(k=0)|k<8
```
[Try it online!](https://tio.run/##tZNdT8IwFIbv/RXKRdeuZ4QRTcz0QLI7KFlgt8vMQFG2wsbAkPH127HzAwNBBZ1Lmpxz@vY57bs26s660/tJOH424uShv3lMEtzYWKMdTLFml6fJqE9pD0KGtd575kKksrTO07qmS6l5VBgh0/Uqpy0jygMf0SXkgnY8ziV4Alq@f4cmsy76s@6QppBhwwhhjk2lJy6iVtYI6VATBIbQwohZtKGiJkYwQDqCGCZ4CWMM@QhSjHisCLYncOyrnWSE0MxrYeqH8VKCYlmVNasrHFsN3hbDOF/IY2ZNCBnQGIwRTAyTwQKXjhVkemZcBdC2AiMLQLwWatVg7bl@ztHm@pxrfMEs91y1cKGzzikmVNhq9VqytyWTqY9KVFPy9npzc3afxNNk2C8Pkyeq3KXemVcql2BnODuxDwck6U5@UPIx5M@SHyjiuEbFSdxc4jN2nF0H4O7p/eXXkvaetH2YIk4/qF2co7@yq/fff9Qp9F7IQhqJo@xy9h7i6Vent7c9Z1v7qxdOIRTxKUm/ocQfdm1eAA "JavaScript (Node.js) โ Try It Online")
-2 bytes from Kevin Cruijssen
-4 bytes from emanresu A
```
foo = a=>g1(k=0)|k<8;
g1 = q=>a.some((b,i)=>b.some((c,j)=>(
I=i,J=j,
c=='N'?g2((x,y)=>x*x+y*y-5): // Knight
c=='P'?g2((x,y)=>y*y-x):
c=='K'?g2((x,y)=>x*x+y*y>2):
c=='R'?h(1,0):
c=='B'?h(1,1):
c=='Q'?h(1,1)|h(1,0):
0
)));
g2 = q=>a.some((b,i)=>b.some((c,j)=>
!q(I-i,J-j)& // Correct destination
c=='.'&& // Empty
g3(1,K=i,L=j) // then go
));
g3 = q=>a.some((b,i)=>b.some((c,j)=>
[,1,1][(K-i)**2+(L-j)**2]&c=='k'? // Near king
!(g[M=[K,L]]=!g[++k,M]) // count as an attack
:0 // and memory the pos
));
h = (m,n,r=4,p=i+m,q=j+n,x=a[K=p])=>
x&&(x[L=q]=='.'|x[q]=='k')? // Not blocked
g3(1)|h(m,n,r,p+m,q+n): // Next step
r&&h(n,-m,r-1) // rotate 90 degree
```
] |
[Question]
[
If you convert a chemical formula to lower case, it may become ambiguous: `co` can be both `CO` or `Co`.
Given an input consisting of `a-z0-9`, where `0` can only stand behind `0-9`. Check whether it's ambiguous, unambiguous, or impossible. Return 3 different values for them. Shortest code wins.
Examples:
```
co - ambiguous
2h83o6 - unambiguous
li - unambiguous
l - impossible
cli - ambiguous
c10h7o - unambiguous
```
One-sentence meaning: Is there zero, one or multiple ways to split input into concatenation of the following strings, case insensitive:
```
0,1,2,3,4,5,6,7,8,9,H,He,Li,Be,B,C,N,O,F,Ne,Na,Mg,Al,Si,P,S,Cl,Ar,K,Ca,Sc,Ti,V,Cr,Mn,Fe,Co,Ni,Cu,Zn,Ga,Ge,As,Se,Br,Kr,Rb,Sr,Y,Zr,Nb,Mo,Tc,Ru,Rh,Pd,Ag,Cd,In,Sn,Sb,Te,I,Xe,Cs,Ba,La,Ce,Pr,Nd,Pm,Sm,Eu,Gd,Tb,Dy,Ho,Er,Tm,Yb,Lu,Hf,Ta,W,Re,Os,Ir,Pt,Au,Hg,Tl,Pb,Bi,Po,At,Rn,Fr,Ra,Ac,Th,Pa,U,Np,Pu,Am,Cm,Bk,Cf,Es,Fm,Md,No,Lr,Rf,Db,Sg,Bh,Hs,Mt,Ds,Rg,Cn,Nh,Fl,Mc,Lv,Ts,Og
```
# Notes
* You need to code the table into your program, since as I searched there was no question requiring an unordered chemical element table.
[Answer]
# JavaScript (ES6), 265 bytes
*Saved 6 bytes thanks to @tsh*
Expects an array of characters. Returns **0** for *unambiguous*, **1** for *ambiguous*, or **-1** for *impossible*.
```
s=>s.reduce((p,c,i)=>p|=1/c||b?b=0:/[bcfhiknopsuvwy]/.test(c)+(b=/([ace][rsu]|[cgn][ade]|[iz][nr]|a[cglmt]|b[aehikr]|c[fl-o]|d[bsy]|f[elmr]|h[efgos]|kr|l[airuv]|m[cdgnot]|n[bhiop]|o[gs]|p[abdmortu]|r[abe-hnu]|s[bcegimnr]|t[abcehilms]|xe|yb)$/.test(c+s[i+1]))-1,b=0)
```
[Try it online!](https://tio.run/##lY/NTsMwEITvPEVVcUjUJmlBAoSU8iArH@zNJjF1vFGclBb53cvyU4lDBa1Po9HnmdlXvdMBB9uPmeeKjnV5DOUm5ANVE1KS9Etc2rTc9LFcFxijeTHl6rkAg3Vrt577MO3eDqrIRwpjgukiMWWRgEZSMIRJRcDGK9AVibTvCvygohbTdaOKBjRJjFgItctYxQpMOKhYA7lO7BaobjiouB2iA22HaadiB1g1nuW/B9Na7lVkaATqQZuq42GU3kE0Za0XGWQtNbb7rB7FRul0nfB7igeT3p7GLwLYxVqlabZeypXpEdkHdpQ7bpI6gTzP58jzmTyBZkUx052xzcRTuDmD3rVP9/ww/0En/yfs7O/c/@Av9gTbrucQrHF0jsXv5EsG43rVPvKFg/d0xeA90fzSwYxXBCPvzwYfPwA "JavaScript (Node.js) โ Try It Online")
## How?
The variable \$p\$ holds the final result. The flag \$b\$ is set whenever a 2-character chemical symbol is matched.
For each character \$c\$ at position \$i\$ in the input array:
* If \$c\$ is a digit or the flag \$b\$ is set, we clear \$b\$ and leave \$p\$ unchanged.
* Otherwise, we compute:
```
p |= /E1/.test(c) + (b = /E2/.test(c + s[i + 1])) - 1
```
where `/E1/` and `/E2/` are regular expressions matching 1-character and 2-character chemical symbols respectively.
Which leads to:
```
/E1/ matching | /E2/ matching | sum - 1 | meaning
---------------+---------------+---------+------------
no | no | -1 | impossible
no | yes | 0 | unchanged
yes | no | 0 | unchanged
yes | yes | 1 | ambiguous
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 194 bytes
```
โรฤฟcแนยฆmรแนy|3ยน,GฦยงแธCฦคแนแปดฦฦรยกษฑษkศทยถสแบกโบแปแป9ฤลผแธฃรท8รCโผยณยฐ0|Kแนชฦล@:แธคvฦฅรฦญsษฒแบธpI0โทtรOยงฦ;แธท8แธhฤฑAโฌแธแนชแธท`ษฆแธaยฅIฦญแปฦครฑยกรท?ยฒแบกยฉล5EแบแนขษฒโบศทษL4QยคFโน~แนพโธแนชแน|eฤgแนโฌแนษ ฦฒ2สโบษฑแธแธณWฦษ แน;โต2nศฆฦ]แนUแน84ยฅแบธแนชแธฒdรพยนแบdยฉโแนรแบ รD;ยตeโฌรD;รAยคลแน
ยขลlโธลแนยคeโฌโฌศฆฦLยซ2
```
[Try it online!](https://tio.run/##JY9bSwJREMff@xThcw9mN8uHim5EQfQQPQWFSVaWQREEEu4WbVgRKLR211qNbpB22XPWKJjjHjx9izlfZDtbMAz/GWZ@85@lWCKx5XkyfcHM@ncU6RmUV9g10vOtVBvQlhGegTskBwPcQqpj7Y0bfJ8ZUBQVkVtu2PDxo6NTlJqDtQOsHXXXTfcTyS2zw2xvQGqf8AovwdQY0ge@76b7epBYm7zEdvnzuqiiQ9ZGg1KzN9jVBNzxbASJHUZyHa9X@qX@hCSjFlVvVpSVnoPSKH9Wh7jFKlBkdi8oRBHu3VzHEDrHSG9EVVlp2MIcb58Ea1hqdBvpl9SIz6G7qVjdXEB64rOpLgq8GvrR1YaoIDlE8jrN86Kgno9I7T202ijzyxmkxhTSvXA7lJTdPzvVefYFFJ3MPNzL9CnSHZZHp8DygxF4jym2r1i@Hyw3h9Rsghs3m1Ae3Kw6DZY/oULRjXF4DHnMUJXnBaLJQEtzIBQPtyU7fZVY/Mt@iv7raGsw3pUM/AI "Jelly โ Try It Online")
-2 bytes thanks to caird coinheringaahing via better usage of chaining
Output 2 for ambiguous, 1 for unambiguous, 0 for impossible.
The logic behind this is pretty trivial, I just need to figure out a better way of encoding this periodic table...
```
โ...โแนรแบ รD;ยตeโฌรD;รAยคลแน Helper Link; produce the list of components
โ...โ Compressed Integer
แนรแบ Base-decoded into the upper and lower-case alphabet
รD; Prepend the digits (as strings) as well
ยต With the list of components (joined on nothing) as the left argument
eโฌ Check if each element is in
รD;รAยค The digits + uppercase alphabet
ลแน And partition the components before those indices
ยขลlโธลแนยคeโฌโฌศฆฦLยซ2 Main Link
ยขลl The components above, lowercased
โธลแนยค All ways of partitioning the input
โฌ For each partition
โฌ For each component
e Is it in the list of valid components?
ศฆฦ Filter to keep partitions where every component was valid
L Length; 0 if impossible, 1 if unambiguous, 2+ if ambiguous
ยซ2 Minimum of the above and 2 (sets ambiguous case to 2 no matter how many occurrences existed)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 117 bytes
Prints `-1` for impossible, `0` for unambiguous and `1` for ambiguous.
```
.ลฮต.โขBโฮโโ
H^ฦถฦตXJโรฆโยบlยฆยฏรญ-ฤะผIรตVรK:ฮโ(ยทรทฮKรฅ<70'Vโโยฑฮถรลกรโบยฟฤร
Rรฮuโรญpฤ<รยฟรฝรQะผรรฌโฐรวโยงKhรบฮณIรรM`รฮนลกโข#โฌSASรตลกรธฮต`รฌ}หลพhSยซsรฅP}O<.ยฑ
```
[Try it online!](https://tio.run/##JY7NS8JgHMf/lViHOtSwgozYpU7ZiF4GEkRhjWCCsEA6Co@CIVkH2Q7lS2CgHZqUxLSGJTzfzQ7Bg3/D7x9ZW10@fC7fFzN/epY9D4UbyoElXJnY4yaxurCJ2VQqb51MBhP3cJsqt@gSa3Ivx7v8Bb1FvzgdpeCmUVPXRYPY3TwfYigsFR0lmZhLRwmqPPC@GKAetFEl5vGxf4XyAe6FfUmshd6FX1TA@BifuNmfjtCAQ@wV1ncrnnpSDXjiLYUaqjsZXIuPoB3dm6WSo21ocKPWd@Fm4BR@msGXofHnPDp7hV1F5v0wPJJ0U1qYkZaNtRVzNbZc9o8x9H/XlxJG0pSOfwE "05AB1E โ Try It Online")
```
.ล # push all partitions of the input
ฮต } # map over the partitions:
... # push the table of valid parts (see below)
s # swap to the current partition
รฅP # test if every part is in the table
O # take the sum over all results
< # decrease by 1
.ยฑ # print the sign of this
```
#### Compressing the table
```
.โขB...ลกโข # alphabet compressed string (contains 26 spaces)
# # split on spaces
โฌS # split each string into a list of chars
ASรตลก # the characters of the alphabet with the empty string prepended
รธฮต`รฌ} # zip alphabet with previous list and prepend matching characters
ห # flatten the list
ลพhSยซ # append the digits
```
[Try this part with step-by-step output!](https://tio.run/##XY67SgNBFIb7fYphLbSIYieIFrEQNVhoRMRCHHfH7MBmd8iMioUwCop4KcQU3iJEUAsjKhIvwQvsSbQQFp9hXiTOZhMF2/Of7/t/n@M5Sur1LiXPBpQ8CvNK5tXa@tDMx8NHeWpEbe7ChZInQcUNLoIbuO6srn6/DEN5EvZSveGxkgcdwSM8hvspOO/r6W6f1ITaPA3uwgc4qhVhW8lK8F7dgPVxOAzzC0oW4JpVV/tABu/wCjtj3y9wDCUlb2H/sxBVXaYcqIT3w7AH26OzsBU@14p6nmEmXebgOSKQ5WdZjnBObMRFjnqZXjPRbxhthmmkmUsF8j3EGbYIjwO1Vkr/ZgRbThND1BM@wsilXDPzyHJwrokk01CuFTU04ZDGHVuC5Hj0JfQFt6YsUeE0LiTLxHLLq9cx4tnEjmXwFJZnobSiddOU/YP17yL1F3i8Ant2i0ZZLCwn0v31x76vE20adLEQxGuUR2gc1d6cdHCl4yRrOKLUphkqmqhpJuAWXhP1@g8)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 124 bytes
```
โโฌแนกฦฅvแบรhส !แปแบ?iแธฅแบแปยน'แน
ษฆรงรงโน.Sรฐ$แนแน ศฅแนขK}/>ล;แปตZฦคแบ}:;tรแนพแธถjโถแธแปตแธฤฐส Uแธแบยฝ^ษฒแนรแนยตโถรฆแธษฆ1ยฅยฉแธรพjHแนแนชแปคฦgแบกศฅแธแนพแธฦฦ@รโพรฆฦญVแบแนฃโแธ90รแธ26แปรaรDWโฌยค;
ลแนfฦฦยขLยซ2
```
[Try it online!](https://tio.run/##JY9LS0JRFIXn/Yq6BE2i1MAeQjVoENQsKmgQhFQqgpMIGghqppFBmRAWkY@8V3qBBMrZ95KDs/OQ/ot1/8jtaJO1F6zFt1mxw3j8zPPc1JOb@QDVlHkK@4azkUF1Ak4B9uVKFMKEXYBzLWkKdNG3uMlNN00zW9yaBD2Cqr8mqL6RnF3ulUJw2nuqAbuUXAqdcA7UhejE3HQHIqsziMJPa1DdhrjSdPm93/8C5bgCysu2brEFUelbfmnKV@24G1sHpUBvcBqqeAy7pp@JzAj7rEqquMq3brrLlvrc0UDQi5t6gDhf9HFWn0BQz@DyAZfXdvVE2QiN9e5A90eqqPKyvinfAx7ndeJ5RjhhTI8bgcjCXCI4dPHoSIcS/vdhvy8ynzD@AA "Jelly โ Try It Online")
A set of links that takes a string argument and returns 0 for impossible, 1 for a single valid interpretation and 2 for ambiguous.
Loosely based on [@hyper-neutrinoโs answer](https://codegolf.stackexchange.com/a/226852/42248), but mostly rewritten.
] |
[Question]
[
**Introduction**
This is a web scraping Code Golf challenge that attempts to take stock Name and price columns from the 'Most Active' list on this [New York Times URL](https://markets.on.nytimes.com/research/markets/overview/overview.asp).
**Why is this challenge interesting?**
Challenge:
Scrape these figures from this NYT page and turn it into a data frame using the smallest number of bytes possible (IE: `import pandas as pd` (should you choose to use Python) would give you a score of 19 (19 bytes). The data frame must be printed or returned as output.
[](https://i.stack.imgur.com/EFrTK.png)
Shortest Code by bytes wins the challenge. That's it!
Input:
>
>
> ```
> import requests
> from bs4 import BeautifulSoup
> import pandas as pd
>
> url='https://markets.on.nytimes.com/research/markets/overview/overview.asp'
>
> def pull_active(url):
> # your code
> response = requests.get(url)
> if response.status_code == 200:
> print("Response Successful")
> else:
> print("Response Unsuccessful")
> return()
> bs_object = BeautifulSoup(response.content,'lxml')
> st_value = bs_object.find_all('td',class_='colPrimary')
> st_name = bs_object.find_all('a',class_="truncateMeTo1")
> x = []
> y = []
> for tag in st_name:
> x.append(tag.get_text())
> for tag in st_value:
> y.append(tag.get_text())
> data = {'Name': x[0:8],
> 'Price': y[0:8]}
> df = pd.DataFrame(data)
> return(df)
> pull_active(url)
>
> ```
>
>
Score: 773 bytes
To beat it, any code under 773 bytes.
Output:
>
>
> ```
> Name Price
> 0 General Electric Co 10.11
> 1 Advanced Micro Devices Inc 33.13
> 2 PG&E Corp 6.14
> 3 Fiat Chrysler Automobiles NV 14.98
> 4 Neuralstem Inc 1.83
> 5 AT&T Inc 38.20
> 6 GrubHub Inc 34.00
> 7 Twitter Inc 29.86
>
> ```
>
>
...
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + [lynx](http://lynx.browser.org/), 73
```
lynx -dump http://nyti.ms/2BY72Ph|grep -Po '\[(1[6-9]|2[0-3])]\K[^.]*...'
```
Output is as follows:
```
General Electric Co 10.11
Advanced Micro Devices Inc 33.13
PG&E Corp 6.14
Fiat Chrysler Automobiles NV 14.98
Neuralstem Inc 1.83
AT&T Inc 38.20
GrubHub Inc 34.00
Twitter Inc 29.86
```
[Answer]
# [R](https://www.r-project.org/), 97 bytes
```
library(rvest)
matrix(html_text(html_nodes(html("http://nyti.ms/2BY72Ph"),"td"))[2:25],,3,T)[,-3]
```
[Try it online!](https://tio.run/##K/r/PyczqSixqFKjqCy1uESTKzexpCizQiOjJDcnviS1ogTCystPSS0GMzWUMkpKCqz09fMqSzL1cov1jZwizY0CMpQ0dZRKUpQ0NaONrIxMY3V0jHVCNKN1dI1j//8HAA "R โ Try It Online")
Gets all the `td` elements of the page. We want elements 2 to 25, which gives everything we need plus the `% change`, which is removed by omitting the 3rd column of the final matrix.
Outputs as a character matrix, since this is less bytes than a data frame:
```
[,1] [,2]
[1,] "General Electric Co" "10.11"
[2,] "PG&E Corp" "6.14"
[3,] "Neuralstem Inc" "1.83"
[4,] "GrubHub Inc" "34.00"
[5,] "Twitter Inc" "29.86"
[6,] "Zynga Inc" "6.21"
[7,] "Iveric Bio Inc" "3.56"
[8,] "Pfizer Inc" "38.48"
```
[Answer]
# [PHP](https://php.net/), ~~154~~ ~~153~~ 130 bytes
```
foreach(DOMDocument::loadHTMLFile('http://nyti.ms/2BY72Ph')->getElementsByTagName(td)as$i)$x<24&&print$x++%3?"$i->nodeValue ":"
";
```
[Try it online!](https://tio.run/##FctNC4IwGADge78ixvIDMcGCYImCWHTI8iBBx6FvbjC3oa@gv97q8tweK@yaZPbnxwzAG@EVz7IwzdSDRsaU4e2tLu9XqcBzBaJlUaQXlPt@jOL8fYor4fph2gFeFPzPmC817x68Bw9bn49U@nRO4qPj2EFqpHMQ7A4ZoTJMtWnhxdUEW8LIhpzX9Qs "PHP โ Try It Online")
*-23 bytes* thx to @Night2!
```
$ php nyt.php
Agile Therapeutics Inc 1.38
Advanced Micro Devices Inc 34.05
Facebook Inc 191.82
Kraft Heinz Co 32.34
Sirius XM Holdings Inc 6.72
Apple Inc 247.40
Zynga Inc 6.24
Snap Inc 15.11
```
[Answer]
# [F# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~271~~ ~~257~~ ~~251~~ 233 bytes
```
let l=HtmlDocument.Load("http://nyti.ms/2BY72Ph").Descendants["td"]|>Seq.filter(fun n->n.HasClass("colText")||n.HasClass("colPrimary"))|>Seq.take 16|>Seq.map(fun n->n.InnerText())|>Seq.toList
[for i in 0..7-> l.[i*2]+" "+l.[i*2+1]]
```
[Try it online!](https://tio.run/##XZBPS8NAEMXv@RTDgpBYuv1zsCAmB1ulQg/FepGQw5JMzOLubNydioF@95imUME5vXm89zu8OkxL57F3LRIcusBoo1E/HxrlW7lRrKLIIEMDaQ9nYdItW7Nx5dEisdw5VcWiYW7vZzPqWEsbZsvH99Vy34hEbjCUSJUiDrngShSn7IBfstaG0cf1kYCmGcmtCmujQohF6cwb/rBITqd/9t5rq3wnkuTCYPWJsLi7PFa1f7QXIvRnSnzNup0OHEFeOw8aNMFcytU0AyNzfbssJgLE5KIni6Lo84cnYt/tnSbOinEAq4aW8h/fkEYw3NnzGI6GIYVmtK7wBioHrR/KNYG4CQL0GFg7Cs6gfMVhtGS05v0v "F# (.NET Core) โ Try It Online")
] |
[Question]
[
Do you know [Icy Tower](https://en.wikipedia.org/wiki/Icy_Tower) ? Here is a [gameplay example](https://www.youtube.com/watch?v=TmyRdsuXdd0) of what i'm talking about
The game concept is simple : you play as Harold the Homeboy, and your goal is to jump from floors to floors to go as high as possible without falling and getting off-screen ( the camera goes higher following you or at a speed that gets faster over time, and does not go down ).
If you get off-screen ( fell or camera was too fast for you to keep up ), it's game over, and then you get a score.
Your task is to write a program/function/whatever that calculates the score based on a input.
### How to calculate the score :
The formula is simple : \$Score = 10 \* LastFloor + Sum(ValidComboList.TotalFloorJumped^2)\$
### What is a valid combo ?
You have to jump from floors to floors to go as high as possible. Sometimes, you will the to the floor \$F+1\$
But sometimes, if you go fast enough ( faster = higher jumps ), you will do a multi-floor jump, and skip some floors between. A combo is a sequence of multi-floors jump. To be considered as a multi-floor jump, you need to skip at least 1 floor, meaning you need to get to the floor \$F+x\$ where \$x >= 2\$
See that you always jump to \$x >= 2\$, jumps to lower floors with floors skipped between are not considered valid
A combo ends when :
* You jump to the floor \$F+x\$ where \$(x < 0) | (x == 1)\$
* You wait more than about 3 seconds on the same floor ( in the gameplay video, you can see on the left a "timing bar", and the combo ends if it gets empty )
* You get off-screen ( falling or not jumping fast enough )
In this challenge, to simplify a bit, we will consider that, when the input indicates a "jump to the same floor \$F+0\$" means that the 3 second timeout is passed, so the two rules will be simplified in one :
"You jump to the floor \$F+x\$ where \$x<2\$
A valid combo ( a combo that will be used for the score calculation ) :
* The number of multi-floor jumps \$N >= 2\$
* The combo MUST NOT end with going off-screen. If you go off-screen, the combo is invalid and won't included in the score. Said in another way : The combo must be followed by a jump to another floor or by waiting about 3 seconds.
In this challenge, since we consider that jumping to the same floor is waiting 3 seconds, the rules to make a valid combo is "You must jump to another floor"
Since you need at least 2 multi-floor jumps to make a combo, the number of total floor jumped is higher than 4
### The input
The input will be a "list" of integers ( or STDIN input ) which represents the sequence of floor jumped on. For example, the start to the video linked previously in the post will look like :
```
[5 4 5 10 12 15 17 18 19 20 23 24 25 28 29 30 31 34 35 36 37 34 35 36 37 38 39 40 43 48 45 46 50 55 54]
```
for the first floors. The start floor is ommited. This input end on floor 54 meaning he went off-screen just after that, without getting to another floor, so there's the game over ( this was not the case in the video since he went to the floor 232, so the array accurately representing the sequence would end with 232 at the end )
Here, with this input, you must output \$829\$, because :
\$Score = 10 \* 54 + 12^2 + 8^2 + 9^2\$ Because the last floor Harold was on is the floor number 54, and he made 3 valid combos :
* First combo of 4 multi-floor jumps with a total of 12 floors jumped in that combo
* Second combo of 2 multi-floor jumps with a total of 8 floors jumped in that combo
* The last combo of 2 multi-floor jumps with a total of 9 floors jumped in that combo
## Test cases :
`[] => Undefined Behavior`
`[5]` => \$50\$
`[4 0 5 6 8 10 10]` => \$10\*10 + 4^2 = 116\$ **Correction applied**
`[4 0 5 6 6 6 6 8 10 10]` => \$10\*10 + 4^2 = 116\$ ( Here, Harold just waited 9 seconds. No combo to validate, but still a legitimate input ) **Correction applied**
`[5 7 10 10 11 9 14 17 15 16]` => \$10\*16 + 10^2 + 8^2 = 324\$
`[5 4 5 10 12 15 17 18 19 20 23 24 25 28 29 30 31 34 35 36 37 34 35 36 37 38 39 40 43 48 45 46 50 55 54]` => \$10 \* 54 + 12^2 + 8^2 + 9^2 = 829\$
`[5 4 5 10 12 15 17 18 19 20 23 24 25 28 29 30 31 34 35 36 37 34 35 36 37 38 39 40 43 48 45 46 50 55 56]` => \$10 \* 54 + 12^2 + 8^2 + 9^2 = 849\$
`[5 4 5 10 12 15 17 18 19 20 23 24 25 28 29 30 31 34 35 36 37 34 35 36 37 38 39 40 43 48 45 46 50 55 55]` => \$10 \* 55 + 12^2 + 8^2 + 9^2 = 839\$ ( harold waited 3 seconds to validate the combo )
`[5 4 5 10 12 15 17 18 19 20 23 24 25 28 29 30 31 34 35 36 37 34 35 36 37 38 39 40 43 48 45 46 50 55]` => \$10 \* 55 + 12^2 + 8^2 = 758\$ ( because harold went off-screen without confirming the combo)
If you want, you can condsider that the input always starts with zero ( since the game start at floor 0 ), if this is the case, say it in your answer
## Rules :
* Input and output in [any convenient way](https://codegolf.meta.stackexchange.com/q/2447/72535)
* Full program, or function, or lambda, or macro are acceptable
* [Standard Loopholes](https://codegolf.meta.stackexchange.com/q/1061/72535) are forbidden
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lower number of bytes are better
Edit : Correction applied on some test cases
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~28~~ ~~27~~ 24 bytes
*-1 byte from @kamil <3, -3 from @Shaggy :o. These guys are genius*
```
รค- รด>2n)ยฏJ lร mx xยฒ+A*Uo
```
[Try it online!](https://tio.run/##bY07DsJADAWv4hbYSMT2EtIgpU2XggqloEX8CopcgXukR0I5QfZgy6SnGMseP9mX8/OVcxoLSdNB76v508o1veU2yDB/N836@Mj5FIN4EGq5BYWlr2APdRDFqwExZad4xRveSsAb3nZQ/ZnJG3kn79xxZl@@so@4SB@9l6L7AQ) or [Test it all](https://tio.run/##vY87CsJQEEV7V3FbNULeZ/JpBFtLwSqksBV/hYVbcB/2grgCs7B4kjQK1pLcx8yd4Z37tpvTuW2b20zNc@4P49d9qV1z1f6iy@sxXUzWx7atRlUqq7szikqZCrmU/8sbvs@JKR86OadSLsphmFw2jBPFpDtdijzq6hwVqEzk8X1ArHlmHt/jB/zgEH7ADxnKf/TsB/Yj@5F7In3sqMwNz6gtksV4hPU5fZ@PlLyjJAB88NCBwwYNGRAcMFC@6wIeOGjAYIGCBEiW/Yljf@HUo1qz/eoN)
---
# [Japt](https://github.com/ETHproductions/japt), 28 bytes, prev approach
*Naive Way*.
**Important** Input should start with 0 to work correctly (in some cases)
```
o *A+UรณรรยฆYยฉY>Xรl>2 ยฎรค- xรxp
```
[Try it online!](https://tio.run/##bY0xCgJBDEWvklpnwU1mXG0WPIKF4CIWtiK4hcX2a@FBRLCx8QaTg41ve4sXkpdPcj71t1KuMtvMd/71h9/zq8vvrt37eGlV8seflQw@Dn0phxQkBqHWC1CY@gZWsA6ieDUgpuwUr3jDWw14w9sSmj8zeSMfyUfuROY4fWWfcIk@xaNU2x8 "Japt โ Try It Online") or [Test it all](https://tio.run/##vY@9isJQEIV7n@LUboTcn8lPI/gKgqBICttll7WwSK@FDyKCjc2@Qe6DZb@YZgVrSc5l5sxwv3M/d/tD3/9ouvhYpd90Tqfuuulum/k6Hb/mXt09XWZq07Hd9/12ss1lzXBGUalQJZfzP3nj939iKsdOzqmWi3IYJleM40wxG06XI4@GukQVqjN5fB8Qa56Zx/f4AT84hB/wQ4HKFz37gf3IfuSeSB8HKnPDM2qLZDEeYY@c/pGPlLyjJgB88NCBwwYNGRAcMFCe6woeOGjAYIGCBEhWvIljb@E0k0az7@Uf)
[Answer]
# JavaScript (ES7), 72 bytes
```
a=>a.map(v=>(v-p>1?r=c++?r:p:t+=(c>1)*(c=0,p-r)**2,p=v),t=c=p=0)&&t+p*10
```
[Try it online!](https://tio.run/##xZLLboMwEEX3/QpWkQ2XxE8wkUyk/kNXVRcWj5YqBYsgfp@6DVk0VdUl8iwsz7lzbMnvbnaXauz8lPZD3SytXZwt3f7DeTLbksypL/lptFWSnMajP06JJVXJaUwqy@DTkcaxgLczxWQr6y2ju92U@JizpRr6y3Bu9ufhlbTk@YXS6HCInvq6abu@qaPH5s3N3TA@3IF6JTW77ygwaGQw4CzUynGe/QVe17@4Rn5FwDkKcAUeDjR4tmakUL8zKii@IuIbDYHgKSAYhIRQEBrCQBSQDJJDKkgNmUHmP/cGsoBiUBLKQIW5GXS4voZWq96IYgv97fVGbaK//QMjN9Cv7lyb5RM "JavaScript (Node.js) โ Try It Online")
### Commented
```
a => // a[] = input array
a.map(v => ( // for each value v in a[]:
v - p > 1 ? // if the difference with the previous floor is greater than 1:
r = c++ ? // increment the combo counter c; if c was not equal to 0:
r // leave r unchanged
: // else:
p // set r (reference floor) to the previous floor p
: // else:
t += // update t only ...
(c > 1) * ( // ... if we have a multi-floor jump combo of at least 2 jumps
c = 0, // reset c to 0
p - r // compute the total number of floors jumped in the combo
) ** 2, // square it and add it to t
p = v // set the previous value p to v
), //
t = c = p = 0 // start with t = c = p = 0
) && // end of map()
t + p * 10 // add the final floor multiplied by 10 to t
```
[Answer]
# J, 54 bytes
```
[:((10*{:)+1#.[:}:]((2<#)*[:*:{:-{.);.1~1,2>2-~/\])0&,
```
[Try it online!](https://tio.run/##vZHBTsMwDIbve4pfTGJNaUsc22lqGBckTpy4lp3QpokLD1CxVy9Z28skzlUSKbE/@XOS7/Gu2Z2wN@xQwcPyqhu8fry/jb0VBflyMPdA26a3XzsURXjeurK30garh8Y9NXShKryE@vL4eXD@vhrd5vh1/oF67HFCZTqfOcgUULQgP01CBxJQDigozhxRnDjJnSgi0kz/n5zHDZJCt3gkr2siTOWzJHMdgkdg5GaCIiRkmj2YwAJWcAS3t/sE7iAewpAEyXXj9XKqUFmUsp5yeaXE6ymXD2w1raTcjH8 "J โ Try It Online")
May add explanation later. For now here's an ungolfed and a parsed version:
### ungolfed
```
[: ((10 * {:) + 1 #. [: }: ] ((2 < #) * [: *: {: - {.);.1~ 1 , 2 > 2 -~/\ ]) 0&,
```
### parsed
```
โโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโ
โ[:โโโโโโโโโโโโฌโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโฌโโโ
โ โโโโโโฌโโฌโโโโ+โโโโฌโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ0โ&โ,โโ
โ โโโ10โ*โ{:โโ โโ1โ#.โโโโโฌโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโดโโโ
โ โโโโโโดโโดโโโโ โโ โ โโ[:โ}:โโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โโ โ โโ โ โโ โ โโ]โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโฌโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โโ โ โโ โ โโ โ โโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโฌโโโ~โโโ1โ,โโโโฌโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โโ โ โโ โ โโ โ โโ โโโโโโโโโโโโฌโโฌโโโโโโโโโโโโโโโโโโโ;.โ1โโ โโโ โ โโ2โ>โโโโฌโโโโโโโโโโโโโโฌโโโโโโโโโ โ
โ โโ โ โโ โ โโ โ โโ โโโโโโโฌโโฌโโโ*โโโโโฌโโโฌโโโโโโโโโโโโ โ โโ โโโ โ โโ โ โโ2โโโโโโโโโโโโฌโโโ]โโโโโโโโ โ
โ โโ โ โโ โ โโ โ โโ โโโโโ2โ<โ#โโ โโ[:โ*:โโโโโฌโโฌโโโโโโ โ โโ โโโ โ โโ โ โโ โโโโโโโโโฌโโโ\โโ โโโโโโโโ โ
โ โโ โ โโ โ โโ โ โโ โโโโโโโดโโดโโโ โโ โ โโ{:โ-โ{.โโโโ โ โโ โโโ โ โโ โ โโ โโโโโโฌโโโ/โโ โโ โโโโโโโโ โ
โ โโ โ โโ โ โโ โ โโ โโโโ โ โโ โ โโโโโดโโดโโโโโโ โ โโ โโโ โ โโ โ โโ โโโโ-โ~โโ โโ โโ โโโโโโโโ โ
โ โโ โ โโ โ โโ โ โโ โโโโ โ โโโโโดโโโดโโโโโโโโโโโโ โ โโ โโโ โ โโ โ โโ โโโโโโดโโโ โโ โโ โโโโโโโโ โ
โ โโ โ โโ โ โโ โ โโ โโโโโโโโโโโโดโโดโโโโโโโโโโโโโโโโโโโ โ โโ โโโ โ โโ โ โโ โโโโโโโโโดโโโ โโ โโโโโโโโ โ
โ โโ โ โโ โ โโ โ โโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโดโโโ โโโ โ โโ โ โโ โโโโโโโโโโโโดโโโ โโโโโโโโ โ
โ โโ โ โโ โ โโ โ โโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโ โ โโ โ โโโโดโโโโโโโโโโโโโโดโโโโโโโโโ โ
โ โโ โ โโ โ โโ โ โโ โ โโ โ โโโโดโโดโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โโ โ โโ โ โโ โ โโ โ โโโโดโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โโ โ โโ โ โโ โ โโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โโ โ โโ โ โโโโโดโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โโ โ โโโโดโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โโโโโโโโโโโโดโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโ
```
[Answer]
# [C++](https://gcc.gnu.org/), ~~202~~ ~~190~~ ~~188~~ ~~187~~ ~~184~~ ~~181~~ ~~177~~ ~~170~~ ~~166~~ 164 bytes
```
int f(int*a,int l){int r=a[l-1]*10,i=0,j,k,s;for(;i<l;i++)for(j=l;s=j-->i;s&&j-i>1&&~j+l?r+=(a[i]-a[j])*(a[i]-a[i=j]),j=l:0)for(k=j;k-i;)s*=a[k--]-a[k]>1;return r;}
```
[Try it online!](https://tio.run/##vZFba4MwGIav568IG5Rq34A5aHWpjnY/Q7wQa0vU2uLhqnR/3SUdZRR2Pcjh/eDJ9ySkvFzosSznWXcjOSzN6hWwuXWvduuTImspyz3mQyc@ajQY1OHcL5XetEqvVq4t6qRVQ1JTmmo1LBY11SlbLL7qVfvRr5JlkemcFlmdu94j68RUMOfe/XuHJqlVQ7VyB88oG0ot1OQpU301Tn1HenWb33RXttO@Iht9Hsa@Kk6pMw26OxLSFadquBRlRYZxrxzHXv5U6G7pkqvzYqttlpOrjwDSTPMcxsFMWINFYDG4Dy7AJXgAHoHHED4Eg5AQAUQIsX7OEUQM6UMKyAjS9A0RmP4BAnlTP87dfzkfws@HcH3XmcEQg8m705hDC5bnaSSbjfnvLYgIXZtfSWKmCRGP7VZ1@/YJ3Rk0eEbXQfQn@gnC2DMquPxFb/M3 "C++ (gcc) โ Try It Online")
Input must begin with 0.
-11 bytes thanks to @ceilingcat
] |
[Question]
[
Given a date, output the X and Y position of the current day of the date on a digital calendar. The digital calendar is sort of the calendar that gets shown when you click on your computers clock (at least on windows), and it looks something like this:
[](https://i.stack.imgur.com/WnLIz.png)
If we assume that the given date is 25.09.2017, the result would be `(2,5)`, because the 25th day of the 9th month of this year is in the second column and fifth row.
Note that if the date would be something like 29.08.2017, we couldn't use the calendar from above, but a new one for August. The gray-ish numbers are simply there to fill the gaps until the day that the month actually starts.
## Input
A date, in any reasonable format.
## Output
The point or coordinates that the day of the given date lies at, in its respective calendar. These should be 1-indexed.
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in any language wins.
* Standard loopholes are forbidden.
## Additional Notes
The first column of the calendar will always be **Sunday**.
Here are the digital calendars from January and September 2017:
[](https://i.stack.imgur.com/WnLIz.png)
[](https://i.stack.imgur.com/p9Bg1.png)
## Test Cases
Input: `06.02.2018 (DD.MM.YYYY)` or `2018.02.06 (YYYY.MM.DD)`
Output: `(3,2)`
Input: `12.11.1982 (DD.MM.YYYY)` or `1982.11.12 (YYYY.MM.DD)`
Output: `(6,2)`
Input: `01.01.2030 (DD.MM.YYYY)` or `2030.01.01 (YYYY.MM.DD)`
Output: `(3,1)`
Input: `13.06.3017 (DD.MM.YYYY)` or `3017.06.13 (YYYY.MM.DD)`
Output: `(6,3)`
[Answer]
# Mathematica, 83 bytes
**New Rules**:Starting on **Sunday**
```
{s=Min@Position[(d=DayName)@{6,1,#}&/@Range@7,d@DateObject@{##}],โ(#3-s)/7โ+1}&
```
*-5 bytes from @Misha Lavrov*
**Input form**
>
> [2030, 1, 1]
>
> yyyy-mm-dd
>
>
>
[Answer]
## JavaScript (ES6), ~~64~~ 59 bytes
```
f=
(s,d=new Date(s),e=d.getDay())=>[1+e,(d.getDate()-e)/7+2|0]
```
```
<input oninput=o.textContent=f(this.value)><pre id=o>
```
Input is any string which JavaScript recognises as a date. Save 16 bytes if a JavaScript date object is acceptable input. Edit: Saved 5 bytes thanks to @GrzegorzOledzki.
[Answer]
# TI-Basic (84+), 27 bytes (50 characters)
```
:Prompt Y,M,D
:dayOfWk(Y,M,D
:{Ans,2+int(7โปยน(D-Ans
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~109~~ 98 bytes
The datetime module docs are 50,000 bytes, so I'm not using the datetime module yet.
```
def f(d,m,y):t=m<3;y-=t;Y=y%100;W=(d+(13*m+156*t-27)/5-y/100*2+y/400+Y+Y/4)%7+1;print W,(d+13-W)/7
```
[Try it online!](https://tio.run/##HYvBCsIwEETv@YpQEJJmS7K7JlVrv8Fj6VVqqWC1aHrI19foYeANb2ZJcXo9aduG2yhHNcAMSZ9iO5@5SVUbm75NO3Su6Vo1GIVczgZ9KGNFtba@SjbLkkyye@dMb3q717vaYLO8788oO8gv5KrTtt5GRR6OQA5rLUYVgH58@DESIAIeD/RvgNmw@zODC8AOg96KohCXNS5rlJ/ptT4Geb2dBEkvWJIIOSxReMkiL78 "Try it Online!")
My formula to compute day of week comes from <https://cs.uwaterloo.ca/~alopez-o/math-faq/node73.html>.
The formula is as follows (converted from image to text):
>
> W = (k + floor(2.6\*m-0.2) - 2\*C + Y + floor(Y/4) + floor(C/4)) mod 7
>
>
> where floor(k) denotes the integer floor function
>
>
> k is day (1 to 31)
>
>
> m is month (1 = March, ..., 10 = December, 11 = Jan, 12 = Feb) Treat Jan & Feb as months of the preceding year C is century (1987 has C = 19)
>
>
> Y is year (1987 has Y = 87 except Y = 86 for Jan & Feb)
>
>
> W is week day (0 = Sunday, ..., 6 = Saturday)
>
>
> Here the century and 400 year corrections are built into the formula. The floor(2.6\*m-0.2) term relates to the repetitive pattern that the 30-day months show when March is taken as the first month.
>
>
>
The row number can be calculated as one more than the number of Sundays in the month preceding the day.
*-7 bytes thanks to @GrzegorzOledzki*
] |
Subsets and Splits