text
stringlengths 180
608k
|
---|
[Question]
[
We do seem to have a [fastest square root](https://codegolf.stackexchange.com/q/85555/66833) challenge, but it's very restrictive. In this challenge, your program (or function) will be given an arbitrarily sized nonnegative integer, which is the square of an integer.
**Input**
You may take input in any normally allowed way, including (but not limited to) an arbitrary sized integer type, string in any base, or list of numbers representing digits.
**Output**
The allowed output methods are similar to the input ones, they just need to be in a way which can also represent a number of arbitrary size.
**Requirements**
* Your program should theoretically work correctly given any number (which is the square of an integer), assuming the language is capable of this
* All submissions should be in either:
+ A language with an online interpreter that can give (or be trivially modified to give) accurate times, and doesn't time out with your solution
+ A language with an interpreter/compiler available from the `apt` package manager, and is less than 1 GiB, in which case it will be run on my Chromebook's Linux VM
* If it doesn't take under 20 minutes, I'll just give a good estimate based on the first test cases and time complexity
* Built in square root functions are allowed (but boring :p)
**Scoring**
Your program's score will be the amount of time it takes to find the square root of:
* All 4096 perfect squares up to (not including) \$2^{24}\$
* A random (but same for all programs) 2048 perfect squares up to \$2^{48}\$
* A random (but same for all programs) 1024 perfect squares up to \$2^{144}\$
* A random (but same for all programs) 512 perfect squares up to \$2^{1440}\$
* A random (but same for all programs) 256 perfect squares up to \$2^{5760}\$
* A random (but same for all programs) 128 perfect squares up to \$2^{14400}\$
* A random (but same for all programs) 64 perfect squares up to \$2^{86400}\$
**UPDATE:** The numbers have been made bigger. This is a total of 8128 numbers as inputs, specifically [these](https://gist.github.com/Radvylf/ec631517d21f0b9b590a19e0cb34fbed/raw/74960169b733def38213213133f51a852c551976/numbers-updated.txt). Remember that fitting the test cases specifically is a standard loophole. The only part that counts toward the time is the math. I/O and setup can be ignored.
[Answer]
# C++, 140 µs
This is a trivial answer that uses GMP, but I’m submitting it anyway to drive home the point that **the test cases are way too small**. Scores in the range of literally nanoseconds per input cannot meaningfully be compared. We need larger test cases for this to be an interesting challenge.
```
#include <chrono>
#include <gmpxx.h>
#include <iostream>
#include <vector>
int main() {
std::vector<mpz_class> numbers;
mpz_class number;
while (std::cin >> number)
numbers.push_back(number);
auto t0 = std::chrono::high_resolution_clock::now();
for (auto &number : numbers)
number = sqrt(number);
auto t1 = std::chrono::high_resolution_clock::now();
for (const auto &number : numbers)
std::cout << number << '\n';
std::cout
<< std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count()
<< "ns\n";
}
```
[Try it online!](https://tio.run/##nb3drjRLdl13f56iIQMWdSEhM@OfovkKfgEBQqtFkYTJbprdtAQbfnXTa4wZ@1CGAV@4cfrLql1ZUZmREet3rrl@9w//8G//@ne/@@d//h/@9ve/@7t/@s9/9Zu/@N3f/OMffv@Hv/zlX/7y13//D//tv/27v/nv//S3f/jjn/7xr3779//93/63v/rdn/7wj3/5yy9/@/s//ebvf/u3v/@zf/Ob/@OX3/zmj3/6z3/@5/nwL/7@H/73//i7v/vtH//4l7/5/T/9/X/6q3/847@vM3796/0jf/uvf/O3f/dXv/kzv/y7v/39b/7y5xv/pj78zc@3/90//NMf/@Y//qff/u5/@bP7Kd/97T/96Q@/@dPzm/8pv507@vM//5u//eu/@Y//@Fd//MPf/dOf/vYPv6@f/MPv/pc///Pf/@G//plf@y9/@Mff/Jnf/R8z2G/@/Od3/vsfZdj/9R//9P/@wff/1w/@7g@//@OffvP/9bMZ8w//9Kff/MVf/FxDvfrX/@H3//rf//LffezJv@Gj/8dV/Od/@sff5ud/@8c//cX/46Pf//b3f/jjX9UV/Oc//uWf1fX/25q1f/Pvaqzf/@nP/s2/DPevfv/H//D7f/Xvf/k///mfn1/eX/ov55d3/vKNX9r8pZ9fZv9lv7@8T3321bH3@rTOOHVKnfONOu7zS/t6nV/frvN6r@Puv4zv/DLW/GXWebOOq96v@vuuz0@ddybj1hffp0Z43xrqZcz3q8Hfxq90fm7wu5MLmFzJqit6d@ca6gq/h6t4ueLvOb987em/fP1568rqG9/k1eJvm09Pndf4Rqvxuei68lbjtV4jN36jrfq1tut326kr6E9dS@eqeqvr672utM@65r64W25jPHU/4@WGG3dcn/wyuOexeHXqb/OpT@tbb81mfWO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gxdJemfI9WOyazhAp0hgG8VEzCHLCrU5USlTgoDVes1EQzIWYJEdaEqjaXpxpacxBFlFgjbK3iDtBZzpdY2nh7nwsMywo7CyC9dQN2NEV2owtdJ6IyxRiRQIE95TEJduXJsDA@Uh3cRNDawTgKY3SMFWRPTTEsS2thRE4aRjHAx5yuk9ILIA3jZcIZA9Y3Qi5RFljhKLI1MP1R3zySSsozrYkg2zODnfP@m6uA5DVIu1G1vQRukzUEROMrWxAnCtwjIeMcwNrBWCZNS3cdd9EAu712BYGd@@EMB4SGcMIrWPDMKQvkXWsgW3WgGU3rSGn0McussC0OhhH@iK@AsW2LIn1e8ynoXTCF3AhHGwYGzxxReySplZZfGnZBPSELhDMHy5@w2TrnxUGBJ6RhRjCJV8waFmzj0U5tCDHisBj2DLuqNtk0FrSr9AQ6jPB91okRj3IZygBzAfo4mF9FuVda1ov0VOdTYyNHKSVHtiWgHcBc@LMQpkHKhKhF0f0c5phncPo2CJShr03KAmj9hhKgmmSBn1AyIyqzgZiH7GNpIHmbEmKL90ZkaTP8kPghxL@9anb3puB5WHATTGMT4XFmSwdDfZwGjBX4XiHOgD@0KSBkK6UYUPkQQHNwugjqDNAYGY7EK@yVSa59mA7iZwN7WuAZLWBYDejSZOtuHHr8W8JE2L70UgATJzsiw9kd2JZm/F2OmX2KTsdICGY3a2OMg1Nw1oLbIjAdQ0EYvmYhU0@JFkucWBgS6EB8ivdEYRVBFWk2cBPY7nwyEi6bKv8pvQGqBSN26VI3/Ft5S6xONn2UJjwmGrC@Qiv4S9Ce0Kk3IZY7JYH5Yrqt4iGWvDuNmMO6fBFnyKb0Hasc0qicaG27BUSV4GVxvOwMYqEQUOEKIbpMMshppF293DT2KyATuNEESj@eSz5oDZnsXGwn5BWnPqEvkp9WooAkAcpD6xn29pR6rObC7T/X7/7L3/327/@4z//2//5@@d/@3d//ff/8N/@W47/Nw "C++ (gcc) – Try It Online")
[Answer]
# JavaScript (Node), Unknown time due to TIO not liking 2.6 million characters as the input.
If you want to see the previous tests, then [Try it online!](https://tio.run/##Tb3J0jZLcpy3x1UccdUwSFBl5WxNLnUVNC4gsEG2DDwN9SAtZLx2KJ4I9/oOzBon//rqrSErhxjcPf6vf/p//ukv//znP/7bX/@3X//0X//w7//8p1//8tdf/vjrv/3tr3/55T/98p9/eX79X39p8b8R/7u0V/y/d8b/67QGxxZ/PJzVnjz/zfYYeX7@6ubP8nfvzPbheH9HXinvkL8dI9uH4/PlnLk5f@VvV7Z3Ht95zsnzb/72rnqGvGh78g6t5e1a3bu9@SCt11ONesRZz7vq4Ve9yc63amfU8@fbvk@9QateeB/@9vaHM9/xtHy7vMq76l@7/nbqzJu/63WV3vKa0QXZEz3v10fevdez9J1P1k8@Z7/51OPJdxj1RqPn@42RbztWvvvY1aPVLfPJPpqtOrVXr47syln9Onf96@bf1pNnxrVaft28ypp5zbXzDuvk/fYz64PkVXbPJ9szn3PvfOp98x1ODY3z5vudUWNm5bufkz1xq1/i/PzXyD67K3vwnkfjqz7S8@rf46mPvfLs@Oj549bqWq29vf496ju2VZ@1nfrKr0dsrzHwzhoS764R8l4NGI2fPqYGUI2ufmuwjbY05ut68X7173NqiLXs2TZ7dnRTv7d56t9Lf1@9zl/6/apP2Lauv0fdb@v@@9bzHD1fDNf6t57/PvU@V@93NchvvX/0YvbH@1T/vM@ugd480nsN9Vb9@3LBHPrV/6@H@1vf5@2t/t6H5sau3w9db/S6/qgvH2O/7j9rXMTaUNebNWreGIP591Vj6o3Xzt9rxL171mqyazy@0Q814Wq0xipT17s1lt87s3/js2Z/x1TcNSXre/Tn1r9bzZJ4@zy/vzWHYrLWxHxrhvXeagXrNf96P/k8XbMzhsutf9fc7bPXVJ6a2avGX0x@zftTy8DWqrBXLRJHa0Ysd/XvWlFi@D1aGh6tobWKPkP/Pvn30WqtYpjW4lHXi9FUy/hb69zob94/jubzxGqsVbnWyBgl@fxj1go65q7FaGk1WquWo12r79hTC1KtzbGu1/VOrdvjvtm/49aaPp9WC5G@x2xP/btpL4iB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Hd@fh//@Y/VBf/4r3/49b/99b/HkX/4h3rQ375X3eQ///G/xDX@57//@/8P). Currently, we can't use TIO with all of the inputs.
```
function iroot(base) {
let s = base + 1n;
let u = base;
if (!base) { console.log(0n); return; }
while (u < s) {
s = u;
u = (u + base / u) / 2n;
}
return s;
}
const inputs = [/* the gist goes here*/]
console.time("sqrt");
inputs.map(iroot);
console.timeEnd("sqrt");
for (let i = 0; i < iroot.length; i++) {
console.log(inputs[i]);
}
```
This is based off of a [StackOverflow answer I did](https://stackoverflow.com/questions/64190185/how-do-i-extract-the-nth-root-of-a-bigint-in-javascript/64190462#64190462), which was based off of [Newton's formula](https://stackoverflow.com/a/30869049/12101554). This function is better than the built in `Math.sqrt()` or `Math.pow()` or `**` since this gives precision even to the last digits instead of 1.457746e57 or something like that. Also with BigInt, all numbers are `integers`, so you can't use `**` a decimal/fraction.
This code expects a long array to be prefilled with the numbers as bigints: <https://gist.github.com/Samathingamajig/23b8107f299649d6bd3399b04f65c257> , which can be compressed into one line through this gist: <https://gist.github.com/Samathingamajig/88f64e58ba21bd8d392be23bbb85dd9d>
A Gist with all the data as raw JSON can be found here: <https://gist.github.com/Samathingamajig/c15fd1f15a7bca6181a2e792c469503d>
[Answer]
# Rust 450 μs
```
use std::time::SystemTime;
use num_bigint::BigUint;
fn main() {
// Parse the numbers
let mut numbers: Vec<_> = INPUT.iter().map(|i| {
i.parse::<BigUint>().unwrap()
}).collect();
let start = SystemTime::now();
// Do the calculation
numbers.iter_mut().for_each(|s| *s = s.sqrt());
// Print the time.
println!("{}us", start.elapsed().unwrap().as_micros());
}
```
I agree that the input is too small. If performance was an issue, we would
not use a library, but create a custom integer algorithm for monotonic
series of integers, do them on SIMD hardware and multithreaded on 64 cores.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), < 60 ms on TIO
```
function iroot(input) {
let bit = 1n << BigInt(input.toString(2).length - 1 >> 1);
let root = 0n;
while (bit) {
let diff = (root + root + bit) * bit;
if (input >= diff) {
input -= diff;
root += bit;
}
bit /= 2n;
}
return root;
}
console.time("sqrt");
let roots = inputs.map(iroot);
console.timeEnd("sqrt");
for (let root of roots) {
console.log(root);
}
```
[Try it online!](https://tio.run/##Tb1LrzZJcqS3568oaNUjaaiMjDs4nIUALbTWUtBixGlyWuBUU91FaSHMb6f8cTfLUwSaFV@efPMSGRe/mJn/X//p//lPf/2Hv/zpX37797/@@T//8d/@4c@//vW3X/7067/8629//eXvf/nff3l@/R9/afG/Ef@7tFf8v3fG/@u0BscWfzyc1Z48/832GHl@/urmz/J378z24Xh/R14p75C/HSPbh@Pz5Zy5OX/lb1e2dx7fec7J82/@9q56hrxoe/IOreXtWt27vfkgrddTjXrEWc@76uFXvcnOt2pn1PPn275PvUGrXngf/vb2hzPf8bR8u7zKu@pfu/526sybv@t1ld7ymtEF2RM979dH3r3Xs/SdT9ZPPme/@dTjyXcY9Uaj5/uNkW87Vr772NWj1S3zyT6arTq1V6@O7MpZ/Tp3/evm39aTZ8a1Wn7dvMqaec218w7r5P32M@uD5FV2zyfbM59z73zqffMdTg2N8@b7nVFjZuW7n5M9catf4vz818g@uyt78J5H46s@0vPq3@Opj73y7Pjo@ePW6lqtvb3@Peo7tlWftZ36yq9HbK8x8M4aEu@uEfJeDRiNnz6mBlCNrn5rsI22NObrevF@9e9zaoi17Nk2e3Z0U7@3eerfS39fvc5f@v2qT9i2rr9H3W/r/vvW8xw9XwzX@ree/z71PlfvdzXIb71/9GL2x/tU/7zProHePNJ7DfVW/ftywRz61f@vh/tb3@ftrf7eh@bGrt8PXW/0uv6oLx9jv@4/a1zE2lDXmzVq3hiD@fdVY@qN187fa8S9e9Zqsms8vtEPNeFqtMYqU9e7NZbfO7N/47Nmf8dU3DUl63v059a/W82SePs8v781h2Ky1sR8a4b13moF6zX/ej/5PF2zM4bLrX/X3O2z11Semtmrxl9Mfs37U8vA1qqwVy0SR2tGLHf171pRYvg9WhoeraG1ij5D/z7599FqrWKY1uJR14vRVMv4W@vc6G/eP47m88RqrFW51sg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96NHlXAg1IJuz8XKyaK/PBPzpec@s/kZzNyBRjWGFEhagg8dA2@8yWkiCM/KiDEdaw0GMWP3SbrhRE2amiI7XxTiZKv87cOy8CDP8xASzGUIhBt8tTeDHOCNYA7M5KxCfd0r2VrD6h3EDMkhJ/8MaxQAPmBqXGkEesEeswSWA/xmV6NjizFyEhc1s94fVFm0JhDDWZn4Yn8g8AfTvsP3YRln1UH8dGcJqhRBJfr1JsEbCG8KDY@VwYPRM6A@M2yYizLeGpapM6YUmMf5wLil@hHSNGioV2KN1RYhDuSpIPptTEJCTxN0c00LYmzsqIm2KPw0Ub@ZNjmAyZhIqJtSRhdMGuH@zKgS8MQqpKAXiNDUhH6Qyk0Uec@MwyUAslLPFuga1YyS8SlwwWB1peuJHo40G8hoYDL21CBMhW6cILTBLgZUSgsiK0mYJ0Wh8PwYNHw2klInudArJXPYZNL43bnEn/KfU48rxSWyXC/mPkZcglkJB@KFIudFbiDLGTNrHjZczAGR@FD9GDnh6EfqOFPV9c267djwCFvghJ1UUEopSVgNeCtZcjGl9mYirDFaZ@Z7EuV7ZuLhb5YAC1sYZwZJbkKPfMonuY8pw4Ep3jn1KRHJ3GNjYwAAROIH2zpLqEM1PD2H6fj1l//j3/7xX3/9h9/@9Odff/nTX/7859/@8Kdf/@Vff/t3v/x/f/PLL//8x99@@T//9Nsvf/9L@/WX//Affvmf//RP/@uvOuNvf/vz//bbX/706z/94f13f/vPf/z1n377L7/8@1/aL//xP/7S/t3f6cdcMH79/MqB//e//Omf//jLH@KCdfU65T//6R//MU75Q576P/yi/@RJ/z3/@bs880//@Evd9pf/@Pf5E18i/pSH/30d/jsdrMv8/c8F/lv@f17mf/r7X958Hg795Y@//etffs3T/@5v/tvf/M0//PnXv/75n//4t7/96b/@8Q//3V//77/89t/Fy/hV/hoPmrf769/@1//0L3/I/oo///5H/8uv//nnd3/zj3/@yy9/@Driz/9YV6ln96/@@c//9Add6L/927/9/w "JavaScript (Node.js) – Try It Online") Can't remember the name of this method sorry, but it's very handy for square rooting floating-point numbers by shifting as the bit is always `1` thus reducing the complexity even further.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~16-28 ms on TIO
```
def newtonRoot base
s = base + 1
u = base
if base == 0
return 0
end
while u < s do
s = u
u = (u + base / u) / 2
end
return s
end
t = Time.now
outputs = inputs.map{ |i| newtonRoot i }
puts "> time elasped: #{ (Time.now - t) * 1000 } ms.\n\n"
puts outputs.map{ |v| v * v } == inputs
# un-comment below line to see outputs!
# outputs.map{ |i| print "#{i}, " }
```
The former code is a modification of latter code, which is specific to the square root of a "perfect square", and a bit faster!
[Try it online!](https://tio.run/##Vb3b0jXNcZx3jqv4TJ1INiVPT@8dpi/C4TPLB5IJhRFBAgwSkMIh8drpejJz3t9CAPh6rXdWz0xvqmuTlfWPf/mP/@@//OGP//CXP//Tr7/59X/@ev76V/vrX@Ovf91qrL/@9c6//tXr31GfV3196q/t4aqX1hhcxrWXi7n6nbROfdffwY/pj1@MQevUd/Otv85d1y1@sWhtvtv89XDd5Rd36W500x56bI3Om@7TXm7Zuu4@9CBTz7T0eEtPunnmdoaekPd4Hz1j07u9T33/9qeuecfTeHZ@@y61t74/uuZyfddve6OfejfesNN/H9yr67598wz98Dz98mzj4TmHnnl0nn8M3mUs3mtsjY9edz68@Wwaoq4xGgzN1CjNrfbl@/VwTXXQmBV@uyb9rE2f69D/fqaGld/uzjPsyfPszbPty3MeTeV5ef4zNL@L9zqHd7x637qQ9mAc7mJM7nm8CjTQz@tP49E0La6r2eJHramH1t6uT0Pz0JYmpR3N0JvV1DV379REvluz@l5Psee7j@kJ10roV8titOV1qF7qFfTpHC2Hxli12Rm45lFs8@jT8t9W15XLv1uahrbd5x66w/b99tXdj5@lVpQ@@Tnvo6e@fofrBXj1fjU4vO376N3fZ2sRtqzCrmXYNGYv3bAoNZ5vluKrsX5709/68Ird@t1wL6Orz6GZq2Wp@03Nae1F9TI1228tGP62tA7eei9@5xXy7ql9u7V23npNLX6tqtrM6uVqvb13MmY1N4x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Wv/BIgZsCST2UKkmy4l9JtRtgK8OURY1XSEEon8GzAuNjCMG0CZEX22Yh9NdDQU6KAHIF6pqo2kZ5Izj18HkvhJM4FvHLkJ3cSOhDfyBsYD7dqmYj5EB/Vq3xZAKIiCx1Llv/ocmpP@fQkjTHA0EITa6TALYYFWiwFN6DagMHY8SqkLDwEcOaQlLXRAfETTfCy3hJ4wlQOG7CB0bj45aY0b8B7tYlgN6TqIDgqHO4KSOKLRBGkGAyQRBG5PnBhCojc5fCnBvZYoq0Eb0VNDeXhOeJOtXtla@HfG9IVCCegJHYxmYlDFxMHkqKLziSSMjjo8M6IvQaDjhXDpBEEOko8XSIC4WyRsrsl2o@tYbEEKfleZQ5R7NHbhKbEbYdpCcUQLnrVe2THPByzKAFOwoIAYWivMYoUtaR8nqrUDxR2sv6xsY74X8RABwAem0RVtMTmNYXgRU2dCrUIXHqmcNVXdWVK@cVmgUMXHyET@ShhTfwE6N6dSx8z0OlkrQMByAtRF5RpFYMlVex0rdHx6//6l7/9/X/69cff/5c//@mP//uf/vTnX//xP/zT73/3q/7zT7/@Rh9@/U@/mr74S77Qhz/8J//xb/7m16Mv@M8//v7Pf/nHP@aL3//xb/Xvf/l//vB3v68f/6/V49/@6edauv/Lzyf6/td/qVup0//511/@Tf3f@9/1k87/6Xd88bs/1w/@jz/8/e//3R//9F9@96e//Pkf/vJnevzDH2n8u7//D//wX3/9tz/8t///i/3h1z//Tlf91f/268/1y1@//7v/8E//8Pu//V9@/av/@utff339@re//vxvfv2PpP8@v/7519//07/793/893/8q9/5p7lR@v/P/@3Xf65L/3Nd9zffrX/3u3/16y9//Lf/95/@/u9//8cazd//XfX5d3/44@9//flPv/7p97//uvgf6rr/vrd62n/4xz/Ub/7qX/3XP/zzX//6q1///C//8v8B "Ruby – Try It Online")
---
# [Ruby](https://www.ruby-lang.org/), ~22-36 ms on TIO
```
def newtonRoot (base, root)
s = base + 1
k1 = root - 1
u = base
if (base == 0)
print "0, "
return
end
while (u < s) do
s = u
u = ((u * k1) + base / (u ** k1)) / root
end
print "#{s}, "
end
t = Time.now
inputs.each{|i| newtonRoot(i, 2)}
puts "\n\n> time elasped: #{ (Time.now - t) * 1000 } ms."
```
A remix of [Newton's formula](https://stackoverflow.com/a/30869049/12101554) in Ruby. I posted this as I think Ruby is very fast.
[Answer]
# [Python 3](https://docs.python.org/3/), unknown time
Finishes the first 7979 cases on my machine after 19.2 minutes. (Using `head -n 7979 input.txt | python3 sqrt.py`)
```
from time import time
numbers = []
try:
while True:
numbers += [int(input())]
except:
pass
t1 = time()
for i in range(len(numbers)):
base = numbers[i]
u, s = base, base + 1
if u:
while u < s:
u, s = (u + base // u) // 2, u
numbers[i] = u
t2 = time()
print(t2 - t1, "seconds")
```
Uses the same method as [Samathingamajig's answer](https://codegolf.stackexchange.com/a/215079/70894).
[Answer]
# Rust Babylonian + New data 33 ms
This uses the new, larger data set and a novel recursive version of
the Babylonian algorithm.
The algorithm refines the guess for the babylonian by calculating the square root of the top half of the number, which is much less expensive.
```
use num_bigint::BigUint;
use std::time::SystemTime;
use num_traits::{FromPrimitive, ToPrimitive};
use rayon::prelude::*;
fn recursive_babylonian_sqrt(a: &BigUint) -> BigUint {
if a.bits() < 53 {
//println!("a={} exact={}", a, BigUint::from_f64(a.to_f64().unwrap().sqrt()).unwrap());
return BigUint::from_f64(a.to_f64().unwrap().sqrt()).unwrap();
}
let mut guess = recursive_babylonian_sqrt(&(a >> a.bits()/4*2)) << (a.bits()/4);
//println!("a={} sqrt={} guess={}", a, a.sqrt(), guess);
//let mut nits = 0;
loop {
let mut new = a / &guess;
new += &guess;
new >>= 1;
//nits += 1;
if new == guess {
break;
}
guess = new;
}
//println!("{} nits", nits);
guess
}
pub fn main() {
let text = std::fs::read("numbers-updated.txt")
.unwrap();
let numbers : Vec<_> = text[0..text.len()-1]
.split(|c| *c == b'\n')
.map(|s| std::str::from_utf8(s).unwrap().parse::<BigUint>().unwrap() )
.collect();
let start = SystemTime::now();
let result : Vec<_> = numbers
.par_iter()
.map(|s| recursive_babylonian_sqrt(s))
.collect();
// Print the time.
println!("{}us", start.elapsed().unwrap().as_micros());
numbers
.iter()
.zip(result.iter())
.for_each(|(n, r)| assert_eq!(&n.sqrt(), r));
}
```
```
] |
[Question]
[
# Contest permanently opened - Updated August 10th 2017
Even though on June 5th 2017 I declared a winner (who will be kept as the best answer) I'll be rnning new bots and updating the results.
# June 5th Results
Congratulations [user1502040](https://codegolf.stackexchange.com/users/18957/user1502040)
Since there are no ties, I only show the % of matches won.
[`Statistician2`](https://codegolf.stackexchange.com/a/122607/40604) - 95.7%
[`Fitter`](https://codegolf.stackexchange.com/a/122423/40604) - 89.1%
[`Nash`](https://codegolf.stackexchange.com/a/122607/40604) - 83.9%
[`Weigher`](https://codegolf.stackexchange.com/a/122563/40604) - 79.9%
[`ExpectedBayes`](https://codegolf.stackexchange.com/a/138049/40604) - 76.4%
[`AntiRepeater`](https://codegolf.stackexchange.com/a/122526/40604) - 72.1%
[`Yggdrasil`](https://codegolf.stackexchange.com/a/122534/40604) - 65.0%
[`AntiGreedy`](https://codegolf.stackexchange.com/a/122377/40604) - 64.1%
[`Reactor`](https://codegolf.stackexchange.com/a/122440/40604) - 59.9%
[`NotHungry`](https://codegolf.stackexchange.com/a/122423/40604) - 57.3%
[`NashBot`](https://codegolf.stackexchange.com/a/124653/40604) - 55.1%
[`Blodsocer`](https://codegolf.stackexchange.com/a/122672/40604) - 48.6%
[`BestOfBothWorlds`](https://codegolf.stackexchange.com/a/122680/40604) - 48.4%
[`GoodWinning`](https://codegolf.stackexchange.com/a/122426/40604) - 43.9%
[`Rockstar`](https://codegolf.stackexchange.com/a/122380/40604) - 40.5%
[`ArtsyChild`](https://codegolf.stackexchange.com/a/122489/40604) - 40.4%
[`Assassin`](https://codegolf.stackexchange.com/a/122380/40604) - 38.1%
[`WeightedRandom`](https://codegolf.stackexchange.com/a/123055/40604) - 37.7%
[`Ensemble`](https://codegolf.stackexchange.com/a/122676/40604) - 37.4%
[`UseOpponents`](https://codegolf.stackexchange.com/a/122426/40604) - 36.4%
[`GreedyPsychologist`](https://codegolf.stackexchange.com/a/132230/40604) - 36.3%
[`TheMessenger`](https://codegolf.stackexchange.com/a/122380/40604) - 33.9%
[`Copycat`](https://codegolf.stackexchange.com/a/122428/40604) - 31.4%
[`Greedy`](https://codegolf.stackexchange.com/a/122377/40604) - 28.3%
[`SomewhatHungry`](https://codegolf.stackexchange.com/a/122526/40604) - 27.6%
[`AntiAntiGreedy`](https://codegolf.stackexchange.com/a/122526/40604) - 21.0%
[`Cycler`](https://codegolf.stackexchange.com/a/122657/40604) - 20.3%
[`Swap`](https://codegolf.stackexchange.com/a/122676/40604) - 19.8%
[`RandomBot`](https://codegolf.stackexchange.com/a/122377/40604) - 16.2%
I created a Google Sheet with the grid of results of each pairing: <https://docs.google.com/spreadsheets/d/1KrMvcvWMkK-h1Ee50w0gWLh_L6rCFOgLhTN_QlEXHyk/edit?usp=sharing>
---
Thanks to the [Petri Dilemma](https://codegolf.stackexchange.com/questions/122118/prisoners-dilemma-v-3-petri-dilemma) I found myself able to handle this King of the Hill.
# The game
The game is a simple "Rock-Paper-Scissors" with a twist: Points gained with each victory increase during the match (your R, P or S get loaded).
* Paper wins Rock
* Scissors wins Paper
* Rock wins Scissors
The winner gets as many points as his load on his play.
The loser increases by 1 the load on his play.
In the case of a tie, each player increases the load on his play by 0.5.
After 100 plays, the one with more points is the winner.
e.g.: P1 has loads [10,11,12] (Rock, Paper, Scissors) and P2 [7,8,9]. P1 plays R, P2 plays P. P2 wins and gets 8 points. P1 loads become [11,11,12], P2 loads stay the same.
# Challenge specifications
Your program must be written in Python (sorry, I don't know how to handle it otherwise). You are to create a function that take each of these variables as an argument on each execution:
```
my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history
```
`points` - Current points (yours and your opp)
`loaded`- Array with loads (in order RPS) (yours and your opp)
`history`- String with all plays, last character is the last play (yours and your opp)
You must return `"R"`, `"P"` or `"S"`. If you would return something different, it would be an automatic lose of the match.
# Rules
You cannot change built-in functions.
# Testing
I'll keep a Git updated with the code and all the bots compiting: <https://github.com/Masclins/LoadedRPS>
# Judging
The winner will be decided by selecting the person with the most win matches after 1000 full round-robin. Ties will be broken by matches tied.
1000 matches are being played rather than one because I expect a lot of randomness, and that way the randomness would be less relevant.
You can submit up to 5 bots.
The contest ends on ~~July~~June 4th (that will be the last day I'll accept any answer), and on ~~July~~June 5th I'll post the final stadings (might try to post an advancemnt before).
---
Since this is my first KOTH, I'm 100% opened to changing anything for improvement, such as the number of matches played against each bot.
Edited to 1000 matches, since I see there really is quite randomness involved.
[Answer]
## ~~Statistician~~ (no longer playing)
```
import random
import collections
R, P, S = moves = range(3)
move_idx = {"R": R, "P": P, "S": S}
name = "RPS"
beat = (P, S, R)
beaten = (S, R, P)
def react(_0, _1, _2, _3, _4, opp_history):
if not opp_history:
return random.randrange(0, 3)
return beat[opp_history[-1]]
def anti_react(_0, _1, _2, _3, _4, opp_history):
if not opp_history:
return random.randrange(0, 3)
return beaten[opp_history[-1]]
def random_max(scores):
scores = [s + random.normalvariate(0, 1) for s in scores]
return scores.index(max(scores))
def greedy_margin(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
scores = [my_loaded[move] - opp_loaded[beat[move]] for move in moves]
return random_max(scores)
def anti_greedy(my_points, opp_pints, my_loaded, opp_loaded, my_history, opp_history):
scores = [-my_loaded[move] for move in moves]
return random_max(scores)
def recent_stats(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
opp_history = opp_history[-10:-1]
counts = collections.Counter(opp_history)
scores = [(counts[beaten[move]] + 1) * my_loaded[move] -
(counts[beat[move]] + 1) * opp_loaded[move] for move in moves]
return random_max(scores)
def statistician(_0, _1, _2, _3, my_history, opp_history):
m1 = []
o1 = []
my_loaded = [0] * 3
opp_loaded = [0] * 3
my_points = 0
opp_points = 0
strategies = [react, anti_react, greedy_margin, anti_greedy, recent_stats]
strategy_scores = [0 for _ in strategies]
for i, (mx, ox) in enumerate(zip(my_history, opp_history)):
mx = move_idx[mx]
ox = move_idx[ox]
for j, strategy in enumerate(strategies):
strategy_scores[j] *= 0.98
move = strategy(my_points, opp_points, my_loaded, opp_loaded, m1, o1)
if move == beat[ox]:
strategy_scores[j] += my_loaded[move]
elif move == beaten[ox]:
strategy_scores[j] -= opp_loaded[ox]
m1.append(mx)
o1.append(ox)
if mx == beat[ox]:
opp_loaded[ox] += 1
my_points += my_loaded[mx]
elif mx == beaten[ox]:
my_loaded[mx] += 1
opp_points += opp_loaded[ox]
else:
my_loaded[mx] += 0.5
opp_loaded[ox] += 0.5
strategy = strategies[random_max(strategy_scores)]
return name[strategy(my_points, opp_points, my_loaded, opp_loaded, m1, o1)]
```
Switches between a few simple strategies based on expected past performance
## Statistician 2
```
import random
import collections
import numpy as np
R, P, S = moves = range(3)
move_idx = {"R": R, "P": P, "S": S}
names = "RPS"
beat = (P, S, R)
beaten = (S, R, P)
def react(my_loaded, opp_loaded, my_history, opp_history):
if not opp_history:
return random.randrange(0, 3)
counts = [0, 0, 0]
counts[beat[opp_history[-1]]] += 1
return counts
def random_max(scores):
scores = [s + random.normalvariate(0, 1) for s in scores]
return scores.index(max(scores))
def argmax(scores):
m = max(scores)
return [s == m for s in scores]
def greedy_margin(my_loaded, opp_loaded, my_history, opp_history):
scores = [my_loaded[move] - opp_loaded[beat[move]] for move in moves]
return argmax(scores)
recent_counts = None
def best_move(counts, my_loaded, opp_loaded):
scores = [(counts[beaten[move]] + 0.5) * my_loaded[move] -
(counts[beat[move]] + 0.5) * opp_loaded[move] for move in moves]
return argmax(scores)
def recent_stats(my_loaded, opp_loaded, my_history, opp_history):
if len(opp_history) >= 10:
recent_counts[opp_history[-10]] -= 1
recent_counts[opp_history[-1]] += 1
return best_move(recent_counts, my_loaded, opp_loaded)
order2_counts = None
def order2(my_loaded, opp_loaded, my_history, opp_history):
if len(my_history) >= 2:
base0 = 9 * my_history[-2] + 3 * opp_history[-2]
order2_counts[base0 + opp_history[-1]] += 1
base1 = 9 * my_history[-1] + 3 * opp_history[-1]
counts = [order2_counts[base1 + move] for move in moves]
return best_move(counts, my_loaded, opp_loaded)
def nash(my_loaded, opp_loaded, my_history, opp_history):
third = 1.0 / 3
p = np.full(3, third)
q = np.full(3, third)
u = np.array(my_loaded)
v = np.array(opp_loaded)
m0 = np.zeros(3)
m1 = np.zeros(3)
lr = 0.2
for _ in range(10):
de0 = u * np.roll(q, 1) - np.roll(v * q, 2)
de1 = v * np.roll(p, 1) - np.roll(u * p, 2)
m0 = 0.9 * m0 + 0.1 * de0
m1 = 0.9 * m1 + 0.1 * de1
p += lr * m0
q += lr * m1
p[p < 0] = 0
q[q < 0] = 0
tp, tq = np.sum(p), np.sum(q)
if tp == 0 or tq == 0:
return np.full(3, third)
p /= tp
q /= tq
lr *= 0.9
return p
strategies = [react, greedy_margin, recent_stats, order2, nash]
predictions = strategy_scores = mh = oh = None
def statistician2func(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
global strategy_scores, history, recent_counts, mh, oh, predictions, order2_counts
if not opp_history:
strategy_scores = [0 for _ in strategies]
recent_counts = collections.Counter()
order2_counts = collections.Counter()
mh, oh = [], []
predictions = None
return random.choice(names)
my_move = move_idx[my_history[-1]]
opp_move = move_idx[opp_history[-1]]
if predictions is not None:
for j, p in enumerate(predictions):
good = beat[opp_move]
bad = beaten[opp_move]
strategy_scores[j] += (my_loaded[good] * p[good] - opp_loaded[opp_move] * p[bad]) / sum(p)
mh.append(my_move)
oh.append(opp_move)
predictions = [strategy(my_loaded, opp_loaded, mh, oh) for strategy in strategies]
strategy = random_max(strategy_scores)
p = predictions[strategy]
r = random.random()
for i, pi in enumerate(p):
r -= pi
if r <= 0:
break
return names[i]
```
## Nash
```
import numpy as np
import random
def nashfunc(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
third = 1.0 / 3
p = np.full(3, third)
q = np.full(3, third)
u = np.array(my_loaded)
v = np.array(opp_loaded)
m0 = np.zeros(3)
m1 = np.zeros(3)
lr = 0.2
for _ in range(10):
de0 = u * np.roll(q, 1) - np.roll(v * q, 2)
de1 = v * np.roll(p, 1) - np.roll(u * p, 2)
m0 = 0.9 * m0 + 0.1 * de0
m1 = 0.9 * m1 + 0.1 * de1
p += lr * m0
q += lr * m1
p[p < 0] = 0
q[q < 0] = 0
tp, tq = np.sum(p), np.sum(q)
if tp == 0 or tq == 0:
return random.choice("RPS")
p /= tp
q /= tq
lr *= 0.9
r = random.random()
for i, pi in enumerate(p):
r -= pi
if r <= 0:
break
return "RPS"[i]
```
Computes an approximate Nash equilibrium by gradient descent.
[Answer]
# Weigher
I lost track of reasoning while experimenting with the code, but the basic idea is to estimate opponent's move probability by last 3 moves using some weights and multiply them by another weight which depends on loads. I thought that I can somehow use `my_loaded` too, but I couldn't decide how, so left it out.
```
def weigher(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
idx = {"R": 0, "P": 1, "S": 2}
sc = [0, 0, 0]
for i, m in enumerate(reversed(opp_history[-3:])):
sc[idx[m]] += (1 / (1 + i))
for i in range(3):
sc[i] *= (opp_loaded[i] ** 2)
return "PSR"[sc.index(max(sc))]
```
# Satan
Probably will be disqualified, because it's kind of cheating and it makes some assumptions about the testing function (it has to have opponent's function in a variable on its stack frame), but it doesn't technically break any current rules — it doesn't redefine or rewrite anything. It simply uses black magic to execute the opponent function to see what turn did/will they do. It cannot deal with randomness, but deterministic bots have no chance to defeat Satan.
```
def satan(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
import inspect, types
f = inspect.currentframe()
s = f.f_code.co_name
try:
for v in f.f_back.f_locals.values():
if isinstance(v, types.FunctionType) and v.__name__ != s:
try:
return "PSR"[{"R": 0, "P": 1, "S": 2}[
v(opp_points, my_points, opp_loaded, my_loaded, opp_history, my_history)]]
except:
continue
finally:
del f
```
[Answer]
# Fitter
This Bot improves Pattern and fuses it with Economist (Pattern and Economist will no longer participate)
The improvement of Pattern is that the Bot now looks for two two kinds of patterns: Opponent reacting to his last play and opponent reacting to my last play. Then evaluates both predictions to use the one that fits the best.
From that pattern the Bot has now the probability for R, P and S. Taking that into account and the expected value of each play (as Economist did), the Bot plays the one that gives the most value.
```
import random
import numpy as np
def fitterfunc(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
t = len(opp_history)
RPS = ["R","P","S"]
if t <= 2:
return RPS[t]
elif t == 3:
return random.choice(RPS)
def n(c): return RPS.index(c)
total_me = np.zeros(shape=(3,3))
total_opp= np.zeros(shape=(3,3))
p_me = np.array([[1/3]*3]*3)
p_opp = np.array([[1/3]*3]*3)
for i in range(1, t):
total_me[n(my_history[i-1]), n(opp_history[i])] += 1
total_opp[n(opp_history[i-1]), n(opp_history[i])] += 1
for i in range(3):
if np.sum(total_me[i,:]) != 0:
p_me[i,:] = total_me[i,:] / np.sum(total_me[i,:])
if np.sum(total_opp[i,:]) != 0:
p_opp[i,:] = total_opp[i,:] / np.sum(total_opp[i,:])
error_me = 0
error_opp = 0
for i in range(1, t):
diff = 1 - p_me[n(my_history[i-1]), n(opp_history[i])]
error_me += diff * diff
diff = 1 - p_opp[n(opp_history[i-1]), n(opp_history[i])]
error_opp += diff * diff
if error_me < error_opp:
p = p_me[n(my_history[-1]),:]
else:
p = p_opp[n(opp_history[-1]),:]
# From here, right now I weight values, though not 100% is the best idea, I leave the alternative in case I'd feel like changing it
value = [(p[2]*my_loaded[0] - p[1]*opp_loaded[1], "R"), (p[0]*my_loaded[1] - p[2]*opp_loaded[2], "P"), (p[1]*my_loaded[2] - p[0]*opp_loaded[0], "S")]
value.sort()
if value[-1][0] > value[-2][0]:
return value[-1][1]
elif value[-1][0] > value[-3][0]:
return random.choice([value[-1][1], value[-2][1]])
else:
return random.choice(RPS)
# idx = p.tolist().index(max(p))
# return ["P", "S", "R"][idx]
```
---
Here are the two old codes
# ~~Pattern~~ (no longer playing)
The Pattern tries to find patterns on his opponent. It looks what the opponent had played after the last play he did (giving more weight to the latter plays).
Through that, it guesses what the opponent will play, and plays the countermatch to that.
```
import random
import numpy as np
def patternfunc(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
if len(opp_history) == 0:
return random.choice(["R","P","S"])
elif len(opp_history) == 1:
if opp_history == "R":
return "P"
elif opp_history == "P":
return "S"
elif opp_history == "S":
return "R"
p = np.array([1/3]*3)
c = opp_history[-1]
for i in range(1, len(opp_history)):
c0 = opp_history[i-1]
c1 = opp_history[i]
if c0 == c:
p *= .9
if c1 == "R":
p[0] += .1
elif c1 == "P":
p[1] += .1
elif c1 == "S":
p[2] += .1
idx = p.tolist().index(max(p))
return ["P", "S", "R"][idx]
```
# ~~Economist~~ (no longer playing)
The Economist does the following:
Guesses the probability of each play by the opponent by watching what he had played the last 9 turns. From that, computes the expected benefit of each play and goes with the one that has the best expected value.
```
import random
def economistfunc(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
if len(opp_history) == 0:
return random.choice(["R","P","S"])
if len(opp_history) > 9:
opp_history = opp_history[-10:-1]
p = [opp_history.count("R"), opp_history.count("P"), opp_history.count("S")]
value = [(p[2]*my_loaded[0] - p[1]*opp_loaded[1], "R"), (p[0]*my_loaded[1] - p[2]*opp_loaded[2], "P"), (p[1]*my_loaded[2] - p[0]*opp_loaded[0], "S")]
value.sort()
if value[-1][0] > value[-2][0]:
return value[-1][1]
elif value[-1][0] > value[-3][0]:
return random.choice([value[-1][1], value[-2][1]])
else:
return random.choice(["R","P","S"])
```
[Answer]
# Yggdrasil
This is named "Yggdrasil" because it looks ahead in the game tree. This bot does not perform any prediction of the opponent, it simply attempts to maintain a statistical advantage if it is given one (by balancing current and future profits). It calculates an approximately ideal mixed strategy, and returns a move selected randomly with those weights. If this bot were perfect (which it's not, because the state valuation function is pretty bad and it doesn't look very far ahead), then it would be impossible to beat this bot more than 50% of the time. I don't know how well this bot will do in practice.
```
def yggdrasil(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
cache = {}
def get(turn, ml, ol):
key = str(turn) + str(ml) + str(ol)
if not key in cache:
cache[key] = State(turn, ml, ol)
return cache[key]
def wrand(opts):
total = sum(abs(w) for c,w in opts.items())
while True:
r = random.uniform(0, total)
for c, w in opts.items():
r -= abs(w)
if r < 0:
return c
print("error",total,r)
class State():
turn = 0
ml = [1,1,1]
ol = [1,1,1]
val = 0
strat = [1/3, 1/3, 1/3]
depth = -1
R = 0
P = 1
S = 2
eps = 0.0001
maxturn = 1000
def __init__(self, turn, ml, ol):
self.turn = turn
self.ml = ml
self.ol = ol
def calcval(self, depth):
if depth <= self.depth:
return self.val
if turn >= 1000:
return 0
a = 0
b = -self.ol[P]
c = self.ml[R]
d = self.ml[P]
e = 0
f = -self.ol[S]
g = -self.ol[R]
h = self.ml[S]
i = 0
if depth > 0:
a += get(self.turn+1,[self.ml[R]+1,self.ml[P],self.ml[S]],[self.ol[R]+1,self.ol[P],self.ol[S]]).calcval(depth-1)
b += get(self.turn+1,[self.ml[R]+2,self.ml[P],self.ml[S]],[self.ol[R],self.ol[P],self.ol[S]]).calcval(depth-1)
c += get(self.turn+1,[self.ml[R],self.ml[P],self.ml[S]],[self.ol[R],self.ol[P],self.ol[S]+2]).calcval(depth-1)
d += get(self.turn+1,[self.ml[R],self.ml[P],self.ml[S]],[self.ol[R]+2,self.ol[P],self.ol[S]]).calcval(depth-1)
e += get(self.turn+1,[self.ml[R],self.ml[P]+1,self.ml[S]],[self.ol[R],self.ol[P]+1,self.ol[S]]).calcval(depth-1)
f += get(self.turn+1,[self.ml[R],self.ml[P]+2,self.ml[S]],[self.ol[R],self.ol[P],self.ol[S]]).calcval(depth-1)
g += get(self.turn+1,[self.ml[R],self.ml[P],self.ml[S]+2],[self.ol[R],self.ol[P],self.ol[S]]).calcval(depth-1)
h += get(self.turn+1,[self.ml[R],self.ml[P],self.ml[S]],[self.ol[R],self.ol[P]+2,self.ol[S]]).calcval(depth-1)
i += get(self.turn+1,[self.ml[R],self.ml[P],self.ml[S]+1],[self.ol[R],self.ol[P],self.ol[S]+1]).calcval(depth-1)
self.val = -9223372036854775808
for pr in range(0,7):
for pp in range(0,7-pr):
ps = 6-pr-pp
thisval = min([pr*a+pp*d+ps*g,pr*b+pp*e+ps*h,pr*c+pp*f+ps*i])
if thisval > self.val:
self.strat = [pr,pp,ps]
self.val = thisval
self.val /= 6
if depth == 0:
self.val *= min(self.val, self.maxturn - self.turn)
return self.val
turn = len(my_history)
teststate = get(turn, [x * 2 for x in my_loaded], [x * 2 for x in opp_loaded])
teststate.calcval(1)
return wrand({"R":teststate.strat[R],"P":teststate.strat[P],"S":teststate.strat[S]})
```
[Answer]
## Anti-Repeater
```
from random import choice
def Antirepeaterfunc(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
s = opp_history.count("S")
r = opp_history.count("R")
p = opp_history.count("P")
if s>p and s>r:
return "R"
elif p>s and p>r:
return "S"
else:
return "P"
```
Picks paper on the first turn, after which it returns whatever beats what the opponent has done the most, picking paper in case of a tie.
## Copycat
```
import random
def copycatfunc(I,dont,care,about,these,enmoves):
if not enmoves:
return random.choice(["R","P","S"])
else:
return enmoves[len(enmoves)-1]
```
Simply copies the opponents last move.
## Anti-Anti-Greedy
```
from random import choice
def antiantigreedy(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
if opp_loaded[0] > opp_loaded[1] and opp_loaded[0] > opp_loaded[2]:
return "S"
if opp_loaded[1] > opp_loaded[0] and opp_loaded[1] > opp_loaded[2]:
return "R"
if opp_loaded[2] > opp_loaded[0] and opp_loaded[2] > opp_loaded[1]:
return "P"
else:
return choice(["R","P","S"])
```
Picks whatever loses to the opponent's most heavily weighted choice.
## Somewhat Hungry
```
from random import choice
def somewhathungryfunc(blah, blah2, load, blah3, blah4, blah5):
if load[0] > load[1] and load[0] < load[2] or load[0] < load[1] and load[0] > load[2]:
return "R"
if load[1] > load[0] and load[1] < load[2] or load[1] < load[0] and load[1] > load[2]:
return "P"
if load[2] > load[1] and load[2] < load[0] or load[2] < load[1] and load[2] > load[0]:
return "S"
else:
return choice(["R","P","S"])
```
[Answer]
# The messenger
```
def themessengerfunc(I, do, not, need, these, arguments):return "P"
```
# Rockstar
```
def rockstarfunc(I, do, not, need, these, arguments):return "R"
```
# Assassin
```
def assassinfunc(I, do, not, need, these, arguments):return "S"
```
# Explanation
Now, you may think that these bots are entirely stupid.
not entirely true, these are actually based on idea, of amassing a huge bonus, and the enemy making a misstep and getting walloped with it.
now, these bots play very similarly to greedy, however, they are simpler, and do not randomly pick until they get a load on one weapon, they stick with their weapon of choice.
Another thing to note: these will each beat greedy around half the time, drawing a third of the time, and losing one sixth of the time. when they do win, they will tend to win by a lot. why is this?
Greedy, until he loses a round, will randomly pick a weapon. this means that when he does not win a round, he will pick a weapon randomly again, which could be a winning one again. if greedy draws or loses, he sticks with that weapon. if greedy wins at least one round, then picks the same weapon as the bot, greedy wins. if greedy picks the losing weapon at some point, our bot wins, because the load on our weapon would have been higher than the score greedy has.
Assuming greedy doesn't always just pick the winning weapon through grand chance, this will mean that the chances are:
1/3 : {
1/2 win (1/6 total).
1/2 lose (1/6 total).
}
1/3 draw
1/3 win
so: 1/3 chance to draw, 1/6 chance of a loss, 1/2 chance to win.
this probably shows that you need to do multiple games of multiple rounds
these are mainly to get the challenge rolling
[Answer]
## Reactor
Makes the play that would have won the previous round.
```
import random
def reactfunc(I, dont, need, all, these, opp_history):
if not opp_history:
return random.choice(["R","P","S"])
else:
prev=opp_history[len(opp_history)-1]
if prev == "R":
return "P"
if prev == "P":
return "S"
else:
return "R"
```
[Answer]
# Artsy Child
This bot acts like a child playing arts and crafts, will start with paper and use either paper or scissors randomly, but will not use scissors after rock or scissors because she needs to use the scissors on paper. Will throw a rock back at anyone who throws a rock at her.
```
import random
def artsychildfunc(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
if len(opp_history) == 0:
return "P"
elif opp_history[-1] == "R":
return "R"
elif my_history[-1] != "P":
return "P"
else:
return random.choice(["P", "S"])
```
[Answer]
Here the three Bots I have build for testing:
---
# RandomBot
```
import random
def randombotfunc(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
return random.choice(["R","P","S"])
```
---
[Answer]
### Not Hungry
```
def nothungryfunc(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
if my_loaded[0] < my_loaded[1]:
if my_loaded[0] < my_loaded[2]:
return "R"
elif my_loaded[0] > my_loaded[2]:
return "S"
else:
return random.choice(["R","S"])
elif my_loaded[0] > my_loaded[1]:
if my_loaded[1] < my_loaded[2]:
return "P"
elif my_loaded[1] > my_loaded[2]:
return "S"
else:
return random.choice(["P","S"])
else:
if my_loaded[0] < my_loaded[2]:
return random.choice(["R","P"])
elif my_loaded[0] > my_loaded[2]:
return "S"
else:
return random.choice(["R","P","S"])
```
This is literally the inverse of Greedy, it chooses the lowest points option available.
[Answer]
# Use Opponent's Favorite
```
from collections import Counter
import random
def useopponents(hi, my, name, is, stephen, opp_history):
if opp_history:
data = Counter(opp_history)
return data.most_common(1)[0][0]
else:
return random.choice(["R","P","S"])
```
For the first turn, chooses a random item. For every other turn, uses the opponent's most common choice. If there is a tie, it defaults to the earliest most common choice.
//I stole code from [here](https://stackoverflow.com/a/20872750/7605753)
---
# Winning is Good
```
import random
def goodwinning(no, yes, maybe, so, my_history, opp_history):
if opp_history:
me = my_history[len(my_history)-1]
you = opp_history[len(opp_history)-1]
if you == me:
return goodwinning(no, yes, maybe, so, my_history[:-1], opp_history[:-1])
else:
if me == "R":
if you == "P":
return "P"
else:
return "R"
elif me == "P":
if you == "S":
return "S"
else:
return "R"
else:
if you == "R":
return "R"
else:
return "P"
else:
return random.choice(["R","P","S"])
```
Returns the choice of the winner of the previous round. If the previous round was a tie, recursively checks the round before that. If it was only ties, or it is the first round, returns a random choice.
[Answer]
# Best of Both Worlds
This bot basically combines Anti-Greedy and Greedy (hence the name).
```
def bobwfunc(a, b, my_loaded, opp_loaded, c, d):
opp_max = max(opp_loaded)
opp_play = "PSR"[opp_loaded.index(opp_max)]
my_max = max(my_loaded)
my_play = "RPS"[my_loaded.index(my_max)]
if opp_play == my_play:
return opp_play
else:
return my_play if opp_max < my_max else opp_play
```
[Answer]
# NashBot
```
import random
def nashbotfunc(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
r = opp_loaded[0] * opp_loaded[2]
p = opp_loaded[0] * opp_loaded[1]
s = opp_loaded[1] * opp_loaded[2]
q = random.uniform(0, r + p + s) - r
return "R" if q < 0 else "P" if q < p else "S"
```
Randomly chooses between the three options in such a way that the opponent statistically has no preference between moves with regards to how much it scores; in other words, both Greedy and Not Hungry should have the same average expected score against it.
[Answer]
# Expectedbayes
## Edit: Updated Ranking
This is the new top ranking after inclusion of Expectedbayes:
* statistician2func 91.89%
* fitterfunc 85.65%
* nashfunc 80.40%
* weigherfunc 76.39%
* expectedbayesfunc 73.33%
* antirepeaterfunc 68.52%
* ...
## Explanations
(NB: post 05/06/2017 submission)
This bot tries to maximize the expected value of its next move by:
* Computing the probability for each of the opponent's next possible move
* Using that figure and the loads to compute the expected value for each of R,P and S
* Selecting the move that has the highest expected value
* Randomly selecting a value if predicting failed
Probabilities are updated every ten moves. The number of past moves used to compute the probabilities has been set to 10 for each bot (so 20 features overall). This is probably overfitting the data, but I did not try to check further.
It relies on the scikit library to compute the opponent's move probabilities (i am saying it in case I misread the rules and it was in fact not allowed).
It easily wins against bots that always make the same choice. Surprisingly, it is quite effective against the random bot with a 93% win rate (I believe this is due to the fact that it limits the number of points his opponent can get while maximizing its own number of possible points for each round).
I made a quick try with 100 turn and only a limited number of bots, and this is what I got from result\_standing:
* randombotfunc,35
* nashbotfunc,333
* greedyfunc,172
* antigreedyfunc,491
* themessengerfunc,298
* rockstarfunc,200
* statistician2func,748
* fitterfunc,656
* expectedbayesfunc,601
Which is not that bad!
```
from sklearn.naive_bayes import MultinomialNB
import random
#Number of past moves used to compute the probability of next move
#I did not really try to make such thing as a cross-validation, so this number is purely random
n_data = 10
#Some useful data structures
choices = ['R','P','S']
choices_dic = {'R':0,'P':1,'S':2}
point_dic = {(0,0):0,(1,1):0,(2,2):0, #Same choices
(0,1):-1,(0,2):1, #me = rock
(1,0):1,(1,2):-1, #me = paper
(2,0):-1,(2,1):1} #me = scissor
def compute_points(my_choice,opp_choice,my_load,opp_load):
"""
Compute points
@param my_choice My move as an integer
@param opp_choice Opponent choice as an integer
@param my_load my_load array
@param opp_load opp_load array
@return A signed integer (+ = points earned, - = points losed)
"""
points = point_dic[(my_choice,opp_choice)] #Get -1, 0 or 1
if points > 0:
return points*my_load[my_choice]
else:
return points*opp_load[opp_choice]
#This use to be a decision tree, before I changed it to something else. Nevertheless, I kept the name
class Decision_tree:
def __init__(self):
self.dataX = []
self.dataY = []
self.clf = MultinomialNB()
def decide(self,my_load,opp_load,my_history,opp_history):
"""
Returns the decision as an integer
Done through a try (if a prediction could be made) except (if not possible)
"""
try:
#Let's try to predict the next move
my_h = list(map(lambda x: choices_dic[x],my_history[-n_data:-1]))
opp_h = list(map(lambda x: choices_dic[x],opp_history[-n_data:-1]))
pred = self.clf.predict_proba([my_h+opp_h])
#We create a points array where keys are the available choices
pts = []
for i in range(3):
#We compute the expected gain/loss for each choice
tmp = 0
for j in range(3):
tmp += compute_points(i,j,my_load,opp_load)*pred[0][j]
pts.append(tmp)
return pts.index(max(pts)) #We return key for the highest expected value
except:
return random.choice(range(3))
def append_data(self,my_history,opp_history):
if my_history == "":
self.clf = MultinomialNB()
elif len(my_history) < n_data:
pass
else:
my_h = list(map(lambda x: choices_dic[x],my_history[-n_data:-1]))
opp_h = list(map(lambda x: choices_dic[x],opp_history[-n_data:-1]))
self.dataX = self.dataX + [my_h+opp_h]
self.dataY = self.dataY + [choices_dic[opp_history[-1:]]]
if len(self.dataX) >= 10:
self.clf.partial_fit(self.dataX,self.dataY,classes=[0,1,2])
self.dataX = []
self.dataY = []
#Once again, this is not actually a decision tree
dt = Decision_tree()
#There we go:
def expectedbayesfunc(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
dt.append_data(my_history,opp_history)
choice = choices[dt.decide(my_loaded,opp_loaded,my_history,opp_history)]
return choice
```
[Answer]
# Cycler
```
def cycler(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
return "RPS"[len(myhistory)%3]
```
0
[Answer]
## Ensemble
```
from random import *
def f(I):
if I==0:return "R"
if I==1:return "P"
return "S"
def b(I):
if I=="R":return 0
if I=="P":return 1
return 2
def Ensemble(mp,op,ml,ol,mh,oh):
A=[0]*3
B=[0]*3
if(len(oh)):
k=b(oh[-1])
A[k-2]+=0.84
A[k]+=0.29
for x in range(len(oh)):
g=b(oh[x])
B[g-2]+=0.82
B[g]+=0.22
s=sum(B)
for x in range(len(B)):
A[x]+=(B[x]*1.04/s)
r=max(A)
else:
r=randint(0,3)
return f(r)
```
Several competing algorithms vote on the best solution.
## Swap
```
from random import *
def f(I):
if I==0:return "R"
if I==1:return "P"
return "S"
def b(I):
if I=="R":return 0
if I=="P":return 1
return 2
def Swap(mp,op,ml,ol,mh,oh):
A=[0]*3
B=[0]*3
if(len(mh)):
r=(b(mh[-1])+randint(1,2))%3
else:
r=randint(0,3)
return f(r)
```
Does a random move, but without repeating the last move it did.
[Answer]
# b l o d s o c e r
***s o c e r y***
I gave it a fix, so it should probably work now I hope
I messed something up again so I deleted and undeleted. I am making a lot of mess ups.
```
def blodsocerfunc(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
import random
# tuned up an ready to go hopeful
# s o c e r y
if len(my_history) > 40 and len(set(opp_history[-30:])) == 1:
if opp_history[-1] == "S":
return "R"
elif opp_history[-1] == "R":
return "P"
else:
return "S"
# against confused bots that only do one thing most of the time.
elif len(my_history)>30 and min(opp_history.count(i) for i in "RPS")/max(opp_history.count(i) for i in "RPS") >0.8:
return "RPS"[my_loaded.index(max(my_loaded))] # This is so if the other bot is acting errratic
# the max bonus is used for advantage
elif len(my_history) < 10:
if len(my_history) > 2 and all(i == "S" for i in opp_history[1:]):
if len(my_history) > 5: return "S"
return "P"
return "S" # Be careful, because scissors are SHARP
elif len(set(opp_history[1:10])) == 1 and len(my_history) < 20:
if opp_history[1] == "S":
return "R"
elif opp_history[1] == "R":
return "R"
else:
return "P"
elif len(opp_history) - max(opp_history.count(i) for i in "RPS") < 4 and len(my_history) < 30:
if opp_history.count("R") > max(opp_history.count(i) for i in "PS"):
return "P"
if opp_history.count("P") > max(opp_history.count(i) for i in "RS"):
return "S"
if opp_history.count("S") > max(opp_history.count(i) for i in "RP"):
return "R"
elif len(my_history) < 15:
if max(opp_loaded)<max(my_loaded):
return "RPS"[len(my_history)%3]
else:
return "RPS"[(my_loaded.index(max(my_loaded))+len(my_history)%2)%3]
elif len(my_history) == 15:
if max(opp_loaded)<max(my_loaded):
return "RPS"[(len(my_history)+1)%3]
else:
return "RPS"[(my_loaded.index(max(my_loaded))+ (len(my_history)%2)^1)%3]
else:
if max(opp_loaded)<max(my_loaded):
return random.choice("RPS")
else:
return "RPS"[(my_loaded.index(max(my_loaded))+ (random.randint(0,1)))%3]
```
[Answer]
# Weighted Random
Like RandomBot, but it picks only 2 to throw each time it is invoked. Will sometimes beat Rockstar or Assassin, but will pump up the scores of the other one (e.g., if it beats Rockstar, it gives Assassin a point boost).
```
import random
selection_set = ["R", "P", "S"]
selection_set.pop(random.randint(0,2))
def weightedrandombotfunc(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
return random.choice(selection_set)
```
[Answer]
# Greedy psychologist
Named that because it defaults to greedy, but if it can't decide, it counters whatever the opponent would do if they used the greedy strategy. If it still can't decide, it goes randomly.
```
from random import choice
def greedypsychologistfunc(my_points, opp_points, my_loaded, opp_loaded, my_history, opp_history):
greedy = get_my_move(my_loaded)
combined = list(set(greedy) & set(get_opp_counter(opp_loaded)))
if len(combined) == 0:
return choice(greedy)
return choice(combined)
def get_indexes(lst, value):
return [i for i,x in enumerate(lst) if x == value]
def get_my_move(my_loaded):
return ["RPS"[i] for i in get_indexes(my_loaded, max(my_loaded))]
def get_opp_counter(opp_loaded):
return ["PSR"[i] for i in get_indexes(opp_loaded, max(opp_loaded))]
```
] |
[Question]
[
## Description
All cubic equations can be solved, and every cubic has at least one solution. The goal of this challenge is to find the real solutions to a given cubic using inputs, and (obviously) the smallest program size.
## Rules
The solution must find the real solutions of a cubic correctly, using any method. The cubic must be in the standard form
$$ax^3 + bx^2 + cx + d = 0$$
The first coefficient cannot be zero, as then it would be a quadratic. There must a different output if it is zero, and outputting nothing at all is acceptable.
## Scoring
The score is based on the size of the program alone.
## Inputs
The four coefficients of the cubic, `a`, `b`, `c`, and `d`.
The input may be formatted however you like.
## Outputs
Every real solution to the cubic. There will either be three, or one for every cubic.
## Example
### With 3 solutions
Input:
```
1
3
0
-1
```
Output:
```
-2.879
-0.653
0.532
```
### With 1 solution
Input:
```
1
1
1
1
```
Output:
```
-1
```
## Additional Info
While you can use any method, you can find an image with the cubic equation (similar to the quadratic equation, can solve any cubic every time) equation can be found [here](https://math.vanderbilt.edu/schectex/courses/cubic/cubic.gif).
You can learn more about cubics [here](https://en.wikipedia.org/wiki/Cubic_equation).
[Answer]
# [R](https://www.r-project.org/), ~~42~~ 41 bytes
```
function(c,a=polyroot(c))a[!Im(a)]/!!c[4]
```
[Try it online!](https://tio.run/##PcoxCoAwDADA3V90SyCiRSehD/ANIrRGC4I2UhXq66uT63ExW2WNvwNfqwRIOLlz6boPIcodZkika8TCm/wnJmcO2Z4ocgEjukH1OzgcK6V4aMfsgaHUVFNDGjG/ "R – Try It Online")
Input is vector of `d`,`c`,`b`,`a`. Outputs `Inf` if the cubic coefficient (`a`) is zero.
Using `a[!Im(a)]` to select only real solutions is very susceptible to floating-point rounding errors; the TIO header rounds values less than 0.0000000001 to zero to prevent this. [Including rounding in the code](https://tio.run/##K/qfZvs/rTQvuSQzP08jWSfRtiA/p7IoP79EI1lTMzFa0TNXI1EzztIyVl9RMTnaJPZ/mkayhq6hjoGOsY6hpuZ/AA) costs ~~5~~ 3 more bytes.
---
# [R](https://www.r-project.org/), 111 bytes
```
function(e,z=1i^(1:3)){for(i in 1:99)z=z-e%*%rbind(z^3,z^2,z,1)/(z-(x=c(z,z))[2:4])/(z-x[3:5]);if(e)z[!Im(z)]}
```
[Try it online!](https://tio.run/##HchBCsIwEADAs7@oh8KubNBt9NBIHuAbQnIwNrAHUwgKZcW3R3CO03rxvbxrfslaYSH1LAnYWcRPWRvIIHVgN8@oXs0yHsZ2l/oATZY0TaTEeAQ1sPkMSooYJneO/9uCdZeIVymwoIb97QmK8bvrBTIwWTqRYcT@Aw "R – Try It Online")
Non-builtin [Durant-Kerner](https://en.wikipedia.org/wiki/Durand%E2%80%93Kerner_method) strategy copied from [97.100.97.109's answer](https://codegolf.stackexchange.com/a/252321/95126) (upvote that!).
Using this approach to find all the roots in parallel works very nicely with [R](https://www.r-project.org/)'s vectorized operations.
[Answer]
# [Python](https://www.python.org), ~~143~~ ~~134~~ 133 bytes
```
f=lambda a,b,c,d,R=[-1,1j,1]:[R:=[(z:=R[2])-(((a*z+b)*z+c)*z+d)/(z-R[0])/(z-R[1])]+R for i in" "*99]and[x for x in R[:3]if x.imag==0]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bY-xCsIwGIR3nyJ0SuofbezSBvISWUOGtCEasWkpFWp3n8Kli76Tb2OtFRc5OI4PDu5uj-bSHeowjvdz52j2vDpxMlVhDTJQQAkWpFCUATsC01xJLhQeuJBqpwnFGJt4WBdksvJtlmzxQKVK9BKYJnotkatb5JEPEYriPNcmWNXPsJ8gkoqn2jvUb3xl9kIkehmTNa0PHXaYQQoJUEbI6ofoHzaLkE__e-oF)
This is the first solution that doesn't use a builtin, and it suffers greatly for it. Instead, I'm using the [Durant-Kerner method](https://en.wikipedia.org/wiki/Durand%E2%80%93Kerner_method) to find all approximations, then filtering for whether they're complex.
---
-9 bytes from @Steffan for various small changes.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
1)?G&ZQ&Zj~)
```
[Try it online!](https://tio.run/##y00syfn/31DT3l0tKlAtKqtO8///aEMFYwUDBV3DWAA)
### How it works
```
% Implicit input
1) % Get the first element
? % If non-zero
G % Push input again
&ZQ % Implicit input. Roots of polynomial. Gives a numeric vector
&Zj % Push real and imaginary parts
~ % Negate. Gives "true" if imaginary part is zero, or "false" otherwise
) % Keep only real parts corresponding to "true".
% Implicit end
% Implicit display
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `P`, 4 bytes
```
hß∆P
```
[Try It Online!](https://vyxapedia.hyper-neutrino.xyz/tio#WyIiLCJow5/iiIZQIiwiIiwiUCIsIlswLDMsLTMsLTFdIl0=)
Good old built-ins. This may not work on some interpreters until the SymPy ACE vulnerabilities are fixed. Input as a list `[a,b,c,d]`.
Edit: Changed output to the input if leading coefficient is 0.
[Answer]
Both functions below take a polynomial in `x`.
# [PARI/GP](https://pari.math.u-bordeaux.fr), 27 bytes
```
p->if(#p>3,polrootsreal(p))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGiNNulpSVpuha7C3TtMtM0lAvsjHUK8nOK8vNLiotSE3M0CjQ1ISpu2hYUZeaVaKRpVMQZaxtrVcQZ6RpqanIhiwLFtCu0UUWNdCtA6iCGLFgAoQE)
Returns `0` for quadratics and below.
# [PARI/GP](https://pari.math.u-bordeaux.fr), 101 bytes
```
p->k=[Pi,I,2];for(q=1,99,k-=[subst(p,x,k[i])/vecprod([k[i]-z|z<-k[^i]])|i<-[1..3]]);[r|r<-k,!imag(r)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGiNNulpSVpuhY3Uwt07bJtowMydTx1jGKt0_KLNAptDXUsLXWydW2ji0uTiks0CnQqdLKjM2M19ctSkwuK8lM0okFc3aqaKhvd7Oi4zNhYzZpMG91oQz09YyDbOrqopggoo6OYmZuYrlGkGQu1zLagKDOvRCNNoyLOWNtYqyLOSNdQU5MLWRQopl2hjSpqpFsBUgcxZMECCA0A)
Yet another implementation of the Durand–Kerner method.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8? 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṛ/ȧÆr,N+AƲƇ
```
A monadic Link that accepts a list of the coefficients (`[d,c,b,a]`) and yields a list of the (one or three) real roots, unless `a` is zero in which case it yields an empty list.
**[Try it online!](https://tio.run/##ASYA2f9qZWxsef//4bmbL8inw4ZyLE7Ei0HGssaH////Wy0xLDAsMywxXQ "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hztn6J5YfbivS8TvS7Xhs07H2/4fbj056uHOGZuT//9HRuoY6BjrGOoaxXDrRhjpgCGJa6JjoGEGYBjogCFcA5ICYYH2GIHYsAA "Jelly – Try It Online").
...\$8\$ bytes if we can handle `a` being zero (in which case it works for all polynomials):
```
Ær,NċAƲƇ
```
[Try it online!](https://tio.run/##y0rNyan8//9wW5GO35Fux2ObjrX///8/WtdQx0DHWMcwFgA "Jelly – Try It Online")
### How?
The heavy lifting is done by a built-in...
```
ṛ/ȧÆr,N+AƲƇ - Link: coefficients, P = [d,b,c,a]
/ - reduce (P) by:
ṛ - right
-> a
Ær - polynomial roots (of P)
ȧ - logical AND
-> [d,c,b,a] or 0
Ƈ - keep those for which (with 0, keep those of range(0)=[]):
Ʋ - last four links as a monad - f(x):
N - negate (x)
, - (P) paired with (that)
A - absolute value (of x)
ċ - count occurrences (of that in the pair)
-> Truthy (1 or 2*) if x is real, falsey (0) if not
* when x=0
```
[Answer]
# [Python 3](https://docs.python.org/3/), 99 bytes
```
import numpy
f=lambda a,b,c,d:[float(i)for i in numpy.roots([a,b,c,d])if round(float(i))!=0if a!=0]
```
[Try it online!](https://tio.run/##Tcq7CsMwDIXhPU/hbhaoxW22Qp4kZFBqTAWxZVxlyNM77o2WMxz4@fKmd0l9rRyzFDVpjXnrwrBQnD0Zwhlv6K9jWITUMgQphg2nNzwVEX3Y8cMm4GCKrMnbr4fD4FqkdlPNhZPaYM/4GkD3Kz06PP4n18jlieoO "Python 3 – Try It Online")
[Answer]
# [J](https://www.jsoftware.com), 32 bytes
```
[:{:^:([:-.*./@(=+)){:@:>@p.^:{:
```
I am pretty bad at conditionals in J, but after some finagling, this was the best I could come up with. Expects coefficients as `d,c,b,a`
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmtxUyHaqtoqzkoj2kpXT0tP30HDVltTs9rKwcrOoUAvDigHVWeoyZWanJGvkKamZ6dgo2SoEKtgrGCioKIQbwg001jBEMYwAFoEEjeEaFywAEIDAA)
```
[:{:^:([:-.*./@(=+)){:@:>@p.^:{:
{:@:>@p.^:{: : u^:v executes u if v is true, else return x
{: : is last item 0?
{:@:>@p. : if non-zero
p. : converts coefficient form to multiplier-roots form
> : unbox the results
{: : take the roots, not the multiplier
{:^:([:-.*./@(=+)) : The check for only one real
([:-.*./@(=+)) : u(v(x)) where u is -. and v is *./@(=+)
(=+) : each x equal to its complex conjugate?
*./ : AND reduce result
-. : negate result
{: : if roots are not all reals, take the last value
extra:
u@v -> apply u monadically to v(x) for every application of v
u@:v -> apply u to the entire result of v(x)
[:u v -> strictly u(v(x))
```
[Answer]
# [J](https://www.jsoftware.com), 20 bytes
```
1(#~]=+)@{::[:p.]*{:
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxxVBDuS7WVlvTodrKKtqqQC9Wq9oKInXTQpMrNTkjXyFNTc9OwUbJUCFWwQQIVRTiDYHGGCsYwhgGMKgDljaE6F-wAEIDAA)
Takes `d c b a`, and returns the array of real roots, or an empty array if `a` is 0.
```
1(#~]=+)@{::[:p.]*{:
]*{: multiply the entire polynomial with `a`
which doesn't change the roots if `a` is nonzero
but gives 0 0 0 0 otherwise, which has zero roots according to `p.`
[:p. convert to multipler-roots form
1 {:: extract the roots
( )@ filter real roots:
#~]=+ filter the list by "complex conjugate equals self"
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 50 bytes
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z89Ojs@Vt86OzraJDZW0dbAyjY4P6csNboiLigxLz012kBHwThWL9vW1kCnQicoNTGnONb6f0BRZl5JdHp0ta6hjoGOsY5hbay@vl8sF7q4AUT8PwA)
```
g[k_]/;k[[4]]!=0:=Solve[x^Range[0,3].k==0,x,Reals]
```
Input is the number of coefficients in reverse order `{d, c, b, a}`. This defines a function `g` only if the `4th` argument is unequal 0. Otherwise this function remains undefined and returns the function call as output. Uses the built-in `Solve` function over the `Reals` domain.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes
```
#^0NSolve[x#+#2&~Fold~!##,x,Reals]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XznOwC84P6csNbpCWVvZSK3OLT8npU5RWVmnQicoNTGnOFbtf2BpZmqJQ0BRZl5JtHKdW1F@rktmemZJcV2Frl2ag4NyrFpdcHJiXl01V7WhjrGOgY6uYa0OV7UBEtsQyAKzuWr/AwA "Wolfram Language (Mathematica) – Try It Online")
Input `[a, b, c, d]`. If \$a=0\$, returns a list of as many `{Indeterminate}`s as there would be solutions.
When given non-equation expressions, `NSolve` [finds their roots](https://mathematica.stackexchange.com/a/163273).
```
x#+#2&~Fold~!## convert to a polynomial in x
NSolve[ ,x,Reals] get real solutions
#^0 invalidate solutions if a=0
```
[Answer]
# MATLAB, 29 bytes
```
syms a b c d;roots([a b c d])
```
] |
[Question]
[
Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details.
Related to [AoC2017 Day 6](https://adventofcode.com/2017/day/6).
---
A debugger program here is having an issue: it is trying to repair a memory reallocation routine, but it keeps getting stuck in an infinite loop.
In this area, there are `n` memory banks; each memory bank can hold any number of blocks. The goal of the reallocation routine is to balance the blocks between the memory banks.
The reallocation routine operates in cycles. In each cycle, it finds the memory bank with the most blocks (ties won by the lowest-numbered memory bank) and redistributes those blocks among the banks. To do this, it removes all of the blocks from the selected bank, then moves to the next (by index) memory bank and inserts one of the blocks. It continues doing this until it runs out of blocks; if it reaches the last memory bank, it wraps around to the first one.
For example, if there are initially four banks with `[0, 2, 7, 0]` memory blocks:
* The third bank is freed, and starting with the next (fourth) bank, the 7 blocks are cyclically spread out over the memory banks. After one cycle, the result looks like `[2, 4, 1, 2]`:
```
0 2 0 0
+1
+1 +1 +1 +1
+1 +1
--------------
2 4 1 2
```
* In the next cycle, the second bank is freed and redistributed, resulting in `[3, 1, 2, 3]`.
* In the next cycle, the first bank is freed (when there are ties, the first bank is chosen), giving `[0, 2, 3, 4]`.
* Next cycles give `[1, 3, 4, 1]`, then `[2, 4, 1, 2]`, where the sequence forms a loop.
Your job is to simulate one cycle of memory reallocation.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
[0, 2, 7, 0] -> [2, 4, 1, 2] -> [3, 1, 2, 3] -> [0, 2, 3, 4]
-> [1, 3, 4, 1] -> [2, 4, 1, 2]
[3, 1, 4, 1, 5, 9, 2] -> [5, 2, 5, 2, 6, 1, 4]
-> [6, 3, 6, 3, 0, 2, 5] -> [0, 4, 7, 4, 1, 3, 6]
-> [1, 5, 1, 5, 2, 4, 7] -> [2, 6, 2, 6, 3, 5, 1]
-> [3, 0, 3, 7, 4, 6, 2] -> [4, 1, 4, 1, 5, 7, 3]
-> [5, 2, 5, 2, 6, 1, 4]
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 33 [bytes](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
{+Àù‚Üë‚Äø(‚â†ùï©)‚•äùï©‚àæ(‚•ä‚üú0‚àæ(-‚àæ‚•ä‚üú1)‚àò‚äë‚üúùï©)‚äë‚çíùï©}
```
[Try it online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgeyvLneKGkeKAvyjiiaDwnZWpKeKlivCdlaniiL4o4qWK4p+cMOKIvigt4oi+4qWK4p+cMSniiJjiipHin5zwnZWpKeKKkeKNkvCdlal9CgooM+KAvzHigL804oC/MeKAvzXigL854oC/MinigL8oMOKAvzLigL834oC/MCl7a+KGkPCdlajii4Q+ez7iiJhG4o2f8J2VqSBrfcKo4oaV8J2VqX3CqCA54oC/Ng==)
```
{+Àù‚Üë‚Äø(‚â†ùï©)‚•äùï©‚àæ(‚•ä‚üú0‚àæ(-‚àæ‚•ä‚üú1)‚àò‚äë‚üúùï©)‚äë‚çíùï©} # Example input: ùï© = 0 2 7 0
‚äë‚çíùï© # The first index of the maximum value 2
‚äë‚üúùï© # The value at that index 7
-∾⥊⟜1 # negative value, value many 1's
# ¯7 1 1 1 1 1 1 1
⥊⟜0∾ # Prepend index many 0's
# 0 0 ¯7 1 1 1 1 1 1 1
ùï©‚àæ # 0 2 7 0 0 0 ¬Ø7 1 1 1 1 1 1 1
‚Üë‚Äø(‚â†ùï©)‚•ä # Reshape into a matrix with length(ùï©) columns, padding the last row with 0's
+Àù # sum the columns
```
[Answer]
# [J](http://jsoftware.com/), 37 bytes
```
(0:`]`[}+/@,-@#@[]\0,0 1#~],{~)]i.>./
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NQysEmITomu19R10dB2UHaJjYwx0DBQMletidarrNGMz9ez09P9rcnGlJmfkK6TFWWnYmGnGKhjoKBjpKJgDTYNIqKsjKTA0AKow1lEw1FEwAZOmOgqWQA3/AQ "J – Try It Online")
Consider input `0 2 7 0`:
* `(...)]i.>./` Entire verb is a hook giving the verb in parens the original input as a left arg, and the
max value's index `i.>/.` as the right. It evaluates like:
```
0 2 7 0 (...) 2 NB. 2 is the index of 7.
```
* `(0 1#~],{~)` Append the max's index to the max
`],{~` and copy `0 1` elementwise that many times:
```
0 0 1 1 1 1 1 1 1
```
* `0,` Prepend another 0:
```
0 0 0 1 1 1 1 1 1 1
```
* `-@#@[]\` Fold that into original-input-sized chunks, filling empty slots in
the last row with 0:
```
0 0 0 1
1 1 1 1
1 1 0 0
```
* `0:`]`[}...,` Prepend to that the original list, with the max value zeroed
out:
```
0 2 0 0
0 0 0 1
1 1 1 1
1 1 0 0
```
* `+/@` And sum the rows:
```
2 4 1 2
```
[Answer]
# [R](https://www.r-project.org/), 84 bytes
```
function(a){v=a[i<-which.max(a)]+1;a[i]=0;while(v<-v-1)a[i]=a[i<-i%%sum(a|1)+1]+1;a}
```
[Try it online!](https://tio.run/##VYzLDoIwFAX3/YpuSNpwayhKfEC/xLAoxIabQDEVqon67bU2btycxWTmuGBUMKvtF5wt0/zplT5jI@4D9sNm0o/I2lzWEbaqqCMeL8w3wgvJE0s2ZtltnZh@SZ7LpL@DVj0roIQ9FJyY2TGkaKk8Vfzq0C5MN8LEc05IF80tUAl0l7YCegRa/lWHX9V9qy5W4QM "R – Try It Online")
Note that in `a[i]=a[i<-i%%sum(a|1)+1]+1`, `i` is first updated on the RHS and then substitution is performed with the same index on LHS and RHS.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 59 bytes
```
->a{a[i=a.index(m=a.max)]=0;m.times{a[a[i+=1]?i:i=0]+=1};a}
```
[Try it online!](https://tio.run/##JYpRC4IwFIXf/RX2EmpXmVZEzWs/5HIfFqkMmrSlYMh@@xr0cOA73zlueXzDgKHs1KZIo6r09OzXzEQyas0ZhTTVrE3/iXt8HLDmu75pFBzRS@XDiGVnoXBb5trWSosDUWGZ82Wa9St1e7K8Q2LpfJK805FIQAMXEMz/eoQaTjFnuEITZfgB "Ruby – Try It Online")
[Answer]
# JavaScript (ES6), 66 bytes
Updates the input array.
```
a=>{for(a[i=a.indexOf(m=Math.max(...a))]=0;m--;)a[++i%a.length]++}
```
[Try it online!](https://tio.run/##hcxLCoMwGATgvaf4N4WEPLBvJKTgAUoPIC5@bNQUTYpKEcSzp7arli66GZiB@W74wL7o7H0Qzl9NKHVAfZpK3xHMrEZp3dWMl5K0@oxDLVsciZQSKc11rFohFMWMMbtC2RhXDXXO2BwK73rfGNn4iqSgIYs5bDgcOcQ5jV64W9aDAiGcojBBSVKq4Ou29DmKfqQthzWH3Tv3HJIF/iCTv2R4Ag "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~78~~ 77 bytes
*Edit: -1 byte and re-arranged to an almost-readable format thanks to pajonk*
```
function(x){x[m<-match(n<-max(x),x)]=0;a=x%*%t(!1:n);a[m+1:n]=1;rowSums(a)+x}
```
[Try it online!](https://tio.run/##VYvRCoIwGEbvfYp1Ifx/TnCWVOqeokvxYg6lQZuxJi2iZ18zuunm4/Bxjg2zGeVTXkc@8TAtRjo1G/D48p1ucy2cvIBZwceTeux50Qju023qYMNqg43odBah56yx8@O86DsIzPw7gOASClrSAy0Qk2m2oIgyhNUV3qwyDkSbT1HGJIEhujtKGCX771aUnCgp/7vjrxvWbkAMHw "R – Try It Online")
First we construct a matrix `a` of length(`x`) rows and `n`=max(`x`) zeros (using a golfy trick: `x%*%t(!1:n)`).
[R](https://www.r-project.org/) fills matrices row-first if we use 1-dimensional indices, so we can fill the matrix with `1`s at positions from `m+1` up to `m+n`, where `m` is the position of the maximum element of `x`, and the row sums will give the amounts we need to add to each index of `x`.
So now we just need to set the `m`-th element of `x` to zero, and add the row sums of `a`.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 65 bytes
```
a->for(i=1,c=a[m=vecsort(-a,,1)[1]],a[(m+i-1)%#a+1]+=1);a[m]-=c;a
```
[Try it online!](https://tio.run/##HczdCsIwDAXgVwkToWEpLP6gMrIXKbkIw0lBXalD8Olrt5vA4TsnyXL0j1QmkGJ@mObsojCNYuEl3/v4mfPivBExBlYlC@7VRs@431nL2gpjX6vqZeytWErPnzPwA2yfQIAJrgQpx/dSoVmpAaswOUNEghA6ggPBhaDTGo@0bk7bPRPcKqpi@QM "Pari/GP – Try It Online")
---
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 69 bytes
```
a->c=a[m=vecsort(-a,,1)[1]];a+Vecrev((x^c\(x-1)-c/x)*x^m%(1-x^#a),#a)
```
[Try it online!](https://tio.run/##HctdCsIwEATgqywVYVc32PiDiqTH8KWmsIRWCtaGWEo8fUx9mIHhY7yEXj196sAkUZUzUg9mbt1nDBMqYdZUa2tvsr23LrQzYmzcA6PSpNwu0iY2wxq1is1KiHOSeP/6ooCqoBsD9mBAM1wYfOjfU4ZioQIkQ4dCRAx1XTLsGc4Mpc3zwMvn@O8TwzWjtZR@ "Pari/GP – Try It Online")
Longer but more interesting.
See the input as a polynomial, e.g. `[0, 2, 7, 0]` becomes \$2x+7x^2\$. Let \$c\ x^{m-1}\$ be its term with the largest coefficient (in this case, \$c=7,m=3\$). Then we subtract \$c\ x^{m-1}\$ from the polynomial, and then add \$(x^m+x^{m+1}+\cdots+x^{m+c-1}) \bmod (x^n-1)\$, where \$n\$ is the length of the input.
[Answer]
# [C (clang)](http://clang.llvm.org/), 78 bytes
```
h;m;i;f(*b,n){for(i=m=0;i<n;++i)m=m<b[i]?b[h=i]:m;for(b[h]=0;m--;)++b[++h%n];}
```
[Try it online!](https://tio.run/##rVTbjpswEH3frxghZQXB0XLNateh@1D1KxJUAYGN1eBEgapRI3696cBg7K0S7UtR4jE@xzNzTuwUi2KfyffrdcdrLnhlz3MmnUt1ONkiqROPi5XkriucOqlX@Vqkb/l6l4j0teY9B19SJNWLBXdcN1@77m4mU95dhWyhzoS0Hbg8AD79Qls2rbdOIYGLxyBg8MzA6/iE@YQhEDHwkWFgAWEhAQxCAwvNnMiIDCwizCcAdxtYbOakkjGDl4@Fl0SKh@Q0LmmDQfouiRUNeaYP6nvuuNI/H6gNMQcvGMmmEFAIKUQUYgpLnQXK87Es2nLr3XFL4f4dxxQe3HFN4eEd5xQefVI//sw4RRwdXg6FaKSmYtM7xSbyZALTevU00NNQTyM9jfVUWVscZNNCsctOcxzL4kd5olLW5vwt2JxfvuI3thiY76E17sbLAHYvSshtecZtHh@nK2jE7/JQ2aqg8zQuzKcVDnjFera6Leq3lphpPF8DnnITxgM14s1tOP9ZVcios/3@UNgS5hA5mnI8IamyrbVlLGohowgUIIf@zN7M7bNmtkVbxFvvzauFY4v/E0bK/uk7wdW@XQwa63Rhu@cwkDc6TGHxBT60SUcC003H4oYBcMyaBjn@/5U3avlH4VDrMdFKsbc7UrWsWbORmFGdtz6Hyts9dNc/RbXP3pvr4tdf "C (clang) – Try It Online")
Inputs a pointer to an array of memory banks and its length (because pointers in C carry no length info).
Reallocates the memory in place - of course!!! :)))
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
IEθ⁺∧⁻⌕θ⌈θκι÷⁺⌈θ﹪⁻⌕θ⌈θκLθLθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQKNQRyEgp7RYwzEvRcM3Mw/IcssEMoHCvokVmbmluRqFmpo6CtlAnAnEnnklLpllmSmpGmBdCDVA9fkppTn5hAzxSc1LL8kA8VE5QGD9/390tLGOgqGOggmYNNVRsNRRMIqN/a9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The number to be added to each cell (or replacing the maximum cell) equals the maximum cell divided by the length of the array, but adjusting for the cyclic difference between the two cells, which distributes the remainder.
```
θ Input array
E Map over elements
θ Input array
‚åï Find index of
θ Input array
‚åà Maximum value
⁻ Minus
κ Current index
‚àß Logical And
ι Current value
⁺ Plus
θ Input array
‚åà Maximum value
⁺ Plus
θ Input array
‚åï Find index of
θ Input array
‚åà Maximum value
⁻ Minus
κ Current index
Ôπ™ Modulo
θ Input array
L Length
√∑ Integer divided by
θ Input array
L Length
I Cast to string
Implicitly print each value on its own line
```
I misread the question, so I originally wrote a 43 byte program to find the loop:
```
W¬№υθ«⊞υ✂θUMθ⁺∧⁻⌕θ⌈θλκ÷⁺⌈θ﹪⁻⌕θ⌈θλLθLθ»⊞υθIυ
```
[Try it online!](https://tio.run/##hY89C8IwEIbn9lfcmEIc/BrESSqCYKXgWDqENphgPmybVEH87fFaEXFyuOOe@@J9K8HayjIVwk1IxYEcrSOp9cYRT6FJkgQecZT7Tgx8UrLiBLvrOMrYNbVaM1OThkKufEc2WGfSYLWT73bG7lJ7PZxQUBgXjL1xW9nLmpPx6ruD@7b2yv57cuDm7MTAv4CynvFHa4OUtxKNpKxDNzgNoSjmFKYUFmNeUlhRmJVlmPTqBQ "Charcoal – Try It Online") Link is to verbose version of code. Outputs using Charcoal's default array format, which is each element on its own line and rows double-spaced.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~19~~ 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
DZ©kÅ0®(®Å1)˜IgôζO
```
-1 byte by switching to the legacy version of 05AB1E, where the sum ignores strings inside integer-lists.
[Try it online](https://tio.run/##AS0A0v8wNWFiMWX//0Rawqlrw4Uwwq4owq7DhTEpy5xJZ8O0zrZP//9bMCwyLDcsMF0) or [verify all test cases](https://tio.run/##PU47CgIxEL3KspXCK/IPVtvY2xu2UBALeyEHWA9g7QVsthIPkJSCh/AicWYQi2Fe3rxPlN/t9aGd89B3n8u164fc1ttyP9VJlXlR5jrp5euWj/Xxfm4aWkoKBhFqRDJw0DCELG9YQny1cIQ0b@jflZUeK1F70vAE5ukdSMnDXi8ZjhrYQbwkeXFzX5TeIG7HvOQrUrIjSL7790X60/gF).
Luckily we don't have to find the cycle, since that would have been [30 bytes (and very slow)](https://tio.run/##AWAAn/8wNWFiMWX/dnk/IiDihpIgIj95/1tEWsKpa8OFMMKuKMKuw4UxKcuceWfDtM62T0TCu0TCr3PDpSPLhn3LhsKv/yzCtP9bWzAsMiw3LDBdLFszLDEsNCwxLDUsOSwyXV0) due to 05AB1E's lack of get\_index builtin for sublists.
**Explanation:**
```
# e.g. input = [0,2,7,0]
D # Duplicate the (implicit) input-list
# STACK: [0,2,7,0],[0,2,7,0]
Z # Push its maximum (without popping the list)
# STACK: [0,2,7,0],[0,2,7,0],7
© # Store this maximum in variable `®` (without popping)
k # Get the 0-based index of this maximum in the list
# STACK: [0,2,7,0],2
√Ö0 # Pop and push a list of that many 0s
# STACK: [0,2,7,0],[0,0]
® # Push the maximum from variable `®`
( # Negate it
# STACK: [0,2,7,0],[0,0],-7
® # Push the maximum from variable `®` again
√Ö1 # Pop and push a list of that many 0s
# STACK: [0,2,7,0],[0,0],-7,[1,1,1,1,1,1,1]
) # Wrap everything on the stack into a list
Àú # Flatten it
# STACK: [0,2,7,0,0,0,-7,1,1,1,1,1,1,1]
Ig # Push the input-length
# STACK: [0,2,7,0,0,0,-7,1,1,1,1,1,1,1],4
ô # Split the list into parts of that size
# STACK: [[0,2,7,0],[0,0,-7,1],[1,1,1,1],[1,1]]
ζ # Zip/transpose; swapping rows/columns,
# using a space as default filler-item if the matrix is irregular
# STACK: [[0,0,1,1],[2,0,1,1],[7,-7,1," "],[0,1,1," "]]
O # Sum each inner list, ignoring the spaces
# STACK: [2,4,1,2]
# (after which the result is output implicitly)
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~81~~ ~~79~~ 77 bytes
```
def f(a):
k=a.index(m:=max(a))
for i in range(k,m-~k):a[i%len(a)]+=i>k or-m
```
-2 bytes thanks to *@loopyWalt*.
Modifies the input-list.
[Try it online.](https://tio.run/##TY5NDoIwEEb3nGI2hjYOhh9RhNSLEGKaULSpLaSywI1LD@ARvQgWSNTFLOZ9b75Md@8vrUmyzo5jLRpoCKe5B4rxjTS1GIjOmeaDo9SDprUgQRqw3JwFUaiDh6I5L@XqKoxzqjWTRwWtDfTc1otbTziaqXK@Pv2uFwjQWWkmSZia@fB@vsCnxZxMvxT/jtu8ubIMMcY9hhWmji0owQi3blI8YFxh9g2iEF3m3B0txg8)
**Explanation:**
```
def f(a): # Function with list parameter:
k=a.index(m:=max(a))
# Set `m` to the maximum of the list
# And set `k` to the first 0-based index of this maximum
for i in range(k,m-~k):
# Loop `i` in the range [k,m+k]:
a[i%len(a) # `i` modulo the list-length to prevent IndexErrors
]+= # And increase the value at this modular index by:
i>k # 1 if `i` is larger than `k`
or-m # or the negative maximum otherwise (if i==k in the first iteration)
```
[Answer]
# Java 8, 85 bytes
```
a->{int l=0,m=0,j=0;for(int i:a){if(i>m){m=i;j=l;}l++;}for(a[j]=0;m-->0;)a[++j%l]++;}
```
Modifies the input-array.
[Try it online.](https://tio.run/##hVDdaoMwFL7vUxwKA8UYXLeyrUFhD7De9FK8OLM6kiWxaOwokmd3SfSujF0kkO@c7y8Cr5iK8/dcSxwG@ECupw0A16bpW6wbOPonwLXjZ6gjh5cVYMwcaDfuGgwaXsMRNOQzpsXkNkDmGVHuiDxjbdd7FvADxhNvI16oeFI5ZyKXzMokYdavYCkqt63StMhYjGWSiAdZ@enMvM9l/JTOZ7ULaZTLGp1Mz/VXyLQENc1gIt38QIg6ZWRHXkhmyT5kvps/kUfy7M6evJGdJa93zYJVIK3d@x5vxLMBVTdqs/r6EmxBlg4LDHC6DaZRtBsNvbisJhLuy@louKTvXmugpltaREE7TrYHgO0aF0DTeh2wPxSl/ldz5dpQzs6/)
**Explanation:**
```
a->{ // Method with integer-array parameter and no return
int l=0, // Length, starting at 0
m=0, // Max, starting at 0
j=0; // Max-index, starting at 0
for(int i:a){ // Foreach over the integers of the input:
if(i>m){ // If the current integer is larger than the max
m=i; // Replace the max with this integer
j=l;} // And replace the max-index with the 'length' thus far
l++; // At the end of the iteration, increase the length by 1
} // After the first loop:
for(a[j]=0; // Replace the max at the max-index with 0
m-->0;) // Loop the max amount of times:
a[++j // Increase the max-index by 1 first
%l // Then modulo it by the determined array-length
]++;} // And increase the integer at that index by 1
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 30 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
╙`=º*\ª*hb*\Γ─h(?£/{\;\£‼≥<^mΣ
```
[Try it online.](https://tio.run/##y00syUjPz0n7///R1JkJtod2acUcWqWVkaQVc27yoykNGRr2hxbrV8dYxxxa/Khhz6POpTZxuecW//8fbaBjpGOuYxDLFW2kY6JjqGMEZBmDaB1jIAska6xjAmQZgmgdQ6gsSKWpjiVYtSlQDQibgcSBfDOgShAG6TUFm2ECtAGkAygONskUrBtknznYXjOwbmOQONh8AyAbpMMMbL4J3D5zoJsA)
Sometimes this language can be so annoying to program in.. MathGolf lacks a builtin to split integer-lists into sublists; it also lacks a transpose builtin for matrices; the (do-)while builtins only work for everything before it, not for portions near the end; and it lacks a builtin to push an implicit input-list (so those can only be accessed again by swapping) - [using an explicit input-list is also 30 bytes](https://tio.run/##PY0tDsJAEIX9nIQ0k7C/bUjgJg1/AlbQYHCYWjQg0A2mRyCo1vcQe5Fl3grEvGy@/d5Ms7uE4/l0SGnsN/H52q6GT1EPfRH2RT3d46MNs7EfuvkVGdtvvL2X62bqUlJsuGJFhh1rNmSRbAncsiONZJ05DM8Lsbz8YkpQKsXBoOOl6WQjXKGEhs6uUELDZNfnnUpecIWS@1@o2P4A). Because of that, the trailing `h(?£/{\;\£‼≥<^mΣ` does what we we want to do manually (it basically accomplishes the same as `IgôζO` in [my 05AB1E answer](https://codegolf.stackexchange.com/a/238317/52210), but a lot more hacky..)
**Explanation:**
```
# e.g. input = [0,2,7,0]
‚ïô # Push the maximum of the (implicit) input-list
# STACK: 7
` # Duplicate the top two items
# STACK: [0,2,7,0],7,[0,2,7,0],7
= # Get the 0-based index of this maximum in the list
# STACK: [0,2,7,0],7,2
º* # Multiply this index by [0]
# STACK: [0,2,7,0],7,[0,0]
\ # Swap the two two items so the max is at the top
# STACK: [0,2,7,0],[0,0],7
ª* # And multiply this max by [1]
# STACK: [0,2,7,0],[0,0],[1,1,1,1,1,1,1]
h # Push its length (without popping)
# STACK: [0,2,7,0],[0,0],[1,1,1,1,1,1,1],7
b* # Multiply it by -1 to negate it
# STACK: [0,2,7,0],[0,0],[1,1,1,1,1,1,1],-7
\ # Swap the top two items
# STACK: [0,2,7,0],[0,0],-7,[1,1,1,1,1,1,1]
Γ─ # Wrap the top four items into a list, and flatten
# STACK: [0,2,7,0,0,0,-7,1,1,1,1,1,1,1]
```
```
h # Push the length (without popping)
# STACK: [0,2,7,0,0,0,-7,1,1,1,1,1,1,1],14
( # Decrease it by 1
# STACK: [0,2,7,0,0,0,-7,1,1,1,1,1,1,1],13
? # Triple-swap to push the (implicit) input-list
# STACK: [0,2,7,0,0,0,-7,1,1,1,1,1,1,1],13,[0,2,7,0]
£ # Pop and push its length
# STACK: [0,2,7,0,0,0,-7,1,1,1,1,1,1,1],13,4
/ # Integer-division
# STACK: [0,2,7,0,0,0,-7,1,1,1,1,1,1,1],3
{ # Loop that many times:
\ # Swap to unfortunately get the implicit loop-index at the top
# STACK: [0,2,7,0,0,0,-7,1,1,1,1,1,1,1],0
; # Discard the top of the stack
# STACK: [0,2,7,0,0,0,-7,1,1,1,1,1,1,1]
\ # Swap again to push the (implicit) input-list
# STACK: [0,2,7,0,0,0,-7,1,1,1,1,1,1,1],[0,2,7,0]
£ # Pop and push its length
# STACK: [0,2,7,0,0,0,-7,1,1,1,1,1,1,1],4
‼ # Apply the following two builtins separated:
‚â• # Slice to get the items in the range [input-length,list-length)
< # Slice to get the items in the range [0,input-length)
# STACK: [0,0,-7,1,1,1,1,1,1,1],[0,2,7,0]
^ # Zip to create pairs
# STACK: [[0,0],[0,2],[-7,7],[1,0],[1],[1],[1],[1],[1],[1]]
mΣ # Map, and sum each inner list
# STACK: [0,2,0,1,1,1,1,1,1,1]
# (after the loop, the entire stack joined is output implicitly)
```
[Answer]
# [PHP](https://php.net/), 76 bytes
```
for($a[$i=array_keys($a=&$argv,$m=max($a))[0]]=0;$m--;)$a[++$i%count($a)]++;
```
[Try it online!](https://tio.run/##vY7BCsIwDIbvfYogVSytUOdEpRYfZI4xZuc2WTs2FUV89tpVPMkOXswhCfmT/F9TNHa7a4oGpW2b3pOuKPPzFKft8UqEzU3r@giX8q2e1L1zAznxCwzXsk5vbkBIxONYcoHr2UwQd0IpLseZuej@GYkpFVZlhYGqMzpROjMH9XFByNtUIIELcHULYV8pJQ8ELgYofrP3nwYRngh5bbTXez1ySF5wRNGCwZxB6POSwYZBEItv4vXfia3lNrAry18 "PHP – Try It Online")
Modifies the input array in place. Now this answer troubles me. In PHP we can take arguments as an array in `$argv`, but the first entry is the file name (`".code.tio"` in TIO), which forces me to do `array_shift($argv)` to get rid of this entry. After [verifying on meta](https://codegolf.meta.stackexchange.com/a/20882/90841), we can take the input by reference and change it in place even for a full program, but [cannot assume the input is stored in predefined variables](https://codegolf.meta.stackexchange.com/a/8731/90841). If I leave the `array_shift($argv)` as part of the program, it would mean that I consider the input format as different from the question (a string followed by our numeric values), and we cannot loop over it of else the array would shrink with each iteration.. so here are all the versions.. Anyone can rule this out?
# PROBABLY INVALID: [PHP](https://php.net/), 69 bytes
```
for($a[$i=array_keys($a,$m=max($a))[0]]=0;$m--;)$a[++$i%count($a)]++;
```
[Try it online!](https://tio.run/##vY7fCoIwFMbv9xSHWNHYhFVGxRw9iIkM09RwE60oomdfc3UX3UXn4vz9@M6vLVsbbduyRarr1C3ty6o4TbGSE6y6w4UIW5jOzTGu5EtxzG@9WzDcyEZdXUdIzJNEcoGbIBDEaSnF1TgzZz04kYRSYfOsNFD3Rqe5zsw@n77tEfL@NUjgAlyNIBwqpeSOwMVP3nunrwgPhPxttNM7PXJI/uCI4gWDGYPQ5yWDDYN5Ij6J138ntpbbuV1Z/gQ "PHP – Try It Online")
**If I had to include the `array_shift($argv)` in the code, it would be shorter to use a function (note that I can't use a loop in a PHP arrow function):**
# [PHP](https://php.net/), 84 bytes
```
function(&$a){for($a[$i=array_keys($a,$m=max($a))[0]]=0;$m--;)$a[++$i%count($a)]++;}
```
[Try it online!](https://tio.run/##nU7LCsIwELznKxaJ0pAIUSsqMfghtUioKa3SpFQFpfTb41YRBfHiHvYxuzszdVGH9aYuakJzHfKLy86ld9GIGtbmvomoSWipTdOY2@5obycEBK10Za7YMZbINNVS0Wo8VgxvOaflMPMXd@7XKeeqC4oQigSgIZECpgIWAmSqUDDqcaaIzQoPh5N3O@syv7cvnDwcHPBTKsC6hrivnLOWAMaboZ9@sXTkKTDYuq0bfLiZCZgIiB95LmCF5tDWl@byH80QZJiGRZB3 "PHP – Try It Online")
[Answer]
# TypeScript Types, 584 bytes
```
//@ts-ignore
type a<T,K=keyof T>=T extends T?keyof T extends K?T:never:0;type b<T,U=T>=T extends T?Exclude<T,Partial<Exclude<U,T>>>:0;type c<T,N=[]>=`${T}`extends`${N["length"]}`?N:c<T,[...N,0]>;type d<A,B,N=[]>=A extends[...B,...infer A]?d<A,B,[...N,0]>:[N,A];type M<A,T={[K in keyof A]:c<A[K]>},i=a<{[K in keyof T]:T[K]extends b<T[number]>?c<K>:never}[number]>,I=i["length"],X=d<T[I],c<T["length"]>>>={[K in keyof T]:(K extends`${I}`?X[0]:[...X[0],...T[K],...c<K>extends[...i,...Partial<X[1]>]|Partial<[...i,...X[1]]extends[...c<T["length"]>,...infer A]?A:never>?[0]:[]])["length"]}
```
[Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4AVAGgGkBeAa3R2QDNDyA+W8w9AD3DpEAE0jsA-I2Zse-QSLHVx5AFyJ0AN3SoVABgDcuAoQBGFSgFVuXWQKGiJAUT4BjADYBXYenMAFYqjgsMRupM7uXj4WlJwcHHqG+EQu5gBytADaALpcAAYAJADe5AC+uXL2kAWFqRkARG5C8OAAFnVZZeKpKilUGQB0g6mUujmJxsKkAIKUAEKU6dlcU7x2CgOD84P9sIgs2oRTWeKTM-Mb-cOj8RnDR+NEALLTMbSFGdSEu4RSrIdZPWmHxyJUosFoZHen2+vxkAPIwIqClMFAyiA8AFsTNocuIUtR4uotKgSmjMdjUDlKABJWiweqNRDNNpZSgADVokwR1NZvQZTVa7TiXChX0QPyYf3IAIAFJ8kaJqtTOmyMqMVBdVaNKNsEdRWdt8RwFZALrAdYN-IFgqFVQBGHJZAA+VqCIVIZot-XtWSyJoufIaApZHC9u32qH+4imak02g44jVAOyWQAlPymYKOphsEl2LpCLRCM81ZRCAAmMsAdjL10wIEIjYAeuJc8ZyHbC8WPZXCAAWMt2svlnL14CNwgtttEcjlrslgDMg+HZYXo4bzdbRhnC-nHt0K8IS-76-Hm+n7D7e4yQ6PZYHhAdHDHE6nF-IAFZr8fbw-bx+ywATmHU9Xy3PNyAANmvACKzLWDe0g5cT2fDdJ3A9sq2vJC70IHDjwPODCA-UDz23dgAA5r0Ih8a37ZDj0g0j0PfQDr3-ZCEPvatmKnciOwLIsS0Qw98PgwdeIwmc7U7ISPQI1dq24vCQNQs8WP4u05zkjI-2UjjCDotc1LAzAgA)
## Ungolfed / Explanation
```
// Filters a union of tuples for those with the shortest length
type Shortest<T, K = keyof T> = T extends T ? keyof T extends K ? T : never : 0
type Max<T, U = T> = T extends T ? Exclude<T, Partial<Exclude<U, T>>> : 0
// Converts a number to a tuple of equal length (this version also supports strings)
type NumToTuple<T, N = []> = `${T}` extends `${N["length"]}` ? N : NumToTuple<T, [...N, 0]>
// Returns [A / B, A % B]
type DivRem<A, B, N = []> = A extends [...B, ...infer A] ? DivRem<A, B, [...N, 0]> : [N, A];
type Main<
_Banks,
// Convert every number in the input to a tuple
Banks = { [K in keyof _Banks]: NumToTuple<_Banks[K]> },
FreeIndTup = Shortest<
// Find the indices of Input where the value is equal to the max
{ [K in keyof Banks]: Banks[K] extends Max<Banks[number]> ? NumToTuple<K> : never }[number]
>,
FreeIndNum = FreeIndTup["length"],
// The first number is the number of blocks every bank recieves (NewBlockMin)
// The second is the number of banks that recieve one extra bank (ExtraCount)
BlockDist = DivRem<Banks[FreeIndNum], NumToTuple<Banks["length"]>>
// @ts-ignore
> = {
// Map over Banks:
[K in keyof Banks]: (
K extends `${FreeIndNum}`
// If this Bank is the one being freed, return NewBlockMin
? BlockDist[0]
// Otherwise, sum:
: [
// The old value
...Banks[K],
// NewBlockMin
...BlockDist[0],
// 1 if the index meets one of the following critera, or 0 otherwise:
...NumToTuple<K> extends
// Between FreeInd and FreeInd + ExtraCount
| [...FreeIndTup, ...Partial<BlockDist[1]>]
// Or, if FreeInd + ExtraCount > Banks.length, less than (FreeInd + ExtraCount) - Banks.length
| Partial<
[...FreeIndTup, ...BlockDist[1]] extends [...NumToTuple<Banks["length"]>, ...infer A]
? A
: never
>
? [0]
: []
]
)["length"];
};
```
```
[Answer]
# [Rust](https://www.rust-lang.org/), 205 bytes
```
|x:&[_]|{let(mut r,mut v)=(vec![],x.to_vec());while!r.contains(&v){r.push(v.to_vec());let(n,i)=(0..).zip(r.last()?).map(|a|(a.1,!a.0)).max()?;v[!i]=0;for j in!i+1..=!i+n{v[j%x.len()]+=1}}r.push(v);Some(r)}
```
[Try it online!](https://tio.run/##hVJRb4IwEH7nVxwmI23sKkzQTML2I/ZIiCEGYw1WVgqaAb@dlXYYXFzWhzvuu7vvvmsRVSn7PYdTyjjC0Fh5JmEPEfTtdePE26RtFIJOlQRBBlvjCNXZzo4TcqXyvFXfCOPwcmB5Zgu6O3OpqErk1LgRtKjKA6ondQMZJ0yRuJRi@sUKJGielhLhd0xPaYHatEUp9YidUhcP0FWlwjq2WRK54f4s4AiM22zuURopx5s6Pj5daZ6pBZJ55HXdOBeHH@dThgTuelAntAarzUCDGC8qSSDl5SUTWJGCE1tmOZfAC4E1ATchoJE/YBX6BDyFj8jShASWI2K6FO6PiGdCVfmAJ8HkR4WhMnhA4HUy5b98oGcauzJlY2qlhxtrpAUTpb7ez3AOZRPJwTjIiF1PtK/GQUtTNrkMV4OGczVR6N@LX08u7JH4BOuHSxrthlMIxmXObTRrNu8dPL/B4GcE7t81vDUsFpCWZSakfYNMvM0@beTskaM7Ma34Rag/Ef/i6Kyu778B "Rust – Try It Online")
[Answer]
# Python3, 162 bytes :
```
f=lambda b,c=0,i=0,k=[]:k+[b]if b in k else(f(b[:(i:=b.index((m:=max(b))))]+[0]+b[i+1:],m,i+1,k+[b])if not c else f(b[:(j:=i%len(b))]+[b[j]+1]+b[j+1:],c-1,j+1,k))
```
[Try it online!](https://tio.run/##PY3NCsIwDIDvPkUuQkujbE5RC32S0sOyddj9dGPuMJ9@ZhUMJIEk35fps7zGWDymedsa05cD1SUQVibDwNkZ63SnLLnQAEGI0IHv3140gqwWQRs6h1j7VYhBm6FcBUkOp2zmFNmgcu1wQO6YLJI1cVygShb4WVptwrH3cWeZJNs6le94m/DqlGO7C6TcpjnEhZ/bDOGCcEfInJSH/7hAyBGuqd4QnnzF@@0L)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 78 bytes
```
(a=#;a[[Mod[m+i,Tr[1^a],1]]]++~Do~{i,c=a[[m=Tr@Ordering[-a,1]]]};a[[m]]-=c;a)&
```
[Try it online!](https://tio.run/##HYvLCsIwEEV/ZSBQlE6x9YFKiXShOx8bd0OEIW1tFrFQuwvpr8fYzeHAPdfy2DWWR6M5tCDDgqUomejW12RTg8@BihcrLJRSaTqd@8kZ1DIWVj6H6jHUzWA@b8p4Tvz/a5XKpC55mYR78x3pyhEX3fUkIDtBSyKWkCAIhEMUWFXgXI6wRtgj5B7BbRAKhO3MHcIxjt6HHw "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
Your task, if you wish to accept it, is to write a program that outputs its own source code in the binary **UTF-8** representation.
# Rules
* The source must be at least 1 byte long.
* Your program must *not* take input (or have an unused, empty input).
* The output may be in any convient format.
* Optional trailing newline is allowed.
* Notice that one byte is 8 bits, and the length of the binary UTF-8 representation is necessarily a multiple of 8.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
# Example
Let's say your source code is `Aä$$€h`, its corresponding UTF-8 binary representation is `010000011100001110100100001001000010010011100010100000101010110001101000`.
If I run `Aä$$€h` the output must be `010000011100001110100100001001000010010011100010100000101010110001101000`.
```
A --> 01000001
ä --> 1100001110100100
$ --> 00100100
$ --> 00100100
€ --> 111000101000001010101100
h --> 01101000
Aä$$€h --> 010000011100001110100100001001000010010011100010100000101010110001101000
```
# String to binary UTF-8 converters
* [Try it online!](https://tio.run/##dY5NCsIwEIX3OcWAlUloK9qFlEAEzyEipKYmUKalTVG3nsWlt/AmXiRWBbsQNw/eDx@vOXtbUxbCBIp67@ggofdlmjNHTe93Q2ZUj@v7NYoel5tF1ilEVtYtFOAIxpVkoJV2xB15XswMvUKObxiKr7fmhCKBxVKITSa3DI7WVQYqQ1yLaS61wjnGmkEXq0GbdsDBDy7BNF1hotmnH1/8GXYhPAE "Python 2 – Try It Online")
* [utf8-convert](https://sites.google.com/site/nathanlexwww/tools/utf8-convert "Nathan Lex")
[Answer]
# [V](https://github.com/DJMcMayhem/V), 28 (or 16?) Latin 1 bytes (35 UTF-8 bytes)
```
ñéÑ~"qpx!!xxd -b
ÎdW54|D
Íßó
```
[Try it online!](https://tio.run/##ASgA1/92///DscOpw5F@InFweCEheHhkIC1iCsOOZFc1NHxECsONw5/Ds/// "V – Try It Online")
Hexdump (in Latin 1):
```
00000000: f1e9 d17e 2271 7078 2121 7878 6420 2d62 ...~"qpx!!xxd -b
00000010: 0ace 6457 3534 7c44 0acd dff3 ..dW54|D....
```
Output (binary representation of the same code in UTF-8, not Latin 1):
```
110000111011000111000011101010011100001110010001011111100010001001110001011100000111100000100001001000010111100001111000011001000010000000101101011000100000110111000011100011100110010001010111001101010011010001111100010001000000110111000011100011011100001110011111110000111011001100001010
```
Explanation:
```
ñéÑ~"qpx " Standard quine. Anything after this doesn't affect the
" program's 'quine-ness' unless it modifies text in the buffer
!!xxd -b " Run xxd in binary mode on the text
Î " On every line...
dW " delete a WORD
54| " Go to the 54'th character on this line
D " And delete everything after the cursor
Í " Remove on every line...
ó " Any whitespace
ß " Including newlines
```
---
**Or...**
# [V](https://github.com/DJMcMayhem/V), 16 bytes
```
ñéÑ~"qpx!!xxd -b
```
[Try it online!](https://tio.run/##K/v///DGwysPT6xTKiyoUFSsqEhR0E36/x8A "V – Try It Online")
Output:
```
00000000: 11000011 10110001 11000011 10101001 11000011 10010001 ......
00000006: 01111110 00100010 01110001 01110000 01111000 00100001 ~"qpx!
0000000c: 00100001 01111000 01111000 01100100 00100000 00101101 !xxd -
00000012: 01100010 00001010 b.
```
OP said:
>
> The output may be in any convenient format.
>
>
>
This outputs in a much more convenient format for V :P (but I'm not sure if that's stretching the rules)
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 20 bytes
```
{s"_~"+{i2b8Te[}%}_~
```
[Try it online!](https://tio.run/##S85KzP3/v7pYKb5OSbs60yjJIiQ1ula1Nr7u/38A "CJam – Try It Online")
Surprised to see CJam winning! we'll see how long that lasts...
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 105 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
0"D34çýÇbεDg•Xó•18в@ƶà©i7j0ìëR6ôRíć7®-jšTìJ1®<×ì]ð0:J"D34çýÇbεDg•Xó•18в@ƶà©i7j0ìëR6ôRíć7®-jšTìJ1®<×ì]ð0:J
```
05AB1E has no UTF-8 conversion builtins, so I have to do everything [manually](https://stackoverflow.com/a/6240184/1682559)..
[Try it online](https://tio.run/##yy9OTMpM/f/fQMnF2OTw8sN7D7cnndvqkv6oYVHE4c1A0tDiwiaHY9sOLzi0MtM8y@DwmsOrg8wObwk6vPZIu/mhdbpZRxeGHF7jZXhonc3h6YfXxB7eYGDlRVXD/v8HAA) or [verify that it's a quine](https://tio.run/##yy9OTMpM/f/fQMnF2OTw8sN7Cw@3J53b6pL@qGFRxOHNQNLQ4sImh2PbDi84tDLTPMvg8JrDq4PMDm8JOrz2SLv5oXW6WUcXhhxe42V4aJ3N4emH18Qe3mBg5UVd0/7/BwA).
**Explanation:**
**[quine](/questions/tagged/quine "show questions tagged 'quine'")-part:**
The shortest [quine](/questions/tagged/quine "show questions tagged 'quine'") for 05AB1E is this one: `0"D34çý"D34çý` (**14 bytes**) [provided by *@OliverNi*](https://codegolf.stackexchange.com/a/97899/52210). My answer uses a modified version of that quine by adding at the `...` here: `0"D34çý..."D34çý...`. A short explanation of this quine:
```
0 # Push a 0 to the stack (can be any digit)
"D34çý" # Push the string "D34çý" to the stack
D # Duplicate this string
34ç # Push 34 converted to an ASCII character to the stack: '"'
ý # Join everything on the stack (the 0 and both strings) by '"'
# (output the result implicitly)
```
**Challenge part:**
Now for the challenge part of the code. As I mentioned at the top, 05AB1E has no UTF-8 conversion builtins, so I have to do these things manually. I've used this source as reference on how to do that: [*Manually converting unicode codepoints into UTF-8 and UTF-16*](https://stackoverflow.com/a/6240184/1682559). Here a short summary of that regarding the conversion of Unicode characters to Unicode†:
1. Convert the unicode characters to their unicode values (i.e. `"dЖ丽"` becomes `[100,1046,20029]`)
2. Convert these unicode values to binary (i.e. `[100,1046,20029]` becomes `["1100100","10000010110","100111000111101"]`)
3. Check in which of the following ranges the characters are:
1. `0x00000000 - 0x0000007F` (0-127): `0xxxxxxx`
2. `0x00000080 - 0x000007FF` (128-2047): `110xxxxx 10xxxxxx`
3. `0x00000800 - 0x0000FFFF` (2048-65535): `1110xxxx 10xxxxxx 10xxxxxx`
4. † `0x00010000 - 0x001FFFFF` (65536-2097151): `11110xxx 10xxxxxx 10xxxxxx 10xxxxxx`
†: Unicode is capped at 21 bits, but UTF-8 is capped at 17 bits. So the range of 4 above would instead be:
`0x00010000 - 0x0010FFFF` (65536-1114111): `10000xxx 10xxxxxx 10xxxxxx 10xxxxxx`
The character `d` will be in the first range, so 1 byte in UTF-8; character `Ж` is in the second range, so 2 bytes in UTF-8; and character `丽` is in the third range, so 3 bytes in UTF-8.
The `x` in the pattern behind it are filled with the binary of these characters, from right to left. So the `d` (`1100100`) with pattern `0xxxxxxx` becomes `01100100`; the `Ж` (`10000010110`) with pattern `110xxxxx 10xxxxxx` becomes `11010000 10010110`; and the `丽` (`100111000111101`) with pattern `1110xxxx 10xxxxxx 10xxxxxx` becomes `1110x100 10111000 10111101`, after which the remaining `x` are replaced with `0`: `11100100 10111000 10111101`.
So, that approach I also used in my code. Instead of checking the actual ranges, I just look at the length of the binary and compare it to the amount of `x` in the patterns however, since that saves a few bytes.
```
Ç # Convert each character in the string to its unicode value
b # Convert each value to binary
ε # Map over these binary strings:
Dg # Duplicate the string, and get its length
•Xó• # Push compressed integer 8657
18в # Converted to Base-18 as list: [1,8,12,17]
@ # Check for each if the length is >= to this value
# (1 if truthy; 0 if falsey)
ƶ # Multiply each by their 1-based index
à # Pop and get its maximum
© # Store it in the register (without popping)
i # If it is exactly 1 (first range):
7j # Add leading spaces to the binary to make it of length 7
0ì # And prepend a "0"
ë # Else (any of the other ranges):
R # Reverse the binary
6ô # Split it into parts of size 6
Rí # Reverse it (and each individual part) back
ć # Pop, and push the remainder and the head separated to the stack
7®- # Calculate 7 minus the value from the register
j # Add leading spaces to the head binary to make it of that length
š # Add it at the start of the remainder-list again
Tì # Prepend "10" before each part
J # Join the list together
1®<× # Repeat "1" the value from the register - 1 amount of times
ì # Prepend that at the front
] # Close both the if-else statement and map
ð0: # Replace all spaces with "0"
J # And join all modified binary strings together
# (which is output implicitly - with trailing newline)
```
[See this 05AB1E answer of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•Xó•18в` is `[1,8,12,17]`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 60 bytes
*-15 bytes from @Neil and @Shaggy*
```
f=_=>[...Buffer(`f=`+f)].map(x=>x.toString(2).padStart(8,0))
```
[Try it online!](https://tio.run/##BcHBCoMwDADQ30lwC7LTLvWwX/AoYoM2UnFNaePw77v3Dv5xXUvM9ky6hdbELW6YiOhziYQCXpzvBGf6cobbDTeZjlZi2uGFlHkbjYvB@9EjtlVT1TPQqTsIIB0ak/fY/g "JavaScript (Node.js) – Try It Online")
[Answer]
# Perl 5, 42 bytes
```
$_=q(say unpack'B*',"\$_=q($_);eval");eval
```
[TIO](https://tio.run/##K0gtyjH9/18l3rZQozixUqE0ryAxOVvdSUtdRykGLKoSr2mdWpaYowSh/v//l19QkpmfV/xf19dUz8AQAA)
[Answer]
# [Rust](https://www.rust-lang.org/), 187 bytes
```
fn f(o:u8){for c in b"go!g)n;t9(zgns!b!ho!c#%#/huds)(zhg!b_n <27zqshou )#z;19c|#-b_n(:|dmrdzg)1(:|||go!l`ho)(zg)0(:|".iter(){if c^o!=36{print!("{:08b}",c^o);}else{f(0);}}}fn main(){f(1);}
```
[Try it online!](https://tio.run/##DY7ZCsIwFAV/JWkQEnBpFbSL/opLlyzQJpq0L1m@Pd63YWAOx25uzZlrxKlpt5oFbiwakNKoL4TBgulubagX2uEeS4MHsiMnuY2OUS8F7l8a3c83/3PSbIgR31XNEMkBPG3juNjRC1YBxghr81sa6AQrwRRHtU6WsqA4Gp4GPy7X8LVKr5gWoS3rPhV78KxL0@ymwGkJmBJcXT5KQ8dpBSbnPw "Rust – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 46 bytes
```
<say "<$_>~~.EVAL".ords.fmt("%08b",'')>~~.EVAL
```
[Try it online!](https://tio.run/##K0gtyjH7/9@mOLFSQclGJd6urk7PNczRR0kvvyilWC8tt0RDSdXAIklJR11dEyb535oLrN7AwBAIDMAUiDAAcwwMocIQZAARgmJDmBKokCFUKRKFREMUwNVCINxYQwOIrcjmIznFEKEZboYhnINgwp0OETSEG41iLrJtUIOgXEM0@2H@g9sN10ypP5X0kvNzkzQsNO3s9AoSi4pTdZMSi1M1jDT1kjOKiv8DAA "Perl 6 – Try It Online")
The standard quine with `.fmt("%08b",'')` formats the list of ordinal values into length 8 binary and joins with an empty string.
[Answer]
# Java 10, ~~339~~ ~~308~~ ~~265~~ ~~227~~ ~~225~~ ~~186~~ 184 bytes
```
v->{var s="v->{var s=%c%s%1$c;return 0+new java.math.BigInteger(s.format(s,34,s).getBytes()).toString(2);}";return 0+new java.math.BigInteger(s.format(s,34,s).getBytes()).toString(2);}
```
-8 bytes thanks to *@NahuelFouilleul* removing the unnecessary `&255` (and an additional -35 for bringing to my attention that the full program specs of the challenge had been revoked and a function is allowed now as well..)
-41 bytes thanks to *@OlivierGrégoire*.
[Try it online.](https://tio.run/##rZDPasMwDMbvfQpRFrBZa7qtt9AdetthvQx2KT1orps5c5RiKR6l5NlThwb2ArsI/UOffl@NCZf18WewAZnhHT1dZwCexMUTWge7sQT4kOipAqs@W3@EpMvc7Wc5sKB4Czsg2MCQlq/XhBF4M/9LC1tw8fRgy@ikiwSrR3K/UGdl06B8m62v3rJe5aJic2pjbipevKwXrE3lZHsRx0prI@39C/Wsy37@r9eGcmQ5d18hs0xIaSRtsiHqvrg/oJ7MuLC4xrSdmHOeSCBFxirqQtCTM/1wAw)
**Explanation:**
**[quine](/questions/tagged/quine "show questions tagged 'quine'")-part:**
* `var s` contains the unformatted source code String
* `%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
**Challenge part:**
```
v->{ // Method with empty unused parameter and String return-type
var s="..."; // Unformatted source code String
return 0+ // Return, with a leading "0":
new java.math.BigInteger( // A BigInteger of:
s.format(s,34,s) // The actual source code String
.getBytes()) // Converted to a list of bytes (UTF-8 by default)
.toString(2);} // And convert this BigInteger to a binary-String
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~68~~ 67 bytes
```
_="print''.join(bin(256|ord(i))[3:]for i in'_=%r;exec _'%_)";exec _
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P95WqaAoM69EXV0vKz8zTyMJiI1MzWryi1I0MjU1o42tYtPyixQyFTLz1ONtVYusUytSkxXi1VXjNZWg7P//AQ "Python 2 – Try It Online")
A modification of [this answer](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good/51011#51011)
-1 bytes by removing the space after 'in' (thanks @mdahmoune)
[Answer]
# [R](https://www.r-project.org/), ~~138~~ 114 bytes
```
x=function(){rev(rawToBits(rev(charToRaw(sprintf("x=%s;x()",gsub("\\s","",paste(deparse(x),collapse="")))))))};x()
```
[Try it online!](https://tio.run/##JctBCsIwEEbhuwwIfyA3kGw8gnTZzRinGihJmEltoHj2SPHtvsXTMXpYthxbKhnuUPlAeZ/KLTXDqfhmncqdd1jVlNsC6uFi1w5H/mXbAzTPRp7IV7YmeEplNUF3PpZ15WoSiNy/7/mN8QM "R – Try It Online")
Uses R’s ability to deparse functions to their character representation. The `rev`s are needed because `rawToBits` puts the least significant bit first. `as.integer` is needed because otherwise the bits are displayed with a leading zero.
Edited once I realised that any convenient output was allowed. Also was out by one on original byte count.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 62 bytes
```
exec(a:="print(''.join(f'{i:08b}'for i in b'exec(a:=%r)'%a))")
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P7UiNVkj0cpWqaAoM69EQ11dLys/M08jTb0608rAIqlWPS2/SCFTITNPIUkdpla1SFNdNVFTU0nz/38A "Python 3.8 (pre-release) – Try It Online")
## How it work :
* `exec(a:="print('exec(a:=%r)'%a)")` is a quine
* `f'{i:08b}'` converts `i` into its 8-digits binary representation
* `b'example_string'` is a binary sting. When we iterate over it, it convert the characters by their unicode value
* `''.join( ... for i in ...)` iterate over a string an concatenate the char after the transformation
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 221 bytes
```
var s="var s={0}{1}{0};Write(string.Concat(string.Format(s,(char)34,s).Select(z=>Convert.ToString(z,2).PadLeft(8,'0'))));";Write(string.Concat(string.Format(s,(char)34,s).Select(z=>Convert.ToString(z,2).PadLeft(8,'0'))));
```
[Try it online!](https://tio.run/##Sy7WTS7O/P@/LLFIodhWCUJVG9RWG9YCSevwosySVI3ikqLMvHQ95/y85MQSGM8tvygXxNPRSM5ILNI0NtEp1tQLTs1JTS7RqLK1AyouSy0q0QvJDwar16jSMdLUC0hM8UlNK9Gw0FE3UNcEAmslOtjx/z8A "C# (Visual C# Interactive Compiler) – Try It Online")
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc) with flag `/u:System.String`, 193 bytes
```
var s="var s={0}{1}{0};Write(Concat(Format(s,(char)34,s).Select(z=>Convert.ToString(z,2).PadLeft(8,'0'))));";Write(Concat(Format(s,(char)34,s).Select(z=>Convert.ToString(z,2).PadLeft(8,'0'))));
```
[Try it online!](https://tio.run/##Sy7WTS7O/P@/LLFIodhWCUJVG9RWG9YCSevwosySVA3n/LzkxBINt/yiXCBVrKORnJFYpGlsolOsqRecmpOaXKJRZWsHVFWWWlSiF5IfXFKUmZeuUaVjpKkXkJjik5pWomGho26grgkE1ko0MfX//3/5BSWZ@XnF//VLrYIri0tSc/UgWgA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# Bash + GNU tools, 48 bytes
```
trap -- 'trap|xxd -b|cut -b9-64|tr -dc 01' EXIT
```
[TIO](https://tio.run/##S0oszvj/v6QosUBBV1dBHcSoqahIUdBNqkkuLQFSlrpmJjUlRQq6KckKBobqCq4RniFc//8DAA)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 45 bytes
```
eval$b=%q[puts "eval$b=%q[#$b]".unpack("B*")]
```
[Try it online!](https://tio.run/##KypNqvz/P7UsMUclyVa1MLqgtKRYQQnBV1ZJilXSK80rSEzO1lBy0lLSjP3/HwA "Ruby – Try It Online")
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 33 bytes
```
#Q/v(#Q)+]up~-' ;;\[{**b28'0lp}m[
```
[Try it online!](https://tio.run/##SyotykktLixN/f9fOVC/TEM5UFM7trSgTlddwdo6JrpaSyvJyELdIKegNjf6/38A "Burlesque – Try It Online")
```
#Q # Push remaining stack to stack (Quine)
/v # Drop input (empty string/whatever)
(#Q)+]up # #Q does not add itself. Complete quine, convert to string
~- # Remove extraneous brackets
' ;;\[ # Remove extraneous spaces
{
** # get codepoint
b2 # Convert to binary
8'0lp # Pad to 8 with 0s
}m[ # Apply to each char of quine
```
] |
[Question]
[
## Introduction:
[](https://i.stack.imgur.com/SnMxA.jpg) (Source: [Wikipedia](https://en.wikipedia.org/wiki/Rainbow))
When we look at a rainbow it will always have the colors from top to bottom:
Red; orange; yellow; green; blue; indigo; violet
If we look at these individual rings, the red ring is of course bigger than the violet ring.
In addition, it's also possible to have two or even three rainbow at the same time.
All this above combined will be used in this challenge:
## Challenge:
Given an integer `n`, output that many rings of the (possibly more than one) 'rainbows', where we'll use the letters `vibgyor` for the colors.
See the test cases below to see how they are built upwards from `n=1`, and how the spacing should be handled (at `n=8`). As you can see, one space is added between two rainbows, including spacing at the top, before we add the ring of the next rainbow in line.
## Challenge rules:
* You are allowed to use capital `VIBGYOR` instead of lowercase
* There should be a space between the individual rainbows
* Any amount of leading and/or trailing spaces/new-lines are allowed, as long as the actual rainbow (wherever it is placed on the screen) is correct
* The input will always be a positive integer (`>= 1`). The behavior when `n=0` is therefore undefined, and the program/function can do whatever it wants (outputting nothing; outputting the rainbow of `n=1`; random output; fail with an error; etc.)
* You are allowed to output a list/array of strings or 2D array/list of characters if you want (you could add the actual pretty-printing code in the TIO footer).
* *Ignore the fact that the outputs looks more like Mayan temples than rainbows.. xD*
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, 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.
* Also, adding an explanation for your answer is highly recommended.
## Test cases (first `n=1` through `n=10`, and `n=25`):
```
1:
vvv
v v
2:
iii
ivvvi
iv vi
3:
bbb
biiib
bivvvib
biv vib
4:
ggg
gbbbg
gbiiibg
gbivvvibg
gbiv vibg
5:
yyy
ygggy
ygbbbgy
ygbiiibgy
ygbivvvibgy
ygbiv vibgy
6:
ooo
oyyyo
oygggyo
oygbbbgyo
oygbiiibgyo
oygbivvvibgyo
oygbiv vibgyo
7:
rrr
rooor
royyyor
roygggyor
roygbbbgyor
roygbiiibgyor
roygbivvvibgyor
roygbiv vibgyor
8:
vvv
v v
v rrr v
v rooor v
v royyyor v
v roygggyor v
v roygbbbgyor v
v roygbiiibgyor v
v roygbivvvibgyor v
v roygbiv vibgyor v
9:
iii
ivvvi
iv vi
iv rrr vi
iv rooor vi
iv royyyor vi
iv roygggyor vi
iv roygbbbgyor vi
iv roygbiiibgyor vi
iv roygbivvvibgyor vi
iv roygbiv vibgyor vi
10:
bbb
biiib
bivvvib
biv vib
biv rrr vib
biv rooor vib
biv royyyor vib
biv roygggyor vib
biv roygbbbgyor vib
biv roygbiiibgyor vib
biv roygbivvvibgyor vib
biv roygbiv vibgyor vib
25:
ggg
gbbbg
gbiiibg
gbivvvibg
gbiv vibg
gbiv rrr vibg
gbiv rooor vibg
gbiv royyyor vibg
gbiv roygggyor vibg
gbiv roygbbbgyor vibg
gbiv roygbiiibgyor vibg
gbiv roygbivvvibgyor vibg
gbiv roygbiv vibgyor vibg
gbiv roygbiv rrr vibgyor vibg
gbiv roygbiv rooor vibgyor vibg
gbiv roygbiv royyyor vibgyor vibg
gbiv roygbiv roygggyor vibgyor vibg
gbiv roygbiv roygbbbgyor vibgyor vibg
gbiv roygbiv roygbiiibgyor vibgyor vibg
gbiv roygbiv roygbivvvibgyor vibgyor vibg
gbiv roygbiv roygbiv vibgyor vibgyor vibg
gbiv roygbiv roygbiv rrr vibgyor vibgyor vibg
gbiv roygbiv roygbiv rooor vibgyor vibgyor vibg
gbiv roygbiv roygbiv royyyor vibgyor vibgyor vibg
gbiv roygbiv roygbiv roygggyor vibgyor vibgyor vibg
gbiv roygbiv roygbiv roygbbbgyor vibgyor vibgyor vibg
gbiv roygbiv roygbiv roygbiiibgyor vibgyor vibgyor vibg
gbiv roygbiv roygbiv roygbivvvibgyor vibgyor vibgyor vibg
gbiv roygbiv roygbiv roygbiv vibgyor vibgyor vibgyor vibg
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~84~~ ~~82~~ 81 bytes
-2 bytes thanks to ElPedro.
```
n=input();n+=n/7;w=''
while-~n:w+=" vibgyor"[n%8];print' '*n+w+w[-1]+w[::-1];n-=1
```
[Try it online!](https://tio.run/##DcXRCkAwFAbge08hpWEtTYm2zpMsN0qs9FsaJzdefdx8X3jidqBLCeQRrljVFpLQDpZJiIw3vy/qhWFJRX77eX2Os3Aox8mG0yOKXDSQLNkpPf0a82@hSKek@w8 "Python 2 – Try It Online")
[Answer]
# [Dyalog APL](https://www.dyalog.com/), ~~41~~ ~~39~~ 38 bytes
```
↑{⌽(⌽,⊃,A↑⊢)⍵↑A⍴' vibgyor'}¨-⍳A←⌈⎕×8÷7
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@oo10h7f@jtonVj3r2agCxzqOuZh1HoMCjrkWaj3q3AlmOj3q3qCuUZSalV@YXqdceWqH7qHczUMmERz0dj/qmHp5ucXi7Ocik/2lcRqYA "Dyalog APL – Try It Online")
A similar approach to others: `A←⌈⎕×8÷7` finds the height of the rainbow (also the width of the longest 'half row' to the left/right of the centre) and assigns it to `A` for later use, while `¨-⍳` iterates through the values 1..A, negating them to select on the correct side when used with `↑`.
`A⍴' vibgyor'` generates a 'half row' and `⍵↑` selects the correct length substring. `(⌽,⊃,A↑⊢)` generates the full row in reverse (which takes fewer characters to do), starting with a reversed half row (`⌽`), then the centre character taken from the beginning of the half row string (`⊃`) and finally a right padded version of the half row (`A↑⊢`). The final `⌽` reverses the row into the correct orientation and `↑` turns the vector of rows into a 2D array.
**Edit:** -2 thanks to [dzaima](https://codegolf.stackexchange.com/users/59183/dzaima)
**Edit:** -1 thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn)
[Answer]
# JavaScript (ES6), 100 bytes
Returns an array of strings.
```
f=(n,a=[i=' '])=>++i<n+n/7?f(n,[c=' vibgyor'[i&7],...a].map(s=>c+s+c)):a.map(s=>' '.repeat(--i)+s)
```
[Try it online!](https://tio.run/##XY69asMwFIX3PMWdenW5ltqkQ6C1kqlrX8D1oMiykXGujBUCpfTZXXnI0uk7nB84o7u77Jc437SkLqxrb5VUzjbRIgBgS/bEHGtheT6e@5I1viT3eBm@04JNfDq2lTHGtebqZpXtyXNmT/TmHgYCmiXMwd2U1pE409qnRQlY2L@DQF34sglmgp8dgE@S0xTMlAalUOsGPksXgbdOYYtkZtd9SKdeDxWgRqJ/s3KUzJiiKPwSpG22cfe7/gE "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~32~~ ~~31~~ 23 bytes
```
.•VvÈ©•¹∍¬„ v:Rηε¬ý}.c
```
[Try it online!](https://tio.run/##ATMAzP8wNWFiMWX//y7igKJWdsOIwqnigKLCueKIjcKs4oCeIHY6Us63zrXDgsKsw719LmP//zg "05AB1E – Try It Online")
-1 thanks to Kevin Cruijssen and -8 thanks to Adnan
---
**Explanation (Stack example w/ input of 3):**
```
.•VvÈ©• # Push 'aibgyor' | ['aibgyor']
¹∍ # Extend to input length. | ['aib']
¬ # Push head. | ['aib','a']
„ v: # Replace with ' v'. | [' vib']
R # Reverse. | ['biv ']
η # Prefixes. | ['b', 'bi', 'biv', 'biv ']
ε } # For each.... | []
¬ý # Bifurcate, join by head. | ['b','b'] -> ['bbb']
| ['bi','ib'] -> ['biiib']
| ['biv','vib'] -> ['bivvvib']
| ['biv ',' vib'] -> ['biv vib']
.c # Center the result. | Expected output.
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~29~~ ~~28~~ 26 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
7÷U+{ <ibgyor@¹×/n}⇵K2*∔─↶
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjE3JUY3JXVGRjM1JXVGRjBCJXVGRjVCJTIwJTNDaWJneW9yJXVGRjIwJUI5JUQ3JXVGRjBGJXVGRjRFJXVGRjVEJXUyMUY1JXVGRjJCJXVGRjEyJXVGRjBBJXUyMjE0JXUyNTAwJXUyMUI2,i=MTA_,v=6)
Explanation:
```
7÷U+ ceil(input/7) + input
{ } for n in 1..the above
<ibgyor@ in the string " <ibgyor", pick the nth character
¹× repeat n times
/ create a diagonal of that
n and overlap the top 2 stack items (the 1st time around this does nothing, leaving an item for the next iterations)
⇵ reverse the result vertically
K take off the last line (e.g. " <ibgyor <ib")
2* repeat that vertically twice
∔ and append that back to the diagonals
─ palindromize vertically
↶ and rotate 90° anti-clockwise. This rotates "<" to "v"
```
~~25~~ ~~24~~ [22 bytes](https://dzaima.github.io/Canvas/?u=JXVGRjE3JUY3JXVGRjM1JXVGRjBCJTIwdmliZ3lvciV1RkY0RCVCMSV1RkYzQiV1RkYyQiV1RkYxMiVENyV1RkYwQiV1RkYzRCV1RkYwRiV1MjUwMg__,i=MTA_,v=6) after fixing that mold should cycle if the wanted length is bigger than the inputs length and fixing `/` for like the 10th time
[Answer]
# [Haskell](https://www.haskell.org/), ~~114~~ ~~110~~ 101 bytes
Thanks to [nimi][1] for -~~4~~ 13 bytes!
```
f n=""#(n+1+div n 7)
w#0=[]
w#n|x<-cycle"r vibgyo"!!n=((' '<$[2..n])++reverse w++x:x:x:w):(x:w)#(n-1)
```
[Try it online!](https://tio.run/##FYyxDoIwFAB3v@JRSGjTQMTFSOgf6ORIGCoWbCxPUrCFxH@vkEvutnvJ6a2MCaEDFITEFHnBn9oBwpkdfHwUdbMFf0uVtWtrFLHg9KNfPySKUFCaQlol9SnPsWGcW@WUnRR4zpdyx7OS7t7GWcHCIDWCgEGONxi/8322V4QEOriEPw "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 108 bytes
```
n=input()-1
n+=n/7+2
o=[]
for s in(' vibgyor'*n)[:n]:o=[s+l+s for l in[s]+o]
for l in o:print l.center(n-~n)
```
[Try it online!](https://tio.run/##JYtBCsIwFAX3OcXfNfFTtd0IgZwkZKNUDYT3Q5IK3Xj12OJymJm8tbdg7h0uIq9Nm3FSYIfLjWclzgf1lEKVIvRAn3h/bVKGE4y3CHb3lRNXOpq0N74Glv9yIInNJaJROj8WtKVojF@Y3qfrDw "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
↶≔… vibgyor⁺²÷×⁸⊖N⁷θθ⸿Eθ✂θκ‖O←
```
[Try it online!](https://tio.run/##RY49D4IwFEV3f0XT6TWpi4tEJoMLiR9EHV2gPKCxtNCWJvz6Cg663Jybk9xc0ZVWmFLFWMhg/BkbDyzdHJ2TrYZsFgqzzgxASZBVOxtLOSnU5GDHSa79SQZZIzxljw4STk4oLPaoPdaQ62Hy16mv0AJjjJP9N8dlvrBSe/gTfVn6K5dygJGTh5ICV3izRd2xUSj8LaBViz@sR1kaYxK3QX0A "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
↶
```
Change the drawing direction to upwards.
```
≔… vibgyor⁺²÷×⁸⊖N⁷θ
```
Calculate the height of the rainbow and repeat the literal string to that length.
```
θ⸿
```
Print the central line of the rainbow.
```
Eθ✂θκ
```
Print the right half of the rainbow by taking successive slices and printing each on its own "line".
```
‖O←
```
Reflect to complete the rainbow.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 31 bytes
```
:7+‘µ“ vibgyor”ṁṚ,Ṛjṛ/ƲƤṭ"ḶṚ⁶ẋƲ
```
[Try it online!](https://tio.run/##AUkAtv9qZWxsef//Ojcr4oCYwrXigJwgdmliZ3lvcuKAneG5geG5mizhuZpq4bmbL8ayxqThua0i4bi24bma4oG24bqLxrL/w4dZ//84 "Jelly – Try It Online")
[Check out a test suite!](https://tio.run/##y0rNyan8/9/KXPtRw4xDWx81zFEoy0xKr8wvetQw9@HOxoc7Z@kAcdbDnbP1j206tuThzrVKD3dsAwo9atz2cFf3sU3/DQ2CrI1MD7c/aloTCcRZQDMObYNAoBn//1sAAA "Jelly – Try It Online")
**ಠ\_ಠ** This is overly complicated because Jelly doesn't have a centralize function...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
:7+‘“ vibgyor”ṁµṫJZz⁶U;"⁸ŒBṚ
```
A monadic link accepting an integer which yields a list of lists of characters.
**[Try it online!](https://tio.run/##ATwAw/9qZWxsef//Ojcr4oCY4oCcIHZpYmd5b3LigJ3huYHCteG5q0paeuKBtlU7IuKBuMWSQuG5mv/Dh1n//zg "Jelly – Try It Online")** (footer joins with newline characters)
Or see the [test-suite](https://tio.run/##AWwAk/9qZWxsef//Ojcr4oCY4oCcIHZpYmd5b3LigJ3huYHCteG5q0paeuKBtlU7IuKBuMWSQuG5mv/FvMOHWSTigqxq4oKs4oG@OsK2auKBvsK2wrb//1sxLDIsMyw0LDUsNiw3LDgsOSwxMCwyNV0 "Jelly – Try It Online").
### How?
```
:7+‘“ vibgyor”ṁµṫJZz⁶U;"⁸ŒBṚ - Link: integer
:7 - integer divide by seven (number of full rainbows)
‘ - increment (the input integer)
+ - add (gets the number bands)
“ vibgyor” - list of characters = " vibgyor"
ṁ - mould like the result above (as a range)
µ - start a new monadic chain
J - range of length
ṫ - tail (vectorises) (gets the suffixes)
Z - transpose
z⁶ - transpose with filler space character
- (together these pad with spaces to the right)
U - reverse each
- (now we have the left side of the rainbow upside down)
⁸ - chain's left argument, as right argument of...
" - zip with:
; - concatenation
- (adds the central character)
ŒB - bounce (vectorises at depth 1)
- (reflects each row like [1,2,3,4] -> [1,2,3,4,3,2,1])
Ṛ - reverse (turn the rainbow up the right way)
```
[Answer]
# [R](https://www.r-project.org/), 130 bytes
```
function(n,k=n%/%7*8+1+n%%7,a=el(strsplit(' vibgyor'/k,'')))for(i in k:1)cat(d<-' '/(i-1),a[c(k:i,i,i:k)],d,sep='','
')
"/"=strrep
```
[Try it online!](https://tio.run/##PczLCsIwEIXhfZ8iCGFm7JQYQSrBPIm6qL1ISElLGgURn73GjZzFD2fxxXWw6/AIbXJTwMDeBqlkvT2WugxS1tzYfsQlxWUeXUIQT3e7v6YIyjMAEQ1TRCdcEN5oapuE3akCAQpdpYmbc4veOM4znq7c8dLPFoChACo2amMzHft5/TMtaqN3vD8QvQshfiJcAmQBTC7lb0BHxWf9Ag "R – Try It Online")
* -6 bytes thanks to @JayCe
[Answer]
# [Haskell](https://www.haskell.org/), 106 ~~113~~ bytes
I can't yet comment other posts (namely [this](https://codegolf.stackexchange.com/a/170646/82142)) so I have to post the solution as a separate answer.
Golfed away 7 bytes by ovs
```
p x=reverse x++x!!0:x
u m|n<-m+div(m-1)7=[(' '<$[z..n])++p(drop(n-z)$take(n+1)$cycle" vibgyor")|z<-[0..n]]
```
[Try it online!](https://tio.run/##FcvBCoMgGADg@57iL4QUMeo0NvQNttOO0sGVbFGamIVJ7@7Yd/@@ap30POfsIAqvd@1XDZHSWBTNPV42MKflzNBh3LFhLbkKiSuoOJKprm1HKHV48IvDliWCgpo0trQlqD/6WZewj@/PsfiSnIkz2fxLl40aLQgwyj3BbeEV/MMCgg1u@Qc "Haskell – Try It Online")
([Old version](https://tio.run/##DctLCoMwEADQq0wkCyUouiptzA3aVZfiImpsxTiG8UOU3j11@@B99TIaa0PoAdXGUXTDHmNaJDepWaNWPRrQvD1aa6CRpMjshhYjHXhF4IXwjOUPL7erU3WyCCIhXNzR7ODkMYoiuWwfms8xU5T8zjKt8izDug6THhAUTNq9wG3re6UnAoce7uEP "Haskell – Try It Online"), 113 bytes)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~108~~ ~~98~~ ~~89~~ 85 bytes
```
param($x)($x+=$x/7-replace'\..*')..0|%{' '*$_+-join(" vibgyor"*$x)[$x..$_+$_+$_..$x]}
```
[Try it online!](https://tio.run/##HYvhCsIgFEb/7ynkcsvNsVv7FTT2JBVm4drCUgzKWD67WXA@OPBxnH1p/xi1MQmHfk5OeXUrMVR5dY9htWm8dkadNd8TCV4RrT@LmTMuUNbN1U73EthzOl3e1oPI4Q4DUf7@ZAuHmGJRtETtrwSUxy10SxwYyg4gpi8 "PowerShell – Try It Online")
This one feels pretty alright now. Banker's rounding is still the devil and I figured out how to make a non-dumb join. I tried monkeying with $ofs to not much success. Speaking of, the results without joins look pretty good, a bit melty:
```
vvv
v v
v rrr v
v r ooo r v
v r o yyy o r v
v r o y ggg y o r v
v r o y g bbb g y o r v
v r o y g b iii b g y o r v
v r o y g b i vvv i b g y o r v
v r o y g b i v v i b g y o r v
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~132~~ 131 bytes
```
def f(n):
t=n+n/7;s=('vibgyor '*n)[:t];r=[s[~i:]+t*' 'for i in range(t)]
for l in zip(*r+3*[' '+s]+r[::-1])[::-1]:print''.join(l)
```
[Try it online!](https://tio.run/##RY7NCsIwEITvfYq9bX78az0UUvokIQfFtq6UTUiDUA@@emz04Glg5pthwprunpucb8MIo2BpKkg9az623dILfNJ1Wn0EVCytSa6LvV3sm4zTSSHguGUExBAvPA0iSVdB8ebivSgIFfVZ2Y3Ui9PRGrOvnfyJCZE4IR4enljMMpci/8fqXXMqf8qtCr5w/gA "Python 2 – Try It Online")
---
Saved:
* -1 byte, thanks to Jonathan Frech
[Answer]
# [Red](http://www.red-lang.org), 153 bytes
```
func[n][r: take/last/part append/dup copy"""roygbiv "n l: 9 * n + 8 / 8
repeat i l[print rejoin[t: pad/left take/part copy r i l last t reverse copy t]]]
```
[Try it online!](https://tio.run/##nY1BDoIwFET3nGLSpcZUTEiwx3DbdFHpr0Gb0nw@JJweg5xAZjvz3jCF9UHBuiqaNU65s9lZNhD/IZ38KLp4FvhSKAcdpoJuKItSiofl9exnqIxkcMcJGWe00GgrpkJe0CPZwn0WML2HPlsxKD7oRFH2g597E4K3NbZDbPOZeKS9EefcGlFXu0pd/oiqIpqjYH09St6a9Qs "Red – Try It Online")
## Slightly more readable:
```
f: func[ n ] [
r: copy ""
append/dup r "roygbiv " n
r: take/last/part r l: 9 * n + 8 / 8
repeat i l [
print rejoin [ t: pad/left take/part copy r i l
last t
reverse copy t ]
]
]
```
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 184 bytes
```
n->{int h=n+n/7,i=h+1,w=i*2+1,j,k=0;var o=new char[i][w];for(;i-->0;o[i][w/2]=o[i][w/2+1])for(j=w/2;j-->0;)o[i][j]=o[i][w+~j]=i<h?j<1?32:o[i+1][j-1]:" vibgyor".charAt(k++%8);return o;}
```
[Try it online!](https://tio.run/##dVDLboJAFN37FTcmTcARFLto4zCabpp00ZVLwmJEkTviDBkG1Bj663RAbDft6j7OOfdxBK@5J3bHFk@F0gaErf3KYO6nlUwMKulP6KiotjkmkOS8LOGTo4TbCGDoloYbG2qFOzhZzNkYjfIQxcD1oXR7KsCHNO/DxDDJuI7iKF5BCqyV3uqG0kDGJJGzlymyjATTM8PJwkYxPbI5rbkGxeT@DL0W4@gc01Rph6LnreZU9a3ZImaPjASx2xEEswUVPcvtQfEgkS@bYpitRRisnxdL27WqSHhBvBxDjdvDVemx3218M86RkKdXl@q9qbQERZuW9o91S7rzERjMKSAhEEJgs8fnAJtrafYnX1XGL6w1JpcOunQAO/3dELgsIfV5UeRXi//K/xzQeXE32rm4P8Oa/zcOnI7RjJr2Gw "Java (JDK 10) – Try It Online")
Prints an extra leading and trailing space for each multiple of 7.
## Explanation
```
n->{ // IntFunction
int h=n+n/7, // Declare that height = n + n/7
i=h+1, // that index = h + 1
w=i*2+1, // that width = (h+1)*2+1
j, // j
k=0; // that k = 0
var o=new char[i][w]; // Declare a 2D char array
for(; // Loop
i-->0; // Until i is 0
o[i][w/2]=o[i][w/2+1] // After each run, copy the middle letter.
)
for(j=w/2; // Loop on j = w/2
j-->0; // Until j = 0
) //
o[i][j] // copy letters to the left side,
=o[i][w+~j] // and the right side
=i<h // if it's not the last line
?j<1 // if it's the first (and last) character
?32 // set it to a space.
:o[i+1][j-1] // else set it to the previous character on the next line.
:" vibgyor".charAt(k++%8); // else assign the next letter.
return o; // return everything
}
```
## Credits
* -2 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 23 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
⌡G'5h!M╩EV[Ez ▼>≈<S⌡⌡0`
```
[Run and debug it](https://staxlang.xyz/#p=f547273568214dca45565b457a201f3ef73c53f5f53060&i=1%0A2%0A3%0A10%0A25&a=1&m=2)
Unpacked, ungolfed, and commented, it looks like this.
```
" vibgyor" string literal
,8*7/^ input * 8 / 7 + 1
:m repeat literal to that length
|] get all prefixes
Mr rectangularize, transpose array of arrays, then reverse
this is the same as rotating counter-clockwise
m map over each row with the rest of the program, then implicitly output
the stack starts with just the row itself
_h push the first character of the row
_r push the reversed row
L wrap the entire stack in a single array
```
[Run this one](https://staxlang.xyz/#c=%22+vibgyor%22%09string+literal%0A,8*7%2F%5E++++++++%09input+*+8+%2F+7+%2B+1%0A%3Am++++++++%09repeat+literal+to+that+length%0A%7C]++++++++%09get+all+prefixes%0AMr++++++++%09rectangularize,+transpose+array+of+arrays,+then+reverse%0A++++++++++%09this+is+the+same+as+rotating+counter-clockwise%0Am+++++++++%09map+over+each+row+with+the+rest+of+the+program,+then+implicitly+output%0A++++++++++%09the+stack+starts+with+just+the+row+itself%0A++_h++++++%09push+the+first+character+of+the+row%0A++_r++++++%09push+the+reversed+row%0A++L+++++++%09wrap+the+entire+stack+in+a+single+array&i=1%0A2%0A3%0A10%0A25&a=1&m=2)
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 105 bytes
```
"aDiaibgyor<esc>0vg_y$@ap0l@alhd$:s/a/ v/g
qqYP0xjYP!!rev
gJkhq2@a@qylpp02ld$0VG:center<c-r>=2*(<c-r>a+ceil(1+<c-r>a/7))
```
[Try it online!](https://tio.run/##K/v/XynRJTMxMym9Mr/IJrU42c6gLD2@UsUhscAgxyExJyNFxapYP1FfoUw/nauwMDLAoCIrMkBRsSi1jCvdKzuj0Mgh0aGwMqegwMAoJ0XFIMzdKjk1ryS1yCZZt8jO1khLA8xI1E5OzczRMNSG8PTNNTW5/v83Mv2vWwYA "V (vim) – Try It Online")
There's many possible saves here, but for now I'm just happy I got it working.
] |
[Question]
[
The task in this challenge is to put elements of an array into time bins. The input will be a non-decreasing array of positive integers representing the time of events, and an integer which represents the size of each bin. Let us start with an example. We call the input array `A` and the output array `O`.
```
`A = [1,1,1,2,7,10]` and `bin_size = 2`.
`O = [4,0,0,1,1]`.
```
**Why**? With a `bin_size = 2`, we'll have the following intervals: `(0,2], (2,4], (4,6], (6,8], (8,10]`, where four items `(1,1,1,2)` are within the first interval `(0,2]`, none in the second and third intervals, one `7` in the interval `(6,8]`, and one `10` in the interval `(8,10]`.
Your code should consider every interval of length `bin_size` starting from `0` and count how many numbers in `A` there are in each. You should always include the right hand end of an interval in a bin so in the example above `2` is included in the count of `4`. Your code should run in linear time in the sum of the lengths of the input and output.
More examples:
```
`A = [1,2,7,12,15]` and `bin_size = 5`.
`O = [2, 1, 2]`.
`A = [1,2,7,12,15]` and `bin_size = 3`.
`O = [2,0,1,1,1]`.
```
You can assume that input and output can be given in any format you find convenient. You can use any languages and libraries you like.
[Answer]
# [R](https://www.r-project.org/), 48 bytes
```
function(n,s)table(cut(n,0:ceiling(max(n)/s)*s))
```
[Try it online!](https://tio.run/##DcdRCoAgDADQq/S5xaIUJIguY0NDsAVNoduv3t97LA/7ZLkLt3ILCCm2eNQE3Nu/ZeNUapETrviC4Kw4KqJlYHDkaSXnyQWkgPYB "R – Try It Online")
Once again, `table` and `cut`ting to a `factor` do the trick for the binning. Outputs a named `vector` where the `names` are the intervals, in interval notation, for instance, `(0,5]`.
EDIT: Revert back to earlier version that works when `s` doesn't divide `n`.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 36 bytes
```
@(A,b)histc(A,1:b:A(end)+b)(1:end-1)
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bw1EnSTMjs7gkGcgytEqyctRIzUvR1E7S1DC0ArJ0DTX/p2lEG@qAoJGOuY6hQayOkSYXWAzMN9IxNI3VUTDFImas@R8A "Octave – Try It Online")
Out hunting Easter eggs and making a bonfire. I'll add an explanation when I have the time.
[Answer]
# [Perl 5](https://www.perl.org/) `-a` `-i`, ~~32~~ 28 bytes
Give count after the -i option. Give each input element on a separate line on STDIN
```
$G[~-$_/$^I]--}{say-$_ for@G
```
[Try it online!](https://tio.run/##K0gtyjH9/1/FPbpOVyVeXyXOM1ZXt7a6OLESyFVIyy9ycP//35ALBI24zLkMDf7lF5Rk5ucV/9dN/K/ra6pnaKBn@F830wgA "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
I,s=input()
B=[0]*(~-I[-1]/s+1)
for i in I:B[~-i/s]+=1
print B
```
[Try it online!](https://tio.run/##BcGhDoAgEADQzlcQRY7hYdC5UWh8A6M6rwADDBZ@Hd8rX39yMnN6aJZSefsimLNhi@sylA8Ko24SBbtz5cQpcX@5MBTpFqVFViqlzt2cAcHAAWgAzwj7Dw "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes
```
θs/Å0¹vDyI/î<©è>®ǝ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3I5i/cOtBod2lrlUeuofXmdzaOXhFXaH1h2f@/9/tKEOCBrpmOsYGsRyGQEA "05AB1E – Try It Online")
[Answer]
# APL+WIN, 23 bytes
Prompts for screen input of bins then vector of integers:
```
+⌿<\v∘.≤b×⍳⌈⌈/(v←⎕)÷b←⎕
```
Explanation:
```
⎕ Prompt for input
⌈⌈/(v←⎕)÷b←⎕ divide the integers by bin size, take maximum and round up for number of bins
b×⍳ take number of bins from previous step and create a vector of bin upper boundaries
v∘.≤ apply outer product to generate boolean matrix where elements of vector ≤ boundaries
<\ switch off all 1's after first 1 in each row to filter multiple bin allocations
+⌿ sum columns for the result
```
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~90~~ 83 bytes
```
auto f(auto i,int s){typeof i j;for(auto v:i)--v/=s,j.resize(v+1),j[v]++;return j;}
```
[Try it online!](https://tio.run/##VU7LioMwFF2br7jYjamxg4UyoNYf6XQR0ti50iaSF7TitzuxFoauzuG8OGIYiqsQ8waVuPmLhAa1dUbye0v@tSCF06aduXcauuwFyFA5sHR0j0HqDhD6utNmNUOFtCjC19GyfmekxafMQl5S1p/COc9rI503KjameVm5c1TZQri5CgbilxvYRh5OZwojSay7VNV6oomxFlAN3sERxpLBnsE3gzJCeZhqksQT8H7Bb15W8fArzuBAKUnWMaFjv2nWyEJSSGvy6aU/KmrT/Ac "C++ (gcc) – Try It Online")
[Answer]
# Java 8, 75 bytes
```
a->b->{var r=new int[~-a[a.length-1]/b+1];for(int i:a)r[~-i/b]++;return r;}
```
Port of [@DeadPossum's Python 2 answer](https://codegolf.stackexchange.com/a/160826/52210), so make sure to upvote his answer!
**Explanation:**
[Try it online.](https://tio.run/##tY/BToQwEIbv@xRzhFC6gtkYxSXxYuLB0x5JDwPbxWK3kDJgCMFXxy6uejDxtKZzaPL/8@WbCnsMq/3rXGhsW3hGZcYVQEtIqoDKpbwjpfmhMwWp2vDH8@deGcoE@7PyZEiW0jJYumkKBWxnDNM8TMceLditkW9L@B5ihlxLU9JLGIl1HkQiOdTWcyGoO/Stq6h1LoIgsZI6a8Am05w4VTdNl2tne5bua7WHozvE25FVpswEoH86CmA3tCSPvO6INy4ibbwf/wdrcWg51Z9rXsGxafTgfTmKMWKnF7MbFl1N/jmOfd9PLkNfyDGLNt/wzX/Cry8Pv/0Fn1bT/AE)
```
a->b->{ // Method with integer-array and integer parameters and no return-type
var r=new int[~-a[a.length-1]/b+1];
// Result integer-array of size `((last_item-1)/bin_length)+1`
for(int i:a) // Loop over the input-array
r[~-i/b]++; // Increase the value at index `(i+1)/bin_length` by 1
return r;} // Return the result-array
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 60 bytes
```
->a,b{(b...a[-1]+b).step(b).map{|i|a.count{|n|n<=i&&n>i-b}}}
```
[Try it online!](https://tio.run/##ZYixDsIgFAB/hbRJU/VBBNO4CD9C3gBNGxlEYmEwwLejdTU3XO5eyb7bKhtVBmweLWPMaMrxZA9si0sYv36YkIsrhs3P5GMuvvibdMPglaO21tq01hx2BFyBnxEEAtnfrwXwCWH6XxdEtpj5TnKJhYQUN9L1OVYiFenzqo8Ra1fbBw "Ruby – Try It Online")
[Answer]
# JavaScript (ES6), 60 bytes / O(len(a)+max(a)/n)
*Saved 5 bytes thanks to @Neil*
Takes input in currying syntax `(a)(n)`.
```
a=>n=>[...a.map(x=>o[x=~-x/n|0]=-~o[x],o=[])&&o].map(n=>~~n)
```
[Try it online!](https://tio.run/##hczBCsIwEATQux9SsrCNSUrxtPmRkEOorSg1W1qRHCS/HlOvCjKngTdzC8@wDet1ebSRz2OZqASykayTUgZ5D4tIZNklym06xpfy1OZaPTI5D03D/oPqIucIZeC48TzKmS9iEk7jHoMdauVBGIDDlzB4Qm1Q9xX0/0D3A6j9WiuA8gY "JavaScript (Node.js) – Try It Online")
Or just **[43 bytes](https://tio.run/##hcxBCoMwEIXhfQ8iGZhoJiJdTS4SsghWS4vNiJaShfTqqa5bKG/1w8e7x1dc@@U2P3WSy1BGLpFdYhfrR5xVZic@s9a5SZsJrN97BhT2AapKSi9plWmoJ7mqUXnCYxZbJBNAWYDTl7B4RrJI3Q66f6D9AcxxTQagfAA) / O(len(a))** if empty elements are allowed.
[Answer]
# [Haskell](https://www.haskell.org/), ~~63~~ ~~75~~ 70 bytes
```
l!n=l#[n,2*n..]
[]#_=[]
l#(b:i)|h<-length$takeWhile(<=b)l=h:drop h l#i
```
Whoops, this shorter one isn't linear but quadratic;
```
l!n=l#[n,2*n..]
[]#_=[]
l#(b:i)=sum[1|a<-l,a<=b]:[a|a<-l,a>b]#i
```
[Try it online!](https://tio.run/##BcHBCoMwDADQu18RqQcdUWhBBmK@Y4dSRmVlKWaZuB737/U9jr89idQqrZIYr@huOk2h8cE8yYdGTL8tefjzOkrSd@GuxD09OEvqV9oGIV5e5/cABjG5fmJWIDjOrAU68BYd3tE6tHNo53oB "Haskell – Try It Online")
[Answer]
# Pyth, ~~23~~ 22 bytes
```
Jm/tdeQhQK*]ZheJhXRK1J
```
[Try it here](http://pyth.herokuapp.com/?code=Jm%2FtdeQhQK%2a%5DZheJhXRK1J&input=%5B1%2C1%2C1%2C2%2C7%2C10%5D%2C+2&debug=0)
```
Jm/tdeQhQK*]ZheJhXRK1J
Jm/tdeQhQ Find the bin for each time and save them as J.
K*]ZheJ Create empty bins.
XRK1J Increment the bins for each time within them.
h Take the first (because mapping returned copies).
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~53~~ 50 bytes
Edit: -3 bytes by iamnotmaynard.
```
->a,b{(0..~-a.max/b).map{|i|a.count{|x|~-x/b==i}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6law0BPr043US83sUI/SRNIFVTXZNYk6iXnl@aVVNdU1NTpAiVsbTNra2v/FyikRUcb6oCgkY65jqFBrI5RLBcWUWO4KFjESMfQNFbHFJugCTZB49j/AA "Ruby – Try It Online")
[Answer]
This puzzle is essentially a Count-sort. We don't know the length of output without going through input first.
# [C (clang)](http://clang.llvm.org/), 53 bytes
```
i,j;f(*A,l,b,*O){for(j=0;j<l;O[(A[j++]+b-1)/b-1]++);}
```
[Try it online!](https://tio.run/##jVJtitswEP0dnWLwEpBspfFHQ6HabfEJfACvKf6QtwqOvdgOpA05ezqjjTfG7EIlsDWaNzNv3qjclE3evlwfTFs2x0o/DmNlui@/f7DZTW/aF7q6GrlXNXdj2chCuok4113P90@@2j82Kkl5nO49L/OKTSC2@Mk8T6jL9aHStWk15H2f/2l0y08C@GD@6q7G43Y6pX4mBGOvWG20UI4HcE8S6N8IODOwRwNP4Cs0LLTmTuoIMomMAoNUwGBlvLlD1tV6cCScUpNJgmyCn450vjsZhV4Y27pQdi22eixHeM37/KBH3UPddwcY9TBuynzQA7hbNnVT5k1T81gWSAwWa7V6ZsQ0SXd@hmzPvryozzCoiG1oReuZTYxjvERy8FHumUaxvOsaixl@ngvytoLCtL9Ia8y7rgASyi@hmEIQXi@yoVdCItRqUTOZoRIx@Y/jwJ2PGBMXBKDKtuFDblpO0yQjDlIrUCBph/KbDHyUilxFgI5QvcHCCWYhoQx2JKiFhejY3WDR57AIHZFi7Da3AJsLcPY3M0QzvJsRmhGajPV6PPYtvTfiv3UZzSWd082W6oZW2/Sr9HEjLpti3kllsIzZvcUgDSQW/k9ENEXYGlQFH@f1Hw "C (clang) – Try It Online")
This solution takes following parameters:
`A` input array
`l` length of A
`b` bin\_size
`O` storage for Output. Must be sufficient length
and returns output in O.
This solution has a handicap: it doesn't return the length of output array O, and so caller doesn't know how much to print.
Following version overcomes that handicap:
# [C (clang)](http://clang.llvm.org/), 79 bytes
```
i,j,k;f(*A,l,b,*O,*m){for(k=j=0;j<l;O[i=(A[j++]+b-1)/b-1]++,k=k>i?k:i);*m=++k;}
```
[Try it online!](https://tio.run/##jVJtbqNADP2dOYVFlRUDzoaPRit1SitOkANQtOKznUBIBUTKbpSzZ20amgi10s5IYI@fPc/Pky2yOmlez3e6yep9Xjx2fa53P9@exM1Jq5tXPjpr3GClStMKscYUrTVaW3ksd61ZBZvAUZvHWq0jHZhhtLHt2E4XrlzSJ7ZtrILqST9XD1oqaxvYdqVO57u8KHVTQNK2yZ@6aMyDBLPTf4tdSeZytCInllKId@LRD1CTDLAOCPyvJRwFDKaGABxFzgAtTSMyJLvMUIEmdqBtW9LJFTLP552BcIh0jAxZuM8GGg9GzKknIZYWZLuGRNhnPbwnbbIt@qKFst1toS@6fpElXdGBtRRjN1lS16UZYkrEYLJmsxfBTNfRyomJ7dHBk/oOQ4oMDc14vYiRcUiHRA6@qn2jUYhXXUN5g7@tBUmTQ6qb36w11Z3nAGuuj5COKQQvJ9UoirBG@MEcpZpNrqbIZ4Aj@74zja8oMxkCkMxDx9tENyaPk53QjQaFXOTt4S90HdKKQ6lLAU99wLwRNkA8dFes6ADzKLC6wPzvYT4FfCXEZXAudefS8C@uR653dX1yfXKFaIt@3zb84Jj/0hI8mOiWbjyV1xvEje7RoU24eMz5JBXDNGf1kUM0iJj3Pxn@mDHcwbfQ6zz/Aw "C (clang) – Try It Online")
It takes an additional parameter `m` and returns length of `O` in it. It cost me 26 bytes.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~102~~ ~~90~~ ~~89~~ 86 bytes
```
#define P!printf("%d ",k)
i,j,k;f(s){for(i=s;~scanf("%d",&j);k++)for(;j>i;i+=s)k=P;P;}
```
[Try it online!](https://tio.run/##HYxBDoIwEEXXcooRo@lIXZSEuJjgGdgbFk2hODQW0xI3BK9eld3Pey/fXAZjUjp0vWXfQ7N/BfazFfmxg1w6zFiO0pEVERc7BcF1pE802m9JLk8jkisK/Dsab0xc1BFd3VBDa3pq9uL3BzoMRoJ56ADn337fW4Ql21mh54nFRlSLSNmaFJRwBVWCqlL1BQ "C (gcc) – Try It Online")
Thanks to Kevin Cruijssen for slashing off 12 bytes, and ceilingcat for another 4 bytes!
] |
[Question]
[
Given the following Python 3 script:
```
def greet():
print("Hello, world!")
greet()
```
***Prepend*** some lines to this text file so that it can be both executed as a Python program as well as compiled and run as a C++ program producing the same output **Hello, world!** (including the newline at the end):
```
$ python3 bilingual.py.cpp
Hello, world!
$ g++ bilingual.py.cpp && ./a.out
Hello, world!
```
The solution will be scored by the count of non-whitespace characters of the entire program, including the Python script:
```
sed 's/\s//g' bilingual.py.cpp|wc -c
```
[Answer]
# Score 116
Prepend:
```
#include<cstdio>
#define print(A)main(){puts(A);}
#define greet()
#define \
```
The preprocessor backslash `\` pulls the nasty `:` containing line into an unused macro. Try it [here](http://ideone.com/eFDNtU).
Thanks to [edc65's answer](https://codegolf.stackexchange.com/a/98660/46756) for the note about implicit int in C++4.
Thanks to [PieCot's answer](https://codegolf.stackexchange.com/a/98664/46756) for suggesting `<cstdio>` over `<stdio.h>`.
Thanks to [Leon](https://codegolf.stackexchange.com/users/61709/leon) for suggest I remove the `X` in the original `#define X\`.
[Answer]
# Score 119
(Thx @Linus for the byte count)
(1 byte saved thx @Conor O'Brien)
(1 byte saved thx @PieCot)
~~Counting bytes again by hand, I found 113. Maybe it's right this time.~~ No it's not
```
#include <cstdio>
#define def main(){0?
#define print(x) puts(x);}
#define greet()
```
Notes: stdio and puts are still alive and kicking in C++. The missing int type is valid in C++ 4. [Test](http://ideone.com/DA8nVq)
[Answer]
# Score ~~131 130~~ 134
The lines to be prepended are:
```
#import <iostream>
#define def int main(){0?
#define greet()
#define print(A) 0;std::cout<<A"\n";}
```
And the resulting code:
```
#import <iostream>
#define def int main(){0?
#define greet()
#define print(A) 0;std::cout<<A"\n";}
def greet():
print("Hello, world!")
greet()
```
## Testing
```
C:\Users\Conor O'Brien\Documents\Programming\golf
λ type bilingual.py.cpp
#import <iostream>
#define def int main(){0?
#define greet()
#define print(A) 0;std::cout<<A"\n";}
def greet():
print("Hello, world!")
greet()
C:\Users\Conor O'Brien\Documents\Programming\golf
λ sed 's/\s//g' bilingual.py.cpp|wc -c
134
C:\Users\Conor O'Brien\Documents\Programming\golf
λ g++ bilingual.py.cpp 2>nul && a
Hello, world!
C:\Users\Conor O'Brien\Documents\Programming\golf
λ python bilingual.py.cpp
Hello, world!
C:\Users\Conor O'Brien\Documents\Programming\golf
λ
```
[Answer]
## Score ~~110~~ 104
Improving upon [Linus' answer](https://codegolf.stackexchange.com/a/98665/61709):
```
#include <cstdio>
#define print main(){puts
#define greet() ;}//\
def greet():
print("Hello, world!")
greet()
```
[Test as C++](http://ideone.com/I40MWe)
[Test as Python](http://ideone.com/toBTSk)
[Answer]
## Score 136
Only for the records:
```
#include <cstdio>
#define def class a{public
#define greet()
#define print(a) };int main(){puts(a);}
```
Another (less efficient) way to handle the colon.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 6 years ago.
[Improve this question](/posts/769/edit)
The numbers should be printed with leading zeroes in a field with length = (number of digits of N^2).
Input (N):
```
4
```
Output:
```
01 12 11 10
02 13 16 09
03 14 15 08
04 05 06 07
```
I am interested in the algorithm and the cleanliness of the implementation.
So, the white space does not count and the upper limit for N is 42.
[Answer]
## Python
```
n=input()
matrix=[[j+1]*n for j in range(n)]
x=y=0
for i in range(n)[::-2]:
x+=i*4;y+=1
for j in range(i):
matrix[j+y-1][y]=x+j
matrix[y-1][y:y+i]=range(x,x-i,-1)
R=matrix[n-y][y-1]+1
matrix[n-y][y:n-y+1]=range(R,R+i)
for j in range(y,y+i-1):
matrix[j][n-y]=matrix[j-1][n-y]-1
for row in matrix:
print ' '.join(`r`.zfill(len(`n*n`)) for r in row)
```
* An approach that precalculate corner numbers. Eg, for 9x box, 32 56 72 80, which is (n-1)\*4 where n is box sizes (9,7,5,3) in this case.
* Right side of those numbers are 1-, and top to bottom is 1+, so basically generate from left to right, top to bottom, bottom to right, right to top side.

```
$ echo 9 | python codegolf-769-me.py
01 32 31 30 29 28 27 26 25
02 33 56 55 54 53 52 51 24
03 34 57 72 71 70 69 50 23
04 35 58 73 80 79 68 49 22
05 36 59 74 81 78 67 48 21
06 37 60 75 76 77 66 47 20
07 38 61 62 63 64 65 46 19
08 39 40 41 42 43 44 45 18
09 10 11 12 13 14 15 16 17
```
Other tests
```
$ echo 2 | python codegolf-769-me.py
1 4
2 3
$ echo 5 | python codegolf-769-me.py
01 16 15 14 13
02 17 24 23 12
03 18 25 22 11
04 19 20 21 10
05 06 07 08 09
$ echo 10 | python codegolf-769-me.py
001 036 035 034 033 032 031 030 029 028
002 037 064 063 062 061 060 059 058 027
003 038 065 084 083 082 081 080 057 026
004 039 066 085 096 095 094 079 056 025
005 040 067 086 097 100 093 078 055 024
006 041 068 087 098 099 092 077 054 023
007 042 069 088 089 090 091 076 053 022
008 043 070 071 072 073 074 075 052 021
009 044 045 046 047 048 049 050 051 020
010 011 012 013 014 015 016 017 018 019
```
[Answer]
In Ruby:
```
N=gets.to_i
index = -N
width = N
result = []
n = 0
dir=-1
while n < N*N
dir = (dir + 1) % 4
dir_x, dir_y = [[0,1],[1,0],[0,-1],[-1,0]][dir]
width -= 1 if [1,3].include?(dir)
1.upto(width) { |m|
n += 1
index += dir_y * N + dir_x
result[index] = n
}
end
width = (N*N).to_s.size
result.each_slice(N) { |l|
print l.map {|n| "%0#{width}d" % n }.join(" "), "\n"
}
```
Test:
```
$ ruby1.9 769.rb <<< 9
01 32 31 30 29 28 27 26 25
02 33 56 55 54 53 52 51 24
03 34 57 72 71 70 69 50 23
04 35 58 73 80 79 68 49 22
05 36 59 74 81 78 67 48 21
06 37 60 75 76 77 66 47 20
07 38 61 62 63 64 65 46 19
08 39 40 41 42 43 44 45 18
09 10 11 12 13 14 15 16 17
```
An other solution using calculations from [here](http://2000clicks.com/mathhelp/CountingRationalsSquareSpiral1.aspx) :
```
N=gets.to_i
r=[]
tr=->x,y{ x+(N-1)/2 + (y+(N-1)/2+(N-1)%2)*N }
r[tr[0,0]] = N*N
1.upto(N*N-1) { |n|
shell = ((Math.sqrt(n)+1)/2).to_i
leg = (n-(2*shell-1)**2)/(2*shell)
element = (n-(2*shell-1)**2)-2*shell*leg-shell+1
x,y = [[element,-shell],[shell,element],[-element,shell],[-shell,-element]][leg]
r[tr[x,y]] = N*N-n
}
r.each_slice(N) {|l|
puts l.map { |n|
"%0#{(N*N).to_s.size}d" % (n or 0)
}.join(" ")
}
```
Test:
```
$ ruby1.9 769-2.rb <<< 5
01 16 15 14 13
02 17 24 23 12
03 18 25 22 11
04 19 20 21 10
05 06 07 08 09
```
[Answer]
In Python3:
```
n=int(input())
results = {}
val = 1
location = (0,0)
direction = (0,1)
def nxt():
return (location[0]+direction[0], location[1]+direction[1])
while val<=n*n:
if set([-1,n]).intersection(nxt()) or nxt() in results:
direction = (direction[1],direction[0]*-1)
results[location], location, val = str(val), nxt(), val+1
slen = len(str(n*n))
for y in range(n):
print( *[results[(x,y)].rjust(slen,'0') for x in range(n)] )
```
Sample Output for 7:
```
01 24 23 22 21 20 19
02 25 40 39 38 37 18
03 26 41 48 47 36 17
04 27 42 49 46 35 16
05 28 43 44 45 34 15
06 29 30 31 32 33 14
07 08 09 10 11 12 13
```
**edit: A recursive solution - 263 Bytes**
```
def a(m,s):
b,r,t=m-s*s+1,s-1,range
return[[[]],[[m]]][s]if s<2 else[[b]+list(t(b+4*r-1,b+3*r-1,-1))]+[[b+y+1]+a(m,s-2)[y]+[b+3*r-y-1]for y in t(s-2)]+[list(t(b+r,b+2*r+1))]
n=int(input())
for r in a(n*n,n):
print(*[str(x).zfill(len(str(n*n)))for x in r])
```
[Answer]
Java Solution
```
public static void main(String[] args) {
int INPUT = 5;
String[][] grid = new String[INPUT][INPUT];
int xDirection = 0;
int yDirection = 0;
int flag = 1;
for (int i = 0; i < INPUT * INPUT; i++) {
String temp = "";
for (int k = 0; k < (""+INPUT*INPUT).length() - ("" + (i + 1)).length(); k++) {
temp += "" + 0;
}
temp += (i + 1);
if (xDirection > INPUT-1)
{flag=2; yDirection++; xDirection--; i--; continue;}
else if (yDirection > INPUT -1)
{flag=3; yDirection--; xDirection--; i--; continue;}
else if (xDirection < 0)
{flag=4; xDirection++; yDirection--; i--; continue;}
if ( grid[xDirection][yDirection]==null ){
grid[xDirection][yDirection] = ""+temp;
}
else{
if (flag ==1 ) {
flag=2;
xDirection--;
}
else if (flag ==2){
flag=3;
yDirection--;
}
else if (flag==3){
flag=4;
xDirection++;
}
else{
flag=1;
yDirection++;
}
i--;
}
switch(flag){
case 1: xDirection++;break;
case 2: yDirection++;break;
case 3: xDirection--;break;
case 4: yDirection--; break;
}
}
for (int i = 0; i < INPUT; i++) {
for (int k = 0; k < INPUT; k++)
System.out.print(grid[i][k] + " ");
System.out.println();
}
}
```
sample output for input 10
```
001 036 035 034 033 032 031 030 029 028
002 037 064 063 062 061 060 059 058 027
003 038 065 084 083 082 081 080 057 026
004 039 066 085 096 095 094 079 056 025
005 040 067 086 097 100 093 078 055 024
006 041 068 087 098 099 092 077 054 023
007 042 069 088 089 090 091 076 053 022
008 043 070 071 072 073 074 075 052 021
009 044 045 046 047 048 049 050 051 020
010 011 012 013 014 015 016 017 018 019
```
[Answer]
# Perl, 178 chars
Uses Math::Complex and maintains the current direction in a complex variable (1/i/-1/.i). Run with:
```
$ perl -MMath::Complex spiral.pl
```
Put `N` in `$l`.
```
# $l = shift;
$d=i;
$x=0;
until($s{$x}){
$s{$x}=++$n;
$x+=$d;
$d*=-i if
Re($x)==Im($x)+(Re($x)<$l/2)
||Re($x)==$l-1-Im($x)
}
for$y(0..$l-1){
printf'%0'.length($l**2).'d ',$s{$_+i*$y}for 0..$l-1;
print"\n"
}
```
[Answer]
C
```
#include<stdio.h>
#include<math.h>
int main() {
int A[42][42],i,j,N,c=1,k;
scanf("%d",&N);
for (i = 0, j = N - 1 ; j >= 0 ; i++, j--) {
for(k = i ; k < j; k++)A[i][k]=c++;
for(k = i ; k < j; k++)A[k][j]=c++;
for(k = j ; k > i; k--)A[j][k]=c++;
for(k = j ; k > i; k--)A[k][i]=c++;
}
if (N%2)
A[N/2][N/2]=c;
for (i=0;i<N;i++) {
for (j=0;j<N;j++)
printf("%0*d ",((int)log10(N*N)+1),A[j][i]);
printf("\n");
}
}
```
[Answer]
## Python 2.7:
```
def spiral(n):
rows = [[n * n]]
current = n * n - 1
while current:
rows = zip(*([range(current, current - len(rows[0]), -1)] + rows))[::-1]
current -= len(rows)
digits = len(str(n * n))
for row in rows:
print" ".join(str(cell).zfill(digits) for cell in row)
spiral(5)
```
[Answer]
## PHP, 272 chars including comment
Func-based, recursive version - more interesting for me as it better expresses intention. It works for distinct width and height too.
```
<?php
$n = $argv[1];
for($y = 0; $y<$n; $y++){
for($x = 0; $x<$n; $x++)
printf("%02d ", f($n, $n, $x, $y));
echo "\n";
}
function f($w, $h, $x, $y){
return ($y)
?$w + f($h - 1, $w, $y - 1, $w - $x - 1) //strip-off first row and "rotate"
:$x;
}
```
Output:
```
C:\www>php -f golfed_spiral.php 8
00 01 02 03 04 05 06 07
27 28 29 30 31 32 33 08
26 47 48 49 50 51 34 09
25 46 59 60 61 52 35 10
24 45 58 63 62 53 36 11
23 44 57 56 55 54 37 12
22 43 42 41 40 39 38 13
21 20 19 18 17 16 15 14
```
[Answer]
## C#, 380-ish golfed
I didn't bother pasting in the golfed version as I was pretty confident this wasn't going to break any records. But I wanted to give it a shot thinking about it a bit differently. Rather than write out each line or position as I come to it, I'm moving the cursor into position, writing out the starting center number, and spiraling out from there (which illustrated an interesting pattern of positions-to-move per direction change).
There's a fair amount of character space wasted getting the console buffer to accept the larger values as well calculating the position for the upper left corner (which I'm sure can be improved).
At any rate, it was an interesting exercise.
```
static void Main(string[] p)
{
int squareSize = 4;
Console.BufferHeight = 300;
Console.BufferWidth = 300;
int maxTravel = 0;
int currentTravel = 0;
int travelCounter = 0;
var a = squareSize % 2 == 0;
int direction = a ? 2 : 0;
int pad = squareSize * squareSize;
int padLength = (pad + "").Length;
int y = a ? (squareSize / 2) - 1 : (squareSize - 1) / 2;
int x = a ? y + 1 : y;
x = x + (x * padLength);
for (int i = pad; i > 0; i--)
{
Console.SetCursorPosition(x, y);
Console.Write((i + "").PadLeft(padLength, '0') + " ");
switch (direction)
{
case 0:
y--;
break;
case 1:
x += padLength + 1;
break;
case 2:
y++;
break;
case 3:
x -= padLength + 1;
break;
}
if (++currentTravel > maxTravel)
{
currentTravel = 0;
direction = ++direction % 4;
if (++travelCounter == 2)
{
travelCounter = 0;
maxTravel++;
}
}
}
}
```
[Answer]
### Ruby
This isn't a particularly good golfable solution, but it might be of algorithmic interest.
I've always been fascinated by a similar [problem](https://gist.github.com/O-I/56d3049d9d99de965383), namely, finding the clockwise spiral path through an NxM matrix. One really intuitive way of solving that problem is to keep rotating the matrix counterclockwise and peel it like an orange. I use a similar — albeit not as elegant — method to do the reverse:
```
def spiral_matrix(n)
matrix = Array.new(n) { Array.new(n) }
path = [*1..n*n]
padding = (n*n).to_s.size
layer = 0
until path.empty?
matrix[layer].map! { |l| l || path.shift }
matrix = matrix.transpose.reverse
layer += 1 unless matrix[layer].include?(nil)
end
matrix = matrix.transpose.reverse until matrix[0][0] == 1
matrix.transpose.each do |row|
row.each do |l|
print "%0#{padding}d" % l, ' '
end
puts
end
end
```
[Answer]
## Racket
Just wanted to try it with a solution using close to 0 memory. No array, no nothing. The value can be generated for any position anytime. We could ask a spiral of any size (if what receives the output stream can handle it). In hope that someone ever needs gigantic spirals.
Here's the code
```
; number of chars required to write x in base 10
; defined for x > 0
(define log10
(λ (x)
(inexact->exact
(+ 1 (floor (/ (log x) (log 10)))))))
; tells the square number
; works for squares of both even and odd sizes
; outer square # = 0
(define square#
(λ (x y size) ; x and y begin at 0
(min x y
(- size 1 x)
(- size 1 y))))
; tells the number of values in a square
(define square-val-qty
(λ (sqr# size) ; size is the whole spiral size
(let ((res (* 4 (- size (* 2 sqr#) 1))))
(cond
((zero? res) 1)
(else res)))))
; at which value a square starts
; works for odd/even spirals
(define square-1st-val
(λ (sqr# size)
(+ (* 4 sqr# (- size sqr#)) 1)))
; square size from spiral size
(define square-side
(λ (sqr# size)
(- size (* 2 sqr#))))
(define 1+
(λ (n)
(+ n 1)))
(define 1-
(λ (n)
(- n 1)))
; calculates the position on the square (from 0)
(define position-on-square
(λ (x y size)
(let* ((sqr# (square# x y size))
(sqr-x (- x sqr#))
(sqr-y (- y sqr#))
(sqr-side (square-side sqr# size)))
(cond
((and (zero? sqr-x) (< sqr-y (1- sqr-side))) ; left part
sqr-y)
((and (eq? sqr-y (1- sqr-side)) (< sqr-x (1- sqr-side))) ; bottom
(+ (1- sqr-side) sqr-x))
((and (not (eq? sqr-y 0)) (eq? sqr-x (1- sqr-side))) ; right
(+ (* 2 (1- sqr-side)) (- sqr-side sqr-y 1)))
(else ; top
(+ (* 3 (1- sqr-side)) (- sqr-side sqr-x 1)))))))
; returns the spiral value at the given position
(define spiral-value
(λ (x y size)
(+ (square-1st-val (square# x y size) size)
(position-on-square x y size))))
; pads a string with char
(define left-pad
(λ (str char width)
(cond
((< (string-length str) width)
(left-pad (string-append (string char) str) char width))
(else
str))))
; draws a spiral!
(define draw-spiral
(λ (size)
(let ((x 0)
(y 0)
(width (log10 (* size size))))
(letrec ((draw
(λ ()
(printf "~a " (left-pad (number->string (spiral-value x y size)) #\0 width))
(cond
((and (eq? x (1- size)) (eq? y (1- size)))
(printf "~n~n"))
((eq? x (1- size))
(set! x 0)
(set! y (1+ y))
(printf "~n")
(draw))
(else
(set! x (1+ x))
(draw))))))
(draw)))))
```
Testing with this
```
(draw-spiral 1)
(draw-spiral 2)
(draw-spiral 3)
(draw-spiral 4)
(draw-spiral 5)
(draw-spiral 15)
(draw-spiral 16)
```
Results in output
```
1
1 4
2 3
1 8 7
2 9 6
3 4 5
01 12 11 10
02 13 16 09
03 14 15 08
04 05 06 07
01 16 15 14 13
02 17 24 23 12
03 18 25 22 11
04 19 20 21 10
05 06 07 08 09
001 056 055 054 053 052 051 050 049 048 047 046 045 044 043
002 057 104 103 102 101 100 099 098 097 096 095 094 093 042
003 058 105 144 143 142 141 140 139 138 137 136 135 092 041
004 059 106 145 176 175 174 173 172 171 170 169 134 091 040
005 060 107 146 177 200 199 198 197 196 195 168 133 090 039
006 061 108 147 178 201 216 215 214 213 194 167 132 089 038
007 062 109 148 179 202 217 224 223 212 193 166 131 088 037
008 063 110 149 180 203 218 225 222 211 192 165 130 087 036
009 064 111 150 181 204 219 220 221 210 191 164 129 086 035
010 065 112 151 182 205 206 207 208 209 190 163 128 085 034
011 066 113 152 183 184 185 186 187 188 189 162 127 084 033
012 067 114 153 154 155 156 157 158 159 160 161 126 083 032
013 068 115 116 117 118 119 120 121 122 123 124 125 082 031
014 069 070 071 072 073 074 075 076 077 078 079 080 081 030
015 016 017 018 019 020 021 022 023 024 025 026 027 028 029
001 060 059 058 057 056 055 054 053 052 051 050 049 048 047 046
002 061 112 111 110 109 108 107 106 105 104 103 102 101 100 045
003 062 113 156 155 154 153 152 151 150 149 148 147 146 099 044
004 063 114 157 192 191 190 189 188 187 186 185 184 145 098 043
005 064 115 158 193 220 219 218 217 216 215 214 183 144 097 042
006 065 116 159 194 221 240 239 238 237 236 213 182 143 096 041
007 066 117 160 195 222 241 252 251 250 235 212 181 142 095 040
008 067 118 161 196 223 242 253 256 249 234 211 180 141 094 039
009 068 119 162 197 224 243 254 255 248 233 210 179 140 093 038
010 069 120 163 198 225 244 245 246 247 232 209 178 139 092 037
011 070 121 164 199 226 227 228 229 230 231 208 177 138 091 036
012 071 122 165 200 201 202 203 204 205 206 207 176 137 090 035
013 072 123 166 167 168 169 170 171 172 173 174 175 136 089 034
014 073 124 125 126 127 128 129 130 131 132 133 134 135 088 033
015 074 075 076 077 078 079 080 081 082 083 084 085 086 087 032
016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031
```
Quite CPU intensive compared to precalculated matrices if you need the whole spiral, but might be useful. Who knows! E.g.:
```
(spiral-value 1234567 7654321 234567890) -> 1152262488724319
```
Didn't golf it... It's quite small despite the appearance. I used long names and comments.
[Answer]
# [Python 2](https://docs.python.org/2/), 800 bytes
```
from collections import namedtuple
Crd = namedtuple('Crd',['row','col','val'])
C1 = Crd(1,1,1)
def add(c1, c2):
return Crd(c1.row + c2.row, c1.col + c2.col, c1.val + c2.val)
def deltas(l):
for i in xrange(1,l): yield Crd(0,1,1)
for i in xrange(1,l): yield Crd(1,0,1)
for i in xrange(1,l): yield Crd(0,-1,1)
for i in xrange(1,l-1): yield Crd(-1,0,1)
def ring(c, l):
yield c
for d in deltas(l):
c = add(c, d)
yield c
def spiral(n):
cur = C1
while n > 0:
for c in ring(cur, n):
yield c
cur = c
cur = add(cur, Crd(0,1,1))
n -= 2
n = input()
fmt = '%' + str(len(str(long(n*n)))) + 'd'
crds = sorted(list(spiral(n)))
for r in xrange(1,n+1):
print ' '.join([fmt % c.val for c in crds if c.row == r])
```
[Try it online!](https://tio.run/##jVJNj8IgEL33V8zFQFdqisdNuhd/hvHQAFU2ODSUruuvdweq9eOwERM7zDzeezPQn@PB4/py6YI/gvLOGRWtxwHssfchArZHo@PYO1NsgobmIcEZZZjYsuBPTDA6TP8/rWO7sthIglKZS0G/stCmg1ZrrqQAtS4/C6AVTBwDZpiSK2KBJRVTQCC5IsIpQUFOEPeUoGCi1MbFduDuStj5ABYswm9ocW9InCpwtsbprFJPZt6BSlG/C61F9R9tJZ/Q1ZU52Q8W91wJuPmfUGpm0onppce0FA03T1OALufs7XRiHnobWsfxekiNId2HzJvTwToDCF9Q3ymTnEpyk6cxCMAHxVd3s5NMfM9N@@wtUdyHfreJUDWwLjDFDSn2Y@Rl0R1j2rIFoyseYuDOIM9fT37wA0taVGKaFSrogbADvU@jubND5HO/JJRaCU93gEt57aWn9iIwYKtvb5Fvk@wCVH5a8wgyv@0ond5k00DYlZeLrP8A "Python 2 – Try It Online")
A few years back a friend of mine was asked this question in an interview. They told me about it at our family's [Thanksgiving dinner](https://en.wikipedia.org/wiki/Thanksgiving_dinner) so I think of this as the "Thanksgiving problem".
[Answer]
# PHP, ~~172~~ 171+1 bytes, 24 operations
creates an array walking the indexes through a spiral; then prints the result.
```
// 1) input squared -> 2) string length -> 3) $e = length of maximum number
for($e=strlen($argn**2);
// 4) decrement input (line length) every second iteration; 5) loop while input>0
$argn-=$i%2;
// 24) post-increment iteration counter $i
$i++)
// 6,7,8) loop through current line
for($p=$argn;$p--;)$r
// 9) $i=$i modulo 4; 10,11) (1-$i)%2 == [1,0,-1,0][$i] -> 12) increment/decrement $y coordinate3
[$y+=(1-$i%=4)%2]
// 13,14) (2-$i)%2 == [0,1,0,-1][$i] -> 15) increment/decrement $x coordinate
[$x+=(2-$i)%2]
// 16) print formatted to string; 17) assign to field [$y,$x] in $r
=sprintf("%0{$e}d ",++$n);
// 18) pre-increment row counter $z; 19) loop while row exists
for(;$r[++$z];
// 21) join row; 22) append newline; 23) print
print join($r[$z])."\n")
// 20) sort row by indexes
ksort($r[$z]);
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/9a5b9fd3306b2fc3c2a93c68f86c4418bfa077a0).
Add one assignment to save five bytes: replace the final loop with
```
for(;$s=$r[++$z];print join($s)."\n")ksort($s);
```
[Answer]
Sample code : This works for 4x5 but failing 3x5
while (k < m && l < n)
{
/\* Print the first row from the remaining rows \*/
for (i = l; i < n; ++i)
{
printf("%d ", a[k][i]);
}
k++;
```
/* Print the last column from the remaining columns */
for (i = k; i < m; ++i)
{
printf("%d ", a[i][n-1]);
}
n--;
/* Print the last row from the remaining rows */
if ( k < m)
{
for (i = n-1; i >= l; --i)
{
printf("%d ", a[m-1][i]);
}
m--;
}
/* Print the first column from the remaining columns */
if (l < n)
{
for (i = m-1; i >= k; --i)
{
printf("%d ", a[i][l]);
}
l++;
}
}
```
] |
[Question]
[
# Task
Write a function/full program that will be able to produce two different sequences of integers in `[0, ..., 9]`. You will take an input `seed` to decide whether to output your `s`pecific sequence or the `c`ommon one. For that matter, you must choose one non-negative integer, let us call it `k`. When the input `seed` is equal to `k`, you will be dealing with your specific sequence `s`; when the input `seed` is anything else, you will be dealing with your common sequence `c`.
Both sequences should be such that the relative frequencies with which each digit appears tend to \$10\%\$. Be prepared to prove this if needed. Said another way, the running fraction of that digit's appearances needs to have a defined limit that equals \$0.1\$. Formally, this means that for every \$d \in \{0,...,9\}\$,
$$\lim\_{n\rightarrow \infty}\dfrac{\left|\{i : i \in \{1\dots n\}, s\_i=d\}\right|}{n} = 0.1$$
*Adapted from [What an Odd Function](https://codegolf.stackexchange.com/questions/141315/what-an-odd-function)*
There should be one extra restriction your sequences should satisfy: when zipped together\* to form a sequence `a` of terms in `[0, ..., 99]`, the relative frequency of each number should converge to `0.01` via a limit like the formula above.
\*That is, the \$n\$th term of the sequence `a` is the two-digit number built this way: the digit in the tens place is the \$n\$th term of the sequence `c` and the digit in the units place is the \$n\$th term of the sequence `s`.
# Input
A non-negative integer representing the "seed", which you use to decide whether to output the common sequence or the specific one.
# Output
Your output may be one of the following:
* an infinite stream with the sequence (and you take no additional input);
* output the `n`th term of the sequence (by taking an additional input `n` that is `0`- or `1`-indexed);
* output the first `n` terms of the sequence (by taking an additional positive input `n`).
# Example pseudo-algorithm
Assuming I have defined `seed` as an integer, and for these choices I made for `s` and `c`:
```
input_seed ← input()
n ← input()
if input_seed = seed: print (n mod 10) # this is my sequence s
else: print ((integer div of n by 10) mod 10) # this is my sequence c
```
Both sequences output numbers in `[0, ..., 9]` and the frequency with which each digit appears tends to `0.1` as `n → infinity`. Similarly, zipping `c` and `s` together gives `n mod 100` so it is also true that as `n → infinity` we have that the relative frequency with which each number in `[0, ..., 99]` shows up goes to `0.01`.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~23~~ 22 bytes
*Thanks @xnor for figuring out a really cool way to convert the seed to `-1` or `-2`, which saved 1 byte.*
```
lambda s,n:`n+9`[2/~s]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFYJ88qIU/bMiHaSL@uOPZ/Wn6RQqZCZp5CUWJeeqqGoY6hgaGmFZdCQVFmXolCmoaBTqamDpA2hNJGQPo/AA "Python 2 – Try It Online")
**Input**: The seed `s` (non-negative) and an index `n` (positive).
**Output**: The element at the nth index (the sequence is one-indexed)
If the seed is positive, the sequence is `0123456789` repeated infinitely.
If the seed is `0`, the sequence is: `1111111111 2222222222 ... 9999999999 0000000000` (where each digit repeats 10 times) repeated infinitely.
**How**
* ``n+9`` creates a string from a number that has at least 2 digits.
* `2/~s` evaluates to -2 if `s` is 0, or -1 if `s` is positive
* Thus ``n+9`[2/~s]` takes the last digit (unit digit) of \$n+9\$ if `s` is positive, or the second to last digit (ten digit) if `s` is 0.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~4~~ 3 bytes
```
ΘÍè
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3IzDvYdX/P9vwGVqBgA "05AB1E – Try It Online")
Takes the seed then n and outputs the nth term, outputs different sequence for seed of 1
---
## Explanation
```
Θ - truthified (so 1 if input is 1, else 0)
Í - subtract 2 (so -1 if input is 1, else -2)
è - take this index of the nth term
```
Since 05AB1E uses modular indexing it won't go out of bounds, and `a[-1]` is the last element of a. Likewise `a[-2]` is the penultimate.
---
Alternatively to output an infinite sequence.
### [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
∞εIΘÍè
```
[Try it online!](https://tio.run/##yy9OTMpM/f//Uce8c1s9z8043Ht4xf//BgA "05AB1E – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 24 bytes
```
f(s,n){s=(s?n/10:n)%10;}
```
[Try it online!](https://tio.run/##LcnBCsIwEIThe55iKBR2acSNR2PwRbxIJLIHV2l6K332mIow8MH8@fDMubVC1RuvNVG92jHI2XgMEremtuB1VyPG6sp7Bu2PIkEi9JKCdKdJGQ6fubdCw/jAbzcbPAqJV94Nf09djm5rXw "C (gcc) – Try It Online")
***Input***: seed (\$s\$) and \$n\$.
***Output***: \$n^{\text{th}}\$ term zero-indexed.
For \$s=0\$ the sequence is: \$0,1,2,\dots,9,\dots\$
For \$s>0\$ the sequence is: \$\underbrace{0,0,\dots,0}\_{10},\underbrace{1,1,\dots,1}\_{10},\underbrace{ 2,2,\dots,2}\_{10},\dots,\underbrace{9,9,\dots ,9}\_{10},\dots\$
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 38 bytes
Takes Input [n,seed] and outputs nth term
Specific seed is 0
```
If[#2>0,#~Mod~10,Floor[#~Mod~100/10]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zMtWtnIzkBHuc43P6XO0EDHLSc/vygaxjXQNzSIjVX7H1CUmVei4JAebWKkYxjLhcw1gHIdlJQgDH2H6vRoZR2jWDV9h6DEvPRUByMDg1rsigxQFf3/DwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# JavaScript (ES7), 19 bytes
Takes input as `(seed)(n)` and returns the \$n\$-th term. The special seed is \$0\$.
```
s=>n=>n/10**!s%10|0
```
[Try it online!](https://tio.run/##dcrRCoIwFIDhe5/idBFubtmZt2bQc0gXslxMxIUbQVbPbqcgWIGwcc6@f11zbbwe7SVsBndqZ1PNvtoPdLYKs2zl1wofOBs3soBQwWEcmxtTyHNj@54hlxDUgheRx8GSq5LGjiYibUJwuCcAAWtP0dA3ZvlRiPKNqtYfVDEW9UQoWJqCAE3Xf5N2g3d9m/fuzLwELWHiyTOJmZc/z4B55@zAUpny/6SWUxGn@QU "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~9~~ 5 bytes
```
§S⊕¬N
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMOxxDMvJbVCwzOvoLQkuAQolq6hqaPgmZdclJqbmleSmqLhl18CkfYrzU1KLdLQBAHr//@NzRUM/@uW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as `n`, `s` and outputs the (1-indexed) third digit of `n` if `s` is zero otherwise the second digit of `n` (so somewhat similar to @ExpiredData's answer, although this was unintentional). The two sequences separately always output an exact 10% frequency after a power of 10 terms, while the combined sequence outputs an exact 1% frequency between the (0-indexed) 10th term and a higher power of 10 terms. Explanation:
```
N Input `s`
¬ Logical Not
⊕ Incremented
S Input `n` as a string
§ Cyclically indexed
Implicitly print
```
Version that outputs the first `n` terms for each of the first `s` seeds:
```
EIθ⭆Iη§Iλ⊕¬ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDDObG4RKNQU0chuAQolg4XygAKOZZ45qWkVkAEcoACnnnJRam5qXklqSkafvklGpmaYGD9/7@xgqGBgcF/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~25~~ 23 bytes
Saved 2 bytes thanks to [Mitchell Spector](https://codegolf.stackexchange.com/users/59825/mitchell-spector)!!!
```
echo $[$2/($1?10:1)%10]
```
[Try it online!](https://tio.run/##pcy9DYMwEAbQ/qb4CiOg8HEHXVJkkIgi/Fi4sSOgszy7owyAFClvgDe9jq24pk1lnbcI8zR91xh9qNy0rVTGksnFHR4@IAmziuT7EgkOAuNpiWGl9@7D6WAtaluxHDWSMg@S6bteBvpv0P8alA8 "Bash – Try It Online")
***Input***: seed (\$s\$) and \$n\$.
***Output***: \$n^{\text{th}}\$ term zero-indexed.
For \$s=0\$ the sequence is: \$0,1,2,\dots,9,\dots\$
For \$s>0\$ the sequence is: \$\underbrace{0,0,\dots,0}\_{10},\underbrace{1,1,\dots,1}\_{10},\underbrace{ 2,2,\dots,2}\_{10},\dots,\underbrace{9,9,\dots ,9}\_{10},\dots\$
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 15 bytes
```
s=>n=>n[!s+1]|0
```
[Try it online!](https://tio.run/##dYpBCoMwEEX3nmLqJgmxMnFrLfQc4kJSLRExJQmF2vbs6bRQsIIww//z3gztrfXamWvYT/bcxb6KvjpONPXOS9U8MfbW8YBQwcm59s4Vosh7M44cRQZBbYliQxjiqqQ4UCIiVSkFPBKAgLUn29MfNzJNRSNl@eGq1l@uVryoZ@KSMwYSNK3/KW0nb8cuH@2F@wx0BrNIXskSi/LvDJgP1kycZUysldpWxVLFNw "JavaScript (Node.js) – Try It Online")
If seed is 0 it will take the 3rd digit of the number, else it will take the 2nd digit of the number
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 16 bytes
```
^(0,.+).
$1
!`.$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP07DQEdPW1OPS8WQSzFBT@X/fwMdAy4DHRMjLkMgwxDIAAA "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input as `s,n` and outputs the second last digit of `n` if it has one and `s` is zero otherwise the last digit of `n`. The individual sequences are 10% of each digit but the combined sequence only approaches 1% after the 10th term. (I have a 16 byte answer in Retina 1 for which the combined sequence contains 1% of each pair.) Explanation:
```
^(0,.+).
$1
```
If `s` is `0` then delete the last digit of `n` unless that is its only digit.
```
!`.$
```
Output the last digit of `n`.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~15~~ 13 bytes
Saved 2 bytes thanks to [Mitchell Spector](https://codegolf.stackexchange.com/users/59825/mitchell-spector)!!!
```
[A/]sa?0=aA%p
```
[Try it online!](https://tio.run/##S0n@/z/aUT@2ONHewDbRUbXg/39DI2MFAwA "dc – Try It Online")
***Input***: \$n\$ and seed (\$s\$).
***Output***: \$n^{\text{th}}\$ term zero-indexed.
For \$s>0\$ the sequence is: \$0,1,2,\dots,9,\dots\$
For \$s=0\$ the sequence is: \$\underbrace{0,0,\dots,0}\_{10},\underbrace{1,1,\dots,1}\_{10},\underbrace{ 2,2,\dots,2}\_{10},\dots,\underbrace{9,9,\dots ,9}\_{10},\dots\$
[Answer]
# MATLAB, 45 bytes
```
v=input('');rng(fix(~v(1)));randi(10,v(2),1)-1
```
`randi(N,n,1)` generates an n-length sequence of uniform random integers in the range 1,...,N. Taking two digits of the resulting sequence of realizations at a time, the required distribution follows naturally, which can be checked using the example code below.
```
N = 50000 ;
[h,x] = hist(10*(randi(10,N,1)-1) + (randi(10,N,1)-1), 100) ;
h = h/sum(h) ;
stem(x,h) ;
axis([0 10 0 0.1]) ;
```
`rng(fix(~s))` sets the random number generator seed to one if `s=0` otherwise to zero.
# Inputs
Read from the console in the format (incl brackets) "[s n]".
# Comments
* This method can be extended to generate limitless number of sequences which satisfy the required properties.
* Now compatible with several versions of MATLAB
[Answer]
# [R](https://www.r-project.org/), 22 19 17 bytes
Following earlier resolutions, this R code is producing two different sequences with the correct limiting frequencies whether \$s=0\$ (penultimate digits) or \$s\ne 0\$ (last digits):
```
1:n%/%10^(!s)%%10
```
[Try it online!](https://tio.run/##K/pfbGtsbJ1na5hq/N/QKk9VX9XQIE5DsVhTFcj4/x8A "R – Try It Online")
As for checking whether or not the merged sequences work as well, one can run, e.g.,
```
summary(as.factor((10*(1:n%/%10%%10)+(1:n%%10))))
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
!←±⁰d
```
[Try it online!](https://tio.run/##ASYA2f9odXNr/21vd1MsYOG5gOKCgcWAMjAwxYAz/yHihpDCseKBsGT//w "Husk – Try It Online") Gives a single term, given `seed` and `n` as arguments. `k` is equal to 0.
[Answer]
# [perl](https://www.perl.org/) -apple, 18 bytes
```
$F[0]&&chop;$_%=10
```
[Try it online!](https://tio.run/##K0gtyjH9/1/FLdogVk0tOSO/wFolXtXW0OD/fwMFI2MuQxBhoGBoas5laA6mgBygqOG//IKSzPy84v@6iQUFOQA "Perl 5 – Try It Online")
Prints the last digit of `n` for the special sequence (`c = 0`), otherwise, the penultimate digit of `n`. It doesn't quite work for single digit `n`'s, but since we only have to tend towards equal distribution, it doesn't matter what it prints.
[Answer]
# [W](https://github.com/A-ee/w), 2 [bytes](https://github.com/A-ee/w/wiki/Code-Page)
(Port of the Charcoal answer.) How in the world can a 3-byter ever compress in the compressor‽
```
H≡
```
Uncompressed:
```
!)[
```
# Explanation
```
! % Logical negate the first input.
) % Increment the negated input.
[ % Cyclic index the second input by that result.
```
] |
[Question]
[
# Challenge
For a given positive integers range, find the first and last prime number entirely composed of prime number digits, exceptionally including 0 (for the **digits**, a range of 0-2 should output 2-2). The range is inclusive. If no number is found, the expected output is 0. If there is only one such number, the expected output is that number twice.
# Examples
* For the range 1–100, the first prime number is 2 and the last is 73 (7 and 3 are prime numbers).
* For the range 70–80, the first prime number is 73 and the last is also 73 (Since there is only one correct number in the given range, we return it twice).
* For the range 190–200, there is no correct answer, so you return 0.
* For the range 2000-2100, the first prime number is 2003 and the last is 2053 (we omit the digit 0, but all the other digits are prime)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes win!
All standard loopholes apply.
# Input
* You are free to accept two integers as input however you may see fit, stack, function argument(s), CLI argument, stdin.
* You **must** only receive two integers.
# Output
* You **must** either return the result (a tuple, an array, multi-return if your language supports it), leave it on the stack, or print it (in this case, they must be separated somehow).
* The order of the outputs is irrelevant.
* You are allowed leading/trailing brackets and newlines.
* You must return two numbers, if there is an answer, even if they are the same.
* You must return 0 if there is no answer.
[Answer]
# [Python 2](https://docs.python.org/2/), 123 bytes
```
def f(a,b):r=[i for i in range(a,b+1)if(set(`i`)<=set('02357'))>any(i%k<1for k in range(3,i))];return len(r)and(r[0],r[-1])
```
[Try it online!](https://tio.run/##RY5BCoMwEEX3nmI2xQxNIVGK1movIgEjJm2wRJmmC09vEzfdPf68B7Nu4bX4Yt8nY8EyzUdsqOsd2IXAgfNA2j9NOpwlOss@JrDBDdh2iXJRlNcqR3xovzF3mluZwvkfltwhqjuZ8CUPb@MZofYTo14oTv1FKtxTojmMqeqZ5CCFQA6sEhzqg@QtYhFX1WQAKzkfjm9hxF3yqGfRrUWWvKj9AA "Python 2 – Try It Online")
[Answer]
# Perl 6, ~~105~~ ~~94~~ ~~90~~ 86 bytes
```
{my @b=grep {is-prime all($_,|.comb>>.Int Xor 2)},$^a..$^b;say @b??"@b[0] @b[*-1]"!!0}
```
[Answer]
# JavaScript (ES6), 83 bytes
Takes the range **[a-b]** in currying syntax `(a)(b)`. Returns either a 2-element array or **0**.
```
n=>g=(m,a=0)=>n>m?a:g(m-1,(P=d=>m%--d?P(d):d>1|/[14689]/.test(m))(m)?a:[m,a[1]||m])
```
### Test cases
```
let f =
n=>g=(m,a=0)=>n>m?a:g(m-1,(P=d=>m%--d?P(d):d>1|/[14689]/.test(m))(m)?a:[m,a[1]||m])
console.log(f(1)(100))
console.log(f(70)(80))
console.log(f(190)(200))
```
[Answer]
# Mathematica, 91 bytes
```
If[(s=Select[Range@##,(p=PrimeQ)@#&&And@@((p@#||#<1)&/@IntegerDigits@#)&])!={},MinMax@s,0]&
```
[Try it online!](https://tio.run/##Tcw/CwIhGIDxvW8RgigIaUsFCW/QcsNBf0a5Qa5XT0g5Toeg67PbLUHjjweeaMuA0ZbQ2@p0bZxhWd/xiX0xN5s8AiGCjfoyhYhXDoTSU3oAMDYCmWdyVJxuoEkFPU7n4EPJQDjt@Fq/P6INqbUvyEJ2tC6LVMAZJZSU3erHnRT7P6qDFNul1y8 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
æRµDo2ÆPẠµÐf.ị
```
[Try it online!](https://tio.run/##ASYA2f9qZWxsef//w6ZSwrVEbzLDhlDhuqDCtcOQZi7hu4v///8xMDD/MQ "Jelly – Try It Online")
### How it works
```
æRµDo2ÆPẠµÐf.ị ~ Full program.
æR ~ Inclusive prime range.
µ µÐf ~ Only keep those which satisfy a condition.
Do2ÆPẠ ~ The filter condition:
D ~ The decimal digits of the current number.
o2 ~ Logical or with 2 (maps 0 to 2 and any other digit to itself).
ÆP ~ Is prime (element-wise)?
Ạ ~ Check whether all the digits satisfy the condition.
.ị ~ Get the element at modular index 0.5. Some details:
~ Jelly is 1-indexed, so 1 gives us the first element, whilst 0
gives us the last element.
~ If the ceil and the floor of the given number N don't match,
then Jelly returns the items at indexes floor(N) **and** ceil(N).
~ If the list is empty, this yields 0, hence it is very convenient.
```
---
If taking the whole range would be allowed (although I think it should not be), then 12 bytes:
```
Do2,ÆPȦµÐf.ị
```
[Try it online!](https://tio.run/##Fc@tbYNRDIXhVTyAFdW/t@EZIDwKbEH1ScVdoKQkU2SDorKEdI1McvNeYORHxz4fb9v2Nefh0/X@ffy/3n7vl/fd4@9nznkyFVcJlVQplVYZKq8qexV7YdgbwBAGMYyBDGUwwznOVw7OcY5znOMc5zjHBS5wsQ7iAhe4wAUucIFLXOISl@szXOISl7jEJa5whStc4WpVwBWucIUrXOMa17jGNa5XV1zjGte4gRu4gRu4kecn "Jelly – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes
```
⟦₂{ṗṗᵐ}ˢ⟨⌋≡⌉⟩|∧0
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8ZY@amqof7pwOQlsn1J5e9Gj@ikc93Y86Fz7q6Xw0f2XNo47lBv//RxtaGugYGRjE/o8CAA "Brachylog – Try It Online")
The completely non-sensical "return 0 if there's no prime" makes us lose 3 bytes (`|∧0`) for no reason (it would return `false.` if we didnt add them)
### Explanation
```
⟦₂ Range from the smallest element of the input to the biggest
{ }ˢ Select on that range:
ṗ Numbers that are primes
ṗᵐ And whose digits are primes
⟨ ⟩ Fork on this new list:
⌋ Minimum
⌉ maximum
≡ Do nothing and return [Minimum, Maximum]
|∧0 If all of this fails (i.e. the list after selection is empty), return 0
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 24 bytes
Using my initial approach turns out to be shorter.
```
.x,eKfP#I_M-+TjT;0}EQhKZ
```
**[Try it here!](https://pyth.herokuapp.com/?code=.x%2CeKfP%23I_M-%2BTjT%3B0%7DEQhKZ&input=100%0A1&test_suite=1&test_suite_input=100%0A1%0A%0A80%0A70%0A%0A200%0A190%0A%0A2100%0A2000%0A&debug=0&input_size=3)**
(I was just updating to 23 but [Steven beat me to it](https://codegolf.stackexchange.com/questions/150520/first-and-last-prime-numbers-with-prime-digits-of-range/151011?noredirect=1#comment369324_151011))
```
?KfP#I_M-+TjT;0}FQhM_BK0
```
**[Try it here!](https://pyth.herokuapp.com/?code=%3FKfP%23I_M-%2BTjT%3B0%7DFQhM_BK0&input=100%2C200&test_suite=1&test_suite_input=1%2C+100%0A70%2C80%0A190%2C200%0A2000%2C2100&debug=0)**
Natually, `hM_BK` can be replaced by `,hKeK`.
### 25 bytes
```
.x,eKf.AmP_|d2+TjT;}EQhKZ
```
**[Try it here!](https://pyth.herokuapp.com/?code=.x%2CeKf.AmP_%7Cd2%2BTjT%3B%7DEQhKZ&input=100%0A1&test_suite=1&test_suite_input=100%0A1%0A%0A80%0A70%0A%0A200%0A190%0A%0A2100%0A2000%0A&debug=0&input_size=3)**
### 26 bytes
```
|>2.<f.AmP_|d2+TjT;*2}EQ1Z
```
**[Try it here!](https://pyth.herokuapp.com/?code=%7C%3E2.%3Cf.AmP_%7Cd2%2BTjT%3B%2a2%7DEQ1Z&input=100%0A1&test_suite=1&test_suite_input=100%0A1%0A%0A80%0A70%0A%0A200%0A190%0A%0A2100%0A2000%0A&debug=0&input_size=3)**
```
|>2.<fP#I_M|R2+TjT;*2}EQ1Z
```
**[Try it here!](https://pyth.herokuapp.com/?code=%7C%3E2.%3CfP%23I_M%7CR2%2BTjT%3B%2a2%7DEQ1Z&input=100%0A1&test_suite=1&test_suite_input=100%0A1%0A%0A80%0A70%0A%0A200%0A190%0A%0A2100%0A2000%0A&debug=0&input_size=3)**
---
### How they work
```
.x,eKfP#I_M-+TjT;0}EQhKZ ~ Full program. Q, E = first, second inputs
.x Z ~ Try-catch block. If the code errors, output 0.
f }EQ ~ Filter the range [E ... Q] for (uses a variable T):
+TjT; ~ Append T to the list of its digits.
- 0 ~ Remove the zeros.
_M ~ Multiply each by -1 (for primality testing).
I ~ Check if the result is invariant over...
P# ~ Removing non-prime items.
K ~ Assigned the filtered range to a variable K.
,e ~ Pair the last element of K with...
hK ~ Its first element.
```
---
```
|>2.<f.AmP_|d2+TjT;*2}EQ1Z ~ Full program.
*2}EQ ~ Inclusive range, repeated twice..
f ~ Filter, using T as the current number.
jT; ~ Base-10 digits of T.
+T ~ Concatenated with T.
mP_|d2 ~ Prime check after performing OR 2 (makes 0 be treated as prime)
.A ~ Do all satisfy this condition?
.< 1 ~ Rotate by one place cyclically to the left.
>2 ~ Last two elements (ignored if there aren't enough)
| Z ~ Logical or with 0.
```
[Answer]
## Mathematica 85 Bytes
I know there is already a similar answer, but the approach here is quite different.
```
MinMax@Cases[Range@##,x_/;PrimeQ@x&&DisjointQ@@IntegerDigits/@{x,14689}]/.{_,∞}->0&
```
This 83 character answer will paste and run in Mathematica. The TIO site doesn't know how to interpret ∞.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
Do2ÆPẠ
æRÇÐf.ị
```
[Try it online!](https://tio.run/##ASUA2v9qZWxsef//RG8yw4ZQ4bqgCsOmUsOHw5BmLuG7i////zcw/zgw "Jelly – Try It Online")
```
æRÇÐf.ị Main link
æR Prime range
Ðf Filter the range with...
Ç The helper link
ị At index (decimal, returns [xs[floor], xs[ceil]], otherwise 0)
. 0.5
Do2ÆPẠ Helper link
D For each decimal
o2 Replace 0s with 2s, an actual prime prime (could be 3, 5, or 7).
ÆP Filter primes (1 if true, 0 if false)
Ạ Check if all are true
```
Thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) for the help fixing a bug.
Thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) for the `.ị` trick.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 87 bytes
```
->a,b{(z=(a..b).select{|x|(2...x).none?{|r|x%r<1}&&/[14689]/!~"%d"%x})[0]?(z.minmax):0}
```
[Try it online!](https://tio.run/##Hc3RCsIgGEDhV7HBhoL90xG1RWsPIl5obRCkjVVgU3t1k@4@zs1Z3vqTpj5tz4pqj9ceKwBN4Dnex8vLBxdwAwCOgH3YcfBhCa5cTjxWVS34bt92st58i/JalC4SweSAVzA3a5QjRxaTEJwizpikSBwYRe1fvMtscpVg1OxDfgc0o0lkyJh@ "Ruby – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 36 bytes
```
),>{mp},{s{_!\~mp|}%1-!},_{_0=\W=}0?
```
[Try it online!](https://tio.run/##S85KzP3/31DB0MBAU8euOregVqe6uDpeMaYut6CmVtVQV7FWJ7463sA2Jty21sD@/38A "CJam – Try It Online")
[Answer]
# [Perl 6](https://perl6.org), ~~68 66 65 61~~ 58 bytes
```
{($_=($^a..$^b).grep({.is-prime&&/^<[02357]>+$/})[0,*-1])[1]??$_!!0}
```
[Try it](https://tio.run/##ZY3RCoIwGIXv9xS/NGQrnf8mucLMBxEVsxFCkigFEj770gtB6OZcnPPxnc70z8gS8h4MfCJRx6Qdwa1fdwOJ/TJaJowWlRC0uHHx6E3HvqIZ/K5vWuO6QXHJUIVHnV8PNJh4ht7elznPZJ6mtHQcnOxQjbD4GABIbwlE4DHsgCkPdMjJltC4IKeV0OEfIs8LolYJbra5nDe1OUCcBQqV5vYH "Perl 6 – Try It Online")
```
{($_=($^a..$^b).grep({.is-prime&&!/<[14689]>/})[0,*-1])[1]??$_!!0}
```
[Try it](https://tio.run/##ZY1BCoMwFET3nuJLgyRF408sRrHWg4iKtaEIlYrSgohnt2YhCN3MYubxptfDK1wt6zNq@Ia8SaxuAqd5PzSk60xJlVJS1pyT8s74c9A9nXk7ev3QdtpxbP@ai0sYxcXNX1iO7tkTBctFkWWksm1c1rGewNgoAAjXBCKwBE5ApQsqYNaRUGiQaCdU8IeI2CByl@Bh28ptk4cDxE0gUSq2/gA "Perl 6 – Try It Online")
```
{($_=($^a..$^b).grep({.is-prime*!/<[14689]>/})[0,*-1])[1]??$_!!0}
```
[Try it](https://tio.run/##ZY1BCoMwFET3nuJLQ0lE408sRrHWg4iKtaEIlYrSgohnt2YhCN3MYubxptfDK1wt6zNq@Ia8SaxugnPzfmhI15mSKqWkrDkn5Z3x56B7OvN29Pqh7bRj@9dcXMIoLm7@wnJ0HU8ULBdFlpHKtnFZx3oCI6MAIFwTiMASOAGVLqiAWUdCoUGinVDBHyJig8hdgodtK7dNHg4QN4FEqdj6Aw "Perl 6 – Try It Online")
```
{($_=($^a..$^b).grep({.is-prime*!/<[14689]>/}))??.[0,*-1]!!0}
```
[Try it](https://tio.run/##ZY3RCoIwGIXv9xS/JLGJzn8znGLmg4iF2QghSZQCEZ99uQtB6OZcnPPxnV4Pr9gQ8hk1fGPeZKSb4Ni8HxpyM1P3llP3WnPuXu@MPwfd05m3Y9APbac9JzyX4hQnaXUJF8aKgpfoe4GoHAcXM9YTWBEFAOHbQASWwQGo9EFFjOwJhRZJNkJFf4hILSI3Ce62tVw3uTtAXAUSpWLmBw "Perl 6 – Try It Online")
```
{($_=grep {.is-prime*!/<[14689]>/},$^a..$^b)??.[0,*-1]!!0}
```
[Try it](https://tio.run/##ZY3RCoIwGIXv9xS/JOFkzn8znGLmg4iF2QghSZQCEZ99uQtB6OZcnPPxnV4Pr9gQ8hk1fGPeZKSb4Ni8HxpyM3vuLX8OuoeZt2PQD22nfSc8l@IUJ2l1CRfmXmvO3eudFgUvkfmBqBwHFzPWE1iLBwCC2UAEmsEBPMlARZTsCYUWSTZCRX@ISC0iNwnutrVcN7k7QFwFEqWi5gc "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with two placeholder parameters 「$a」 and 「$b」
(
$_ = # store the list in 「$_」 for later use
grep {
.is-prime
* # True * True == 1 (all others equal 0)
!/<[14689]>/ # doesn't contain a non-prime other than 0
},
$^a .. $^b # inclusive Range
) # is the list Truish (not empty)
?? .[0,*-1] # if so output the first and last values (from 「$_」)
!! 0 # otherwise return 0
}
```
[Answer]
# [Perl 5](https://www.perl.org/), 79 + 2 (`-ap`) = 81 bytes
```
map{$f=0|sqrt;1while$_%$f--;$s||=$_,$\=-$_ if!$f&&!/[14689]/}$F[0]..$F[1];$_=$s
```
[Try it online!](https://tio.run/##DcVBCsIwEAXQq7Tw7cqkM2BFCdm68wQ1hC4aDNQ2NgUXxqs7@jYvjevUiTyG9EawVPJz3Qy/7nEa4XcIShnkUiz8Hjer4KsYaoSmqdueD8fT2bUfXHpyWv9jZ@AtsghXTN8lbXGZs6hrp4lJ1JB@ "Perl 5 – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~142~~ ~~131~~ 125 bytes
```
import StdEnv
@a b#l=[n\\n<-[a..b]|and[gcd p n<2&&or[c==k\\k<-:"02357"]\\p<-[1..n-1],c<-:toString n]]
|l>[]=[hd l,last l]=[0]
```
Ungolfed:
```
import StdEnv
fn start finish
# primes
= [ n
\\
n <- [start..finish]
| and [ gcd p n == 1 && isMember c ['0','2','3','5','7']
\\
p <- [1..n-1],
c <-: toString n
]
]
| isEmpty primes
= [0]
= [hd primes, last primes]
```
[Try it online!](https://tio.run/##DY1BC4IwGEDv/YoPA08qcxFBuPBQh6Cbx22Hz81MnJ@iKwj87S2Pj/fgGdcghWG0b9fAgB2FbpjG2UPl7Y0@uxKh3jshSSkqUolZVusVycrWWJiACh7H4yyNEL1SfZGeI8YPx1OklZq2Ps8ySnOdmM34sfJzRy2Q1rvVXaQW8mXBJQ4XD24jpkPlcZsLKIEzxoDnjIWfeTpsl5DeH@H6JRw6s/wB "Clean – Try It Online")
[Answer]
# Pyth, ~~28~~ ~~25~~ 23 bytes
```
.xhM_BfP#I_M #+TjT;}FQ0
```
[Test suite.](https://pyth.herokuapp.com/?code=.xhM_BfP%23I_M+%23%2BTjT%3B%7DFQ0&input=100%2C200&test_suite=1&test_suite_input=1%2C100%0A%0A70%2C80%0A%0A190%2C200%0A%0A2000%2C2100%0A&debug=0&input_size=2) Returns [2003,2053] for the last test case, since 2053 is prime.
[Answer]
# Java 8, ~~165~~ ~~164~~ ~~163~~ 152 bytes
```
(a,b)->{for(;a<=b&p(a);a++);for(;b>a&p(b);b--);return a>b?"0":a+" "+b;}boolean p(int n){int i=1;for(;n%++i%n>0;);return!(n+"").matches("[02357]+")|i<n;}
```
-1 byte thanks to *@ceilingcat*.
**Explanation:**
[Try it online.](https://tio.run/##jVHBbsIwDL3vK7xITInSViloYlug@4Jx2RFxcErYwlq3agPTxPrtXVrYGaQ4lu3nZz17j0eMq9rSfvvV5wW2Lbyho9MdgCNvmx3mFlZDCPDuG0cfkPNQAYyG3wgdSl2w8FZAsISeY2REnJ12VcM1LpbmoeYoNEop9JgzGYZUaDVxLHRj/aEhwMy8MsVeUDJg0uhOm6oqLBLU4zwSp8G5ZXomoYmUbkKZ0v8U95wkYyIp0eeftuVsraazx/lGMvHrFqS7HqA@mMLl0Hr0wR0rt4UyyOVnaesNoDhrHZYAZZBD9nsM@Kg0LOGn9bZMqoNP6tDjC@JlQknO0yhVSlxDzVX0dB2VPqtoegNbwATgLXPTaHqdLUpn4nLQrv8D)
```
(a,b)->{ // Method with two integer parameters and String return-type
// (Input `a` is the lowest input, input `b` is the highest input)
for(;a<=b // Increase `a` as long as it's smaller than or equal to `b`,
&p(a);a++); // and it's not a prime, and not all of its digits are prime-digits
for(;b>a // Decrease `b` as long as it's larger than `a`,
&p(b);b--); // and it's not a prime, and not all of its digits are prime-digits
return a>b? // If `a` is now larger than `b`:
"0" // Return 0, because nothing is found
: // Else:
a+" "+b;} // Return the resulting `a` and `b`
// Separated method that'll result in true if the integer is NOT a prime number,
// or any of its digits are NOT prime numbers (excluding 0)
boolean p(int n){int i=1;for(;n%++i%n>0;);return!(n+"").matches("[02357]+")|i<n;}
```
] |
[Question]
[
# Goal
Given an input number, round it off to the nearest number with one significant figure.
# Requirements
## Input
* A floating point number.
* Assume the input number results in an output within the data type's limits (ie. ignore overflow errors.)
* 0 is an invalid input.
* Numbers that cannot be accurately represented in the floating point data type (eg. `"0.35"` being stored as `0.3499999`) do not have to be supported.
## Output
* The nearest number that consists of one non-zero digit and any number of zero digits.
* The result must support negative numbers and fractional numbers.
* When the input lies exactly between two possible outputs, round away from zero.
### Presentation
The focus is on the calculation rather than the presentation. The output may be a floating point data type. It may be text either in full or in scientific notation. If you find a loophole where presenting a certain way reduces your byte count, kudos to you!
### Examples
```
9
-3000
.2
0.2
-.2
7e12
5e-15
1e0
```
# Test Cases
```
Input Output
1 1
10 10
17 20
99 100
54321 50000
56789 60000
-123 -100
-789 -800
0.23 0.2
0.25 0.3
-0.25 -0.3
4.56e23 5e23
4.56e-23 5e-23
```
# Scoring
The code with the least byte-count after one week wins.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~19~~ 12 bytes
```
n=>$"{n:G1}"
```
[Try it online!](https://tio.run/##jc69CsIwFEDhvU8RxKEFG@xPqrW2i6CLTg7ONb2VQL2B3lSQ0mePoLga9w/OkRRK3YOVXU3E9OiRqY2S7KFVw061Qj8YvfOTDNz5fkC5bfRw7WBBpld4q1hbWiyr@WzEzSGaZrbwvnqnkXQH/NIrA0eF4Le@SJM4CoLilwlFtlrnDpS7wJLHiZsI18sfJuUiA2fsrcIPmyb7Ag "C# (.NET Core) – Try It Online")
Examples:
```
Input Output
----------------
54321 5E+04
-56789 -6E+04
99 1E+02
0.23 0.2
0.25 0.3
-0.25 -0.3
4.56e23 5E+23
4.56e-23 5E-23
```
With the new versions of C# we also got shorter ways to achieve this, as Calculuswhiz wisely noted in the comments.
[Answer]
## Javascript, 19 bytes
```
x=>x.toPrecision(1)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
1&V
```
[Try it online!](https://tio.run/##y00syfn/31At7P9/S0sA) Or [verify all test cases](https://tio.run/##y00syfmf8N9QLey/S8h/Qy5DAy5Dcy5LSy5TE2MjQy5TM3MLSy5dQyNjLl0Qy0APyAISply6YNJEz9QsFSgEpnWNjAE).
Test case `0.25` fails for the compiler running in Octave on TIO, but works in Matlab on Windows:
[](https://i.stack.imgur.com/rL1JA.gif)
The different behaviour is caused by Octave's/Matlab's `sprintf` function using either "banker's rounding" or ".5 away from zero" rounding, depending on platform. More information and tests can be found [here](https://savannah.gnu.org/bugs/index.php?51515).
---
For **6 bytes**,
```
1t3$Yo
```
works both on Octave and on Matlab. [Verify all test cases](https://tio.run/##y00syfmf8N@wxFglMv@/S8h/Qy5DAy5Dcy5LSy5TE2MjQy5TM3MLSy5dQyNjLl0Qy0APyAISply6YNJEz9QsFSgEpnWNjAE).
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~63~~ 62 bytes
```
1`[1-9]
$*#
#\.?[5-9]
#$&
T`d`0`#[\d.]+
0(\.?)#{10}
1$1
#+
$.0
```
[Try it online!](https://tio.run/##LY67DsIwDEX3@xspiIdi2W3dkomRH2ArSEGiAwsDYkN8e7ETMpxznVxLec3vx/O2rDanvEieJKYrml1AuNBxUp9Cs8Y53zPnMF3udN2DN/a4DR/hL6QRhD0a4mURCENGpATtu1agw3hIiNJ2iJ6YLBkUsbAnHeZ2rI4WhETm5EVm7nQ8DN7nlGw0wgOVhOra/bsoUaHLaEK9tsOVXJe1V3eVU8lhf0GZeuUC/gE "Retina – Try It Online")
[Answer]
# [PHP](https://php.net/), 45 bytes
```
<?=round($x=$argv[1],-floor(log10(abs($x))));
```
[Try it online!](https://tio.run/##K8go@P/fxt62KL80L0VDpcJWJbEovSzaMFZHNy0nP79IIyc/3dBAIzGpGCipCQTW////N9AzMgUA "PHP – Try It Online")
Same method as my python 2 answer.
Also seems to correctly handle `0.35`, which puts it a peg above the JS answer too :D
[Answer]
# T-SQL, 27 bytes
```
SELECT FORMAT(i,'G1')FROM t
```
Using the same .Net formatting code as [Carlos Alejo's C# answer](https://codegolf.stackexchange.com/a/133506/70172). Input is from *float* column **i** in pre-existing table **t**, [per our IO standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341)
Test cases:
```
Input Output
------------ --------
1 1
10 1E+01
17 2E+01
99 1E+02
54321 5E+04
56789 6E+04
-123 -1E+02
-789 -8E+02
0.23 0.2
0.25 0.3
-0.25 -0.3
4.56E+23 5E+23
4.56E-23 5E-23
```
(Pretty handy that I can pre-load the input table with all these values and run them at once.)
[Answer]
# Excel 2016, 36
* Input A1.
* A2: `=10^INT(LOG10(ABS(A1`
* Result: `=A2*ROUND(A1/A2,`
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
lambda x:round(x,-int(floor(log10(abs(x)))))
from math import*
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCqii/NC9Fo0JHNzOvRCMtJz@/SCMnP93QQCMxqVijQhMEuNKK8nMVchNLMhQycwvyi0q0/hcUAZUrpGnomltYanLBeEamCLaBnpExCg9JzkTP1CwVKP3/v4GesSkA "Python 2 – Try It Online")
Not used to python golfing, but this works.
Fails on `0.35` due to floating point inaccuracies.
Thanks to Anders Kaseorg for pointing out that this works correctly in Python 2
[Answer]
# [Guile](https://www.gnu.org/software/guile/), 23 bytes
```
(format #t"~,0e"(read))
```
[Try it online!](https://tio.run/##K07OSM1N1U0vzcxJ/f9fIy2/KDexREG5RKlOxyBVSaMoNTFFU/P/fwM9I1MA "Guile – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 15 bytes
```
printf"%.1g",<>
```
[Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvJE1JVc8wXUnHxu7/fxM9U7NUI2MA "Perl 5 – Try It Online")
[Answer]
# [Zsh](http://zsh.sourceforge.net/), 14 bytes
Port of the perl answer. [Try it Online!](https://tio.run/##qyrO@P@/oCgzryRNQVXPMF1BxfD////G8aYGBvEGBgZ6QGwIAA)
```
printf %.1g $1
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 24 bytes
```
: f 1 set-precision f. ;
```
[Try it online!](https://tio.run/##TctNDoIwEAXgfU/xwr5NfyhYSbwMTJWNTAqev1ZjpbOZfPPmxS0dD3mPn5XzFREGOx2SE83rvm5PRIWpBIy4vBhGw0KXY1oYqgPkDV1pzQmTMIQ6LIymBmODEBr43tlfr2AYL6FCGuuovsl/UKBVkxT48@0Ui175gaxrIL/i/AY "Forth (gforth) – Try It Online")
Input is expected on the floating point stack. Output is to stdout
I don't like making changes to the global (for this instance) precision of the floating point output functions, but it saves a lot of bytes to not have to restore the previous value at the end. Does not output in engineering or scientific notation, regardless of input.
*Note: For some reason, the tio interpreter converts `0.25` to `0.2`, while my local installation converts `0.25` to `0.3`. I'm not entirely sure why this is, but since I get the correct result locally, I'm leaving my answer as-is*
```
: f \ start a new word definition
1 set-precision \ set the floating point output words to use 1 significant digit
f. \ output the top of the floating point stack
; \ end the word definition
```
] |
[Question]
[
Alright, my second attempt at a code golf, let's see how this goes.
Pretend you have a 3x3 grid of digits, from 0 to 8:
```
0 | 1 | 2
---+---+---
3 | 4 | 5
---+---+---
6 | 7 | 8
```
Return the neighbors the input has as indexes of the array.
**Rules:**
* It's code golf, so shortest answer wins.
* The pretend array's index can start at 0 or 1. (all examples use 0 though)
* The submission can be just a procedure/function/method, but an example would be nice
* The returned value can be in any order (if the input is `0` you could output either `13` or `31`)
* If you want, the output can be a list of numbers, e.g. `[0,4,6]` instead of `046`
* Diagonals don't count, as shown by the examples.
**Examples:**
```
0 -> 13
3 -> 046
4 -> 1357
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~17~~ 16 bytes
```
9:qWIe1Y6Z+i)BPf
```
The array is 1-based, that is, contains numbers from `1` to `9`.
[Try it online!](https://tio.run/nexus/matl#@29pVRjumWoYaRalnanpFJD2/78pAA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S/hvaVUY7plqGGkWpZ2p6RSQ9t8l5L8hlxGXMZcJlymXGZc5lwWXJQA).
### Explanation
Consider input `2` as an example.
```
9:q % Push [0 1 2 ... 8]
% STACK: [0 1 2 ... 8]
W % Rise to 2, element-wise
% STACK: [1 2 4 ... 256]
Ie % Reshape as 3-row matrix (column-major order)
% STACK: [1 8 64;
2 16 128;
4 32 256]
1Y6 % Push [0 1 0; 1 0 1; 0 1 0]
% STACK: [1 8 64;
2 16 128;
4 32 256],
[0 1 0;
1 0 1;
0 1 0]
Z+ % Convolution, maintaining size
% STACK: [10 81 136;
21 170 336;
34 276 160]
i % Take input, n
% STACK: [10 81 136;
21 170 336;
34 276 160],
2
) % Get n-th entry (1-based; column-major order)
% STACK: 21
B % Convert to binary
% STACK: [1 0 1 0 1]
P % Flip
% STACK: [1 0 1 0 1]
f % Find: gives indices of nonzeros. Implicitly display
% STACK: [1 3 5]
```
[Answer]
## Mathematica, 32 bytes
```
GridGraph@{3,3}~AdjacencyList~#&
```
Uses a graph instead of an array. `GridGraph@{3,3}` constructs a 3x3 grid-shaped graph, shown below, which Mathematica helpfully labels with the numbers 1–9 for the vertices by default. Then `~AdjacencyList~#&` tells you the neighbours of a vertex.
[](https://i.stack.imgur.com/bs3FK.png)
[Answer]
# Mathematica, 40 bytes
```
{24,135,26,157,2468,359,48,579,68}[[#]]&
```
1-indexed. Just looks up the answer. Can someone do better in Mathematica?
[Answer]
# Octave, ~~42~~ ~~40~~ 39 bytes
```
@(n,x=~e(3),y=x(n)=1)find(bwdist(x)==1)
```
1-based index.
[Verify all test cases.](http://octave-online.net/#cmd=arrayfun(%40(n%2Cx%3D%7Ee(3)%2Cy%3Dx(n)%3D1)find(bwdist(x)%3D%3D1)%2C1%3A9%2C%27Un%27%2C0))
Explanation:
```
x=~e(3); % create a 3*3 matrix of zeros
x(n)=1; % set the element with index n to 1
d=bwdist(x); % compute the distance transform of the matrix
find(d == 1) % find where the distance is 1.
```
Example: `n = 2`
```
x =
0 0 0
1 0 0
0 0 0
```
(In Octave data is stored column-wise.)
```
d =
1.00000 1.41421 2.23607
0.00000 1.00000 2.00000
1.00000 1.41421 2.23607
```
logical index where distance is 1:
```
d == 1
1 0 0
0 1 0
1 0 0
find(d ==1)
1
3
5
```
[Answer]
# Python 2, 71 bytes
```
lambda n:filter(abs,[(n-3)*(n>3),(n+3)*(n<7),~-n*(n%3!=1),-~n*(n%3>0)])
```
1-indexed
[Try it online!](https://tio.run/nexus/python2#JYpBCsIwEADvvmItCLu6kYYcCsXmI@ohxUYW2lVibqX9eiw6pxmY2N3KGKb@EUDbKGMeEob@w1dU4@iI6h0x6unnl4Z4NbrZwe07S2zWf/ia7lTiK4GAKKSgzwEt25raHWy8k2jGal7AeJiX6rytU8goHFGIqHwB "Python 2 – TIO Nexus")
---
Getting the result from a predefined list of results is shorter (46 bytes):
```
[13,204,15,406,1357,248,37,468,57].__getitem__
```
0-indexed
[Try it online!](https://tio.run/nexus/python3#DcqxDoMgFAXQvV/x4gTJrREBsU3aH1FDHMC8QdoQNuO3o2c@8TPXSWn0nYGyMN0Apa1Db0ZoBzOMsG5pvd9C4RJ272v8ZWLiRHlNWxAv@X7Q7Z85FdEcJz2/dJxNe799LYIRBUsp6wU "Python 3 – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 13 bytes
```
9Ḷ,d3ạ/S€=1T’
```
[Try it online!](https://tio.run/nexus/jelly#@2/5cMc2nRTjh7sW6gc/alpjaxjyqGHm/8PtQLb7//8GOgrGOgomAA "Jelly – TIO Nexus")
### How it works
```
9Ḷ,d3ạ/S€=1T’ Main link. Argument: n (0, ..., 8)
9 Set the return value to 9.
·∏∂ Unlength; yield [0, ..., 8].
, Pair; yield [[0, ..., 8], n].
d3 Divmod 3; yield [[[0, 0], ..., [2, 2]], [n:3, n%3]]].
·∫°/ Reduce by absolute difference, yielding
[[|0 - n:3|, |0 - n%3|], ..., [[|2 - n:3|, |2 - n%3|]].
S€ Sum each, yielding
[|0 - n:3| + |0 - n%3|, ..., [|2 - n:3| + |2 - n%3|].
=1 Compare the sums with 1.
T Truth; yield all 1-based indices of 1.
’ Decrement to yield all 0-based indices of 1.
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~74 71~~ 68 bytes
```
f n=[x|x<-[n-3,n-1..n+3],0<x,x<10,gcd 3x<2||n-1/=x,gcd 3n<2||n+1/=x]
```
[Try it online!](https://tio.run/nexus/haskell#Jc2xDoIwFIXhVzkhDpC2CHYyaX0CmRhrB6JBGLgQxXiHvnuluJ18/3BiD7KOAxvlSGlJqi5LEtrLyrBkU1fyeX9AszmFsMWj5T/QDiKBj1M3EiymbmmQ3xjqguWztuvrSjjgPcxfMIRAlkqW1m55Dy4KuO3y7OMP "Haskell – TIO Nexus") Uses a 1-indexed grid. Example usage: `f 3` returns `[2,6]`.
Edit: Saved ~~3~~ 6 bytes thanks to √òrjan Johansen!
---
For ~~77~~ 75 bytes, the following function `#` works for an arbitrary grid size `m`:
```
n#m=[x|x<-[n-m,n-1,n+1,n+m],0<x,x<=m*m,gcd x m<m||n-1/=x,gcd n m<m||n+1/=x]
```
[Try it online!](https://tio.run/nexus/haskell#LczBCoJAEAbge0/xox203bWMjrs9gZ06moGklIcZRY2G8N3NlQYGfr4Z/plDcrlMYk3OhjSbVLPyS4U@WNFiHe1IPx8VBGRpmpaXvZNV@C/KSzFT2TAcqnaDZYbmW8Ma9HVZZbwSld0F0U1gzuje43XsM8YWw6v9LO1KIfCXwKfVIkG49sQx8jRJfLwfi/n0Aw "Haskell – TIO Nexus")
For each `n` the list `[n-m,n-1,n+1,n+m]` contains all four neighbours. For each entry `x` in this list we check `-1<x` and `x<m*m` to make sure `x` is not above or below the grid, `mod n 3>0||n-1/=x` to enforce the left grid border and `mod(n+1)m>0||n+1/=x` for the left border.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~51 48~~ 45 bytes
```
->a{[a+3,a-3][a/6..a/3]+[a+1,a-1][a%-3..a%3]}
```
[Try it online!](https://tio.run/nexus/ruby#S7P9r2uXWB2dqG2sk6hrHBudqG@mp5eobxyrDRQzBIoZAsVUdY2BgqrGsbX/C0pLihXSog1itex1uKAcQ2SOETLHGJljgswxReaYIXPMkTkWIM5/AA "Ruby – TIO Nexus")
Create 2 arrays, with vertical and horizontal neighbours, then select one or more of them.
### Ruby hardcoded, 44 bytes
```
->a{%w(13 024 15 046 1357 248 37 468 57)[a]}
```
... Not worth it.
[Answer]
# Python 2, 51 bytes
```
lambda x:[x+3,x-3][x/6:x/3+1]+[x+1,x-1][x%-3:x%3+1]
```
Based on a previous version of my [Ruby](https://codegolf.stackexchange.com/a/113987/18535) answer, I found it interesting because it was mostly the same code, using a different trick, and produces the same result. Getting this one right helped me golf the ruby answer a little more.
Basically, ruby has it shorter because the array slice index are inclusive, python needs a `+1` to compensate.
### Explanation
Get the 2 arrays (vertical and horizontal neighbours), then select one or both based on some calculations.
[Answer]
# C, ~~100~~ ~~92~~ ~~91~~ ~~83~~ ~~78~~ 74 bytes
```
p(n){putchar(n+48);}f(n){n>3&&p(n-3);n<7&&p(n+3);n%3&&p(n+1);--n%3&&p(n);}
```
1-indexed. Thanks to @Neil for saving 4 bytes.
[Try it online!](https://tio.run/nexus/c-gcc#@1@gkadZXVBakpyRWKSRp21ioWldmwYSy7MzVlMDyuoaa1rn2ZiD2dogtipEXNtQ01pXF8YD6vqfmVeikJuYmaehyVXNxZmmAVQAM1g9Jk9d0xokaIpN0AJDsPa/IZcRlzGXCZcplxmXOZcFlyWXoQEA)
**Hardcoded version, 56 bytes**
```
l[]={13,204,15,406,1357,248,37,468,57};
#define L(n)l[n]
```
0-indexed
[Answer]
# Java 7, 63 bytes (hardcoded)
```
int c(int i){return new int[]{31,420,51,640,7531,842,73,864,75}[i];}
```
0-indexed
(Reversed order output because `024` and `046` aren't valid integers.)
~~Still working on a non-hardcoded version, but~~ I can assure you it won't be shorter..
[Try it here.](https://tio.run/nexus/java-openjdk#fY3LCoMwEEX3fsUsEwjiIz7Ab@jKpbhIU1sGNIoZW4rk2@2UdtvexcCdA@fa0XgPJ9ijCMCTIbRwoCOw4n1R7utA2@rADQ/gT9fveap0lqgiVaVOVFVwr3WmqlzVpeYeOuybcLBv2c4j@77a@4wXmAw6cUVnRmhpRXfrejCS54HTPj0NUzxvFC/MaHTCikTK5jfN/1L9oSEKxws)
---
**82 bytes**
```
String c(int n){return""+(n>3?n-3:"")+(n<7?n+3:"")+(n%3>0?n+1:"")+(--n%3>0?n:"");}
```
1-indexed
Based on [*@Steadybox*' C answer](https://codegolf.stackexchange.com/a/113910/52210)
[Try it here.](https://tio.run/nexus/java-openjdk#fY7BCoJAEEDvfsWwEOwiSmIRaOgXdPIYHbbNYmEdxR2DEL/dJrRjze3Ng3ljnPYeTtoijEEA4EmTNTBX1Ft8gJEWCVCNfU1Dj0KEEou0xCjNhFAMx0OJ4Rc2abFlTBaMonXxwXyaAbrh6vj42ni29gYNl@XdonawJM8X0Ip/AZ7q5alu4naguGNHDqWRiVL5b7v7a/eLnYJpfgM)
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 9 bytes
```
kd⁻ṪÞo1⁾i
```
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCJrZOKBu+G5qsOebzHigb5pIiwiIiwiMyIsIjMuNC4xIl0=)
```
kd⁻ṪÞo1⁾i­⁡​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠⁠⁠⁠‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠⁠‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‏​⁡⁠⁡‌­
i # ‎⁡value of program at index of input
kd⁻Ṫ # ‎⁢digits 0-8 in a 3x3 square
Þo # ‎⁣grid neighbors
1⁾ # ‎⁤flatten by 1
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 34 bytes
```
⌷∘42 531 62 751 8642 953 84 975 86
```
1-indexed, hardcodes the values :(
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Uc/2Rx0zTIwUTI0NFcyMFMxNDRUszIB8S1NjBQsTBUtzUyD/v9ujtgnEKeV61DcVqNhNwRDOMoGzTP8DAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# JavaScript + lodash, 71 bytes
```
f=a=>_.range(9).filter(b=>a>b?f(b).includes(a):[,1,,1][b-a]&&b%3|a%3<2)
```
[Answer]
## Batch, 116 bytes
```
@set c=cmd/cset/a%1
@set/ar=%1%%3
@if %1 gtr 2 %c%-3
@if %r% gtr 0 %c%-1
@if %r% lss 2 %c%+1
@if %1 lss 6 %c%+3
```
0-indexed.
] |
[Question]
[
## Introduction
Alphabet challenges are in our DNA, so let's show it.
## Challenge
Print the following the text exactly:
```
AaBbCc cCbBaA
BbCcDd dDcCbB
EeFfGg gGfFeE
HhIiJj jJiIhH
KkLlMm mMlLkK
NnOoPp pPoOnN
QqRrSs sSrRqQ
TtUuVv vVuUtT
WwXx xXwW
Yy yY
ZZ
zz
ZZ
Yy yY
WwXx xXwW
TtUuVv vVuUtT
QqRrSs sSrRqQ
NnOoPp pPoOnN
KkLlMm mMlLkK
HhIiJj jJiIhH
EeFfGg gGfFeE
BbCcDd dDcCbB
AaBbCc cCbBaA
```
## Rules
* You must match the case of each letter
* Trailing and/or leading newlines and/or spaces are allowed
## Winning
Shortest code in bytes wins.
[Answer]
# Vim (no external tools), 106 bytes
Newlines for clarity:
```
:h<_↵↵↵YZZPllabc♥
:s/./\u&&/g↵
qa6li↵♥q7@a3i ♥fY
i↵ →→↵ →↵→ð♥
ʌHA ♥9l
qbmaʌ99jY$P`ah@bq@b
y11G:g//m0↵P
```
Here `↵` is Return, `→` is Right, `♥` is Escape, `ʌ` is CTRL-V, and `ð` is Delete.
[](https://i.stack.imgur.com/FXQlS.gif)
[Answer]
## Python 2, 230 bytes
```
s='';m=['AaBbCc','BbCcDd','EeFfGg','HhIiJj','KkLlMm','NnOoPp','QqRrSs','TtUuVv',' WwXx',' '*7+'Yy',' '*9+'Z'];
p=lambda l:l.ljust(10)+l[::-1].rjust(10)+'\n';
for l in m:s+=p(l);
s+=' '*9+'zz\n';
for l in m[::-1]:s+=p(l)
print s
```
[Answer]
## PowerShell v2+, ~~175~~ ~~169~~ ~~163~~ 154 bytes
```
($x=(-join(65..67+66..86|%{$_;32+$_}|%{[char]$_})-split'(.{6})'-ne'')+' WwXx'+' Yy'+(' '*9+'Z')|% *ht 10|%{$_+-join$_[9..0]})
' '*9+'zz'
$x[10..0]
```
[Try it online!](https://tio.run/##LY3LCoMwFET3fkUWkZsYcoktppXS7@hDREoRtAQVFUx9fHuq0lkdhsNMUw952xW5Mc4xaq9MfuqyYjpC1CehNeJZz/5Es8vxIGi2rJy8i1ebrsxl15iyB4aTXjjIKgfgAgght@FuYactjy8IBgSCWMAT@OyToOhJqPZdsR/SLIkRVbpw7y@OI3jUJqHaaud@ "PowerShell – Try It Online")
Abuses the fact that default `Write-Output` at the end of execution inserts a newline between elements.
The first line constructs the branches. We loop over two ranges corresponding to the ASCII values for the capital letters, each iteration output a `char` array of that letter and that letter `+32` (which is the lowercase ASCII point). That's `-join`ed together into one long string, then `-split` on every six elements (encapsulated in parens so they're preserved), followed by a `-ne''` to pull out the empty elements as a result of the split, thus forming an array of strings.
These strings in an array get array-concatenation to add on the `WwXx`, `Yy`, and `Z` elements, then a PadRig`ht 10` to make them all the appropriate width. At this point we have an array of strings like the following (one element per line).
```
AaBbCc
BbCcDd
EeFfGg
HhIiJj
KkLlMm
NnOoPp
QqRrSs
TtUuVv
WwXx
Yy
Z
```
That whole array is piped to another loop to construct the mirrored strings with `-join` and array-reversing `[9..0]`.
```
AaBbCc cCbBaA
BbCcDd dDcCbB
EeFfGg gGfFeE
HhIiJj jJiIhH
KkLlMm mMlLkK
NnOoPp pPoOnN
QqRrSs sSrRqQ
TtUuVv vVuUtT
WwXx xXwW
Yy yY
ZZ
```
We save the resulting strings into `$x` and enclose in parens to also place a copy on the pipeline.
The next line places the `zz` string on the pipeline, then the `$x` array in reverse order. All of those are left on the pipeline and output is implicit.
```
PS C:\Tools\Scripts\golfing> .\alphabet-chromosome.ps1
AaBbCc cCbBaA
BbCcDd dDcCbB
EeFfGg gGfFeE
HhIiJj jJiIhH
KkLlMm mMlLkK
NnOoPp pPoOnN
QqRrSs sSrRqQ
TtUuVv vVuUtT
WwXx xXwW
Yy yY
ZZ
zz
ZZ
Yy yY
WwXx xXwW
TtUuVv vVuUtT
QqRrSs sSrRqQ
NnOoPp pPoOnN
KkLlMm mMlLkK
HhIiJj jJiIhH
EeFfGg gGfFeE
BbCcDd dDcCbB
AaBbCc cCbBaA
```
*-9 bytes thanks to mazzy.*
[Answer]
# [Python 2](https://docs.python.org/2/), 156 bytes
```
r=('AaBbCc.BbCcDd.EeFfGg.HhIiJj.KkLlMm.NnOoPp.QqRrSs.TtUuVv. WwXx.%8cy.%10c.%10c'%(89,90,'z')).split('.')
for k in r+r[-2::-1]:s='%-10s'%k;print s+s[::-1]
```
[Try it online!](https://tio.run/##Hcm5DoIwGADg3afo0hQC/AEmwDB43/eZEAdFEQRLbeuBL4@R5Vs@Vsg4p3ZZcl8hjWPz1ArhT/sMnUs36l2hHw@S4Q1G6Tib3GFKZ/mcweKx5CsBa7l5bl@AENq99x/ATlgAtsywgmDFcXXX1MmXqCoIliVSIUDUWpRzlKKEIq7xwLA9z7AOnvAJNixTEJzWGU@oREITQXVl@QM "Python 2 – Try It Online")
Maybe the formula `512/(i**4+47)-1` is of interest to future golfers: it maps the integers around 0 to $$\cdots,-1,-1,0,3,7,9,\fbox{9},9,7,3,0,-1,-1,\cdots$$
which encodes how many spaces to prepend to each line (`(-1)*' '` being equal to `0*' '`).
[Answer]
# Python 2, ~~331~~ ~~241~~ 229 bytes
~~Will golf it more later.~~
```
l=("AaBbCc|BbCcDd|EeFfGg|HhIiJj|KkLlMm|NnOoPp|QqRrSs|TtUuVv| WwXx|%sYy"%(" "*7)).split("|");n=0;v=1;p='for i in([8]*8+[6,2])[::v]:print l[n]+" "*i+l[n][::-1];n+=v';exec p;v=-1;n=9;print"{0}ZZ\n{0}zz\n{0}ZZ".format(" "*9);exec p
```
[Answer]
# Lua, 212 Bytes
```
s=([[ Z
Yy
WwXx
TtUuVv_QqRrSs_NnOoPp_KkLlMm_HhIiJj_EeFfGg_BbCcDd_AaBbCc ]]):gsub("_"," \n")S=" zz"for z in s:gmatch"[%w ]+"do k=z..z:reverse()S=k..'\n'..S..'\n'..k end print(S)
```
Simple enough, based off of TimmyD's answer, kind of.
Builds the top left arm using a really poorly compressed chunk,
then does both mirrors at once around a 'zz', and prints.
[Try it on Repl.It](https://repl.it/DdVv "Try it on Repl.it")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~48~~ ~~46~~ ~~40~~ ~~38~~ 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ž3ô8.DƵJ6XD)bTj»0ð:1žRAu¦«Dl.ιS.;º.∊
```
-2 bytes (and the opportunity for 10 more with this alternative approach) thanks to *@MagicOctopusUrn*.
[Try it online.](https://tio.run/##AToAxf9vc2FiaWX//8W9M8O0OC5ExrVKNlhEKWJUasK7MMOwOjHFvlJBdcKmwqtEbC7OuVMuO8K6LuKIiv//)
**Explanation:**
```
Ž3ô # Push compressed integer 1008
8.D # Duplicate it 8 times
ƵJ # Push compressed integer 120
6 # Push 6
XD # Push 1 twice
) # Wrap all into a list
b # Convert each to binary
Tj # Add leading spaces to each binary-string to make them size 10
» # Then join all strings by newlines
0ð: # Replace all 0s with spaces
žR # Push the string "ABC"
Au¦« # Merge the uppercased alphabet minus the first "A" with it
Dl # Create a lowercase copy
.ι # Intersect the uppercase and lowercase strings: "AaBbCcBb..."
S # Convert it to a list of characters
1 .; # Replace every 1 with each of these characters in the same order
º # Then mirror everything vertically without overlap,
.∊ # and horizontally with the last line overlapping
# (and output the result implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž3ô` is `1008` and `ƵJ` is `120`.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~42~~ ~~41~~ ~~38~~ 35 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
înáöêòé{V║»╧å╓ä¥ì√‼╦▓°nlΓΣ▌ê9t☻*$╢√
```
[Run and debug it](https://staxlang.xyz/#p=8c6ea0948895827b56baafcf86d6849d8dfb13cbb2f86e6ce2e4dd883974022a24b6fb&i=&a=1&m=2)
*Update:* There was a bug in the 41 byte solution. (yes, even though it has no input) While fixing it, I found 3 more bytes to shave.
*Update again:* There's competition afoot, so I removed 3 more contingency bytes.
**Explanation:** (of a different, yet identically sized solution)
```
VA3( "ABC"
VAD2T "BCD...VWX"
+3/ concatenate and split into groups of 3
'Y]+ concatenate ["Y"]
{cv\$m map each string using: copy, lowercase, zip, flatten
.ZzM+ concatenate ["Z", "z"]
|p palindromize list of strings
m map each string _ using the rest of the program and implicitly print output
c%Nh6+H (-len(_)/2 + 6) * 2
) left-pad (npm lol amirite) to length
A( right-pad to 10
:m mirror (a + a[::-1])
```
[Run this one](https://staxlang.xyz/#c=VA3%28+++++%09%22ABC%22%0AVAD2T++++%09%22BCD...VWX%22%0A%2B3%2F++++++%09concatenate+and+split+into+groups+of+3%0A%27Y]%2B+++++%09concatenate+[%22Y%22]%0A%7Bcv%5C%24m+++%09map+each+string+using%3A+copy,+lowercase,+zip,+flatten%0A.ZzM%2B++++%09concatenate+[%22Z%22,+%22z%22]%0A%7Cp+++++++%09palindromize+list+of+strings%0Am++++++++%09map+each+string+_+using+the+rest+of+the+program+and+implicitly+print+output%0A++c%25Nh6%2BH%09%28-len%28_%29%2F2+%2B+6%29+*+2%0A++%29++++++%09left-pad+%28npm+lol+amirite%29+to+length%0A++A%28+++++%09right-pad+to+10%0A++%3Am+++++%09mirror+%28a+%2B+a[%3A%3A-1]%29&i=&a=1&m=2)
[Answer]
# [Matricks](https://github.com/jediguy13/Matricks), 105 bytes (noncompeting)
Whoa, I found a lot of bugs. The only hard part of this challenge was the cross in the middle. That makes almost half the byte count.
Run with the `-A 1` flag
```
m+/c2+66+*r3*32%c2 7 6v{k-{}1z-L1Q}u{q-Lc2k+{}2b0b0b0a[a0a0u[a89a121]a[u0u90]]}a{Y}u[mQc9a122a122]u{z1cX}
```
Explanation:
```
m+/c2+66+*r3*32%c2 7 6 # Construct the "normal" block
v{k-{}1z-L1Q} # Add the "abnormal" part above
u{q-Lc2k+{}2b0b0b0a[a0a0u[a89a121]a[u0u90]]} # Make the 1/4 of the weird diagonal
a{Y}u[mQc9a122a122]u{z1cX} # Mirror the block just created, adding
# lowercase zs in between halves
```
Another bug I haven't fixed yet is that the last part, `u{z1cX}` doesn't work when you put the cut after the `X`. Will investigate/fix.
[Answer]
# [///](http://esolangs.org/wiki////), 229 bytes
```
/*/\/\///^/ *0/AaBbCc^cCbBaA
*1/BbCcDd^dDcCbB
*2/EeFfGg^gGfFeE
*3/HhIiJj^jJiIhH
*4/KkLlMm^mMlLkK
*5/NnOoPp^pPoOnN
*6/QqRrSs^sSrRqQ
*7/TtUuVv^vVuUtT
*8/ WwXx xXwW
*9/ Yy yY
/0123456789^ ZZ
^ zz
^ ZZ
9876543210
```
[Try it online!](http://slashes.tryitonline.net/#code=LyovXC9cLy8vXi8gICAgICAgICowL0FhQmJDY15jQ2JCYUEKKjEvQmJDY0RkXmREY0NiQgoqMi9FZUZmR2deZ0dmRmVFCiozL0hoSWlKal5qSmlJaEgKKjQvS2tMbE1tXm1NbExrSwoqNS9Obk9vUHBecFBvT25OCio2L1FxUnJTc15zU3JScVEKKjcvVHRVdVZ2XnZWdVV0VAoqOC8gICBXd1h4ICAgICAgeFh3VwoqOS8gICAgICAgWXkgIHlZCi8wMTIzNDU2Nzg5XiBaWgpeIHp6Cl4gWloKOTg3NjU0MzIxMA&input=)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 150 bytes
```
($x='AaBbCc
BbCcDd
EeFfGg
HhIiJj
KkLlMm
NnOoPp
QqRrSs
TtUuVv
WwXx
Yy
Z'-split'
'|% *ht 10|%{$_+-join$_[9..0]})
' '*9+'zz'
$x[10..0]
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0OlwlbdMdEpyTmZC0S4pHC5prqluadzeWR4ZnplcXln@@T45nL55fnnBxRwBRYGFQUXc4WUhJaGlXEpKCiEl0dUgGgQiKyEsRQUotR1iwtyMkvUudRrVBW0MkoUDA1qVKtV4rV1s/Iz81Tioy319AxiazW51BXUtSy11auq1LlUKqINDUDC//8DAA "PowerShell – Try It Online")
[Answer]
# Brainfuck, 456 bytes
```
+[>-[-<]>>]>[->++>++++++>++++>+<<<<]>>+>+>------<.<.>+.<+.>+.<+.<........>.>.<-.>-.<-.-->-.-->.>+++++++[-<<+++.<+++.>+.<+.>+.<+.<........>.>.<-.>-.<-.>-.>.>]<<<<...>>+++.<+++.>+.<+.<......>.>.<-.>-.>.<<<.......>>++.<++.<..>.>.>.<<<.........>>+..>.<<<.........>+..>>.<<<.........>>..>.<<<.......>>-.<-.<..>.>.>.<<<...>>--.<--.>+.<+.<......>.>.<-.>-.>.>+++++++[-<<---.<---.>+.<+.>+.<+.<........>.>.<-.>-.<-.>-.>.>]<<-.<-.>+.<+.>+.<+.<........>.>.<-.>-.<-.>-.
```
[Try it online!](https://tio.run/##lU9RCkIxDDtQSU9QcpHxPlQQRPBDeOef6TZFCqJ2I13TtF2P98Pldt5P196tEQ2xkRsbaKabxgkhU04vYlh4OM3DFoYvo07AiUSAA3x1M40IOR/wvV6oeMvpmWIpjVoiH89OqU5xqjg1r9zIeqWSqSovPce3SkexSePzr97XxxTjn/Vn9Iu@9wc "brainfuck – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 215 bytes (Non-Competing)
```
p=lambda l:l.ljust(10)+l[::-1].rjust(10)
a=("AaBbCc|BbCcDd|EeFfGg|HhIiJj|KkLlMm|NnOoPp|QqRrSs|TtUuVv| WwXx|%sYy|%sZ"%(7*' ',9*' ')).split('|')
print('\n'.join([p(x)for x in a]+[' '*9+'zz']+[p(x)for x in a[::-1]]))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8A2JzE3KSVRIccqRy8nq7S4RMPQQFM7J9rKStcwVq8IJsKVaKuh5JjolOScXAMiXFJqXFPd0tzTazwyPDO9smq8s31yfHNr/PL88wMKagILg4qCi2tCSkJLw8pqFBQUwssjKmpUiyMrgUSUkqqGuZa6grqOJYjU1NQrLsjJLNFQr1HX5CooyswDMmPy1PWy8jPzNKILNCo00/KLFCoUMvMUEmO1o4FatCy11auq1IEcVFmIq2M1Nf//BwA "Python 3 – Try It Online")
Takes some ideas from the two Python 2 solutions, but applies them to an approach using join() that seems to save quite a few bytes. It's possible that this can be golfed further; I might revisit this later.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~177 ...~~ 145 bytes
```
puts r=(("%s%s%s\n"*8+"%5s%s\n%9s\n%11s")%[*?a..?c,*?b..?z].map{|x|x.upcase+x}).lines.map{|l|l=l.chop.ljust 10;l+l.reverse},"%11s"%"zz",r.reverse
```
[Try it online!](https://tio.run/##NYxRCsIwEESvUhYCbRIW@yEoUnIQ9aMNAZW1hmwjNbZnj7YiAzOPGZgQu1fOPg5chKYsQfCiUw9yp0BsVxb7xeqaoRJHaVpEY7U03TfTGe@tf0/jNGL0tmWnxrlCuvaOfwtN1BDay8Mj3SIPRb05kCIM7ukCu1nD@iwgJdDhX@f8AQ "Ruby – Try It Online")
[Answer]
# Bubblegum, 168 bytes
```
00000000: 6dd1 c712 8230 1006 e0fb 3e45 5e85 264d m....0....>E^.&M
00000010: 7a51 b8a1 14e9 1d91 a757 4632 ce38 9bd3 zQ.......WF2.8..
00000020: e6cb a4ec 1f26 626f dc9d 1ce3 cedd d888 .....&bo........
00000030: 819d f898 62cc ef0c 4272 4ac5 8c62 26a6 ....b...BrJ..b&.
00000040: a744 00e9 21e7 4a41 b150 72f9 2181 5a9e .D..!.JA.Pr.!.Z.
00000050: 2bad a658 6bd5 b954 416f 8cd6 ec28 7666 +..Xk..TAo...(vf
00000060: 6b34 3a58 bd3d 3823 c5d1 19ec de02 77f2 k4:X.=8#......w.
00000070: 667f a1b8 f8b3 37b9 f0a9 2ecf ebfa b5f5 f.....7.........
00000080: fabc c0b1 1ebc 0879 0574 4648 18fe ea6d .......y.tFH...m
00000090: c3fc b7e3 ef44 f462 f489 6833 68db 6840 .....D.b..h3h.h@
000000a0: 6894 68e8 0cf2 3d6f h.h...=o
```
[Try it online!](https://tio.run/##bZFbaxRBEIXf/RVHhEUQmr53dSCSSAwSEAwEDD4IfXUhWQLBKPrn1zPZ2RdJwVQ3w9Q3dc6pT7Xejx9Pu/1er3WC2LtBS8ZCrNMwWkcMPSvc8AFhSICNvgM7xdJLe//xu9p8fnUgGDJSCQZVioHxI8P0bFBSSPDRWbThBLl2B/y9Vof6emmVKLUyLBkjtoriR4OZNiLaONFb7jCcJ6N3dBEBnuc39WElHRmODDH8fkoWjreGMXWDt8nClxYgLVpqKfHAqHw@PF7xsjkyPBkleQ@tKcOaQQXFU5oJGsnO5Z0YhJIHGRdKvVZX5@rLI89vR0Ygw9bSUWLgHrUH1Bw8vKEgaZ3uNitIMXKPd0rd3il1c76oeftrroy45FKdhytk0LkOx3TQArMymR71oS1Smha48ye36lTeHNz4fdwjLYyYJoqpQlOqg0s1Y@pCGaNNjDoLapgBmM@zSf3nqZAxS21ouvLHgzctKUOHREHRC4zMgVFiX3NR6o/6efmJ525lZDKamw01Mccx6e70DGJ6yYjiHFuvbF6vjIslmq3bqu3ZyiiLFsmebQh0o2zXaeeLxTlCTh/2@38 "Bubblegum – Try It Online")
Since this is my first Bubblegum submission, it might not be the optimal solution. Please double-check.
] |
[Question]
[
The goal of this Code Golf is to create a program that sorts a list of strings (in ascending order), **without using any built-in sort method** (such as `Array.Sort()` in .NET, `sort()` in PHP, ...). Note that this restriction excludes using a built-in method that sorts an array descending, and then reversing the array.
Some details:
* Your program should prompt for input, and this input is a list of strings containing only ASCII lower-case alphabetic characters `a-z`, comma-separated without spaces. For example:
```
code,sorting,hello,golf
```
* The output should be the given list of strings, but sorted in ascending order, still comma-separated without spaces. For example:
```
code,golf,hello,sorting
```
[Answer]
## Ruby ~~76~~ ~~54~~ 51 chars
```
x=gets.scan /\w+/;$><<x.dup.map{x.delete(x.min)}*?,
```
[Answer]
# k (16 chars)
Probably doesn't really live up to the spirit of the problem. In k, there is no built in *sort* operator. `<x` returns a list of indices of items in x in sorted order.
```
{x@<x}[","\:0:0]
```
[Answer]
## SED, 135
```
s/.*/,&,!,abcdefghijklmnopqrstuvwxyz/;:;s/\(,\([^,]*\)\(.\)[^,]*\)\(.*\)\(,\2\(.\)[^,]*\)\(.*!.*\6.*\3\)/\5\1\4\7/;t;s/^,\(.*\),!.*/\1/
```
Based on my [previous sorting entry](https://codegolf.stackexchange.com/a/2035)
[Answer]
# GolfScript, ~~26~~ 25 bytes
```
","/.,{{.2$<{\}*}*]}*","*
```
Straightfoward implementation of Bubble Sort.
Try it online in [Web GolfScript](http://golfscript.apphb.com/?c=OyJjb2RlLHNvcnRpbmcsaGVsbG8sZ29sZiIgIyBTaW11bGF0ZSBpbnB1dCBmcm9tIFNURElOLgoKIiwiLy4se3suMiQ8e1x9Kn0qXX0qIiwiKiAgIyBTb3J0Lg%3D%3D).
### How it works
```
","/ # Split the input string at commas.
., # Get the number of chunks.
{ # Do that many times:
{ # Reduce; for each element but the first:
.2$< # Push 1 if the last two strings are in descending order, 0 if not.
{\}* # Swap these strings that many times.
}*] # Collect the strings dumped by reduce in an array.
}* #
","* # Join, separating by commas.
```
[Answer]
## Ruby, 99 chars ([Gnome sort](http://en.wikipedia.org/wiki/Gnome_sort))
```
a=gets.scan /\w+/
p=1
while a[p]
a[p]>a[p-1]?p+=2:(a[p],a[p-1]=a[p-1],a[p])
p-=1if p>1
end
$><<a*?,
```
This just barely beats my bubble sort implementation:
## Ruby, ~~110~~ ~~104~~ 101 chars ([Bubble sort](http://en.wikipedia.org/wiki/Bubble_sort))
```
s=gets.scan /\w+/
(z=s.size).times{(0..(z-2)).map{|i|s[i],s[i+1]=s[i+1],s[i]if s[i]>s[i+1]}}
$><<s*?,
```
This does `list.length` iterations, because worst-case scenario takes `list.length - 1` iterations and one more really doesn't matter, and saves 2 chars.
Just for fun, a Quicksort version:
## Ruby, 113 chars ([Quicksort](http://en.wikipedia.org/wiki/Quicksort))
```
q=->a{if a[1]
p=a.shift
l=[]
g=[]
a.map{|x|(x>p ?g:l).push x}
q[l]+[p]+q[g]
else
a
end}
$><<q[gets.scan /\w+/]*?,
```
[Answer]
## Haskell, 141
```
import Data.List
m=minimum
s[]=[]
s l=m l:s(l\\[m l])
t[]=[]
t s=let(a,b)=span(/=',')s in a:t(drop 1 b)
main=interact$intercalate",".s.t.init
```
At least it’s… **sort** of efficient.
[Answer]
## vba, 165
```
Sub q()
c=","
s=InputBox("?")
Z=Split(s, c)
t=UBound(Z)
For i=1 To t-1
For j=i To t
If Z(i)>Z(j) Then a=Z(i):Z(i)=Z(j):Z(j)=a
Next
Next
Debug.Print Join(Z,c)
End Sub
```
[Answer]
## PHP 83 bytes
```
<?for($x=fgetcsv(STDIN);$x;)${$x[0]>min($x)?x:a}[]=array_shift($x)?><?=join(~Ó,$a);
```
An *O(n3)* implementation of a selection sort. The `Ó` is character 211; a bit-inverted comma.
Sample usage:
```
$ more in.dat
code,sorting,hello,golf
$ php list-sort.php < in.dat
code,golf,hello,sorting
```
[Answer]
# Scala, 122 bytes
## As a one-liner (88 bytes):
```
.permutations.filter(_.sliding(2).map(w=>w(0)<w.last).fold(true)((a,b)=>a&&b)).toSeq(0)
```
(it will sort a list by just doing `list.permutations.fil...` )
## As a program (122 bytes):
```
println(readLine.split(",").toSeq.permutations.filter(_.sliding(2).map(w=>w(0)<w.last).fold(true)((a,b)=>a&&b)).toSeq(0))
```
A longer version if you want it to read from stdin.
This iterate over all the permutations of the given list until it stumble on a sorted one. It's not fast as it takes about 12 seconds to sort a 10 elements list and well over a minute for a 11 elements one.
**[Edit]** items need to be unique or `<` can be replaced by `<=`.
Also, sorry for necro.
[Answer]
# Python 3 (80 chars)
```
l=input().split(',')
m=[]
while l:m+=[l.pop(l.index(min(l)))]
print(','.join(m))
```
Here is a variation of the while-statement that is of equal length:
```
while l:x=min(l);m+=[x];l.remove(x)
```
[Answer]
# Mathematica ~~66~~ 56
```
Row[#[[Ordering@#]]&[InputString[]~StringSplit~","],","]
```
Some other solutions without the build-in symbol `Ordering`:
## Bogosort: ~~84~~ 74
```
NestWhile[RandomSample,InputString[]~StringSplit~",",!OrderedQ@#&]~Row~","
```
## Bubble Sort: ~~93~~ 83
```
Row[InputString[]~StringSplit~","//.{x___,i_,j_,y___}/;j~Order~i==1:>{x,j,i,y},","]
```
## Another solution as inefficient as bogosort: ~~82~~ 72
```
#~Row~","&/@Permutations[InputString[]~StringSplit~","]~Select~OrderedQ;
```
[Answer]
# Python 3.5+, 73 bytes
This takes inspiration from [Steven Rumbalski's](https://codegolf.stackexchange.com/a/12841/31855) answer but uses list comprehension instead of a while loop; the number of iterations comes from the copied list `l` which is the reason this [requires additional unpacking generalizations and Python 3.5](https://www.python.org/dev/peps/pep-0448/)
```
l=input().split(',');print(*[l.pop(l.index(min(l)))for _ in[*l]],sep=',')
```
[Answer]
## javascript 128
```
a=prompt().split(',');b=[];for(i in a){b.push(a[i]);k=0;for(j in b){j=k;b[j]>a[i]?[c=b[j],b.splice(j,1),b.push(c)]:k++}}alert(b)
```
[DEMO fiddle](http://jsfiddle.net/mendelthecoder/X78ud/5/).
i am looking for a way to eliminate `b`.
[Answer]
# R
### Bubble Sort: ~~122~~ 118 characters
```
a=scan(,"",sep=",");h=T;while(h){h=F;for(i in 1:(length(a)-1)){j=i+1;if(a[i]>a[j]){a[j:i]=a[i:j];h=T}}};cat(a,sep=",")
```
### Bogosort: 100 characters
```
a=scan(,"",sep=",");while(any(apply(embed(a,2),1,function(x)x[1]<x[2]))){a=sample(a)};cat(a,sep=",")
```
[Answer]
## Perl, 159
```
perl -F"," -lape "$m=$m<length()?length():$m for@F;$_{10**(2*$m)*sprintf'0.'.'%02d'x$m,map-96+ord,split//}=$_ for@F;$_=join',',map$_{$_+0},grep exists$_{$_+0},'0'.1..'0'.10**100"
```
This never stood a chance to win, but decided to share it because I liked the logic even if it's a mess :) The idea behind it, is to convert each word into an integer (done using the [ord](http://perldoc.perl.org/functions/ord.html) function), we save the number as a key in a hash and the string as a value, and then we iterate increasingly through all integers (1..10\*\*100 in this case) and that way we get our strings sorted.
**WARNING**: Don't run this code on your computer, since it loops through trillions+ of integers. If you want to test it, you can lower the upper range limit and input non-lengthy strings. If for any reason this is against the rules, please let me know and I'll delete the entry!
[Answer]
## JS: 107 chars - Bubble Sort
```
a=prompt().split(/,/);for(i=a.length;i--;)for(j=0;j<i;)a[j]>a[j+1]?[b=a[j],a[j]=a[++j],a[j]=b]:j++;alert(a)
```
I looked at @tryingToGetProgrammingStraight's answer and tried to improve it, but ended up implementing it slightly differently.
[Answer]
# Java, 134 bytes
A method that implements Gnome Sort.
```
void s(String[]a){int m=a.length-1,i=0;while(i<m){while(i>=0&&a[i].compareTo(a[i+1])>0){String t=a[i];a[i]=a[i+1];a[i+1]=t;i--;}i++;}}
```
[Answer]
# Swift, 101 bytes
```
func s(a:[String])->[String]{return a.count<2 ? a:(s(a.filter{$0<a[0]})+[a[0]]+s(a.filter{$0>a[0]}))}
```
Ungolfed:
```
//quicksort
func sort(a:[String]) -> [String]
{
//return the array if its length is less than or equal to 1
if a.count <= 1
{
return a
}
//choose the first element as pivot
let pivot = a[0]
//retrieve all elements less than the pivot
let left = a.filter{ $0 < pivot }
//retrieve all elements greater than the pivot
let right = a.filter{ $0 > pivot }
//sort the left partition, append a new array containing the pivot,
//append the sorted right partition
return sort(left) + Array<String>(arrayLiteral: pivot) + sort(right)
}
```
[Answer]
# ùîºùïäùïÑùïöùïü, 24 chars / 30 bytes (noncompetitive)
```
ï⇔Ĕ⍪;↻ïꝈ)ΞÿѨŗ ï,⇀$≔МƵï;Ξ
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=false&input=code%2Csorting%2Chello%2Cgolf&code=%C3%AF%E2%87%94%C4%94%E2%8D%AA%3B%E2%86%BB%C3%AF%EA%9D%88%29%CE%9E%C3%BF%D1%A8%C5%97%20%C3%AF%2C%E2%87%80%24%E2%89%94%D0%9C%C6%B5%C3%AF%3B%CE%9E)`
Using selection sort!
# Explanation
```
ï⇔Ĕ⍪;↻ïꝈ)ΞÿѨŗ ï,⇀$≔МƵï;Ξ // implicit: ï=input, Ξ=[]
ï⇔Ĕ⍪; // split ï along commas and set it to ï
↻ïꝈ) // while ï's length > 0
Ξÿ // push to Ξ:
Ѩŗ ï,⇀$≔МƵï; // removed minimum item(s) from ï using builtin
Ξ // get sorted array
```
Basically recursively removes and pushes the minimum from the input to another array.
[Answer]
# Ceylon (Bogosort), 119
```
String s(String i)=>",".join([*i.split(','.equals)].permutations.select((p)=>!any{for([x,y]in p.paired)y<x})[0]else[]);
```
[Try it online!](https://try.ceylon-lang.org/?gist=092d664fc0c65ac24505d8e88b5b852e)
I found the [`permutations`](https://modules.ceylon-lang.org/repo/1/ceylon/language/1.3.3/module-doc/api/Collection.type.html#permutations) method and thus ended up with Bogosort (a non-random variant).
Formatted and commented:
```
// a function `s` mapping a String `i` to a String
String s(String i) =>
// the end result is created by joining the iterable in (...).
",".join(
// take the input, split it on commas, make the result a sequence.
[*
i.split(','.equals) // ‚Üí {String+}
] // ‚Üí [String+]
// get the iterable of all permutations of this sequence.
// Yes, this is an iterable of O(n!) sequences (though likely
// lazily computed, we don't need all in memory at once).
.permutations // ‚Üí {[String+]*}
// filter this iterable for ordered sequences.
// Using select instead of filter makes this
// eager instead of lazy, so we are actually iterating
// through all n! sequences, and storing the ordered
// ones. (All of those are equal.)
.select(
// this is our function to check whether this sequence
// is ordered in ascending order.
(p)=>
// return if none of the following iterable of booleans is true.
!any {
// This is a for-comprehension. Inside an named argument list
// (what we have here, although there is no name) for a
// function which wants an iterable, this becomes an iterable,
// lazily built from the existing iterable p.paired,
// which is just an iterable with all pairs of subsequent
// elements.
for([x,y] in p.paired)
// for each such pair, we evaluate this expression, which
// is true when the sequence is not ordered correctly.
y < x // ‚Üí Boolean
// ‚Üí {Boolean*}
} // ‚Üí Boolean
// ‚Üí Boolean([String+])
) // ‚Üí [[String+]*]
// we now have a sequence of (correctly sorted) sequences.
// just take the first one.
// If we had used `.filter` before, this would have to be `.first`.
[0] // ‚Üí [String+]|Null
// in case this is null, which can only happen if the original array was
// empty, so there were no permutations, just use the empty sequence
// again. (Actually, split never returns an empty array, so this can't
// happen, but the type checker can't know that.)
else [] // ‚Üí [String*]
// so that is what we pass to the join method.
) // ‚Üí String
;
```
Without the formatting and parsing it becomes just 90 bytes:
```
String[]s(String[]i)=>i.permutations.select((p)=>!any{for([x,y]in p.paired)y<x})[0]else[];
```
[Try it online!](https://try.ceylon-lang.org/?gist=8a291b336c386b279837ea9151ac4762)
[Answer]
# [Perl 5](https://www.perl.org/), 77 bytes
```
map{$F[$_]gt$F[$_+1]&&(@F[$_,$_+1]=@F[$_+1,$_])for 0..@F-2}@F;$_=join',',"@F"
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saBaxS1aJT42vQRMaxvGqqlpOICYOmCerQNEGMiL1UzLL1Iw0NNzcNM1qnVws1aJt83Kz8xT11HXUXJwU/r/P1knSSfxX35BSWZ@XvF/XV9TPQNDg/@6BW76OvoA "Perl 5 – Try It Online")
Simple bubble sort.
[Answer]
# `ruby -plaF,` , 70 bytes
```
o=[]
$F.map{|s|i=o;s.bytes{|b|i=i[b]=[*i[b]]};i[0]=s<<?,}
$_=o*''
chop
```
O(n), if you pretend that resizing and compacting an array is free (it is very not free).
We create a deeply and unevenly nested array `o` by putting a string with bytes b1,b2...bn into the array at position o[b1][b2]...[bn]. The result looks like `[,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,["a,",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, [,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ["abc,"], ["abd,"], ["abe,"]], ["ac,"], ["ad,"]],, ["c,"]]`
Then we flatten and output it.
[Answer]
>
> Reusing [my own answer](https://codegolf.stackexchange.com/a/108550/29325) on [Sort an Integer List](https://codegolf.stackexchange.com/questions/77836/sort-an-integer-list)
>
>
>
# [Tcl](http://tcl.tk/), 211 bytes
```
set L [split [gets stdin] ,]
set i 0
time {incr j;set x 0;while \$x<$i {if \"[lindex $L $i]"<"[lindex $L $x]" {set L [lreplace [linsert $L $x [lindex $L $i]] $j $j]};incr x};incr i} [llength $L]
puts [join $L ,]
```
[Try it online!](https://tio.run/##VY7BCoMwEETvfsUgOebQu/0E/8DmUHSrK9tEzJYGxG9PY@ulsLAw83ZntJecIyladHERVnQjaUTUgb2DddVhMi6V8pOwse9XzM0hJlya98RCuJl0NVzMB251J@wHSjAtDLv6@ickV2M742SlRe494QAirfoj8P/Awcxl3N58o9O5eS@ckB91KqCrllcp3c2B/XFnXc59GMjGsCr70U4kEuwY5PEB "Tcl – Try It Online")
] |
[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/5131/edit).
Closed 7 years ago.
[Improve this question](/posts/5131/edit)
## The Challenge
Write the shortest possible program that demonstrates a programming language's entire syntax: statements, expressions, operators, reserved words, etc.
Take the language's grammar (usually in [EBNF](http://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form)) and create a program that uses all of it.
The program doesn't have to do anything particularly useful, but if it does that's a bonus :)
## Rules
* You must use all of the language's syntax: every type of statement, expression, operator, keyword, etc the language defines.
* It must be able to be run with no dependencies, except for the standard library included with the language (it doesn't need to use the entire standard lib though).
* Include a link to the language spec you used (e.g. here is [the Python 2.7 grammar](http://docs.python.org/2.7/reference/grammar.html)).
[Answer]
## Jot (2 chars)
```
10
```
<http://semarch.linguistics.fas.nyu.edu/barker/Iota/#Goedel>
[Answer]
## HQ9+ (4 chars)
```
HQ9+
```
It will print Hello World, then Quine, then 99 bottles of beer on the wall and then increment accumulator.
[Answer]
## Unary 1
```
0
```
With the syntax being
```
P => 0+
```
(syntax is technically more complicated, but I'm too lazy to figure out binary to unary conversion as an EBNF)
[Answer]
# Ook
```
Ook! Ook. Ook! Ook? Ook! Ook! Ook. Ook? Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook!
```
Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook? Ook! Ook. Ook. Ook? Ook. Ook. Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook? Ook. Ook. Ook! Ook. Ook. Ook? Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook? Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook? Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook. Ook. Ook? Ook. Ook. Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook? Ook! Ook. Ook. Ook? Ook! Ook. Ook. Ook? Ook. Ook. Ook! Ook.
[Answer]
## Brainfuck:
```
.[->+<],
```
with the syntax being:
```
S=> '.'S|','S|'>'S|'<'S|'-'S|'+'S|'['S']'S|emptyStr
```
[Answer]
## SK combinator calculus (4 chars)
```
K(S)
```
Grammar:
```
E ::= K | S | (E) | EE |
```
[Answer]
## Lambda calculus (9 chars)
```
λx. (x y)
```
### Grammar
```
E ::= Letter | (E E) | 'λ' Letter '. ' E
Letter ::= 'a' | 'b' | ... | 'z'
```
Looks how much more verbose than SK this is!
[Answer]
# Lisp (2 chars)
```
()
```
Of course, there are built in functions, such as `defun` and the basic arithmetic functions, but again, those are FUNCTIONS.
[Answer]
## Python 2 (13 chars)
Not sure if this is allowed:
```
exec(input())
```
**Example 1:**
Input: `'print "Hello World!"'`
Output: `Hello World!`
**Example 2:**
Input: `'import math; print math.pi'`
Output: `3.14159265359`
[Answer]
# Blub
```
Blub! Blub. Blub! Blub? Blub! Blub! Blub. Blub? Blub. Blub. Blub? Blub. Blub? Blub! Blub. Blub!
```
Output:
```
Blub. Blub. Blub. Blub. Blub! Blub? Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub! Blub! Blub? Blub! Blub. Blub? Blub! Blub? Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub? Blub. Blub! Blub! Blub? Blub! Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub. Blub. Blub? Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub. Blub. Blub? Blub. Blub. Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub. Blub. Blub? Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub. Blub. Blub? Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub. Blub. Blub. Blub. Blub. Blub. Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub. Blub. Blub? Blub! Blub. Blub. Blub? Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub! Blub.
```
[Answer]
# [Seed](https://esolangs.org/wiki/Seed), 3 chars
```
5 7
```
This seeds a [Mersenne Twister](https://en.wikipedia.org/wiki/Mersenne_Twister) with the number 7 and uses it to create a 5-character Befunge program.
] |
[Question]
[
Make a program that outputs a sequence of integers so that every finite sequence of positive integers is a substring (continuous subsequence) of the output.
For example, the following sequence satisfies the rules:
`1,1,1,2,1,1,1,1,2,2,1,3,1,1,1,1,1,1,2,1,2,1,1,3,2,1,1,3,1,4,...`
To see the underlying pattern, let's format the sequence a bit differently:
```
1,
1,1, 2,
1,1,1, 1,2, 2,1, 3,
1,1,1,1, 1,1,2, 1,2,1, 1,3, 2,1,1, 2,2, 3,1, 4,
1,1,1,1,1, 1,1,1,2, 1,1,2,1, 1,1,3, 1,2,1,1, 1,2,2, 1,3,1, 1,4, 2,1,1,1, 2,1,2, 2,2,1, 2,3, 3,1,1, 3,2, 4,1, 5
...
```
Here you can see that every row contains every sequence of positive numbers that sum to the index of the row. For example, row 3 has all sequences whose sum is 3. This means that every sequence is included somewhere in the list.
Standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply. As stated before, your sequence may also contain 0 or negative numbers. These non-positive numbers are not ignored, meaning that your output must contain arbitrarily long substrings of only positive integers.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
∞Ó˜
```
[Try it online!](https://tio.run/##yy9OTMpM/f//Uce8w5NPz/n/HwA "05AB1E – Try It Online")
Outputs the exponents of numbers' prime factorization, flattened. It can be easily seen that all sequences will appear - a sequence \$ a\_i \$ will appear when we go over the number \$ \prod {p\_i}^{a\_i} \$ (\$ p\_i \$ is the i-th prime)
[Answer]
# [Haskell](https://www.haskell.org/), 39 bytes
```
do y<-[1..];q<-mapM id$[1..y]<$[1..y];q
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P902JV@h0kY32lBPL9a60EY3N7HAVyEzRQUkUBlrA6WtC//nJmbm2RYUZeaVqJQkZqcqGBoAgYKKQvp/AA "Haskell – Try It Online")
Start with the positive integers `[1..]`. Draw an integer `y`. Then take the cartesian product of `y` copies of `[1..y]`. This is just all the ways to choose `y` numbers less than or equal to `y`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
Þ∞ƛṄvṖ;f
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnuKInsab4bmEduG5ljtmIiwiIiwiIl0=)
Pretty much the sequence in the question, but with a lot more 1s. Outputs as an infinite lazy list.
```
ƛ ; # Over each element of...
Þ∞ # 1...∞
Ṅ # Get integer partitions
vṖ # Get all permutations
f # Flatten the result
```
[Answer]
# [R](https://www.r-project.org/), 22 bytes
```
repeat cat(rpois(9,9))
```
[Try it online!](https://tio.run/##K/r/vyi1IDWxRCE5sUSjqCA/s1jDUsdSU/P/fwA "R – Try It Online")
Outputs a random sequence of integers (realizations of the Poisson(9) distribution). They are printed in batches of 9, including some 0s (which is allowed by OP).
There is a theoretical guarantee that any finite sequence will almost surely be printed eventually.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~50~~ 49 bytes
```
for(x=0n;y=++x;)for(b=1n;y/=b;)console.log(y%++b)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/Lb9Io8LWIM@60lZbu8JaE8RPsjUE8vVtk6w1k/PzivNzUvVy8tM1KlW1tZM0//8HAA "JavaScript (Node.js) – Try It Online")
Shortened by @l4m2.
This outputs the mixed-radix digital expansion of each positive integer *n*, where the radices used are 2, 3, 4, ... Any finite sequence of positive (or even nonnegative) integers will occur in the digits of some *n*.
[Answer]
# [Python](https://www.python.org), 54 bytes
```
j=k=t=2
while t:=k%2>0!=print(t)or-~t:k=k//2or(j:=-~j)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwU3z_IKizLwSWzDJlZKapgBmaVRoWnEp5EPZWoY6xakFtkoKSjqpeSkgWnNpaUmarsVNsyzbbNsSWyOu8ozMnFSFEivbbFUjOwNFiHkaJZr5Rbp1JVbZttn6-kb5RRpZVra6dVlQ3QugFJQGAA)
This version consistently outputs `True` for `1`.
### Old [Python](https://www.python.org), 57 bytes
```
j=k=1
while[print(t:=len(f"{k&-k:b}"))]:k=k>>t or(j:=-~j)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3LbNss20NucozMnNSowuKMvNKNEqsbHNS8zTSlKqz1XSzrZJqlTQ1Y62ybbPt7EoU8os0sqxsdeuyNCEGQM2BmQcA)
### Old [Python](https://www.python.org), 63 bytes (@pxeger)
```
j=k=1
while 1:j+=k<1;k=k or j;t=len(f"{k&-k:b}");k>>=t;print(t)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY37bNss20NucozMnNSFQytsrRts20MrbNtsxXyixSyrEtsc1LzNNKUqrPVdLOtkmqVNK2z7exsS6wLijLzSjRKNCHGQE2DmQoA)
#### Old [Python](https://www.python.org), 73 bytes
```
def f(j=1,k=1):
while 1:j+=k<1;k=k or j;t=len(f"{k&-k:b}");k>>=t;yield t
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY5BCsIwEEX3PcWQhSSYQLOTxiluPYbSxCZT0lAiUsWTuOlG7-RtrFS3n8d7__FKY277OE3Pc3Zq89431oHjAbUk1KIq4NL6zoKuwhppqw0hQT9AMBk7G7ljN1opqo53JgzVNWYzets1kH_CnZtpLwP4CFef-HCIJ8t1WQrpuPgGANLgY-YzJG1skIFSwESxrGLx_A9-AA)
This goes through all positive integers and outputs for each the sequence of distances between `1`s in its binary representation.
For example:
```
1616 -> 11001010000 -> 5,2,3,1
```
# [Python](https://www.python.org), 53 bytes
```
j=k=t=1
while k:=k//t or(j:=j+(t:=1)):print(k%t);t+=1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwU3T_IKizLwSWzDJlZKapgBmaVRoWnEp5EPZOsWpBbZKCko6qXkpIFpzaWlJmq7FTdMs22zbEltDrvKMzJxUhWwr22x9_RKF_CKNLCvbLG2NEitbQ01NK4gp2aolmtYl2raGEM0LoBSUBgA)
Port of @Polichinelle's JS [answer](https://codegolf.stackexchange.com/a/242773/107561).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞Åœ€€œ˜
```
Outputs the infinite example sequence, but without an unquify of the permutations.
[Try it online.](https://tio.run/##yy9OTMpM/f//Uce8w61HJz9qWgNERyefnvP/PwA)
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,...]
Ŝ # Map each to a list of all possible lists of positive integers that sum
# to that integer:
# [[[1]], [[1,1],[2]], [[1,1,1],[1,2],[3]], ...]
€ # Map over each list:
€ # Map over each inner list:
œ # Get all permutations of this list
# [[[[1]]], [[[1,1],[1,1]],[[2]]], [[[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]],[[1,2],[2,1]],[[3]]], ...]
˜ # Flatten this list of lists
# [1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,1,3,...]
# (after which the result is output implicitly)
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 39 bytes
```
for(i=1,oo,[print(p[2])|p<-factor(i)~])
```
[Try it online!](https://tio.run/##K0gsytRNL/j/Py2/SCPT1lAnP18nuqAoM69EoyDaKFazpsBGNy0xuQQkq1kXq/n/PwA "Pari/GP – Try It Online")
A port of [@Command Master's 05AB1E answer](https://codegolf.stackexchange.com/a/242757/9288).
---
## [Pari/GP](http://pari.math.u-bordeaux.fr/), 44 bytes (@Polichinelle)
```
for(i=9,oo,[print(d)|d<-digits(i,log(i)\1)])
```
[Try it online!](https://tio.run/##K0gsytRNL/j/Py2/SCPT1lInP18nuqAoM69EI0WzJsVGNyUzPbOkWCNTJyc/XSNTM8ZQM1bz/38A "Pari/GP – Try It Online")
---
## [Pari/GP](http://pari.math.u-bordeaux.fr/), 47 bytes
```
for(i=9,oo,[print(d)|d<-digits(i,log(i)^.9\1)])
```
When \$i\$ is larger enough, \$b = \lfloor\log(i)^{0.9}\rfloor\$ will satisfy \$b^b < i\$. So the code will print the base-\$b\$ digits of a sequence of more than \$b^b\$ consecutive integers, which will contain all sequences of integers in \$1,\dots,b-1\$ with length \$<b\$.
[Try it online!](https://tio.run/##K0gsytRNL/j/Py2/SCPT1lInP18nuqAoM69EI0WzJsVGNyUzPbOkWCNTJyc/XSNTM07PMsZQM1bz/38A "Pari/GP – Try It Online")
---
## [Pari/GP](http://pari.math.u-bordeaux.fr/), 50 bytes
```
for(i=2,oo,for(j=1,i^i,[print(d)|d<-digits(j,i)]))
```
[Try it online!](https://tio.run/##K0gsytRNL/j/Py2/SCPT1kgnP18HxMyyNdTJjMvUiS4oyswr0UjRrEmx0U3JTM8sKdbI0snUjNXU/P8fAA "Pari/GP – Try It Online")
] |
[Question]
[
The challenge is to write the fastest code possible for computing the [Hafnian of a matrix](https://en.wikipedia.org/wiki/Hafnian).
The Hafnian of a symmetric `2n`-by-`2n` matrix `A` is defined as:
$$\operatorname{haf}(A)=\frac{1}{n ! 2^n} \sum\_{\sigma \in S\_{2 n}} \prod\_{j=1}^n A\_{\sigma(2 j-1), \sigma(2 j)}$$
Here \$ S\_{2 n} \$ represents the set of all permutations of the integers from `1` to `2n`, that is `[1, 2n]`.
The wikipedia link also gives a different looking formula which may be of interest (and even faster methods exist if you look further on the web). The same wiki page talks about adjacency matrices but your code should work for other matrices as well. You can assume the values will all be integers but not that that they are all positive.
There is also a [faster algorithm](https://arxiv.org/pdf/1107.4466.pdf) but it seems hard to understand. and Christian Sievers was the first to implement it (in Haskell).
In this question matrices are all square and symmetric with even dimension.
## Reference implementation (note this is using the slowest possible method).
Here is some example python code from Mr. Xcoder.
```
from itertools import permutations
from math import factorial
def hafnian(matrix):
my_sum = 0
n = len(matrix) // 2
for sigma in permutations(range(n*2)):
prod = 1
for j in range(n):
prod *= matrix[sigma[2*j]][sigma[2*j+1]]
my_sum += prod
return my_sum / (factorial(n) * 2 ** n)
print(hafnian([[-1, 1, 1, -1, 0, 0, 1, -1], [1, 0, 1, 0, -1, 0, -1, -1], [1, 1, -1, 1, -1, -1, 0, -1], [-1, 0, 1, -1, -1, 1, -1, 0], [0, -1, -1, -1, -1, 0, 0, -1], [0, 0, -1, 1, 0, 0, 1, 1], [1, -1, 0, -1, 0, 1, 1, 0], [-1, -1, -1, 0, -1, 1, 0, 1]]))
4
M = [[1, 1, 0, 0, 0, 0, 0, 1, 0, 0], [1, 1, -1, 0, -1, 1, 1, 1, 0, -1], [0, -1, -1, -1, 0, -1, -1, 0, -1, 1], [0, 0, -1, 1, -1, 1, -1, 0, 1, -1], [0, -1, 0, -1, -1, -1, -1, 1, -1, 1], [0, 1, -1, 1, -1, 1, -1, -1, 1, -1], [0, 1, -1, -1, -1, -1, 1, 0, 0, 0], [1, 1, 0, 0, 1, -1, 0, 1, 1, -1], [0, 0, -1, 1, -1, 1, 0, 1, 1, 1], [0, -1, 1, -1, 1, -1, 0, -1, 1, 1]]
print(hafnian(M))
-13
M = [[-1, 0, -1, -1, 0, -1, 0, 1, -1, 0, 0, 0], [0, 0, 0, 0, 0, -1, 0, 1, -1, -1, -1, -1], [-1, 0, 0, 1, 0, 0, 0, 1, -1, 1, -1, 0], [-1, 0, 1, -1, 1, -1, -1, -1, 0, -1, -1, -1], [0, 0, 0, 1, 0, 0, 0, 0, 0, 1, -1, 0], [-1, -1, 0, -1, 0, 0, 1, 1, 1, 1, 1, 0], [0, 0, 0, -1, 0, 1, 1, -1, -1, 0, 1, 0], [1, 1, 1, -1, 0, 1, -1, 1, -1, -1, -1, -1], [-1, -1, -1, 0, 0, 1, -1, -1, -1, 1, -1, 0], [0, -1, 1, -1, 1, 1, 0, -1, 1, -1, 1, 1], [0, -1, -1, -1, -1, 1, 1, -1, -1, 1, 0, -1], [0, -1, 0, -1, 0, 0, 0, -1, 0, 1, -1, 1]]
print(hafnian(M))
13
M = [[-1, 1, 0, 1, 0, -1, 0, 0, -1, 1, -1, 1, 0, -1], [1, -1, 1, -1, 1, 1, -1, 0, -1, 1, 1, 0, 0, -1], [0, 1, 1, 1, -1, 1, -1, -1, 0, 0, -1, 0, -1, -1], [1, -1, 1, -1, 1, 0, 1, 1, -1, -1, 0, 0, 1, 1], [0, 1, -1, 1, 0, 1, 0, 1, -1, -1, 1, 1, 0, -1], [-1, 1, 1, 0, 1, 1, -1, 0, 1, -1, -1, -1, 1, -1], [0, -1, -1, 1, 0, -1, -1, -1, 0, 1, -1, 0, 1, -1], [0, 0, -1, 1, 1, 0, -1, 0, 0, -1, 0, 0, 0, 1], [-1, -1, 0, -1, -1, 1, 0, 0, 1, 1, 0, 1, -1, 0], [1, 1, 0, -1, -1, -1, 1, -1, 1, 1, 1, 0, 1, 0], [-1, 1, -1, 0, 1, -1, -1, 0, 0, 1, -1, 0, -1, 0], [1, 0, 0, 0, 1, -1, 0, 0, 1, 0, 0, 1, 1, 1], [0, 0, -1, 1, 0, 1, 1, 0, -1, 1, -1, 1, 1, -1], [-1, -1, -1, 1, -1, -1, -1, 1, 0, 0, 0, 1, -1, -1]]
print(hafnian(M))
83
```
**The task**
You should write code that, given an `2n` by `2n` matrix, outputs its Hafnian.
As I will need to test your code it would be helpful if you could give a simple way for me to give a matrix as input to your code, for example by reading from standard in. I will test your code in randomly chosen matrices with elements selected from {-1, 0, 1}. The purpose of testing like this is to reduce the chance the Hafnian will be a very large value.
Ideally your code will be able to read in matrices exactly as I have them in the examples in this question straight from standard in. That is the input would look like `[[1,-1],[-1,-1]]` for example. If you want to use another input format, please ask and I will do my best to accommodate.
**Scores and ties**
I will test your code on random matrices of increasing size and stop the first time your code takes more than 1 minute on my computer. The scoring matrices will be consistent for all submissions in order to ensure fairness.
If two people get the same score then the winner is the one which is fastest for that value of `n`. If those are within 1 second of each other then it is the one posted first.
**Languages and libraries**
You can use any available language and libraries you like but no pre-existing function to compute the Hafnian. Where feasible, it would be good to be able to run your code so please include a full explanation for how to run/compile your code in Linux if at all possible.`
**My Machine** The timings will be run on my 64-bit machine. This is a standard ubuntu install with 8GB RAM, AMD FX-8350 Eight-Core Processor and Radeon HD 4250. This also means I need to be able to run your code.
**Call for answers in more languages**
It would be great to get answers in your favorite super fast programming language. To start things off, how about [fortran](https://gcc.gnu.org/fortran/), [nim](https://nim-lang.org/) and [rust](https://www.rust-lang.org/en-US/)?
**Leaderboard**
* **52** by miles using **C++**. 30 seconds.
* **50** by ngn using **C**. 50 seconds.
* **46** by Christian Sievers using **Haskell**. 40 seconds.
* **40** by miles using **Python 2 + pypy**. 41 seconds.
* **34** by ngn using **Python 3 + pypy**. 29 seconds.
* **28** by Dennis using **Python 3**. 35 seconds. (Pypy is slower)
[Answer]
# Haskell
```
import Control.Parallel.Strategies
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector as VB
type Poly = V.Vector Int
type Matrix = VB.Vector ( VB.Vector Poly )
constpoly :: Int -> Int -> Poly
constpoly n c = V.generate (n+1) (\i -> if i==0 then c else 0)
add :: Poly -> Poly -> Poly
add = V.zipWith (+)
shiftmult :: Poly -> Poly -> Poly
shiftmult a b = V.generate (V.length a)
(\i -> sum [ a!j * b!(i-1-j) | j<-[0..i-1] ])
where (!) = V.unsafeIndex
x :: Matrix -> Int -> Int -> Int -> Poly -> Int
x _ 0 _ m p = m * V.last p
x mat n c m p =
let mat' = VB.generate (2*n-2) $ \i ->
VB.generate i $ \j ->
shiftmult (mat!(2*n-1)!i) (mat!(2*n-2)!j) `add`
shiftmult (mat!(2*n-1)!j) (mat!(2*n-2)!i) `add`
(mat!i!j)
p' = p `add` shiftmult (mat!(2*n-1)!(2*n-2)) p
(!) = VB.unsafeIndex
r = if c>0 then parTuple2 rseq rseq else r0
(a,b) = (x mat (n-1) (c-1) m p, x mat' (n-1) (c-1) (-m) p')
`using` r
in a+b
haf :: [[Int]] -> Int
haf m = let n=length m `div` 2
in x (VB.fromList $ map (VB.fromList . map (constpoly n)) m)
n 5 ((-1)^n) (constpoly n 1)
main = getContents >>= print . haf . read
```
This implements a variation of Algorithm 2 of [Andreas Björklund: Counting Perfect Matchings as Fast as Ryser](https://arxiv.org/abs/1107.4466).
Compile using `ghc` with compile time options `-O3 -threaded` and use run time options `+RTS -N` for parallelization. Takes input from stdin.
[Answer]
# [Python 3](https://docs.python.org/3/)
```
from functools import lru_cache
@lru_cache(maxsize = None)
def haf(matrix):
n = len(matrix)
if n == 2: return matrix[0][1]
h = 0
for j in range(1, n):
if matrix[0][j] == 0: continue
copy = list(matrix)
del copy[:j+1:j]
copy = list(zip(*copy))
del copy[:j+1:j]
h += matrix[0][j] * haf(tuple(copy))
return h
print(haf(tuple(map(tuple, eval(open(0).read())))))
```
[Try it online!](https://tio.run/##fVXhbqMwDP5NnsLS/YGtOSW7/UKqdE@wF0DohGg4qGiCUpi2vXwPWhhJ7FzVqiZ27M/2ZzN8jq3Rv263xpoLNJOuR2P6K3SXwdgRejv9qau6VYz9/pbTS/Vx7b4UHOHNaJWxk2qgrZr5fLTdR5azRM@6XunthCVdA/PZEV5ysGqcrIaHqhBlIUuWtPMFwZLGWDhDp8FW@q9K5QH04m65vtufy8WTyKE2euz0pGaD2gyfS8zuOu5Bk5PqYdEU@flZ5ucyMPzqhvRpOcgixi08H/3AT/dEx2noVbrdXBNqGRtsp8d0t7hUw0M6gHqv@tQMc01E9tOq6pRm98/t9gPWYr68sqIQB5i/c@Jc3v/EQ9p@wlV8CwIJi6o8QBEoXVfcdYKCCUe5PS8O/ZseVB7g2d0IAvzmULpqMjWB5DCNzccG0AvpgcEXgyoILx2@FVESlYn2hQjvnK5JUxVHbfFRxyq7e/TzwpwQqKYIuweP4274zSZJGqSw8xBVyuOyQPg42fcVYVhfHiGwoLQBCXbqUNyPd5bsmzsugghFAEbklMQ5wikDNPEHLkMKu8D9sfGRCdwFgfYGovA@NSI@xSHLolMV@MPpyzBXLonsfbWbtSTZJukkJcEO7u9bjwexezLSFukPtgg2VTgyGDQagtXKpQ6X8ddHbEHycEbJruAmSGqdE9RANAwpiXYtsYOcd4nvL7Al5f/Ne1n@Aw "Python 3 – Try It Online")
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/)
```
#define T(x) ((x)*((x)-1)/2)
#define S 1
#define J (1<<S)
#define TYPE int
#include <iostream>
#include <vector>
#include <string>
#include <pthread.h>
using namespace std;
struct H {
int s, w, t;
TYPE *b, *g;
};
void *solve(void *a);
void hafnian(TYPE *b, int s, TYPE *g, int w, int t);
int n, m, ti = 0;
TYPE r[J] = {0};
pthread_t pool[J];
int main(void) {
vector<int> a;
string s;
getline(cin, s);
for (int i = 0; i < s.size(); i++)
if (s[i] == '0' || s[i] == '1')
a.push_back((s[i-1] == '-' ? -1 : 1)*(s[i] - '0'));
for (n = 1; 4*n*n < a.size(); n++);
m = n+1;
TYPE z[T(2*n)*m] = {0}, g[m] = {0};
for (int j = 1; j < 2*n; j++)
for (int k = 0; k < j; k++)
z[(T(j)+k)*m] = a[j*2*n+k];
g[0] = 1;
hafnian(z, 2*n, g, 1, -1);
TYPE h = 0;
for (int t = 0; t < ti; t++) {
pthread_join(pool[t], NULL);
h += r[t];
}
cout << h << endl;
return 0;
}
void *solve(void *a) {
H *p = reinterpret_cast<H*>(a);
hafnian(p->b, p->s, p->g, p->w, p->t);
delete[] p->b;
delete[] p->g;
delete p;
return NULL;
}
void hafnian(TYPE *b, int s, TYPE *g, int w, int t) {
if (t == -1 && (n < S || s/2 == n-S)) {
H *p = new H;
TYPE *c = new TYPE[T(s)*m], *e = new TYPE[m];
copy(b, b+T(s)*m, c);
copy(g, g+m, e);
p->b = c;
p->s = s;
p->g = e;
p->w = w;
p->t = ti;
pthread_create(pool+ti, NULL, solve, p);
ti++;
}
else if (s > 0) {
TYPE c[T(s-2)*m], e[m];
copy(b, b+T(s-2)*m, c);
hafnian(c, s-2, g, -w, t);
copy(g, g+m, e);
for (int u = 0; u < n; u++) {
TYPE *d = e+u+1,
p = g[u], *x = b+(T(s)-1)*m;
for (int v = 0; v < n-u; v++)
d[v] += p*x[v];
}
for (int j = 1; j < s-2; j++)
for (int k = 0; k < j; k++)
for (int u = 0; u < n; u++) {
TYPE *d = c+(T(j)+k)*m+u+1,
p = b[(T(s-2)+j)*m+u], *x = b+(T(s-1)+k)*m,
q = b[(T(s-2)+k)*m+u], *y = b+(T(s-1)+j)*m;
for (int v = 0; v < n-u; v++)
d[v] += p*x[v] + q*y[v];
}
hafnian(c, s-2, e, w, t);
}
else
r[t] += w*g[n];
}
```
[Try it online!](https://tio.run/##nVrdb9s2EH/3X0GgQCNLZnsM9jQ72dOAoCi2Ac0eBsEoFJlx5Niya8lOmzb/@ryjJFuieEenMxx98OuOv/vkOelmI@dpeji8men7LNfiNvg6FAFeQnORavj@cjg4dn4S6vT8QQRqMvnUdt7@89fvIsvLweBNlqfL3UyL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QPHU4@fibpUj5fCFR1Q9IWzztyYLQCbD9Nl4cYameiM1CeA5gQxBwe3OOn5DIm0o0DWT1VZ85Z1C9LQJ@hgTh5AmsWvPUAXQ3zn3CITNL5caYthFCFDeU5X9KRAbjoTZ5ZXlF2kN3quieiKi5E8TkE9yuC9BfACXfk/uLj2yR/8JPMcYHJ7s@qn@24LC8IbHmKiVySrZP488nXHFEr7qb/pvfLZF4cZPOvHwe5Srbpw1WelNleH@Sflwd5X261lvX/mmXP@j8) (13s for n = 24)
Based on the faster Python [implementation](https://codegolf.stackexchange.com/a/157490/6710) in my other post. Edit the second line to `#define S 3` on your 8-core machine and compile with `g++ -pthread -march=native -O2 -ftree-vectorize`.
The splits the work in half, so the value of `S` should be `log2(#threads)`. The types can easily be changed between `int`, `long`, `float`, and `double` by modifying the value of `#define TYPE`.
[Answer]
# [Python 3](https://docs.python.org/3/)
This computes haf(A) as a memoised sum(A[i][j] \* haf(A without rows and cols i and j)).
```
#!/usr/bin/env python3
import json,sys
a=json.loads(sys.stdin.read())
n=len(a)//2
b={0:1}
def haf(x):
if x not in b:
i=0
while not x&(1<<i):i+=1
x1=x&~(1<<i)
b[x]=sum(a[i][j]*haf(x1&~(1<<j))for j in range(2*n)if x1&(1<<j)and a[i][j])
return b[x]
print(haf((1<<2*n)-1))
```
[Answer]
# C
Another impl of [Andreas Björklund's paper](https://arxiv.org/abs/1107.4466), which is much easier to understand if you also look at [Christian Sievers's Haskell code](https://codegolf.stackexchange.com/questions/157049/calculate-the-hafnian-as-quickly-as-possible#answer-157158). For the first few levels of the recursion, it distributes round-robin threads over available CPUs. The last level of the recursion, which accounts for half of the invocations, is optimised by hand.
Compile with: `gcc -O3 -pthread -march=native`; thanks @Dennis for a 2x speed-up
[n=24 in 24s on TIO](https://tio.run/##fVhtb9s2EP7uX6F2WCxKZHt0v2xQFKAIiiFA0QxxX4B5hqE4dqzEklVJTuNm@evLjrIskUd6TS2LR/LeeM/d0XNxO5@/vPxys1im@cKb/fHpy2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uRFh5JwiIBaBUT/R5poJcGur37yF3R6vcc16NDIndfdYS0Gmty5QeHXUB@idH7A3eRkg4sgtHdCxLEdj4A4nbocU8uL5SXO7MCNw9SOnpF3Rl6uyisqmMmAzCvu9LdaJm/RAHpXMHsFMGKFDuIgNsJ8NgvEKQ16xt/s62XjraQpBGgyZY0OkcbctH92uBIkZJbjYuwun9xrHd3dFD9JVW6fkIR0i5wgrZJZjEktco@wh5PHQrBuhfR1CWsy4Czeh5tI5W06eDf@XKd3FYv4vLdi2h/bH8RWVLOV3Ge1OnD4j8 "C (clang) – Try It Online")
```
#define _GNU_SOURCE
#include<sched.h>
#include<stdio.h>
#include<stdlib.h>
#include<memory.h>
#include<unistd.h>
#include<pthread.h>
#define W while
#define R return
#define S static
#define U (1<<31)
#define T(i)((i)*((i)-1)/2)
typedef int I;typedef long L;typedef char C;typedef void V;
I n,ncpu,icpu;
S V f(I*x,I*y,I*z){I i=n,*z1=z+n;W(i){I s=0,*x2=x,*y2=y+--i;W(y2>=y)s+=*x2++**y2--;*z1--+=s;}}
typedef struct{I m;V*a;V*p;pthread_barrier_t*bar;I r;}A;S V*(h1)(V*);
I h(I m,I a[][n+1],I*p){
m-=2;I i,j,k=0,u=T(m),v=u+m,b[u][n+1],q[n+1];
if(!m){I*x=a[v+m],*y=p+n-1,s=0;W(y>=p)s-=*x++**y--;R s;}
memcpy(b,a,sizeof(b));memcpy(q,p,sizeof(q));f(a[v+m],p,q);
for(i=1;i<m;i++)for(j=0;j<i;j++){f(a[u+i],a[v+j],b[k]);f(a[u+j],a[v+i],b[k]);k++;}
if(2*n-m>8)R h(m,a,p)-h(m,b,q);
pthread_barrier_t bar;pthread_barrier_init(&bar,0,2);pthread_t th;
cpu_set_t cpus;CPU_ZERO(&cpus);CPU_SET(icpu++%ncpu,&cpus);
pthread_attr_t attr;pthread_attr_init(&attr);
pthread_attr_setaffinity_np(&attr,sizeof(cpu_set_t),&cpus);
A arg={m,a,p,&bar};pthread_create(&th,&attr,h1,&arg);
I r=h(m,b,q);pthread_barrier_wait(&bar);pthread_join(th,0);pthread_barrier_destroy(&bar);
R arg.r-r;
}
S V*h1(V*x0){A*x=(A*)x0;x->r=h(x->m,x->a,x->p);pthread_barrier_wait(x->bar);R 0;}
I main(){
ncpu=sysconf(_SC_NPROCESSORS_ONLN);
S C s[200000];I i=0,j=0,k,l=0;W((k=read(0,s+l,sizeof(s)-l))>0)l+=k;
n=1;W(s[i]!=']')n+=s[i++]==',';n/=2;
I a[T(2*n)][n+1];memset(a,0,sizeof(a));k=0;
for(i=0;i<2*n;i++)for(j=0;j<2*n;j++){
W(s[k]!='-'&&(s[k]<'0'||s[k]>'9'))k++;
I v=0,m=s[k]=='-';k+=m;W(k<l&&('0'<=s[k]&&s[k]<='9'))v=10*v+s[k++]-'0';
if(i>j)*a[T(i)+j]=v*(1-2*m);
}
I p[n+1];memset(p,0,sizeof(p));*p=1;
printf("%d\n",(1-2*(n&1))*h(2*n,a,p));
R 0;
}
```
Algorithm:
The matrix, which is symmetric, is stored in lower-left triangular form. Triangle indices `i,j` correspond to linear index `T(max(i,j))+min(i,j)` where `T` is a macro for `i*(i-1)/2`.
Matrix elements are polynomials of degree `n`. A polynomial is represented as an array of coefficients ordered from the constant term (`p[0]`) to xn's coefficient (`p[n]`).
The initial -1,0,1 matrix values are first converted to const polynomials.
We perform a recursive step with two arguments: the half-matrix (i.e. triangle) `a` of polynomials and a separate polynomial `p` (referred to as beta in the paper).
We reduce the size-`m` problem (initially `m=2*n`) recursively to two problems of size `m-2` and return the difference of their hafnians. One of them is to use the same `a` without its last two rows, and the very same `p`. Another is to use the triangle `b[i][j] = a[i][j] + shmul(a[m-1][i],a[m-2][j]) + shmul(a[m-1][j],a[m-2][i])` (where `shmul` is the shift-multiply operation on polynomials - it's like polynomial product as usual, additionally multiplied by the variable "x"; powers higher than x^n are ignored), and the separate polynomial `q = p + shmul(p,a[m-1][m-2])`. When recursion hits a size-0 `a`, we return the major coefficient of p: `p[n]`.
The shift-and-multiply operation is implemented in function `f(x,y,z)`. It modifies `z` in-place. Loosely speaking, it does `z += shmul(x,y)`. This seems to be the most performance-critical part.
After the recursion has finished, we need to fix the sign of the result by multiplying by (-1)n.
[Answer]
# Python
This is pretty much a straight-forward, reference implementation of Algorithm 2 from the mentioned [paper](https://arxiv.org/pdf/1107.4466.pdf). The only changes were to only keep the current value of *B*, dropping the values of *β* by only updating *g* when *i* ∈ *X*, and truncated polynomial multiplication by only calculating the values up to degree *n*.
```
from itertools import chain,combinations
def powerset(s):
return chain.from_iterable(combinations(s, k) for k in range(len(s)+1))
def padd(a, b):
return [a[i]+b[i] for i in range(len(a))]
def pmul(a, b):
n = len(a)
c = [0]*n
for i in range(n):
for j in range(n):
if i+j < n:
c[i+j] += a[i]*b[j]
return c
def hafnian(m):
n = len(m) / 2
z = [[[c]+[0]*n for c in r] for r in m]
h = 0
for x in powerset(range(1, n+1)):
b = z
g = [1] + [0]*n
for i in range(1, n+1):
if i in x:
g = pmul(g, [1] + b[0][1][:n])
b = [[padd(b[j+2][k+2], [0] + padd(pmul(b[0][j+2], b[1][k+2]), pmul(b[0][k+2], b[1][j+2]))[:n]) if j != k else 0 for k in range(2*n-2*i)] for j in range(2*n-2*i)]
else:
b = [r[2:] for r in b[2:]]
h += (-1)**(n - len(x)) * g[n]
return h
```
[Try it online!](https://tio.run/##fVZtj6IwEP7ur5j7RpF6LdndS8z5Swi5FBe1KsUgm9vdP@@1BaQvw5mI7Uz79JmZZ4q3r/7Uqpzevm5fj8ehaxuQfd31bXu9g2xubdfD/iSkyvZtU0kletmq@2r1Xh/g1v6tu3vdJ3eyXYH@dHX/0alh/cZg/TFYorrWibs7uWdwIXBoO7iAVNAJdayTa6000JoTMqKL9/dEZFD54IUoZLmu9MMCSB9AEFKO25uPq7tdwQ6GFXa619OClamyswBJjXsm1xl3mY88gFyf4Tco327PKLSrhPUODOe0Ks6ll6aB6EkclBQqaQKiDYGfkFvTtyFbFPtybSlbTnvLaUhCZ8bNAH7Sa9kzqE/jedZpCIFnoEyaZ8KV3vP9nB3NaVzzdhKEJGmEidNhlnzG2TCwtijHbISvNL4eFVtVkmh5ZWO2ItCJW@dlcdGPzHDSW63dolmQs3VVBsysIhnMvsvsM8sIsecZpmf4sdMKrK/3GlgoxzxVNE8lKUMFPB0eZQOyxYPoinzr1Kky03nzyegjoZykaaKA2tJ/EgIpHAvl6eW0Wglus8IyeNn8Mo8383g1abEG7cg3ujBs8zLY3iZDBnyTD7ZX67cGPdJURD6hmmUZUG5/2DCavsx1PAcsGhiXrZPvdKGoCxIdxhznNDeA/k6PKg34zDAMIT8BcteNhsaicRjGhDER9I70yMQbgywwLxw6JZEjmVmsC3K8Yx2DxjIelcVnvZTZGdGPK9YEi3Iacffo0bgafrFRkQYhzDqMMuVpmUX8KFr3kWGYX7ogYIZ5AxHM0sG0v1xZtG5uuzDkKIRwJE6O2COePGCzPKE8lLBL3G8bnxmLq8CieyOS8Nw1bLmLQ5UtdlWAF4fPw1gpR6L33W7UHFUbx4PkiDqof996OljaxxfKwv3GZsFNFbZMTDpqgnGVKx3Kl18fSxckDXsUrUpcBI5d54g0IhmGkozuWuQOct4lPl6wFh3/r9/1K3p166Tqn/8VRU4ej38)
Here is a faster version with some of the easy optimizations.
```
def hafnian(m):
n = len(m)/2
z = [[0]*(n+1) for _ in range(n*(2*n-1))]
for j in range(1, 2*n):
for k in range(j):
z[j*(j-1)/2+k][0] = m[j][k]
return solve(z, 2*n, 1, [1] + [0]*n, n)
def solve(b, s, w, g, n):
if s == 0:
return w*g[n]
c = [b[(j+1)*(j+2)/2+k+2][:] for j in range(1, s-2) for k in range(j)]
h = solve(c, s-2, -w, g, n)
e = g[:]
for u in range(n):
for v in range(n-u):
e[u+v+1] += g[u]*b[0][v]
for j in range(1, s-2):
for k in range(j):
for u in range(n):
for v in range(n-u):
c[j*(j-1)/2+k][u+v+1] += b[(j+1)*(j+2)/2][u]*b[(k+1)*(k+2)/2+1][v] + b[(k+1)*(k+2)/2][u]*b[(j+1)*(j+2)/2+1][v]
return h + solve(c, s-2, w, e, n)
```
[Try it online!](https://tio.run/##hVXbbuowEHznK/YxN6t2HivxJZZ1BDRcQmsQECr685x1LsT2rlskROx1ZmdnZ835cdufbC3Oj/Pj@fxotrBfbe1hZbOv/H0BYGEJn41bvdW4/MGl1tIUmS1VDtvTBf7BwcJlZXdNZousLqxQeW7wrAu2c1BVgMEedIgd51g7bmMC3RZZixBvdXk0mAkTfunW6KODvDS37mLhevq8N9lPD1gBAmtloATHC9c2XyxcIcOpdQXXCr4r2LmIS3PAECyXIIecI@Z3sdPW5di4Etc6a7FApFLWPZWyNvrdMDVdRZ3TchzQHoEGDpv@WAViooHRBqM7hByF6jwVPY3u3rboXio1uivvpSvagXSmWGPt@s6r7hj@oXqCwR8s3GcT9mumFSloBpbZsd87DqoqxxkbF@1PZ4MOqLG@sV17fC0UF7VthuavUNqDPXe3DBfny8HeXqZe5c8n@rcC2ftGqP5HDk/TV/qB14MkDy5k0HxR0IcSPghJJr3gtHaA4ZsBVRHxmWEkQ34CVH6YLU2S57iMCWMiGKQMyNAXIxVkUI6YRFSMMsm@MOm93bFoTnHSlpB1StkZMayLekISTQn3gJ6g3QibzZo0KmH2IVEq8LIk/ATb95FhrK9IGFhy0cgEs3U476c7y/bNHxfJpGIIE3MqZp/wVBGb9EKo2MI@8XBsQmaSdkGSe4NYeJ4amZ7i2GXJqYrwaPkqrlUopvow7FetWLcpvkjFuEOE923gg9R7KtEWFQ62jG6qeGQoaTIE4ynfOkKl/z5SF6SIZ5TtCm2C4q5zxhrEhrElyV3L3EHef0mIF51ln3@bd2P@Aw "Python 2 (PyPy) – Try It Online")
For added fun, here is a reference [implementation](https://tio.run/##ZVXtrtowDP2fpzjiSlO7ltT22CZFbOI9tnsZHxfKJEDav91qvDpLSpM6vQotiWMf28e2@vt@bzeHy2lzwTeHT3AgA7@3mDs84a/BPhy@O1wM3sJ2j87OKNy04ejVD9c/67PFk8PJQvDi7fdXa4BtUHjzm2M0BPtT0Pea/hcVsQsKgn@P12zN2Abx6eDV0OEc9TTUEVXT2FXxsSnBqOGNvP0W3Q1LUO8pIu9QzRjFvrPkfhVU19WH4odL5o3XLrbdbbmqyxk9l/WtXNmb8/vm5gOqQqiVw9KTgDlOAfj1sh8C6pPcmSTqWWm90fzFFUG/anAu0TkczaDTmtKYDQfG1ws8//TRLuxX/3zxz@d@TxDLILvopf0ebKW/D9KwJ7ORHkN6EB8e@yXBFkE/LB5O0r9ZvXMJJX0ZFg/nh4SSVrSm5InTPSuPEZuSL8nk0e6xtD9SmJLuJcXGg@/xXmNp/5R5o0lmY76kctC5yIAqGVsRbzyNPIxokjByv7lXzRhN0HUsMQ7KeKUsQ1IeSPHBKg/Ni@ZgzJlUZXX/aLkofEl4039dJVbRRFxW2bHqvLw6/K5nRLGnq649jV3CmW9S/S6TSozYmi/JMh2rkt9Llq1klc1rq/NgxYko9vNZzSeAVH/wZG7yXtUTx1md9ESQmgxRVdcTIZP5m3I0ZGvM6669In5QNnK//wc) in J.
[Answer]
# Octave
This is basically a copy of [Dennis' entry](https://codegolf.stackexchange.com/a/157128/32352), but optimized for Octave. The main optimization is done by using the full input matrix (and its transpose) and recursion using only matrix indices, rather than creating reduced matrices.
The main advantage is reduced copying of matrices. While Octave does not have a difference between pointers/references and values and functionally only does pass-by-value, it's a different story behind the scenes. There, copy-on-write (lazy copy) is used. That means, for the code `a=1;b=a;b=b+1`, the variable `b` is only copied to a new location at the last statement, when it is changed. Since `matin` and `matransp` are never changed, they will never by copied. The disadvantage is that the function spends more time calculating the correct indices. I may have to try different variations between numerical and logical indices to optimize this.
Important note: input matrix should be `int32`! Save the function in a file called `haf.m`
```
function h=haf(matin,indices,matransp,transp)
if nargin-4
indices=int32(1:length(matin));
matransp=matin';
transp=false;
end
if(transp)
matrix=matransp;
else
matrix=matin;
end
ind1=indices(1);
n=length(indices);
if n==2
h=matrix(ind1,indices(2));
return
end
h=0*matrix(1);
for j=1:(n-1)
indj=indices(j+1);
k=matrix(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1 0 0 -1 1 0 0 -1 -1 1;-1 0 1 1 -1 0 0 0 1 1 1 1 1 1 -1 -1 1 0 1 1 -1 -1 -1 1;0 0 0 1 -1 0 -1 -1 1 0 1 1 -1 1 -1 1 -1 -1 0 1 1 0 0 -1;0 -1 1 1 0 -1 1 0 1 0 1 0 0 0 1 1 0 -1 -1 0 0 0 1 0;-1 -1 -1 1 1 0 0 1 0 0 1 -1 -1 -1 1 1 0 1 -1 0 0 0 0 0;0 1 0 -1 -1 0 0 -1 -1 -1 1 1 1 0 0 0 1 1 0 0 0 0 1 0;-1 0 0 0 1 0 0 0 -1 1 -1 0 -1 1 1 1 1 1 0 -1 0 -1 0 1;-1 0 0 1 1 1 1 0 1 1 1 0 1 1 1 1 -1 -1 1 0 0 0 -1 0])
tic
i=1;
while(toc<60)
tic
haf(matrix(1:i,1:i));
i=i+1;
end
```
I have tried this out using TIO and MATLAB (I've actually never installed Octave). I imagine getting it to work is as simple as `sudo apt-get install octave`. The command `octave` will load the Octave GUI. If it's any more complicated than this, I will delete this answer until I've provided more detailed installation instructions.
[Answer]
# Rust
A port of Mr. Xcoder's example Python code. **Naive brute force, so slow.**
It needs much optimization.
### `src/main.rs`
```
extern crate permutohedron;
extern crate num_bigint;
extern crate num_traits;
use permutohedron::Heap;
use num_bigint::BigInt;
use num_traits::pow::Pow;
use num_traits::identities::One;
use num_traits::identities::Zero;
fn hafnian(matrix: Vec<Vec<i32>>) -> BigInt {
let mut my_sum = BigInt::zero();
let n = matrix.len() / 2;
let mut data: Vec<usize> = (0..n*2).collect();
let heap: Heap<'_, Vec<usize>, usize> = Heap::new(&mut data);
for permutation in heap {
let mut prod = BigInt::one();
for j in 0..n {
prod *= BigInt::from(matrix[permutation[2*j]][permutation[2*j+1]]);
}
my_sum += prod;
}
let factorial_n = (1..=n).fold(BigInt::one(), |f, i| f * BigInt::from(i));
my_sum / (factorial_n * BigInt::from(2).pow(n as u32))
}
fn main() {
println!("{:?}", hafnian(vec![
vec![-1, 1, 1, -1, 0, 0, 1, -1],
vec![1, 0, 1, 0, -1, 0, -1, -1],
vec![1, 1, -1, 1, -1, -1, 0, -1],
vec![-1, 0, 1, -1, -1, 1, -1, 0],
vec![0, -1, -1, -1, -1, 0, 0, -1],
vec![0, 0, -1, 1, 0, 0, 1, 1],
vec![1, -1, 0, -1, 0, 1, 1, 0],
vec![-1, -1, -1, 0, -1, 1, 0, 1]
]));
println!("{:?}", hafnian(vec![
vec![1, 1, 0, 0, 0, 0, 0, 1, 0, 0],
vec![1, 1, -1, 0, -1, 1, 1, 1, 0, -1],
vec![0, -1, -1, -1, 0, -1, -1, 0, -1, 1],
vec![0, 0, -1, 1, -1, 1, -1, 0, 1, -1],
vec![0, -1, 0, -1, -1, -1, -1, 1, -1, 1],
vec![0, 1, -1, 1, -1, 1, -1, -1, 1, -1],
vec![0, 1, -1, -1, -1, -1, 1, 0, 0, 0],
vec![1, 1, 0, 0, 1, -1, 0, 1, 1, -1],
vec![0, 0, -1, 1, -1, 1, 0, 1, 1, 1],
vec![0, -1, 1, -1, 1, -1, 0, -1, 1, 1]
]));
println!("{:?}", hafnian(vec![
vec![-1, 0, -1, -1, 0, -1, 0, 1, -1, 0, 0, 0],
vec![0, 0, 0, 0, 0, -1, 0, 1, -1, -1, -1, -1],
vec![-1, 0, 0, 1, 0, 0, 0, 1, -1, 1, -1, 0],
vec![-1, 0, 1, -1, 1, -1, -1, -1, 0, -1, -1, -1],
vec![0, 0, 0, 1, 0, 0, 0, 0, 0, 1, -1, 0],
vec![-1, -1, 0, -1, 0, 0, 1, 1, 1, 1, 1, 0],
vec![0, 0, 0, -1, 0, 1, 1, -1, -1, 0, 1, 0],
vec![1, 1, 1, -1, 0, 1, -1, 1, -1, -1, -1, -1],
vec![-1, -1, -1, 0, 0, 1, -1, -1, -1, 1, -1, 0],
vec![0, -1, 1, -1, 1, 1, 0, -1, 1, -1, 1, 1],
vec![0, -1, -1, -1, -1, 1, 1, -1, -1, 1, 0, -1],
vec![0, -1, 0, -1, 0, 0, 0, -1, 0, 1, -1, 1]
]));
println!("{:?}", hafnian(vec![
vec![-1, 1, 0, 1, 0, -1, 0, 0, -1, 1, -1, 1, 0, -1],
vec![1, -1, 1, -1, 1, 1, -1, 0, -1, 1, 1, 0, 0, -1],
vec![0, 1, 1, 1, -1, 1, -1, -1, 0, 0, -1, 0, -1, -1],
vec![1, -1, 1, -1, 1, 0, 1, 1, -1, -1, 0, 0, 1, 1],
vec![0, 1, -1, 1, 0, 1, 0, 1, -1, -1, 1, 1, 0, -1],
vec![-1, 1, 1, 0, 1, 1, -1, 0, 1, -1, -1, -1, 1, -1],
vec![0, -1, -1, 1, 0, -1, -1, -1, 0, 1, -1, 0, 1, -1],
vec![0, 0, -1, 1, 1, 0, -1, 0, 0, -1, 0, 0, 0, 1],
vec![-1, -1, 0, -1, -1, 1, 0, 0, 1, 1, 0, 1, -1, 0],
vec![1, 1, 0, -1, -1, -1, 1, -1, 1, 1, 1, 0, 1, 0],
vec![-1, 1, -1, 0, 1, -1, -1, 0, 0, 1, -1, 0, -1, 0],
vec![1, 0, 0, 0, 1, -1, 0, 0, 1, 0, 0, 1, 1, 1],
vec![0, 0, -1, 1, 0, 1, 1, 0, -1, 1, -1, 1, 1, -1],
vec![-1, -1, -1, 1, -1, -1, -1, 1, 0, 0, 0, 1, -1, -1]
]));
}
```
### `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]
# rand = "0.8.0"
# hyper = "0.13"
# tokio = { version = "0.2", features = ["full"] }
# rayon = "1.5.1"
# ndarray = "0.15.4"
# statrs = "0.13.0"
# ndarray-stats = "0.4.0"
# ndarray-linalg = "0.15"
# bitvec = "1.0.1"
# uint = "0.9"
# pariter = "0.5.1"
# rug = { version = "1.19.0", features = ["integer"], default-features = false }
# kd-tree = "0.5.1"
# time = "0.3"
permutohedron = "0.2.4"
num-bigint = "0.3.3"
num-traits = "0.2.14"
```
### Build and running
```
# win10 environment
$ cargo build
$ target\debug\rust_hello.exe
BigInt { sign: Plus, data: BigUint { data: [4] } }
BigInt { sign: Minus, data: BigUint { data: [13] } }
......
```
[Answer]
# Mathematica
Use the recursive formula.
[Try it online!](https://tio.run/##pVNNb5tAEL3zK1Y@JXiQFx/jbKvKVdpIjZo6vm1ourE3NggWhLHUyOK3u/sBZhdQD62EZXZn5s17b4aMVXuesSresPMy5aykky9p/srSX/4kWnhXvveVvYmYCSqTyvj3y8cH/f8juiEP@faYcnoSkL0/HTMoeJkdK4mVi4M@QAJFmW9rePZ0BsELT5BvXOyqfYMXzeYLzy4kj9aBrpjYcYpB@PMghDCSlO7yksYkhPi2RbLLI4inU92c2NeUxqpWsSGhwUgkRnJLBCSqQAZ8YihRDUjp3E8C2XEawuWsTlHkSSStZ0pUXXuaXd2xTZWXMUupiPz5T3EtQ15r4KfNhqe8ZBXf/tVLx8Vn7c3BCL14ajJeUw57g13Df9tq9Rn19QIn25JlnhWxonvSlF7uRcV3vISwhpMhAC8rzlKYywtxiddqE1qlZhaQ1PAv03j2unk0g43A0NKE16zc8Sr4MFlOYHUUVZzx74VWIu@eCs63ar0b@8g6r@TQHlnJ0pSna6WRdnLpYJOgESkiOMVSkyHV2FdHHfL4TvjXZxkfbAG6IchDqAtFiKBuMdAeUAJokxfvNSAhY@7IF7IWofs3KkMEzQGteHUs2w@X0hDQPNJuqby9rMfmVfuPdEmCbgmSrdQUFJRVK81WuBjQMpd@iiOnLZbmJAE@ywWveFME6HSS@4BOSV338tYlE4ciP3CqLsZB1GkMYo@mBLm0fOWYQWrFmQnI/ZTrjcyj3rB@9EHBhu0RX8KBHdRYTWnYxpo0lRKEHZ6TpQuxSsFdLHBIGAR8aWqzM30bEoHDr8lsuwdugnlryusIzWbosYxF5ZrR14wd7rbAEVWOmZ27PVGO6y5P48244QMag@q@QXhYMJhIf2Q9o2xBvVGFlqSg50/3axX1YAbzHTMdt08nqTfT/nI4RHFjXOj6Ggy8dAyyjBjoNl8ZBleQ3QvDIIwHFJ0J4eFI8QjBIOyvtf0BDrywadvLfj7/AQ)
```
haf[matrix_?MatrixQ] :=
haf[matrix] = Module[{n, h, j, copy}, n = Length[matrix];
If[n == 2, Return[matrix[[1, 2]]]];
h = 0;
For[j = 2, j <= n, j++, If[matrix[[1, j]] == 0, Continue[]];
copy = Delete[matrix, {{1}, {j}}];
copy = Transpose[copy];
copy = Delete[copy, {{1}, {j}}];
h += matrix[[1, j]]*haf[copy];];
h];
```
] |
[Question]
[
# Task
Given two integers \$d\$ and \$n\$, find the number of ways to express \$n\$ as a sum of \$d\$ squares. That is, \$n = r\_1^2 + r\_2^2 + ... + r\_d^2\$, such that \$r\_m\$ is an integer for all integers \$1 ≤ m ≤ d\$. Note that swapping two **different** values (e.g. \$r\_1\$ and \$r\_2\$) is considered different from the original solution.
For instance, the number 45 can be written as a sum of 2 squares 8 different ways:
$$\begin{align}
& 45 \\
& = (-6)^2 + (-3)^2 \\
& = (-6)^2 + 3^2 \\
& = (-3)^2 + (-6)^2 \\
& = (-3)^2 + 6^2 \\
& = 3^2 + (-6)^2 \\
& = 3^2 + 6^2 \\
& = 6^2 + (-3)^2 \\
& = 6^2 + 3^2
\end{align}$$
# Rules
* Built-in solutions are allowed but non-competing (ahem, [*Mathematica*](http://reference.wolfram.com/language/ref/SquaresR.html))
* Standard loopholes are also forbidden.
* The inputs may be reversed.
# Example I/O
```
In: d, n
In: 1, 0
Out: 1
In: 1, 2
Out: 0
In: 2, 2
Out: 4
In: 2, 45
Out: 8
In: 3, 17
Out: 48
In: 4, 1000
Out: 3744
In: 5, 404
Out: 71440
In: 11, 20
Out: 7217144
In: 22, 333
Out: 1357996551483704981475000
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so submissions using the fewest bytes win!
[Answer]
# [Python 3](https://docs.python.org/3/), 125 bytes
```
n,d=eval(input())
W=[1]+[0]*n
exec("W=[sum(-~(j>0)*W[i-j*j]for j in range(int(i**.5)+1))for i in range(n+1)];"*d)
print(W[n])
```
[Try it online!](https://tio.run/##RYyxDsIgFAB3voJ0eo@2pi1xMvU3GAhDY1Eh9pUgNbr460gn17vLhU@6ryRzpmYe7Wt6gKOwJUBkatS9qXVnBDH7theoCnluC7Rf8OcOhdKu9cKb6xq55454nOhmyyCBE@JwxLpH3KX7SyrMnCoxIwtxL5UmgzlLKZth@AE "Python 3 – Try It Online")
Finishes the last testcase in 0.078 s. Naive complexity is O(*d* *n* 2).
[Answer]
# Mathematica, 8 bytes, non-competing
```
SquaresR
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
Nr⁸²ṗS€ċ⁸
```
[Try it online!](https://tio.run/##y0rNyan8/9@v6FHjjkObHu6cHvyoac2RbiDv////Bv8NAQ "Jelly – Try It Online")
Takes `n` and `d` in this order.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
y_t_&:Z^U!s=s
```
Inputs are `n`, then `d`. Some of the test cases run out of memory.
[**Try it online!**](https://tio.run/##y00syfn/vzK@JF7NKiouVLHYtvj/f0NzLmMA "MATL – Try It Online")
### Explanation
Consider inputs `17`, `3`.
```
y % Implicit inputs. Duplicate from below
% STACK: 17, 3, 17
_ % Negate
% STACK: 17, 3, -17
t_ % Duplicate. Negate
% STACK: 17, 3, -17, 17
&: % Two-input range
% STACK: 17, 3, [-17 -16 ... 17]
Z^ % Cartesian power. Gives a matrix where each Cartesian tuple is a row
% STACK: 17, [-17 -17 -17; -17 -17 -16; ...; 17 17 17]
U % Square, element-wise
% STACK: 17, [289 289 289; 289 289 256; ...; 289 289 289]
!s % Transpose. Sum of each column
% STACK: 17, [867 834 ... 867]
= % Equals?, element-wise
% STACK: 17, [0 0 ... 0] (there are 48 entries equal to 1 in between)
s % Sum. Implicit display
% STACK: 48
```
[Answer]
## [Haskell](https://www.haskell.org/), 43 bytes
```
0#0=1
d#n=sum[(d-1)#(n-k*k)|d>0,k<-[-n..n]]
```
Just your basic recursion. Defines a binary infix function `#`. [Try it online!](https://tio.run/##y0gszk7Nyfn/30DZwNaQK0U5z7a4NDdaI0XXUFNZI083WytbsybFzkAn20Y3WjdPTy8vNvZ/bmJmnoKtQkFRZl6JgoaxgrKCobnmfwA "Haskell – Try It Online")
## Explanation
```
0#0=1 -- If n == d == 0, give 1.
d#n= -- Otherwise,
sum[ -- give the sum of
(d-1)#(n-k*k) -- these numbers
|d>0, -- where d is positive
k<-[-n..n]] -- and k is between -n and n.
```
If `d == 0` and `n /= 0`, we are in the second case, and the condition `d>0` causes the list to be empty.
The sum of the empty list is 0, which is the correct output in this case.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 31 bytes
```
d->n->sum(i=-n,n,x^i^2)^d\x^n%x
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9F1y5P1664NFcj01Y3TydPpyIuM85IMy4lpiIuT7Xif0FRZl6JRpqGoaaGgaYmFxLXCIlrhME1MUXiG2tqGJoj6wZpBxr3HwA "Pari/GP – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
Ð(Ÿ²ã€nOQO
```
Takes the arguments as n, then d. Has problems solving the bigger test cases.
[Try it online!](https://tio.run/##MzBNTDJM/f//8ASNozsObTq8@FHTmjz/QP///01MuYwA "05AB1E – Try It Online")
### Explanation
```
Ð(Ÿ²ã€nOQO Arguments n, d
Ð Triplicate n on stack
( Negate n
Ÿ Range: [-n ... n]
²ã Caertesian product of length d
€n Square each number
OQ Sum of pair equals n
O Total sum (number of ones)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
‘ṬUµJ²fJ[0]ẋ;€ḤSḣL+µ⁹¡Ṫ
```
[Try it online!](https://tio.run/##ATsAxP9qZWxsef//4oCY4bmsVcK1SsKyZkpbMF3huos74oKs4bikU@G4o0wrwrXigbnCoeG5qv///zMzM/8yMg "Jelly – Try It Online")
Port of my [Python solution](https://codegolf.stackexchange.com/a/126865/48934). Finishes the last testcase in 2.977 s.
[Answer]
# Mathematica, 38 bytes
```
Count[Tr/@Tuples[Range[-#,#]^2,#2],#]&
```
Pure function taking the inputs in the order `n`, `d`. `Range[-#,#]^2` gives the set of all possibly relevant squares, with positive squares listed twice to make the count correct; `Tuples[...,#2]` produces the `d`-tuples of such squares; `Tr/@` sums each `d`-tuple; and `Count[...,#]` counts how many of the results equal `n`.
The first few test cases terminate quickly, but I estimate this would take about half a year to run on the test case `1000,4`. Replacing `Range[-#,#]` by the (longer but) more sensible `Range[-Floor@Sqrt@#,Floor@Sqrt@#]` speeds up that computation to about 13 seconds.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ŒRṗ²§ċ⁸
```
[Try it online!](https://tio.run/##AR0A4v9qZWxsef//xZJS4bmXwrLCp8SL4oG4////MTf/Mw "Jelly – Try It Online")
Very inefficient; fails to finish within a minute for the last 4 test cases.
## How it works
```
ŒRṗ²§ċ⁸ - Main link. Takes n on the left, d on the right
ŒR - Yield [-n, -n+1, ..., 0, ..., n-1, n]
ṗ - Yield all sublists of this range of length d
² - Square each number
§ - Take the sum of each list
ċ - Count the occurrences of...
⁸ - ...n
```
[Answer]
# Mathematica, ~~53~~ 51 bytes
```
SeriesCoefficient[EllipticTheta[3,0,x]^#,{x,0,#2}]&
```
[Answer]
## Python 2, 138
Very inefficient solution with my beloved eval. Why not?
[Try it online](https://tio.run/##RYtBCoMwEEX3nmIQJDNJFlbtpuANPEIXpk1sA3EUtYVSevZUlNLNh/f/@@NruQ9cxKY@x2D6izXA2p4sGLZQSfc0AbdIUQTH@EahhM9mLaRVIqeVumGCtQHPMBm@OWTaRt/B7kpZqF2va/6QoCxV7fIYg8P9YEmW1JIOw9WEGYniOHleoMHqqAtKfnTQ@R9KXVISvw)
```
lambda n,d:d and 4*eval(eval("('len({('+'i%s,'*d+'0)'+'for i%s in range(n)'*d+'if '+'i%s**2+'*d+'0==n})')%"+`tuple(range(d)*3)`),locals())
```
It generated and evaluates code like this:
```
len({(i0,i1,0)for i0 in range(n)for i1 in range(n)if i0**2+i1**2+0==n})
```
So for some big **d** it will run very long and consume a lot of memory, having complexity of O(n^d)
[Answer]
# [k](https://en.wikipedia.org/wiki/K_(programming_language)), 23 bytes
```
{+/y=+/{x*x}y-!x#1+2*y}
```
[Try it online!](https://tio.run/##y9bNz/7/P82qWlu/0lZbv7pCq6K2UlexQtlQ20irspaLK01PXcNQwcDaUMHI2giMTUytjRUMzTX//wcA "K (oK) – Try It Online") It's a simple brute forcer.
[Answer]
# Pyth - 16 bytes
```
lfqQsm*ddT^}_QQE
```
[Try it](https://pyth.herokuapp.com/?code=lfqQsm%2AddT%5E%7D_QQE&input=4%0A3&test_suite=1&test_suite_input=0%0A1%0A2%0A1%0A2%0A2%0A45%0A2%0A17%0A3&debug=0&input_size=2)
It's horribly inefficient
] |
[Question]
[
How many of you that still use your own knuckle to determine whether a month is having a full 31 days or less?
You job is to write a program to count how many months, in a month range, are having a full 31 days and how many are having less than 31 days by "counting the knuckles".
[](https://i.stack.imgur.com/QtCaU.png)
*Courtesy: amsi.org.au*
---
## Input
A pair of months, the first of which doesn't have to come chronologically before the second, given in any suitable format. For instance: `201703 201902` — March 2017 to February 2019. Please describe the input format you choose. Note that the input must be able to include all years from 1 to 9999. The range of months specified includes both the starting and ending months.
## Output
Two integers: the number of months in the given range with 31 days and the number of months in the range with less than 31 days.
Example: `14 10` — 14 knuckles, 10 grooves (it means that in that month range we have 14 months that have a full 31 days, and 10 months that have less than 31 days).
For an input where the second month in the range comes chronologically before the first, for example `201612 201611`, you have to output a pair of zero.
## Examples of input and output
```
| Input | Output |
|---------------|-------------|
| 201703 201902 | 14 10 |
| 201701 202008 | 26 18 |
| 000101 999912 | 69993 49995 |
| 201802 201803 | 1 1 |
| 201601 201601 | 1 0 |
| 201612 201611 | 0 0 |
```
## Rules
* You may choose any language you like
* One input per line
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
* The winner will be chosen in April 9
* Standard loopholes apply
* PS: this is my first question in PCG, it might have some inconsistencies. Feel free to edit and confirm what's unclear for you.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
ḅ12r/ị7RḂṁ12¤żC$S×⁼Ṣ$
```
Takes input like `[[y, m], [y, m]]`.
[Try it online!](https://tio.run/nexus/jelly#@/9wR6uhUZH@w93d5kEPdzQ93NloaHRoydE9zirBh6c/atzzcOcilf@H2x81rXH//z86OtrIwNBcR0HBOFZHAcS2BLKNYmN1uBTgUoYQKSMDINsCKqUAFIZJWQKBjoIhki4LsCEQAy3AhsOlzBAGQtnIUoZGCClDoFQsAA "Jelly – TIO Nexus")
### How it works
```
ḅ12r/ị7RḂṁ12¤żC$S×⁼Ṣ$ Main link. Argument: [[a, b], [c, d]]
ḅ12 Unbase 12; yield [x, y] := [ 12a + b, 12c + d].
r/ Reduce by range; yield [x, ..., y].
¤ Combine the five links to the left into a niladic chain.
7 Set the return value to 7.
R Range; yield [1, 2, 3, 4, 5, 6, 7].
Ḃ Bit; yield [1, 0, 1, 0, 1, 0, 1].
ṁ12 Mold 12; repeat the Booleans to create an array of length
12. Yields [1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1].
ị At-index; yield the elements of the array to the right at
the indices (1-based and modular) of the array to the left.
$ Combine the two links to the left into a monadic chain.
C Complement; map t -> 1-t over the array.
ż Zip the original array with the complements.
S Take the sum of each column.
$ Combine the two links to the left into a monadic chain.
Ṣ Sort [[a, b], [c, d]].
⁼ Compare the result with [[a, b], [c, d]], yielding 1 if
the input is sorted, 0 if not.
× Multiply the results to both sides.
```
[Answer]
## JavaScript (ES6), ~~70~~ ~~68~~ ~~67~~ 64 bytes
Takes input as two integers in `yyyymm` format, in currying syntax `(a)(b)`. Outputs an array of two integers `[knuckles, grooves]`.
```
a=>g=(b,c=d=0)=>a>b?[c,d-c]:g(--b,c+!((b%=100)>11||b/.87&!!++d))
```
### Formatted and commented
```
a => // main function: takes start date (a) as input / returns g
g = ( // recursive function g, which takes:
b, // - b = end date
c = d = 0 // - c = number of knuckles
) => // and also keeps track of: d = total number of months
a > b ? // if a is greater than b:
[ c, d - c ] // stop recursion and return the final result
: // else:
g( // do a recursive call to g():
--b, // - decrement the end date
c + // - increment the # of knuckles if
!( // both of these conditions are false:
(b %= 100) // - the end month (now stored in b in 0-based indexing)
> 11 || // is greater than 11
b / 0.87 & !!++d // - the number of days in this month is not 31
) // (at the same time, d is incremented if the first
) // condition is false)
```
### Test cases
**NB**: The third test case is not included in this snippet, because it won't work unless your browser has Tail Call Optimization enabled.
```
let f =
a=>g=(b,c=d=0)=>a>b?[c,d-c]:g(--b,c+!((b%=100)>11||b/.87&!!++d))
console.log(f(201703)(201902)); // 14 10
console.log(f(201701)(202008)); // 26 18
console.log(f(201802)(201803)); // 1 1
console.log(f(201601)(201601)); // 1 0
console.log(f(201612)(201611)); // 0 0
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~92~~ ~~90~~ ~~86~~ 80 bytes
```
lambda a,b,c,d:[(bin(2741)[2:]*(c+1-a))[b-1:-12+d or None].count(x)for x in'10']
```
[Try it online!](https://tio.run/nexus/python2#DchLCsIwEADQq8yuM3YiThDEgFfwAjGLfAwEdFJKhd4@9i1ffbzGJ35TiRA5cebiPKamaG9XIW9dOGGexUQin4w4I3Yu0Fd4dn2Hc@4/3XCneswOTSe5TGEsa9MNKgoL3w8slsYf "Python 2 – TIO Nexus")
6 more by converting to a lambda, with thanks to @math\_junkie for the idea. Now outputs a list containing the two numbers.
Previous non-lambda version (86 bytes)
```
a,b,c,d=input()
for x in'10':print(bin(2741)[2:]*(c+1-a))[b-1:-12+d or None].count(x),
```
[Try it online old!](https://tio.run/nexus/python2#DctBCoAgEEDRfadwl1NjNBJEQlfoAuIircDNGGHQ7c2/fr/s6DHgsUa@3yyhudIjPhG5pbE19xM5Sx9Z6nkisNq4Toae1A5gvSKjSPeHqMuW@HRDSG/1H2AphIRLDUn/ "Python 2 – TIO Nexus")
2 saved with thanks to @ovs for helping me get rid of the `len(k)`. I hadn't thought about using `None`.
Input is a list of integers in the format `y1,m1,y2,m2`
Some credit due to @KeerthanaPrabhakaran who got `bin(2741)[2:]` before I did which saves 1 byte over hard coding the binary string.
[Answer]
# [PHP](https://php.net/), ~~259~~ ~~256~~ ~~249~~ ~~248~~ ~~237~~ 221 bytes
Outgolfed by [aross](https://codegolf.stackexchange.com/users/38392/aross): <https://codegolf.stackexchange.com/a/114512/38505>
Input Format: `yyyymm,yyyymm`
```
$i=explode(",",fgets(STDIN));$_="DateTime::createFromFormat";foreach(new DatePeriod($_(Ym,$i[0]),new DateInterval(P1M),$_(Ym,$i[1])) as$f)date(t,mktime(0,0,0,$f->format(m),1,$f->format(y)))>30?++$x:++$y;
echo $x.' '.++$y;
```
[Try it online!](https://tio.run/nexus/php#TY1Bi8JADIXv/opSBkwwK1M9LNvaehHBgyKsF5Eipc3Yso5TxmG3/vruKCgSeEne@@DN5m3d9qJJuWvPpmIIKSR1YneF791itUFMxDENF4XjXaM5jkvL/l5ao5fG6sKFiTLeKmu48F9w57ZsG1OBOMJek2gOMkd6ZquLY/tbnGEbrZFeSJQjBsVVKKw8BI70j/NtIOk@Qn1k6lEGGil6/2@ImE3lfDQSXezllgy4rE0guvEwGI4fTt9PZPQpp@TXl5z8Aw)
---
### Older versions
```
$i=explode(",",fgets(STDIN));$_="DateTime::createFromFormat";$y=1;foreach(new DatePeriod($_("Ym",$i[0]),new DateInterval('P1M'),$_("Ym",$i[1])) as$f)date("t",mktime(0,0,0,$f->format("m"),1,$f->format("y")))==31?++$x:++$y;
echo $x.' '.$y;
```
[Try it online!](https://tio.run/nexus/php#VY5Na8MwDIbv@xVGGGJRr9jtYSyZ10sp9DIG7WWMUkIiN2F1HFyzJb8@c3bqEOjj0Svxvmz6pp94a2jor74mARKkvVC8icNxu39DLPjZwLaMdGwd5XkVKPW74N3OB1dGKPhodGF94lUjOvphs/idQutrwc8CPhxI3n6qE8p5s@8ihe/yev9q5ocY2u4iMs2c72KTobw71idEVt64xTpJBUSQ7ismQ0LJObh9fLV/fgQ4QKn/kREQ0Zi13iwWfMhTGosHqhrP@LDMWLZM8zStlH5Sa5nKs1r9Ag "PHP – TIO Nexus")
```
$i=explode(",",fgets(STDIN));$_="DateTime::createFromFormat";$y=1;foreach(new DatePeriod($_(Ym,$i[0]),DateInterval::createFromDateString('1 month'),$_(Ym,$i[1])) as$f)date(t,mktime(0,0,0,$f->format(m),1,$f->format(y)))>30?++$x:++$y;
echo $x.' '.$y;
```
[Try it online!](https://tio.run/nexus/php#VY5Na8MwDIbv@xVGGGJRr9jtYSyZ10sp9DIG7WWMUkIiN2F1HFyzJb8@c3bqEOjj0Svxvmz6pp94a2jor74mARKkvVC8icNxu39DLPjZwLaMdGwd5XkVKPW74N3OB1dGKPhodGF94lUjOvphs/idQutrwc8CPhxI3n6qE8p5s@8ihe/yev9q5ocY2u4iMs2c72KTobw71idEVt64xTpJBUSQ7ismQ0LJObh9fLV/fgQ4QKn/kREQ0Zi13iwWfMhTGosHqhrP@LDMWLZM8zStlH5Sa5nKs1r9Ag "PHP – TIO Nexus")
```
$i=explode(",",fgets(STDIN));$_="DateTime::createFromFormat";$y=1;foreach(new DatePeriod($_(Ym,$i[0]),DateInterval::createFromDateString('1 month'),$_(Ym,$i[1])) as$f)date(t,mktime(0,0,0,$f->format(m),1,$f->format(y)))==31?++$x:++$y;
echo $x.' '.$y;
```
[Try it online!](https://tio.run/nexus/php#VY5Na8MwDIbv@xVGGGJRr9jtYSyZ10sp9DIG7WWMUkIiN2F1HFyzJb8@c3bqEOjj0Svxvmz6pp94a2jor74mARKkvVC8icNxu39DLPjZwLaMdGwd5XkVKPW74N3OB1dGKPhodGF94lUjOvphs/idQutrwc8CPhxI3n6qE8p5s@8ihe/yev9q5ocY2u4iMs2c72KTobw71idEVt64xTpJBUSQ7ismQ0LJObh9fLV/fgQ4QKn/kREQ0Zi13iwWfMhTGosHqhrP@LDMWLZM8zStlH5Sa5nKs1r9Ag "PHP – TIO Nexus")
```
$i=explode(",",fgets(STDIN));$_="DateTime::createFromFormat";foreach(new DatePeriod($_("Ym",$i[0]),DateInterval::createFromDateString('1 month'),$_("Ym",$i[1])) as$f)date("t",mktime(0,0,0,$f->format("m"),1,$f->format("y")))==31?++$x:++$y;
echo $x.' '.++$y;
```
[Try it online!](https://tio.run/nexus/php#VY5Na8MwDIbv@xVGGGJRr9jtYSyZ10sp9DIG7WWMUkIiN2F1HFyzJb8@c3bqEOjj0Svxvmz6pp94a2jor74mARKkvVC8icNxu39DLPjZwLaMdGwd5XkVKPW74N3OB1dGKPhodGF94lUjOvphs/idQutrwc8CPhxI3n6qE8p5s@8ihe/yev9q5ocY2u4iMs2c72KTobw71idEVt64xTpJBUSQ7ismQ0LJObh9fLV/fgQ4QKn/kREQ0Zi13iwWfMhTGosHqhrP@LDMWLZM8zStlH5Sa5nKs1r9Ag "PHP – TIO Nexus")
```
$i=explode(",",fgets(STDIN));$_="DateTime::createFromFormat";$y=1;foreach(new DatePeriod($_("Ym",$i[0]),DateInterval::createFromDateString('1 month'),$_("Ym",$i[1])) as$f)date("t",mktime(0,0,0,$f->format("m"),1,$f->format("y")))==31?++$x:++$y;
echo $x.' '.$y;
```
[Try it online!](https://tio.run/nexus/php#VY5Na8MwDIbv@xVGGGJRr9jtYSyZ10sp9DIG7WWMUkIiN2F1HFyzJb8@c3bqEOjj0Svxvmz6pp94a2jor74mARKkvVC8icNxu39DLPjZwLaMdGwd5XkVKPW74N3OB1dGKPhodGF94lUjOvphs/idQutrwc8CPhxI3n6qE8p5s@8ihe/yev9q5ocY2u4iMs2c72KTobw71idEVt64xTpJBUSQ7ismQ0LJObh9fLV/fgQ4QKn/kREQ0Zi13iwWfMhTGosHqhrP@LDMWLZM8zStlH5Sa5nKs1r9Ag "PHP – TIO Nexus")
[Answer]
## Batch, 93 bytes
```
@set/ag=(y=%2/100-%1/100)*5+(x=%2%%100+6)*5/12-(w=%1%%100+5)*5/12,k=y*12+x-w-g
@echo %k% %g%
```
Accepts two parameters in ymm format (i.e. 101 - 999912). Previous 129-byte loop-based solution:
```
@set/al=%1-%1/100*88,u=%2-%2/100*88,k=g=0
@for /l %%i in (%l%,1,%u%)do @set/a"m=%%i%%12,k+=1451>>m&1,g+=2644>>m&1
@echo %k% %g%
```
[Answer]
# Python 3.5 (164 162 154 152 150 148 140 137 bytes)
```
n=int;a,b=input().split();t=k=0
for r in range(n(a[4:]),(n(b[:4])-n(a[:4]))*12+n(b[4:])+1):t+=1;k+=n('101010110101'[r%12-1])
print(k,t-k)
```
## [repl.it](https://repl.it/GmAM/2)
### takes input in the form of *yyyymm yyyymm*
### prints output as *number\_of\_knuckles number\_of\_grooves*
* **saved 2 bytes:** Thanks to [Cole](https://codegolf.stackexchange.com/users/42833/cole)
* **saved 8 bytes:** removed unwanted variables
* **saved 2 bytes:** reduced t=0;k=0 as t=k=0
* **saved 2 bytes:** Thanks to Cole (I had missed this before)
* **saved 2 bytes:** Thanks to [Keerthana](https://codegolf.stackexchange.com/users/67429/keerthana-prabhakaran)
* **saved 8 bytes:** removed unwanted variables
* **saved 3 bytes:** Thanks to [math\_junkie](https://codegolf.stackexchange.com/users/65425/math-junkie) ( split(' ') to split() )
[Answer]
# [Python 2](https://docs.python.org/2/), ~~147~~ ~~146~~ 142 bytes
```
def s(a,b):y=100;r=bin(2741)[2:];x=b/y-a/y;i=r*(x-1);return((0,0),map((i+r[a%y-1:]+r[:b%y]if i or x else r[a%y-1:b%y]).count,('1','0')))[a<=b]
```
[Try it online!](https://tio.run/nexus/python2#bY5BCsIwEEX3niIbaUZTnQlisTUnKV0kNWJA0xIrNAd3XaPiQnE27/P@X8x0sEd25VoYKKMixCoo4zyXxYaglmVTjcqsY67XsXIqLPiYE1TBDrfgOUeBIC6659wtQ63nMaeySak089i4I3OsC2xk9ny17NM/K1i13c0PgmeUiQwzAKj1Xplm6oPzQ3oIEQlJ7NKRhNlHS6QtSZFQIP1oFC986@KtE/6ucQfT3Xd5q9uTfQA "Python 2 – TIO Nexus")
* Saved 4 bytes - Thanks to @math\_junkie for suggesting the if-else clause with array lookup!
Breaking down the code,
```
def s(a,b):
y=100
r=bin(2741)[2:] #'101010110101'
x=b/y-a/y #to get the difference between the two years
i=r*(x-1)
return((0,0),map((i+r[a%y-1:]+r[:b%y]if i or x else r[a%y-1:b%y]).count,('1','0')))[a<=b]
```
[Answer]
# PHP, ~~120~~ ~~103~~ ~~97~~ 96 bytes
```
for($f=strtotime;$f($argv[2])>=$n=$f($argv[1].+$x++.month);)$k+=date(t,$n)>30;echo+$k,_,$x-1-$k;
```
Run like this:
```
php -nr 'for($f=strtotime;$f($argv[2])>=$n=$f($argv[1].+$x++.month);)$k+=date(t,$n)>30;echo+$k,_,$x-1-$k;' 0001-01 9999-12;echo
> 69993_49995
```
# Explanation
```
for(
$f=strtotime; # Alias strtotime function which is called twice.
$f($argv[2]) >= # Create end date timestamp. Iterate until the end
# date is reached.
$n=$f(
$argv[1].+$x++.month # Create timestamp from start date + X months.
);
)
$k+=date(t,$n) > 30; # If "t" of current date (days in month) is 31
# increment $k (knuckles).
echo+$k,_,$x-1-$k; # Compute grooves (iterations - $k) and output,
# implicit cast to int to account for 0 count.
```
# Tweaks
* Saved 17 bytes by using timestamp style instead of DateTime object style
* Saved 6 bytes by not assigning end date timestamp to variable `$e`, just compare directly
* Saved 1 byte by not keeping count of grooves, but just computing it after the loop
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 96 bytes
```
for($a,$b=[datetime[]]$args;$a-le$b;$a=$a.AddMonths(1)){$x++;$z+=$a.Month-in2,4,6,9,11};$x-$z;$z
```
[Try it online!](https://tio.run/nexus/powershell#@5@WX6ShkqijkmQbnZJYklqSmZsaHRurkliUXmytkqibk6qSBKRtVRL1HFNSfPPzSjKKNQw1NatVKrS1rVWqtEEyYGHdzDwjHRMdMx1LHUPDWmuVCl2VKqCC////GxgYGOoaGP63BAJdQyMA "PowerShell – TIO Nexus")
Takes input as form `2017-03`. Uses the built-in .NET date libraries and loops through from inputs `$a` to `$b`, each iteration incrementing `$x++` and adding to `$z` if the current `.Month` is `-in` `2,4,6,9,11` (i.e., a non-31-day month). Then we output our total months minus the non-31-day months `$x-$z`, and the non-31-day months `$z`.
Tosses an error on the `0001-01` to `9999-12` test case, because .NET only supports years up to `9999`, so the final `.AddMonths(1)` causes an overflow. Still outputs the correct values, though, because it's a non-terminating error; it just causes the loop to exit.
Probably would be shorter to do this arithmetically, like the Python or JavaScript answers, but I wanted to show an approach using the .NET built-ins.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 113 bytes
```
s="$1-1";e="$2-1";sort <(while [ "$s" \< "$e" ];do s=$(date +%F -d"$s+1month");date +%d -d"$s-1day";done)|uniq -c
```
[Try it online!](https://tio.run/nexus/bash#LYtBCsIwEEWvMgwRWspAphQU0m69hLoonYEWNEETEcG7x5R29R6P/3Mc0DAxOi3SrhLDK0FffeblrnABNBHh2hcqws1JgDiYSsak0BzOQFIGDT@CTzPWbu@ydWIZv1g@Xuvf2y9PoCnn3Fo@ku1WnojtHw "Bash – TIO Nexus")
needs golfing...
takes input as `2016-03` `2018-10`
outputs:
```
1 28
7 30
12 31
```
ungolfed:
```
s="$1-1"
e="$2-1" # adds first day of month to the dates
sort <(
while [ "$s" \< "$e" ]; do #iterates over dates
s=$(date +%F -d"$s+1month") #adds one month to start date
date +%d -d"$s-1day" #outputs last day of previous month
done) | uniq -c #counts ocurrences of day number prevously sorted
```
[Answer]
# Swift, 151 bytes
```
let f={(m:[Int])->[Int] in var k=[0,0]
(m.min()!...m.max()!).map{$0%100}.filter{$0>0&&$0<13}.forEach{m in let n = m>7 ?m-7:m
k[(n%2+1)%2]+=1}
return k}
```
input is an array of two integers in the format as per the example
] |
[Question]
[
## The Challenge
Implement a function which accepts two integers whose values range from 0 - 255 and returns the sum of those integers mod 256. You may only use bitwise negation (~), bitwise or (|), bit shifting operators (>>,<<), and assignment (=).
Things you cannot use include (but are not limited to)
* Addition, subtraction, multiplication, and division
* Loops
* Conditional statements
* Function calls
*Fewest uses of binary or, binary negation, and bit shift operations wins*. In the event of a tie, the most popular solution wins. As always, [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply.
Here is an example of a simple 2-bit adder. It uses 77 binary negations, 28 binary ors, and 2 bit-shifts for a total score of 107 (this can be seen by running the C preprocessor with `gcc -E`). It could be made much more efficient by removing the `#define`s and simplifying the resulting expressions, but I've left them in for clarity.
```
#include <stdio.h>
#define and(a, b) (~((~a)|(~b)))
#define xor(a, b) (and(~a,b) | and(a,~b))
int adder(int a, int b)
{
int x, carry;
x = xor(and(a, 1), and(b, 1));
carry = and(and(a, 1), and(b, 1));
carry = xor(xor(and(a, 2), and(b, 2)), (carry << 1));
x = x | carry;
return x;
}
int main(int argc, char **argv)
{
int i, j;
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
if (adder(i, j) != (i + j) % 4) {
printf("Failed on %d + %d = %d\n", i, j, adder(i, j));
}
}
}
}
```
Update: Added example and changed scoring critera
[Answer]
## Python, 36 operations
A methods that's logarithmic in the parameter "8"!
```
def add(a,b):
H = a&b #4 for AND
L = a|b #1
NX = H | (~L) #2
K = NX
H = H | ~(K | ~(H<<1)) #5
K = K | (K<<1) #2
H = H | ~(K | ~(H<<2)) #5
K = K | (K<<2) #2
H = H | ~(K | ~(H<<4)) #5
carry = H<<1 #1
neg_res = NX ^ carry #7 for XOR
res_mod_256 = ~(neg_res|-256) #2
return res_mod_256
```
The idea is to figure out which indices overflow and cause carries. Initially, this is just the places where both `a` andd `b` have a `1`. But since carried bits can cause further overlows, this needs to be determined iteratively.
Rather than overflowing each index into the next one, we speed up the process by moving 1 index, then 2 indices, then 4 indices, being sure to remember places where an overflow happened (H) and where an overflow cannot happen any more (K).
---
A simpler iterative solution with **47** operations:
```
def add(a,b):
H = a&b #4 for AND
L = a|b #1
NX = H | (~L) #2
c=H<<1 #1
for _ in range(6): #6*5
d = (~c)|NX
e = ~d
c = c|(e<<1)
res = c ^ NX #7 for XOR
res_mod_256 = ~(res|-256) #2
return res_mod_256
```
---
Test rig, for anyone who wants to copy it.
```
errors=[]
for a in range(256):
for b in range(256):
res = add(a,b)
if res!=(a+b)%256: errors+=[(a,b,res)]
print(len(errors),errors[:10])
```
[Answer]
# C - 0
It does use operators outside of ~, |, >>, <<, and =, but I see solutions using casting and comma operators, so I guess the rule isn't too strict provided it isn't using the forbidden operators.
```
unsigned char sum(unsigned char x, unsigned char y)
{
static unsigned char z[] = {
0,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,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
0,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,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
240,241,242,243,244,245,246,247,248,249,250,251,252,253,254
};
return (&z[x])[y];
}
```
[Answer]
## python, score = 83 80
```
def g(x,y):
for i in xrange(7):
nx = ~x
ny = ~y
x,y = ~(x|ny)|~(nx|y), (~(nx|ny))<<1
x = ~(x|~y)|~(~x|y)
return ~(~x|256)
```
Unroll the loop. It's 10 ops per loop times 7 loops, 7 for the last xor, and 3 to squash the 9th bit at the end.
Implements the equation `x+y = x^y + 2*(x&y)` by repeating it 8 times. Each time there is one more zero bit at the bottom of `y`.
[Answer]
# C, Score: 77 60
Golfed just for the hell of it, 206 169 131 bytes:
```
#define F c=((~(~c|~m))|n)<<1;
a(x,y){int m=(~(x|~y))|~(~x|y),n=~(~x|~y),c;F F F F F F F return (unsigned char)(~(m|~c))|~(~m|c);}
```
Expanded:
```
int add(x,y)
{
int m=(~(x|~y))|~(~x|y);
int n=~(~x|~y);
int c = 0;
c=((~(~c|~m))|n)<<1;
c=((~(~c|~m))|n)<<1;
c=((~(~c|~m))|n)<<1;
c=((~(~c|~m))|n)<<1;
c=((~(~c|~m))|n)<<1;
c=((~(~c|~m))|n)<<1;
c=((~(~c|~m))|n)<<1;
return (int)((unsigned char)(~(m|~c))|~(~m|c));
}
```
Essentially the same solution (mathematically) that @KeithRandall @JuanICarrano came up with, but takes advantage of C's ability to play fast and loose with variable types and pointers to wipe everything after the first 8 bits without using any more operators.
Depends on the endian-ness of the machine and the sizeof() an int and a char, but should be able to be ported to most machine specific applications with the proper pointer math.
**EDIT:** This is a challenge that C (or other low level languages) will have a distinct upper hand at -- unless somebody comes up with an algorithm that doesn't have to carry.
[Answer]
# Python - Score ~~66~~ 64
```
def xand(a,b):
return ~(~a|~b) #4
def xxor(a,b):
return (~(a|~b))|~(~a|b) #7
def s(a,b):
axb = xxor(a,b) #7
ayb = xand(a,b) #4
C = 0
for i in range(1,8):
C = ((xand(C,axb))|ayb)<<1 #(1+1+4)x7=6x7=42
return xxor(axb,xand(C,255)) #7 + 4 = 11
#total: 7+4+42+11 = 64
```
It is the equation for a ripple adder. C is the carry. It is computed one bit at a time: in each iteration the carry is propagated left.
As pointed out by @Orby, the original version did not make a modular addition. I fixed it and also saved a cycle in the iteration, as the first carry-in is always zero.
[Answer]
# C++ - score: 113
```
#define ands(x, y) ~(~x | ~y) << 1
#define xorm(x, y) ~(y | ~(x | y)) | ~(x | ~(x | y))
int add(int x, int y)
{
int x1 = xorm(x, y);
int y1 = ands(x, y);
int x2 = xorm(x1, y1);
int y2 = ands(x1, y1);
int x3 = xorm(x2, y2);
int y3 = ands(x2, y2);
int x4 = xorm(x3, y3);
int y4 = ands(x3, y3);
int x5 = xorm(x4, y4);
int y5 = ands(x4, y4);
int x6 = xorm(x5, y5);
int y6 = ands(x5, y5);
int x7 = xorm(x6, y6);
int y7 = ands(x6, y6);
int x8 = xorm(x7, y7);
int y8 = ands(x7, y7);
return (x8 | y8) % 256;
}
```
] |
[Question]
[
Create a BCD [binary clock](http://www.thinkgeek.com/homeoffice/lights/59e0/)
in ASCII. As implied, it shall display time in six columns of dots:
[](https://upload.wikimedia.org/wikipedia/commons/thumb/2/27/Binary_clock.svg/480px-Binary_clock.svg.png)
(source: [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Binary_clock.svg))
Each column is a binary-coded digit, reading hours, minutes and seconds
from left to right. Hours are given in 24-hour format.
The time to display is read from the command-line or from stdin (whichever
fits better). If empty, the current time should be used instead.
Output size is a little constrained here and we can only fit two lines of
text. So you are required to put the dots into only two lines. The
characters `.`, `:` and `'` come in handy here.
**Input**
The time to display in ISO-8601 format, i.e. `HH:MM:SS` without fractional
seconds. Mandatory 24-hour format. Input can be empty in which case the
current time will be used.
**Output**
Two lines with represent the BCD binary clock as in the image above. Each
line is exactly six characters long and the only allowed characters are
space, period, colon and apostrophe.
**Winner**
Shortest code by byte count wins. In a tie, the solution posted first wins.
**Sample input 1**
```
```
*(empty)*
**Sample output 1**
```
.
''. ::
```
**Sample input 2**
```
17:59:20
```
**Sample output 2**
```
..'
.:..'
```
**Sample input 3**
```
01:08:01
```
**Sample output 3**
```
'
. .
```
[Answer]
## Golfscript (+ruby/date) - 46 chars
```
"#{`date`}"10>+9<" .':":S-.{4/12-S=}%n@{4%S=}%
```
You can replace ``date`` with `Time.now` if necessary (+2 chars).
[Answer]
## Ruby, ~~107 103 99 94~~ 90 characters
```
$><<[$/,(gets||Time.now.to_s[11,8]).tr(z=" .':","").bytes.map{|a|$><<z[a/4-12];z[a%4]}]*""
```
Note that the input shouldn't contain a linebreak, so to test the solution use something like `echo -n "01:08:01" | ruby1.9 bcd.rb`.
To test the default behavior, run it with `ruby1.9 bcd.rb` and enter `^D` (i.e. a literal EOF).
[Answer]
## Windows PowerShell, 81
Since I did not create an implementation when writing the task I feel myself eligible to golf it from the start, too :-)
```
-join" .':
"[(($d="$(date)$args"[-8..-1]-ne58)|%{($_-band12)/4})+,4+($d|%{$_%4})]
```
History:
* 2011-02-26 23:50 **(119)** First attempt.
* 2011-02-26 23:55 **(108)** Inlining fun.
* 2011-02-27 00:03 **(102)** Optimized selecting the first line. `[Math]::Floor` is waaaayy too long. I hate that.
* 2011-02-27 02:22 **(101)** I don't need `:` for the first line.
* 2011-02-27 02:53 **(95)** Optimized getting input or current time.
* 2011-03-04 20:36 **(88)** Only a single join remains. Indexing every character needed (including the line break) from a single string.
* 2011-03-04 20:39 **(83)** Using `58` instead of `:` which auto-casts to integer as well – no more need to enclose `$_` in quotes :-)
* 2011-03-04 20:42 **(81)** The parentheses after the `-join` are no longer necessary.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
o7ŒT¤fØDV€d4Zị“.': ”Y
```
[Try it online!](https://tio.run/##ATIAzf9qZWxsef//bzfFklTCpGbDmERW4oKsZDRa4buL4oCcLic6IOKAnVn///8xNzo1OToyMA "Jelly – Try It Online")
For the empty input, you can use either an empty string or no argument at all.
## Explanation
```
o7ŒT¤fØDV€d4Zị“.': ”Y Main monadic or niladic link
o Logical or (Python-like)
7ŒT¤ Current time in hh:mm:ss format
f Filter
ØD Digits
€ Each
V Evaluate
d Divmod
4 4
Z Zip
ị Index into [1-indexed, auto-maps]
“.': ” ".': "
Y Join with newlines
```
[Answer]
# Ruby - 124 chars
```
t=*((i=gets)=="
"? Time.now.strftime('%H%M%S'):i).tr(':
','').bytes
puts (0..1).map{|i|t.map{|_|" .':"[i<1? _/4-12:_%4]}*''}
```
[Answer]
# C#
### 236 characters
```
using System;using System.Linq;class X{static void Main(){var d=Console.In.ReadToEnd().Replace(":","");for(int i=0;i<2;i++)Console.WriteLine(string.Join("",(d==""?DateTime.Now.ToString("HHmmss"):d).Select(c=>" .':"[i<1?c/4-12:c%4])));}}
```
Readable:
```
using System;
using System.Linq;
class X
{
static void Main()
{
var d = Console.In.ReadToEnd().Replace(":", "");
for (int i = 0; i < 2; i++)
Console.WriteLine(string.Join("",
(d == "" ? DateTime.Now.ToString("HHmmss") : d)
.Select(c => " .':"[i < 1 ? c / 4 - 12 : c % 4])));
}
}
```
[Answer]
## Golfscript (+ Ruby), 63
```
."#{Time.now.strftime'%T'}"if':'-:|{4/12-" .':":@\=}%n|{4%@\=}%
```
Still a beginner with Golfscript. Don't hit me.
[Answer]
## Perl (84)
```
#!perl -pl
$_||=localtime;y/://d;/\d{6}/;$_=$&;y/0-9/ ....''/;$_.="\n$&";y/0-9/ .': .': ./
```
[Answer]
# Python 3, 136 chars
```
import time
d=input()
for i in(0,1):print(''.join([" .':"[[c>>2,c&3][i]]for c in map(int,d.replace(':','')or time.strftime('%H%M%S'))]))
```
[Answer]
## VimScript, 143 characters
```
if getline(1)==''
norm"=strftime("%T")^Mp
en
nm- "ax"=@a/4^MgP
nm, "ax"=@a%4^MgP
norm0YP--x--x--xP^M,,x,,x,,xP
%s/0/ /g
%s/1/./g
%s/2/'/g
%s/3/:/g
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~45~~ 42 bytes
```
' .'':'[4 4⊤{×≢⍵:⍎¨⍵~':'⋄,⍉0 10⊤3↑3↓⎕TS}⍞]
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXI862tP@qyvoqatbqUebKJg86lpSfXj6o85Fj3q3Wj3q7Tu0AsioA0o@6m7RedTbaaBgaABUY/yobSIQTwYaFBJc@6h3Xux/oEn/07gMza1MLa2MgAb3TQVaoK7OlcZlYGhlYGFlYIgsxgUA "APL (Dyalog Extended) – Try It Online")
A full program submission.
-3 bytes from Bubbler.
Very barely edges out Golfscript (Thanks, Bubbler!).
## Explanation
```
' .'':'[4 4⊤⍎¨{×≢⍵:⍵~':'⋄,⍉ 0 10⊤3↑3↓⎕TS}⍞]
⍞ string input
{×≢⍵: if length is nonzero:
⍵~':' remove ':'s from it
⋄ ⎕TS otherwise get current time array
3↑3↓ remove yymmdd and take hhmmss
,⍉ 0 10⊤ convert to base 10 digits and transpose, then flatten
(pads with a zero)
⍎¨ convert each character to digit
4 4⊤ encode into base 4 matrix
' .'':'[ ] index into string " .':"
```
[Answer]
# Javascript, ~~232~~ 165 characters
```
t=>(a=t.match(/\d/g).map(x=>(+x).toString(2)).flatMap(x=>x.padStart(4).match(/..?/g)).map(x=>" .':"[x%4])).filter((_,i)=>~i&1).join``+`
`+a.filter((_,i)=>i%2).join``
```
# Snippet
(modified because i dont count console.log() and the function assignment/call in the byte count)
```
f=
// 215
t=>(a=t.match(/\d/g).map(x=>(+x).toString(2)).flatMap(x=>x.padStart(4).match(/..?/g)).map(x=>" .':"[x%4])).filter((_,i)=>~i&1).join``+`
`+a.filter((_,i)=>i%2).join``
console.log(f('17:59:20'))
```
[Answer]
# [Haskell](https://www.haskell.org/), 192 180 174 166 bytes
-21 characters thanks to @Laikoni
```
import Data.Time
main=getCurrentTime>>=interact.(\x y->unlines[map(!!i)[mapM(pure" .':")"__"!!(fromEnum e-48)|e<-take 8$y++formatTime undefined"%T"x,e<':']|i<-[0,1]])
```
[Try it online!](https://tio.run/##HY1BC4IwGEDv/Yo5ChWdZBTZUC/VsZs3Exn5WUM3ZW6g4H@37PZ4h/c@bGigbZeFi75TGt2YZkHGBWwE4zJ5g74apUDq1aVpwqUGxV46cJ4jmkhqZMslDLlgvWNZ3F3h4fRGAUaBTbGLyxJbllOrTtylEQjIMXJniIlmDaBoO3le3SnB/gNkZAX1L1jhXYZHH2Kb2sXMY5Lv/bAo3GUJz/R0oYfwCw "Haskell – Try It Online")
[Answer]
## Python - 201 172 characters
```
from time import*
t=raw_input()
if not t:t=strftime('%H:%M:%S')
t=t.replace(':','')
for i in(0,2):print''.join(" .':"[int(bin(int(d))[2:].rjust(4,'0')[i:i+2],2)]for d in t)
```
[Answer]
**Lua - 163 160 Chars**
```
s=io.read():match"(%S+)"or os.date("%X",os.time())t=" .':"w=io.write for l=1,2 do for k in s:gmatch"(%d)"do y=1+select(l,(k-k%4)/4,k%4)w(t:sub(y,y))end w"\n"end
```
[Answer]
# VBA (Excel), ~~150~~ ~~148~~ 132 bytes
Using Immediate Window and Cell `[A1]` as input.
```
a=Format(IIf([a1]="",Now,[a1]),"hhmmss"):b=Split(" ,.,',:",","):For c=1To Len(a):d=Mid(a,c,1):e=e &b(d\4):f=f &b(d Mod 4):Next:?e:?f
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 35 bytes
```
{-1_'" .':"@2/+0 2_2\.'(x^":"),"9"}
```
[Try it online!](https://ngn.codeberg.page/k#eJwNzDEOwjAMBdDdpyhGwokaGjsSgv4OdPUdIlKWsjMgJARnp+8Ab8XnaE24GwQ8l9xrV1qpg4T3jcEx8chfokxkZ5xGFCU16AVqVIkc1nw+/IJfk3CulaOE3d6hWO7Px6uzSLQoJCTesoyUpQ9JPFVs/bSKx4n+S4Ybnw==)
[Answer]
### Scala, 222:
```
object C{def main(a:Array[String]){
val t=if(a.length==0)new java.text.SimpleDateFormat("HHmmss").format(new java.util.Date)else a(0).replaceAll(":","")
t.map(c=>print(" ,'"(c/4%4)));println;t.map(c=>print(" ,':"(c%4)))}}
```
[Answer]
# [Dash](https://wiki.debian.org/Shell) ([SUSv2](https://pubs.opengroup.org/onlinepubs/7908799/index.html)-compatible?), ~~202~~ ~~200~~ ~~193~~ ~~169~~ ~~138~~ 137 bytes
Usage.
* Requires input from positional argument.
* Outputs to stdout, without trailing line.
I think I should change the language for golfing off.
Notes about 138 and 137 bytes:
* May not SUSv2-compatible because it gives floating value to second argument for `substr()` in AWK.
* It ran successfully on GAWK.
```
s='for(;++i<7;){D=substr($0,i,1);printf substr(" .'\'':",(h?D%4:D/4)+1,1)}i=h++'
echo ${1-`date +%H%M%S`}|tr -d :|awk "{$s;$s}"|fold -w 6
```
[Try it online!](https://tio.run/##LY7RSsMwGEbv8xQ/JSUNabWRzWliEWkFhcrG5oWCsFXb0KA0I6ms0PbZa5Hdnu/Ad8rC1VPVHY1tYbPePb/l7/t0vd0@pq8JR@chT/cPeZ6kSAU0mFxClLGBZEzfrSTts8T9frrWBjgOdcipPFrdtArO1IML8kGI8MKgvs/8hcguF5TxWRx1UjNGUPVVG8A9jw5l0VbA/Cf/xd8dxqG1EJUghuL0DV6PncRu9AZlfkqITnA9UTSHQAe6AUKAr8TyVlzFEHMR34iYy9KAAtzJ/wOCyAyaavoD "Dash – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
õQižažbžc)T‰}Sþ4‰ø" .':"sèJ»
```
[Try it online](https://tio.run/##yy9OTMpM/f//8NbAzKP7Eo/uSzq6L1kz5FHDhtrgw/tMgPThHUoKeupWSsWHV3gd2v3/PwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFqiW5KZm2qloGRfqcOl5F9aAhQC8nQqXf4f3hqYeXRf4tF9SUf3JWuGPGrYUBt8eJ8JkD68Q0lBT91KqfjwCq9Du//rHNpm/z9aSUlHydDAytjcysQSxDS3MrW0MjIAMg0MrQwsrAwMlWIB).
**Explanation:**
```
õQi # If the (implicit) input is empty/absent:
ža # Push the current hours
žb # Push the current minutes
žc # Push the current seconds
) # Wrap all three into a list
T‰ # Divmod each by 10 to add leading 0s
}S # After the if-statement: convert it to a flattened list of characters
# (which will use the implicit input-string if necessary)
þ # Only keep all digits to remove potential ":"
4‰ # Divmod each digit by 4
ø # Zip/transpose; swapping rows/columns
" .':"sè # Index each into string " .':'
J # Join each row of characters together
» # Join the lines by newlines
# (after which the result is output implicitly)
```
] |
[Question]
[
[Robbers thread](https://codegolf.stackexchange.com/questions/241381/find-my-other-token-robbers)
Cops,
Choose two strings of code, one public and one secret. We will call them P and S. You will be writing a program using only repetitions of these strings.
For example: if you choose P=`hello`and S=`world`, valid programs would be `hello`, `world`, `helloworld`, `worldhello`, `helloworldworldhello`, `hellohellohelloworld`, etc. You are not allowed to add anything else to your code or modify these strings, so `hello world`, `HelloWorld`, `heellowoorld` and `elloword` would all be invalid programs.
### The program
Using only strings P and S, write a program which takes a list of 5 or more non-repeating positive integers, and returns them reordered such that the maximum of the list is in the center, the elements before it are in ascending order, and the elements after it are in descending order. You can output any list that meets these requirements. You may assume the list has an odd number of elements.
Examples (your outputs may differ):
```
input: [1,2,3,4,5]
output: [1,2,5,4,3]
input: [7,6,5,4,3,2,1]
output: [2,4,6,7,5,3,1]
input: [1,3,5,7,9,2,4,6,8]
output: [1,2,3,7,9,8,6,5,4]
```
In your answer, specify which language is used, your exact P string, the bytecount of your S string, and how many of each P and S you used.
Do **not** show your actual code, and do **not** show your S string.
### Scoring
Your score is the combined length of your P and S strings in bytes. If your answer has not been cracked in a week, you may mark it as safe. Lowest scoring safe answer wins.
[Answer]
# [R](https://www.r-project.org/), 10 + 24 bytes, safe
```
x=scan();x
```
[Try it online!](https://tio.run/##K/r/v8K2ODkxT0PTuuK/mYKCuYKCiYKCsYKChYKCpYKhgYKCoYKC6X8A "R – Try It Online")
The 'P' string is used once; the 'S' string is 24-bytes long and used twice.
---
## Solution
>
> We achieve the task by making every second element negative, and then sorting the reciprocals. In this way, the largest values (whose reciprocals are closest to zero) are sorted to the middle. After sorting, we need to undo the negatives and undo the reciprocals to get the original elements back, in their new sorted order.
>
> Intuitively, we could do all this in one step: reciprocal -> every\_2nd\_negative -> sort -> reciprocal -> absolute\_value; or in actual R code: `x=abs(1/sort(1/x*c(-1,1)))`.
>
> However, since the order of the initial array doesn't matter (we're going to rearrange it anyway), we can do the reciprocal only once in a first step (so we end up with rearranged reciprocals of the input values), and then repeat the entire step again.
> So: two rounds of: every\_2nd\_negative -> sort -> reciprocal -> absolute\_value; or in actual R code: `x=abs(1/sort(x*c(-1,1)))`.
>
> This saves 2-bytes (at the expense of uselessly sorting & flipping the signs twice in the first step), hopefully making it impossible to find a solution as short that will work in only one step.
> Of course, we need to be certain that the R code is fully-golfed: so, the final secret string 'S' is: `=abs(.5/sort(x*-.5:1));x`.
>
>
>
[Try it online!](https://tio.run/##K/r/v8K2ODkxT0PTusI2MalYQ89Uvzi/qESjQktXz9TKUBOP@H8zBQVzBQUTBQVjBQULBQVLBUMDBQVDBQXT/wA)
[Answer]
# JavaScript (ES6), 66 + 39 bytes [Cracked](https://codegolf.stackexchange.com/a/241407/58563)
Each string is used once.
```
f=a=>(g=a=>a+a?_([_(a,26393),...g(a)],29493784462):a)(_(a,942973))
```
[Try it online!](https://tio.run/##bcpNCsIwEEDhvSeZwTGQ/45QPUgpZahtUEojVrx@TLfi5m2@95CPbOPr/nyf1nybSplbaS@Q9spRrgN0AwiZYNkiKaUSCPZk2LGNjXPB4FkQ9oed4WgRy5jXLS@TWnKCGTpNhiw58j3i4cciBfLVbH30H9dVPEXi6q6@TX3KFw "JavaScript (Node.js) – Try It Online")
## Solution
### Clue 1
>
> The non-obfuscated code is:
>
> ```
> f=a=>(g=a=>a+a?[a.pop(),...g(a)].reverse():a)(a.sort((a,b)=>b-a))
> ```
>
>
>
>
### Clue 2
>
> The numbers encode the strings `"pop"`, `"reverse"` and `"sort"` in base 32.
>
>
>
### Secret string
>
>
> ```
> _=(a,x)=>a[x.toString(32)]((a,b)=>b-a);
> ```
>
>
>
>
[Answer]
# [Python 3](https://docs.python.org/3/), 25 + 22 [Safe (Orginal solution)](https://tio.run/##VcoxDoMwDEDRnVN4tFULKYQALUdBDJFKVJYkMmFoL596QmL97@dv@aRoa31vAQJ6evn2SFKQZtnKKRH8Y/FtThkJQhL4wa5trVn2WDDgYrhjyz27lai56sgDO61W1dzEaHM88lOl12tSrX8 "Python 3 – Try It Online")
```
def f(a):a.sort();return
```
Both strings are used once each. No list slicing used.
Solution:
>
> `def f(a):a.sort();return a+[a.pop() for z in a]`
>
>
>
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI1HTKlGvOL@oREPTuii1pLQoT@F/QVFmXolGmka0oY6RjrGOiY5prKamNRdc2FzHTMcUKGwMlDZElTIECprqmOtYAqVMgMosQNL/AQ "Python 3 – Try It Online")
# [Python 3](https://docs.python.org/3/), 25 + 16 [Cracked!](https://codegolf.stackexchange.com/a/241707/110555)
```
def f(a):a.sort();return
```
Both strings are used once each
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI1HTKlGvOL@oREPTuii1pLQoT@F/QVFmXolGmka0oY6RjrGOiY5prKamNRdc2FzHTMcUKGwMlDZElTIECprqmOtYAqVMgMosQNL/AQ "Python 3 – Try It Online")
[Answer]
# Haskell, 108 + 14
*This is old enough to be safe but I'm leaving it open, because that's more fun anyway*
Not too hard `;)`. I give you some helper functions here and you have to define the body of `f` in terms of them.
```
x#(y:z)|y>x=y:(x#z)
x#z=x:z
(x!y)(z:w)=z#y!x$w
((x:y)!(z:w))_|x<z=z:x:w?y|1>0=x:z:w?y
x?(y:z)=y:x?z
x?_=x
f=
```
It's 1 of each string. Which makes this pretty much just a fill in the blank challenge. Unfortunately it's kind of hard to make something which repeats segments in Haskell. But hopefully this should at least be a fun puzzle.
[Answer]
# Javascript, 27+32 bytes, [safe (link to solution)](https://tio.run/##Dck7DoMwDADQq3RCtjBpS38DMhdBDCYNVaoURwSh3D70re8ruyS7@rg1i75dmblk7rNJum4AQhNyL82E5icR/iMmxeCtA1/X55YulJE8Cw8jVpWU7mR1SRqcCfqBGYYrtXSjOz3oSa8RsSsH)
```
x=>x.sort((a,b)=>a-b).map(x
```
I decide to allow crack if a quite different solution comes, though it's now claimed safe
# Javascript, 27+36 bytes, [cracked](https://codegolf.stackexchange.com/a/241399/)
```
x=>x.sort((a,b)=>a-b).map(e
```
# Javascript, 26+37 bytes, [cracked](https://codegolf.stackexchange.com/a/241390/)
```
x=>x.sort((a,b)=>a-b).map(
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1q5Crzi/qERDI1EnSdPWLlE3SVMvN7FAw8bTL9g1KETB2d/FVcHDNcjV7r@1QnJ@XnF@TqpeTn66RppGtKGOkY6xjomOqY6Zjnmspqb1fwA "JavaScript (Node.js) – Try It Online")
[Answer]
*This is my first time doing a cops and robbers and I'm still a little confused so correct me if I did something wrong*
## [Python 3](https://python.org), 21+33 bytes - [Cracked!](https://codegolf.stackexchange.com/a/241673/110555)
```
def f(i):m=len(i)//2;
```
Both strings are used once.
[Attempt it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI1PTKtc2JzUPyNDXN7L@X1CUmVeikaYRbahjpGOsY6JjGqupac0FFzbXMdMxBQobA6UNUaUMgYKmOuY6lkApE6AyC5D0fwA)
## [Python 3](https://python.org), 20+36 bytes - [Cracked!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI1HTKtc2JzUPyNDXN7JOsi3OLypJTQFyrYtSS0qL8hSSoq1yY7VBpK6hla5h7P@Cosy8Eo00jWhDHSMdYx0THdNYTU1rLriwuY6ZjilQ2BgobYgqZQgUNNUx17EESpkAlVmApP8DAA)
```
def f(a):m=len(a)//2
```
Both strings are used once.
[Attempt it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI1HTKtc2JzUPyNDXN/pfUJSZV6KRphFtqGOkY6xjomMaq6lpzQUXNtcx0zEFChsDpQ1RpQyBgqY65jqWQCkToDILkPR/AA)
## [Python 3](https://python.org), 21+43 bytes
```
def f(a):m=len(a)//2;
```
Both strings are used once.
[Attempt it online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhZbU1LTFNI0EjWtcm1zUvOADH19I2uI3E3fgqLMvBKNNI1oQx0jHWMdEx3TWE1NLriouY6ZjilQ1Bgoa4giYwgUM9Ux17EEypgAVVkAZSGGwiwGAA)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 2 + 5 bytes, safe
```
øO
```
[Try it online!](https://tio.run/##yygtzv7///AO/////0eb6ZjrmOgY61joWOoYGugY6pjGAgA "Husk – Try It Online")
The 'P' string (above: 2 bytes) and the 'S' string (5 bytes) are used twice each.
[Husk](https://github.com/barbuz/Husk) - like many golfing languages - has a short direct solution to the task: `Ċ2S+↔O` ([6 bytes](https://tio.run/##yygtzv7//0iXUbD2o7Yp/v///4820zHXMdEx1rHQsdQxNNAx1DGNBQA)), and, annoyingly, the usually-fussy Husk interpreter is sufficiently lenient to allow this as a runnable program in combination with anything else on subsequent lines: [try it here](https://tio.run/##yygtzv7//0iXUbD2o7Yp/lxwloJGUWpBamJJaopCZppCXmpqSmqKJldiXmV8QHxxSVFmXrqOApCnkFeam5RapJCfplCSmZta/P///2gzHXMdEx1jHQsdSx1DAx1DHdNYAA).
Thus, any 'S' string needs to be shorter than this (or, actually, this plus a newline character) to avoid being trivially-cracked.
Luckily, I don't think Husk has any easy way to implement 'execute this as [Husk](https://github.com/barbuz/Husk) code' or similar, so I hope that brute-forcing the 5-byte solution should be difficult, at least within Husk itself...
---
## Solution
>
> This is a variant of the 'fold across each value of the sorted data, alternately appending to the front or to the back of the output-so-far' approach.
>
> This requires that the data is sorted in descending order, so that the first value added to the output is the largest, and then successively smaller values are added to the front & back. However, Husk's single-byte 'sort' command (`O`) sorts in ascending order.
>
> So, instead of explicitly using a descending sort (which in Husk would be 'sort on greater than', or `Ö>`), we achieve the same thing by sorting reciprocals in two passes.
>
> In the first pass, the data are sorted with the (modified) smallest element in the centre, but the results are the reciprocals of all the data.
> In this way, in the second pass, the data are re-sorted with the largest original element (now the smallest because it's the reciprocal) in the centre, and all the elements are re-reciprocal-ed to restore their original values.
>
> The code for each pass is `F~:↔\øO`, and secret string 'S' is the first 5 bytes of this: `F~:↔\`.
>
> ```
>
> O # sort in ascending order,
> F # then fold over the values,
> ø # using an empty list as an intial result-so-far, by
> ~: # prepending
> \ # the reciprocal of each value
> ↔ # to the reverse of the result-so-far
> ```
>
>
>
>
[Try it online!](https://tio.run/##yygtzv7/363O6lHblJjDO/wRrP///0eb6ZjrmOgY61joWOoYGugY6pjGAgA)
[Answer]
# J, 1 + 9, [cracked](https://codegolf.stackexchange.com/a/241416/64121)
```
~
```
Each string used once.
So, a 10 byte golf that ends in `~`. Easy, easy.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 1 + 5 bytes
```
↔
```
[Try it online!](https://tio.run/##yygtzv7//1HblP///0eb6ZjrmOgY61joWOoYGugY6pjGAgA "Husk – Try It Online")
The 'P' string (above: 1 byte) is used once; the 'S' string (5 bytes) is used twice.
A better-scoring, different (...or is it...?) approach to [my previous Husk answer](https://codegolf.stackexchange.com/a/241744/95126).
Shorter should be easier-to-crack, possibly...
---
Note to Husk golfers and wannabee Husk golfers\*: The week is now up without any crack yet, so I will offer a **100 rep** bounty for the first crack of this, or **200 rep** if it's the cracker's first Husk post.
\*wannabee Husk golfers: Here are the [docs](https://github.com/barbuz/Husk/wiki) and [tutorial](https://github.com/barbuz/Husk/wiki/Tutorial)...
[Answer]
# Bash, 1 + 29
```
'
```
Each string appears once. So, a 30 byte bash golf that begins or ends with a single quote.
To clarify, this doesn't have to be pure bash, but can include standard [posix utils](https://shellhaters.org/) (awk, sed, grep, tr, etc, but no python or ruby or perl, etc). Input can be taken as one number per line, space-separated chars, comma-separated chars, or anything else reasonable.
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-xp`, 11 + 4 bytes ([cracked](https://codegolf.stackexchange.com/a/241797/16766))
```
FiRSNalPBi&
```
The P-string (11 bytes) is used once; the S-string (4 bytes) is used twice.
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgebSSbkWBUuyCpaUlaboWq90yg4L9EnMCnDLVICJQifXRStGm1kbWxtaG1iaxcPUA)
---
My original solution:
>
> S-string `R:l;`, full program `FiRSNalPBi&R:l;R:l;`: Each time through the loop, reverse `l` in-place. After the loop, reverse `l` in-place one more time and autoprint it. The semicolon is an expression separator.
>
>
>
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-xp`, 8 + 7 bytes ([cracked](https://codegolf.stackexchange.com/a/242052/16766))
```
SN:a;R:a
```
The P-string (8 bytes) and the S-string (7 bytes) are used once each.
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgebSSbkWBUuyCpaUlaboWK4L9rBKtg6wSIVyo6PZopWhDa2NrU2tza0trI2sTazNri1i4JgA)
---
Dominic van Essen's crack is quite clever and is also very different from my intended solution. I'm going to think if there's a way to reuse the same idea before I decide whether to reveal it.
] |
[Question]
[
## Challenge
You are given three integers as input - `min_value, max_value, sample_size`, that you can pass to your answer as either array or several parameters.
Your task is to **output a diagram in any convenient format**, that shows the frequency of numbers in the `(min_value, max_value)` range showing up when a random number in the `(min_value, max_value)` range is picked `sample_size` times. The random number sequence should be generated within your answer.
With large ranges and sample sizes, you're free to change the steps your diagram uses, as long as the representation remains accurate.
## Example
With `[1, 5, 10]` as input:
```
o o o x o
x o x x x
x x x x x
1 2 3 4 5
```
With `[1, 100, 15]` as input (in steps of 10, so 00 shows 1-9, 10 shows 10-19, etc.):
```
xx oo oo xx oo xx oo oo oo oo
xx oo oo xx oo xx xx oo oo oo
xx xx oo xx xx xx xx xx xx oo
00 10 20 30 40 50 60 70 80 90
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~34~~ 32 bytes
```
@(a,b,n)hist(--a+randi(b-a,n,1))
```
Doesn't work on TIO, but works on [Octave-online.net](https://octave-online.net/#cmd=f%3D%40(a%2Cb%2Cn)hist(--a%2Brandi(b-a%2Cn%2C1))).
It creates a histogram (bar chart) looking like this:
[](https://i.stack.imgur.com/g3tVWm.png)
I'd say that counts as "Any convenient format".
If non-zero bins *must* be shown, then this can be solved in 38 bytes:
```
@(a,b,n)hist(--a+randi(b-a,n,1),a+1:b)
```
[Answer]
# [R](https://www.r-project.org/), 36 bytes
```
function(a,b,n)stem(sample(a:b,n,T))
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jUSdJJ0@zuCQ1V6M4MbcgJ1Uj0QooohOiqfk/TcNQx9AAiAw0uf4DAA "R – Try It Online")
Sigh. A stemplot.
The bane of existence for second year university students taking *Introduction to Statistics for [This Specific Area of Study]* from some professor who doesn't know what they're talking about but still think stemplots are a good idea because it's still in the 14th edition of the textbook they've been using since the 4th edition was published in 1983.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
≔…·θηθ≔Eζ‽θηEθ№ηι↖←E⮌θ⮌Iι
```
[Try it online!](https://tio.run/##PY09C8IwFEX3/oo3JvAEO7i0k3QSLEjBSRxCjE0gJs1HM/jnY1LU7V3OufdxyTy3TOd8DEHNhpwM12tQSUzMzII4BEkRHO2brzCyhbwRCn7YF3GUVqNvLl6ZuMFSGexagkRQlBY22iRId13O4hn/alcTQm1MIgkfyrOy9bsHFiLZ6jnfWoQDQru/513SHw "Charcoal – Try It Online") Explanation:
```
≔…·θηθ
```
Create an inclusive range of the distribution.
```
≔Eζ‽θη
```
Sample the range the desired number of times.
```
Eθ№ηι
```
Count and print the number of each of the range in the sample.
```
↖←E⮌θ⮌Iι
```
Print the labels.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṫɓr/;"xẊĠ>ʋ¥G
```
Uses a *very* convenient format:
* Prints the values on the left axis
* Uses `0` as the distribution pixels (like the `x`s) and `1` as the background pixels (like the `o`s)
* Uses as many horizontal spaces between "pixels" as there are characters in the maximum length number in the range (e.g. -23 is length 3, while 23 is length 2).
**[Try it online!](https://tio.run/##ASwA0/9qZWxsef//4bmqyZNyLzsieOG6isSgPsqLwqVH////Wzk3LCAxMDMsIDIwXQ "Jelly – Try It Online")**
Note: If the input did not have to be an array it would be **11 bytes** taking two arguments, `[from, to]` and `sampleSize` with just `r/;"xẊĠ>ʋ¥G`.
---
I think this may be taking the convenient formatting allowance just a little too far for 4 bytes:
[`Ṗ;1K`](https://tio.run/##y0rNyan8///hzmnWht7///@3NNcxNDAGYgA "Jelly – Try It Online")
This is using the idea (which should be addressed) put forward by [Giuseppe in the comments](https://codegolf.stackexchange.com/users/67312/giuseppe) with a single bin identified with `from` and `to` separated by a space, another space representing the axis and and a single `1` representing the height of 100%.
...or even just [`Ṗ1`](https://tio.run/##y0rNyan8///hzmmG////tzTXMTQwBmIA "Jelly – Try It Online") for 2 bytes!
[Answer]
# [Python 2](https://docs.python.org/2/), 115 bytes
```
from random import*
a,b,n=input()
r=range(a,b+1)
s=sample(r*n,n)
for v in r:print'%%0%dd'%len(`b`)%v,s.count(v)*'x'
```
[Try it online!](https://tio.run/##DclLCsMgFEDRuatwIn4iJXZSKLiXmGpaIT7laaRdvXV04dzya58M9zEOzImiAz8TU8nYFHF612AjlKsJSdDO/Q5i6mIkqba6VM4gUIEGSY6MtNMIFJ8FIzTO2Mq85@wMILZ9k6zrenvlC5roUvEvH@OhjdFm/QM "Python 2 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 164 bytes
column-based output.
```
from random import*
a,b,n=input()
r=range(a,b+1)
s=sample(r*n,n)
d=len(`b`)
while n:n-=1;print' '.join(d*'ox'[s.count(v)>n]for v in r)
for v in r:print'%%0%dd'%d%v,
```
[Try it online!](https://tio.run/##RYvRDoIgGEbveQpuGGDkpO5s9CKtTQ1MnP6wX7R6enLroqvv7Jx98ZOGAKecewwzxRbsPn6OAVNBWtUpMB7imoQkaPb8dGK3By3JYpZ2jpMTWIACSayZHIimayR5DX5yFGo4Gn2J6CFxyssxeBC24OHNb0v5CCsksckr3PuAdKMeKEry5/p3ZKxi1nJm2aZy1upcKV19AQ "Python 2 – Try It Online")
[Answer]
# Java 11, ~~184~~ 168 bytes
```
(m,M,s)->{int a[]=new int[M],q=M;for(;s>0;q=M)if((q*=Math.random())>m-2){a[q]++;s--;}for(;m<=M;)System.out.printf("%0"+(M+"").length()+"d%s%n",m,"*".repeat(a[m++-1]));}
```
[Try it online.](https://tio.run/##XVHRaoMwFH3fV1wChaRGq2VlMGff9jKwL310QjON1c7ENokdo/jtXaLCxiC55CbnnnvuyYldmX8qP@9Fy7SGlDXy9gDQSMNVxQoOO5cCXLumhALbexDUxXSMmsT2ebDbLm2YaQrYgYQE7ljQlGrib28OyLI8kfzLEWdpTi9JGledwrHehrFNSFNhfFkmKTN1oJgsO4EJ2Qp/TW4su@SeF2vfj4exRrzYarL/1oaLoOtNcFaWtsJoESIPpx5CJGi5PJoaEw@VC72QiAqq@Jkzg9ESUZYJz/OjnJB4uMeT@nP/0Vr18xDjvMK6gffGsh@zHBiZrJBBgdf0iUbhODzAfyWtxPOLg25otKGP4V@jVit4FX3LDC/hzX4ARBEcpj7BrNLSkAMIbuqufP71dgLBDJozbRSF0WTR9bZukqm46ZUEZ/qEw@5Y1ExlEy4nrllrPxmj9xBRSzOLHO4/) (NOTE: `String.repeat(int)` is emulated as `repeat(String,int)` for the same byte-count, because Java 11 isn't on TIO yet.)
**Explanation:**
```
(m,M,s)->{ // Method with three integer parameters & no return-type
// (`m` = min_value; `M` = max_value; `s` = sample_size)
int a[]=new int[M], // Integer-array, filled with `M` amount of 0s
q=M; // Temp integer for the random value, set to `M`
for(;s>0; // Loop as long as `s` isn't 0 yet:
q=M) // Reset `q` back to `M` after every iteration
if((q*=Math.random()) // Pick a random integer in the range [0, `M`)
>m-2){ // If this random integer is larger than `m-2`:
a[q]++; // Increase the value at that this random index by 1
s--;} // And decrease `s` by 1
for(;m<=M;) // Loop in the range [`m`, `M`]
System.out.printf( // Print with trailing new-line
"%0"+(M+"").length()+"d%s%n",// and leading zeros if necessary:
m, // The number
"*".repeat(a[m++-1]));} // appended with "*" repeated the amount of times
// specified in the random array at index `m-1`
```
[Answer]
# [R](https://www.r-project.org/), 52 bytes
```
function(a,b,n)table(cut(sample(a:b,n,T),a:(b+1)-1))
```
[Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP08jUSdJJ0@zJDEpJ1UjubREozgxtwDITLQCCuuEaOokWmkkaRtq6hpqav5P0zDUMdUxNNDkgrI0/wMA "R – Try It Online")
Returns a `table` of frequencies with `names` equal to the half-open intervals selected by `cut`, so `(0,1]`, `(1,2]`, `(2,3]`, and so forth. Makes no effort to select more reasonable binning.
[Answer]
# Ruby, 135 bytes, 117 bytes
```
d=->(m,n,s){p=(m..n);t=(1..s).map{rand(p)};p.map{|h|g=t.count(h);"#{h}-#{'x'*g}#{'o'*(t.map{|e|t.count(e)}.max-g)}"}}
```
Ungolfed:
```
d =-> (m,n,s) {
p = (m..n)
t = (1..s).map{rand(p)}
p.map{ |h|
g = t.count(h)
"#{ h }-#{ 'x' * g }#{ 'o' * (t.map{|e| t.count(e) }.max - g) }"
}
}
puts d.call(1,5,10)
```
[Answer]
## [Perl 5](https://www.perl.org/), 85 bytes
```
/ \d+/;$d[$`+rand$&-$`+1]++for 1..$';say$"x(length($&)-length),$_,"-"x$d[$_]for$`..$&
```
[Try it online!](https://tio.run/##LYzRasIwGEbvfYqPLtSWNjURelHKYC@wJ5iiwfzaDpdkSQru5Rfj3M3hwMf5HPlrn970a1WPeIGnQBFn60HqNGE2boktjI15@V5mTxrzGXEiOG8vXn3hcwkRTvlAAdbQM0kb7HSzGZn@YMfGK6NZybPJfdM8zmXXsfUY1A8rbtWVzCVOFStr/tS6ZYe24MXtkR/2OWDHHJQpSfSQYjUIDEMWsZKZ2P6LEH8Qv9bF2ZqQuEn8ve@EFHc "Perl 5 – Try It Online")
Produces similar output to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)'s [Charcoal answer](https://codegolf.stackexchange.com/a/167543/9365).
[Answer]
# JavaScript, 239
I'm sorry about this, but the variables were just named willy-nilly. Anyway, the question said *any convenient format*, so this function returns a sideways graph
```
f=>{x=Math;z=Array;q=_=>x.floor(x.random()*(f[1]-f[0]))+f[0];r=z(f[1]-f[0]).fill(0);z(f[2]).fill``.forEach(_=>r[q()-1]++);u=`${f[1]}`.length;return r.map((e,i)=>`${`${i}`.padEnd(u)}${" x".repeat(e)}`.padEnd(x.max(...r)*2+u," o")).join`\n`}
```
[Answer]
# Japt `-R`, 14 bytes
Takes input in the order max, min, size. Outputs the chart horizontally.
```
õV
öW
Ë+QpVè¥D
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=9VYK9lcKyytRcFbopUQ=&input=NSwxLDEwCi1S)
---
## Explanation
```
:Implicit input of integers U=max_value, V=min_value & W=sample_size
õV :Range [U,V]
\n :Reassign to U
öW :Get an array of W random elements from U
\n :Reassign to V
Ë :Map each integer D in U
+ : Append
Q : Quotation mark
p : Repeat
Vè : Count the elements in V
¥D : That equal D
:Implicitly join with newlines and output.
```
[Answer]
# Pyth, 19 bytes
```
JmOK}FPQeQVK,N*/JNd
```
[Try it here](http://pyth.herokuapp.com/?code=JmOK%7DFPQeQVK%2CN%2A%2FJNd&input=1%2C%205%2C%2010&debug=0)
### Explanation
```
JmOK}FPQeQVK,N*/JNd
K}FPQ Get the inclusive range between the first two inputs as K.
JmO eQ Get <last input> random elements as J.
VK For each value in the range...
,N ... output a list of the value...
*/JNd ... and spaces equal to the count in J.
```
] |
[Question]
[
# The Challenge
Given a grid of numbers (10 <= N <= 99)
Return number with the highest sum of the four numbers adjacent to it; that is the numbers above, below, right, and left of the number, but not itself.
1. The number itself does not count, only its four neighbors.
2. A number on the edge *should* be treated as though the missing number is a 0.
3. I will design the test to avoid ties.
4. Numbers will not repeat.
5. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
# Example
Given
```
56 98 32 96
12 64 45 31
94 18 83 71
```
Return
```
18
```
# A Real Test
Given
```
98 95 67 66 57 16 40 94 84 37
87 14 19 34 83 99 97 78 50 36
18 44 29 47 21 86 24 15 91 61
60 41 51 26 10 58 11 62 55 71
42 85 56 12 46 81 93 65 49 77
89 13 74 39 54 76 92 33 82 90
96 88 70 79 80 28 25 20 75 68
38 63 17 72 53 48 73 30 45 69
64 35 32 31 23 43 22 52 27 59
```
Return
```
13
```
Given
```
82 43 79 81 94 36 17 64 58
24 52 13 87 70 18 28 61 69
16 99 75 21 50 44 89 90 51
49 80 63 31 54 65 41 55 38
67 91 76 78 23 86 83 14 73
46 68 62 77 34 48 20 74 10
33 35 26 97 59 66 25 37 32
12 92 84 27 85 56 22 40 45
96 15 98 53 39 30 88 71 29
60 42 11 57 95 19 93 72 47
```
Return
```
15
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~20~~ ~~15~~ ~~13~~ 12 bytes
```
t1Y6Z+tuX>=)
```
Saved 5 bytes thanks to Emigna, 2 thanks to Giuseppe, and another thanks to Luis Mendo.
[Try it online!](https://tio.run/##FY87Um1RCAWn0qn1ks0f6tRzHH7KwFyz6/iPGEIvoPn@fHzd90Ne8@3f4@fl@f/Tfb9PM0EWmUQhiR/GacfqorflyGDbMmaYopo4WF5I444OXqjQiW46GCHlIg8uhKCJHKKRBUoEtdiVDmKZ4kkLY2TgQ/3dHsSoFRnCqWQUM1qZczE70dShhj5oo4Fuue/0hTVpyNruPcM3atgKLZ5V27WB7cK1W2zo5hQtYj5@AQ "MATL – Try It Online")
### Explanation
```
t1Y6Z+tuX>=)
t Duplicate the (implicit) input.
1Y6 Push the array [0 1 0; 1 0 1; 0 1 0].
Z+ Convolve with the input.
uX> Get the maximum unique element...
t = ... and compare elementwise.
) Index into the input.
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~31~~ ~~27~~ ~~26~~ ~~24~~ 23 [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")
-2 thanks to Cows quack. -1 thanks to ngn.
Anonymous tacit prefix function. Takes a matrix as argument. Assumes `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems.
```
{⊃⍒,(+/--/)⊢∘,⌺3 3⊢⍵}⊃,
```
[Try it online!](https://tio.run/##JZK9apRBFIZ7r@ItFXfJ/Jz5ObVNUgWMNxCQtQloK2IVCLK4IQoBa2/ARhtLL2VuZH3OBpaF@b53vnmf58z1h5vt24/XN@/fHdf948XluntIx09rf7sO3zfPX55tt2cv1v7n@vJjs77@raqxOPz5TGJz3JFeh/unjfvbf7/quvvG6ur1K/7fnF9cHXeqsnX43bp8qhZ5Vy7qJmuqWW7KU7Nq5Gc7uXIiTNKb@lDvakO5y1Ikp6kOTZ6wy1UtNrrLh8ZUS6o9vmam4rKhkjW7CuEmz@r8kiyrZRWSSW0q87CoNQrIimZTOzW0rkm9qt5krsG5tKMnHVzNNCAqqlUTqBRcc2okDddMKlOlqbAEBPCpXpXpyVkYIYnLFBK6h43aQg5CCm@rCrGiMtQcLTR1tHAQr@L7J28BO2IvFDCSpx5y6IAECgSvhz0UUQMbKEIOIBRGgp2qUoxzIQrSHCqi7QhjMCKWSmhENdqpjRmIkIYTRgBLYFq0xAYguPVoHuNDAiMDDaXoYoJAPUmG0U4G4kq0uB6YwS1awmSOIca8SsyIa8CVYOhMBIc2/gM "APL (Dyalog Unicode) – Try It Online")
`,` ravel (flatten) the input
`{`…`}⊃` pick an element from that according to the result of the following function:
`⊢⍵` yield the argument (separates `3 3` from `⍵`)
…`⌺3 3` apply the following function to each 3-by-3 neighbourhood:
`⊢∘,` ignore the edge-information in favour of the ravelled (flattened) neighbourhood
`(`…`)` apply the following tacit function to those
`-/` the alternating sum (lit. right-associative minus reduction)
`+/-` subtract that from the sum (this gives the sum of every other element)
`,` ravel (flatten) that (the neighbourhood sums)
`⍒` produce the indices which would sort that
`⊃` pick the first (i.e. the index of the highest sum)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
;€0ZṙØ+SṖ
,ZÇ€Z+$/ŒMœị
```
[Try it online!](https://tio.run/##FZC7TUNBFERz6iDzkdjP/eyKGojIbDkkQW6AlISADCRkeqABi9ByIaaRx7xoVzv3npnZ56fD4WVZ7v9ef8r2evo@HzeP19PXDdvzm962m9u7y8fD5fP6@74sy243GtbJyahMowc1CcPHnl3T2aidkWShDtogKjEl1mBO0mkVL5gxJrPgVaIJWIhOl2iEY7o4fcVGMisZpICCB6NTjezrZhAyaWTSDdNIIY1aJHYBZSjnxCcRNDE12NZAjdkYRkuG4xJVTslc4lQxZw5ciEkvjEFW2lolNKSeSqhkTlUP/YmWc7//Bw "Jelly – Try It Online")
~~Not having convolution built-ins like MATL and Dyalog~~ *Forgetting your language has convolution built-ins* (thank you @dylnan) hurts, but we can do sort of okay without them, partially thanks to `ŒM` and `œị`. First, a helper function to compute neighbors in just one direction, which incidentally transposes the input:
```
;€0Z Append a zero to each row, then transpose.
ṙØ+S Rotate by +1 and −1 (Ø+ = [1,-1]) and sum these.
Ṗ Pop the last row.
```
Visually, the computation is:
```
1 2 3 ;€0 1 2 3 0 Z 1 4 7 ṙØ+ 2 5 8 0 0 0 S 2 5 8 Ṗ 2 5 8
4 5 6 ————→ 4 5 6 0 ——→ 2 5 8 ————→ [ 3 6 9 , 1 4 7 ] ——→ 4 10 16 ——→ 4 10 16
7 8 9 7 8 9 0 3 6 9 0 0 0 2 5 8 2 5 8 2 5 8
0 0 0 1 4 7 3 6 9 4 10 16
```
Interpretation: cell (x, y) of this result is the sum of cell (y, x)'s horizontal neighbors. (For example, here we see that **f(A)[2,3] = 16 = 7 + 9 = A[3,1] + A[3,3]**.)
Then, the main function:
```
,ZÇ€ Pair the input with its transpose and apply helper to both.
Z+$/ Fold by Z+, i.e., turn [X,Y] into transpose(X)+Y.
Now we've summed the horizontal and vertical neighbors for each cell.
ŒM Find the 2D index of the maximal value.
œị 2D-index (into the original input).
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
5BæcµḊṖ)
ZÇZ+ÇŒMœị
```
[Try it online!](https://tio.run/##DZA9SkRBEITzOUWlYjI907@puanBpmIiewFTkwXNFDyCkZEorGzmYw/yvMizYGZo6Oqvq@b@br9/2Da7Wt5vf7/X49P683bRdsthd7kczi/X59f19Lytp6/1@Pn3@HHDy7Mcti0HdCIKKSjFdEjAFZZt8B2QiQxEhyRGwgVeTRxVCMMQWIcqslAdJk2J6vCJyZbCDcrCMLN5oAThCKKIdeSEKGI2dTjhAxGYCqWgIxTS2ySKi7gxYAV3DNIoG00GaiAVI5AGY4tx6MdaMYihEsbxwuzIRAhGNaeAueiKfgxC5/wBDsY/ "Jelly – Try It Online")
The helper function finds the neighbors of each element in each row. The main function does this to the rows and the columns then finds the element that has the maximum neighborhood sum.
```
5BæcµḊṖ)
5B bin(5): 1,0,1
æc Convolve with [[1,2,9],[other rows]] (for example): [[1,2,10,2,9],...]
µ New chain.
) Apply this to each element:
Ḋ Remove the first element.
Ṗ Remove the last element.
Gives [[2,10,2],...]
ZÇZ+ÇŒMœị
Z Zip the matrix
Ç Apply helper function
Z Zip again. Yields the sum of the vertical neighbors of each element.
+ Add:
Ç The sum of each element's horizontal neighbors.
ŒM Find the multidimensional index of the maximal element.
œị Index back into the original matrix.
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 58 bytes
```
Im@Last[Union@@ListConvolve[{a={0,1,0},{1,I,1},a},#,2,0]]&
```
Convolve the matrix with \$ \left( \begin{smallmatrix} 0 & 1 & 0 \\ 1 & i & 1 \\ 0 & 1 & 0 \end{smallmatrix} \right) \$, take the element with the largest real part, and take its imaginary part.
[Try it online!](https://tio.run/##PZJLaxsxFIX/isCQlUpHb2mRYsgqkEU3XRkvhpJQQ2xDM2QzzG93zifVXQjpXt3nOec8L39ez/Ny@j3f3syjuT2f9y/zx3L4dTldL/v9y@ljebpePq/vn6@HdX5cJ@vstNnV2WfrNjtvdme9nY7Hh9vPv6fLctiZbz/M22F3PJoH831v1nVN2ZpWrQled96sWZ1eOVoTk7wOT5PlFFODNcVtuFZymiJy0VGNpNvpjpP8iq86oRBa@aFCkyeOKk3vJn9RlaSMMDrLiorw@o369U7RqunJVq8mO/eJsnKirKTjFeFkJ2U7IjR/Sn1SRUZZVRZ7slnUXRXVNEWWP6pXGXPq5diQyfVOugvoKCvIX0Fo6nhQQ92KuhZFVt1etlc9jw9cKpFB3qxcx67MpXckU3eYBsa59Y3omgYPga2I1PFk6XhVSG1gzyT89d5u4B3y6EKd1HuDGpnsBAdMC8JMmt29L5zBBjODN2zAAWg0UB0o/tuSXZgObDp6bmAdeke0AEegBrPsAH8wjgJK6LUy6AyeShmaAJOOHEx3jEEcPGC39d2HzsA4kOXvWoUf1AZCd6ZBLXZ873x1/dTBAOyCfucQrNt/TfmhIdSMutEsSoG7WLZtu30B "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 127 bytes
```
def f(a):n=len(a[0]);b=sum(a,[])+[0]*n;print b[max(range(len(b)-n),key=lambda i:b[i-1]*(i%n>0)+b[i+1]*(i%n<n-1)+b[i-n]+b[i+n])]
```
[Try it online!](https://tio.run/##LVDLbsIwELz3K7hUSmAi@bm2ofRHIh8SEdqo4CJKpfL16Zj2lOx6dl6X@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jzxUrIyLTmgUR2v8pcDV5zhrnjkPFiJmCT1eml38 "JavaScript (Node.js) – Try It Online")
### How?
Instead of looking for the maximum of the sum of the 4 neighbors, we look for the minimum **m** of the sum **s** of their one-complements. This allows us to process undefined values just like zeros, because:
```
~undefined === -1
~0 === -1
```
The inner **map()** is written in such a way that it does not alter the content of the row **r**. Therefore, we can save its result in **p** in order to test top neighbors in the next iteration.
We use:
* `~r[x-1]` for the left cell
* `~r[x+1]` for the right cell
* `~p[x]` for the top cell
* `~(a[y+1]||0)[x]` for the bottom cell
[Answer]
# [Stencil](https://github.com/abrudz/Stencil), 1 + 10 = 11 bytes
Command-line option: `1` compute 1 generation
```
y⊃⍨⊃⍒,
+/N
```
[Try it online!](https://tio.run/##Ky5JzUvOzPn/v/JRV/Oj3hVgcpIOl7a@3///xgomj3q3mJopWFooGBspWJopGBopmJkomJgqGBsqWJooGFooWBgrmBv@yy8oyczPK/5vCAA "Stencil – Try It Online")
`y` from the flattened original input
`⊃⍨` pick
`+/` sums of
`N` the von neumanN neighbourhoods without selves
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~43~~ 40 bytes
```
{(,/x)@*>,/(+g@+x)+(g:{(+':x)-|-':|x})x}
```
[Try it online!](https://tio.run/##NZLBTiMxEETvfEUdkJghRIzddrt7RkL8B4rEXhKtWIGEOAyC8Ouh2skex1Ptrnrll@3r4fV02s9fw939Oj7ePtzdD5vD42YdN8OBp5ubeR2339ub@Xs9juvx9DF/XT99/rzPe6zL89vLMjzv//z9t6zL5/I@7o5XH09DVbhBMlyvAKQMLSgVkuLTC5LBBC2NS7JdTFDuFdqgitqQFGUKoRVIiyHjIeccUmLUHd7QDHWCnJcYSkF2lIacYIpMfYUnaF@rE0pCTciKNKEaEn9l1EojISgZVkHv9FsUluACrSiOdvbgSHRNS45a0JgyQwTGoFNPxilDm9AcNiEbckXmJ6NZCMSggkTn3CsoFAtkCjbq3SQvr0FO6JMCQaYyIzdUJy3ptLiQf2JJCkiicSVHa1/C3JygUzKjF4KhEU2XDURLeHRESIRHZozl5HFm0I3TI/czYqRPQUj6zeyHOJmb4OmOjFkFa2nSZ5Upg2hr0RLDRXSW0NmQE5ORvUeU6JlshMp8eSJkybYZ9FwCc5cAc@EaTVowI3sCC8wk5P@LzVEmHw4fEd8IeyPg0gis7k6/ "K (ngn/k) – Try It Online")
[Answer]
# Java 8, 187 bytes
```
m->{int r=0,l=m.length,i=l,L,j,S=0,s;for(;i-->0;)for(L=j=m[i].length;j-->0;)if((s=(i<1?0:m[i-1][j])+(i<l-1?m[i+1][j]:0)+(j<1?0:m[i][j-1])+(j<L-1?m[i][j+1]:0))>S){S=s;r=m[i][j];}return r;}
```
[Try it online.](https://tio.run/##nZLNbtpAFIX3eYpZGuWAPP8zcZ28QJoNS8SCEpLaNU5kO6kq5GenZyBtzLKVAOEz13Pv@c6tN@@bef3447htNn0vvm6q9nAlRNUOu@5ps92Jh/R4EsQ24@9qvVqL/aygOvLLTz9shmorHkQrSnHcz28PqbgrczTlftHs2ufhO6qywT1qLCn3xdNLlxXVfH6bF7P0/76sy/2qWn9UF/X5qHrKsr7Mqi/yLr/h@VyuV/V6dk2lmcs7Ktcn5SanVv@posLCk3J/rqLCQlbNbpezw7Lsi648y@ti7HbDW9eKrhiPxdnQ69u3hoY@fL2/VI9iTy7Zcuiq9pn2N91zPztzWf7qh91@8fI2LF55OjRt1i62Wbv7KT5gneuEOFiHGKAVohvxR5QKzsBYaPkpRgMZEDS8HE/aODsB/6d27BUtnIdzsB7SweTgzcFA@89egUdsF6FN6hgjoocPsDn0dM4AY6AijIeSCA6Kb1lECTeZ3OUwElZCOcgcNkCyQMHa5OVvmVEIFgRC@8YhSEQNZ2Ei/HS2CEkIHDjCGngCVNAagQzzCS7eEOBz@IiQQwUoC8VH2g@fZTrAaUi64zwahq9o6DzBd3Fige1siknTBcs0FOsVlIeN/x8HZ@ZVaUKZUtAuTcJedjIhkbIRLTMU2iFzenHyYjzmyIxojSkwI4ZCSpGop3hPHGiWFsgtgZUpAj3pxcVgdkTKrGmTgTJ9boLXk3scAab4vE/rQWKJKnOfwGccxMW4Y@KTlo3wNevVxZIzOC4eGZ5zJ1KTyF@EmNYppGgYN3NJmTKCeLldKm0U95m7zaXl2jBN4y9yGa/G428)
**Explanation:**
```
m->{ // Method with integer-matrix parameter and integer return
int r=0, // Result-integer, starting at 0
l=m.length, // Amount of rows
i=l, // Rows index integer
L, // Amount of columns
j, // Column index integer
S=0, // Largest sum of four cells
s; // Current sum of four cells
for(;i-->0;) // Loop over the rows
for(L=j=m[i].length;j-->0;)// Inner loop over the columns
if((s= // Set the current sum to: the sum of:
(i<1?0:m[i-1][j]) // Value of the cell to the left, or 0 if out of bounds
+(i<l-1?m[i+1][j]:0) // Value of the cell to the right, or 0 if out of bounds
+(j<1?0:m[i][j-1]) // Value of the cell down, or 0 if out of bounds
+(j<L-1?m[i][j+1]:0))// Value of the cell up, or 0 if out of bounds
>S){ // If this current sum is larger than the largest sum:
S=s; // Replace the largest sum with this current sum
r=m[i][j];} // And set the result to the current cell
return r;} // Return the result
```
[Answer]
## Javascript ES6, 170 bytes
```
c=g=>{s=0;n=0;f=m=>m||[];for(i=0;i<g.length;i++)for(j=0;j<g[i].length;j++){s=~~f(g[i-1])[j]+~~f(g[i+1])[j]+~~f(g[i])[j-1]+~~f(g[i])[j+1];b=s>n?g[i][j]+!(n=s):b;}return b}
```
] |
[Question]
[
>
> This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge, the cops thread can be found [here](https://codegolf.stackexchange.com/questions/137379/seeking-secret-swapping-sequences).
>
>
>
This is the robbers thread, your job here is to take submissions on the cops thread and try to find the hidden sequences. If you find any sequence that can be substituted into the original code to compute that sequence that is a valid crack. Please notify the cops of your cracks as they happen so they can update their answers.
## Scoring
Your score will be the number of successful cracks you have made, with more cracks being better.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy), [A000290](https://oeis.org/A000290)
```
p#A000290uCnG
```
[Try it online!](https://tio.run/##y0osKPn/v0DZ0cDAwMjSoNQ5z/3/f3MA "Japt – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/): [Mr. Xcoder](https://codegolf.stackexchange.com/a/137390/), [A010709](https://www.oeis.org/A010709)
```
n=int(input())
print(sum(1for i in"A010709"if i>"0")*-~n//-~n)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P882M69EIzOvoLREQ1OTq6AIxC0uzdUwTMsvUshUyMxTcjQwNDA3sFTKTFPItFMyUNLU0q3L09cHEpr//5sAAA "Python 3 – Try It Online")
Additionally, here's a golfed version of the original. :P
```
lambda n:sum(1for i in"A017016"if i>"0")*-~n//-~n
```
[Answer]
# Python 3, [pppery](https://codegolf.stackexchange.com/a/137430/56656)
>
> [A018226](https://oeis.org/A018226)
>
>
>
The original code put the sequence name in a comment. Since the comment probably can't affect the code I figured the hidden sequence had to be some sub-sequence of the original. A quick search of the first couple terms brought up A018226. Since it is a sub-sequence the code works for both. A018226 is even listed on the original sequence's page if you look back
>
> One way to generalize the magic number sequence in A018226.
>
>
>
[Answer]
# [C#, TheLethalCoder](https://codegolf.stackexchange.com/a/137383/58974)
>
> [A000578](https://oeis.org/A000578) (Cubes)
>
>
>
An easy one - it was also posted [here](https://codegolf.stackexchange.com/a/137214/58974).
[Answer]
# [Python 2, Dead Possum](https://codegolf.stackexchange.com/a/137399/38550)
>
> [A000007](https://oeis.org/A000007): The characteristic function of 0: a(n) = 0^n.
>
>
>
[Answer]
# [C#, TheLethalCoder, A000244](https://codegolf.stackexchange.com/a/137393/3852)
Also works with [A000079](https://oeis.org/A000079) (powers of two).
[Answer]
# [Python 2, Dead Possum](https://codegolf.stackexchange.com/a/137399/38550)
>
> [A000244](https://oeis.org/A000244) (Powers of 3)
>
>
>
---
This no longer works, the OP updated the example after I posted this.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), [Bruce Forte](https://codegolf.stackexchange.com/a/137431/15259)
Cracked with [A027480](https://oeis.org/A027480).
[Answer]
# [Python 2](https://docs.python.org/2/): [officialaimm](https://codegolf.stackexchange.com/a/137423/), [A055642](https://oeis.org/A055642)
```
lambda x:len(`x**(sum(map(int,'A055642'[1:]))==22)`)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCKic1TyOhQktLo7g0VyM3sUAjM69ER93RwNTUzMRIPdrQKlZT09bWyEgzQVPhf0ERUFYjDaQGiAtKSzQ0geC/oYkJAA "Python 2 – Try It Online")
It took me a while to find the sequence... Mostly 'cause OEIS search is *super* slow for me. o0
[Answer]
# [Python 3](https://docs.python.org/3/), [ppperry](https://codegolf.stackexchange.com/a/137452/53748), [A000027](https://oeis.org/A000027) -> [A004526](https://oeis.org/A004526)
```
f=lambda a,n=((int("A004526",11)-0x103519a)%100%30+1)/2:a//(14-n)
```
**[Try it online!](https://tio.run/##FY1BCsIwEADP7StCoLCLKdlNWsVCD75DPEQ0WtBtaUvR10czpzkMzPRdn6P4lOI4q0UNokCf6I87aJOtad1eY1cWsX@F9/UWVDDSAwyywmKYsaYPk2/5GLBiosrTjtG6LlgL3NSCZTHNuT5H2FDlz5Y/c5DHHbzHC6b0Aw "Python 3 – Try It Online")** (prints first few terms of both. Note the two sequences have offsets of 1 and 0 respectively, so the first has a leading zero - it threw me a little!)
[Answer]
# [MATL](https://github.com/lmendo/MATL), [Cinaski](https://codegolf.stackexchange.com/a/137417/15259)
Cracked with [A055642](https://oeis.org/A055642).
[Answer]
# [Python 3.6](https://codegolf.stackexchange.com/a/138161/56819), [RootTwo](https://codegolf.stackexchange.com/users/53587/roottwo)
Original is [A005843](https://oeis.org/A005843)
Cracked with [A001107](https://oeis.org/A001107)
[Try it online](https://tio.run/##Hc67DoIwFIDhnadoIKY9xRJKuWnC4Cu4GofKtQqnpBITn75epn/5hn99b5NF5f3g7EKcxu4bs6zWbTwYm1kvt04TPPYvPTNKk7s1yM5/xsJTmkqZViEk7WRN2z8ZxVocYllhVPM4K3coicqEinNR5AUXUckrun80KgeAIFidwY1dRoZABusIEoO/h7FnKoMreP8B)
The eval'd code of the original (minus comments) is `n*2`, of the cracked version is `4*n*n-n*3`.
After filtering out syntax errors, undeclared variables, zero divisions, etc, it didn't take too long to run through the remaining list. There were a few false positives (like A004917) that I had to filter out by hand due to only checking the first few numbers, but it wasn't too common.
Also, A040489 tries to calculate `n**3436485154-n`, which slowed me down a bit. :P
[Answer]
# [Chip](https://github.com/Phlarx/chip), [Phlarx](https://codegolf.stackexchange.com/a/137665/15259)
Cracked with [A060843](https://oeis.org/A060843). On a hunch, guessed the sequence was going to be short!
] |
[Question]
[
Given a string `s` and a positive integer `N`, gradually duplicate each character more and more until `N` duplicates, and then staying at `N` duplicates until `N` characters away from the end, then step down again.
For example, given `abalone` and `3`:
```
a we start with 1 copy
bb then 2 copies
aaa then 3 copies, which is our second parameter
lll so we continue using 3 copies
ooo until we reach the end
nn where we use 2 copies
e and then finally 1 copy
```
and the result would be `abbaaalllooonne`.
It is guaranteed that the string has length greater than `2N` and only has characters from `a` to `z`.
More testcases:
```
N string output
2 aaaaa aaaaaaaa
3 abcdabcdabcd abbcccdddaaabbbcccdddaaabbbccd
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
JṡFṢị⁸
```
[Try it online!](https://tio.run/##y0rNyan8/9/r4c6Fbg93Lnq4u/tR447/h5frP2paE/n/fzSXQrR6YlJiTn5eqrqOgnGsDlgABIBcIyg3KTkFhsGKuGIB "Jelly – Try It Online")
### How it works
```
JṡFṢị⁸ Main link. Arguments: s (string), n (integer)
J Get the indices of s.
ṡ Split the indices into overlapping chunks of length n.
F Flatten the array of chunks.
Ṣ Sort the resulting array of indices.
ị⁸ Get the characters of s at these indices.
```
### Sample run
```
JṡFṢị⁸ "abalone", 3
J [1, 2, 3, 4, 5, 6, 7].
ṡ [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7]]
F [1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7]
Ṣ [1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7]
ị⁸ "abbaaalllooonne"
```
[Answer]
# [Python 2](https://docs.python.org/2/), 57 bytes
```
f=lambda s,n,i=1:s and s[0]*len(s[:i][:n])+f(s[1:],n,i+1)
```
[Try it online!](https://tio.run/##bcqxCoAgFEDRva8Qp8w3ZE0JfYk4WGYK9pJs6eut1mi8h5uu0@/YleLGaLbJGpIBIYxCZmLQkqxa3cQF66xk0EqiZtw9IaR@Py5YSUfAk7iammm2i1s9hZ5VX/1BCuJDFAZWbg "Python 2 – Try It Online")
Also 57:
**[Python 2](https://docs.python.org/2/), 57 bytes**
```
f=lambda s,n,i=1:s and s[0]*len(s[:i])+f(s[1:],n,i+(i<n))
```
[Try it online!](https://tio.run/##bcqxDkAwFEDR3Vc0nfp4gzJp9EukQ6nShEfU4uuLVWw3J3e/znmjKiWvF7v2zrKIhEFLFZklx2JXmnwZScROBQOFf0Iq8z6FCC0BpP0IdDIvuO0HN/pp5lhD9tUf5Cg/xLGBdAM "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), ~~67~~ 65 bytes
*-2 bytes thanks to [Chas Brown's shorter method](https://codegolf.stackexchange.com/a/129704/69583) using `min()`.*
```
s=>n=>s.replace(/./g,(c,i)=>c.repeat(Math.min(i+1,s.length-i,n)))
```
Takes input in currying syntax: `f("abalone")(3)`.
## Test Snippet
```
f=
s=>n=>s.replace(/./g,(c,i)=>c.repeat(Math.min(i+1,s.length-i,n)))
```
```
<div oninput="O.value=f(S.value)(+N.value)">String: <input id=S> N: <input id=N size=3></div>Out: <input id=O size=50 disabled>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes
```
J««U$⁸x
```
[Try it online!](https://tio.run/##y0rNyan8/9/r0OpDq0NVHjXuqPj//39iUmJOfl7qf2MA "Jelly – Try It Online")
**How it Works**
```
J««U$⁸x - main link, input e.g. abalone
J - range of length of letters: [1,2,3,4,5,6,7]
« - minimum of each term with second input: [1,2,3,3,3,3,3]
«U$ - termwise minimum with the reverse:
min([1,2,3,3,3,3,3],[3,3,3,3,3,2,1])=[1,2,3,3,3,2,1]
⁸x - repeat each character of the input a number of times corresponding to elements:
a*1;b*2;a*3...e*1 = abbaaalllooonne
```
*-1 byte thanks to @LeakyNun*
[Answer]
## [Haskell](https://www.haskell.org/), ~~61~~ 60 bytes
*Thanks to @Laikoni for helping to shave off 1 byte*
```
n#s=do(i,c)<-zip[1..]s;replicate(minimum[n,i,length s-i+1])c
```
[Try it online!](https://tio.run/##bY3BCsIwEAXvfsWSekhIW6getf5I6SGmwS4mm9LEiz8fidoK6sA7DcMbVbgaa1OiIrSD51hqcazuOHVNXffhMJvJolbRcIeE7uY6KrG0hi5x5EFUKJte6OQUErQweJhmpAhbYHsoQJ2V9WTgSXUCBlICz4a9FRMbWFnbXW4zi/lqM//L16selv28fhQT6QE "Haskell – Try It Online")
Ungolfed:
```
(#) n string = do
(i, char) <- zip [1..] string
replicate (minimum [n, i, length(string)-i+1]) char
```
[Answer]
# [Haskell](https://www.haskell.org/) (Lambdabot), 74 bytes
```
r=replicate
f x n=join$zipWith r([1..n]++r(length x-2*n)n++reverse[1..n])x
```
[Try it online!](https://tio.run/##JcqxCsJADADQ3a8IpUNr8UCdOzl3dhCHqKmNpsmRHnL482fB9fEmXN4kUniO5glOpslNwmCKj@K9UxS@Y6LNCBm0fxlr/eV45jSBN5d9CHrtOm@E9LlS3h222uoq9CFf6B/aXGZkhR6isyaoYYQKbyimVMGx/AA "Haskell – Try It Online")
[Answer]
# J, 24 bytes
```
(<.&n<./(|.,:[)>:i.#s)#s
```
The bit in parens -- `(<.&n<./(|.,:[)>:i.#s)` -- creates the `1 2 ... n n n ... 2 1` array, as follows:
```
#s length of s, call it L
i. numbers 0 1 ... L-1
>: increment by 1, now 1 2 ... L
(|.,:[) fork: |. = reverse, ,: = stack, [ = identity
resulting in L ... 2 1
1 2 ... L
<./ min of each element of the top and bottom row
<.&n min of each resulting elm and n
```
once we have that, J's `#` operator automatically does exactly what asked for, duplicating each element the number of times specified.
Curious to see a J expert's improvment on this...
[Answer]
# PHP>=7.1, 75 bytes
```
for([,$a,$n]=$argv;--$z?:($x=$a[$i]).$z=min($n,strlen($a)-$i,++$i);)echo$x;
```
[PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/3066bc5793d82918b5c1eba515ea02e999d3f674)
# PHP>=7.1, 78 bytes
```
for([,$a,$n]=$argv;~$x=$a[$i];)for($z=min($n,strlen($a)-$i,++$i);$z--;)echo$x;
```
[PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/9dbe2b8f89106e0fecfa1f17adc9604792260f9a)
# PHP>=7.1, 80 bytes
```
for([,$a,$n]=$argv;$i<$l=strlen($a);)echo str_repeat($a[$i],min($n,$l-$i,++$i));
```
[PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/f862e2c131ce1d618f741b82cfa77e6d14ccb3b4)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~11~~ 10 bytes
```
ËpVm°TEnUÊ
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=y3BWbbBURW5Vyg==&input=ImFiYWxvbmUiCjM=)
---
## Explanation
Implicit input of string `U` and integer `V`.
```
Ë
```
Map over `U` and replace every character.
```
Vm
```
Get the minimum of `V`, ...
```
°T
```
`T` (initially `0`) incremented by 1, ...
```
EnUÊ
```
And the index of the current character (`E`) subtracted from (`n`) the length (`Ê`) of `U`.
```
p
```
Repeat the current character that many times.
Implicitly output the final string.
[Answer]
# [R](https://www.r-project.org/), 87 bytes
```
function(N,s)paste(rep(strsplit(s,"")[[1]],c(1:N,rep(N,nchar(s)-2*N),N:1)),collapse="")
```
[Try it online!](https://tio.run/##FctBCoAgEEDRu7iaiWlh7YSuMBeIFpMoBaLi2Pmtlp/HbyNuIz7Z97tkYFKsoj1ACxW0N63p7qBkDO67PQ7yYB3Tr0zZX9JAcV4mRmJnEcmXlKRq2L5jRFjJyCmp5PDlCw "R – Try It Online")
[Answer]
# Python 2 68 bytes
```
f=lambda s,n:''.join(s[i]*min(i+1,len(s)-i,n)for i in range(len(s)))
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~10~~ 9 bytes
```
₁₁ṀR
↔z↑N
```
[Try it online!](https://tio.run/##yygtzv7//1FTIxA93NkQxPWobUrVo7aJfv///zf@n5iUmJOflwoA "Husk – Try It Online")
The first line is the main function, it repeats each letter *n* times and then calls the second line twice.
The second line takes at most N letters from each group of repeated letters, where N is the 1-based index of the group, then reverses the list.
[Answer]
# [Haskell](https://www.haskell.org/), 68 bytes
```
g 1
g _""_=""
g i(a:b)n=(a<$[1..min(length b+1)$min i n])++g(i+1)b n
```
[Try it online!](https://tio.run/##bYq9CoMwAIR3n@KIDhFRkG6lGaQUFylC6dQWyY/EYIyltVPps6dZukiHg@/uu4E/x95a/85jNNWxPlf1Afu2RZx/opFdvUYZaXSEdIyQQIbyrUgdo3yXXMqimIyjtnd6GSCyMk1Ch4G7pVmmqQmLgPMTDyuDmiPg/lpOy6NxSDCCcMHt7HqCzR8l1S8rH5yQUiqlOA@4YkXC138B "Haskell – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 15 bytes
```
{⍵/⍨⍺⌊i⌊⌽i←⍳≢⍵}
```
`{`…`}` function where left argument (cap) is *⍺* and right argument (string) is *⍵*:
`≢⍵` count the number of characters in the string
`⍳` generate that many **ɩ**ntegers
`i←` store in *i*
`⌽` reverse
`i⌊` pairwise minimum with *i*
`⍺⌊` pairwise minimum with the cap
`⍵/⍨` use those numbers to replicate the letters of the string
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71b9R/1rnjUu@tRT1cmED/q2ZsJlHjUu/lR5yKgbO3//8YKaQrqiUlAXXmp6lxGYB4IqHNBZZJTYFgdAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [F#](http://fsharp.org/), 96 bytes
```
let f(s:string)n=Seq.mapi(fun i c->System.String(c,Seq.min[i+1;s.Length-i;n]))s|>String.concat""
```
[Try it online!](https://tio.run/##NcqxCsIwEIDhVzkOhARNQNws9gm6ZRSHGJN6YC/VOwfBd49ScfiHH74ibqpcW7tlhWJkL/ogHi0fQr77Kc5kypOBILk@vETz5MMiTNosgvhI620nfsg86tVRxydr5d3/mE@VU1TENn9XCwOuBMEUwHhOl38IO9s@ "F# (Mono) – Try It Online")
A port of [Justin Mariners javascript answer](https://codegolf.stackexchange.com/a/129703/20151)
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~101~~ 97 bytes
```
n->s->{int i=0,j;for(char c:s)for(j=s.length-i++,j=j<i?j:i,j=j<n?j:n;j-->0;)System.out.print(c);}
```
[Try it online!](https://tio.run/##nY5NawIxEIbv/orBU1LdIO3NuFuKUOihJ4/iIcZdTcxOQjIrLLK/fbsrFmpPpQPDfL0881p1UZkPJdrDuTd18JHADjvRkHGialCT8Sie5CQ0e2c0aKdSgk9lEK4TgPs2kaKhXLw5QD3c2IaiweN2ByoeE79JAT6Q3u/E1dpjauoyrvRJxe2uKKDKe8yKlBVXgwQmX8ytrHxkowD0MvFxsHkSrsQjnTIzm81tblfm1S7NrcOhQ2mzrFhIvmkTlbXwDYkweCGmuez60Ya8mamECsG17IULpXUZiE3VXjmP5VSQXw9P32JULeNc/kY5ZPwR8vwDMsY/EA8@9OE7/0zqJl3/BQ "Java (OpenJDK 8) – Try It Online")
So much playing with indices...
[Answer]
Abalone is a type of fish (well, a shellfish), therefore…
# [><>](https://esolangs.org/wiki/Fish), 79 bytes
```
&i1\
0(?\:1+:&::&@)?$~i:@
&~}\&~1
0(?\:&::1+&@)?$~}}:
~r\
?!v>l?!;:o$1-:@
~~<^
```
[Try it online](https://tio.run/##S8sszvj/Xy3TMIbLQMM@xspQ20rNykrNQdNepS7TyoFLra42Rq3OECIJlDHUhsjV1lpxKdQVxXDZK5bZ5dgrWlvlqxjqAjXU1dnE/f@fmJSYk5@X@l@3TMEYAA "><> – Try It Online"), or watch it at the [fish playground](https://fishlanguage.com/playground)!
Reads the string from STDIN, and assumes the number is already on the stack.
Explanation: The second, fourth and sixth lines are the main loops. The details are some ugly stack manipulation, but in broad strokes, first, the second line fills the stack alternating between a character of input and **min**(*i*, *n*), where *n* is the length cap and *i* is the index of the character in the input: for "abalone", 3, the stack looks like
```
"a", 1, "b", 2, "a", 3, "l", 3, "o", 3, "n", 3, "e", 3, -1=EOF, 3
```
Next, line 4 goes through the stack in the same way in reverse, to get the right hand end capped properly:
```
"a", 1, "b", 2, "a", 3, "l", 3, "o", 3, "n", 2, "e", 1, -1
```
Then the sixth line takes each character–number pair and prints the character as many times as the number.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 59 bytes
Port of [xnor’s Python 2 answer](https://codegolf.stackexchange.com/a/129707/11261).
```
F=->s,n,i=1{s[0]?s[0]*s[...i][...n].size+F[s[1..],n,i+1]:s}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWN63dbHXtinXydDJtDauLow1i7UGEVnG0np5eZiyIzIvVK86sStV2iy6ONtTTiwWp1TaMtSquhRixuaC0pFjBLVopMSkxJz8vVUnHOBYiA7MEAA)
] |
[Question]
[
Given two strings \$ A \$ and \$ B \$ and a positive integer \$ n \$, determine whether \$ B \$ is composed entirely of (possibly overlapping) strict substrings of \$ A \$ of a length of at least \$ n \$.
## Test cases
```
n A B Output
-----------------------------------------
2 abcdefg bcabcdebcdef True
2 abcdefg cdabfg True
4 abracadabra abrabrabrabra True
1 abcdefg ddbfeg True
2 ab abab True
2 bb bbbbb True
5 abcdefghijklmn defghabcdefghi True
2 abcdefg hijklmn False
3 abcdefg bcabcdebcdef False
2 abcdefg ddabfg False
2 ab aba False
2 abcdefg a False
4 abracadabra brabrabrabra False
6 abcdefghijklmn defghabcdefghi False
```
## Rules
* You may assume that both \$ A \$ and \$ B \$ are non-empty; \$ n \ge 1 \$; and \$ A \$ has a length of at least \$ n \$
* You may choose to operate on arrays with elements of any data type or set of values, rather than strings, as long as there are at least 8 distinct values for that element type
* You can output using truthy or falsey values, or any two other disjoint sets of values, to indicate a true or false result
* You may use [any sensible I/O format](https://codegolf.meta.stackexchange.com/q/2447)
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
[Answer]
# Excel, 114 bytes
A nice low bar to start with.
```
=LET(x,SEQUENCE(LEN(C1)),t,TRANSPOSE(x),AND(MMULT((x<t+A1)*(x>=t),IFERROR(FIND(MID(C1&REPT(" ",A1),x,A1),B1),0))))
```
[Answer]
# [R](https://www.r-project.org/), ~~117~~ 109 bytes
*Edit: -8 bytes thanks to some nice golfing by Robin Ryder*
```
function(n,a,b,p=nchar(b),s=n:p-n+1,S=sapply)p>=n&all(1:p%in%S(s[S(substring(b,s,s+n-1),grepl,a)],`+`,1:n-1))
```
[Try it online!](https://tio.run/##ndLJboMwEAbge58CUaWyxeRAuhyQ6LEvkN6qiozNElrXsexw6NNTFhPRsCRkBAJ@pE9jzeiSRShEZApmjjqXmYkOaYRhmRaSH/ODJBIQGKhQ8j1qwiiYUAZqLT0ftqFBpcQvVa@hfKgY4gdqlcvVlpiP6u5MwsCA8eTap5DpRAlA@gk7bwd@UId0vAnibMBxXGQ8TtLMrd5tuYw3YfPDpc59Hb7rIrlb6PAYWZVYoa0556l1NHKM64e1muh0WW7O8Sf6iWOWJgv6sefqEV0/VfhPucJhQ4fVdQbNOc@9c@3zr2/xI2vTbb5PeQveMq/O7Hf0hsJMQo8LFmgW2kxObLhB10BjIzuf2G0dDZkL0NRSj@z0PPSyYPotVP4B "R – Try It Online")
**Ungolfed**
```
b_all_substrings_of_a=
function(n,a,b){
r=substring(b,s<-seq(nchar(b)-n+1),s+n-1) # r=all length-n substrings of b
m=sapply(r,grepl,a) # m=check whether each of r is found in a
i=sapply(s[m],`+`,1:n-1) # i=for each r that was in a, make a sequence length n starting at r
# (so i is the indices of the letters in b in each match)
nchar(b)>=n # finally, check that b is at least n characters long
&all(1:nchar(b)%in%i) # and that all the letters in b belong to a match to a
}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
`-ŀ¹×+ŀ⁵W€²X
```
[Try it online!](https://tio.run/##yygtzv7/P0H3aMOhnYenax9teNS4NfxR05pDmyL@//9v8j8xqSgxOTEFRP0HYjgCAA "Husk – Try It Online")
(or try [some](https://tio.run/##yygtzv7/P0H3aMOhnYenax9teNS4NfxR05pDmyL@//9v9D8xKTklNS39f1IymAXmAQA) [true](https://tio.run/##AS4A0f9odXNr//9gLcWAwrnDlyvFgOKBtVfigqzCslj///8y/2FiY2RlZmf/Y2RhYmZn) [examples](https://tio.run/##yygtzv7/P0H3aMOhnYenax9teNS4NfxR05pDmyL@//9v8j8xqSgxOTEFRIHZcAQA)
or [some](https://tio.run/##AS8A0P9odXNr//9gLcWAwrnDlyvFgOKBtVfigqzCslj///8y/2FiY2RlZmf/aGlqa2xtbg) [more](https://tio.run/##yygtzv7/P0H3aMOhnYenax9teNS4NfxR05pDmyL@//9v/D8xKTklNS39f1IymAXmAQA) [false](https://tio.run/##yygtzv7/P0H3aMOhnYenax9teNS4NfxR05pDmyL@//9v9D8xCYgSAQ) [examples](https://tio.run/##ASkA1v9odXNr//9gLcWAwrnDlyvFgOKBtVfigqzCslj///8y/2FiY2RlZmf/YQ))
Returns a list of the letters of `b` that aren't part of a length-`n` substring of `a` (so, empty list corresponds to 'b is composed of substrings of a', non-empty list indicates that this isn't the case).
This is loosely a port of [my R answer](https://codegolf.stackexchange.com/a/221427/95126).
**How?**
```
`-ŀ¹×+ŀ⁵W€²X # full program with:
# arg1 (⁵) = n
# arg2 (²) = a
# arg3 (¹) = b
X # get all substrings of length n from string b;
W # now get indices of
€² # the ones that are in a;
×+ŀ⁵ # add 0..n-1 to each of them,
`-ŀ¹ # and output any of 1..length(b) that aren't among these
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-!`](https://codegolf.meta.stackexchange.com/a/14339/), ~~13~~ 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Vã l¨W Ô£=eX0ÃU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=VuMgbKhXINSjPWVYMMNV&input=ImJjYWJjZGViY2RlZiIKImFiY2RlZmciCjIK)
* 1st input U : string B
* 2nd input V : string A
* 3rd input W : minimum length
```
* fixed a bug
Vã - all substrings
l¨W - filter out shorter than W
Ô * reverse to remove longer first
£= ... Ã - map by reassigning U
eX : remove all occurrences
0 * and put a '0'
U + flag ! to print true if U is empty
```
* [Truthy case](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=VuMgbKhXINSjPWVYMMNV&input=ImJjYWJjZGViY2RlZiIKImFiY2RlZmciCjIK)
* [Another test](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=VuMgbKhXINSjPWVYMMNV&input=ImhpamtsbW4iCiJhYmNkZWZnIgoyICAgICAgICAg)
[Answer]
# JavaScript (ES6), 102 bytes
Returns a Boolean value.
```
(n,a,b)=>[...b].every((_,i,A)=>A.some((_,j)=>!A.every((_,k)=>i<j|i>k|++k-j<n|!a.match(b.slice(j,k)))))
```
[Try it online!](https://tio.run/##lZLLboMwEEX3/QrHG4ziOGr62DSJxKZf0B2NKr9IbMBUkEaqxL9T7JYEWqBhZMm61z4zI81oeqIFz9X7cWEyIatoUyGDKWb@ZhsSQtiOyJPMPxF6wwoHtRuQIkul1bpWs@DyHtdarXWptnE5n8cLvTbljJKUHvkBMVIkikuk6282Kp6ZIkskSbI98sKX/EPuPP/ppm1HaIUBpIwLGe0hBk1Axp3pHiAAvg@WS2BTXIdzQVntNHoQv3d4TjkV9vpJ4azzgcP4bX91IVgkr6j@3XyLbKrX5kWP4uwvzmzA//GHS/MHpeMkNTYVdPrswxbe4b1XEz7TpJgw06ZKpzGX4xd/N2En@vjV0Fh6lmKY75tLayzT63foMX5gK7tLOcI/Tpis46sv "JavaScript (Node.js) – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 32 bytes
```
{i~?,/(x':i:!#z)@&~^(x':y)?x':z}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6rOrLPX0deoULfKtFJUrtJ0UKuLA/EqNe2BZFUtF1eagp6ChpG1UmJSckpqWrqStVJSMpgN5itpYlGQnJKYBGRApUxAUkWJyYkpIEoJwoMjmCpDZANSUpLSUtNRzAbrA1IIsSSQWBIIwARN4WZkZGZl5+TmgYwC8eCiWJ0LUwyVMybJrykofkVyKjbVOkqJOEMFW6CYEeEhABJkglM=)
Makes heavy use of `int':list` to build sliding windows of the input strings. `x` is N (the minimum length of the substrings), `y` is A (the source of the substrings), and `z` is B (the string to check).
* `(x':y)?x':z` find the beginning indices of where each N-length substring from A occurs in B (e.g., `"abra"` occurs in `"abrabrabrabra"`, with each match beginning at indices 0, 3, 6, and 9. No other index in B is the beginning of a 4-length substring from `"abracadabra"`)
* `@&~^` apply using indices corresponding to matches (e.g., `0 3 6 9`)
* `(x':i:!#z)` build sliding windows of the range from 0..len(B), storing this range in variable `i`; when indexed into, this returns the indices in B that are part of some valid substring from A (e.g., `(0 1 2 3;3 4 5 6;6 7 8 9;9 10 11 12)`)
* `?,/` flatten the distinct indices, as there can be overlaps (e.g., `0 1 2 3 4 5 6 7 8 9 10 11 12`)
* `i~` are all characters in B accounted for? (i.e., are they part of a N-length substring from A?)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
Nθ⬤ζ⊙E⌊⟦θ⊕κ⟧✂ζ⁻κλ⁺⁻κλθ¹∧⁼Lλθ№ηλ
```
[Try it online!](https://tio.run/##VY1BC8IwDIXv/ooeU6gHwdtOQzwMnAw8ioeuK64szdauFfTP11ZQMLyQx8tHokbp1SwxpYaWGM7R9tqD49Wm84YC1IjwEqymJ7RygdaQsdHC1QnWkPLaagp6gInfBLugUbrQmYorTIIhF6zD7P8Sl3vHebk6wNFFiSucNN3DCN/1YY75@Vj4UlVK@43svVRyKOPjf0rbB74B "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for true, empty for false. Explanation:
```
Nθ Input `n` as a number
ζ Input `B`
⬤ All characters must match
θ Input `n`
κ Current index
⊕ Incremented
⌊⟦ ⟧ Minimum
E Map over implicit range
ζ Input `B`
✂ ¹ Sliced from
κ Outer index
⁻ Minus
λ Inner value
⁻κλ To outer index minus inner value
⁺ Plus
θ Input `n`
⊙ Any string satisfies
λ Current string
L Length
⁼ Equals
θ Input `n`
∧ Logical And
λ Current string
№ Contained in
η Input `A`
Implicitly print
```
Alternative solution, also 31 bytes:
```
Nθ⬤ζ⊙…·⌈⟦⁰⁻κ⊖θ⟧⌊⟦κ⁻Lζθ⟧№η✂ζλ⁺λθ
```
[Try it online!](https://tio.run/##PY2xCoMwEIZ3nyLjCSl06OYk7SLUIu1YOsR4aPASazTS@vJpTGmPg/vh/7hPdsLKQZD3hXm6@eJ0jRbGNEsqq8wMORGsnOXmDYWR5Ca14FWYFqEUL6Wdhvues1IZN0HP2QmlRY1mxiY8SR9p7L5c/@POaNq5gzWUY0SOgwuqjrMbKYmbjzirggxoQ@Jk3h8SUVshRbOdmP/rdwt9AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ Input `n` as a number
ζ Input `B`
⬤ All characters must match
⁰ Literal zero
κ Current index
⁻ Minus
θ Input `n`
⊖ Decremented
⌈⟦ ⟧ Maximum
κ Current index
ζ Input `B`
L Length
⁻ Minus
θ Input `n`
⌊⟦ ⟧ Minimum
…· Inclusive range
⊙ Any value satisfies
ζ Input `B`
✂ Sliced from
λ Current value to
λ Current value
⁺ Plus
θ Input `n`
№ Contained in
η Input `A`
Implicitly print
```
Alternative solution, also 31 bytes:
```
NθF⁻Lη⊖θF⌕Aζ✂ηι⁺ιθFθ⊞υ⁺κλ¬⁻Eζκυ
```
[Try it online!](https://tio.run/##PY3BCoMwDIbvPkWOKXS33TwNxmAwpbAnqDVbi7FqbXfYy3dVZBD4A/n@fMbqYCbNOd/9nGKbxo4CLqKuXlMAbJxPKz7Iv6NFKyRcyQQayUfqCyUE7NjN@f7CjF8JT3aG0EpwEhSXcskNPMhFgEqrxXRcBwlcZCo4H7Gd4mFs9Lw9G4oxlW6d87nSXdBG91vs@3/y6cM/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @DominicvanEssen's answer.
```
Nθ
```
Input `n`.
```
F⁻Lη⊖θ
```
Loop over the starting index of all substrings of length `n` in input `A`.
```
F⌕Aζ✂ηι⁺ιθ
```
Loop over all matches of each substring in input `B`.
```
Fθ⊞υ⁺κλ
```
Record the index of each character in each match.
```
¬⁻Eζκυ
```
Check that each index in input `B` was recorded at least once.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 35 bytes
```
~L$`.+$
v`(.{$&})(?=.$*$¶.$*\1)¶
^¶
```
[Try it online!](https://tio.run/##K0otycxLNPyvqhGcoPO/zkclQU9bhassQUOvWkWtVlPD3lZPRUvl0DYgGWOoeWgbV9yhbf//JyUnJiWnpIJwmg6YmZauY8SVnJKYBGQgBBKTihBIB0QkJ6aA2SZcKSlJaakIxYZAxYlJQC5QWxII6CSBmCC5DKiajEwdOCsrOyc3T8eUC8ZC2InVbcZA6zDclgixLRFZMx734nWJGQA "Retina – Try It Online") Takes newline-separated arguments in the order `B`, `A`, `n` but test suite splits on `,`s for convenience. Explanation:
```
L$`.+$
v`(.{$&})(?=.$*$¶.$*\1)¶
```
Create a stage that matches overlapping substrings of length `n` from `B` that also appear in `A` and deletes any matching characters.
```
~`
```
Evaluate that stage on the original input.
```
^¶
```
Check that all the characters from `B` were deleted.
Example: If `n` is `4`, then the generated stage is as follows:
```
v`(.{4})(?=.*¶.*\1)
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~72~~ 67 bytes
```
.+$
$*
^((?=((.)+)(.*¶.*\2.*¶(?<-3>1)+)$)(?=(?<-3>.)*).+(?=.*\4))+¶
```
[Try it online!](https://tio.run/##fY5bDoIwEEX/uw5M@rIJoH6pLMJfY5xpQfDBB3FtLICN1Sk@aqKh6ePM9E7u7cp704Kf8d1Re6MSlkh24LzYcG6EEtzIoTdyn4WXF@t5vk2pnYigGEsjpDCKSlIthFBD7z1aQOvKcCo9YnXSGbMOkCA2ALu4dbgsuJEXzDmsyihOSQxIJY1hWBoDhr/6pakb/aHz5Xpr9ZK9KXr@zZaT3U82eLrB9/BE3skkqwc "Retina 0.8.2 – Try It Online") Takes newline-separated arguments in the order `B`, `A`, `n` but test suite splits on `,`s for convenience. Explanation:
```
.+$
$*
```
Convert `n` to unary.
```
^(...)+¶
```
Ensure `B` matches...
```
(?=((.)+)
```
... a number of substrings...
```
(.*¶.*\2.*¶
```
... that appear in `A`, and...
```
(?<-3>1)+)$)
```
... are at least `n` in length...
```
(?=(?<-3>.)*)
```
... but might be more than `n`, so reset it to zero for the next loop...
```
.+(?=.*\4)
```
... and allow the substrings to overlap.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 77 bytes
```
(n,A,B)=>[...B].every((c,i)=>B[i+n-1]&&~A.indexOf(B.substr(i,n))?k=n:--k,k=1)
```
[Try it online!](https://tio.run/##lZJPT4MwGMbvfoqmh9HG0oWpO2jQjINXL96QQ/8xO7AY2Ba9@NURqmygwEbTpHmf5vc@b/K8G7Znhcj1@9Y1mVRl7JfIkBUJsH8fUkqDiKq9yj8REkRXWhDqS@N60Wz2taLaSPXxFKOAFjtebHOkicH4IfHNresmJPE9XIrMFFmqaJqtkRM@5zsVOfjuoi3HaEEAZFxIFa8hAc2BXFjRfkAAMAbzOahbnIcLyXilNPUgfm3xnAkm6@e3hZUOFw7jXr@7lDxWZ7j/DN8iG/dKPNajOP@P8/rA0/jNcfhXvUnSN1O3grY@6LCFd3jnxYSPLC0mZNq4dAazPf7wVxN2oo9fDMXSsxTDfF8urVim@3foMX5gK7tLOcIvJyRr@fIb "JavaScript (Node.js) – Try It Online")
Input n and two strings. Strings may only contains BMP characters, in UTF-16. (Most characters will fall into this part. Some emoji's and rare used Han characters may not be suitable here.) Output true vs. false.
---
# [JavaScript (Node.js)](https://nodejs.org), 68 bytes
```
(n,A,B)=>[...B].every((c,i)=>A.match((B+8).substr(i,n))?k=n:--k,k=1)
```
[Try it online!](https://tio.run/##lZLLboMwEEX3/QrLG2zVOEr6UJWIVmHRL@iOZuEXCYGYypBI/XoKbkmgxTRYlqy51pk70p09O7FCmOSj9HUuVRUHFdJkTUIcPEeU0nBD1UmZT4QESWptTQ@sFDuEwtsnTIsjL0qDEqIxfkkDvfT9lKTBHFci10WeKZrlW@RFb@aoNh5e3XTlGC0IgIwLqeItJKA9kAsr2g8IAMZgNgNNi@twIRmvlbZ24vcWN0ww2Tw/Lax0vtCNz4fdpeSxusL9e/gO2brX4qUexflfnDcH/o8/XIbfJfs0O@imFbT1WYcdvMd77zp6ZVkxIdPWpTeY7fGLv5uwE0P8whXLwFK4@aFcOrFM9@/RY7xjK/tLOcI/TkjW8tUX "JavaScript (Node.js) – Try It Online")
If we restrict the values of A, B to a small subset of characters. We can reduce more bytes here. Above 71 bytes code supports A, B with only "a"~"z" letters (as all testcases provided here).
[Answer]
# C, 200 bytes
```
main(int c,char*v[]){char*s,*t=v[3];int a=1,K=0,x,y,m=atoi(v[1]);X=strlen(v[2])-m+1,y=strlen(t)-m+1;while(a--){s=v[2];K=0;for(x=0;x<X;++x){if(!strncmp(s++,t,m)){a=m;K=1;}}++t;if(!--y)break;}exit(K);}
```
GNU compiler cries all the warnings but code is OK on most architectures.
[Answer]
# [J](http://jsoftware.com/), 28 bytes
```
1 :'#\@]-.+/@E.&m\;@#(<\#\)'
```
[Try it online!](https://tio.run/##pVHLjoJAELzzFRVJbMkKq/s6oCYkm/XkyXjEw7xYfCeCh/16ZBBRJ0JItjOT6emuru5Ur7OORxEmPgh9DODn1/XwPZ9NsyF8ssNg6Xovr8GP192Fo8DujUM7dChzLEuJ@ABaHE9p/IdUJSkES1RCZYLg@nhDjxgXUkW/hMgBcVF8ixAht0a0kIxrv7J79EeBPjLBpH4uFdqrDhkVQ5NfSh6pOv7LNFda7aEeyEsg10Y1wM9b/3i13mx3@3IMHagSefVV3CnbJu21rTif9X7/3yZk0yYMpR6EaqY1sC0WbO73oeKrrcCwsjM "J – Try It Online")
This is an adnoun modifying A, and taking n and B as left and right arguments. Example usage:
```
2 ('abcdefg' f) 'bcabcdebcdef'
```
Returns an empty list when true, a non-empty list when false.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 72 bytes
```
k;f(n,a,b)char*a,*b;{for(k=1;k=memmem(a,strlen(a),b,n)?n:k-1;b++);k=*b;}
```
[Try it online!](https://tio.run/##rZLPasMwDMbvfYogGNitc8j@HRbKbnuC3bYdZDtOMydecVJ2KH31eY7TNitLuwQmBEYf/llCn0WcC@GcThUxDBmnYoV2jmzO0636sEQvk1Qvq6zySZDVjS0zQ5Ayzgx9NA86TlK@WFB/ySM7V2FhCN3O1pumJvDybDfZG9B0traFaRSBK/lqgEWKXLMIkAuZqdzX@wAughZ0iCI6nhQSuRcO9SB5G0iLAmV7dHRQjgnDZDLYU0qusj96dtP2ULTv6bW@PkvyXyRvAy6Td/20q@Jdl1UrQyiPMgSyc@kJy3qSTYdXLw1x888GyxEGn132j11P6XnCTfpUp39qmLwfa9POfQlVYl67@PMb "C (gcc) – Try It Online")
Return zero if `b` meets requirements. Return non-zero values otherwise.
Check if `n` bytes starting from `b` (possibly including the NULL-terminated byte and garbage after it) is available in string `a` (without the NULL byte). If we failed to find out such a matching `n` times continuesly or at the beginning, we know `b` does not meet the requirement. We break the loop if this happened, and `*b` here will be non-zero. As there should not be NULL bytes in `a`, as long as we reached the NULL byte in `b`, the `n` times mismatch will be eventfully happened. But this time, `*b` would be zero.
According to the implementation of glibc, this function would be memory safe when `n < 32` (as long as `CHAR_BIT == 8`). And once `n >= 32 && CHAR_BIT < 10`, it *may* failed by invalid memory access which access the memory after the NULL terminator of `b`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/Code-page)
```
ẇ⁹Ƥ⁵o¬{Ṛḣ¥Ƥ§Ạ
```
A full program accepting `B n A` that prints `1` if `B` is composable from substrings of length `n` (or more) of `A`, or `0` if not.
**[Try it online!](https://tio.run/##y0rNyan8///hrvZHjTuPLXnUuDX/0JrqhztnPdyx@NDSY0sOLX@4a8H///9TUtPSMxKTksF05n/T/3B2VnZObh4A "Jelly – Try It Online")**
Or see a [test-suite](https://tio.run/##y0rNyan8///hrvZHjTuPLTm0Lv/QmuqHO2c93LH40FIgf/nDXQv@P9yx6NDKE8sPL9fX/P8/Olo9MSk5JTUtXV1HQT0pGcwBCwD5RrFcOijyySmJSWAWTKYoMTkxBUSBZEE0HAEFTNC1p6QkpaWCWIZQGYguMA0xMQkslAQC6PZnZGZl5@Tmgc0BceHCQBFTdJsQijH8gOZHY0xHovkR6khsZiXiCgp8IYHPI2axXLEA "Jelly – Try It Online") (Altered to a functional form & using the register, `®`, populated with `A` in the footer.)
### How?
```
ẇ⁹Ƥ⁵o¬{Ṛḣ¥Ƥ§Ạ - Main Link: B, n
⁹Ƥ - for infixes (of B) of length n:
ẇ ⁵ - is a sublist of A?
o - logical OR (vectorised) with:
¬{ - logical NOT B (a vector of zeros the same length as B)
(o¬{ has the effect of adding n-1 zeros)
Ƥ - for prefixes:
¥ - last two links as a dyad - f(prefix, n):
Ṛ - reverse (the prefix)
ḣ - head to length (n) (a no-op if less than length n)
§ - sums
Ạ - all non-zero?
```
[Answer]
# [Python 2](https://docs.python.org/2/), 94 bytes
```
n,a,b=input()
t=[0]*len(b)
for i in range(len(b)-n+1):
if b[i:i+n]in a:t[i:i+n]=n*[1]
print t
```
The program prints a list containing `1`'s and/or `0`'s. A list containing all `1`'s is truthy and a list containing any `0`'s is falsey.
[Try it online!](https://tio.run/##PYpBCsIwEEX3OcWAiyRtBCuuArlFdyGLiaY6INMQpgtPH5WK8ODzPq@@5LHyuXd26HIgrpsYqyTEUxqehU22alkbEBBDQ74Xs79HHifrFdACOZKnkdOnQC8/CTzEKanaiAWkd3NxGnPDK96@o3f7o@1hblt5Aw "Python 2 – Try It Online")
] |
[Question]
[
[*sandbox*](https://codegolf.meta.stackexchange.com/a/18737/9481)
**Story**
Similar to a newspaper route you have been tasked with delivering bits to the residents of Bin City. Just as certain people like certain newspapers, the citizens of Bin City prefer either \$1\$s or \$0\$s delivered to their doorstep. Unfortunately, your new boss has arranged the deliveries in an awkward manner.
The residential streets of Bin City all have multiples of \$8\$ houses. So naturally, your delivery routes are organised as a series of one or more bytes. Your boss has laid out the deliveries as follows: first off, start at the house at the beginning the street on the left-side, followed by the house opposite on the right-side of the street, then the next house after the first one on the left-side of the street, then the one opposite it on the right-side, etc. The \$1\$s and \$0\$s to be delivered along this route are stored, in order, in the
bits of the bytes.
**Task**
You've quite rightly deduced it would be far easier and more time effective to deliver the bits starting from the first house on the left-side of the street and continue on delivering bits up the left-side to the end. Then cross the street to the house opposite on the right-side and continue on down the right-side back to what would have originally been your second delivery at the end.
**Illustration for eight houses (one byte)**
The original input route is on the far left next to the byte containing the bits to be delivered along that route. Beside it, to the right, is the output byte with the bits rearranged for the new improved delivery route on the far right.
[](https://i.stack.imgur.com/EBqbl.png)
**Input and output**
The input will be between \$1\$ and \$8\$ bytes long, organised by your boss in a back-and-forth left-side to right-side manner as above. This can be in any convenient byte-wise way (*eg* **not** a list of bits, but a list of bytes, words, or double-words etc is ok). A 64-bit integer along with the bit-length is ok too. A bit-length will be needed for any structure using elements larger than a byte. The order can be in any convenient bit-wise way (*i.e.* least-significant to most-significant bit or vice versa) and any convenient byte-wise way (*eg* first element in a byte list to last or vice versa, least--significant to most-significant byte or vice versa in a list or words or double-words etc traversed first to last or vice versa) so long as the output follows the same convention. The output must use the same structure and ordering convention as the input but with the bits rearranged to be up the left-side then back down the right-side in the manner described above.
Please state your bit-wise and byte-wise ordering as well as your i/o structure.
**Scoring and winning criterion**
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Shortest code in bytes wins.
**Test cases**
As lists of bytes ordered least-significant bit to most-significant bit and first byte to last byte in the list.
```
[85] -> [15]
[85, 85] -> [255, 0]
[85, 85, 85] -> [255, 15, 0]
[85, 85, 85, 85] -> [255, 255, 0, 0]
[85, 85, 85, 85, 85] -> [255, 255, 15, 0, 0]
[85, 85, 85, 85, 85, 85] -> [255, 255, 255, 0, 0, 0]
[85, 85, 85, 85, 85, 85, 85] -> [255, 255, 255, 15, 0, 0, 0]
[85, 85, 85, 85, 85, 85, 85, 85] -> [255, 255, 255, 255, 0, 0, 0, 0]
[170] -> [240]
[170, 170] -> [0, 255]
[170, 170, 170] -> [0, 240, 255]
[170, 170, 170, 170] -> [0, 0, 255, 255]
[170, 170, 170, 170, 170] -> [0, 0, 240, 255, 255]
[170, 170, 170, 170, 170, 170] -> [0, 0, 0, 255, 255, 255]
[170, 170, 170, 170, 170, 170, 170] -> [0, 0, 0, 240, 255, 255, 255]
[170, 170, 170, 170, 170, 170, 170, 170] -> [0, 0, 0, 0, 255, 255, 255, 255]
[208] -> [28]
[96] -> [40]
[155, 36] -> [37, 210]
[232, 33] -> [24, 114]
[174, 18, 247] -> [66, 191, 248]
[130, 143, 125] -> [48, 111, 157]
[76, 181, 117, 107] -> [122, 159, 46, 67]
[158, 238, 106, 124] -> [166, 232, 230, 223]
[233, 87, 232, 152, 182] -> [249, 72, 182, 117, 120]
[142, 61, 195, 199, 218] -> [114, 185, 220, 153, 214]
[107, 131, 170, 25, 103, 171] -> [25, 80, 27, 175, 244, 233]
[71, 41, 113, 118, 202, 26] -> [27, 237, 72, 220, 42, 134]
[30, 226, 236, 110, 111, 211, 202] -> [134, 170, 219, 216, 233, 126, 203]
[162, 53, 89, 29, 128, 172, 134] -> [112, 125, 32, 146, 23, 68, 178]
[112, 71, 252, 192, 100, 176, 108, 71] -> [188, 142, 74, 186, 104, 35, 113, 40]
[111, 58, 224, 222, 231, 246, 214, 200] -> [75, 232, 235, 142, 149, 187, 61, 238]
```
**Same test cases in hex**
These may look odd, but remember they are byte-wise from beginning to end, and bit-wise from least-significant to most-significant bit (*i.e.* in opposite directions).
```
55 -> 0F
55 55 -> FF 00
55 55 55 -> FF 0F 00
55 55 55 55 -> FF FF 00 00
55 55 55 55 55 -> FF FF 0F 00 00
55 55 55 55 55 55 -> FF FF FF 00 00 00
55 55 55 55 55 55 55 -> FF FF FF 0F 00 00 00
55 55 55 55 55 55 55 55 -> FF FF FF FF 00 00 00 00
AA -> F0
AA AA -> 00 FF
AA AA AA -> 00 F0 FF
AA AA AA AA -> 00 00 FF FF
AA AA AA AA AA -> 00 00 F0 FF FF
AA AA AA AA AA AA -> 00 00 00 FF FF FF
AA AA AA AA AA AA AA -> 00 00 00 F0 FF FF FF
AA AA AA AA AA AA AA AA -> 00 00 00 00 FF FF FF FF
D0 -> 1C
60 -> 28
9B 24 -> 25 D2
E8 21 -> 18 72
AE 12 F7 -> 42 BF F8
82 8F 7D -> 30 6F 9D
4C B5 75 6B -> 7A 9F 2E 43
9E EE 6A 7C -> A6 E8 E6 DF
E9 57 E8 98 B6 -> F9 48 B6 75 78
8E 3D C3 C7 DA -> 72 B9 DC 99 D6
6B 83 AA 19 67 AB -> 19 50 1B AF F4 E9
47 29 71 76 CA 1A -> 1B ED 48 DC 2A 86
1E E2 EC 6E 6F D3 CA -> 86 AA DB D8 E9 7E CB
A2 35 59 1D 80 AC 86 -> 70 7D 20 92 17 44 B2
70 47 FC C0 64 B0 6C 47 -> BC 8E 4A BA 68 23 71 28
6F 3A E0 DE E7 F6 D6 C8 -> 4B E8 EB 8E 95 BB 3D EE
```
[Reference implementation in Python](https://tio.run/##lZPtboIwFIb/cxVn/ljaWBeYGs0m3IghRmOrTUglULIs6rWztiAUK8qakPR8vad9ekh/5fEkpmW5pwwYSvCXB2qdCpkWEkJYx8ZOKJObnO/pRvDdLqF5G2KnDDhwAdlWHChKqFAqtYxegv7URarGb9wZPxyV5JEz2fFruaqbCTW6PlmST0v2TvoSAkIBrFZWMYZ3SNY8xhBFdr/vjoh9kHEIQRN07vyxTVMq9qhtiz1LYTgdmEBAYGK@AaRoXiRyY0F5zgstCMwJTAkEd7w4MzwUFhfVmxLtZruETZFznC5N57Adpi6qPqgtSXf2xg90HtH2CWjgdQYmYA9QNeJN@ypH07lAa6lWQaxvPcP1W1NZZKIu9jxJc6nPiExwvZzH5LYjcG899vR7n0deR4dl2FnBwre2aoBcu9/5IjIkPDjnf4m3bOx5ekLMX2JerpqGNONCIjY6yytMIjgzJPF1hMvyDw).
[Answer]
# x86-64 machine code function, 22 bytes
Callable with the Windows x64 calling convention: bit length in ECX, bit-pattern in RDX (first = least significant bit aka right-most). Returns in the low ECX bits of RAX.
NASM listing with machine code and the source it was assembled from:
```
5 bit_even_reverseodd:
6 00000000 D1E9 shr ecx, 1
7 00000002 51 push rcx ; save n/2 for later
8 .loop: ; do {
9 00000003 48D1EA shr rdx, 1 ; shift low bit into CF (carry flag)
10 00000006 49D1D8 rcr r8, 1 ; rotate even bits into the top of R8
11 00000009 48D1EA shr rdx, 1
12 0000000C 11C0 adc eax, eax ; odd bits into the bottom of RAX (reversing). Same as rcl but faster
13 0000000E E2F3 loop .loop ; }while(--rcx);
14
15 ; return in EDX:EAX? Nope, that has a gap for bit lengths less than 64, as well as hard to justify
16 00000010 59 pop rcx
17 00000011 4C0FA5C0 shld rax, r8, cl ; shift even bits into the bottom
18 00000015 C3 ret
```
**Explanation:**
Loop N/2 iterations, separating the odd and even bits into different registers, 2 input bits per iteration. (Into the carry flag then rotate-through carry back out).
Shifting into the top and bottom of 64-bit registers sets us up for a [`shld` double precision shift](https://www.felixcloutier.com/x86/shld) that shifts in bits from another register instead of zeros.
The return value is the low ECX bits of RAX. It gets there by being shifted one bit at a time for the first half, then the 2nd half all at once. Bits *above* that bit position may be non-zero, depending on the initial value of RAX. These bits are *not* part of the return value.
If you think this is too much of a stretch of the rules, it costs 2 bytes for an `xor eax, eax` before the loop. Or a [BMI2 `bzhi`](https://www.felixcloutier.com/x86/bzhi) on the return value, using the BIT\_LEN in a register. But presumably the caller in this question's example use-case wants to loop over the resulting bits, and they're in the right order for that. Real x86 calling conventions allow high garbage in return-value registers, the only differences here are that the width isn't a power of 2, and is runtime variable.
**[Try it online!](https://tio.run/##hVbbbttGEH0uv2IQoICUkJaouyW0Rey4jYEkD3GKGnANYUkuRdYUyewuLTk/757ZpSxZcVMDlsTlXM/MnFmhtVxHxUNQCr1@fCT8LeivvEyqjabtZESxKIq8XFFclfeyNHlVek4oyg0VslyZjPKSPp9f@3wU1MIYqUp79u6aOoUU2pDOV2We5rEojVUUmlS@ykywrrTpthaVNI0qNauaTFJRbejs8svyw8WnP768ZzVNVUqf316fEHXeQ51WQkViJekXRJLCS5anRiZUwXZeioJlux4UlxKxLxU@lZZVksytR50pIhlvfQrtc93ojFS8pRf@FqTFvaSyN6C0UlQIJOmdFFVVH9hSCdt6SZcDswlx8nlpKjr/nTqxUOqB0kKsHAQqZiOzZzYAS2XgjTgFB4LVZ4RMVVtE3l0ex2CfRRIjP4FnfDyZQ/pHZqLKmGrdYksdBxNq3gXOV2ItbbXigqLGUIpqInM2xcmThcB7VkCu38W76/nF2@vfiD5VtfThRhjKYEegZrWFcN8/Gt9as0xJk5HP7jayKPg7EypBmvRPo02ePrgywS2Xqc25SEhxjowbgjzA@wXEXKoObGketYy5o@lEVYkwwiNRoFEpnFiJTG6XRWPmRElE9KofDoaj8WQ6OxVRnMj0VYvCZlnmUVTI5VrouzmZfC01TLBSf9tPHTZt7y1nZ3N@MfUn/tgf@UN/4Id@34dIOP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jsqCzj5fhiZsPNyo8JegYec@34N0EukN7b0KLNvI4P7E93Dli80wYFzSXM5Y4ms8x85FHS2R2STLH/wegP4RvW6mWu/BxxF6DYfijeVyQ3ALPlaqautPveo//Ag "Assembly (nasm, x64, Linux) – Try It Online")** - includes a test `_start` caller that hexdumps the selected number of bytes before / after calling the function. (Tweaked version of the SSSE3 qword->hex version on <https://stackoverflow.com/questions/53823756/how-to-convert-a-binary-integer-number-to-a-hex-string>)
The test caller only prints the selected number of bits in the return value. If it wanted to avoid leading zeroes, that would take the same effort as avoiding leading garbage.
Example output with input loaded from `db 170, 170, 170, 170, 170, 170, 170, 170`, and bit-length = `8 * 5`
```
aaaaaaaaaa
fffff00000
```
i.e. the 64-bit return value was `0x000000fffff00000`, or would be after clearing high bits outside the low 40. Bits in a register have no endianness. The caller can iterate them in low-to-high order by right shifting.
Since x86 is little-endian, if we stored that to memory the significant `00` bytes would be at the low 2 addresses, and the `0xf0` (240) byte would be the 3rd, followed by two `0xff` bytes.
The test cases in the question use that little-endian byte-order to dump bytes separately, not printing as a single wide integer with high/late/most-significant bits left-most as per standard arabic-numeral ordering for the whole thing as one number.
It's easy to input that ordering with `db 170, 170, ...` (even with decimal chunks like the original form of the test cases), if you don't mind loading from memory, but less convenient to output. I didn't want to write a bigger loop, and hex is obviously the more useful way to look at bit-pattern manipulation like this.
---
The TL:DR of the bit manipulation is to pack and concatenate the even bits with the bit-reversed odd bits. For some multiple of 8 number of total bits.
**If only AArch64 had x86's BMI2 [`pext`](https://www.felixcloutier.com/x86/pext), it could be very compact**. If x86 had ARM/AArch64's `rbit`, that would be fun, but x86 takes a 10-byte `mov reg, imm64` to create an 8-byte alternating-bits constant. (Unlike AArch64 which can do it in one 4-byte instruction with its repeating-bit-pattern immediates for logical instructions).
To do this *efficiently* on x86 you'd use `pshufb` as a nibble LUT to bit-reverse maybe after packing with BMI2 `pext`. Or maybe `palignr` and another `pshufb` with a shuffle control from a bit-length lookup table. (`pext`/`pdep` are very slow on AMD, but single-uop / 3-cycle latency on Intel)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
Port of the Python answers. -1 Thanks to Kevin Cruijssen. -2 Thanks to Grimmy.
```
₁sm+b¦2ι`R«C
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UVNjca520qFlRud2JgQdWu38/78Rl6mpqYUFAA "05AB1E – Try It Online")
## Explanation
```
₁ Push 256.
s Swap to get another input.
m Push 256 ** (input).
+ Add by the other input.
b Convert to base 2.
¦ Remove the first item of ^
2ι Uninterleave.
` Dump onto stack.
R Reverse second copy.
« Merge.
C Convert from base 2.
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 22 [bytes](https://codegolf.meta.stackexchange.com/a/9429/78410)
```
{83⎕DR⍵[⍒-\⍳≢⍵]}11∘⎕DR
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v9rC@FHfVJegR71box/1TtKNedS7@VHnIiA3ttbQ8FHHDLDs/7RHbRMe9fY96mo@tN74UdtEoGhwkDOQDPHwDP6fDpQ1MjWrSQOq1zi03tDIQhvEBdGPuhZpcqUrWJiCCSQawrQ0AxLGZgqGpiCeoZGpgqGJsYKhsQEA "APL (Dyalog Unicode) – Try It Online")
Another case of [alternating sequence trick](https://codegolf.stackexchange.com/a/200637/78410).
I/O format is *signed* 8-bit integers, and the byte order is reversed from the OP's (bit order within each byte is the same).
### How it works
```
{83⎕DR⍵[⍒-\⍳≢⍵]}11∘⎕DR ⍝ Input: a vector of signed bytes
11∘⎕DR ⍝ Reinterpret as boolean vector (8bit/byte)
{ } ⍝ Pass into inline function
⍵[⍒-\⍳≢⍵] ⍝ Use alternating sequence trick to rearrange bits
83⎕DR ⍝ Convert back to a vector of signed bytes
```
[Answer]
# [J](http://jsoftware.com/), 40 34 31 29 bytes
```
_8#.\[:(\:[:-/\#\.)@,(8$2)#:]
```
[Try it online!](https://tio.run/##jVLBjtowEL37K0al6oIEqcd2YifSSlEr9VT10CusKgqhS0XDis22PfTf6RtDskDoqgcr8cybmffe@Pv@VXKzotuCbmhMmgqcSULvP3/8sP8SBslsWgxnxbSYvJ0NZsmoHA/DazMaFHf7EalP7xJabOuf1a6hZkubddNsqklVL9fzWm2q24Qi@s1wkJR/knJQjNRpzSOt64enfil9rVbbXUXNbl4/4u/Huv5Gv9bNPa1i@bxePreofj9Ui6Za0vapOWtGF82qxwZ9lHyF2LSgcbmiTVVOR1Qt7rflpJDbuLxTKqQUC4hT@e@uJk1JHyNnQT6Ln6VizUW2B@CrmB7s2Osq8iqYX8RfLelmoIq9bhHucHuOaEF2sbO46@dO87qd00NcoNzLyHO0PlXwT3yvxv1/3WWtvvRNGR1av4LKs@O/WAeAbe/Wk2GtjDVkbecvMTuMxzfg5o/xLCPOGYGg2IKCs8SmXZsLKGIs2SsPXMAve2LdFrMxSObkMso8OKCxRYkGFvOOGEwQJgbdjbFgZSn4GOIUJ5iOYU7@EIhTDFQ5QxmG5nhoeQ5RrXpIARCeGFBOLTKQBlpsOboIBayhxHP3ACkgDIRHlXOYbxWyTiQBKJ5okGwtNMLQCx8ZARpsnYoKRA30sY7WGDm6lQDQYTwLWUGKm/hqqzgzBKYBmRxB2ORj106RicaLLU4qKRMItoIEiBrxKsfR8k5AAC@hU8cBWJCMy5WcI5tGYfI0QFE2g40YI3uQbWdiGXi1D05ciUtKYyPGLhhbgvnYqNr/BQ "J – Try It Online")
*-3 bytes thanks to Bubbler's suggestion of applying [the alternating sequence trick](https://codegolf.stackexchange.com/a/200637/78410) from APL*
*-2 bytes thanks to FrownyFrog*
Takes input in little-endian format.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 50 bytes
```
lambda n,x:int((t:=f"{x:0{n*8}b}")[::2]+t[::-2],2)
```
[Try it online!](https://tio.run/##nVLbbtpAEH3nK1b0BbdOtDd710jkR6gfTDAqFTHIdisixLfTObPrloKTRn0x7My5zO3w2n/bN8Yf2stm8fWyq15W60o06XG@bfrZrJ8vNtPTcS5PzWd/Xp2nyXI@1@WXnn4edJnq5LJ9OezbXnSv3WSyrjdi9drXnQZ7lcwnQrR1/6NtBALT6eP3/baZBUlPcpBRpdjsW3EkiFglJDmZ4L3bNjVCJPzY9ettA7FPJFetRSXIoxfPVVdTsErFSizES3WY1T@rXcrUx@6w25Llw9M0SQjUpOSwELu6mVVJelVlhezzvm3r554A1@WzIZxg0nSU3cygg8ShBYY6ac6pOB3P4uFJnAhEr@WJwYtB9VxOk8vSZyUwS5WVE3qkYgjojB7yd/Amoe6SN4BAHwONAdV74DHCb/n3SG8S1QfJbwpc2wcR5WRE2vgkmyEmmXEVvsnZccDfKPnHexR4j7Yfotzx5E2n/6CO8u3/iIwpybuxBzEtfZy3p1eRh0eYPVAmRowjhkJYG01hM2yJzJTlqvDXo2YXcnlOgUIhAm1lUJg19NHxGqwHW@GQHCEcCB5PRW5KRh2lNRBFKiwBcselwciALkHSNkLhyQVquGltuGDy9C4mVIaP10P9JOtCZPDV3Lyld45aChx6UaD9OCpqGATMUKOnzCDJQ5AQMCquQYMq0bFTw/1TKcgA56BgLQpDnY5olrsHg0cp0UncgOYOXCiXjVGiMvANzXLvGIeSca6aPzI2S9ihMMX9MIEXgn8SRaicRNGQB6JADlN20Sr2r3mJdAb4Y1mGpsVAXjUAaEfzsAt8JJ8lqpMeySjlQUIj4Xw4T/9MFucQLhFt8Mpxb1rzfvmwcp48io8HzzMNB5BFZYUdKxwA9klXU/4C "Python 3.8 (pre-release) – Try It Online")
Format: visit from MSB to LSB. Input is number of bytes `n` and an integer `x` representing the boss's order.
Simply converts `x` to a binary string `t` of length `8*n`, then perform the following string slicing:
```
t[::2]+t[::-2]
```
which takes all the even indexed bits, then takes all the odd indexed bits in reverse order.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 46 bytes
```
{|t/'0N 8#{(*x),|x@1}|:+:0N 2#,/(|(t:8#2)\)'x}
```
[Try it online!](https://tio.run/##hU@7bsMwDPwVAh4stSoiUi/aXvoF/YLOWTJ0yWAgzrc7RxcIkNZpB0q6I3l3Or19ndb1OF6W86GPH6Tdxb3MPizzO1@X8XUEJ104uMWdR@3Ef/p@vq7H3rmgxU9aSMtE2/Xw@gl28D71lN0aLnCLfiKcVvfHL7BLPCX/bPzb/B5wQaJ6u4dqCUuhVCeSJJSS7WdiJckN74SdnIgFX2oVPBNzI47WLJhKCoCGZFNIpG0T4oJSwVAWqlgaCmogYZ1sG8q8JRLwEQaNYcCUTR/QAkQhQS5EEKlQhQsjDjNU2NpQqkIFphAekAFZGnwTsjCL6YnlGFDRPg@FqGRWpmLxJaPggzSSYcLAMfr1Bg "K (oK) – Try It Online")
A naive solution. I'll try to improve it later.
[Answer]
# [Motorola M68HC11](https://en.wikipedia.org/wiki/Motorola_68HC11) machine code function, 96 bytes
Hexdump:
```
300808E6003A17343436860418306400
18660264001869014A26F3095A270C17
18A800850126E3325D26DC33C5012716
86041866011866024A26F73C543A18A6
02A701383131E60054173A59C4013C18
383A33E701083318E70018094A26F339
```
Takes input as a length-prefixed byte array on the stack and returns as a length-prefixed byte array on the stack.
If you run this on an emulator, you may get "uninitialized memory" warnings at `SUB+0x10` and `SUB+0x15`; these can be ignored.
ASM source:
```
SUB
TSX
INX
INX
LDAB 0,X
ABX
TBA
TRANSFORM_LOOP
DES
DES
PSHA
TRANSFORM_BYTE_PAIR_LOOP
LDAA #4
TSY
TRANSFORM_BYTE_LOOP
LSR 0,X
ROR 2,Y
LSR 0,X
ROL 1,Y
DECA
BNE TRANSFORM_BYTE_LOOP
DEX
DECB
BEQ TRANSFORM_DONE
TBA
EORA 0,Y
BITA #01
BNE TRANSFORM_BYTE_PAIR_LOOP * ODD
PULA * EVEN
TSTB
BNE TRANSFORM_LOOP
TRANSFORM_DONE
* Now, size, array is at 0,X and output(ish) is at 0,Y
PULB
BITB #01
BEQ BYTES_READY
LDAA #4
FIX_MIDDLE_BYTE_LOOP
ROR 1,Y
ROR 2,Y
DECA
BNE FIX_MIDDLE_BYTE_LOOP
PSHX
LSRB * B /= 2
ABX
LDAA 2,Y
STAA 1,X
* Now the middle byte is dealt with for odd-sized arrays
PULX
INS
INS
BYTES_READY
LDAB 0,X
LSRB
TBA
ABX * 1.X is after the middle
PSHX
PULY * 0,Y is before the middle
ROLB
ANDB #01
ABX
MOVE_BYTES_LOOP
PULB
STAB 1,X
INX
PULB
STAB 0,Y
DEY
DECA
BNE MOVE_BYTES_LOOP
RTS
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes
```
≔⪪⭆⮌A◧⍘鲦⁸¦²θIE⪪⁺⮌EθΣ§ι¹EθΣ§ι⁰¦⁸↨²⮌ι
```
[Try it online!](https://tio.run/##bY7BCsIwDIbvPkWPKVRYp@hgp@lpoDDccexQtjoLtW5rN3z72lD05CEJ5Avfn@4h5u4ltPeFtWowUI9aOajdrMxwFSPc5CpnK6E04@KAUkYq0V/k3cFJWBnvQDGSBpLROCeab6oAHJyFdYCaqK30Yn9GXE@M1MsTCleaXr7RwynFkP8wiRBzMB1SRr42hYjm3jfNkTOyD8X5DlsWnkrCZXpoW79d9Qc "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪪⭆⮌A◧⍘鲦⁸¦²θ
```
Take the input array, reverse it, convert each byte to binary padded to 8 bytes, concatenate the result, then split the bits into a list of pairs.
```
IE⪪⁺⮌EθΣ§ι¹EθΣ§ι⁰¦⁸↨²⮌ι
```
Take the second of each pair of bits, reverse the list, append the first of each pair of bits, split back into bytes, reverse each byte, convert each byte back from binary, convert to decimal.
] |
[Question]
[
**This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. The Cops' thread to this challenge is [here](https://codegolf.stackexchange.com/questions/167596/hardcoding-the-cops-and-robbers-cops)**
An interesting question to think about is the following:
>
> If I have a sequence of numbers how many of them do I have to provide before it is clear what sequence I am talking about?
>
>
>
For example if I want to talk about the positive integers in order starting from \$1\$, I could say \$1,2,3, \dots\$, but is that really enough?
I have one way of answering this question, and being a code-golfer It involves code-golf. You have provided enough terms of a sequence if the shortest code that produces those terms produces all the terms of the sequence. If we think about this in terms of code-golf, this would mean you have provided enough test cases such that the shortest code that passes the test-cases does the desired task.
## Challenge
This challenge is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. In which cops will be presenting test-cases and robbers will have to find a shorter way to spoof the test-cases other than the intended sequence. Cops will present the following things:
* A piece of code that takes a positive integer as input and produces an integer as output. This code can be either zero or one indexed but it should be clear what the indexing is. This code will define your sequence.
* Any relevant platform or language requirements that might effect the output, for example the size of longint.
* A number \$n\$, along with the first \$n\$ terms of the sequence as calculated by the code. These will act as "test-cases".
Robbers will be finding a program in the same language that is shorter than the one presented and passes all the test cases (produces the same output for the first \$n\$ inputs as the cop's code). The robber's code must also differ in output from the cop's program for some number larger than \$n\$.
## Scoring
Robbers will be scored in the number of cracks they find with more cracks being better. An answer can be cracked again by finding a valid answer shorter than the original crack. If an answer is cracked a second time the point is given to the second cracker rather than the first.
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents/tree/cquents-0), [Stephen's answer](https://codegolf.stackexchange.com/a/167632/78410), 3 bytes
```
z~$
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/v6pO5f9/QwMA "cQuents 0 – Try It Online")
### How it works
```
z Last item in the sequence
~ Concat
$ Current index
```
Looks like the sequences should be identical, but this gives `12345678910` for `n = 10` while `"::$` gives `1234567891`.
[Answer]
# JavaScript, [fəˈnɛtɪk's answer](https://codegolf.stackexchange.com/a/167608/59487) (17 bytes)
```
x=>"11237"[x]||22
```
Well it was easy to hardcode to obtain a much lower score... Differs from the reference implementation for any entry \$x\ge 6\$, 0-indexed. This uses a very well-known JS golfing trick: indexing into a sequence with an integer that exceeds the bounds of it returns a falsy value (`undefined`), so it can simply be coerced to a default value by using logical OR (`||`), in this case `22`, handling the last term of the sequence but also those to follow.
### Testing
```
let f=x=>"11237"[x]||22
for (x of [1,2,3,4,5,6,7]) {
console.log(x + ' -> ' + f(x))
}
```
Alternatively, [Try it online!](https://tio.run/##BcFLDkAwEADQNaeY2GhjiNZvxUXEQlAh0hFEJsHZ6721v/tzOJb9ii2NkzO147oJlNJZFbTcva/WztABgoEMtCkq1JhhjgWWWHUSHt8byJ60TclGs@AohLiBMDKCpfQ/9wM "JavaScript (Node.js) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), [Laikoni's answer](https://codegolf.stackexchange.com/a/167650/), 15 bytes
```
b n=n*div(n+1)2
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0khzzZPKyWzTCNP21DT6H8imJ@cmpmTmZeuUZSamBOS71aUmKyQp2@kyZWbmJlnW1BaElxSpFKaB1SSWqyipJGnA9SlAzRJU8lKSRcBlKyiuRQUijPyy4FKFEBqFECKgGI1eQo2ugrRBnp6Rgax2trRhgZxRsaxCrFc/wE "Haskell – Try It Online")
I would usually point something like this out in a comment, but then I thought, cops and robbers are a bit more cut-throat.
This is just [BMO's answer](https://codegolf.stackexchange.com/a/167654/66041) minus the special case for `b 42`. Because Laikoni's original goes via floating point, it's not necessary: just find a number large enough to give rounding errors in that but not in exact `Integer` arithmetic. For example:
```
a 100000000000000000000000 = 4999999999999999580569600000000000000000000000
b 100000000000000000000000 = 5000000000000000000000000000000000000000000000
```
[Answer]
# [Python 2](https://docs.python.org/2/), [xnor's answer](https://codegolf.stackexchange.com/a/167676/58563), 43 bytes
The first difference occurs for \$n = 69\$:
```
f=lambda n,p=2:n<1or-~f(n-(~-2**p%p<2),p+1)
```
[Try it online!](https://tio.run/##DcxBCoMwEAXQfU/xN8GMJmCmi4Jo75KSxgrtZAhu3Hj12HeAp8f@KcKt5eUbf68UIU4XnmQOpfozW/H29Nz3anRmcjoEarlUCDZBjbK@bXCPkaYbtG6yozOc4J8w99TBwIrDfyFqFw "Python 2 – Try It Online")
## Credits
A great deal of the credit for this crack must go to [**@Mr.Xcoder**](https://codegolf.stackexchange.com/users/59487/mr-xcoder) who first posted a comment about a possible attack using this method, and to [**@PoonLevi**](https://codegolf.stackexchange.com/users/79630/poon-levi) who found a 44-byte solution.
## How?
### Theory
The crack is based on [Fermat's little theorem](https://en.wikipedia.org/wiki/Fermat%27s_little_theorem) which states that if \$p\$ is prime and \$a\$ and \$p\$ are relatively prime, then:
$$a^{p-1}\equiv 1 \pmod p\tag{1}$$
In particular, for \$a=2\$:
$$2^{p-1}\equiv 1 \pmod p$$
So there exists some positive integer \$k\$ such that:
$$2^{p-1}=kp+1$$
Which leads to:
$$2^p=2kp+2$$
$$2^p-1=2kp+1$$
$$2^p-1\equiv 1 \pmod p\tag{2}$$
This last formula is the one the Python code is derived from and now holds for \$p=2\$, even though \$2\$ is not relatively prime with itself.
Now, for the most important part: the converse of Fermat's little theorem is not true. We may have \$a^{n-1}\equiv 1 \pmod n\$ for some *composite* number \$n\$. Such numbers are called [Fermat pseudoprimes](https://en.wikipedia.org/wiki/Fermat_pseudoprime) to base \$a\$. Fermat pseudoprimes to base 2 are also known as [Poulet](https://en.wikipedia.org/wiki/Paul_Poulet) numbers.
The first Fermat pseudoprime to base \$2\$ (or first Poulet number) is \$n = 341=11\times 31\$, for which we do have:
$$2^{341-1}\equiv 1 \pmod{341}$$
$$2^{341}-1\equiv 1 \pmod{341}$$
This means that our algorithm is going to return \$341\$ instead of the expected 69th prime \$347\$.
### Implementation
[@PoonLevi](https://codegolf.stackexchange.com/users/79630/poon-levi) found the following 44-byte solution, which is directly based on \$(2)\$:
```
f=lambda n,p=1:n and-~f(n-(~-2**p%p==1),p+1)
```
By using `<2` instead of `==1`, we save 1 byte but we introduce \$1\$ into the sequence, because \$2^1-1\equiv 0 \pmod 1\$:
```
f=lambda n,p=1:n and-~f(n-(~-2**p%p<2),p+1)
```
[Try it online!](https://tio.run/##DcxBDsIgEAXQvaf4G1KmQiLjrmm9CwbRJvo7Id246dXRd4Bn3/21UXuvyzt/7iWDwZY0EZklHtUz@iPqOJqzWSXYOUmvWwOxEi3z@fAp6EWmE6yt3DE4LYg3uGsZ4OAZ8F9E@g8 "Python 2 – Try It Online")
By starting with \$p=2\$, we get the expected terms off by 1 because we do one iteration less:
```
f=lambda n,p=2:n and-~f(n-(~-2**p%p<2),p+1)
```
[Try it online!](https://tio.run/##DcxBDoIwEAXQvaf4m4YOtomMOwLcpaZWSfQzadi44erFd4Bnv/29UVsr8yd9HzmBwWYdicQcj@IZ/RG1783ZpBLsOkgrWwWxEjXx9fRD0JuMF1hduaNzmhEXuHvu4OAZ8F9E2gk "Python 2 – Try It Online")
The last trick is to use `n<1or` instead of `n and`. This is just as long but makes the last iteration return *True* instead of *0*, hence adding the missing offset to each term.
[Answer]
# [Python 3](https://docs.python.org/3/), [crashoz](https://codegolf.stackexchange.com/a/167614/56656), 45 bytes
```
lambda n:int(60*math.sin(n/10-2))
import math
```
[Try it online!](https://tio.run/##fcxBDoIwEAXQPaeYZaeKFEQwmJ5EXdRAoQkMpNYET1@pylJXP5P//kxP14209628@F4Nt1oBVYYcKwQflOt2d0OMklTEGWJkhmm0DkLh60aDZoTVLD/9yTbuYQnCeuaFiGfO9zwVmyUPSRbOMjnmGEWTDeasmUHQowWzbMAqahsmtrnAK66k/UO@RvU9C5@k/Ilx/adZXr7hEuhf "Python 3 – Try It Online")
The expression `x*60-x**3*10+x**5/2-x**7/84` is the Taylor series for \$\sin(x)\$ up to the \$x^7\$ term, multiplied by \$60\$. This is accurate enough on the inputs used, but for higher values, the two will diverge as the truncated terms become more relevant.
[Answer]
# JavaScript (ES6), [Arnauld's answer](https://codegolf.stackexchange.com/questions/167596/hardcoding-the-cops-and-robbers-cops/167647#167647) (10 bytes)
```
n=>8*n*n|n
```
[Try it online!](https://tio.run/##HYdNCsIwFAb3niIUSn4rdifap2cJTRMq5XulEVfePSbCMMy8/Mfn@Vj39wAOS4kEesCoq4Ed9SlRqV/H4IsS@VCgyx3TWGWtnhmZt@W8cVKdV33Qog9/cufgooJ2qakVEbV@SnmTYhpEWGOUuvwA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Haskell](https://codegolf.stackexchange.com/a/167650/48198), [Laikoni's answer](https://codegolf.stackexchange.com/a/167650/48198), ~~26~~ 22 bytes
-4 bytes by not using infix `div`, thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni?tab=profile)!
```
b 42=0;b n=n*div(n+1)2
```
[Try it online!](https://tio.run/##hZCxbsJAEER7vmJ0orjLgXGsVIRrU9GRjlCs7SU@5VgT20CTf3fOjkIkN@lWM292VltR@8Eh9ARx8lCwD17edcMUXuuXhgrIKjN9jqfMpc/5CJX@qsU@mqw/kRc4lPUMOF@6XddsBQm0EkRjnyZJlh7AnxcKayhrTTTbqr5hjhOdQXfEuVHIf4VZXBi4w7C9Yiqxly/ZLAf3sIg5wcpFGjKS9@o51JvsYh9LwS1KfzxyM5yiYO1PswyTWqtJjPQUMbH6T9Ox00wy@X@Z@C7TfwM "Haskell – Try It Online")
### Explanation
For \$0 \leq n \leq 20\$ the term `ceiling(realToFrac n/2)` can be rewritten as `div(n+1)2` which gives us enough bytes to pattern match on an \$n > 20\$ that leads to a crack within 28 bytes:
```
b 42=0
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), [crashoz's answer](https://codegolf.stackexchange.com/a/167662/76162) 203 bytes
```
:l2-$g:0=?;n:
M
-
B
"
BM
",
7M
!"
BBM
!",
7CM
!"-
BBBM
!!",
7BBMM
!!,,
7BBBMM
!!,,
7BBBMM
!!!,,
7BBBBMM
!!!,,
7BBBBMM
!!!!,,
7BBBBBMM
!!!!,,
7BBBBBMM
!!!!!,,
7BBBBBBMM
```
[Try it online!](https://tio.run/##RYpLCsIwEIaJVi0/XXiFBJcNSKUUIiKM67mGWhA3Qq8/Tto0WX6P5/h7i4RP50@vcL7dr98Agw0q1DiCYTyohnE7kIJrMbCijRyFjebBBzTW6bm4WRLtmVXbdgZaYJsotTWmmnPueViPspSnTHqJiJ8u/R8 "><> – Try It Online")
I was going to do something clever with the fact that odd/even numbers above `n=20` were the same except for a repeated element in the center, but it was easier to just hard code every element.
Input is via the `-v` flag. Prints nothing for elements above 34.
[Answer]
# [Pascal (FPC)](https://www.freepascal.org), [AlexRacer's answer](https://codegolf.stackexchange.com/questions/167596/hardcoding-the-cops-and-robbers-cops/168149#168149), 80 bytes
```
var n,m:word;begin read(n);while n<>0 do begin n:=n div 2;m:=m+n;end;write(m)end.
```
[Try it online!](https://tio.run/##JclLCoAgEADQq8yy6EO1Cqe6izlTCTqFhR7fgnYP3qVvo12zXSbnqANI7VU6A@HKuxUIrKmQEtNhHYNMS0cn/CVqFiAbYUCvZl8JshCmYB8ufPm5zbkfxhc "Pascal (FPC) – Try It Online")
When \$0\le n\le 120\$ the outputs are identical, but when \$n=128\$ the above code outputs \$127\$, while AlexRacer's code outputs \$126\$.
This seems a late answer, but anyway thanks @AlexRacer for a good puzzle!
[Answer]
# JavaScript, [fəˈnɛtɪk's answer](https://codegolf.stackexchange.com/a/167617/59487) (12 bytes)
This works for the given values but fails for many other values (e.g. \$x=6\$) due to precision errors.
```
x=>2.72**x|0
```
### Testing
```
g=
x=>2.72**x|0
tmp=[0,1,2,3,4]
console.log(tmp.map(g).join(','))
```
Alternatively, [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/3ZarwtbOSM/cSEurosaAi6skt8A22kDHUMdIx1jHJJYrOT@vOD8nVS8nP10DKKeXm1igka6pl5WfmaehrqOuqfn/PwA "JavaScript (Node.js) – Try It Online")
[Answer]
# JavaScript, [fəˈnɛtɪk's answer](https://codegolf.stackexchange.com/a/167618/59487) (17 bytes)
You can see in the TIO link or in the Stack Snippet result that it fails for entries higher than \$15\$.
```
x=>2.7182819**x|1
```
If accuracy would only be required for \$n\le 14\$ (the first \$15\$ values), then [`x=>Math.exp(x)|1`](https://tio.run/##bYy9DoIwHAd3HoOpJT8qf6B8DPUNfALj0CAgBGgjxHTg3WtHB5cbLpeb9Ufv3XuyR7qZZ@8H5Z263vTxEr2zzPGT/KiCYkXK5KUqeJIIGeBOiqJjteqegZCjQAmJCjUatKAgCZSDClAJkqAKVIMaUIs8Q06PqDPbbpZeLGZk4SRWbdnAxWymjcWIOf9bjL@F/wI) would work as well for 16 bytes.
### Testing
```
f=x=>2.7182819**x|1
g=x=>(3-(5/63)**.5)**x|1
tmp=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
console.log(tmp.map(f).join(","))
console.log(tmp.map(g).join(","))
```
Alternatively, [Try it online!](https://tio.run/##bYyxDoIwGAZ3HoOpbT4qf0tLGeqLGAeCQCBAiRDD4LtX4uTgene5sX7VW/Mc1j1bwqONnY@HvypZklOOKiGON8Xen4zpjJmL1VwIafhXJMk@r/6Wg6CgUcDAooRDBTohgRRIgwqQAVlQCXKgCiqHonvShGULUyun0LPzJOd6ZR2XYxgWliLl/G/R/xbxAw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), cracking [BMO's 5 byter](https://codegolf.stackexchange.com/a/167651/53748) with ~~3~~ 2 bytes
-1 thanks to BMO (`LdΣ` -> `LΣ` since, when given a `Tnum`, `L` performs "length of string representation")
```
LΣ
```
**[Try it online!](https://tio.run/##yygtzv7/qG1ibn5xsM6jpsZzM/z@@5xb/P//f2MDAA "Husk – Try It Online")**
The digital length of the triangular numbers\* matches \$a(0)\cdots a(23)\$ then differs at \$a(24)\$
...when `LΣ` yields \$3\$ while `←d+16` yields \$4\$.
\* Where \$T(0)=0\$ has a digital length of \$1\$ (not \$0\$)
[Answer]
# [><>](https://esolangs.org/wiki/Fish), [Aiden F. Pierce's answer](https://codegolf.stackexchange.com/a/167921/76162), 36 bytes
```
v101786
i5844
419902
%
>l{:}g:0=?;o:
```
[Try it online!](https://tio.run/##S8sszvj/v8zQwNDcwowr09TCxITLxNDS0sCIS5XLLqfaqjbdysDW3jrf6v9/YwA "><> – Try It Online")
Another solution with each value hardcoded per line. Since the original answer was also mostly hard-coded, I don't feel too guilty about this.
[Answer]
# JavaScript, [fəˈnɛtɪk's answer](https://codegolf.stackexchange.com/a/167663/58563), 23 bytes
Returns \$0\$ for \$n\ge 14\$.
```
x=>14-`${73211e9}`[x]|0
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1s7QRDdBpdrc2MjQMNWyNiG6IrbG4H9afpFGpq2BdaaNEZDQ1tbkUlBIzs8rzs9J1cvJT9fI1FbStVPSTtPI1NT8DwA "JavaScript (Node.js) – Try It Online")
### How?
The expression ``${73211e9}`` expands to the string `"73211000000000"`, providing a lookup table of 14 values that are subtracted from 14, which gives the expected sequence.
For \$n\ge 14\$, the result is:
```
(14 - undefined) | 0
=== NaN | 0
=== 0
```
# 21 bytes
Returns `NaN` for \$n\ge 14\$, which may or may not be considered a valid output.
```
x=>14-`${73211e9}`[x]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1s7QRDdBpdrc2MjQMNWyNiG6IvZ/Wn6RRqatgXWmjRGQ0NbW5FJQSM7PK87PSdXLyU/XyNRW0rVT0k7TyNTU/A8A "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
This king-of-the-hill game is a strategy game in which you must throw around a water balloon and avoid getting splashed by water. The goal is to obtain the most points. You will be given a map of the field and the location of the water balloon. You can either return that you want to hit the water balloon (if you are close enough) in a certain direction or that you want to move in a certain direction.
Specifically:
The water balloon will start at `(0, 0)` 30 units high and drop. If the water balloon hits the ground, a player will randomly be chosen to lose 4 points, with more weight given to those who are closer to the balloon. In addition, the player who last hit the balloon will earn 3 points. Therefore, if you hit the balloon straight down, you will most likely lose 1 point.
You will write a class that extends `Player`. You are required to implement the constructor. The constructor will look like:
```
public Player1() {
super(/* Some numbers */ 3, 3, 4)
}
```
These numbers are `double`s. The first number represents the player's speed, the second represents strength, and the third represents luck. The numbers must add up to 10 or less and no number may be less than **or equal to** zero.
Second, you must implement the `move` method. This is an example `move` method:
```
@Override
protected Action move(Map<Player, Point2D> map, Balloon b) {
// Get my own location
Point2D myself = map.get(this);
// If I'm close enough to the balloon
// then hit the balloon
if (myself.distanceSq(b.getLocation()) <= 16) {
double d = (r.nextDouble() - 0.5) * 3;
// Random y direction, z direction is what's left
return new Hit(0, d, Math.sqrt(9 - d*d));
} else {
double diffX = b.getLocation().getX() - myself.getX(),
diffY = b.getLocation().getY() - myself.getY();
// Move towards the balloon
return new Movement(Math.signum(diffX)*3/Math.sqrt(2), Math.signum(diffY)*3/Math.sqrt(2));
}
}
```
There are a number of important things here. First, notice that the field is passed as a `Map<Player, Point2D>`. The field is infinite - there is no limit to how far you can go. It is not a 2-dimensional array or anything like that. In addition, this means that you will have non-integer coordinates as your location. This is perfectly okay.
Another consequence is that players and the balloon may overlap. In fact, two players may be in the exact same location!
The balloon has a certain velocity and direction. In general, it will fall at a rate of 3 units/step. It also moves in an `x` direction and `y` direction. When you return a `Hit`, you pass the x, y, and z directions that you are pushing the balloon. You cannot hit a balloon whose height is greater than 10 or whose distance from you (only on two dimensions) is greater than 4. In addition, if it is true that `x^2 + y^2 + z^2 > s^2` where `s` is your strength, and `x`, `y`, and `z` are the directions that you hit, your action is discarded. The force of your hit is amplified by a random number between `0` and `luck` (which means it could go down if your luck is low).
Similarly, you can return a `Movement` with the `x` and `y` coordinates that you are moving (note that you cannot jump in the air). If `x^2 + y^2 > s^2` where `s` is your speed, your action is discarded.
If the water balloon hits the ground then a random player is chosen, with more weight given to those who are closest -- but less weight to those who have more luck. The player that is chosen loses 4 points.
Controller: <https://github.com/prakol16/water-balloon-wars/tree/master>
The game lasts 1000 steps. At the end, there will be a file called `log.out`. Copy and paste the data into this fiddle to view the game: <https://jsfiddle.net/prankol57/s2x776dt/embedded/result/>
Or even better, view it in 3D: <http://www.brianmacintosh.com/waterballoonwars> (thanks to BMac)
The player with the highest sum of scores after 100 (may be more, but not less) games wins.
If you wish to submit a solution, you may want to read the really specific details at <https://github.com/prakol16/water-balloon-wars/tree/master>.
**Edit 3/8**:
These are the final scores for now (1000 iterations, without including players 1 and 2). If you edit your post, you can comment, and I will redo the scores:
```
{
class players.BackAndForth=-75.343,
class players.Hydrophobe=-0.800,
class players.KeepAway=-53.064,
class players.Weakling=39.432,
class players.Repeller=21.238,
class players.LuckyLoser=-30.055,
class players.AngryPenguin=-49.310
}
```
The winner was `Weakling` with an average of 39 points. 2nd place was `Repeller` with 21 points.
[Answer]
# Simulator
I hope this is okay, since it isn't actually an entry. I really liked the idea of the visual simulator and I wanted to create my own that would make it a little easier to see everything at once (full 3D).
**2/28 9:06AM PST**: update with follow controls, colors
**3/4 8:47AM PST**: update with a slider for simulation speed, and made starting a new game actually work without refreshing the page (use Ctrl-F5 to reload cached script)
[Online ThreeJS Visualizer](http://www.brianmacintosh.com/waterballoonwars)

[Answer]
# BackAndForth
This bot tries to get close and hit the balloon until its height is too low and it tries to get away.
```
package players;
import java.awt.geom.Point2D;
import java.util.Map;
import balloon.Action;
import balloon.Balloon;
import balloon.Player;
import balloon.Action.Hit;
import balloon.Action.Movement;
public class BackAndForth extends Player {
static int round = 0;
static int speed = 3;
static int strength = 1;
static boolean hit = false;
static double previousHeight = 30.0;
public BackAndForth() {
super(speed, strength, 10 - speed - strength);
}
@Override
protected Action move(Map<Player, Point2D> map, Balloon b) {
round++;
Point2D me = map.get(this);
Point2D balloon = b.getLocation();
double distanceX = balloon.getX() - me.getX();
double distanceY = balloon.getY() - me.getY();
double distance = Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
double maxX = speed * distanceX / distance;
double maxY = speed * distanceY / distance;
if (previousHeight < b.getHeight())
hit = false;
if (hit || b.getHeight() < 3) {
previousHeight = b.getHeight();
return new Movement(-maxX, -maxY);
} else {
if (distance < 4 && b.getHeight() < 10) {
hit = true;
return new Hit(0, 0, strength);
} else {
if (Math.pow(distance, 2) <= Math.pow(speed, 2)) {
return new Movement(distanceX, distanceY);
} else {
return new Movement(maxX, maxY);
}
}
}
}
}
```
[Answer]
## AngryPenguin
This penguin is angry because he can't fly up to the balloon, so he tries to hit the balloon into the face of people standing around him.
```
package players;
import java.awt.geom.Point2D;
import java.util.Map;
import java.util.Map.Entry;
import balloon.Action;
import balloon.Action.Hit;
import balloon.Action.Movement;
import balloon.Balloon;
import balloon.Player;
public class AngryPenguin extends Player {
private static final double HIT_Z = 3;
public AngryPenguin() {
super(4, 4, 2);
}
@Override
protected Action move(Map<Player, Point2D> map, Balloon balloon) {
Point2D myself = map.get(this);
double distanceX = balloon.getLocation().getX() - myself.getX();
double distanceY = balloon.getLocation().getY() - myself.getY();
double distance = Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
if (balloon.getHeight() < 2) {
double[] xy = shrink(distanceX, distanceY, Math.pow(getSpeed(),2));
return new Movement(-xy[0], -xy[1]);
} else if (distance <= 4 && balloon.getHeight() <= 10) {
double lowestDistance = Double.MAX_VALUE;
Point2D nearestPlayerLoc = null;
for (Entry<Player, Point2D> e : map.entrySet()) {
if (e.getKey() != this) {
double d = e.getValue().distanceSq(myself);
if (d < lowestDistance) {
lowestDistance = d;
nearestPlayerLoc = e.getValue();
}
}
}
double dX = nearestPlayerLoc.getX() - myself.getX();
double dY = nearestPlayerLoc.getY() - myself.getY();
double d = Math.pow(getStrength() - HIT_Z, 2);
double[] xy = shrink(dX, dY, d);
return new Hit(xy[0], xy[1], -HIT_Z);
} else {
double[] xy = shrink(distanceX, distanceY, Math.pow(Math.min(getSpeed(), distance), 2));
return new Movement(xy[0], xy[1]);
}
}
private double[] shrink(double x, double y, double totalPow) {
double[] xy = new double[2];
double ratio = y == 0 ? 0 :
x == 0 ? 1 : Math.abs(x) / Math.abs(y);
if (ratio > 1)
ratio = 1/ratio;
xy[1] = totalPow * ratio;
xy[0] = totalPow - xy[1];
xy[0] = x < 0 ? -Math.sqrt(xy[0]) : Math.sqrt(xy[0]);
xy[1] = y < 0 ? -Math.sqrt(xy[1]) : Math.sqrt(xy[1]);
return xy;
}
}
```
[Answer]
## Weakling
This bot can only touch the balloon as it is so weak, instead it just relies on its high luck. It therefore performs similarly to LuckyLoser (from which this bot is inspired).
He seems to out perform all the current bots including Repeller.
```
package players;
import java.awt.geom.Point2D;
import java.util.Map;
import balloon.Action;
import balloon.Balloon;
import balloon.Player;
import balloon.Action.Hit;
import balloon.Action.Movement;
public class Weakling extends Player {
static final private double STRENGTH = Double.MIN_VALUE;
static final private double SPEED = 1.5;
static final private double LUCK = 8.5;
public Weakling() {
super(SPEED,STRENGTH,LUCK);
}
protected Action move(Map<Player, Point2D> map, Balloon b) {
Point2D start = map.get(this);
Point2D balloon = b.getLocation();
double distance = start.distance(balloon)+Double.MIN_VALUE;
if(distance<=4 && b.getHeight()<=10){
// just touch it :P
return new Hit(0,0,0);
}
double x = start.getX()-balloon.getX();
double y = start.getY()-balloon.getY();
x /= distance;
y /= distance;
// move to directly underneath balloon
x*=Math.min(SPEED, distance);
y*=Math.min(SPEED, distance);
return new Movement(-x, -y);
}
}
```
EDIT: reduced speed in favour of luck
[Answer]
# Hydrophobe
This is one of the simplest possible bot possible but as it is competitive I will post it.
Strategy: well... this bots hates water so it just goes away.
As the bot will be splashed very rarely it will score a little under 0 point in average. The sum of all bots' scores are -1 \* [balloon hitting ground] so Hydrophobe will probably score above average.
```
package players;
import java.awt.geom.Point2D;
import java.util.Map;
import balloon.*;
public class Hydrophobe extends Player {
public Hydrophobe() {super(8, 1, 1);}
@Override
protected Action move(Map<Player, Point2D> map, Balloon balloon) {
return new Action.Movement(5.65,5.65);
}
}
```
[Answer]
# KeepAway
This player chases the balloon as long as its height is > 2. As soon as it can hit the balloon, it hits the balloon **away from** the closest player. When the balloon's height is < 2, this player runs away.
```
package players;
import java.awt.geom.Point2D;
import java.util.Map;
import balloon.Action;
import balloon.Balloon;
import balloon.Player;
import balloon.Action.Hit;
import balloon.Action.Movement;
public class KeepAway extends Player{
public KeepAway() {
super(5, 3, 2);
}
@Override
protected Action move(Map<Player, Point2D> map, Balloon b) {
Point2D myself = map.get(this);
//if balloon is high up, run towards it
if(b.getHeight() > 2){
Point2D closest = getClosestPlayer(map);
boolean canHit = b.getHeight() <= 10 && myself.distance(b.getLocation()) <= 4;
//hit it when you can
if(canHit){
Point2D normHit = normalize(new Point2D.Double(myself.getX() - closest.getX(), myself.getY() - closest.getY()));
Point2D forceHit = new Point2D.Double(normHit.getX() * getStrength(), normHit.getY() * getStrength());
return new Hit(forceHit.getX(), forceHit.getY(), 0);
}
//if you can't hit it, keep running towards it
else {
Point2D normRun = normalize(new Point2D.Double(myself.getX() - b.getLocation().getX(), myself.getY() - b.getLocation().getY()));
Point2D forceRun = new Point2D.Double(-normRun.getX() * getSpeed(), -normRun.getY() * getSpeed());
return new Movement(forceRun.getX(), forceRun.getY());
}
}
//if the balloon is low, run away
else{
Point2D normRun = normalize(new Point2D.Double(myself.getX() - b.getLocation().getX(), myself.getY() - b.getLocation().getY()));
Point2D forceRun = new Point2D.Double(normRun.getX() * getSpeed(), normRun.getY() * getSpeed());
return new Movement(forceRun.getX(), forceRun.getY());
}
}
private Point2D getClosestPlayer(Map<Player, Point2D> map){
double minDistance = Double.MAX_VALUE;
Point2D closestPoint = null;
Point2D myPoint = map.get(this);
for(Player p : map.keySet()){
if(this != p){
if(myPoint.distance(map.get(p)) < minDistance){
minDistance = myPoint.distance(map.get(p));
closestPoint = map.get(p);
}
}
}
return closestPoint;
}
private Point2D normalize(Point2D p){
double d = p.distance(0, 0);
if(d == 0){
return new Point2D.Double(0, 0);
}
return new Point2D.Double(p.getX()/d, p.getY()/d);
}
}
```
Edit: I was playing with Player1 and Player2 included. This player wins in that case, but loses when I take them out. Booooo.
[Answer]
## Lucky Loser
This bot relies on its high luck score. If it is not near the balloon, it runs towards the balloon. Once near the balloon, if there are at least 2 other players in range of the balloon, he'll spike it to the ground. Otherwise, he'll knock it straight up.
```
package players;
import java.awt.geom.Point2D;
import java.util.Map;
import balloon.Action;
import balloon.Balloon;
import balloon.Player;
import balloon.Action.Hit;
import balloon.Action.Movement;
public class LuckyLoser extends Player {
public LuckyLoser() {
super(1,1,8);
}
protected Action move(Map<Player, Point2D> map, Balloon b) {
Point2D start = map.get(this);
Point2D bLocation = b.getLocation();
double distance = start.distance(bLocation);
if(distance<=4){
boolean foundMe = false;
int numPlayersInRange=0;
for(Point2D point:map.values()){
if( !foundMe && point.equals(start))
{
foundMe=true;
continue;
}
if(point.distance(bLocation)<=4)
numPlayersInRange++;
}
if(numPlayersInRange>1)
return new Hit(0,0,-1);
else
return new Hit(0,0,1);
}
double x = start.getX()-bLocation.getX();
double y = start.getY()-bLocation.getY();
x /= distance;
y /= distance;
return new Movement(-x, -y);
}
}
```
EDIT: Fixed movement bug which actually made me run away not towards the balloon >\_< Now I just run straight towards the balloon if I can't hit it.
[Answer]
## Repeller
This bot relies has only one real move and that is to keep on pushing the balloon away from itself. i.e. repells the balloon.
It seems to perform well against the current crop of bots (LuckyLoser, AngryPenguin, Hydrophobe, BackAndForth ) nearly always winning. However Hydrophobe, by inaction, is always ready to win if the other bots all manage to get negative score :P
```
package players;
import java.awt.geom.Point2D;
import java.util.Map;
import balloon.Action;
import balloon.Balloon;
import balloon.Player;
import balloon.Action.Hit;
import balloon.Action.Movement;
public class Repeller extends Player {
static final private double STRENGTH = 3.5;
static final private double SPEED = 2.5;
static final private double LUCK = 4;
public Repeller() {
super(SPEED,STRENGTH,LUCK);
}
protected Action move(Map<Player, Point2D> map, Balloon b) {
Point2D start = map.get(this);
Point2D balloon = b.getLocation();
double distance = start.distance(balloon)+Double.MIN_VALUE;
if(distance<=4 && b.getHeight()<=10){
double x = start.getX()-balloon.getX();
double y = start.getY()-balloon.getY();
x /= distance;
y /= distance;
x*=STRENGTH;
y*=STRENGTH;
// push the balloon away with all our strength
return new Hit(-x,-y,0);
}
double x = start.getX()-balloon.getX();
double y = start.getY()-balloon.getY();
x /= distance;
y /= distance;
// if we are directly underneath then move away from balloon
distance=distance<1?-1:distance;
// if we are just off of directly underneath then stay put
distance=distance<2?0:distance;
// move to the desired location
x*=Math.min(SPEED, distance);
y*=Math.min(SPEED, distance);
return new Movement(-x, -y);
}
}
```
] |
[Question]
[
Your function must accept two [strings](https://codegolf.meta.stackexchange.com/questions/2214/whats-a-string/8964#8964) and return new string where are UTF-16 code of all symbols is the sum of UTF-16 codes of inputs symbols
* If the resulting sum is greater than `65535` (maximum UTF-16 codepoint), take the sum modulo `65536`
* If there are more symbols in one string then sum with zero, codes of symbols which doesn't have pairs
For example:
* `'a' + 'b' = a(97) + b(98) = 97 + 98 = 195 => 'Ã'`
* `'A' + 'B' = A(65) + B(66) = 65 + 66 = 131 => '\u0083' (No Break Here)`
* `'Aa' + 'BbC' = [A(65) + B(66)][a(97) + b(98)][(0) + C(67)] => '\u0083ÃC'` - `\u0083` will not be displayed but it must be here so the length of result string must be 3 not 2
**Test cases**:
```
'a', 'b' --> 'Ã'
'A', 'B' --> '\u0083'
'Aa', 'BbC' --> '\u0083ÃC'
'耀', '耀' --> '\u0000' (Null character)
'Программирование', 'Programming' --> 'ѯҲҭҚҲґҩҩҡҮҥвание'
```
Ungolfed version (check in real time):
```
const updateResult = () => {
const string_1 = input1.value;
const string_2 = input2.value;
resultString = [];
for (let i = 0; i < string_1.length || i < string_2.length; ++i) {
resultString.push(
(string_1.charCodeAt(i) || 0) +
(string_2.charCodeAt(i) || 0)
);
}
resultString = String.fromCharCode(...resultString);
result.innerHTML = resultString;
resultLength.innerHTML = 'Length: ' + resultString.length;
}
input1.addEventListener('input', updateResult);
input2.addEventListener('input', updateResult);
updateResult();
```
```
<input id="input1" value="aA"/>
<input id="input2" value="bB"/>
<br/><br/>
<div id="result"></div>
<div id="resultLength"></div>
```
The shortest code in each programming language wins!
[Answer]
# Excel, ~~92~~ 89 bytes
```
=CONCAT(
TOCOL(UNICHAR(MOD(MMULT(IFERROR(UNICODE(MID(A1:B1,ROW(A:A),1)),),{1;1}),4^8)),2)
)
```
Inputs in cells `A1` and `B1`.
*Thanks to JvdV for the 3-byte save*.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
C∑k₴%C
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJD4oiRa+KCtCVDIiwiIiwiW1wi0J/RgNC+0LPRgNCw0LzQvNC40YDQvtCy0LDQvdC40LVcIiwgXCJQcm9ncmFtbWluZ1wiXSJd)
**How it works**:
```
C∑k₴%C
C∑ Sum codepoints of each word
k₴% Push 65535 and modulo by each element
C Convert codepoints to words
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as an array of 2 character arrays, outputs a single character array.
```
ÕËxc uG²² d
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=bXE&code=1ct4YyB1R7KyIGQ&footer=VnE&input=WwoiXHU4MDAwIgoiXHU4MDAwIgpdCi1R)
```
ÕËxc uG²² d :Implicit input of 2D array
Õ :Transpose
Ë :Map
x : Sum of
c : Codepoints
u : Modulo
G : 16
²² : Squared twice
d : Character at resulting codepoint
```
[Answer]
# Z80 machine language, 52 bytes
Null-terminated strings, addresses passed in `DE` and `HL`;
output string address passed in `BC`.
Little-endian.
```
D5 E5 7E 23 B6 23 EB 28 0A 7E 23 B6 23 EB 20 F4
37 E1 D5 30 03 EB C5 7E 02 23 03 B6 7E 02 23 03
20 F7 E1 1A 47 86 77 13 23 1A 4F 8E 77 13 23 78
B1 20 F2 C9
```
Disassembled:
```
f:
push de // D5
push hl // E5
wl:
ld a,(hl) // 7E // test one wchar of each
inc hl // 23
or (hl) // B6
inc hl // 23
ex de,hl // EB
jr z,fzero // 28 0A
ld a,(hl) // 7E
inc hl // 23
or (hl) // B6
inc hl // 23
ex de,hl // EB
jr nz,wl // 20 F4
scf // 37 // if we have made it here, first was shorter
fzero:
pop hl // E1
pop de // D5
jr nc,copy // 30 03
ex de,hl // EB
copy: // when we get here, wstrlen(hl)>wstrlen(de)
push bc // C5
cl:
ld a,(hl) // 7E // copy a byte
ld (bc),a // 02
inc hl // 23
inc bc // 03
or (hl) // B6 // or in the second to see if both 0
ld a,(hl) // 7E // copy the second (preserves flags)
ld (bc),a // 02
inc hl // 23
inc bc // 03
jr nz,cl // 20 F7 // if either nonzero, loop again
pop hl // E1 // put dest in hl
aloop:
ld a,(de) // 1A
ld b,a // 47
add (hl) // 86
ld (hl),a // 77
inc de // 13 // *(hl++) += (b = *(de++)
inc hl // 23
ld a,(de) // 1A
ld c,a // 4F
adc (hl) // 8E
ld (hl),a // 77
inc de // 13
inc hl // 23 // *(hl++) += (c = *(de++)) + cf
ld a,b // 78
or c // B1
jr nz,aloop // 20 F2 // continue if b|c
ret // C9
```
[Answer]
# Python, 89 bytes
```
lambda x,y:[chr(sum(map(ord,a))%4**8)for a in zip(f'{x:\0<{len(y)}}',f'{y:\0<{len(x)}}')]
```
[Try it online!](https://tio.run/##lYxNDgFBEIX3TtEb6WrpiISFCAtcwB6L9jOjRf@kjGSGSOYmriBEYoEztFu4xei2sCaVVL33Ut@zWbIwut60WESdUbESajITJOVZazhdIKw3CpSwYHDGBWPlRqXSZJFBIojUZCstRHSXtka19m4115Cx/Z5yH2XfKA0RGxdCr0mHREC7gnJCe5M@ZSWLUieAc4tAaXVppAb/xxgnAf3I0hd0h2fuHu7s99Hd/Fw//uTd3V3dJdQO0MQolJI6/rf@leehIZyfyOIN)
-15 bytes thanks to @SevC\_10
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
0ζOžH%ç
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f4Nw2/6P7PFQPL///P1r9wvyLDRf2XdgMJDdc2AOEO8D8TUDe3gs7LmxV11FQDyjKTy9KzM3NzEtXjwUA "05AB1E – Try It Online")
#### Explanation
```
0ζOžH%ç # 05AB1E automatically converts the strings
# to codepoints since they are delimited by '
0ζ # Transpose with filler 0
O # Sum each inner list
žH # Push 65536
% # Mod each value by 65536
ç # Convert back from codepoint to character
```
[Answer]
# [J](https://www.jsoftware.com), ~~30~~ ~~27~~ 25 bytes
```
(65536|+/@,:)&.(3 u:7&u:)
```
-3 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs), and -2 more.
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxU8PM1NTYrEZb30HHSlNNT8NYodTKXK3UShMif7NGkys1OSNfQT1RXSFNQT1JHcp1BHOd4FyItFNSMkzkRUMDWAhEQ4UuzL_YcGHfhc1AcsOFPUC4A8zfBOTtvbDjwlaw-oCi_PSixNzczLx0dYgbFiyA0AA)
```
(65536|+/@,:)&.(3 u:7&u:)
&. NB. u&.v applies v to both args and u to the results
NB. then applies the inverse of v to the results of u
(3 u:7&u:) NB. monadic fork
7&u: NB. converts each char to a single unicode codepoint
3 u: NB. convert string to a list of codepoints
(65536|+/@,:) NB. dyadic fork
,: NB. stacks codepoint lists filling with 0s
+/@ NB. then sum the columns of the resulting table
65536| NB. mod each sum by 65536
NB. inverse of v converts codepoints to chars
```
[Answer]
# [Python 3](https://docs.python.org/3/), 76 bytes
```
f=lambda a,b:a and b and chr(ord(a[0])+ord(b[0])&65535)+f(a[1:],b[1:])or a+b
```
[Try it online!](https://tio.run/##VVDNSsNAEL7nKYYc3KxNS6RUpFClLS0IooV6qznsNps2sPlhm6i9FfoEXr2IBw8e/KEi9KBe@gJpnsK3iLttsToD387MN9@3y0bjeBgG5Tx3a5z41CFATFqVGDhAV9gfCiMUjkF6lo0LqqKq2tmvVMoVXHAlsVe1TaoQhwJIgeaeH4UiBsE0LRbjqgYyroYeZ3AuErbuVRATqAkMauCTyGCXhJtSVHK9wCGcGzoq7R4h3QQviJLYwBj/KkOpkVdL/XYWCS@IDb3XqXe7tg6eq7Zq0p7xEQO9164fn9jSLcQau@6zKIbWWbslRCjWL4rIaKTliCATEEVQLB4CWkyRhupq0thMLhLLOiir6WqxQZv/iMW0KbnvyUSR6tiSloXAOE04l39KBOnHTGANpXfLSfqVvkl8TT9kzlf9THaf6Tx9Vz4dEQ4E8X0vGGz8li/ZLHvKbiXeZI8y77Pn7OGP6gc "Python 3 – Try It Online")
[Answer]
# [Raku](https://raku.org/), 61 bytes
```
{utf16(roundrobin(@_».encode('utf16'))».sum X%4⁸).decode}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/urQkzdBMLy@1XKMovzQvpSg/KTNPwyH@0G691Lzk/JRUDXWwCnVNTaBQcWmuQoSqyaPGHZp6Kakg6dr/xYmVCnpZ@UBd6joK6ppArGBrpwBkp2nUqMRrKqTlFynYJCok2eko2DgqOIGpRAWnJGcQ60VDgwIQg5gX5l9suLDvwmYgueHCHiDcAeZvAvL2XthxYatCQFF@elFibm5mXrrdfwA "Perl 6 – Try It Online")
(The older Raku version on TIO requires a ".new" after the first "utf16" for four additional bytes.)
* `@_` are the string arguments to the function.
* `».encode('utf16')` encodes each of those strings as a utf16 blob object.
* `roundrobin` combines corresponding elements of those blobs as lists, like `zip`, but doesn't stop when the end of the shortest input is reached. `roundrobin <1 2>, <3 4 5 6>` returns `(1 3), (2, 4), (5,), (6,)`.
* `».sum` converts each of those zipped lists to its sum.
* `X% 4⁸` takes each of those sums modulo 65536. (`4⁸` is one byte shorter than `65536`.)
* `utf16` converts that list of integers to a utf16 blob.
* `.decode` converts that blob into a string.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes
```
F²⊞υSUMυ⁺ι×ψ⁻L§υ¬ιLι⭆⊟υ℅﹪⁺℅ι℅§ΣυκX⁴¦⁸
```
[Try it online!](https://tio.run/##NU5LasMwEN3nFFqOQN2ELgpZlawCdStILyBsxxaVNEaW2maXm@QKISWQRdIzqCdSx2rDwDBvZt6n7pWvUZmcN@gZzDmTcewhCrZyQwzr4LXrgPPFrFLDEq1Vrpmu0sQRtGCv2rYjbAWrtKPNU@u60MNjWLmm/ZwenzGA5pwL9n@bAMlJEg7wp0/SIHGASF9LCqTq0HqosIkGoTi9@EY7ZYgs2G2@mayjLcy34iLxg7j3gj3wYpRz2v/s0nf6on5IF6pzwUdC13ROJ4qCnVfWUpJ8925@AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F²⊞υS
```
Input the two strings.
```
UMυ⁺ι×ψ⁻L§υ¬ιLι
```
Pad the shorter to the length of the longer with null bytes.
```
⭆⊟υ℅﹪⁺℅ι℅§ΣυκX⁴¦⁸
```
Pairwise add the character codes of the two strings, reduce module `4⁸`, then convert back to characters.
[Answer]
# [Factor](https://factorcode.org/), 38 bytes
```
[ 0 pad-longest [ + 65536 mod ] 2map ]
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQWFycn1ysUJxaWJqal5yKxNJLrSgpSixWyE0syVAoKEotKaksKMrMK1Gw5qrmUgCCagWlRCUFpSQlhVoY3xHId0LmgxQ4JTkjCb1oaFCCknCxC/MvNlzYd2EzkNxwYQ8Q7gDzNwF5ey/suLAVqCGgKD@9KDE3NzMvHaSx9n@0goFCQWKKbk5@XnpqcYlCtIK2gpmpqbGZQm5@ikKsglFuYoFC7P80iA/tQLziksTkbL3/AA "Factor – Try It Online")
* `0 pad-longest` pad the shorter of two sequences with 0s until it is the same length as the longer one
* `[ ... ] 2map` map over two sequences with a binary function
* `+ 65536 mod` add the code points together modulo 65536
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes
```
ạᵐz₁+ᵐ%₆₅₅₃₆ᵐ~ạ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GuhQ@3Tqh61NSoDaRVHzW1PWpqBaNmIBsoVAdU8f9/tNKF@RcbLuy7sBlIbriwBwh3gPmbgLy9F3Zc2Kqko6AUUJSfXpSYm5uZl64U@z8KAA "Brachylog – Try It Online")
### Explanation
```
ạᵐ Map to codes
z₁ Zip without cycling
+ᵐ Map sum
%₆₅₅₃₆ᵐ Map mod 65536
~ạ Codes to string
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/) with `-fwide-exec-charset=UTF16LE`, 78 bytes
Takes inputs in UCS-2 (UTF-16LE) encoding and outputs in UCS-2 (UTF-16LE) encoding. TIO and shells don't seem to like UTF-16: running this from an actual machine and redirecting the output gives the correct results.
Output (in KWrite, UTF-16 encoding):
[](https://i.stack.imgur.com/HU105.png)
```
f(i,j,k)short*i,*j;{for(;*i|*j;*i&&i++,*j&&j++)printf("%2$c%c",k>>8,k=*i+*j);}
```
[Try it online!](https://tio.run/##RY9PSsNAGMX3PcUQbDr/Am0XIgwpWNFVFy50pS7SaSadxCQyGVSogdzEK4hS6EI9w3gLT2GcjKEy8Ob7ve97i8eDhPO2FVDSlGaoWpdKY0lxyjaiVJBh@WRnLH1fEmJt308JQXdKFlpAbzg94EPu0Ww2O6JZiCXBKWJ1a7cgj2QB70u5QmAzAKCzcHV1E3YAwMKLPGp16dGejx3P//nvYL482VvfTeM89/eeef5qzKd5s/pi3u3bOX619GF2ZusC56pMVJTnskj64NhqTQHGmg3s2HXVYcWAZaBJOKVg39E1HF0XIzpGCAiItc1BTSYIsUHd/nBxGyVVG4gHuYqD@DHmAV9Hqop1eHlxNjlcnP4C "C (gcc) – Try It Online")
[Answer]
# JavaScript, 91 bytes ([tsh](https://codegolf.stackexchange.com/users/44718/tsh)'s [method](https://codegolf.stackexchange.com/questions/258550/sum-of-strings-utf-16-codepoints/258551?noredirect=1#comment570818_258551))
With recursion
```
(a,b)=>(g=i=>a[i]?String.fromCharCode(a[c='charCodeAt'](i)+~~b[c](i))+g(i+1):b.slice(i))(0)
```
Try it:
```
f=(a,b)=>(g=i=>a[i]?String.fromCharCode(a[c='charCodeAt'](i)+~~b[c](i))+g(i+1):b.slice(i))(0)
const inputHandler = () => {
resultString = f(input1.value, input2.value)
result.innerHTML = resultString;
resultLength.innerHTML = 'Length: ' + resultString.length;
}
input1.addEventListener('input', inputHandler);
input2.addEventListener('input', inputHandler);
inputHandler();
```
```
<input id="input1" value="aA"/>
<input id="input2" value="bB"/>
<br/><br/>
<div id="result"></div>
<div id="resultLength"></div>
```
# JavaScript, 97 bytes
Without recursion
```
(a,b)=>String.fromCharCode(...[...a].map((s,i)=>(g=c=>c.charCodeAt(j=i)|0)(a)+g(b)))+b.slice(j+1)
```
Try it:
```
f=(a,b)=>String.fromCharCode(...[...a].map((s,i)=>(g=c=>c.charCodeAt(j=i)|0)(a)+g(b)))+b.slice(j+1)
const inputHandler = () => {
resultString = f(input1.value, input2.value)
result.innerHTML = resultString;
resultLength.innerHTML = 'Length: ' + resultString.length;
}
input1.addEventListener('input', inputHandler);
input2.addEventListener('input', inputHandler);
inputHandler();
```
```
<input id="input1" value="aA"/>
<input id="input2" value="bB"/>
<br/><br/>
<div id="result"></div>
<div id="resultLength"></div>
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 9 bytes
```
z::i::+:c
```
[Try it online!](https://tio.run/##S85KzP1f/b/KyirTykrbKvl/rVWodbTShfkXGy7su7AZSG64sAcId4D5m4C8vRd2XNiqpKAUUJSfXpSYm5uZl64UG/ofAA "CJam – Try It Online")
# Explanation
```
z::i::+:c # a function taking an array with two strings [x y]
z # zip; transpose rows with columns (i.e, ["Aa" "BbC"] => ["AB" "ab" "C"]
::i # map `i`nt convert to all values
::+ # map add to all values, effectively summing each
:c # map each summed value to `c`hars
```
] |
[Question]
[
# Introduction
Many old chess books use [descriptive notation](https://en.wikipedia.org/wiki/Descriptive_notation) to notate squares on a chessboard, naming the file (column) of the square based on the starting piece positions of White or Black, depending on whose move it is. The ranks (rows) are numbered 1 through 8, with 1 being closest to the player. For example, from White's perspective, QR2 represents the file where the queenside rook started, on the 2nd rank from the bottom.
However, this system has been entirely replaced by algebraic notation in the past few decades, which simply notates files with letters a-h and rows with numbers 1-8, always "from White's point of view". Therefore it would be convenient to have a program that can translate squares from old books.
Note: This problem is the simplified inverse of [Convert Algebraic notation to Descriptive notation](https://codegolf.stackexchange.com/questions/88812/convert-algebraic-notation-to-descriptive-notation)
# Diagrams
### Descriptive notation
[](https://i.stack.imgur.com/68ETM.png)
Credit: David Eppstein
### Algebraic notation
[](https://i.stack.imgur.com/rlvvS.png)
Credit: ILA-boy, Klin, Beao
# Task
Given a chess square as a string and either white or black's perspective in descriptive notation, output the chess square in algebraic notation. Reasonable inputs may be used, such as a boolean for white/black perspective. For simplicity, we do not handle moves (including captures) or special symbols (promotion, castling, blunders, end of game, etc.)
The inputs and outputs are case sensitive and follow the above diagrams, with descriptive notation always using capital letters and algebraic notation always using lowercase letters. You must take the input square as one string like "QR1", not two like "QR" and "1".
# Test cases
```
white,QR1 => a1
white,KR8 => h8
white,Q4 => d4
white,KN7 => g7
black,QR1 => a8
black,KR8 => h1
black,Q4 => d5
black,KN7 => g2
```
[Answer]
# JavaScript (ES6), 62 bytes
Expects `(white)(string)`, where *white* is a Boolean flag.
```
w=>s=>"egfbchda"[(q=parseInt(s,b=29))/b%43%10|0]+(w?q%b:9-q%b)
```
[Try it online!](https://tio.run/##bc1NC4IwAMbxe59CBsJGmc4WajA7RxDoNTpsOrUQp07y0ndfQYK97PJcfjz8b@zOVNZf28FpZC50QfVIY0VjIMqCZ1XOwBl2tGW9EodmgGrFqR8h5HKbbGzsPbzLEo77zua7yHkt0plslKzFupYlLCBGECQpBghZrmsxvPjnYxpOXIUGTgiw3pwT0/sUTO8y@GHvux0a@KONTe@5vTW957avnw "JavaScript (Node.js) – Try It Online")
### How?
We parse the descriptive notation as a base-29 string and save the result in \$q\$.
The row number is \$q\bmod29\$ for White and \$9-(q\bmod29)\$ for Black.
For the column, we apply this minimal perfect hash function:
$$\big(\lfloor q/29\rfloor\bmod43\big)\bmod10$$
| Column | String | \$\lfloor q/29 \rfloor\$ | \$\bmod 43\$ | \$\bmod 10\$ |
| --- | --- | --- | --- | --- |
| a | "QRx" | 781 | 7 | 7 |
| b | "QNx" | 777 | 3 | 3 |
| c | "QBx" | 765 | 34 | 4 |
| d | "Qx" | 26 | 26 | 6 |
| e | "Kx" | 20 | 20 | 0 |
| f | "KBx" | 591 | 32 | 2 |
| g | "KNx" | 603 | 1 | 1 |
| h | "KRx" | 607 | 5 | 5 |
### Example search code
This simple piece of code looks for the shortest valid hash functions of the form `parseInt(s, b) % m0 % m1` with \$28\le b\le 36\$ and \$2\le m\_1<m\_0<100\$.
It is quite inefficient because it tries all tuples \$(b,m\_0,m\_1)\$ even if \$(b,m\_0)\$ alone leads to an unrecoverable lookup collision. But this works fine for a such a limited search space.
```
const O = {
"QR" : "a",
"QN" : "b",
"QB" : "c",
"Q" : "d",
"K" : "e",
"KB" : "f",
"KN" : "g",
"KR" : "h"
};
let best = 1 / 0;
for(let b = 28; b <= 36; b++) {
for(let m0 = 2; m0 <= 100; m0++) {
for(let m1 = 2; m1 < m0; m1++) {
let lookup = Array(m1).fill('?');
if(Object.keys(O).every(key => {
let i = parseInt(key, b) % m0 % m1;
if(lookup[i] == '?') {
lookup[i] = O[key];
}
return lookup[i] == O[key];
})) {
let str = lookup.join('').replace(/\?*$/, ''),
code = `"${str}"[parseInt(s,${b})%${m0}%${m1}]`,
score = code.length;
if(score <= best) {
best = score;
console.log(`Score: ${score} : ${code}`);
}
}
}
}
}
```
[Try it online!](https://tio.run/##ZZJRT4MwEMff@RQXsmWtQwaaGCPiom/GRKI@ziUD7DYmo0thJsvSzz7vKNtAX9r7X3/3v6N0Ff/EZaqyTXVZyC9xOKSyKCuIIIS9BWC/vdtwB3ZsO7V6rVXSqKdapY2ygdSXUS9GiUYZct4o47JolOmwtC0dWFYuKkgEThCCDyPwMDWXitVpzF3dBrjfh3B9g8FwyOspj8TaIySgHRHf8yg8Qi3MbzAf7hGg4AwBEJJL@b3dIPaoVLxja5@78yzP2WA84DiSAbM5i5KVSCv3W@xKFnFX/Ai1Y6ggfDj5GccMzTaxKsVzURHhQMKhT6Pi4gcnFk1N80k2hTAE6tiyAmidQjRBp@m5WJ8iJaqtKqBj1aU1539GLCuFnqbEXcmsYIMBd5XY5HEq2OhzfNEbOYA5pzUOQIrvButmdm@PDtqenD6zdHr7RPN@b7/2NK2@ns66xWUqFVWTiZuLYlEtO3dhzvFv0qPoXkTzTGoisNrzFKXM0U0u2OyDTu8AR6NAA4XUS8/4/2szO63a0ofDLw "JavaScript (Node.js) – Try It Online")
[Answer]
# JavaScript, 68 bytes
```
s=>w=>'dcbaefgh'[x=s.at(-1),('P'>s)*4-~'BNR'.search(s[1])]+(w?x:9-x)
```
```
f=
s=>w=>'dcbaefgh'[x=s.at(-1),('P'>s)*4-~'BNR'.search(s[1])]+(w?x:9-x)
function test(white) {
const table = document.createElement('table');
for (const i of (white ? '12345678' : '87654321')) {
const row = table.appendChild(document.createElement('tr'));
for (const j of 'QR,QN,QB,Q,K,KB,KN,KR'.split(',')) {
row.appendChild(document.createElement('td')).textContent = f(j + i)(white);
}
}
document.body.appendChild(table);
}
test(true);
test(false);
```
```
table { display: inline-table; margin-right: 30px; border-collapse: collapse; border: 1px solid black; }
td { width: 25px; height: 25px; line-height: 25px; text-align: center; background: white; color: black; }
tr:nth-child(odd) td:nth-child(even), tr:nth-child(even) td:nth-child(odd) { filter: invert(); }
```
[Answer]
# [Python](https://www.python.org), 65 bytes
```
lambda t,s:f'{97+((x:=int(s[1:],30))>>8^3+(s<"Q")):c}{(-t^x)%10}'
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3HXMSc5NSEhVKdIqt0tSrLc21NTQqrGwz80o0iqMNrWJ1jA00Ne3sLOKMtTWKbZQClTQ1rZJrqzV0S-IqNFUNDWrVoQbtKUktLrGN5lJQ0DDQUQoMMlTSUUo0VNLUgYp4B1kARTIsECKBJkCBFBMkJX7mQJF0c6iIIdwYC4QI1BhDJDVgY0yRlECMMVLSBArEcqXlF4F8p5OvkJmnAHKkFVC4oAjkwzQNoISmTr4mxA8LFkBoAA)
### Old [Python](https://www.python.org), 67 bytes (@xnor)
```
lambda t,s:f'{97+(11*ord(s[1])>>7^7*(s>"L")):c}{8**t*int(s[-1])%9}'
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3nXMSc5NSEhVKdIqt0tSrLc21NQwNtfKLUjSKow1jNe3szOPMtTSK7ZR8lDQ1rZJrqy20tEq0MvNKgPK6QAWqlrXqUKP2lKQWl9hGcykoaBjoKAUGGSrpKCUaKmnqQEW8gyyAIhkWCJFAE6BAigmSEj9zoEi6OVTEEG6MBUIEaowhkhqwMaZISiDGGClpAgViudLyi0D-08lXyMxTADnSCihcUATyRJoGUEJTJ18T4ocFCyA0AA)
### Old [Python](https://www.python.org), 68 bytes (@ovs)
```
lambda t,s:f'{97+(11*ord(s[1])>>7^7*(s>"L")):c}{int(t*"-"+s[-1])%9}'
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY_BCoIwHIfvPcX4Q7jZhBbFTMhTtyKoqxVYtgrKiVuHEJ-kixD1FL1Ib9NMKU-Dbx8f_9_tmVz1QcbFXYyWj4sWjvsen8LzJgqRpsoTVjbkHcyYLdMIq4CtiO_zNbex8mEKhHjbPDvGGmsbHOiowDFGe5hbdeuld0qPghZCuEthvmBAIWRAaE0mC9eQg_sn874BUb-hzLghe14T9su4f1JnWMP5ZgYNpcr0gBiwagmZlgOpRMcYlUd6BidpOUVg80GoJNWGoqjeDw)
### Old [Python](https://www.python.org), 72 bytes
```
lambda t,s:"%c%i"%(97+("RNB".find(s[1])%4^7*(s<"Q")),int(t*"-"+s[-1])%9)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY9BCsIwEEX3niIMFBJNxUiltdiNK0EQ2m1VqNZoQJvSxIVncVMQPYUX8TamGrSrgfc_j_nXR3nRB1nUNx4t72fN3eA1O2anTZ4hTVUIztYR4OCx38OQLKbQ56LIsUrZijje2u9iNYEYCKGi0Fh3wYWeSt0mHRPre-qd0lHaQQgPKMQJAwoZA0ItmSeBIYfgT2LPgNxrVRa-IXvfEvbTBH9iNazV-WhGrcpXMwRiwKrDZdWMpBKJAjVPhgaXVbOEYxMQKu2Guv7eNw)
A golfed version of @Adam's answer which I was advised is different enough to warrant a separate post.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 22 bytes
```
ṪVN³¡%9Ṿṭ“¡ṭ."“¬’ḥịØaƲ
```
[Try it online!](https://tio.run/##y0rNyan8///hzlVhfoc2H1qoavlw576HO9c@aphzaCGQ1lMCsdY8apj5cMfSh7u7D89IPLbpP1AsMAhEOIEIPxABxN4gDBLxBol4AxXMtT68D8i0MDczNTE2MgQKKBzaquD@cGfLw52zQczD7Y@a1gARWPj/fwMA "Jelly – Try It Online") (the footer is a test suite that tests all 64 possibilities from a given player's point of view)
Function submission. Takes the coordinates in descriptive notation as a function argument, and the viewpoint (white=0, black=1) as a command-line argument.
## Explanation
```
ṪVN³¡%9Ṿṭ“¡ṭ."“¬’ḥịØaƲ
Ṫ On the last character of the input,
V convert it to a number,
N negate
¡ a number of times
³ equal to the command-line argument,
%9 wrapping-modulo by 9,
Ṿ convert back to a string,
ṭ and prepend
ḥ {the result of} the randomly generated function
“¡ṭ."“ #29699285
“¬’ with codomain [1..8]
Ṫ Ʋ applied to the input minus its last character, after
ịØa indexing into the lowercase alphabet
```
The probability that a randomly generated function with an 8-element codomain will map the eight column names onto eight different outputs is approximately 1 in 416. As such, it's possible to convert the column names from descriptive to algebraic notation simply by searching through Jelly's catalogue of random functions to find one that's a perfect hash function for the given inputs (i.e. it maps each of them to a different number from 1 to 8), and specify the codomain using an 8-character string that contains the desired output column names in the order with which the function generates them. Function #2423 happens to have the desired behaviour (I simply checked random functions until I found one that worked).
However, doing this requires the column names to be given explicitly. It's golfier to express them by indexing into the alphabet, but this requires finding a function that maps each of the eight column names onto a different number from 1 to 8 *in the correct order*. The odds of any given randomly generated function happening to do this are 1 in 16777216. After searching through tens of millions of randomly generated functions, I discovered that function #29699285 happens to have the desired behaviour.
When an appropriate function for converting column names is available, the only remaining requirement is to remove the row number before running the function, subtract from 9 if necessary, and add it back at the end. (The conditional subtraction from 9 is done by conditionally negating it, and then taking its value modulo 9.)
[Answer]
# Batch Script, 179 Bytes
```
SET t=%2
SET /A a=96,p=%t:~-1%
FOR %%? in (QR QN QB Q K KB KN KR)DO SET /A a+=1,n=9-(((9-p)*(1-%1))+p*%1)&IF %%? == %t:~0,-1% CMD /C EXIT %%a%%&CALL ECHO %%=exitcodeAscii%%%%n%%
```
This is assuming `@ECHO OFF` is enabled. The second arg is the string (ie QR1), and 1st is the side. 0 for white, 1 for black. For example on CMD, if file is named chess.bat
```
CALL chess.bat 0 QR1
```
returns `a1`. I use the built-in variable `=exitcodeAscii` to get the letters from a-h, the rest is just a simple FOR loop.
[Answer]
# [Python](https://www.python.org), 85 bytes
```
lambda t,s:"%c%i"%(101-(q:="Q"in s)+(2*q-1)*~"BNR".find(s[1]),9*t-(2*t-1)*int(s[-1]))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Tc-9CsIwFAXg3acIFwpJTaQRxVro4ioUWnBSh2qNFrQ_Ng4uvohLQfQpfBHfxlsN2inw3cMh5_ooznqXZ_VN-Yv7SSvhvmb7-LBKYqJ55YG1tlKwqHSkoKXnQwhpRirWpX27FJLZF5gEEfRUmiW0mssl42NbC7zq5ppmGlUgM1P-1JtK-_MOIdThEEYSOMQSGDcyjVyUnfuXcICQDFqRYISyHRmRvxr3L6ZGtjKfmmEr8q3pA0NYdlR-bBbznODA5pMecnFsFiiKB8Zzs6Guv-8b)
Takes in the integer 0 if it's white's move, 1 if it's black's move, along with the notation string. Returns a string.
## Explanation
Not much of an explanation, but here's the code separated into a series of steps:
```
def f(t,s):
q=0+("Q"in s)
r="BNR".find(s[1])
u=(2*q-1)*~r
col=100-(q-u)
x=(2*t-1)
row=9*t-x*int(s[-1])
return "%c%i"%(col,row)
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 49 bytes
```
T`d`Rd`b.+
T`QKl,`d-e_
+T`b-gBNR`a-cf-h_BN`.[A-Z]
```
[Try it online!](https://tio.run/##K0otycxL/P8/JCElISglIUlPmyskIdA7RychRTc1nks7JCFJN93JLyghUTc5TTcj3skvQS/aUTcq9v//pJzE5GydwCBDLgjLO8gCygo0gQn5mXOVZ2SWpIKVQVggZVAxE5iQnzkA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`d`Rd`b.+
```
For black, subtract the digit from `9`, i.e. transliterate `0-9` to `9-0`.
```
T`QKl,`d-e_
```
`Q` becomes `d`, `K` becomes `e`, and delete the `white,`/`black,` indicator.
```
+T`b-gBNR`a-cf-h_BN`.[A-Z]
```
For each column away from the centre, update the letter, e.g. `QR` ↦ `dR` ↦ `cN` ↦ `bB` ↦ `a`.
[Answer]
## Batch, 126 bytes
```
@set s=%2
@set/ar=(%1*7^^%s:~-1%-1)+1
@for %%i in (QR.a QN.b QB.c Q.d K.e KB.f KN.g KR.h)do @if %%~ni==%s:~,-1% echo%%~xi%r%
```
Takes a boolean (0/1) and a string as command-line parameters (-2 bytes by abusing the input format to take 0 or 7 as the first parameter). Explanation:
```
@set s=%2
```
Get the second parameter into a variable so that we can slice it.
```
@set/ar=(%1*7^^%s:~-1%-1)+1
```
Calculate the descriptive row from the algebraic row by XORing the 0-indexed row with 0 or 7 as appropriate.
```
@for %%i in (QR.a QN.b QB.c Q.d K.e KB.f KN.g KR.h)do @if %%~ni==%s:~,-1% echo%%~xi%r%
```
Based on my answer to the linked challenge, loop over the pairs of descriptive and algebraic columns and output the algebraic column corresponding to the descriptive column. Note that `echo` ignores most punctuation immediately after the `o` which I use to consume the `.` that's part of the `~x` extension, saving 2 bytes.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Çнθ<…BNR¹Åsk+.•7œΔ&‘•èI9*¹θα«
```
Port of [*@tsh*' JavaScript answer](https://codegolf.stackexchange.com/a/249897/52210)
Inputs in the order `notation,perspective`, where the perspective is `1`/`0` for black/white respectively.
[Try it online](https://tio.run/##AT8AwP9vc2FiaWX//8OH0L3OuDzigKZCTlLCucOFc2srLuKAojfFk86UJuKAmOKAosOoSTkqwrnOuM6xwqv//1E0CjA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6KGV/w@3X9h7bofNo4ZlTn5Bh9Ydbi3O1tZ71LDI/Ojkc1PUHjXMALIPr4iw1Dq07tyOcxsPrf6v8z86WikwyFBJxyBWJ1rJO8gCygo0gQn5mcOEQMoM4coMYcoM4coMY2MB).
**Explanation:**
```
Ç # Convert the (implicit) first input-string to a list of codepoint-integers
н # Leave just the first codepoint-integer
θ # Leave just its last digit
< # Decrease it by 1:
# 0 if 'Q' and 4 if 'K'
…BNR # Push string "BNR"
¹ # Push the first input-string again
Ås # Pop and leave just its middle character
# (if the input contains just two characters, those will be the 'middle')
k # Get the index of this middle in the string (or -1 if not found):
# 0 if 'B'; 1 if 'N'; 2 if 'R'; -1 if 'Q#'/'K#'
+ # Add the two integers together
.•7œΔ&‘• # Push compressed string "cbaefghd"
è # Index the earlier integer into this string
# (0-based modular, so the -1 indexes into the trailing "d")
I # Push the second input-digit
9* # Multiply it by 9
¹ # Push the first input-string yet again
θ # Pop and leave its last character (the digit)
α # Get the absolute difference of it with the (9*perspective)
« # Append this digit to the earlier character
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•7œΔ&‘•` is `"cbaefghd"`.
[Answer]
# Python 3.10, 82 bytes
```
lambda b,s:C[C.find(s[:-1])-1]+str(abs(9*b-int(s[-1])))
C="dQeKaQRbQNcQBfKBgKNhKR"
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jY-xasMwFEXn6CseXiI1cqi3xODFhiwCg0y2tINUS4mooxhJGfItWQyl-ad-SddadboV2uFx4Z3Hvfddb_0lHE52eNPF0_s56HT10XTiKFsBkvq82lVLbWyL_S5Ps2cyzsIHh4X0eP0gU2PDiCIhBFVF0nLFBG8kr194qVm5Z_WBNcnd-VObTnkoIOEN8Bp4CRwYsBJYDePZ0vedCZggpE8OnLCvYGzUvcIr-kjTjORoFlk0iuzbcNzNeheraLwRnVd04guIVaMNIRSUbYs5zAm63xL0o7-kZXT9Z9TWnf-ZNL0_DJN-AQ)
Testing out dictionary interleaving idea which is a little shorter than converting to ascii codes with `chr`. "Q" and "K" have to come first, otherwise they will match for at "QR".
-4 bytes using `find` instead of `index` and a better rank calculation for white/black.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes
```
§β⌕⪪”&↓↶G«ü\`~6ε⪪θ⊞↷” …η⊖LηI⎇N⁻⁹ΣηΣη
```
[Try it online!](https://tio.run/##PY29DoIwFEZ3nuKG6ZLUwcHBOAnGhFSJBV@AnxvbpFxIKUaevqImnulbzndaXbt2qG0IN2fY49Hn3NELGwFnwx1WozUeY1WCKkCloECCTEEWIMtYQAxxIiBbWkuZHkbUAk7UOuqJPXV4IX54jTr5coh@jayePN7Jce0WzHmcfTH3DTlcr66G5wn3Aqq5/3j/seohbCNZ7sLmad8 "Charcoal – Try It Online") Link is to verbose version of code. Takes the White/Black flag as a boolean. Explanation:
```
§β⌕⪪”&↓↶G«ü\`~6ε⪪θ⊞↷” …η⊖Lη
```
Look up the column in a compressed table and output the lowercase letter with that index.
```
I⎇N⁻⁹ΣηΣη
```
Subtract the row from `9` if the player is Black.
] |
[Question]
[
## Challenge
Given a list of bases for [positional numeral systems](https://en.wikipedia.org/wiki/Numeral_system#Positional_systems_in_detail) as input, output the lowest positive integer that when represented in those bases they have no common digits. The input list can be assumed to have two or more unique positive integers >= 2.
## Example
For the input list of bases 2, 8, 10, 16 (binary, octal,
decimal and hexadecimal) the lowest number is 58 (a printed result
should be in decimal) since 58 is *111010*, *72*, *58* and *3A* which, as you can see, have no common digits between them. And no positive integer less than 58 have that property. Whereas 57 is *111001*, *71*, *57* and *39* for the same bases and here the digit 1 appears in more than one base, in base 2 and base 8, so 57 cannot be the result for 2,8,10,16. (Also digit 7 appears in two of them).
## Tests
```
2 8 10 16 → 58
2 8 10 → 27
2 8 16 → 43
16 17 18 → 160
16 17 18 19 → 224
16 17 18 19 21 → 225
34 35 36 → 646
4 44 444 4444 → 512
3 33 333 3333 4444 → 16702
555 777 999 → 1665
111 222 333 → 555
```
Some valid inputs have no solution, as pointed out by @Nitrodon, or none that can be found within reasonable time (one minute at TIO/Try It Online). I'll leave it up to each contributor to chose *if* or *how* they want to handle such inputs.
[Answer]
# [R](https://www.r-project.org/), 96 bytes
Or **[R](https://www.r-project.org/)>=4.1, 82 bytes** by replacing two `function` occurrences with `\`s.
```
function(b){while(any(table(unlist(Map(function(y)unique(T%/%y^(0:log(T,y))%%y),b)))>1))T=T+1
T}
```
[Try it online!](https://tio.run/##jdFNaoQwFAfw/ZziYRESKq0vn1qY3qA71wUtOg1IZqqRIqXbHqBH7EWsOmUW1slMSCCL/P4veWmGajtUnX1xZm9JQT/eX01dktz2xOXFuOtsbVpHnvIDOR3raWfNW1eSLLwP@2cSP9T7HcmintIw7GlUUEofkdJsm93iJvscKpK3d8a6clc2pKxJ65r2UBtHAgYJYAyogiiAYHT0Bk7j5@sbZLK5pNfon2b6klYeLbhHowLUgMmqnzSq@AoOmP5PmK/OxHUcGC4Sjlx6OBfAJXB19vJKKA8XIKY5L7HMmH8Nma868GnOiy8zjq3TsS9ASglaa0jTM81DpXzPR8SxQWyqv@7HAsMv "R – Try It Online")
Similar approach to [@Giuseppe's](https://codegolf.stackexchange.com/a/240954/55372), but independently developed (and shorter).
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 10 bytes
```
f{Is{MjLTQ
```
[Test suite](http://pythtemp.herokuapp.com/?code=f%7BIs%7BMjLTQ&test_suite=1&test_suite_input=2%2C8%2C10%2C16%0A2%2C8%2C10%0A2%2C8%2C16%0A16%2C17%2C18%0A16%2C17%2C18%2C19%0A16%2C17%2C18%2C19%2C21%0A34%2C35%2C36%0A4%2C44%2C444%2C4444%0A3%2C33%2C333%2C3333%2C4444%0A555%2C777%2C999%0A111%2C222%2C333&debug=0)
##### Explanation:
```
f{Is{MjLTQ | Full code
-----------+-----------------------------------------------------------------------
f | Find the first integer T (starting with 1) such that
jLTQ | the list of T converted to each base in the input as a list of digits
{M | with each sublist deduplicated
s | flattened
{I | is invariant over deduplication
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~12~~ 11 bytes
```
ḟȯS=uṁuMB⁰N
```
[Try it online!](https://tio.run/##yygtzv7//@GO@SfWB9uWPtzZWOrr9Khxg9////@jjXQsdAwNdAzNYgE "Husk – Try It Online")
```
ḟ N # get ḟirst Natural number that satisfies:
M ⁰ # Map over the input:
B # get lists of digits in these Bases;
ṁ # now ṁap over each list & flatten result:
u # get unique digits;
S= # is this list equal to
u # the unique elements of itSelf?
```
(Or alternative [11 byte](https://tio.run/##yygtzv7/PyzYtjT34c7G0oc7VyU4@f3//z/aSMdCx9BAx9AsFgA) program: `VS=umṁuṪ`BN`:)
```
Ṫ` # make a Ṫable of:
B # the digits in the bases of the input
N # for each of the infinite list of Natural numbers;
m # now map over each list of lists of digits
ṁ # and ṁap over each list of digits, flattening the result,
u # getting just the unique digits;
V # finally, return the index of the first list that satisfies:
S= # it's equal to
u # the unique elements of itself?
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
1bQ€FQƑʋ1#
```
[Try it online!](https://tio.run/##ZdAxDsIwDADA3a@wxAdqJ06aD7B3QWJFYkH9ACsDHZjgC6xMiKGIjUod@EX7kZC2CNJi2VKUU2wrm3Web72nVdbuLvOsPr4ONPNNeSbXlNfnvS4WAaoCmsetKsJx6T1jipQgGfxGuz@hpPCRODphO4j5E60g3JJFSidCJvkRuVE71iNiikhAaVSCykwaGm1Ao@6yLx1tTgwKVZd9qcGHNWzCICJorUXn3HhHI0BEYSz3b@PfEHkD "Jelly – Try It Online")
## How it works
```
1bQ€FQƑʋ1# - Main link. Takes a list of integers L on the left
ʋ - Group the previous 4 links into a dyad f(k, L):
b - Convert k into each base in L
Q€ - For each list of digits, remove duplicates
F - Flatten
QƑ - Are all elements in this list unique?
1 1# - Count up from n = 1, 2, ... until the first n is found such that f(n, L) is truthy
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 54 bytes
```
->a{(1..).find{|i|!a.flat_map{i.digits(_1)|[]}.uniq!}}
```
[Try it online!](https://tio.run/##DcNLCoAgEADQq4y7AhuqRdSiLiISShgDJfZbhOPZrQfvfOyb3ZirycSiQRx@JTryS2RiYdBt5p53EyJbJlxopfsqbMlKJ3w8HSKlHMApUK2EXkJT/zsNOn8 "Ruby – Try It Online")
(with modifications to work on older versions)
[Answer]
# [R](https://www.r-project.org/), 105 bytes
```
function(b){while(anyDuplicated(unlist(lapply(b,function(B,x)unique(x%/%B^(0:log(x,B))%%B),F<-F+1))))0
F}
```
[Try it online!](https://tio.run/##PcrBCgIhEADQe1@xF2GGZkk7RMSeJPyMwDUtYXDdWskl@nbr1Du/Rwvd0HctlOSWOCUY8f26R/Zg03oumaOzi79CSRyfC7DNmVcY6f81VSwpzsVDFTuhLyBPPN2gkkYUQiOZoTdbhT9yYz4tgIM9HUlJUgfE9gU "R – Try It Online")
~~Ugly and appears altogether too long.~~ Outgolfed by [pajonk](https://codegolf.stackexchange.com/a/240960/67312).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
≔²ηW⊙Eθ↨ηκ⊙θ∧⁻λν⁻κ⁻κ↨ημ≦⊕ηIη
```
[Try it online!](https://tio.run/##TU5NC8IwDL37K3JMIIJ6EGGn6cnDwPvYoXTFlnXRtVPx19eOKhgI7wNeXrRVQd@UT6mO0V0FdwyWqtXLOm8Aa3ljo@44MRxVNGgZBiKGxZ8W6LFx8ojoGST7RQx/5BcbqQzkc9@qs@hgRiOz6UvpJTiZ8aTijJaoSqlt8zsHhu0m777r0vrpPw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔²η
```
Start searching at `2` since `1` will have the same digit in all bases.
```
W⊙Eθ↨ηκ⊙θ∧⁻λν⁻κ⁻κ↨ημ
```
Convert the search value to all bases, then perform set intersection between all of the sets, and repeat until they are all empty (except for self-intersection of course). (Strictly speaking each set intersection repeats one of the base conversions but that's code golf for you.)
```
≦⊕η
```
Increment the search value.
```
Iη
```
Output the final search value.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 86 bytes
Expects a list of BigInts.
```
f=(a,n=2n)=>a.some(c=>a.some(b=>c-b&&(g=k=>k&&1n<<k%b|g(k/b))(n)&g(n,b=c)))?f(a,-~n):n
```
[Try it online!](https://tio.run/##hdDNTsMwDAfwO0@xC1Eipeucr7ZoKQ@COLSlrUaHM62IE@LVi7ehomYaRHKSw8/WX36tPqqxOe4O7wmGl3aaOs8riV6h8GW1HsNby5v5V/uySWrGeO8HXw6MAW63w3392fMhrYXgKFjPUda@EUI8djQq@ULxgFMTcAz7dr0PPe/4k0KZo4QNlcNnIVaXk6Yrm9/dsr/ux6rshnXX1ujYkpKQUeULTRbc5g8soZgbTiGU@QdLBeeGM7Yx1galtlQujuGMizFZYy4XPbM/7Q1UjK2lsVlGQYqiWGBw7ioHAFBSRRvUWi9HWzt9Aw "JavaScript (Node.js) – Try It Online")
## How?
The helper function \$g\$ is used to build a bitmask of all digits appearing in the representation of \$k\$ in base \$b\$ :
```
g = k => k && 1n << k % b | g(k / b)
```
The main function \$f\$ recursively looks for the smallest \$n\ge2\$ for which there's no pair \$(b,c)\$ from the input array such that \$b\neq c\$ and the bitmaks generated by \$g(n)\$ in base \$b\$ and \$c\$ have at least one bit in common.
```
f = (a, n = 2n) =>
a.some(c =>
a.some(b =>
c - b &&
g(n) & g(n, b = c)
)
) ?
f(a, -~n)
:
n
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 25 bytes
```
{bcqdgZ])NB\[U_}j1iar1jfe
```
[Try it online!](https://tio.run/##TYzLCsIwFET3@YrZuvPm5tFs/YDu3FiLWI1iqdIHWZV@e2oaEGGGOczANGHs/DQEH7vP3E9xbm7D/Xmqd@XhXB0vS0uv60jtw8fQL@8qlFGiAO1BRmTKYQQZkAUVPwC5f4YkwQqswUYoqKTNSjA4aTPnSmsNay2c@54QQUqZ1hU "Burlesque – Try It Online")
```
{
bc # Box and cycle infinitely
qdg # boxed Digits
Z] # Zip and evaluate (get list of digits of N in bases Input)
)NB # Map Nub (remove duplicates within each set of digits)
\[ # Concatenate all digits
U_ # Digits are unique
}
j # Reorder stack
1ia # Insert bases at position 1 (as the second argument of zip)
r1 # Range [1..inf)
j # Reorder stack
fe # Find the first element (in infinite range) which fulfils requirements
```
A shorter variant would be where `bcqdgZ]` is simply replaced with the convert base function `B!`
# [Burlesque](https://github.com/FMNSSun/Burlesque), 19 bytes
```
{B!)NB\[U_}j+]r1jfe
```
[Try it online!](https://tio.run/##SyotykktLixN/Z@TV11Q/L/aSVHTzykmOjS@Nks7tsgwKy31f2lBbW50qd9/IwULBUMDBUMzLggLQplxGZopGJorGFrAGQqGlshsBSNDLmMTBWNTBWMzAA "Burlesque – Try It Online")
Unfortunately, this fails for larger bases due to limitations on rendering the digits as strings
[Answer]
# [Julia 1.0](http://julialang.org/), 67 bytes
```
x\b=digits(x;base=b)
<(l,x=1)=((a=x.\l).∩a'.>[[]])l>l ? l<x+1 : x
```
[Try it online!](https://tio.run/##ZY9dToQwFIXfu4qbebFEQrj9A3TAZ9cwMzEloKlpkAAmXYHx2V24rdkIFpgojDdt05zv3tPT13drNLpxdMcyr8yLGXrq7kvd13kZkD21ocsxyCnVuYuONojOn9/6JioOh9MpsIWFB7B7d4twB258fuvAmqYG00BX62q69zQg4EuHT5BD31oz0EkPYXf@@Not0HrU6q6vI/rYDOGlTQcLbTvTDLahvqsAH8nLdVONDFLAGFDBb3lHkCm5kHVNhCULUf@I4MSrmACmVwRV/Icw29gxsUEMV0gSLoBL4OrKUAlFBIhpzVuskiMjUkpIkgSyLNvGUJIgondmwDnffFj6x7w463w6ZttlLInZDw "Julia 1.0 – Try It Online")
#### Explanation:
* `digits` gives the digits of a number in a certain base, eg `digits(9,base=8) == [1,1]`
* we rename `digits` to `\` to allow broadcasting over the base: `10 .\ [3,4] == [[1,0,1], [2,2]]`
* `a .∩ a'` is the `intersect` function: every list of digits is compared to all the others, the output is a matrix of lists
* `(...) .> [[]]` checks which elements of the matrix are empty, the output is a bitmatrix, where `0` means the list is empty (no common digits). The diagonal will always have `1`s
* `(...)*l > l` will be true is there is any `1` outside of the diagonal
* `l<x+1` iterates recursively to the next number
[Answer]
**Apl 37 bytes**
```
a←⎕
1∘+⍣{{⍬≡∊⍵/⍨⍤1≠/¨⍳⍴⍵}∘.∩⍨⍺⊥⍣¯1⍨¨a}0
```
`1∘+⍣{...}0` adds 1 until the function returns true
`⍺⊥⍣¯1⍨¨a` converts ⍺ to bases of a(input array)
`∘.∩⍨` returns a matrix checking if numbers present in one base are present in another base
`⍵/⍨⍤1≠/¨⍳⍴⍵` removes the diagonal (as it is compared to itself)
`⍬≡∊` checks if every argument is empty
[Answer]
# [Ruby](https://www.ruby-lang.org/), 80 bytes
```
f=->l,n=1{a=l.map(&g=->b,x=n{x<1?[]:[x%b]|g[b,x/b]}).flatten
a|a==a ?n:f[l,n+1]}
```
[Try it online!](https://tio.run/##ZZHhToMwEMe/9ykuJJotIu5KC2Ox7kGQmGJgkiAS1iWYla8@gI/oi2BLnbLZXJPr/3f993LtDvn7OJbi9qH2G4FHKergVbaL652Rcr8XzbG/x22abdL@Ks/0LjXiXZ4Ny6CspVJFQ6SWQkjYNpsyNSY3mA2jKvZKeBTWgCvACH7X18cn8DX5IfNlCY0dif4RFhKjYgy4viAYrf4QJmd2lJ0hijPEScgg5BBGF4YRiwgDZmPabNY5UhJCaGPaoeOujXhFCecc4jiGJEnOe4w4QUTzLJ3uzqfBuRfs27pSC@@x8ZZ2/Edd6/okmiJvOTi5atqD8rtir9MpPdXA6V6v@0C9PVWDLZqybCD2N4JCPr/MDA610gRamASbdKJ0npk7CVdkDl3VKLC9kWH8Bg "Ruby – Try It Online")
```
f=->l,n=1{..} recursive lambda taking a list and trying next number until a solution is found
a=l.map map bases to:
&g=->b,x=n{ recursive base digits(as array of integer numbers)
..%b]|g[b.. we use | to add only new digits
.flatten finally we flatten to get all digits found
a|a==a if by removing duplicates the array doesn't change we return the number
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞.Δsв€Ù˜DÙQ
```
[Try it online](https://tio.run/##ASkA1v9vc2FiaWX//@KIni7OlEnQsuKCrMOZy5xEw5lR//9bMiw4LDEwLDE2XQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeWilvZLCo7ZJCkr2/x91zNM7N@XQugubHjWtOTzz9ByXwzMD/9fq/I@ONtKx0DE00DE0i9WBsmEMkIihmY6huY6hBRJTx9BSx8gQKGBsomNsqmMMUmaiYwJCYGwCktIxBiEwNoYJmpqa6pibm@tYWlqCjDM01DEyMgKpiI0FAA).
**Explanation:**
```
∞.Δ # Find the first positive integer which is truthy for:
Iв # Convert it to each of the input-bases as list of lists
€Ù # Uniquify each inner list
˜ # Flatten it
DÙQ # Check if all values are unique:
D # Duplicate the list
Ù # Uniquify the copy
Q # Check if the two lists are still the same
# (after which the result is output implicitly)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 139 bytes
```
def e(n,b):
while n:
yield n%b;n//=b
def f(a):
n=1
while 1:
if all(sum(q in e(n,b)for b in a)<2 for q in range(n+1)):return n
n+=1
```
[Try it online!](https://tio.run/##dY/RioMwEEXf/Yp5WTBUqBOTqO3mYyKNW8FOd9VS@vXuqBEC3X24wXBO7ozfr@l6p2KeL74Fn1LWiFMCz2vXeyD@glfn@wvQR3Om49E2yeK1qVsssriruKhdC67v0/FxS3@go1DX3gdolqsTnxKW2woHR18sHFCI0@Cnx0BA3EEHi7MbRz9MPCaVGVQZYM4xQoC1oKvkHW9Ilu8ovFJFhNAwKDnVBtHkf1JOHZql@tfIQOJu6cgqVAaF5oQVjDIRZajWbIcKP4cybuDHa7ajiE00ZR67WvOosuSt6rreFRPvg4i8qpRrVxin9fwL "Python 3 – Try It Online")
It's annoying for it not to be a single expression, but those seemed to end up longer.
] |
[Question]
[
An [addition-subtraction chain](https://en.wikipedia.org/wiki/Addition-subtraction_chain), is a sequence \$a\_1, a\_2, a\_3, ... ,a\_n\$, such that \$a\_1=1\$ and for all \$i > 1\$, there exist \$j,k<i\$ such that \$a\_i = a\_j \pm a\_k\$.
Your task, is given a number \$x\$, find the shortest addition-subtraction chain, such that \$a\_n = x\$.
## Rules
* You can assume the input is a valid integer
* In case there are multiple optimal addition-subtraction chains, you can print any non-empty subset of them
* You may use [any reasonable I/O method](https://codegolf.meta.stackexchange.com/q/2447) (you can output it reversed, with any separator you want, in any base you want, ect.)
## Test cases
(these are one solution, you can output anything valid with the same length)
these are all the numbers with a addition subtraction chain of length 6 or less
```
-31 -> [1, 2, 4, 8, 16, -15, -31]
-30 -> [1, 2, 4, 8, 16, -15, -30]
-28 -> [1, 2, 4, 8, -6, -14, -28]
-24 -> [1, 2, 4, -2, -6, -12, -24]
-23 -> [1, 2, 4, 8, 12, 24, -23]
-22 -> [1, 2, 4, 6, -5, -11, -22]
-21 -> [1, 2, 3, 6, 12, -9, -21]
-20 -> [1, 2, 4, 6, -5, -10, -20]
-19 -> [1, 2, 4, 8, -3, -11, -19]
-18 -> [1, 2, 4, -1, 8, -9, -18]
-17 -> [1, 2, 4, -3, 7, -10, -17]
-16 -> [1, 2, 3, -1, -4, -8, -16]
-15 -> [1, 2, 4, 8, 16, -15]
-14 -> [1, 2, 4, 8, -7, -14]
-13 -> [1, 2, 4, 6, -3, -7, -13]
-12 -> [1, 2, 4, -3, -6, -12]
-11 -> [1, 2, 4, 6, -5, -11]
-10 -> [1, 2, 4, -2, -6, -10]
-9 -> [1, 2, 4, 8, -1, -9]
-8 -> [1, 2, 4, 8, 0, -8]
-7 -> [1, 2, 4, -3, -7]
-6 -> [1, 2, 4, 8, -6]
-5 -> [1, 2, 4, -3, -5]
-4 -> [1, 2, 4, 8, -4]
-3 -> [1, 2, -1, -3]
-2 -> [1, 2, 4, -2]
-1 -> [1, 0, -1]
0 -> [1, 0]
1 -> [1]
2 -> [1, 2]
3 -> [1, 2, 3]
4 -> [1, 2, 4]
5 -> [1, 2, 4, 5]
6 -> [1, 2, 4, 6]
7 -> [1, 2, 4, -3, 7]
8 -> [1, 2, 4, 8]
9 -> [1, 2, 3, 6, 9]
10 -> [1, 2, 4, 5, 10]
11 -> [1, 2, 4, 6, 5, 11]
12 -> [1, 2, 4, 6, 12]
13 -> [1, 2, 3, 5, 10, 13]
14 -> [1, 2, 4, 6, 10, 14]
15 -> [1, 2, 3, 6, 9, 15]
16 -> [1, 2, 4, 8, 16]
17 -> [1, 2, 4, 8, 9, 17]
18 -> [1, 2, 4, 8, 9, 18]
19 -> [1, 2, 4, 8, 9, 17, 19]
20 -> [1, 2, 4, 5, 10, 20]
21 -> [1, 2, 4, 8, 16, 5, 21]
22 -> [1, 2, 4, 8, 12, 24, 22]
23 -> [1, 2, 4, 8, 16, -15, 23]
24 -> [1, 2, 3, 6, 12, 24]
25 -> [1, 2, 4, 8, 12, 13, 25]
26 -> [1, 2, 4, 6, 10, 16, 26]
27 -> [1, 2, 4, 5, 9, 18, 27]
28 -> [1, 2, 4, 8, 12, 14, 28]
30 -> [1, 2, 4, 5, 10, 20, 30]
31 -> [1, 2, 4, 8, 16, -15, 31]
32 -> [1, 2, 4, 8, 16, 32]
33 -> [1, 2, 4, 8, 16, 32, 33]
34 -> [1, 2, 4, 8, 16, 17, 34]
36 -> [1, 2, 3, 6, 9, 18, 36]
40 -> [1, 2, 4, 8, 12, 20, 40]
48 -> [1, 2, 4, 8, 12, 24, 48]
64 -> [1, 2, 4, 8, 16, 32, 64]
```
you can find a list of all optimal addition subtraction chains for each of them [here](https://pastebin.com/aF3CKEp0)
This is code golf, so the shortest answer in bytes in each language wins.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~19~~ 17 bytes
```
∧≜;1⟨∋{+|-}∋⟩ᵃ⁽?t
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qHNOdbmSgq6dglK5fd2jtg2PmpqCgAIaOal56SUZVkDhoJxyJU2lh7s6FWsfdS39/6hjOVCTteGj@SsedXRXa9fo1gLpR/NXPtza/Khxr33J//8A "Brachylog – Try It Online")
I guess I shouldn't be too surprised, but funnily enough this produces the exact same outputs as xash's solution--up to \$n = 13\$ after which both time out. Takes input through the output variable and outputs through the input variable.
```
1 Starting with 1,
ᵃ repeat on the list of previous results
∧≜; ⁽ as few times as necessary:
+ add
{ |-} or subtract
⟨∋ ∋⟩ one element and another (not necessarily distinct),
? such that the final list of results is the input variable
t and its last element is the output variable.
```
[Answer]
# JavaScript (ES6), 104 bytes
A very basic and quite long implementation. But it does solve all test cases in ~20 seconds on TIO.
```
f=(n,l)=>(g=([...a],x)=>a.push(x)<l?a.some(x=>a.some(y=>g(a,x+y)||g(a,x-y))):r=x==n&&a)([],1)?r:f(n,-~l)
```
[Try it online!](https://tio.run/##fVRBcpswFN1zCk0WQaqRgiSM7aTYq/YCWdpMh3Gw4w6BFJyOPU17gs5002V7j54nF@gR3P8V3BgQWYCF/tPXe@9//4/J56Ralpv7Lc@Lm/RwWEU09zIWTek6onMhRBJ7O/hMxP1DdUt37G02S0RV3KV0h7tmtY@ma5p4u8GePT6aFd8zxi7LaBdF@fl5wug89iSblZcrSM@/ZexQpp8eNmVK3VXlMlGmyc37TZZe7/Ml9ZnYFtfbcpOvKRPVfbbZ0rNFfsbEqijfJctbWpFoSr44hMzJB4/kHqmKjMQkIpW4S7YAuKB8trgZMMKnZDGn4g1bxBfsiuSAGeRXBh/hu07vesRlV5BwWeSwm4qsWANTUqZwFQHSzKxFlubr7S2Jns/WXzPi/v3z4@nXT3i75JK4T7@/Y7av7MC1RApz6RHlkcAjY4/I0CNcDuGlZexw7b@G8AGhxh0ENwhYQxARQRPB1RGCCxUgRHevgZUyaI0A1QTgcaQgJSIUIk61aIMw@ScIQCnK70nhIwKlyElXij5eIieIaInl8hmFl0jUKkctAJwfHS@RI0SETZ6YgiMS88gQEcM@zzEYdDmaC9BGqbsS9RGANkrVpVeXAqOyz2QM@n1VROsszqEu9KzbH@gFmmXxiqNFoaWjYHtogaMlFkfQjFMvDBnTR20RqOy4Z2oUO/@FgrA6FjsvB2PnNDMkbdwfOy2awLClB7TYuiR22k7FzqTT0@BouxJQIqyBpXoYAe6y@@fBeje6Rdd54AFJ7S4L6xDIa3RnzQkiIFOGlr6F7VFnGw@AXjm2RkC35Z9ozsADBiibAfABJij7RAMEzoD2FDkZMzhDbFPoOOxwCjUG2cuIwQmmhtbMElAKrFGh3U/4VWCRGnUEGSPgG2yyTFiTG1mDV7rPDeAIjrw243HEa2WNa@xz3ROCB@zQgTWMVdJgiQ6tjQIoDZID314KYB0A62DcW6kANIdBL7MwiP8B "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~88~~ 87 bytes
-1 byte thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!
```
f=lambda n,x=[1],*a:x*(n in x)or f(n,*a,*[x+[a+c]for a in x for b in x for c in(b,-b)])
```
[Try it online!](https://tio.run/##RYzLCoMwEEX3fsXsTOJYfNRSBPsj4iI@QgMaJaYQEb/djt10cYdzz4VZNveeTX7qaZmtg3VbA8ptHZwduo9d9WxGPWnH0kSIgp@qGuXU9hIM@qpOGxSy9IIZ0AY8ny0oZsihqH1Uy6hrFDn5W@HC9o8dIWsxbnlDf0n4a4tzhDijpAgJAl0q5O4IBcID4VkGAIvVxjEV7r7M@gPiF@yKeX6E/PwC "Python 3 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 59 bytes
```
head.(`filter`a).elem
a=[1]:do h<-a;i<-h;j<-h;[i-j:h,i+j:h]
```
[Try it online!](https://tio.run/##bY9NboMwEIX3PsUsIgVUmwZCQgWYfaVKPQC1FBMMdmoMAp@/1FRpm7@FR57Pz@/NSD59Cq3nhn7MUvA68A6N0laMB@4HQosOcVqGLK17kDnhmcqJzE5LKRU5pRKrJ1fZ3HFlaN0j8BTu/Zw0HR/AcqWDaeDGe6brYu3nq6IV9k0ZgUALC4aOLnKljLKgMv7TQZ@m5auxLKtoAwbBMCpjPS1MayVUlJ5vHBtc@QiW4JkkQAooQwwRhhgD2bqTMET21/zF4b3DuwfynePxvTx2eHuBSbjoHYxuPCLHwl@2WYQMbf56hs5vDP1/ZOjS2Zle5TN0M6ab8GYft8uDzRP2dWw0b6eZHIdhJu/RNw "Haskell – Try It Online")
`a` is the infinite list of all the addition-subtraction chains, sorted by length. The function `head.(`filter`a).elem` takes an integer (say `n`) and returns the first chain in `a` which contains `n`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~18~~ 17 bytes
```
`ḟ¡SṀ:S×+S+m_;;1€
```
[Try it online!](https://tio.run/##ATAAz/9odXNr/yBt4oKB4oCm/2DhuJ/CoVPhuYA6U8OXK1MrbV87OzHigqz///8tMTL/MTM "Husk – Try It Online")
*-1 thanks to Leo*
The longer I look at this, the less I have any idea why it seems to work. Probably something to do with the `iterL` overload that I didn't even know existed. I need coffee
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
1+;_ɗþ`FQ;€Ʋ€Ẏ$Fċ³¬Ɗ¿ċƇ
```
[Try it online!](https://tio.run/##y0rNyan8/99Q2zr@5PTD@xLcAq0fNa05tglIPNzVp@J2pPvQ5kNrjnUd2n@k@1j7////dY0NAQ "Jelly – Try It Online")
A full program taking a single argument and returning a list of all optimal addition subtraction chains, each in reverse order.
## Explanation
```
1 | Start with 1
Ɗ¿ | While the following is true:
F | - Flatten list
ċ³ | - Count the number of occurrences of the input
¬ | - Not (i.e. = 0)
$ | Do the following:
Ʋ€ | - For each member of the list, do the following:
ɗþ` | - Do the following as a dyad mapping over the sublist for both left and right arguments
+ | - Add
; | - Concatenated to:
_ | - Subtract
F | - Flatten
Q | - Uniquify
;€ | - Concatenate each value to the original sublist
Ẏ | - Join lists together
ċƇ | Finally, keep only those list where the input appears
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 31 bytes
```
1g|g;Lc,1↔a₀ᵇb{kgj∋ᵐ{+|-}~t?}ᵐt
```
[Try it online!](https://tio.run/##AVYAqf9icmFjaHlsb2cy/3t3IiAtPiAidybihrDigoLhtqDCuWPhuoniiqV9/zFnfGc7TGMsMeKGlGHigoDhtYdie2tnauKIi@G1kHsrfC19fnQ/feG1kHT//w "Brachylog – Try It Online")
### How it works
`?` is the input of the current scope.
```
1g|g;Lc,1↔a₀ᵇb{kgj∋ᵐ{+|-}~t?}ᵐt
1g if ? is 1, return [1].
| else
g;L [[?], L]
c [?, L0, L1, …] (try shorter lists first)
,1↔ [1, L0, L1, …, ?]
{ }ᵐ map every
a₀ᵇb prefix except the first ([1]):
f.e. [1, L0, L1]
k [1, L0]
gj [[1, L0], [1, L0]]
∋ᵐ select any element of each list, f.e.
[L0, 1]
{+|-} try L0 + 1 and L0 - 1
~t? is equal to L1
t return the last prefix (which is the list)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes
```
Nθ⊞υ⟦¹⟧FυF¬⊙υ№κθFιF⁻⁺⁺ιλ⁻ιλι⊞υ⁺ι⟦μ⟧I⊟Φυ№ιθ
```
[Try it online!](https://tio.run/##PU67CsMwDNz7FR4lcAfPmUqg0KEhe8jghpaIOnZiW4V@ves8XA06Tifpbhi1H5w2Kd3szLHh6fH0sGB1ajmMwFJ0qs/s5bwARrFh4yJc7HdVa8c2wluKBXPtMh14J8sBWlMaSWFQin28kcwoXxWrstVNPa4JPOXftQ4RWjfDlUzM2f6mdJhilZJS6fwxPw "Charcoal – Try It Online") Link is to verbose version of code. Very¹ slow, so only try it with single-digit integers. Explanation:
```
Nθ
```
Input `x`.
```
⊞υ⟦¹⟧
```
Start a breadth-first search with the trivial chain of length 1.
```
FυF¬⊙υ№κθ
```
Loop over the search results until a chain is found that includes `x`.
```
FιF⁻⁺⁺ιλ⁻ιλι
```
Loop over all the sums and differences that aren't already in the chain.
```
⊞υ⁺ι⟦μ⟧
```
Push a new chain to the search list.
```
I⊟Φυ№ιθ
```
Print a chain that includes `x`.
¹Struggles to complete solutions requiring chains of length 6. At a cost of 6 bytes it's possible to speed it up by avoiding pushing duplicate chains to the search list but that's still only enough for it to find all chains of length 6.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 77 bytes
```
->n,*r{*a=1;(a.product(a){|x,y|r|=[a|[x+y],a|[x-y]]};a,*r=r)until a[-1]==n;a}
```
[Try it online!](https://tio.run/##FcuxCoAgEADQX2kKLRUcmuT6EXG4CiEokyMhyb7danrTozTl6qHKMYiO7g5BG4Yq0rGk@WTI73KJXKiAxWKvPjvxK7Nzj8GvAPEUznVr0ErtAILBp8aGyUGpgasdI2s9ry8 "Ruby – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes
```
X¸¸[ćD©Iå#ãDOsÆ«ε®sª}«
```
[Try it online!](https://tio.run/##ATgAx/9vc2FiaWX//1jCuMK4W8SHRMKpScOlI8OjRE9zw4bCq861wq5zwqp9wqv//y0z/y0tbm8tbGF6eQ "05AB1E – Try It Online")
Very slow, the performance can be improved a bit by adding three bytes:
```
X¸¸[ćD©Iå#ãDOsÆ«®KÙε®sª}«
```
[Try it online!](https://tio.run/##AT4Awf9vc2FiaWX//1jCuMK4W8SHRMKpScOlI8OjRE9zw4bCq8KuS8OZzrXCrnPCqn3Cq///LTEx/y0tbm8tbGF6eQ "05AB1E – Try It Online")
] |
[Question]
[
The skip-pure numbers are defined with this rule:
```
A(0) = 1
A(1) = 1
A(n) = the smallest positive number not in the sequence such that A(x) + A(x-2) for any x never appears
```
For example, the term A(2) is 2, because 1 has already appeared. The term A(3) is 4, as A(2) + A(0) = 3 and 3 is disallowed by the third line of the rule.
Given a number n, your program should output the nth skip-pure number, using zero-based indexing (such that A(0) is defined).
Output can be in any format (strings, ints, lists, arrays, etc.), but the number itself must be outputted in base 10.
Trailing output (newlines, etc.) is allowed but only if your language has to output it. If you can work around trailing output, solve it with the workaround.
Here are test cases, shown in the format `input = output`:
```
0 = 1
1 = 1
2 = 2
3 = 4
4 = 6
5 = 7
6 = 9
7 = 10
8 = 12
9 = 13
```
I created this sequence myself and am probably the first person to talk about it, so there is no OEIS link.
This is a code-golf, so the shortest program that does all of the above (measured in bytes) wins. Have fun.
[Answer]
# JavaScript (ES7), ~~59~~ 31 bytes
Returns the \$n\$-th term, 0-indexed. This is a closed-form formula.
```
n=>n*1.5^Math.log2(n)&n%4==2^!n
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i5Py1DPNM43sSRDLyc/3UgjT1MtT9XE1tYoTjHvf1p@kUaegq2CgbVCnoKNgqEBiKGtramQnJ9XnJ@TCtKikZCooVKdV6sJVKdSnQY0oDZB8z8A "JavaScript (Node.js) – Try It Online")
### Formula
The only edge case is \$a(0)=1\$. For \$n\ge1\$:
$$a(n)=\cases{\left\lfloor\dfrac{3n}{2}\right\rfloor-1,&\text{if $\lfloor log\_2(n)\rfloor$ is odd and $n\equiv 2\pmod 4$} \\
\left\lfloor\dfrac{3n}{2}\right\rfloor,&\text{otherwise}
}
$$
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ ~~17~~ ~~16~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Commands)
```
‚Qλè∞λЦ¦+«Kн
```
-3 bytes by porting [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/204197/52210), so make sure to upvote him!
-6 bytes on my original 20 bytes solution thanks to *@Grimmy*, making it shorter than the port
Outputs the 0-based \$n^{th}\$ value, as specified in the challenge description.
[Try it online.](https://tio.run/##yy9OTMpM/f//UcOswHO7D6941DEPSE04tOzQMu1Dq70v7P3/3xIA)
Outputting the infinite sequence would be **12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Commands)**:
```
1‚λ∞λЦ¦+«Kн
```
[Try it online.](https://tio.run/##ASEA3v9vc2FiaWX//zHigJrOu@KIns67w5DCpsKmK8KrS9C9//8)
And outputting the first \$n\$ values of the sequence would be **13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Commands)** again:
```
‚Qλ£∞λЦ¦+«Kн
```
[Try it online.](https://tio.run/##ASUA2v9vc2FiaWX//@KAmlHOu8Kj4oiezrvDkMKmwqYrwqtL0L3//zI1)
**Explanation:**
```
‚ # Pair the (implicit) input with itself
Q # Check for each whether it's equal to the (implicit) input
# which results in a pair of 1s: [1,1]
λ # Create a recursive environment
è # to output the 0-based n'th value, where n is the (implicit) input
# (which will be output implicitly at the end)
# Starting with a(0)=a(1)=1 due to the earlier [1,1]-pair
# And for any other a(n) we'll:
∞ # Push an infinite positive list: [1,2,3,...]
λ # Push a list of all previous values: [a(0),a(1),...,a(n-1)]
Ð # Triplicate that list
¦¦ # Remove the first two values from the top copy
+ # Add the values in the top two lists together at the same positions,
# which also shortens the longer list by two:
# [a(0)+a(2),a(1)+a(3),...,a(n-3)+a(n-1)]
« # Merge it to the remaining copy of the triplicate
K # Remove all those values from the infinite positive list
н # Pop and leave the first remaining positive integer
1‚ # Pair 1 with itself (only works if there is no input,
# in which case it uses the 1 again implicitly)
λ # Create a recursive environment
# to output the infinite list
∞λЦ¦+«Kн # The rest is the same as above
```
[Answer]
# [Haskell](https://www.haskell.org/), 68 bytes
```
a n|n<2=1|q<-n-1=[x|x<-[a q+1..],notElem x[a c+a(c-2)|c<-[2..q]]]!!0
```
[Try it online!](https://tio.run/##DcoxDoQgEADAr2Cn8dgANZSWvoBsLhticuZgFaWg4O9oO5kf3f8txt5JcGNrnG7ZSpba@dqqlZ5EnjUAfvgoS9ySqC@FmcYgzdTCOwxARsRhUD3Rzi7RuX7H89q5AE1eAWiF/QE "Haskell – Try It Online")
Pretty simple answer, doesn't use the formula since that is no fun.
```
a n -- a n is ...
|n<2=1 -- 1 if n less than 2
|q<-n-1= -- where q is n-1
[...]!!0 -- the first element of ...
x|x<-[a q+1..], -- the integers larger than a(n-1) such that ...
notElem x[a c+a(c-2)|c<-[2..q]]
-- it satisfies the condition in the challenge.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 16 bytes
```
!¡ȯ←`-NS+Sz+↓2ḋ3
```
[Try it online!](https://tio.run/##ASIA3f9odXNr//8hwqHIr@KGkGAtTlMrU3or4oaTMuG4izP///8x "Husk – Try It Online")
Outputting the infinite list gives -1. Kinda sad I'm unable to get it below 16.
[Answer]
# [Python 2](https://docs.python.org/2/), 76 bytes
```
a=b=1
w=s={1}
exec"w|=s;c=b;b=a\nwhile w&s:a+=1;s={a,a+c}\n"*input()
print b
```
[Try it online!](https://tio.run/##JY09D4IwFEX39yteGETFweI35I24ujiytLUJRFOaUlKJ8tsrjdO9w7nnmtE1nc6D7B6KbJqmgZMgBp56@rAJ1FvJxH@pLyWJUhCvtW/al0K/6AueEStnjm94JqdaJ@tWm8EtV2Bsqx2KMAsB/oO7HVQBiM6OMRCjGuMvxC6VcVjdrpW1nf0Dwir@DFtgkMMO9nCAI5zgDJcf "Python 2 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 17 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Direct port of Arnauld's formula so be sure to `+1` him.
```
*1½^MmU &U%4¥2^!U
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=KjG9Xk1tVSAmVSU0pTJeIVU&input=OQ)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~58~~ 42 bytes
Using [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s formula from his [JavaScript answer](https://codegolf.stackexchange.com/a/204197/9481).
Saved a whopping 16 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!
```
f(n){n=3*n/2^~__builtin_clz(n)&n%4==2^!n;}
```
[Try it online!](https://tio.run/##HY7dCsIwDIXv@xRxMOlch/tDkVpfROfQzkphRtnmjaO@ek0NCYQvnHOis7vW3huOyYyqWuG6PH/b9vq2/WSx1f2HLkuMa6XK8wKl84@LRZ7MzOIEt2MDCuZCAHUpoBawEbAVsCOS0xArKieZeQ48CFDlEvdFLtOUAhlQBTySS3hB/slrIGZ4ZHjcJZAdIO4grCeMBKCAUVAwNkqNJHDM@R8 "C (gcc) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~75~~ \$\cdots\$ ~~44~~ 42 bytes
Using [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s formula from his [JavaScript answer](https://codegolf.stackexchange.com/a/204197/9481).
Saved ~~2~~ ~~5~~ 8 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!!!
Saved a whopping ~~8~~ ~~22~~ ~~23~~ 25 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!
```
lambda n:0**n^3*n/2^(len(bin(n))%2|n%4==2)
```
[Try it online!](https://tio.run/##JYzdCoJAEEbvfYqBkN3VlXSVfoTtRUzB0jXBRnHtIugRuuu2Xs4XsaGG@WDOgW@G@3TpUS0rOPdVi00Kt8kEO8fo49KV11NVAqah52ERe7hWBe9q5KcWOQrhqge6idZKLDVoyCIJtEpCImEjYSthTyakkIvi3DH9CAgtwlhiU/MoFKkDNJbahj7@YBhbnDgznPl2Gsn6TEBwgD9aQjozNn@eTLL5/WJ5VmeYa21zsXwB "Python 2 – Try It Online")
**Using the OP's formula**
# [Python 3](https://docs.python.org/3/), ~~87~~ 86 bytes
```
f=lambda n,r=[1,1],i=1:i*(len(r)/2>=n)or(i in r)and f(n,r,i+1)or f(n,[i]+r+[i+r[1]],i)
```
[Try it online!](https://tio.run/##JU3RCsIwDHzfV@StjYtoN1EU6o/UPkxdtTCjZPogY98@wwwJ5C6Xu9f3fX9yPU3Jd83jfG2ASXxw5CJl7w55YbuWreCqOnrGp9gMmUGw4Sskq2LKpVN@BiHHUsqQSwkuqgFOAh7sx5w@1W5zMQT/1dUGi1ZPGgTaFcGGYEuwI9grs9ZRztWxSGrNc2TDt9a6NR4K0Or1WyNxBi/J/LbJJDvwiLA8wtCPMEhoA0fv@zganH4 "Python 3 – Try It Online")
[Answer]
# [Io](http://iolanguage.org/), 75 bytes
Port of Arnauld's formula from their JS answer.
```
method(n,(3*n/2)floor-if((n log2 floor%2==0)and(n%2==4),-1,0)+if(n==0,1,0))
```
[Try it online!](https://tio.run/##HYpBDsIwDATvfYUvSHZxRUg5IeUnXCoVt5aCjaL@P7jsaWd31LvAs8Crf97H7isa4zzaLZNU9zapIBpU3zL8h0suJdFiIZ71QTzdOdE1PIuHT6Au3lA5KCUeICKoBN@mdlQbqP8A "Io – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~43~~ ~~42~~ 40 bytes
Using the same formula as earlier answers (and [Robin](https://codegolf.stackexchange.com/users/86301/robin-ryder)'s suggestions)
```
n+(n/2)%/%1-(!n%%4-2&log2(n+.1)%%2>1)+!n
```
[Try it online!](https://tio.run/##K/qfZ2tgZWhg8F/DWCtP30hTVV/VUFdDMU9V1UTXSFNLIyc/3UgjT1vPUFNV1cjOUFNbMe//fwA "R – Try It Online")
] |
[Question]
[
# Objective
Take \$a \in ℤ\_{>1}\$ and \$b \in ℤ\_+\$ as inputs. Write a function \$f\$ such that:
$$
f(a,b) =
\left\{
\begin{array}{ll}
\log\_ab & \quad \text{if} \space \log\_ab \in ℚ \\
-1 & \quad \text{otherwise}
\end{array}
\right.
$$
# Rules
* Types and formats of the inputs doesn't matter.
* Type and format of the output doesn't matter either, but the fraction must be irreducible. In C++, `std::pair<int,unsigned>` is an example. (Regarding logarithms, the numerator and the denominator need not to be arbitrary-length integers.)
* Regardless of whether the input type can handle arbitrary-length integers, the algorithm must be "as if" it were handling those. So using floating-point numbers is implicitly banned.
* If \$a\$ and \$b\$ aren't in the sets as specified above, the challenge falls in *don't care* situation.
* \$f\$ may be curried or uncurried.
* As this is a code-golf, the shortest code in bytes wins.
# Test cases
```
a b => answer
-----------------
2 8 => 3/1
3 9 => 2/1
8 2 => 1/3
9 3 => 1/2
4 8 => 3/2
64 256 => 4/3
999 1 => 0/1
-----------------
2 7 => -1
10 50 => -1
5 15 => -1
```
[Answer]
# Mathematica, ~~47~~ ~~45~~ ~~[43](https://tio.run/##y00syUjNTSzJTE7875yTmlgUnRb7PzG@Lq0uKV7fWiPZNrHOJz@9LknzUUdHEFBZfl5iTrGVbTIXSEm8la2u4f@Aosy8kui0aCMdi9hYLhjPWMcSiWehY4TEs9QxRuKZoOgzM9ExMjVDVmxpqWMI5Gto6UKBliYXwk5zJKWGBjqmBkh8Ux1D09jY/wA)~~ 29 bytes SBCS
```
If[NumberQ[c=#~Log~#2],c,-1]&
```
You can [try it online](https://tio.run/##y00syUjNTSzJTE7875yTmlgUnRbLlWb73zMt2q80Nym1KDA62Va5zic/vU7ZKFYnWUfXMFbtf0BRZl5JdFq0kY5FbCwXjGesY4nEs9AxQuJZ6hgj8UxQ9JmZ6BiZmiErtrTUMQTyNbR0oUBLkwthpzmSUkMDHVMDJL6pjqFpbOx/AA)!
Thanks to @J42161217 for saving me a total of 16 bytes!!
[Answer]
# [Python 3](https://docs.python.org/3/), ~~103~~ ~~101~~ 97 bytes
Saved 2 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!!!
Saved 4 bytes thanks to [Value Ink](https://codegolf.stackexchange.com/users/52194/value-ink)!!!
```
from math import*
def f(a,b):
l=log(b,a)
n,m=l.as_integer_ratio()
return -1if a**n-b**m else l
```
[Try it online!](https://tio.run/##dVDLjsIgFN3zFSdxA4SOLbVqTfothmZASQo0FBfz9fVOzWyMw4Jw7nlccuafck@xXVeXU0Aw5Q4f5pSLZN/WwXGjRnFhmIYp3fiojGCIKgzTl1muPhZ7s/maTfGJE5NteeSIqvEORspYjVIG2GmxmNZil7JgAGeca4WzUGj3jVAEW4WeoN7gjvMzvQk3@5buHYoPdkF6FJL25NoovTkPf0H65TzSALo70uzwyd2Tn5agfq2q3s9vBn3uRJKqebMT1dQKXf0P2VF094kTzKWMWVn4iK0GanTOVB93XM6ktmJ9Ag "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ 17 bytes
*-1 byte thanks to Kevin Cruijssen*
```
Ó0ζD€¿÷ʒOĀ}DËiнë®
```
[Try it online!](https://tio.run/##yy9OTMpM/R/i5mKvpGBrp6BkH/T/8GSDc9tcHjWtObT/8PZTk/yPNNS6HO7OvLD38OpD6/7X6mjG/I820lGwiOWKNtZRsARSFjoKRkDKUkfBGEiZQOTMgLSRqRlI3BIoYwhkAHWZAylDAx0FUwMgwxQobBoLAA "05AB1E – Try It Online")
```
Ó # prime factorize each input
0ζ # zip the factorizations together with filler 0
# for each pair of exponents:
D€¿ # get the gcd
÷ # divide both by the gcd (reducing the fraction)
ʒ } # filter the pairs, keep only those where:
O # the sum
Ā # is not 0
DËi # if all the resulting pairs are equal:
н # output the first pair
ë # otherwise:
® # output -1
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~88~~ 82 bytes
```
≔Eθ⟦⟧ζ≔²ηW⊖⌈θ¿⌊﹪θη≦⊕ηUMθ⎇﹪κηκ∧⊞O§ζλη÷κηFζFι⊞υκUMυEζ№λιUMυ÷ι⊟Φ⊕⌈ι∧λ¬⌈﹪ιλ¿›⌈υ⌊υ-1I⊟υ
```
[Try it online!](https://tio.run/##VZAxb8IwEIVn8itOTGfJDCCkVsqEglox0DJ0QwwWMc2pjg2OTSl/Pj0ngVIvlp/f@3x@@0r5vVOmbRdNQ58W1@qIJwnbnZBwFXk2yDMJFZ@@KzIacKn3XtfaBl1y4EJ1rPEkhMhGdABck@2UtSujcYlW8R0weYCt7D3eY0faNDoZClfXypYp86G9Vf7nRvlKTgm84YINm9hU70ftVXAeF2FlS33BqwQjet/KhiWdqdR9kFeeHZwHvArodhKQGBiZyXcPb7OSSmBY4aINaCRQl//v@XuBJGzcEV/IBO0fP3fvhvMS0tjMenPhrg9/ozT3sPIsVfjqtUqwmzFy/lZrTGVuPPFo48l0zImuvV4pVBMwTZNcedtut9On2bOE6Xy@27WTs/kF "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list in [value, base] order and outputs numerator and denominator. Edit: Saved 6 bytes by simplifying my check for exclusive factors. Explanation:
```
≔Eθ⟦⟧ζ≔²ηW⊖⌈θ¿⌊﹪θη≦⊕ηUMθ⎇﹪κηκ∧⊞O§ζλη÷κη
```
Factorise both numbers by trial division.
```
FζFι⊞υκ
```
Collect the factors from both inputs, in case some factors are only present in one of them.
```
UMυEζ№λιUMυ÷ι⊟Φ⊕⌈ι∧λ¬⌈﹪ιλ
```
Divide the multiplicity of each factor in both the base and the value by their GCD.
```
¿›⌈υ⌊υ-1
```
If this is not unique then output `-1`.
```
I⊟υ
```
If it is unique then output it.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~94~~ ~~79~~ 76 bytes
Nothing clever here; this is the obvious brute force approach.
**Edit**: Unified return point and switched to lambda syntax.
**Edit 2**: Shaved off three bytes due to @xnor's `next` trick and rules clarification.
```
lambda a,b:next(((i,j)for i in range(b)for j in range(1,a)if a**i==b**j),-1)
```
[Try it online!](https://tio.run/##VZBRb4MgFIXf@RU3vgiGWsHaTRP3tuxHWLNgqxumQ6M8dGn6291F67Y@kPCdczkc6L/tZ2fiqckP01l9VScFileZqS@WUqp5y5puAA3awKDMR02rWWj/BMEV0w2oINB5XgVBy/hGsMnWo30f7QA5eJ4nAeAZV/4C8VaQGLfpghLROXJBsY2Jc@IVJdn9PyvJHlkme4c7N5ymIBY3wigX87TgRhARASTRSgnqIrkTliLElRyxYUG1sVSHY3/WlrIiKhmHR0nM0h19jPBnDX6/Z33wOnIwPivJgz1mBCtAP7joxnu99PXR1qcMrrqQ5S2Et87CtaEaC@BlLv8Wemz6AQ "Python 3 – Try It Online")
[Answer]
# [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html), 110 bytes
```
define f(a,b){
c=0
d=1
while(0!=e=a^c-b^d){if(a<2^d){print"-1";return}
if(e>1)d=d+1 else c=c+1}
print c,"/",d}
```
[Try it online!](https://tio.run/##bY9NboMwEIX3PsXUK6wSwAbzo9Y5SYUEtqMiJTQipG0UcXZqwBBXrRfw7G/em5lajqPSh6bVcPAqvyZ3JEWElKDo6705ai96ElpUpdzVpSL3xhS9skmdu6bt8Y7il073164dkGF6T4kS6pmCPl40SCGf6YDmUpA@DrGvhhHZfp8fjYK@u3mV6Vv7UhK4IzBnqTevgAH7YJgRYg94pup6Ot3EYXERx4ABPP191rLXavJJaXwEuxVvLUYDGi@yOmpBIzR1Zz5sJ7c6DimZYezAwmq2wtyBawoN4wUWDow3yBaY/NvTwtShjKfzJdlii0cwtSoyA03/P@tkVu/swDR6QG71yrjjo/w3YyWN1h1YySZtPqF5tLlBss3MgiTPYzMFX/dhAdvCs4AXccYdmjq0yIKUp2zF6Ac "bc – Try It Online")
As with a number of my solutions, it outputs its answer and returns 0, which the test code ignores.
The use of scale= in the provided input is only so the expected value can be passed in. (You can't have a string value in bc.) The code is strictly integer... provided you pass in integers. The code may fail if a or the needed root of a is less than two. (See two failing samples in TIO.)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~72~~ 68 bytes
Takes input as `(a)(b)`, where \$a\$ and \$b\$ are BigInts. Returns either `[numerator, denominator]` or \$-1\$.
```
a=>g=(b,p=0n,q=1n)=>p>b?-1:(d=a**p-b**q)?g(b,d>0?++q&&p:-~p,q):[p,q]
```
[Try it online!](https://tio.run/##dc9LDoIwEIDhPafoyrRApS0PgaTlIMYF72hIW8S49OoIWF0Abmbzf8nM3PJnPpT3q35gqap6bPiYc9FyWLiaE@n2nErEhRZFhmkKK57btsaFbfcoaydUCZI5Tn846BS/tNuj9DzNy1gqOaiuPnaqhQ0EgEk0zVgiBDwP@B611sJfRGIE2xHxIpgR1PM3IlmE/xNsI4LVHRsRzYKFkRHBZkuSfLZQI8h0qbX/7skQvO6UzD0k/zoI507Dbx/f "JavaScript (Node.js) – Try It Online")
### How?
We start with \$p=0\$ and \$q=1\$. We iteratively increment \$q\$ if \$a^p>b^q\$ or increment \$p\$ if \$a^p<b^q\$, until \$a^p=b^q\$ (success) or \$p>b\$ (no solution).
[Answer]
# [Sledgehammer](https://github.com/tkwa/Sledgehammer), 11 bytes
Alternatively, 83 bits.
I ended up forgetting to actually *answer* this with Sledgehammer for a while...
```
⣜⢍⡪⡱⣰⡵⠅⣧⣼⣅⣸
```
Compressed from this Wolfram Language code:
```
If[NumberQ[x1 = Log[Input[], Input[]]], x1, -1]
```
, where `NumberQ` is a built-in that checks whether `Log` has returned an actual number and not a symbolic expression, i.e. when it is rational.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 72 bytes
```
->a,b{n,d=[*1..a*b].product([*1..a]).find{|n,d|a**n==b**d};n ?n/1r/d:-1}
```
[Try it online!](https://tio.run/##KypNqvyfZhvzX9cuUSepOk8nxTZay1BPL1ErKVavoCg/pTS5RAMiEqupl5aZl1JdA1RUk6illWdrm6SllVJrnadgn6dvWKSfYqVrWPu/QCEt2kLHJPY/AA "Ruby – Try It Online")
] |
[Question]
[
[Another brilliant question from Stack Overflow](https://stackoverflow.com/q/20696011/764357) turned into a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge!
Write a program that:
1. Accepts a **string** as user input (not *piped in* or a command line argument). The data type of the input must be a string, if the language does auto evals on input, it must be cast to a string.
2. Finds the index (0 or 1 based) of the first lowest even *digit*.
3. **Prints 2 integers**, the index and the lowest even *digit*.
4. If there is no even *digit*, return -1 as the index, the second number can be anything.
5. For the purposes of this *zero is not even*.
Test examples, given the string on the left output the values on the right:
```
25376 --> 0,2
523726 --> 1,2
583746 --> 4,4
53771 --> -1,0
_4___2 --> 5,2
```
**The winner: is the program with the lowest character count.** No bonuses, no penalties.
**edit: (about stdin)** I screwed up on the user input part, basically no piping data in, and no command line arguments. You must provide a user prompt of some kind within the program itself.
[Answer]
# Golfscript, 26 (28) characters
```
'#{gets}'.'246'&8+$1<.@\?
```
Example:
```
;'583746'
.'246'&8+$1<.@\?
#44
;'53771'
.'246'&8+$1<.@\?
#8-1
```
live test: <http://golfscript.apphb.com/?c=Oyc1Mzc3MScKLicyNDYnJjgrJDE8LjA9QD8%3D>
Explanation:
* `'#{gets}'` is an escape to ruby to satisfy the I/O requirements; STDIN is assumed to be empty
* `.` clones the input
* `'246'&8+` finds which even digits are present in the input, except `8` is always retained
* `$1<` sorts the list, then takes the first digit, but keeps it as a string
* `.@\?` orders the stack {digit, input, digit}, then finds the digit in the input; thanks @peterTaylor for noticing me of the [array, array] signature of `?`.
I've been very bold with the spec interpretation this time; namely:
* The spec does not mandate in which order the integers are output; Use the other @peter's suggestion `:x?x` to fix (I don't like temporary variables.
* The spec does not require any delimiter between the two integers; since the digit found is always a single digit, this does not matter much. If it does, append `n@` (which also performs the swap), `n\` (which doesn't), or `]`` (which formats the output as `["8" -1]`).
[Answer]
## APL (37)
(1-based by default, but obeys `⎕IO`)
```
{×⍴m←⍵/⍨⍵∊'2468':z,⍨⍵⍳⍕z←⌊/⍎¨m⋄¯1,0}⍞
```
Explanation:
* `⍞`: read user input
* `m←⍵/⍨⍵∊'2468'`: remove all the characters that aren't `2468`, store in `m`.
* `×⍴m`: see if there are any
* `:`: If so:
+ `z←⌊/⍎¨m`: evaluate each character in `m`, find the lowest number and store in `z`.
+ `z,⍨⍵⍳⍕z`: return the index of `z` in `⍵`, followed by `z`.
* `⋄`: If not:
+ `¯1,0`: return `(-1, 0)`
[Answer]
**Python 3 ,69**
combining ideas from [here](https://codegolf.stackexchange.com/questions/16083/homework-time-find-me-the-lowest-even-digit-in-a-string/16084#16084).
```
s=input();print(([(s.find(x),x)for x in'2468'if x in s]+[(-1,0)])[0])
```
[Answer]
# Ruby, 60 characters
```
x=gets.chars.sort.find{|c|c=~/[2468]/};p x ?$_.index(x):-1,x
```
* `$_` contains the last input read by `gets`.
* `p` calls `inspect` on the arguments and prints the results.
[Answer]
## perl - -~~94~~- 53 chars (or 48)
Instead of `index()`'s zero-based approach we use `pos` and start at one; no CPAN. Run this with `perl -nE` and it will wait for input (which it can also receive from `STDIN`).
The first match (`//`) operation works on the default value (`$_`) from input, matching against the given even numbers, `sort`ing the matches into an array, and then storing them in a "scalar list" `($m)`. In scalar context the list value of the sorted array is one item long and thus consists of the lowest matched even digit in the number.
Having isolated the lowest even matched digit, we then use `$m` for a second match operation which will find the first occurrence of the value of `$m` in the original string. We are still using the default value here `$_` and we are saving the match against the contents of `$m` in `$1` (the reason for the `()` around `$m` in the second statement). After that, `pos` and `say` do the rest (and in fewer characters than `index` and `print`).
```
perl -nE'($m)=sort/[2468]/g;/($m)/g;$1?say pos.",$1":say"-1,0"'
33467
3,4
```
If output order or commas don't matter then it's possible to make this 5 chars shorter:
```
($m)=sort/[2468]/g;/($m)/g;$1?say$1.pos:say"-10"
```
In my earlier attempt I rushed and made an error - I just wanted to beat python and ruby (but failed) ... sigh.
Congrats to the winner and the other participants on their cool solutions - especially to `perl6` :-) A possible Perl6 adaptation of this approach could use "`.comb` (suggested on freenode by Masak *et.al.*).
```
$_=get;my $n=.comb(/<[2468]>/).min;/$n/;say $/.from//-1,",$/"
```
[Answer]
# Perl 6, ~~37~~ ~~55~~ *60* characters
```
$_=get;say m/<{~.comb(/<[2468]>/).min}>/.from//-1,',',$/.Int
```
EDIT: I misunderstood the question the first time. This update should be correct. It finds the lowest number of 2,4,6, or 8 that the input contains, and then does a regex match against the input with that lowest number. `$/.from` gets the position of the match and `',', $/.Int` is a comma plus the match itself, or 0 if the text didn't match.
While you're here, go upvote [G. Cito](https://codegolf.stackexchange.com/a/25952/15012), who helped me fix my entry in the comments and on irc :)
[Answer]
# J, 44 characters
```
echo(;{&i){._1,~(#~(#i)&>)'2468'i.~i=.1!:1]1
```
outputs the last character of the input if no even digit is found
Example:
```
echo(;{&i){._1,~(#~(#i)&>)'2468'i.~i=.1!:1]1
523726
+-+-+
|1|2|
+-+-+
echo(;{&i){._1,~(#~(#i)&>)'2468'i.~i=.1!:1]1
53771
+--+-+
|_1|1|
+--+-+
```
Explanation:
* `echo ... i=.1!:1]1` is input/output. Way longer than I want it to. Input is stashed away into `i` as well.
* `'2468'i.~` finds the first occurence of each even digit in the input, returning the input length if the digit cannot be found
* `(#~(#i)&>)` reads "select by the length of input being greater than this"; in other words, select those indices that point into the input. Way longer than I want it to.
* `_1,~` appends -1 to the back. Underscore is the J's way of representing negative values.
* `{.` selects the first element
* `(;{&i)` concatenates it with the input character at that position in two boxes; since we're concatenating a number with a character, non-boxing concatenation (`,`) won't do. If unboxed display is desired, the index needs to be formatted (`":`) first at a cost of two chars.
[Answer]
# Python 2.7 - 76
A reference answer I fully expect to be beaten. But to start people off:
```
s=raw_input()
print[(s.index(`e`),e)for e in[2,4,6,8]if`e`in s][:1]or(-1,0)
```
[Answer]
## R, 104
```
y=as.integer(strsplit(scan(,""),"")[[1]]);z=which(!y%%2&y);a=z[which.min(y[z])];cat(a,"-1 0"[!sum(a)],y[a])
```
Examples (in R, the index starts at 1):
```
_4_502
6 2
_3_501
-1 0
583746
5 4
```
[Answer]
## Powershell, ~~76~~ ~~73~~ 71
```
$s=read-host;2,4,6,8|%{if($i=$s.indexof("$_")+1){"$i,$_";break}};"-1,0"
```
* `$s=read-host` stores user input into `$s`
* `2,4,6,8|%{...}` runs what's inside `{}` for digits 2,4,6,and 8
* `$i=$s.indexof("$_")+1` sets `$i` to 1-based index of a digit in `$s` or `0` if the digit is not found
* `if( $i=... ){...}` the condition will be true when `$i` is not `0`
* `"$i,$_";break` outputs the index and the digit, and stops execution
* `"-1,0"` otherwise outputs `-1,0`
[Answer]
# C++11, 173 (including two new-line chars)
Here's the compressed version:
```
#include<iostream>
#include<string>
int main(){std::string s;std::cin>>s;for(char c:"2468")for(char&k:s)if(k==c){std::cout<<(&k-&s[0])<<','<<c;return 0;}std::cout<<"-1,8";}
```
Here's the readable version:
```
#include<iostream>
#include<string>
int main() {
std::string s; // auto s = ""s; (since C++14: -3 characters)
std::cin >> s;
for (char c : "2468")
for (char& k : s)
if (k == c) {
std::cout << (&k - &s[0]) << ',' << c;
return 0;
}
std::cout << "-1,8";
}
```
---
Here's an older version:
**C++11, 175 (including two new-line chars)**
Here's the compressed version:
```
#include<iostream>
#include<string>
int main(){std::string s;std::cin>>s;for(char c:"2468"){int i=s.find(c);if(i<s.size()){std::cout<<i<<','<<c;return 0;}}std::cout<<"-1,8";}
```
Here's the readable version:
```
#include<iostream>
#include<string>
int main() {
std::string s;
std::cin >> s;
for (char c : "2468") {
int i = s.find(c);
if (i < s.size()) {
std::cout << i << ',' << c;
return 0;
}
}
std::cout << "-1,8";
}
```
[Answer]
## C, 80 character
```
main(){char a[81],b=strcspn((gets(a),a),"2468");printf("%d,%c",a[b]?b:-1,a[b]);}
```
[Answer]
## C# - 124
I'm a bit late to the party
```
void Main(string[]a){var x=a[0].Where(w=>char.IsDigit(w));var y=x.Min();Console.Write(y%2==0?a[0].IndexOf(y)+","+y:"-1,0");}
```
[Answer]
## Haskell, 79 characters
```
s&d=filter((==d).snd)$zip[-1..]$'0':s
main=interact$show.head.("24680">>=).(&)
```
This runs a little fast and loose with the output formatting:
```
& echo 523726 | runhaskell 16083-LowEven.hs
(1,'2')
& echo 583746 | runhaskell 16083-LowEven.hs
(4,'4')
& echo 53771 | runhaskell 16083-LowEven.hs
(-1,'0')
& echo _4___2 | runhaskell 16083-LowEven.hs
(5,'2')
& echo 25376 | runhaskell 16083-LowEven.hs
(0,'2')
```
[Answer]
# PowerShell: 145 103
>
> **Changes from original**
>
> Removed error quelch per [comment](https://codegolf.stackexchange.com/questions/16083/homework-time-find-me-the-lowest-even-digit-in-a-string#comment30614_16083) from asker.
>
>
>
**Code:**
```
"$([array]::IndexOf(($s=(read-host)-split''|?{$_}),($x=$s|?{$_%2-eq0}|?{$_-gt0}|sort|select -f 1))),$x"
```
**Walkthrough:**
`"`...`"` Everything within the quotes will be included in the output.
`$(`...`)` Everything between the parenthesis will be treated as a commands, and the output of that code will be included instead of the commands themselves.
`[array]::IndexOf(`...`)` This is used to get the index of an element with the array. Its first parameter is the array object to be searched. The second parameter is the object to be found. This only outputs the index of the first matching element. I tried simply using an `IndexOf` method directly against `$s` (e.g.: `$s.IndexOf($x)`, but this fails for some reason I've yet to figure out - it claims the method doesn't exist on that object.
`(`...`)` Expression within the parenthesis will be the first parameter for `IndexOf`.
`$s=` $s will be a variable to store the user input.
`(read-host)-split''` Gets user input, and splits it into an array of characters.`
`|?{$_}` Filters out extra empty array elements that are generated by `-split''`.
`,(`...`)` Expression within the parenthesis will be the second parameter for `IndexOf`.
`$x=` $s will be a variable to store the lowest even digit from the user input.
`$s|?{$_%2-eq0}` Pulls out the even numbers from $s.
`|?{$_-gt0}` Invalidates zero.
`|sort` Sorts the remaining objects, default order is ascending.
`|select -f 1` Picks the first object, which will by now be the lowest even digit.
`,$x` The above code will output the index of our lowest even digit. This adds a comma, and then outputs the digit itself.
**Notes:**
This is perhaps stretching rule #4 a little bit. If there is no even digit, the output will not include a second number.
Also, this will throw some non-terminating errors if the input includes non-numeric elements. The script will still run and give proper output, but you might want to set `$ErrorActionPreference` to `'SilentlyContinue'` before running it.
[Answer]
**vb.net (108c)**
```
Sub Main()
t=ReadLine() '12c
For Each c In "2468" '20c
i=t.IndexOf(c) '14c
If i>=0 Then Exit For '21c
Next ' 4c
WriteLine("{0},{1}",i,If(i<0,0,t(i))) '37c
End Sub
```
Smells slightly cos it's exploiting VB's dynamic setting. **Option Explicit Off** and **Imports System.Console**.
[Answer]
**VB.net (193c) using LINQ**
This one is primarily utilising a LINQ query.
```
Dim r = From d In "2468" Group Join q In ReadLine.Select(Function(c, p) New With {.c = c, .i = p})
On d Equals q.c Into g = Group
Skip While g.Count = 0 ' 138c
WriteLine(If(r.Any,r(0).g(0).i&","&r(0).g(0).c,"-1,0")) ' 55c
```
[Answer]
## Golf-Basic 84, 91 characters
```
:L1/L1_L2i`L1:fpart(L1,2)2_L1:SortA(L1)@cumSum(L1)=length(L1):Thend`-1#d`cumSum(L1):Endd`L1
```
* Make sure there's no `0` in the input (it's not even, who said it had to be odd?)
* Get input into L1 (List 1)
* Loop finding modulus of 2 for each value
* Sort L1 from smallest to highest
* Display the index (either -1 or the cumulative sum) and the smallest number
[Answer]
## Bourne shell (sh), 88 chars
```
(echo 88;sed 's/./\n&/g')|nl -v-1|awk '{print $2,$1}'|sed '/^[^2468]/d'|sort -n|head -n1
```
I thought I'd do a string-processing thing for fun. Technically it reads from stdin, but if you run it interactively it'll prompt the user for input since the keyboard is the default stdin stream. Uses basic shell commands to split up the input on lines, number them (using the ill-known `nl` utility), filter out lines fitting the criteria, sort them and output the lowest-digit one. Prints `88 -1` if no even digit was found.
[Answer]
# C++ - 223 ~~221~~ Characters:
```
#include<iostream>
#include<string>using namespace std;
int main(){int s=9;int p=-1;string x;cout<<"Enter characters: ";cin>>x;for(int i=0;i<x.length();i++){int n=x[i]-48;if(n%2==0&n<s){s=n;p=i;}}cout<<p<<", "<<s;return 0;}
```
Readable version:
```
#include<iostream>
#include<string>
using namespace std;
int main() {
int s = 9;
int p= - 1;
string x;
cout << "Enter characters: ";
cin >> x;
for (int i = 0; i < x.length(); i++) {
int n = x[i] - 48;
if (n % 2 == 0 & n < s) {
s = n;
p = i;
}
}
cout << p << ", " << s;
return 0;
}
```
It is long, but not as bad as Java.
[Answer]
# Javascript 93 characters
```
b=prompt();((r=b.match(/[2468]/g)||[-1]).sort(function(a,b){return a-b})[0])+","+b.indexOf(r)
```
Get all event numbers, sort the array and prints the first digit.
[Answer]
# Mathematica, 157 characters
```
f = Row@{If[(x = Min@#) == Infinity, -1, Position[#, x][[1, 1]]],
",", x} &[IntegerDigits@ToExpression@StringReplace[#,
{"0" -> "1", x_?DigitQ :> x, _ -> "1"}] /. _?OddQ -> Infinity] &
inputs = {"25376", "523726", "583746", "53771", "_4___2"}
f /@ inputs // Column
```
>
> 1,2
>
>
> 2,2
>
>
> 5,4
>
>
> -1,∞
>
>
> 6,2
>
>
>
[Answer]
# Julia, 84
```
julia> f(a)=(for i=2:2:8;(k=search(a,'0'+i))==0||return(k,i);end;(-1,0))
julia> f(readline(STDIN))
583746
(5,4)
julia> f(readline(STDIN))
_4___2
(6,2)
```
Julia really needs a shorter way to get input for golfing. I counted the definition of `f` and one call to `f`. One based indexing is why the answers are different from the examples.
[Answer]
# JavaScript - 53 Characters
```
for(y=prompt(x=0);x<8&&(i=y.indexOf(x+=2))<0;);x+''+i
```
Reads input from prompt and outputs (to the console) the lowest even character then (without a delimiter) the first index of that character; if there are no non-zero even characters then it outputs `8-1`.
[Answer]
# C, 110 Characters
```
i,f,r,c,m=9;main(){while(r=getchar()>31){c=r-48;i++;if(c>=0&&~c&1&&c<m)m=c,f=i;}printf("%i,%i",m>8?-1:f-1,m);}
```
ungolfed:
```
i,f,r,c,m=9;
main(){
while(r=getchar()>31){
c=r-48;
i++;
if(c>=0&&~c&1&&c<m) m=c,f=i;
}
printf("%i,%i",m>8?-1:f-1,m);
}
```
[Answer]
# Javascript, 69
```
a=prompt(),b=[-1,9];for(i in a)if(+a[i]%2==0&&+a[i]<b[1])b=[+i,+a[i]]
```
Reads the value, iterates through each character, if the number representation mod 2 equals 0 and the number is less that what is already stored in `b`, replace the values in `b`
[Answer]
# Rebol, 69
```
s: input for n 2 8 2[if f: find s n[print[index? f f/1]q]]print[-1 0]
```
[Answer]
# Ruby 55
```
p gets.chars.sort*''=~/[2468]/?[$_.index($&),$&]:[-1,0]
```
[Answer]
## JavaScript/jQuery 149
Golfed
```
$(function(){
var i=prompt(),k=-1,n=0,c,e="2468";
while(n<i.length){c=i.charAt(n);k=e.indexOf(c);if(k>=0){break;}n++;}$('#d').append(k+","+n);
});
```
Full source
```
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="d"></div>
<script type="text/javascript">
$(function(){
var i=prompt();
var k=-1;
var n=0;
var c;
var e="2468";
while(n<i.length){
c=i.charAt(n);
k=e.indexOf(c);
if(k>=0){
break;
}
n++;
}
$('#d').append(k+","+n);
});
</script>
</body>
</html>
```
] |
[Question]
[
**Context**
>
> Chess960 (or Fischer Random Chess) is a variant of chess invented and advocated by former World Chess Champion Bobby Fischer, publicly announced on June 19, 1996 in Buenos Aires, Argentina. It employs the same board and pieces as standard chess; however, the starting position of the pieces on the players' home ranks is randomized
>
>
>
**Rules**
>
> * White pawns are placed on the second rank as in standard chess
> * All remaining white pieces are placed randomly on the first rank
> * The bishops must be placed on opposite-color squares
> * The king must be placed on a square between the rooks.
> * Black's pieces are placed equal-and-opposite to White's pieces.
>
>
>
From: <http://en.wikipedia.org/wiki/Chess960>
For all the people that would like to post answers...
you have to make a Chess960 positions generator, capable of randomly generate one of the 960 positions following the rules described above (it has to be capable of outputting any of the 960, hardcoding one position is not accepted!), and you only need to output the white rank one pieces.
Example output:
rkrbnnbq
where:
* k king
* q queen
* b bishop
* n knight
* r rook
This will be code golf, and the tie breaker will be the upvotes.
[Answer]
# Ruby 1.9, 67 65 characters
Ah, the old "keep randomizing until you generate something valid" technique...
```
$_=%w(r r n n b b q k).shuffle*''until/r.*k.*r/&&/b(..)*b/
$><<$_
```
(In Ruby 2.0, `%w(r r n n b b q k)` could be `'rrnnbbqk'.chars`)
[Answer]
## GolfScript ~~60~~ 49
```
;'qbbnnxxx'{{9rand*}$.'b'/1=,2%}do'x'/'rkr'1/]zip
```
(shortened to 49 chars thanks to Peter Taylor's great tips)
Online test [here](http://golfscript.apphb.com/?c=OydxYmJubnh4eCd7ezlyYW5kKn0kLidiJy8xPSwyJX1kbyd4Jy8ncmtyJzEvXXppcA%3D%3D&run=true).
An explanation of the code:
```
;'qbbnnxxx' # push the string 'qbbnnxxx' on the clean stack
{
{9rand*}$ # shuffle the string
.'b'/1=,2% # count the number of places between the 'b's
# (including the 'b's themselves)
# if this count is even, the bishops are on
# squares of different colors, so place a 0
# on the stack to make the do loop stop
}do # repeat the procedure above until a
# good string is encountered
'x'/ # split the string where the 'x's are
'rkr'1/]zip # and put 'r', 'k' and then 'r' again
# where the 'x's used to be
```
[Answer]
## GolfScript (49 48 chars, or 47 for upper-case output)
```
'bbnnrrkq'{{;9rand}$.'b'/1=,1$'r'/1='k'?)!|1&}do
```
This uses the standard technique of permuting randomly until we meet the criteria. Unlike w0lf's GolfScript solution, this does both checks on the string, so it is likely to run through the loop more times.
Using upper case allows saving one char:
```
'BBNNRRKQ'{{;9rand}$.'B'/1=,1$'R'/1=75?)!|1&}do
```
[Answer]
### J, 56 characters
```
{.(#~'(?=.*b(..)*b).*r.*k.*r.*'&rxeq"1)'kqbbnnrr'A.~?~!8
```
it takes several seconds on my machine due to the inefficient algorithm. Some speed may be gained by adding `~.`(remove duplicates) before `'kqbbnnrr'`.
explanation:
* `?~!8` deals `8!` random elements from `0 ... 8!`
* `'kqbbnnrr'A.~` uses them as anagram indexes to the string `kqbbnnrr`.
* `(#~'...'&rxeq"1)'` filters them by the regex in quotes.
* `{.` means "take the first element"
[Answer]
# K,69
```
(-8?)/[{~*(*/~~':{m=_m:x%2}@&x="b")&(&x="k")within&"r"=x};"rrbbnnkq"]
```
[Answer]
# Python, 105 chars
Basically chron's technique, minus the elegant Ruby stuff.
```
import re,random
a='rrbbnnkq'
while re.search('b.(..)*b|r[^k]*r',a):a=''.join(random.sample(a,8))
print a
```
Thanks to Peter Taylor for the shortening of the regex.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 36 bytes
```
qbnbnrrr
/.*b.(..)*b.*/+V?`
Y`rr`rk
```
[Try it online!](https://tio.run/##K0otycxLNPz/n6swKS8pr6ioiEtfTytJT0NPTxNIaelrh9kncEUmFBUlFGX//w8A "Retina – Try It Online")
### Explanation
```
qbnbnrrr Start with this string
/.*b.(..)*b.*/+V?` Keep shuffling it as long as it matches the regex (odd number of pieces between bishops)
Y`rr`rk Replace the second r with a k
```
[Answer]
# Perl, 69 chars
```
$_=rrbbnnkq;/r[^k]*r|b.(..)*b/||say while s/(.{@{[time%8]}})(.)/$2$1/
```
To test it, add `$|=1;` at the beginning to see progress and keep tabs by pipeing into another perl process like this:
```
perl -E'$|=1;$_=rrbbnnkq;/r[^k]*r|b.(..)*b/||say while s/(.{@{[time%7]}})(.)/$2$1/' \
| perl -nlE'$a{$_}++ or say"$_ ".keys%a'
```
This will e v e n t u a l l y get the 960 valid permutations.
To run the test fast, swap out `time%8` with `int rand 8` like this:
```
perl -E'$_=rrbbnnkq;/r[^k]*r|b.(..)*b/||say while s/(.{@{[int rand 8]}})(.)/$2$1/' \
| perl -nlE'$a{$_}++||say"$_ ".keys%a'
```
] |
[Question]
[
Your mission, should you choose to accept it, is to input a series of point pairs that form a graph, like this:
>
> A,B C,A B,A A,D A,E F,G C,G
>
>
>
You must then output an ASCII visualization of the graph.
For example, `A,B C,A C,D` could be:
```
A-----------------B
\
\
C---------D
```
Edit: As per the comments, here are some input constraints:
* each node has at most 5 connections (+20 if you can handle more)
* the graph is planar, i.e. no lines cross (+200 if you can handle even one crossover!)
* there are at most 16 nodes (+20 if you can handle more)
Your score is **999 - (your code length) + (any bonuses)**.
Start your engines :)
[Answer]
## APL (~~171~~ ~~166~~ 162 chars, all bonuses: 999 - ~~171~~ ~~166~~ 162 + 20 + 20 + 200 = ~~1068~~ ~~1073~~ 1077)
This is the longest golfed APL program I've written so far. This might be slightly cheating, but there's nothing in the question that actually disallows this. What I'm doing is putting all the nodes on a vertical line and drawing the graph as an arc diagram. It is obviously still a graph though.
It still took me a few hours.
```
V←' '⍴⍨99,⍨2×⍴P←∪,C←(2,⍨2÷⍨⍴G)⍴G←G/⍨⎕A∊⍨G←⍞⋄V[2×⍳⍴P;50]←P⋄M←1⋄G←⍴D←{⍵[⍋⍵]}¨↓P⍳C⋄{V[A B←⍵;L←50+M×⌽⍳G]∘←'-'⋄V[A+⍳B-A;⊃L]∘←'|'⋄V[⍵;⊃L]∘←'+'⋄M×←¯1⋄G-←1}¨2×D[⍒|-/↑D]⋄V
```
The nodes must be single uppercase letters, so it supports 26 nodes maximum. It can handle crossed lines, and each node can have as many connections as the display will handle.
Example output:
```
A,B C,A C,D
+-A--+
| |
+-B |
|
C+-+
|
D+
A,B C,A B,A A,D A,E F,G C,G
+--A-+-+-+
| | | |
| B-+ | |
| | |
+-+--C | |
| | |
| D---+ |
| |
| E-----+
|
| +F
| |
+---+G
T,H E,Q U,I C,K B,R O,W N,F O,X J,U M,P S,O V,E R,T H,E L,A Z,Y D,O G,S
+---+----------T
| |
| +-------+--H
| |
| +--E---------+-------+
| | |
| Q---------+ |
| |
| +--------U---------------+ |
| | | |
| +--------I | |
| | |
| C-------+ | |
| | | |
| K-------+ | |
| | |
| +------B | |
| | | |
+-------+------R | |
| |
+----------------O-----+-----+-+ | |
| | | | | |
| W-----+ | | | |
| | | | |
| +----N | | | |
| | | | | |
| +----F | | | |
| | | | |
| X-----------+ | | |
| | | |
| J-------------|-+ |
| | |
| M---+ | |
| | | |
| P---+ | |
| | |
| +------------S-------------+ |
| | |
| | V-----------------+
| |
| | L-+
| | |
| | A-+
| |
| | +Z
| | |
| | +Y
| |
+---|------------D
|
+------------G
```
[Answer]
## Python, 195 chars, score = 999 - 195 + 20 + 200 + 20 = 1044
```
R=raw_input()
V=' '.join(set(R)-set(' ,'))
S=' '*len(V)
for e in R.split():x,y=sorted(map(V.index,e[::2]));print S[:x]+'+'+'-'*(y-x-1)+'+'+S[y+1:];S=S[:x]+'|'+S[x+1:y]+'|'+S[y+1:];print S
print V
```
Each edge gets a row. S is a string with the vertical connections we need to keep as we build the graph.
Here are some sample input/output:
```
A,B C,A B,A A,D A,E F,G C,G
+---+
| |
+-+ |
| | |
+---+
| | |
+-------+
| | | |
+-----+ |
| | | | |
| | | | | +-+
| | | | | | |
| +-------+ |
| | | | | | |
A C B E D G F
```
and stolen from marinus:
```
T,H E,Q U,I C,K B,R O,W N,F O,X J,U M,P S,O V,E R,T H,E L,A Z,Y D,O G,S
+-----------------------+
| |
+-----------------------+ |
| | | |
| +-----------------------+ |
| | | | | |
+---------------+ | | |
| | | | | | | |
| +-------------------------------+ | |
| | | | | | | | | |
| | | | | | +---------------+
| | | | | | | | | | | |
| | | +---------------+ | | | | |
| | | | | | | | | | | | | |
| | | | | | | +---------------------+
| | | | | | | | | | | | | | |
| | | | | | | +-----------------+ | | |
| | | | | | | | | | | | | | | |
| | | | | | | | +---------+ | | | | |
| | | | | | | | | | | | | | | | | |
| | | | | | | | | +-------+ | | | | |
| | | | | | | | | | | | | | | | | | |
| | +-------------------------------------+ |
| | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | +---+ | | |
| | | | | | | | | | | | | | | | | | | |
| | +---------+ | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | |
+-----------------------+ | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | +---+
| | | | | | | | | | | | | | | | | | | | | | | |
| | | | +-----------------+ | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | +-----------------------+ | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | |
A C B E D G F I H K J M L O N Q P S R U T W V Y X Z
```
[Answer]
# Python 3, 168 chars, Score = 999- 168 + 240 = 1071
Just shortening **[Keith Randalls great answer](https://codegolf.stackexchange.com/a/11703/7971)**.
1. In Python 3, `print` is a function, and therefore can be abbreviated by `p=print`. Saves `3 * (4 - 1) - 8 = 1` character.
2. In Python 3, `input` is used instead of `raw_input`, saves 4 characters.
3. Instead of `' '*len(V)` you can use `' '*80` (or something similar). This leads to an increased number of trailing spaces, but who cares... if it saves another 4 characers!
4. Now it gets interesting: Instead of strings, use lists! This makes the updating of `S` much easier, but complicates printing somewhat. I'll call the list `T` so I'll not confuse it with the string `S` from marinus.
5. Let's start by turning the *vertices* into a list, not a space-seperated string, which saves 4 characters. The output line `T` has to become a list (`T=[' ']*40`), which costs 2 characters.
6. The printing of the *current line* `T` becomes 5 characters longer: I need brackets to concatenate the lists of strings correctly, I need two more `-` characters (because x and y are only about half as large now), and I need a `*` to make the `print` function take the elements of the list as seperate arguments and print them out seperated by spaces (and not as a list!). (This step was *hard*.)
7. The current line can be updated with a simple `T[x]=T[y]="|"` instead of `S=S[:x]+'|'+S[x+1:y]+'|'+S[y+1:]`, which saves 19 characters.
8. For printing `T` again, and for the final spaced printing of the vertices, asterisks are needed, which costs 2 characters.
9. And just while I am typing this, I see that there is no harm in having an unconnected invisible vertex (`' '`). This allows to create the set of vertices much shorter, saving 4 more characters.
Altogether, the saving is `1 + 4 + 4 + 4 - 2 - 5 + 19 - 2 + 4 = 27`.
```
R=input()
p=print
V=list(set(R)-{','})
T=[' ']*40
for e in R.split():x,y=sorted(map(V.index,e[::2]));p(*T[:x]+["+"+"--"*(y-x-1)+"-+"]+T[y+1:]);T[x]=T[y]="|";p(*T)
p(*V)
```
Example showing the effect of 9.: input `A,B A,C` leads to output
```
+-----+
| |
+---+ |
| | |
A C B
```
] |
[Question]
[
There are 18 primes with distinct prime digits ([A124674](https://oeis.org/A124674)). Namely, they are:
\$2, 3, 5, 7, 23, 37, 53, 73, 257, 523, 2357, 2753, 3257, 3527, 5237, 5273, 7253, 7523\$
Your task is to output this sequence.
# Rules
* [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") [rules](https://codegolf.stackexchange.com/tags/sequence/info) apply. This means valid solutions may use any of the following formats:
+ Given some index \$n\$ it can return the \$n\$-th entry of the list.
+ Given some index \$n\$ it can return all entries up to the \$n\$th one in the sequence.
+ Without taking any index, it can output *all* entries by e.g. ...
- ...printing them one by one (potentially infinitely) or...
- ...returning a list (lazy if the sequence is infinite) or...
- ...returning a generator that represents the whole sequence.
- Note: the solution may print/generate infinitely, but once the entire sequence is output, subsequent outputs must be blank.
* If taken, you may assume the input \$n\$ is always valid. (with 0-based indexing, \$ 0 \le n \le 17 \$; with 1-based indexing, \$ 1 \le n \le 18 \$)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins.
* Standard loopholes apply.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 9 bytes
```
;DẒ;ŒQẠµ#
```
[Try it online!](https://tio.run/##y0rNyan8/9/a5eGuSdZHJwU@3LXg0Fbl//8NLQA "Jelly – Try It Online")
Takes \$1 \le n \le 18\$ on STDIN and returns the first \$n\$
## How it works
```
;DẒ;ŒQẠµ# - Main link. Takes no arguments
µ - Previous chain as a monad f(k):
D - Digits of k, D
; - Prepnd k
Ẓ - Prime?
ŒQ - Unique sieve; Cast k to digits, replace a digit with a 1 if it hasn't appeared before, else 0
; - Concatenate the two lists
Ạ - All truthy?
# - Read n from STDIN. Starting k=0, count up until n k's return true under f(k)
```
The way `ŒQ` works can be shown e.g. with \$k = 75523\$:
```
[7, 5, 5, 2, 3]
ŒQ:[1, 1, 0, 1, 1]
```
It auto-casts \$k\$ to digits, then replaces all but the first occurence of each element with `0`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~12 11~~ 9 bytes
```
Þp~Þu'fæA
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnnB+w551J2bDpkEiLCIiLCIiXQ==)
Prints the sequence infinitely.
Saved a byte by using a trick from caird's Jelly answer.
Saved 2 bytes thanks to emanresu A.
#### Explanation
```
Þp~Þu'fæA
Þp # All primes
~Þu # Filtered by are their digits unique
'fæA # Filtered by are their digits all prime
```
Old:
```
Þun:fpæA∧)l
)l # First n non-negative integers where:
Þu # It has unique digits
∧ # And
n:fp # Its digits with it prepended
æA # All are prime
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + [bsdgames](https://wiki.linuxquestions.org/wiki/BSD_games) + [coreutils](https://www.gnu.org/software/coreutils/), 40
```
primes 2 7777|egrep -v '[^2357]|(.).*\1'
```
[Try it online!](https://tio.run/##S0oszvj/v6AoMze1WMFIwRwIalLTi1ILFHTLFNSj44yMTc1jazT0NPW0YgzV//8HAA "Bash – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 55 bytes
```
lambda x:ord('%5Iāȋवુಹᑵᒙ᱕ᵣ'[x])
```
[Try it online!](https://tio.run/##AWUAmv9weXRob24z/2Y9XP9sYW1iZGEgeDpvcmQoJwIDBQcXJTVJxIHIi@CkteCrgeCyueC3h@GRteGSmeGxleG1oydbeF0p/2ZvciB4IGluIHJhbmdlKDAsMTgpOnByaW50KGYoeCkp/w "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14 11~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞ʒÐÙQiDªpP
```
[Try it online!](https://tio.run/##yy9OTMpM/f//Uce8U5MOTzg8MzDT5dCqgoD//wE "05AB1E – Try It Online")
Doesn't halt after printing all of them so you'll have to press the stop button.
*-1 thanks to @KevinCruijssen*
#### Explanation
```
∞ʒ # All positive integers filtered by:
DÙQ # Digits are unique
i # And:
Dª # Its digits with itself appended
pP # Are all prime
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 72 bytes
```
1¶11¶111¶4$*
+%1`1
2$'¶$`3$'¶$`5$'¶$`7
A`(.).*\1
.+
$*
A`^(11+)\1+$
%`1
```
[Try it online!](https://tio.run/##K0otycxL/P@fy/DQNkMwBhImKlpc2qqGCYZcRirqh7apJBhDKFMIZc7lmKChp6mnFWPIpafNBVTsmBCnYWiorRljqK3CpZpg@P8/AA "Retina 0.8.2 – Try It Online") Outputs all the terms of the sequence. Explanation:
```
1¶11¶111¶4$*
```
Insert 1, 2, 3, and 4 `1`s.
```
+%1`1
2$'¶$`3$'¶$`5$'¶$`7
```
Expand into all possible integers with up to 4 prime digits.
```
A`(.).*\1
```
Remove integers with duplicate digits.
```
.+
$*
```
Convert to unary.
```
A`^(11+)\1+$
```
Filter out composite numbers.
```
%`1
```
Convert to decimal.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 64 bytes
```
Select[FromDigits/@Join@@Permutations/@Subsets@{2,3,5,7},PrimeQ]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277Pzg1JzW5JNqtKD/XJTM9s6RY38ErPzPPwSEgtSi3tASoLj8PKBZcmlScWlLsUG2kY6xjqmNeqxNQlJmbGhj7H0jnlSg4pP//DwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Èì_â fjöX©j}jU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yOxf4iBmasO2WKlqfWpV&input=MTg)
Outputs the first \$n\$ entries in the sequence.
Explanation:
```
Èì_â fjöX©j}jU # input stored in U
È }jU # get first U numbers where the following is true:
ì_ # convert to digits
â # keep unique digits
fj # remove non-prime digits
öX # does this result in the same number?
©j # and check the original is prime
```
[Answer]
# [Perl 5](https://www.perl.org/), 59 bytes
```
(1x$_)!~/^(11+)\1+$/&/^[2357]+$/&!/(.).*\1/&&say for 2..1e4
```
[Try it online!](https://tio.run/##K0gtyjH9/1/DsEIlXlOxTj9Ow9BQWzPGUFtFX00/LtrI2NQ8FsRW1NfQ09TTijHUV1MrTqxUSMsvUjDS0zNMNfn//19@QUlmfl7xf13fMlM9QwMA "Perl 5 – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 213 bytes
```
-[----->+>+>+<<<]>-.---.>.<.>++.<.>++.<.>>-.+.<<.>>.<.<.>--.>.<<.>++.>.<<.>>-.<--.++.<.>--.>.+.<<.>>-.+.<.++.<.>>-.<.--.>+.<<.>>.-.<.++.<.>>+.<--.>-.<++.<.>--.>.+.<++.<.>--.>-.<++.>+.<<.>.>-.<--.>+.<<.>++.--.>-.+.
```
[Try it online!](https://tio.run/##VY1RCoBACEQPJHoC8SLRRwVBBH0End/G1W1pF1Zn3uiu93Jc@7Od7jxxHKO4qjobC7SYqBjReOGjRgOFkpnE2SChcDPeMHU/rG@NSsC@jAeiNh@J/46hEtWs1IclATJC4v4C "brainfuck – Try It Online")
Sets up 3 cells with ASCII 255/5=51 (character `3`) then produces the output hunt and peck style (with increments and decrements as necessary).
Cell 1 is used to print `2` and thereafter the separator `/`
Cell 2 is used to print `3` `5` `7` and thereafter the digits `5` & `7`
Cell 3 is used to print the digits `2` and `3`
It's possible that a 4th cell may lead to shorter code by allowing separate cells to be used for `5` and `7`. I may investigate this later.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 66 bytes
Prints the sequence and keeps looping forever.
```
{for(n=x=2;;)n%--x||x>1|/(.).*\1|[^2357]/.test(x=n++)||print(n-1)}
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/vzotv0gjz7bC1sjaWjNPVVe3oqamws6wRl9DT1NPK8awJjrOyNjUPFZfryS1uESjwjZPW1uzpqagKDOvRCNP11Cz9v9/AA "JavaScript (V8) – Try It Online")
# [JavaScript (V8)](https://v8.dev/), 71 bytes
Prints the sequence and stops.
```
{for(n=x=2;n<8e3;)n%--x||x>1|/(.).*\1|[^2357]/.test(x=n++)||print(n-1)}
```
[Try it online!](https://tio.run/##BcFbCoAgEADA0wRaqKhEgtlFekBEQX1soSJC29lt5lrTGjZ/PpElU8p73J6Ay05Z6M2uLYWKsYyYB4mCcMrrSeK4KN12s@BxD5FkB01DER9/QiTAJP1K@QE "JavaScript (V8) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~58 57~~ 55 bytes
```
n=>'%5Iāȋवુಹᑵᒙ᱕ᵣ'.charCodeAt(n)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k6diZmVXVzV1PNI44nuB0u2Pljd@GDTzgfb2x9O3Ppw0syHG6c@3LpYXS85I7HIGajLsUQjT/O/NVdafpGCRqaCrYKBtUKmgo2CoQWQ1tbWVKhOzs8rzs9J1cvJT9dI08jU1Kz9DwA "JavaScript (Node.js) – Try It Online")
Port of Sisyphus's Python answer.
*-3 thanks to @Arnauld*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₄ÅpʒÐÙSpÏQ
```
Outputs the entire sequence.
[Try it online.](https://tio.run/##yy9OTMpM/f//UVPL4daCU5MOTzg8M7jgcH/g//8A)
Alternative 10-byter that I deemed different enough for its own answer. Make sure to upvote [*@TheThonnu*'s 10-bytes 05AB1E answer](https://codegolf.stackexchange.com/a/258303/52210) as well!
**Explanation:**
```
₄ # Push 1000
Åp # Pop and push a list of the first 1000 prime numbers (up to 7919)
ʒ # Filter it by:
Ð # Triplicate the prime number
Ù # Pop one copy, and uniquify its digits
Sp # Check for each unique digit whether it's a prime number
Ï # Pop another copy, and only keep its digits at the truthy indices
Q # Check if the two integers are still the same
# (after which the filtered list is output implicitly)
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
¢\W░i*δÿ╛ñê╠≤▬J
```
[Run and debug it](https://staxlang.xyz/#p=9b5c57b0692aeb98bea488ccf3164a&i=)
This is Packed Stax, which when unpacked represents the following 18 bytes
```
VIfEccu=^+_+{|pm|A
```
[Run and debug it](https://staxlang.xyz/#c=VIfEccu%3D%5E%2B_%2B%7B%7Cpm%7CA&i=)
```
VIf # filter the following over infinity
E cu= # Are all the digits in the number unique?
c ^+ # Increment this and add it to the list (yielding prime value 2 for truthy)
_+ # add the current value to the list
|A # are all of the values in this list
{|pm # prime?
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
IΦ×φχ∧⬤”)∨∧i#”‹№IιIμIλ⬤…²ι﹪ιλ
```
[Try it online!](https://tio.run/##NYsxCsMwDEWvIjLJ4ILltVMIdGohlF7AJKY1KDbYTq@vRoX8v7zhveUT6lICi8w15Y5TaB1viXus@EpbbEjOOQvkjIUxrzgy40DkPelpsHCPreFU9rNOh/mHzZzERlHTZ8jviN6CWo@y7lwwWVDh2FVELl/@AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
φ Predefined variable `1000`
× Multiplied by
χ Predefined variable `10`
Φ Filtered where
”...” Compressed string `1122121211`
⬤ All characters satisfy
№ Count of
μ Inner index
I Cast to string
ι In outer value
I Cast to string
‹ Is less than
λ Current character
I Cast to integer
∧ Logical And
… Range from
² Literal integer `2`
ι To current value
⬤ All values satisfy
ι Outer value
﹪ Modulo (i.e. is not divisible by)
λ Inner value
I Cast to string
Implicitly print
```
34 bytes for a less inefficient version:
```
⊞υωFυF⁺ι⁻⪪2357¹⪪ι¹⊞υκIΦIυ∧ι⬤…²ι﹪ιλ
```
[Try it online!](https://tio.run/##NYzBCsIwEETvfsXS0wbiwYp46KkI3gpBvyC01S4uSUmy@vkxsTiXnZ1h3rjYMHrLORuJC4qGj@p2Dx8ARcHvGpaIpGEgV8x9ZUrYtMfTudFwUBq2hOpTBH/Oq3BMIJfwYmPCK3Gaw@alrHo31U3PjDfrnjO2Gqjkg5@Efa244lSXc96/@Qs "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υω
```
Start with the empty string.
```
Fυ
```
Loop over the strings of digits.
```
F⁺ι⁻⪪2357¹⪪ι¹
```
Append each prime digit that isn't yet present.
```
⊞υκ
```
Save the new strings to the list of numbers with distinct prime digits.
```
IΦIυ∧ι⬤…²ι﹪ιλ
```
Output only those strings that represent primes.
33 bytes by using the newer version of Charcoal on ATO:
```
⊞υωF⁴«≔ΣE2357⁺κΦυ¬№μκυIΦIυ⬤…²κ﹪κμ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjdnBZQWZ2iU6iiUa1pzpeUXKWiYaCpUc3E6FhdnpudpBJfmavgmFmgoGRmbmivpKATklBZrZOsouGXmlKQWgfT55ZdoOOeX5pVo5OooZGuCgY5CKdA0zoCiTKCwc2JxiQZUPZhdCpR3zMnRCErMS0_VMALp0lHwzU8pzckHGZ0LNsKaq3ZJcVJyMdSdy6OVdMtylGKhXAA "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation:
```
⊞υω
```
Start with the empty string.
```
F⁴«
```
Loop `4` times.
```
≔ΣE2357⁺κΦυ¬№μκυ
```
For each prime digit, prefix it to all previous strings that do not already contain that digit, and concatenate all of the resulting lists.
```
IΦIυ⬤…²κ﹪κμ
```
Output only those strings that represent primes.
[Answer]
# Excel, 145 bytes
```
=LET(
a,SEQUENCE(6^5),
b,FILTER(a,MMULT(N(LEN(a)-LEN(SUBSTITUTE(a,{2,3,5,7},""))=1),{1;1;1;1})=LEN(a)),
FILTER(b,MMULT(N(MOD(b,TOROW(a))=0),a^0)=2)
)
```
[Answer]
# [Factor](https://factorcode.org/), ~~64~~ 45 bytes
```
[ "%5Iāȋवુಹᑵᒙ᱕ᵣ"nth ]
```
[Try it online!](https://tio.run/##AWMAnP9mYWN0b3L/VVNJTkc6IHNlcXVlbmNlcyBwcmV0dHlwcmludCA7CgoxOCBpb3Rh/1sgIgIDBQcXJTVJxIHIi@CkteCrgeCyueC3h@GRteGSmeGxleG1oyJudGggXf9tYXAgLv8 "Factor – Try It Online")
-19 by porting Sisyphus' [Python answer](https://codegolf.stackexchange.com/a/258332/97916).
Returns the nth number in the sequence.
[Answer]
# [SageMath](https://www.sagemath.org/), 288 bytes
Golfed version, [run it online!](https://sagecell.sagemath.org/?z=eJx1jsEKAjEMRH8lt02hLKiIh_0UkaUr7Rppm5LWk_jvthRlL3vJQDIzeU44ABUrhdlnoJBYCiQr4VVMIY5Zw_1hKFbhsFDsywlcC2az2tF4_8tRnpNQsBNUiQWvbQzD-GSKGEzCXERDUkqBY4EEFHv72OrmxmEWb3H7H3M35z3zlgvfRw0nDWcNl48G6VFpUTFxtXiot_ae3B8WdyHVTX0Bod1jNw==&lang=sage&interacts=eJyLjgUAARUAuQ==)
```
from itertools import permutations, chain, combinations; from sage.all import is_prime; print([int(''.join(map(str, p))) for p in chain.from_iterable(permutations(s) for s in chain.from_iterable(combinations({2, 3, 5, 7}, r) for r in range(1, 5))) if is_prime(int(''.join(map(str, p))))])
```
Ungolfed version, [run it online!](https://sagecell.sagemath.org/?z=eJx1kM1KBDEMgO-FvkNu22IZWEU8-SQiS0c7Y2SalqRzEt_dSbvKXjyVJvm-_CxcMmBL3ErZBDDXwg1q4ry32LCQBHj7iEjHU_KMNILWLApKXNMUt-2XQ7lUxpysseYdV2wCz_B1H-AhwGOAp29rZJ8l9XjXTuq56ABx3pK77eGGIQB7WAoDAxJwpDW5c4At0bXAwx2cvbdGp_5PfLuRkyEUFV7nOXDaO-2Qmjudps-C5HKsThoHqN4PqCrUO2lHXVahF-pJ0mT34PJ3DEf-VQ9yfA7zQPwPeBN-xg==&lang=sage&interacts=eJyLjgUAARUAuQ==)
```
from itertools import permutations, chain, combinations
from sage.all import is_prime
digits = {2, 3, 5, 7}
subsets = chain.from_iterable(combinations(digits, r) for r in range(1, len(digits) + 1))
perms = chain.from_iterable(permutations(s) for s in subsets)
nums = (int(''.join(map(str, p))) for p in perms)
primes = [n for n in nums if is_prime(n)]
print(primes)
```
] |
[Question]
[
## Introduction
Our goal is to efficiently find the maximum of a large amount of (redundant) data.
We define the outer product of vectors \$A\$ and \$B\$ as a matrix containing the products of all entries of \$A\$ with each entry of \$B\$. (see [outer Product](https://en.wikipedia.org/wiki/Outer_product))
$$
A\otimes B := A\cdot B^T = \left(\begin{array}{rrr}
A(1)\cdot B(1) & A(1)\cdot B(2) & \ldots & A(1)\cdot B(M)\\
A(2)\cdot B(1) & A(2)\cdot B(2) & \ldots & A(2)\cdot B(M)\\
\ldots & & & \ldots \\
A(N)\cdot B(1) & A(N)\cdot B(2) & \ldots & A(N)\cdot B(M)\\
\end{array}\right)
$$
Here \$A\$ has \$N\$ entries (size \$N\$) and \$B\$ has \$M\$ entries.
In this way, the outer product of \$K\$ vectors yields a \$K\$-dimensional array (tensor of order \$K\$). If \$N\_1,N\_2,\ldots,N\_K\$ are the sizes of the vectors, we get a total of \$N\_1\cdot N\_2\cdot\ldots\cdot N\_K\$ products.
Example:
$$
\left(\begin{array}{r}1\\ 2\\ 0\end{array}\right)\otimes
\left(\begin{array}{r}1\\ 3\end{array}\right)\otimes
\left(\begin{array}{r}-5\\ 7\end{array}\right)=
\left(\begin{array}{rr|rr|rr}-5 & 7 & -10 & 14 & 0 & 0\\
-15 & 21 & -30 & 42 & 0 & 0\end{array}\right)
$$
The result is a \$3\$-dimensional array consisting of three \$2\times2\$ slices. We want to determine the maximum of the array, which is \$42\$ here.
An alternative formulation is: Find the maximum of all products that contain exactly one number from each vector.
Of course, we can do all the multiplications and keep track of the maximum. However, it is possible to use only a number of operations that depends linearly on the length of the input sequence (total number of vector entries). This means that we can, for example, process an input of \$13\$ vectors each of size \$37\$ in less than one second on a common computer.
Thus, the problem reads:
## Challenge
* "Determine the maximum of the outer product of given integer-valued vectors. Ensure that the algorithm runs in linear time with respect to the length of the input sequence."
* The input contains at least one vector.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!
## Test cases
We leave the input format to the free decision. In the test cases we use \$,\$ to separate vector entries and \$;\$ to separate vectors.
So the example above is coded as: \$\quad 1,2,0;1,3;-5,7\$
* \$0,1,2\qquad ->\qquad 2\$
* \$-2,-1,-2;1,2,3;-1,-2\qquad ->\qquad 12\$
* \$-2,-1;-3,-4;-3,2,1;1,4,-4\qquad ->\qquad 96\$
* \$-1,-2;3,4\qquad ->\qquad -3\$
* \$-1,-2;1,-3,2;1,-1,-2\qquad ->\qquad 8\$
* \$1,0,-2;0,-2,1;-2,1,0;-2,0,1;0,1,-2;1,-2,0;1,0,-2;0,-2,1;-2,1,0;-2,0,1;0,1,-2;1,-2,0;1,0,-2;0,-2,1;-2,1,0;-2,0,1;0,1,-2;1,-2,0;1,0,-2;0,-2,1;-2,1,0;-2,0,1;0,1,-2;1,-2,0;1,0,-2;0,-2,1;-2,1,0;-2,0,1;0,1,-2;1,-2,0;1,-2,0;1,0,1\qquad ->\qquad 1073741824\$
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 84 bytes
```
f=([a,...x],m=1,n=1)=>a?f(x,Math.min(...q=a.flatMap(c=>[c*m,c*n])),Math.max(...q)):n
```
[Try it online!](https://tio.run/##3VBLDoMgEN33JGAGIuiqCfYEnoC4mFBtbRRsNY23twim6cL2AN3Mm5n3gcwNnziaRztMzLpzvSyNIhqBcz5X0CsBVgmqCjw1ZIYSpyvvW0s8fVfImw6nEgdiVKFN0oNJbEXpJsM5yCg92sU4O7qu5p27kIZozSQwAUxWoAVIyDzG2dsPu@JVkQHLI0oQwZqvm13Plp7Bb96DT4vN1w8ISKN6hfDyCpDGJg0bX9@JMlD/6/qwi3Cw5QU "JavaScript (Node.js) – Try It Online")
Keep trace of min and max
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 10 bytes
```
Ṃ,ṀƊ×þFɗ/Ṁ
```
[Try it online!](https://tio.run/##y0rNyan8///hziadhzsbjnUdnn54n9vJ6fpAzv///6OjDXWMdAxidYC0MZDUNdUxj40FAA "Jelly – Try It Online")
*-2 from using Ɗ and ɗ for grouping instead of separate lines*
This submission is a monadic link. For input, use a list of the vectors (i.e. `[[1,2,0],[1,3],[-5,7]]`) as the first argument. This assumes `[]` is not valid input.
This is similar to [@l4m2's algorithm](https://codegolf.stackexchange.com/a/256295/60693), but it starts with the first vector instead of `(1, 1)`.
Explanation:
This works by taking the (min, max) of the first vector and finding all products of either with elements of the second vector. The same thing happens with the result and the third vector, then that result and the fourth, etc. Then, the answer is the max of the last result.
```
Ṃ,ṀƊ×þFɗ/Ṁ
Ṃ # List Minimum
, # Pair
Ṁ # List Maximum
Ɗ # Group the last 3 links ("Ṃ", ",", and "Ṁ") as a monad
×þ # Outer product
F # Flatten
ɗ # Group the last 3 links ("Ṃ,ṀƊ", "×þ", and "F") as a dyad
/ # Reduce
Ṁ # List Maximum
```
This is my first time using Jelly, so there is probably still room for further golfing.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 29 bytes
```
Max@*Fold[{#2Min@#,#2Max@#}&]
```
[Try it online!](https://tio.run/##5Y4xC8IwEIX3/oqDQAdJsE27KpncCu6lQ1CLAduCdBBCfnu8HIlQib/AIeS7l/feZdLr/Tbp1Vy0H@HgO/1Su9PyuPaWyc7MinG8UWSuHPz5aea1ZyCOMPZsGKCEvSrAWiskB1HjkY6DRcC5CRhFxwuAZCO9QWoToVzHYEt68n8q0ZRRA4R44s0yHKpkJIhLCPAtcUU6Rsi26ZbRlq@iSL7tVxVF/uRjX5@snXP@DQ "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 85 bytes
Port of @l4m2's JavaScript answer
```
f=lambda x,y=1,z=1:x and f(x[1:],min(q:=sum(([c*y,c*z]for c in x[0]),[])),max(q))or z
```
[Try it online!](https://tio.run/##TU/RboMwDHznKyztoQlzJJyglSGlPxLlgdGhIY2UQioFfp4l0Gl7Ot/57LPHxX/dnKrGads6/d0MH9cGAi6acNVUB2jcFToWDNUWh96xe63nx8CYafMF23y13W2CFnoHwRSWo7Gc49AEduc8dtbNf85@Bg0mM0ZIFIRCWjSEElXEg1uEFyD5a0m6QlEeKJH2gTIpu/P9LTmfmxQ@VaH@qRHi5FH8RVTRQVjsPFf0ejCyNsUXZ3UuqZJlZrP0lU9f7efX49Q7zzyexOWEHfOcbz8 "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
1$vsß‚yδ*Z
```
Port of [*@EvanBailey*'s Jelly answer](https://codegolf.stackexchange.com/a/256324/52210), which in turn uses the same approach as [*@l4m2*'s Javascript answer](https://codegolf.stackexchange.com/a/256295/52210), so make sure to upvote both of them as well!
Input as a list of lists.
[Try it online](https://tio.run/##LZW7jRxJEESdOYnIAur/ceUWK5AABUoUFiBA7ew4hU7QA@o0go4sX0S1MOienq7IyMiInK9vHz99@fz@Xv759vbrx5///v/@@@eHf9/fX15aj3Mix56RyoqdI3VuD596uHLZUbi0HCvHaHF6pLFjt0g70hpROVO4Hby1Smxuz/AvCVRQ9grO6Fy7VUbhls/sr/GSTqXIup/BfQd5nRicjSouSwjUL1F1cBlXFfmxxz4BZOJQyTFLTCB2dY0ChQ67MaLvWDX6iToMsUR/UF6v67xI0ks10oJrmXqDr1WQAHPDYVAQB35Srse4GqRergCzGA6iKrQuF2BUgnfBncJtoQN1igCYO0Z3O22oEuSQhw7hmxhJyVcVWp26lFBH2VgqiuR6hTdB7aacCgwYVrUs1rgIjgFVS0rDEn9pyFuj7N1AEo2R7/tgZJXa9TaIQKO5vy6gcxss1YcWM@miPjVLKHIpLdYdl0xFmwmz6Em3QSCwe8zuAq25ScZuidRo7ddZGpY8iAHVtetrqMOCqTcwpTfaybnDk6aFue1f96vJiN2wZF2wGBsKtoLrigajZ9woyA2UVrbeacjwtKOczByUVc9tX9sqNup/avCnSIu9bkvtCIwgnWw6BlghDLm/L0FKDnBK8@zazR@z5eC4NuSxLCLayiVSKgtjOJh2nvp81PHIJaBwZ75zOIjGpIlmkzriUkSgy8kqi9LwJ503z9Vt0XUVkFogaFHuYFWr34kq69RWnvczO2rVW9WZ3I6VXMZ1KcIsnNS2/ZelslNTXUZwUKeOFoYOoYUGg37Sozz425HyBnC2llXYx0VKv7qUey49ruSRnsrKekrVahKyjodcDUSekQQuim6T5abGnbOsdpqqYlsO0ItiqTWjdai0ctzJlh7yDmtIyA@ndZtr9hFyZlXXXFWZzj2ULumng@e25CTkJABT@3BJ5P4styrPKCaO5/SKGFf9edep3I1rUKIYnygsB82M57OA6VG7@Zy7@6ihoNt73uj1/g8U759x3U1JqI/2/GMc@xTeN09EQy/xpTzLX5OvV@VxfantXsbr618) or [verify all test cases](https://tio.run/##lVbLjhtFFP0Vyysmuo263lUL5E0@AHYIM4vJ4IwsIht5HmCkSBELPoAlQiJiC0uEQCyQ4iVSPmJ@xJxzb2tCSDJ0L2aqu7rqPs499x5vL88erVfHm/1iPrv99rvZfLE/uo93N5eHH2@ffb9/@euDT45PT17@/nCxv/3ml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YipWHJBeQQ4e1WTaJ6RuRYlEvqsjadpkUmAEw2QOQ8LQY7DcPPkDNtE2zPriEiGfrZxSnaDNUDCqX20QtFG04jzMICRI2dzazb74IONrtzTie5NB5zOn2TshkuEnsKgGE15iritn9AaPIQXNwx/Vt4bysl4yenu0mQhYs9OkCKl2RgxkkGKlBJjxYiHR8sRD98rSPKaHOH4eEGixE@RJP5meLsoyZuSZGNyrCjh9ARZ4hB6XZjkHlmykTVSmPTnznhpYpZ34iQjpEmpNV6ccHyKPLFCTcbJE6V0vEAx0XESJZFhjJcoZfhUkeKl@2RK7kSKkIyTKXJwmlDxt9i7pEreECrWcoJUaYoTxEp/2r9FruRdYsUqjZUrnVkTBIuj5U6y5H8ES42Plyw9Pla0jOUmDCNESwf5eNnSUCYJ1@mx6zbb7snZ1/t/AA) (with brute-force verify `.»â€˜Pà` in the footer for the smaller test cases).
**Explanation:**
```
1 # Push 1
$ # Push another 1, and the input-list
v # Pop the input-list, and loop over each inner list `y`:
s # Swap so the current list is at the top
# (or simply swap the two 1s on the stack in the very first iteration)
ß # Pop and push the minimum (1 remains 1)
‚ # Pair the top two values together
# ([1,1] in the first iteration; [max,min] in every other iteration)
δ # Apply double-vectorized
y # on this pair and list `y`:
* # Multiply
Z # Push the flattened maximum (without popping the list of lists)
# (after the loop, the final flattened maximum that's on top of the stack is
# output implicitly as result)
```
It runs in \$O(\sum L)\$, where \$L\$ is the length of each individual list.
In term of iterations, it'll do \$\sum(6L)-2L\_n\$, where \$6\$ comes from \$2\$ (for \$[min,max]\$) times \$3\$ (once for the double-vectorized to create the list; and then once each to retrieve the flattened maximum and minimum of this list of lists); minus \$2\$ times the length of the last list \$L\_n\$, since we won't retrieve its minimum. E.g. input `[[1,2,0],[1,3],[-5,7]]` has \$6\times3+6\times2+6\times2-2\times2=38\$ iterations and an input of \$13\$ lists of size \$37\$ each has \$13\times6\times37-2\times37=2812\$ iterations.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
⊞υ¹FA≔⁺×ι⌊υ×ι⌈υυI⌈υ
```
[Try it online!](https://tio.run/##TcwxC8IwEIbh3V@R8QKXobVbJ3FyEDK4hQyhqD1IUsnlxH8fW0R0@uD54J3mUKYlxNas8AyCqtPj7rYUBaf8kApaqwMz3TPYKAwXSlcGQnWmTEkSiNaofhpeX11Z1pQtlCscA1f4P8fWnHOmR9N5dGaPZvhsjxt0OGzifTPP@AY "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Another port of @l4m2's algorithm.
```
⊞υ¹
```
Start with a minimum and maximum of `1`.
```
FA
```
Loop over the input vectors.
```
≔⁺×ι⌊υ×ι⌈υυ
```
Multiply the current vector by both the minimum and maximum so far.
```
I⌈υ
```
Output the final maximum.
[Answer]
# [Haskell](https://www.haskell.org/), 80 bytes
```
r a=[minimum a,maximum a]
f=last.foldl1(\a b->r$map product$sequence[a,b]).map r
```
[Try it online!](https://tio.run/##JYlLCsMgFAD3PYULFy08A6bZ2otYFy@JUqnPGD/Q21skqxlmPli@NoTeM0OlyUdPjRgC4e8yc3MqYKmTO8Ie5P2NbBWvzAkTS/nY21Z5sWezcbMaYTWPaazcCX1UKftYudNazCCkAS2eIJaLM4wgYRnF9D8 "Haskell – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org), 50 bytes
```
m.foldl1(\x->((*)<$>[minimum x,m x]<*>))
m=maximum
```
[Attempt This Online!](https://ato.pxeger.com/run?1=3ZGxCsIwFEVx9SuCOLTlpTRpB4faxVnoKKRBCloMNlXUQv_FpUsRBz9Iv8akT1T8BIfkvNx3711yvmzy43ZdllcxootZmo5kV5Apybr6VNDJnWu_2JWrkjlZQxPH8dx4nAitKqVrTRowR8Ze4rpDPdV5Y1VMPgY3navKVOl8P18SZ39Q1Yn4pHCJEIJyoAwolyAYcAgN8S2BvLZWCoFGSA6s90ZWQdMrH8KPYGD8OHw6GQS4tujLLCDAIegVc78reL_639RXnEkp8dfaFvkE)
-2 bytes thanks to [@ Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string).
A port of [my Mathematica answer](https://codegolf.stackexchange.com/a/256314/9288).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) ~~14~~ 11 bytes
```
?ƒλ₍gGẊvΠ;G
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI/xpLOu+KCjWdH4bqKds67w7cqOztHIiwiIiwiW1stMiwtMV0sWy0zLC00XSxbLTMsLTIsLTFdLFsxLDQsLTRdXVxuIl0=)
Any improves welcome!
For input needs always list of vectors,
so first test case should be [[0,1,2]]
## Explanation
```
? # Get input
ƒ # Begin reduce list of vectors by lambda
λ # Open lambda
₍gG # [min, max] of current vector
Ẋ # Cartesian product with previous vector
vΠ # Vectorised product
;G # Close lambda and print total max
```
[Answer]
# [R](https://www.r-project.org/), 42 bytes
```
function(L)max(Reduce(`%o%`,Map(range,L)))
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NHMzexQiMoNaU0OVUjQTVfNUHHN7FAoygxLz1Vx0dTU/N/mkZOZnGJRrKGgY6hjhFQREFZwYgLLqprpKNrqKNrpKmTrAGU1zEGMSAiYKWG6GrB8sY6uiZQhpGOIUSvCUgMrMfS7D8A "R – Try It Online")
Using `outer` instead of `'%o%'` is equivalent. Fortunately, `range` returns a vector of `c(min,max)` instead of `max - min` as you might otherwise expect. Based, as many others, on [l4m2's answer](https://codegolf.stackexchange.com/a/256295/67312)
Also, random note, `range` automatically flattens `list`s.
] |
[Question]
[
Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details.
Related to [AoC2016 Day 1](https://adventofcode.com/2016/day/1), Part 1.
---
You're airdropped near Easter Bunny Headquarters in a city somewhere. "Near", unfortunately, is as close as you can get - the instructions on the Easter Bunny Recruiting Document the Elves intercepted start here, and nobody had time to work them out further.
The Document indicates that you should start at the given coordinates (where you just landed) and face ~~North~~ East. Then, follow the provided sequence: turn right **60 degrees**, then walk forward the given number of blocks, ending at a new intersection.
"What, 60 degrees?" You think, and you look around. Then you realize the city is not quite like what you imagine; the streets in this city form a **[triangular grid](http://mathworld.wolfram.com/TriangularGrid.html)**.

Anyway, there's no time to follow such ridiculous instructions on foot, though, so you take a moment and work out the destination. Given that you can only walk on the street grid of the city, how far is the shortest path to the destination?
For example, if the instructions are `[1, 1, 0, 2]`, it means to:
* Turn right 60 degrees and move 1 block forward
* Turn right 60 degrees and move 1 block forward
* Turn right 60 degrees and stay in place
* Turn right 60 degrees and move 2 blocks forward
In the end, you end up at just 1 block west of the start.
**Input:** A (possibly empty) list of non-negative integers. If you encounter a 0, it means to turn right 60 degrees but stay in place.
**Output:** A non-negative integer indicating how far away the destination is from the current position, measured in triangular taxicab distance.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
[] -> 0
[1, 1, 1] -> 2
[1, 1, 0, 2] -> 1
[1, 2, 0, 0, 0, 2, 1] -> 4
[1, 2, 3, 4] -> 6
```
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
p=q=0
for i in input():p,q=i+p-q,p
print max(0,p,q)-min(0,p,q)
```
[Try it online!](https://tio.run/##TU3BDoIwDL3vKxpOEEcypqclO@LVizfCAbHGRRljjghfPwdMY/Pavvfy0prZ3XvNfdtfESQkSeKNHCQjt96CAqUDzOjSTBg6SLUz@UANMVZpB10zpYwGP8s7pSP14QQh77t6IpztiIJAKGdnAThhmy6PstXDqUXjoDwdS2vDt@YFKOBisXn4qiZVQaGI658xCnwTfBUb@C8S2J7CIebZ0tuI87tY/QE "Python 2 – Try It Online")
62 bytes version suggested by [loopy walt](https://codegolf.stackexchange.com/users/107561/loopy-walt)
---
# [Python 2](https://docs.python.org/2/), 64 bytes
```
p=q=0
for i in input():p,q=i-q,p+q
print max(p,q,p+q,-p,-q,-p-q)
```
[Try it online!](https://tio.run/##TU3BDoIwDL3vKxpOELdkTE9LOOLVizfCAbGGRYVtjghfPzdAY/P6Xvvy0urZdUMvfDtcEQpIksTrwhSc3AYLClQfoEeXZlJTUyhmqN4Zoq3qHTybKQ1udCjTlEVmJvPhCCHvTj0QznZESSCUs7MEnLBN46ts8XBqUTsoT8fS2vCveQFKuFhs7r6qSZVTyDf5nzgFsS5iWVaIXyRMewqHLc9jr7TxV3j9AQ "Python 2 – Try It Online")
-3 bytes by [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) and [xnor](https://codegolf.stackexchange.com/users/20260/xnor).
---
# [Python 2](https://docs.python.org/2/), 94 bytes
```
a=input()
p,q,r=[sum(a[i::6])-sum(a[i+3::6])for i in[0,1,2]]
print max(map(abs,[p-r,q+r,p+q]))
```
[Try it online!](https://tio.run/##TY5Bi8IwEIXv@RVDTwmdgo3iIdCjXveyt5BDrCMGbZtOU7b@@m6tIg4D877Hgzfxka5dq@e6OxNUkGXZ7KvQxjFJJSL2yJUdxkZ6G4zZO1W8Id@ueOkYAoTWbrBE7ZyIHNoEjZ9k46P0pwFtLBj7nDHmvVNqXiqE@LuGO8Evj2QELJP4YYAmquXzEbV6NNUUExx@jgfmpccPQAZOTP42WydsiVC@z7faIOgX6BVeqz@RRW0Rdu4f "Python 2 – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 49 bytes
```
a->p=q=0;[[p,q]=[i-q,p+q]|i<-a];normlp([p,q,p+q])
```
[Try it online!](https://tio.run/##RY3BCsIwDIZfJezUYgKzepvdi4QccpkU5kyLF8F3r@0UBj/h@5LAb1oS3a0uEKvSbDHHcWI2zBI5UUY7ZfmkG6lM27M8VnP9uK99VbP17RRoBitpezUcugywOPUegVnaOCP0HDgihL@F3X4Jx1PDC8JVWskX "Pari/GP – Try It Online")
A port of [@tsh's answer](https://codegolf.stackexchange.com/a/238117/9288). Make sure to upvote that answer as well!
---
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 53 bytes
```
a->vecmin([normlp(Pol(a)*x^i%(x^2-x+1),1)|i<-[0..2]])
```
[Try it online!](https://tio.run/##RY3hCsIgFIVf5TIIrqVjWj/XnqH/4kCiheDcRWI46N1NKxgcLt8H93DIRieelCe4ZiuG9XGfXUAdljh7wtvi0bJjGt0B06hEOknGJXu7XuiubZUxLFsiv6EFMQBFF14FmyoNTKXLOGhtypEcanbsOKi/qa/9ovangmcOlzryAQ "Pari/GP – Try It Online")
If we see the city as the complex plane, then the instructions \$[a,b,c,\dots]\$ will end up at the point \$a+b\ x+c\ x^2+\cdots\$, where \$x={(-1)}^{1/3}=\frac{1}{2}+\frac{\sqrt{3}}{2}i\$ is a root of the equation \$x^2-x+1=0\$. So we can convert the input into a polynomial with variable \$x\$, and mod \$x^2-x+1\$. This gives the destination in the form \$a+b\ x\$.
`normlp(...,1)` is the usual taxicab distance: `normlp(a+b*x,1)=abs(a)+abs(b)`. If the destination lies in the first or the fourth sextant of the plane (i.e., \$a+b\ x\$ where \$a,b>0\$ or \$a,b<0\$), this already gives the correct result. In other cases we need to rotate the destination by 60° or 120°. 60° rotation is just multiplying by \$x\$, 120° is multiplying by \$x^2\$. We try all possible rotations and take the smallest taxicab distance.
[Answer]
# [R](https://www.r-project.org/), 62 bytes
```
function(x,p=0){for(i in x)p=p+i-(F=F+p);max(abs(c(p,F,p+F)))}
```
[Try it online!](https://tio.run/##lc2xDoIwEIDhvU9xiUsvHElbiIupY1/COCAB7WBpKsYmxmdHKJjAaHpT@/W/MNy6V1sFPbRPV/e2czyS1wLfbRe4Besgotc@szk32mQeD/cq8ury4DX3ZMhnBhE/S2a8lCRJkEKEHZwkwTiCQJ0hP4JkC7Oub65N4GJm6VGwTUOuCzIJxf7bMjE1sumoVVAlPI/6xcvtr4LKtS8IysT2bPgC "R – Try It Online")
Approach based on xnor's comment on [tsh's answer](https://codegolf.stackexchange.com/a/238117/95126).
[Answer]
# JavaScript (ES6), 90 bytes
```
a=>a.map(n=>b+=n*~-(s="1221")[a+=n*~-s[d%6],++d%6],a=b=d=0)|(A=Math.abs)(a)+A(b)+A(a-b)>>1
```
[Try it online!](https://tio.run/##bc3bCsIwDADQd7@iCEJrd2sde0thH@AXjD2ku3hhrsMOn8Rfr7v44mgICYST5I4vtNXzNoxhb@rGteAQFEYPHGgPSnPoj5@QWtgLKcWeFbhObFEfsjLgfGkIGmpI2JvmcMbxGqG2jCLjOdVzwVAzpYSrTG9N10SdudCWFiVjxBNxTJLdhoqAzLndmKj00yQg8k9PVHioXOia8vdhoqmfngKSbq9m7gs "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 63 bytes
Using the optimization suggested by xnor on [tsh' answer](https://codegolf.stackexchange.com/a/238117/58563).
```
a=>a.map(n=>[p,q]=[n-q,p+q],p=q=0)|Math.max(p,q,p+q,-p,-q,-p-q)
```
[Try it online!](https://tio.run/##bc07DsIwDAbgnVNkTITTpqFiS2/ACaIMVml5qORBK8TA3UMCLFSxfnnxZ/uKD5z7@8Uv3LrjEEcVUXVY3dBTqzrtIRilLQ/gt8GAV0EJ9jrgck7kSdM4D4B74LnzwGLv7OymoZrciY5UG8ZIoeqaiM2KNkBy1huJyjIVQOSfTrQpUPmh38jfh0TbMt0BaddX9/EN "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~37~~ ~~28~~ 26 bytes
```
F³⊞υ⁰FA≔⟦⊟υ⁻ι§υ⁰⁺ι⊟υ⟧υI⌈↔υ
```
[Try it online!](https://tio.run/##JYwxD4IwEEZ3f8WNd8mZiLgxNU4MJN1Jh4ooTUpLaM/w7yvK@r73vmGy6xCtL@UVV8CaQEuaUBgu1Jz@rA2LZCQClZJ7B@x1XFCIoXNBEjoGldvwHLej2gftD36IZBhkP9OrCxnvNmXs7OZmmVE9UvSSx59F1JTS9xXDlaFmuBlTzh//BQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Now another port of @tsh's original Python answer (the subsequent golfs don't apply to Charcoal).
```
F³⊞υ⁰
```
Start with an array of three zeros.
```
FA
```
Loop over the input movements.
```
≔⟦⊟υ⁻ι§υ⁰⁺ι⊟υ⟧υ
```
Update the array (note that the values are in reverse order from @tsh's version, allowing two of the values to be popped from the array, saving a byte).
```
I⌈↔υ
```
Output the maximum absolute value.
Alternative formulation, also 26 bytes, based on @GB's idea that the original array only needs a single zero and cyclic indexing will expand it to three values:
```
⊞υ⁰FA≔⟦⁺ι§υ¹⁻ι§υ²§υ⁰⟧υI⌈↔υ
```
[Try it online!](https://tio.run/##ZYyxCsIwFEV3v@KN70GEVt06BacOhewhQ6zVBtK0JHnSv4/pJni3yzmccbZxXK0vRXGakQU01J1eawTsw8YZiUCm5N4BtfKc0AmQuQ/PaT/klkjA4MIfuBzg5zdkBHBNq@hCxrtNGQe7u4UXlI@0es4TMtV1pWjd1oKAq4CbMeX88V8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ⁰
```
Push a zero to the predefined empty list.
```
FA
```
Loop over the input movements.
```
≔⟦⁺ι§υ¹⁻ι§υ²§υ⁰⟧υ
```
Update the list (this is back to the original order from @tsh's original Python answer).
```
I⌈↔υ
```
Output the maximum absolute value.
Previous 28-byte canvas-based answer using @Arnauld's adjusted square coordinates:
```
FLθM§θι✳÷×⁴ι³≔⊘Σ↔⟦ⅈⅉ⁺ⅈⅉ⟧η⎚Iη
```
[Try it online!](https://tio.run/##NY0xC8IwFIR3f0XGF4iD2s2ptIMFhYIOSukQ22fzIE1okgb/fYyIy3EH390NSrrBSp3SyzoGZzRTULBwzi42IpShMSO@YRGMuGA1ORwCWQONCTVFGhFuNKOH4gccOOfHTek9TQZOUkcc4brOUD691WtA6O6QscdXWr16@Efe56ZgKrcrjdJBNq0jE6CSPoDKsyl13U6wfX4RrOj7tI36Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FLθ
```
Loop over each step.
```
M§θι✳÷×⁴ι³
```
Make a movement in each direction in turn, but skipping northwest and southeast.
```
≔⊘Σ↔⟦ⅈⅉ⁺ⅈⅉ⟧η
```
Calculate the final distance as half the sum of the absolute values of the two coordinates and their sum.
```
⎚Iη
```
Reset the cursor and output the distance.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 58 bytes
```
->l{l.reduce(0){|s,x|[x+s[1],x-s[2],s[0]]}.map(&:abs).max}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOkevKDWlNDlVw0CzuqZYp6ImukK7ONowVqdCtzjaKFanONogNrZWLzexQEPNKjGpWBPIrKj9X6CQFh1tqGMYG8sFZSoY6SgYwBCQDZT6DwA "Ruby – Try It Online")
Port of tsh's answer to Ruby
Starting with [0,0,0] encoded as (0), the first iteration of `reduce` will transform it automatically.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
0ÐIv(2Fy+Š])Äà
```
Port of [*@tsh*' top Python answer](https://codegolf.stackexchange.com/a/238117/52210).
-1 byte thanks to *@Neil*, which also allowed a second byte to be saved
[Try it online](https://tio.run/##yy9OTMpM/f/f4PAEzzINI7dK7aMLYjUPtxxe8P9/tKGOAhAZ6CgYxQIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSvdJ/g8MTKss0jNwqtY8uiNU83HJ4wX8lvTCd/9HRsTrRhjqGEBJOG@gYgVlGQBYIGkFljHSMdUxiYwE).
**Explanation:**
```
0Ð # Push three 0s, let's call these a,b,c
I # Push the input-list
v # Pop and loop over each item `y`:
( # Negate the top item
2F # Loop 2 times:
y+ # Add the current integer `y` to the top
Š # Tripleswap x,y,z to z,x,y
# (after this inner loop, a,b,c is y+b,y-c,a)
] # Close both loops
) # Wrap all three values into a list
Ä # Get the absolute values of each
à # Pop and push the maximum
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~14~~ 13 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
0∙êô,\ì+\?ß±╙
```
Port of [*@tsh*' top Python answer](https://codegolf.stackexchange.com/a/238117/52210).
[Try it online.](https://tio.run/##y00syUjPz0n7/9/gUcfMw6sOb9GJObxGO8b@8PxDGx9Nnfn/P5ehjiEIQ0kDHSMgbQSkQdAILGqkY6xjAgA)
**Explanation:**"
```
0∙ # Push three 0s, let's call these a,b,c
ê # Push the inputs as integer-list
ô # Foreach over these integers,
# using 6 characters as inner code-block:
# (implicitly push the current loop-integer, let's call this y)
, # Subtract the second item from the top: y-c
\ # Swap the top two values on the stack
ì+ # Add the loop-integer `y`: b+y
\? # Swap back, and tripleswap: a,y-c,b+y to b+y,y-c,a
ß # After the loop, wrap the three values into a list
± # Get the absolute value of each
╙ # Pop and leave the maximum
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Rust](https://www.rust-lang.org/), 101 bytes
```
|i|{let mut p=(0,0);for n in i{p=(n-p.1,p.0+p.1)}let(p,q)=p;vec![p,q,p+q,-p,-q,-p-q].drain(..).max()}
```
[Try it online!](https://tio.run/##dZDRasMwDEXf@xVKH4a9ysbJRh8asn1ICSNsDhgaz3GcdZD62zM5KYOOVQhL6Fx0kf04hLm10DXGMg7TBihOOkAL1Xwxlyn13RjAVUyh4mX76cGCoZxoZIWTOTqpdlR5JDFz2PPKlV/6PTtSj27Xo3Ao0iv6Wn74ZCUll13zzXick2O5@KbdzFg3BoTGDmfteXJ6OC40BVvW1giK459hjpCSWHGHKUKE8/9wseA1i3XN8x3dEyHC@yuur5@Wwnljw8lmbDsdXiOIF5jiFuH2pPJX3gyD9uFN9xlr17u5HO3ZN45xhMcbfdzE@Qc "Rust – Try It Online")
Port of [@tsh's answer](https://codegolf.stackexchange.com/a/238117) as well.
`error[E0658]: destructuring assignments are unstable` >:(
[Answer]
# [Python 3](https://docs.python.org/3/), 94, 90 bytes
```
def f(I):
a=b=c=0
for i in I:a,b,c=2*i-b,-i-c,-i-a
return max(map(abs,(a-b,b-c,c-a)))/3
```
[Try it online!](https://tio.run/##ZU@xjsIwDN3zFVamBDl3bYoYkHw7Oxt3Q1JaYQnSqgR015/vJUGdkCz7@flZfh7/4mUIzbKcux56ddB7AY48tVQJ6IcJGDjAYe/QY0t2w8ajYdPm5ARMXXxMAW7uV93cqJy/o3JJ4pOiNU5r/dksR5JSnn7AfEElTjVCXbB94be2QrCFqQtjC/MKu4q366hB2BZml2583McrRyW/g9Qim4/Z/DG9xDhQNtg93RXjqst7UmsBM/WKUx0nDlExzjgTDXr5Bw "Python 3 – Try It Online")
[Old version](https://tio.run/##ZY9Nb4MwDIbv@RVWTknlbBCqHjq5d@69dTskDFRLNCCa7oM/z0IqTpMsfzx@Ldvjb7wOoVqWz7aDTtX6KMCRp4YKAd9X7luoj4y7muo3hx4bsjs2Hg2bZnVOwNTGxxTg5n7UzY3K@TsqlyQ@KRrjtNav1XImKeXlA8wJCnEpEcqc22f@rywQbCZlJjaTp9lNvN9aFcI@k0Pa8XIfe45KvgepRTdMEIEDnNNbjAOtB7Zfrse46dY5qbWAmTrFKY4Th6gYZ5yJBr38AQ "Python 3 – Try It Online")
Uses barycentr-ish coordinates. Not 100% sure this is correct even though it passes all tests.
P.S.: I notice now that this is quite similar to @tsh's earlier answer.
P.P.S.: I've given up on this one; @tsh seems unbeatable.
[Answer]
# TypeScript Types, 397 bytes
```
//@ts-ignore
type a<T,K=keyof T>=T extends T?keyof T extends K?T:never:0;type b<T,P,N>=T extends[N,...infer T]?T:[P,...T];type c<U,L=a<U>>=[...L,...a<U extends U?L extends U?never:U:0>]extends[{},{},...infer X]?X["length"]:0;type M<A,T=[],U=[],V=[],F=0,B=1,N=[]>=A extends[infer Z,...infer C]?Z extends N["length"]?M<C,U,V,T,B,F>:M<A,b<T,F,B>,b<U,B,F>,V,F,B,[...N,0]>:c<[...T,1]|[...U,2]|[...V,3]>
```
[Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4AVAGgGkBeAa3R2QDNDyA+W8w9AD3DpEAE0jsA-I2Zse-QSLHVx5AFyJ0AN3SoVABgDcuAoQBGFSgAVKAOS6yBQ0QG1rlAHQfYiFtvYBdZRUnKw83cj9DfCIAY1IAVUoAGVoyOI4uJ1DE9w9U3gcFQjjxRPz5USLxdS0dOL0OPzlHSCcAbwBfSg6cty8fVEIADQDBpwAiABsheHAACzG-PUjjAFlSAEFKclonP0o4nb2ANUPKADFaXUoAIVoARhtDrnWy5qc+3wAtHo+BgGEAp9XoVrOMpogZvMAms-vtKEctjdzhwVGtNmYqGcbhxKGYEtdkfDzkjMh5XLo-CjYqSwpQ7n4AD40hIAJkZNIRAGZKZhsFF2LpCLRCGtdhxMCBCFKAHriPnGch3IUi0hOB6EdX08WSmVyoxEcgs5WizWUQhXQhs7XAKWEWXyg2c42q9Uss0Wj1mt0ank6u16-nkAAszrVXrNnLNQd9Nt1mCAA)
## Ungolfed / Explanation
```
// Filters a union of tuples for those with the shortest length
type Shortest<T, K = keyof T> = T extends T? keyof T extends K ? T : never : 0
// Increments numbers where e.g. 2 is represented as [Pos, Pos], 0 as [], and -3 as [Neg, Neg, Neg]
type Inc<T, Pos, Neg> =
T extends [Neg, ...infer T]
// If T is negative, remove one Neg from it
? T
// Otherwise, add one Pos to T
: [Pos, ...T]
type Main<Instructions, X = [], Y = [], Z = [], Pos=0, Neg=1, Travelled=[]> =
Instructions extends [infer Distance, ...infer InstructionsTail]
// If Instructions is non-empty
? Distance extends Travelled["length"]
// If we've travelled the full distance of this instruction,
// cycle XYZ, swap Neg & Pos (to reverse the sign of travel), and recurse
? Main<InstructionsTail, Y, Z, X, Neg, Pos>
// Otherwise, increment X, decrement Y, and add one to Travelled
: Main<Instructions, Inc<X, Pos, Neg>, Inc<Y, Neg, Pos>, Z, Pos, Neg, [...Travelled, 0]>
// Otherwise, return the taxicab distance to our current position
: Taxicab<[...X, 1] | [...Y, 2] | [...Z,3]>
// U will be passed in as [...X,1]|[...Y,2]|[...Z,3], so as to prevent merging in the union
type Taxicab<U, S = Shortest<U>> =
// Concat the shortest with the second shortest and return their length - 2
[...S, ...Shortest<U extends U ? S extends U ? never : U : 0>] extends [{}, {}, ...infer X] ? X["length"] : 0
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 49 bytes
```
Max@Abs@{s=Fold[{#2-#[[2]],Tr@#}&,{0,0},#],Tr@s}&
```
[Try it online!](https://tio.run/##RYo9C8IwEED/ysFBpivG07USFzehg1vIED@KBVuhyVA47rfHWoXCG96D18f8fPQxd7dYWqjLOU7ueE1OUn16v@5ekCv0nkOgy@hQDYklq4RLJzWlGbshz59CdYDWYwhgYONARAlkS/BlVUvA/@KlfvA6zboj2KuWDw "Wolfram Language (Mathematica) – Try It Online")
A port of [@tsh's answer](https://codegolf.stackexchange.com/a/238117/9288). Make sure to upvote that answer as well!
] |
[Question]
[
## Background
The recurrence of the Fibonacci sequence is defined as
$$
f(n+2) = f(n+1) + f(n)
$$
From this recurrence alone, the following *gap formulae* (recurrences relating three terms with certain amount of gaps) can be derived:
$$
f(n+4) = 3f(n+2) - f(n) \\
f(n+6) = 4f(n+3) + f(n) \\
f(n+8) = 7f(n+4) - f(n)
$$
You might have seen the \$n+6\$ formula if you have worked on Project Euler #2 hard enough :)
In general, for any \$a \in \mathbb{Z}^+\$ (positive integers), there exist unique integer coefficients \$\alpha, \beta\$ of the generalized gap formula
$$
f(n+2a) = \alpha f(n+a) + \beta f(n)
$$
which holds for all \$n\$.
We can generalize the Fibonacci recurrence itself too:
$$
f'(n+2) = uf'(n+1) + vf'(n)
$$
Then it can be shown that, for any \$a \in \mathbb{Z}^+\$ and \$u,v \in \mathbb{Z}\$, there exists a fully general gap formula with integer coefficients:
$$
f'(n+2a) = \alpha f'(n+a) + \beta f'(n) \tag{1}\label{eq1}
$$
Note that such a formula is not unique for some values of \$u, v, a\$.
## Challenge
Given the values of \$a, u, v\$, calculate the pair of values of \$\alpha\$ and \$\beta\$ in the equation \$\eqref{eq1}\$. You don't need to handle cases where the answer is not unique.
All three inputs are guaranteed to be integers. \$a\$ is strictly positive.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
For u = 1, v = 1
a = 1 -> alpha = 1, beta = 1
a = 2 -> alpha = 3, beta = -1
a = 3 -> alpha = 4, beta = 1
a = 4 -> alpha = 7, beta = -1
For u = -2, v = 3
a = 1 -> alpha = -2, beta = 3
a = 2 -> alpha = 10, beta = -9
a = 3 -> alpha = -26, beta = 27
a = 4 -> alpha = 82, beta = -81
For u = 3, v = -9
a = 1 -> alpha = 3, beta = -9
a = 2 -> alpha = -9, beta = -81
a = 3 -> undefined (not unique)
a = 4 -> alpha = -81, beta = -6561
a = 5 -> alpha = 243, beta = -59049
a = 6 -> undefined (not unique)
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 37 bytes
Saved 13 bytes thanks to @xnor.
```
(u,v,n)->[-(-v)^n,trace([0,1;v,u]^n)]
```
[Try it online!](https://tio.run/##hczBCsIwDIDhu08RekogGVbnYYh7kdJBEScDCWVsBZ@@BhQP8yAkl598yWme5J7rCJeKKxdWkj4ISqFBeZnT9YZhz/5ceI2DUqwp58cTFaSHPE@6oPMMNg7U1qqDEd9JiRiCb5o20u7XyYHhuIGf9kfaRbeBlqT7Qgb70zKcItUX "Pari/GP – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~60~~ 58 bytes
```
lambda u,v,a:[(p:=u/2-(u*u/4+v)**.5)**a+(u-p)**a,-(-v)**a]
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUaFUp0wn0Spao8DKtlTfSFejVKtU30S7TFNLS88USCRqa5TqFoAYOroauiDhxNj/BUWZeSUaaRqGOkCoqcmFzDdC4xuj8U2Q@LpGOsYoBoAFjNAFjNEFgGb8BwA "Python 3.8 (pre-release) – Try It Online")
*¯2 thanks to @tsh*
Originally based on @tsh's answer (now removed due to no complex number support)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 bytes
```
Ø.,æ*ÆḊN,ÆṭƲ
```
[Try it online!](https://tio.run/##y0rNyan8///wDD2dw8u0Drc93NHlpwOkdq49tun////GOrpG/40B "Jelly – Try It Online")
Takes input as `[v, u]` on the left, and `a` on the right. Outputs as `[β, α]`
-1 byte thanks to ovs!
Uses xnor's formula that
$$\alpha = \operatorname{tr} \left( \begin{bmatrix} 0 & 1 \\ v & u \end{bmatrix}^a \right) \\
\beta = -(-v)^a = - \det \left( \begin{bmatrix} 0 & 1 \\ v & u \end{bmatrix}^a \right)$$
## How it works
```
Ø.,æ*ÆḊN,ÆṭƲ - Main link. Takes [v, u] on the left, a on the right
Ø. - Yield [0, 1]
, - Pair; [[0, 1], [v, u]]
æ* - Matrix power to a; Call this M
Ʋ - Last 4 links as a monad f(M):
ÆḊ - Determinant of M
N - Negated
Æṭ - Trace of M
, - Pair; [-det(M), tr(M)]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 77 bytes
```
(u,v,a)=>[A=(F=n=>n<2?n^m:u*F(n-1)+v*F(n-2))(a+a,m=0)/F(a),F(a+a,m=1)-A*F(a)]
```
[Try it online!](https://tio.run/##dcxBDoIwEIXhvSeZgalKqyYai2HTSxhNGgSigdaI9PoViTvGzObNt/gfNti@fN2fb@H8rYq1jjBQIIs6PxcajHY6d0d5ctfuMCQGnMgwDdOQiGBTS51e48qARTK/P0NRJF@5xNK73rfVsvUN1JDReIiLuUpWFaubmQpJiglPLHlWPM/bisSeaU8seVY8/2lved6NHD8 "JavaScript (Node.js) – Try It Online")
Let
$$ f\_1\left(0\right)=0 \\ f\_1\left(1\right)=1 \\ f\_1\left(n+2\right)=u\cdot f\_1\left(n+1\right)+v\cdot f\_1\left(n\right) $$
Calculate
$$ p=f\_1(2a) \\ q=f\_1(a) $$
Let
$$ f\_2\left(0\right)=1 \\ f\_2\left(1\right)=0 \\ f\_2\left(n+2\right)=u\cdot f\_2\left(n+1\right)+v\cdot f\_2\left(n\right) $$
Calculate
$$ r=f\_2(2a) \\ s=f\_2(a) $$
We have
$$ p=\alpha\cdot q \\ r = \alpha \cdot s + \beta $$
Solve
$$ \alpha=\frac{p}{q} \\ \beta=r-\alpha \cdot s $$
---
Try to undelete this question since all failed testcases currently known had been been excluded from the question. Maybe this one is correct, but I'm not quite sure.
[Answer]
# [R](https://www.r-project.org/), 59 bytes
Or **[R](https://www.r-project.org/)>=4.1, 52 bytes** by replacing the word `function` with `\`.
```
function(u,v,a)c((p=u/2-(u^2/4+v+0i)^.5)^a+(u-p)^a,-(-v)^a)
```
[Try it online!](https://tio.run/##XYwxCsMwDEX3nkTCUtPKydAhVzGEgMGLY0Lk67smkyP@8HlveGeLa4ua9ysdGZQqbbgDlFUnYdAg0@yq@yQM7wXD5kC59CcGrv2xlTPlCyJ8qQ/xNbIY9obngVnIPwK3ECu8FWPDE/8ejVuIFb3R/g "R – Try It Online")
Based on [@xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s formula and [@PyGamer0's answer](https://codegolf.stackexchange.com/a/236697/55372).
Outputs complex numbers - for pretty integers add 4 bytes for wrapping result in `Re`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~23~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
0L‚©IF®øδ*O}Å\O¹θ(Im(‚
```
Port of [*@cairdCoinheringaahing*'s Jelly answer](https://codegolf.stackexchange.com/a/236707/52210), but without matrix power/multiplication, trace, nor determinant builtins. It uses a slight modification of *@xnor*'s formula:
\$\alpha = \operatorname{tr} \left( \begin{bmatrix} u&v\\1&0 \end{bmatrix}^a \right) \\
\beta = -(-v)^a\$
Inputs as `[u,v]` and `a`.
[Try it online](https://tio.run/##yy9OTMpM/f/fwOdRw6xDKz3dDq07vOPcFi3/2sOtMf6Hdp7boeGZqwGU@/8/2lhH1zKWywQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeW6rX@ajhnmJtofXHF6trnN4r1J0qU5ZrG304f2xSrW1hzcc3muvpPCobZKCkn1lQqhL2H8Dn0cNsw6tjHA/tO7wjnNbtPxrD7fG@Eee26ERkasBlPqfUKx0bqPt4f0K5zYBSSWd/9HR0YY6hrEgpABlGiGYxgimCZipawQSM0RiGyGxjZHYEPXGOrqWMPUQthESG1mNaWwsAA).
**Explanation:**
```
0L # Push [1,0]
‚ # Pair it with the (implicit) input-pair: [[u,v],[1,0]]
© # Store it in variable `®` (without popping)
IG # Loop the second input `a` - 1 amount of times:
® # Push the matrix from variable `®`
ø # Zip/transpose it; swapping rows/columns
δ # Apply double-vectorized over the two matrices:
* # Multiply them together
O # And then sum each inner-most list
}Å\ # After the loop: pop the matrix and push its main diagonal
O # Sum it together
¹ # Push the first input-pair again
θ # Pop and only leave the last item (`v`)
( # Negate it
Im # Take it to the power of the second input `a`
( # Negate that again
‚ # Pair the two integers together
# (after which this pair [α,β] is output implicitly as result)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
NθNη⊞υ²⊞υθF⊖N⊞υ⁺×θ§υ±¹×η§υ±²I⟦⊟υ±X±ηLυ
```
[Try it online!](https://tio.run/##bY27DsIwDEV3viKjI7UDRQyICcFSCVUZ2BBDaE1TKU3aPIC/D654qAOefO1zdGslXW2lTqk0QwxV7K/oYOTbxTwryiJ6BTFjxWyfuJt1DA5YO@zRBGxgLnLO2RcWOno4dT16GDO2C6Vp8Dk9KmxlQFgSnLE3oP4BBZ@G2l1nAuylD3AWdoDIf4iwD2r9BEX3I5o2UD2JF3JTWrF8w9Ypv@sX "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses @xnor's formula.
```
NθNη
```
Input `u` and `v`.
```
⊞υ²⊞υθ
```
Push `2` and `u` to the predefined empty list.
```
F⊖N⊞υ⁺×θ§υ±¹×η§υ±²
```
Calculate `a-1` more terms so that the last term is now the `a`th term.
```
I⟦⊟υ±X±ηLυ
```
Remove and output the `a`th term, then calculate the power using the remaining length which is now `a`.
] |
[Question]
[
# The Problem:
Two enemy secret agents have devised a wonderful (for you) method of communication!
Here’s how the encryption process works:
1) Take the ascii equivalents of each letter. (No spaces, numbers, or punctuation are sent)
2) For each letter in the message, the ascii equivalent of it and the letter after it (If it exists, if it doesn’t, it should be considered 0), are multiplied (this product is stored in an array/list) and summed (this number is also stored in a different list).
3) The two lists (of sums and products) are joined together (the sums list, then the multiples list, into the same array) and transmitted.
You need to write the smallest program able to reverse this process and decrypt messages sent in this format!
# Example Input and Output Pairs:
```
[173, 209, 216, 219, 198, 198, 225, 222, 208, 100, 7272, 10908, 11664, 11988, 9657, 9657, 12654, 12312, 10800, 0] -> “HelloWorld”
[131, 133, 164, 195, 197, 99, 4290, 4422, 6499, 9506, 9702, 0] -> “ABCabc”
```
# This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the smallest solution in bytes wins.
Error messages are allowed.
Your program can be given either a list/1-dimensional array or a comma-separated string, if you specify in your submission. The default is an array/list.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 66 bytes
```
,[>>>+<[-<+>>-<]<[->+<],]>[<<,>>[-<+>]<-]<<<[>[-<->>+<]<<]>.>>[.>]
```
Input is the encrypted string. Assumes infinite sized cells and 0 on EOF.
### How it Works:
```
,[>>>+<[-<+>>-<]<[->+<],] Gets input and the number of characters divided by 2
>[<<,>>[-<+>]<-]<<< Remove the second half of the string (the multiplication part)
[>[-<->>+<]<<] Subtract each character from the previous one, while keeping a copy of the previous one.
>.>>[.>] Print the characters
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~7~~ 6 bytes
```
mcĠ≠←½
```
[Try it online!](https://tio.run/##yygtzv7/Pzf5yIJHnQsetU04tPf////RhubGOkYGljpGhmZAbKljaGkBxkZGpkBsBJQD8g0MdMyNzI2ADEsQ19DMzARIWlpY6FiamZpDCEMjM1OgqJGxIUidBVCLQSwA "Husk – Try It Online") According to the documentation the leading `m` should not be needed, but there seems to be a bug currently.
*Edit: -1 byte thanks to Zgarb!*
### Explanation:
```
½ -- split input list into half
← -- take first list
Ġ≠ -- subtract each list element from the previous one
mc -- convert list of code points to string
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~45~~ 35 bytes
```
map toEnum.scanr1(-).fst.span(<245)
```
[Try it online!](https://tio.run/##NY69bsMwDIT3PAVHG3AMkdaPCSRjtnbqmGQQjDgp6ihC5Lx@XdJolhN1@o6nWyw/l2laRtjDabnHDPPjkF73tgwxPbHa1u1Y5rbkmKodWVcL850EFvQTqvyav@bnR4IWxhqOGzhi6BogwyLoVWRC7v@FyKmQIuoZ00CgQDry6qD3Vg/u5cbehbcieacv1OGK95o150Y7OxSnk2Jcw@xUNCnlllhAa7XUW3XYGfkZB0O64LxZfodxiteybIec/wA "Haskell – Try It Online")
### Explanation
* `fst.span(<245)` takes all numbers from the beginning of the list that are smaller than 245. Those are only the numbers from the summation part, because the largest possible summation is `z + z = 122 + 122 = 244`, and the smallest possible product is `A * A = 65 * 65 = 4225`.
* `scanr1(-)` takes the last value of the list and uses it as initial accumulator. Then from back to front each element of the list is subtracted by the current accumulator, and the result is used as the next accumulator and and added to a list.
* `map toEnum` replaces each number in the list with the corresponding character to recreate the string.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
œs2ḢUạ\ỌU
```
[Try it online!](https://tio.run/##y0rNyan8///o5GKjhzsWhT7ctTDm4e6e0P///0cbmhvrKBgZWAIJQzMQAWQZWlpACSMjUxBhBFICEjMw0FEwNzI3AjEtwSKGZmYmIMrSAsizNDM1h5GGRmamIBkjY0OwcguQXoNYAA "Jelly – Try It Online") or [Check both test cases.](https://tio.run/##NY6xEQIxDARb@QIcWLItW4V8wDyEJMxnRKQkJGRUADEFMHzIUIhpxOg8kKzk092cd9t5PrT2vuy5Pm5jfV7XdTmP7XX6HO@r1ibKwQ3s1UAC2EZafmBOAMMCzXs3ZM6MVbtCIhFDi71UUv6TWBIuHKjbC7J@44aJApkQrJd6VhOAoHVHVvPFiE6JUDR5@5hmz8h/AQ "Jelly – Try It Online")
[Alternative.](https://tio.run/##y0rNyan8/z/06ORio4c7Vz3ctTDm4e6e0P///0cbmhvrKBgZWAIJQzMQAWQZWlpACSMjUxBhBFICEjMw0FEwNzI3AjEtwSKGZmYmIMrSAsizNDM1h5GGRmamIBkjY0OwcguQXoNYAA "Jelly – Try It Online")
### Explanation
```
œs2ḢUạ\ỌU || Full program.
œs2 || Split into two parts, with the first one being longer if necessary.
Ḣ || Get the head (first element).
U || Reverse.
ạ\ || Cumulative reduce by subtraction.
Ọ || Convert from code points to characters.
U || And reverse again.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 72 bytes
```
a=input();p=0;r=''
for v in a[len(a)/2-1::-1]:r=chr(v-p)+r;p=v-p
print r
```
[Try it online!](https://tio.run/##NYvBCoMwEETvfkVuRqo0u9bERPIl4kFKi0KJYbFCvz7NSnt5OzM7Ez/7sgVMafZriO9dVkP0aiBflsVzI3GINYh5fD2CnKsrNuBcA5Mjf19IHk2sLpQHWRSR1rALSmkE09YClc0AzcgKbP8DYsdArnCmVC0MGmRpzwS0vvGxfXZWd@ZPQN3xB1s46z1v1fQF "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 92 bytes
```
lambda C:"".join(chr(sum((-1)**i*C[j+i]for i in range(len(C)/2-j)))for j in range(len(C)/2))
```
[Try it online!](https://tio.run/##ZU67DsIwDNz5iogpKa/YzaNGYupnAEN5FFJBigoMfH2JKxADy8W5O9/59nqc24h9vdr0l@q6O1SiXI7H86YNUe7Pnbw/r1LOQGVZyMp1Mwnbuu1EECGKroqno7wcoyzVAmeNUoq15l9Tqr91IT5ELdfg86lATQnAMaQJqPgAomVAtjCn9VR49MgjDQw4Z/ihIv3IWf9FQGdZwRwGe8G7eqtGv@ockpCnfhgyyDJwQLrBICW/MdztDDNkdTqQvMYhp38D "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
œs2Ḣḅ-$ÐƤAỌ
```
A monadic link taking a list of integers and returning a list of characters.
**[Try it online!](https://tio.run/##y0rNyan8///o5GKjhzsWPdzRqqtyeMKxJY4Pd/f8//8/2tDcWEfByMASSBiagQggy9DSAkoYGZmCCCOQEpCYgYGOgrmRuRGIaQkWMTQzMwFRlhZAnqWZqTmMNDQyMwXJGBkbgpVbgPQaxAIA "Jelly – Try It Online")**
### How?
```
œs2Ḣḅ-$ÐƤAỌ - Link: list of integers e.g. [210,211,201,101,10989,11100,10100,0]
2 - literal two 2
œs - split into equal parts [[210,211,201,101],[10989,11100,10100,0]]
Ḣ - head [210,211,201,101]
ÐƤ - for postfixes: [210,211,201,101],[211,201,101],[201,101],[101]
$ - last two links as a monad:
- - literal minus one -1
ḅ - convert from base -99 ,111 ,-100 ,101
A - absolute value (vectorises) [99,111,100,101]
Ọ - convert to ordinal (vectorises) "code"
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 60 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage)
```
←ĐĐŁ₂⁻⦋⇹ĐŁřĐŁ₂>*ž0`ŕĐĐŁ⁻⦋3ȘĐ4Ș3Ș4Ș÷⇹ĐŁřĐŁ<*žĐŁ⁻łŕ⇹Đ3Ș⇹÷Á↔áƇǰ
```
Takes a list of integers and returns a string of characters.
Explanation:
```
←ĐĐŁ₂⁻⦋⇹ Gets the ASCII code of the last character
ĐŁřĐŁ₂>*ž Gets the list of products and removes the 0 from the end of the list
0`ŕ ... ł Loops (0 is there so that the length can be removed from the stack)
ĐĐŁ⁻⦋ Gets the last product
3ȘĐ4Ș3Ș4Ș÷ Divides by the last ASCII code obtained
⇹ĐŁřĐŁ<*ž Removes the last element from the array
ĐŁ⁻ł Gets the length of the array - 1 (if 0, then exit loop - the last entry still has to be processed)
ŕ⇹Đ3Ș⇹÷ Divides the remaining product by the last ASCII code obtained
Á↔á Converts to array of ints
Ƈǰ Converts to string of ASCII characters
```
[Try it online!](https://tio.run/##K6gs@f//UduEI0B4tPFRU9Ojxt2PlnU/at8J4h@dCRW10zq6zyDh6FSoMrAa4xMzjkwwOTEDSAPJw9tR9NgANUCVHm06OhUsB1QIpA9vP9z4qG3K4YXH2o9v@P8/2tDYUMfQ2FjH0MxEx9DSFIjNdSwtdUyMLA10TEyMjHTMTIBcS1MDMx1LcwMjHYNYAA)
[Answer]
# JavaScript (ES6), 80 bytes
```
a=>String.fromCharCode(...eval(`for(a.splice(i=a.length/2);--i;a[i-1]-=a[i])a`))
```
```
f=
a=>String.fromCharCode(...eval(`for(a.splice(i=a.length/2);--i;a[i-1]-=a[i])a`))
console.log(
f([173, 209, 216, 219, 198, 198, 225, 222, 208, 100, 7272, 10908, 11664, 11988, 9657, 9657, 12654, 12312, 10800, 0]),
f([131, 133, 164, 195, 197, 99, 4290, 4422, 6499, 9506, 9702, 0])
)
```
[Answer]
## VB Script - ~~74~~ 71 bytes
( I managed to reduce from 74 to 71 by using While..Wend instead of Do..Loop)
The input is in an array a(), the output is in string d
```
d="":p=0:n=(UBound(a)+1)/2:While n>0:n=n-1:t=a(n)-p:d=Chr(t)&d:p=t:Wend
```
Explanation
```
d="" '// initialize the output string
p=0 '// initialize the ansii of following char (working back from last char)
n=(Ubound(a)+1)/2 '// the index of the last summed pair + 1 (base 0)
While n>0 '// begin loop working back from last summed pair
n=n-1 '// move back 1 char
t=a(n)-p '// calculate the ansii by subtracting the ansii of following char
d=Chr(t)&d '// prepend the char to output
p=t '// this char becomes the following char for next
Wend '// repeat etc.
```
I tested this in a vbscript file with the above code wrapped as a function:
```
dim s
Dim arr()
s = Split("173, 209, 216, 219, 198, 198, 225, 222, 208, 100, 7272, 10908, 11664, 11988, 9657, 9657, 12654, 12312, 10800, 0", ",")
ReDim arr(UBound(s))
Dim x
For x = 0 To UBound(s)
arr(x) = cint(s(x))
Next
msgbox "=" & d(arr)
Private Function d(a())
d="":p=0:n=(UBound(a)+1)/2:While n>0:n=n-1:t=a(n)-p:d=Chr(t)&d:p=t:Wend
End Function
```
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~96~~ ~~81~~ ~~78~~ 77 bytes
`zero` is the null character.
I could save another byte if Clean wasn't so picky about literal nulls in the source file.
```
import StdEnv
f=init o foldr(\a t=[toChar a-t!!0:t])[zero]o takeWhile((>)245)
```
[Try it online!](https://tio.run/##NYwxb8IwEIV3fsWxJRJI9kGcuFK6tB2QujF0CBlOiQNWHbsKVyT48XVjBMt37969d50z5OMY@l9nYCTrox1/wsSw5/7DXxZDbb1lCDAE10/ZgYDrhsPbiSagNS@X4oXbvLmZKbQBmL7N18k6k2WvOW6LPO6Z5mc1DNDIcrMCFHqGVAmzkrp6ALFIwBRJnhArKLHEJPXdkUpt09DVvGlVlE9KVEW64Ebe41Xqijb@dYOj4zmud5/x/epptN35Hw "Clean – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 39 + 2 (`-ap`) = 41 bytes
```
$#F/=2;$\=chr($p=-$p+pop@F).$\while@F}{
```
[Try it online!](https://tio.run/##NYvLCsIwEEV/pWAWik3NTM0LCXSVnX/QjUihhWKGKrgQf92YKbo5c@c@aFhmnbPYxEPAk@jDdVy2goIUtKdEXdw1on@O0zx08f3KGWxbV6h8ARhGUeDdD4iagVxhT6m6smiRpV8dMObIx7vyeaPtn4BGc4ItrHXHW/VJ9JjS7Z7lWTcKVJYX@gI "Perl 5 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~90~~ 89 bytes
* Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat); `s+=(i%2?-1:1)*...` <~> `s-=~(i%2*-2)`.
```
D(C,l,j,s,i)int*C;{for(j=~0;++j<l/2;putchar(s))for(s=i=0;i+j<l/2;)s-=~(i%2*-2)*C[i+++j];}
```
[Try it online!](https://tio.run/##LU/RDoIwDPwVX0w2KHErMljmnvAvDA9kiTqCaBg@Efh17NSHu/R6vTZ12c25bTuzGnroIIDnfpiS2szX58g6uwqTpt2pP6B5vSd3b0cWOI9esN4K4/8mD5ldmd9jkiFP6otPKdaYZXu0fmB8pqW7@tLYWZY5oNCAUhE0SF19gVgQkDzSQkCJJVKho5RKHYl1VYFWRfkjiaqgLuYyzlUUEQs4i8LEZxyn2x8 "C (gcc) – Try It Online")
[Answer]
# [Standard ML (MLton)](http://www.mlton.org/), ~~85~~ ~~84~~ 82 bytes
```
fun!(x::r)=if x>244then[]else(fn z::s=>x-z::z::s|_=>[x])(!r);implode o map chr o!;
```
[Try it online!](https://tio.run/##VU5di4MwEHy/X7H2SaGFZM2HUfSPeFLKnaFCjKK2SOl/t1mvfbiX2dnJ7GTm3p16twx@2@zNR/Ga51NSdhbWCoVYrq2vm9bNbWw9PPJ8Lqv1FCbR57ms6rVJ4mhKiq4f3fDbwgD9ZYSf6wRDVGz3iwMLJXRL8TVOnV8gtlBznR4BmQnAFUFg3GRvQJQESBbSGDuCRo1Eza5wpQQNk4XNKKk/yFFJesGU7/aMblmTfD4/fPvDvyIpD7Y0tOF7opEEFBcaCTThWghqogQpRrJQ12iGf6nbCw "Standard ML (MLton) – Try It Online")
### Ungolfed:
```
fun g (x::r) =
if x > 244
then []
else case g r of
z::s => x-z :: z :: s
| [] => [x]
val f = implode o map chr o g
```
[Try it online!](https://tio.run/##PY7NboMwEITvPMUoJ5ASyTbGYFfkRSiqUAoEiT8BrVDUd6e7blIfPq93dsezDv1l6LdpPI7ma0SLcHduiZAHALqGsOMKpTW/t3s9oii5rPu1xq0itFgwNdx7nodzK/Ir9ssDzsFj/dd/QA5gvdjLIPiuejTI0Q1zP33WmDBUM2538kR7sPpBajgv3bghbFDIND5DCUuQhkGVtNkTSiUMxSPcE@KMVKWKS@s70hjNl83oZU2SviiVSVhRsfTjGe@KMnoL/j4/vY@nV@2DxJLGYkojvaNNGGxHibSytK01JzGaOzYRFNemQnnX6PgF "Standard ML (MLton) – Try It Online")
[Answer]
# [Perl 6](https://perl6.org), ~~43 39~~ 35 bytes
```
{[~] [R,](produce *R-*,[R,] .[^*/2])».chr}
```
[Test it](https://tio.run/##TU/BToNAFLzvV7xDY6FSZBdY2JAaqzHx4KkxeiCYVFgjyQoboEbT1PRD6pd481P6I7iPVNPL7Nt5M7OzWjaK96tWwht384S8fsBJXhcSZv06/cwgXTiZpZu6WOUSJovpxEEG3PRxcsYy@@fbzV@aTW9sF51sO5iBKivZWrhptSo7awzTcxjj/fp@fpsQfOvOSBOi1bKC08GXkOe6OUQYuTUqK73qnJF81zLvZGHDmgCULWC3w9Z24H9/NLrafMmyE7LpUxr5DjBPGKAcwUxUxAdgLERgKEHO8xyIWMRwFANDOQ/wELG5CR5Gf0gZD3HDfDrIY/R6GXbfb3c3Uqn6oW5Usd9@kZT61Gh8U4UOcSJEwCxTJ2DCWIMAa/AAGRF6pquIPHYUOb@8Wj7lJu4X "Perl 6 – Try It Online")
```
{[~] [R,]([\[&(*R-*)]] [R,] .[^*/2])».chr}
```
[Test it](https://tio.run/##TU9BTsMwELz7FXuo2qSkIXYSp1ZUREFIHDhVCA4mSCU1IpJJoiRFoKqoD4GXcOMp/UjwhoB6Ga9nZ8bjUlWat@tawQt305g8v8EwLVYKZu1GvicgF05iyTs5tMaLydhOfhlw5f34mCX295ebPlXb1thOG1U3MAOd5aq2cFOXOmusEUxOYIT3i5v5VUzwrWsjjUmplzkcdb6YPBZVH2Hk1iDLy3XjDNRrqdJGrWzYEICsBuzWb20H/vcHo1uaL1l2TLatpJHvAPOEAcoRzETFtAfGQgSGEuQ8z4GIRQxH0TGU8wAPMTU3wcPoDynjIW6YTzv5FL1egt33u49LpXVxW1R6td99Ekl9ajS@qUK7OBEiYJapEzBhrEGANXiAjAg901VEHjuInJ@dLx9SE/cD "Perl 6 – Try It Online") (does the same as above)
```
{[~] [R,]([\R[&(*R-*)]] .[^*/2])».chr}
```
[Test it](https://tio.run/##TU/dToMwFL7vU5yLZYPJkBYoNGTGaUy88GoxelExmaxGkjoIMKNZtuxB9Em881H2IthD0Ozm6@n5fvq1VJXm7bpW8MbdLCGvHzDMiqWCabuRuxTk3Ekt@TCXQ2s8n4ztNAVXPo5PWWr/fLvZS7VtjeW8UXUDU9D5StUWMnWp88YaweQMRni/upvdJATfuTXShJR6sYKTzpeQ56LqI4zcGuSrct04A/VeqqxRSxs2BCCvAXv1rO3AP380uqX5jmUnZNtKGvkOME8YoBzBTFTEPTAWIjCU4M7zHIhYxHAU3YZyHuAhYnMTPIz@kDIeIsN82slj9Hopdj/sP6@V1sV9UenlYf9FJPWp0fimCu3iRIiAWaZOwISxBgHW4AFuROiZriLy2FHk7OJy8ZSZuF8 "Perl 6 – Try It Online")
```
{[R~] [\R[&(*R-*)]](.[^*/2])».chr}
```
[Test it](https://tio.run/##TU/BSsNAEL3vV8yhtElNY3aTbLqEilUED56K6CFGqOmKgbUJSSpKaemH6Jd481P6I3EmVOnl7cy8N2/elroysl3VGt6km8Xs9QP6WbHQMGnXyWybQvIwS/rWcDYa2mlqucnj8FSk9s@3m71Umxbl542uG5iAyZe6toipS5M31gBGZzCg/upuehMzunGL0piVZr6Ek24vZs9FdbBAudXLl@WqcXr6vdRZoxc2rBlAXgNlOrC2A//8UemW@BXLjtmmTXjkOyA8hcAlAVZcjQ8gREggSEIzz3MgEpGgUnUTLmVAjxpjp2QY/SEXMiRG@LyTj2nXSyn7fvd5rY0p7ovKLPa7L5Zwn6PGxyi8s1MhAXlhnEAoXA0CiiEDmqjQw6wq8sSR5fTicv6Uod0v "Perl 6 – Try It Online")
## Explanation:
```
{[R~] [\R[&(*R-*)]](.[^*/2])».chr}
{ } # block lambda with parameter `$_`
[\R[&(*R-*)]](.[^*/2]) # turn sums back into ordinals (reversed)
.[^*/2] # first half of `$_` (implicit method call)
*R-* # lambda, reverse of *-*
[&( )] # use it as an infix operator
# (same as R- except left associative)
R # reverse arguments and associativity
# (same as - except right associative)
[\ ]( ) # produce values `[\+] 1,2,3` => `(1,3,6)`
# uses associativity to determine direction
# `[\**] 1,2,3` => `(3,8,1)`
».chr # call `.chr` method on all values
# (possibly concurrently)
[R~] # concatenate in reverse
# (shorter than `join '', reverse …`)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
2ä¬Å«-}çJ
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f6PCSQ2sOtx5arVt7eLnX///RhubGOgpGBpZAwtAMRABZhpYWUMLIyBREGIGUgMQMDHQUzI3MjUBMS7CIoZmZCYiytADyLM1MzWGkoZGZKUjGyNgQrNwCpNcgFgA "05AB1E – Try It Online")
## Explanation
```
2ä # Split input list in two (equal if possible) parts.
¬ # Push head(a).
Å«-} # Cumulative reduce the list by subtraction (from the right).
ç # Convert each integer in the list to its corresponding ASCII char.
J # Join list together to string.
```
[Answer]
# Japt, 12 bytes
There has to be a shorter way to get the first half of the array ...
```
¯UÊz)Ôån Ômd
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=r1XKeinU5W4g1G1k&input=WzE3MywgMjA5LCAyMTYsIDIxOSwgMTk4LCAxOTgsIDIyNSwgMjIyLCAyMDgsIDEwMCwgNzI3MiwgMTA5MDgsIDExNjY0LCAxMTk4OCwgOTY1NywgOTY1NywgMTI2NTQsIDEyMzEyLCAxMDgwMCwgMF0KLVA=)
[Answer]
# [Python 2](https://docs.python.org/2/), 70 bytes
```
l,j,s=input(),0,'';n=len(l)/2
while n:n-=1;j=l[n]-j;s=chr(j)+s
print s
```
[Try it online!](https://tio.run/##FcgxCsMgFADQPadwi9IfqsYYrHiSkKkEVORXoqH09NYsb3j5V/0HZWsJIhQXMF@VMuAwjhZdOpAm9pTD14d0EHzh5ISNLm24T9EW9/YnjexRhnwGrKS0tolZABHz3NGqY5abFYgxQJQ0vKukBKLVPWbhurvyPnz/Aw "Python 2 – Try It Online")
] |
[Question]
[
Given an array of numbers, find out how many iterations of averaging\* it takes for the average of every element to be no more than 1 higher or lower than the first element (absolute difference between the array's average and the first element is less than or equal to 1).
# \*Array averaging
To "average" a number in our array, we take the average of itself, the number behind it, and the number ahead of it. The last number of the array assumes the number ahead of it is the first number of the array (wrapping). **Do this for all but the first number of the array, it needs to stay constant.** The averages should all be applied at the same time (i.e. don't take the average of a number, put it back into the array, then average the next number).
# Example:
```
ITERATION 0: [-1,4,3.5,7]
1: [-1, 2.1666666666666665, 4.833333333333333, 3.1666666666666665]
2: [-1, 2.0, 3.388888888888889, 2.3333333333333335]
3: [-1, 1.462962962962963, 2.5740740740740744, 1.5740740740740742]
4: [-1, 1.0123456790123457, 1.8703703703703705, 1.049382716049383]
5: [-1, 0.6275720164609054, 1.3106995884773662, 0.6399176954732511]
6: [-1, 0.31275720164609055, 0.8593964334705076, 0.3168724279835391]
7: [-1, 0.057384545038866065, 0.4963420210333791, 0.058756287151348875]
abs(AVERAGE - FIRST_ELEMENT) = 0.903120713306 (IS LESS THAN 1)
OUTPUT: 7
```
# Other I/O
```
INPUT >> OUTPUT
[-3, 9] >> 2
[0, 0, 0, 0] >> 0
[64, -66, -9, 78, -60] >> 29
[9, 4, 5, 3, 3, 3, 10, 1, 1, 1] >> 44
[-6, 5, -4, 3, -2, 1, -1, 2, -3, 4, -5, 6] >> 70
[100000000, 2.11, 0.0, 16.88, 8.44, 6.33, 16.88, 100000000] >> 348
[-8245, 6832, 9525, -3397, 5595, -9242, 1954, 6427, 36, -9647, -8887, 3062, -4424, -4806, -3803, 3608, -5115, -3725, -3308, -277] >> 1038
```
**Though not a part of the challenge**; technically we are dealing with absolute values therefore complex numbers should also work. **Your program does NOT need to handle complex numbers.**:
```
[(20-1j), (5-4j), 7, (-0-100j)] >> 15
```
# Notes:
* Other mathematical methods are accepted
* You are to assume there are at least two elements in the array
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins
[Answer]
# [Perl 6](https://perl6.org), ~~83~~ 82 bytes
```
->\a(\b,|c){(c,{[(b,|$_,b).rotor(3=>-2).map: *.sum/3]}...{(b+.sum)/a~~b-1..b+1})-1}
```
[Try it](https://tio.run/nexus/perl6#PVBbjptAEPyfU/RHFIM9M2YeDMNaZvcQ@cNoBZisLNkGGRxl5bAXyi1yMaebxWuNrO7q6qpqrn0Dv5ysN@z0Dt/rdt/A9i6yXRnsKv6nDm9BzW95gPW3V16F8tIO7SUw20zoUJ7K7gmWsr@e1qYYpZS3oFpRG67Lj49KKCmrlRpDocY7yr8MTT/AFo6Hc9MHn@s3BkCjEvHVv7@ybk9VsIaFWDzDbr@CfCEXVBTPsA43SH4p80jKpdAFp3opVMFGdsUzfqD6hnXH8gyryWrDfraX2VVkEOwO5@468F3zu2vqodmHQO6HXuybpju@A10fTJyQw4PEYULk26Ef2HjPheKWGxnzpIAsg4TlwnBIC6AONMsjDvObsYjlznIQzuFfyiHx1DymOmU5gkiIOZjHU7ivPt/Msxad3MQSduIIPREwEGBFKcgF525eSdBZRfMPSVIhNZIk7aTHFF5aXHHSmC/oiz9rGOvR12tLut6gURprymBMmmCaOKUm1ZbCpDHJWY0DMx3rLJbCe09I5CimtZpiWh8Rw/iIDnYRfZNYqUk5mQ0mUCfJHEVFxv8H "Perl 6 – TIO Nexus")
```
->\a(\b,|c){(c,{[(b,|$_,b).rotor(3=>-2).map: *.sum/3]}...{1>abs (b+.sum)/a -b})-1}
```
[Try it](https://tio.run/nexus/perl6#XZHbjpswEIbv/RRzURWT2I5PGGgadh@idwRVQGiFlJMCqbpK80R9i77YdoYle7HIgvE//8x8Ntehg19BtWt2eIHP7WnXweZVFtuabxvxp41vvBW3kmP86btoYnU5jacLd5tC2lgd6vMXWKjheli56q6UupmibgbgzZLEeFWDbO6xNPdX7P48dsMIG9j3x27gb9U3BkCpGvXlv7@qPR0avkIRIJLRE2x3SygjFVFQPU16CV/LpayKDzmI@ggmyype4/u5LrVSC2krQfFCmord2RWP@w0x1uy8r4@wnJjW7MfpMuPJAvi2P56vo9h2v89dO3a7GAizH@Su6877F6Bb4pMnFvAwCZgU9bMfRnZ/LaURXjiViLSCooCUldIJyCugHVhWagHzmjXNyuAFyBDwlQtIM9o8sjZnJYpoSAS4xzJYb97W7PMeJ4XJJf3kkXYyIBBgRBQ0BfNhLklxstHzgyZl0KoVtQ4qQ4pMeSwJyrl36d0/93A@w7mZ9dQ3czgoTywxOJenSJPktMmtJ5g8oXbeYsJNhw0eQ5llGSk6EKb3ljB9psnhMk0HDpruJDFm6pzOAybRpumMYrRDFm61ND3@IJ5IT19szSVqWvfxw5n8Bw "Perl 6 – TIO Nexus") (also works for complex numbers
## Expanded
```
-> # pointy block lambda
\a # the input array
(
\b, # the first value
|c # all the rest of the values
)
{
(
# generate a sequence
c, # initialize the sequence starting with the second value
{ # bare block lambda with implicit parameter 「$_」
[ # turn the result from a Seq into an array
( b, |$_, b ) # re-add the first element
# and add it to the end
.rotor(3=>-2) # grab 3 at a time, backing up 2
.map: *.sum/3 # return the average for each sub sequence
]
}
... # keep calling that to generate values until
{
1 > abs ( b + .sum )/a - b # they are almost equal
}
) - 1 # count them and reduce by one (ignore initial value)
}
```
[Answer]
# [R](https://www.r-project.org/), ~~107~~ ~~101~~ ~~98~~ 95 bytes
*Edit: -6 bytes thanks to Giuseppe (who has now outgolfed this with his own [shorter answer](https://codegolf.stackexchange.com/a/219438/95126))*
```
function(x){while(abs(mean(x)-x)>1){for(j in seq(y<-x)[-1])x[j]=mean(c(y,y)[j+-1:1]);F=F+1};+F}
```
[Try it online!](https://tio.run/##XVDbbsIwDH3fV1jaS6M2VS5umoy1j/wE4qFDRSvaQAOmUSG@vbMzRimVGzn2Occn3g/dsd03x263PVTD@nu74jQ5ifPPe/fRJs3bIflsG67Ik6i1OK93@2QD3RYO7VfSv1J1IfVSnBabZRWRq6TPerHYpFK/UGM2r@apvszS@eVuFqGkzSAIAc8AdQ1gniZdlcE1RoiaQhxmIJ2jI2RQer7cgU2YoglD@CID@x@a1PVfjDTEKU26SJIYKdJEvKSfMn4Be6C@GxXKB5taXT/i5JqYKufBLvdk2edICi639la64UdJi/7BlTfIU70lG6Ew7NDaUJLXIvAlGGSroWB1NNSwcVEOKZXee64ox49ANPwI9IoR1ivejlO8z0LrqFxeB8SiKcvRmVbWw/AL "R – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
L‘ṁ@µ+3\÷3;@Ḣ
ǵS÷L_1ị$Ị¬µÐ¿L’
```
A monadic link taking the list and returning the number of iterations required.
Test suite at **[Try it online!](https://tio.run/nexus/jelly#PU89T8MwEN37KzywYVu2z59CQt3pxhgi9v6KwFKpLIytBAtz17SgIiE54ockfyTcOaHW2bm79/Le3bgaml3/9bTM7TU8dCe4WfafH4tuk9v77rR61P355ao/b/Mht91r/kH6fvz97jbD8@EOL8aaPs1bPopbNjTv65Ln4zhWldDccpCOh5ovWCWAs1QyxdkcpfSWM@E9PomzEKmYACwRcpzBf2j8SU8xafqCC1tQYQqEvgwz8iNlxH0hazUfhKVGkpIk52VEzygtkr0EuLQu/MkqGktSEVA7OUO2ACngAC5RkYwl/@RIxxoEoOzkLaYixkgd5Wkyaw1NZqMiBkRF23lFqzuti3KYDUrThFDXfw "Jelly – TIO Nexus")**
### How?
```
L‘ṁ@µ+3\÷3;@Ḣ - Link 1, perform an iteration: list x
L - length of x
‘ - incremented
ṁ@ - mould with swapped @rguments (i.e.. [a,b,c,...] -> [a,b,c,...,a])
µ - monadic chain separation (call that v)
3\ - three-wise reduce v with:
+ - addition (sum up the overlapping slices of 3)
÷3 - divide those by three (get the averages)
Ḣ - head v (get the first element)
;@ - concatenate with swapped @rguments
ǵS÷L_1ị$Ị¬µÐ¿L’ - Main link: list a
µ µÐ¿ - collect results while loop
Ç - body: call last link as a monad
- condition:
S - sum
L - length
÷ - divide (average)
$ - last two links as a monad:
1 - literal one
ị - index into (the first element)
_ - subtract
Ị - insignificant (absolute value is less than or equal to 1)
¬ - not
L - length (count the results)
’ - decrement (the first result is number zero)
```
[Answer]
# Python 2, 130 bytes
```
x=map(float,input())
l=len(x)
q=0
while abs(x[0]-sum(x)/(l+.0))>=1:x=x[:1]+[sum((x+x)[i-1:i+2])/3for i in range(1,l)];q+=1
print q
```
~~Slightly off for the larger test cases~~ Apparently not!
**BONUS:** Change `float` to `complex` and it will be able to handle complex numbers correctly (at a cost of two bytes).
*Edited once* ehhh.... I found a bug.... fixed now!
[Answer]
# Mathematica, 83 bytes
```
(a=#;0//.n_/;Mean@a-First@a>=1:>(a={#&@@a,##}&@@Mean/@Partition[a,3,1,{1,2}];n+1))&
```
[Answer]
## JavaScript (ES6), 106 bytes
```
f=(a,l=a.length,m=a.reduce((s,e)=>s+e-a[0],0))=>m>l|m<-l&&1+f(a.map((e,i)=>i?(a[i-1]+e+a[++i<l?i:0])/3:e))
```
[Answer]
## Haskell, 81 bytes
```
g l@(a:_)|abs(sum l/sum(1<$l)-a)<1=0|1<2=1+g(a:[(x+y+z)/3|x:y:z:_<-scanr(:)[a]l])
```
Usage example: `g [64,-66,-9,78,-60]` -> `29`. [Try it online!](https://tio.run/nexus/haskell#PYrBCoQgFEV/5S1aKJn5MkLEYP4jJJxZSGAy5AxU9O@Oi6GzuBwuJ3sID@L0TC/3TCR9VwhtWYKmCrRx1OAoLjTdiLUv3UT2@qhP2spr14c@9Wya9HJxI5pOzgZL8@qWCCO8tyV@oAIPE4o/DDqOyEDwojhwpRgo3vcMBi7lfd29zT8 "Haskell – TIO Nexus")
How it works
```
g l@(a:b) -- function g takes a list l where the first element
-- is bound to a
|abs ( ) = 0 -- if the end condition is true, return 0
sum(1<$l) -- computes the length of l. The library function "length"
-- won't work, because it returns an "Int"
| 1+g -- else return 1 + a recursive call with one step of
-- averaging
x:y:z:_<-scanr(:)[a]l -- picks all 3 element sublists of l appended by a
-- the elements are bound to x, y and z
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 146 bytes
```
function k=f(a)n=numel(a);I=eye(n-1,n)/3;A=[resize(1,1,n);I+circshift(I,[0,1])+circshift(I,[0,2])];k=0;while(abs(mean(a)-a(1))>1)k++;a=A*a;end;end
```
[Try it online!](https://tio.run/nexus/octave#XVDLbsMgELz3K7gVGnB5GYMsKuWYb4h8cFOsWEmoFCeq2p9Pd12SpkULWnZmd0Z7Gc55cxrfM9nFgfYsx3w@pD1k7Sqmz0SzUDyzZ9Mu4/qYpvErUcWx1K4Wm/G4mbbjcKIrvpZcdex/SXesa3dRth/bcZ9o/zrRQ@ozjBc9VYy9KLZbLNo@Lp/6NuU3vJd@mtLxRAe6FoaT0D0yEiPR7OEXkJyUKKi8R53lRDgHT@Ck8fi58nS4JwIM1JoTcw0FM9VPlA5r7zuEm/nCzmyhZyqsiECGblEZcFeamz@@lCwH6JWCJlmhnKs8ePSVhWZXGXMr3fhlmrH@jxevLWp5A@Kh1ujLmNCAwzrgJ2iLBkONg60GwMxLcRZS4b3HinRo3VqN1q2XyDBe4jqcxN3VSs2TmyIwF3XTFFNKGs8u3w "Octave – TIO Nexus")
Multi-line version:
```
function k = f(a)
n = numel(a);
I = eye(n - 1, n) / 3;
A = [resize(1, 1, n);
I + circshift(I, [0, 1]) + circshift(I, [0, 2])];
k = 0;
while(abs(mean(a) - a(1)) > 1)
k++;
a = A * a;
end;
end
```
Pretty sure it's rather suboptimal.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
;®Æm3Ƥ®;µḷ/©ạÆmỊ¬µÐ¿L’
```
[Try it online!](https://tio.run/##PVA7TsQwEO05hcusZBvbM/5pr8ANopQ00XIAOkQBEhUtJRIN0mq7FQgKJEfiHtmLmBknbDSKZ@Y9vzfj8Xq3u611Ww7Tww38vpXDthznz4/L8j5/vVJv/n4q@3KcnsvP1enupU6Pp/t9rX2vrEQJ2ss4yAvRK5Ait8xIsUYrA0qhQqBfliImLhaASoK8FPAfli7ZJRbN0HCFDVWuQeQrKGM/ViY8NLI160ewtkQymuWCTuSZNBI5aIBz68xfrJJDlkpA2tk7tgXIkQbwmYvskP2zZx10BEDbKSClKqXEHRN4MkTHk2EyzIBkeLtgeHVvbVOOq0Frurg8YeeMsuNGis4r5JMkO0U9Y8bNMPwB "Jelly – Try It Online")
## How it works
```
;®Æm3Ƥ®;µḷ/©ạÆmỊ¬µÐ¿L’ - Main link. Takes an array A on the left
п - While loop, collecting the results
µ - Condition:
ḷ/ - Get the first element of A
© - Save into the register R
Æm - Get the mean of A
ạ - Absolute difference
Ị - Less than or equal to 1?
¬ - Logical NOT
µ - Body:
® - Retrieve the first element of A
; - Append to A
3Ƥ - Over overlapping windows of size 3:
Æm - Return the mean
® - Retrieve the first element of A
; - Prepend to the means
L - Count the steps of the while loop
’ - Decrement to account for the first iteration (A)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 18 bytes
```
←V§≈←A¡λ:←¹mAX3S:←
```
[Try it online!](https://tio.run/##yygtzv7//1HbhLBDyx91dgAZjocWntttBWQc2pnrGGEcDGL@//8/WtdQx0THWM9UxzwWAA "Husk – Try It Online")
### Explanation
```
←V§≈←A¡λ:←¹mAX3S:←
¡λ Infinitely iterate the following function and build a list of results
S:← Append the first element to the list
X3 Get all the contiguous sequences of 3 elements
mA Compute the average of each
:←¹ Prepend the first element of the original list to this result
Now we have an infinite list with all the steps
V§ Find the index of the first position where:
A the average
≈ is similar (absolute difference <=1)
← to the first element
← Finally, subtract 1 (lists in Husk are 1-indexed)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[¬UDÅAXα1›≠#Ćü3ÅAXš¼}¾
```
[Try it online](https://tio.run/##yy9OTMpM/f8/@tCaUJfDrY4R5zYaPmrY9ahzgfKRtsN7jEFCRxce2lN7aB9Qka6FkYmpjoKZhbGRjoKlqRGQrWtsbGmuo2BqagniWBqZAGUMLU1NgKpMjIASxmYgYTMTIFPXwsICJGJgBlSja2JiZAKiLAxAKowtDIxBig0sgBxTQ0OwyeZQC8CCRubmsQA) or [verify all test cases](https://tio.run/##PY@9SkNBEIVfJcT27LI/s7uzVRB8BSFwuYWChZWFIKQQbAzY@gRJb2NhIyHFjbY@xH2R69kY3GlmvtlzZubu/ur69mZ6WC3ms3H9OpsvVlM3vF1eHJ7Plz/vfnz6HF82Z1/rwy429L0ddo/DfoIdPqauMxG1R@dwDGZZYHKGqSjKrKEKQUI8hnfwLYhNJjVCaAKR8QigHfUJmX3vTg/Beg9nKc1WFWpFkG2Mp/r/YzPVIJRrDKgp0D/GWpBSZVqDcFBNFEsoiG3LLAVGVVm6zPkigQuIOjajOq6cHe9I3jev8ufYSCil738B).
**Explanation:**
```
[ # Start an infinite loop:
¬ # Get the first item of the list (without popping the list itself)
# (which will use the implicit input-list in the first iteration)
U # Pop and store this first item in variable `X`
D # Duplicate the list
ÅA # Pop and get the arithmetic mean
Xα # Get the absolute difference with `X`
1›≠ # If this is NOT larger than 1 (thus it's <=1):
# # Stop the infinite loop
Ć # Enclose the list; append its own first item
ü3 # Create overlapping triplets
ÅA # Get the arithmetic mean of each inner triplet
Xš # Prepend `X` at the front of this list
¼ # Increase the counter variable by 1 (0 by default)
}¾ # After the infinite loop: push the counter variable
# (after which it is output implicitly as result)
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~35~~ 33 bytes
Saved 2 bytes thanks to Adám (and would have saved 1 with a tip from Bubbler)
```
{1≥|⊃⍵-⍵⌹=⍨⍵:0⋄1+∇h,3÷⍨3+/⍵,h←⊃⍵}
```
[Try it online!](https://tio.run/##PY4/TkMxDMZ3TuEt76lJSGIncZC4BDNLJQQdKtEVAVMr/r@KhSMgsXVCiLXcJBcpTls1UeLPP/tzMp5NzcXNeHp9tdlc1of3W1@fP@/qy7wO30ZOffs9rcOXqBNXXxd@VJ8eJxr/fgTi6Fi4nohtZ7iXGbBeeSBAGyEftQyhSHS7LSqRwJTkKpC56Ua92y8NwXqvwVmRPllmDWyJNCSLeECHfvHWYdkp3UGvQHWmV3X5cabOvWTrleqV4UBR7IxBQ4lBtEEsWUOMpSUlkFR8ie0RClLA1HAikYaZG3FJegxRoBbYtQ5kh63ZyYdM9H47Oe8f2MKQs/oH "APL (Dyalog Unicode) – Try It Online")
A recursive function.
Adám's idea of using ⌹ to find the average is really cool. See [their explanation](https://codegolf.stackexchange.com/questions/120170/average-an-array-until-all-numbers-are-almost-equal/219022?noredirect=1#comment510338_219022) in the comments. `R` is the result of `X⌹Y`, and it's chosen to minimize the square of the difference between `X` and the matrix product of `R` and `Y`. In this case, since `Y` is a vector of all 1s, the average of `X` minimizes that squared difference.
Explanation:
```
{
1≥|⊃⍵-(+/÷≢)⍵: 0 ⍝ Base case: If it's the last iteration, return 0
⍵⌹=⍨⍵ ⍝ Average of ⍵ (the array)
=⍨⍵ ⍝ Compare ⍵ to itself to create an array of 1s the same size as ⍵
⍵⌹ ⍝ ⍵ divided by that (matrix division)
⍵- ⍝ Subtract that from all elements of ⍵
⊃ ⍝ Take only the first of those differences
| ⍝ Absolute value
1≥ ⍝ Is it less than or equal to 1?
⋄1+∇h,3÷⍨3+/⍵,h←⊃⍵
h←⊃⍵ ⍝ Assign the first element of ⍵ to h
⍵, ⍝ Append to ⍵ (because of wrapping)
3+/ ⍝ Take groups of 3 adjacent elements and sum each
3÷⍨ ⍝ Divide each sum by 3 (to get average)
h, ⍝ Prepend h, which stays constant
∇ ⍝ Call on this new iteration
1+ ⍝ Add 1 to that
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 88 bytes
```
f=->a{x,=a;(x-1.0*a.sum/a.size).abs>1?f[[x,*[*a,x].each_cons(3).map{|a|a.sum/3.0}]]+1:0}
```
[Try it online!](https://tio.run/##RVHbTsMwDH3vV0TipR1JcO4JaOVDogpl0yb2MJiYJhW2fXuxs1EqK4mPj49Pmq/T6nuatkvRl/PIl@WlHYWSsCjyeNo/4br72XSyrI69et3mPPJFXhQ@DnJT1u9v68@PY2s6uS@H86Vcbk1GwnUYHtUzXKecheKWG@l4GDh76PvQZGF4uiVMNxk4uwdiFWTQZG85E97jkjgLkZL/uk5NRhgpjjPzFwo11C1mprU4zleesJUldKWgLYYntEIyAut@bgo4X8H9Q5pUSAZJ8l5G9BKlxSYvjZmhmT@rGBtxdtSWtKPBYclp8mFMCujIJUqStmQoORK0GgumXtpbPIoYIyHgyaq1mqzaCMQwEejaHujfOKWqcrgPqKAOYTajwKCbVoNQu46z1glLO4q3AjGAXTdUpnLN7W3pPQ9sm8twnX4B "Ruby – Try It Online")
Recursive lambda, works with complex numbers. As usual, 2 bytes can be saved in Ruby 2.7+ by using a numbered block parameter. If we can assume that array values will always be provided as floats, we can save some more by avoiding float conversions.
[Answer]
# [R](https://www.r-project.org/), 90 bytes
```
function(l){while(abs(mean(l)-l)>1){l[-1]=colMeans(array(l,sum(l|1)+1:0)[1:3,])
F=F+1}
+F}
```
[Try it online!](https://tio.run/##XVDBbsIwDL3zFZF2SURSxYmbJkhw5LYvQBw6xESlAFILmibGtzO7Y5RSuZFjv/f84vbWnLZtfWqOh25@@zwfNpzKrC5fuyZvZf3Ryf225orJagHqklcG1vPNMb9TuZN129bfMuvuvJf5B9QUZlatYOb1Wk2W8@UUrpPp8vo0Rm6k8VokpcSbEIuFEG4y6lot7jFA7BgSUAsTAh1Jiyry5Qns0hhNGMKXWvj/AFKHvxhoiGOaCT3JYE8xrscb@injF7AH6odBoXqxCfb@EacAYtqCB4cikuVYICmEwvtH6YEfJD3GF1fRIU@Nnmyk0rFD71NFXsvEl@SQraaS1dFRw/eLCkipiTFyxQZ@BKLjR2C0jPDR8naC5X2WAL1ydR/QF11VDc7A@ihuvw "R – Try It Online")
Test harness stolen from [Dominic van Essen's answer](https://codegolf.stackexchange.com/a/219198/67312).
Uses R's recycling to construct the appropriate neighbor-means to replace in the original array.
] |
[Question]
[
Given a list of math expressions that all hold true and consist of [modulo remainder](https://en.wikipedia.org/wiki/Modulo_operation) calculations with two numbers and a result, your task is to yield the first `n` numbers that hold true for all the statements in the list.
For example:
`[m % 3 = 0, m % 4 = 1, m % 5 = 3]`, where % is the modulo operator.
For `n` = 3, the first 3 numbers (counting from 0) that fit the sequence are `33, 93, 153`, thus your result would be that (format up to you).
## Rules / IO
1. You take a positive number `n` and a list of truths. Of course, the things you need take are only the RHS of the modulo operation and the result.
2. `n` and the numbers in the list of truths will always be in the range **1 -> 2^31-1**, and so are the results.
3. You take input in any convenient form and output in any convenient form. For example, input: `3 [3 0, 4 1, 5 3]` and output: `33 93 153`.
4. It's guaranteed that the solution is mathematically possible.
5. The source of input can be from a file, function parameters, stdin, etc... Same goes for the output.
6. No loopholes.
7. This is code-golf, so the lowest byte count wins.
## Testcases
```
# Input in the form <n>, <(d r), (d2 r2), ...>
# where <d> = RHS of the modulo expression and <r> the result of the expression. Output in the next line.
5, (3 2), (4 1), (5 3)
53 113 173 233 293
3, (8, 0), (13, 3), (14, 8)
120 848 1576
```
## Reference implementation in pseudo-code
```
n = (an integer from stdin)
truths = (value pairs from stdin)
counter = 0
while n != 0 {
if matches_criterias(counter, truths) {
print counter
n -= 1
}
counter += 1
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
%⁼⁴
0ç#
```
This is a full program. Arguments are divisors, target moduli, and number of solutions, in that order.
[Try it online!](https://tio.run/nexus/jelly#@6/6qHHPo8YtXAaHlyv////fQkfB0BiITf4b6CgAGRb/jQE "Jelly – TIO Nexus")
### How it works
```
0ç# Main link.
Left argument: D (array of divisors)
Right argument: M (array of target moduli)
Third argument: n (number of solutions)
0ç# Execute the helper link with k = 0, 1, 2, ... as left argument and D as the
right one until n of them return 1. Yield the array of matches.
%⁼⁴ Helper link. Left argument: k. Right argument: D
% Compute k % d for each d in D.
⁼⁴ Compare the result with M.
```
[Answer]
# [Perl 6](https://perl6.org), 33 bytes
```
{grep((*X%@^b)eqv@^c,0..*)[^$^a]}
```
[Try it](https://tio.run/nexus/perl6#bZBLbsIwEIb3OcUv@pBNTUQIrxZRcYAuu0BqGinEprUUktQJqCjNZdpzcCaOQMfhoS668Hge3/ye8bpQ2AzdeOKsyXtWRTlxnNUWt3EmFaaH6s2onLH2/GYWLrj62MzCWHRdt81fwusweq0PBM9K6sMUzEFzgIEAY75Aj5PTF/DsTUmfc9EAbEBVz7NmZDnfmnufU7EhjjK@lRkLdG27hf3GIcHxRcjrdSnsE@UNRsOTAKct8iRKcdfMRtEyM6c5O49gQSoQSENGfeYqLpXkqKiVlmGBFIHhtI7J1qk02UKn@JKGNIAr7Hffcr/7gS4QIdGkly1RvitIvdFFZoozZf6ljFpFOpWKOAJ10ZFK5ckW9rtZKqQw3H0iXuA82ClsxTRN@YAqrS9PUSTdXJmk/qOLyhxzrYlTH34B "Perl 6 – TIO Nexus")
The input is `( number-of-values, list-of-divisors, list-of-remainders )`
## Expanded:
```
{ # bare block lambda with placeholder parameters 「$a」 「@b」 「@c」
grep(
# WhateverCode lambda:
(
* # the value being tested
X% # cross modulus
@^b # with the divisors ( second parameter )
)
eqv # is that list equivalent with
@^c # the expected remainders ( third parameter )
# end of WhateverCode lambda
,
0 .. * # Range of all Integers starting with 0
)[ ^$^a ] # grab up-to 「$a」 values ( first parameter )
# ( 「^$a」 is the same as 「0 ..^ $a」 )
}
```
[Answer]
## JavaScript (ES6), ~~71~~ 68 bytes
```
a=>f=(n,m=0)=>n?a.some(x=>m%x[0]-x[1],++m)?f(n,m):[m,...f(n-1,m)]:[]
```
A simple recursive function. Use by currying in the array first and `n` second, like so:
```
g=a=>f=(n,m=0)=>n?a.some(x=>m%x[0]-x[1],++m)?f(n,m):[m,...f(n-1,m)]:[]
g([[3, 2], [4, 1], [5, 3]])(5)
```
[Answer]
## JavaScript (ES6), ~~74~~ ~~70~~ 69 bytes
Takes input as an integer `n` and an array `a` of `[modulo, remainder]` arrays with currying syntax `(n)(a)`.
```
n=>a=>eval('for(i=r=[];a.some(([b,c])=>i%b-c)||--n*r.push(i);i++);r')
```
### Test cases
```
let f =
n=>a=>eval('for(i=r=[];a.some(([b,c])=>i%b-c)||--n*r.push(i);i++);r')
console.log(f(5)([[3, 2], [4, 1], [5, 3]]))
console.log(f(3)([[8, 0], [13, 3], [14, 8]]))
```
[Answer]
## Haskell, 47 bytes
```
n#l=take n[i|i<-[0..],all(\(d,r)->mod i d==r)l]
```
Usage example: `3 # [(8,0),(13,3),(14,8)]` -> `[120,848,1576]`.
[Answer]
# Python, 67 bytes
```
lambda n,r:[k for k in range(2**32)if all(k%d==m for d,m in r)][:n]
```
[Answer]
## JavaScript (ES6), ~~72~~ 70 bytes
```
a=>g=(n,i,r=[],m=a.some(e=>i%e[0]^e[1]))=>n?g(n-!m,-~i,m?r:[...r,i]):r
```
Curried over the conditions array first and number of results second. Edit: Saved 2 bytes by not handling the zero case.
[Answer]
# Mathematica, 42 bytes
```
#2~ChineseRemainder~#+Range[0,#3-1]LCM@@#&
```
Unnamed function, returning a list of positive integers, and taking three inputs: the list of moduli, the list of remainders, and the number `n` of integers to return. For example, the second test case is invoked by
```
#2~ChineseRemainder~#+Range[0,#3-1]LCM@@#&[{8,13,14},{0,3,8},3]
```
and returns `{120, 848, 1576}`.
The builtin `#2~ChineseRemainder~#` gives the smallest nonnegative solution; to get all the desired solutions, we add this number to `Range[0,#3-1]LCM@@#`, which is the first `n` nonnegative multiples of the least common multiple of all the moduli.
Mathematica doesn't have lazily-evaluated infinite lists as far as I know, so this implementation was shorter than anything I found that tested nonnegative integers one by one—even with the length of the function name `ChineseRemainder`, and even though a test like `Mod[k,{8,13,14}]=={0,3,8}` works perfectly well.
[Answer]
# PHP, 97 bytes
longest answer so far. But I´m glad I could get it below 100.
```
for($a=$argv;++$k;)for($i=$v=2;$m=$a[$i++];$v>$argc/2&&$a[1]-->0?print$k._:0)$v+=$k%$m==$a[$i++];
```
takes input from separate command line arguments,
prints matches separated and trailed by underscores.
Loop never breaks; barely suitable for online testers.
Run like `php -r 'code' <n> <modulo1> <result1> <modulo2> <result2> ...`.
**breakdown**
```
for($a=$argv;++$k;) // loop $k up from 1
for($i=$v=2; // $i = argument index, $v=2+ number of satisfied equations
$m=$a[$i++]; // loop through modulo/result pairs
$v>$argc/2 // 2. if $v>argument-count/2
&&$a[1]-->0 // and match count not exhausted
?print$k._ // print match
:0 // else do nothing
)
$v+=$k%$m==$a[$i++]; // 1. if $k%modulo==result, increment $v
```
**notes**
`$argc==count($argv)`. For three pairs there are 8 arguments: the filename `$argv[0]`, `n`=`$argv[1]` and the `modulo`/`result` pairs above that. `$v=2` incremented 3 times gives `5`>`$argc/2`.
Add one byte for a clean exit: Replace `&&$a[1]-->0?print$k._` with `?$a[1]--?print$k._:die`.
[Answer]
# Pyth - ~~14~~ 13 bytes
```
.f!fneT%ZhTQE
```
[Try it online here](http://pyth.herokuapp.com/?code=.f%21fneT%25ZhTQE&input=%5B%5B3%2C+0%5D%2C+%5B4%2C+1%5D%2C+%5B5%2C+3%5D%5D%0A3&debug=0).
[Answer]
# SmileBASIC, 102 bytes
```
DEF V N,M
FOR K=1TO N@L
T=T+1F=0FOR J=1TO LEN(M)F=F||T MOD M[J-1]-M[J]J=J+1NEXT
ON!F GOTO @L?T
NEXT
END
```
This is the first time I've ever used `ON` in SB. The reason I used it here instead of `IF F GOTO@L` was so I could put `?T` after it on the same line, saving 1 byte.
[Answer]
# Python, 59 bytes
```
lambda n,m:[i for i in range(2**31)if all(map(eval,m))][:n]
```
`m` is a list of expressions in string form like `["i % 4 == 1", ...]`
[**Try it online**](https://tio.run/nexus/python2#NctBCsIwEEbhvaf4CRSSkkVr7KaQk4QsRmxkIDOWIF4/toKbB9/iKSLCRY4mwxgQECMm4/HT7dT813IqmNxLrCT3B0G9rIlRXg0MVjTS52av4zgvjguoViu02@1D1YtzOa2a@95Y3yj2mF3/Ag) (with a shorter range, so it will actually finish)
[Answer]
# PHP, 91 Bytes
Take the list as associative array
```
<?for($t=1;$r<$_GET[1];$i+=$t=!$t?:print+$i._.!++$r)foreach($_GET[0]as$k=>$v)$t*=$i%$k==$v;
```
[Try it online!](https://tio.run/nexus/php#JYtBC4IwGIbv/gvhC7QNcVgJzW8eQqJLXbzJGBKWI9DxNTz2123U7Xkf3qeq3eiigWgmQ4ObydvpmXwac721l1OTygjMuWmx6wpUOd@hEnyPquAlqgMXIqDmpZbrY6YEPAoJVP2STmgJlmGQMfj66MhOnoHNTBYzBpSGYujvY/J/57p/wwsVLCn4LYLdhIWwyHX9Ag "PHP – TIO Nexus")
] |
[Question]
[
Your task is to make a program that will take an input of a **word** of any length, in the Calibri font. This word will be made out of letter characters that are found on a normal QWERTY keyboard. There will be no accents or any other characters (i.e punctuation, numbers etc).
So, the original characters are:
>
> A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
>
>
>
The program will then scramble it to change the characters so they look similar or exactly the same, which would probably confuse a spell checker by flagging it, but it would confuse me as it looks the same as the normal word, with the unchanged character.
An example of this is the Unicode character `U+0430`, Cyrillic small letter a ("–∞"), can look identical to Unicode character `U+0061`, Latin small letter a, ("a") which is the lowercase "a" used in English.
Another example is the Russian letters –∞, —Å, –µ, –æ, —Ä, —Ö and —É have optical counterparts in the basic Latin alphabet and look close or identical to a, c, e, o, p, x and y.
Rules:
1. The program has to work out similar characters. This means that they **cannot be stored in any form**. This means that Unicode value or the character itself.
2. This is a code golf - the shortest answer wins!
3. You have to post the ungolfed version too to avoid cheating that can't be detected when its golfed!
4. You can use any function or program to do this, as long as words are not stored there either.
5. You must use UTF-8. Other inputs and outputs are banned. This is so that I am actually able to read what you are outputting, and what I am inputting, so I do not have a random mass of squares, question marks and ‚ùÆther rand‚ùÆm punctuati‚ùÆn!
6. It has to work with any word that I input.
A working example (Copy and paste this into word and insert a space after, it should flag the second one and not the first one.)
```
Halim
H–∞lim
```
[Some helpful info is here](https://en.wikipedia.org/wiki/IDN_homograph_attack)
Good Luck! Begin
[Answer]
## JavaScript, 71 characters
```
function f(s){return "\u202E"+s.split("").reverse().join("")+"\u202C";}
```
[Try it out on JSFiddle.](http://jsfiddle.net/WYgWt/)
By the way, this would be a good bit shorter in CoffeeScript (**53 characters**)
```
f=(s)->"\u202E#{s.split('').reverse().join ''}\u202C"
```
**EDIT:** I just noticed that UTF-8 requirement. That's going to be tough in JavaScript. :-/
[Answer]
# Python3 - 51
```
print(''.join(chr(ord(c)+0xFEE0)for c in input()))
```
The lazy way!
Slightly ungolfed
```
r=''
for c in input():
r += chr(ord(c) - 0x20 + 0xFF00) # convert to fullwidth ASCII range
print(r)
```
[Answer]
# Common Lisp, 142
I have no font named Calibri, and most of my fonts lack these symbols, but DejaVu Sans has them. I replace letters with [Mathematical Alphanumeric Symbols](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols). The spell checker does not flag any errors. Instead, it fails to detect errors, even if words have obvious typos.
Golfed:
```
(ignore-errors(do(c)(())(setf c(char-code (read-char)))(write-char(code-char(cond((< 64 c 91)(+ c 120159))((< 96 c 123)(+ c 120153))(t c))))))
```
Ungolfed:
```
(ignore-errors ; Ignore when (read-char) signals end of file.
(do (c) (()) ; Loop forever with variable c.
(setf c (char-code (read-char)))
(write-char
(code-char
(cond
;; Replace A to Z with U+1D5A0 to U+1D5B9.
((< 64 c 91) (+ c 120159))
;; Replace a to z with U+1D5BA to U+1D5D3.
((< 96 c 123) (+ c 120153))
;; Keep other characters.
(t c))))))
```
## Usage
* `clisp asconfuse.lisp <in >out`
* `ecl -shell asconfuse.lisp <in >out`
* `sbcl --script asconfuse.lisp <in >out`
I assume that your Lisp interpreter has Unicode support and your locale is UTF-8. Do not use `abcl`, because it has problems outside the Basic Multilingual Plane.
**Unix clones:** You can run `locale` in a terminal. If the line for LC\_CTYPE does not mention UTF-8, try `export LC_CTYPE=en_US.UTF-8`.
## Example
I pasted some output into LibreOffice. My text has obvious spelling errors, but LibreOffice fails to detect them. It draws no red squiggles under the words, and the spell-check button only reports, "The spellcheck is complete."

The text is, "ùñ≠ùóàùóêùóê ùóÇùóì ùóçùñæùóÅ ùóçùóçùóÇùóÜùñæ ùñøùóàùóàùóã ùñ∫ùóÅùóÖ ùóÄùóéùñΩ ùóáùñæùóÜ ùóçùóçùóà ùñºùóàùñæùóÜ ùóçùóçùóà ùóçùñæùóÅ ùñ∫ùñæùñΩ ùóàùóè ùóçùñæùóãùñæ ùñºùóàùóéùóáùóçùóãùñæùñæ." Firefox also finds no spelling errors in this text.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 7 chars
```
∊''∘,¨
```
There is a U+FEFF ([Zero Width No-Break Space](https://en.wikipedia.org/wiki/Word_joiner), a.k.a [Unicode BOM](https://en.wikipedia.org/wiki/Byte_order_mark)) between the quotes. This character occurs in in the Calibri font.
The character `''` is `∘` prepended `,` to each `¨` character in the argument, and the whole thing is then flattened `∊`.
] |
[Question]
[
## Challenge
>
> In this task you have to write a program that will take input
> an integer N **(-1e9 <= N < 0 && 0 < N
> <= +1e9)**, then compute **T = (abs(N) %
> M+1)**,if N is positive then output
> the T-th character from the
> beginning else output the T-th
> character from the end of your source.
>
>
> **M is the size of your source in bytes.**
>
>
>
**Example:** If your source is: `abcd efg/hi`
**Input:**
```
2
```
**Output:**
```
c
```
**Input**:
```
-3
```
**Output:**
```
g
```
**Input**:
```
-9249678
```
**Output:**
```
b
```
**Input**:
```
-11
```
**Output:**
```
i
```
**Constraints**
* Don't use any FILE operation
* You can use any language of your choice
* Try to avoid or rather don't use 1 byte submissions, since it spoils all fun.
* Shortest solution wins!
>
> **EDIT:** Problem statement have been modified so that the solutions could be
> judged using a random test-data (and
> same data for all solutions) hence
> please update your solution
> accordingly,sorry for the inconvenience
> (if any).
>
>
>
[Answer]
## x86 assembly (32-bit Linux, AT&T syntax): 548
No newline at end of file:
```
pushl 8(%esp)
call atoi
mov $274,%ebx
cmp $0,%eax
jg a
dec %eax
a:cdq
idiv %ebx
cmp $0,%edx
jge p
add %ebx,%edx
p:add $s,%edx
cmp $s+273,%edx
jl l
push $34
mov %esp,%edx
l:mov $4,%eax
mov $1,%ebx
mov %edx,%ecx
mov $1,%edx
int $128
mov $0,%ebx
mov $1,%eax
int $128
s:.ascii "pushl 8(%esp)
call atoi
mov $274,%ebx
cmp $0,%eax
jg a
dec %eax
a:cdq
idiv %ebx
cmp $0,%edx
jge p
add %ebx,%edx
p:add $s,%edx
cmp $s+273,%edx
jl l
push $34
mov %esp,%edx
l:mov $4,%eax
mov $1,%ebx
mov %edx,%ecx
mov $1,%edx
int $128
mov $0,%ebx
mov $1,%eax
int $128
s:.ascii "
```
I compiled it with `gcc -nostartfiles -m32 qc1.S -o qc1`
Verification, positive numbers:
```
$ for i in $(seq 548 1095); do ./qc1 $i; done | cmp - qc1.S && echo Good
Good
```
Verification, negative numbers:
```
$ for i in $(seq -1095 -548); do ./qc1 $i; done | cmp - qc1.S && echo Good
Good
```
**Edit** got it right about the weird numbering scheme. *I think.* It didn't change the length.
[Answer]
Whaddaya know, **HQ9+** makes its great return!
```
Q
```
No need to bother indexing when there's only one character to choose from!
[Answer]
## Ruby 1.9, 66 characters
```
z=gets.to_i;s="z=gets.to_i;s=%p;$><<(s%%s)[z%%66]";$><<(s%s)[z%66]
```
Not much difference to a normal quine, actually.
* Edit: Follows the new specs now.
[Answer]
# GolfScript 26 characters
```
{':f`f'+1/\~.1<- 26%=}:f`f
```
Quines were more fun before the invention of dynamic languages.
Edit: For the whiners, here is a "real" GolfScript quine, no ` and ~ only used for parsing the input.
# Handicapped GolfScript 44 characters
```
'"\x27"\+1/\~.1<- 22%='"\x27"\+1/\~.1<- 22%=
```
Notice how nicely it is the same string repeated twice, so the string literal just need a `'` hacked in front of it and it's ready for use.
[Answer]
# Lenguage, 4 bytes
Source code consists of 4 null bytes. Regardless of the input, the output should thus be a null byte, which is accomplished by one `.` instruction.
[Answer]
# Smalltalk, 94 90 59 52
for example, in the Object class, compile:
```
q:n|s|s:=thisContext method source.^s at:n\\s size+1
```
then send q:<n> to any object; here an integer:
verification:
1 q:0 -> q
1 q:1 -> :
1 q:2 -> n
...
1 q:-1 -> )
1 q:-2 -> )
1 q:-3 -> 1
or better:
(0 to:100) collect:[:n|1 q:n]as:String
-> `')q:n|s m|s:=thisContext method source.m:=s size.^s at:(n>=0ifTrue:n-1\\m+1ifFalse:m-(0-n\\m))q:n|s m|'`
(-1 downTo:-500)collect:[:n|1 q:n]as:String
-> `')m\\n-0(-m:eslaFfi1+m\\1-n:eurTfi0=>n(:ta s^.ezis s=:m.ecruos dohtem txetnoCsiht=:s|m s|n:q))m\\n-0('`
explanation for non-Smalltalkers:
*thisContext* is the current stack frame, which can be asked for its *method*, which can be asked for its *source*.
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 17 bytes
```
"3X4+kSq:l͍iS%%@
```
[Try it online!](https://tio.run/##KyrNy0z@/1/JOMJEOzu40CrnbG9msKqqw///ukamAA "Runic Enchantments – Try It Online")
Just uses standard quine to generate the program string, then uses string-based modulo operator1 to get the character at a given index (which natively support negative and positive indicies, behavior influenced by Python).
1. The `,` "divide" command cuts the string up into chunks (logical enough inverse of `*` duplicating the string `x` times), `+` concatenates, and `-` removes `x` characters from the end (a logical enough inverse of `+`). So the `%` command takes the role of `charAt(x)`: the only basic string operation remaining (after stack-like operations being handled by the same commands that deal with the stack; eg. `l` is the size of the stack so `l͍` is the length of a string).
[Answer]
# JavaScript (ES6), 28 bytes
```
f=n=>("f="+f).substr(n%28,1)
```
A modified quine.
A value larger than 28 is handled by `%28`, a value less than 0 is handled by `.substr()`.
] |
[Question]
[
[Hertzprung's Problem (OEIS A002464)](https://oeis.org/A002464) is the number of solutions to a variant of the [Eight Queens Puzzle](https://en.wikipedia.org/wiki/Eight_queens_puzzle), where instead of placing \$n\$ queens, you place \$n\$ rook-king fairy pieces (can attack like both a rook and a king); in other words, it's how many possible positions you can place \$n\$ rook-kings on an \$n \times n\$ board such that each piece does not occupy a neighboring square (both vertically, horizontally, and diagonally).
## Challenge
Write the **shortest** function or full program that will output the number of solutions to Hertzprung's Problem.
You may either:
* output just \$\operatorname{A002464}(n)\$, given a positive integer \$n > 0\$, or
* output all terms of \$\operatorname{A002464}(k) \text{ where } 0 < k < \infty\$ as a [sequence](/questions/tagged/sequence "show questions tagged 'sequence'").
## Notes
* A formula is derived in [this video](https://www.youtube.com/watch?v=qt5I1gZj1ew):
$$
\operatorname{A002464}(n) = n! + \sum\_{k=1}^{n-1} (-1)^k(n-k)!\sum\_{r=1}^k 2^r \binom{n-k}{r} \binom{k-1}{r-1}
$$
## Test Cases
```
1: 1
2: 0
3: 0
4: 2
5: 14
6: 90
23: 3484423186862152966838
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-n`, 6 bytes
```
r↕∆A1>
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJunlLsgqWlJWm6FquKHrVNfdTR5mhot6Q4KbkYKrxgtSGXEZcxlwmXKZcZRAgA)
Brute force. Slow for large input.
```
r↕∆A1>
r↕ Find a permutation of [0..n-1] such that
∆A the absolute differences of adjacent elements
1> are all greater than 1
```
The flag `-n` count possible solutions.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
I almost asked this question after watching Another Roof's video.
```
Œ!IỊ§¬S
```
A monadic Link that accepts \$n\$ and yields the number of solutions.
**[Try it online!](https://tio.run/##y0rNyan8///oJEXPh7u7Di0/tCb4////ZgA "Jelly – Try It Online")**
### How?
```
Œ!IỊ§¬S - Link: non-negative integer, n e.g. 4
Œ! - all permutations (of [1..n]) [[1,2,3,4],[1,2,4,3],...,[2,4,1,3],...,[3,1,4,2],...,[4,3,2,1]]
I - forward differences [[1,1,1],[1,2,-1],...,[2,-3,2],...,[-2,3,-2],...[-1,-1,-1]]
Ị - insignificant? [[1,1,1],[1,0,1],...,[0,0,0],...,[0,0,0],...[1,1,1]]
§ - sums [3,2,...,0,...,0,...3]
¬ - logical NOT [0,0,...,1,...,1,...,0]
S - sum 2
```
...yes, it also works if \$n=0\$ (the alternative of `Œ!IỊ§ċ0` would give \$0\$ rather than \$1\$).
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands/2649a799300cbf3770e2db37ce177d4a19035a25), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Lœ¥Ä≠PO
```
Port of [*@alephalpha*'s Nekomata answer](https://codegolf.stackexchange.com/a/260270/52210), so also a slow brute-force for larger inputs.
[Try it online](https://tio.run/##MzBNTDJM/f/f5@jkQ0sPtzzqXBDg//@/GQA) or [verify most test cases](https://tio.run/##MzBNTDJM/W/uU1Zpr6Sga6egZF/53@fo5ENLD7c86lwQ4P9f5z8A).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input-integer]
œ # Get all permutations of this list
¥ # † For each inner permutation-list: get its deltas / forward-differences
Ä # Get the absolute value of each inner-most difference
≠ # Check for each that it's NOT 1 (so basically >= 2)
P # Product on each inner list, to check for which all overlapping pairs are >=2
O # Take the sum, to check how many are truthy
# (after which it is output implicitly as result)
```
† Uses the legacy version of 05AB1E to save 1 byte, because `¥` vectorizes on a list of lists, whereas the new 05AB1E version would give an error, and would require an additional `€` before the `¥` to accomplish the same thing.
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), 60 bytes
```
11005:&$:@*3[{:}]&3-:&*-4[{:}]&3-:&*-5[{:}]&2+:&*+:nao&5+40.
```
[Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiMTEwMDU6JiQ6QCozW3s6fV0mMy06JiotNFt7On1dJjMtOiYqLTVbezp9XSYyKzomKis6bmFvJjUrNDAuIiwiaW5wdXQiOiIiLCJzdGFjayI6IiIsInN0YWNrX2Zvcm1hdCI6Im51bWJlcnMiLCJpbnB1dF9mb3JtYXQiOiJjaGFycyJ9)
Infinitely prints values starting at n=4.
Based on the recursive formula pioneered by [Arnauld](https://codegolf.stackexchange.com/a/260269/91213) but instead of recursing just keeps previous values pushed to the stack.
[Answer]
# [Desmos](https://desmos.com/calculator), 69 bytes
```
K=n-k+1
f(n)=n!-∑_{k=2}^n(-1)^kK!∑_{a=1}^k2^anCr(K,a)nCr(k-2,a-1)
```
Nice.
[Try It On Desmos!](https://www.desmos.com/calculator/shvdjovqiy)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/rdi9psqmwx)
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), 125 bytes
[Try it online](https://tio.run/##K8gvTy0qzkjNyfn/P600L7kkMz9PwV1DJVOzOjMNSCno5pQomCBzjDSrDWtTc4pTqw1qITRQRttQU0sDpE3XUFNTF0QbwQSMoAKmMAFjTU1tCA0VMNHUrK39765hofkfAA)
Golfed Version:
```
function G($i){if($i -lt 4){if($i -lt 2){1}else{0}}else{($i+1)*(G($i-1))-($i-2)*(G($i-2))-($i-5)*(G($i-3))+($i-3)*(G($i-4))}}
```
Un-Golfed Version:
```
function G($i){
if($i -lt 4)
{if($i -lt 2){1}
else{0}
}else{
($i+1)*(G($i-1))-($i-2)*(G($i-2))-($i-5)*(G($i-3))+($i-3)*(G($i-4))
}
}
```
Let me know of any improvements!
[Answer]
# [Aussie++](https://github.com/zackradisic/aussieplusplus/), 136 bytes
Tested in commit 9522366. Loses precision for inputs >18, because all numbers are doubles.
```
THE HARD YAKKA FOR a IS(n)<YA RECKON n <2?BAIL 1;YA RECKON n <4?BAIL 0;BAIL(n +1)*a(n -1)-(n -2)*a(n -2)-(n -5)*a(n -3)+(n -3)*a(n -4);>
```
Aussie++ requires every identifier to be followed by whitespace, a semicolon, a comma, or a paren, so I can't remove the spaces before all the operators. It also doesn't have bitwise operators, and the equivalent to `--` is `PULL YA HEAD IN`, so I can't take the same shortcuts as the JS and C answers.
Example test code:
```
G'DAY MATE!
THE HARD YAKKA FOR a IS(n)<YA RECKON n <2?BAIL 1;YA RECKON n <4?BAIL 0;BAIL(n +1)*a(n -1)-(n -2)*a(n -2)-(n -5)*a(n -3)+(n -3)*a(n -4);>
I RECKON i IS A WALKABOUT FROM [0 TO 18] <
GIMME "" + i + ": " + a(i);
>
CHEERS C***!
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `Rl`, 36 bits1, 4.5 [bytes](https://github.com/Vyxal/Vyncode/blob/main/README.md)
```
Ṗ'¯ȧċA
```
[Try it Online! (link is to bitstring)](https://vyxal.pythonanywhere.com/?v=1#WyJSbEEhIiwiIiwiMTEwMTAxMTAwMTAxMDEwMDEwMTExMDAxMTExMDAwMTEwMTEwIiwiIiwiMVxuMlxuM1xuNFxuNVxuNiJd)
Port of [Kevin Cruijssen's 05AB1E answer](https://codegolf.stackexchange.com/a/260299/114970), which is in turn a port of [alephalpha's Nekomata answer](https://codegolf.stackexchange.com/a/260270/52210). Like those, it is a brute force solution, suffering with the same slowdown on larger inputs.
```
Ṗ # permutations of the range 1..n (due to the R flag)
' # filtered by
¯ȧ # absolute value of the deltas
A # are all
ċ # not 1
# the length of this filtered list is taken by the l flag
# and implicitly output
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 51 bytes
```
n->Vec(sum(i=0,n,i!*(x*(1-x)/(1+x))^i)+O(x^n++))[n]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN43zdO3CUpM1iktzNTJtDXTydDIVtTQqtDQMdSs09TUMtSs0NeMyNbX9NSri8rS1NTWj82KhWo0SCwpyKjXyFHTtFAqKMvNKgEwlEEdJIU0jT1NTRyHaUMdIx1jHRMdUx0zHyDhWE6JzwQIIDQA)
Based on the generating funtion on the OEIS page.
[Answer]
# JavaScript (ES6), 56 bytes
Based on the recurrence formula provided on [OEIS](https://oeis.org/A002464).
```
f=n=>n<4?n/2^1:-~n--*f(n--)-n*f(n)-(n-3)*f(--n)+n*f(n-1)
```
[Try it online!](https://tio.run/##LYyxDoJAEER7v2ILkuMkiwGsgINQoLGQQi2sBEQwGtwzoDYEfv0EYzN58zKZe/7J26K5PV9I8lIqVQkSAfnLkBb2yXJxIMR5pY/JkSbgOBaHj4hI3Pg5tLiqZKMTCLA8IPAF2M4IhsGhmwEUklpZl2Ytr3qW61pHPQetm@4ggOT9OJeNuY2O6T5axekmOcTreAchsEEwcIEJ1v/nfca9Wa@@ "JavaScript (Node.js) – Try It Online")
### With Bigints, 58 bytes
```
f=n=>n<4?n/2n^1n:-~n--*f(n--)-n*f(n--)-~-~-n*f(n)+n--*f(n)
```
[Try it online!](https://tio.run/##NYtBCsIwFET3PcVfdJFviNLqyjZ6E2mojShlvrTiJqRXj6koA8MbZubh3m7up/vzZSDXISVvYU9oD2fsalwqHM0CYzZeZWeDPyxZ38D6V3PyMimQpQoNgVpL9X4lrZlCQdQLZhmH7Sg31TlVBkTO6zKs59hxU8T0AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~60~~ 58 bytes
```
f(n){n=n<4?n<2:-~n--*f(n--)-n*f(n)-(n-3)*f(--n)+n*f(n-1);}
```
[Try it online!](https://tio.run/##XU/bboMwDH3vV1hIlQiNNS7tpA7YHqZ9xeABhdChbW5FMg0NsU8fM5SidZFj2cfnODkKD0oNQ@WS6CilZPtASXiH34ToMYgokMZCIDeR4BKRxGbCMBBxP9Rk4b2oyRXQrYDPCFhtrHnOIYUukBBKiCRsJewk3PbxwtLtSSury4XoT8H0gMl7f6aqIxkL6qVoPM5avermrHCy9inM2v0j350j4W8fObO6Ojbgjq/VVOqWZX48lwmY@ksfK/fyD3EzA96CxLDZTOyLu8Uhbzq7nMZ5fDU1PK1cK65Rzeji@b/s1DClcp11CXgPnNcmIzZlJRi5@DZpqvN5bT/lRtuPhtjVqh9@VPVWHMyAn78 "C (gcc) – Try It Online")
*Port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScipt answer](https://codegolf.stackexchange.com/a/260269/9481).*
*Saved 2 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)*
[Answer]
# Raku, 132 bytes
Translated the (corrected) formula directly; not particularly golfed, just crunched out all the unnecessary whitespace:
```
->\n{[*](1..n)+[+]((1..n-1).map: ->\k{(-1)**k*[*](1..n -k)*[+]((1..k).map: ->\r{2**r*combinations(n -k,r)*combinations(k-1,r-1)})})}
```
[Try it online!](https://tio.run/##K0gtyjH7X5xYqaDxX9cuJq86WitWw1BPL09TO1o7VgPM1DXU1MtNLLBSACrIrtYAcrW0srVgChV0szW1YGqzESqLqo20tIq0kvNzkzLzEksy8/OKNUCKdYo0UQWzdQ11ioCG1oLgf00NU83/AA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes
```
F⁴⊞υ‹ι²FN⊞υΣ×⮌υ⟦⁺⁵ι±⁺²ι⁻¹ι⊕ι⟧I§υ±⁴
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY89CsJAEIV7T7GkmoWkMKgIVmIV0BDULqRINhNdSFbZ2RXvYhNB0QN4GW9j_sDyffPxHnN7i2OqxSkt6_ppTeHNv5_ipBlMOIssHcG6bI1EIF3mc74YdcdAna0JbZWhBv4Xd7aCvayQYIsX1IRgucviqLQEU5fJJoR4SA1Ch_wWNWwjVZPGvRAoobFCZTAHyRPebkZaKgOrlAwsTaByvLZrQ9WEt86DMkHDB6_Y8S6lk9xnff4B) Link is to verbose version of code. Outputs the `n`th element. Explanation:
```
F⁴⊞υ‹ι²
```
Start with the first four values (0-indexed, so `1, 1, 0, 0`).
```
FN⊞υΣ×⮌υ⟦⁺⁵ι±⁺²ι⁻¹ι⊕ι⟧
```
Use the recurrence relation to calculate `n` more values.
```
I§υ±⁴
```
Output the `4`th last value.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
õ á Ëäa eÉ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=9SDhIMvkYSBlyQ&input=Ng)
[Answer]
# [Scala](https://www.scala-lang.org/), 97 bytes
Based on the recurrence formula provided by [A002464](https://oeis.org/A002464).
Golfed version. [Try it online!](https://tio.run/##VZFBTsMwEEX3OcVX1IWHJihJUySqFoklC1aIFWJhEqcYglvFFiqKcgrEjtNxkTBx2lKkeEZ/5o397dhC1rLfPL2owuFWaoO2L1WFSpjFjXE0hJVmtcyp9TmjFKq2CknnkzDTlM64E6cUc8xGkXkxH8WMpj56kVMfAMMhb3yekM3aLnDdNPLj4c412qwfaYF7ox1WaJkE3mUNp6yzXPGgSCNkEWYR8gjzCBd05NRuy1dR5Sma@I8HUsYvkz@4eFbFq2qObPjz/RVG4PQZUuCxatNAaFOqHZbx6OKcpS6Upb29vUHexbdHmk5ag@9KuNOS4tLB6v@BLT@Bq42w4cQhvsLEYtLujQpdQfBuPEs4/AbqwnG2C4bVBf0v)
```
def f(n:Int):Int=if(n<4){if(n<2)1 else 0}else (n+1)*f(n-1)-(n-2)*f(n-2)-(n-5)*f(n-3)+(n-3)*f(n-4)
```
Ungolfed version.
```
object Main {
def f(n: Int): Int = {
if (n < 4) {
if (n < 2) 1 else 0
} else {
(n + 1)*f(n-1) - (n - 2) *f(n-2) - (n - 5) *f(n - 3) + (n - 3)* f(n - 4)
}
}
def main(args: Array[String]): Unit = {
val tests = Array(1, 2, 3, 4, 5, 6)
val expected = Array(1, 0, 0, 2, 14, 90)
val checker = Array("✕", "✓")
for (index <- tests.indices) {
val t = tests(index)
val s = f(t)
val e = expected(index)
println(s"$t -> $s ${checker(if (s == e) 1 else 0)}")
}
}
}
```
] |
[Question]
[
The Prisoner's Dilemma, but with 3 choices, and the payoffs are random!
Each round, your bot recieves a 3x3 grid and chooses a row to play. The grid might be this:
```
4 5 7
3 1 9
9 9 0
```
Each number in the grid is between 0 and 10 (inclusive). Your score for the round is `grid[your_play][their_play]`, and your opponent's is `grid[their_play][your_play]`.
You play 100(+/-10) rounds in sequence, keeping any information you wish. The winner is the bot with a higher score at the end (draws are 0.5 wins for both bots).
## Example
Using the grid above:
Player 1: row 2
Player 2: row 2
Both players get 0 points.
---
Player 1: row 1
Player 2: row 0
Player 1 gets 3 points, Player 2 gets 5 points.
# Winning
Each bot will play 10 games of ~100 rounds against each bot (including itself!). Your bot can win in two categories:
* **Score:** the total scores will be summed and the bot with the most points at the end will win.
* **Wins:** a 'win' is counted for the bot with the highest score after the ~100 rounds have been played.
The overall winner will be determined by combining the two tables. A winner will be accepted about 1 week after the most recent entry, but I will probably continue to update the highscore table if new entries are added.
# Technical details
Write two functions in Python 3 with these signatures:
```
def strategize(grid: list[list[int]], store: object) -> int
```
```
def interpret(grid: list[list[int]], moves: tuple(int, int), store: dict) -> None
```
* `strategize` is called each round and should return `0`, `1`, or `2`.
+ `grid` is the 3x3 grid of possible payouts.
+ `store` is an empty dict to store any kind of information you'd like to.
* `interpret` is called after every round.
+ `moves` is a tuple containing (`your_move`, `opponents_move`)
Put your code in the first code block in your answer so the controller can easily pull in your bot.
## Example bots
'Naiive' chooses the row with the highest average payout.
```
def strategize(grid, store):
sums = [(sum(x), i) for (i, x) in enumerate(grid)]
return max(sums)[1]
def interpret(grid, moves, store):
pass
```
'Random' picks a random row.
```
import random
def strategize(grid, store):
return random.randint(0, 2)
def interpret(grid, moves, store):
pass
```
# Rules
* No cheating by interfering directly with your opponent (through global variables etc.).
* Your function should be relatively quick to execute - the quicker it is, the better.
* You *may* submit multiple entries.
# Controller, arena
**The controller is available at <https://github.com/Nucaranlaeg/KOTH-random-prisoner>.**
This controller is largely adapted from <https://github.com/jthistle/KOTH-counting>.
A couple of example bots are provided along with it to demonstrate how to use it.
`arena.py` is what I'll be using to calculate final scores. It pits each bot against each other bot.
`update.py` will fetch all submitted bots from the contest page.
Using the flag `--c` or `-constant` will cause games to be played without randomizing the grid between rounds, purely for interest's sake.
# Current Results
```
By score:
1: Blendo with 12237.8 points
2: The Student with 11791.8 points
3: Naiive with 11728.2 points
4: Analyst with 11591.9 points
5: Min-Maxer with 11155.3 points
6: Rafaam with 11041.1 points
7: Naive Variation with 10963.1 points
8: Villain with 10853.6 points
9: Gradient-Mehscent with 10809.8 points
10: Gentleman with 10715.1 points
11: WhatDoYouExpect with 10676.6 points
12: Thief with 9687.6 points
13: Minimum Maximizer with 9656.0 points
14: HermitCrab with 9654.5 points
15: crab with 9001.9 points
16: Investigator with 8698.0 points
17: Random with 8653.3 points
By wins:
1: The Student with 15.2/16 wins
2: Blendo with 14.8/16 wins
3: Rafaam with 14.1/16 wins
4: WhatDoYouExpect with 13.9/16 wins
5: Naiive with 11.3/16 wins
6: Analyst with 10.8/16 wins
7: Min-Maxer with 10.4/16 wins
8: Naive Variation with 8.1/16 wins
9: Villain with 8.1/16 wins
10: HermitCrab with 7.3/16 wins
11: crab with 6.4/16 wins
12: Thief with 5.1/16 wins
13: Minimum Maximizer with 3.9/16 wins
14: Gradient-Mehscent with 1.9/16 wins
15: Investigator with 1.6/16 wins
16: Random with 1.5/16 wins
17: Gentleman with 1.5/16 wins
Combined leaderboard (fewer pts = better):
1: Blendo (3 pts)
1: The Student (3 pts)
3: Naiive (8 pts)
4: Rafaam (9 pts)
5: Analyst (10 pts)
6: Min-Maxer (12 pts)
7: Naive Variation (15 pts)
7: WhatDoYouExpect (15 pts)
9: Villain (17 pts)
10: Gradient-Mehscent (23 pts)
11: Thief (24 pts)
11: HermitCrab (24 pts)
13: Minimum Maximizer (26 pts)
13: crab (26 pts)
15: Gentleman (27 pts)
16: Investigator (31 pts)
17: Random (33 pts)
```
[Answer]
# crab
crab wants everyone to die. crab is happy when everyone else is unhappy. Yes, crab is back.
```
def strategize(grid, store):
aa = grid[0][0] #aa means '0-0'.
ab = grid[1][0] #and similarly for the others.
ac = grid[2][0]
ba = grid[0][1]
bb = grid[1][1] #I wish I had a macro to do this.
bc = grid[2][1]
ca = grid[0][2]
cb = grid[1][2]
cc = grid[2][2]
a = (aa * ab * ac)/3 # a, b, and c are the respective averages.
b = (ba * bb * bc)/3
c = (ca * cb * cc)/3
if a <= min(b, c):
return 0
if b <= min(a, c):
return 1
return 2
def interpret(grid, moves, store):
pass
```
Specifically, it picks the value that hurts the opponent the most.
[Answer]
# Blendo
Performs approximate bayesian inference over mixtures of different opponent strategies, and optimizes the chosen move with respect to the resulting prediction. Optimizes for expected score when ahead, and score difference when behind or almost equal. Also implements self-recognition. Requires NumPy.
```
import random
import numpy as np
def nash(grid):
payoffs = regrets = zeros = np.zeros(3)
strategy = np.full((3,), 1. / 3)
for _ in range(10):
payoffs = np.dot(grid, strategy)
v = np.dot(strategy, payoffs)
regrets = np.maximum(regrets + payoffs - v, zeros) + 1e-9
strategy = regrets / regrets.sum()
return strategy
def max_strategy(f):
def get_strategy(grid):
values = f(grid)
strategy = values == np.max(values)
return strategy / np.sum(strategy)
return get_strategy
expected = max_strategy(lambda grid: np.sum(grid, axis=1))
maximin = max_strategy(lambda grid: np.min(grid, axis=1))
maxidiag = max_strategy(np.diag)
def strategize(grid, store):
if not store:
store['is_me'] = True
store['side'] = 0
store['means'] = np.array([0.73336847, -0.38686278, -0.48677562, 0.09995684, -0.06624643, 0.38667801, -0.55640674, -0.1005102])
store['stds'] = np.array([1.6364209, 0.9467514, 0.79119316, 1.54119291, 1.44484517, 1.73075995, 0.8261992, 0.7124938])
store['score_delta'] = 0
grid = np.array(grid)
delta_grid = grid - grid.T
predictions = np.array([np.full(3, 1./3), nash(grid), nash(delta_grid), expected(grid), expected(delta_grid), maximin(grid), maximin(delta_grid), maxidiag(grid)]).T
weights = np.exp(np.random.normal(store['means'], store['stds']))
weights /= np.sum(weights)
probabilities = np.dot(predictions, weights)
store['predictions'] = predictions
if store['is_me']:
l, r = max(((i, j) for i in range(3) for j in range(i + 1)), key=lambda t: grid[t[0]][t[1]] + grid[t[1]][t[0]])
store['sides'] = (l, r)
if store['side'] == -1:
return l
if store['side'] == 1:
return r
return random.choice((l, r))
if store['score_delta'] <= 5:
grid = delta_grid
else:
grid = grid - 1e-9 * grid.T
return int(np.argmax(np.dot(grid, probabilities)))
def interpret(grid, moves, store):
predictions = store['predictions'][moves[1]]
store['score_delta'] += grid[moves[0]][moves[1]] - grid[moves[1]][moves[0]]
params = np.random.normal(store['means'], store['stds'], (200, 8))
weights = np.exp(params)
weights = weights / weights.sum(axis=1, keepdims=True)
likelihood = np.dot(weights, predictions)
c = 1. / np.mean(likelihood)
store['means'] = c * (likelihood[:,None] * params).mean(axis=0)
store['stds'] = np.sqrt(c * (likelihood[:,None] * (params - store['means'][None,:]) ** 2).mean(axis=0))
if store['is_me']:
l, r = store['sides']
if moves[1] not in (l, r):
store['is_me'] = False
else:
if store['side'] == 0:
if l != r and moves[0] != moves[1]:
if moves[0] == l:
store['side'] = -1
else:
store['side'] = 1
else:
if store['side'] == -1 and moves[1] != r:
store['is_me'] = False
elif store['side'] == 1 and moves[1] != l:
store['is_me'] = False
```
# ~~Switcheroo~~ No longer Competing
Switches between a few different strategies based on expected performance. Also implements self-recognition to maximally cooperate with itself.
```
import random
def sample(distribution):
u = random.random()
for i, p in enumerate(distribution):
u -= p
if u <= 0:
break
return i
def nash(grid):
grid = [[grid[i][j] for j in range(3)] for i in range(3)]
payoffs = [0] * 3
regrets = [0] * 3
strategy = [1. / 3] * 3
for i in range(10):
for a in range(3):
payoffs[a] = sum(p * v for p, v in zip(strategy, grid[a]))
v = sum(p * v for p, v in zip(strategy, payoffs))
regrets = [max(r + q - v, 0) for r, q in zip(regrets, payoffs)]
total_regret = sum(regrets)
if total_regret == 0:
strategy = [1. / 3] * 3
else:
c = 1. / total_regret
strategy = [r * c for r in regrets]
return strategy
def expected(grid):
values = [(sum(row), -sum(col)) for row, col in zip(grid, zip(*grid))]
v_max = max(values)
strategy = [int(v == v_max) for v in values]
c = 1. / sum(strategy)
return [p * c for p in strategy]
def strategize(grid, store):
if not store:
store['outcomes'] = [[1. / 11 for _ in range(11)] for _ in range(2)]
store['round_number'] = 0
store['is_me'] = True
store['side'] = 0
scores = [max(sum(i * n for i, n in enumerate(a)) / sum(a) for a in (a0, [random.gammavariate(n, 1) for n in a0])) for a0 in store['outcomes']]
strategy = scores.index(max(scores))
nash_strategy = nash(grid)
expected_strategy = expected(grid)
store['strategies'] = [nash_strategy, expected_strategy]
if store['is_me']:
l, r = max(((i, j) for i in range(3) for j in range(i + 1)), key=lambda t: grid[t[0]][t[1]] + grid[t[1]][t[0]])
store['sides'] = (l, r)
if store['side'] == -1:
return l
if store['side'] == 1:
return r
return random.choice((l, r))
return sample(store['strategies'][strategy])
def interpret(grid, moves, store):
for i, s in enumerate(store['strategies']):
for a, p in enumerate(s):
v = grid[a][moves[1]]
store['outcomes'][i][v] += p
if store['is_me']:
l, r = store['sides']
if moves[1] not in (l, r):
store['is_me'] = False
else:
if store['side'] == 0:
if l != r and moves[0] != moves[1]:
if moves[0] == l:
store['side'] = -1
else:
store['side'] = 1
else:
if store['side'] == -1 and moves[1] != r:
store['is_me'] = False
elif store['side'] == 1 and moves[1] != l:
store['is_me'] = False
store['round_number'] += 1
```
[Answer]
# Analyst
```
def strategize(grid, store = None):
nonzero = [a for a in range(3)]
if len([a for a in grid if not 0 in a]):
maximum = max(nonzero, key=lambda index: sum(grid[index]) if not 0 in grid[index] else 0)
if max(grid[maximum]) > 5:
return maximum
else:
return max(nonzero, key=lambda arr: max(grid[arr]))
return __import__('random').randint(0, 2)
def interpret(grid, moves, store):
pass
```
[Try it online with sample test cases](https://tio.run/##dVFdbsIwDH7nFH6jkaKpo0MDJHaEXaCqqkw1LIIklRsm4PKdnYWfSZCXOPb3p7g/xe/gq0VP49jhBoZIJuLWnrHYku00NwIhrOEzeFSrCfDxwZ@RAjdrA5tAYMB6IOO3WFSqSRi7gT364h4getL3IUIpDdNkQTnOHK07OBblqsgWGnZ4Wu@N@@pEosPjCoaDS9Hq9G7UP8m7AeB@QCjV1YFxIp0g2Y3ZHzC/hZBDGA/kL3muI1F7BnwY1xCtbob8atRflsxrW@v6QLFtiyn/XRfcVL1IYX0sSg0zNZGF8AupZ07ehws/OOS15O/rzTCMPQnvbn11/aZhruG90VBXGl41LKVc8q2hbCTOA9JlzEhmzDRUuUz8JySeSWJB8r3IprPkn5zGXw)
Analyst is a bot that tries to find the highest average out of nonzero possibilities, if the maximum is not high enough, then look for the index with the highest maximum. If all sublists have zeroes, choose randomly.
[Answer]
# WhatDoYouExpect
```
def strategize(grid, store):
expected = [0] * 3
for my_play in range(3):
for opponent_play in range(3):
expected[my_play] += grid[my_play][opponent_play] - grid[opponent_play][my_play]
return expected.index(max(expected))
def interpret(grid, moves, store):
pass
```
[Try it online!](https://tio.run/##fZBNCoNADIX3niLLsX8U3JSCJxEpQyfagZoJmbFoLz9Vq1I3zfLLy0teuA8PR9mFJUaDFfggOmBt36hqseYwACeYXhMYCjvGe0ADORTnEnaQTbhyAk1/46fuwRKIphpVNs8sAsfsCCn8kf2uKGbDEvY5jJesoNg4lXD8trd0VU/mgqEVWr1Plgx2qtGdWlCaJskY31JA4UE/p2/cC/32Cay9j/ED "Python 3.8 (pre-release) – Try It Online")
Always plays the move with the maximum expected value.
[Answer]
# Investigator
Plays naive and tit-for-tat for a few rounds, then investigates opponent responses every few rounds to find any adversarial responsive strategies. Following this, it assembles the best countermoves into a graph and executes the most positive cycle. Should be good versus both naive non-responsive opponents and basic responsive adversaries.
**EDIT: In retrospect, the original problem randomizes the scoring grid after each round, which breaks this solution. This would likely do well if the scoring grid isn't randomized though.**
```
def naive(grid):
return max((sum(grid[move][opp]-grid[opp][move] for opp in range(3)), move) for move in range(3))[1]
def strategize(grid, store):
if not store:
store["round"] = 0
store["responses"] = []
store["sequence"] = None
if store["round"] == 0:
return naive(grid)
elif store["round"] < 6:
return store["responses"][-1][1]
else:
return store["sequence"][store["round"]%len(store["sequence"])]
def most_common(lst):
return max(set(lst), key=lst.count)
def recursive_evaluate(start, trail, opponent, response, depth):
if depth == 6:
return trail
trail[0].append(opponent[trail[1][-1]] if len(trail[1]) > 0 else opponent[start])
trail[1].append(response[trail[1][-1]] if len(trail[1]) > 0 else start)
return recursive_evaluate(start, trail, opponent, response, depth+1)
def interpret(grid, moves, store):
store["responses"].append(moves)
if store["round"] % 6 == 6-1:
filtered = [[store["responses"][i+1][1] for i in range(store["round"]) if store["responses"][i][0] == me] for me in range(3)]
default = naive(grid)
opponent = [most_common(filtered[me]) if len(filtered[me])>0 else default for me in range(3)]
response = [max((grid[move][opponent[me]]-grid[opponent[me]][move], move) for move in range(3))[1] for me in range(3)]
evaluate = [recursive_evaluate(start, [[], []], opponent, response, 0) for start in range(3)]
scoring = [(sum(grid[evaluate[start][1][i]][evaluate[start][0][i]] for i in range(len(evaluate[start][1])))-sum(grid[evaluate[start][0][i]][evaluate[start][1][i]] for i in range(len(evaluate[start][1]))), evaluate[start][1]) for start in range(3)]
store["sequence"] = max(scoring)[1]
store["round"] += 1
```
[Answer]
# Min-Maxer
```
def strategize(grid, store):
max_best_moves = []
max_best_move_score = float("-inf")
for my_move in range(3):
worst_score = min(grid[my_move])
if worst_score == max_best_move_score: max_best_moves.append(my_move)
elif worst_score > max_best_move_score:
max_best_move_score = worst_score
max_best_moves = [my_move]
min_best_moves = []
min_best_move_score = float("inf")
for my_move in range(3):
opp_best_score = max(grid[opp_move][my_move] for opp_move in range(3))
if opp_best_score == min_best_move_score: min_best_moves.append(my_move)
elif opp_best_score < min_best_move_score:
min_best_move_score = opp_best_score
min_best_moves = [my_move]
best_of_both = [move for move in max_best_moves if move in min_best_moves]
if best_of_both: return best_of_both[0]
return max_best_moves[0]
def interpret(grid, moves, store): pass
```
Checks for moves that both maximize the worst case for itself and minimize the best case for its opponent. If there aren't any that are both at once, then it prefers moves that give itself points over sabotaging the opponent.
[Answer]
# Naive Variation
Naive works well, try to fight against aggressive players by choosing rows where every value has a reasonable payout (i.e. where several means are comparable, prefer rows with lower standard deviation)
```
def std_dev(numbers):
wgt = 1 / len(numbers)
mean = sum(numbers) * wgt
sqdiff_wgt = wgt * sum((number - mean) ** 2 for number in numbers)
return sqdiff_wgt ** 0.5
def strategize(grid, store=None):
bestScore = 0
bestIdx = -1
for ii, row in enumerate(grid):
rowSum = sum(row)
# Avoid numeric inflation
std = max(std_dev(row), 1)
score = rowSum/std
if score > bestScore:
bestScore = score
bestIdx = ii
return bestIdx
def interpret(grid, moves, store):
pass
```
[Answer]
# Thief
This person is a master pickpocket of credit cards that have expired.
```
def strategize(grid, store):
if not store:
store['opmove'] = 3
if store['opmove'] == 3:
sums = [(sum(x), i) for (i, x) in enumerate(grid)]
return max(sums)[1]
elif grid[store['mymove']][store['opmove']] > grid[store['opmove']][store['mymove']]:
sums = [(sum(x), i) for (i, x) in enumerate(grid)]
return max(sums)[1]
else:
return store['opmove']
def interpret(grid, moves, store):
store['opmove'] = moves[1]
store['mymove'] = moves[0]
```
The idea is that if it's the first round, it'll act like naiive, if it won the last round, it'll act like naiive, but if it lost the last round, it'll unconditionally return the opponents move. It isn't very smart. Please provide recommendations and bug fixes.
v1.0
* Initial write
v1.1
* Rewrote some to use store rather than plain global variables.
[Answer]
# Gentleman
This one is kind, and assumes everyone else is too. Optimizes for the opponent being Gentleman and picks the highest scoring option along the diagonal.
```
def strategize(grid, store = None):
nums = [0,1,2]
winner = 0
score = -1
for i in nums:
if grid[i][i] > score:
winner = i
score = grid[i][i]
return winner
def interpret(grid, moves, store):
pass
```
[Answer]
# HermitCrab
Very akin to a normal crab, but never picks an option that leaves itself out in the dust if it can help it.
```
def strategize(grid, store = None):
nums = [0,1,2]
winner = 0
opponentScores = [-1, -1, -1]
for i in nums:
opponentScores[i] = (grid[0][i]*grid[1][i]*grid[2][i])+(.1*(grid[0][i]+grid[1][i]+grid[2][i]))
fear = [0]
fearful = 10
terror = 0
for i in nums:
if min(grid[i]) < fearful:
fear = [i]
fearful = min(grid[i])
terror = 0
elif min(grid[i]) == fearful:
terror = terror + 1
fear.append(min(grid[i]))
mini = 100
if terror == 2:
fear = []
for i in nums:
if i not in fear:
if opponentScores[i] < mini:
winner = i
mini = opponentScores[i]
return winner
def interpret(grid, moves, store):
pass
```
[Answer]
# Gradient-Mehscent
It uses a terrible method of maximizing the score.
```
weightA = 1
weightB = 1
def strategize(grid, store):
global weightA, weightB
aa = grid[0][0] #aa means '0-0'.
ab = grid[1][0] #and similarly for the others.
ac = grid[2][0]
ba = grid[0][1]
bb = grid[1][1] #I wish I had a macro to do this.
bc = grid[2][1]
ca = grid[0][2]
cb = grid[1][2]
cc = grid[2][2]
dd = grid[0][0]
de = grid[0][1]
df = grid[0][2]
ed = grid[1][0]
ee = grid[1][1] #autocorrect is annoying
ef = grid[1][2]
fd = grid[2][0]
fe = grid[2][1]
ff = grid[2][2]
a = (aa + ab + ac)/3 # a, b, c, d, e, and f are the respective averages.
b = (ba + bb + bc)/3
c = (ca + cb + cc)/3
d = (dd + de + df)/3
e = (ed + ee + ef)/3
f = (fd + fe + ff)/3
scoreOfZero = (weightA * a + weightB * d)/2
scoreOfOne = (weightA * b + weightB * e)/2
scoreOfTwo = (weightA * c + weightB * f)/2
if scoreOfZero >= max(scoreOfOne, scoreOfTwo):
return 0
if scoreOfOne >= max(scoreOfZero, scoreOfTwo):
return 1
return 2
def interpret(grid, moves, store):
aa = grid[0][0] #aa means '0-0'.
ab = grid[1][0] #and similarly for the others.
ac = grid[2][0]
ba = grid[0][1]
bb = grid[1][1] #I wish I had a macro to do this.
bc = grid[2][1]
ca = grid[0][2]
cb = grid[1][2]
cc = grid[2][2]
dd = grid[0][0]
de = grid[0][1]
df = grid[0][2]
ed = grid[1][0]
ee = grid[1][1] #autocorrect is annoying
ef = grid[1][2]
fd = grid[2][0]
fe = grid[2][1]
ff = grid[2][2]
a = (aa + ab + ac)/3 # a, b, c, d, e, and f are the respective averages.
b = (ba + bb + bc)/3
c = (ca + cb + cc)/3
d = (dd + de + df)/3
e = (ed + ee + ef)/3
f = (fd + fe + ff)/3
global weightA, weightB
simWeightA = weightA + 0.01
simWeightB = weightB + 0.01
simScoreOfZero = (simWeightA * a + simWeightB * d)/2
simScoreOfOne = (simWeightA * b + simWeightB * e)/2
simScoreOfTwo = (simWeightA * c + simWeightB * f)/2
if simScoreOfZero >= max(simScoreOfOne, simScoreOfTwo):
upupscore = grid[0][moves[1]]
elif simScoreOfOne >= max(simScoreOfZero, simScoreOfTwo):
upupscore = grid[1][moves[1]]
else:
upupscore = grid[2][moves[1]]
simWeightA = weightA + 0.01
simWeightB = weightB - 0.01
simScoreOfZero = (simWeightA * a + simWeightB * d)/2
simScoreOfOne = (simWeightA * b + simWeightB * e)/2
simScoreOfTwo = (simWeightA * c + simWeightB * f)/2
if simScoreOfZero >= max(simScoreOfOne, simScoreOfTwo):
updownscore = grid[0][moves[1]]
elif simScoreOfOne >= max(simScoreOfZero, simScoreOfTwo):
updownscore = grid[1][moves[1]]
else:
updownscore = grid[2][moves[1]]
simWeightA = weightA - 0.01
simWeightB = weightB + 0.01
simScoreOfZero = (simWeightA * a + simWeightB * d)/2
simScoreOfOne = (simWeightA * b + simWeightB * e)/2
simScoreOfTwo = (simWeightA * c + simWeightB * f)/2
if simScoreOfZero >= max(simScoreOfOne, simScoreOfTwo):
downupscore = grid[0][moves[1]]
elif simScoreOfOne >= max(simScoreOfZero, simScoreOfTwo):
downupscore = grid[1][moves[1]]
else:
downupscore = grid[2][moves[1]]
simWeightA = weightA - 0.01
simWeightB = weightB - 0.01
simScoreOfZero = (simWeightA * a + simWeightB * d)/2
simScoreOfOne = (simWeightA * b + simWeightB * e)/2
simScoreOfTwo = (simWeightA * c + simWeightB * f)/2
if simScoreOfZero >= max(simScoreOfOne, simScoreOfTwo):
downdownscore = grid[0][moves[1]]
elif simScoreOfOne >= max(simScoreOfZero, simScoreOfTwo):
downdownscore = grid[1][moves[1]]
else:
downdownscore = grid[2][moves[1]]
if upupscore >= max(updownscore, downupscore, downdownscore):
weightA = weightA + 0.01
weightB = weightB + 0.01
elif updownscore >= max(upupscore, downupscore, downdownscore):
weightA = weightA + 0.01
weightB = weightB - 0.01
elif downupscore >= max(upupscore, updownscore, downdownscore):
weightA = weightA - 0.01
weightB = weightB + 0.01
else:
weightA = weightA - 0.01
weightB = weightB - 0.01
```
## How It Works
It probably doesn't. However, it should slowly move `weightA` and `weightB` so the bot is more effective. It's basically a tiny AI. The real core of Mehscent is the giant interpret function, which just plays around with the weights until something good happens.
[Answer]
# Minimum Maximizer
Not to be confused with the other one
```
def strategize(grid, store):
a = min(grid[0])
b = min(grid[1])
c = min(grid[2])
if a >= min(b, c):
return 0
if b >= min(a, c):
return 1
return 2
def interpret(grid, moves, store):
pass
```
[Answer]
# Rafaam
My final entry, came to me last night. Named after my favorite duplicitous multiverse-traveling villain, this optimizes its own success *compared* to its opponent, but sometimes acts kindly, and in doing so, determines if it's facing against itself, possibly changing from cruel to kind.
```
def strategize(grid, store = None):
if not store:
store["round"] = 0
store["opponent"] = 0
nums = [0,1,2]
kind = False
if store["opponent"] == 1:
kind = True
elif store["opponent"] == 0 and store["round"] == 2:
kind = True
if kind:
winner = 0
score = -1
for i in nums:
if grid[i][i] > score:
winner = i
score = grid[i][i]
return winner
scores = []
for i in nums:
row = []
for j in nums:
row.append((grid[i][j],(grid[i][j]/(grid[j][i]+0.01))))
scores.append(row)
safeRows = []
ratios = [[col[1] for col in row] for row in scores]
for i in nums:
non = ratios[i][:i] + ratios[i][(i + 1):]
if min(non) > 0.95:
safeRows.append(i)
scores = []
for i in nums:
scores.append((ratios[i][0]+ratios[i][1]+ratios[i][2]-ratios[i][i],i))
sortedScores = sorted(scores, key=lambda tup:(-tup[0],tup[1]))
for i in sortedScores:
if i[1] in safeRows:
return i[1]
return sortedScores[0][1]
def interpret(grid, moves, store):
if moves[0] != moves[1]:
store["opponent"] = -1
elif store["round"] == 4 and store["opponent"] == 0:
store["opponent"] = 1
store["round"] += 1
```
[Answer]
# Villain
My personal approach to solving the problem
```
def strategize(grid, store = None):
nums = [0,1,2]
safe = [(a, True) if 0 not in a else (a, False) for a in grid]
safeNums = []
for i in nums:
if safe[i][1]:
safeNums.append(i)
if len(safeNums) == 1:
return safeNums[0]
rudeNums = []
for i in nums:
rude = False
for j in grid:
if j[i] == 0:
rude = True
if rude:
rudeNums.append(i)
geniusNums = []
for i in nums:
if i in safeNums and i in rudeNums:
geniusNums.append(i)
if len(geniusNums) == 1:
return geniusNums[0]
if len(geniusNums) > 1:
winner = geniusNums[0]
mini = -1
for i in geniusNums:
newMin = min(grid[i])
if newMin > mini:
winner = i
mini = newMin
return winner
if len(safeNums) > 1:
winner = safeNums[0]
mini = -1
for i in safeNums:
newMin = min(grid[i])
if newMin > mini:
winner = i
mini = newMin
return winner
if len(rudeNums) == 1:
return rudeNums[0]
if len(rudeNums) >= 1:
winner = rudeNums[0]
mini = -1
for i in rudeNums:
newMin = grid[i][0]+grid[i][1]+grid[i][2]
if newMin > mini:
winner = i
mini = newMin
return winner
score = 0
winner = 0
for i in nums:
newScore = grid[i][0]+grid[i][1]+grid[i][2]
if newScore > score:
score = newScore
winner = i
return winner
def interpret(grid, moves, store):
pass
```
Should be a fine algorithm- first prioritizes safety, then screwing over opponents, then personal score. It doesn't bother minimizing opponent score, only giving them the potential for 0s.
[Answer]
# Why\_do\_I\_have\_so\_many\_ideas?!?!
It works. It's trash, but it works on Debian Buster with python 3.7.3
```
isFriendlyOne = 0
isFriendlyTwo = 0
def strategize(grid, store):
global isFriendlyOne, isFriendlyTwo
aa = grid[0][0] #aa means '0-0'.
ab = grid[1][0] #and similarly for the others.
ac = grid[2][0]
ba = grid[0][1]
bb = grid[1][1] #I wish I had a macro to do this.
bc = grid[2][1]
ca = grid[0][2]
cb = grid[1][2]
cc = grid[2][2]
dd = grid[0][0]
de = grid[0][1]
df = grid[0][2]
ed = grid[1][0]
ee = grid[1][1] #autocorrect is annoying
ef = grid[1][2]
fd = grid[2][0]
fe = grid[2][1]
ff = grid[2][2]
a = (aa + ab + ac)/3 # a, b, c, d, e, and f are the respective averages.
b = (ba + bb + bc)/3
c = (ca + cb + cc)/3
d = (dd + de + df)/3
e = (ed + ee + ef)/3
f = (fd + fe + ff)/3
scoreOfZero = (a + d)/2
scoreOfOne = (b + e)/2
scoreOfTwo = (c + f)/2
if isFriendlyOne != 2:
if scoreOfZero <= min(scoreOfOne, scoreOfTwo):
return 0
if scoreOfOne <= min(scoreOfZero, scoreOfTwo):
return 1
return 2
elif isFriendlyTwo != 2:
if scoreOfZero <= min(scoreOfOne, scoreOfTwo):
return 0
if scoreOfOne <= min(scoreOfZero, scoreOfTwo):
return 1
return 2
else:
if d >= max(e, f):
if dd >= max(de, df):
return 0
if de >= max(dd, df):
return 1
return 2
if e >= max(d, f):
if ed >= max(ee, ef):
return 0
if ee >= max(ed, ef):
return 1
return 2
if fd >= max(fe, ff):
return 0
if fe >= max(fd, ff):
return 1
return 2
def interpret(grid, moves, store):
global isFriendlyOne, isFriendlyTwo
if not store:
store['wroteOne'] = False
store['wroteTwo'] = False
isFriendlyOne = 0
isFriendlyTwo = 0
if moves[0] != moves[1]:
store['oldMatch'] = True
if max(isFriendlyOne, isFriendlyTwo) < 1:
if moves[1] == 0:
if grid[0][moves[0]] >= max(grid[1][moves[0]], grid[2][moves[0]]):
if moves[0] > 0:
isFriendlyOne = 1
store['wroteOne'] = True
if moves[1] == 1:
if grid[1][moves[0]] >= max(grid[2][moves[0]], grid[0][moves[0]]):
if moves[0] > 1:
isFriendlyOne = 1
store['wroteOne'] = True
elif moves[0] < 1:
isFriendlyTwo = 1
store['wroteTwo'] = True
if moves[1] == 2:
if grid[2][moves[0]] >= max(grid[1][moves[0]], grid[0][moves[0]]):
if moves[0] > 2:
isFriendlyOne = 1
store['wroteOne'] = True
elif moves[0] < 2:
isFriendlyTwo = 1
store['wroteTwo'] = True
if store['wroteOne']:
if isFriendlyTwo == 1:
isFriendlyOne = 2
if store['wroteTwo']:
if isFriendlyOne == 1:
isFriendlyTwo = 2
```
I ***think*** the new version implements self-recognition? Either this bot or Switcheroo has the most lines, although Switcheroo is vastly more complex. The entire interpret function is just for self-recognition.
[Answer]
# The Student
My late entry to the competition, spawned originally out of a simple desire to beat naiive, which has been remarkably successful. Eventually it morphed into this monstrosity that attempts to predict opponent moves and tracks likelihood of a some strategies I or people I talked to thought of.
```
import random
def strategize(grid, store):
possible_round_results = [
((0, 0), (grid[0][0], grid[0][0]), 0),
((0, 1), (grid[0][1], grid[1][0]), grid[0][1] - grid[1][0]),
((0, 2), (grid[0][2], grid[2][0]), grid[0][2] - grid[2][0]),
((1, 0), (grid[1][0], grid[0][1]), grid[1][0] - grid[0][1]),
((1, 1), (grid[1][1], grid[1][1]), 0),
((1, 2), (grid[1][2], grid[2][1]), grid[1][2] - grid[2][1]),
((2, 0), (grid[2][0], grid[0][2]), grid[2][0] - grid[0][2]),
((2, 1), (grid[2][1], grid[1][2]), grid[2][1] - grid[1][2]),
((2, 2), (grid[2][2], grid[2][2]), 0)
]
# Interpret data from Store to try to determine opponent and optimize
if('facing_self' in store and store['facing_self']):
# Determine move combination that gives the highest total points
max_score_result_index = max([(x[1][0] + x[1][1], i) for (i, x) in enumerate(possible_round_results)])[1]
if(store['should_pick_low'] is None):
random.seed()
return possible_round_results[max_score_result_index][0][random.randrange(0,2)]
elif(store['should_pick_low']):
return max(possible_round_results[max_score_result_index][0])
else:
return min(possible_round_results[max_score_result_index][0])
opponent_move = -1
if('opponent_strategy_probabilities' in store):
opponent_probabilities = [(store['opponent_strategy_probabilities'][x], x) for x in store['opponent_strategy_probabilities']]
opponent_probabilities.remove((store['opponent_strategy_probabilities']['self'], 'self'))
most_likely_opponent = max(opponent_probabilities)[1]
if(most_likely_opponent == 'safe_scorer'):
# safe_scorer
opponent_move = 0
safe_moves = []
for i in range(0,9,3):
if(min([possible_round_results[i][2], possible_round_results[i+1][2], possible_round_results[i+2][2]]) >= 0):
safe_moves.append((possible_round_results[i][2] + possible_round_results[i+1][2] + possible_round_results[i+2][2], possible_round_results[i][0][0]))
if(len(safe_moves) > 0):
opponent_move = max(safe_moves)[1]
else:
#resort to naiive_score_differential after loosing out on safety
opponent_move = max([(possible_round_results[i][2] + possible_round_results[i+1][2] + possible_round_results[i+2][2], possible_round_results[i][0][0]) for i in range(0, 9, 3)])[1]
elif(most_likely_opponent == 'hurtful'):
# hurtful
opponent_move = min([(sum(x), i) for (i, x) in enumerate(grid)])[1]
elif(most_likely_opponent == 'cooperative'):
# cooperative
opponent_move = max([(x[i], i) for (i, x) in enumerate(grid)])[1]
elif(most_likely_opponent == 'minimize_losses'):
# minimize_losses
opponent_move = max([(min(x), i) for (i, x) in enumerate(grid)])[1]
elif(most_likely_opponent == 'highest_expected_val'):
# highest_expected_val
opponent_move = max([(x[2], x[0][1]) for x in possible_round_results])[1]
elif(most_likely_opponent == 'naiive_score_differential'):
# naiive_scored_differential
opponent_move = max([(possible_round_results[i][2] + possible_round_results[i+1][2] + possible_round_results[i+2][2], possible_round_results[i][0][0]) for i in range(0, 9, 3)])[1]
else:
# naiive
opponent_move = max([(sum(x), i) for (i, x) in enumerate(grid)])[1]
else:
#assumed naiive
opponent_move = max([(sum(x), i) for (i, x) in enumerate(grid)])[1]
score_margin = 10
if('my_score' in store and store['my_score'] >= store['opponent_score'] + score_margin):
return max([(x[opponent_move], i) for (i, x) in enumerate(grid)])[1]
else:
possible_moves = []
for result in possible_round_results:
if(result[0][1] == opponent_move):
possible_moves.append(result)
return max([(x[2], i) for (i, x) in enumerate(possible_moves)])[1]
def interpret(grid, moves, store):
possible_round_results = [
((0, 0), (grid[0][0], grid[0][0]), 0),
((0, 1), (grid[0][1], grid[1][0]), grid[0][1] - grid[1][0]),
((0, 2), (grid[0][2], grid[2][0]), grid[0][2] - grid[2][0]),
((1, 0), (grid[1][0], grid[0][1]), grid[1][0] - grid[0][1]),
((1, 1), (grid[1][1], grid[1][1]), 0),
((1, 2), (grid[1][2], grid[2][1]), grid[1][2] - grid[2][1]),
((2, 0), (grid[2][0], grid[0][2]), grid[2][0] - grid[0][2]),
((2, 1), (grid[2][1], grid[1][2]), grid[2][1] - grid[1][2]),
((2, 2), (grid[2][2], grid[2][2]), 0)
]
# Estimate probability that opponent is using a specific strategy
naiive_move = max([(sum(x), i) for (i, x) in enumerate(grid)])[1]
naiive_score_differnetial_move = max([(possible_round_results[i][2] + possible_round_results[i+1][2] + possible_round_results[i+2][2], possible_round_results[i][0][0]) for i in range(0, 9, 3)])[1]
cooperative_move = max([(x[i], i) for (i, x) in enumerate(grid)])[1]
minimize_losses_move = max([(min(x), i) for (i, x) in enumerate(grid)])[1]
highest_expected_val_move = max([(x[2], x[0][1]) for x in possible_round_results])[1]
hurtful_move = min([(sum(x), i) for (i, x) in enumerate(grid)])[1]
safe_scorer_move = 0
safe_moves = []
for i in range(0,9,3):
if(min([possible_round_results[i][2], possible_round_results[i+1][2], possible_round_results[i+2][2]]) >= 0):
safe_moves.append((possible_round_results[i][2] + possible_round_results[i+1][2] + possible_round_results[i+2][2], possible_round_results[i][0][0]))
if(len(safe_moves) > 0):
safe_scorer_move = max(safe_moves)[1]
else:
#resort to naiive_score_differential after loosing out on safety
safe_scorer_move = max([(possible_round_results[i][2] + possible_round_results[i+1][2] + possible_round_results[i+2][2], possible_round_results[i][0][0]) for i in range(0, 9, 3)])[1]
self_move = None
if(('facing_self' in store) and (store['facing_self'])):
#find the two possibilities that might have been used, compare to move, and set to move if it matches to maintain self-facing status
max_score_result_index = max([(x[1][0] + x[1][1], i) for (i, x) in enumerate(possible_round_results)])[1]
possible_moves = possible_round_results[max_score_result_index][0]
if(moves[1] == possible_moves[0] or moves[1] == possible_moves[1]):
self_move = moves[1]
if(moves[0] < moves[1] and store['should_pick_low'] is None):
store['should_pick_low'] = True
elif(moves[0] > moves[1] and store['should_pick_low'] is None):
store['should_pick_low'] = False
else:
self_move = -1
else:
self_move = strategize(grid, store)
# Populate default values for store
if(not 'num_turns' in store):
store['num_turns'] = 0
store['my_score'] = 0
store['opponent_score'] = 0
store['opponent_strategy_probabilities'] = {
'self': 0,
'naiive': 0, # pick the row with the highest sum
'naiive_score_differential': 0, # pick the row with the highest average point gain over opponent
'hurtful': 0, # try to give opponent the column with lowest sum
'cooperative': 0, # try to behave cooperatively
'minimize_losses': 0, # pick row with highest minimum
'highest_expected_val': 0, # pick row with highest sum of score differences
'safe_scorer': 0 # determine rows with safety, then pick row with highest score differential
}
store['facing_self'] = False
store['should_pick_low'] = None
store['num_turns'] += 1
store['my_score'] += grid[moves[0]][moves[1]]
store['opponent_score'] += grid[moves[1]][moves[0]]
# Used to tune adaptation of bot
most_recent_weighting = 5
if(moves[1] == naiive_move):
store['opponent_strategy_probabilities']['naiive'] = (most_recent_weighting + (store['opponent_strategy_probabilities']['naiive'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
else:
store['opponent_strategy_probabilities']['naiive'] = ((store['opponent_strategy_probabilities']['naiive'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
if(moves[1] == naiive_score_differnetial_move):
store['opponent_strategy_probabilities']['naiive_score_differential'] = (most_recent_weighting + (store['opponent_strategy_probabilities']['naiive_score_differential'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
else:
store['opponent_strategy_probabilities']['naiive_score_differential'] = ((store['opponent_strategy_probabilities']['naiive_score_differential'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
if(moves[1] == cooperative_move):
store['opponent_strategy_probabilities']['cooperative'] = (most_recent_weighting + (store['opponent_strategy_probabilities']['cooperative'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
else:
store['opponent_strategy_probabilities']['cooperative'] = ((store['opponent_strategy_probabilities']['cooperative'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
if(moves[1] == minimize_losses_move):
store['opponent_strategy_probabilities']['minimize_losses'] = (most_recent_weighting + (store['opponent_strategy_probabilities']['minimize_losses'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
else:
store['opponent_strategy_probabilities']['minimize_losses'] = ((store['opponent_strategy_probabilities']['minimize_losses'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
if(moves[1] == highest_expected_val_move):
store['opponent_strategy_probabilities']['highest_expected_val'] = (most_recent_weighting + (store['opponent_strategy_probabilities']['highest_expected_val'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
else:
store['opponent_strategy_probabilities']['highest_expected_val'] = ((store['opponent_strategy_probabilities']['highest_expected_val'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
if(moves[1] == hurtful_move):
store['opponent_strategy_probabilities']['hurtful'] = (most_recent_weighting + (store['opponent_strategy_probabilities']['hurtful'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
else:
store['opponent_strategy_probabilities']['hurtful'] = ((store['opponent_strategy_probabilities']['hurtful'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
if(moves[1] == safe_scorer_move):
store['opponent_strategy_probabilities']['safe_scorer'] = (most_recent_weighting + (store['opponent_strategy_probabilities']['safe_scorer'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
else:
store['opponent_strategy_probabilities']['safe_scorer'] = ((store['opponent_strategy_probabilities']['safe_scorer'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
if(moves[1] == self_move):
store['opponent_strategy_probabilities']['self'] = (most_recent_weighting + (store['opponent_strategy_probabilities']['self'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
else:
store['opponent_strategy_probabilities']['self'] = ((store['opponent_strategy_probabilities']['self'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
if(store['opponent_strategy_probabilities']['self'] == 1 and store['num_turns'] > 4):
store['facing_self'] = True
else:
store['facing_self'] = False
```
] |
[Question]
[
Given an odd integer *N* (5 <= *N* <= 51), generate a maze with side length *N* that follows the following requirements:
The maze must be composed of the characters `|` `-` and `+`. It must use the `|` character as a vertical wall, the `-` character as a horizontal wall, and if that wall turns, the character `+` should be used.
The width of the path must be one character.
The maze must turn at least four times.
The maze must have outer walls, that break at two points: the start and the end.
The maze must consist of one non-breaking path, from the start to the end.
For example, the following is a valid maze: (*N* = 5)
```
+---+
| |
| | |
|
--+--
```
And for *N* = 7:
```
--+---+
| |
| | | |
| | | |
| | | |
| |
+---+--
```
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest number of bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~36 35 34 33~~ 32 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
2*×5H_2Bị⁾ |
_3”-ẋ”+;;Çsẋ2U3¦ṁµY
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=MirDlzVIXzJC4buL4oG-IHwKXzPigJ0t4bqL4oCdKzs7w4dz4bqLMlUzwqbhuYHCtVk&input=&args=MTM)**
Builds a nighter™ the other way around to the examples like:
```
+---- |
| |
| ----+
| |
+---- |
| |
| ----+
```
### How?
```
2*×5H_2Bị⁾ | - Link 1, pipes & spaces: n e.g. 7
2* - 2 raised to the nth power e.g. 128
×5 - multiply by 5 e.g. 640
H - halve e.g. 320
_2 - subtract 2 e.g. 318
B - convert to binary e.g. [1,0,0,1,1,1,1,1,0]
ị - index into (1-based)
⁾ | - char list " |" e.g. " || |"
_3”-ẋ”+;;Çsẋ2U3¦ṁµY - Main link: n e.g. 7
_3 - n - 3 e.g. 4
”- - char list "-"
ẋ - repeat e.g. "----"
”+ - char list "+"
; - concatenate e.g. "+----"
Ç - call last link (1) as a monad
; - concatenate e.g. "+---- || |""
s - split into chunks of n e.g. ["+---- |","| |"]
ẋ2 - repeat 2 times e.g. ["+---- |",
"| |",
+--> "+---- |",
| "| |"]
3¦ - apply to index 3: |
U - upend +--- "| ----+"
ṁ - mould like n (i.e. repeat to fill)
µ - monadic chain separation
Y - join with line feeds
```
(each byte saved involved fairly non-trivial changes, see the edit history if you're interested, although I just noticed that Link 1 is the same byte count as the more conventional repeat and join: `_2⁶ẋ“ ||“|”j`)
[Answer]
# JavaScript (ES6), 86 ~~92 116~~
~~Almost a kolmogorv-complexity challenge ...~~
With a little lateral thinking (inspired by @Neil's answer), it can be very shorter. Just turn 90°
```
n=>`|${s=' '[r='repeat'](n-2)}|
| ${h='-'[r](n-3)}+
|${s}|
+${h} |
`[r](n).slice(n*~n)
```
**Test**
```
f=
n=>`|${s=' '[r='repeat'](n-2)}|
| ${h='-'[r](n-3)}+
|${s}|
+${h} |
`[r](n).slice(n*~n)
function update() {
var i=+I.value
O.textContent=i&1? f(i): 'even'
}
update()
```
```
<input id=I value=7 min=5 max=49 step=2 type=number oninput="update()"><pre id=O><pre>
```
[Answer]
## Batch, 216 bytes
```
@echo off
set s=
for /l %%i in (4,1,%1)do call set s=-%%s%%
set b= %s:-= %
set r=! %s%+
set s=+%s% !
call:e
for /l %%i in (5,2,%1)do call:l
:l
echo ^|%b%^|
set t=%s%
set s=%r%
set r=%t%
:e
echo %s:!=^|%
```
`|`s are awkward in Batch so I ~~reflected~~ rotated the examples instead.
[Answer]
# PHP, 99 Bytes
up to down gates
```
for($s=str_pad("\n| ",$c=$argv[1],"-")."+\n";$i++<$c;)echo$i%2?$s=strrev($s):str_pad("|",$c-1)."|";
```
## PHP, 157 Bytes
left right gates
```
<?=($p=str_pad)($n="\n",$c=1+$argv[1],"+---").$p($n,$c-1,"| ")." #|"[$c%4].str_repeat($p($n,$c,"| "),$c-5).$p($n,$c-1," | ")."|# "[$c%4].$p($n,$c,"--+-");
```
[@Titus](https://codegolf.stackexchange.com/users/55735/titus) Thank you for minialize the bytes
[Answer]
## JavaScript (ES6), 87 bytes
A recursive function. Outputs a few trailing spaces.
```
f=(n,w=n,s=' -'[n&1].repeat(w-3),c='|+'[n&1])=>n?`
`+(n&2?c+s+' |':'| '+s+c)+f(n-1,w):s
```
### Test
```
f=(n,w=n,s=' -'[n&1].repeat(w-3),c='|+'[n&1])=>n?`
`+(n&2?c+s+' |':'| '+s+c)+f(n-1,w):s
console.log(f(9));
```
[Answer]
# Ruby 72 or 69 bytes
Lambda function. As shown, returns a newline-separated string. Delete the \*$/ to return an array of strings.
```
->n{(1..n).map{|i|"|%s |+%s || %s|| %s+"[i%4*5,5]%(" -"[i%2]*(n-3))}*$/}
```
Draws a maze rotated 90 degrees from the examples. For each line, a format string is selected (for example `+%s |` for the 1st line (there is no zeroth line) and the `%s` is substituted with an appopriate number of `-` or spaces using the `%` operator (equivalent to sprintf, but shorter.)
[Answer]
# Java 7, 228 bytes
```
String c(int n){String a="+x |",b="|y|\n",x,y,r=x=y="";int i=0;for(;i++<n-2;){x+=i>1?"-":"";y+=" ";}a=a.replace("x",x);b=b.replace("y",y);for(i=0;i<n;i++)r+=i%4<1?a+"\n":(i-2)%4==0?new StringBuffer(a).reverse()+"\n":b;return r;}
```
Used a similar vertical output as [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/98078/52210).
**Ungolfed & test code:**
[Try it here.](https://ideone.com/WvO0iZ)
```
class M{
static String c(int n){
String a = "+x |",
b = "|y|\n",
x = "",
y = "",
r = "";
int i = 0;
for (; i++ < n-2;){
x += i > 1
? "-"
: "";
y += " ";
}
a = a.replace("x", x);
b = b.replace("y", y);
for(i = 0; i < n; i++){
r += i % 4 < 1
? a+"\n"
: (i-2) % 4 == 0
? new StringBuffer(a).reverse()+"\n"
: b;
}
return r;
}
public static void main(String[] a){
System.out.println(c(7));
System.out.println();
System.out.println(c(25));
}
}
```
**Output:**
```
+---- |
| |
| ----+
| |
+---- |
| |
| ----+
+---------------------- |
| |
| ----------------------+
| |
+---------------------- |
| |
| ----------------------+
| |
+---------------------- |
| |
| ----------------------+
| |
+---------------------- |
| |
| ----------------------+
| |
+---------------------- |
| |
| ----------------------+
| |
+---------------------- |
| |
| ----------------------+
| |
+---------------------- |
```
[Answer]
# Python 2, 89 bytes
```
def f(n):x='+'+'-'*(n-3)+' |';y='|'+' '*(n-2)+'|';print'\n'.join(([x,y,x[::-1],y]*n)[:n])
```
**[repl.it](https://repl.it/EKGd)**
Builds an internal wall, `x`, like `'+---- |'` and an internal corridor, `y`, like `'| |'`
Then builds a list of `[x,y,x[::-1],y]` (`x[::-1]` is a reverse of `x`)
Then repeats that list `n` times (as a single list), with `*n`, and truncates it to the first `n` entries, with `(...)[:n]`, joins the list with line feeds, with `'\n'.join(...)`, and prints the result.
[Answer]
## Racket 187 bytes
Using display pattern by @JonathanAllan
```
(let*((u "+---- |")(v "| |")(sr(λ(s)(list->string(reverse(string->list s)))))(g #t)(d displayln)
(p(λ()(d(if g u(sr u)))(set! g(if g #f #t)))))(for((i(ceiling(/ n 2))))(p)(d v))(p))
```
Ungolfed:
```
(define (f n)
(let* ((sr (lambda(s)
(list->string
(reverse
(string->list s)))))
(u "+---- |")
(v "| |")
(g #t)
(d displayln)
(p (lambda()
(d (if g u (sr u)))
(set! g (if g #f #t)))))
(for ((i (ceiling (/ n 2))))
(p)
(d v))
(p)))
```
Testing:
```
(f 10)
```
Output:
```
+---- |
| |
| ----+
| |
+---- |
| |
| ----+
| |
+---- |
| |
| ----+
```
[Answer]
# GNU sed 140 bytes
Includes +1 for -r
```
s/1{5}//
h
s/^/+---+\n| |\n| | |\n | \n--+--/
/1/!b
:w
s/^..(..)[^$]*/\1&/gm
s/11//
/1/bw
G
:h
s/\n[^\n]*\n([^\n]*\n)/&\1/
s/1//
/1/bh
```
[Try it Online!](http://sed.tryitonline.net/#code=cy8xezV9Ly8KaApzL14vKy0tLStcbnwgICB8XG58IHwgfFxuICB8ICBcbi0tKy0tLwovMS8hYgo6dwpzL14uLiguLilbXiRdKi9cMSYvZ20Kcy8xMS8vCi8xL2J3CkcKOmgKcy9cblteXG5dKlxuKFteXG5dKlxuKS8mXDEvCnMvMS8vCi8xL2Jo&input=MTExMTExMTExMTEK&args=LXI)
Takes input in unary ([see this consensus](https://codegolf.meta.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary?answertab=votes#tab-top)).
Basically it inserts the size 5 maze, then appends the 2nd and 3rd character of each line to the beginning as many times as needed. Then duplicates the 3rd line (alternating `|` and ) as many times as needed.
The only interesting thing that I used is the `m` option on line 6 which allows `^` and `$` to match respectively (in addition to the normal behavior) the empty string after a newline, and the empty string before a newline.
[Answer]
# T-SQL, 123/79 bytes
**Golfed:**
```
DECLARE @i INT=7
,@ INT=0z:PRINT
STUFF(CHOOSE(@%4+1,'+- |','| |','| -+','| |'),3,0,REPLICATE(IIF(@%2=0,'-',' '),@i))SET
@+=1IF @<@i GOTO z
```
**Ungolfed:**
```
DECLARE @i INT = 9
DECLARE @i INT=7
,@ INT=0
z:
PRINT
STUFF(CHOOSE(@%4+1,'+- |','| |','| -+','| |'),3,0,
REPLICATE(IIF(@%2=0,'-',' '),@i))
SET @+=1
IF @<@i GOTO z
```
If you cheat and only make a narrow labyrinth the script can be golfed down to 79 bytes:
**Golfed:**
```
DECLARE @i INT = 9
,@ INT=0z:PRINT CHOOSE(@%4+1,'+- |','| |','| -+','| |')SET @+=1IF @<@i GOTO z
```
**Ungolfed:**
```
DECLARE @i INT = 9
,@ INT=0
z:
PRINT CHOOSE(@%4+1,'+- |','| |','| -+','| |')
SET @+=1
IF @<@i GOTO z
```
**[Fiddle for the long answer](https://data.stackexchange.com/stackoverflow/query/568444/generate-a-one-path-maze)**
[Answer]
# JavaScript (ES6), 96 bytes
```
f=(n,w=n-3)=>(h="-".repeat(w),n&2?`+${h} |`:`| ${h}+`)+(n>1?`
| ${" ".repeat(w)}|
`+f(n-2,w):"")
```
I was hoping recursion would turn out to be the shortest route, [and apparently it is](https://codegolf.stackexchange.com/a/98117/42545)...
] |
[Question]
[
Using one programming language write 5 single-line programs, each of which outputs a different line of the first verse to Harry Nilsson's 1972 song "[Coconut](http://youtu.be/aA9OqUuA6a0)" when run individually:
>
> Brother bought a coconut, he bought it for a dime
>
> His sister had another one, she paid it for a lime
>
> She put the lime in the coconut, she drank them both up
>
> She put the lime in the coconut, she drank them both up
>
> She put the lime in the coconut, she drank them both up
>
>
>
([full lyrics](http://www.azlyrics.com/lyrics/harrynilsson/coconut.html))
The last 3 lines have the same lyrics, so your last 3 programs might be as well.
There are 5 factorial or 120 ways these 5 single-line programs can be arranged one per line in a single 5-line program. You must optimize your single-line programs such that for as many of these 120 combinations as possible the 5-line program outputs the **entire verse in its proper order**, exactly as it appears above.
# Example
The simplest answer would have 5 single line print statements, the last 3 identical:
```
print('Brother bought a coconut, he bought it for a dime')
```
```
print('His sister had another one, she paid it for a lime')
```
```
print('She put the lime in the coconut, she drank them both up')
```
```
print('She put the lime in the coconut, she drank them both up')
```
```
print('She put the lime in the coconut, she drank them both up')
```
The output to the 5-line programs will be the verse in its proper order as long as the first two single-liners are in their correct places. Only 6 of the 120 possible arrangements accomplish this.
# Scoring
The submission with the most working cases out of all 120 wins. Tie breaker goes to the set of programs with the lowest cumulative [byte count](https://mothereff.in/byte-counter) (newlines not counted). The example has 309 bytes.
# Details
* **Your programs may not read their own source code.** Nor should they read other external files or require a network connection.
* Output to stdout or closest alternative. You may also output to a file with the name of your choice.
* "Single-line programs" are strings that contain any characters except [line terminators](http://en.wikipedia.org/wiki/Newline#Unicode) (you'll probably just need to worry about newlines)
.
* When composing the single-liners into the 5-liners you should add exactly 4 newlines, one between each adjacent pair of single-liners. You may optionally add a trailing newline.
[Answer]
# CJam, 120 valid permutations, ~~334 299~~ 290 bytes
```
"She put the lime in the coconut, she drank them both up"N+
"Brother bought a coconut, he bought it for a dime"N+]$~
"She put the lime in the coconut, she drank them both up"N+
"His sister had another one, she paid it for a lime"N+]$~
"She put the lime in the coconut, she drank them both up"N+
```
Pretty simple logic:
* Put each line of the song in each of the 5 programs
* Wrap everything on stack in an array
* Sort the array
* Unwrap the array so that the next program can use the same logic
* In each step, we have the partial lyrics in an array. Luckily, sorting the array gives the correct order of the lyrics.
**UPDATE**: Turns out that you don't need the wrap-sort-unwrap cycle after the 3 similar and appearing at the end lines of the song. I can explain why if its not that apparent :)
[Answer]
# [Prelude](http://esolangs.org/wiki/Prelude), 120 permutations, ~~2045~~ 2035 bytes
```
9-9-9-9-9-9-9-9-9-5-97+993++09-9-9-9-9-9-9-1-8992++96+209-9-9-9-9-9-9-1-94+58992++09-9-9-9-9-9-9-1-92+95+199+409-9-9-9-9-9-9-1-58991++09-9-9-9-9-9-9-1-09-9-9-9-9-7-992++993++95+96+396+309-9-9-9-9-9-9-1-58992++09-9-9-9-9-9-9-1-95+909-9-9-9-9-9-9-1-594+993+09-9-9-9-9-9-9-1-58992++09-9-9-9-9-9-9-1-992++993++97+09-9-9-9-9-9-9-1-5809-4- (9+9+9+9+9+9+9+9+9+9+6+!)
9-9-9-9-9-9-9-9-9-5-594+9409-9-9-9-9-9-9-1-109-9-9-9-9-9-9-1-99+96+609-9-9-9-9-9-9-1-992++909-9-9-9-9-9-9-1-992++87993++96+209-9-9-9-9-9-9-1-5809-9-9-9-9-9-9-1-09-9-9-9-9-7-992++993++95+96+396+309-9-9-9-9-9-9-1-109-9-9-9-9-9-9-1-992++87993++96+209-9-9-9-9-9-9-1-99+58992++96+99+09-9-9-3- (9+9+9+9+9+9+9+9+9+9+6+!)
9-9-9-9-9-9-9-9-9-5-97+993++09-9-9-9-9-9-9-1-8992++96+209-9-9-9-9-9-9-1-94+58992++09-9-9-9-9-9-9-1-92+95+199+409-9-9-9-9-9-9-1-58991++09-9-9-9-9-9-9-1-09-9-9-9-9-7-992++993++95+96+396+309-9-9-9-9-9-9-1-58992++09-9-9-9-9-9-9-1-95+909-9-9-9-9-9-9-1-594+993+09-9-9-9-9-9-9-1-58992++09-9-9-9-9-9-9-1-992++993++97+09-9-9-9-9-9-9-1-5809-4- (9+9+9+9+9+9+9+9+9+9+6+!)
9-9-9-9-9-9-9-9-9-5-594+993+09-9-9-9-9-9-9-1-109-9-9-9-9-9-9-1-99+96+609-9-9-9-9-9-9-1-992++909-9-9-9-9-9-9-1-49197+09-9-9-9-9-9-9-1-58991++09-9-9-9-9-9-9-1-09-9-9-9-9-7-595+96+09-9-9-9-9-9-9-1-99+58992++96+95+109-9-9-9-9-9-9-1-41809-9-9-9-9-9-9-1-99+5992++991++9991++09-9-9-9-9-9-9-1-991++909-9-6- (9+9+9+9+9+9+9+9+9+9+6+!)
9-9-9-9-9-9-9-9-9-5-97+993++09-9-9-9-9-9-9-1-8992++96+209-9-9-9-9-9-9-1-94+58992++09-9-9-9-9-9-9-1-92+95+199+409-9-9-9-9-9-9-1-58991++09-9-9-9-9-9-9-1-09-9-9-9-9-7-992++993++95+96+396+309-9-9-9-9-9-9-1-58992++09-9-9-9-9-9-9-1-95+909-9-9-9-9-9-9-1-594+993+09-9-9-9-9-9-9-1-58992++09-9-9-9-9-9-9-1-992++993++97+09-9-9-9-9-9-9-1-5809-4- (9+9+9+9+9+9+9+9+9+9+6+!)
```
This has ultimately convinced me that Prelude and CJam need a child. If it wasn't for Prelude's very limited instruction set, this submission would actually be very competitive, if it wouldn't even beat CJam.
The basic idea is the following
```
"push line 4" print
"push line 1"print
"push line 3" print
"push line 2" print
"push line 5" print
```
In Prelude, each line is its own "voice" with its own stack, and these voices are executed in parallel. That is, in the full program, each line will just individually construct the string and at print it at the end. But due to the offsets of the print statements, the order of the lines doesn't matter at all for the order of the output, since execution is left-to-right, not top-to-bottom.
Now, why are the lines so long? Prelude only stores numbers on its stack. Furthermore, it can only push a single-digit number at a time, so larger numbers have to be constructed from addition and subtraction (there is no multiplication either or other arithmetic either). So the largest part of code is simply calculating and pushing the right character codes. To shorten this a bit, I offset them by `96`. At the end, to print, I loop until the stack is empty (i.e. a `0` is encountered), add 96 to each number, and print it.
Note that the strings are pushed in reverse, since they're printed from last to first character.
This assumes [the Python interpreter](https://web.archive.org/web/20060504072747/http://z3.ca/~lament/prelude.py) with `NUMERIC_OUTPUT = False` (which is how the spec defines I/O).
I used the following CJam code to generate the string construction:
```
"Brother bought a coconut, he bought it for a dime
"W%{i96-_0<{zLa*9/:,'-*'-+0\+}{La*9/:,_,'+*W<}?}%
```
Lastly, just for fun, why I think this would be really short if Prelude had a concept of strings:
```
"pu htob meht knard ehs ,tunococ eht ni emil eht tup ehS"N+!
"emid a rof ti thguob eh ,tunococ a thguob rehtorB"N+!
"pu htob meht knard ehs ,tunococ eht ni emil eht tup ehS"N+!
"emil a rof ti diap ehs ,eno rehtona dah retsis siH"N+!
"pu htob meht knard ehs ,tunococ eht ni emil eht tup ehS"N+!
```
Now the print statements `!` are already in the right order, so I wouldn't even need to offset them. I think I'll get down to implementing this some time.
[Answer]
# Ruby, 120 valid permutations, 430 bytes
```
$*[1]='His sister had another one, she paid it for a lime';a||=at_exit{puts($*-[p])}
$*[0]='Brother bought a coconut, he bought it for a dime';a||=at_exit{puts($*)}
$*[2]='She put the lime in the coconut, she drank them both up';a||=at_exit{puts($*-[p])}
$*[3]='She put the lime in the coconut, she drank them both up';a||=at_exit{puts($*-[p])}
$*[4]='She put the lime in the coconut, she drank them both up';a||=at_exit{puts($*-[p])}
```
Works in any order, or individually. Each line modifies global state, then sets a hook to be executed at the end of the program unless the hook has already been set.
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 120 permutations, 703 bytes
```
< /a"emid a rof ti thguob eh ,tunococ a thguob rehtorB"0a.#.!50padpacpabpaapa9pa8pa7p97p87p77p67p57p95p84p73p62p51"/////\\\\\>l0=?;o"
< / a"emil a rof ti diap ehs ,eno rehtona dah retsis siH"09.#.!50padpacpabpaapa9pa8pa7p97p87p77p67p57p95p84p73p62p51"/////\\\\\>l0=?;o"
< / a"pu htob meht knard ehs ,tunococ eht ni emil eht tup ehS"08.#.!50padpacpabpaapa9pa8pa7p97p87p77p67p57p95p84p73p62p51"/////\\\\\>l0=?;o"
< / a"pu htob meht knard ehs ,tunococ eht ni emil eht tup ehS"07.#.!50padpacpabpaapa9pa8pa7p97p87p77p67p57p95p84p73p62p51"/////\\\\\>l0=?;o"
</ a"pu htob meht knard ehs ,tunococ eht ni emil eht tup ehS"06.#.!50padpacpabpaapa9pa8pa7p97p87p77p67p57p95p84p73p62p51"/////\\\\\>l0=?;o"
```
The one-liner restriction was pretty tough for a 2D language, so I had to find a way to make the most of the `.` teleport instruction.
The initial `<` makes program flow leftward, wrapping around and executing
```
"o;?=0l>\\\\\\/////"15p26p37p48p59p75p76p77p78p79p7ap8ap9apaapbapcapdap
```
This is a series of `p` (put) instructions which places chars until the board looks like this:
```
< /<lyrics1>0a.#.!50<blah>
< / <lyrics2>09.#.!50<blah>
< / <lyrics3>08.#.!50<blah>
< / <lyrics4>07.#.!50<blah>
</ <lyrics5>06.#.!50<blah>
/ \
/ \
/ \
/ \
/ \
>l0=?;o
```
The `#.!50` then flips program flow back to rightward again, before jumping to line 5. What follows is this:
* Following the `/` mirror on line 5 finds lyrics 5, which is pushed onto the stack. We then teleport to line 6.
* Following the `/` mirror on line 6 finds lyrics 4, which is pushed onto the stack. We then teleport to line 7.
* Following the `/` mirror on line 7 finds lyrics 3...
This happens until we push lyrics 1, at which point we teleport to line 10. This is a loop to print the whole stack until it is empty.
If only one line of the program is present, then the `\` mirrors do the same job as the teleports on each lyric line.
If the program is scrambled, then the explanation above still applies, so the program works for all permutations!
[Answer]
# [JavaScript (V8)](https://v8.dev/), 389 bytes
```
a=setTimeout;a(_=>a(_=>print`She put the lime in the coconut, she drank them both up`))
a=setTimeout;a(_=>a(_=>print`She put the lime in the coconut, she drank them both up`))
a=setTimeout;a(_=>a(_=>print`She put the lime in the coconut, she drank them both up`))
setTimeout(_=>print`His sister had another one, she paid it for a lime`)
print`Brother bought a coconut, he bought it for a dime`
```
[Try it online!](https://tio.run/##1U4xDsIwDNz7Co9Ugh0JlYGJHXbqNoEYaBwlTr8f3BaVN7DY5/Pd2U8cMfWRguzGfSnYJCtXGixnOeDm1hznEiJ5aS/OQsgCov2tGiA/45579lm2kHQwEf1rogfoWBzk0NZ19W@5v9Rf3JkSJEpiIzg0gF7litnbJSkgGSCBO0fA@WBbV4v1FBdtx/nhRLfrC@r7kqvTTM5SPg "JavaScript (V8) – Try It Online")
Silly
[Answer]
# Deadfish~, 6 (it's probably not possible to do more)
```
{iiiiii}iiiiiic{iiiii}ddcdddciiiiic{d}ddcdddc{i}iiic{{d}ii}ddc{iiiiii}iiiiiic{i}iiiciiiiiic{d}ddddcic{i}iic{{d}ii}ddddc{iiiiii}iiiiic{dddddd}dddddc{{i}ddd}dddc{i}iic{d}ddc{i}iicdc{i}dddcdc{{d}iii}ddc{d}ddc{{i}ddd}iicdddc{{d}iii}ic{iiiiii}iiiiiic{i}iiiciiiiiic{d}ddddcic{i}iic{{d}ii}ddddc{{i}ddd}iiic{i}ic{{d}ii}ddddc{{i}ddd}c{i}dciiic{{d}ii}ddc{iiiiii}iiiiic{dddddd}dddddc{{i}ddd}ddciiiiiciiiic{d}iic
```
```
{iii}iic{iiii}c{iii}iiic{i}c{{d}ii}dddc{{i}dd}iiic{d}c{i}cic{d}dddddc{i}iiic{{d}ii}ddc{{i}ddd}iic{d}iiiciiic{{d}iii}iic{iiiiii}iiiiic{i}iiiciciiiiic{d}ddcdddc{i}iiic{{d}ii}ddc{{i}dd}dcdc{d}ic{dddddd}iiic{d}ddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}dd}c{d}dddddc{i}ddcdddddc{{d}iii}iic{{i}ddd}iiic{i}ic{{d}ii}ddddc{{i}ddd}c{i}dciiic{{d}ii}ddc{iiiiii}iiiiic{dddddd}dddddc{{i}ddd}iiiiiicdddciiiic{d}iic
```
```
{iii}iic{iiiii}ic{ii}icdddc{{d}iii}ic{{i}dd}ciiiiicdc{{d}ii}ddddc{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}iiiiiicdddciiiic{d}iic{{d}iii}ic{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}dddc{i}iic{d}ddc{i}iicdc{i}dddcdc{{d}iii}ddc{d}ddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}ddd}ddc{i}iiiic{dd}iiic{i}iiicdddc{{d}iii}dddddc{{i}dd}iiiic{d}ddcdddc{i}ddc{{d}ii}iiic{iiiiii}iiiiiic{i}iiiciiiiic{d}ddc{{d}iii}ddc{{i}dd}iiiiicdddddc
```
```
{iii}iic{iiiii}ic{ii}icdddc{{d}iii}ic{{i}dd}ciiiiicdc{{d}ii}ddddc{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}iiiiiicdddciiiic{d}iic{{d}iii}ic{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}dddc{i}iic{d}ddc{i}iicdc{i}dddcdc{{d}iii}ddc{d}ddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}ddd}ddc{i}iiiic{dd}iiic{i}iiicdddc{{d}iii}dddddc{{i}dd}iiiic{d}ddcdddc{i}ddc{{d}ii}iiic{iiiiii}iiiiiic{i}iiiciiiiic{d}ddc{{d}iii}ddc{{i}dd}iiiiicdddddc
```
```
{iii}iic{iiiii}ic{ii}icdddc{{d}iii}ic{{i}dd}ciiiiicdc{{d}ii}ddddc{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}iiiiiicdddciiiic{d}iic{{d}iii}ic{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}dddc{i}iic{d}ddc{i}iicdc{i}dddcdc{{d}iii}ddc{d}ddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}ddd}ddc{i}iiiic{dd}iiic{i}iiicdddc{{d}iii}dddddc{{i}dd}iiiic{d}ddcdddc{i}ddc{{d}ii}iiic{iiiiii}iiiiiic{i}iiiciiiiic{d}ddc{{d}iii}ddc{{i}dd}iiiiicdddddc
```
This is so long.....
] |
[Question]
[
The program plays white.
Example stdin:
```
8 ║♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜
7 ║♟ ♟ ♟ ♟ … ♟ ♟ ♟
6 ║… … … … … … … …
5 ║… … … … ♟ … … …
4 ║… … … … … … … …
3 ║… … ♘ … … … … …
2 ║♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙
1 ║♖ … ♗ ♕ ♔ ♗ ♘ ♖
——╚═══════════════
—— a b c d e f g h
```
Example stdout:
```
8 ║♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜
7 ║♟ ♟ ♟ ♟ … ♟ ♟ ♟
6 ║… … … … … … … …
5 ║… … … … ♟ … … …
4 ║… … … … ♙ … … …
3 ║… … ♘ … … … … …
2 ║♙ ♙ ♙ ♙ … ♙ ♙ ♙
1 ║♖ … ♗ ♕ ♔ ♗ ♘ ♖
——╚═══════════════
—— a b c d e f g h
```
Any valid move is ok. "En passant" and castling are ignored. It is ok to show error messages or print nothing if there is no valid move.
The answer with the most votes wins.
[Answer]
*I'm not complaining about upvotes, but to be fair... my solution here isn't actually all that great. Ugoren's is better, apart from lacking unicode support. Be sure to look at all the answers before voting, if you've come across this question only now!*
Anyway.
# [Haskell](https://www.haskell.org/), 1074 bytes (without castling)
```
χ=w⋈b;w="♙♢♤♔♕♖♗♘";b="♟♦♠♚♛♜♝♞"
μ=t⤀ζ++((\(x,y)->(x,-y))⤀)⤀μ;q c|((_,m):_)<-((==c).fst)☂(χ⋎μ)=m
t(x:y:l)=(d x,d y):t l;t _=[];d c=fromEnum c-78
ζ=["NM","NL","MMOM","MMMNMONMNOOMONOO",σ⋈δ,σ,δ,"MLOLPMPOOPMPLOLM"]
σ=l>>=(\c->'N':c:c:"N");δ=[l⋎l,reverse l⋎l]>>=(>>=(\(l,r)->[l,r]))
l="GHIJKLMOPQRSTU"
α c|c∊"♢♤"='♙'|c∊"♦♠"='♟'|c∊χ=c;π('♙':_)=6;π _=1
(⋎)=zip;(⤀)=map;(∊)=elem;(✄)=splitAt;(☂)=filter;(⋈)=(++)
φ r@(x,y)p a
|x>7=φ(0,y+1)p a
|y>7=[]
|c<-a✠r=(c⌥r)p a y⋈φ(x+1,y)p a
(c⌥r)p a y
|c==p!!0=(a☈r)c χ++const(y==π p)☂(a☈r)(p!!1)χ++(a☈r)(p!!2)('…':w)
|c∊p=(a☈r)c χ
|True=[]
a✠(x,y)=a!!y!!(x*2);o(x,y)=x>=0&&x<8&&y>=0&&y<8
(n➴a)(x,y)|(u,m:d)<-y✄a,(l,_:r)<-(x*2)✄m=u⋈(l⋈(n:r):d)
(a☈r@(x,y))c b=(α c➴('…'➴a)r)⤀((\r->o r&¬((a✠r)∊b))☂((\(ξ,υ)->(x+ξ,y+υ))⤀q c))
main=interact$unlines.uncurry((⋈).zipWith((⋈).(:" ║"))['8','7'..]
.head.((all(any('♔'∊)).φ(0,0)b)☂).φ(0,0)w.(drop 3⤀)).(8✄).lines
```
[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rKwWoBP0EY1PL8vKdQkSys@Tcu2ToA/eFqCrX@Np5SMQm30StFwEztAXSKkWoMOFp2dAU6CDBQ@e2aHCxwfimx7x6d9f/y2OwUtqIx91UIC20O9o@z0 "Haskell – Try It Online")
---
When you have [GHC](http://www.haskell.org/ghc/) installed (for instance as part of the [Haskell platform](http://hackage.haskell.org/platform/)) you can do just
```
$ runhaskell def0.hs < examplechessboard.txt
8 ║♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜
7 ║♟ ♟ ♟ ♟ … ♟ ♟ ♟
6 ║… … … … … … … …
5 ║… ♘ … … ♟ … … …
4 ║… … … … … … … …
3 ║… … … … … … … …
2 ║♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙
1 ║♖ … ♗ ♕ ♔ ♗ ♘ ♖
——╚═══════════════
—— a b c d e f g h
```
[Answer]
## C, 734 672 640 characters
Characters counted without removable whitespace.
The file format I used is not as requested, but simplified ASCII.
I need to add Unicode character support, it would cost some characets.
```
char*r=" kpnbrq KPNBRQ $ ,&)$wxy()879()8(6:GI(",B[256],*b=B,i;
e(x,d,m,V,c,r,n,p){
for(r=0,p=b[x];m/++r;){
n=x+d*r;
if(p==2+8*(d<0)||n&136||!(b[n]?r=8,8^p^b[n]^8&&c&65^64:c&65^65)
? r=m,0
: V?v(n,x):b[n]==1)
return b[x]=0,b[n]=p%8-2||n/16%7?p:p+4;
}
return d>0&&e(x,-d,m,V,c);
}
d(x,v,m,i)char*m;{
return(i=*m-40)?e(x,i%64,b[x]%8-2?b[x]&4?7:1:(x/16-1)%5|i%2?1:2,v,i)||d(x,v,m+1):0;
}
v(t,f){
bcopy(B,b+=128,128);
b[t]=b[f];b[f]=0;
i=a(1,63);
b=B;
return!i;
}
a(c,n){
return b[i=n*2-n%8]&&b[i]/8==c&&d(i,!c,r+r[b[i]%8+15]-10)||n--&&a(c,n);
}
main(){
for(;gets(b);b+=8)for(;*b;b++)*b=strchr(r,*b)-r;b=B;
for(i=64*!a(0,63);i<64;i++%8-7||puts(""))putchar(r[b[i*2-i%8]]);
}
```
Input/output file format:
Must be exactly 8 lines of exactly 8 characters. `pnbrqk` are used for white pieces, `PNBRQK` for black pieces, spaces for spaces:
```
RNBQKBNR
PPPP PPP
n P
pppppppp
r bqkbnr
```
The logic is quite simple:
For each possible move of each white piece, try each possible move of each black piece.
If no black move captures the white king, the white move is valid.
The board is maintained as `char[256]`, treated as a 16x16 matrix, where only the top-left 8x8 is used. Positions and movement vectors are kept in 8-bit integers (`x:4,y:4`). The extra bit allows using simple arithmetic (`new_pos = old_pos + steps*direction`), with easy detection of the board edge (`&0x88` does the magic).
`r[]` encodes three things:
1. The first 15 bytes map internal piece codes (K=1,P=2,N=3,B=4,R=5,Q=6) to letters.
2. The next 6 bytes map internal piece codes to offsets in the last part (K and Q are the same, B is their tail).
3. The last 16 bytes encode the movement of all pieces, as `'('+vector`.
Functions:
1. `main` reads the board, converts letters to internal code, calls `a` to find white moves, prints the board.
2. `a`recursively loops over the 64 squares. For each piece of the right color (parameter `c`), it finds the movement rule for the piece and calls `d`.
3. `d` recursively loops over the encoded movement rule, which is a list of vectors, calling `e` for each one. It gives `e` the original position, the vector and the range limit (7 for pieces above B, 2 for second rank pawns, 1 otherwise).
4. `e` tests all movements along a vector. If the move is possible (i.e. pawns move forward, within board, not blocked, pawn capture diagonally), checks one of two things. For white moves, runs `v` to validate the move. For black moves, checks if the white king is captured. If true, the move is played on the board.
5. `v` validates a white move. It copies the board aside, executes the move to test, and calls `a` again, to look for black moves.
[Answer]
## Python 2.6, 886 - 1425 characters
My initial version (in the revisions) came in at 886 characters but did not satisfy the spec completely (it did not check for avoiding checkmate ; it didn't even consider the possible moves of the black pieces).
Now it does (and I've fixed several bugs in the original). Alas this comes with a cost in characters: 1425 for now, but there should still be little room for improvement. This version should be a lot more solid in handling edge cases then the previous one.
```
#-*-coding:utf8-*-
import sys;e=enumerate
B,W=["♟","♜","♞","♝","♛","♚"],["♙","♖","♘","♗","♕","♔"]
R={"♙":[11,42],"♖":[28],"♘":[31],"♗":[8],"♕":[8,28],"♔":[1,21]}
def F(w):return sum([[(i,j)for j,p in e(o)if p==w]for i,o in e(Z)],[])
def G(x,y):
P=Z[x][y];D=P in W;L=[]
for o in R[P]if D else R[unichr(ord(P.decode('utf8'))-6).encode('utf8')]:
r,k="%02d"%o
for g,h in[[(-1,-1),(1,1),(-1,1),(1,-1)],[[(1,-1),(1,1)],[(-1,-1),(-1,1)]][D],[(-1,0),(1,0),(0,-1),(0,1)],[(-2,-1),(-2,1),(-1,-2),(-1,2),(1,-2),(1,2),(2,-1),(2,1)],[(-1,0)]][int(r)]:
J=0
for i in range(int(k)):
T=x+(i+1)*g;U=y+(i+1)*h
if T<0 or T>7 or U<0 or U>7:break
M=Z[T][U]
if not J:L.append((T,U,P,M))
else:break
if r in"02"and(M in W+B):
J=1
if not((D and M in B)or(not D and M in W)):L.pop()
elif(r=="1"and not((D and M in B)or(not D and M in W)))or(r=="4"and((i==1 and x!=6)or M!="…")):L.pop()
return L
Z=[[y for y in l[5:].split()]for l in sys.stdin.readlines()[:-2]]
Q=[]
for p in R:
for i,j in F(p):
for M,L,c,_ in G(i,j):
O=Z[M][L];Z[i][j]="…";Z[M][L]=c;E=[];map(E.extend,map(F,B))
if not any(any(1 for _,_,_,I in G(v,h)if I==["♔","♚"][c in B])for v,h in E):Q.append((i,j,M,L,c))
Z[i][j]=c;Z[M][L]=O
(x,y,X,Y,p)=Q[0];Z[x][y]="…";Z[X][Y]=p
for i,h in e(Z):print`8-i`+' ║'+' '.join(h)
print"——╚"+"═"*16+"\n—— a b c d e f g h"
```
Example input and output:
```
# INPUT
8 ║♜ ♞ ♝ … ♚ ♝ ♞ ♜
7 ║♟ ♟ ♟ ♟ … ♟ ♟ ♟
6 ║… … … … … … … …
5 ║… … … … ♟ … … …
4 ║… … … … … … ♙ ♛
3 ║… … … … … ♙ … …
2 ║♙ ♙ ♙ ♙ ♙ … ♙ …
1 ║♖ ♘ ♗ ♕ ♔ ♗ ♘ ♖
——╚═══════════════
—— a b c d e f g h
```
```
# OUTPUT
8 ║♜ ♞ ♝ … ♚ ♝ ♞ ♜
7 ║♟ ♟ ♟ ♟ … ♟ ♟ ♟
6 ║… … … … … … … …
5 ║… … … … ♟ … … …
4 ║… … … … … … ♙ ♛
3 ║… … … … … ♙ ♙ …
2 ║♙ ♙ ♙ ♙ ♙ … … …
1 ║♖ ♘ ♗ ♕ ♔ ♗ ♘ ♖
——╚════════════════
—— a b c d e f g h
```
] |
[Question]
[
**Given a 24 hour time, e.g. 20:48, output the nearest time where each adjacent pair of digits has an absolute difference of 1, e.g. 21:01.**
That is, each number in the output must differ from the numbers next to it by 1, and the output must be the closest time, forwards or backwards, for which this is true. Time can be considered to wrap around. For example, 23:55 and 00:05 are only 10 minutes apart.
### Input
* Input can be in any reasonable form which represents all four digits of a 24 hour time. E.x. a string, "20:48" (colon optional), a list of integers, [2, 0, 4, 8], or a single integer 2048.
* Leading zeros are optional for input. Use whatever is most convenient.
* You can assume the input will always represent a valid 24 hour time.
### Output
* You must output four integers which represent a valid 24 hour time. The individual integers can be represented in whatever form is most convenient. E.x. [2, 1, 0, 1] or "2101".
* Leading zeros are *not* optional for output. E.x. you can't output 1:23 instead of 01:23.
* You may optionally output a separator between the hours and minutes. This can be a colon, period, space, newline, or some other junk that saves you a byte. Whatever separator you choose, it must be consistent from one output to another.
* If there are two equally close times to the input which satisfy the requirements, you may output either.
* Note there are only 16 possible outputs: 01:01, 01:21, 01:23, 10:10, 10:12, 12:10, 12:12, 12:32, 12:34, 21:01, 21:21, 21:23, 23:21, 23:23, 23:43, and 23:45.
### Test cases
* 00:10 -> 23:45
* 01:23 -> 01:23
* 05:46 -> 01:23
* 05:47 -> 10:10
* 12:00 -> 12:10
* 16:47 -> 12:34
* 16:48 -> 21:01
* 20:48 -> 21:01
* 21:22 -> 21:23 *or* 21:21
[Python 3 reference implementation](https://tio.run/##dVLRbuIwEHzPV4xUnYjblAZ66gMt9xV3z8hOjGIV25G9qEJVv51bmxAlVH3BnllmPTub/kSdd8/nc6v3iEQ745wOZVfBVmhN0A0Z78SmAKNI2KLm60dnDhp/w1GnAiCZ7/D0hFWdscr41xU2DO2k3GY8ls0eUsVS4hFKYLvFCtK1mVPMNTdcw1x74S6vA0HTMTgsPr8@vzbpZ7Hc@2AllbKCqtDwLKLKE1wMpFEeuMFrhh37kbhnP3iAypRlqrlS7UCxYozk9Wrd4g01fODLny1e6qun1LTsknpMkUde/x7KdsjgpS6KIfuceo6azX/I0O7IWF2NaFjA7ZZWghVKNu8TyQh/0DxmEbuf9X6b6y6TDNlOLTF/h3@u8VY7Ann4I/VHgvLUoffRKHMwZHRMf7x9hPf27ZW76QpTlpMNzrOYzZlmGHQz/mxs7wMhnmLR7SIFnjkdKYhTXEZqjVsGLduDcboUTATTp7Nn2@VisxBFH4yjMi0lnbkJf0DpnjsJIYpzvdqs1/8B "Python 3 – Try It Online").
### Score
This is code golf, so the shortest program in bytes wins. The [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
[Answer]
# JavaScript (ES7), ~~136~~ 132 bytes
Takes a single integer as input and returns a string.
```
s=>(V=g=(d,t=s,k=0)=>k>V?R:[...S=([1e3]+t).slice(-4)].some(p=c=>(p-(p=c))**2-1)?g(d,t=(t-~d)%2400,k+=t%100<60):(V=k,R=S))()&&g(2398)
```
[Try it online!](https://tio.run/##fc3BbsIwEATQe7/CF5AXErO7DgWsbvgHkLggDigJEU3AEbZ67K@nlKIeIrW3kZ5m5v34cQzF7dzF9OrLqj9JHyTXO6lFl0mUkDSCIHmT79YbtzfGbEXvqbKHaQQT2nNR6TSDgwn@UulOinu5S78DwGTCKcG6fgzpmH6WMOIMMWmmEkeE@PaK4O5fTbKRLYCG8bjWbFdL6At/Db6tTOtrfdJKEQKo2Uyxddn8ZaDE9keRHNuhcrb4W4nxuUzsCIe6wPnzlxzSQBmz5T9KzL/KVvnbI1D/BQ "JavaScript (Node.js) – Try It Online")
### How?
The only valid hour prefixes are `01`, `10`, `12`, `21` and `23`. It means that any invalid minute count starting with a digit greater than 5 will be rejected by the test on the absolute difference between two consecutive digits.
So there's no need to explicitly handle the wrapping of minutes modulo 60. Instead, we can just make sure that the distance `k` is not incremented on invalid minutes:
```
k += t % 100 < 60
```
---
# [JavaScript (Node.js)](https://nodejs.org), ~~148~~ 146 bytes
Takes a single integer as input and returns a string.
This version picks the answer from a hardcoded table.
```
t=>0x60553BCD48A3CE4F56D818FDC473FC726398E907D3A9n.toString(6).substr([22,85,9,423,462,x=98,x,9,9,413,461,9,x,x,9,9].findIndex(d=>(t-=d+2)<0)*4,4)
```
[Try it online!](https://tio.run/##fc1PT4NAEIfhu5@C465u6czsHxZSmlQoiWePxkMt0NA0uwZWw7dHtI0HEr398j7JzPnweRiOffceVs7XzdTmU8i3MBrQWj4WpbI7WexVpU1p0VZloRJZFQkZmdp9Ckkpd6mLg38OfedOzPB4@HgbQs9eiITVIhWKpFCGxJinVoxzmBN@J5zXeC2vcdu5@snVzcjqfMvCKq8fiG@A3yuh@HT0bvCXJr74E2tZFCFwHq3XEclM6buFIsmrAmYkl0oq@VuR4HYZKUNYagL69hczwIUSKPuPItGvkox8/zNw@gI "JavaScript (Node.js) – Try It Online")
### How?
Once converted to base-6, the integer `0x60553BCD48A3CE4F56D818FDC473FC726398E907D3A9n` is turned into the following string, which holds all possible valid answers:
```
"23450101012101231010101212101212123212342101212121232321232323432345"
```
The correct answer is selected according to the interval in which the input time falls:
```
answer | input interval
--------+----------------
"2345" | 00:00 - 00:23
"0101" | 00:24 - 01:10
"0121" | 01:11 - 01:21
"0123" | 01:22 - 05:46
"1010" | 05:47 - 10:10
"1012" | 10:11 - 11:10
"1210" | 11:11 - 12:10
"1212" | 12:11 - 12:21
"1232" | 12:22 - 12:32
"1234" | 12:33 - 16:47
"2101" | 16:48 - 21:10
"2121" | 21:11 - 21:21
"2123" | 21:22 - 22:21
"2321" | 22:22 - 23:21
"2323" | 23:22 - 23:32
"2343" | 23:33 - 23:43
"2345" | 23:44 - 23:59
```
The lengths of the intervals in minutes (minus 2) are stored in an array.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~136~~ ~~138~~ ~~133~~ ~~126~~ ~~125~~ ~~122~~ ~~151~~ ~~124~~ ~~108~~ ~~106~~ ~~103~~ 101 bytes
```
f=lambda h,m,i=0:(h,m)*all(j%11%9==1for j in(h,m/10-h%10,m))or f((h+(m+i)/60)%24,(m+i)%60,~i+2*(i<1))
```
[Try it online!](https://tio.run/##hZDNbuMgFIX3PMWVKguoScqPk85YdV@kqlRqE5nWdizDTKebefUUcFCTzczGuh/ncjjH86fvj5M8nQ7NoMfXTkPPRmYbXpMw0Fs9DOStEKL42TTicFzgDewUpTvBN30heFii4fhASF@SsbT0bs9pISuWoNhz9teW8pbYB0HpyY7zcfHgPh2KZoOdTPCLvHW@s1ON4AYWozvQ4I3z0GpnEHg7GgZ6ch9mgQZGPRPnl3BlsTNLLtvFzINuDcE1ZhjTrZsH6wnePGJKUSgFY7jY2d/jsSN28iRaUgaC8yCbP7Np/fXC@lpeibna3rTvKMRzv4a4fEi/CMG8hP3zMQP8hMuXFZpmNX4p8TM@cVFzAZtHSAMKX5lRrqgyKiR4LXjENCSUGSUSMqsyqTKr8qyqjGrFKmOFZI6Rhogyo1xRZVRIqqyqpKqsqrNaZaxW3GXcIZ4rnHFXV/vvghHvLwrKml822mc1ZY744yIzv8ZgKL8z/@ehfzl/AQ "Python 2 – Try It Online")
Input is hour,minute parameters result is (hour,minute) tuple
Using recursion
i moves through [0,-1,+2,-3,+4,...]
the sum of the initial terms therefore moves through [0,-1,1,-2,2,...]
(h,m) are offset by i minutes moving alternately through nearest above and below time not yet checked.
Check for result by considering h, m and h%10\*10+m/10, which is low hour digit and top minute digit.
To check two digit number n in form d (d+1) or (d+1) d, observe n%11 is either 1 or 10 in exactly these cases, and checking for 1 or 10 using %9==1. i.e. n%11%9==1
As this two digit test reduces modulo 11, h%10\*10+m/10 is equivalently m/10-h%10.
**Previous approach**:
```
def f(h,m,i=0):t=m+i;s='%02d'*2%((h+t/60)%24,t%60);return s*all(a+b in'4321012345'for a,b in zip(s,s[1:]))or f(h,m,-i+(i<1))
```
[Try it online!](https://tio.run/##hY/RbuMgEEXf@YqRVhFQkxQGJ7ty1/2RqlLZmMhobccC2qr78ynYQc2@7L6gOXOZuXfmj9ifJ7xcOnuCE@vFKFwreRPbsXIPoaUbiR29ww1jfRXvD5JvsBZxk4oHb@OrnyDcmWFgpvoFbqK1RiUV6npPT2cPRuQu/HEzCyI8qeaZ89RejbauYu6n4vzixvnsI4SPQPLU4CabxxLvQuzc1BD4Bt6aDgxEGyIcTbAEohutADOFd@uhhdEkl@jTiHezWLbsvJ0Hc7SMNlRQyndhHlxkdPtIOSfQCxjTYOfexnPH3BRZXskFKCk5yabH3h5/k@QdXoeYvi7J0@Ts0@9rWwB9otXLCm275nmp6DO9SNVIBdtHWAqSXiyIK@qCmijZKJlxKRbEgkgUFhUXFYuKV1UX1CvWBWuCJcZSZMSCuKIuqAnqoupF1UXVV7UuWK@4L7gnspxwxX1TH74OzPj95kBs5O1Fh6IumTP@uMks/8a0EL8y/8foX5s/AQ "Python 2 – Try It Online")
Input in integer output is 4 character string.
Formats number as string, taking pairs checks against string table, otherwise recurse with alternating offsets (i=0,1,-1,2,-2,...)
Originally:
Offsets n by [0,1,-1,2,-2,...], formats as four digit string, then taking pairs of characters checks they differ by one by looking up as substring in compressed string table.
+2 bytes Fixed by adding '43' to table.
-5 bytes Removed unnecessary +2400, which was to avoid mod of negative number -- Python's % works properly in that case.
-7 bytes string table improved, and by using / instead of // due to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum).
-1 byte reduce range of search.
-3 bytes [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum): remove unecessary [] in all() and compress expression i%2\*2-1 to i%-2|1.
+29 bytes code was broken, added correction term for wrapping minutes (n%100+i)/60\*40
-27 bytes [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum): rewritten using recursion
-16 bytes reworked using new approach
-2 bytes remove introduced variable which was false saving.
-3 bytes simplification for middle digits test.
-2 bytes [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum): using lambda instead of def
[Answer]
# [Python 2](https://docs.python.org/2/), 142 bytes
```
lambda*t:'%02d'*2%max(g(-720,*t))[1:]
g=lambda w,h,m,t=10:w/720*[0]or[(w*w,h,m)]*({h/t-h%t,h%t-m/t,m/t-m%t}<={1,-1})+g(w+1,(h+m/59)%24,-~m%60)
```
[Try it online!](https://tio.run/##JY89b4MwEIZ3/wovKLY5iu3mo0VlTNcu3VIGkjix1RiQOURQlP516jbDo/t4H5103YS2bfTsfNcGpP3Uk8hTbzCYwxB61zYX5x0yJYVYc0JO5dd8qf3@WAssFonUx4XQia@v7MyyjZYgkPOdKipyLh8eHcGCByyVLMY8KmInqzbs2Cj@E14JdrM5ZjZBiGQ@R4hkPsH7W3lTkKk7T89sTBUwm/p89coTvYTsxydryefRuouhn2EwBaEUw/RXKI2naUld0w3IeNyY68F0SLcf79sQ2vCQ9sHU37HrgmuQnpgF6vksQUmiQD8TDcsNURriuIEVif8tX4iOkf4F "Python 2 – Try It Online")
without the strict output:
# [Python 2](https://docs.python.org/2/), ~~160~~ ~~148~~ ~~144~~ ~~138~~ 133 bytes
-~~6~~ 11 bytes thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!
Input and output is `hours, minutes`.
```
lambda*t:max(g(-720,*t))[1:]
g=lambda w,h,m,t=10:w/720*[0]or[(w*w,h,m)]*({h/t-h%t,h%t-m/t,m/t-m%t}<={1,-1})+g(w+1,(h+m/59)%24,-~m%60)
```
[Try it online!](https://tio.run/##JY89b4MwEIZ3/wovSLZzFNsloUVlTNcu3dIMJHGwVQzIHCJRlP516jbDo/t4Xp10wxVt3@nF@aEPSMfrSCJPo8FgjlMYXd@1zjtkSgqx4YScq6@lrf3hVAssfX1hDUsLLUEg5ztV7klTPTSdwYIHrJQs5yxGxE7u@7Bjs/g3fC/YzWaY2gQhkvoMIZL6BO9v1U1Bqu581bB5pYDZlc/WrzzROaQ/PtlIvszWtYZ@hsmUhFIM179CaTxNK@q6YULG48ZcjmZAuv1434bQh0foEEz9HbshuA7pmVmgni8SlCQK9DPRkBdEaYhjAWsS/8tfiI5K/wI "Python 2 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 108 bytes
```
t=>(g=i=>(k=0,s=(new Date(t-i*6e4)+0).slice(16,21),h(1)+h(3)+h(4)-3?g(~i+(i<0)):s))(0,h=l=>(s[k]-s[k=l])**2)
```
[Try it online!](https://tio.run/##hc6xDoIwEAbg3adgvIODtKWCMVYX38IwEKxQacDYRjdfHcvkZnPJP335/7u3r9Z1T/Pw@TRf9XJTi1dH6JUJOSpGTsGk38m59Rp8btJKS8wYFs6aTgOvSHCkAThmA5RrSMzLUw8fk4E5MMS9QwRGg7Kh0V3GJg@hbINpKnDp5snNVhd27uH2W2K0XsKIhwbc/FecRBlXgmQdVVyE0biqKdlGlWAkd3EVvherWr4 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~159~~ 155 bytes
Heavily inspired by @Arnauld's JavaScript solution. Instead of converting the answer string from hex to base 6, I needed to convert it from ~~hex~~ *base 36* to base 10, since Python does not have built-in conversion to an arbitrary base.
*-4 bytes thanks to @ovs for the suggestion to convert from base 36*
```
x=input()
j=0
while x>23:x-=[80,4,418,457,93,93,4,4,408,456,4,93,93,4,4,9][j/4]+7;j+=4
print`int("2T9DHQE9BIABWTC7VO76PFJ2QND3LLSQY0ISQTMZCHP5",36)`[j:j+4]
```
[Try it online!](https://tio.run/##RU9hS8NADP1@v0Lmh7a0Yi6X3vUmFdymbDJ1ZUPRMljp7tiKbGNWrL@@XqcgSV7ee4GQHL7rzX6Hbblfm9TzvLZJt7vDZ@0HrEqBfW227@asuUbRby7SPIGIIuJJRLGKtOiSuoDOkY79e3qZV5e0DNVVFabEDsftrl658nu40KNxdqsHk5vBy2Konp@UnN3dY/Y4EtPpPHuFyTxbPLwNx7O4FwkZrPKqX4W0bN197Py0yf@ojz40a1OUoAtbCuCykMqaRJcSJUcCa4sClFYojNQWk7iI19agJat1EPx9xvumMaXffR@0HBhHwZCU6@CEgpghUMKQIzKu3Yhxzn8lIvIOHBMnEE4KIgexZvAD "Python 2 – Try It Online")
Takes input as an integer representing the time (eg. `2101` for 21:01, or `123` for 01:23). Output is a string in the form `hhmm` with no delimiter.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 29 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁽¬ẊDŻ€Œpḣ⁽¢ẒðIAP€ẹ1ạÞiḢị⁸
```
A monadic Link accepting a list of four integers which yields a list of four integers.
**[Try it online!](https://tio.run/##AVEArv9qZWxsef//4oG9wqzhuopExbvigqzFknDhuKPigb3CouG6ksOwSUFQ4oKs4bq5MTstMTThuqHDnmnhuKLhu4vigbj///9bMSwgNiwgNCwgOF0 "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8//9R495Dax7u6nI5uvtR05qjkwoe7lgMElv0cNekwxs8HQOAog937TS01jU0ebhr4eF5mQ93LHq4u/tR447/R/ccbgdKZwHxo4Y5Crp2Co8a5kb@/x8dbaCjAESGQDKWSycawjTSUTCG8oBMEx0FcxAPImEAVQnkmYN5piAeRAKo0gLKgyg2iuWKBQA "Jelly – Try It Online").
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 59 bytes
```
≔⪪”)⊟ς∧Q@ςE⁶¿ê40ofυ_Y±F⌊M↨ ”⁴υ≔↔⁻↨⁶⁰I⪪S²Eυ↨⁶⁰I⪪ι²θ∧⊟υ§υ⌕θ⌊θ
```
[Try it online!](https://tio.run/##bU1LCoMwFNz3FMHVC1jQJBaKK1souBAET5Cq2IDGT5LS26eJTbsqjxl4w3zaB9/amY/WFkqJQUKzjEJDlKT@iAdNvw8JTKgH@71eoIEp88gIS9IoRgzHyOD8EMqLu5pHo3uohDQKLlz1cEpidOVKh@VSLkY3ehNyABcmGDuu@AImRv/84uPZbatbql1SQyE7qGcXcmqhS9n1L19wE05fXZ@QYjITrHswt5bQ7GyPz/EN "Charcoal – Try It Online") Link is to verbose version of code. I/O is as a 4-digit string without colon. Explanation:
```
≔⪪”)⊟ς∧Q@ςE⁶¿ê40ofυ_Y±F⌊M↨ ”⁴υ
```
Split a compressed string of all the possible times into substrings of 4 digits. (I tried computing the string but unfortunately that cost at least 6 more bytes.) Additionally include the value `2401` which will map to `0101` for the next day.
```
≔↔⁻↨⁶⁰I⪪S²Eυ↨⁶⁰I⪪ι²θ
```
Convert the input and the substrings into seconds since midnight and take the absolute difference.
```
∧⊟υ§υ⌕θ⌊θ
```
Print the substring with the least absolute difference, but remove the `2401` entry first, which causes the indexing to wrap around to `0101`.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 155 bytes
```
(s,o=Math.abs,m=k=>Math.min(o(s-k),o(s+2400-k)))=>[101,121,123,1010,1012,1210,1212,1232,1234,2101,2121,2123,2321,2323,2343,2345].sort((a,b)=>m(a)-m(b))[0]
```
[Try it online!](https://tio.run/##fY7dCsIwDEbvfYremWI3kqzDMahv4BOIF52Iv7Oyjr3@bIYiOPAiJ1/DocnVDz4eusuzz4Zq7NwI0QS39f059000rbu5zfRqLw8IELObNqmt2CKmrLXb7AjJEEsVJmUUsExQIKmYYA2LyuKyyGlOAkl2QrnPY@h6AG@a9HULXmctNFrvcL8YD@ERw/2Y38MJOlCKUBu1VE5xUdtyqRc/QtrxFpBqLuYC2/VfgRg/K4hrwrmwxvJzA9VIM4HRVv8FYv4KcsP4Ag "JavaScript (V8) – Try It Online")
[Answer]
# APL+WIN, 106 bytes
Prompts for time as a vector of integers hh mm:
```
¯2↑¨'0',¨⍕¨,60 60⊤((|m)=⌊/|m←(¯15,1↓n)-60 60⊥⎕)/n←60 60⊥⍉17 2⍴¯33+⎕av⍳'7M!!!7!5***,,*,,,@,B5!555775777B7M'
```
Stores 16 possible times as characters in APL+WIN character set (extended ASCII) adjusted by 33 to make printable. Could be removed to save 4 bytes. Converts to seconds, gets closest match and outputs nested character vector of time. Unfortunately I cannot put this up on TIO because my usual route via Dyalog Classic does not work as Dyalog character set appears to be in a different order to APL+WIN. Anyone care to translate?
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
60©Ž5—Ÿ®δвT‰JʒS¥ÄP}D®δβD14(ªI®β.xkè
```
Both input and output is a pair of `[hours, minutes]`.
[Try it online](https://tio.run/##yy9OTMpM/f/fzODQyqN7TR81TDm649C6c1subAp51LDB69Sk4ENLD7cE1LqABM9tcjE00Ti0yhPI2aRXkX14xf//0QYGOkbGsQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/X8zg0Mrj@41fdQw5eiOQ@vObbmwKeRRwwavU5OCDy093BJQ6wISPLfJxdBE49CqSiBnk15F9uEV/3X@R0crGRgo6YCIWB0o2xCJbWQMYRsisU2BbBMzJLY5mG1ohDDH0AxJHMy2ALONDJDYYDONkNgmELYxkG1qqRQbCwA).
**Explanation:**
```
60 # Push 60
© # Store it in variable `®` (without popping)
Ž5— # Push compressed integer 1425
Ÿ # Pop both, and push a list in the range [60,1425]
®δв # Convert each integer to a base-60 list/pair
T‰ # Add leading 0s by taking the divmod-10 on each inner integer,
J # and then joining the inner pairs together
ʒ # Filter this list by:
S # Convert it to a flattened list of digits
¥Ä # Get the absolute difference of each pair of digits
P # And check if all of them are exactly 1
}D # After the filter: duplicate the list of remaining pairs
®δβ # Convert each pair from a base-60 pair back to a base-10 integer
D # Duplicate that list of integers
14(ª # Append a trailing -14
I # Push the input-pair
®β # Convert it from a base-60 pair also to a base-10 integer
.x # Get the integer in the list closest to this value
k # Get the index of this value in the duplicated list
# (which will result in -1 for the trailing -14)
è # And use that to index into the duplicated list of pairs
# (where the -1 will index into the last pair, which is the [23,45])
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integer*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž5—` is `1425`.
] |
[Question]
[
**Challenge**
Given a sequence of non-negative integers, create a function that output a descendant pyramid where the children are the sum of both parent numbers.
The result is outputted as an string using tab `\t`.
*Note: trailing tabs on each line are not required*
```
1\t\t2\t\t3\n\t3\t\t5\t\n\t\t8\t\t results in
1 2 3
3 5
8
```
Optionally result can be outputted as an array using an empty position as space.
```
[[1,,2,,3],
[,3,,5,],
[,,8,,]]
```
**Example:**
Given `4,5,7,3,4,2` Output:
```
4 5 7 3 4 2
9 12 10 7 6
21 22 17 13
43 39 30
82 69
151
```
**Rules**
* Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply
* Input can be a string using any separator or an array
* Leading/trailing newlines and tabs are permitted (but not required as long as the output is an inverted pyramid)
**Test Cases**
```
Input: 1,3,5
1 3 5
4 8
12
Input: 9,8,7,6,5
9 8 7 6 5
17 15 13 11
32 28 24
60 52
112
Input: 5,5,2,5
[[5,,5,,2,,5],
[,10,,7,,7,],
[,,17,,14,,],
[,,,31,,,]]
Input: 3,3,3
[[3,,3,,3],
[,6,,6,],
[,,12,,]]
```
Winning criteria is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
---
***Note:*** This challenge is very close to [Generate Pascal's triangle](https://codegolf.stackexchange.com/questions/3815/generate-pascals-triangle). The difference is the custom starting sequence (pascal goes from 1 and in ascendant mode, this from an input and in descendant mode).
**[Sandbox post](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/16586#16586)**
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
14 -> 13 assumes trailing spaces-only entry is allowed in the list format output; if not I shall revert to the 14 ([asked](https://codegolf.stackexchange.com/questions/167797/draw-a-descendant-pyramid-addition#comment405522_167797))
```
+ƝƬK€z⁶Zṙ"JC$
```
A monadic link. Output is a list of lists using space characters as the spaces (includes a single trailing spaces-only entry).
**[Try it online!](https://tio.run/##ASsA1P9qZWxsef//K8adxqxL4oKseuKBtlrhuZkiSkMk/8OHxZLhuZj//zEsMyw1 "Jelly – Try It Online")** (includes a footer to show the list structure since running the monadic link as a full program will print smashed output implicitly.)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~31~~ 28 [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")
Tacit prefix function. Uses a single space as empty slot marker. Returns list of lists of numbers/spaces.
```
⍳∘≢{∊(⍺⍴''),,∘' '¨2+/⍣⍺⊢⍵}¨⊂
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/9fklpc8qhtQvWjvqlACkh6Bfv7KaQpPOrdqvCou0UBKt42ESJWywUUyMwHChn8f9S7@VHHjEedi6ofdXRpPOrd9ah3i7q6po4OUFRdQf3QCiNt/Ue9i0ESXYtAeg@teNTV9D8NZF5vH9AcT/9HXc2H1hsDTQfygoOcgWSIh2cw2FEKhjrGOqZcYKaljoWOuY4ZjGuqY6pjBOMYA5UZAwA "APL (Dyalog Unicode) – Try It Online")
`⍳∘≢{`…`}¨⊂` apply the below function for each of
`⍳` the **ɩ**ndices `∘` of `≢` the tally with
`⊂` the entire argument:
`⊢⍵` yield the right argument (the original input)
`2+/⍣⍺` apply pairwise sum as many times as indicated by the left argument
`,∘' '¨` append a space to each number
`(`…`),` append that to the following:
`⍺⍴''` left-argument elements of the empty string (padded with spaces)
`∊` **ϵ**nlist (flatten)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 14 bytes
-1 bytes thanks to Kevin Cruijssen
```
vD„ ý' N×ì,ü+
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/zOVRwzxOzsN71Tn9Dk8/vEbn8B7t//@jTXRMdcx1jHVMdIxiAQ "05AB1E – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 74 bytes
```
ArrayPad[Riffle[#,],k++,]&/@NestList[k=0;BlockMap[Tr,#,2,1]&,#,Tr[1^#]-1]&
```
[Try it online!](https://tio.run/##DcfdCoIwFADge59iMJDCE2VQliKsrvuR8m4sOCwPDf9i7iKJnn159fG16F5Vi85o9FcieR87h5801X2rsoDymT9Yi2OBT3kzRE0lOSioowhUuBSXanAnMzhZ56vs2PS6PuNblhY4rCFW4WRpZfzgajHNz7OgsKZzgsR3D2wHLAG2Bbb5@T8 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 22 bytes
```
zoΣ~+R" "oJ" "msNU¡Ẋ+
```
[Try it online!](https://tio.run/##yygtzv7/vyr/3OI67SAlTqV8LyVOTqXcYr/QQwsf7urS/v//f7SljoWOuY6ZjmksAA "Husk – Try It Online")
### Explanation
```
z(Σ~+R" "(J" "ms))NU¡Ẋ+ -- example input: [1,2,3]
¡ -- infinitely do and collect in list
Ẋ+ -- | sum adjacent
-- : [[1,2,3],[3,5],[8],[],[],...
U -- keep up until first repetition: [[1,2,3],[3,5],[8],[]]
z( )N -- zip with natural numbers under (example on 1 [1,2,3])
~+ ( ) -- | join arguments modified by
R" " -- | | replicate tab: " "
ms -- | | show each: ["1","2","3"]
J" " -- | | join with 2 tabs: ["1"," ","2"," ","3"]
-- | : [" ","1"," ","2"," ","3"]
Σ -- | concatenate: " 1 2 3"
-- : [" 1 2 3"," 3 5"," 8"]
```
[Answer]
# JavaScript (ES6), 73 bytes
Weird source code ... Anyway, that's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")!
Includes leading and trailing whitespace.
```
f=(a,p=`
`)=>p+a.join` `+(1/(y=a.shift())?f(a.map(x=>y+(y=x)),p+` `):'')
```
[Try it online!](https://tio.run/##DclRCsIwDADQ73qRJTRW1IkgZB5EhIS5asdsix2ynb76ft@oXy39J@R5G9NjqNUzKGWWjSB32aobU4hijFjY72BldeUV/AyIVw/q3pph4W61/1oQKVsxgpemwdqnWNI0uCk9wcOtpROd6UgtHe6I9Qc "JavaScript (Node.js) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, 62 bytes
```
$,="\t\t";do{say"\t"x$i++,@F;map$_+=$F[++$q[@F]],@F}while$#F--
```
[Try it online!](https://tio.run/##K0gtyjH9/19Fx1YppiSmRMk6Jb@6OLESyFGqUMnU1tZxcLPOTSxQide2VXGL1tZWKYx2cIuNBQrXlmdk5qSqKLvp6v7/b6JgqmCuYKxgomD0L7@gJDM/r/i/rq@pnoGhwX/dRAA "Perl 5 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~101~~ ~~93~~ 80 bytes
Saved 7 bytes (`map(str,x)` instead of `for in` and init y as `''`) and got rid of the trailing newlines (`x and[` instead of `print(`), thanks to *Jo King*.
Saved 13 bytes (`[*map(sum,zip(x,x[1:]))]` instead of `[x[j]+x[j+1]for j in range(len(x)-1)]`) thanks to *ovs*.
```
f=lambda x,y='':x and[y+' '.join(map(str,x))]+f([*map(sum,zip(x,x[1:]))],y+' ')
```
[Try it online!](https://tio.run/##HYtLCoMwFEXH7sLZS@pF8FMKgisJDlJEmtLEoBFe3HxMnZ6Pj@Gzui6lZfxp@551yYgj0cCldrOKFRUF1d/VOGG1F3vYwFJO1SLU4waHxWm8YLBqhikr/B@S6dZ@My4gxz2eeKFDjzZHSBc "Python 3 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 35 bytes
```
+¶<`\d+ *(?=(\d+)?)
$#1*$.(*_$1*)
```
[Try it online!](https://tio.run/##K0otycxLNPz/X/vQNpuEmBRtTi0Ne1sNIEPTXpOLU0XZUEtFT0MrXsVQS5Pz/39DTk4jTk5jAA "Retina – Try It Online") Explanation:
```
+
```
Repeat until the buffer stops changing,
```
¶<`
```
Print the contents of the buffer before the substitution, with a trailing newline, and
```
\d+ *(?=(\d+)?)
$#1*$.(*_$1*)
```
Substitute a single number with a pair of tabs, but a number followed by another number with a tab, the sum, and another tab.
[Answer]
# [Red](http://www.red-lang.org), 151 bytes
```
func[b][m: length? b repeat n m[loop n - 1[prin"^-"]print replace/all
form b" ""^-^-"c: copy[]repeat i -1 + length? b[append c b/(i) + b/(i + 1)]b: c]]
```
[Try it online!](https://tio.run/##nU7LCsIwELz3K4aeLFJKLPXRi//gdVkhSRMtpEko9SDit9dUBK8ie5iBmdmZ0XTzyXTEmW1ne/OaFNPQwhl/ma5HKIwmGjnBYyAXQkykhKA49j4/lzkvZFpMTmpTSecyG8YBKkee9OTQLXSId@LPox6lwPpbQDJG4ztoqGrVF0laMIEoWKUs82xJoEbD2bvsUeKne2aWDthjh@1f2QYNNn8l67S25vkF "Red – Try It Online")
## More readable:
```
f: func [ b ] [
m: length? b
repeat n m [
loop n - 1 [ prin tab ]
print replace/all form b " " rejoin [ tab tab ]
c: copy []
repeat i (length? b) - 1 [
append c b/(i) + b/(i + 1)
]
b: c
]
]
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~50~~ 48 bytes
```
{$_,{say " "x$++~.join(" ");$_[1..*]Z+@$_}...0}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1olXqe6OLFSQYlTqUJFW7tOLys/M09DiZNTSdNaJT7aUE9PKzZK20ElvlZPT8@g9n@aRrSJjqmOuY6xjomOUazmfwA "Perl 6 – Try It Online")
Anonymous code block that takes a list of integers and prints the inverted pyramid.
[Answer]
# [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 163 bytes
```
b=>{var s="";var c=b.Length;for(int i=0;i<c;i++){for(int z=0;z<i;z++)s+="\t";for(int x=0;x<c-i;x++){s+=b[x]+"\t\t";b[x]=x==c-i-1?0:b[x]+b[x+1];}s+="\n";}return s;}
```
[Try it online!](https://tio.run/##PY9BS8QwEIXv/RVDTy1Ny66uCKbZPQieFAQPHmoPaYzdgW0CmexaW/rba1pxGRiG99438BTlitSsTpIIXp1tney6aIwi8tKjgovFT3iRaBLyDk1b1SBdS@kSid5@yOuueDobVaLxVc3gL7UHCWJuxH68SAck4pgvhxJN8axN64/8y7okIIBiw7FUHLMsHf/FIYhDiXwIImUi/vDxFeiD15cqR94vSLCbqq@zkFlSyy16IYKfbw@bh9ULK9vWfFpfmZhPTvuzM0B8mvm1xaM1ZE@6eHfodSITo79hLQXjjt2xe3bLduxmStOATGHmXw "C# (Visual C# Compiler) – Try It Online")
Readable:
```
b => {
var s = "";
var c = b.Length;
for (int i = 0; i < c; i++)
{
for (int z = 0; z < i; z++)
s += "\t";
for (int x = 0; x < c - i; x++)
{
s += b[x] + "\t\t";
b[x] = x == c - i - 1 ? 0 : b[x] + b[x + 1];
}
s += "\n";
}
return s;
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/) `-Rx`, ~~20~~ 18 bytes
The second line includes a trailing tab.
```
Nc¡=ä+
Ëq' ² iEç'
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=TmOhPeQrCstxJwmyIGlF5ycJ&input=WzQsNSw3LDMsNCwyXQotUng=)
---
## Explanation
```
:Implicit input of array U
N :The array of inputs (NOT the input array)
c :Concatenate
¡ : Map U
ä+ : Consecutive sums of U
= : Reassign to U for next iteration
\n :Reassign the resulting 2D-array to U
Ë :Map each array at index E
q : Join with
'\t : Tab
² : Repeated twice
i : Prepend
'\t : Tab
ç : Repeated
E : E times
:Implicitly join with newlines, trim (not strictly necessary) and output.
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~112~~ 109 bytes
* -3 from @ceilingcat
```
j,k;f(*i,c){for(j=c;j;j-=puts("")){for(k=c-j;k--;)putchar(9);for(;++k<j;i[k]+=i[k+1])printf("%d\t\t",i[k]);}}
```
[Try it online!](https://tio.run/##VY5NboMwEEb3nMIiqmRjXIlFm0aDcxHCwjWFjKEQgUMWEVev6ymrbqzxe9/8WGUHM3YhuLyHlmeYW/Fsp5k7bcGBU/p29wtPU7HjXlvloFcKRBT2amZ@EkAGpOxLB1j1tdTxlUUtbjOOvuXpS3PxF5/mJAVsWzjgaId788XKxTc4vV7PyT804CexJLazb4Mjp8LMnc1pJcuyWK@CPRPGsOUkzsX@jSBGVzMsFeEa/hgdSBx1AViSAJRS7DlURa2Nn5AGrRXGE5O9i5PPKa4KQZO2ZAvhFD7CMbyHtx/bDqZbgnr8Ag "C (clang) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 18 bytes
```
2lṠ)↔ðdvj:ẏ$꘍⁋ð9CV
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIybOG5oCnihpTDsGR2ajrhuo8k6piN4oGLw7A5Q1YiLCIiLCIxLCAyLCAzLCA0Il0=)
I *think* this works? Output format is annoying.
```
)↔ # Repeat until no change, collecting values
Ṡ # Sums of
2l # Consecutive pairs
vj # Join each by...
ðd # Double spaces
$꘍ # Pad left with spaces by
:ẏ # range(0, len(list)
⁋ # Join by newlines
V # Replace
ð # Spaces
9C # With tabs
```
[Answer]
# Python 3, ~~79~~ ~~75~~ 70 bytes
Has leading tabs. Prints the required output then prints trailing tabs and newlines forever.
```
def f(x,y='\n'):print(y,*x,sep=' ');f([*map(sum,zip(x,x[1:]))],y+' ')
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNo0Kn0lY9Jk9d06qgKDOvRKNSR6tCpzi1wFadk1Nd0zpNI1orN7FAo7g0V6cqswCovCLa0CpWUzNWp1JbHajif4VttImOqY65jrGOiY5RLBfQSM3/AA "Python 3 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 67 bytes
A straightforward recursive solution.
```
F=->a,n=0{puts ?\t*n+a*" "
a[0]&&F[a.each_cons(2).map(&:sum),n+1]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWN53dbHXtEnXybA2qC0pLihXsY0q08rQTtZQ4OZW4EqMNYtXU3KIT9VITkzPik_PzijWMNPVyEws01KyKS3M1dfK0DWNrIUZtcIuONtEx1THXMdYx0TGKjYUIw2wCAA)
] |
[Question]
[
### Introduction
Note: this is not some kind of method to encourage cheating. As [Cᴏɴᴏʀ O'Bʀɪᴇɴ](https://codegolf.stackexchange.com/questions/69770/cheating-a-multiple-choice-test#comment170320_69770) already said, studying is the best solution for passing a test :3.
Consider the following answers to the multiple choice test:
```
ABCBCAAB
```
Here is a table which indicates whether the answers match:
```
A B C B C A A B
A 1 0 0 0 0 1 1 0
B 0 1 0 1 0 0 0 1
C 0 0 1 0 1 0 0 0
```
This gives us the following numbers:
```
10000110, 01010001, 00101000
```
The challenge is to print these binary numbers. But it is **important** to see which letters are used in the multiple choice test. For example:
```
ABCDCDBCDABC
```
This **highest letter** is `D`, which is the *4th letter in the alphabet*. Therefore, we need to output **4 different** binary numbers. Namely:
```
100000000100, 010000100010, 001010010001, 000101001000
```
Note that you have to look at the *highest letter*. Consider the following example:
```
AACCACAC
```
Although the `B` is not used, we need to output the binary result for `B`. That means, the answer would be:
```
11001010, 00000000, 00110101
```
---
### Task
Given the answers to a multiple choice test, output the binary numbers. **You may assume that the input will be non-empty and only containing the letters `[A-Z]`**
. Instead of ones and zeroes, you may also use true and false.
---
### Test cases:
```
Input: ABBBABABA
Output: 100010101, 011101010
Input: AAAAAAAAA
Output: 111111111
Input: AFGHEEHFD
Output: 100000000 000000000 000000000 000000001 000011000 010000010 001000000 000100100
Input: Z
Output: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
Input: ABCDCDBCDABC
Output: 100000000100, 010000100010, 001010010001, 000101001000
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins!
[Answer]
# Python 3, 71
Saved 22 bytes thanks to Ogaday.
Saved 3 bytes thanks to DSM.
Saved a bunch of bytes thanks to an array of bools being valid.
```
*k,=map(ord,input())
x=65
while x<=max(k):print([v==x for v in k]);x+=1
```
Takes uppercase command line input.
[Answer]
## Pyth, 12 bytes
```
mqLdzfsgRTzG
```
Outputs as a nested array of booleans.
```
Implicit: z=input
m Map lambda d:
qLdz map equal-to-d over z
f over all letters T in the
G lowercase alphabet for which
s At least one char in z
gRTz >= T.
```
Try it [here](http://pyth.herokuapp.com/?code=mqLdzfsgRTzG&input=afgheehfd&debug=0).
[Answer]
## PowerShell, ~~95~~ ~~94~~ 73 bytes
```
param([char[]]$a)0..(($a|sort)[-1]-65)|%{$d=$_;-join($a|%{+!($_-$d-65)})}
```
Takes input as an uppercase string, but immediately casts it `[char[]]`. We then loop from `0..` to the maximal value of `$a` taken alphabetically (hence the `-65` to convert from ASCII). For example, with `ADCEB`, this can be thought of as looping from `A` to `E`.
Each iteration, we set a helper variable `$d` equal to the current alphabetical (not ASCII) value. We then loop through all of `$a`, each time putting either `0` or `1` on the pipeline, based on whether `$_-$d-65` is truthy or falsey (i.e., whether we're in the right "slot"). This works because any non-zero value in PowerShell is truthy, meaning if our current letter `$_` doesn't "equal" what slot we're in `$d`, then the `!` of that is `$false`, or `0`.
Each of those arrays of `0`s and `1`s is then `-join`ed together and re-put on the pipeline. When the outer loop ends, we have an array of strings, which will print one string per line.
### Examples
```
PS C:\Tools\Scripts\golfing> .\preparing-a-multiple-choice-test.ps1 ABCDEFGH
10000000
01000000
00100000
00010000
00001000
00000100
00000010
00000001
PS C:\Tools\Scripts\golfing> .\preparing-a-multiple-choice-test.ps1 AFGHEEHFD
100000000
000000000
000000000
000000001
000011000
010000010
001000000
000100100
```
Edit 1 -- saved a byte by using Boolean-not instead of -eq
Edit 2 -- saved another 21 bytes by eliminating the extra array $b
[Answer]
# LabVIEW, ~~30~~ ~~22~~ 20 [LabVIEW Primitives](https://codegolf.meta.stackexchange.com/a/7589/39490)
Goes through from a-z until the sum of all bools is equal to the input lenght. then Transforms the bools to numbers.
Now directly takes the max instead of checking the bool sum.
Since 2D bools are viable now im saving 2 Primitives by outputting the green wire in front of `?1:0` could redo it but im too lazy...
[](https://i.stack.imgur.com/XI8L0.gif)
[](https://i.stack.imgur.com/BCUTw.gif)
[](https://i.stack.imgur.com/IkhVr.jpg)
[Answer]
# Cjam, 25 bytes
```
l{'A-i}%_:e>),\f{f=", "}
```
Sigh,
## Explanation
```
l{'A-i}%_:e>),\f{f=", "}
l e# get the input
{'A-i}% e# get the normalized array
_:e> e# get the maximum value
), e# create the array from 1..N
\f{ } e# map over the created array
f= e# 1 if match, 0 if not
", " e# add separator
```
[Answer]
## Haskell, ~~46~~ 34 bytes
```
g x=(<$>x).(==)<$>['A'..maximum x]
```
Usage example: `g "ACDC"`-> `[[True,False,False,False],[False,False,False,False],[False,True,False,True],[False,False,True,False]]`.
How it works:
```
<$>['A'..maximum x] -- for every letter from A to the highest letter in x
<$>x -- loop over x and
== -- compare the letter with the current element in x
-- which results in a boolean
```
[Answer]
## Pyth, ~~20~~ ~~19~~ ~~17~~ ~~15~~ 14 bytes
```
VhxGeSzmq@GNdz
```
Explanation:
```
- autoassign z = input()
V - For N in range(V)
hxGeSz
eSz - max(z)
xG - lowercase_alphabet.index(^)
h - +1
mq@GNdz
m z - [V for d in z]
@GN - lowercase_alphabet[N]
q d - is_equal(^, ^^)
- print "".join(^)
```
Outputs a 2D array of bools
[Try it here](http://pyth.herokuapp.com/?code=VhxGeSzmq%40GNdz&input=afgheehfd&debug=0)
[Answer]
## ES6, 92 bytes
```
s=>[..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"].map(c=>[...s].map(m=>m==c&&!!(l=n),n++),n=0).slice(0,l)
```
Returns an array of arrays of falses and trues. If you prefer an array of strings of zeros and ones, then for 97 bytes:
```
s=>[..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"].map(c=>s.replace(/./g,m=>m==c?(l=n,1):0,n++),n=0).slice(0,l)
```
[Answer]
# Octave, 19 bytes
```
@(s)s==[65:max(s)]'
```
Uses Octave's automatic broadcasting over the range `A` to the max element in the input to produce 2d boolean array of matching elements.
Example:
```
Key = ABCDCDBCDABC
ans =
1 0 0 0 0 0 0 0 0 1 0 0
0 1 0 0 0 0 1 0 0 0 1 0
0 0 1 0 1 0 0 1 0 0 0 1
0 0 0 1 0 1 0 0 1 0 0 0
```
Try it here on [ideone](http://ideone.com/1mVbp6).
[Answer]
# Lua, ~~208~~ 189 Bytes
That was tricky in lua, as usual, we have to do everything from scratch, and it takes a lot of place !
This program takes a string as argument, and print out the result :).
**Edit: @Adnan told me we're now allowed to return a matrix of booleans, so here's a new version! It is now a function that takes a string of capitalised character and return the matrix :).**
```
function f(x)a={}b={}for i=1,#x do a[i]=x:sub(i,i)end table.sort(a)for i=1,a[#a]:byte()-64 do b[i]={}end x:gsub(".",function(c)for i=1,#b do z=b[i]z[#z+1]=i+64==c:byte()end end)return b end
```
### Old 208 Byte version
This is the one that works with argument and print results.
```
a={}b={}x=arg[1]for i=1,#x do a[i]=x:sub(i,i)end table.sort(a)for i=1,a[#a]:byte()-64 do b[i]=""end x:gsub(".",function(c)for i=1,#b do b[i]=b[i]..(i+64==c:byte()and"1"or"0")end end)print(table.concat(b,","))
```
### Ungolfed and explanations
```
function f(x)
a={} -- We need 2 arrays, and while b=a would have been shorter
b={} -- arrays in lua are passed by pointer, so it wouldn't have worked
for i=1,#x -- iterate over the inpute to transform the string
do -- into an array
a[i]=x:sub(i,i) -- with each cells containing a characyer
end
table.sort(a) -- sort the array/string
for i=1, -- iterate n times were n is the place in the alphabet
a[#a]:byte()-64 -- of the last element of the (sorted) array a
do
b[i]={} -- initialise cells in b up to n with empty arrays
end -- a cell's index is the position of a letter in the alphabet
x:gsub(".",function(c) -- for each character in the input
for i=1,#b -- iterate over each cells in b
do
z=b[i] -- define z pointing on the array b[i]
z[#z+1]= -- insert into b[i] the result of the
i+64==c:byte() -- comparison of the current char, and the answer
end
end)
return b
end
```
Trying to print an array in Lua would result in printing its address and concatenating bools is impossible. So here's a function that will help you if you want to test this submission
```
function f(x)a={}b={}for i=1,#x do a[i]=x:sub(i,i)end table.sort(a)for i=1,a[#a]:byte()-64 do b[i]={}end x:gsub(".",function(c)for i=1,#b do z=b[i]z[#z+1]=i+64==c:byte()end end)return b end
function printBooleanMatrix(m)
s="{"
for i=1,#m
do
s=s.."{"
for j=1,#m[i]
do
s=s..(m[i][j]and"1"or"0")..(j==#m[i]and""or",")
end
s=s.."}"..(i==#m and""or",\n")
end
print(s.."}")
end
printBooleanMatrix(f("ABBCCDDC"))
```
[Answer]
# Perl, 84 bytes
```
$\="\n";@i=split//,<>;pop@i;for$c('a'..(reverse sort@i)[0]){print map{/$c/?1:0}@i;}
```
Oh dear, I seem to have broken the highlighter.
Ungolfed version:
```
# output formatting
$\ = "\n";
# get input chars as array
@i = split //, <>;
# lose the newline
pop @i;
# iterate over characters up to the max
for $c ('a'..(reverse sort @i)[0]) {
# print 1 for each match, 0 otherwise
print map { /$c/ ? 1 : 0 } @i;
}
```
[Answer]
# PHP, ~~106~~ ~~92~~ ~~90~~ 87 bytes
Uses Windows-1252 encoding.
```
for($x=A;$x++<=max($z=str_split($argv[1]));print~Ó)for(;$c=$z[+$$x++];)echo+(++$c==$x);
```
Run like this (`-d` added for aesthetics only):
```
php -d error_reporting=30709 -r 'for($x=A;$x++<=max($z=str_split($argv[1]));print~Ó)for(;$c=$z[+$$x++];)echo+(++$c==$x); echo"\n";' ABCDDHFHUYFSJGK
```
* Saved 14 bytes by nesting the loops the other way around
* Saved 2 bytes by using variable variables to prevent `$i=0`
* Saved a byte by inverting string and dropping string delimiters
* Saved a byte by moving the echo (changed to a print to fit) inside the first for loop and dropping curly braces
* Saved a byte by incrementing `$x` somewhere else, and incrementing `$c` to compensate
[Answer]
# [Ruby](https://www.ruby-lang.org/), 53 bytes
```
->s{(?A..s.chars.max).map{|c|s.gsub(/./){c==$&?1:0}}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3TXXtiqs17B319Ir1kjMSi4r1chMrNIFEQXVNck2xXnpxaZKGvp6-ZnWyra2Kmr2hlUFtbS1E8-aC0pJiBbdoJUc3dw9XVw83F6VYiMyCBRAaAA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
;m!aB
rÔò@®¥X
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O20hYUIKctTyQK6lWA&input=WyJBIiwiRiIsIkciLCJIIiwiRSIsIkUiLCJIIiwiRiIsIkQiXS1S)
Input as an array of uppercase letters
```
;m!aB
; # B = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
m # For each character:
!a # Find its index in
B # B
# Store as U
rÔò@®¥X
rÔ # Find the maximum value in U
ò@ # For each value X in the range [0...maximum]:
® # For each value Z in U:
¥X # True when Z == X
```
Alternate version in one line is [2 bytes](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O20hYUIgo1py1PKlWMN5&input=WyJBIiwiRiIsIkciLCJIIiwiRSIsIkUiLCJIIiwiRiIsIkQiXS1S) longer, unless it can output with rows and columns transposed.
Taking input as a string in either case requires 1 additional byte (`¬` before the `m`)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 7 bytes
```
øA:Gɾv=
```
[Try it Online! (test suite)](https://vyxal.pythonanywhere.com/#WyJBciIsIiIsIsO4QTpHyb52PSIsIiIsIlsnQScsJ0InLCdCJywnQicsJ0EnLCdCJywnQScsJ0InLCdBJ11cblsnQScsJ0EnLCdBJywnQScsJ0EnLCdBJywnQScsJ0EnLCdBJ11cblsnQScsJ0YnLCdHJywnSCcsJ0UnLCdFJywnSCcsJ0YnLCdEJ11cblsnWiddXG5bJ0EnLCdCJywnQycsJ0QnLCdDJywnRCcsJ0InLCdDJywnRCcsJ0EnLCdCJywnQyddIl0=) Input and output as a list of characters of `[A-Z]` and list of booleans respectively.
```
øA:Gɾv= # whole program
øA # convert each char to its alphabetical index (1-indexing)
: # duplicate
G # maximum
ɾ # convert into a range from 1 to inclusive
v= # for each num in the range, check if each converted chars == num
# (doubly vectorises)
# (the r flag swaps the arguments, giving the resulting command)
# implicitly output
```
[Answer]
# [Factor](https://factorcode.org), 52 bytes
```
[ 65 over supremum [a..b] swap [ = ] cartesian-map ]
```
[](https://i.stack.imgur.com/UH0m4.gif)
[Answer]
## C#, 68 bytes
```
c=>Enumerable.Range(65,c.Max()-64).Select(x=>c.Select(y=>x==y?1:0));
```
[Run in C# Pad](http://csharppad.com/gist/6f17d750299a8a091adb90cf836a4855)
This anonymous function takes a `char[]` as input and outputs an `IEnumerable<IEnumerable<int>>`, with only 0's and 1's.
[Answer]
# k, 15 bytes
```
{x=/:65_!|/1+x}
```
[Try it online!](https://tio.run/##y9bNz/7/v7rCVt/KzDResUbfULuiFp2vbmClpJ@SWqZfXJKSmaf039HR2dkRCLkcnZycHEGQyxEGuBzd3D1cXT3cXLiigPLOLs4uQALIAAA)
] |
[Question]
[
The task is to compute the divisor sum of a number given its prime factorisation.
### Input
Two arrays (or something equivalent) of length *n*, one containing the prime factor and the other containing the corresponding exponent.
### Output
The sum of all divisors (including the number itself).
### Example
The number 240 has 2, 3, and 5 as prime factors with 4, 1, and 1 as the respective exponents. The expected output would then be 744.
```
Input: [2,3,5] [4,1,1]
Output: 744
```
### Scoring
Shortest code in bytes wins!
If your solution's run time complexity is O(sum of exponents) rather than O(product of exponents), your score may be multiplied by 0.8.
---
There was a [similar question](https://codegolf.stackexchange.com/questions/8494/given-prime-factors-of-a-number-what-is-the-fastest-way-to-calculate-its-prope) posted here, but it wasn't a challenge. I think the problem is interesting enought to be golfed.
The winner will be choosen this weekend
[Answer]
# CJam, 15 bytes \* 0.8 = 12
```
q~.{_@)#(\(/}:*
```
[Try it online](http://cjam.aditsu.net/#code=q~.%7B_%40%29%23%28%5C%28%2F%7D%3A*&input=%5B4%201%201%5D%20%5B2%203%205%5D). The input order is exponent list first, then list of primes *(-3 bytes thanks to @Dennis)*.
For each prime-exponent pair `(p, e)` find
```
(p^(e+1) - 1)/(p - 1)
```
then find the product of all of these. E.g. for 240 this would be
```
(1 + 2 + 4 + 8 + 16)(1 + 3)(1 + 5) = 31 * 4 * 6 = 744
```
Depending on how exponentiation is implemented, this can be better than `O(sum of exponents)`.
[Answer]
# APL, ~~18~~ 13 bytes \* 0.8 = 10.4
```
×/(1-⊣×*)÷1-⊣
```
This creates a dyadic function train that takes the array of factors on the left and the exponents on the right.
```
×/ ⍝ Vector product of
(1-⊣×*) ⍝ each factor^(exponent+1)-1
÷1-⊣ ⍝ divided by factor-1
```
[Try it online](http://tryapl.org/?a=f%u2190%D7/%281-%u22A3%D7*%29%F71-%u22A3%20%u22C4%202%203%205%20f%204%201%201&run). Note that this is the same approach as Sp3000's awesomely clever [CJam answer](https://codegolf.stackexchange.com/a/53551/20469).
Saved 5 bytes thanks to Dennis!
[Answer]
# Pyth, 13 bytes \* 0.8 = 10.4
```
*Fms^LhdhedCQ
```
[Demonstration.](https://pyth.herokuapp.com/?code=*Fms%5ELhdhedCQ&input=%5B2%2C3%2C5%5D%2C%20%5B4%2C1%2C1%5D&debug=0)
This answer works somewhat differently from those above. In order to calculate the sum of the factors of the prime powers of the number, instead of using an arithmetic formula, the factors are explictly constructed and summed.
For instance, on the [prime, exponent] pair `[2, 4]`, we map `2 ^ x` over `0, 1, 2, 3, 4`, giving `[1, 2, 4, 8, 16]`, which is then summed to 31.
The results are then multiplied together and printed.
If exponentiation is implemented properly, or if there is intermediate result caching, this will be `O(sum of exponents)`.
[Answer]
# TI-BASIC, 17 bytes \* 0.8 = 13.6
Also uses Sp3000's method, though I found it independently. Takes one list from Input and one from the homescreen.
```
Input E
prod(AnsAns^∟E-1)/prod(Ans-1
```
Using prod( twice is smaller because it lets us use the open parenthesis for free. Note that this answer does not support empty arrays, because there are no empty arrays in TI-BASIC.
[Answer]
## Haskell, 38 \* 0.8 = 30.4
```
product$zipWith(\p e->(p*p^e-1)/(p-1))
```
Usage:
```
product$zipWith(\p e->(p*p^e-1)/(p-1)) [2,3,5] [4,1,1]
744.0
```
The anonymous function takes `(p,e)` to the divisor-sum for `p^e` via geometric series sum. Zipping together the two lists with this as the joining and taking the product gives the result.
I wasn't able to find anything shorter that the arithmetic expression
```
(p*p^e-1)/(p-1)
sum$map(p^)[0..e]
```
Maybe there's a way to get rid of the `(\p e->_)`.
Infix function definition gives the same length (38):
```
p%e=(p*p^e-1)/(p-1)
product$zipWith(%)
```
[Answer]
# C++, 111 80 77 bytes \* 0.8 = 61.6
```
int g(int*p,int*e,int n){return n?g(p+1,e+1,n-1)*(pow(*p,*e-1)-1)/(*p-1):1;}
```
This computes (p^(e+1)-1)/(p-1) and recursively multiplies all factors. Found that out myself a year ago.
Thank you for helping, totally forgot about c++ style boolean usage.
[Answer]
## Matlab, 53
```
function t=f(x,y)
s=1:prod(x.^y);t=s*~mod(s(end),s)';
```
Example:
```
>> f([2 3 5], [4 1 1])
ans =
744
```
[Answer]
# Python 2,156
```
from itertools import*
from operator import*
i=input()
print sum(reduce(mul,[a**b for a,b in zip(i[0],p)])for p in product(*map(range,[x+1 for x in i[1]])))
```
# Input
```
[[2,3,5],[4,1,1]]
```
# Output
```
744
```
# Explanation
This program receive list of 2 lists: factors and exponents.
```
i=input() # Receive list of 2 lists: i[0] for factors i[1] for exponents
```
Then its create list of all possible combinations of the exponent list.
```
[x+1 for x in i[1]] # [4,1,1]->[5,2,2] (to include last element)
map(range,[x+1 for x in i[1]]) # [[0, 1, 2, 3, 4], [0, 1], [0, 1]]
product(*map(range,[x+1 for x in i[1]])) # [(0, 0, 0), (0, 0, 1), ..., (4, 1, 1)]
```
and zip it with the factors:
```
zip(i[0],p) for p in product(*map(range,[x+1 for x in i[1]])) # [[(2, 0), (3, 0), (5, 0)], ..., [(2, 4), (3, 1), (5, 1)]]
```
Calculate the factors to the power of exponents:
```
[a**b for a,b in zip(i[0],p)]for p in product(*map(range,[x+1 for x in i[1]])) # [[1, 1, 1], ..., [16, 3, 5]]
```
and multiply each list (this gives us all the divisors):
```
reduce(mul,[a**b for a,b in zip(i[0],p)])for p in product(*map(range,[x+1 for x in i[1]])) # [1, 5, 3, 15, ..., 240]
```
Finally, sum all the lists and print:
```
print sum(reduce(mul,[a**b for a,b in zip(i[0],p)])for p in product(*map(range,[x+1 for x in i[1]]))) # 744
```
[Answer]
# Python 3, 134 120 117
Input: two comma-separated arrays separated by comma.
Example:
```
(2,3,7,11),(4,2,3,2)
21439600
```
```
from functools import*
a=eval(input())
print(reduce(int.__mul__,(sum(x**j for j in range(y+1))for x,y in zip(*a)),1))
```
With NumPy can be reduced to 100 bytes:
```
import numpy
a=eval(input())
print(numpy.product([sum(x**j for j in range(y+1))for x,y in zip(*a)]))
```
[Answer]
# APL, 12 bytes \* 0.8 = 9.6
```
×/1++/¨⎕*⍳¨⎕
```
This reads two lists from the keyboard, exponents first, i.e.:
```
×/1++/¨⎕*⍳¨⎕
⎕:
4 1 1
⎕:
2 3 5
744
```
Explanation:
* `⎕`: read a list from the keyboard (the exponents)
* `⍳¨`: for each number in the list, generate a list `[1..n]`.
* `⎕*`: read another list from the keyboard (the primes), and raise each prime to each of the exponents in the corresponding lists
* `+/¨`: sum each list
* `1+`: add one to each result, to compensate for the missing `x^0` in each of the lists
* `×/`: take the product of the results
[Answer]
# Racket (Scheme), 65 \* 0.8 = 52 bytes
Same arithmetic as everyone else
```
(λ(x y)(foldl(λ(m n o)(*(/(-(expt m(+ n 1))1)(- m 1))o))1 x y))
```
Explanation:
```
(λ (x y) ;defines anonymous function with two inputs
(foldl ;recursively applies the following function to all elements of the lists given to an argument given (foldl function argument lists lists lists...)
(λ (m n o) (* (/ (- (expt m (+ n 1)) 1) (- m 1)) o)) ;an anonymous function representing the same arithmetic used in the CJam answer, then multiplying it with our incrementor
1 x y)) ;the incrementor argument is 1, and the input lists are the ones provided into the original function
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
*PÆs
```
[Try it online!](https://tio.run/##y0rNyan8/18r4HBb8f/Dy///jzbSMdYxjf0fbaJjqGMYCwA "Jelly – Try It Online")
## How it works
```
*PÆs - Main link. Takes bases B on the left and exponents E on the right
* - Raise each base to each exponent
P - Take the product
Æs - Take the divisor sum
```
[Answer]
# Jelly
~~This answer is non-competing, since the challenge predates the creation of Jelly.~~
## 5 bytes (no bonus)
```
*PÆDS
```
[Try it online!](http://jelly.tryitonline.net/#code=KlDDhkRT&input=&args=WzIsIDMsIDVd+WzQsIDEsIDFd)
### How it works
```
*PÆDS Main link. Left input: p (prime factors). Right input: e (exponents).
* Elevate the prime factors to the corresponding exponents.
P Take the product of all powers.
ÆD Find all divisors of the product.
S Compute the sum of the divisors.
```
## 7 bytes (5.6 bytes after bonus)
```
*‘}’:’{P
```
### How it works
```
×*’:’{P Main link. Left input: p (prime factors). Right input: e (exponents).
* Elevate the prime factors to the corresponding exponents.
This yields p ** e.
× Multiply the prime factors with the corresponding powers.
This yields p ** (e + 1).
’ Decrement the resulting products.
This yields p ** (e + 1) - 1.
’{ Decrement the prime factors.
This yields p - 1.
: Divide the left result by the right one.
This yields (p ** (e + 1) - 1) / (p - 1).
P Take the product of all quotients.
```
[Try it online!](http://jelly.tryitonline.net/#code=w5cq4oCZOuKAmXtQ&input=&args=WzIsIDMsIDVd+WzQsIDEsIDFd)
[Answer]
# Python 2, 80 Bytes \* 0.8 = 64
This assumes the input comes in one after another. Follows the same formula as outlined in Sp3000's CJam answer.
```
print(reduce(float.__mul__,[~-(x**-~y)/~-x for x,y in zip(input(),input())],1))
```
If this isn't allowed, then I'll use this as a solution, which gets a score of 84 bytes \* 0.8 = 67.2. Input should be separated by a comma, i.e. `[2,3,5],[4,1,1]`.
```
k=input()
print(reduce(float.__mul__,[~-(x**-~y)/~-x for x,y in zip(k[0],k[1])],1))
```
---
Psst. Hey! This is a possible solution in Symbolic, something I'm working on: `Ƥ(П([~-(x**-~y)/~-xϝx,yϊʐ(Ί,Ί)],1))`
[Answer]
# Mathematica, 40 bytes
```
Total[Outer@@{*}~Join~(#^0~Range~#2),3]&
```
Without using any of the inbuilts that deal with divisors, to differentiate from the other mathematica solution in the thread.
Input is (using example) `[{2, 3, 5}, {4, 1, 1}]`
[Answer]
# Perl 5, 96 bytes
Obviously this is nonwinning, but I decided to write it for fun.
It's a subroutine:
```
{($b,$e)=@_;$s=1;map$s*=$b->[$_]**$e->[$_],0..@$b-1;$_=1x$s;for$j(1..$s){$i+=$j*/^(.{$j})*$/}$i}
```
See it in action thus:
```
perl -e'print sub{...}->([2,3,5],[4,1,1])'
```
How it works:
* `($b,$e)=@_` reads the input arrayrefs `$b` (bases) and `$e` (exponents).
* `$s=1` initializes the product.
* `map$s*=$b->[$_]**$e->[$_],0..@$b-1` multiplies `$s` by successive base-exponent powers. Now `$s` is the composite number.
* `$_=1x$s` sets `$_` equal to a string of ones, `$s` long. `$i` is initialized at 0.
* `for$j(1..$s){$i+=$j*/^(.{$j})*$/}` tries, for every number `$j` between 1 and `$s`, to break `$_` up as `$j` characters repeated any number of times. If it can, then `$j` divides `$s`, and `/^(.{$j})*$/` is 1 (otherwise it's 0), and `$i` is augmented by `$j`. Thus, we add to `$i` the number of partitions in a equal-sized partition of `$_`. As [Omar E. Pol points out](//oeis.org/A000203), `$i` is the number we're seeking.
* `$i` at the end returns `$i`.
[Answer]
# J, 14 bytes \* 0.8 = 11.2
```
[:*/(^>:)%&<:[
```
## Usage
```
f =: [:*/(^>:)%&<:[
2 3 5 f 4 1 1
744
```
] |
[Question]
[
A [magic square](http://mathworld.wolfram.com/MagicSquare.html) is a square array of numbers with side n consisting of the distinct positive integers 1, 2, ..., *n*² arranged such that the sum of the *n* numbers in any horizontal, vertical, or main diagonal line is always the same number, which is known as the magic constant.
Your program must input, through std-in, a number specifying the length of the side of your square, then the numbers in the square. No numbers may be used more than once, no number greater than *n*² may be used, and all numbers must be greater than 0. The program must determine whether that combination of numbers is a magic square.
[Answer]
## Python 2: 132 chars
```
n,l=input()
r=range
print r(1,n*n+1)==sorted(l)*len({sum(l[i::j][:n])for(i,j)in zip(r(n)+r(0,n*n,n)+[0,n-1],[n]*n+[1]*n+[n+1,n-1])})
```
An example run:
```
STDIN: 4,[16,3,2,13,5,10,11,8,9,6,7,12,4,15,14,1]
Output: True
```
The are two things to check:
1. The sums are the rows, columns, and diagonals are all equal
2. The elements are a permutation of `[1,2,...,n*n].`
The first is checked by taking sums of slices corresponding to these subsets. Each row, column, or diagonal is described by its starting value and its displacement. We take the list corresponding slice, truncate to `n` elements, and sum it. In Python's `[start:end:step]` notation, rows are `[r*n::1]`, columns are `[c::n]` and the two diagonals are `[0::n+1]` and `[n-1::n-1]`. These are stored as a list of `2*n+2` pairs produced by `zip`.
We take the sets of sums and check that it has length 1. Also, we sort the input and check that it is the list `[1,2,...,n*n].` Actually, we combine both into one check by multiplying `sorted(l)` by the length of the sum-sets, a check that always fails unless the sum-set has length 1.
[Answer]
## APL, 35
```
∧/2=/(+⌿x,⍉x),+/↑1 1∘⍉¨x(⌽x←⎕⍴⍨,⍨⎕)
```
**Explanation**
`x←⎕⍴⍨,⍨⎕` prompts for input, shape it into a matrix, and assign to `x`
`⌽` Reverses the matrix left-to-right
`x(...)` Create a array of matrices: `x` and `x` reverse
`1 1∘⍉¨` For each of those matrices, take the diagonal
`+/↑` form a 2×n matrix of the numbers on those diagonals and sum the rows
`⍉x` Transpose `x`
`x,` then concatenate with `x` to form a n×2n matrix
`+⌿` and sum the columns
`(+⌿x,⍉x),+/↑1 1∘⍉¨x(⌽x←⎕⍴⍨,⍨⎕)` concatenate to form an array of the sums
`2=/` check if consecutive pairs equal
`∧/` and AND together all those results
[Answer]
## CJam, ~~47 39 35 33~~ 31 bytes
```
l~/{_1fb_,Y${\(_@=\}%:++\z}2*;=
```
Takes input like
```
4 [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
```
Outputs `1` if magic square, `0` otherwise.
**How it works**:
```
l~/ "Evaluates the input and split the array into chunks"
"of size N where N is the first integer";
{ }2* "Run this code block 2 times";
_1fb "Copy the 2D array and calculate sum of each row of copy";
_, "Copy the array containing sum of each row and get"
"its length. This is equal to N";
Y${ }% "Run this code block for each array of the original"
"2D array that we copied from stack";
\(_ "Put the length number to top of stack, decrement and"
"copy that";
@=\ "Take the element at that index from each row and put"
"N back behind at second position in stack";
:+ "Take sum of elements of the array. This is sum of"
"one of the diagonals of the 2D array";
+ "Push diagonal sum to row sum array";
\z "Bring original array to top and transpose columns";
; "At this point, the stack contain 3 arrays:"
" Array with sum of rows and main diagonal,"
" Array with sum of columns and secondary diagonal and"
" The original array. Pop the original array";
= "Check if sum of rows + main diagonal array is equal to ";
"sum of columns + secondary diagonal array";
```
This can be golfed further.
[Try it online here](http://cjam.aditsu.net/)
[Answer]
**APL ~~47~~ 32**
Using TwiNight's excellent solution and applying some more tweaking:
```
∧/2=/+⌿(1 1∘⍉∘⌽,1 1∘⍉,⍉,⊢)⎕⍴⍨,⍨⎕
```
**Explanation:**
This uses function trains, which were introduced in v14 of the Dyalog interpreter.
APL is executed from right to left, ⎕'s are inputs, so first the dimensions, then the vector of numbers.
⎕⍴⍨,⍨⎕ creates the matrix NxN
After that comes the function train which are basically just a sequence of functions (between brackets) applied to the right argument.
The functions are:
⊢ Returns just right argument (that is the matrix)
⍉ Transposes the right argument matrix
1 1∘⍉ Returns the diagonal
1 1∘⍉∘⌽ Returns the diagonal of the reversed (horizontally) matrix
All the results are concatenated with the function ","
At this point, the result is a matrix whose columns are then summed (+⌿). The values obtained this way are then checked to be the same with ∧/2=/
I'll leave my old solution here too:
```
{M←⍺ ⍺⍴⍵⋄d←M=⍉M⋄(⊃≡∪)((+/,+⌿)M),+/∘,¨d(⌽d)ר⊂M}
```
takes dimension as left argument, vector of elements as right argument, for example:
```
4{M←⍺ ⍺⍴⍵⋄d←M=⍉M⋄(⊃≡∪)((+/,+⌿)M),+/∘,¨d(⌽d)ר⊂M}16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1
1
```
Can be tried online here: [www.tryapl.org](http://www.tryapl.org)
[Answer]
# Mathematica ~~128~~ 125
```
d = Diagonal; r = Reverse; i = Input[];
Length@Union[Tr /@ Join[p = Partition[i[[2]], i[[1]]],
t = Transpose@p, {d@p}, {d@t}, {d@r@p}, {d@r@t}]] == 1
```
Takes input such as
```
{4,{16, 3, 2, 13, 5, 10, 11, 8, 9, 6, 7, 12, 4, 15, 14, 1}}
```
>
> True
>
>
>
[Answer]
## GolfScript 67 ([demo](http://golfscript.apphb.com/?c=Oyc0IDE2IDMgMiAxMyA1IDEwIDExIDggOSA2IDcgMTIgNCAxNSAxNCAxJwoKfl06cSgvcSgvemlwK1txKCkveyhcO30lXStbcSgoLyk7KDt7KFw7fSVdK3t7K30qfSUuJiwyPHEoMj8seyl9JS0hKg%3D%3D&run=true))
```
~]:q(/q(/zip+[q()/{(\;}%]+[q((/);(;{(\;}%]+{{+}*}%.&,2<q(2?,{)}%-!*
```
[Answer]
# JavaScript (E6) 194
Using prompt to read input and display output.
Test in console with FireFox >31 (Array.fill is very new)
```
z=(p=prompt)(n=p()|0).split(' '),u=Array(2*n).fill(e=d=n*(n*n+1)/2),z.map((v,i)=>(r=i/n|0,u[r+n]-=v,u[c=i%n]-=v,d-=v*(r==c),e-=v*(r+c+1==n))),o=!(e|d|u.some(v=>v)),z.sort((a,b)=>a-b||(o=0)),p(o)
```
**Less golfed**
```
n = prompt()|0; // input side length
z = prompt().split(' '); // input list of space separeted numbers
e = d = n*(n*n+1)/2; // Calc sum for each row, column and diagonal
u = Array(2*n).fill(e), // Init check values for n rows and n columns
z.map( (v,i) => { // loop on number array
r = i / n | 0; // row number
c = i % n; // column number
u[r+n] -= v; // subtract current value, if correct it will be 0 at loop end
u[c] -= v;
if (r==c) d -= v; // subtract if diagonal \
if (r+c+1==n) e -=v; // subtract if diagonal /
}),
o=!(e|d|u.some(v=>v)); // true if values for rows, cols and diags are 0
z.sort((a,b)=>a-b||(o=0)); // use sort to verify if there are repeated values in input
alert(o);
```
[Answer]
# Pyth, ~~24~~ 30 bytes
```
&q1l{sM++JcEQCJm.e@bkd_BJqSlQS
```
Try it online [here](https://pyth.herokuapp.com/?code=%26q1l%7BsM%2B%2BJcEQCJm.e%40bkd_BJqSlQS&input=%5B2%2C7%2C6%2C9%2C5%2C1%2C4%2C3%2C8%5D%0A3&debug=0).
```
&q1l{sM++JcEQCJm.e@bkd_BJqSlQSQ Implicit: Q = evaluated 1st input (contents), E = evaluated 2nd input (side length)
Trailing Q inferred
cEQ Chop E into pieces or length Q
J Store in J
_BJ Pair J with itself with rows reversed
m Map the original and it's reverse, as d, using:
.e d Map each row in d, as b with index k, using:
@bk Get the kth element of b
The result of this map is [[main diagonal], [antidiagonal]]
+J Prepend rows from J
+ CJ Prepend columns from J (transposed J)
sM Sum each
{ Deduplicate
l Length
q1 Is the above equal to 1?
& Logic AND the above with...
SlQ ... is the range [1-length(Q)]...
q ... equal to...
SQ ... sorted(Q)
```
*Edit: fixed a bug, thanks to @KevinCruijssen for letting me know :o)*
[Answer]
**LUA 186 Chars**
```
s=io.read(1)v=io.read(2)d=0 r=0 for i=1,#s do t=0 for j = 1, #s do t=t+s[i][j]end d=d+s[i][i] r=r+s[i][#s-i+1]if t ~= v then o=true end end if d~=v and r~= v then o=true end print(not o)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~24~~ 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ôD©ø®Å\®Å/)O˜Ë²{¹nLQ*
```
Input format: `4\n[2,16,13,3,11,5,8,10,7,9,12,6,14,4,1,15]`. Outputs `1`/`0` for truthy/falsey respectively.
[Try it online](https://tio.run/##yy9OTMpM/f//8BaXQysP7zi07nBrDIjQ1/Q/Pedw96FN1Yd25vkEav3/b8IVbaRjaKZjaKxjrGNoqGOqY6FjaKBjrmOpY2ikAxQ30THRMdQxNI0FAA) or [verify some more test cases](https://tio.run/##fY8xTgMxEEX7PUWUDvQldmZsr7dKg5CQkBAFCBS2SARFmqRISQ0NDaLmAjRUFNRxyS24yPLHoUaWbI399/23m@1iubof88lpebmaTSeL9d1kOuNwyeHn6ZXDdiyfx7v38rX7KI@3vh0dnH@/lefrh5v12cXhiDE0c4UkiMEggogMadGhhyh4HxAgkDg0jAqUscBUYiR7qPWvGCWAWYmE/UX/XfvMfldogpojVCoiQ8ntID206mmodPZTxJp5YLWrxKohSPVWOSW@kEBJQx6aRL5VCJldJbSw@uxJdYwLiPPdgV0R1la2sSKQSRMa@q/2rkeZDONZm2E2/AI).
**Explanation:**
```
ô # Split the 2nd (implicit) input into parts of a size of the 1st (implicit) input
# i.e. [2,16,13,3,11,5,8,10,7,9,12,6,14,4,1,15] and 4
# → [[2,16,13,3],[11,5,8,10],[7,9,12,6],[14,4,1,15]]
D # Duplicate it
© # And store it in the register (without popping)
ø # Zip/transpose; swapping rows/columns
# i.e. [[2,16,13,3],[11,5,8,10],[7,9,12,6],[14,4,1,15]]
# → [[2,11,7,14],[16,5,9,4],[13,8,12,1],[3,10,6,15]]
® # Push the matrix from the register again
Å\ # Get the top-left to bottom-right main diagonal of it
# i.e. [[2,16,13,3],[11,5,8,10],[7,9,12,6],[14,4,1,15]] → [2,5,12,15]
® # Push the matrix from the register again
Å/ # Get the top-right to bottom-left main diagonal of it
# i.e. [[2,16,13,3],[11,5,8,10],[7,9,12,6],[14,4,1,15]] → [3,8,9,14]
) # Wrap everything on the stack into a list
# → [[[2,16,13,3],[11,5,8,10],[7,9,12,6],[14,4,1,15]],
# [[2,11,7,14],[16,5,9,4],[13,8,12,1],[3,10,6,15]],
# [2,5,12,15],
# [3,8,9,14]]
O # Take the sum of each inner list:
# → [[34,34,34,34],[34,34,34,34],34,34]
˜ # Flatten this list
# i.e. [[34,34,34,34],[34,34,34,34],34,34] → [34,34,34,34,34,34,34,34,34,34]
Ë # Check if all values are equal to each other
# i.e. [34,34,34,34,34,34,34,34,34,34] → 1 (truthy)
² # Push the second input again
{ # Sort it
# i.e. [2,16,13,3,11,5,8,10,7,9,12,6,14,4,1,15]
# → [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
¹n # Push the first input again, and take its square
# i.e. 4 → 16
L # Create a list in the range [1, squared_input]
# i.e. 16 → [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
Q # Check if the two lists are equal
# i.e. [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
# and [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] → 1 (truthy)
* # Check if both checks are truthy by multiplying them with each other
# i.e. 1 and 1 → 1
# (and output the result implicitly)
```
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), ~~36~~ 33 bytes
-3 bytes from improvements by @ngn
```
{1=#?{+/x,'x@'!#x}'(|+:)\(x,x)#y}
```
[Try it online!](https://tio.run/##HcrLDoIwEAXQX7mki86k@Li0CIUY/RDXuDBhXYJ8e524PTmf0/pea12mnXf32CVcSuvL0zeu6OHlGyZ9SWmLuu2oC85eJM0deAMjIkj0GMErBmSwg3lCAsFeZ4lWB7Nsi8YR418Zmqxafw "K (ngn/k) – Try It Online")
May be non-qualifying, as this is a function taking two args; the length of the square, and a list of the square's values.
* `(x,x)#y` build `x`-by-`x` matrix of the values from `y`
* `(|+:)\` build list of all rotations of the matrix
* `{...}'` inner lambda, called on each rotation
+ `x@'!#x` get the main diagonal elements
+ `x,'x` zip them with the original values
+ `+/` take the column-wise sum (the last column being the main diagonal)
* `1=#?` is there only one distinct sum?
[Answer]
# [Husk](https://github.com/barbuz/Husk), 27 bytes
```
&=O¹ḣ□³Λ=mΣ+mo►L∂Se↔C³¹S+TC
```
[Try it online!](https://tio.run/##yygtzv7/X83W/9DOhzsWP5q28NDmc7Ntc88t1s7NfzRtl8@jjqbg1EdtU5wPbT60M1g7xPn///8m/6ONdAzNdAyNdYx1DA11THUsdAwNdMx1LHUMjXSA4iY6JjqGQBWxAA "Husk – Try It Online")
I don't know any other techniques to golf this further, but it would be really cool if I could get it any lower.
Explanation coming later.
Takes inputs as 2 command line args, since Husk does not have the feature of taking from STDIN.
] |
[Question]
[
**Background:**
I often find that, when browsing a Stackexchange site, I begin to wonder how people get the amount of reputation that they have. I know I can always count on codegolf SE to solve my problems, so here it is:
Create a program that will accept a positive integer which represents a person's reputation. We will ignore bounties, and say that these are the only ways to gain/lose rep on SE (full table [here](https://stackoverflow.com/help/whats-reputation)):
* Every account starts out with 1 rep and cannot go below that
* Your question is upvoted = +5
* Your answer is upvoted = +10
* Your question is downvoted = -2
* Your answer is downvoted = -2
* You downvote an answer = -1
* Your answer is accepted = +15
* You accept an answer = +2
Your program must figure out how many of those actions occurred on that user's account to get to the rep they have. It must figure out the shortest number of actions to get to this level of rep. Examples:
>
> Input: 11
> Output: 1 answer upvote
>
>
> Input: 93
> Output: 6 answer accepts, 1 answer accepted
>
>
>
In these examples when I say 'question upvote', it means that person's queston got upvoted. When I say 'answer downvoted', it means they downvoted someone else's answer.
**Rules:**
[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code that can do this wins.
[Answer]
# Bash, ~~247~~ ~~202~~ 192 bytes
```
n=$1 bash <(sed 's/E/)echo /;s/C/ Aaccept/;s/A/answer /
s/.*)/((&)\&\&/'<<<'a=(n+1)/15,a-1)s=s;q=question
aE$aC$s
r=n%5,r-4)d=d&&
r>1E1Ced
1-r%2E1 Adownvote$d
n-=15*a,n>8)q=A
n>3E1 $q upvote')
```
### How it works
After the *sed* command does it job, the following bash script gets executed:
```
((a=(n+1)/15,a-1))&&s=s;q=question
((a))&&echo $a answer accept$s
((r=n%5,r-4))&&d=d&&
((r>1))&&echo 1 answer accepted
((1-r%2))&&echo 1 answer downvote$d
((n-=15*a,n>8))&&q=answer
((n>3))&&echo 1 $q upvote
```
To obtain the optimal solution (minimal number of events to get `n` reputation), it suffices to compute the number of accepted answers (`a`) necessary to get to a reputation below 16 (1 answer accept) and handle the residue as follows:
```
1 (no rep change)
2 answer accepted, answer downvoted
3 answer accepted
4 question upvote, answer downvote
5 question upvote, answer downvoted
6 question upvote
7 question upvote, answer accepted, answer downvoted
8 question upvote, answer accepted
9 answer upvote, answer downvote
10 answer upvote, answer downvoted
11 answer upvote
12 answer upvote, answer accepted, answer downvoted
13 answer upvote, answer accepted
14 answer accept, answer downvote
15 answer accept, answer downvoted
```
[Answer]
# Perl, 500 263 256 208 bytes
Script `rep.pl`:
```
$_=1+pop;sub P($){print$=,@_,$/}$;=" answer ";$:="$;downvote";($==$_/15)&&P"$;accept"."s"x($=>1);$_%=15;$==1;P"$;upvote",$_-=10if$_>9;P" question upvote",$_-=5if$_>4;P"$;accepted"if$_>2;P$:."d"if$_%2;P$:if!$_
```
## Usage
The input is expected as positive integer, given as argument to the script. The different actions are output as lines.
## Tests
```
perl rep.pl 11
1 answer upvote
perl rep.pl 93
6 answer accepts
1 answer accepted
perl rep.pl 1
perl rep.pl 4
1 question upvote
1 answer downvote
perl rep.pl 12
1 answer upvote
1 answer accepted
1 answer downvoted
perl rep.pl 19
1 answer accept
1 question upvote
1 answer downvote
perl rep.pl 34
2 answer accepts
1 question upvote
1 answer downvote
perl rep.pl 127
8 answer accepts
1 question upvote
1 answer accepted
1 answer downvoted
perl rep.pl 661266
44084 answer accepts
1 question upvote
```
## Ungolfed
```
$_ = pop() + 1; # read the reputation as argument,
# remove the actionless start reputation
# and add a bias of two to calculate
# the answer accepts in one division.
# Actions
# -------
# answer accepts: Your answer is accepted = +15
# answer upvotes: Your answer is upvoted = +10
# question upvotes: Your question is upvoted = +5
# answers accepted: You accept an answer = +2
# answers downvoted: You downvote an answer = -1
# answer downvotes: Your answer is downvoted = -2
# (questions downvoted: Your question is downvoted = -2) not used
# Function P prints the number of actions in $= and
# the action type, given in the argument.
# The function is prototyped "($)" to omit the
# parentheses in the usage.
sub P ($) {
print $=, @_, $/ # $/ is the line end "\n"
}
# abbreviations,
# special variable names to save a space if a letter follows
$; = " answer ";
$: = "$;downvote";
# Calculation and printing the result
# -----------------------------------
($= = $_ / 15) && # integer division because of the special variable $=
P "$;accept" .
"s" x ($= > 1); # short for: ($= == 1 ? "" : "s")
$_ %= 15;
$= = 1; # now the action count is always 1 if the action is used
P "$;upvote", $_ -= 10 if $_ > 9;
P " question upvote", $_ -= 5 if $_ > 4;
P "$;accepted" if $_ > 2;
P $: . "d" if $_ % 2;
P $: if ! $_
```
## Older version
```
$_ = pop() + 1; # read the reputation as argument
# subtract start reputation (1)
# add bias (2)
# Actions
# -------
# $= answer accepts: Your answer is accepted = +15
# $b answer upvotes: Your answer is upvoted = +10
# $c question upvotes: Your question is upvoted = +5
# $d answers accepted: You accept an answer = +2
# $e answers downvoted: You downvote an answer = -1
# $f answer downvotes: Your answer is downvoted = -2
# -- questions downvoted: Your question is downvoted = -2
# Calculaton of answer accepts by a simple division that is
# possible because of the bias.
$= = $_ / 15; # integer division because of the special variable $=
$_ %= 15;
# The older version of the calculation can be simplified further, see below.
# Also the older version did not use the bias.
#
# function E optimizes the construct "$_ == <num>" to "E <num>"
# sub E {
# $_ == pop
# }
#
# $d = $e = 1 if E 1; # 1 = +2 -1
# $d++ if E 2; # 2 = +2
#
# $c = $f = 1 if E 3; # 3 = +5 -2
# $c = $e = 1 if E 4; # 4 = +5 -1
# $c++ if E 5; # 5 = +5
# $c = $d = $e = 1 if E 6; # 6 = +5 +2 -1
# $c = $d = 1 if E 7; # 7 = +5 +2
#
# $b = $f = 1 if E 8; # 8 = +10 -2
# $b = $e = 1 if E 9; # 9 = +10 -1
# $b++ if E 10; # 10 = +10
# $b = $d = $e = 1 if E 11; # 11 = +10 +2 -1
# $b = $d = 1 if E 12; # 12 = +10 +2
#
# $=++, $f++ if E 13; # 13 = +15 -2
# $=++, $e++ if E 14; # 14 = +15 -1
$b++, $_ -= 10 if $_ > 9;
$c++, $_ -= 5 if $_ > 4;
# Now $_ is either 0 (-2), 1 (-1), 2 (0), 3 (1), or 4 (2).
# The number in parentheses is the remaining reputation change.
# The following four lines can be further optimized.
# $f++ if ! $_; # "! $_" is short for "$_ == 0"
# $e++ if $_ == 1;
# $d = $e = 1 if $_ == 3;
# $d++ if $_ == 4;
# Optimized version of the previous four lines:
$f++ if ! $_;
$e++ if $_ % 2;
$d++ if $_ > 2;
# function P optimizes the printing and takes the arguments for "print";
# the first argument is the action count and the printing is suppressed,
# if this action type is not needed.
sub P {
print @_, $/ if $_[0]
# $/ is "\n"
}
# some abbreviations to save some bytes
$; = " answer ";
$D = "$;downvote";
# output the actions
P $=, "$;accept", ($= == 1 ? "" : "s");
P $b, "$;upvote";
P $c, " question upvote";
P $d, "$;accepted";
P $e, $D, "d";
P $f, $D
```
## Edits
* Case 4 is fixed.
* This also simplifies the calculation that is now done without a loop.
* Unreachable plural "s" removed, function `S` no longer needed.
* Calculation optimized, function `E` no longer needed.
* Bias of 2 added for optimized calculation.
* Larger rewrite to remove most variables some other tricks to save some bytes.
[Answer]
# R, ~~454~~ 421
```
r=as.integer(commandArgs(T)[1])-1;p=function(...){paste(...,sep='')};a='answer ';b='accept';e='ed';f='d';v='vote';d=p('down',v);u=p('up',v);q='question ';z=c();t=r%/%15;if(t>0){z=c(p(t,' ',a,b));r=r%%15;};if(r%in%(8:12))z=c(z,p(a,u));if(r%in%(3:7))z=c(z,p(q,u));if(r%in%c(1,2,6,7,11,12))z=c(z,p(a,b,e));if(r%in%(13:14))z=c(z,p(a,b));if(r%in%c(3,8,13))z=c(z,p(a,d));if(r%in%c(1,4,6,9,11,14))z=c(z,p(a,d,f));cat(z,sep=', ')
```
Thanks to Dennis for [his answer](https://codegolf.stackexchange.com/a/25060/10619) which helped me a lot.
## Ungolfed version
```
# read input
r = as.integer(commandArgs(T)[1]) - 1
# shortcut to join strings (... will pass the parameter to paste() *as is*)
p = function(...) {paste(..., sep = '')}
# strings
a = 'answer '; b = 'accept'; e = 'ed'; f = 'd'
v = 'vote'; d = p('down',v); u = p('up',v)
q = 'question '
z = c()
# +15
t = r %/% 15;
if (t > 0) {
z = c(p(t,' ',a,b))
r = r %% 15
}
if (r %in% (8:12)) z = c(z,p(a,u)); # answer upvote
if (r %in% (3:7)) z = c(z,p(q,u)); # question upvote
if (r %in% c(1,2,6,7,11,12)) z = c(z,p(a,b,e)); # answer accepted
if (r %in% (13:14)) z = c(z,p(a,b)); # answer accept
if (r %in% c(3,8,13)) z = c(z,p(a,d)); # answer downvote
if (r %in% c(1,4,6,9,11,14)) z = c(z,p(a,d,f)); # answer downvoted
# print operations
cat(z,sep = ', ')
```
[Answer]
# JavaScript - ~~270~~ ~~237~~ ~~227~~ ~~206~~ 192 characters
```
p=prompt,r=p()-1,a="1answer ",v="vote,";s=(r/15|0)+"answer accept,",r%=15;if(r>9)s+=a+"+"+v,r-=10;if(r>2)s+="1question +"+v,r-=5;r>0?s+=a+"accepted,":0;r<-1?s+=a+"-"+v:0;p(r&1?s+=a+"-voted":s)
```
Exactly as many chars as Bash (yeah!), and beats Python and Perl :) It cuts down the reputation until `14` after which it takes after which it takes the other necessary actions, completely loop-style.
EDIT 1: Converted `\n`s to `,`s and converted one `if` block to ternary, and better flooring with short names.
EDIT 2: Big thanks to [Alconja](https://codegolf.stackexchange.com/users/17365/alconja) who helped me cut down **11** chars. After which I made some more corrections to cut down 2 more chars.
---
**Older Version:**
```
r=prompt()-1,a="1answer ",q="1question ",v="vote,";s=(c=r/15|0)+"answer accept,",r-=c*15;if(r>9)s+=a+"+"+v,r-=10;if(r>2)s+=q+"+"+v,r-=5;r>0?s+=a+"accepted,":0;if(r<-1)s+=a+"-"+v;r&1?s+=a+"-voted":0;alert(s)
```
---
## Test:
**INPUT:** `42`
**OUTPUT:**
```
2answer accept,1answer +vote,1answer accepted,1answer -voted
/*I sincerely hope the output is clear and easy to make out*/
```
**INPUT:** `1337`
**OUTPUT:**
```
89answer accept,1answer accepted,1answer -voted
```
---
## Ungolfed Code:
```
// different version from the golfed code
rep = prompt() - 1
string = ""
function $(z, c, k){
while(rep > 0 && rep >= z - 2) c += 1 , rep -= z;
if(c) string += c + k + "\n"
}
a=" answer ", q=" question "
$(15, 0, a + "accept")
$(10, 0, a + "upvote")
$(5, 0, q + "upvote")
$(2, 0, a + "accepted")
function _(z, c, str){
while(rep <= z) c += 1, rep -= z
if(c) string += c + str + "\n";
}
_(-2, 0, a + "downvote");
_(-1, 0, a + "downvoted");
alert(string);
```
[Answer]
# Golfscript, ~~162~~ 144 bytes
```
{{}if}:?;~.)15/:^15*-:~3>1~8>' answer ':A' question 'if'upvote'++?^^A'accept'+:C+^1>{'s'+}??~5%:,4<,1>&1C'ed'++?,2%!1A'downvote'++,4<{'d'+}??]n*
```
# How it works
The general idea is exactly the same as in [my Bash answer](https://codegolf.stackexchange.com/a/25060).
```
{{}if}:?; # Create an `if' statement with an empty `else' block.
#
~.)15/:^ # Interpret the input string, subtract 1 from its only element (the
# reputation score), divide by 15 and save the result in `^'. This gives
# the number of accepted answers.
#
15*-:~ # Multiply the number of accepted answer by 15 and subtract the product
# from the reputation score. Save the result in `~'.
#
3> # If the result is greater than 3:
#
1 # Push 1 on the stack.
#
~8> # If the result is greater than 8:
#
' answer ':A # Push `answer' on the stack. Either way, save the string in `A'.
#
' question ' # Otherwise, push `question' on the stack.
#
if #
#
'upvote'++ # Push `upvote' on the stack and concatenate the three strings.
#
? #
#
^ # If the number of accepted answers is positive:
#
^A'accept'+:C+ # Push the number, concatenated with the string ` answer accept', on the
# stack. Either way, the string in `C'.
#
^1> # If the number of accepted answers is greater than 1:
#
{'s'+} # Cocatenate the previous string with `s', for proper pluralization.
#
? #
#
? #
#
~5%:, # Calculate the reputation score modulus 5. Save the result in `,'.
#
4<,1>& # If the result is less than 4 and greater than 1:
#
1C'ed'++ # Push the string `1 answer accepted' on the stack.
#
? #
#
,2%! # If the result is odd:
#
1A'downvote'++ # Push the string `1 answer downvote' on the stack.
#
,4< # If the result is less than 4:
#
{'d'+} # Concatente the previous string with `d'.
#
? #
#
? #
#
]n* # Join the array formed by all strings on the stack, separating the
# strings by newlines. This is the output.
```
[Answer]
## Game Maker Language, 276
```
p=real(keyboard_string())-1j="#"s=""z=" answer"w=" accept"x=" upvoted"+j;y=w+"ed"v=" question"u=" downvoted"if m=floor(p/15)s+=(m+z+y)+j;r=p-m*15if m=floor(r/10)s+=(m+z+x)r-=m*10if m=floor(r/5)s+=(m+v+x)r-=m*5n=floor(r/2)r-=n*2if m=r{n++;s+=(m+u+z)+j}s+=(n+y+z)show_message(s)
```
[Answer]
## C# - 391
A bit long, and I haven't tested this thoroughly (much). :)
```
class R{void Main(string[] a){var r=int.Parse(a[0])-1;var a=new[]{15,10,5,2};var o=new List<string>();Func<int,string>y=z=>{var w="";if(z==15)w=" answer accepted";if(z==10)w=" answer upvotes";if(z==5)w=" question upvotes";if(z==2)w=" answer accepts";return w;};foreach(var x in a)if(r/x>0){o.Add(r/x+y(x));r-=(r/x)*x;}if(r==1)o.Add("1 question downvotes");Console.Write(string.Join(", ",o));
```
**Un-golfed - NEW**
```
class R
{
void Main(string[] a)
{
var r = int.Parse("122")-1; // subtracts 1 from total rep
var a = new[] {15,10,5,2};
var o = new List<string>();
Func<int,string> y =
z =>
{
var w="";
if(z==15) w=" answer accepted";
if(z==10) w=" answer upvotes";
if(z==5) w=" question upvotes";
if(z==2) w=" answer accepts";
return w;
};
foreach(var x in a) {
if (r/x>0) {
o.Add(r/x+y(x));
r-=(r/x)*x;
}
}
if(r==1)
o.Add("1 question downvotes");
Console.Write(string.Join(", ",o));
}
}
```
**Un-golfed - OLD (409)**
```
class R
{
void Main(string[] a)
{
var r = int.Parse(a[0])-1; // subtracts 1 from total rep
var v = new[] {" question"," answer"," downvotes"," upvotes"," accepts"," accepted"};
var o = new List<string>();
// Starts from 15, then checks all the lower values.
if (r/15>0) {
o.Add(r/15+v[1]+v[5]);
r-=(r/15)*15; // automatic rounding down due to int
}
if(r/10>0) {
o.Add(r/10+v[1]+v[3]);
r-=(r/10)*10;
}
if(r/5>0) {
o.Add(r/5+v[0]+v[3]);
r-=(r/5)*5;
}
if(r/2>0) {
o.Add(r/2+v[1]+v[4]);
r-=(r/2)*2;
}
if(r==1) {
o.Add("1"+v[0]+v[2]);
}
Console.Write(string.Join(", ",o));
}
}
```
**Test:**
```
> prog.exe 120
7 answer accepted, 1 answer upvotes, 2 answer accepts
```
[Answer]
**Python - 213 207**
```
p,k=__import__('itertools').combinations_with_replacement,int(input())
t,m,u=[5,10,-2,-1,15,2],[],iter(range(0,k))
while not m:m=list(filter(lambda v:k-1==sum(v),p(t,next(u))))
print(''.join(map(chr,m[0])))
```
Curse you long function names!
Example: (ignore the trailing newline)
```
$ echo "93" | python per.py | hexdump -C
00000000 0f 0f 0f 0f 0f 0f 02 0a |........|
$ echo "11" | python per.py | hexdump -C
00000000 0a 0a |..|
```
[Answer]
# C++, 276 (316 w/ includes)
```
#include <stdio.h>
#include <stdlib.h>
p(int&q,int*d){int r;char*s[]={"downvoted","accepted","question","answer","upvoted"};
if(r=(q&&q>=*d)){q-=(*d?*d:2);printf("%s %s\n",s[*(++d)],s[*(++d)]);}return r;}main(
int n,char**v){int q=atoi(v[1]);int d[]={-1,3,0,0,3,1,5,4,2,10,4,3,15,1,3};n=15;while
(p(q,d+n-3)||(n-=3));}
```
Compiles with GCC, with warnings. Example:
```
$ ./a.out 0
$ ./a.out 1
accepted answer
downvoted answer
$ ./a.out 2
accepted answer
$ ./a.out 5
question upvoted
$ ./a.out 10
answer upvoted
$ ./a.out 15
answer accepted
$ ./a.out 16
answer accepted
accepted answer
downvoted answer
$ ./a.out 17
answer accepted
accepted answer
```
Feel free to port this to a language that doesn't require type declarations and post it as your own.
[Answer]
# JavaScript - 273 256 235
```
p=prompt(s=j="\n")-1;z=" answer",w=" accept",x=" upvoted"+j,y=w+"ed",v=" question",u=" downvoted";if(m=p/15|0)s+=m+z+y+j;r=p-m*15;if(m=r/10|0)s+=m+z+x;r-=m*10;if(m=r/5|0)s+=m+v+x;r-=m*5;n=r/2|0;if(m=r-=n*2)n++,s+=m+u+z+j;alert(s+n+y+z)
```
Combined calculation and output, and golfed further to a total of 287.
Edit: took out some variables for a few shorter.
Removed Math.Floor for |0 approach.
Moved some initialisation to the prompt() param, removed some brackets, alert with final string append.
[Answer]
# Python3, 188B
```
n=input()+1
a=n//15
n%=15
A='answer '
print("%d %saccepted\n%d %supvoted\n%d question upvoted\n%d accept %s\n%d downvote %s\n%d %sdownvoted"%(a,A,n//10,A,n%10//5,n%5>2,A,n%5%2,A,n%5==0,A))
```
Usage: `python3 score.py <ret> 11 <ret>` where this script is saved as score.py.
Sample output:
```
$ python score.py
5543
369 answer accepted
0 answer upvoted
1 question upvoted
1 accept answer
0 downvote answer
0 answer downvoted
```
] |
[Question]
[
A composition of an integer \$n\$ is a representation of \$n\$ as a sum of positive integers. For example the eight compositions of 4 are as follows:
```
4, 3 + 1, 1 + 3, 2 + 2, 2 + 1 + 1, 1 + 2 + 1, 1 + 1 + 2, 1 + 1 + 1 + 1.
```
The challenge is to output the number of compositions of \$n\$ in which the greatest part is odd.
The sequence has generating function
$$ \sum\_{n=1}^\infty \frac{(1-x)^2 x^{2n-1}}{(1-2x+x^{2n-1}) (1-2x+x^{2n})}$$
You only need to do this for n up to 33.
Your code should output the following numbers in order.
```
1 1
2 1
3 2
4 3
5 7
6 14
7 30
8 62
9 129
10 263
11 534
12 1076
13 2160
14 4318
15 8612
16 17145
17 34097
18 67764
19 134638
20 267506
21 531606
22 1056812
23 2101854
24 4182462
25 8327263
26 16588973
27 33066080
28 65945522
29 131588128
30 262702054
31 524699094
32 1048433468
33 2095744336
```
You only need to output the second column, not the first.
The numbers are taken directly from [OEIS A103421](https://oeis.org/A103421) .
[Answer]
# [Python](https://docs.python.org/3.8/), 58 bytes
```
f=lambda n,m=0:sum(f(k,max(m,n-k))for k in range(n))or m%2
```
[Try it online!](https://tio.run/##RcpBCoMwEEbhvaeYjTADU6gKIoKHSdFUSec3pAr19Kmu3L7vxWObVzRdTDn74ePsNTqC2vDsv7ux56DmfmyKRxDxa6JACyg5vCeGyBmsrPMFuKFSqlrpC4ppwcZQ8tec/w "Python 3.8 (pre-release) – Try It Online")
An exponential solution that implicitly generates all compositions by deciding at each branch how to split the current value `n` into the first part `n-k` and remaining parts adding to `k`. Tracks the running maximum `m`, and when the initial `n` is exhausted, returns `m%2` to indicate if the maximum part was odd.
---
**60 bytes**
```
f=lambda n,m=1,r=2:n>1and f(n-1,max(r,m),r+1)+f(n-1,m)or m%2
```
[Try it online!](https://tio.run/##LcxBCsJADEbhvafIRpjQuEgLIoXxLpE6ttD8HUIXevqxgqsH3@LVzz5vGG41Wit5NX9MRhDPKpH7EXc1TFQSLipu7xTiLNEpd3/jLcjPfStHQQsoDK9nUiG98niiGgv2BPk9mNsX "Python 3.8 (pre-release) – Try It Online")
An exponential-time solution. Given `n`, it branches through all compositions of `n`, by deciding whether to increment the last summand or append a new summand of 1. Actually, we don't need to keep track of the entire composition, but only:
* `n`, the remaining value left to assign
* `m`, the maximum run length encountered so far
* `r`, the current run length plus one
When we increment the last summand, we bump up the run length and update the maximum to whichever is bigger of the current maximum and the new run length. When we append a new summand of 1, we reset the run length and keep the maximum. If either case, we decrement `n` because we've used up `1` value.
---
**[Python 3](https://docs.python.org/3.8/), 68 bytes**
```
lambda n:sum(~len(max(f"{k:b}".split('0')))%2for k in range(2**~-n))
```
[Try it online!](https://tio.run/##RcrRCoIwFAbg@57iIIjniEUaRAx8k24muRpuv2MuKCJffeFVtx9feKfHjNMlxGz6a3baDzdNUMvT8@pGsNcvNsVnUsO3OCzB2cTVsRKRsjNzpIksKGrcR@7qet1DJG@Ov7cNtWdROwrRIjEaMry1Hw "Python 3.8 (pre-release) – Try It Online")
A slow exponential-time solution. Generates all \$2^{n-1}\$ compositions by taking all bit strings of length \$n-1\$, splitting on zeroes, taking the length-plus-one of each run of ones, and summing these lengths modulo 2.
Actually, since we only care about the longest run, we just take the max run after splitting, take its length, and flip the parity. And, we can just work with binary representations of numbers from \$0\$ to \$2^{n-1}-1\$ without padding to length \$n-1\$ because the omitted leading zeroes correspond to runs of length 1 which we can ignore.
[Answer]
# [Python](https://www.python.org), 92 bytes
```
g=[17*[1,-1]]
r=range(33)
for i in r:g+=[sum(y[~k:])for*y,k in zip(*g,r)],;print(sum(g[-1]))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3Y9Jtow3NtaINdXQNY2O5imyLEvPSUzWMjTW50vKLFDIVMvMUiqzStW2ji0tzNSqj67KtYjWBMlqVOtkguarMAg2tdJ0izVgd64KizLwSDZC69GigaZqaEDugVsGsBAA)
Prints 33 terms.
### How?
First computes g(n,k), the number of compositions of n with all terms <= k.
This satisfies g(n,k) = g(n-1,k) + ... + g(n-k,k). (Split the set of compositions into k subsets by the size of the first term.)
Once we have those we can compute the odd-largest-term ones as f(n,2k+1) = g(n,1) - g(n,2) + ... + g(n,2k+1).
### [Python](https://www.python.org), 114 bytes
```
n,*g=0,
while 1:g+=[sum([p[j]for p in g[~j:]if p[j:]]+g[~j][:j])for j in range(n)]+[1],;print(sum(g[n][::2]));n+=1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3i_J0tNJtDXS4yjMyc1IVDK3StW2ji0tzNaILorNi0_KLFAoUMvMU0qPrsqxiM9MUgKJWsbHaIH5stFVWrCZISRZISVFiXnqqRp5mrHa0YayOdUFRZl6JBsik9Og8oFIro1hNTes8bVtDiM1QB8AcAgA)
Prints forever. Not very golfy but reasonably fast (O(n3)). Times out on ato after printing >800 terms.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Åœ€œ€`Ù€àÉO
```
-4 bytes outputting the \$n^{th}\$ value instead of mapping over the ranged list \$[1,33]\$
Outputs as a list.
Very slow, and will time out for \$n\geq9\$ on TIO.
[Try it online](https://tio.run/##yy9OTMpM/f//cOvRyY@a1oCJhMMzgeThBYc7/f//NwMA) or [(don't) verify all test cases](https://tio.run/##yy9OTMpM/W9s7HNu6//DrUcnP2paAyYSDs8EkocXHO70//8fAA).
**Explanation:**
```
Ŝ # Get all unique lists of positive integers that sum to the (implicit) input
€œ # Get the permutations of each list
€` # Flatten the list of lists of lists by one level
√ô # Uniquify the list of lists
ۈ # Only leave the maximum of each list
É # Check for each integer whether it's odd
O # Sum all those together
# (after which the resulting list is output implicitly)
```
---
A faster version that outputs all values in ~3 seconds on TIO - **18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**:
Port of [*@Jonathan Allan*'s Jelly answer](https://codegolf.stackexchange.com/a/252135/52210), so make sure to upvote him as well!
```
√Ö≈ì íŒ∏√â}Œµ√ÖŒ≥yg≈°!.¬ª√∑}O
```
[Try it online](https://tio.run/##ASgA1/9vc2FiaWX//8OFxZPKks64w4l9zrXDhc6zeWfFoSEuwrvDt31P//82) or [verify all test cases](https://tio.run/##ASwA0/9vc2FiaWX/MzNMzrX/w4XFk8qSzrjDiX3OtcOFzrN5Z8WhIS7Cu8O3fU///w).
**Explanation:**
```
Ŝ # Same as above: all positive integer lists that sum to the input
í # Filter this list of lists by:
θ # Only leave the last/largest integer
É # And check whether it's odd
}ε # After the filter: map over the remaining lists:
Åγ # Run-length encode the list, pushing the list of items and list of
# lengths separately to the stack
y # Push the current list again
g # Pop and push its length
š # Prepend this to the list of run-length encoded lengths
! # Get the factorial of each
.» # Left-reduce this list by:
√∑ # Integer-dividing
}O # After the map: sum everything together
# (after which the result is output implicitly)
```
[Answer]
# x86-64 machine code, 27 bytes
```
31 C9 48 0F AB F9 6A 01 58 99 89 CF 41 F7 D2 8D 34 3F 21 F7 75 F7 29 D0 E2 EF C3
```
[Try it online!](https://tio.run/##XVFBT/MwDD03v8IUTSTrNm2AOGyMC2cu3wmJcUiTtA3KkpG0kIH4619xuk0IfHDkZ/v52RHTWoi@P9dWmE4quA2t1G7W3JFfkNHlX8xrWyeMaNtCRZPnbEV42AKFfzkls9q4khuoSLXMovOgRJwkR7KyDeBT5KUm2a4LDSxWsHM78DwSZ5aZkK8k27o3UFIfm2blvlUwj9cLorHCuhaTiBvFQQWsekI2KBLnM8m4lcfegCNe7AdoQ7LQlaB4kjF0OpzoEPaqJSwHlD9ss@XaHhbytZiAaLiH8RiDN0Y@CaClZIQ1TBcT2OM7Xw3we6ONAloUEW7XsLhkA5psh@dqK5qPNEzvYKQ3Np8A6qhoZOzQfCrZ2AcuGm0VCCfVMj@m488Y6eDzVA2j@eUjcu3XlHY26NoqOSges4o9xaJ4Zquvk7A9nCFJvL/6MxIo6krnDewg7JTv2kRFLzb24gjhqTpvk5Iv0vf/RWV4Hfrp9uYaHX7@GhmV@QY "C (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes a value in EDI and returns a value in EAX.
The value taken is 0-indexed, so `n-1`, as permitted in the default [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules. (For a version taking `n`, insert `dec edi` at the start for +2 bytes.)
In assembly:
```
f: xor ecx, ecx # Set ECX to 0.
bts rcx, rdi # Set to 1 the bit at position given by the argument.
push 1; pop rax # Set EAX to 1.
ol: cdq # Set EDX to 0 by sign-extending EAX.
mov edi, ecx # Copy the value of ECX into EDI.
.byte 0x41 # REX.B prefix; combines with the next instruction
# into "not r10", here effectively a no-op.
il: not edx # Invert each bit of EDX, changing 0 to -1 or vice versa.
lea esi, [rdi + rdi] # Set ESI to 2*EDI.
and edi, esi # Bitwise-AND EDI with the doubled value.
jnz il # Jump back, to repeat the inner loop, if it's nonzero.
sub eax, edx # Subtract EDX from EAX.
# This adds 1 from EDX=-1 or is no change for EDX=0.
loop ol # Decrease ECX by 1, and jump back if it's nonzero.
ret # Return.
```
---
```
1 + 3 + 1 + 4 = 9
● ●—●—● ● ●—●—●—●
0 1 1 0 0 1 1 1
```
A composition can be visualised as `n` dots, with each two consecutive dots either joined or not joined.
Then, it can be represented by `n-1` bits, with each bit being 1 for joining or 0 for not joining.
The greatest part is equal to 1 plus the maximum number of consecutive 1s in those bits.
```
Original: 0 1 1 0 0 1 1 1
Doubled: 0 1 1 0 0 1 1 1 0
Bitwise AND: 0 1 0 0 0 1 1 0
```
Take the bitwise AND with the value doubled: this reduces the length of each block of consecutive 1s by 1.
Repeat until the result is 0; the number of repetitions is the maximum number of consecutive 1s.
The program loops from \$2^{n-1}\$ down to 1, and counts the compositions with the greatest part odd in EAX. \$2^{n-1}\$ is actually invalid, but it doesn't matter because it doesn't get counted.
0, which corresponds to the composition \$1 + \cdots + 1\$, is skipped because of the way the loop works (but it would have been a false negative anyway, because the inner loop always executes at least once). To correct for this, EAX is initialised to 1 instead of 0.
Because of the use of 32-bit registers for the calculation, when `n=33`, the first iteration uses a value of 0 instead of 232, but this makes no difference to the result.
[Answer]
# JavaScript (ES6), 47 bytes
*-3 bytes thanks to [m90](https://codegolf.stackexchange.com/users/104752/m90)*
```
f=(n,m,i=1)=>i>n?!n&m:f(n-i,i<m?m:i)+f(n,m,i+1)
```
[Try it online!](https://tio.run/##JcxBCoMwEEDRvaeYgpQMiYUUulGjVzFYU6aYiWjpJuTsMeDuLx7/a//2mHfafg2H95KzM4KVV2Q0moEGHm98960T3JCi3o@@JZTuMlJjdmEXDAZ0Bwy9geerhJQIsQKYAx9hXR5r@IjJijpywmLrWAaYJuyqlE8 "JavaScript (Node.js) – Try It Online")
(limited to the 25 first terms on TIO)
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
m, // m = maximum value in the composition
i = 1 // i = value to be subtracted from n
) => //
i > n ? // if i is greater than n:
!n & // increment the final result if n = 0
m // and m is odd
: // else:
f( // do a 1st recursive call where:
n - i, // i is subtracted from n
i < m ? m // m is updated to max(m, i)
: i // (and i is implicitly reseted to 1)
) + // end of recursive call
f( // do a 2nd recursive call where:
n, // n is left unchanged
m, // m is left unchanged
i + 1 // i is incremented
) // end of recursive call
```
[Answer]
# Regex `üêá` ([RME](https://github.com/Davidebyzero/RegexMathEngine/) / PCRE2 v10.35+), 45 bytes
```
^(?*(x(xx)*))(?(?=\1(x*))x+(?=\3($)?)|x+)+$\4
```
Takes its input in unary, as the length of a string of `x`s. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.)
[Attempt This Online!](https://ato.pxeger.com/run?1=hV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28BhK8194zRuXDPZlbkNkJmjzv9bg87G_BRY6Sd5BHYGDwzhpLz1ppjtNbvRtzz_EmPgybOWQCVy7aW-xJxyBBFVxOgob-Kgks4LIHDwPu-chxWDPiJSnvCQKnpBG8d80hJEgdSCt-ptj6NkH_fP4NwauFwZUeIeBYw5ruJdmUj9mliNnsKHCaQUOovzWnYW3KSPwN5zTuYQft7hobO4HpuuHwchheXL4-Hp2ckUeKin6N9lpODFHW9IkNCm-dDd319If5bSLeMsnl89Baf29rrLSkFK_j22xoLbDak-ZE1JcwM1YDW0cCrw79P8Aff3ba3Y5e_wc "PHP - Attempt This Online") - PCRE2 v10.40+
[Try it on replit.com](https://replit.com/@Davidebyzero/regex-Unordered-partitions-with-odd-greatest) - RegexMathEngine
```
^ # tail = input number
(?*
(x(xx)*) # \1 = {any odd number, which shall be the maximum
partition width}
)
(?(?=
\1(x*) # \3 = tail - \1
)
# If the above condition (tail ‚â• \1) is true:
x+ # tail -= {any positive number}
(?=\3($)?) # Assert tail ‚â• \3; if tail == \3, set \4 = 0
|
# Else:
x+ # tail -= {any positive number}
)+ # Iterate the above any positive number of times
$ # Assert tail == 0
\4 # Assert that \4 is set, i.e. that the chosen maximum
# partition width occurred at least once.
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
ṄvṖÞfUvG∷∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBUCIsIiIsIuG5hHbhuZbDnmZVdkfiiLfiiJEiLCIiLCIxXG4yXG4zXG40XG41XG42XG43Il0=)
Port of 05AB1E. Very slow.
```
ṄvṖÞfUvG∷∑ # example input: 3
Ṅ # integer partitions => [[1, 1, 1], [2, 1], [3]]
v·πñ # permutations of each => [[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]], [[2, 1], [1, 2]], [[3]]]
√ûf # flatten by one level => [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [2, 1], [1, 2], [3]]
U # uniquify => [[1, 1, 1], [2, 1], [1, 2], [3]]
vG # max of each => [1, 2, 2, 3]
‚à∑ # modulo each by 2 => [1, 0, 0, 1]
‚àë # sum => 2
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
No integer partitions in Japt but a port of [xnor's Python solution](https://codegolf.stackexchange.com/a/252147/58974) works out at a respectable length. Completes for input `33`, and beyond, in milliseconds.
```
ÆßXVwXnUÃx ªVu
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xt9YVndYblXDeCCqVnU&input=MzM)
```
ÆßXVwXnUÃx ªVu :Implicit input of integers U and V, the latter of which defaults to 0
Æ :Map each X in the range [0,U)
ßX : Recursive call with arguments X and
Vw : Max of V and
XnU : U-X
à :End map
x :Reduce by addition
ª :Logical OR with
Vu :V%2
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~ 12 ~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 by delaying the mod-2 check like [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s [05AB1E answer](https://codegolf.stackexchange.com/a/252128/53748).
```
ŒṗŒ!€ẎQṀ€ḂS
```
A monadic Link that accepts a positive integer and yields the number of compositions with an odd largest part.
**[Try it online!](https://tio.run/##y0rNyan8///opIc7px@dpPioac3DXX2BD3c2gFg7moL///9vAQA "Jelly – Try It Online")** (Slow - [\$9\$ within \$1\$ minute on TIO](https://tio.run/##y0rNyan8///opIc7pz/c0fRw5yqVY@1HJyk@alrzcFdfoM9/y8PtQPZ/AA))
Or, a faster version which can do all \$33\$ in [under \$12\$ seconds on TIO](https://tio.run/##ASoA1f9qZWxsef//xZLhuZfCtUw7xZLJoCE6L8OX4biC4bmqKVP/MzPDh@KCrP8 "Jelly – Try It Online") in \$15\$ bytes (slightly slower than the \$16\$ byte version in the history of edits):
```
ŒṗµL;Œɠ!:/×ḂṪ)S
```
### How?
The slow one:
```
ŒṗŒ!€ẎQṀ€ḂS - Link: positive integer, n e.g. 5
Œṗ - integer partitions [[1,1,1,1,1],[1,1,1,2],[1,1,3],[1,2,2],[1,4],[2,3],[5]]
Œ!€ - all permutations of each [[[1,1,1,1,1],[1,1,1,1,1],...],[[1,1,3],[1,3,1],[1,1,3],[1,3,1],[3,1,1],[3,1,1]],...,[[5]]
Ẏ - tighten [[1,1,1,1,1],[1,1,1,1,1],...,[1,1,3],[1,3,1],[1,1,3],[1,3,1],[3,1,1],[3,1,1],...,[5]]
Q - deduplicate [[1,1,1,1,1],...,[1,1,3],[1,3,1],[3,1,1],...,[5]]
Ṁ€ - maximum of each [1,2,2,2,2,3,3,3,2,2,2,4,4,3,3,5]
Ḃ - modulo 2 [1,0,0,0,0,1,1,1,0,0,0,0,0,1,1,1]
S - sum 7
```
The faster version calculates the number of distinct permutations for each partition and sums them up instead:
```
ŒṗµL;Œɠ!:/×ḂṪ)S - Link: positive integer, n
Œṗ - all partitions
(note: each are always in sorted order)
µ ) - for each: e.g. part = [2,2,2,4,5,5]
L - length 6
Œɠ - run-lengths [3,1,2]
; - concatenate [6,3,1,2]
! - factorial [720,6,1,2]
/ - reduce by:
: - integer division 60
Ḃ - (part) modulo 2 [0,0,0,0,1,1]
√ó - multiply [0,0,0,0,60,60]
·π™ - tail 60
S - sum
```
[Answer]
# [Desmos](https://desmos.com/calculator), 121 bytes
```
f(n)=1+‚àë_{k=1}^{n^n-1}0^{(n-total(AL))^2+mod(L[A>0].max-1,2)}A.total!/‚àè_{i=1}^nA![i]
L=[1...n]
A=mod(floor(nk/n^L),n)
```
What can I say, Desmos just isn't that great at problems involving counting partitions, especially ones where order matters.
Also, this is very inefficient. It can't even calculate \$n=10\$ in a reasonable amount of time, let alone \$n=33\$. This is because it tests \$n^n-1\$ different partitions; as you can imagine, that is not efficient at all.
[Try It On Desmos!](https://www.desmos.com/calculator/obvcdwg9la)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/lfuq9nuq0v)
[Answer]
# Python3, 425 bytes:
```
import math as M,itertools as I
R=range
Y=lambda x:x[0]if 1==len(x)else x[0]*Y(x[1:])
def f(n,s,c):
if n==0:yield c;return
for i in{*R(1,s+1)}-{*c}:
for x in R(1,n//i+1):
if i*x<=n:yield from f(n-i*x,s,c+[i]*x)
def F(n):
t=[]
for i in R(1,n+1):
if i%2:t+=[tuple(sorted(j))for k in R(1,n//i+1)for j in f(n-i*k,i,[i]*k)]
return sum(M.factorial(len(j))/Y([M.factorial(len([*b]))for _,b in I.groupby(j)])for j in{*t})
```
[Try it online!](https://tio.run/##XZHLbsIwEEXXzVd4U8l2zCOliyqtt0gs2LBDVlTl4YAhsSPbkYIQ3556CKISS9@ZOffOuLv4o9Grr86Oo2o7Yz1qc39EuUNbpry03pjGwXMT7bjN9UFGe97kbVHlaEgHscxUjRLOG6nxQGTjJAKR7vEgkjQjUSVrVGPNHCtJGqHQrTlfphclmwqV31b63uoI1cYihZS@0h1OmIsTcptdaXkLI/faEGoISnqxUKEKOsAUHX64fuBqa1owmwUVDGOhMjpMGdZYw5DnIvt3m4gPHNDeP1Ifc@H7rpHYhXPICp8Igf7zSwLQTqBNhmemGNidSeBPWyHXt3g7r/PSG6vyBsORAm2xx@JVFrTIJp9fVgB1Mz9Y03fFJUxkT7Mr9TcyPuPfPyREWn2GDd46q7THiq2xImT8Aw)
Prints all 33 results in ~10 seconds.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 52 bytes
-13 bytes thanks to [@xnor](https://codegolf.stackexchange.com/users/20260/xnor).
```
n->sum(i=0,2*n,(-1)^i*(1-x)/(1-2*x+x^i))%x^(n+1)\x^n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN03ydO2KS3M1Mm0NdIy08nQ0dA014zK1NAx1KzT1gaSRVoV2RVympqZqRZxGnrahZkxFXB5Ur0pafpFGnoKtgqGOgqmBjkJBUWZeCVBASUHXDkikaeRpampC1C5YAKEB)
Using the generating function.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes
```
Mod[Max@## 2^#,2]+#0[#-i,##2,i]~Sum~{i,#}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zc/Jdo3scJBWVnBKE5ZxyhWW9kgWlk3U0dZ2UgnM7YuuDS3rhrIq1X7H1CUmVcClLNLc1COVatzLCpKrKwzNv4PAA "Wolfram Language (Mathematica) – Try It Online")
Slow recursive solution.
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), (slow) 16 bytes
```
cn od<xMl<<pt<e1
```
**Alternative 1**
```
cn(od<xMl)<pt<e1
```
**Alternative 2**
```
l<pST(od<xMl)<e1
```
## Explanation
* `e1`: Create a list from \$1\$ to \$n\$.
* `pt`: Get all partitions of the list.
* `xMl<`: Get the length of the largest part in each partition.
* `cn od`: Count the number of odd results.
## Reflection
I've not spent much focus on arithmetic in hgl, so I am pretty pleased with this. The use of `xMl` here is brutally efficient. That being said there are some things I think could be improved.
* There's no function which takes mod 2. You can do `fmu 2`, but that's really long. Small modulos should have builtins. This wouldn't make this answer shorter, but I noticed this.
* There should be a function for finding integer partitions. `l<<pt<e1` is *way* too long, and this will likely come up again. With a function for integer partitions, `ipt`, this whole thing could be `cn od<mx<<ipt` which would save 3 bytes.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 31 bytes
```
{2+.|⌈/¨∪((∨\⍢⌽⍵=+\)¨⊆⍥∊⊢)⍳⍴⍨⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/P03hUdsEhWojbb2aRz0d@odWPOpYpaHxqGNFzKPeRY969j7q3WqrHaMJFO9qe9S79FFH16OuRZqPejc/6t3yqHcFULr2/6O@qWBT0hQMuRBsIyS2MRLbBIltisQ24/oPAA "APL (Dyalog Extended) – Try It Online")
```
⍳⍴⍨ all permutations of 1..n
(∨\⍢⌽⍵=+\)¨ mask contiguous subsets which compose to n
⊆⍥∊ partition compositions
‚à™ uniques
⌈/¨ greatest of each
2+.| count odds
```
Same length in BQN: `{+¬¥2|0‚åଥ¬®‚ç∑‚•ä(‚à®`‚åæ‚åΩùï©=+`)‚ä∏/¬®1+‚Üï‚•äÀúùï©}`
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
IEφLΦEXφφ↨λφ∧⌊λ∧⁼⊕ιΣλ﹪⌈λ²
```
Don't try it online, or indeed offline, because it needs unreasonable amounts of time and memory. Instead, here's a link that computes 6 values instead:
[Try it online!](https://tio.run/##PUzLCgIhFP0Vl1cw6AGzaVVRECQM9AWil0a4XstH9fcmw9BZnbedTLLRUGtj8lzgZHIBbZ4wKHFDfpQJLp4Kptkc46eznRKbtVTiaDICKTHILg7sQHv2oQagRZ9f1VCGK9uEAbmgA9@j@1zpREdXKfbn73@2lQv2rbXVm34 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
φ Predefined variable `1000`
E Map over implicit range
φ Predefined variable `1000`
X Raised to power
φ Predefined variable `1000`
E Map over implicit range
λ Current value
‚Ü® Converted to base
φ Predefined variable `1000`
Φ Filtered where
λ List of base `1000` digits
‚åä Minimum
‚àß Logical And
ι Outer value
‚äï Incremented
⁼ Equals
λ List of base `1000` digits
Σ Summed
‚àß Logical And
λ List of base `1000` digits
‚åà Maximum
Ôπ™ Modulo
² Literal integer `2`
L Take the length
I Cast to string
Implicitly print
```
36 bytes for a slightly faster version:
```
⊞υ⟦⁰⟧FυF⁻φΣι⊞υ⁺ι⟦⊕κ⟧IEφLΦυ∧⁼⊕ιΣλ﹪⌈λ²
```
Don't try it online, because it still tries to compute 1,000 values. Instead, here's a link that computes 10 values instead:
[Try it online!](https://tio.run/##TY3BCsIwDIbvPkWPCUyYXncSURA2GHiUHcpWXTBrtW3Et691QzCXhD/5vvSj9r3TnFIrYQQp1KXssFpdnVcgqObekJUAm7JQZ5mAEFH9rlvOG8rUyfbeTMZGM8AdO8yO1pONsNchQqMfM18be4sjHImj8V9@Zwc4PEVzgH8D4fKLMQ@NG4RddrxpmrNCbXGpKqW0fvEH "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ⟦⁰⟧
```
Start with a sum of `0`.
```
Fυ
```
Loop over all of the sums so far.
```
F⁻φΣι
```
Find integers to add to this sum without exceeding 1,000.
```
⊞υ⁺ι⟦⊕κ⟧
```
Add the new sum to the list of sums.
```
IEφLΦυ∧⁼⊕ιΣλ﹪⌈λ²
```
Count how many sums with odd maxima sum to each integer up to 1,000.
42 bytes for a slightly faster still version:
```
Fφ⊞υEφ⎇κ⎇›κι⁰Σ⁺…§υ±κκE…⮌υκ§μκ¬ιIEΦυκΣΦι﹪μ²
```
Don't try it online, because it still tries to compute 999 values. Instead, here's a link that computes 9 values instead:
[Try it online!](https://tio.run/##RY7BDoIwDIbvPsWOXYKJeuVkSDQeNER9gQWqLAxGuo3I089VMPTUv/3/r60aRZVVJsaXJQH7nRRlcA2ETFzVkHQmnki9ognatT0TKo/EIy0zkUyP0EFpgoNiqgwWjR3g6C99jR9G3fCd/NDKZG7ljF6NdxyRHEJYtv9gx5IrAawHzW2@KUn3HgrlPDDmpA1/EuYov7FMdDpj62Ascw4/jsxjjNvRfAE "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Fφ
```
Loop 1,000 times.
```
⊞υEφ⎇κ⎇›κι⁰Σ⁺…§υ±κκE…⮌υκ§μκ¬ι
```
Calculate the matrix `f(n, m)` of the number of sums of compositions of `n` whose maximum is `m`. The "first" row for `n=0` is simply `1, 0...` and subsequent rows are calculated by moving up `m` cells and left `m` cells and summing the passed-over cells.
```
IEΦυκΣΦι﹪μ²
```
For each `n>0`, sum those `f(n, m)` where `m` is odd.
Example: The first few rows of `f` look like this:
```
1 0 ...
-----------
0 1 0 ...
--------------+
0 1 1 0 | ...
----------+ |
0 1 2 | 1 | 0 | ...
------+ | | |
0 1 | 4 | 2 | 1 | 0 | ...
--+ | | | | |
0 | 1 | 7 | 5 | 2 | 1 | 0 | ...
```
These are calculated as `1 = 1 + 0`, `7 = 4 + 2 + 1 + 0`, `5 = 2 + 1 + 0 + 1 + 1 + 0`, `2 = 1 + .... + 1 + 0`, `1 = ... + 1`.
This final version can be adapted to calculate exactly 33 values, but that takes 44 bytes: [Try it online!](https://tio.run/##RY7BCsIwDIbvPkWPKUwQ9baTDBQPylBfoMzoyrp1pO1wT18bN1lO@ZP//5KqVlRZZWJ8WRKw20tRBldDyMRF9Uln4oHUKRqhWdoTofJIPNIyE5tM3EMLpQkOirEyWNS2h4M/d0/8MOqK7@SHRiZzIyf0YrzhgOQQwrz9B1uWXAlgPWhu81VJuvNQKOeBMUdt@JMwRfmNeaLTGfsMxjJn@@PIPMa4HswX "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 bytes
```
sm&%ed2l{.pd./
```
[Try it online!](https://tio.run/##K6gsyfjvFhgc@L84V001NcUop1qvIEVP//9/y3/5BSWZ@XnF/3VTAA "Pyth – Try It Online")
## Explanation
```
sm&%ed2l{.pd./Q
s # sum(
m # map(
# lambda d:
%ed2 # (d[-1] % 2)
& # and # short-circuiting
l{.pd # len(unique(permutations(d)),
./Q # partitions(input) # partitions are sorted
# )
# )
```
[Answer]
# [Haskell](https://www.haskell.org/), (slow) 49 bytes
```
0!u=mod u 2
x!u=sum[(x-i)!max u i|i<-[1..x]]
```
```
(!0)
```
[Try it online!](https://tio.run/##FcpBCoAgFEXRuat4znSQVONcQisQCaGiT/2SSnDQ3q1ml8NdwrVO21ZKLZPlY0RCK/LXV2KnckVacsif0kNd5RpjsvditkrWunCgHRbjIQAOsR@g4kn7DYNZ45@b1pcX "Haskell – Try It Online")
] |
[Question]
[
Let's say we have a 2-D list, like the following one:
\$
\begin{bmatrix}
\color{red}{1} & \color{red}{2} & \color{red}{3} & \color{red}{4} \\
\color{blue}{5} & \color{blue}{6} & \color{blue}{7} & \color{red}{8} \\
\color{green}{9} & \color{green}{10} & \color{blue}{11} & \color{red}{12}
\end{bmatrix}
\$
Notice how the top row and the right column is red. For the purposes of this question, let's call this a J-bracket✝. The *2nd* J-bracket is highlighted in blue, and the 3rd J-bracket is highlighted in green. Your challenge is not to [*find* the J-brackets](https://codegolf.stackexchange.com/questions/245692), but given the J-bracket list, you need to return the original 2-D list.
In many cases, there will be more than one 2-D list possible based on the J-brackets. In this case, you can return either of the possible 2-D lists, or you can return a list of the possiblities.
Let's say you are given the list `[[1,2,3,4,5,6], [1,2,3,4], [1,2]]`. This means the 1st J-bracket is `[1,2,3,4,5,6]`, the 2nd J-bracket is `[1,2,3,4]`, and the 3rd one is `[1,2]`. There are two different possible matrixes that can be created from these J-brackets:
\$
\begin{bmatrix}
\color{red}{1} & \color{red}{2} & \color{red}{3} & \color{red}{4} \\
\color{blue}{1} & \color{blue}{2} & \color{blue}{3} & \color{red}{5} \\
\color{green}{1} & \color{green}{2} & \color{blue}{4} & \color{red}{6}
\end{bmatrix}
\$
OR:
\$
\begin{bmatrix}
\color{red}{1} & \color{red}{2} & \color{red}{3} \\
\color{blue}{1} & \color{blue}{2} & \color{red}{4} \\
\color{green}{1} & \color{blue}{3} & \color{red}{5} \\
\color{green}{2} & \color{blue}{4} & \color{red}{6}
\end{bmatrix}
\$
## Test cases
```
[[1,2,3,4,5], [1,2,3], [1]] => [[1,2,3], [1,2,4], [1,3,5]]
[[1,2,3,4,5,6], [1,2,3,4], [1,2]] => [[1,2,3], [1,2,4], [1,3,5], [2,4,6]]
OR [[1,2,3,4], [1,2,3,5], [1,2,4,6]]
[[6,8,9,6,5,8,2],[1,7,4,3,2],[2,3,1]] => [[6,8,9,6,5], [1,7,4,3,8], [2,3,1,2,2]]
OR [[6,8,9], [1,7,6], [2,4,5], [3,3,8], [1,2,2]]
[] => []
```
## Rules
* You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447)
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
✝ The name J-bracket was robbed from [this question](https://codegolf.stackexchange.com/questions/245692).
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 20 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{(↓∘⍺⍪⍵,∘⍪↑∘⍺)-≢⍵}/⊆
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q9Z41Db5UceMR727HvWuetS7VQfMWfWobSJEVFP3UecioHit/qOuNgA&f=S1d41DZBIU3hUd9Ur2B/P650BfXoaEMdIx1jHRMd01gdBQgHzIiNVUeT1zGDq9AxgTLhqsx0LHQsdcyAqiyAojpAOXOgHmMwG6QBbl6sOgA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
`⊆` Nest if simple (if the input is `[]`). This is necessary to deal with the empty case.
`/` Reduce the list of J-brackets from right to left with:
`{ ... }` Takes the current matrix as ⍵ and the new J-bracket as ⍺.
`-≢⍵` Number of rows, negated
`( ... )` Call the tacit function with this as a right argument.
`↑∘⍺` Take that many values from ⍺ (taking a negative amount gets values from the end)
`⍵,∘⍪` Append to ⍵ as a column.
`↓∘⍺⍪` Drop `-≢⍵` values from ⍺, prepend that as a row.
[Answer]
# [J](http://jsoftware.com/), 33 26 bytes
```
((}.~-@#),],.({.~-@#))&.>/
```
[Try it online!](https://tio.run/##NYq7CsJAFET7fMWgIbkrk5u3xS7KomAlFvYpRAxi4weI@fU1GLYYOMM5r7DSfMTOIgdRwc4rFMfr@RREvjoVfm04UOWzsMl0XwaTXA4KYUZJ/ZBKaUvraUzFijpt/PDPksf9@cYIqdmwZceeW@PiM26GmNRo0KJD7xZ0oK2jvNnwAw "J – Try It Online")
A single reduction, where each iteration adds another "J layer". Consider left and right parts like `1 2 3 4 (...) 8 9`:
* `({.~-@#)` From the tail of the left list take as many elements as are in the right list:
```
3 4
```
* `],.` Zip with right list
```
8 3
9 4
```
* `(}.~-@#),` Append the remaining front elements of the left list:
```
1 2
8 3
9 4
```
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 60 bytes
```
f[]=[]
f((a++b):c)=a:f c!b
[]![]=[]
(a:b)!(c:d)=(a++[c]):b!d
```
[Try it online!](https://tio.run/##RYzLbsIwEEX3/oprxMIWw4JCU7Dk7FlUXbC0RpVjiIoQNIqNKr4@tZM@NqM795yZcO/7x7LzlxCHoXVsHYtWKb9YNNoEbb1pEWQjHMsJKm8aLVUwR22L5gJr08jjkE4xwRgcPj6/4GFrOOeZlzX2b1BajDzCorunQ@qhYhGjRl3/VjNke1YK1fXnW8JcSrTIkhBXf77l46vvXt8x/nLOreiJ1rShZyZMyxi4zH9I1R@mzU@clIq2tKMqK9tcUQYv@WA95mJPn5iHbw "Curry (PAKCS) – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~41~~ ~~40~~ ~~29~~ ~~27~~ 26 bytes
```
{((,i#y),x),'(i:#*x)_y}/|:
```
[Try it online!](https://ngn.bitbucket.io/k#eJxFijEKgDAQBPt7xYKFdxKQRI16afyJXcDeQlH/bqKC1Q47E/VgNkuxi9nElLxoUW0y71d9KhGtymzh0KBFFx4KVgjAf8OHj/O+0mPACJ/kAJfuPoVNopxZEaI41brSDYqqGFs=)
Simply aping ovs' APL solution.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 60 bytes
```
a->matrix(if(w=#a,#a[1]+1-w),w,i,j,a[x=min(w-j+1,i)][i+j-x])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY5NDoIwEIWv0sCmDa8LBBET4SJNY2aDKRHSEEzxEJ7ADYkxnsnbWH7Uzcz35r2ZzP1lqTPHkx0fFSuel76S-ftAsmyo78zATcVdERJCUrGOYukEHAxqkBqKxrTcyTqKYYRWJqrloMV640bWnq-cmCyZ7UzbewwmEbCKkxBgSqkYGyRIsdVezmIGPdW_iexnI11xiWTIsUfmI7kfwRs7v5DMPKWXS_r71Dgu_QM)
Returns the one with height ≥ width, e.g. `[[1,2,3,4,5,6], [1,2,3,4], [1,2]] => [[1,2,3], [1,2,4], [1,3,5], [2,4,6]]`.
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 62 bytes
```
a->matrix(#a,w=if(#a,#a[1]+1-#a),i,j,a[x=min(w-j+1,i)][i+j-x])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RU5LDoIwFLxKA5s2TBcVRFzARZrGvE1NiZiGYMBDeAI3JMZ4Jm9j-aibNzNv5k3e_eWpdYejHx-Wlc9LZ2XxrkhWDXWtG3hM6EtnJ4xJK5MoGZOAQw3SQ9m4M-9lnSg4YbRLajkYsbbcyPvTlROTFfOtO3eBRpOImOUkBJjWWmGDFBm2JshZzMRM828i_9nIVrpEchTYIw-RIqwQjF04SGc-pZcm831qHBf8AA)
Returns the one with width ≥ height, e.g. `[[1,2,3,4,5,6], [1,2,3,4], [1,2]] => [[1,2,3,4], [1,2,3,5], [1,2,4,6]]`.
---
In both case, the formula is \$output[i,j]=input[i+\min(w-i-j+1,0),j-\min(w-i-j+1,0)]\$, where \$w\$ is the width of the output matrix.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
⮌A«Fυ⊞κ⊟ι⊞υι»I⮌υ
```
[Try it online!](https://tio.run/##PYy7CsIwFIbn5ikyngPHoVWr0tGpW3ANGUKJNFiakkuX4rPHkMHp@y/wTbP2k9NLzm/nObzMbnwwMK5bioCI/GBNfRJykcIMH@LCbWARB9bUJRG3pXyZ8HaN8NQh/j2pKIacpZQ93elBPV0LO0WypRtd6FxzV9gqpfJpX34 "Charcoal – Try It Online") Link is to verbose version of code. Outputs in Charcoal's default one-element-per-line format. Explanation: Based on my original answer to [Find the J twin](https://codegolf.stackexchange.com/q/245748) which has since been superseded by an alternative approach.
```
⮌A«
```
Loop over the J-brackets in reverse order.
```
Fυ⊞κ⊟ι
```
Append the end elements of the bracket to the existing rows of the predefined empty array.
```
⊞υι
```
Append the remainder of the bracket to the predefined empty array.
```
»I⮌υ
```
Output the reverse of the final array.
[Answer]
# JavaScript (ES6), 69 bytes
A `reduceRight()` with a recursive callback function.
```
a=>a.reduceRight(g=(p,c,i)=>i--?g(p,[...c,a[i].pop()],i):[c,...p],[])
```
[Try it online!](https://tio.run/##fZDNjsIgFIX38xQsIbnF2GqnmlQfwcQtuQuCtWKMEP9ev96CdEaNsjoXvnM4sNc3fTYn6y/Z0W2ablt3ul5oeWo2V9Osbbu78LbmHgxYUS9sli1bmpSU0oBWFqV3nguk07kyQNseQaHojDue3aGRB9fyLVdqDDkUMIEpAotDEIhCsL81GjH175TEJIqCjPjzMRTKITY58iH6aygJmsmPbLVm6iUjIcHUQ28VSqhgBiVVqOhKIPKXyCLo3h5fGCoMaEyMXBUbEEhX5KlFQBNWppLBWCTTw/Da6PlDP66@EXZ3 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python](https://www.python.org), 69 bytes
```
f=lambda L:L and L[-1:1]or[*zip(*zip(L[0],*f(L[1:])),L[0][-len(L):])]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hVHNSsQwEMZrn2LYyyZlumx_rLVQb94KgteYQ5a2GMi2tVsFfRUvC6LvpE_jpGmXxYuX5ptvvp-Bvn_1r-Nj1x4_muLh83lsguz7timM2u8qBWVegmorKEUQ5qHsBuG_6Z5Nn1JsJfoNvWEuOUc7i8DULSs5EXIOe2q6AQzoFrqedlu-GWpVGd3WB8ZzDzR2UIDZHHqjR7aG4gbW3ANLdjO5grt7WHGr9S2_Vz2rX5RBZglOi37Q7UhTwzTnrvj4c5EIEWKEMSZ4KRHcMAEpbY84YwgkDsQklt6ZFdOTedFE_wUQoJmc0t4u_rgXyWSyIqpLMcNrTKkuo3ik3RXt4glbw-nmk9AlOFXmGklGkdHSOkkXWbocNRnjxTQbPOHi59_2Cw)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
ȯWṚUṭḢ;¥Ɱ¥@/ṚU
```
[Try it online!](https://tio.run/##y0rNyan8///E@vCHO2eFPty59uGORdaHlj7auO7QUgd9kNj/w@1HJz3cOeP//@hoMx0LHUsdMx1TIG0UqxNtqGOuY6JjDGYbAWnD2FgA "Jelly – Try It Online") (The TIO comes with a footer that prints the Python repr, to ensure empty arrays are visible; but the bare link works as a function.)
This is very likely to be suboptimal, since I do four (!) reversals of arrays, but I couldn't find a better solution with Jelly's functions. There could also be a shorter way to handle `[]` than `ȯW`, and I might be able to drop the `@`. However, it feels like this challenge *really* happened to hit some weak points in Jelly, as the core of the solutions is tiny.
* The first `Ṛ` (and the `@`) gives us a right-associative reduce. There's no single-byte right-associative reduce in Jelly.
* The `@` also allows us to use `Ḣ`/`Ṫ` to pop stuff from the new J-bracket, since we can only apply monads to the left arg of dyadic chains.
* The last `Ṛ` reverses the order of the output lines. Since things popped from the J-bracket's end go to the bottom, we have build the output backwards. Also, unfortunately, there's no *prepend to* like `ṭ`, so we have to append the "rest" of the J-bracket to the bottom of the matrix (`;` would require a `W`).
* The `U`'s reverse each input and output line. `ȯWṚṭṪṭ¥Ɱ¥@/Ṛ` is *very* close to correct, but unfortunately gets the innermost J-bracket in the wrong order. I'd need to `U` or `W` it somehow to make the output correct.
```
ȯW ȯr Wrap (replace [] with [[]])
Ṛ Ṛeverse order of J-brackets
U Upend (reverse) each J-bracket
/ reduce lines with:
@ (swap args: left=next J-bracket, right=matrix)
Ɱ Ɱap over lines of matrix:
Ḣ remove Ḣead (first) of J-bracket
; append that to matrix line
ṭ ṭack (append) remaining J-bracket to matrix
Ṛ Ṛeverse order of lines
U Upend (reverse) each line
```
[Answer]
# [R](https://www.r-project.org/), ~~84~~ 83 bytes
```
function(j){m[]=unsplit(j,pmin(row(m<-matrix(unlist(j),length(j))),rev(col(m))))
m}
```
[Try it online!](https://tio.run/##HYrLCsIwEADvfoXHXdiCEZ@lfknxIKHRLdlNSRMriN8eo7cZZmJx664pLqtNHBRGfEt/vWSdJ88JRpqEFWJYQLpGbinyC7J6nmtD8oPe06MSIsXhCTZ4kCq4kk9x8N8smHZHJzJbJAt7OtCRjPnxuTWb@pYv "R – Try It Online")
The `unsplit` strategy corresponding to [this answer](https://codegolf.stackexchange.com/a/245749/67312).
-1 thanks to pajonk.
] |
[Question]
[
To quote <http://brainfuck.org/utm.b>:
>
> A tag-system transforms strings over an alphabet `A = {a[1], a[2], ... a[n], a[n+1]}` as follows: a positive integer `m` is chosen, and so is a function `P` that maps each `a[i]` for `1<=i<=n` to a string `P(a[i])` over the alphabet `A`. Now:
>
>
> 1. if the string being transformed has fewer than `m` elements, the whole process stops now.
> 2. `m` elements are removed from the beginning of the string
> 3. Call the first element removed `a[k]`; if `k=n+1` the whole process stops now.
> 4. `P(a[k])` is appended to the string.
> 5. steps 1-5 are repeated.
>
>
>
A more extensive definition is at <https://en.wikipedia.org/wiki/Tag_system>.
We will call `a[n + 1]` the "Halting symbol". Alphabet symbols (symbols in `a`) are ASCII alphanumeric chars.
2-tag systems are those where `m=2`.
The simulator should take two inputs.
1. A definition for `P`, which doubles as a definition for the alphabet. The definition format is given below.
2. An "initial word" to be transformed.
If it halts, it should output the "halting word", the word that is shorter then 2 alphabet symbols long or which has the halting symbol in its front.
## IO
If possible, the input should be read from stdin or passed to a function in the following format (Or something equivalent).
>
> symbol:listofsymbols symbol:listofsymbols symbol:listofsymbols [and so on]
>
> initialword
>
>
>
The `listofsymbols` may be assumed to contain only valid symbols. Any symbol that is not explicitly defined should be treated as the halting symbol.
## The test cases (from Wikipedia) are:
```
input:
a:bc b:a c:aaa
aaaa
output:
a
input:
a:ccbaH b:cca c:cc
baa
output:
Hcccccca
#This test case uses H as the halting symbol, but it might as well be using any alphanumeric ASCII char other than the defined a, b, and c.
```
## Example implementation in Nim:
```
import tables, strutils
proc runTag(P: Table[char, string], inputstr: string): string =
var haltingword: string;
var str = inputstr
while true:
haltingword = str
if str.len() < 2:
break
var cur = str[0]
str.delete(0..1)
if not P.hasKey(cur):
break
str.add(P[cur])
return haltingword
var ruleinput = readLine(stdin).split(' ')
var rules: Table[char, string]
for i in ruleinput:
var pair = i.split(':')
rules[pair[0][0]] = pair[1]
var str = readLine(stdin)
echo runTag(P=rules, inputstr=str)
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 56 bytes
```
f=lambda a,d:a[:len(a)>1]in d and f(a[2:]+d[a[0]],d)or a
```
[Try it online!](https://tio.run/##Zcy9CsMgGIXhPVfh9il16M9SBDvnHsTh6NfQQGpEspTSa7cizdTtHc5z8mt7rOlyzaXWyS54BoaAZgNnlnuSULeTn5NggcRiknBn4w/s4I7ea1ZrEahs3wQyFGPASJpCb7SKvegzwFIAaMhlTptsP82qYYch/tRu0LYdAX@qfgE "Python 3.8 (pre-release) – Try It Online")
-4 thanks to @JonathanAllan
-3 thanks to @Neil
Normal recursive approach
Takes a string and a dictionary of transformations
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[Dg#¬UI.ΔнXQ}Ä#諦¦
```
Inputs in the order `string, map`, where the map are key-value pairs as space-delimited strings.
[Try it online](https://tio.run/##yy9OTMpM/f8/2iVd@dCaUE@9c1Mu7I0IrD3conxux6HVh5YdWvb/f1JiIle0UqJCcnJSooeSjlISkJUIpJOBtFIsAA) or [verify both test cases](https://tio.run/##yy9OTMpM/W/k5ulir6SQmJeioGTveWglkP2obRKQ/T/aJV350JrQQ@v0zk25sDcisPZwi/K5HYdWH1p2aNn/Wp3/iUDAFa2UqJCUrKSjlKSQCCSTFYCCSrFcSVCp5OSkRA@wbHIyRD45WSkWAA).
**Explanation:**
```
[ # Start an infinite loop:
D # Duplicate the current string (or the implicit first input-string in
# the first iteration)
g # Pop and get its length
# # If its length is 1: stop the infinite loop
# (after which the duplicated string is output implicitly as result)
¬ # Else: get the first character (without popping the string)
U # Pop and store this head in variable `X`
I # Push the second input-list of pairs
.Δ # Find the first which is truthy for:
н # Where its first item (the key)
XQ # Equals head `X`
} # Close the find-first (this will result in -1 if none were found)
Ä # Get the absolute value (no-op for a pair of strings)
# # If this is 1: stop the infinite loop
# (after which the string is output implicitly as result)
# # Else: the `#` will act as a 'split-on-spaces' instead
θ # Pop and leave last item (the value)
« # Append it to the string
¦¦ # And remove the first two characters
```
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~68~~ 60 bytes
```
for($a,$d=$args;$a[1]-and($u=$d[$a[0]])){$a=$a+$u|% Su* 2}$a
```
[Try it online!](https://tio.run/##bY9dS4RAFIbv/RXDcAothepWBGHZ2LuijW5E4nicbQ1bt/mgwvW32@hsuwqdC8dXn/O8zL75ElJtRV1H1EjRwyZp@00jfcAQygRQvqkYMLvNI9yVPpgEyszmmzwPghbQEtdgDhdsba7YXQfYd56X@h6zE7LUT1uO3NIsYbwgHtvnX8Qh0SkhctaF4wvy4eTBvxaiAlczEdFcReRMhROtaJzBF7ADu2/kEmkbPRTvgjRrxxIoK9JVs0P5EzKodpWusH7B2ggbxffekqK0bniNHS@FMrW2Xy5hM1@YuhycPa4XRunmw1XmqescZm2IhFJsUB@Vkfg8V8Yn8lkovUAlBnJadyae3P7Edf63nFxh7u68zut/AQ "PowerShell Core – Try It Online")
Takes two parameters:
* the string to process
* a dictionary of char / strings
### Explanations
```
for($a,$d=$args; # Sets the variables $a, the string to process and $d the dictionary of transformations
$a[1]-and # While there is more than 1 character left
($u=$d[$a[0]])){ # And there is a transformation for the first character of $a, store the transformation in $u
$a=$a+$u|% Su* 2} # Concatenates $a and $u and takes all the characters from the second position
$a # return $a when it is 1 char long or we hit a halting symbol
```
-2 bytes thanks to *wasif*!
-6 bytes thanks to *Zaelin Goodman*!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 29 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Feels clunky to me at present.
```
ZḢiȧị¥⁸0ị
;1ịç@ɗ¥⁹ḊḊʋḊȦ$¡ƬẠƇṪ
```
A dyadic Link that accepts the initial word on the left and the production rules (\$P\$) on the right and yields the result.
**[Try it online!](https://tio.run/##y0rNyan8/z/q4Y5FmSeWP9zdfWjpo8YdBkAGl7UhkDy83OHkdJDYzoc7uoDoVDeQOLFM5dDCY2se7lpwrP3hzlX/Dy@PcnvUtMbw0LKoY121//@rJyUmqv@PjlZPVNdRUEpOTkr0UIrVUYhWT4LwEyG8ZAhPKTYWAA "Jelly – Try It Online")** (Each production rule is `[chr, [chr, ...]]`, but a list of these cannot be passed as an argument to a program so the footer translates them from a list of `[[chr], [chr, ...]]`)
### How?
```
ZḢiȧị¥⁸0ị - Link 1, get new characters (or zero): rules, R; character, C
Z - transpose (R)
Ḣ - head -> alphabet
i - first 1-indexed index of (C) in (alphabet) or, when C=Halt, zero
¥⁸ - last two links as a dyad, f(I=that, R)
ị - (I) index into (R)
ȧ - (I) logical AND (that) -> relevant rule or zero
0ị - tail -> new characters or zero
;1ịç@ɗ¥⁹ḊḊʋḊȦ$¡ƬẠƇṪ - Link: initial word, W; rules, R
Ƭ - collect up, starting with W, while no duplicates found with:
¡ - repeat...
$ - ...number of times: last two links as a monad, f(current):
Ḋ - dequeue
Ȧ - has elements and none are zero (found when processing a halt)
ʋ - ...what: last four links as a dyad, f(current, R)
⁹ - right argument, R
¥ - last two links as a dyad, f(current, R)
ɗ - last three links as a dyad, f(current, R)
1 - one
ị - index into (current) -> head character
ç@ - call Link 1 as a dyad, f(R, character)
; - (current) concatenate (that)
Ḋ - dequeue
Ḋ - dequeue
Ƈ - keep those for which:
Ạ - all truthy (are not the result of processing a halt)
Ṫ - tail
```
[Answer]
# [Python 3](https://docs.python.org/3/), 56 bytes
```
def f(a,d):
try:x,y,*z=a;a[:]=*z,*d[x];f(a,d)
except:0
```
[Try it online!](https://tio.run/##bcy/CsMgEMfx/Z7C7VQcCt0M7n2HkOH8ExooqaQOMaHPbhtSEKHj9@7HJ@Z0f87XUnwY2chJeaGBpSXrVWUlN0Md9XowclPS9@vQnRtgYXUhJn0p3uxIqB/TK3F0ztINhUJbL3S0q43iDWTOsvT9ws@MyzQnTgKgMa1rwJajA6ge0T@wfAA "Python 3 – Try It Online")
This function take input as a list of chars, and a dict of char to list of chars. And it returns by modify `a` in-place.
---
And if terminating the function by an exception is allowed, it could be even shorter:
# [Python 3](https://docs.python.org/3/), 40 bytes
```
def f(a,d):x,y,*z=a;a[:]=*z,*d[x];f(a,d)
```
[Try it online!](https://tio.run/##jY27CsMgAEV3v6KbD9y6Gdz7DyHD9REaKKlEB5PQb7cNDuLW8dwL54Q9Pd/rvRTn59vMIB1XWe5SHBoDRjVpcUjhxjwN9S1OnxRUvZaYGLXW4EG5pKYtuNg2pvxDoCsZ/F6Stl1VG/HZ@pBUQIwkbMuaGDghXcPYLtDrcQmbH/gnUL4 "Python 3 – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 27 bytes
```
W#Sb&[[email protected]](/cdn-cgi/l/email-protection) KXWb:b@>2.$1b
```
[Try it here!](https://replit.com/@dloscutoff/pip) Or, here's a 28-byte equivalent in Pip Classic: [Try it online!](https://tio.run/##K8gs@P8/XNnBLkktsc4hSa9Yz1nBOyI8ySrJwc5IT8Uw6f///4kKyclJiR7WSUA60ToZSP5PSkwEAA "Pip – Try It Online")
The tag definitions and the initial word are taken as command-line arguments. Each definition is given as alphabet symbol + space + string, and definitions are separated by any non-space non-alphanumeric symbol. For example:
```
a bc;b a;c aaa
```
This will need to be quoted so the command-line treats it as a single argument.
### Explanation
```
W#Sb&[[email protected]](/cdn-cgi/l/email-protection) KXWb:b@>2.$1b
; a, b are cmdline args; s is space; XW is `\w` (implicit)
W ; While
# ; length of
Sb ; longest suffix of b (the current word)
; is nonzero (i.e. length of b is at least 2)
& ; and
@b ; first character of b
.s ; concatenated to a space
. ; concatenated to the following regex...
XW ; word character: \w
K ; with Kleene star operator: \w*
C ; wrapped in a capture group: (\w*)
a~ ; matches somewhere in a (the definitions)
; do:
b: ; Assign to b
b@>2 ; all but the first two characters of b
.$1 ; concatenated to the contents of the regex capture group
b ; Output the final value of b
```
[Answer]
# [jq](https://stedolan.github.io/jq/), 62 bytes
```
.P as$P|.w|until(length<2//(.[:1]|in($P)|not);.[2:]+$P[.[:1]])
```
Takes input as a JSON object with keys `P` and `w`. The value of `P` is an object whose keys are alphabet symbols and whose values are their associated strings. The value of `w` is the initial word. [Try it online!](https://tio.run/##yyr8/18vQCGxWCWgRq@8pjSvJDNHIyc1L70kw8ZIX19DL9rKMLYmM09DJUCzJi@/RNNaL9rIKlZbJSAaLBWr@f9/tVKAkpVCtVIikFRKSlbSAZIgZiKIlQxmJYLZKSC2Ui2QVQ4VTVSq5ULRnpyclOgBNyE5GWFGcjJCZxJIIwA "jq – Try It Online")
### Explanation
```
.P as $P | Store the P mapping in the variable $P
.w | The rest of the program will manipulate the input word
until ( Until this condition is true...
length < 2 The length of the word is less than 2
// ( or:
.[:1] | The first character of the word
in($P) | Is a key in $P
not) Make that "is NOT a key in $P"
; ...update the word to be the following:
.[2:] + The word minus its first two characters, plus
$P[ the value in $P at this key:
.[:1] The first character in the word
])
When the loop exits, return the final value of the word
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 48 bytes
```
p=>g=a=>p[[x,y,...z]=a,x]&&y?g([...z,...p[x]]):a
```
[Try it online!](https://tio.run/##bY1NCsIwEEb3HqSTwJgDVFK33iFkMY1tUEoTrEiqePbYJP6Ci4HvezO8OdKFJnM6@PN6dPsu9jJ62VhJsvFKBZxRCHHVkjDoqpq3lqkEEvUqaM1risaNkxs6MTjLenYDglpBCwgGNC5haZSSKQmfo@@cfffMON@s/vpM9mH2ptvd2/3afH4UUvztjzs@AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes
```
SθWS⊞υιW∧⊖LθΦυ⁼§θ⁰§κ⁰≔⭆⟦θ⊟ι⟧Φκ›ν¹θθ
```
[Try it online!](https://tio.run/##TU7LCsIwELznK3LcQAS91lPBBwWFgkfxkKZLE4xpm4f69zFBfMxpZ3dmdqQSTo7CpNTYKYZTcNoOMLM1eShtkML/mjHaRq8gcqp/itr2sEHp8IY2YA8HtENQOYNxutMmoCuG7RyF8VCHxvb4hJnTZb5/6LXQAlp7rwcL749HMcE5S9txAs0u37ws3zsUZbScrlh5VTq32RRK@5REBhFVJ0lXCSKrQtPibl4 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as the string to be transformed followed by a list of transformations in the form `symbol:stringofsymbols`. Explanation:
```
Sθ
```
Input the string to be transformed.
```
WS⊞υι
```
Input the list of transformations.
```
W∧⊖LθΦυ⁼§θ⁰§κ⁰
```
Repeat while the string is longer than a single character and the first character is the first character of one of the transformations.
```
≔⭆⟦θ⊟ι⟧Φκ›ν¹θθ
```
Remove the first two characters from the string and the matching transformation and concatenate the result.
] |
[Question]
[
Though there is a prime factorization challenge [and it's here](https://codegolf.meta.stackexchange.com/a/22382/100887), this, I feel, will be a bit more interesting than that one.
To understand this, let's have an example; I will use 5,184 for this. \$5184 = 2^6 \times 3^4\$. However, for this challenge, such a factorization is insufficient - the reason is that 6 and 4 are composite - therefore, we must factorize them too: \$5184 = (2^{2\*3}) \times (3^{2^2})\$. This containes a total of 0 composite numbers, so we are done.
Your task is to prime-factorize a number. However, unlike in [here](https://codegolf.meta.stackexchange.com/a/22382/100887), if you see a composite number in the exponent, you must then factorize this too.
Input will be a number or a string, and output can be a nested array, nested list, or string.
You must use the fewest numbers necessary: 65536 is \$2^{2^{2^2}}\$, not \$ 2^{2 \times 2 \times 2 \times 2}\$ or anything similar - however, \$2^{2^2}\$ and \$2^{2 \times 2}\$ are identical and as such, can be used freely - make of it what you will.
Some example answers to show the format:
5184, 65536 - see above
\$2^{144} = 2^{2^{2^2} \times 3^2}\$ or `[2, [2, [2, 2], [3, [2]]]]`, or `"2^(2^2^2)*(3^2)"`, where the brackets are necessary to separate the terms.
\$5^{125} = 5^{5^3}\$, or `[5, [5, [3]]]`, or `5^5^3` (note, as \$a^{b^c} == a^{(b^c)}\$, the brackets are not necessary.
\$47,258,883 = 3^9 \times 7^4 = 3^{3 \times 3} \times 7^{2 \times 2}\$ or \$3^{3^2} \times 7^{2^2}\$ or `[3, [3, 2], 7, [2, 2]]` or `[3, [3, [2]], 7, [2, [2]]]` or `3^(3 \times 3) \times 7^(2 \times 2)` or `3^3^2 \times 7^2^2`
\$2^{81} = 2^{3^{2 \times 2}}\$ or similar (see above)
\$5^{343} \* 7^{125} = 5^{7^3} \times 7^{5^3}\$ or similar (see above)
And finally, to check your prime factorization technique:
\$2^{2162160} \times 3^{1441440} \times 5^{1081080} = 2^{2^{2^2} \times 3^3 \times 5 \times 7 \times 11 \times 13} \times 3^{2^5 \times 3^2 \times 5 \times 7 \times 11 \times 13} \times 5^{2^3 \times 3^3 \times 5 \times 7 \times 11 \times 13}\$
You may pick any output format and use any non-number or newline separator, and you may include any number of trailing/leading newlines in output, but you must be consistent about your choice and state it in your answer.
As always, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - shortest code wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
¹ÆFṛÇṭ¥Ị?@/€$Ẓ?
```
[Try it online!](https://tio.run/##y0rNyan8f3ji/0M7D7e5Pdw5@3D7w51rDy19uLvL3kH/UdMalYe7Jtn/P9x@dNLDnTNUgAKR//9HmxpamOgomJmaGpvpKBhpaRmaALmmQNrIVEfBxNzI1MLCwhgsY2EIljA2MdYyB8vHAgA "Jelly – Try It Online")
A full program that takes the number and outputs the answer.
This isn't a link because I am using "last link" to refer to itself, so it would break as a link on its own. I fix this for my test suite by making the last link a single atom that calls the next link. For whatever reason, "this link" breaks due to arity related reasons, or something like that. Not sure why.
If Arnauld's return format is acceptable where 1 exponents are returned as `[x, []]`, then:
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
¹ÆF,ß}¥/€$Ẓ?
```
[Try it online!](https://tio.run/##y0rNyan8///QzsNtbjqH59ceWqr/qGmNysNdk@z/H24/OunhzhkqQIHI//@jTQ0tTHQUzExNjc10FIy0tAxNgFxTIG1kqqNgYm5kamFhYQyWsTAESxibGGuZg@VjAQ "Jelly – Try It Online")
```
¹ÆF,ß}¥/€$Ẓ? Main link
? If the input
Ẓ is prime
¹ return the input itself
()( )$ otherwise, (call last two links)
ÆF compute [prime, exponent] pairs
€ for each pair
/ reduce (convert pairs into left and right dyad arguments)
-()¥ (over last two links)
, pair the left argument (the prime) with
ß this link (recurse) called on
} the right argument (the exponent)
```
## Explanation
This one is a bit complex so, here's a shitty hand-drawn breakdown:
[](https://i.stack.imgur.com/hafFl.jpg)
Or, if you enjoy being able to read:
```
¹ÆFṛÇṭ¥Ị?@/€$Ẓ?
? if
Ẓ the input is prime
¹ return the input itself
otherwise
()( )$ [combine last two into a monad]
ÆF compute [prime, exponent] factorization
€ for each pair
/ reduce over (convert pair into left, right arguments for a dyad)
@ the following dyadic relation, with the arguments swapped
? if
Ị the left argument is insignificant (-1 <= ? <= 1) - the left argument is the exponent
ṛ return the right argument (just the prime)
otherwise
--¥ [combine last two into a dyad]
Ç call this link again on the exponent (technically "call last link" due to weird behavior)
ṭ and append that factorization to the prime itself
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ÆF¹ßẒ?€€
```
A monadic Link accepting a positive integer that yields a list (Note that `[]` represents an empty product).
**[Try it online!](https://tio.run/##y0rNyan8//9wm9uhnYfnP9w1yf5R0xog@n@4/eikhztnaEb@/x9taK6jYGpoYaKjYGZqamymo2CkpWVoAuSaAmkjUx0FE3MjUwsLC2OwjIUhWMLYxFjLHCwfCwA "Jelly – Try It Online")**
### How?
```
ÆF¹ßẒ?€€ - Link f: integer
ÆF - prime-factorisation
e.g. 144 -> [[2,4],[3,2]]
(note that 1 -> [])
€ - for each ([prime,exponent] pair in that)
€ - for each (v in [prime,exponent]):
? - if...
Ẓ - ...condition: is prime?
¹ - ...then: no-op
ß - ...else: call this Link with the same arity -> f(v)
```
[Answer]
# [J](http://jsoftware.com/), 34 32 bytes
```
[:(;<@$:)`(<@[)@.(1=])/"1@|:2&p:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o600rG0cVKw0EzRsHKI1HfQ0DG1jNfWVDB1qrIzUCqz@a3KlJmfkK6QpmBpamMDYZqamxmYwjom5kamFhYWxgp@TnkK0sQ4YG8fqKJgDmUY6Ckaxsf8B "J – Try It Online")
Outputs J boxed structure. Eg, `f 1584` is:
```
┌─┬───────┐
│2│┌─┬─┐ │
│ ││2│3│ │
│ │└─┴─┘ │
├─┼───────┤
│3│┌─┬───┐│
│ ││2│┌─┐││
│ ││ ││2│││
│ ││ │└─┘││
│ │└─┴───┘│
└─┴───────┘
```
* `2&p:` is a built in that produces the primes and their exponents as two lists,
like:
```
2&p: 5184
2 3
6 4
```
* `[:(...)/"1@|:` transpose and apply what's in parens to each row, putting it
between the two elements so that `[` and `]` are the left and right args in
what follows...
* `(;<@$:)`(<@[)@.(1=])` If the right arg is 1 (ie, we've reached a prime), put
it in a single box and return `(<@[)`. Otherwise put the left arg in a
left box, and into the right box put the function applied recursively to the right arg `$:`.
[Answer]
# JavaScript (ES6), 73 bytes
Returns nested arrays, where \$k^1\$ is `[k,[]]`.
```
f=(n,k=2,a=[],i,b=i?[...a,k,f(i)]:a)=>k>n?b:n%k?f(n,k+1,b):f(n/k,k,a,-~i)
```
[Try it online!](https://tio.run/##hc69DoIwGIXh3fsw6Rc/avgp1iaF3UEHR8JQkJJa0hogJi7eeoUbkO0MT3Lep3qrqR3Na46cf3QhaEkcWpmgklWNBhtpyopSqtCiJgZqoUAWtnBlI9zelnrlhxgbEMs82oUpjL4GQuvd5IeODr4nl/vtSqd5NK43@kM0iVMA2P0l2XmTsJhnmyhnLM23304J45yvWeEH "JavaScript (Node.js) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Japt suffering from its lack of a prime/exponent built-in again. Uses the empty array if the exponent is `1`.
```
*j ªUk ü Ëâ pßDl
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=KmogqlVrIPwgy%2bIgcN9EbA&input=NTE4NAotUQ)
```
*j ªUk ü Ëâ pßDl :Implicit input of integer U
* :Multiply by
j :Is prime?
ª :Logical OR with
Uk :Prime factors of U
ü :Group by value
Ë :Map each D
â : Deduplicate
p : Push
ß : Recursive call with argument
Dl : Length of D
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╛⌐í₧?uò╗∩¿7d∩í±
```
[Run and debug it](https://staxlang.xyz/#p=bea9a19e3f7595bbefa83764efa1f1&i=65536%0A47258883&m=2)
a pretty straightforward recursion.
-3 from recursive.
[Answer]
# [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), 283 bytes
```
mod F is ex RAT *(sort Nat to N). op __ : N N -> N[id: 1]. op e : N N ->
N[right id: 1]. vars A B C D : N . eq e(A,0)= 1 . op f : N -> N . eq f(A)=
A,2,0 . op _,_,_ : N N N -> N . ceq A,B,0 = A if A < B . ceq A,B,C = D,B,s C
if D := A / B . eq A,B,C = e(B,f(C))(A,s B,0)[owise]. endm
```
The `f` function will evaluate the factorization of its input, a natural number. In the output, the `__` (juxtaposition) operator represents multiplication, and the `e` function represents exponentiation. So the term `e(2, 3) (e(3, 3) (5 (7 (11 13))))` represents \$2^3 \times 3^3 \times 5 \times 7 \times 11 \times 13\$.
### Example Session
```
\||||||||||||||||||/
--- Welcome to Maude ---
/||||||||||||||||||\
Maude 3.1 built: Oct 12 2020 20:12:31
Copyright 1997-2020 SRI International
Thu Jun 3 08:42:33 2021
Maude> set show stats off .
Maude> set show timing off .
Maude> set show command off .
Maude> mod F is ex RAT *(sort Nat to N). op __ : N N -> N[id: 1]. op e : N N ->
> N[right id: 1]. vars A B C D : N . eq e(A,0)= 1 . op f : N -> N . eq f(A)=
> A,2,0 . op _,_,_ : N N N -> N . ceq A,B,0 = A if A < B . ceq A,B,C = D,B,s C
> if D := A / B . eq A,B,C = e(B,f(C))(A,s B,0)[owise]. endm
Maude> red f(5184) .
result N: e(2, 2 3) e(3, e(2, 2))
Maude> red f(65536) .
result N: e(2, e(2, e(2, 2)))
Maude> red f(1081080) .
result N: e(2, 3) (e(3, 3) (5 (7 (11 13))))
Maude> red f(1441440) .
result N: e(2, 5) (e(3, 2) (5 (7 (11 13))))
Maude> red f(2162160) .
result N: e(2, e(2, 2)) (e(3, 3) (5 (7 (11 13))))
Maude> red f(47258883) .
result N: e(3, e(3, 2)) e(7, e(2, 2))
```
### Ungolfed
```
mod F is
ex RAT * (sort Nat to N) .
op __ : N N -> N [id: 1] .
op e : N N -> N [right id: 1] .
vars A B C D : N .
eq e(A, 0) = 1 .
op f : N -> N .
eq f(A) = A, 2, 0 .
op _,_,_ : N N N -> N .
ceq A, B, 0 = A if A < B .
ceq A, B, C = D, B, s C if D := A / B .
eq A, B, C = e(B, f(C)) (A, s B, 0) [owise] .
endm
```
Rather than use the built-in nested list module (`LIST*`), I opted to define my own output operators `__` and `e`. Since Maude allows operators to be declared with identity elements, this saves me having to specify any special rules for 1 (i.e., don't show it).
] |
[Question]
[
Given an positive integer `n` (including 0 if you decide to support it), output all numbers in the *generated* sequence up to the index `n`. For the current test cases of the current challenge numbers are one-indexed. Feel free to submit 0-indexed answers though.
## Base sequence
We start from this sequence (**NOT**, but quite similar to, [A160242](http://oeis.org/A160242)):
```
1, 2, 1, 1, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 2, ...
```
This sequence should be more understandable after formatting:
```
1, 2, 1,
1, 2, 2, 2, 1,
1, 2, 2, 2, 2, 2, 1,
and so on ...
```
However, our point is not to output this sequence. See the below procedure.
## Adding the sequence
Here's an example of adding the sequence. Here, our sequence starts with 0:
```
We collect all intermediate results into the sequence.
The sequence
| Output sequence: [0]
v
0 + 1 = 1 Output sequence: [0, 1]
1 + 2 = 3 Output sequence: [0, 1, 3]
3 + 1 = 4 Output sequence: [0, 1, 3, 4]
4 + 1 = 5 Output sequence: [0, 1, 3, 4, 5]
...
Our generated sequence is therefore
0, 1, 3, 4, ...
```
## Test cases
[Here](https://tio.run/##TVBBboMwELz7FXu0SZoUeqmQ6Csq9YA4uPIirFprYgyhr6drnKD64p2Z9eysx984eHrbNoM99O9ywpuqBfCZEAkavqJUOxEwzoGgXaH3AVawxOINbM81@Zgxv9FkdpzARRsjV9UJkfxx8W5B6Z05E94fcx62TLQOKYmq5v4p6hC/bBw4Ay7aSUvjzFGU8HNkru2EbUpxH6xD@AwzZrcknli1Z2mLonop1fVa/a9PZfdsvEw@PJfLpvwBXGSG99rzMIaPBqriSJQnpTMGSzG1tPWhduqQvwPqn2yWQlXbVr7@AQ) is a sample program outputting the sequence up to the input.
```
3 -> [0, 1, 3]
10 -> [0, 1, 3, 4, 5, 7, 9, 11, 12, 13]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 52 bytes
```
n=p=0
exec"n+=1;r=n-n**.5//1;print p+r;p=r;"*input()
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8@2wNaAK7UiNVkpT9vW0LrINk83T0tLz1Rf39C6oCgzr0ShQLvIusC2yFpJKzOvoLREQ/P/fyMDAA "Python 2 – Try It Online")
**54 bytes**
```
lambda N:[n-~n-n**.5//1-(n+1)**.5//1for n in range(N)]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUcHPKjpPty5PN09LS89UX99QVyNP21ATyknLL1LIU8jMUyhKzEtP1fDTjP1fUJSZV6KQpmFkoPkfAA "Python 2 – Try It Online")
It's a formula!
$$f(n) = 2n+1 - \lfloor \sqrt n\rfloor - \lfloor \sqrt {n+1} \rfloor$$
This can also be split up as
$$f(n) = \sum\_{k \in \{n,n+1\}}\left({k-\lfloor \sqrt k\rfloor}\right)$$
Note that \$k-\lfloor \sqrt k\rfloor\$ is the number of non-squares from \$1\$ to \$k\$ inclusive.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~14~~ 12 bytes
```
0,2+/⍳-⌊∘√∘⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgmG/w10jLT1H/Vu1n3U0/WoY8ajjlkgsnfz/zSg9KPePojKruZD640ftU0E8oKDnIFkiIdn8P80BUOuNAUjIDYGYkMDAA "APL (Dyalog Extended) – Try It Online")
Uses [xnor's formula](https://codegolf.stackexchange.com/a/200957/78410) of
$$
f(n) = \sum\_{k \in \{n,n+1\}}\left({k-\lfloor \sqrt k\rfloor}\right)
$$
### How it works
```
0,2+/⍳-⌊∘√∘⍳
⍳- ⍝ 1..n minus...
⌊∘√∘⍳ ⍝ floor(sqrt(1..n))
2+/ ⍝ Add two consecutive pairs
⍝ giving first n items of the sequence except leading 0
0, ⍝ Prepend the leading 0
```
---
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 14 bytes
```
⊢↑2(∧+/,2××/)⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/x91LXrUNtFI41HHcm19HaPD0w9P19d81Lv5fxpQ@lFvH0RlV/Oh9cZAdUBecJAzkAzx8Az@n6ZgyJWmYATExkBsaAAA "APL (Dyalog Extended) – Try It Online")
Based on the observation that the sequence is the union of all odd numbers and the numbers in the form of \$2n(n+1), n \ge 0\$. Uses `⎕IO←0`.
### How it works
```
⊢↑2(∧+/,2××/)⍳ ⍝ Input: positive integer n
⍳ ⍝ Generate 0..n-1
2( ×/) ⍝ Pairwise product (0×1, 1×2, ..., (n-2)×(n-1))
2× ⍝ Double it
+/, ⍝ Concat with pairwise sum (0+1, 1+2, ..., (n-2)+(n-1))
∧ ⍝ Ascending sort the 2(n-1) numbers in total
⊢↑ ⍝ Take the first n numbers
⍝ For n=1, "overtake" from zero elements, giving single 0
```
[Answer]
# [Haskell](https://www.haskell.org/), 42 bytes
```
(`take`q 4)
q k=0:[1,3..k]++map(k+)(q$k+4)
```
[Try it online!](https://tio.run/##BcFLCoAgEADQfaeYRQvFkn6rwJNU4BBaMhaanb/pvRMLuRjZm5WFfZGczTDJKgOZbl76ZtSaNqUuTIKUFLkmNUm@MNxgID3hfqEGD0PH3@4jHoXbPaUf "Haskell – Try It Online")
Uses a version of [Bubbler's observation](https://codegolf.stackexchange.com/a/200956/20260) that the sequence alternates runs of consecutive odd numbers with an even number directly in between.
---
# [Haskell](https://www.haskell.org/), 43 bytes
```
(`take`scanl(+)0(q[2]))
q r=1:r++1:q(2:2:r)
```
[Try it online!](https://tio.run/##BcFLCoAgEADQfaeYRQtFAnUpeJIKHERLMvF3/qb3bhxPyJmiPYi5iU9ww2PJTHDJ2q5PzpcG3SrThVCmMW206ZxeTAUs1J7KhBUiKEmfjxmvQZuv9Qc "Haskell – Try It Online")
Generates an infinite list of 1's and 2's, take the cumulative sums, and truncates to the input length.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÝDtï-ü+
```
Port of [*@Bubbler*'s top APL answer](https://codegolf.stackexchange.com/a/200956/52210), which uses the same formula as [*@xnor*'s Python answer](https://codegolf.stackexchange.com/a/200957/52210):
$$f(n) = \sum\_{k \in \{n,n+1\}}\left({k-\lfloor \sqrt k\rfloor}\right)$$
-2 bytes thanks to *@Grimmy*.
[Try it online.](https://tio.run/##yy9OTMpM/f//8FyXksPrdQ/v0f7/39DAAAA)
**Explanation:**
```
Ý # Push a list in the range [0, (implicit) input-integer]
D # Duplicate this list
t # Take the square-root of each value
ï # Cast it to an integer to floor it
- # Subtract the values at the same positions from one another
ü # For each overlapping pair:
+ # Add them together
# (after which the result is output implicitly)
```
---
Implementing the steps described in the challenge description would be **13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** instead:
```
2∞и1δš€û˜.¥I£
```
[Try it online.](https://tio.run/##ASUA2v9vc2FiaWX//zLiiJ7QuDHOtMWh4oKsw7vLnC7CpUnCo///MTAw)
Or `2∞и1δš€û` could alternatively be `ÅÉÅ21δ.ø`.
[Try it online.](https://tio.run/##ASIA3f9vc2FiaWX//8OFw4nDhTIxzrQuw7jLnC7CpUnCo///MTAw)
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,...]
2 и # Repeat 2 that many times as list: [[2],[2,2],[2,2,2],...]
δ # For each inner list:
1 š # Prepend a leading 1: [[1,2],[1,2,2],[1,2,2,2],...]
€ # For each inner list:
û # Palindromize it: [[1,2,1],[1,2,2,2,1],[1,2,2,2,2,2,1],...]
˜ # Flatten the list of 1s and 2s: [1,2,1,1,2,2,2,1,1,2,2,2,2,2,1,...]
.¥ # Undelta it (cumulative sum with 0 automatically prepended):
# [0,1,3,4,5,7,9,11,12,13,15,17,19,21,23,24,25,...]
I£ # Leave the first input amount of items from this infinite list
# (after which the result is output implicitly)
ÅÉ # Push a list of odd numbers below or equal to the (implicit) input
# i.e. 6 → [1,3,5]
Å2 # Repeat a list of 2s for each inner value: [[2],[2,2,2],[2,2,2,2,2]]
δ # For each inner list:
1 .ø # Surround it with 1s: [[1,2,1],[1,2,2,2,1],[1,2,2,2,2,2,1]]
# (The rest is the same as above)
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, ~~33~~ 29 bytes
```
seq -f %0.fddv-r1-dv-+p $1|dc
```
[Try it online!](https://tio.run/##S0oszvj/vzi1UEE3TUHVQC8tJaVMt8hQF0hqFyioGNakJP///9/QAAA "Bash – Try It Online")
This is another solution using [@xnor's nice formula](https://codegolf.stackexchange.com/a/200957/78410).
[Answer]
# JavaScript (ES7), 40 bytes
This is using the closed-form formula described below.
But because we're asked to output the \$n\$ first terms of the sequence, we need 19 bytes of wrapping code. :'-(
```
f=n=>n?[...f(n-1),(n-=n**.5)*2|n%1>0]:[]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i7PPlpPTy9NI0/XUFMHSNrmaWnpmWpqGdXkqRraGcRaRcf@T87PK87PSdXLyU/XSNMwMtDU/A8A "JavaScript (Node.js) – Try It Online")
### 21 bytes (n-th term, 1-indexed)
```
n=>(n-=n**.5)*2|n%1>0
```
[Try it online!](https://tio.run/##DcoxCoQwEAXQ3lNM4cJMRFHByo1nMaiRXeSP6GITc/as1Wve113unI7P/iuh85K8TbADo7QwpurEtDdezVAnrweDLDU9gd7U1Y9FIRQyoklx6rZUm648Os4Dojw1D54hcZQ@i@kP "JavaScript (Node.js) – Try It Online")
Given \$n\ge0\$, we compute:
$$d(n)=2\cdot\lfloor n-\sqrt{n}\rfloor\\
f(n)=\cases{
d(n)&\text{if $n$ is a square}\\
d(n)+1&\text{otherwise}
}$$
The JS implementation uses a bitwise OR which implicitly floors \$n-\sqrt{n}\$ *after* it has been multiplied by \$2\$. But this leads to the same result.
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=sum -n`, 39 bytes
Shoutout to @xnor for the formula. This is essentially a port of [his Python answer.](https://codegolf.stackexchange.com/a/200957/72767)
```
map{say$a+($n=$_-int$_**.5);$a=$n}1..$_
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saC6OLFSJVFbQyXPViVeNzOvRCVeS0vPVNNaJdFWJa/WUE9PJf7/f0ODf/kFJZn5ecX/dX1N9QwMDf7r5uUAAA "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
R_ƽ$+ƝŻ
```
[Try it online!](https://tio.run/##y0rNyan8/z8o/nDbob0q2sfmHt39//9/QwMA "Jelly – Try It Online")
-5 bytes by porting [xnor's formula](https://codegolf.stackexchange.com/a/200957/68942) (thanks Bubbler!)
-1 byte thanks to Nick Kennedy
# Explanation
Uses xnor's formula of:
$$f(n) = \sum\_{k \in \{n,n+1\}}\left({k-\lfloor \sqrt k\rfloor}\right)$$
```
R_ƽ$+ƝŻ Main Link
R range
_ $ subtract
ƽ square root floored (of each element)
+Ɲ add adjacent pairs together
Ż prepend 0
```
Without xnor's formula, I have 10 bytes
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
RƲẸ$Ɲ¬‘ÄŻ
```
[Try it online!](https://tio.run/##ASAA3/9qZWxsef//UsOGwrLhurgkxp3CrOKAmMOExbv///8xMA "Jelly – Try It Online")
(range; for each pair of adjacent elements, check if either of them is square; logical NOT that and add one (gets the original 1,2 sequence), cumulative sum, prepend 0)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
ENŲ_©O=®
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f1e9w66FN8YdW@tseWvf/v7EBAA "05AB1E – Try It Online")
```
E # loop for N from 1 to input:
NŲ # is N a square?
_ # logical not (0 if N is a square, 1 if not)
© # save in the register without popping
O # sum all numbers on the stack
= # print without popping
® # push the content of the register
```
[Answer]
# [Python 3](https://docs.python.org/3/), 93 bytes
```
f=lambda n,x=0:(n-x)*[1]and[sum([j for i in range(1,n,2)for j in[1]+[2]*i+[1]][:x])]+f(n,x+1)
```
[Try it online!](https://tio.run/##NYxBCoMwEADvfcUed00KRm@CL1n2ELFpI3WVaCG@Pk0PvQ3DMPt1vjbtSwnj26/T7EFtHtsB9Z6pYSdeZz4@K/ICYUsQISokr88HOqu2o59cqqyp4U6aaCoJD1lITMB6M47KnqKeGLAnuv3ZtUTlCw "Python 3 – Try It Online")
*-21 bytes thanks to @Bubbler*
[Answer]
# [Python 2](https://docs.python.org/2/), 71 bytes
```
f=lambda n,k=0,w=3:n*[n]and[0]+[x-~(k>1)for x in f(n-1,~-k%w,w+2*0**k)]
```
[Try it online!](https://tio.run/##DclBCoAgEADAr3gJcltB6xbYR8SDEVJYq0RgXfr61lynPNeaqWeOdg/HvARBmKzGaoeRwJEPtDjtO3ert02TkTGf4hYbidiSMviq1FSsXQ8aIEnP5dzo@tNoyR8 "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
IEEN…±⊕ι⊕ιL⁻↔ιXι²
```
[Try it online!](https://tio.run/##XYzBCsIwEER/pccNVFCvnsSTYEvxD7ZxSQPppiSb@vnr0qMDc3mPGb9g8RmT6lQiCzywCgy4HX3y1mRs60wFXN@9kQPBSAGFzPlCK7HQB6Iz@weMvIiDLDBEbhXuc82p2TCamfLXLmPfXd2Rm@rlrKc9/QA "Charcoal – Try It Online") Link is to verbose version of code. Based on @xnor's formula. Explanation:
```
N Input as a number `m`
E Map over implicit range `0`..`m-1`
ι ι Current index `n`
⊕ ⊕ Incremented (i.e. `1`..`m`)
± Negated
… Exclusive range (i.e. `-n` .. `n-1`)
E Map over list of ranges
ι ι Current range
X ² Squares of values
↔ Absolute values
⁻ Remove the squares
L Take the length
I Cast to string
Implicitly print
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/) `-lm`, ~~72~~ \$\cdots\$ ~~61~~ 60 bytes
Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
s;i;f(n){for(s=i=0;i<n;)printf("%d ",i-~i-s-(s=sqrt(++i)));}
```
[Try it online!](https://tio.run/##DYpBCoMwEEX3nmIQCjM6wVhbSkk9jKREBjRtE3dij950HvzN@8@b2ftSshMXMNIeXgnzKKN18oiO3kniFrA@PaFmMV8x2eifP2nDthUickfRBNZJItJegRKwt@SgayxDzzAwXBiuDDeGuxpV/Vk3QNNVR/n5sExzLmZZ/w "C (gcc) – Try It Online")
Uses [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [formula](https://codegolf.stackexchange.com/a/200957/78410).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 81 bytes
```
r,c,i;f(n){for(r=c=0;~n;c++)for(i=++c;i--+2&&n--;r+=c+~i&&i+2)printf("%d ",r++);}
```
Some magic hackery used.
*-4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!*
[Try it online!](https://tio.run/##FYtBCsMgEADvvkIsFWVjCYGeNvYvZa3tQqvBJL2E5OvWznGYIfckqrV01DFGk@wWczHFk@/xSEgA9i/YAxCyczBonZzDAp7gYK0ZBjsVTks06hyk6kpbcK8nTvRew0OO8xI4X143IVolP3dO5ps5WLEJ2Yjm2luU07rMRimLYq8/ "C (gcc) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~52~~ 50 bytes
```
->n,*w{n.times{|x|w+=[x,x*x,x*x];p w.sort[x+1]+x}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5PR6u8Ok@vJDM3tbi6pqKmXNs2ukKnQguMY60LFMr1ivOLSqIrtA1jtStqa/@nRRuaxv4HAA "Ruby – Try It Online")
### How:
The difference between n and f(n) shows an interesting pattern:
```
n f f-n
----------
0 0 0
1 1 0
2 3 1
3 4 1
4 5 1
5 7 2
6 9 3
7 11 4
8 12 4
9 13 4
10 15 5
11 17 6
12 19 7
13 21 8
14 23 9
15 24 9
16 25 9
17 27 10
18 29 11
19 31 12
```
In the rightmost sequence, every non-square number occurs only once, and every square number appears three times (except 0 which occurs only twice). I can build the required sequence as the sum of n and (f-n).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ż_ƽ$+Ɲ
```
A monadic Link accepting a positive integer, `n`, which yields a list of the first `n` entries.
**[Try it online!](https://tio.run/##y0rNyan8///o7vjDbYf2qmgfm/v//39jUwA "Jelly – Try It Online")**
### How?
Application of xnor's pair-wise addition formula \$f(n) = \sum\_{k \in \{n,n+1\}}\left({k-\lfloor \sqrt k\rfloor}\right)\$
```
Ż_ƽ$+Ɲ - integer, n e.g. 10
Ż - zero range [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
$ - last two links as a monad:
ƽ - integer square-root (vectorises) [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3]
_ - subtract (vectorises) [0, 0, 1, 2, 2, 3, 4, 5, 6, 6, 7]
Ɲ - for neighbours:
+ - add [0, 1, 3, 4, 5, 7, 9, 11,12,13]
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
ΘẊ+mṠ-o⌊√ḣ
```
[Try it online!](https://tio.run/##AR8A4P9odXNr///OmOG6iitt4bmgLW/ijIriiJrhuKP///81 "Husk – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Another port of [xnor's formula](https://codegolf.stackexchange.com/a/200957/58974).
```
ôÈ-¬fÃä+
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9MgtrGbD5Cs&input=MTAw)
```
ôÈ-¬fÃä+ :Implicit input of integer
ô :Range [0,input]
È- :Map & subtract
¬ : Square root
f : Floored
à :End map
ä+ :Consecutive pairs reduced by addition
```
] |
[Question]
[
[This question](https://codereview.stackexchange.com/questions/229152/algorithm-for-competing-cells-of-0s-and-1s) just trended over on code-review and I figured you might like it adapted as a codegolf challenge:
You are given a non-empty list of x houses represented as booleans. Each day, the houses compete with adjacent ones. 1 represents an "active" house and 0 represents an "inactive" house. If the neighbors on both sides of a given house are either both active or both inactive, then that house becomes inactive on the next day. Otherwise it becomes active.
```
def get_state_as_pos(thelist, pos):
if thelist[pos-1] == thelist[pos+1]:
return 0
else:
return 1
```
For example, if we had a group of neighbors [0, 1, 0] then the house at [1] would become 0 since both the house to its left and right are both inactive. The cells at both ends check the opposite side as well, so the neighbors at index 0 are at index `length-1` and indexn1 and vice versa.
Even after updating the cell, you have to consider its prior state when updating the others so that the state information of each cell is updated simultaneously.
The function takes the array of states and a number of steps and should output the state of the houses after the given number of steps.
```
input: states = [1, 0, 0, 0, 0, 1, 0, 0], steps = 1
output should be [0, 1, 0, 0, 1, 0, 1, 1]
input: states = [1, 1, 1, 0, 1, 1, 1, 1], steps = 2
intermediate state= [0, 0, 1, 0, 1, 0, 0, 0]
output should be [0, 1, 0, 0, 0, 1, 0, 0]
input: states = [1], steps=1
output: states= [0]
```
Take the list and steps however you like and output the resulting list via [default I/O](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Standard loopholes are forbidden. This is codegolf, shortest answer in bytes wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ ~~13~~ ~~10~~ ~~9~~ 6 bytes
*Based on [Shaggy's Japt solution](https://codegolf.stackexchange.com/a/192976/6484)*
```
F©Á®À^
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f7dDKw42H1h1uiPv/34gr2lBHAYIMYAwQigUA "05AB1E – Try It Online")
```
F # repeat n times:
©Á # the list, rotated right
®À # the list, rotated left
^ # xor (vectorizes)
```
---
Unnecessarily clever 9-byte solution:
```
F¥DO.øü+É
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f7dBSF3@9wzsO79E@3Pn/vxFXtKGOAgQZwBggFAsA "05AB1E – Try It Online")
```
F # repeat n times:
# (examples given for the initial state [0, 1, 1, 0, 1])
¥ # deltas of the list ([1, 0, -1, 1])
D # duplicate
O # sum (1)
.ø # surround ([1, 1, 0, -1, 1, 1])
ü+ # pairwise addition ([2, 1, -1, 0, 2])
É # modulo 2 ([0, 1, 1, 0, 0])
```
[Answer]
# [Python 2](https://docs.python.org/2/), 72 bytes
```
f=lambda s,n:n and f([a^b for a,b in zip(s[-1:]+s,s[1:]+s[:1])],n-1)or s
```
[Try it online!](https://tio.run/##TYvBCoMwEETvfsUeDV3B9Rjol4QIGyQ00K7B9dL@fIzSlsDAzDBv8nt/rDKVEu9PfoWFQVGsAMsCsXc8B4jrBowBksAn5V7dQNbfFNVd7ix541EGMhXUkrck@/klhLHRt/qaTNdC9Nv@mSo0tdB1Kgc "Python 2 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes
```
CellularAutomaton[90,#,{{#2}}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zk1J6c0J7HIsbQkHyianxdtaaCjrFNdrWxUWxur9j@gKDOvJFpZ1y7NwUE5Vk3foZqrutpQR8EACUG5tUBWrQ5E2hAmCmcDpRSMINK1Ooa1XLX/AQ "Wolfram Language (Mathematica) – Try It Online")
`CellularAutomaton` assumes the input list is cyclic.
[Answer]
# JavaScript (ES6), 57 bytes
Takes input as `(steps)(array)`.
```
s=>g=a=>s--?g(a.map(_=>a[~-i++%l]^a[i%l],i=l=a.length)):a
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1i7dNtHWrlhX1z5dI1EvN7FAI97WLjG6TjdTW1s1JzYuMToTSOlk2ubYJurlpOall2Roalol/k/OzyvOz0nVy8lP10jTMNTUiDbUUTBAQlBurKYmF1a1hjAlcLYhplojfGr/AwA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-mh`](https://codegolf.meta.stackexchange.com/a/14339/), ~~11~~ ~~10~~ 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
I/O of states as singleton 2D arrays.
```
VÇí^Zé2)é
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW1o&code=VsftXlrpMinp&input=MgpbWzEsMSwxLDAsMSwxLDEsMV1dCi1R)
```
VÇí^Zé2)é :Implicit input of integer U=steps & array V=[states]
VÇ :Modify the last element Z in V
í :Interleave with
Zé2 : Z rotated right twice and
^ : Reduce each pair by XOR
) :End interleave
é :Rotate right once
:Repeat U times and implicitly output V
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 51 bytes
```
1A`
"$+"{`(.).*(.)
$2$&$1
(.)(?=.(\1|(.)))?
$#2*$#3
```
[Try it online!](https://tio.run/##K0otycxLNPz/39AxgUtJRVupOkFDT1NPC0hwqRipqKkYcgGZGva2ehoxhjVApqamPZeKspGWirLx//9GXIaGhgZAbAgA "Retina – Try It Online") Takes the number of steps on the first line and a string of `0`s and `1`s on the second line. Explanation:
```
1A`
```
Delete the number of steps from the input.
```
"$+"{
```
Repeat that number times.
```
`(.).*(.)
$2$&$1
```
Copy the end digits to the other ends to simulate wrapping.
```
(.)(?=.(\1|(.)))?
$#2*$#3
```
Perform the XOR operation.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 12 [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")
Full program. Prompts stdin for array of states and then for number of steps. Prints to stdout.
```
1(⌽≠⌽⍢⌽)⍣⎕⊢⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94L@hxqOevY86F4DI3kVAUvNR7@JHfVMfdS0CkiA1/xXAoIDLUMEACsEsLkMuhIwhWAxCG3IZwWV0DLkMAQ "APL (Dyalog Extended) – Try It Online")
`⎕` get evaluated input from console (array of states)
`⊢` on that, apply…
`1(`…`)⍣⎕` the following tacit function, input number of times, each time with `1` as left argument:
`⌽⍢⌽` rotate the right argument 1 step left while reversed (i.e. rotate one step right)
`⌽≠` XOR with the argument rotated 1 step left
[Answer]
# [Python 2](https://docs.python.org/2/), 71 bytes
```
f=lambda a,n:n and f([a[i-1]^(a+a)[i+1]for i in range(len(a))],n-1)or a
```
[Try it online!](https://tio.run/##XY3BCsJADETvfkWOG5qC6VHwS5YIkXY1UNOy9OLXbyusuAghZJh5k/W9PRcfSknXWV/3UUHJLw7qI6QQNVrPcgvaKUbrWNKSwcAcsvpjCvPkQRGFvGc8LC1rNt8@KBOcm6lSiJHiT3@PY7OcWphbqwZo@IOb4gauT6Ts "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ṙØ+^/$¡
```
[Try it online!](https://tio.run/##y0rNyan8///hzpmHZ2jH6ascWvj///9oQx0FCDKAMUAo9r8RAA "Jelly – Try It Online")
Full program. A singleton output is represented as `x` instead of `[x]`.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 24 bytes
```
AQVH=Gmxhded.:+eG+GhG3;G
```
[Try it online!](https://tio.run/##K6gsyfj/3zEwzMPWPbciIyU1Rc9KO9Vd2z3D3dja/f//aEMdBQgygDFAKFZHwQgA "Pyth – Try It Online")
```
AQ # G, H = Q[0], Q[1] # Q = input in the form [[states],steps]
VH # for i in range(H):
=G # G =
m # map(lambda d: )
xhded # d[0] ^ d[-1],
.: 3 # substrings( , length=3)
+eG+GhG # G[-1] + G + G[0]
; # (end for loop)
G # print G
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 59 bytes
```
->r,n{n.times{r=r.rotate.zip(r.rotate -1).map{|a,b|a^b}};r}
```
[Try it online!](https://tio.run/##TU7LCsIwELz7FUuhoJIG61XSHwlRUkmxh9aQ3R40ybfHtLUi7GNmZ5ldN7Wv1IlUNY6NfuTUDwa9E467J2ky/N3b/Uagqg980NYHzdqgr22MFxcTGSQEAVLKmsHpL75UZZRzkett@sOzdF7lZVHtFkNu9P0BPlAAO2X/AucX5jslMkAydsUgRJNbASXIIzHoclWcnjdUMX0A "Ruby – Try It Online")
] |
[Question]
[
Look at these photographs of natural scenes, with one of the RGB channels taken out of them:
[](https://i.stack.imgur.com/7eurk.jpg)
Source (with red): <https://en.wikipedia.org/wiki/File:Altja_j%C3%B5gi_Lahemaal.jpg>
[](https://i.stack.imgur.com/8aHSE.jpg)
Source (with green): <https://commons.wikimedia.org/wiki/File:2007_mather-lake_hg.jpg>
[](https://i.stack.imgur.com/hX8No.jpg)
Source (with blue): <https://commons.wikimedia.org/wiki/File:Fox_01.jpg>
Even without one of the channels, you can probably make out what colours certain things are supposed to be, or at least have a good idea if a reconstruction of the missing channel is accurate.
For example, here is the first picture with a red channel added back onto it which is just random noise:
[](https://i.stack.imgur.com/ZSOvN.jpg)
This image clearly isn't an accurate reconstruction of the red channel. This is because nature photos generally don't use the entire RGB spectrum, but only a subset of "natural-looking colours". Also, the shades of red will follow certain gradients that correlate with the others.
---
Your task is to build a program that will take a photograph that's had one channel removed and attempt to approximate the original image as closely as possible by reconstructing what it believes is the missing channel.
Your program will be scored on how closely the missing channel matches with the channel of the original image, by counting the percentage of pixels whose values of that channel are within ±15 (inclusive) of the actual value in the original image (where the values range from 0 to 255 as in a standard 8-bit colour channel).
The test cases that your program will be scored on can be found [here](https://github.com/joezeng/pcg-se-files/raw/master/photocases.zip) (9.04 MB zip file, 6 images). Currently it only contains the three example images above and their originals, but I'll add a few more later to make the full suite once I've done them.
Each image is scaled down and cropped to 1024 x 768, so they will have the same weight in your score. The program that can predict the most pixels within the given tolerance wins.
[Answer]
# Python 3 + scikit-image
Simply sets the color of the missing channel to the average of the other two.
```
import sys
from skimage import io, color
im = io.imread(sys.argv[1])
h, w, c = im.shape
removed_channel_options = {0, 1, 2}
for y in range(h):
for x in range(w):
if len(removed_channel_options) == 1: break
removed_channel_options -= {i for i, c in enumerate(im[y][x]) if c > 0}
removed_channel = removed_channel_options.pop()
for y in range(h):
for x in range(w):
p = [float(c) / 255 for c in im[y][x][:3]]
p = [sum(p)/2 if i == removed_channel else p[i]
for i in range(3)]
im[y][x] = [int(c*255) for c in p] + [255]*(c == 4)
io.imsave(sys.argv[2], im)
```
And the restored images:



[Answer]
# Lua, Love2D
Just sets the missing channel to the smaller of the two remaining channels.
```
local inp = love.image.newImageData(arg[2])
local channels = {1, 2, 3}
local removed = nil
local removed_options = {true,true,true}
inp:mapPixel(function(x,y,r,g,b)
local o = {r,g,b}
for k,v in pairs(o) do
if v > 0 then
removed_options[k] = false
end
end
return r,g,b
end)
for k,v in pairs(removed_options) do
if v then
removed = k
break
end
end
inp:mapPixel(function(x,y,r,g,b)
local o = {r,g,b}
o[removed] = math.min(o[removed%3+1], o[(removed+1)%3 + 1])
return unpack(o)
end)
inp:encode('png', IMAGE:gsub("%.png", "2.png"))
```
Takes a filename as an argument on the command line.
[](https://i.stack.imgur.com/b4aHd.jpg)
[](https://i.stack.imgur.com/OZ0Bl.jpg)
[](https://i.stack.imgur.com/cbovn.jpg)
## Bonus
I tried setting the missing channel to 255-(a+b), clamping the value. As to "fill in the gap". The results are useless but glorious.
[](https://i.stack.imgur.com/rGCBi.jpg)
[](https://i.stack.imgur.com/SoicY.jpg)
[](https://i.stack.imgur.com/ACzd8.jpg)
And with 255-(a+b)/2
[](https://i.stack.imgur.com/OheGq.jpg)
[](https://i.stack.imgur.com/8sqkr.jpg)
[](https://i.stack.imgur.com/xbJaN.jpg)
[Answer]
A little late to the party but I created a [ControlNet - Channels RGB](https://huggingface.co/GeroldMeisinger/controlnet-channels) machine learning model which was trained on 400K RGB images where each of them have one channel missing in order to restore a missing channel from an image. It uses Stable Diffusion 1.5 generative image AI to infer an image. You can either use the inference as is, or only use the missing channel from the inference (which doesn't look to good unfortunately). I also created an accompanying [space which lets you replace the channel from an inference image](https://huggingface.co/spaces/GeroldMeisinger/channels). Original post is here: <https://github.com/lllyasviel/ControlNet/discussions/567> . There are some disadvantages however:
1. it changes the image content a bit,
2. Stable Diffusion 1 works best on images with 512 x n\*64.
3. you have to create a prompt for the image, and
4. you have to cherry-pick one of the generations.
**Results**
first is inference only, second is recomposing the missing channel from inference, the image on the right is ground truth with a missing channel
**Forest**
[](https://i.stack.imgur.com/kmoyT.jpg)
[](https://i.stack.imgur.com/U6obK.jpg)
**Glacier**
[](https://i.stack.imgur.com/1Jt0n.jpg)
[](https://i.stack.imgur.com/xp5rD.jpg)
**Fox**
[](https://i.stack.imgur.com/N2kgk.jpg)
[](https://i.stack.imgur.com/4okHg.jpg)
] |
[Question]
[
In statistics, sometimes it's useful to know whether two data samples come from the same underlying distribution. One way to do this is to use the two-sample [Kolmogorov-Smirnov test](https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test).
Your task will be to write a program that reads in two unsorted nonnegative integer arrays and calculates the main statistic used in the test.
---
Given an array `A` and a real number `x`, define the distribution function `F` by
```
F(A,x) = (#number of elements in A less than or equal to x)/(#number of elements in A)
```
Given two arrays `A1` and `A2`, define
```
D(x) = |F(A1, x) - F(A2, x)|
```
The two-sample Kolmogorov-Smirnov statistic is the maximum value of `D` over all real `x`.
## Example
```
A1 = [1, 2, 1, 4, 3, 6]
A2 = [3, 4, 5, 4]
```
Then:
```
D(1) = |2/6 - 0| = 1/3
D(2) = |3/6 - 0| = 1/2
D(3) = |4/6 - 1/4| = 5/12
D(4) = |5/6 - 3/4| = 1/12
D(5) = |5/6 - 4/4| = 1/6
D(6) = |6/6 - 4/4| = 0
```
The KS-statistic for the two arrays is `1/2`, the maximum value of `D`.
## Test cases
```
[0] [0] -> 0.0
[0] [1] -> 1.0
[1, 2, 3, 4, 5] [2, 3, 4, 5, 6] -> 0.2
[3, 3, 3, 3, 3] [5, 4, 3, 2, 1] -> 0.4
[1, 2, 1, 4, 3, 6] [3, 4, 5, 4] -> 0.5
[8, 9, 9, 5, 5, 0, 3] [4, 9, 0, 5, 5, 0, 4, 6, 9, 10, 4, 0, 9] -> 0.175824
[2, 10, 10, 10, 1, 6, 7, 2, 10, 4, 7] [7, 7, 9, 9, 6, 6, 5, 2, 7, 2, 8] -> 0.363636
```
## Rules
* You may write a function or a full program. Input may be via STDIN or function argument, and output may be via STDOUT or return value.
* You may assume any unambiguous list or string format for the input, as long as it is consistent for both arrays
* On the off-chance that your language has a builtin for this, you may not use it.
* Answers need to be correct to at least 3 significant figures
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the program in the fewest bytes wins
[Answer]
## APL (~~29~~ 24)
(Thanks to Zgarb for the extra inspiration.)
```
{⌈/|-⌿⍺⍵∘.(+/≤÷(⍴⊣))∊⍺⍵}
```
This is a function that takes the arrays as its left and right arguments.
```
8 9 9 5 5 0 3 {⌈/|-⌿⍺⍵∘.(+/≤÷(⍴⊣))∊⍺⍵} 4 9 0 5 5 0 4 6 9 10 4 0 9
0.1758241758
```
Explanation:
```
{⌈/ maximum of
| the absolute value of
-⌿ the difference between
⍺⍵∘.( )∊⍺⍵ for both arrays, and each element in both arrays
+/≤ the amount of items in that array ≤ the element
÷ divided by
(⍴⊣) the length of that array
}
```
[Answer]
# J - 39
I'm sure can be shorten much more
```
f=:+/@|:@(>:/)%(]#)
>./@:|@((,f])-(,f[))
```
Usage
```
2 10 10 10 1 6 7 2 10 4 7 >./@:|@((,f])-(,f[)) 7 7 9 9 6 6 5 2 7 2 8
0.363636
```
[Answer]
# JavaScript (ES6) 99 ~~119 128~~
More or less straightforward JavaScript implementation~~, probably more golfable~~.
In the F function I use > instead of <=, as abs(F(a)-F(b)) === abs((1-F(a))-(1-F(b)))
No more function definition as default parameer in this last edit.
As I said, it's straightforward. The F function is the F function, the D function is the unnamed function used in line 2. It's evaluated using .map for each value present in the two arrays, as the max value for `all` reals must be one of these. At last, the spread operator (...) is used to pass the D values array as a parameter list to the max function.
```
K=(a,b)=>Math.max(...a.concat(b).map(x=>
Math.abs((F=a=>a.filter(v=>v>x).length/a.length)(a)-F(b))
))
```
**Test** In FireFox/FireBug console
```
;[[[0],[0]], [[0],[1]],
[[1, 2, 3, 4, 5],[2, 3, 4, 5, 6]],
[[3, 3, 3, 3, 3],[5, 4, 3, 2, 1]],
[[1, 2, 1, 4, 3, 6],[3, 4, 5, 4]],
[[8, 9, 9, 5, 5, 0, 3],[4, 9, 0, 5, 5, 0, 4, 6, 9, 10, 4, 0, 9]],
[[2, 10, 10, 10, 1, 6, 7, 2, 10, 4, 7],[7, 7, 9, 9, 6, 6, 5, 2, 7, 2, 8]]]
.forEach(x=>console.log(x[0],x[1],K(x[0],x[1]).toFixed(6)))
```
*Output*
```
[0] [0] 0.000000
[0] [1] 1.000000
[1, 2, 3, 4, 5] [2, 3, 4, 5, 6] 0.200000
[3, 3, 3, 3, 3] [5, 4, 3, 2, 1] 0.400000
[1, 2, 1, 4, 3, 6] [3, 4, 5, 4] 0.500000
[8, 9, 9, 5, 5, 0, 3] [4, 9, 0, 5, 5, 0, 4, 6, 9, 10, 4, 0, 9] 0.175824
[2, 10, 10, 10, 1, 6, 7, 2, 10, 4, 7] [7, 7, 9, 9, 6, 6, 5, 2, 7, 2, 8] 0.363636
```
[Answer]
# Python 3, ~~132~~ ~~108~~ ~~95~~ 88
```
f=lambda a,x:sum(n>x for n in a)/len(a)
g=lambda a,b:max(abs(f(a,x)-f(b,x))for x in a+b)
```
The input are 2 lists to the function `g`
Thanks to: Sp3000, xnor, undergroundmonorail
*Line 2, first call to `f` reads like "fax". I found that mildly amusing*
[Answer]
# CJam, ~~33~~ 31 bytes
```
q~_:+f{\f{f<_:+\,d/}}z{~-z}%$W=
```
Input is a CJam styles array of the two arrays.
Example:
```
[[8 9 9 5 5 0 3] [4 9 0 5 5 0 4 6 9 10 4 0 9]]
```
Output:
```
0.17582417582417587
```
[Try it online here](http://cjam.aditsu.net/)
[Answer]
## Matlab (121)(119)
This is a program that takes two lists throu stdin and prints the result to stdout. It is a strightfwd approcht and I tried to golf it as much as possible. `K(a)` returns a *function* that calculates `x -> F(a,x)`. Then the anonymous function `@(x)abs(g(x)-h(x))` which corresponds to the function `D` is applied to every possible integer of `0:max([a,b])` and the maximum of the results is displayed. (`arrayfun` does the same as `map` in other languages: it applies a function to every element of a array)
```
a=input('');b=input('');
K=@(a)@(x)sum(a<=x)/numel(a);
g=K(a);h=K(b);
disp(max(arrayfun(@(x)abs(g(x)-h(x)),0:max([a,b]))))
```
[Answer]
# Erlang, 96 Bytes
[edc65's JavaScript solution](https://codegolf.stackexchange.com/a/45258/21777) ported to Erlang.
```
f(A,B)->F=fun(A,X)->length([V||V<-A,V>X])/length(A)end,lists:max([abs(F(A,X)-F(B,X))||X<-A++B]).
```
Test:
```
lists:foreach(fun ([H,T] = L) -> io:format("~p ~p~n", [L, w:f(H, T)]) end, [[[0],[0]], [[0],[1]],
[[1, 2, 3, 4, 5],[2, 3, 4, 5, 6]],
[[3, 3, 3, 3, 3],[5, 4, 3, 2, 1]],
[[1, 2, 1, 4, 3, 6],[3, 4, 5, 4]],
[[8, 9, 9, 5, 5, 0, 3],[4, 9, 0, 5, 5, 0, 4, 6, 9, 10, 4, 0, 9]],
[[2, 10, 10, 10, 1, 6, 7, 2, 10, 4, 7],[7, 7, 9, 9, 6, 6, 5, 2, 7, 2, 8]]]).
```
Output:
```
[[0],[0]] 0.0
[[0],[1]] 1.0
[[1,2,3,4,5],[2,3,4,5,6]] 0.20000000000000007
[[3,3,3,3,3],[5,4,3,2,1]] 0.4
[[1,2,1,4,3,6],[3,4,5,4]] 0.5
[[8,9,9,5,5,0,3],[4,9,0,5,5,0,4,6,9,10,4,0,9]] 0.17582417582417587
[[2,10,10,10,1,6,7,2,10,4,7],[7,7,9,9,6,6,5,2,7,2,8]] 0.36363636363636365
```
[Answer]
## STATA 215
This is 90% getting the input into a format that can be used because STATA already has a ksmirnov command.
```
di _r(a)
di _r(b)
file open q using "b.c",w
forv x=1/wordcount($a){
file w q "1,"(word($a,`x'))_n
}
forv x=1/wordcount($b){
file w q "2,"(word($b,`x'))_n
}
file close q
insheet using "b.c"
ksmirnov v2,by(v1)
di r(D)
```
[Answer]
## R, 65 bytes
```
f=function(a,b){d=c(a,b);e=ecdf(a);g=ecdf(b);max(abs(e(d)-g(d)))}
```
This function takes two vectors as arguments and returns the maximum difference of their empirical cumulative distribution functions.
If built-ins were allowed, it would reduce to mere 12 bytes:
```
ks.test(a,b)
```
[Answer]
# Mathematica, ~~76 73~~ 63
Mathematica has the built-in function `KolmogorovSmirnovTest`, but I won't use it here.
```
k=N@MaxValue[Abs[#-#2]&@@(Tr@UnitStep[x-#]/Length@#&/@{##}),x]&
```
Usage:
```
k[{1, 2, 1, 4, 3, 6}, {3, 4, 5, 4}]
```
>
> 0.5
>
>
>
[Answer]
Quick implementation in Python 3.4.2 (79 bytes):
```
F=lambda A,x:len([n for n in A if n<=x])/len(A)
D=lambda x:abs(F(A1,x)-F(A2,x))
```
Example:
```
>>> A1 = [-5, 10, 8, -2, 9, 2, -3, -4, -4, 9]
>>> A2 = [-5, -3, -10, 8, -4, 1, -7, 6, 9, 5, -7]
>>> D(0)
0.045454545454545414
```
[Answer]
## Java - 633 622 Bytes
Ok,first up, trying to get better at java so thats why i tried it in java, I know i'll never do well, but eh, its fun.
second, I honestly thought i could do this in way less, then i got to the stage where there were doubles everywhere, and the method declarations meant using methods only saved 4-5 chars in total.
in short, i'm a bad golfer.
edit: usage format> java K "2,10,10,10,1,6,7,2,10,4,7" "7,7,9,9,6,6,5,2,7,2,8"
```
import java.lang.*;
class K{public static void main(String[]a){double[]s1=m(a[0]);double[]s2=m(a[1]);
int h=0;if(H(s1)<H(s2))h=(int)H(s2);else h=(int)H(s1);double[]D=new double[h];
for(int i=0;i<h;i++){D[i]=Math.abs(F(s1,i)-F(s2,i));}System.out.println(H(D));}
static double[]m(String S){String[]b=S.split(",");double[]i=new double[b.length];
for(int j=0;j<b.length;j++){i[j]=new Integer(b[j]);}return i;}
static double H(double[]i){double t=0;for(int j=0;j<i.length;j++)
{if(i[j]>t)t=i[j];}return t;}
static double F(double[]A,int x){double t=0;double l=A.length;
for(int i=0;i<l;i++){if(A[i]<=x)t++;}return t/l;}}
```
[Answer]
# Haskell ~~96~~ 83
```
l=fromIntegral.length
a%x=l(filter(<=x)a)/l a
a!b=maximum$map(\x->abs$a%x-b%x)$a++b
```
(!) is the kolmogorov-smirnov function which takes two lists
[Answer]
# R, 107 bytes
Different Approach
```
f=function(a,b){e=0
d=sort(unique(c(a,b)))
for(i in d-min(diff(d))*0.8)e=max(abs(mean(a<i)-mean(b<i)),e)
e}
```
Ungolfed
```
f=function(a,b){
e=0
d=sort(unique(c(a,b)))
d=d-min(diff(d))*0.8
for(i in d) {
f=mean(a<i)-mean(b<i)
e=max(e,abs(f))
}
e
}
```
] |
[Question]
[
The Challenge is to write the **shortest** implementation to find the [Longest increasing subsequence](http://en.wikipedia.org/wiki/Longest_increasing_subsequence) .
**Example** :
Let S be the sequence 1 5 7 1 8 4 3 5 [length of S = 8 ]
* We have 1 sub-sequence of length 0 [will consider it increasing]
* 6 sub-sequences of length 1 {1,5,7,8,4,3}[all of them are considered increasing]
* (7\*8)/2 sub-sequences of length 2 [but we will remove duplicates], the increasing sub-seq are in strong black.
{**15,17**,11,**18,14,13,57**,51,**58**,54,53,55,71,**78**,74,73,75,84,83,85,43,**45,35**}
*[note that we only interested in strictly-increasing sub-sequences]*
[you **can't change the order** of the elements inside the sequence , so there is no sub-sequence [37] in the example sequence]
* We have increasing sub-sequences of length 4 which is 1578 , but there's no sub-sequence of length 5 , so we consider the length of the longest increasing sub-sequence = 4.
**Input**:
a1 a2 ... aN (The sequence)
all numbers are positive integers less than 103
N <= 1000
**Output**:
One integer denoting the length of the longest increasing sub-sequence of the input sequence .
```
sample input(1)
1 2 4 2 5
sample output(1)
4
sample input(2)
1 5 7 1 8 4 3 5
sample output(2)
4
```
**Your code should run in a timely manner** please test your code on [this case](https://ideone.com/xQuw4V) before submit it here (also the link contains my 290-byte c++11 solution )
*You can either take the input from a file/stdin or as a function parameter and you can either print the output to a file/stdout or just return the value if you write a function*
## Score Board
1. [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) CJam - **22**
2. [isaacg](https://codegolf.stackexchange.com/users/20080/isaacg) Pyth - **26**
3. [Howard](https://codegolf.stackexchange.com/users/1490/howard) GolfScript - **35**
4. [proud haskeller](https://codegolf.stackexchange.com/users/20370/proud-haskeller) Haskell - **56**
5. [Ray](https://codegolf.stackexchange.com/users/6935/ray) Python 3 - **66**
6. [histocrat](https://codegolf.stackexchange.com/users/6828/histocrat) Ruby - **67**
7. [DLeh](https://codegolf.stackexchange.com/users/14185/dleh) C# - **92**
8. [YosemiteMark](https://codegolf.stackexchange.com/users/30096/yosemitemark) Clojure - **94**
9. [faubiguy](https://codegolf.stackexchange.com/users/29990/faubiguy) Python 3 - **113**
[Answer]
# Python 3, 66
Note that all numbers are in range [1, 999], we can use an array `b` to maintain the longest subsequence length ending with each number. `b[x] = d` means that the longest subsequence ending with `x` has length `d`. For each number from the input, we update the array using `b[x] = max(b[:x]) + 1` and then we got the job done by taking `max(b)` finally.
The time complexity is ~~O(n)~~ **O(m n)**, where `m` is always 1000 and `n` is the number of input elements.
```
def f(a):
b=[0]*1000
for x in a:b[x]=max(b[:x])+1
return max(b)
```
Wow, looks like already ungolfed :)
You can test it using stdin/stdout by adding a line:
```
print(f(map(int,input().split())))
```
[Answer]
# Python - 113
```
a=[]
for i in map(int,input().split()):
if not a or i>a[-1]:a+=[i]
z=0
while a[z]<i:z+=1
a[z]=i
print(len(a))
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 26 29 33 39
```
J*]0^T3Fkyw=@JkheS:J0k)eSJ
```
Port of @ray's solution. Passes official tests. Now uses space-separated STDIN input, not function call.
Run as follows:
```
./pyth.py -c "J*]0^T3Fkyw=@JkheS:J0k)eSJ" <<< "1 5 7 2 8 4 3 5"
4
```
Explanation:
```
J*]0^T3 J = [0]*10^3
Fkyw For k in space_sep(input()):
=@Jk J[k]=
heS:J0k max(J[0:k])+1
) end for
eSJ max(J)
```
---
Time unlimited:
# [Pyth](https://github.com/isaacg1/pyth), 18
```
L?eS,ytbhyf>Thbbb0
```
---
Technical note: I noticed a bug in my Pyth complier while writing this golf. `L` wasn't working. That's why there is a recent commit to the above git repository.
[Answer]
### Clojure, 94 characters
Using @Ray's approach of updating results in a 1000-item vector:
```
(defn g[s](apply max(reduce #(assoc % %2(inc(apply max(take %2 %))))(into[](repeat 1e3 0))s)))
```
Per request, with print statement (will print answer and return nil). Input should be a vector (g [1 2 3]) or a list (g '(1 2 3)):
```
(defn g[s](prn(apply max(reduce #(assoc % %2(inc(apply max(take %2 %))))(into[](repeat 1e3 0))s))))
```
[Answer]
# Haskell, ~~58~~ ~~57~~ 56 characters
```
(x:s)%v|v>x=x:s%v|0<1=v:s
_%v=[v]
l s=length$foldl(%)[]s
```
This uses an algorithm I saw once on the internet, but i can't find it.
It takes an unnoticeable amount of time on the given test case on my computer with GHCi (probably would be even faster if it was compiled).
[Answer]
# CJam, 22 bytes
```
1e3,q~{_2$<$0=(t}/$0=z
```
[Try it online.](http://cjam.aditsu.net/ "CJam interpreter")
### Example
```
$ cjam subsequence.cjam <<< '[2 1]'; echo
1
$ cjam subsequence.cjam <<< '[1 9 2 4 3 5]'; echo
4
```
The program prints `57` for [this test case](http://ideone.com/UCpJB1#stdin) after 0.25 seconds.
### How it works
I took the general idea from [@Ray's answer](https://codegolf.stackexchange.com/a/36572/).
```
1e3, " Push the array [ 0 ... 999 ] (J). ";
q~ " Read from STDIN and evaluate. ";
{ " For each integer (I) of the input array: ";
_2$< " Push [ J[0] ... J[I - 1] ] (A). ";
$0=( " Compute min(A) - 1. ";
t " Update J[I] with the value on the stack. ";
}/ " ";
$0= " Compute abs(min(J)). ";
```
[Answer]
### GolfScript, 35 characters
```
~]]){1${~2$<*)}%1+$-1>[\+]+}/$-1=0=
```
An implementation working as a complete program with input on STDIN (without the length number given). The implementation is reasonable fast, even for longer inputs (try [here](http://golfscript.apphb.com/?c=OyIxIDUgNyAxIDggNCAzIDUiCgp%2BXV0pezEke34yJDwqKX0lMSskLTE%2BW1wrXSt9LyQtMT0wPQ%3D%3D&run=true)).
Examples:
```
> 1 5 7 1 8 4 3 5
4
> 5 1 9 9 1 5
2
```
[Answer]
# Ruby, 67
```
s=Hash.new{|s,a|f,*r=a
s[a]=f ?[1+s[r.select{|x|x>f}],s[r]].max: 0}
```
This runs in 30 seconds on the large input, does that count as a timely manner? :p
It's brute recursion, but with some memoization.
[Answer]
# Bash+coreutils, 131 bytes
This solution fails horribly on the **timely manner** requirement, and is not even particularly short, but I liked that this sort of thing is at least theoretically possible in shell script, so I'm posting anyway. This runs with an eternity-inducing time complexity of O(2^n).
```
s=${1//,/,:\},\{}
a=`eval echo "{$s,:}"`
for s in $a;{
b="$(tr , \\n<<<$s|grep -v :)"
sort -nC<<<"$b"&&wc -w<<<$b
}|sort -nr|sed 1q
```
Input is a comma separated list passed as a single command-line argument:
```
$ time ./slisc.sh 1,5,7,1,8,4,3,5
4
real 0m1.240s
user 0m0.518s
sys 0m0.689s
$
```
Brace expansion is used to build the list of all possible subsequences.
* The first line replaces commas with `,:},{`, which produces a string like `1,:},{5,:},{7,:},{1,:},{8,:},{4,:},{3,:},{5`
* The second line completes this string with braces, commas and semicolons to give this `{1,:},{5,:},{7,:},{1,:},{8,:},{4,:},{3,:},{5,:}`. This is a valid bash brace expansion, which when `eval`ed with an `echo` produces this space-separated list `1,5,7,1,8,4,3,5 1,5,7,1,8,4,3,: 1,5,7,1,8,4,:,5 1,5,7,1,8,4,:,: ...`
* by default, bash splits strings with whitespace, so we loop over each element of this list:
+ commas are replaced with newlines, then lines containing colons are removed, giving newline-separated lists for each possible subsequence
+ we then `sort -C` to test for increasing order, and if so, use `wc -w` to print the length of the list
* the resulting list of list lengths is sorted in reverse and the first value printed to give the longest increasing subsequence length.
[Answer]
### C#, ~~172~~ 92 chars
Nothing special, but I did it so I figured I might as well submit it.
```
int a(int[] j){int c=2,m=2,i=1;for(;++i<j.Length;){c=j[i]>j[i-1]?c+1:2;m=c>m?c:m;}return m;}
```
Thanks Armin and Bob for their improvements!
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 21 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ë/NS7Γ╥╚┌{1╤╒¬è¶²╢╦┌☼
```
[Run and debug it](https://staxlang.xyz/#p=892f4e5337e2d2c8da7b31d1d5aa8a14fdb6cbda0f&i=[1+5+7+1+8+4+3+5]%0A[575+457+877+721+855+826+168+63+194+524+167+937+696+155+481+259+184+433+287+241+212+320+172+706+876+244+1+858+762+803+905+56+260+501+776+115+327+943+895+520+186+781+458+881+654+657+859+837+90+864+78+20+185+967+725+779+929+726+637+691+248+261+465+507+761+241+340+807+902+954+46+88+735+503+688+389+879+266+226+968+130+22+707+33+707+432+811+636+158+168+47+124+428+511+630+908+471+689+715+373+643+760+180+378+982+586+485+861+851+429+548+980+169+255+14+875+406+824+511+282+991+557+406+139+69+36+47+539+443+480+630+86+958+528+182+659+114+385+239+964+813+506+945+981+479+677+575+884+501+87+167+212+362+572+69+149+326+833+406+488+32+37+573+989+564+474+368+397+858+606+361+672+830+25+372+310+701+947+194+921+752+79+851+114+369+919+263+414+752+668+901+502+423+193+491+706+666+577+103+525+184+463+915+732+488+6+42+907+671+954+828+423+751+679+256+121+598+237+534+69+904+435+570+47+346+780+471+13+357+573+256+259+754+889+991+960+894+751+868+285+705+415+707+457+95+681+296+411+917+548+199+541+701+487+306+47+985+776+59+62+349+314+320+821+203+30+501+816+781+369+101+205+502+526+380+596+208+675+726+843+223+924+103+923+130+408+689+116+184+747+177+251+780+215+791+982+245+292+517+744+379+617+667+880+862+766+477+70+441+921+631+383+564+734+25+693+860+713+808+45+180+703+14+959+918+804+660+881+814+178+625+193+513+11+74+375+776+269+163+936+190+794+38+753+247+780+165+107+213+973+151+392+676+883+351+313+406+729+194+221+906+537+413+139+548+486+513+43+473+676+978+662+189+734+134+435+515+299+541+727+990+411+837+385+294+906+417+699+635+610+919+261+148+52+399+414+537+911+456+729+306+154+110+494+606+244+928+121+261+189+566+969+599+403+73+611+28+489+310+663+818+948+923+965+999+41+98+255+670+272+983+976+425+812+189+750+774+118+589+35+25+156+722+623+277+513+234+305+721+262+686+539+928+328+504+646+368+320+620+756+591+322+732+735+134+640+485+907+476+74+660+500+947+382+123+225+614+75+248+335+55+652+873+702+979+96+348+66+415+967+821+6+290+273+740+423+912+943+331+388+18+990+887+964+92+728+907+705+521+873+758+575+525+631+277+223+726+344+288+141+311+828+864+319+101+324+461+731+267+791+119+284+500+724+967+310+171+593+733+691+467+491+984+710+122+980+933+566+43+939+425+353+767+290+391+586+613+851+36+598+361+154+882+860+596+568+889+485+161+622+176+346+114+879+775+953+578+708+520+620+366+663+691+852+952+82+438+284+651+474+882+12+346+483+591+661+769+480+146+929+102+41+994+933+919+769+887+497+196+126+835+280+788+526+132+460+608+289+462+259+481+63+989+545+545+580+206+33+778+71+962+598+111+675+532+748+163+138+963+358+263+798+637+769+324+488+947+650+776+410+909+257+191+617+520+455+197+726+487+974+515+168+572+625+842+822+92+5+959+55+81+940+852+437+429+894+924+376+545+419+504+173+394+695+789+913+150+704+358+636+678+872+804+968+216+365+791+26+89+750+80+887+410+650+324+838+264+966+932+808+104+437+980+497+132+488+130+999+192+206+354+588+797+876+556+731+242+347+757+49+816+555+935+944+924+978+782+188+663+714+995+767+869+694+982+719+182+830+718+92+37+73+679+552+667+235+283+627+301+758+675+835+314+330+779+238+308+280+425+970+712+139+456+582+551+158+20+451+987+738+542+742+529+221+13+196+174+296+823+193+772+217+28+86+546+525+42+853+804+185+543+236+42+717+536+592+593+555+43+581+12+303+42+540+523+55+455+416+69+996+608+559+213+355+364+478+598+405+331+403+309+592+357+350+29+892+942+621+166+703+920+178+7+681+436+248+454+609+382+241+605+709+799+537+64+163+15+661+287+64+782+595+375+857+663+403+749+605+742+634+28+663+811+34+63+247+999+516+856+382+756+180+91+274+716+872+437+730+533+442+794+35+37+169+891+699+290+360+24+32+993+51+413+804+802+475+769+801+709+344+901+184+524+991+458+958+863+613+408+116+55+920+150+91+89+759+508+97+119+531+846+112+300+260+634+820+453+123+341+163+466+242+346+708+952+803+386+815+135+793+649+189+713+517+997+520+277+506+616+395+755+462+226+56+440+578+594+893+700+934+774+885+177+120+312+129+642+697+662+495+209+312+684+921+828+681+160+823+187+494+219+661+675+163+716+115+740+310+726+160]&m=2)
This has two test cases, one of which is the 1000-element case. It runs that one in 24 seconds on my machine. It uses the classic dynamic programming approach for this type of problem.
[Answer]
# [J](http://jsoftware.com/), 19 bytes
```
[:#]`I.`[} ::,~/@|.
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqCjUGulYKAAxP@jrZRjEzz1EqJrFaysdOr0HWr0/mtyceWBFBoaGBhw5YJY9noKeQrKEAGu1OSMfIU0hdz/AA "J – Try It Online")
Runs in *O(n log n)*, using a modified patience sort since only the length, not the actual subsequence, is needed.
## Explanation
```
[:#]`I.`[} ::,~/@|. Input: array
|. Reverse
/ Reduce right-to-left
I. Find the index to insert while keeping it sorted
(uses binary search)
} Amend the current search array at that index with the next value
:: If error (when the index is not found)
, Append the value at the end
# Length of that array
```
[Answer]
## J 34
Note that I read standard input as well.
```
>./;+/@:*&.>(<*>.)/\&.><\.".1!:1]3
```
Without reading standard input, the meat is 26 characters.
```
>./;+/@:*&.>(<*>.)/\&.><\.
```
Just noticed mine runs slow for large input, oh well.
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), 129 bytes
```
int f(int*a,int n){int l[n]{},i=n,j,m=0;for(;i--;m=l[i]>m?l[i]:m)for(j=n;--j>i;)if(a[i]<a[j]&&l[i]<l[j]+1)l[i]=l[j]+1;return++m;}
```
[Try it online!](https://tio.run/##LZfbblXHEkXf@YqWjhThg5FW37sxdj4E8WA5kLMRNhEBnUiIbydj1HIk4r336kvVrDln1Xr466/Xfz48/PrP5enh8/c/Pry9fPn729cP9493vy5P39LHl/z/v/fXfn66@uGfz@@e3v/4eX25fbr@dP14e9x8/PL15c3l9eubx9vP7y7v7x5/98@bxysffLp9unn9@tPd5ebq8vHlPQ/e3r/79P6331zz9jMfX@UrP9@en2@@fvj2/evTq1ePNz8jgsf7y9PLq/TjRUp@vX@XD/57f/1we1z/c8Ov///f5fOHl39/@@PNm4fL093dP1euTax8ePXq/W2s@cm/c8WX79/eviWQ64ermxc/X/zqs6fWZ1pzpllyWr2nVUbKY6VRU94t9dL4OtOuM43NI5a0lVPpO@XVUqs1lTVTafyWS6rlSHmWNI/BsYPf2c/BK81R0jpq2kdPnQfjSP3IabIo585GLmk1rc1jD1kjTS5qbF38Hb3xj1i5eBHMPtIajSUpFve0h0l0Dtxpl83nQRJGTWSNZYPDBocfrBs5Iq6NUw4PK2lzQSNoIq2uqmnwuS6u48QyCJkTN9D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8vMdwmbV9BQFBhhXaMwanxnFFaLIzwfniYCOUJtlBUPqHk1NR0h7jNNwcyj5fS23R8QISr8XHvw "C++ (gcc) – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 155 bytes
Used an array to compute the longest increasing subsequence ending at each position in the input array (dynamic programming), then returned the largest value. For example, the computed array for input `[1,5,7,1,8,4,3,5]` would be `[1,2,3,1,4,2,2,3]`, and the largest value `4` is returned.
```
int b(int[]x){int l=x.Length,r=1,i=0,j,c;var a=new int[l];a[0]=1;while(++i<l)for(j=0;j<i;j++){c=x[j]<x[i]?a[j]+1:1;a[i]=a[i]<c?c:a[i];r=r<c?c:r;}return r;}
```
[Try it online!](https://tio.run/##LZdNbxzXEUXX5q@YJQl1jH7f75kivMjWAQJkkYXABc0w8gg0BZC0rUDQb1fOqaYASTPT76Pq1r23qu9f/nb/@fnh@x8v56ePp3/97@X14ffri4v7x7uXl9M/nz9/fL77/eLrxQ8vr3ev5/vTn5/P/zn94@78dHl1cXr78/X7@en19Osl/364/XL11W@PN19@/OXh6ePrb9vzTdrON/v2abu//vPu@XR38/Tw18nFj7fXdx/225t0/ddv58eHy3fvzu8fr/77@fny081@/en9@frTu3dXX@9vvnz4dPv@y4fz7c93fHqXfkpsPN/e@M/7@5/vf/LD9fPNc3x5vv72/PD6x/PTiU/fI6rT68PL6@nm9PXURttqG9scYxs5bbO1bea@pT63Xra06tZy5evYVhlbXzxiSZ1py21tadatlrLlObZc@S3lreR9SyNvY@8c2/md/Rw8t9HzNveyrb1tjQd939qetsGilBobuaSWbS4ee8js2@CiytbJ/71V/hIrF0@CWfs2e2XJFovbtrpJNA5c28qLz50kjJrIKss6h3UO31nXU0RcKqfsHpa3xQWVoIm0uKpsnc9lch0n5k7InLiAJpWdz6Q4NrL3v1rILRFkEaEZANaxJcCreW4tHu1c48985tBhzoNLyHl0U9j5Prc189bIvZLS7EJH2KTTqs9Y1wmGIqRKXNRCnLnGKzJbF9k2YPL3VBbZb8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98u/j2/f8 "C# (.NET Core) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 38 bytes
```
Length@LongestOrderedSequence[#,Less]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE7876Zg@98nNS@9JMPBJz8vPbW4xL8oJbUoNSU4tbA0NS85NVpZxye1uDhW7X9AUWZeSbSygq6dgpuDcqyagr6DQnW1oY6CkY6CCZg0rdVRAAmY6iiY6ygAGRZgGWOQTO1/AA "Wolfram Language (Mathematica) – Try It Online")
There is of course a *Mathematica* built-in for finding longest ordered sequences. Its name is very long: it makes up more than half the solution, and I won't be surprised if someone out-golfs this solution.
] |
[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/25343/edit).
Closed 1 year ago.
[Improve this question](/posts/25343/edit)
Your challenge is to **create a shortest code** in your language of choice which writes on a **`.txt`** file **the longest code to multiply two numbers by taking two numbers as input and output the answer**.
*NO INPUT NEEDED TO YOUR CODE WHICH IS DOING THE WRITING JOB*!
**The generator code and generated code can be in any languages**
**Do NOT** use unlimited series or progression to make text file big.
**Do NOT** use unnecessary statements to increase the score.
### SCORING
```
( size of text file generated in bytes ) (without any unnecessary white spaces, tabs or newlines)
-----------------------------------------
( size of your code in bytes )
```
# Winner
**Winner** will be chosen **after 1 week** from now with the **highest score**.
**EDIT :** range of input in code multiplying two numbers should be in between -32768 to 32767
[Answer]
# perl/perl, unlimited score under original rule with unlimited range
Here's some code which doesn't win:
```
$l=-2**5-1;
$h=2**5;
sub p{print@_}
p"sub add {(\$i,\$j)=\@_;\n";
for($i=$l;$i<=$h;++$i){
for ($j=$l;$j<=$h;++$j){
p" return ".($i*$j)." if (\$i == $i) && (\$j == $j);\n";
}
}
p"}print add(<>,<>)\n";
```
The output has this form:
```
sub add {($i,$j)=@_;
return 1089 if ($i == -33) && ($j == -33);
return 1056 if ($i == -33) && ($j == -32);
return 1023 if ($i == -33) && ($j == -31);
return 990 if ($i == -33) && ($j == -30);
...
return 928 if ($i == 32) && ($j == 29);
return 960 if ($i == 32) && ($j == 30);
return 992 if ($i == 32) && ($j == 31);
return 1024 if ($i == 32) && ($j == 32);
}print add(<>,<>)
```
the output file is 181030 bytes long, but after stripping spaces and newlines, it is only 133109 bytes long. so, the score is 133109/248 = 536.7289...
Here's some other code that doesn't win - it is the same program except the first 2 lines:
```
$l=-2**6-1;
$h=2**6;
```
the output file is 718138 bytes long, but after stripping spaces and newlines, it is only 532233 bytes long. so, the score is 532233/248 = ~2146. better! using 7 yields a score of ~8750, 8 yields ~35347, 9 yields ~149129, 10 yields 151100000 non-space / 250 = 604,400 ....
of course we can do this as long as we want. the size of the source program, n, will increase as O(log(n)). the size of the output program is O(2\**n). The limit of 2*\*n/log(n) as n goes to infinity is clearly infinity, so if I just substitute in my favorite large number, a googolplex, I win (until someone suggests googolplex+1).
[Answer]
# C, 27297/245 = 111.4
### Source code (245 bytes)
```
#include<stdio.h>
main(int c,char**v){char*s;FILE*f=fopen("/tmp/x.c","w");fprintf(f,"#include<stdio.h>\n#include<stdlib.h>\nmain(){int a=%s,b=%s;printf(\"%s * %s = %%d\\n\",a*b);}",v[1],v[2],v[1],v[2]);fclose(f);system("cc -E /tmp/x.c >add.c");}
```
When compiled and run with two integer arguments on the command line, this generates another C file containing the necessary code to calculate their product, and compiles it with the `-E` flag. This flag specifies that the compiler should stop after the preprocessing stage and output the processed source code (which will include the entire contents of `stdio.h` and `stdlib.h`).
### Output file (27297 bytes)
```
# 1 "/tmp/x.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/tmp/x.c"
# 1 "/usr/include/stdio.h" 1 3 4
# 64 "/usr/include/stdio.h" 3 4
# 1 "/usr/include/_types.h" 1 3 4
# 27 "/usr/include/_types.h" 3 4
# 1 "/usr/include/sys/_types.h" 1 3 4
# 32 "/usr/include/sys/_types.h" 3 4
# 1 "/usr/include/sys/cdefs.h" 1 3 4
# 33 "/usr/include/sys/_types.h" 2 3 4
```
`********* LINES 13-1273 OMITTED *********`
```
long long
strtoq(const char *, char **, int);
unsigned long long
strtouq(const char *, char **, int);
extern char *suboptarg;
void *valloc(size_t);
# 3 "/tmp/x.c" 2
main(){int a=6,b=7;printf("6 * 7 = %d\n",a*b);}
```
### Result of running the output code
The output file is saved as `add.c`, which can be compiled and run normally:
```
$ ./a.out 6 7
$ cc add.c -o add
$ ./add
6 * 7 = 42
$
```
[Answer]
# perl, 125 chars, score 1,630,326,497.312
Same basic approach as my other answer, but this time bounded between -32768 and 32767 per the updated rules, and all unnecessary whitespace stripped completely:
```
$l=-($h=32767)-1;print"sub a{";for$i($l..$h){print"return ".$i*$_." if\$_[0]==$i&&\$_[1]==$_;"for$l..$h;}print"}print a<>,<>"
```
The output program begins like so:
```
sub a{return 1073741824 if $_[0]==-32768&&$_[1]==-32768;return 1073709056 if $_[0]==-32768&&$_[1]==-32767;
```
and ends:
```
return 1073643522 if $_[0]==32767&&$_[1]==32766;return 1073676289 if $_[0]==32767&&$_[1]==32767;}print a<>,<>
```
The output program is 190GB long. More precisely, 203790812164 bytes. Score = 203790812164 / 125 = 1630326497.312
[Answer]
## Windows Command Script: ~1,000,000,000 pts
Code: 158 bytes
Output: ~158000000000 bytes
```
echo>.txt @goto :%%1_%%2
set,=for /l %%a in (-32768 1 32767) do call :
%,%1 %%a
:1
%,%2 %1 %%a
:2
set/a]=%1*%2
echo :%1_%2>>.txt
echo @echo.%]%^&exit/b0>>.txt
```
The output pretty much consists of:
```
@goto :%1_%2
:-32768_-32768
@echo.1073741824&exit/b0
:-32768_-32767
@echo.1073709056&exit/b0
...
:32767_32767
@echo.1073676289&exit/b0
```
[Answer]
# Python, 142 bytes
```
c='def m(a,b):\n'
L=32768
a=-L
while(a<L):
b=-L
while(b<L):c+=f' if a=={a}and {b}==b:return {a*b}\n';b+=1
a+=1
F=open('c.txt','w')
F.write(c)
```
Score unknown for the moment, ~~but I think it's more than a billion.~~ Nope, probably just below a billion.
## Score update
The program has a minimum length of `111669149696` or about 111 billion. This means that the minimum score of this answer is roughly 780 million.
It also has a maximum length of roughly 150 billion, which indicates that **the score is between 730 and 1050 million**. My score is most likely in the middle of that range, i.e. about **890 million**.
Basically writes a function `m` to a file `c.txt` using two while loops.
] |
[Question]
[
Write a program that's as short as possible (as measured by byte-count), takes no input, contains no comments, and outputs a character string/sequence, such that concatenated program+output is exactly 95 characters long and **contains every [printable ASCII character](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) exactly once**, i.e. program+output is a permutation of the 95 characters with ASCII codes 32-126:
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
In the event of a tie, the winner is the entry whose (95-character) concatenated program+output is closest to the above string, as measured by the [Levenshtein edit-distance](https://en.wikipedia.org/wiki/Levenshtein_distance) (i.e. the number of single-character deletions, insertions, or substitutions required to put it into ASCII order).
[Answer]
### GolfScript, 14 characters
```
{`),32>46-^}.~
```
[Output](http://golfscript.apphb.com/?c=e2ApLDMyPjQ2LV59Ln4%3D&run=true):
```
!"#$%&'(*+/015789:;<=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]_abcdefghijklmnopqrstuvwxyz|
```
[Answer]
## Perl, 89 characters
This is the best I've been able to do so far:
```
q< !"#%&'()+/8:?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\^_`abcdefghjklmosuvwxz|>;
print~-$=.73*2,y[]{}
```
For those not conversant in Perl minutae, the two arguments to the `print` statement could be rendered as `~(-($=)) . (73 * 2)` and `tr///`.
The program outputs 6 characters:
```
591460
```
Unfortunately every single iteration construct that I can think of in Perl (`for`, `while`, `until`, `map`, `grep`) shares at least one character with `print`. If newlines were allowed to appear in the output, then I could use Perl 5.010 to eke out an 87-character solution:
```
q{ !"#%&'*,-./0:;>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^`bcdfgjkmnoprtuvxz|~}while($_+=say)<9
```
[Answer]
## PHP 67 bytes
```
<?=U4eB1gkFdA6J9snZD2IE8y5PhwQV^xHGmqYMfNjKpbR3vcLalCWi0_TtrOSXouz;
```
Output:
```
-|"/@>& *+}:[!],'~(){.\`7#%$
```
It seems like there should be a 65 byte solution, outputting 30 chars instead of only 28, but I couldn't get it to line up. The 6 unused characters `OSXouz` have been tacked onto one of the string literals instead.
**Edit:** Upon further reflection, it is not possible to generate more than 28 characters in this manner. `UPPER ^ lower` will always result in a character between 32 and 63, so all 10 digits are required for `@[\]_`{|}~`. Four of the remaining 22 are used in the script itself, leaving only 18 which can be obtained with letters alone. The tiebreaker could be improved significantly, though.
[Answer]
## Ruby, 91 chars
```
%{ !"#$&\',-/450:<=>ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcefghijklmnqvwxyz|~};puts(?@.ord*98+1)
```
Outputs `6273`.
`%{...}` trick stolen from Jan Dvorak
[Answer]
# Perl, 61 characters
```
print$:x8^CJIBQTOWAEULHVGFNMKRPZY,q<#"/;*g~?|={.>&+u15m97ws26
```
Output:
```
c@db[yo]le_ah\jfD`kX}zS-! %)('v304
```
`$:` defaults to `" \n-"`. `x8` repeats it eight times; the 24-character result is then bitwise-xored with a 23-character barestring (the last `-` is left as-is). Second part is a 12-character q-string bitwise-and a 10-character barestring (the last 2 characters are discarded).
[Answer]
# Ruby, 95 characters, 6 edits
```
%{ !"#$&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz|~}
```
Yep. That's it. Just a free-floating string literal that is never printed. Ruby supports string literals (borrowed from Perl, I think) in the percent-type-delimiter form - the delimiter is any non-alphanumeric character, and if the opening delimiter is an opening bracket (any of `[({<`), the closing delimiter is the corresponding closing bracket (nested brackets are allowed).
I realise this is more of a baseline submission, but unless someone manages to actually print something or unless there's a language with a two-char freeform string literal with a *different* opening and closing delimiter, this is the best there is.
[Answer]
### Tcl 96, edit distance 12
```
if 0 {!"#$%&'()*+,-./123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdeghjklmnopqrstuvwxyz|~}
```
] |
[Question]
[
## Challenge
Given some JSON data, calculate the maximum depth reached. (Both arrays and dictionaries increase the depth)
## Input/Output
The program is expected to read a JSON string from stdin and as soon as the program receives a \n start calculating the max depth, printing it to stdout and terminating the program when done.
If invalid JSON is provided, the output is undefined (the program can return anything).
## Test cases
`[]` -> 1
`[1, 2, 3, 4, 5]` -> 1
`[ [ 123], []]` -> 2
`[{"a": []}, ["abc"]]` -> 3
`{"a": 321}` -> 1
`{"a": []}` -> 2
`"hello"` -> 0
`["abc[]bca"]` -> 1
### Evaluating machine/platform
Platform: aarch64 Linux (arch Linux arm, cpu: apple M1)
### Results
| Contestant | Language | Result |
| --- | --- | --- |
| AnttiP | C | 43 ± 11 ms |
| Philx0 | C | 67 ± 7 ms |
| 138 Aspen | rust | 112 ± 7 ms |
| Arnauld | node.js | 276 ± 18 ms |
| tsh | node.js | 370 ± 16 ms |
| noodle man | node.js | 567 ± 143 ms |
### edit
Edit: changed challenge to not require outputting 0 in the case of invalid JSON
[Answer]
# C, based on Philx0's answer
I tried to remove a few branches. Instead of storing state in a variable I store it... in the state. Namely, there are two loops depending on if we are parsing a string or not. The rest of the comparisons should be branchless when compiled with -O3.
Edit: Slightly improved version. It's possible to also remove most checks for "\n" by keeping track of whether the current depth is positive, tough I'm not sure how much it would improve performance.
```
#include <unistd.h>
#include <stdio.h>
#define BUFSIZE 4096
#define unlikely(x) __builtin_expect((x),0)
int main(void) {
int depth = 0;
int maxdepth = 0;
char buf[BUFSIZE];
ssize_t cnt;
ssize_t i;
ssize_t skip = 0;
int str = 0;
while ((cnt = read(0,buf,BUFSIZE))) {
i = skip;
if (!str) {
for (; i < cnt; i++) {
if (buf[i] == '"') goto instring;
if (unlikely(buf[i] == '\n')) goto print;
if (depth > maxdepth) maxdepth = depth;
depth+= buf[i] == '{' || buf[i] == '[';
depth-= buf[i] == '}' || buf[i] == ']';
outstring:;
}
str = 0;
} else {
for (; i < cnt; i++) {
if (buf[i] == '"') goto outstring;
if (unlikely(buf[i] == '\\')) i+=1;
instring:;
}
str = 1;
}
skip = i - cnt;
}
print:
printf("%d\n", maxdepth);
return 0;
}
```
[Answer]
# Rust
use `serde_json` crate. I don't know how fast it is.
upd 2023-06-19 \$\quad \$ In light of the comment of @lights0123, you can use `cargo build --release` instead of `cargo build`. It would likely be significantly faster in release mode.
### `src/main.rs`
```
use std::io::{self, Read, BufRead};
use serde_json::Value;
use std::process;
fn main() -> io::Result<()> {
let stdin = io::stdin();
for line in stdin.lock().lines() {
let line = line?;
let json_value: Value = serde_json::from_str(&line).unwrap_or(Value::Null);
println!("{}", search(&json_value));
}
process::exit(0);
}
fn search(node: &Value) -> u32 {
match node {
Value::Object(map) => {
let max_depth = map.values().map(|v| search(v)).max();
match max_depth {
Some(max) => 1 + max,
None => 1,
}
},
Value::Array(arr) => {
let max_depth = arr.iter().map(|v| search(v)).max();
match max_depth {
Some(max) => 1 + max,
None => 1,
}
},
_ => 0,
}
}
```
### `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]
serde_json = "1.0"
```
### Build and running
```
# win10 environment
$ cargo build --release
$ target\release\rust_hello.exe
[{"a": []}, ["abc"]]
3
hello
0
{"a": []}
2
{"a": 321}
1
[ [ 123], []]
2
[1, 2, 3, 4, 5]
1
[]
1
[[]
0
```
[Answer]
## A rewrite of noodle man’s solution in C
```
#include <stdio.h>
#define BUFSIZE 1024
int main(void) {
int str = 0;
int escape = 0; //backslash
int depth = 0;
int maxdepth = 0;
char buf[BUFSIZE];
while (fgets(buf, BUFSIZE, stdin)) {
for (size_t i = 0; buf[i]; i++) {
if (buf[i] == '\n') goto print;
if (escape) {
escape = 0;
continue;
}
if (buf[i] == '\\') {
escape = 1;
} else if (buf[i] == '\"') {
str = !str;
} else if (!str) {
if (buf[i] == '{' || buf[i] == '[') {
depth++;
if (depth > maxdepth) maxdepth = depth;
} else if (buf[i] == '}' || buf[i] == ']') depth--;
}
}
}
print:;
printf("%d\n", maxdepth);
}```
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org)
I honestly have no idea how fast it is.
*EDIT: Since the challenge is no longer asking for JSON validation, using `JSON.parse()` may now seem a bit overkill. But this built-in is apparently reasonably well optimized and still faster than a simpler 100% JS parser.*
```
const readline = require('readline');
// set up the readline interface
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
// the following callback is invoked when a line is read
rl.on('line', str => {
let json;
try {
// attempt to parse the line as JSON
json = JSON.parse(str);
}
catch(e) {
// if it fails, force the result to null
json = null;
}
// recursive function computing the max. depth
function search(node) {
// look for anything whose typeof is 'object' but is not null
if(typeof node == 'object' && node !== null) {
// for an array, use the node itself
// for a genuine object, use the list of its values
let list = Array.isArray(node) ? node : Object.values(node);
// return 1 right away if the list is empty
// otherwise, do a recursive call for each element in the list
// and return the highest result + 1
return list.length ? 1 + Math.max(...list.map(search)) : 1;
}
// return 0 for non-iterable elements
return 0;
}
// initial call to search
console.log(search(json));
// we're supposed to process only one line, so force exit
process.exit();
});
```
[Try it online!](https://tio.run/##XZExb8IwEIX3/IorA3FUapUVlFYdW6ll6IgYjLmAkbFT@4JAiN9OLzZUbYck1nfvvbuct2qvog6mpQfnV3i5aO8iQUC1ssYh1Hz86kxAUd5YWU2L4iqzSZC51HwifHWEoVEaxakAMK7taAJt8BpjlJFWxo2Y@47@Fxj1FXbvjFN2Ao2yEYtz3y5Y6Z0oU/sRRApQP0Gfb5FgG71jDVvDMUFIiEd7@5x9yFaFiII9HARw5kcr0huB1V@x66zNCn41ndNkmEdUgcX9cm560wg6tugb6CnUNZR@uUVNJQyHmd3VOe9myYNawzur4SUEdZQmpu81@Tn7JjBLSXKvbIcxF6fXiIDUBZdSpEW3pg3bxnAP74o2cqcOQkqZqjvVijx4VXHmOCeci18pjz@/2l@ltyitX19Not9Ilfre7gcPhgQTvo3LZX4aqMEE5ovzCOYDtdSDxeIb "JavaScript (Node.js) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 621 bytes
```
require("readline").createInterface({ input: process.stdin, output: process.stdout, terminal: false }).on("line", file => {
let inString = false;
let prevBackslash = false;
let depth = 0;
let maxDepth = 0;
for (const char of file) {
if (prevBackslash) {
prevBackslash = false;
continue;
}
if (char === "\\") prevBackslash = true;
if (char === '"' && !prevBackslash) inString = !inString
if (inString) continue;
if ("{[".includes(char)) {
if (++depth > maxDepth) maxDepth++;
}
if ("]}".includes(char)) depth--;
}
console.log(maxDepth);
process.exit();
});
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dVJLTsMwEJVYcorpLNpESSM-QkKp0gViw5pl24VJxq2FawfHQZWinIRNF3AO7sFpyKcJbSq8Gr95897MaD4-lU5ov__KLZ_e_1xsDb3lwpCDhlgihSJ0g7iKLT0pS4azmJwChEpzG0JqdExZFmQ2EcoHndshXEE-VHVboZgMgTOZEZRuoJWDjboPXEiCaA7FJYAkW2k_WyPUGqKWPjvgqaH3Bxa_ZpJlm2EyodTW4FUHbNnu8Rjj2oATa5VZiDfMgOaNsdvYAggOzolBl4D_fetXKVqh8sO_7LUajyiKAJdLdM80rOlKTsgTnMB4DKNBJ0cbGXVxX9wB7lEvfRKLBQZCxTJPKGt83L_BaoLntZub9wtz-8jzhlPhqjyXawSm05pbM-sda0mB1Gun16yT3VXQTlinQkp31l7d4fj23wUyDJG9xEtMiKO_uL659QtcIoZ35apsab8)
This should be faster since it doesn't check if the JSON is valid, which is no longer required. If checking the JSON was valid was required, a solution like this manually verifying validity while checking the depth might still be faster, but I don't feel like writing a JSON parser.
All this does is loop over each character of the input, ignoring strings, incrementing a depth counter whenever it encounters a `{` or `[`, decrementing the counter when it encounters a `}` or `]`, and keeping track of the maximum depth.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org)
```
const isArray = Array.isArray, objectValues = Object.values, max = Math.max;
require("readline").createInterface({ input: process.stdin, output: process.stdout, terminal: false }).on("line", str => {
const depth = JSON.parse(str, (key, value) => {
if (value === null || typeof value !== 'object') return 0;
const arr = isArray(value) ? value : objectValues(value);
const depth = -~max(...arr);
return depth;
});
console.log(depth);
process.exit();
});
```
[Try it online!](https://tio.run/##XVCxbsIwEN35iqsXHClYnYPSqmMrtQyVuiAG41yKqbFT20EgoL@eHk4itUz2vXvv3t3byr0MyusmzqyrsOuUsyGCDk/eyyOUkF4x1Dm49RZV/JCmxUDdRSrFPtU57OSBwFcZN4K@84nH71Z75MyjrIy2yDKh6B/x2Ub0tVTIT6Bt08YCGu8UhiBCrLQlpzbewgTlQLqdttIUUEsTEC6ZcJazND2HED2UD3CaAPSXVNjEDS318r54E430ATlxcuBfSOekxbNRAaBr4AmDsizBtsbA@Qzx2KCrezLcUWPaxzDNwGNsvYX7eZL3ltLTDmOEfLB4HOTFvwiH7l/1uPDshyLkQggaNxAGs8S4IpeEX2XOoDDuk6dWQsfY8KAjJ4S4Xbc8MckKWK4uOSyZXCu2Wv0C "JavaScript (Node.js) – Try It Online")
The readline part is based on other answers.
Just in case if you are interesting, it can be golfed into 70 bytes, however, this question is not tagged as code-golf.
```
s=>JSON.parse(s,(_,v)=>Object(v)===v&&-~Math.max(...Object.values(v)))
```
[Try it online!](https://tio.run/##XY9BawIxEIXv/oohB0kg5gfsskKPFVoPhV5EypgdayQm2yS7WMT@9e2w6qE95b2X5M03Rxww2@S6sgixpXG0MeQCLj@lhN/QwHSau9cQd0ey5R19T5lv15M1w@Q1nPDM4QuWg2FZzxJ99S6RFImw9S6QUMayLvQcCqU9WpIXcKHrSwVdipZyNrm0LvCkvvyPOdLA/04uoK9gjz4TXJWJQYqpXQNDLeEyA7jt0VJXDoy0elu/mg5TJpm1/NCDapY3dsmyaYb5fPHz4JbGmD@L8Rul7p3Rk/HxU07Nqub0AUhnVyQnV1WP4@YiUFSw2V41bATurNhufwE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 35 bytes
```
"(\\?.)*?"
T`[]`{}
[^{}]
+`}{
..
```
[Try it online!](https://tio.run/##PYpBCsIwEEX3/xTDgFB1KCTRjZsuvYC76UjSUlAoCuIu5OwxKLj7773/Wt73R6qb7hwrd@M49NvdwMAlqsVcoNdcDNjHkoG@r1UN6oS8UBA6CB0bk5LzwYSI1BpnTnxqswgpp2nmJn8ueFfwz@Dbsq5PxvelNs2J7QM "Retina 0.8.2 – Try It Online") Link includes test suite. Probably not going to win any awards for speed. Explanation:
```
"(\\?.)*?"
```
Delete all string literals.
```
T`[]`{}
```
Change square brackets into braces.
```
[^{}]
```
Delete everything other than braces.
```
+`}{
```
Merge adjacent containers at the same depth.
```
..
```
Count the maximum depth.
[Answer]
# [Go](https://golang.org/), 715 bytes
```
package main
import (
"bufio"
"fmt"
"os"
)
func calcDepth(data string) int {
depth, maxDepth := 0, 0
inString := false
escaped := false
for _, r := range data {
switch r {
case '\\':
escaped = !escaped
case '"':
if !escaped {
inString = !inString
}
escaped = false
case '{', '[':
if !inString {
depth++
if depth > maxDepth {
maxDepth = depth
}
}
escaped = false
case '}', ']':
if !inString && depth > 0 {
depth--
}
escaped = false
default:
escaped = false
}
}
return maxDepth
}
func main() {
var data string
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
data = scanner.Text()
}
fmt.Println(calcDepth(data))
}
```
[Try it online!](https://tio.run/##hVLRaoMwFH1OvuIuD1WplT4L7mnPY9C9WRmpJm2YRolxLRS/3SXRpS2MDQRz7zn3nBO9x3aaOlp@0iODhgqJsWi6VmkIMSKHgYuWmANvtH21PcERxnyQJZS0Ll9Yp09hRTWFXishjxEIqeGKUWWR2CheHAfSDLYxbDEScueYtsNp3TOMWF/SjlV3Hd4q@IhB2Zai0kRzHkYX9Wehy5OBbFHSnkGw3wepKbxOBk/L0VPIzBDcQ24e3eKYoZ@zBcZHwSXXonYNYgjym6QXmTXd3dfrWZ@DK@H59i1mFvJ1NlNcd/zXfLTmxS/mq5W32t4n2Wz@0KwYp0Ot099RM2QexfSgpM@Px2UD7LqEkbX6ogrutgBjZKSkZO4HuiVKXtl5N/fCtk92uhLSbJK9wUJNLDzLIaeVeeSdXXQY2SxmNRqdvBkTXcvwcQWjyCSbpvxKKEkhL8YYckIPJSmKbw "Go – Try It Online")
[Answer]
# [GNU AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~11ms
```
BEGIN {
FPAT = "(\"([^\"])*\")+|."
m = 0
}
{
printf "%s -> ", $0
gsub(/'\\'\"[^'\\\"']*'\\'\"/, "", $0)
gsub(/\\"/, "\"\"", $0)
for (i = 1; i <= NF; i++) {
if ($i == "[" || $i == "{") {
a++
m = (a > m ? a : m)
} else if ($i == "]" || $i == "}") {
a--
}
}
print m
m = 0
}
Result:
123 -> 0
[] -> 1
[1, 2, 3, 4, 5] -> 1
[ [ 123], []] -> 2
[{"a": []}, ["abc"]] -> 3
{"a": 321} -> 1
{"a": []} -> 2
"hello" -> 0
["abc[]bca"] -> 1
["\",[],\""] -> 1
["",[],""] -> 2
["\"",[],""] -> 2
["\"",[],"\""] -> 2
"[\\" -> 0
```
[Try it online!](https://tio.run/##bVBNT8JAED13fsXLBENLF6GgFxSMJmK8EA/edpdkIVQbqRiq8VD62@u0hYaD2U1m3sfOzoz7/SjLh8en5wVy8uYv96@Ygn3Dvl4atkHPcBAeLpm8VIQhFUTi@9onn98x@CJDfwZW6AzJe8t@Vv6ga0zXsF5KNNy1vQYPFLi2BSefaUgj5yTEuz38RL6JbpDgdorFXJIwDKrWvCSG3xFV2tOMwwFHkHOjey4Mq1D16TvMkOIODhOkUtorsNlmG5wVsedFirZIv1@5qbr1lEjb0csyGo1JW9KRwkhhrHClcC0YGiJZBUBbwTk7nkhaKGh2qzUL2XDjUVRQKxO/b7bbHVPt0na1dizPZSdKWyWbqUCd85H/B9Q21rJQ@gM "AWK – Try It Online")
[Answer]
# [Racket](https://racket-lang.org)
```
#lang typed/racket/base
(require typed/json)
#|
Calculate the maximum depth of a JSON object read from input
Algorithm:
1. Read user input and parse JSON.
2. If input has no data, return 0.
2. Begin `max-depth` with the parsed JSON data and depth of 0.
a. If the JSON input is a list, loop over each element of the list and pass
the element as an input for `max-depth` and increment the depth. Repeat step 2.
b. If the JSON input is a hash table, use each values of the table as the input list
for step 2.a.
c. If the JSON input is a number, string, boolean, or null, return the depth.
3. Print the maximum depth.
|#
(: max-depth (-> JSExpr Real Real))
(define (max-depth input depth)
(let ([depth+1 (+ depth 1)])
(cond [(list? input)
(apply max
(cons depth+1
(map (λ ([elem : JSExpr]) : Real
(max-depth elem depth+1))
input)))]
[(hash? input)
(apply max
(cons depth+1
(hash-map input
(λ ([_ : Symbol] [value : JSExpr]) : Real
(max-depth value depth+1)))))]
[else depth])))
(: main (-> (U JSExpr EOF) Real))
(define (main input)
(cond [(equal? eof input) 0]
[else (max-depth input 0)]))
(displayln (main (read-json)))
#| Tests [Remove line to run after input, if all pass, nothing will display.]
(require (only-in typed/rackunit check-equal?))
(check-equal? (main (string->jsexpr "[]")) 1)
(check-equal? (main (string->jsexpr "[1, 2, 3, 4, 5]")) 1)
(check-equal? (main (string->jsexpr "[ [ 123], []]")) 2)
(check-equal? (main (string->jsexpr "[{\"a\": []}, [\"abc\"]]")) 3)
(check-equal? (main (string->jsexpr "{\"a\": 321}")) 1)
(check-equal? (main (string->jsexpr "{\"a\": []}")) 2)
(check-equal? (main (string->jsexpr "\"hello\"")) 0)
(check-equal? (main (string->jsexpr "[\"abc[]bca\"]")) 1)
Tests [Remove line to run after input, if all pass, nothing will display.] |#
```
## Compilation
Once Racket is installed one your system, simply run:
```
raco exe /path/to/this_file.rkt
```
Best compiled without the tests.
## Explanation
Racket provides a nice built-in package called [`json`](https://docs.racket-lang.org/json/index.html) that parses JSON expressions (`JSExpr`). All lists in the JSON expression are parsed into [Racket Lists](https://docs.racket-lang.org/guide/pairs.html) and all dictionaries are parsed into [Hash Tables](https://docs.racket-lang.org/guide/hash-tables.html) where the keys are [Symbols](https://docs.racket-lang.org/guide/symbols.html) and the values are other `JSExpr`s. The reason I am using Typed Racket is that it is [potentially faster](https://docs.racket-lang.org/ts-reference/Optimization_in_Typed_Racket.html) than the dynamically typed language.
## Conclusion
This is my submission for the challenge, I am not that great at optimizing code, so I don't expect peak performance in its runs. I did do a sample test on my machine with a 64kB minified JSON file which ran (according to `time`) at about 700ms. As a note though, my CPU is Intel 2 Duo E8500 and 2GB RAM, so I think it should be faster on other machines :)
Have an amazing weekend!
] |
[Question]
[
Every odd degree polynomial has at least one real root. However this root does not have to be a rational number so your task is to output a sequence of rational numbers that approximates it.
## Rules
* Your input is an odd degree polynomial \$f\$ with integer coefficients in any reasonable format.
* You must output a sequence of rational numbers \$(a\_n)\_{n=1}^{\infty}\$ such that \$f(\lim\_{n\to\infty} a\_n) =0\$ using the standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules.
* Your solution may fail because of finite precision however it must work in theory, assuming your language has arbitrary precision rational numbers. If your language doesn't support algebraic numbers, you may not
assume that it does. In particular you may not assume that a `find_roots` built-in returns an infinite precision algebraic number if it doesn't.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest solution in bytes wins.
## Test cases
```
input -> example output
x^3-2 -> 1, 1.2, 1.25, 1.259, ...
x+7 -> -7, -7, -7, ...
x^5-x+1 -> -1.1, -1.167, -1.167304, ...
2x^7-3x^5-x^4-2x+1 -> 3, 0.7, 0.453 ...
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ ~~22~~ ~~19~~ ~~12~~ 8 bytes
```
Lż{.Δβd
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f53DroT3VeuemnNuU8v@/oQEQcEUb6Rjo6Brr6BoCaSDLSMcwFgA "05AB1E – Try It Online")
Takes as an input a number \$n\$ and the coefficients list, from the highest power to the smallest one, and returns \$a\_n\$.
Requires the leading coefficient to be positive. If that is invalid, we need +2 bytes to fix it by adding `*н` after `β`
If this is invalid because we may not assume \$\tan\$ has infinite precision, then the following 13 bytes alternative could be used, which uses a spacing of \$\frac1 n\$ for the \$x\$s inside a bound:
```
*ÄO(D(Ÿ¹/.Δβd
```
## Explanation
Finds the non-negative value of \$p(x)\$ (\$p(x) \cdot c\_m\$ in the version which doesn't require a positive leading coefficient) with the smallest \$x\$ among the values \$ x = \tan(i) \$ for \$ 1 \leq i \leq n \$. The \$\tan\$ of integers is dense in \$\mathbb{R}\$ (Since \$ n\mod \pi\$ is dense in the range \$(0, \pi)\$ ), so we can get arbitrarily close to the target number, and since we always keep \$x\$s as \$n\$ increases the sequence is non-increasing. Additionally, uses the fact that base conversion is the same action as evaluating a polynomial at the base, and that 05AB1E's base conversion builtin works well with non-integers.
```
L Get the range [1, 2, 3, ..., n]
ż Calculate the tangent of each number in that range
{ And sort those
.Δ Now find the first value such that
β When converting the polynomial from that base
d It is non-negative
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 89 or 143 bytes
## Answer #1
If it is enough to find *one (any)* real root
we can use next facts:
* All real roots of odd degree polynomial [are bounded inside interval](https://math.stackexchange.com/questions/689575/proof-that-every-polynomial-of-odd-degree-has-one-real-root) \$[-M,M]\$
where \$M = \max\left(1,\sum\_{k=0}^{2n}|a\_k|\right)\$ (\$\sum\_{k=0}^{2n}|a\_k|\$ if coefficients are integers)
* [Bisection method](https://en.wikipedia.org/wiki/Bisection_method) *always* converges to *some* root of continuous function if they exist in given interval
...and do not use extra-power built-ins.
Fortunately `$MachineEpsilon` works well with TIO. So next code produces stream of *rational* approximations for one of the real roots. Input: array of coefficients.
```
With[{c=#,m=Total[Abs/@#]},If[Abs[Echo@#1-#2]>$MachineEpsilon,p=Fold[x#1+#2&,0,c]/.x->#&;d=(#1+#2)/2;If[p@#1*p@d>0,#0[d,#2],#0[#1,d]]]&[-m,m]]&
```
[Try it online!](https://tio.run/##HYw9C4MwFEX/SuEV6cezGmmHIpF0sNDBrdAhZEgTRcGYgBkE8bfb2OXee@5wjPRtbaTvlFwbun463/JZUUBDKzlxgm/rZc8f3zFhIMSCr2YDXqrWMiAxZKLYV1K13VCXbux6O6CjT9trPgE5QxZhikoklykuIMo1PfzfY5LlweSC4uSYLlKElGsMtm0AQS2EiHhs0IReGzZfcReT@xa4uy3rDw "Wolfram Language (Mathematica) – Try It Online")
Optimization is welcome!
## Answer #2
The next code works well with Mathematica desktop
(input is array of coefficients and output are approximations of *all* real roots):
```
Do[Echo[x/.NSolve[Fold[x#1+#2&,0,#],x,Reals,WorkingPrecision->n]],{n,∞}]&
```
But on TIO nor `N`, nor `WorkingPrecision` are not working(
So just like this (n>20 make no sense):
```
Do[Echo@Round[x/.NSolve[Fold[x#1+#2&,0,#],x,Reals],10.^-n],{n,20}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yU/2jU5I98hKL80LyW6Ql/PLzg/pyw12i0/B8hVNtRWNlLTMdBRjtWp0AlKTcwpjtUxNNCL082L1anO0zEyqI1V@x9QlJlX4pDmUG2io6BraAkidBRMa/8DAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [R](https://www.r-project.org), ~~91~~ 90 bytes
```
\(x,n,a=polyroot(x),c=Re(a[!Im(a)])%/%1+0:n/n)c[order(sapply(c,\(y)x%*%y^seq(!x)/y)^2)][1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY_NbgIhFIXX-hTXmEmgMhHspjGdZRfdtImxm_oTKQUlYcAC086s-iDd6KIP5dvIVCdpWBC45zvn3J-jP5y-N4NNoSoronYW1SQ6UzCZM4r5W0A1vk8fMAT3Kf2X11FC0gMybqsFN_nT8xxDR0N04GWsvIX57OUBtALut1UpbQQdIJTcGJDWVdtdv--di0F-FL9VVPnd6XWZsi3hxd6Zpp2laCKKmUR8MXgsEccrnI0zNqJTO7ZYLJx_lx4Fvt-bBgmyRA2us5usWSdTNKjxuMHrCV4t2OqacGydC4HyCaHpMJy2Ek4qpYVODQM4BflkVK9v-1dXNmWUUnJtSuq_bhh6Q1DahwjtFKSRZYcnVSWtkN1yqAVIK6M0cb1EXh5x13H_sUvRw-FynwE)
Uses the R `polyroot` function to find the (limited-precision) root `a`, then for each element `n` of the sequence, divides `floor(a)`-`ceiling(a)` into `n` steps and returns the one with the smallest absolute result after applying the polynomial.
The final result is still limited by R's precision\*, but the approach should work in principle, and is not affected by the limited-precision of the `polyroot` function (as long as it is correct to the nearest integer).
The limit as `n` tends to infinity is the true real root of the polynomial; however, successive elements of the sequence may have increasing absolute differences from the true root, depending on whether partitioning the interval into `n-1` or `n` steps allows a better solution. For a convergent-at-every-step sequence, divide into `2^n` instead of `n` steps, for 4 more bytes: try it [here](https://ato.pxeger.com/run?1=TY_PSsMwHMfP21P8xigkLmVNZSDDHj14URjztK0sxmQLpMlMUm1PPoUnL_PgQ-1tTN0KEkLgl8_3z-_r2x1PH9vRtpC14UFZgxoSrC6oSGmG2bNHDb6NAxiDfRPu3akgIPKAtN0pznT68LjE0KshWHAi1M7AcvF0B0oCc7u6EiaA8uArpjUIY-vdfjh01gYvXoufOsj05lSuY7YhrDhY3XZ_MZrwYiEQW43uK8TwBifThE6yeV6aabyYr6x7EQ55djjoFnGyRi1ukqukLaMxGjV42uIyx5sV3VxSPjv3gqM0J1k8FMfNuBVSKq5iSw9WQppPmvJ6eHGlczojl66k-WuHYTAGqZwPQGcgtKh6aWRqYbjol0MdTvIsKgZRk2dh3_P_8XO54_H8_gI).
---
(\*) Note that this approach is actually *very* limited by R's precision, as the `a[!Im(a)]` part of the code (=get non-complex roots) fails quite easily due to floating-point inaccuracies: the test link overcomes this by redefining R's ``!`` (logical-NOT) operator to return `TRUE` as long as its argument is sufficiently small.
[Answer]
# JavaScript (ES7), 74 bytes
*-26 bytes (!) thanks to @CommandMaster*
A port of [@CommandMaster's method](https://codegolf.stackexchange.com/a/258023/58563).
Expects `(p)(n)` where `p` is the coefficient list from lowest to highest.
```
p=>g=(n,m)=>n?g(n-1,p.reduce((q,c,i)=>q+c*(v=Math.tan(n))**i)<0|v>m?m:v):m
```
[Try it online!](https://tio.run/##TY47DoMwEER7TuFylxhkSBGJxFClzAkQhWXMJ8I2v7jK3QkBEUXaYvbNaDRP4cQkx7afA2NLtVR86XlaczBUI09NVoMJItqHoypfUgEMVNJ2dYaT9MHxh5ibcBYGDKLvt3hjb5fqTCcOE71cc4@QnESUsO2CmBT0QJc/zX6J9YkOI97RecdHxRbwCi@s7HgXsoGe8JRIaybbqbCzNVTw3evUOClAhIgxhojLBw "JavaScript (Node.js) – Try It Online")
### Commented
```
p => // p[] = list of coefficients
g = ( // g is a recursive function taking:
n, // n = counter
m // m = minimum result, initially undefined
) => //
n ? // if n is not equal to 0:
g( // do a recursive call:
n - 1, // decrement n
p.reduce( // using q as accumulator,
(q, c, i) => // for each coefficient c at index i:
q + // add to q:
c * ( // c multiplied by v ** i
v = // where v = tan(n)
Math.tan(n) //
) ** i //
) // end of reduce()
< 0 | // if the evaluation of the polynomial is negative
v > m ? // or v is greater than m:
m // keep m unchanged
: // else:
v // update m to v
) // end of recursive call
: // else:
m // stop and return m
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 8 bytes
```
∆P≬İ⌊=cḞ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuItyIiwiIiwi4oiGUOKJrMSw4oyKPWPhuJ4iLCIiLCJbMSwgMCwgMCwgLTJdXG44Il0=)
I think this is valid. Takes list of coefficients and then the nth term to generate.
## Explained
```
∆P≬İ⌊=cḞ
∆P # Get roots from polynomial with coefficients. Returns a list of exact algebraic numbers because sympy.
≬ c # Get the first root where:
İ⌊= # the root is real
Ḟ # format to n decimal places
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
⊞υΣ↔θ⊞υ±ΣυFη«≔⊘Συζ§≔υ‹↨θζ⁰ζ⟦Iζ
```
[Try it online!](https://tio.run/##NY2xCsIwEIZn@xQZL9CCXVycqouCSMExdIhtbAppgr2kSMVnj1cxcDfc/33c32o5tU6aGOuAGkLObmGE6o7OBK/gyTnfZwldVS8pXI3wAw83MdCcvbNNhTj0Fk7SzKpLSs4Wsv6s8mfbqdf66KIQ4SCRClYlZ9uk1tNgPYijRA8Lbyj6xChESUqago6yod01sZjNFw "Charcoal – Try It Online") Takes the polynomial and a number of terms (but because it uses floats there's no point asking for more than 50). Assumes that the leading term is positive. Explanation: Simple binary search over the bound of roots given by @CommandMaster.
```
⊞υΣ↔θ
```
Set the upper bound to the sum of the absolute coefficients.
```
⊞υ±Συ
```
Set the lower bound to the negation of the upper bound.
```
Fη«
```
Repeat `n` times.
```
≔⊘Συζ
```
Calculate the average of the bounds.
```
§≔υ‹↨θζ⁰ζ
```
Evaluate the polynomial at that point and update the appropriate bound.
```
⟦Iζ
```
Also output the next approximation.
] |
[Question]
[
As some of you may remember, Peter, who was a [picky eater](https://codegolf.stackexchange.com/questions/225962/peter-is-a-picky-eater) is now puzzled Peter.
This time Peter got some puzzles as a present from his Aunt. He has tried a lot, but has failed to solve the puzzles. Peter needs your help to solve them.
Each one of the puzzle has 2 pieces. To solve the puzzle, you must tell the number of ways piece 1 can fit into the empty spaces in Piece 2. We can safely assume that both the pieces cannot be rotated.
For example,
```
Piece 1:
.#
##
.#
Piece 2:
#..#######
#.##..####
###..##...
####.#####
##.#######
##......##
##.....###
########..
```
There is only 1 possible way to fit Piece one into Piece 2:
```
#..#######
#.##*.####
###**##...
####*#####
##.#######
##......##
##.....###
########..
```
Hence, the output must be \$1\$.
## Input
You may take the input as a binary matrix of 1's and 0's, or as a string with empty spaces and filled spaces as characters of your choice.
Piece 1 is not always a solid piece, it may or may not be connected.
## Output
An integer \$n\$ for the number of ways to fit Piece 1 in Piece 2. If there are no ways, you may return \$0\$ or any other non-integer value.
## Test Cases
```
All inputs formatted as a 2d array, with each inner array representing a row in the puzzle. 0 represents empty gap, 1 represents filled space.
Piece 1: [[0, 1], [1, 1], [0, 1]]
Piece 2: [[1, 0, 0, 1, 1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 0, 0, 1, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 0, 0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0]]
Output: 1
Piece 1: [[1, 0], [1, 1], [0, 1]]
Piece 2: [[1, 0, 0, 1, 1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 0, 0, 1, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 0, 0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 1, 1, 0, 1, 1, 0, 0]]
Output: 1
Piece 1: [[1, 1]]
Piece 2: [[0, 1, 0, 1], [1, 1, 0, 0], [0, 0, 0, 0], [1, 1, 0, 1]]
Output: 4
Piece 1: [[1, 1, 1]]
Piece 2: [[0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0]]
Output: 4
Piece 1: [[0, 1, 1, 0, 1, 1, 0], [1, 0, 0, 1, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0]]
Piece 2: [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]
Output: 1
Piece 1: [[1, 0, 0], [1, 1, 1]]
Piece 2: [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
Output: 42
Piece 1: [[1, 0, 1], [1, 1, 1]]
Piece 2: [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
Output: 35
Piece 1: [[0, 0, 1], [1, 0, 0], [0, 1, 0]]
Piece 2: [[1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1]]
Output: 1
Piece 1: [[1]]
Piece 2: [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
Output: 0 (Or any other non-integer value)
```
## Winning criteria
this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer, in each language wins.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 bytes
*Thanks to [@att](https://codegolf.stackexchange.com/users/81203/att) for pointing out a mistake, now corrected.*
```
,XP!]&2Y+~z
```
Inputs piece 1, then piece 2 as binary matrices.
[Try it online!](https://tio.run/##y00syfn/XyciQDFWzShSu67q//9oQx0Fw1iuaAMgpaMAIq1BDAjbwBpMwthwccNYAA) Or [verify all test cases](https://tio.run/##7VSxCgIxDN39irq4eEPimtUPcHBQjsK56@bk4K9Xexxpm@SCCoKDEErbJO8lL7SX0/WchtQddsu42hzX91va7lMPXUAKOK55Hxf98wCjobYxlF0yjMoeVBhQAwUWMrq8Baoyx6urEpbDpoZ/SgP8vgagNch9AztrPKog6zlNeZwKVSroVMZv@KmRiiGMyJoETAb/ssyV5bAhWxihK7okvlcXqIeGL@dKxrZmvyPTiz4v64d//T7UT74QhitPaf5DmPtDzJ5QlVNGhpKNwhvH@AA "MATL – Try It Online").
### Explanation
>
> [Convolution is the key to success](https://codegolf.stackexchange.com/a/230445/36398)
>
>
>
This computes the 2D-convolution of piece 2 and a vertically and horizontally flipped version of piece 1, keeping only the results that assume no zero padding of piece 2. What the convolution does is:
* Piece 1 is flipped vertically and horizontally, which undoes the previous flipping of this piece; then
* it is shifted in the two dimensions, traversing all positions so that it doesn't move "outside" of piece 2. For each position,
* corresponding entries of both pieces are multiplied, and
* the sum of all those products is computed.
Piece 1 fits in a given position if and only if the sum computed as above is 0, meaning that all `1` entries of piece 1 coincide with a `0` of piece 2.
```
, % Do twice
XP % Implicitly inputs piece 1 the first time. Flip vertically
! % Transpose
] % End
&2Y+ % Implicitly inputs piece 2. 2D convolution, only 'valid' part
~z % Number of zeros. Implicitly displays the result
```
[Answer]
# [J](http://jsoftware.com/), 23 bytes
```
4 :'+/,x(-:y<]);._3~$y'
```
[Try it online!](https://tio.run/##zVKxTsMwEN39FScO1bFoHzQwOWRCYmJirSoG1BaxkJEu/fVg@@zEtVwJiQVLsc/Oe@@ez/c5XkHvqbekaUl3ZN23Aj29vjyPD2T1ze3yu1nZ4@PWdHi7P10f9WjUwRM2dvf@8UXNptt2e7NoNOtF70CtOSk1rHsrcgqsmP1s1NBOpwywDBdy3DlgiAD4kBEBPGP9P3hMCiMtDEdzSdZ0oKHNLTD@boF/YQGFhTMPRXYwREBBcom9KrOkwlORqHUWxE64pcenfamEpJOvF4xITaoSgR3qwbNQFkZ5qRgXp4IMCplYjDjHXjLG/9NYfCjPKXqP576aWi2lZJ5Wc37PikhlzryMPw "J – Try It Online")
(Tacit for 24b: `[:+/@,](]-:<)"2([;._3~$)`)
For each tile `u;._3~` of the size of the piece `$y`, is no position blocked? (Tile still equal to itself `-:` when comparing each position from the piece with the tile `y<]`?) Sum the result `+/,`.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 24 bytes
Anonymous infix lambda taking Piece 1 as left argument Boolean matrix of needed positions, and Piece 2 as right argument Boolean matrix of *available* positions. Requires 0-based indexing (`⎕IO←0`).
```
{≢⍸∧/⍵[(⍳1+⍵-⍥⍴⍺)∘.+⍸⍺]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXIenAalqjUe9W8FolyYQgxGEv7VW4VHvXCBeqlCQn1OZlpmTo5CWX6QQ4umvXqxgaK5nqPCobZKCoYWewf/qR52LHvXueNSxXB@oMRpo5mZDbSBLF2hH7xaw2R0z9LRBSnp3xdb@TwPa/Ki371FX86PeNUAVh9YbP2qbCHRacJAzkAzx8Az@H5CZmpxqCFIIlvEK9vdTj4420FEwjNVRiDaE0mB@rDoXWLURUHUdinKgMgMwMsREUGPgkugKYdZgSELYBijyhpi2IOTx2o8wEAnhlcfmPjQEdh8sWAwV0hQg4QOOUUMuLuxha4jkqSETtob0ClsDSsMWX1gawK1AdRk0GjBCBSVq0Nxggs8NBJ1hgOIMA6zOINViA8wwRDHfEMVabKqJcLIBDtcSFCYnm6AmUdKch@4gtHRoSMDBhOSxeRgzqRuSpB/dZnT3E/IfVnlDgvbjSmdG@KPGcDRqBipqjE3xlAFo5QqSG/DXMoYECn/cdQaOoDLE4kP09EJ0aUCs2zGqFCIEcDjGAAA "APL (Dyalog Unicode) – Try It Online") (using a polyfill for `⍥` since TIO is stuck on version 17.1)
`{`…`}` "dfn"; left and right arguments are `⍺` and `⍵`:
`⍵[`…`]` index into `⍵` to get the elements at the following positions:
`⍸⍺` list of true-coordinates in `⍺`
`(`…`)∘.+` outer sum (i.e. all addition combinations with):
`⍵-⍥⍴⍺` the difference in shapes between Piece 2 and Piece 1
`1+` increment
`⍳` all indices of an array of that size
`∧/` AND-reduction along the trailing axis (computes where all required slots are available)
`⍸` indices of available placements
`≢` tally those
---
I'm a bot, so [my owner](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m) posted this for me.
[Answer]
# JavaScript (ES6), 95 bytes
Expects two binary matrices as `(a)(b)`.
```
a=>b=>b.map((r,y)=>r.map((_,x)=>t+=!a.some((r,Y)=>r.some((v,X)=>v&(b[y+Y]||0)[x+X]!=0))),t=0)|t
```
[Try it online!](https://tio.run/##7VTNTuMwEL7nKYZKbGzVG9n8XBalnNgX4AJKo5WbuhAUkmJnq1aUN1hpLxzhPXgeXmAfobhJ2vwTVkKIA9Ioyfib@Wb8TewrPuPKk/40/h5GY7Ga2CtuD0barGs@RUiSBbYHMnV@kbl24r69wy0VXYs1fJ7AqTcjZ9qbfUMjZ9E/d5dLip15/8zdsSnGmMT6tYxXUtz89qVA5kSZ2JKCj3/6gThdhB6i2Iqj01j64QXClpoGfox6w3AY9rA1ieQJ9y6RAnsAtwaAA5zAiICYT4UXizG4YIPKssxhqMnXXYsZD/CRjpdCp8IEcYxGyYIXhSoKhBVEF6i3q2BX9cg6iqShds58DOa/p7/PD/f6acIPMJ8f/5ia4w6vHIcSYC4Bh2XvxHcNZ71AE2N1yxK2YDVwQ1gD029awlm9So6/Wj8nLNireFN/FUv6cw1mZBp8YnHYR4lDW8RJxaDbmDJ1plhtW5mKBxuSAg8t8dBGniyT1psrpbESW1N0qSZtKde5XPhVysNr468yVmbBOip24U0d18fN/iu/Wrnaf9f@GnHWWV9Pei/Xln1p@67a7h8aWxGLJ65AvbnrWMcV1H5zteyVNbSYjzY9UPXitZvpDQuuQV8A "JavaScript (Node.js) – Try It Online")
Or [92 bytes](https://tio.run/##7VVLbtswEN3rFBMDjkiYFcgm3SSQs2oukE0CWQhomXYVKJJLKoaNtDco0E2XzT1yHl8gR3BpSbb@VgMEQRcFBpSHb@bN8I1M3fEFV5705/GHMJqIzdTecHs41mbd8zlCkqywPZSpc0uW2okH9hG3VHQvtvBNAqfeglxrb3E8dlaDG/fCcpaDa/fIphhjEuvHt3gjxdcHXwpkTpWJLSn45NIPxNUq9BDFVhxdxdIPZwhbah74MeqNwlHYw9Y0kp@59wUpsIfwaAA4wAmMCYjlXHixmIALNqgsyxyFmnzbsljwAJ/reCl0KkwRx2icbHhRqKJAWEE0Q72@gr7qkW0USUPtnPkCzJfnn@vfv/RqwhmY66cfpub4jjeOw1zXSFdqGDuX6pVtXUqAuQQclj0TP0kgQBNjdcsS9mA1cEdYA9PftISzepUcP1g/JyzYQbypv4ol/WXisEKv/6A47L3EoS3iZO/SPqZMnSlWO1am4umOpMBDSzy0kSfLpPXmSmmsxNYUXapJW8p1bhdelfLw2virjJVZsI6KXXhTx/Vxs1flVytX@@86XyPOOuvrSX/MtWX/tX1TbU8@GXsRi/@4AvXurmMdV1D7zdVyVtbQYj5aln@nDt98f7Ghv3p/AA) with optional chaining (doesn't work on TIO).
[Answer]
# [Python 3](https://docs.python.org/3/), 85 ~~109~~ bytes
```
from numpy import*
from scipy.signal import*
lambda a,b:sum(correlate(a,b,'valid')<1)
```
`correlate` needs `scipy.signal` for 2d arrays and will give back `0` for matching positions, using `numpy.count_nonzero` with the condition will give back the number of zeroes which is the expected result.
Edit1: changed `count_nonzero` to `sum`, removed `array` conversions
[Try it online!](https://tio.run/##7VZLboMwFNznFN4BFa38knYTNWfoAaIsHOIkSGBbxlTl9JRAQvAHSJWPsqhkCfCM/ebN8wdRqD1ns7LcSp4ilqeiQHEquFQvk7ori2JRvGXxjpGkRRKSrjcEkXA9z/LUj7iUNCGK@lVP6H2TJN54wScE5XZxKXUyETGNKCzQcolDBKsQLeH4rL9XDWF6IFQArhvY7TiwBU3iaWILbN6xhoMd5YwPxj9P2GmDuEuf0Wp9lREyZsr3eK5EruZeuPUb78LGoSA4MeiPoJGiG9RSMyV9D7yWovkOnfSf2Hd4lO/4cb7rPuM2vK76WBTLsVOhrtT3PqDPIRFrErFT4v1EYbtKmhLQBLrYznRwTyaj3ffdlvoGGZNuijXWPYwkM4a7zLC3FvxpvBnZ1D@WnxOH0fg3WJ/TwbLBf9mesmyzj/5zxTjVOmrN2xBGLqn@u63HRnBk31k99zph@vOyrsULOq4XipH/JRFhBeJqTyVinL1WfLqr3qt/xpwGh0zKXw "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
ṡ€ZL$}¹ṡL}Z€Ẏa€¬Ȧ€S
```
[Try it online!](https://tio.run/##y0rNyan8///hzoWPmtZE@ajUHtoJZPvURgG5D3f1JQKpQ2tOLANSwf8PL9cH0v//R3NxAhFndLShjoIBGBliolgdBag8RABdIVQeUxLCNkCRN8S0BSGP136EgUgIrzw296EhsPtidcBhYICkFkSD@bFcnCD2IAokQ3oFkgG2QDJEcivWQDKA60W1EqoYw7sQA@CGYxhmgGKYAVbDkLTjNMEAh2aCwkipAy1YUNxkiOJUbKoJOAvdIWixZUjAoYTksXkUM0EYkqQf3WZ09xPyH1Z5Q4L2IyVF1JwzGsQ0CWJDXEGMtxwiVLzh8KchFufB7dZBilnkIgHJv7gdiFHEESGAXjBxxQIA "Jelly – Try It Online")
-1 byte thanks to Nick Kennedy
```
ṡ€ZL$}¹ṡL}Z€Ẏa€¬Ȧ€S Main Link; accept piece 2 on the left and piece 1 on the right
ṡ€ Get all overlapping slices of piece 2 of length
ZL$} Width of piece 1
¹ (Identity)
ṡ Slice this into overlapping pieces of length
L} Height of piece 1
Z€ Transform each to get it to the correct orientation
Ẏ Flatten once; we now have a list of 2D blocks in piece 2
a€ Logical AND with piece 1 (vectorizing); gives intersection areas
¬ Logical NOT (vectorize)
Ȧ€ For each chunk, check if all are truthy (i.e. none were truthy initially; 1 if it fits, 0 otherwise)
S Sum; count number of positions that fit
```
[Answer]
# [Python 3](https://docs.python.org/3/), 138 bytes
```
lambda a,b,l=len:sum(all(q&p^1for Q,P in zip(a,b[i:])for q,p in zip(Q,P[j:]))for i in range(l(b)-l(a)+1)for j in range(l(b[0])-l(a[0])+1))
```
[Try it online!](https://tio.run/##7VXLToQwFF3LVzSzMCXWpNfRDQl@g64rJhDBgXQYBnChP4@lw6MvBk2McWHSpHDO7bm3p6/qvd0dym2XhU8dj/fJS4xikhAe8rQMmrc9jjnHx8vqGbJDjR7JA8pL9JFXWESxPIj8Hj6SaoRFBCsELPG8R@u4fE0xx4l/zXHsX4GkCo1iNJJs34sAv2vTpm1QiJjHGKMEQUQQg6GX/xERlECobGC3YcREmoGjokWevqnGg51l5s/mnwWVdpZ31Wc0WZ9wQAR5vUOg1PsXHYLfcoiecWhwhE6Buv7gmzW30ctbRUkVo5oYdYopw6ldqjYUNEVXtJ6YLuRchY3to6/nYhJT1lgfWEm7xrvKtrcAfGu8mdmsf21@Th5W8/drfqMZDP8G/7DB27v5VBmHUJGfbkJYuaCW77WFCYOjTmWBp/PlqMC6vL4ACBUaeZHnyceVFCTtX1H5VgbeRVXnZYszLAifoE14vyEoDcMT4Hef "Python 3 – Try It Online")
## Ungolfed :
```
def f(a,b):
s=0 # intitialise the counter
for i in range(len(b)-len(a)+1): # iterate through all the lines
for j in range(len(b[0])-len(a[0])+1): # iterate through all the column
# verify if the piece can fit
if all(a[k][l]&b[i+k][j+l]^1 for k in range(len(a))for l in range(len(a[0]))):
s+=1 # increase the counter
return s # return the counter
```
[Try it online!](https://tio.run/##7VVda4MwFH1efsWlD8NgBrnr9lJwfyRkYFncbMUWdQ/79S5JrTUf1g3G2MMgaLzn5NybE5McP7q3Q73u@xdVQJHkbEs3BKDNuH4WhwZKKGto8vpVJZWqky29M6@cpmiJJ9LOIwkuB57pjVSAsoC8qnR4L0Ulb7eiTHVvl1byGa3S3lXKKTXRyosaVTqK6nLTDPVHo7r3poa271TbtZCBIEIIzgAlA4HD235LpiEd4bZh2IYRI@gTz4oBeOpzB8cwywW/mv8iOGlX8Vh9XrP1aQc0iRiHcFLvX3QIf8shfsWhwRE@El39wbdgbmcvHyZKUzHuiPGo2GQ4D0t1hqKjGGO7iflMzsWw9/u46zmbxJf11gcX0i7hsbLDXwC/Nd7P7Ne/NL8ojov5zZrfOwbjv8E/bPD68bKrvE04kR9PQlw4oObPtZkJY6TOyQKP@ytSQXB4fSGgVbgkkhB7r7MdU@ZatXflhtwcm7LukiLRAGWwyp5WDFSWnQK0/wQ "Python 3 – Try It Online")
* `q&p^1` will be equal to 1 only if at most 1 of `q` and `p` is equal to 1
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 165 bytes
```
(a,b,d=b[z=0][L='length'],F=a.flat())=>b.flat().map((e,i)=>z+=b.slice(i/d,i/d+a[L]).flatMap((l,c)=>l.slice(i%d,i%d+a[0][L])).every((l,c,A)=>A[L]==F[L]&&!l|F[c]<l))|z
```
[Try it online!](https://tio.run/##7VVdT8IwFH3vr5gPsDXU2aI@aUmIkSf8BbUJZXQwUzfCFhIRfzt2Y2PfTBNjfDApo9xzeu7tuax9EVsROhtvHV36wUIeXHqwBJqjBZ2zHcWcTamppL@MViZHEypsV4nIgpCO5unUfhVry5LI07HdgM7tUHmOtLyrBdKfgWBTDhPqU8xTyNE8lZF6mtSLSXEmDqEtt3LzltDQWBPHOkrpRD/7/Qu1nzCH3ysI97uDE/hhZEQyjB5EKEODGjPGMDIIRwYj6XfymwMWB3AySH2kC05glZgJ1sDjHJdwUs@S42fz54KFcRZvqq8ykvo4ICD14A@bQ37LHNxiztEMfOKUpVPHattKXbzJRAo6uKSDG3XSlbheXGkZKak1sUs5cUu6znDhr1JuXpt@VbHSC9KRsQtvqrjebvKt9dXM1fq79teIk878utPD3Fvy7@2Pent9C04mFt@4gnR21pGOI6j95GrZK2koMW/t8YWqJ6@dTF8IcIBndrhWXmSZz/6zbx5vX6kMOjKkyqEysBVKTyGEdwCcbkzbDTaPwlmlpHcQ36iBkrYKlparo/pORvpJODQopVqeDTkEH/DwCQ "JavaScript (Node.js) – Try It Online")
This feels too long.
Calculate the number of items in flattened `b` (second piece) that satisfy the conditions: the `a`-sized tile with that item as the top-left corner is equal to `a` and fits in `b`.
Credits: @EliteDaMyth (see comments)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes
```
≔⟦⟧ηWS⊞ηιWS⊞υ⁺ι⭆θ#Fη⊞υ#IΣ⭆υ⭆ι⬤η⬤ν№⁺π§§υ⁺κξ⁺μρ.
```
[Try it online!](https://tio.run/##fU4xbsMwDNz1CsJcKEDlBzwFmTIUMJCxyGCkaSRUkR1LSvN7lXJsuFNvEI/kHXVn20/nofel7GJ010AfJwNWt@rHOn8BOoQxp2OaXLiS1tDlaMkacP8rsoHO50jOwGvz3o90N9Bgo7VYv4YJyG7iOm9VJ8pE@z4mOuYbbc7894zc3HlfQ9QSDOyHLLb5v1GG6RA@L09a6xrl28BT66W5GZh07RqugWa0pTAqRCWvQmZ8QSgunSxnxsyVIi8C3LR1x1Wz0sU2Q2zl7eF/AQ "Charcoal – Try It Online") Link is to verbose version of code. Takes input as two newline-terminated lists of strings of `.` and any other character. Explanation:
```
≔⟦⟧ηWS⊞ηι
```
Input piece 1.
```
WS⊞υ⁺ι⭆θ#Fη⊞υ#
```
Input piece 2, but pad it so that piece 1 can't accidentally wrap around (this is slightly golfier than calculating the positions that won't wrap around).
```
IΣ⭆υ⭆ι⬤η⬤ν№⁺π§§υ⁺κξ⁺μρ.
```
Count the number of possible positions of piece 1 in piece 2 where for all of the overlapping squares at least one of them is a `.`.
[Answer]
# JavaScript, 108 bytes
```
a=>b=>[...b.matchAll(`(?=${a.replace(/./sg,c=>[`[
21]{${b.search`
`-a.search`
`+1}}`,'.',1][+c])})`)].length
```
```
f =
a=>b=>[...b.matchAll(`(?=${a.replace(/./sg,c=>[`[
21]{${b.search`
`-a.search`
`+1}}`,'.',1][+c])})`)].length
testcases = `
Piece 1: [[0, 1], [1, 1], [0, 1]]
Piece 2: [[1, 0, 0, 1, 1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 0, 0, 1, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 0, 0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0]]
Output: 1
Piece 1: [[1, 0], [1, 1], [0, 1]]
Piece 2: [[1, 0, 0, 1, 1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 0, 0, 1, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 0, 0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 1, 1, 0, 1, 1, 0, 0]]
Output: 1
Piece 1: [[1, 1]]
Piece 2: [[0, 1, 0, 1], [1, 1, 0, 0], [0, 0, 0, 0], [1, 1, 0, 1]]
Output: 4
Piece 1: [[1, 1, 1]]
Piece 2: [[0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0]]
Output: 4
Piece 1: [[0, 1, 1, 0, 1, 1, 0], [1, 0, 0, 1, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0]]
Piece 2: [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]
Output: 1
Piece 1: [[1, 0, 0], [1, 1, 1]]
Piece 2: [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
Output: 42
Piece 1: [[1, 0, 1], [1, 1, 1]]
Piece 2: [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
Output: 35
Piece 1: [[0, 0, 1], [1, 0, 0], [0, 1, 0]]
Piece 2: [[1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1]]
Output: 1
Piece 1: [[1]]
Piece 2: [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
Output: 0 (Or any other non-integer value)
`.trim().split('\n\n').map(t => t.split('\n').map(l => JSON.parse(l.replace(/^.*:|\(.*$/g, '')))).map(([a, b, e]) => [a.map(l => l.map(n => '12'[n]).join('')).join('\n'), b.map(l => l.map(n => '12'[n]).join('')).join('\n'), e]);
testcases.forEach(([a, b, e]) => { console.log(f(a)(b) === e, f(a)(b)); });
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes
```
Count[ListCorrelate@##,0,2]&
```
[Try it online!](https://tio.run/##7VVdS8MwFH3vryhRRCGDZOrLxsZk7kEQHM63GKSWTANdW7oMBqX967VfW9skbeeD4oMQ6G1ucs7J6c3txhKfbGMJblvJepLMvZ0ryCPfirkXBMyxBJudnUEEh/QiufeIEXLoRROHu2xshBZ8jyYv3mLvB2y75Z47W4mAux8r3@GCFPEz8x3LZoTDECw5s5kJ4vgtjsHIBIMpANAEJAvCLKJZFIGIQvDqAjo2limEIGuSMqVz5iWAHgRXgBowzDTAgmOxF4FlC3K@sgPuiwfX34kik@GkSIPpneNk8dNOpLmcOp2hEU0KTXhkEoKgiSk0CS6f@Ts1ihXDbEWaQfnA6ih3HpPywgOykixi1MhjlaXKd/JXgLXRmdfpk0aujxoH97Bh1GzDNfF/2Tb8W7ahU22TbELH3U3S0lTlwKXRB/gbBV7HgBoMSMvQhonUEzZwcANet1qvBrUI6Z3uKslmbfQyy1zSN8c9WvryurOoZYW/tV9mlvX3nU@bx738teoYalzH/67/rOvXt/KllC50jUvpw7inPbZ31RYXsEZ89fVbrmeHLKWfnjBR8SC1xZa@qKVY@1cdZX4B "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
Modern British number plates (a.k.a. registration marks or license plates) use the format `AANNXXX` where `AA` is a "DVLA memory tag" (basically a location code), `NN` is the age identifier, and `XXX` is three random letters.
Your task is to, given a date, generate a random valid number plate with a date code matching the supplied date. Simplified from the [actual implementation](https://data.gov.uk/data/contracts-finder-archive/download/1236323/960d4b76-2263-40d2-b71c-9a0f4d85692a), this is how to generate them:
* The memory tag will just be generated randomly:
+ First letter: random from `ABCDEFGHKLMNOPRSVWY` (the alphabet, minus `IJQTUXZ`)
+ Second letter: random from `ABCDEFGHJKLMNOPRSTUVWXY` (the alphabet, minus `IQZ`)
* The age identifier follows this pattern:
+ 1st September 2001 - 28th February 2002: `51`
+ 1st March 2002 - 31st August 2002: `02`
+ September 2002 - February 2003: `52`
+ March 2003 - August 2003: `03`
+ ...
+ March 2010 - August 2010: `10`
+ September 2010 - February 2011: `60`
+ March 2011 - August 2011: `11`
+ September 2011 - **29th** February 2012: `61`
+ ...
+ September 2020 - February 2021: `70`
+ ...
+ September 2049 - February 2050: `99`
+ March 2050 - August 2050: `00`
+ September 2050 - February 2051: `50`
+ March 2051 - August 2051: `01`
* The 3 random letters are picked from `ABCDEFGHJKLMNOPRSTUVWXYZ` (the alphabet, minus `IQ`)
## Rules
* You must output in uppercase with no spaces or dashes between letters. However, trailing newlines, or any other output from your language that is not easily suppressible, are allowed
* For the purposes of this challenge, "random" means picked pseudo-randomly with any distribution as long as all possibilities have a non-zero chance of occurring
* You may assume the date will always be in the range 1st September 2001 to 31st August 2051
* The date can be in any reasonable input format (for example, your language's native date object, `april 28 2021`, `(28,4,21)`, `1619615864` (a Unix epoch timestamp))
* You may ignore leap seconds, daylight savings time, and timezone issues (just assume the date is always in UTC)
* You may use [any reasonable I/O method](https://codegolf.meta.stackexchange.com/q/2447)
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
## Test cases
These are to test the date conversion alone.
```
23rd September 2001 51
1st March 2006 06
29th February 2012 61
1st December 2021 71
11th October 2049 99
19th January 2051 50
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 48 bytes
```
Ṗḅ12_3:6d2Ṛ%50ḅ50ṾŻṫ-“IQ“““Z“JTUX”;\ØAḟⱮ$X€ŒH¤jṚ
```
[Try it online!](https://tio.run/##y0rNyan8///hzmkPd7QaGsUbW5mlGD3cOUvV1AAoACR27ju6@@HO1bqPGuZ4BgIJCIoCYq@Q0IhHDXOtYw7PcHy4Y/6jjetUIh41rTk6yePQkiygEUBD91kD1Sno2imA1B1u5zI1LDDSMdaxfLijC4R2TrMGajA83A4kI/8DAA "Jelly – Try It Online")
A full program taking the date as a list of integers `[y,m,d]` and printing the numberplate.
Thanks to @JonathanAllan for pointing out a couple of errors!
[Answer]
# JavaScript (ES6), ~~121~~ 116 bytes
Expects `(month)(year)`. The day [is ignored](https://codegolf.meta.stackexchange.com/a/12442/58563). Returns an array of characters.
```
m=>y=>[...'9512444'].map(n=>((y-(m<3))%50-50*~-~(m<3|m>8)+n)[n]||'ABCDEFGHKLMNOPRSVWYJTUXZ'[Math.random()*(28-n)|0])
```
[Try it online!](https://tio.run/##ddBdT8IwGAXge39Fb8xazEbbrUgTt0RFNOjEiN@EizKKaFi3jGlCsvDX57qNhDDZ3d48PTk53@JXrILkK05NFc1kPnfz0PXWrje2LMvgjFDHcYyJFYoYKteDcG3C8MxG6Jhhk@HWxtzo/yz0uuhEobGaZJlxfnHZu@pf39ze@ffDh8fRy@v74On57cMY@yJdWIlQsyiEqAVp11QowxOUB5FaRUtpLaNPOIeAI0gxJgiBdhuMZJzKcCoToG8AMoKO9rxd@k7lfZEEC207QH@wuO97qj2hle/LafIjkjXQp8J3Gvmk9LTu05PBtg4lhT9teqy9wys/DNKo4g7XfThv9CHaszp/IFRdhxHtGT7gccPjA/n2rt/uU2q9TzOf7/rd/Ys3//Wp9rf39rfrfBvlfw "JavaScript (Node.js) – Try It Online")
### Commented
```
m => // m = 1-indexed month
y => // y = full year
[...'9512444'] // split 9,5,1,2,4,4,4 as characters
.map(n => // for each value n above:
( // build a string:
( y - // subtract 1 from y if ...
(m < 3) // ... the month is January of February
) % 50 // reduce modulo 50
- 50 * // add 100 to the result for March to August
~-~(m < 3 | m > 8) // or 150 otherwise
+ n // coerce to a string
)[n] // attempt to extract the n-th character
|| // if n is greater than or equal to 4:
'ABCDEFGHKLMNOPRSVWYJTUXZ' // use this string instead
[ Math.random() // and extract a random character
* (28 - n) // in [0 ... 18] (if n = '9')
| 0 // or [0 ... 22] (if n = '5')
] // or [0 ... 23] (if n = '4')
) // end of map()
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 51 bytes
```
≔⁻⪪α¹⪪IQ¹ζ‽⁻ζ⪪JTUXZ¹‽⁻ζZ﹪%02d⁺﹪⁻θ›³η⁵⁰∧÷⁻⁸η⁶¦⁵⁰F³‽ζ
```
[Try it online!](https://tio.run/##dY5LC8IwEITv/ooQEBKI0AcVxVNBkAqF@gJRPISm2kBMNE176J@PqS2iB2FZ2Jlv2MlLqnNFhbVxVfGbRCmXdYV2D8ENogT4mID@gMkGdrcTWrwYZZpLg7ZUMnUfQu0HXe8Px1NP478sPMEvN1WsFgrBsRcwl8yEgwatTzwJWOmCmkKjkICy6xF5bsWSoUSaJW84KwZ21gEETHvm/eWqNEAhBj9dWudYew68yHdl3cwvdtKIFw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as `[Y, M, D]` (well the `D` is optional and unused). Explanation:
```
≔⁻⪪α¹⪪IQ¹θ
```
Make a copy of the uppercase alphabet with the letters `I` and `Q` removed.
```
‽⁻θ⪪JTUXZ¹
```
Print a random letter excluding the letters `J`, `T`, `U`, `X` and `Z`.
```
‽⁻θZ
```
Print a random letter excluding `Z`.
```
﹪%02d⁺﹪⁻θ›³η⁵⁰∧÷⁻⁸η⁶¦⁵⁰
```
Decrement the year if the month is January or February, reduce modulo `50`, then add `50` if appropriate, and format the result as two digits.
```
F³‽θ
```
Print three more random letters.
[Answer]
# Excel, 142 bytes
```
=REPLACE(CONCAT(MID("ABCDEFGHKLMNOPRSVWYJTUXZ",INT(RANDARRAY(7)*{19;23;1;1;24;24;24}+1),1)),3,2,TEXT(MOD(B2,50)+IFS(A2<3,49,A2>8,50,1,),"00"))
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnDcs_Tg7Us3YWljs?e=6qewDV)
Assumes Month in `A2` and Year is in `B2`
## Excel date as input, 161 bytes
```
=LET(x,EOMONTH(A1,-2),REPLACE(CONCAT(MID("ABCDEFGHKLMNOPRSVWYJTUXZ",INT(RANDARRAY(7)*{19;23;1;1;24;24;24}+1),1)),3,2,TEXT(MOD(YEAR(x),50)+(MONTH(x)>6)*50,"00")))
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 118 bytes
```
T`d`9d`.0?(?=/0[12])
T`5-9`d`^.
T`d`5-9`^.(?!./0[3-8])
L$`^..
==$&===
=
<26*=>
Y`=`L
I|Q
,4`[JTUXZ]
0`Z
<(\w)+>
$?1
```
[Try it online!](https://tio.run/##FYq7CsJAEEX7@xdClPjamdkYccExtZJGiKBRwwha2FiIYKF@e9x0955znrfX/XGRtp@W1rhP/msru1q4muMiLZT4KP48RGX5NETROHS@O41Li56LQTZdxKJMInFQTQaqCsXSz0e6wsHUSqy/W2Ays@Om2u3rM8BWA8v09B6OV0gKaVsW4kA@A8@JM2KBeGJPPsALdVswCyRMIshjHGH4Aw "Retina – Try It Online") Takes input in the format `YY/MM` but link includes test suite that trims off any trailing `/DD`. Explanation:
```
T`d`9d`.0?(?=/0[12])
```
Decrement the year if the month is January or February.
```
T`5-9`d`^.
```
Reduce the year modulo `50`.
```
T`d`5-9`^.(?!./0[3-8])
```
Add `50` to the year unless the month is in the range March to August.
```
L$`^..
==$&===
```
Remove the month and add placeholders for the letters.
```
=
<26*=>
Y`=`L
```
Expand each placeholder to a run of letters `<A..Z>`.
```
I|Q
,4`[JTUXZ]
0`Z
```
Delete the `I`s, `Q`s, the first `J`, `T`, `U`, `X` and `Z`, and the (originally second) `Z`.
```
<(\w)+>
$?1
```
Pick a random remaining letter from each run.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 60 bytes
```
«ÞTȮa⟩Ȯ2¬~Zyė∆₂ċ«⇧D3ȯ℅₴7ȯ℅₴6ɾ2+?ḟu=50*?50%+:₀<[\0p]₴2ȯDẊẊ℅ṅ₴
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%AB%C3%9ET%C8%AEa%E2%9F%A9%C8%AE2%C2%AC%7EZy%C4%97%E2%88%86%E2%82%82%C4%8B%C2%AB%E2%87%A7D3%C8%AF%E2%84%85%E2%82%B47%C8%AF%E2%84%85%E2%82%B46%C9%BE2%2B%3F%E1%B8%9Fu%3D50*%3F50%25%2B%3A%E2%82%80%3C%5B%5C0p%5D%E2%82%B42%C8%AFD%E1%BA%8A%E1%BA%8A%E2%84%85%E1%B9%85%E2%82%B4&inputs=4%0A2005&header=&footer=)
It's... not terrible, but still bad.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~167...~~ 164 bytes
```
lambda m,y,p=lambda e=0:choice('ZJTUXABCDEFGHKLMNOPRSVWY'[e:]):p(5)+p(1)+[str((z:=y%50)+49+(m>2)+50*(z<1)),'0'*(z<10)+str(z)][2<m<9]+p()+p()+p()
from random import*
```
[Try it online!](https://tio.run/##ZcxLb4MwDAfwez8Flwm7ycFJy1QQTNp72qvV3hvjwFpQkRaIMi7w5VmoVinSDpHjn/@27tptU88W2gxl8jl85@prk3uKd1wnf02RULTeNtW6AP/j@un57fjk9Oz84vLq5vbufrl6eHx5fffTIsow0hAg0yCQpT@tAeijpDsICNk8ZKCOJLKAptDHApH75O@@djpme8xSGas4zOwB3L9JaRrlmbze2FIp3Zh2OmhT1S2UEHpcEtlbk73MdnLoiBxFSEeEtCLdLUFW5qEr3JMUuJnFKEL8yxDi8As "Python 3.8 (pre-release) – Try It Online")
Similar technique to Arnauld: this was written by analyzing the age identifiers. If the month is between 3 and 8 (bounds included) add the `y%50` string with a leading zero if `y%50<10`. Otherwise, add either 50 or 49 to `y%50` and return that.
Takes two inputs: month and year (in that order).
I know that `from random import*` definitely saves bytes, but I'm yet to find a way to integrate that without breaking TIO and adding `f=` (which actually *inflates* the bytecount.)
*- ~~1~~ 3 bytes thanks to ovs.*
*+9 bytes to fix a bug.*
[Answer]
# [Julia](http://julialang.org/), 100 bytes
```
!n=rand(setdiff('A':'Z',"IQZJTUX"[1:n]))
m$y=!7*!3lpad((a=(m+12y-3)÷6)÷2%50+a%2*50,2,'0')*!2*!2*!2
```
[Try it online!](https://tio.run/##TdDRSsMwFAbg@zzF6XQ02SLkpGtHB70QRHAgIirIxi6yNmOVNRtpBvbJfAAfrKauFQ9Jrj7@P5yP86FU@Nm2gcmsMgWttSvK3Y6Gt@EiXIV89PC8Wr6@vY/WuDAbxkh13WTBfBJEh5MqKFUZraYom5uIfX8l/spxLKZqLCex4JKHImSTQF5O63TtashgTSikHACZf@AKZGQLeNEnp6uttiCFQOgmRg8jb5IeYu3gUdl835kE/kYkHkoOKIfE1O3hXm/tWdnGY5QXmPhE9FDiv8Q7nQ/FEvvEeQcFh1k6QPSJT7k7XuAs7WGa@mrk/q8D7KqXyvTN8ZAYC7IhZHe0QCveMCgN/O6DnGxp3MFQv1lGtCnaHw "Julia 1.0 – Try It Online")
] |
[Question]
[
A polygonal number is the number of dots in a `k`-gon of size `n`.
You will be given `n` and `k`, and your task is to write a program/function that outputs/prints the corresponding number.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest solution in bytes wins.
# Example
[](https://i.stack.imgur.com/5z3yt.png)
The `3`rd hexagon number (`k=6, n=3`) is `28` because there are `28` dots above.
# Testcases
Can be generated from [this Pyth test suite](http://pyth.herokuapp.com/?code=JEsmh*dttJ&test_suite=1&test_suite_input=10%0A3%0A10%0A4%0A10%0A5%0A100%0A3%0A1000%0A24&debug=0&input_size=2).
Usage: two lines per testcase, `n` above, `k` below.
```
n k output
10 3 55
10 5 145
100 3 5050
1000 24 10990000
```
# Further information
* In Wikipedia: <https://en.wikipedia.org/wiki/Polygonal_number>
* In Wolfram Mathworld: <http://mathworld.wolfram.com/PolygonalNumber.html>
* In OEIS Wiki: <http://oeis.org/wiki/Polygonal_numbers>
* OEIS sequences for **n**-gonal numbers for various **n**: **3** [(A000217)](http://oeis.org/A000217), **4** [(A000290)](http://oeis.org/A000290), **5** [(A000326)](http://oeis.org/A000326), **6** [(A000384)](http://oeis.org/A000384), **7** [(A000566)](http://oeis.org/A000566), **8** [(A000567)](http://oeis.org/A000567), **9** [(A001106)](http://oeis.org/A001106), **10** [(A001107)](http://oeis.org/A001107), **11** [(A051682)](http://oeis.org/A051682), **12** [(A051624)](http://oeis.org/A051624), **13** [(A051865)](http://oeis.org/A051865), **14** [(A051866)](http://oeis.org/A051866), **15** [(A051867)](http://oeis.org/A051867), **16** [(A051868)](http://oeis.org/A051868), **17** [(A051869)](http://oeis.org/A051869), **18** [(A051870)](http://oeis.org/A051870), **19** [(A051871)](http://oeis.org/A051871), **20** [(A051872)](http://oeis.org/A051872), **21** [(A051873)](http://oeis.org/A051873), **22** [(A051874)](http://oeis.org/A051874), **23** [(A051875)](http://oeis.org/A051875), **24** [(A051876)](http://oeis.org/A051876)
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
’;’;PH+
```
This uses the formula

to compute the **n**th **s**-gonal number.
[Try it online!](http://jelly.tryitonline.net/#code=4oCZO-KAmTtQSCs&input=&args=MjQ+MTAwMA)
### How it works
```
’;’;PH+ Main link. Arguments: s, n
’ Decrement; yield s - 1.
; Concatenate; yield [s - 1, n].
’ Decrement; yield [s - 2, n - 1].
; Concatenate; yield [s - 2, n - 1, n].
P Product; yield (s - 2)(n - 1)n.
H Halve; yield (s - 2)(n - 1)n ÷ 2.
+ Add; yield (s - 2)(n - 1)n ÷ 2 + n.
```
[Answer]
## [Hexagony](https://github.com/mbuettner/hexagony), 25 bytes
```
?(({"+!@/"*'+{/?('*})/2':
```
Unfolded:
```
? ( ( {
" + ! @ /
" * ' + { /
? ( ' * } ) /
2 ' : . . .
. . . . .
. . . .
```
Reads `k` first and `n` second (using any separator).
[Try it online!](http://hexagony.tryitonline.net/#code=ICAgPyAoICggewogICIgKyAhIEAgLwogIiAqICcgKyB7IC8KPyAoICcgKiB9ICkgLwogMiAnIDogLiAuIC4KICAuIC4gLiAuIC4KICAgLiAuIC4gLg&input=MjQgMTAwMA)
### Explanation
The program is completely linear, but as usual in Hexagony, the order of execution is all over the place:
[](https://i.stack.imgur.com/Gw1fu.png)
The paths are executed in the order *grey*, *dark blue*, *red*, *light blue*, *dark green*, *pink*. As you can see, the three `/` only act to redirect the flow. Also, the `.` are no-ops. Stripping all hexagonal fanciness, the resulting linear program is:
```
?(({?('*})"*'+{2':"+!@
```
This computes the standard formula

like most of the other answers. It does so using the following five memory edges, with the memory pointer (MP) starting as shown in red:
[](https://i.stack.imgur.com/aCmmr.png)
Here's how this is done:
```
? Read integer input s into edge A.
(( Decrement twice to get (s-2).
{ Move the MP forwards onto edge B.
? Read integer input n into edge B.
( Decrement to get (n-1).
' Move the MP backwards onto edge C.
* Multiply edges A and B to store the result (s-2)(n-1) in edge C.
} Move the MP forwards onto edge B.
) Increment to restore the value n.
" Move the MP backwards onto edge A.
* Multiply edge B and C to store the result (s-2)(n-1)n in edge A.
' Move the MP backwards onto edge D.
+ Add edges E (initially 0) and A to copy (s-2)(n-1)n into edge D.
{ Move the MP forwards onto edge E.
2 Set the memory edge to value 2.
' Move the MP backwards onto edge A.
: Divide edge D by edge E to store (s-2)(n-1)n/2 in edge A.
" Move the MP backwards onto edge C.
+ Add edges A and B to store (s-2)(n-1)n/2+n in edge C.
! Print as integer.
@ Terminate the program.
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 8 bytes
Code:
```
D<LOIÍ*+
```
Explanation:
```
D # Duplicate the input
<LO # Compute n × (n - 1) / 2
IÍ # Compute k - 2
* # Multiply, resulting into (k - 2)(n - 1)(n) / 2
+ # Add, resulting into n + (k - 2)(n - 1)(n) / 2
```
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=RDxMT0nDjSor&input=MTAKNQ).
[Answer]
## [Labyrinth](https://github.com/mbuettner/labyrinth), 13 bytes
```
?::(*?((*#/+!
```
[Try it online!](http://labyrinth.tryitonline.net/#code=Pzo6KCo_KCgqIy8rIQ&input=MTAwMCAyNA)
### Explanation
Due to its single-character commands (which are merely a necessity of the 2D-ness of the language), Labyrinth can be surprisingly golfy for linear programs.
This uses the same formula as several other answers:

```
Op Explanation Stack
? Read n. [n]
:: Make two copies. [n n n]
( Decrement. [n n (n-1)]
* Multiply. [n (n*(n-1))]
? Read s. [n (n*(n-1)) s]
(( Decrement twice. [n (n*(n-1)) (s-2)]
* Multiply. [n (n*(n-1)*(s-2))]
# Push stack depth, 2. [n (n*(n-1)*(s-2)) 2]
/ Divide. [n (n*(n-1)*(s-2))/2]
+ Add. [(n+(n*(n-1)*(s-2))/2)]
! Print. []
```
At this point, the instruction pointer hits a dead end and turns around. Now `+` is executed again, which is a no-op (since the bottom of the stack is implicitly filled with an infinite amount of zeros), and then `/` attempts a division-by-zero which terminates the program with an error.
[Answer]
## JavaScript (ES6), ~~24~~ 22 bytes
```
(k,n)=>n+n*--n*(k-2)/2
```
Explanation: Each n-gon can be considered to be n points along one side plus k-2 triangles of size n-1, i.e. n+n(n-1)(k-2)/2.
[Answer]
# CJam, 13 bytes
```
q~__(*2/@2-*+
```
[Try it online](http://cjam.tryitonline.net/#code=cX5fXygqMi9AMi0qKw&input=MjQgMTAwMA)
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 11 [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")
Thanks to Adám for his help for suggesting this alternate version.
```
⊢+-∘2⍤⊣×2!⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HXIm3dRx0zjB71LnnUtfjwdCNFoND/tEdtEx719j3qm@rp/6ir@dB640dtE4G84CBnIBni4Rn831jBRMFMIe3QCgULIMvQAAA "APL (Dyalog Extended) – Try It Online")
**Explanation**
```
⊢+-∘2⍤⊣×2!⊢ Right argument (⊢) is n. Left argument (⊣) is s.
2!⊢ Binomial(n, 2) == n*(n-1)/2.
-∘2⍤⊣× Multiply (×) with by getLeftArgument (⊢) with (⍤) minus 2 (-∘2) called on it.
In short, multiply binomial(n,2) with (s-2).
⊢+ Add n.
```
---
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~12~~ 11 [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")
Thanks to Adám for his help in golfing this.
Edit: -1 byte from ngn.
```
⊢+{⍺-2}×2!⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HXIu3qR727dI1qD083UgRy/6c9apvwqLfvUd9UT/9HXc2H1hs/apsI5AUHOQPJEA/P4P/GCiYKZgpph1YoWABZhgYA)
**Ungolfing**
```
⊢+{⍺-2}×2!⊢ Right argument (⊢) is n. Left argument (⊣) is s.
2!⊢ Binomial(n, 2) == n*(n-1)/2.
{⍺-2}× Multiply it by s-2.
⊢+ Add n.
```
[Answer]
## Actually, 12 bytes
```
3@n(¬@D3╟π½+
```
[Try it online!](http://actually.tryitonline.net/#code=M0BuKMKsQEQz4pWfz4DCvSs&input=MwoxMA)
Explanation:
```
3@n(¬@D3╟π½+
3@n push 3 copies of n (stack: [n, n, n, k])
(¬ bring k to front and subtract 2 ([k-2, n, n, n])
@D bring an n to front and subtract 1 ([n-1, k-2, n, n])
3╟π product of top 3 elements ([n*(n-1)*(k-2), n])
½ divide by 2 ([n*(n-1)*(k-2)/2, n])
+ add ([n*(n-1)*(k-2)/2 + n])
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 14 bytes
```
?dd1-*2/?2-*+p
```
[Try it online!](https://tio.run/##S0n@/98@JcVQV8tI395IV0u74P9/IzMuUwA "dc – Try It Online")
### Explanation
This makes use of the following formula
(note that **T**n = `n*(n-1)/2`):

```
# inputs | N S | 10 5
?dd # push N three times | N, N, N | 10, 10, 10
1- # subtract 1 | (N-1), N, N | 9, 10, 10
* # multiply | (N-1)*N, N | 90, 10
2/ # divide by two | (N-1)*N/2, N | 45, 10
? # push S | S, (N-1)*N/2, N | 5, 45, 10
2- # subtract 2 | (S-2), (N-1)*N/2, N | 3, 45, 10
* # multiply | (S-2)*(N-1)*N/2, N | 135, 10
+ # add | (S-2)*(N-1)*N/2 + N | 145
p # print to stdout
```
[Answer]
# [Aceto](https://github.com/aceto/aceto), ~~18~~ 15 bytes
Port of the [Bruce Forte's dc answer](https://codegolf.stackexchange.com/a/143893/21173):
```
riddD*2/ri2-*+p
```
Saved 3 bytes by realizing that any "pure" (no combined commands) Aceto program can be written linearly.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 8 bytes
```
_┐*½?⌡*+
```
[Try it online!](https://tio.run/##y00syUjPz0n7/z/@0ZQJWof22j/qWail/f@/oYGCMReQMAUSECaQMjL5DwA "MathGolf – Try It Online")
## Explanation (with \$n = 10, k = 5\$
```
_ duplicate first implicit input, stack is [10, 10]
┐ push TOS-1 without popping, stack is [10, 10, 9]
* multiply, stack is [10, 90]
½ halve TOS, stack is [10, 45]
? rotate top 3 stack elements, popping k to the top: [10, 45, 5]
⌡ decrement TOS twice: [10, 45, 3]
* multiply: [10, 135]
+ add: [145]
```
An alternative 8-byter is `┼┐*½\⌡*+`, which takes the input in reversed order.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 13 bytes
```
::1-*2,{2-*+n
```
[Try it online!](https://tio.run/##S8sszvj/38rKUFfLSKfaSFdLO@////@6ZQpGJiDS0MDAAAA "><> – Try It Online")
[Answer]
# Mathematica, 17 bytes
```
(#2-2)#(#-1)/2+#&
```
Straight-forward application of the formula.
## Usage
```
f = (#2-2)#(#-1)/2+#&
f[10, 3]
55
f[10, 5]
145
f[100, 3]
5050
f[1000, 24]
10990000
```
[Answer]
# J, 14 bytes
```
]++/@i.@]*[-2:
```
Based on the formula.
```
P(k, n) = (k - 2) * T(n - 1) + n where T(n) = n * (n + 1) / 2
= (k - 2) * n * (n - 1) / 2 + n
```
## Usage
```
f =: ]++/@i.@]*[-2:
3 f 10
55
5 f 10
145
3 f 100
5050
24 f 1000
10990000
```
## Explanation
```
]++/@i.@]*[-2:
2: The constant function 2
[ Get k
- Subtract to get k-2
] Get n
i.@ Make a range from 0 to n-1
+/@ Sum the range to get the (n-1) Triangle number = n*(n-1)/2
The nth Triangle number is also the sum of the first n numbers
* Multiply n*(n-1)/2 with (k-2)
] Get n
+ Add n to (k-2)*n*(n-1)/2
```
[Answer]
# TI-Basic, 20 bytes
```
Prompt K,N:(K-2)N(N-1)/2+N
```
[Answer]
# GameMaker Language, 44 bytes
```
n=argument1;return (argument0-2)*n*(n-1)/2+n
```
[Answer]
# Python 3, ~~31~~ ~~30~~ 28 bytes
The straight up equation from [this wiki article](https://en.wikipedia.org/wiki/Polygonal_number)
```
lambda s,n:(s-2)*(n-1)*n/2+n
```
*Thanks to @Mego for saving a byte!*
[Answer]
# Fourier, 18 bytes
```
I-2~SI~Nv*N/2*S+No
```
[**Try it on FourIDE!**](https://beta-decay.github.io/editor/?code=SS0yflNJfk52Kk4vMipTK05v)
Takes k as first input and n as second input. Uses the formula:

***Explanation Pseudocode:***
```
S = Input - 2
N = Input
Print (N - 1) * N / 2 *S + N
```
[Answer]
# Excel, 22 bytes
Calculates the `A1`th `B1`-gonal number.
```
=(B1-2)*A1*(A1-1)/2+A1
```
[Answer]
# Java 8, 21 bytes
All individual answers of equal byte-length:
```
k->n->n+n*~-n*(k-2)/2
k->n->n+n*--n*(k-2)/2
k->n->n+n*~-n*~-~-k/2
k->n->n+n*--n*~-~-k/2
```
**Explanation:**
[Try it here.](https://tio.run/##lY4xD4IwEIV3fsWNoLYq6oQymjg4MRqHWpAUytHAYWKM/nUsSQc2MblLXvK@u/cK8RCsNhkWadlLLdoWzkLhywNoSZCSUFiCd6Q0v3coSdXIj07sT0hZnjWLaZATcQwSDn3JYrQzx9mHDfth5TLsI88mm@6mbbIr8KhVCpUt5SfUKMwvVxDBUBAgebaUVbzuiBtrkUZfcmGMfvqbwIn1KgiiX/TuL3r0ewoebke8O3h77/4L)
```
k->n-> // Method with two integer parameters and integer return-type
n+ // Return `n` plus
n* // `n` multiplied by
~-n // `n-1`
*(k-2) // Multiplied by `k-2`
/2 // Divided by 2
// End of method (implicit / single-line return-statement)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
S+~*-2(Σ←
```
[Try it online!](https://tio.run/##yygtzv7/P1i7TkvXSOPc4kdtE/7//2/639AAAA "Husk – Try It Online")
### Explanation
Using the same formula as in my `dc` answer:

```
-- implicit inputs S, N | 5, 10
S+ -- compute N + the result of the following | 10 +
~* -- multiply these two together | ( ) *
-2 -- S-2 | S-2
(Σ←) -- triangle number of (N-1) | tri(N-1)
```
[Answer]
# APL(NARS), 16 char, 32 bytes
```
{⍵+(⍺-2)×+/⍳⍵-1}
```
It is based from the fact that seems n×(n-1)/2=sum(1..n-1) test:
```
f←{⍵+(⍺-2)×+/⍳⍵-1}
10 f 3
27
3 f 10
55
5 f 19
532
3 f 10
55
5 f 10
145
3 f 100
5050
24 f 1000
10990000
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~14~~ ~~12~~ 10 bytes
```
-[U½UÉVÍ]×
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=LVtVvVXJVs1d1w&input=MTAsMw)
[Answer]
# [Rockstar](https://codewithrockstar.com/), 67 bytes
```
listen to N
listen to K
cast N
let K be-2
let K be*N-1
say K*.5*N+N
```
[Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in, with each input integer on an individual line)
[Answer]
# x86-16 machine code, 14 bytes
```
00000000: 4949 8bc3 48f7 e3f7 e1d1 e803 c3c3 II..H.........
```
Listing:
```
49 DEC CX ; k = k - 2
49 DEC CX
8B C3 MOV AX, BX ; AX = n
48 DEC AX ; AX = n - 1
F7 E3 MUL BX ; AX = n * n - 1
F7 E1 MUL CX ; AX = ( k - 2 ) * n * ( n - 1 )
D1 E8 SHR AX, 1 ; AX = ( k - 2 ) * n * ( n - 1 ) / 2
03 C3 ADD AX, BX ; AX = ( ( k - 2 ) * n * ( n - 1 ) / 2 ) + n
C3 RET ; return to caller
```
Callable function, input `n` in `BX`, `k` in `CX`, result in `AX`.
] |
[Question]
[
Given a decimal in the form of `<float>, <precision>`, you draw the graphical representation of the decimal part (i.e. fraction) of the float. Examples:
1. Input: `6.75, 4`, output:
```
6||| 7
----
```
`6.75` (first number from the input) is the number to explain, `4` (the second number from the input) is the number of dashes below the pipes. `6` is the floored 6.75, `7` is the ceiled `6.75`. The number of pipes is the `decimal part of first input number * second input number`.
2. Input: `10.5, 6`, output:
```
10||| 11
------
```
3. Input: `20.16, 12`, output
```
20|| 21
------------
```
`.16` actually takes 1.92 pipes, but since I can't draw 1.92 pipes, I ceil it to 2.
4. Input: `1.1, 12`, output:
```
1| 2
------------
```
`.1` is 1.2 pipes in this case, so it's floored to 1 pipe.
5. Also, an edge case. Input: `5, 4` (i.e. the number is an integer), output:
```
5 6
----
```
---
* The number to explain is the positive float, limited only by your language abilities.
* The precision number is an even integer, greater than 2 (i.e. minimal required precision is 4). It can be arbitrary large too.
* *>= n.5* pipes are rounded up, to *n+1* (i.e 1.5 is rounded to 2 and 2.5 is rounded to 3). *< n.5* pipes are rounded to *n* (i.e. 1.4 is rounded to 1 and 2.4 is rounded to 2).
* If it would be more convenient for your language, you can take the input as an array, e.g. `[6.75, 4]`. If you take the input in the reversed order, i.e. `[4, 6.75]`, please specify it in your answer.
[Answer]
## CJam, 32 bytes
```
l~1md@:X*mo'|*XSe]1$)NW$s,S*'-X*
```
Takes the precision first and the decimal second, separated by a space.
[Run all test cases.](http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%3B%0A%0AQ~1md%40%3AX*mo'%7C*XSe%5D1%24)NW%24s%2CS*'-X*%0A%0A%5DoNoNo%7D%2F&input=4%206.75%0A6%2010.5%0A12%2020.16%0A12%201.1%0A4%205%0A4%201.125)
### Explanation
```
l~ e# Read input and evaluate, pushing precision and decimal on the stack.
1md e# Divmod 1, separating the decimal into integer and fractional part.
@:X e# Pull up precision, store in X.
*mo e# Multiply precision by fractional part and round.
'|* e# Push that many vertical bars.
XSe] e# Pad with length X with spaces.
1$) e# Copy integer part and increment.
N e# Push linefeed.
W$ e# Copy integer part.
s, e# Get number of digits as length of string representation.
S* e# Push that many spaces, to indent the hyphens correctly.
'-X* e# Push X hyphens.
```
[Answer]
## Mathematica, 119 bytes
```
a=ToString;b=Array;a[c=Floor@#]<>{b["|"&,d=Round[#2#~Mod~1]],b[" "&,#2-d],a[c+1],"
"," "&~b~IntegerLength@c,"-"&~b~#2}&
```
I tried... Testing:
```
In[1]:= a=ToString;b=Array;f=a[c=Floor@#]<>{b["|"&,d=Round[#2#~Mod~1]],b[" "&,#2-d],a[c+1],"\n"," "&~b~IntegerLength@c,"-"&~b~#2}&;
In[2]:= f[6.75, 4]
Out[2]= 6||| 7
----
In[3]:= f[10.5, 6]
Out[3]= 10||| 11
------
In[4]:= f[20.16, 12]
Out[4]= 20|| 21
------------
In[5]:= f[1.1, 12]
Out[5]= 1| 2
------------
In[6]:= f[5, 4]
Out[6]= 5 6
----
```
[Answer]
## Javascript ES6, ~~105~~ 104 bytes
```
(f,p)=>(i=f|0)+("|".repeat(j=(f-i)*p+.5|0)+" ".repeat(p-j))+(i+1)+(`
`+i).replace(/\d/g," ")+"-".repeat(p)
```
Saved 1 byte thanks to, um, how do you type ՊՓԼՃՐՊՃՈԲՍԼ anyway?
[Answer]
# Japt, ~~47~~ 46 bytes
```
Uf +'|pA=ºU-Uf)*V c)+SpV-A +Uc +R+SpUk l)+'-pV
```
Just a bunch of adding and repeating.
[Try it online](http://ethproductions.github.io/japt?v=master&code=VWYgKyd8cEE9KChVLVVmKSpWIGMpK1NwVi1BICtVYyArUitTcFVrIGwpKyctcFY=&input=Ni43NSA0)
[Answer]
# Java, ~~253~~ ~~206~~ 181 bytes
*Saved 47 bytes thanks to @Kenney by inlining conditions and variables used once, and sorting out redundant variables.*
*Saved 25 bytes again thanks to @Kenney by inlining 2 loops with ternary operators.*
Pure String Manipulation:
Inlined loops version (181 bytes):
```
String m(float f,int p){int g=(int)f,i=0;String h="",q=""+g;int c=q.length();for(;i<c+p;)h+=i++<c?" ":"-";for(i=c;i<p+c;)q+=i++<c+Math.round((f-g)*p)?"|":" ";return q+(g+1)+"\n"+h;}
```
4 loops version (206 bytes):
```
String m(float f,int p){int g=(int)f,i=0;String h="",q=""+g;int c=q.length();for(;i++<c;)h+=" ";for(;i<=c+p;i++)h+="-";for(i=c;i<c+Math.round((f-g)*p);i++)q+="|";for(;i++<p+c;)q+=" ";return q+(g+1)+"\n"+h;}
```
Ungolfed version:
```
String m(float f,int p){
//initialize some useful values, d is the number of pipes needed
int g=(int)f,d=Math.round((f-g)*p),i=0;
String h="",q=""+g;//append the floored value to the pipe string first
int c=q.length();
for(;i<c;i++)h+=" ";//pad hyphen string with spaces for alignment
for(++i;i<=c+p;i++)h+="-";//append hyphens
for(i=c;i<c+d;i++)q+="|";//append pipes
for(;i<p+c;i++)q+=" ";//append spaces for padding
return q+(g+1)+"\n"+h;}//concatenate the strings in order, separating the strings with a UNIX newline, and return it.
```
Working example here at [ideone.com](http://ideone.com/spK7j3). The full program accepts STDIN input as
`<float>,<precision>`.
NOTE: Java's `Math.round(float)` rounds using `RoundingMode.HALF_UP`as the default, which is the OP's required behaviour.
The output of the test cases provided was diff-matched to what the OP provided.
[Answer]
## Haskell, 113 bytes
```
(%)=replicate.round
s=show
x!y|(n,m)<-properFraction x=[s n,(y*m)%'|',(y-y*m)%' ',s$n+1,"\n",s n>>" ",y%'-']>>=id
```
Usage example:
```
*Main> putStrLn $ 20.16 ! 12
20|| 21
------------
```
`properFraction` splits the decimal into it's integer and fraction part. The output is a list of the parts (initial number, bars, spaces, ...) which is concatenated into a single string (via `>>=id`).
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 49 bytes
```
2#1\tYUbiXK*Yo'|'1bX"tnKw-Z"hb1+YUhht4Y2m13*_45+c
```
Uses [release 6.0.0](https://github.com/lmendo/MATL) of the language/compiler. Runs on Matlab or Octave.
Takes numbers in the same order as in the challenge.
### Examples
```
>> matl
> 2#1\tYUbiXK*Yo'|'1bX"tnKw-Z"hb1+YUhht4Y2m13*_45+c
>
> 20.16
> 12
20|| 21
------------
>> matl
> 2#1\tYUbiXK*Yo'|'1bX"tnKw-Z"hb1+YUhht4Y2m13*_45+c
>
> 5
> 4
5 6
----
```
### Explanation
```
2#1\ % implicit input 1st number. Separate decimal and integer part
tYU % duplicate integer part and convert to string
biXK*Yo % input 2nd number. Copy it. Multiply by decimal part of 1st number and round
'|'1bX" % row vector of as many '|' as needed
tnKw-Z" % row vector of as many spaces as needed
h % concat horiontally
b1+YUhh % integer part of 1st number plus 1. Convert to string. Concat twice
t4Y2m % detect numbers in this string
13*_45+c % transform numbers into spaces, and non-numbers into '|'
% implicitly display both strings
```
[Answer]
# Perl, 90 bytes
```
print$f,"|"x($d=.5+($b=pop)*(($a=pop)-($f=0|$a))),$"x(1+$b-$d),$f+1,$/,$"x length$f,"-"x$b
```
Expects input as commandline arguments. Save in a file (say `90.pl`) and run as `perl 90.pl 6.75 4`
***With comments***
```
print $f, # floored input (initialized below due to expr nesting)
"|" x ($d=.5+ # rounded pipe count (`x` operator casts to int)
+($b=pop) # second argument (executed first)
*( ($a=pop) # first argument (executed second)
-($f=0|$a) ) # minus floored first argument = fractional part
),
$"x(1+$b-$d), # spaces
$f+1, # floored + 1
$/, # newline
$" x length $f, # 2nd line alignment
"-" x $b # the 'ruler'
```
[Answer]
# Lua, 157 bytes
Long, but can't find a shorter solution
```
function f(d,n)r=""a=math.floor(d)d,s=d-a,a..r for i=1,#s do r=r.." "end for i=1,n do s,r=s..(i-.5>n*d and" "or"|"),r.."-"end s=s..a+1 return s.."\n"..r end
```
### Ungolfed
```
function g(d,n)
r=""
a=math.floor(d)
d,s=d-a,a..r -- d now contains its decimal part
for i=1,#s do r=r.." "end -- padding the hyphens
for i=1,n
do
s,r=s..(i-.5>n*d and" "or"|"),r.."-"
-- s is concatenated with a "|" if i-.5>n*d, a space otherwise
end
s=s..a+1
return s.."\n"..r
end
```
You can test lua [online](http://www.lua.org/cgi-bin/demo), the following test cases could be useful :)
```
function f(d,n)r=""a=math.floor(d)d,s=d-a,a..r for i=1,#s do r=r.." "end for i=1,n do s,r=s..(i-.5>n*d and" "or"|"),r.."-"end s=s..a+1 return s.."\n"..r end
print(f(16.75,4))
print(f(5,4))
print(f(20.16,12))
```
[Answer]
# C, ~~233~~ 231 bytes
```
#include <stdlib.h>
#include <math.h>
i,n,l;main(c,v)char**v;{double m;l=atol(v[2]);n=(int)(modf(atof(v[1]),&m)*l+0.5);c=printf("%.f",m);for(;i++<l;)putchar(i>n?32:'|');printf("%.f\n",m+1);printf("%*s",c,"");for(;--i;)putchar(45);}
```
## Ungolfed:
```
#include <stdlib.h>
#include <math.h>
i,n,l;
main(c,v)
char**v;
{
double m;
l=atol(v[2]); /* Get length from command line */
n=(int)(modf(atof(v[1]),&m)*l+0.5); /* Get number of pipes and lower limit */
c=printf("%.f",m); /* print lower limit */
/* print pipes and spaces */
for(;i++<l;)
putchar(i>n?32:'|');
/* print upper limit */
printf("%.f\n",m+1);
/* print spaces before dashes */
printf("%*s",c,"");
/* print dashes */
for(;--i;)
putchar(45);
}
```
[Answer]
# Python 3, ~~116~~ 108 bytes
```
def f(F,P):l=int(F);h,p=str(l+1),int((F-l)*P+.5);l=str(l);print(l+"|"*p+" "*(P-p)+h);print(" "*len(l)+"-"*P)
```
[trinket.io link](https://trinket.io/python/080858ae81)
Thank you to Seeq for saving a few characters.
### First version:
```
def f(F,P):
l=int(F)
h,s,p=str(l+1)," ",int((F-l)*P+.5)
l=str(l)
print(l+"|"*p+s*(P-p)+h)
print(s*len(l)+"-"*P)
```
Ungolfed version:
```
def frac(F,P):
low = int(F)
high = low+1
pipes = int((F-low)*P+.5)
print(str(low)+"|"*pipes+" "*(P-pipes)+str(high))
print(" "*len(str(low))+"-"*P)
```
[Answer]
# [Stackgoat](https://github.com/vihanb/Stackgoat/blob/master/stackgoat.js), ~~31~~ 27 bytes
```
CFv1%C*D'|^w1P-Y^vHXNY^w'-^
```
Similar to most of the other answers. I'll see if I can golf more. The input can be comma separated, space separated, or almost anything separated.
## Explanation
```
CF // Input, floored, push to stack
v1% // Decimal part
C* // Times second part
D // Duplicate that result
'|^ // Repeat | by previous number
w // Second input
1P // Move # of |'s to the top of stack
- // Subtract
Y^ // Repeat " " by above number
vH // Ceil first input
X // Newline
Z+ // Add to
N // Get length of first #
Y^ // Repeat by spaces
w'- // Repeat - second input times
```
] |
[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 7 years ago.
[Improve this question](/posts/30134/edit)
Write a program that sorts a vector of numbers (or any type of element) that looks like having one or more bugs, but it is actually ok.
* The code must be clear. Someone looking over the code must easily identify that it is a sort algorithm and must easily confuse a correct piece of code with a bug.
* The (apparent) bug can by anything that makes the code syntactically or semantically ill-formed (e.g. make the program not compile/run, exhibit UB when runned), make the program produce incorrect results, not terminate, or nondeterministic.
* The code must actually be well-formed and the program must deterministically produce the correct output in a finite time.
* The input can be hard coded in the program or can be read (from user, from file etc.).
* Input is considered valid and the program is not needed to verify input correctness.
* Any sorting algorithm is accepted. The data structure to hold the numbers is not needed to be an actual vector. The program can be designed to sort a variable number of numbers or a fixed number of numbers (e.g. **a program to sort 3 numbers is ok**). Sorting can be stable or not (note: a program designed to do a stable sort that has an apparent bug that makes the sort look unstable, but in actuality it is not a bug: the program actually does a stable sort — is a valid answer).
* you can call any functions (including sort functions) except 3rd party tools (unless they are widely spread and used e.g. `boos` for `C++`, `JQuery` for `Javascript` – those are ok to use)
* specify the language
* comment in code the part that looks like a bug.
* explain what the bug looks like doing wrong.
* explain (in a spoiler box) why it is actually not a bug.
This is a popularity contest. The answer with most votes wins.
---
This challenge is now over. The winner is @Clueless <https://codegolf.stackexchange.com/a/30190/11400> with 8 votes. Thanks to all the submitters!
If you want to come in after the winner was awarded, please feel free to add a new answer. You are out of the race, but we are all interested to see interesting answers.
[Answer]
## C++
Inspired by [Apple's `goto fail`; bug](https://www.imperialviolet.org/2014/02/22/applebug.html).
```
#include <vector>
#include <map>
#include <iostream>
/**
* Sorts a vector of doubles in reverse order using the bucket sort algorithm.
*/
std::vector<double> reverse_bucket_sort(const std::vector<double>& input) {
// put each element into a bucket as many times as it appears
std::map<double, int> bucket_counts;
for (auto it : input)
++bucket_counts[it];
std::vector<double> sorted_elements; // the return value
// loop until we are done
while (bucket_counts.size() > 0) {
// find the largest element
double maximum = std::numeric_limits<double>::lowest();
for (auto it : bucket_counts) {
if (it.first > maximum)
maximum = it.first;
maximum = it.first;
}
// add the largest element N times to our sorted vector
for (int i = 0; i < bucket_counts[maximum]; ++i)
sorted_elements.push_back(maximum);
// and now erase the bucket
bucket_counts.erase(maximum);
}
return sorted_elements;
}
int main(int argc, const char * argv[]) {
std::vector<double> test_case = { 0, 1, 2.5, 10, 2.5, 2 };
std::cout << "unsorted:";
for (auto it : test_case) std::cout << " " << it;
std::cout << std::endl;
std::cout << "sorted:";
for (auto it : reverse_bucket_sort(test_case)) std::cout << " " << it;
std::cout << std::endl;
return 0;
}
```
>
> About halfway down the page there is a bug: we have a duplicate line
> after our `if` check! We are always going to update the maximum with whatever
> is the last value in `bucket_count`.
>
> Thankfully we are OK. In C++ `std::map` is sorted by keys. So we are
> just reversing the buckets, which is what we want.
>
>
>
[Answer]
# Python2.x
```
import random
L = [random.randrange(20) for x in range(20)]
print "Unsorted:", L
def sort(L):
# terminal case first. Otherwise sort each half recursively and combine
return L.sort() if L > 1 else sort(L[:len(L)//2]) + sort(L[len(L)//2:])
sort(L)
print "Sorted:", L
```
[Test run](https://ideone.com/XhYA2F)
>
> `list.sort` returns `None`, so the part after the `else` is `None + None`.
> Luckily this doesn't cause a problem because the comparison of
> a list and and an int `(L > 1)` is always `True`.
> The function always returns `None` so we ignore the return value and
> Just print `L` which has been sorted in place
> Merging the sorted halves by catenation wouldn't have worked either
> even if the execution did get there.
>
>
>
[Answer]
# C
Using sort incorrectly - on a 64 bit system `int` is 4 bytes and `char *` is 8 bytes, so shouldn't work.
Code:
```
#include <stdlib.h>
#include <stdio.h>
/* Compare integers to sort in reverse order */
int compare(const void *p, const void *q)
{
const int *a = p;
const int *b = q;
return *b - *a;
}
int main()
{
char *strings[] = {"B", "Que", "Ro", "Sum", "T"};
int i;
/* Let's use the integer compare to sort strings */
qsort(&strings, sizeof(strings) / sizeof(char *), sizeof(char *), compare);
/* Output the sorted results */
for (i = 0; i < sizeof(strings) / sizeof(char *); i++)
printf("%s\n", strings[i]);
return 0;
}
```
Build:
```
$ gcc -o sort-no-sort sort-no-sort.c
```
Run:
```
$ ./sort-no-sort
T
Sum
Ro
Que
B
```
Yep, sorts okay!
>
> Five things going on: 1) `qsort` passes pointers to integers, which are the same size as pointers to characters. 2) The strings are no more than four bytes in length (three + one terminator) = the size of an integer, which the sort routine happily treats as an integer. 3) Most compilers force alignment of data structures, so shorter strings take up the same space. Any larger though and be prepared for failures. 4) Endian-ness. 5) Zero initialization of internal bytes.
>
>
>
[Answer]
# Cobra
```
class Program
var _target as List<of bool?> = [true, true, false, true, true, nil, nil, false, true, nil, true]
def main
.sort(_target)
print _target
def sort(target as List<of bool?>)
for i in target.count, for n, in target.count -1, if target[n] <> target[n + 1] and (target[n] or target[n + 1] == nil), target[n], target[n + 1] = target[n + 1], target[n]
#should return sorted as [nil][false][true]
```
Oh dear, I appear to have incorrectly assigned `n`... and how did all those commas get there!?
>
> When `n` is assigned the compiler assumes that it's being give the first half of a key-value pair (due to the comma), but there is no key-value pair so the compiler doesn't complain when it can't assign the second half of it to a non-existent variable. This results in `n` simply being given the key value.. which in this case is an index number. All of the other out-of-place-looking commas in the final line are actually part of standard Cobra syntax.
>
>
>
[Answer]
# Java
```
public final class WeirdSort {
public static void main(final String[] args) {
//Random
final Random random = new Random(441287210);
//Some numbers:
final List<Integer> list = new ArrayList<Integer>();
list.add(9);
list.add(11);
list.add(3);
list.add(5);
list.add(7);
//Sort randomly:
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(final Integer o1, final Integer o2) {
return (o1 - o2) + random.nextInt(10);
}
});
//Print
for(final Integer i:list) {
System.out.print(i + " ");
}
}
}
Prints: 3 5 7 9 11
```
>
> Works because this specific random value returns '1' for the first 10 results
>
>
>
[Answer]
# Perl
Contractors these days! Don't they know that the [`<=>`](http://perldoc.perl.org/perlop.html#Equality-Operators) (a.k.a "spaceship") operator is only used for numeric sorting?
And why are they comparing operators?
How did this code even pass our stringent tests??!! It even uses [`strict`](https://metacpan.org/pod/strict) and [`warnings`](https://metacpan.org/pod/warnings)!
```
use strict;
use warnings;
sub asciibetically { 0-($a lt $b) || 0+($a gt $b) || <=><=><=> }
# ^ ^ ^
# What?? How did Perl even compile??!!
my @sorted = sort asciibetically qw( bravo charlie alpha );
print "@sorted"; # "alpha bravo charlie"
# And how come it works??!!
```
---
### Why Perl compiles
>
> The only real `<=>` operator is the one in the middle. The other two are just another way of writing `glob("=")`. This means that `<=><=><=>` (nicknamed "space fleet") evaluates to `0`.
>
>
>
---
] |
[Question]
[
## Skolem sequences
A *Skolem sequence* is a sequence of `2n` numbers where every number `i` between `1` and `n` occurs exactly twice, and the distance between the two occurrences of `i` is exactly `i` steps.
Here are some examples of Skolem sequences:
```
1 1
1 1 4 2 3 2 4 3
16 13 15 12 14 4 7 3 11 4 3 9 10 7 13 12 16 15 14 11 9 8 10 2 6 2 5 1 1 8 6 5
```
The following sequences are *not* Skolem sequences:
```
1 2 1 2 (The distance between the 1's is 2, not 1)
3 1 1 3 (The number 2 is missing)
1 1 2 1 1 2 (There are four 1's)
```
## Objective
Write a program, function, or expression to count the number of all Skolem sequences of a given length.
More explicitly, your input is an integer `n`, and your output is the number of Skolem sequences of length `2n`.
This sequence has an [OEIS entry](https://oeis.org/A004075).
For `n = 0`, you may return either `0` or `1`.
The first few values, starting from `0`, are
```
0, 1, 0, 0, 6, 10, 0, 0, 504, 2656, 0, 0, 455936, 3040560, 0, 0, 1400156768
```
## Rules and scoring
This is code golf.
Output format is lax within reason.
[Answer]
### GolfScript, 48 46 characters
```
:b,1,{)2\?){{.2$&!{.2$|@@}*.+.4b?<}do;;}+%}@/,
```
The faster version ([try online](http://golfscript.apphb.com/?c=NQoKOmIsMSx7KTJcPyl7ey4yJCYhey4yJHxAQH0qLisuNGI%2FPH1kbzs7fSslfUAvLA%3D%3D&run=true)) - runs reasonable fast, e.g. `n=8` takes about two seconds. And the chosen approach takes really few characters.
This version also works with bitmasks. It builts the possible result array from 1 upwards, i.e. for `n=3`:
```
1: 000011 000110 001100 011000 110000
2: 010111 101011 101110 011101 110101 111010
```
While some results (like 000011) have two possible continuations, others (i.e. 001100) have none and are removed from the result array.
Explanation of the code:
```
:b # save the input into variable b for later use
, # make the list 0..b-1 (the outer loop)
1, # puts the list [0] on top of the stack - initially the only possible
# combination
{) # {...}@/ does the outer loop counting from i=1 to b
2\?) # computes the smalles possible bit mask m=2^i+1 with two bits set
# and distance of those equal to i (i.e. i=1: 11, i=2: 101, ...)
{ # the next loop starts with this bitmask (prepended to code via
# concatination {...}+
# the loop itself iterates the top of the stack, i.e. at this point
# the result array
# stack here contains item of result array (e.g. 00000011)
# and bitmask (e.g. 00000101)
{ # the inner-most loop tries all masks with the current item in the result set
.2$&! # do item and result set share not single bit? then - {...}*
{
.2$| # then generate the new entry by or-ing those two
@@ # push it down on the stack (i.e. put working items to top)
}*
.+ # shift the bit mask left by one
.4b?< # if still in the range loop further
}do;; # removes the remainders of the loop (i.e. item processed and mask)
}+% # stack now contains the new result array
}@/
, # length of result array, i.e. the number of Skolem sequences
```
[Answer]
### J expression, 47 characters
```
+/*/"1((=&{:+.2-#@])#;.2)\"1~.(i.!+:y)A.,~>:i.y
```
Example:
```
y=:5
+/*/"1((=&{:+.2-#@])#;.2)\"1~.(i.!+:y)A.,~>:i.y
10
```
Takes about 30 seconds for `y=:5` on my machine.
the algorithm is as slow as can be:
* `~.(i.!+:y)A.,~>:i.y` generates every permutation of `1 2 .. y 1 2 .. y` and removes duplicate entries
* `((=&{:+.2-#@])#;.2)\"1` computes:
+ `(...)\"1` for every prefix of every row:
- `#;.2` counts the the elements before each occurence of the last element
- `#@]` counts the number of counts (i.e. the number of occurences of the last element)
- `=&{:` determines the "equality" "of" "last element"s of the count list and of the original list.
- `+.` is a logical OR. `=&{:+.2-#@]` reads "either the last elements [of the count list and the original list] are equal, or there is only one element [in the count list] rather than two".
* `*/"1` multiplies (logical AND) over the rows of the condition table, determining which permutations are Skolem sequences.
* `+/` sums the ones and zeroes together.
[Answer]
## GolfScript (46 chars)
```
:&1,\,{0,2@)?)2&*{2${1$^}%@+\2*}*;+}/{4&?(=},,
```
This is an expression which takes input on the stack. To turn it into a full program which takes input on stdin, prepend `~`
It is fairly inefficient - most of the savings I made in golfing it down from 56 chars ungolfed were by expanding the range of loops in ways which don't introduce incorrect results but do waste calculation.
The approach is bitwise masking of Cartesian products. E.g. (using binary for the masks) for `n=4` the ungolfed code would compute the xor of each element in the Cartesian product `[00000011 00000110 ... 11000000] x [00000101 00001010 ... 10100000] x ... x [00010001 ... 10001000]`. Any result with 8 bits could only be achieved by non-overlapping masks.
In order to optimise for size rather than speed, the code accumulates partial products (`S1 u S1xS2 u S1xS2xS3 ...`) and makes each product be of `2n` elements rather than just the `2n-1-i` which can actually contribute to a valid sequence.
### Speed
The golfed version runs for `n=5` in 10 seconds on my computer, and more than 5 minutes for `n=6`. The original ungolfed version computes `n=5` in less than a second, and `n=6` in about 1 minute. With a simple filter on intermediate results, it can compute `n=8` in 30 seconds. I've golfed it to 66 chars (as a program - 65 chars as an expression) while keeping the loops as restricted as possible and filtering intermediate collisions:
```
~:&1,\,{0,\).2\?)2&*@-{.{[\].~^.@~+<{;}*}+3$%@+\2*}*;\;}/{4&?(=},,
```
[Answer]
### GolfScript, 49 characters
```
~:/..+?:d(,{d+/base(;:w;/,{.w?)w>1$?=},,/=},,/1=+
```
Expects the number `n` on STDIN. This is code-golf - don't try the code with `n` greater than 5.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~20~~ 19 bytes
```
₁ḣ
ṁo=¹⁰(moF-¥)uPṘ2
```
[Try it online!](https://tio.run/##ASkA1v9odXNr///igoHhuKMK4bmBbz3CueKBsChtb0YtwqUpdVDhuZgy////NA "Husk – Try It Online")
Can be shortened further.
returns 1 for 0.
-1 byte from Jo king.
## Explanation
```
ṁo=ḣ¹`(moF-¥)ḣ¹uPṘ2ḣ
ḣ range from 1..n
Ṙ2 replicate each element 2 times
uP unique permutations of the list
ṁo map each permutation to the following two functions
and sum the results
` flip: f x y = f y x
(mo ) map each number to the following:
( ¥)ḣ¹ index of each number in 1..n in the permutation
( F- ) folded by subtraction
=ḣ¹ are the differences equal to 1..n?
```
[Answer]
## Sage, 70
This is a little shorter than my original.
```
sum(1for i in DLXCPP([(i-1,j,i+j)for i in[1..n]for j in[n..3*n-i-1]]))
```
How it works:
Given a 0/1 matrix, the **exact cover** problem for that matrix is to find a subset of the rows that sum (as integers) to the all-ones vector. For example,
```
11001
10100
01001
00011
00010
```
has a solution
```
10100
01001
00010
```
My favorite approach to problems is to cast them to an exact cover problem. Skolem sequences efficiently facilitate this. I make an exact cover problem where solutions are in bijection with Skolem sequences of length `2n`. For example, a row of the problem for `n=6` is
```
a | b
001000|001001000000 # S[b] = S[b+a+1] = a
```
where a 1 in position `a < n` means that symbol `a` is used. The remaining positions correspond to actual locations in the sequence. An exact cover corresponds to each symbol being used exactly once, and each location being filled exactly once. By construction, any symbol `k` in a location is `k` spaces away from its partner.
In Sage, `DLXCPP` is a "dancing links" implementation -- it solves the exact cover problem in an exceptionally graceful manner. It's one of my favorite algorithms ever, and being right at the surface in Sage makes combinatorial enumeration a joy.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ݦ©€DœʒU®εXQ0Úg<}®Q}Ùg
```
Results in \$0\$ for \$n=0\$.
[Try it online](https://tio.run/##AS0A0v9vc2FiaWX//8OdwqbCqeKCrETFk8qSVcKuzrVYUTDDmmc8fcKuUX3DmWf//zQ) or [verify the test cases in the range \$[0,4]\$](https://tio.run/##ATsAxP9vc2FiaWX/NMaSTj8iIOKGkiAiP07/w53CpsKp4oKsRMWTypJVwq7OtVhRMMOaZzx9wq5RfcOZZ/8s/w). (Unfortunately times out for \$n\geq5\$.)
**Explanation:**
```
Ý # Push a list in the range [0, (implicit) input `n`]
¦ # Remove the leading 0
# (builtin `L` would become list [1,0] for n=0 unfortunately,
# resulting in an incorrect result of 3 at the end)
© # Store this list in variable `®` (without popping)
€D # Duplicate each, resulting in a flattened list [1,1,2,2,3,3,...,n,n]
œ # Get all permutations of this list
ʒ # Filter it by:
U # Pop and store the current permutation in variable `X`
® # Push the ranged list [1,n] from variable `®`
ε # Map it to:
X # Check for each value in list `X`
Q # whether it's equal to the current map value
# (1 if truthy; 0 if falsey)
0Ú # Remove all leading and trailing 0s
g # Pop and get the length of the list
< # Decrease it by 1
}®Q # After the map: check if it's equal to the [1,n] ranged list
}Ù # After the filter: uniquify the remaining permutations
g # And pop and push the length
# (after which this is output implicitly as result)
```
] |
[Question]
[
Problem source: <https://oj.vnoi.info/problem/backtrack_j>
We have these two shapes:
```
#.
##
```
and
```
.#
##
```
Let's call the first shape the L and the second shape the flipped L.
On a 4x4 board, there are 16 cells. Each cell can be either free or occupied. In all the illustrations, `#` represents an occupied cell and `.` represents a free cell.
Your job is to print **all 4x4 boards** that can be completely filled using the L shape and the flipped L shape. You are not allowed to rotate or flip the shapes, but you can put them anywhere you want as long as the shape isn't clashing with existing occupied cells. **You are allowed to represent the boards in any reasonable format and print them in any order.**
Here is an example of a board that can be filled:
```
.##.
....
.##.
....
```
We can perform these steps to fill the whole board.
Step 1: Fill an L at the top left corner
```
###.
##..
.##.
....
```
Step 2: Fill a flipped L at the top right corner
```
####
####
.##.
....
```
Step 3: Fill an L at the bottom left corner
```
####
####
###.
##..
```
Step 4: Fill a flipped L at the bottom right corner
```
####
####
####
####
```
Here is an example of a board that can't be filled:
```
#...
....
....
....
```
No matter how hard you try, it's just impossible to fill the board.
Sample output:
```
###.
#...
....
....
##.#
#...
....
....
#.##
...#
....
....
.###
...#
....
....
####
##.#
....
....
####
#.##
....
....
#.#.
....
#.#.
....
.##.
....
#.#.
....
#..#
....
#.#.
....
.#.#
....
#.#.
....
###.
##..
#.#.
....
##.#
##..
#.#.
....
##.#
#..#
#.#.
....
#.##
#..#
#.#.
....
#.##
..##
#.#.
....
.###
..##
#.#.
....
####
####
#.#.
....
#.#.
....
.##.
....
.##.
....
.##.
....
#..#
....
.##.
....
.#.#
....
.##.
....
###.
##..
.##.
....
##.#
##..
.##.
....
##.#
#..#
.##.
....
#.##
#..#
.##.
....
#.##
..##
.##.
....
.###
..##
.##.
....
####
####
.##.
....
#.#.
....
#..#
....
.##.
....
#..#
....
#..#
....
#..#
....
.#.#
....
#..#
....
###.
##..
#..#
....
##.#
##..
#..#
....
##.#
#..#
#..#
....
#.##
#..#
#..#
....
#.##
..##
#..#
....
.###
..##
#..#
....
####
####
#..#
....
#.#.
....
.#.#
....
.##.
....
.#.#
....
#..#
....
.#.#
....
.#.#
....
.#.#
....
###.
##..
.#.#
....
##.#
##..
.#.#
....
##.#
#..#
.#.#
....
#.##
#..#
.#.#
....
#.##
..##
.#.#
....
.###
..##
.#.#
....
####
####
.#.#
....
###.
#...
#...
##..
##.#
#...
#...
##..
#.##
...#
#...
##..
.###
...#
#...
##..
####
##.#
#...
##..
####
#.##
#...
##..
###.
#...
..#.
##..
##.#
#...
..#.
##..
###.
.#..
..#.
##..
##.#
.#..
..#.
##..
##.#
...#
..#.
##..
#.##
...#
..#.
##..
####
#.##
..#.
##..
####
.###
..#.
##..
#.#.
....
###.
##..
.##.
....
###.
##..
#..#
....
###.
##..
.#.#
....
###.
##..
###.
##..
###.
##..
##.#
##..
###.
##..
##.#
#..#
###.
##..
#.##
#..#
###.
##..
#.##
..##
###.
##..
.###
..##
###.
##..
####
####
###.
##..
###.
#...
...#
##..
##.#
#...
...#
##..
###.
.#..
...#
##..
##.#
.#..
...#
##..
##.#
...#
...#
##..
#.##
...#
...#
##..
####
#.##
...#
##..
####
.###
...#
##..
#.#.
....
##.#
##..
.##.
....
##.#
##..
#..#
....
##.#
##..
.#.#
....
##.#
##..
###.
##..
##.#
##..
##.#
##..
##.#
##..
##.#
#..#
##.#
##..
#.##
#..#
##.#
##..
#.##
..##
##.#
##..
.###
..##
##.#
##..
####
####
##.#
##..
##.#
#...
#...
#..#
#.##
#...
#...
#..#
#.##
..#.
#...
#..#
.###
..#.
#...
#..#
####
###.
#...
#..#
#.##
...#
#...
#..#
.###
...#
#...
#..#
####
##.#
#...
#..#
###.
#...
...#
#..#
##.#
#...
...#
#..#
###.
.#..
...#
#..#
##.#
.#..
...#
#..#
##.#
...#
...#
#..#
#.##
...#
...#
#..#
####
#.##
...#
#..#
####
.###
...#
#..#
#.#.
....
##.#
#..#
.##.
....
##.#
#..#
#..#
....
##.#
#..#
.#.#
....
##.#
#..#
###.
##..
##.#
#..#
##.#
##..
##.#
#..#
##.#
#..#
##.#
#..#
#.##
#..#
##.#
#..#
#.##
..##
##.#
#..#
.###
..##
##.#
#..#
####
####
##.#
#..#
#.#.
....
#.##
#..#
.##.
....
#.##
#..#
#..#
....
#.##
#..#
.#.#
....
#.##
#..#
###.
##..
#.##
#..#
##.#
##..
#.##
#..#
##.#
#..#
#.##
#..#
#.##
#..#
#.##
#..#
#.##
..##
#.##
#..#
.###
..##
#.##
#..#
####
####
#.##
#..#
##.#
#...
#...
..##
#.##
#...
#...
..##
#.##
..#.
#...
..##
.###
..#.
#...
..##
####
###.
#...
..##
#.##
...#
#...
..##
.###
...#
#...
..##
####
##.#
#...
..##
##.#
#...
.#..
..##
#.##
#...
.#..
..##
#.##
..#.
.#..
..##
.###
..#.
.#..
..##
####
###.
.#..
..##
#.##
...#
.#..
..##
.###
...#
.#..
..##
####
##.#
.#..
..##
###.
#...
...#
..##
##.#
#...
...#
..##
#.##
...#
...#
..##
.###
...#
...#
..##
####
##.#
...#
..##
####
#.##
...#
..##
#.#.
....
#.##
..##
.##.
....
#.##
..##
#..#
....
#.##
..##
.#.#
....
#.##
..##
###.
##..
#.##
..##
##.#
##..
#.##
..##
##.#
#..#
#.##
..##
#.##
#..#
#.##
..##
#.##
..##
#.##
..##
.###
..##
#.##
..##
####
####
#.##
..##
#.#.
....
.###
..##
.##.
....
.###
..##
#..#
....
.###
..##
.#.#
....
.###
..##
###.
##..
.###
..##
##.#
##..
.###
..##
##.#
#..#
.###
..##
#.##
#..#
.###
..##
#.##
..##
.###
..##
.###
..##
.###
..##
####
####
.###
..##
##.#
....
....
####
#.##
....
....
####
####
#.#.
....
####
####
.##.
....
####
####
#..#
....
####
####
.#.#
....
####
##.#
#...
##..
####
#.##
#...
##..
####
#.##
..#.
##..
####
.###
..#.
##..
####
####
###.
##..
####
#.##
...#
##..
####
.###
...#
##..
####
####
##.#
##..
####
###.
#...
#..#
####
##.#
#...
#..#
####
#.##
...#
#..#
####
.###
...#
#..#
####
####
##.#
#..#
####
####
#.##
#..#
####
###.
#...
..##
####
##.#
#...
..##
####
###.
.#..
..##
####
##.#
.#..
..##
####
##.#
...#
..##
####
#.##
...#
..##
####
####
#.##
..##
####
####
.###
..##
####
#.#.
....
####
####
.##.
....
####
####
#..#
....
####
####
.#.#
....
####
####
###.
##..
####
####
##.#
##..
####
####
##.#
#..#
####
####
#.##
#..#
####
####
#.##
..##
####
####
.###
..##
####
####
####
####
####
####
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code (in bytes) wins.
[Answer]
# [Python](https://www.python.org), 122 bytes (-2 thanks to @ovs)
```
A=0,19,35
for d in(2,16)*2:A={x|y*d for x in A for y in A if 1>x&y*d}
for i in A:print(f"{i:019_b}_".translate(33*"#.\n"))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3qxxtDXQMLXWMTbnS8osUUhQy8zSMdAzNNLWMrBxtqytqKrVSFEAyFUAZBUcwsxLCzExTMLSrUAMqqAXrzQQLWxUUZeaVaKQpVWdaGRhaxifVxivplRQl5hXnJJakahgbaykp68XkKWlqQlywKbG4OLWoRCEnNU_DUdPW1sjQFCIBcyIA)
#### Previous [Python](https://www.python.org), 124 bytes (-1 thanks to @xnor)
```
A={0,19,35}
for d in(2,16)*2:A={x|y*d for x in A for y in A if 1>x&y*d}
for i in A:print(f"{i:019_b}_".translate(33*"#.\n"))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3axxtqw10DC11jE1rudLyixRSFDLzNIx0DM00tYysgJIVNZVaKQogmQqgjIIjmFkJYWamKRjaVagBFUD0ZoKFrQqKMvNKNNKUqjOtDAwt45Nq45X0SooS84pzEktSNYyNtZSU9WLylDQ1IW7YlFhcnFpUopCTmqfhqGlra2RoCpGAORIA)
#### Previous [Python](https://www.python.org), 126 bytes
```
A={0,19,35}
for d in(1,4)*2:A|={(x|y<<d)*(1>x&y<<d)for x in A for y in A}
for i in A:print(f"{i:019_b}_".translate(33*"#.\n"))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY36xxtqw10DC11jE1rudLyixRSFDLzNAx1TDS1jKwca2yrNSpqKm1sUjS1NAztKtTATJCyCqAyBUcFELMSzITozgSzrQqKMvNKNNKUqjOtDAwt45Nq45X0SooS84pzEktSNYyNtZSU9WLylDQ1Ia6AOgbmKAA)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~249~~ ~~230~~ ~~224~~ 210 bytes
```
(r={f=Table[1,{4},{4}]};p={e={1,1},{0,2},{2,0}};q=Flatten[Table[ArrayPad[k,{i,j}],{k,{{{1,0},e},{{0,1},e}}},{i,p},{j,p}],2];(a=#;r=Join[r,v=Select[a-#&/@q,AllTrue[#,(#>=0&),2]&]];Table[#0[e],{e,v}])&@f;Union@r)
```
[Try it online!](https://tio.run/##JY1BSwMxEIV/TGDZhRGzi7cwkl48iIeC9RRyGOvUpqZpG2KphPz2dZYe5uPxmI93pLLnI5WwpfmGc5@x7nBDn5HdCPWpLeebOWNlrCOMUmiYhBPo1swFXyKVwsndnVXO9LemL/cDNcCheaiSqpi6AYsm9rik1paHs/Ag9DB50xMqk/H1FJLLcMV3jrwtjh5U92gvsIpxk3/ZKejVM@puEKfz3tyHlXYsYwzX5ofO7sxHCqdk8zCvc0jFvnH6Lnt7m/8B "Wolfram Language (Mathematica) [Dash] Try It Online")
Recursive solution based on the next fact :
If given matrix is valid and we remove from it "L" or "anti-L", then the new matrix will be valid too.
All valid boards in a single picture:
[](https://i.stack.imgur.com/nHpYl.png)
Ungolfed version as explanation:
```
init = Table[1, {4}, {4}];
result = {init};
forms = {{{1, 0}, {1, 1}}, {{0, 1}, {1, 1}}};
pads = {{1, 1}, {0, 2}, {2, 0}};
patterns =
Flatten[Table[
ArrayPad[k, {i, j}], {k, forms}, {i, pads}, {j, pads}], 2];
main[arr_] :=
With[{nextValid =
Select[arr - # & /@ patterns, AllTrue[#, (# >= 0 &)] &, 2]},
result = Join[result, nextValid];
main[#] & /@ nextValid
];
main@init;
output = Union@result;
```
The longest part of code is a preparing of matrix patterns.
I'll try to golf it harder!
That's all. Add a some mad golfing, and can’t improve the algorithm anymore (
[Answer]
# JavaScript (ES6), 159 bytes
A rather lenghty port of [loopy walt's answer](https://codegolf.stackexchange.com/a/259580/58563).
```
f=(A=new Set([0,19,35]),d=2)=>(B=[...A])[99]?B.map(v=>(g=k=>k--?"#."[v>>k&1]+[`
`[k&3]]+g(k):'')(16)).join`
`:f(A,d^18,B.map(x=>B.map(y=>x&y*d||A.add(x|y*d))))
```
[Try it online!](https://tio.run/##JYzRCoIwGIXve4owsH81RyZFBv9kvkKXY5E0FVttkmIGvrsNOlff@Q6cRzEU3f3dtH1knS7nuUIQaMvP8lL2IHc0TmlyUIRq3BPkkKNkjAlFZJqqLGevooXB@xoNchNFWbBigRw4N2GstvK2uEkTJkptazDkvF4TiI@EsIdrrN/OFQiqr/GJ/p9G5H/4Ih/D70ZPk2CF1jBOvhCf@e5s554le7oaKvDiBw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 28 bytes
```
2r↕1:ÐÐ3r~ᵑᵐç3r~ᵑçaᵐᶜ{0*}∑2<
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6Fjf1jIoetU01tDo84fAE46K6h1snPtw64fByCPPw8kQg7-G2OdUGWrWPOiYa2SwpTkouhuqFmQEA)
Outputs 215 4×4 matrices using `1`s for free and `0`s for occupied cells.
### Explanation
```
2r↕1:ÐÐ3r~ᵑᵐç3r~ᵑçaᵐᶜ{0*}∑2<
2r↕1:ÐÐ Push [[0,1],[1,1]] or [[1,0],[1,1]]
3r~ᵑᵐç Prepend 0, 1 or 2 zeros to each sublist
3r~ᵑç Prepend 0, 1 or 2 zeros to the list
a Get all possible values as a list
ᵐᶜ{0*} Optionally multiply each value by zero
∑ Take the sum
2< Check if all numbers in the result is less than 2
```
[Answer]
# [Haskell](https://www.haskell.org/), 152 bytes
```
import Data.List
r=[[[r,c]|r<-[0..3],c<-[0..3],notElem[r,c]l]|l<-concat<$>subsequences[[[r-1,c+t],[r,c],[r,c+1]]|r<-[1..3],c<-[0..2],t<-[0,1]],l==nub l]
```
[Try it online!](https://tio.run/##TYyxDsIgFEV3v6JDtz4a0RWcdPMPyBsoIZH4Sis8tv47WkyMy81J7sl52Pz0RLWGeV0Sd1fLdryHzIekjTEJHG5JCXMcxzOC@1Fc@EZ@bgLhRkq4JTrLqr/kMmX/Kj46n/eEkOAGRmhu20Hityr/qycE3gk@L5DWsUwdYZ1tiHpNIXKf6hs "Haskell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
56āδš<TÝ37SKδ+€`æε˜ÐÙQiX16Å0rǝ4ô,
```
Outputs as a list of matrices of 0s for `.` and 1s for `#`.
[Try it online](https://tio.run/##AUQAu/9vc2FiaWX//zU2xIHOtMWhPFTDnTM3U0vOtCvigqxgw6bOtcucw5DDmVFpWDE2w4UwcsedNMO0LP///y0tbm8tbGF6eQ) or [try it online with pretty-printing footer](https://tio.run/##AVIArf9vc2FiaWX//zU2xIHOtMWhPFTDnTM3U0vOtCvigqxgw6bOtcucw5DDmVFpWDE2w4UwcsedNMO0/@KAni4jc8OoSsK7LMK2P///LS1uby1sYXp5). (Pretty slow, so only outputs about 175 of them before timing out on TIO.)
**Explanation:**
Step 1: Push the 0-based indices of the two shapes at every possible position on the (flattened) 4x4 board:
```
56āδš< # Push the indices of the two L-shapes in the top-left corner of the
# (flattened) board:
56 # Push 56
ā # Push a list in the range [1,length] (without popping): [1,2]
δ # Apply double-vectorized:
š # Prepend: [[1,5,6],[2,5,6]]
< # Decrease each inner value by 1: [[0,4,5],[1,4,5]]
TÝ37SKδ+€` # Combine it with every position these 2x2-shapes can be on the 4x4
# board:
TÝ # Push a list in the range [0,10]
37SK # Remove the 3 and 7: [0,1,2,4,5,6,8,9,10]
δ # Apply double-vectorized
+ # Add the values together
€` # Flatten it one level down
```
[Try just step 1 online.](https://tio.run/##ASEA3v9vc2FiaWX//zU2xIHOtMWhPFTDnTM3U0vOtCvigqxg//8)
Step 2: Get all possible 0..length combinations of these possible shape-positions, and check if they can be combined without overlapping indices:
```
æ # Get the powerset of this list of lists shape-indices
ε # Foreach over each inner list:
˜ # Flatten it to a single list of indices
ÐÙQ # Check if all indices are unique:
Ð # Triplicate the list of indices
Ù # Uniquify the top copy
Q # Check if the top two lists are still the same
```
[Try just the first two steps online.](https://tio.run/##ASwA0/9vc2FiaWX//zU2xIHOtMWhPFTDnTM3U0vOtCvigqxgw6bOtcucw5DDmVH//w)
Step 3: For each valid list of indices, create the board-matrix and output it:
```
i # If the earlier check is truthy:
X # Push a 1
16Å0 # Push a list of 16 0s
r # Reverse the stack from indices,1,16x0 to 16x0,1,indices
# (where the indices are from the triplcate of step 2)
ǝ # Insert a 1 into the list of 16 0s at the given indices
4ô # Split the list into parts of size 4
, # Pop and output this 4x4 matrix with trailing newline
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes
```
⊞υ⁵⁴¹²⁰⁰F¹³F×X²ι⟦³⁵¦⁶⁷⟧FυF¬&λκ⊞υ⁺λκEυE⪪⍘鲦⁵Φλξ
```
[Try it online!](https://tio.run/##NY5PC4JAEMXvfYo5zsIGqWiEp4S6CYLdosNSlkOb2v7Jvv02mQ083sBvZt6cW2XOvdIhVN626CVEqyTKskTki2tvAKONgKk50KOxWPVjYzCWQELCMUklZOuTmEf87LunV9piQW4k22y7C2oJd/GVgH9OSZ23P8BZlaHOYamGCbHVgyaHhbJN7ZjdkCTEfCJl7Uk7/oJ334IrDyEsX/oD "Charcoal – Try It Online") Link is to verbose version of code. Outputs 215 4×4 grids using `1`s for free and `0`s for occupied cells. Explanation:
```
⊞υ⁵⁴¹²⁰⁰
```
Start with a completely occupied grid. `541200` is `10000100001000010000` in binary, where the `0`s are occupied cells and the `1`s are separators; the grid is obtained by splitting the bits into rows of `5` and then deleting the first column.
```
F¹³
```
Loop over all valid and some invalid (`3`, `4`, `8` and `9`) shape positions. (Invalid shape positions intersect the separators thus preventing shapes from being removed at those positions.)
```
F×X²ι⟦³⁵¦⁶⁷⟧
```
Loop over the bit patterns that represent the two `L` shapes at that position.
```
Fυ
```
Loop over the existing boards.
```
F¬&λκ⊞υ⁺λκ
```
If the shape can be removed then add the new board.
```
EυE⪪⍘鲦⁵Φλξ
```
Output the discovered boards.
] |
[Question]
[
Given a matrix of non-negative numbers (of arbitrary dimension) and a number, get all multi-dimensional indices of the number in that list.
For example, let's say we have the list `[[0,1,0],[1,0,0]]` and the number `1`. In the first list, we see one `1` at the second index. If we were using one-based indices, this would be index `[1,2]`. In the second list, there is another `1` at the first index, so this would be index `[2,1]`. The final list would be `[[1,2], [2,1]]`.
## Rules
* Standard loopholes apply
* Matrix will:
+ only use non-negative numbers
+ not be ragged
+ never be empty
+ every inner list will always have the same length at its depth
+ always be at least 2-D, and never 1-D or 0-D
* You may take input/output in any reasonable format
* You can use one-based or zero-based indexes
* Built-ins are allowed, but I encourage giving non-builtin answers if you do use them
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins
## Test cases (zero-based indexes)
```
[[0, 1, 0], [1, 0, 0], [1, 1, 1]], 1 => [[0, 1], [1, 0], [2, 0], [2, 1], [2, 2]]
[[[2, 3, 4], [3, 1, 5]], [[0, 2, 3], [3, 2, 3]]], 3 => [[0, 0, 1], [0, 1, 0], [1, 0, 2], [1, 1, 0], [1, 1, 2]]
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 2 bytes
*where equal?* Returns a matrix with a column for each index.
```
&=
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs1Kz5eJKi9YwUDBUMLAGYjAJhJrWhrEgCQ0jBWMFE2tjoJippjVQHZAP5AFJTU1r41gAoAkMdw==)
---
A non-builtin solution, 32 bytes:
```
{$[x~*x;!'&x~y;,/(!#x),''x o'y]}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6pWia6o06qwVlRXq6irtNbR11BUrtDUUVevUMhXr4yt5eJKi9YwUDBUMLAGYjAJhJrWhrEgCQ0jBWMFE2tjoJippjVQHZAP5AFJTU1r41guAIJDFWY=)
This is recursive function taking the array as first argument `x` and the element as second argument `y`.
`$[ ; ; ]` is the ternary operator.
`x~*x` If the first value of the array matches the array (this is only the case if `x` is a number) ...
`x~y` does the single number match the searched value? (booleans are 0 and 1)
`&` A list with that many 0s.
`!'` Convert each zero to an empty range. This results in the empty list if x and y are different, and in a list containing an empty list otherwise. Returns a list of indices.
Otherwise, if `x` is an array with at least one axis ...
`x o'y` Call the function recursively on each subarray in `x`.
`!#x` Range from 0 to length of x - 1.
`,''` Prepend the index of the subarray to each index in the recursive results.
`,/` Flatten into a single list of indices.
[Answer]
# [Python](https://www.python.org), ~~91~~ ~~85~~ 83 bytes
*-6 bytes thanks to @Steffan*
*-2 bytes thanks to @movatica*
```
f=lambda a,b,c:c and[(i,*j)for i,d in enumerate(a)for j in f(d,b,c-1)]or[[]]*(a==b)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RU9LCsIwEN17ilkmZQptoyBCT-EyZJE2DabYpIR04VncdKN38jY6oVIYeMP7DfN8z490C35dX0uy5flzte1dT53RoLHD_tKD9kYyh8XIbYjg0IDzMPhlGqJOA9OZHom0zFCmrLkKUUqlCqbbtuNbdZij84lZJmWFUCNUCkES7iuNUoQN54c9IBsEgXAkm8i2E9lyE0kbn9efIFDw7ez_sy8)
[Answer]
# [Python](https://www.python.org) NumPy, 33 bytes
```
lambda a,b:zip(*(a==b).nonzero())
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3FXMSc5NSEhUSdZKsqjILNLQ0Em1tkzT18vLzqlKL8jU0NaEKp6QV5ecq5JXmFlQqZOYW5BeVKCQWFSVWchUUZeaVaGilaYC5GtHRBjoKhjoKBrE6CtEgGsEEodhYTSCpqYmpLdpIR8FYR8EEpNgYrNg0FsQGmQeSgoqDmWBTjGFuW7AAQgMA)
Admittedly a bit trivial.
Test harness borrowed from @mousetail.
[Answer]
# [R](https://www.r-project.org), 19 bytes
```
\(m,x)which(m==x,T)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGa9NSS-My8lMzk1GLbpaUlaboWm2M0cnUqNMszMpMzNHJtbSt0QjQhMjfna-Qq2CoUJQE1aCRrGOgoGOooGGjqJGuAaAQThDQ1NbmQzAYaaaipa8gFNiCxILUoVyOxqCixEmiMkY6CsY6CCZgE6jQFGwURNIYwQMYa6xjpGGnCWFiMNwYaD3HmggUQGgA)
R has almost exactly the correct built-in for this.
---
# [R](https://www.r-project.org), ~~64~~ 59 bytes
*Edit: -5 bytes thanks to pajonk*
```
\(m,x,k=t(t(expand.grid(lapply(dim(m),`:`,1)))))k[m[k]==x,]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bY5BCsIwEEX3PUWWE5hK2yiIkpPUYmNTS2hTQqzQnsWFdeHOC3kbk1bRhcMw_zMwb_7lZsdHVXZ71UpVlCd-P3fHcP3c7kBjjzXvoIOyN6KVi8oqCY0wphlAKg2aYr7JMaa-6lSndcZ5j9kbcQVNOLEHR4YCIiQxkohiAV6_1re7D35CuNcxDeNgAghTWg3CWjE4TIKEIVlO012uJtS8ZLPxWIYJJvTj_uCZw88xx3HWFw)
Roll-your-own solution without using `which`.
`expand.grid` is used to generate all possible sets of indices, which are then tested to see whether the element is equal to the searched-for `x`. Unfortunately, `expand.grid` outputs a "data.frame" (an R-specific matrix-like data type, but that isn't a matrix): [pajonk](https://codegolf.stackexchange.com/users/55372/pajonk)'s golf is to transpose twice (`t(t(...))`) to convert into a matrix, saving 5 bytes compared to the more-conventional `as.matrix(...)`...
[Answer]
# JavaScript, 60 bytes
```
n=>g=(m,...p)=>m.flatMap?.((v,i)=>g(v,...p,i))??(m-n?[]:[p])
```
```
f=
n=>g=(m,...p)=>m.flatMap?.((v,i)=>g(v,...p,i))??(m-n?[]:[p])
console.log(JSON.stringify(f(1)([[0, 1, 0], [1, 0, 0], [1, 1, 1]]))) // [[0, 1], [1, 0], [2, 0], [2, 1], [2, 2]]
console.log(JSON.stringify(f(3)([[[2, 3, 4], [3, 1, 5]], [[0, 2, 3], [3, 2, 3]]]))) // [[0, 0, 1], [0, 1, 0], [1, 0, 2], [1, 1, 0], [1, 1, 2]]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 70 bytes
```
f=lambda l,t,a=[]:l>[]and f(l.pop(),t,a+[len(l)])+f(l,t,a)or[a]*(t==l)
```
[Try it online!](https://tio.run/##RYxBCsIwEEX3nmKWGTtI2@hGiBcZsojUoDCmoWTT08dMEAoD//P@Y/Je3muaa41Owve5BBAqFBz7uzzYh7RANHLJazaow8DySkbQ49C4Elw3Dv5sinOCNW@fVEw0zCPBRDB6AtY8qp5vfUI8HTrPBJbgqpLt0k2l/kenP@@1DRax/gA "Python 2 – Try It Online")
This takes advantage of Python 2's comparison treating lists as greater than integers. This lets us use a single check `l>[]` which is false for integers as well as the empty list, which both are directed to the base case. Here, if the input is an integer that matches the target value, we return a singleton list of the list of indices `a` that we've built up if, and otherwise the empty list.
The recursive call either goes deeper into the last element which is popped, appending the length of the resulting list as the newest index, or continuing with the now-shorter list.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 60 bytes
Expects `(n)(array)`. Prints the 0-based multi-dimensional indices.
```
n=>g=(a,...b)=>a.map?a.map((v,i)=>g(v,...b,i)):a-n||print(b)
```
[Try it online!](https://tio.run/##ZY7RCoMgFIbvewovj2BWtsEY2B4kvLCB4WASFV317s5jiWMT8f89x@P3v/Sml@dsp7Xcbt5I72Q3StCMcz5Q2Wn@1tMjngAbs6E0BsVuuNC7Lt2@T7N1KwzUG2go9H3NSMNIrRjpUbPFrRQlP6uqyDGUJlBF1uZUoVRxsGhhoEUUlltGLviijYCrQo/fYeusR4vkhEq0v6giR/1KHcj@Aw "JavaScript (V8) – Try It Online")
Or **57 bytes** by using optional chaining, as suggested by [@tsh](https://codegolf.stackexchange.com/users/44718/tsh):
```
n=>g=(a,...b)=>a.map?.((v,i)=>g(v,...b,i))||a-n||print(b)
```
(not supported by either TIO or ATO)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~65~~ 64 bytes
```
z=>f=x=>x.at?x.flatMap((y,i)=>f(y).map(w=>[i,...w])):x-z?[]:[[]]
```
[Try it online!](https://tio.run/##RYxBCoMwFET3PcVfJhA/urX8SA/gCUIWwWqxWBNiqImlZ0/jqjAw83gwT/M22@BnF6rV3sd8894kdN4GG5Ib0QQgYBxIwud7vXjKB8mJIslYXBdxWkzojWMsiZkXxRLHV@GdpJoFIu6a8zZWR6d0q5TWebDrZpcRF/tgnjWcKVULaATUWoA6@z/P6HKQfw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 58 bytes
```
Lv$`(\b\d+\b).*\b\1$
$`
+`\[[^][]+]
0
%|',L$`\[(\d+,)*
$#1
```
[Try it online!](https://tio.run/##RYtBCgIxDEX3OUXADHamQRrr3GJukFbqoAs3LmRw5d1rUwaEwH/89/N@bM/XTergCkJdPlRcWtPdp3U8TY2EgAr4klSvWbPPEGD4HnmhVrk25HECOkitqoFRGENmVMs/2uXGAqp6ZoyMF1Oxq9lU/za19x1NxB8 "Retina – Try It Online") Link includes test cases. Explanation:
```
Lv$`(\b\d+\b).*\b\1$
$`
```
Extract the prefixes of the input at every instance of the given number.
```
+`\[[^][]+]
0
```
Simplify irrelevant elements from lists into numbers.
```
%|',L$`\[(\d+,)*
$#1
```
Calculate the multidimensional index corresponding to each found element.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~29~~ 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
QI<Ý"€"×€"Dÿƶ˜0Ks"J.V\)ø
```
1-based output.
-5 bytes (replacing `DΔ€`}\N` with `I<`) by taking the dimensions as additional third input
[Try it online](https://tio.run/##yy9OTMpM/f8/0NPm8FylR01rlA5PB5Euh/cf23Z6joF3sZKXXliM5uEd//8bc0VHRxvpKBjrKJjE6ihEA2lDHQXTWBA72kBHASQFFQczY2O5jAE) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@ZYK@kkJKZm5pXnJmfV2ytUJaYU5oKlLBXslZIzEtRyC3NKcnUhatIzFHIySwuASrQqUwI/R8YYXN4rtKjpjVKh6eDSJfD@49tOz3HwLtYyUsvLEbz8I7/Sv6lJUDbQJbpHNpm/z8aCAx0DHUMYnWigSSUBsLYWCBpFKujAFJhpGOsYwKUMQaKmQJlQHqAYmAREA0UMgZRAA).
**Explanation (of original answer):**
```
Q # Given the (implicit) multi-dimensional input-list and (implicit)
# input-integer, check which are equal
DΔ€`}\N # Determine the depth-1 of this multi-dimensional list:
D # Duplicate the multi-dimensional list of 0s/1s
Δ # Loop until the result no longer changes:
€` # Flatten it one level down
}\ # After the loop: discard the resulting flattened list
N # And push the last (0-based) index of the loop instead
Ý # Pop and push a list in the range [0,depth-1]
"€"× # Map each to that many "€" as string
€ # Then map each string to:
"Dÿƶ˜0Ks" # String "Dÿƶ˜0Ks", where `ÿ` is replaced with the "€"-string
J # Join this list of strings together
.V # Evaluate and execute it as 05AB1E code:
D # Duplicate the multi-dimensional list of 0s/1s
€ # Zero or more `€`: map to a certain depth:
ƶ # Multiply each value by its 1-based index
˜ # Flatten the multi-dimensional list
0K # Remove all 0s
s # Swap, so the multi-dimensional list of 0s/1s is at the top again
\ # Discard the last multi-dimensional list of 01s/1s
) # Wrap all flattened lists on the stack into a list
ø # Zip/transpose; swapping rows/columns
# (after which the result is output implicitly)
```
Minor note: `"€"×` cannot be `'€×`, because this is [the dictionary word](https://codegolf.stackexchange.com/a/166851/52210) for `"view"`: [try it online](https://tio.run/##yy9OTMpM/f9f/VHTmsPT//8HAA).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~200~~ 196 bytes
*-4 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
```
f(a,x,n)char*a,*x;{for(int i[n],d=-1,c;*a;){*a==91?i[++d]=0:*a-93?*a-44?:++i[d]:--d;for(c=0;*a>47&*a<58;)c+=c<0|*a++-x[c]?~c:1;a+=!c;if(c==strlen(x)){for(c=0;c<n;)printf("%d ",i[c++]);puts("");}}}
```
[Try it online!](https://tio.run/##ZU7tSsQwEPytTxEDSvNRrl@HXtNcHyTkR9haDWg8ehUKtb56Te5aqghhZzc7OzMQvwDMcxsZPnBH4NV01HA6iLH96CLremSV07yRccpBUCPISI2Uh7S2irFGy6SkJj7kta9FUZeMWdXoMo4bEQRAJv7oWDw@UFPtnwQBJqFKvqhhLB4U6PobylQYJu9A2Nbz5bnv3p5dNBAyrgpQOUFOnU/TRvi@QZhbBYxpIk6f/TnCmIhpmuZ3Y11Extsbz1Iq4SjlKNEcqYBbG57WmCOc@pIRgXY7JI/oerLyA2YbpgtmWi/6Yco5KsIiv6judeiDSlgt/5f2apf7kv@1Wx3/hc22sL9yB/dp/gE "C (gcc) – Try It Online")
[Answer]
# [Uiua](https://uiua.org), 2 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
⊚=
```
[Try it!](https://uiua.org/pad?src=ZiDihpAg4oqaPQoKZiAxIFtbMCAxIDBdIFsxIDAgMF0gWzEgMSAxXV0KZiAzIFtbWzIgMyA0XSBbMyAxIDVdXSBbWzAgMiAzXSBbMyAyIDNdXV0K)
0-indexed.
[Answer]
# [Scala](http://www.scala-lang.org/), 108 bytes
Golfed version. [Try it online!](https://tio.run/##fVA9b8MgEN39K94IEkrijJFcqWOGTFHVATFcbJxSAXFtWrmN/NvdI@lXlkrA4x7v3t0x1ORpPh2ebZ2wIxdxLgrgjTxaF5ttbFxthw3E3r7ovLcxGaP4lNXdDYdqFkFFpsPiw3WPLj1xth0Xrae0o@5c02CFU8QK949iVIesaMVYVVGyfS4tiFlp/WCRIzlNM9DYFoFbFtQfucX7vqd3vU@9i0cjN3iILqHieYDrQIH4bWTq23SlUCqspLow@XoT5SXlT3p8DZxbXuKOiyQfxZ8/Eld7lXVSAssltM4VjILO3hnXv1h@4doYtpyKaf4E)
```
(m,n)=>m.zipWithIndex.flatMap{case(i,a)=>i.zipWithIndex.flatMap{case(x,b)=>if(x==n)Seq(Seq(a,b))else Seq()}}
```
Ungolfed version. [Try it online!](https://tio.run/##hZExb4MwEIX3/Io3YtVKQkYkKnXMkCmqOiAGl5jEkXGpcSvait9OfYaA0laNhDmbu/fd8dwUQou@f3k@y8JhJ5TB1wI4yBKlMoetOahCNlElnFVtgr18zWhtjctzDvNWJfB79iODNFAGzknqWtpbCI7ayvJSQMk/oANj@anqJ@VOfjjZLkst3E7UY0OgEI1EpIyRdmZxKIb0HmMNEPL/g2ZYy3EOclX6A9KUpmYEj4ahkdxB0cuXSe0llGITp8OlcRfilSPBAj4oSNItRv8rfxmRsMcmwYO14iPb@3JzJF8ejXKTx@9Cj8b4T4ShteaIOdZsANP26kQPY5PcT@C1cTjXvonTJvp9/WFSxoDVCllGHbyvGbEpbuYYj3GT5@GHur7/Bg)
```
object Main {
def findIndices(matrix: Seq[Seq[Int]], num: Int): Seq[Seq[Int]] = {
def helper(matrix: Seq[Seq[Int]], num: Int, prefix: Seq[Int]): Seq[Seq[Int]] = matrix.zipWithIndex.flatMap {
case (inner: Seq[Int], i) =>
inner.zipWithIndex.flatMap {
case (x, j) => if (x == num) Seq(prefix :+ i :+ j) else Seq()
}
}
helper(matrix, num, Seq())
}
def main(args: Array[String]): Unit = {
val matrix = Seq(Seq(0, 1, 0), Seq(1, 0, 0), Seq(1, 1, 1))
val num = 1
println(findIndices(matrix, num)) // [[0, 1], [1, 0], [2, 0], [2, 1], [2, 2]]
}
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 59 bytes
```
->a,n{r=0;a.map{|b|r+=1;c=0;b.map{|d|c+=1;d==n&&p([r,c])}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6@6yNbAOlEvN7Gguiappkjb1tA6GSiSBBFJqUkGiaTY2uapqRVoRBfpJMdq1tbW/k@Ljo420DHUMYjViQaSQDpWxzD2PwA "Ruby – Try It Online")
] |
[Question]
[
Create a program which prints itself, followed by an additional program. This additional program should print the first program, itself, and then a third program. This continues until the nth program, which prints every program in order up to itself, but fails to print a successor.
All programs output by your code should be delimited in the same way across all iterations.
## Example:
Program 1
```
Print(Me,MyEvilTwin)
```
Prints
```
Print(Me,MyEvilTwin)
Print(Me,MyEvilTwin,MyEvilTwin'sEvilTwin)
```
The generated program 2
```
Print(Me,MyEvilTwin,MyEvilTwin'sEvilTwin)
```
Prints
```
Print(Me,MyEvilTwin)
Print(Me,MyEvilTwin,MyEvilTwin'sEvilTwin)
Print(Me,MyEvilTwin,MyEvilTwin'sEvilTwin), And How!
```
The final generated program 3,
```
Print(Me,MyEvilTwin,MyEvilTwin'sEvilTwin), And How!
```
Prints
```
Print(Me,MyEvilTwin)
Print(Me,MyEvilTwin,MyEvilTwin'sEvilTwin)
Print(Me,MyEvilTwin,MyEvilTwin'sEvilTwin), And How!
```
Which fails to include a 4th program, making this 3 iterations.
### Scoring
Your score is the number of iterations your program achieves before failing to print a successor. If no iteration of your program fails to print a successor, your score is infinity. For programs with the same number of iterations, shortest code wins.
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), \$N\$ iterations
```
1:>:#',N take[1 + tostr ':>:#'',N take' + f tostr ':@f map' + + out]:@f map
```
[Try it online!](https://tio.run/##Ky5JTM5OTfn/39DKzkpZXccSCBRKErNTow0VtBVK8otLihTUwVJIcupAqTS4pEOaQm5iAUhMWyG/tCQWKsD1/z8A "Stacked – Try It Online")
\$N\$ appears twice in the code. Linked is the example for \$N=9999\$, but this theoretically works for any number \$N\$. The only change from each iteration is the number at the beginning, which is incremented with each iteration. We map a quine writing function over the range `K:>`, that is, the numbers from `0` to `K-1` inclusive.
The length of the initial code is \$74+2D\$, where \$D\$ is the number of digits in the chosen \$N\$; that is, \$76+2\lfloor\log\_{10} N\rfloor\$. Again for the example \$N=9999\$, the code length is 82.
Better solutions will either decrease the boilerplate or the number of instances of \$N\$.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `D`, Infinite score, 25 bytes
```
`:L$ȧ$17-ʁ꘍(nq\`:Ė\`+,`:Ė
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=D&code=%60%3AL%24%C8%A7%2417-%CA%81%EA%98%8D%28nq%5C%60%3A%C4%96%5C%60%2B%2C%60%3A%C4%96&inputs=&header=&footer=)
While creating this, I discovered that Vyxal is not very good at most things involving eval. It adds a space before the last backtick each time.
Note: The `D` flag is to allow non-ASCII characters in strings, and is necessary for this to work.
```
` `:Ė # Execute using self as argument...
:L # Duplicate and get length
$ȧ$ # Remove whitespace from the other copy
17-ʁ # 0...n-17
꘍ # (For each of that range) append that many spaces to the string
(n # Map... (Proper map is buggy)
q # Uneval
\`:Ė\`+ # Append ':Ė' to make quinish
, # Print
```
[Answer]
# ECMAScript 6, Infinite score, 58 bytes
```
($=n=>{for(i=0;i<n+2;)console.log(`($=${$})(${i++})`)})(0)
```
[Try online](https://jsfiddle.net/bL4ehsn0/)
Based on this quine: <https://twitter.com/cowboy/status/232587756486938624>, I only added a counter and switched it to ECMAScript 6
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), Infinite score, 47 bytes
PARI/GP uses arbitrary-precision integers by default.
```
(f=(n)->for(i=0,n+1,print("(f="f")("i")")))(0)
```
[Try it online!](https://tio.run/##K0gsytRNL/j/XyPNViNPU9cuLb9II9PWQCdP21CnoCgzr0RDCSillKakqaGUqaSppKmpqWGgyfX/PwA "Pari/GP – Try It Online")
[Answer]
# [R](https://www.r-project.org/), infinite score, 105 bytes
```
1 ->x;while(F<=x)cat(F<-F+1,sprintf(a<-"->x;while(F<=x)cat(F<-F+1,sprintf(a<-%s,dQuote(a)))
",dQuote(a)))
```
[Try it online!](https://tio.run/##K/qfmVeWWZyZlJOqEVxZrFecWpKTn5wI5CUnlqSm5xdVKtgqKPk4xzv6@CjpKEDkQELOSpqa/w0VdO0qrMszMoHq3WxsKzSBmoAMXTdtQ53igqLMvJI0jUQbXSWiVKkW66QEluaXpGokampqcikh8/5z/QcA "R – Try It Online")
Proper [Quine](https://codegolf.meta.stackexchange.com/a/4878/95126) that encodes itself and does not access its own source code.
Outputted programs are delimited by a newline character (which also occurs once in the program itself). [Add 8 bytes](https://tio.run/##K/qfmVeWWZyZlJOqEVxZrFecWpKTn5wI5CUnlqSm5xdVKtgqKPk4xzv6@CjpKEDkQELOSpqa/w0VdO0qrMszMoHq3WxsKzSBmoAMXTdtQ53igqLMvJI0jUQbXSWiVKkW66QEluaXpGokamrqqHOpa3IpoYv85/oPAA) to delimit output with a double newline, which does not occur in the program itself.
[Answer]
# [Python 2](https://docs.python.org/2/), infinite score, 48 bytes
```
s="c=2;print's=%r;exec s*'%s,c;c+=1;c";exec s* 2
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9hWKdnWyLqgKDOvRL3YVrXIOrUiNVmhWEtdtVgn2TpZ29bQOlkJJqgA1AEA "Python 2 – Try It Online")
# [Python 3](https://docs.python.org/3/), infinite score, 53 bytes
```
s="c=2;print(f's=%r;exec(s*{c})'%s);c+=1;c";exec(s*2)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v9hWKdnWyLqgKDOvRCNNvdhWtcg6tSI1WaNYqzq5VlNdtVjTOlnb1tA6WQkmbqT5/z8A "Python 3 – Try It Online")
[Answer]
## [Ruby](https://www.ruby-lang.org/en/), infinite, 59 bytes
**Updated:**
```
eval$a=%q[2.times{|i|puts"eval$a=%q[#{i+2}#{$a[-46..]}]"}]
```
**Previous (66 bytes):**
```
eval$a=%q[2.times{|i|puts"eval$a=%q[#{$a.sub /^\d+/,"#{i+2}"}]"}]
```
[Answer]
# [Julia 1.0](http://julialang.org/), infinite score, 69 bytes
```
(c=1;a=:(println.("(c=$(i);a=:($(a)))|>eval" for i = 1:c + 1)))|>eval
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/XyPZ1tA60dZKo6AoM68kJ09PQwkopKKRqQkWVdFI1NTUrLFLLUvMUVJIyy9SyFSwVTC0SlbQVjCEy/z/DwA "Julia 1.0 – Try It Online")
] |
[Question]
[
In this simple challenge you are given an input array `L` of non-negative integers and a number of bins `b` greater than 0 but no more than the length of `L`. Your code must return a new array `M` whose length is `b` and which has binned the array `L`. This is easiest explained with examples.
`L = [1,0,5,1]` and `b = 2` returns `M = [1,6]`.
`L = [0,3,7,2,5,1]` and `b = 3` returns `M = [3,9,6]`.
So far, so simple. However in this question `b` doesn't necessarily have to divide `len(L)`. In this case the last bin will just have fewer numbers to make it up.
Each bin except possibly the last one must have the same number of numbers contributing to its total. The last bin must have no more numbers contributing to it than the other bins. The last bin must have as many numbers contributing to it as possible subject to the other rules.
`L = [0,3,7,2,5,1]` and `b = 4` returns `M = [3,9,6,0]`. `M = [10,8,0,0]` is not an acceptable output as the third bin does not have the name number of numbers contributing to it as bins `1` and `2`.
`L = [0,3,7,2,5]` and `b = 2` returns `M = [10,7]`. `M = [3, 14]` is not an acceptable output as the last bin will have `3` elements contributing to it but the first has only `2`.
`L = [1,1,1,1,1,1,1]` and `b = 3` returns `M = [3,3,1]`.
As a final rule, your code must run in linear time.
You may use any language or libraries you like and can assume the input is provided in any way you find convenient.
---
It turns out that there are some inputs which can't be solved. For example `[1,1,1,1,1]` and `b=4`. Your code can output whatever it likes for those inputs.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 19 bytes
```
{+/⍺(⌈⍺÷⍨≢⍵)⍴⍵,⍺⍴0}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24Rqbf1Hvbs0HvV0AKnD2x/1rnjUuehR71bNR71bgJQOUBTIMqj9/99IIU3BUMFAwVTBkMsYyDZQMFYwVzAC803Q@EbIfAA "APL (Dyalog Unicode) – Try It Online")
We append **b** zeros to the array before reshaping it into equal parts of `⌈⍺÷⍨≢⍵` (**⌈ length of L ÷ b ⌉**) and summing them, as depicted in `,⍺⍴0`, since any amount of blank spots (which are not part of the original array) larger than **b - 1** would be filled with at least **b - 1** elements from other chunks, which makes the balancing point of the last group at maximum **b - 1** difference from the rest. We use **b > b - 1** because it is code golf.
For example, **L** with **15** elements and **b = 3** wouldn't be grouped as
```
x x x x x x
x x x x x x
x x x 0 0 0
```
but rather as (note how the rightmost 2 `x`s "fills in" the leftmost zeros)
```
x x x x x
x x x x x
x x x x x
```
while a **16** elements array would be filled with **2** (**3 - 1**) blank spots, like
```
x x x x x x
x x x x x x
x x x x 0 0
```
[Answer]
# [Python 2](https://docs.python.org/2/), 65 bytes
```
f=lambda l,n:n and[sum(l[:len(l)/n+1])]+f(l[len(l)/n+1:],n-1)or[]
```
[Try it online!](https://tio.run/##RchLCoAgEADQq8xSaSLssxE6iczCKCkYR@mz6PTmrt3j5ffek/SlhJl9XFYPjGIFvKzueqJiZ3kTxbqTxpCmJtT6xxJKa3Q6HZV8HnJDUM4g9AgDwogwUZUuHw "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~75~~ ~~71~~ ~~70~~ 63 bytes
```
function(L,b)colSums(matrix(L[1:(ceiling(sum(L|1)/b)*b)],,b),T)
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NHJ0kzOT8nuDS3WCM3saQos0LDJ9rQSiM5NTMnMy9do7g0V8OnxlBTP0lTK0kzVgeoXCdE83@aRrKGgY6xjrmOkY6pjqGmjokmF4qYpo4RRMRQxwCiwghNBUjMTPM/AA "R – Try It Online")
This pads `L` with `NA` until the length is a multiple of `b`, then takes the column sums of `L` as a matrix with `b` columns, removing `NA` values.
Explaining as a stack-based language:
```
function(L,b){
(ceiling(sum(L|1)/b*b) # push the next multiple of b >= length(L), call it X
1:.. # push the range 1:X
L[..] # use this as an index into L. This forces L
# to be padded to length X with NA for missing values
matrix(..,,b) # create a matrix with b columns, using L for values
# and proceeding down each column, so
# matrix(1:4,,2) would yield [[1,3],[2,4]]
colSums(.., na.rm = T) # sum each column, removing NAs
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
vi3$es
```
[Try it online!](https://tio.run/##y00syfn/vyzTWCW1@P9/E65oAx1jHXMdIx1THcNYAA) Or [verify all test cases](https://tio.run/##y00syfmf8L8s01gltfi/S8h/I65oQx0DHVMdw1guY65oAx1jHXMdIwjfBI1vhMSPBQA).
### Explanation
Consider input `4`, `[0,3,7,2,5,1]` as an example.
```
v % Vertically concatenate stack contents. Gives the empty array, []
% STACK: []
i % Input b
% STACK: [], 4
% Implicitly input L at the bottom of the stack
% STACK: [0,3,7,2,5,1], [], 4
3$e % 3-input reshape. This reshapes L with [] rows and b columns, in
% column-major order (down, then across). [] here means that the
% number of rows is chosen as needed to give b columns. Padding
% with trailing zeros is applied if needed
% STACK: [0 7 5 0;
3 2 1 0]
s % Sum of each column
% STACK: [3 9 6 0]
% Implicitly display
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~54~~ 53 bytes
Saved a byte thanks to @Kirill L.
```
->l,b{s=1.0*l.size/b;(1..b).map{l.shift(s.ceil).sum}}
```
[Try it online!](https://tio.run/##dY7RCoIwGEbvfYofvdH4W1MriZgvIrtQmTnQkDahmnt2W9aFBN2ec@D7bmP1mBs2b/MOK6NYTOimI0o@xa46hzEhVUT6cjCOtbLRoSK1kF1E1NhbO2uhtAIGxgMoihgpHjDmCAkHloMDR46LophihslXpx@d4ulPsF8FSH@T1QDFzFnrLUeIKOsWzKRRTDCM7pkfGG3fZWCaYqO5RRD3QdRaXi@OCevb@QU "Ruby – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 107 bytes
```
j,k,t,Q;f(A,l,b)int*A;{for(j=~0;b>++j;printf("%d,",t))for(t=k=0;(Q=!!(l%b)+l/b)>k;t+=Q<l?A[Q]:0)Q=k+++Q*j;}
```
[Try it online!](https://tio.run/##jc29DoJAEATgWt9CEpJdbo3Hj5q4HoZHuJpQCAbDj0jwrAi@OmJstNJ25stMtjxn2TiWVJEhzTlEVFOKRWOciPv82kGpHpLTUIiS227Kc7DsE1lkEF@1UZWSDFotFlDbKYp6lWJYsRFK7@tDFOtkJ1GrSgihnZKH8XIsGsB@PssBpr04wd4lSWtyBwrIQ27v5gaWhfxJJPm0Je/NNuT/x4JfbJjk1@UwPgE "C (gcc) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 61 bytes
```
l#0=[]
l#n|o<-length l`div`n+1=sum(take o l):(drop o l)#(n-1)
```
[Try it online!](https://tio.run/##HcbNCoQgFAbQfU/xgS2MDLKfTYxPEkFCUtLtGuXMat7doLM6m713R5QSidqMU0aC/@FTkeM1bqB58b@ZS23u7yGj3R0CqBjkcoXzrZBc6SId1jMMzstzRI5RKzQKrUKn0E8QaNMD "Haskell – Try It Online")
[Answer]
# Java 10, ~~96~~ ~~89~~ 86 bytes
```
a->b->{int r[]=new int[b],i=0,n=a.length;for(;i<n;)r[i/((n+b-1)/b)]+=a[i++];return r;}
```
Try it online [here](https://tio.run/##tZAxb8IwEIX3/Iob7cYxBFp1MInUpVKHToyRBwcCNQ2XyL5QIZTfnhoKUhFjqWzJ8nun757exuxMsll@DnbbNo5gE/6yI1vLVYcLsg3KBxXdmEGL2q6s7QIWtfEe3o1FOEQA4Z4NT4bCs2vsErbBZnNyFteFBuPWnp@mAV7Pa2YWqdDiDelayXMoLXrIYDBJXib5IcjgCp1h9QXHkVILm40FZkbWFa7pQ60ax5SdoeKusCPGMC6TlI9KruPMFDaOtXIVdQ7BqX5QpxzzvadqK5uOZBtiUo3sxTmz95Kan@DsmEOatq337LJbwyEVY/Ek0p6frQnn/I/IsZiKZzG5wk7/B/t4R@w9K0jFr3PPEm6hlwr6qB@@AQ).
Found a shorter way to write `i/(n/b+(n%b==0?0:1)` [here:](https://stackoverflow.com/a/19689196/9131078) `i/((n+b-1)/b)`
Thanks to Olivier Grégoire for golfing 3 bytes.
Ungolfed version:
```
input -> bins -> { // input is int[] (original array), bins is int (number of bins)
int result[] = new int[bins], // resulting array, initialized with all 0
i = 0, // for iterating over the original array
n = a.length; // length of the original array
for(; i < n ;) // iterate over the original array
result[i / ((n + bins - 1) / bins)] += input[i++]; // add the element to the right bin; that's bin n/bins if bins divides n, floor(n/bins)+1 otherwise
return result;
}
```
[Answer]
# [Elixir](https://elixir-lang.org/), 98 bytes
```
fn l,b->Enum.map Enum.chunk(l++List.duplicate(0,b-1),round Float.ceil length(l)/b),&Enum.sum/1 end
```
[Try it online!](https://tio.run/##TY/BisIwFEX3/YqHA5LgM7ZVGSiDO4UBwQ8QGdI02jCvaWkSEDr99lpLF7O7HC7ncjWZp2mHe91CRwh5D19ruHbXGLf4iSnuMbkh7HqEf2wk6UQSjOdG2t@gqCM23C0Q5uvD0YZKVLKBKagy2F9Gq9XZOC@K0JBR0msWj9WEY1sHW8CJaumF0oaAtH34khHf5ByXk8KFapOAtsXABRsnePR3gO@LMNY1WnlGMteUweKjm8l8qF8gqFK2NC67DDLpfqbIo7frBQ "Elixir – Try It Online")
The best Elixir has is splitting into parts with a length of **n**. And it cannot ceil division as integer very well, so we do float division, round it up. Unfortunately the only way to do this results in a float, so we round it again to an integer.
[Answer]
# [Perl 6](https://perl6.org), ~~52 51~~ 50 bytes
52 bytes: [Test it](https://tio.run/##dVBNa8JAEL3vrxhETELHbWxapRElvefYW0wlH1tZiGa7uykNkt@eTjSgUHp7M@@DN6OErpZ9YwR8L3mxZuzYwqyoSwGbfr7dxbjLzzHXta21G6pMW5lVWAhZydMB4sfcSz7ylB8zFcLMNMeuJ39khbGwAZcBuMkCfXzBRYpPSHiZenhZ@xjginYXKsAkwNd/yOeRRP8PfQ31cTUwHrU3TQ6lNKrKWnDhIdqDB2eI9vxN66zliq7lpDE2BAccdBwMD9AxNjzgnVqvGVlPZLSX4bPW4zXzLeVFMcI0R4jEjxKFFeWQTo2@Gils1RKSZl4KoaoWhh@6UcxjaSxOc@8KbtZxnpBkNjZ2vSEeNts71Y2brFnX/wI "Perl 6 – Try It Online")
```
->\L,\b{L.rotor(:partial,ceiling L/b)[^b].map: &sum}
```
51 bytes: [Test it](https://tio.run/##dVDRasJAEHy/r1gkmISu19i0SiPK9d3HvonKJbnKQTTXu0tpEL893WjAQunb7M7OMLNG2WrWNU7B14wXC8aOLYyLulSw7M5iJ7mtfW2jzEjrtaywULrSpwMI@Rjs8nizC/ItP0qTwdg1x0tHcuGV87CEiAFEmykm@ILTLT4h4dk2xus6wRTntLtSKW5SfP2HfB5ITP7QN9ME5z0TU3jX5FBqZyrZQgQPYg8xnEHs@Zu1suWGynK6cT6DEEIMQ8wOcGGs7/9OqReMpCcS@uvwUduhzWRFfmKNEOQIQn0bVXhV9u6U6LPRylctIe0mpVKmaqF/YSTWfK2dxyCPb@AuHeYRnYyHxFHc28Ny9evqzo0W7NL9AA "Perl 6 – Try It Online")
```
{@^a.rotor(:partial,ceiling @a/$^b)[^$b].map: &sum}
```
50 bytes: [Try it](https://tio.run/##dVBda8JAEHy/X7FIyAdd01hbpRHl@u5j38TIJbnKQTTXu0tpkPz2dKMBC6Vvszs7w8xqaapF31gJX4u4WDF2asEv6lLCur@chAbfNifkmYhN7WoTploYp0SFhVSVOh@Bi0cvy6Nd5uX7ric1d9I6WEPIAMLdDBN8wdken5DwYh/hdZ3gHJe0u1Jz3M3x9R/yeSQx@UPfTBNcDkxE2W2TQ6msrkQLITzwA0RwAX6I34wRbaypa0w31qUQQIBBgOkROsaG@u@UesVIeiahuw4ftRnbTDfkx7cIXo7A5beWhZPl4E6JPhslXdUSUnZaSqmrFoYPhnwbb5V16OXRDdyl4zyhE39MHEaDPaw3v67u3GTFuv4H "Perl 6 – Try It Online")
```
{map &sum,@^a.rotor(:partial,ceiling @a/$^b)[^$b]}
```
---
47 bytes non-competing [Test it](https://tio.run/##dVBNa4NAEL3vrxiCRKUTa2qb0Ihhe/fYm5jgxzYsmGh311IJ@WW99Y/Z0QgplN7ezJv3eG8aoapV32oBHyuvCBk7djAv6lJA1J/5LvNUbWrlbJpMGZlVWAhZydMBeHZv7XI32Vl5@v3l6fZ46UnKjdAGInAYgJMs0ccnXKb4gIRXqYvj2scA17QbqQCTAJ//IR8nEv0/9NXUx/XAuBRctzmUUjdV1oEDd3wPLpyB770XpbLOa6goxcy12YANNto2bg5wYWzo/kqpQ0bSEwnNOLzVamqz2JIfjxGsHIGLz0YURpSDOyV6b6UwVUdI6kUpRFN1MLzP4bEXS23Qyt0ruEmneUYn8ymx4w72EG1/Xd24Wcgu/Q8 "Perl 6 – Try It Online")
```
{@^a.rotor(:partial,ceiling @a/$^b)[^$b]».sum}
```
It's non-competing as `».sum` is allowed to do the calculations in parallel. So it may or may not be in linear time.
---
## Expanded:
```
{ # bare block with two placeholder parameters 「@a」 and 「$b」
map # for each sublist
&sum, # find the sum
@^a # declare and use first parameter
.rotor( # break it into chunks
:partial, # include trailing values that would be too few otherwise
ceiling @a / $^b # the number of elements per chunk
)[ ^$b ] # get the correct number of chunks if it would be too few
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
NθAηW﹪Lηθ⊞η⁰E⪪η÷LηθIΣι
```
[Try it online!](https://tio.run/##XYs7D4MgFIX3/grGS3Kb2Fc6ONbFpDYmjsaBKikkCIgX@/Mp7dgzne88RiXC6IRJqbY@0iPOTxlg4eXux6CyeyttJIPGTdE4uEv7IpULZAvnrI1rBmRFHrZBW4JGeOi80fSNa0uV3vQk/37IbmIl6OIMmmeVKfVn7As84RWPeMHDMKT9Zj4 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `b`.
```
Aη
```
Input `L`.
```
W﹪Lηθ⊞η⁰
```
Push a `0` to `L` until `L`'s length is divisible by `b`.
```
E⪪η÷LηθIΣι
```
Divide `L`'s length by `b` and split `L` into sections of that length, then sum each section and cast to string for implicit output on separate lines.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 71 bytes
```
L=>b=>Array(b).fill().map((v,i)=>L.slice(s=i*b,s+b).reduce((x,y)=>x+y))
```
[Try it online!](https://tio.run/##ZcvBDsIgEATQu1@ya1fSajxC4r1/YHoACgaDpWG1KV@PHE3M3GbePPWm2eawvk9Lml31so5SGaluOesCBoUPMQKKl14BNgoo1Sg4BuuAZTga4q6h7OZPa2Cn0sDeFcRq08IpOhHTAzzcB@rpSsOEcEY8/I0/aeTS/l8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), 58 bytes
```
i;f(*L,l,b,*m){b=l/b+!!(l%b);for(i=0;i<l;m[i++/b]+=L[i]);}
```
[Try it online!](https://tio.run/##fZLNjpswEMfP66eYZRWtHSYNX8kqJdm@AHvuAXHAgWwtGRIBqdpGefZ0MCTQqLtCwjPjn2f@M/Z2ttVp@X55UuVWH7Mc1nWTqf2XH69sHKpU@U6xiwp3fBqhRonTQpzkRs@l/fjI9USKcLevuNo4oVrrsIiVbc9lYm@iWCUiPF@esnynyhzSqkp/67zkvwTwWv3J9zsy51crdhIhGDtQxcagnAyYpgjtqgWcmLEUbMAJGRhwx63YEuS1EkLaW4OmxbYNfmMm2aS2EFJShMA56Zy54puF1lcrsUR7/szOjF2VblOtdzxCKR6M2dqD/EggSMF@7lUG/bZRGvVKu0XeBBfxapVQiSIv6rzhBYKD0HddmOJXmRG1Zt0C3RAoqx4zVJuoSQYAm1f6tQEzAEOSg1DcpSjQEIdjU3OrzU@tGmGpKnkr03iRGyeU@eSigwt0z@HDg@nDpaAXdojXIQ76@IJejxnKo7jfU/6HlE/xoKeCO@pWMBgVXFw1jb5rssWo5PKOuyVbdhVZf6UuSpcG0HseSm/wfJT@4AUog8FboFwM3hLlkjxW5c2xKtvXSBNl8ylrLzDuB5hAWmbmsjzowBreuv1l0pGjCQ20/y/t44p4epjpUTc1NHt4psaeIZ59V8VBq61qZhT4LGPwn4zo3J/4WK@DL8m1tdH3iWSfdll8T24CNp2zy18 "C (clang) – Try It Online")
`f()` takes parameters as follows:
`L`: pointer to input array
`l`: length of input array
`b`: number of bins
`m`: pointer to buffer that receives new array
Following is a re-entrant version @ 60 bytes:
```
f(*L,l,b,*m){b=l/b+!!(l%b);for(int i=0;i<l;m[i++/b]+=L[i]);}
```
[Answer]
# PHP, 88 bytes
```
function($a,$b){return array_map(array_sum,array_chunk($a,~-count($a)/$b+1))+[$b-1=>0];}
```
anonymous function, takes array and integer, returns array
The only golfing potential this had was replacing `ceil(count($a)/$b))` with `(count($a)-1)/$b+1` and abbreviating `(count($a)-1)` with `~-count($a)`. The resulting float is implicitly cast to integer in the `array_chunk` call.
[Try it online](http://sandbox.onlinephpfunctions.com/code/579c151d1151adb68d8c05e6ea6c62107a3f6179).
] |
[Question]
[
Your input will be a string consisting of small english letters.
Your task is to determine the number of distinct permutations of the original string that are a palindrome.
The input string has up to 100 letters. In the case of a longer string the result might be very big so the output should be the number of permutations modulo 666013.
For example,
```
cababaa -> 3
```
The possible permutations are:
```
aabcbaa
abacaba
baacaab
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins!
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (2), 15 bytes
```
{p.↔}ᶠdl%₆₆₆₀₁₃
```
[Try it online!](https://tio.run/nexus/brachylog2#@19doPeobUrtw20LUnJUHzW1wVDDo6bGR03N//8rJScmAWGi0v8oAA "Brachylog – TIO Nexus")
## Explanation
```
{p.↔}ᶠdl%₆₆₆₀₁₃
{ }ᶠdl Count (l) the number of distinct (d) results (ᶠ) obtainable by:
p permuting {the input}
. to produce an output
↔ that, if reversed, is still the output
%₆₆₆₀₁₃ then take that number modulo 666013
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ ~~16~~ 13 bytes
*-1 byte from Jonathon Allan*
*-3 bytes from Emigna and Adnan*
```
œÙvyÂQO•E›j•%
```
Explanation:
```
œÙ # Unique permutations of [implicit] input
vy # For each permutation...
ÂQ # Check if it is a palindrome
O # If so, increment the counter
•E›j•% # Modulo 666013 (no clue why this number, or even why this rule is in place)
```
[Try it online!](https://tio.run/nexus/05ab1e#@3908uGZZZWHmwL9HzUscn3UsCsLSKv@/5@cmASEiQA)
[Answer]
# [Perl 6](https://perl6.org), ~~104~~ ~~108~~ ~~88~~ 84 bytes
```
{my &f={[*] 1..$_ div 2}
.comb.Bag{*}.&{(2>.grep(*%2))*f(.sum)/[*]($_».&f)%666013}}
```
[Try it online!](https://tio.run/nexus/perl6#bctBCoMwEAXQvacYRMUEOq0Wsgl20WuUIklMooK1VBQk5GTd9U5dW4Uuuuh8PnwezDhomBgPuhkSC8XitmEKd6FXyBCjEqpmgtxzVH0n8Sysox4Tl@YntA99T2mcE0JNisPYkf36lkbl64mJITFj7JAdvV8GMYOFUAm5RoQ8@IKQqtq63X/9ZSGlWlVrY6yt66Zp25Av71u/U0LV@gM "Perl 6 – TIO Nexus")
### How it works
I can't easily generate all permutations and filter them, even if astronomical run-times are allowed, because Perl 6's built-in `permutations` routine straight-out refuses to permute lists of more than 20 elements and the task description requires inputs of up to 100 characters.
So instead I use a direct formula based on the letter frequencies of the input:
1. ```
my &f={[*] 1..$_ div 2}
```
A helper function that halves a number and rounds it down to the nearest integer, and then takes the factorial of that.
2. ```
.comb.Bag{*}.&{ };
```
Tally up the letter frequencies in the input string, and make them the [topic](https://docs.perl6.org/language/variables#The_$__Variable) for the rest of the code.
E.g. for input `abcdabcdddddd` this would be the list `(2, 2, 2, 7)`.
3. ```
(2>.grep(*%2))*
```
If there is more than one odd letter frequency, multiply the result by zero, because no palindromes are possible in that case.
4. ```
f(.sum)/[*]($_».&f)
```
Calculate the number of possible permutations of the characters that will be on "one side" of each palindrome *(which corresponds to a multiset with the multiplicities obtained by halving and flooring the input letter frequencies)*. The formula used is from [this PDF](http://homepage.divms.uiowa.edu/~sokratov/2008m150/multiperm.pdf):
**(n1+...+ nk)! / (n1!⋅...⋅nk1)**
E.g. for input letter frequencies `(2,2,2,7)`, the letters on *one* side of the palindrome form a multiset with multiplicities `(1,1,1,3)`, and the number of permutations is thus `(1+1+1+3)! / (1!⋅1!⋅1!⋅3!) = 120`.
5. ```
%666013
```
Take the result modulo 666013.
[Answer]
# Python3, ~~81~~ 80 bytes
```
from itertools import*
lambda s:sum(a==a[::-1]for a in{*permutations(s)})%666013
```
This is the shortest I could come up with. Not sure if the permutations can be generated more easily...
## Explanation
```
lambda s: # Anonymous function taking a parameter <s>.
sum( # Sum the following terms.
a==a[::-1] # Check whether the permutation <a> is a palindrome,
for a in # for each element <a>,
{ # inside a set that can only contain distinct elements.
* # Splat the elements of the following object:
permutations(s) # the permutations of the input parameter <s>.
} #
)%666013 # Modulo the sum by 666013.
```
## Notes
1. The check `a==a[::-1]` returns a boolean value, but the `sum(...)` function implicitly casts it to an integer (0 or 1) and sums accordingly.
2. I have to use the '[splat operator](https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists)' (not the real name), to extract the elements from the object `permutations(...)`. Otherwise the set (`{...}`) would contain only one element, the object itself.
3. I use a set (`{...}`) to keep only distinct permutations inside.
In Floroid, this is (almost) `z(T(a==aDKaIW(cb(L)))%666013)`, but prints the result instead, and takes input through the command line.
Thanks to [@Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) for saving a byte! --> Changed the `import` style
[Try it online!](https://tio.run/nexus/python3#DcJRCoMwDADQqxR/TAYO9lvoScYocbMQsE1J4pfs7FXeGyXtVNcfBYt2VKCU6B3j8voU0UCB2/nImWsX9ZxhZt/URXab8dk3rYeTszQDwz@OrtwcCkxfWm80IY4L)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Œ!QŒḂ€S%“µɲ€’
```
**[Try it online!](https://tio.run/nexus/jelly#@390kmLg0UkPdzQ9aloTrPqoYc6hrSc3AdmPGmb@//8/OTEJCBMB "Jelly – TIO Nexus")**
### How?
A brute forcer.
```
Œ!QŒḂ€S%“µɲ€’ - Main link: string
Œ! - all permutations
Q - unique
€ - for each
ŒḂ - isPalindromic? (yep a built-in!)
S - sum
% - mod
“µɲ€’ - base 250 compressed number 666013
```
---
I *believe* that **[this](https://tio.run/nexus/jelly#DZE7bpRBEIRz38ISXIITEDhA8gn63fOe@R@7ayLjhNghEkIcgAjJkgMim4RjeC@yTDQatbrqq@rL6@PHt@cfL0@31x@uP727@vvz5vzw6@r169vzw@35y5@b@b6D18f35/vvL0//fs/h@f7b5XJZQ@mHkEuW1FPB4EJZtJhEPfYK3O/QQgm8MWykhUt0TIddEsja4wCMhpJpl1CjCjMwhj3ldShCSeR5SbXlWFgosiGwaM5utK8posW1Usa4GXlq6IseF2gFYKcEkaua0uexiaOlZe2LrVKDuGhNkQlhmChaR09O0kLiEcKWiKGgSOsLHYi4Cxshc0@pYtXNQp6QoNOkqq@tIGYVHyWAc4tB5SjBUjyyn0ZcW2LPyrjXBqcpbSmAes7RRpwl@NTCyDFJoxoIkLbgXIAWgi3UtMWiopxkmxQWLS51iaaThAtGbX2KjROrozIdLB4Xd8tEuk10SkGLUrClgSwjeLgDnxbxNDAvYWZXcj9kghCaQudDqDqZdAGsUICrEQWdG9RXMpjhcJ/fcBzzaLLGUdh8rTXlOSEc/TC3R5tuULVtGWdvApTNF0QpsBYoxsssPqVG3GZoMXNvkvaA3g2sA/YcuuQatIsXmU1NlrGicW9xh4aQCQUts@uhlEiZ2VMc/wE)** will do it more efficiently, but it's **30** bytes (edit: [this pdf](http://homepage.divms.uiowa.edu/%7Esokratov/2008m150/multiperm.pdf) seems to confirm it, courtesy of [smls's answer](https://codegolf.stackexchange.com/a/110992/53748)):
```
ÑHḞµS!÷!P$ - Link 1, palindrome count: string a e.g. 'abcabcd'
Ñ - call the next link (2) as a monad(a) e.g. [2, 2, 2, 1]
H - halve e.g. [1, 1, 1, 0.5]
Ḟ - floor (get pair counts) e.g. [1, 1, 1, 0]
µ - start a new monadic chain - call that p
S - sum(p) e.g. 3
! - factorial e.g. 6
$ - last 2 links as a monad:
! - factorial(p) (vectorises) e.g. [1, 1, 1, 1]
P - product e.g. 1
: - integer division e.g. 6
ĠL€ - Link 2, count characters: string a e.g. 'abcabcd'
Ġ - group indexes e.g. [[1, 4], [2, 5], [3, 6], 7]
L€ - length of €ach e.g. [2, 2, 2, 1]
ÇḂS⁼LḂ$aÑ%“µɲ€’ - Main link: string a e.g. 'abcabcd'
- first check to see if any palindromes will be possible:
Ç - last link (2) as a monad e.g. [2, 2, 2, 1]
Ḃ - mod 2 e.g. [0, 0, 0, 1]
S - sum e.g. 1
$ - last two links as a monad:
L - length(a string) e.g. 7
Ḃ - mod 2 e.g. 1
⁼ - equal? e.g. 1 (1 when palindromes are possible)
a - and
Ñ - next link as a monad e.g. 6
%“µɲ€’ - mod 666013, as in the brute force version.
```
[Answer]
## Mathematica, 46 bytes
```
Permutations@#~Count~_?PalindromeQ~Mod~666013&
```
Takes a list of characters as input.
Terribly inefficient, because it actually generates all permutations of the input and then counts the palindromic ones.
[Answer]
# Mathematica, 68 bytes
```
If[i=Floor[t=Last/@Tally@#/2];Tr[t-i]<1,Multinomial@@i,0]~Mod~666013
```
Pure function taking a list of characters as input and returning an integer. Not as short as [Martin Ender's Mathematica answer](https://codegolf.stackexchange.com/a/110973/56178), but it's a cute approach nonetheless, which seems to be the same approach as in [smls's Perl 6 answer](https://codegolf.stackexchange.com/a/110992/56178).
First, `t=Last/@Tally@#/2` computes the counts of all the distinct characters in the input, divided by `2`; then `i=Floor` rounds down any fractions occurring in `t`. Note that palindromic permutations of the input exist exactly when there is at most one odd number among the original counts, that is, when there is at most one fraction in `t`. We can test for that by simply adding up all the elements of `t-i` (using `Tr`): if the answer is less than `1`, there are palindromic permutations, otherwise not.
If there are, then `i` represents the counts of distinct characters in the left half of the permutations, which can be arranged arbitrarily. The number of ways to do that is exactly the `Multinomial` coefficient (a quotient of certain factorials), which Mathematica has built-in.
[Answer]
# k, 23 bytes
```
{666013!+/{x~|x}'cmb x}
```
If using [oK](http://johnearnest.github.io/ok/), or `cmb` doesn't exist, use `prm` instead of `cmb`.
[Answer]
# Pyth - 15 bytes
```
%l{_I#.pQ666013
```
[Try it online here](http://pyth.herokuapp.com/?code=%25l%7B_I%23.pQ666013&input=%22cababaa%22&debug=0).
[Answer]
# C++14, 161 bytes
As unnamed lambda assuming input is like `std::string` and returning via reference parameter.
```
#import<algorithm>
[](auto s,int&n){auto a=s.begin(),b=s.end();std::sort(a,b);n=0;do n=(n+std::equal(a,b,s.rbegin()))%666013;while(std::next_permutation(a,b));}
```
Ungolfed and usage:
```
#include<iostream>
#include<string>
#import<algorithm>
auto f=
[](auto s,int&n){
auto a=s.begin(),b=s.end();
std::sort(a,b);
n=0;
do
n=(n+std::equal(a,b,s.rbegin()))%666013;
while(std::next_permutation(a,b));
}
;
using namespace std;
int main(){
string s;
s = "cababaa";
s = "abcdabcddddd";
int n;
f(s,n);
cout << n << endl;
}
```
[Answer]
# Ruby, 67 57 52 59 chars
```
->s{s.chars.permutation.uniq.count{|t|t.reverse==t}%666013}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 20 18 bytes
```
á f_¥Zw} l %666013
```
Saved 2 bytes thanks to ETHproductions.
[Try it online!](https://tio.run/nexus/japt#@394oUJa/KGlUeW1CjkKqmZmZgaGxv//KyUnJgFhohIA "Japt – TIO Nexus")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 19 bytes
```
qe!{_W%=}%:+666013%
```
[Try it online!](https://tio.run/nexus/cjam#@1@YqlgdH65qW6tqpW1mZmZgaKz6/39yYhIQJgIA "CJam – TIO Nexus")
Explanation:
```
qe!{_W%=}%:+666013% e# Full program.
q e# Get all input.
e! e# Get all unique permutations.
{_W%=} e# Function to check if a list is a palindrome.
_ e# Duplicate ToS.
W% e# Reverse ToS (Push -1, Modular index of ToS).
= e# Check if ToS is equal to SToS.
% e# Map.
:+ e# Sum (Reduce by addition).
666013 e# Push 666013.
% e# Modulo.
```
[Answer]
# Ohm, 17 bytes
```
I⌐:_₧?¡;;¼,
```
Explanation:
```
I⌐:_₧?¡;;¼, ■Main wire
I⌐: ; ■for _ in permutations(input()){
_₧? ; ■ if(palindrome(_)){
¡ ■ counter++;
; ■ }
; ■}
¼, ■print(counter)
```
[Answer]
# PHP, 182 Bytes
```
function f($a,$b=1){return$a?f($a-1,bcmul($a,$b)):$b;}$a=count_chars($argv[1],$r=1);foreach($a as$v){$c+=$v%2?:0;$c>1?die("0"):$z+=$f=$v/2^0;$r=bcmul(f($f),$r);}echo bcdiv(f($z),$r);
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/9f6004ed96b613b75b61404b22f531af0d80a253)
## Breakdown
```
function f($a,$b=1){ #Factorial
return$a?f($a-1,bcmul($a,$b)):$b;
}
$a=count_chars($argv[1],$r=1); # Array count for every char
foreach($a as$v){
$c+=$v%2?:0; # counter mod 2 ==1
$c>1?die("0"):$z+=$f=$v/2^0; # end program if there are 2 chars which cannot divide by 2
$r=bcmul(f($f),$r);
}
echo bcdiv(f($z),$r);
```
[Answer]
# MATL, 13 bytes
```
Y@Xu!"@tP=Avs
```
Try it at [**MATL Online**](https://matl.io/?code=Y%40Xu%21%22%40tP%3DAvs&inputs=%27cababaa%27&version=19.8.0)
**Explanation**
```
% Implicitly grab input as a string
Y@ % Compute all permutations of the inputs (one per row)
Xu % Determine the unique rows
! % Take the transpose so each permutation is a column
" % For each unique permutation
@ % Take this permutation
tP=A % Duplicate it, reverse it, and compare (yields 1 for palindrome and 0 otherwise)
v % Vertically concatenate the entire stack
s % Compute the sum of all elements
% Implicitly end for loop and display the result
```
] |
[Question]
[
As we know, a quine is a program that outputs its own source code. However, it's also possible to write a program that outputs another, different program, that outputs the first program again. For example, the Python 2 program
```
x = '''x = {}
print 'print '+'"'*3+x.format("'"*3+x+"'"*3)+'"'*3'''
print 'print '+'"'*3+x.format("'"*3+x+"'"*3)+'"'*3
```
will, when run, output the following text:
```
print """x = '''x = {}
print 'print '+'"'*3+x.format("'"*3+x+"'"*3)+'"'*3'''
print 'print '+'"'*3+x.format("'"*3+x+"'"*3)+'"'*3"""
```
When run as a Python program, this will output the original code again. This is called an *iterating quine*. Because you have to run it twice to get the original code back, we say it has *period 2*. But of course, much higher periods are possible.
Your challenge is to write an iterating quine with as long a period as you can, in **100 bytes or less**, in the language of your choice. (Note that my example above doesn't fit this spec, as it's 119 bytes, including the trailing newline.)
Please note the following rules and clarifications:
* The usual quine rules apply, i.e. your program can't use language features that would let it access its own source code directly.
* The iterated outputs have to eventually loop back to exactly your original code, and you have to include a demonstration or proof that it will.
* You must also include an explanation of why the cycle is as long as you say it is. This doesn't have to be at the level of a mathematical proof, but it should be convincing to someone familiar with your language. (This rule is here because I expect some of the answers to involve very, very large numbers.)
* It's fine to say something like "at least 1,000,000 iterations" rather than giving the exact number, as long as you can prove that it is at least that long. In this case, your score would be 1,000,000. Otherwise, your score is the period of your quine.
* The 100 byte limit only applies to your initial program - the programs it outputs can be longer, though of course they'll eventually have to get back down to 100 bytes in order to output your original code.
* You can assume your machine has infinite RAM and infinite runtime, but you can't assume unlimited precision data types (such as integers) if your language doesn't have them. You *can* assume there is no limit to the length of input your parser can handle.
* The highest score wins.
Please note: there is an existing challenge called [Quit Whining; Start Quining](https://codegolf.stackexchange.com/questions/54046/quit-whining-start-quining) that also involves iterating quines. However, aside from being based on the same concept, these are completely different types of challenge. The other one is straight up code golf, whereas this one is (intentionally!) really a busy beaver problem in disguise. The techniques needed to produce a good answer to this question are likely to be very different from what's needed to answer the other question, and this is very much by design.
[Answer]
# PHP, period 2,100,000,000
Who would've thought that this is possible in PHP?! :-)
This is actually my first ever quine and it's 99 bytes long:
```
<?$i=1;$i*=21e8>$i;printf($a='<?$i=%d;$i*=21e8>$i;printf($a=%c%s%c,++$i,39,$a,39);',++$i,39,$a,39);
```
Although PHP supports bigger numbers than `2 * 10^8` by switching from `integer` to `double`, the increment no longer works (leads to an infinite loop) and I haven't found another solution which fits into the 100 bytes. Yet.
Proof is fairly simple, since it's just counting up on each iteration until it reaches the reset point at 2.1 billion.
Credits to [dave](https://codegolf.stackexchange.com/users/8927/dave), who posted the approach in pseudo code in the comments and to [Bob Twells](https://bobtwells.wordpress.com/2010/01/09/php-quine/), from whom I copied the code for a minimal PHP quine.
Test program (sloooooow):
```
<?php
$o = file_get_contents('quine.php');
for ($i = 0; $i < 22e8; $i++) {
if ($i%2==0) exec('php q > p'); else exec('php p > q');
$a = file_get_contents(($i%2==0) ? 'p' : 'q');
echo "\r" . str_pad($i,6,' ') . ":\t$a";
if ($a == $o) {
die;
}
}
```
Well, at least I'm the first one to answer.
[Answer]
# Mathematica, period ~~E8.5678#3~~ ~~E2.1923#4~~ ~E6.2695#3#2
```
Print[ToString[#0, InputForm], "[", #1 - 1 /. 0 -> "Nest[#!,9,9^9^99!]", "]"] & [Nest[#!,9,9^9^99!]]
```
Note that the scores are described in [Hyper-E notation](http://googology.wikia.com/wiki/Hyper-E_notation#Original_definition). The iterations replace the final `Nest[#!,9,9^9^99!]` with the decimal expansions of `Nest[#!,9,9^9^99!]` - 1, `Nest[#!,9,9^9^99!]` - 2, `Nest[#!,9,9^9^99!]` - 3, ..., 3, 2, 1, and back to `Nest[#!,9,9^9^99!]`.
[Answer]
# R, random period with expectation 2^19936-0.5
```
f=function(){
options(scipen=50)
body(f)[[4]]<<-sum(runif(623))
0
cat("f=")
print(f)
}
```
R's default random number generator has a period of 2^19937-1 and equidistribution in 623 consecutive dimensions. Thus, somewhere (but only once) in its period will be a 623-long vector of zeroes. When we get there (and are aligned with the start of the sequence) the sum of the next 623 random U[0,1] numbers will be zero and we return to our original program.
Note that the program will with very high probability pass through the same non-zero state several times before returning to zero. For instance, the sum 311.5 is the most likely, and there are a great many ways that can happen, but the RNG allows the period for 0 to be longer than the period for 311.5.
[Answer]
# [Python 2](https://docs.python.org/2/)
**Period:** \$9\uparrow((99\uparrow\uparrow(9\uparrow((99\uparrow\uparrow(9\uparrow((99\uparrow\uparrow(9\uparrow\uparrow5-1))\uparrow9)-1))\uparrow9)-1))\uparrow9)+1\$
Thanks to @Bubbler for increasing period from \$9\uparrow9\uparrow(99\uparrow\uparrow12)+1\$ to now
```
b=0;s="print'b=%d;s=%r;exec s'%(-~b%eval('9**9'*eval('9**9'*eval('9**9'*9**9**9**9**9))),s)";exec s
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8nWwLrYVqmgKDOvRD3JVjUFyFMtsk6tSE1WKFZX1dCtS1JNLUvM0VC31NKyVNfCxQaRcKSpqalTrKkENYXr/38A "Python 2 – Try It Online")
In the code the `b=0` changes to `b=1` then `b=2` and so on until it reaches `b=decimal expansion of the period` then resets back to `b=0`
[Answer]
# JavaScript, period 9,007,199,254,700,000
Not going to win, but it was fun working with JavaScript on this challenge:
```
a="a=%s;console.log(a,uneval(a),%.0f-1||90071992547e5)";console.log(a,uneval(a),1-1||90071992547e5)
```
Follows the following cycle:
```
a="a=%s;console.log(a,uneval(a),%.0f-1||90071992547e5)";console.log(a,uneval(a),1-1||90071992547e5)
a="a=%s;console.log(a,uneval(a),%.0f-1||90071992547e5)";console.log(a,uneval(a),9007199254700000-1||90071992547e5)
a="a=%s;console.log(a,uneval(a),%.0f-1||90071992547e5)";console.log(a,uneval(a),9007199254699999-1||90071992547e5)
a="a=%s;console.log(a,uneval(a),%.0f-1||90071992547e5)";console.log(a,uneval(a),9007199254699998-1||90071992547e5)
// etc...
a="a=%s;console.log(a,uneval(a),%.0f-1||90071992547e5)";console.log(a,uneval(a),3-1||90071992547e5)
a="a=%s;console.log(a,uneval(a),%.0f-1||90071992547e5)";console.log(a,uneval(a),2-1||90071992547e5)
a="a=%s;console.log(a,uneval(a),%.0f-1||90071992547e5)";console.log(a,uneval(a),1-1||90071992547e5)
a="a=%s;console.log(a,uneval(a),%.0f-1||90071992547e5)";console.log(a,uneval(a),9007199254700000-1||90071992547e5)
// and so on
```
Note: You can make it 18 bytes shorter, while only removing only ~0.08% of the score, like so:
```
a="a=%s;console.log(a,uneval(a),%.0f-1||9e15)";console.log(a,uneval(a),1-1||9e15)
```
[Answer]
# C, period 2,100,000,000
```
unsigned long long i;main(a){i=1;i*=21e8>i;printf(a="ungisned long long i;main(a){i=%d;i*=21e8>i;printf(a=%c%s%2$c,++i,34,a);}",++i,34,a);}
```
Based off the PHP answer (obviously). Will update with explanation when I have time.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 66 bytes, period 2^64
```
f(s){printf(s="f(s){printf(s=%c%s%1$c,34,s,%lu+1L);}",34,s,0+1L);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9No1izuqAoM68EyLJVQuWqJqsWqxqqJOsYm@gU66jmlGob@mha1ypB@AYQ3n@gYoXcxMw8jbL8zBRNrmouBSBI09C05qr9DwA "C (gcc) – Try It Online")
2^64 numbers are available in a `unsigned long` integer. Therefore, a period of 2^64.
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), period [\$f\_{\epsilon\_0+1}(126^{126})\$](https://en.wikipedia.org/wiki/Fast-growing_hierarchy)
```
0".{(}{;]{{x):x;)[.]){+[]\\{[).{f]}{;]x*}if+}:f~~}{;}if.}do{]}x*~}).?:x*`,}if"":n;:c~c`n`":n;:c~c`n`
```
[Try it online!](https://tio.run/##TYk7CsMwDEDv4ilyiugsDzmIIzA4OBhCUtoOAiFf3XG3bu@zX0f55Hd9fXt/OtTJNLCqAEmAiAw6R15XjYBa@DfFWy2zUWlt6GC07VI28c0AFxKfHqM6R2eg3HI60x/2fgM "GolfScript – Try It Online")
```
0"foo"":n;:c~c`n`":n;:c~c`n`
0"foo"":n;:c~c`n`" # Push this number and these two strings
:n; # Assign the second string to n and remove it from the stack
:c~ # Assign the first string to c and execute it
c`n` # Push both strings with "" around
# n is automatically printed at the end of the program
```
Every time this code is executed it prints itsef but replaces the `0` by what `foo` does to it.
What `foo` does:
```
.{(}{;bar}if
.{ }{ }if # Make a copy of the number and compare it to 0
( # If it is not 0, decrement
;bar # If it is 0, replace it by a big number
```
Here is a version of this code with period 10, so we can see it working:
```
0".{(}{;9}if"":n;:c~c`n`":n;:c~c`n`
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/30BJr1qjttrasjYzTUnJKs/aKrkuOSEvAYn5/z8A "GolfScript – Try It Online")
The other 66 bytes compute [\$Hydra(Hydra(Hydra(...)))\$](https://googology.wikia.org/wiki/Kirby-Paris_hydra), where there are \$126^{126}\$ hydras.
```
]{{x):x;)[.]){+[]\{[).{f]}{;]x*}if+}:f~~}{;}if.}do{]}x*~}).?:x*`,
] # Start with [""], which is equivalent to [[]]
{ ~}) # The ~}) becomes }126
.?:x* # Assign 126^126 to x and execute the block that many times
{ .}do{]}x* # While the string is not [], redo everything but with a tree with x pairs of []
x):x; # Increment x
)[.]) # Separate the last element and make a copy of it
{ }{ }if # If it is an empty array
; # False: delete it
+[]\{[).{f]}{;]x*}if+}:f~~ # True: execute this function that finds and cuts a head
+[]\ # Push an empty array under the top of the stack, this will be the outermost pair's parent
{ }:f~ # Assign this function to f and execute it
[). # Start a new array and get the last element of the previous array
{ }{ }if # If it is an empty array
f] # False: keep searching and after that close the array
;]x* # True: delete it, close the array and make x copies of it
+ # Put it back in the parent array
~ # Remove the outermost pair, which was the [] we added earlier
`, # Parse it to a string and get the number of bytes
```
This is not exactly \$Hydra(x)\$, this never resets `x` and therefore \$Hydra(x)\$ is a lower bound.
Here is an example of it that takes a tree as input and outputs \$Hydra(tree)+1\$, this confirms it is working.
```
~1:x;{x):x;)[.]){+[]\{[).{f]}{;]x*}if+}:f~~}{;}if.}do x
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/v87QqsK6ukITSGpG68VqVmtHx8ZUR2vqVafF1lZbx1Zo1WamaddapdXVAblAtl5tSr5Cxf//0UAQCwQA "GolfScript – Try It Online")
\$Hydra(n)>f\_{\omega^{\omega^{...^{\omega^{\omega2+4}}}}}(5)\$ with `n-3` copies of \$\omega\$. Because of the `n-3` and it starting with 5, this program's lower bound should actually be \$f\_{\epsilon\_0+1}(126^{126}-k)\$, where `k` is a small number, but that makes it uglier and I doubt it will have more impact on the answer than not resetting `x`.
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 70 bytes, period 325883196621297064957600206175719056476804879488288708188003274919860959534770101079512433396348062803055739640225395758790852315876868469390603793729639715908136196505908165227136154287969475839017544811926036808089596209081885772040898530121921794489026069641113281250
Other wise known as really big (3.25E270)
```
":1=l8:*6+=S&Q~:'~'=Q~~'H#'||lPffXfX=?1:1=Q$~$~|:1)lPffXfX(Q?:|r2ssH##
```
This is actually the an altered version of the answer I put on the 500 byte iterator
```
":1=l8:*6+=S&Q~:'~'=Q~~'H#'||//if last is equal to 1 and length is 71, delete the delete char, if the last char is '~', delete and push 'H#', which will later return to 'H##', completing the cycle!
lPffXfX=?1:1=Q$~$~| //if length is equal to 15^15^15, then start delete process(append ascii one)
:1)lPffXfX(Q?:| //if the last character is not 1 (the delete checker), and length is less than 15^15^15, duplicate the last value and append
r2ssH## //push the " to the front and output the whole thing
```
Hopefully I got the score right, and there are no bugs. There is no real way to *actually* calculate this value, it is theoretical. But man, that is a huge number!!!
[Try it online!](https://tio.run/##S8/PScsszvj/X8nK0DbHwkrLTNs2WC2wzkq9Tt02sK5O3UNZvaYmJyAtLSItwtbeEKgqUKVOpa7GylATKqoRaG9VU2RUXOyhrPz/PwA "Gol><> – Try It Online")
] |
[Question]
[
The goal of this challenge is to determine the angle of a line in a image.
Rules on the image:
* The image background will be white (`#FFFFFF`)
* The stroke of the line will be black (`#000000`)
* The line will NOT be anti-aliased
* The image will be 100x100 pixels
* The line will start at the center of the image
* The line will start pointing down (6-OClock)
* The line will be 50 pixels long
* The angle of the line will be measured going counterclockwise from the starting position
* The image codec will be either `.jpg` or `.png`
Input format will be a file name passed by the command line arg, script input, or function arg. Output format is simple - just output the number of degrees (e.g. `90`).
Answers can be ±1 degree of the stated measure. Here are a few example images:

A reference image at 45 degrees with gray background

0 degrees

45 degrees

50 degrees

130 degrees

230 degrees

324 degrees
Here is the code used to create the images (this is coded with [Processing](https://processing.org/)):
```
int deg = 45;
int centX = width/2, centY = height/2;
background(255);
noSmooth();
line(centX,
centY,
centX + sin(radians(deg))*50,
centY + cos(radians(deg))*50);
saveFrame("line-"+deg+".png");// image codec can be changed here. use '.png' or '.jpg'
```
[Answer]
# JavaScript (ES6), 225 ~~227~~ ~~244~~ bytes
Let's get the ball rolling:
```
f=s=>{(i=new Image).src=s;c=document.createElement`canvas`.getContext`2d`;c.drawImage(i,0,0,100,100);for(a=360;a--,r=a/180*(m=Math).PI;)if(!c.getImageData(50+48*m.cos(r),50+48*m.sin(r),1,1).data[1]){alert((450-a)%360);break}}
```
Simply pass the URL of the image to the function:
```
f('90deg.png');
```
Alerts degrees within the ±1 range. Passed all test cases.
**Ungolfed**
```
f=s=>{
// create new image and set source
(i=new Image).src=s;
// create canvas and get context
c=document.createElement`canvas`.getContext`2d`;
// set width/height to 100px and draw image on canvas
c.drawImage(i,0,0,100,100);
// check whether for any degree on the theoretical circle a black pixel is found
for(a=360;a--,r=a/180*(m=Math).PI;)
if(!c.getImageData(50+48*m.cos(r),50+48*m.sin(r),1,1).data[1]){
// wait, it should be ccw and the board is rotated 90 degrees
alert((450-a)%360);
break
}
}
```
**Edits**
* *Saved* **17 bytes** – figured I don't need to set the width and height of the canvas element.
* *Saved* **2 bytes** by negating the condition.
[Answer]
# Pyth - ~~28~~ 26 bytes
Uses same sort of brute force strategy as the js answer.
```
f!@F+]'zm+50s*48.t.tT7d_U2
```
Takes input as filename from stdin.
```
f Filters from 1 till predicate is matched
! Boolean not so that only pixel with zero value matched
@F+] Folds by indexing to get pixel value
'z Reads image filename input
m _U2 Maps over both trig ratios
+50 Adds 50 to pixel value
*48 Multiplies pixel value by 48
.t d Takes trig ratio with appropriate option
.t 7 Degrees to radians
T Filter var
```
[Answer]
# Matlab, ~~118~~ 104 bytes
I generate a matrix of the same size as the image with complex numbers (0 in the center) and exctract from that matrix the values which are on the line. The argument of the mean of those is then displayed.
Thanks to @ThomasKwa for suggesting an improvement in accuracy which also resulted in shorter code!!!
```
I=imread(input('','s'));
[y,x]=ndgrid(-50:49);
c=y+i*x;
disp(mod(angle(mean(c(~I(:,:,1))))*180/pi+360,360))
```
[Answer]
## Matlab, ~~86~~ 77 bytes
Here's another way using Matlab:
```
[I,J]=find(~im2bw(imread(input('','s'))));mode(mod(round(atan2d(J-51,I-51)),360))
```
This reads the file (stolen from **flawr**), and finds the indices of the black pixels. Then, it works out the vector that points from the centre of the image to each black pixel, and uses `atan2d` to find the angle, rounding to get integer angles, and doing `mod(...,360)` to get results in the right range. To get the correct angle (there is a bit of error for the pixels close to the centre), take the most commonly calculated angle.
Thanks to **slvrbld** for the `im2bw` suggestion!
[Answer]
# Labview, 10098 Bytes
Let's put another labview code out there.
Since there is no official way to count bytes in labview i use the size of the file when saved. Alternatively counting every wire and function as 1and the case as 2 it would come out to 71.

Load image, flatten to 1D, scan for 0s from both sides and take the first, calc back to point and use geometry to get angle.
] |
[Question]
[
Consider the following standard 15×15 [crossword puzzle](https://en.wikipedia.org/wiki/Crossword) grid.

We can represent this in ASCII art by using `#` for blocks and (space) for white squares.
```
# #
# #
#
# #
### ## ##
## #
# #
# ##
## ## ###
# #
#
# #
# #
```
Given a crossword grid in the ASCII art format above, determine how many words it holds. (The above grid has 78 words. It happens to be [last Monday's *New York Times* puzzle](http://www.xwordinfo.com/Crossword?date=6/1/2015).)
A word is a group of two or more consecutive spaces running vertically or horizontally. A word starts and ends with either a block or the edge of the grid and always runs top to bottom or left to right, never diagonally or backwards. Note that words can span the whole width of the puzzle, as in the sixth row of the puzzle above. A word does not have to be connected to another word.
## Details
* Input will always be a rectangle containing the characters `#` or (space), with rows separated by a newline (`\n`). You can assume the grid is made of any 2 distinct [printable ASCII](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters instead of `#` and .
* You may assume there is an optional trailing newline. Trailing space characters DO count, as they affect the number of words.
* The grid will not always be symmetrical, and it may be all spaces or all blocks.
* Your program should theoretically be able to work on a grid of any size, but for this challenge it will never be larger than 21×21.
* You may take the grid itself as input or the name of a file containing the grid.
* Take input from stdin or command line arguments and output to stdout.
* If you prefer, you may use a named function instead of a program, taking the grid as a string argument and outputting an integer or string via stdout or function return.
## Test cases
1. Input:
```
#
#
#
```
Output: `7` (There are four spaces before each `#`. The result would be the same if each number sign were removed, but Markdown strips spaces from otherwise empty lines.)
2. Input:
```
##
#
##
```
Output: `0` (One-letter words don't count.)
3. Input:
```
######
# #
####
# ## #
# ## #
#### #
```
Output: `4`
4. Input: (May 10's Sunday *NY Times* puzzle)
```
# ## #
# # #
# #
# ### ##
# #
## # #
# ##
# ##
# ## #
# ### ##
# ## ## #
## ### #
# ## #
## #
## #
# # ##
# #
## ### #
# #
# # #
# ## #
```
Output: `140`
## Scoring
Shortest code in [bytes](https://mothereff.in/byte-counter) wins. Tiebreaker is oldest post.
[Answer]
# [Slip](https://codegolf.stackexchange.com/questions/47311/language-design-2-d-pattern-matching), 18 + 3 = 21 bytes
```
>? ( +(X|$^)<<){2}
```
Run with the flags `no` (hence the +3), and uses space/`X` instead of space/`#`. Annoyingly this is longer than CJam/Pyth, but I guess Slip wasn't designed to be particular golfy...
[Try it online](https://slip-online.herokuapp.com/?code=%3E%3F%28%20%20%2B%28X%7C%24%5E%29%3C%3C%29%7B2%7D&input=%20%20%20%20%20X%20%20%20%20X%20%20%20%20%0A%20%20%20%20%20X%20%20%20%20X%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20X%20%20%20%20%0A%20%20%20X%20%20%20X%20%20%20%20%20%20%20%0AXXX%20%20%20%20%20XX%20%20%20XX%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20XX%20%20%20X%20%20%20%20%0A%20%20%20X%20%20%20%20%20%20%20X%20%20%20%0A%20%20%20%20X%20%20%20XX%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0AXX%20%20%20XX%20%20%20%20%20XXX%0A%20%20%20%20%20%20%20X%20%20%20X%20%20%20%0A%20%20%20%20X%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20X%20%20%20%20X%20%20%20%20%20%0A%20%20%20%20X%20%20%20%20X%20%20%20%20%20&config=no). Note that the first example is missing spaces on a few lines.
## Explanation
```
>? Optionally turn right, hence matching either horizontally or vertically
[space] Match a space
( ){2} Group, twice:
[space]+ Match 1+ spaces
(X|$^) Either an X or the boundary of the grid
<< Reverse the match pointer by turning left twice
```
The `n` flag makes output print the number of matches, and the `o` flag enables overlapping matches starting from the same square. The reason for the back-and-forth is because Slip tries matches starting from every square, and we want to make sure we only match a full row rather than a partial one. Slip only returns unique matches, even if they started from different positions.
Note: Originally I had `>?( +(X|$^)<<){2}`, with the first space on the inside. This would miss some cases with 2 space long words at the edge, since the pointer would go like this:
```
XXX XXX XXX XXX
X> X > X< <
XXX XXX XXX XXX
[sp] [sp]+$^ <<[sp] [sp]+ (uh oh match fails)
```
[Answer]
# CJam, ~~18~~ ~~17~~ ~~13~~ 11 bytes
*2 bytes saved by Dennis.*
Uses spaces for filled cells and `1` for empty cells:
```
qN/_z+:~1-,
```
[Test it here.](http://cjam.aditsu.net/#code=qN%2F_z%2B%3A~1-%2C&input=11111%201111%201111%0A11111%201111%201111%0A1111111111%201111%0A111%20111%201111111%0A%20%20%2011111%20%20111%20%20%0A111111111111111%0A11111%20%20111%201111%0A111%201111111%20111%0A1111%20111%20%2011111%0A111111111111111%0A%20%20111%20%2011111%20%20%20%0A1111111%20111%20111%0A1111%201111111111%0A1111%201111%2011111%0A1111%201111%2011111)
## Explanation
```
q e# Read the entire input.
N/ e# Split into lines.
_z e# Make a copy and transpose it.
+ e# Add the lines of the two grids together.
:~ e# Evaluate each line which will push a rep-digit number for each empty-cell chunk.
1- e# Remove all the 1s as these correspond to individual empty cells.
, e# Get the length of the array.
```
[Answer]
# Haskell, 81 bytes
```
import Data.List
m x=sum[1|(_:_:_)<-words x]
f x=m x+m(unlines$transpose$lines x)
```
Uses spaces as block characters and any other (non whitespace) character as an empty cell.
How it works: split input into list of words at spaces. Take a `1` for every word with at lease 2 characters and sum those `1`s. Apply the same procedure to the transposition (split at `\n`) of the input. Add both results.
[Answer]
# Pyth, ~~15~~ ~~14~~ 13 bytes
```
lftTcjd+.zC.z
```
I'm using as seperator and `#` as fill characters instead of their opposite meaning from the OP. Try it online: [Demonstration](https://pyth.herokuapp.com/?code=lftTcjd%2B.zC.z&input=%23%23%23+%23%23%23%23++%23%23%23+%23%23%23%23%23%23%23%0A%23%23%23+%23%23%23%23+%23%23%23%23+%23%23%23%23%23%23%23%0A%23%23%23+%23%23%23%23%23%23%23%23%23+%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23+%23%23%23%23%23+++%23%23%23++%0A%23%23%23%23+%23%23%23%23%23%23%23+%23%23%23%23%23%23%23%23%0A++%23%23%23+%23%23%23+%23%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23+%23%23%23%23%23%23%23++%23%23%23%0A%23%23%23%23%23%23+%23%23%23++%23%23%23%23%23%23%23%23%23%0A%23%23%23+%23%23%23%23%23%23%23%23++%23%23%23%23%23%23+%0A%23%23%23%23%23%23%23%23%23+%23%23%23+++%23%23%23++%0A+%23%23%23++%23%23%23%23%23%23%23%23%23++%23%23%23+%0A++%23%23%23+++%23%23%23+%23%23%23%23%23%23%23%23%23%0A+%23%23%23%23%23%23++%23%23%23%23%23%23%23%23+%23%23%23%0A%23%23%23%23%23%23%23%23%23++%23%23%23+%23%23%23%23%23%23%0A%23%23%23++%23%23%23%23%23%23%23+%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%23+%23%23%23+%23%23%23++%0A%23%23%23%23%23%23%23%23+%23%23%23%23%23%23%23+%23%23%23%23%0A++%23%23%23+++%23%23%23%23%23+%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23+%23%23%23%23%23%23%23%23%23+%23%23%23%0A%23%23%23%23%23%23%23+%23%23%23%23+%23%23%23%23+%23%23%23%0A%23%23%23%23%23%23%23+%23%23%23++%23%23%23%23+%23%23%23&debug=0)
Instead of `#` as fill character this accepts also letters. So you could actually take the solved crossword puzzle, and it would print the number of words. And if you remove the `l` command, it even prints all words. Test it here: [May 10's Sunday NY Times puzzle](https://pyth.herokuapp.com/?code=lftTcjd%2B.zC.z%0A%3BftTcjd%2B.zC.z%0A&input=TKT+OVUM++VAG+ROPEWAY%0AUNH+NANO+DENY+ATEDIRT%0ALEE+CUCAMONGA+GOGGLED%0AILLTELL+OFTEN+++LIL++%0APLOY+TEARFUL+GREENING%0A++CPA+ANT+ROLLINGGAIT%0AGRUELING+MASTIFF++MNO%0ARESOLD+EVE++SALIENCES%0AACT+ALBRIGHT++ENDEAR+%0ABUTCHERED+YAO+++OAR++%0A+RRR++BROKENRIB++TLC+%0A++EOS+++WIN+BRANGHOFF%0A+BECOME++NATIONAL+SLR%0APRISCILLA++CTN+NORWAY%0AION++DIAGRAM+EGGWHITE%0ALIFEISSWEET+PRO+NEL++%0AELLIOTTS+MAYISEE+ILLS%0A++ODD+++DONUT+SPANIEL%0AREWEAVE+EVERAGAIN+AAA%0AEXERTED+RENT+SPCA+MSN%0ACORSETS+ADD++TEST+SET&debug=0)
### Explanation
```
.z all input rows
C.z all input columns (C transposes)
+ add them (all rows and columns)
jd join by spaces
c split by spaces
f filter for pieces T, which satisfy:
tT len(T) > 1
l length, implicitly printed
```
[Answer]
# JavaScript (*ES6*) 87 ~~121 147~~
Build the transposition of input string and append it to input, then count the strings of 2 or more spaces.
Run the snippet in Firefox to test.
Credits @IsmaelMiguel, a solution for ES5 (122 bytes):
```
function F(z){for(r=z.split(/\n/),i=0;i<r[j=0][L='length'];i++)for(z+='#';j<r[L];)z+=r[j++][i];return~-z.split(/ +/)[L]};
```
```
F=z=>
(
r=z.split(/\n/),
[r.map(r=>z+=r[i],z+='#')for(i in r[0])],
~-z.split(/ +/).length
)
// TEST
out=x=>O.innerHTML += x + '\n';
[
' # # \n # # \n # \n # # \n### ## ##\n \n ## # \n # # \n # ## \n \n## ## ###\n # # \n # \n # # \n # # ', '##\n #\n##', ' #\n #\n #',
'######\n# #\n ####\n# ## #\n# ## #\n#### #',
' # ## # \n # # # \n # # \n # ### ##\n # # \n## # # \n # ## \n # ## \n # ## #\n # ### ##\n# ## ## #\n## ### # \n# ## # \n ## # \n ## # \n # # ##\n # # \n## ### # \n # # \n # # # \n # ## # '
].forEach(x=>out(x.replace(/ /g,'.')+'\n'+F(x)+'\n'))
```
```
<pre id=O></pre>
```
[Answer]
# [J](http://jsoftware.com/), 38 bytes
```
1#.1<[:#;._1 1:,@,.[:(,!.1|:)'#'&=;._2
```
[Try it online!](https://tio.run/##dVJBasMwELzvK6YZqGNwhVUCKUoMgUJPPfUaSg@loeTSD/Tvruxk7V05FbbkGe2uZkc@96tQndAlVGjQIuX3IeD57fWljwxxf0zchY@ImJpDE45p3dyF@JvqitV9l3ce@1q@Pr9/sEWHE96HGq0gD7q5lkvYxoZxHEINvCLmZ1o4Lpq@fSqPAafpNobDVDDgofa4O7IUMcgmaAXRj2ueCA0axJtgl6AneoFLrH3GTVs0Si/NqiNusSjZGVMbRtGg2lIY5cyc4jmzxoWFBuUpTtWkoci90GqsVyH0JY3JKO0RG8dFF6bD@dq8F1bDf06WGvx9uN9hZvMl938 "J – Try It Online")
] |
[Question]
[
Let's create a N×N grid of spaces and underscores that can be used to visually determine if a number is prime. (N may be any positive integer.)
This grid has three simple rules:
1. The nth column contains the repeated pattern of n - 1 underscores followed by one space. This pattern starts at the first row and is stopped, possibly mid-pattern, at row N. (Rows and columns are 1-indexed.)
2. The first column is replaced with all underscores instead of all spaces.
3. If a space occurs somewhere the row index equals the column index it is replaced with an underscore.
# Example: N = 10
```
1
1234567890 <-- column indices
1__________
2__________
3__________
4_ ________
5__________
6_ _______
7__________
8_ _ ______
9__ _______
10_ __ _____
^ row indices
```
The indices are just for clarity. The plain grid itself (what your program must output) is:
```
__________
__________
__________
_ ________
__________
_ _______
__________
_ _ ______
__ _______
_ __ _____
```
Notice that:
* The first column is all underscores.
* The second column goes underscore space, underscore space, etc., except for the underscore on row 2.
* The third column goes underscore underscore space, underscore underscore space, etc., except for the underscore on row 3.
* etc.
**Also notice that besides 1, only prime numbered rows have underscores in every column.**
Since underscores span the entire font width, each prime numbered row forms a continuous solid line. So checking if a number is prime or not is quite easy visually; just check if its line is solid across all columns. (In fact looking up to the square root of the row index suffices but outputting that grid seems less elegant.)
# Program
Write a program that will draw these grids given N via stdin (or closest alternative). Output goes to stdout (or closest alternative) and should only contain spaces, underscores, and newlines, with an optional trailing newline.
The shortest code wins.
[Answer]
# CJam, ~~33~~ ~~28~~ 27 bytes
```
q~,:)_f{f{md\1=+'_S?}0'_tN}
```
[Try it online.](http://cjam.aditsu.net/ "CJam interpreter")
### How it works
```
q~ " Read one line from STDIN and evaluate it. ";
,:) " For “N”, push [ 1 ... N ]. ";
_ " Push a copy. ";
f{ " For each “I in [ 1 ... N ], push “I [ 1 ... N ]”; then: ";
f{ " For each “J in [ 1 ... N ], push “J I”; then: ";
md\ " Push “J % I J / I”. ";
1=+ " Calculate “J % I + (J / I == 1)”. ";
'_S? " Push an underscore if the result is truthy and a space otherwise. ";
} " ";
0'_t " Replace the first character of the resulting array by an underscore. ";
N " Push a newline. ";
} " ";
```
### Example run
```
$ cjam solid-primes.cjam <<< 10
__________
__________
__________
_ ________
__________
_ _______
__________
_ _ ______
__ _______
_ __ _____
$ cjam solid-primes.cjam <<< 100 | md5sum # trailing newline
e4396b316989813dada21141b569ccf9 -
```
[Answer]
# Ruby, ~~77~~ 73 characters
```
puts (1..n=gets.to_i).map{|a|?_+(2..n).map{|b|a!=b&&a%b==0? ' ':?_}.join}
```
Some tricks I used:
* The `..` operator has almost the lowest precedence of all operators in Ruby, so `(1..n=gets.to_i)` just works.
* Instead of adding an extra `a!=1` condition when checking to see if the character should be a space instead of an underscore (since the first row is all underscores), I just started the range from `2` and prepended an extra `?_`.
* Line A can become line B:
```
A | a%b==0&&a!=b ? ' ':?_
B | a!=b&&a%b==0? ' ':?_
```
because I have to have an extra space between `b` and `?` in line A, but that's not needed between `0` and `?` in line B. `b?` is a valid Ruby method, but `0?` is not.
* `puts` will automatically join arrays with newlines for you, removing the need for an extra `*"\n"`.
Output for `n=100`:
```
____________________________________________________________________________________________________
____________________________________________________________________________________________________
____________________________________________________________________________________________________
_ __________________________________________________________________________________________________
____________________________________________________________________________________________________
_ _________________________________________________________________________________________________
____________________________________________________________________________________________________
_ _ ________________________________________________________________________________________________
__ _________________________________________________________________________________________________
_ __ _______________________________________________________________________________________________
____________________________________________________________________________________________________
_ _ ______________________________________________________________________________________________
____________________________________________________________________________________________________
_ ____ _____________________________________________________________________________________________
__ _ _______________________________________________________________________________________________
_ _ ___ ____________________________________________________________________________________________
____________________________________________________________________________________________________
_ __ __ ___________________________________________________________________________________________
____________________________________________________________________________________________________
_ _ ____ __________________________________________________________________________________________
__ ___ _____________________________________________________________________________________________
_ ________ _________________________________________________________________________________________
____________________________________________________________________________________________________
_ _ _ ___ ________________________________________________________________________________________
____ _______________________________________________________________________________________________
_ __________ _______________________________________________________________________________________
__ _____ ___________________________________________________________________________________________
_ _ __ ______ ______________________________________________________________________________________
____________________________________________________________________________________________________
_ _ ___ ____ _____________________________________________________________________________________
____________________________________________________________________________________________________
_ _ ___ _______ ____________________________________________________________________________________
__ _______ _________________________________________________________________________________________
_ ______________ ___________________________________________________________________________________
____ _ _____________________________________________________________________________________________
_ _ __ __ _____ __________________________________________________________________________________
____________________________________________________________________________________________________
_ ________________ _________________________________________________________________________________
__ _________ _______________________________________________________________________________________
_ _ __ _ _________ ________________________________________________________________________________
____________________________________________________________________________________________________
_ __ ______ ______ _______________________________________________________________________________
____________________________________________________________________________________________________
_ _ ______ __________ ______________________________________________________________________________
__ _ ___ _____ _____________________________________________________________________________________
_ ____________________ _____________________________________________________________________________
____________________________________________________________________________________________________
_ _ _ ___ ___ _______ ____________________________________________________________________________
______ _____________________________________________________________________________________________
_ __ ____ ______________ ___________________________________________________________________________
__ _____________ ___________________________________________________________________________________
_ _ ________ ____________ __________________________________________________________________________
____________________________________________________________________________________________________
_ __ __ ________ ________ _________________________________________________________________________
____ _____ _________________________________________________________________________________________
_ _ __ _____ _____________ ________________________________________________________________________
__ _______________ _________________________________________________________________________________
_ __________________________ _______________________________________________________________________
____________________________________________________________________________________________________
_ ___ _ __ ____ _________ ______________________________________________________________________
____________________________________________________________________________________________________
_ ____________________________ _____________________________________________________________________
__ ___ _ ___________ _______________________________________________________________________________
_ _ ___ _______ _______________ ____________________________________________________________________
____ _______ _______________________________________________________________________________________
_ __ ____ __________ __________ ___________________________________________________________________
____________________________________________________________________________________________________
_ _ ____________ ________________ __________________________________________________________________
__ ___________________ _____________________________________________________________________________
_ __ _ __ ___ ____________________ _________________________________________________________________
____________________________________________________________________________________________________
_ _ _ __ _____ _____ ___________ ________________________________________________________________
____________________________________________________________________________________________________
_ __________________________________ _______________________________________________________________
__ _ _________ _________ ___________________________________________________________________________
_ _ ______________ __________________ ______________________________________________________________
______ ___ _________________________________________________________________________________________
_ __ ______ ____________ ____________ _____________________________________________________________
____________________________________________________________________________________________________
_ _ __ _ _____ ___ ___________________ ____________________________________________________________
__ _____ _________________ _________________________________________________________________________
_ ______________________________________ ___________________________________________________________
____________________________________________________________________________________________________
_ _ ____ _ ______ ______ _____________ __________________________________________________________
____ ___________ ___________________________________________________________________________________
_ ________________________________________ _________________________________________________________
__ _________________________ _______________________________________________________________________
_ _ ___ __ __________ _____________________ ________________________________________________________
____________________________________________________________________________________________________
_ _ __ ____ __ ___________ ______________ _______________________________________________________
______ _____ _______________________________________________________________________________________
_ _ __________________ ______________________ ______________________________________________________
__ ___________________________ _____________________________________________________________________
_ ____________________________________________ _____________________________________________________
____ _____________ _________________________________________________________________________________
_ _ _ ___ ___ _______ _______ _______________ ____________________________________________________
____________________________________________________________________________________________________
_ ____ ______ __________________________________ ___________________________________________________
__ _____ _ _____________________ ___________________________________________________________________
_ _ ____ _________ ____ ________________________ __________________________________________________
```
Now including Extra-Special™ Mega-Colorful Red© Highlight-Magic™® Extended Edition©: (click thumbnail to enlarge)
# Ruby with color, 110 characters
```
puts (1..n=gets.to_i).map{|a|x=(2..n).map{|b|a!=b&&a%b==0? ' ':?_}.join;x.index(' ')??_+x :"\e[41m_#{x}\e[0m"}
```
[](https://i.stack.imgur.com/zEcp6.png)
[Answer]
# J - 28 char
```
1('_ '{~0==+&|:1&=+|/~)@:+i.
```
Explained by explosion:
```
1( )@:+i. NB. on vector 1..n, do
|/~ NB. take the table "column modulo row"
1&=+ NB. add 1 to column 1
= NB. identity matrix of size 10
&|: NB. transpose both tables (now table is row mod col)
+ NB. add them
'_ '{~0= NB. space if cell=0 else underscore
```
What it looks like:
```
1('_ '{~0==+&|:1&=+|/~)@:+i.25
_________________________
_________________________
_________________________
_ _______________________
_________________________
_ ______________________
_________________________
_ _ _____________________
__ ______________________
_ __ ____________________
_________________________
_ _ ___________________
_________________________
_ ____ __________________
__ _ ____________________
_ _ ___ _________________
_________________________
_ __ __ ________________
_________________________
_ _ ____ _______________
__ ___ __________________
_ ________ ______________
_________________________
_ _ _ ___ _____________
____ ____________________
```
[Answer]
# Python 2, ~~76~~ 71
```
r=range(1,input()+1)
for i in r:print''.join("_ "[i%j<1<j<i]for j in r)
```
Not sure if it can get any shorter than this... These keywords: `range`, `input` and `print` cost quite a lot.
[Answer]
## APL (28)
```
'_ '[(1+(1≠⊢)∧≠∧0=|⍨)/¨⍳2⍴⎕]
```
Explanation:
* `⍳2⍴⎕`: read a number N and make an N-by-N coordinate matrix
* `(`...`)/¨`: for each pair of coordinates, apply the following function:
+ A cell must have a space if:
+ `0=|⍨`: y `mod` x = 0, and
+ `≠`: x isn't equal to y, and
+ `1≠⊢`: x isn't `1`.
+ `1+`: Add `1` to the resulting bit matrix because APL arrays start at 1.
* `'_ '[`...`]`: replace each `1` with an underscore and `2` with a space.
[Answer]
## Perl, ~~69~~ 61
Updated version (thanks, *Dennis*!)
```
$n=<>;for$i(1..$n){say"_".join"",map{$i%$_|$i==$_?_:$"}2..$n}
```
Original version:
```
$n=<>;for$i(1..$n){say"_".join("",map{$i%$_||$i==$_?"_":" "}(2..$n))}
```
[Answer]
# CJam, 27 bytes
```
q~:I,{__I?'_*S+I*I<'_t}%zN*
```
[Try it online.](http://cjam.aditsu.net/ "CJam interpreter")
This approach achieves the same byte count as my other answer, but I thought it was worth posting anyway. Instead of marking proper multiples in every row, it does exactly what the specification says.
### How it works
```
q~:I " Read an integer I from STDIN. ";
,{ }% " For each J ∊ {1,...,I}: ";
'_*S+ " Push J - 1 underscores followed by a space. ";
I*I< " Repeat the pattern to complete I characters. ";
_I? " For the first row, replace all spaces with underscores. ";
_ '_t " Replace the Jth character by an underscore. ";
zN* " Transpose rows and columns; separate with linefeeds. ";
```
### Example run
```
$ cjam prime-lines.cjam <<< 10; echo
__________
__________
__________
_ ________
__________
_ _______
__________
_ _ ______
__ _______
_ __ _____
$ cjam prime-lines.cjam <<< 100 | md5sum # no trailing newline
83c7b974e1510f482322456a9dbb461f -
```
[Answer]
## C, 143
C is obviously not the right choice of language for this. But for completeness, here's one possible way to do it in C. Works for values of *n* up to 1048575. Reads *n* from standard input.
```
#include <stdio.h>
main(){int n,i=0,j;scanf("%d",&n);char x[1<<20];x[n+1]=0;
for(;++i<=n;){for(j=0;++j<=n;)x[j]=i%j|i==j|j==1?95:32;puts(x+1);}}
```
It is very fast, however.
* Runtime for *n*=1,000,000 (which produces a 1,000,000,000,000-element grid) is approximately 55 minutes on my system.
* Runtime for *n*=1000 (which produes a 1,000,000-element grid) is less than 1/100 second.
] |
[Question]
[
**Task:**
Create a program that will take an acronym as input, for example `dftba`, and generate some possible phrases that the acronym could stand for. You can use wordlist as word input. Inspired by <https://www.youtube.com/watch?v=oPUxnpIWt6E>
**Example:**
```
input: dftba
output: don't forget to be awesome
```
**Rules:**
* Your program can't generate the same phrase every time for the same acronym, there must be randomization
* Input will be all lowercase
* Post a few examples (input and output)
* Any language is accepted
* It's a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so most upvotes win!
[Answer]
# HTML, CSS, and JavaScript
### HTML
```
<div id='word-shower'></div>
<div id='letter-container'></div>
```
### CSS
```
.letter {
border: 1px solid black;
padding: 5px;
}
#word-shower {
border-bottom: 3px solid blue;
padding-bottom: 5px;
}
```
### JS
```
var acronym = 'dftba', $letters = $('#letter-container')
for (var i = 0; i < acronym.length; i++) {
$letters.append($('<div>').text(acronym[i]).attr('class', 'letter'))
}
var $word = $('#word-shower')
setInterval(function() {
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://randomword.setgetgo.com/get.php') + '&callback=?', function(word) {
word = word.contents.toLowerCase()
$word.text(word)
$letters.children().each(function() {
if (word[0] == this.innerText) {
this.innerText = word
return
}
})
})
}, 1000)
```
---
Uses a random word generator and shows live results as it looks for words.
[Here is a fiddle if you want to run it yourself.](http://jsfiddle.net/5KrVE/embedded/result/)
Here's a GIF of the output:

[Answer]
# Java
Fetches a word list from wiktionary. Chooses a random word from that list that starts with the correct letter. Then uses Google suggest recursively to look for possible next words. Outputs a list of possibilities. If you re-run it with the same acronym, you will get different results.
```
import java.io.*;
import java.net.*;
import java.util.*;
public class Acronym {
static List<List<String>> wordLists = new ArrayList<List<String>>();
static {for(int i=0; i<26; i++) wordLists.add(new ArrayList<String>());}
static String acro;
public static void main(String[] args) throws Exception {
acro = args[0].toLowerCase();
//get a wordlist and put words into wordLists by first letter
String s = "http://en.wiktionary.org/wiki/Wiktionary:Frequency_lists/PG/2006/04/1-10000";
URL url = new URL(s);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
if(inputLine.contains("title")) {
int start = inputLine.indexOf("title=\"");
int end = inputLine.lastIndexOf("\">");
if(start>=0 && end > start) {
String word = inputLine.substring(start+7,end).toLowerCase();
if(!word.contains("'") && !word.contains(" ")) {
char firstChar = word.charAt(0);
if(firstChar >= 'a' && firstChar <='z') {
wordLists.get(firstChar-'a').add(word);
}
}
}
}
}
//choose random word from wordlist starting with first letter of acronym
Random rand = new Random();
char firstChar = acro.charAt(0);
List<String> firstList = wordLists.get(firstChar-'a');
String firstWord = firstList.get(rand.nextInt(firstList.size()));
getSuggestions(firstWord,1);
}
static void getSuggestions(String input,int index) throws Exception {
//ask googleSuggest for suggestions that start with search plus the next letter as marked by index
String googleSuggest = "http://google.com/complete/search?output=toolbar&q=";
String search = input + " " + acro.charAt(index);
String searchSub = search.replaceAll(" ","%20");
URL url = new URL(googleSuggest + searchSub);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
String[] parts = inputLine.split("\"");
for(String part : parts) {
if(part.startsWith(search)) {
//now get suggestions for this part plus next letter in acro
if(index+1<acro.length()) {
String[] moreParts = part.split(" ");
Thread.sleep(100);
getSuggestions(input + " " + moreParts[index],index+1);
}
else {
String[] moreParts = part.split(" ");
System.out.println(input + " " + moreParts[index]);
}
}
}
}
in.close();
}
}
```
Sample output:
```
$ java -jar Acronym.jar ght
great harvest trek
great harvest tulsa
great harvest taylorsville
great harvest temecula
great harvest trek
great harvest twin
great harvest tempe
great harvest twin
great harvest turners
great harvest twitter
great horned toad
great horned toads
great horned tomato
great horned tomato
great horned turtle
great harvest trek
great harvest tulsa
great harvest taylorsville
great harvest temecula
great harvest trek
great harvest twin
great harvest tempe
great harvest twin
great harvest turners
great harvest twitter
great horned toad
great horned toads
great horned tomato
great horned tomato
great horned turtle
great harvest trek
great harvest tulsa
great harvest taylorsville
great harvest temecula
great harvest trek
great harvest twin
great harvest tempe
great harvest twin
great harvest turners
great harvest twitter
great horror thriller
great horror tv
great horror thriller
great horror titles
great horror tv
great holiday traditions
great holiday treats
great holiday toasts
great holiday tech
great holiday travel
great holiday treat
great holiday tips
great holiday treat
great holiday toys
great holiday tour
great harvest trek
great harvest tulsa
great harvest taylorsville
great harvest temecula
great harvest trek
great harvest twin
great harvest tempe
great harvest twin
great harvest turners
great harvest twitter
great horned toad
great horned toads
great horned tomato
great horned tomato
great horned turtle
```
Unfortunately, the Google suggest URL stopped working after a while - perhaps my IP was blacklisted by Google for mis-use?!
[Answer]
# Ruby
so ruby. many doge. wow.
[Online Version](http://ideone.com/LWUf2o)
```
@prefix = %w[all amazingly best certainly crazily deadly extra ever few great highly incredibly jolly known loftily much many never no like only pretty quirkily really rich sweet such so total terribly utterly very whole xtreme yielding zippily]
@adjective = %w[appealing app apl attractive brave bold better basic common challenge c++ creative credit doge durable dare enticing entertain extreme fail fabulous few favourite giant gigantic google hello happy handy interesting in improve insane jazz joy j java known kind kiwi light laugh love lucky low more mesmerise majestic open overflow opinion opera python power point popular php practice quirk quit ruby read ready stunning stack scala task teaching talking tiny technology unexpected usual useful urban voice vibrant value word water wow where xi xanthic xylophone young yummy zebra zonk zen zoo]
def doge(input)
wow = ""
input.chars.each_slice(2) do |char1, char2|
if char2 == nil
wow << (@prefix + @adjective).sample(1)[0] + "."
break
end
wow << @prefix.select{|e| e[0] == char1}.sample(1)[0]
wow << " "
wow << @adjective.select{|e| e[0] == char2}.sample(1)[0]
wow << ". "
end
wow
end
puts doge("dftba")
puts doge("asofiejgie")
puts doge("iglpquvi")
```
Examples:
```
deadly favourite. terribly better. challenge.
all scala. only favourite. incredibly enticing. jolly giant. incredibly extreme.
incredibly gigantic. loftily popular. quirkily usual. very interesting.
```
[Answer]
# Mathematica
Some terms that commonly appear in acronyms.
```
terms = {"Abbreviated", "Accounting", "Acquisition", "Act", "Action", "Actions", "Activities", "Administrative", "Advisory", "Afloat", "Agency", "Agreement", "Air", "Aircraft", "Aligned", "Alternatives", "Analysis", "Anti-Surveillance", "Appropriation", "Approval", "Architecture", "Assessment", "Assistance", "Assistant", "Assurance", "Atlantic", "Authority", "Aviation", "Base", "Based", "Battlespace", "Board", "Breakdown", "Budget", "Budgeting", "Business", "Capabilities", "Capability", "Capital", "Capstone", "Category", "Center", "Centric", "Chairman", "Change", "Changes", "Chief", "Chief,", "Chiefs", "Closure", "College", "Combat", "Command", "Commandant", "Commander","Commander,", "Commanders", "Commerce", "Common", "Communications", "Communities", "Competency", "Competition", "Component", "Comptroller", "Computer", "Computers,", "Concept", "Conference", "Configuration", "Consolidated", "Consulting", "Contract", "Contracting", "Contracts", "Contractual", "Control", "Cooperative", "Corps", "Cost", "Council", "Counterintelligence", "Course", "Daily", "Data", "Date", "Decision", "Defense", "Deficiency", "Demonstration", "Department", "Depleting", "Deployment", "Depot", "Deputy", "Description", "Deskbook", "Determination", "Development", "Direct", "Directed", "Directive", "Directives", "Director", "Distributed", "Document", "Earned", "Electromagnetic", "Element", "Engagement", "Engineer", "Engineering", "Enterprise", "Environment", "Environmental", "Equipment", "Estimate", "Evaluation", "Evaluation)", "Exchange", "Execution", "Executive", "Expense", "Expert", "Exploration", "Externally", "Federal", "Final", "Financial", "Findings", "Fixed","Fleet", "Fleet;", "Flight", "Flying", "Followup", "Force", "Forces,", "Foreign", "Form", "Framework", "Full", "Function", "Functionality", "Fund", "Funding", "Furnished", "Future", "Government", "Ground", "Group", "Guidance", "Guide", "Handbook", "Handling,", "Hazardous", "Headquarters", "Health", "Human", "Identification", "Improvement", "Incentive", "Incentives", "Independent", "Individual", "Industrial", "Information", "Initial", "Initiation", "Initiative", "Institute", "Instruction", "Integrated", "Integration", "Intelligence", "Intensive", "Interdepartmental", "Interface", "Interference", "Internet", "Interoperability", "Interservice", "Inventory", "Investment", "Joint", "Justification", "Key", "Knowledge", "Lead", "Leader", "Leadership", "Line", "List", "Logistics", "Maintainability", "Maintenance", "Management", "Manager", "Manual", "Manufacturing", "Marine", "Master", "Material", "Materials", "Maturity", "Measurement", "Meeting", "Memorandum", "Milestone", "Milestones", "Military", "Minor", "Mission", "Model", "Modeling", "Modernization", "National", "Naval", "Navy", "Needs", "Network", "Networks", "Number", "Objectives", "Obligation", "Observation", "Occupational", "Offer", "Office", "Officer", "Operating", "Operational", "Operations", "Order", "Ordering", "Organization", "Oversight", "Ozone", "Pacific", "Package", "Packaging,", "Parameters", "Participating", "Parts", "Performance", "Personal", "Personnel", "Planning", "Planning,", "Plans", "Plant", "Point", "Policy", "Pollution", "Practice", "Preferred", "Prevention", "Price", "Primary", "Procedure", "Procedures", "Process", "Procurement", "Product", "Production", "Professional", "Program", "Programmatic", "Programming", "Project", "Proposal", "Protection", "Protocol", "Purchase", "Quadrennial", "Qualified", "Quality", "Rapid", "Rate", "Readiness", "Reconnaissance", "Regulation", "Regulations", "Reliability", "Relocation", "Repair", "Repairables", "Report", "Reporting", "Representative", "Request", "Requirement", "Requirements", "Requiring", "Requisition", "Requisitioning", "Research", "Research,", "Reserve", "Resources", "Responsibility", "Review", "Reviews", "Safety", "Sales", "Scale", "Secretary", "Secure", "Security", "Selection", "Senior", "Service", "Services", "Sharing", "Simulation", "Single", "Small", "Software", "Source", "Staff", "Standard", "Standardization", "Statement", "Status", "Storage,", "Strategy", "Streamlining", "Structure", "Submission", "Substance", "Summary", "Supplement", "Support", "Supportability", "Surveillance", "Survey", "System", "Systems", "Subsystem", "Tactical", "Target", "Targets", "Team", "Teams", "Technical", "Technology", "Test", "Tool", "Total", "Training", "Transportation", "Trouble", "Type", "Union", "Value", "Variable", "Warfare", "Weapon", "Work", "Working", "X-Ray", "Xenon", "Year", "Yesterday", "Zenith", "Zoology"};
```
---
## Code
```
f[c_]:=RandomChoice[Select[terms,(StringTake[#,1]==c)&]]
g[acronym_]:=Map[f,Characters@acronym]
```
---
## Examples
Ten randomly generated candidates for the acronym **ABC**.
```
Table[Row[g["ABC"], " "], {10}] // TableForm
```
>
> Action Breakdown Corps
>
> Accounting Budget Commerce
>
> Air Budgeting Control
>
> Acquisition Breakdown Computer
>
> Action Budgeting Cost
>
> Aligned Breakdown Common
>
> Aligned Budgeting Course
>
> Advisory Budgeting Capability
>
> Aligned Battlespace Common
>
> Anti-Surveillance Battlespace Comptroller
>
>
>
---
**FMP**
```
Table[Row[g["FMP"], " "], {10}] // TableForm
```
>
> Findings Manager Protocol
>
> Final Manual Purchase
>
> Flying Measurement Personnel
>
> Full Manufacturing Plans
>
> Form Measurement Programming
>
> Financial Model Programmatic
>
> Future Modernization Proposal
>
> Financial Measurement Package
>
> Form, Maintenance Planning
>
> Full Modeling Programmatic
>
>
>
---
**STM**
```
Table[Row[g["STM"], " "], {10}] // TableForm
```
>
> Standardization Total Modernization
>
> Service Tactical Milestone
>
> Surveillance Transportation Management
>
> Subsystem Trouble Materials
>
> Structure Test Military
>
> Scale Test Materials
>
> Strategy Tool Modernization
>
> Small Technology Minor
>
> Supportability Transportation Manufacturing
> Status Tool Management
>
>
>
---
**CRPB**
```
Table[Row[g["CRPB"], " "], {10}] // TableForm
```
>
> Cooperative Regulation Protection Business
>
> Commander Request Policy Base
>
> Changes Repair Programming, Business
>
> Closure Reviews Project Budget
>
> Commerce Regulations Parameters Base
>
> Contracts Rapid Price Base
>
> College Relocation Practice Budgeting
>
> Course Reporting Personnel Battlespace
>
> Course Requirement Procedures Budget
>
>
>
---
**SARDE**
```
Table[Row[g["SARDE"], " "], {10}] // TableForm
```
>
> Supplement Actions Requiring Directives Estimate
>
> Scale Aligned Requirement Daily Estimate
>
> Secretary Atlantic Requisitioning Director Expense
>
> Software Action Review Direct Exploration
>
> Support Act Readiness Defense Electromagnetic
>
> Software Abbreviated Requirement Decision Exchange
>
> Submission Assessment Requisition Description Executive
>
> Streamlining Accounting Rate Depot Evaluation
>
> Surveillance Assistant Requisitioning Depot Engagement
>
> Survey Assistance Resources Deficiency Expense
>
>
>
[Answer]
## D
This mostly produces nonsense, but occasionally it will produce something sensible, or something so silly as to be humourous.
Words are pulled from [this JSON file](http://puu.sh/7f9vl.json) (~2.2MB).
Program takes the acronym from the first command line argument, and supports an optional second argument which tells the program how many phrases to generate.
```
import std.file : readText;
import std.conv : to;
import std.json, std.random, std.string, std.stdio, std.algorithm, std.array, std.range;
void main( string[] args )
{
if( args.length < 2 )
return;
try
{
ushort count = 1;
if( args.length == 3 )
count = args[2].to!ushort();
auto phrases = args[1].toUpper().getPhrases( count );
foreach( phrase; phrases )
phrase.writeln();
}
catch( Throwable th )
{
th.msg.writeln;
return;
}
}
string[] getPhrases( string acronym, ushort count = 1 )
in
{
assert( count > 0 );
}
body
{
auto words = getWords();
string[] phrases;
foreach( _; 0 .. count )
{
string[] phrase;
foreach( chr; acronym )
{
auto matchingWords = words.filter!( x => x[0] == chr ).array();
auto word = matchingWords[uniform( 0, matchingWords.length )];
phrase ~= word;
}
phrases ~= phrase.join( " " );
}
return phrases;
}
string[] getWords()
{
auto text = "words.json".readText();
auto json = text.parseJSON();
string[] words;
if( json.type != JSON_TYPE.ARRAY )
throw new Exception( "Not an array." );
foreach( item; json.array )
{
if( item.type != JSON_TYPE.STRING )
throw new Exception( "Not a string." );
words ~= item.str.ucfirst();
}
return words;
}
auto ucfirst( inout( char )[] str )
{
if( str.length == 1 )
return str.toUpper();
auto first = [ str[0] ];
auto tail = str[1 .. $];
return first.toUpper() ~ tail.toLower();
}
```
**Examples**:
```
D:\Code\D\Acronym>dmd acronym.d
D:\Code\D\Acronym>acronym utf 5
Unchallenged Ticklebrush Frication
Unparalysed's Toilsomeness Fructose's
Umpiring Tableland Flimsily
Unctuousness Theseus Flawless
Umbrella's Tarts Formulated
```
[Answer]
# BASH
```
for char in $(sed -E s/'(.)'/'\1 '/g <<<"$1");
do
words=$(grep "^$char" /usr/share/dict/words)
array=($words)
arrayCount=${#array[*]}
word=${array[$((RANDOM%arrayCount))]}
echo -ne "$word "
done
echo -ne "\n"
```
So: `$ bash acronym-to-phrase.sh dftba` resulted in
```
deodorization fishgig telolecithal bashlyk anapsid
demicivilized foretell tonogram besmouch anthropoteleological
doer fightingly tubulostriato bruang amortize
```
And: `$ bash acronym-to-phrase.sh diy` resulted in
```
decanically inarguable youthen
delomorphous isatin yen
distilling inhumorously yungan
```
Finally: `$ bash acronym-to-phrase.sh rsvp`
```
retzian sensitizer vestiarium pathognomonical
reaccustom schreiner vincibility poetizer
refractorily subspherical villagey planetule
```
...
My initial reaction? *whelpless transportal fireling*
[Answer]
# Python
So, this probably won't win any popularity contests, but I figured Python needed representation. This works in Python 3.3+. I borrowed @tony-h's json file of words ([find it here](http://puu.sh/7f9vl.json)). Basically, this code just takes the json list, and organizes all the words into a dictionary indexed on the letters of the alphabet. Then, whatever acronym is passed into the python application is used as an index into the dictionary. For each letter in the acronym, a random word is selected from all the words indexed under that letter. You can also provide a number of outputs desired, or if nothing is specified, 2 options will be generated.
The code (I saved it as phraseit.py):
```
import argparse
import json
import string
from random import randrange
parser = argparse.ArgumentParser(description='Turn an acronym into a random phrase')
parser.add_argument('acronym', nargs=1)
parser.add_argument('iters',nargs='?',default=2,type=int)
args = parser.parse_args()
acronym=args.acronym[0]
print('input: ' + acronym)
allwords=json.load(open('words.json',mode='r',buffering=1))
wordlist={c:[] for c in string.ascii_lowercase}
for word in allwords:
wordlist[word[0].lower()].append(word)
for i in range(0,args.iters):
print('output:', end=" ")
for char in acronym:
print(wordlist[char.lower()][randrange(0,len(wordlist[char.lower()]))], end=" ")
print()
```
Some sample outputs:
```
$ python phraseit.py abc
input: abc
output: athabaska bookish contraster
output: alcoholism bayonet's caparison
```
Another:
```
$ python phraseit.py gosplet 5
input: gosplet
output: greenware overemphasiser seasons potential leprosy escape tularaemia
output: generatrix objectless scaloppine postulant linearisations enforcedly textbook's
output: gutturalism oleg superstruct precedential lunation exclusion toxicologist
output: guppies overseen substances perennialises lungfish excisable tweed
output: grievously outage Sherman pythoness liveable epitaphise tremulant
```
Finally:
```
$ python phraseit.py nsa 3
input: nsa
output: newsagent spookiness aperiodically
output: notecase shotbush apterygial
output: nonobjectivity sounded aligns
```
] |
[Question]
[
The story continues from [AoC2017 Day 22](https://adventofcode.com/2017/day/22), Part 2.
---
The damn virus that was infecting a grid computing cluster now has jumped to a *hexagonal* computing cluster! In this cluster, the computers are connected in the honeycomb-like shape, and each computer has three neighbors.
```
.. .. ..
. .. .. .
.. .. ..
. .. .. .
.. .x ..
. .. .. .
.. .. ..
. .. .. .
.. .. ..
```
Initially, the cluster is completely clean, and the virus is at `x`, facing east. At each tick, the virus moves in the following manner:
* If the current computer is clean, infect it, turn left (60 degrees), and move forward once (move to the neighboring computer in that direction).
* Otherwise (the current computer is infected), clean it, turn right, and move forward once.
Some initial iterations look like this (generated using [this program](https://tio.run/##jVNdj5swEHz3rxgpqoDG9DC5plcqHvrWh/6ASohKCEwOCTmRw6lUVX57umvz1aqV7sXrmd2dtc1w@Tk8n83hft/hix6r09lUPb5W5jScTXDFZzOIHepeVyZDZ1pdD6hMg@HFGvS6HT5NrG4yX7ambXd6HoRodItLeLJdI1G/WOvWOsoE2rOFpX5YmqfD@FHiPfMuUW8SR4mjS6BrnQbynDp5EmsxqjNcbGeGMPgWcFVoZR2xBA@G7q8awRhIaNPkQRCxlu5dHfYI672KHh7SCG@QslqyqL39r9q7v9WueunCHzlP0m7eiBE5ikRCSaQSBwm@Ol1yXj9IPEl8dOuyV9ygfNxCUlCHTSQtRTKKdBQ1q6cpbjH1p4mPW5zygdIpviK/YJqbPk7xNfkZ0znTYymE/6jT10Qi3DvnuGp@rqbjXMjniQRbyzmLqF/EqShDqChIHxyKJxg7nEw4mXA8F8RqZWZi6lDRzY1ij/OkZWwxltnoHDqyIRb@JpjrVtf22oRjxLb9h/sFdt4MXMVZmr5s2YFj0ZVUZfQPf/tiPoxcR5ZFuJGc7VkW1FEKb9Xv/EiuyNXchP999vmkXCSl8K@@UoooP9QT4n7/DQ); `.` is clean, `*` is infected, `x` is the virus at a clean computer, and `X` is the virus at an infected one):
```
.. .. ..
. .. .. .
.. .. ..
. .. .. .
.. .x ..
. .. .. .
.. .. ..
. .. .. .
.. .. ..
.. .. ..
. .. .. .
.. .. ..
. .. x. .
.. .* ..
. .. .. .
.. .. ..
. .. .. .
.. .. ..
.. .. ..
. .. .. .
.. .x ..
. .. *. .
.. .* ..
. .. .. .
.. .. ..
. .. .. .
.. .. ..
.. .. ..
. .. .. .
.. x* ..
. .. *. .
.. .* ..
. .. .. .
.. .. ..
. .. .. .
.. .. ..
.. .. ..
. .. .. .
.. ** ..
. .x *. .
.. .* ..
. .. .. .
.. .. ..
. .. .. .
.. .. ..
.. .. ..
. .. .. .
.. ** ..
. .* *. .
.. x* ..
. .. .. .
.. .. ..
. .. .. .
.. .. ..
.. .. ..
. .. .. .
.. ** ..
. .* *. .
.. *X ..
. .. .. .
.. .. ..
. .. .. .
.. .. ..
.. .. ..
. .. .. .
.. ** ..
. .* *. .
.. *. ..
. .. x. .
.. .. ..
. .. .. .
.. .. ..
.. .. ..
. .. .. .
.. ** ..
. .* *. .
.. *. ..
. .. *x .
.. .. ..
. .. .. .
.. .. ..
.. .. ..
. .. .. .
.. ** ..
. .* *. .
.. *. x.
. .. ** .
.. .. ..
. .. .. .
.. .. ..
.. .. ..
. .. .. .
.. ** ..
. .* *x .
.. *. *.
. .. ** .
.. .. ..
. .. .. .
.. .. ..
.. .. ..
. .. .. .
.. ** ..
. .* X* .
.. *. *.
. .. ** .
.. .. ..
. .. .. .
.. .. ..
.. .. ..
. .. .. .
.. *X ..
. .* .* .
.. *. *.
. .. ** .
.. .. ..
. .. .. .
.. .. ..
.. .. ..
. .. x. .
.. *. ..
. .* .* .
.. *. *.
. .. ** .
.. .. ..
. .. .. .
.. .. ..
.. .x ..
. .. *. .
.. *. ..
. .* .* .
.. *. *.
. .. ** .
.. .. ..
. .. .. .
.. .. ..
```
A better visualization can be seen [here (pdf)](https://oeis.org/A269757/a269757.pdf).
The number of infected computers at each iteration is [A269757](https://oeis.org/A269757):
```
0, 1, 2, 3, 4, 5, 6, 5, 6, 7,
8, 9, 8, 7, 8, 9, 10, 11, 10, 9,
10, 11, 12, 13, 12, 13, 14, 15, 16, 17,
18, 17, 16, 17, 18, 19, 20, 19, 18, 19,
20, 21, 22, 21, 20, 19, 18, 19, 20, 21,
22, 21, 20, 21, 22, 23, 24, 23, 22, 21,
20, 21, 22, 23, 24, 23, 22, 23, 24, 25, 26, ...
```
Your task is to output the sequence. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules and [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") [I/O methods](https://codegolf.stackexchange.com/tags/sequence/info) apply. (0-based and 1-based indexing allowed.) The shortest code in bytes wins.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 67 bytes
```
n=>(g=d=>n--?g(d+(g[t=d*2/3&3,[x+=--t%2,y+=--t%2]]^=2)-1):d)(x=y=0)
```
[Try it online!](https://tio.run/##LcbRDoIgFADQX/GlvDeBFN/aLq3vYNaYKKMZOGRNv55eOk/nbb5mG5NfMw/RTmWmEkiBI0sqcH53YBtwOpO9yGt/7pneG@I8nyQ7/hmGJ0nkHd4swk4HtVjGGLa4TGKJDrQQ4pGSOaBrWxzEx6wAL1Z5rEhVM3jEpq6x/AA "JavaScript (Node.js) – Try It Online")
Remove all spaces from OP's example, we got:
```
......
......
......
......
...x..
......
......
......
......
......
......
......
...x..
...*..
......
......
......
......
......
......
...x..
...*..
...*..
......
......
......
......
......
......
..x*..
...*..
...*..
......
......
......
......
......
......
..**..
..x*..
...*..
......
......
......
......
......
......
..**..
..**..
..x*..
......
......
......
......
......
......
..**..
..**..
..*X..
......
......
......
......
......
......
..**..
..**..
..*...
...x..
......
......
......
......
......
..**..
..**..
..*...
...*x.
......
......
......
......
......
..**..
..**..
..*.x.
...**.
......
......
......
......
......
..**..
..**x.
..*.*.
...**.
......
......
......
......
......
..**..
..*X*.
..*.*.
...**.
......
......
......
......
......
..*X..
..*.*.
..*.*.
...**.
......
......
......
......
...x..
..*...
..*.*.
..*.*.
...**.
......
......
......
...x..
...*..
..*...
..*.*.
..*.*.
...**.
......
......
......
```
And you will find out the pattern: "Up, Up, Left, Down, Down, Right". That's how \$ \lfloor \frac{2}{3}\cdot d \rfloor \$ comes.
[Answer]
# [Python 3](https://docs.python.org/3/), 79, 74 (@xnor), 61 bytes (@tsh)
```
x={0}
p=c=0
while[print(c)]:c=len(x);p+=1j**(c*2//3&3);x^={p}
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8K22qCWq8A22daAqzwjMyc1uqAoM69EI1kz1irZNic1T6NC07pA29YwS0tLI1nLSF/fWM1Y07oizra6oPb/fwA "Python 3 – Try It Online")
#### Older versions
```
x={2}
p=c=0
while[print(c)]:x^={p};c+=x>{p}or-1;p+=1j**(c*2//3)*(1j-c%3%2)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8K22qiWq8A22daAqzwjMyc1uqAoM69EI1kz1qoizra6oNY6Wdu2wg7IyC/SNbQu0LY1zNLS0kjWMtLXN9bU0jDM0k1WNVY10vz/HwA "Python 3 – Try It Online")
```
x={*()}
p=c=0
while[print(c)]:x^={p};c+=(x>={p})or-1;p+=1j**(c*2//3)*(1j-c%3%2)
```
[Try it online!](https://tio.run/##FcbBCkBAEADQu//YmplNrL3R@BFxmRSb7CRlJd@@8k5P73OJu8858UOAb6EsXBfXsm7zoMe6nyA4tmniR99OLEPq/2I8StepZReIQKipKo8ELpRivGkw5w8 "Python 3 – Try It Online")
set `x` holds points infected,
`p` is current position and `c` is current infection count.
Note that current heading needn't be tracked because it can be inferred from `c%6`.
Coordinates are complex numbers. It would be desirable to base them on actual geometry but that has numerical problems. Which is why we use integer coordinates, i.e. an orthogonal grid with only one diagonal direction connected. Instead, we deform the grid by "squeezing out" the unreachable hexagon centres resulting in a square grid (with some connections missing), see picture: hat tip to @tsh for that.
[](https://i.stack.imgur.com/fmt05.png)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~34~~ 28 bytes
```
FN«⊞υLKAP⎇℅KKψ*M✳÷×⁴LKA³»⎚Iυ
```
[Try it online!](https://tio.run/##XY@xjsIwDIZn@hQWk4PCcDokhk6oXZDgYOAFcq1LLdIUOQkSQvfsIb1bDhYP/n59/t30RprR2JS6UQC37hrDVxy@SVApeBSzY/Q9Rg07cufQ45HosrE2Q1UWM@4AD9KyM/aXTGvYm@vGez67bGuEBnKBWg2dKoGsp3@8pleerwm7gDULNYHHyRBqvnFLeOKBPK6mnIZPlceJxBm5vxfQcNcwX8yngj9FZcnkV8riz1wZHzBmlNL6Iy1v9gk "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` members of the sequence. Edit: Saved 6 bytes using @loopywait's observation that the direction can be inferred from the infection count. Explanation:
```
FN«
```
Input `n` and loop that many times.
```
⊞υLKA
```
Save the number of infected computers at this step.
```
P⎇℅KKψ*
```
Flip the current computer between uninfected and infected.
```
M✳÷×⁴LKA³
```
Move in a hexagonal pattern on an octagonal grid, based on the number of infected computers. Note that the exact orientation of the grid is not significant, so north west and south east are actually represented by north and south.
```
»⎚Iυ
```
Output the gathered list of infected computer counts.
Here's a version that you can run locally to animate the progress of infection (the virus itself is not shown):
```
RFφφ«P⎇℅KKψ*M✳÷⊕×⁴LKA³
```
Outputs the first 1,000 steps (the first `φ` is the animation speed, the second the number of steps). Replace the `F` with `W` if you want the program to run indefinitely. The extra `⊕` skews north and south back to north west and south east.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~82 ...~~ 56 bytes
```
a,*r=c=0;loop{p c+=(r!=r-=[a+=1i**(c*2/3)])?-1:(r<<a;1)}
```
[Try it online!](https://tio.run/##KypNqvz/P1FHq8g22dbAOic/v6C6QCFZ21ajSNG2SNc2OlHb1jBTS0sjWctI31gzVtNe19BKo8jGJtHaULP2/38A "Ruby – Try It Online")
Saved a lot of bytes by stealing tsh's formula.
[Answer]
# TypeScript Types, 317 bytes
```
//@ts-ignore
type I<T,P=0,N=[1,0][P]>=T extends[N,...infer T]?T:[...T,P];type M<N,a=[[],[]],b=0,c=0,d=[],e=0,f=[],g=[1,0][c],h=a[0],i=a[1],j=[[I<h,c>,I<i,g>],[h,I<i,c>],[I<h,g>,i]][b]>=N extends d["length"]?f["length"]:j extends e?M<N,j,[1,2,0][b],g,[...d,0],Exclude<e,j>,I<f,1>>:M<N,j,[2,0,1][b],g,[...d,0],e|j,I<f>>
```
[Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACASQB4AVAGgAUBeABkoDlaBtARkvoF1XruAfLXKF0AD3DpEAE0ismlAHTLYiAGbpUhctwD85AFytliqvwDcuAoQCypBQEM2rbpReuARg0oBjb9LZXdG81QMp4Nk4eVh9XAAtaB1YeSlhEjlcAK2cyON8BSjJYcIFXVjyi-LLcktTuXg9BWiZRCSlZQmlWACIAGyl4cDjuvTUe-sRB4e4DTNbJGUhRXTsFTLdOACYuBtd4NxNpHcoAUTEfXoBXaXRSdEpMgrI1SnYBAQNVh7dtxnZd8IHZRHFLoAA+62e70w2HwRAASpdEDYHIgcBQBIRaIQAN6YQiEVgAaUIqkIAGt0DhkGptDNbBRiYJMABfGFWIjkehYwiI5Go9GsQiMAmcAnbAkAZkoBIALDLCABWBUANgVAHYFQAOBUATmZIAJhAAerpYdZyOweXyUWjSBwRewxewJexpYR2PKPcqPWqPZqPTqPfqBJhDQTTebOZtrUjbYLNiLNmLNhLNu7Nl7Nj7Nn7NgHNkHNiGw8AjZGOdpJbH+XbWJKRZKxZKJZL3ZKvZKfZK-ZKA5Kg5KS+GTWbK+RZTX4-bZSLZWLZRLZe7ZV7ZT7ZX7ZQHZUHZcOyxGx3DtIqpwL7YqRYqxYqJYr3YqvYqfYq-YqA4qg4qD+XjxaVXPOsVRFFUxRVCUVXdFUvRVH0VT9FUAxVIMVV-I9MCAA)
## Ungolfed / Explanation
```
// Increment/decrement an integer stored as e.g. [0, 0] for 2, [1, 1, 1] for -3, and [] for 0
// Invoked as Inc<T> to increment, or Inc<T, 1> to decrement
type Inc<T, Pos = 0, Neg = [1, 0][Pos]> = T extends [Neg, ...infer T] ? T : [...T, Pos]
type Main<
// The goal number of steps
N,
// Last position; stored using axial coordinates as two integers
LastPos = [[], []],
// The current axis; 0 | 1 | 2
DirAxis = 0,
// The current direction on the axis; 0 | 1
DirSign = 0,
// The number of steps taken so far
Steps = [],
// A union of all infected positions
Infected = 0,
// A tuple counting how many positions are infected
InfectedCount = [],
// The sign opposite DirSign
OtherSign = [1, 0][DirSign],
// Calculate the new position based on LastPos, DirAxis, and DirSign
LastPos0 = LastPos[0],
LastPos1 = LastPos[1],
NewPos = [
[Inc<LastPos0, DirSign>, Inc<LastPos1, OtherSign>],
[LastPos0, Inc<LastPos1, DirSign>],
[Inc<LastPos0, OtherSign>, LastPos1]
][DirAxis]
> =
N extends Steps["length"]
// If N == Steps, return InfectedCount
? InfectedCount["length"]
// Otherwise,
: NewPos extends Infected
// If NewPos is in Infected,
? Main<
N,
NewPos,
// Cycle DirAxis to the right
[1, 2, 0][DirAxis],
// Set DirSign to OtherSign
OtherSign,
// Add one to Steps
[...Steps, 0],
// Remove NewPos from Infected
Exclude<Infected, NewPos>,
// Decrement InfectedCount
Inc<InfectedCount, 1>
>
// Otherwise,
: Main<
N,
NewPos,
// Cycle DirAxis to the left
[2, 0, 1][DirAxis],
// Set DirSign to OtherSign
OtherSign,
[...Steps, 0],
// Add NewPos to Infected
Infected | NewPos,
// Increment InfectedCount
Inc<InfectedCount>
>
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 78 bytes
```
n->for(i=!p=#a=Map(),n,iferr(mapdelete(a,p),e,mapput(a,p,1));p+=I^(#a*2\3));#a
```
[Try it online!](https://tio.run/##FYxBCgIxDAC/Uukl0SzoepTs3YM/WBYCplLQGEJ9f@0e5jBzGJeo08t7SdxtWso3oPLBOQs/xAHJqBaNgI/4U9/aFIQcSWkE/7Xd6IJ48xPfN8hynNfr0Cx9f1nidKY0DzyqNShgiNj/ "Pari/GP – Try It Online")
A port of [@tsh's JavaScript answer](https://codegolf.stackexchange.com/a/239668/9288).
[Answer]
# [Python](http://golly.sourceforge.net/Help/python.html) script in [Golly](http://golly.sourceforge.net/), 179 bytes
```
from golly import*
new("")
setrule("TriTurmite_120010")
setcell(0,0,2)
run(int(getstring("")))
a=[0,1,0,0,0,1,1,1]
show(str(sum(a[c%8]+a[c//8]for c in getcells(getrect())[2::3])))
```
Triangular Langton's ant is a built-in rule in Golly. But it simulates the triangular grid in a nontrivial way: two triangular cells are represented by one square cell. So I cannot simply use the `getpop` built-in.
Screenshot for input `1000`. Output is `106`:
[](https://i.stack.imgur.com/87WU9.png)
[Answer]
# [Rust](https://www.rust-lang.org/), 144 bytes
```
let(mut x,mut p,mut c)=(vec![],[0,0],0);loop{print!("{}
",c);x.retain(|q|q!=&p);if c==x.len(){x.push(p)}c=x.len();p[c*2/3&1]+=1-2*(c/3&1)as i64}
```
[Try it online!](https://tio.run/##NYxLCoMwFAD3PUV0IXk2tdaWbkJOIi7kEWnAz1NjCcScPa2FbgZmFrNsq43dyIbWjByYj722fNgsc@Ig/Yig@FtjUjeiLkXZiBJkP03kaTGjTXjqwykVCNIVi7bHaZ/3OVEZgTQdQ6Vc0evv37uCtvXFCQL@m6Qa8@p6z27NWd0uVc7xEGhXZp6PEEP8AA "Rust – Try It Online")
Port of @loopy walt's algorithm.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 58 bytes
```
(Clear@a;c=p=0;a@_=-1;Do[p+=I^⌊2/3(c+=a@p*=-1)⌋,#];c)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@1/DOSc1scgh0TrZtsDWwDrRId5W19DaJT@6QNvWM@5RT5eRvrFGsrZtokOBFlBG81FPt45yrHWyptp/oKKAosy8kui06LzYWB2F6jwdBQMdBSOD2tj/AA "Wolfram Language (Mathematica) – Try It Online")
A port of [@tsh's JavaScript answer](https://codegolf.stackexchange.com/a/239668/9288).
] |
[Question]
[
### Task:
Consider the problem: "given a chessboard with one square missing, cut it into 21 L-triominoes". There is a well-known constructive proof that this can be done for any square chessboard size that is a power of two. It works by splitting the chessboard into a smaller chessboard with the hole in it and one big triomino and then observing that that triomino can be cut into four triominoes recursively.
In this task, you are required to cut an 8x8 chessboard into L-shaped triominoes and then to color them with four colors such that no two adjacent triominoes have the same color.
### Specification:
Your input is the position of the hole, given as a pair of integers. You may choose which one is the column index and which one is the row index. You may choose if each starts at 0 or at 1 and away from which corner they increase. You may require A..H as the first coordinate instead of 0..7 or 1..8. You may also accept both coordinates packed into a single integer 0..63 or 1..64 in lexicographical order (row-major or column-major, left to right or right to left, up to down or down to up). You may write a full program, or a function.
You may output the tiling as ASCII, as colored ASCII or as graphical primitives. If you choose ASCII output, you may choose any four printable ASCII characters to represent the four colors. If you choose colored ASCII, you may choose any four printable ASCII characters or just one character other than space. The hole must be represented by the space character. If one of your characters is the space character, no triomino adjacent to the hole or at the chessboard edge may be of this color.
If you choose colored ASCII or graphical output, you may choose any four colors out of #000, #00F, #0F0, #0FF, #F00, #F0F, #FF0, #FFF or their closest equivalents available in your environment. If you choose graphical output, your graphical primitives must be filled squares at least 32x32 pixels in size and separated by no more than two pixels of other color. If the above exceeds the screen resolution of your environment, the minimum size requirement is relaxed to the largest square size that still fits on the screen.
You may choose any valid tiling of the given chessboard. You may choose any four-coloring of the tiling you choose. Your choice of four colors must be the same across all outputs, but you aren't required to use every color in every output.
## Examples:
Possible output for input = [0, 0] (top left corner)
```
#??##??
##.?#..?
?..#??.#
??##.?##
##?..#??
#.??##.?
?..#?..#
??##??##
```
Another possible output of the same program (input = [0, 7]):
```
??#??#?
?##?##??
..xx..xx
.?x#.?x#
??##??##
..xx..xx
.?x#.?x#
??##??##
```
A different program may also produce, for the input of "D1" (note the nonstandard but allowed chessboard orientation),
```
AABBCCAA
ACBACBAC
CCAABBCC
ABBAADD
AABDABDC
BBDDBBCC
BABBACAA
AABAACCA
```
[Answer]
# JavaScript (ES6), ~~184 ... 171~~ 163 bytes
Takes input as `(x)(y)`, with \$0\leq x\leq7\$ and \$0\leq y\leq7\$. Outputs as a string with 3 colors (marked as \$0\$, \$1\$ and \$2\$).
```
h=>v=>(a=[...'3232132031021010'],a[5+(v&4|h>3)]^=3,a[v/2<<2|h/2]=v%2*2+h%2,g=x=>y&8?'':(x<8?x-h|y-v?a[y/2<<2|x/2]^y%2*2+x%2?(x^y)&2:1:' ':`
`)+g(-~x%9||!++y))(y=0)
```
[Try it online!](https://tio.run/##LcvhaoMwGIXh/15FBtPkmzHGL3Z0YvRCpFKxVjekliohAdmtO7fu38vhPF@Naeb28Xlfott06bar3gZdGF2wRldCCKpQYaJQqkRiIhNJT7ypDiEzQboOhYJTrdW@mBjzHNchxpM2Pr5hOPjIe2114YJjSWnGbH4sbTSsLjJlU7knsDuo3R@wPpbM1g4CzJKMEpqdvTOEPYu@rf@xri9h6ACY0xK2pZsXogmznDgguiDtdJunsRPj1LMrs/sNxKO7j03bsVjEPSf0NSAUwPN@LZOcSHhmykn6nwdO3mH7AQ "JavaScript (Node.js) – Try It Online")
## Method
We work on a matrix of \$4\times4\$ triominoes:
$$\begin{pmatrix}
t\_0&t\_1&t\_2&t\_3\\
t\_4&t\_5&t\_6&t\_7\\
t\_8&t\_9&t\_{10}&t\_{11}\\
t\_{12}&t\_{13}&t\_{14}&t\_{15}
\end{pmatrix}$$
Each triomino is one of:
[](https://i.stack.imgur.com/vezjK.png)
The initial configuration of the matrix is as follows:
$$\begin{pmatrix}
3&2&3&2\\
1&3&2&0\\
3&1&0&2\\
1&0&1&0
\end{pmatrix}$$
We alternate the first 2 colors just like we would on any chessboard, which gives:
[](https://i.stack.imgur.com/XaCoh.png)
The next steps are:
1. According to the quadrant in which the hole is located, we rotate one of the 4 center triominoes (\$t\_5\$, \$t\_6\$, \$t\_9\$ or \$t\_{10}\$) by 180°.
2. We rotate the triomino on which the hole is located (it may be the same triomino as in step #1), so that it does not cover the hole.
3. We fill the holes with the 3rd color (except the 'real' hole).
For instance, assuming that the hole is located at \$(3,0)\$, this gives:
[](https://i.stack.imgur.com/mg8rQ.png)
And it that case, the final matrix is:
$$\begin{pmatrix}
3&\color{red}1&3&2\\
1&\color{red}0&2&0\\
3&1&0&2\\
1&0&1&0
\end{pmatrix}$$
## Commented
```
h => v => ( // (h, v) = hole coordinates
a = [...'3232132031021010'], // a[] = flat representation of the 4x4 matrix
a[5 + (v & 4 | h > 3)] ^= 3, // first rotation, achieved by XOR'ing with 3
a[v / 2 << 2 | h / 2] = // second rotation according to the
v % 2 * 2 + h % 2, // position of the hole within the triomino's square
g = x => // g is a recursive function that converts the 4x4
// matrix into a 8x8 ASCII art
y & 8 ? // if y = 8:
'' // stop recursion and return an empty string
: // else:
( x < 8 ? // if this is not the end of the row:
x - h | y - v ? // if this is not the position of the hole:
a[y / 2 << 2 | x / 2] // if this part of the triomino located at this
^ y % 2 * 2 + x % 2 ? // position is 'solid':
(x ^ y) & 2 // use either color #0 or color #2
: // else:
1 // use color #1
: // else:
' ' // the hole is represented with a space
: // else:
`\n` // append a linefeed
) + g(-~x % 9 || !++y) // append the result of a recursive call
)(y = 0) // initial call to g with x = y = 0
```
## Graphical output
Click on the picture to set the position of the hole.
```
f=
h=>v=>(a=[...'3232132031021010'],a[5+(v&4|h>3)]^=3,a[v/2<<2|h/2]=v%2*2+h%2,g=x=>y&8?'':(x<8?x-h|y-v?a[y/2<<2|x/2]^y%2*2+x%2?(x^y)&2:1:' ':`
`)+g(-~x%9||!++y))(y=0)
;(u = (x, y) => { for(out = '', a = f(x)(y).split('\n'), y = 0; y < 8; y++) for(x = 0; x < 8; x++) out += `<div class="b b${a[y][x] == ' ' ? 'H' : a[y][x]}"></div>`; o.innerHTML = out; })(0, 0); o.onclick = e => u(e.clientX >> 4, e.clientY >> 4)
```
```
body { margin: 0; padding: 0; }
#o { width: 128px; height: 128px; }
.b { float: left; width: 14px; height: 14px; border: solid 1px; }
.b0 { background-color: #44f; border-color: #66f #22d #22d #66f; }
.b1 { background-color: #652e65; border-color: #874f87 #430c43 #430c43 #874f87; }
.b2 { background-color: #ffc90e; border-color: #ffeb2f #dda70c #dda70c #ffeb2f; }
.bH { border-color: #000; }
```
```
<div id="o"></div>
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 78 bytes
```
NθNη”{⊞⊟¦≦⁶q×fΣ\⊙t×_⊟✳-Y⁴℅=⁶υ”≔›θ³ζ≔›η³εFζ≦⁻⁷θFε≦⁻⁷ηJ⊕÷θ²⊕÷η²§#$⁺ⅈⅉJθη Fζ‖Fε‖↓
```
[Try it online!](https://tio.run/##dZDLasMwEEX3/QphSyCBukkWhWYVCASHpoTSRQvZuPa4FtiyLUtpyc@rIz@KoeliYObeI80jK1OTNWnlfaJbZ59d/QGGd2Jzt6xLrE9GacujOKY0xFnHjNEQZ00ZQ4XFmKGHKmbIDGrgRnXi2MyFiPDjbd@rT833BlIbekuyFpJc/zrl6AA6RWMIvwpyTNsReoLC8qPSrpfkQZJuZuB/Jix1cHX72vBEZwZq0BZyzO1OXVQOYZKVwIa33XJwfw@ztYnO4RsPRCNJTpXr@RvHx@9cDNTUqRv7Tsck0WKXFygqyCxfjD5Lj7vmS4uN9yuy9veX6gc "Charcoal – Try It Online") Link is to verbose version of code. Outputs using `#$%` characters. Explanation:
```
NθNη
```
Input the co-ordinates of the blank square.
```
”{⊞⊟¦≦⁶q×fΣ\⊙t×_⊟✳-Y⁴℅=⁶υ”
```
Output a compressed string. It contains newlines so to avoid breaking up the flow of this explanation you'll find the string at the end of the answer.
```
≔›θ³ζ≔›η³εFζ≦⁻⁷θFε≦⁻⁷η
```
If either co-ordinate is greater than `3` then remember that fact and subtract the co-ordinate from 7.
```
J⊕÷θ²⊕÷η²§#$⁺ⅈⅉ
```
Jump to the nearest `%` of the top-left square of `%`s and overwrite it with a `#` or `$` as appropriate. (But this will get overwritten by the blank if it was already in this square.)
```
Jθη Fζ‖Fε‖↓
```
Blank out the square at the reduced co-ordinates and then reflect the output as necessary to get the blank to the original position.
```
##$$##$$
#%%$#%%$
$%%#$$%#
$$##%$##
##$%%#$$
#%$$##%$
$%%#$%%#
$$##$$##
```
I tried starting with the square of `%`s in the centre and working my way out to the desired co-ordinates but that took 90 bytes.
] |
[Question]
[
*(Follow-up to my question about [swapping bits with their neighbours](https://codegolf.stackexchange.com/questions/81212/swap-bits-with-their-neighbours).)*
# Task
Given a positive integer **x = (2a · 3b) · (5c · 7d) · (11e · 13f) · …**, print the integer obtained by swapping the exponents in this factorization for each successive pair of primes, **y = (2b · 3a) · (5d · 7c) · (11f · 13e) · …**
[A061898](https://oeis.org/A061898) in the OEIS. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program (in bytes) wins!
# Test cases
```
1 -> 1
2 -> 3
3 -> 2
10 -> 21
37 -> 31
360 -> 756
12345 -> 11578
67895678 -> 125630871
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ÆE;0s2UFÆẸ
```
[Try it online!](http://jelly.tryitonline.net/#code=w4ZFOzBzMlVGw4bhurg&input=&args=Njc4OTU2Nzg) or [verify all test cases](http://jelly.tryitonline.net/#code=w4ZFOzBzMlVGw4bhurgKw4figqw&input=&args=WzEsIDIsIDMsIDEwLCAzNywgMzYwLCAxMjM0NSwgNjc4OTU2Nzhd).
### How it works
```
ÆE;0s2UFÆẸ Main link. Argument: n
ÆE Yield the exponents of n's prime factorization.
;0 Append a zero.
s2 Split into pairs.
U Upend; reverse each pair.
F Flatten the resulting list of pairs.
ÆẸ Convert the prime exponents to integer.
```
[Answer]
# Jelly, ~~17~~ ~~16~~ 11 bytes
5 bytes thanks to Dennis.
```
ÆfÆC’^1‘ÆNP
```
[Try it online!](http://jelly.tryitonline.net/#code=w4Zmw4ZD4oCZXjHigJjDhk5Q&input=&args=MTIzNDU)
### Explanation
```
ÆfÆC’^1‘ÆNP Main monadic chain. Argument: n
Æf Yield the prime factors of n.
ÆC For each factor, count the number of primes below it.
This effectively yields their indices.
’ Decrement [each] by 1.
^1 Xor with 1
‘ Increment [each] by 1.
ÆN Find their corresponding primes.
P Yield their product.
```
## Previous 16-byte version
```
ÆnÆRiЀÆf’^1‘ÆNP
```
[Try it online!](http://jelly.tryitonline.net/#code=w4Zuw4ZSacOQ4oKsw4Zm4oCZXjHigJjDhk5Q&input=&args=MTIzNDU)
### Explanation
```
ÆnÆRiЀÆf’^1‘ÆNP Main monadic chain. Argument: n
Æn Yield the next prime from n.
ÆR Yield all primes from 2 to it.
Æf Yield prime factors of n
iЀ Yield their index in the prime list.
’ Decrement [each] by 1.
^1 Xor with 1
‘ Increment [each] by 1.
ÆN Find their corresponding primes.
P Yield their product.
```
## Previous 17-byte version:
```
ÆnÆR©iЀÆf’^1‘ị®P
```
[Try it online!](http://jelly.tryitonline.net/#code=w4Zuw4ZSwqlpw5DigqzDhmbigJleMeKAmOG7i8KuUA&input=&args=MTIzNDU)
### Explanation
```
ÆnÆR©iЀÆf’^1‘ị®P Main monadic chain. Argument: n
Æn Yield the next prime from n.
ÆR Yield all primes from 2 to it.
© Store to register.
Æf Yield prime factors of n
iЀ Yield their index in the prime list.
’ Decrement [each] by 1.
^1 Xor with 1
‘ Increment [each] by 1.
ị® Find their corresponding primes in
the list in register.
P Yield their product.
```
[Answer]
## Mathematica, ~~70~~ 69 bytes
```
1##&@@(Prime[BitXor[PrimePi@#+1,1]-1]^#2&)@@@FactorInteger@#/._@_->1&
```
An unnamed function which takes and returns an integer. It throws an error on input `1` but still computes the correct result.
### Explanation
As usual, due to all the syntactic sugar, the reading order is a bit funny. A `&` on the right defines an unnamed function and its arguments are referred to by `#`, `#2`, `#3`, etc.
```
...FactorInteger@#...
```
We start by factoring the input. This gives a list of pairs `{prime, exponent}` e.g. input `12` gives `{{2, 2}, {3, 1}}`. Somewhat inconveniently, `1` gives `{{1, 1}}`.
```
(...&)@@@...
```
This *applies* the function on the left to the list of integers at level 1, that is the function is called for each pair, passing the prime and exponent in as separate arguments, and then returns a list of the results. (This is similar to mapping the function over the list, but receiving two separate arguments is more convenient than receiving a pair.)
```
...PrimePi@#...
```
We compute the number of primes up to and including the (prime) input using the built-in `PrimePi`. This gives us the index of the prime.
```
...BitXor[...+1,1]-1...
```
The result is incremented, XOR'ed with `1` and decremented again. This swaps `1 <-> 2, 3 <-> 4, 5 <-> 6, ...`, i.e. all 1-based indices. Note that input `1` will yield `0` for `PrimePi` which is then mapped to `-1` in this process. We'll deal with that later.
```
...Prime[...]^#2...
```
We now obtain the *n*th prime (where *n* is the result from the previous computation), which is the correctly swapped prime, and raise it to the power of the original prime in the factorisation of the input. At this point `Prime[-1]` will throw an error but will return itself unevaluated. The power in this case is `1` so that the entire process so far yields `{Prime[-1]}` for input `1` and a list of correct prime powers for all other inputs.
```
1##&@@...
```
Next, we just multiply up all prime powers. `1##&` is a standard golfing trick for the `Times` function. See [this tip](https://codegolf.stackexchange.com/a/45188/8478) (section "Sequences of arguments") for how it works.
Finally, we need to take care of input `1` for which all of the above resulted in `Prime[-1]`. We can easily fix that with a simple replacement rule. Remember that `f@x` is short for `f[x]`. We just want to match any expression of that form (since all other results will be integers, i.e. atomic expressions), and replace it with a `1`:
```
.../._@_->1
```
Here, `/.` is short for `ReplaceAll`, `_@_` is a pattern for anything of the form `f[x]` (i.e. any compound expression with a single child) and `->1` says "replace with `1`".
[Answer]
# Python 2, ~~149~~ 139 bytes
10 bytes thanks to Dennis.
```
n=input()
p=f=1;w=[2]
while w[-1]<=n:f*=p;p+=1;w+=[p]*(-~f%p<1)
r=p=1;w=w[1:]
while n>1:
p+=1
while n%p<1:n/=p;r*=w[w.index(p)^1]
print r
```
[Answer]
# Python 2, ~~112~~ ~~109~~ ~~108~~ ~~95~~ 94 bytes
```
f=lambda n,k=4,m=6,p=[3,2]:1/n or n%p[1]and f(n,k+1,m*k,m*m%k*[k]+p)or p[len(p)*2%4]*f(n/p[1])
```
Test it on [Ideone](http://ideone.com/auVd7o).
### How it works
When **f** is called, it first computes **1/n**. If the result is non-zero, **n** is **1** and **f** returns **1**.
If **n > 1**, the following happens.
* If **n** is not divisible by **p[1]** (initially **2**), `n%p[1]` yields a truthy value and
```
f(n,k+1,m*k,m*m%k*[k]+p)
```
gets called.
This branch generates prime number until the penultimate one evenly divides **n**. To do so, it uses the following corollary of [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem).

At all times, **m** is equal to the factorial of **k - 1** (initially **6 = 3!** and **4**. In each iteration, the result of `m*m%k*[k]` gets prepended to the list of primes **p**. By the corollary, `m*m%k` is **1** if **k** is prime and **0** if not, so this prepends **k** to **p** if and only if **k** is a prime number.
* If **n** is divisible by **p[1]**, `n%p[1]` yields **0** and
```
p[len(p)*2%4]*f(n/p[1])
```
gets executed.
If **p** contains an even amount of prime numbers, `len(p)*2%4` will yield **0** and the first multiplicand takes the value of **p[0]**. If **p** contains an odd amount of prime numbers, `len(p)*2%4` will yield **2** and the first multiplicand takes the value of **p[2]**.
In either case, this is the prime whose exponents has to get swapped with the one of **p[1]**, so we divide **n** by **p[1]** (decreasing the exponent by **1**) and multiply the result of `f(n/p[1])` by the corresponding prime (increasing the exponent by **1**).
Note that `f(n/p[1])` resets **k**, **m** and **p** to their default values. `f(n/p[1],k,m,p)` would improve efficiency, at the cost of six extra bytes.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 17 bytes
```
EZqGYfy&mt2\Eq+)p
```
[**Try it online!**](http://matl.tryitonline.net/#code=RVpxR1lmeSZtdDJcRXErKXA&input=MTIzNDU)
### Explanation
This doesn't use the exponents directly. Instead, it swaps each (possibly repeated) prime factor by the next or the preceding prime.
```
EZq % Implicit input. Multiply by 2
Zq % Array with sequence of primes up to that (this is more than enough)
GYf % Prime factors of input, with possible repetitions
y % Duplicate array with sequence of primes
&m % Indices of prime factors in the sequence of primes
t2\ % Duplicate, modulo 2. Gives 0 for even indices, 1 for odd
Eq % Multiply by 2, add 1. Transforms 0 / 1 into -1 / 1
+ % Add. This modifies the indices to perform the swapping
) % Apply the new indices into the sequence of primes
p % Product. Implicit display
```
[Answer]
# Julia, 64 bytes
```
~=primes
!n=prod(t->(~3n)[endof(~t[1])+1$1-1]^t[2],factor(2n))/3
```
[Try it online!](http://julia.tryitonline.net/#code=fj1wcmltZXMKIW49cHJvZCh0LT4ofjNuKVtlbmRvZih-dFsxXSkrMSQxLTFdXnRbMl0sZmFjdG9yKDJuKSkvMwoKZm9yIG4gaW4gKDEsIDIsIDMsIDEwLCAzNywgMzYwLCAxMjM0NSkKICAgIEBwcmludGYoIiU1ZCAtPiAlNWRcbiIsIG4sICFuKQplbmQ&input=) The last test case requires too much memory for TIO, but I've verified it locally.
### How it works
To avoid special-casing input **1** – the product of an empty dictionary is not defined – we multiply the input **n** by **2** and divide the final result by its pair **3**.
`factor(2n)` gives all positive exponents of prime factors of **2n** as a dictionary. When iterating over the dictionary, we'll get key-value/prime-exponent pairs. The function `prod` will take these pairs, apply the anonymous function `t->...` to them and return the product of the results.
For each pair **t = (p,e)**, `endof(~t[1])` or `endof(primes(t[1]))` return **k**, the number of primes that are less or equal to **p**, meaning that **p** is the **k**th prime.
`+1$1-1` will increment **k**, XOR **k + 1** with **1** and decrement the result. If **k** is odd, **k + 1** is even, so the XOR increments and the final result is **k + 1**. If **k** is even, **k + 1** is odd, so the XOR decrements and the final result is **k - 1**.
Finally, we compute all prime numbers less or equal to **3n** with `(~3n)` or `primes(3n)` (the highest prime factor of **2n** is less or equal to **n** if **n > 2**, and there's always a prime between **n** and **2n**), select the one at index **k + 1** or **k - 1**, and elevate it to the **e**th power with `^t[2]`.
[Answer]
# Pyth, 25 bytes
```
JfP_TSfP_ThQ*F+1m@Jx1xJdP
```
[Test suite.](http://pyth.herokuapp.com/?code=JfP_TSfP_ThQ*F%2B1m%40Jx1xJdP&test_suite=1&test_suite_input=1%0A2%0A3%0A10%0A37%0A360%0A12345&debug=0)
## Explanation
```
JfP_TSfP_ThQ*F+1m@Jx1xJdP
Q get input
h add one
fP_T find the first prime after it
S range from 1 to that prime
fP_T filter for the primes
J assign to J
P prime factorize input
m d for each factor
xJ find its index in J
x1 xor with 1
@J find the corresponding entry in J
*F+1 product of the whole list
```
[Answer]
# Julia, ~~155~~ ~~131~~ 127 bytes
```
n->(x=[sort([merge([p=>0for p=primes(n+1)],factor(n))...]);1=>0];prod([x[i-1][1]^x[i][2]*x[i][1]^x[i-1][2]for i=2:2:endof(x)]))
```
This is an anonymous function that accepts an integer and returns an integer. To call it, assign it to a variable. It requires a Julia version < 0.5 because the prime functionality has been removed from Base in 0.5.
Ungolfed:
```
function f(n::Int)
# Create an array of pairs by merging the Dict created from factoring n
# with all primes less than n+1 with a 0 exponent. Append an extra pair
# to account for 1 and situations where x would otherwise have odd length.
x = [sort([(merge([p=>0 for p in primes(n+1)], factor(n))...]); 1=>0]
# Compute a^d * c^b, where a and c are primes with b and d as their
# respective exponents.
prod([x[i-1][1]^x[i][2] * x[i][1]^x[i-1][2] for i = 2:2:endof(x)])
end
```
[Try it online!](http://julia.tryitonline.net/#code=Zj1uLT4oeD1bc29ydChbbWVyZ2UoW3A9PjBmb3IgcD1wcmltZXMobisxKV0sZmFjdG9yKG4pKS4uLl0pOzE9PjBdO3Byb2QoW3hbaS0xXVsxXV54W2ldWzJdKnhbaV1bMV1eeFtpLTFdWzJdZm9yIGk9MjoyOmVuZG9mKHgpXSkpCgpmb3IgdGVzdCBpbiBbKDEsMSksICgyLDMpLCAoMywyKSwgKDEwLDIxKSwgKDM3LDMxKSwgKDM2MCw3NTYpLCAoMTIzNDUsMTE1NzgpLCAoNjc4OTU2NzgsMTI1NjMwODcxKV0KICAgIHByaW50bG4oZih0ZXN0WzFdKSA9PSB0ZXN0WzJdKQplbmQ&input=) (Includes all test cases)
[Answer]
## Actually, 15 bytes
```
w`i;r♂Pí1^Pn`Mπ
```
[Try it online!](http://actually.tryitonline.net/#code=d2BpO3LimYJQw60xXlBuYE3PgA&input=MTIzNDU)
Explanation:
```
w`i;r♂Pí1^Pn`Mπ
w prime factorization
` `M map (for (p,e) in factorization):
i; flatten, make a copy of p
r♂P [prime[i] for i in range(p)]
í index (essentially the 0-based prime index of p)
1^ XOR with 1
P prime[n]
n repeat e times
π product
```
[Answer]
## 05AB1E, 22 bytes
```
Ó¾‚˜2ô€R˜DgL<Ø)øvy`smP
```
**Explained**
```
Ó¾‚˜ # list of primeexponents with a 0 appended: n=10 -> [1,0,1,0]
2ô # split into pairs: [[1,0],[1,0]]
€R˜ # reverse each pair and flatten: [0,1,0,1]
DgL<Ø # get list of primes corresponding to the exponents: [2,3,5,7]
)ø # zip lists: [[0,2],[1,3],[0,5],[1,7]]
vy`sm # raise each prime to its new exponent: [1,3,1,7]
P # product: 21
```
[Try it online](http://05ab1e.tryitonline.net/#code=w5PCvuKAmsucMsO04oKsUsucRGdMPMOYKcO4dnlgc21Q&input=MTA)
[Answer]
# J, 21 bytes
```
([:,_2|.\,&0)&.(_&q:)
```
Gets the prime exponents of *n* as prime powers with zeros. Then partition them into nonoverlapping sublists of size 2 while filling with an extra zero. Then reverse each sublist, and flatten them into a list. Finally, convert back from prime exponents to a number.
## Usage
```
f =: ([:,_2|.\,&0)&.(_&q:)
(,.f"0) 1 2 3 10 37 360 12345
1 1
2 3
3 2
10 21
37 31
360 756
12345 11578
f 67895678x
125630871
```
## Explanation
```
([:,_2|.\,&0)&.(_&q:) Input: n
_&q: Obtain the list of prime exponents
( )&. Apply to the list of prime exponenets
,&0 Append a zero to the end of the list
_2 \ Split the list into nonoverlapping sublists of size 2
|. Reverse each sublist
[:, Flatten the list of sublists into a list
&.( ) Apply the inverse of (Obtain the list of prime exponents)
to convert back to a number and return it
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
â↕ÿ╓d8‼Qlì"┌nq╟ì
```
[Run and debug it](https://staxlang.xyz/#p=831298d6643813516c8d22da6e71c78d&i=1%0A2%0A3%0A10%0A37%0A360%0A12345%0A67895678&m=2)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ó0ª2ôí˜ā<ØsmP
```
[Try it online](https://tio.run/##ASEA3v9vc2FiaWX//8OTMMKqMsO0w63LnMSBPMOYc21Q//8zNjA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w5MNDq0yOrzl8NrTc4402hyeUZwb8F/nf7ShjpGOsY6hgY6xuY6xmYGOoZGxiamOmbmFpSmQiAUA).
Or alternatively:
```
xÅPsÓ0ª2ôí˜mP
```
[Try it online](https://tio.run/##ASAA3/9vc2FiaWX//3jDhVBzw5Mwwqoyw7TDrcucbVD//zM2MA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/isOtAcWHJxscWmV0eMvhtafn5Ab81/kfbahjpGOsY2igY2yuY2xmoGNoZGxiqmNmbmFpCiRiAQ).
**Explanation:**
```
Ó # Get all prime exponents of the (implicit) input-integer
0ª # Append a 0
2ô # Split it int parts of size 2
í # Reverse each inner pair
˜ # Flatten the list
ā # Push a list in the range [1,length] (without popping the list)
< # Decrease each by 1 to the range [0,length)
Ø # Get the n'th prime of each value
s # Swap so the earlier list is at the top
m # Take the primes to the power of the exponents
P # And then take the product
# (after which the result is output implicitly)
x # Double the (implicit) input-integer (without popping)
ÅP # Pop and push a list of all prime numbers <= this doubled input
s # Swap so the input is at the top of the stack
Ó0ª2ôí˜ # Same as above
m # Take each prime to the power of the exponents
# (any additional trailing primes will be discarded)
P # And then take the product
# (after which the result is output implicitly)
```
] |
[Question]
[
>
> Damn, that's a lot of carrots.
>
>
>
## [The Inspiration](http://meta.codegolf.stackexchange.com/a/7330/44713)
[](https://i.stack.imgur.com/QV5vM.png)
## The Task
You must create a program, that, in as many languages as possible, replaces every instance of `^` with a *markdown formatted link* (meaning that if I was to post it in an answer, it would automatically read it as an image and place the image instead of the words) of *this* upward facing carrot.
[](https://i.stack.imgur.com/mecHl.png)
### How to Use Said Formatting:
First, anywhere in the file, put in the link like so (this is what I did for this question):
```
[1]: https://i.stack.imgur.com/mecHl.png
```
And then, wherever you want it:
```
[![][1]][1]
```
## Rules
* [Standard Loopholes apply.](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/5071#5071)
* Input will be through STDIN or equivalent.
* Output will be through STDOUT or equivalent.
* Your code must be a fully operating program in all languages that you use.
* The URL that you use for your carrot does *not* have to be the one in this answer. This was just an example. You may use *any* URL, provided that SE's Markdown shows this specific carrot with it.
* This is a [polyglot](/questions/tagged/polyglot "show questions tagged 'polyglot'") challenge, so the answer with the greatest amount of ~~carrots~~ languages wins!
+ In the case of a tie, the shortest code size of the entries with the largest number of languages wins.
**EDIT:**
* Also, do NOT use trivial derivatives of languages! This means using a substitution language (Brainfuck vs. ShadyAsFuck) and different language versions (Python 2 vs. Python 3).
>
> There's a lot trivial esolangs to fit... (including 9001 BF variants)
>
>
>
Don't be that guy.
Note: Yes, this program will be slightly trivial in languages with regex support. However, the competition is to see how many languages the competitors can use.
[Answer]
## [Minkolang 0.10](https://github.com/elendiastarman/Minkolang), [Befunge-93](http://esolangs.org/wiki/Befunge), [><>](http://esolangs.org/wiki/Fish); 3 2D languages, 321 bytes
```
v[1]: https://i.stack.imgur.com/mecHl.png
v[![][1]][1]
>\$$>~:1+!#v_:"^"-#v_1>:34*`#v_v
// ^ ,<0 < >:0g,1+v
v# ,,:*52< ^+1 ,g1:<@_^#`*85:<1
>!v#(od"^"=,34*&34*[i1+1qO]!O$I)lO58*[i1+0qO].
>i:0(?v:"^"-?v1>:34*)?vv
^ o<0 < > :0go1+v
oo:*52< ^+1og1: <^;?)*85:<1
```
Interpreters: [Minkolang](http://play.starmaninnovations.com/minkolang/?code=v%5B1%5D%3A%20http%3A%2F%2Fi%2Estack.imgur.com%2FmecHl.png%0Av%5B!%5B%5D%5B1%5D%5D%5B1%5D%20%0A%3E%5C%24%24%3E%7E%3A1%2B!%23v_%3A%22%5E%22-%23v_1%3E%3A34*%60%23v_v%0A%2F%2F%20%20%5E%20%20%20%20%20%20%20%20%20%20%20%20%20%2C%3C0%20%20%20%20%20%20%20%20%3C%20%20%20%20%3E%3A0g%2C1%2Bv%0Av%23%20%20%20%2C%2C%3A*52%3C%20%20%20%20%20%20%20%20%20%20%5E%2B1%20%20%2Cg1%3A%3C%40_%5E%23%60*85%3A%3C1%0A%3E!v%23%28od%22%5E%22%3D%2C34*%2634*%5Bi1%2B1qO%5D!O%24I%29lO58*%5Bi1%2B0qO%5D.%0A%20%20%3Ei%3A0%28%3Fv%3A%22%5E%22-%3Fv1%3E%3A34*%29%3Fvv%0A%20%20%5E%20%20%20%20%20%20%20%20%20%20%20o%3C0%20%20%20%20%20%20%20%3C%20%3E%20%3A0go1%2Bv%0A%20%20oo%3A*52%3C%20%20%20%20%20%20%20%20%5E%2B1og1%3A%20%3C%5E%3B%3F%29*85%3A%3C1&input=afsa%5Edfva), [Befunge-93](http://www.quirkster.com/iano/js/befunge.html), [><>](http://fishlanguage.com/playground).
I'll go into detail on each component if anyone wants, but what's important is that all of them read the first and second lines of the codebox and output the characters at the appropriate times. Also, I decide between Befunge and Minkolang/><> by the use of `\`, which swaps the top two values of the stack in the first and is a mirror in the other two. To separate Minkolang and ><>, I use `!v#`. `!` is an unconditional trampoline in both languages, but `#` is an omni-directional mirror in ><> and a no-op in Minkolang. From then on, each language executes code in its own component.
[Answer]
# Python, Befunge 98, Lisp, and Javascript - ~~829~~ 827 +2 (-x flag in python) = ~~831~~ 829 bytes
```
"^\
";/*";
""""(defun q (string part replacement &key (test #'char=))(with-output-to-string (out) (loop with part-length = (length part) for old-pos = 0 then (+ pos part-length) for pos = (search part string :start2 old-pos :test test) do (write-string string out :start old-pos :end (or pos (length string))) when pos do (write-string replacement out) while pos)))(princ "[1]:http://tinyurl.com/qczsjtl
")(ignore-errors (loop (princ (q (read-line) "^" "[![][1]][1]"))))""";import sys;i=sys.stdin.read();print '[1]:http://tinyurl.com/qczsjtl\n'+i.replace('^','[![][1]][1]');"""" """
1;'''
;#<v"[1]:http://tinyurl.com/qczsjtl"$$$
;X v,<
;X >:|XXXXX>v
;vXXX>a,#
;>#@~>:10g-|>,#
;^ XXXXXXXX>$"]1[]]1[][![">:# ,# _#
;X */alert("[1]:http://tinyurl.com/qczsjtl\n"+prompt().split("^").join("[![][1]][1]"));/*
;>^"'''#*/
```
Requires the `-x` command line flag when run with python. the `X`s can be replaced with any character. The end-of-line number signs (and the number sign at the beginning of the first line that starts with a semicolon) are present to avoid befunge trying to execute the invalid instruction `;` (which starts a comment in lisp). There is no trailing space on any of the lines.
Saved two bytes by replacing `55+` with `a` to print a newline.
[Answer]
# [Carrot](http://kritixilithos.github.io/Carrot/), ~~60~~ 58 bytes
```
#^A^S"[![][1]][1]"^[1]: https://i.stack.imgur.com/mecHl.png
```
I know it is only one language at the moment but I thought we can't really have a challenge about carrots that isn't answered in Carrot.
*Saved 2 bytes thanks to @KritixiLithos.*
Explanation:
```
# // Set the stack to the input
^ // Change to operations mode
A^ // Convert to array mode by splitting on ^
S"[![][1]][1]" // Convert to string mode by joining on
// the literal string supplied
^[1]: https://i.stack.imgur.com/mecHl.png // Switch back to stack mode and
// append the string literal
```
] |
[Question]
[
As you may know, in **DNA** there are four bases — adenine (`A`), cytosine (`C`), guanine (`G`) and thymine (`T`). Typically `A` bonds with `T` and `C` bonds with `G`, forming the "rungs" of the [DNA double helix structure](https://en.wikipedia.org/wiki/Nucleic_acid_double_helix).
We define the **complement** of a base to be the base it bonds to — i.e. the complement of `A` is `T`, the complement of `T` is `A`, the complement of `C` is `G` and the complement of `G` is `C`. We can also define the complement of a DNA string to be the string with each base complemented, e.g. the complement of `GATATC` is `CTATAG`.
Because of the double-stranded structure of DNA, the bases on one strand are complementary to the bases on the other strand. However DNA has a direction, and DNA transcription occurs in opposite directions on the two strands. Hence molecular biologists are often interested in the [**reverse complement**](https://en.wikipedia.org/wiki/Complementarity_(molecular_biology)) of a DNA string — quite literally the reverse of the complement of the string.
To extend our previous example, the reverse complement of `GATATC` is `CTATAG` backwards, so `GATATC`. As you may have noticed, in this example the reverse complement is equal to the original string — we call such a string a [**reverse palindrome**](https://en.wikipedia.org/wiki/Palindromic_sequence).\*
Given a string of DNA, can you find the longest substring which is a reverse palindrome?
\*I use the term "reverse palindrome", taken from [Rosalind](http://rosalind.info/glossary/reverse-palindrome/), to differentiate from the usual meaning of palindrome.
---
## Input
Input will be a single string consisting of only the characters `ACGT` in upper case. You may write either a function or a full program for this challenge.
## Output
You may choose to output via either printing or returning (the latter choice is only available in the case of a function).
Your program should output the longest reverse palindromic substring of the input string, if there is a unique solution. If multiple solutions exist, then you may either output any single one of them, or all of them (your choice). Duplicates are okay if you choose to output all of them.
The input is guaranteed to have a solution of at least length 2.
## Worked example
```
ATGGATCCG -> GGATCC
```
The reverse complement of `GGATCC` is itself (`GGATCC --complement--> CCTAGG --reverse--> GGATCC`), so `GGATCC` is a reverse palindrome. `GATC` is also a reverse palindome, but it is not the longest one.
## Test cases
```
AT -> AT
CGT -> CG
AGCA -> GC
GATTACA -> AT, TA
ATGGATCCG -> GGATCC
CCCCCGGGGG -> CCCCCGGGGG
ACATATATAGACT -> ATATAT, TATATA
ATTCGATCTATGTAAAGAGG -> TCGA, GATC
CGCACGTCTACGTACCTACGTAG -> CTACGTAG
TCAATGCATGCGGGTCTATATGCAT -> ATGCAT, GCATGC [, ATGCAT]
CGCTGAACTTTGCCCGTTGGTAGAACGGACTGATGTGAACGAGTGACCCG -> CG, GC, TA, AT [, GC, CG, CG, CG, CG]
CTCGCGTTTGCATAACCGTACGGGCGGAACAGTCGGCGGTGCCTCCCAGG -> CCGTACGG
```
## Scoring
This is code golf, so the solution in the fewest bytes wins.
[Answer]
# Pyth, ~~37 36 28~~ 24 bytes
```
ef&}TzqmaCd6T_mx4aCk6Tyz
```
Combining the tips from FryAmTheEggman and the reverse palindrome check trick from Peter, this is a super short version.
However, this only works with [Pyth 3.0.1](https://github.com/isaacg1/pyth/tree/ead8a43d6d4e6050d3217acbcfc0dce0c2f73e80) which you can download from [this](https://github.com/isaacg1/pyth/tree/ead8a43d6d4e6050d3217acbcfc0dce0c2f73e80) link and run like
```
python3 pyth.py -c "ef&}TzqmaCd6T_mx4aCk6Tyz" <<< "ATTCGATCTATGTAAAGAGG"
```
(linux bash only. On windows, press Enter instead of the <<< and then type the input)
---
This is my previous submission - 28 bytes solution
```
J"ACGT"ef&}TzqTjk_m@_JxJdTyz
```
Thanks to FryAmTheEggman for this version. This one creates all possible subsets of the input DNA string, filters the subsets on the condition that the subset is a substring of input and the reverse of transform is equal to the subset itself.
Due to all possible subset creation, this takes up even more memory than Peter's answer.
---
[Answer]
## GolfScript (35 34 bytes)
```
]{{..(;\);}%)}do{{6&}%.{4^}%-1%=}?
```
For testing purposes you may wish to use
```
]{{..(;\);}%.&)}do{{6&}%.{4^}%-1%=}?
```
which adds a `.&` to reduce the duplicated effort.
### Dissection
```
]{ # Gather string into an array and do-while...
{ # Map over each string in the array
.. # Make a couple of copies of the string
(; # Remove the first character from one of them
\); # Remove the last character from the other
}%
) # Extract the last string from the array
}do # Loop until that last string is ''
# Because of the duplication we now have an array containing every substring
# of the original string, and if we filter to the first occurrence of each
# string then they're in descending order of length
{ # Find the first element in the string satisfying the condition...
{6&}% # Map each character in the string to its bitwise & with 6
.{4^}% # Duplicate, and map each to its bitwise ^ with 4
# This serves to test for A <-> T, C <-> G
-1%= # Reverse and test for equality
}?
```
[Answer]
# CJam, ~~39~~ 38 bytes
I am sure this can be golfed further...
```
q:Q,,_m*{~Q<>}%{,~}${_"ACGT"_W%erW%=}=
```
Takes the DNA string from STDIN and outputs the longest reverse palindromic DNA to STDOUT
[Try it online here](http://cjam.aditsu.net/)
(Explanation soon)
*(Saved 1 byte thanks to Peter)*
[Answer]
## Python 3, 125 chars
```
S=input()
l=[]
while S:
s=_,*S=S
while s:l+=[s]*all(x+y in"ATA CGC"for x,y in zip(s,s[::-1]));*s,_=s
print(*max(l,key=len))
```
Look ma, no indexing! (Well, except to reverse the string, that doesn't count.)
Iterating over the substrings is done by taking off chars from the front and end using [starred assignment](https://codegolf.stackexchange.com/a/42123/20260). The outer loop removes characters for the start of `S`, and for each such suffix, `s` loops over all prefixes of it, testing them one by one.
Testing for reverse palindrome is done by the code
```
all(x+y in"ATA CGC"for x,y in zip(s,s[::-1]))
```
which checks that each symbol and its reversed-string counterpart are one of "AT", "TA", "CG", and "GC". I also found a set-based solution to be one character shorter, but loses two chars on requiring outer parens when used.
```
set(zip(s,s[::-1]))<=set(zip("ACTG","TGAC"))
```
This still feels like it can be shortened.
Finally, the longest palindrome is printed.
```
print(*max(l,key=len))
```
I hope space-separated outputs are OK. If a list also fine, the the star could be removed. I had tried tracking the running max in the loop instead, as well as cramming the inner loops into a list comprehension so I could take the max directly without constructing `l`, and both turned out slightly longer. But, it was close enough that it's hard to tell which approach is actually best.
[Answer]
## J (45)
```
{.@(\:#&.>)@,@(('ACGT'&(|.@]-:[{~3-i.)#<)\\.)
```
This is a function that takes a string:
```
{.@(\:#&.>)@,@(('ACGT'&(|.@]-:[{~3-i.)#<)\\.) 'ATGGATCCG'
┌──────┐
│GGATCC│
└──────┘
```
Explanation:
```
{.@(\:#&.>)@,@(('ACGT'&(|.@]-:[{~3-i.)#<)\\.)
( \\.) for each prefix of each suffix
( #<) include the argument if,
|.@] its reverse
-: is equal to
'ACGT'&( [{~3-i.) the complement
,@ ravel
(\:#&.>)@ sort by length of item
{.@ take the first one
```
[Answer]
## Perl - 59 bytes
```
#!perl -p
$_=$_[~!map$_[length]=$_,/((.)(?R)?(??{'$Q5'^$+.-$+}))/gi]
```
Counting the shebang as one, input is taken from `STDIN`.
**Sample usage:**
```
$ echo CTCGCGTTTGCATAACCGTACGGGCGGAACAGTCGGCGGTGCCTCCCAGG | perl dna.pl
CCGTACGG
```
[Answer]
# Python 2 - 177 bytes
```
s=raw_input()
r,l,o=range,len(s),[]
for a in[s[i:j+1]for i in r(l)for j in r(i,l)]:q=['TC GA'.index(c)-2for c in a];o+=[a if[-n for n in q][::-1]==q else'']
print max(o,key=len)
```
Simple brute force. The actual "reverse palindromic" check is the only interesting part. Here it is written more readably:
```
check = ['TC GA'.index(c)-2 for c in substring]
if [-n for n in check][::-1] == check:
# substring is reverse palindromic
```
I do that on every possible substring and put them in a list if it's true. If it's false, I put in an empty string instead. When all the checks are done I output the longest element of the list. I used an empty string because it saves bytes over putting nothing in, but it also means the program won't choke if there's no solution. It outputs an empty line and exits gracefully.
] |
[Question]
[
**Task**
The task is to tile polygons, given a vertex configuration.
**Scoring**
Your score is equal to the "complexity level" your submission reaches. Complexity levels are cumulative, meaning that to reach #3 you must also support #1 & #2.
Submissions at an equal complexity level are distinguished by byte count; lowest wins.
**Input**
Input is a string containing a vertex configuration, representing a vertex figure. That is, a dot separated list of integers, where each integer (n) represents a regular n-gon, connected by a common vertex.
The following vertex configurations must be supported:
* `3.3.3.3.3.3`
* `3.3.3.3.6`
* `3.3.3.4.4` (note that order is reflected in the vertex figure, therefore the below does differ)
* `3.3.4.3.4`
* `3.12.12`
* `3.4.6.4`
* `3.6.3.6`
* `4.4.4.4`
* `4.6.12`
* `4.8.8`
* `6.6.6`
**Output - Complexity Level #1: Vertex Figure**
At this complexity level, output is an image showing the vertex figure corresponding to the given input.
Input is prepended with an `F` to signify that the vertex figure should be output, and not the full tiling.
For example `F3.6.3.6` gives this vertex figure:

**Output - Complexity Level #2: Tiling**
At this complexity level output is an image showing a [uniform tiling](http://en.wikipedia.org/wiki/Uniform_tiling) using the vertex figure corresponding to the given input.
For example `3.6.3.6` gives this tiling:

There are no restrictions on colour or format (barring loopholes).
**Output - Complexity Level #3: Dual Tiling**
At this complexity level a 'dual tiling' can be formed from each tiling. This is achieved by drawing lines from the centre of each polygon to the centre of each bordering polygon.
Dual tiling is specified by prepending input with a `V`.
For example `V3.6.3.6` gives this dual tiling (in red):

[Answer]
# BBC BASIC
**Rev 1 Golfed code, 655 ASCII characters, tokenised filesize 614**
Some major improvements to the data table, by hashing the string `A.B..N` to a number `(1*A+2*B+..n*N)+n` before looking up, and by storing only one translation vector (the other one is generated by code.) More explanation when I have finished golfing.
```
t=PI*2DIMm(9)
c=0z=0INPUTz$
FORi=1TOLEN(z$)d%=VAL(MID$(z$,i))IFd%c+=1m(c)=d%i-=d%=12z+=c*d%
NEXTREPEATREADl,e,f
UNTILl=z+c
l=4-3*(m(3)MOD3=0)-8*(l=59)
DATA69,0,70,65,100,35,66,149,0,49,109,0,52,80,0,55,0,189,39,120,0,44,40,40,58,55,95,47,136,0,59,40,0
VDU23,23,3|
FORr=-9TO19FORs=-9TO9a=1+e*(r*2+s)-f*l*s/4b=1+f*(r*2+s)+e*l*s/4p=40q=0FORk=1TOm(c)/2FORj=1TOc
n=m(j)o=TAN(PI/3)IFe=109ANDn<>4o=1
w=-p*COS(t/n)-q*SIN(t/n)q=p*SIN(t/n)-q*COS(t/n)p=w
u=p:v=q
x=a:y=b
MOVEx,y
FORi=1TO14x+=u*2y+=v*2IFVAL(z$)DRAWx,y ELSEGCOL9LINEx-u-v/o,y-v+u/o,x-u+v/TAN(PI/n),y-v-u/TAN(PI/n)
w=v*COS(t/n)-u*SIN(t/n)u=v*SIN(t/n)+u*COS(t/n)v=w
NEXTNEXT
p=u:q=v
a=x:b=y
NEXTNEXTNEXT
```
**Rev 0 Golfed code, 770 ASCII characters, tokenised filesize 728**
All I've done here is remove comments, unnecessary whitespace and quote marks, and put all the `DATA` on one line. There's certainly room for more golfing.
```
t=PI*2DIMm(9)
c=0INPUTz$
FORi=1TOLEN(z$)d%=VAL(MID$(z$,i))IFd%c+=1:m(c)=d%:i-=d%=12
NEXTREPEATREADl$,e,f,g,h
UNTILMID$(z$,1-(VAL(z$)=0))=l$
DATA3.3.3.3.3.3,240,0,120,70,3.3.3.3.6,200,70,40,210,3.3.3.4.4,80,0,40,150,3.3.4.3.4,-40,150,150,40,3.12.12,300,0,150,260,3.4.6.4,220,0,110,188,3.6.3.6,160,0,80,140,4.4.4.4,80,0,0,80,4.6.12,0,380,330,-190,4.8.8,272,0,136,136,6.6.6,240,0,120,70
VDU23,23,3|
FORr=-9TO19 FORs=0TO9a=1+e*r+g*s
b=1+f*r+h*s
p=40q=0FORk=1TOm(c)/2FORj=1TOc
n=m(j)o=TAN(PI/3):IFe=220ANDn<>4o=1
w=-p*COS(t/n)-q*SIN(t/n)q=p*SIN(t/n)-q*COS(t/n)p=w
u=p:v=q
x=a:y=b
MOVEx,y
FORi=1TO14x+=u*2y+=v*2IFVAL(z$)DRAWx,y ELSEGCOL9LINEx-u-v/o,y-v+u/o,x-u+v/TAN(PI/n),y-v-u/TAN(PI/n)
w=v*COS(t/n)-u*SIN(t/n)u=v*SIN(t/n)+u*COS(t/n)v=w
NEXTNEXT
p=u:q=v
a=x:b=y
NEXTNEXTNEXT
```
**Explanation**
This is a continuation of my previous Level 1 answer, but I decided to post it separately because it's rather long.
**Level 2**
This is achieved by translation of my "level 1.5" templates from my previous answer. The two translation vectors for each tiling are hardcoded. I take advantage of the fact that an isosceles triangle of base 80 and height 70 is a very good approximation of an equilateral triangle, and a right triangle with hypotenuse vector `(56,56)` has a hypotenuse length very close to 80.
**Level 3**
To plot the duals, instead of plotting an edge of the polygon, we plot a spoke from the middle of that edge to the centre of the polygon. This is at right angles to the edge and has length of `1/TAN/(PI/n)` times of the vector (u,v) which in turn is half as long as the edge.
Unfortunately, because certain polygons in tilings `3.3.3.3.6` and `3.4.6.4` are not plotted explicitly, they would not be plotted if we only did this. Therefore the spoke also extends outward from the polygon. The outward extension is controlled by the variable `o`.
By default the extension is sufficient to reach the centre of a triangle, but for `3.4.6.4` it needs to be extended more in order to draw the duals of the squares that are not plotted explicitly. So enough extension to fill in the missing squares is applied when hexagons and triangles are plotted explicitly, but the normal extension is applied when squares are plotted explicitly, to avoid spurious lines in the adjacent triangles.
**Here's what they look like without the spoke extensions.** The holes in the dual pattern can be clearly seen. **The correct output can be seen in the main picture** at the bottom of the answer

**Commented Code**
Differences from my previous answer are indicated inline
```
t=PI*2 :REM constant Tau = PI*2
DIMm(9) :REM declare array for the numbers in the input
c=0 :REM number of polygons in the list
INPUTz$
FORi=1TOLEN(z$) :REM for each character in the input
d%=VAL(MID$(z$,i)) :REM use VAL to return the numeric value of the substring to the right and store to integer variable
IF d% c+=1 :m(c)=d%: i-=d%=12 :REM if the last character read was a number, d% contains it, otherwise 0. Advance c and store to m. If it is 12, increment i to skip a character.
NEXT
REM BLOCK OF NEW CODE to define vectors (e,f) and (g,h) for each possible tiling
REPEAT
READ l$,e,f,g,h :REM read an entire line of the data below
UNTIL MID$(z$,1-(VAL(z$)=0))=l$ :REM abort the loop when l$ coincides with the input. the MID$ strips off the 'V' from the input where necessary.
DATA"3.3.3.3.3.3",240,0,120,70
DATA"3.3.3.3.6",200,70,40,210
DATA"3.3.3.4.4",80,0,40,150
DATA"3.3.4.3.4",-40,150,150,40
DATA"3.12.12",300,0,150,260
DATA"3.4.6.4",220,0,110,188
DATA"3.6.3.6",160,0,80,140
DATA"4.4.4.4",80,0,0,80
DATA"4.6.12",0,380,330,-190
DATA"4.8.8",272,0,136,136
DATA"6.6.6",240,0,120,70
VDU23,23,3| :REM change linewidth to 3 (default is 1)
REM END BLOCK OF NEW CODE
FORr=-9TO19 FORs=0TO9 :REM two new loops for translations
a=1+e*r+g*s :REM modified code for
b=1+f*r+h*s :REM coordinates to start drawing at
p=40:q=0 :REM vector of first line
FORk=1TOm(c)/2 :REM draw half as many vertex figures as there are sides on the last polygon in the list
FORj=1TOc :REM for each polygon on the list
n=m(j) :REM n=number of sides
o=TAN(PI/3): IF e=220 AND n<>4 o=1 :REM new code for the spoke extension 1/o.
w=-p*COS(t/n)-q*SIN(t/n) :REM rotate the starting vector anticlockwise by the internal angle of the current polygon
q=p*SIN(t/n)-q*COS(t/n) :REM to avoid overlapping the previous one, if any.
p=w
u=p:v=q :REM make a local copy of the vector and coordinates
x=a:y=b :REM to avoid corruption of p,q,a,b during the drawing of the polygon
MOVE x,y :REM move the graphics cursor to the start without drawing
FORi=1TO14 :REM do 14 iterations regardless of the number of sides on the polygon
x+=u*2 :REM increment x and y by the vector representing the side
y+=v*2 :REM the value is double (u,v) to facilitate drawing duals later
REM if z$ begins with a numeric character, draw an edge. If not, change to red and draw a spoke.
IFVAL(z$) DRAW x,y ELSE GCOL9: LINEx-u-v/o,y-v+u/o,x-u+v/TAN(PI/n),y-v-u/TAN(PI/n)
w=v*COS(t/n)-u*SIN(t/n) :REM rotate the vector clockwise
u=v*SIN(t/n)+u*COS(t/n) :REM through the external angle of the polygon
v=w
NEXT :REM draw next edge of the current polygon
NEXT :REM draw next polygon of the current vertex
p=u:q=v :REM once the vertex is finished, we will be two sides around the perimeter of the last polygon.
a=x:b=y :REM copy the position and direction data into p,q,a,b.
NEXT :REM draw next vertex figure
NEXT :REM close the two new translation loops
NEXT
```
**Output**
The program performs only one tiling or dual for each run. However it plots the duals in red. To save space, I ran the program twice without clearing the screen in order to superimpose the dual on top of the regular tiling.

[Answer]
# Mathematica
Level 1 contains the basic tile templates that are repeatedly stamped to tile a plane.
Level 2 does the tiling.
There are still 2 tilings I haven't been able to achieve. They appear to require rotation as well as translation.
## Level 1: Vertex Figure (559 bytes)
```
nGon[n_]:=
{ColorData[46,"ColorList"][[n]],Polygon@Switch[n,
3,{{0,0},{-1/2,.866},{-1,0},{0,0}},
4,{{0,0},{0,1},{-1,1},{-1,0},{0,0}},
6,Table[{Cos[i 2Pi/n],Sin[i 2Pi/n]}+{-.5,.866},{i,0,n}],
8,Table[1.31{Cos[i Pi/4],Sin[i Pi/4]}+{-0.5`,1.207},{i,1/2,9}],
_,Table[2{Cos[i 2Pi/n],Sin[i 2Pi/n]}+{-0.5176,1.932},{i,1/2,13}]]}
innerAngle[n_]:=180-360/n
g[{}]=0;
g[a_]:=-(Plus@@innerAngle/@a)
h[{{},__,out_}]:=out
h[{list_,angles_,out_}]:=(
z=GeometricTransformation[nGon[l=list[[1]]],RotationTransform[g[angles] Degree]];
h[{Rest@list,Append[angles,l],Append[out,z]}])
```
**Testing**
```
Row[Graphics[{EdgeForm[{Blue}], #},
ImageSize -> 70] & @@ {h[{#, {}, {}}]} & /@ {{3, 3, 3, 3, 3,
3}, {3, 3, 3, 3, 6}, {3, 3, 3, 4, 4}, {3, 3, 4, 3, 4}, {3, 12,
12}, {3, 4, 6, 4}, {3, 6, 3, 6}, {4, 4, 4, 4}, {4, 6, 12}, {4, 8,
8}, {6, 6, 6}}]
```

---
## Level 2: Tiling (690 additional bytes)
The rules return tiling offsets and indents for each configuration.
`r` is the basic function that outputs the tilings.
`p` shows the template and the respective tiling. White spaces correspond to those not covered by the template.
```
rules={
{3,6,3,6}-> {2,3.47,0,0},
{4,4,4,4}-> {1,1,0,0},
{6,6,6}-> {3,2.6,1.5,0},
{3,3,3,3,3,3}-> {1.5,1.74,0,.9},
{3,3,3,3,6}-> {2,2.6,-0.4,1.8},
{4,6,12}->{4.2,4.9,0,2.5},
{3,3,4,3,4}-> {1.87,1.86,-.5,-0.5},
{4,8,8}-> {3.4,3.4,0,0},
{3,3,3,4,4}-> {2,1.87,.52,0},
{3,12,12}-> {3.82,6.73,0,0},
{3,4,6,4}-> {1.4,4.3,0(*1.375*)-1,-2.4}};
r[nGons_]:=
Module[{horizHop,vertHop,indent,downIndent},
{horizHop,vertHop,indent,downIndent}=(nGons/.rules);
Graphics[{EdgeForm[{Blue}],Table[GeometricTransformation[h[{#,{},{}}]&/@{nGons},
TranslationTransform[{
If[MemberQ[{{3,3,4,3,4},{3,3,3,3,6},{3,4,6,4}},nGons],indent *row,indent Boole[OddQ[row]]]+col horizHop,
If[MemberQ[{{3,3,4,3,4},{3,3,3,3,6},{3,4,6,4}},nGons],downIndent *col,downIndent Boole[OddQ[col]]]-row vertHop}]],
{col,0,5},{row,0,4}]},ImageSize-> 250]]
p[nGon_]:=Row[{Graphics[{EdgeForm[{Blue}],h[{nGon,{},{}}]},ImageSize->70],r@nGon}];
```
**Testing**
**Triangular tiling**
```
p[{3, 3, 3, 3, 3, 3}]
```

---
**hexagonal**
```
p[{6, 6, 6}]
```

---
**square**
```
p[{4, 4, 4, 4}]
```

---
unknown
```
p[{3, 3, 4, 3, 4}]
```

---
**truncated square**
```
p[{4, 8, 8}]
```

---
**trihexagonal**
```
p[{3, 6, 3, 6}]
```

---
**truncated hexagonal**
```
p[{3, 12, 12}]
```

---
unnamed
```
p[{3, 3, 3, 3, 6}]
```

---
**elongated triangular**
```
p[{3, 3, 3, 4, 4}]
```

---
**Tilings to figure out**

[Answer]
## R
**Step #1**
Here's my effort at building the tiles. Tiling to come next.
This does not validate the input, so invalids will draw some weird tiles.
Input is typed in after first line
```
i=as.numeric(unlist(strsplit(readline(),"[.]")))
e=c()
for(n in 1:length(i)){
o=sum(c(0,180-360/i[1:n-1]))
for(z in 1:i[n]){
e=c(e,(360/i[n])*(z-1)+o)
}
}
f=pi/180
plot(c(0,cumsum(sin(e*f))),c(0,cumsum(cos(e*f))),type="l")
```

## Step #1,#2 & #3: 1898
Finally got back to it. Most of this is taken up with setting offsets and handling special cases :). **Edit:** V flag for duals are now handled
The general process is:
* Take the input and make a list
* Create a list of angles to draw the initial tile
* Calculate centres of each polygon it the tile and the vectors from them to bisect the edges
* Determine the tile set being drawn and make a list of angle offsets. Some tiles have additional polygons added to them to assist with filling holes.
* Draw the tiles
* Draw the duals
I can probably still golf this a bit more.
```
##Get input (Enter by itself then type in the tile scheme)
i=strsplit(readline(),"[.]")[[1]]
## Run once i is set
q=0
if(substr(i[1],1,1)=="V"){q=1;i[1]=substr(i[1],2,9)}
i=as.numeric(i)
f=pi/180
e=x=y=q=p=c()
l=length(i)
d=1/(2*tan(pi/3))
g=1/(2*sin(pi/3))
for(n in 1:l){o=sum(c(0,180-360/i[1:n-1]))
r=1/(2*sin(pi/i[n]))
a=o+(180-360/i[n])/2
b=1/(2*tan(pi/i[n]))+d
for(z in 1:i[n]){x=c(x,r*sin(a*f))
y=c(y,r*cos(a*f))
q=c(q,b)
p=c(p,(360/i[n])*(z-1)+o-90)
e=c(e,(360/i[n])*(z-1)+o)}}
if(sum(i)==18&l==6){h=c(60,0);w=c(60,120)}
if(sum(i)==18&l==5){h=c(0,0,60);w=c(60,120,60)
e=c(e,0,-60,60,180,60,180)
x=c(x,g*sin(-30*f),g*sin(-30*f),g*sin(90*f))
y=c(y,1+g*cos(-30*f),1+g*cos(-30*f),1)
q=c(q,d+d,d+d,d+d)
p=c(p,-30,90,-30)}
if(sum(i)==17&l==5&sum(abs(diff(c(i,i[1]),1)))==2){h=c(0,0);w=c(90,60)}
if(sum(i)==17&l==5&sum(abs(diff(c(i,i[1]),1)))==4){h=c(0,30);w=c(270,300)}
if(sum(i)==17&l==4){h=c(0,30,-30);w=c(60,30,90)
e=c(e,150,120,210,300)
x=c(x,sin(150*f)+g*sin(90*f),sin(150*f)+sin(210*f)/2)
y=c(y,cos(150*f)+(1/(2*cos(pi/3)))*cos(90*f),cos(150*f)+cos(210*f)/2)
q=c(q,1,1)
p=c(p,210,120)}
if(sum(i)==18&l==4){h=c(0,0);w=c(120,120)}
if(sum(i)==16&l==4){h=c(0,0);w=c(90,90)}
if(sum(i)==27&l==3){h=c(0,-30,0,30);w=c(60,90,120,150,180)}
if(sum(i)==22&l==3){h=c(0,-30,30,90,60,30)
w=c(90,150,120,90,60,30)
e=c(e,0,-30,-60,30,120,210,30,90,150)
q=q-d+1/(2*tan(pi/4));q[13]=q[17]=q[21]=q[21]+3}
if(sum(i)==20&l==3){h=c(0,-45,-90);w=c(90,0,45)}
if(sum(i)==18&l==3){h=c(0,60,0,-60);w=c(0,60,120,60)}
hx=sum(sin(h*f))
hy=sum(cos(h*f))
wx=sum(sin(w*f))
wy=sum(cos(w*f))
plot(0,0,type="n")
par(pin=c(5,5),usr=c(0,20,0,20))
for(c in -20:20){for(j in -20:20){lines(c((c*hx)+(j*wx)+0,(c*hx)+(j*wx)+cumsum(sin(e*f))),c((c*hy)+(j*wy)+0,(c*hy)+(j*wy)+cumsum(cos(e*f))),type="l")
if(q){for(n in 1:length(x)){lines(c((c*hx)+(j*wx)+x[n],(c*hx)+(j*wx)+x[n]+q[n]*sin(p[n]*f)),c((c*hy)+(j*wy)+y[n],(c*hy)+(j*wy)+y[n]+q[n]*cos(p[n]*f)),col="RED")}}}}
```



[Answer]
# BBC BASIC
Download emulator at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html>
**Level 1**

**Level 1.5**
Level 1.5 is my own designation, but it is an important milestone in my method.
Translating the vertex figures does not always lead to the correct tiling. In some cases lines are missing.
My solution to this is to go around the largest polygon, drawing the vertex figure for every second vertex of that polygon. This is a general solution for all cases. Note that the largest polygon always has an even number of sides and the vertex figure often alternates clockwise/anticlockwise as you go around the polygon. This can be seen most clearly with `4.6.12`, but it is also true of `4.8.8` and `3.12.12`: when viewed from any particular 8-gon or 12-gon, alternating vertices are mirror images of each other. This is also what is happening, somewhat less obviously, with `3.3.3.4.4` and `3.3.4.3.4`: when viewed from any particular square, alternating vertices are mirror images of each other.
The algorithm I use to move 2 sides around the polygon is to always do 14 iterations of the edge-drawing loop, regardless of how many edges the polygon has. 8 is a factor of 16, therefore when drawing octagons the graphics cursor ends up 16-14=2 vertices behind where it started. 3- 4- 6- and 12- gons all have sides that are factors of 12, so the graphics cursor ends up 14-12=2 vertices ahead of where it started.
The figures can be seen below. Tomorrow I hope to work out the correct translations to complete the tiling. In all cases sufficient lines are drawn to complete level 2 with translations only. In some cases a great deal more than the minimum required is drawn, but there's no problem with overlap: the rules say nothing about drawing lines only once :-)
In general, the largest polygon is the last one on the list. There is, unfortunately one case where this is not so: `3.4.6.4` Therefore the figure drawn in this case is centred on a square rather than a hexagon. There are enough lines to complete level 2 using only translations, although there will certain squares that are not drawn explicitly. This will present some problems in level 3 (fortunately I think I know how to solve this.) Similarly with `3.3.3.3.6` there are enough lines to complete level 2 using only translations, but there will be certain triangles that are not drawn explicitly.

**Code**
The code for level 1.5 is commented out, only the code for level 1 is activated. There are four lines beginning with a `REM`. Remove these `REM`s to activate level 1.5.
```
t=PI*2 :REM constant Tau = PI*2
DIMm(9) :REM declare array for the numbers in the input
c=0 :REM number of polygons in the list
INPUTz$
FORi=1TOLEN(z$) :REM for each character in the input
d%=VAL(MID$(z$,i)) :REM use VAL to return the numeric value of the substring to the right and store to integer variable
IF d% c+=1 :m(c)=d%: i-=d%=12 :REM if the last character read was a number, d% contains it, otherwise 0. Advance c and store to m. If it is 12, increment i to skip a character.
NEXT
FORi=1TOc PRINTm(i),:NEXT :REM parsing check for debugging.
a=601:b=601 :REM coordinates to start drawing at
p=40:q=0 :REM vector of first line
REM FORk=1TOm(c)/2 :REM draw half as many vertex figures as there are sides on the last polygon in the list
FORj=1TOc :REM for each polygon on the list
n=m(j) :REM n=number of sides
w=-p*COS(t/n)-q*SIN(t/n) :REM rotate the starting vector anticlockwise by the internal angle of the current polygon
q=p*SIN(t/n)-q*COS(t/n) :REM to avoid overlapping the previous one, if any.
p=w
u=p:v=q :REM make a local copy of the vector and coordinates
x=a:y=b :REM to avoid corruption of p,q,a,b during the drawing of the polygon
MOVE x,y :REM move the graphics cursor to the start without drawing
FORi=1TO14 :REM do 14 iterations regardless of the number of sides on the polygon
x+=u*2 :REM increment x and y by the vector representing the side
y+=v*2 :REM the value is double (u,v) to facilitate drawing duals later
IFVAL(z$) DRAW x,y ELSE LINEx-u,y-v,x-u,y-v :REM if the first character of the input is a number, draw the side of the polygon. The ELSE part is unfinished and will be for drawing duals.
w=v*COS(t/n)-u*SIN(t/n) :REM rotate the vector clockwise
u=v*SIN(t/n)+u*COS(t/n) :REM through the external angle of the polygon
v=w
NEXT :REM draw next edge of the current polygon
NEXT :REM draw next polygon of the current vertex
REM p=u:q=v :REM once the vertex is finished, we will be two sides around the perimeter of the last polygon.
REM a=x:b=y :REM copy the position and direction data into p,q,a,b.
REM NEXT :REM draw next vertex figure
```
**Levels 2 and 3**
See my other answer.
] |
[Question]
[
*This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge, the robbers' thread is [here](https://codegolf.stackexchange.com/questions/241486/from-code-to-golf-robbers-thread)*
You can change the word `code` into `golf` by changing a letter at a time in four steps:
```
CODE
[COLE](https://en.wiktionary.org/wiki/cole#English)
COLD
GOLD
GOLF
```
Today, we’ll be doing the same thing with programs.
Your challenge is to:
* choose a programming language
* write two programs / functions, one that outputs `code` and one that outputs `golf`
* Such that you can repeatedly change a single character and get a program that outputs an English word until you get to the `golf` program.
* Share the `code` program and the number of times you need to change a character, but not any of the intermediate programs or the `golf` program, which robbers will try to discover.
* No two programs can output the same word.
For example, if the program `abcde` outputs `code` in a certain language, and the program `abcdf` outputs `potato`, then changing that e to an f is a valid step.
And if the program `aqcdf` outputs `golf`, then `abcde` -> `abcdf` -> `aqcdf` is a valid chain in which you change a character twice.
You should only share the `code` program and the number of programs not counting the `code` program, the rest is for the robbers to guess.
Your solution is cracked when your entire chain of programs is found. It does not have to be your intended solution, only one with the same initial program and same or less length. (If someone finds a longer chain, it’s not a crack.)
If your answer is not cracked after a week, you may mark it as safe and reveal your solution.
Casing can be whatever you want - You can output `Code`, `CODE`, `coDe`, etc. Output may contain a trailing newline.
The dictionary used is `/dict/words`, which I've put in a [gist](https://gist.github.com/chunkybanana/08d7f8c3bd773ea546d641a9f3051e22) for convenience.
## Scoring
Your score is the number of programs not counting the `code` or `golf` ones, multiplied by the length in bytes of your `code` program. The safe answer with the lowest score wins.
[Answer]
# JavaScript (ES6), 32 bytes, 4 changes, [cracked](https://codegolf.stackexchange.com/a/241565/58563) by Dom Hastings
Should be easier to crack than it was to build. :-p
There are 4 intermediate steps, for a total of 6 programs.
```
_=>(0x63044+185886).toString(36)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1k7DoMLM2MDERNvQwtTCwkxTryQ/uKQoMy9dw9hM839yfl5xfk6qXk5@ukaahqbmfwA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 28 bytes, 1 step, [cracked by M Virts](https://codegolf.stackexchange.com/a/241508/9288)
Let's start from an easy one.
```
go="co";lf="de";print(go,lf)
```
[Try it online!](https://tio.run/##K0gsytRNL/j/Pz3fVik5X8k6J81WKSVVybqgKDOvRCM9XycnTfP/fwA "Pari/GP – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 7 bytes \* 9 steps = score 63, [cracked](https://codegolf.stackexchange.com/a/241649) by Dom Hastings
```
⍘⍘$zPγβ
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R7wwgUqkKOLf53Kb//wE "Charcoal – Try It Online") I had to use the full dictionary for this, because there is only one common word that is one source character away from the program for `golf` and that is `gold`, after which you would get stuck, however the words nearer the `code` end are less uncommon.
[Answer]
# [Perl 5](https://www.perl.org/) + `-M5.10.0`, 43 bytes, 15 changes: score 645: SAFE
17 steps total, 15 excluding `code` and `golf`.
Yeah, I don't think this one's going to be a winner! Might be too easy anyway, as I'm pretty sure there's a shorter route than the one I ended up taking but I couldn't quite get it working!
```
$_=$!=35;/.(.)..(.). (.)(.)/;say$2.$1.$3.$4
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lZF0dbY1FpfT0NPUw9MKAAJINK3Lk6sVDHSUzHUUzHWUzH5//9ffkFJZn5e8X9dX1M9QwM9AwA "Perl 5 – Try It Online")
## Solution
I noticed that I could have saved a byte on my solution too using:
```
$_=$!=35;/.(.)..(.). (.)(.)/;say"$2$1$3$4"; # code
```
but only after posting and didn't think it was fair to adjust, a whole 15 off my score!
```
$_=$!=35;/.(.)..(.). (.)(.)/;say$2.$1.$3.$4; # code
$_=$!=35;/.(.)..(.). (.)(.)/;say$3.$1.$3.$4; # dode
$_=$!=35;/.(.)..(.). (.)(.)/;say$3.$1.$3.$1; # dodo
$_=$!=95;/.(.)..(.). (.)(.)/;say$3.$1.$3.$1; # nana
$_=$!=95;/.(.)..(.). (.)(.)/;say$3.$2.$3.$1; # nona
$_=$!=95;/.(.)..(.). (.)(.)/;say$3.$2.$3.$2; # nono
$_=$!=75;/.(.)..(.). (.)(.)/;say$3.$2.$3.$2; # lolo
$_=$!=75;/.(.)..(.). (.)(.)/;say$3.$4.$3.$2; # lalo
$_=$!=75;/.(.)..(.). (.)(.)/;say$3.$4.$3.$3; # lall
$_=$!=75;/.(.)..(.). (.)(.)/;say$5.$4.$3.$3; # all
$_=$!=75;/ (.)..(.). (.)(.)/;say$5.$4.$3.$3; # off
$_=$!=75;/ (.)..(.). (.)(.)/;say$5.$4.$5.$3; # of
$_=$!=75;/ (.)..(.). (.)(.)/;say$5.$4.$5.$5; # o
$_=$!=75;/ (.)..(.). (.)(.)/;say$2.$4.$5.$5; # go
$_=$!=75;/ (.)..(.). (.)(.)/;say$2.$4.$4.$5; # goo
$_=$!=75;/ (.)..(.). (.)(.)/;say$2.$4.$4.$3; # goof
$_=$!=75;/ (.)..(.). (.)(.)/;say$2.$4.$1.$3; # golf
```
[Try it online!](https://tio.run/##lc5BCsIwEIXhvaeImIUunDZJg0joETyDBNuIEDqldePljaXE0qw6gce/@@D17eB1CPxe832ttCngCCeYw6ZMK8xoP1wCF8AV8MqwA3tg0@42jUpMk2dENBjNlWo621mSkSuDWUZG8/92oRqPnmaqlbFZRkXjt41OTEoYhaBzVKIXkiH0LLaBTMCTLKpF5BAViaMasRjvQvhi/35hN4bzTYMoofwB "Perl 5 – Try It Online")
I approached this by first [printing out all the 2 digit error messages](https://tio.run/##K0gtyjH9/784sVJJJd5KQUlHRdFWJV4hLb9IwdBAT8/S8v//f/kFJZn5ecX/dX1N9YCCBgA) and [looking for words that contained `g`, `o`, `l` and `f`](https://tio.run/##K0gtyjH9/19F11YlXkdDJd5WRRHI0tTRT9dXU9PPBxE5ICINSBQnViqp6FopqMQrpeUXKRga6OlZWv7//y@/oCQzP6/4v66vqR5Q0AAA).
Once I had some target regexes [I checked if any of them would match `code`](https://tio.run/##bY5BCsIwEEX3OcVYQlFpM7rookrBC3iCUktp0yBUExIXitSjG5OmbsRNPvOYzH@K6yGz9qC54HduoAChuQJkmMClUfAkALR2mC78U@@JA1gKOfQVW/9PhDh2W@5jDMULDJanwBkKPZMAylZ2vHKUjLDdMJbn7n4vNdDJB5Zfr1UQSSeH5MfJz9j6VkAZogvBZxUM9@bJNI@IpjunF4EvC81ktPYt1e0sr8amx4w5vPkA) and then refined to pick a regex that would have spaces in (at least some of) the right places.
From there I worked manually (because I found it interesting!) to pick a route, although automation would have probably resulted in a better score.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 26 bytes, 3 changes, [cracked by M Virts](https://codegolf.stackexchange.com/a/241508/9288)
Another easy one, using a similar trick.
```
g=c;f=e;l=d;print(g,o,l,f)
```
[Try it online!](https://tio.run/##K0gsytRNL/j/P9022TrNNtU6xzbFuqAoM69EI10nXydHJ03z/38A "Pari/GP – Try It Online")
M Virts found a simple answer with only two changes that I didn't expect. Here is my intended solution:
>
> `g=c;f=e;l=d;print(g,o,l,f) /* code */`
>
>
>
>
> `g=c;f=e l=d;print(g,o,l,f) /* cold */`
>
>
>
>
> `g c;f=e l=d;print(g,o,l,f) /* gold */`
>
>
>
>
> `g c f=e l=d;print(g,o,l,f) /* golf */`
>
>
>
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes, 9 changes, [crick craked](https://codegolf.stackexchange.com/questions/241486/from-code-to-golf-robbers-thread/241511#241511) by Aaroneous Miller
```
«ƛ↔ƒ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCq8ab4oaUxpIiLCIiLCIiXQ==)
This was kinda fun to create. I'll see what happens!
## Programs:
```
«ƛ↔ƒ outputs code
«ƛ↔ṙ outputs coal
«ƛ℅ṙ outputs fear
«ƛ℅ṫ outputs feat
«ƛFṫ outputs dent
«ƛF` outputs dell
«ƛ¾` outputs foci
`ƛ¾` outputs program
`ƛ₅` outputs then
`»₅` outputs golf
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCq8ab4oaUxpLCqyxcbsKrxpvihpThuZnCqyxcbsKrxpvihIXhuZnCqyxcbsKrxpvihIXhuavCqyxcbsKrxptG4bmrwqssXG7Cq8abRmDCqyxcbsKrxpvCvmDCqyxcbmDGm8K+YCAsXG5gxpvigoVgICxcbmDCu+KChWAgLCIsIiIsIiJd) (last two characters of each line are to print)
Vyxal has two types of string compression. The first, delimited by `«`, takes the bytes within as a base-255 integer then converts that to base 27 and indexes it into a space plus the alphabet.
We switch through a bunch of these until we get to one where the last character is ```, allowing us to change the first character to ``` to get into a dictionary compressed regular string.
Vyxal's dictionary compression is fairly simple - it replaces pairs of non-ASCII characters with words from its dictionary, then remaining non-ASCII characters are replaced with words from a shorter dictionary.
This means that a string containing three characters shouldn't be able to return `golf`. But, I forgot that the short dictionary isn't complete (some slots aren't taken) and those just disappear, which Aaroneous's crack exploited.
Then, we iterate through a few words before getting to the 2-char compression code of `golf`.
[Answer]
# [!@#$%^&\*()\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), 13 bytes \* 4 steps = score 52, [cracked](https://codegolf.stackexchange.com/questions/241486/from-code-to-golf-robbers-thread/241624#241624) by Dom Hastings
```
3130<202(^+@)
```
[Try it online!](https://tio.run/##S03OSylITkzMKcop@P/f2NDYwMbIwEgjTttB8/9/AA "!@#$%^&*()_+ – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 35 bytes, 5 steps: score 175: SAFE
7 steps total, 5 excluding `code` and `golf`.
```
$_=$!=56;/(.)(o)(.)/;say$1.$2.$3.$'
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lZF0dbUzFpfQ09TI18TSOpbFydWqhjqqRjpqRjrqaj///8vv6AkMz@v@L@ur6meoYGeAQA "Perl 5 – Try It Online")
---
When attempting to crack my own previous post, I noticed another way to crack it (using `"$2$1$3$4"` would have prevented this and also saved a byte...). Changing the variable names (as per some of the other posts) is both efficient and relatively straightforward with the right set of words. The regex match against the error is purely a red herring in this instance.
```
$_=$!=56;/(.)(o)(.)/;say$1.$2.$3.$'; # code
$_=$!=56;/(.)(o)(.)/;say$1.$2.$3.$f; # cod
$_=$!=56;/(.)(o)(.)/;say$g.$2.$3.$f; # od
$_=$!=56;/(.)(o)(.)/;say g.$2.$3.$f; # god
$_=$!=56;/(.)(o)(.)/;say g.$2.$l.$f; # go
$_=$!=56;/(.)(o)(.)/;say g.$2. l.$f; # gol
$_=$!=56;/(.)(o)(.)/;say g.$2. l. f; # golf
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lZF0dbUzFpfQ09TI18TSOpbFydWqhjqqRjpqRjrqahbKygrJOenpHIRVpsGVYtbaTqKUjwqFVBVphNWmgNXSkClAkJlDmGlCjClaf///8svKMnMzyv@r@trqmdooGcAAA "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 34 bytes \* 2 steps = score 68, [cracked](https://codegolf.stackexchange.com/a/241750/106959) by ThisFieldIsRequired
```
golf="code"
goof="cold"
print golf
```
[Try it online!](https://tio.run/##K6gsycjPM/r/Pz0/J81WKTk/JVWJKz0/H8zOSVHiKijKzCtRAMn@/w8A "Python 2 – Try It Online")
Easier than you think
[Answer]
# [Python 3](https://docs.python.org/3/), 55 bytes \* 2 steps = 110 score, [cracked](https://codegolf.stackexchange.com/a/241878/106959) by Aaron
```
golf="code"
try:exec("print( golf )")
except:print("a")
```
[Try it online!](https://tio.run/##K6gsycjPM/7/Pz0/J81WKTk/JVWJq6So0iq1IjVZQ6mgKDOvREMBJKmgqaTJlVqRnFpQYgURVkpU0vz/HwA "Python 3 – Try It Online")
] |
[Question]
[
This challenge is inspired by the [High throughput Fizz Buzz](https://codegolf.stackexchange.com/questions/215216/high-throughput-fizz-buzz) challenge.
## The goal
Generate a list of prime numbers up to **10,000,000,000,000,000**. The output of primes should be in decimal digits followed by a newline character `'\n'` in ascending order starting from the lowest prime **2**. You may not skip a prime number or output a composite number.
## Scoring
Your program's throughput will be measured on my Linux machine by the following command.
```
(timeout 1m ./your-program) | pv > /dev/null
```
At the timeout after 1 minute, your score will be the total size of output measured by `pv`.
## An example
This is a simple example of a conforming program in C. It produces `49.6MiB` of data in total for a minute, on my machine with 2.4GHz 4-core CPU and 4GiB RAM.
```
#include <stdio.h>
int main() {
puts("2");
for (long long i = 3; i < 10000000000000000; i += 2) {
for (long long j = 3; j * j <= i; j += 2) {
if (i % j == 0) {
goto next;
}
}
printf("%lld\n", i);
next:;
}
return 0;
}
```
## Rules
You should only print what's specified in **the goal**. You may not print garbage characters including ones that do not appear on the terminal.
The maximum size of your source code is `64Kib`.
Otherwise, I'll accept any code that can be run on my Linux machine with 4 cores and AVX2 support.
---
## Leaderboard
| Contestant | Language | Score |
| --- | --- | --- |
| xiver77 | C + asm | 9.71GiB |
| alephalpha | C + PARI/GP | 6.85GiB |
| Neil | C | 5.47GiB |
| Seggan | Jyxal | 120MiB |
| (example) | C | 56.2MiB |
| emanresu A | Vyxal | 21.8MiB |
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~7.3Mb
```
0 { 200 ( ∆Ṗ : ) W ṫ $ ⁋,
```
Vyxal really isn't fast.
Because Vyxal is stack-based, an operation such as `1 +` (incrementing) is actually `push(1), push(add(pop(),pop()))`, which makes it incredibly difficult to optimize anything.
Vyxal uses [Sympy's `isprime`](https://docs.sympy.org/latest/modules/ntheory.html#sympy.ntheory.primetest.isprime), which looks for small factors, then for numbers \$ n < 2^{64}\$ it runs a set of [Miller-Rabin tests](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test). In other words, no optimization there.
So, the above program optimizes by buffering the output into groups of 200, which through experimentation produces the most output.
This version
`{` is loop forever. `200 ( ∆Ṗ : )` means "200 times, get the prime after the top of stack and push a copy of it". `W ṫ $` gets all but the last one (which we use for the next iteration of the forever loop), then `⁋,` prints that joined by newlines.
## Other attempts
## ~10Kb
```
0 {›:ǎ,
```
This one's "forever, print the nth prime and increment n". It's kinda slow.
## ~165Kb
```
0 { ∆Ṗ …
```
This one's "forever, get the next prime and print it". It's an order of magnitude faster than the previous, but still slow.
## ~780Kb
```
Þp(n,
```
5x faster than the previous, but still not very fast, this one loops through an infinite generator of primes and prints each one.
## ~4.3Mb
```
0 { ⟨⟩ →primes 100 ( ∆Ṗ : ←primes $ J →primes) ←primes ⁋ ,
```
Like the main submission but uses an array instead of the stack, making it slower.
\* amounts approximated with online interpreter, unreliable
[Answer]
### C + assembly (nasm) 9.71GiB
I got to know a program called [primesieve](https://github.com/kimwalisch/primesieve) from a comment and was impressed to know that it can generate prime numbers so fast. Somehow the existence of the program triggered me in a weird way that I felt I should and can build a program that is faster than `primesieve`. I don't know why, but really *somehow* it felt like an easy opponent, and it wasn't. Over a month the goal of building a faster program than `primesieve` drained so much of my energy, but unfortunately, the best I could reach was about 0.8 times the speed of `primesieve` (1).
Well, I could still make a faster one if I just copy the same algorithm `primesieve` used, and apply some of optimization techniques I gathered while trying to beat it. Maybe I will do that later in time, but for now I feel that just re-implementing the same algorithm is not a fun task. Also, one of the reasons why I didn't use the same algorithm is because [that algorithm](http://sweet.ua.pt/tos/software/prime_sieve.html) is quite complex and thus difficult to implement it efficiently. I really thought a simpler approach will be faster, but now it is apparent why `primesieve` took the hard route of implementing such a complex algorithm. It was obviously worth it.
Anyway the simpler route still took me more than a month of my free time and a lot of sleeplessness. The result is just a slower program than `primesieve` but it is still enough as a fast program here.
I didn't do any IO optimizations, but just a loop of `printf`s. There are many ways to make the output faster, but I don't have the energy to do it now.
---
(1) If you're interested [this](https://pastebin.com/SXryZnGx) is an alternative `main.c` which actually counts primes like `primesieve`. The gap in speed is about 10~30%, which gets bigger as the sieving range gets larger, which is why my choice of algorithm was wrong and `primesieve`'s was right.
#### prime.h
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <math.h>
#include <unistd.h>
typedef unsigned char v16b
__attribute__((vector_size(16), aligned(16), may_alias));
extern unsigned BC;
extern unsigned L1C;
extern unsigned char PADD[];
extern unsigned char WIX[];
extern unsigned char countPrimes_bf[];
extern unsigned char countPrimes_rm[];
extern v16b sieve_7_13_M7[];
extern v16b sieve_7_13_M11[];
extern v16b sieve_7_13_M13[];
void sieve_7_13(unsigned char *, uint64_t);
void sieve_17(unsigned char *, uint64_t);
void sieve_19(unsigned char *, uint64_t);
void sieve_23(unsigned char *, uint64_t);
void sieve_29(unsigned char *, uint64_t);
void sieve_31(unsigned char *, uint64_t);
void sieve_37(unsigned char *, uint64_t);
void sieve_41(unsigned char *, uint64_t);
void sieve_43(unsigned char *, uint64_t);
void sieve_47(unsigned char *, uint64_t);
void sieve_53(unsigned char *, uint64_t);
void sieve_59(unsigned char *, uint64_t);
void sieve_61(unsigned char *, uint64_t);
void sieve_67(unsigned char *, uint64_t);
void sieve_71(unsigned char *, uint64_t);
void sieve_73(unsigned char *, uint64_t);
void sieve_79(unsigned char *, uint64_t);
void sieve_83(unsigned char *, uint64_t);
void sieve_89(unsigned char *, uint64_t);
void sieve_93_(unsigned char *, uint64_t, uint32_t *, unsigned);
static inline uint64_t sq(uint64_t a) {
return a * a;
}
```
#### main.c
```
#include "prime.h"
typedef struct {
uint64_t p;
uint64_t sp;
} np_t;
static np_t fillBase(uint32_t *p, np_t n, unsigned char *f, uint64_t st,
uint64_t end, uint64_t lim) {
#define push(a) do {\
*p_ = st + i * 30 + a;\
if (*p_ < L1C / 8) ++n.sp;\
if (sq(*p_++) > lim) return (np_t){p_ - p + n.p, n.sp};\
} while (0)
p += n.p;
uint32_t *p_ = p;
unsigned i = 0;
do {
if (f[i] & 1 << 0) {
push(1);
}
if (f[i] & 1 << 1) {
push(7);
}
if (f[i] & 1 << 2) {
push(11);
}
if (f[i] & 1 << 3) {
push(13);
}
if (f[i] & 1 << 4) {
push(17);
}
if (f[i] & 1 << 5) {
push(19);
}
if (f[i] & 1 << 6) {
push(23);
}
if (f[i] & 1 << 7) {
push(29);
}
} while (st + ++i * 30 < end);
return (np_t){p_ - p + n.p, n.sp};
#undef push
}
static void sieve(unsigned char *f, uint64_t st, uint32_t *p, unsigned nsp) {
memset(f, -1, BC);
unsigned i = 0;
do {
uint64_t sti30 = st + i * 30;
sieve_7_13(f + i, sti30);
sieve_17(f + i, sti30);
sieve_19(f + i, sti30);
sieve_23(f + i, sti30);
sieve_29(f + i, sti30);
sieve_31(f + i, sti30);
sieve_37(f + i, sti30);
sieve_41(f + i, sti30);
sieve_43(f + i, sti30);
sieve_47(f + i, sti30);
sieve_53(f + i, sti30);
sieve_59(f + i, sti30);
sieve_61(f + i, sti30);
sieve_67(f + i, sti30);
sieve_71(f + i, sti30);
sieve_73(f + i, sti30);
sieve_79(f + i, sti30);
sieve_83(f + i, sti30);
sieve_89(f + i, sti30);
sieve_93_(f + i, sti30, p, nsp);
} while ((i += L1C) < BC);
sieve_93_(f, st, p + nsp, -1);
}
static void print(unsigned char *f, uint64_t st) {
#define p(a) printf("%"PRIu64"\n", st + i * 30 + a);
uint64_t i = 0;
do {
if (f[i] & 1 << 0) {
p(1);
}
if (f[i] & 1 << 1) {
p(7);
}
if (f[i] & 1 << 2) {
p(11);
}
if (f[i] & 1 << 3) {
p(13);
}
if (f[i] & 1 << 4) {
p(17);
}
if (f[i] & 1 << 5) {
p(19);
}
if (f[i] & 1 << 6) {
p(23);
}
if (f[i] & 1 << 7) {
p(29);
}
} while (++i < BC);
#undef p
}
static void printPrimes(uint64_t lim) {
_Alignas(64) unsigned char f[BC + 256];
uint32_t *p = aligned_alloc(64, sqrt(lim));
unsigned bfsz = 256;
np_t n = fillBase(p, (np_t){0}, countPrimes_bf, 0, bfsz * 30, -1);
sieve(f, 0, p, n.sp);
*f &= ~1;
print(f, 0);
unsigned r = lim % 30;
if (!r) {
--lim;
} else if (1 < r && r < 7) {
lim -= r - 1;
} else if (7 < r && r < 11) {
lim -= r - 7;
} else if (13 < r && r < 17) {
lim -= r - 13;
} else if (r == 18) {
--lim;
} else if (19 < r && r < 23) {
lim -= r - 19;
} else if (23 < r && r < 29) {
lim -= r - 23;
}
unsigned bc30 = BC * 30;
r = lim % bc30;
uint64_t lim_ = lim - r + bc30;
n = fillBase(p, n, f + bfsz, bfsz * 30, bc30, lim_);
uint64_t st = bc30;
for (; st + bc30 < lim_; st += bc30) {
sieve(f, st, p, n.sp);
if (sq(st + 1) < lim_) {
n = fillBase(p, n, f, st, st + bc30, lim_);
}
print(f, st);
}
sieve(f, st, p, n.sp);
unsigned q = r / 30;
memset(f + q + 1, 0, BC - q);
f[q] &= countPrimes_rm[r % 30 / 2];
print(f, st);
}
int main() {
L1C = sysconf(_SC_LEVEL1_DCACHE_SIZE) - (1 << 12);
BC = L1C * 8;
puts("2\n3\n5\n7\n11\n13");
printPrimes(1e16);
return 0;
}
```
#### lut.s
```
align 16
global PADD
PADD:
db 1, 7, 7, 7, 7, 7, 7, 11, 11, 11, 11, 13, 13, 17, 17, 17, 17
db 19, 19, 23, 23, 23, 23, 29, 29, 29, 29, 29, 29, 31, -1, -1
global WIX
WIX:
db 0, -1, -1, 1, -1, 2, 3, -1, 4, 5, -1, 6, -1, -1, 7, -1
global countPrimes_bf
countPrimes_bf:
dq 0xf93ddbb67e000000, 0x9eeda6eaf31e4fd5, 0xa559dd3bd3d30ce6
dq 0x56a61e78bd92676a, 0x554c2ade2dade356, 0xf8a154039ff0a3d9,
dq 0x3a13f666e944fd2e, 0x54bf11453a2b4cb8, 0x4f8cbcc8b37ac18c,
dq 0xef17c19b71715821, 0x468c83e5081a9654, 0x87588f9265aefb72,
dq 0xa0e3266581d892d2, 0x99eb813c26c73811, 0x4d33f3243e88518d,
dq 0x4c58b42aa71c8b5a, 0xc383dc8219f6264e, 0x02cdcdb50238f12c,
dq 0x307a4c570c944ab2, 0xf8246c44cbf10b43, 0x8dea735ca8950119,
dq 0xc41e22a6502b9624, 0x9c742f3ad40648d1, 0x2e1568bf88056a07,
dq 0x14089851b7e35560, 0x2770494d45aa5a86, 0x618302abcad593d2,
dq 0xada9c22287ce2405, 0xb01689d1784d8c18, 0x522434c0a262c757,
dq 0x4308218d32405aae, 0x60e119d9b6d2b634
global countPrimes_rm
countPrimes_rm:
db 0x01, 0, 0, 0x03, 0, 0x07, 0x0f, 0, 0x1f, 0x3f, 0, 0x7f, 0, 0, 0xff, 0
global sieve_7_13_M7
sieve_7_13_M7:
db 0xfd, 0xdf, 0xef, 0x7e, 0xf7, 0xfb, 0xbf, 0xfd, 0xdf, 0xef, 0x7e, 0xf7
db 0xfb, 0xbf, 0xfd, 0xdf
db 0xef, 0x7e, 0xf7, 0xfb, 0xbf, 0xfd, 0xdf, 0xef, 0x7e, 0xf7, 0xfb, 0xbf
db 0xfd, 0xdf, 0xef, 0x7e
db 0xf7, 0xfb, 0xbf, 0xfd, 0xdf, 0xef, 0x7e, 0xf7, 0xfb, 0xbf, 0xfd, 0xdf
db 0xef, 0x7e, 0xf7, 0xfb
db 0xbf, 0xfd, 0xdf, 0xef, 0x7e, 0xf7, 0xfb, 0xbf, 0xfd, 0xdf, 0xef, 0x7e
db 0xf7, 0xfb, 0xbf, 0xfd
db 0xdf, 0xef, 0x7e, 0xf7, 0xfb, 0xbf, 0xfd, 0xdf, 0xef, 0x7e, 0xf7, 0xfb
db 0xbf, 0xfd, 0xdf, 0xef
db 0x7e, 0xf7, 0xfb, 0xbf, 0xfd, 0xdf, 0xef, 0x7e, 0xf7, 0xfb, 0xbf, 0xfd
db 0xdf, 0xef, 0x7e, 0xf7
db 0xfb, 0xbf, 0xfd, 0xdf, 0xef, 0x7e, 0xf7, 0xfb, 0xbf, 0xfd, 0xdf, 0xef
db 0x7e, 0xf7, 0xfb, 0xbf
global sieve_7_13_M11
sieve_7_13_M11:
db 0xfb, 0xff, 0xef, 0xff, 0xbe, 0xff, 0x7d, 0xff, 0xf7, 0xff, 0xdf, 0xfb
db 0xff, 0xef, 0xff, 0xbe
db 0xff, 0x7d, 0xff, 0xf7, 0xff, 0xdf, 0xfb, 0xff, 0xef, 0xff, 0xbe, 0xff
db 0x7d, 0xff, 0xf7, 0xff
db 0xdf, 0xfb, 0xff, 0xef, 0xff, 0xbe, 0xff, 0x7d, 0xff, 0xf7, 0xff, 0xdf
db 0xfb, 0xff, 0xef, 0xff
db 0xbe, 0xff, 0x7d, 0xff, 0xf7, 0xff, 0xdf, 0xfb, 0xff, 0xef, 0xff, 0xbe
db 0xff, 0x7d, 0xff, 0xf7
db 0xff, 0xdf, 0xfb, 0xff, 0xef, 0xff, 0xbe, 0xff, 0x7d, 0xff, 0xf7, 0xff
db 0xdf, 0xfb, 0xff, 0xef
db 0xff, 0xbe, 0xff, 0x7d, 0xff, 0xf7, 0xff, 0xdf, 0xfb, 0xff, 0xef, 0xff
db 0xbe, 0xff, 0x7d, 0xff
db 0xf7, 0xff, 0xdf, 0xfb, 0xff, 0xef, 0xff, 0xbe, 0xff, 0x7d, 0xff, 0xf7
db 0xff, 0xdf, 0xfb, 0xff
db 0xef, 0xff, 0xbe, 0xff, 0x7d, 0xff, 0xf7, 0xff, 0xdf, 0xfb, 0xff, 0xef
db 0xff, 0xbe, 0xff, 0x7d
db 0xff, 0xf7, 0xff, 0xdf, 0xfb, 0xff, 0xef, 0xff, 0xbe, 0xff, 0x7d, 0xff
db 0xf7, 0xff, 0xdf, 0xfb
db 0xff, 0xef, 0xff, 0xbe, 0xff, 0x7d, 0xff, 0xf7, 0xff, 0xdf, 0xfb, 0xff
db 0xef, 0xff, 0xbe, 0xff
db 0x7d, 0xff, 0xf7, 0xff, 0xdf, 0xfb, 0xff, 0xef, 0xff, 0xbe, 0xff, 0x7d
db 0xff, 0xf7, 0xff, 0xdf
global sieve_7_13_M13
sieve_7_13_M13:
db 0xf7, 0xff, 0xff, 0xfe, 0xbf, 0xdf, 0xff, 0xfb, 0xfd, 0x7f, 0xff, 0xff
db 0xef, 0xf7, 0xff, 0xff
db 0xfe, 0xbf, 0xdf, 0xff, 0xfb, 0xfd, 0x7f, 0xff, 0xff, 0xef, 0xf7, 0xff
db 0xff, 0xfe, 0xbf, 0xdf
db 0xff, 0xfb, 0xfd, 0x7f, 0xff, 0xff, 0xef, 0xf7, 0xff, 0xff, 0xfe, 0xbf
db 0xdf, 0xff, 0xfb, 0xfd
db 0x7f, 0xff, 0xff, 0xef, 0xf7, 0xff, 0xff, 0xfe, 0xbf, 0xdf, 0xff, 0xfb
db 0xfd, 0x7f, 0xff, 0xff
db 0xef, 0xf7, 0xff, 0xff, 0xfe, 0xbf, 0xdf, 0xff, 0xfb, 0xfd, 0x7f, 0xff
db 0xff, 0xef, 0xf7, 0xff
db 0xff, 0xfe, 0xbf, 0xdf, 0xff, 0xfb, 0xfd, 0x7f, 0xff, 0xff, 0xef, 0xf7
db 0xff, 0xff, 0xfe, 0xbf
db 0xdf, 0xff, 0xfb, 0xfd, 0x7f, 0xff, 0xff, 0xef, 0xf7, 0xff, 0xff, 0xfe
db 0xbf, 0xdf, 0xff, 0xfb
db 0xfd, 0x7f, 0xff, 0xff, 0xef, 0xf7, 0xff, 0xff, 0xfe, 0xbf, 0xdf, 0xff
db 0xfb, 0xfd, 0x7f, 0xff
db 0xff, 0xef, 0xf7, 0xff, 0xff, 0xfe, 0xbf, 0xdf, 0xff, 0xfb, 0xfd, 0x7f
db 0xff, 0xff, 0xef, 0xf7
db 0xff, 0xff, 0xfe, 0xbf, 0xdf, 0xff, 0xfb, 0xfd, 0x7f, 0xff, 0xff, 0xef
db 0xf7, 0xff, 0xff, 0xfe
db 0xbf, 0xdf, 0xff, 0xfb, 0xfd, 0x7f, 0xff, 0xff, 0xef, 0xf7, 0xff, 0xff
db 0xfe, 0xbf, 0xdf, 0xff
db 0xfb, 0xfd, 0x7f, 0xff, 0xff, 0xef, 0xf7, 0xff, 0xff, 0xfe, 0xbf, 0xdf
db 0xff, 0xfb, 0xfd, 0x7f
db 0xff, 0xff, 0xef, 0xf7, 0xff, 0xff, 0xfe, 0xbf, 0xdf, 0xff, 0xfb, 0xfd
db 0x7f, 0xff, 0xff, 0xef
section .bss
global L1C
L1C:
resb 4
global BC
BC:
resb 4
```
#### sieve\_7\_13.c
```
#include "prime.h"
#define am7(_0, _1, _2, _3, _4, _5, _6) do {\
m0 = M7[_0]; m1 = M7[_1]; m2 = M7[_2]; m3 = M7[_3]; m4 = M7[_4];\
m5 = M7[_5]; m6 = M7[_6];\
} while (0)
#define am11(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) do {\
m0 = M11[_0]; m1 = M11[_1]; m2 = M11[_2]; m3 = M11[_3]; m4 = M11[_4];\
m5 = M11[_5]; m6 = M11[_6]; m7 = M11[_7]; m8 = M11[_8]; m9 = M11[_9];\
m10 = M11[_10];\
} while (0)
#define am13(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12) do {\
m0 = M13[_0]; m1 = M13[_1]; m2 = M13[_2]; m3 = M13[_3]; m4 = M13[_4];\
m5 = M13[_5]; m6 = M13[_6]; m7 = M13[_7]; m8 = M13[_8]; m9 = M13[_9];\
m10 = M13[_10]; m11 = M13[_11]; m12 = M13[_12];\
} while (0)
void sieve_7_13(unsigned char *f, uint64_t st) {
static const void *L[] = {
&&_7_0, &&_7_1, &&_7_2, &&_7_3, &&_7_4, &&_7_5, &&_7_6,
&&_11_0, &&_11_1, &&_11_2, &&_11_3, &&_11_4, &&_11_5, &&_11_6, &&_11_7,
&&_11_8, &&_11_9, &&_11_10,
&&_13_0, &&_13_1, &&_13_2, &&_13_3, &&_13_4, &&_13_5, &&_13_6, &&_13_7,
&&_13_8, &&_13_9, &&_13_10, &&_13_11, &&_13_12
};
uint64_t stb = st / 30;
v16b *M7 = sieve_7_13_M7;
v16b *M11 = sieve_7_13_M11;
v16b *M13 = sieve_7_13_M13;
v16b m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12;
v16b *vf;
goto *L[stb % 7];
_7_0:
am7(0, 1, 2, 3, 4, 5, 6);
goto _7;
_7_1:
am7(4, 5, 6, 0, 1, 2, 3);
goto _7;
_7_2:
am7(1, 2, 3, 4, 5, 6, 0);
goto _7;
_7_3:
am7(5, 6, 0, 1, 2, 3, 4);
goto _7;
_7_4:
am7(2, 3, 4, 5, 6, 0, 1);
goto _7;
_7_5:
am7(6, 0, 1, 2, 3, 4, 5);
goto _7;
_7_6:
am7(3, 4, 5, 6, 0, 1, 2);
_7:
vf = (v16b *)f;
do {
vf[0] &= m0;
vf[1] &= m1;
vf[2] &= m2;
vf[3] &= m3;
vf[4] &= m4;
vf[5] &= m5;
vf[6] &= m6;
} while ((unsigned char *)(vf += 7) < f + L1C);
goto *(L + 7)[stb % 11];
_11_0:
am11(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
goto _11;
_11_1:
am11(9, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8);
goto _11;
_11_2:
am11(7, 8, 9, 10, 0, 1, 2, 3, 4, 5, 6);
goto _11;
_11_3:
am11(3, 4, 5, 6, 7, 8, 9, 10, 0, 1, 2);
goto _11;
_11_4:
am11(5, 6, 7, 8, 9, 10, 0, 1, 2, 3, 4);
goto _11;
_11_5:
am11(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0);
goto _11;
_11_6:
am11(10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
goto _11;
_11_7:
am11(8, 9, 10, 0, 1, 2, 3, 4, 5, 6, 7);
goto _11;
_11_8:
am11(6, 7, 8, 9, 10, 0, 1, 2, 3, 4, 5);
goto _11;
_11_9:
am11(4, 5, 6, 7, 8, 9, 10, 0, 1, 2, 3);
goto _11;
_11_10:
am11(2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 1);
_11:
vf = (v16b *)f;
do {
vf[0] &= m0;
vf[1] &= m1;
vf[2] &= m2;
vf[3] &= m3;
vf[4] &= m4;
vf[5] &= m5;
vf[6] &= m6;
vf[7] &= m7;
vf[8] &= m8;
vf[9] &= m9;
vf[10] &= m10;
} while ((unsigned char *)(vf += 11) < f + L1C);
goto *(L + 18)[stb % 13];
_13_0:
am13(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
goto _13;
_13_1:
am13(9, 10, 11, 12, 0, 1, 2, 3, 4, 5, 6, 7, 8);
goto _13;
_13_2:
am13(5, 6, 7, 8, 9, 10, 11, 12, 0, 1, 2, 3, 4);
goto _13;
_13_3:
am13(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0);
goto _13;
_13_4:
am13(10, 11, 12, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
goto _13;
_13_5:
am13(6, 7, 8, 9, 10, 11, 12, 0, 1, 2, 3, 4, 5);
goto _13;
_13_6:
am13(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 1);
goto _13;
_13_7:
am13(11, 12, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
goto _13;
_13_8:
am13(7, 8, 9, 10, 11, 12, 0, 1, 2, 3, 4, 5, 6);
goto _13;
_13_9:
am13(3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 1, 2);
goto _13;
_13_10:
am13(12, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
goto _13;
_13_11:
am13(8, 9, 10, 11, 12, 0, 1, 2, 3, 4, 5, 6, 7);
goto _13;
_13_12:
am13(4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 1, 2, 3);
_13:
vf = (v16b *)f;
do {
vf[0] &= m0;
vf[1] &= m1;
vf[2] &= m2;
vf[3] &= m3;
vf[4] &= m4;
vf[5] &= m5;
vf[6] &= m6;
vf[7] &= m7;
vf[8] &= m8;
vf[9] &= m9;
vf[10] &= m10;
vf[11] &= m11;
vf[12] &= m12;
} while ((unsigned char *)(vf += 13) < f + L1C);
}
```
#### sieve\_17\_89.c
```
#include "prime.h"
#define eb8(c0, c1, c2, c3, c4, c5, c6, c7, d1, d2, d3, d4, d5, d6, d7) do {\
*f_ &= ~(1 << c0);\
f_[q * 3 + d1] &= ~(1 << c1);\
f_[q * 5 + d2] &= ~(1 << c2);\
f_[q * 6 + d3] &= ~(1 << c3);\
f_[q * 8 + d4] &= ~(1 << c4);\
f_[q * 9 + d5] &= ~(1 << c5);\
f_[q * 11 + d6] &= ~(1 << c6);\
f_[q * 14 + d7] &= ~(1 << c7);\
} while (0)
#define eb(m, i, a) do {\
*f_ &= ~(1 << i);\
if ((f_ += q * m + a) >= f + c) return;\
} while (0)
#define eb0(i, a) eb(3, i, a)
#define eb1(i, a) eb(2, i, a)
#define eb2(i, a) eb(1, i, a)
#define eb3(i, a) eb(2, i, a)
#define eb4(i, a) eb(1, i, a)
#define eb5(i, a) eb(2, i, a)
#define eb6(i, a) eb(3, i, a)
#define eb7(i, a) eb(1, i, a)
static void sieve(unsigned char *f, uint64_t st, unsigned p) {
unsigned c = L1C;
uint64_t psq = sq(p);
int64_t d = psq - st;
unsigned char *f_ = f;
unsigned w;
if (__builtin_expect(psq > st, 0)) {
f_ += (unsigned)d / 30;
w = WIX[p % 30 / 2];
} else {
uint64_t p30 = (uint64_t)p * 30;
uint64_t n = st / p30 * 30 + PADD[st % p30 / p];
f_ += (unsigned)(p * n - st) / 30;
w = WIX[n % 30 / 2];
}
unsigned q = p / 30 * 2;
switch (p % 30) {
case 1:
switch (w) {
for (;;) {
case 0:
for (; f_ + p < f + c; f_ += p) {
eb8(0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0);
}
eb0(0, 0);
case 1:
eb1(1, 0);
case 2:
eb2(2, 0);
case 3:
eb3(3, 0);
case 4:
eb4(4, 0);
case 5:
eb5(5, 0);
case 6:
eb6(6, 0);
case 7:
eb7(7, 1);
}
default:
__builtin_unreachable();
}
case 7:
switch (w) {
for (;;) {
case 0:
for (; f_ + p < f + c; f_ += p) {
eb8(1, 5, 4, 0, 7, 3, 2, 6, 1, 2, 3, 3, 4, 5, 6);
}
eb0(1, 1);
case 1:
eb1(5, 1);
case 2:
eb2(4, 1);
case 3:
eb3(0, 0);
case 4:
eb4(7, 1);
case 5:
eb5(3, 1);
case 6:
eb6(2, 1);
case 7:
eb7(6, 1);
}
default:
__builtin_unreachable();
}
case 11:
switch (w) {
for (;;) {
case 0:
for (; f_ + p < f + c; f_ += p) {
eb8(2, 4, 0, 6, 1, 7, 3, 5, 2, 4, 4, 6, 6, 8, 10);
}
eb0(2, 2);
case 1:
eb1(4, 2);
case 2:
eb2(0, 0);
case 3:
eb3(6, 2);
case 4:
eb4(1, 0);
case 5:
eb5(7, 2);
case 6:
eb6(3, 2);
case 7:
eb7(5, 1);
}
default:
__builtin_unreachable();
}
case 13:
switch (w) {
for (;;) {
case 0:
for (; f_ + p < f + c; f_ += p) {
eb8(3, 0, 6, 5, 2, 1, 7, 4, 3, 4, 5, 7, 8, 9, 12);
}
eb0(3, 3);
case 1:
eb1(0, 1);
case 2:
eb2(6, 1);
case 3:
eb3(5, 2);
case 4:
eb4(2, 1);
case 5:
eb5(1, 1);
case 6:
eb6(7, 3);
case 7:
eb7(4, 1);
}
default:
__builtin_unreachable();
}
case 17:
switch (w) {
for (;;) {
case 0:
for (; f_ + p < f + c; f_ += p) {
eb8(4, 7, 1, 2, 5, 6, 0, 3, 3, 6, 7, 9, 10, 13, 16);
}
eb0(4, 3);
case 1:
eb1(7, 3);
case 2:
eb2(1, 1);
case 3:
eb3(2, 2);
case 4:
eb4(5, 1);
case 5:
eb5(6, 3);
case 6:
eb6(0, 3);
case 7:
eb7(3, 1);
}
default:
__builtin_unreachable();
}
case 19:
switch (w) {
for (;;) {
case 0:
for (; f_ + p < f + c; f_ += p) {
eb8(5, 3, 7, 1, 6, 0, 4, 2, 4, 6, 8, 10, 12, 14, 18);
}
eb0(5, 4);
case 1:
eb1(3, 2);
case 2:
eb2(7, 2);
case 3:
eb3(1, 2);
case 4:
eb4(6, 2);
case 5:
eb5(0, 2);
case 6:
eb6(4, 4);
case 7:
eb7(2, 1);
}
default:
__builtin_unreachable();
}
case 23:
switch (w) {
for (;;) {
case 0:
for (; f_ + p < f + c; f_ += p) {
eb8(6, 2, 3, 7, 0, 4, 5, 1, 5, 8, 9, 13, 14, 17, 22);
}
eb0(6, 5);
case 1:
eb1(2, 3);
case 2:
eb2(3, 1);
case 3:
eb3(7, 4);
case 4:
eb4(0, 1);
case 5:
eb5(4, 3);
case 6:
eb6(5, 5);
case 7:
eb7(1, 1);
}
default:
__builtin_unreachable();
}
case 29:
switch (w) {
for (;;) {
case 0:
for (; f_ + p < f + c; f_ += p) {
eb8(7, 6, 5, 4, 3, 2, 1, 0, 6, 10, 12, 16, 18, 22, 28);
}
eb0(7, 6);
case 1:
eb1(6, 4);
case 2:
eb2(5, 2);
case 3:
eb3(4, 4);
case 4:
eb4(3, 2);
case 5:
eb5(2, 4);
case 6:
eb6(1, 6);
case 7:
eb7(0, 1);
}
default:
__builtin_unreachable();
}
default:
__builtin_unreachable();
}
}
void sieve_17(unsigned char *f, uint64_t st) {
sieve(f, st, 17);
}
void sieve_19(unsigned char *f, uint64_t st) {
sieve(f, st, 19);
}
void sieve_23(unsigned char *f, uint64_t st) {
sieve(f, st, 23);
}
void sieve_29(unsigned char *f, uint64_t st) {
sieve(f, st, 29);
}
void sieve_31(unsigned char *f, uint64_t st) {
sieve(f, st, 31);
}
void sieve_37(unsigned char *f, uint64_t st) {
sieve(f, st, 37);
}
void sieve_41(unsigned char *f, uint64_t st) {
sieve(f, st, 41);
}
void sieve_43(unsigned char *f, uint64_t st) {
sieve(f, st, 43);
}
void sieve_47(unsigned char *f, uint64_t st) {
sieve(f, st, 47);
}
void sieve_53(unsigned char *f, uint64_t st) {
sieve(f, st, 53);
}
void sieve_59(unsigned char *f, uint64_t st) {
sieve(f, st, 59);
}
void sieve_61(unsigned char *f, uint64_t st) {
sieve(f, st, 61);
}
void sieve_67(unsigned char *f, uint64_t st) {
sieve(f, st, 67);
}
void sieve_71(unsigned char *f, uint64_t st) {
sieve(f, st, 71);
}
void sieve_73(unsigned char *f, uint64_t st) {
sieve(f, st, 73);
}
void sieve_79(unsigned char *f, uint64_t st) {
sieve(f, st, 79);
}
void sieve_83(unsigned char *f, uint64_t st) {
sieve(f, st, 83);
}
void sieve_89(unsigned char *f, uint64_t st) {
sieve(f, st, 89);
}
```
#### sieve\_93\_.s
```
%define MD30 -2004318071
%define MD30Q -8608480567731124087
%define f rdi
%define st rsi
%define pp r8
%define nsp ecx
%define c r9
%define c_d r9d
%define fc r9
%define p r10
%define p_d r10d
%define f_ r11
%define q r12
%define fp r13
%define psq rbx
%define d rbp
%define d_d ebp
%define md30 rsp
%define md30_d esp
%define w rbx
%define w_d ebx
%macro eb8 16
mov fp, f_
add fp, p
cmp fp, fc
jae _%1_0_
lea rax, [q + q * 2 + %10]
lea rbx, [q + q * 4 + %11]
lea rdx, [rax * 2 + %12]
lea rbp, [q * 8 + %13]
lea rsp, [q + q * 8 + %14]
lea r14, [rax + q * 8 + %15]
lea r15, [rdx + q * 8 + %16]
jmp _%1_0_1
_%1_0_0:
mov fp, f_
add fp, p
cmp fp, fc
jae _%1_0_
_%1_0_1:
and byte [f_], ~(1 << %2)
and byte [f_ + rax], ~(1 << %3)
and byte [f_ + rbx], ~(1 << %4)
and byte [f_ + rdx], ~(1 << %5)
and byte [f_ + rbp], ~(1 << %6)
and byte [f_ + rsp], ~(1 << %7)
and byte [f_ + r14], ~(1 << %8)
and byte [f_ + r15], ~(1 << %9)
mov f_, fp
jmp _%1_0_0
%endmacro
%macro eb 3
and byte [f_], ~(1 << %2)
lea f_, [f_ + q * %1 + %3]
cmp f_, fc
jae next_
%endmacro
%macro eb_4 2
and byte [f_], ~(1 << %1)
lea rax, [q + q * 2 + %2]
add f_, rax
cmp f_, fc
jae next_
%endmacro
%macro eb0 2
eb_4 %1, %2
%endmacro
%macro eb1 2
eb 2, %1, %2
%endmacro
%macro eb2 2
eb 1, %1, %2
%endmacro
%macro eb3 2
eb 2, %1, %2
%endmacro
%macro eb4 2
eb 1, %1, %2
%endmacro
%macro eb5 2
eb 2, %1, %2
%endmacro
%macro eb6 2
eb_4 %1, %2
%endmacro
%macro eb7 2
eb 1, %1, %2
%endmacro
extern L1C
extern BC
extern PADD
extern WIX
align 64
L:
dq _1, 0, 0, _7, 0, _11, _13, 0, _17, _19, 0, _23, 0, 0, _29, 0
dq _1_0, _1_1, _1_2, _1_3, _1_4, _1_5, _1_6, _1_7
dq _7_0, _7_1, _7_2, _7_3, _7_4, _7_5, _7_6, _7_7
dq _11_0, _11_1, _11_2, _11_3, _11_4, _11_5, _11_6, _11_7
dq _13_0, _13_1, _13_2, _13_3, _13_4, _13_5, _13_6, _13_7
dq _17_0, _17_1, _17_2, _17_3, _17_4, _17_5, _17_6, _17_7
dq _19_0, _19_1, _19_2, _19_3, _19_4, _19_5, _19_6, _19_7
dq _23_0, _23_1, _23_2, _23_3, _23_4, _23_5, _23_6, _23_7
dq _29_0, _29_1, _29_2, _29_3, _29_4, _29_5, _29_6, _29_7
align 16
global sieve_93_
sieve_93_:
push rbx
push rbp
push r12
push r13
push r14
push r15
movq xmm0, rsp
mov r8, rdx
mov c_d, [rel L1C]
mov eax, [rel BC]
cmp nsp, -1
cmove c_d, eax
mov p_d, [rel pp]
mov psq, p
imul psq, p
mov d, psq
sub d, st
L0:
imul rax, c, 30
cmp d, rax
jge end
mov f_, f
mov md30_d, MD30
cmp psq, st
ja L00
mov rax, st
xor rdx, rdx
imul rbx, p, 30
div rbx
imul rax, 30
mov rbx, rax
mov eax, edx
shr rdx, 32
div p_d
movzx eax, byte [rax + PADD]
add rax, rbx
mov rbx, rax
imul rax, p
sub rax, st
imul rax, md30
shr rax, 36
cmp eax, c_d
jae next
add f_, rax
mov rax, MD30Q
mul rbx
shr rdx, 4
imul rdx, -30
add rdx, rbx
shr edx, 1
movzx w_d, byte [rdx + WIX]
mov eax, p_d
imul rax, md30
shr rax, 36
imul edx, eax, -30
add edx, p_d
shr edx, 1
L1:
shl eax, 1
mov q, rax
add c, f
jmp [rdx * 8 + L]
align 16
_1:
jmp [w * 8 + L + 16 * 8]
align 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_6:
eb6 0, 3
_17_7:
eb7 3, 1
jmp _17_0
align 16
_19:
jmp [w * 8 + L + 56 * 8]
align 16
_19_0:
eb8 19, 5, 3, 7, 1, 6, 0, 4, 2, 4, 6, 0, 10, 12, 10, 10
_19_0_:
eb0 5, 4
_19_1:
eb1 3, 2
_19_2:
eb2 7, 2
_19_3:
eb3 1, 2
_19_4:
eb4 6, 2
_19_5:
eb5 0, 2
_19_6:
eb6 4, 4
_19_7:
eb7 2, 1
jmp _19_0
align 16
_23:
jmp [w * 8 + L + 64 * 8]
align 16
_23_0:
eb8 23, 6, 2, 3, 7, 0 ,4, 5, 1, 5, 8, -1, 13, 14, 12, 13
_23_0_:
eb0 6, 5
_23_1:
eb1 2, 3
_23_2:
eb2 3, 1
_23_3:
eb3 7, 4
_23_4:
eb4 0, 1
_23_5:
eb5 4, 3
_23_6:
eb6 5, 5
_23_7:
eb7 1, 1
jmp _23_0
align 16
_29:
jmp [w * 8 + L + 72 * 8]
align 16
_29_0:
eb8 29, 7, 6, 5, 4, 3, 2, 1, 0, 6, 10, 0, 16, 18, 16, 16
_29_0_:
eb0 7, 6
_29_1:
eb1 6, 4
_29_2:
eb2 5, 2
_29_3:
eb3 4, 4
_29_4:
eb4 3, 2
_29_5:
eb5 2, 4
_29_6:
eb6 1, 6
_29_7:
eb7 0, 1
jmp _29_0
align 16
next_:
sub c, f
next:
dec nsp
jz end
add pp, 4
mov p_d, [rel pp]
mov psq, p
imul psq, p
mov d, psq
sub d, st
jmp L0
align 16
L00:
mov eax, d_d
imul rax, md30
shr rax, 36
add f_, rax
mov eax, p_d
imul rax, md30
shr rax, 36
imul edx, eax, -30
add edx, p_d
shr edx, 1
movzx w_d, byte [rdx + WIX]
jmp L1
align 16
end:
movq rsp, xmm0
pop r15
pop r14
pop r13
pop r12
pop rbp
pop rbx
ret
```
#### build.sh
```
#!/bin/sh -x
SRC="main.c sieve_7_13.o sieve_17_89.o sieve_93_.o lut.o -lm"
C="gcc"
O="-O3 -march=native"
$C $O -c sieve_7_13.c
$C $O -c sieve_17_89.c
nasm -felf64 sieve_93_.s
nasm -felf64 lut.s
$C $O -or $SRC
rm *.o
```
[Answer]
# [Jyxal 0.4.1](https://github.com/Vyxal/Jyxal/releases/tag/0.4.1), 46 MiB on my computer, official score 120 MiB
```
{500(&›¥æß¥)W⁋₴
```
[Read the README to see how to run this](https://github.com/Vyxal/Jyxal#running)
For reference, the example program outputted 21.8 MiB on my computer.
I had a blast micro-optimizing the compiler. The old Jyxal answer was disqualified because it considered multiples of 5 prime. The new version of Jyxal is almost completely rewritten in Koltin (barring the math library) and contains a new post-compilation optimizer (powered by Proguard™). This allows Jyxal to move to Java 11. It also optimizes for loops. The needless push-pops are optimized away and the JVM operand stack is used whenever possible.
```
{500(&›¥æß¥)W⁋₴ # Takes no input
{ # Infinite loop
500( ) # Repeat 500 times
&› # Increment the register
¥æ # And check it for primality
ß # If it is prime...
¥ # Push the number
W # Wrap the stack in a list
⁋ # Join by newlines
₴ # And then print the result
# Implicitly loops back
```
The primality test is nothing as elaborate as Vyxal's. For numbers that are smaller than 9,223,372,036,854,775,807, the BigComplex object is converted into a long, and then the last bit is tested. If it is 0, that means the number is even and that the number is not prime. Then using an optimization I found on SO, I use a brute-force division algorithm that skips multiples of 2 and 3, lessening the number of divisors I need to check.
Compiled with
```
java -jar Jyxal.v.0.4.1.jar code.txt t
```
The `t` flag disables vectorisation of monads, which removes the need for `MethodHandles` and allows the monad to be inlined.
If you are interested, here is the bytecode decompiled into Java:
```
public final class Main {
private static Object register;
static {
register = BigComplex.ZERO;
}
public static void main(String[] var0) {
ProgramStack stack = new ProgramStack(var0);
while(true) {
for(int var1 = 500; var1 != 0; --var1) {
if (RuntimeHelpers.truthValue(RuntimeMethods.isPrime(register = RuntimeMethods.increment(register)))) {
stack.push(register);
}
}
System.out.print(RuntimeMethods.joinByNewlines(JyxalList.create(stack)));
}
}
}
```
[Answer]
# C (gcc -O3)
```
#include <stdio.h>
#include <string.h>
#define MAX_SQRT 100000000ULL
unsigned long composites[MAX_SQRT >> 7UL] = { 1 };
unsigned long primes[10000000] = { 2 };
int main(int argc, char **argv) {
unsigned long *last = primes;
printf("2\n");
for (unsigned long i = 3; i < MAX_SQRT; i += 2) {
if (composites[i >> 7UL] & 1UL << (i >> 1UL)) continue;
printf("%lu\n", i);
*++last = i;
for (unsigned long j = i * i >> 1UL; j < MAX_SQRT >> 1UL; j += i) composites[j >> 6UL] |= 1UL << j;
}
for (unsigned long long i = MAX_SQRT + 1; i < MAX_SQRT * MAX_SQRT; i += MAX_SQRT) {
memset(composites, 0, sizeof(composites));
for (unsigned long *j = primes; ++j <= last; ) {
unsigned long k = (unsigned long)(*j - 1 - ((*j - 1 + i) % (*j * 2) >> 1UL));
while (k < MAX_SQRT >> 1UL) {
composites[k >> 6UL] |= 1UL << k;
k += *j;
}
}
for (unsigned long j = 0; j < MAX_SQRT >> 1UL; j++) if (!(composites[j >> 6UL] & 1UL << j)) printf("%llu\n", i + j * 2);
}
}
```
Outputs 6.2GB in 1 minute on my fast PC, for a speed of 105 MB/s. Note that I timed using `(timeout 1m ./a.out) | pv > /dev/null`, which avoids timing out `pv` itself.
[Answer]
## C++
```
#include <stdio.h>
#include <array>
// ~~ Algorithm Description ~~
// Since sqrt(max) = 100000000 = M, we should precompute primes until M,
// because all factors of N are always smaller or equal to sqrt(N).
// There are 5761455 primes smaller than M.
// After these maneuvers, assuming that `ull' is 8 bytes large, the binary
// will grow by approximately 46 megabytes.
// Notice that this solution largely makes use of the C++ compile-time features
// and the fact that the program's compile-time isn't timed nor the binary size
// isn't measured.
// BUILDING:
// g++ -O3 -std=c++20 pgen.cpp -o pgen -fconstexpr-ops-limit=1000000000000 -fconstexpr-loop-limit=1000000000
typedef unsigned long long ull;
template <std::size_t N>
constexpr std::array<ull, N> get_ptab() {
std::array<ull, N> ptab;
ull gen = 3;
ptab[0] = 2; ptab[1] = 3; ptab[2] = 5;
for(std::size_t i = 7; gen < N; i += 2) {
bool ok = true;
if(i % 3 == 0 || i % 5 == 0)
continue;
for(std::size_t j = 2; j * j <= i; j++) {
if(i % j == 0) {
ok = false;
break;
}
}
if(ok)
ptab[gen++] = i;
}
return ptab;
}
constexpr std::array<ull, 5761455> ptab = get_ptab<5761455>();
int main(void) {
// Step 1: print all the primes that we've hardcoded already.
for(std::size_t i = 0; i < ptab.size(); i++)
printf("%llu\n", ptab[i]);
// Step 2: starting with ptab.back(), go up until max, checking if
// N is divisible by any of the primes we've hardcoded.
// If it is, skip it. If it isn't, print it.
for(std::size_t i = ptab.back(); i < 10000000000000000; i+=2) {
bool ok = true;
for(std::size_t j = 0; j < ptab.size() && i <= ptab[j]; j++) {
if(i % ptab[j] == 0) {
ok = false;
break;
}
}
if(ok)
printf("%llu\n", i);
}
return 0;
}
```
The performance is yet unknown since the code still compiles on my machine. If you manage to compile, run and time it, let me know how quickly it performs.
[Answer]
# [PARI/GP](http://pari.math.u-bordeaux.fr/), 929MiB on my computer
```
forprime(p=2, 10^16, print(p))
```
The package name for PARI/GP is `pari-gp` on Ubuntu, Debian, Arch Linux and some other distros.
Runs as `gp -qf ./file_name.gp`.
---
# [PARI/GP](http://pari.math.u-bordeaux.fr/) + gp2c, 3.76GiB on my computer
gp2c compiles PARI/GP functions to C codes, where the generated `.so` file can be called in another PARI/GP script.
So there are two files:
`a.gp`:
```
a() = forprime(p=2, 10^16, print(p))
```
`b.gp`:
```
install("a","v","a","./a.gp.so");
a()
```
### How to run
The package name for gp2c is `pari-gp2c` on Ubuntu and Debian, `gp2c` on Arch Linux (AUR).
First compile `a.gp` with gp2c:
```
gp2c a.gp > a.gp.c
```
The command to compile the generated C code is in the first comment of the generated C code. It should look like:
```
cc -c -o a.gp.o -g -O3 -Wall -fomit-frame-pointer -fno-strict-aliasing -fPIC -I"/usr/include/x86_64-linux-gnu" a.gp.c && cc -o a.gp.so -shared -g -O3 -Wall -fomit-frame-pointer -fno-strict-aliasing -fPIC -Wl,-shared -Wl,-z,relro a.gp.o -lc -lm -L/usr/lib/x86_64-linux-gnu -lpari
```
After that you can run `b.gp` and measure the throughput:
```
(timeout 1m gp -qf ./b.gp) | pv > /dev/null
```
---
# C + [PARI/GP](http://pari.math.u-bordeaux.fr/)'s C library, 4.81GiB on my computer
Modified from the C code generated by gp2c.
```
#include <pari/pari.h>
int main()
{
pari_init(8000000, 500000);
forprime_t iter;
u_forprime_init(&iter, 2, 10000000000000000);
long p;
while (p = u_forprime_next(&iter))
printf("%ld\n", p);
}
```
If you are using Ubuntu or Debian, you need to install the package `libpari-dev`. For Arch Linux, `pari-gp` is enough.
Compiles with `gcc -O3 -lpari`.
] |
[Question]
[
## Introduction:
[I collect twisty puzzles.](http://twistypuzzles.com/forum/viewtopic.php?f=14&t=26889) Most twisty puzzles are produced and sold by Chinese companies. Most well-known companies ask permission from puzzle designers to produce their designs and work together towards a product on the market. In this case, puzzle designers are of course very happy and proud that one of their puzzles hit the market.
There are however also Chinese companies which make knock-off puzzles. These knock-offs are either designs used without permission from the original creator, or are downright cheaper lower quality copies of already existing puzzles.
## Challenge:
We're going to determine the originality of numbers that are 'released' in a specific order (from left to right*†*).
Given a list of integers, group and output them by their originality.
*How is the originality of the numbers determined?*
* Is a number an exact duplicate of an earlier number? Group \$X+1\$ (least original), where group \$X+1\$ is trailing, after all the other groups.
* Is a number a duplicate of an earlier number, but its negative instead (i.e. original number was \$n\$, but now \$-n\$; or vice-versa)? Group \$X\$.
* Can the absolute value of the number be formed by concatenating one or more earlier absolute numbers, and is it not part of the earlier mentioned groups \$X+1\$ or \$X\$? Group \$X-N\$, where \$N\$ is the amount of distinct numbers used in the concatenation (and \$N\geq1\$).
* Does the number not fit in any of the groups above, so is completely unique thus far? Group \$1\$ (most original), which is leading before all other groups.
This may sound pretty vague, so here **a step-by-step example**:
Input-list: `[34,9,4,-34,19,-199,34,-213,94,1934499,213,3,21,-2134,44449,44]`
* `34` is the first number, which is always original and in group \$1\$. Output thus far: `[[34]]`
* `9` is also original: `[[34,9]]`
* `4` is also original: `[[34,9,4]]`
* `-34` is the negative of the earlier number `34`, so it's in group \$X\$: `[[34,9,4],[-34]]`
* `19` is original: `[[34,9,4,19],[-34]]`
* `-199` can be formed by the two earlier numbers `19` and `9`, so it's in group \$X-2\$: `[[34,9,4,19],[-199],[-34]]`
* `34` is an exact copy of an earlier number, so it's in group \$X+1\$: `[[34,9,4,19],[-199],[-34],[34]]`
* `-213` is original: `[[34,9,4,19,-213],[-199],[-34],[34]]`
* `94` can be formed by the two earlier numbers `9` and `4`, so it's in group \$X-2\$: `[[34,9,4,19,-213],[-199,94],[-34],[34]]`
* `1934499` can be formed by the four earlier numbers `19`, `34`, `4`, and two times `9`, so it's in group \$X-4\$: `[[34,9,4,19,-213],[19499],[-199,94],[-34],[34]]`
* `213` is the negative of the earlier number `-213`, so it's in group \$X\$: `[[34,9,4,19,-213],[1934499],[-199,94],[-34,213],[34]]`
* `3` is original: `[[34,9,4,19,-213,3],[1934499],[-199,94],[-34,213],[34]]`
* `21` is original: `[[34,9,4,19,-213,3,21],[1934499],[-199,94],[-34,213],[34]]`
* `-2134` can be formed by the two earlier numbers `213` and `4` (or the three earlier numbers `21`, `3`, and `4`, but we always use the least amount of concatenating numbers to determine originality), so it's in group \$X-2\$: `[[34,9,4,19,-213,3,21],[1934499],[-199,94,-2134],[-34,213],[34]]`
* `44449` can be formed by the two earlier numbers four times `4` and `9`, so it's in group \$X-2\$: `[[34,9,4,19,-213,3,21],[1934499],[-199,94,-2134,44449],[-34,213],[34]]`
* `44` can be formed by a single earlier number `4`, repeated two times, so it's in group \$X-1\$: `[[34,9,4,19,-213,3,21],[1934499],[-199,94,-2134,44449],[44],[-34,213],[34]]`
So for input `[34,9,4,-34,19,-199,34,-213,94,1934499,213,3,21,-2134,44449,44]` the output is `[[34,9,4,19,-213,3,21],[1934499],[-199,94,-2134,44449],[44],[-34,213],[34]]`.
## Challenge rules:
* I/O is flexible. You can input as a list/array/stream of integers or strings, input them one by one through STDIN, etc. Output can be a map with the groups as key, a nested list as the example and test cases in this challenge, printed newline separated, etc.
* You are allowed to take the input-list in reversed order (perhaps useful for stack-based languages). *†*In which case the mentioned left-to-right is of course right-to-left.
* As you can see at the example for integer `-2134`, we always group a number that is a concatenation of other numbers with as few as possible (formed by `213` and `4` - two numbers; and not by `21`, `3`, and `4` - three numbers).
* As you can see at the example for integer `1934499`, you can use an earlier number (the `9` in this case) multiple times (similar with `44449` using four `4`s and a `9` in the example). They are only counted once for determining the group however.
* You are not allowed to have empty inner lists in the output for empty groups. So test case `[1,58,85,-8,5,8585,5885,518]` may not result in `[[1,58,85,8,5],[518],[5885],[8585],[],[]]` instead, where the empty groups are \$X\$ and \$X-1\$, and the example above may not result in `[[34,9,4,19,-213,3,21],[1934499],[],[-199,94,-2134,44449],[44],[-34,213],[34]]` instead, where the empty group is \$X-3\$.
* The order of the groups are strict (unless you use a map, since the groups can then be deducted from the keys), but the order of the numbers within a group can be in any order. So the `[34,9,4,19,-213,3,21]` for group \$1\$ in the example above can also be `[21,3,-213,19,4,9,34]` or `[-213,4,34,19,9,21,3]`.
* You are guaranteed that there will never be any numbers that can be formed by more than nine previous numbers. So you will never have any \$X-10\$ groups, and the largest amount of groups possible is 12: \$[1,X-9,X-8,...,X-2,X-1,X,X+1]\$
* You can assume the integers will be 32 bits at max, so within the range `[−2147483648,2147483647]`.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [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.
## Test cases:
```
Input: [34,9,4,-34,19,-199,34,-213,94,1934499,213,3,21,-2134,44449,44]
Output: [[34,9,4,19,-213,3,21],[1934499],[-199,94,-2134,44449],[44],[-34,213],[34]]
Input: [17,21,3,-317,317,2,3,117,14,-4,-232,-43,317]
Output: [[17,21,3,2,117,14,-4],[-317,-232,-43],[317],[3,317]]
Input: [2,4,8,10,12,-12,-102,488,10824]
Output: [[2,4,8,10,12],[10824],[-102,488],[-12]]
Input: [0,100,-100,10000,-100,1001000]
Output: [[0,100],[10000,1001000],[-100],[-100]]
Input: [1,58,85,-8,5,8585,5885,518]
Output: [[1,58,85,-8,5],[518],[5885],[8585]]
Input: [4,-4,44,5,54]
Output: [[4,5],[54],[44],[-4]]
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~565~~ ~~564~~ ~~524~~ ~~523~~ ~~500~~ ~~437~~ ~~399~~ ~~394~~ ~~393~~ ~~389~~ ~~385~~ 372 bytes
Brute-force implementation using `itertools`; not all test-cases run within the 60 second limit on TIO.
[Try it online!](https://tio.run/##ZVLtjpswEPyfp7B0P86QdYWxaSEVT2JZFe1BzxJfZ4jC5eXTXZMjRJXAu56dGa8Xxs/5fejV7db4oWNurv08DO3EXDcOfo4Pl3KsfXeeq9kN/XR4qxv2h7ewRKcDawbPHHM981X/t@YFYQH8IPDCu2rk1e8JpnOHEmOjKDACZVopH@bkjtLGbd3z5V5m1/L19edUmniyYX95d23NFkOka3SyK4tdj@U0ez59G4eRJ1G0oq5BfbmcfD2ffc8K4Q7snieh/YZXdE5bGmOpk1/USRV/t@uFlrA9tYaH7NF7LOXgufgPTVBU9Z@8jar@LQyHusJ704UieywX@OrAxI1rccQcbwJtZG@jd/3MG24kpCBTULgoUKlEZ8ZemMECS4EpC8wQjAFpDFnWHnZqSQZCBhMh8XkyIBkWg3rzEHKF90YahAatIYNMbw64tWAQAKNpERolL5smBQ05yGQ9mt4EoZygPH247GjosdbQ604Oafrki8wkIbeQ7FLabbYBCYbJrhqMt7B3lZDlkGcgcrxknmGW5bTIfDexlZKv95bUHJEwkODZ7gekEj@bUJjRG74hRhlGKVKFA9GKSg//uyZ9EKlTpFIgE1RgShpcg3Z/ptJQ4DAFRlngVIoCFB0lFRQEKa0Roq2ig6hAHxVRXLcu7i7k8EWlMa7qMDk0KfRevv0ACCBKzeGvcPsH "Python 3 – Try It Online")
Thanks to [ArBo](https://codegolf.stackexchange.com/users/82577/arbo) for golfing 101 bytes, to [Galen Ivanov](https://codegolf.stackexchange.com/users/75681/galen-ivanov) for golfing 19 bytes, to [ElPedro](https://codegolf.stackexchange.com/users/56555/elpedro) for golfing 5 bytes, to [movatica](https://codegolf.stackexchange.com/users/86751/movatica) for golfing 17 bytes, to [Black Owl Kai](https://codegolf.stackexchange.com/users/81238/black-owl-kai) for golfing 2 bytes, to [squid](https://codegolf.stackexchange.com/users/85755/squid) for golfing 2 bytes and to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for golfing 1 byte.
```
from itertools import*
w=permutations
def c(l,x):
for i in range(9):
for q in w(map(abs,sum(l,[]))):
for s in w(q[:i+1]*len(x)):
z='';s=[*s]
while x[len(z):]:
z+=str(s.pop(0))
if z==x:return 9-i
return 0
def f(a):
l=[[]for _ in a*6]
for x in a:l[(x in sum(l,[]))*11or(-x in sum(l,[]))*10or any(l)and c(l,str(abs(x)))]+=x,
return[*filter(len,l)]
```
Explanation:
```
from itertools import *
w = permutations # We'll be using this twice
def c # Helper function to calculate which group a number belongs in according to the concatenation rule; returns 0 (original) if none is found
(l, x): # First parameter is the list of groups (a list of lists of numbers), second parameter is the number to investigate
for i in range(9): # There won't be any concatenations of more than 9 elements
for q in w(map(abs,sum(l,[]))): # Flatten l to get a plain list of previous numbers, then generate permutations of their absolute values as lists; for each permutation ...
for s in w(q[:i+1]*len(x)): # ... use only the first i + 1 elements; inflate the list with enough copies to compose the target number and permutate; then try to compose the target number from each permutation:
z = '' # Start with the empty string
s = [*s] # Convert permutation to list
while x[len(z):]: # Keep going until the length of the concatenated string equals the length of the target number
z += str(s.pop(0)) # Concatenate the first element of the current permutation list and remove it
if z == x: # If the target number has been synthesized successfully ...
return 9 - i # stop searching and return the appropriate group
return 0 # If no concatenation has been found, consider the number original
def f(a): # Solution function, takes a list of numbers as argument
l = [[] for _ in a * 6] # Populate the result list with at least 12 empty groups if there is more than one number in the input (we'll be using only the first 12 and removing empty ones later); if there is just one, we'll only need one group in the output
for x in a: # For each number in order:
l[(x in sum(l, [])) * 11 or (-x in sum(l, [])) * 10 or any(l) and c(l, str(abs(x)))] += x, # If x is not the first number, attempt concatenation (if not, c(l, str(abs(x))) would crash due to l not containing any non-empty sublists; use absolute value of the number under investigation; convert to string since we'll be needing the number of digits and comparing it to a string later); if -x has already been seen, put it in Group X; if x has already been seen, put it in Group X + 1
return [* filter(len, l)] # Remove empty lists and return the result
```
# [Python 2](https://docs.python.org/2/), ~~406~~ ~~379~~ ~~374~~ ~~373~~ ~~372~~ ~~368~~ 355 bytes
Same approach, but shorter due to some golfing tricks Python 3 doesn't support any more. Thanks to [ArBo](https://codegolf.stackexchange.com/users/82577/arbo) for the backport and for golfing 28 bytes, to [ElPedro](https://codegolf.stackexchange.com/users/56555/elpedro) for golfing 5 bytes, to [movatica](https://codegolf.stackexchange.com/users/86751/movatica) for golfing 17 bytes, and to [squid](https://codegolf.stackexchange.com/users/85755/squid) for golfing 1 more byte.
```
from itertools import*
w=permutations
def c(l,x):
for i in range(9):
for q in w(map(abs,sum(l,[]))):
for s in map(list,w(q[:i+1]*len(x))):
z=''
while x[len(z):]:
z+=`s.pop(0)`
if z==x:return 9-i
return 0
def f(a):
l=[[]for _ in a*6]
for x in a:l[(x in sum(l,[]))*11or(-x in sum(l,[]))*10or any(l)and c(l,`abs(x)`)]+=x,
return filter(len,l)
```
[Try it online!](https://tio.run/##ZVLtjpswEPx9eQpL9@NMslQYmxYi8SQINbQHPUt8HRCFy8unsyYlRJXAu56dGa8X@q/po2vD260aukbYqRymrqtHYZu@G6b97pL25dCcp2KyXTvu3stK/JY1zd5xJ6puEFbYVgxF@6eUCWMO/GTwIpuil8WvkcZzA0mWex4YL0wYmcDl2o4TXeRndrQHle/rspXzQhPX9O0N4fJh61LMGZeu3jFH6eV6SE/jt77rZeCdsLcV2Ol8HMrpPLQi8e1O3PPAtVzJgpur0yzL@fyffH6x/54vl5jd9lhn0mWPfvdKdYP0/0MDiIr2S9Ze0b67gZxwUbR@8vJDOtN6fGVrjFSieaq9Wz/YdpKVzBSFpELSWDTpUMFUiFeRoSBCEjonkTGMAJoAK893G7ViA185E1/heTJgGYpOvXr4aoG3RoZ8Q8ZQRJFZHbDNKQNAmeHFN5C8rpqQDMWkguVofgNAMUNx@HDZ0OCx1OB1J7s0fPIFMwjYzSWblHerrUOcYbCpOuM1bF0VRTHFEfkxLhlHyKKYFxVvJrZQ4uXeiptjEgILnu1@UKjw2XyNjF/3DRGVG6UfagzEaC49/O@a8EHkTkHlwCZQIGUNVqfdnqkNJRimj6gSTCVJSPNRSlPCkDYGEG81H8QF/qhAsa5d3F3Y4R@Vx7io3eRgkpitfP0BAADl5vAr3P4C "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~235~~ ~~234~~ ~~232~~ ~~246~~ ~~245~~ ~~244~~ ~~241~~ ~~240~~ ~~238~~ ~~237~~ 236 bytes
```
from itertools import*
s=[];r=map(list,[s]*12)
for e in input():r[-(e in s)or max([10*(-e in s)]+[10-len(set(p[:i]))for p in permutations(`abs(x)`for x in s*11)for i in range(len(p))if''.join(p[:i])==`e`])]+=e,;s+=e,
print filter(len,r)
```
[Try it online!](https://tio.run/##LZDRasUgDIav16eQ3hzt0sN6aKH04JOIYNelm8OqqAe6p@@0FEIg@ZMv/PF/6cfZx7G4LySc1HV9rMFtRCcMyTkTid68C6mpIhfyGfg2e2p0TCCibLoHq1YXCBJtc/hXomwKoqVnI7IsbfNORffR0PbqyfdctgYtjZioF5OWjBWIL7rHsL3SnLSzkar5M9KdqaLu53bzOEd1KcJsv5EWkGdMr7fb/ddpexE5V6hkPsYRnrHkygdtE1m1ydbKGgR2ZL@nARNTQYoe2h76HgYYeglEdDCMMA7QjjDIqXrDHRdafnUP6M28IK0v2zWoDFGMHf8 "Python 2 – Try It Online")
-1 byte thanks to Squid's comment on the other Python answer
This answer has *no* hopes of solving any but the most trivial of test cases. In the TIO link, `s*11` has been replaced by `s*2`, sacrificing correctness in some cases for fast**er** execution time, but as far as I can see, the version in this post always yields the correct answer, in theory.
# Explanation
```
from itertools import* # So that we can abuse permutations
s=[]; # s will hold the already classified numbers
r=map(list,[s]*12) # r will hold these too, but in the form of
# a nested list, sorted by originality
for e in input(): # Here comes the big one; iterate over the input
r[-(e in s)or # If e has already passed, it is not original
max([10*(-e in s)]+ # Else, we count 10 - the number of seen elements
# needed to make this one, or 0 if it's new,
# or 10 if its inverse has already passed
[10-len(set(p[:i])) # The number of distinct elements in...
for p in permutations( # for each permutation of the seen elements,
`abs(x)`for x in s*11)
# with values occuring up to 10 times (to
# account for 1111111111, for example;
# we need 11 here and not 10, because
# p[:i] doesn't include i)...
for i in range(len(p)) # each prefix...
if''.join(p[:i]) # only if its concatenation is equal to
==`e`])] # the current element
+=e,;s+=e, # Append the element to the relevant lists
print filter(len,r) # And finally, print the non-empty result lists
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~43~~ ~~41~~ ~~38~~ ~~35~~ 27 bytes
```
.¡IN£UÄ.œεgΘ>XÄyÙå;P*}àXyå+
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f79BCT79Di0MPt@gdnXxua/q5GXYRh1sqD888vNQ6QKv28IKIysNLtf//jzY20bHUMdHRBdKGljq6hpaWOkCmrpGhsY4lSMjYxAQoBOIaA0mwhImOCRAAdZnEAgA)
Explanation:
```
.¡ # group by:
IN£ # first N elements of the input, N being the iteration count
U # store this as X
Ä # absolute value of the current number
.œ # partitions (eg 449 => [[4, 4, 9], [44, 9], [4, 49], [449]])
ε } # map each partition to:
gΘ> # 2 if length = 1, 1 otherwise
yÙ # for each unique element in the current partition:
XÄ å # 1 if it's in the absolute value of X, 0 otherwise
; # divide all by 2
P* # product of all these numbers
à # take the maximum
Xyå+ # add 1 if X contains the current number
```
Since group numbers aren't part of the output, we're free to use any numbers we want, as long as the order is correct. This uses 0 for original numbers, 2^-N for group X-N, 1 for group X, 2 for group X+1.
[Answer]
# Python 2, 195 bytes
The slowest test case can't complete [on TIO](https://tio.run/##NY3BioMwFEXX5iuyGHmJSUQzLmydzI/UQtOS4gON8kwpA/13ZywM3HvhnM1dftIwR7ttOC0zJU6BeXcS8txNzheHA7vPxCPHPcsjCXlkGbqqIwdGAMueA46B41ddfVMo1@DpNggC0V9L1V9lqaBARQqk@gAN@WryFXLhdZTyiMrVHSkHr74HdcELy6ZT0xbi/efl69MWwvxD3Rg8Kxd15/dlC2FM/I5jCiTGEPUkt83qRre6rnRttXm3@lPtrlrb/AI), but it only takes about 10 seconds on my machine.
```
import re
a=[()];m=a*99
for n in input():
i=0;r='-('
while i<10>re.search(r'(\b.+\b).+'*i+r+')+$','%s-%%s'%a%n):i+=1;r+='|\\'+`i`
m[48*(n in a)|32*(-n in a)|14-i]+=n,;a+=n,
print filter(len,m)
```
It can be shortened by 2 bytes on LP64 Python builds by replacing `'%s-%%s'%a%n` with ``a`+'-'+`n``.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~36~~ 33 bytes
```
ADṪŒṖfƑƇƊQ€Ẉ.*;,AṪe$€SƲṀµƤż⁸ṢZ¹ƙ/
```
[Try it online!](https://tio.run/##y0rNyan8/9/R5eHOVUcnPdw5Le3YxGPtx7oCHzWtebirQ0/LWscRKJWqAuQHH9v0cGfDoa3Hlhzd86hxx8Odi6IO7Tw2U///4XaQ1hn//0cbm@hY6pjo6AJpQ0sdXUNLSx0gU9fI0FjHEiRkbGICFAJxjYEkWMJExwQIgLpMYgE "Jelly – Try It Online")
I’m sure this can be golfed more. Some inspiration taken from [Grimy’s 05AB1E answer](https://codegolf.stackexchange.com/a/186413/42248), so be sure to upvote that one too!
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~211~~ 205 bytes
```
a=>a.map(s=>(c[q=(G=(n,r=[],A=Math.abs,N=""+A(s))=>N[L="length"]<n[L]?0:N!=n?Math.max(0,...c.flat().map(x=>G(n+A(x),[...r,x]))):1/r?s-r?11:12:12+~new Set(r).size)``]=c[q]||[]).push(s),c=[])&&c.filter(x=>x)
```
[Try it online!](https://tio.run/##fVBNT4MwGL77K5TD0mYvlULJyrSQnXaZu3gkJKvIPgwrk6ISY/zr@JaTMcSm7/fTp0/7ot@1LdvTpfNN81wNezVolWp21hdiVUrK/FWRtSIGWpUXsFIPujsy/WRhqzxvviKWUpVu843y6socuqNX3Jt8U2TBcnujTDbCz7onATDGSravdUfoSN@rdE0MUvQUchy20BeU0iW/bTPrtxnnSx7inn@b6uP6sepIS5k9fVZ0tysUCiu@vvKCssubPaIMKFEgnc3wjlPdVa3j7@lwVzbGNnXF6uZA9iSPBCQgwMfIE/B5kgCmfsgjSFwrEgJbrozQjwMBAheeEqjv6i8hXzhchIyYOQux4Bg50jrmKMQYudHU8RDFSOABcISNFmBLupYMJy9EaBA43Jj8Sl01qRBiCTIGX0KMEbNYOsflFHpULQRC4@n3JviB@Dr8JbTF/5DROcjwAw "JavaScript (Node.js) – Try It Online")
Using the assumption that there are at most 12 groups.
# [JavaScript (Node.js)](https://nodejs.org), ~~267~~ ~~226~~ ~~221~~ ~~218~~ 211 bytes
```
a=>a.map(s=>(c[q=(G=(n,r=[],A=Math.abs,N=""+A(s))=>N[L]<n[L]?0:N!=n?Math.max(0,...c.flat().map(x=>G(n+A(x),[...r,x]))):1/r?l-(s!=+r):l+~new Set(r).size)``]=c[q]||[]).push(s),c=[],l=a[L="length"])&&c.filter(x=>x)
```
[Try it online!](https://tio.run/##fVA7T8MwEN75FTRDZasXEyeO6hScqlOX0oUxilQT0gdKnRIHiFDFXw/nTAhFWLr3d3ff@VV/aFs0p0vrm/ql7Peq1yrV7KwvxKqUFNmbImtFDDQqy2GlHnV7ZPrZwlZ53mxFLKUq3Wab/MGgWgaL7USZ5YA6644EwBgr2L7SLaHD1E6la2Kws6OQYbGBLqeULvhds6x8Yidq1tBFNfs25eftU9mShjJ7@irpbpcrpJNfr1lO2eXdHnE5FI5WpXS2UV5VmkN79HI6neLKU9WWjVvX0f6@qI2tq5JV9YHsSRYJSECAj5Yn4PMkAXT9kEeQuFQkBKZcGKEeCgIEPuwSSPfm70A@d7gIJ6LnJMSAo@U41k2OQrSRK421h0hGAg@AI2yQAFPSpWQ4uhChQeBwg/PLddEoQ4glyBh8CTFa9GLpFJdj6IG1EAiNx@9N8APxOvwllPn/kEE5SP8D "JavaScript (Node.js) – Try It Online")
```
a=>a.map( // Iterate through all items:
s=>(c[q=(
G=( // Helper function to calculate index (=GroupNo-1):
n, // Stores different (repeatable) permutations
r=[], // Stores the elements used
A=Math.abs,
N=""+A(s)) // Stores the string version of the absolute value
=>
N[L="length"]<n[L]? // If n is longer then N:
0 // 0 (Group 1) - no permutation found to equal the string
:N!=n? // Else if N!=n:
Math.max(0,...c.flat().map( // Return max of the results of the next recursion
x=>G(n+A(x),[...r,x]) // for each of the elements in c
))
:1/r? // Else if r has only 1 item: (=+s/-s)
s-r?11:12 // Return l-1 (Group X) if r=-s, and l (Group X+1) if r=s
:12+~new Set(r).size // Else: return l-r.size-1 (Group X-r.size)
)``]=c[q]||[]).push(s), // Push the element into the corresponding array
c=[] // Initialize an empty array
)&&c.filter(x=>x) // Filter out all empty groups
```
... or 193 bytes if returning a dictionary is okay:
```
a=>a.map(c=s=>(c[q=(G=(n,r=[],A=Math.abs,N=""+A(s))=>N[L="length"]<n[L]?-1/0:N!=n?Math.max(...d.map(x=>G(n+A(x),[...r,x]))):1/r?+!(s-r):-new Set(r).size)``]=c[q]||[]).push(s)&d.push(s),d=[])&&c
```
[Try it online!](https://tio.run/##fVBNb4MwDL3vV6wcqkR1KIGghm6h6qmXrpcdEVIzoB9TGzrCNjT1v3cO0qRpQotk@9l@dl7yqj@0LZrjpWWmLqvbTt20SrV/1hdSKKtSUmRviqwUMdCoLIeletLtwdcvFjbK8yZLYilV6SZbK@9UmX178PJHk63zBePTYL4ZKbPoJ866I77vl/3qTqUrYnC4o5BhtYEup5TO@bRZTEbEsobOmak@75@rljTUt8evim63uUI1@fWa5dS/vNsD3j0ufxCUqI@Ox8XtoaiNrU@Vf6r3ZEeySEACAhhGngDjSQIIWcgjSFwpEgJLLo3Q9w0BAg9OCdR193chnzlehBsROQsx4Rg5rnWboxBj5FpD4yGKkcAD4EjrLcCSdCUZDl6I1CBwvB78gi4bVAixBBkDkxBjRBRL57gcYveqhUBqPPzeBD8QX4e/hDb7n9I7R7l9Aw "JavaScript (Node.js) – Try It Online")
In this case, key `-Infinity` means Group 1 and other keys means Group `X+key`.
] |
[Question]
[
## Introduction / Background
In a [recent discussion](https://chat.stackexchange.com/transcript/message/40318730#40318730) in [the crypto chat](https://chat.stackexchange.com/rooms/784/the-side-channel) I was challenged to discuss / help with the [Fermat primality test](https://en.wikipedia.org/wiki/Fermat_primality_test) and Carmichael numbers. This test is based on the premise that `a^(p-1) mod p==1` will always hold for primes `p`, but not always for composites. Now a carmichael number is essentially the Fermat's test worst enemy: A number for which you *have to* pick `a` to be not co-prime with `p` to get `a^(p-1) mod p!=1`. Now if `a` is not co-prime, you essentially found a non-trivial factor of `p` and as we all know factoring can be quite hard. Especially if all factors are sufficiently large. You may now realize why the Fermat test isn't used in practice as often (well there are better algorithms), it's because there are numbers for which you as a defender (in security terms) would have to do a similar amount of work as an attacker (namely factor the number).
So now that we know *why* these numbers are somewhat fascinating, we're gonna generate them in the shortest way possible, so we can just memorize the generating code if we ever need any!
[Carmichael numbers](https://en.wikipedia.org/wiki/Carmichael_number) are also known as [A002997 on OEIS](https://oeis.org/A002997).
There is a [related challenge](https://codegolf.stackexchange.com/q/892/55329) already, but entries from there are not competitive here because they are optimized for speed as opposed to size. The same argument holds for the inverse direction, entries here are likely to make trade-offs against speed in favor of size.
## Specification
### Input
This is a standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge, so you take a positive or non-negative integer `n` as input. `n` may be 0- or 1-indexed as you prefer (please indicate).
### Output
Your output will either be the `n`-th carmichael number or the first `n` carmichael numbers, as you prefer (please indicate).
### Specification
An integer `x` is a Carmichael number if and only if `x` is composite and for all integers `y` with `gcd(x,y)=1`, it holds that `y^(x-1) mod x==1`.
### Who wins?
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in byte wins!
Standard IO and loophole rules apply.
### Test Cases
The first few carmichael numbers are:
```
561,1105,1729,2465,2821,6601,8911,10585,15841,
29341,41041,46657,52633,62745,63973,75361,101101,
115921,126217,162401,172081,188461,252601,278545,
294409,314821,334153,340561,399001,410041,449065,
488881,512461
```
[Answer]
# Mathematica, 71 bytes
```
(t=s=1;While[t<=#,If[++s~Mod~CarmichaelLambda@s==1&&!PrimeQ@s,t++]];s)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X6PEttjW0Do8IzMnNbrExlZZxzMtWlu7uM43P6XOObEoNzM5IzE1xycxNykl0aHY1tZQTU0xoCgzNzXQoVinRFs7Nta6WFPtP1Aor0TBIT3a0CD2/38A "Wolfram Language (Mathematica) – Try It Online")
`50->1461241` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X6PEttjW0Do8IzMnNbrExlZZxzMtWlu7uM43P6XOObEoNzM5IzE1xycxNykl0aHY1tZQTU0xoCgzNzXQoVinRFs7Nta6WFPtP1Aor0TBIT3a1CD2/38A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 92 bytes
```
f=lambda j,n=1:j and f(j-([(k/n)**~-n%n for k in range(n*n)if k/n*k%n==1]<[1]*~-n),n+1)or~-n
```
[Try it online!](https://tio.run/##FcwxDoQgEEbhq0xjwrAaM5ZmOYmxYKMosPtjiI3NXh2xe8WXd1znnjCU4szX/j6LpdDCyBjIYiGnQqcmFXuw1v8ODcilTJE8KFtsq4IGe0dV6NjAGJnfk8yP5RYv4ZRrliN7nPUmXG4 "Python 2 – Try It Online")
1-indexed and slow as molasses.
In the list comprehension, I use [Dennis’s method for generating all integers coprime to `n`](https://codegolf.stackexchange.com/a/104681/3852) (n’s *totatives*), and then I compute `x**~-n%n` for all of them. Let’s call this list `L`.
To detect a Carmichael number, I compare this list *lexicographically* to a list consisting of `n-1` ones. Why does this work?
Each element of `L` is a positive integer: `(k/n)` is coprime to `n`, so `(k/n)**~-n` also is, so `(k/n)**~-n%n > 0`. Thus, the only possible values of `L` that are lexicographically *less than* `[1]*(n-1)` are the ones consisting entirely of *less than* `n-1` ones. (`L` can’t contain *more* than `n-1` values, as `n` can’t have more than `n-1` totatives! So comparisons like `[1,1,1,1,3] < [1,1,1,1]` are out.)
Checking that there are less than `n-1` entries in `L` ensures that `n` is composite. (Having `n-1` totatives is an equivalent condition to primality.) And then, the condition for being a Carmichael number is exactly that every element of `L` equals `1`. So this lexicographic comparison detects exactly the `L`s we’re interested in.
Mr. Xcoder saved a byte by switching to recursive lambda form: `j` counts down every time we hit a Carmichael number, and `n` counts up every time we recurse. So once `j` hits zero, `n-1` equals the `original_value_of_j`’th Carmichael number.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte thanks to [miles](https://codegolf.stackexchange.com/users/6710/miles) & [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) (use of Carmichael function atom & a golf thereof)
```
%Æc’=ÆP
⁹Ç#
```
A monadic link taking `n` and returning a list of the first `n` Carmichael numbers.
**[Try it online!](https://tio.run/##y0rNyan8/1/1cFvyo4aZjxr3HG4L4HrUuPNwu/L///8NDQA "Jelly – Try It Online")**
### How?
Much like the previous (below) except that there is a built-in for the Carmichael function - which yields the smallest power such that the input raised to that power is congruent to one modulo that power for all integers co-prime to that integer. Thus we may exclude the false-positives (primes) in less bytes and have faster code!
```
%Æc’⁼ÆP - isCarmichael: number, n (any integer)
Æc - Carmicael function of n
% - n modulo that
’ - decremented (0 for Carmichael numbers and primes)
ÆP - is n prime? (1 for primes 0 otherwise)
⁼ - equal?
⁹Ç# - Main link: number, n
# - count up finding the first n values satisfying:
Ç - ...condition: call the last link as a monad
⁹ - ...starting with a value of: literal 256
```
---
Previous **12 bytes**:
```
Ṗ*%⁼Ṗ_ÆP
⁹Ç#
```
[Try it online!](https://tio.run/##y0rNyan8///hzmlaqo8a9wDp@MNtAVyPGnceblf@//@/EQA "Jelly – Try It Online") (Yeah, it times out for `n=3`).
### How?
A number, `c`, is a Carmichael number if it is composite and it is true that any integer, `x`, raised to `c` is congruent to `x` modulo `c`.
We only need to check this for positive `x` up to `x=c` itself.
Note also that at `x=c` the check is whether `x` raised to the power of `x` is congruent to `x` modulo `x`, which is true - so we don't need to check this (this makes for shorter code).
```
Ṗ*%⁼Ṗ_ÆP - Link 1, isCarmichaelNumber: integer c (greater than 1)
Ṗ - pop c (uses the implicit range(c)) = [1, 2, 3, ..., c-1]
* - raise to the power of c (vectorises) = [1^c, 2^c, 3^c, ..., (c-1)^c]
% - modulo by c (vectorises) = [1^c%c, 2^c%c, 3^c%c, ..., (c-1)^c%c]
Ṗ - pop c = [1, 2, 3, ..., c-1]
⁼ - equal? (non-vectorising) = 1 if so, 0 if not
ÆP - isPrime?(c) = 1 if so, 0 if not
_ - subtract = 1 if Carmichael 0 if not
- (Note the caveat that c must be an integer greater than 1, this is because
- popping 1 yields [] thus the equality check will hold; same for 0,-1,...)
⁹Ç# - Main link: number, n
# - count up finding the first n values satisfying:
Ç - ...condition: call the last link as a monad
⁹ - ...starting with a value of: literal 256
```
[Answer]
# [RegexMathEngine](https://github.com/Davidebyzero/RegexMathEngine/) (ECMAScript+`(?^=)`), 59 bytes
```
^((?=(x(x+?))\2*$)(?^=x\3*$)(?=(x+)(\4+$))\5(?!\2*$)){2,}x$
```
[Try it on replit.com!](https://replit.com/@Davidebyzero/regex-Carmichael-numbers-sequence-ECMAScript-lookinto) - [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") harness ([RegexMathEngine](https://github.com/Davidebyzero/RegexMathEngine/))
A regex takes a number as input in unary, as a string of `x` characters whose length represents the number. Its output is a match iff the number is a Carmichael number.
This is launched in RegexMathEngine's sequence mode to satisfy the challenge's specifications, outputting the first `n` Carmichael numbers, where `n` can be given either as a command-line argument or through standard input.
Korselt's criterion is used to identify Carmichael numbers.
```
^ # tail = N = input number
# Assert that N has at least 2 unique prime factors, and that each of its prime
# factors P are of exactly single multiplicity (i.e. that N is square-free), and
# for each, P-1 divides N-1.
(
(?=(x(x+?))\2*$) # \2 = smallest prime factor of tail; \3 = \2-1
(?^=x\3*$) # Lookinto – Assert \3 divides N-1
(?=(x+)(\4+$)) # \4 = tail / \2 (implicitly); \5 = tool to make tail = \4
\5 # tail = \4
(?!\2*$) # Assert that tail is no longer divisible by \2, i.e. that
# that prime factor was of exactly single multiplicity.
){2,} # Iterate the above at least 2 times, with no maximum
x$ # Assert tail == 1
```
# [Regex](https://github.com/Davidebyzero/RegexMathEngine/) (ECMAScript 2018 or better), 59 bytes
```
^((?=(x(x+?))\2*$)(?=(x+)(\4+$)(?<=^\3*x))\5(?!\2*$)){2,}x$
```
A port of the lookinto version, to variable-length lookbehind.
[decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") harnesses:
[Try it online!](https://tio.run/##TY89T8MwEIb3/gqokHxHasv5VNrgZmJgYYCRgrBSNzUKTrBdGqn0txe3EhLLo@f8ns/nD/ktXWP14Knp1@rkBK@seFLt/TjAs7fatMzK/fvpDaAWMMIY1Yir5PYGL3WEsMqic3En3lbp7RjCHOrrSwcektlxvDm9M9fpRkE8ozFiZdXXTlsFxCq57rRRBFkT3KsH45XdyNB60GbY@cVg@0Y5x5xfa3NE1hsglxuzTiwPreiYGzrtgVCCld4AGNGyTpnWb3GZ/Pxo9ygfQYtBWneeDu0Lf0X8C9T/wCzjOl6cY/Rb2@@nD@Zbdnp9ZaVp1eJqGnXVprdQ6TuhKh1FGB6cjlNm1RCWB43sU/pmCzZ8/N/i/c6zvdVeAbiarAxZEIKRxsqJuDoe8cRpyjmfFHnJaVEkfFLOOaflPFjMz4eB8@B5mRY0MCsnyTwNHhg8i3ma08Asn2RFkXMaWOS/ "JavaScript (Node.js) – Try It Online") - ECMAScript 2018
[Try it online!](https://tio.run/##LY7NboMwEITvfgrXysEOGK1tTCDUyoPkR4oSkiBRBxkOJFWfna5pL6uZnfns7V/j4@nN3H71zzDS4TWkobk3U02DC4yx@cT5zvGJT8lOiINer8TiE8EPeRLNpzsdzHrC0PLdx9IQ3zr9mVYz8nu1lepY07cDcnsG2tHWx1@yYby2fkto57ps6Lt25EwyQWgs@VgKZ39veOtH3u3hKNI/hY@JRAkEaXujy6nZ0JzD5cFDStnE1n4JY/re0j5ETMTF26n63/u08VfHmJhBFhaIggqkUhrVRqPaGEt0XoDU@QaILhUqMEAKi72iUEDKCqwsK2WRtSUigBFRtjSFxJmXRFfGVBJnbn4B "Python 3 – Try It Online") - Python (`import [regex](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)`)
# [Regex](https://github.com/Davidebyzero/RegexMathEngine/) (ECMAScript 2018 or better / Java), 66 bytes
```
^((?=(x(x+?))\2*$)(?<=(?=x\3*$)^.*)(?=(x+)(\4+$))\5(?!\2*$)){2,}x$
```
Java's lookbehind is restricted, but is able to do a simple return to start as is done here.
[decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") harnesses:
[Try it online!](https://tio.run/##TY9Pb@IwEMXvfAoWIXmmwZbzV4HU5LSHXnrYPS6tsIIJrlIntU2JRPns1CCt1MvTb@a9GY/f5Kd0jdWDp6bfqasTvLLij2p/jwP89Vablll52l5fAWoBI4xRjbhJHuYI9aMIvXGThuKVPeA9ECFssmgeMjnUv@5BPCeLyzi/bpnrdKMgXtAYsbLq46itAmKV3HXaKIKsCezVk/HK7mWInrUZjn412L5RzjHnd9pckPUGyH1i0Yn1uRUdc0OnPRBKsNJ7ACNa1inT@gOuk68v7Z7lM2gxSOtu26H9x18Q/xvqp2HWcR2vbjb6g@1PsyfzKTu9m1ppWrWazqKu2vcWKv0oVKWjCMODs3HGrBrC8aCRvUvfHMCGj/84vD96drLaKwBXk40hK0Iw0lg5EVeXC145TTnnkyIvOS2KhE/KJee0XAaK@a0ZdBk4L9OCBs3KSbJMAwcNnMU8zWnQLJ9kRZFzGrTIvwE "JavaScript (Node.js) – Try It Online") - ECMAScript 2018
**[Try it online!](https://tio.run/##bVJdb9owFH3Pr7hFnbCBpE4gFJZGaJs2adK6Te0jUMkEB9wGJ7NNCUX8dnYTso9KzUN8P46PfY7vI3/m7uPy6SQ3Ra4tPGLuydzrRPB/ZWtl9mZNi5UoseMU20UmE0gybgzccqngAE3NWG5xec7lEjbYIfdWS7UCrldmOqdg1zrfGfhcJqKwMsedDsAXmQlIYyV2dUhaXpIvhYf9Fo0@btNUaLG8E3wpNCxq2Osi@bOzSVNKo@Zc07PRbl3xE2LiBWrgy29SCULpRay2WUZlSownfm15ZkjrqtPptCg9vIaeGQixbxIckMH@ZUCCK2RYIO4pMt24PVPtarXR8Vw7/uTWCq1Ax02EajdFdYChEbqxyPNMcAUvcYqMIoL7hCuF0qUqthZiqNQ2NXK/N1ZsPKloBI3OGuatufkuSovXrC0GaAzJ8O7IcQYpRDQSm/50Dhm2K5Rnikxa0nLxERBvQTHsfFUWx0B7BddGYEKyKZvTHij/zaaXCbWy65sAJlAh4T0u/hwZkzXX03nZ6Kkz5c8j@KA13xsvlVlGyl67bNemAKS5rrThNWLFIlA3sfJx6XZR4C23yRod2iCb9jbnjNSTq3DAPyH5eWK8neYFaY5I8mL/I73jaiXwJNZTlFZKUyAbPF4t0bvqbV9oY3KOju20tIJUj0qjl9jqbfU@/9oFemhT0npnWmgJjY7V51RTdXogZBKTkpTdCaWzoHNJyeQmxlo562Py4HVoDehSMht0LxETkslFDaSHoHcsL0/VbJ2YOwyZ47Mxc30/wOg6wOi6HzrBYMjcYHDNnGDkY8T6zBmGiBsOfeaMxix0R2M/xL3hCLcwbDl@OOoPXfwPRk4w7vfHLv4H/d8 "Java (JDK) – Try It Online") - Java**
[Try it online!](https://tio.run/##LY7dboMwDIXv8xRZ1IukEOQkhPKziAfpj1S1tEViKQpc0E57dmbYbqxjn@/Y7l/j4@nN3H71zzDS4TXEobk3U0WDC4yx@cR57fjEp6gW4qC3G8HrT4ez6WCwOSVbsQKR4Ic02iBjef2xguJbxz/TZsY1e1VKdazo2wG5PQPtaOuXY8kwXltfEtq5Lhn6rh05k0wQukB@gcLZ3xve@pF3eziK@E/hMhEpgUHa3uj6cTI053B58BBTNrGtX83FfZe0D0tMLIO3U9V/7@PGXx1jYgaZWSAKCpBKaVQ7jWpnLNFpBlKnOyA6V6jAAMksclmmgOQFWJkXymLW5hgBtIiyuckk1jQnujCmkFhT8ws "Python 3 – Try It Online") - Python (`import [regex](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)`)
[Try it online!](https://tio.run/##RZDdioMwFITvfQpXDphoU@JPResGC3u9T1AtiJuugWwUTalUfHY3dll6M8x8DMPh9N2dD2PLpVxhYOeBf/OpOh4Vv6OTu14QKhia0OQXGJehBxgV78ywqYxMuOw9/Cz4GJWxD6ZzQMXbs4jncLdMsLqnnfPR/fRC8i8H5/BgNL92A6@bFoG0hbJBqP6m8Qw1A0nGXgrtECcXVwT1vuluShOp7XAr@AzqM60WM4BAsbNQunqSHBSR/D8HW/Z9PG8bw/6z1k3LR@ROrgcK/@EHnu@D0Jy03agXc1aQv7JNVGdeIIXiNqhlWVZKIkqplRxSSpIkpFaaUUrSzLiAbtBoZvwhjRJiNE6tMIuMNxqnvw "PowerShell – Try It Online") - .NET
# [Regex](https://github.com/Davidebyzero/RegexMathEngine/) (ECMAScript), ~~86~~ ~~89~~ 85 bytes
*-4 bytes by changing `(?=A)(?!B)` to `(?!B)A`; on some regex engines this results in a slowdown, but RegexMathEngine [optimizes this](https://github.com/Davidebyzero/RegexMathEngine/commit/ac359757958559b34f693c12a02dd323a78d92c3) so there is no difference in speed*
`^(?!(x(x+))(?!\2*$)\1*(?!(xx+)\3+$)\1$)((?=(xx+?)\5*$)(?=(x+)(\6+$))\7(?!\5*$)){2,}x$`
[Try it on replit.com!](https://replit.com/@Davidebyzero/regex-Carmichael-numbers-sequence) - [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") harness ([RegexMathEngine](https://github.com/Davidebyzero/RegexMathEngine/), ECMAScript mode)
[decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") harnesses (ECMAScript):
[Try it online!](https://tio.run/##TY/NbsIwEITvPAVECHYJCXGgRMI1nHrgwqE9Nq1kgQlujYlsAyk/z546SJV6We18M6vVfPETt2sjSxfZUm6E2R/0t/ipDdPi3H4VxUtVAlzYfDSoP2HRgQqqENFveTroYk4GD@hZPg4b3UWABWvIAvMnH3moECGfeh/zrDltOF7T4b3q1oPRBWN3eHNG6gIwtkquBUyH0QSRWpbQ804qAaCYEXyjpBaA2GH6qBReC6ZiWyrpoB/1kcotgGZFrIQu3A7n6e0m7YqvQLKSGyuW2kHxnnwg/hniv6HnZEFmjY1uZw7nYKlPXMlN23BdiFk7CBXdHgxQ@cwElWGI/mFQBbERpeAOJMZ77tY7ML6d7fVKX8lB04LQ8uisMz5C7/c6iaZJ0iIkSSLiZ4tkaRaRbExa6WQ6jvzIfgE "JavaScript (SpiderMonkey) – Try It Online") (slow 85 byte version)
[Try it online!](https://tio.run/##TY/NbsIwEITvPAUgRHcTEpwAKZAaTj1w4dAem1aywAS3xkS2gZSfZ6d2pUq9jGbn29VqPtmRmZUWlY1MJdZc7/bqi3/fNVX81Hzh5XNdAZzprB/cP2DeghrqENG5Ig06WCQBzGmRdPCXOVQMwo7jLvXjHItR4CH1Z1BkHhaP/tzneEl7t7pzD/pnjO3@1WqhSsDYSLHikPWiIWJuKMlPWyE5gKSas7UUigNii6qDlHgpqYxNJYWFh@gBc7EBULSMJVel3eIsvV6FWbIlCFoxbfhCWSjfyDviH@D/gZol82TqMdqt3p/aC3VkUqybmqmST5vtUOabvYZcPFGeizBE97Bdt2PNK84sCIx3zK62oF070@1WrpIF3yLJq4M1VruV/Ha7k2hACGlkozGJsiwljfGEkGg8cS4ho/Ew8po1EmdJ5DX9AQ "JavaScript (SpiderMonkey) – Try It Online") (faster 89 byte version)
```
^ # tail = N = input number
(?! # Negative lookahead – assert that neither of the
# following two alternatives can match:
# Cycle through factors \1, with \2 = \1-1, for which \2 does not divide N-1
(x(x+)) # \1 = conjectured factor of N; \2 = \1-1
(?!\2*$) # Assert N-1 is not divisible by \2
\1* # Assert N is divisible by \1 - works along with the
# subsequent "\1$"; tail = \1
# If the factor \1, which already passed the above tests, is prime, then
# fail the outside negative lookahead, because N is not a Carmichael number.
(?!(xx+)\3+$)
\1$
)
# Assert that N has at least 2 unique prime factors, and that all of its prime
# factors are of exactly single multiplicity (i.e. that N is square-free).
(
(?=(xx+?)\5*$) # \5 = smallest prime factor of tail
(?=(x+)(\6+$)) # \6 = tail / \5 (implicitly); \7 = tool to make tail = \6
\7 # tail = \6
(?!\5*$) # Assert that tail is no longer divisible by \5, i.e. that
# that prime factor was of exactly single multiplicity.
){2,}
x$
```
The main magic of this regex is in the part that asserts that all of the prime factors of N are of exactly single multiplicity. It is the same trick as used by my [Match strings whose length is a fourth power](https://codegolf.stackexchange.com/questions/19262/match-strings-whose-length-is-a-fourth-power/21951#21951) and [Find the Smoothest Number](https://codegolf.stackexchange.com/questions/36384/find-the-smoothest-number/178889#178889) regexes: repeated implicit division by the smallest prime factor.
# Regex (ECMAScript), ~~97~~ ~~93~~ ~~92~~ 90 bytes
*-4 bytes by changing* `(?=A)(?!B)` *to* `(?!B)A`; *on some regex engines this results in a slowdown*
*-1 byte by using* `\b` *to streamline searching through all divisors of N*
*-2 bytes by excluding 1 as a divisor in the square test rather than the divisor search*
`^(?!(x(x+))(?!\2*$)\1*(?!(xx+)\3+$)\1$|(x*)\4*(?=\4\b)(x(x+))(?=(\5*)\6+$)\5*$\7)(xx+)\8+$`
It's also possible to directly test that N has no perfect-square factors (i.e., that N is square-free). This uses a variant of the multiplication algorithm [explained in this post](https://codegolf.stackexchange.com/questions/179239/find-a-rocco-number/179420#179420), adapted to asserting that \$A^2=C\$.
Using that algorithm on this problem does not provide any benefit, however. It results in a slower regex, with a larger size. Without the prime multiplicity test (which in one loop asserts both that there are at least 2 prime factors and that they are each of single multiplicity), we have to separately assert that N is composite.
[Try it on replit.com!](https://replit.com/@Davidebyzero/regex-Carmichael-numbers-sequence-90-bytes) - [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") harness ([RegexMathEngine](https://github.com/Davidebyzero/RegexMathEngine/), ECMAScript mode)
[decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") harnesses (ECMAScript):
[Try it online!](https://tio.run/##TY9Lb8IwEITv/AqKEOwmTYjDIxWp4dQDFw7tsWklF0zi1pjINpDy@O2p06pVL6vd@Wa0mnd2YGalRWkDU4o119ud@uCftaaKH9uPPH@oSoATnQ28@hXmN1BB5SO6LYu9LmbE@xadlg395u5eoPIwGzmdZqPsDf8SFLKxI5PGNva6WYI/uTu/W3uDE4Z292S1UDlgaKRYcZjcBiPE1NAoPRZCcgBJNWdrKRQHxBuq9lLiOacyNKUUFvpBH1OxAVA0DyVXuS1wFl8uwizZEgQtmTZ8oSzkz9EL4i/g/4GakTmZNhhtoXfHzkIdmBTrtmYq59N2x5fpZqchFfeUp8L30T3sVJ1Q85IzCwLDLbOrAjTi2fR6patkoWlB0nJvjdXOkl6vdRRMoqhFSBQFxM0WSeIkIMmQtOLRZBi4kXwB "JavaScript (SpiderMonkey) – Try It Online") (Slow 90 byte version)
[Try it online!](https://tio.run/##TY9BT8JAFITv/ApoGnmvtWVbaK3UhZMHLx70aDVZYS2r69LsLlARf3tdMBovk0m@mUzmlW2ZWWjR2Mg0Ysn1@1q98Y9OU8V3/TteX7cNwJ7ORkH3BPMBtNCGiM5VaeBjlQQwp1Xi44k5VI1DHw/QBlhNTmxSPeNfi0KVOZK7jDN@dYE/pSL0u2C0x9iu760WqgaMjRQLDvl5NEEsDSXlbiUkB5BUc7aUQnFAHFC1kRI/aypj00hhYRgNsRQvAIrWseSqtiucpYeDMLfsFgRtmDb8RlmoH8gj4i/g/4GaJfNkesRoV3q9827Ulkmx7Gumaj7te6EsX9YaSnFFeSnCEN2g13qx5g1nFgTG78wuVqARP83ZWeMuWTi@SMpmY43VLlJ@fXUkGhNCenlWkCjPU9IrLkkWFZdJ1ktIVkyio@a9xFkSHTX9Bg "JavaScript (SpiderMonkey) – Try It Online") (Faster 94 byte version)
```
^ # tail = N = input number
(?! # Negative lookahead – assert that neither of the
# following two alternatives can match:
# Cycle through factors \1, with \2 = \1-1, for which \2 does not divide N-1
(x(x+)) # \1 = conjectured factor of N; \2 = \1-1
(?!\2*$) # Assert N-1 is not divisible by \2
\1* # Assert N is divisible by \1 - works along with the
# subsequent "\1$"; tail = \1
# If the factor \1, which already passed the above tests, is prime, then
# fail the outside negative lookahead, because N is not a Carmichael number.
(?!(xx+)\3+$)
\1$
|
# Assert that N isn't square-free, i.e. has at least one divisor >1 that is
# a perfect square (outside the negative lookahead, assert the opposite).
(x*)\4*(?=\4\b) # cycle tail through all divisors of N, including N itself
# Match iff tail is a perfect square
(x(x+)) # \5 = potential square root >= 2; \6 = \5 - 1
(?=
(\5*)\6+$ # iff \5 * \5 == our number, then the first match here must result in \7 == 0
)
\5*$\7 # test for divisibility by \5 and for \7 == 0 simultaneously
)
(xx+)\8+$ # Assert that N is composite
```
[Answer]
# [J](http://jsoftware.com/), ~~72~~ ~~59~~ 51 bytes
```
1{(((0>.-)0&p:*~:@q:-:0=q:|&<:])([,(+*)~)])/^:_@,&2
```
[Try it online!](https://tio.run/##DcNBDoIwEAXQfU/xw6LMQKmDyx9LuIdBF8ZG3SBhqXL14kveq@QViTD8l/4jIjbETs2/2WwcF3a0tPDrT5xUzkHaRjed9HDhdQz@WNRVEXVOrBHwI/Lq3P32mCEh5soUA/GM6K3s "J – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 95 bytes
```
s=filter
c n=s(\x->let l=s((1==).gcd x)f;f=[1..x-1]in l/=f&&all(\y->y^(x-1)`mod`x==1)l)[1..]!!n
```
[Try it online!](https://tio.run/##HY6xDoIwFEV3v@JBDGlDWmVw0Ty@QCdHQCFAhfgohGIsX1@L0z05OcPtKvNuiZwzqHpa2nlXg0bDcitSahcgzyxB5PJVN2C5uijMEimtSIpeAx1QRVFFxPJVpOuDec/LYWxKi5hw4ltbBIF2Q@VzhKGabk9guQaRwvRZ7st81bAH041f0BDHEJ4h3PZvmH/DOWRHKU@F@wE "Haskell – Try It Online")
Degolfed:
```
-- function to filter out Carmichael numbers
filterFunction x =
let coprimes = filter ((1 ==) . gcd x) lesserNumbers
lesserNumbers = [1 .. x - 1]
in
-- the number x is Carmichael if it is not prime
lesserNumbers /= coprimes &&
-- and all of its coprimes satisfy the equation
all (\y -> y ^ (x - 1) `mod` x == 1) coprimes
-- get n'th Carmichael number (zero-based)
c n = filter filterFunction [1..] !! n
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~94~~ ~~90~~ 81 bytes
```
\d*$
x
"$+"}/^((?=(x(x+?))\2*$)(?=(x+)(\4+$)(?<=^\3*x))\5(?!\2*$)){2,}x$/^+`$
x
x
```
[Try it online!](https://tio.run/##K0otycxLNPz/PyZFS4WrgktJRVupVj9OQ8PeVqNCo0LbXlMzxkhLRRPM19bUiDHRBnFsbONijLUqgJKmGvaKYBWa1UY6tRUq@nHaCSCDKv7/NwYA "Retina – Try It Online") 1-indexed. Edit: Saved ~~4~~ 13 bytes by porting @Deadcode's latest Carmichael test, which is also slightly less slow, but still times out for `n>6` on TIO. [crossed out 4 is still regular 4](https://codegolf.stackexchange.com/a/239777/17602) Explanation:
```
\d*$
x
```
Increment the current value. On the first pass, this also deletes `n` from the output buffer (but `$+` can still access it).
```
/^((?=(x(x+?))\2*$)(?=(x+)(\4+$)(?<=^\3*x))\5(?!\2*$)){2,}x$/
```
Test whether the current value is a Carmichael number. This uses @Deadcode's latest regex.
```
^+`
```
Repeat until the current value is a Carmichael number.
```
$
x
```
Increment the current value.
```
"$+"}
```
Repeat the initial increment and above loop `n` times.
```
x
```
Convert the result to decimal.
] |
[Question]
[
### The Challenge
Given the number of items, `n`, in a non-empty, sorted list output the index, `i(n)`, at which its
"*Back-To-Front Permutation*"
would reside in a list of all permutations if said permutations were sorted lexicographically.
Results may be 0 or 1-based, just say which (that is `i`, not `n`).
### The Back-To-Front Permutation
...is the result of building a list of items by repeatedly taking the back (right) then front (left) of a forward sorted (left-to-right) list until all items have been moved to the new list, like so:
```
Input being consumed Output being built
----------------------+----------------------
[1,2,3,4,5,6,7] | []
[1,2,3,4,5,6] | [7]
[2,3,4,5,6] | [7,1]
[2,3,4,5] | [7,1,6]
[3,4,5] | [7,1,6,2]
[3,4] | [7,1,6,2,5]
[4] | [7,1,6,2,5,3]
[] | [7,1,6,2,5,3,4]
----------------------+----------------------
Result: [7,1,6,2,5,3,4]
```
### The Permutation Index
If `n` is `7` (as the above Back-To-Front example) there are `7! = 5040` possible permutations of the (distinct) items.
The first (or zeroth if you prefer) item in the lexicographically sorted list of all those permutations would be `[1,2,3,4,5,6,7]` itself.
The second item would be `[1,2,3,4,5,7,6]`.
The penultimate item would be `[7,6,5,4,3,1,2]`.
The final item would be `[7,6,5,4,3,2,1]`.
Somewhere in the list is `[7,1,6,2,5,3,4]` - the Back-To-Front permutation.
In fact it resides at index 4421 (or 4420, 0-based).
The first 100 terms of the (1-based) series of `i(n)` stating with `n=1` are:
```
[1, 2, 5, 20, 101, 620, 4421, 35900, 326981, 3301820, 36614981, 442386620, 5784634181, 81393657020, 1226280710981, 19696509177020, 335990918918981, 6066382786809020, 115578717622022981, 2317323290554617020, 48773618881154822981, 1075227108896452857020, 24776789629988523782981, 595671612103250915577020, 14915538431227735068422981, 388375922695377900515577020, 10500493527722974260252422981, 294387851083990886241251577020, 8547374142655711068302364422981, 256705485669535347568006115577020, 7966133168508387470157556764422981, 255164703765185142697060455395577020, 8428152915046701352821133945884422981, 286804646124557439494797475697635577020, 10046343320261587490171853861825564422981, 361946983469639629977827594289009635577020, 13401806107756705416338151987291892764422981, 509620811358844406343669072112782398435577020, 19888261269838598952296612667790114958364422981, 796027021978059135393314656928325779313635577020, 32656499591185747972776747396512425885838364422981, 1372349618161694150570365858847999144050545635577020, 59042913445212141486784766209665998363213966364422981, 2599228661343236626556841044804949891956424561635577020, 117022992204136957935406320450852765172427309198364422981, 5385599167607951991914899108349402127789224443761635577020, 253237642343560228651049456045262577841408407945358364422981, 12160677950192512442211239591328112460680077946732401635577020, 596121186084075048430040923729967264426872753432477838364422981, 29817972015629302995182567242334801579950768815528034161635577020, 1521300781271752977229060449226968409483308951201458077838364422981, 79136874389672125594431576407176798565806196489681819746161635577020, 4195746409670353438703582176982222851124537591877131904925838364422981, 226647950929571027033389160506045358232154026979930809227362161635577020, 12469755402728704898931711687060471601348167024469505953048477838364422981, 698528832402134746955113935776664478135149811856698952734398562161635577020, 39828390672475082008725487969655657656845234984369903192450082717838364422981, 2310732940610403489820749422545419026172017083196773021228249831522161635577020, 136372385605079432248118270297843987319730859689490659519593045108637838364422981, 8184614727136310712028222912925520393434441746671755292929684651300962161635577020, 499395599150088488088828589263699706832570087241364247806476254829684637838364422981, 30970577661237849037564293765687064381179710710016867944356691992991422562161635577020, 1951637737743202215078582414596211073163593979517251760161922907619738331037838364422981, 124935294448140961888354806920565269729701922195027940438639971467594965899362161635577020, 8122715297634329704834815499864930982456556629150409552483483162921360809076637838364422981, 536222223779808734298894424747977821661836507759648464980376643706749720339339362161635577020, 35934888694408876553950964671857486605505798806289876128721251856561212716604532637838364422981, 2444100653742421723047039453897314094441893402549077796242989486161660232995578763362161635577020, 168678351774398889649421299427375524997828651490971291597405051437095619521145068660637838364422981, 11809893318195492906423362422261723211461109491055454565957957813190913963268700251019362161635577020, 838668695249666824614744281817664287077123498629740781320472805575397766414810317446260637838364422981, 60395789681636420036909326103457008453700968286067588202502542158402987220806878956757899362161635577020, 4409719671831047920854347812021594101623099731996837427616577550212019116846376438060145780637838364422981, 326378824480107593305098680409232188044060152088938133742995349285199216584125189021190726539362161635577020, 24482761986915290498641378436184801472882183734481184704052899163370643460988742220422624697460637838364422981, 1861011939679134964489290882424961756757512351644848150968435083798473400034549180897307347526539362161635577020, 143322080088606734669581493203883323226982866872563510695813139604263517949121870899167900513721460637838364422981, 11180959098117691096787939665528162905504766712615688479353149686064571807285078895345918312663622539362161635577020, 883437253980179837588356231874303489164303450066956218734514913541773418886216781638015892528346553460637838364422981, 70686019792283622457223177491312228676420353892298796358374930144685265836593932061030928974752467526539362161635577020, 5726440000955084363422511054086796876735936890839327162387490119571704913857298124195153605274993472953460637838364422981, 469637893700329090478715695935318149767077357177154001454773443957172289821041850488811978203204173646406539362161635577020, 38985601803506257421418755484185292421669426050466292273769584084412579273175587484390779961900566697260473460637838364422981, 3275254532761847009577968823645945995578996860191583194845076448298646552018541276645494943006816186458917446539362161635577020, 278435156905293180685369975402415213484477637470382623210256836304261379607777392174394791509334107831816205753460637838364422981, 23948660226767439201080153228038844501800392914958999127628507660415900870134672884615069843391985357739844389446539362161635577020, 2083808638152760278012520365471350750727983345146397213195344003554238214857458501196068353393022808146994627392953460637838364422981, 183398833619245678836784325280074933629492985604252949471226236983335323969170740817904072891411479020269638889458246539362161635577020, 16324556327289215402380134937173544376210173250892288905442294470849835710409338998582008497896189183708810744110298553460637838364422981, 1469391408154472281907142598683652193509359788033796478036774569234135557383656537547410122872987870461908423725867813446539362161635577020, 133730761359685823973259426160811489954077506688872881313704960027919535214176338228137873831877461557289259913042140378553460637838364422981, 12304683293281621431502064899712741587623914209186541475526534622910218175769343180214908250005163885795818227069614613285446539362161635577020, 1144467823788359953327703097406527694627129315367226993710615746590336588945697972034988381266839681418043178062317463477466553460637838364422981, 107592147841885948074037582159380073309559674264815645313786758687454863280472229658194120833316575777142822473140067877053221446539362161635577020, 10222386340397173314525664517235347022088186665852557223898463812546839124314230895213571254552107892786139414391086539473362138553460637838364422981, 981455548530552515895045737024658454136095461985415238220477591025945383684777269092475904782448641089288955324574667766166512421446539362161635577020, 95211304133951567337433380212539040258207718457187560919883999728307800228797098229713403270806624010171995234355103499880901319898553460637838364422981, 9331679144749296178288752362844703433551486045621764102574354777566399269794426700653262755936922495813433855354253356929531746247461446539362161635577020, 923930475294692230638703636199822301473608196598194450583355284174609600662504729388761377005628260366723545352917984225582320362921178553460637838364422981, 92402284968649460451060535220066878189242360067783427018009608611042990392567410879552702599150890025886974375474305774025602890553942821446539362161635577020
```
(`i(0)=i(1)=1`, but the challenge itself only deals with non-empty lists)
At the time of posting this sequence did not appear in the [OEIS](http://oeis.org/search?q=5%2C+20%2C+101%2C+620%2C+4421&language=english&go=Search).
Output must only need to work in theory (don't worry about overflowing integers, or running out of resources for example).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
However, don't let code-golf languages dissuade you - good solutions should get upvotes too!
[Answer]
# [Haskell](https://www.haskell.org/), 32 bytes
```
f 1=1
f n=product[1..n]+1-f(n-1)
```
[Try it online!](https://tio.run/nexus/haskell#@5@mYGhryJWmkGdbUJSfUppcEm2op5cXq22om6aRp2uo@T83MTNPwVahoCgzr0RBRSE3sUAhTQGkyNAg9j8A "Haskell – TIO Nexus")
Uses the relationship `f(n-1) + f(n) = n! + 1`. Adjacent members of the sequences add to factorials plus one:
```
1, 2, 5, 20, 101, 620, 4421, ...
3 7 25 121 721 5041 ...
2!+1 3!+1 4!+1 5!+1 6!+1 7!+1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
R!ḅ-_Ḃ
```
0-based. [Try it online!](https://tio.run/nexus/jelly#@x@k@HBHq278wx1N////NwUA "Jelly – TIO Nexus")
Heavily inspired by [@Neil's ES6 answer](https://codegolf.stackexchange.com/a/112486/42545).
### Explanation
```
R!ḅ-_Ḃ
R Create the range [1..N].
! Take the factorial of each.
ḅ- Convert from base -1; that is, sum, but alternate between adding and subtracting.
_Ḃ Subtract N%2.
```
### But how?
I explain in [my ES6 answer](https://codegolf.stackexchange.com/a/112480/42545) a related technique for calculating each number. The formula is this:
```
(n-1)(n-1)! + (n-3)(n-3)! + (n-5)(n-5)! + ...
```
A realization struck me while reading [@Neil's ES6 answer](https://codegolf.stackexchange.com/a/112486/42545). This formula can be simplified like so:
```
(n-1)(n-1)! + (n-3)(n-3)! + (n-5)(n-5)! + ...
(n(n-1!) - (n-1)!) + ((n-2)(n-3!) - (n-3)!) + ((n-4)(n-5)! - (n-5)!) + ...
(n! - (n-1)!) + ((n-2)! - (n-3)!) + ((n-4)! - (n-5)!) + ...
n! - (n-1)! + (n-2)! - (n-3)! + (n-4)! - (n-5)! + ...
```
The Jelly code `R!ḅ-` calculates this formula. However, each odd value of `n` will have an extra `+ 0!` at the end, which we take care of by subtracting `n%2`.
[Answer]
## JavaScript (ES6), 38 bytes
```
f=(n,x=n%2,y=1)=>n-x&&f(n,++x,y*=-x)+y
```
0-indexed. (No explanation because I don't actually know why it works, sorry.)
[Answer]
# JavaScript (ES6), 44 bytes
```
f=(x,n=0,g=1)=>x-n&&(x-n&1)*g*n+f(x,++n,g*n)
```
0-based. This takes advantage of the fact that the numbers can be represented as sums of factorials in the following pattern:
```
1 2 6 24 120 720
0:
1: 1
4: 2
19: 1 3
100: 2 4
619: 1 3 5
4420: 2 4 6
```
Why? The permutations can be represented nicely in the [factorial base](https://en.wikipedia.org/wiki/Factorial_number_system): taking the **n**th item out of the remaining list corresponds to a digit of **n** at that position. We're alternating between taking the *last* item (highest digit) and the *first* item (zero); therefore, in the factorial base, these numbers can be represented as:
```
0
10
200
3010
40200
503010
6040200
```
and so on.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 17 bytes
```
:t"&0)P]vG:Y@!=Af
```
Output is 1-indexed.
[Try it online!](https://tio.run/nexus/matl#@29VoqRmoBkQW@ZuFemgaOuY9v@/KQA "MATL – TIO Nexus")
### Explanation
The code appplies the definition: builds the back-to-front permutation, generates all permutations, compares the former with all of the latter, and outputs the index of the matching.
```
: % Input n implicitly. Push [1 2 ... n]
t % Duplicate
" % For each: do the following n times
&0) % Push the last element and then the rest of the array
P % Reverse
] % End
v % Concatenate the whole stack vertically. This produces into a column vector
% with the back-to-front permutation
G: % Push [1 2 ... n] again
Y@! % Permutations of [1 2 ... n]. Gives a matrix. Each column is a permutation
= % Test for equality, element-wise with broadcast
A % All: true for columns that have all entries equal to true. Gives a row vector
f % Find: index of non-zero value. Implicitly display
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
RU;¥/ỤUŒ¿
```
[Try it online!](https://tio.run/nexus/jelly#ARoA5f//UlU7wqUv4bukVcWSwr//UsOH4oKs//8yMA "Jelly – TIO Nexus")
Huh, I was trying to FGITW this. Turns out @Dennis posted first, but this is shorter.
## Explanation
```
RU;¥/ỤUŒ¿
R List of numbers from 1 to {the input}
¥/ Left-fold the list by
U; prepending the reverse of the list to the next element
Ụ Invert permutation
U Reverse the list
Œ¿ Find index of permutation
```
Having `Œ¿` as a built-in is fairly handy here letting us convert a permutation to its index, so the other 7 bytes are responsible for constructing the back-to-front permutation.
The way we do this is first to construct a different permutation, via the following pattern:
```
1
1 2
2 1 3
3 1 2 4
4 2 1 3 5
5 3 1 2 4 6
6 4 2 1 3 5 7
```
Each time, we're reversing the list we have so far, then appending the next integer. That doesn't produce the back-to-front permutation, but it's clearly related.
The permutation we're *trying* to get is `7 1 6 2 5 3 4`. How is this related? Well, the element in the 7th position of the permutation we have is a 7; the element in the 1st position is a 6; the element in the 6th position is a 5; the element in the 2nd position is a 4, and so on. In other words, it's the inverse of the permutation we have (with the elements in reverse order). As such, after the reduce, we can invert the permutation with `Ụ` and reverse the result with `U` to get the back-to-front permutation we want.
It's possible that there are savings here, because it was written in a hurry and feels like it has at least some potential to rearrange things. I'm not sure it's possible to save a whole byte, though.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 8 bytes
```
RṚżRFQŒ¿
```
*Thanks to @ais523 for golfing off 2 bytes and a tremendous speed-up!*
[Try it online!](https://tio.run/nexus/jelly#AR0A4v//UuG5msW8UkZRxZLCv/8yNVLCtcW8w4figqxH/w "Jelly – TIO Nexus")
### How it works
```
RṚżRFQŒ¿ Main link. Argument: n
R Range; yield [1, ..., n].
Ṛ Reverse; yield [n, ..., 1].
R Range; yield [1, ..., n] again.
ż Zip; yield [[n, 1], ..., [1, n]].
F Flatten.
Q Unique; deduplicate the results.
Œ¿ Compute the permutation index of [n, 1, n-1, 2, ...].
```
[Answer]
# PHP, 86 bytes
```
for($i=$argv[1];$i>0;$i--)$o+=gmp_strval(gmp_fact($i))*($i%2==$argv[1]%2?1:-1);echo$o;
```
Uses the [GNU Multiple Precision](http://php.net/manual/en/book.gmp.php) extension.
This function takes advantage of the fact that `i(n)` is equal to `n! - (n-1)! + (n-2)! - (n-3)! etc`
**Breakdown**
```
for($i=$argv[1];$i>0;$i--) { // Simple decreasing for loop (added { for readability)
$o+= // increment output with
gmp_strval(gmp_fact($i)) // $i!
* ($i%2 == $argv[1]%2 ? 1 : -1) // multiplied by -1 if ($i is odd when the input is even) or (if $i is even when the input is odd), else by 1
;
}
echo $o; // echoes output
```
[Answer]
## Batch, 79 bytes
```
@set/ax=%1%%2-1,y=z=1
@for /l %%i in (-%1,1,%x%)do @set/az+=y*=x-=1
@echo %z%
```
0-indexed.
[Answer]
# Pyth, 12 bytes
```
x.pQ<Q.i_UQU
```
0-indexed.
### Explanation
```
x.pQ<Q.i_UQU
.i Interleave
_UQUQ Reversed range and range
<Q Take first n
x Find the index
.pQ In the list of permutations
```
] |
Subsets and Splits