text
stringlengths
180
608k
[Question] [ Somehow, we don't yet have a challenge for finding the inverse of an arbitrarily-sized square matrix, despite having ones for [3x3](https://codegolf.stackexchange.com/questions/168828/find-the-inverse-of-a-3-by-3-matrix) and [4x4](https://codegolf.stackexchange.com/questions/45369/find-the-inverse-of-a-matrix), as well as a [more complex version](https://codegolf.stackexchange.com/q/200685/66833). Your task is, given a square \$n\times n\$ non-singular matrix \$M\$, output the matrix \$M^{-1}\$ that satisfies $$MM^{-1} = I\_n$$ There are a number of methods and formulae for calculating \$M^{-1}\$, but one of the most well known is $$M^{-1} = \frac1{\det(M)}\text{ adj}(M)$$ where \$\det\$ represents the determinant and \$\newcommand{\adj}{\text{adj}}\adj\$ the adjugate Some definitions: * \$I\_n\$: The \$n\times n\$ [identity matrix](https://en.wikipedia.org/wiki/Identity_matrix) i.e. an \$n\times n\$ matrix where the leading diagonal consists entirely of \$1\$s and the rest \$0\$s * Non-singular: the determinant of \$M\$ is guaranteed to be non-zero * [Determinant](https://en.wikipedia.org/wiki/Determinant): a specific number that can be calculated for any given square matrix. Exact methods can be found in the Wikipedia article * [Adjugate](https://en.wikipedia.org/wiki/Adjugate_matrix): Formally, the transpose of the cofactor matrix of \$M\$. Informally, this is a operation on \$M\$ which takes determinants of submatrices in a specific way to construct a related matrix. Again, exact details can be found in the linked article. For sake of simplicity, you may assume: * The elements of \$M\$ will all be integers within the native bounds of your language * \$n\$, nor \$n^2\$, will never exceed the maximum value in your language, and will always be greater than or equal to \$1\$ * The elements of \$M^{-1}\$ will never exceed the maximum value in your language (or minimum for negative values) * \$M\$ will never be singular No builtins are banned and you may use whatever (valid) method you like for calculating \$M^{-1}\$. It is acceptable if your program fails for some inputs due to floating point issues, so long as the underlying algorithm or method works for arbitrary matrices. This is, of course, entirely optional, but if your answer consists entirely of a builtin, consider including a non-builtin method, simply for the sake of general interest. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. This means you may input or output in any [convenient format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), and that [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. The shortest code in bytes wins. [This](https://tio.run/##ZY5NDoIwEIXXzCm6o02ggRg3Jp4EWDSC2IROJ7VoOH2dCq6czfy872UebfHh8ZSSdeRDFMHg6B0cG66ONoDROnEVFqO0SGuUSoEzkU/dAHD3QQT/Zjmb50kyrS5QMKEN0YSj7AYFReZuflkd/qGZ7ep2@PF7CJ1bflq3TSXahr8ChXxgvBIMcoKyxx5LdQiLfWaVvkO1x9eLRbPM2uIrGxVXSucP) script will take an input \$n\$ and generate an \$n\times n\$ matrix with random integers between \$-10\$ and \$10\$, along with it's inverse. You can use this for test cases. --- ### Worked example Lets take the \$3\times3\$ matrix \$M\$ as: $$M = \left[\begin{matrix} 4 & -3 & 0 \\ -4 & -7 & 6 \\ 5 & 7 & 6 \end{matrix}\right]$$ We'll use the above formula, \$M^{-1} = \frac{\adj(M)}{\det(M)}\$ for this example. First, we'll calculate \$\det(M)\$ by expanding along the third column: $$\begin{align} \det(M) & = \left|\begin{matrix} 4 & -3 & 0 \\ -4 & -7 & 6 \\ 5 & 7 & 6 \end{matrix}\right| \\ & = 0\left|\begin{matrix} -4 & -7 \\ 5 & 7 \end{matrix}\right| - 6\left|\begin{matrix} 4 & -3 \\ 5 & 7 \end{matrix}\right| + 6\left|\begin{matrix} 4 & -3 \\ -4 & -7 \end{matrix}\right| \\ & = 0 - 6(4\cdot7 - -3\cdot5) + 6(4\cdot-7 - -3\cdot-4) \\ & = -6(28 + 15) + 6(-28 - 12) \\ & = -6\cdot43 + 6\cdot-40 \\ & = -498 \\ \therefore det(M) & = -498 \end{align}$$ We then need to calculate \$\adj(M)\$. As \$\adj(\cdot)\$ of a matrix is the transpose of the cofactor matrix, this essentially boils down to calculating the cofactor matrix of \$M\$, \$C\_M\$: $$\begin{align} \adj(M) & = C\_M^T \\ & = \left[\begin{matrix} \left|\begin{matrix} -7 & 6 \\ 7 & 6 \end{matrix}\right| & \left|\begin{matrix} -4 & 6 \\ 5 & 6 \end{matrix}\right| & \left|\begin{matrix} -4 & -7 \\ 5 & 7 \end{matrix}\right| \\ \left|\begin{matrix} -3 & 0 \\ 7 & 6 \end{matrix}\right| & \left|\begin{matrix} 4 & 0 \\ 5 & 6 \end{matrix}\right| & \left|\begin{matrix} 4 & -3 \\ 5 & 7 \end{matrix}\right| \\ \left|\begin{matrix} -3 & 0 \\ -7 & 6 \end{matrix}\right| & \left|\begin{matrix} 4 & 0 \\ -4 & 6 \end{matrix}\right| & \left|\begin{matrix} 4 & -3 \\ -4 & -7 \end{matrix}\right| \end{matrix}\right]^T \\ & = \left[\begin{matrix} -84 & 54 & 7 \\ 18 & 24 & -43 \\ -18 & -24 & -40 \end{matrix}\right]^T \\ & =\left[\begin{matrix} -84 & 18 & -18 \\ 54 & 24 & -24 \\ 7 & -43 & -40 \end{matrix}\right] \end{align}$$ Finally, having calculated both \$\det(M)\$ and \$\adj(M)\$, we divide each element of \$\adj(M)\$ by \$\det(M)\$ to compute the final output, \$M^{-1}\$: $$\begin{align} M^{-1} & = \frac{\adj(M)}{\det(M)} \\ & = \left[\begin{matrix} \frac{-84}{-498} & \frac{ 18}{-498} & \frac{-18}{-498} \\ \frac{ 54}{-498} & \frac{ 24}{-498} & \frac{-24}{-498} \\ \frac{ 7}{-498} & \frac{-43}{-498} & \frac{-40}{-498} \end{matrix}\right] \\ & = \left[\begin{matrix} \frac{ 14}{ 83} & \frac{-3}{ 83} & \frac{ 3}{ 83} \\ \frac{ -9}{ 83} & \frac{-4}{ 83} & \frac{ 4}{ 83} \\ \frac{ -7}{498} & \frac{43}{498} & \frac{20}{249} \end{matrix}\right] \end{align}$$ Alternatively, as decimals, \$M^{-1}\$ is ``` [[ 0.1686746987951807, -0.03614457831325301, 0.03614457831325303], [-0.10843373493975902, -0.04819277108433735, 0.04819277108433734] [-0.014056224899598388, 0.08634538152610442, 0.08032128514056225]] ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 57 bytes ``` A=input('');V=A'/trace(A*A');for i=1:1e4V=2*V-V*A*V;end V ``` [Try it online!](https://tio.run/##y08uSSxL/f/f0TYzr6C0RENdXdM6zNZRXb@kKDE5VcNRyxEokJZfpJBpa2hlmGoSZmukFaYbpuWoFWadmpfCFfY/M69Mw1Hzf1FiXoqGsY6xJgA "Octave – Try It Online") This is not particularly well golfed, but I wanted to advertise an approach that could be useful for other non-builtin answers. This uses the Hotelling-Bodewig scheme: $$ V\_{i+1} = V\_i\left(2I - AV\_i\right)$$ Which iteratively computes the inverse of a non singular matrix. This is guaranteed to converge for \$\left\lVert I - AV\_0\right\rVert < 1\$ (under a suitable matrix norm). Choosing the \$V\_0\$ is difficult, but Soleymani, F. shows in ["A New Method For Solving Ill-Conditioned Linear Systems"](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.882.7271&rep=rep1&type=pdf) that the inital guess \$V\_0 = \frac{A^T}{\text{tr}(AA^T)}\$ will always satisfy this condition, so the system is numerically stable. What makes this a particularly attractive approach to other potential answers is that we don't require any builtin determinant or inverse functions. The most complex part is just matrix multiplication, since the transpose and trace are trivial to compute. I have chosen `1e4` iterations here to make the runtime somewhat reasonable, although you could of course push it to `1e9` with no loss of byte count. --- -10 thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) for noting we don't need to construct an identity matrix. [Answer] # [R](https://www.r-project.org/), 5 bytes ``` solve ``` [Try it online!](https://tio.run/##K/qfZvu/OD@nLPV/mkZuYklRZoVGsoaJjoKxjoKuqY4CkKVraKCjYKGjYAkmQYLGYI4lVMoQSJsDKSjTEqIGhIGiuiYQISMQpamjYApGIZqa/wE "R – Try It Online") Nothing new here... Basically, the code `solve(A, B)` solves \$AX = B\$, but when \$B\$ is not given, it is treated as identity matrix, thus giving us the inverse as the result. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 1 byte[SBCS](https://en.wikipedia.org/wiki/SBCS) ``` ⌹ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HPzv@P@qY@apugAGQqGCkYPerdYmigYKFwaD0Y/wcA "APL (Dyalog Unicode) – Try It Online") The domino primitive is a very interesting APL "built-in". It already [featured in another 1-byte answer of my own](https://codegolf.stackexchange.com/a/205897/75323) where it was used to solve a least-squares problem. When applied to a square matrix, `⌹` tries to find the matrix inverse of its argument. Many golfing languages will also have a built-in for this... But mind you, APL is **not** a golfing language, although it is terse enough to be very competitive and, in cases like this, win. [Answer] # [R](https://www.r-project.org/), ~~72~~ 61 bytes ``` function(A,V=t(A/sum(diag(A%*%t(A))))){for(i in 1:1e4)V=2*V-V%*%A%*%V;V} ``` [Try it online!](https://tio.run/##vY3dCoMwDIXv9xS5EVJJ2eoPmxu98B1G78XZUVALWsdg7Nm7Vn2GhSQn@XIgk9fS62VsnbEj1qSkw/o4LwM@TPPEOkmTAFiMj7YTGjAjiKvoCqZkliqugiO61E19vcahcZN5Y4sFQU7AS4IwcXEiuBBUa48wX5dqP4mg5yD7WG2eWIHyYkNZFEZQrnln7DDb/tX99aX/AQ "R – Try It Online") Porting [Sisyphus' answer](https://codegolf.stackexchange.com/a/213913/67312) is not futile at all...and thanks to Sisyphus for -11 bytes. Observes that \$Tr(AA^T)=\sum\limits\_{i,j}a\_{ij}^2\$. # [R](https://www.r-project.org/), 94 bytes ``` function(M)outer(k<-1:dim(M),k,Vectorize(function(j,i)det(M[-i,-j,drop=F])*(-1)^(i+j)))/det(M) ``` [Try it online!](https://tio.run/##vY3BCsIwDIbvPkWPiaZo3YZO3NXbbuJFFGTroJtbpXYivnztuuEjCEn@P19@iHFV5qq@K6zSHeSoeysNNHsudqVqPaCGTrKw2qiPhF@wJoWltJCfuSJeU2n0IztccA5c4BXUokbEZUigq6C9WaPeUEBMLCLGE2LecbEitiWWhjnAKCzpdBJeN14mm46ZoT3l8YjWgyCxJNQRcfbU95f860v3BQ "R – Try It Online") Thanks to [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder) for fixing a bug and making this actually work. Calculates \$A^{-1}\$ using the adjugate/determinant method. [Answer] # [Python 2](https://docs.python.org/2/), 228 bytes ``` from random import* a=input() exec"""$:j,J=i,I;J+=[j==i $] while~-all(I[i]$):shuffle(a) $: j,J=i,I $: if j-i:I[:]=[y-I[j]*x/J[j]for x,y in zip(J,I)] $:print[x/I[i]for x in I][len(a):]""".replace("$","for i,I in enumerate(a)") ``` [Try it online!](https://tio.run/##NU5BbsMgEDyXVyDkg53gJGraVKLiAfgLiANKQV4LY0Rt1e6hX3eXqL3szEgzO5O2uZ/i8777PI002/iBAGOa8nwgVkJMy1w3xK3uzhirxMA7CVy9d0epBymBVoZ89RDcT2tDqJUGUzXis1@8D662DakEoX8hQlE8gadDC0JpYaTeWqUHc1jPHYKfMl35RiHSb0h1x1VjMJ8yxFmv5/L7YSkGZXRwEQuEwV2n7FKwd1ezinFWTFhXbC4uo8t2LlNYs@9aX04X3l7xIDFcty9Fv@G5PfQrsn9lfgE "Python 2 – Try It Online") Augment the matrix with the identity matrix, then apply Gauss–Jordan elimination. I don't know if this is the shortest approach, but it's the one I wanted to try golfing down. I use `while not all(a[i][i]for i in r):shuffle(a)` to move zeros off the diagonal. This loop will definitely terminate, because if there is *no* permutation of the rows of \$A\$ that makes the diagonal free of zeros, then \$\det(A)=0\$, which we are guaranteed is not the case. This can be seen from the Leibniz formula for \$\det(A)\$: $$\det(A) = \sum\_{\sigma \in S\_n} \text{sgn}(\sigma) \prod\_{i=1}^n a\_{\sigma(i),i}$$ “There is no permutation \$\sigma\$ of the rows that makes the diagonal free of zeros” can be equivalently rephrased as “\$\prod\_{i=1}^n a\_{\sigma(i),i}\$ is always 0, for all \$\sigma\$” which causes this whole formula to be 0. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~27~~ 23 [bytes](https://github.com/abrudz/SBCS) -4 bytes thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m)! This implements the method [advertised by Sisyphus](https://codegolf.stackexchange.com/a/213913/64121). ``` ⊢(⊢+⊢-⊢+.×+.×)⍣≡⍉÷,+.×, ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HXIg0g1gZiXRCtd3g6CGs@6l38qHPho97Ow9t1QAI6/9MetU141Nv3qKv5Ue@aR71bDq03ftQ28VHf1OAgZyAZ4uEZ/D9NwRgIgZIKhgoGYIigQeBR71wFz5TUvJLMkkoF38SSoswKLoQeEwWgmUC1h9aDWOYKZgqmCiASrC0gv7ikWCG1IjG3ICcVAA "APL (Dyalog Unicode) – Try It Online") A function that takes the matrix as the right argument. `+.×` computes the dot product (sum of element-wise product) of the flattened matrix `,` and the flattened matrix `,`. This is sum of the squared matrix entries, which is equal to \$tr(AA^T)\$. `⍉÷` divides the transposed matrix by the trace. `(⊢+⊢-⊢+.×+.×)⍣≡` is a function which is applied to the original matrix \$A\$ as a left argument (`⊢`) and \$A^T\div tr(AA^T)\$ as the right argument (`⍉÷,+.×,`): `⊢+⊢-⊢+.×+.×` takes the current matrix \$V\$ on its right and the input matrix \$A\$ on its left and executes one iteration step: `+.×` is the inner product of `+` and `×`. Given two matrices, this calculates their product. In this case \$ A \times V \$. `⊢` is the right argument \$V\$, `⊢+.×` the product \$V \times (A \times V)\$. `⊢-` subtracts this from the right argument: \$V-V \times A \times V\$. `⊢+` adds this to the right argument: \$V+V-V \times A \times V\$. `⍣≡` applies the function on its left until the result doesn't change. Because of the way [equality testing works](https://help.dyalog.com/18.0/Content/Language/System%20Functions/ct.htm) in Dyalog APL, this actually terminates. [Answer] # [Julia 1.0](http://julialang.org/), 3 bytes ``` inv ``` [Try it online!](https://tio.run/##yyrNyUw0rPifZvs/M6/sf0FRZl6JRppGtImCsYKuqYKJgq6hgbWChYIlEAP5xtZAliVIUMFQQdfcWgHCsATJ6ZpaK5gr6JqAuEZAIlZT8z8A "Julia 1.0 – Try It Online") Yet another short built-in solution. [Answer] # JavaScript (ES6), 169 bytes This computes \$M^{-1} = \dfrac{\operatorname{adj}(M)}{\det(M)}\$ ``` M=>M.map((r,y)=>r.map((_,x)=>D(h(M,x).map(r=>h(r,y)))*(x+y&1?-1:1)/D(M)),h=(a,n)=>a.filter(_=>n--),D=M=>+M||M.reduce((s,[v],i)=>s+(i&1?-v:v)*D(h(M,i).map(r=>h(r,0))),0)) ``` [Try it online!](https://tio.run/##VY7NasQgFEb3eQpXnetE7aTttDBgugndueoyHQbJT@OQaDBWMjDvnpoIhW7kO5fveu5VejlVVo2OalM3S8sXwXPBBjkCWHLDPLcRLmQOUEAHIqRtZnnebSWM9zCnt4fsnWanDD8WIDAmHQdJdFiSrFW9ayxceK4pxaTgQZKK@10w29Q/VQMwkdKfiQrtKQW1/uRPHu@jT/3zHYJvfZbW2EE6xNGAeI4qoyfTN6w33zDE/jqO5/s1eubMh5qbGrInzEZZfzppHWRHjNnVKA07tPuLXzrkJIkOaKFMECrRC6HPBB3OZCUa6I2g10joSNBGyTnc9gs "JavaScript (Node.js) – Try It Online") [Answer] # [J](http://jsoftware.com/), 2 bytes ``` %. ``` [Try it online!](https://tio.run/##y/qfmpyRb6Rga6UQbaUAYqvZKairq1n/V9X7/z83sQQkY6IQb6xgoKCjEA9kmSuYKehYKZgqABlcEM2qekCFcLZChZUCkA8A "J – Try It Online") Same as APL, but more powerful, as J can produce exact rational matrix when given a matrix of extended integers as input. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~38~~ ~~22~~ ~~21~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ˜nO/øтF©I2Føδ*O®}·s- ``` Port of [*@Sisyphus*' Octave answer](https://codegolf.stackexchange.com/a/213913/52210), so make sure to upvote him!! -16 bytes thanks to *@ovs*. [**Try this online.**](https://tio.run/##yy9OTMpM/f//9Jw8f/3DOy42uR1a6WnkdnjHuS1a/ofW1R7aXqz7/390tImOrrGOQaxOtC6QZa5jBmSZ6oDo2P@6unn5ujmJVZUA) **Code explanation:** ``` ˜ # Flatten the (implicit) input-matrix to a single list n # Square each value in this list O # Take the sum (this is the trace of M*M') / # Divide each value in the (implicit) input-matrix by this trace ø # Zip/transpose this matrix; swapping rows/columns тF # Loop 100 times: © # Store the current matrix in variable `®` (without popping) I # Push the input-matrix 2F # Loop 2 times: ø # Zip/transpose the top matrix; swapping rows/columns δ # Apply double-vectorized with the top two matrices: * # Multiply O # Sum each inner row ® # Push the matrix from variable `®` again }· # After the inner loop: double all values in matrix `®` s # Swap so the calculated matrix VMV is at the top again - # Subtract this VMV from the 2V # (after the outer loop, the resulting matrix is output implicitly) ``` --- ## Original answer (38 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) and detailed explanation: ``` εUεX*O]Å\OIøs/тFxs©εUIøεX*O}U®øεX*O}}- ``` [**Try it online.**](https://tio.run/##yy9OTMpM/f//3NbQc1sjtPxjD7fG@Hse3lGsf7HJraL40EqgBJALlqsNPbQOxqzV/f8/OtpER9dYxyBWJ1oXyDLXMQOyTHVAdOx/Xd28fN2cxKpKAA) 05AB1E has barely any useful builtins for matrices, not even matrix manipulation. So almost everything has to be done manually.. Since I'm an absolute noob in math, I'm gonna explain everything in full detail to help others like me who want to do this challenge without any builtins, and also to keep this answer self-contained. **Step 1)** [Matrix manipulation](https://en.wikipedia.org/wiki/Matrix_multiplication#Definition) of the input-matrix \$M\$ with it's transpose: \$M\times M'\$: If we have a matrix \$A\$ and \$B\$ and want to do matrix-manipulation \$AB\$, we take the [dot-product](https://en.wikipedia.org/wiki/Dot_product#Algebraic_definition) of every \$i^{th}\$ row of \$A\$ and \$j^{th}\$ column of B for every coordinate \$i,j\$ in the two matrices. For example, if we use the matrix in the challenge description: \$M = \left[\begin{matrix} 4 & -3 & 0 \\ -4 & -7 & 6 \\ 5 & 7 & 6 \end{matrix}\right]\$ We can for example calculate the values in the top row of the resulting \$M\times M'\$ matrix with: Top-left: \$4\times4+-3\times-3+0\times0 = 25\$ Top-center: \$4\times-4+-3\times-7+0\times6=5\$ Top-right: \$4\times5+-3\times7+0\times6 = -1\$ I've done matrix manipulation in 05AB1E before in [this answer of mine](https://codegolf.stackexchange.com/a/197011/52210), so I've used that code snippet here as well. Since we want to multiply the input-matrix by it's transpose, we actually won't need the transpose builtin here. ``` ε # Map over each row of the (implicit) input-matrix U # Pop and store the current row in variable `X` ε # Map over each row of the (implicit) input-matrix again X* # Multiply the values of the current row by the values at the same # positions in row `X` O # And take the sum of this row ] # Close both maps ``` [Try just this step online.](https://tio.run/##yy9OTMpM/f//3NbQc1sjtPxj//@PjjbR0TXWMYjVidYFssx1zIAsUx0QHftfVzcvXzcnsaoSAA) **Step 2)** Take the [trace](https://en.wikipedia.org/wiki/Trace_(linear_algebra)#Definition) of this new matrix: \$(M\times M')^T\$ The trace of a square matrix is basically the sum of its main diagonal (the values of the top-left to the bottom-right). ``` Å\ # Take the main diagonal of the matrix of step 1 O # And sum the values in this list together ``` [Try the first two steps online.](https://tio.run/##yy9OTMpM/f//3NbQc1sjtPxjD7fG@P//Hx1toqNrrGMQqxOtC2SZ65gBWaY6IDr2v65uXr5uTmJVJQA) **Step 3)** Divide all values in the transposed matrix by this trace we calculated: ``` I # Push the input-matrix ø # Zip/transpose it; swapping rows/columns s # Swap so the trace we calculated it at the top of the stack / # And divide each value in the transposed matrix by this trace ``` [Try the first three steps online.](https://tio.run/##yy9OTMpM/f//3NbQc1sjtPxjD7fG@Hse3lGs//9/dLSJjq6xjkGsTrQukGWuYwZkmeqA6Nj/urp5@bo5iVWVAA) **Step 4)** Repeat the following steps (5 through 8) enough times for the answer to not change anymore: Since this program isn't very fast in 05AB1E, I've decided to loop just 100 times, but this can be increased to improve the accuracy of the decimal results (I've verified with [*@Sisyphus*' Octave answer](https://codegolf.stackexchange.com/a/213913/52210) that changing the `1e4` to `1e2` still holds the same result for most matrices). ``` тF # Loop 100 times: ``` I'm not sure if the values will eventually not change anymore if we loop enough times. If this is the case we could (in theory) save a byte by changing this `тF` to `Δ` (loop until the result no longer changes). (Let's call the intermediate matrix inside this loop \$V\$ for the explanations of the following steps.) **Step 5)** Double each value in the current matrix: \$2V\$: ``` x # Double each value in the current matrix V (without popping) ``` [Try the first five steps online, excluding the loop of step 4.](https://tio.run/##yy9OTMpM/f//3NbQc1sjtPxjD7fG@Hse3lGsX/H/f3S0iY6usY5BrE60LpBlrmMGZJnqgOjY/7q6efm6OYlVlQA) **Step 6)** Do matrix manipulation again for \$VM\$ (where \$M\$ is the input-matrix): ``` s # Swap to take the non-doubled matrix V at the top again © # Store this matrix V in variable `®` (without popping) ε # Map over each row of matrix V: U # Pop the current row, and store it in variable `X` I # Push the input-matrix M ø # Zip/transpose; swapping rows/columns ε # Map over each row of this transposed matrix M': X* # Multiply the values in the current row by row `X` O # And take the sum ``` [Try the first six steps online, excluding the loop of step 4.](https://tio.run/##yy9OTMpM/f//3NbQc1sjtPxjD7fG@Hse3lGsX1F8aCVQFMgGS/z/Hx1toqNrrGMQqxOtC2SZ65gBWaY6IDr2v65uXr5uTmJVJQA) **Step 7)** And do matrix manipulation yet again right after: \$VMV\$: ``` } # Close the inner map U # Pop and store this as new `X` ® # Push the matrix V from variable `®` ø # Zip/transpose; swapping rows/columns ε # Map over each row of this transposed matrix V': X* # Multiply the values in the current row by row `X` O # And take the sum }} # Close both the inner and outer maps ``` [Try the first seven steps online, excluding the loop of step 4.](https://tio.run/##yy9OTMpM/f//3NbQc1sjtPxjD7fG@Hse3lGsX1F8aCVQFMgGS9SGHloHY9b@/x8dbaKja6xjEKsTrQtkmeuYAVmmOiA69r@ubl6@bk5iVSUA) **Step 8)** Subtract the values at the same positions of these two matrices from one another: \$2V-VMV\$: ``` - # Subtract matrix VMV from 2V ``` [Try the first eight steps online, excluding the loop of step 4.](https://tio.run/##yy9OTMpM/f//3NbQc1sjtPxjD7fG@Hse3lGsX1F8aCVQFMgGS9SGHloHY9bq/v8fHW2io2usYxCrE60LZJnrmAFZpjogOva/rm5evm5OYlUlAA) And after the loop is done, the resulting matrix is output implicitly. [Answer] # [Python 2](https://docs.python.org/2/), 188 bytes ``` lambda a:[[c(a,j,i)/d(a)for j,_ in e(a)]for i,_ in e(a)] c=lambda a,i,j:(-1)**(i+j)*d([b[:j]+b[j+1:]for I,b in e(a)if i-I]) d=lambda a:a==[]or sum(b[0]*c(a,i,0)for i,b in e(a)) e=enumerate ``` [Try it online!](https://tio.run/##TY5NDoIwEEb3nKLLFgYs/iZNegDPMDamhRKnETSIC0@PBQNx82Ve8r2ZeX6G26Pbjo2@jHfbutoyqxArbiEAiU3NrWgePQtwZdQxH9FMTH@cVHpRgSAonpciTTllQaQ1R4cqmMxhyEo1u2dwi0sNo/xsRFKvK5TVGk2svd4tdyhNOj1DIMXv7uqKxGvfvVvf28GPz566gTUccV9IyHcxZCENYD7zKcZx5kOcFjJi/AI "Python 2 – Try It Online") The top lambda computes \$A^{-1} = \frac{1}{\det(A)}\text{adj}(A)\$. `d(a)` computes the determinant and `c(a,i,j)` computes cofactors. [Answer] # [Scala](http://www.scala-lang.org/), ~~237~~ 232 bytes Uses the method from [Sisyphus's answer](https://codegolf.stackexchange.com/a/213913/95792). Go upvote that! ``` m=>{val h=m.indices Seq.iterate(m.transpose.map(_.map(_/m.flatten.map(x=>x*x).sum)),9999){v=>h.map(i=>h.map{j=>2*v(i)(j)-(h.map(k=>v(i).zip(m.transpose.apply(k))map(t=>t._1*t._2)sum),v.transpose.apply(j)).zipped.map(_*_).sum})}last} ``` [Try it online!](https://tio.run/##nZFbS8MwGIbv8yvCrvKVNpvzhGICgpd6tUsdI9syl65pY5OVaulvr2mqDNkQMZDT8x3zxq5EJrpimcqVw09C5VjWTuZri@@NwQ2qRIbVLZ7Jt@d@PhT7ZSbnc8z4CdZpxps@Yss0VflaraRF3oUqJ0vhJNHUlSK3prCSamHIYljHmm4y4XzdcK8Zr6MaqN1rgPjGD2gqxrfBqL4OTcr4NKqIApJCQgbjjvGe0A9lftQSxmTvZAfQOznGHV2cRX6ZQl8jro5cUwhJjFwPHUaL0E4LbSasa7v@kVo4zPCjso4gPOwXdBLj5DzGE4i/WTLA6xhfHeBlzwJCgJApVe6ynCjicwLVu5nz5JWMXvIReHuLxtEgbUmqeAvsHzom/PAlm6Ik9V0ywa7AQV5Usd/U/aO49EjdUDoEnJb4ZEDr22mjcfcJ "Scala – Try It Online") `h` is just a range from 0 until n to reuse later (mostly because Scala doesn't have matrix multiplication builtins). The function makes a sequence of 9999 elements and takes the last element. The first element is the transpose of `m` divided by the trace of `m` times its transpose. Subsequent elements are calculated with `2*v-v*m*v`, where `v` was the previous element. To calculate \$V\_0\$ (It turns out the trace of `m` times its transpose is just the sum of squares of all of `m`'s cells): ``` m.transpose.map( //For every row in m's transpose _.map( //For every cell in that row _ / //Divide it by (trace(M * M's transpose)) m.flatten //Turn m into a 1D list .map(x=>x*x) //Square each cell .sum)) //Add them up ``` To calculate subsequent elements, we use \$2V - (VA)V\$, but you have to map over `h` instead of over `v` itself: ``` h.map(i => //For every i in [0, n) h.map{j => //For every j in [0, n) 2*v(i)(j) - //2V at these coordinates minus <(v * m * v)[i][j]> }) //v*m*v at these coordinates (see explanation below) ``` To calculate `(v*m)[i]`: ``` h.map(k => //k is the index of a row in [0, n) v(i).zip( //Zip column i of v with m.transpose.apply(k) //Row k of m (apply is used for indexing here) ) map(t=>t._1*t._2) //Multiply v(i)(j) with m(k)(i) sum //Add then up ) ``` And getting the cross product of that with row `j` of `v` uses pretty much the same approach. --- # Scala, ~~346~~ 342 bytes Saved 4 bytes thanks to **@corvus\_192**! ``` type M=Seq[Seq[Double]] def c(m:M)={val I=m.indices;I.map(i=>I.map(j=>m(i)(j)*math.pow(-1,i+j)))} def d(m:M):(M,Double)=if(m.size<2)m->m(0)(0)else{val I=m.indices val M=I.map(i=>I.map{j=>d(I.filter(i!=_)map(k=>I.filter(j!=_)map(m(k))))._2}) c(M)->c(m).head.zip(M.head).map(t=>t._1*t._2).sum} def i(m:M)=d(m)._1.transpose.map(_.map(_/d(m)._2)) ``` [Try it in Scastie!](https://scastie.scala-lang.org/RihOhcl4QLuy8JaqEEzpGg) As you can see, I'm not very good at math. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 7 bytes ``` Inverse ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zOvLLWoOPV/QFFmXomCg59DenR1ta65joKuERADaSBlDGRZ1uooVEPYlmBBXRMgNjQACeuagZhAbApSqKNgAFQDFjcFKwaSJmAtpiBBA4gakHpDiA26RmDFJhAJkADIPAsQrq3liv3/HwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage/wiki), 3 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page) ``` æ*- ``` [Try it online.](https://tio.run/##y0rNyan8///wMi3d////R0eb6Oga6xjE6kTrAlnmOmZAlqkOiI4FAA) **Explanation:** ``` # Full program taking a single integer-matrix as argument æ* # Matrix exponentiation - # with -1 # (after which the result is output implicitly) ``` [Answer] # Excel, 29 bytes ``` =MINVERSE(OFFSET(A2,,,A1,A1)) ``` Straightforward application of the [MINVERSE()](https://support.microsoft.com/en-us/office/minverse-function-11f55086-adde-4c9f-8eb9-59da2d72efc6) function. It's boring but I got excited about Excel having a built-in for something. Input \$n\$ in `A1`, the matrix starting in `A2`, and the formula anywhere the spill won't interfere. [![Screenshot](https://i.stack.imgur.com/qFsgT.png)](https://i.stack.imgur.com/qFsgT.png) [Answer] # [Matlab](https://au.mathworks.com/products/matlab.html) ~~6~~ 3 bytes ``` inv ``` Computes and prints the inverse of a square matrix. Pretty boring in-built solution. Thanks to @Bubbler for the clarification and -3 bytes. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes ``` ≔Eθ∕Eθ§λκΣEXθ²ΣληFφUMηEκ⁻⊗μΣEθ×ΣEθ×§κς§ρπ§§ηπνIη ``` [Try it online!](https://tio.run/##ZY67bsMwDEV3fwVHCqABJ30NngxnyRAgQLsZHtRYjQTrkUi2279XpaRGC5QLeS5f9yS5PzmuY2xCUGeLB37BK8FOLWoQKzXT3g7iCzXByBjB62xuraP7FD4PbH9EzXIQSFYXH84DbqqqYpBmW2cMtwNKyoRjSsrOAXduftdiQPPnbDr4powI@E9YjaT1hf368gSX@@NVWbPMHQLL7lEXR6/shC0PE8rEMXZd90hQPhBUPUFXZngheM7wRHAr@z6Wi/4G "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Another port of @Sisyphus's answer. ``` ≔Eθ∕Eθ§λκΣEXθ²Σλη ``` Transpose the input and divide it by the sum of squares of all the elements. Sadly neither sum nor divide fully vectorise, so I have to divide a row at a time and calculate the sum via a nested loop. ``` Fφ ``` Repeat 1000 times, which should be enough for floating-point precision. ``` UMηEκ⁻⊗μΣEθ×ΣEθ×§κς§ρπ§§ηπν ``` Calculate the matrix multiplication and subtraction in-place. Charcoal doesn't have any vector or matrix operations, so we have to loop over the rows and columns manually, but there are a couple of places where we can share variables which saves us a couple of bytes each. ``` Iη ``` Output the array. (Note that each element is output on its own line and each row is double-spaced from the previous.) [Answer] # [MATL](https://github.com/lmendo/MATL), 4 bytes ``` -1Y^ ``` [Try it online!](https://tio.run/##y00syfn/X9cwMu7//2gTBV1jBQNrBV0gw1zBzFrBVAFIxQIA "MATL – Try It Online") ## Explanation ``` -1Y^ -1 : Push -1 onto the stack Y^ : Raise implicit input to -1 power ``` [Answer] # PARI/GP 8 bytes ``` f(A)=1/A ``` Built-in function; particularly efficient for matrices with integer matrix elements. Most likely, the method used is similar to the one described in this refererence: H. Haramotu, M. Matsumotu, [A p-adic algorithm for computing the inverse of integer matrices](https://doi.org/10.1016/j.cam.2008.07.044), Journal of Computational and Applied Mathematics, Volume 225, Issue 1, 1 March 2009, Pages 320-322. [Answer] # [SageMath](https://www.sagemath.org/), ~~14~~ ~~13~~ 11 bytes Saved a byte thanks to [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman)!!! Saved 2 bytes thanks to [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus)!!! ``` lambda M:~M ``` [Try it online!](https://sagecell.sagemath.org/?z=eJxLs43hyknMTUpJVPC1qvPl4ipJLS5RsFXITSwpyqzQiI420dE10TGN1YnWNdbRNdcxB7IMdMx0zGJjNbkKijLzSjRAOoBs2zQYCyxaoAkAz70bIw==&lang=sage&interacts=eJyLjgUAARUAuQ==) Inputs any square `matrix` and returns its inverse. [Answer] # [Ruby](https://www.ruby-lang.org/) `-rmatrix`, ~~23~~ 19 bytes ``` ->a{Matrix[*a].inv} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6x2jexpCizIlorMVYvM6@s9n@BQlp0dLSCiY6usY6CQaxOtC6Qaa6jYAZkKpjqKICZsbH//@UXlGTm5xX/1y3KBRsBAA "Ruby – Try It Online") Returns the result as a Ruby matrix object. -4 bytes from Dingus. [Answer] # [q](https://code.kx.com/), 3 bytes ``` inv ``` # k, 1 byte ``` ! ``` Does exactly as requested. Input must be a float matrix [Answer] # [Fortran (GFortran)](https://gcc.gnu.org/fortran/), 350 ~~376~~ bytes ``` real,allocatable,dimension(:,:)::A,B,U;read*,n;allocate(A(n,n));B=A;U=A;read*,((A(i,j),j=1,n),i=1,n) do i=1,n;do j=1,n;U(i,j)=merge(1,0,i==j);B(i,j)=merge(1.,1/A(i,j),A(i,j)==0);enddo;enddo do 4 l=1,99;do 4 i=1,n;do 4 j=1,n;s=U(i,j);do k=1,n;m=i;if(k/=m)s=s-A(i,k)*B(k,j);enddo;B(m,j)=s/A(i,m) 4 continue;print'(3(x,f9.6))',((B(i,j),j=1,n),i=1,n) end ``` [Try it Online!](https://tio.run/##bU/RboQgEHznK3g7uKx3Gu01SnjQf/AD6IkXVKARm/Tv7QqmSZM@wExmJzO7o1@3VbnsNSay76tWC6hl8U@1qY9Fw2CsdsF4xxpoeNO00EEv0DZcwYnTqVnLHDjORSdb0eNLBoa6gYnDJAscg4lABk8jE0jiRPTRJq1eX5oVkKNTTpj2R75BcT/zEkiZc6HdMPj0H8EVXTCxrkXkvzXVWRRkqjq0OSpWGmFGNt@l5UGG7Iie@bVj82FL6R2zR12I9ZaTij6924z70uJzNW67sJJ9w1jfHpxf8Oruv6sxat9LgqtkJc1JhvhOH4S@UYr4Aw)   ~~[376 bytes](https://tio.run/##bVBBboQwELvnFbltsgqFFXQriOZA/sAD0iVUgZBUQKX@nk4C6vbQy4xlW/ZohrBsi/bZx3CAfV@MdkI7Fx560@/OiN7Oxq82eNaIhjdNK5ToJNr6q/DkdBrWMi8851JBKztoyWFgyFsxcjHCDWVh0yJ9oAlJBEkhdmAWYORdssMtEfmTKCJxZOVQcHXacp3AU4Q/IjG@74NMM1ZW1GFXXcuEfw@ojhPkCkdXtE6JmcFKTJ5ymPkKaxYrJn5VbELbmavYHMvWPIozJxV9BL9Z/2XI52L9dmEl@xZD/XLn/IL/UP/9A6P2vSR4SlbSgmS43@id0FdKcf8A "Fortran (GFortran) – Try It Online")~~ Adapted from [here](http://www.uprh.edu/rbaretti/MatrixInv17mar2014.htm). Saved 26 bytes using `merge` instead of `if`. ]
[Question] [ My father who [was a really good APLer](https://youtu.be/pL8OQIR5cB4?t=3m16s) and taught me all the basics of APL (and much more), passed away on this day, five years ago. In preparation for [50 Years of APL](http://www.dyalog.com/50-years-of-apl.htm), I found [this patent letter](https://tidsskrift.dk/plugins/generic/pdfJsViewer/pdf.js/web/viewer.html?file=https%3A%2F%2Ftidsskrift.dk%2Fregistreringstidende-varemaerker%2Farticle%2Fdownload%2F95152%2F143241%2F#page=8) (translated for the convenience of those who do not read Danish) for a handwritten logo. It explains a major reason for APL never gaining a large user base – a reason which of course applies to all of this community's amazing golfing languages too: --- A 3497/77                           Req. 29th Aug. 1977 at 13 [![EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS …](https://i.stack.imgur.com/pEzT8.png)](https://i.stack.imgur.com/pEzT8.png) **Henri Brudzewsky,** engineering consultancy company, **Mindevej 28, Søborg,** **class 9**, including computers, especially APL coded computers, **class 42:** IT service agency company, especially during use of APL coded computers. --- # Task **Produce infinitely repeating output of the text `EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS` with no newlines.** You may begin the text with `EASIER` or `FASTER` or `FEWER`. [Answer] ## SVG(HTML5), 336 bytes ``` <svg width=500 height=500><defs><path id=p d=M49,250a201,201,0,0,1,402,0a201,201,0,0,1,-402,0></defs><text font-size="32"><textPath xlink:href=#p>EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS</textPath><animateTransform attributeName=transform type=rotate from=360,250,250 to=0,250,250 dur=9s repeatCount=indefinite> ``` Edit: Some people have found that the font doesn't quite fit for them so here is a version that allows you a few pixels of adjustment: ``` <p><input type=number value=0 min=0 max=9 oninput=p.setAttribute('d','M250,250m20_,0a20_,20_,0,1,1,-20_,-20_a20_,20_,0,1,1,-20_,20_a20_,20_,0,1,1,20_,20_a20_,20_,0,1,1,20_,-20_'.replace(/_/g,this.value))></p> <svg width=500 height=500><defs><path id=p d=M250,250m200,0a200,200,0,1,1,-200,-200a200,200,0,1,1,-200,200a200,200,0,1,1,200,200a200,200,0,1,1,200,-200></defs><text font-size="32"><textPath xlink:href=#p>EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS</textPath><animateTransform attributeName=transform type=rotate from=360,250,250 to=0,250,250 dur=9s repeatCount=indefinite> ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes ``` [‘æƒËRSˆ¾¥ƒŽÁˆ¾¡ŸÂ ‘? ``` [Try it online!](https://tio.run/nexus/05ab1e#@x/9qGHG4eZDy45NOtwdFHy67dC@Q0uPTTq693AjmL3w6I7DTYfXg9gKQJX2//8DAA "05AB1E – TIO Nexus") Explanation: ``` [‘æƒËRSˆ¾¥ƒŽÁˆ¾¡ŸÂ ‘? [ Start infinite loop ‘æƒËRSˆ¾¥ƒŽÁˆ¾¡ŸÂ ‘ Push the compressed string in uppercase, starting from FEWER, with a trailing space ? Print without trailing newline ``` [Answer] # PHP, 76 Bytes ``` for(;;)echo strtr(EASI0MMUNICATION1FAST0DING1FEW0DERS1,["ER CO"," MEANS "]); ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgSi0qyi@KL0otyC8qycxL16hzjffzD/F0dtW0/p@WX6Rhba2ZmpyRr1BcUlRSpOHqGOxp4Osb6ufp7Bji6e9n6OYYHGLg4unnbujmGm7g4hoUbKgTreQapODsr6SjpODr6ugXrKAUCzTsPwA "PHP – TIO Nexus") [Answer] # Vim 69 bytes ``` qqAFEWER CODERS MEANS EASIER COMMUNICATION M<C-n> FASTER CODING M<C-n> <esc>@qq@q ``` [Answer] ## HTML, 122 bytes. Sorry, can't help myself. ``` <marquee style="width:5em;word-spacing:5em;">EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS </marquee> ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~82~~ 81 bytes *-1 byte thanks to Leaky Nun.* I'm probably doing something wrong but it's really late so meh. Note the trailing comma. ``` while 1:print'FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS', ``` [Try it online!](https://tio.run/nexus/python2#@1@ekZmTqmBoVVCUmVei7uYa7hqk4Ozv4hoUrODr6ugXrODqGOwJFvP1DfXzdHYM8fT3g0q5OQaHQJR7@rlDxNR1/v//mpevm5yYnJEKAA "Python 2 – TIO Nexus") ## Another solution, 85 bytes I can probably golf this further. ``` while 1:print'%sER CO%s MEANS'*3%('FEW','DERS',' EASI','MMUNICATION',' FAST','DING'), ``` [Try it online!](https://tio.run/nexus/python2#@1@ekZmTqmBoVVCUmVeirlrsGqTg7K9arODr6ugXrK5lrKqh7uYarq6j7uIaFAykFFwdgz2BtK9vqJ@ns2OIp78fSNTNMTgEpMjTz11dU@f/fwA "Python 2 – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~33~~ 29 bytes 4 bytes thanks to Erik the Outgolfer. ``` “©%5ÐƬwȮh¬Þ6.⁷ḷḊḥṫɠlḶṀġß»Œu⁶¢ ``` [Try it online!](https://tio.run/nexus/jelly#AT4Awf//4oCcwqklNcOQxqx3yK5owqzDnjYu4oG34bi34biK4bil4bmryaBs4bi24bmAxKHDn8K7xZJ14oG2wqL//w "Jelly – TIO Nexus") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 70 bytes ``` "FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS "w↰ ``` [Try it online!](https://tio.run/nexus/brachylog2#@6/k5hruGqTg7O/iGhSs4Ovq6Bes4OoY7AkW8/UN9fN0dgzx9PeDSrk5BodAlHv6uUPFlMoftW34/x8A "Brachylog – TIO Nexus") ## How it works ``` "..."w↰ "..." generate the string "..." w print to STDOUT without trailing newline ↰ do the whole thing all over again ``` [Answer] # HTML/CSS (firefox only), ~~179~~ ~~177~~ ~~183~~ ~~176~~ 173 bytes ``` <b id=a>EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS </b>E<a><style>*{margin:0;}a{position:fixed;left:0;right:0;height:1em;background:-moz-element(#a)} ``` Certianly nowhere near the lowest scores, I just thought it would be fun to get infinite repitition in HTML/CSS, without any JS involved :) ## Changelog: * Removed quotes around id attribute * added "round" background-repeat to stretch the text so it wraps correctly * changed to single-line output * replace `width:100%` style with `right:0` to save 3 bytes [Answer] # [Python 3](https://docs.python.org/3/), 87 bytes ``` while 1:print(end="FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ") ``` [Try it online!](https://tio.run/nexus/python3#@1@ekZmTqmBoVVCUmVeikZqXYqvk5hruGqTg7O/iGhSs4Ovq6Bes4OoY7AkW8/UN9fN0dgzx9PeDSrk5BodAlHv6uUPFlDT//wcA "Python 3 – TIO Nexus") [Answer] # [C (gcc)](https://gcc.gnu.org/), 92 bytes ``` main(){for(;printf("FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS "););} ``` [Try it online!](https://tio.run/nexus/c-gcc#@5@bmJmnoVmdll@kYV1QlJlXkqah5OYa7hqk4Ozv4hoUrODr6ugXrODqGOwJFvP1DfXzdHYM8fT3g0q5OQaHQJR7@rlDxZQ0rTWta///BwA "C (gcc) – TIO Nexus") [Answer] # [LOLCODE](http://lolcode.org/), 116 bytes ``` HAI 1 IM IN YR O VISIBLE "FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS "! IM OUTTA YR O KTHXBYE ``` [Try it online!](https://tio.run/nexus/lolcode#LYzLDYAwDMXunSKwASMECPAETaUmfLr/IEV8rrblujCoC4gEpZIphQOGfhNqJzkl05BGyUZRWI2EDS@LcVcM7Ej6q4nNvxw6/6xtnnHa3fl7r75cfZFabw "LOLCODE – TIO Nexus") [Answer] # Ruby, 77 bytes assigning `" MEANS "` to a variable saved all of 1 byte :-) ``` loop{$><<"EASIER COMMUNICATION#{m=" MEANS "}FASTER CODING#{m}FEWER CODERS"+m} ``` [Answer] # JavaScript (ES6), ~~90~~ 87 bytes ``` while(1)console.log`EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS ` ``` --- ## Functioning Alternative, 100 bytes "Functioning" here meaning "won't crash your browser" (for a while, at least)! ``` setInterval(_=>console.log`EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS `,1) ``` [Answer] # [Befunge](https://github.com/catseye/Befunge-93), 73 bytes ``` " SNAEM GNIDOC RETSAF SNAEM NOITACINUMMOC REISAE SNAEM SREDOC REWEF">:#,_ ``` [Try it online!](https://tio.run/nexus/befunge#@6@kEOzn6Oqr4O7n6eLvrBDkGhLs6AYV8/P3DHF09vQL9fUFS3kGO7pCpYKDXCHKw13dlOyslHXi//8HAA "Befunge – TIO Nexus") [Answer] # Octave, 86 bytes ``` while fprintf('FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ')end ``` **Explanation:** This is fairly self-explanatory. The only real "trick" here is to use `while fprintf`. When `fprintf` is given a return argument, it will return the number of characters printed, and all non-zero numbers are considered `true` in Octave, so the loop condition will always be true. --- I desperately tried to make the more interesting approach shorter, but it turned out to be 9 bytes longer, unfortunately: ``` while fprintf('FEW%sDERS%sEASI%sMMUNICATION%sFAST%sDING%s',{'ER CO',' MEANS '}{'ababab'-96})end ``` This tries to insert the strings `'ER CO'` and `' MEANS'` into the string at the correct locations, using direct indexing where `'ababab'-96` is a shorter version of `[1 2 1 2 1 2]`. This was a bit shorter (93 bytes), but still longer than the naive approach ``` while fprintf('FEWER CODERS%sEASIER COMMUNICATION%sFASTER CODING%s',{' MEANS '}{[1,1,1]})end ``` And another one (89 bytes), using Level River St's approach: ``` while fprintf(['FEWER CODERS',s=' MEANS ','EASIER COMMUNIDATION',s,'FASTER CODING',s])end ``` This should work in theory, for one less byte than the original solution, but it fails for some strange reason: ``` while fprintf"FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS " end ``` This uses the buggy feature that `fprintf('abc def')` is equivalent to `fprintf"abc def"`. The `end` must be on the next line, but it's still one byte shorter since two parentheses are skipped. And one more for 87: ``` while fprintf('FEWER CODERS%sEASIER COMMUNICATION%sFASTER CODING%s',k=' MEANS ',k,k)end ``` --- Well, don't say I didn't try :) [Answer] ## [Alice](https://github.com/m-ender/alice), 70 bytes ``` " SNAEM "k"SREDOC REWEF"e0j"GNIDOC RETSAF"e0j"NOITACINUMMOC REISAE"d&o ``` [Try it online!](https://tio.run/nexus/alice#@6@kEOzn6OqroJStFBzk6uLvrBDkGu7qppRqkKXk7ucJEQgJdoSI@Pl7hjg6e/qF@vqCJTyDHV2VUtTy//8HAA "Alice – TIO Nexus") ### Explanation Unfortunately, reusing the `MEANS` (with spaces) only saves a single byte over just printing the whole thing in one go. Consequently, extracting the `ER CO` would actually cost a byte (or probably more, because it would be slightly more expensive to extract another section). ``` " SNAEM " Push the code points of " MEANS " in reverse. k If there is a return address on the return address stack (which there isn't right now), pop it and jump there. "SREDOC REWEF" Push the code points of "FEWER CODERS" in reverse. e0j Jump to the beginning of the line, pushing the location of the j to the return address stack. Hence, we push the code points of " MEANS " again, but then the k pops the return address and jumps back here. "GNIDOC RETSAF" Push the code points of "FASTER CODING" in reverse. e0j Jump to the beginning of the line again. "NOITACINUMMOC REISAE" Push the code points of "EASIER COMMUNICATION" in reverse. d Push the stack depth. &o Print that many bytes from the top of the stack. Afterwards the IP wraps around to the first column and the program starts over. ``` [Answer] ## C#, 102 bytes ``` _=>{for(;;)System.Console.Write("EASIER COMMUNICATION{0}FASTER CODING{0}FEWER CODERS{0}"," MEANS ");}; ``` [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 85 bytes ``` BEGIN{for(c=" MEANS ";;)printf"EASIER COMMUNICATION"c"FASTER CODING"c"FEWER CODERS"c} ``` [Try it online!](https://tio.run/nexus/awk#@@/k6u7pV52WX6SRbKuk4Ovq6BesoGRtrVlQlJlXkqbk6hjs6Rqk4Ozv6xvq5@nsGOLp76eUrOTmGBwCFnbx9HMH8V3DIVzXoGCl5Nr//wE "AWK – TIO Nexus") Apparently I came up with the same shortcut as others. All other substitutions take up too much space. :( [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~64~~ 60 bytes ``` +>(`$ EASI_MMUNICATION@FAST_DING@FEW_DERS@ @ MEANS _ ER CO ``` [Try it online!](https://tio.run/##K0otycxLNPz/X9tOI0GFy9Ux2DPe1zfUz9PZMcTT38/BzTE4JN7F08/dwc01PN7FNSjYgcuBS8HX1dEvWIErnss1SMHZ//9/AA "Retina – Try It Online") ### Explanation The program consists of three grouped replacement stages. The group as a whole is applied repeatedly until the output stops changing (which it never will) and the output is printed after each time (rather than just at the end, because there will be no end) The first stage adds the string `EASI_MMUNICATION@FAST_DING@FEW_DERS@` at the end of the input. The input starts out empty, but keeps growing. The second stage replaces each of those `@`s with the string `MEANS` (surrounded by a space on each side). The third stage replaces the `_`s with the string `ER CO`. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 69 bytes ``` Wp"FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ``` [Try it online!](https://tio.run/nexus/pyth#@x9eoOTmGu4apODs7@IaFKzg6@roF6zg6hjsCRbz9Q3183R2DPH094NKuTkGh0CUe/q5Q8X@/wcA "Pyth – TIO Nexus") ## How it works ``` Wp"... W while the following is true: (do nothing) p print the following and return the following "... ``` [Answer] # [Lua](https://www.lua.org), 92 bytes ``` while 1 do io.write("FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ")end ``` [Try it online!](https://tio.run/nexus/lua#@1@ekZmTqmCokJKvkJmvV16UWZKqoeTmGu4apODs7@IaFKzg6@roF6zg6hjsCRbz9Q3183R2DPH094NKuTkGh0CUe/q5Q8WUNFPzUv7/BwA "Lua – TIO Nexus") [Answer] # [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 114 bytes ``` static void f(){while(1>0)System.out.print("FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ");} ``` [Try it online!](https://tio.run/nexus/java-openjdk9#S85JLC5W8E3MzFOo5lIAgoLSpJzMZIXiksQSIFWWn5mikAuU1QguKcrMS4@OVUgsSi/WhCoGgTQNTWswp/Y/siagcHV5RmZOqoahnYFmcGVxSWquXn5piV4B0JwSDSU313DXIAVnfxfXoGAFX1dHv2AFV8dgT7CYr2@on6ezY4invx9Uys0xOASi3NPPHSqmpGld@5@r9v/XvHzd5MTkjFQA "Java (OpenJDK 9) – TIO Nexus") Stop the execution after a few seconds because it does not know when to stop. [Answer] ## C, 86 bytes ``` f(){printf("FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ");f();} ``` See it [work online](https://tio.run/nexus/c-gcc#@5@moVldUJSZV5KmoeTmGu4apODs7@IaFKzg6@roF6zg6hjsCRbz9Q3183R2DPH094NKuTkGh0CUe/q5Q8WUNK2BBlrX/gcaqJCbmJmnoVCWn5mioMlVzcUJkuGq/f81L183OTE5IxUA). [Answer] # [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html), 76 bytes ``` while(1)"EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS " ``` [Answer] # [Perl 6](https://perl6.org), ~~81 80~~ 79 bytes ``` print ('EASIER COMMUNICATION','FASTER CODING','FEWER CODERS'X'MEANS'),' 'for ^Inf ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u2/l9QlJlXoqCh7uoY7OkapODs7@sb6ufp7Bji6e@nrqPu5hgcAhZ28fRzB/FdwyFc16Bg9Qh1X1dHv2B1TR11BfW0/CKFOM@8tP//AQ "Perl 6 – TIO Nexus") ``` loop {print ('EASIER COMMUNICATION','FASTER CODING','FEWER CODERS'X'MEANS'),' '} ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u2/p@Tn1@gUF1QlJlXoqCh7uoY7OkapODs7@sb6ufp7Bji6e@nrqPu5hgcAhZ28fRzB/FdwyFc16Bg9Qh1X1dHv2B1TR11BfXa//8B "Perl 6 – TIO Nexus") ``` loop {print [~] 'EASIER COMMUNICATION','FASTER CODING','FEWER CODERS'X'MEANS '} ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u2/p@Tn1@gUF1QlJlXohBdF6ug7uoY7OkapODs7@sb6ufp7Bji6e@nrqPu5hgcAhZ28fRzB/FdwyFc16Bg9Qh1X1dHv2AF9dr//wE "Perl 6 – TIO Nexus") [Answer] # [MATL](https://github.com/lmendo/MATL), 68 bytes ``` `'EASIER COMMUNICATION*FASTER CODING*FEWER CODERS*'42' MEANS 'Zt&YDT ``` [Try it online!](https://tio.run/nexus/matl#@5@g7uoY7OkapODs7@sb6ufp7Bji6e@n5eYYHAIWdPH0c9dycw2HcFyDgrXUTYzUFXxdHf2CFdSjStQiXUL@/wcA "MATL – TIO Nexus") ### Explanation ``` ` % Do...while 'EASIER COMMUNICATION*FASTER CODING*FEWER CODERS*' % Push this string 42 % Push 42 (ASCII for '*') ' MEANS ' % Push this string Zt % String replacement &YD % printf to STDOUT T % Push true as loop condition % End (implicit) ``` [Answer] # Axiom, ~~92~~ 89 bytes ``` repeat fortranLiteral"EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS " ``` insert in one line to Axiom window. Possible there is one function shorter than "fortranLiteral" that not write "\n" [Answer] # [Blank](https://esolangs.org/wiki/Blank), 267 bytes ``` [70][69][87][69][82][32][67][79][68][69][82][83][32][77][69][65][78][83][32][69][65][83][73][69][82][32][67][79][77][77][85][78][73][67][65][84][73][79][78][32][77][69][65][78][83][32][70][65][83][84][69][82][32][67][79][68][73][78][71][32][77][69][65][78][83][32]{p} ``` Pushes `FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS` to the stack, then prints it. Never terminates as no `{@}` Also fun fact, I used the following [Braingolf](https://esolangs.org/wiki/Braingolf) script to generate this code ``` "FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS "l>[<$_<91+2^9-@_ 91+2^7-@l>]"{p}"@3 ``` [Answer] # Groovy 79 bytes ``` m=" MEANS";for(;;)print"EASIER COMMUNICATION$m FASTER CODING$m FEWER CODERS$m " ``` Uses groovy's string interpolation. ]
[Question] [ Lower level languages, such as C and C++ actually have no concept of multidimensional arrays. (Other than vectors and dynamic arrays) When you create a multidimensional array with ``` int foo[5][10]; ``` This is actually just [syntactic sugar](https://en.wikipedia.org/wiki/Syntactic_sugar). What C really does is create a single contiguous array of *5 \* 10* elements. This ``` foo[4][2] ``` is also syntactic sugar. This really refers to the element at ``` 4 * 10 + 2 ``` or, the 42nd element. In general, the index of element `[a][b]` in array `foo[x][y]` is at ``` a * y + b ``` The same concept applies to 3d arrays. If we have `foo[x][y][z]` and we access element `[a][b][c]` we are really accessing element: ``` a * y * z + b * z + c ``` This concept applies to *n*-dimensional arrays. If we have an array with dimensions `D1, D2, D3 ... Dn` and we access element `S1, S2, S3 ... Sn` the formula is ``` (S1 * D2 * D3 ... * Dn) + (S2 * D3 * D4 ... * Dn) + (S3 * D4 ... * Dn) ... + (Sn-1 * Dn) + Sn ``` # The challenge You must write a program or function that calculates the index of a multidimensional array according to the formula above. Input will be two arrays. The first array is the dimensions, and the second array is the indices. The length of these two arrays will always be equal and at least 1. You can safely assume that every number in the arrays will be an non-negative integer. You can also assume that you will not get a `0` in the dimension array, although a `0` *might* be in the indices. You can also assume that indices will not be larger than the dimensions. # Test IO ``` Dimensions: [5, 10] Indices: [4, 2] Output: 42 Dimensions: [10, 10, 4, 62, 7] Indices: [1, 2, 3, 4, 5] Output: 22167 Dimensions: [5, 1, 10] Indices: [3, 0, 7] Output: 37 Dimensions: [6, 6, 6, 6, 6, 6, 6, 6, 6, 6] Indices: [3, 1, 5, 5, 3, 0, 5, 2, 5, 4] Output: 33570178 ``` [Answer] # APL, 1 byte ``` ⊥ ``` Test it on [TryAPL](http://tryapl.org/?a=f%20%u2190%20%u22A5%20%u22C4%205%2010%20f%204%202%20%u22C4%2010%2010%204%2062%207%20f%201%202%203%204%205%20%u22C4%205%201%2010%20f%203%200%207%20%u22C4%206%206%206%206%206%206%206%206%206%206%20f%203%201%205%205%203%200%205%202%205%204&run). [Answer] # J, 2 bytes ``` #. ``` Where there's an APL, there's a J! Kind of. Takes dimensions as left arg and index as right arg. ["Indexing a multidimensional array is essentially mixed base conversion."](https://codegolf.stackexchange.com/questions/79609/index-of-a-multidimensional-array#comment195189_79617) [Answer] ## JavaScript (ES6), 34 bytes ``` (d,a)=>a.reduce((r,i,j)=>r*d[j]+i) ``` Surely `reduce` must be better than `map`. [Answer] # Python, 43 bytes ``` f=lambda x,y:x>[]and y.pop()+x.pop()*f(x,y) ``` Test it on [Ideone](http://ideone.com/sYEJFA). [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ṇ;żḅ@/ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmGO8W84biFQC8&input=&args=WzEwLCAxMCwgNCwgNjIsIDdd+WzEsIDIsIDMsIDQsIDVd) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmGO8W84biFQC8Kw6ciRw&input=&args=WzUsIDEwXSwgWzEwLCAxMCwgNCwgNjIsIDddLCBbNSwgMSwgMTBdLCBbNiwgNiwgNiwgNiwgNiwgNiwgNiwgNiwgNiwgNl0+WzQsIDJdLCBbMSwgMiwgMywgNCwgNV0sIFszLCAwLCA3XSwgWzMsIDEsIDUsIDUsIDMsIDAsIDUsIDIsIDUsIDRd). ### How it works ``` Ṇ;żḅ@/ Main link. Arguments: D (list of dimensions), I (list of indices) Ṇ Yield 0, the logical NOT of D. ż Zip D with I. If D = [10, 10, 4, 62, 7] and I = [1, 2, 3, 4, 5], this yields [[10, 1], [10, 2], [4, 3], [62, 4], [7, 5]]. ; Concatenate, yielding [0, [10, 1], [10, 2], [4, 3], [62, 4], [7, 5]]. ḅ@/ Reduce by swapped base conversion to integer. [10, 1] in base 0 is 0 × 10 + 1 = 1. [10, 2] in base 1 is 1 × 10 + 2 = 12. [ 4, 3] in base 12 is 12 × 4 + 3 = 51. [62, 4] in base 51 is 51 × 62 + 4 = 3166. [ 7, 5] in base 3166 is 3166 × 7 + 5 = 22167. ``` [Answer] # Pyth, 10 bytes ``` e.b=+*ZNYC ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=e.b%3D%2B*ZNYC&input=[5%2C%2010]%2C%20[4%2C%202]&test_suite_input=[5%2C%2010]%2C%20[4%2C%202]%0A[10%2C%2010%2C%204%2C%2062%2C%203]%2C%20[1%2C%202%2C%203%2C%204%2C%205]%0A[5%2C%201%2C%2010]%2C%20[3%2C%200%2C%207]%0A[6%2C%206%2C%206%2C%206%2C%206%2C%206%2C%206%2C%206%2C%206%2C%206]%2C%20[3%2C%201%2C%205%2C%205%2C%203%2C%200%2C%205%2C%202%2C%205%2C%204]&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=e.b%3D%2B*ZNYC&input=[5%2C%2010]%2C%20[4%2C%202]&test_suite=1&test_suite_input=[5%2C%2010]%2C%20[4%2C%202]%0A[10%2C%2010%2C%204%2C%2062%2C%203]%2C%20[1%2C%202%2C%203%2C%204%2C%205]%0A[5%2C%201%2C%2010]%2C%20[3%2C%200%2C%207]%0A[6%2C%206%2C%206%2C%206%2C%206%2C%206%2C%206%2C%206%2C%206%2C%206]%2C%20[3%2C%201%2C%205%2C%205%2C%203%2C%200%2C%205%2C%202%2C%205%2C%204]&debug=0) Using Horner's method to calculate the index. [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` PiPZ}N$X] ``` This uses 1-based indexing (now allowed by the challenge), which is the natural choice in MATL. To compare with the test cases in the challenge, add `1` to each entry in the input index vector, and subtract `1` from the output. [**Try it online!**](http://matl.tryitonline.net/#code=UGlQWn1OJFhd&input=WzEwLCAxMCwgNCwgNjIsIDddClsyLCAzLCA0LCA1LCA2XQ) ### Explanation The code is based on the builtin `X]` function, which converts multidimensional indices to a single, linear index (like Matlab or Octave's `sub2ind` function). ``` P % Take dimension vector implicitly. Reverse iP % Take vector of indices. Reverse Z} % Split vector into its elements N$X] % Convert indices to linear index (`sub2ind` function). Implicitly display ``` [Answer] # Julia, ~~29~~ 27 bytes ``` x%y=prod(x)÷cumprod(x)⋅y ``` [Try it online!](http://julia.tryitonline.net/#code=eCV5PXByb2QoeCnDt2N1bXByb2QoeCnii4V5CgpwcmludGxuKFs1LCAxMF0lWzQsIDJdKQpwcmludGxuKFsxMCwgMTAsIDQsIDYyLCA3XSVbMSwgMiwgMywgNCwgNV0pCnByaW50bG4oWzUsIDEsIDEwXSVbMywgMCwgN10pCnByaW50bG4oWzYsIDYsIDYsIDYsIDYsIDYsIDYsIDYsIDYsIDZdJVszLCAxLCA1LCA1LCAzLCAwLCA1LCAyLCA1LCA0XSk&input=) [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` 4L)1hPYpP*s ``` This uses 0-based indexing, as in the original challenge. [**Try it online!**](http://matl.tryitonline.net/#code=NEwpMWhQWXBQKnM&input=WzEwLCAxMCwgNCwgNjIsIDddClsxLCAyLCAzLCA0LCA1XQ) ### Explanation The code explicitly does the required multiplications and additions. ``` 4L) % Take first input array implicitly. Remove its first entry 1h % Append a 1 PYpP % Cumulative product from right to left * % Take second input array implicitly. Multiply the two arrays element-wise s % Sum of resulting array. Implicitly display ``` [Answer] # Python, 85 bytes ``` lambda a,b:sum(b[i]*eval('*'.join(str(n)for n in a[i+1:])or'1')for i in range(len(a))) ``` I'll probably get my butt kicked by the better python golfers out there. [Answer] # Python 3.5, 69 ``` lambda d,i:sum(eval("*".join(map(str,[z,*d])))for z in i if d.pop(0)) ``` Test [here](https://repl.it/CO8G) [Answer] ## Haskell, 34 bytes ``` a#b=sum$zipWith(*)(0:b)$scanr(*)1a ``` Usage example: `[10,10,4,62,7] # [1,2,3,4,5]` -> `22167`. How it works: ``` scanr(*)1a -- build partial products of the first parameter from the right, -- starting with 1, e.g. [173600,17360,1736,434,7,1] (0:b) -- prepend 0 to second parameter, e.g. [0,1,2,3,4,5] zipWith(*) -- multiply both lists elementwise, e.g. [0,17360,3472,1302,28,5] sum -- calculate sum ``` [Answer] # C++, 66 bytes A quick macro: ``` #include<stdio.h> #define F(d,i) int x d;printf("%d",&x i-(int*)x) ``` Use like: ``` int main(){ F([5][1][10], [3][0][7]); } ``` This may be a bit of an abuse of the rules. Creates an array with the given size, than checks to see how far the given indexes offset the pointer. Outputs to STDOUT. This feels so dirty... But I just love the fact that this is valid. [Answer] ## Mathematica, 27 bytes ``` #~FromDigits~MixedRadix@#2& ``` An unnamed function which takes the list of indices as the first argument and the list of dimensions second. Based on the same observation as Dennis's APL answer that computing the index is really just a mixed-base conversion. [Answer] # Octave, ~~58~~ 54 bytes *Thanks to @AlexA. for his suggestion, which removed 4 bytes* ``` @(d,i)reshape(1:prod(d),flip(d))(num2cell(flip(i)){:}) ``` Input and output are 1-based. To compare with the test cases, add `1` ot each entry in the input and subtract `1` from the output. This is an anonymous function. To call it, assign it to a variable. [**Try it here**](http://ideone.com/NNpIQR). ### Explanation This works by actually building the multidimensional array (`reshape(...)`), filled with values `1`, `2`, ... in linear order (`1:prod(d)`), and then indexing with the multidimensional index to get the corrresponding value. The indexing is done by converting the input multidimensional index `i` into a cell array (`num2cell(...)`) and then to a comma-separated list (`{:}`). The two `flip` operations are needed to adapt the order of dimensions from C to Octave. [Answer] # CJam, 7 bytes ``` 0q~z+:b ``` [Try it online!](http://cjam.tryitonline.net/#code=MHF-eis6Yg&input=W1sxMCAxMCA0IDYyIDddIFsxIDIgMyA0IDVdXQ) ### How it works ``` 0 e# Push 0 on the stack. q e# Read and push all input, e.g., "[[10 10 4 62 7] [1 2 3 4 5]]". ~ e# Eval, pushing [[10 10 4 62 7] [1 2 3 4 5]]. z e# Zip, pushing [[10 1] [10 2] [4 3] [62 4] [7 5]]. + e# Concatenate, pushing [0 [10 1] [10 2] [4 3] [62 4] [7 5]] :b e# Reduce by base conversion. e# [10 1] in base 0 is 0 * 10 + 1 = 1. e# [10 2] in base 1 is 1 * 10 + 2 = 12. e# [ 4 3] in base 12 is 12 * 4 + 3 = 51. e# [62 4] in base 51 is 51 * 62 + 4 = 3166. e# [ 7 5] in base 3166 is 3166 * 7 + 5 = 22167. ``` [Answer] # Haskell, 47 bytes Two equal length solutions: ``` s(a:b)(x:y)=a*product y:s b y s _ _=[] (sum.).s ``` Called like: `((sum.).s)[4,2][5,10]`. Here's an infix version: ``` (a:b)&(x:y)=a*product y:b&y _ & _=[] (sum.).(&) ``` [Answer] # Octave, ~~47~~/~~43~~/31 bytes `@(d,i)sub2ind(flip(d),num2cell(flip(i+1)){:})-1` [Test it here](https://ideone.com/E9S01o). Having said that, as it was asked in a [comment](https://codegolf.stackexchange.com/questions/79609/index-of-a-multidimensional-array#comment195179_79609), 1-based indexing was said to be OK when this is natural to the language being used. In this case, we can save 4 bytes: `@(d,i)sub2ind(flip(d),num2cell(flip(i)){:})` In analogy, I argue that if the objective of the code is to linearly index an array **within that language**, the whole flipping around and accounting for MATLAB/Octave's column major order should not be necessary, either. In that case, my solution becomes `@(d,i)sub2ind(d,num2cell(i){:})` [Test that one here](https://ideone.com/2avXAb). [Answer] # Mathematica, 47 bytes ``` Fold[Last@#2#+First@#2&,First@#,Rest/@{##}]& ``` (Unicode is U+F3C7, or `\[Transpose]`.) For this, I rewrote the expression as *D**n*(*D**n*-1( ⋯ (*D*3(*D*2*S*1 + *S*2) + *S*3) ⋯ ) + *S**n*-1) + *S**n*. Just `Fold`s the function over both lists. [Answer] ## Actually, 13 bytes ``` ;pX╗lr`╜tπ`M* ``` [Try it online!](http://actually.tryitonline.net/#code=O3BY4pWXbHJg4pWcdM-AYE0q&input=WzEsIDIsIDMsIDQsIDVdClsxMCwgMTAsIDQsIDYyLCA3XQ) This program takes the list of indices as the first input and the list of dimensions as the second input. Explanation: ``` ;pX╗lr`╜tπ`M* ;pX╗ push dims[1:] to reg0 lr` `M map: for n in range(len(dims)): ╜tπ push product of last n values in reg0 * dot product of indices and map result ``` [Answer] ## Racket 76 bytes ``` (λ(l i(s 0))(if(null? i)s(f(cdr l)(cdr i)(+ s(*(car i)(apply *(cdr l))))))) ``` Ungolfed: ``` (define f (λ (ll il (sum 0)) (if (null? il) sum (f (rest ll) (rest il) (+ sum (* (first il) (apply * (rest ll)))))))) ``` Testing: ``` (f '(5 10) '(4 2)) (f '(10 10 4 62 7) '(1 2 3 4 5)) (f '(5 1 10) '(3 0 7)) ``` Output: ``` 42 22167 37 ``` [Answer] ## Javascript, 119 79 bytes ``` x=(d,i)=>{a=0;for(m in d){m*=1;a+=i[m];if(m!=i.length-1){a*=d[m+1];}}return a;} ``` [Try it online!](https://tio.run/##HcjJDoMgFEDRX3ndgaKRDnZBXn@EsCCCloahQduYGL@dDoubnNyHfut5yO65NDEZW8qKxDBH8bZp7MSYMgngIhi6hQq50DU6GZRwIwkHdK23cVruDaebrtDIUHMl9j3b5ZUjaLGXIcU5edv6NJGVSN4x@HVm0B8ZXBWTnMFXp/@7KEpF@QA) [Answer] # C#, 73 bytes ``` d=>i=>{int n=d.Length,x=0,y=1;for(;n>0;){x+=y*i[--n];y*=d[n];}return x;}; ``` Full program with test cases: ``` using System; namespace IndexOfAMultidimensionalArray { class Program { static void Main(string[] args) { Func<int[],Func<int[],int>>f= d=>i=>{int n=d.Length,x=0,y=1;for(;n>0;){x+=y*i[--n];y*=d[n];}return x;}; int[] dimensions, indices; dimensions =new int[]{5, 10}; indices=new int[]{4,2}; Console.WriteLine(f(dimensions)(indices)); //42 dimensions=new int[]{10, 10, 4, 62, 7}; indices=new int[]{1, 2, 3, 4, 5}; Console.WriteLine(f(dimensions)(indices)); //22167 dimensions=new int[]{5, 1, 10}; indices=new int[]{3, 0, 7}; Console.WriteLine(f(dimensions)(indices)); //37 dimensions=new int[]{6, 6, 6, 6, 6, 6, 6, 6, 6, 6}; indices=new int[]{3, 1, 5, 5, 3, 0, 5, 2, 5, 4}; Console.WriteLine(f(dimensions)(indices)); //33570178 } } } ``` [Answer] # Perl 6, 39 bytes ``` ->\d,\i{sum i.map:{[×] $_,|d[++$ ..*]}} ``` A rather naive golf here, just squished a anonymous sub. Perl 6 has an anonymous state variable `$` which is useful for creating a counter in a loop (eg, using post-increment `$++` or pre-increment `++$`). I pre-increment this state variable to increment the starting index of the dimension array slice inside a map. Here's a ungolfed function that creates the sub-lists ``` sub md-index(@dim, @idx) { @idx.map(-> $i { $i, |@dim[++$ .. *] }) } say md-index([10, 10, 4, 62, 7], [1, 2, 3, 4, 5]); # OUTPUT: ((1 10 4 62 7) (2 4 62 7) (3 62 7) (4 7) (5)) ``` Then it's just a matter of reducing the sub-lists with the multiplication (`×`) operator, and `sum`ing the results. ``` sub md-index(@dim, @idx) { @idx.map(-> $i { [×] $i, |@dim[++$ .. *] }).sum } say md-index([10, 10, 4, 62, 7], [1, 2, 3, 4, 5]); # OUTPUT: 22167 ``` [Answer] # Perl, 71 bytes ``` sub{$s+=$_[1][-$_]*($p*=$_[0][1-$_])for($p=$_[0][$s=0]=1)..@{$_[0]};$s} ``` Ungolfed: ``` sub { my $s = 0; my $p = 1; $_[0]->[0] = 1; for (1 .. @{$_[1]}) { $p *= $_[0]->[1 - $_]; $s += $_[1]->[-$_] * $p; } return $s; } ``` [Answer] # C++17, ~~133~~ 115 bytes -18 bytes for using `auto...` ``` template<int d,int ...D>struct M{int f(int s){return s;}int f(int s,auto...S){return(s*...*D)+M<D...>().f(S...);}}; ``` Ungolfed: ``` template <int d,int ...D> //extract first dimension struct M{ int f(int s){return s;} //base case for Sn int f(int s, auto... S) { //extract first index return (s*...*D)+M<D...>().f(S...); //S_i * D_(i+1) * D(i+2) * ... + recursive without first dimension and first index } }; ``` Usage: ``` M<5,10>().f(4,2) M<10,10,4,62,7>().f(1,2,3,4,5) ``` ## Alternative, only functions, 116 bytes ``` #define R return #define A auto A f(A d){R[](A s){R s;};}A f(A d,A...D){R[=](A s,A...S){R(s*...*D)+f(D...)(S...);};} ``` Ungolfed: ``` auto f(auto d){ return [](auto s){ return s; }; } auto f(auto d, auto...D){ return [=](auto s, auto...S){ return (s*...*D)+f(D...)(S...); }; } ``` Usage: ``` f(5,10)(4,2) f(10,10,10)(4,3,2) f(10,10,4,62,7)(1,2,3,4,5) ``` ]
[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/23860/edit). Closed 4 years ago. [Improve this question](/posts/23860/edit) Your task is **simple**. Determine if one string equals the other (not address, the value) without the use of equality operators (such as `==`, `===`, or `.equal()`) or inequality (`!=`, `!==`) anything similar for other languages. This means anywhere! You may not use these operators anywhere in the code. You may however, you use toggles such as `!exp` as you're not directly comparing the `exp != with something else`. In addition, you may not use any functions such as [strcmp](https://www.php.net/strcmp), [strcasecmp](https://www.php.net/manual/en/function.strcasecmp.php), etc. As for comparison operators (`>=`, `<=`, `>`, `<`), they are also **disallowed**. I realize that some answers include this, but I'd really like to see more answers that don't borderline the equality operator. An example using PHP is shown: ``` <?php $a = 'string'; $b = 'string'; $tmp = array_unique(array($a, $b)); return -count($tmp) + 2; ``` Simply return true or false (or something that evaluates in the language to true or false like 0 or 1) to indicate if the strings match. The strings should be hardcoded seen in the above example. The strings should not be counted in the golf, so if you declare the variable before hand, don't count the declaration. [Answer] # Python 49 45 18 22 15 14 ## ( + 3 if string variables are considered) ``` print{a:0,b:1}[a] ``` The string should be hard coded at the two occurrences of `a` and one occurrence of `b` surrounded by quotes. `a` and `b` should be pre-initialized to the strings. --- # Python shell, 9 ## ( + 3 if string variables are considered) ``` {a:0,b:1}[a] ``` Output in shell ``` >>> a = 'string' >>> b = 'string' >>> {a:0,b:1}[a] 1 >>> a = 'string' >>> b = 'stringgg' >>> {a:0,b:1}[a] 0 >>> {'string':0,'string':1}['string'] 1 >>> {'stringggg':0,'string':1}['stringggg'] 0 >>> ``` --- Explanation Creates a dict(hash table) with the key of first and second string. If second string is the same, the value of first is replaced by that of second. Finally, we print the value of first key. EDIT: OP allowed 0/1 instead of False/True as well as using pre-initialized variables. [Answer] # Python (~~17~~ 11): ``` b in a in b ``` (Checks if b is contained in a and a is contained in b, if that wasn't clear from the code.) ## Alternative python: (~~8~~ 7) derived from Tom Verelst's Go solution: ``` b in[a] ``` Bonus: this works for any type. EDIT: Wait a second, just read that you can also directly program in the strings, and don't have to count quotes... (or at least, that what golfscript does). So... Python on par with golfscript? Oh my! ## Alternative alternative Python (~~5~~ 4): (thanks Claudiu) ``` "string"in["string"] ``` original: ``` "string" in["string"] ``` ## Alternative Alternative Alternative Bendy-ruly Python (2): ``` "string"is"string" ``` Nothing was said about comparison **keywords** (This is not a serious submission, just something that occurred to me...) [Answer] # JavaScript, 11 10 Strings have to be stored in a and b. ``` !(a>b|a<b) ``` Edit: thanks Danny for pointing out, `|` is enough instead of `||` [Answer] # Ruby, 11 ``` s = 'string' t = 'string' !!s[t]&t[s] ``` Checks if each string is contained within the other. [Answer] # Python - 11 (without the strings) ``` >>> a = 'ss' >>> b = 's' >>> a in b in a False ``` [Answer] ## GolfScript (5 chars) ``` 'string1''string1'].&,( ``` Fairly straightforward port of the PHP reference implementation. Leaves `0` (=false) on the stack if the strings are the same, or `1` (=true) if they're different. [Answer] # Javascript (45 bytes): Here is another solution in Javascript. ``` var a='string',b='string',c=!a.replace(b,''); ``` The space is important. `c` should be `true`. [Answer] # C++, ~~63~~ ~~58~~ 56 ``` const char* a = "string"; const char* b = "string"; int main(){while(*a**b*!(*a^*b))++a,++b;return!(*a^*b);} ``` [Answer] # coreutils: uniq -d Just enter your two strings as the standard input of a pipe and `uniq -d | grep -q .` will print nothing but will have a return value of success or error. If you want to print the boolean, just replace with `uniq -d | grep -c .` How many characters? I let you count; `uniq -d|grep -q .` with no extra spaces has 17 characters in it, but since the whole job is performed by uniq, I would say this solution is a 0-character one in... `uniq` own language! Actually, `uniq -d` will print one line if the two strings are identical, and nothing if the are different. [Answer] Strings have to be stored in a and b. Will not work if either is `null`. # C#, 53 ``` string.IsNullOrEmpty(a.Replace(b,"")+b.Replace(a,"")) ``` --- # C#, 28 ``` a.Contains(b)&&b.Contains(a) ``` [Answer] ### PHP - 49 characters ``` !(strlen($a)^strlen($b)|strlen(trim($a^$b,"\0"))) ``` [Answer] ## APL (~~8~~ 9) Update: the old one does not work for strings of different lengths. ``` {∧/∊⌿↑⍺⍵} ``` * `↑⍺⍵`: make a matrix with `⍺` on the first line and `⍵` on the second line, filling blanks with spaces. * `∊⌿`: For each column, see if the upper row contains the lower row (as in the old version). * `∧/`: Take the logical `and` of all the values. Old one: ``` {∧/⍺∊¨⍵} ``` * `⍺∊¨⍵`: for each combination of elements in `⍺` and `⍵`, see if the element from `⍺` contains the element from `⍵`. Since in a string these will all be single characters, and a string contains itself, this is basically comparing each pair of characters. * `∧/`: take the logical and of all the values (if all the characters match, the strings are equal) [Answer] # Python - 12 ``` not({a}-{b}) ``` This solution uses sets. Subtracting equal sets will result in an empty set, which has a boolean value of False. Negating that will result in a True value for a and b being equal strings. ``` >>> a="string1" >>> b="string2" >>> not({a}-{b}) False >>> a="string" >>> b="string" >>> not({a}-{b}) True ``` Edit: Thanks to Peter Taylor for pointing out the unnecessary whitespace. [Answer] ## C — 62 ``` e(char*p,char*q){for(;*p&*q&&!(*p^*q);q++,p++);return!(*p^*q);} ``` Tested. Call as `e(str1, str2)` Come to think of it, if you don't count the `char*p,char*q`, which seems only fair, it's only 49 bytes :) [Answer] # Haskell -- 9 ``` elem a[b] ``` Note that this, just like many entries here, is just an expression. This is not a Haskell program. [Answer] ## Java - 162 147 characters The idea is to compare the difference of each byte, same bytes will have difference 0. The program will throw `java.lang.ArrayIndexOutOfBoundsException` for when bytes are different (try to access a negative index) or when strings are of different length. It will catch the exception and return 0 (strings not equal), or return 1 otherwise (strings equal). **Compressed:** ``` String a = "12345"; String b = "12345"; byte[]x=a.getBytes(),y=b.getBytes();int z,i=a.length()-b.length();try{for(byte d:x){z=d-y[i];z=x[-z*z];i++;}}catch(Exception e){return 0;}return 1; ``` **Normal:** ``` String a = "12345"; String b = "12345"; byte[] byteArrA = a.getBytes(); byte[] byteArrB = b.getBytes(); int byteDifference = 0; int i = a.length() - b.length(); try { for (byte aByte : byteArrA) { byteDifference = aByte - byteArrB[i]; byteDifference = byteArrA[-byteDifference*byteDifference]; i++; } } catch (Exception e){ return 0; } return 1; ``` [Answer] # PHP ``` $string = 'string'; isset( ${'string'} ); ``` This script may not have any utility, but atleast this provides a way to compare strings. # PHP Aother one: ``` $string = 'something'; $text = 'something'; return count( array( $string => 1 , $text => 1 ) ) % 2; ``` [Answer] # Prolog 7 ``` e(A,A). ``` This makes use of the pattern matching feature in Prolog to unify the 2 arguments to the predicate, which effectively tests for equals equivalence *when there is no unbound variable*. Sample usage: ``` ?- e("abcd", "Abcd"). false. ?- e("abcd", "abcd"). true. ``` Technically speaking, the behavior of this solution is that of unification operator [`=/2`](http://www.swi-prolog.org/pldoc/doc_for?object=%28%3D%29/2), rather than that of [`==/2`](http://www.swi-prolog.org/pldoc/man?section=standardorder), which checks for term equivalence. The difference shows when unbound variables are involved. In this solution, when unbound variable is supplied, the predicate will return `true` when unification is successful. In comparison, `==/2` will compare order of term without unification. [Answer] ## PHP, 21 This one is doing the job using variable indirection. ``` $$a=$b;!!$$b; ``` Or, if you don't need it to be bool ``` $$a=$b;$$b; ``` **EDIT** : I forgot to handle the case where you try to compare two empty strings, so the code now is ``` $$a=$b;!($a.$b)||$$b; ``` which is 21 chars. [Answer] ## CPython: 6 ``` a is b ``` --- ``` >>> a = 'string' >>> b = 'string' >>> c = 'STRING' >>> a is b True >>> a is c False ``` The use of `is` is obviously pretty suspect, but since the task specifically calls out that we're to determine value equality rather than reference equality, and `is` only compares object identity, I feel like it *may* not fall under the list of banned operators. Of course there's also some question as to whether this is even valid; it works on all of my systems, but it's implementation-specific and probably won't always work if the strings aren't defined by hand in the interactive interpreter. [Answer] ## Mathematica / Wolfram Language, 15 bytes ``` 2 - Length[{a} ∪ {b}] ``` Pretty self explanatory, sets each string as a set, then checks the length of the union of the two sets. If the strings are the same, returns 1, otherwise returns 0. If I'm allowed to return '2' for "different" and '1' for "same", subtract two bytes. [Answer] **C 342 golfed** ``` #include <stdio.h> #define N 100 #define P(x) printf("%s\n",x) #define G(x) gets(x) void e(int x){x?P("y"):P("n");} int main(){ char s[N],t[N];char *p,*q;int r=0; int n=0,m=0;int i=1;p=s,q=t; if((p=G(s))&&(q=G(t))){while (*p){n+=i*(int)*p;m+=i*(int)*q;i++;p++;q++;if(!(*q)){break;}} if(!*p&!*q){if(!(m-n)){r=1;}}e(r);} return 0; } ``` Note: Visual Studio complains if you don't use their safe methods eg gets\_s. CodeBlocks with mingw compiles without warnings. **C 655 not golfed** Code creates weighted sum of chars for each string. If the difference is zero then they are equal, including 2 empty strings: ``` #include <stdio.h> #define N 100 #define P(x) printf(x) #define G(x) gets_s(x) void e(int x){ x ? P("equal\n") : P("not equal\n"); } int main() { char s[N], t[N];//words char *p = 0, *q = 0; int r = 0; //result 0=false int n=0, m=0; //weighted sums int i = 1; //char pos start at 1 if ((p=gets_s(s)) && (q=gets_s(t))) { while (*p) { n += i*(int)*p; m += i*(int)*q; i++; p++; q++; if (!(*q)){ break; } } if (!*p && !*q){ //both same length strings if (!(m - n)){ r = 1; } //weighted sums are equal }//else r=0, false=>not equal e(r); } else{ P("error\n"); } getchar(); } ``` [Answer] # Python It's long and it's not beautiful, but this is my first entry! ``` def is_equal(a,b): i=0 a,b=list(a),list(b) if len(a)>len(b): c=a lst=b else: c=b lst=a try: while i<len(c): for j in c: if j not in lst[i]: return False i+=1 except IndexError: return False return True ``` [Answer] # R (4 chars) ``` 'string1'%in%'string2' ``` Or, for an actual function, ## (6 chars) ``` `%in%` ``` which is called with ``` `%in%`(x,y) ``` As R is a vector-based language, is treated as a string and b is treated as a vector of one string, so this is similar to the `elem a[b]`/`a in b in a`/`a in[b]` solutions in spirit. [Answer] ## PHP, 68 Bytes I assume you're prohibited to use **any** comparison operators. So `<` or `>` are included. The idea is to use bitwise XOR. In different languages this operator has different syntax - I'll show an example for PHP. There it's available with `^`. Unfortunately, its behavior with strings isn't as good as it could be, so you'll need to check string length before. That is because in PHP, xor will strip the longer string down to the length of the shorter string. Next thing is to work with strings properly, because a single `xor` will not produce a result, available for further operations in PHP. That's why [`unpack()`](http://php.net/unpack) was used. So, the code would be: ``` return !(strlen($a)^strlen($b)) & !array_filter(unpack('c*', $a^$b)) ``` It's longer than option with `<` / `>` but it won't use them. Also, the important thing is about [PHP type juggling](http://www.php.net/manual/en/language.types.type-juggling.php) (so empty array will be cast to `false`). Or maybe there's a simpler way to check if an array contain non-zero members (*Edit*: while I've been typing this, there's a good catch with `trim()` in another answer, so we can get rid of array operations) But I believe there are languages, where we can do just `a ^ b` - literally, getting the result. If it's `0` (treated from all resulted bytes) - then our strings *are equal*. It's very easy and even more simple than `<` or `>` stuff. [Answer] # grep 14 characters Of course, I only count the grep code; the two strings are on two consecutive lines in the input (either a pipe or a file or even an interactive session). ``` $ echo -e 'string\nstring' | grep -cPzo "(?s)^(\N*).\1$" 1 $ echo -e 'string\nstring1' | grep -cPzo "(?s)^(\N*).\1$" 0 $ echo -e 'string1\nstring' | grep -cPzo "(?s)^(\N*).\1$" 0 ``` [Answer] # Matlab: 12 chars (after the strings are in variables) ``` ~(x*x'-y*y') ``` The code including assignments would be: ``` x='string1' y='string2' ~(x*x'-y*y') ``` [Answer] # The very crazy way Just for the fun, but many ways for making it fail if one thinks about it. More over, don't forget the strings will be EXECUTED by the shell. ``` $ echo -e 'string\nstring1' | sed -e '1s/^/#define /' | cpp | sh 2>/dev/null && echo true $ echo -e 'string\nstring' | sed -e '1s/^/#define /' | cpp | sh 2>/dev/null && echo true true $ echo -e 'string1\nstring' | sed -e '1s/^/#define /' | cpp | sh 2>/dev/null && echo true ``` A good counter-example is comparing "string" as first string and "rm -Rf /" as a second string; just check as root and see: it will say "true" though both strings obviously aren't the same. [Answer] # JavaScript [18 bytes] ``` (_={})[a]=1,!!_[b] ``` **OR** ``` !!((_={})[a]=_)[b] ``` This will return `true` if `a == b` and `false` if `a =/= b`. The logic behind is creating an object with a value of `a` as a property and returning `1` or `undefined` in case if a property of `b` value exists or doesn't exist in that object. [Answer] # JavaScript [15 bytes] ``` ![a].indexOf(b) ``` This will return `true` if `a == b` and `false` if `a =/= b`. The script is looking for the value of `b` in the array that holds a single element of value of `a`. ]
[Question] [ **This question already has answers here**: [Fibonacci function or sequence](/questions/85/fibonacci-function-or-sequence) (334 answers) Closed 6 years ago. The Fibtraction sequence (as I call it) is similar to the Fibonacci sequence except, instead of adding numbers, you subtract them. **The first few numbers of this challenge are:** ``` 1, 2, -1, 3, -4, 7, -11, 18, -29, 47, -76, 123, -199, 322, -521, 843, -1364... ``` The sequence **starts with 1 and 2**. Every next number can be calculated by subtracting the previous number from the number before it. ``` 1 2 -1 = 1 - 2 3 = 2 - (-1) = 2 + 1 -4 = -1 - 3 7 = 3 - (-4) = 3 + 4 ... ``` In other words: ``` f(1) = 1 f(2) = 2 f(n) = f(n - 2) - f(n - 1) ``` This is [OEIS sequence A061084](https://oeis.org/A061084 "A061084 - OEIS"). ## Challenge Write a **program/function** that takes a positive integer **n** as input and prints the **nth number of the Fibtraction sequence**. ### Specifications * [Standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods "Default for Code Golf: Input/Output methods") apply. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default "Loopholes that are forbidden by default") are **forbidden**. * Your solution **can either be 0-indexed or 1-indexed** but please specify which. * This challenge is not about finding the shortest approach in all languages, rather, it is about finding the **shortest approach in each language**. * Your code will be **scored in bytes**, usually in the encoding UTF-8, unless specified otherwise. * Built-in functions that compute this sequence are **allowed** but including a solution that doesn't rely on a built-in is encouraged. * Explanations, even for "practical" languages, are **encouraged**. ## Test cases These are 0-indexed. ``` Input Output 1 2 2 -1 11 123 14 -521 21 15127 24 -64079 31 1860498 ``` That pattern was totally not intentional. :P [This challenge was sandboxed.](https://codegolf.meta.stackexchange.com/a/13219) > > Before you go pressing any buttons that do scary things, hear me out. This might be considered a dupe of the [regular Fibonacci challenge](https://codegolf.stackexchange.com/questions/85/fibonacci-function-or-sequence "Fibonacci function or sequence") and I agree, to some extent, that it should be easy enough to port solutions from there. However, the challenge is old and outdated; is severely under-specified; allows for two types of solutions; has answers that don't have easy ways to try online; and in general, is lacking of answers. Essentially, in my opinion, it doesn't serve as a good "catalogue" of solutions. > > > plz send teh codez [Answer] # [Oasis](https://github.com/Adriandmen/Oasis), 4 bytes ``` c-21 ``` [Try it online!](https://tio.run/##y08sziz@/z9Z18jw////xoYA "Oasis – Try It Online") 0-indexed. I saw this language used for a similar challenge once, and immediately I knew I should try it here. Can't say I'm disappointed. ### Explanation ``` 1 a(0) = 1 2 a(1) = 2 c a(n) = a(n - 2) - - a(n - 1) ``` [Answer] # [Python 2](https://docs.python.org/2/), 35 34 bytes -1 byte thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)! ``` f=lambda n:n*(n<3)or f(n-2)-f(n-1) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIc8qT0sjz8ZYM79IIU0jT9dIUxdEGWr@LyjKzCvRyE0s0EjTUShKzEtP1TDUUTAy1dTU/A8A "Python 2 – Try It Online") Answers are 1-indexed. Takes advantage of `f(2)` and `f(1)` being equal to their respective inputs. [Answer] ## Javascript, 24 bytes ``` f=n=>n<3?n:f(n-2)-f(n-1) ``` ``` f=n=>n<3?n:f(n-2)-f(n-1) for (let i = 1; i <= 20; i++) { console.log(f(i)) } ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 27 bytes 0-indexed. ``` @(n)([1,2]*[0,1;1,-1]^n)(1) ``` [Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjT1Mj2lDHKFYr2kDH0NpQR9cwNg4oZqj5P7GoKLEyrTRPI00HpELH0FDH0ETHCMg00TE2jNX8DwA "Octave – Try It Online") [Answer] # x86 Machine Code, 12 bytes **Iterative solution; 0-indexed** ``` 31 C0 40 8D 50 01 29 D0 92 E2 FB C3 ``` The above function takes a single input, *n* (passed in the `ECX` register, following Microsoft's [fastcall calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_fastcall)), and returns the *n*th number of the Fibtraction sequence in the `EAX` register. The implementation is based on the well-known trick for calculating a Fibonacci number using two variables, which [Snowman's answer in Java](https://codegolf.stackexchange.com/a/131680/58518) reminded me of. Not only is this solution *much smaller* in size than [my first attempt](https://codegolf.stackexchange.com/a/131685/58518) (it even competes with [Mathematica using a built-in](https://codegolf.stackexchange.com/a/131573/58518)), it will also be *much faster* because it is iterative, rather than recursive. Theoretical comp-sci's love for recursion is foiled once more! **Ungolfed assembly mnemonics:** ``` Fibtraction: xor eax, eax inc eax ; EAX = 1 (XOR+INC are 3 bytes; same as PUSH+POP) lea edx, [eax + 1] ; EDX = 2 (LEA is 3 bytes; same as PUSH+POP) Iterate: sub eax, edx ; EAX = EAX - EDX xchg eax, edx ; swap EAX and EDX loop Iterate ; decrement ECX and keep looping as long as ECX != 0 ret ; return, with result in EAX ``` **[Try it online!](https://tio.run/##hc3daoMwGIDhY3MVH45CMuqqUVvFrQdr15tYhmTR2oCNQyMExm59LrC26ZkHIb9vHhE0QkyT6NSgQZx4DyZb77qqfv@AF/CZiSNmdiEziR3ZnpnUzqE9ozkze7vOKTNvdhxe7bvYL9CguZYCRjXIRtUVlCXXupefo67LEuMjH7TgbUsI4EdrHYwi@PqYWPPiF9ODVKIdqxqeB13J7um0RUgqDWcuFSboG3lfvd0fsf//DV5UhOlgy/SiYspfQrSEy01ESOF5qxXQ2YjeInqNgmieurNuWETj@TBxYXIDUzpPUkdSR6YR3cynDqUOXSfhJp9tY8fGjs3WYZJnyOtrPfYKwgL9TL/i2PJmmIJzTP8A "C (gcc) – Try It Online")** A couple of things worth pointing out here… * We start by loading the constants 1 and 2 into registers. These are our starting values. The standard way, of course, to load constants into registers is `mov reg, imm`. That's fast, but it takes a whopping *5 bytes* to encode. So, for code-golfing purposes, we make use of various other tricks to load values into registers. A 2-byte `PUSH` that pushes the immediate value onto the stack, followed by a 1-byte `POP` that pops the value off the top of the stack and into a register, is the workhorse trick—very common and very useful. But, if you are just setting the register to 1, you can do `XOR`+`INC`, which is the same 3 bytes. And, if you already have the value you want in a register, then you can build off of it using the magic `LEA` instruction, which is also only 3 bytes. Both of those tricks are showcased here, since they are more interesting and somewhat faster than the good old `PUSH`+`POP`. * Inside of the body of the loop, we do a pretty neat optimization. The fundamental operation we're doing here is: ``` edx = (eax - edx) eax -= edx ``` which would naively be translated to (indeed, this is what most C compilers do): ``` sub eax, edx ; 2 bytes mov ebx, edx ; 2 bytes mov edx, eax ; 2 bytes mov eax, ebx ; 2 bytes ``` or, somewhat better—rewrite the subtraction as addition of a negative so that the operand order can be reversed, allowing the result to end up in the desired register without having to clobber a temporary register (ICC is able to apply this optimization): ``` neg edx ; 2 bytes add edx, eax ; edx = (eax - edx) ; 2 bytes sub eax, edx ; eax -= edx ; 2 bytes ``` but I have written it as: ``` sub eax, edx ; 2 bytes xchg eax, edx ; 1 byte ``` which is conceptually similar to the naive version (only one subtraction is done, then some moves), but much more compact because of the `XCHG` instruction. This avoids clobbering a register, and decreases the size of the code. (I guess you could have equally well used an `XOR` to avoid clobbering a register—the famous move-without-a-temporary trick—but `XCHG` is 1 fewer byte for golfing purposes.) Now, to be fair, the `MOV`s are probably much faster in real-world code, especially on modern processors that can elide moves in the front end via register renaming. Exchanges can't be elided, and aren't known for being particularly fast. If it weren't for register renaming, ICC's code (the add-a-negative approach) would probably be the fastest in the real-world, since it's compact and arithmetic operations are extremely efficient. * The `LOOP` instruction. This is an old CISC-style instruction that is equivalent to: ``` dec ecx jnz Label ``` but is avoided in modern code (and by all compilers) because it's actually *slower* than the above sequence. It's also less versatile, because it has the `ECX` register hard-coded as the counter. However, for code-golf purposes, it's great! And since we used a calling convention that passes the parameter in `ECX`, we don't even have to do anything! (If you wanted to use a different calling convention, you'd just have to do a `MOV` or `XCHG` at the very top of the function to copy the parameter into `ECX`; or, you could swap out the `LOOP` instruction for the expanded form shown above. Either of these would only cost a couple of bytes, maximum, so this optimization isn't really saving us much, but I think it does earn a couple of *style* points! :-) Similarly, if you wanted to write this for x86-64, like my original answer, which uses a different calling convention, it would be easy to adapt. Either of these will do it, and both are only 14 bytes: ``` Fibtraction_64_A | Fibtraction_64_B: push 1 | mov ecx, edi pop rax | push 1 lea edx, [rax+1] | pop rax Iterate: | lea edx, [rax+1] sub eax, edx | Iterate: xchg eax, edx | sub eax, edx dec edi | xchg eax, edx jg Iterate | loop Iterate ret | ret ``` [Answer] # [Haskell](https://www.haskell.org/), ~~29~~ 26 bytes Inspired by alephalpha's answer I thought, I'd derive an explicit formula. It's been a while since I did an Eigenvalue decomposition, turns out the explicit formula (even after golfing it down) is longer and fails because of floating point issues. 0-indexed: ``` (g!!) g=1:scanl(flip(-))2g ``` [Try it online!](https://tio.run/##y0gszk7Nyflfraus4OPo5x7q6O6q4BwQoKCsW8uVZhvzXyNdUVGTK93W0Ko4OTEvRyMtJ7NAQ1dT0yj9f25iZp6CrUJBUWZeiYKKQm5igUKaQrSBnp6hgUHsfwA "Haskell – Try It Online") Saved 3 bytes thanks to @Laikoni ## Decomposition solution, 48 bytes There are a couple eigenvector decompositions; the simplest is actually -1-indexed rather than 0-indexed or 1-indexed: ``` Prelude> map (\n -> ((-1 + sqrt 5)/2)**n + ((-1 - sqrt 5)/2)**n) [0..10] [2.0,-1.0,3.0,-4.0,7.0,-11.0,18.0,-29.000000000000004,47.0,-76.0,123.0] ``` Since the `(-1 + sqrt 5)/2` term is less than 1, we can absorb that into the needed `round` at the cost of adding some leading terms, ``` Prelude> [round$((-1 - sqrt 5)/2)^n|n<-[0..10]] [1,-2,3,-4,7,-11,18,-29,47,-76,123] ``` So e.g. one can get to a function by, but this is not much-more golfable and it's 48 bytes: ``` ((1:2: -1:[round$(-(1+sqrt 5)/2)^n|n<-[2..]])!!) ``` [Try it online!](https://tio.run/##y0gszk7Nyflfraus4OPo5x7q6O6q4BwQoKCsW8uVZhvzX0PD0MrISkHX0Cq6KL80L0VFQ1fDULu4sKhEwVRT30gzLq8mz0Y32khPLzZWU1FR839uYmaegq1CQVFmXomCikJuYoFCmkK0gZ6eoYFB7H8A "Haskell – Try It Online") [Answer] # [cQuents](https://github.com/stestoltz/cQuents), 8 bytes ``` =1,2:y-z ``` 1-indexed. Since cQuents isn't stack based it isn't as terse as Oasis. Prints the whole sequence if no input is given. [Try it online!](https://tio.run/##Sy4sTc0rKf7/39ZQx8iqUrfq/38A "cQuents – Try It Online") ### Explanation ``` =1,2 Sequence start equals 1,2 : Mode: sequence. Prints the 1-indexed nth term for input n. y-z Each item in the sequence equals the second to last item minus the last item ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` 1_@¡3 ``` 0-indexed. [Try it online!](https://tio.run/##y0rNyan8/98w3uHQQuP///8bGwIA "Jelly – Try It Online") [Answer] # [Perl 6](https://perl6.org), 19 bytes ``` {(1,2,*-*...*)[$_]} ``` [test it](https://tio.run/##LY5Bi8IwEIXv@RXvsNqmTINNa6sUPenV0552FREbpaCtmCqK6F/vTsKeZt73voG5mOsp72/W4J6rfSnOTwz3bWUw619hQpqiOFJKRfL3a7t5e/Hb2K4Uy9UCVduYuONYN8dSiEN7xYhd/CAhaELMI@WREQqXOCYTXvSUkDlS5Ey0U5Ips1S7o7Fmb5J5muaZiOcI13VTmQet77vTzUi8BFBbuEdD30iCrwg@qsO5C4NBajGbB/Ljq39W2ECKd/8H "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 ( 1, 2, # seed the sequence * - * # WhateverCode lambda used to generate the rest of the values ... # keep generating until: * # never stop )[ $_ ] # index into the sequence } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` 3XIFDŠ- ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fOMLTzeXoAt3//y0A "05AB1E – Try It Online") **Explanation** ``` 3 # push 3 X # push 1 IF # input times do: D # duplicate top of stack Š # move the copy down 2 spaces on the stack - # subtract top 2 numbers ``` [Answer] ## Mathematica (using a built-in), ~~18~~ 12 bytes *Several bytes saved by user202729 !* ``` LucasL[2-#]& ``` Or the same idea without a built-in, for ~~32~~ ~~31~~ ~~30~~ 29 bytes: ``` Tr[{p=(1+5^.5)/2,1-p}^(2-#)]& ``` Uses 1-indexing. [Try them at the Wolfram sandbox](https://sandbox.open.wolframcloud.com/) (they don't work in Mathics, unfortunately). This uses the observation by ETHproductions and user202729 that the sequence is nearly the Lucas numbers (only with alternating sign, or reading backwards). The 29-byte function is the [closed formula](https://en.wikipedia.org/wiki/Lucas_number#Relationship_to_Fibonacci_numbers) for the Lucas numbers. [Answer] # [Mathics](http://mathics.github.io/), 31 bytes ``` f@1=1 f@2=2 f@x_:=f[x-2]-f[x-1] ``` -2 thanks to @MartinEnder! [Try it online!](https://tio.run/##y00sychMLv7/P83B0NaQK83ByNYISFbEW9mmRVfoGsXqgijD2P8BRZl5JdFp@g5BiXnpqQ6GprH/AQ "Mathics – Try It Online") [Answer] # Brainfuck, ~~51~~ 44 bytes ``` +++++>+>++<<[>[>>+<<-]>[<+>>-<-]>[<+>-]<<<-] ``` 0-indexed, the input is on cell 0 and the output on cell 1. Output is in two complement format. Per [this meta consensus](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), [input for Turing machines may be written to the tape pre-execution](https://codegolf.meta.stackexchange.com/a/7031/65326), and [the contents of the tape post-execution may be used as a Turing machine's output](https://codegolf.meta.stackexchange.com/a/7032/65326). **How?** ``` # The tape: I O A B . . . # I = input, O = output >+ # O = 1 >++ # A = 2 <<[ >[>>+<<-] # B = O [ I 0 A O ] >[<+>>-<-] # B = B - A, O = A [ I A 0 O-A ] >[<+>-]<<< # A = B = O - A [ I A O-A 0 ] -] # Repeat I times ``` [Answer] # [PHP](https://php.net/), 45 bytes 0-indexed ``` for($x=1,$y=2;$argn--;)$x=$x-$y=$x-$y;echo$x; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkbKhk/T8tv0hDpcLWUEel0tbIGiyjq2utCRRSqdAFioFJ69TkjHyVCuv//wE "PHP – Try It Online") # [PHP](https://php.net/), 46 bytes 1-indexed recursive function ``` function f($i){return$i<3?$i:f($i-2)-f($i-1);} ``` [Try it online!](https://tio.run/##K8go@G9jXwAk00rzkksy8/MU0jRUMjWri1JLSovyVDJtjO1VMq1AYrpGmrpg2lDTuvZ/anJGPlCpsZGm9X8A "PHP – Try It Online") [Answer] # Java, ~~65~~ 61 bytes Golfed: ``` n->{int a=1,b=2;for(;n-->0;a-=b)b=a-b;System.out.println(a);} ``` This uses the standard trick of calculating Fibonacci using only two variables to hold the state, but modified to work with subtraction. I am aware that theoretically, `System.out.print()` *should* work here but in practice it is inconsistent with flushing output and sometimes (often enough to be an issue) will literally print *nothing* using the Oracle JVM. This function is zero-indexed. [Try it online!](https://tio.run/##VVDBToNAEL3zFe8ICRCpnqztQRMTzz14MB4WusWpMEuW2RrT8O04EMG4yebN7Hsvs/PO5mIy11k@Hz/HqjF9j2cqxZtKyLGWjk1V0WOQV5KPQ1gpXKMI6ELZUIVejChcHB3RGuL4IJ64fnuH8XWfqBZ6Ts4jJhYQ7sH2C1qr5IoixSZFoVDcaTm1ircFhsWq5nhkZPu1x@SGwW5ylwqb7crMg7bgLMMeN1tVZTuUycpjNugryj/T4bsX2@YuSN7p56Xh2CQLPYxIQb/tEE132t7TxYj9t/4pPmukeRBq8lPgOav8yXEfWusfXlhsbf0eC5XOa/Aa0eLQ0G0nMc8jh2iIxh8) Ungolfed: ``` public class FibtractionFibonacciButWithSubtraction { public static void main(String[] args) { for (int i : new int[] { 1, 2, 11, 14, 21, 24, 31 }) { f(n -> { int a = 1, b = 2; for (; n-- > 0; a -= b) b = a - b; System.out.println(a); } , i); } } private static void f(java.util.function.Consumer<Integer> function, int n) { function.accept(n); } } ``` [Answer] # C, 30 bytes [**Try Online**](https://tio.run/##FcsxCoAwDEDRq4ggJLSFqpuxehapVDIYpXETz151@m/50W0xlqKUQPDWIFM3f3Qduj8tDkJPYdoXFsA7HRk4tMRj74mNsRo8JmC0Z2a5EtTNaqvaKn7XCw) 1-indexed ``` s;f(n){s=n>2?f(n-2)-f(n-1):n;} ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 26 bytes ``` n->([1,2]*[0,1;1,-1]^n)[1] ``` [Try it online!](https://tio.run/##FctBCoAgEEbhqwyuNEboN3dRFxEDN4YQwxBtOr3l7nuLp@Vu/tReaevid5vAIU9pZqxgj3yIS8i9qF6vFfI76d3k@WlGGKpWnGMaHwOMyOFn5AXZ9Q8 "Pari/GP – Try It Online") [Answer] # Common Lisp, 46 bytes ``` (defun f(n)(if(< n 3)n(-(f(- n 2))(f(1- n))))) ``` [Try it online!](https://tio.run/##FckxCoBADETRq6ScKbZwbb2NGgjIsKx6/hh/9eDvV9wjE8fpr8whIhybyVYKDY5W7mRpKfIvMWboMbj1WvkB) 1-indexed, plain recursive solution. [Answer] ## R, 38 bytes ``` f=function(n)`if`(n<3,n,f(n-2)-f(n-1)) ``` 1-indexed solution **Explanation :** The `'if'` function has the same syntax as `ifelse` : `ifelse(test, TRUE, FALSE)`. In this solution, we create a function `f` that begins to test if the input `n` is strictly inferior to `3` (i.e. equals to 1 or 2 ; `test` part of the `'if'`). If its the case, the output is simply the input (`TRUE` part). The function otherwise recursively calls itself and outputs the final result (`FALSE` part) [Answer] # Mini-Flak, 72 bytes (1-indexed) ``` ({}(()()())(())[()()()()]){({}(([{}]({})))[({}([{}]{})[({})])][()])}{}{} ``` [Try it online!](https://tio.run/##bVHBboMwDD0nX2GxC0gFjXWnTjvsA6btsBvqIWncgkoTBKGdhPh25iSla9cFkLD9/PxeLFtR6XRbi/00Re@Vrvx/BnlaaYXfqCLO42FkdB6gabHD9oig4VRWNa44i@PEPYmr9l0JS59K2BznnBUBEidrSna9tK3YWHjmSSDtrNjsQZvTCr4@Pok6hyVkdPgQAC02KCxoYvZCrnXwAKHuM08gkSCoEruvGMa17zENyAUIrUDjTlh0rUTolFvTLACPou4pT5HvTtjFhIAUZPY7JQwRqbwDutSObvQFbFl1IGtDmm6YU0kt9Bac3fshIQfT2TPKG2CzgWuWNCJE5KqOIZhzUlhyo9mj4BU8WeHMeqaUxtzppsQ67MOQdrpvW@I/@sPkDN6UcqEDCWmOM5RSO7TwyJ3DPxvPYduag9tZmIy0iotz385HPozznZClFlWvldBE6BcnwClBMDrsgU9T/vQD "Brain-Flak – Try It Online") The TIO links have more comments, so it is easier to understand. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 34 33 bytes ``` A¹αA²βF…²θ¿﹪ι²A⁻βαβA⁻αβα⎇﹪Iθ²IαIβ ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9noWHdp7bCKI2ndv0fs@yRw3LgKwdh/a/37nq3M5DQKGFjxp3n9t0buM5GHsjiPeorx2o4v2elUC1m0DURhCx6f9/YyMA "Charcoal – Try It Online") 1-indexed. I insist on writing answers in a language with a totally different purpose... Link to the [verbose version](https://tio.run/##VcyxCoNAEATQ3q/YchfWIpfSKqQWQvAH9oyaA7nDOw3k6zeboEW6mYF5/VNyn2RWvZQSpognFmqqvTj2VsaUAe8Sp8GGhagCCCNgmx7bnDCwI4L90Ia4FfRmMNj1fxbTGL78LYe4YjfkKPl9QFcpKy5kHMMvyxE8ETWqZ6f1S@syfwA). [Answer] # Ruby, 26 bytes Nothing fancy here, it's just a translation of Python or Javascript solutions : ``` f=->n{n<3?n:f[n-2]-f[n-1]} ``` The results are 1-indexed. [Try it online!](https://tio.run/##NY7NCsIwEITvfYo9KiaF/NgfMYrPEXpQbDFQYkkapLY@e9xYPM3Ox8zuunCbYuwUPdnZHsXZHjptKW9oEtZ8on88Q38HBZoR4AQoikCRBMrk0LIKB14TkImUBRKeIqxGJngq7TnmKvmjopBN5lof@hHXXpy7TrltX5v1Uu7Nu93Oi1mg02aHL2QDrOlsCKOHf1PBWohf "Ruby – Try It Online") [Answer] # x86-64 Machine Code, 29 bytes **Simple recursive solution; 1-indexed** The following is a function written according to the [System V AMD64 calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI) that computes and returns the *n*th number of the Fibtraction sequence. The sole parameter, *n*, is passed in the `EDI` register. The function returns its result in the `EAX` register. ``` 53 51 89 F9 83 EF 02 7E 10 E8 00 00 00 00 8D 79 FF 91 E8 00 00 00 00 29 C1 91 59 5B C3 ``` [Try it online!](https://tio.run/##3Vbfa9swEH73X3FvSSAJcbqNkq6Mrj@2whh72ENhjCHbl1jBljJJzo/@89lJsmW7y0Zhg8H8oLrSfXfffXdnhWmNZVIcJoLp8rgqZMIK@KYNUyaKNKaGSwFTg3tzvOOJUcztLCIA2FQ6B/uoZA/tcwEbhRrVFkEqvuKCHG5ZUSFwAbdvH/rQ9PnQawct5dYbY7ofA2b819CBGHSAukpqYMbHMG9j3t7cwyUImMDc2q0L9CfTOy64zjGr7fiSjF5fwnwMOxwohEwKhGHCNEJql6VUoDCtlCaJRtZXyorCoTvaOV@pLDeVIciQoo/IYc7THLimDUfEoQtkHcZfSKtJ/LXPOLZ2@zRfeTtmJWkkvQDNSA6SpSoMyKX1PZmPaklg6GPuLHkBQu7IfInFAVJqggTVHyUQj/qSu1qxQIzcplXBHN7nS0tABuEX8OS5gKUlZHIlq1U@nU5/mz61Skh/qWTp0ubCSLi98m0oN3CyDQlkpPqpCy3y@gkyeTbSt75CAyceizSVEqQkN3nD2pbq6uH4SRHrj7j7wAW2oxefhXlwmceh7AdtsPS1i1sb20TBZsmpzXMmMvoTw1CbTFZm1DHuOhRVSQ1hWyg5GNQ2G7Km@gd7avkxLRtvz7KMEtAWoA1xX/URxM9yCzoqtq@ViSKX6r0wLs09DRSo82xsl5ZbYrnNosjFutcNPYErZvgW39gDomnqhvDe10LTSL9Dc0OFMbpGv/cKNNDGVUJTIMUWlanJb6Tm1mAMBPDQ7xVWaI@rDTA7q5n9J3jSfCVs/UyOdequWekcGkquinXy/7yMjsxgMvirJQ3vUat8W1nHjha7kXFfWftOserDF@etTt6OixSabjhR48d@jaeunTpxHaTbUevH7pfeMcE2wv8wXF63dUnvXTmizmc2TF/kb/5FGzp@SVq5PKPpZxLvmi46vejnbY3CZdG5KMJeM9T9jfqDFrVlbfxYrj7yWRyu5Da8Y@O0wD03/Tq9mp2o06tZp@d4@NXQfHNp1jOEWUe94w8 "Assembly (nasm, x64, Linux) – Try It Online") (Hey, I finally figured out how to make TIO work for assembly language! Ignore the ugly boilerplate to print numbers… :-p) **Ungolfed assembly mnemonics:** ``` Fibtraction: push rbx ; preserve original value in EBX push rcx ; preserve original value in ECX mov ecx, edi ; preserve original 'n' in ECX sub edi, 2 ; EDI = n - 2 jle .Finished ; if n <= 2, we're done (base case for recursion) call Fibtraction ; compute f(EDI), which is f(n - 2) lea edi, [rcx-1] ; EDI = n - 1 xchg eax, ecx ; save result of f(n-2) in ECX (which we can now safely clobber) call Fibtraction ; compute f(EDI), which is f(n - 1) sub ecx, eax ; calculate f(n - 2) - f(n - 1) .Finished: ; fall through... xchg eax, ecx ; move result from ECX into EAX pop rcx ; restore original value to ECX pop rbx ; restore original value to EBX ret ; return, with result in EAX ``` Okay, it's assembly language, so there are no fancy built-ins to help us. But just look at all of those 1-byte opcodes! `PUSH`, `POP`, and `XCHG` are all very handy here. These `XCHG` instructions are really just substitutions for register-to-register `MOV`es. We don't actually need to exchange the values; we just care about a one-way movement. But, although normally `MOV reg, reg` and `XCHG reg, reg` are both 2 bytes, there is a special 1-byte encoding for `XCHG` when one of the operands is the accumulator (`EAX`). Thus, this substitution saves us a few bytes (at the possible expense of speed). The only long, ugly instructions are the `CALL`s, used to invoke the function recursively. (Technically, all of those 0s in the opcodes get replaced by the linker with the function's actual 32-bit relative displacement when the code gets linked, but the resulting binary will be the same size in bytes because this won't change the *length* of the instruction.) But there isn't really anything we can do to reduce the size. `CALL` can be emulated as `PUSH`+`JMP`, but just the `PUSH` instruction alone consumes more bytes than `CALL`! The recursive nature of this algorithm made it a fun and interesting challenge—to me, at least. It's not very often in the real world that you get to write recursive code! It just isn't an efficient way to do things. (Double recursion leads to *exponential complexity*! Bleh!) Compilers also do a bad job, in general, optimizing it, so this hand-written assembly is head-and-shoulders above what a C compiler would generate for the naive solution: ``` int Fibtraction(int n) { return n <= 2 ? n : f(n-2) - f(n-1); } ``` (although it has been optimized for *size*, rather than speed, obviously). [Answer] # SWI Prolog, 88bytes Did I hear recursion? Prolog is here! ``` g(1,1). g(2,2). g(X,Y):-A is X-2,g(A,B),C is X-1,g(C,D),Y is B-D. f(X):-g(X,Y),print(Y). ``` Try it: [SWISH](https://swish.swi-prolog.org/p/Fibtraction%20-%20Fibonacci%20but%20with%20subtraction.pl) [Answer] # [><>](https://esolangs.org/wiki/Fish), 17+3 = 20 bytes ``` 43\n; ?!\:@-{1-:} ``` [Try it online!](https://tio.run/##S8sszvj/38Q4Js@ay14xxspBt9pQ16r2/39zi/@6ZQqGhgA "><> – Try It Online") Input is expected on the stack at the start of the program, so +3 bytes for the `-v` flag. [Answer] # [Julia](https://julialang.org/), 24 bytes ``` f(n)=n>2?f(n-2)-f(n-1):n ``` 1-indexed [Try it online!](https://tio.run/##yyrNyUw0/f8/TSNP0zbPzsgeyNA10tQFUYaaVnn//WyNTLjS8osU8mwNrfy4ODPTFPJsgDRnQVFmXomGkooGSKumjoKSJhdnak5xKkwqJw8uqaenB5bNS@EC4v8A "Julia 0.5 – Try It Online") [Answer] # Fortress 0.1 Alpha, 39 bytes. ``` f(n)=if n<3then n else f(n-2)-f(n-1)end ``` The interpreter is archived [here](http://web.archive.org/web/20070715233437/http://fortress.sunsource.net/files/documents/81/140/fortress_168.zip) (direct download). This language is old and dead, very dead. (1-indexed: f(1)=1, f(2)=2). Can be placed into a program like this: ``` export Executable f(n)=if n<3then n else f(n-2)-f(n-1)end run(args) = do println(f(3)) end ``` Does this **really** need explaining? This is just the definition. [Answer] # Mathematica, 37 bytes ``` LinearRecurrence[{-1,1},{1,2},{#+1}]& ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 32 bytes ``` ?3sb1sc[lblcdsb-sc1-d0<d]dsdxlbp ``` 1-indexed. [Try it online!](https://tio.run/##S0n@/9/euDjJsDg5OicpJzmlOEm3ONlQN8XAJiU2pTilIiep4P9/QwA "dc – Try It Online") ## Explanation ``` ? # Take input and push it onto the main stack. 3sb # Push 3 into register "b". 1sc # Push 1 into register "c". [ # Begin macro definition. lblc # Load the values in registers "b" and "c" onto the main stack. dsb # Duplicate the top-of-stack value and push it into register "b". -sc # Push the difference of the top two values into register "c". 1-d # Subtract 1 from the top-of-stack value and duplicate the result. 0<d # If the result is greater than 0, execute the macro in register "d". ] # End macro definition. dsdx # Duplicate the macro, push a copy into register "d", and execute the # remaining copy. lbp # Output the value stored in register "b". ``` [Answer] # VBA, 62 Bytes Recursive function that takes input, `n`, as integer and outputs the 1-indexed element of A061084 ``` Function f(n):If n<3Then f=n Else f=f(n-2)-f(n-1):End Function ``` ]
[Question] [ Dither a grayscale image into pure black and white with your own algorithm. Guidelines: You must come up with your own new algorithm. You cannot use pre-existing algorithms (ex. Floyd-Steinburg) but you can use the general technique. Your program must be able to read an image and produce an image the same size. This is a popularity contest, so whoever produces the best (closest to original) and most creative (determined by votes) wins. Bonus if the code is short, though this is not necessary. You can use whatever grayscale image you want as input, it should be larger than 300x300. Any file format is fine. Example input: ![puppy](https://i.stack.imgur.com/B2DBy.jpg) Example output: ![dithered](https://i.stack.imgur.com/Nl8wL.jpg) This is a pretty good job, but there still are visible lines and patterns. [Answer] ## GraphicsMagick/ImageMagick ## Ordered Dither: ``` magick B2DBy.jpg -gamma .45455 -ordered-dither [all] 4x4 ordered4x4g45.pbm ``` Before complaining about my using an "established algorithm" please read the ChangeLog for GraphicsMagick and ImageMagick for April 2003 where you'll see that I implemented the algorithm in those applications. Also, the combination of "-gamma .45455" with "-ordered-dither" is new. The "-gamma .45455" takes care of the image being too light. The "all" parameter is only needed with GraphicsMagick. There's banding because there are only 17 graylevels in a 4x4 ordered-dither image. The appearance of banding can be reduced by using an 8x8 ordered-dither which has 65 levels. Here are the original image, the 4x4 and 8x8 ordered dithered output and the random-threshold output: [![enter image description here](https://i.stack.imgur.com/8Euxq.png)](https://i.stack.imgur.com/8Euxq.png) I prefer the ordered-dither version, but am including the random-threshold version for completeness. ``` magick B2DBy.jpg -gamma .6 -random-threshold 10x90% random-threshold.pbm ``` The "10x90%" means to render below 10 percent intensity pixels as pure black and above 90 percent as pure white, to avoid having a few lonely specks in those areas. It's probably worth noting that both are as memory-efficient as they can possibly be. Neither does any diffusion, so they work one pixel at a time, even when writing ordered-dither blocks, and don't need to know anything about the neighboring pixels. ImageMagick and GraphicsMagick process a row at a time, but it's not necessary for these methods. The ordered-dither conversions take less than .04 second real time on my old x86\_64 computer. [Answer] I apologize for the code style, I threw this together using some libraries we just built in my java class, and it has a bad case of copy-paste and magic numbers. The algorithm picks random rectangles in the image, and checks if the average brightness is greater in the dithered image or the original image. It then turns a pixel on or off to bring the brightnesses closer in line, preferentially picking pixels that are more different from the original image. I think it does a better job bringing out thin details like the puppy's hair, but the image is noisier because it tries to bring out details even in areas with none. ![enter image description here](https://i.stack.imgur.com/ADqGq.png) ``` public void dither(){ int count = 0; ditheredFrame.suspendNotifications(); while(count < 1000000){ count ++; int widthw = 5+r.nextInt(5); int heightw = widthw; int minx = r.nextInt(width-widthw); int miny = r.nextInt(height-heightw); Frame targetCropped = targetFrame.crop(minx, miny, widthw, heightw); Frame ditherCropped = ditheredFrame.crop(minx, miny, widthw, heightw); if(targetCropped.getAverage().getBrightness() > ditherCropped.getAverage().getBrightness() ){ int x = 0; int y = 0; double diff = 0; for(int i = 1; i < ditherCropped.getWidth()-1; i ++){ for(int j = 1; j < ditherCropped.getHeight()-1; j ++){ double d = targetCropped.getPixel(i, j).getBrightness() - ditherCropped.getPixel(i, j).getBrightness(); d += .005* targetCropped.getPixel(i+1, j).getBrightness() - .005*ditherCropped.getPixel(i+1, j).getBrightness(); d += .005* targetCropped.getPixel(i-1, j).getBrightness() - .005*ditherCropped.getPixel(i-1, j).getBrightness(); d += .005* targetCropped.getPixel(i, j+1).getBrightness() -.005* ditherCropped.getPixel(i, j+1).getBrightness(); d += .005* targetCropped.getPixel(i, j-1).getBrightness() - .005*ditherCropped.getPixel(i, j-1).getBrightness(); if(d > diff){ diff = d; x = i; y = j; } } ditherCropped.setPixel(x, y, WHITE); } } else { int x = 0; int y = 0; double diff = 0; for(int i = 1; i < ditherCropped.getWidth()-1; i ++){ for(int j = 1; j < ditherCropped.getHeight()-1; j ++){ double d = ditherCropped.getPixel(i, j).getBrightness() -targetCropped.getPixel(i, j).getBrightness(); d += -.005* targetCropped.getPixel(i+1, j).getBrightness() +.005* ditherCropped.getPixel(i+1, j).getBrightness(); d += -.005* targetCropped.getPixel(i-1, j).getBrightness() +.005* ditherCropped.getPixel(i+1, j).getBrightness(); d += -.005* targetCropped.getPixel(i, j+1).getBrightness() + .005*ditherCropped.getPixel(i, j+1).getBrightness(); d += -.005* targetCropped.getPixel(i, j-1).getBrightness() + .005*ditherCropped.getPixel(i, j-1).getBrightness(); if(d > diff){ diff = d; x = i; y = j; } } ditherCropped.setPixel(x, y, BLACK); } } } ditheredFrame.resumeNotifications(); } ``` [Answer] # Fortran Okay, I'm using an obscure image format called FITS which is used for astronomy. This means there is a Fortran library for reading and writing such images. Also, ImageMagick and Gimp can both read/write FITS images. The algorithm I use is based on "Sierra Lite" dithering, but with two improvements: a) I reduce the propagated error by a factor 4/5. b) I introduce a random variation in the diffusion matrix while keeping its sum constant. Together these almost completely elminiate the patterns seen in OPs example. Assuming you have the CFITSIO library installed, compile with > > gfortran -lcfitsio dither.f90 > > > The file names are hard-coded (couldn't be bothered to fix this). Code: ``` program dither integer :: status,unit,readwrite,blocksize,naxes(2),nfound integer :: group,npixels,bitpix,naxis,i,j,fpixel,un real :: nullval,diff_mat(3,2),perr real, allocatable :: image(:,:), error(:,:) integer, allocatable :: seed(:) logical :: anynull,simple,extend character(len=80) :: filename call random_seed(size=Nrand) allocate(seed(Nrand)) open(newunit=un,file="/dev/urandom",access="stream",& form="unformatted",action="read",status="old") read(un) seed close(un) call random_seed(put=seed) deallocate(seed) status=0 call ftgiou(unit,status) filename='PUPPY.FITS' readwrite=0 call ftopen(unit,filename,readwrite,blocksize,status) call ftgknj(unit,'NAXIS',1,2,naxes,nfound,status) call ftgidt(unit,bitpix,status) npixels=naxes(1)*naxes(2) group=1 nullval=-999 allocate(image(naxes(1),naxes(2))) allocate(error(naxes(1)+1,naxes(2)+1)) call ftgpve(unit,group,1,npixels,nullval,image,anynull,status) call ftclos(unit, status) call ftfiou(unit, status) diff_mat=0.0 diff_mat(3,1) = 2.0 diff_mat(1,2) = 1.0 diff_mat(2,2) = 1.0 diff_mat=diff_mat/5.0 error=0.0 perr=0 do j=1,naxes(2) do i=1,naxes(1) p=max(min(image(i,j)+error(i,j),255.0),0.0) if (p < 127.0) then perr=p image(i,j)=0.0 else perr=p-255.0 image(i,j)=255.0 endif call random_number(r) r=0.6*(r-0.5) error(i+1,j)= error(i+1,j) +perr*(diff_mat(3,1)+r) error(i-1,j+1)=error(i-1,j+1)+perr*diff_mat(1,2) error(i ,j+1)=error(i ,j+1) +perr*(diff_mat(2,2)-r) end do end do call ftgiou(unit,status) blocksize=1 filename='PUPPY-OUT.FITS' call ftinit(unit,filename,blocksize,status) simple=.true. naxis=2 extend=.true. call ftphpr(unit,simple,bitpix,naxis,naxes,0,1,extend,status) group=1 fpixel=1 call ftppre(unit,group,fpixel,npixels,image,status) call ftclos(unit, status) call ftfiou(unit, status) deallocate(image) deallocate(error) end program dither ``` Example output for the puppy image in OPs post: ![Dithered picture of puppy](https://i.stack.imgur.com/asMv8.png) OPs example output: ![OPs dithered picture of puppy](https://i.stack.imgur.com/ivcwx.jpg) [Answer] ## Ghostscript (with little help of ImageMagick) Far from being my 'own new algorithm', but, sorry, could not resist it. ``` convert puppy.jpg puppy.pdf && \ convert puppy.jpg -depth 8 -colorspace Gray -resize 20x20! -negate gray:- | \ gs -q -sDEVICE=ps2write -o- -c \ '<</Thresholds (%stdin) (r) file 400 string readstring pop /HalftoneType 3 /Width 20 /Height 20 >>sethalftone' \ -f puppy.pdf | \ gs -q -sDEVICE=pngmono -o puppy.png - ``` ![enter image description here](https://i.stack.imgur.com/CzUYj.png) Of course it works better without 'same size' restraint. [Answer] ## JAVA Here is my submission. Takes a JPG image, calculates pixel per pixel luminosity (thanks to Bonan in [this](https://stackoverflow.com/questions/21205871/java-bufferedimage-get-single-pixel-brightness) SO question) and then check it against a random pattern for knowing if the resulting pixel will be black or white. Darkerst pixels will be always black and brightest pixels will be always white to preserve image details. ``` import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; public class DitherGrayscale { private BufferedImage original; private double[] threshold = { 0.25, 0.26, 0.27, 0.28, 0.29, 0.3, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.5, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.6, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69 }; public static void main(String[] args) { DitherGrayscale d = new DitherGrayscale(); d.readOriginal(); d.dither(); } private void readOriginal() { File f = new File("original.jpg"); try { original = ImageIO.read(f); } catch (IOException e) { e.printStackTrace(); } } private void dither() { BufferedImage imRes = new BufferedImage(original.getWidth(), original.getHeight(), BufferedImage.TYPE_INT_RGB); Random rn = new Random(); for (int i = 0; i < original.getWidth(); i++) { for (int j = 0; j < original.getHeight(); j++) { int color = original.getRGB(i, j); int red = (color >>> 16) & 0xFF; int green = (color >>> 8) & 0xFF; int blue = (color >>> 0) & 0xFF; double lum = (red * 0.21f + green * 0.71f + blue * 0.07f) / 255; if (lum <= threshold[rn.nextInt(threshold.length)]) { imRes.setRGB(i, j, 0x000000); } else { imRes.setRGB(i, j, 0xFFFFFF); } } } try { ImageIO.write(imRes, "PNG", new File("result.png")); } catch (IOException e) { e.printStackTrace(); } } } ``` ![Processed image](https://i.stack.imgur.com/vEzep.png) Other examples: ![Original](https://i.stack.imgur.com/30qTv.jpg) ![Processed](https://i.stack.imgur.com/4kp0e.png) Also works with full color images: ![Color image](https://i.stack.imgur.com/lcQ0B.jpg) ![Result](https://i.stack.imgur.com/ncNDS.png) [Answer] # CJam ``` lNl_~:H;:W;Nl;1N[{[{ri}W*]{2/{:+}%}:P~}H*]z{P}%:A;H{W{I2/A=J2/=210/[0X9EF]=I2%2*J2%+m>2%N}fI}fJ ``` 95 bytes :) It uses the [ASCII PGM (P2) format](http://en.wikipedia.org/wiki/Netpbm_format) with no comment line, for both input and output. The method is very basic: it adds up squares of 2\*2 pixels, converts to the 0..4 range, then uses a corresponding pattern of 4 bits to generate 2\*2 black-and-white pixels. That also means that the width and height must be even. Sample: ![deterministic puppy](https://i.stack.imgur.com/WnAbk.png) And a random algorithm in only 27 bytes: ``` lNl_~*:X;Nl;1N{ri256mr>N}X* ``` It uses the same file format. Sample: ![random puppy](https://i.stack.imgur.com/dnhMU.png) And finally a mixed approach: random dithering with a bias towards a checkerboard pattern; 44 bytes: ``` lNl_~:H;:W;Nl;1NH{W{ri128_mr\IJ+2%*+>N}fI}fJ ``` Sample: ![mixed puppy](https://i.stack.imgur.com/rANkB.png) [Answer] # Python The idea is following: The image gets divided in to `n x n` tiles. We calculate the average colour each of those tiles. Then we map the colour range `0 - 255` to the range `0 - n*n` which gives us a new value `v`. Then we colour all pixels from that tile black, and randomly colour `v` pixels within that tile white. It is far from optimal but still gives us recognizable results. Depending on the resolution, it works usually best at `n=2` or `n=3`. While in `n=2` you can already find artefacts from the 'simulated colour depth, in case `n=3` it can already get somewhat blurry. I assumed that the images should stay the same size, but you can of course also use this method and just double/triple the size of the generated image in order to get more details. PS: I know that I am a bit late to the party, I remember that I did not have any ideas when the challenge started but now just had this brain wave=) ``` from PIL import Image import random im = Image.open("dog.jpg") #Can be many different formats. new = im.copy() pix = im.load() newpix = new.load() width,height=im.size print([width,height]) print(pix[1,1]) window = 3 # input parameter 'n' area = window*window for i in range(width//window): #loop over pixels for j in range(height//window):#loop over pixels avg = 0 area_pix = [] for k in range(window): for l in range(window): area_pix.append((k,l))#make a list of coordinates within the tile try: avg += pix[window*i+k,window*j+l][0] newpix[window*i+k,window*j+l] = (0,0,0) #set everything to black except IndexError: avg += 255/2 #just an arbitrary mean value (when were outside of the image) # this is just a dirty trick for coping with images that have # sides that are not multiples of window avg = avg/area # val = v is the number of pixels within the tile that will be turned white val = round(avg/255 * (area+0.99) - 0.5)#0.99 due to rounding errors assert val<=area,'something went wrong with the val' print(val) random.shuffle(area_pix) #randomize pixel coordinates for m in range(val): rel_coords = area_pix.pop()#find random pixel within tile and turn it white newpix[window*i+rel_coords[0],window*j+rel_coords[1]] = (255,255,255) new.save('dog_dithered'+str(window)+'.jpg') ``` ## Results: `n=2:` [![enter image description here](https://i.stack.imgur.com/S0NVq.jpg)](https://i.stack.imgur.com/S0NVq.jpg) `n=3:` [![enter image description here](https://i.stack.imgur.com/cyDZZ.jpg)](https://i.stack.imgur.com/cyDZZ.jpg) [Answer] ## Java (1.4+) I am not sure as to whether I am re-inventing the wheel here but I think it may be unique... [![with limited random sequences](https://i.stack.imgur.com/EW0r1.png)](https://i.stack.imgur.com/EW0r1.png) With limited random sequences [![Pure random dithering](https://i.stack.imgur.com/DoX3e.png)](https://i.stack.imgur.com/DoX3e.png) Pure random dithering [![enter image description here](https://i.stack.imgur.com/jUGcu.png)](https://i.stack.imgur.com/jUGcu.png) City image from [Averroes's answer](https://codegolf.stackexchange.com/a/26690/20193) The algorithm uses the concept of localized luminosity energy and normalizing to retain features. The initial version then used a random jitter to produce a dithered look over areas of similar luminosity. However it was not that visually appealing. To counter this, a limited set of limited random sequences are mapped to raw input pixel luminosity and samples are used iteratively and repeatedly yielding dithered looking backgrounds. ``` import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class LocalisedEnergyDitherRepeatRandom { static private final float EIGHT_BIT_DIVISOR=1.0F/256; private static final int KERNEL_SIZE_DIV_2 =4; private static final double JITTER_MULTIPLIER=0.01; private static final double NO_VARIANCE_JITTER_MULTIPLIER=1.5; private static final int RANDOM_SEQUENCE_LENGTH=10; private static final int RANDOM_SEQUENCE_COUNT=20; private static final boolean USE_RANDOM_SEQUENCES=true; public static void main(String args[]) throws Exception { BufferedImage image = ImageIO.read(new File("data/dog.jpg")); final int width = image.getWidth(); final int height = image.getHeight(); float[][][] yuvImage =convertToYUVImage(image); float[][][] outputYUVImage = new float[width][height][3]; double circularKernelLumaMean,sum,jitter,outputLuma,variance,inputLuma; int circularKernelPixelCount,y,x,kx,ky; double[][] randomSequences = new double[RANDOM_SEQUENCE_COUNT][RANDOM_SEQUENCE_LENGTH]; int[] randomSequenceOffsets = new int[RANDOM_SEQUENCE_COUNT]; // Generate random sequences for (y=0;y<RANDOM_SEQUENCE_COUNT;y++) { for (x=0;x<RANDOM_SEQUENCE_LENGTH;x++) { randomSequences[y][x]=Math.random(); } } for (y=0;y<height;y++) { for (x=0;x<width;x++) { circularKernelLumaMean=0; sum=0; circularKernelPixelCount=0; /// calculate the mean of the localised surrounding pixels contained in /// the area of a circle surrounding the pixel. for (ky=y-KERNEL_SIZE_DIV_2;ky<y+KERNEL_SIZE_DIV_2;ky++) { if (ky>=0 && ky<height) { for (kx=x-KERNEL_SIZE_DIV_2;kx<x+KERNEL_SIZE_DIV_2;kx++) { if (kx>=0 && kx<width) { double distance= Math.sqrt((x-kx)*(x-kx)+(y-ky)*(y-ky)); if (distance<=KERNEL_SIZE_DIV_2) { sum+=yuvImage[kx][ky][0]; circularKernelPixelCount++; } } } } } circularKernelLumaMean=sum/circularKernelPixelCount; /// calculate the variance of the localised surrounding pixels contained in /// the area of a circle surrounding the pixel. sum =0; for (ky=y-KERNEL_SIZE_DIV_2;ky<y+KERNEL_SIZE_DIV_2;ky++) { if (ky>=0 && ky<height) { for (kx=x-KERNEL_SIZE_DIV_2;kx<x+KERNEL_SIZE_DIV_2;kx++) { if (kx>=0 && kx<width) { double distance= Math.sqrt((x-kx)*(x-kx)+(y-ky)*(y-ky)); if (distance<=KERNEL_SIZE_DIV_2) { sum+=Math.abs(yuvImage[kx][ky][0]-circularKernelLumaMean); } } } } } variance = sum/(circularKernelPixelCount-1); if (variance==0) { // apply some jitter to ensure there are no large blocks of single colour inputLuma=yuvImage[x][y][0]; jitter = Math.random()*NO_VARIANCE_JITTER_MULTIPLIER; } else { // normalise the pixel based on localised circular kernel inputLuma = outputYUVImage[x][y][0]=(float) Math.min(1.0, Math.max(0,yuvImage[x][y][0]/(circularKernelLumaMean*2))); jitter = Math.exp(variance)*JITTER_MULTIPLIER; } if (USE_RANDOM_SEQUENCES) { int sequenceIndex =(int) (yuvImage[x][y][0]*RANDOM_SEQUENCE_COUNT); int sequenceOffset = (randomSequenceOffsets[sequenceIndex]++)%RANDOM_SEQUENCE_LENGTH; outputLuma=inputLuma+randomSequences[sequenceIndex][sequenceOffset]*jitter*2-jitter; } else { outputLuma=inputLuma+Math.random()*jitter*2-jitter; } // convert 8bit luma to 2 bit luma outputYUVImage[x][y][0]=outputLuma<0.5?0:1.0f; } } renderYUV(image,outputYUVImage); ImageIO.write(image, "png", new File("data/dog.jpg.out.png")); } /** * Converts the given buffered image into a 3-dimensional array of YUV pixels * @param image the buffered image to convert * @return 3-dimensional array of YUV pixels */ static private float[][][] convertToYUVImage(BufferedImage image) { final int width = image.getWidth(); final int height = image.getHeight(); float[][][] yuv = new float[width][height][3]; for (int y=0;y<height;y++) { for (int x=0;x<width;x++) { int rgb = image.getRGB( x, y ); yuv[x][y]=rgb2yuv(rgb); } } return yuv; } /** * Renders the given YUV image into the given buffered image. * @param image the buffered image to render to * @param pixels the YUV image to render. * @param dimension the */ static private void renderYUV(BufferedImage image, float[][][] pixels) { final int height = image.getHeight(); final int width = image.getWidth(); int rgb; for (int y=0;y<height;y++) { for (int x=0;x<width;x++) { rgb = yuv2rgb( pixels[x][y] ); image.setRGB( x, y,rgb ); } } } /** * Converts a RGB pixel into a YUV pixel * @param rgb a pixel encoded as 24 bit RGB * @return array representing a pixel. Consisting of Y,U and V components */ static float[] rgb2yuv(int rgb) { float red = EIGHT_BIT_DIVISOR*((rgb>>16)&0xFF); float green = EIGHT_BIT_DIVISOR*((rgb>>8)&0xFF); float blue = EIGHT_BIT_DIVISOR*(rgb&0xFF); float Y = 0.299F*red + 0.587F * green + 0.114F * blue; float U = (blue-Y)*0.565F; float V = (red-Y)*0.713F; return new float[]{Y,U,V}; } /** * Converts a YUV pixel into a RGB pixel * @param yuv array representing a pixel. Consisting of Y,U and V components * @return a pixel encoded as 24 bit RGB */ static int yuv2rgb(float[] yuv) { int red = (int) ((yuv[0]+1.403*yuv[2])*256); int green = (int) ((yuv[0]-0.344 *yuv[1]- 0.714*yuv[2])*256); int blue = (int) ((yuv[0]+1.77*yuv[1])*256); // clamp to 0-255 range red=red<0?0:red>255?255:red; green=green<0?0:green>255?255:green; blue=blue<0?0:blue>255?255:blue; return (red<<16) | (green<<8) | blue; } } ``` [Answer] # Dyalog APL This is an implementation of ordered dither with a special dither array. The input format is a restricted form of raster PGM while it is also the default style produced by Netpbm programs that requires no comment line, file header separated by newline character rather than arbitrary whitespace, and assumes "maxval" to be 255, so the file can be handled easily with APL's `⎕MAP` system function. The output format satisfies raster PBM specification. This program can dither images as large as 3000×2000 in very short time, however for larger image it needs more than default workspace size. ``` ∇img←readpgm file;data;size data←83 ¯1 ⎕MAP file ⍝ drop magic data←(⊢↓⍨⍳∘10)data size←⌽⍎⎕UCS ¯1↓(⊢↑⍨⍳∘10)data img←size⍴256|(⊢↓⍨⍳∘10)⍣2⊢data ∇ ∇img writepbm file;data;size;h;s;tie tie←file(⎕NCREATE⍠'IfExists' 'Error')0 h←10,⍨⎕UCS'P4 ',⍕size←⌽⍴img tie ⎕ARBOUT h s←8×⌈8÷⍨⊃size data←,⍉s↑⍉img data←2⊥⍉data⍴⍨8,⍨8÷⍨≢data tie ⎕ARBOUT data ⎕NUNTIE tie ∇ da←1 8⍴51 25 61 10 45 57 8 16 da⍪←58 6 34 23 1 36 49 30 da⍪←44 32 29 14 41 62 20 12 da⍪←2 21 60 52 47 4 24 55 da⍪←50 9 18 7 38 28 15 40 da⍪←37 56 26 43 59 11 53 35 da⍪←46 13 31 3 48 22 5 63 da⍪←0 19 33 54 17 39 27 42 dither←{ ⎕IO←0 x y←⍴⍵ a b←⍴⍺ (63×⍵÷255)<(,⍺)[(x y⍴y⍴⍳b)+⍉y x⍴x⍴b×⍳a] } 'out.pbm' writepbm⍨ da dither readpgm 'input.pgm' ``` [![input image](https://i.stack.imgur.com/sRShq.png)](https://i.stack.imgur.com/sRShq.png) [![output image](https://i.stack.imgur.com/gGPv9.png)](https://i.stack.imgur.com/gGPv9.png) [![OP's image for completeness](https://i.stack.imgur.com/2st8g.png)](https://i.stack.imgur.com/2st8g.png) [Answer] > > Any file format you want is fine. > > > Let's define a very compact, theoretical file format for this question as any of the existing file formats have too much overhead to write a quick answer for. Let the first four bytes of the image file define the width and height of the image in pixels, respectively: ``` 00000001 00101100 00000001 00101100 width: 300 px height: 300 px ``` followed by `w * h` bytes of grayscale values from 0 to 255: ``` 10000101 10100101 10111110 11000110 ... [89,996 more bytes] ``` Then, we can define a piece of code in Python (145 bytes) that will take this image and do: ``` import random f=open("a","rb");g=open("b","wb");g.write(f.read(4)) for i in f.read():g.write('\xff' if ord(i)>random.randint(0,255) else '\x00') ``` which "dithers" by returning white or black with probability equal to the grayscale value of that pixel. --- Applied on the sample image, it gives something like this: ![dithered dog](https://i.stack.imgur.com/AexU2.png) It's not too pretty, but it does look very similar when scaled down in a preview, and for just 145 bytes of Python, I don't think you can get much better. [Answer] # Cobra Takes a 24-bit or 32-bit PNG/BMP file (JPG produces output with some greys in it). It is also extensible to files containing color. It uses speed-optimized ELA to dither the image into 3-bit color, which will return as black/white when given your test image. Did I mention that it's really fast? ``` use System.Drawing use System.Drawing.Imaging use System.Runtime.InteropServices use System.IO class BW_Dither var path as String = Directory.getCurrentDirectory to ! var rng = Random() def main file as String = Console.readLine to ! image as Bitmap = Bitmap(.path+"\\"+file) image = .dither(image) image.save(.path+"\\test\\image.png") def dither(image as Bitmap) as Bitmap output as Bitmap = Bitmap(image) layers as Bitmap[] = @[ Bitmap(image), Bitmap(image), Bitmap(image), Bitmap(image), Bitmap(image), Bitmap(image), Bitmap(image)] layers[0].rotateFlip(RotateFlipType.RotateNoneFlipX) layers[1].rotateFlip(RotateFlipType.RotateNoneFlipY) layers[2].rotateFlip(RotateFlipType.Rotate90FlipX) layers[3].rotateFlip(RotateFlipType.Rotate90FlipY) layers[4].rotateFlip(RotateFlipType.Rotate90FlipNone) layers[5].rotateFlip(RotateFlipType.Rotate180FlipNone) layers[6].rotateFlip(RotateFlipType.Rotate270FlipNone) for i in layers.length, layers[i] = .dither_ela(layers[i]) layers[0].rotateFlip(RotateFlipType.RotateNoneFlipX) layers[1].rotateFlip(RotateFlipType.RotateNoneFlipY) layers[2].rotateFlip(RotateFlipType.Rotate270FlipY) layers[3].rotateFlip(RotateFlipType.Rotate270FlipX) layers[4].rotateFlip(RotateFlipType.Rotate270FlipNone) layers[5].rotateFlip(RotateFlipType.Rotate180FlipNone) layers[6].rotateFlip(RotateFlipType.Rotate90FlipNone) vals = List<of List<of uint8[]>>() data as List<of uint8[]> = .getData(output) for l in layers, vals.add(.getData(l)) for i in data.count, for c in 3 x as int = 0 for n in vals.count, if vals[n][i][c] == 255, x += 1 if x > 3.5, data[i][c] = 255 to uint8 if x < 3.5, data[i][c] = 0 to uint8 .setData(output, data) return output def dither_ela(image as Bitmap) as Bitmap error as decimal[] = @[0d, 0d, 0d] rectangle as Rectangle = Rectangle(0, 0, image.width, image.height) image_data as BitmapData = image.lockBits(rectangle, ImageLockMode.ReadWrite, image.pixelFormat) to ! pointer as IntPtr = image_data.scan0 bytes as uint8[] = uint8[](image_data.stride * image.height) pfs as int = Image.getPixelFormatSize(image.pixelFormat) // 8 Marshal.copy(pointer, bytes, 0, image_data.stride * image.height) for y as int in image.height, for x as int in image.width position as int = (y * image_data.stride) + (x * pfs) for i in 3 error[i] -= bytes[position + i] if Math.abs(error[i] + 255 - bytes[position + i]) < Math.abs(error[i] - bytes[position + i]) bytes[position + i] = 255 to uint8 error[i] += 255 else, bytes[position + i] = 0 to uint8 Marshal.copy(bytes, 0, pointer, image_data.stride * image.height) image.unlockBits(image_data) return image def getData(image as Bitmap) as List<of uint8[]> rectangle as Rectangle = Rectangle(0, 0, image.width, image.height) image_data as BitmapData = image.lockBits(rectangle, ImageLockMode.ReadOnly, image.pixelFormat) to ! pointer as IntPtr = image_data.scan0 bytes as uint8[] = uint8[](image_data.stride * image.height) pixels as List<of uint8[]> = List<of uint8[]>() for i in image.width * image.height, pixels.add(nil) pfs as int = Image.getPixelFormatSize(image.pixelFormat) // 8 Marshal.copy(pointer, bytes, 0, image_data.stride * image.height) count as int = 0 for y as int in image.height, for x as int in image.width position as int = (y * image_data.stride) + (x * pfs) if pfs == 4, alpha as uint8 = bytes[position + 3] else, alpha as uint8 = 255 pixels[count] = @[ bytes[position + 2], #red bytes[position + 1], #green bytes[position], #blue alpha] #alpha count += 1 image.unlockBits(image_data) return pixels def setData(image as Bitmap, pixels as List<of uint8[]>) if pixels.count <> image.width * image.height, throw Exception() rectangle as Rectangle = Rectangle(0, 0, image.width, image.height) image_data as BitmapData = image.lockBits(rectangle, ImageLockMode.ReadWrite, image.pixelFormat) to ! pointer as IntPtr = image_data.scan0 bytes as uint8[] = uint8[](image_data.stride * image.height) pfs as int = Image.getPixelFormatSize(image.pixelFormat) // 8 Marshal.copy(pointer, bytes, 0, image_data.stride * image.height) count as int = 0 for y as int in image.height, for x as int in image.width position as int = (y * image_data.stride) + (x * pfs) if pfs == 4, bytes[position + 3] = pixels[count][3] #alpha bytes[position + 2] = pixels[count][0] #red bytes[position + 1] = pixels[count][1] #green bytes[position] = pixels[count][2] #blue count += 1 Marshal.copy(bytes, 0, pointer, image_data.stride * image.height) image.unlockBits(image_data) ``` ![Dog](https://i.stack.imgur.com/yqLn1.png) ![Trees](https://i.stack.imgur.com/VZF9y.jpg) [Answer] ## Java Low level code, using [PNGJ](https://code.google.com/p/pngj/) and a noise addition plus basic diffusion. This implementation requires a grayscale 8-bits PNG source. ``` import java.io.File; import java.util.Random; import ar.com.hjg.pngj.ImageInfo; import ar.com.hjg.pngj.ImageLineInt; import ar.com.hjg.pngj.PngReaderInt; import ar.com.hjg.pngj.PngWriter; public class Dither { private static void dither1(File file1, File file2) { PngReaderInt reader = new PngReaderInt(file1); ImageInfo info = reader.imgInfo; if( info.bitDepth != 8 && !info.greyscale ) throw new RuntimeException("only 8bits grayscale valid"); PngWriter writer = new PngWriter(file2, reader.imgInfo); ImageLineInt line2 = new ImageLineInt(info); int[] y = line2.getScanline(); int[] ye = new int[info.cols]; int ex = 0; Random rand = new Random(); while(reader.hasMoreRows()) { int[] x = reader.readRowInt().getScanline(); for( int i = 0; i < info.cols; i++ ) { int t = x[i] + ex + ye[i]; y[i] = t > rand.nextInt(256) ? 255 : 0; ex = (t - y[i]) / 2; ye[i] = ex / 2; } writer.writeRow(line2); } reader.end(); writer.end(); } public static void main(String[] args) { dither1(new File(args[0]), new File(args[1])); System.out.println("See output in " + args[1]); } } ``` (Add [this jar](http://hjg.com.ar/pngj/releases/2.1.0/pngj-2.1.0.jar) to your build path if you want to try it). ![enter image description here](https://i.stack.imgur.com/SzIXw.png) As a bonus: this is extremely efficient in memory usage (it only stores three rows) so it could be used for huge images. [Answer] # Python The code is quite bad, so I'll try to explain the algorithm. For each pixel, it stores the brightness of the pixel in the variable `brightness`, and changes `brightness` based on the values of `x % 2` and `y % 2`, where `x` and `y` are coordinates of that pixel. This creates a typical two by two regular dithering pattern. Then, `brightness` is randomly changed by some amount to hide banding and strongly visible patterns created by the dithering algorithm. Finally, `brightness` is changed by the difference between the average brightness of the current pixel and the average brightness of the pixel around it. This makes details and outlines more visible, since small groups of pixels that are very different from their surroundings are more likely to get a different color than their surroundings. The brightness is then rounded to 0 (black) or 1 (white). The program has four parameters that can be changed to change the result: `dither_details`, which determines how likely pixels with a different brightness than their surroundings are to get a different color than their surroundings; `dither_regular`, which determines how strong the typical two by two dithering pattern is, `dither_random`, which determines the strength of the random dithering; and `s`, which determines how big an area of its surrounding the pixels are compared to. ![](https://i.stack.imgur.com/J4uiY.png) When `dither_details` equals 999 and `s` equals 2, the program gives a result quite similar to [@Moogie's submission](https://codegolf.stackexchange.com/a/73457/108622) (the rectangle-like patterns are likely a product of image compression): ![](https://i.stack.imgur.com/EOcVe.png) ``` import matplotlib.image as mplimg import matplotlib as mpl import matplotlib.pyplot as plt import numpy image = mplimg.imread("pup.png") new_im = [ [0 for x in range(len(image[0]))] for y in range(len(image))] def avg(x, y, f): sum_ = 0 n = 0 for x1 in range(x, x + f): for y1 in range(y, y + f): if x1 < 0 or x1 >= len(image[0]) or y1 < 0 or y1 >= len(image): continue n += 1 sum_ += image[y1][x1] return sum_ / n dither_details = 3.0 dither_regular = 0.15 dither_random = 0.03 s = 3 for x in range(len(image[0])): for y in range(len(image)): brightness = image[y][x] if x % 2 == 0 and y % 2 == 0: brightness += dither_regular elif x % 2 == 1 and y % 2 == 1: brightness += dither_regular / 2 elif x % 2 == 0 and y % 2 == 1: brightness -= dither_regular elif x % 2 == 1 and y % 2 == 0: brightness -= dither_regular / 2 brightness += numpy.random.normal(scale = dither_random) average_brightness = avg(x - s, y - s, s * 2 + 1) brightness += image[y][x] * dither_details - average_brightness * dither_details new_im[y][x] = 0 if brightness < 0.5 else 1 dpi = 16 mpl.rcParams['savefig.dpi'] = dpi * 16 plt.figure(figsize=(len(image[0]) / dpi, len(image) / dpi), dpi = dpi * 16) plt.axis("off") plt.imshow(new_im, cmap = "gray", interpolation = "nearest") plt.savefig("dither.png", bbox_inches="tight") plt.show() ``` [Answer] # Java Just a simple RNG-based algorithm, plus some logic for dealing with color images. Has probability *b* of setting any given pixel to white, sets it to black otherwise; where *b* is that pixel's original brightness. ``` import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import java.util.Scanner; import javax.imageio.ImageIO; public class Ditherizer { public static void main(String[]a) throws IOException{ Scanner input=new Scanner(System.in); Random rand=new Random(); BufferedImage img=ImageIO.read(new File(input.nextLine())); for(int x=0;x<img.getWidth();x++){ for(int y=0;y<img.getHeight();y++){ Color c=new Color(img.getRGB(x, y)); int r=c.getRed(),g=c.getGreen(),b=c.getBlue(); double bright=(r==g&&g==b)?r:Math.sqrt(0.299*r*r+0.587*g*g+0.114*b*b); img.setRGB(x,y,(rand.nextInt(256)>bright?Color.BLACK:Color.WHITE).getRGB()); } } ImageIO.write(img,"jpg",new File(input.nextLine())); input.close(); } } ``` Here's a potential result for the dog image: [![enter image description here](https://i.stack.imgur.com/TGfdN.jpg)](https://i.stack.imgur.com/TGfdN.jpg) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 28 bytes ``` x=>x.map(t=>t>Math.random()) ``` [Try it online!](https://tio.run/##RY8/T8MwFMR3PoUXGhu5jxbIFNkDAylDAYl2iipkOX7FVf4Y@xXKpw9BLUW67XS/u9uZT5Ns9IGmXV@7AdVwUPoArQmclCa9NPQO0XR133IhhgKTiu5j76PjGaZMFBelwgTRmfrBN@71u7M8e3x6Wa8ghPbXX6gKAMoNoG/IRc7fpBdKez2/Y5MJ85e3Ss3EufH6Js/H1Mj8ip7cP/R5vfqjyvs9ootg@84a4lUJqfHW8Zmc50Kyk4tx3Ix8IQAbQ8sjv6IrNTZIkrQRYlQxILbBbdnUs@PuXdiy84Mf "JavaScript (Node.js) – Try It Online") [![enter image description here](https://i.stack.imgur.com/j7rnS.png)](https://i.stack.imgur.com/j7rnS.png) Trying to golf one ]
[Question] [ ## The Challenge The challenge is simple: given an input list `a` and another list `b`, repeat `a` until it is longer than `b`. As an example, call the repeated list `ra`. Then the following condition must hold true: `len(b) < len(ra) <= len(b) + len(a)`. That is, `a` must not be repeated more than is required. ## Sample Python Implementation ``` def repeat(a, b): ra = a.copy() while len(b) >= len(ra): ra += a return ra ``` [Try it online!](https://tio.run/##LcxLCoNAEIThtZ6il9OkCCSaJ5iLiIvWdFCQcWgmBE8/UXFXi6/@MMd@8kVKb/2QaVCJTkAtP/PMhCqSYzeF2XGe/fphVBrVu5bpVW3LZIWrPCx0uWj8mieTFGzw0e3F@oQzigZUl7jgihvueDTM6Q8 "Python 3 – Try It Online") ## Examples ``` [1,2,3], [2,4] -> [1,2,3] [1,2,3], [2,3,4] -> [1,2,3,1,2,3] [1,2,3], [18,26,43,86] -> [1,2,3,1,2,3] [2,3,5], [1,2,3,4,5,6,7] -> [2,3,5,2,3,5,2,3,5] [1,123], [1,12,123,1234] -> [1,123,1,123,1,123] ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins. Have fun! [Answer] # [Python 3](https://docs.python.org/3/), 29 bytes ``` lambda x,y:len(y)//len(x)*x+x ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PycxNyklUaFCp9IqJzVPo1JTXx9EV2hqVWhX/P8PAA "Python 3 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` *¹→¤÷L ``` [Try it online!](https://tio.run/##yygtzv7/X@vQzkdtkw4tObzd5////9GGOoZGxrEQGsQEYZNYAA "Husk – Try It Online") ``` ¤ # combin: ¤ f g x y = f (g x) (g y) L # where g = length ÷ # and f = integer divide # so ¤÷L calculates the (integer) ratio of input lengths; → # then increment the result, *¹ # and repeat input 1 that many times ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 7 bytes ``` ₅?Lḭ›ẋf ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJyIiwiIiwi4oKFP0zhuK3igLrhuotmIiwiIiwiWzIsMyw1XVxuWzEsMiwzLDQsNSw2LDddIl0=) **How it works:** ``` ₅?Lḭ›ẋf ₅ # Push first list and its length ?Lḭ # Integer-divide by length of second list › # Increment ^ ẋ # Repeat first list that many times f # Flatten into a single list ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~20~~ 18 bytes ``` {(A×⌈(⍴⍵,1)÷A←⍴⍺)⍴⍺} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@lR24RqDcfD0x/1dGg86t3yqHerjqHm4e2OQHEwd5cmhKr9/99QwUjBWCFJwRBImiiYKphxGQLZID4YcsHlLRSMzBRMjBUszLhAIqZgNSAWmATpMoKYY2gEZgKxCQA "APL (Dyalog Unicode) – Try It Online") Thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m) for golfing some bytes and helping me to fix errors in chat. `⎕←,⍣2⍨'thanks'` -2 thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco) `⎕←'thanks'` [Answer] # [J](http://jsoftware.com/), ~~15~~ 14 bytes *-1 byte thanks to [Jonah](https://codegolf.stackexchange.com/users/15469/jonah)'s very clever idea!* ``` ];@;<.@%&##<@] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Y60drG30HFTVlJVtHGL/a3L5OekpxKrUKTvEahkCJbSBMmAxINvOCqTO2kEFqJIrNTkjX8FIwUQhTcEQSBvDBIyxC5miChrChc0UzIFSIJ7pfwA "J – Try It Online") Takes input as `b f a`, if `f` is the name you assign the verb to. ## Explanation ``` ];@;<.@%&##<@] % divide &# the lengths of the lists by each other <.@ and floor it; <@] box b # and repeat it that many times ] ; prepend b to this boxed array ;@ and raze the result, collapsing it into a single list ``` Instead of incrementing the division result, as I did in the first version below, we simply prepend the input list to the resulting tiled box list, which is equivalent. ## Old Answer ``` ]$~#@]*1<.@+%&# ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6zkE6Pm7/Y1XqlB1itQxt9By0VdWU/2typSZn5CsYKZgo4ABpQGwIVGAMU2mMSy2aSkMLBSMzBRNjBQszQiqhppoqmCmYY6oESZrCVBoaAZExCJtgMxMojk0liDAlQSWYNEOo/A8A "J – Try It Online") ### Explanation ``` ]$~#@]*1<.@+%&# % divide &# the lengths of the lists by each other 1 + increment <.@ and floor * multiplied by #@] length of a ]$~ and reshape a to be that length ``` Unfortunately, `#` doesn't work here, as it doesn't preserve the order. (`1 1 1 2 2 2 3 3 3 -: 3 # 1 2 3`.) [Answer] # Curry, ~~57~~ 42 bytes This being my first Curry answer, I'm pretty certain its not quite optimal, but as it is our current lang of the month, I figured I'd give at least a half-hearted try at it. ``` l=length a!b|l a>l b=a|1>0=a++a!drop(l a)b ``` Edit: [Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z/HNic1L70kgytRMakmRyHRLkchyTaxxtDOwDZRWztRMaUov0ADKK6Z9D83MTNPwVYh2kjHWMc0VkFRIdpQB8Q20THVMdMx17GI/Q8A) A bit longer than I'd like, my first idea involved the recursive return being `r(a++a)b`, but I realized that didn't work unless the correct number of repetitions was a power of two. Edit -15 bytes from some good tips by [WheatWizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` gIg÷>и ``` Takes the input-lists in the order \$b,a\$. [Try it online](https://tio.run/##yy9OTMpM/f8/3TP98Ha7Czv@/4820jHWMYnlijbUAbJiAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWWCS9H/9OL0w9vtLuz4r/M/OjraSMc4VifaUAdEx@oogAV0TFCFDC10jMx0TIx1LMzQJHTAqnVMdcx0zIFSIJ4pTMrQCIiMQRhiHJARGxsLAA). **Explanation:** ``` g # Push the length of the first (implicit) input-list `b` Ig # Push the length of the second input-list `a` ÷ # Integer-divide the length by `b` by that of `a` > # Increase it by 1 и # Repeat the second (implicit) input-list `a` that many times # (after which the result is output implicitly) ``` [Answer] # Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 18 bytes ``` m**frt$P1<<fdv.*l ``` Divide the lengths, add 1 and then repeat that many times. # Reflection This is kind of long, but also pretty compact. Part of the issue is that variable reuse is always going to be a bit long. We also have to use both `frt` and `fdv` which are unfortunately 3 bytes each. It's totally possible to do this without flipping via `rt` and `dv` ``` m jn$rt<<P1<<dv.*l ``` But that ends up being a byte longer. It seems mostly like a quirk of the specific problem that flipping is required. The only real improvement I can see here is to combine some of the glue used to make things more compact. * `m jn` used in the 19 byte solution could be 1 function. It has a useful type. If it were 3 bytes it would save 1 byte overall ``` mjn$rt<<P1<<dv.*l ``` * `l2 m` is a little more niche but could be added. As a 3 byte prefix it would actually have *costed* a byte here ``` l2m frt$P1<<fdv.*l ``` It could also be an infix, but that also costs a byte. ``` frt**<(P1<<fdv.*l) ``` However in better circumstances it could potentially save a byte. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ẋɓL:L}‘ ``` [Try it online!](https://tio.run/##y0rNyan8///hru6Tk32sfGofNcz4f3i5/tFJD3fO0Iz8/z862lDHSMc4Vkch2kjHJBZEI4sYY4gZWugYmemYGOtYmEFkQIpMwTI6YPU6pjpmOuYwXYZGEF1ABogNwkATAQ "Jelly – Try It Online") Nothing all too original. ``` ẋ Repeat a by ɓL the length of b :L} floor divided by the length of a ‘ plus 1. ``` [Answer] # [Perl 5](https://www.perl.org/), 29 bytes ``` sub{(@{$a=shift})x(1+@_/@$a)} ``` [Try it online!](https://tio.run/##fZBNS8MwGMfP5lM8hGgbfET66liJ5i64y261jEaTOtS1thUmpZ@9Jt0ERVgO4f/2uzyNbt@SiRkxdZ9q8OXAStG9bE0/8r0fXMrNtWQlH6eMmLr1SQ725QGGGBUIeYhxAeL2J7Fdgf830Z8VntgGCwxTjCNcpKcJlyYzMQ9iTDDFmwMzd/jrP5J8II59//JZiUwh01xItsmOqazEBTOuk0zxQ9q0211v6PlV2llXLsEewwrlhLJC7xv91Otn57X1Vd1bWT3uKJIzajMK@gOorCjcgVe/erAE72G1htW9l5Fx@gY "Perl 5 – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~10~~ 9 bytes ``` *h/l.).Ql ``` [Try it online!](https://tio.run/##K6gsyfj/XytDP0dPUy8w5///aCMdYx3TWK5oQx0Qy0THVMdMxzwWAA "Pyth – Try It Online") ``` *h/l.).Ql l.).Q # get the length of the second list / l # integer divide it by the length of the first list h # increment the result of the division * # multiply by the first list (like int * list in Python) ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 18 bytes ``` {(~(#y)<#:)(x,)/x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxtT0FugzAQvPsVK6UHLBksbONQXPUVuSFLQRQSFAopOBIoSt5e7NKEJj3seHZmNCuXydm7eqsRv60S7A0E0+GC0CY5v6TjtUtKCGBQ2/agvG2ZVbUa1Kg6rC9ok3ohMOCKgcDKUb0U+U2GRzOMgUkQHGL5HLFbNKsCIpCwxq4uggXObSGb2ia0xI476fgdNUIU7Y059gmleftR7Nq6DHqT5YdiyPdZsyuCvP2kX6eiN1Xb9JQJ/hrFtCuORWb8uuqNf2pMVft1O4U7hNKQMMI1pIwIDf47zMLS4H8s8hgIY8IkEZzE8r+Y5ZH+VQWJiCTrn6CzyAJdq/0ouNdSO7fzbr+jRt+7lHTR) Appends copies of `x` until the length is greater than the length of `y`. * `(cond)(code)/x` set up a while-reduce, beginning with `x`, the input. the "code" part is repeated until the "cond" part returns a non-truthy value + `(~(#y)<#:)` check whether or not the current list is longer than `y` + `(x,)` prepend a copy to the current list An alternative version, with the same byte count, instead uses the do-reduce overload, swapping `(~(#y)<#:)` for `((-#x)!#y)`. [Answer] # [Desmos](https://desmos.com/calculator), ~~55~~ 49 bytes ``` f(a,b)=[lforl=a,i=[0...floor(b.length/a.length)]] ``` [Try It On Desmos!](https://www.desmos.com/calculator/b8wdtegkqi) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/bemfawamsu) ~~I had to write `l=a[1...]` instead of just `l=a` because apparently Desmos defaults to recognizing function arguments as numbers, which the list comprehension doesn't like. The workaround is to force Desmos to recognize it as a list by slicing it in such a way that it just returns the entire list, resulting in +6 bytes.~~ Apparently the workaround wasn't even necessary because I *think* `a.length` forces Desmos to recognize `a` as a list, rather than a number. Thanks [@att](https://codegolf.stackexchange.com/users/81203/att) for helping me realize this. [Answer] # [Factor](https://factorcode.org/) + `sequences.repeating`, ~~45~~ 42 bytes ``` [ length over length tuck /i 1 + * cycle ] ``` [![enter image description here](https://i.stack.imgur.com/eODfW.gif)](https://i.stack.imgur.com/eODfW.gif) ## Explanation ``` ! { 2 3 5 } { 1 2 3 4 5 6 7 } length ! { 2 3 5 } 7 over ! { 2 3 5 } 7 { 2 3 5 } length ! { 2 3 5 } 7 3 tuck ! { 2 3 5 } 3 7 3 /i ! { 2 3 5 } 3 2 1 ! { 2 3 5 } 3 2 1 + ! { 2 3 5 } 3 3 * ! { 2 3 5 } 9 cycle ! { 2 3 5 2 3 5 2 3 5 } ``` [Answer] # [R](https://www.r-project.org), ~~33~~ 31 bytes ``` \(a,b,`-`=length)rep(a,1+-b/-a) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGSNAUb3aWlJWm6FvtjNBJ1knQSdBNsc1Lz0ksyNItSC4BChtq6Sfq6iZoQVTfj0zSSNQx1jHSMNXWSNYx0TDQ1udCEjDEFDS10jMx0TIx1LMygUiBlpmApHbAOHVMdMx1zTag1CxZAaAA) -2 bytes thanks to pajonk. [Answer] # JavaScript (ES6), 43 bytes Expects `(a)(b)`. This code assumes that both lists are filled with positive integers (as allowed by the OP). ``` a=>g=(b,...c)=>c[b.length]?c:g(b,...c,...a) ``` [Try it online!](https://tio.run/##hctNDsIgEIbhvafoEpKRpoViY0I9CGFBkaINKcY2Xh8DNv4sTGfxbd55Rv3Qs7lfb8t@CmcbBxG16JxAPRBCDBadkT3xdnLLRZ3M0a0hjcbRhGkO3hIfHBqQrKAGqjCSNTCFcfG5sizWuvtv6K96G9iQVQs1B0ah5S@/JVNpssxPDBrgcEg2yVzha1V8Ag "JavaScript (Node.js) – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~11~~ 10 bytes *-1 byte thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string) in chat* ``` lᵐ÷<;?tᵗj₍ ``` Takes input as a single list containing the two input lists in reverse order. [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P@fh1gmHt9tY25c83Do961FT7///0dGGOkY6xjomOqY6ZrE6ChBubOx/HwA "Brachylog – Try It Online") ### Explanation Ports the common strategy of using int-division to calculate the rep-count: ``` lᵐ÷<;?tᵗj₍ lᵐ Length of each list in the input ÷ Int-divide < Next greater integer ;? Pair with input tᵗ Replace the last element with its tail (i.e. the second input list) j₍ Repeat the last element a number of times equal to the first element ``` For example, with input `[[1, 2, 3, 4, 5], [8, 9]]`: ``` lᵐ [5, 2] ÷ 2 < 3 ;? [3, [[1, 2, 3, 4, 5], [8, 9]]] tᵗ [3, [8, 9]] j₍ [8, 9, 8, 9, 8, 9] ``` ### Old solution, 11 bytes Implements the spec pretty directly, using Brachylog's backtracking: ``` hj↙İ.&tl<~l h The first of the inputs j Concatenated to itself ↙İ an unspecified number of times . is the output & And t The second of the inputs l Length of ^ < is less than a number ~l which is the length of the output (implicit) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes ``` Table[##&@@#,Tr[1^#2]/Tr[1^#]+1]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyQxKSc1WllZzcFBWSekKNowTtkoVh/CiNU2jFX7H1CUmVcSraxrlwZUEqtWF5ycmFdXzVVtqGOkY1xbU22kY1Krg8w1RhUwtNAxMtMxMdaxMAMJg@RNQcI6YJU6pjpmOuYQ9YZGYPVAGsQEYZNartr/AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Mathematica/Wolfram Language](https://wolfram.com/language), (44) 41 Bytes `PadLeft[#,Ceiling[Tr[1^#2]+1,Tr[1^#]],#]&` *-3 bytes from alephalpha on something I really should have caught* I feel like this could still be shorter, but it works as-is. Uses Tr[1^x] as a way of getting Length for cheap, and takes advantage of Ceiling having a two-argument mode. Other than that, it would probably take a full rewrite to improve, since I can't use [LeftCeiling] to shave bytes with the two-argument mode. [Try It Online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyAxxSc1rSRaWcc5NTMnMy89OqQo2jBO2ShW21AHwoyN1VGOVfufX1pimxZdbahjpGNcq1MNJHVMamO5Aooy80qigZKx/wE) [Answer] # [Exceptionally](https://github.com/dloscutoff/Esolangs/tree/master/Exceptionally), ~~25~~ 18 bytes ``` GV}lL}nGVL/nIU*lP/ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m702tSI5taAkMz8vMSencsGCpaUlaboWm9zDanN8avPcw3z08zxDtXIC9CESUPkF26MNdQyNjGO5wDSICcImsRBpAA) ### Explanation ``` ' Get an input G ' Eval it V ' Store that in ls } ls ' Get its length L ' Store that in num } num ' Get an input G ' Eval it V ' Get the length L ' Divide by num / num ' Truncate to integer I ' Increment U ' Repeat ls that many times * ls ' Print P ' Attempt to divide the list by itself, ending the program / ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~9~~ 8 bytes ``` W¬›ⅉLηIθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDL79Ew70oNbEktUgjUkNTR8EnNS@9JEMjQxMIFAKKMvNKNJwTi0s0CjU1rf//j4421DE0Mo7VAdMgJgibxMb@1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` W¬›ⅉLη ``` Until the number of output lines exceeds the length of the second input... ``` Iθ ``` ... output each element of the first input on its own line. [Answer] # [Ruby](https://www.ruby-lang.org/), 26 bytes ``` ->x,y{x*(y.size/x.size+1)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVBLToRAEI3bPkVlNg1MgeEzIzHDuHK2useOQQOxExRCwwQETuKGGL2ER_E0Ng2Oo3HR9arqvapKv5e3orprhtckeK_KxPQ_zG2NTVsbWmMJ_hyf1gqWtt5Pgs-TfRmLUkAAm83l1c4SecpLbXHztNCtxyhvu7oLazTqmaBgboHqrJ_IAjlmXSjhwNNpLt5HKdzaPY6JlskJEtrooMsgdNBj4565cUy4vyj8K7B9dNboueiv_5ON-Yp9dz1c4RrPJqGi8Ciqrbajtkoc0_Edzqv6JzIi3SFEmWXF0f0DtCC_Dxwh6whAXkkTtSQ0OIMggAwugF5HQlA4B7qLeEp1WAKVhYSCzPYPw4Rf) [Answer] # TI-Basic, 26 bytes ``` Prompt A,B ʟA While dim(Ans)≤dim(ʟB augment(Ans,ʟA End Ans ``` Output is stored in `Ans` and displayed. [Answer] # [Julia 1.0](http://julialang.org/), 31 bytes ``` ~=length A%B=repeat(A,~B÷~A+1) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/v842JzUvvSSDy1HVybYotSA1sUTDUafO6fD2OkdtQ83/XA7FGfnlCtGGOkY6xrEKqgrRRjomsQq2tjAhbAqMUZTo4FJoaKFjZKZjYqxjYYZbOUjEFKIcLGuiY6pjpmMO0QCW1EEikWwxNILaAmSBOCAMdxaYjyBj/wMA "Julia 1.0 – Try It Online") [Answer] # APL+WIN, 18 bytes Prompts for a nested vector comprising of list b followed by list a ``` ∊(∊1+⌊÷/⍴¨v)⍴1↓v←⎕ ``` [Try it online! Thanks to Dyalog APL Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3t/6OOLg0gNtR@1NN1eLv@o94th1aUaQIpw0dtk8uA6oDqgYrauf6ncWkYKZhoKmgYKhgpGGtygfnGaCKGFgpGZgomxgoWZqjiCmC1CqYKZgrmQBkQzxQqY2gERMYgDDELyNAEAA "APL (Dyalog Classic) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 61 bytes ``` (a,b)=>Array(~~(b.length/a.length)+1).fill``.map(_=>a).flat() ``` [Try it online!](https://tio.run/##hY3NCoJAEIDvPUXHWZo2dv1JiBV6DpEcTc3YdkUl6OKrb2odpQ4DHzMf39zpSX3RNe2wN/Zauko5IMyZis9dRy8YR8i5Lk093A70BbYTjFeN1lnGH9TCRcU0LTQNwNxpU1jTW11ybWuoIBEo0Utxm0j0U8Z@3b0/hohQhuh7GIVr3hwIFg@XFgYY4nG9KOSnOMHM8yy/3Rs "JavaScript (Node.js) – Try It Online") Way longer than the other answers but who cares. Should work in the browser too but TIO only supports `Array.flat()` in Node. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 34 bytes ``` {|@^a xx 1+@^b.elems div@^a.elems} ``` [Try it online!](https://tio.run/##bU7dCoIwFL73Kc5VKJ2CbbqEKHwPmWA0IVCIhFCqZ1/bUWnGLnZ2zvfHd9ePVppuhE0DJ/N6F1UNwwBsW1SXvW5118P19rTodHzMMerrEZo4ZshRJBhzTJMkgIogznLkElOBufRYp84ci@TDDCUeVm7GyW1/t7pH6aYki4LS1lCwO8MMRB4hVhT@C7xKIRl1Uws6d5uERKE3KdV2I7lXdcml@zfVFw "Perl 6 – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), ~~62~~ 61 bytes *-1 thanks to @ceilingcat* ``` f(*a,b,c,d){for(;b=++d%c;);for(;d--;)printf("%d ",a[b++%c]);} ``` [Try it online!](https://tio.run/##dY/LCoMwEEX3/YoiCEm9LvLSQvBLbBeZiKXQ2lK6E7/dRlPdiItZ3BPumYnP/cN1t3Fs2cmB4NHwvn19mKUqy5rUW27n2OS55e/Pvfu2LEmbYwJXU5al/srtMD7dvWO8P4TnoxP1teoFJNRgZ0IzkdAht8wJkICC5PawCC9dElKsy01dxrpaBBI0JbUjUBtBJGfIAlrhXESNAqlJuqPRy1azaPQqhoZBgTKKNEgHVu6ITKwJud6zkglO8/@YAZmg3140jD8 "C (clang) – Try It Online") Inputs are list `a`, list `b`, and their respective lengths in that order (as C doesn't store length information in arrays); outputs are sent to stdout. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 17 bytes ``` ⊑⥊˜≠∘⊑×1+·⌊∘÷˜´≠¨ ``` Anonymous tacit function that takes a single argument, a list containing the two input lists. [Try it at BQN online](https://mlochbaum.github.io/BQN/try.html#code=RyDihpAg4oqR4qWKy5ziiaDiiJjiipHDlzErwrfijIriiJjDt8ucwrTiiaDCqAoKRyDin6gy4oC/MywgMeKAvzLigL8z4oC/NOKAvzXin6kKCg==) ### Explanation ``` ⊑⥊˜≠∘⊑×1+·⌊∘÷˜´≠¨ ≠¨ Length of each list ´ Fold that two-integer list on ˜ Reversed-order ⌊∘÷ Division-and-floor · Then 1+ Add 1 × Multiply by ≠∘⊑ Length of the first list ⥊˜ Reshape to that length ⊑ The first list ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 12 bytes ``` Ty#>b{Yy.a}y ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJUeSM+YntZeS5hfXkiLCIiLCIiLCJcIjFcIlwiMlwiXCIzXCIgXCIxXCJcIjJcIlwiM1wiXCI0XCIiXQ==) How? ``` Ty#>b{Yy.a}y T { } - Till y#>b - Length of y greater than length of b(2nd input) Y - Yank (equivalent to (y:a)) y.a - y concatenated with a y - Return y ``` ]
[Question] [ ## *Back*ground A **[backronym](https://en.wikipedia.org/wiki/Backronym)** is an acronym that was formed from an existing word. For example, *spam* is actually named after the canned meat product as used in the [Monty Python sketch](https://en.wikipedia.org/wiki/Spam_(Monty_Python)), but can be interpreted as "stupid pointless annoying mail". ## Challenge Given a string `a`, and a word `t`, capitalise the correct letters of the words in `a` such that they spell out `t`. You should always move left-to-right through `a`, and capitalise the first occurrence of each letter. For example, if `a` is `all the worlds a stage`, and `t` is `LAG`, then we walk along the letters of `all the worlds a stage`: * we look for the first `l` and capitalise it: `aLl the worlds a stage` * now we look for the next `a`, but it must be after the previously found `l`: `aLl the worlds A stage` * now we look for a `g`: `aLl the worlds A staGe`. You may assume `a` will only contain lowercase ASCII letters and spaces. You may assume `t` will only contain ASCII letters. You should choose whether `t` will be input in uppercase or lowercase. You do not need to handle empty inputs or inputs that have no possible backronymisation. ## Test cases ``` a t output ================================================================ never gonna give you up VIP neVer gonna gIve you uP all the worlds a stage LAG aLl the worlds A staGe why WHY WHY baacbbccba ABC bAacBbCcba x X X xxxx X Xxxx yellow submarine time YEET YEllow submarinE Time ``` ## Rules * You may use [any standard I/O method](https://codegolf.meta.stackexchange.com/q/2447); also, you can use lists of characters or lists of codepoints instead of strings. * [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] # [C (gcc)](https://gcc.gnu.org/), 49 bytes ``` f(char*a,char*t){for(;*a;)*a++^=*a-*t?0:32+!++t;} ``` [Try it online!](https://tio.run/##RU/LboMwEDyHr9giRbIxqJSkl9KoH4KotLg8LFFA2JBQxLfTNSSKLzuznlnNyKCUcl0LJivsPfS3YfhctD2LPYy5h0J8XzwMPPMVfpwi8SKEiZf1F1XD@OxYA3hGJmkSpXCB2ZndJh/zHsq2aRBKNeYwtQMMneuDO6rOXXzSYF2DqXK4tn39owFBGyxzK6mx3CXXarLcjo1niDLLpES7xUzu25tltzumd6fOEjsOtQCmGgOKkoUxjU/Q6i9vC2Ykh9cHofycfoXglP/Q9WQpmHsMoncNx@CsgY5SRZUmYfpAbymPncNWH5NTmBLRppfdxPAptpLiudg93WA0Q0IUcv0H "C (gcc) – Try It Online") Modifies `a` in place. Input `t` lowercase. [Answer] # Python 3.10, ~~76~~ ~~73~~ ~~47~~ ~~57~~ ~~51~~ 49 bytes ``` def f(a,t,i=0): for c in t:a[i:=a.find(c,i)]-=32 ``` [Attempt This Online](https://ato.pxeger.com/run?1=NZA9bsQgEIXr-BQjKojYVbJpIks-yWqLAQ82EgYLY1ucJc02yZ1ylVSBrNPMn94MfO_ja85pDP5-_1yTOb1_v_ZkwHCUSdruRbQNmBBBg_WQWrzatsOzsb7nWlpxO3Vvl2PxJ9GSumvzxBk6B2kk2EN0_QIIS8KBmGQOByZklXjaKMIQvEcY7EaQwwrrXDSbnQ_NPubS1_joMzkXdlhWNWG0niDZqV7NROmQKEStlNYKyxyVZqK5NRVAyfUPofyxIBW6bsKZq5wIY8QseREIeXnmrNCU3RqFaGAuD6XqRqnNkY_ZuScdeuJCPBz4t_AX) Takes in `a` and `t` as byte arrays with UTF-8 encodings with `t` lowercase, modifies `a` in place. --- -3 bytes from @pxeger for replacing the double spaces with single spaces (I blame my IDE for auto-converting my tabs) -26 bytes from @Cong Chen because the rules allow you to take in a list of characters and modify it in place (I should have read the rules more carefully) +10 bytes from @Cong Chen because all of the previous methods just didn't work properly (not sure how to notate this) -6 bytes by using code points instead of characters -2 bytes from @loopy walt by using byte arrays & walrus operator [Answer] # [J](http://jsoftware.com/), 49 bytes ``` toupper@[`(0{"1[:(|.~"#:0,2>:/\{."1)^:_[:I.=/)`]} ``` [Try it online!](https://tio.run/##nVJbb5swFH7PrzgKVWw3xEAenQa5rbqtUrVNU7W1cmhjmEOZyEVA0lYk/PXMJmUbbZ@GBIjzXfA55/u171IUw5gBAhtcYPoeUDj/dvVhXyzXq5XKuJhit@x6guEtrboWc@2hz5xJSbseuWP3gl3SsUOmwW5POp/PKHxIkxXILF7P1aLIaWc2phBXnY6KHpaAnkIZhVGIZkiGEWqK@kIwAxs9NaVrlRcQyVzllNKmGJ7K6Cw8jySCgT5yKLVXGJnPGfzrt1DfVQbxcrGQEF9uFDwv17D@elAt1OYvmDTgqvbYJKvGQ16lUDwoeFxm6c8cTiEv5Ed1sJBpC5MGi1XtkMq4cfjx6fZAf3x4rjHzftVJ@KqV8HUv2EY3iBgONtMh7Snd1IMzBu@M8PYiTZePkK/DucySxQVcJ/OXBp5VC1JQ1NDMIKpAnXqRX3SLGciiUPNVYdZQV3UOsHfCLXpEXPB6ONCpGG5xv6S8pIQEZOzUPE2ZcIExJgmtSI/6Dt9SPqqIYH3HQMcvxCHeUbtyrUq8A7lsihPKhcnXGzhT0TrL9QoZ6JDiTUkFsZvY6vME9k4/jlgldrTy@psxTag@I6f4mAfWIa2tlLtb9ifmQ9@ZuPbblLdUuqNgigUbaVlgV/jS@JeibrdHt1SwE26EFZmKtlLLBtzigT5zLXVL7GutJciLsC377/6GA2cimNXzux427FHlM45r3k7b9XznjklWU3GA7lH3vh54YP7s9VurGzn73w "J – Try It Online") This challenge resisted all my attempts to find a short array paradigm solution. I tried more than 5 approaches, and my best result is still rather long. It's interesting to contrast how simple it is to solve procedurally -- you need only a single loop and a single register. ## my best idea The interesting part of the solution is calculating the indices of the uppercase letters. Consider `'abc' f 'xbacbcb'`. * First we construct an equality table: ``` 0 0 1 0 0 0 0 0 1 0 0 1 0 1 0 0 0 1 0 1 0 ``` * And then convert each row to the indices of its ones, with zero fill: ``` 2 0 0 1 4 6 3 5 0 ``` * Finally, we start rotating any "out of order" rows to the left. A row is out of order if first element is not greater than the first element of the row above. We continue rotating until a fixed point is reached: the entire first column is increasing. ``` Focus on first column | v 2 0 0 1 4 6 <-- 1 less than 2, so rotate 3 5 0 2 0 0 4 6 1 3 5 0 <-- 3 less than 4, so rotate 2 0 0 4 6 1 5 0 3 <-- now 2, 4, 5 increasing, so done ``` * We now have our answer: `2 4 5` are the indices we need to capitalize. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 55 bytes ``` [H|T]+Z+[X|P]:-[H|B]=Z,X is H-32,T+B+P;X=H,(T+Z+P;P=T). ``` [Try it online!](https://tio.run/##VYyxCsMgFAB/RZwUnx3arUFKzJItDg4hIZS0lSJoLGoJhfx76tiOxx33isGFJ0@r3fex3fTEBjb2m5rOvKCcxAA9sgm1/HQEzSRTVS9aILp0qlJC08N@4WjOwV/v4WESwR/jXFhRet/8HO1iULbeYKgp/FcmY5AU6jJtflUHDYU12mzcQrry/wI "Prolog (SWI) – Try It Online") -33 bytes thanks to Jo King Recursive. # [Haskell](https://www.haskell.org/), 44 bytes ``` x#[]=x (h:t)#a@(x:b)|h==x=h-32:t#b|1>0=h:t#a ``` [Try it online!](https://tio.run/##bZDNasMwEITveYpBLkUiCfTnZnAolN7aU49pKCtHtkxsyVhyIkPe3ZUd6MHtgtDufDMgrSZ3UnU9jiHZH7Kw4jr1IqEXHlIprjrLQqa3z0@pT@T1cfeQRZzQWJm29w4Z9pwZdVYdSmsMoazOCoPt0bdsA3auWiY2K/wWZ1TX8FrhYrv66EBwnko1mWsql@aLHiYyXQsiiXIp81zSZCCZLw1h0sMfNda/YIg7sBe4XjbUVUbBV838qkEpz8Rh1VBl4n@PNsYaaj@@wb94sXEC2x3iMj59925whwLrNRju44mNu03RMo88JmMuTIK3b6ZvEJCmeNXUiRieedHZZkaFQLKQnBACt@WPPw "Haskell – Try It Online") I/O as codepoints. -2 bytes thanks to alephalpha [Answer] # [Curry (KiCS2)](https://www-ps.informatik.uni-kiel.de/kics2/index.html) + `:set +first`, 61 bytes ``` import Data.Char (f s)#(g s)=s f=map toLower g=filter isUpper ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m706ubSoqDI-OzO52GjBgqWlJWm6FjdtM3ML8otKFFwSSxL1nDMSi7g00hSKNZU10oGkbTFXmm1uYoFCSb5PfnlqEVe6bVpmTklqkUJmcWhBQWoRxJDduYmZeQq2CkpJiYnJSUnJyUmJSgrKCkqOTs5KEBWbopWsilNLlHQUlLTTMouKS5RioQ4AAA) `a # t` finds a string `s` such that converting `s` to lowercase gives `a`, and picking out the uppercase characters in `s` gives `t`. Curry is a functional logic programming language. It searches for solutions using backtracking. Without `:set +first` it would return all possible solutions. With `:set +first` it only gives the first one. This works on KICS2 3.0.0. It seems that it does not work on PAKCS or older versions of KICS2. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes ``` v=vTΠ~Þ⇧h⁽⇧V ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ2PXZUzqB+w57ih6do4oG94oenViIsIuKIkSIsIltcIm5cIiwgXCJlXCIsIFwidlwiLCBcImVcIiwgXCJyXCIsIFwiIFwiLCBcImdcIiwgXCJvXCIsIFwiblwiLCBcIm5cIiwgXCJhXCIsIFwiIFwiLCBcImdcIiwgXCJpXCIsIFwidlwiLCBcImVcIiwgXCIgXCIsIFwieVwiLCBcIm9cIiwgXCJ1XCIsIFwiIFwiLCBcInVcIiwgXCJwXCJdXG5bXCJ2XCIsXCJpXCIsXCJwXCJdIl0=) I/O as char lists. I feel like there's gotta be a smarter/faster way to do `Π~Þ⇧h`. ``` v= # Create an equality table vT # Get all indices of each letter in the string Π # Take the cartesian product, getting all combinations ~Þ⇧ # Filter by those which are strictly ascending h # Get the first, which will be the first occurences V # To those indices in the original string... ⁽⇧ # Uppercase them ``` [Answer] # x86-64 machine code, 11 bytes ``` AC AE 75 FD 80 67 FF DF 75 F6 C3 ``` [Try it online!](https://tio.run/##dVLfa9swEH6W/oqrR0Buk9JmZYxk3sN@vQ1G6UNL0sH5LNsasmQsOYk3@q/PO2fdoGUTSHfc3Xffd4doURGNI4YGFFwnSp5X1udooZTlSlhfhFx2tBKBkD3xzWnoSAp0Bby7u/kIX26uYdMVZnF5P4eLw4dPU813RotOR5kmkK4l1dhBqY7mFOfw24mckS@MI9sXGt6EWBh/Xr99EuqMq6aYcREaNE6l8ocUR3zcXC5fMyce7VqKfW2sBsVCXamSWYDZ5uvW3UMyh8hlKWQZLFMpuIEoFcuYBAjR9jEonNwHKVomjIzeus9IteFhyRd6lUxp8i5E6F0wldPF4xAtZKD@mUnL9bMQcZPCwx8OmF0sb1kcZaft2Vm6hscBCE4y3uT7lxPp32I1M5APUYd06xjULv7HyqiHcdyZVji90x1U3jmEyuw0DL6HvpUWK4HWQqw17H1niwAIIWKl5b4eeI@DxJxEjkh5TpSjPIjDdPnIQesoBm2t30Po8wa7aUvRNPonldw5jIvm1RU//KMy1q7tLw "C (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the addresses of `a` and `t`, as null-terminated byte strings, in RDI and RSI, respectively, with `t` lowercase, and modifies `a` in place. In assembly: ``` f: lodsb # Load a character from t into AL, advancing the pointer. rc: scasb # Compare AL with a character from a, advancing the pointer. jne rc # Jump back to repeat if they are not equal. and BYTE PTR [rdi-1], 0xDF # Set bit 5 of the matching character to 0, capitalizing it. jnz f # Jump to the start if the result is not 0. ret # Return (once the null terminator is reached). ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 27 bytes ``` i+`(.)(.+)/(\1) $3¶$2/ ¶|/ ``` Takes input separated by `/`. [Try it online!](https://tio.run/##K0otycxLNPz/P1M7QUNPU0NPW1NfI8ZQk0vF@NA2FSN9rkPbavS5/v@vTM3JyS9XKC5Nyk0sysxLVSjJzE3Vj3R1DQEA "Retina – Try It Online") [Answer] # [R](https://www.r-project.org), ~~55~~ 54 bytes ``` \(s,t)sapply(s,\(c){if(F<-t[1]%in%c)t<<-t[-1];c-32*F}) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3zWI0inVKNIsTCwpyKoHMGI1kzerMNA03G92SaMNY1cw81WTNEhsQT9cw1jpZ19hIy61WE6rbq9gWyLAIyffMK9FQSszJUSjJSFUozy_KSSlWSFQoLklMT1XS5CpBVpWTmA4UyswrCckPBYpqpIEdADVxwQIIDQA) Input is vector of codepoints. --- # [R](https://www.r-project.org), 61 bytes ``` \(s,t)for(c in s){if(t[1]%in%c){c=toupper(c);t=t[-1]};cat(c)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY5BCoMwFET3PUUICPlQF-4EyS3alXUR0sQGPonkf-lCPEk3ttBD9TaV6qarYXjDzDyeeXl5_R7Zl_VHXxQdGXzKyooQBcEUvOK26ooQCwuT1ZzGYXArh4Y1t2XVzY01vPp5L2lJO1TEmQYMrKRBFHxz4p4yXkkYQWx6J49SAhz4P4um30EcEXWIfEpn9rXyv2OwTSzLpl8) Function with null return value that prints output to console. Input is vector of characters. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` £ƛ¥h=[&Ḣ⇧ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiwqPGm8KlaD1bJuG4ouKHpyIsIiIsInllZXRcbnllbGxvdyBzdWJtYXJpbmUgdGltZSJd) Literally is different by one character from [this](https://codegolf.stackexchange.com/a/249833/92689), and also very similar to [this](https://codegolf.stackexchange.com/a/249605/92689). Input as strings, output as char list. (`s` flag in link smashes) ``` £ƛ¥h=[&Ḣ⇧ £ # Put the first input in the register ƛ # Map over the second input: ¥h=[ # Is the current character equal to the first character of the register? &Ḣ⇧ # If so, remove the first character of the register and uppercase the current character # (implicit) else, return the current character unchanged ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 40 bytes ``` a->t->a.map(c->t.peek()!=c?c:t.pop()^32) ``` [Try it online!](https://tio.run/##bVJRi9swDH7vr9AKBWck5ra9NdeMMRgMbk/d23EDxVVSt44dbCVtGPfbMyfXretuBluWvg/pk@wD9pgddsdRN63zDIfoy461kW/zxatY1VnF2tn/goE9YTNBymAI8A21hZ8LgLYrjVYQGDma3ukdNBETW/ba1o9PgL4OyUwF@HIpcb@d091/tUw1@SL9Azxoe6Tdgw58Bf8hFwVUsBkxKzgrUDbYChXvsiU6iuTNRn1U6@i5ViQ/PrxPxnwuXTkPokc/6YH1jSqAKR5gM0VlaI1mscyXSf4XihENj3dPUu3RB5HI0p1pJ244PHPeveJI5YwhxeLzi3U@SHYXJzYtrk2v15ZOyU1Wv6kktq0ZBCaXCydT199dnIjQWaGTmO6T9zhc9VzMdghMjXRdHEh8D67EchVSWAXIiniu7DKd20pn4SnE6vDycsKnd6mXhmzN@9@KnhfTfh5HSz15qJ21CLXuCQbXQdfmvW5HNAZ4T3By3uxCnFz8GzXlBuvxtB/yuMcSUZWlUiXmWKrxnJ/Hc1zRDGSMO0HoygajDALWDeUDEf8C "Java (JDK) – Try It Online") With `a` is an `Stream<Integer>` (stream of codepoints) and `t` is a `Deque<Integer>`. Both inputs are lowercase. There's a lot going on with automatic null tests, autoboxing and friends, so this answer might seem trivial, but it's actually not at all. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 24 bytes -1 byte from @ngn's improvement ``` {`c$x-32*y{y_x,y~:*x}/x} ``` [Try it online!](https://ngn.codeberg.page/k/#eJxVjs9rwjAYhu/9Kz6CByu6wXZrTk5kG+ywQ9kUKeuXLK1hsZH0V0LRv32JqwxzeCHv87zwFcmQ84ldPD7M3OC+7Nydk5k93dtTFEVpMkx27mySAu7A0lz/0GleoFTUUkdNnHkp3U1JJTphoNRVhVDKToDTLbRHQkknjySmXvj4F16vwjvJLnNUCpq9gF4b9V0DQt1gKfxaYRnW+HbDl4E/i3Hc7503Q3rz82U71gyRM8Y5Q0+R8UDZEvkTW4XuIs2JJTRE7HMzDq1/15Zswuevd0Ip3UPdsgMaWQlo5CHc6IRogrpd3/A1pIFnv8PQblo=) Adapted from my answer on the [Speed of Lobsters](https://codegolf.stackexchange.com/questions/217690/speed-of-lobsters/218688#218688) code golf. * `y{...}/x` set up a reduction seeded with y (the characters to search for), run over the characters in x (the full string). confusingly, within the function itself, x and y are flipped. this ends up returning a boolean array with 1s in the positions containing the desired matches and 0s everywhere else + `y~:*x` compare the first character to search for (`*x`) to the current character being iterated over (`y`), updating y with the result of 0 or 1. note that as soon as we have matched all the search characters, no more matches will be identified (since a character will never ~ (match) a 0 or 1) + `x,` append this result to the list of characters to search for (essentially overloading the reduction to end up returning the desired output) + `y_` if there was a match, drop the first character (if there wasn't a match, this is a no-op). this allows us to search for the next search character in the next iteration of the reduction * ``c$x-32*` multiply this bitmask by 32, representing the offset necessary to capitalize characters at truthy indices, subtract it from the original text, and convert that result "back" to a string/text [Answer] # [JavaScript (Node.js)](https://nodejs.org), 62 bytes ``` f=(a,[h,...l])=>a.replace(eval(`/${h}(.*)/i`),(s,t)=>h+f(t,l)) ``` [Try it online!](https://tio.run/##jZJfS8MwFMXf8ynug7BEYwa@SoUpRQUfBMU/TGG32e1aSZPSZl3H2Gefqd0miorn6XDP7xAuuW/YYK2rvPTH1k1ps0kjjnKcSaWUeRXRGaqKSoOaODVo@GR4sMrWXB2KYT4RktfSByg7SrmXRoiNp9pDBBNmqaEKZs5ahFneECzdHOYlfOjh@rY3lh4@qesddcvQGPAZwcJVZloDQu1xRn0HbkaXvcGbL9Sooy6JLbIl/KrHq@e9YQmiThKt8SdydH7Rm2SE@jy50Mha@ENPe8PaoH9wgWJLMsYtoJ4nBVa5JfB5sVsUnuP4fmu@UDHcB4rVLqBzO6U0FKeQUUWfz9zFO@OK@BvFJspXecGFqkuTez54sQOhCix5C9EZtNvxEFYncj3sk6ZLmm1PiFPWfbVKXRWjzjgftxKWEuhVdNyKAWhnwy24cA0p78JQ6YfOkDJuxkMURUASXIjW4nTzDg "JavaScript (Node.js) – Try It Online") Input uppercase `t`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` v¬yQićuëy}? ``` Based on [my 05AB1E answer of the related challenge](https://codegolf.stackexchange.com/a/217695/52210). Inputs as lowercase strings in the order \$a,t\$. [Try it online](https://tio.run/##yy9OTMpM/f@/7NCaysDMI@2lh1dX1tr//1@ZmpOTX65QXJqUm1iUmZeqUJKZm8pVmZpaAgA) or [verify all test cases](https://tio.run/##PYy9DcIwFIRXeXLNDp6BOorEs3lyLDl2FP8kLtJCzxpQM0BgEhYxTpC44nTf6XTOo9BUUuYMPpcbMJ5PvqT1kY/6fY2ve154WdYnL03DLCUaQTlrEZROBNlFiAM7sKQH1h4ahsZA6AgmN5qzBwQfUFEdGFT7YOpypc03EohSCCkF1hKF3Mu55vmXqv6QyRg3gY@ix1FbgqD77TkTBda2Xw). **Explanation:** ``` v # Loop over the characters `y` of the first (implicit) input-string `a` ¬ # Push the first character of string `t` # (which will be the implicit second input-string `t` in the first iteration) yQi # If it's equal to character `y`: ć # Extract the first character from string `t` u # And uppercase it ë # Else: y # Push character `y` as is } # After the if-else statement: ? # Pop this character, and print it ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (v2), 10 bytes ``` ↔{|ụ}ᵐ↔w₆⊇ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HblOqah7uX1j7cOgHILn/U1Paoq/3/f6WkxMTkpKTk5KREpf9Kjk7OSgA "Brachylog – Try It Online") Function submission, using both its arguments (input string on the left, uppercase acronym on the right) and outputting to standard output. Very inefficient (O(2*n*) performance). ## Explanation ``` ↔{|ụ}ᵐ↔w₆⊇ ᵐ Iterate over {the left argument} ↔ ↔ in reverse order {| either doing nothing (try this option first) |ụ} or uppercasing {the character being iterated over} ⊇ such that {the right argument} is a subsequence of {the result} w₆ and when we find it, output {the result of the iteration} ``` Uppercase some of the characters so that we can find the acronym in the uppercased string. The inefficiency comes from the fact that the iteration order will try uppercasing the first character, then the second, then the first two, then the third, then the first and third, then the second and third, then the first three, then the fourth, etc. – the interpreter doesn't realise that the first solution it finds will uppercase a number of characters exactly equal to the length of the right-hand argument (because any solution which uppercases too many characters will be found later, and any solution that doesn't uppercase enough won't match), so it just tries all possibilities within a given prefix before going onto the next character. Iterating in reverse is required for the uppercasing of prefixes to be the first thing the interpreter requires (with the normal iteration method, it would try uppercasing the last character first, etc.). `w₆` (which outputs the current value, without discarding it, and where the output is used only if all the constraints in the rest of the program end up matching) is by far the most useful of Brachylog's nine write instructions, so could probably do with a 1-byte representation (I would likely make this the default behaviour for a write if I were designing a Brachylog-alike from scratch). [Answer] # [Perl 5](https://www.perl.org/) `-plF` , ~~36~~ 35 bytes *saved a byte by taking the first input in upper case* ``` $_=<>;s/./uc$&eq$F[0]?shift@F:$&/ge ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tbGzrpYX0@/NFlFLbVQxS3aINa@OCMzrcTBzUpFTT899f9/H0d3rsScHIWSjFSF8vyinJRihUSF4pLE9NR/@QUlmfl5xf91fU31DAwN/usW5LgBAA "Perl 5 – Try It Online") Takes `t` on the first input line in upper case, then `a` on the second line. [Answer] # [Rust](https://www.rust-lang.org), ~~149~~ 148 bytes ``` |m:&str,v:&str|{m.chars().fold(v.chars().peekable(),|mut a,c|{print!("{}",if a.peek()==Some(&((c as u8+32)as char)){a.next().unwrap()}else{c});a});} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZFNTsMwEIXFtqeYZlHZInQBm6pVF2mFSqUuKiEVELAYu5M2InGixElbJbkFOzZdwAE4DpyGOOmPGMl-nqdvLOv54zNOE73_dhUE6CnGc580uDD8SrV71ft5L4J-J9GxndVS5EFXrjFOGO-6ob9k2amNiN5Q-MS4XQSpBrRlkUexp3SbWXlp2Z4LWFOMD4f3YUCsw5gETCDtXd5c8-pg7uI8x66ira7uTNUmxojxkvyEclnyAVarbN72ezGFqgZuGANDG4QNtI1Ialpy8BRkJNvPzFKUUQyrUCmElZcR7MIU0siywVpM50YULc7E9EjMLW4Ds9D3Qa8JNmHsLxNASDSuyIzNnIkRnP0DHANMqBnerHcGebh7OkptC0QphJRoXGc0NiIclCMxlgIbZmvMx2ZrjKrOnmn4K-QtOJRbRSD44NTXyfuqyv5Fw-0hlz6YjzjH1OBl65Doft_oHw) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 15 bytes ``` ?Lqrd4h+Q0.(Q0E ``` [Try it online!](https://tio.run/##K6gsyfj/396nsCjFJEM70EBPI9DA9f//aKUwJR0lTyAOUIrlilbPU9dRUE8FEWVwVhGIUAAR6SAiH0TkwYlEVNlMVL1giUq4tlK4GJhVoB4LAA "Pyth – Try It Online") -- [Try with formatted I/O](https://tio.run/##K6gsyfj/3zYwNyXQ1j03xbXY3qewKMUkQzvQQE8j0MD9/3@lMM8AJS6lvNSy1CKF9Py8vESF9MyyVIXK/FKF0gIlAA "Pyth – Try It Online") -- [Try all test cases](https://tio.run/##NYnNCsIwEAbvPsUSL4IgPXgtUiVUoQcD4s8xaUJTSNKapK15@rgeXNgZPmZMUedcMivZuqytpOHQvL3c6y0rdhtW1PBrNGdyv1zJijg1Kw/d4ByHrp8VpGGCacTSVDWSGwNRK1gGb2QADiHyTmF4nF/IRSdkdTwhBeetEG0rOI4n/udvPNSL0hsqKWOGBcIkLPe9UxB7q8gX "Pyth – Try It Online") Accepts `t` then `a` on separate lines as lists of characters and returns a list of characters. [Answer] # [Factor](https://factorcode.org/), 55 bytes ``` [ [ over index cut capitalize swap write ] each print ] ``` [Try it online!](https://tio.run/##jZFPSwMxEMXv@ymeufsF9FQ91IKIIP6j9DCZjttgSNYku9ta@tnX3bVxEYr4DsOQeb83kHkjTj50jw@Lu/kF3iU4sYjyUYtjiaDIxvQ1eo4wHpdFsS/Qaw/lpJGA0jtHKE0j2PkadaUwSjWmbw9jfwYnT5N3kb33OYqsRdoIWh/sut@KmKiUYxKUpXKKottf3tngnUtOaje7jJ3Q9zgnPd@8ZkwTsdbMdBJWpHnC9Iz4Sl@zpkxv/1iJ4zjTLz9QL/VfqPcWh6JbYgk//Lpxa9mC6wSmyiSy5lMQW6rQBpMEKwjxBlUwLmHVjQc8H566Lw "Factor – Try It Online") Takes the string and the lowercase word in that order. Assuming the input is `"all the worlds a stage" "lag"` * `[ ... ] each` For each letter in the word... ``` <<iteration 1 of each>> ! "all the worlds a stage" 108 over ! "all the worlds a stage" 108 "all the worlds a stage" index ! "all the worlds a stage" 1 cut ! "a" "ll the worlds a stage" capitalize ! "a" "Ll the worlds a stage" swap ! "Ll the worlds a stage" "a" write ! "Ll the worlds a stage" (write to stdout without newline) <<iteration 2 of each>> ! "Ll the worlds a stage" 97 over ! "Ll the worlds a stage" 97 "Ll the worlds a stage" index ! "Ll the worlds a stage" 14 cut ! "Ll the worlds " "a stage" capitalize ! "Ll the worlds " "A stage" swap ! "A stage" "Ll the worlds " write ! "A stage" (write to stdout without a newline) <<and so forth..>> ! "Ge" print ! (write to stdout with a newline) ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 36 bytes Takes the string as first argument, then the acronym in lowercase. ``` {@[x;(#x)-1+#'x{y/1_y\x}\y;`c$-;32]} ``` [Try it online!](https://ngn.codeberg.page/k#eJxNjcsKwjAURPf9iksqqGiR6s5s/I+26E28rYE0KX0mlP67ad04i4EzHJjyPj8yxw+xOybpKd672V/Sp8/dknv+kruE367FEkVlxgyN1EJljUGo1Ejg7QBDwzgbVcOKVUGtof8QTLbV7w4Quh4rCobG6mdMHx9w7Q0FohRCSoFhRSG39cwc42ttigv5Q09a2wm6QdTYKkPQq3p98EQ9K76bIEHe) [Answer] # [Go](https://golang.org/), 70 bytes ``` func s(a,b[]byte){i:=0;for _,c:=range b{for a[i]-32!=c{i++};a[i]-=32}} ``` [Try it online!](https://tio.run/##PY5BCoMwEEXXeoppVhFtKbpTcoDuXHUjUkaJIbQmEqMgIWe3sUJ38x8z74/Q@4T9GwWHEaWK5ThpY8kwWrIPi@phpph1TdttlidOluxeDdrAK@tLZlCFs84dABvZXov8wnon09RXv8yK3PtTc8hpAi6OEEoGp5ASxVduQGilEIRcOWx6gWUiSRwdxf@956MmSYDhr1ttpLIfRWcbBkExcL9/AQ "Go – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` ẹⱮŒpI>0PƊƇḢ Œuç¦ ``` [Try it online!](https://tio.run/##y0rNyan8///hrp2PNq47OqnA084g4FjXsfaHOxZxHZ1Uenj5oWX///@vBKrKL1coLk3KTSzKzEtVKMnMTQWKppYAAA "Jelly – Try It Online") ``` ẹⱮŒpI>0PƊƇḢ - Helper link g(s, w) - takes string on the left and word on the right. ẹⱮ - For each character in w, get all indices of it in s. Œp - Take the cartesian product over this list. Ƈ - Filter keep for: Ɗ - Last three links as a monad: I - Increments (deltas / consecutive differences) >0 - Are they greater than zero? (positive) P - Take the product of is to check that all are truthy Ḣ - Get the first item (that satisfies that condition) Œuç¦ - Main link f(s, w) - takes string on the left and word on the right. ç - Run the helper link (as a dyad, given s and w) ¦ - At those indices in w... Œu - Uppercase them ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` Fη«≔⌕θ↧ιζ…θζι≔Φθ›λζθ»θ ``` [Try it online!](https://tio.run/##RcyxCsIwEMbxuXmKGxOIT@AkBUVw6OQe4pkEQq69tpFWfPbYKOj2h/t9Z71hSyaWcicG6RU8RXMYx@CSPIZ0k4OGCz2QrRlRBqU0rGovmo5DmmS72Iitp76yVf0PoebvTZyQqzgxmprxgzUMm3qJ72LrUhJmZHCUkgEXMsJCM8y9uJ67ssvxDQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Fη« ``` Loop over the uppercase letters. ``` ≔⌕θ↧ιζ ``` Find the index of the next matching lowercase letter. ``` …θζ ``` Output its prefix. ``` ι ``` Output the uppercase letter. ``` ≔Φθ›λζθ ``` Remove the prefix and the lowercase letter from the string. ``` »θ ``` Output any remaining lowercase letters. [Answer] # Regex (GNU ERE or better), 30 bytes ``` s/(.)(.*( ))(\1)| /$4$3$3$2/ig ``` [Try it online!](https://tio.run/##bZLfbtMwFMbv8xRn0TTba@uu226gpKigaQzxTwwxprZoTuKmHo5jbKddt5VLHoBH5EXKSacOLoil6Pic4y8/fyfXYi585pQNHVPlcn2bHPRdch6cMgV3YnG19l3KGeX7NGKMjnvsPuruHu8e4TrsqmJ9xb1WmaS9dqfH@qCmQN3oYLKTEE8YhJmrFkDeKu9REGIfkyiHBNyoN3lozgfkB4H7e8h5KUI2o93RQefJsDOeiM5ql7L9Fn82eP510mWPamdmLrTKIZdalSpIRyLXaHJvtQo032JwLU0RZrCTwPHj4QtXIYipy1Q6qKZ/RTzpg9@gHSJaI/hRFic3ljasbUwfTVjk5PdaOUmJkyLXykjCeIZxkGcGNaYCnbhTxtbhqXVVJr3nPuTKrBivDCWbE22dDO5uYW8P/mmp6sAXDjkoGRuCN7hNehGARYzX5@/fcSucx9qItHSLTPCr15Uy295p5Wi/z@5K7LbcSasbDtcGv7GClkliWYqY3/pgk3K1sUfjlJKExDil/3JoaEEMv3/@wnfrAcJvfgs1XVLL2IqtYyPn6GJRGSOgUHMJy6qG2sZtiD@ffYijWGiNxktYVE7nHgT4IArZ1N8MT7G@mC2bzcWrS9ykQmRpmmWpaHLDFy8xd9OEX5oAn228lFrjLH2dlgKJJARVbkQvT04@xX8A "JavaScript (Node.js) – Try It Online") - ECMAScript [Try it online!](https://tio.run/##TU7LTsMwELznK1aWpcQopA2PS02BQhEPIUACAVUbRU7qpkFuUvJoqEqufACfyI@ENaUC78GzM7uzM5eZ2m/KXMLV/e0NB436ohCdTr@czWXGjUmaWTTutvnBIcffZSuIJ8iw1TyLkwLIKCG8BqqgC3kZ5AWO@/a2a7tMvmoRjv7xbVQYdID63AA0AmujKdT0iklMtqIC3cYyTMfSf8nTBMyh6VDlmJ7JYX0XF0z4@vgEZKiP48e4VQ/bnqOPOuvO9Ti4UE1jJZu8ZTnMcrYsgzFr5LJ3o0X36C7WTiuOmo3vbx6Z/B0fUt@zwbUBs/O6bkgiFzKDKE0SAVG8kLBMSyjnxAbyeHlHDCKUgmIqoUozNc5BQF6ISGr9uneOejVd6ubpYoBNIEQYBGEYCM31Tk6Re9PwWQN8G7yUSqWVTjgTmFVCEc9@TAdnZw/kGw "Perl 5 – Try It Online") - Perl This is a single regex substitution to be repeatedly applied until it has nothing to match (or until there is no change, in engines whose API doesn't supply the information as to whether anything was matched – i.e. ECMAScript, Boost, and Python). Input is taken as string `a` and word `t` concatenated with a newline delimiter between them. This is similar to [Leaky Nun's **27 byte** Retina solution](https://codegolf.stackexchange.com/a/249808/17216), but that one does two regex substitutions (looping the first until there is no change, then applying the second one once, then done) and uses two different types of delimiters at once (newline and slash), while this solution does just one looping regex substitution, and only uses newlines as a delimiter. The intermediate states as this one progresses are different than those in the 27 byte Retina solution. In it, as the first stage progresses, it inserts a newline after each capitalized letter in string `a` and deletes the corresponding letter from the beginning of word `t`. It's only in its second stage that the newlines in string `a` are deleted. As this 30 byte regex substitution progresses, it inserts two newlines after each capitalized letter in string `a` and deletes the corresponding letter from the beginning of word `t` – but as it progresses, the previous double newline gets deleted; at any given step (other than before it starts), only the letter last changed to uppercase has two newlines after it. Then when no letters are left to capitalize, it deletes all the newlines. ``` s/ # Match the following: (.) # \1 = $1 = one character from string A (which is in lowercase) ( # $2 = concatenation of the following: .* # Match as many non-newline characters as possible, minimum zero (¶) # $3 = one newline ) (\1) # $4 = the first character in word T (which is in uppercase) | # or ¶ # One newline / # Replace with the following: $4 # The uppercase letter from word T, replacing $1 $3$3 # Two newlines inserted $2 # $2, preserved unchanged from string A # No $4 – it is deleted from the beginning of word T # Note that all of the above will be empty if the second # alternative, one newline, was what matched, thus deleting # the newline. / # Flags: i # Case Insensitive g # Global - replace all matches instead of only the first. After # the first match is made, each additional match attempt begins # after the end of the last full match (i.e. they don't overlap). # The replacement pass is only done after all matches are found. ``` ## \$\large\textit{Anonymous functions}\$ # [Ruby](https://www.ruby-lang.org/), 52 bytes ``` ->s{0while s.gsub! /(.)(.*( ))(\1)| /i,'\4\3\3\2';s} ``` [Try it online!](https://tio.run/##NVDLTsMwELznK7a@OKFp@oCbFaSCKh5CgAQCqiQHp92mrlwn2ElDC1z5AD6RHwlOELZkzczOrFerq3TfaHythEagG5MrymAVNoNT8z6q10IimCAzVdqDoRt4bnDkOp7nxmPvwxkKn8Yn8bG9E8rMZ3MIRwz@QjLMsDQOgFjBoWf1oioNQ7Vkh3DMWlVGg3EShiRWhFm7jEZBMJgkDKzpL2cla6CEWgpgIITrh7vboODaoEsj2pd9mlAv2ORCuW0frzMWWqgSpE/g5@sbiN@FMlSoeYnuKjKJ133SPQ1RuEMNWa4Uh0zsEPZ5BVVBfCBPV/fEIVxKKNcIda7l0gAHU/IM2/rN9MLW6/W@Jc@Xc0tSzhdpulikvNWmZ@dWe2vhSwvs@cd7lDKvwW52y@3ACKXYdk3ns9kj@QU "Ruby – Try It Online") ## \$\large\textit{Full programs}\$ # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 28 bytes ``` i+`(.)(.*(¶))(\1)|¶ $4$3$3$2 ``` [Try it online!](https://tio.run/##K0otycxLNPz/P1M7QUNPU0NPS@PQNk1NjRhDzZpD27hUTFSMgdDo///K1Jyc/HKF4tKk3MSizLxUhZLM3FSuSFfXEAA "Retina – Try It Online") # Perl `-p0`, 37 bytes ``` 1while s/(.)(.*( ))(\1)| /$4$3$3$2/ig ``` [Try it online!](https://tio.run/##K0gtyjH9/9@wPCMzJ1WhWF9DT1NDT0uDS1NTI8ZQs4ZLX8VExRgIjfQz0///r0zNyckvVyguTcpNLMrMS1UoycxN5Yp0dQ35l19QkpmfV/xf19dUz8DQ4L9ugQEA "Perl 5 – Try It Online") # [GNU sed](https://www.gnu.org/software/sed/) `-z`, 39 bytes ``` :a s/(.)(.*(\n))(\1)|\n/\4\3\3\2/Mig ta ``` [Try it online!](https://tio.run/##bU7NTsJAED7bp5isJNttoA3qiUIIGlQSTUw0KmHBbNtN22TZkt1CLdmzD@Aj@iJ1i3Bz5vL9zHwzEdNZozhLoKcSwBjUcIg/joWbAXN04PrE9T2XSkJc2ieGyoBe0UvbF8Fjnjola04bTpXlgsPs9nkEx1QQxiygJwF1BIJlmBTOmeV76GhYGsPjrAj1qB@24DBjNlwJ6G04YB2skOuOB5T6ZrFCS@IRBF4XvH9UK5z7HhkHtE@l/Qwb9xD5dxl@vr4BYYRD0Ny@Nd1zKysUwmnIesRJCskbJPmOK0gLKRmk@Y5DXWxhu0FdQK@zJ@QgJgSUGYeqUCLRwECXLOWt/zC5s36V1S15u59bEjEWR1EcR6zVJtc3Vvts4XsLbJ1wzYUoKtDbaM1ULjmU@foQOp9OX9Av "Bash – Try It Online") The `M` flag tells `.` to match everything except newline, whereas normally in sed, `.` matches any character including newline. [Answer] # Regex (.NET), 69 bytes ``` s/.(?=(.*$)(?<=(?=(?>.*?(.)(?=.* ((?>\3?)(\2))))+\1$)^.*))| .*/$4/img ``` [Try it online!](https://tio.run/##lVTdbtMwFL7vUxwZS4lLk63ADSuhjGqDISZNMDFQF8BNncTIsYPtrC1duOQBeEReZJysUKjEDeciOj@fP33n@MS1WQjrSqHUDbXJk@DG7cXhOAnjPmXh@FHS@ePHcX8cxhgncb8XYnx5f8zCy3sM7e7lkLL3cZ@x617c36MP9mRV3ARPRjIPqZ3up5EWxBG29qU1CwhOpXNSF4C5oKXzBDHD9BY8jwpPvpLI2HBqRSGWaTDdjx4eRpcpj1oasv7d@NHj8fs0YPEp91kpHB5iW@YTfcWVnMNcKFlJLyzyW@SPX9dK@g660RQroQtfoi54sD18YQ2K0k01ExZM/ofEBW2Puk7mvXQEtEiG@M0TMjFVLZWYkxFMs5LbaZoi5n56fWzsEc/KtVtI1BjSD2zdA7SgCGBNC0ggGrabjOwyOWYIXeft4KTQxooJd4L8AlS7gNNGeamk3tbdbv01DlaJvwF6F3C0xFFk0k947Ru7RS3/peOMe2xfX5Q4BVfzbIu2u@hXsij9uXkpck9auLU7kDXOmwoi0MaDa@raWC/mMFtBOM4VLxi4lfZ8uWHMdhkn2Caq6@7TSq472v9gbPG@bPJrgw4OtFiEtzs2oDnr0S/J/ijH7nh3NQqkBip13Xi27nZDdfsqPgck2MRf2Hphsf@oNM63eHg4@hNDpA2yd@NG4Qp@fPsONJwYfSUsDiR64Qyy29iKWuH4wt@lY2uqTZFMqUoJiz4Z1EE@6o9kQN2AFoyRtr0hWiAcCqM1h0JeCViZBpqaDIC8OTkjPcKVAl8KWBir5g44OM8L0dVfHj7D@qJcdcHF83cYzDjPZrMsm/Eud/h0grll577tHLTf/gofA/wlXDOrcP7YnJfVLem7o6Nz8hM "PowerShell – Try It Online") - all test cases [Try it on regex101!](https://regex101.com/r/H2drs5/10) - try it on your own This is a single regex substitution, to be applied once. This is the only kind of substitution that can be efficiently used on regex101. Input is taken in the form of the two strings delimited by a newline. The primary challenge here is that each match+substitution must be done as a separate event, with no communication between them (other than that each subsequent match is done following the end of the previous one). No captures can survive from one match to the next, so each one must reconstruct its state from scratch, relying only on the position of the match to let it do that. Also note that the actual replacement is only done after all matches are found, so that can't be used to communicate state. In this explanation, a raw newline is shown as `¶`: ``` s/ # Match the following: . # Match a character in string A (?= # Lookahead (keep this out of what will # be replaced) (.*$) # \1 = capture the rest of string A, to # our position (?<= # Lookbehind - evaluated from right to # left, so read from the bottom up (?= # Lookahead - go back to evaluating from # left to right. (?> # Atomic group - after each iteration, # lock in its match and prevent # backtracking. .*? # Skip as few characters as possible, # minimum zero, to match the following: (.) # \2 = a character in string A (?= # Lookahead .*¶ # Skip to the beginning of string T ( # \3 = concatenation of the following: (?>\3?) # Previous value of \3, if set (\2) # $4 = the next character in string T # (which is capitalized) ) ) )+ # Loop the above as many times as # possible, minimum one, to make the # following match: \1$ # Stop at the point we snapshotted, # making sure that the string ends after # it, to prevent matching an earlier # duplicate. ) ^.* # First step in the lookbehind - skip # back to the beginning of the string. ) ) | # or... ¶.* # Match the newline and string T, in # order to erase it. / # Substitution - replace with this: $4 # The capital letter we captured in $4, # which will be empty if it was the # second alternative that matched. / # Flags: i # Case Insensitive (so that letters in # string T will match those captured in # string A) m # Multiline - "$" matches the end of any # line instead of just the end of string. g # Global - replace all matches instead of # only the first. ``` # Regex (Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) / .NET), 74 bytes ``` s/.(?=(.*$)(?<=(?=(?>.*?(.)(?=.* (?=(\4?))(\3+(\2))))+\1$)^.*))| .*/\5/img ``` **[Attempt This Online!](https://ato.pxeger.com/run?1=bVPNTttAEJZ69FMMFpJ3E2MSIC0kmCjQiKYKUAGFIidITrw2i9braNeGhJ9rH6CHXnrh0t76CH0QeuyTdGwToar4NPPt7LffzDf-9mMySy8S-fCLx5NEpaBn2lYsYlP7UieyBcpVpml-z9Jwaf3xvV52SNslTmWRkvamm8ftLafSJg7mrlMxcmSw1qaUDFarZLBC8asO6ov03KlQemc4leVBY5nHUcn4-9VPZPfqzaX60OAhKK82XHAtbTVB-VwzOJrJ1J92lUoUsfa41lxGYGrTokbgKq-8laiABBS4BM1SJ5M8kQQjonwZMbK2bjfWKbWfkY03dn2l8Q_0umFvrCJyW4n9CUFC21wktFJ1Nrfa5ya9py8K6skrX_AAAiZ4zFOmUJYCF5SjJ4KnKCqXJ5gkii64ay9ynKoEW5JZPGIKkvCZSyNZKPxIu7UWjJNMpm7dCBMFYd6p8laHTQOQPnRdK8KBlSU1A5jQrAnFVbhz4dbiVrOw1Ont7h8cdnc6R10brHiO7n3sH_f6vf0c1HPw7cFxp99HZDpHTrqH2wdH3XsvHBoaZ78yLLYDPWjBDb6bSxOFCTPt6DTgEvXBU_-Cgi8DEF6ZoN2oeiBRtnCFVyv8_7-4lleZVs5THN40YaK4TAktkBu33noCBCr98_kLWDYwGbj57jpBFk808Ur1OhuhCzZoLMR3ncuES1KUicQPNLE8qyqq1tDCJShHaZcjpKhiSMsVpeXWPjx-NSW7Qr-iREofIn7FYJZkkE1MG8yT3gfTMH0hIL1gcJ0oEWjwQad-xPLzfmcXz68vZnly-u4Mk5Hvj0ej8Xjk51hnewexaR5-ygP85vGMCZFcA3YT-9g4g5THBelZt3v89Jv-BQ "Python – Attempt This Online") - Python `import regex`** [Try it online!](https://tio.run/##lVTbjtMwEH3vV4yMpcTdJrvl8gAllKXahUWshACxoDaAmzqJkWMH29m2lPDIB/CJ/Mgy2UKhEi/MQzSX46Mz44lrsxTWlUKpK2qTh8GVO4zDcRLGfcrC8f2k88cP4v44jDFO4n6vy8xujxkLZ7cOwtlNhnYwG1L2Lu4z9qUX9w/pnUNZFVfBw5HMQ2qnR2mkBXGEbXxpzRKCc@mc1AVgLmjpIkHMML0GL6LCk68kMjacWlGIVRpMj6K7x9Es5VFLQ9Y/iO8/GL9LAxafc5@VwuEhtmM@05dcyQUshJKV9MIiv0X@@GWtpO@gW02xErrwJeqC27vDF9agKN1Uc2HB5H9IXND2qOtk3kxHQItkiN88IRNT1VKJBRnBNCu5naYpYm6lX06NPeFZuXFLiRpD@p5teoAWFAFsaAEJRMN2m5FdJscMoZu8HZwV2lgx4U6QX4BqH3DeKC@V1Lu626@/xMEq8TdA7wNOVjiKTPoJr31jd6jVv3Q85x7b1xclTsHVPNuh7T76hSxK/8o8E7knLVzbDcga500FEWjjwTV1bawXC5ivIRznihcM3Fp7vtoyZvuME2wT1XX3aSXXHe1/MLZ4Xzb5tUH37mmxDK93bEBz1qOfk6NRjt3x7moUSA1U6rrxbNPthur2VXwKSLCNP7PN0mL/UWmcb/HwcPQnhkgbZO/GjcIV/Pj2HWg4MfpSWBxI9NQZZLexFbXC8YW/S6fWVNsimVKVEhZ9NKiDfNAfyIC6AS0YI217RbRAOBRGaw6FvBSwNg00NRkAeX32nPQIVwp8KWBprFo44OA8L0RXf3b8GOvLct0FF0/eYjDnPJvPs2zOu9zxownmVp37pnPQfvtrfBHwl3DNvML5Y3NeVtekb09OXpGf "PowerShell – Try It Online") - .NET Since mrab-regex supports variable-length lookbehind, the only adaptation necessary in this port was to eliminate the use of nested backreferences. Groups `\4` and `\5` are copied to each other. # Regex (Perl / PCRE), 86 bytes ``` s/.(?=(.*) (.)+((?<=(?=^(?>.*?(.)(?=.* (\5?+(\4))))+\1 .*(?=\2)\4|(?3)).)))| .*/$2/sig ``` [Try it online!](https://tio.run/##TY/bTsJAEIbv@xSTTZPuQl2ohxsWqAeIhxg10aiEYrOFFWqWFnsQCXLrA/iIvgjOqkTnZme@fw7/zlSm99ZlruDs@vJCgMk6spCNRqeczlQmrMc0o3bcqotmW@DrsSXEj0jYcpbFSQEkSIhYga2hBXkZ5QW2h@6W53pMPRsR/H@8jgqDBtihsAAXAd1oGjUz4hCHLW2J20ZqmI5U@JSnCTh9h9uaOwNHwM9dHHDg8/0DkNghtu/j1KpfH3BzlP9U3kCs8xqnfovyCrMoZ1VK/WYLwQP127ziI8KCVywa7PlVGuwyjGrgWbyCPNhmwe4b9XcY48jfkNbs7Voej9cbH7/@VfJntm@HAxc8F/CvYrVak0S9qAzGaZJIGMcvChZpCeWMuEBuT6@IRaTWUEwUzNNMj3KQkBdyrIx@fnCM@nyyMMXdSQ@LSMphFA2HkTTs4PAI2atJ702CsckXSut0bhxOJXpVUMTT76W9bveGfAE "Perl 5 – Try It Online") - Perl - all test cases [Try it online!](https://tio.run/##lVTbbts4EH33V0wJIiIdWbbT7ENXVoxs6@160U0C947IFWiJkpXSlEDKsXPbx/2A/cT@SDqUWxQNtgtUD/ZwODwz53CGC2GX90aKDHomA88DMxp5yU9@Xmc0rpc1UAMR1EYWiZG1EqlkXj/ojpNkKVSTpNWqLpU0MYt5GM/61vMxoQ85OpNCugDdSN1YliS/T19MkoT7MORhp8yBUXM@mD@KPOtxaJam2oCWG5hsU1k3ZaWZ91dpbakLIJZ4eIZmWAoeGs5DaM9nR97fHtze7upbiSZdYnXng96T4148F707ynh3PxgdjT/M@55PM/7fichUXwpVZpBJVa7KRhri0jnmclurKpOYy8fUfJc4rda6wfL5o@jwB4hvTYWF6/VqIQ1U@Tdk20LbHZMDZELznf3Y2S4l0gx2NN1/ht4CvcOwk1d4qUjRNiaxtSqxhJyDsEBTftMKksLeHuB2XVlGinJlt8fPXr/7c018DImiKBfKyh@I/VobmVaFLq9lBrkSKLsX0DTwnPY7vdMo8gq8LFpEvWEIEsFcyQHWnIZ3nXxjkCF7@erZZDbzydnT2QQuke73fuwI2wjUz3MByZvJ7OX09MTjD@NIrJ1UpS4TKxtG6tTIYCHSj43Bn6SVk/hAekPi6vsuDJmsjUVa/x92sdsauDwoLqPX0SCkKsqxc62rY3rCQ36D5BlV56irkhot3hvOo6itD4PteoE76PYHfm/YSoVAXKbLyoXg9V1HeHnQSvgNY28PIQeI4/S9Abp6OGbUYMdZHy6qEvsJkfwLi4QyvCTsR3JOAqoCMiccJ4oWmNdlBEIVfPrnXyBf1i2kErZJpDFIEVv2bDZ5npycJijy6WxMJs5Pfm3BpW7B6Qrh7u4ezDjj4b3tB2wcsaDLOyzg@4yNRxE6PrDxET4K6MJF0O2w@JfxPosPOX778bATdNEfH/D48JaNH3MeoP8WvX160Ldlcf@zj1On5dbTSNeQI1dzgG9VKLcyhf7amv6i1H33en3duidaXuIkFpXWAoryUsJVtYZ17e7/zfSMdIhQCgdDwqYyKrMgcI5EId3@i@PnuL9ZXrnF2z/e42IhRLpYpOlCON/xb0/Rt3XmO2fg99W@kkrhrGGTrIQptYSmXLWg7yeTV@Qz "Bash – Try It Online") - PCRE1 - all test cases [Try it online!](https://tio.run/##fVTbbts4EH33V7AEEZGOLNtp9mGrKEK2UbtedJPAvSNyBVqiZKYUJZBynOs@7gfsJ@6PZIdyi6JBuwJsD2dGZ@acGbpdtQ8HcbtqETEoQq0RVWZEq3guqDcOhnGWrbjqsrypW6mESWnKwnQ@tp6PPPiU4Mwq4RJ0J3RnaZa9mL1Ksoz5aMrCgSwRJeZ8sngSedZjqFuZZoO02KDkKhdtJxtNvT@ltVJXCFvswTukgFbgpekiRP37xaH3l4fu7rb91bzLV9Dd@WT069EoXfDRPaFsuBscHMafFmPPJwX7cSE805dcyQIVQsladsJgV84xF1etagoBtXwozbaF82atO2ifPYn2f4L43jTQuF7XS2FQU35Dtj203TLZAyak3NpPne1KAs1gS9P9FuCtwDsNB2VjBAeKtjOZbZWEFkqGuEUkZ7e9IDna2UEQbhtLcSVre3V0/PbDH2vsQ0oURSVXVvxE7LfaiLyptLwRBSoVB9m9gOSB57Tf6p1HkVfBsEgVjaYhEgDmWg6g5zy8H5QbAwzp6zfHyXzu47Pn82QPXQLf7wOwErbjIKDnMrJ3yfz17PTEY4/zcKqdVlLLzIqO4jY3Iljy/HNn4Cvr9cQ@wqMpdg1@lwZU1sYCr/9Pu9iGJq4OqEvJTTQJiYpKWF3r@pidsJDdAntK1DkIq4QGi42miyjq@4Nku15CBNz@xB9Ne60AiIl81bgUmN9NBNNDvYbfMHZ2AHICOE7gW0Tqx/eMGFg566OLRsJCAZJ/YYFQAVOChcTnOCAqwAvM4EqRCuq6iggThf79@x@Ev5x7SMVtlwljgCLs7Nk8eZmdnGYg8uk8xonz42c9uNA9OKkB7v7@0SWnLHyw44DGEQ2GbEADtktpfBCB4xOND@FfAVxwCIYDmv4S79J0n8Gzm04HwRD86R5L9@9o/JSxAPx34B2TvbGV1cMD1uISbkrVaM1RJS8Fum7WaN268bybneEB5krB4gq0aYwqLOKw57wSLv7q6CXEN6trd3j/@0c4LDnPl8s8X3LnO/rtOfiunPnBGfB8ta@FUnAXYIY1N1IL1Mm6B/2YJG/wfw "PHP – Try It Online") - PCRE2 v10.33 / [Attempt This Online!](https://ato.pxeger.com/run?1=fVTNbtw2EL70tOc-AEMQFrnWancdF2gry4KTqOkWqW1sEieBtRG4EqWVS1ECqfX6t8c8QA699BIgyEOlxz5Jh1KKIEZTAbsazgy_me_jUH--b1bNu7---XYvBAMRjQLUaFEkWjSSp4I6Y28YJsmKyzZJ66oppdAxjZkfz8fGcZEDvxycSSFsgmqFag1Nkp9mT6IkYS6aMn9Q5ogSfTpZ3Asc4zDUrnS9QUpsUHSRiqYta0WdX0tjSlUgbLADe0gGrcCm6cJH3f5s3_ndQTc3fX8Vb9MVdHc6Gf1wMIoXfHRLKBtue3v74evF2HFJxv67EJ6pcy7LDGVCllXZCo1tOctcXDSyzgTUcqE06wun9Vq10D67F-x-BfGFrqFxta6WQqM6_4xsOmjTM9kBJiTv7fvWtiWBptfTtO8MvAV4p_4gr7XgQNG0OjGNLKGFnCFuEEnZdSdIira2EISb2lBclJW5OHj0_OUva-xCShAEOZdGfEXs50qLtC5UeSUylEsOsjseST3Hat_rnQaBU8BhkSIYTX0kAMy27EHPqX87yDcaGNKnzx5F87mLjx_Oox10Dny_DMBImJaDgI7NSE6i-dPZ0aHD7ubhWFmtSlUmRrQUN6kW3pKnv7Ua_pJOT-wiPJpi2-AXaUBlrQ3w-v-0sz40sXVAXUqugolPZJDD6Brbx-yQ-ewa2FMiT0FYKRRYbDRdBEHXHySb9RIi4HYn7mjaaQVATKSr2qbA-V0FcHqo0_AzxtYWQE4Axwp8jUh1954RDSNnXHRWlzBQgOSeGSCUwSnBQOJT7BHp4QVmcKVIAXVtRYSJRH-_eYvwp3UHKblpE6E1UISZPZ5Hj5PDowREPpqHOLJ-_GMHLlQHTiqAu729c8kp8z-s23z0_ccTM_ZoGFBvyAbUY9uUhnsBOF7TcB8-DuCChTcc0Pi7cJvGuwye7Xg68Ibgj3dYvHtDw_uMeeC_Ae-Y7IxNWfTo7z69Pv6BlTiH61PUSnFUlOcCXdZrtG7smZ3MjvEAcylhmgXa1FpmBnEYfl4IG39y8Bjim9WlXbz4-RUslpyny2WaLrn1HTx4CL4La760Bjz_2pdCSrggcLAV16USqC2rDvRVFD3DfXv_AA "PHP - Attempt This Online") - PCRE2 v10.40+ - all test cases [Try it on regex101!](https://regex101.com/r/H2drs5/9) - PCRE1/PCRE2 - try it on your own This is a port of the .NET regex, emulating variable-length lookbehind using recursion with fixed-length lookbehind, but there's an additional challenge. The .NET regex makes a capture inside the lookbehind which is used as the substitution replacement. That is impossible in Perl/PCRE, since all captures made inside a subroutine (recursive or not) are erased upon exiting it. So to communicate back from the emulated lookbehind, this regex makes a guess (`\3`, captured by `(.)+`) as to what the capital letter in string `t` will be, and then compares that with the capital letter actually matched inside the lookbehind (`(?=\3)\5`). If it's not a match, the regex will backtrack to before the emulated lookbehind, and try capturing a different capital letter from string `t`. [Answer] # PHP, 90 bytes ``` function($a,$t,$i=0){foreach(str_split($a)as$c)echo($z=$c^' ')==@$t[$i]?[$z,++$i][0]:$c;}; ``` Simply loops through the characters in the string, and outputs the capitalized one when necessary. This is an anonymous function, so, it has to be given to a variable to be called. You can try it on here: <https://onlinephp.io/c/61a1c> (Contains all test cases in the question.) --- ## How it works? It uses the fact that [XOR](https://en.wikipedia.org/wiki/Exclusive_or)ing an [ASCII](https://en.wikipedia.org/wiki/ASCII) character with a space, will toggle the 3rd bit, which will change the letter case. With this knowledge, I avoid running [`strtoupper($c)`](https://www.php.net/manual/en/function.strtoupper.php), saving me a bunch of bytes. --- This is useful for checking against the backronym letters, which are in upper case, and to display the upper case letter. These are accomplished in `($z=$c^' ')==@$t[$i]`. The `@` is there to suppress warnings, which will happen when we exhaust all characters in `$t`. --- To make the code shorter, I've used `[$z,++$i][0]`, which displays the upper case character and increments `$i`, without the need to make an `if`. The (much longer) alternative is the following: ``` if(($z=$c^' ')==@$t[$i]){++$i;echo$z;}else echo$c; ``` --- One edge-case that people may see as an issue, is with spaces. However, if you XOR a space with a space, it gives a [null character (`\0`)](https://en.wikipedia.org/wiki/Null_character). **Luckily**, a null character is a [truthy value](https://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting). Another possible edge-case, with spaces, comes from the fact that, after the `$t` string is exhausted, the value will be `null`. Since the null character is a [truthy value](https://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting), and `null` is a [falsy value](https://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting), this will never be `true`, which means that I can use [`==`](https://www.php.net/manual/en/language.operators.comparison.php) instead of [`===`](https://www.php.net/manual/en/language.operators.comparison.php), and saves 1 byte. [Answer] # [Lua](https://www.lua.org/), 71 bytes ``` a,b=...;j=1;for i=1,#a do x=a[i]-32;if x==b[j]then a[i]=x j=j+1 end end ``` [Try it online!](https://tio.run/##Jc2xTsQwDAbgnaewekui60UqbFd5YGK5N6gyuGnSpoTklLjiEOLZSwODZfmX/TlstDsMiaZh2KkdUSnVr9j1LmXw2LUnginBA2nw@vLy3Ht3DDgOq@bFRqgxPmDF9dyBjVOtXWu3RcM@RRi/2BZRZEiGAjB@/1TYgI9QrvMHsVka1RwfeDjxudNorvVEyGply1uOwBV9YvyzGgqHs1j4TDlMBQgK02wbJ7j9X7i9vjXynn1kUfhoszILZcE0Bqu2eCfzLlhKuf8C "Lua – Try It Online") Chunk which modifies `a` in place. Mostly equivalent to the Go solution. [Answer] # knight, 68 60 bytes ``` ;;=aP=bP;=j=i 0W<iLa;O I-32-A=cGa i 1A=dGb j 1c;=j+1j d=i+1i ``` [Try it online!](https://tio.run/##rVltU9tIEv5s/4rBKWyNXxJJcFVblmUKskBRR4CF5PIBfEGWZZisLPskGZYj3F/PdffMSCPb5C53ywfLmnm6p/uZnu4eE/buwvD7G5GE8XISDbJ8IuZv74d1cyQW48pQmD8tohVQKpK7ylAuZhIziaYiiVgcs3ie3NFHvRj9ePbpA3PK16uPl8wtX/@2f8l2y9ejs/fsl/L18hNzSvDR6ZWBPft0akA/nX3Yv/qrlXFm4UeT/cv5Cy9m969gWTkZ3gcpa/NSwESBrYWK4ZDtlnNnh59xMoFJ8ugbw@@DwQoGlyEMugmYOOYIrGAOzs9PCYQfe@RkH30zDLk8lgCQN2x9COJlxPl1MuL1OvkBu3I98i8bh@dH1nfP84MLf3zh@V99wezPA3EaeOfspLfj9vb98Dhggjn7/uR4zL4yJwRYx/nKJr7oOOI7BxUNT2ptg9oomDEf9Xv1OhixCNIssjh7rtdEkjPh1WswSgZ1WXu6TEIYIeEQ3vPZopstkmt35D/bXfsFdNQEqCM8PG0cePcO1YsFe7wXeZQtgjCq1@B7HFkwDuKWNKPLGjf5TXIzvUnZ88v1yOL9Nw1OptTElFmFtT5rvWlxJlXo0S0YvUlguNORI2BnLYqzyBx4keaE91H4O5vOU5YsZ@MozZQ9zBLZRNyJXGuF1dEdp1t4JJ9t5tisw9rK8k6Hsx5r2S1YAi0VnKVRvkwTpkNIilEUeas2PASpCMZxpK0AI@L5Y5RaIaynDWHfvjFtXEhvIRHxpcUVPWKD68J3urBHfjG8Yh0eShW8AEkmy4WFW8oUpz0Gb@sGyxSRSW3SjJtWq7Sp0ZKbBsLgQWEUAyWQUuA7WLYIspzl9xEoC9IcwGoD2ppR3NCQoyfaWOOkvWosfDqcNrpWkkHmY@jmYp6A2Rix9ghMCzUj2XKxQMK5jio9YtJvxh/QbpCNOnQoLxKIY0hvGLnKcsnKx1aRA@TAEQ5gqutjikMzdZBRdpSuWmg3mhrE8Ty0du2uw9FBHC6cIAeTZRwH6ZPpaLk/l8b2XLQKy2hBJb9MVqRpCQeXUElhk6f7hwfvb3/bOv313HDYVDsWG/W663q3KoqPT65e0ZhHKakMkgn7xzLQr6j2wVxiZ30JScBxq@DiZAMXJLxbFa5iXihVpssEd8hTKbqdzzNL50o6ABDauQgZzY6X02t3d6TskBvdpPRQGJAt4FjlUwug4P92HE8aOu9QieqiklUFcCgKBbL4yfUruAFzdqp@ovMYi3uskafLqAExWIxjSML4NIAMghMNjKxGSQL6ib6rKkV0fDmYz2OYGVcZeNXX0q0fOdT@eY9MM8drZsZoY/Kn2ghBm8/j2DJN7TK7CxXifzA5WTMZq/CH/YuzLtZiGWjwenLt2LYN4QSuwKt@y8Q/oy85w4dnxKjhLTIAb138cOlzx3d0SccMh1UdH/TpyscOAI5OTg/bbArJ0asVoa3WwzQcBotuHCXUARhc6SZKcgbn7jUyVgWxNmFpw4JjCeoloBYPiAsPiorAySJvhLPFyg4QSWJUphCkSYxwmexR5OG91QZm1nou4IipvxDrVGu/1We4igT4SCh2bZCFeZOcUupV31gJWe5RFS4R1JzmKZYu6k@vR/y5DDNooCi3y4UvYeGq7hQynsWb9h9T/CuRF4AErZKjuyiPobW0mrSXTdwhLJETkXBPTC2L9hMbgvA@RVu6EKecy232bW@jrfDg1AbI9Q7lerJzxGygCPG0vUiSyp2llQelPxJfzLwvZ1DSpLjA3AIGowHiz1/MF1FiGQt3G2mDWgWwyp/JSgnx6Lv27i80rpoLS3YkUzB9gk5BCwch28X@DuDQO9AbrgFL6/CyYJB1fGqF8MQCkiu6QQ@tRVSjhrbPXLNnKWksPfkNPIn@gDYOT/uan1uVXacbxBZmsjXg6Vp4wCpxlRcD/murr/rEDYFcZD5VgRpn1BZbWIO4LkLD4S4vG8u1dKhFr6g5tLYzFKwehnVhoBNaH3NdyKS8UUL1BJaXKEiU2tdKmKpZ5g6o3KJYOC9ZwIMhLz5ImtzPCnWs2aRrV6@H0JFsc2@o3a5ps7bftjOwx4I3zvRRSw3zl3mmd7@ICdnrSYM6hUGUJyFfYkrG0DK2R3bTtepuyzssoqHvZzqWXLnn2P/SYZAbQCgcxlPuay9dvjlUwyDXD9V1Op2SJq6/oy4O3WiXnrnKEcqv3lp0GtGOrXrVXinULndnAwur5XkDD@01HuS@bmJhtsG1NmF8UwkJQA2yKEP6rRu45CHI6/VInyKKSubqRktG88rpf/dDYt5tJmb7h0Lbm4X@TmxWHJJXBxpzTS89Rbtk3Wc9p2CZsEC9A@es58AZc0yw@5PoAaTHCtb3EUrr9vWIrSknot2hrbh2ObUrbZ/4r68eCJokV@COQAkWSwx8xyvDfZRGrYwlc@ihRZyLhD0GT8Abm8zhTppHd1EKMot5EiW5CPAWASd5zh4jdh88RABUihCes1mQLCF8nt7iKHo3RsaBCmIiW8Y5/mhAixcJT0N6JkYvuUKZKVdAVtSjvteR9uuGFLBBBWXT/TyIsTY@gdfJJI4m7LY0@7bQ8ozfZGNmLFI6M0RlvZ5@5wSvKWjbMP2lyIMDCtaVwodJr5IX/WpW3GPm4R@YxwBF@@rXuSaTgD1WaRRpsMuMbIg6bCmpS64r6wBit3yoNkYXNIRDiaE1n8z7bBbNwgWGWcKGt3v/ryvDP8GVoXZla4MvvvJFubL3Ovty1Q0m4/QeqwDcAuHqArq1yc7ypXBPZx5TQWFes0x/6Mum2rBnSqpUUsh/@2/kVQ4y1BTyXqtvoitt7irWL7NudfqnLzK6ty1vMoirVW4zRSokDGoc@RVpI02iBCI6nUJMmvwZ3JO/epmNZsU7ZvYuSuyk2rUj1JDfc/s7Bi3H8srgGx1WxyxA63ekRF08usVZ2Kk0tFeS6BWl3mrJczeVvB1e9AFuIb1Lg/@hIULD8IlbERbNf9EOmb2RCx7iqh0HmyRqEGT8y0l6EKKjTgKsPommASRJ8Ex3mCKBSTGhH5GCMIcy1doOW9hz4ghnr9xiUVlRA6EbVD8kzAKRYLPKgvQu7JLSdhu@P3D8uYrul/jPHssma6rXuJfv4yAIx@MwHAf1/YP3/wY "C (gcc) – Try It Online") *-8 bytes thanks to Adam for some nice spacing rearrangements* In my [J answer](https://codegolf.stackexchange.com/a/249849/15469), which required a lot of machinery, I noted: > > It's interesting to contrast how simple it is to solve procedurally -- you need only a single loop and a single register. > > > Since knight is a very simple procedural language, I thought it would make an interesting juxtaposition. ## how ``` ;=j=i 0 # initialize indices for the two input strings ; ;=aP=bP # read the inputs into variables a and b W<iLa # while (i < a.length)... ;O I-32-A=cGa i 1A=dGb j 1 # Take the ascii difference between the chars # a[i] (store it in c) and b[i] (store in d), # and subtract that from 32 c # if the difference is not 0, return c (the lowercase) ;=j+1j d # if it is 0, return d (the uppercase) and # increment j =i+1i # increment i in either case ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 26 bytes ``` ri\ >~&o! &:<&o^?=-*48@:$ ``` [Try it online!](https://tio.run/##S8sszvj/vygzRkHBrk4tX5FLzcpGLT/O3lZXy8TCwUrl//9IV9eQ/7rFlak5OfnlCsWlSbmJRZl5qQolmbmpAA "><> – Try It Online") [Answer] # [Thunno](https://github.com/Thunno/Thunno) `J`, \$ 13 \log\_{256}(96) \approx \$ 10.70 bytes ``` XeDxAJ=?xZTXu ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSSl1LsgqWlJWm6FmsjUl0qHL1s7SuiQiJKIWJQqQX7lcoyC5S4lPJSy1KLFNLz8_ISFdIzy1IVKvNLFUoLlCDKAA) Port of Steffan's Vyxal answer. #### Explanation ``` XeDxAJ=?xZTXu # Implicit input X # Store the first input in x e # Map over the second input: D # Duplicate the character xAJ # Push the first character of x =? # If they are equal: xZT # Push x without its first character X # And store it back in x u # Push the character, uppercased # (Otherwise: the character remains on top) # The J flag joins it into a string # Implicit output ``` ]
[Question] [ # Introduction I don't *particularly* know where the fizz buzz trend came from. It might just be a meme or something, but it is somewhat popular. # Challenge Your job today is to convert Fizz Buzz into binary (0, 1) respectively, and convert that binary to text. Pretty standard stuff. # How does that work? FizzBuzzBuzzFizzBuzzFizzFizzFizz FizzBuzzBuzzFizzBuzzFizzFizzBuzz would translate into 01101000 01101001 then that would translate into "hi" # Constraints * Input is Fizz Buzz in a binary standpoint (see examples below.) * Output must be text. * You can assume the FizzBuzz input is right. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest bytes win. # Input > > FizzBuzzBuzzFizzBuzzFizzFizzFizz FizzBuzzBuzzFizzBuzzFizzFizzBuzz FizzFizzBuzzFizzFizzFizzFizzBuzz > > > # Output "hi!" [Answer] ## C, 59 bytes ``` i;f(char*s){while(*s&3?*s&9||(i+=i+*s%5):putchar(i),*s++);} ``` Magic numbers, magic numbers everywhere! (Also, C shorter than Python, JS, PHP, and Ruby? Unheard of!) This is a function that takes a string as input and outputs to STDOUT. ### Walkthrough The basic structure is: ``` i; // initialize an integer i to 0 f(char*s){ while(...); // run the stuff inside until it becomes 0 } ``` Here, the "stuff inside" is a bunch of code followed by `,*s++`, where the comma operater returns only the value of its second argument. Hence, this will run through the string and set `*s` to every character, including the trailing NUL byte (since postfix `++` returns the previous value), before exiting. Let's take a look at the rest: ``` *s&3?*s&9||(i+=i+*s%5):putchar(i) ``` Peeling away the ternary and short circuiting `||`, this can be expanded to ``` if (*s & 3) { if (!(*s & 9)) { i += i + *s % 5; } } else { putchar(i); } ``` Where do these magic numbers come from? Here are the binary representations of all the characters involved: ``` F 70 01000110 B 66 01000010 i 105 01101001 z 122 01111010 u 117 01110101 32 00100000 \0 0 00000000 ``` First, we need to separate space and NUL from the rest of the characters. The way this algorithm works, it keeps an accumulator of the "current" number, and prints it whenever it reaches a space or the end of the string (i.e. `'\0'`). By noticing that `' '` and `'\0'` are the only characters to not have any of the two least significant bits set, we can bitwise AND the character with `0b11` to get zero if the character is space or NUL and nonzero otherwise. Digging deeper, in the first "if" branch, we now have a character that's one of `FBizu`. I chose only to update the accumulator on `F`s and `B`s, so I needed some way to filter out the `izu`s. Conveniently, `F` and `B` both have only the second, third, or seventh least significant bits set, and all the other numbers have at least one other bit set. In fact, they all have either the first or fourth least significant bit. Hence, we can bitwise AND with `0b00001001`, which is 9, which will yield 0 for `F` and `B` and nonzero otherwise. Once we've determined that we have an `F` or `B`, we can map them to `0` and `1` respectively by taking their modulus 5, because `F` is `70` and `B` is `66`. Then the snippet ``` i += i + *s % 5; ``` is just a golfy way of saying ``` i = (i * 2) + (*s % 5); ``` which can also be expressed as ``` i = (i << 1) | (*s % 5); ``` which inserts the new bit at the least significant position and shifts everything else over 1. "But wait!" you might protest. "After you print `i`, when does it ever get reset back to 0?" Well, `putchar` casts its argument to an `unsigned char`, which just so happens to be 8 bits in size. That means everything past the 8th least significant bit (i.e. the junk from previous iterations) is thrown away, and we don't need to worry about it. Thanks to [@ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions) for suggesting to replace `57` with `9`, saving a byte! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Ḳm€4O%5ḄỌ ``` [Try it online!](https://tio.run/nexus/jelly#@/9wx6bcR01rTPxVTR/uaHm4u@f///9umVVVTqUQDGODaBhWwKcAxFZA5iDrhIkBAA "Jelly – TIO Nexus") [Answer] # [Bash](https://www.gnu.org/software/bash/) + coreutils, ~~61~~ 50 bytes *(-11 bytes thanks to [Doorknob](https://codegolf.stackexchange.com/users/3808/doorknob)!)* ``` tr -d izu<<<$1|tr FB 01|dc -e'2i?[aPz0<k]dskx'|rev ``` [Try it online!](https://tio.run/##S0oszvj/v6RIQTdFIbOq1MbGRsWwBsh1c1IwMKxJSVbQTVU3yrSPTgyoMrDJjk0pzq5QrylKLfv/3y2zqsqpFIJhbBANwwr4FIDYCsgcZJ0wMTpY8TUvXzc5MTkjFQA "Bash – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~169~~ ~~101~~ ~~93~~ ~~91~~ ~~85~~ 81 bytes ``` lambda s,j="".join:j(chr(int(j('01'[b<"C"])for b in c[::4]),2))for c in s.split()) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFYJ8tWSUkvKz8zzypLIzmjSCMzr0QjS0PdwFA9OslGyVkpNi2/SCFJITNPITnaysokVlPHSFMTJJYMEivWKy7IySzR0NT8X1AE0poGNKCgFCSg@d8ts6rKqRSCYWwQDcMK@BSA2ArIHGSdMDEA "Python 3 – TIO Nexus") Explanation: ``` lambda s,j="".join: # Create a lambda function j( # call "".join, adds characters together with nothing in between chr( # character by int int( # string to int j( # "".join again '01'[b<"C"] # 1 or 0, based on what character we get for b in c[::4] # For every first of 4 characters ), 2) # Base 2 ) for c in s.split() # for every group of Fizz and Buzz with any whitespace character after it ) ``` [Answer] ## JavaScript (ES6), ~~80~~ 79 bytes ``` let f = s=>`${s} `.replace(/.{4} ?/g,m=>m[s=s*2|m<'F',4]?String.fromCharCode(s&255):'') console.log(f("FizzBuzzBuzzFizzBuzzFizzFizzFizz FizzBuzzBuzzFizzBuzzFizzFizzBuzz FizzFizzBuzzFizzFizzFizzFizzBuzz")) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~26~~ ~~24~~ ~~19~~ 17 bytes ``` ¸®ë4 ®c u5Ãn2 dÃq ``` [Try it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=uK7rNCCuYyB1NcNuMiBkw3E=&input=IkZpenpCdXp6QnV6ekZpenpCdXp6Rml6ekZpenpGaXp6IEZpenpCdXp6QnV6ekZpenpCdXp6Rml6ekZpenpCdXp6IEZpenpGaXp6QnV6ekZpenpGaXp6Rml6ekZpenpCdXp6IiAtUQ==) Saved 2 bytes thanks to [@Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) & 2 bytes thanks to [@ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions) ### Explanation ``` input: "FizzBuzzBuzzFizzBuzzFizzFizzFizz FizzBuzzBuzzFizzBuzzFizzFizzBuzz FizzFizzBuzzFizzFizzFizzFizzBuzz" ¸® // ["FizzBuzzBuzzFizzBuzzFizzFizzFizz","FizzBuzzBuzzFizzBuzzFizzFizzBuzz","FizzFizzBuzzFizzFizzFizzFizzBuzz"] ë4 // ["FBBFBFFF","FBBFBFFB","FFBFFFFB"] ®c // [[70,66,66,70,66,70,70,70],[70,66,66,70,66,70,70,66],[70,70,66,70,70,70,70,66]] u5à // ["01101000","01101001","00100001"] n2 // [104,105,33] d // ["h","i","!"] Ãq // "hi!" ``` [Answer] ## Ruby, ~~65~~ ~~63~~ 60 bytes ``` ->s{s.split.map{|x|x.gsub(/..../){$&.ord%5}.to_i(2).chr}*''} ``` This is an anonymous proc that takes input and gives output as a string. ``` ->s{ s.split # split on whitespace .map{|x| # for each word as x, x.gsub(/..../){ # replace each sequence of four characters with $&.ord%5 # the ASCII value of the first character, mod 5 # F is 70, B is 66, so this yields 0 for Fizz and 1 for Buzz }.to_i(2) # interpret as a binary number .chr # the character with this ASCII value }*'' # join on empty string } ``` [Answer] # JavaScript (ES6), ~~95~~ ~~88~~ ~~85~~ 81 bytes ``` s=>s.replace(/..zz/g,m=>m<"F"|0).replace(/\d+ ?/g,m=>String.fromCharCode("0b"+m)) ``` * 4 bytes saved thanks to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions). --- ## Try it ``` f= s=>s.replace(/..zz/g,m=>m<"F"|0).replace(/\d+ ?/g,m=>String.fromCharCode("0b"+m)) oninput=_=>o.innerText=f(i.value) o.innerText=f(i.value="FizzBuzzBuzzFizzBuzzFizzFizzFizz FizzBuzzBuzzFizzBuzzFizzFizzBuzz FizzFizzBuzzFizzFizzFizzFizzBuzz") ``` ``` *{font-family:sans-serif} ``` ``` <input id=i><p id=o> ``` [Answer] # Perl 5, 33 Bytes ``` print(pack'B*',<>=~y/FB -z/01/dr) ``` Replaces 'F' and 'B' in the input with 0 and 1 respectively, and deletes the other characters. It then uses perl's `pack` function to turn this bit string into ASCII characters. [Answer] # [Python 2](https://docs.python.org/2/), ~~90~~ ~~83~~ ~~82~~ 81 bytes -1 byte thanks to totallyhuman -1 byte thanks to Martmists -1 byte thanks to Jonathan Frech ``` lambda x:''.join(chr(int(`[+(l<'D')for l in b[::4]]`[1::3],2))for b in x.split()) ``` [Try it online!](https://tio.run/##fUvdCsIgFH6Vc3eOFINWV1I3MXoJEzYLmWEqZrD28paFsKsuPr7/8Eqjd23Wh3O2w11dB5g4YnPzxtFljGRcol6syO6xQ6Z9BAvGgRKc76TsxYbzrVy37FupUk3NI1iTiLEc4ucOmvBk5vn4/KHqwhXwb1A0LM3yWTNk@Q0 "Python 2 – Try It Online") [Answer] # Whitespace, 123 bytes Visible representation: ``` SSNNSSNSNSSSNSNSTNTSTTTSSSTSSSSSNTSSTSNSNTSSNSSSTSSTTSNTSSTNTSTNSSSTNTSSSNSSTNSSNSNSSNSTNTSTNTSTNTSTSSSNSNNNSSSNSNTTNSSNSNN ``` Unobfuscated program: ``` push 0 loop: dup push 0 dup ichr get push 32 sub dup jz space push 38 sub jz fizz push 1 add fizz: push 0 dup dup ichr ichr ichr add jmp loop space: swap pchr jmp loop ``` There's nothing particularly odd about the implementation, the only real golfing is in some strange reuse of temporaries as well as not caring about the unbounded stack growth to skim down some more bytes. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~59~~ ~~57~~ 53 bytes ``` @(s)['',bi2de(flip(reshape(s(65<s&s<71)<70,8,[]))')'] ``` This doesn't work on TIO, since the communication toolbox is not implemented. It works fine if you copy-paste it to [Octave-online](http://octave-online.net/). It's not even close to be working code in MATLAB. Managed to save two bytes by transposing the matrix after flipping it, instead of the other way around. ### Explanation: ``` @(s) % Anonymous function that takes a string as input ['',<code>] % Implicitly convert the result of <code> to its ASCII-characters ``` **Let's start in the middle of `<code>`:** ``` s(65<s&s<71) % Takes the elements of the input string that are between 66 and 70 (B and F) % This gives a string FBBFFBBFBBBFFFBF... s(65<s&s<71)<70 % Converts the resulting string into true and false, where F becomes false. % Transformation: FBBFFB -> [0, 1, 1, 0, 0, 1] ``` Let's call the resulting boolean (binary) vector for `t`. ``` reshape(t,8,[]) % Convert the list of 1 and 0 into a matrix with 8 rows, one for each bit flip(reshape(t,8,[])) % Flip the matrix vertically, since bi2de reads the bits from the wrong end flip(reshape(t,8,[]))' % Transpose it, so that we have 8 columns, and one row per character bi2de(.....)' % Convert the result decimal values and transpose it so that it's horizontal ``` [Answer] # Perl 5, 28 bytes+4 bytes for flags=32 bytes Run with the flags `-040pE` ``` $_=chr oct"0b".y/FB -z/01/dr ``` `-040` sets the record separator to a space so that perl sees each group of FizzBuzzes as a separate line, then loops over those lines, changing F to 0, B to 1, deleting everything else, then converting to binary and from there to ascii. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Ḳm€4=”BḄỌ ``` [Try it online!](https://tio.run/nexus/jelly#@/9wx6bcR01rTGwfNcx1erij5eHunv///7tlVlU5lUIwjA2iYVgBnwIQGwA "Jelly – TIO Nexus") ``` Ḳm€4=”BḄỌ Main Link Ḳ Split on spaces € Map m 4 Take every fourth letter (F and B) =”B Check if each letter is equal to B (gives the binary representation) Ḅ Binary -> Integer Ọ Unord; gives chr(i) ``` -3 bytes thanks to Erik the Outgolfer [Answer] # PHP, 67 Bytes Limited to 8 letters ``` <?=hex2bin(dechex(bindec(strtr($argn,[Fizz=>0,Buzz=>1," "=>""])))); ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6vklllV5VQKwTA2iIZhBXwKQGwFZA6yTpiYkjWXvR3QUtuM1AqjpMw8jZTUZCBTA8gEsjSKS4pKijTArtGJBumxtTPQAemztTPUUVJQsrVTUorVBALr//8B "PHP – Try It Online") # PHP, 77 Bytes ``` foreach(explode(" ",strtr($argn,[Fizz=>0,Buzz=>1]))as$v)echo chr(bindec($v)); ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6vklllV5VQKwTA2iIZhBXwKQGwFZA6yTpiYkvX/tPyi1MTkDI3UioKc/JRUDSUFJZ3ikqKSIg2wK3SiQWpt7Qx0QOpt7QxjNTUTi1XKNFOTM/IVkjOKNJIy81JSkzWAQprW//8DAA "PHP – Try It Online") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 107 bytes ``` {(((((()()()()){}){}){})({}[{}])()())((){[()](<{}>)}{}<>)<>{(<{}{}{}{}>)<>({}({}){})<>}{}}<>{({}<>)<>}<> ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/v1oDDDQhULO6Foo0qmujq2tjIaJA@epoDc1YDZvqWjvN2upaGztNG7tqEBcCQVygDg2IXhs7oFAtSAFUJZD8/98ts6rKqRSCYWwQDcMK@BSA2P91kwE "Brain-Flak – Try It Online") +3 bytes for the `-c` flag. ### Explanation ``` { For each character in input: (((((()()()()){}){}){})({}[{}])()()) Push 32-n and 66-n ((){[()](<{}>)}{}<>)<> If character is B, push 1 on second stack. Otherwise, push 0 { If character is not space: (<{}{}{}{}>) Burn 3 additional characters <>({}({}){})<> Multiply current byte by 2 and add previously pushed bit } (otherwise, the pushed 0 becomes the new current byte) {} Remove character from input } <>{({}<>)<>}<> Reverse stack for output ``` [Answer] # q/kdb+, ~~41~~ ~~40~~ ~~37~~ 33 bytes **Solution:** ``` {10h$0b sv'66=vs[" ";x][;4*(!)8]} ``` **Example:** ``` q){10h$0b sv'66=vs[" ";x][;4*(!)8]}"FizzBuzzBuzzFizzBuzzFizzFizzFizz FizzBuzzBuzzFizzBuzzFizzFizzBuzz FizzFizzBuzzFizzFizzFizzFizzBuzz" "hi!" ``` **Explanation:** Split the input string on `" "` to give distinct lists of `FizzBuzz...`, index into each of these lists at the first character (ie `0 4 8 ... 28`). Return boolean list determined by whether each character is `"B"` (ASCII `66`). Convert these lists to base 10, and then cast result to string. ``` {10h$0b sv'66=vs[" ";x][;4*til 8]} / ungolfed solution { } / lambda function with x as implicit input vs[" ";x] / split (vs) input (x) on space (" ") til 8 / til 8, the range 0..7 inclusive 4* / vectorised multiplication, 0 1 2 3 => 0 4 8 12 [; ] / index the 2nd level at these indices (0, 4, 8 ... 28) 66= / 66 is ASCII B, 66="FBBFBFFF" -> 01101000b 0b sv' / join (sv) each row back with 0b (converts from binary) 10h$ / cast to ASCII (0x686921 -> "hi!") ``` [Answer] ## Haskell, 72 bytes ``` (>>= \w->toEnum(foldl1((+).(2*))[mod(fromEnum c)5|c<-w,c<'a']):"").words ``` [Try it online!](https://tio.run/nexus/haskell#@59mq2FnZ6sQU65rV5Lvmleaq5GWn5OSY6ihoa2pp2GkpakZnZufopFWlJ8LklVI1jStSbbRLddJtlFPVI/VtFJS0tQrzy9KKf6fm5iZp2CrUFCUmVeioKKQpqDklllV5VQKwTA2iIZhBXwKQGwFZA6yTpiY0n8A "Haskell – TIO Nexus") How it works ``` words -- split input string into words at spaces (>>= ) -- map the function to each word and flatten the resulting -- list of strings into a single string \w-> -- for each word w [ |c<-w,c<'a'] -- take chars c that are less than 'a' (i.e. B and F) mod(fromEnum c)5 -- take ascii value of c modulus 5, i.e. convert to bit value foldl1((+).(2*)) -- convert list of bit to int toEnum( ):"" -- convert ascii to char. :"" forces toEnum to be of type String -- now we have a list of single char strings, e.g. ["h","i","!"] ``` [Answer] # JavaScript ES6 - 98 bytes **too many bytes, but at least readable** Defined as function it is 98 bytes ``` let s=>s.replace(/(F)|(B)|./g,(c,F,B)=>B?1:F?0:'').replace(/.{8}/g,v=>String.fromCharCode('0b'+v)) ``` **test:** ``` "FizzBuzzBuzzFizzBuzzFizzFizzFizz FizzBuzzBuzzFizzBuzzFizzFizzBuzz FizzFizzBuzzFizzFizzFizzFizzBuzz" .replace(/(F)|(B)|./g,(c,F,B)=>F?0:B?1:'').replace(/.{8}/g,v=>String.fromCharCode('0b'+v)) ``` ### Explanation: ``` /(F)|(B)|./ ``` Matches the F and B letters and anything else as Groups ``` (c,F,B)=>F?0:B?1:'' ``` is a Function that captures the groups , returns a 0 for F and 1 for B , or '' c is the character matched F and B are now Parameters! the 3rd **.** group is ommitted as parameter F and B are `undefined` when the 3rd group is matched B is `undefined` when group F is matched The resulting 0100.. etc string is cut in slices of 8 bytes ``` .replace(/.{8}/g,v=>String.fromCharCode('0b'+v)) ``` and processed as **0b** *binary* string [Answer] # [shortC](//github.com/aaronryank/shortC), 35 bytes ``` i;AW*@&3?*@&9||(i+=i+*s%5):Pi),*s++ ``` Conversions in this program: * `A` - `int main(int argc, char **argv){` * `W` - `while(` * `@` - `argv` * `P` - `putchar(` * Auto-inserted `);}` Heavily based off of [Doorknob's answer.](https://codegolf.stackexchange.com/a/123368/61563) [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 17 bytes ``` {82⎕DR'B'=⍵∩'BF'} ``` ## Explanation ``` ⍵∩'BF' cut, removes all but 'BF' from ⍵ 'B'= equals 'B' turns it into binary stream 82⎕DR converts into character stream ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/2sLoUd9UlyB1J3XbR71bH3WsVHdyU6/FKaHulllV5VQKwTA2iIZhBXwKQGwFZA6yTpiYOgA "APL (Dyalog Classic) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Or [8 bytes](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVA&header=dg&code=uMtuYmlmKWQ&input=IkZpenpCdXp6QnV6ekZpenpCdXp6Rml6ekZpenpGaXp6IEZpenpCdXp6QnV6ekZpenpCdXp6Rml6ekZpenpCdXp6IEZpenpGaXp6QnV6ekZpenpGaXp6Rml6ekZpenpCdXp6Ig) if input can be lowercase. ``` ¸Ën"FB" d ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVA&code=uMtuIkZCIiBk&input=IkZpenpCdXp6QnV6ekZpenpCdXp6Rml6ekZpenpGaXp6IEZpenpCdXp6QnV6ekZpenpCdXp6Rml6ekZpenpCdXp6IEZpenpGaXp6QnV6ekZpenpGaXp6Rml6ekZpenpCdXp6Ig) ``` ¸Ën"FB" d :Implicit input of string ¸ :Split on spaces Ë :Map n"FB" : Convert from base "FB" to decimal, ignoring all other characters d : Get the character at that codepoint :Implicitly join and output ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes ``` #vy„FBÃS'BQ2βçJ ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fuazyUcM8N6fDzcHqToFG5zYdXu71/79bZlWVUykEw9ggGoYV8CkAsRWQOcg6YWIA "05AB1E – Try It Online") [Answer] # Google Sheets, 94 bytes ``` =ArrayFormula(JOIN("",CHAR(BIN2DEC(SPLIT(SUBSTITUTE(SUBSTITUTE(A1,"Fizz",0),"Buzz",1)," "))))) ``` I'm not familiar with FizzBuzz binary but it seems that they're delineated by spaces so this formula relies on that. The logic is pretty simple: * Replace `Fizz` with `0` and `Buzz` with `1` * Split the result into an array using a space as a delimiter * Convert each element from binary to decimal * Replace each element with its ASCII equivalent * Join each element without a delimiter [Answer] # Java 8, ~~117~~ 115 bytes ``` s->{for(String x:s.split(" "))System.out.print((char)Long.parseLong(x.replace("Fizz","0").replace("Buzz","1"),2));} ``` I doubt you can do a lot of the fancy regex replacements in Java like most other answers, mainly because you can't do anything with the captured capture-groups in Java-regexes.. (I.e. `"$1".charAt(...)` or `"$1".replace(...)` aren't possible for example.) **Explanation:** [Try it here.](https://tio.run/##fVA9bwIxDN35FVamWIKIdiwqQ4dOhYWxYnBDoKFHEsU5xIfut6cJ3KlMlfLk52fHec6ejjTxwbj95ifrhphhQdZdRwDWJRO3pA0sawpw9HYDWq5StG4HjLOidgXlcKJkNSzBwStknsyvWx@HztMLKw6NTVKAQFydOZmD8m1SodSTlPqbIn54t1OBIpvK5ElFE5ryuhTv9nIRYzEV@Ke9tTftSeD4GXHW5WomtF9NcdGbudk9lGV6H59rILxv4pS@j61jKgZe4wD4r6FyeEwebw6a6L@oy/kX) ``` s->{ // Method with String parameter and no return-type for(String x:s.split(" ")) // Loop over the input split by spaces: System.out.print( // Print: (char) // Each character Long.parseLong( // after we've converted each binary-String to a long x.replace("Fizz","0").replace("Buzz","1") // after we've replaced the Fizz/Buzz to 0/1 ,2)); } // End of method ``` [Answer] # [J](http://jsoftware.com/), 20 bytes ``` a.{~_8#.\2-.~'FB'i.] ``` [Try it online!](https://tio.run/##y/r/P81WTyFRr7ou3kJZL8ZIV69O3c1JPVMv9n9qcka@Qpq6W2ZVlVMpBMPYIBqGFfApALEVkDnIOmFi6v8B "J – Try It Online") ]
[Question] [ The sum of the squares of the first ten natural numbers is, \$1^2 + 2^2 + \dots + 10^2 = 385\$ The square of the sum of the first ten natural numbers is, \$(1 + 2 + ... + 10)^2 = 55^2 = 3025\$ Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is \$3025 − 385 = 2640\$ For a given input n, find the difference between the sum of the squares of the first n natural numbers and the square of the sum. Test cases ``` 1 => 0 2 => 4 3 => 22 10 => 2640 24 => 85100 100 => 25164150 ``` This challenge was first announced at [Project Euler #6](https://projecteuler.net/problem=6). ### Winning Criteria * There are no rules about what should be the behavior with negative or zero input. * The shortest answer wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḋ²ḋṖ ``` **[Try it online!](https://tio.run/##y0rNyan8///hjq5Dmx7u6H64c9r///8NDQwA "Jelly – Try It Online")** ### How? Implements \$\sum\_{i=2}^n{(i^2(i-1))}\$... ``` Ḋ²ḋṖ - Link: non-negative integer, n Ḋ - dequeue (implicit range) [2,3,4,5,...,n] ² - square (vectorises) [4,9,16,25,...,n*n] Ṗ - pop (implicit range) [1,2,3,4,...,n-1] ḋ - dot product 4*1+9*2+16*3+25*4+...+n*n*(n-1) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~28~~ 27 bytes -1 thanks to xnor ``` lambda n:(n**3-n)*(n/4+1/6) ``` **[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPSiNPS8tYN09TSyNP30TbUN9M839afpFCSWpxiUJmnoKGoY6RjrGOoYGOkQmQNNC04lIAgoKizLwSDZAiHQV1XTt1HYU0ME9T8z8A "Python 3 – Try It Online")** Implements \$n(n-1)(n+1)(3n+2)/12\$ --- Python 2, ~~29~~ 28 bytes: [`lambda n:(n**3-n)*(3*n+2)/12`](https://tio.run/##HYpBCoAgEADvvWJvqW2U2kmol3QxShJqDfPS682aw8DAXE/aA6nsxjkf9lxWC2QYCaFb4oJpQY3inSxDiJC2O4EnYBIVapQ9qqG456aCwhU9pX9CqNupRnDsK55f "Python 2 – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 bytes ``` 1⊥⍳×⍳×1-⍨⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/BR19JHvZsPTwcThrqPelcAWf/THrVNeNTb96hvqqf/o67mQ@uNH7VNBPKCg5yBZIiHZ/D/NAUjrjQFYyA2NAAA "APL (Dyalog Unicode) – Try It Online") ### How it works ``` 1⊥⍳×⍳×1-⍨⍳ ⍳×⍳×1-⍨⍳ Compute (x^3 - x^2) for 1..n 1⊥ Sum ``` Uses the fact that "square of sum" is equal to "sum of cubes". [Answer] # TI-Basic (TI-83 series), ~~12~~ 11 bytes ``` sum(Ans² nCr 2/{2,3Ans ``` Implements \$\binom{n^2}{2}(\frac12 + \frac1{3n})\$. Takes input in `Ans`: for example, run `10:prgmX` to compute the result for input `10`. [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), ~~74~~ ~~72~~ ~~68~~ 64 bytes ``` ((([{}])){({}())}{})([{({}())({})}{}]{(({}())){({})({}())}{}}{}) ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v9fQ0Mjuro2VlOzWqO6VkNTs7a6VhMoAuEASZBAbLUGhA9WpAlXCFL7//9/QwMA "Brain-Flak (BrainHack) – Try It Online") Pretty simple way of doing it with a couple of tricky shifts. Hopefully someone will find some more tricks to make this even shorter. [Answer] # Japt `-x`, ~~9~~ ~~8~~ ~~5~~ 4 bytes ``` õ²í* ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=9bLtKg==&input=MjQKLXg=) --- ## Explanation ``` õ :Range [1,input] ² :Square each í :Interleave with 0-based indices * :Reduce each pair by multiplication :Implicit output of the sum of the resulting array ``` [Answer] # JavaScript, 20 bytes ``` f=n=>n&&n*n*--n+f(n) ``` [Try it online](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i5PTS1PK09LVzdPO00jT/N/cn5ecX5Oql5OfrpGmoaRiabmfwA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~12~~ 10 bytes ``` IΣEN×ιX⊕ι² ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUDDMy@5KDU3Na8kNQXILigt8SvNTUot0tDU1FHwzcwrLdYIyC8H8jN1FIyBQnCOkSYYWP//b2jwX7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: \$ ( \sum\_1^n x )^2 = \sum\_1^n x^3 \$ so \$ ( \sum\_1^n x )^2 - \sum\_1^n x^2 = \sum\_1^n (x^3 - x^2) = \sum\_1^n (x - 1)x^2 = \sum\_0^{n-1} x(x + 1)^2 \$. ``` N Input number E Map over implicit range i.e. 0 .. n - 1 ι Current value ⊕ Incremented ² Literal 2 X Power ι Current value × Multiply Σ Sum I Cast to string Implicitly print ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 22 bytes ``` {sum (1..$_)>>²Z*^$_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv7q4NFdBw1BPTyVe087u0KYorTiV@Nr/xYmVCmkKhtZcEIYRjGEMYxgawOVMEGIG1v8B "Perl 6 – Try It Online") Uses the construction \$ \sum\_{i=1}^n {(i^2(i-1))} \$ [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 16 bytes ``` ?dd3^r-r3*2+*C/p ``` Implements \$(n^3-n)(3n+2)/12\$ [Try it online!](https://tio.run/##S0n@/98@JcU4rki3yFjLSFvLWb/g/39DAwA "dc – Try It Online") [Answer] # APL(Dyalog), 17 bytes ``` {+/(¯1↓⍵)×1↓×⍨⍵}⍳ ``` (Much longer) Port of Jonathan Allan's Jelly answer. [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1pbX@PQesNHbZMf9W7VPDwdxDo8/VHvCiC39lHv5v9pj9omPOrte9Q31dP/UVfzofXGj9omAnnBQc5AMsTDM/h/moIRV5qCMRAbGgAA) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 16 bytes ``` ((×⍨+/)-(+/×⍨))⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X0Pj8PRHvSu09TV1NbT1wWxNzUe9m/@nPWqb8Ki371HfVE//R13Nh9YbP2qbCOQFBzkDyRAPz@D/aQpGXGkKxkBsaAAA "APL (Dyalog Unicode) – Try It Online") ``` (×⍨+/) The square (× self) of the sum (+ fold) - minus (+/×⍨) the sum of the square ( )⍳ of [1, 2, … input]. ``` [Answer] # Mathematica, ~~21~~ 17 bytes *-4 bytes thanks to [alephalpha](https://codegolf.stackexchange.com/users/9288).* ``` (3#+2)(#^3-#)/12& ``` Pure function. Takes an integer as input and returns an integer as output. Just implements the polynomial, since `Sum`s, `Range`s, `Tr`s, etc. take up a lot of bytes. [Answer] # [Java (JDK)](http://jdk.java.net/), 23 bytes ``` n->(3*n+2)*(n*n*n-n)/12 ``` [Try it online!](https://tio.run/##NY5Na8MwDIbv@RWiELAzx2vSnlo62HGHsUPZaezgJXFxlsjGVgqh5LdnTsIQQl/PK6lVd5W39e9semc9QRtrOZDppB6wImNRZuek6lQI8K4MwiMBcMNPZyoIpCiGuzU19HHGruQN3r6@Qflb4CsK8Ib0icqPH67xiqwHfZkxf2GHDJ9KnjHMouXIn4tyPq8KgxR3UBMowAUehYBSwEFAsY/ZcYn7aSO19SzSK3vaFP9nAa5joKaXdiDp4l@k2S491idI6xR3YoEFaKmc68bXEL9kS4vzbfOULD7Nfw "Java (JDK) – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 6 bytes ``` {î²ï*+ ``` [Try it online!](https://tio.run/##y00syUjPz0n7/7/68LpDmw6v19L@/9@Qy4jLmMvQgMvIBEgaAAA "MathGolf – Try It Online") Calculates \$\sum\_{k=1}^n (k^2(k-1))\$ ### Explanation: ``` { Loop (implicit) input times î² 1-index of loop squared * Multiplied by ï The 0-index of the loop + And add to the running total ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` ÝDOnsnO- ``` Explanation: ``` ÝDOnsnO- //Full program Ý //Push [0..a] where a is implicit input D //Duplicate top of stack On //Push sum, then square it s //Swap top two elements of stack nO //Square each element, then push sum - //Difference (implicitly printed) ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8FwX/7ziPH/d//8NDQA "05AB1E – Try It Online") [Answer] ## C, C++, ~~46~~ ~~40~~ 37 bytes ( #define ), ~~50~~ ~~47~~ 46 bytes ( function ) -1 byte thanks to Zacharý -11 bytes thanks to ceilingcat Macro version : ``` #define F(n)n*n*~n*~n/4+n*~n*(n-~n)/6 ``` Function version : ``` int f(int n){return~n*n*n*~n/4+n*~n*(n-~n)/6;} ``` Thoses lines are based on thoses 2 formulas : Sum of numbers between 1 and n = `n*(n+1)/2` Sum of squares between 1 and n = `n*(n+1)*(2n+1)/6` So the formula to get the answer is simply `(n*(n+1)/2) * (n*(n+1)/2) - n*(n+1)*(2n+1)/6` And now to "optimize" the byte count, we break parenthesis and move stuff around, **while testing it always gives the same result** `(n*(n+1)/2) * (n*(n+1)/2) - n*(n+1)*(2n+1)/6` => `n*(n+1)/2*n*(n+1)/2 - n*(n+1)*(2n+1)/6` => `n*(n+1)*n*(n+1)/4 - n*(n+1)*(2n+1)/6` Notice the pattern `p = n*n+1 = n*n+n`, so in the function, we declare another variable `int p = n*n+n` and it gives : `p*p/4 - p*(2n+1)/6` For `p*(p/4-(2*n+1)/6)` and so `n*(n+1)*(n*(n+1)/4 - (2n+1)/6)`, it works half the time only, and I suspect integer division to be the cause ( `f(3)` giving 24 instead of 22, `f(24)` giving 85200 instead of 85100, so we can't factorize the macro's formula that way, even if mathematically it is the same. Both the macro and function version are here because of macro substitution : F(3) gives `3*3*(3+1)*(3+1)/4-3*(3+1)*(2*3+1)/6 = 22` F(5-2) gives `5-2*5-2*(5-2+1)*(5-2+1)/4-5-2*(5-2+1)*(2*5-2+1)/6 = -30` and mess up with the operator precedence. the function version does not have this problem [Answer] # JavaScript (ES6), 22 bytes ``` n=>n*~-n*-~n*(n/4+1/6) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i5Pq043T0u3Lk9LI0/fRNtQ30zzf3J@XnF@TqpeTn66RpqGoaYmF6qIEYaIMYaIoQGmNhMsqoDK/gMA "JavaScript (Node.js) – Try It Online") [Answer] # Pyth, 7 bytes ``` sm**hdh ``` Try it online [here](https://pyth.herokuapp.com/?code=sm%2A%2Ahdh&input=10&debug=0). Uses the formula in [Neil's answer](https://codegolf.stackexchange.com/a/175268/41020). ``` sm**hdhddQ Implicit: Q=eval(input()) Trailing ddQ inferred m Q Map [0-Q) as d, using: hd Increment d * hd Multiply the above with another copy * d Multiply the above by d s Sum, implicit print ``` [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~70~~ 69 bytes ``` N =INPUT I X =X + N ^ 3 - N ^ 2 N =GT(N) N - 1 :S(I) OUTPUT =X END ``` [Try it online!](https://tio.run/##K87LT8rPMfn/X8FPwdbTLyA0hMtTIULBNkJBGygSp2CsoAumjbhACtxDNPw0gQxdBUMFq2ANT00uBf/QEKAmoAYuVz@X//8NDQA "SNOBOL4 (CSNOBOL4) – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 21 bytes ``` n->(3*n+2)*(n^3-n)/12 ``` [Try it online!](https://tio.run/##FcdLCoAwDEXRrTw6ajTFfpzqRkTBSUWQEIoTVx91dM/VvZ3hUKuYYBJmXzrpM3VethKEhpRtV70eLwgztJ1yf3T/OFQvRIwlMTKjMFL8NP6NK9kL "Pari/GP – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` LnDƶαO ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fJ8/l2LZzG/3//zc0MAAA "05AB1E – Try It Online") **Explanation** ``` L # push range [1 ... input] n # square each D # duplicate ƶ # lift, multiply each by its 1-based index α # element-wise absolute difference O # sum ``` Some other versions at the same byte count: `L<ān*O` `Ln.āPO` `L¦nā*O` [Answer] # [R](https://www.r-project.org/), 28 bytes ``` x=1:scan();sum(x)^2-sum(x^2) ``` [Try it online!](https://tio.run/##K/r/v8LW0Ko4OTFPQ9O6uDRXo0IzzkgXzIgz0vxvaGDw/z8A "R – Try It Online") [Answer] # [Clojure](https://clojure.org/), 58 bytes ``` (fn[s](-(Math/pow(reduce + s)2)(reduce +(map #(* % %)s)))) ``` [Try it online!](https://tio.run/##S87JzyotSv3/XyMtL7o4VkNXwzexJEO/IL9coyg1pTQ5VUFboVjTSBPO08hNLFBQ1tBSUFVQ1SzWBIL//wE "Clojure – Try It Online") --- ## Edit: I misunderstood the question # [Clojure](https://clojure.org/), 55, 35 bytes ``` #(* %(+ 1 %)(- % 1)(+(* 3 %)2)1/12) ``` [Try it online!](https://tio.run/##jYwxDsIwEAR7XrESsnRHhJCdki9Q8AUTziLInCHYSLzeOKU7yt2Z3Smme1mk1i3tYGiAhWHaw8AyDa0bW3ZsD9ZxpasEBPyhMo44SW6yvIqPyDeB16TfRypvhKJTnpPCX9JHNvRcZs1RQaFdrdPzWiCQ5Q66Droejh0cuf4A "Clojure – Try It Online") [Answer] # [cQuents](https://github.com/stestoltz/cQuents/tree/cquents-0), ~~17~~ 15 bytes ``` b$)^2-c$ ;$ ;$$ ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/P0lFM85IN1mFyxqEVP7/NzQAAA "cQuents – Try It Online") ## Explanation ``` b$)^2-c$ First line : Implicit (output nth term in sequence) b$) Each term in the sequence equals the second line at the current index ^2 squared -c$ minus the third line at the current index ;$ Second line - sum of integers up to n ;$$ Third line - sum of squares up to n ``` [Answer] # MATLAB/Octave, 21 bytes ``` @(x)(x^3-x)*(x/4+1/6) ``` Anonymous function. We could save another 4 bytes if we assume `x` can be given as variable in workspace. Implements \$n(n−1)(n+1)(3n+2)/12\$ --- One of my approaches was `@(x)-sum([sum(1:x)*i,1:x].^2)` which is few bytes longer but I found it interesting because It used imaginary unit to change the sign. I also found out I can generate sum of squares by multiplying normal and transposed vector with `(1:x)*(1:x)'`. Might be useful for future challenges! [Answer] # [Labyrinth](https://github.com/m-ender/labyrinth), 20 bytes ``` ?(:):):_3*(***_12/!@ ``` [Try it online!](https://tio.run/##y0lMqizKzCvJ@P/fXsNKEwjjjbU0tLS04g2N9BUd/v83NDAAAA "Labyrinth – Try It Online") Straightforward closed-form formula of \$(x-1)x(x+1)(3x+2)/12\$. ``` ? Take input [x] (:):) Decrement, dup, increment, dup, increment [x-1 x x+1] :_3*( Dup, 3 times, decrement [x-1 x x+1 3x+2] *** Multiply four values _12/ Divide by 12 !@ Print it and halt ``` # [Labyrinth](https://github.com/m-ender/labyrinth), 21 bytes ``` ? ::(";;;!@ { : +**} ``` [Try it online!](https://tio.run/##y0lMqizKzCvJ@P/fnsvKSkPJ2tpa0YGrWkHBiktbS6v2/39DAwMA "Labyrinth – Try It Online") # [Labyrinth](https://github.com/m-ender/labyrinth), 22 bytes ``` ? :(:: } " **+{;!@ ``` [Try it online!](https://tio.run/##y0lMqizKzCvJ@P9fQUHBnstKw8qKq1ZBQYlLS0u72lrR4f9/QwMDAA "Labyrinth – Try It Online") Two versions using a loop to evaluate \$\sum\_{i=1}^{x}{i^2(i-1)}\$. Both versions test the loop exit with `i-1 == 0`, discard the top values `;` as necessary, print the sum and exit. ``` ? Take input [x]; enter loop [sum i] with initial values of sum=0, i=x ::( Dup, dup, decrement [sum i i i-1] :} Dup and move i-1 to aux. store [sum i i i-1 | i-1] **+ Multiply top three values and add to sum [sum' | i-1] { Move i-1 back to the main stack Loop exit test can be done anywhere in the last iteration (i==1 or i==0), since that iteration does not affect the sum. ``` [Answer] # ARM (Thumb), 18 bytes ``` .section .text .global func .thumb // int func(int dummy, int x) // returns sum(i*i*(i-1) for i in 1..x) // r1 = i (x->1), r2 = i*i*(i-1), r0 = sum func: mov r0, #0 // 2000 int sum = 0; mov r2, #0 // 2200 int prod = 0; .loop: // do { add r0, r0, r2 // 1880 sum += prod; mov r2, r1 // 1c0a prod = x; mul r2, r1 // 434a prod *= x; sub r1, #1 // 3901 x -= 1; mul r2, r1 // 434a prod *= x; bne .loop // d1f9 } while (prod != 0); bx lr // 4770 return sum; ``` A function that takes the input integer via `r1` and returns the value via `r0`. Uses the iterative formula \$\sum\_{i=1}^{x}{i^2(i-1)}\$, iterating backwards. The loop terminates when the value of \$i^2(i-1)\$ is 0. For the purposes of writing test cases, the C-side function signature takes a dummy value for `r0`. Test cases written in C: ``` #include <stdio.h> int func(int dummy, int x); int main(void) { int dummy; int inputs[] = {1, 2, 3, 10, 24, 100}; for(int i = 0; i < 6; ++i) { int v = inputs[i]; printf("input = %d -> ans = %d\n", v, func(dummy, v)); } return 0; } ``` Build, run, objdump commands: ``` arm-linux-gnueabihf-gcc main_c.c func_c.S -static -o main_c qemu-arm -L /usr/arm-linux-gnueabihf ./main_c arm-linux-gnueabihf-objdump -d main_c | awk -v RS= '/^[[:xdigit:]]+ <(func|.loop)>/' ``` (The objdump + awk trick comes from [this SO answer](https://stackoverflow.com/a/31138400).) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` ɾ∑²⁰ɾ²∑- ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwiyb7iiJHCsuKBsMm+wrLiiJEtIiwiIiwiMyJd) literal solution, squares the sum and subtracts the sum of the squares. [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 32 bytes ``` [ [1,b] 3 dupn Σ sq -rot v. - ] ``` [Try it online!](https://tio.run/##JcwxDoJAFIThnlPMAYQAWukBjI2NsSIU6/LEjfB22X2QqPE03scrrRiaKb5J/qvSYn08nw7H/Ra9klvmFbcUcCfP1C00stG2IbTE5FVnnkqM5bCcE/0TAYGGkVjTwnCeRB7OGxbskuSFAiXWKHKUm3lzvJNYoSpWl3rmZnSM7wdhQOqtYMqQoo69csjiDw "Factor – Try It Online") ``` word | data stack | comment -------+------------------------------------------------+-------------- | 10 | example input [1,b] | { 1 2 ... 10 } | 3 | { 1 2 ... 10 } 3 | dupn | { 1 2 ... 10 } { 1 2 ... 10 } { 1 2 ... 10 } | Σ | { 1 2 ... 10 } { 1 2 ... 10 } 55 | sum sq | { 1 2 ... 10 } { 1 2 ... 10 } 3025 | square -rot | 3025 { 1 2 ... 10 } { 1 2 ... 10 } | v. | 3025 385 | dot product - | 2640 | output ``` ]
[Question] [ There are two forms of nouns, singular and plural. The conversion between these two is quite easy. 1. Normally, you end it with `s`. ex. `car` => `cars`. 2. If it ends with `s`,`x`,`z`,`ch` or `sh`, end it with `es`. ex. `bus`=>`buses`. 3. If it ends with `y` with a consonant just before it, change the `y` to `ies`. ex. `penny` => `pennies`. 4. If it ends with `f` or `fe`, change it to `ves`. ex. `knife` => `knives`. 5. If it ends with `o` with a consonant just before it, change it to `oes`. ex.`potato` => `potatoes`. --- # Task You will be given a singular noun. You have to convert the given noun to plural and output it. --- # Rules * You will not be given irregular nouns, like `mouse` and `moose`. * You will not be given exceptions, such as `safe` (`safes`; violating #4), `piano` (`pianos`; violating #5) and `o` (`oes`, violating #5). * You will not be given words which have two or more possible plural forms, such as `mosquito` (`mosquitos` or `mosquitoes`) and `roof` (`roofs` or `rooves`). * You will not be given uncountable nouns. * `y` doesn't count as a vowel. --- # Examples ``` car => cars bus => buses potato => potatoes knife => knives penny => pennies exception => exceptions wolf => wolves eye => eyes decoy => decoys radio => radios ``` [Answer] # Mathematica, 9 bytes ``` Pluralize ``` Yes, there is a built-in for this! **Sample output** ``` Pluralize["car"] ``` > > `cars` > > > ``` Pluralize /@ {"bus", "potato", "knife", "penny", "exception", "wolf", "eye"} ``` > > `{"buses", "potatoes", "knives", "pennies", "exceptions", "wolves", "eyes"}` > > > [Answer] # [Retina](https://github.com/m-ender/retina), ~~57~~ ~~53~~ ~~56~~ ~~55~~ ~~58~~ 57 bytes *Thanks to MartinEnder for some golfing suggestions* *Thanks to BusinessCat for golfing 1 byte* ``` ([^aeiou]o|sh?|ch|z|x)$ $1e fe?$ ve ([^aeiou])y$ $1ie $ s ``` [Try it online!](https://tio.run/nexus/retina#PcoxDsIwEETRfs5hpKTkBCk5BAJhNhPZirRrYQfFke9uoKH41fun4fLow/XuGW27WcthahLa0fbRwZ2JhZPDm/g/Y/1BJBxy7@JfeG4Zs@nKilXjQiQrvhgSVSu4C1OJpmAl5m9iXsIH "Retina – TIO Nexus") ### Explanation (outdated) ``` ([^aeiou])y$ $1ie ``` Changes `{consonant}y` to `{consonant}ie` ``` ([^aeiou]o|[fxzs]|[sc]h)$ $&e ``` Appends an `e` to when the word ends with an `{consonant}o`, `f`,`x`,`z`,`s`,`sh` or `ch`. ``` fe$ ve ``` Changes an ending `fe` to `ve` ``` $ s ``` Finally append an `s` to the word. ### Edits * Added bytes because I forgot the second rule * Added bytes to update with `eye` as an example [Answer] # JavaScript (ES6), ~~109~~ 97 bytes ``` s=>s[R='replace'](/([^aeiou])y$/,'$1ie')[R](/fe?$/,'ve')[R](/([^aeiou]o|[sxz]|[cs]h)$/,'$1e')+'s' ``` [Try it online!](https://tio.run/##bdDRbsIgFIDhe5@iMSaUzK3x2tS9g7ekSxg9KNpwmp5a7eK7dyhbNT1yx88HAQ6602QaV7fvHksYbD5QviG1zUUDdaUNiCLNUvWlweGpkP0iW4rFyoGQahtWLHzeSvc/HyVeFV1@iqsyVOxl3BXQmyAxGPSEFXxUuEttOje6mUu5Tv5GliX5JgmRZhP4fSIOQwQma2x1iyOOMkaOj95ZeBwccYjdi3PB@35Kb9FxCxcDdevQRx/tGBk/Y2WfXhd5iC9uAT3wfwiRwRIMsuveI6ONLh1O6T3S8As "JavaScript (Node.js) – Try It Online") [Answer] ## Batch, 325 bytes ``` @set/ps= @for %%v in (a e i o u)do @( for %%e in (o y)do @if %s:~-2%==%%v%%e goto s if %s:~-2%==%%vf set s=%s:~,-1%ve&goto s if %s:~-3%==%%vfe set s=%s:~,-2%ve&goto s ) @if %s:~-1%==y set s=%s:~,-1%ie @for %%e in (o s x z)do @if %s:~-1%==%%e set s=%s%e @for %%e in (c s)do @if %s:~-2%==%%eh set s=%s%e :s @echo %s%s ``` [Answer] # Haskell, 216 207 205 bytes Thanks to @Lynn, @user1472751 and @Laikoni for the help! ``` import Data.List (!)s=or.map(\x->x`isSuffixOf`s) c=['b'..'z']\\"eiou" p s|s!(words"s x z ch sh"++map(:"o")c)=s++"es"|s!map(:"y")c=init s++"ies"|s!["f"]=init s++"ves"|s!["fe"]=(init.init)s++"ves"|0<1=s++"s" ``` ## Readable ``` import Data.List; endsWithOneOf :: String -> [String] -> Bool endsWithOneOf str ends = (or . map (\end -> end `isSuffixOf` str)) ends consonants :: [Char] consonants = ['a'..'z'] \\ "aeiou" pluralize :: String -> String pluralize str | str `endsWithOneOf` (words "s x z ch sh" ++ (map (:"o") consonants)) = str ++ "es" | str `endsWithOneOf` (map (:"y") consonants) = init str ++ "ies" | str `endsWithOneOf` ["f"] = init str ++ "ves" | str `endsWithOneOf` ["fe"] = (init.init) str ++ "ves" | otherwise = str ++ "s" ``` ## Explanation `import Data.List` for the function `isSuffixOf`. `endsWithOneOf` (`€` in the golfed version) returns whether one of the list elements is an ending of the string. `consonants(c)` is just a list of all consonants. Finally, `pluralize(p)` checks for the endings and returns the proper pluralization. Example: ``` p "potato" == "potatoes" ``` [Answer] # Perl, 66 + 2 (`-pl` flag) = 68 bytes ``` $_.=/(ch|sh?|x|z|[^aeiou]o)$/+s/([^aeiou])y$/$1i/+s/fe?$/v/?es:"s" ``` Using: ``` perl -ple '$_.=/(ch|sh?|x|z|[^aeiou]o)$/+s/([^aeiou])y$/$1i/+s/fe?$/v/?es:"s"' <<< car ``` [Try it on Ideone.](http://ideone.com/LIMaEo) [Answer] # [Röda](https://github.com/fergusq/roda), 80 bytes ``` f&s{s~="([^aeiou])y$","$1ie","([sxz]|[cs]h|[^aeiuo]o)$","$1e","fe?$","ve"s.="s"} ``` The function modifies its argument. Usage: `main word { f word; print word }` Here's a version that uses a return value (83 bytes): ``` f s{s~="([^aeiou])y$","$1ie","([sxz]|[cs]h|[^aeiuo]o)$","$1e","fe?$","ve";[s.."s"]} ``` And below is a function that reads infinitely many values from the input stream and pushes plural forms to the output stream (~~87~~ 83 bytes): ``` {replace"([^aeiou])y$","$1ie","([sxz]|[cs]h|[^aeiuo]o)$","$1e","fe?$","ve","$","s"} ``` It's an anonymous function, as that is shorter than creating a named function. [Answer] # PHP, ~~103~~ 100 bytes ``` <?=preg_replace(['/([^aeiou]o|sh?|x|z|ch)$/','/(?<![aeiou])y$/','/fe?$/'],['\1e',ie,ve],$argv[1]).s; ``` [Try it online!](https://tio.run/nexus/php#JclbCoAgEEDRtQSBCUPRd4YLmSwkJhUCxR5UuHcL@rvck4XsQyQzRQqrnqlC1lQ4anL@UD5tVqYrPWm2vGwYfCZFgb/y@18LyS8UIBtaYuAITlJQ6mhObBWvty7nHPyud/8C "PHP – TIO Nexus") The `preg_replace` function takes in an array of patterns and replacements. * Saved 2 bytes thanks to Titus. * Saved 1 byte thanks to Dewi Morgan. [Answer] # Python 3, ~~271~~ ~~239~~ 199 bytes Thanks to @ovs for reducing it by 72 bytes! ``` lambda s,v="aeiou":(s[-2:]=="fe"and s[:-2]+"ve"or s[:-1]+((s[-1]=="y"and s[-2]not in v)*"ie"or s[-1]=="f"and"ve"or s[-1]+((s[-1]in"sxz"or s[-2:]in["ch","sh"])+(s[-1]=="o"and s[-2]not in v))*"e"))+"s" ``` [Try it online!](https://tio.run/nexus/python3#bY/BbsIwDIbP21NE/ylZyyQ4Viov0uUQ2kRYg7hqQkdBPHtJugrtsJPtX5/9ya7@mk/mfOiMCOVYw1jiCyoZms2u0nUNZ2F8J0JTbXa6wGjBwzJtdSEzts3UtEKJ8RwFeTGqD9AK/zIuM68Df/bJI1xva5ys5Bu0R5QIR2hVvCT8jyRZLJQqEDC7dIFynNbNgFLgcAm59BxN5Nx9e0oP5ch6P@XGXlvbR2Kfhx8@uSWcFqizLS/QYDpi6Or9rR/IR4n7Q9R7cX/gM0nPJkoqnSSl1PwE "Python 3 – TIO Nexus") [Answer] # [Python 3](https://docs.python.org/3/), ~~131~~ ~~125~~ ~~118~~ 121 bytes *Thanks to [The Thonnu](https://codegolf.stackexchange.com/users/114446/the-thonnu) for -6 bytes! Golfed 7 bytes! Fixed an issue for +3 bytes!* ``` lambda x:S("([sc]h?|x|z)$","\\1e",S(V+"y$","ie",S("fe?$","ve",S(V+"o$","oe",x))))+"s" import re;S,V=re.sub,"(?<![aeiou])" ``` [Try it online!](https://tio.run/##NclBTsMwEEDRPacYRixs1VRC7Aohh4jUTdOFk4zVUVOPZTskRr17aJD4u6cfSr6If19d1a6jvXWDheXQKFSn1J8v9X25/@gXNNi2b4SmUccdls38J3RUb/r@f7JJHlr0ox0mfOJbkJgh0kdjjlWkfZo6g6r@fD5ZYpnOGlcnEWZgD9jbCN2UIEi2WeDq2REE8r4ALT2FzOJhltEBFYKBeikQ7cCC@xRGzkofQmSf1WycmrVJFCqE1y9Avf4C "Python 3 – Try It Online") My first submission on here! Let me know if I did anything wrong. [Answer] # sed, 70 ~~79~~ bytes 69 ~~78~~ + 1 for `-E` (BSD)/`-r` (GNU) flag ``` s/([^aeiou])y$/\1ie/ s/([^aeiou]o|[fxzs]|[sc]h)$/&e/ s/fe/ve/ s/$/s/ ``` Direct port of the [retina answer](https://codegolf.stackexchange.com/a/112080/). [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~63~~ 61 bytes ``` Y`[^aeiou]`OaR[C`sh?|x|z|ch`Cy.'y`fe?`y.'o].'$[_B.'i'v_].'e's ``` *So close* to catching Retina! But it's probably not going to happen. :( [Try it online!](https://tio.run/nexus/pip#JYpBDoIwFET3nqIhJtUNVyCRxK3GnWmQfsuvNGJLoChFPDv@hs28mZc5gkgUdAlL7kO/Zk3QZpoIHkbKZrAqyhc8jFqtIbTOg3dUntZojAKtDUQcFbbeOEv94xodVYiHCpWLhw4q45Jiw85s912uUtwAjRsKeYKLyGVfZ/M4T7OqZR5SHqTGTFJxRcq3ojyk3PB3SQN5v7Afg/3yBw "Pip – TIO Nexus") ### Explanation Basic strategy: `R`eplace performs several replacements one after the other when given lists of patterns and replacements. We want to make the following replacements: * `(sh?|x|z|ch)$` -> add an `e` * `[^aeiou]y` -> change the `y` to `i` and add an `e` * `fe?` -> change to `v` and add an `e` * `[^aeiou]o` -> add an `e` Then we want to tack on an `s` regardless. Tricks: * The `C` operator, given a regex, wraps it in a capturing group; `C`xyz`` is one byte shorter than ``(xyz)``. * A list of regexes or replacements that all end with the same character can be created by concatenating the character to the list instead of including it in all the items. Concatenating a Scalar (string) to a Pattern (regex/replacement) coerces to a Pattern. * Instead of concatenating the `s` (and having to deal with the precedence ordering of `R` and `.`), we can simply `O`utput the main part of the word and then print the `s` separately. Spaced and commented code: ``` a is 1st cmdline input (implicit) Y`[^aeiou]` Yank the consonant regex into the y variable O a R Output (without newline): a, with the following replacements: [ List of regexes to replace: C `sh?|x|z|ch` (sh?|x|z|ch) Cy . 'y ([^aeiou])y `fe?` fe? y . 'o [^aeiou]o ] . '$ End of list; concatenate $ to each item [ List of replacements: _ Identity function (replace with whole match) B B is short for {b}, a function returning its second argument; as a callback function for regex replacement, the second argument is the value of capturing group 1 (the consonant before y) . 'i To that, concatenate i 'v Scalar literal v _ Identity function ] . 'e End of list; concatenate e to each item 's Return Scalar literal s, which is autoprinted ``` [Answer] ## C#, ~~73~~ 163 bytes: ``` Func<string,string>p=System.Data.Entity.Design.PluralizationServices.PluralizationService.CreateService(System.Globalization.CultureInfo.CurrentCulture).Pluralize ``` Yes, another language with it built-in (although you need to add a reference to `System.Data.Entity.Design.dll`) To use: ``` var words = new[] { "car", "bus", "potato", "knife", "penny", "exception", "wolf", "eye", "decoy", "radio" }; foreach (var word in words) { var plural = p(word); Console.Out.WriteLine($"{word} => {plural}"); } ``` Output: > > > ``` > car => cars > bus => buses > potato => potatoes > knife => knives > penny => pennies > exception => exceptions > wolf => wolves > eye => eyes > decoy => decoys > radio => radios > > ``` > > [Answer] # Python ~~199~~ ~~187~~ 176 Bytes ``` lambda s:s+'\bve'*(s[-1]=='f')+'\b\bve'*(s[-2:]=='fe')+'e'*(s[-1]in'sxz'or s[-2:]in('ch','sh')or s[-1]=='o'and s[-2]not in'aiueo')+'\bie'*(s[-1]=='y'and s[-2]not in'aiueo')+'s' ``` [Answer] ## Rails runner, 18 bytes ``` $><<gets.pluralize ``` Example: ``` $ echo knife | rails r filename.rb knives ``` [Answer] **Python,** **296** **bytes** ``` z = input() if z[-1]in['s','x','z','ch','sh']:print(z+'es') elif z[-1]=='y'and z[-2]not in['a','e','i','o','u']:print(z[:-1]+'ies') elif z[-2:]=='fe':print(z[:-2]+'ves') elif z[-1]=='f':print(z[:-1]+'ves') elif z[-1]=='o'and z[-2]not in['a','e','i','o','u']:print(z[:-1]+'oes') else:print(z+'s') ``` [Answer] # [Lexurgy](https://www.lexurgy.com/sc), 102 bytes ``` Class v {a,e,i,o,u} p: *=>es/{s,x,z,ch,zh,!@v o} _ $ y=>ies/!@v _ $ f e?=>ves/_ $ Else: *=>s/_ $ ``` Ungolfed explanation: ``` # define vowels Class vowel {a,e,i,o,u} plural: *=>es/{s,x,z,ch,zh,!@vowel o} _ $ # 2,5 y=>ies/!@vowel _ $ # 3 {f,fe}=>ves/_ $ # 4 Else: # Run the rules below if the above rules don't apply *=>s/_ $ # 1 ``` [Answer] ## Java 7, 408 bytes **Golfed:** ``` boolean b="bcdfghjklmnpqrstvwxyzs".contains(String.valueOf(s.charAt(s.length()-2))); String x=s.substring(0,s.length()-1);if(s.endsWith("s")||s.endsWith("x")||s.endsWith("z")||s.endsWith("ch")||s.endsWith("sh"))return s+"es";if(s.endsWith("y")&&b)return x+"ies";if(s.endsWith("f")) return x+"ves";if(s.endsWith("fe"))return s.substring(0,s.length()-2)+"ves";if(s.endsWith("o")&&b)return s+"es";return s+="s"; ``` Basically testing what the end of the String is and adding / replacing letters depending on what case it is. The boolean and String at the beginning are just for removing repetition in the test cases and making the code smaller. **Readable version:** ``` public static String pluralize(String s){ // Consonant at the 2nd last position? boolean b = "bcdfghjklmnpqrstvwxyzs".contains(String.valueOf(s.charAt(s.length()-2))); // Substring for cases where last letter needs to be replaced String x = s.substring(0,s.length()-1); if(s.endsWith("s") || s.endsWith("x") || s.endsWith("z") || s.endsWith("ch") || s.endsWith("sh")) return s + "es"; if(s.endsWith("y") && b) return x + "ies"; if(s.endsWith("f")) return x + "ves"; if(s.endsWith("fe")) return s.substring(0,s.length()-2) + "ves"; if(s.endsWith("o") && b) return s + "es"; return s += "s"; } ``` [Answer] Direct port of Retina: # [Ruby](https://www.ruby-lang.org/), 111 bytes ``` 'sub(/([^aeiou])y/){"#{$1}ie"};sub(/(.*)([^aeiou]o|[fxzs]|[sc]h)$/){"#{$1}#{$2}e"};sub(/fe/,"ve");sub(/$/,"s")' ``` [Try it online!](https://tio.run/##KypNqvz/X724NElDXyM6LjE1M780VrNSX7NaSblaxbA2M1Wp1hoiq6elCVeRXxOdVlFVHFsTXZwcm6GpAlcPJIxq4XrSUvV1lMpSlTQhXBUgr1hJU/3/f67///ILSjLz84r/6@YUpAIA "Ruby – Try It Online") Invoke via `ruby -lpe` and supply a file as `input.txt` for first CLI argument. [Answer] # C, 321 bytes ``` #define E else if( #define C unsigned char C*p(C*b){static C r[999],i,w,n,m;for(n=w=i=0;r[i]=b[i];n=w,w=b[i++]);m=!strchr("aeiou",n);if(strchr("sxz",w)||(w=='h'&&strchr("cs",n))||(w=='o'&&m))r[i++]='e';E'y'==w&&m)r[i-1]='i',r[i++]='e';E'f'==w)r[i-1]='v',r[i++]='e';E'f'==n&&w=='e')r[i-2]='v';r[i++]='s';r[i]=0;return r;} ``` test: ``` C*mx[]={"car","bus","potato","knife","penny","exception","wolf","eye","decoy","radio",0}; main() {unsigned i; for(i=0;mx[i];++i) printf("[%s] [%s]\n", mx[i], p(mx[i])); return 0; } ``` results: ``` [car] [cars] [bus] [buses] [potato] [potatoes] [knife] [knives] [penny] [pennies] [exception] [exceptions] [wolf] [wolves] [eye] [eyes] [decoy] [decoys] [radio] [radios] [radio] [radios] ``` ]
[Question] [ # Background When I was younger, I was taught a method of drawing a weird "S" shape, that I (along with my classmates) found fascinating. Today, I rediscovered it, and due to its formulaic approach to drawing it, thought it could lead to an interesting challenge :P # Drawing the "S" The S can be drawn by following these simple steps: First, draw 2 rows of three vertical lines like so ``` | | | | | | ``` Next, connect the top left line with the bottom middle line and the top middle with the bottom right line to produce ``` | | | \ \ | | | ``` Finally, draw a top and bottom on the currently drawn image so that it ends up looking like ``` ^ / \ | | | \ \ | | | \ / v ``` As you can see, this results in an "S" shape. When extended however (drawing it with more than 2 rows), it produces a very interesting pattern. Your task is reproduce this interesting pattern. # Task Given an integer where `n >= 2`, output The S with `n` rows to be made from it. Output may be returned from a function, and input may be taken in standard methods. Trailing/leading whitespace for both the overall image, as well as each line, is fine. However, leading line spaces must be consistent so that the " isn't broken. You may output as a list of lines. # Test cases ``` input output --- 2 ^ / \ | | | \ \ | | | \ / v --- 8 ^ / \ | | | \ \ | | | \ \ | | | \ \ | | | \ \ | | | \ \ | | | \ \ | | | \ \ | | | \ / v --- 10 ^ / \ | | | \ \ | | | \ \ | | | \ \ | | | \ \ | | | \ \ | | | \ \ | | | \ \ | | | \ \ | | | \ \ | | | \ / v ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins! Good luck, [Answer] # [Python 2](https://docs.python.org/2/), 47 bytes ``` lambda k:' ^\n / '+'\\\n| | |\n \ '*k+'/\n v' ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHbSl1BIS4mT0FfQV1bPSYmJq9GAQiBAjEK6lrZ2ur6QKZCmfr/gqLMvBKFNA0Tzf8A "Python 2 – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~73~~ ~~69~~ ~~66~~ ~~64~~ 62 bytes Two less bytes and perl-like appearance thanks to Barodus. Didn't think of using int? for nulls. ``` n=>$@" ^ / {string.Join(@"\ | | | \ ",new int?[++n])}/ v" ``` [Try it online!](https://tio.run/##hY3BCoJAGITv@xSDdFA0hU5BaULQIerUoYMayLbKgv0L7maF@ey24aVbM8f5ZobrOVetGHlTao0n65k2pZEcnZJXHEtJcLVpJdVZgbKttWcRWJ1e2ohbuLsTX0syASYqQYV4pDiZpQ5wYYjQT0m4V5Lc1MnZG9YMOZyAxAO2vcl8nwpviOx054yr34etIq0aEZ5bacRBknArd@F5f5nllxnYMH4A "C# (.NET Core) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 48 ~~56 59 61~~ bytes ``` lambda k:' ^\n / %s/\n v'%('\\\n| | |\n \ '*k) ``` [Try it online!](https://tio.run/##JYjRCgIhFAV/5byI3ghs683oTy4LRmuJdRVXFoL9dxNiHmaY8m2vLJcebtzf/nN/eCSngZkFFmq1w9i0MpqZZcdgHIY@JOohV0REQfXyXMz5OJ3IlRqlmWAi0fXf1H8 "Python 3 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~27~~ 26 bytes ``` …^ /ð"\ | | | \ "I×…/ vJ.c ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcOyOC79wxuUYrhqFICQK0ZByfPwdKCwPleZl17y//9GAA "05AB1E – Try It Online") **Alternate 27 byte version** ``` '^…/ \©IF…| |û…\ \}\®R'v».c ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fPe5RwzJ9hZhDKz3dgKwahZrDu4F0jEJMbcyhdUHqZYd26yX//28EAA "05AB1E – Try It Online") **Explanation** ``` '^ # push "^" …/ \© # push "/ \" and store a copy in register IF # input times do: …| |û # push "| | |" …\ \ # push "\ \" } # end loop \ # discard top of stack (the extra "\ \") ®R # push "/ \" reversed = "\ /" 'v # push "v" » # join stack on newlines .c # center each row ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~34~~ ~~25~~ 23 bytes ``` " ^ /{ç'\²i|³1}/ v"¬¸ò5 ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=IiBeIC975ydcsml8szF9LyB2Iqy48jU=&input=MyAtUg==) Outputs as an array of lines; `-R` flag added to join on newlines. (Thanks @Shaggy) ~~First~~ Second attempt, might be improvable... ### How it works ``` " ^ /{ ç'\² i |³ 1}/ v"¬ ¸ ò5 " ^ /{Uç'\p2 i'|p3 1}/ v"q qS ò5 Ungolfed Implicit: U = input number '\p2 Repeat a backslash twice, giving "\\". i 1 Insert at index 1 '|p3 3 vertical bars. This gives "\|||\". Uç Make U copies of this string. U = 2: "\|||\\|||\" " ^ /{ }/ v" Insert this into this string. " ^ /\|||\\|||\/ v" q qS Split into chars; join on spaces." ^ / \ | | | \ \ | | | \ / v" ò5 Split into rows of length 5. [" ^ "," / \ ","| | |"," \ \ ","| | |"," \ / "," v"] Joining on newlines gives " ^ / \ | | | \ \ | | | \ / v" ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~26~~ ~~25~~ 18 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` °I-‘*"∑ūCƨΩ)¹‘@∑5n ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JUIwSS0ldTIwMTgqJTIyJXUyMjExJXUwMTZCQyV1MDFBOCV1MDNBOSUyOSVCOSV1MjAxOEAldTIyMTE1bg__,inputs=Mw__) Uses the same strategy as [ETHproductions's Japt answer](https://codegolf.stackexchange.com/a/143349/59183) Explanation: ``` ..‘ push "\|||\" * repeat input times "..‘ push " ^ /ŗ/ v ", with ŗ replaced with POP. The reason why there's a trailing space is because otherwise it didn't have enough repeating characters to compress @∑ join with spaces 5n split to line lengths of 5 ``` [Answer] # JavaScript (ES6), 60 bytes ``` n=>` ^ / \\ ${`| | | \\ \\ `.repeat(n-1)}| | | \\ / v` ``` ## Test Snippet ``` let f= n=>` ^ / \\ ${`| | | \\ \\ `.repeat(n-1)}| | | \\ / v` ;(I.oninput=_=>O.innerHTML=I.value+"\n"+f(+I.value))() ``` ``` <input id=I type=range min=2 max=15 value=2><pre id=O></pre> ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~27~~ ~~26~~ 25 bytes *-1 byte thanks to Carlos Alejo. -1 byte thanks to ASCII-only.* ``` ^⸿ / ×\⸿| | |⸿ \ N/⸿ v ``` [Try it online!](https://tio.run/##S85ILErOT8z5/19JQSHu0DYFfQUlLQ2lmJiYohoFIIwpUohRUNLxzCsoLfErzU1KLdLQ1FTSBworlCn9/2/yX7fsv25xDgA "Charcoal – Try It Online") Link is to verbose version. *#charcoal-verbose-obfucation* [Answer] # [C (gcc)](https://gcc.gnu.org/), 82 bytes ``` f(n){for(puts(" ^\n / \\");--n;puts("| | |\n \\ \\"));puts("| | |\n \\ /\n v");} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOi2/SKOgtKRYQ0lBIS4mT0FfISZGSdNaVzfPGiJcowCEQImYGLCMJqawPpBSKANqqv2fm5iZp6HJVc2lAARpGkaa1mAWRIsSlJemYQJk1f4HAA "C (gcc) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), ~~39~~ 37 bytes ``` say" ^ / ".'\ | | | \ 'x<>."/ v" ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJJQSGOS0FfQUlPPYarRgEIuRRiFNQrbOz0lPS5FBTKlP7/NzT4l19QkpmfV/xf19dUz8DQAAA "Perl 5 – Try It Online") *Shaved two bytes with @DomHastings' suggestion* [Answer] # [Actually](https://github.com/Mego/Seriously), 49 bytes ``` "| | |"@α;lD" \ \"@α@Z♂ii" v"" \ /"))" / \"" ^" ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/1@pRgEIlRzObbTOcVFSiFGIAbEdoh7NbMrMVFJQKFMCCeoraWoqKegDJYFCcUr//1sAAA "Actually – Try It Online") Explanation: ``` "| | |"@α;lD" \ \"@α@Z♂ii" v"" \ /"))" / \"" ^" "| | |"@α push a list containing n copies of the vertical lines ;lD" \ \"@α push a list containing n-1 copies of the diagonal connections @Z♂i interleave i flatten " v"" \ /")) make the bottom " / \"" ^" make the top ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 38 bytes ``` …| |ûU" ^ / \"XI<F„ \2×X}" \ / v"» ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcOyGoWaw7tDlRQU4rgU9BVilCI8bdweNcxTiDE6PD2iVkkhRkGfS0GhTOnQ7v//jQE "05AB1E – Try It Online") ``` …| | # Push "| |" û # Palindromize U # Store in X "..."X # Push the top three rows I<F } # One less than input times do: „ \ # Push " \" 2× # Concatenate that with itself X # Push "| | |" "..." # Push the last two rows » # Join stack with newlines ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~101~~ ~~77~~ 73 bytes Saved 24 bytes thanks to **i cri everytim**! Saved 4 bytes thanks to **Kevin Cruijssen**! ``` n=>{var s=" ^\n / ";for(;n-->0;s+="\\\n| | |\n \\ ");return s+"/\n v";} ``` [Try it online!](https://tio.run/##hc0xC8IwEAXgvb/ikalFq@IkxHYRnHRycDAKIaYloBfIxaJof3uNuLh5b3vvgzNcGh/sYC6aGffsmXHU0Rl03p2x1Y6QcwyO2sMROrRcJIJ0uwdHe52sb2SWjuIYX1WjQTVQVT87HcCVAE6KMIWQjQ@5pLKsZ5JHlVBK0QspaVYKopDBxlsg8EhMU4dOyH6Qv89Wnthf7GQfXLQbRzZv8nlR/DWLj@mzfngD "C# (.NET Core) – Try It Online") As per usual, string repeating in C# is a pain. [Answer] ## [Retina](https://github.com/m-ender/retina), 38 bytes ``` .+ $* 1 ¶|||¶x\\ ^ ^¶x/\ .$ /¶ v x? ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYvLkOvQtpqamkPbKmJiuOK4FOKALP0YLj0VLv1D2xTKuCrsuRT@/zcGAA "Retina – Try It Online") Prints a column of leading spaces and on trailing space on each line. ### Explanation The main byte savings come from omitting the spaces in all the literal parts and inserting them at the end. The figure is structured such that there are never two non-spaces next to each other, so if we just remove them all, we can almost fix the shape by inserting a space at every position at the end: ``` ^ /\ ||| \\ ||| \/ v ``` becomes: ``` ^ / \ | | | \ \ | | | \ / v ``` That's almost correct, except for indentation. The `^` and `v` are missing two spaces. That's actually easier to fix, because if we just insert an explicit space in front of each of them, that'll result in two additional spaces at the end. The lines with the slashes are trickier because they require just one additional space. To fix this, we insert a placeholder character there (`x`). When we insert the spaces at the end, we don't just insert them for every empty match, but we optionally match that `x`. That means instead of inserting a space in front of the `x`, the `x` itself gets replaced. And then there will still be an empty match right after the `x`. That means, every `x` adds exactly one space without changing anything else. So what we want to set up is this: ``` ^ x/\ ||| x\\ ||| x\/ v ``` which will give us the desired result. So here's the code: ``` .+ $* ``` Convert the input to unary. ``` 1 ¶|||¶x\\ ``` Convert each `1` to two lines with `|||` and `x\\` (and a leading linefeed). ``` ^ ^¶x/\ ``` Inser the first two lines with `^` and `x/\`. ``` .$ /¶ v ``` Fix the final `x\\` by turning the last `\` into `/` and appending a line with the `v`. ``` x? ``` Replace each `x` or empty match with a space. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~21~~ 20 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ⌐èüYΩ╜yu╝√♪╪▌yº⌐▌2Σ⌠ ``` [Run and debug it](https://staxlang.xyz/#p=a98a8159eabd7975bcfb0dd8dd79a7a9dd32e4f4&i=5) Uses ETHProductions' idea. -1 after changing `1/` to `M` (from recursive). [Answer] # Pyth, 46 bytes ``` " ^ / \\" +*j[jd*\|3" \ \\"k))Q" \ / v ``` [Test suite.](https://pyth.herokuapp.com/?code=%22++%5E%0A+%2F+%5C%5C%22%0A%2B%2aj%5BKjd%2a%5C%7C3%22+%5C+%5C%5C%22k%29%29QK%0A%22+%5C+%2F%0A++v&input=3&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5&debug=0) [Answer] # Pyth, 40 bytes ``` K" / \ "" ^"Kj+b+*2+d\\b*Q]*3"| "_K" v ``` Fairly similar to Steven Hewitt's, but developed independently. [Try it Online](http://pyth.herokuapp.com/?code=K%22+%2F+%5C+%22%22++%5E%22Kj%2Bb%2B*2%2Bd%5C%5Cb*Q]*3%22|+%22_K%22++v&input=2&debug=0) ### Explanation ``` K" / \ "" ^"Kj+b+*2+d\\b*Q]*3"| "_K" v K" / \ "" Set K = " / \ " " ^" " v Draw the end points. K _K Draw the slants. *Q]*3"| " Draw the vertical bars... j+b+*2+d\\b ... interspersed with slants. ``` [Answer] # Pyth, ~~33~~ ~~32~~ 31 bytes Thanks Mr. Xcoder for one byte. ``` %" ^ / %s/ v"*tj\|_B" \\ | ``` Try it online: [Demonstration](https://pyth.herokuapp.com/?code=%25%22++%5E%0A+%2F+%25s%2F%0A++v%22%2atj%5C%7C_B%22+%5C%5C%0A%7C+&input=5&test_suite_input=2%0A3%0A4%0A5%0A6&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=%25%22++%5E%0A+%2F+%25s%2F%0A++v%22%2atj%5C%7C_B%22+%5C%5C%0A%7C+&input=5&test_suite=1&test_suite_input=2%0A3%0A4%0A5%0A6&debug=0) [Answer] # [Retina](https://github.com/m-ender/retina), 45 bytes This is a pretty simple solution. ``` .+ $* ^1 ^¶ /x $ \ /¶ v 1 \x x \¶| | |¶ ``` [**Try it online**](https://tio.run/##K0otycxL/K/qrpHA9V9Pm0tFiyvOkEtBIe7QNgX9Ci4VLoUYBX0gW6GMCygcU8FVASQPbatRAMJD2/7/N@KyAAA) If the art could be 1-indexed instead, it'd be a bit shorter (44 bytes): ``` .+ ^¶ /x$0$*1 $ \ /¶ v 1 \x x \¶| | |¶ ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~45~~ ~~42~~ 33 bytes ``` " ^ / "."\ | | | \ "Xa."/ v" ``` [Try it online!](https://tio.run/##K8gs@P9fSUEhjktBX0FJTymGq0YBCLkUYhSUIhL1lPS5FBTKlP7//28MAA "Pip – Try It Online") ### Explanation The code is really simple, though the newlines make it harder to read. Here's a better way to see the structure: ``` "prefix" . "repeated" X a . "suffix" ``` The repeated element in the S-chain is ``` \ | | | \ ``` Take this as a literal string and repeat it `a` times (where `a` is the first command-line argument). Then prepend the prefix: ``` ^ / ``` and append the suffix: ``` / v ``` and print. (I like how this ended up looking kinda like a ><> program.) [Answer] # [AsciiDots](https://github.com/aaronduino/asciidots), 88 bytes ``` .*$" ^"$" / \" />#?)--*$"| | |"$" \ \" *#1\ /-~$"| | |"$" \ /"$" v" *-{-}*[<] \#0----/ ``` [Try it online!](https://tio.run/##SyxOzsxMyS8p/v9fT0tFSUEhTglI6ivEKHHp2ynba@rqAkVrFIAQJB4DEtdSNoxR0NetQxHXB1EKZUBZ3WrdWq1om1iuGGUDXSDQ///f0AAA "AsciiDots – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~47~~ ~~44~~ 43 bytes -3 bytes thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) ``` ' ^' ' / \ 'XK'| | |'XJGq:"' \'thJ]KP' v' ``` [Try it online!](https://tio.run/##y00syfn/X11BIU5dQV1BXyFGQT3CW71GAQjVI7zcC62U1BVi1EsyvGK9A4CqytT//zcFAA "MATL – Try It Online") [Answer] # bash, 67 bytes ``` printf -v a %\*s $1 \ ;echo ' ^ / '"${a// /\\ | | | \\ }"'/ v' ``` [Try it online](https://tio.run/##DcLBCkBAFEDR/XzFTaMppRdbv/JSQzQ2yMgG3/7onCHmZLYfy3rO1BeRUquMb1C6aUwbAXqHEAp/RxFE1T38HKq8RRAHVzCz9gM) [Answer] # [Ruby](https://www.ruby-lang.org/), 39 bytes ``` ->n{" ^ / #{"\\ | | | \\ "*n}/ v"} ``` [Try it online!](https://tio.run/##KypNqvyflmf7X9cur1pJQSGOS0FfQblaKSaGq0YBCLkUYmIUlLTyavW5FBTKlGr/F5SWFCuk5UWbxv4HAA "Ruby – Try It Online") [Answer] # [///](https://esolangs.org/wiki////), 54 bytes ``` /*/ | | | b//b>///b/ \\\\ \\\\/ ^ \/ \\**> \\ \/ v ``` [Try it online!](https://tio.run/##K85JLM5ILf7/X19Ln6tGAQi5kvT1k@z0gYS@QgwQgAl9BYU4LoUYkIiWlp0CSFSfS0Gh7P9/IwA "/// – Try It Online") For input, change the number of asterisks ``` \/ \\**> \\ \/ ^^ ``` [Answer] ## Haskell, 53 bytes ``` f n=" ^\n /"++([1..n]>>" \\\n| | |\n \\")++" /\n v" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz1ZJQSEuJk9BX0lbWyPaUE8vL9bOTkkhJiYmr0YBCIFSMTFKmtraSgr6QLZCmdL/3MTMPAVbhYLSkuCSIp88BRWFNAWL/wA "Haskell – Try It Online") [Answer] # Java 8, ~~93~~ 76 bytes ``` n->{String r=" ^\n / ";for(;n-->0;r+="\\\n| | |\n \\ ");return r+"/\n v";} ``` Port of [*@IanH.*'s C# .NET answer](https://codegolf.stackexchange.com/a/143333/52210) after I golfed it a bit more. [Try it here.](https://tio.run/##hY/NbsIwEITvPMXIJ1soP3CqZIU3KJceMUjGGGQIm8hxIiHIs6fbkmtV7e5h51tpZq92sFnTerqebpOrbdfh0wZ6LoBAycezdR7bnxX4SjHQBU4yASnN4sjD3SWbgsMWhAoTZZvnfBsrARwMoYDQ5yZKTVm2KXVcVsIYQy9wMTYGQunoUx8JcSkK1jAIPU767dD2x5odZqOhCSfcOad8@@z2sGoO@eiSv@dNn/KWUapJUu7kWv3m/ZN//MNXpZofHqdv) [Answer] # Excel, 60 bytes ``` =" ^ / \ "&REPT("| | | \ \ ",A1-1)&"| | | \ / v" ``` [Answer] # SpecBAS - 74 bytes ``` 1 INPUT n 2 ?" ^"'" / \"'("| | |"#13" \ \"#13)*(n-1);"| | |"'" \ /"'" v" ``` Apostrophe moves to next line, but doesn't work inside the string being repeated, so have to use `#13` to insert line feeds in that part. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~83~~, 57 bytes ``` " ^ / \" 1..--$args[0]|%{"| | | \ \"} "| | | \ / v" ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0lBIY5LQV8hRonLUE9PV1clsSi9ONogtka1WqlGAQi5FGKAkrVcCJ4@l4JCmdL///8tAA "PowerShell – Try It Online") Per @AdmBorkBork's suggestions, * Simplified `for` by using a number range. * Replaced `;`'s and combined strings. * Removed an unnecessary variable definition. ]
[Question] [ # Introduction Long ago, when I used to code card games with usual playing cards, I used to specify a number for each card and call a function with some number to get a card. This somewhat inspired me to make this challenge. So for the people unaware of the playing cards, a deck of cards consist of 52 cards (13 in each of the four suits, i.e, Hearts, Diamonds, Spades, Clubs). In each suit, there are 13 cards - firstly the cards numbered from 2-10, then the Jack(J), Queen(Q), King(K) and the Ace(A). This is the order # Challenge The challenge is to take an integer between 1-52 as input and display the card at that position. But, your output must be in words. Also, order must be maintained, i.e, first 13 cards will be of Hearts, then Diamonds, then Spades and finally Clubs. For example, if someone chooses the number `30`.The card would then belong to the third suit, i.e, the Spades. Also, it would be the fourth card in the suit, which means the number 5. Hence your output in words must be: `five of spades` and it should **always follow this format**, i.e, first the card, followed by an `of` and the name of the suit at the end, with required spaces in between. # Input And Output **The input will be** **an integer** between 1-52 (both inclusive). Note that here counting starts from 1. **You may choose to start from 0**. However, **you must maintain the order** of the cards which is mentioned above. Your output should be the card at that position written in words. You do not need to handle invalid inputs. Also, your output may be in lower-case or in upper-case. Given below is the list of all the possible inputs and their outputs: ``` 1 -> two of hearts 2 -> three of hearts 3 -> four of hearts 4 -> five of hearts 5 -> six of hearts 6 -> seven of hearts 7 -> eight of hearts 8 -> nine of hearts 9 -> ten of hearts 10 -> jack of hearts 11 -> queen of hearts 12 -> king of hearts 13 -> ace of hearts 14 -> two of diamonds 15 -> three of diamonds 16 -> four of diamonds 17 -> five of diamonds 18 -> six of diamonds 19 -> seven of diamonds 20 -> eight of diamonds 21 -> nine of diamonds 22 -> ten of diamonds 23 -> jack of diamonds 24 -> queen of diamonds 25 -> king of diamonds 26 -> ace of diamonds 27 -> two of spades 28 -> three of spades 29 -> four of spades 30 -> five of spades 31 -> six of spades 32 -> seven of spades 33 -> eight of spades 34 -> nine of spades 35 -> ten of spades 36 -> jack of spades 37 -> queen of spades 38 -> king of spades 39 -> ace of spades 40 -> two of clubs 41 -> three of clubs 42 -> four of clubs 43 -> five of clubs 44 -> six of clubs 45 -> seven of clubs 46 -> eight of clubs 47 -> nine of clubs 48 -> ten of clubs 49 -> jack of clubs 50 -> queen of clubs 51 -> king of clubs 52 -> ace of clubs ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins. [Answer] # [Python 3](https://docs.python.org/3/), ~~115~~ 90 bytes ``` from unicodedata import* lambda n:name(chr(n%13+n%13//11+[6,0,4,2][-n//13]*8+127137))[13:] ``` An unnamed function returning the string in uppercase. **[Try it online!](https://tio.run/##HYlBDoIwEADP8oq9GFoowaUqhkQ/ghwqtNDEbkmtB19fxcskM7N@4uJJJnO9p6dyj0kBdaScZuMSGO1RlhvqGrHsz@IgjqIZ@op@QQ7FpcSmRdly3qPshswE7@BNdvSTnlRUYN3qQyyS8QGifkWwBEHRrBmKk@RdtluDpci2JyCvbrkA8zfO0xc "Python 3 ‚Äì Try It Online")** ### How? Unicode characters have names. The names of some of these are like "PLAYING CARD TWO OF SPADES", hence we can get the characters of the Unicode character representing the required card and strip off the first 13 characters to get our output. The Unicode characters of interest are within a block like so: ``` 0 1 2 3 4 5 6 7 8 9 A B C D E F U+1F0Ax x As 2s 3s 4s 5s 6s 7s 8s 9s Ts Js x Qs Ks x U+1F0Bx x Ah 2h 3h 4h 5h 6h 7h 8h 9h Th Jh x Qh Kh x U+1F0Cx x Ad 2d 3d 4d 5d 6d 7d 8d 9d Td Jd x Qd Kd x U+1F0Dx x Ac 2c 3c 4c 5c 6c 7c 8c 9c Tc Jc x Qc Kc x ``` Where the `x` are not characters we are after (the four in the `C` column are "knights"; three in `F` are "jokers"; one in `0` is generic; the rest are reserved characters). As such we can add *some* value to 0x1F0A1 = 127137 (As) to find the card we want. The value to add is only complicated by three things: 1. We need to reorder the suits (from s,h,d,c to h,d,s,c) 2. We need to reorder the ranks from (A,2,...,K to 2,...,K,A) 3. We need to avoid the columns without cards of interest. Using the one-indexing option allows the use of negative integer division to index into an array of row-wise offsets for the suit re-ordering with `[6,0,4,2][-n//13]*8+` (effectively `[48,0,32,16][-n//13]`), we can then also place the aces into the correct locations with `n%13+` and then avoid the knights in column `C` with `n%13//11+` (effectively `(n%13>10)+`). [Answer] # [Perl6/Rakudo](https://perl6.org/) 70 bytes Index 0 Using `perl6 -pe`, and with no dictionary compression: ``` chr('üDZüÉÅüǰüÉë'.ords[$_/13]+($_+1)%13*1.091).uniname.substr(13) ``` It just looks up the card in Unicode (starting from the Ace), asks for the name and uses that. This is a similar route (though I didn't know it at the time!) to [Jonathan Aitken's Python answer](https://codegolf.stackexchange.com/a/158092/14710) - only I index from all 4 aces rather than 4 offsets from the Ace of Spades, and I multiply by 1.091 to make the index round away from the Knight entry in Unicode. See all the output (for input values 0 to 51) <https://glot.io/snippets/ez5v2gkx83> Edited to cope with Knights in the Unicode deck, because Unicode. Perl6 ‚ô• Unicode [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 54 bytes 0-indexed ``` ‚Äú¬ª‚Ǩ√Ö‚Äπ¬°≈†des≈æ‚Ķ‚Äú#‚Äú‚Äö‚Ä¢‚Äû√≠‚Ć√¨ÀÜ√à≈í≈°√جø≈∏¬Ø¬•≈†‚Äî¬ø‚Äî√â≈∏√Ñ‚Äπ≈í√Å√†‚Äú#√¢√≠" of "√Ωs√® ``` [Try it online!](https://tio.run/##FYwxCsJQEAWvEpILqOiBFGNrkQtsREXbYCUiPwElRULaiGhgH1t5i3eR708x0wzMZLFcTVPvKTd9c9fgQHlpaW6dZvalPENIApQrpaLc0VIcmt8RJyusRKeD9drpwxzlokMQztZjHz5WIIcbD6jQxtF2E8X4ZKi9n83/ "05AB1E ‚Äì Try It Online") **Explanation** ``` ‚Äú¬ª‚Ǩ√Ö‚Äπ¬°≈†des≈æ‚Ķ‚Äú# # push list of suits ‚Äú‚Äö‚Ä¢‚Äû√≠‚Ć√¨ÀÜ√à≈í≈°√جø≈∏¬Ø¬•≈†‚Äî¬ø‚Äî√â≈∏√Ñ‚Äπ≈í√Å√†‚Äú# # push list of ranks √¢ # cartesian product √≠ # reverse each " of "√Ω # join on " of " s√® # index into cardlist with input ``` [Answer] # [Emojicode](http://www.emojicode.org/), 202 bytes ``` üçáiüöÇüòÄüç™üç∫üêΩüî´üî§two.three.four.five.six.seven.eight.nine.ten.jack.queen.king.aceüî§üî§.üî§üöÆi 13üî§ of üî§üç∫üêΩüî´üî§hearts.diamonds.spades.clubsüî§üî§.üî§‚ûói 13üç™üçâ ``` 0 indexed. [Try it online!](https://tio.run/##VY9BbsIwEEX3nGJOMCpUHMg4EzIBbIgd2mVhU2VR0QUSKAu8QUi0ogeoxGVyAt8gtRN1weJr/rc0f/xooXOWOqHWu90GvPt4H0Acl7RUso2Zvau33h3fQvgK@vXu8@7d/jvobF802qwgwlSXBaa8JjT8iobWpJB4mllUrAhtiLmQM1yVFOyM1RSFpNgRhb2pfxiGz9GDTqF/ezyYkSiswYTFQqvEoFmKhAzKeTkxD2XN6dB3dZ@u2ki13wJDs7vCE4xH/7Ad7g0iL3APXw26lT8 "Emojicode ‚Äì Try It Online") **Explanation**: ``` üçá start of the closure block iüöÇ closure takes an integer argument i üòÄ print: üç™ concatenate these strings: üç∫üêΩüî´üî§...üî§üî§.üî§üöÆi 13 [a] üî§ of üî§ üç∫üêΩüî´üî§...üî§üî§.üî§‚ûói 13 [b] üç™ üçâ [a]: üç∫ tell Emojicode to dereference without checking üêΩ get the nth element of the following array üî´ create an array using the following string and separator üî§...üî§ üî§.üî§ üöÆ i 13 n, i mod 13 [b] üç∫üêΩüî´üî§...üî§üî§.üî§‚ûói 13 same but with ‚åäi√∑13‚åã ``` [Answer] # [Python 2](https://docs.python.org/2/), 167 148 bytes ``` n=input();print 'two three four five six seven eight nine ten jack queen king ace'.split()[n%13]+' of '+['hearts','diamonds','spades','clubs'][n/13] ``` Zero-indexed. [Try It Online!](https://tio.run/##FcwxDsIwDIXhq3hBBhWBgIEBcZKoQ2jdxrQ4IXEKnD6k2/cP74WfOi/nUuTOErJud7cQWRRQPx7URSIYfI4w8EKQ@AuJFhIgHp2CsBBozaftJnhnqpxYRrAd4SGFmeuhkc3p0jYIfgBsDDqyURPusWf78tKvTMH2tKKb8yNha@RYN6Vc/w) EDIT: Bubbler made a great point using the split method (and providing a shorter answer). On the second block using split() yields the same byte count. [Answer] # [R](https://www.r-project.org/), 154 bytes ``` paste(el(strsplit("Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten,Jack,Queen,King,Ace",",")),"of",rep(c("Hearts","Diamonds","Spades","Clubs"),e=13))[scan()] ``` [Try it online!](https://tio.run/##FcixCsIwFIXhd8mUwB0szg6iFlEQpN3EIU2v7cU0CTdp1aePKWf5zs/ZUseaf3LCNPo@qhx0TCjRypg4BktJivbjoR0ZEWo/M9S0IDT0hQYXdHCiYUxwI4fQlnvR5g33GQuv5AbYGxRQphQI/xLAGKSR4oyaUyz9SHryrl/ZBN3jioOduygU4K7aKvWIRjupnrna5D8 "R ‚Äì Try It Online") Takes input (1-indexed) from STDIN and with `source(...,echo=T)` will print the result to console. It's not pretty, BUT it comes in 2 bytes shorter than the best solution I could using `outer` (presented below), so let this be a reminder to examine another approach! ``` paste( # concatenate together, separating by spaces, # and recycling each arg to match the length of the longest el(strsplit("Two,...",",")), # split on commas and take the first element "of", # rep(c("Hearts",...), # replicate the suits (shorter as a vector than using strsplit e=13) # each 13 times )[scan()] # and take the input'th index. ``` # [R](https://www.r-project.org/), 156 bytes ``` outer(el(strsplit("Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten,Jack,Queen,King,Ace",",")),c("Hearts","Diamonds","Spades","Clubs"),paste,sep=" of ")[scan()] ``` [Try it online!](https://tio.run/##FcdBCsIwEEDRq5SsEpiFHsCFqEUUBGl34iJtx3YwTUImqXr6mPI374dsqAs6/OSMcXIDq@xSxCDRSI6BvaEoRftx0E4BEWqXAtS0IDT0hQYXtHCicYpwI4vQlr3o/g33hIVXsiPsexRQUgp6Kc6oQ@SyR9Kzs8PKxusBVxxM6lgo8JojAqPficq9KqEe3Gsr1TNvN/kP "R ‚Äì Try It Online") Essentially the same as above; however, `outer` will do the recycling properly, but having to set `sep=" of "` for the `paste` made this just a hair longer. [Answer] ## Excel, 156 bytes ``` =TRIM(MID("two threefour five six seveneightnine ten jack queenking ace",1+MOD(A1,13)*5,5))&" of "&CHOOSE(1+(A1/13),"hearts","diamonds","spades","clubs") ``` Cards from 0-51. Unfortunately, Excel does not feature a function to convert `1` to `"one"`... Using `TRIM` and `MID` is shorter than using `CHOOSE` for the face values, but longer than using `CHOOSE` for the Suit. [Answer] # Java 8, 141 bytes ``` n->"two;three;four;five;six;seven;eight;nine;ten;jack;queen;king;ace".split(";")[n%13]+" of "+"hearts;diamonds;spades;clubs".split(";")[n/13] ``` Input is 0-indexed. **Explanation:** [Try it online.](https://tio.run/##VVDLasNADLz3K8RCwcbEfdFL1PQPmkuPIYeNLcfyQ@t6Zbel5NtdNcmlIAk9GDQzjZ/9KgwkTdkuRedjhDfP8nMDwKI0Vr4g2P6NAO86shyhSOwCkqItT5YWUb1yAVsQ2MAiq1ennwG1HomwCtOIFc@Ekb8w0kyCxMdaUVgI1cbGFy1@TGRtax/Qfro8Dh1r4tClO7l9eNpnDkIFLnM1@VEjluz7IGXEOPiSIhbddIj/YXcGW/BCcZgOnVG8Mp0Dl9Cb0OQiarf36UVkFcazPt7cI/DL86PVLEvPN7PgOyr1eZg0HwynnSScubXRktx8Sa@mnJZf) ``` n-> // Method with integer parameter and String return-type "two;three;four;five;six;seven;eight;nine;ten;jack;queen;king;ace".split(";")[n%13] // Take `n` modulo-13 as 0-indexed card value +" of " // append " of " +"hearts;diamonds;spades;clubs".split(";")[n/13] // append `n` integer-divided by 13 as 0-indexed suit ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 52 bytes ``` ;‚Üî!Œ†mw¬∂¬®√ó‚ĺs√ø·∫㌥·∫é‚ÇÜ·π°‚Å∑·∏Ç6‚Ä∞fœâŒ∏¬ª&‚åàŒ∏∆íV‚ÇÜx‚ŵ‚ñº√ヰ`nƒ±E·πÖ'jƒäk‚Å∏"e√Øk√Ñc ``` [Try it online!](https://tio.run/##AW4Akf9odXNr//874oaUIc6gbXfCtsKow5figLxzw7/huovOtOG6juKChuG5oeKBt@G4gjbigLBmz4nOuMK7JuKMiM64xpJW4oKGeOKBteKWvMOLxKFgbsSxReG5hSdqxIpr4oG4ImXDr2vDhGP///81MQ "Husk ‚Äì Try It Online") I'm always happy to show off Husk's string compression system :D ### Explanation The majority of the program (from `¬®` onwards) is obviously a compressed string. When uncompressed it turns into: ``` hearts diamonds spades clubs of two three four five six seven eight nine ten jack queen king ace ``` The program then is: ``` ;‚Üî!Œ†mw¬∂¬®‚Ķ ¬®‚Ķ The previous string ¬∂ Split on lines mw Split each line into words - we now have a list of lists of words Œ† Cartesian product of the three lists - with this we obtain all possible combinations of suits and values with "of" between the two (e.g. ["spades","of","king"]) ! Pick the combination at the index corresponding to the input ‚Üî Reverse it, so words are in the correct order ; Wrap it in a list. Result: [["king","of","spades"]] ``` There are a couple of things left to explain: * We build the cards with suits before values because of how the cartesian product `Œ†` works: if we did it the other way around, the list of cards would be ordered by value (i.e. two of hearts, two of diamonds, two of spades, two of clubs, three of hearts...). As a consequence, we have to reverse our result. * The result of the program is a two-dimensional matrix of strings. This is automatically printed by Husk as a single string built by joining rows of the matrix with newlines and cells with spaces. The reason we build this matrix instead of using the more straightforward `w` (join a list of words with spaces) is that if using `w` the type inferencer guesses another interpretation for the program, producing a different result. [Answer] # [Kotlin](https://kotlinlang.org), ~~154~~ ~~152~~ 140 bytes ``` i->"two,three,four,five,six,seven,eight,nine,ten,jack,queen,king,ace".split(',')[i%13]+" of ${"heart,diamond,spade,club".split(',')[i/13]}s" ``` [Try it online!](https://tio.run/##VY3NTsQwDITvfQorWrSJcPkVl5XonTNHxCG0SWuadUriFqSqz14CnBjJkkfj@TxGCcS7nxnOllgvNtnUQ5l8gmdJxL2BtYIiHxNoAmK4gZmFAjzcmd/kR1M5lcBaHQjqBg6r12Q2ZaqtWmwAf9JPLKZu/piP6051o@QzogzJOfRxTuhpcZjpC7NbHKOjfhBkYodS7LttR/yYXVnHgkDbOnWVp0Cij3g0L3Rxe/96qSD68l0NzibBjuw5cod5sp3DNsxv/yvXpbJltW/7Nw "Kotlin ‚Äì Try It Online") Updated to use just lambda expression. [Answer] # JavaScript ES6, ~~124~~ 118 Bytes, 0-index ``` F= x=>(h=btoa`O ?N√û{√±h¬∫¬ø√Ö√∑¬øJ,I√´√û√±"6)√û√Ω7¬ß√º√¥.y√©√ø*)√†√º√ø√ø√ø√¶¬´¬∑√∑bjj'w√ª)i√ó¬ør[`.split`/`)[x%13]+` of ${h[x/13|16]}s` console.log (F(51)) ``` Base64 version ``` eD0+KGg9YnRvYWBPCj9OGt578Wi6v8WK979KLH9J696f8SKCG382Kd79N6f8lpyT9C556f8qKeD8Bx7///+F5qu392Jqaid3+ylp179yW5tgLnNwbGl0YC9gKVt4JTEzXStgIG9mICR7aFt4LzEzfDE2XX1zYA== ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 58 57 56 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` √Æ‚Üë√†‚ñ†?R‚ï¢8¬´E‚ñѬ°‚ïî√ø‚Ä¢L‚ï´<<‚å†√Ø‚àû‚àü‚å°‚ô™√ñs1"T√†LŒ±‚ï•‚ñĬ¢¬°‚óÑ‚îî%‚âàŒ¥√±M;;}'‚ñëo=‚å°¬ª‚ï¨√≠‚àö ``` [Run and debug it](https://staxlang.xyz/#p=8c1885fe3f52b638ae45dcadc998074cd73c3cf48bec1cf50d9973312254854ce0d2df9bad11c025f7eba44d3b3b7d27b06f3df5afcea1fb&i=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A26%0A39&a=1&m=2) Here's the commented ungolfed representation of the same program. It uses stax's compressed literals heavily. The input is 0-indexed. It's Emigna's 05AB1E algorithm. ``` `SsUI'S~pTU5T@T^Ez+`j suits `fV:l7eTkQtL*L2!CZb6u[&YNO4>cNHn;9(`j ranks |* cross-product @ index with input r reverse pair `%+(`* join with " of " ``` [Run this one](https://staxlang.xyz/#c=%60SsUI%27S%7EpTU5T%40T%5EEz%2B%60j%09suits%0A%60fV%3Al7eTkQtL*L2%21CZb6u[%26YNO4%3EcNHn%3B9%28%60j%09ranks%0A%7C*%09cross-product%0A%40+%09index+with+input%0Ar%09reverse+pair%0A%60%25%2B%28%60*%09join+with+%22+of+%22&i=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A26%0A39&a=1&m=2) [Answer] ## [mIRCScript](https://www.mirc.com/), 157 bytes ``` c echo $token(ace two three four five six seven eight nine ten jack queen king,$calc(1+$1% 13),32) of $token(clubs spades diamonds hearts,$calc(-$1// 13),32) ``` Load as an alias, then use: `/c N`. mIRC is 1-indexed, so floor division (//) on the negative value of the input produces -1 to -4 as required. [Answer] # [C (gcc)](https://gcc.gnu.org/), 148 bytes ``` f(n){printf("%.5s of %.7ss","two\0 threefour\0five\0six\0 seveneightnine\0ten\0 jack\0queenking\0ace"+n%13*5,"heart\0 diamondspade\0 club"+n/13*7);} ``` [Try it online!](https://tio.run/##PY5BTsMwEEXXySlGliLZJC0uKOoiwEm8Mc44MW3Hqe0UpKpnD8OGzXzp/TfSd7vJuW3zktR9SYGKl6LZ9xmih2Z/zFl0onxHo6HMCdHHNRntww2NzuGHccYbEoZpLhSIaUFi@mXdyejrikinQJPR1qFoqTm8PvWdmNGmwtYY7CXSmBc78ie48/rJ0jNLRzU8Nl4DFxtIqvpeVz4mkH8owDvogeMN@hfOtlV1Vf2PH2H3AaLjvoWD6sDLwHdZS5ZCqKF@bL8 "C (gcc) ‚Äì Try It Online") 0-based. [Answer] # [Haskell](https://www.haskell.org/), 132 bytes ``` (!!)[v++" of "++s|s<-words"hearts diamonds spades clubs",v<-words"two three four five six seven eight nine ten jack queen king ace"] ``` [Try it online!](https://tio.run/##NcoxEoIwEEbhq/xkLHSQwsJOTmGpFmvYQCQmmE3AwrMbaezeN/MGkpGdK6a9lm1V7S5zXSsEA1XX8pFTs4TYiRqYYhJ0lp7BdwKZqGOBdvkuaj//t7QEpCEyw4QcYezMEPuG8MwebPshwVvPSCsfpEe8Mq85Wt@DNKtbeZL1aDHldE4RGxgcD@WrjaNeSqOn6Qc "Haskell ‚Äì Try It Online") An anonymous function, using list comprehension to build all the combinations of suit and value, and indexing into the resulting list with the input. [Answer] # F#, 174 168 bytes Removed some extra whitespace as noted by Manish Kundu. Thanks! ``` let c x=["two";"three";"four";"five";"six";"seven";"eight";"nine";"ten";"jack";"queen";"king";"ace"].[(x-1)%13]+" of "+["hearts";"diamonds";"spades";"clubs"].[(x-1)/13] ``` [Try it online!](https://tio.run/##PZCxbsMwDER3fwUhIECCIHHSolPqbB0LZDc8qBJts7GlhJJd9@tdSkMXPfJ4B0pqw8F4xnX0dhoQPjW5G/uO9QjVCgNGMLBUtYo/Xl1U7BlR2PqJE2hOXaAlnTijEyJ1fRQ6cmkYs/itzV3wnDC3d3KdQBtUzbHeLofzbnN@bfYKfAtqX6seNccgFkt69M6mMjy0xVSYYfoK/8FSgmsB9fuHi/x78@TitSny1Ud5DWjuZqiggCxRJfOsHeuT2ODBIsjSTVCwNUC7QsQTlCUwxokl70Ac2CEDLiT/4S2uxfr28gc) I'll be honest - I'm new at code golf, so I don't know if it's more appropriate to answer with a pure function like this (with parameters, but no I/O) or with a working code block with user I/O. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~155~~ ~~153~~ ~~151~~ 150 bytes ``` @(x)[strsplit(' of ,s,heart,diamond,spade,club,ace,two,three,four,five,six,seven,eight,nine,ten,jack,queen,king',','){[mod(x,13)+7,1,ceil(2+x/13),2]}] ``` [Try it online!](https://tio.run/##DYrtCoIwGIVvxX9ueLA0IggC70P8seY7Xelm@zAjunYbhwPPeThWBrHSrm5lWe4N23jrg/PLpAPLM6syeIwkXECvxWxND7@IniCneIeQhPC2CKMjgrLRQemV4PUGTysZkB7GAKNNOqb5EPKJV6SET22GHCn82862ZxuqEy8uqCBJT6wutkMSqLtft7fCOfFR0bCGGa5SUV3PNfJochx5t/8B "Octave ‚Äì Try It Online") This creates a string starting with `' of '` and `'s'`, then all the suits followed by all the ranks. This string is split at commas into separate strings. The suits are before the ranks, because since that saves a byte when creating the indices. After this, we index it using square brackets with the following indices: ``` {[mod(x,13)+7,1,ceil(2+x/13),2]} ``` which is the rank, followed by the first element `' of '`, followed by the suit, followed by `'s'`. Having the `'s'` as part of the suits (`hearts,diamonds,spades,clubs`) instead of a separate string is the exact same length but less fun. Splitting on the default separator would save 4 bytes in the `strsplit`-call, but the spaces around `' of '` would be removed and would have to be added manually, costing more bytes. [Answer] # [V](https://github.com/DJMcMayhem/V), 154 147 144 142 Bytes -7 Bytes thanks to DJMcMayhem ``` 13i1heart 2diamond 3spade 4club √öGxCtwo three four five six seven eight nine ten jack queen king aceH$A of 012j$d4√±13jP√±√ç ¬´/ {√ÄjYHVGpAs ``` [Try it online!](https://tio.run/##Fc6xEYIwGIbh/huAhiYFvQZYgLPA0so7ywg/kKAJkoDc2biAC7iCFSuYwRC79@necVl4InlDoneISymuRpdIbCdKQlpchjNC/w7yaefuBq7piVCZoUclR4KVEyyNpEGybhy01AS3UomixW2gNVupa4iCwmAfZcxULNwGPFZRmfqZJ@rgZ/9i38@G4eGf6rQ/5l1ml//WDw "V ‚Äì Try It Online") Hexdump: ``` 00000000: 3133 6931 6865 6172 740a 3264 6961 6d6f 13i1heart.2diamo 00000010: 6e64 0a33 7370 6164 650a 3463 6c75 620a nd.3spade.4club. 00000020: 1bda 1647 7843 7477 6f0a 7468 7265 650a ...GxCtwo.three. 00000030: 666f 7572 0a66 6976 650a 7369 780a 7365 four.five.six.se 00000040: 7665 6e0a 6569 6768 740a 6e69 6e65 0a74 ven.eight.nine.t 00000050: 656e 0a6a 6163 6b0a 7175 6565 6e0a 6b69 en.jack.queen.ki 00000060: 6e67 0a61 6365 1b16 4824 4120 6f66 201b ng.ace..H$A of . 00000070: 3016 3132 6a24 6434 f131 336a 50f1 cd20 0.12j$d4.13jP.. 00000080: ab2f 200a 7bc0 6a59 4856 4770 4173 ./ .{.jYHVGpAs ``` [Answer] # [C#](https://docs.microsoft.com/en-us/dotnet/csharp/), 219 207 202 197 bytes (0 indexed) ``` static string O(int i){string[]s={"two","three","four","five","six","seven","eight","nine","ten","jack","queen","king","ace","hearts","diamonds","spades","clubs"};return s[i%13]+" of "+s[i/14+13];} ``` thanks to input from @Ciaran\_McCarthy and @raznagul Takes an input of int I, subtracts 1 to match 0 indexing of the string array and outputs the number based on I mod 13 and the suit based on i/14+13. works pretty well for my second code golf, just wondering if i could get it shorter using LINQ or something else. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 207 192 182 174 165 163 161 157 bytes # 0-Indexed ``` $args|%{(-split'two three four five six seven eight nine ten jack queen king ace')[$_%13]+' of '+('hearts','diamonds','spades','clubs')[$_/13-replace'\..*']} ``` [Try it online!](https://tio.run/##HcxBDoIwEIXhq8wCMiiCIcTTKDEVBlqpbe0UMFHPXsHd9y/ec3Yhz5K0jjERfuBP@s4KdloFDIuFID0R9Hby0KuZgNULmGYyQGqQAYwyBGHNu2hHeE60clRmANES7s7JNa3qJkewPWCeoSThA@MBOyUe1nQb2YmONrR6uvF/dKzqwpPT28mlLPfYfGOMp@oH "PowerShell ‚Äì Try It Online") *4 bytes saved thanks to AdmBorkBork in the comments* [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~161~~ ~~160~~ ~~158~~ 142 bytes ``` [TWO][THREE][FOUR][FIVE][SIX][SEVEN][EIGHT][NINE][TEN][JACK][QUEEN][KING][ACE][HEART][DIAMOND][SPADE][CLUB][z2-:rz1<A]dsAxD~;rP[ OF ]PD+;rP83P ``` [Try it online!](https://tio.run/##FYyxDsIwDER/pTtioDAgYDGJ25hCEkpSkCxP9AvKgjrw68FdTnfvTje@y64unJ5BOLkeUbgJuVelQf2DXio4oBdGal0S9uS1SAu5gOmE7xmX0JFvhcFo6RB6XVqCW/BWDyJYxeaaz8JzvT5M8@YEMn7ga3/HKXIVmkqiXanfb2Mpfw "dc ‚Äì Try It Online") Over a year later, I was looking for something in my old golfs and found 16 bytes of inefficiency in the previous code: ``` [ACE][KING][QUEEN][JACK][TEN][NINE][EIGHT][SEVEN][SIX][FIVE][FOUR][THREE][TWO]0[d1+si:rlidD>A]dsAxr[CLUB]3:s[SPADE]2:s[DIAMOND]1:s[HEART]0:sD~;rP[ OF ]P;sP83P ``` [Try that chunkier version online!](https://tio.run/##FYq9DoIwFEZfhd2FHwcDicmVXqCibYUWTW7uZBcSJ7o4@eq1bOd85/PveCwjQYtMo1Q908MhKqYrtCOT3VFJlSrKfrBMMy77NssXUyeXFDrtpvQcJkxin5pz8sUhrPX2Wb04A/sA343am7twVQeaDQjkMpGQcNdKcJF4QJgs53UQv2YzlOkuY9MEc6pMjH8 "dc ‚Äì Try It Online") Top of stack used as input. 0-indexed. In the old version, the array of ranks (`r`) was created using an iterator to run through the strings on the stack (`0[d1+si:rlidD>A]dsAxr`), but with only four items, it's shorter to manually assign the suits (`3:s`, etc.). The new version simply uses one array for all of it and also doesn't check against a fixed stack size. `[z2-:rz1<A]dsAx` replaces the above stack-crawler, popping everything into `r` at the position `(stack depth)-2`; it stops when there's one value left. After all that setup is done, we divide by 13 leaving remainder & quotient on stack (`D~`). In the old version, we used these values to pick from the two arrays. In the new version, without a separate array of suits, we add 14 (`E+`) to the suit value, since our suits are after our ranks in array `r`. Print the strings, and print `OF` in the middle (`;rP[ OF ]PE+;rP`). (First two golfs: -1 byte by outputting uppercase; this allows me to remove the 4 `s`es from the end of the suits, and instead print it via its ASCII value with the 3-byte `83P` at the end. -2 bytes because I repeatedly misread the challenge as requiring 1-indexing. Now 0-indexed.) [Answer] # [CJam](https://sourceforge.net/p/cjam), 114 bytes ``` riDmd"two three four five six seven eight nine ten jack queen king ace"S/=" of "@"hearts diamonds spades clubs"S/= ``` [Try it online!](https://tio.run/##FcrREcIgEEXRVt7QgBU444cdWMEKj7CJgLIQ7Z7Ev3tmrl8lz9n0noPr34qeGolYR0PUnTD9wbizgLqkjqKF6CdX8Rs@g2duWhaIp3tcrg41wt1corRuCCq5lmCwtwQa/Gs87f/NeQA "CJam ‚Äì Try It Online") Zero-indexed. Will probably be beaten by languages with dictionary compression, but oh well... [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 61 bytes ``` d13U·ªã"‚Äú¬¢¬∂/C≈ª)G·ª•+·∏∂}ƒã< Ç·∏§a·ª¥¬£k7·ª¥‚Ǩ^·∏•√¶]¬ø9·ª§‚Äú¬°¬¢|h·∏Ç·πó∆¨√üƒñ,$√∞ƒø»ß¬ª·∏≤‚Ǩ¬§j‚Äú of ``` 0-indexing. [Try it online!](https://tio.run/##AXsAhP9qZWxsef//ZDEzVeG7iyLigJzCosK2L0PFuylH4bulK@G4tn3EizzKguG4pGHhu7TCo2s34bu04oKsXuG4pcOmXcK/OeG7pOKAnMKhwqJ8aOG4guG5l8asw5/Eliwkw7DEv8inwrvhuLLigqzCpGrigJwgb2Yg////NTE "Jelly ‚Äì Try It Online") [Answer] # [Julia 0.6](http://julialang.org/), 156 bytes ``` f(n)=print(split(" of ,hearts,diamonds,spades,clubs,two,three,four,five,six,seven,eight,nine,ten,jack,queen,king,ace",',')[[(n-1)%13+6,1,div(n-1,13)+2]]...) ``` [Try it online!](https://tio.run/##Fc1LDoIwFEbhrRgSQxt@SSoJM1dCGFS4hQvYYh/o7ivOzjc6S9pYtzkbYeVj92yjCPvGURQXZy6YSfsYMLJ@OTsGhF2PFDBs6RkQPw5x9kQwLnkYPgiBvwh0kAXxNEdYtoR4ctHDineiM1e2E/RABUqUsuuEvSl5VU3VQp2r42@oRlb3vq/rWub8Aw "Julia 0.6 ‚Äì Try It Online") -2 bytes thanks to @Stewie Griffin [Answer] # [Haskell](https://www.haskell.org/), 144 bytes ``` f n=words"two three four five six seven eight nine ten jack queen king ace"!!(n`mod`13)++" of "++words"hearts diamonds spades clubs"!!(n`div`13) ``` [Try it online!](https://tio.run/##JYwxEoIwFAWv8shY6KTRseYGdl6ASH5IBH4wPwFvH3Hodotdb2SkaarVgdstJisqbxHZJyK4WBJcWAkSvhBaiUFh8BkcmJB3fZt@xKfQjmPgAaYn1TRn7uZou9v9orVCdFBaH3NPJmWBDWaObAWyGEuCfiovOUIb1n9YZxMYLZaSnzk9GCc4XOsP "Haskell ‚Äì Try It Online") This hits all kinds of Haskell's pain points. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 53 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ƒ∑Œ∂‚â°‚óÑŒ§≈´‚îåp9P7≈°H‚ñ°‚â°‚Öù'‚ïóŒ¶qŒñ‚ñí∆®M.‚ÄòŒ∏.wo"C‚ñà}y1+‚ñ∫ŒöqŒö‚ÄòŒ∏J¬º o.'‚Å∞/wp ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTM3JXUwM0I2JXUyMjYxJXUyNUM0JXUwM0E0JXUwMTZCJXUyNTBDcDlQNyV1MDE2MUgldTI1QTEldTIyNjEldTIxNUQlMjcldTI1NTcldTAzQTZxJXUwMzk2JXUyNTkyJXUwMUE4TS4ldTIwMTgldTAzQjgud28lMjJDJXUyNTg4JTdEeTErJXUyNUJBJXUwMzlBcSV1MDM5QSV1MjAxOCV1MDNCOEolQkMlMjBvLiUyNyV1MjA3MC93cA__,inputs=MTM_,v=0.12) [Answer] ## Javascript ~~149~~ ~~143~~ 140 bytes ``` a=_=>"two three four five six seven eight nine ten jack queen king ace".split` `[_%13]+' of '+["hearts","diamonds","spades","clubs"][_/13|0] ``` *-3 bits thanks to [@rick hitchcock](https://codegolf.stackexchange.com/users/42260/rick-hitchcock)* ``` a=_=>"two three four five six seven eight nine ten jack queen king ace".split` `[_%13]+' of '+["hearts","diamonds","spades","clubs"][_/13|0] console.log(a(14)) console.log(a(34)) console.log(a(51)) console.log(a(8)) console.log(a(24)) ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 119 bytes 0-based ``` $_=(TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,TEN,JACK,QUEEN,KING,ACE)[$_%13].' OF '.(HEART,DIAMOND,SPADE,CLUB)[$_/13].S ``` [Try it online!](https://tio.run/##FcrBCoJAFEbhV3FhaPBnhLhsMY5X52bNlDNaEOGqRRAp1fM36e4c@Mb7@5l5H/bb2J0NnGqIUJq2QckdwfIFljrSIK6Ug2ZNcNPuhKxxamnKmnUFIWl5DfvFJr0lUWDKIEpiRaJxKFgcjC5gj6IgyH2bz3A9Q@t9mv2G8fsYXh@/Gv8 "Perl 5 ‚Äì Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~91~~ 86 bytes 0-indexed. I used a [tool written by @Shaggy](https://codegolf.stackexchange.com/a/142629/61613) to generate the compressed lists. ``` `{`twod√à(‚f√Üfiv√Ĭ£x√ß P ightd√ç√Çd√àˆjackdqu√Å√àkˆg¬ª¬≠`qd gU} è {`√ä#tsk¬πa√öˆ√§i√Ǭ£kclubs`qk gUzD ``` [Try it online!](https://tio.run/##AXcAiP9qYXB0//9ge2B0d29kw4gowoJmw4YHZml2w4DCo3jDpyBQIGlnaHRkw43DgmTDiMKIamFja2RxdcOBw4hrwohnwrvCrWBxZCBnVX0gwo8ge2DDiiN0c2vCuWHDmsKIw6Rpw4LCo2tjbHVic2BxayBnVXpE//81MQ "Japt ‚Äì Try It Online") ## Explanation: The first compressed string contains the card values delimited by `d`. The second compressed string contains the card ranks delimited by `k`. These chars were picked using Shaggy's tool, which generates a string delimited by a char that is optimally compressed using shoco (the compression that Japt uses). This allows us to create a list of card values and ranks. We use backticks ``` to decompress these strings, then we split the string using `q`, followed by the char to split on. Once we have the lists, we map through the card values, then we get the index of the input. It is important to note that Japt wraps its indexes, so we don't have to modulo by 13. At each item, we loop through the card ranks. We get the index by dividing the input by 13. Once we have both items, we concatenate them with `" of "`, which produces the final string. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~58~~ 55 bytes ``` ‚Äúƒ±ƒø‚ÅΩ‚Å∑lg3e/‚Äú·∫è‚Äú¬£·π¢¬¢√∑y·∏ä‚Åæ‚Å∂∆≠‚ź·∫é·∫á·∏Ñ·π°¬øOn·πÉ‚Å∂·∏Ç·∏Çf·π†»Æ‚Ū·∫â√ë%¬ª·∏≤‚Ǩp/‚Å∏·ªã·πöj‚Äú of ``` [Try it online!](https://tio.run/##AYUAev9qZWxsef//4oCcxLHEv@KBveKBt2xnM2Uv4oCc4bqP4oCcwqPhuaLCosO3eeG4iuKBvuKBtsat4oG84bqO4bqH4biE4bmhwr9PbuG5g@KBtuG4guG4gmbhuaDIruKBu@G6icORJcK74biy4oKscC/igbjhu4vhuZpq4oCcIG9mIP///zUy "Jelly ‚Äì Try It Online") ]
[Question] [ The [On-Line Encyclopedia of Integer Sequences](https://en.wikipedia.org/wiki/On-Line_Encyclopedia_of_Integer_Sequences) (OEIS) is an online database of integer sequences. It contains nearly 280000 sequences of mathematical interest. Examples of sequences: * positive integers ([A000027](https://oeis.org/A000027)) * prime numbers ([A000040](http://oeis.org/A000040)) * Fibonacci numbers ([A000045](https://oeis.org/A000045)) Your task is to write a program or function that displays as many OEIS sequences as you can, with a source code of **100 bytes** maximum. Your program should accept as input the sequence id (without the prepending `A` and the zeroes), and output the 20 first numbers in that sequence. You are not allowed to fetch the data directly from the OEIS website; all sequences must be computed by your code. **Scoring** Score is the number of OEIS sequences the program can display. Answers will have to list the IDs of the sequences recognised by their program. **Example** Here's a valid answer in Java 8: ``` (int a) -> { for (int i = 0; i < 20; i++) { System.out.println(a==27?i+1:i*i); } }; ``` This program can display the positive integers (A000027 - input 27) and the squares (A000290 - input 290), thus its score is 2. **Note** Please avoid scraping the whole OEIS website :-) you can download the [sequence names](https://oeis.org/names.gz) (about 3 megs) or [sequence values](http://oeis.org/stripped.gz) (about 9 megs). Note that this download is covered by the [OEIS End-User License Agreement](http://oeis.org/wiki/The_OEIS_End-User_License_Agreement). [Answer] ## Python 2, 875 sequences ``` print', '.join('%020d'%(10**20/(input()-21004))) ``` Works for 875 of the sequences [21016](https://oeis.org/A021016) (decimal digits of 1/12) through [21999](https://oeis.org/A021999) (decimal digits of 1/995). I found this chunk with the sophisticated search algorithm of haphazardly typing in sequence id's by hand. Some of the sequences in the range are not of this format and appear elsewhere (thanks to Mitchell Spector for pointing this out). For example, [21021](https://oeis.org/A021021) is not the expansion of 1/17. Even with the interruptions, the sequences for 1/n appear as id `n+21004`. The remainder is not shifted, but the missing sequences appear elsewhere. For example, 1/17 appears as [7450](https://oeis.org/A007450). I counted the ones that match using [a downloaded copy](https://oeis.org/names.gz) of the sequence names. A different block gives **848 sequences** from [16742](https://oeis.org/A016742) to [17664](https://oeis.org/A017664). ``` n=input()-16729 for i in range(20):k=n/12;a=int((8*k+1)**.5/2+.5);print(a*i+k-a*(a-1)/2)**(n%12+1) ``` These all have form `n -> (a*n+b)^c`, where `2≤a≤12, 0≤b<a, 1≤c≤12`. The code extracts the coefficients via inverting triangular numbers and moduli. As before, not all sequences in the range match. If these two expressions could fit in 100 bytes, it would give 1723 sequences. Promising chunks: * 1929 matching sequences: [41006](https://oeis.org/A041006) through [42397](https://oeis.org/A042937), numerators and denominators of continued fraction convergents. * ~3300 matching sequences: [147999](https://oeis.org/A147999) to [151254](https://oeis.org/A151254): counts of walks on Z^3, if you can find how the vector lists are ordered. Here are categories for other potential chunks, via grouping the OEIS sequence names by removing all numbers (digits, minus sign, decimal point). They are sorted by number of appearances. ``` 3010 Number of walks within N^ (the first octant of Z^) starting at (,,) and consisting of n steps taken from {(, , ), (, , ), (, , ), (, , ), (, , )} 2302 Number of reduced words of length n in Coxeter group on generators S_i with relations (S_i)^ = (S_i S_j)^ = I 979 Primes congruent to mod 969 Numerators of continued fraction convergents to sqrt() 967 Denominators of continued fraction convergents to sqrt() 966 Continued fraction for sqrt() 932 Decimal expansion of / 894 Duplicate of A 659 Partial sums of A 577 Divisors of 517 Inverse of th cyclotomic polynomial 488 Expansion of /((x)(x)(x)(x)) 480 Decimal expansion of th root of 471 Number of nX arrays with each element x equal to the number its horizontal and vertical neighbors equal to ,,,, for x=,,,, 455 First differences of A 448 Decimal expansion of log_ () 380 Numbers n such that string , occurs in the base representation of n but not of n+ 378 Erroneous version of A 375 Numbers n such that string , occurs in the base representation of n but not of n 340 Numbers n with property that in base representation the numbers of 's and 's are and , respectively ``` --- **35 sequences:** ``` c=input() for n in range(20):print[(c-1010)**n,(c-8582)*n][c>2e3] ``` Works from [8585](https://oeis.org/A008585) (multiples of 3) through [8607](https://oeis.org/A008607) (multiples of 25), and [1018](https://oeis.org/A001018) (powers of 8) through [1029](https://oeis.org/A001029) (powers of 19). Conveniently, these are all in one chunk ordered by id. This uses only 65 of the 100 allowed bytes and isn't fully golfed yet, so I'll look for another nice chunk. [Answer] # [Bash](https://www.gnu.org/software/bash/) + coreutils, 252 sequences ``` yes 0|head -20 ``` [Try it online!](https://tio.run/nexus/bash#@1@ZWqxgUJORmpiioGtk8P8/AA "Bash – TIO Nexus") Works on 252 OEIS sequences: A000004, A006983, A011734, A011735, A011736, A011737, A011738, A011739, A011740, A011741, A011742, A011743, A011744, A011745, A023975, A023976, A025438, A025439, A025443, A025444, A025466, A025469, A034422, A034423, A034427, A034429, A034432, A034435, A034437, A034438, A034439, A034441, A034443, A034445, A034447, A034449, A034450, A034451, A034452, A034453, A034454, A034455, A034456, A034457, A034458, A034459, A034461, A034462, A034464, A034465, A034466, A034467, A034468, A034469, A034471, A034473, A034475, A034476, A034477, A034479, A034480, A034481, A034482, A034483, A034484, A034485, A034486, A034487, A034489, A034490, A034492, A034493, A034495, A034497, A034498, A034499, A034500, A034501, A034502, A034503, A034504, A034505, A034506, A034507, A034508, A034509, A034510, A034511, A034512, A034514, A034515, A034516, A034518, A034519, A034520, A034521, A034522, A034523, A034525, A034526, A034527, A034528, A034529, A034530, A034531, A034532, A034533, A034534, A034535, A034536, A034537, A034538, A034539, A034540, A034541, A034542, A034543, A034544, A034545, A034546, A034547, A034548, A034549, A034550, A034551, A034552, A034553, A034554, A034555, A034556, A034557, A034558, A034559, A034560, A034561, A034562, A034563, A034564, A034565, A034566, A034567, A034568, A034569, A034570, A034571, A034572, A034573, A034574, A034575, A034576, A034577, A034578, A034579, A034580, A034581, A034582, A036861, A047752, A052375, A055967, A061858, A065687, A066035, A067159, A067168, A070097, A070202, A070204, A070205, A070206, A072325, A072769, A076142, A082998, A083344, A085974, A085982, A086007, A086015, A089458, A093392, A094382, A105517, A108322, A111855, A111859, A111898, A111899, A112802, A122180, A129947, A137579, A159708, A161277, A161278, A161279, A161280, A165766, A167263, A178780, A178798, A180472, A180601, A181340, A181735, A184946, A185037, A185203, A185237, A185238, A185245, A185246, A185255, A185264, A185284, A191928, A192541, A197629, A198255, A200214, A206499, A210632, A212619, A217148, A217149, A217151, A217155, A217156, A228953, A230533, A230686, A235044, A235358, A236265, A236417, A236460, A238403, A243831, A243832, A243833, A243834, A243835, A243836, A248805, A250002, A256974, A260502, A264668, A276183, A277165, A280492, A280815 [Answer] ## CJam (2182 2780 3034 sequences) ``` {:ZA3#:Cb(40-z_!!:B-\+CbB)/)_mqmo:M+:NK{)[N0{N1$_*-@/M@+1$md@M@-}K*]<W%B{X0@{2$*+\}%}*ZB&=}%\C)<f*} ``` This gives correct answers for the inclusive ranges * `[A040000, A040003]`, `[A040005, A040008]`, `[A040011, A040013]`, `A040015`, `[A040019, A040022]`, `A040024`, `[A040029, A040033]`, `A040035`, `A040037`, `[A040041, A040043]`, `A040048`, `A040052`, `[A040055, A040057]`, `A040059`, `A040063`, `[A040071, A040074]`, `A040077`, `A040080`, `[A040090, A040091]`, `[A040093, A040094]`, `A040097`, `A040099`, `[A040109, A040111]`, `A040118`, `A040120`, `[A040131, A040135]`, `A040137`, `A040139`, `[A040142, A040143]`, `A040151`, `[A040155, A040157]`, `A040166`, `A040168`, `[A040181, A040183]`, `[A040185, A040968]` * `[A041006, A041011]`, `[A041014, A042937]` * `A006983`, `[A011734, A011745]`, `[A023975, A023976]`, `[A025438, A025439]`, `[A025443, A025444]`, `A025466`, `A025469`, `[A034422, A034423]`, `A034427`, `A034429`, `A034432`, `A034435`, `[A034437, A034439]`, `A034441`, `A034443`, `A034445`, `A034447`, `[A034449, A034459]`, `[A034461, A034462]`, `[A034464, A034469]`, `A034471`, `A034473`, `[A034475, A034477]`, `[A034479, A034487]`, `[A034489, A034490]`, `[A034492, A034493]`, `A034495`, `[A034497, A034512]`, `[A034514, A034516]`, `[A034518, A034523]`, `[A034525, A034582]`, `A036861`, `A047752`, `A052375`, `A055967`, `A061858`, `A065687`, `A066035`, `A067159`, `A067168`, `A070097`, `A070202`, `A070204`, `[A070205, A070206]`, `A072325`, `A072769`, `A076142`, `A082998`, `A083344`, `A085974`, `A085982`, `A086007`, `A086015`, `A089458`, `A093392`, `A094382`, `A105517`, `A108322`, `A111855`, `A111859`, `[A111898, A111899]`, `A112802`, `A122180`, `A129947`, `A137579`, `A159708`, `[A161277, A161280]`, `A165766`, `A167263`, `A178780`, `A178798`, `A180472`, `A180601`, `A181340`, `A181735`, `A184946`, `A185037`, `A185203`, `[A185237, A185238]`, `[A185245, A185246]`, `A185255`, `A185264`, `A185284`, `A191928`, `A192541`, `A197629`, `A198255`, `A200214`, `A206499`, `A210632`, `A212619`, `[A217148, A217149]`, `A217151`, `[A217155, A217156]`, `A228953`, `A230533`, `A230686`, `A235044`, `A235358`, `A236265`, `A236417`, `A236460`, `A238403`, `[A243831, A243836]`, `A248805`, `A250002`, `A256974`, `A260502`, `A264668`, `A276183`, `A277165`, `A280492`, `A280815` The `A040???` sequences correspond to the continued fractions of non-rational square roots from `sqrt(2)` to `sqrt(1000)` (with the gaps corresponding to ones which appear earlier in OEIS, but conveniently filled with random sequences). The `A041???` sequences correspond to the numerators and denominators of the continued fraction *convergents* for non-rational square roots from `sqrt(6)` to `sqrt(1000)` (with the gap corresponding to `sqrt(10)`, at `A005667 and A005668`). The other assorted sequences have zeroes for their first twenty values. The answer ports elements of two earlier answers of mine in GolfScript: * [Determining the continued fractions of square roots](https://codegolf.stackexchange.com/a/6416/194) * [Good rational approximations of pi](https://codegolf.stackexchange.com/a/4236/194) Many thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) for the short closed form `x -> x + round(sqrt(x))` mapping sequence offsets to the value to sqrt. The savings over my previous calculation (generating the list of non-squares and selecting by index) provided enough to have an all-zero fallback for most out-of-range indices. [Answer] # Python (with sympy), ~~144~~ 146 sequences ``` import sympy f=lambda a,M=16627:[int(c)for c in str(sympy.log((a<M)*46.5+4+a-M).n(20))if'.'<c][-20:] ``` The function `f` works for the **146** sequences **[A016578](https://oeis.org/A016578)** through **[A016723](https://oeis.org/A016723)** inclusive. All of these are output by the test harness at **[repl.it](https://repl.it/FMWx/3)**. The **49** sequences **[A016578](https://oeis.org/A016578)** through **[A016626](https://oeis.org/A016626)** inclusive are the decimal expansions of log(3/2), log(5/2), log(7/2), ..., log(99/2). The **97** sequences **[A016627](https://oeis.org/A016627)** through **[A016723](https://oeis.org/A016723)** inclusive are the decimal expansions of log(4), log(5), log(6), ..., log(100). The first **two** of the **49** start at the first decimal place since the log values for them are less than **1**, so the `[-20:]` takes the trailing 20 decimal places of the result of the call to `...n(20)` which gets 20 significant figures. The `if'.'<c` filters out the decimal place character, and the `int(c)` casts each remaining digit character to an integer (although maybe not necessary). [Answer] # Jelly, ~~1127~~ 1975 sequences -- this currently combines the findings of [xnor](https://codegolf.stackexchange.com/a/107210/53748) and [Mitchell Spector](https://codegolf.stackexchange.com/a/107220/53748), but still has some room for growth at 78 bytes. Go give them some credit! ``` 0x20 _21004µȷ20:DU¢oU 20Ḷ×⁸+µ*þ12 11R‘µẋ`€F$ç"Ḷ€F$;/ _108ị¢ “æÑØ‘×ȷ3¤>J×$S‘µĿ ``` **[TryItOnline!](https://tio.run/nexus/jelly#@29QYWTAFW9kaGBgcmjrie1GBlYuoYcW5YdyGRk83LHt8PRHjTu0D23VOrzP0IjL0DDoUcOMQ1sf7upOeNS0xk3l8HIloCIw01qfK97QwOLh7u5Di7i4HjXMObzs8MTDM4DqD08/sd340BI7r8PTVYLB@o/s////v6GZubkFAA)** The 1975 sequences are: * the 252 that start with twenty zeros (the behaviour for input outside of `[16000,21999]`); * the 848 sequences lying in the range [16742](https://oeis.org/A016742) to [17664](https://oeis.org/A017664) that match the `(a*n+b)**c` formula (the behaviour for input in `[16000,17999]`); and * the 875 sequences lying in the range [21016](https://oeis.org/A021016) to [21999](https://oeis.org/A021999) that match the decimal expansion of `1/n` (the behaviour for input in `[18000,21999]`). ### How? ``` 0x20 - Link 1, TwentyZeros: no arguments 0 - zero 20 - twenty x - repeat _21004µȷ20:DU¢oU - Link 2, DecimalExpansionOfReciprocal: oeisIndexNumber µ - monadic chain separation ȷ20 - 1e20 _21004 - subtract 21004 from oeisNumber to get the n value : - integer division, i.e. 1e20 // n D - decimal list U - reverse ¢ - call last link (1) as a nilad, i.e. get twenty zeros o - logical or, i.e. pad the right of the reversed list to twenty with zeros U - reverse again 20Ḷ×⁸+µ*þ12 - Link 3, BlockOf12abcFormulaResults: a, b 20Ḷ - lowered range of 20 [0,1,...,19] i.e. the values of n in (a*n+b)**c ⁸ - left argument, a × - multiply + - add b µ - monadic chain separation þ12 - outer product with [1,2,...,12] of... i.e. the values of c in (a*n+b)**c * - exponentiation 11R‘µẋ`€F$ç"Ḷ€F$;/ - link 4, AllabcFormulaResults: no aguments 11R - range of 11 [1,2,...,11] ‘ - increment [2,3,...12] i.e. the values of a in (a*n+b)**c µ - monadic chain separation $ - last two links as a monad ẋ`€ - repeat list with repeated arguments for €ach [[2,2],[3,3,3],...,[12,12,12,12,12,12,12,12,12,12,12,12]] F - flatten into one list $ - last two links as a monad Ḷ€ - lowered range of €ach [[0,1],[0,1,2],...,[0,1,2,3,4,5,6,7,8,9,10,11]] F - flatten into one list ç" - zip with (") last link (3) as a dydad (ç) i.e. get all the results / - reduce with ; - concatenation i.e. make the list of lists of lists one list of lists. _108ị¢ - Link 5, abcFormulaResult: oeisIndexNumber _108 - subtract 108 from the oeisNumber (indexes in Jelly are modular and there are 924 entries, this is shorter than _16740) ¢ - call last link (4) as a nilad ị - index into i.e. get the one relevant result of 20 terms - Link 6, an empty link (cheaper in bytes than the %6 alternative in the main link) “æÑØ‘×ȷ3¤>J×$S‘µĿ - Main link: oeisIndexNumber e.g. 1-15999; 16000-17999; 18000-21999; 22000+ ¤ - nilad followed by link(s) as a nilad “æÑØ‘ - codePage indexes [22,16,18] ȷ3 - 1e3 × - multiply [22000,16000,18000] > - greater than (vectorises) e.g. [1,1,1]; [1,0,1]; [1,0,0]; [0,0,0] $ - last two links as a monad J - range(length) [1,2,3] × - multiply e.g. [1,2,3]; [1,0,3]; [1,0,0]; [0,0,0] S - sum e.g. 6; 4; 1; 0 ‘ - increment e.g. 7; 5; 2; 1 µ - monadic chain separation Ŀ - call link(index) as a monad with the oeisIndexNumber link indexing is 1-based and modular so 7 calls link 1 >< hence the empty link 6 replacing a %6 here ``` [Answer] # Mathematica, ~~39~~ ~~173~~ 189 sequences ``` If[l=0~Range~19;#<4^7,l,If[#<3^9,#&@@RealDigits[Log[j=16627;#-j+If[#<j,49.5,4]],10,20],#-22956-l]]& ``` Inspired by [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/107218/60043). Works for: * [1477](https://oeis.org/A001477), [2837](https://oeis.org/A002837), [4830](https://oeis.org/A004830), and [8554](https://oeis.org/A008554) (the first 20 terms of these are `{0, 1, 2, ... , 19}`) * [16578](https://oeis.org/A016578) to [16626](https://oeis.org/A016626) (decimal expansion of log(3/2), decimal expansion of log(5/2), ... decimal expansion of log(99/2)) * [16627](https://oeis.org/A016627) to [16723](https://oeis.org/A016723) (decimal expansion of log(4), decimal expansion of log(5), ... decimal expansion of log(100)) * [22958](https://oeis.org/A022958) to [22996](https://oeis.org/A022996) (2-n, 3-n, ... 40-n) [Answer] ## CJam, 1831 sequences ``` {168680-:Zz1320b900b48md:R;H+:QB+2*,:!1_tQWtQ)WtK{[WQW*_(]+1$f=[1R2+R~R4+*2/WR-X$-].*1b+}/J~>ZW>f*} ``` This gives correct output for 199 sequences beginning `0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0` and all sequences in the inclusive ranges `[A168680, A169579]` and `[A170000, A170731]`. The bulk of it deals with those two ranges, with a fallback for all-zeroes before the start of the first range. The two ranges in question have the form > > Number of reduced words of length \$n\$ in Coxeter group on \$P\$ generators \$S\_i\$ with relations \$(S\_i)^2 = (S\_i S\_j)^Q = I\$ > > > for values of \$P\$ ranging from \$3\$ to \$50\$ and values of \$Q\$ ranging from \$17\$ to \$50\$. Their generating functions are given in a thoroughly inefficient manner: I found it useful to multiply numerators and denominators by \$(t - 1)\$ to give g.f. $$\frac{t^{Q+1} + t^Q - t - 1}{\frac12(P-2)(P-1) t^{Q+1} - \frac12(P-2)(P+1) t^Q + (P-1)t - 1}$$ although for golfing purposes I'm actually working with \$R = P + 3\$. [Answer] ## Batch, 62 sequences ``` @for /l %%i in (1,1,20)do @set/a"n=(n=22956-%1)*(n>>=16)+%%i*(n|%1-8582)"&call echo %%n%% ``` Just implementing one block of sequences was hard, but I managed two in 89 bytes! Explanation: For a parameter `%1` of 8585-8607, `22956-%1>>16` returns zero, causing the `(22956-%1)` expression to be ignored and we end up multiplying the loop variable by 3-25 respectively, while for a parameter of 22958-22996 it returns minus one causing the expression to be negated, while the `n|` causes the multiplication factor to be replaced with minus one effectively subtracting the loop variable. [Answer] # [PHP](https://php.net/), 28 bytes, 33 Sequences I assume ``` for(;;)print_r(range(0,32)); ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKytNQuKMvNK4os0ihLz0lM1DHSMjTQ1rf//BwA "PHP – Try It Online") <https://oeis.org/A000004> 0 <https://oeis.org/A007395> 2 <https://oeis.org/A010701> 3 <https://oeis.org/A010709> 4 <https://oeis.org/A010716> 5 <https://oeis.org/A010722> 6 <https://oeis.org/A010727> 7 <https://oeis.org/A010731> 8 <https://oeis.org/A010734> 9 <https://oeis.org/A010692> 10 <https://oeis.org/A010850> 11 <https://oeis.org/A010851> 12 <https://oeis.org/A010852> 13 <https://oeis.org/A010854> 15 <https://oeis.org/A010855> 16 <https://oeis.org/A010857> 18 <https://oeis.org/A010859> 20 <https://oeis.org/A010861> 22 <https://oeis.org/A010863> 24 <https://oeis.org/A010871> 32 ]
[Question] [ Taken straight from the ACM Winter Programming Contest 2013. You are a person who likes to take things literally. Therefore, for you, the end of The World is ed; the last letters of "The" and "World" concatenated. Make a program which takes a sentence, and output the last letter of each word in that sentence in as little space as possible (fewest bytes). Words are separated with anything but letters from the alphabet (65 - 90, 97 - 122 on the ASCII table.) That means underscores, tildes, graves, curly braces, etc. are separators. There can be more than one seperator between each word. `asdf jkl;__zxcv~< vbnm,.qwer| |uiop` -> `flvmrp` `pigs, eat dogs; eat Bob: eat pigs` -> `ststbts` `looc si siht ,gnitirw esreveR` -> `citwR` `99_bottles_of_beer_on_the_wall` -> `sfrnel` [Answer] # ed, 35 characters ``` s/[a-zA-Z]*\([a-zA-Z]\)\|./\1/g p Q ``` So, the world ends in ed. As I like to be too literal, I decided to write to write the solution with ed - [and apparently it is actually a programming language](https://nixwindows.wordpress.com/2018/03/13/ed1-is-turing-complete/). It's surprisingly short, even considering many shorter solutions already exist in this thread. It would be nicer if I could use something other than `[a-zA-Z]`, but considering ed isn't a programming language, it's actually good enough. First, I would like to say this only parses the last line in file. It would be possible to parse more, just type `,` at beginning of two first lines (this specified "everything" range, as opposed to standard last line range), but that would increase code size to 37 characters. Now for explanations. The first line does exactly what Perl solution does (except without support for Unicode characters). I haven't copied the Perl solution, I just invented something similar by coincidence. The second line prints last line, so you could see the output. The third line forces quit - I have to do it, otherwise `ed` would print `?` to remind you that you haven't saved the file. Now for how to execute it. Well, it's very simple. Just run `ed` with the file containing test case, while piping my program, like that. ``` ed -s testcase < program ``` `-s` is silent. This prevents `ed` from outputing ugly file size at beginning. After all, I use it as a script, not editor, so I don't need metadata. If I wouldn't do that, ed would show file size that I couldn't prevent otherwise. [Answer] ## Perl 5, 18 bytes ``` s/\pL*(\pL)|./$1/g ``` Requires a `-p` command line switch. The named property `L` matches only letter characters `A-Za-z`. There are [several hundred](http://perldoc.perl.org/perluniprops.html) such named properties, but when dealing with ASCII text, very few of them are interesting. Besides `\pL`, the only other one of any real note is `\pP`, which matches punctuation. [Try it online!](https://tio.run/##HYmxDoIwFAB3vqKDgxqEODggTs5OziYvFB6lWvtqXwVjiJ9uRZLL5ZJz6M0uRs4v7rReTlqNWb7Y5irGiptWXG@mBHi/6v5zEL209zR7DOhHMT41ucRpxanAKoiGFJdzHUnu5/jPxBDVgvVEF0SqrA7aDwLZY4/npChAUggGGagFieiBLIQOYaiM@ZILmizHjfsB "Perl 5 – Try It Online") --- **Perl 5, 17 bytes** *A one byte improvement by [Dom Hastings](https://codegolf.stackexchange.com/posts/comments/385684?noredirect=1)* ``` print/\pL*(\pL)/g ``` Requires `-n` (and `-l` to support multiple inputs). [Try it online!](https://tio.run/##HYmxDoIwEEB3vuJGNSiTA@rk7ORscqFwlGrt1fYEY4ifbkWSl5eXPE/BblPywTgpLv60WkxaFjqlKjYtXG92j/h@1f3nAL1y93zzGCiMMD4N@8wbHXOgSqBhHfdzHVnt5vjPzDLXEM1EJ5BrZ8SEASgG6umclSUqFrEUkVtURAHZoXSEQ2Xtl70YdjGtnf0B "Perl 5 – Try It Online") --- **Sample usage** ``` $ more in.dat asdf jkl;__zxcv~< vbnm,.qwer| |uiop pigs, eat dogs; eat Bob: eat pigs looc si siht ,gnitirw esreveR 99_bottles_of_beer_on_the_wall $ perl -p ends-in-ed.pl < in.dat flvmrp ststbts citwR sfrnel ``` [Answer] ## Javascript, 49 ``` alert(prompt().replace(/.(?=[a-z])|[^a-z]/gi,'')) ``` It uses a regular expression to remove all characters that come before a letter, as well as all non-letter characters. Then we're left with the last letter of each word. Thanks to [tomsmeding](https://codegolf.stackexchange.com/users/6689/tomsmeding) for a nice improvement. [Answer] # C, 78 Golfed: ``` main(int c,char**s){for(;c=*s[1]++;)isalpha(c)&&!isalpha(*s[1])?putchar(c):0;} ``` With whitespace: ``` main(int c,char**s) { for(;c=*s[1]++;) isalpha(c)&&!isalpha(*s[1])?putchar(c):0; } ``` Output: ![enter image description here](https://i.stack.imgur.com/PIye9.jpg) [Answer] ## GNU Sed, 40 38 37 ``` s/[a-z]\b/&\n/g; s/[^\n]*\(.\)\n/\1/g ``` ### Testing ``` cat << EOF > data.txt asdf jkl;__zxcv~< vbnm,.qwer| |uiop pigs, eat dogs; eat Bob: eat pigs looc si siht ,gnitirw esreveR EOF ``` Run sed: ``` sed 's/[A-Za-z]\b/&\n/gi; s/[^\n]*\(.\)\n/\1/g' data.txt ``` Output: ``` flvmrp ststbts citwR ``` ### Explanation The first substitution replaces all word boundaries, that are preceded by the desired match group, with a new-line. This makes it easy to remove all extraneous characters in the second substitution. ### Edit * Use case-insensitive flag (-2), thanks **manatwork**. * Don't count whitespace (-1). [Answer] ## Grep and Paste, 36 34 28 ``` > echo 'asdf jkl;__zxcv~< vbnm,.qwer| |uiop' | grep -io '[a-z]\b' | tr -d \\n flvmrp > echo 'pigs, eat dogs; eat Bob: eat pigs' | grep -io '[a-z]\b' | tr -d \\n ststbts echo 'looc si siht ,gnitirw esreveR' | grep -io '[a-z]\b' | tr -d \\n citwR ``` If a final new-line is needed, replace `tr -d \\n` with `paste -sd ''`. ### Edit * Use case-insensitive grep (-2), thanks **manatwork**. * Use `tr` instead of `paste` (-4), thanks **manatwork**. * Don't count whitespace around pipe (-2). [Answer] ## sed, 37 chars Equal length to [Thor's answer](https://codegolf.stackexchange.com/a/10882/3544), but, I think, simpler. ``` s/[a-z]*\([a-z]\)/\1/ig;s/[^a-z]*//ig ``` The logic is quite trivial - replace letter sequences with their last letter, then delete all non-letters. [Answer] ## Mathematica, 39 ``` ""<>StringCases[#,(__~~x_)?LetterQ:>x]& ``` Test: ``` ""<>StringCases[#,(__~~x_)?LetterQ:>x]& /@ {"asdf jkl;__zxcv~< vbnm,.qwer| |uiop", "pigs, eat dogs; eat Bob: eat pigs", "looc si siht ,gnitirw esreveR", "99_bottles_of_beer_on_the_wall"} ``` > > > ``` > {"flvmrp", "ststbts", "citwR", "sfrnel"} > > ``` > > [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 4.5 bytes (9 nibbles) ``` .%~$\$a/\ ``` ``` .%~$\$a/\ # 9 nibble program .%~$\$a/\$$ # with implicit variables added: $~ # split $ # the input \ # by whether the character class $ # of each element a # is alphabetic; . # now, map over this \ # reversing $ # each group / # and folding across these $ # returning the first (left-hand) argument # (in other words, return the first character of each group) ``` [![enter image description here](https://i.stack.imgur.com/qgNHI.png)](https://i.stack.imgur.com/qgNHI.png) [Answer] # [Zsh](https://zsh.sourceforge.io/) (builtins only), 40 ``` for j (${=@//[^a-zA-Z]/ });printf $j[-1] ``` [Try it Online](https://tio.run/##NcvdToNAEAXg@z7FBKuBBCTV9KKiifQRvDDapp3wM8Ai7tDdlVX68@poG0nOxUnOd3pdDSRz7Xr7oWAFNbjT/dNzGK63SdDHwWoTwtGLWiWkKWBar4PZZqCs4slxcv6Bs7P3wexOmR9L8/nV9fYG8e195XpaxzG8Lp1/lui8gPqjiRD776w7PUKXyk//dmdJHeDwJbgdaStK7QMlBnIudXRpS04fLuU8jrBhzkCLv1QG/FIKI5QF0oo6ehnRYoEpG9OQRi4wJVLIEk1FaJOmcYZf)... [Answer] # K, 49 ``` {last'f@&"b"$#:'f:"|"\:@[x;&~x in,/.Q`a`A;:;"|"]} ``` . ``` k){last'f@&"b"$#:'f:"|"\:@[x;&~x in,/.Q`a`A;:;"|"]}"asdf jkl;__zxcv~< vbnm,.qwer| |uiop" "flvmrp" k){last'f@&"b"$#:'f:"|"\:@[x;&~x in,/.Q`a`A;:;"|"]}"pigs, eat dogs; eat Bob: eat pigs" "ststbts" k){last'f@&"b"$#:'f:"|"\:@[x;&~x in,/.Q`a`A;:;"|"]}"looc si siht ,gnitirw esreveR" "citwR" ``` [Answer] ## Scala, 59 (or 43) Assuming the string in already in `s`: ``` s.split("[^a-zA-Z]+").map(_.last).mkString ``` If you need to read from a prompt and print rather than using the REPL output, convert `s` to `readLine` and wrap in `println()` for 59. [Answer] ## x86: 54 bytes Assume a [cdecl](http://en.wikipedia.org/wiki/X86_calling_conventions#cdecl) routine with the signature `void world_end(char *input, char *output)`: ``` 60 8b 74 24 24 8b 7c 24 28 33 d2 8a 0e 8a c1 24 df 3c 41 72 08 3c 5a 77 04 8a d1 eb 09 84 d2 74 05 88 17 47 33 d2 46 84 c9 75 e0 84 d2 74 03 88 17 47 88 0f 61 c3 ``` [Answer] ## Xi, 32 ``` println$ @{=>.-1}<>input re"\W+" ``` [Xi](https://github.com/arshajii/xi) is a language still in its beta phase, but it seems to work well with code golf so I figured I might as well show yet another short and functional solution (and advertise the language a little :-)). [Answer] ## Mathematica ~~62~~ ~~57~~ 52 ``` Row@StringTake[StringCases[#,LetterCharacter..],-1]& ``` Testing ``` l = {"asdf jkl;__zxcv~<vbnm,.qwer| |uiop", "pigs,eat dogs;eat Bob:eat pigs", "looc si siht,gnitirw esreveR"} Row@StringTake[StringCases[#,LetterCharacter..],-1]&/@ l (*{flvmrp,ststbts,citwR}*) ``` [Answer] # Python3, 59 chars ``` import re;print(re.sub('.(?=[a-z])|[^a-z]','',input(),0,2)) ``` Correctly deals with capital letters and underscores. The 2 is to pass `re.sub` the `re.IGNORECASE` flag without having to use `re.I`. [Answer] # Python, 76 chars `import re;print "".join(re.findall("([a-zA-Z])(?=$|[^a-zA-Z])",raw_input()))` [Answer] # R, 126 My R solution ``` function(x){cat(paste(unlist(sapply(strsplit(unlist(strsplit(gsub(" [^[:alpha:]]"," ",x)," ")),""),tail,1)),collapse=""),"\n")} ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 8 bytes ``` DQ*a@+XA ``` Verify all test cases: [Try it online!](https://tio.run/##HcmxDoIwEIDhnae4WRt3wEGND6Auul1aOKBauNJWagzx1auS/MOX/FbbdAVZjHBKx/NK7ta3fUrS1w3cH6ZEfL@q6bOFSQ292IyR3AzzU7PNrG69AJIBam59uejAqljwn5lhrsDrX10A0Q46aBeBvKOJLlmeo@IQDHnkBhWRQx4wdIRRGvMF "Pip – Try It Online") ### Explanation ``` XA Built-in regex variable: `[A-Za-z]` + Apply regex + quantifier: `[A-Za-z]+` a@ Find all matches in the input DQ* Dequeue the last character from each match Concatenate together and autoprint (implicit) ``` [Answer] # [Haskell](https://www.haskell.org/), ~~62~~ 60 bytes ``` f s=last<$>words[last$' ':[c|'@'<c,c<'{','`'<c||c<'[']|c<-s] ``` [Try it online!](https://tio.run/##FcdNDsIgEEDhq0waktmgB1BqvINL0lSkJdbSHxnaGp14dcTVe9/dUN96n5IDKr2hqMRpm0JD@g@BgAdtGc@orLQKPyjxmp85Q2OVs6MqDaYboYR5iZcYQICDwlDj4NH7Y12/X3b9Klhv4yD3z60NDLx001ykHw "Haskell – Try It Online") Thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard) for a version without the import, saving two bytes! --- ### [Haskell](https://www.haskell.org/), 62 bytes ``` import Data.Char f s=last<$>words[last$' ':[c|isAlpha c]|c<-s] ``` [Try it online!](https://tio.run/##FcfRCoIwFAbg@57iRwRvygeoGUS9QZcicpoOl5uunakRo1df9N19A/HYG5OStm72ATcKVF4H8jsFrgxxEPl5m33H9T95geJYy6j5YtxAkE2U4sBNsqQnVHBLuAePHAoZcafwHM2pbT9vuX4F1sdk9@Vr631EXPTssvQD "Haskell – Try It Online") Given an input string `s`, `[last$' ':[c|isAlpha c]|c<-s]` converts all non-alphabetic characters to spaces. `words` splits the resulting string on white space and `last<$>` takes the last character of each of the resulting strings. [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), ~~16~~ ~~9~~ 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` q\L mÌ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVA&code=cVxMIG3M&input=IlRoZSBXb3JsZCI) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=cVxMIG3M&footer=cQ&input=WwoiYXNkZiBqa2w7X196eGN2fjwgdmJubSwucXdlcnwgfHVpb3AiIC0%2bIGZsdm1ycAoicGlncywgZWF0IGRvZ3M7IGVhdCBCb2I6IGVhdCBwaWdzIiAgIC0%2bIHN0c3RidHMKImxvb2Mgc2kgc2lodCAsZ25pdGlydyBlc3JldmVSIiAgICAgICAtPiBjaXR3UgoiOTlfYm90dGxlc19vZl9iZWVyX29uX3RoZV93YWxsIiAgICAgIC0%2bIHNmcm5lbApdLW1S) ``` q\L mÌ :Implicit input of string U q :Split on \L : Regex /[^a-z]/gi m :Map Ì : Last character :Implicitly join & output ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~27~~ 19 bytes ``` seMc:z"[^A-Za-z]+"d ``` [Test suite](https://pythtemp.herokuapp.com/?code=seMc%3Az%22%5B%5EA-Za-z%5D%2B%22d&test_suite=1&test_suite_input=asdf+jkl%3B__zxcv%7E%3C+vbnm%2C.qwer%7C+%7Cuiop%0Apigs%2C+eat+dogs%3B+eat+Bob%3A+eat+pigs%0Alooc+si+siht+%2Cgnitirw+esreveR%0A99_bottles_of_beer_on_the_wall&debug=0) ##### Explanation: ``` seMc:z"[^A-Za-z]+"d | Full code --------------------+--------------------------------------------- :z"[^A-Za-z]+"d | In the input, replace non-letters with space c | Split on spaces eM | Replace each word with its last letter s | Concatenate each letter ``` [Answer] # Python 3.x, 64 bytes ``` import re;print(''.join(a[-1] for a in re.split('\W+',input()))) ``` [Answer] # **Lua, 42** ``` print(((...):gsub('.-(.)%f[%A]%A*','%1'))) ``` Usage example: `lua script.lua "asdf jkl;__zxcv~< vbnm,.qwer| |uiop"` [Answer] ## Mathematica ~~71~~ ~~47~~ ~~45~~ 61 Back to the drawing board, after @belisarius found an error in the code. ``` StringCases[#, RegularExpression["[A-Za-z](?![A-Za-z])"]] <> "" & ``` Testing ``` l = {"asdf jkl;__zxcv~<vbnm,.qwer| |uiop", "asdf jkl__zxcv~<vbnm,.qwer| |uiop", "pigs,eat dogs;eat Bob:eat pigs", "looc si siht,gnitirw esreveR"}; StringCases[#, RegularExpression["[A-Za-z](?![A-Za-z])"]] <> "" & /@ l ``` > > {"flvmrp", "flvmrp", "ststbts", "citwR"} > > > [Answer] # Python 2, 88 80 75 69 68 ``` s=p='' for c in raw_input()+' ':a=c.isalpha();s+=p[a:];p=c*a print s ``` Input: `435_ASDC__uio;|d re;fG o55677jkl..f` Output: `CodeGolf` --- This solution can be shortened to **67** characters if you allow the output to include backspace characters (ASCII code 8) at the beginning. The output will be visually identical. ``` s=p='<BS>' for c in raw_input()+p:a=c.isalpha();s+=p[a:];p=c*a print s ``` Same input, (visually) same output. `<BS>` is meant to be the backspace character. [Answer] **Smalltalk**, Squeak/Pharo flavour **122** char with traditional formatting for this method added to String: ``` endOfWords ^(self subStrings: (CharacterSet allCharacters select: #isLetter) complement) collect: #last as: String ``` **62** chars in Pharo 1.4, with regex and weird formatting ``` endOfWords^''join:(self regex:'[a-zA-Z]+'matchesCollect:#last) ``` [Answer] # J: 60 characters (or 38 characters for a less correct version) ``` (#~e.&(,26&{.&(}.&a.)"0(97 65))){:&>;:]`(' '"_)@.(e.&'_:')"0 ``` If we're willing let the program break whenever there are words ending in a colon or an underscore, then we can simplify this to 38 characters. ``` (#~e.&(,26&{.&(}.&a.)"0(97 65))){:&>;: ``` Sample run: ``` (#~e.&(,26&{.&(}.&a.)"0(97 65))){:&>;:]`(' '"_)@.(e.&'_:')"0'asdf jkl;__zxcv~< vbnm,.qwer| |uiop' flvmrp (#~e.&(,26&{.&(}.&a.)"0(97 65))){:&>;:]`(' '"_)@.(e.&'_:')"0'pigs, eat dogs; eat Bob: eat pigs' ststbts (#~e.&(,26&{.&(}.&a.)"0(97 65))){:&>;:]`(' '"_)@.(e.&'_:')"0'99_bottles_of_beer_on_the_wall' sfrnel ``` [Answer] # **C#** Method, **105** bytes: (assumes usings for System, System.Text.RegularExpressions and System.Linq) ``` string R(string i){return string.Concat(Regex.Split(i,"[^a-zA-Z]").Where(x=>x!="").Select(n=>n.Last()));} ``` Program, **211** bytes: ``` using System;using System.Text.RegularExpressions;using System.Linq;class A{static void Main(){Console.WriteLine(string.Concat(Regex.Split(Console.ReadLine(),"[^a-zA-Z]").Where(x=>x!="").Select(n=>n.Last())));}} ``` [Answer] ## VBA, 147 161 ``` Sub a(s) For n=0 To 255:m=Chr(n):s=Replace(s,IIf(m Like"[A-Za-z]","",m)," "):Next For Each r In Split(s," "):t=t & Right(r,1):Next MsgBox t End Sub ``` ]
[Question] [ We are all familiar with the famous [Fibonacci sequence](https://en.wikipedia.org/wiki/Fibonacci_number), that starts with `0` and `1`, and each element is the sum of the previous two. Here are the first few terms (OEIS [A000045](http://oeis.org/A000045)): ``` 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584 ``` --- Given a *positive integer*, return the closest number of the Fibonacci sequence, under these rules: * The *closest Fibonacci number* is defined as the Fibonacci number with the smallest absolute difference with the given integer. For example, `34` is the closest Fibonacci number to `30`, because `|34 - 30| = 4`, which is smaller than the second closest one, `21`, for which `|21 - 30| = 9`. * If the given integer belongs to the Fibonacci sequence, the closest Fibonacci number is exactly itself. For example, the closest Fibonacci number to `13` is exactly `13`. * In case of a tie, you may choose to output either one of the Fibonacci numbers that are both closest to the input or just output them both. For instance, if the input is `17`, all of the following are valid: `21`, `13` or `21, 13`. In case you return them both, please mention the format. [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. You can take input and provide output through [any standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Your program / function must only handle values up to 108. --- # Test Cases ``` Input -> Output 1 -> 1 3 -> 3 4 -> 3 or 5 or 3, 5 6 -> 5 7 -> 8 11 -> 13 17 -> 13 or 21 or 13, 21 63 -> 55 101 -> 89 377 -> 377 467 -> 377 500 -> 610 1399 -> 1597 ``` --- # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes *in every language* wins! [Answer] # [Python 2](https://docs.python.org/2/), 43 bytes ``` f=lambda n,a=0,b=1:a*(2*n<a+b)or f(n,b,a+b) ``` [Try it online!](https://tio.run/##dZAxa8MwEIV3/4ojEJAapdihU1oP6VDo0KlDCyGEsy0lwsrZyDZNfr0rKQ52A/Vine7dd3qvvrTHilZ9r1KDp6xAIIFpLLI0WeMDWz3QCy4yXllQjEQmfNEXUoHStmn3SmcNK/k6AjDpdud@bvjZDbuTckN70AQW6SAHldM9Yl1LKhjyUKPbFbiusrLtLIGJorf3109Ip1ueYh5FfnN@lHm5J4lWXntMCaBAzw3qkyxuTQ9gxCeNQodbQAe8Fy8hSL2HvO3QTCgnTcy/SJTycsupXHtIuSTOx5GB7zt3kJE@mPz7pHRK8LrRqeoo9xY/Nt9pErsvWPXp0phuEvqLZAjZreyMf8k/YQWRVkBVO2ivcwC11dTC7MtWdACk5kdamDdh3byZwRyYj1QMCIDMSizdWZpGXhkDYWMM5JW1Mm9n3tD1esvOQrEz54F4nhpI4oTvoqln3v8C "Python 2 – Try It Online") Iterates through pairs of consecutive Fibonacci numbers `(a,b)` until it reaches one where the input `n` is less than their midpoint `(a+b)/2`, then returns `a`. Written as a program (47 bytes): ``` n=input() a=b=1 while 2*n>a+b:a,b=b,a+b print a ``` [Same length](https://tio.run/##dZAxa8MwEIV3/4ojEJAapbFDpxQP6VDo0KlDCyEEyZYSYeVsZJsmv96VZAe7gXixpHv33b1XXZtTieuuU6nhZ5FzQMbTmIk02YjVeoVPRCw5LS0ogkwwvhC0y6UCpW3dHJQWNSnoJgIw6W7vfq751TW7k3JNB9AIluNRDiqne@ZVJTEnnIY7d7MC192sbFqLYKLo/ePtC9LplJeYRpGfnJ1kVhxQciv7GlEMMNAzw/VZ5reiBxCkk0KuwytwB7wXLyFIvYesabmZUM4aid@IFfJ6y6nYeEixRErHloHvK3eQkT6Y/L9SOiV43ehUtZh5i5/bnzSJ3Res@nRxTDcJ9UUyhOxGtsZv8iCsINIKsGwGbd8HUFmNDcy@bYlH4Fj/SgvzOoyb1zOYA/GRsgEBIKzkhTtLU8ueMRC2xkBWWiuzZuYN9c87cmGKXCgNxMvUQBIndB9NPdPuDw): ``` f=lambda n,a=0,b=1:b/2/n*(b-a)or f(n,b,a+b) ``` [Answer] # [Neim](https://github.com/okx-code/Neim), 5 bytes ``` f𝐖𝕖S𝕔 ``` Explanation: ``` f Push infinite Fibonacci list 𝐖 93 𝕖 Select the first ^ elements This is the maximum amount of elements we can get before the values overflow which means the largest value we support is 7,540,113,804,746,346,429 S𝕔 Closest value to the input in the list ``` In the newest version of Neim, this can be golfed to 3 bytes: ``` fS𝕔 ``` As infinite lists have been reworked to only go up to their maximum value. [Try it online!](https://tio.run/##y0vNzP3/P@3D3AnTPsydOi0YSEz5/9/QHAA "Neim – Try It Online") [Answer] # [Python](https://docs.python.org/3/), ~~55~~ 52 bytes ``` f=lambda x,a=1,b=1:[a,b][b-x<x-a]*(b>x)or f(x,b,a+b) ``` [Try it online!](https://tio.run/##FcqxDoIwFEDR/X3FG6mWhCdIAxE3XF3cCEOrJZAgNKXE8vUVxntzzOb6ebqE0FWj/KqPRM9lRVxVVDaSq7ZRsb/5WLanSN09my12keeKy7NiwdmtBMRfP4waX3bVRyEaO0xud8NkVhcxBtq/tXFYPx@1tbM9lJHLEghSyCAHAURAAvIUKNmnEJDlAq5JApQWxR8 "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~70~~ ~~67~~ ~~64~~ ~~62~~ 60 bytes *-2 bytes thanks to djhurio!* *-2 more bytes thanks to djhurio* (boy can he golf!) ``` F=1:0;while(F<1e8)F=c(F[1]+F[2],F);F[order((F-scan())^2)][1] ``` Since we only have to handle values up to `10^8`, this works. [Try it online!](https://tio.run/##K/r/383W0MrAOs@2ODkxT0PTujwjMydVI8/OTdPNNlnDLdowVtst2ihWx03T2i06vygltUhDw003TzPOSDMWKPnf2Nz8PwA "R – Try It Online") Reads `n` from stdin. the `while` loop generates the fibonacci numbers in `F` (in decreasing order); in the event of a tie, the larger is returned. This will trigger a number of warnings because `while(F<1e8)` only evaluates the statement for the first element of `F` with a warning Originally I used `F[which.min(abs(F-n))]`, the naive approach, but @djhurio suggested `(F-n)^2` since the ordering will be equivalent, and `order` instead of `which.min`. `order` returns a permutation of indices to put its input into increasing order, though, so we need `[1]` at the end to get only the first value. ### faster version: ``` F=1:0;n=scan();while(n>F)F=c(sum(F),F[1]);F[order((F-n)^2)][‌​1] ``` only stores the last two fibonacci numbers [Answer] ## JavaScript (ES6), 41 bytes ``` f=(n,x=0,y=1)=>y<n?f(n,y,x+y):y-n>n-x?x:y ``` ``` <input type=number min=0 value=0 oninput=o.textContent=f(this.value)><pre id=o>0 ``` Rounds up by preference. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 7 bytes -2 bytes thanks to @EriktheOutgolfer ``` ‘RÆḞạÐṂ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw4ygw20Pd8x7uGvh4QkPdzb9P9x@dNLDnTNUHjWtifz/P9pQh8tYh8tEh8tMh8tch8sQyDcE0mZAQUMDkKQ5kGdiBiRMDQyAYsaWlrEA "Jelly – Try It Online") Golfing tips welcome :). Takes an int for input and returns an int-list. ``` ' input -> 4 ‘ ' increment -> 5 R ' range -> [1,2,3,4,5] ÆḞ ' fibonacci (vectorizes) -> [1,1,2,3,5,8] ÐṂ ' filter and keep the minimum by: ạ ' absolute difference -> [3,3,2,1,1,4] ' after filter -> [3,5] ``` [Answer] # Mathematica, 30 bytes ``` Array[Fibonacci,2#]~Nearest~#& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvvfsagosTLaLTMpPy8xOTlTx0g5ts4vNbEotbikTlntf0BRZl6JgkOagoOhsaXlfwA "Mathics – Try It Online") [Answer] # x86-64 Machine Code, 24 bytes ``` 31 C0 8D 50 01 92 01 C2 39 FA 7E F9 89 D1 29 FA 29 C7 39 D7 0F 4F C1 C3 ``` The above bytes of code define a function in 64-bit x86 machine code that finds the closest Fibonacci number to the specified input value, `n`. The function follows the [System V AMD64 calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI) (standard on Gnu/Unix systems), such that the sole parameter (`n`) is passed in the `EDI` register, and the result is returned in the `EAX` register. **Ungolfed assembly mnemonics:** ``` ; unsigned int ClosestFibonacci(unsigned int n); xor eax, eax ; initialize EAX to 0 lea edx, [rax+1] ; initialize EDX to 1 CalcFib: xchg eax, edx ; swap EAX and EDX add edx, eax ; EDX += EAX cmp edx, edi jle CalcFib ; keep looping until we find a Fibonacci number > n mov ecx, edx ; temporary copy of EDX, because we 'bout to clobber it sub edx, edi sub edi, eax cmp edi, edx cmovg eax, ecx ; EAX = (n-EAX > EDX-n) ? EDX : EAX ret ``` **[Try it online!](https://tio.run/##dVDRaoMwFH33K4JjoFJHbGxU3ApD508se5BobaCNQ@MIjP363E3b9SkJhJOce87l3MvjgfN15aOcFeLHdkI6p9XY9e8f6AX5TJOE6QoznddM7wAx/IvtFStAUjDdvDKdvQHCO4dbQ2174w1W2VVXA@KG6RRuZfzEL71ZtUpwtMhZDLLvUBBBgkbLMPinQkhyS1WuD0Ly09L16HlWnRifjnvPE1KhcytkYB7tNPDNZZQoMp@v0Pv2EJzPCcqHwL@2D5KQqXjP1GPHpL9BdzYsbWpiVROHOrWqU4eaWtXUoc6s6syhThxjuuZM7O0TV39qXwx1bSbBjkDYufnMHsnwju1Tu8PwdscOY6vD8I45SFHYBzEF8FxMU6@WSSJcej/rLz@c2mFe4zNN/wA "C (gcc) – Try It Online")** The code basically divides up into three parts: * The first part is very simple: it just initializes our working registers. `EAX` is set to 0, and `EDX` is set to 1. * The next part is a loop that iteratively calculates the Fibonacci numbers on either side of the input value, `n`. This code is based on [my previous implementation of Fibonacci with subtraction](https://codegolf.stackexchange.com/questions/131513/fibtraction-fibonacci-but-with-subtraction/131706#131706), but…um…isn't with subtraction. :-) In particular, it uses the same trick of calculating the Fibonacci number using two variables—here, these are the `EAX` and `EDX` registers. This approach is *extremely* convenient here, because it gives us adjacent Fibonacci numbers. The candidate potentially *less than* `n` is held in `EAX`, while the candidate potentially *greater than* `n` is held in `EDX`. I'm quite proud of how tight I was able to make the code inside of this loop (and even more tickled that I re-discovered it independently, and only later realized how similar it was to the subtraction answer linked above). * Once we have the candidate Fibonacci values available in `EAX` and `EDX`, it is a conceptually simple matter of figuring out which one is closer (in terms of absolute value) to `n`. Actually taking an absolute value would cost *way* too many bytes, so we just do a series of subtractions. The comment out to the right of the penultimate conditional-move instruction aptly explains the logic here. This either moves `EDX` into `EAX`, or leaves `EAX` alone, so that when the function `RET`urns, the closest Fibonacci number is returned in `EAX`. In the case of a tie, the *smaller* of the two candidate values is returned, since we've used `CMOVG` instead of `CMOVGE` to do the selection. It is a trivial change, if you'd prefer the other behavior. Returning *both* values is a non-starter, though; only one integer result, please! [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~80~~ 74 bytes ``` param($n)for($a,$b=1,0;$a-lt$n;$a,$b=$b,($a+$b)){}($b,$a)[($b-$n-gt$n-$a)] ``` (Try it online! temporarily unresponsive) Iterative solution. Takes input `$n`, sets `$a,$b` to be `1,0`, and then loops with Fibonacci until `$a` is larger than the input. At that point, we index into `($b,$a)` based on Boolean of whether the difference between the first element and `$n` is greater than between `$n` and the second element. That's left on the pipeline, output is implicit. [Answer] ## JavaScript (ES6), 67 bytes ``` f=(n,k,y)=>(g=k=>x=k>1?g(--k)+g(--k):k)(k)>n?x+y>2*n?y:x:f(n,-~k,x) ``` ### Test cases ``` f=(n,k,y)=>(g=k=>x=k>1?g(--k)+g(--k):k)(k)>n?x+y>2*n?y:x:f(n,-~k,x) console.log(f(1 )) // -> 1 console.log(f(3 )) // -> 3 console.log(f(4 )) // -> 3 or 5 or 3, 5 console.log(f(6 )) // -> 5 console.log(f(7 )) // -> 8 console.log(f(11 )) // -> 13 console.log(f(17 )) // -> 13 or 21 or 13, 21 console.log(f(63 )) // -> 55 console.log(f(101 )) // -> 89 console.log(f(377 )) // -> 377 console.log(f(467 )) // -> 377 console.log(f(500 )) // -> 610 console.log(f(1399)) // -> 1597 ``` [Answer] # [JavaScript (Babel Node)](https://babeljs.io/), 41 bytes ``` f=(n,i=1,j=1)=>j<n?f(n,j,j+i):j-n>n-i?i:j ``` Based on [ovs's awesome Python answer](https://codegolf.stackexchange.com/a/133381/53880) [Try it online!](https://tio.run/##DchRCoAgDADQ6zhygV@BpJ5FTWNDZmR0fet9Po5vHPmm68EUU2ko/ShzVqdEkzOanQHneZdQ/2HNC4FlFC9IgSzP3GX0VtbWT1WV2QDmBw "JavaScript (Babel Node) – Try It Online") ### Ungolfed ``` f=(n,i=1,j=1)=> // Function f: n is the input, i and j are the most recent two Fibonacci numbers, initially 1, 1 j<n? // If j is still less than n f(n,j,j+i) // Try again with the next two Fibonacci numbers : // Else: j-n>n-i?i:j // If n is closer to i, return i, else return j ``` [Answer] # Python, 74 bytes ``` import math r=5**.5 p=r/2+.5 lambda n:round(p**int(math.log(n*2*r,p)-1)/r) ``` [Try it online!](https://tio.run/##FY1BDoMgEADvvIIj0K26IhJNfEnbg42xmshCNvTQ11Od48xh0i9vkWxZp2c55vBeZkkjxy8tKhmzU1Zhzlt1xI8i0xqGpO@oa9ZiDylyllcWPDljKifSxHV7q1xZI0uSO8kHgoUOevCACOiht4DNKb2HrvfgmgbQDsNrFPIk8bUkWBVpXf4 "Python 3 – Try It Online") ### How it works For all *k* ≥ 0, since |φ−*k*/√5| < 1/2, *F**k* = φ*k*/√5 + φ−*k*/√5 = round(φ*k*/√5). So the return value switches from *F**k* − 1 to *F**k* exactly where *k* = logφ(*n*⋅2√5) − 1, or *n* = φ*k* + 1/(2√5), which is within 1/4 of *F**k* + 1/2 = (*F**k* − 1 + *F**k*)/2. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` nÅFs.x ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/73CrW7Fexf//JgA "05AB1E – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~86~~ ~~85~~ ~~83~~ 76 bytes ``` f(n){n=n<2?:f(n-1)+f(n-2);}i,j,k;g(n){for(;k<n;j=k,k=f(i++));n=k-n<n-j?k:j;} ``` [Try it online!](https://tio.run/##ZdDRboMgFAbge5/CNFkCERKOKMyi64vsZnHRKBldTO8an92CZdiBFxzFT/zP6enY99s2IIPvpjNteTnbewq4cKXEap3ITLQaHRiuC1K6NWruNNHdgKaiwFiZTlPTGjpf9HlW6/bzNRmEs3uW2@t3mcxtQCdwD/Qjh/zt@9OcyIjAfvqPcE94IDwmVSDXJa/dwomtf76KvfD@ICIm0pP3QGRMAHz2Ixkk6UEGZGOV4Faw6cqXjpOTBff5XgImTQODZ8LmOIml05PyORpbw/xk8sdKpMzuxaxmbGcCWGB2L4nGm2Zvum72OR4B7QuH12x7AA "C (gcc) – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~60~~ ~~57~~ 56 bytes ``` c->{int s=1,r=2;for(;c>r;s=r-s)r+=s;return c-s>r-c?r:s;} ``` [Try it online!](https://tio.run/##RY8xb8IwEIV3fsWNiepESaEgYoVOHTpUDKhT1cF1HGoaztH5goQQvz09Cm3fcL57lv2@25mDyULvcNd8jf3w0XkLtjMxwovxCKcJiCIbFr/1aDrYyYt8YN/l7YCWfcD8GfkVDR3XvSPDgQChHm22OnlkiHWpqL7XbaBE2xXpWFMWU7qroybHAyHYLK4os49URX0e9U/mjeUWfQi@gb0QJRsmj9u3dzC0jekN8KJ/rsjkzP5Ctbl2oU1KBVMFMwVzBQsFpcylnHMxy@JyuZBpNpfyUBTiTZfL9O/rX@V70yeY5rLKk7Gfa2ocuSbZHCM7SRm4qnqh4w7T6xLnyXkyfgM "Java (OpenJDK 8) – Try It Online") -1 byte thanks to @Neil [Answer] # [Python 3](https://docs.python.org/3/), 103 bytes ``` import math def f(n):d=5**.5;p=.5+d/2;l=p**int(math.log(d*n,p))/d;L=[l,p*l];return round(L[2*n>sum(L)]) ``` [Try it online!](https://tio.run/##FY5BDoMgEEXX7SkmroBOVVRq1NgTeAPjognSkigQioue3sLiv8n8@T8Z9wsfa@rz1LuzPsD@Cp@rXBUoYmgvR8FYLgY35uImi2rYRseYNoGkXL7ZN5HMoKO0kMM0zhs6ti2DX8PhDXh7GEmmuWLm@T12MtGFnsp60KANzByhRmgQHggtAo87j7OKapIbj20ZlfwygTcJIiFW6jYFHxGijDFed93SXy/Op/c0ZvdnhopoSs8/ "Python 3 – Try It Online") Sadly, had to use a def instead of lambda... There's probably much room for improvement here. Original (incorrect) answer: # ~~[Python 3](https://docs.python.org/3/), 72 bytes~~ ``` lambda n:r(p**r(math.log(d*n,p))/d) import math d=5**.5 p=.5+d/2 r=round ``` [Try it online!](https://tio.run/##FYnBDoMgEAXP5Ss2noBurVTRaEJ/pO3BhlhJFMiGHvr1FC/vZWbiL63Bt3kxz7zN@9vO4CfiUUri@5zWegsfbqXHKMTVCub2GCjBkZg1Wspas2hqfbbXGyND4ettXgKBA@fhoRBahA6hRxgQVGFVvi9SNUccCnV9Gd00xbXj@JrYKZLziTusLvcKF@6EyH8 "Python 3 – Try It Online") My first PPCG submission. Instead of either calculating Fibonacci numbers recursively or having them predefined, this code uses how the n-th Fibonacci number is the nearest integer to the n-th power of the golden ratio divided by the root of 5. [Answer] # Taxi, 2321 bytes ``` Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Trunkers.Go to Trunkers:n 1 l 1 l.0 is waiting at Starchild Numerology.1 is waiting at Starchild Numerology.Go to Starchild Numerology:w 1 l 2 l.Pickup a passenger going to Bird's Bench.Pickup a passenger going to Cyclone.Go to Cyclone:w 1 r 4 l.[a]Pickup a passenger going to Rob's Rest.Pickup a passenger going to Magic Eight.Go to Bird's Bench:n 1 r 2 r 1 l.Go to Rob's Rest:n.Go to Trunkers:s 1 l 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:w 2 r.Pickup a passenger going to Trunkers.Pickup a passenger going to Magic Eight.Go to Zoom Zoom:n.Go to Trunkers:w 3 l.Go to Magic Eight:e 1 r.Switch to plan "b" if no one is waiting.Pickup a passenger going to Firemouth Grill.Go to Firemouth Grill:w 1 r.Go to Rob's Rest:w 1 l 1 r 1 l 1 r 1 r.Pickup a passenger going to Cyclone.Go to Bird's Bench:s.Pickup a passenger going to Addition Alley.Go to Cyclone:n 1 r 1 l 2 l.Pickup a passenger going to Addition Alley.Pickup a passenger going to Bird's Bench.Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l.Switch to plan "a".[b]Go to Trunkers:w 1 l.Pickup a passenger going to Cyclone.Go to Bird's Bench:w 1 l 1 r 1 l.Pickup a passenger going to Cyclone.Go to Rob's Rest:n.Pickup a passenger going to Cyclone.Go to Cyclone:s 1 l 1 l 2 l.Pickup a passenger going to Sunny Skies Park.Pickup a passenger going to What's The Difference.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 1 l.Pickup a passenger going to Magic Eight.Go to Sunny Skies Park:e 1 r 1 l.Go to Cyclone:n 1 l.Pickup a passenger going to Sunny Skies Park.Pickup a passenger going to What's The Difference.Go to Sunny Skies Park:n 1 r.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 1 r 1 l.Pickup a passenger going to Magic Eight.Go to Magic Eight:e 1 r 2 l 2 r.Switch to plan "c" if no one is waiting.Go to Sunny Skies Park:w 1 l 1 r.Pickup a passenger going to The Babelfishery.Go to Cyclone:n 1 l.Switch to plan "d".[c]Go to Cyclone:w 1 l 2 r.[d]Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 2 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r. ``` [Try it online!](https://tio.run/##tVZNj9owEP0rIy69RYXtZXNb2u2etkVLpUpFHIzjJCOMjWxHaX49deLAJg7kA3UPECX2zLw3b2ZsQ/7i6fQiwUhYSW3gZxwjZWEOc@D2p8pnsEK6z45A4Ei0ZiJhChKJIimtfqUMlmTHeIw6ZaoInDP/c6jPHvu9qUzsmdJnL/VrKGprHnwG1JATNKUFMbA2RNEUeQQ/sgNTksukCOZjNrkQ15Zq@osB6ktU0ScNSyZo2rvxa0G5FKyOWL9VQRR8sUE2ZNtn/iZ3Nswb06Y3yitJkMIzJqmpIzUBVilUlpOT1G149xwKP@VnwYZFu0VvMVbsaaz@SHmo/rqYc3i4cGsYhqzisM7R0LRcO3IiYLabAcYgJFi4jYLphfMdFTvIzKTwopCfY3lfnbTdHLe6qn5OSW1Lz/60PUWRJSMFPHHOCk8accEwVOKem9Hd4OK1rW3YxWTKTchuAPgqklmw2W07hTA0t3oyO374tZ20umk6xfeGG1JlnQlRwHqPTMOKqH3v5t8pMRZWOZC/YRwzZTmyOywc2KtrTp2JbeyTcE3aGE4t6T86HzcwicFyvS9Z6o6EdQZaWSfVkPVbgt4YbDdI5uOO5usHfVslH0lkm5Nuu@eew72Jtv/vajFmtjSuOEH30iMueTid5g@Pj/8A) [Try it online with comments!](https://tio.run/##vVffT9tIEH7nrxjxUmghEHJ3UtMDqVwvFQ@lqKl00kU8rO1xPIqzm9td100Rfzs3u/6BY0KcoKoSJHF2d@ab@b6Z2VjxnR4eJjAiGYFNkD8ESoowJJDZPEANYaoMGgtW@XWSi8zC7d4ErqRZkMYIguUQEmsXZnhyEqoIpyqNe8aKcIbfw0TIKfZCNT/576Q/GAz@@J0P7/FxCecw/vrh6pqfPypn/kaxm89xTCEOc@hDyv/avff2biicZQsQsBDGIFvUMFUkp@7YV0Z1KQJMYzIJ6mWvNNf@fmgqmx32dCZnqE1tp3weyvI849nz8ZMlkdIPhJxsAqPT81MQnMZR/7zPQZ0CGcgFb2K7wsLYCh0mlEZwnc1Rq1RNGWt/q10FknVrZabOurJ0STp6ZeASZZhs3vnXkimXWDktH70fDb9V0Y@UhgNiDvvvmMoLGB3Q4TugN28O4Y6BKo3@KxfSFxWw5y9ORD49B3Tc9wtNTHDvRCVuN0J7tLQ5hE9iSiH8TdPEVmE0fXkmNeesVFex49H4UD7hvtLOFvp5Nn9n2ytvx@D@VWruX9Ygz2HwGGPj7BCLUMYsXk4/Ly5SIWE/2AeKQSpg0A1t9oqavTgvaDUKyKIWlvfAZtJG3CTmKuMK@agpraG0vi70tYaLlU5Qvu/GwAr1Hcl9H0UcrpLwPk1x2eZQ1jg6661taPvaLFyunmfPZy@IvIm77FxtusW@r@fAdXTP7AWznCfEe@YopKk59zXL5ZsjSOSuzxZimmZc50xieYLl4seF9jsXmqRlmdw@lWRnU99E4Q6zoWVmtcRfkMjHNtApgHEm5RLGM0IDN0LPNu/@JxGWobmZ9YHiGDVHii86MmFv5V4eWUfAfyV7FQ9rDxYa2aHzPPFz3HLTTkDRcJodd0WevyCbK5BrwFV@jgr9Pwtfdpff7n75VW5BTJm2TYaOZUcfXjM3nowDJ@tiTrX7RLhhLFzVC7moV47cdVHCXYXyHv6EuwLovRsf3Ec02kxL6NJNvuW97Zl7YEtl7cAi1wAnoet/nxmxzslgEzV3v2dhH/qL8LWyOHRJ4LWIIvnKgll1Eh65NWN5zsGiCMGfDrhzltHnbi1Af8d@HZM29nUjyLLxKpkuKwMu3XyHakfdQHSJocg4GBVDovIm2ZArPTMelPcr0lwszUpgJD0U/Ibcw9mCAEtYc9S8FJaCmUS3P/OavtW4a/xi6K35ESFr4Tw89Adv3/4P) Un-golfed with comments: ``` [ Find the Fibonacci number closest to the input ] [ Inspired by: https://codegolf.stackexchange.com/q/133365 ] [ n = STDIN ] Go to Post Office: west 1st left 1st right 1st left. Pickup a passenger going to The Babelfishery. Go to The Babelfishery: south 1st left 1st right. Pickup a passenger going to Trunkers. Go to Trunkers: north 1st left 1st left. [ Initialize with F0=0 and F1=1 ] 0 is waiting at Starchild Numerology. 1 is waiting at Starchild Numerology. Go to Starchild Numerology: west 1st left 2nd left. Pickup a passenger going to Bird's Bench. Pickup a passenger going to Cyclone. Go to Cyclone: west 1st right 4th left. [ For (i = 1; n > F(i); i++) { Store F(i) at Rob's Rest and F(i-1) at Bird's Bench } ] [a] Pickup a passenger going to Rob's Rest. Pickup a passenger going to Magic Eight. Go to Bird's Bench: north 1st right 2nd right 1st left. Go to Rob's Rest: north. Go to Trunkers: south 1st left 1st left 1st right. Pickup a passenger going to Cyclone. Go to Cyclone: west 2nd right. Pickup a passenger going to Trunkers. Pickup a passenger going to Magic Eight. Go to Zoom Zoom: north. Go to Trunkers: west 3rd left. Go to Magic Eight: east 1st right. Switch to plan "b" if no one is waiting. [ n >= F(i) so iterate i ] Pickup a passenger going to Firemouth Grill. Go to Firemouth Grill: west 1st right. Go to Rob's Rest: west 1st left 1st right 1st left 1st right 1st right. Pickup a passenger going to Cyclone. Go to Bird's Bench: south. Pickup a passenger going to Addition Alley. Go to Cyclone: north 1st right 1st left 2nd left. Pickup a passenger going to Addition Alley. Pickup a passenger going to Bird's Bench. Go to Addition Alley: north 2nd right 1st right. Pickup a passenger going to Cyclone. Go to Cyclone: north 1st left 1st left. Switch to plan "a". [b] [ F(i) > n which means n >= F(i-1) and we need to figure out which is closer and print it] Go to Trunkers: west 1st left. Pickup a passenger going to Cyclone. Go to Bird's Bench: west 1st left 1st right 1st left. Pickup a passenger going to Cyclone. Go to Rob's Rest: north. Pickup a passenger going to Cyclone. Go to Cyclone: south 1st left 1st left 2nd left. Pickup a passenger going to Sunny Skies Park. Pickup a passenger going to What's The Difference. Pickup a passenger going to What's The Difference. [ Passengers:n, n, F(i-1) ] Go to What's The Difference: north 1st left. Pickup a passenger going to Magic Eight. [ Passengers:n, n-F(i-1) ] Go to Sunny Skies Park: east 1st right 1st left. Go to Cyclone: north 1st left. Pickup a passenger going to Sunny Skies Park. Pickup a passenger going to What's The Difference. [ Passengers: n-F(i-1), F(i-1), F(i) ] Go to Sunny Skies Park: north 1st right. Pickup a passenger going to What's The Difference. [ Passengers: n-F(i-1), F(i), n ] Go to What's The Difference: north 1st right 1st left. [ Passengers: n-F(i-1), F(i)-n ] Pickup a passenger going to Magic Eight. Go to Magic Eight: east 1st right 2nd left 2nd right. Switch to plan "c" if no one is waiting. [ If no one was waiting, then {n-F(i-1)} < {F(i)-n} so we return F(i-1) ] Go to Sunny Skies Park: west 1st left 1st right. Pickup a passenger going to The Babelfishery. Go to Cyclone: north 1st left. Switch to plan "d". [c] [ Otherwise {n-F(i-1)} >= {F(i)-n} so we return F(i) ] [ Note: If we didn't switch to plan c, we still pickup F(i) but F(i-1) will be the *first* passenger and we only pickup one at The Babelfishery ] [ Note: Because of how Magic Eight works, we will always return F(i) in the event of a tie ] Go to Cyclone: west 1st left 2nd right. [d] Pickup a passenger going to The Babelfishery. Go to The Babelfishery: south 1st left 2nd right 1st right. Pickup a passenger going to Post Office. Go to Post Office: north 1st left 1st right. ``` [Answer] # [Python 3](https://docs.python.org/3/), 84 bytes ``` lambda k:min(map(f,range(2*k)),key=lambda n:abs(n-k)) f=lambda i:i<3or f(i-1)+f(i-2) ``` [Try it online!](https://tio.run/##NcpBDsIgEIXhfU8xy0GnC4qxCbEnURc0FpwgU4Ld9PSIia5e/i8v79tzFVPDdKsvl@aHg2gTCyaX0VNxEhYcDlEpiss@/S5i3fxG6Rt3/o9s@WLWAh651@r4nUFV34SBBa6awBCcCM4EI4Furce77SAXlg2ZICArVT8 "Python 3 – Try It Online") It may work, but it's certainly not fast... Outputs `True` instead of `1`, but in Python these are equivalent. [Answer] # dc, 52 bytes ``` si1d[dsf+lfrdli>F]dsFxli-rlir-sdd[lild-pq]sDld<Dli+p ``` [Try it online!](https://tio.run/##S0n@b2xqgAn@F2capkSnFKdp56QVpeRk2rnFphS7VeRk6hblZBbpFqekROdk5qToFhTGFrvkpNi45GRqF/z/DwA "dc – Try It Online") Takes input at run using `?` Edited to assume top of stack as input value, -1 byte. Input is stored in register `i`. Then we put 1 and 1 on the stack to start the Fibonacci sequence, and we generate the sequence until we hit a value greater than `i`. At this point we have two numbers in the Fibonacci sequence on the stack: one that is less than or equal to `i`, and one that is greater than `i`. We convert these into their respective differences with `i` and then compare the differences. Finally we reconstruct the Fibonacci number by either adding or subtracting the difference to `i`. Oops, I was loading two registers in the wrong order and then swapping them, wasting a byte. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 63 56 bytes -1 byte thanks to @Neil -6 bytes thanks to @Nevay ``` n=>{int a=0,b=1;for(;b<n;a=b-a)b+=a;return n-a>b-n?b:a;} ``` [Try it online!](https://tio.run/##dc2xCsIwGATgvU@RscVWDC0tNU0dBCedHJz/xFgC9Q8mqSClzx7rbpbj4OM46QpprAqT0ziQ68d59WSJHME58poT58FrSd5G38kFNKbZnJwmlJ1Gn5M1ejLwgLyf106A73LBKXsYmzLRIQMuCsjEhgOzyk8WCRbQiwIPYg9sCSw5GnRmVNub1V6dNap0SGmW/YcyBlUM6hjQJjqJvpRNdFTVUaJl2/5sWcIX "C# (.NET Core) – Try It Online") [Answer] ## Q/KDB+, 51 bytes ``` {w where l=min l:abs neg[x]+w:{x,sum -2#x}/[x;0 1]} ``` [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 37 bytes ``` ?\=-${&"*.2}+".|'=='.@.&}1.!_|._}$_}{ ``` [Try it online!](https://tio.run/##y0itSEzPz6v8/98@xlZXpVpNSUvPqFZbSa9G3dZWXc9BT63WUE8xvkYvvlYlvrb6/39DQwA "Hexagony – Try It Online") ungolfed: ``` ? \ = - $ { & " * . 2 } + " . | ' = = ' . @ . & } 1 . ! _ | . _ } $ _ } { ``` Broken down: ``` start: ? { 2 ' * //set up 2*target number " ' 1 //initialize curr to 1 main loop: } = + //next + curr + last " - //test = next - (2*target) branch: <= 0 -> continue; > 0 -> return continue: { } = & //last = curr } = & //curr = next return: { } ! @ //print last ``` Like some other posters, I realized that when the midpoint of last and curr is greater than the target, the smaller of the two is the closest or tied for closest. The midpoint is at (last + curr)/2. We can shorten that because next is already last + curr, and if we instead multiply our target integer by 2, we only need to check that (next - 2\*target) > 0, then return last. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 22 bytes ``` ;I≜-.∧{0;1⟨t≡+⟩ⁱhℕ↙.!} ``` [Try it online!](https://tio.run/##AXQAi/9icmFjaHlsb2cy/3t3IiAtPiAidz/ihrDigoLhuol94bWQ/ztJ4omcLS7iiKd7MDsx4p@odOKJoSvin6nigbFo4oSV4oaZLiF9//9bMSwzLDQsNiw3LDExLDE3LDYzLDEwMSwzNzcsNDY3LDUwMCwxMzk5XQ "Brachylog – Try It Online") Really all I've done here is paste together Fatalize's classic [Return the closest prime number](https://codegolf.stackexchange.com/a/182381/85334) solution and my own [Am I a Fibonacci Number?](https://codegolf.stackexchange.com/a/190930/85334) solution. Fortunately, the latter already operates on the output variable; unfortunately, it also includes a necessary cut which has to be isolated for +2 bytes, so the only choice point it discards is `ⁱ`, leaving `≜` intact. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ò!gM ñaU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=8iFnTSDxYVU&input=MTM5OQ) [Answer] # Java 7, ~~244~~ 234 Bytes ``` String c(int c){for(int i=1;;i++){int r=f(i);int s=f(i-1);if(r>c && s<c){if(c-s == r-c)return ""+r+","+s;else if(s-c > r-c)return ""+r;return ""+s;}}} int f(int i){if(i<1)return 0;else if(i==1)return 1;else return f(i-2)+f(i-1);} ``` [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 6 bytes ``` }~F>R^ ``` [Try it online!](https://tio.run/##K6jMTv3/v7bOzS4o7v9/Q0MA "Pyke – Try It Online") ``` } - input*2 ~F - infinite list of the fibonacci numbers > - ^[:input] R^ - closest_to(^, input) ``` [Answer] # Common Lisp, 69 bytes ``` (lambda(n)(do((x 0 y)(y 1(+ x y)))((< n y)(if(<(- n x)(- y n))x y)))) ``` [Try it online!](https://tio.run/##JUxLCoNAFLtKEErzKMI8tA6C9C62Igg6I62LmY1X19d2k4T8XvP0WQ/OMa4Y4xsJU8CVigo1GnioQj2aCurM9B5143F3Dlq1rWCItNnSb9iKvR5QPmC0Xwp7ov32y3PoGYRWZIJDFmYob5ZnESE7hK85jexYmk5ilBFE/g050g9P) [Answer] # [Perl 6](https://perl6.org), 38 bytes ``` {(0,1,*+*...*>$_).sort((*-$_).abs)[0]} ``` [Test it](https://tio.run/##RY7PboJAEMbv8xRzwMo/kXGBLSGaXnvvzZpGYU1IEAi7Nm2MT9ZbX4zu4lr3MPntfPN9M70Ymmw8S4GfWVQWcPrGp7KrBK7HixuHFPqBH0WRv3E@vEh2g3Jdf2F4f5DeNt5dR@14UUIqXGNTt0K63u9PVHang7t8r4Kl/m11zk43X1tVgFn1pscL6Jt9i8HkLeDYDTZmsUHXqdv@rEJHfPWiVKLy8AKItURzmlW9EP/1EGU/1K064nyWVCZiVs21fot5zBVwHQn10xMEzBKD5E6oz0hNYSGmkNl2CtzSMxBZOwPidzSOFZlK2rgiyJh1pkAx3aw5MM5vaziHJHtwGscTZxQDsTyfQtOc/wE "Perl 6 – Try It Online") ``` { # bare block lambda with implicit parameter 「$_」 ( # generate Fibonacci sequence 0, 1, # seed the sequence * + * # WhateverCode lambda that generates the rest of the values ... # keep generating until * > $_ # it generates one larger than the original input # (that larger value is included in the sequence) ).sort( # sort it by ( * - $_ ).abs # the absolute difference to the original input )[0] # get the first value from the sorted list } ``` For a potential speed-up add `.tail(2)` before `.sort(…)`. In the case of a tie, it will always return the smaller of the two values, because `sort` is a stable sort. (two values which would sort the same keep their order) [Answer] # Pyth, 19 bytes ``` JU2VQ=+Js>2J)hoaNQJ ``` [Try it here](http://pyth.herokuapp.com/?code=JU2VQ%3D%2BJs%3E2J%29hoaNQJ&input=467&debug=0) ### Explanation ``` JU2VQ=+Js>2J)hoaNQJ JU2 Set J = [0, 1]. VQ=+Js>2J) Add the next <input> Fibonacci numbers. oaNQJ Sort them by distance to <input>. h Take the first. ``` [Answer] # Haskell, 48 bytes ``` (%)a b x|abs(b-x)>abs(a-x)=a|1>0=b%(a+b)$x (1%2) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/X0NVM1EhSaGiJjGpWCNJt0LTDsRIBDJsE2sM7Qxsk1Q1ErWTNFUq/ucmZuYp2CoUFGXmlSioKGgYqhppKpgaGPwHAA "Haskell – Try It Online") ]
[Question] [ **A simple one:** Take a list of positive integers as input and output the numbers modulus their 1-based index in the list. If the input integers are `{a, b, c, d, e, f, g}` then the output should be `{a%1, b%2, c%3, d%4, e%5, f%6, g%7}` where `%` is the modulus operator. --- **Test cases:** ``` 10 9 8 7 6 5 4 3 2 1 0 1 2 3 1 5 4 3 2 1 8 18 6 11 14 3 15 10 6 19 12 3 7 5 5 19 12 12 14 5 0 0 0 3 4 3 1 2 6 9 1 3 7 5 5 3 12 12 14 5 1 0 1 1 0 1 ``` [Answer] # [Haskell](https://www.haskell.org/), 20 bytes ``` ($[1..]).zipWith mod ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P81WQyXaUE8vVlOvKrMgPLMkQyE3P@V/bmJmnoKtQkFRZl6JgopCmkK0oYGOpY6FjrmOmY6pjomOsY6RjmHsfwA "Haskell – Try It Online") A trick to `flip` I learned from [a golf of Anders Kaseorg](https://codegolf.stackexchange.com/a/83883/20260). [Answer] # [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, 73 bytes ``` f={l=_this;r=[];i=0;while{i<count l}do{r=r+[(l select i)%(i+1)];i=i+1};r} ``` **Call with:** ``` numList = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]; hint format["%1\n%2", numList, numList call f]; ``` **Output:** [![](https://i.stack.imgur.com/Iu37K.jpg)](https://i.stack.imgur.com/Iu37K.jpg) [Answer] # [Python 2](https://docs.python.org/2/), 35 bytes ``` i=1 for x in input():print x%i;i+=1 ``` [Try it online!](https://tio.run/##DcI7CoAwEAXA3lO8RlB8hRv/Sk4ituI2SZAI8fTRYcIbL@9MzmqlOP2NBHX/8MSqXsOtLiKVumljJeddWmIhZmIiRmIgeqIjDCHHBw "Python 2 – Try It Online") Counts the index up manually, as per [a tip of mine](https://codegolf.stackexchange.com/a/40791/20260). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` %J ``` [Try it online!](https://tio.run/##y0rNyan8/1/V6////9GGBjoKCpZAbAHE5kBsBsSmQGwCxMZAbATEhrEA "Jelly – Try It Online") **Explanation:** ``` %J J List 1 .. len(input). This is results in a list of the indexes. % Modulo. ``` Basically, the code modulos the original list by the list of indexes. [Answer] # R, ~~24~~ 18 bytes ``` pryr::f(x%%seq(x)) ``` Evaluates to the function: ``` function (x) x%%seq(x) ``` Which uses `seq_along()` to create a vector of the same length as `x`, starting at 1, and then `%%` to take the modulo. Default behaviour of `seq` when presented with a vector is `seq(along.with = x)` which is the same output as `seq_along(x)`, but 6 bytes shorter. [Answer] # R, 27 bytes ``` x=scan();cat(x%%1:sum(1|x)) ``` saved 5 bytes thanks to @Jarko saved 4 more thanks to @Giuseppe saved 2 more thanks to @Taylor Scott Saved 2 more thanks to @returnbull [Answer] # [MATL](https://github.com/lmendo/MATL), ~~4~~, 3 bytes ``` tf\ ``` [Try it online!](https://tio.run/##BcG5AYAgEACwVTKCgPLMohY2VNqx/5l8z3oj1rwizrQx6DQqBzuFTLp/ "MATL – Try It Online") *One byte saved thanks to @LuisMendo!* [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 5 bytes ``` ⍳∘≢|⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHvZsfdcx41Lmo5lHXIqCQgqGBgoKlgoKFgoK5goKZgoKpgoKJgoKxgoKRgoIhVxpQwtACJGFoqGAIljA0BesBilgqGBqBlZqDtZlCRUAIqNIUqBlkAFAfAA "APL (Dyalog Unicode) – Try It Online") `⍳` the indices `∘` of `≢` the length of the argument `|` that modulus `⊢` the argument [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 19 bytes ``` ;ww.1I!@s%Ow;)Sow.$ ``` [Try it online!](https://tio.run/##Sy5Nyqz4/9@6vFzP0FPRoVjVv9xaMzi/XE/l/38LBUMLBQUzBUNDBUMTBQVjBUNTBUMDsIilgqERSETBXEHBFIQgIiAEVGkKAA "Cubix – Try It Online") ``` ; w w . 1 I ! @ s % O w ; ) S o w . $ . . . . . ``` [Watch It Run](https://ethproductions.github.io/cubix/?code=ICAgIDsgdwogICAgdyAuCjEgSSAhIEAgcyAlIE8gdwo7ICkgUyBvIHcgLiAkIC4KICAgIC4gLgogICAgLiAuCg==&input=OCAxOCAgNiAxMSAxNCAgMyAxNSAxMCAgNiAxOSAxMiAgMyAgNyAgNSAgNSAxOSAxMiAxMiAxNCAgNQ==&speed=10) A fairly straight forward implementation. * `1` push 1 to the stack to start the index * `I!@` get the integer input and halt if 0 * `s%Ow` swap the index up, mod, output result and change lane * `;)` remove result and increment index * `Sow` push 32, output space and change lane (heading down from o) * `$O` jump the output * `w;w` change lange, remove 32 from stack and change lane onto the `I` input [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` ā% ``` [Try it online!](https://tio.run/##MzBNTDJM/f//SKPq///RFjqGFjpmOoaGOoYmOsY6hqY6hgYgvqWOoRGQb65jCoQQHgiZ6JjGAgA "05AB1E – Try It Online") or [Try all tests](https://tio.run/##LYvBDYAgEASr8TcPFzmBWggPTWzBhKe92Rceicl@ZjOz2nHqGnfv432WwahVK4VMYseIbATUqBllvyQ0TxkuOhcUnJPL9tNcxDyaoQetfQ "05AB1E – Try It Online") ``` ā # Push the range(1, len(a) + 1) % # Mod each element in the input by the same one in this list ``` [Answer] ## Mathematica, 22 bytes ``` #&@@@Mod~MapIndexed~#& ``` One more Mathematica approach. [Answer] # [Starry](https://esolangs.org/wiki/Starry), ~~75~~ 70 bytes ``` +` , + + * + + + +* + * . + + .' ``` [Try it online!](https://tio.run/##VYpBEoAgDAPveUVuzoDDWAXF3@gX0IuvrxS8mOTQTXrdZymPKpv8QY701aRrBT@y2/WiTYF/2VcYVDMkY4UIJGKBJMhkvEPmyhtSdSdLRHoB) ### Explanation This is an infinite loop that keeps reading numbers from the input and increasing a counter initiallized at `1`. For each pair of input and counter, the modulus is computed and printed. To end the loop when input has been exhausted, the following trick is used. When no more input is available, trying to read one more number gives a `0`. Thus, we divide the read number by itself, and if it is `0` the program ends with an error. Else we discard the result and continue. ``` + Push 1. This is the initial value of the counter ` Mark label , Read number from input and push it. Gives 0 if no more input + Duplicate top of the stack + Duplicate top of the stack * Pop two numbers and push their division. Error if divisor is 0 + Pop (discard) top of the stack + Swap top two numbers + Duplicate top of the stack + Push 1 * Pop two numbers and push their sum. This increases the counter + Rotate stack down, to move increased counter to bottom * Pop two numbers and push their modulus . Pop a number and print it as a number + Push 10 + Duplicate top of the stack . Pop a number (10) and print it as ASCII character (newline) ' If top of the stack is non-zero (it is, namely 10) go to label ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes ``` l⟦₁;?↔z%ᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P@fR/GWPmhqt7R@1TalSfbh1wv//0YYGOpY6FjrmOmY6pjomOsY6RjqGsf@jAA "Brachylog – Try It Online") ### Explanation ``` l⟦₁ [1, ..., length(Input)] ;?↔z Zip the Input with that range %ᵐ Map mod ``` [Answer] # R, 22 bytes ``` pryr::f(x%%1:sum(x|1)) ``` R performs 1:length(x) before doing the modulus. [Answer] # [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 5 bytes `#äL¹%` [online interpreter](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=I-RMuSU=&in=KDEwICA5ICA4ICA3ICA2ICA1ICA0ICAzICAyICAxKQ==) # Explanation ``` # ; read the list from standard input äL ; push its length ¹ ; converted to 1-based range % ; point-wise modulo ; implicitly output list ``` --- # Itr, [4 bytes](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=I0y5JQ==&in=KDEwICA5ICA4ICA3ICA2ICA1ICA0ICAzICAyICAxKQ==) `#L¹%` The `ä` before the `L` is no-longer necessary in newer versions [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), ~~5~~ ~~4~~ 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` uVÄ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=dVbE&input=WzEwIDmgOKA3oDagNaA0oDOgMiAxXQ) -1 byte thanks to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions) [Answer] # [Python 2](https://docs.python.org/2/), 42 bytes ``` lambda l:[v%(i+1) for i,v in enumerate(l)] ``` [Try it online!](https://tio.run/##BcHLCoQgAAXQX7mbAWXuInsXzJdUCyMlwSzEgvl6O@f6p/0MZba/OXt9rJuGH6fnI9xXSdgzwvGBCzDhPkzUyQgvl3xFFxKsmFRBDERPdERLNERNVERJqEXmFw "Python 2 – Try It Online") [Answer] ## Haskell, 22 bytes ``` zipWith(flip mod)[1..] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P822KrMgPLMkQyMtJ7NAITc/RTPaUE8v9n9uYmaegq1CQVFmXomCikKaQrShgY6ljoWOuY6ZjqmOiY6xjpGOYex/AA "Haskell – Try It Online") Also: `flip(zipWith mod)[1..]`. [Answer] # Mathematica, 21 bytes ``` #~Mod~Range@Length@#& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvtfuc43P6UuKDEvPdXBJzUvvSTDQVntf0BRZl6JQ5qCQ7WFjoIhEJsBKUMgNtFRMAZSpkBsABG1BGIjsKi5joIpGMHEwBiow7T2PwA "Mathics – Try It Online") or **20 bytes** (by Martin) ``` #~Mod~Range@Tr[1^#]& ``` [Answer] # Excel VBA, ~~59~~ 46 Bytes ### Golfed Anonymous VBE Immediate window funtion that takes a space () delimited array string as input from range `[A1]` and output the numbers modulus their 1-based index in the starting list to the VBE immediate window ``` For Each n In Split([A1]):i=i+1:?n Mod i;:Next ``` Input / Output: ``` [A1]="10 9 8 7 6 5 4 3 2 1" ''# or manually set the value For Each n In Split([A1]):i=i+1:?n Mod i;:Next 0 1 2 3 1 5 4 3 2 1 ``` ### Old `Sub`routine version Subroutine that takes input as a passed array and outouts to the VBE immediate window. ``` Sub m(n) For Each a In n i=i+1 Debug.?a Mod i; Next End Sub ``` Input / Ouput: ``` m Array(10,9,8,7,6,5,4,3,2,1) 0 1 2 3 1 5 4 3 2 1 ``` ### Ungolfed ``` Option Private Module Option Compare Binary Option Explicit Option Base 0 ''# apparently Option Base 1 does not work with ParamArrays Public Sub modIndex(ParamArray n() As Variant) Dim index As Integer For index = LBound(n) To UBound(n) Debug.Print n(index) Mod (index + 1); Next index End Sub ``` Input / Output: ``` Call modIndex(10,9,8,7,6,5,4,3,2,1) 0 1 2 3 1 5 4 3 2 1 ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 2 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` ż% ``` [Try it online!](https://Not-Thonnu.github.io/run?code=%C5%BC%25&input=%5B10%2C%209%2C%208%2C%207%2C%206%2C%205%2C%204%2C%203%2C%202%2C%201%5D&flags=) #### Explanation ``` ż% # Implicit input $ # Vectorised modulo ż # List [1..length] # Implicit output ``` [Answer] # Rust, 46 bytes ``` |v|v.iter().zip(1..).map(|(n,i)|n%i).collect() ``` [Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&code=fn+main%28%29+%7B%0A++++let+solution%3A+fn%28%26%5Busize%5D%29+-%3E+Vec%3Cusize%3E+%3D+%7Cv%7C+v.iter%28%29.zip%281..%29.map%28%7C%28n%2C+i%29%7C+n+%25+i%29.collect%28%29%3B%0A++++%2F%2F+%7Cv%7Cv.iter%28%29.zip%281..%29.map%28%7C%28n%2Ci%29%7Cn%25i%29.collect%28%29%0A%0A++++assert_eq%21%28%0A++++++++solution%28%26%5B10%2C+9%2C+8%2C+7%2C+6%2C+5%2C+4%2C+3%2C+2%2C+1%5D%29%2C%0A++++++++vec%21%5B0%2C+1%2C+2%2C+3%2C+1%2C+5%2C+4%2C+3%2C+2%2C+1%5D%0A++++%29%3B%0A%0A++++assert_eq%21%28%0A++++++++solution%28%26%5B8%2C+18%2C+6%2C+11%2C+14%2C+3%2C+15%2C+10%2C+6%2C+19%2C+12%2C+3%2C+7%2C+5%2C+5%2C+19%2C+12%2C+12%2C+14%2C+5%5D%29%2C%0A++++++++vec%21%5B0%2C+0%2C+0%2C+3%2C+4%2C+3%2C+1%2C+2%2C+6%2C+9%2C+1%2C+3%2C+7%2C+5%2C+5%2C+3%2C+12%2C+12%2C+14%2C+5%5D%2C%0A++++%29%3B%0A%0A++++assert_eq%21%28solution%28%26%5B1%5D%29%2C+vec%21%5B0%5D%29%3B%0A%0A++++assert_eq%21%28solution%28%26%5B1%2C+1%5D%29%2C+vec%21%5B0%2C+1%5D%29%3B%0A%7D%0A) [Answer] # [CJam](https://sourceforge.net/p/cjam), 9 bytes ``` {_,,:).%} ``` Anonymous block that expects an array on the stack and replaces it by the output array. [**Try it online!**](https://tio.run/##S85KzP0fbaFgaKGgYKZgaKhgaKKgYKxgaKpgaAAWsVQwNAKJKJgrKJiCEEQEhIAqTWP/V8fr6Fhp6qnW/q8r@A8A "CJam – Try It Online") ### Explanation ``` { } e# Define block _ e# Duplicate , e# Length , e# Range, 0-based :) e# Add 1 to each entry .% e# Vectorized modulus ``` [Answer] # J, 9 bytes ``` >:@i.@#|[ ``` 1 ... n | original list `|` is mod [Answer] # JavaScript (ES6), 22 bytes ``` a=>a.map((x,y)=>x%++y) ``` [Answer] # AWK, 13 ``` {print $1%NR} ``` [Try it online](https://tio.run/##SyzP/v@/uqAoM69EQcVQ1S@o9v9/QwMuSy4LLnMuMy5TLhMuYy4jLkMA). [Answer] # tcl, 35 ``` lmap l $L {puts [expr $l%[incr i]]} ``` ## [demo](http://rextester.com/UVQG28963) [Answer] # GNU APL 1.2, 9 bytes ``` (⍳⍴R)|R←⎕ ``` APL operates from right to left, hence the parentheses. `R←⎕` assigns user input to vector `R`. `⍴R` gives the length of the vector; `⍳⍴R` gives a vector with all numbers from 1 to that length (so the indices). `|` is the mod operator (`a|b` yields `b%a`). APL operates on arrays, so the code snippet a vector containing each element from the user's input mod its index. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 22 bytes ``` a->[a[n]%n|n<-[1..#a]] ``` [Try it online!](https://tio.run/##LYvBCsIwEER/ZakIDUyKWxubgPZHwh72UilICKUXwX@PiQh7mDezL@u@2WcuKz2oqF2ixiTn9El3G3kYTipSNOfXu1eyC@V9S0eNXYOO1l6NAcXIFwR4zLjBYcIVI1jq4MG@dszg1rIDh8YBPFae67f7U7upOT@xCiKmfAE "Pari/GP – Try It Online") [Answer] # Pyth, 5 ``` .e%bh ``` [Online test](https://pyth.herokuapp.com/?code=.e%25bh&input=%5B10%2C%209%2C%208%2C%207%2C%206%2C%205%2C%204%2C%203%2C%202%2C%201%5D&debug=0). ``` hk # 1-based index of (implicit) lambda variable b # element % # element mod (1-based index) .e Q # enumerated map over (implicit) input ``` ]
[Question] [ **Problem:** You are making a new phone where people can type in specialized phone numbers, for example, `1-800-program`, and they would be converted automatically to a usable phone number, like `1-800-7764726` (for the previous example). Your program will recieve a string if any length with numbers, letters and dashes, and convert all the letters to their corresponding numbers. Here is a keypad, for reference: ![keypad](https://i.stack.imgur.com/7TKsb.png) **Rules:** * Your program will receive a string * It will process it and return/print another string * Any language is accepted * Since it is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code wins [Answer] ## Bash, 30 Edit: Thank you Doorknob for eliminating 3 chars ``` tr a-z 22233344455566677778889 ``` Example: ![](https://i.stack.imgur.com/RmNe7.png) [Answer] # C, ~~83~~ ~~78~~ ~~77~~ ~~65~~ ~~63~~ 62 ``` main(c){for(;~(c=getchar());putchar(c>96?20-c/122+5*c/16:c));} ``` <http://ideone.com/qMsIFQ> [Answer] # GolfScript, 24 chars ``` {.96>{,91,'qx'+-,3/`}*}% ``` Test input: ``` 0123456789-abcdefghijklmnopqrstuvwxyz ``` Test output: ``` 0123456789-22233344455566677778889999 ``` Explanation: * `{ }%` applies the code between the braces to each character of the input. * `.96>{ }*` executes the code between the inner braces if and only if the ASCII code of the character is greater than 96 (i.e. it is a lowercase letter). * The first `,` turns the character into a list of all characters with lower ASCII codes, and `91,'qx'+-` filters out all characters with ASCII codes less than 91, as well as the letters `q` and `x`, from the list. Thus, for example, the character `a` gets turned into the 6-character list `[\]^_``, while `z` gets turned into the 29-character list `[\]^_`abcdefghijklmnoprstuvwy`. * The second `,` counts the elements remaining in the list, and `3/` divides this count by three (rounding down). Finally, the ``` turns the resulting number (in the range 2 – 9) into a string. Thus, as per spec, hyphens and numbers are left unchanged, while lowercase letters are mapped into numbers according to the reference keypad diagram. The code will actually cleanly pass through all printable ASCII characters except for lowercase letters (which as mapped as described) and the characters `{`, `|` and `}` (which are mapped to the two-character string `10`). Non-ASCII 8-bit input will produce all sorts of weird numeric output. After all this, it's a bit disappointing that this only beats the [trivial bash solution](https://codegolf.stackexchange.com/a/21331) by just six chars. [Answer] # Javascript - 103 characters ``` alert(prompt().replace(/[a-z]/g,function(y){y=y.charCodeAt(0)-91;return y>27?9:y>24?8:y>20?7:~~(y/3)})) ``` [Answer] # Ruby, 75 chars ``` gets.chars{|c|$><<"22233344455566677778889999#{c}"[[*?a..?z].index(c)||-1]} ``` Uses the deprecated `chars` with block, and prints each letter individually with `$><<`. I also like `[[*?a..?z].index(c)||-1]`; it grabs the character corresponding to that letter of the alphabet if it's a letter, and the last character (which happens to be the test character unchanged) if not. # Ruby, 43 (or 35) chars Blatantly stealing from @ace ;) ``` puts gets.tr'a-z','22233344455566677778889' ``` Shave off 8 chars if I can run in IRB with the variable `s` as the string: ``` s.tr'a-z','22233344455566677778889' ``` [Answer] # C++ - 222 chars Longest solution so far: ``` #include<iostream> #include<string> #define o std::cout<< int main(){std::string s;std::cin>>s;for(int i=0;i<s.size();i++){int j=s[i]-97;if(j<0)o s[i];if(0<=j&j<15)o 2+j/3;if(14<j&j<19)o 7;if(18<j&j<22)o 8;if(21<j&j<26)o 9;}} ``` [Answer] # Frink, 92 A rather verbose language, I know. This checks 8 values instead of 26 without having to type out the compares. Can any of the above "222333444.." solutions be reduced in a similar way? Using built in structures, 107 ``` co=new OrderedList co.insertAll[charList["cfilosv{"]] println[input[""]=~%s/([a-z])/co.binarySearch[$1]+2/eg] ``` Using a custom recursive function, 92 ``` fn[x,a]:=x<=(charList["cfilosv{"])@a?a+2:fn[x,a+1] println[input[""]=~%s/([a-z])/fn[$1,0]/eg] ``` [Answer] # Python 2.7, 66 65 ### Anakata's Original ``` for c in raw_input():print'\b'+(`(ord(c)-97)/3+2-(c in('svyz'))`if c>'`'else c), ``` ### Further golfed ``` for c in input():print(ord(c)-91)/3-(c in('svyz'))if c>'`'else c, ``` I don't have enough reputation to comment on @anakata's answer, so I made a separate post here. I had the same idea (taking the ordinance modulus 3) but couldn't figure out how to print the right numbers for *s - z*. Anyways, the golf improvements I made: * changed `raw_input` to `input` * removed the extraneous `'\b'` and parentheses and single quotes * removed the `+2` offset and placed that in the original subtraction (97 - (3 \* 2) = 91) *Tested with the Python 2.7.6 interpreter. Assumes, per the rules, a string input.* [Answer] # [Scala](http://www.scala-lang.org/), 49 48 bytes ``` _.map(c=>if(c>96)(c/3.2+20).toChar min'9'else c) ``` [Try it online!](https://tio.run/##VczPasJAEMfxu08xeHGXMnEb658IBkpPQilCH6Bs1omJJps1u1Zb8dnj5CJ4m4Hv5@eNrnTXZHsyAT4pBGr92m6KxtLXqc74A7oEslsP787BdQCwpRzyJXyHtrQ7WKWPq/uJau2EWaVlLkyazKQw40kUv8RKRqH5KHQLdWlHyYgqT2BkB@CYhsqKXAx1Znh6V5T7Q1Xbxh1bH06/58vf/1DKwVOqlELOkXtkgCyQCfYGGWGvUCWL@Wz6Nolf@4Fbdwc "Scala – Try It Online") Maps `abcdefghijklmnopqrstuvwxyz` to `22233344455566677778889999` via `(c/3.2+20).toChar min'9'` (saved 1 byte thanks to Kevin Cruijssen) [Answer] # Smalltalk, 79 70 input is s: ``` s collect:[:c|' 22233344455566677778889999'at:1put:c;at:(($ato:$z)indexOf:c)+1] ``` probably not a candidate for being shortest - but may be of interest for an old trick to avoid a test for a not-found condition (indexOf: returns 0 in this case). So no special test for letters is needed. Some Smalltalks however, have immutable strings, and we need 4 more chars ("copy"). Oh, a better version, which even deals with immutable strings in 70 chars: ``` s collect:[:c|c,'22233344455566677778889999'at:(($ato:$z)indexOf:c)+1] ``` [Answer] # Mathematica 90 This follows the logic of @ace's solution: ``` StringReplace[#,Thread[CharacterRange["A","Z"]->Characters@"22233344455566677778889999"]]& ``` Example ``` StringReplace[#1,Thread[CharacterRange["A","Z"]-> Characters@"22233344455566677778889999"]]&["VI37889"] ``` > > 8437889 > > > [Answer] ## Perl, 50 Another obvious copy of Ace's bash answer ``` ($_)=@ARGV;y/a-z/22233344455566677778889999/;print ``` [Answer] ## R, very long but fun ``` foo <- '1-800-splurghazquieaobuer57' oof <- unlist(strsplit(foo,'')) #don't count that part - it's input formatting :-) digout <- unlist(strsplit('22233344455566677778889999','')) oof[oof%in%letters[1:26]] <- unlist(sapply(oof[oof%in%letters[1:26]], function(j) digout[which(letters[1:26]==j)] )) ``` [Answer] # k [32 Chars] ``` {(.Q.a!|,/(4 3 4,5#3)#'|$2+!8)x} ``` ### Usage ``` {(.Q.a!|,/(4 3 4,5#3)#'|$2+!8)x}"stack exchange" "78225 39242643" ``` [Answer] # JavaScript, 85 JavaScript is never going to win the golf wars, but I like it and I wanted to do something different than jump on the @ace bandwagon. ``` alert(prompt().replace(/[a-z]/g,function(a){for(i=7;a<"dgjmptw{"[i--];);return i+4})) ``` [Answer] ## PHP, 141 Not the shortest, but more fun: ``` <?php foreach(str_split($argv[1])as$c){$v=ord($c);if($v>114){$v--;}if($v==121){$v--;}if($v<123&$v>96){echo chr(ceil($v/3+17));}else{echo$c;}} ``` More readable: ``` <?php foreach (str_split($argv[1]) as $c) { $v=ord($c); if ($v>114) {$v--;} if ($v==121){$v--;} if ($v<123 & $v>96){ echo chr(ceil($v/3+17)); } else {echo $c;} } ``` [Answer] **Python 2.7, 80** ``` for c in raw_input():print'\b'+(`(ord(c)-97)/3+2-(c in('svyz'))`if c>'`'else c), ``` I am new to python, so **I'm sure there must be a way to golf this even further**, it's a different aproach, hope you guys like it, ***my god, is python pretty!*** Run example: * input: 01-800-abcdefghijklmnopqrstuvwxyz * output: 01-800-22233344455566677778889999 [Answer] # T-SQL, 216 bytes I spent quite some time over the past couple of nights painstakingly creating a mathematical sequence function that would round correctly to generate the proper ASCII codes for the numbers from the alphabetical ASCII codes. It had a ridiculous number of decimal places in the coefficients, but it worked. However, mattnewport's rational approach works in SQL as well, at a much lower cost of bytes, so I am shamelessly scrapping my own math in favor of his. Go up-vote him, it's an elegant solution! Here's mine: ``` DECLARE @p VARCHAR(MAX)='';WITH t AS(SELECT ASCII(LEFT(@s,1))c,2 i UNION ALL SELECT ASCII(SUBSTRING(@s,i,1)),i+1FROM t WHERE i<=LEN(@s))SELECT @p=@p+CHAR(CASE WHEN c>96THEN 20-c/122+5*c/16 ELSE c END)FROM t;SELECT @p ``` This uses a recursive CTE to make an impromptu stack of the characters in the phone number and translate the letters on the fly, then a bit of SQL trickery (SELECT @p=@p+columnValue) to recompose the string from the CTE without requiring another recursion construct. Output: ``` DECLARE @s VARCHAR(MAX)='1-800-abcdefghijklmnopqrstuvwxyz' --above code runs here 1-800-22233344455566677778889999 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` Aā6+žq÷T9:‡ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f8UijmfbRfYWHt4dYWj1qWPj/v4GhkbGJqZm5haVuYlJySmpaekZmVnZObl5@QWFRcUlpWXlFZRUA "05AB1E – Try It Online") ``` A # alphabet: "abcdefghijklmnoqrstuvwxyz" ā # length range: [1..26] 6+ # add 6 to each: [7..32] žq÷ # divide by pi: [2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,10] T9: # replace 10 with 9 ‡ # transliterate the input (a => 2, ..., z => 9) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes ``` ka:ż6+kiḭṪ9JṅĿ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrYTrFvDYra2nhuK3huao5SuG5hcS/IiwiIiwiMDEyMzQ1Njc4OS1hYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5eiJd) ``` ka:ż6+kiḭṪ9JṅĿ ka: # Push the alphabet twice ż # Length range: [1..26] 6+ # Add 6: [7..32] kiḭ # Floor divide by pi: [2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,10] Ṫ9J # Remove the last item and append 10 ṅ # Join by nothing to make a string Ŀ # Transliterate the input from the alphabet to this ``` [Answer] ## PHP, 87 ``` echo str_ireplace(range('a','z'),str_split('22233344455566677778889999'),fgets(STDIN)); ``` [Answer] # q [38 Chars] ``` {(.Q.a!"22233344455566677778889999")x} ``` Inspired by @ace's solution Example ``` {(.Q.a!"22233344455566677778889999")x}"stack exchange" "78225 39242643" ``` [Answer] ### XQuery, 71 [BaseX](http://basex.org) was used as XQuery processor. `$i` is input. ``` translate($i,"abcdefghijklmnopqrstuvwxyz","22233344455566677778889999") ``` Not the shortest answer, but quite short and very readable. [Answer] ## Python, very ungolfed Since everyone is copying ace, i decided to post the code i made up before i submitted the question: ``` def phonekeypad(text): c = ['','','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz'] st = "" for i in list(text): a = False for t in range(len(c)): if i in c[t]: st += str(t) a=True if a == False: st += str(i) return st ``` [Answer] # EcmaScript 6 (103 bytes): ``` i.replace(/[a-z]/g,x=>keys(a='00abc0def0ghi0jkl0mno0pqrs0tuv0wxyz'.split(0)).find(X=>a[X].contains(x))) ``` *Expects `i` to contain the string.* Try it in any recent version of Firefox. I've not tried Google Chrome. [Answer] ## Python 3, 121 ``` print("".join((lambda x:"22233344455566677778889999"[ord(x)-97] if ord(x)>96 and ord(x)<123 else x)(i) for i in input())) ``` [Answer] # Haskell, 93C ``` t[]_ a=a t(b:c)(d:e)a |a==b=d |True=t c e a y=map(t['a'..'z']"22233344455566677778889999") ``` Usage ``` y "1-800-program" ``` [Answer] # C# 140 ``` using System.Linq;class P{static void Main(string[]a){System.Console.Write(string.Concat(a[0].Select(d=>(char)(d>96?20-d/122+5*d/16:d))));}} ``` [Answer] # Perl, 54 ``` print map{/[a-y]/?int(5/16*ord)-28:/z/?9:$_}<>=~/./gs ``` Shoot, @RobHoare still beat me by 4 characters. :) [Answer] # [C++ (clang)](http://clang.llvm.org/), 50 bytes ``` [](auto&s){for(auto&c:s)c=c>96?20-c/122+5*c/16:c;} ``` this is a port of [mattnewport's C solution](https://codegolf.stackexchange.com/a/21349/112488). [Try it online!](https://tio.run/##TY7dCoJAFISvPU@xEIQWkgpJqW0P4WV0sRw3WXB/2D0GET27KUJ0NTMMwzfoXIqDMP1EUrtBkGzo5aQRWrKWQ8tIBopbFhJ4T7d7LEay25C8H9avHquQ4AX5ubwWWYqHvCj2x92sZYX1Z4rikNQQeUmjNyzU8AHYKIPD2EnWKBvIS6E5gDIEWigTP63qZhhEgbqqmntl@mW4ZlSGcf6X7UisadabC@rHymbWlKenLEudt70X@gs "C++ (clang) – Try It Online") ]
[Question] [ # Challenge : Given an integer `n` as input. Create a diamond that is 2x the given number `n`. # Input : Input is integer `n` and 2 < n ≤ 3000. # Output : Output will be a string and it will be in form of a diamond consisting of `+` with an addition line at the start showing `n` using `+` # Examples : ``` D(3) : +++ + +++ +++++ +++++ +++ + D(5) : +++++ + +++ +++++ +++++++ +++++++++ +++++++++ +++++++ +++++ +++ + D(6) : ++++++ + +++ +++++ +++++++ +++++++++ +++++++++++ +++++++++++ +++++++++ +++++++ +++++ +++ + ``` # Winning Criteria : This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes for each programming language wins. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~151~~ 139 bytes ``` ,[.[<]<+[>>]++++[-<++++++++>],]<[<]<<<++++++++++.>>[[>]>[-<+>]>[-<+>]>>[.>>]<<[<]<<.<<[..<<]<.>>-]>[[>]>[.>>]<<[<<]>.>>[..>>]<<,<[<]<<.>>>] ``` [Try it online!](https://tio.run/##RY1RCoBACEQP5K4nkLmIzEcFQQR9BJ3f3HYrPxxmfOp8TtuxXsseUVzdaOIAJcurySiw0NrQvkhEAXcQjfsFnnmCD62pmo2WYeXgX8CIdkO7L2MF6SL6ixs "brainfuck – Try It Online") Takes input via unary, with `+`s as tally marks ([allowed by the poster](https://codegolf.stackexchange.com/questions/162798/diamond-creator/162810#comment394423_162798)). Decided to rework this, as I thought the old one was a bit longer than it could be (though this one is too!). ### Old Version (151 bytes): ``` >--[>+<++++++]<[->+>.<<]++++++++[-<+<++++>>]<++>>[<<.>>-[-<+<<.>>>]<[->+<]>>>+[-<.>>+<]>+[-<+>]<<<]>>[<<<<.>>[-<+<<.>>>]<[->+<]>+>>-[-<.>>+<]>-[-<+>]<] ``` [Try it online!](https://tio.run/##bYxBCoBQCEQPJHaCYS4iLioIImgRdH5T/182C3FmfG7Pet7Hu18hpaCqUdBGHKYULoDLlClGSzpqGrCQ2nltHBA817rOqEyD2aGKZPr2B5Lxa1I6KY/4AA "brainfuck – Try It Online") Takes input as the starting cell. I couldn't think of a way to leverage the first half to help with the second, so there's a loop for each of them. ### How It Works: ``` >--[>+<++++++] Create 43 ('+') two space to the left of n <[->+>.<<] Print n '+'s while preserving n ++++++++[-<+<++++>>]<++ Create 32 (' ') and 10 ('\n') Tape: 32 10 0 n 43 t >> [ Loop over the first half of the diamond <<.>> Print a newline -[-<+<<.>>>] Decrement n and print n spaces <[->+<] Restore n >>>+[-<.>>+<] Increment t and print t '+'s >+[-<+>]<<< Increment t again and restore it ]>> [ Loop over the second half <<<<.>> Print a newline [-<+<<.>>>]< Print n spaces [->+<]>+ Restore and increment n >>-[-<.>>+<] Decrement t and print t '+'s >-[-<+>]< Decrement t again and restore it ] ``` And just for fun: ``` +++++++++ > --[ >+<++ ++++]<[ ->+>.<<]+ +++++++[-<+ <++++>>]<++>> [<<.>>-[-<+<<.> >>]<[->+<]>>>+[-< .>>+<]>+[-<+>]<<< ]>>[<<<<.>>[-<+ <<.>>>]<[->+< ]>+>>-[-<.> >+<]>-[-< +>]<]++ +++++ +++ + ``` [Try it online!](https://tio.run/##VY9LCgMxDEP3PkX2wTmB0EVCFtNCoRRmUej5M1Y@pfUiyMhPsW/v43k@PvdX73mXpVXcyr0uyYw9oNGGaTgzC9CGtWKqQy2kyQa9lipQSJcpZXJq4GgkxVjY6gYfJmApvOAGuVOlN6pPA5ixZW49MtSvZWO2fU/7O/P34tz7BQ "brainfuck – Try It Online") [Answer] # [Canvas](https://github.com/dzaima/Canvas), 9 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` +×O{+×]±╪ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=KyVENyV1RkYyRiV1RkY1QislRDcldUZGM0QlQjEldTI1NkE_,i=NQ__,v=2) Explanation (some characters have been replaced to look monospace): ``` +×O{+×]±╪ +× repeat "+" input times O output that { ] map over 1..input +× repeat "+" that many times ± interpret the array as a 2D string, and reverse it ╪ quad-palindromize with 1 horizontal overlap and 0 vertical overlap ``` [Answer] # [Python 3](https://docs.python.org/3/), 95 94 75 bytes ``` def f(n):a=[' '*(n+~i)+'+'*(i-~i)for i in range(n)];return['+'*n]+a+a[::-1] ``` [Try it online!](https://tio.run/##FYoxDkIhEAWvsh2L5Bt/7DCeBClIBF2LB9nwCxuvjjDVTDLt298V1zGeuVBhWJ/uwZA5MdxPrDNuqmxTS1USEpAmvPI8401zPxRhPYguuRS83/Y4mgo6mwfM@VMFXHi1oB2d7WLslz8 "Python 3 – Try It Online") --- My first attempt at some golfing, any suggestions for improvement are welcome. EDIT: saved 1 byte thanks to Kevin Cruijssen EDIT: removed misunderstanding about byte count EDIT: Saved many more bytes thanks to Jo King and user202729 [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` '+×sL·<'+×∊.c» ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fXfvw9GKfQ9ttQIxHHV16yYd2//9vCgA "05AB1E – Try It Online") **Explanation** ``` '+× # push "+" repeated <input> times sL # push range [1 ... input] ·< # multiply each element by 2 and decrement (x*2-1) '+× # replace each number with the corresponding number of "+"'s ∊ # mirror vertically .c # center » # join with the "+"-row created at the start ``` Also 14 bytes: `L‚˜'+×ćs.∞∊.c»` [Answer] # [Python 3](https://docs.python.org/3/), ~~79~~ 78 bytes ``` def f(n):x=[('++'*i+'+').center(n*2)for i in range(n)];return[n*'+']+x+x[::-1] ``` [Try it online!](https://tio.run/##FcpBDsIgEEbhq7CbgYmN1R3GkyALo6C4@GkmNKGnx/btXvItW/tWXMd4p2wyw/p@D0wi5IqQkJ1eCS0pw11srmqKKTD6xCftON40tVUR4HYbpUsP3p/mOBYtaEwP0PSrBZz5@IJlbWyPxnz@Aw "Python 3 – Try It Online") Thanks to this [Tips for golfing Python](https://codegolf.stackexchange.com/a/98613/76162) answer for informing me about the `.center` function. Returns a list of strings. [Answer] # [R](https://www.r-project.org/), ~~135 110~~ 96 bytes ``` function(n){cat("+"<n," ",sep="") for(i in c(1:n,n:1))cat(" "<n-i,"+"<2*i-1," ",sep="")} "<"=rep ``` [Try it online!](https://tio.run/##Tcs7DoAgDADQnVOQTq3CgIMDgcMYYpMu1aBOxrPjZ3J/rza2yTc@tOyyKCqdZdoRekjqwIDb5jUDkOGlolhRWzBEdRoD0SftI724dwyd@PBfl4EEuc5rYxyp3Q "R – Try It Online") @JayCe with the final cut. The `rep` function is assigned to an existing infix operator, such as `<` or `^` so that `rep("+", n)` is equivalent to `"<"("+", n)` which can be written out using `<` as an infix operator as in `"+" < n` and shortened to `"+"<n`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` G→→↙N+↓‖M↑×⊕ⅈ+‖ ``` [Try it online!](https://tio.run/##RYyxCsJAEER7vyKk2sNY2iStTcBICAq28dwkB3e7Yd1E/PrzENFqZh4zY6deLPc@xpb9a2SCsnPjpEX20wM/6YhDsjXNi56WcEMBU2T5NjfVpuEV4VNKocPBo9XGibBAeZkTa8WRwtkFfEBNVjAgKd7hCuZ78h@CqWLcx93q3w "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` G→→↙N+ ``` Print an inverted triangle of `+`s the height of the input and almost twice the width. ``` ↓ ``` Move the cursor down so it lands on the additional line after the reflection. ``` ‖M↑ ``` Make a mirror image of the triangle. ``` ×⊕ⅈ+ ``` Draw the additional line using the current column to avoid having to read the input again. ``` ‖ ``` Reflect the output so that the additional line points to the left. [Answer] # [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ñ1┌╙@↔g+┤a☻ ``` [Run and debug it](https://staxlang.xyz/#p=a431dad3401d672bb46102&i=9&a=1) [Answer] # [Python 3](https://docs.python.org/3/), ~~76~~ 75 bytes ``` lambda n:['+'*n]+[' '*(n+~i)+'+'*(i-~i)for i in[*range(n),*range(n)[::-1]]] ``` [Try it online!](https://tio.run/##PcixDoIwEAbgV@l2d60YiVsTn6R0KNHCGf1LGhYWXr3I4vblW7Z1Lri3/BjaJ33HZzLwgRxZRBfIkGW4XcWdxdr9mEs1ahTB1oTpxZDLX8H7ro8xtqUqVqYBdH0XBWfubyLSDg "Python 3 – Try It Online") [Answer] ## QB64, 82 79 bytes ``` INPUT n ?STRING$(n,43):FOR a=1TO 2*n:d=a-(a>n)*2*(n-a):?SPC(n-d);STRING$(2*d-1,43):NEXT ``` [Answer] # [J](http://jsoftware.com/), ~~29~~ 22 bytes -7 bytes thanks to Jonah! ``` ' +'{~#&1,]>:[:+/~|@i: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1RW01avrlNUMdWLtrKKttPXrahwyrf5rcqUmZ@QrpCmY/gcA "J – Try It Online") ### Original solution: # [J](http://jsoftware.com/), 29 bytes ``` '+'(,]\(}:@|."1,.])@,]\.)@$~] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1bXVNXRiYzRqrRxq9JQMdfRiNR2AfD1NB5W62P@aXApcqckZ@QppCsYwhimMYWjC9R8A "J – Try It Online") ## Explanation: ``` '+'$~] - generates the line at the start, which is a seed for the diamond: '+'$~] 3 +++ ]\,]\. - finds the prefixes (]\) and suffixes (]\.) of the line, making "half" the diamond '+'(]\,]\.)@$~] 3 + ++ +++ +++ ++ + }:@|."1,.] - makes the other "half" of the diamond by reversing each line (|."1) and dropping its last '+' (}:) and stitches the first half to it (,.]) '+'(]\(}:@|."1,.])@,]\.)@$~] 3 + +++ +++++ +++++ +++ + , - prepends the initial line to the diamond '+'(,]\(}:@|."1,.])@,]\.)@$~] 3 +++ + +++ +++++ +++++ +++ + ``` [Answer] # [Scala](http://www.scala-lang.org/), ~~95~~ 94 bytes saved 1 byte(s) thanks to the comment. --- Golfed version. [Try it online!](https://tio.run/##JY3BCsIwDIbve4rQU2phbB4nEzx68DQ8qYc4O6l2UbtuIGO@@mwVEgjf/4evq8nS/DjfdO1hR4ZhnC@6gQa52LKX5TiQBSoxg569scAybemJplwLEAv8GMVSCRXO5cKoXMrUPyr9WoXFiEOqKEzq9KBdp6c5AYiGNsiQ3LUrYOMcvQ@Vd4avJ1nAno2HEsbQBIh@p7veRtRgnskffoayt4z/KG3v/3cURxYyVqZkSuYv) ``` def f(n:Int)={val a=(0 until n).map(i=>" "*(~i+n)+"+"*(2*i+1)).toSeq;Seq("+"*n)++a++a.reverse} ``` Ungolfed version. ``` object Main { def f(n: Int): Array[String] = { val a = (0 until n).map(i => " "*(n-1-i) + "+"*(2*i+1)).toArray Array("+"*n) ++ a ++ a.reverse } def main(args: Array[String]): Unit = { val result = f(10) println(result.mkString("\n")) } } ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 106 105 bytes * thanks to @Kevin Cruijssen for reducing by 1 byte ``` n=>[...Array(n*2+1)].map((_,i)=>" ".repeat(i?i>n?i+~n:n-i:0)+"+".repeat(i?i>n?4*n-2*i+1:i*2-1:n)).join` ` ``` [Try it online!](https://tio.run/##XY3NCoMwEITvPkXwlLg1VNtehCh9jlKaYLWs2I2oFHrpq6dW/KEedhiY@XYq8zJd3mLTh2TvhSuVI5VepJTntjVvTkEMkbjKp2k4v@1QqNRnvmyLpjA9xwxTyhA@lFCIyV6AD5vwGFAYBwhRgkEcRgkJISuLpD3tckudrQtZ2wcv@UEopQHAY2y4nwFYlU2JFoP@g6cJHAsjzOb2gq6fNm4Jl/YMj2PuCw "JavaScript (Node.js) – Try It Online") ## \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ Second approach # [JavaScript (Node.js)](https://nodejs.org), 105 100 99 98 bytes * thanks to @Kevin Cruijssen for reducing by 1 byte * thanks to @ovs for reducing by 1 byte ``` n=>[X="+"[r="repeat"](n),...x=[...X].map((_,i)=>" "[r](n+~i)+"+"[r](i-~i)),...x.reverse()].join` ` ``` [Try it online!](https://tio.run/##XY3PCsMgDIfvfQrxpGT1MnZMn6NQZEpnh6XTYkvZaa/unOsftkN@JOT7kl4vemqDHefS@ZuJHUaHVVMjBdoEpMGMRs9UMsdPQognNilrKR56ZOx6shwrShKZAHhZDlmTzJZp@BoimMWEyTAuRe@tU4WKrXeTH4wY/J117MwRFQAUhKT6NABHknWjeMpf8bKKGcgy2ehdPS79dftypzc5P4tv "JavaScript (Node.js) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) `-R`, ~~18~~ 17 bytes ``` õÈ+Y î+Ãû ê1 iUî+ ``` [Try it online!](https://tio.run/##y0osKPn///DWwx3akQqH12kfbj68W@HwKkOFzFAg7/9/YwXdIAA) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 55 bytes ``` param($l)'+'*$l;1..$l+$l..1|%{" "*($l-$_)+'+'*($_*2-1)} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVHU11bXUslx9pQT08lR1slR0/PsEa1WklBSQsoqasSr6kNUqChEq9lpGuoWfv//39jAA "PowerShell – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~85~~ 82 bytes Saved 3 bytes thanks to [nimi](https://codegolf.stackexchange.com/users/34531/nimi)! ``` n!c=[1..n]>>c f n|x<-[(n-i)!" "++(i*2-1)!"+"|i<-[1..n]]=unlines$n!"+":x++reverse x ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P08x2TbaUE8vL9bOLpkrTSGvpsJGN1ojTzdTU1FJQUlbWyNTy0jXEMjRVqrJBEqB1cbalublZOalFqvkgSSsKrS1i1LLUouKUxUq/ucmZuYp2Cqk5HMpQEBBaUlwSZFPnoKKQpqCMVZRU6yiZv8B "Haskell – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 98 bytes ``` def d(s):print("+"*s);t=[("+"*i).center(2*s-1)for i in range(1,2*s,2)];print("\n".join(t+t[::-1])) ``` [Try it online!](https://tio.run/##Lcs7DsIwEEXRnlVYrublJzkRjSNWkqRA2IGhGEf2NKzeoIju6kj3@OgryVRriLsJVOCPzKJkW9sUzHpbzmQMjygaM41N6R32lA0bFpPv8ozkuh93I7b5f69ih3diIW118b53G1ADTbgEuqJ@AQ "Python 3 – Try It Online") Readable version: ``` def diamond(size): print(size * "+") top = [("+" * i).center(2*size - 1) for i in range(1, 2*size, 2)] print("\n".join(top)) print("\n".join(reversed(top))) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes ``` Dη€û.C∊» ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f5dz2R01rDu/Wc37U0XVo9///2mAAAA "05AB1E – Try It Online") Takes input in unary with `+` as a tally mark; allowed as per [OP's comment](https://codegolf.stackexchange.com/questions/162798/diamond-creator?page=2&tab=oldest#comment394399_162798). ``` Dη€û.C∊» # full program » # join... D # implicit input... » # and... η # prefixes of... D # implicit input... € # with each element... û # concatenated with... # (implicit) current element in list... û # reversed excluding the first character... .C # with... # (implicit) each element... .C # centered by spaces to length of longest element in this list (extra space on the left if unequal spaces)... ∊ # mirrored vertically... » # by a newline # implicit output ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~71~~ 61 bytes ``` ->n{[?+*n]+(a=(1..n).map{|x|?\s*(n-x)+?+*(x+x-1)})+a.reverse} ``` [Try it online!](https://tio.run/##DcoxDoAgDADArzi2NjQhzuhD1AENTEgIqMGAb0dvvnhtT7OqidGXeaLerwRagWT2yIcOpeY6LakHLzLSHyBTFhJfJM3R3CYm87ZwnamzvGvnYMD2AQ "Ruby – Try It Online") [Answer] # PHP, 103 bytes ``` for(;$i++<$argn;$s.=" ".str_pad(str_pad("",$i*2-1,"+",2),$argn*2-1," ",2))echo"+";echo"$s ",strrev($s); ``` Run as pipe with `-nR´ or [try it online](http://sandbox.onlinephpfunctions.com/code/3199ee83cc4499000c1f8a1fbc808ef40170311d). [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 58 bytes ``` param($n)'+'*$n;1..$n+$n..1|%{" "*($n-$_)+"+"*$_+"+"*--$_} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVPU11bXUslz9pQT08lT1slT0/PsEa1WklBSQsoqasSr6mtpK2kpRIPpnSBArX///83AwA "PowerShell – Try It Online") Simply a loop-up and -down, each iterating outputting the appropriate number of spaces and then the appropriate number of plus signs. Ho-hum. [Answer] # [F# (Mono)](http://www.mono-project.com/), 123 bytes ``` let d n= let t n=String('+',n) let s n=t(n*2-1) [1..n]@[n.. -1..1]|>Seq.fold(fun a x->a+sprintf"\n%*s"(n+x-1)(s x))(t n) ``` [Try it online!](https://tio.run/##JY1NCoMwEEb3PcUQEBPThKZ7pXdwaV0ISUpBJ7aTggXvnk5x93h8P5HMkjCVtAaE/ks5LGUOGTxge4I/ZaY@v5/4kLWuz6gOTayzxOZqHJvBWYvjbUBrwTC7ce/68LIxzV7GD8IEm@kmTSsP5SjuWDUkJOqN65JgU0rykSoe3AX2Do4cgqhIlB8 "F# (Mono) – Try It Online") [Answer] # PHP 102 bytes ``` for($r=str_pad;$i++<$a;$s.="\n".$r($r("",$i*2-1,"+",2),$a*2-1," ",2))echo"+";echo"$s\n",strrev($s); ``` Ik know it can be much smaller than this ;) Greetz mangas [Answer] # [sed 4.2.2](https://www.gnu.org/software/sed/), 69 Score includes +1 for the `-r` option to sed. ``` h y/1/+/ p x s/1\B/ /g y/1/+/ p : s/ \+/+++/p t p :a s/\+\+/ /p ta d ``` [Try it online!](https://tio.run/##K05N@f8/g6tS31BfW5@rgKuCq1jfMMZJX0E/HSFoBRRUiNHW19bW1i/gKgGJJAKFYrSBYgogkUQuoCmGQPAvv6AkMz@v@L9uEQA "sed 4.2.2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 59 bytes ``` ->i{[?+*i,b=(1..i).map{|c|' '*(i-c)+?+*(2*c-1)},b.reverse]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6zOtpeWytTJ8lWw1BPL1NTLzexoLomuUZdQV1LI1M3WVMbKK1hpJWsa6hZq5OkV5RallpUnBpb@7@gtKRYIS3aOPY/AA "Ruby – Try It Online") [Answer] # [Yabasic](http://www.yabasic.de), 102 bytes An anonymous function that takes input as a unary number with `+` tally marks and outputs to the console. ``` Input""s$ n=Len(s$) ?s$ For i=-n To n j=Abs(i) If i For k=2To j?" ";Next:?Mid$(s$+s$,1,2*(n-j)+1) Next ``` [Try it online!](https://tio.run/##q0xMSizOTP7/3zOvoLRESalYhSvP1ic1T6NYRZPLHshzyy9SyLTVzVMIyVfI48qydUwq1sjU5PJMU8hUAMll2xoBZbLslRSUrP1SK0qs7H0zU1SA2rWLVXQMdYy0NPJ0szS1DTW5QLL//2trawMA "Yabasic – Try It Online") ### Alternate Version, 117 bytes An anonymous function answer that takes input as a decimal integer and outputs to the console. ``` Input""n For i=1To n s$=s$+"+"Next ?s$ For i=-n To n j=Abs(i) If i For k=2To j?" ";Next:?Mid$(s$+s$,1,2*(n-j)+1) Next ``` [Try it online!](https://tio.run/##q0xMSizOTP7/3zOvoLRESSmPyy2/SCHT1jAkXyFPoVjFtlhFW0lbyS@1ooTLvlgFKqubpwCS58qydUwq1sjU5PJMU8hUAMll2xoBZbLslRSUrEGarOx9M1NUNICmFKvoGOoYaWnk6WZpahtqcoFk//83BgA "Yabasic – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 183 bytes ``` a=x=>{g='\n';r=(m,n)=>String.prototype.repeat.call(m,n);k='+';l=r(k,x)+g;c=d='';for(i=0;i++<x;c+=r(' ',x-i)+r(k,i)+r(k,i-1)+g,d+=r(' ',i-1)+r(k,x+1-i)+r(k,x-i)+g);console.log(l+c+d);} ``` [Try it online!](https://tio.run/##NYxBDsIgFESv4g7Ip41N3H2/l3DrhgASLAKhxNQYz46VpKvJZN6bh3qpRRef6xCTsa0pWunyccRukWEh/pRR0OVai49uzCXVVN/ZjsVmq@qoVQgdwZkYMAxU@CxXAQ41GWIM76lwT0f0AOcVNWwAOzC5Dl7An91jmDZJmn3vvX/BtKPdcQJ1iksKdgzJ8QAajMBvU/wk2g8 "JavaScript (Node.js) – Try It Online") Updated my answer thanks to **@JoKing** [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 25 [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") ``` ⍪∘⊖⍨c,⍨⌽1↓[2]c←↑,\⎕←⎕/'+' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@j3lWPOmY86pr2qHdFsg6QeNSz1/BR2@Roo9jkR20THrVN1Il51DcVxOybqq@urQ7S9p8zjcuY61HvGi4gwwTGMIUxzEAMAA "APL (Dyalog Unicode) – Try It Online") Explanation: ``` ⍪∘⊖⍨c,⍨⌽1↓[2]c←↑,\⎕←⎕/'+' ⍝ Full program ⎕/'+' ⍝ Get input from user as N, replicate '+' N times ⎕← ⍝ Print above string ,\ ⍝ Find all prefixes of above string, e.g. '+','++','+++' etc. ↑ ⍝ Mix the above into a matrix - right-pads with spaces as needed c← ⍝ Assign above matrix to 'c' for 'corner' 1↓[2] ⍝ Drop the first column ⌽ ⍝ Reverse the resulting matrix c,⍨ ⍝ Append 'c' to above - this gives us the top half ⍪∘⊖⍨ ⍝ Take the above, flip it about the horizontal axis, ⍝ and append it to itself ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas) (v8), ~~8~~ 5 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` []↔╪∔ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjNCJXVGRjNEJXUyMTk0JXUyNTZBJXUyMjE0,i=KysrKys_,v=8) Takes input as unary using `+` as tally. The other Canvas answer here uses v2. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 6 bytes ``` ¦ʁøĊmJ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwiwqbKgcO4xIptSiIsIiIsIisrKysrKyJd) ## How? ``` ¦ʁøĊmJ ¦ # Prefixes of implicit input ʁ # Palindromize each øĊ # Center m # Mirror each J # Join the (implicit) input with this ``` ]
[Question] [ > > Well, although this challenge turned out to be a huge success, it also turned out to be very trivial to solve. Therefore, for those of looking for more of a challenge, I created a sequel to this challenge in which you must now count the number of *unique* rectangles. [Check it out!](https://codegolf.stackexchange.com/q/87500/52405) > > > Now, for those of you looking to solve *this* challenge, here it comes. > > > --- Well, we don't really have a challenge like this yet, so here we go. Consider this `3 x 3` grid of rectangles: [![Example](https://i.stack.imgur.com/DoLX6.png)](https://i.stack.imgur.com/DoLX6.png) How many rectangles are there? Well, counting visually, we can see that there are actually `36` rectangles, including the entire plane itself, which are all shown in the animated GIF below: [![Rectangles in Example](https://i.stack.imgur.com/ItYuw.gif)](https://i.stack.imgur.com/ItYuw.gif) ## The Task The counting of rectangles as shown above is the task. In other words, given 2 integers greater than or equal to `0`, `m` and `n`, where `m` represents the width and `n` represents the height, output the total number of rectangles in that `m x n` grid of rectangles. ## Rules * The use of any built-ins that directly solve this problem is explicitly disallowed. * This challenge is not about finding the shortest answer, but finding the shortest answer in every language. Therefore, no answer will be accepted. * Standard loopholes are prohibited. ## Test Cases Presented in the format `Array of Integers Input -> Integer Output`: ``` [0,0] -> 0 [1,1] -> 1 [3,3] -> 36 (Visualized above) [4,4] -> 100 [6,7] -> 588 ``` ## References * <http://oeis.org/A096948> Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins! [Answer] ## Python, 22 bytes ``` lambda m,n:m*~m*n*~n/4 ``` The formula `m*n*(m+1)*(n+1)/4` is shortened using the bit-complement `~m=-(m+1)`, expressing `(m+1)*(n+1)` as `~m*~n`. Why is the number of rectangles `m*n*(m+1)*(n+1)/4`? Each rectangle is specified by the choice of two horizontal lines (top and bottom) and two vertical lines (left and right). There are `m+1` horizontal lines, of which we choose a subset of two distinct ones. So the number of choices is `choose(m+1,2)`, which is `m*(m+1)/2`. Multiplying by the `n*(n+1)/2` choices for vertical lines gives the result. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` RS€P ``` [Try it online!](http://jelly.tryitonline.net/#code=UlPigqxQ&input=&args=WzMsM10) ### Alternatively, also 4 bytes ``` pP€S ``` [Try it online!](http://jelly.tryitonline.net/#code=cFDigqxT&input=&args=Mw+Mw) [Answer] # Javascript (ES6), 17 bytes ``` m=>n=>m*n*~m*~n/4 ``` A fork of [this answer](https://codegolf.stackexchange.com/a/87191/48934). ``` f=m=>n=>m*n*~m*~n/4 alert(f(prompt())(prompt())) ``` [Answer] ## Mathematica, 15 bytes ``` ##(1##+##+1)/4& ``` This is an unnamed function taking two integer arguments and returning the number of rectangles. ### Explanation The implementation is basically a very golfy form of the product of the two triangular numbers. It might be worth reading the section "Sequences of arguments" [in this post](https://codegolf.stackexchange.com/a/45188/8478) for the details, but I'll try to summarise the gist here. `##` expands to a *sequence* of all arguments. This is similar to *splatting* in other languages. For instance, if the arguments are `3` and `4`, then `{1, 2, ##, 5}` will give you `{1, 2, 3, 4, 5}`. But this doesn't just work in lists, but in any expression whatsoever, e.g. `f[1, 2, ##, 5]` would also be `f[1, 2, 3, 4, 5]`. This gets interesting when you combine `##` with operators. All operators in Mathematica are just short-hands for some `f[...]`-like expression (possibly nested). E.g. `a+b` is `Plus[a, b]` and `a-b` actually represents `Plus[a, Times[-1, b]]`. Now when you combine `##` with operators, what Mathematica does is to expand the operators first, treating `##` like a single operand, and expand them only at the end. By inserting `##` in the right places, we can therefore use it both to multiply and to add the operands. Let's do this for the code above: ``` ##(1##+##+1)/4 ``` Expanding it to its full form, we get this: ``` Times[##, Plus[Times[1, ##], ##, 1], Rational[1/4]] ``` Let's insert the function arguments `a` and `b`: ``` Times[a, b, Plus[Times[1, a, b], a, b, 1], Rational[1/4]] ``` And now we convert it back into standard mathematical notation: ``` a * b * (a * b + a + b + 1) / 4 ``` A little rearranging shows that this is the product of the triangular numbers: ``` a * b * (a + 1) * (b + 1) / 4 (a * (a + 1) / 2) * (b * (b + 1) / 2) T(a) * T(b) ``` Fun fact: this implementation is so golfy, it's the same length as the built-in for computing a single triangular number, `PolygonalNumber`. [Answer] # C, 25 bytes ``` #define r(x,y)x*y*~x*~y/4 ``` Purist version (27): ``` r(x,y){return x*y*~x*~y/4;} ``` ISO-er version (35): ``` #define r(x,y)((x)*(y)*~(x)*~(y)/4) ``` [Answer] ## [Jellyfish](https://github.com/iatorm/jellyfish/blob/master/doc.md), 16 bytes ``` p|%/**+1 4 Ei ``` Input format is `[x y]`, output is just the result. [Try it online!](http://jellyfish.tryitonline.net/#code=cHwlLyoqKzEKICA0ICBFaQ&input=WzYgN10) Alternative solution, same byte count: ``` pm%/*[*i 4 +1 ``` ### Explanation Time to give Jellyfish the introduction it deserves! :) Jellyfish is [Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb)'s language [based on his 2D syntax challenge](https://codegolf.stackexchange.com/q/65661/8478). The semantics are largely inspired by J, but the syntax is a work of art. All functions are single characters and laid out on a grid. Functions take their arguments from the next token south and east of them and return the result north and west. This let's you create an interesting web of function calls where you reuse values by passing them into several functions from multiple directions. If we ignore the fact that some of tokens in the above program are special *operators* (higher-level functions), the above program would be written something like this in a sane language: ``` p(|( /*(i*(i+1)) % 4 )) ``` Let's go through the code bottom-up. Input gets fed in by the `i`, which therefore evaluates to `[x y]`. The `+` on top of it receives this input together with the literal `1` and therefore increments both elements to give `[(x+1) (y+1)]` (most operations are threaded automatically over lists). The other value of `i` is sent left, but the `E` splits is eastern argument north and west. That means the inputs to the right `*` are actually `[x y]` and `[(x+1) (y+1)]` so this computes `[x*(x+1) y*(y+1)]`. The next `*` up is actually modified by the preceding `/` which turns it into a fold operation. Folding `*` over a pair simply multiplies it, so that we get `x*(x+1)*y*(y+1)`. Now `%` is just division so it computes `x*(x+1)*y*(y+1)/4`. Unfortunately, this results in a float so we need to round it with the unary `|`. Finally, this value is fed to `p` which prints the final result. [Answer] # R, ~~40~~ 35 bytes Well, time to jump in at the deep end ! Here is my **R** code, inspired from @xnor answer : ``` a=scan();(n=a[1])*(m=a[2])*(n+1)*(m+1)/4 ``` *EDIT* : In this version, **R** will ask twice for inputs. ``` (n=scan())*(m=scan())*(n+1)*(m+1)/4 ``` [Answer] # CJam, ~~12~~ 10 Bytes 2 bytes saved thanks to Martin. ``` {_:)+:*4/} ``` [Try it online!](http://cjam.tryitonline.net/#code=cmlhcmkre186KSs6KjQvfX4&input=MyAz) This is a block that takes a list of 2 elements from the stack and leaves the solution on the stack. Usable full program for testing: `riari+{_:)+:*4/}~`. Based off of xnor's outstanding python solution. Explanation: ``` {_:)+:*4/} { } -- Define a block _:) -- Duplicate list, increment all values in new list + -- Join the two lists :* -- Fold multiply over all 4 elements 4/ -- Divide by 4 ``` [Answer] ## Matlab, ~~23~~ 19 bytes ``` @(x)prod([x/2,x+1]) ``` Implementation of the formula `m*n*(m+1)*(n+1)/4` Usage: `ans([m,n])` [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` tQ*2/p ``` Input is an array of the form `[m,n]`. [**Try it online!**](http://matl.tryitonline.net/#code=dFEqMi9w&input=WzYsN10) ### Explanation Direct computation based on the formula `m*(m+1)*n*(n+1)/4`. ``` t % Input array [m,n] implicitly. Duplicate Q % Add 1 to each entry of the copy: gives [m+1,n+1] * % Multiply element-wise: gives [m*(m+1),n*(n+1)] 2/ % Divide each entry by 2: [m*(m+1)/2,n*(n+1)/2] p % Product of the two entries: m*(m+1)*n*(n+1)/4. Display implicitly ``` [Answer] # J, 8 bytes ``` 2*/@:!>: ``` **Usage:** ``` f =: 2*/@:!>: f 0 0 0 f 3 3 36 ``` [Answer] # Java 7, ~~39~~ 38 bytes ``` int c(int a,int b){return~a*a*b*~b/4;} ``` # Java 8, ~~26~~ ~~25~~ ~~19~~ ~~18~~ 17 bytes ``` a->b->a*~a*b*~b/4 ``` Based on [*@xnor*'s excellent answer](https://codegolf.stackexchange.com/a/87191/52210). Multiple bytes saved thanks to *@DavidConrad*. [Try it here.](https://ideone.com/lraSKq) **Test code (Java 7):** [Try it here.](https://tio.run/nexus/java-openjdk#fcyxCoMwGATg3ae4MZFgFaUdfAYnx9LhTyoloFHMb6GIvrptaNdmueW@O9OT92jWBPBMbM1hHcOIkKRCarnOHS@z2ymlVKe7PlX1dgDTontrfjM8R3vHQNaJlmfrHtcbSIZboH157oZsXDibPhX3ThiRK@RS1v9BoVBEQalQRkGlUEXBWeHyBVuyHW8) ``` class M{ static int c(int a,int b){return~a*a*b*~b/4;} public static void main(String[] a){ System.out.println(c(0, 0)); System.out.println(c(1, 1)); System.out.println(c(3, 3)); System.out.println(c(4, 4)); System.out.println(c(6, 7)); } } ``` **Output:** ``` 0 1 36 100 588 ``` [Answer] # Ruby, 22 bytes Stealing @xnor's trick and making a stabby-lambda: ``` r=->(m,n){m*n*~m*~n/4} ``` Example call: ``` r[6,7] # => 588 ``` Or as a proc, also 22 bytes: ``` proc{|m,n|m*n*~m*~n/4} ``` Which we could then call: ``` proc{|m,n|m*n*~m*~n/4}.call(6,7) # => 588 ``` [Answer] ## [Labyrinth](https://github.com/m-ender/labyrinth), ~~13~~ 11 bytes ``` *?;*_4/! ): ``` [Try it online!](http://labyrinth.tryitonline.net/#code=Kj87Kl80LyEKKTo&input=NiA3) ### Explanation This also computes the product of the triangular numbers like most answers. The leading 2x2 block is a small loop: ``` *? ): ``` On the first iteration `*` doesn't do anything, so that the real loop order is this: ``` ? Read integer N from STDIN or 0 at EOF and push onto stack. If 0, exit the loop. : Duplicate N. ) Increment. * Multiply to get N*(N+1). ``` The remaining code is just linear: ``` ; Discard the zero that terminated the loop. * Multiply the other two values. _4 Push a 4. / Divide. ! Print. ``` Labyrinth then tries to execute `/` again, which terminates the program due to a division by zero. [Answer] ## Pyke, 6 bytes ``` mh+Bee ``` [Try it here!](http://pyke.catbus.co.uk/?code=mh%2BBee&input=%5B3%2C3%5D) ``` mh - map(increment, input) + - ^ + input B - product(^) ee - ^ \ 4 ``` [Answer] ## 05AB1E, 4 bytes ``` €LOP ``` **Explanation** Uses the formula described at [A096948](http://oeis.org/A096948) ``` # Implicit input, ex: [7,6] €L # Enumerate each, [[1,2,3,4,5,6,7],[1,2,3,4,5,6]] O # Sum, [28,21] P # Product, 588 # Implicit display ``` Takes input as **[n,m]**. [Try it online](http://05ab1e.tryitonline.net/#code=4oKsTE9Q&input=WzcsNl0) [Answer] # Pyth, ~~8~~ 6 bytes Two bytes saved thanks to @DenkerAffe. ``` *FmsSd ``` Input is expected as a list like `[m,n]`. Try it out [here](https://pyth.herokuapp.com/?code=%2aFmsSd&input=%5B6%2C7%5D&test_suite=1&test_suite_input=%5B0%2C0%5D%0A%5B1%2C1%5D%0A%5B3%2C3%5D%0A%5B4%2C4%5D%0A%5B6%2C7%5D&debug=0). Explanation: ``` Implicit assignment of Q to eval(input). * Multiplication. F Splat the following sequence onto the arguments of the previous function. m Map the following function of d over Q (Q is implicitly added to the end). s Reduce the following list with addition, initial value of 0. Sd Return range(1,d+1). ``` [Answer] ## C#, 19 bytes ``` (n,m)=>m*n*~m*~n/4; ``` An anonymous function based off of @xnor's answer. [Answer] ## Lua, ~~74~~ 63 bytes ``` x,y=...n=0 for i=1,y do for j=i,i*x,i do n=n+j end end print(n) ``` Function takes input as number parameters. Because of the way Lua is implemented, this is technically a function, with variable args, which can be called by wrapping it in a "function" statement, or loading it from source code using "loadstring" [Answer] # [Cheddar](https://github.com/cheddar-lang/Cheddar), 23 bytes ``` m->n->m*(m+1)*n*(n+1)/4 ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~84~~ 80 bytes ``` ({}<>)({({})<({}[()])>}{})<>({({})<({}[()])>}{}[()]){<>(({}))<>({}[()])}<>({{}}) ``` [Try it online!](https://tio.run/nexus/brain-flak#@69RXWtjp6lRDaQ1bYBEtIZmrKZdLYhnh0UUzKgGSoFkwEogQrUgZnVtreb//2YK5gA "Brain-Flak – TIO Nexus") Probably very sub-optimal, especially because of the code reuse regarding triangle numbers, but at least we have a Brain-Flak solution that works. Sadly it seems to fail by looping infinitely with the `0 0` testcase but all others work fine. [Answer] ## Convex, 7 bytes I know that this can be smaller, I just can't figure out how yet... ``` _:)+×½½ ``` [Try it online!](http://convex.tryitonline.net/#code=XzopK8OXwr3CvQ&input=&args=WzMgM10). Uses the CP-1252 encoding. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 9 bytes ``` ×/+/∘⍳¨∘⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TD0/W19R91zHjUu/nQChDdtQgooWCgYMCVpmCoYAgkjRWMgaSJggmQNFMwBwA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Pyt](https://github.com/mudkip201/pyt), 3 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage) ``` ←△Π ``` Explanation: ``` ← Get input △ Get triangle numbers Π Array product Implicit output ``` [Try it online!](https://tio.run/##K6gs@f//UduER9M2n1vw/3@0qY5lLAA) ]
[Question] [ ### Task Given a UTF-8 string (by any means) answer (by any means) an equivalent list where every element is the number of bytes used to encode the corresponding input character. ### Examples `!` ‚Üí `1` `Ciao` ‚Üí `1 1 1 1` `t Éa ä` ‚Üí `1 2 1 2` `Ad√°m` ‚Üí `1 1 2 1` `ƒâa≈≠` ‚Üí `2 1 2` (single characters) `cÃÇauÃÜ` ‚Üí `1 2 1 1 2` (uses combining overlays) `„Éńɣ„Ç™` ‚Üí `3 3 3` (empty input) ‚Üí (empty output) `!¬±‚â°©∏Ω` ‚Üí `1 2 3 4` (a null byte) ‚Üí `1` ### Null bytes If the only way to keep reading input beyond null bytes is by knowing the total byte count, you may get the byte count by any means (even user input). If your language cannot handle null bytes at all, you may assume the input does not contain nulls. [Answer] ## Python 3, ~~42~~ 36 bytes ``` lambda x:[len(i.encode())for i in x] ``` [Answer] # C, ~~68~~ 65 bytes ``` b;main(c){for(;~c;b=c/64^2?b?putchar(b+48)/48:1:b+1)c=getchar();} ``` *Thanks to @FryAmTheEggman for golfing off 3 bytes!* Test it on [Ideone](http://ideone.com/RaDWEf). [Answer] ## APL, 15 chars ``` ‚⢬®'UTF-8'‚àò‚éïucs¬® ``` In English: convert each character to UTF-8 (meaning: vector of bytes representation) and get its tally. [Answer] # Pyth, ~~9~~ 7 bytes Thanks to @Maltysen for saving 2 bytes! ``` mlc.Bd8 ``` [Test suite](http://pyth.herokuapp.com/?code=mlc.Bd8&input=%22t%CA%83a%CA%8A%22&test_suite=1&test_suite_input=%22%21%22%0A%22Ciao%22%0A%22t%CA%83a%CA%8A%22%0A%22Ad%C3%A1m%22%0A%22%C4%89a%C5%AD%22%0A%22%E3%83%81%E3%83%A3%E3%82%AA%22%0A%22%22%0A%22%21%C2%B1%E2%89%A1%F0%A9%B8%BD%22&debug=0) Converts every character of the input to it's binary representation and then splits this into chunks of length 8. The number of those chunks is then the amount of bytes needed to encode that character. [Answer] # GolfScript, 16 bytes ``` {64/2=}%1,/{,)}* ``` [Try it online!](http://golfscript.tryitonline.net/#code=ezY0LzI9fSUxLC97LCl9Kg&input=IcKx4omh8Km4vQ) ### Background GolfScript doesn't have a clue what Unicode is; all strings (input, output, internal) are composed of bytes. While that can be pretty annoying, it's perfect for this challenge. UTF-8 encodes ASCII and non-ASCII characters differently: * All code points below 128 are encoded as `0xxxxxxx`. * All other code points are encoded as `11xxxxxx 10xxxxxx ... 10xxxxxx`. This means that the encoding of each Unicode character contains either a single `0xxxxxxx` byte or a single `11xxxxxx` byte and 1 to 5 `10xxxxxx` bytes. By dividing all bytes of the input by **64**, we turn `0xxxxxxx` into **0** or **1**, `11xxxxxx` into **3**, and `10xxxxxx` into **2**. If we compare the quotient with **2** – pushing **1** for **2**; and **0** for **0**, **1**, and **3** – each character will be turned into a **0**, followed by 1 to 5 **1**'s. All that's left is to split the resulting string at occurrences of **0**, count the number of **1**'s between those zeroes and add one to the amount. ### How it works ``` { }% Map the following over all bytes in the input. 64/ Divide the byte by 64. 2= Compare the quotient with 2, pushing 1 or 0. 1, Push range(1), i.e., [0]. / Split the array of Booleans around zeroes. { }* Fold; for each run of ones but the first: , Push its length. ) Increment. ``` [Answer] ## PowerShell v4, 58 bytes ``` [char[]]$args[0]|%{[Text.Encoding]::UTF8.GetByteCount($_)} ``` --- ### NB OK, this should work, and does in almost all of the test cases except for `©∏Ω` which is somehow counted as `3,3` on my machine. That character even shows as [7 bytes](https://i.stack.imgur.com/mLqdp.png) on my computer. I suspect this is due to some sort of bug in the Windows or .NET version that I'm running locally, as @Mego [doesn't have that issue](https://i.stack.imgur.com/w7mxE.png). (*Edit: @cat points out this is due to [BOM](https://en.wikipedia.org/wiki/Byte_order_mark). Thanks for solving that mystery, @cat!*) However, that still doesn't account for all of the problem. I think I know where *some* of the problems are coming from, though. Inside .NET, all strings are composed of [UTF-16 code units](https://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspx) (which is the System.Char type). With the very loose typecasting that PowerShell uses, there's a *lot* of implicit casting and conversion between types in the background. *Likely* this is a contributing factor to the behavior we're seeing -- for example, `[system.text.encoding]::utf8.getchars([System.Text.UTF8Encoding]::UTF8.GetBytes('©∏Ω'))` returns two unprintables, rather than a single character. --- ### Explanation Very straightforward code. Takes the input `$args[0]` and explicitly casts it as a char-array so we can loop through each component of the string `|%{...}`. Each iteration, we use the .NET call `[System.Text.Encoding]::UTF8.GetByteCount()` (the `System.` is implied) to get the byte count of the current character `$_`. That's placed on the pipeline for later output. Since it's a collection of `[int]`s that are returned, casting to an array is implicit. ### Test Runs ``` PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 't Éa ä' 1 2 1 2 PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 'Ad√°m' 1 1 2 1 PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 'ƒâa≈≠' 2 1 2 PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 'cÃÇauÃÜ' 1 2 1 1 2 PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 '„Éńɣ„Ç™' 3 3 3 PS C:\Tools\Scripts\golfing> .\bytes-per-character.ps1 '!¬±‚â°©∏Ω' 1 2 3 3 3 ``` *Edited to add* This does properly account for the null-bytes requirement that was added to the challenge after I originally posted, provided you pull the data from a text file and pipe it as follows: ``` PS C:\Tools\Scripts\golfing> gc .\z.txt -Encoding UTF8|%{.\bytes-per-character.ps1 $_} 2 1 1 1 ``` [![z.txt](https://i.stack.imgur.com/SgRXR.png)](https://i.stack.imgur.com/SgRXR.png) [Answer] ## JavaScript (ES6), ~~54~~ ~~45~~ 43 bytes ``` s=>[...s].map(c=>encodeURI(c).length/3-8&7) ``` Edit: Saved 2 bytes with help from @l4m2. [Answer] # Ruby, 33 bytes Barely edges out Python, yay! [Try it online.](https://repl.it/C5cN) ``` ->s{s.chars.map{|c|c.bytes.size}} ``` [Answer] # [Perl 6](http://perl6.org), ~~¬†77 69¬†~~ 63 bytes ``` put +$0 if $_¬ª.base(2).fmt("%8d")~~/^(1)**2..*|^(" ")/ while $_=$*IN.read: 1 ``` ``` put +$0 if $_¬ª.fmt("%8b")~~/^(1)**2..*|^(" ")/ while $_=$*IN.read: 1 ``` ``` put 1+$0 if $_¬ª.fmt("%8b")~~/^1(1)+|^" "/while $_=$*IN.read: 1 ``` ``` put 1+$0 if $_¬ª.fmt("%0.8b")~~/^1(1)+|^0/while $_=$*IN.read: 1 ``` Since [Perl¬†6](http://perl6.org) uses NFG strings I have to pull in the bytes directly, which sidesteps the feature. (NFG is like NFC except it also creates synthetic composed codepoints) The output is separated by newlines. ### Test: ``` for text in '!' 'Ciao' 't Éa ä' 'Ad√°m' 'ƒâa≈≠' 'cÃÇauÃÜ' '„Éńɣ„Ç™' '' '!¬±‚â°©∏Ω' '©∏Ω\0©∏Ω'; do echo -en $text | perl6 -e 'put 1+$0 if $_¬ª.fmt("%8b")~~/^1(1)+|^" "/while $_=$*IN.read: 1' | # combine all of the lines into a single one for display purposes env text=$text perl6 -e 'put qq["%*ENV<text>"], "\t\t", lines.gist' done ``` ``` "!" (1) "t Éa ä" (1 2 1 2) "Ad√°m" (1 1 2 1) "ƒâa≈≠" (2 1 2) "cÃÇauÃÜ" (1 2 1 1 2) "„Éńɣ„Ç™" (3 3 3) "" () "!¬±‚â°©∏Ω" (1 2 3 4) "©∏Ω\0©∏Ω" (4 1 4) ``` ### Explanation: ``` # turns the list in ÔΩ¢$0ÔΩ£ into a count, and adds one # ÔΩ¢putÔΩ£ prints that with a trailing newline put 1+$0 # if the following is true if # format the input byte to base 2 and pad it out to 8 characters $_¬ª.fmt("%8b") ~~ # smart match against # check to see if it starts with more than one 1s, or a space # ( also sets ÔΩ¢$0ÔΩ£ to a list that is 1 shorter # than the number of bytes in this codepoint ) / ^1 (1)+ | ^" " / # for every byte in STDIN while $_ = $*IN.read: 1 ``` This works because the first byte in a multi-byte codepoint has the number of bytes encoded inside of it, and the other bytes in the codepoint have the highest bit set, but not the next highest. While the single byte codepoints don't have the highest bit set. [Answer] # Python 3, 82 bytes ``` import math lambda x:[ord(i)<128and 1or int((math.log2(ord(i))-1)//5+1)for i in x] ``` This is much longer than the other Python answer, and the majority of the other answers, but uses an approach involving logarithms that I haven't yet seen. An anonymous function that takes input, via argument, as a string and returns a list. [Try it on Ideone](https://ideone.com/p0p6QU) **How it works** This method relies on the way in which UTF-8 encodes the code-point of a character. If the code-point is less than 128, the character is encoded as in ASCII: ``` 0xxxxxxx ``` where `x` represents the bits of the code point. However, for code-points greater than or equal to 128, the first byte is padded with the same number of `1` s as the total number of bytes, and subsequent bytes begin `10`. The bits of the code-point are then entered to give the shortest possible multibyte sequence, and any remaining bits become `0`. ``` No. of bytes Format 1 0xxxxxxx 2 110xxxxx 10xxxxxx 3 1110xxxx 10xxxxxx 10xxxxxx 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx ... ... ``` and so forth. It can now be noticed that for each number of bytes `n`, the upper limit for the number of code-point bits is given by `(-n+7)+6(n-1) = 5n+1`. Hence, the upper limit code-point `c` for each `n` is given, in decimal, by `c= 2^(5n+1)`. Rearranging this gives `n = (log2(c)-1)/5`. So for any code-point, the number of bytes can be found by evaluating the above expression, and then taking the ceiling. However, this does not work for code points in the range `64 <= c <= 127`, since the lack of a padding `1` due to the ASCII-like encoding for 1 byte characters means that the wrong upper limit is predicted, and `log2` is undefined for `c = 0`, which happens if a null byte is present in the input. Therefore, if `c <= 127`, a value of `1` is returned for n. This is exactly what the code is doing; for each character `i` in the string `x`, the code-point is found using the `ord` function, and the ceiling of the expression is found by using integer rather than float division by `5` and then adding `1`. Since Python's float type always represents integers as `x.0`, even after integer division, the result is passed to the `int` function to remove the trailing zero. If `ord(i) <= 127`, logical short-circuiting means that `1` is instead returned. The number of bytes for each character is stored as an element in a list, and this list is returned. [Answer] # Java 10, ~~100~~ ~~96~~ ~~95~~ ~~67~~ 61 bytes ``` a->{for(var c:a)System.out.print(c.getBytes("utf8").length);} ``` -4 bytes removing spaces because [this is allowed in the comments](https://codegolf.stackexchange.com/questions/83673/bytes-character/83690#comment204264_83673) -1 byte changing `UTF-8` to `utf8` **Explanation:** [Try it online.](https://tio.run/##lZE7TsNAEIZ7n2Lial3ESomwQAJESZqUkGLYrJ0N9tryjhOiyAWJhBRuEVGBREFHk4ZHE@UU@ALcwDjBokAU2WaleXz/fNIOcIjNQe@q5CFqDWco1cQCkIpE6iMX0N6UAMNY9oCzDqVSBedddID6aTzScHrNRUIyVl61l1vVowlJcmiDggMosXk48eOUDTEFvo9OZ6xJRG6ckZtUWcS4Gwg6HpPQzM7I37MdNxQqoL7j5aW3CUyyy7AKrHO3JlHl@SsD/9j8WCuXM7thuzoJJTHbdhxv2/8rESpWT7bEicTYGKLVDFd3xthR720RGVPvc/x4Mqb4eorZ@taYK2Y3xey@mD6akkqMoP6lVne3W43X58/54uvhZWmsedHaHcmtvPwG) ``` a->{ // Method with String-array parameter and no return-type for(var c:a) // Loop over the input-array System.out.print( // Print: c.getBytes("utf8") // The bytes as array in UTF-8 of the current item, .length);} // and print the amount of bytes in this array ``` [Answer] # Julia, 34 bytes ``` s->s>""?map(sizeof,split(s,"")):[] ``` This is an anonymous function that accepts a string and returns an integer array. To call it, assign it to a variable. The approach is quite straightforward: If the input is empty, the output is empty. Otherwise we map the `sizeof` function, which counts the number of bytes in a string, to each one-character substring. [Try it online!](http://julia.tryitonline.net/#code=Zj1zLT5zPiIiP21hcChzaXplb2Ysc3BsaXQocywiIikpOltdCgpmb3IgdGVzdCBpbiBbKCIhIiwgWzFdKSwKICAgICAgICAgICAgICgiQ2lhbyIsIFsxLDEsMSwxXSksCiAgICAgICAgICAgICAoInTKg2HKiiIsIFsxLDIsMSwyXSksCiAgICAgICAgICAgICAoIkFkw6FtIiwgWzEsMSwyLDFdKSwKICAgICAgICAgICAgICgixIlhxa0iLCBbMiwxLDJdKSwgICAgICAjIHNpbmdsZSBjaGFyYWN0ZXJzCiAgICAgICAgICAgICAoImPMgmF1zIYiLCBbMSwyLDEsMSwyXSksICAjIHVzZXMgY29tYmluaW5nIG92ZXJsYXlzCiAgICAgICAgICAgICAoIuODgeODo-OCqiIsIFszLDMsM10pLAogICAgICAgICAgICAgKCIiLCBbXSksCiAgICAgICAgICAgICAoIiHCseKJofCpuL0iLCBbMSwyLDMsNF0pXQogICAgcHJpbnRsbihmKHRlc3RbMV0pID09IHRlc3RbMl0pCmVuZA&input=) (includes all test cases) [Answer] # PHP, ~~92~~ 57 bytes On second thought you can do this with much less faffing around: ``` <?php for(;$a=strlen(mb_substr($argv[1],$i++,1));)echo$a; ``` [Try it online](https://ideone.com/Z7qsFj) note that this is slightly longer as it uses stdin rather than a program argument. This version requires you to ignore notices sent to stderr but [that's fine](http://meta.codegolf.stackexchange.com/questions/4780/should-submissions-be-allowed-to-exit-with-an-error/). old version: Uses a rather different approach to the other php answer. Relies on the lack of native support for multi-byte strings in php. ``` <?php for($l=strlen($a=$argv[1]);$a=mb_substr($a,1);$l=$v)echo$l-($v=strlen($a));echo$l?:''; ``` [Answer] # Emacs Lisp, ~~55~~ 49 bytes ``` (lambda(s)(mapcar'string-bytes(mapcar'string s))) ``` First dissects the string into a list of characters with `(mapcar 'string s)`. The `string` function in Emacs Lisp takes a list of characters and builds a string out of them. Due to the way Emacs splits strings with `mapcar` (i.e. into a list of integers, not characters or strings), this explicit conversion is needed. Then maps the `string-bytes` function onto that list of strings. Example: ``` (mapcar 'string "abc") ; => ("a" "b" "c") (mapcar 'string-bytes '("a" "b" "c")) ; => (1 1 1) ``` Testcases: ``` (mapcar (lambda(s)(mapcar'string-bytes(mapcar'string s))) '("!""Ciao""t Éa ä""Ad√°m""ƒâa≈≠""cÃÇauÃÜ""„Éńɣ„Ç™""""!¬±‚â°©∏Ω""\0")) ;; ((1) (1 1 1 1) (1 2 1 2) (1 1 2 1) (2 1 2) (1 2 1 1 2) (3 3 3) nil (1 2 3 4) (1)) ``` ~~Old answer:~~ ``` (lambda(s)(mapcar(lambda(s)(string-bytes(string s)))s)) ``` Ungolfed: ``` (lambda (s) (mapcar ;; we can't use string-bytes directly, ;; since Emacs mapcar yields a list of ints instead of characters ;; therefore we need a wrapper function here. (lambda (s) (string-bytes (string s))) s)) ``` Testcases: ``` (mapcar (lambda(s)(mapcar(lambda(s)(string-bytes(string s)))s)) '("!""Ciao""t Éa ä""Ad√°m""ƒâa≈≠""cÃÇauÃÜ""„Éńɣ„Ç™""""!¬±‚â°©∏Ω""\0")) ;; ((1) (1 1 1 1) (1 2 1 2) (1 1 2 1) (2 1 2) (1 2 1 1 2) (3 3 3) nil (1 2 3 4) (1)) ``` [Answer] # JavaScript (Node), 27 bytes ``` s=>s.map(Buffer.byteLength) ``` This takes input as an array of individual characters, and returns an array of byte counts. `Buffer` is a method of representing raw binary data. [Buffer.byteLength(string)](https://nodejs.org/api/buffer.html#buffer_class_method_buffer_bytelength_string_encoding) gives the number of bytes in the string. UTF-8 is the default encoding. Note that only Node.js has buffers, not browser JS. The rough browser equivalent is called [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob), which comes in at 31 bytes: ``` s=>s.map(e=>new Blob([e]).size) ``` ## Test Save this file and run it through node, or [try it online](https://repl.it/C546). ``` var f = s=>s.map(Buffer.byteLength) var tests = [ ["!"], ["C","i","a","o"], ["t"," É","a"," ä"], ["A","d","√°","m"], ["ƒâ","a","≈≠"], ["c","ÃÇ","a","u","ÃÜ"], ["„ÉÅ","„É£","„Ç™"], [], ["!","¬±","‚â°","©∏Ω"] ]; tests.forEach(test => { console.log(test, f(test)); }); ``` This should be the result: ``` $ node bytes.js [ '!' ] [ 1 ] [ 'C', 'i', 'a', 'o' ] [ 1, 1, 1, 1 ] [ 't', ' É', 'a', ' ä' ] [ 1, 2, 1, 2 ] [ 'A', 'd', '√°', 'm' ] [ 1, 1, 2, 1 ] [ 'ƒâ', 'a', '≈≠' ] [ 2, 1, 2 ] [ 'c', 'ÃÇ', 'a', 'u', 'ÃÜ' ] [ 1, 2, 1, 1, 2 ] [ '„ÉÅ', '„É£', '„Ç™' ] [ 3, 3, 3 ] [] [] [ '!', '¬±', '‚â°', 'ÔøΩ' ] [ 1, 2, 3, 4 ] ``` [Answer] # Bash, 74 bytes **Golfed** ``` xxd -p|fold -2|cut -c1|tr -d '89ab'|echo `tr -t '01234567cbef' '[1*]2234'` ``` **Algorithm** hexdump input string, fold 2 chars per line, cut the first char only ``` echo -ne '!¬±‚â°©∏Ω' | xxd -p|fold -2|cut -c1 2 c b e 8 a f a b b ``` (4 high order bits of an each input byte as a hex char, one per line) Remove "continuation bytes" 0x80..0xBF ``` tr -d '89ab' 2 c e f ``` (what is left, is 4 bits of the first byte of an each unicode char) map the first bits into the char length, collapse the output and print ``` echo `tr -t '01234567cbef' '[1*]2234'` 1 2 3 4 ``` **Test** ``` U() { xxd -p|fold -2|cut -c1|tr -d '89ab'|echo `tr -t '01234567cbef' '[1*]2234'`;} echo -ne '!' | U 1 echo -ne 'Ciao' | U 1 1 1 1 echo -ne 't Éa ä' | U 1 2 1 2 echo -ne 'Ad√°m' | U 1 1 2 1 echo -ne 'ƒâa≈≠' | U 2 1 2 echo -ne 'cÃÇauÃÜ' | U 1 2 1 1 2 echo -ne '„Éńɣ„Ç™' | U 3 3 3 echo -ne '!¬±‚â°©∏Ω' | U 1 2 3 4 echo -ne "\x0" | U 1 echo -ne '' | U ``` [Answer] # PHP, 126 bytes ``` <?php $s=fgets(STDIN);echo $s!=''?implode(' ',array_map(function($x){return strlen($x);},preg_split('/(?<!^)(?!$)/u',$s))):''; ``` [Try it online!](https://ideone.com/PY6B7a) [Answer] # C#, ~~89~~ 82 bytes ``` I=>{var J="";foreach(char c in I){J+=Encoding.UTF8.GetByteCount(c+"");}return J;}; ``` A simple C# lambda that iterates through the string and returns the space separated list. **Edit:** saved 6 bytes thanks to some very nice comments. [Answer] # Haskell, 85 bytes ``` import Data.ByteString as B import Data.ByteString.UTF8 (B.length.fromString.pure<$>) ``` [Answer] # Pyth, 17 bytes ``` mhxS+11+16,7lCdlC ``` [Try it online!](http://pyth.herokuapp.com/?code=mhxS%2B11%2B16%2C7lCdlC&input=%22%21%C2%B1%E2%89%A1%F0%A9%B8%BD%22&debug=0) Use the code-point of the characters with some arithmetics. [Answer] # C, 85 bytes. ``` l(unsigned char* c){while(*c){int d=(*c>>4)-11; d=d<0?1:d+(d==1);putchar(48+d);c+=d;}} ``` Examines the high 4 bits of each byte to determine the encoding and the number of subsequent bytes to skip; [Answer] # Factor, ~~57~~ ~~87~~ ~~82~~ 80 bytes ``` [ [ dup zero? [ drop "1"] [ >bin length 4 /i 10 >base ] if ] { } map-as ""join ] ``` Explained: ``` USING: kernel math math.parser sequences ; IN: byte-counts : string>byte-counts ( str -- counts ) [ ! new quotation: takes a char as a fixnum dup zero? ! true if this is a NUL byte [ drop "1" ] ! NUL bytes have length 1 [ >bin ! else, convert to binary string length ! length of binary string 4 ! the constant 4 /i ! integer division number>string ! 4 -> "4" ] if ! conditionally execute one of the previous quotations ] ! end { } map-as ! map and clone-like an { } array "" join ; ! join array of 1strings on empty string ``` Unit tests: ``` USING: tools.test byte-counts ; IN: byte-counts.tests { "1" } [ "!" string>byte-counts ] unit-test { "1111" } [ "Ciao" string>byte-counts ] unit-test { "1212"} [ "t Éa ä" string>byte-counts ] unit-test { "1121" } [ "Ad√°m" string>byte-counts ] unit-test { "212" } [ "ƒâa≈≠" string>byte-counts ] unit-test { "12112" } [ "cÃÇauÃÜ" string>byte-counts ] unit-test { "333" } [ "„Éńɣ„Ç™" string>byte-counts ] unit-test { "" } [ "" string>byte-counts ] unit-test { "1234" } [ "!¬±‚â°©∏Ω" string>byte-counts ] unit-test { "1" } [ "\0" string>byte-counts ] unit-test ``` They all pass, now. c: [Answer] # Swift 2.2, ~~67~~ ~~52~~ 50 bytes ``` for c in i.characters{print(String(c).utf8.count)} ``` Horribly ugly. There's no way to get the UTF-8 length of a Character in Swift, so I need to iterate through the string by character, convert the `Character` to a `String`, and find the `count` of that single-character `String` (hey, at least there's a built-in method to do that). Looking for optimizations, possibly using a scanner. Revision 1: Saved 15 bytes by using `count` instead of `underestimateCount()`. Revisions 2: Saved another 2 character by using a for-in loop instead of a for each closure. [Answer] ## Rust, 53 bytes ``` |s:&str|for c in s.chars(){print!("{}",c.len_utf8())} ``` Rust has utf-8 char primitives, iterators, and lambdas, so this was straightforward. Test code: ``` fn main() { let s = "L√∂we ËÄÅËôé L√©opardüíñüíñüíñüíñ"; let f =|s:&str|for c in s.chars(){print!("{}",c.len_utf8())}; f(s); } ``` Outputs ``` 1211133112111114444 ``` [Answer] # jq, 26 characters (23 characters code + 3 characters command line option) ``` (./"")[]|utf8bytelength ``` Hopefully competing. Although `utf8bytelength` was [added 9++ months before](https://github.com/stedolan/jq/commit/83e8ec587f56a88980c55204ee8433e2f50419cc) this question, it is still not included in released version. Sample run: ``` bash-4.3$ ./jq -R '(./"")[]|utf8bytelength' <<< 't Éa ä' 1 2 1 2 bash-4.3$ ./jq -R '(./"")[]|utf8bytelength' <<< 'cÃÇauÃÜ ' 1 2 1 1 2 1 bash-4.3$ ./jq -R '(./"")[]|utf8bytelength' <<< '„Éńɣ„Ç™' 3 3 3 bash-4.3$ ./jq -R '(./"")[]|utf8bytelength' <<< '' bash-4.3$ ./jq -R '(./"")[]|utf8bytelength' <<< '!¬±‚â°©∏Ω' 1 2 3 4 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 53 bytes ``` k=49;f(char*s){*++s/64-2?k=puts(&k)+47:++k;*s&&f(s);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/b1sTSOk2jNK84Mz0vNUUhOSOxSKtYs1pLW7tY38xE18g@27agtKRYQy1bU9vE3EpbO9taq1hNLU2jWNO69n9uYmaehmZ1mobSkc7Eo2uVQGIA "C (gcc) ‚Äì Try It Online") [Answer] # SmileBASIC, 69 bytes ``` DEF C B WHILE I<LEN(B)Q=INSTR(BIN$(B[I],8),"0")I=I+Q+!Q?Q+!Q WEND END ``` Input is an array of bytes. The number of bytes in a UTF-8 character is equal to the number of leading `1` bits in the first byte (unless there are no `1`s, in which case the character is 1 byte). To find the number of leading 1s, the program finds the first `0` in the binary representation, then adds 1 if this was 0. ``` 0xxxxxxx - no leading ones, 1 byte 110xxxxx 10xxxxxx - 2 leading ones, 2 bytes 1110xxxx 10xxxxxx 10xxxxxx - 3 leading ones, 3 bytes etc. ``` [Answer] # F#, ~~59~~ ~~54~~ 66 bytes ``` (s)=seq{for c in s->System.Text.Encoding.UTF8.GetByteCount([|c|])} ``` Technically, s is a char sequence, but it turns out there's an implicit conversion that allows a string to be passed in. When testing this in the console with `!¬±‚â°©∏Ω`, it splits the kanji into two characters, each 3 bytes long. All the other test cases work fine. **Edit:** It turns out common namespace imports are not implicit. Up another 12 chars. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` √ጵD≈æy‚Äπi1√´.¬≤<5√∑> ``` [**Try it online.**](https://tio.run/##MzBNTDJM/X9u6//D7ee2uhzdV/moYWem4eHVeoc22Zge3m73//D6WK/aQ7v/Rys5ZybmK@koKJWcak481QViOaYcXpgLYhzpTDy6FsRIPtOUWHqmDcR83Nz4uHnx46ZVIA4IKx7a@Khz4YeVO/aCeDEGSrEA) Header `Œµ` is used to for-each over all the test cases; Footer `√Ø]J]¬ª` to pretty-print the output character-lists (`√Ø`: decimals and characters to integers; `]`: close if-else and for-each; `J`: Join digits together; `}`: close header foreach; `¬ª`: Join by new-lines). **Explanation:** ``` √á # Convert each character to its unicode value ŒµD # Foreach over this list i # If the current item ‚Äπ # is smaller than ≈æy # 128 1 # Use 1 √´ # Else .¬≤ # Use log_2 < # minus 1 5√∑ # integer-divided by 5 > # plus 1 ``` Since 05AB1E doesn't have any builtins to convert characters to amount of bytes used, I use `√á` to convert the characters to their unicode values, and in a for-each do the following in pseudo-code: ``` if(unicodeValue < 128) return 1 else return log_2(unicodeValue-1)//5+1 # (where // is integer-division) ``` Inspired by [*@TheBikingViking*'s Python 3 answer](https://codegolf.stackexchange.com/a/83798/52210). [Answer] # [Zsh](https://www.zsh.org/), 41 bytes ``` for c (${(s::)1})set +o multibyte&&<<<$#c ``` [Try it online!](https://tio.run/##qyrO@J@moVn9Py2/SCFZQUOlWqPYykrTsFazOLVEQTtfIbc0pyQzqbIkVU3NxsZGRTn5fy1XmoJ6yanmxFNdj5sb1f8DAA "Zsh ‚Äì Try It Online") Zsh is UTF-8 aware, so we split the string on characters, then disable multibyte and print each character's length. ]
[Question] [ Monday, October 31st, is Halloween. And it got me thinking -- I wonder what other months have the last day of the month *also* be a Monday? ### Input * A positive integer [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963) representing a year, `10000 > y > 0`. * The input can be padded with zeros (e.g., `0025` for year `25`) if required. ### Output * A list of the months of that year where the last day of the month is a Monday. * This can be as month names (e.g., `January, March, October`), or shortnames (`Jan, Mar, Oct`), or numbers (`1, 3, 10`), as separate lines or a list or delimited, etc., just so long as it's unambiguous to the reader. * The output format must be consistent: + For all years input (meaning, you can't output month names for some inputs, and month numbers for other inputs) + As well as consistent per output (meaning, you can't output `1` for `January` in the same output as `Jul` for `July`) + Basically, pick one format and stick to it. ### Rules * Assume the Gregorian calendar for input/output, even down to `y = 1`. * Leap years must be properly accounted for (as a reminder: every year divisible by 4, except not years divisible by 100, unless also divisible by 400 -- 1700, 1800, 1900 all weren't leap years, but 2000 was). * You may use any built-ins or other date calculation tools you like. * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. ### Examples ``` 1 --> Apr, Dec 297 --> May 1776 --> Sep 2000 --> Jan, Jul 2016 --> Feb, Oct 3385 --> Jan, Feb, Oct ``` --- ### Leaderboard ``` var QUESTION_ID=97585,OVERRIDE_USER=42963;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # JavaScript (Firefox 30+), ~~112~~ ~~109~~ ~~103~~ 95 bytes Look ma, no built-ins! ``` y=>[for(m of(i=0,y%4|y%400*!(y%100)&&6)+"63153042641")if((i++,y+(y>>2)-(y/100|0)*3/4|0)%7==m)i] ``` Here's a 107-byte ES6 version: ``` y=>[...(y%4|y%400*!(y%100)&&6)+"63153042641"].map((m,i)=>(y+(y>>2)-(y/100|0)*3/4|0)%7-m?0:i+1).filter(x=>x) ``` And here's my previous attempt, ~~123~~ 113 bytes of ES6: ``` y=>[(l=y%4|y%400*!(y%100))?[7]:[1,7],[4,12],[9],[3,6],[8,11],[5],l?[1,2,10]:[2,10]][(y+(y>>2)-(y/100|0)*3/4|0)%7] ``` ## Explanation The day of the week of a particular year is calculated like so: ``` y+(y>>2)-(y/100|0)*3/4|0)%7 ``` In other words: * Take `y`. * Add the number of 4th years before `y` (`y>>2`). * Subtract the number of 100th years before `y` (`y/100|0`). * Add back in the number of 400th years before `y`; this is 1/4 of `y/100|0`, so we use `*3/4|0`. Then we modulo the result by 7. If we let `0` mean Sunday, `1` mean Monday, etc., the result corresponds to the day of the week of December 31st of that year. Therefore, for December, we want to check if the result is `1`. This gives us the last char in the string. The last day of November is 31 days before the last day of December. This means that for the last day of November to be a Monday, Dec 31 needs to be a `(1 + 31) % 7 = 4` = Thursday. This procedure is repeated until we get back to March (a `3`). Whether or not there is a leap day, the last day of February is 31 days before the last day of March, so we can calculate that too (it's `(3 + 31) % 7 = 6`). The tricky part is finding the correct value for January: * If it is a leap year, the last day of January is 29 days before the last day of Feb, resulting in `(6 + 29) % 7 = 0`. * Otherwise, it is 28 days before the last day of Feb, resulting in `(6 + 28) % 7 = 6`. We can calculate whether or not it is a leap year with the following snippet: ``` !(y%400)|y%100*!(y%4) ``` This gives `0` if `y` is not a leap year, and a positive integer otherwise. This leads us to ``` !(y%400)|y%100*!(y%4)?0:6 ``` for calculating the day for January. However, we can do better by reversing the conditions: ``` y%4|y%400*!(y%100)?6:0 ``` Since the falsy result is always 0 anyway, we can reduce it to ``` y%4|y%400*!(y%100)&&6 ``` saving one more precious byte. Putting it all together, we loop through each char in the string, checking if each is equal to the day of the week of Dec 31st. We keep the indexes of the ones that match, returning this array in the end. And that is how you do leap year calculations without built-ins. [Answer] ## JavaScript (Firefox 30-57), ~~67~~ ~~65~~ ~~64~~ ~~63~~ 61 bytes ``` y=>[for(_ of(m='')+1e11)if(new Date(y+400,++m).getDay()==2)m] ``` Saved ~~2~~ ~~4~~ 6 bytes thanks to @ETHproductions. ~~Saved another byte by outputting the months in reverse order.~~ [Answer] # MySQL, ~~183~~ ~~134~~ ~~129~~ 106 bytes ``` SET @y=2016;SELECT help_topic_id AS m FROM mysql.help_topic HAVING m BETWEEN 1 AND 12 AND 2=DAYOFWEEK(LAST_DAY(CONCAT(@y,-m,-1))) ``` Replace `2016` with the desired year. Run. Rev. 2: Used the `help_topics` table in the default installation instead of creating a temporary table. Rev.3: Adopted [aross´s `-` trick](https://codegolf.stackexchange.com/a/97697#97697) and noticed I can also omit the quotes for `"-1"`. However, `-1` is required in MySQL: I need a full date. Rev.4: Restriction `m BETWEEN 1 AND 12` could be done as `m>0 AND m<13` (-6), but is not needed at all - invalid values will be ignored; warnings will be counted but not listed. [Answer] # Perl, 64 bytes Includes +1 for `-n` Give input on STDIN: ``` perl -M5.010 mon.pl <<< 2016 ``` `mon.pl`: ``` #!/usr/bin/perl -n map$b.=$/.gmtime$_.e4,-7e6..3e7;say$b=~/on (\S+ )\S.* $_.* 1 /g ``` [Answer] ## Batch, ~~160~~ 152 bytes ``` @set/ay=%1,m=0,j=6*!(!(y%%4)*(y%%100)+(y%%400)),y=(y*5/4-y/100*3/4)%%7 @for %%d in (%j% 6 3 1 5 3 0 4 2 6 4 1)do @set/am+=1&if %%d==%y% call echo %%m%% ``` Port of @ETHproduction's answer. With month abbreviations for ~~197~~ 189 bytes: ``` @set/ay=%1,j=6*!(!(y%%4)*(y%%100)+(y%%400)),y=(y*5/4-y/100*3/4)%%7 @for %%m in (Jan.%j% Feb.6 Mar.3 Apr.1 May.5 Jun.3 Jul.0 Aug.4 Sep.2 Oct.6 Nov.4 Dec.1)do @if %%~xm==.%y% call echo %%~nm ``` [Answer] # Mathematica, ~~62~~ 57 bytes ``` DayName@DayRange[{#},{#+1},"EndOfMonth"]~Position~Monday& ``` Anonymous function. Takes a number as input and returns a list of single-element lists of numbers as output. I'm honestly not sure myself how it works anymore. [Answer] # Perl+cal, 46 bytes ``` say`cal $_ $ARGV[0]`=~/\n.{5}\n/&&$_ for 1..12 ``` Example: ``` $ perl -E 'say`cal $_ $ARGV[0]`=~/\n.{5}\n/&&$_ for 1..12' 2016 2 10 $ ``` [Answer] # J, ~~48~~ ~~34~~ 33 bytes ``` [:I.(2=7|_2#@".@,@{.])&>@calendar ``` Saved 15 bytes with help from @[Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m). Uses the calendar builtin to generate an array of strings representing the months, then parses each string to determine the whether the last Monday is the last day of the month. It outputs each month as the month number of each. That is, `Jan = 0`, `Feb = 1`, ..., `Dec = 11`. The output of `calendar` is ``` _3 ]\ calendar 2016 ┌─────────────────────┬─────────────────────┬─────────────────────┐ │ Jan │ Feb │ Mar │ │ Su Mo Tu We Th Fr Sa│ Su Mo Tu We Th Fr Sa│ Su Mo Tu We Th Fr Sa│ │ 1 2│ 1 2 3 4 5 6│ 1 2 3 4 5│ │ 3 4 5 6 7 8 9│ 7 8 9 10 11 12 13│ 6 7 8 9 10 11 12│ │ 10 11 12 13 14 15 16│ 14 15 16 17 18 19 20│ 13 14 15 16 17 18 19│ │ 17 18 19 20 21 22 23│ 21 22 23 24 25 26 27│ 20 21 22 23 24 25 26│ │ 24 25 26 27 28 29 30│ 28 29 │ 27 28 29 30 31 │ │ 31 │ │ │ ├─────────────────────┼─────────────────────┼─────────────────────┤ │ Apr │ May │ Jun │ │ Su Mo Tu We Th Fr Sa│ Su Mo Tu We Th Fr Sa│ Su Mo Tu We Th Fr Sa│ │ 1 2│ 1 2 3 4 5 6 7│ 1 2 3 4│ │ 3 4 5 6 7 8 9│ 8 9 10 11 12 13 14│ 5 6 7 8 9 10 11│ │ 10 11 12 13 14 15 16│ 15 16 17 18 19 20 21│ 12 13 14 15 16 17 18│ │ 17 18 19 20 21 22 23│ 22 23 24 25 26 27 28│ 19 20 21 22 23 24 25│ │ 24 25 26 27 28 29 30│ 29 30 31 │ 26 27 28 29 30 │ │ │ │ │ ├─────────────────────┼─────────────────────┼─────────────────────┤ │ Jul │ Aug │ Sep │ │ Su Mo Tu We Th Fr Sa│ Su Mo Tu We Th Fr Sa│ Su Mo Tu We Th Fr Sa│ │ 1 2│ 1 2 3 4 5 6│ 1 2 3│ │ 3 4 5 6 7 8 9│ 7 8 9 10 11 12 13│ 4 5 6 7 8 9 10│ │ 10 11 12 13 14 15 16│ 14 15 16 17 18 19 20│ 11 12 13 14 15 16 17│ │ 17 18 19 20 21 22 23│ 21 22 23 24 25 26 27│ 18 19 20 21 22 23 24│ │ 24 25 26 27 28 29 30│ 28 29 30 31 │ 25 26 27 28 29 30 │ │ 31 │ │ │ ├─────────────────────┼─────────────────────┼─────────────────────┤ │ Oct │ Nov │ Dec │ │ Su Mo Tu We Th Fr Sa│ Su Mo Tu We Th Fr Sa│ Su Mo Tu We Th Fr Sa│ │ 1│ 1 2 3 4 5│ 1 2 3│ │ 2 3 4 5 6 7 8│ 6 7 8 9 10 11 12│ 4 5 6 7 8 9 10│ │ 9 10 11 12 13 14 15│ 13 14 15 16 17 18 19│ 11 12 13 14 15 16 17│ │ 16 17 18 19 20 21 22│ 20 21 22 23 24 25 26│ 18 19 20 21 22 23 24│ │ 23 24 25 26 27 28 29│ 27 28 29 30 │ 25 26 27 28 29 30 31│ │ 30 31 │ │ │ └─────────────────────┴─────────────────────┴─────────────────────┘ ``` ## Usage ``` f =: [:I.(2=7|_2#@".@,@{.])&>@calendar f 1 3 11 f 297 4 f 1776 8 f 2000 0 6 f 2016 1 9 f 3385 0 1 9 ``` ## Explanation ``` [:I.(2=7|_2#@".@,@{.])&>@calendar Input: year Y calendar Get 12 boxes each containing a month ( )&>@ Operate on each box ] Identity, get the box _2 {. Take the last two strings ,@ Flatten it ".@ Parse it into an array of integers #@ Get the length 7| Take it modulo 7 2= Test if it equals 2 - it will either have two days or 9 days in the last two lines if the end is on a Monday [:I. Return the indices containing a true value ``` [Answer] # C, 119 bytes ``` t=1248700335,m;main(y){for(scanf("%d",&y),t+=y&3||y%25<1&&y&15;m++,(6+y+y/4-y/100+y/400+t)%7||printf("%d,",m),t;t/=7);} ``` This uses a table that contains the offset of the weekdays of the last day of every month for a leap year, encoded in a signed 32-bit word using base 7. If it is not a leap year we add 1 to the offset of January (as you can see `y&3||y%25<1&&y&15` is used to check for years without leap days). Then we simply loop through every month and check if its last day is a Monday. Quite simple actually, no ugly hacks or tricks. Here it is slightly ungolfed: ``` t=1248700335,m; main(y){ for( scanf("%d",&y),t+=y&3||y%25<1&&y&15; m++,(6+y+y/4-y/100+y/400+t)%7||printf("%d,",m),t; t/=7 ); } ``` I might revisit this to rewrite it as a function to save a few characters. The `printf` also takes up a little too much space... [Answer] # Java 7 ,~~186 182~~ 172 bytes *Thanks to kevin for saving 4 bytes* *Thanks to @cliffroot for saving 10 bytes* ``` int[]f(int n){int c=n-1,x=c*365+c/4+c/400-c/100,k=0,b[]={3,(n%4<1&n%100>0)|n%400<1?1:0,3,2,3,2,3,3,2,3,2,3},a[]=new int[12];for(int i:b)a[k++]=(x+=i+28)%7==1?1:0;return a;} ``` # ungolfed ``` int[] f(int n) { int c=n-1,x=c*365+(c/4)+(c/400)-(c/100),k=0, b[] = {3,(n % 4 < 1 & n % 100 > 0) | n % 400 < 1 ? 1 : 0 ,3,2,3,2,3,3,2,3,2,3},a = new int[ 12 ]; if ( (n % 4 < 1 & n % 100 > 1) | n % 400 < 1 ) b[ 1 ] = -1; for (int i : b) a[ k++ ] = (x += i + 28) % 7 == 1 ? 1 : 0; return a; } ``` This version is provide by [@cliffroot](https://codegolf.stackexchange.com/users/53197/cliffroot)(**168 bytes**) ``` static int[] f(int n) { int b = 13561787 | ( (n%4 < 1 & n%100 > 0) | n%400 < 1 ? 1 << 20 : 0 ), x = --n*365 + n/4 + n/400 - n/100,a[]=new int[12],k=0; while (k < 12) a[k++] = (x += (b >> 24 - k*2&3 ) + 28) % 7 == 1 ? 1 : 0; return a; } } ``` # output sample ``` 1 1 0 0 0 0 0 0 0 1 0 0(for input 3385) ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 21 bytes ``` 12:"G@QhO6(YO9XO77=?@ ``` Months are displayed as numbers. [Try it online!](http://matl.tryitonline.net/#code=MTI6IkdAUWhPNihZTzlYTzc3PT9A&input=MjAxNg) Or [verify all test cases](http://matl.tryitonline.net/#code=IkBYS3gKMTI6IktAUWhPNihZTzlYTzc3PT9ACl1dJmhE&input=WzEgMjk3IDE3NzYgMjAwMCAyMDE2IDMzODVd). ### Explanation This uses date conversion builtin functions. For the given year it tests which months' last day is Monday. Instead of explicitly specifying the last day of month `k` (which may be 28, 29, 30 or 31), we specify the `0`-th day of month `k+1`, which is equivalent and does not depend on month or year. ``` 12: % Push [1 2 ... 12] (months) " % For each month k G % Push input @Q % Push k+1 h % Concatenate O6( % Postpend four zeros. For example, for input 2016 and month k=1 % (first iteration) this gives [2016 2 0 0 0 0] (year, month, day, % hour, min, sec). The 0-th day of month k+1 is the same as the % last day of month k. YO % Convert the above 6-element date vector to date number 9XO % Convert date number to date string with output format 9, which % is weekday as a capital letter 77= % Is it an 'M'? ? % If so @ % Push current month (will be implicitly displayed) ``` [Answer] # Bash + GNU utilities, 56 bytes ``` seq -f1month-1day$1-%g-1 12|date -f- +%B%u|sed -n s/1//p ``` Appears to require `date` version 8.25. The 8.23 version in Ideone doesn't cut it. [Answer] # Excel, 537 bytes Because – you know – Excel! Takes input year in A1. Returns hexadecimal list of months; 1=January, C= December. Since each month is a single digit, no separator is needed. ``` =IF(2=WEEKDAY(EOMONTH(DATE(A1,1,1),0)),1,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,2,1),0)),2,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,3,1),0)),3,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,4,1),0)),4,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,5,1),0)),5,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,6,1),0)),6,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,7,1),0)),7,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,8,1),0)),8,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,9,1),0)),9,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,10,1),0)),"A","")&IF(2=WEEKDAY(EOMONTH(DATE(A1,11,1),0)),"B","")&IF(2=WEEKDAY(EOMONTH(DATE(A1,12,1),0)),"C","") ``` Example: A1 contains 2016. B1 contains the above formula, and displays as `2A`, meaning February and October. [Answer] ## PHP, 109 180 159 bytes ``` for($z=$argv[1];$m++<12;)if(date(N,strtotime(sprintf("%04d-$m-",$z).cal_days_in_month(0,$m,$z)))<2)echo"$m,"; ``` * Outputs the provided year, not all of them (... always read the question) * Ignored notices (thanks Titus) * Change `while` to `for` as it's now a single year (again, thanks Titus) ### Old 2 ``` $z=0;while($z++<9999){$o=[];$m=0;while($m++<12)if(date("N",strtotime(sprintf("%04d-$m-","$z").cal_days_in_month(0,$m,$z)))<2)$o[]=$m;echo count($o)>0?"$z:".implode(",",$o)." ":"";} ``` Supports all years from dot to 10000, also got rid of an undefined var warning I wasn't aware of on one PC. Yes it's longer than the old version, but it's more robust. ### Old 1 ``` while($z++<9999){$o=[];$m=0;while($m++<12)if(date("N",strtotime("$z-$m-".cal_days_in_month(0,$m,$z)))<2)$o[]=$m;echo count($o)>0?"$z:".implode(",",$o)." ":"";} ``` If running on Windows or a 32bit system there will be the dreaded 2038 bug, but on a 64bit linux system it's fine. I did attempt to use `date("t"...` which is meant to represent the last date of the given month, but the results didn't match those previously mentioned in this thread. [Answer] # PHP, 92 Bytes ``` for($d=new DateTime("$argv[1]-1-1");$i++<12;)$d->modify("1month")->format(w)!=2?:print"$i,"; ``` check 12 times 1 month after first day of a year is a tuesday. If it is then is the day before the last day in the month is a monday. [Answer] # C, 214 bytes ``` main(int a,char *b[]){for(int x,y,d,m=12;m;m--){y=atoi(b[1]);x=m-1;d=x==1?(y%4==0?(y%100==0?(y%400==0?29:28):29):28):(x==3||x==5||x==10?30:31);if((d+=m<3?y--:y-2,23*m/9+d+4+y/4-y/100+y/400)%7==1)printf("%d\n",m);}} ``` # Compile ``` gcc -std=c99 -o foo foo.c ``` # Ungolfed With credits to the relevant gurus. *Michael Keith* and *Tom Craver* for [C Program to find day of week given date](https://stackoverflow.com/questions/6054016/c-program-to-find-day-of-week-given-date). *Collin Biedenkapp* for [Q&A: How do I figure out what the last day of the month is?](https://stackoverflow.com/questions/15630821/qa-how-do-i-figure-out-what-the-last-day-of-the-month-is) ``` /* credit to Collin Biedenkapp */ short _get_max_day(short x, int z) { if(x == 0 || x == 2 || x == 4 || x == 6 || x == 7 || x == 9 || x == 11) return 31; else if(x == 3 || x == 5 || x == 8 || x == 10) return 30; else { if(z % 4 == 0) { if(z % 100 == 0) { if(z % 400 == 0) return 29; return 28; } return 29; } return 28; } } main(int argc,char *argv[]) { for(int y,d,m=12;m;m--) { y=atoi(argv[1]); d=_get_max_day(m-1,y); /* credit to Michael Keith and Tom Craver */ if ((d+=m<3?y--:y-2,23*m/9+d+4+y/4-y/100+y/400)%7 == 1) printf("%d\n",m); } } ``` [Answer] # PHP, ~~96~~ ~~95~~ ~~76~~ ~~71~~ ~~69~~ ~~64~~ 61 bytes Note: year numbers must be padded to 4 chars, like `0070`. ``` for(;13+$i-=1;)date(N,mktime(0,0,0,1-$i,0,$argn))-1||print$i; ``` Run like this: ``` echo 3385 | php -nR 'for(;13+$i-=1;)date(N,mktime(0,0,0,1-$i,0,$argn))-1||print$i;';echo > -1-2-10 ``` # Explanation Iterates from -1 to -12. Create date using mktime, day `0` (the last day of the previous month) and month `2..13`. Format the date as **day number**, and if the result is 1, print the current number. The negative sign `-` is used as the delimiter. # [The Millenium Bug Strikes Again!](https://en.wikipedia.org/wiki/Year_2000_problem) Note that with this version, the range `0..100` is interpreted as `1970..2069`. This is no problem for the range `0..69`, as weeks have a pattern that repeats every 400 years (146097 days, exactly 20871 weeks), but for the range `70..99`, 1900 is added to the year number, which is not a multiple of 400. To fix that problem JUST for 30 year numbers in a range of 10k, the simplest way is to add 400 to the year number to prevent the 2-digit interpretation (**+4 bytes**): ``` for(;13+$i-=1;)date(N,mktime(0,0,0,1-$i,0,$argn+400))-1||print$i; ``` # Tweaks * Saved a byte by using `!~-$i` to compare `$i` with `1` (`-1` binary negated is `0`, logically negated is `true`; every other number is `false`), so parentheses aren't needed * Saved 19 bytes by using `last day ofYYYY-m` notation to create the date * Saved 5 bytes by using `date` and `strtotime` instead of `date_create` * Saved 2 bytes by counting from negative numbers, using the negative sign as output delimiter (negative month numbers don't exist) and also as delim in the `YYYY-m` part of the date * Saved 5 bytes by using `mktime` instead of `strtotime`. Reverted to using day `0` (`mktime` also supports month 13, so `0-13`==`31-12`) * Saved 3 bytes by using `-R` to make `$argn` available [Answer] # Excel, ~~428~~ ~~97~~ 96 bytes Input in A1. Output un-separated Hexadecimal values (January = 0, December = B) ``` =IF(2=WEEKDAY(DATE(A1+2000,1,31)),0,"")&CHOOSE(WEEKDAY(DATE(A1+2000,3,0)),4,19,6,"3B",8,25,"7A") ``` Added 10 bytes ("+2000") to allow handling of pre-1990 dates. Saved 11 bytes thanks to @[Engineer Toast](https://codegolf.stackexchange.com/users/38183/engineer-toast). --- First attempt (428 bytes), borrowing heavily from @[Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m)'s solution. ``` =IF(2=WEEKDAY(DATE(A1,1,31)),1,"")&IF(2=WEEKDAY(EOMONTH(DATE(A1,2,1),0)),2,"")&IF(2=WEEKDAY(DATE(A1,3,31)),3,"")&IF(2=WEEKDAY(DATE(A1,4,30)),4,"")&IF(2=WEEKDAY(DATE(A1,5,31)),5,"")&IF(2=WEEKDAY(DATE(A1,6,30)),6,"")&IF(2=WEEKDAY(DATE(A1,7,31)),7,"")&IF(2=WEEKDAY(DATE(A1,8,31)),8,"")&IF(2=WEEKDAY(DATE(A1,9,30)),9,"")&IF(2=WEEKDAY(DATE(A1,10,31)),"A","")&IF(2=WEEKDAY(DATE(A1,11,30)),"B","")&IF(2=WEEKDAY(DATE(A1,12,31)),"C","") ``` [Answer] # Python 2, 122 bytes Ugh. Math with dates isn't as simple as I'd like. ``` from datetime import* lambda y:[m+1for m in range(12)if(date(y,12,31)if m>10else(date(y,m+2,1)-timedelta(1))).weekday()<1] ``` [**Try it online**](https://repl.it/EHKa) **Same length:** ``` from datetime import* lambda y:[m-1for m in range(2,14)if(date(y,12,31)if m>12else(date(y,m,1)-timedelta(1))).weekday()<1] ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM) with [dfns](http://dfns.dyalog.com/)'s [cal](http://dfns.dyalog.com/n_cal.htm), Version 15.0: 22; Version 16.0: 19 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) The cal function comes with a default install, just enter `)copy dfns`. ### Version 15.0: `∊⎕{⍵/⍨2=≢⍎⊢⌿cal⍺⍵}¨⍳12` `∊` enlist (flatten) `⎕{`...`}¨` numeric input as left argument to the following anonymous function, taking each of the right side values as right argument in turn  `⍵/⍨` the argument if (gives an empty list if not)  `2=` two (namely Sunday and Monday) is equal to  `≢` the tally of  `⍎` the numbers in  `⊢⌿` the bottom-most row of  `cal` the calendar for  `⍺⍵` year left-argument, month right-argument, the latter being `⍳12` 1 to 12 ### Version 16.0: `⍸2=⎕{≢⍎⊢⌿cal⍺⍵}¨⍳12` `⍸` the indices where `2=` two equals (namely Sunday and Monday) `⎕{`...`}¨` numeric input as left argument to the following anonymous function, taking each of the right side values as right argument in turn  `≢` the tally of  `⍎` the numbers in  `⊢⌿` the bottom-most row of  `cal` the calendar for  `⍺⍵` year left-argument, month right-argument, the latter being `⍳12` 1 to 12 [Answer] # Bash+cal, 58 bytes ``` $ cat t.sh for A in {1..12};do cal $A $1|grep -qx .....&&echo $A;done $ bash t.sh 2016 2 10 $ ``` [Answer] # Python 2, 94 bytes ``` from datetime import* lambda y:[m for m in range(1,13)if date(y+(m>11),m%12+1,1).weekday()==1] ``` **[repl.it](https://repl.it/EHX5/1)** An unnamed function, takes an integer year, outputs a list of the month numbers `[1-12]`. I also tried to beat the byte count with arithmetic without success (110 bytes). : ``` lambda y:map(lambda x,v:(23*((x+2)%13or 1)/9+y-2*(0<x<11)+(x>10)+v/4-v/100+v/400)%7==4,range(12),[y-1]+[y]*11) ``` An unnamed function which returns a list of boolean values representing if the months [Jan-Dec] end in a Monday [Answer] # Java 7, ~~200~~ 249 bytes ``` import java.util.*;String c(int y){String r="";GregorianCalendar c=new GregorianCalendar();c.setGregorianChange(new Date(1L<<63));c.set(1,y);c.set(2,0);for(int i=0;i++<12;c.add(2,1)){c.set(5,c.getActualMaximum(5));if(c.get(7)==2)r+=i+" ";}return r;} ``` In Java, `GregorianCalendar` is a mix between a Gregorian and Julian calendar. Because of this, year `1` gave incorrect results. Changing `Calendar c=Calendar.getInstance();` to `GregorianCalendar c=new GregorianCalendar();c.setGregorianChange(new Date(1L<<63));` fixes this by forcing a use of the Gregorian calendar only. [Thanks to *@JonSkeet* on stackoverflow.com for explaining this to me.](https://stackoverflow.com/questions/40280182/calendar-giving-unexpected-results-for-year-1/40280292#40280292) **Ungolfed & test code:** [Try it here.](https://ideone.com/ZAwjCg) ``` import java.util.*; class M{ static String c(int year){ String r = ""; GregorianCalendar calendar = new GregorianCalendar(); calendar.setGregorianChange(new Date(Long.MIN_VALUE)); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, 0); for(int i = 0; i++ < 12; calendar.add(Calendar.MONTH, 1)){ calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE)); if(calendar.get(Calendar.DAY_OF_WEEK) == 2){ r += i+" "; } } return r; } public static void main(String[] a){ System.out.println(c(1)); System.out.println(c(297)); System.out.println(c(1776)); System.out.println(c(2000)); System.out.println(c(2016)); System.out.println(c(3385)); } } ``` **Output:** ``` 4 12 5 9 1 7 2 10 1 2 10 ``` [Answer] # ~~C#6~~ C#, ~~171~~ ~~167~~ 135 bytes ``` using System; void d(int n){for(int i=0;++i<13;)if((int)new DateTime(n,i,DateTime.DaysInMonth(n,i)).DayOfWeek==1)Console.Write(i+" ");} ``` *-32 bytes thanks to Shebang* Print months as numbers; with space delimited; with trailing space. Now this answer also works for earlier versions of C#. --- Old, 167 bytes ``` using System;using System.Linq; c(int n)=>string.Join(",",Enumerable.Range(1,12).Where(i=>new DateTime(n,i,DateTime.DaysInMonth(n,i)).DayOfWeek==(DayOfWeek)1)); ``` *-4 bytes thanks to TimmyD* Output months are numbers in return string, comma delimited Ungolfed ``` string c(int n)=> string.Join(",", // Join them with commas Enumerable.Range(1,12) // For 1-12 inclusive .Where( // Select only i=>new DateTime(n,i,DateTime.DaysInMonth(n,i) // Get last day of that year-month ).DayOfWeek // Get its day of week ==(DayOfWeek)1 // Is Monday ) ) ; ``` [Answer] ## Ruby, 54 + 6 = 60 bytes ``` λ cat monday.rb p (1..12).select{|m|Date.new($*[0].to_i,m,-1).monday?} λ ruby -rdate monday.rb 2016 [2, 10] ``` 6 bytes for `-rdate` on the command line to get the Date class from the standard library. Explanation: pretty straightforward thanks to the Ruby stdlib's great `Date` class. Not only does it have methods like `monday?`, `tuesday?`, etc, the constructor will take negative numbers for any field past year to mean 'count this field backwards from the end of the period represented by the previous field'. `$*` is shorthand for `ARGV`, so `$*[0]` is a quick way to get the first command line argument. [Answer] # R, ~~106~~ ~~99~~ ~~95~~ ~~83~~ ~~78~~ ~~77~~ 74 bytes ``` g=function(x)which(format(seq(as.Date(paste0(x,-2,-1)),,'m',12)-1,"%u")<2) ``` The sequence of last days of each month is given by `seq(as.Date(paste0(x,-2,-1)),,'m',12)-1`: * `paste0` coerces -2 and -1 to characters. If the `x` was 2016 for instance, `paste0(x,-2,-1)` gives `"2016-2-1"` which is then converted to the 1st of February 2016 by `as.Date`. * `seq` applied to a POSIXct or a Date object is `seq(from, to , by, length.out)`: here `to` is not given, `by` is given as `'m'` which is matched to `'month'` thanks to partial matching, and `length.out` is of course 12. * The resulting sequence is the first day of the 12 months starting with February of the year in question. `-1` gives us then the last day of the 12 months starting with January of the year in question. Test cases: ``` > g(1) [1] 4 12 > g(25) [1] 3 6 > g(297) [1] 5 > g(2000) [1] 1 7 > g(2016) [1] 2 10 > g(3385) [1] 1 2 10 > g(9999) [1] 5 ``` **Old version at 95 bytes, outputting the month names instead of just their numbers:** ``` g=function(x)format(S<-seq(as.Date(sprintf("%04i-02-01",x)),,'m',12)-1,"%B")[format(S,"%u")==1] ``` [Answer] # Japt, 24 bytes ``` Do1 £Ov"Ð400+U"+X e ¥2©X ``` [**Test it online!**](http://ethproductions.github.io/japt/?v=master&code=RG8xIKNPdiLQNDAwK1UiK1ggZSClMqlY&input=MjAxNg==) Outputs an array of numbers, with `false` in place of months that don't end in a Monday. There was a bug in the interpreter that didn't allow me to use `Ð` in the function body `£`. After the bug fix and another feature addition, this is 18 bytes in the current commit: ``` Do1@Ð400+UX e ¥2©X ``` [Answer] # Java, ~~143~~ 129 bytes This uses the new time API of Java 8. ``` y->{String s="";for(int m=0;++m<13;)if(java.time.YearMonth.of(y,m).atEndOfMonth().getDayOfWeek().ordinal()==0)s+=m+" ";return s;} ``` ## Output Note that each line has an extra space at the end. ``` 4 12 5 9 1 7 2 10 1 2 10 ``` ## Ungolfed and testing ``` import java.time.*; import java.util.function.*; public class Main { public static void main (String[] args) { IntFunction<String> func = year -> { String result = ""; for (int month=1; month <= 12; month++) { if (YearMonth.of(year, month).atEndOfMonth().getDayOfWeek().ordinal() == 0) { result += month + " "; } } return result; }; System.out.println(func.apply(1)); System.out.println(func.apply(297)); System.out.println(func.apply(1776)); System.out.println(func.apply(2000)); System.out.println(func.apply(2016)); System.out.println(func.apply(3385)); } } ``` ## Shaves 1. 143 to 129 bytes: use `DayOfWeek::ordinal` to compare with a numerical constant instead of the enum constant. Thanks @TimmyD for the general idea if not the exact solution! ;-) [Answer] # GNU awk, 80 bytes ``` {for(;m<13;a=mktime($0" "++m" 1 9 0 0")){if(strftime("%w",a-8e4)~1){print m-1}}} ``` Example ``` $ gawk '{for(;m<13;a=mktime($0" "++m" 1 9 0 0")){if(strftime("%w",a-8e4)~1){print m-1}}}' <<<2016 2 10 $ ``` [Answer] # PHP, 109 bytes ``` $y=$argv[1];for($i;++$i<13;)echo(date('N',strtotime($y."-$i-".date('t',strtotime("$y-$i-1"))))==1?"$i ":''); ``` The code produces a notice due to `for($i;` but the question mentions nothing about avoiding errors. --- Outputs months numbers separated by a space. ``` 1 --> 1 12 297 --> 5 1776 --> 9 2000 --> 1 7 2016 --> 2 10 3385 --> 1 2 10 ``` --- Works in PHP 5.2.16 and onward at <http://sandbox.onlinephpfunctions.com/> ]
[Question] [ # Challenge In this challenge you have to take a number as input and output the corresponding letter of the alphabet, and vice versa. (1 <=> A, 2 <=> B) etc. ``` 1 -> A 2 -> B ... 26 -> Z A -> 1 B -> 2 ... Z -> 26 ``` # Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. * The input will only consist of either an uppercase letter from `A` to `Z` or an integer from `1` to `26` inclusive. * Trailing whitespaces (space and newline) are allowed. [Answer] # Pure Bash, 51 Most of the rest of the answers use some sort of conditional. This one dispenses with conditionals entirely, and instead treats the input as a base-36 number which indexes into an appropriately constructed bash-brace-expansion array: ``` a=(_ {A..I} {1..26} {J..Z} {A..Z}) echo ${a[36#$1]} ``` [Ideone.](https://ideone.com/zFW3J7) [Answer] # Erlang, 26 bytes ``` f([X])->X-64;f(X)->[X+64]. ``` One of the few times where Erlang's string behavior is useful. [Answer] ## Actually, 7 bytes ``` ú' +ûEí ``` [Try it online!](http://actually.tryitonline.net/#code=w7onICvDu0XDrQ&input=IkUi) Explanation: ``` ú' +ûEí ú' + lowercase English alphabet, prepend space û uppercase E element (pushes the nth letter if input is an integer, leaves stack alone otherwise) í index (pushes index of input if input is a string, leaves stack alone otherwise) ``` If lowercase is acceptable, this is 6 bytes: ``` ú' +Eí ``` [Try it online!](http://actually.tryitonline.net/#code=w7onICtFw60&input=ImUi) [Answer] # Python 2, 38 bytes ``` lambda x:x>''and 64^ord(x)or chr(64^x) ``` Test it on [Ideone](http://ideone.com/E9pcsJ). [Answer] # Python 3, 43 bytes ``` lambda x:x!=str(x)and chr(64|x)or ord(x)^64 ``` The interesting thing about this solution is that it incorporates all the senses of OR, bitwise OR `|`, logical OR `or`, bitwise XOR `^` and logical XOR `!=` ... [Answer] # [2sable](http://github.com/Adriandmen/2sable), ~~9~~ 8 bytes Code: ``` .bAu¹kr, ``` Explanation: ``` .b # Convert 1 -> A, 2 -> B, etc. A # Push the alphabet. u # Convert it to uppercase. ¹k # Find the index of the letter in the alphabet. r # Reverse the stack. , # Pop and print with a newline. ``` Uses the **CP-1252** encoding. [Try it online!](http://2sable.tryitonline.net/#code=LmJBdcK5a3Is&input=Rw). [Answer] # Ruby, ~~47 39 + `n` flag = 40 bytes~~ ~~33~~ ~~34~~ 31 bytes Anonymous function. Uses an exception handling trick like in @KarlNapf's [Python solution](https://codegolf.stackexchange.com/a/89968/52194). -3 bytes from @manatwork [Try it online](https://repl.it/Cn5s) ``` ->i{(64+i).chr rescue i.ord-64} ``` Original full program version with the `n` flag for 40 bytes and reads from STDIN: ``` puts$_!~/\d/?$_.ord-64:(64+$_.to_i).chr ``` [Answer] # Cheddar, ~~34~~ 32 bytes *Saved 2 bytes thanks to @LeakyNun* ``` n->"%s"%n==n?n.ord()-64:@"(n+64) ``` I wish there was shorter way to check if string or number. [Try it online!](http://cheddar.tryitonline.net/#code=bi0-IiVzIiVuPT1uP24ub3JkKCktNjQ6QCIobis2NCk&input=MQ) or [Test Suite](http://cheddar.tryitonline.net/#code=bGV0IGY9IG4tPiIlcyIlbj09bj9uLm9yZCgpLTY0OkAiKG4rNjQpOwpwcmludCBmKDEpOwpwcmludCBmKDI2KTsKcHJpbnQgZigiQSIpOwpwcmludCBmKCJaIik7&input=) ## Explanation ``` n -> // func with arg `n` "%s"%n==n ? // if n is string... (see below) n.ord() - 64 // return code point - 64 : // else... @"(n+64) // chr(n+64) ``` `"%s"%n==n` checks if it is a string in a simple way. `"%s"` is a string format, I can format with `%` e.g. `"a %s c" % "b"` is equal to `"a b c"`. `%s` specifies it is a string, if a digit is passed it'll remain as `%s`. [Answer] # Mathematica ~~54~~ 41 Bytes With an absolutely clever suggestion from LegionMammal978 that saves 13 bytes. ``` If[#>0,FromLetterNumber,,LetterNumber]@#& ``` `If[#>0,FromLetterNumber,,LetterNumber]` serves the sole purpose of deciding whether to apply `FromLetterNumber` or `LetterNumber` to the input. `#>0` will be satisfied if the input, `#`, is a number, in which case `FromLetterNumber`will be selected. However `#>0` will be neither true nor false if `#` is a letter, and `LetterNumber` will be selected instead. --- ``` If[#>0,FromLetterNumber,,LetterNumber]@#&["d"] ``` 4 --- ``` If[#>0,FromLetterNumber,,LetterNumber]@#&[4] ``` d --- In Mathematica, `FromLetterNumber` and `LetterNumber` will also work with other alphabets. This requires only a few more bytes. ``` If[# > 0, FromLetterNumber, , LetterNumber][#, #2] &[4, "Greek"] If[# > 0, FromLetterNumber, , LetterNumber][#, #2] &[4, "Russian"] If[# > 0, FromLetterNumber, , LetterNumber][#, #2] &[4, "Romanian"] ``` δ г b ``` If[# > 0, FromLetterNumber, , LetterNumber][#, #2] &[δ, "Greek"] If[# > 0, FromLetterNumber, , LetterNumber][#, #2] &[г, "Russian"] If[# > 0, FromLetterNumber, , LetterNumber][#, #2] &[b, "Romanian"] ``` 4 4 4 [Answer] ## Haskell, 54 bytes ``` f s|s<"A"=[['@'..]!!read s]|1<2=show$fromEnum(s!!0)-64 ``` Usage example: `map f ["1","26","A","Z"]` -> `["A","Z","1","26"]`. Haskell's strict type system is a real pain here. Additionally all the short char <-> int functions like `chr` and `ord` need an import, so I have to do it by hand. For the letter -> int case, for example I need to convert `String` -> `Char` (via `!!0`) -> `Integer` (via `fromEnum`) -> `String` (via `show`). [Answer] # C, 55 bytes ``` i;f(char*s){i=atol(s);printf(i?"%c":"%d",64^(i?i:*s));} ``` [Answer] # [Perl 6](http://perl6.org), 25 bytes ``` {+$_??chr $_+64!!.ord-64} ``` ## Explanation: ``` # bare block lambda with implicit parameter of 「$_」 { +$_ # is the input numeric ?? chr $_ + 64 # if it is add 64 and get the character !! $_.ord - 64 # otherwise get the ordinal and subtract 64 } ``` ## Example: ``` say ('A'..'Z').map: {+$_??chr $_+64!!.ord-64} # (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) say (1..26).map: {+$_??chr $_+64!!.ord-64} # (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) ``` [Answer] # C#, 32 bytes ``` n=>(n^=64)>26?(object)(char)n:n; ``` Casts to `Func<int, object>`. Input: `char` implicitely converts to `int` so can be called with `int` (1-26) or `char` ('A'-Z'). Output: Either a `char` or `int`. [Answer] ## PHP, 49 41 40 bytes ``` <?=+($i=$argv[1])?chr($i+64):ord($i)-64; ``` I do not think there is a good alternative to `is_numeric` right? This is executed from command line (`$argv[1]` is the first variable given) ## Thanks to: @insertusernamehere: Golfed 8 bytes. Replacing `is_numeric($i=$argv[1])` with `0<($i=$argv[1])`.This works because `(int)"randomLetter" == 0`. @manatwork: Reduced with 1 byte. Replace `0<` with `+`. What happens in this case is that the + signal will cast the "Z" (or whatever letter) to an 0. This will result in false. Therefor any letter is always false and a number is always true. [Answer] # Excel, 33 bytes ``` =IFERROR(CHAR(A1+64),CODE(A1)-64) ``` [Answer] # Python 2, 61 bytes ``` i=raw_input() try:o=chr(int(i)+64) except:o=ord(i)-64 print o ``` Yes I could switch to Python 3 for `input` [Answer] ## PowerShell v2+, 42 bytes ``` param($n)([char](64+$n),(+$n-64))[$n-ge65] ``` Takes input `$n` (as an integer or an explicit char) and uses a pseudo-ternary to choose between two elements of an array. The conditional is `$n-ge65` (i.e., is the input ASCII `A` or greater). If so, we simply cast the input as an int and subtract `64`. Otherwise, we add `64` to the input integer, and cast it as a `[char]`. In either case, the result is left on the pipeline and printing is implicit. ## Examples ``` PS C:\Tools\Scripts\golfing> ([char[]](65..90)|%{.\alphabet-to-number.ps1 $_})-join',' 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 PS C:\Tools\Scripts\golfing> (1..26|%{.\alphabet-to-number.ps1 $_})-join',' 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 ``` [Answer] # [Befunge-98](https://github.com/catseye/Funge-98/blob/master/doc/funge98.markdown)\*, 19 bytes ``` &:39*\`'@\j;+,@;-.@ ``` Because the question said you'll receive a `1-26` or an `A-Z` I assumed this meant the number 26 or the character A-Z. Most interprets struggle with entering alt-codes, so it is easier to use `&` and enter values like 26 for 26 or 90 for 'Z', as opposed to `~`. ## Pseudo-code ``` int c = get stdin push the value of 27 bool is_number = 27 > c push the value of `@` (64) if is_number == 1 jump to adding 64 to c //putting it the ASCII range print as ASCII end else jump to subtracting 64 from c //putting it in the numerical range print as number end ``` Test it out (on Windows) [here!](https://github.com/tngreene/BefungeSharp) \*This is technically Unefunge-98 because it only uses 1 dimension, but that name might be unfamiliar. [Answer] ## [Befunge 93](https://esolangs.org/wiki/Befunge), 144 90 66 54 36 19 bytes Not 100% sure if this is allowed, but if you are allowed to type A as 65, B as 66, etc., then (for [my] convenience's sake): ``` &:"@"`"@"\#. #-_+,@ ``` Otherwise, at 36 bytes: ``` ~:0\"A"-`#v_88*-.@ **~28*++,@>68*-52 ``` (Thanks to tngreene for the suggestions!) ``` ~:0\567+*-`#v_88*-.>$28*+,@ 52**\28*++,@>~:0`!#^_\68*- ``` (Thanks to Sp3000 for saving 12 bytes by rearranging!) ``` ~:0\567+*-`#v_88*-.>$82*+,@ >~:0`!#^_\68*-52**\28*++,@ v >$28*+,@ >~:0`!#^_\68*-52**\28*++,@ >~:0\567+*-`#^_88*-.@ v >$28*+,@ ~ >11g~:0`!| 1 >\68*-52**\28*++,@ 1 p >011g567+*-`| >11g88*-.@ ``` Ungolfed: ``` v >$ 28* + , @ >~:0 `!| >\ 68* - 52* * \ 28* + + , @ >~:0\ 5 67+ * - `| >88* - . @ ``` This is my first working Befunge program ever, and I feel the need to golf this further. Any help would be greatly appreciated. You can test Befunge code [here](http://www.quirkster.com/iano/js/befunge.html). [Answer] # Brainfuck, 445 Characters More a proof of concept than a golfed code. Requires Unsigned, Non-wrapping Brainfuck. ``` ,[>+>+<<-]>[<+>-]>>++[->++++++<]>[-<<<+++++>>>]<<<<[->-<]>[,<++++[->------------<]++++[->>------------<<][-<<++++++++++>>]>[-<+>]>[-<<++++++++++>>]>++[->++++++<]>+[-<+++++>]<-[-<<<+>>>]<<<.>]>[[-<+<+>>]>++[->++++++<]>+[-<+++++>]<-[-<<->>]<<[->+>+<<]>>>++++++++++<+[>[->+>+<<]>[-<<-[>]>>>[<[-<->]<[>]>>[[-]>>+<]>-<]<<]>>>+<<[-<<+>>]<<<]>>>>>[-<<<<<+>>>>>]<<<<<-[->+>+<<]>[-<++++++++++>]<[-<->]++++[-<++++++++++++>]++++[->>++++++++++++<<]>>.<<<.>] ``` With Comments ``` ,[>+>+<<-] Firstly Duplicate it across two buffers >[<+>-] Move the second buffer back to the first buffer >>++[->++++++<]>[-<<<+++++>>>] Establish 60 in the second buffer <<<< Compare Buffers 1 and 2 [->-<] > [ If there's still data in buffer 2 , Write the value in the units column to buffer two < ++++ [->------------<] Subtract 12 from the units buffer ++++ [->>------------<<] Subtract 12 from the tens buffer [-<<++++++++++>>] Multiply buffer three by ten into buffer 1 > [-<+>] Add the units > [-<<++++++++++>>] Add the tens >++ Add 65 to the buffer [->++++++<]>+ [-<+++++>] <- Actually we need 64 because A is 1 [-<<<+>>>] Add 64 to the first buffer <<< . Print the new letter > Move to blank buffer ] > [ Otherwise we're a letter [-<+<+>>] Copy it back over the first two buffers >++ Write 64 to the buffer [->++++++<]>+ [-<+++++>] <- [-<<->>] Subtract 64 from the letter <<[->+>+<<] >>>++++++++++< Copy pasted Division step x = current buffer y = 10 rest of the buffers are conveniently blank + [>[->+>+<<]>[-<<-[>]>>>[<[-<->]<[>]>>[[-]>>+<]>-<]<<]>>>+<<[-<<+>>]<<<]>>>>>[-<<<<<+>>>>>]<<<<< - [->+>+<<] >[-<++++++++++>] <[-<->] ++++ [-<++++++++++++>] ++++ [->>++++++++++++<<] >>.<<<.> ] ``` [Answer] # Java, ~~104~~ ~~98~~ ~~97~~ ~~83~~ ~~54~~ ~~53~~ ~~51~~ ~~50~~ 30 bytes `x->(x^=64)>64?(char)x+"":x+"";` **Test Program**: ``` IntFunction<String> f = x -> (x ^= 64) > 64 ? (char) x + "" : x + ""; out.println(f.apply('A')); // 1 out.println(f.apply('Z')); // 26 out.println((f.apply(1))); // A out.println((f.apply(26))); //Z ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 67 bytes ``` : f 2dup s>number? if d>s 64 + emit else 2drop d>s c@ 64 - . then ; ``` [Try it online!](https://tio.run/##hY/dTgIxEIXveYrjcoHGXSIbgomYVV7DhYvSnUKTbqdpuyK@PLaAwTt7M3/nzDdV7OO@2qkcTqcXKNTd4BAaO/Rb8m/QCl0TsJjjEdTrCDKBksizOw/ke55VmCLuyWKZdrjLjnh0hJzUaSy2AcEJSQHTAqgaFIklPZZYw3ltI7R1Q8S9IRUrYfTOUpd6FxdYIejvBH4or/KiaorfnIeYvUmkSig2hg/JvD3C0sFoS6NR/YwZ2o43aPUGT3gdYxwwbtKxrWF2G6S3Rk6hPPdJHRn1ooRk@0k@n9fRV26GmJi7hBYhXIvcVoOVUbMdTVpMVjeWEx3k3TnMbrS/qFW2f5RpF3uC3AsvZCSfPx@pd@yFP/5HPf0A "Forth (gforth) – Try It Online") Input is passed as a string to the function ### Code Explanation ``` : f \ start a new word definition 2dup \ make a copy of the input string s>number? \ attempt to convert to a number in base 10 if \ check if successful d>s \ drop a number (don't need double-precision) 64 + emit \ add to 64 and output the ascii letter at that value else \ if not successful (input was a letter) 2drop d>s \ get rid of garbage number conversion result and string-length c@ 64 - . \ get ascii value of char, subtract 64 and output then \ end the if block ; \ end the word definition ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` i@ịe?ØA ``` [Try it online!](https://tio.run/##y0rNyan8/z/T4eHu7lT7wzMc/7sdbn/UtCby/39DHQVTHQUjEDbTUVByVAISHiAiEEREKQEA "Jelly – Try It Online") ## How it works ``` i@ịe?ØA - Main link. Takes an input A on the left ØA - Set the right argument to "ABC...XYZ" ? - If statement: e - Condition: left in right; is A in the alphabet? i@ - If so: return the 1-index of A in the alphabet ị - Else: yield the A'th element of the alphabet ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~11~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ¤?UdI:InUc ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=pD9VZEk6SW5VYw&input=WzgsIkgiXS1tUw) ``` ¤?UdI:InUc :Implicit input of integer or string U ¤ :Convert to binary string if integer (always truthy) ¤ :Slice off first 2 character if string (always falsey) ? :If truthy Ud : Get character at codepoint U I : After first adding 64 : :Else In : Subtract 64 from Uc : Codepoint of U ``` [Answer] # q, 29 bytes ``` {@[1+.Q.A?;x;{.Q.A y-1}[;x]]} ``` Find the index at which our letter occurs in the built-in list of uppercase letters If it errors, index into the same list with the input instead Adding and taking away ones as q indexing starts at 0, not 1 [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), ~~[27](https://codegolf.stackexchange.com/revisions/259112/1)~~ ~~[24](https://codegolf.stackexchange.com/revisions/259112/2)~~ ~~[21](https://codegolf.stackexchange.com/revisions/259112/3)~~ 19 bytes ``` <o+v?)0-}:"@": n-$< ``` [Try it with a number test case](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiPG8rdj8pMC19OlwiQFwiOlxubi0kPCIsImlucHV0IjoiIiwic3RhY2siOiIyNiIsInN0YWNrX2Zvcm1hdCI6Im51bWJlcnMiLCJpbnB1dF9mb3JtYXQiOiJjaGFycyJ9) [Try it with a letter test case](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiPG8rdj8pMC19OlwiQFwiOlxubi0kPCIsImlucHV0IjoiIiwic3RhY2siOiJBIiwic3RhY2tfZm9ybWF0IjoiY2hhcnMiLCJpbnB1dF9mb3JtYXQiOiJjaGFycyJ9) Takes input on the stack, which is [a default input method for stack-based languages](https://codegolf.meta.stackexchange.com/a/8493/114970), and outputs with error. [Answer] ## JavaScript (ES6), 49 bytes ``` s=>s>0?String.fromCharCode(s|64):parseInt(s,36)-9 ``` Accepts integers in either number or string format, always return integers as a number. 42 bytes if I can return lower case and don't need to handle integers in string format: ``` s=>s>0?(s+9).toString(36):parseInt(s,36)-9 ``` [Answer] # Fourier, 30 bytes ``` I~F<64{1}{F+64a}F>64{1}{F-64o} ``` [**Try it online!**](http://fourier.tryitonline.net/#code=SX5GPDY0ezF9e0YrNjRhfUY-NjR7MX17Ri02NG99&input=RQ) [Answer] ## R, 73 bytes ``` f=function(x){L=LETTERS;if(is.numeric(x)){i=L[(x)]}else{i=which(L==x)};i} ``` [Answer] # MATL, 10 bytes ``` 6WZ~t42>?c ``` Explanation: ``` 6W % 2**6 = 64, but golfier looking Z~ % bit-wise XOR with input t42>? % if result is greater than 42 c % convert it to a character % else, don't ``` [Try it online!](http://matl.tryitonline.net/#code=NldafnQ0Mj4_Yw&input=WzE6MjZd) with numeric inputs. [Try it online!](http://matl.tryitonline.net/#code=NldafnQ0Mj4_Yw&input=WydBJzonWidd) with alphabetic inputs. ]
[Question] [ ## Story Have you seen [this](https://9gag.com/gag/aE2y7MO) post from [9gag](https://9gag.com/)? Maybe you got the feeling to make your own sentences. But then you realize that you could just golf a script in half an hour, and you will never have to deal time with that. ## The submission Your program will get an input string which it will return with added quotation marks as explained below. Standard loopholes are forbidden. Output as a list of lines is allowed. Trailing spaces and empty lines that don't break the output are allowed. ## The rules of input * The input only contains printable ASCII characters. * The input may contain spaces. The words are determined with them. * It's guaranteed that a space will never be followed by another space. * The case of no input or empty string doesn't matter. ## The rules of output If one word is given then the program has to return the string between quotation marks. If the input string has 2 or more words, it first returns the initial input, but the first word is in quotation marks. Then on the next line, it returns the initial input, but with the second word in quotes. And so on for the remaining words. In general, the program has to return as many lines as there are words in the input. ## Examples: ``` test -> "test" This is codegolf -> "This" is codegolf This "is" codegolf This is "codegolf" This is a significantly longer, but not the longest testcase -> "This" is a significantly longer, but not the longest testcase This "is" a significantly longer, but not the longest testcase This is "a" significantly longer, but not the longest testcase This is a "significantly" longer, but not the longest testcase This is a significantly "longer," but not the longest testcase This is a significantly longer, "but" not the longest testcase This is a significantly longer, but "not" the longest testcase This is a significantly longer, but not "the" longest testcase This is a significantly longer, but not the "longest" testcase This is a significantly longer, but not the longest "testcase" Here is an another one -> "Here" is an another one Here "is" an another one Here is "an" another one Here is an "another" one Here is an another "one" ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the least byte answer wins! [Answer] ## vim, 38 bytes ``` :s/"/<C-d>/g qqysW"Ypds"W@qq@qdk:%s/<C-d>/"/g ``` [Try it online!](https://tio.run/##K/v/36pYX0nfxlk3xU4/nauwsLI4XCmyIKVYKdyhsNChMCXbSrUYKq0EVPD/f0lGZrECECUqKJWkFpco/dctAwA) Requires the [vim-surround plugin](https://github.com/tpope/vim-surround). If the input does not contain `"` characters, this can be done in **19 bytes**: ``` qqysW"Ypds"W@qq@qdk ``` Here, we record a recursive macro (`qq ... @qq@q`) that surrounds a word with quotation marks (`ysW"`), duplicates the line (`Yp`), deletes the quotation marks (`ds"`), and moves to the next word (`W`) before calling itself recursively. After it terminates, there are two extraneous lines, which are deleted with `dk`. The full solution simply wraps this with `:s/"/<C-d>/g` at the beginning, which replaces existing `"` characters with an unprintable character, and `:%s/<C-d>/"/g` at the end, which undoes the replacement. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḳ⁾""j$€⁹¦K¥ⱮJ$ ``` **[Try it online!](https://tio.run/##y0rNyan8///hjk2PGvcpKWWpPGpa86hx56Fl3oeWPtq4zkvl/@H2yP//QzIyixWAKDk/JTU9PycNAA "Jelly – Try It Online")** ### How? ``` Ḳ⁾""j$€⁹¦K¥ⱮJ$ - Link: list of characters, S Ḳ - split (S) at spaces -> A $ - last two links as a monad: Ɱ - map... J - ...across: range of length -> I = [1,2,...len(A)] ¥ - ...doing: last two links as a dyad: i.e. f(A, i) for i in I € ¦ - sparse application... ⁹ - ...to indices: chain's right argument, i $ - ...action: last two links as a monad: ⁾"" - literal list of characters = ['"', '"'] j - join (with A[i]) -> (e.g. with ['i','s']) ['"','i','s','"'] K - join with spaces ``` [Answer] ## Haskell, 65 bytes ``` ([]#).words a#(b:c)=unwords(a++('"':b++"\""):c):(a++[b])#c _#_=[] ``` Returns a list of lines. [Try it online!](https://tio.run/##VYyxbsMwDER3fwUhD5HgNB9gwHuHdmo3RzBkhbKFKpQhySj681WZeCpwIB@Ph1tN/sIQqoMBrlWOulWX75huuTGtnHurhp2etzRdJ0/i1M9dJ65CKP71D3OctWptM7XTMOp6N5646m629wnksba9fJT0RnAByXkhtGJ0CsYGQBTMRZwf9Ln6DCwbb7jE4P67BrJfyDtvDZXwAyHSgukM816AYoGy4uFlZh7WZDwaXjHhs4FYkXMJIqHQ9de6YJZcX@y2/QE "Haskell – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 17 bytes ``` " $'¶$` " ^|$ " ``` [Try it online!](https://tio.run/##PYtBCkIxDET3OUUoFV14Dz2Aa/m15reBkkATF4Ln@gfwYrUoCMNjeMx0cpY0dofTMhACxv17iwsGuL4ihDGczOFS2XAm652KtvUvEhoX4ZVzEm9PbCqF@hFvD0dRR6/0czb7RE5GcKZO3/NcVOqoQh8 "Retina 0.8.2 – Try It Online") Link includes test suite. Explanation: ``` " $'¶$` " ``` Expand each space by duplicating the line and then inserting quotation marks. ``` ^|$ " ``` Fix the first and last lines. [Answer] # JavaScript (ES6), ~~43 42 41~~ 38 bytes *Saved 3 bytes thanks to @mazzy* Uses the non-standard but widely supported [`RegExp.left​Context`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/leftContext) and [`RegExp.rightContext`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/rightContext). That's a lot of different quotes... ``` s=>s.replace(/(\S+) ?/g,`$\`"$1" $' `) ``` [Try it online!](https://tio.run/##fYxBCsIwEEX3PcUQAiZYWzxA9RC67KIxTtJIyJRMFDx9DLhzIXw@n8fnPczLsM1hK4dEd6xuqjydeMi4RWNRjWq@7DWcR98vcl6EPAqQu27R1VJiijhE8sopcUUuQuvuF6@BocU2uafo/lwMcPApuGBNKvENkZLH3MPtWSBRgbLil3HbraxhbLr6AQ "JavaScript (Node.js) – Try It Online") [Answer] # Java, ~~235 183~~ 132 bytes ``` s->{String a[]=s.split(" "),r="",t;for(int l=a.length,i=0,j;i<l;i++,r+="\n")for(j=0;j<l;)r+=(t=i==j?"\"":"")+a[j++]+t+" ";return r;} ``` -52 bytes by abusing a variety of things (static access, list vs array, print instead of returning, etc. Thanks @ValueInk!) -51 bytes by beung lazy and letting @KevinCruijssen do the work for me [Try it online](https://tio.run/##NY4xa8MwEIV3/4rjJgk5JnNUtVu2TunmeFBtyZGqyEY6B4Lxb3dVSOHgHY/v3j2vH/rgh5@9Dzpn@NQurpWLZJLVvYHzeqHk4giWvZbM5VbNy3dwPWTSVOQxuQHu5fLFtB3oNGa@VmewoPZ8eP@P0W2ncpPn4IghIK@TQqxJ2imx8hWC0k0wcaRb7dSx9tK9BemEqJNQeI3I/0CvjtIXnxeTkXJK@Q@8Ip4QudCtF6ITJEq8TIaWFCHJbZfV5ZnJ3JtpoWYuZShEZhvL8OvmMpTpp8GMU7DIuay2bf8F) [Answer] First code golf attempt hopefully it's not terrible and hopefully it's not rule breaking ## Kotlin, ~~105~~ ~~112~~ ~~147~~ 117 bytes/chars ``` fun main(a:Array<String>){val q=a[0].split(" ") q.forEach{println(q.fold(""){i,n->i+if(it==n)"\"$n\" " else n+" "})}} ``` [Try it online!](https://tio.run/##FYtBCsIwEEX3nmIILhLU4lpswYUn0J11MbZNOzhO2iQKUnr2GOEvHo/3ny4ySUr2LfBCEo2Hk/f4PV6iJ@krM3@QYSrxtr8XYWSKWoEyq6mwzp@xGeYxd5FF/w23Wikz01Z2FW3IaoplKUbVai11/kHHoQPZZFzMsqSUrgMFyGtc2/WOLTwoNgNgCD8 "Kotlin – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) with `-an`, 53 bytes The flags `-an` are read each line and split to `$F`. ``` $F.size.times{|i|a=$F.dup;a[i]=?"+a[i]+?";puts a*' '} ``` [Try it online!](https://tio.run/##PYvdCoJQEITvfYpFAiHLFxDxLnqA7qKLo666YLvi7rmwn1fvdCoIhpnhY2bxzRrC5lAo3bAwuqLeH/RwVUSdn0t3pktVp/kn8zotZ28KbptB9gzBUC05jaQQ1UqHg0z9HzhQGph6ah3btMIkPOCyg8YbsBjYiD@msUdrnWJyxAW/Z46SOFlAGF8yGwlr2Dt@Aw "Ruby – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` ð¡©ε®y…"ÿ"Nǝ}» ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8IZDCw@tPLf10LrKRw3LlA7vV/I7Prf20O7//0syMosVgChRoSS1uAQA "05AB1E – Try It Online") --- +1 byte (and it works for the edge case) thanks to Emigna. -1 byte thanks to Kevin! [Answer] ## JavaScript, ~~91~~ ~~97~~ ~~75~~ 78 bytes ``` f= t=>t.split` `.map((c,i,a)=>[...a.slice(0,i),`"${c}"`,...a.slice(i+1)].join` `) // and test console.log(f("Hello folks and world").join('\n')); ``` Outputs a list of lines as a JavaScript array. The last entry has a trailing space as allowed in the question. The test code writes each entry to the console on a separate line for demonstration purposes. Thanks to Shaggy for 19 bytes off and no leading spaces - when the spread operator is used on an empty array to initialize an array literal, no slots are created in the array produced by the spread operator: ``` let empty = []; let array = [...empty, value] // produces an array of length 1 containing value ``` (The 91 byte version had a leading space on the first line, the 97 byte version took 6 bytes to remove it.) [Answer] # [Python 3](https://docs.python.org/3/), 79, 69, 65 bytes ``` w,i=input(),0 while~i:m=w.split();m[i]='"%s"'%m[i];print(*m);i+=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v1wn0zYzr6C0RENTx4CrPCMzJ7Uu0yrXtlyvuCAnEyhqnRudGWurrqRarKSuCmJbFxRl5pVoaOVqWmdq2xr@/2@oYKRgrGCiYAoA "Python 3 – Try It Online") Shaved 10 bytes thanks to xnor. And now this is 65 bytes as per Erik the Outgolfer solution. Program ends with IndexError but this is fine. [Answer] # Java 8, ~~72~~ ~~71~~ ~~67~~ 62 bytes ``` s->s.replaceAll("(?<=(^.*))(\\S+) ?(?=(.*$))","$1\"$2\" $3\n") ``` [Try it online.](https://tio.run/##dVBNT8MwDL3vV1hRD8k@KgE3xqi4wYFxGDcKUpZmbUbmVI07aUL77SVtgxASkxLLsd97efZeHuViX3x2ykrv4Vka/JoAGCTd7KTSsO6fABtqDJageEy8WIb6eRKCJ0lGwRoQVtD5xb1PG13bQH6wljOe3a34RzoVguf5ZiYg49mKp9NECDZnyVXOkuucQXKTIxPdsles260NilH46EwBh2As/v32DlKMrkh74qyPbPDzU3mtjIdwlCt06ezu/64Eb0o0O6Mkkj2BdVjqZg7blgAdAVV6rHkamEp6/VfpUTd6UArwSjfgMALO4f6uZphgYMTtGaxbijNsTp70IXUtpXVokkXOnvr@LbDZCFxeBL60NCIvYzBVfJSJzs7dNw) **Explanation:** ``` s-> // Method with String as both parameter and return-type s.replaceAll("...", // Replace all matches in this regex "...") // With this // And then return the result ``` *Regex explanation:* ``` (?<=(^.*))(\\S+) ?(?=(.*$)) # === MATCH === (?<= ) # A positive look-behind to: ^.* # The optional leading portion of the string ( ) # (which is captured in capture group 1) \\S+ # Followed by one or more non-space characters, # so the next word in line ( ) # (which is captured in capture group 2) ? # Followed by an optional space (?= ) # Followed by a positive look-ahead to: .*$ # The trailing optional portion of the string ( ) # (which is captured in capture group 3) $1\"$2\" $3\n # === REPLACEMENT === $1 # The match of capture group 1 # (the leading portion) $2 # Followed by the match of capture group 2 # (the current word in the 'iteration'), \" \" # surrounded by quotation marks # Followed by a space character $3 # Followed by the match of capture group 3 # (the trailing portion) \n # Followed by a trailing newline ``` [Answer] # [Ruby](https://www.ruby-lang.org/en/), 98 chars. First submission ever. This can definitely be shortened. I just wanted to get an answer in quickly. ``` a=->s{s.split.each_index{|i|puts s.split.each_with_index.map{|a,j|i==j ? "\"#{a}\"":a}.join(" ")}} ``` [Try it online!](https://tio.run/##bY1BCsJQDET3niJ8NwraAwjVrQdwpyKxjTal/l9@UlTanr1G60ZwMwwzw7zYnJ/DgOlyLa0kUlesCWFWnNjn9Gg77upGBX6qO@u3T25Ytx0uyo7TtIQNuIObttgfnFthn5SB/cyBm/f9gHunJOqOE3NbigQsgIA@aEERgqexep9D3hgtQyW4h5gL/AvH@a6wm8@T8NXzxQZeqydUwV8pLuDcKBgCDDJmYt4kQzHg8AI) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~43~~ 40 bytes ``` {m:ex/^(.*?<<)(\S+)(>>.*)$/>>.join('"')} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJZm@7861yq1Qj9OQ0/L3sZGUyMmWFtTw85OT0tTRR9IZeVn5mmoK6lr1v5P01AKycgsVgCi5PyU1PT8nDQlTaCS4sTK/wA "Perl 6 – Try It Online") Matches all possible words, then joins each list by quotes. This could be one byte shorter if we could output lines in reverse order. ### Explanation: ``` { } # Anonymous code block m:ex/^ $/ # Match all strings (.*?) (.*) # Match before and after sections <<(\S+)>> # And the actual word (with no spaces) >>.join('"') # And join each line by "s ``` [Answer] ## [Reflections](https://gitlab.com/TheWastl/Reflections#reflections), 229 bytes ``` _1 +\ /\/(3\ /(0\ /+_: # \#_: v1=2#_ \ \ /_+/:3; / 1/\:1) /v(3(2/ \3)(3 ;\#@ \ / /:#_(0\:_ / (0* /0 \ 0 >~ <>~ <0 \ *#_/ \ / /\/ v/ \=2#_1/\2#_> (0~ \ ^\ \ / ``` [Test it!](https://thewastl.gitlab.io/Reflections/reflections.html##ICBfMSArXCAvXC8oM1wgIC8oMFwKLytfOiAgICMgXCNfOiB2MT0yI18gXApcICAgICAvXysvOjM7IC8gMS9cOjEpCi92KDMoMi8gXDMpKDMgO1wjQCBcIC8KICAgLzojXygwXDpfIC8gKDAqICAvMCAgXAogMCA+fiAgICA8Pn4gICA8MCBcICAqI18vCiBcICAgICAgIC8gICAgIC9cLyB2LyAKICAgXD0yI18xL1wyI18+ICAoMH4KICAgICAgICAgICAgICAgICBcIF5cClwgICAgICAgICAgICAgICAgICAgL/8w/zIwMP8w/1RoaXMgaXMgYSBzaWduaWZpY2FudGx5IGxvbmdlciwgYnV0IG5vdCB0aGUgbG9uZ2VzdCB0ZXN0Y2FzZQ==) I "quickly" "golfed" this in a "funny" "golfing" language. Looking at all that whitespace, it could probably be shorter. [Answer] # [Haskell](https://www.haskell.org/), 64 bytes ``` map unwords.g.words g(h:t)=(('"':h++"\""):t):map(h:)(g t) g _=[] ``` [Try it online!](https://tio.run/##VU/LasQwELvnK4Qva5NtPiCQew/tqb1lw@J6/aKuHewJpT/fdLrppSBGQhKCCbq925R2N132D71iy5@l3trghzt3XoaR1CTlSZzG0PfiIoRiZ@QyR0p6kOo8rtO88EDMmMDR8xXyoHWjF6pPGQNk389CLIqlU5g7QJBtJM6/6jXEBoYpN@tLcv9djRZ9ji4anSl9IZXsbT3jbSPkQqBgD6@x5mN0s8fCo632vpAZhXsVJf9l/MuyfxuXtG/7g1nXHw "Haskell – Try It Online") Outputs a list of strings. Based on [nimi's answer](https://codegolf.stackexchange.com/a/185426/20260). [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ▓¼MY@≈╢∞◙╗ ``` [Run and debug it](https://staxlang.xyz/#p=b2ac4d5940f7b6ec0abb&i=this+is+codegolf&a=1) Unpacked, ungolfed, and commented, it looks like this. ``` jY split on spaces and store in y register m for each word, run the rest of the program and implicitly output '"|S surround with double quotes yia& start with register y, and replace the ith element, where i is the iteration index J join with spaces ``` [Run this one](https://staxlang.xyz/#c=jY++++%09split+on+spaces+and+store+in+y+register%0Am+++++%09for+each+word,+run+the+rest+of+the+program+and+implicitly+output%0A++%27%22%7CS%09surround+with+double+quotes%0A++yia%26%09start+with+register+y,+and+replace+the+ith+element,+where+i+is+the+iteration+index%0A++J+++%09join+with+spaces&i=this+is+codegolf) [Answer] # [C (gcc)](https://gcc.gnu.org/), 136 133 bytes As C's tokenizing functions would mess up the string on future reads, I instead calculate the number and offsets for each word and then finish when the total number of iterations of the outer loop matches the number of words. ``` i,j=1;f(s,c,t)char*s,*c,*t;{for(i=0;i++<j;puts(""))for(j=0,c=t=s;t;t=c+!!c)printf("%3$s%.*s%s ",(c=index(t,32))-t,t,"\""+!!(i-++j));} ``` [Try it online!](https://tio.run/##HY7BasNADETv@QplqUHalUucHDfbH2l7MGqcyFA3WEoohHz71i7M4c0MAyPtWaRW5bF0eUBjYSe59HM0jsLR82P4mVHLLmtKxzFfb24YAtEaj2XHUrxY9uxF0nYrdJ118gFDc3ix5jVaYxAYpej0dfpF58OeqHV2Dh8hLAvUNqWRKD/rMoTvXidcoZ/PwrBegRgXcyd4bAB0wLV56wj@6f7efVLePGv1ixos6sFP5n8 "C (gcc) – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~60~~ ~~40~~ 36 bytes *-20 bytes inspired by [Arnauld](https://codegolf.stackexchange.com/a/185469/80745)* ``` $args-replace'(\S+) ?','$`"$1" $'' ' ``` [Try it online!](https://tio.run/##rZTRTsMgFIbv@xQnJyhr7C58AKOX3uulibLurGtCoAKLmrlnr0DpZqPdLlpCSsv5@PKTFBr9QcZuScqWbeAO9i0TprJLQ40UJfHFy9NNDve84OwN2S0C4zzj7SHLHhYZ@FZ0Q2jckXW8OH1jmEAeJ/LsD77Wu5UkSIOLw2B5V8FxIhWO4CjRgx0wHul5W1vwvdRrqrTcDOKEIo5V40oMwGg1AH3xcgQBtq5UvalLoZz8AqlVRaaA1c6B0g7clro569/9oxSW/o871XTa2iymIBM4k0kADkQ4wTRMhEmEk019IvQinMUUEqEX4SymkAi9CGcxhUSYRDjZ1CfCXjR@cB7JUNQq37VfbECr4ZEICJ5noqX72c8z8TdWeInxFkwInmF6C3rkuMUcvuEK9vGLWWdqVRXA6LOh0tHa39bstasZsjvp/MS1v8QTGSvIFkvbyNolJMdlSe94dODv9dmh/QE "PowerShell – Try It Online") The result has one extra space and one empty line in the tail. --- # Powershell, no regexp, 60 bytes ``` ($w=-split$args)|%{$p=++$c "$($w|%{$q='"'*!--$p "$q$_$q"})"} ``` [Try it online!](https://tio.run/##rZRNboMwFIT3nOJ15JTQwBGQuuwBuo8IcQiSZQN2lFYJZ6c2P0lRS7IAC2H8Zt6nsWRTqDOv9JEL0bADxXRp1uwcR7oQuWFJlengurqwIt5sWOqBWdGty9iH//YSRaywxZJtWYk6QN3Unve@9siOsJvc8A3Xxg/va7gC/LYQeH/se3XaCU79ZNpp1N4pmHb0ws046RiMnWE60ucx12SfVO15psRhFMeJmFLbTjjDpOoMg/g8QkI6z2R@yNNEGvFNQsmMVyHtToakMmSOvKtp@21faaL5/3Hnku5bW4TkYAkWIiWEEQgzSONE6EGYTRoSwYKwCMklggVhEZJLBAvCIiSXCD0Is0lDIgyg6YvzwSveYqV9lG2uSMnxlXAWPPa0lO6wP/a0x1jimcdS0FvwwDNQYC23LQZ0pRVd2hXTpsplFhLjXwVPDd/bvzjbdlrF9UkYW3i1P/fe2SroJUQpL3Frxe82r25@AA "PowerShell – Try It Online") Less golfed: ``` $words=-split $args # split by whitespaces $words|%{ $position=++$counter $array=$words|%{ $quotation='"'*!--$position # empty string or quotation char "$quotation$_$quotation" } "$($array)" # equivalent to $array-join' ' } ``` [Answer] # JavaScript, 62 bytes Thanks @Shaggy for golfing off 10 bytes ``` f= x=>x.split` `.map((c,i,a)=>(s=[...a],s[i]=`"${c}"`,s.join` `)) console.log(f("Hello folks and world").join('\n')); ``` ### Explanation * The function splits the string at each space (x.split` `) * For each element in the resulting array perform the following function * Create a shallow copy of the array (s=[...a]) * Replace the nth element in the array with itself surrounded with quotation marks (s[i]=`"${c}"`) * return the shallow copy joined with spaces (s.join` `) [Answer] # [Java (JDK)](http://jdk.java.net/), 104 bytes ``` t->{var w=t.split(" ");int i=0;for(var s:w){w[i]='"'+s+'"';System.out.println(s.join(" ",w));w[i++]=s;}} ``` [Try it online!](https://tio.run/##XY/BboMwDIbvPIXFpWTQaOcyetlll526W9VDmgZqBgmKTVFV8ewsgNZJk5xY8W///lKrm9rWl@8J2855hjq8Zc/YyLK3mtFZ@ZJHkW4UEXwqtPCIALr@3KAGYsUh3RxeoA1acmCPtjqeQPmKxNwJ8O4s9a3xb6u4hxIKmHi7f9yUh6FgSV2DnMQQixwtAxaveel8Msu0G8RjOOKp2MSblNJw54c7sWml61l2wZEbm5CsXVgfLLJBiDwMpOmpoHwcp3yBeIKxIaYAsLIBxF9XJAih3cVUrinj7L@igLCyWKJWYdkdGmcr4zM49wzWMfDVrDXixV4rMn8uH8abxcWGcKHXg7MmXuRxhfv97Dy8WwnFE7CUSmvTcTLXxTowRvMZpx8 "Java (JDK) – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~94~~ 76 bytes -18 bytes thanks to Giuseppe ``` m=matrix(s<-scan(,a<-'"'),n<-length(s),n);diag(m)=paste0(a,s,a);write(m,1,n) ``` [Try it online!](https://tio.run/##DcpNCoAgEEDhq0QbRxih1tktusBgZoI/4Qh1@0l4mw9eE8l7pt7iB2wNOyqAZI2alcZiTfIl9Bt4QG9npABZ7w9x9wsQMpLe3ha7h4zrWOS4I08jV08farpEfg "R – Try It Online") Thanks to digEmAll for setting up the TIO properly. It takes in e.g. `This is codegolf` and outputs correctly ``` "This" is codegolf This "is" codegolf This is "codegolf" ``` It uses a matrix format with the sentence repeated `n` times; then we only need to change the diagonal entries. Note that usually, in R code-golf, strings are read in with `scan(,"")`, but any string can be used instead of the empty string as the `what` (or `w`) parameter. Explanation of old ungolfed version: ``` s <- scan(t=scan(,''),w=t) # read in input and separate by spaces n <- length(s) # number of words m = matrix(s, n, n) # fill a matrix, one word per entry, each column corresponds to the whole sentence. The sentence is repeated n times. diag(m) = paste0('"', s, '"') # replace diagonal entries with the corresponding word surrounded by quotes cat(rbind(m,"\n")) # add a \n at the end of each column, then print column-wise ``` [Answer] This is my first code golf. hopefully its not shit. **EDIT: got it down to 54 bytes with a better regular expression.** \*\*EDIT 2: per suggestions, fixed a bug and made it shorter \*\* # [JavaScript (V8)](https://v8.dev/), 46 bytes ``` t=>t.split(' ').map(v=>t.replace(v,'"'+v+'"')) ``` [Try it online!](https://tio.run/##HYtBDsIgEADvvoJwYUmVXk1MPfcRXggFQ11ZApv1@Vi9zGEys3vxPbRc@SLXkZbBy51dr5gZjDLWvX0F@bkWK/oQQc5Gm0mmg9aOeVa@bIpj51Og0gmjQ3pCAr1GRFKJ8NX/zYcabtq6nXIB8yjHfhtf "JavaScript (V8) – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](https://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc) with `/u:System.Text.RegularExpressions.Regex` flag, ~~59~~ 40 bytes ``` s=>Replace(s,"(\\S+) ?","$`\"$1\" $'\n") ``` ~~Port of [my Java 8 answer](https://codegolf.stackexchange.com/a/185575/52210), so look there for an explanation.~~ -19 bytes by porting [*@Arnauld*'s regex](https://codegolf.stackexchange.com/a/185469/52210), since the `$`` and `$'` are supported in C# .NET. [Try it online.](https://tio.run/##dYzBSgNBDIbvPkUYFrqLa8Wr2npSeuipLXiZg@OYnQ2MmWWShe3Ld9y2N0UIyc/Hl9/LnRcqbyP7Z9FMHFq43jV0sCqyWu9wiM5jLa2prd3fNvBiWlN9WFM9WAPVwrJpytPNeybFLTHWXW0URU3T/KKHngTm8ekLQ4rd/4YDocDUkXes8QgxccDcwueowElBe7wymfO8vBP827bBjJe2@aXHDIkvUjmlQSmxlPvxcX8Uxe/lASdd7jCM0eXXacgocjbOCKcf) [Answer] # [Elm](https://elm-lang.org) Using recursion, ~~132,130,121,111,100~~ 99 bytes Golfed down 9 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) technique and another 22 bytes were cracked by [ASCII-only](https://codegolf.stackexchange.com/users/39244/ascii-only). Turned to non-tail recursion during the golf. ``` f b a=case a of c::r->String.join" "(b++("\""++c++"\"")::r)::f(b++[c])r _->[] u=f[]<<String.words ``` [Try it online](https://ellie-app.com/5xXSnKStRq3a1) 85 bytes after exposing `String` functions to the current scope ``` f b a=case a of c::r->join" "(b++("""++c++""")::r)::f(b++[c])r _->[] u=f[]<<words ``` Ungolfed version (Using tail recursion) ``` push : List a -> a -> List a push list el = list ++ [ el ] zip : (List a -> a -> List a -> b) -> List a -> List a -> List b -> List b zip transform before after mapped = case after of [] -> mapped current :: rest -> transform before current rest |> push mapped |> zip transform (push before current) rest wrap : appendable -> appendable -> appendable wrap v str = v ++ str ++ v cb : List String -> String -> List String -> String cb before current rest = before ++ wrap "\"" current :: rest |> String.join " " result : List String result = zip cb [] (String.words "This is code golf") [] ``` [Try ungolfed](https://ellie-app.com/5xYCtbmYhspa1) [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ 12 bytes ``` ¸£¸hYQ²i1X)¸ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=uKO4aFlRsmkxWCm4&input=IlRoaXMgaXMgY29kZWdvbGYiCi1S) 2 bytes saved thanks to Oliver. ``` ¸£¸hYQ²i1X)¸ :Implicit input of string ¸ :Split on spaces £ :Map each X at index Y ¸ : Split input on spaces hY : Set the element at index Y to Q : Quotation mark ² : Repeat twice i1X : Insert X at 0-based index 1 ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~70~~ 65 bytes ``` param($a)$a.Split()|%{$a-replace[regex]"( |^)$_( |$)"," ""$_"" "} ``` [Try it online!](https://tio.run/##ZY/BasMwDIbvfgoh3BJD2jfYPfcOdhht0DIlMXi2sV3akuTZM7Vhpwmh/0cfv0Ax3DjlkZ1bdQ9vMK2REv1Umoym4yk6Wyoz7yZNh8TRUcefiQe@n7GC@WJ0K6IN1giIukWRZV2UqhRIYeFcsN58w4nBZiAvHcrICYLnP/o@CnpSyHbwtrcd@eIe4IIfONXwdS0gKZDctsviZXSU/93owjcPwfWoDMywg@mF9/Kfbl/2I9nChybkopb1Fw "PowerShell – Try It Online") Has test suite in trial. Has 1 leading space on first row, and 1 trailing space on last row. Attempting to refactor. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` E⪪θ ⪫E⪪θ ⎇⁼κμ⪫""λλ ``` [Try it online!](https://tio.run/##bUu7CgIxEOz9iiVVAvELrG0EQfBKmzXEy@K6uUv2hPv6GDnsZB4Mw0xIWEJGbu1SSNSecbLXiUnt7MGAcR5OmeRfP8QiWFZ7nBfkap8eXr@1uXUYD@y@ctvDuUNrQ6IKnQiVRqEHBRTlFTjLGIuH@6IgWUFT3Lrac7eANe7a/s0f "Charcoal – Try It Online") Link is to verbose version of code. Note: Trailing space. Explanation: ``` θ Input string ⪪ Split on literal space E Map over words θ Input string ⪪ Split on literal space E Map over words μ Inner index ⁼ Equals κ Outer index ⎇ If true then "" Literal string `""` ⪫ Joined i.e. wrapping λ Current word λ Otherwise current word ⪫ Joined with literal space Implicitly print each result on its own line ``` [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 34 bytes ``` Join&sp=>{On&_&Repr=>Iota@_}@Split ``` [Try it online!](https://tio.run/##NY7BCsIwDIbve4owZJftCYTJwIt6UFFvY4zapVuhtKWNBxGfvUbdwk/4@ZI/RBAJOWFSsK7TwWlbRF9vXidb9MUFfag3e0ei6d/N1RtN6Yg4xHblvRy77By0pRtG2oqIsX0ZVfalUe/md8ioRlXQZsCVE2/l1ewnHYEl3YCjM2rhOwz45cKyHE0YwFlcprc5JSDq0WqlpbBknmCcHTFUcH8QcAo492eRPTfJv@VZ16UP "Attache – Try It Online") Anonymous function returning a list of lines. ## Explanation ``` Join&sp=>{On&_&Repr=>Iota@_}@Split Split Splits the input on whitespace { =>Iota@_} Over each number K, 0 to #words - 1 On &Repr Apply the Repr (quoting) function &_ on the Kth element in the input Join&sp=> then rejoin the words of each inner sentence ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 123 bytes I wonder if can this be shortened with regular expressions. ``` s=>(r=s.Split(' ')).Select((a,i)=>(string.Join(" ",r.Take(i))+" \""+a+"\" "+string.Join(" ",r.Skip(i+1))).Trim());string[]r ``` [Try it online!](https://tio.run/##hY5BT4QwEIXv/oqXXrYNSOJ5hYtxE43xAsaDeCi1CyOlYFvU9c9js@zFeNhkMpm8efO@Uf5SeVp2s1XXPjiybYq7WzsP2snG6JNWFNg9Pd7ki88L7nKflZOhwDfYCJGV2mgVOJcpibheL7L7kSxnYKnLKtlrTkIkDDVjiUxYHRfJf2PZ08QpuRIxtXI0cCG2q@vl1S3bi2dHQf8F1Jalx984qzryiCXhqbW0JyVtMAeY0bbapWjmADsGhE6vmo9zbEp6zSLylP9AVnNxDibRQOENGnu06EB4Rw@DARYjJnzAwSNgxie@8I0Dfo6M5Rc "C# (Visual C# Interactive Compiler) – Try It Online") ]
[Question] [ To *normalize* a vector is to scale it to a length of 1 ([a unit vector](https://en.wikipedia.org/wiki/Unit_vector)), whilst keeping the direction consistent. For example, if we wanted to normalize a vector with 3 components, **u**, we would first find its length: > > **|u| = sqrt(ux2 + uy2 + uz2)** > > > ...and then scale each component by this value to get a length 1 vector. > > **û = u ÷ |u|** > > > --- # The Challenge Your task is to write a program or function which, given a non-empty list of signed integers, interprets it as a vector, and normalizes it. This should work for any number of dimensions, for example (test cases rounded to two decimal places): ``` [20] -> [1] [-5] -> [-1] [-3, 0] -> [-1, 0] [5.5, 6, -3.5] -> [0.62, 0.68, -0.40] [3, 4, -5, -6] -> [0.32, 0.43, -0.54, -0.65] [0, 0, 5, 0] -> [0, 0, 1, 0] ``` **Rules:** * You can assume the input list will: + Have at least one non-zero element + Only contain numbers within your language's standard floating point range * Your output should be accurate to *at least* **two decimal places**. Returning "infinite precision" fractions / symbolic values is also allowed, if this is how your language internally stores the data. * Submissions should be either a full program which performs I/O, or a function. Function submissions can either return a new list, or modify the given list in place. * Builtin vector functions/classes are allowed. Additionally, if your language has a vector type which supports an arbitrary number of dimensions, you can take one of these as input. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") contest, so you should aim to achieve the shortest solution possible (in bytes). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ### Code: ``` nOt/ ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/z79E////aGMdBRMdBV1TIDaLBQA "05AB1E – Try It Online") ### Explanation ``` n # Square each element of the input O # Sum all elements t # Take the square root of the sum / # Divide each element by the square root of the sum ``` [Answer] # JavaScript (ES6), 31 bytes ``` a=>a.map(n=>n/Math.hypot(...a)) ``` ### Test cases ``` let f = a=>a.map(n=>n/Math.hypot(...a)) console.log(JSON.stringify(f([20] ))) // -> [1] console.log(JSON.stringify(f([-5] ))) // -> [-1] console.log(JSON.stringify(f([-3, 0] ))) // -> [-1, 0] console.log(JSON.stringify(f([5.5, 6, -3.5]))) // -> [0.62, 0.68, -0.40] console.log(JSON.stringify(f([3, 4, -5, -6]))) // -> [0.32, 0.43, -0.54, -0.65] console.log(JSON.stringify(f([0, 0, 5, 0] ))) // -> [0, 0, 1, 0] ``` [Answer] # Mathematica, 9 bytes ``` Normalize ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y@/KDcxJ7Mq9X9AUWZeiUNadLWRQW0sF5yna4rCM9ZRQJE21TPVUTDTUdA11kNRaKxjoqNrqqNrhixoANSso2AKNuI/AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [J](http://jsoftware.com/), 8 bytes ``` %+/&.:*: ``` [Try it online!](https://tio.run/##y/r/P83WSkFVW19Nz0rLCshTMDLgSlOINwURxgogtqmeqYIZkKMHEjNWMAFKKsSbAdkGQGiqYAAA) 6 bytes `%|@j./` works [if the vector is at least 2-dimensional](https://codegolf.stackexchange.com/a/149169/74681). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 3 bytes ``` ÷ÆḊ ``` [Try it online!](https://tio.run/##y0rNyan8///w9sNtD3d0/f//P9pYR8FER0HXFIjNYgE), or see the [test suite](https://tio.run/##y0rNyan8///w9sNtD3d0/T/cfnhZkZGKyqOmNf//RxsZxOooROuagkljHQUw11TPVEfBTEdB11gPLAEUNwHygIK6ZiC@AVCdjoIpSDUA) Saved 2 bytes thanks to miles! [Answer] # [Octave](https://www.gnu.org/software/octave/), 13 bytes ``` @(x)x/norm(x) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzQj8vvygXyPifphFtrKNgoqOgawrEZrEKmv8B "Octave – Try It Online") [Answer] # C, ~~73~~ 70 bytes *Thanks to @Christoph for saving a byte!* ``` s,i;f(v,n)float*v;{for(s=0;i++<n;)s+=*v**v++;for(;--i;)*--v/=sqrt(s);} ``` [Try it online!](https://tio.run/##bY7NboMwEITvPMUKqZJ/KeHv4vAkUQ6I1pElAil2fEG8eumCox4ge7J35tuZVt7adlmsMEoTL3qqu6FxzKtJDyOxdaoM5@deUctr5hnznKtVUVIaRZmU/rO2P6Mjlqp58YP5AvdtHdnOAPMCTO@gp9EUAU7IUOE9jEBW1WAKGAwBzg3dtHUeI4qaxB9JpiEW/mKuL/LxdJbEMf7mKFov3BvTk/@MLXptcbpcoYYpS@fAbc02QcAJ6Z09C3ZZ7u3ZW3v@sucCDgG4y45EEYgyKQVUAmSeHKIKAfkRLAOIV1GXSMtqD@KyOIJVAFOsKKB8U7QK2Lz8trprbnaR3f0P) [Answer] # Python, ~~47~~ 46 bytes ``` lambda v:[e/sum(e*e for e in v)**.5for e in v] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHMKjpVv7g0VyNVK1UhLb9IIVUhM0@hTFNLS88UwY39X1CUmVeikaYRbayjYKKjoGsKxGaxmpr/AQ "Python 3 – Try It Online") [Answer] # [Julia](http://julialang.org/), 9 bytes ``` normalize ``` [Try it online!](https://tio.run/##yyrNyUw0@/8/zTYvvyg3MSezKvV/QVFmXklOnkaaRrSRQaymJheSgK4puoCxjgK6IlM9Ux0FMx0FXWM9dOVA1SZACaC8rhmalAHQIB0FU4hx/wE "Julia 0.6 – Try It Online") [Answer] ## [CJam](https://sourceforge.net/p/cjam), 9 bytes ``` {_:mhzf/} ``` [Try it online!](https://tio.run/##S85KzP1fWBf7vzreKjejKk2/9r@qVcH/aCODWK5oXVMQYawAYpvqmSqYKega64HEjBVMFHRNFXTNgGwDBQMFU6ASAA "CJam – Try It Online") ### Explanation ``` _ e# Duplicate input. :mh e# Fold hypothenuse-length over the vector. This gives the norm, unless the vector e# has only one component, in which case it just gives that component. z e# Abs. For the case of a single negative vector component. f/ e# Divide each vector component by the norm. ``` [Answer] # TI-Basic, 6 bytes ``` Ans/√(sum(Ans2 ``` Run with `{1,2,3}:prgmNAME`, where `{1,2,3}` is the vector to be normalized. Divides each element in the vector by the square root of the sum of the squares of its elements. [Answer] # [R](https://www.r-project.org/), 23 bytes ``` function(v)v/(v%*%v)^.5 ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NMs0xfo0xVS7VMM07P9H@aRrKGoaWOkYGm5n8A "R – Try It Online") `v%*%v` computes the dot product of v with itself. The function will issue a warning for length 2 or greater vectors. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 57 bytes ``` v->v.stream().map(x->x/v.stream().reduce(0d,Math::hypot)) ``` [Try it online!](https://tio.run/##bVHBboMwDL33K6yekg2yah07lA5p0rTTeupx2iGF0IYBiYhBRVO/nQVI1dJNSiL5vWf72cl4w32lRZkl350stKoQMouxGmXO7sLZHyytyxilKv8lDVaCFz2l610uY4hzbgxsuCzhZwZgkKNF312N9Yc0uH5TVisibzskn8MI0peu8aPGFSWUFVyTox8dH66wSiR1LMgi8TYcD6vVodUKKe1C2815cE0bJRMorBNiG8ly//kFvNobOhgDQGGQPC4SGl5CP5iGy8SDqSJggcWe7fWXbKruxU89MSquKevWnqB/B/h0Wc3gchCNe2CMQXP2uG0NioKpGpm2IyB5rSreGoZqHIk01LW5VeYlmYMfwRzu4TYpZVzrvD0X46b/lb6UlQwYodTZPHW/ "Java (OpenJDK 8) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` t2&|/ ``` [Try it online!](https://tio.run/##y00syfn/v8RIrUb///9oYx0FEx0FXVMgNosFAA "MATL – Try It Online") I'm not entirely sure this is the shortest way to do this. First, we duplicate the input, then select the second output type of `|` (which is either `abs`, `norm` or `determinant`). Finally, we divide the input by the norm. Alternative for 7 bytes: ``` t2^sX^/ ``` [Answer] # [Haskell](https://www.haskell.org/), 29 bytes ``` f x=map(/sqrt(sum$(^2)<$>x))x ``` [Try it online!](https://tio.run/##JYs9D8IgGIT/yjt0gOQFSSsdGsti4ubkSNCQSD9iS2vBpP8eMS733F3uBhtebppS6mBvZ7uSQ3hvkYTPXJB7SU@F2ind02xHDy30Lp4XH52PAZRqIR@uDyDrNvoIHDqahWzOPqFp4BZz3QNToPVlWmw0hiatS8GFQc3kHxX@ILnEGlnFZQ4VHpFJZHX2AgXKPDFf "Haskell – Try It Online") Or for 1 byte more pointfree: `map=<<flip(/).sqrt.sum.map(^2)` [Answer] # [Funky](https://github.com/TehFlaminTaco/Funky), 42 bytes ``` a=>(d=a::map)(c=>c/d(b=>b^2)::reduce@+^.5) ``` [Try it online!](https://tio.run/##SyvNy678n2b7P9HWTiPFNtHKKjexQFMj2dYuWT9FI8nWLinOSNPKqig1pTQ51UE7Ts9U839BUWZeiUaaRrWxjomOrqmOrlmtpuZ/AA "Funky – Try It Online") [Answer] # [Ohm v2](https://github.com/nickbclifford/Ohm), 5 bytes ``` D²Σ¬/ ``` [Try it online!](https://tio.run/##y8/INfr/3@XQpnOLD63R//8/2lhHwURHQdcUiM1iAQ "Ohm v2 – Try It Online") [Answer] # C++ (gcc), 70 bytes Input by `std::valarray<float>`. Overwrites the original vector. ``` #import<valarray> int f(std::valarray<float>&a){a/=sqrt((a*a).sum());} ``` [Try it online!](https://tio.run/##bYzLCoMwEEXX5isGS8tM0XbRx8LXvwyxKQFN0hgLRfx2G4XuurhwuY8jncufUi7LTvfO@lC9uWPv@dMIbQIoHEJbFL@wUp3l0ByYJj7Xw8sHRD4ynYaxR6Jyjhgju7F9QCXjU9tGbJyetUESk0j@8aDlwFDDdMngmkF@i7rPpUgUrg2tznrAbQ0aiu1A4HxkK0z3CtIMdNzNyxc "C++ (gcc) – Try It Online") [Answer] # Common Lisp, 69 bytes ``` (lambda(v)(mapcar(lambda(x)(/ x(sqrt(loop as y in v sum(* y y)))))v)) ``` [Try it online!](https://tio.run/##Ncg7EoAgEATRq0zmrIkkHmjVhCp@glJwetTAzl7vzpY0mLINFzjo1G@Hsgq9pl3zP5pwQWM580UXY4IWdNiAinJ7zi@6fFWRMdHAYIV5PR4) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~13~~ ~~12~~ 10 bytes *1 byte saved thanks to @Adám* *2 bytes saved thanks to @ngn* ``` ⊢÷.5*⍨+.×⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHXYsOb9cz1XrUu0JDW//wdCCtCZRRMDLgSlM4tN4UTBorgHimeqYKZiCeHkjUWMEEJA/EZgA) **How?** ``` ⊢ ÷ .5*⍨ +. ×⍨ u ÷ √ Σ u² ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` ²∑√/ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCLCsuKIkeKImi8iLCIiLCJbNS41LCA2LCAtMy41XSJd) ``` ² # Square each ∑ # Sum √ # Square root / # Divide by that ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~8~~ 7 bytes ``` ´(Ṁ/√ṁ□ ``` [Try it online!](https://tio.run/##yygtzv5/aFtusM6jpsb/h7ZoPNzZoP@oY9bDnY2Ppi38//9/dLSRQaxOtK4piDDWAbFN9Ux1zHR0jfVAYsY6Jjq6pjq6ZkC2gY6BjilQSSwA "Husk – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 51+64=115 bytes ``` v=>v.Select(d=>d/Math.Sqrt(v.Select(x=>x*x).Sum())) ``` [Try it online!](https://tio.run/##pZJNT@MwEIbPya8YbjYk3tIPLmkiIQSrlQAhFbGH1R7SZAqWXHvxRyiq@tvLJCUVVL3tJda88jvP65lULq2MxW1wUj/D7N15XGbx10pcGaWw8tJoJ36iRiurgxu3Ur9mcaVK5@BhHTtfelnBTdDV9FY6P61NmCssEvh1rcMSbUlVLxZwb@yyVNLhE1GMhRy2TV40YoYtltV5Uf@4K/2LmL1az/b6Ki9WpysuZmHJOOfbLO7BjZE13JVSMx6v4@iKghuF4reVHikqsid6w@L9gMs0vsHXuLCGIWwSOKKfw4bz7H9aj5Jxkk6S9OI4YCBGw4S@41EC6UBMxt1xMdlxN/unzo1RcJz5rWPTacl3DK7@kYx1N6WmtGDRBeVpAYe9dnYuHk3bgFGEOJILYDsD/SFBkwon@b5nr/E4iiz6YDUsSuWwdS5oyUxqD5JQg4yO6WfA3kXa2RlZKVfH6dZ/OXefwD/yL6R7FFUcCjjHdNjSDnARDauXvA3YTm@z/QA "C# (.NET Core) – Try It Online") +64 bytes for the `using System;using System.Collections.Generic;using System.Linq;` # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 94+13=107 bytes ``` v=>{var m=0d;foreach(var x in v)m+=x*x;for(int i=0;i<v.Length;)v[i++]/=Math.Sqrt(m);return v;} ``` [Try it online!](https://tio.run/##lVFNT4NAED3DrxhvYAHpl5ctTYyJXtSYNKmHpgcKU7vJsqu7C7Zp@tvrQKGaxosXlje7896bN5kJM6XxWBou32G2MxYL5v5G0b0SAjPLlTTRI0rUPLt48cTlJ3MzkRoDr3vX2NTyDB5KmU1yVa4ELpYBdH9TeFG6SAU3OCdapSGBY5VM91WqoUjinK3JUJptvLqwBS6h8otesr3e1jcelxZ4EjM@qaInlO92w/xqwXu95U3ynNpNNPvU1it8ptGWmprZ4cjczlSleA7PKZee7@5d556GUgKjN80t0hjozWm@9e7Coifxa7GEPQxyOATQoT4h32f/phnmwSgIx0F4@4ssjoaDgL6jYQBhHI1HzXE7PkkczhOslBLwN30XMVQN/skccPtBJcyboetcNZpSWIr@kuPUSoquw9fgnd61QcNVcmZqS77rOG3Q61QYrPtoS3BaE/HHjI5J66hbGNC6qJO8NCLN2u5WplVb8CWEZyFCPkyhj@GgFrtQcyiYrmR1iXVSh@M3 "C# (.NET Core) – Try It Online") +13 bytes for `using System;` The non-Linq approach ### DeGolfed ``` v=>{ var m=0d; foreach (var x in v) m+=x*x; for (int i=0; i < v.Length;) v[i++] /= Math.Sqrt(m); return v; } ``` [Answer] # [Perl 5](https://www.perl.org/), 45 + 1 (`-a`) = 46 bytes ``` say$_/sqrt eval join'+',map"($_)**2",@F for@F ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIlXr@4sKhEIbUsMUchKz8zT11bXSc3sUBJQyVeU0vLSEnHwU0hLb/Iwe3/f2MFEwVdUwVds3/5BSWZ@XnF/3V9TfUMDA3@6yYCAA "Perl 5 – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), 10 bytes 9 bytes of code, +1 for `-p` flag. ``` g/RT$+g*g ``` Takes the vector as separate command-line arguments. [Try it online!](https://tio.run/##K8gs@P8/XT8oREU7XSv9////ugX/TfVM/5v91zXWMwUA "Pip – Try It Online") ### How it works ``` g*g Arglist, multiplied by itself itemwise $+ Sum RT Square root g/ Divide arglist itemwise by that scalar Result is autoprinted (-p flag to format as list) ``` [Answer] # Pyth, 5 bytes ``` cR.aQ ``` Try it online: [Test Suite](https://pyth.herokuapp.com/?code=cR.aQ&test_suite=1&test_suite_input=%5B20%5D%0A%5B-5%5D%0A%5B-3%2C%200%5D%0A%5B5.5%2C%206%2C%20-3.5%5D%0A%5B3%2C%204%2C%20-5%2C%20-6%5D%0A%5B0%2C%200%2C%205%2C%200%5D&debug=0) ### Explanation: ``` cR.aQQ implicit Q at the end c divide R Q each element of the input .aQ by the L2 norm of the input vector ``` [Answer] # [Perl 6](http://perl6.org), 25 bytes ``` {$_ »/»sqrt sum $_»²} ``` [Try it online!](https://tio.run/##HYo7DsIwFASvMooiKhwszHOTz1UiClwRATYUUZRL0brzxYxxs9LM7PPm7zYvKwfHmLd2JsVTiuHl34TPQjunmL577gnXlab0cWJzxe8N7uEZzno6Miipa6gknWBRpqvWcEEJyv5Bo5Hy6vMP "Perl 6 – Try It Online") `$_`, the list argument to the function, is divided elementwise (`»/»`) by the square root of the sum of the squares of the elements (`»²`). [Answer] # Ruby, ~~39~~ 35 bytes ``` ->v{v.map{|x|x/v.sum{|x|x*x}**0.5}} ``` -4 bytes thanks to G B. [Answer] # [Coconut](http://coconut-lang.org/), 40 bytes ``` x->map((/)$(?,sum(map(t->t*t,x))**.5),x) ``` I have no idea what I'm doing... [Try it online!](https://tio.run/##HYqxCsMgGITn9ilu6KDya0NTMwRqHyTtUAKC0GhIDDj03a263N13d3OYgz9itnjglZM0y2dl7Mov7En7sbCKUZooIiXOhVCal5Bt2JDgPKZb9yZMUjftCQ210oSBIHvVhtLfC5VSDpW78iPo@h7Pp4Sfga3ydXusvm7Ox/wH "Coconut – Try It Online") [Answer] # [Thunno](https://github.com/Thunno/Thunno) `D`, \$ 5 \log\_{256}(96) \approx \$ 4.12 bytes ``` 2^St/ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSSi1LsgqWlJWm6FkuN4oJL9CFsqNCCddHGOgomOgq6pkBsFgsRBQA) #### Explanation ``` 2^St/ # D flag duplicates the input 2^ # Square each S # Sum this list t # Push the square root / # Divide the input by this number ``` ]
[Question] [ The **subfactorial** or **rencontres numbers** ([A000166](https://oeis.org/A000166)) are a sequence of numbers similar to the factorial numbers which show up in the combinatorics of permutations. In particular the **n**th subfactorial **!n** gives the number of [derangements](https://en.wikipedia.org/wiki/Derangement) of a set of **n** elements. A derangement is a permutation in which no element remains in the same position. The subfactorial can be defined via the following recurrence relation: ``` !n = (n-1) (!(n-1) + !(n-2)) ``` In fact, the same recurrence relation holds for the factorial, but for the subfactorial we start from: ``` !0 = 1 !1 = 0 ``` (For the factorial we'd have, of course, **1! = 1**.) Your task is to compute **!n**, given **n**. ## Rules Like the factorial, the subfactorial grows very quickly. It is fine if your program can only handle inputs **n** such that **!n** can be represented by your language's native number type. However, your *algorithm* must in theory work for arbitrary **n**. That means, you may assume that *integral* results and intermediate value can be represented exactly by your language. Note that this excludes the constant **e** if it is stored or computed with finite precision. The result needs to be an exact integer (in particular, you cannot approximate the result with scientific notation). You may write a [program or a function](https://codegolf.meta.stackexchange.com/q/2419) and use any of the [standard methods](https://codegolf.meta.stackexchange.com/q/2447) of receiving input and providing output. You may use any [programming language](https://codegolf.meta.stackexchange.com/q/2028), but note that [these loopholes](https://codegolf.meta.stackexchange.com/q/1061/) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins. ## Test Cases ``` n !n 0 1 1 0 2 1 3 2 4 9 5 44 6 265 10 1334961 12 176214841 13 2290792932 14 32071101049 20 895014631192902121 21 18795307255050944540 100 34332795984163804765195977526776142032365783805375784983543400282685180793327632432791396429850988990237345920155783984828001486412574060553756854137069878601 ``` [Answer] ## [Funciton](https://github.com/Timwi/Funciton), 336 bytes Byte count assumes UTF-16 encoding with BOM. ``` ┌─╖┌─╖ ┌─╖ │f╟┤♭╟┐┌┤♭╟┐ ╘╤╝╘═╝├┘╘═╝├────┐ │┌─╖ │ ┌┐┌┘╔═╗╓┴╖ ││f╟─┴┐└┴┼─╢0║║f║ │╘╤╝ │ │ ╚═╝╙─╜ │┌┴╖ ┌┴╖┌┴╖ ╔═╗ ││+╟┐│×╟┤?╟┐║1║ │╘╤╝│╘╤╝╘╤╝┘╚╤╝ └─┘ └─┘ └───┘ ``` This defines a function `f` which takes one integer and outputs another integer at a 90 degree turn to the left. It works for arbitrarily large inputs. [Try it online!](https://tio.run/nexus/funciton#dVIxDsIwDNz7iuwssLDym0osDMADqg5MDC3YNCAQEurKxsjGT/yR4thJk4oi3XBxbN/ZSUewJygITz0xJtKMoMwJ7wQtnZ9CKrmNx4zQEraENyGVI3AlsMNjkaDKWKKMKnxQTe3NZSCVDeGR4MUpvsB7KVzQJYOQt7R5TAlrBqfUmh58GRFQFbx4T3iWqmu08lIrniWh4CaYmIQ9lJ9Gd7PwEaxnP@oDHoNWrDju0kGGsgnrqcJ2wYaiMfw2WBvOY8EwVqvD8Z2Mm/kVuyUVI@C9uqVstmvaHZarre9lk16/uI31Tn7NP7gUkctNeERGa1iX1dlDDPceqjDPMDBiqpt/AQ "Funciton – TIO Nexus") Considering this is Funciton it's even *reasonably* fast (n = 20 takes about 14 seconds on TIO). The main slowdown comes from the double-recursion, as I don't think the Funciton interpreter automatically memoises functions. Unfortunately, some monospaced fonts don't correctly monospace the `♭` and/or insert small gaps between the lines. Here's a screenshot of the code from TIO in all its beauty: [![enter image description here](https://i.stack.imgur.com/25gz6.png)](https://i.stack.imgur.com/25gz6.png) I think it might be possible to golf this some more, e.g. by changing the condition from `>0` to `<1` and swapping the branches of the conditional, so that I could reuse the number literal, or maybe by using a completely different formula, but I'm quite happy with how compact it is already. ### Explanation This basically implements the recursion given in the challenge, although it uses the base case **!(-1) = !0 = 1**. **n-1** and **n-2** are computed with the predecessor function `♭`, and the intermediate result **n-1** is reused in three places. There isn't much more to it, so I'll just quickly go through the control flow: ``` ─┐ ╓┴╖ ║f║ ╙─╜ ``` This is the function header which emits the function's input **n** long the attached line. This immediately reaches T-junction, which simply duplicates the value. ``` ┌┐┌┘╔═╗ └┴┼─╢0║ │ ╚═╝ ``` The `0` box is just a numeric literal. A 4-way junction computes two functions: the path that leads off the bottom computes **0 < n**, which we'll use to determine the base case. The path that goes left separately computes **0 << n** (a left-shift), but we discard this value with the [Starkov construct](http://esolangs.org/wiki/Funciton#The_Starkov_construct). ``` ┌┴╖ ╔═╗ ┤?╟┐║1║ ╘╤╝┘╚╤╝ └───┘ ``` We lead this into the three-way conditional `?`. If the value is false, we return the constant result `1`. The loose end right of the `?` is the function output. I'm twisting it around by 180 degrees here, so that the relative orientation of input and output of `f` is more convenient in the rest of the program. If the condition was true, then the other value will be used. Let's look at the path that leads to this branch. (Note that Funciton's evaluation is actually lazy so that this branch will never be evaluated if it's not needed, which makes the recursion possible in the first place.) ``` ┌─╖ ┐┌┤♭╟┐ ├┘╘═╝ │ ─┴┐ ``` In the other branch we first compute **n-1** and then split the path twice so we get three copies of the value (one for the coefficient of the recurrence, one for the first subfactorial, the last for **n-2**). ``` ┌─╖┌─╖ │f╟┤♭╟ ╘╤╝╘═╝ │┌─╖ ││f╟ │╘╤╝ │┌┴╖ ││+╟ │╘╤╝ └─┘ ``` Like I said, we decrement one copy again with another `♭`, then we feed both **n-1** and **n-2** recursively to `f` and finally add the two results together in the `+`. ``` ┐ │ ┌┴╖ ┐│×╟ │╘╤╝ └─┘ ``` All that's left is to multiply **n-1** by **!(n-1) + !(n-2)**. [Answer] # [Oasis](https://github.com/Adriandmen/Oasis), 5 bytes Uses the formula given by Martin. Code: ``` +n<*X ``` Dissected version: ``` +n<* ``` with `a(0) = 1` and `a(1) = 0`. Explanation, `a(n) =`: ``` + # Add the previous two terms, a(n - 1) + a(n - 2). n< # Compute n - 1. * # Multiply the top two elements. ``` [Try it online!](https://tio.run/nexus/oasis#@6@dZ6MV8f//f0MDAA "Oasis – TIO Nexus") [Answer] # [Haskell](https://www.haskell.org/), 25 bytes ``` f 0=1 f n=n*f(n-1)+(-1)^n ``` [Try it online!](https://tio.run/nexus/haskell#@5@mYGBryJWmkGebp5WmkadrqKmtASTi8v7nJmbmKdgqFKUmpvjkKdjZ2SoUFGXmlSjoKaT9NzQAAA "Haskell – TIO Nexus") Uses the other recurrence from the [OEIS](https://oeis.org/A000166) page. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` R=Œ!Ḅċ0 ``` This approach constructs the derangements, so it's rather slow. [Try it online!](https://tio.run/nexus/jelly#ARsA5P//Uj3FkiHhuITEizD/MHI4wrXFvMOH4oKsR/8 "Jelly – TIO Nexus") ### How it works ``` R=Œ!Ḅċ0 Main link. Argument: n R Range; yield [1, ..., n]. Œ! Yield all permutations of [1, ..., n]. = Perform elementwise comparison of [1, ..., n] and each permutation. Ḅ Unbinary; convert each result from base 2 to integer. This yields 0 for derangements, a positive value otherwise. ċ0 Count the number of zeroes. ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (2), 11 bytes ``` ⟦₁{p:?\≠ᵐ}ᶜ ``` [Try it online!](https://tio.run/nexus/brachylog2#ARsA5P//4p@m4oKBe3A6P1ziiaDhtZB94bac//82/1o "Brachylog – TIO Nexus") ## Explanation This is basically just a direct translation of the spec from English to Brachylog (and thus has the advantage that it could easily be modified to handle small changes to the specification, such as finding the number of derangements of a specific list). ``` ⟦₁{p:?\≠ᵐ}ᶜ ⟦₁ Start with a list of {the input} distinct elements { }ᶜ Then count the number of ways to p permute that list \ such that taking corresponding elements :? in {the permutation} and the list of distinct elements ≠ gives different elements ᵐ at every position ``` [Answer] # Languages with built-in solutions Following [xnor's suggestion](https://codegolf.meta.stackexchange.com/a/11218/8478) this is a CW answer into which trivial solutions based on a single built-in to compute the subfactorial or generate all derangements should be edited. ## Mathematica, 12 bytes ``` Subfactorial ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~35~~ 32 bytes ``` f=lambda n:n<1or(-1)**n+n*f(n-1) ``` This uses the recurrence relation **!n = n !(n-1) + (-1)n** from [@Laikoni's Haskell answer](https://codegolf.stackexchange.com/a/113942/12012), with base case **!0 = 1**. [Try it online!](https://tio.run/nexus/python3#FczBCsIwEIThs32KuYTu1gSaVRCK@iKlh5QYKditBM@@el0PH8Nc/r3cXmmdc4IOeo1b/QbtqJCGyMf/CPNetgrFohi7mvT5oAt7xN6IOZmzh9iXOA3N4V0X/VDrJCPc4aTPLRxIPSzI1vsB "Python 3 – TIO Nexus") [Answer] # [M](https://github.com/DennisMitchell/m), 9 bytes ``` o2!÷Øe+.Ḟ ``` As you can see by removing the `Ḟ`, **M** uses symbolic math, so there will be no precision issues. [Try it online!](https://tio.run/nexus/m#@59vpHh4@@EZqdp6D3fM@390z@H2R01rsoD4UeO2rEeN2///N9BRMNRRMNJRMNZRMNFRMNVRMAOKgESBYoZAQUOgqBGQb2QIEjcAAA "M – TIO Nexus") Not the shortest solution that has been posted, but *fast*. ### How it works ``` o2!÷Øe+.Ḟ Main link. Argument: n o2 Replace input 0 with 2, as the following formula fails for 0. ! Compute the factorial of n or 2. ÷Øe Divide the result by e, Euler's natural number. +. Add 1/2 to the result. Ḟ Floor; round down to the nearest integer. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~9~~ 8 bytes ``` :tY@-!As ``` Similarly to [@Dennis' Jelly answer](https://codegolf.stackexchange.com/a/113937/36398), this actually builds the permutations and counts how many of them are derangements; so it is slow. [Try it online!](https://tio.run/nexus/matl#@29VEumgq@hY/P@/oQEA "MATL – TIO Nexus") ``` : % Input n implicitly: Push [1 2 ... n] t % Duplicate Y@ % Matrix of all permutations, each on a row - % Element-wise subtract. A zero in a row means that row is not a derangement ! % Transpose A % True for columns that don't contain zeros s % Sum. Implicitly display ``` [Answer] # [Mathics](http://mathics.github.io/), 21 bytes ``` Round@If[#>0,#!/E,1]& ``` I am *very* new to this and have no idea what I'm doing... [Try it online!](https://tio.run/nexus/mathics#S1Ow/R@UX5qX4uCZFq1sZ6CjrKjvqmMYq/Y/oCgzr8ShOs3BQCfNwRCIjYDYGMQ2qP0PAA "Mathics – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` ΃N*®Nm+ ``` [Try it online!](https://tio.run/nexus/05ab1e#@3@479gkP61D6/xytf//NzQwAAA "05AB1E – TIO Nexus") **Explanation** ``` Î # initialize stack with 0 and input ƒ # for N in range [0 ... input]: N* # multiply top of stack with N ®Nm # push (-1)^N + # add ``` [Answer] # Ruby, 27 bytes ``` f=->n{n<1?1:n*f[n-1]+~0**n} ``` `~0**n` is shorter than `(-1)**n`! [Answer] ## CJam (10 bytes) ``` 1qi{~*)}/z ``` [Online demo](http://cjam.aditsu.net/#code=1qi%7B~*)%7D%2Fz&input=5). This uses the recurrence `!n = n !(n-1) + (-1)^n`, which I derived from `n! / e` and then discovered was already in OEIS. ### Dissection The loop calculates `(-1)^n !n`, so we need to take the absolute value at the end: ``` 1 e# Push !0 to the stack qi{ e# Read an integer n and loop from 0 to n-1 ~ e# Bitwise not takes i to -(i+1), so we can effectively loop from 1 to n * e# Multiply ) e# Increment }/ z e# Take the absolute value ``` [Answer] # [Quipu](https://github.com/cgccuser/quipu), 73 bytes ``` \/1&1&2&1& 1&++++^^[] ++2&0&--1& 2&[][]1&++ ??**%%??/\ 3&4& []== -- ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m720sDSzoHTBgqWlJWm6Fjc9Y_QN1QzVjICYy1BNGwji4qJjubS1jdQM1HR1gaJGatGx0bEgOS57ey0tVVV7e_0YLgUFYzUTNSAVHWtrC6R0dSEGQs1dsMjQAMICAA) Based on [Aaroneous Miller's factorial answer](https://codegolf.stackexchange.com/a/234986/9288). Equivalent pseudocode: ``` a = [0, 0, 0, 0, 0] // implicitly 0: a[0] = input + 1 goto 2 1: a[1] = (a[1] + 1) * a[2] - a[3] 2: a[2] = (a[2] + 1) % a[0] if a[2] == 0 goto 4 3: a[3] = 2 - a[3] goto 1 4: a[4] = a[1] + 1 print a[4] ``` [Answer] # MATLAB, 33 bytes ``` @(n)(-1)^n*hypergeom([1 -n],[],1) ``` Anonympus function that uses the formula in Section 3 of [*Derangements and applications*](https://eudml.org/doc/51444) by Mehdi Hassani. Example use: ``` >> @(n)(-1)^n*hypergeom([1 -n],[],1) ans = @(n)(-1)^n*hypergeom([1,-n],[],1) >> ans(6) ans = 265 ``` [Answer] ## JavaScript (ES6), 26 bytes ``` f=n=>!n||n*f(n-1)-(~n%2|1) ``` Uses the recurrence relation from @Laikoni's answer. In ES7 you can save a byte by using `+(-1)**n` instead of `-(~n%2|1)`. [Answer] ### PostScript, ~~81~~ ~~76~~ 69 bytes Here are implementations of both formulae. n\*f(n-1)+(-1)^n ~~/f{dup 0 eq{pop 1}{dup dup 1 sub f mul exch 2 mod 2 mul 1 sub sub}ifelse}def~~ ``` /f{dup 0 eq{pop 1}{dup dup 1 sub f mul -1 3 2 roll exp add}ifelse}def ``` That version outputs a float. If it's necessary to output an integer: ``` /f{dup 0 eq{pop 1}{dup dup 1 sub f mul -1 3 2 roll exp cvi add}ifelse}def ``` which weighs in at 73 bytes. The other formula is a little longer: 81 bytes. (n-1)\*(f(n-1)+f(n-2)) ``` /f{dup 1 le{1 exch sub}{1 sub dup f exch dup 1 sub f 3 -1 roll add mul}ifelse}def ``` These functions get their argument from the stack, and leave the result on the stack. You can test the functions, either in a file or at an interactive PostScript prompt (eg GhostScript) with ``` 0 1 12{/i exch def [i i f] ==}for ``` **output** ``` [0 1] [1 0.0] [2 1.0] [3 2.0] [4 9.0] [5 44.0] [6 265.0] [7 1854.0] [8 14833.0] [9 133496.0] [10 1334961.0] [11 14684570.0] [12 176214848.0] ``` Here's a complete PostScript file which renders the output to the screen or a printer page. (Comments in PostScript start with `%`). ``` %!PS-Adobe-3.0 % (n-1)*(f(n-1)+f(n-2)) % /f{dup 1 le{1 exch sub}{1 sub dup f exch dup 1 sub f 3 -1 roll add mul}ifelse}def % n*f(n-1)+(-1)^n /f{dup 0 eq{pop 1}{dup dup 1 sub f mul -1 3 2 roll exp add}ifelse}def % 0 1 12{/i exch def [i i f] ==}for /FS 16 def %font size /LM 5 def %left margin /numst 12 string def %numeric string buffer /Newline{currentpoint exch pop FS sub LM exch moveto}def /Courier findfont FS scalefont setfont LM 700 moveto (Subfactorials) Newline 0 1 12{ dup numst cvs show (: ) show f numst cvs show Newline }for showpage quit ``` [Answer] # [Raku](http://raku.org/), 22 bytes ``` 1,{++$*$_+($*=-1)}...* ``` [Try it online!](https://tio.run/##K0gtyjH7r1ecWKmQll@koPHfUKdaW1tFSyVeW0NFy1bXULNWT09P679mdJyRYaxVwX8A "Perl 6 – Try It Online") This is an expression for the infinite sequence of subfactorials. [Answer] # [Python 3](https://docs.python.org/3/), 27 bytes ``` f=lambda n:n<1or f(n-1)*n^1 ``` [Try it online!](https://tio.run/##XYw9DoAgGEN3T8HI508isqlcxQQjoIlWgyyeHkU3p5f0tT2uMO@QMVq16m2cNEOLXuyeWY5KUI5BRPdzn@HuZZHQEGX2GYEtYF7DGS5ravV5Gh/SFSn19Kg7/ILAUaaI4g0 "Python 3 – Try It Online") Based on [@Laikoni's formula](https://codegolf.stackexchange.com/a/113942/107561) and the observation that *n* and !*n* always have opposite parity. Broken down: n odd -> n x !(n-1) also odd -> adding (-1)^n=-1 is the same as unsetting the lowest bit n even -> n x !(n-1) also even -> adding (-1)^n=1 is the same as setting the lowest bit therefore flipping the lowest bit works in either case [Answer] # PHP, 69 Bytes ``` function f($i){return$i>1?$i*f($i-1)+(-1)**$i:1-$i;}echo f($argv[1]); ``` use this way `a(n) = n*a(n-1) + (-1)^n` [Answer] # PHP, 50 44 ``` for(;$i++<$argn;)$n=++$n*$i-$i%2*2;echo$n+1; ``` Run with `echo <n> | php -nR '<code>` The beauty of `a(n) = n*a(n-1) + (-1)^n` is that it depends only on the previous value. This allows it to be implemented iteratively instead of recursively. This saves a long *function* declarition. *-6 bytes* by @Titus. Thanks ! [Answer] # [Alice](https://github.com/m-ender/alice), ~~20~~ 18 bytes ``` 1/o k\i@/&wq*eqE+] ``` [Try it online!](https://tio.run/##S8zJTE79/99QP58rOybTQV@tvFArtdBVOxYoZmAAAA "Alice – Try It Online") ### Explanation This uses the recursion from [Laikoni's answer](https://codegolf.stackexchange.com/a/113942/8478), **!n = n !(n-1) + (-1)n**. Similar to the Funciton answer, I'm using the base case **!(-1) = 1**. We put that **1** on the stack with `1.`. Then this... ``` .../o ...\i@/... ``` ... is just the usual decimal I/O framework. The main code is actually ``` &wq*eqE+]k ``` Broken down: ``` &w Push the current IP address N times to the return address stack, which effectively begins a loop which will be executed N+1 times. q Push the position of the tape head, which we're abusing as the iterator variable n. * Multiply !(n-1) by n. e Push -1. q Retrieve n again. E Raise -1 to the nth power. + Add it to n*!(n-1). ] Move the tape head to the right. k Jump back to the w, as long as there is still a copy of the return address on the return address stack. Otherwise, do nothing and exit the loop. ``` [Answer] # [Julia 1.0](http://julialang.org/), 21 bytes ``` !n=n<1||n*!~-n+(-1)^n ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/XzHPNs/GsKYmT0uxTjdPW0PXUDMu739afpFCpkJmnkJSZrqGgaaVoYEBlwIQFBRl5pXk5GkoKapkKtgqKOkoKGZqcqXmpfwHAA "Julia 1.0 – Try It Online") with the following formula from the [OEIS page](https://oeis.org/A000166): $$ a(0)=1,\ a(n) = n\*a(n-1) + (-1)^n $$ [Answer] # TI-Basic, ~~12~~ 19 bytes ``` Ans!∑((-1)^K/K!,K,0,Ans ``` with the following formula from the [OEIS page](https://oeis.org/A000166): $$ a(n) = n!\*\sum\_{k=0..n}(-1)^k/k! $$ ![screenshot of demo on calculator](https://i.stack.imgur.com/xIvxgm.jpg) ### previous answer (12 bytes) ``` round(Ans!/𝓮,0)+not(Ans ``` this is invalid because `𝓮` (euler number) is stored with limited precision, which is explicitly forbiden by the challenge [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 0Lλè+N<* ``` I know there is already [a great 8 bytes 05AB1E answer](https://codegolf.stackexchange.com/a/113955/52210), but this uses a completely different approach. [Try it online](https://tio.run/##yy9OTMpM/f/fwOfc7sMrtP1stP7/NwMA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/A59zuw@v0Paz0fpfq/M/2kDHUMdIx1jHRMdUx0zHEMg10jE01jE00TEy0DEyBIoYxAIA). **Explanation:** ``` λ # Start a recursive environment, è # to output the (implicit) input'th value 0L # Starting with a(0)=1 and a(1)=0 # Where every following a(n) is calculated as: + # Add two values together # (since + requires 2 arguments, it implicitly uses a(n-2) and a(n-1)) N<* # Multiplied by n-1 # (after which the result of a(input) is output implicitly) ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 26 bytes ``` n->n!*sum(k=0,n,(-1)^k/k!) ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P0/XLk9Rq7g0VyPb1kAnT0dD11AzLls/W1Hzf1p@kUaegq2CgY6CERAXFGXmlQAFlBR07YBEmkaepqbmfwA "Pari/GP – Try It Online") --- # [Pari/GP](http://pari.math.u-bordeaux.fr/), 28 bytes ``` f(n)=if(n,n*f(n-1)+(-1)^n,1) ``` [Try it online!](https://tio.run/##K0gsytRNL/j/P00jT9M2E0jq5GkBSV1DTW0NIBGXp2Oo@T8tv0gjT8FWwUBHwQiIC4oy80qAAkoKunZAAqRVU/M/AA "Pari/GP – Try It Online") --- # [Pari/GP](http://pari.math.u-bordeaux.fr/), 15 bytes (invalid because of finite precision) ``` n->n!\/exp(!!n) ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P0/XLk8xRj@1okBDUTFP839afpFGnoKtgoGOghEQFxRl5pUABZQUdO2ARJpGnqam5n8A "Pari/GP – Try It Online") [Answer] ## Mathematica, 40 bytes ``` ±0=1;±1=0;±n_:=(n-1)(±(n-1)+±(n-2)) ``` Which comes in at 31 bytes under the default ISO 8859-1 encoding. [Answer] # C, 34 bytes ``` a(n){return n?n*a(n-1)-n%2*2+1:1;} ``` Explanation: ``` a(n){ } define a function called a of n return ; make the function evaluate to... n? :1 set the base case of 1 when n is 0 n*a(n-1) first half of the formula on the page -n%2*2+1 (-1)**n ``` [Answer] # R, 47 bytes ``` n=scan();`if`(!n,1,floor(gamma(n+1)/exp(1)+.5)) ``` Uses the same formula as [Mego's answer](https://codegolf.stackexchange.com/a/113975/67312). Alternate method, 52 bytes using the `PerMallows` library ``` n=scan();`if`(!n,1,PerMallows::count.perms(n,n,'h')) ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 18 bytes ``` ;!@ur⌠;!@0Dⁿ/⌡MΣ*≈ ``` [Try it online!](https://tio.run/nexus/actually#@2@t6FBa9KhnAZA2cHnUuF//Uc9C33OLtR51dvz/b2gAAA) Explanation: ``` ;!@ur⌠;!@0Dⁿ/⌡MΣ*≈ ; duplicate input ! n! @ur range(0, n+1) (yields [0, n]) ⌠;!@0Dⁿ/⌡M for each i in range: ; duplicate i ! i! @0Dⁿ (-1)**i / (-1)**i/i! Σ sum * multiply sum by n! ≈ floor into int ``` --- A 12-byte version that would work if Actually had more precision: ``` ;!╠@/1½+L@Y+ ``` [Try it online!](https://tio.run/nexus/actually#@2@t@GjqAgd9w0N7tX0cIrX//zc0AgA "Actually – TIO Nexus") Unlike all of the other answers (as of posting), this solution uses neither the recursive formula nor the summation formula. Instead, it uses the following formula: [![derangement formula](https://i.stack.imgur.com/3VmLu.png)](https://i.stack.imgur.com/3VmLu.png) This formula is relatively easy to implement in Actually: ``` !╠@/1½+L ! n! ╠ e @/ divide n! by e 1½+ add 0.5 L floor ``` Now, the only problem is that the formula only holds for positive `n`. If you try to use `n = 0`, the formula incorrectly yields `0`. This is easily fixed, however: by applying boolean negation to the input and adding that to the output of the formula, the correct output is given for all non-negative `n`. Thus, the program with that correction is: ``` ;!╠@/1½+L@Y+ ; duplicate input ! n! ╠ e @/ divide n! by e 1½+ add 0.5 L floor @Y boolean negate the other copy of the input (1 if n == 0 else 0) + add ``` ]
[Question] [ The natural numbers including 0 are formally defined as sets, in the [following way](https://en.wikipedia.org/wiki/Set-theoretic_definition_of_natural_numbers#Contemporary_standard): * Number 0 is defined as the empty set, {} * For *n* ≥ 0, number *n*+1 is defined as *n* ∪ {*n*}. As a consequence, *n* = {0, 1, ..., *n*-1}. The first numbers, defined by this procedure, are: * 0 = {} * 1 = {{}} * 2 = {{}, {{}}} * 3 = {{}, {{}}, {{}, {{}}}} # Challenge Given `n`, output its representation as a set. # Rules The output can consistently use any **bracket** character such as `{}`, `[]`, `()` or `<>`. Arbitrary characters (such as `01`) are not allowed. Instead of a comma as above, the **separator** can be any punctuation sign; or it may be inexistent. **Spaces** (not newlines) may be included arbitrarily and inconsistently. For example, number 2 with square brackets and semicolon as separator is `[[]; [[]]]`, or equivalently `[ [ ]; [ [ ] ] ]`, or even `[ [ ] ;[ []]]` The **order** in which elements of a set are specified doesn't matter. So you can use any order in the representation. For example, these are some valid outputs for `3`: ``` {{},{{}},{{},{{}}}} {{{}},{{},{{}}},{}} {{{}},{{{}},{}},{}} ``` You can write a **program or function**. Output may be a string or, if using a function, you may return a nested list or array whose string representation conforms to the above. # Test cases ``` 0 -> {} 1 -> {{}} 2 -> {{},{{}}} 3 -> {{},{{}},{{},{{}}}} 4 -> {{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}} 5 -> {{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}}} 6 -> {{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}}}} 7 -> {{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}}}}} ``` [Answer] # Python 2, 26 bytes ``` f=lambda n:map(f,range(n)) ``` Test it on [Ideone](http://ideone.com/8Gde07). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḷ߀ ``` This is a monadic link. [Try it online!](http://jelly.tryitonline.net/#code=4bi2w5_igqwKMHI3w4figqzFkuG5mOKCrFk&input=) ### How it works Each natural number is the set of all previous natural numbers, i.e., **n = {0, …, n-1}**. Since there are no natural numbers preceding **0**, we have that **0 = {}**. ``` Ḷ߀ Monadic link. Argument: n (natural number) Ḷ Unlength; yield [0, ..., n-1]. ߀ Recursively map this link over the range. ``` [Answer] # JavaScript (ES6), 32 bytes ``` f=n=>[...Array(n).keys()].map(f) ``` Simple enough. [Answer] # [Perl 6](https://perl6.org), 16 bytes ``` {({@_}…*)[$_]} ``` Returns nested data structure. ## Example: ``` say {({@_}…*)[$_]}( 4 ); # [[] [[]] [[] [[]]] [[] [[]] [[] [[]]]]] ``` ## Explanation: ``` { # lambda with implicit parameter 「$_」 ( # produce a lazy infinite sequence of all results { # lambda with implicit parameter 「@_」 @_ # array containing all previously seen values in the sequence } … # keep repeating that block until: * # Whatever ( never stop ) )[ $_ ] # use the outer block's argument to index into the sequence } ``` [Answer] # Haskell, ~~32~~ 27 bytes ``` p n='{':(p=<<[0..n-1])++"}" ``` [Try it on Ideone.](https://ideone.com/2gcgQD) [Answer] # Ruby, ~~27~~ 21 bytes I'm new to ruby golfing, but here goes nothing. *Thanks to Jordan for saving 6 bytes!* ``` f=->s{(0...s).map &f} ``` This is a recursive function `f` (a proc, to be specific) and takes an argument `s`. It maps the proc `f` over `0...s`, which is the range `[0, s)`. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes ``` )IF)©`® ``` **Explanation** ``` ) # wrap stack in a list, as stack is empty this becomes the empty list [] IF # input number of times do: ) # wrap stack in list © # store a copy of the list in the register ` # flatten the list ® # push the copy from the register # implicitly print top value of stack after the last loop iteration ``` [Try it online!](http://05ab1e.tryitonline.net/#code=KUlGKcKpYMKufQ&input=Mw) Saved 1 byte thanks to Adnan. [Answer] # [CJam](http://sourceforge.net/projects/cjam/), 14 bytes ``` "[]"{_)@\]}ri* ``` [Try it online!](http://cjam.tryitonline.net/#code=IltdIntfKUBcXX1yaSo&input=Mw) ### Explanation ``` "[]" e# Push this string. It is the representation of 0, and also serves e# to initialize { }ri* e# Repeat this block as many times as the input number _ e# Duplicate ) e# Uncons: split into array without the last element, and last element @\ e# Rotate, swap ] e# Pack stack contents into an array e# Implicitly display ``` In each iteration, the block builds the representation of a number from that of the preceding one. To illustrate, let's consider the second iteration, where the representation of number `2` is built from that of `1`, which is the string `"[[]]"`. 1. The stack contains `"[[]]"` 2. After statement `_` (duplicate) it contains `"[[]]"`, `"[[]]"` 3. After statement `)` (uncons) it contains `"[[]]"`, `"[[]"`, `"]"` 4. After statement `@` (rotate) it contains `"[[]"`, `"]"`, `"[[]]"` 5. After statement `\` (swap) it contains `"[[]"`, `"[[]]"`, `"]"` 6. After statement `]` (pack into array) it contains `["[[]" "[[]]" "]"]`, which would be displayed as the string `"[[][[]]]"`. [Answer] # Cheddar, 17 bytes ``` n f->(|>n).map(f) ``` Short recursion + Short range + Short iteration = A challenge where cheddar does very well # Non-competing, 11 bytes ``` n f->|>n=>f ``` The `=>` operator was added after this challenge was released making this answer non-competing. This may look confusing but let me simplify it: ``` n f -> |> n => f ``` basically `n` is the input and `f` is the function itself. `|>n` generates [0, n) and `=>` maps that over `f`. [Answer] # Mathematica, 14 bytes ``` Array[#0,#,0]& ``` [Answer] # Pyth, 4 bytes ``` LyMb ``` [Test suite](https://pyth.herokuapp.com/?code=LyMby&test_suite=1&test_suite_input=0%0A1%0A2%0A3&debug=0) `L`: Define the function `y` with input `b` `yMb`: `y` mapped over the range `0, 1, ..., b-1` On the input 0, this map returns `[]`. Otherwise, it returns `y` mapped over all numbers up to `b`. [Answer] # [MATL](http://github.com/lmendo/MATL), 13 bytes ``` Xhi:"tY:Xh]&D ``` [Try it online!](http://matl.tryitonline.net/#code=WGhpOiJ0WTpYaF0mRA&input=Mw) ### Explanation ``` Xh % Concatenate the stack contents into cell array. Since the stack % is empty, this produces the empty cell array, {} i:" ] % Take input number. Repeat that many times t % Duplicate the cell array that is at the top of the stack Y: % Unbox it, i.e., push its contents onto the stack Xh % Concatenate the stack contents into a cell array &D % String representation. Implicitly display ``` [Answer] # Perl, 27 bytes Includes +1 for `-p` Many different methods all seem to end up as either 27 or 28 bytes. e.g. ``` #!/usr/bin/perl -p $\=$_="{@F}"for@F[0..$_]}{ ``` The best I could find is ``` #!/usr/bin/perl -p s/./{$_/ for($\="{}")x$_}{ ``` since on older perls you can drop the space before the `for` and get 26 bytes [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` `:'}:'{ṁ₀ŀ ``` [Try it online!](https://tio.run/##yygtzv7/P8FKvdZKvfrhzsZHTQ1HG/7//28CAA "Husk – Try It Online") ``` `:'}:'{ṁ₀ŀ ŀ Range [0, n) ṁ₀ For all numbers in that range, run this function on them ṁ Then concatenate those representations together :'{ Prepend '{' `:'} Append '}' ``` [Answer] # Mathematica, 31 bytes Straightforwardly implements the definition as a nested list. Uses an unnamed function that recursively calls itself using `#0`. ``` If[#<1,{},Join[t=#0[#-1],{t}]]& ``` [Answer] ## [Retina](http://github.com/mbuettner/retina), ~~24~~ 18 bytes ``` .+ $*1<> +`1< <<$' ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYAouKwokKjE8PgorYDE8Cjw8JCc&input=MAoxCjIKMwo0CjU) (The first line enables a linefeed-separated test suite.) ### Explanation ``` .+ $*1<> ``` This converts the input to unary and appends `<>`, the representation of `0`. ``` +`1< <<$' ``` Here, the `+` indicates that this substitution should be run in a loop until the string stops changing. It's easier to explain this by going through the individual steps I took golfing it down. Let's with this version of the substitution: ``` 1<(.*)> <<$1>$1> ``` This matches the last `1` of the unary representation of the remaining input (to remove it and decrement the input), as well as the contents of the current set at the end. This is then replaced with a new set containing the previous one as well as its contents. However, we can notice that `$1` is followed by `>` in both cases and hence we can include it in the capture itself and omit it from the substitution pattern. That leads to the form ``` 1<(.*) <<$1$1 ``` However, now we can observe that `(.*)` just captures the suffix of the string after `1<` and we even reinsert this suffix at the end with `$1`. Since the substitution syntax gives us a way to refer to the part of a string *after* a match with `$'` we can simply omit both of those parts and end up with the version used in the answer: ``` 1< <<$' ``` [Answer] # [Underload](https://github.com/catseye/stringie), 14 bytes ``` ((:a*)~^()~^a) ``` [Try it online!](https://tio.run/##K81LSS3KyU9M@a9hpWWlpflfQ8MqUUuzLk4DiBM1/8cF/wcA "Underload – Try It Online") Underload full programs can't take input via any of our defined methods, so this is a function that takes input from the stack as a Church numeral (the normal way to define integers in Underload), and produces output to the stack as a string. The `(…)` grouping markers are required to make this a function (reusable) rather than a snippet (only usable once). The wrapper in the TIO link calls the function in question destructively using `^`, but it could be reused via making a copy of it and only consuming one of the copies when calling it. It also provides input to the program (here, `(:*:*)`, i.e. 4), and prints the output using `S`. ## Explanation Underload's surprisingly suited for this task as Turing tarpits go, having such useful primitives as "copy" and "surround with parentheses". (Somehow, Underload, normally a very verbose language, is beating Mathematica, normally a language which wins due to having a huge set of builtins, via having more appropriate builtins!) Here's how the program works: ``` ((:a*)~^()~^a) ( ) Make a snippet into a function ( )~^ Exponentiate the following function by the top of stack: : Copy the top stack element a Surround the copy in parentheses * Append the copy to the original, popping the copy ~^ Run the resulting function, with the following argument on its stack: () Empty string a Surround the result in parentheses ``` Function exponentiation effectively causes the steps of the function to repeat that many times, so, e.g., `(:a*)`³ would be `(:a*:a*:a*)`. That's the idiomatic way to write a loop that repeats a given number of times in Underload. (You can note that the `~^` is described two different ways above; that's because integers in Underload are defined *as* function exponentiation specialised to that integer, so in order to do a function exponentiation, you simply try to execute an integer as though it were a function.) [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 23 bytes ``` f(n)=[f(i)|i<-[0..n-1]] ``` [Try it online!](https://tio.run/##K0gsytRNL/j/P00jT9M2Ok0jU7Mm00Y32kBPL0/XMDb2f1p@kUaegq2CgY6CqY5CQVFmXgmQr6SgawckQJo0Nf8DAA "Pari/GP – Try It Online") [Answer] # APL(NARS), 15 chars, 30 bytes ``` {⍵=0:⍬⋄∇¨¯1+⍳⍵} ``` test: ``` f←{⍵=0:⍬⋄∇¨¯1+⍳⍵} o←⎕fmt o f 0 ┌0─┐ │ 0│ └~─┘ o f 1 ┌1───┐ │┌0─┐│ ││ 0││ │└~─┘2 └∊───┘ o f 2 ┌2──────────┐ │┌0─┐ ┌1───┐│ ││ 0│ │┌0─┐││ │└~─┘ ││ 0│││ │ │└~─┘2│ │ └∊───┘3 └∊──────────┘ o f 3 ┌3────────────────────────┐ │┌0─┐ ┌1───┐ ┌2──────────┐│ ││ 0│ │┌0─┐│ │┌0─┐ ┌1───┐││ │└~─┘ ││ 0││ ││ 0│ │┌0─┐│││ │ │└~─┘2 │└~─┘ ││ 0││││ │ └∊───┘ │ │└~─┘2││ │ │ └∊───┘3│ │ └∊──────────┘4 └∊────────────────────────┘ o f 4 ┌4────────────────────────────────────────────────────┐ │┌0─┐ ┌1───┐ ┌2──────────┐ ┌3────────────────────────┐│ ││ 0│ │┌0─┐│ │┌0─┐ ┌1───┐│ │┌0─┐ ┌1───┐ ┌2──────────┐││ │└~─┘ ││ 0││ ││ 0│ │┌0─┐││ ││ 0│ │┌0─┐│ │┌0─┐ ┌1───┐│││ │ │└~─┘2 │└~─┘ ││ 0│││ │└~─┘ ││ 0││ ││ 0│ │┌0─┐││││ │ └∊───┘ │ │└~─┘2│ │ │└~─┘2 │└~─┘ ││ 0│││││ │ │ └∊───┘3 │ └∊───┘ │ │└~─┘2│││ │ └∊──────────┘ │ │ └∊───┘3││ │ │ └∊──────────┘4│ │ └∊────────────────────────┘5 └∊────────────────────────────────────────────────────┘ ``` I don't know if this would be accepted... Zilde is ⍬ here it represent the void set {} if I want print the Zilde element or one element full of Zilde, and Zilde enclosed all what happen is print nothing... so for see Zilde one has to define one function I call it o (`o←⎕fmt`) I do not insert in the count because the element and its structure exist even if the sys not print it...It is possible if io is 0 ``` {⍵=0:⍬⋄∇¨⍳⍵} ``` could be 12 characters solution too... [Answer] # [Pip](https://github.com/dloscutoff/pip) `-p`, 4 bytes ``` fM,a ``` [Try it online!](https://tio.run/##K8gs@P8/zVcn8f///7oF/40B "Pip – Try It Online") The basic recursive approach works well in Pip: ``` f The main function, i.e. the whole program treated as a function M mapped to ,a range(argument) ``` The result is a nested list, which is printed using square brackets thanks to the `-p` flag. [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), ~~17~~ 15 bytes ``` (),{|$_,$_}...* ``` [Try it online!](https://tio.run/##K0gtyjH7/z@3UsEh0VZDU6e6RiVeRyW@Vk9PT8v6f3EiSDw6PbUk9r8pAA "Perl 6 – Try It Online") An anonymous lazy list. You can assign it to a variable like: `my @list = (),{|$_,$_}...* ;` and access it with `@list[n]`. [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 14 bytes ``` yk:{,[]:?:gi}a ``` [Try it online!](http://brachylog.tryitonline.net/#code=eWs6eyxbXTo_OmdpfWE&input=Mw&args=Wg) ### Explanation ``` yk The range [0, ..., Input - 1] :{ }a Apply on each element of the range ,[]:?:gi Group the empty list [] in a list Input times ``` [Answer] ## [GAP](http://gap-system.org), 22 bytes ``` f:=n->Set([0..n-1],f); ``` For example: ``` gap> f(3); [ [ ], [ [ ] ], [ [ ], [ [ ] ] ] ] ``` [Answer] ## Racket 119 bytes ``` (λ(n)(define ll(list'()))(for((i(range 1 n)))(set! ll(cons ll(for/list((j(length ll)))(list-ref ll j)))))(reverse ll)) ``` Ungolfed: ``` (define f (λ (n) (define ll (list '())) (for ((i (range 1 n))) (set! ll (cons ll (for/list ((j (length ll))) (list-ref ll j) )))) (reverse ll))) ``` Testing (In Racket {} is same as () and default output is ()): ``` (f 4) '(() (()) ((()) ()) (((()) ()) (()) ())) ``` To clearly see each number (0 to 3): ``` (for((i (f 4))) (println (reverse i))) '() '(()) '(() (())) '(() (()) ((()) ())) ``` [Answer] ## Batch, 74 bytes ``` @set s={} @for /l %%i in (1,1,%1)do @call set s={%%s%%%%s:~1%% @echo %s% ``` Uses the fact that each answer is equal to the previous answer inserted into itself after the leading `{`. The first few outputs are as follows: ``` {} {{}} {{{}}{}} {{{{}}{}}{{}}{}} {{{{{}}{}}{{}}{}}{{{}}{}}{{}}{}} {{{{{{}}{}}{{}}{}}{{{}}{}}{{}}{}}{{{{}}{}}{{}}{}}{{{}}{}}{{}}{}} ``` [Answer] # x86-64 machine code, 22 bytes ``` 31 C0 99 B0 7B AA FF C2 0F BC CA 39 F1 B0 7D F3 AA 75 F0 66 AB C3 ``` [Try it online!](https://tio.run/##TVFLb8IwDD7Hv8LrhJSOgqoxDYnHDmPXXXaaBBzaNIFMbdo1BVIh/vo6BxjaxZbzvWxFVNVgI0TXJbZAjh8Bh@EmL9MkRwVqwlxZo0xc5AswkX1DPWFFucckjzB241dgtiltCkwbgTIjUmoVSuElfhJFdZ2shv/KN2C1rPCq/jIS64vXwQMNhAGGU5CukbXBYBHgcV/qDBUX26R@QBuhNg2acHoCuKfwfJdJnNkm0@Vw@wLg0SLRhodwpDVIhLW0u7xZjuJ4PQWm6DR@9sA5xlNqszmOqff7ITDSMMUvisjH0FzVRFc86Gns2ZUJ6D26mnr8BDfGyrwnYqvpKFFmchJ42Ec5HxVhS2NW4vGPjr348ZPs2jnnO2P1xsgMz3eGKly6fn9NZ@Jhq3OJvMU7MnGLkTe9OXBaKm0bacPzYo7AU9f9CJUnG9sNiucnKvTJc@LL/Bc "C++ (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string, and takes the number `n` in RSI. In assembly: ``` f: xor eax, eax # cdq # Set EAX and EDX to 0. r: mov al, 0x7B # Put the ASCII code of '{' into AL. stosb # Add that to the string, advancing the pointer. inc edx # Add 1 to EDX. bsf ecx, edx # Set ECX to the lowest position of a 1 bit in EDX. cmp ecx, esi # Compare that number with n. mov al, 0x7D # Put the ASCII code of '}' in AL. rep stosb # Add that to the string ECX times, advancing the pointer. jne r # Repeat if the number is not equal to n. stosw # Add two bytes from AX to the string: one more '}' and a null byte. ret # Return. ``` ]
[Question] [ ### Introduction This is how a chessboard looks like. [![enter image description here](https://i.stack.imgur.com/YxP53.gif)](https://i.stack.imgur.com/YxP53.gif) You can see that `a1` is a **dark** square. However, `b1` is a **light square**. ### The Task The challenge is, given `dark`, `light` or `both`, output all the **dark**, **light** or **all squares** *with a separator* (like a whitespace or a newline). The order of all the squares *does not matter*. ### Test cases ``` Input: dark Output: a1 a3 a5 a7 b2 b4 b6 b8 c1 c3 c5 c7 d2 d4 d6 d8 e1 e3 e5 e7 f2 f4 f6 f8 g1 g3 g5 g7 h2 h4 h6 h8 Input: light Output: a2 a4 a6 a8 b1 b3 b5 b7 c2 c4 c6 c8 d1 d3 d5 d7 e2 e4 e6 e8 f1 f3 f5 f7 g2 g4 g6 g8 h1 h3 h5 h7 Input: both Output: a1 a2 a3 a4 a5 a6 a7 a8 b1 b2 b3 b4 b5 b6 b7 b8 c1 c2 c3 c4 c5 c6 c7 c8 d1 d2 d3 d4 d5 d6 d7 d8 e1 e2 e3 e4 e5 e6 e7 e8 f1 f2 f3 f4 f5 f6 f7 f8 g1 g2 g3 g4 g5 g6 g7 g8 h1 h2 h3 h4 h5 h6 h7 h8 ``` *Note:* I have prettified the output but this is **not necessary**. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! [Answer] ## Pyth, ~~22~~ 21 bytes *-1 byte by @Sp3000* ``` fn%Chz3%sCMT2sM*<G8S8 ``` Under the function `%Chz3`, `dark` hashes to 1, `light` to 0, and `both` to 2. If we take the parity of the sum of the ords of a chess square (that is, `a1` -> `[97, 33]` -> `(97 + 33)%2` = `0`, dark squares go to 0, and light to 1. This allows us to filter by inequality. ``` fn%Chz3%sCMT2sM*<G8S8 implicit: z=input * Cartesian product of <G8 first 8 letters in G (alphabet) S8 with [1,...,8] implicitly stringified sM*<G8S8 ['a1','a2,...,'a8','b1'...'h8'] f T Filter that by gives truthy result to lambda T: sCMT The sum of the ords of the chars in T, % 2 modulo 2 n does not equal Chz ord of the first char in z, % 3 modulo 3 Implicitly print the list. ``` Try it [here](https://pyth.herokuapp.com/?code=fn%25Chz3%25sCMT2sM%2a%3CG8S8&input=dark&test_suite=1&test_suite_input=dark%0Alight%0Aboth&debug=0). [Answer] # Bash + GNU Utilities, 74 ``` printf %s\\n {a..h}{1..9}|sed -n "`sed '/[db]/a1~2p /t/a2~2p c/9/d'<<<$1`" ``` `{a..h}{1..9}` is a bash brace expansion that produces all the coordinates for an 8x8 board, plus an extra column `9`. This is important because it makes the row length odd which allows the chequerboard effect. The `printf` simply formats each coordinate, one per line. The built sed expression then deletes all `x9` coordinates and then prints either even or odd or both input lines, according to the script input. [Answer] ## JavaScript (SpiderMonkey 30+), ~~90~~ ~~85~~ ~~83~~ 82 bytes ``` x=>[for(d of"12345678")for(c of"abcdefgh")if(x>'l'^parseInt(c+=d,19)%2|x<'d')c]+'' ``` Returns a comma-separated string of squares. Compatible version for 99 bytes: ``` x=>([..."12345678"].map(d=>[..."abcdefgh"].map(c=>c+d).filter(s=>x>'l'^parseInt(s,19)%2|x<'d')))+'' ``` Works by enumerating all 64 square names, then parsing them in base 19 to see whether they are light or dark modulo 2. [Answer] # JavaScript (ES6), 82 ~~87 98~~ Anonymous function returning a space separated string of squares. ``` i=>eval("for(o='',v=190;v<322;)v++%19<8&&i<'d'|v&1^i>'l'?o+=v.toString(19)+' ':o") ``` **TEST** ``` f=i=>eval("for(o='',v=190;v<322;)v++%19<8&&i<'d'|v&1^i>'l'?o+=v.toString(19)+' ':o") // less golfed q=i=>{ // loop over the range of number a0 (base 19) to h8 (base 19) for(o='',v=190;v<322;) { if (v++ %19 < 8) // increment and execute the line below only if second digit in 1..8 if (i<'d'|v&1^i>'l') // even == light, odd == dark, take both if input is 'both' o+=v.toString(19)+' ' } return o } document.write('<hr>Both<br>'+f('both')) document.write('<hr>Light<br>'+f('light')) document.write('<hr>Dark<br>'+f('dark')) ``` [Answer] ## Batch, 192 bytes ``` @set s=a1 a3 a5 a7 @set t=b2 b4 b6 b8 @if not %1==light call:b @set s=a2 a4 a6 a8 @set t=b1 b3 b5 b7 @if %1==dark exit/b :b @echo %s% %s:a=c% %s:a=e% %s:a=g% %t% %t:b=d% %t:b=f% %t:b=h% ``` [Answer] # Pyth, ~~48~~ 39 bytes ``` K*<G8S8Jfq%xGhT2%seT2K?qhz\bK?qhz\lJ-KJ ``` [Try it here!](http://pyth.herokuapp.com/?code=K*%3CG8S8Jfq%25xGhT2%25seT2K%3Fqhz%5CbK%3Fqhz%5ClJ-KJ&input=light&test_suite=1&test_suite_input=both%0Alight%0Adark&debug=0) Still longer than the other Pyth solution, but I don't think I can beat this with my algorithm. ## Explanation First we generate a list of all squares on the board and assign it to `Y`. Then we filter this list so that only light squares remain and assign this list to `J`. After that we evaluate the input and print: * `Y` if input was `both` * `J` if input was `light` * `Y-J` if the input was `dark` Determining if a square is light works as follows: * Map the char to a number from 1-8 (a->1, b->2), results in `18` for `a8`, etc. * check if both those numbers are odd or even (`x%2 == y%2`) * If they are, the square is light, otherwise its dark ``` K*&ltG8S8Jfq%xGhT2%seT2K?qhz\bK?qhz\lJ-KJ # z=input * # Cartesian product of &ltG8 # first 8 letters of the alphabet (a-h) S8 # 1-indexed range (1-8) K # K holds now all squares f K # Filter K q # is equal %xGhT2 # map [a-h] to a number [1-8] and take it modulo 2 %seT2 # Take modulo 2 from the row number ?qhz\bK # If input starts with 'b' print K ?qhz\lJ # If it starts with 'l' print J -KJ # Otherwise print the difference of those 2 ``` [Answer] ## Python 2, ~~73~~ ~~71~~ 70 bytes ``` lambda s:[chr(x/8+97)+`x%8+1`for x in range(64)if x+x/8&1^ord(s[0])%3] ``` I'm still a bit confused whether functions are okay for the question, since the challenge mentions a "separator", but since there's a lot of other function submissions I've done the same. Similar to [Erwan's answer](https://codegolf.stackexchange.com/a/73366/21487) but with a ~~lot~~ bit more Python 2-ness. *(-2 bytes thanks to @xnor)* [Answer] # PHP, ~~132~~ ~~126~~ ~~120~~ ~~108~~ 106 bytes ``` for($s=strtr($argv[1],bdl,210);$c<8;$c++)for($r=0;$r<8;)if((++$r+$c)%2==$s||$s>1)echo"abcdefgh"[$c]."$r "; ``` It loops through the cols (0-7) and rows (1-8) and checks if the sum of both is odd/even. Tested with PHP 5.6.4, run it: `php -d error_reporting=30709 -r '<CODE>' {dark|light|both}` [Answer] # [Vitsy](http://github.com/VTCAKAVSMoACE/Vitsy), ~~90~~ 82 bytes ``` '`'8\[1+8\:]Yy1-\?8\['1'v8\[vD1+vr?]vX]i'h'-)[88*\[Z?aO]]i'r'-)[?1m]1m 84*\[Z??aO] ``` Explanation of the first line: ``` '`'8\[1+8\:]Yy1-\?8\['1'v8\[vD1+vr?]vX]i'h'-)[88*\[Z?aO]]i'r'-)[?1m]i'g'-)[1m] '`' Push ` to the stack. (this is 1 less than a in ASCII) 8\[ ] Do the stuff in brackets 8 times. 1+ Add one on every recursion (this gets a, b, c, d...) 8\: Clone the stack 8 times. (This gets 8 of each a, b, c...) Y Remove the current stack. y1-\? Go one stack to the left (I really need to builtin this) 8\[ ] Do the stuff in brackets 8 times. '1' Push character literal 1 to the stack. v Save it as a temporary variable. 8\[ ] Do the stuff in brackets 8 times. v Push the temporary variable to the stack. D Duplicate the top item of the stack. 1+ Add one to it (this gives us 1, 2, 3, 4...) v Capture the top item of the stack as a temporary variable. r Reverse the stack. ? Go a stack to the right. vX Clear the temporary variable slot. i'h')[ ] If the last character of the input is 'h', do the stuff in brackets 88*\[ ] Do the stuff in brackets 64 times. Z Output everything in the stack as a character. ? Rotate right a stack. aO Output a newline. i'r')[?1m] If the penultimate character of the input is 'r', rotate over a stack, then execute the first index of lines of code. 1m Execute the first index of lines of code. ``` Explanation of the second line: ``` 84*\[Z??aO] 84*\[ ] Do the stuff in brackets 32 times. Z Output everything in the stack as a char. ?? Rotate two stacks over. aO Output a newline. ``` There will be bonus trailing newlines for 'dark' and 'both'. Requires that only 'dark', 'both', or 'light' will be input. [Try it online!](http://vitsy.tryitonline.net/#code=J2AnOFxbMSs4XDpdWXkxLVw_OFxbJzEndjhcW3ZEMSt2cj9ddlhdaSdoJy0pWzg4KlxbWj9hT11daSdyJy0pWz8xbV0xbQo4NCpcW1o_P2FPXQ&input=&args=bGlnaHQ) [Answer] ## PowerShell v3+, ~~142~~ 129 bytes ``` param($a)$d=$a[0]-in('d','b');$l=$a[0]-in('l','b') 97..104|%{$i=[char]$_;1..8|%{if((($q=($_+$i)%2)-eq$l)-or($q+1-eq$d)){"$i$_"}}} ``` Takes input `$a` and sets two variables for if we're to output `$d`ark or `$l`ight squares based on the first letter of the input. Then, we loop over `a-h` and `1-8` and uses the same trick as on [Determine the color of a chess square](https://codegolf.stackexchange.com/a/64050/42963) to parse whether it's a light or dark square (setting helper variable `$q` in the first test) and add that square to the pipeline if appropriate. After execution, the elements on the pipeline are output one per line. Requires v3 or newer for the `-in` operator. Edit - Saved 13 bytes by eliminating the `switch` and by changing equality testing order [Answer] # Jolf, 48 bytes ``` Ζ-ώ~1tΜ fΜZAQ8ΨΖ+ζ|<%ζγwώt8ώ6d|<i'd!x%H2>i'ldbHγ ``` It's all greek to me ¯\\_(ツ)\_/¯ This is a transpiling of edc65's excellent answer. ``` Ζ-ώ~1t Ζ set ζ to ώ~1 100 * 2 - t minus 10 (=190) ΜZAQ8ΨΖ+ζ|<%ζγwώt8+2t ZAQ8 A zero array of length Q8 (8*8 = 64) Μ Ψ map that Ζ+ζ ζ += %ζγwώt ζ % (γ = 19) < 8 < 8 | ώ6 || 12 Μ f■above thing■d|<i'd!x%H2>i'ldbHγ _f■above thing■d filter the above thing |<i'd!x%H2>i'l removing all the bad stuff (i<'d'|v%2^i>'l') Μ dbHγ map each character to base 19 ``` [Answer] # Perl, 69 + 3 = 72 bytes ``` $b=/b/;$i=/l/;$_="@{[grep{$i=!$i||$b}map{$l=$_;map{$l.$_}1..8}a..h]}" ``` To be run with `perl -p`, for which I've added 3 bytes. Less-golfed version (slightly different, as the babycart operator makes it hard to format nicely): ``` $b=/b/; # flag for input containing b $i=/l/; # start $i as true if input contains 'l' @a = grep { $i = !$i||$b # alternate unless $b is true } map { $l = $_; # save letter map { $l.$_ # join letter and number } 1..8 # generate number sequence } a..h; # generate letter sequence # golfed version uses babycart operator around array expr to save one byte $_ = "@a" # write array, separated ``` The golfed version uses [`"@{[]}"`](http://search.cpan.org/dist/perlsecret/lib/perlsecret.pod#Baby_cart); the commented version uses `@a=...; "@"` so that the commented code is still runnable. [Answer] # C++, 132 bytes Takes input by command-line. Uses pointer/modulo voodoo for print condition. ``` #include<stdio.h> int main(int i,char**v){for(int n=0;n<64;n++)if((n+(i=n/8))%2-*v[1]%3){putchar(i+97);putchar(n%8+49);putchar(32);}} ``` [Answer] # Java, 143 ``` class H{public static void main(String[]a){for(char c=96;++c<'i';)for(int i=0;++i<9;)if((i+c)%2!=a[0].charAt(0)%3)System.out.println(c+""+i);}} ``` Hey, it's not the longest answer :) Input is taken as a command-line argument. [Answer] # PHP, ~~99~~ ~~82~~ ~~79~~ ~~76~~ ~~74~~ 73 bytes Uses ISO 8859-1 encoding. ``` for($z=$argv[1];++$x<72;)$x%9&&$z<c|$z>k^$x&1&&print~ß.chr($x/9+97).$x%9; ``` Run like this (`-d` added for aesthetics only): ``` php -d error_reporting=30709 -r 'for($z=$argv[1];++$x<72;)$x%9&&$z<c|$z>k^$x&1&&print~ß.chr($x/9+97).$x%9; echo"\n";' dark ``` It works like this: variable `$x` is incremented from 1 to 71, the numbers correspond to the cells as shown below. ``` r\c 1 2 3 4 5 6 7 8 [invalid column] A 1 2 3 4 5 6 7 8 9 B 10 11 12 13 14 15 16 17 18 C 19 20 21 22 23 24 25 26 27 D 28 29 30 31 32 33 34 35 36 E 37 38 39 40 41 42 43 44 45 F 46 47 48 49 50 51 52 53 54 G 55 56 57 58 59 60 61 62 63 H 64 65 66 67 68 69 70 71 72 ``` Therefore, `$x modulo 9` yields the column number and `$x / 9` yields the row number, which I convert to a letter using `chr`. The code `$z<c|$z>k^$x&1` yields `true` for input `both` (`$z<c`) and in the case of `light` or `dark` only for the even or odd cells respectively (`$z>k ^ $x&1`). The result of this expression determines whether or not the cell coordinates will then be printed. Finally, if `$x modulo 9` results in `0`, I skip that non-existant cell. * Saved ~~18~~ 17 bytes (fixed a bug) by having only 1 loop, converting the number to a char instead of the other way around * Saved 3 bytes by combining the condition for dark and light with a `xor` * Saved 3 bytes by comparing against the full input instead of the first char * Saved 2 bytes because no longer need to subtract `.125` in the expression `$x/9+69.9` to get the correct row number before converting to a char * Saved a byte by using `~ß` to yield a space [Answer] # JavaScript ES6, ~~187~~ ~~160~~ 159 bytes ~~I'm probably missing something painfully obvious.~~ Oh well. Not having to flatten the array helps. ``` l=s=>(E=[2,4,6,8],O=[1,3,5,7],h=(z=s[0]=="d")?O:E,d=z?E:O,[...h.map(t=>[..."aceg"].map(e=>e+t)),...(d.map(t=>[..."bdfh"].map(e=>e+t))),...(s[0]=="b"?l`d`:[])]) ``` Returns a 2D array. --- Try it here: ``` l=s=>(E=[2,4,6,8],O=[1,3,5,7],h=(z=s[0]=="d")?O:E,d=z?E:O,[...h.map(t=>[..."aceg"].map(e=>e+t)),...(d.map(t=>[..."bdfh"].map(e=>e+t))),...(s[0]=="b"?l`d`:[])]) U=x=>o.innerHTML=JSON.stringify(l(i.value)); i.onchange=U;U(); ``` ``` *{font-family:Consolas,monospace;} ``` ``` <select id=i><option value="light">light</option><option value="dark">dark</option><option value="both">both</option></select><div id=o></div> ``` [Answer] # Ruby, 85 I think there are shorter ways about this, but this is a cute use of `.upto`. ``` gets;'a1'.upto('h8'){|e|puts e if e[/[1-8]/]&&(~/b/||((e.ord%2!=e[1].ord%2)^! ~/l/))} ``` [Answer] # R, ~~129~~ 94 bytes I knew I could generate the board better :). Essentially this builds an inverted board, filtering out grid references where the shade does not match the input. Output is space separated. ``` a=which(array(c('light','dark'),c(9,9))[-9,-9]!=scan(,''),T);cat(paste0(letters[a[,1]],a[,2])) ``` Ungolfed ``` a=which( # Get the indexes of array(c('light','dark'),c(9,9)) # an array of light dark [-9,-9] # except for the ninth row and column !=scan(,'') # where the value doesn't equal the input ,T # return array index not vector ); cat(paste0(letters[a[,1]],a[,2])) # using letters for col ``` Test ``` > a=which(array(c('light','dark'),c(9,9))[-9,-9]!=scan(,''),T);cat(paste0(letters[a[,1]],a[,2])) 1: dark 2: Read 1 item a1 c1 e1 g1 b2 d2 f2 h2 a3 c3 e3 g3 b4 d4 f4 h4 a5 c5 e5 g5 b6 d6 f6 h6 a7 c7 e7 g7 b8 d8 f8 h8 > a=which(array(c('light','dark'),c(9,9))[-9,-9]!=scan(,''),T);cat(paste0(letters[a[,1]],a[,2])) 1: light 2: Read 1 item b1 d1 f1 h1 a2 c2 e2 g2 b3 d3 f3 h3 a4 c4 e4 g4 b5 d5 f5 h5 a6 c6 e6 g6 b7 d7 f7 h7 a8 c8 e8 g8 > a=which(array(c('light','dark'),c(9,9))[-9,-9]!=scan(,''),T);cat(paste0(letters[a[,1]],a[,2])) 1: both 2: Read 1 item a1 b1 c1 d1 e1 f1 g1 h1 a2 b2 c2 d2 e2 f2 g2 h2 a3 b3 c3 d3 e3 f3 g3 h3 a4 b4 c4 d4 e4 f4 g4 h4 a5 b5 c5 d5 e5 f5 g5 h5 a6 b6 c6 d6 e6 f6 g6 h6 a7 b7 c7 d7 e7 f7 g7 h7 a8 b8 c8 d8 e8 f8 g8 h8 > ``` [Answer] # Oracle SQL 11.2, ~~192~~ 180 bytes ``` SELECT CHR(64+x),DECODE(y,0,8,y)FROM(SELECT CEIL(LEVEL/8)x,MOD(LEVEL,8)y FROM DUAL CONNECT BY LEVEL<=64)WHERE(:1='dark'AND MOD(x+y,2)=0)OR(:1='light'AND MOD(x+y,2)=1)OR(:1='both'); ``` Un-golfed ``` WITH v AS ( SELECT CEIL(LEVEL/8)x, DECODE(MOD(LEVEL,8),0,8,MOD(LEVEL,8))y FROM DUAL CONNECT BY LEVEL<=64 ) SELECT CHR(64+x),y FROM v WHERE (:1='dark' AND MOD(x+y,2)=0)OR(:1='light' AND MOD(x+y,2)=1)OR(:1='both'); ``` The v view generate the coordinates of each square. If the sum of the coordinates is even then the square is black, else it's white. [Answer] **Rust, ~~263~~ ~~259~~ 244 Bytes** ``` use std::char;use std::env;fn main(){let n=env::args().nth(1).unwrap();for i in 0..8{for j in 0..8{if n=="both"||(n=="dark"&&(i+j)%2==0)||(n== "light"&&(i+j)%2!=0){println!("{}{}",char::from_u32(i+97).unwrap(),char::from_u32(j+49).unwrap())}}}} ``` Expanded Form: ``` fn main() { let input = env::args().nth(1).unwrap(); for i in 0..8{ for j in 0..8{ if input == "both" || (input == "dark" && (i+j)%2==0) || (input == "light" && (i+j)%2!=0){ println!("{}{}",char::from_u32(i+97).unwrap(),char::from_u32(j+49).unwrap()); } } } } ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 31 bytes ``` 1)t3\8:t!++w4\~?H\]2#f2Y2!w)wVh ``` [**Try it online!**](http://matl.tryitonline.net/#code=MSl0M1w4OnQhKyt3NFx-P0hcXTIjZjJZMiF3KXdWaA&input=J2Rhcmsn) [Answer] # CJam, 29 ``` qci3%:X;8Ym*{~+2%X-},"a1 "f.+ ``` Just a quick and dirty solution :p [Try it online](http://cjam.aditsu.net/#code=qci3%25%3AX%3B8Ym*%7B%7E%2B2%25X-%7D%2C%22a1%20%22f.%2B&input=dark) **Explanation:** ``` q read the input ci convert to (first) character then to integer 3% modulo 3; results for d(ark), l(ight) and b(oth) are 1, 0, 2 :X; store in X and pop 8Ym* generate all pairs (Y=2) of numbers from 0 to 7 {…}, filter using the condition block ~ dump the current pair on the stack +2% calculate the sum modulo 2 X- subtract X; if the result is not 0, the pair is kept "a1 "f.+ vectorized-add "a1 " to each remaining pair this means the character 'a' is added to the first number, the character '1' is added to the second number, and then the space character is appended the contents of the stack are automatically printed at the end ``` [Answer] # Haskell, 133 116 105 100 98 91 bytes ``` f r=[["abcdefgh"!!x,"12345678"!!y]|x<-l,y<-l,odd(x+y)||r<"l",even(x+y)||r!!0/='d'] l=[0..7] ``` This is my first attempt at golfing Haskell. With some help from Michael Klein, we managed to get it under 100 chars! [Answer] # Mathematica 133 bytes **Method 1**: 108 bytes. This constructs the board as a table, with labels in each cell, and returns light or dark diagonals or bands as required. ``` Table[Table[{i,j},{i,{h,g,f,e,d,c,b,a}},{j,Range@8}]~Diagonal~k,{k,If[#=="light",-6,-7],7,If[#=="both",1,2]}]& ``` --- ``` %["light"] (*where % repeats the preceding line *) ``` > > {{{b, 1}, {a, 2}}, {{d, 1}, {c, 2}, {b, 3}, {a, 4}}, {{f, 1}, {e, > 2}, {d, 3}, {c, 4}, {b, 5}, {a, 6}}, {{h, 1}, {g, 2}, {f, 3}, {e, > 4}, {d, 5}, {c, 6}, {b, 7}, {a, 8}}, {{h, 3}, {g, 4}, {f, 5}, {e, > 6}, {d, 7}, {c, 8}}, {{h, 5}, {g, 6}, {f, 7}, {e, 8}}, {{h, 7}, {g, > 8}}} > > > --- **Method 2**: 133 bytes. Creates an array and selects according to the even-odd nature of the sum of the row number + column number of each cell. ``` Position[Array[Boole@OddQ[#+#2] &,{8,8}],Switch[#,"dark",0,"light",1,"both",0|1]]/. {j_,k_}:>{j/.Thread[Range@8->{a,b,c,d,e,f,g,h}],k}& ``` --- [Answer] # JS, 197 bytes ``` b=[];d=[];l=[];for(i=1;i<9;i++){for(j=1;j<9;j++){a=String.fromCharCode(96+i*1)+j;b.push(a);if((i+j)%2<1){d.push(a)}else{l.push(a)}}}m=[0,"both",b,"dark",d,"light",l];alert(m[m.indexOf(prompt())+1]) ``` [Answer] ## Python (3.5), ~~106~~ ~~100~~ ~~96~~ 92 bytes use the trick of MegaTom `(i+j)%2` to win 6 bytes ``` f=lambda s:[chr(97+i//8)+str(1+i%8)for i in range(64)if s[0]=='b'or(i//8+i)%2==(s[0]=='l')] ``` [Try it on repl.it](https://repl.it/Bn5f/3) ## Results ``` >>> f('light') ['a2', 'a4', 'a6', 'a8', 'b1', 'b3', 'b5', 'b7', 'c2', 'c4', 'c6', 'c8', 'd1', 'd3', 'd5', 'd7', 'e2', 'e4', 'e6', 'e8', 'f1', 'f3', 'f5', 'f7', 'g2', 'g4', 'g6', 'g8', 'h1', 'h3', 'h5', 'h7'] >>> f('dark') ['a1', 'a3', 'a5', 'a7', 'b2', 'b4', 'b6', 'b8', 'c1', 'c3', 'c5', 'c7', 'd2', 'd4', 'd6', 'd8', 'e1', 'e3', 'e5', 'e7', 'f2', 'f4', 'f6', 'f8', 'g1', 'g3', 'g5', 'g7', 'h2', 'h4', 'h6', 'h8'] >>> f('both') ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'g1', 'g2', 'g3', 'g4', 'g5', 'g6', 'g7', 'g8', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8'] ``` **Previous version** ``` f=lambda s:[i for i in[i+j for i in'abcdefgh'for j in'123456780'][s[0]=='l'::2-(s[0]=='b')]if'0'not in i] ``` [Answer] C++, 119 Bytes Based on MegaTom's trick. ``` #include <stdio.h> int main(int n,char**v){for(n=0;n<64;++n){if((n+n/8)%2-**(v+1)%3){printf("%c%c ",n/8+97,n%8+49);}}} ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 112 bytes ``` f(char*s){for(int m=*s^'d'?*s^'l'?3:2:1,l=64,x;l--;m&1&!x|(m&2&&x)&&printf("%c%d ",l%8+97,l/8+1))x=l%8%2^l/8%2;} ``` [Try it online!](https://tio.run/##PY7bCoMwEESfzVfYQGKikaItrVXEHxHBJnih8YKxRbB@u42C3ZfZmeUwy92S83UtCK/ywVZ0LrqB1O1oNrGtMktYySbSSi6hH3pMxrcrmyLpulGDPXyavqTBPsYTxbgfNFcQiDgSJmQSBc7jzuQ5cDxKp1h75GfaIj9a1k9XC7M8WsEMjD@u0tbVk7aQmYpGwCiIlv49KgJ1qJMFgP3FvG7JzpYEinx4bbdtl3VZjYd5dmO1Q@sP "C (gcc) – Try It Online") If a == 1, then a square will always be black if the "oddness" of row and column is the same, i.e. both are odd or both are even. The opposite is true for white squares, where row and column will always differ in oddness. After that, it's just a matter of combining row and column loops, as well as consulting a table of operator precedence until a sufficient level of incomprehensibility has been reached. ]
[Question] [ ### Introduction [As ToonAlfrink says](https://codegolf.stackexchange.com/questions/30361/the-shortest-code-to-invert-a-binary-string): "Me thinks there aren't enough easy questions on here that beginners can attempt!". So the task is very simple. Given a string, output a truthy or falsy value whether the name is official or not. **A name is "official" if it is a single title-case word, that is:** * If the *first* letter is capitalized (not official: `adnan`) * If the other letters are *not* capitalized (not official: `AdNaN`) * If the name *doesn't* contain any non-alphabetic characters (not official: `Adnan123`, `Adnan!`) * If the name consists of just one word (not official: `Adn an`, `Adn An`) * If the name has more than one character (not official: `A`) ### Rules * You may provide a function or a program * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! * **Note:** To simplify things, names like Mary-Ann are in this challenge *not official.* * Assume that there are no leading whitespaces in the name. * Assume that only the printable ASCII characters (`32-126`) are used in the names ### Test cases ``` Input: Adnan Output: True Input: adnan Output: False Input: AdnaN Output: False Input: Adnan123 Output: False Input: Adnan Adnan Output: False Input: A Output: False Input: Mary-Ann Output: False ``` ### Leaderboard ``` /* Configuration */ var QUESTION_ID = 67554; // Obtain this from the url // It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 34388; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1; if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # Retina, 13 bytes ``` ^[A-Z][a-z]+$ ``` [Try it online](http://retina.tryitonline.net/#code=XltBLVpdW2Etel0rJA&input=QWRuYW4) | [Test suite](http://retina.tryitonline.net/#code=bWBeW0EtWl1bYS16XSsk&input=YWRuYW4KQWRuYU4KQWRuYW4xMjMKQWRuYW4gQWRuYW4KQQpNYXJ5LUFubg) (The output `0` means none of the strings matched, which is expected.) When Retina is only provided with a single line of code, it outputs the number of times the expression matched the input string, so it will output `1` (truthy) if it matches and therefore is an official name and `0` (falsy) if it's not. ### Breakdown ``` ^ The beginning of the string [A-Z] One uppercase letter [a-z]+ One or more lowercase letters $ The end of the string ``` [Answer] # TeaScript, 12 bytes ``` xO`A-Z][a-z` ``` Abuses the `O` function. [Try this online](http://vihanserver.tk/p/TeaScript/#?code=%22xO%60A-Z%5D%5Ba-z%60%22&inputs=%5B%22Vihan%22%5D&opts=%7B%22int%22:false,%22ar%22:false,%22debug%22:false,%22chars%22:false,%22html%22:false%7D) [Test Suite](http://vihanserver.tk/p/TeaScript/#?code=%22xs%C2%A7.m(%23(x%3Dl,%20%60$%7Bl%7D:%20$%7BxO%60A-Z%5D%5Ba-z%60%7D%60))j%C2%A7%22&inputs=%5B%22Adnan%5Cnadnan%5CnAdnaN%5CnAdnan123%5CnAdnan%20Adnan%5CnA%5CnMary-Ann%22%5D&opts=%7B%22int%22:false,%22ar%22:false,%22debug%22:false,%22chars%22:false,%22html%22:false%7D) ## Explanation The `O` function makes this: ``` x O `A-Z][a-z` x.O(/^[A-Z][a-z]+$/) ``` Then, the O function checks if the regex matches `x`. --- Alternatively, a TeaScript 3 answer at **7 bytes**: ``` xO/\A\a ``` [Answer] # JavaScript (ES6), 26 ``` n=>/^[A-Z][a-z]+$/.test(n) ``` By: Edcsixtyfive ``` f=n=>/^[A-Z][a-z]+$/.test(n) console.log=x=>O.textContent+=x+'\n' ;['Adnan','adnan','AdnaN','Adnan123','Adnan Adnan','A','Mary-Ann'] .forEach(t=>console.log(t+' '+f(t))) ``` ``` <pre id=O></pre> ``` [Answer] # Python, ~~59~~ 58 bytes I'm sure there's no real way to beat the Retina version, since this is basically just that within Python. But I think this is my first submission ;) ``` import re,sys;print(re.match('[A-Z][a-z]+$',sys.argv[1])) ``` It's a very *odd* truthy value: ``` (test2)wayne@arglefraster ~/programming/inactive/golf/67554 ⚘ python golf.py AdNan $? 148 %# 3 10:06:36 None (test2)wayne@arglefraster ~/programming/inactive/golf/67554 ⚘ python golf.py Adnan %# 3 10:06:40 <_sre.SRE_Match object at 0x7feefea7f440> (test2)wayne@arglefraster ~/programming/inactive/golf/67554 ⚘ python golf.py "Adnan Banana" %# 3 10:06:47 None ``` (And it does require `""` around strings with spaces in it, if passed via the shell) [Answer] # Pyth, ~~16~~ ~~13~~ 12 bytes *Thanks to @Thomas Kwa for reminding me about titlecase.* ``` &qzr@GrzZ3tz ``` [Test Suite](http://pyth.herokuapp.com/?code=%26qzr%40GrzZ3tz&input=Adnan&test_suite=1&test_suite_input=Adnan%0Aadnan%0AAdnaN%0AAdnan123%0AAdnan+Adnan%0AA%0AMary-Ann&debug=0). ``` & Boolean and operator qz Equality test on input r 3 Titlecase operator @G Setwise intersection with the alphabet rzZ Input to lowercase tz All but the first character of the input ``` [Answer] # Java, 53 bytes ``` boolean b(String a){return a.matches("[A-Z][a-z]+");} ``` [Answer] # Python, ~~50~~ ~~45~~ ~~43~~ 41 bytes ``` lambda s:s.isalpha()*s.istitle()*len(s)>1 ``` Returns `True` if it's an official name or `False` if it's not. [Answer] # [BotEngine](https://github.com/SuperJedi224/Bot-Engine), ~~203~~ ~~180~~ 29x6=174 ``` v ABCDEFGHIJKLMNOPQRSTUVWXYZ >ISSSSSSSSSSSSSSSSSSSSSSSSSSF v <<<<<<<<<<<<<<<<<<<<<<<<<< Tabcdefghijklmnopqrstuvwxyz > SSSSSSSSSSSSSSSSSSSSSSSSSSF ^E<<<<<<<<<<<<<<<<<<<<<<<<<< ``` I should really add builtins for identifying uppercase and lowercase letters. That would be much more concise than checking each letter individually. Rough translation: ``` for a of input enqueue a if ABCDEFGHIJKLMNOPQRSTUVWXYZ contains first remove first while abcdefghijklmnopqrstuvwxyz contains first remove first if empty yield TRUE exit else yield FALSE exit else yield FALSE exit ``` [Answer] # Ruby, 28 bytes ``` p (gets=~/^[A-Z][a-z]+$/)!=p ``` -2 bytes( thanks to manatwork ) [Answer] # C, 129 122 121 111 bytes ``` main(c,b,d){b=d=0;while((c=getchar())>13)b|=b|=!b&&c>90|c<65?1:2&&d++&&c<97|c>122?4:2;printf("%d\n",b<3&&d>1);} ``` [Try It Online](https://ideone.com/xaQPoR) ``` main(c,b,d) { b=d=0; while((c=getchar())>13) { // Twiddle bits, 1<<0 for first character and 1<<3 for subsequent b|=!b&&c>90|c<65?1:2; // check first character is valid b|=d++&&c<97|c>122?4:2; // check later characters are valid } // If all OK b == 2, if either of above are wrong, b >= 3 due to // extra bits. Also, d should be > 1 for name length to be valid. printf("%d\n",b<3&&d>1); } ``` [Answer] # VB6, 48 bytes ``` Function f(i):f=i Like"[A-Z][a-z]+":End Function ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ ~~7~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` á™Qצ ``` -4 bytes thanks to *@Grimy*. [Try it online](https://tio.run/##yy9OTMpM/f//8MJHLYsCD08/tOxIw///jgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeXhCf8PL3zUsijw8PRDy440/Nf5H63kmJKXmKeko6CUCGe4@Dn6gRiOKbpQIZAiPxgjz9DIGM5WgOt3BBG@iUWVuo55YAGf/BxkqBQLAA). **Explanation:** ``` á # Only leave the letters of the (implicit) input # i.e. "Adnan" → "Adnan" # i.e. "A" → "A" # i.e. "aDNAN" → "aDNAN" # i.e. "Adnan123" → "Adnan" ™ # Titlecase it # i.e. "Adnan" → "Adnan" # i.e. "Adnan" → "A" # i.e. "aDNAN" → "Adnan" Q # Check if it's still equal to the (implicit) input # i.e. "Adnan" and "Adnan" → 1 (truthy) # i.e. "A" and "A" → 1 (truthy) # i.e. "aDNAN" and "Adnan" → 0 (falsey) # i.e. "Adnan123" and "Adnan" → 0 (falsey) × # Repeat the (implicit) input that many times # i.e. "Adnan" and 1 → "Adnan" # i.e. "A" and 1 → "A" # i.e. "aDNAN" and 0 → "" # i.e. "Adnan123" and 0 → "" ¦Ā # Remove the first character, and check that it's non-empty # i.e. "Adnan" → "dnan" → 1 (truthy) # i.e. "A" → "" → 0 (falsey) # i.e. "" → "" → 0 (falsey) # (which is output implicitly as result) ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 18 bytes The current version ([4.0.0](https://github.com/lmendo/MATL/releases/tag/4.0.0)) of the language is used. This applies the same regular expression as [NinjaBearMonkey's answer](https://codegolf.stackexchange.com/a/67555/36398): ``` j'^[A-Z][a-z]+$'XX ``` The output is the string (which [is truthy](http://meta.codegolf.stackexchange.com/a/2194/36398)) if it's an official name, and nothing (which [is falsy](http://meta.codegolf.stackexchange.com/a/2194/36398)) if it's not. ### Examples ``` >> matl > j'^[A-Z][a-z]+$'XX > > December December >> >> matl > j'^[A-Z][a-z]+$'XX > > ASCII >> ``` [Answer] # Haskell, 61 bytes ``` f(h:t@(_:_))=elem h['A'..'Z']&&all(`elem`['a'..'z'])t f _=1<0 ``` [Answer] # Gema, 17 characters ``` \B<K1><J>\E=1 *=0 ``` Sample run: ``` bash-4.3$ echo -n 'Adnan' | gema '\B<K1><J>\E=1;*=0' 1 bash-4.3$ echo -n 'adnan' | gema '\B<K1><J>\E=1;*=0' 0 bash-4.3$ echo -n 'Adnan123' | gema '\B<K1><J>\E=1;*=0' 0 ``` [Answer] # IA-32 machine code, 19 bytes A function that receives the pointer to a null-terminating string in `ecx` and returns 0 or 1 in `eax` (according to the `fastcall` convention). Hexdump of the code: ``` 6a 20 58 32 01 74 0a 41 2c 61 3c 1a b0 00 72 f3 c3 40 c3 ``` In assembly language: ``` push 32; pop eax; myloop: xor al, [ecx]; jz yes; inc ecx; sub al, 'a'; cmp al, 26; mov al, 0; jb myloop; ret; yes: inc eax; ret; ``` The first byte of the input name has its 5th bit flipped (`xor` with `32`) to convert it from capital case to small case. This loads 32 into `eax`, using 3 bytes of code: ``` push 32; pop eax; ``` To check whether the byte is a small letter: ``` sub al, 'a'; cmp al, 26; jb myloop; ``` If not, this code falls through. To return 0 in this case, it puts 0 in `al` before doing the conditional jump: ``` sub al, 'a'; cmp al, 26; mov al, 0; jb myloop; ``` The 0 in `al` also serves as a xor-mask (or absence of it) for the following bytes of the input name. A successful exit is when it encounters a zero byte, which stays zero after the `xor`: ``` xor al, [ecx]; jz yes; ``` It assumes that the input name is not empty. I guess it's a reasonable assumption about a name (not an arbitrary string)! [Answer] ### `grep`, 16 bytes This is the pattern: ``` [A-Z][a-z]+ ``` If you use the `-E` and `-x` and `-c` switches `grep` will print a count of matching input lines. So if you give it one line you get a 1 or a 0. I think that's how this place works. The pattern is 11 chars, the whole command line is 23. I've seen people use `sed` scripts without the command so I don't know what is what. But, it reads stdin, and so you can just type at it. Here's `echo`: ``` for a in Adnan adnan Ad\ nan do echo "$a" | grep -cxE \[A-Z]\[a-z]+ done ``` --- ``` 1 0 0 ``` [Answer] ## Mathematica 10.1, 46 bytes ``` LetterQ@#&&#==ToCamelCase@#&&StringLength@#>1& ``` Uses one less byte than the standard regex solution. It does three checks. `LetterQ@#` ensures that the string is entirely composed of letters, and `StringLength@#>1` invalidates single-letter strings. `#==ToCamelCase@#` makes less sense, however. `ToCamelCase` is an undocumented function I found that takes an input string AndOutputsItLikeThis. Since there is only one word, it will capitalize the first letter, so we check if the string is equal to that. [Answer] ## bash/zsh/ksh, 25 bytes ``` [[ $1 =~ ^[A-Z][a-z]+$ ]] ``` To actually use this, make a file with it as the only line and make the file executable; executable files not recognized as a known binary type are treated as shell scripts (for `/bin/sh` specifically). ``` $ printf '[[ $1 =~ ^[A-Z][a-z]+$ ]]' >f $ chmod +x f $ wc -c f 25 f $ for x in 'Adnan' 'adnan' 'AdnaN' 'Adnan123' 'Adnan Adnan' 'A' 'Mary-Ann'; do f "$x" && echo 1 || echo 0; done 1 0 0 0 0 0 0 $ ``` [Answer] ## C# 4, 89 bytes My first attempt at Code Golf. Here it comes: ``` bool o(string i){return System.Text.RegularExpressions.Regex.IsMatch(i,"^[A-Z][a-z]+$");} ``` See it in action at [Dot Net Fiddle](https://dotnetfiddle.net/CulhZw). [Answer] # Java, 28 bytes ``` n->n.matches("[A-Z][a-z]+") ``` Uses regex to make sure the string consists of an uppercase character followed by at least one lowercase character. -1 bytes thanks to Benjamin Urquhart [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` Lċ?₍ǐǍ≈∧ ``` [Try it Online (with test cases)!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiTMSLP+KCjceQx43iiYjiiKciLCIiLCJBZG5hblxuRW1pcnBzXG5Kb2huXG5hZG5hblxuQWRuYU5cbkFkbmFuMTIzXG5BZG5hbiBBZG5hblxuQVxuTWFyeS1Bbm4iXQ==) Potentially golfable. I swear there was a builtin for `len(a)>1`... Assumes input is nonempty. ``` L # Length of input ċ # is not 1 ? # Push the input, ₍ # parallel apply... ǐ # title case and Ǎ # keep only alphabetic chars ≈ # is equal? ∧ # bitwise AND the length and ^ ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `b`, 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md "Thunno 2 Codepage") ``` Ịḟ=×ḣ ``` Port of Kevin Cruijssen's 05AB1E answer. #### Explanation ``` Ịḟ=×ḣ # Implicit input Ị # Remove non-alphabets from the input ḟ # Convert this string to title case = # Check whether it's still equal to the input × # Repeat the input this many times # (i.e. input if true, empty string otherwise) ḣ # Remove the first character from this string # The b flag boolifies the resulting string, # checking that it is not empty # Implicit output ``` #### Screenshots [![Screenshot 1](https://i.stack.imgur.com/8n3bDm.png)](https://i.stack.imgur.com/8n3bD.png) [![Screenshot 2](https://i.stack.imgur.com/cPLQ2m.png)](https://i.stack.imgur.com/cPLQ2.png) (click to enlarge) [Answer] ## k4, 39 bytes ``` {((*x)in .Q.A)&(&/(1_,/x)in .Q.a)&1<#x} ``` First char is upper, all others are lower, count greater than one. E.g.: ``` {((*x)in .Q.A)&(&/(1_,/x)in .Q.a)&1<#x}'("Adnan";"adnan";"AdnaN";"Adnan123";"Adnan Adnan";"A";"Mary-Ann") 1000000b ``` [Answer] ## Seriously, 16 bytes ``` ú4,nÿ=)l1<)ù-Y&& ``` Hex Dump: ``` a3342c6e983d296c313c29972d592626 ``` [Try It Online](http://seriouslylang.herokuapp.com/link/code=a3342c6e983d296c313c29972d592626&input=Adnan) Seriously does not have regex support yet, so the best we can do is: ``` 4,n Push 4 copies of input ÿ= Check that it's equal to itself converted to titlecase ) Put the boolean on the bottom l1< Check that it's longer than 1 character ) Put the boolean on the bottom ù Convert it to lowercase. ú -Y Check that removing the lowercase alphabet empties it && And all the booleans together ``` [Answer] # Ocaml, 231 216 197 166 bytes ``` let f n=let l=String.length n in if l=1 then 0 else let rec e=function 0->1|i->match n.[i] with('a'..'z')->e(i - 1)|_->0 in match n.[0]with('A'..'Z')->e(l - 1)|_->0;; ``` Example usage: ``` # f "Adnan";; - : int = 1 # f "adnan";; - : int = 0 # f "AdnaN";; - : int = 0 # f "Adnan123";; - : int = 0 # f "Adnan Adnan";; - : int = 0 # f "A";; - : int = 0 # f "Mary-Ann";; - : int = 0 ``` Ungolfed (with real function names): ``` let is_name name = let len = String.length name in if len = 1 then 0 else let rec explode_lower = function | 0 -> 1 | i -> match name.[i] with | ('a'..'z') -> explode_lower (i - 1) | _ -> 0 in match name.[0] with | ('A'..'Z') -> explode_lower (len - 1) | _ -> 0;; ``` [Answer] # SpecBAS - 39 bytes SpecBAS handles regular expressions through the `MATCH` command. Output is 0 for false and 1 if true. ``` 1 input n$: ?MATCH("^[A-Z][a-z]+$",n$) ``` [Answer] ## Swift 2, 116 bytes Regex is so verbose in Swift that doing this is much shorter ``` func e(s:String)->Int{var c=0;for k in s.utf8{if(c==0 ?k<65||k>90:k<97||k>122){return 0};c++};return s.utf8.count-1} ``` This will return `0` or `-1` (in the case of no input) for non-official names, and a number `> 0` (which is equal to the length of the string - 1) if the name is official ### Ungolfed ``` func e(s: String) -> Int{ var c = 0 for k in s.utf8{ if(c == 0 ? k < 65 || k > 90 : k < 97 || k > 122){ return 0 } c++ } return s.utf8.count - 1 } ``` [Answer] ## C#, 188 bytes Regular expressions would have been the right way to tackle this, but here's an attempt without it. ``` bool O(string s){for(int i=1;i<s.Length;i++){if(char.IsUpper(s[i])){return false;}}if(char.IsUpper(s[0])&&s.All(Char.IsLetter)&&!s.Contains(" ")&& s.Length > 1){return true;}return false;} ``` Longhand ``` static bool O(string s) { for (int i = 1; i < s.Length; i++) { if (char.IsUpper(s[i]) ) { return false; } } if (char.IsUpper(s[0]) && s.All(Char.IsLetter) && !s.Contains(" ") && s.Length > 1) { return true; } return false; } ``` Would love advice on how to make the lowercase check shorter, perhaps without the loop. I just started learning the language, and used this as practice, figured I'd share my result anyway. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 18 bytes ``` $_=/^[A-Z][a-z]+$/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lY/LtpRNyo2OlG3KlZbRf//f8eUvMQ8rkQwCWL7gck8QyNjCEMBosCRyzexqFLXMS/vX35BSWZ@XvF/3YIcAA "Perl 5 – 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/17456/edit). Closed 6 years ago. [Improve this question](/posts/17456/edit) Write a program that checks if the integer is a power of 2. --- *Sample input:* ``` 8 ``` *Sample output:* ``` Yes ``` --- *Sample input:* ``` 10 ``` *Sample output:* ``` No ``` --- **Rules:** * Don't use `+`,`-` operations. * Use some sort of input stream to get the number. Input is not supposed to be initially stored in a variable. * The shortest code (in bytes) wins. You can use any truthy/falsy response (for instance, `true`/`false`). You may assume that input number is greater than `0`. [Answer] ## APL (7) Yes, that's 7 *bytes*. Assume for the moment that I'm using [IBM codepage 907](http://www-03.ibm.com/systems/resources/systems_i_software_globalization_pdf_cp00907z.pdf) instead of Unicode and then each character is a byte :) ``` 0=1|2⍟⎕ ``` i.e. `0 = mod(log(input(),2),1)` [Answer] ## GolfScript, 6 chars, no decrements ``` ~.3/&! ``` Here's a solution that doesn't use the `x & (x-1)` method in *any* form. It uses `x & (x/3)` instead. ;-) Outputs `0` if false, `1` if true. **Explanation:** * `~` evals the input string to turn it into a number, * `.` duplicates it (for the subsequent `&`), * `3/` divides it by three (truncating down), * `&` computes the bitwise AND of the divided value with the original, which will be zero if and only if the input is zero or a power of two (i.e. has at most one bit set), and * `!` logically negates this, mapping zero to one and all other values to zero. **Notes:** * Per the clarified rules, [zero is not a valid input](/posts/comments/33451), so this code is OK, even though it outputs `1` if the input is zero. * If the GolfScript decrement operator `(` is allowed, then the **5-character** solution `~.(&!` [posted by aditsu](/a/17479) is enough. However, it seems to go against [the spirit of the rules](/posts/comments/33459), if not the letter. * I came up with the `x & (x/3)` trick years ago on the Fun With Perl mailing list. (I'm sure I'm not the first to discover it, but I did (re)invent it independently.) [Here's a link to the original post](http://www.bumppo.net/lists/fun-with-perl/2000/05/msg00065.html), including a proof that it actually works. [Answer] # GolfScript, 11 (for 1 (true) and 0 (false)) ``` .,{2\?}%?0> ``` Put the number on the stack and then run. # GolfScript, 22 (for Yes/No) ``` .,{2\?}%?0>'Yes''No'if ``` I love how converting `1`/`0` to `Yes`/`No` takes as much code as the challenge itself :D Warning: EXTREMELY inefficient ;) It does work fine for numbers up to 10000, but once you get that high you start to notice slight lag. Explanation: * `.,`: turns `n` into `n 0..n` (`.` duplicate, `,` 0..n range) * `{2\?}`: to the power of 2 * `%`: map "power of 2" over "0..n" so it becomes `n [1 2 4 8 16 ...]` * `?0>`: checks to see if the array contains the number (0 is greater than index) [Answer] # Mathematica 28 ``` Numerator[Input[]~Log~2]==1 ``` For integer powers of 2, the numerator of the base 2 log will be 1 (meaning that the log is a unit fraction). Here we modify the function slightly to display the presumed input. We use `#` in place of `Input[]` and add `&` to define a pure function. It returns the same answer that would be returned if the user input the number in the above function. ``` Numerator[#~Log~2] == 1 &[1024] Numerator[#~Log~2] == 1 &[17] ``` > > True > > False > > > Testing several numbers at a time. ``` Numerator[#~Log~2] == 1 &&/@{64,8,7,0} ``` > > {True, True, False, False} > > > [Answer] # Perl 6 (17 characters) ``` say get.log(2)%%1 ``` This program gets a line from STDIN `get` function, calculates logarithm with base 2 on it (`log(2)`), and checks if the result divides by 1 (`%%1`, where `%%` is divides by operator). Not as short as GolfScript solution, but I find this acceptable (GolfScript wins everything anyway), but way faster (even considering that Perl 6 is slow right now). ``` ~ $ perl6 -e 'say get.log(2)%%1' 256 True ~ $ perl6 -e 'say get.log(2)%%1' 255 False ``` [Answer] **Octave (~~15~~ 23)** EDIT: Updated due to user input requirement; ``` ~mod(log2(input('')),1) ``` Lets the user input a value and outputs 1 for true, 0 for false. Tested in Octave, should work in Matlab also. [Answer] ## R, 13 11 Based on the Perl solution. Returns `FALSE` or `TRUE`. ``` !log2(i)%%1 ``` The parameter `i` represents the input variable. An alternative version with user input: ``` !log2(scan())%%1 ``` [Answer] # GolfScript, 5 Outputs 1 for true, 0 for false. Based on user3142747's idea: ``` ~.(&! ``` Note: `(` is decrement, hopefully it doesn't count as `-` :) If it does (and the OP's comments suggest that it might), then please refer to [Ilmari Karonen's solution](https://codegolf.stackexchange.com/a/17526/7416) instead. For Y/N output, append `'NY'1/=` at the end (7 more bytes). [Answer] ## Python, 31 ``` print 3>bin(input()).rfind('1') ``` [Answer] # C, 48 ``` main(x){scanf("%i",&x);puts(x&~(x*~0)?"F":"T");} ``` [Answer] I decided to to use another approach, based on the [*population count*](http://en.wikipedia.org/wiki/Hamming_weight) or *sideways sum* of the number (the number of 1-bits). The idea is that all powers of two have exactly one `1` bit, and no other number does. I added a JavaScript version because I found it amusing, though it certainly won't win any golfing competition. ### J, ~~14~~ 15 chars (outputs 0 or 1) ``` 1=##~#:".1!:1]1 ``` ### JavaScript, 76 chars (outputs true or false) ``` alert((~~prompt()).toString(2).split("").map(Number).filter(Boolean).length) ``` [Answer] # [Clip](http://esolangs.org/wiki/Clip), ~~9~~ ~~8~~ 7 ``` !%lnxWO ``` Reads a number from stdin. Explanation: To start with, `Z` = `0`, `W` = `2` and `O` = 1. This allows placing of `W` and `O` next to each other, whereas using `2` and `1` would be interpreted as the number 21 without a separating space (an unwanted extra character). In Clip, the modulo function (`%`) works on non-integers, so, to work out if some value `v` is an integer, you check if `v` mod 1 = 0. Using Clip syntax, this is written as `=0%v1`. However, as booleans are stored as `1` (or anything else) and `0`, checking if something is equal to `0` is just 'not'ing it. For this, Clip has the `!` operator. In my code, `v` is `lnx2`. `x` is an input from stdin, `n` converts a string to a number and `lab` is log base `b` of `a`. The program therefore translates (more readably) to `0 = ((log base 2 of parseInt(readLine)) mod 1)`. Examples: ``` 8 ``` outputs ``` 1 ``` and ``` 10 ``` outputs ``` 0 ``` Edit 1: replaced `0`, `1` and `2` with `Z`, `O` and `W`. Edit 2: replaced `=Z` with `!`. Also: # [Pyth](http://esolangs.org/wiki/Pyth), 5 Compresses the Clip version even further, as Pyth has Q for already evaluated input and a log2(a) function instead of just general log(a, b). ``` !%lQ1 ``` [Answer] **Javascript (37)** ``` a=prompt();while(a>1)a/=2;alert(a==1) ``` Simple script that just divides by 2 repeatedly and checks the remainder. [Answer] # Mathematica (21) ``` IntegerQ@Log2@Input[] ``` Without input it is a bit shorter ``` IntegerQ@Log2[8] ``` > > True > > > ``` IntegerQ@Log2[7] ``` > > False > > > [Answer] ### Ruby — 17 characters (fourth try) ``` p /.1/!~'%b'%gets ``` My current best is a fusion of @steenslag's answer with my own. Below are my previous attempts. ### Ruby — 19 characters (third try) ``` p /10*1/!~'%b'%gets ``` ### Ruby — 22 characters (second try) ``` p !('%b'%gets)[/10*1/] ``` ### Ruby — 24 characters (first try) ``` p !!('%b'%gets=~/^10*$/) ``` [Answer] ## JavaScript, ~~41~~ 40 characters ``` l=Math.log;alert(l(prompt())/l(2)%1==0); ``` How this works: you take the logarithm at base 2 using `l(prompt()) / l(2)`, and if that result modulo 1 is equal to zero, then it is a power of 2. For example: after taking the logarithm of 8 on base `2`, you get `3`. `3 modulo 1` is equal to 0, so this returns true. After taking the logarithm of 7 on base 2, you get `2.807354922057604`. `2.807354922057604 modulo 1` is equal to `0.807354922057604`, so this returns false. [Answer] # JavaScript, 35 Works for bytes. ``` alert((+prompt()).toString(2)%9==1) ``` **46 character version**, Works for 16 bit numbers. ``` x=(+prompt()).toString(2)%99;alert(x==1|x==10) ``` The trick works in most dynamic languages. **Explanation:** Convert the number to base 2, interpret that string as base 10, do modulo 9 to get the digit sum, which must be 1. [Answer] ## Perl 5.10+, 13 + 1 = 14 chars ``` say!($_&$_/3) ``` Uses the same method [from an old FWP thread](http://www.bumppo.net/lists/fun-with-perl/2000/05/msg00065.html) as [my GolfScript entry](/a/17526). Prints `1` if the input is a power of two, and an empty line otherwise. Needs to be run with `perl -nE`; the `n` [costs one extra char](//meta.codegolf.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions), for a total of 14 chars. Alternatively, here's an **18-character** version that doesn't need the `n`: ``` say!(($_=<>)&$_/3) ``` [Answer] **python 3, 38** ``` print(1==bin(int(input())).count('1')) ``` **python, 32** However, the code doesn't work in every version. ``` print 1==bin(input()).count('1') ``` Notice that the solution works also for 0 (print False). [Answer] ## K/Kona (24 17) ``` d:{(+/(2_vs x))~1 ``` Returns 1 if true and 0 if false. Any power of 2 has a single bit equal to 1: ``` 2_vs'_(2^'(!10)) (,1 1 0 1 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0) ``` (this prints out all the powers of 2 (from 0 to 9) in binary) So I sum up all the components of the binary expression of `x` and see if it's equal to 1; if yes then `x=2^n`, otherwise nope. ...knew I could make it smaller [Answer] **C# (54 characters)** ``` Math.Log(int.Parse(Console.ReadLine()),2)%1==0?"Y":"N" ``` [Answer] # Rebmu (9 chars) ``` z?MOl2A 1 ``` **Test** ``` >> rebmu/args [z?MOl2A 1] 7 == false >> rebmu/args [z?MOl2A 1] 8 == true >> rebmu/args [z?MOl2A 1] 9 == false ``` [Rebmu](http://rebmu.hostilefork.com/) is a constricted dialect of Rebol. The code is essentially: ``` z? mo l2 a 1 ; zero? mod log-2 input 1 ``` **Alternative** *14 chars—Rebmu does not have a 'mushed' bitwise AND~* ``` z?AND~aTIddA 3 ``` In Rebol: ``` zero? a & to-integer a / 3 ``` [Answer] # OCaml - 42 or 45 Since no-one has submitted an OCaml solution, I submit one inspired by nightcrackers C solution. There is some debate as to whether the operator `-` includes unary negation. Other entries have managed to sidestep the issue by finding a solution that is equally short without unary negation. I instead give two answers: `let x=read_int()in 0=x land lnot(x* -1);;` and `let x=read_int()in 0=x land lnot(x*lnot 0);;` the `;;` ends a group of statements in the OCaml interpreter and causes the result to be printed as `- : bool = false` or `- : bool = true`, which are clear negative/positive answers as required by the question. [Answer] ## [GTB](http://timtechsoftware.com/gtb), 46 bytes ``` 2→P`N[@N=Pg;1P^2→P@P>1E90g;2]l;2~"NO"&l;1"YES" ``` [Answer] **Python, 35** ``` print bin(input()).strip('0')=='b1' ``` Doesn't use not only +/- operations, but any math operations aside from converting to binary form. Other stuff (interesting, but not for competition): I have also a **regexp version (61)**: ``` import re;print re.match(r'^0b10+$',bin(input())) is not None ``` (Love the idea, but import and match function make it too long) And nice, but boring **bitwise operations version (31)**: ``` x=input();print x and not x&~-x ``` (yes, it's shorter, but it uses ~-x for decrement which comtains - operation) [Answer] **Python 2.7 (~~30~~ ~~29~~ ~~39~~ 37)** EDIT: Updated due to user input requirement; ``` a=input() while a>1:a/=2. print a==1 ``` Brute force, try to divide until =1 (success) or <1 (fail) [Answer] # Python (33) ``` print int(bin(input())[3:]or 0)<1 ``` [Answer] # Ruby, ~~33~~, ~~28~~, 25 ``` p /.1/!~gets.to_i.to_s(2) ``` [Answer] # APL (12 for 0/1, 27 for yes/no) ``` ≠/A=2*0,ιA←⍞ ``` or, if we must output text: ``` 3↑(3x≠/A=2*0,ιA←⍞)↓'YESNO ' ``` Read in A. Form a vector 0..A, then a vector 20..2A (yes, that's way more than necessary), then a vector comparing A with each of those (resulting in a vector of 0's and at most one 1), then xor that (there's no xor operator in APL, but ≠ applied to booleans will act as one.) We now have 0 or 1. To get YES or NO: multiply the 0 or 1 by 3, drop this number of characters from 'YESNO ', then take the first 3 characters of this. [Answer] **C, 65 bytes** ``` main(k){scanf("%i",&k);while(k&&!(k%2))k/=2;puts(k==1?"T":"F");} ``` ]
[Question] [ A matrix is [antisymmetric](https://en.wikipedia.org/wiki/Skew-symmetric_matrix), or skew-symmetric, if its transpose equals its negative. The transpose of a matrix can be obtained by reflecting its elements across the main diagonal. Examples of transpositions can be seen here: \$\begin{pmatrix}11&12&13\\21&22&23\end{pmatrix}\rightarrow\begin{pmatrix}11&21\\12&22\\13&23\end{pmatrix}\$ \$\begin{pmatrix}11&12&13\\21&22&23\\31&32&33\end{pmatrix}\rightarrow\begin{pmatrix}11&21&31\\12&22&32\\13&23&33\end{pmatrix}\$ This matrix is antisymmetric because it equals its transpose when multiplied by -1: \$\begin{pmatrix}0&2&-1\\-2&0&0\\1&0&0\end{pmatrix}\$ All antisymmetric matrices exhibit certain characteristics: * Antisymmetry can only be found on square matrices, because otherwise the matrix and its transpose would be of different dimensions. * Elements which lie on the main diagonal must equal zero because they do not move and consequently must be their own negatives, and zero is the only number which satisfies \$x=-x\$. * The sum of two antisymmetric matrices is also antisymmetric. # The Challenge Given a square, non-empty matrix which contains only integers, check whether it is antisymmetric or not. # Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest program in bytes wins. * Input and output can assume whatever forms are most convenient as long as they are self-consistent (including output which is not truthy or falsy, or is truthy for non-antisymmetry and falsy for antisymmetry, etc). * Assume only valid input will be given. # Test Cases ``` In: 1 1 1 1 1 1 1 1 1 Out: False In: 0 0 1 0 0 0 -1 0 0 Out: True In: 0 -2 2 0 Out: True ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 3 [bytes](https://github.com/abrudz/SBCS) ``` -≡⍉ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X/dR58JHvZ3/0x61TXjU2/eoq/nQeuNHbRMf9U0NDnIGkiEensH/0xSALKAKYwXjR71bDLlQ@QYKBgqGCgZgeGg9mAVXYaRgBFZxaD2QpWAAAA "APL (Dyalog Unicode) – Try It Online") This is exactly an [APLcart entry](https://aplcart.info/?q=antisym#) on "antisymmetric". Basically it checks if the input's negative `-` matches `≡` the input's transpose `⍉`. [Answer] # [Python 2](https://docs.python.org/2/), 45 bytes ``` lambda A:A==[[-x for x in R]for R in zip(*A)] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUcHRytHWNjpat0IhLb9IoUIhM08hKBbEDAIxqzILNLQcNWP/FxRl5pUouCXmFKfqKKRpREcb6iiAUKwOlwIaIEYqVpOLC2JkSFEp0ESwkQoGOiCEVSNUzgCbnK4hVA5oKrKhIDOB4rpGmJqijYB2gjX8BwA "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), 23 bytes ``` function(m)!any(m+t(m)) ``` [Try it online!](https://tio.run/##K/qfpmD7P600L7kkMz9PI1dTMTGvUiNXuwTI1PyfppGbWFKUWaFhqKNgDESamlxwoWQNAx0FINI1BFMQZKiJQ6ERUKGRJpg2AhoMAA "R – Try It Online") Checks whether there are any non-zero elements in \$M+M^T\$. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes 5 bytes seems to be the right length for this (unless you're Jelly). Actually, this would be three bytes if Brachylog implicitly vectorized predicates like negation. ``` \ṅᵐ²? ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P@bhztaHWycc2mT//390tIGOkY5hrE50vJGOgY4BiGEIZsQCAA "Brachylog – Try It Online") ### Explanation ``` \ Transpose ṅᵐ² Map negation at depth 2 ? Assert that the result is the same as the input ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~67~~ 64 bytes -3 thanks to [AZTECCO](https://codegolf.stackexchange.com/questions/208982/antisymmetry-of-a-matrix/209002?noredirect=1#comment493066_209002) ``` i,j;f(m,s)int**m;{for(i=j=0;i=i?:s--;)j|=m[s][--i]+m[i][s];m=j;} ``` [Try it online!](https://tio.run/##bVHRasMgFH2OXyGBgkZlaftWJ/sQ50NIm3FDbUrNIFmWb8@upi0bDMTc6zmec7yp1UddLwvIVjfMy8Dh0heF11PT3RiY1pQaDLwdglKat9/G2@CsUuCEt@Cw0d60el58BRfGJ4LXaX8KfbCOGjqRvaTb@yKU/l8jp0xrPS/vLdZq@6h3cVe7RIg1mTVJEdEPYsjXAF@nrmHJnL/87mzpuOYYJovsiGC0FQEhnF7P8dVVj4CvzueuZpFWPDeUSoPhHNnoS5NxnA5tkzN@hUgeGcrY1plkIAD5GQiTOCSbSXa94dWG5eGwOUrqD@@XXEb0j/KAysMqPAghr599YHnOOX0yRmSMK2NEZ3R5CG/2x1zGEIOzo4uyT@QYzfA/V71Mc4jPmcm8/AA "C (gcc) – Try It Online") Returns `0` if the matrix is antisymmetric, and a nonzero value otherewise. [Answer] # [Octave](https://www.gnu.org/software/octave/), 19 bytes ``` @(a)isequal(a',-a); ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mG/PfQSNRM7M4tbA0MUcjUV1HN1HT@n9KZnGBRppGtKEOEFojkbGamlwwSQMdA6AwiDSw1jUEUaiyukbWRmCx/wA "Octave – Try It Online") The semicolon doesn't *need* to be there, but it outputs the function otherwise, so I'll take the one-byte hit to my score for now. # Explanation It's pretty straightforward - it checks to see if the matrix of the transpose is equal to the negative matrix [Answer] # JavaScript (ES6), 42 bytes Returns *false* for antisymmetric or *true* for non-antisymmetric. ``` m=>m.some((r,y)=>r.some((v,x)=>m[x][y]+v)) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/X1i5Xrzg/N1VDo0inUtPWrgjKK9OpAPJyoytioytjtcs0Nf8n5@cV5@ek6uXkp2ukaURzKShEKxjqgJFCrA5eLlespiYXNv0KBjogBNcB5RvA@LqGMD5OI4DSukYw9UY6CjDF/wE "JavaScript (Node.js) – Try It Online") [Answer] # [Io](http://iolanguage.org/), 67 bytes ``` method(~,~map(i,\,\map(I,V,V+x at(I)at(i)))flatten unique==list(0)) ``` [Try it online!](https://tio.run/##fY8/C8IwEMX3forbzOEVU62LUHDtIDpIpy5BUwy2aTUJOPWrx1gQ/xRK4HI/uPfunmp9BZsMSt9Ie2nPrKe@ER1TVFL5anIqqJg/QFiWYygKEataWCs1OK1uTmZZrYxlHNEvFnCUxsJJGGmgurcN7A9RVLFhIgIY/oTCQ5rEQIjQ3ZW2tR45ACf@rRmYfzhOBp424RQvP5IlwUgQ4mx37ur0WehVks4M2He6kVuc/p7Aaf2LYd1fLP8E "Io – Try It Online") ## Explanation For all `a[x][y]`, it checks whether all `a[x][y]+a[y][x]==0`. ``` method(~, // Input x. ~ map(i,\, // Map all x's rows (index i): \ map(I,V, // Foreach the rows (index I): V+x at(I)at(i) // x[i][I] + x[I][i] ) ) flatten // Flatten the resulting list unique // Uniquify the list ==list(0) // Does this resulting list *only* contain the item 0? ) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` qC_MM ``` [Try it online!](https://tio.run/##K6gsyfj/v9A53tf3///oaAMdBaNYHYVoXSMdBYPY2H/5BSWZ@XnF/3VTAA "Pyth – Try It Online") ## Explanation ``` qC_MM q : Check if input equals C : Transpose of _MM : Negated input ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` !_GX= ``` [Try it online!](https://tio.run/##y00syfn/XzHePcL2//9oQwUgtFZApmIB "MATL – Try It Online") ## Explanation ``` !_GX= // Implicit input on top of stack ! // Replace top stack element with its transpose _ // Replace top stack element with its negative G // Push input onto stack X= // Check for equality ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` eUy®n ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ZVV5rm4&input=W1sxLDAsMV0sClswLDAsMF0sClstMSwwLDFdXQ) ``` e compare input with : Uy columns of input ®n with each element negated ``` Previous version `ÕeËËn` didn't work, corrected using the ® symbol [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes ``` ⁼θEθEθ±§λκ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO1sDQxp1ijUEfBN7EAifJLTU8sSdVwLPHMS0mt0MjRUcjWBAPr//@jo6MNdBR0jWJ1uBQUoo10FAxiY2P/65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if the matrix is antisymmetric, nothing if not. Explanation: ``` Eθ Map over input matrix rows (should be columns, but it's square) Eθ Map over input matrix rows §λκ Cell of transpose ± Negated ⁼θ Does matrix equal its negated transpose? ``` [Answer] # [Wolfram Mathematica](https://www.wolfram.com/mathematica), ~~20~~, 7 bytes There is a [built-in function](https://reference.wolfram.com/language/ref/AntisymmetricMatrixQ.html) for this task: `AntisymmetricMatrixQ` But one can simply write a script with less byte counts: `#==-#ᵀ&` The `ᵀ` character, as it is displayed in notebooks, stands for transpose. But if you copy this into [tio](https://tio.run/), it won't be recognized because these characters are only supported by Mathematica notebooks. [Answer] # [Julia 1.0](http://julialang.org/), 9 bytes ``` A->A==-A' ``` A straightforward anonymous function checking the equality. [Try it online!](https://tio.run/##yyrNyUw0rPifWZyYV5JZXJmbm1pSlJls@99R187R1lbXUf2/Q3FGfrkCmgKNaEMFILRWQKZiNblwKDZQMACpAlEG1gq6hiAan2pdI2sFI5CS/wA "Julia 1.0 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` §=T†_ ``` [Try it online!](https://tio.run/##yygtzv7//9By25BHDQvi////Hx1toGOgYxirA6YNgLSuIZgRCwA "Husk – Try It Online") [Answer] # Google Sheets, ~~90~~ ~~88~~ 41 (Now with lambdas) Closing parens discounted. ## Named Functions (name, args, and formula text all count): | Name | args | Formula | | --- | --- | --- | | `P` | `a`, `b` | `a+b` | | `Q` | `a` | `MAP(a,TRANSPOSE(a),P)` | ## Formula: ``` =SUM(Q(A1:C3)) ``` No, I cannot currently use `ADD` instead of `P` as it is not a lambda. ## How it Works: Add the matrix to its transpose. If the resulting matrix is all 0's, then the sum of all elements is 0, which means we the two are equal. Return 0 if equal, some positive number otherwise. [Answer] # [Haskell](https://www.haskell.org/), 40 bytes ``` (==)<*>foldr(zipWith(:).map(0-))z z=[]:z ``` [Try it online!](https://tio.run/##XY2xDsIgEIZ3nuIGBzBggG6N@AbODshAVCyRq6TtxMOLtHEyl8v333eX3ODn1yOlGsy1UmPYcX8K73SfaIn5EpeB9uyAPlMpGCukGOv6UlGBAWsVb@X4Hx1Bva0ll5teKRuF2oIDgt3vQOjm9SoJ@jg2236dIU9xXGC3DhDAouKAunXn6ucWkn/OVdxy/gI "Haskell – Try It Online") Uses [this tip for shorter transpose](https://codegolf.stackexchange.com/a/111362/20260) and the idiom of `(==)<*>` to check invariance under an operation. [Answer] # [Haskell](https://www.haskell.org/), ~~49~~ 47 bytes ``` import Data.List f x=x==transpose(map(0-)<$>x) ``` [Try it online!](https://tio.run/##HcYxDoAgDADA3Vd0cNAEDO7i5OgPCEMHjY2CBDrw@2qY7i4s9/E8IhTSmxk2ZJx2KgzdCdVWazljLOktxxAwDUaPS7/WUQJSBAspU2To4XTOKKNmr5rmV88tHuQD "Haskell – Try It Online") * saved 2 thanks to @Unrelated String My first Haskell. Function tacking a matrix and checking if input is equal to input mapped to (0-value) and transposed [Answer] # Scala, 32 bytes ``` l=>l.transpose==l.map(_.map(-_)) ``` Finally, something that Scala has a builtin for! The function's pretty straightforward - it compares the transpose of a `List[List[Int]]`(doesn't have to be a `List`, could be any Iterable) to the negative, found by mapping each list inside `l` and using `-` to make it negative. [Try it in Scastie](https://scastie.scala-lang.org/oIWhqnLcRhaTGOgoR4HV2Q) [Answer] # [Ruby 2.7](https://www.ruby-lang.org/en/), 40 bytes ``` ->a{a==a.transpose.map{|r|r.map{|c|-c}}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6xOtHWNlGvpCgxr7ggvzhVLzexoLqmqKYIwkiu0U2ura39X6CQFh0dbagDhLE6aHRsLBdE2kDHACwMog2AtK4hmIEkr2sEFDYCi/0HAA) [Answer] # [Pip](https://github.com/dloscutoff/pip), 5 bytes ``` Z_=-_ ``` A function submission; pass a nested list as its argument. [Try it online!](https://tio.run/##K8gs@K/xPyreVjf@f3S0gbWCkbVhLJdCtK6RtYG1AZhlCGbFcmn@BwA "Pip – Try It Online") ### Explanation ``` Z_ The argument, zipped together = Equals -_ The argument, negated ``` [Answer] # [gorbitsa](https://esolangs.org/wiki/GORBITSA)-ROM, 8 bytes ``` r1 R A1 B0 T ``` This is an awful abuse of rule > > Input and output can assume whatever forms are most convenient. > > > If input takes form of "arr[i][j] arr[j][i]", the problem becomes "is sum = 0?". This code takes pairs of values and outputs their sum if it's not 0 Thus if you provide matrix as previously mentioned pairs, code will return some value for not-anti-symmetric ones and will not return anything for anti-symmetric ones. ``` r1 R A1 B0 T r1 #store first number R #read second number A1 #add first number B0 #if sum==0, jump to the beginning T #else output the sum ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` N⁼Z ``` [Try it online!](https://tio.run/##y0rNyan8/9/vUeOeqP///0dHG@gY6BjG6oBpAyCtawhmxAIA "Jelly – Try It Online") Posting before caird coinheringaahing finds this question. [Answer] # [Java (JDK)](http://jdk.java.net/), ~~89~~ ~~87~~ 86 bytes * -2 bytes thanks to Calculuswhiz! ``` m->{int i=0,j,r=1;for(;++i<m.length;)for(j=0;++j<i;)r=m[i][j]!=-m[j][i]?0:r;return r;} ``` [Try it online!](https://tio.run/##jZJBb4JAEIXv/oqpJ0hhgx5dsWnaNOmhJ4@Ew4qLXQoL2R1MreG301G2YhPTlJDM8ob35c1AIfYiLLYffVYKa@FNKA3HCYBFgSqDgtqsRVWyvNUZqlqzF3dYKo1JmqQBvGqUO2lWkEPcV@HqSB1QcRQUgYlnPK@Nx@/v1bJipdQ7fOf@SSriiNRiqbhv4ipRaVKkd3FYUaGHh2hhuJHYGg2Gdz2fUKim3ZQUymXb12oLFQX21miU3iUpZGqvSvUlt89yI1Ba/zwLgIsKJOGTsNLSOXY9uFQ4zgI43V3wD8UJl85IiQKIfnsGJbpSwpmT/sTMrx3za8Lg6/i50DrB@5mxErSNT1iMw/oX6PpgUVasbpE1tDIstTcNb1xTnzvHiAZhDFEHvH8LNf4sj8aIg2VYD1/GI6t/Qd5w5kw0TXnwHNy9epqxm3T9Nw "Java (JDK) – Try It Online") Returns 0 for `false` and 1 for `true`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ø(Q ``` [Try it online](https://tio.run/##yy9OTMpM/f//8A6NwP//o6MNdIx0dA1jdaJ1jXQMdAyADEMwHQsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU3loudG5LVmHdutwKfmXlkBE7Std/h/eoRH4X@fQNvv/0dHRBjpGOrqGsTrRukY6BjoGQIYhmAYygCwgBIsg0yAZoAqwiAFUjy5Ck4GOrhGQNgJxYwE). **Explanation:** ``` ø # Zip/transpose the (implicit) input-matrix; swapping rows/columns ( # Negate each value in this transposed matrix Q # And check if it's equal to the (implicit) input-matrix # (after which the result is output implicitly) ``` [Answer] # [Factor](https://factorcode.org/) + `math.matrices`, 19 bytes ``` [ dup flip mneg = ] ``` [Try it online!](https://tio.run/##bY6xCsIwFEX3fMX9gZa0oyK4iYuLOIlDia8aTGP6kg5S/PYYY7rJhcs7nDu8vlPhyfF03B92KzyILRl4GieyijyGLtzrVKy/5JhCeDnWNmAtxIwZTc5b4P@dKM8gUxaXQRaomh8sS4mqLapFEfGM6@TQG@0wWLphg0tMP21ReyhDHccP "Factor – Try It Online") * `dup` make a copy of the input * `flip` transpose it * `mneg` negate it * `=` are they equal? [Answer] # [Raku](https://raku.org/), 26 bytes ``` {none flat $_ »+«[Z] $_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Oi8/L1UhLSexREElXuHQbu1Dq6OjYoHs2v/FiZUKSirxeumZxSUamgq2dgrV9mkgGSWFtPwiBQ0NQx0g1NRBo4EMDQMdA7AIiDYA0rqGYAZEStcISBuBuP8B "Perl 6 – Try It Online") * `$_` is the input matrix, in the form of a list of lists of integers. * `[Z] $_` is the transpose of the input matrix. * `»+«` adds the input matrix to its transpose. * `flat` flattens the matrix into a single list of numbers. * `none` converts that list of numbers into a junction which is true if and only if none of the numbers is truthy, that is, nonzero. The none-junction is returned. It is truthy only if adding the matrix to its transpose results in a matrix containing all zeroes. [Answer] # [J-uby](https://github.com/cyoce/J-uby), 28 bytes Port of [Razetime's Ruby answer](https://codegolf.stackexchange.com/a/208998/11261). ``` :=~&(:transpose|:*&(:*&:-@)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWe6xs69Q0rEqKEvOKC_KLU2ustIBcLTUrXQdNTYiSm0EFCm7R0dGGOkAYq4NGx8ZyQaQNdAzAwiDaAEjrGoIZSPK6RkBhI7AYxOQFCyA0AA) ## Explanation ``` :=~ & (:transpose | :* & (:* & :-@)) :transpose | # Transpose input, then :* & ( ) # Map with :* & :-@ # Map with negate :=~ & ( ) # Equal to input ``` [Answer] # k, 7 bytes Similar to the APL solution. Compare (x~) original matrix against negated transpose (-+x} ``` {x~-+x} ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 3 bytes ``` Ť_= ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6FkuOLom3XVKclFwMFVhw0zk62lAHCGN10OhYruhoAx0DsAiINgDSuoZgBkRK1wgoYgTiQswCAA) ``` Ť Transpose _ Negate = Check equality ``` ]
[Question] [ ## Challenge Weirdly, this hasn't been done yet: output the current date. ## Rules The date format you should follow is as follows: ``` YYYY-MM-DD ``` Where the month and day should be padded by zeroes if they are less than 10. For example, if the program is run on the 24th May 2017, it should output ``` 2017-05-24 ``` The date can either be always in UTC or in the local date. You must handle leaps years. i.e. in leap years, February has 29 days but 28 days in a normal year. ## Winning Shortest code in bytes wins. [Answer] # [Bash](https://tio.run/nexus/bash#@5@SWJKqoK3q9v8/AA) with [GNU coreutils](https://www.gnu.org/software/coreutils/), ~~16~~ 7 bytes -8 bytes thanks to Neil (and fergusq) (no pipe required to output) -1 byte thanks to 12431234123412341234123 (use the built-in option with flag `-I`!) ``` date -I ``` **[Try it online!](https://tio.run/nexus/bash#@5@SWJKqoOv5//9/AA)** [Answer] # PHP, 17 bytes ``` <?=date('Y-m-d'); ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 bytes ``` Ks3 ¯A ``` [Try it online!](https://tio.run/nexus/japt#@@9dbKxwaL3j//8A "Japt – TIO Nexus") ## Explanation: ``` Ks3 ¯A K // New Date() s3 // .toISOString() ¯A // .slice(0,10) ``` [Answer] # Bash, 15 bytes ``` printf '%(%F)T' ``` Sample run: ``` bash-4.4$ printf '%(%F)T' 2017-05-24 ``` [Try it online!](https://tio.run/nexus/bash#@19QlJlXkqagrqqh6qYZov7/PwA "Bash – TIO Nexus") [Answer] ## JavaScript (ES6), 34 bytes ``` _=>new Date().toJSON().split`T`[0] ``` ``` f= _=>new Date().toJSON().split`T`[0] console.log(f()); ``` [Answer] # SQLite, 13 characters ``` select date() ``` Good boy, SQLite. Other SQL dialects usually need either `current_date` or `date(now())`. Sample run: ``` bash-4.4$ sqlite3 <<< 'select date()' 2017-05-24 ``` [Answer] ## Mathematica, 20 bytes ``` DateString@"ISODate" ``` [Answer] # [Perl 6](https://perl6.org), ~~14~~ 12 bytes ``` Date.today.say ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u2/u@SWJKqV5KfklipV5xY@f//17x83eTE5IxUAA "Perl 6 – TIO Nexus") ``` now.Date.say ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u2/p@XX67nkliSqlecWPn//9e8fN3kxOSMVAA "Perl 6 – TIO Nexus") [Answer] # Excel, 24 bytes ``` =TEXT(NOW(),"yyy-mm-dd") ``` Excel will still do a 4-digit year with only 3 `y`'s. [Answer] # [R](https://www.r-project.org/), 10 bytes ``` Sys.Date() ``` [Try it online!](https://tio.run/nexus/r#@x9cWaznkliSqqH5/z8A "R – TIO Nexus") [Answer] # jq, 19 characters (15 characters code + 4 characters command line options) ``` now|todate[:10] ``` Sample run: ``` bash-4.4$ jq -nr 'now|todate[:10]' 2017-05-24 ``` [Try in jq‣play](https://jqplay.org/s/TtdTTXsPIO) [Answer] # Lua, 18 characters ``` print(os.date"%F") ``` Sample run: ``` bash-4.4$ lua -e 'print(os.date"%F")' 2017-05-24 ``` [Try it online!](https://tio.run/nexus/lua#@19QlJlXopFfrJeSWJKqpOqmpPn/PwA "Lua – TIO Nexus") [Answer] ## [Alice](https://github.com/m-ender/alice), 9 bytes ``` /oT\ @%;' ``` [Try it online!](https://tio.run/nexus/alice#@6@fHxLD5aBqrf7/PwA "Alice – TIO Nexus") ### Explanation I'll leave the exact control flow as an exercise to the reader, but the linearised code that is being run in Ordinal mode is: ``` %T'T%;o@ ``` And here is what it does: ``` % Split an implicit empty string around an implicit empty string. Really doesn't do anything at all. T Push the current datetime as a string like "2017-05-24T20:53:08.150+00:00" 'T Push "T". % Split the datetime string around the "T", to separate the date from the time. ; Discard the time. o Output the date. @ Terminate the program. ``` One way this might be golfable is to reuse the `%` to terminate the program in Cardinal mode with a division by zero, but the only layout I've come up with is the following: ``` \;T \%o' ``` But here, the `%` doesn't actually terminate the program, because we push 111 (`'o`) right beforehand so there's never a division by zero. In principle it might also be possible to reuse `%` to get rid of the `;`, since trying to split the date around the time will simply discard the time. [Answer] # SmileBASIC 3, 29 bytes SB has a date string built in... but it's in the wrong format! It uses slashes instead of dashes, no good. Plus, being the self-respecting BASIC it is, there is no global replace function. I guess I have to do it myself... ``` D$=DATE$D$[4]="- D$[7]="- ?D$ ``` [Answer] # Java 8, ~~26~~ 32 bytes ``` ()->java.time.LocalDate.now()+"" ``` Fixed format thanks to Kevin Cruijssen [Answer] # VBA, 5 25 bytes `?Date` *unpredictable, dependent on system short date settings* ``` ?Format(Now,"yyyy-mm-dd") ``` ### Output: ``` 2017-05-25 ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 46 bytes ``` f(X):-get_time(Y),format_time(atom(X),'%F',Y). ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P00jQtNKNz21JL4kMzdVI1JTRyEtvyg3EcpPLMnPBarQUVBXdVPXUYjU1INo0QMA "Prolog (SWI) – Try It Online") [Answer] # Pyth, 19 bytes `++++.d3"-".d4"-".d5` In Pyth `.` allows you to access a number of extra syntactic goodies. `d` contains various date options which are accessed with `.d#`, where `#` is a number 0-9. `3` is for the current year, `4` is the current month, and `5` is for the current day. Format for the challenge wants dashes between each element of the date so we append them. Pyth using Polish notation for all math operands, thus the `++++`. [Answer] # [Factor](https://factorcode.org/), 21 bytes ``` [ now timestamp>ymd ] ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjkJyYk5qXklgEZ@il5RflJpYoZOYrWP@PVsjLL1coycxNLS5JzC2wq8xNUYj9D1Sao1BQlJlX8h8A "Factor – Try It Online") [Answer] # x86-16 machine code, IBM PC DOS, ~~55~~ ~~53~~ 48 bytes Binary: ``` 00000000: b42a cd21 91b3 64f6 f38b c8e8 1400 8ac5 .*.!..d......... 00000010: e80f 00b0 2dcd 298a c6e8 0600 b02d cd29 ....-.)......-.) 00000020: 8ac2 d40a 0530 3050 86c4 cd29 58cd 29c3 .....00P...)X.). ``` Listing: ``` B4 2A MOV AH, 2AH ; get system date: CX=year, DH=month, DL=day CD 21 INT 21H ; call DOS API 91 XCHG AX, CX ; move year in CX to AX (dividend) B3 64 MOV BL, 100 ; divide by 100 to separate digits of year F6 F3 DIV BL ; AL = first two digits, AH = last two digits 8B C8 MOV CX, AX ; save AX to CX to display last two digits later E8 0122 CALL DISP_WORD ; display decimal value in AL 8A C5 MOV AL, CH ; move last two digits to AL E8 0122 CALL DISP_WORD ; display decimal value in AL B0 2D MOV AL, '-' ; date separator CD 29 INT 29H ; fast write AL to screen 8A C6 MOV AL, DH ; move month in DH into AL for display E8 0122 CALL DISP_WORD ; display decimal value in AL B0 2D MOV AL, '-' ; date separator CD 29 INT 29H ; fast write AL to screen 8A C2 MOV AL, DL ; move day into AL and display DISP_WORD: D4 0A AAM ; convert binary to BCD 05 3030 ADD AX, '00' ; convert BCD to ASCII char 50 PUSH AX ; save second digit for display later 86 C4 XCHG AL, AH ; convert endian, AL = first digit, AH = second digit CD 29 INT 29H ; fast write AL to screen 58 POP AX ; restore digits CD 29 INT 29H ; fast write AL to screen C3 RET ; return to caller/DOS ``` ***Output*** Standalone DOS program, run from the command line outputs current date to the screen. [![enter image description here](https://i.stack.imgur.com/Csg39.png)](https://i.stack.imgur.com/Csg39.png) Much of this program is converting binary values to ASCII for console output. This uses (abuses) the binary-to-BCD instruction (`AAM`) to create a printable ASCII version of the output. [Answer] # TI-Basic, 72 bytes ``` getDate→A toString(Ans(1→B toString(ʟA(2→C toString(ʟA(3→D If C<10 "0"+C→C If D<10 "0"+D→D B+"-"+C+"-"+D ``` This only works on a TI-84+ CE OS 5.2 and if the user has already set the time and date correctly. [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 33 bytes ``` B=_D?_sB,-4|+@-`+_sB,2|+A+_sB,4,2 ``` Explanation: ``` B=_D Assign the system's date to B$ This is in American mm-dd-yyyy format, so we'll need to do some reformatting ?_sB,-4| PRINT substring B, take 4 chars from the right +@-` plus the string literal "-", now A$ +_sB,2| plus the leftmost two chars +A and A$ again +_sB,4,2 plus the middle part. ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~22~~ 15 bytes ``` et3<{sY0e[}%'-* ``` [Try it online!](https://tio.run/nexus/cjam#@59aYmxTXRxpkBpdq6quq/X/PwA "CJam – TIO Nexus") -7 bytes thanks to Challenger5. Explanation: ``` et Get array with [year,month,day,stuff...] 3< Slice array to get [y,m,d] { For each item do: s To string Y0e[ add a 0 to the beginning of the string if it is shorter than 2 chars. }% End for each '-* Join the array with "-" as a separator ``` [Answer] # Python 2, 40 bytes ``` from datetime import*;print date.today() ``` [Answer] # [Go](https://golang.org/), ~~62~~ 56 bytes ``` import."time" func f()string{return Now().String()[:10]} ``` [Try it online!](https://tio.run/nexus/go#K0hMzk5MT1XITczM48rMLcgvKtFTSsstUfoP45Rk5qYqcaWV5iUrpGloFpcUZealVxellpQW5Sn45ZdraOoFg8U0NKOtDA1ia/@DlYLM09Cs5lIAggCgdIkGULMmV@1/AA "Go – TIO Nexus") [Answer] # Oracle SQL, 46 bytes ``` SELECT TO_CHAR(SYSDATE,'YYYY-MM-DD') FROM DUAL ``` [Answer] # Powershell, ~~26~~ 17 bytes ``` Date -f yyy-MM-dd ``` Thanks to @ConnorLSW for the 9 bytes. [Answer] # Ruby, 23 bytes Prints the local time. ``` p Time.now.strftime'%F' ``` [Answer] # MATLAB/[Octave](https://www.gnu.org/software/octave/), ~~25~~ 15 bytes ``` datestr(now,29) ``` [Try it online!](https://tio.run/nexus/octave#@5@SWJJaXFKkkZdfrmNkqfn/PwA "Octave – TIO Nexus") --- The built-in function `now` returns the current system date in a weirdy MATLAB serial format. `datestr` formats the weirdy serial format into a string of a requested format - which is in this case `'YYYY-mm-dd'`. It turns out that MATLAB has a list of predefined formats for `datestr`. ISO8601 is one of them and is represented by the number 29, which allows a saving of 10 bytes. [Answer] # [Python 2](https://docs.python.org/2/), ~~53~~ 40 bytes -10 bytes thanks to Gábor Fekete (ISO-8601 is the default format for a date object) ``` from datetime import* print date.today() ``` **[Try it online!](https://tio.run/nexus/python2#@59WlJ@rkJJYklqSmZuqkJlbkF9UosVVUJSZVwIW1ivJT0ms1ND8/x8A)** ### How? `datetime.date.today()` will return a `datetime.date` object containing the local date information. `print` will print a string representation of that object, this will call the object's `__str__` function. From the [docs](https://docs.python.org/2/library/datetime.html): * `date.__str__()`: For a `date` `d`, `str(d)` is equivalent to `d.isoformat()`. * `date.isoformat()`: Return a `string` representing the date in **ISO 8601** format, `‘YYYY-MM-DD’`. For example, `date(2002, 12, 4).isoformat() == '2002-12-04'`. ]
[Question] [ mbomb007 asked us to make a [self mutilating program](https://codegolf.stackexchange.com/questions/60003/self-mutilating-program). Its an interesting challenge, but I personally don't like to encourage my programs to be self-mutilating. I like to think that, at the heart of every program is a beautiful butterfly waiting to break out. As such, for my first ever Code Golf challenge, I challenge Stack Exchange to metamorph a butterfly. Your program should accept its own code as input and output `I am a caterpillar!` followed by the code for another program in the same language (you may put a divider between the outputs or not... but we're talking butterflies, so prettiness counts!). This second program should output `I am a beautiful butterfly!` Metamorphosis: This program should modify itself, which is why it is being passed itself as input. I don't want a boring nested program that is nothing but a print statement `I am a caterpillar!` followed by printing source code. You have to metamorph the code itself, so the most boring acceptable answer is one which prints `I am a caterpillar`, then rips a string out of the input (which happens to be code) and prints that. Of course, this is a very tricky little requirement to write, so it should be thought of as a "spirit of the challenge." The formal requirement is going to be set at "If your program is given a random string of the same length as your program, there should be less than a 5% chance of printing `I am a butterfly` when the second program is run." Summary: * Write a program which, when provided its own code as input, prints `I am a caterpillar!` followed by a block of source code (with a delimiter between them or not). * This second block of source code, when compiled/interpreted as the same language, prints `I am a beautiful butterfly!` * If your program is not fed its own source code as input, and is instead given a random string of characters that does not match its own code, the result must either fail to compile/interpret, or not print `I am a butterfly!` for at least 95% of random strings (spirit: you are expected to read your own source code from the input, and stitch it together into a butterfly). + *I'm comfortable with you not proving this, so long as you're holding to the spirit of the metamorphosis idea, modifying your own code, but if you're trying to play loophole games to work around using your inputs, expect to have to prove it.* * Standard loopholes apply I'd like these to be judged by their beauty, but that's a decidedly non-quantitative approach, so the usual "number of bytes" route can be used to judge **Bonus**: -20% - pick any 3 letter string that doesn't match the first 3 letters of your program. If I run the caterpillar program, but modify the input so that the first 3 character are changed to the specified ones, print `I am Batman!` instead. Always be Batman. (*Same random string rules apply for this... metamorphosis!*) Trivial example (python): ``` """ print "I am a beautiful butterfly!" #print "I am Batman!" """ import sys code = sys.stdin.read() if code.startswith("YYZ"): # swap the comments between the print statements code = code.replace("#print", "_a").replace("print", "#print").replace("_a", "print") code = [3:] # remove """ or XYZ code = code.split('"""')[0] print "I am a caterpillar!" print code ``` [Answer] # Befunge-98, 602 bytes ``` "^@<"v@@ "'I'"00v>00g:: "@v"0v@@@>g::a">#" "a">v@@> 0g::'"1> / ":\"'"v@> 'm'"00g:a >"@v$" "lufituaeb"'"'v00ga"@v\"'":'b\00v@> :'a\":*84>"00ga"\>@@@@_,#:>"00g:a'<'" "et"'"'va'v'":'l\00g5k:'""y!">>v@> g::'''""ut"'"'>a'<'""fr"'"00g3k:'"> "ma"00g>'I~48*-~48*-+#@_>:#,_@> '"aa"---"aa"!rallipretac"00g:'a\ ``` Tested in PyFunge. When run with a string not starting with 2 spaces (probability well over 95% when random) outputs nothing. This isn't exactly what the OP is looking for, but fits the specification. When passed a string starting with 2 spaces (like itself) outputs this: ``` I am a caterpillar! --- "!y" "l"v v"te" "rf"< >"tu"' "b"\v@ v"beautiful"< >:#,_@@@@>\ >48*:"a"\:$v@ "ma" v@#> 'I' <@^ ``` The lower part of that, in turn, outputs: ``` I am a beautiful butterfly! ``` [Answer] # PHP, 74 Bytes ``` <?=~¶ßž’ßžß,$s="caterpillar!",strtr($argv[1],[$s=>~šžŠ‹–™Š“ߊ‹‹š™“†Þ]); ``` * `<?=` is equivalent to `<?php echo` and can take several comma separated values to output * `¶ßž’ßžß` and `šžŠ‹–™Š“ߊ‹‹š™“†Þ` are valid constant names in PHP, but because the constants do not exist are treated as string literal. `~` inverts them to `"I am a "` and `"beautiful butterfly!"` (saving a byte for one quotation mark each) * `strtr` replaces "caterpillar!" with "a beautiful butterfly!" in the argument [Answer] # Pyth, ~~50~~ 46 bytes ``` "I am a caterpillar!"+<z8"beautiful butterfly! ``` ## Explanation ``` "I am a caterpillar!" print "I am a caterpillar!" z<8 first 8 chars of input + "beautiful butterfly! add "beautiful butterfly!" to that and print ``` The resulting source code is ``` "I am a beautiful butterfly! ``` Which basically prints the text. [Answer] # Perl 6, ~~60~~ 56 bytes ``` say "I am a caterpillar!"; s/\S+\!/beautiful butterfly!/ ``` Requires -p to run properly; I have accounted for this in the byte count. Sadly one of the downsides to Perl 6 is that the syntax is much more strict now... [Answer] # Retina, 53 bytes ``` caterpillar beautiful butterfly ^ I am a caterpillar! ``` **Prints out:** ``` I am a caterpillar!beautiful butterfly beautiful butterfly ^ I am a beautiful butterfly! ``` Notice that there is no separator between `I am a caterpillar!` and the new program. The new program expects no input. [Answer] # `bash` / `awk` / `cksum` - ~~179.2~~ ~~169.6~~ 168 bytes ``` awk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."!NF"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0}' ``` Demo: ``` $ awk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."!NF"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0}'<<'E' > awk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."!NF"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0}' > E I am a caterpillar! echo|awk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."10"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0}' $ echo|awk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."10"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0}' I am a beautiful butterfly! # Batman! $ awk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."!NF"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0}'<<'E' > xyzawk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."!NF"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0}' > E I am Batman! # Invalid input $ awk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."!NF"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0}'<<'E' > awk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."!NF"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0{' > E ``` I hope the 20% applies for *any* string starting with `xyz`, otherwise the original count is ~~224~~ ~~212~~ 210 bytes (fixed the `"I am Batman!"` part). Transformation done: replaces the only occurrence of the literal `!NF` with `10`, so that `" butterfly"` is [also printed using the `printf`](https://www.gnu.org/software/gawk/manual/html_node/Format-Modifiers.html). Performs a simple `cksum` on a portion (i.e. the remainder) of the source code, hence its requirement as well. ~~Caveat: first input must end with `'`.~~ Not so much a caveat as to suppress *wrong* input... No second input is expected. [Answer] # Python - 184 bytes -20% for bonus = 147.2 ``` """""" import sys;c=sys.stdin.read();print"I am a caterpillar!";x=c[3:] if"\'''"!=c[:3] else c print x+c[:3] """;print"I am a beautiful butterfly!" """ ''';print"I am Batman";''' ``` To print `I am batman`, replace the first three double quotes with single quotes in the input.(First line is `'''"""`) [Answer] # [FMSLogo](https://fmslogo.sourceforge.io/manual), 169.6 bytes from 212 \* 0.8 ``` to f[:b]1 type[I am]type char 32 ifelse name? "b[make "b last :b print[a caterpillar!;beautiful butterfly ](foreach[23 8 19 2][10 32 13 97][repeat ?2[ignore pop "b]repeat ?1[type pop "b]])][print[Batman!]]print " ``` The online logo interpreters I know of do not support every logo feature this program is using. [calormen.com](https://www.calormen.com/jslogo/#), for example, does not support anonymous functions. The program works on FMSLogo 8.3.2. Luckily for readability, the newlines are either necessary or have no cost. The program, in caterpillar form, is a variadic function which defaults to 1 argument. Pass the program code to it by pasting it between the bars in `f "||`. It will print "I am a caterpillar!", then splice together the output program from its own parts character by character by popping from the string. It will output this: ``` type[I am]type char 32 print[a beautiful butterfly!] ``` I should change the `type char 32` part, but then the splicing code will look less epic. In Batman form, achieved by replacing `to` with `;` , thereby commenting out the function header, the Program will run when you load the file, and obviously not take input. For me, non-declarative code pasted into the edit window runs twice, but loading it as a file will still make it run once. To decide whether it is Batman, the program checks whether the input variable exists. [Answer] # [morsecco](https://codegolf.meta.stackexchange.com/a/26119/72726): ~~190~~ 193 bytes Morsecco itself ignores those boring strings without any dots or dashes, but if you provide it as input, why not use it and modify it? ``` I am a caterpillar!beautiful butterfly!. .-. - - . - .-. -... -.. --.. --.- --.- -.-. -..-- - - --- -.-. --- - .. -.-. -.-.. - .-. -.-. . . . - . -.- .- -.-. .... . -.- - --- -.-. ... --- ``` * `. .-. - - . - .-.` to `R`ead the own source code and stdin * `-... -.. --.. --.- --.-` for a `B`inary `D`iff and to `Z`eroskip the `Q`uit if it's identical * `-.-. -..-- - - ---` `C`uts the caterpillar string, keeps a copy and `O`utputs it * `-.-. --- - .. -.-. -.-.. - .-. -.-. .` gets rid of the caterpillar and sets in the butterfly * `. . - . -.- .- -.-. ....` `K`onverts from `·T`ext to hide the butterfly in the caterpillar * `. -.- - --- -.-. ... ---` finally `C`oncatenates the code for butterfly `O`utput and put this code `O`ut. Other languages may need to do some ASCII art now, but the output of the code (if given the correct source, otherwise silently quit) will be: ``` I am a caterpillar! . -..-..- -..... --....- --.--.- -..... --....- -..... --...-. --..-.- --....- ---.-.- ---.-.. --.-..- --..--. ---.-.- --.--.. -..... --...-. ---.-.- ---.-.. ---.-.. --..-.- ---..-. --..--. --.--.. ----..- -....- -.- - --- ``` and honestly: It looks a little like crawling caterpillars anyhow! Maybe like a millipede, but you wouldn't expect this to turn into a butterfly, wouldn't you? But execute it with morsecco and be surprised about the metamorphosis! ]
[Question] [ # Introduction The *[telephone numbers](https://en.wikipedia.org/wiki/Telephone_number_(mathematics))* or *involution numbers* are a sequence of integers that count the ways \$n\$ telephone lines can be connected to each other, where each line can be connected to at most one other line. These were first studied by Heinrich August Rothe in 1800, when he gave a recurrence equation where they may be calculated. It is sequence [A000085](https://oeis.org/A000085) in the OEIS. ## Some help * The first terms of the sequence are \$1, 1, 2, 4, 10, 26, 76, 232, 764, 2620, 9496\$ * It can be described by the recurrence relation \$T(n)=T(n-1)+(n-1)T(n-2)\$ (starting from \$n=0\$) * It can be expressed exactly by the summation \$T(n)=\sum\limits\_{k=0}^{\lfloor n/2 \rfloor}{n\choose 2k}(2k-1)!!=\sum\limits\_{k=0}^{\lfloor n/2 \rfloor}\frac{n!}{2^k(n-2k)!k!}\$ (starting from \$n=0\$) * There are other ways to get the telephone numbers which can be found on the [Wikipedia](https://en.wikipedia.org/wiki/Telephone_number_(mathematics)) and [OEIS](https://oeis.org/A000085) pages # Challenge Write a program or function which returns the \$n^{th}\$ telephone number. # I/O examples ``` (0 based indexing) input --> output 0 --> 1 10 --> 9496 16 --> 46206736 22 --> 618884638912 ``` # Rules * Input will be the index of the sequence * The index origin can be anything * As the numbers can get very large, you only need to support numbers as large as your language can handle * [Standard I/O](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) rules apply * No [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins [Answer] # [Python](https://docs.python.org/3/), 33 bytes ``` f=lambda n:n<2or~-n*f(n-2)+f(n-1) ``` [Try it online!](https://tio.run/##FcXBCoMwDADQ@74ieGq2FtYMPRTtvygjKGyplFxE6q9XfZe3bjon@dTKw2/8T98RJEhPKR9OnmzEEb7uPFZOGRQWAfO23rbWX3WWCMMD1ryIGm52DT0VcC7CzkYxRE@lwXoC "Python 3 – Try It Online") Uses the recursive formula. [Answer] # [Oasis](https://github.com/Adriandmen/Oasis), ~~7~~ ~~6~~ 5 bytes ``` àn*+1 ``` [Try it online!](https://tio.run/##y08sziz@///wgjwtbcP///8bGvzX9QcA "Oasis – Try It Online") ``` # to compute the nth telephone number f(n): à # push the telephone numbers f(n-1) and f(n-2) n # push n * # multiply: n * f(n-2) + # add: n * f(n-2) + f(n-1) 1 # base case: f(0) = 1 ``` [Answer] # [cQuents](https://github.com/stestoltz/cQuents), 10 bytes ``` =1:Z+Y($-2 ``` 1-indexed. [Try it online!](https://tio.run/##Sy4sTc0rKf7/39bQKko7UkNF1@j/fwA "cQuents – Try It Online") ## Explanation ``` =1 first term in sequence is 1 : given n, output nth term in sequence (1-indexed) each term is Z+ (n-1) term + Y (n-2) term * ($-2 (index - 2) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Œ!ỤƑ€S ``` A monadic Link accepting a non-negative integer which yields a positive integer. **[Try it online!](https://tio.run/##y0rNyan8///oJMWHu5ccm/ioaU3w////LQE "Jelly – Try It Online")** Or see the [first 10](https://tio.run/##y0rNyan8///oJMWHu5ccm/ioaU3w/6O7j@453A5kqrj//28JAA "Jelly – Try It Online") (`n=10` is too slow) ### How? Builds all permutations of `[1...n]` (or if `n=0` just `[[]]`) and counts the number which are involutions. ``` Œ!ỤƑ€S - Link: integer, n e.g. 0 3 Œ! - all permutations [[]] [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] € - for each: Ƒ - is invariant under: Ụ - grade ( [] [1,2,3] [1,3,2] [2,1,3] [3,1,2] [2,3,1] [3,2,1] ) - } [1] [1, 1, 1, 0, 0, 1] S - sum 1 4 ``` [Answer] # TI-BASIC, ~~28~~ 22 bytes ``` ∑((Ans nCr (2K))(2K)!/(2^KK!),K,0,int(.5Ans ``` Input is *n* in Ans. Output is the *n*th telephone number. I was going to use the first formula mentioned in the challenge, but testing it resulted in **ERROR: OVERFLOW**s even on smaller numbers because TI-BASIC handles `n!!` as two successive factorials instead of a [double factorial](https://whatis.techtarget.com/definition/double-factorial). At least it has a builtin for summation notation! **Update:** I found that \$(2k-1)!!=\frac{(2k)!}{2^kk!}\$, so i replaced the function i was using to \${{n}\choose{2k}}\frac{(2k)!}{2^kk!}\$, which is represented as `(Ans nCr (2K))(2K)!/(2^KK!)` in TI-BASIC. **Explanation:** ``` ∑((Ans nCr (2K))(2K)!/(2^KK!) ;sum the equation mentioned above ,K ;using K as the loop variable ,0 ;starting at 0 ,int(.5Ans ;and ending at the floor of half of the input ;leave the result in Ans ;implicit print of Ans ``` **Examples:** ``` 10:prgmCDGF26 9496 5:prgmCDGF26 26 ``` **Note:** TI-BASIC is a tokenized language. Character count does *not* equal byte count. [Answer] # JavaScript (ES6), 25 bytes 0-indexed. Uses the recurrence relation. ``` f=n=>n<2||f(--n)+n*f(n-1) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i7PxqimJk1DVzdPUztPK00jT9dQ839yfl5xfk6qXk5@ukaahoGmJheqiCEWITMMISMjTc3/AA "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 8 bytes *-4 bytes by porting [Stephen's cQuent answer](https://codegolf.stackexchange.com/a/198243/6484)* ``` 1λèsN<*+ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f8NzuwyuK/Wy0tIFsAwA "05AB1E – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 29 bytes ``` f n|n<2=1|m<-n-1=f m+m*f(n-2) ``` [Try it online!](https://tio.run/##BcE7DoAgDADQq3Rw8BMIMMNJjENDrBJpQ8TRs1vfO7Ffe62qBPJKDMm/HI0Ynwh44ZlGMWFSxiKQoN1FHhiAsQHB6qz1btMvU8Wjq8mt/Q "Haskell – Try It Online") Implements the recursive formula. [Answer] # [C (gcc)](https://gcc.gnu.org/), 40 bytes ``` long f(long n){n=n<2?1:f(--n)+n*f(n-1);} ``` [Try it online!](https://tio.run/##NcvNCoJAEAfw@zzFIAi75YK7yrRm1ot0CW0XwaYQO4XPvk1Fpx/8P3oT@z6l6c4Rg/rC@sUdH9zJ7oMyhvWWN0GxsbpdU1RSAz7mkZeAKssH7I6YT8OZs4IL2WndwgogPd4uI6vPPKpSUsH@pZ/OiTBfl@fMWMoxWWjqhqAmV9KuIiDrva@p8o11bw "C (gcc) – Try It Online") Merely copied from [@Arnauld answer](https://codegolf.stackexchange.com/a/198244/84844) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 26 bytes ``` {{(1,1,++$×*+*...*)[$_]}} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/ulrDUMdQR1tb5fB0LW0tPT09Lc1olfjY2tr/xYmVCnpARWn5RQoGOgqGIGymo2Bk9B8A "Perl 6 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~81~~ \$\cdots\$ ~~57~~ 56 bytes ``` def f(n): a=b=i=1 while i<n:a,b=a+i*b,a;i+=1 return a ``` [Try it online!](https://tio.run/##FcxBCoMwEEDRvacYXCV1hCalCqnxLglNcKCMEqaUIp49rau/ePC3rywr32p9pgxZsXYNBB89edPAZ6FXAprYBYw@dHSJGB7UnVaSvAtDqHktIEAM6ooG72j@GdBatOM52wqxqNzu4iZ7QN/PsGcl2s1mOFpdfw "Python 3 – Try It Online") Uses 0 based indexing and implements the recursive formula. [Answer] # [J](http://jsoftware.com/), 25 bytes ``` ($:+]*$:@<:)@<:`1:@.(<&2) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NVSstGO1VKwcbKw0gTjB0MpBT8NGzUjzvyYXV2pyRr5CmpKBQqaeocF/AA "J – Try It Online") `$:` is J's recursion operator, so this is a fairly straightforward impl of the recursive def. I tried a couple other approaches (including using `^:` power of operator) but wasn't able to get shorter than this. Am curious if anyone can improve it... [Answer] # [PHP](https://php.net/), 48 bytes ``` function f($n){return$n<2?1:f(--$n)+$n*f($n-1);} ``` [Try it online!](https://tio.run/##K8go@G9jXwAk00rzkksy8/MU0jRU8jSri1JLSovyVPJsjOwNrdI0dHWBgtoqeVogWV1DTeva/6nJGfkKSgYKCrp2Ckp6aRoGmnpKMXlK1lwQCUMDmIQhuowZXMYMVcbICCZjZASV@Q8A "PHP – Try It Online") Implementation of the recursive function. **Original version: 54 bytes** (port of @Noodle9 answer): ``` for($i=$j=1;++$n<$argn;$j=$k){$k=$i;$i+=$n*$j;}echo$i; ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNFQybVWybA2ttbVV8mxUEovS86yBfJVszWqVbFuVTGuVTG1blTwtlSzr2tTkjHygyP//hgb/8gtKMvPziv/rugEA "PHP – Try It Online") [Answer] # Mathematica ~~46~~ 42 bytes ``` f=2^(#/2)HypergeometricU[-#/2,.5,-.5]I^-#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/N1ihOQ1nfSNOjsiC1KD01Pze1pCgzOTRaFyioo2eqo6tnGusZp6us9j@gKDOvJDot2iA2lgvGNkThmCFxjIxiY/8DAA) Thanks to mabel for helping me shave 4 bytes by using what I think is an anonymous function. As seen in <https://www.wolframalpha.com/input/?i=OEIS+A000085> and <http://mathworld.wolfram.com/ConfluentHypergeometricFunctionoftheSecondKind.html> [Answer] # [Red](http://www.red-lang.org), 53 bytes ``` f: func[n][either 1 > n: n - 1[1][n *(f n - 1)+ f n]] ``` [Try it online!](https://tio.run/##JYtBCoQwEAS/0nhalaDxIIsHH@F1mEMwExSWWQnx/Toi9KGroLLEa5FIfKUJ6dSVlEn2skmGxwydoHDw5JkUzSe9WLewx1b9s4R1M0s9vG1kOvKuBXSEaHpA5dxcwaj7SSpPh6@VNw "Red – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` ⊞υ¹FN⊞υ⁺§υι×ι§υ⊖ιI⊟υ ``` [Try it online!](https://tio.run/##TYm7DsIwDAD3foVHRwpDF5ZOCJYuKAM/EFKjRsqjcmzE3wdlQOK2uwu751B96t1p21EtzGaZXpUB13Ko3DU/idEY@H2XtOFF1rLRZ3g0Fh4xU8No4a/fKDBlKkIbRjNYJsexCF59E3T1QB2x9/ncT@/0BQ "Charcoal – Try It Online") Link is to verbose version of code. Uses the recurrence relation. Explanation: ``` ⊞υ¹ ``` `T(0)=1` ``` FN ``` Loop `n` times. ``` ⊞υ⁺§υι×ι§υ⊖ι ``` `T(i+1)=T(i)+iT(i-1)` ``` I⊟υ ``` Output `T(n)`. [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 21 bytes ``` :1≤[_1|;:@Tƒ^:;@Tƒ*+] ``` [Try it online!](https://tio.run/##y05N/@8QomBY89/K8FHnkuh4wxprK4eQY5PirKxBlJZ27P9jk7gSDBR07RQSdB41LDQACeuZmmrrcCUYIoQNUcTNEOJmSOJGRnBxIyOw@P//upl5AA "Keg – Try It Online") Simply implements the formula in a recursive manner. The footer is mainly for testing purposes [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 80 bytes ``` .+ $*_;;_; {`^_(_*;)(_*;_+) $1_$2,$2 +`(,_*)_(;_+;(_*))|, $3$1$2 ^;_*;(_*).* $.1 ``` [Try it online!](https://tio.run/##FYqhDoAwDAV9v6Ni3ZYlHQmm/8IbAoFBEBz8e@nMibu7j@e8dvdWiDPMYPSODQnZZAJFiBXcK3cqI1VkQQptUUW@SrywRtss7ulaJm7qrusP "Retina 0.8.2 – Try It Online") Explanation: ``` .+ $*_;;_; ``` Initialise the work area with `n`, `i=0`, and `T=[1]` (note that the list indices are reversed, so that the first element of `T` is `T[i]` and the last is `T[0]`) converted to unary. ``` {` ``` Loop `n` times (actually until the buffer stops changing, but see below). ``` ^_(_*;)(_*;_+) $1_$2,$2 ``` Decrement `n`, increment `i`, and make extra copies of `i` and `T[i]`. ``` +` ``` Repeat `i` times. ``` (,_*)_(;_+;(_*))|, $3$1$2 ``` Decrement the copy of `i` and add `T[i-1]` to the copy of `T[i]`, stopping when the copy reaches zero by deleting the `,` entirely, causing the repeat to terminate. The result is therefore `T[i+1]=T[i]+iT[i-1]`. ``` ^;_*;(_*).* $.1 ``` When `n` is zero, replace the work area with `T[i]` converted to decimal. This causes the loop to terminate as the stages can no longer match. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~28~~ 26 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` _pZÌ+(ZÊÉ *ZgJÑ}g´U1õ ï)gJ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=X3BazCsoWsrJICpaZ0rRfWe0VTH1IO8pZ0o&input=WzAsMTAsMTYsMjJdCi1t) ``` pZÌ+(ZÊÉ *ZgJÑ make sequence with next element from previous sequence _ ... }g´U repeat input -1 times 1õ ï) starting with [[1,1]] gJ implicit output last element of resulting sequence ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 16 bytes This is inspired by the Fibonacci GolfScript program. ``` ~,1.@{)*1$+\}/\; ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v07HUM@hWlPLUEU7plY/xvr/f7P/AA "GolfScript – Try It Online") ## Explanation ``` ~, # Generate exclusive range from input to 0 1. # Make 2 copies of 1 @ # Make the each target on the top { }/ # Foreach over the range ) # Increment the current item * # Multiply top by the current item 1$+ # And add by the second-to-top \ # Swap items \; # Swap & discard the bottom item ``` [Answer] # [Elm](https://elm-lang.org/), 45 bytes ``` f n = if n<2 then 1 else (n-1)*f(n-2)+f(n-1) ``` [Try it online!](https://ellie-app.com/7Q49bz3NyrPa1) Implementation of the recursive function. [Answer] # k4, 53 bytes ``` {+/{*/[1+!x]*%*/[y#2]**/*/'1+(!x-2*y;!y)}[x]'!1+_x%2} { }[x]'!1+_x%2 /pass inner lambda 2 args - x and each (') enumerate (!) 1+floor float-div 2 (!x-2*y;!y) /enumerate 1+ /add 1 to both list items */' /multiply over each - this gives both denominator factorials */ /multiply them */[y#2] /make list of 2s of y-length and multiply over - gives y^2 * /multiply left and right args % /reciprocal */[1+!x] /x factorial +/ /sum ``` examples: ``` {+/{*/[1+!x]*%*/*/[y#2],*/'1+(!x-2*y;!y)}[x]'!1+_x%2}'[0 3 10 14] 1 4 9496 2390480f ``` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 27 bytes ``` {*|x{x,+/(2#|x)*1,#2_x}/!2} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqlqrpqK6QkdbX8NIuaZCU8tQR9kovqJWX9Go9n@auoGCIRCZKRgZ/QcA "K (ngn/k) – Try It Online") * `x{...}/!2` setup a do-reduction with `x` (the input) as the number of iterations to run, seeded with `0 1` (the first two terms of the sequence) * `1,#2_x` build list containing how to multiply the previous values (i.e. `T(n-1)` by 1, and `T(n-2)` by n-1). Note that this infers the value of `n` from the length of the sequence so far. * `(2#|x)*` get the last two values of the reversed sequence (i.e. `(x[n-1];x[n-2])`) * `x,+/` take their sum, and append to the sequence * `*|` return the last value of the generated sequence [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` #S=ηÖPḣ ``` [Try it online!](https://tio.run/##yygtzv7/XznY9tz2w9MCHu5Y/P//f3MA "Husk – Try It Online") or [Verify first 10 values](https://tio.run/##ARwA4/9odXNr/23igoHFgDn/4bmBUz3Ot8OWUOG4o/// "Husk – Try It Online") Same idea as the Jelly answer, and equally as slow. 0-indexed. ## Explanation ``` #S=ηÖPḣ ḣ range 1..n P permutations # number of arrays which satisfy: S self = equals η indices of Ö ordered elements? ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` öƒ◙─v◙6 ``` [Run and debug it](https://staxlang.xyz/#p=949f0ac4760a36&i=0%0A1%0A2%0A3%0A4%0A5&m=2) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 37 bytes ``` {⍵<2:1⋄+/(2⍵-1)×∇¨⍵-⍳2} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR71YbIyvDR90t2voaRkCerqHm4emPOtoPrQBxHvVuNqr9n/aobcKj3r5HXc2Petc86t1yaL3xo7aJj/qmBgc5A8kQD89gsEk6j3pXpYE11hoA2ZsNDQA "APL (Dyalog Unicode) – Try It Online") -1 byte from Adám. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~16~~ ~~12~~ 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) 1-indexed ``` È+T°*ZÔÅÎ}g ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yCtUsCpa1MXOfWc&input=MTE) ]
[Question] [ ## Challenge: Take input of two black and white (monochrome) images and xor each pixel of the first, with each pixel of the second, add them to a new image and output the new image. ## Some clarifications: Size of pictures does not matter. Extension/Image format doesn't matter. You can make it take input any extension and output any extension, as long as the extension is used to store digital images. You can also use graphics to draw the output in eg: a picturebox if you wish. Otherwise, save the output as a file. Input can be taken as a path to the image, or url. One thing you can't do however, is I/O arrays, eg. of triplets(R,G,B). Do NOT tamper with [alpha](https://en.wikipedia.org/wiki/Alpha_compositing). It should not be xored, it should be 255 (max value) for every pixel. ## What do you mean xor each pixel? You don't have to do it this way, but one way to xor two pixels is to take their RGB values and xor R1 with R2, G1 with G2, B1 with B2, and take the result, which is your new color Since we have only two colors, obviously when the colors are the same the result would be (0,0,0) and when they are different (white is 255,255,255 and black is 0,0,0) in this case, the result would be 255,255,255. Thus when two pixels are different, the result is a white pixel, else a black pixel ## Example I/O: --- Input 1: Input 2: [![Input 1](https://i.stack.imgur.com/UbbfM.png)](https://i.stack.imgur.com/UbbfM.png) [![Input 2](https://i.stack.imgur.com/YyZG2.png)](https://i.stack.imgur.com/YyZG2.png) --- Output: [![Output](https://i.stack.imgur.com/uOhZg.png)](https://i.stack.imgur.com/uOhZg.png) --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins. [Answer] # The Fx Expression Language (ImageMagick), ~~8~~ 4 bytes EDITS * Simplified to `u!=v`, -4 bytes As ["Fx Expression Language"](https://www.imagemagick.org/script/fx.php) is apparently Turing complete, I've re-profiled my answer to it (was Unix Shell + Image Magick). **Golfed** ``` u!=v ``` *Fx* does not support bitwise *XOR* nor bitwise *NOT*, so I've used `!=` instead (which works just fine for the pure BW images). ``` u=> stands for "first image in list" v=> "second image in list" ``` Input and output are implicit (controlled by the interpreter). **Usage** ImageMagick [*convert*](https://www.imagemagick.org/script/convert.php) utility, serves as the "Fx Expression Language" interpreter, when invoked with `-fx`, as illustrated below: ``` convert $1 $2 -fx u!=v $3 ``` The arguments are: 1. Input image *A* 2. Input image *B* 3. Output image *O* (A^B). **Sample output** ``` convert a.png b.png -fx u!=v o.png ``` [![enter image description here](https://i.stack.imgur.com/DpPuz.png)](https://i.stack.imgur.com/DpPuz.png) [Answer] # Mathematica, ~~37~~ ~~34~~ 15 bytes *Thanks to Ian Miller for cutting the number of bytes by more than half!* ``` ImageDifference ``` In the end, there's always a builtin. This function takes two images as input and outputs an image; it does something more complicated for color images, but for black-and-white it's exactly XOR. Previous submissions: *Thanks to JungHwan Min for saving 3 bytes!* ``` Image[BitXor@@Chop[ImageData/@#]]& ``` Unnamed function that takes an ordered pair of images (of compatible dimensions) as input, and returns a displayed image. `ImageData` gets only the pixel data without all the wrappers/metadata; unfortunately it returns real numbers, so `Chop` is needed to help treat them as integers. `BitXor` does exactly what it says on the tin (and threads over nested lists), and `Image` turns the resulting RGB back into an image. Original submission, which took an ordered pair of URLs or filenames a input: ``` Image[BitXor@@(#~Import~"Data"&/@#)]& ``` [Answer] # Java, 336 335 328 bytes ``` import static javax.imageio.ImageIO.*;import java.io.*;public class M{static void main(String[]y)throws Exception{java.awt.image.BufferedImage a=read(new File("a.png"));for(int i=0,j;i<a.getHeight();i++)for(j=0;j<a.getWidth();)a.setRGB(j,i,a.getRGB(j,i)^read(new File("b.png")).getRGB(j++,i));write(a,"png",new File("c.png"));}} ``` ## Ungolfed: ``` import static javax.imageio.ImageIO.*; import java.io.*; class M { public static void main(String[]y) throws Exception { java.awt.image.BufferedImage a = read(new File("a.png")); for (int i = 0, j; i < a.getHeight(); i++) for (j = 0; j < a.getWidth(); ) a.setRGB(j, i, a.getRGB(j, i) ^ read(new File("b.png")).getRGB(j++, i)); write(a, "png", new File("c.png")); } } ``` [Answer] # Python, ~~64~~ ~~60~~ 57 bytes I'm new to golfing so have some mercy! ``` from cv2 import* r=imread;lambda a,b:imshow('c',r(a)^r(b)) ``` Thanks to @Blender and @FlipTack for saving me 7 bytes! [Answer] # [MATL](https://esolangs.org/wiki/MATL), 10 bytes ``` YiiYiY~1YG ``` ### Explanation This is basically the same answer, as the existing [Octave solution](https://codegolf.stackexchange.com/a/106947/64514): It takes the file names or URLs of both images as inputs and displays the result on the screen. ``` Yi % Read first image from the URL or filename (implicit input) i % Get the second URL or filename as input Yi % Read that second image Y~ % XOR the two images 1 % Push 1 (needed to make YG act as imagesc) YG % Display result using the MATLAB imagesc function ``` ### Usage ``` >> matl > YiiYiY~1YG > > 'https://i.stack.imgur.com/UbbfM.png' > 'https://i.stack.imgur.com/YyZG2.png' ``` [Answer] # Octave, ~~43~~ ~~38~~ 34 bytes ``` @(a,b)imshow(imread(a)~=imread(b)) ``` Thanks to [flawr](https://codegolf.stackexchange.com/users/24877/flawr) saved me 5 bytes. Thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo) saved me 4 bytes suggested to use `a~=b` instead of `xor(a,b)`. A function that takes as input file name of the two input images `a,b` and shows the result. Previous answer that writes to a file: ``` @(a,b,c)imwrite(imread(a)~=imread(b),c) ``` A function that takes as input file name of the two input images `a,b` and file name of the output image `c`. Usage: ``` #two test images that used in the question #https://i.stack.imgur.com/UbbfM.png #https://i.stack.imgur.com/YyZG2.png A = "UbbfM.png"; B = "YyZG2.png"; C = "out.png"; (@(a,b,c)imwrite(imread(a)~=imread(b),c))(A,B,C) ``` Result is saved in `out.png` [Answer] # Processing, ~~124~~ ~~118~~ 117 bytes ``` void m(PImage a,PImage q){for(int i=0,j;i<400;i++)for(j=0;j<400;point(i,j++))stroke((a.get(i,j)^q.get(i,j))<9?0:-1);} ``` Usage: > > **Note:** this code can support images up to `400px` (with modifications can support upto 999 for the same bytecount). Any "leftover" space will be coloured black, so for best results, the image size should be the same size as the dimensions in the code (also the `size()` needs to be changed with the updated dimensions) > > > ``` m(loadImage("http://i.imgur.com/a0M6o9e.png"),loadImage("http://i.imgur.com/bP1TsjQ.png")); ``` [![enter image description here](https://i.stack.imgur.com/WlODv.png)](https://i.stack.imgur.com/WlODv.png) ``` m(loadImage("https://i.stack.imgur.com/UbbfM.png"),loadImage("https://i.stack.imgur.com/YyZG2.png")); ``` [![enter image description here](https://i.stack.imgur.com/dP6yy.png)](https://i.stack.imgur.com/dP6yy.png) ### Ungolfed ``` void Q106945(PImage a,PImage q){ // takes two images as input for(int i=0,j;i<400;i++) // looping through the x-coordinates for(j=0;j<400;point(i,j++)) // looping through the y-coordinates stroke((a.get(i,j)^q.get(i,j))<9?0:-1); /* Here we have to colour the point according to the xor. So we do a simple a.get(i,j)^q.get(i,j). But since the alpha gets xored, instead of outputting white, this outputs a colour with alpha 0 (completely invisible). So to fix this I have a ternary that checks the value and changes the colour accordingly. At the end of all this, the third statement of the for-loop with j gets triggered since all this code is in this for-loop. Now we draw a point over the coordinate with the colour we have chosen before. */ } ``` [Answer] ## JavaScript (ES6), 253 bytes **- ~~12~~ 20 bytes saved by Ismael Miguel** **- 2 bytes saved by user2428118** Expects already loaded images, takes the last input's size as output size and returns a canvas element. ``` (i,j)=>(c=i=>{with(document.createElement(C='canvas')){({width,height}=i);return getContext`2d`}},g=i=>(x=c(i),x.drawImage(i,0,0),x.getImageData(0,0,1e4,1e4)),a=g(i),b=g(j).data,d=a.data,d.forEach((e,i)=>d[i]=i%4>2?e:e^b[i]),x.putImageData(a,0,0),x[C]) ``` ``` let func = (i,j)=>(c=i=>{with(document.createElement(C='canvas')){({width,height}=i);return getContext`2d`}},g=i=>(x=c(i),x.drawImage(i,0,0),x.getImageData(0,0,1e4,1e4)),a=g(i),b=g(j).data,d=a.data,d.forEach((e,i)=>d[i]=i%4>2?e:e^b[i]),x.putImageData(a,0,0),x[C]) window.onload =_=>{ document.body.appendChild(func(img1, img2)); } ``` ``` <img id="img1" crossOrigin="anonymous" src="https://dl.dropboxusercontent.com/s/nnfkzpvabk77pnl/UbbfM.png"> <img id="img2" crossOrigin="anonymous" src="https://dl.dropboxusercontent.com/s/58euf43vcb9pvpa/YyZG2.png"> ``` **Ungolfed** ``` (i, j) => ( c = i => { // an helper to create a canvas object with the input's dimension with(document.createElement(C='canvas')) { ({width, height}=i); // set the canvas size return getContext`2d` } }, g = i => ( // an helper to get an ImageData object from an Image x = c(i), x.drawImage(i, 0, 0), x.getImageData(0, 0, 1e4, 1e4) // 1e4 x 1e4 px should be big enough // (bigger might not be supported by the browser) ), a = g(i), b = g(j).data, d = a.data, d.forEach((e, i) => { // loop through all rgba values d[i] = i % 4 > 2 // we need to special handle the alpha channel ? e : // keep the alpha of the first input e ^ b[i] // xor the rgb values }), x.putImageData(a, 0, 0), // put that back on the last context we created x[C] // return its canvas } ``` **Could be even further golfed (220 bytes) with a fixed 300\*150px size (all remaining is transparent black)** as in the Processing answer ``` (c=i=>document.createElement(C='canvas').getContext('2d'),g=i=>(x=c(i),x.drawImage(i,0,0),x.getImageData(0,0,1e4,1e4)),a=g(i),b=g(j).data,d=a.data,d.forEach((e,i)=>d[i]=i%4>2?e:e^b[i]),x.putImageData(a,0,0),x[C]) ``` ``` let func = (i,j)=>(c=i=>document.createElement(C='canvas').getContext('2d'),g=i=>(x=c(i),x.drawImage(i,0,0),x.getImageData(0,0,1e4,1e4)),a=g(i),b=g(j).data,d=a.data,d.forEach((e,i)=>d[i]=i%4>2?e:e^b[i]),x.putImageData(a,0,0),x[C]) window.onload =_=>{ document.body.appendChild(func(img1, img2)); } ``` ``` <img id="img1" crossOrigin="anonymous" src="https://dl.dropboxusercontent.com/s/nnfkzpvabk77pnl/UbbfM.png"> <img id="img2" crossOrigin="anonymous" src="https://dl.dropboxusercontent.com/s/58euf43vcb9pvpa/YyZG2.png"> ``` [Answer] ## Perl, 260 bytes 251 bytes of code + 9 bytes for `-MImager`. ``` ($i,$j)=map{new Imager(file,pop)}0,1;$p=getpixel;for$x(0..$i->getwidth()-1){$i->setpixel(x=>$x,y=>$_,color=>[map{($j->$p(%t)->rgba)[$c++%3]^$_?0:255}($i->$p(%t=(x=>$x,y=>$_,type=>'8bit'))->rgba)[0..2]])for 0..$i->getheight()-1}$i->write(file=>'a.png') ``` I'm not sure Perl is the best language for this challenge, but I wanted to know what was the image of @orlp's comment. And it makes me use a little bit of those graphic modules, that's a good thing. And I enjoyed coding it! A more readable version: ``` use Imager; $img1 = new Imager( file => $ARGV[1] ); $img2 = new Imager( file => $ARGV[0] ); for $x ( 0 .. $img1->getwidth()-1 ) { for $y ( 0 .. $img1->getheight()-1 ) { ($r1, $g1, $b1) = $img1->getpixel( x => $x, y => $y, type => "8bit" )->rgba(); ($r2, $g2, $b2) = $img2->getpixel( x => $x, y => $y, type => "8bit" )->rgba(); $r = $r1 ^ $r2 ? 0 : 255 ; $g = $g1 ^ $g2 ? 0 : 255 ; $b = $b1 ^ $b2 ? 0 : 255 ; $img1->setpixel( x => $x, y => $y , color => [ $r, $g, $b] ); } } $img1->write( file => 'a.png' ) ``` You'll need to install Imager if you want to try it, but it's quite simple: just run `(echo y;echo) | perl -MCPAN -e 'install Imager'` in your terminal. [Answer] # [LÖVE2D](https://love2d.org/), 199 bytes ``` u,c=... i=love.image.newImageData a=math.abs X=i(u)Y=i(c)Z=i(X:getDimensions())Z:mapPixel(function(x,y)r,g,b=X:getPixel(x,y)R,G,B=Y:getPixel(x,y)return a(r-R),a(g-G),a(b-B)end)Z:encode("png","Z") ``` Simple enough, takes two image files on the command line, outputs a file called "Z" to the Love directory. Also works for full colour images! [Answer] # J, 54 bytes ``` load'bmp' 'o'writebmp~256#.255*~:&*&((3#256)#:readbmp) ``` Takes two arguments where each is the path to an input image in `bmp` format. Each image is read as a matrix of 24-bit RGB integers and parsed into a triplet of 8-bit RGB values, the sign of each is taken, and the two matrices are XOR'd together. The result is then scaled by 255, converted back from a triplet of base 256 numbers into an integer, and written to an output `bmp` file named `o`. [Answer] # C, 189 bytes ``` #include<stdio.h> s,t[9]; #define o(f,p)int*f=fopen(p,"ab+"); #define f(p,q,r)o(a,p)o(b,q)o(c,r)fscanf(a,"%*s %*d %*d %n",&s);for(fwrite(t,1,fread(t,1,s,b),c);s=~getc(a);putc(~s^getc(b),c)) ``` Operates on PBM images. Call `f(a, b, out)` with the names of both input files and the output file. Assumptions: * Both input image headers are identical (whitespace included), and are less than `9 * sizeof(int)` characters. * We're on a nice OS that flushes and closes leaked files. * `EOF == -1` **Ungolfed and explained:** (backslashes omitted) ``` // Scratch variable and "big enough" buffer s, t[9]; // Opens a file in read/append binary mode #define o(f,p)int*f=fopen(p,"ab+"); #define f(p, q, r) // Open the three file pointers a, b, c from the paths p, q, r o(a, p) o(b, q) o(c, r) // Read from a to locate the end of the PBM header fscanf(a, "%*s %*d %*d %n", &s); for( // Read the header from b into the buffer, // then write it back from the buffer to c fwrite(t, 1, fread(t, 1, s, b), c); // Loop condition: get the next byte from a // and check for EOF with a bitwise-not // (Assumes that EOF == -1) s = ~getc(a); // Loop increment: get the next byte from b, // flip s back, xor and write to c putc(~s ^ getc(b), c) ) // Snatch the semicolon from the call syntax :) ``` --- # C (spec-bending), 149 bytes ``` #include<stdio.h> t[7]; #define o(f,p,u)int*f=fopen(p,"ab+");u(t,1,7,f); #define f(p,q,r)o(a,p,fread)o(b,q,fread)o(c,r,fwrite)putc(getc(a)^getc(b),c) ``` Still uses PBM files, but now: * The image has to be one pixel high and 8 pixels wide or less, because PBM packs 8 pixels in a byte. * The header has to be 7 bytes (e.g. `P4 8 1` with a trailing space). Both files are seeked forwards while filling `t` with their header, then the last bytes are read, xor'd and written back. Takes advantage of `fread` and `fwrite` having similar parameter lists to factor all three operations on the header behind the same macro. [Answer] ## R, 45 bytes ``` p=png::readPNG;plot(as.raster(+(p(a)!=p(b)))) ``` `a`and `b` represent the file names of the two image files. Example: ``` a <- "YyZG2.png" b <- "UbbfM.png" p=png::readPNG;plot(as.raster(+(p(a)!=p(b)))) ``` Output: [![enter image description here](https://i.stack.imgur.com/Wqi85.png)](https://i.stack.imgur.com/Wqi85.png) [Answer] # Processing, 82 bytes ``` void x(PImage a,PImage b){int x=b.width;b.blend(a,0,0,x,x,0,0,x,x,32);set(0,0,b);} ``` Abuses Processing's extensive drawing functions to avoid actually doing any XORing. Blends the two images together with `DIFFERENCE` mode and draws them to the screen. ### Usage ``` x(loadImage("http://i.imgur.com/a0M6o9e.png"),loadImage("http://i.imgur.com/bP1TsjQ.png")); ``` ### Ungolfed ``` void xor(PImage a, PImage b) { int x = a.width; b.blend(a, 0, 0, x, x, 0, 0, x, x, DIFFERENCE); set(0, 0, b); } ``` [Answer] # C#, 233 bytes ``` using System.Drawing;class C{static void Main(){Bitmap a=new Bitmap("a"),b=new Bitmap("b");for(int x=0,y=0;;)try{a.SetPixel(x,y,a.GetPixel(x,y)==b.GetPixel(x,y)?Color.Black:Color.White);x++;}catch{if(x<1)break;x=0;++y;}a.Save("c");}} ``` Thanks to Unknown6656 for the tip that command line arguments are not necessary. The program now reads from files "a" and "b" and writes to file "c" in the same format as "a". Off by one error fixed too. It sets each pixel to black if the colour is the same, otherwise white. To save bytes, it catches out of bounds exceptions, rather than checking the Width and Height properties of the Bitmaps. Each time x goes out of bounds it is reset to 0, and y is incremented. When y goes out of bounds, x is 0 and the loop breaks to save the image and quit. Example compile using csc and run using mono: ``` csc xor.cs mono xor.exe ``` [Answer] # Clojure, 300 bytes ``` (ns s(:import[java.io File][java.awt.image BufferedImage][javax.imageio ImageIO]))(defn -main[](let[a(ImageIO/read(File."a.png"))](doseq[i(range(.getHeight a))j(range(.getWidth a))](.setRGB a j i(bit-xor(.getRGB a j i)(.getRGB(ImageIO/read(File."b.png")) j i))))(ImageIO/write a"png"(File."c.png")))) ``` Blatant rip-off of the [Java answer](https://codegolf.stackexchange.com/a/106955/31224). I didn't know how to do the challenge, but was curious how well the Java solution translated into Clojure. It was pretty straightforward. The ungolfed code is actually kind of pretty. This was the first code-golf challenge I've done that included imports. There's probably a way to optimize them to save some bytes. Ungolfed: ``` (ns bits.golf.bit-or-picts (:import [java.io File] [java.awt.image BufferedImage] [javax.imageio ImageIO])) (defn -main [] (let [^BufferedImage a (ImageIO/read (File. "a.png")) ^BufferedImage b (ImageIO/read (File. "b.png"))] (doseq [i (range (.getHeight a)) j (range (.getWidth a))] (.setRGB a j i (bit-xor (.getRGB a j i) (.getRGB b j i)))) (ImageIO/write a "png" (File. "c.png")))) ``` [Answer] ## PHP, ~~246~~ 243 bytes I can probably golf this down more. ``` $o=imagecreatetruecolor($w=max(imagesx($a=($i=imagecreatefrompng)($argv[1])),imagesx($b=$i($argv[2]))),$h=max(imagesy($a),imagesy($b)));for(;$k<$w*$h;)imagesetpixel($o,$x=$k%$w,$y=$k++/$w,($t=imagecolorat)($a,$x,$y)^$t($b,$x,$y));imagepng($o); ``` Run it from the command line like this: ``` php -d error_reporting=0 -r "$o=imagecreatetruecolor($w=max(imagesx($a=($i=imagecreatefrompng)($argv[1])),imagesx($b=$i($argv[2]))),$h=max(imagesy($a),imagesy($b)));for(;$k<$w*$h;)imagesetpixel($o,$x=$k%$w,$y=$k++/$w,($t=imagecolorat)($a,$x,$y)^$t($b,$x,$y));imagepng($o);" "https://i.stack.imgur.com/UbbfM.png" "https://i.stack.imgur.com/YyZG2.png" > output.png ``` [Answer] # Node.js, ~~156~~ 135 bytes ``` (a,b)=>(f=require('fs')).writeFile(a+b,((s=f.readFileSync)(a)+'').replace(/\d+$/,(c,d)=>[...c].map((e,f)=>+!(e^(s(b)+b)[f+d])).join``)) ``` Input and output image files should be in the [PBM](https://en.wikipedia.org/wiki/Netpbm_format) (P1) format, where the first line is `P1 [width] [height]`, and the second line is the b/w ascii values without spaces. Here's a the input images followed by the xor output (32x32 pixels): [![Input #1](https://i.stack.imgur.com/AjlRn.png)](https://i.stack.imgur.com/AjlRn.png) [![Input #2](https://i.stack.imgur.com/N67qQ.png)](https://i.stack.imgur.com/N67qQ.png) [![Output](https://i.stack.imgur.com/StrHo.png)](https://i.stack.imgur.com/StrHo.png) ]
[Question] [ The [dragon curve sequence](http://oeis.org/A014577) (or the regular paper folding sequence) is a binary sequence. `a(n)` is given by negation of the bit left of the least significant 1 of `n`. For example to calculate `a(2136)` we first convert to binary: ``` 100001011000 ``` We find our least significant bit ``` 100001011000 ^ ``` Take the bit to its left ``` 100001011000 ^ ``` And return its negation ``` 0 ``` # Task Given a positive integer as input, output `a(n)`. (You may output by integer or by boolean). You should aim to make your code as small as possible as measured by bytes. # Test Cases Here are the first 100 entries in order ``` 1 1 0 1 1 0 0 1 1 1 0 0 1 0 0 1 1 1 0 1 1 0 0 0 1 1 0 0 1 0 0 1 1 1 0 1 1 0 0 1 1 1 0 0 1 0 0 0 1 1 0 1 1 0 0 0 1 1 0 0 1 0 0 1 1 1 0 1 1 0 0 1 1 1 0 0 1 0 0 1 1 1 0 1 1 0 0 0 1 1 0 0 1 0 0 0 1 1 0 1 ``` [Answer] ## Mathematica 25 Bytes ``` 1/2+JacobiSymbol[-1,#]/2& ``` Other ways of doing this: 56 bytes ``` (v:=1-IntegerDigits[#,2,i][[1]];For[i=1,v>0,i++];i++;v)& ``` 58 bytes ``` 1-Nest[Join[#,{0},Reverse[1-#]]&,{0},Floor@Log[2,#]][[#]]& ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~22~~ 21 bytes 1 byte thanks to ETHproductions. ``` lambda n:n&2*(n&-n)<1 ``` [Try it online!](https://tio.run/##RcixCoAgFAXQva94U/nKQBMapP6kxShLqJuIS19vY2c88c3nA1P8vJTL3evmCBb10ArUPXjSxT@JAgVQcjh2oaVWim1MAVmozovAcsc2N9Rw9e@gzchcPg "Python 3 – Try It Online") Bitwise arithmetic ftw. [Answer] # [Retina](https://github.com/m-ender/retina), ~~38~~ ~~34~~ 29 bytes ``` \d+ $* +`^(1+)\1$|1111 $1 ^1$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFm0tFi0s7IU7DUFszxlClxhAIuFQMueIMVf7/N@Qy4jLmMuEy5TLjMuey4LLkMjTgMjI0NgMA "Retina – Try It Online") Martin and Leaky essentially came up with this idea, for 5 more bytes off! Converts the input to unary, and then progressively divides the number by 2. Once it can't do that evenly anymore (i.e. the number is odd) it then removes patches of 4 from the input, computing the result of the last operation mod 4. Finally, this checks if the result was 1, which means that digit to the left of the least significant 1 bit was zero. If that is true, the final result is 1, otherwise it is zero. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` &N&HṆ ``` [Try it online!](https://tio.run/##y0rNyan8/1/NT83j4c62/4YGBofbHzWt8f4PAA "Jelly – Try It Online") ### How it works ``` &N&HṆ Main link. Argument: n N Negate; yield -n. & Bitwise AND; compute n&-n. This yields the highest power of 2 that divides n evenly. H Halve; yield n/2. & Bitwise AND; compute n&-n&n/2. This rounds n/2 down if n is odd. Ṇ Take the logical NOT of the result. ``` [Answer] ## [Alice](https://github.com/m-ender/alice), 8 bytes ``` I2z1xnO@ ``` [Try it online!](https://tio.run/##S8zJTE79/9/TqMqwIs/f4f//BwtnAAA "Alice – Try It Online") Takes input [as the code point of a Unicode character](http://meta.codegolf.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values) and outputs the result as a 0x00 or 0x01 byte accordingly. For testability, here is a decimal I/O version at 12 bytes which uses the exact same algorithm (only I/O is different): ``` /o \i@/2z1xn ``` [Try it online!](https://tio.run/##S8zJTE79/18/nysm00HfqMqwIu//fyNDYzMA "Alice – Try It Online") If Alice was a golfing language and didn't require explicit I/O and program termination, this would clock in at a mere 5 bytes (`2z1xn`) beating both 05AB1E and Jelly. ### Explanation ``` I Read input. 2z Drop all factors of 2 from the input, i.e. divide it by 2 as long as its even. This shifts the binary representation to the right until there are no more trailing zeros. 1x Extract the second-least significant bit. n Negate it. O Output it. @ Terminate the program. ``` [Answer] # [Haskell](https://www.haskell.org/), 33 bytes ``` g~(a:b:c)=1:a:0:b:g c d=g d (d!!) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P71OI9EqySpZ09bQKtHKAMhMV0jmSrFNV0jhSrPVSFFU1Pyfm5iZp2CrUFCUmVeioJGbWKCQphBtoKdnaRmr@R8A "Haskell – Try It Online") Uses 0-indexing. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~24 23~~ 21 bytes ``` {~⍵[¯1+⌈/⍸⍵]}0,2⊥⍣¯1⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v7ruUe/W6EPrDbUf9XToP@rdAeTG1hroGD3qWvqodzFQ4lHXov9pj9omPOrte9TV/Kh3zaPeLYfWGz9qm/iob2pwkDOQDPHwDP6fdmjFo97NhgYGAA "APL (Dyalog Unicode) – Try It Online") Bitwise operations are a bit long in APL, so I went with the method in the question. -1 byte from dzaima. -2 bytes from Adám. ## Explanation ``` {~⍵[¯1+⌈/⍸⍵]}0,2⊥⍣¯1⊢ input n taken on the right 2⊥⍣¯1⊢ n in binary 0, with 0 prepended in case the LSB is at first index { } do the following to the array ⍵: ⍸⍵ get indices of 1's in ⍵ ⌈/ find maximum index ¯1+ subtract 1 from it to get the previous index ⍵[ ] Find the element at that index in ⍵ ~ bitwise NOT ``` [Answer] # [Haskell](https://www.haskell.org/), 26 bytes ``` f n=even$div n$2*gcd(2^n)n ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzza1LDVPJSWzTCFPxUgrPTlFwyguTzPvf25iZp6CrUJBUWZeiYKKQm5igUKaQrShnp6pQex/AA "Haskell – Try It Online") Boolean output. **32 bytes** ``` (d!!) d=d%1 ~(h:t)%k=k:h:t%(1-k) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzXyNFUVGTK8U2RdWQq04jw6pEUzXbNtsKyFDVMNTN1vyfm5iZp2CrUFCUmVeioJGbWKCQphBtoKdnaRmr@f9fclpOYnrxf93kggIA "Haskell – Try It Online") Saves one byte off of [Anders Kaseorg's recursive-list solution](https://codegolf.stackexchange.com/a/132818/20260). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` b0ܨθ≠ ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/yeDwnEMrzu141Lng/38jQ2MzAA "05AB1E – Try It Online") [Answer] # [Wise](https://github.com/Wheatwizard/Wise), ~~28~~ ~~20~~ 16 bytes ``` ::-~^~-&:[?>]~-^ ``` [Try it online!](https://tio.run/##K88sTv3/36rOyiquTtfKXi3aKi7OzqpOEciMjatTtFGz@///v6ExAA "Wise – Try It Online") ## Explanation This is a port of Leaky Nun's Python answer. It unfortunately does not work on TIO because TIO's version of the interpreter is a bit outdated. We start by making 3 copies of our input with `::`, we then decrement the top copy by 1. This will flip all the bits up until the first 1. We then xor this with another copy of our input. Since all of the bits up until the first 1 on our input have been flipped this will result in all those bits being 1 on the result. If we then add one `~-` to the result we will get a single 1 at the place *to the left of* our least significant 1. We AND this with the input to get that bit from the input. Now we will have `0` iff that bit was off and a power of 2 iff that bit was on, we can change this into a single `1` or `0` with `:[?>]`. Once this is done we need only negate the bit `~-^` and we are done. [Answer] # [Python 2](https://docs.python.org/2/), 19 bytes ``` lambda n:n&-n&n/2<1 ``` [Try it online!](https://tio.run/##BcFBCoAgEAXQq/yVOFDUuJQuY2Ql1FfETaef3mvfuCuDnbWDKERPvLLXCbqqRLReOODtSe9@JDDSzXRcwqYmnmI/ "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~45~~ ~~43~~ 39 bytes *6 bytes saved thanks to nimi* ``` f x|d<-div x 2=[f d,mod(1+d)2]!!mod x 2 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hoibFRjcls0yhQsHINjpNIUUnNz9Fw1A7RdMoVlERyAZJ/M9NzMyzLSgtCS4pUknOz0tOLFGJVldQtyrOyC8HGlFho5ubWKCQFm2op2doYBAb@x8A "Haskell – Try It Online") [Answer] # x86 Machine Code, ~~17~~ ~~16~~ 15 bytes: Assumes an ABI where parameters are pushed on the stack and the return value is in the `AL` register. ``` 8B 44 24 04 0F BC C8 41 0F BB C8 0F 93 C0 C3 ``` This is disassembled as follows: ``` _dragoncurve: 00000000: 8B 44 24 04 mov eax,dword ptr [esp+4] 00000004: 0F BC C8 bsf ecx,eax 00000007: 41 inc ecx 00000008: 0F BB C8 btc eax,ecx 0000000B: 0F 93 C0 setae al 0000000E: C3 ret ``` [Answer] ## JavaScript (ES6), ~~17~~ 14 bytes ``` f= n=>!(n&-n&n/2) ``` ``` <input type=number min=0 oninput=o.textContent=f(this.value)><pre id=o> ``` Edit: Saved 3 bytes by porting @Dennis's answer once I noticed that boolean output was acceptable. [Answer] # [C (gcc)](https://gcc.gnu.org/), 20 bytes ``` f(n){n=!(n&-n&n/2);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOs9WUSNPTTdPLU/fSNO69n9mXolCbmJmnoYmVzUXZ1p@kQZIJE/BVsHQGkjZAGkDAyBLW1uTi5OzoAgom6ahpFqqoKSjADJQ05qrlus/AA "C (gcc) – Try It Online") [Answer] # [INTERCAL](https://esolangs.org/wiki/INTERCAL), 50 bytes ``` DOWRITEIN.1DO.1<-!?1~.1'~#1DOREADOUT.1PLEASEGIVEUP ``` INTERCALs unary operators are quite suitable for this, so I decided to write my first post. ``` DO WRITE IN .1 DO .1 <- !?1~.1'~#1 DO READ OUT .1 PLEASE GIVE UP ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 bytes 1 byte thanks to Erik the Outgolfer. ``` Bt0ṖṪṆ ``` [Try it online!](https://tio.run/##AR0A4v9qZWxsef//QnQw4bmW4bmq4bmG/zk5w4figqxH/w "Jelly – Try It Online") ## Longer programs * 7 bytes: [`Họ¡2&2Ị`](https://tio.run/##y0rNyan8/9/j4e7eQwuN1Iwe7u76b2l5uP1R0xr3/wA) * 7 bytes: [`Bt0ṫ-ḄỊ`](https://tio.run/##y0rNyan8/9@pxODhztW6D3e0PNzd9d/S8nD7o6Y17v8B) [Answer] # [Befunge-98](https://github.com/catseye/FBBI), 19 bytes ``` &#;:2%\2/\#;_;@.!%2 ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X03Z2spINcZIP0bZOt7aQU9R1ej/fyNDYzMA "Befunge-98 – Try It Online") ``` &# Initial input: Read a number an skip the next command ;:2%\2/\#;_; Main loop: (Direction: East) :2% Duplicate the current number and read the last bit \2/ Swap the first two items on stack (last bit and number) and divide the number by two => remove last bit \ swap last bit and number again #;_; If the last bit is 0, keep going East and jump to the beginning of the loop If the last bit is 1, turn West and jump to the beginning of the loop, but in a different direction. &#; @.!%2 End: (Direction: West) &# Jump over the input, wrap around %2 Take the number mod 2 => read the last bit .! Negate the bit and print as a number @ Terminate ``` [Answer] # [,,,](https://github.com/totallyhuman/commata), ~~10~~ 9 [bytes](https://github.com/totallyhuman/commata/wiki/Code-page) ``` ::0-&2*&¬ ``` ## Explanation Take input as 3 for example. ``` ::0-&2*&1≥ implicitly push command line argument [3] :: duplicate twice [3, 3, 3] 0 push 0 on to the stack [3, 3, 3, 0] - pop 0 and 3 and push 0 - 3 [3, 3, -3] & pop -3 and 3 and push -3 & 3 (bitwise AND) [3, 1] 2 push 2 on to the stack [3, 1, 2] * pop 2 and 1 and push 2 * 1 [3, 2] & pop 2 and 3 and push 2 & 3 [2] ¬ pop 2 and push ¬ 2 (logical NOT) [0] implicit output [] ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 34 bytes ``` @(x)~(k=[de2bi(x),0])(find(k,1)+1) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzTiPbNjol1SgpE8jRMYjV1EjLzEvRyNYx1NQ21PyfpmFooPkfAA "Octave – Try It Online") **Explanation:** ``` @(x) % Anonymous function taking a decimal number as input ~.... % Negate whatever comes next ( de2bi(x) ) % Convert x to a binary array that's conveniently % ordered with the least significant bits first [de2bi(x),0] % Append a zero to the end, to avoid out of bound index (k=[de2bi(x),0]) % Store the vector as a variable 'k' (find(k,1) % Find the first '1' in k (the least significant 1-bit) +1 % Add 1 to the index to get the next bit (k=[de2bi(x),0])(find(k,1)+1) % Use as index to the vector k to get the correct bit ``` [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 71 bytes ``` (load library (q((x)(not(nth(c 0(to-base 2 x))(last-index(to-base 2 x)1 ``` Anonymous function that takes a number and returns 0 or 1. [Try it online!](https://tio.run/##VckxDoAgDAXQ3VN0/B1IkEtwjiImkiAgdMDT4@xbn6by5jTaWshVIuUUuvR3QySPB5iMUhVFLxxkodUEGSc5mszIMtSkEs/5i33hlkaesGslZ5nXBw "tinylisp – Try It Online") ### Ungolfed/explanation Surprisingly, tinylisp's library lets us implement the spec almost directly. ``` (load library) (lambda (x) ; Anonymous function with one argument (not ; Logical negation of (nth ; The element of _ at index __: (cons 0 (to-base 2 x)) ; The binary representation of x with a 0 prepended (last-index ; Index of the last occurrence (to-base 2 x) ; in the binary representation of x 1))))) ; of 1 ``` Prepending a 0 handles the "previous bit" logic by shifting all elements down one spot, and it keeps us from walking off the left end of the list when there is only a single 1 bit. [Answer] # Submission: # [Python 2](https://docs.python.org/2/), ~~41~~ 39 bytes ``` x=input() while~-x&1:x/=2 print 1-x/2%2 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8I2M6@gtERDk6s8IzMntU63Qs3QqkLf1oiroCgzr0TBULdC30gVqNDI0NgMAA "Python 2 – Try It Online") -2 bytes thanks to FryAmTheEggman # Initial Solution: # [Python 2](https://docs.python.org/2/), 43 bytes ``` lambda x:1-int(bin(x)[bin(x).rfind('1')-1]) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCylA3M69EIykzT6NCMxpC6RWlZealaKgbqmvqGsZq/i8oAilJ0zAyNDbT1PwPAA "Python 2 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~11~~ 10 bytes ``` t4*YF1)Z.~ ``` [Try it online!](https://tio.run/##y00syfn/v8REK9LNUDNKr@7/f1MA "MATL – Try It Online") Or see the [first 100 outputs](https://tio.run/##y00syflvaGBgpeTwv8REK9LNUDNKr@5/rFrGfwA). ### Explanation ``` t % Implicit input. Duplicate 4* % Multiply by 4. This ensures that the input is a multiple of 2, and % takes into account that bit positions are 1 based YF % Exponents of prime factorization 1) % Get first exponent, which is that of factor 2 Z. % Get bit of input at that (1-based) position ~ % Negate. Implicit display ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 20 bytes ``` n->kronecker(-1,n)>0 ``` Using the [Kronecker symbol](https://en.wikipedia.org/wiki/Kronecker_symbol). [Try it online!](https://tio.run/##DcjBCcAgDAXQVUJPBgyYAcwupWgR4Suh@6de3uHt24e8OzrVgNj0hfbM5kk0g61EX55AlTSTlpJp@8B35iKxQ09g5vgB "Pari/GP – Try It Online") [Answer] # SCALA, 99(78?) chars, 99(78?) bytes ``` if(i==0)print(1)else print(if(('0'+i.toBinaryString).reverse.dropWhile(x=>x=='0')(1)=='1')0 else 1) ``` where `i` is the input. As you can see, I do save 21 bytes if I don't take care of the zero (as the author did in his test case) : ``` print(if(('0'+i.toBinaryString).reverse.dropWhile(x=>x=='0')(1)=='1')0 else 1) ``` This is my first codegolf so I hope I did well :) [Try it online!](https://tio.run/##TY4xb8IwEIVn/CtOWeJTRGQXiQHVSLAxdOrQpYtJLuAqOkeOQalQf3t6iKpiu7v33XtvbHzv53j8oibDmw8MNGXidoTdMNzUoqUO2uRPkZtLupIOmwNnvM2h08E5g0MKnLVF6kdSj0UkXZqyCnWO@8A@fb9nEU5YJ7pSGqluUxw@zqEnPbnt5JzQKB4y2BIN3L3A4vyjVBeTZnhdgoEcwRqD0ukRU3xyUXFVwHILBUrTp5aMSp7/uRe7Wv9hz9T9LOD8Cw) Though it's quite long to compute lol. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~35~~ 31 bytes ``` f(x){return~x&1?f(x/2):!(x&2);} ``` Switched to a recursive implementation. [Try it online!](https://tio.run/##FclBCoMwEEbhfU7xK1RmsKXGpan0LCVtZBZNJUQISHr1GJfvffa2WFuKo8R7@MQt@H/q9LP2feSpodSNbHIRH/F9iSfeFeB@gc4jszbymPUwGOl7ME4E1lDRUXt5o73CkTDYVMkqq3IA "C (gcc) – Try It Online") [Answer] # Java 8, 17 bytes ``` n->(n&2*(n&-n))<1 ``` Straightforward port of [LeakyNun's Python 3 answer](https://codegolf.stackexchange.com/a/128877/58251). I'm not familiar enough with bitwise operations and operator precedence to see a shorter solution; maybe there's a way to avoid the extra parentehesis? [Answer] # [Chip](https://github.com/Phlarx/chip), 93 bytes ``` HZABCDEFG,t ))))))))^~S H\\\\\\\/v~a G\\\\\\/v' F\\\\\/v' E\\\\/v' D\\\/v' C\\/v' B\/v' A/-' ``` Takes input as little endian bytes. (The TIO has a bit of python that does this for you). Gives output as either `0x0` or `0x1`. (The TIO uses xxd to inspect the value). [Try it online!](https://tio.run/##TVDLasMwELzrK5ZcZNFEog20gTwgDzu59dBbKQ1@KLHAlYS0aW0I@XVXTpzSOczM7sLOslnqyzZPERZgnTnyvFQWZjOg8WtC2937crXexMl2iARYj8/LG9l93CC@LynZ3j0lyZ@L72bT6/omqysvxYi2IYKQLpsrbU/IURk4g22wNHoMoxwG6ssah@AbP4Ua5qA0RqHgHguluZNpETE2hb5lwo7sdDhIx3@cQhnVHM0@a1D6KPhM4b6S@ohlxB5emBCTIXRD4wrp5rRSiJWkjA3CEcJYFN0vrsRt8@87Z6jron16HD//Ag "Chip – Try It Online") ### How do it this? Chip looks at input one byte at a time, so handling multibyte input adds some bulk, but not near as much as I had feared. Let's go into it: ``` HZABCDEFG ``` These are `HZ`, high bit of the previous byte (if there was one), and `A`-`G`, the seven lower bits of the current byte. These are used to locate the lowest set bit of the number. ``` ,t ))))))))^~S ``` When the lowest set bit is found, we have a few things to do. This first chunk says "if we have a set bit (the `)`'s), then stop `S`uppressing the output, and `t`erminate after we print the answer. ``` H\\\\\\\/v~a G\\\\\\/v' ... A/-' ``` Whichever bit of the current byte (`A`-`H`) is only preceded by a bunch of zeroes then a one (`\` and `/`: these look at the bits directly north of them; we can trust that all previous bits were zero) is passed through to the wires on the right (`v`, `'`, ...), then whichever value it is is inverted and given as the low bit of output (`~a`). [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 12 bytes ``` 1≠¯1⊥2↑⍸∘⌽∘⊤ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/3/BR54JD6w0fdS01etQ28VHvjkcdMx717AWRXUv@pz1qm/Cot@9RV/Oh9cYg@b6pwUHOQDLEwzP4fxlItm8ql6GCoYKBAoSE0DAWMh8makBAHl2/AYX6CdkPN5/rUdeicqCX0g6teNS72dDAgKvsUefCcgA "APL (Dyalog Extended) – Try It Online") Took the idea of using `⍸` from [Razetime's answer](https://codegolf.stackexchange.com/a/211228/78410). ### How it works ``` 1≠¯1⊥2↑⍸∘⌽∘⊤ ⍝ Input: n ⊤ ⍝ Binary representation of n ⌽∘ ⍝ Reverse ⍸∘ ⍝ Get indices of ones, in increasing order ⍝ LSB index (l) comes first, and the next number is l+1 ⍝ iff the bit on the left of LSB is also 1 2↑ ⍝ Take first two numbers, filling with 0 if too short ¯1⊥ ⍝ From [a, b] compute -a + b 1≠ ⍝ Is it not equal to 1? ``` Equivalent non-extended program: # [APL (Dyalog Unicode)](https://www.dyalog.com/), 17 bytes ``` 1≠¯1⊥2↑∘⍸∘⌽2∘⊥⍣¯1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/BR54JD6w0fdS01etQ28VHHjEe9O0Bkz14jENW19FHvYqD8/7RHbRMe9fY96mo@tN4YpLJvanCQM5AM8fAM/l8Gku2bymWoYKhgoAAhITSMhcyHiRoQkEfXb0ChfkL2w83netS1qBzopbRDKx71bjY0MOAqe9S5sBwA "APL (Dyalog Unicode) – Try It Online") [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 12 bytes ``` ~1=-/|-2#&2\ ``` Modeled after [@Bubbler's APL answer](https://codegolf.stackexchange.com/a/211251/98547). * `2\` convert input to base-2 * `-2#&` get the last two indices containing 1's * `-/|` subtract the smaller index from the larger one * `~1=` if the last truthy index isn't preceded by another truthy value, return 0. otherwise, return 1 [Try it online!](https://tio.run/##y9bNS8/7/z/Nqs7QVle/RtdIWc0o5n@RlaGCoYKBAoSE0DAWMh8makBAHl2/AYX6CdkPN5@rqC5N3VBb0dDA4D8A "K (ngn/k) – Try It Online") ]
[Question] [ Write a program or function that takes a character as input and outputs a character. Also, choose a list of 13 distinct ASCII printable characters (32-126). When a character from this list is passed into the program or function, it should output the character at the corresponding position in `Hello, world!`. This way, running your code on each element of the list in turn would produce `Hello, world!`. **Example:** If your chosen list is `Troublemaking`, you should produce a program or function that maps: ``` T -> H r -> e o -> l u -> l b -> o l -> , e -> m -> w a -> o k -> r i -> l n -> d g -> ! ``` **Rules:** * Your score is length of the program/function. * You can't store any data between program/function runs. * Include list of the characters you chose into the answer. [Answer] # [Perl 5](https://www.perl.org/), 8 bytes −1 byte by Sisyphus. ``` y;yav;ol ``` Input: `Heavy, world!` [Try it online!](https://tio.run/##K0gtyjH9/7/SujKxzDo/5/9/j9TEskodhfL8opwUxX/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 18 bytes A function that inputs and outputs an ASCII code. ``` lambda c:c-954%c%3 ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHZKlnX0tRENVnV@L@3a6SCrUKSukdqTm6@jlJlQVFeiqI6V2JxcWpRiUJOap5GcWqJBlCVpqaCra2CoTFXQVFmXolGUmVJarFGbmKBRpqOAlwabE5Ovo5CeX5RDtAczf8A "Python 3 – Try It Online") The chosen 13-byte string is: `Helmo,"yprnd!`, and was found using [brute force](https://tio.run/##lVTBbqMwEL37KyapSMyGtpBU2mpJctlL/6HLrgCbYBVMBEZBWvHt2bEJKSRN1fWBGZ6fn4dnxvH9Lo6Pxzsh46xmHNaVYkKqh3RLxlhxCZVC7jRG7hhPhOSQ0MYG2tw3rtVYjWcTUqPS8x8FsVSv3vI58EmchiUo3uD7UwAbmL7wLCscOBRlxiZTB0pe6SmfkMdH@Fnk@1rxCsLfEeQFg/yBoCTsc6pD6IAOURdyG/4SwKFfUAbVPd8Ah1RkHGjUEwwpQQBm4NknLs0KuQP96JBvEIIFuX9eEV6Qwp7iQATb7Xm31jxLrupSaiWftMRUnYdC0r6GpCjBfETjmkJ1XIPnuq5OF4thre9c78T13rnemKtHzvOKK4quO@A6gM7b/ohwFoxRb7X0MaLe8jsm12q9pWmVIjuh8YVY7ybWvzGk2cyEtdkYFgt9@npZMF7XkksFTZxn8wDQzJWWMUDRAcsz8IJAn/NB7syDcWH9BAxIh0FeDnI2yCfz4CMTTrbikXa2rj4w4r@d/Yq7I2GBNDx3oXVXGG/L9rYa6U3XdcJ85UR3mQg@W9j9w5qF@8X@p7yo5OHbbUpLvoZeI3u8Y1RCp0lRS/YDqMUci9nwalXBL4mXRYPH0Hjm0rBv/VztdVO6uiWPx38). **Alternative Solutions** ``` lambda c:c^656%c%7 # 18b ('Mahim/!sntjd"') lambda c:c^308268%c # 19b ('Z{@HU 2I}B`Y5') lambda c:c|2242944%c # 20b ('HeLdi, AoblD!') lambda c:c^c*2%54%21 # 20b ('Ngchb"+|i{lt,') lambda c:c-c*c%60%11 # 20b ('Mjmpr-#|tvqe$') ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 14 bytes ``` c=>'lol'[c]||c ``` [Try it online!](https://tio.run/##BcExDoAgDADAryALkGij7jj7B@JAChhNpQaNLv4d73b/@AvLdt5d5hBrshXtpIhJOVy@DytyvpgiEK/aAYCcI/XcincoY2jkAoc/NQo7iaTRGNh5y1opY@oP "JavaScript (Node.js) – Try It Online") Input text is: ``` Hel0o, w1r2d! ``` lol [Answer] # JavaScript (ES6), 16 bytes Expects and returns an ASCII code. Produces `Hello, world!` when given `(a-IK*s]d5P/+`. ``` c=>28+c*c%389%96 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/Z1s7IQjtZK1nV2MJS1dLsf3J@XnF@TqpeTn66RrSenp6SRqKup7dWcWyKaYC@tlKsXm5igUaygq2dQnBJUWZeul5aUX6uc0ZikTPQRI00jWS9ZCjHsURDEwj0svIz8zTU1TU1/wMA "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 19 bytes This version was built such that the output character is guaranteed to be in the range 32-126 as well. The OP has since clarified that this is not required. Expects and returns an ASCII code. Produces `Hello, world!` when given `,X=CI:YWx.~7-`. ``` c=>32+c*c*71%193%91 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/Z1s7YSDtZK1nL3FDV0NJY1dLwf3J@XnF@TqpeTn66RrSenp6SToSts6dVZHiFXp25rlKsXm5igUaygq2dQnBJUWZeul5aUX6uc0ZikTPQUI00jWS9ZCjHsURDEwj0svIz8zTU1TU1/wMA "JavaScript (Node.js) – Try It Online") ### Full mapping ``` | 0 1 2 3 4 5 6 7 8 9 A B C D E F ---+-------------------------------- 20 | M < S B Y = I - 9 m y G H ! r @ 30 | 6 T J h S f Q d D L , 4 d l 6 3 40 | c U z l + x 7 y - o # Z i : > u 50 | n ? 8 Y R s a w e ^ i L W / / 60 | b b / / W L i ^ e w a s R Y 8 70 | ? n u > : i Z # o - y 7 x + l ``` [Answer] # [Python](https://www.python.org), 31 bytes ``` lambda c:c.translate('ll !o'*8) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhb7cxJzk1ISFZKtkvVKihLzinMSS1I11HNyFBTz1bUsNCGqbuoWFGXmlWgoKell5WfmaaRpJGsqpOUXKSQrZOYpqHuk5ijn6yiUKxWppCiqa0I1LVgAoQE) Input characters to use are `Hel#o, w"r$d!` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` “½ṬṚ»y ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5xDex/uXPNw56xDu4H8/x6picl5OgrluUU5KYoA "Jelly – Try It Online") Takes `Heacn, wmrld!`. Searched with [this script](https://tio.run/##ZY5BasMwEEX3OsV001iuGnC6M3ifOxgTjC0nCspIjFSEG3J2R@OUYuhKw3/89@XneHH4tUzkbnDV1s5gbt5RhMGN@uT7s1YwmiEahz3N4heSXiZHkMDghu7DheHHNrIOz7UAM4HVWCT5XtVZjdHgtxYQoIHdMc86BcmRHd92AojTtvwxvkhtXR86ldqKX9kJ4FnPsxQy@6y6LF81YU/a237QRelfREEl/5bvZXjIpuEzSO7gWsrHxsj5C@BWly2sYfDvu2vFk8FYJBXksjwB). ``` y Transliterate the input by “½ṬṚ» "monoclinal". ``` Unless I [brute-forced something wrong](https://tio.run/##bVLLTsMwELznK5YLcUqImiIuUcOFC/8QVchNXDBNbWvXUVQQ3168TloqgXJZZR47O7I7@ndrHk47tAf4UH1/BH1wFj20tlOvTr6pHDrdem2NxGMORJTMDFTnSXuF3tqeTp3agVfkX2nYktd@YCGJrWz3o8Quh51FHrIqAYIa0pew0@YwWuy7mzRhHBxoA2dJIEYmFahcL1slFq6pqvtyk0OZJaB30Csjvhb0ndU1j8TmYKIoDBfHeTWDE2quPYNVuMgPaCL4JxpI0wW/hO2e2e5ydOHQdkPrxaWyplo9LkO@4K6kr1ccaOQ4ROL5N/OYwS2UnIfBNHx3MEY0tSkY63nN2JRVtdpAWDuPRWsH40XapxmsYcX61hqvzaASQD6sWXxqJ8aG2fmsyjYJONRBOGZTzQdJe96A0rwpUcJ6HVMhZbFAhlXHbpvrFpFigSFk1M8HnOmFNhRqEcscYqMT6emphjL2S0Pvg@U/T2TSh86IdcF@IkfzOXc@/4vGW1Ryfzr9AA), a 2-byte compressed string does not seem to be possible. [Answer] # x86 32-bit machine code, 7 bytes ``` A8 28 75 02 0C 6C C3 ``` [Try it online!](https://tio.run/##TVFRa4MwEH42v@LqGCTTltiyPdR1DDrYXvayp0FbJGqiGRolRqor/etzSVlhJOS4@@6@@@6Ste28yLJpYl0NGD58jBZF1aSsAoHE2jO8M8CqEGhKaWQPpcj7Ut/AkdfoKxJF7lLE157mBhEfSIz4YLhW4G99OCUJM0bLtDc8STDWvGiZrnFECIGsZBoEvpiBxGeEbqTKqj7n8NiZXDaL8gkhqQzUTCpM0Al5zhtgAzSE0ZkYeZd6qdre7Jb3DwcbEQU3Hb6EQrCxEBydIg6y2nH8lz4eYhiDgCDPs67jwQJfIeLSW20bCuzv1TvLSqk4ZE3O177D8gZOVxxu6fLTt5o2GPeqk4Xi@WW@OyLIbgiCg50PjqWsOOARZlb5sF397wD4VkI62rWTvbJMdiHoPE1v/PnlNYRjo6t89pOJihXdNK9XS/vYn9vYYl79Ag "C++ (gcc) – Try It Online") Using the `regparm(1)` calling convention, this takes an ASCII code in AL and returns one in AL. Chooses `He@DG, world!`. In assembly: ``` f: test al, 0b00101000 # Set flags based on bits 3 and 5 of the character. jnz e # If they are not both 0 (true for all of "Hello, world!"), # jump to the end, to leave the character unchanged. or al, 0b01101100 # Otherwise, set bits 2, 3, 5, and 6 to 1. # (These are the bits that are 1 in both 'l' and 'o'.) e: ret # Return. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞'Ÿ™‡ ``` Uses `H2345, world!` as 13 characters. [Try it online](https://tio.run/##yy9OTMpM/f//Ucc89aM7HrUsetSw8P9/DyNjE1MdhfL8opwURQA) or [verify each ASCII character separately](https://tio.run/##ASYA2f9vc2FiaWX/xb5Rdnk/IiDihpIgIj95/@KInifFuOKEouKAof8s/w). **Explanation:** ``` ∞ # Push an infinite positive list: [1,2,3,...] 'Ÿ™ '# Push dictionary string "hello" ‡ # Transliterate the characters of the (implicit) input-string # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `'Ÿ™` is `"hello"`. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 7 bytes ``` T`d`o-l ``` [Try it online!](https://tio.run/##K0otycxL/P8/JCElIV835/9/j9Qc43wdhXKDIpMURQA "Retina 0.8.2 – Try It Online") Explanation: Inspired by @loopywalt's Python answer, works by translating `0` to `o` and both `3` and `4` to `l`, so given the 13 distinct characters `Hel3o, w0r4d!` as input the output is `Hello, world!` as desired. (The full transliteration actually maps `0123456789` to `onmlllllll`.) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` kakH¡Ŀ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwia2FrSMKhxL8iLCIiLCJhXG5iXG5jXG5kXG5lXG5mXG5nXG5oXG5pXG5qXG5rXG5sXG5tIl0=) Takes `a`, `b`, ... `m` ``` Ŀ # Transliterate ka # Lowercase alphabet kH¡ # To corresponding chars of "Hello, world!" ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 9 bytes * -1 byte thanks to [@Anders Kaseorg](https://codegolf.stackexchange.com/users/39242/anders-kaseorg) ``` tr 012 ol ``` Takes `Hel1o, w0r2d!` [Try it online!](https://tio.run/##S0oszvj/v6RIwcDQSCE/5/9/j9Qcw3wdhXKDIqMURQA "Bash – Try It Online") [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), ~~6.5~~ 6 bytes (12 nibbles) ``` =`r\$d:"lo" ``` `"Hel1o, w2r4d!"` becomes `"Hello, world!"`. ``` \$d # keep only digit characters `r # and get the value # (so non-digits become zero) = # and use this to index into "lo" # the string "lo" : # with the input character appended # (wrapping around for index >3) ``` [![enter image description here](https://i.stack.imgur.com/b1eaS.png)](https://i.stack.imgur.com/b1eaS.png) [Answer] # [C (clang)](http://clang.llvm.org/), 23 bytes ``` f(c){return 656%c%7^c;} ``` [Try it online!](https://tio.run/##Jc1BDsIgEEDRNXMK1DSBRXVl1dR6A69gQgZaxlBqCuiiqUcXa1z@v3lYolO@y7kVKKfRxDR6Xu2rAovDDes5b8ijS9rwc4iahq29AJCP0Cvy4jmQljABWw7HGtjLkjNcvAXyhncmolWjkFICY4/0rx8ka5jzVVnqd6vg412vP9g61YVcLkqDx9MX "C (clang) – Try It Online") Takes `Mahim/!sntjd"`. Brute forced solution found using [this](https://tio.run/##bVLLboMwEDzjr9hSWbIDaUly6IGk5976AWkqGQPBEQFkSBOa8uulax55SOXgx@zsznpYOZWpyLZtq7IKYiZd5e74WUfVQWegqKS7T@k37aPKZHoII1iWVajyp@SV3EJaZVuDEaxC9kJl7CtXISdnYsW5BmaKn2AFMx@3Jcw8z/PBcU4ckHGl1D2lvqHUPcUyYY1hzzc3mQgNYr1BwH6L0jR34ZjrNHywXZgUV0qwLtV3lMcg4BnG49rbmMRz4xNDvKhLBBdzH3eUn7/gwXEG9b5ajgRjEZxcqHmnYqkYGCswsI/2MtFMuIDNDFLBVTVAVZjCjPOxpDUpLu@xrGBdYFiYxmQPNWRc7jr0@gb/f5dxTPIuXcPPCjG56aqZNtE@TO@jBf6xKmY2HFWVAC2B0RCCuopK/pHZbseB/gvubmMi@nAZExpSHBRKQzMqQ/LA75zqrMKXNKRpf2Wcim3ZTt8Xfw) program. # [C++ (clang)](http://clang.llvm.org/), 22 bytes ``` [](int&c){c^=656%c%7;} ``` Port of the above. [Try it online!](https://tio.run/##JcpLCsIwEADQdeYUo1LJgOLKuoj1Bp5AFMKkn5E0LTbVRalXjwW3j8d9v2dvQ53sGDussEi3u5YQt0wTP4r8mGecncycDGwksB9diWceopPuArBEaK0E/e7EEUygFkE2oD6N@BL1VzMWWJeRG/vSRARKVZpph/34NyYDc7raRtrDagjx6dY/ "C++ (clang) – Try It Online") [Answer] # [Python](https://www.python.org), 32 bytes ``` lambda c:"Helo, wrd!"[ord(c)%10] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3FXISc5NSEhWSrZQ8UnPydRTKi1IUlaLzi1I0kjVVDQ1ioer0Cooy80o0lJT0svIz8zTSgLIKaflFCskKmXkKSm7uHkGeXt4-wb4xMX7-SpqaEF0LFkBoAA) Takes in characters `[F,G,H,R,I,J,K,L,S,M,\,N,O]`. ## [Python](https://www.python.org), 35 bytes ``` lambda c:"Hello, world!"[ord(c)-97] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3lXMSc5NSEhWSrZQ8UnNy8nUUyvOLclIUlaLzi1I0kjV1Lc1joUp1C4oy80o0lJT0svIz8zTSgLIKaflFCskKmXkKSolJySmpaekZmVnZOblKmpoQTQsWQGgA) Takes in `[a,b,c,d,e,f,g,h,i,j,k,l,m]`. [Answer] # [JavaScript (V8)](https://v8.dev/), 12 bytes ``` c=>c-954%c%3 ``` [Try it online!](https://tio.run/##VYtBC4IwHMXvfYoliBvkn6CCQiaElw7dPEaHsaZOdLNtGvXll7QO9W7v/d6vZROz3MjBpdPeV9RzmvP0sNvGPN54rpV1yDojVY0oSk6i6/Uqeg5G3ZZJtgh8VPI@irNQtWvmlxIPVAqHg0bAypcIV90J6HSNfwXyjy4AEMQr9GzAHNEclZ8BKqP7omGm0DeBK8yBf8vR4TWZA62WCkcRIZl/Aw "JavaScript (V8) – Try It Online") Using the string `Helmo,"yprnd!`, ported from [dingledooper's answer](https://codegolf.stackexchange.com/a/250568/98937) Expects input as a charcode and outputs as the charcode [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~26~~ 21 bytes ``` "Hello world!"`i$-97+ ``` *Down 5 bytes thanks to Razetime* A port of [Adam's Python answer](https://codegolf.stackexchange.com/a/250558/107017). Takes in `[a..l]`. [Try it online!](https://ngn.codeberg.page/k#eJxLs1LySM3JyVcozy/KSVFUSshU0bU01+biSlNKTEpOSU1Lz8jMys5RAgD84QyD) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes ``` ⭆S§⁺ιloΣι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaHjmFZSWQLgamjoKjiWeeSmpFRoBOaXFGpk6Cko5@UpA4eDSXI1MTSCw/v/fI9XQxEhHoTy/KCdFkeu/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. Takes as input the 13 distinct characters `He142, world!`. Explanation: Works by mapping `147` to `l` and `258` to `o`. ``` S Input string ⭆ Map over characters and join ι Current character ⁺ Concatenated with lo Literal string `lo` § Cyclically indexed by ι Current character Σ Digit value (0 if not a digit) ``` [Answer] ## [Knight](https://github.com/knight-lang/knight-lang), 13 bytes ``` O-=cP%%954c 3 ``` Port of @dingledooper's answer. ## [Knight](https://github.com/knight-lang/knight-lang), 16 bytes ``` O+28%%^P2 389 96 ``` Port of @Arnauld's answer. [Answer] # [Headascii](https://esolangs.org/wiki/Headass#Headascii), 45 bytes ``` -----[]]]]]--[]]]][U-]()R-:-()R--:--()R-:R;P! ``` Takes a character and prints it, except for `m`, `n`, and `p`, which map to `l`, `l`, and `o` specifcially. Full chosen string therefore is `Helmo, wprnd!` [Try It In Headass!](https://dso.surge.sh/#@WyJoZWFkYXNzIiwiIiwiLS0tLS1bXV1dXV0tLVtdXV1dW1UtXSgpUi06LSgpUi0tOi0tKClSLTpSO1AhIiwiIiwiMTEzIiwiIl0=), which is the same except that it takes character codes as input and returns character codes. Or, run it in Headascii [here](https://replit.com/@thejonymyster/HA23) by pasting this in: ``` erun("-----[]]]]]--[]]]][U-]()R-:-()R--:--()R-:R;P!","x") ``` and replacing `x` with the character input of your choice. Or verify the whole thing at once like this lol: ``` > hellowarp="-----[]]]]]--[]]]][U-]()R-:-()R--:--()R-:R;P!" '-----[]]]]]--[]]]][U-]()R-:-()R--:--()R-:R;P!' > verify=x=>erun(hellowarp,x) [Function: verify] > "Helmo, wprnd!".split("").forEach(verify) H e l l o , w o r l d ! ``` ### Explanation ``` -----[]]]]]--[]]]][U-]()R-:-()R--:--()R-:R;P! full program -----[]]]]]--[]]]][ r2 = -108 U i = input (charcode) U-]() if(i - r2 - 1 == 0){ // m R-: ;P! print i - 1 // m - 1 == l :-() }else if(i - r2 - 2 == 0){ // n R--: ;P! print i - 2 // n - 2 == l :--() }else if(i - r2 - 4 == 0){ // p R-: ;P! print i - 1 // p - 1 == o : }else{ R;P! print i } ``` ]
[Question] [ Upon the rumor that Codegolf will have a *Rock-Paper-Scissors tournament* you look into the topic of **square-free words**. A word made of the letters `R`, `P`, `S` is *square-free* if it does not contain a sequence that repeats twice. That is to say, the word can not be written as ``` a x x b ``` where `a` and `b` are words of any length and `x` is a word of length at least one, all made of the letters `R`, `P`, `S`. ## Task Write a program that generates the *square-free* words of the letters `R`, `P`, `S` of length `n` where the number `1 <= n <= 10` is taken as input. ## Example For example the *square-free* words of length 3 are `RPR`, `RSR`, `RPS`, `RSP`, `SPS`, `SRS`, `SRP`, `SPR`, `PRP`, `PSP`, `PSR`, `PRS` and those of length 4 are `RPRS`, `RPSR`, `RPSP`, `RSRP`, `RSPR`, `RSPS`, `PRPS`, `PRSR`, `PRSP`, `PSRP`, `PSRS`, `PSPR`, `SRPR`, `SRPS`, `SRSP`, `SPRP`, `SPRS`, `SPSR` and note that for example `SPSP` or `PRPR` are not square-free ## Rules * This is codegolf, shortest program wins, standard loopholes are closed. * You may print the words or create them in memory. * Your program may be written as a function. ## References [Wikipedia entry on square-free words](https://en.wikipedia.org/wiki/Square-free_word) The number of square-free ternary words of given length are in <https://oeis.org/A006156> Related: [Arbitrary-Length Ternary Squarefree Words](https://codegolf.stackexchange.com/questions/10601/arbitrary-length-ternary-squarefree-words) [Answer] # Ruby, 39 bytes ``` ->n{(?P*n..?S*n).grep_v /[^RPS]|(.+)\1/} ``` This hilariously inefficient function generates all strings of length N that lie alphabetically between N Ps and N Ss, then filters out the vast majority that contain non-RPS characters. The actual squarefree check just uses a Regexp backreference: `(.+)\1`. More idiomatic **65 bytes** that finish in a reasonable amount of time for N=10: ``` ->n{%w[R P S].repeated_permutation(n).map(&:join).grep_v /(.+)\1/} ``` Edit: Saved a byte thanks to G B. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 bytes ``` “RPS”ṗẆ;"f$$Ðḟ ``` [Try it online!](https://tio.run/##AUIAvf9qZWxsef//4oCcUlBT4oCd4bmX4bqGOyJmJCTDkOG4n/87IsOH4oKsWeKCrGrigb7CtsK2//9yYW5nZSgxLCAxMCk "Jelly – Try It Online") ### How it works ``` “RPS”ṗẆ;"f$$Ðḟ Main link. Argument: n “RPS”ṗ Cartesian power; yield all strings of length n over this alphabet. Ðḟ Filterfalse; keep only strings for which the quicklink to the left returns a falsy result. $ Monadic chain. Argument: s (string) Ẇ Window; yield the array A of all substrings of s. $ Monadic chain. Argument: A ;" Concatenate all strings in A with themselves. f Filter; yield all results that belong to A as well. ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 28 bytes ``` +%1`1 R$'¶$`P$'¶$`S A`(.+)\1 ``` [Try it online!](https://tio.run/##K0otycxL/P9fW9UwwZArSEX90DaVhAAIFczlmKChp60ZY/j/vyEQAAA "Retina – Try It Online") Takes input [in unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary). ### Explanation ``` +%1`1 R$'¶$`P$'¶$`S ``` This generates *all* strings made up of `RPS` of length `n`. The way we do this is that we repeatedly replace the first `1` in each line. Let's think about the line as `<1>`, where `<` is everything in front of the match and `>` is everything after the match (they're `$`` and `$'` respectively in regex substitution syntax, but those look less intuitive). We replace the `1` with `R>¶<P>¶<S`, where `¶` are linefeeds. So the full result of this substitution is actually `<R>¶<P>¶<S>`, which is three copies of the line, with the `1` replace with `R`, `P`, `S`, respectively, in each of the three copies. This process stops once all `1`s have substituted. ``` A`(.+)\1 ``` Finally, we simply discard all lines that contain a repetition. [Answer] # Mathematica, 61 bytes ``` ""<>#&/@{"R","P","S"}~Tuples~#~DeleteCases~{___,x__,x__,___}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/BfScnGTllN36FaKUhJRykAiIOVautCSgtyUovrlOtcUnNSS1KdE4uBvOr4@HidCigGsmvV/gcUZeaVKOg7pOk7BCXmpac6GBr8BwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~15~~ 14 bytes *-1 byte thanks to Zgarb!* ``` fȯεfoE½QΠR"RPS ``` [Try it online!](https://tio.run/##yygtzv7/P@3E@nNb0/JdD@0NPLcgSCkoIPj///8mAA "Husk – Try It Online") Builds all possible sequences of the correct length and keeps only the ones whose all substrings (except the empty one) are composed by two different halves. Damn, I really wanted to beat Jelly here. [Answer] # Java 8, ~~285~~ 277 bytes ``` import java.util.*;Set r=new HashSet();n->p("",((1<<3*n)+"").replaceAll(".","PRS"),n)void p(String p,String s,int n){int l=s.length(),i=0;if(l<1&&(s=p.substring(0,n)).equals(s.replaceAll("(.*)\\1","")))r.add(s);for(;i<l;p(p+s.charAt(i),s.substring(0,i)+s.substring(++i,l),n));} ``` Although Java is almost always verbose, in this case it's definitely not the right language for a challenge like this. Generating permutations with substrings is bad for performance and inefficient. Can definitely be golfed some more, though. -8 bytes thanks to *@Jakob*. **Explanation:** [Try it here.](https://tio.run/##bVGxbsIwEN3zFScP6I4EA2IMqcTWpQiVsXQwiQFTx3Fthwohvp06kKFIXXx@T7p3794dxUmMGivNsfq6qdo2LsAxcrwNSvNhDgDjMaxEpJsdhIOE7TnIUdm0JiSlFt7Dm1DmkgAoE6TbiVLCsoMAp0ZVUGLkwVAeqWsSnyUYKOBmRi8WGcsQp/P5bGgoZYy4k1ZHhYXWyDjL2Op9zSgzlPRGlk0A@7@Z@zSL6@CU2YPN@o/PHvMvXdGF51qafTggZaqY5GqHej4dDNAXlvt26@9NOIkjicvvVmiP/skV8iFtNtPojRGR46Kq0FO@axzmaq5zizb1vDwItwioKPNPsorSv0Saqkx3@1F@TdYygCuM/IFX4Q8RIeU3ANtutSrBBxFiuW9Zx8T7RT8@QdAj7u4OUMdsO4kO4D10gJobXuKsR@uzD7LmTRu4jQpBG6y56@9zvf0C) (Performance is too bad for test cases above 3, but it does work locally..) ``` import java.util.*; // Required import for Set and HashSet Set r=new HashSet(); // Result-Set on class-level n-> // Method with integer parameter and no return-type p("",((1<<3*n)+"").replaceAll(".","PRS"),n) // Get all permutations and save them in the Set // End of method (implicit / single-line return-statement) void p(String p,String s,int n){ // Separated method with 2 String & int parameters and no return-type int l=s.length(), // The length of the second input-String i=0; // Index-integer, starting at 0 if(l<1 // If the length is 0, &&(s=p.substring(0,n)).equals(s.replaceAll("(.*)\\1",""))) // and it doesn't contain a repeated part: r.add(s); // Add it to the result-Set for(;i<l; // Loop (2) from 0 to `l` p( // Recursive-call with: p+s.charAt(i), // Prefix-input + the character of the second input at index `i` s.substring(0,i)+s.substring(++i,l), // and the second input except for this character n) // and `n` ); // End of loop (2) } // End of separated method ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~97~~ 96 bytes ``` f=lambda n:{c+s for c in'RPS'*n for s in f(n-1)or{''}if all(k-s.find(c+s[:k])for k in range(n))} ``` Returns a set of strings. [Try it online!](https://tio.run/##RYuxDoIwFEVn/Yq3tcViQhxMSPgHo6M6VNpqA9ySlsUQvr1SHdzuOTl3fE8vj0NKtunV8NCKUM/tLpL1gVpyYOfThRX4clyZLEdZCR9mxhZnSfU978q4tw6ar8dr3d1FjrscB4Wn4RBiSdnh7ypJR1FvN2NwmDgkFdGHyWhucy4pmpEaYjcwSQb6t1cS6QM "Python 3 – Try It Online") [Answer] # [Julia 0.6](http://julialang.org/), 65 bytes ``` !n=n>0?["$c"s for s=!~-n,c="RPS"if~ismatch(r"(.+)\1","$c"s)]:[""] ``` [Try it online!](https://tio.run/##VYuxDoIwGAZneIq/XxzaWA1dHEiKr2B0BAZSJZbAj2lxM7x6jU46Xu5ueI6@O6Qk2HJVHGtsHCL1c6Boxbpj7SzOpwt8v/o4dYu7ywC536rGQH9j1ZY10KbPw@SZTGmKPGN6VfQInpeR82yYPUvBmtAw1J8CfvHG1/QG "Julia 0.6 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 37 bytes ``` sub r{grep!/(.+)\1/,glob"{R,S,P}"x<>} ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4NEmhqDq9KLVAUV9DT1szxlBfJz0nP0mpOkgnWCegVqnCxq72f3FipUJafpFC0X@Tf/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online") Function returns an array of the square free strings. **Explained:** The `glob` generates all combinations of R, S, & P with length equal to the input. The `grep` statement filters out the ones that are not square free. [Answer] # [R](https://www.r-project.org/), 97 bytes ``` cat((x=unique(combn(rep(c('p','r','s'),n),n<-scan(),paste,collapse='')))[!grepl("(.+)\\1",x,,T)]) ``` [Try it online!](https://tio.run/##DcsxCoQwEEbhs6zN/IOjYGGnt7BbLbJDWBZijImB3D4beF/5Yq1qHqCs2f/ubKHX@fGINkBBgYRik4jFt5YhqfFgCSY9VvRyzoRkVyJmfr@@bXPoMPa871MnRWTjg@tc/w "R – Try It Online") `combn(rep(c('p','r','s'),n),n,paste,collapse='')` computes all `n`-character strings with `p`, `r`, `s`, but it unfortunately duplicates many(\*), so we uniquify it, and take those that match the regex `(.+)\1`, using perl-style matching, then we print out the resultant list. (\*) technically, it generates all combinations of the `3n` letters in `p,r,s` repeated 3 times taken `n` at a time, then applies `paste(..., collapse='')` to each combination rather than computing the `3^n` strings directly, but this is golfier than an `expand.grid` (the true Cartesian product). [Answer] ## JavaScript (Firefox 30-57), 69 bytes ``` f=n=>n?[for(x of f(n-1))for(y of'RPS')if(!/(.+)\1/.test(y+=x))y]:[''] ``` Since all substrings of square-free words are also square-free the check can be done recursively. [Answer] # [Haskell](https://www.haskell.org/), ~~101~~ 98 bytes ``` f n=[x:r|x:r<-mapM(\_->"RPS")[1..n],[x]#r] h#t@(x:r)=h/=take(length h)t&&(h++[x])#r&&[x]#r h#t=1<3 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzza6wqqoBohtdHMTC3w1YuJ17ZSCAoKVNKMN9fTyYnWiK2KVi2K5MpRLHDSAyjRtM/RtSxKzUzVyUvPSSzIUMjRL1NQ0MrS1gQo1lYvU1MAaQOptDW2M/@cmZuYp2CoUFGXmlSioKKQpmPwHAA "Haskell – Try It Online") [Answer] # Julia, 88 ``` f(n)=[filter(A->!ismatch.(r"(.+)\1",join(A)),Iterators.product(repeated("RPS",n)...))...] ``` Nothing fancy. [Answer] ## JavaScript (ES7), 93 bytes ``` n=>[...Array(3**n)].map(g=(d=n,i)=>d?'RPS'[i%3]+g(d-1,i/3|0):'').filter(s=>!/(.+)\1/.test(s)) ``` Converts all the integers from 0 to 3ⁿ to (reversed padded) base 3 using `RPS` as digits and filters them for square-free words. [Answer] ## C# / LINQ, 169 ``` Enumerable.Range(0,(int)Math.Pow(3,n)).Select(i=>string.Concat(Enumerable.Range(1,n).Select(p=>"PRS"[(i/(int)Math.Pow(3,n-p))%3]))).Where(s=>!Regex.IsMatch(s,@"(.+)\1")) ``` There has to be a better way to do this :) [Answer] ## F#, 143 ``` let f n=[1..n]|>List.fold(fun l _->List.collect(fun s->["R";"P";"S";]|>List.map((+)s))l)[""]|>Seq.filter(fun x->not(Regex.IsMatch(x,"(.+)\1"))) ``` [Answer] # k, 56 bytes ``` f:{$[x;(,/"RPS",/:\:f x-1){x@&~~/'(2,y)#/:x}/1_!x;,""]} ``` The lack of native regex puts k well behind the curve for once. I went with a recursive solution, since the characters to implement it were saved by a simpler squarefree check. ``` $[ test ; if-true ; if-false ] ``` is k's ternary operator, here we do interesting stuff for non-zero length, and return a single empty string if asked for zero-length words. ``` (,/"RPS",/:\:f x-1) ``` takes the cartesian product of "RPS" and all n-1 length squarefree words. ,/:\: joins each element of the right to the left, giving a length 3 array of length n arrays. ,/ flattens this into a length 3n array. ``` {x@&~~/'(2,y)#/:x} ``` takes the first n letters of each string and compares it to the second n, then reduces the array to only where they do not match. Because we know the previous result is square-free, only the substrings starting at the first character need matching - simplifying the check here was worth the characters spent implementing recursion. Finally, ``` /1_!x ``` applies the lambda to the initial result set to its left, iterating over each substring length from 1 to (word length)-1. !x generates a list from 0 to x-1, then 1\_ removes the first element (since 0-length substrings will always match) Sacrificing a few characters we can use .z.s to self-reference rather than rely on the function name, and instead of checking substrings up to length n-1 only check floor(n/2) for performance. It finds all length 49 words (of which there are 5207706) in about 120 seconds on a 7700k, above that I run into the 4GB limit of free 32-bit k. ``` {$[x;(,/"RPS",/:\:.z.s x-1){x@&~~/'(2,y)#/:x}/1+!_x%2;,""]} ``` [Answer] # [Python 2](https://docs.python.org/2/), 99 bytes ``` import re f=lambda n:n and[c+s for c in'RPS'for s in f(n-1)if not re.search(r'(.+)(\1)',c+s)]or[''] ``` [Try it online!](https://tio.run/##FcsxDoMwDADAnVd4cywoElWnSvwB0ZEypIGISMWOnCx9fRrGGy7@8iF8LyWcUTSD7o0fv/b8bBb4yWB5W1ybwIuCg8A4Ty@8kCrAG74NFDywXLVPu1V3GEXTt2TeA2FXM62iC@JaogbONT2o/AE "Python 2 – Try It Online") ]
[Question] [ # 0xUsernames There's so many people using a messaging service that they're running out of space to store all the usernames! To fix this, they are going to start storing usernames as hexadecimal, where possible. If a username consists of only the characters `0123456789ABCDEF` (case insensitive), it can be converted to a hexadecimal and stored as an integer. For example, the username `ba5eba11` can be interpreted as `0xBA5EBA11`, a hexadecimal integer. But what about `05AB1E`? That's got a leading zero, which would be lost. So, whenever we convert a username, we make sure to prepend a `1` before reading it as an integer. --- ## The Challenge Your task is to write a program or function which, given a non-empty username as a string, 'hexa-compresses' the username: * If it can be interpreted as a hexadecimal integer, prepend a 1, interpret as hexadecimal, and then print the result **as base 10.** * Otherwise, just return the string unmodified. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution (in bytes) wins! Built-in base conversion functions are permitted. --- ## Test Cases You can assume that any resulting integers with be within your language's standard integer range. As with usernames on most messaging systems, the input strings will only contain alphanumerics and underscores. Remember, you always need to add a leading `1` before conversion! ``` "ba5eba11" -> 7421737489 "05AB1E" -> 17148702 "dec0de" -> 31375582 "Beef" -> 114415 "da7aba5e" -> 7960443486 "500" -> 5376 "DENNIS" -> "DENNIS" "Garth" -> "Garth" "A_B_C" -> "A_B_C" "0x000" -> "0x000" ``` For reference, here is a Python 3 implementation I used for the test cases (ungolfed): ``` import re def convert_name(name): if re.fullmatch('^[0-9A-Fa-f]+$', name): return int('1' + name.upper(), base = 16) else: return name ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` D1ìH ``` ## Explanation ``` D Duplicate input 1ì Prepend 1 H Interpret as hexadecimal and implicitly display the value in base 10 ``` If the input has invalid hex characters, `H` won't push anything so the last value on the stack will be the duplicated input, that's why the program prints its input in case of invalid input. [Try it online!](https://tio.run/nexus/05ab1e#@@9ieHiNx///Lq5@fp7BAA "05AB1E – TIO Nexus") [Answer] # JavaScript (ES6), 15 bytes ``` s=>'0x1'+s-0||s ``` ### How it works `'0x1'+s` converts the input into a literal hexadecimal string with a prepended `1`, e.g. `0x105ab1e`. Then `-0` casts the result to a number. JavaScript sees the `0x` at the beginning and implicitly tries to convert from hexadecimal; if `s` contains any non-hexadecimal chars, this returns `NaN`. Since this is falsy (and output `0` can never be given because of the prepended `1`), we can use `||s` to return `s` if the hex conversion failed. ### Test snippet ``` f = s=>'0x1'+s-0||s for(i of [ "ba5eba11", "05AB1E", "dec0de", "Beef", "da7aba5e", "500", "DENNIS", "Garth", "A_B_C", "0x000" ]) console.log(i + ":", f(i)); ``` [Answer] # [Python 2](https://docs.python.org/2/), 44 bytes Takes input as a quoted string. -2 bytes thanks to Rod! ``` a=input() try:exec'a=0x1'+a except:1 print a ``` As we're guaranteed that the input will only contain alphanumerics and underscores, there's no way to create valid Python after `0x1` other than having a hex string. If the input is anything else, the error is ignored, and printing as it originally was. I couldn't seem to make a regex match any shorter than `try/except`. In fact, regex turned out to be terribly verbose: ``` import re lambda n:re.match('^[0-9A-F]+$',n,2)and int('1'+n,16)or n ``` [Answer] # [Perl 6](https://perl6.org), 19 bytes ``` {:16(1~S/_/Z/)//$_} ``` [Test it](https://tio.run/nexus/perl6#VVDLbsIwELz7K7ZWVJLySExePEOhRVUvXOipQKNATIsEASWhoqLw63TthEcvq/HszOx6twmHb6cya5ItojeepE1CVj9wP1uHHNqnfYM5KjsOdV9/1zVdV/zDCduPKSqhDctFxBNVq6yCTQP2BAB7it5EEPFdCttoyZMEVjoSAB@yjikcRVFaODGOghX3MAha5RGdeMVMkjxAoewVBJDESNZf9CRpvIg@hWN0DeK7DZ@lPBR0njO5OG6b4zAbILpyS8UvwfFmkxKo1xmdzj/73R0Ub94aORCyWQYRFOU18G7zdZxfpuxhkDhOCZRzOMKzWZO3WiQgrqxeFNqNBKHwk8OJTgObTwPGqIh1rSpzTdeq1Qk17G6P9Sl@CBvMZVbNNaqEhnxmhDynTWa6tl1Dusf5XJCZmlkWs8UD9YEbiBlZft0xLMu0ag6htmFkBtGwTdchhD73B4PXoZSeMaEvQZx@USnLMaFdv@c/5VyGceGdISMFl@E/ "Perl 6 – TIO Nexus") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 :16( # convert from base 16 1 ~ # Str concatenated S/_/Z/ # replace an underscore with an invalid base 16 character ) // # defined or $_ # the input unchanged } ``` [Answer] ## Perl, 27 bytes *-1 byte thanks to [@ardnew](https://codegolf.stackexchange.com/users/3348/ardnew).* 26 bytes of code + `-p` flag. ``` $_=hex"1$_"if!/[^0-9a-f]/i ``` Supply the input *without* final newline. With `echo -n` for instance: ``` echo -n 05AB1E | perl -pe '$_=hex"1$_"if!/[^0-9a-f]/i' ``` **Explanation** This is pretty straight forward: `/[^0-9a-f]/i` is true if the input contains a character other than those allowed inside hexadecimal numbers. If it's false, `$_` (which contains the input) it is set to the converted value (the conversion is done by the builtin `hex`). And `$_` is implicitly printed thanks to `-p` flag. [Answer] # [Pyth](https://github.com/isaacg1/pyth) - 9 bytes ``` .xi+1z16z ``` Same idea as [fliptack's answer](https://codegolf.stackexchange.com/a/105344/47650). Try hexadecimal-decimal conversion else output the input. [Try it here!](http://pyth.herokuapp.com/?code=.xi%2B1z16z&input=da7aba5e&debug=0) [Answer] # Batch, 33 bytes ``` @(cmd/cset/a0x1%1 2>nul)||echo %1 ``` ## How it works A string is passed in as an argument, 1 is prepended to it, and the string is implicitly converted to decimal and printed. If the string is not valid hexadecimal, it is simply displayed. It should be noted that since batch math uses signed 32-bit integers, the biggest allowed username is `FFFFFFF`. `cmd /c` takes the next command, runs it in a new terminal, and exits. `set /a` performs math and implicitly displays the result in decimal when not stored to a variable. `0x1%1` tells set to prepend a 1 to the first argument (this is easy since all batch variables are strings) and indicates that the string should be treated as hexadecimal. `2>nul` silences any errors resulting from an invalid hexadecimal number `||` is a logical OR and performs the command on the right if the command on the left is not successful. The parentheses make everything up to this point one command. `echo %1` simply displays the first argument. [Answer] ## Common Lisp, 71 ``` (lambda(n)(or(ignore-errors(parse-integer(format()"1~A"n):radix 16))n)) ``` ## Tests Define function ``` CL-USER> (lambda(n)(or(ignore-errors(parse-integer(format()"1~A"n):radix 16))n)) #<FUNCTION (LAMBDA (N)) {10041D213B}> ``` Quote a list of expected inputs, as given by the question: ``` CL-USER> '("ba5eba11" -> 7421737489 "05AB1E" -> 17148702 "dec0de" -> 31375582 "Beef" -> 114415 "da7aba5e" -> 7960443486 "500" -> 5376 "DENNIS" -> "DENNIS" "Garth" -> "Garth" "A_B_C" -> "A_B_C" "0x000" -> "0x000") ("ba5eba11" -> 7421737489 "05AB1E" -> 17148702 "dec0de" -> 31375582 "Beef" -> 114415 "da7aba5e" -> 7960443486 "500" -> 5376 "DENNIS" -> "DENNIS" "Garth" -> "Garth" "A_B_C" -> "A_B_C" "0x000" -> "0x000") ``` Parse it and collect results ``` CL-USER> (loop for (in _ out) on * by #'cdddr collect (list in out (funcall ** in))) (("ba5eba11" 7421737489 7421737489) ("05AB1E" 17148702 17148702) ("dec0de" 31375582 31375582) ("Beef" 114415 114415) ("da7aba5e" 7960443486 7960443486) ("500" 5376 5376) ("DENNIS" "DENNIS" "DENNIS") ("Garth" "Garth" "Garth") ("A_B_C" "A_B_C" "A_B_C") ("0x000" "0x000" "0x000")) ``` Check that the expected outputs match the actual ones: ``` CL-USER> (every (lambda (x) (equalp (second x) (third x))) *) T ``` [Answer] ## C, 108 bytes ``` i;f(char*s){char*S=malloc(strlen(s)+2);*S=49;strcpy(S+1,s);sscanf(S,"%x%c",&i,&i)<2?printf("%d",i):puts(s);} ``` This is a function that takes the string as an argument and prints the result to STDOUT. ``` i; // declare i as an int f(char*s){ char*S=malloc(strlen(s)+2); // allocate space for a new string with 1 more char *S=49; // set the first char to '1' (ASCII 49) strcpy(S+1,s); // copy the original string to the remainder sscanf(S,"%x%c",&i,&i) // scan a hex integer followed by any char <2? // if less than 2 items were scanned (i.e. the hex // integer made up the entire string), printf("%d",i) // output the hex integer :puts(s);} // otherwise, output the original string ``` [Answer] # Python 2 - ~~63~~, ~~52~~, ~~50~~, 46 Bytes ``` n=input() try:n=int("1"+n,16) except:1 print n ``` This uses Python's [`int()`](https://docs.python.org/2/library/functions.html#int) which converts any string with its appropriate base into base 10. In this case, the string is the number 1 attached to the input. If the input is invalid (has characters other than `0123456789ABCDEF` (case-insensitive), it returns `ValueError`: ``` n = input() # Get input (with quotes) try: # Trying conversion to base 10 n = int("1"+n,16) except: # If invalid string for base 36, 1 # do nothing to n print n # Print result ``` [Try it here!](https://repl.it/EzQ6/6) Thanks to @FlipTack for saving 15 bytes! [Answer] # JavaScript: ~~46~~ 41 bytes ``` s=>/[^\dA-F]/i.test(s)?s:parseInt(1+s,16) ``` [Answer] # PHP, 42 bytes hex2bin() returns false if the input is not a valid hex string. This is shorter than using regex to look for non hex digits, but we need the @ operator because it's not silent when it fails. ``` <?=@hex2bin($s=$argv[1])?hexdec("1$s"):$s; ``` [Answer] # bash, ~~46~~ ~~35~~ 31 bytes ``` (echo $[0x1$1])2> >(:)||echo $1 ``` Save as a script, and pass the username as an argument. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 37 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Uses no built-in validation or hex-dec conversion. Requires `⎕IO←0` which is default on many systems. ``` {∧/(u←1(819⌶)⍵)∊d←⎕D,6↑⎕A:16⊥1,d⍳u⋄⍵} ``` Ungolfed: ``` { d ← ⎕D , 6 ↑ ⎕A u←1 (819⌶) ⍵ ∧/ u ∊ d: 16 ⊥ 1 , d ⍳ u ⍵ } ``` `d ← ⎕D , 6 ↑ ⎕A` *d* gets **D**igits followed by the first 6 elements of the **A**lphabet `u ← 1 (819⌶) ⍵` *u* gets uppercased (819 ≈ "Big") argument `∧/ u ∊ d:` if all elements of *u* are members of *d*, then:  `16 ⊥ 1 , d ⍳ u` find the indices of *u* in *d*, prepend a 1, and evaluate as base 16 `⍵` else: return the (unmodified) argument TryAPL online: 1. [Set `⎕IO` to zero, define a replacement for `⌶` (forbidden on TryAPL for security reasons), and set `⎕PP` (**P**rint **P**recision) to 10 for the large results](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20%u2395PP%u219010%20%u22C4%20I%u2190%7Bw%u2190%u2375%20%u22C4%20u%u2190%u2395UCS%20%u2375%20%u22C4%20%u237A%3A%20%u2395UCS%20u%u22A3%28e/u%29-%u219032%u22A3e%u2190u%u220A97+%u237326%20%u22C4%20%u2395UCS%20u%u22A3%28e/u%29+%u219032%u22A3e%u2190u%u220A65+%u237326%20%u22C4%20%u237A%u237A%7D&run) 2. [Try all the test cases](http://tryapl.org/?a=%7B%u2227/%28u%u21901%28819I%29%u2375%29%u220Ad%u2190%u2395D%2C6%u2191%u2395A%3A16%u22A51%2Cd%u2373u%u22C4%u2375%7D%A8%27ba5eba11%27%20%2705AB1E%27%20%27dec0de%27%20%27Beef%27%20%27da7aba5e%27%20%27500%27%20%27DENNIS%27%20%27Garth%27%20%27A_B_C%27%20%270x000%27&run) [Answer] # Ruby, ~~47~~ 44 bytes ``` p gets=~/^[a-f\d]+\s$/i?('1'+$&).to_i(16):$_ ``` ~~I *could* remove 3 bytes by changing `puts` for `p`, but I feel like the output would be considered wrong since it has a newline at the end.~~ Edit: Changed `puts` for `p` as trailing newlines are typically accepted, thanks @Mego. [Answer] ## [Japt](http://ethproductions.github.io/japt/), 11 bytes ``` +`0x1{U}`ªU ``` [Try it Online!](https://tio.run/nexus/japt#@6@dYFBhWB1am3BoVej//0oGpolJhqlKAA) Big thanks to ETHproductions! [Answer] # REXX, ~~49~~ 48 bytes ``` signal on syntax pull a a=x2d(1||a) syntax: say a ``` The `signal on syntax` tells the interpreter to jump to the label `syntax` whenever a syntax error occurs. The program tries to reassign `a` with a hex-to-decimal converted version with a leading 1, but jumps to the `syntax` label if that fails. If the conversion does pass, it simply ignores the label and outputs the reassigned variable. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` k6↔=[1pH ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrNuKGlD1bMXBIIiwiIiwiYmFnIl0=) ``` k6↔ # Remove non-hex chars from input =[ # If it equals the original 1p # Prepend a 1 H # Convert from hexadecimal ``` [Answer] # [Whython](https://github.com/pxeger/whython), 34 bytes ``` lambda n:eval("_"in n or"0x1"+n)?n ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY7BCoJAEIbvPsUwJyWF9SBFUKEl0cVLxwpZcxcFW2Xdyl6lLkJEz9TbtK3N5f_-f36GebyvxU0VteiffLZ_nRX3Jh-s6CnLKYgpu9DKxhRLAQJqiaTzcSSchfg377yW0IJe7yzAjAYso76PrjYkCCM_NpizI8mZwYgxPmR0TH99YwJCjK7iJNlsDa6pVIWhMI3S5XCyI7p4mFqgp5GlULZkjbRbxwX05uiCsVwHjjN82PeDfgE) ### Explanation The `?` operator in Whython returns the value of its left operand, unless the left operand raised an error during execution, in which case it returns the value of its right operand. So in theory, all we have to put on the left is `eval("0x1" + n)`: prepend a `1` and evaluate as a hexadecimal literal. In practice, since Whython is based on Python 3, we run afoul of the Python 3 feature that underscores can be used as separators in numeric literals. Thus, an input like `A_B_C` does not error, but is treated as if it were `ABC`. That's not what we want. We need to make inputs with underscores cause errors too. Thus, we pass the following to `eval`: ``` "_" in n or "0x1" + n ``` If `n` contains any underscores, `"_" in n` is `True`, the `or` short-circuits, and we're left with `eval(True)`, which errors because `eval` expects a string. If there are no underscores, `"_" in n` is `False`, and we go on to eval the hex-literal string as usual. [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), 35 bytes ``` param($v)(($h="0x1$v"|iex),$v)[!$h] ``` [Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6FSpqmhoZJhq2RQYahSplSTmVqhqQMUjFZUyYj9//@/elKiaWpSoqGhOgA "PowerShell – TIO Nexus") or [**Run all test cases!**](https://tio.run/nexus/powershell#RY1PC4JAEEfv@ymmZQOFhPUgnYLUJITo4jFCJp1SzD/oJoH52W3bS7fH4/1mhKJBhTjQADvYW4zf0KMbui5nXHp@4EYcgPGcMpmTwYDorsFY3OKv160npZHaHqLzOU64piP2qjAjPw3S0JB8S50ymzHxf/2BNUwQN2NbkRO2dY1NDo7fP141NepUDgpECk6S9WWngmebVTAtHfZYW2K0LUsUO33YFSP/lPS2N1peVqK4LjPMyxc "PowerShell – TIO Nexus") ### Explanation 1. Take parameter (`$v`) 2. Create a two-element array where the first element (`0`) is the result of a string containing `0x1$v` piped into `Invoke-Expression` (`iex`), while simultaneously assigning this value to `$h`. If the conversion fails, `$h` will remain `$null`. 3. The second element of the array is the original parameter. 4. Index into the array with the boolean `-not` value of `$h`. Whatever `$h` is will be implicitly converted to `[bool]` (`$null` in the case of an invalid conversion will become `$false`, a positive integer in the case of successful conversion will become `$true`) before being negated, which is then implicitly converted to `[int]` by the array indexer `[]` (`$true` will be `1`, `$false` will be `0`), thus resulting in the first element of the array (the conversion result) chosen if the conversion was successful, and the second element chosen if the conversion was unsuccessful. [Answer] # Scala, 40 bytes ``` s=>try{BigInt("1"+s,16)}catch{case e=>s} ``` Usage: ``` val f:(String=>Any)=s=>try{BigInt("1"+s,16)}catch{case e=>s} f("ba5eba11") //returns 7421737489 ``` Explanation: ``` s=> //define a anonymous function with a parameter called s try { //try... BigInt("1"+s,16) //to contruct a BigInt from "1" prepended to the number, parsing it as base 16 } catch { //if the constructor throws an exception case e => //in case of an execption which we'll call e s //return s } ``` [Answer] # C#, 58 bytes ``` u=>{try{u=Convert.ToInt64("1"+u,16)+"";}catch{}return u;}; ``` Ungolfed with test cases: ``` using System; class Class { public static void Main() { Func<string, string> convert = u=> { try { u = Convert.ToInt64("1" + u, 16) //Prepends "1" and tries to convert the string to and integer using base 16. + ""; //Appending an empty string converts the integer to a string. Shorter than calling .ToString() } catch { } //If the conversion fails catch the exception and discard it. return u; //Return the result, or the unmodified input if the conversion failed. }; Console.WriteLine(convert("ba5eba11")); Console.WriteLine(convert("05AB1E")); Console.WriteLine(convert("dec0de")); Console.WriteLine(convert("Beef")); Console.WriteLine(convert("da7aba5e")); Console.WriteLine(convert("500")); Console.WriteLine(convert("DENNIS")); Console.WriteLine(convert("Garth")); Console.WriteLine(convert("A_B_C")); Console.WriteLine(convert("0x000")); Console.Read(); } } ``` [Try online](http://csharppad.com/gist/4093fe2118616dda627dbdf61b6b113e) [Answer] ## Dart, 51 bytes ``` (s)=>int.parse('1$s',radix:16,onError:(_)=>null)??s ``` [Try it here](https://dartpad.dartlang.org/e7018a1db00e744d2511458a71701298) Most of the overhead comes from named parameters... Oh well! At least Dart lets you be dynamically typed, if you want to :D [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes ``` "0x1ÿ".EDн>ΘI'_å~_× ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fyaDC8PB@JT1Xlwt77c7N8FSPP7y0Lv7w9P//kxJNU5MSDQ0B "05AB1E – Try It Online") ]
[Question] [ Every phone needs a calculator app. Because of the limited screen real estate, the developer of mine has decided to save some buttons. Instead of having two dedicated bracket buttons - one for open `(` and one for close `)` - there is just a single bracket button `()`. It looks something like this: [![My phone's calculator app](https://i.stack.imgur.com/b9XvQl.jpg)](https://i.stack.imgur.com/b9XvQl.jpg) When the button is pressed, it places a bracket. Based on the input given so far, it predicts whether the bracket should be open `(` or close `)`. By trial and error, I have found the button to follow these rules: * If there are no unmatched brackets, the next bracket will **always** be open `(`. * Else, if the last character is a numeral `0123456789` or close `)` bracket, the next bracket will be close `)`. * Else, if the last character is an operator `+-*/` or open `(` bracket, the next bracket will be open `(`. ## The challenge Based on the given input and the rules mentioned above, predict whether the button places an open `(` or close `)` bracket. ## Input Either a string, an array of characters, or anything equivalent. The input will **only** contain the following characters\*: `0123456789+-*/()` ## Output An open `(` or close `)` bracket **or** any two consistent values representing them. ## Test cases ``` "" -> "(" "(1+" -> "(" "(1+(2/3" -> ")" "(1+(2/3)" -> ")" "(1+(2/3))-8" -> "(" "(1+(2/3))-8*(" -> "(" "(1+(2/3))-8*((5" -> ")" "(1+(2/3))-8*((5)" -> ")" "(1+(2/3))-8*((5))" -> "(" ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins. ### Note \* The actual calculator also includes the symbols `.%`, but you don't need to care about those. [Answer] # [JavaScript (Node.js v11.6.0)](https://nodejs.org), 48 bytes ``` a=>/k/.test(eval("try{eval(a+')')}catch(e){e}")) ``` [Try it online!](https://tio.run/##jc69CsIwFMXx3acIZ@m9ljaoCC71XUJM/QqNNKEgpc8erYtQEe6ZzvAb/jczmGj76yNVXTi53DbZNEd913VyMZEbjCek/jl@nikLLniyJtkLOR7dBOZsQxeDd7UPZ2oJUMsxK60VCKsFpU0JOaWt3uGH8j/KkFOuDpAFzHRNkFPaQxYw03ezmDK@AfkF "JavaScript (Node.js) – Try It Online") We try to append a character `')'` to the end of expression and `eval` it. Node v11.6.0 (as current version on TIO) may: * Calculate the expression if the expression is valid + The calculate result may only contain characters `/[0-9INafinty]/` * Report error `SyntaxError: Unexpected token )` if the `)` should not be there * Report error `SyntaxError: Unexpected end of input` if the `)` is valid there So we just need to check if the result contains letter `"k"`. [Answer] # [C (clang)](http://clang.llvm.org/) on Linux, ~~82~~ ~~79~~ ~~66~~ 62 bytes ``` c;f(*x){for(c=0;*x;++x)*x&22?:*x&1?--c:++c;c*=*--x&16|*x==41;} ``` [Try it online!](https://tio.run/##bZBLTsMwEIb3OcXIVZE9riEJFKEa0wtwg6aLyEnaSMFFTooshZw9OIaiUjqLeXzjx/yjhW5ysxtHLSuKjvXVwVKtYolOcu4Yups0Xa98SNZC6BXnWmpUKIQnj5/olHpI5DDOaqObY1E@t11RH273L1FUmw7e8trQKcntTi9A73ML6POPzZZBH4G3qYtd2XbtZgsKenglZOEdTfgp0vTu/jxnfwomni5rpP8JXV5j7Cr8oZc24RgGGeb2i4JJGiJM0/vRgwj5LUaGivOTynCDhhaTv@Td@gcqSuYFZGTetBnJjP/Db@r85BC8LbujNRDLaBi/AA "C (clang) – Try It Online") Expects a nul-terminated ASCII wide string (4 bytes per character). Returns false (zero) for open bracket and true (nonzero) for close bracket. * Thank you to @AZTECCO for golfing off 13 bytes! * And thank you to @jdt for golfing off 4 more bytes. (This required switching to clang; the original answer was for gcc.) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` „()S¢Ëžh')«Iθå≠~ ``` -2 bytes by outputting `1` for `(` and `0` for `)`. [Try it online](https://tio.run/##ATAAz/9vc2FiaWX//@KAnigpU8Kiw4vFvmgnKcKrSc64w6XiiaB@//8oMSsoMi8zKSktOCo) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/Rw3zNDSDDy063H10X4a65qHVled2HF76qHNB3X@d/9FKSjpKGobaEFLDSN8YwdJEYmrqWqDytDTQ@RqmmCKaWIQ0lWIB). **Explanation:** ``` „() # Push string "()" S # Convert it to a character-list: ["(",")"] ¢ # Count the "(" and ")" in the (implicit) input-string Ë # Check whether both are the same žh # Push builtin "0123456789" ')« '# Append a ")" Iθ # Push the last character of the input-string å≠ # Check that it's NOT in the string "0123456789)" ~ # Bitwise-OR to check if at least one is truthy # (after which this is output implicitly as result) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes ``` ‛()$vO≈9ʀ\)J?tc∨ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%80%9B%28%29%24vO%E2%89%889%CA%80%5C%29J%3Ftc%E2%88%A8&inputs=%27%281%2B%27&header=&footer=) 0 for `(` and 1 for `)` [Answer] # [Python 2](https://docs.python.org/2/), 48 bytes ``` lambda L:"0">cmp(*map(L.count,"()"))*L[-1:]!=")" ``` [Try it online!](https://tio.run/##ddBNC4JAEAbg@/6K7b04Y9onQQjrL/DorTzYh7Sgu0ttQb/elIigdG7DM7zDjHv6izWrtlL7ti6bw6mUWYIF0mPjKGxKR9nsaO/GRyAGc5jt4mVSTBQYba6CIADkX8WpBEGAllOME63ma/wQf4kxThxvMRzYU0gYJ9pgOLCnfucYdfYO7I6e3VytPWFvwKKyV@mlNjJPhNSRVf3bzo@yjvxn7h3KQrqrNl3PhF1FmgulLIv2BQ "Python 2 – Try It Online") Based on @wasif's Python 3 answer; shortened using `cmp` which is not available in Python 3. True for "(" False for ")" [Answer] # [Perl 5](https://www.perl.org/) -nMv5.10, 23 bytes ``` say!/[\d)]$/||eval&&!$@ ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJRPzomRTNWRb@mJrUsMUdNTVHF4f9/Lg1DbRDWMNI3htGacIamrgUyW0sDladhis7XxBDQ/JdfUJKZn1f8Xzfvv66vqZ6hgZ4BAA "Perl 5 – Try It Online") Prints true/1 for `(` and false/empty string for `)`. And for eight extra bytes we can print `(` and `)` like this: [Try it online](https://tio.run/##K0gtyjH9/784sVJRPzomRTNWRb@mJrUsMUdNTVHFwV5dQ91KXVP9/38uDUNtENYw0jeG0ZpwhqauBTJbSwOVp2GKztfEEND8l19QkpmfV/xfN@@/rq@pnqGBngEA "Perl 5 – Try It Online") 31 bytes. The `eval&&!$@` checks if the input expression have balancing parentheses by using the Perl compiler to check if it compiles. [Answer] # [GNU AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 75 bytes ``` BEGIN{RS=".|"}RT~/\(/{++n}RT~/\)/{--n}END{print n?RT~/[\)0-9]/?")":"(":"("} ``` [Try it online!](https://tio.run/##SyzP/v/fydXd0686KNhWSa9GqTYopE4/RkO/Wls7D8LW1K/W1c2rdfVzqS4oyswrUcizB4lHx2ga6FrG6tsraSpZKWmAce3//wA "AWK – Try It Online") ``` BEGIN{RS=".|"} ``` Starts reading the input one character at a time, which are stored in the `RT` variable, by the way. ``` RT~/\(/{++n} RT~/\)/{--n} ``` If the character is a `(`, increments `n` by one. If it is `)`, decrements `n` by one. ``` END{print n? RT~/[\)0-9]/? ")" :"(" :"(" } ``` If `n` equals zero, i.e., there are as many `(` as `)`, prints `(`. If `n` is different from zero, evaluates the last character (registered in `RT`). If it is a number or `)`, prints a `)`, otherwise, prints `(`. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 30 bytes ``` {(^"(*+-/"?*|x)>~+/-/x=/:"()"} ``` [Try it online!](https://ngn.codeberg.page/k#eJx1z9EKgjAUxvH7PcU4dHGmjGkRxEb2IGLYjRAFgXgxMX323BRTt53bH3yHfyU7vANGMRdwi76aZUMsuNBXIQEZ9IQ0sjvk7VDLilKqVfl5KSyrx/OttGpVzYqeNDmAos4lhRFMYwcXwaM4bTRdC1vTVhi/LJjsJcLZPIJna86aEfvPL4bGNSIIgFvKMwoIxLaGycbuiP2JQZhMrn9w7g3TGOwfnIrDNNo0+AOtr2Ho) Returns `0` for `"("` and `1` for `")"`. * `~+/-/x=/:"()"` determine whether or not the input contains a balanced number of parenthesis, i.e. that the number of `"("`s minus the number of `")"`s is 0 * `(^"(*+-/"?*|x)` determine if the last character is one that should be followed by a `"("` (i.e. one of `"+-*/("`) or not * `(...)>...` use `>` as material nonimplication (i.e. only return a truthy value if the left side is truthy and the right side isn't) [Answer] # JavaScript (ES6), ~~52~~ 51 bytes Expects an array of characters. Returns `0` for `(`, or `1` for `)`. ``` a=>a.map(c=>q+=-(d=c>-1,C=c==')')|c<')',q=0)|q&&d|C ``` [Try it online!](https://tio.run/##lc@xDoIwEMbx3acgN8Cd0FY0Jg5eFx7DODQFDAYpiHHi3StMJmpMesu3/Ib/Xc3TjPbe9A/RubLyNXvD2sib6dGyHlIWWLLVIs8KtswJJTTZ4zzZwBuahjgup8Jb142urWTrLljjSUoJEH3emShSKgKE1Q@PeQqBHrdqB9@e/nmCQE/iAAE9i18jBHrcQ0DP4uc/wjzBu8e/AA "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array of characters a.map(c => // for each character c in a[]: q += // update q -( // which keeps track of the balance of parentheses d = c > -1, // d = digit flag C = c == ')' // C = closing parenthesis flag ) // decrement q if C is set | c < ')', // or increment it if c is '(' q = 0 // start with q = 0 ) | // end of map() q && // return 1 if q is not 0 (unbalanced parentheses) d // and the last character was either a digit | C // or a closing parenthesis ``` [Answer] # [Zsh](https://www.zsh.org/), 39 bytes Exits truthy if a `(` should be inserted, falsy if a `)` should be inserted. ``` eval ${(s..)1//[^()]/;}||${(M)1%[0-9)]} ``` [Try it online!](https://tio.run/##fc3dSgMxEAXg@zzFYVghY03XtQiVRfEFvPC6VGibWTcQNtKsP9jus68JCIJ2zd3kO3PmM7ZjlD689JCPXjor9tmHrWo061HeNh7FQcf5nKuyXD1pXpf1cDymvweuzlaX5obXw8hKvbfOC/aysTB7eNdJDRuUAlI7jAGlnftHLg63GYeBErkGDYqqRt9Kl2ZAdm0AxTa8eoutoFhcwEXonBYf5b8Q51DjlLKhk5EIf565A6Uq0tWMpklflQv6RfxDTNPEZkmnCzOda5omfU2nCzPlm1OU7LvwCw "Zsh – Try It Online") The `eval` handles the matching (getting rid of non-`()` characters, and spawning nested subshells with spaces and `;`s to prevent `()()` or `(( ))` from erroring). The `${(M)1%[0-9)]}` simply tries to run the last character of the input as a program if it is in `0123456789)`, failing. `||` brings the whole logic together. [Answer] # TI-Basic, 71 bytes ``` Prompt Str1 For(I,1,length(Str1 sub(Str1,I,1→Str2 O+(Ans="(→O C+(Str2=")→C End 0 If O≠C not(inString("+-*/(",sub(Str1,length(Str1),1 Ans ``` Output is stored in `Ans` and displayed. Outputs `0` for `(` and `1` for `)`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 bytes ``` ċⱮØ(Iɓ”)ØD;faƒ ``` [Try it online!](https://tio.run/##y0rNyan8//9I96ON6w7P0PA8OflRw1zNwzNcrNMSj036f7hdM/L/fyUlHSUNQ20IqWGkb4xgaSIxNXUtUHlaGuh8DVNMEU0sQppKAA "Jelly – Try It Online") *-1 because I actually looked at other solutions and remembered `ċ` exists* Returns falsy (empty list) for open or truthy (nonempty list) for close. Took a hell of a lot of permuting to get here from `=€Ø(ISaṪe”)ṭØD¤Ɗ`. ``` ØD; Concatenate "0123456789" and ”) a closing parenthesis. f Keep only its elements which are also elements of ɓ aƒ the input reduced LtR by logical AND starting with: ċⱮØ( Count the opening and closing parentheses in the input, I and subtract the opens from the closes. ``` [Answer] # [Haskell](https://www.haskell.org/), 64 bytes ``` o i=elem(last i)"+-*/("||let[o,c]=[[1|c<-i,c==p]|p<-"()"]in o==c ``` [Try it online!](https://tio.run/##BcFBCoAgEADAr8jSYa0krGv7EvEgIrS0qZRH/24zV/juJDJGUUxJ0oMSvqZYw2LmDaF3Sc2VNXpyzvZ4Gl4jUfW9ngZQg@esClEcT@BM9eXcpqIA7YL7dsD4AQ "Haskell – Try It Online") [Answer] # C# (8.0), ~~76~~ ~~68~~ 64 bytes *-3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) -1 byte thanks to [Aaroneous Miller](https://codegolf.stackexchange.com/users/101522/aaroneous-miller)* ``` bool p(char[]i)=>i.Sum(x=>x<42?x*2-81:0)==0||i[^1]<48&i[^1]!=41; ``` [Try it online!](https://tio.run/##bY5RS4RAFEaf119xGyLv3dTUDGTdcYl97SEq6ME1MJvWgc1ZZiYwXH@7RUEh7cvHOefpq41fGzmOz0rtYI91U@milMRzGdy/v2HH826ZxKtuHvtptAiJ8/BwkMVTVC6T9OwbTngSZaOxWrbbogQrjF1XRhjg0Dszxjz4WozOfwHji8uJ0NTIT5k39Tn@L3h1rNHRSMwZMudVaVHVDf58BQOy/btLzmytWqN2InjU0oob2QpkfTiAn0MfDcw7ZRvWm2HDWHBbvdzJbWMxDgm8PZrgQV1rXX0gEazARXfhkkuZM34C "C# (Visual C# Interactive Compiler) – Try It Online") Takes not-null (but it might be empty) array of characters and outputs `true` for `(` and `false` for `)`. Ungolfed: ``` bool p(char[] input){ int sum = input.Where(x=>x<42) // take only brackets .Select(x=>x*2-81) // replace '(' with -1 and ')' with 1 .Sum(); // sum them if(sum == 0) // if sum is 0, brackets are balanced return true; // when left condition in || operator is true the right one isn't checked // this is beneficial for us because it prevents from taking last element // of empty array - empty input will always have balanced brackets char lastChar = i[^1]; // takes last character (this notation requires C# 8.0) return // return true (opening bracket) IF: lastChar < 48 // last char is '/','*','-','+','(' or ')' && // AND lastChar != 41;// last char isn't ')' } ``` [Answer] ## php 4 (83 chars) Edited because the initial 67 chars answer was not a function, it was a single imperative line : Using a traditional function allowing to call *f($input)*, so the answer is printed to stdout : ``` function f($a){$s=count_chars($a);echo$s[41]-$s[40]&&$a!=chop($a,')0..9')?')':'(';} ``` ## php 7.4 (73 chars) Using an arrow function allowing to call *$g($input)*, the answer is returned by *$g* : ``` $g=fn($a)=>$a!=chop($a,')0..9')&&($a=count_chars($a))[41]-$a[40]?')':'('; ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` ∨⁼№θ(№θ)№(*+-/§θ±¹ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO/SMO1sDQxp1jDOb8UyC/UUVDSUNLUUUBwNZU04XwlDS1tXX0lHQXHEs@8lNQKkAK/1PTEklQNQ00QsP7/X8NQ@79uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Outputs `-` for `(`, nothing for `)`. Pretty output can be obtained by prefixing `§)(` (equivalent to `AtIndex(")(", ...)`. Explanation: Port of @wasif's Python answer. ``` № Count of ( Literal `(` θ In input string ⁼ Is equal to № Count of ) Literal `)` θ In input string ∨ Logical Or № Count of §θ±¹ Last character of input string (*+-/ In literal `(*+-/` Implicitly print ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 39 bytes ``` (?>(\()|(?<-1>\))|.)*$(?<-1>(?<=[\d)])) ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX8PeTiNGQ7NGw95G19AuRlOzRk9TSwXCA5K20TEpmrGamv81ueI07BWB8npaXBr/uTQMtUFYw0jfGEZrwhmauhbIbC0NVJ6GKTpfE0NAEwA "Retina 0.8.2 – Try It Online") Outputs `0` for `(` or `1` for `)`, but link is to test suite that maps the results for you. Explanation: ``` (?>(\()|(?<-1>\))|.)*$ ``` Atomically count the `(`s and `)`s. (It needs to be atomic otherwise the `.` messes up the count of `)`s, but it's still golfier than `[^()]`.) ``` (?<-1>(?<=[\d)])) ``` Test whether there is an unclosed `(` and the last character is a digit or a `)`. [Answer] # [Flex](https://github.com/westes/flex), ~~86~~ 85 bytes ``` %{ p;l; %} %% [(] l=!++p; [)] p-=l=1; [0-9] l=1; [-+*/] l=0; \n putchar(!!p*l+40); %% ``` To run this code, copy the above into a file named `calc.l` and run the following (on linux/bash): ``` flex calc.l gcc lex.yy.c -o calc -lfl for t in "" "(1+" "(1+(2/3" "(1+(2/3)" "(1+(2/3))-8" "(1+(2/3))-8*(" "(1+(2/3))-8*((5" "(1+(2/3))-8*((5)" "(1+(2/3))-8*((5))"; do echo -n "\"$t\" -> " echo $t | ./calc echo done ``` and it will output either `(` or `)` to `stdout` for each test string. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 23 bytes ``` k(↔k(øo[tkd\(+$ck($i|\( ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=k%28%E2%86%94k%28%C3%B8o%5Btkd%5C%28%2B%24ck%28%24i%7C%5C%28&inputs=%27%281%2B%282%2F%27&header=&footer=) ``` k(↔ # When you remove all but `()` from the input k(øo # Then remove that until there is no change [ # Is there nothing left? \( # If so, opening bracket | # Else... t # Is the last character of the input... $c # Contained in... kd\(+ # Digits + `(`? k($i # Index that into `()` ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~47~~ 43 bytes ``` ->e{!!e[/[\d)]$/]&&e.count(?()>e.count(?))} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y61WlExNVo/OiZFM1ZFP1ZNLVUvOb80r0TDXkPTDs7W1Kz9X6CQFq2kFGuvpKlkpaShpKCsgA507RSAElxghRqG2rjVoinUMNI3xq4YpFATVaEm8So1dS2wKMZiOUillgaGWpwqNUzR1OKwHaQSzb34VKIqhdj@HwA "Ruby – Try It Online") Outputs *True* for `)`, *False* for `(`. * Thanks to @Dingus for the insights and 4 Bytes saved To choose `)` two conditions must hold: `!!e[/[\d)]$/]` # match($ at the end) the set of characters [numbers, ')']. And double negate it to transform *nil*(no match) to *false* else *true* `e.count(?()>e.count(?))` # open brackets can be equal if balanced, else more than closed ones in which case the second condition is met. [Answer] # PHP (8.0), 110 bytes ``` <?php $a=$argv[1]; $b=ord($a[-1]??''); die($b>=47||$b==41&&substr_count($a,'(')>substr_count($a,')')?')':'('); ``` [Try it online!](https://tio.run/##ZYpBDoIwEADvfceG3VWJqWI01tKHEGJaIeJFmgKe@Ptaz17mMDNxiCI3F4eowFvw6flpdGsUBDumjsA3pW6dQ2SjuldPEGpbndc1d1vpopiWMM3p/hiX95zvHRJy/ScZ2WVcf9WICOktHfZH5vKyITrxFw "PHP – Try It Online") Ungolfed: ``` <?php $a = $argv[1]; // Get the binary value of the first byte of the last character $lastCharAsciiCode = ord($a[-1] ?? ''); // If the last character in the string is either 0-9 (47-57) OR Closing parenthesis (41) if ($lastCharAsciiCode >= 47 || $lastCharAsciiCode == 41) { // If we have more opening parenthesis than closing, return closing. if (substr_count($a,'(') > substr_count($a,')')) { die(')'); } } // Return opening by default die('('); ``` [Answer] # [R](https://www.r-project.org/), 57 bytes ``` function(x)sum((x=="(")-(x==")"))&&grepl("[)0-9]",rev(x)) ``` [Try it online!](https://tio.run/##pdBNC4JAEAbge79imUBmSimLoA4GHerUqY@TiIRsJdgqu2v47027aRqlwxzmMDzDOzIXPNN@cpFc6DtXofKLDqJYcSe/piLQYSwwI5U@EDPHAQSy3gMBkWHcJE8iBJem1soDU/JnsUztKCotVRKFGgFMAHJd2/OIDVm9rDUrbjGH7Tb743bwC4j2@IvZDcTZZN6CliCV4Olw/sujZrC7R9aygeweuARH@EH2BXFRI3slLr3aJ/t7VbAaOH8B "R – Try It Online") Input is an array of characters; outputs `TRUE` if next parenthesis is close (`)`), `FALSE` otherwise. [Answer] # [Rust](https://www.rust-lang.org/), ~~107~~ 104 bytes ``` |s:&str|(|(n,x)|n==0||x)(s.chars().fold((0,true),|v,c|(v.0+match c{'('=>1,')'=>-1,_=>0},c<'0'&&c!=')'))) ``` [Try it online!](https://tio.run/##jVLRbpswFH3nK278EK5XhySrqk2k5GHT3qf1AyLkmAaVGIYvbaTAt2fXhDRVV6T6ARsf33OOz3XdODo1zoCjbRznZRz/aLI/Jt2ugszCPs0tSjhCYQiy5NS6eOqobrFFqw6ytUmyaNuDRBfpXVo7lFFWFlvEhaK6MVK1z0q3@BwtbvYp6R3oY4hhsl6qUPI0W6pNsl50St@Hi3A61ZOE96WUJ4BVAJCVNRS5NZDbqz9eeFNRUeonPzHuvEc@DzCfgzcPZBzplK@V1eWey6uGetzfA/tfBeZQGU1mKyGBis2bTQ/g1FNGjX2p0wqlXPWFVZ1bmqA4xvfLbx3M1iDUmZcPXKR/HYxuiEUbqykv7atkbVxTEOtkOH1f9NszDyeuUoU9i911cOxY6oyzZDYsfZCdKZw5cmTd4JLpfu6MfoL0kTvn6DWHHk2dMzVtzN8JjtC8CcUTdkEX@GfwNh0fTgz@FUifAj4Q231Uvv2XJvgb7xuC3N@4D9NVRU4o@tgGq9h//cgpsuZA3MtL5hFz7odp0z8cbnEoQt4pN@WLNVuU6hP1lzdpaYfLK9xXyqA7CQH/DW8RRSBweSPGIfw6vxXvIHmFpBiH5Oy7@JjQQ19QjEN4Jz4m9JDXHIOkGAj/AQ "Rust – Try It Online") `true` for `(` and `false` for `)` ## Ungolfed ``` |s: &str| { // Iterate over all chars, folding from left let (paren_counter, ends_with_op_or_open) = s.chars().fold( (0, true), // Initial value for fold |(n,_), character| ( // Increment for opening braces and decrement for closing ones n + match character { '(' => 1, ')' => -1, _ => 0 }, // true for +-*/( but not for 0123456789) character < '0' && character != ')' ) ); // Return true if parentheses are balanced or the string ends // with an operator or open parenthesis, false otherwise paren_counter == 0 || ends_with_op_or_open } ``` [Answer] # Javascript, 90 chars ``` s=>s.replace(/.*?([\d)])?$/,(m,c)=>")("[s.replace(/[()]/g,m=>t+=m=='('||-1,t=0),+!(t&&c)]) ``` ## Test: ``` f=s=>s.replace(/.*?([\d)])?$/,(m,c)=>")("[s.replace(/[()]/g,m=>t+=m=='('||-1,t=0),+!(t&&c)]) console.log(` "" -> "(" "(1+" -> "(" "(1+(2/3" -> ")" "(1+(2/3)" -> ")" "(1+(2/3))-8" -> "(" "(1+(2/3))-8*(" -> "(" "(1+(2/3))-8*((5" -> ")" "(1+(2/3))-8*((5)" -> ")" "(1+(2/3))-8*((5))" -> "(" `.split` `.filter(x=>x).map(x=>x.match(/"(.*)".*"(.)"/)).map(([,x,r])=>f(x)==r).every(x=>x)) ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 73 bytes ``` ,[+>-->[+]+[->+[--->]<<<]<[->>+<<]>>>[->>-<<],]<[,>>]->[+>[>]--<<<++<+]>. ``` [Try it online!](https://tio.run/##FYpBCoBADAO/s0u2XryWfKT0oIIgggfB99fsIWQmZH@36zm/464aAZoxkAijIkl3T5cSApITTTi0DjLnn6HW6IAjuVS1hrX3Hw "brainfuck – Try It Online") Outputs truthy for `)` and falsy for `(`. Note that this will fail if there are 256 unmatched `(`. [Version which outputs '(' or ')'](https://tio.run/##HYyxCoBADEN3v@QkVxcnoeRHSgcVBBEcBL//zFkITUL7tmc97@Pdr9ZqgGYMJMIoKaS7pysSMiS7NdmqtpLZ7xnaKh1wJIehM7rcLPSIf1JwHcWPqmJNrZWCecTyAQ "brainfuck – Try It Online") (not particularly golfed) **Explanation:** ``` ,[ ,] loop until end of input +>-->[+]+[->+[--->]<<<] paren depth calculation: (brute forced black magic) '(' => 1 ')' => 255 '0123456789+-*/' => 0 <[->>+<<] accumulate paren depth counter >>>[->>-<<] preserve a data cell uniquely identifying last character <[,>>] if depth counter is nonzero move to cell identifying last character ->[+>[>]--<<<++<+]>. character to final output calculation: (brute forced black magic) '+-*/(' or \0 => 0 '0123456789)' => nonzero ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 17 bytes ``` $>^pNa&`[\d)]$`Na ``` Takes the partial expression as a command-line argument. Outputs `0` for open parenthesis, `1` for close parenthesis. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhYbVeziCvwS1RKiY1I0Y1US_BIh4jDpaCUNQ20NI31jTU1dCy0NpVioBAA) [Verify all test cases!](https://ato.pxeger.com/run?1=m724ILNgebSSblGOUuzC6qWlJWm6FhtV7OIK_BLVEqJjUjRjVRL8EiHiS2sVfBXSIewFN5O4NAy1QVjDSN8YRmvCGZq6FshsLQ1UnoYpOl8TQ0ATYhUA) ### Explanation ``` $>^pNa&`[\d)]$`Na a is command-line arg; p is "()" (implicit) ^p Split p into a list of two parenthesis characters Na Get the count of each parenthesis in the argument $> Fold on > (1 if there are more open than close parens, 0 otherwise) (Because we "can expect the input to be typed on the calculator," there will never be more close than open parens) & Logical AND ` ` The following regex: [\d)] Either a digit or a close paren $ followed by end-of-string N Count matches in a The argument ``` Thus: * If the parentheses are balanced, `$>` gives `0`, which short-circuits the AND and returns `0` (open paren) * Otherwise: + If the argument ends with a digit or `)`, return `1` (close paren) + If it doesn't, return `0` (open paren) To get `(` and `)` as output, wrap the whole thing in `(p` ... `)` for +3 bytes. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 15 bytes ``` a=>eval(a+')m') ``` [Try it online!](https://tio.run/##jc7BTsMwDIDhe5/C8iU226gAIaFN3Y0nQJwQhyh1u0CXVFk2dZr67CXlgjQESm5WPsv/hz7pgwm2jyvna5naatLVVk66I71QvFc8bYq97qGCSwGgXs4u6uE5BB/W8Opk6MVEqSH6T3HAag2K1PI/aWtx0TZWwow54bFojs5E6x00NPD3oRjOcIE2jRsYwehodiTpC4LEY3CQkt7kHca0XBjvDr6T28631BAiXD9mKEtAwmtKdwvMp3RfPuAvyn9RxnzKqyfMC5jpDWE@pUfMC5hpas6mjD8B0xc "JavaScript (Node.js) – Try It Online") [tsh](https://codegolf.stackexchange.com/a/237465/) claim that "My function return results via throwing an exception" [Answer] # MATLAB, 65 bytes ``` @(x)all([sum(x(x<42)*2-81),feval(@(a,b)a(end)~=b,[0,x],'/*-+(')]) ``` [Try it online!](https://tio.run/##bcixDoIwGMTx3RfpXWmDVE1IlIT3IAwf2k4IA0o6@epVFxNil8v9f/P1IatPqUWkjCO65XlHRLwcHbWzdUUT/CojWogZKPDTja9mMN3exN6oUtsCij1TaGRazrsApfhdVMXvwJWHTXBbtPUfaGQIpywyrx9Obw "Octave – Try It Online") Anonymous function. Outputs logical 1 for `)` and logical 0 for `(`. Monstrosity with `eval` is required to handle empty input. Without that case it reduces to: ``` @(x)all([sum(x(x<42)*2-81),x(end)~='/*-+(']) ``` which is much easier to comprehend. Ungolfed: ``` @(x)all([ % all of the conditions must be met sum(x(x<42)*2-81) % brackets are unbalanced , % AND x(end)~='/ % last character isn't / AND *-+(' % isn't * AND ... (so on) ]) ``` Checking of bracket unbalance works by taking only brackets in input: `x(x<42)` and then with multiplication and subtraction transforming `(` into `-1` and `)` into `1`. Then sum of these is converted to logical during execution of `all` - `0` stays logical `0` anything else becomes logical `1`. Omitted in ungolfed version `eval` additionaly puts `0` before whole input so last character will always exist. [Answer] # [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), 206 bytes ``` mod B is pr LIST{Int}. ops b p : Nat ~> Nat . var A : Nat . var X Y Z :[Nat]. eq b(nil)= 0 . eq b(X A)= 0 ^((~ A & 16)*(A xor 41)+ 0 ^ p(X A)). eq p(nil)= 0 . eq p(A X)= 0 ^(A & 22)* -1 ^(A & 1)+ p(X). endm ``` The result is obtained by reducing the `b` function with the input string given as a list of ASCII code points. The output will be `0` for open bracket and `1` for close bracket. ### Example Session ``` Maude> --- "" -> "(" > red b(nil) . result Zero: 0 Maude> --- "(1+" -> "(" > red b(40 49 43) . result Zero: 0 Maude> --- "(1+(2/3" -> ")" > red b(40 49 43 40 50 47 51) . result NzNat: 1 Maude> --- "(1+(2/3)" -> ")" > red b(40 49 43 40 50 47 51 41) . result NzNat: 1 Maude> --- "(1+(2/3))-8" -> "(" > red b(40 49 43 40 50 47 51 41 41 45 56) . result Zero: 0 Maude> --- "(1+(2/3))-8*(" -> "(" > red b(40 49 43 40 50 47 51 41 41 45 56 42 40) . result Zero: 0 Maude> --- "(1+(2/3))-8*((5" -> ")" > red b(40 49 43 40 50 47 51 41 41 45 56 42 40 40 53) . result NzNat: 1 Maude> --- "(1+(2/3))-8*((5)" -> ")" > red b(40 49 43 40 50 47 51 41 41 45 56 42 40 40 53 41) . result NzNat: 1 Maude> --- "(1+(2/3))-8*((5))" -> "(" > red b(40 49 43 40 50 47 51 41 41 45 56 42 40 40 53 41 41) . result Zero: 0 ``` ### Ungolfed ``` mod B is pr LIST{Int} . ops b p : Nat ~> Nat . var A : Nat . var X Y Z : [Nat] . eq b(nil) = 0 . eq b(X A) = 0 ^ ((~ A & 16) * (A xor 41) + 0 ^ p(X A)) . eq p(nil) = 0 . eq p(A X) = 0 ^ (A & 22) * -1 ^ (A & 1) + p(X) . endm ``` I hope it's not too cheesy to accept input as ASCII code points. Maude *has* a string module, but it's pretty weak and kind of verbose. [Answer] # [Ly](https://github.com/LyricLy/Ly), 50 bytes ``` is<l>0sp["("=l+f")"=fp-sp]<")"=!f'0Lfp*l!+!!")"f-o ``` [Try it online!](https://tio.run/##y6n8/z@z2CbHzqC4IFpJQ8k2RztNSVPJNq1At7gg1gbEVExTN/BJK9DKUdRWVAQKpOnm//@vYagNAA "Ly – Try It Online") The algorithm for this one is: * read in the input, store the last character in a separate stack * run through all the chars, track `(` vs `)` balance in a saved cell * test, `last="("` and `last<"0"` * combine those three tests (paren balance is the 3rd one) to pick output There's a caveat though. I don't think `Ly` can handle null character (as opposed to numeric) input. So it doesn't handle the first test case, which is a null string. Here's the sausage making... First part, get input and setup for run ``` i - read the input onto the stack as codepoints s - save the last char in the backup cell <l> - switch stacks, load backup cell, switch back to original stack 0sp - set the backup cell to "0", then delete 0 from stack ``` Count the `(` vs `)` chars, keeping a summary count of the balance ``` [ p] - process one char per iteration, until stack is empty "("= - compare top of stack to "(" l+ - load balance summary, increments on match f - flip the current character to the top ")"= - compare top of stack to ")" fp - flip current char to the top, delete it - - decrement balance summary if char was ")" s - save balance summary to backup cell ``` Third, test the last character of the input. ``` < - switch to the stack where we stashed the last char ")"= - compare to ")" ! - negate result, we want "not equal" f - pull the character to the top of the stack '0L - test if less than character codepoint for "0" fp - pull the char to the top, then delete it ``` Fourth, combine the tests to get an output choice ``` * - compute "and" of the last two tests l! - load balance summary, negate + - compute "or" of that and the previous test combo !! - convert anything ">0" to "1" via double negate ")"f - add ")" to stack, pull tests results to top - - subtract to change char to "(" if called for o - output top of stack as a character ``` ]
[Question] [ # Definition 1. a(1) = 1 2. a(2) = 1 3. a(n) = a(n-a(n-1)) + a(n-a(n-2)) for n > 2 where n is an integer # Task Given positive integer `n`, generate `a(n)`. # Testcases ``` n a(n) 1 1 2 1 3 2 4 3 5 3 6 4 7 5 8 5 9 6 10 6 11 6 12 8 13 8 14 8 15 10 16 9 17 10 18 11 19 11 20 12 ``` # Reference * Obligatory OEIS [A005185](http://oeis.org/A005185) [Answer] # Haskell, ~~35~~ 33 bytes ``` a n|n<3=1|b<-a.(-)n=b(b 1)+b(b 2) ``` Defines a function `a`. [Answer] ## [Retina](https://github.com/m-ender/retina), ~~84~~ ~~83~~ ~~79~~ 74 bytes Byte count assumes ISO 8859-1 encoding. ``` .+ $*;1¶1¶ +`;(?=(1)+¶(1)+)(?=(?<-1>(1+)¶)+)(?=(?<-2>(1+)¶)+) $3$4¶ G3=` 1 ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYAouKwokKjsxwrYxwrYKK2A7KD89KDEpK8K2KDEpKykoPz0oPzwtMT4oMSspwrYpKykoPz0oPzwtMj4oMSspwrYpKykKJDMkNMK2CkczPWAKMQ&input=MQoyCjMKNAo1CjYKNwo4CjkKMTA) (The first line enables a linefeed-separated test suite.) I'll have to golf this some more later. [Answer] # Julia, 29 bytes ``` !n=n<3||!(n-!~-n)+!(n-!~-~-n) ``` [Try it online!](http://julia.tryitonline.net/#code=IW49bjwzfHwhKG4tIX4tbikrIShuLSF-LX4tbikKCmZvciBuIGluIDE6MjAKICAgIEBwcmludGYoIiUydSAtPiAlMnVcbiIsIG4sICFuKQplbmQ&input=) ### How it works We redefine the unary operator `!` for our purposes. If **n** is **1** or **2**, `n<3` returns *true* and this is our return value. If **n** larger than **2**, `n<3` returns *false* and the *||* branch gets executed. This is a straightforward implementation of the definition, where `~-n` yields **n - 1** and `~-~-n` yields **n - 2**. [Answer] # Sesos, 54 bytes ``` 0000000: eefb5b 04f83a a75dc2 36f8d7 cf6dd0 af7b3b 3ef8d7 ..[..:.].6...m..{;>.. 0000015: cfed12 f661f0 ae9d83 ee63e6 065df7 ce6183 af7383 ....a.....c..]..a..s. 000002a: 76ef3c 3f6383 7eff9c b9e37f v.<?c.~..... ``` [Try it online](http://sesos.tryitonline.net/#code=c2V0IG51bWluCnNldCBudW1vdXQKYWRkIDEKZndkIDEKYWRkIDEKZndkIDYKZ2V0CnN1YiAxCmptcAogICAgam1wCiAgICAgICAgc3ViIDEKICAgICAgICBmd2QgMQogICAgICAgIGFkZCAxCiAgICAgICAgcndkIDEKICAgIGpuegogICAgZndkIDEKICAgIHN1YiAxCiAgICByd2QgMgogICAgYWRkIDIKICAgIGptcAogICAgICAgIHJ3ZCA0CiAgICAgICAgam1wCiAgICAgICAgICAgIHN1YiAxCiAgICAgICAgICAgIGZ3ZCAzCiAgICAgICAgICAgIGFkZCAxCiAgICAgICAgICAgIHJ3ZCAzCiAgICAgICAgam56CiAgICAgICAgZndkIDQKICAgICAgICBqbXAKICAgICAgICAgICAgc3ViIDEKICAgICAgICAgICAgcndkIDMKICAgICAgICAgICAgYWRkIDEKICAgICAgICAgICAgcndkIDEKICAgICAgICAgICAgYWRkIDEKICAgICAgICAgICAgZndkIDQKICAgICAgICBqbnoKICAgICAgICByd2QgMwogICAgICAgIGptcAogICAgICAgICAgICBzdWIgMQogICAgICAgICAgICBmd2QgMwogICAgICAgICAgICBhZGQgMQogICAgICAgICAgICByd2QgMwogICAgICAgIGpuegogICAgICAgIGZ3ZCA0CiAgICAgICAgYWRkIDIKICAgICAgICBqbXAKICAgICAgICAgICAgcndkIDUKICAgICAgICAgICAgam1wCiAgICAgICAgICAgICAgICByd2QgMQogICAgICAgICAgICAgICAgam1wCiAgICAgICAgICAgICAgICAgICAgc3ViIDEKICAgICAgICAgICAgICAgICAgICBmd2QgMgogICAgICAgICAgICAgICAgICAgIGFkZCAxCiAgICAgICAgICAgICAgICAgICAgcndkIDIKICAgICAgICAgICAgICAgIGpuegogICAgICAgICAgICAgICAgZndkIDEKICAgICAgICAgICAgICAgIGptcAogICAgICAgICAgICAgICAgICAgIHN1YiAxCiAgICAgICAgICAgICAgICAgICAgcndkIDEKICAgICAgICAgICAgICAgICAgICBhZGQgMQogICAgICAgICAgICAgICAgICAgIGZ3ZCAxCiAgICAgICAgICAgICAgICBqbnoKICAgICAgICAgICAgICAgIHJ3ZCAxCiAgICAgICAgICAgICAgICBzdWIgMQogICAgICAgICAgICBqbnoKICAgICAgICAgICAgZndkIDIKICAgICAgICAgICAgam1wCiAgICAgICAgICAgICAgICBzdWIgMQogICAgICAgICAgICAgICAgcndkIDEKICAgICAgICAgICAgICAgIGFkZCAxCiAgICAgICAgICAgICAgICByd2QgMQogICAgICAgICAgICAgICAgYWRkIDEKICAgICAgICAgICAgICAgIGZ3ZCAyCiAgICAgICAgICAgIGpuegogICAgICAgICAgICBmd2QgMQogICAgICAgICAgICBqbXAKICAgICAgICAgICAgICAgIHJ3ZCAyCiAgICAgICAgICAgICAgICBqbXAKICAgICAgICAgICAgICAgICAgICBzdWIgMQogICAgICAgICAgICAgICAgICAgIGZ3ZCAxCiAgICAgICAgICAgICAgICAgICAgYWRkIDEKICAgICAgICAgICAgICAgICAgICByd2QgMQogICAgICAgICAgICAgICAgam56CiAgICAgICAgICAgICAgICBmd2QgMgogICAgICAgICAgICAgICAgam1wCiAgICAgICAgICAgICAgICAgICAgc3ViIDEKICAgICAgICAgICAgICAgICAgICByd2QgMgogICAgICAgICAgICAgICAgICAgIGFkZCAxCiAgICAgICAgICAgICAgICAgICAgZndkIDIKICAgICAgICAgICAgICAgIGpuegogICAgICAgICAgICAgICAgZndkIDEKICAgICAgICAgICAgam56CiAgICAgICAgICAgIGZ3ZCAzCiAgICAgICAgICAgIHN1YiAxCiAgICAgICAgam56CiAgICAgICAgcndkIDIKICAgICAgICBqbXAKICAgICAgICAgICAgc3ViIDEKICAgICAgICAgICAgcndkIDMKICAgICAgICAgICAgYWRkIDEKICAgICAgICAgICAgZndkIDMKICAgICAgICBqbnoKICAgICAgICBmd2QgMQogICAgICAgIHN1YiAxCiAgICBqbnoKICAgIGZ3ZCAyCmpuegpyd2QgNwpwdXQ&input=MjA&debug=on) ### Disassembled ``` set numin set numout add 1 fwd 1 add 1 fwd 6 get sub 1 jmp jmp sub 1 fwd 1 add 1 rwd 1 jnz fwd 1 sub 1 rwd 2 add 2 jmp rwd 4 jmp sub 1 fwd 3 add 1 rwd 3 jnz fwd 4 jmp sub 1 rwd 3 add 1 rwd 1 add 1 fwd 4 jnz rwd 3 jmp sub 1 fwd 3 add 1 rwd 3 jnz fwd 4 add 2 jmp rwd 5 jmp rwd 1 jmp sub 1 fwd 2 add 1 rwd 2 jnz fwd 1 jmp sub 1 rwd 1 add 1 fwd 1 jnz rwd 1 sub 1 jnz fwd 2 jmp sub 1 rwd 1 add 1 rwd 1 add 1 fwd 2 jnz fwd 1 jmp rwd 2 jmp sub 1 fwd 1 add 1 rwd 1 jnz fwd 2 jmp sub 1 rwd 2 add 1 fwd 2 jnz fwd 1 jnz fwd 3 sub 1 jnz rwd 2 jmp sub 1 rwd 3 add 1 fwd 3 jnz fwd 1 sub 1 jnz fwd 2 jnz rwd 7 put ``` Or in Brainfuck notation: ``` +>+>>>>>>,-[[->+<]>-<<++[<<<<[->>>+<<<]>>>>[-<<<+<+>>>>]<<<[->>>+<<<]>>>>++[<<<<<[< [->>+<<]>[-<+>]<-]>>[-<+<+>>]>[<<[->+<]>>[-<<+>>]>]>>>-]<<[-<<<+>>>]>-]>>]<<<<<<<. ``` [Answer] # C, ~~43~~ 42 bytes *Saved 1 byte thanks to @Dennis* Every answer is the same, I must do something different! [Try it online!](https://ideone.com/yuS2JB) ``` a(n){return n<3?:a(n-a(n-2))+a(n---a(n));} ``` Explanation: it's basically `a(n-a(n-2))+a(n-a(n-1))` but with swaggyundefinedbehavior (works on my phone (gcc) and ideone). [Answer] ## Mathematica, 36 bytes Byte count assumes ISO 8859-1 encoding and Mathematica's `$CharacterEncoding` set to `WindowsANSI` (the default on Windows; other settings might work as well, but some like `UTF-8` definitely don't). ``` ±1=±2=1 ±n_:=±(n-±(n-1))+±(n-±(n-2)) ``` Defines `±` as a unary operator. I tried getting rid of the duplication, but ended up with the same byte count: ``` ±1=±2=1 ±n_:=Tr[±(n-±(n-#))&/@{1,2}] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 2Rạ⁸߀$⁺Sµ1>?2 ``` [Try it online!](http://jelly.tryitonline.net/#code=MlLhuqHigbjDn-KCrCTigbpTwrUxPj8y&input=&args=MTA) or [verify all test cases](http://jelly.tryitonline.net/#code=MlLhuqHigbjDn-KCrCTigbpTwrUxPj8yCjIwUsK1xbzDh-KCrEc&input=) (takes a few seconds). ### How it works ``` 2Rạ⁸߀$⁺Sµ1>?2 Main link. Argument: n (integer) 2R Yield [1, 2]. $ Combine the previous three links into a monadic chain. ⁸ Yield n. ạ Take the absolute difference of the return value and n. ߀ Recursively call the main link on each result. ⁺ Duplicate the chain. The first copy maps [1, 2] to [a(n - 1), a(n - 2)]. The second copy maps [a(n - 1), a(n - 2)] to [a(n - a(n - 1)), a(n - a(n - 2))]. S Take the sum. µ Combine all links to the left into a chain. ? If... > 2 n is greater than 2, call the chain. 1 Else, return 1. ``` [Answer] ## JavaScript (ES6), ~~45 Bytes~~ 34 Bytes A recursive solution in ES6. Any golfing tips much appreciated. ``` a=n=>n>2?a(n-a(n-1))+a(n-a(n-2)):1 ``` Thank you to [/u/ismillo](http://reddit.com/u/ismillo) for shortening even further. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ịḣ2S; 1Ç⁸¡2ị ``` This is an iterative approach. [Try it online!](https://tio.run/nexus/jelly#@/9wd/fDHYuNgq25DA@3H1poBOT////fyAAA) or [verify all test cases](https://tio.run/nexus/jelly#@/9wd/fDHYuNgq25DA@3P2rccWihEVDov5FB0KGtR/cAhZrWuP8HAA). ### How it works ``` 1Ç¡2ị Main link. Argument: n 1 Set the return value to 1. Ç¡ Call the helper link n times, updating the return value after each call. 2ị Extract the second element of the resulting array. ịḣ2S; Helper link. Argument: A (array) ị At-index; retrieve the elements of A at the values of A. ḣ2 Head 2; extract the first two results. S Take the sum of the result. ; Prepend the sum to A. ``` [Answer] # Python, ~~45~~ 40 bytes ``` a=lambda n:n<3or a(n-a(n-1))+a(n-a(n-2)) ``` Simple naïve interpretation of the challenge. *Saved 5 bytes thanks to @LeakyNun!* [Answer] # Haskell, ~~39~~ 37 Bytes ``` h n|n<3=1|n>2=h(n-h(n-1))+h(n-h(n-2)) ``` exactly like described in the challenge, using guards [Answer] # R, 50 bytes ``` a=function(n)ifelse(n<3,1,a(n-a(n-1))+a(n-a(n-2))) ``` Usage: ``` > a(1) 1 > a(20) 12 ``` [Answer] ## CJam, ~~19~~ 18 bytes ``` XXri{_($2$$+}*]-3= ``` [Try it online!](http://cjam.aditsu.net/#code=XXri%7B_(%242%24%24%2B%7D*%5D-3%3D&input=20) Uses the iterative approach. [Answer] ## C#, 51 44 bytes ``` int a(int n)=>n<3?1:a(n-a(n-1))+a(n-a(n-2)); ``` i wonder if this can be shortened by making it anonymous thanks pinkfloydx33! [Answer] # Golfscript, 29 bytes ``` ~[1 1]{..0=(=\..1=(=@+\+}@*2= ``` [Try it online!](http://golfscript.tryitonline.net/#code=flsxIDFdey4uMD0oPVwuLjE9KD1AK1wrfUAqMj0&input=MjA) [Answer] ## 05AB1E, 29 bytes An iterative solution. ``` XˆXˆÍL>v¯¤ys-è¯y¯yÍè-è+ˆ}¯¹<è ``` [Try it online](http://05ab1e.tryitonline.net/#code=WMuGWMuGw41MPnbCr8KkeXMtw6jCr3nCr3nDjcOoLcOoK8uGfcKvwrk8w6g&input=MTY) [Answer] # APL, 20 bytes ``` {⍵≤2:1⋄+/∇¨⍵-∇¨⍵-⍳2} ``` Explanation: ``` {⍵≤2:1⋄+/∇¨⍵-∇¨⍵-⍳2} ⍵≤2:1 If argument is 2 or less, return 1 ⋄ Otherwise: ⍵-⍳2 Subtract [1, 2] from the argument ∇¨ Recursive call on both ⍵- Subtract both results from the argument ∇¨ Recursive call on both again +/ Sum ``` [Answer] # VBA Excel 87 bytes Non-recursive, since I want this to work for n=100000, say: ``` Function A(N):ReDim B(N):For i=3 To N:B(i)=B(i-B(i-1)-1)+B(i-B(i-2)-1)+1:Next:A=B(N)+1 ``` ... and press `return` (byte #87) at the end of the line to get the `End Function` statement for "free". Note that B values are offset by -1 to avoid initializing for n=1 and 2. Invoke in spreadsheet as normal, eg `=A(100000)` to get `48157` The recursive version, **61 bytes**, ``` Function Y(N):If N<3 Then Y=1 Else Y=Y(N-Y(N-1))+Y(N-Y(N-2)) ``` starts to get unreasonably slow for n>30, and couldn't be said to work at all for n>40. [Answer] # Ruby, 36 bytes A direct implementation. Any golfing suggestions are welcome. ``` a=->n{n<3?1:a[n-a[n-1]]+a[n-a[n-2]]} ``` [Answer] ## Java 7, ~~68~~ ~~61~~ 51 bytes 17 saved thanks to Leaky Nun. ``` int a(int n){return n<3?1:a(n-a(n-1))+a(n-a(n-2));} ``` [Answer] # [Oasis](http://github.com/Adriandmen/Oasis), ~~9~~ ~~7~~ 5 bytes ~~**Non-competing**, since the language postdates the challenge.~~ Thanks to **Kenny Lau** for saving 4 bytes. Code: ``` ece+V ``` Expanded form (`V` is short for `11`): ``` a(n) = ece+ a(0) = 1 a(1) = 1 ``` Code: ``` e # Stack is empty, so a(n - 1) is used, and it calculates a(n - a(n - 1)) c # Calculate a(n - 2) e # Calculate a(n - a(n - 2)) + # Add up ``` [Try it online!](http://oasis.tryitonline.net/#code=ZWNlK1Y&input=&args=MTAwMA). Calculates n = 1000 in 0.1 seconds. [Answer] ## PowerShell v2+, ~~85~~ ~~79~~ 69 bytes ``` param($n)$b=1,1;2..$n|%{$b+=$b[$_-$b[$_-1]]+$b[$_-$b[$_-2]]};$b[$n-1] ``` Takes input `$n`, sets `$b` to be an array of `@(1, 1)`, then enters a loop from `2 .. $n`. Each iteration we tack onto `$b` the latest calculation in the sequence with a simple `+=` and the definition of the sequence. We then output the appropriate number from `$b` (with a `-1` because arrays in PowerShell are zero-indexed). This works if `$n` is `1` or `2` because both of those values are pre-populated into the lower indices of `$b` from the start, so even if the loop tacks on junk, it's ignored anyway. --- ### Recursive solution ~~78~~ 76 bytes ``` $a={param($k)if($k-lt3){1}else{(&$a($k-(&$a($k-1))))+(&$a($k-(&$a($k-2))))}} ``` First time I've used the equivalent of a lambda as the answer, as usually an iterative solution is shorter (as you can see from all the nested parens). ~~But, in this case, the nested parens are almost duplicated in the iterative solution with the nested array calls, so the recursive solution is shorter.~~ Nope, the iterative solution is indeed shorter (see above). Call it via the execution-operator, like `&$a 20`. Just a straight-up recursive call. [Answer] ## JavaScript (ES6), 66 bytes ``` n=>[...Array(n+1)].reduce((p,_,i,a)=>a[i]=i<3||a[i-p]+a[i-a[i-2]]) ``` Non-recursive version for speed; recursive version is probably shorter but I'll leave it for someone else to write. I always like it when I get to use `reduce`. Note: 1 byte saved by returning `true` (which casts to `1` when used in an integer context) for of `a(1)` and `a(2)`. [Answer] # Pyth, 16 bytes ``` L|<b3smy-bytdtBb L def y(b): |<b3 b < 3 or … m tBb map for d in [b - 1, b]: y-bytd y(b - y(d - 1)) s sum ``` Defines a function `y`. [Try it online](https://pyth.herokuapp.com/?code=L%7C%3Cb3smy-bytdtBbyMS20) (added `yMS20` to print the first 20 values) [Answer] # Forth, 76 bytes I finally got it working! ``` : Q recursive dup dup 3 < if - 1+ else 2dup 2 - Q - Q -rot 1- Q - Q + then ; ``` [**Try it online**](http://ideone.com/b8uJSr) **Explanation:** ``` : Q recursive \ Define a recursive function Q dup dup 3 < \ I moved a dup here to golf 2 bytes if \ If n < 3, return 1 - 1 \ Golf: n-n is zero, add one. Same as 2drop 1+ else 2dup 2 - Q - Q \ Copy n until 4 on stack, find Q(n-Q(n-2)) -rot \ Move the result below 2 copies of n 1- Q - Q + \ Find Q(n-Q(n-2)), then add to previous ^ then ; ``` [**Try it online**](http://ideone.com/PmnJRO) (slightly un-golfed from above) Unfortunately, [mutual recursion](https://en.wikipedia.org/wiki/Mutual_recursion) is a bit [too wordy](https://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Calls-and-returns.html) to use for golfing. [Answer] ## Lua, 59 bytes ``` function a(n)return n<3 and 1 or a(n-a(n-1))+a(n-a(n-2))end ``` [Answer] # Maple, ~~43~~ 41 bytes ``` a:=n->`if`(n>2,a(n-a(n-1))+a(n-a(n-2)),1) ``` Usage: ``` > a(1); 1 > a(20); 12 ``` This problem is certainly a good candidate for memoization. Using [option cache](https://www.maplesoft.com/support/help/maple/view.aspx?path=CacheOption), the run times are cut down significantly: ``` aC := proc(n) option cache; ifelse( n > 2, aC( n - aC(n-1) ) + aC( n - aC(n-2) ), 1 ); end proc: ``` This can be seen using: ``` CodeTools:-Usage( aC(50) ); ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 17 bytes ``` !¡λṁ!¹m≠→L¹↑_2)ḋ3 ``` [Try it online!](https://tio.run/##ASoA1f9odXNr//8hwqHOu@G5gSHCuW3iiaDihpJMwrnihpFfMinhuIsz////MTU "Husk – Try It Online") Feels too long. I'll post something with `fix` soon. [Answer] # [Japt](https://github.com/ETHproductions/japt), 20 bytes No big shenanigans, just recursively calculates the result. ``` §2?1:ßU-ßUÉ)+ßU-ßU-2 §2 // If the input is less than or equal to 2 ?1 // return 1, : // otherwise ß // recursively recall with U-ßUÉ // input minus recursive recall input minus one )+ // plus ßU-ßU-2 // same with input minus two. ``` [Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=pzI/MTrfVS3fVckpK99VLd9VLTI=&input=MTU=) [Answer] # J, ~~29~~ 28 bytes ``` 1:`(+&$:/@:-$:@-&1 2)@.(2&<) ``` Uses the recursive definition. ### Usage Extra commands are used for formatting multiple input/output. ``` f =: 1:`(+&$:/@:-$:@-&1 2)@.(2&<) (,:f"0) >: i. 20 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 1 1 2 3 3 4 5 5 6 6 6 8 8 8 10 9 10 11 11 12 ``` ### Explanation ``` 1:`(+&$:/@:-$:@-&1 2)@.(2&<) Input: n 2&< If n < 2 1: Return 1 Else -&1 2 Subtract [1, 2] from n to get [n-1, n-2] $:@ Call recursively on n-1 and n-2 - Subtract each of the results from n /@: Reduce using $: A recursive call on each +& Then summation Return that value as the result ``` ]
[Question] [ What general tips do you have for golfing in Julia? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Julia (e.g. "remove comments" is not an answer). [Answer] NOTE: The below are correct as of Julia 1.4.1 A few tricks to save a few characters 1. **Overload operators with frequently used binary functions**. For example, if you need to do a lot of integer divisions, and no need for inverse division, use `\ =div`, and you can then type `a\b` instead of `div(a,b)`. Note the space - this is necessary to avoid it parsing as a "=" operator. Also note that, if overloaded at REPL prompt level, use `(\)=Base.(\)` or `\ =Base. \` to reset it. NOTE: some functions have existing UTF-8 operators pre-defined, such as `÷` for `div`, as noted by Alex A. 2. **Use ^ with strings for conditional output**. That is, rather than `a>0?"Hi":""`, use `"Hi"^(a>0)` to save one byte, or for boolean a, use `"Hi"^a` to save three bytes. 3. (sometimes) **Store small fixed-size vectors as separate variables**. For instance, rather than `a=split("Hi there"," ")`, you may be able to avoid `a[1]` and `a[2]` by using `a,b=split("Hi there"," ")`, which can be referenced as `a` and `b`, saving three bytes for each use, at the cost of just two extra characters at assignment. Obviously, do not do this if you can work with vector operations. 4. **Don't use isempty for Arrays, Tuples, or Strings** - instead, use `==[]` for arrays and `==()` for tuples; similarly, for the negative, use `!=[]` and `!=()`. For strings, use `==""` for empty, but use `>""` for not-empty, as "" is lexicographically before any other string and it saves one byte. 5. **Use the right short-circuit boolean operator in place of "if"**. It might be a bit less Julia-specific, but it is worth bearing in mind. `x<=1&&"Hi"` can be written as `x>1||"Hi"`, saving a character (so long as the return of the boolean isn't important). 6. **Don't use contains to check presence of character in string** - if you're restricted to the basic ASCII, use `in('^',s)` rather than `contains(s,"^")`. If you can use other characters, you can save a bit more with `'^'∈s`, but note that `∈` is 3 bytes in UTF-8. 7. **Looking for minimum/maximum values in an array? Don't use minimum or maximum** - rather than using `minimum(x)` or `maximum(x)`, use `min(x...)` or `max(x...)`, to shave one character off your code. ~~Alternatively, if you know all elements of `x` will be non-negative, use `minabs(x)` or `maxabs(x)`~~ 8. **Where possible and permitted by the challenge, use an actual newline instead of \n** - note that this will make your code harder to read, and may mean that you need to provide an "ungolfed" version to make it possible for people to actually understand it. 9. **Put options after the regex string** - if you want to have a regex string in multiline mode, for example, don't type `r"(?m)match^ this"`, type `r"match^ this"m`, saving three characters. 10. **Where possible, use array concatenation instead of push!, unshift!, append!, or prepend!** - for normal arrays, this can be done easily. For arrays of type Any with array elements, you will need the type `Any`, as in `Any[[1,2]]`. At one stage, curly braces could be used as an alternate notation (`{[1,2]}`), but this has been discontinued. 11. **Don't use collect to convert a string into a char array** - instead of `collect(A)`, use `[A...]`, which will do the same thing and save 4 bytes. 12. **Need a number converted to a string?** Use `"$(s[i])"` ~~or `dec(s[i])`~~ for expressions or multi-character variables, and `"$i"` for single-character variables. 13. **Use `union` or `∪` instead of `unique`** - `union(s)` will do the same thing as `unique(s)`, and save a byte in the process. If you can use non-ASCII characters, then `∪(s)` will do the same thing, and `∪` only costs 3 bytes instead of the 5 bytes in `union`. In some circumstances, for single-character variables, you can save another byte using `s∪s` (thanks, MarcMush, for `s∪s`). 14. **Use array indexing to get the size of an array or string** - when you use `end` within array indexing, it automatically gets converted to the length of the array/string. This can be handy when you want to collect the length while doing certain operations. For example, if you need the length of `A` and the middle value, you might write `A[(k=end)÷2]`. This can also work in multiple dimensions, and for index iterators - `A[(k=1:end;)]` will give you an iterator for `k=1:length(A)`, which can be handy when you also want to use `A`. Note that the assignment must occur in brackets, with a semicolon (such as `(k=end;)`) if no operation is done outside the brackets. (thanks to MarcMush for identifying a workaround for keywords in array indexing) ***Outdated tricks that worked at some point, but no longer do:*** > > **Access first element of Array with `[]`** - for arrays, the expression `A[]` is equivalent to `A[1]`. Note that this does not work for Strings if you wish to get the first character, or for Tuples. - **`A[]` no longer works.** > > > > > **Reverse 1-D arrays using flipud** - `reverse(x)` is one byte longer than `flipud(x)` and will perform the same operation, so the latter is better. - **`flipud` is no longer in Base.** > > > > > **Use `?:` instead of `&&` or `||` for conditional assignment** - that is, if you want to perform an assignment only on some condition, you can save one byte by writing `cond?A=B:1` rather than `cond&&(A=B)`, or `cond?1:A=B` rather than `cond||(A=B)`. Note that the `1`, here, is a dummy value. - **the `?:` notation now requires spaces around `?` and `:`.** > > > [Answer] # Redefine operators to define functions Redefining operators can save a lot of bytes in parentheses and commas. ### Recursive unary operators For a unary example, compare the following recursive implementations of the Fibonacci sequence: ``` F(n)=n>1?F(n-1)+F(n-2):n # 24 bytes !n=n>1?!~-n+!(n-2):n # 20 bytes !n=n>1?!~-n+!~-~-n:n # 20 bytes ``` [Try it online!](http://julia.tryitonline.net/#code=IW49bj4xPyF-LW4rIX4tfi1uOm4KCnByaW50KCEyMCk&input=) The redefined operator retains its initial precedence. Note that we could not simply swap out `!` in favor of `~`, since `~` is already defined for integers, while `!` is only defined for Booleans. ### Binary operators Even without recursion, redefining an operator is shorter than defining a binary function. Compare the following definitions of a simple divisibility test. ``` f(x,y)=x==0?y==0:y%x==0 # 23 bytes (x,y)->x==0?y==0:y%x==0 # 23 bytes x->y->x==0?y==0:y%x==0 # 22 bytes x\y=x==0?y==0:y%x==0 # 20 bytes ``` [Try it online!](http://julia.tryitonline.net/#code=eFx5PXg9PTA_eT09MDp5JXg9PTAKClt4XHkgZm9yIHg9MDo2LHk9MDo2XSB8PiBkaXNwbGF5&input=) ### Recursive binary operators The following illustrates how to redefine a binary operator to compute the Ackermann function: ``` A(m,n)=m>0?A(m-1,n<1||A(m,n-1)):n+1 # 35 bytes ^ =(m,n)->m>0?(m-1)^(n<1||m^~-n):n+1 # 36 bytes | =(m,n)->m>0?m-1|(n<1||m|~-n):n+1 # 34 bytes m\n=m>0?~-m\(n<1||m\~-n):n+1 # 28 bytes ``` [Try it online!](http://julia.tryitonline.net/#code=bVxuPW0-MD9-LW1cKG48MXx8bVx-LW4pOm4rMQoKcHJpbnQoM1wxMCk&input=) Note that `^` is even longer than using a regular identifier, since its precedence is too high. As mentioned before ``` m|n=m>0?m-1|(n<1||m|~-n):n+1 # 28 bytes ``` would not work for integer arguments, since `|` is already defined in this case. The definition for integers *can* be changed with ``` m::Int|n::Int=m>0?m-1|(n<1||m|~-n):n+1 # 38 bytes ``` but that's prohibitively long. However, it *does* work if we pass a float as left argument and an integer as right argument. [Answer] 1. **Don't be too easily seduced by factor(n)** The tempting base library function `factor(n)` has a fatal flaw: it returns the factorization of your integer in an unordered `Dict` type. Thus, it requires costly `collect(keys())` and `collect(values())` and potentially also a `cat` and a `sort` to get the data you wanted out of it. In many cases, it may be cheaper to just factor by trial division. Sad, but true. 2. **Use map** `map` is a great alternative to looping. Be aware of the difference between `map` and `map!` and exploit the in-place functionality of the latter when you can. 3. **Use mapreduce** `mapreduce` extends the functionality of map even further and can be a significant byte-saver. 4. **Anonymous functions are great!** ..especially when passed to the aforementioned `map` functions. 5. **Cumulative array functions** `cumprod`, `cumsum`, the flavorful `cummin` and the other similarly named functions enable cumulative operations along a specified dimension of an n-dimensional array. (Or \*un\*specified if the array is 1-d) 6. **Short notation for Any** When you want to select all of a particular dimension of a multi-dimensional array (or Dict), e.g. `A[Any,2]`, you can save bytes by using `A[:,2]` 7. **Use the single-line notation for functions** Instead of `function f(x) begin ... end` you can often simplify to `f(x)=(...)` 8. **Use the ternary operator** It can be a space-saver for single-expression If-Then-Else constructions. *Caveats:* While possible in some other languages, you cannot omit the portion after the colon in Julia. Also, the operator is expression-level in Julia, so you cannot use it for conditional execution of whole blocks of code. `if x<10 then true else false end` vs `x<10?true:false` [Answer] # Iterate over functions This is also possible in other languages, but usually longer than the straightforward method. However, Julia's ability to redefine its unary and binary operators make it quite golfy. For example, to generate the addition, subtraction, multiplication and division table for the natural numbers from 1 to 10, one could use ``` [x|y for x=1:10,y=1:10,| =(+,-,*,÷)] ``` which redefines the *binary* operator `|` as `+`, `-`, `*` and `÷`, then computes `x|y` for each operation and `x` and `y` in the desired ranges. This works for unary operators as well. For example, to compute complex numbers **1+2i**, **3-4i**, **-5+6i** and **-7-8i**, their negatives, their complex conjugates and their multiplicative inverses, one could use ``` [~x for~=(+,-,conj,inv),x=(1+2im,3-4im,-5+6im,-7-8im)] ``` which redefines the *unary* operator `~` as `+`, `-`, `conj` and `inv`, then computes `~x` for all desired complex numbers. ### Examples in actual contests * [Female and Male Sequences](https://codegolf.stackexchange.com/a/80720) (binary) * [Case Permutation](https://codegolf.stackexchange.com/a/81021) (unary) [Answer] # 1. Use [`@b_str`](https://docs.julialang.org/en/v1/base/strings/#Base.@b_str) to store lists returning an array of `UInt8`s (ranging 0-127 in ascii) for example * `[99,100]` -- 8 characters * `b"cd"` -- 5 characters and using Unicode characters: * `b"🐢"` -- 4 characters, 7 bytes * `[240,159,144,162]` -- way more # 2. Avoid loops, use [`.|>`](https://docs.julialang.org/en/v1/base/base/#Base.:%7C%3E) or [`@.`](https://docs.julialang.org/en/v1/base/arrays/#Base.Broadcast.@__dot__) Very often, `.|>` or broadcasting is shorter: * `r=1:n;@.print(r*n^r)` * `1:n.|>i->print(i*n^i)` * `@.print((1:n)n^(1:n))` * `print.((1:n).*n.^(1:n))` * `[print(i*n^i) for i=1:n]` * `for i=1:n print(i*n^i)end` # 3. Choose the right function to override * depending on the number of arguments it can take without parenthesis (useful for recursive functions) + `-` can take 1 or 2 arguments [Try it online!](https://tio.run/##yyrNyUw0rPj/X7fC1pCrQrfS1ui/Q3FGfrmCrlKiEheECWSBeP8B "Julia 1.0 – Try It Online") + `~` can kinda take 1 or 2 arguments [Try it online!](https://tio.run/##yyrNyUw0rPj/v67C1pBLo6KuUtPW6L9DcUZ@uUKdUqISF4QJZIF4/wE "Julia 1.0 – Try It Online") + `+` can take 1 or more arguments [Try it online!](https://tio.run/##yyrNyUw0rPj/X7vCVslQiatCu9JWyQhMa1fZKhlDWdrltkomSv8dijPyyxW0lRKVuCBMIAuTh10EhP8DAA "Julia 1.0 – Try It Online") + `*` can take 2 or more arguments [Try it online!](https://tio.run/##yyrNyUw0rPj/v0Kr0lbJSIkLSGtV2SoZQ1la5bZKJkr/HYoz8ssVlBKVtICYC4WHXQSE/wMA "Julia 1.0 – Try It Online") * depending on their [operator precedence](https://docs.julialang.org/en/v1/manual/mathematical-operations/#Operator-Precedence-and-Associativity) + `>` and `<` are useful, with a lower precedence than `+` [Example with `<`](https://codegolf.stackexchange.com/a/240979/98541) + `~` has a *very* low precedence, lower than `<`, `=>`, `&&`... [Example](https://codegolf.stackexchange.com/a/246647/98541) + `^` has the highest precedence, battling with unary operators (`-x^-y == -(x^(-y))`) + `*` has the precedence of an unary operator when the `*` is omitted (`2x^2abs(y)a == 2*(x^(2*abs(y)*a))`) * some quirky operators + `~` is the only operator that can be placed directly before a `=` (for example `~=length`) + `>` (and `>`, `==`...) can be splat without parenthesis, `~` also but not in the function definition [Try it online!](https://tio.run/##yyrNyUw0rPj/P9EuSU9PzzZRq7g0VyNJkyvRBo1va4sqoJFYBxLQhIv856pQsFWINtQx0jGO5XIozsgvV7DTMDTQUTDUUTDSUTDWhAoaGthVAHXCeTYoPFtbFG4diPcfAA "Julia 1.0 – Try It Online") + `+` (and `*`, `++`) interprets `a+b+c` as `+(a,b,c)` rather than `(a+b)+c` + `<` (and `>`, `==`...) has a short-circuiting behaviour [Try it online!](https://tio.run/##yyrNyUw0rPj/36E4I79cQddQwUbBAIg18vJLMjLz0hVsbW0VCooy80py8jSUHB2VNDW5IEoNFewUjIAq4ZJOTkoIORugnB1CztlZSVNBWSG1qCi/qPj/fwA "Julia 1.0 – Try It Online") # 4. Some common substitions: * `codeunits(s)` => `[s...]`, `Int[s...]`, `for i=s`, `[s...].-'\0'` [Try it online!](https://tio.run/##yyrNyUw0rPj/36E4I79coVjBVkHJ0clZiQvCT85PSS3Nyywp1ijWhApFF@vp6cVCOZ55JSh8CEdPV51BHSaSqZCWX6SQaVsc@/8/AA "Julia 1.0 – Try It Online") * `sum(a[i]*b[i] for i=1:9)` => `sum(a.*b)` or `a'*b` [Try it online!](https://tio.run/##yyrNyUw0rPj/36E4I79cIVHBVsHQypQLwksC8ooS81I0DK0sLXVMNaHCxaW5GonRmbFJQKyQll@kkGkL1IMiq6eVBOMnqmsl/f8PAA "Julia 1.0 – Try It Online") [Answer] 1. Keywords can sometimes immediately follow constants without the need for a space or semicolon. For example: ``` n->(for i=1:n n-=1end;n) ``` Note the lack of a space between `1` and `end`. This is also true for `end` occurring after a close paren, i.e. `)end`. 2. Perform integer division using `÷` rather than `div()` or overloading an operator. Note that `÷` is worth 2 bytes in UTF-8. 3. Use `vec()` or `A[:]` (for some array `A`) rather than `reshape()` whenever possible. 4. Create functions rather than full programs when allowed in the challenge rules. It's shorter to define a function which accepts input rather than defining variables by reading from stdin. For example: ``` n->(n^2-1) n=read(STDIN,Int);n^2-1 ``` 5. Variables can be incremented inside the argument to a function. For example, the following is [my answer](https://codegolf.stackexchange.com/a/48375/20469) to the [Find the Next 1-Sparse Binary Number](https://codegolf.stackexchange.com/q/48355/20469) challenge: ``` n->(while contains(bin(n+=1),"11")end;n) ``` This is shorter than incrementing `n` inside of the loop. [Answer] 1. **Don't type `return`** `f(x)=x+4` is identical to but shorter than `f(x)=return x+4`. Julia always returns the result of the last statement. 2. **Use = instead of in**. `[x for x in 1:4]` is 3 characters longer than, but equivalent to `[x for x=1:4]` [Answer] # Use Broadcasting function calls. Introduced in Julia 0.5. It is like map, but uses less characters, and does broadcasting behavour over it's args -- which means you can write less lambda's to deal with things. Rather than: * `map(f,x)` -- 8 characters. * `f.(x)` -- 5 characters Better still: * `map(a->g(a,y),x)` -- 16 characters * `g.(x,[y])` -- 9 characters ]
[Question] [ *(related/inspired by: [Draw a bowling formation](https://codegolf.stackexchange.com/q/42645/42963))* A fun pastime in the winter months here is to perform snowman bowling, using a large ball (like a basketball) and tiny snowman figures. Let's recreate this in ASCII. Each snowman consists of the following: ``` (.,.) ( : ) ``` Here is the alignment of the ten snowman "pins" ``` (.,.) (.,.) (.,.) (.,.) ( : ) ( : ) ( : ) ( : ) (.,.) (.,.) (.,.) ( : ) ( : ) ( : ) (.,.) (.,.) ( : ) ( : ) (.,.) ( : ) ``` These "pins" are labeled from `1` to `10` as ``` 7 8 9 10 4 5 6 2 3 1 ``` So far, so standard. However, unlike normal bowling, the snowman pins are merely flattened and not totally removed. This is done by someone needing to manually flatten the snow of any pins that were struck. A flattened snowman is represented by `_____` (five underscores), with whitespace above. Here is an example with the `1 3 5 6 9 10` pins flattened (meaning only the `2 4 7 8` pins remain): ``` (.,.) (.,.) ( : ) ( : ) _____ _____ (.,.) ( : ) _____ _____ (.,.) ( : ) _____ _____ ``` ### Input * A list of integers from `1` to `10` [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963) representing which pins were struck and thus need to be flattened. * Each number will only appear at most once, and the numbers can be in any order (sorted, unsorted, sorted descending) -- your choice, whatever makes your code golfier. * The input is guaranteed to have at least one integer. ### Output The resulting ASCII art representation of the snowman pins, with the correct pins flattened. ### Rules * Leading or trailing newlines or whitespace are all optional, so long as the characters themselves line up correctly. * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * If possible, please include a link to an online testing environment so people can try out your code! * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. ### Examples ``` 1 3 5 6 9 10 (.,.) (.,.) ( : ) ( : ) _____ _____ (.,.) ( : ) _____ _____ (.,.) ( : ) _____ _____ 1 2 3 (.,.) (.,.) (.,.) (.,.) ( : ) ( : ) ( : ) ( : ) (.,.) (.,.) (.,.) ( : ) ( : ) ( : ) _____ _____ _____ 1 2 3 4 5 6 8 9 10 (.,.) ( : ) _____ _____ _____ _____ _____ _____ _____ _____ _____ ``` [Answer] ## [Snowman 1.0.2](https://github.com/KeyboardFire/snowman-lang/releases/tag/v1.0.2-beta), 157 bytes ``` (()("789:045600230001"4aG::48nSdU][:#:]eq]/nM;AsI[:"_____"wR[" "wR/aC;:"( : )"wR["(.,.)"wR/aC;bI;:" "wRdUaC;bI\#**\;aMaZ:" "aJ1AfL;aM;aM1AfL" "aJ1AfL*)) ``` [Try it online!](https://tio.run/nexus/snowman#LYq9CoNAEIT7ewpZm7sj6F78ia6VWARDhGCwiUq8YFIKwcIqz25OuWHZmfl2f0wt9cACs3QxsMh6bD21rtAGuXIuOJySlDCMYsRjgIgKQn0mCpPpPjZ9Sy7172/vT1WWz2VL8NwES92Cs8kkXxcZAXfIETvn3sETlr9Kc9q/xmavnStll@lKPwwHfVH552qqmS0Bs0gKsbrzbf0D) When I saw this challenge, I knew I just had to answer in the perfect language... This is a subroutine that takes input as an array of numbers and outputs as a string via the current permavar. Wrapped for "readability" / aesthetics: ``` (()("789:045600230001"4aG::48nSdU][:#:]eq]/nM;AsI[ :"_____"wR[" "wR/aC;:"( : )"wR["(.,.)"wR/aC;bI ;:" "wRdUaC;bI\#**\;aMaZ:" "aJ1AfL;aM;aM1AfL" "aJ1AfL*)) ``` Slightly ungolfed / commented version: ``` } 1wR` 3wR`aC` 5wR`aC` 6wR`aC` 9wR`aC` * (( )( "789:045600230001" // pin layout data 4aG // split into groups of 4; we need each row twice : // map over groups of 2 output lines : // map over pins (or whitespace) 48nS // subtract ascii '0' dU][ // duplicate the pin; we need it in the if{} : // if (pin) { #:]eq]/nM;AsI[:"_____"wR[" "wR/aC;:"( : )"wR["(.,.)"wR/aC;bI ;: // } else { " "wRdUaC ;bI // } \#**\ // maneuver the permavars around to discard pin ;aM aZ:" "aJ1AfL;aM ;aM 1AfL // flatten (simulate a flatmap) " "aJ // join on newline 1AfL // flatten again into a single string * )) #sP ``` [Answer] # [stacked](https://github.com/ConorOBrien-Foxx/stacked/), noncompeting, 118 bytes I added `deepmap` and a few other things after this challenge, along with tons of bugfixes. [Try it here!](https://conorobrien-foxx.github.io/stacked/stacked.html) ``` @a((7 8 9 10)(4 5 6)(2 3)(1)){e:('(.,.) ( : )' ' _'5 hrep)a e has#' 'hcat }deepmap{e i:' 'i 3*hrep e,$hcat#/!LF+}map ``` ## Ungolfed ``` { a : ((7 8 9 10) (4 5 6) (2 3) (1)) { e : ( '(.,.)' LF '( : )' + + ' ' LF '_' + + 5 hrep ) @possible a e has @ind possible ind get @res ' ' @padding res padding hcat return } deepmap { e i: ' ' LF ' ' + + i 3 * hrep e , $hcat insert! LF + } map } @:bowl (1 2 3 4 6 10) bowl out ``` Output: ``` (.,.) (.,.) (.,.) ( : ) ( : ) ( : ) _____ (.,.) _____ ( : ) _____ _____ _____ _____ ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~45~~ 44 bytes ``` TF"(.,.)( : )"„ _5×{«4ä2ä¹N>åè})4L£Rvyø»}».c ``` [Try it online!](https://tio.run/nexus/05ab1e#AUoAtf//VEYiKC4sLikoIDogKSLigJ4gXzXDl3vCqzTDpDLDpMK5Tj7DpcOofSk0TMKjUnZ5w7jCu33Cuy5j//9bMSwzLDUsNiw5LDEwXQ "05AB1E – TIO Nexus") **Explanation** ``` TF # for N in [0 ... 9] do: "(.,.)( : )" # push string „ _ # push the string " _" 5× # repeat it 5 times { # sort « # concatenate the strings 4ä # split the string in 4 parts 2ä # split the list in 2 parts ¹N>åè # if index+1 is in the input, push the first part # else push the second part } # end loop ) # wrap stack in a list 4L£ # split list in parts of size 1,2,3,4 R # reverse list v # for each list in list of lists yø # transpose the list » # join by spaces and newlines } # end loop » # join by newlines .c # centralize ``` [Answer] # Python 2, ~~248~~ ~~243~~ ~~241~~ ~~226~~ ~~224~~ ~~223~~ ~~221~~ ~~210~~ ~~206~~ ~~200~~ 177 bytes -5 with thanks to @Rod -15 again thanks to Rod -1 using space calculation again from Rod Looks longer due to more lines and indents but surprisingly 11 bytes shorter. I'm sure this will go under 200... I was right but not without 23 bytes worth of serious hints from @Pietu1998. Many thanks! ``` i,z=input(),0;m=['']*10;n=m[:] for x in range(11):m[x-1],n[x-1]=('(.,.)',' '*5,'( : )','_'*5)[x in i::2] for y in 10,6,3,1: for q in m,n:print' '*3*z+' '.join(q[y-4+z:y]) z+=1 ``` [Try it online!](https://tio.run/nexus/python2#JYzLCoMwEEX3fsXskugojrZdjORLQihdtCUFxwcWND9vjV0dzoF794DRBhm/izZYd711Svmc6k5s79hnr2GGFYLA/JD3UxMZ7t1akkc5YbXSFVZGoQKVX1FpYEh2P8y4cxqYm//TlpRqvGGLxBmkNqXWo/A4B1nSS5vH4mD1GYLoyW3lpYi8eZNBLCztO2GD7Q8 "Python 2 – TIO Nexus") Takes input as a list of integers. Way too big at 248 but it works. [Answer] # C# ~~233~~ ~~221~~ ~~213~~ 203 bytes method takes an int array a as the list of fallen pins ``` string S(int[]a){string o="",x=o,y=o,z=o;for(int i=10;i>0;){var c=a.Contains(i);x=(c?" ":"(.,.) ")+x;y=(c?"_____ ":"( : ) ")+y;if(i==7|i<5&i--!=3){o+=$"{z}{x}\n{z}{y}\n";x=y="";z+=" ";}}return o;} ``` wrapped ``` string S(int[]a){string o="",x=o,y=o,z=o;for(int i=10;i>0;) {var c=a.Contains(i);x=(c?" ":"(.,.) ")+x;y=(c?"_____ ": "( : ) ")+y;if(i==7|i<5&i--!=3){o+=$"{z}{x}\n{z}{y}\n";x=y=""; z+=" ";}}return o;} ``` expanded ``` string S(int[] a) { string o = "", x = o, y = o, z= o; for (int i = 10; i > 0;) { var c = a.Contains(i); x = (c ? " " : "(.,.) ") + x; y = (c ? "_____ " : "( : ) ") + y; if (i==7|i<5&i--!=3) { o += $"{z}{x}\n{z}{y}\n"; x = y = ""; z += " "; } } return o; } ``` knocked off a few bytes by suggestions in comments from Ghost, raznagul and auhmaan. [Answer] ## Batch, 262 bytes ``` @echo off for /l %%i in (1,1,10)do set s%%i=( : ) for %%i in (%*)do set s%%i=_____ set l=call:l %l%%s7%%s8%%s9%%s10% %l%" %s4%%s5%%s6% %l%" %s2%%s3% %l%" %s1% exit/b :l set s=%~1 set s=%s:( : )=(.,.)% echo(%s:_____= % echo(%~1 ``` Note: Lines 2, 3 and 4 end in a space, and also outputs a trailing space on each line. These can be removed at a cost of 5 bytes. Works by creating variables s1...s10 as the bottom halves of the snowmen, then flattening the ones given as command-line arguments. The appropriate rows are printed twice, the first time with the bottom halves replaced with the top halves. This saves 18 bytes over using two sets of top and bottom half variables. [Answer] # JavaScript, ~~154~~ 149 bytes ``` f= a=>`6 7 8 9 _3 4 5 __1 2 ___0 `[r='replace'](/\d|_/g,m=>++m?~a.indexOf(m)?'_____':'( : )':' ')[r](/.*\n?/g,m=>m[r](/ : |_/g,s=>s=='_'?' ':'.,.')+m) I.oninput=()=>O.innerHTML=f(JSON.parse(`[${I.value.match(/\d+/g)}]`)) I.oninput() ``` ``` <input id=I value="1 3 5 6 9 10"><pre id=O> ``` [Answer] # Pyth, 63 bytes ``` j.ejm+**3k;j;db)_CcR[1 3 6).e:*T]btMQ@m*T]*5d,d\_kc2"(.,.)( : ) ``` A program that takes input of a list of integers and prints the result. [Test suite](http://pyth.herokuapp.com/?code=j.ejm%2B%2a%2a3k%3Bj%3Bdb%29_CcR%5B1+3+6%29.e%3A%2aT%5DbtMQ%40m%2aT%5D%2a5d%2Cd%5C_kc2%22%28.%2C.%29%28+%3A+%29&test_suite=1&test_suite_input=%5B1%2C3%2C5%2C6%2C9%2C10%5D%0A%5B1%2C2%2C3%5D%0A%5B1%2C2%2C3%2C4%2C5%2C6%2C8%2C9%2C10%5D&debug=0) *[Explanation coming later]* [Answer] # Pyth, 51 bytes The code contains some unprintables, so here is an `xxd` hexdump. ``` 00000000: 6a6d 2e5b 3233 5f6a 3b6d 4063 323f 7d6b jm.[23_j;m@c2?}k 00000010: 5172 2235 2035 5f22 392e 2220 3b5b 8db2 Qr"5 5_"9." ;[.. 00000020: 1778 a822 6472 4673 4d50 4253 2d34 2f64 .x."drFsMPBS-4/d 00000030: 323b 38 2;8 ``` [Try it online.](https://pyth.herokuapp.com/?code=jm.%5B23_j%3Bm%40c2%3F%7DkQr%225+5_%229.%22+%3B%5B%C2%8D%C2%B2%17x%C2%A8%22drFsMPBS-4%2Fd2%3B8&input=%5B1%2C3%2C5%2C9%5D&debug=0) ### Without unprintables, 52 bytes ``` jm.[23_j;m@c2?}kQr"5 5_"9").,.() : ("drFsMPBS-4/d2;8 ``` [Try it online.](https://pyth.herokuapp.com/?code=jm.%5B23_j%3Bm%40c2%3F%7DkQr%225+5_%229%22%29.%2C.%28%29+%3A+%28%22drFsMPBS-4%2Fd2%3B8&input=%5B1%2C3%2C5%2C9%5D&debug=0) [Answer] # Javascript ~~178~~ 169 bytes Essentially a port from my C# answer. Takes an int array as the list of flattened "pins"; ``` f=a=>{o=x=y=z="";for(i=10;i>0;){c=a.includes(i);x=(c?" ":"(.,.) ")+x;y=(c?"_____ ":"( : ) ")+y;if(i==7|i<5&i--!=3){o+=z+x+"\n"+z+y+"\n";x=y="";z+= " ";}}return o} ``` Wrapped: ``` f=a=>{o=x=y=z="";for(i=10;i>0;){c=a.includes(i); x=(c?" ":"(.,.) ")+x;y=(c?"_____ ":"( : ) ")+y; if(i==7|i<5&i--!=3){o+=z+x+"\n"+z+y+"\n";x=y=""; z+= " ";}}return o} ``` Expanded & Explained: ``` // function f takes parameter a (an array of ints) f = a => { // four strings: // o: output // x: top row of snowmen // y: bottom row of snowmen // z: padding to indent the snowmen o = x = y = z = ""; // loop from 10 to 1 (the pins) // remove the "afterthought" decrement - we can do that later for (i = 10; i > 0;) { // set the boolean c to whether the current pin has been flattened c = a.includes(i); // prefix x and y with the appropriate "sprite" // using a ternary if on c x = (c ? " " : "(.,.) ") + x; y = (c ? "_____ " : "( : ) ") + y; // determine if we've reached the end of a row (i equals 7, 4, 2 or 1) // use non shortcircuit operators to save bytes and ensure we hit the final i, because... // we also decrement i here // (we didn't do this in the for loop declaration to save a byte) if (i == 7 | i < 5 & i-- != 3) { // concatenate our rows x & y, // prefixing them with the padding z, // postfixing them with a newline o += z + x + "\n" + z + y + "\n"; // reset x and y rows x = y = ""; // increase our padding for next time z += " "; } } // return our final string (no semicolon to save a byte) return o } ``` ]
[Question] [ There are a lot™ of pokemon. One of the defining characteristics of pokemon is their type, of which every1 pokemon has up to two types, a primary type and an optional secondary type. There are mechanical implications to each type, and so it is very useful to know what type a given pokemon is during battle. But there's no way that I'm going to memorize the type(s) of every single possible pokemon. So I need you to write me a program that takes the name of a pokemon as input, and outputs what type(s) this pokemon (probably) is. Probably, you say? This is because it would be difficult to correctly identify every single pokemon's type(s), especially if you're trying to make your program as short as possible. So you do not need to identify every single pokemon with 100% reliability, you just need to make a reasonably good guess. You must find the optimal balance between identifying as many pokemon as possible, and keeping your code as short as possible. Your entry's score is calculated as follows: ``` Length of program * (1 / ratio of correct guesses) ^ 2 ``` For example, if you wrote a program that was 500 bytes long, and it correctly identifies 50% of inputs, your score would be 2000 `(500 * (1/0.5)^2) == 500 * 4`, and a program that is 1000 bytes long that correctly identifies *all* of the inputs would have a score of 1000. For the purposes of scoring, 1/0 will be considered to equal infinity (so you better identify at least one of them correctly). Since there are a lot™ of pokemon, we'll restrict this challenge to the first generation of pokemon, of which there are 151 pokemon2 and 17 types3. Here is a dataset of all the gen 1 pokemon by name, pokedex number, and type(s). ``` #,Name,Type 1,Type 2 1,Bulbasaur,Grass,Poison 2,Ivysaur,Grass,Poison 3,Venusaur,Grass,Poison 4,Charmander,Fire, 5,Charmeleon,Fire, 6,Charizard,Fire,Flying 7,Squirtle,Water, 8,Wartortle,Water, 9,Blastoise,Water, 10,Caterpie,Bug, 11,Metapod,Bug, 12,Butterfree,Bug,Flying 13,Weedle,Bug,Poison 14,Kakuna,Bug,Poison 15,Beedrill,Bug,Poison 16,Pidgey,Normal,Flying 17,Pidgeotto,Normal,Flying 18,Pidgeot,Normal,Flying 19,Rattata,Normal, 20,Raticate,Normal, 21,Spearow,Normal,Flying 22,Fearow,Normal,Flying 23,Ekans,Poison, 24,Arbok,Poison, 25,Pikachu,Electric, 26,Raichu,Electric, 27,Sandshrew,Ground, 28,Sandslash,Ground, 29,Nidoran,Poison, 30,Nidorina,Poison, 31,Nidoqueen,Poison,Ground 32,Nidoran,Poison, 33,Nidorino,Poison, 34,Nidoking,Poison,Ground 35,Clefairy,Fairy, 36,Clefable,Fairy, 37,Vulpix,Fire, 38,Ninetales,Fire, 39,Jigglypuff,Normal,Fairy 40,Wigglytuff,Normal,Fairy 41,Zubat,Poison,Flying 42,Golbat,Poison,Flying 43,Oddish,Grass,Poison 44,Gloom,Grass,Poison 45,Vileplume,Grass,Poison 46,Paras,Bug,Grass 47,Parasect,Bug,Grass 48,Venonat,Bug,Poison 49,Venomoth,Bug,Poison 50,Diglett,Ground, 51,Dugtrio,Ground, 52,Meowth,Normal, 53,Persian,Normal, 54,Psyduck,Water, 55,Golduck,Water, 56,Mankey,Fighting, 57,Primeape,Fighting, 58,Growlithe,Fire, 59,Arcanine,Fire, 60,Poliwag,Water, 61,Poliwhirl,Water, 62,Poliwrath,Water,Fighting 63,Abra,Psychic, 64,Kadabra,Psychic, 65,Alakazam,Psychic, 66,Machop,Fighting, 67,Machoke,Fighting, 68,Machamp,Fighting, 69,Bellsprout,Grass,Poison 70,Weepinbell,Grass,Poison 71,Victreebel,Grass,Poison 72,Tentacool,Water,Poison 73,Tentacruel,Water,Poison 74,Geodude,Rock,Ground 75,Graveler,Rock,Ground 76,Golem,Rock,Ground 77,Ponyta,Fire, 78,Rapidash,Fire, 79,Slowpoke,Water,Psychic 80,Slowbro,Water,Psychic 81,Magnemite,Electric,Steel 82,Magneton,Electric,Steel 83,Farfetch'd,Normal,Flying 84,Doduo,Normal,Flying 85,Dodrio,Normal,Flying 86,Seel,Water, 87,Dewgong,Water,Ice 88,Grimer,Poison, 89,Muk,Poison, 90,Shellder,Water, 91,Cloyster,Water,Ice 92,Gastly,Ghost,Poison 93,Haunter,Ghost,Poison 94,Gengar,Ghost,Poison 95,Onix,Rock,Ground 96,Drowzee,Psychic, 97,Hypno,Psychic, 98,Krabby,Water, 99,Kingler,Water, 100,Voltorb,Electric, 101,Electrode,Electric, 102,Exeggcute,Grass,Psychic 103,Exeggutor,Grass,Psychic 104,Cubone,Ground, 105,Marowak,Ground, 106,Hitmonlee,Fighting, 107,Hitmonchan,Fighting, 108,Lickitung,Normal, 109,Koffing,Poison, 110,Weezing,Poison, 111,Rhyhorn,Ground,Rock 112,Rhydon,Ground,Rock 113,Chansey,Normal, 114,Tangela,Grass, 115,Kangaskhan,Normal, 116,Horsea,Water, 117,Seadra,Water, 118,Goldeen,Water, 119,Seaking,Water, 120,Staryu,Water, 121,Starmie,Water,Psychic 122,Mr. Mime,Psychic,Fairy 123,Scyther,Bug,Flying 124,Jynx,Ice,Psychic 125,Electabuzz,Electric, 126,Magmar,Fire, 127,Pinsir,Bug, 128,Tauros,Normal, 129,Magikarp,Water, 130,Gyarados,Water,Flying 131,Lapras,Water,Ice 132,Ditto,Normal, 133,Eevee,Normal, 134,Vaporeon,Water, 135,Jolteon,Electric, 136,Flareon,Fire, 137,Porygon,Normal, 138,Omanyte,Rock,Water 139,Omastar,Rock,Water 140,Kabuto,Rock,Water 141,Kabutops,Rock,Water 142,Aerodactyl,Rock,Flying 143,Snorlax,Normal, 144,Articuno,Ice,Flying 145,Zapdos,Electric,Flying 146,Moltres,Fire,Flying 147,Dratini,Dragon, 148,Dragonair,Dragon, 149,Dragonite,Dragon,Flying 150,Mewtwo,Psychic, 151,Mew,Psychic, ``` And here is a list of all the available types: ``` Bug Dragon Electric Fairy Fighting Fire Flying Ghost Grass Ground Ice Normal Poison Psychic Rock Steel Water ``` Your input will always be one of the specified 151 gen 1 pokemon2. Your output must be one or two of the specified types. If outputting multiple types, you can choose the format to return them in (for example, separated by a space or a comma), but it must be consistent. Your input and output may be of any combination of upper and lower case that you require, just please specify what casing is required for your submission. To count as a correct guess, you must match both types exactly. For example, outputting just "fire" for charizard, or outputting "ground + <anything else>" for diglett, both of these would be considered an entirely wrong guess. Notes/edge cases * Entry 29 in the Pokedex is "Nidoran (female)", and entry 32 is "Nidoran (male)". Because both of these are just "Poison" type, the input will simply be "Nidoran", with no male/female designation. For calculating "ratio of correct guesses", treat Nidoran as a single entry (number of correct guesses / 150). * Every entry is comprised of only alphabetical characters with the following exceptions. To score these as correct guesses, the punctuation and spaces *may not* be removed or altered. + 83: Farfetch'd (Normal, Flying) + 122: Mr. Mime (Psychic, Fairy) * In pokemon mechanics, the order of the types is significant, as in "Type A/Type B" is different than "Type B/Type A". This is ignored for the purposes of this challenge, e.g. "Bulbasaur is 'Grass,Poison', but an output of 'Poison,Grass' is considered correct." The only types that Gen 1 pokemon have in both orders are "Rock/Ground" and "Ground/Rock" types, which are listed separately in the dataset, but can be counted as the same type for this challenge. --- * 1: There is arguably also a "???" type, which may or may not count as being a type. * 2: See Nidoran. * 3: Pokebiology was very primitive in the year of 1996, and both Fairy and Steel types were not yet recognized as being their own type when Gen 1 was released. Nevertheless, this challenge uses types as understood by our current modern day understanding of pokebiology. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 181 bytes, accuracy 148/150, score ≈ 185.925 ``` ȷ;€ȷḥ€⁸ḣ5¤ḋ“¢ṣẉṙ.þbɦṪỊ2ßẓʂẹ{©ṗḷ⁺¶ɱıEDẓẇlR³ṣɼcṭɲ9^O⁹¿ƭ{ÑṬṄLȥȧ§Spṗ¡¶?ṁcØÑ"Ḷ9ọẈ⁽~ƊŒ°Fȷðḳẓ@*Ƙ>Uƭ⁺aɦṪṇẈfẸȥsɱƑhṁt/.rẏỊSṠ8Ġe¥Ṡ )§’b97¤%97ḃ⁴UÄị“Ḅ ṚṘṢOṚıƁqø⁷)^ʋ<:Ɓ(ʠKħ)ṬƘH1ḍ×Uµ(5;§XMoƑ»ḲŒt¤ ``` [Try it online!](https://tio.run/##XVRdb9RGFH2fX4GqVoVKpWolRFOqtiSbbCCkWbEQKh6Qru1Ze@rZGTOeYeMgVSyNRAtCVegDoapUCqRRK5AIUGJv@iF5wyrhX8z@kfSOHV764nNmPL5z77nn@mvKeba/v7t1Ynz98e6WzdcRx/3c5g@PlY9sfmt87efygS0e2sH3trh3dPiPt/ebLf6w2zc/Gv5iBz@@vm4HxdXyd1vctfnWuD8oX@5t7mxON/CdHdzgZ8vn@PXeX74tnuw9m7i0MO4X5b@jJ1eHq7Z4bIuVM7vruxvlRjvBCOWv5cvPbdH3h2vD1bds/nLCbt@2g@/G/b@/Gd18dad8OrO7NXxq8@cY/Yv3RmufnR89wTuhzqm4gWc7dpDvrqd7m6PVCEPpD44qO/gB823b4v7HO/dpuY7k0JFyY3ztnjdxvHz0zsRxm3877r84P1yx265im68cssVPtlizxYMFZDubo/7lYT7ubx259PrWp5@M@odf358brpQbR7CK0drshza/Pbx7vvzz8LET5cZX83K0Wm7b/NmrO7p8tG@3X2D5wxtvo7ioIj7fb@7vTxruQQpGkVNXsgoXqTAVmYpAdUEE9IBSTqWoKFsGFZD2ZcOU5pRcAKVlxSY5pFqylJIp0FQljJJ5qiGRAZk0Gnc6iuJ5SgM8PAexEUAmcaUY56TFgpBmNUit5RtGzoLWoMEh8zEuaScUlOyRmRqmYxApOak8GeM3MfiRwbPMQRvzTyNFezXD9CLyJQukAlEjwwwcuWwoFf9/JSsSMxGSKU47wFRWEw/TXzQ8YUt4QmCFnKbkNAtDniWm0yEXKqodvWg80KQpuYOFIGCYQZNL2SWLjNOEmy4lLVCQ1k/qa9cBKaDGrtQRabCQU61Jw4RaMYmayh5ut6hKGWbbSrPA@LG7pMJ5ELETUrEuhYSSJorEmY4oauSDwIRJS3LWg7DGiCleMwUY9qSnAJsTgMOTHGJYhi4G9SOZ1BDTCqGbYPc4TxMljXZtTZjwcANL8zV2Gjk5R4UGX8o3TBncbFIZmMBlBlfQVsqlTruYg8iqPicscJ1qc9lL3G2OeAoLh1DQLtO0Zhr9OAOqQ7UfvRuQBgaV7uk0alO8p0F7ocTuNZ0UisybmLQjTLDyNJdZqt3d6FmekVkwolpSEYIiCwKb20DlltGxs1mCZphT4HkZmUM/uJwXJUfbe2SaY9OUxHKml2gY@kYfMIOvyZTxpHD5YiiIySzTXSm4i1kxVFGQM8yPmTaY6JzsdJzdUMtlh2ejLJJKOAzq4RMptvYciJBy1yXMNY1djFmpUgpYNgTYNmcFZ2hcVvZta1CZqaDrhlIdPTSPkpC2n6EvFDmdiaW6EPDM8rKTt4sitJhImcLrjJKp28TpUglpZmjVAHfOQOKc22BuXKfpFSxrEadduR/FaZTH4QyHat2SKsNmkAX8p2QoEWKK6WANHgp1AAnOMUUtwdcZJ20hFYcltC0OvsEOXITEXTuPoRVOXAP9ygRziJFxPA9YZRDa0z03Kr3/AA "Jelly – Try It Online") Function submission: outputs a list of 1 or 2 type names. The footer in the TIO! link runs the program on all possible inputs. ## Explanation ### Algorithm This is mostly based on my standard "map these large inputs to these small outputs" program, which I've used on many questions before (see [this answer](https://codegolf.stackexchange.com/a/214222) and [this answer](https://codegolf.stackexchange.com/a/220588) for the history), and it's reached the point that these questions can mostly be answered in an automated way: [here's the program that generated the bulk of this answer](https://tio.run/##hVZNbxxFGr77V5RGQpoRjdfj2JMxFocA@cAhH8JZRxtgUXV3TU9lqqua6uqMOyfYBe2BGycOIO1h97ZCQiw40Up7cIQUfob9R4bnfavbY7QrkFJ5pqrej@f9qvZjZUy7Wp1/8vWbxtW1K8VMm6C8UDZzufKbGxvXfNGUyob69Y3T78Ubwug6CDcT2lZNqMVQ2laEtlKjZOP8039fEsic96qunM21LYRrwv@R/wHytilTeIRGBQo6NWotXDawlSpReV2qkXhN5E1ldCaDqoX0Cj4aG1QunM1UIqTNResaUcpWyDwX6jh4eWFMW7r00MldKbELcxnYilVPQKCpYUjP2MJS13Pi9yP4HVCOwMAVXpZRKWYHFGxnHcaDoy1QFTDG5pXw0hZKbG1u/pliHfrGQimAQllpxBkQVSJqBwbwbR3HWjgzUzmn5@R33f@mv55Ux3FIDkABSfRUkmgmESnuOHhZi0p6Lh4Zm2krTe95hFZ4gMNSHuuyKS9VrWsEXaPypaZqwOt4a2uLSDmPLqKDUi4UW@3I9AFJaIVgYtgassPHVPNszpGQQq0y9FBPKsy9UuLlSU1GoSw9hd@xSZVxS7q4UNd1T7wvFNImDmWhfpXSRCznylJyEuo1dDuk/jfzazF0SJijYuifbjwuFNepK5RVXlJGfj1dYHTXBfU68xNzSc7qUhrDvDNFsaKSaFP4n0ltUK0EVVMx5hrbBoEjp8HrY@RYDFOVSdSw44xftUh18ZrC8KEBUlnTrFi0ea2drUe9MeJqlOQJzXWhUfvYSFBeJ5VuJbpq408YjQz2ZvDKYYJbQ2PItGsQsg3CaBPixHWkMZRo72Vskz/01Zeau2LglXfGDLqkcXLOP/lmA0/Nwf75X/718uTs2T@Bp8/FK@joDTxUJWbiDgc@vHljCGFBrY6LUSJod/r9i79B46cvz55/xcfig9@Ux5Cf/vDk/Ltv6fV6@Gitd/qjf6MOfoiOH9KbNixHo008KFyOjzKnZjOdaZR@ONo0egZ4dQwl7oKhVxU0N1kPatgamanhQAySwWAkXhWDs2efD4Cefqfbu1tn//nixVcHHzTbW@Oc/8/2I7w8uZyJn/9@9uyLKLW/f0l6r5NOL4ye/uOVS9F2KnQbT0/Onv@Xg8Ulsx0MNh87bSlF@/uUgBF@/fTlEScDP1er1fuDa6mXCOEaypYTGrngvU/dghHtwRh0BnwT75pnNKYmNLIOhI1JJWMICvgWpoTk3kIj1RG97rAkNGomGV3L903qyM/balk4Ql0YxRgC713O@sCG914WHQY@9275lLApAvm9ji8A6V9fRP/XjcqI5/VjVRTAG9LP6P6Gkp7s3MD40f4mwjGEyhaSEQ4JjXPE@6aLcQJz1WETUfG9l0/4nL5vjG7J9lrJeb4l8X0j1KEkv7ecr0nuVltZ2r/zpK1J7kAXBekdOMP5PGjtMeC2xNvOmMuUcdFYxkj3NjqZ1G479DKhlynJvSsrdv@uzhZ0fkdiwjt0jIVeRCzjeWEVo11ERByEyi0DY5AVYzxdBkaQpeTf8ZviDmFDNu/q3PX4cYee0SqydS/PNZXoHh6bNiK31D2rKeT7SBxd36enjlDnhWJcyIzRxnNn9JLRtoHRt1Tp@10l7tctV@o9qbM5Y6VzxtjZwEChvzdvcxeRU3OId5v8H2ZtIL1DvK4@IqfyUCnK@OEcE0GID1baIWXo0DrP5xU6jfDjRjOGOAiEFPUD@r4xNtyQD/AOEZ0jWXG2jpTlBiS0ERuidaQzzvkR/vwgf0eoAekfNaYieg/x/af9QwyuiRjPlXrK2DXaI1lx2I@aVIbBh6v3p4m4upsIgkSMdxKxcyURV/YSsbuN/VbEnXEicDTBbi9KQWgXOuPtNeJ22q1d/rc@J9OAyXQtQkam23FNOjdXx9ElrUm3OlbbkyjaSUyjwu44Gp5ivxePr0Se4051K/KbRM3OPPHvbEV@e6w6jeFNr7DqtFsdAXJHLvY6XtOdi4jH0UJverJ2NLk4mawjGncJ7SPt1063eqvdljHmfjfuKMS@Qv3qXfX3nM6YoL0xZfbD1d7V1WCwwvfrr/hi/vHFZ4NfAA "Jelly – Try It Online"). The basic idea is to write a program that runs the input through a lot of different hash functions, then take the dot product of the hashes with a hardcoded vector in a finite field – working out an appropriate hardcoded vector for this is simply a case of solving a lot of simultaneous linear equations, which is trivial for a computer to do. This time, though, there was a bit more manual work and ingenuity involved than usual. One observation is that a lossy algorithm is permitted (at a cost in score), so I chose to look at only the first five characters of each Pokémon's name (or all of them, if the name is shorter than that); this introduces a large number of beneficial collisions (turns out that Pokémon whose name start the same way normally have the same type!), and there are only two collisions that lead to incorrect results: Dragonite with Dragonair, ("Drago"), and Poliwrath with Poliwag and Poliwhirl ("Poliw" – Poliwag and Poliwhirl have the same type, but Poliwrath's is different). This produces a lot of savings, both due to the beneficial collisions, and because Dragonite and Poliwrath have unique types that would otherwise be difficult to encode. The next trick was to order the types carefully. Each type is internally stored as a number, in the order `fighting ghost fairy Grass dragon normal poison psychic bug water flying ground Ice fire rock electric steel` (which is what the compressed string `“Ḅ ṚṘṢOṚıƁqø⁷)^ʋ<:Ɓ(ʠKħ)ṬƘH1ḍ×Uµ(5;§XMoƑ»` near the end of the program decompresses to – most types are shorter in lowercase, but Grass and Ice are shorter in titlecase for some reason). This order was chosen with a lot of manual experimentation so that for all dual-typed Pokémon, their types are at most five elements apart in the list. A type or type pair can then be encoded as a one- or two-digit number in bijective base 16, with the less significant digit being the lower-numbered type, and the more significant digit being the distance between the types; this encoding maps all the type pairings onto the range 1 (pure Fighting) to 91 (Electric/Flying). This reduces the codomain of the mapping function, and thus means that the hardcoded vector can contain smaller numbers and thus be shorter. An advantage of skipping Dragonite and Poliwrath is that their types would not encode very well in this pattern, with Dragon being six spaces from Flying in the list, and Fighting nine spaces away from Water. Possible improvement: using a smaller modulus than 97, which is a little wasteful. I realised while writing this proof that it's actually OK for the modulus to not be prime – you can use two or more different finite fields and combine the results into a single vector that works modulo a non-prime. (In theory this would work for any size of codomain, although Jelly doesn't have finite field operators so it would only be easily expressible in Jelly for square-free numbers.) The odds of the equations being unsolvable would be higher, but hopefully it wouldn't be too bad to calculate them. I'd need to generate a new encoding program to be able to handle that, though. ### Expressing the algorithm in Jelly ``` ȷ;€ȷḥ€⁸ḣ5¤ḋ“…’b97¤%97ḃ⁴UÄị“…»ḲŒt¤ ȷ;€ȷ 1000 hash function configurations ḥ€ with each of them, hash ḣ5 the first 5 characters of ⁸ ¤ the function input ḋ ¤ dot product with “…’ a very large hardcoded number b97 converted to base 97 digits %97 take the result modulo 97 ḃ⁴ express in bijective base 16 U reverse digit order Ä cumulative sum ị ¤ index into “…» a hardcoded compressed string Ḳ split on spaces Œt and converted to titlecase ``` The first large constant is the vector used to do the mapping. The second is the list of type names – it was shorter to write this in mixed case and fix the case later than it would have been to write it in the correct case from the start. [Answer] # [PHP](https://php.net/), 5 bytes, score = 347.222 Correctly guesses 18 Pokemon. ``` Water ``` [Try it online!](https://tio.run/##K8go@P8/PLEktej/fwA "PHP – Try It Online") [Answer] # [Node.js](https://nodejs.org), score = 579 (579 bytes, 100%) This is at the other end of the spectrum, as opposed to [@dingledooper's answer](https://codegolf.stackexchange.com/a/265056/58563), as it gives the correct answer for all inputs. ``` s=>(g=i=>["GrassPoisonFireFlyingWaterBugNormalElectricGroundFairyFightingPsychicRockSteelIceGhostDragon".match(/.[a-z]+/g)[(B=Buffer)(`7$1 !7$<)&5!4$J%8,$*6#$?!P*<!4'R.+#&9$B !=,$M(!9%!"B+$K$B04$d%!3% 5%!A(@.$;+J*:#&3#&=&N$@*$&1(: P$6 !?(,9&6#!K/!"#3(T$6(,S&N$B$J#!? !?(,7!6"1!1'J!>*H"@*T,$5 !C(6%!.$3%@'-+$C+>&<(,9!8+J+P"1 +% O+>*4#&#&#&_!J0J!6'p(<#.=#&S"4&:$8+8):)F +7'< !="6)&o/!$J)+7'#g+$a$1!$.$;#&3&X&1#,="l$1"1'Z'-&1"Z(,= !A"V0#Q&4&4(!= !W%4$4%!;%#c+L$x%#7,$5*8!$K/!y"#G !3'6(:(,&`.replace(/[2-~]/g,c=>"1".repeat(B(c)[0]-49)))[parseInt(s,36)%9313%1248*2|i]-32]])``+" "+g(1) ``` [Try it online!](https://tio.run/##TZVrU@JIFIa/z69IQgiBIIoweBlxFBUdHEdWLGdLy9o5JE3openOdDpirK396@7pbpjZ4gNPX8@l33PyN7xAHkuaqS0uEvI@67/n/eMw7dP@8ZN3KSHPx4Lmgg@pJENWUp5@B0XkoEi/CbkEdsFIrCSNL6UoeDIEKsshTecKN47zMp7T@E7Ei4kihH2JyeVc5OpcQiq411qCiufhdusJtt6eo@20/hQO@oNiNiOyHv7Y89uOu@cf1YOPbtcfVfebfqNX8T@748aR263dtaJKcOAPHLff9G9C96DqeoPIv/YHO10/qbqdqvOx6p6GJy3/UzRqHFaCTiXoB9/8k4YftMNDZ@z3HPdz2DwIehX3etv1Kp3w3u@FzQluGvijivvZrO@5Pa/ttmsj97hx5Z007pv@R8c9C3tVt@V3qie1rcg/i46DI7zK3Y9G0dhrO1HVuY2OG91KoH9/uaOdkdurZeFRpdWvBBOvGxz6@9F@/bA@dKK92hFG4fXqgdh2/VEdJypp5IPfdn30Hj0P/gzalWbfY37ba9cea1tB23sMm33HPfUedip/BN2gG7o4/F7t@t2q@6laiaOv/mu1sofeNvZdHwMsvcql43ZqvfAwbAY/WpJkDGISbj/tbv37vJ024/6x1/b0PAEVDsK4/rTzvNU9qNfrTxnInHzhKsybnV69etBpd6rt3e5@Y/cf@rzV2X1@rv/4EXmOF6Vhu/7@6emDNyjYFHIopNf0vryUa3ogvFjj2RxQQTwhvwaEERSGHdA3kAny5GdBpWIE8TtIJdY8YJArVKbmM63IjGq8IQoyoc8NCoWzM0nMSUISc@waFgUHvYwzkjKGOKZJSsoNCKXEb0a6A6VAgSUaoy3tFeZIihXScAMXC@A5/p/KqViYGxYQzwtzjlqYYLT5XJLVhjGIOfI3mggJfEPUeKjxZ0HI/6bFGhdYXTpuRma64DY4NSE@FCyjr2Ynx2wwop0a0TRlZYbFpbNhBsoOHosp6DAvBbNwmyTUeHXJhFjqCylDqRRLffkYsCVs/rHy7YsKDhtaCqXPntOUEaUnz4sU@4MwbyNWZnFMZE5NuNgikiJeWPNrugG@sM8h6ZJAps1id1kxqubE5DcGjqHpHYLRFaQbmlPJNizBmDqdSjDPnoClUwYLeIOlMRTPRbaBBVkTLDOjD8byDJuasvLJKJ8SI5cHig2PEBzh4J5wBbEQv1kWZuGSiKRIrO/wgsKWNkiyNB7ycq2ojCZWAxMmVpn1QuNUmpRBysmSKrJhZepjCHJGsHnWtNDP0ZCw/zbPE2I8OCcrbLOp8QATqe3fFDrBkzkGsq46JspcWd@wnphO@xUUfD1FeAoabrkR1Dm@wpupp6syM2K8ljCd6kPXqEgb44NgWKRTXRDm0yBMEi5eSZrGhfrFBW7SDhRTwW10eDlo966oWgrOrB3D@CY66q80XlBVmJCuxWxmiwDf5s3S3bycC8ktJZtGwnMjpnvgKWFWCxhVvrB3Xgnsa2CSBokRiBaiLTqcWhfaRIEsizUsbaORLeeGmpqYxCUqU0czKvnrJnCYFm9v9tmWJoljynMqjSuFFLldwh4htdwuSyyoxMx@hczW2Dm1reiCvJhkPGBnk7ZBjjDJloYM1nNjIcvU0C121dKkGilXxvo1@mNus5CZTkXwdSBWpZbLhAvJ4NUUGLa5wrzvI2TWqRs0KE0nwa83ftypJbQHJibLa6GSlVrZgl95H54/tGZCXmBhhbnTP3ZiwXMsgxYTaZi3MkgueBK2d@tO5MzCHL817/8B "JavaScript (Node.js) – Try It Online") [Answer] # jAvAscRIpt, 273 characters, score = 322.5425 This answer includes insincere rules-lawyering, but it doesn't seem to literally abuse a [standard loophole.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) It might count as "adding input or rules". Since the Question says > > "If outputting multiple types, you can choose the format to return them in (for example, > separated by a space or a comma), but it must be consistent. Your input and output may be of any combination of upper and lower case that you require, just please specify what casing is required for your submission." > > > , inputs to this submission must follow the casing of the revised Pokéorthography (that I made up) to have it generate the correct answer 138 out of 150 times. This is the revised Pokéorthography: ``` muk Poison Mew Psychic Abra Psychic seEl Water ONIx Rock Ground JynX Psychic Ice ekans Poison arbok Poison zUbAt Poison Flying glooM Grass Poison ParaS Bug Grass GOLem Rock Ground dODUO Normal Flying Hypno Psychic diTtO Normal eeVeE Normal WeedLE Bug Poison KakuNA Bug Poison pIDGEy Normal Flying fEAROw Normal Flying RaIcHu Electric vulpix Fire gOlBat Poison Flying oddiSH Grass Poison meOwTh Normal mankey Fighting machop Fighting ponyta Fire dODRIo Normal Flying grimer Poison gastlY Ghost Poison gengaR Ghost Poison krAbby Water cubone Ground RHYdon Rock Ground hoRsea Water seAdra Water stAryu Water magmar Fire PinsIr Bug taUrOs Normal lapRaS Ice Water KaBUtO Rock Water ZAPDOs Electric Flying Mewtwo Psychic ivysAUr Grass Poison MetaPod Bug pIDGEot Normal Flying raTtAta Normal sPEARow Normal Flying PiKaChu Electric nidoran Poison nidoran Poison VenoNAt Bug Poison DiGletT Ground DuGtriO Ground peRsIan Normal psYduck Water goLduck Water poLiwag Water Kadabra Psychic MachokE Fighting MachamP Fighting GEOdude Rock Ground SloWbRo Psychic Water dewGONG Ice Water haUntER Ghost Poison Drowzee Psychic kiNgler Water VoLtOrb Electric MaRowaK Ground koffing Poison weezing Poison RHYhorn Rock Ground chAnSey Normal tangEla Grass goLdeen Water seAking Water StaRmIe Psychic Water SCyTHer Bug Flying JoLtEon Electric flareoN Fire poRyGon Normal OmANyTe Rock Water OmAStAr Rock Water snOrLax Normal mOlTreS Fire Flying DratInI Dragon venuSAur Grass Poison sqUirtle Water CateRpie Bug BeedRIll Bug Poison raTiCate Normal nidorina Poison nidorino Poison nIdoking Poison Ground clEfAiRy Fairy clEfAbLe Fairy PAraSEct Bug Grass VenoMOth Bug Poison PrimeaPe Fighting arcaniNe Fire Alakazam Psychic GRAveler Rock Ground rapidaSh Fire SloWpOke Psychic Water MAGNETon Electric Steel shEllder Water cloYSTEr Ice Water Mr. mimE Psychic Fairy maGikarp Water gYARados Water Flying vaPoreon Water KaBUtOps Rock Water aRtICuNo Ice Flying bulbASaur Grass Poison cHaRizArd Fire Flying waRtortle Water blAstoise Water pIDGEotto Normal Flying SaNdshRew Ground SaNdslAsh Ground nIdoqueen Poison Ground ninetaLes Fire vilePLume Grass Poison growliThe Fire poLiwhirl Water PolIwRAth Fighting Water teNtaCool Water Poison MAGNEMite Electric Steel ElEcTrode Electric EXeggCute Psychic Grass EXeggUtor Psychic Grass HitmonLee Fighting liCkItung Normal DragOnAir Dragon DRaGOnIte Dragon Flying charmaNder Fire charmeLeon Fire BUtTErfree Bug Flying jiGgLypUff Normal Fairy wiGgLytUff Normal Fairy bellSProut Grass Poison weepINbell Grass Poison victREebel Grass Poison teNtaCruel Water Poison fARFEtch'd Normal Flying HitmonChan Fighting kaNgAskhan Normal ElEcTabuzz Electric AEROdactyl Rock Flying ``` This is the program: ``` p=>(n=[..."PoisonPsychicWaterRockGrassBugNormalElectricFireFightingGhostGroundIceDragonFairyFlyingSteel".match(/.[a-z]+/g)],m=[n,[" "].concat([11,12,15,0,4,2,16,14].map(i=>n[i]))],[0,1].map(j=>m[j][parseInt([6,4,2,0].map(i=>+(p.charCodeAt(i+j)<91)).join(""),2)]).join(" ")) ``` Or more legibly: ``` t=p=>{n=[..."PoisonPsychicWaterRockGrassBugNormalElectricFireFightingGhostGroundIceDragonFairyFlyingSteel".match(/.[a-z]+/g)] m=[n,[" "].concat([11,12,15,0,4,2,16,14].map(i=>n[i]))] return[0,1].map(j=>m[j][parseInt([6,4,2,0].map(i=>+(p.charCodeAt(i+j)<91)).join(""),2)]).join(" ")} ``` * I wrote some other code to help find which type tuples to flip such that the number of types on each side becomes smaller than a power of two, which I didn't achieve on the secondaries: there are 15 first types and 9 second types. The list above reflects that order. * I also had a program work out the order of types on the lookup lists based on their appearance in the list of pokémon sorted by name length (the above one), since you can store less bits in the casing of shorter names. This all might not be optimal, since for example, it does not prioritize keeping the set of types used for short-name-pokémon small over doing it generally for all pokémon, and generally isn't some rigorous thing with a binary tree in it. That approximately 60-80 line piece of code is also useful for testing. Should I add it? [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~496~~ 400 bytes, score 400 ``` EΦE⪪”}⊞λ⪫¡↥↙vQ�≡⧴ï\`⊕B◨V~R&‖7≔NPv,BJ?…u“κo=B)↘ⅉ⁶2∧M÷5№?m⁹U↑O∕№f}B≡MD|“⧴{x⁼⮌≦3GE⁷℅64↑jEo0ºBjUQ|ÞU⪪↗↘↨→ξ¡Y➙F◧À⎚≔ eω↗3⎇ητ>ⅉ↓ρηX∧"⟧Φζ⊘Q←R]BLHfδ>@J%>;⊖Uf3‽ρIV⭆W↧UZW!⎚H#o?ⅈ8avdQTL^¶¶E◨¹…&5⌕¹WⅉJ"UR«³:⟧⭆·⎚↧ns?;⟧*≡↖,)k⁺⁴WF e´ζwE▶L⍘τ±ïχD↶~A≡1⁶OSkJ^\ωη▷¶«"³AH;_W↷q%⟧‹➙⦃λZ›⊞'≡&B↔⧴↧⭆⊖MU?κL«8▷IZ⁶1Σ:1w▷U›W{L⁵№sΦπ⁸σIPH{:κ/ï\À!e⟦Y�PM⦃¶W.ξ3ζXVLsKL⟲PUoOψI;▶~w∕X3⊙,Sp✳v⊙⎇αkμZτ-ε:ν&[÷c⁰L¡⁴M.ω±YuTZ+)7≕⊖“B?Lec{”¶⪪ι ⊙ι№θλ⊟ι ``` [Try it online!](https://tio.run/##XVLLjtowFN33K45YgUT7A13xDAOTISIjkEbZmOSKWBg7GKfTfD09DnQqdRHLdnzved2yVr50ytzvmdc2DFPVDJfaBPH9Nm@MDsPBTCGVgGkbcBCpsFFnTEWQKezFOuQlMm35/1TYuVfgd3K2sJk@Y6c0UnWy2DssDNYOH4obKYPXZWFnRrDWOPCRx1Jp3xU2VRaZR@aM/vQsLrHSWOpTHbQlwoycsW/xRsjEO0w84Z0lUhORLlgapI4FXh6Pdc880xXyBkvBBxJnjkTDvOeedJgI24RY9uBOPNP1aInCSiERYtXuFgo7bQ1eou4W2wqJwV5HI6ZiojkNFr/xriIzdbsVNlfkWblrv54x1yfMW7Zz8UHkIdhazFoy99jVUVBrK9oomBmHdYdX1VN7KSUaWlFmeOp4@sZemTzVvGpQsWVClixa4gUsGJTzyC3enL8o808CCT@zxOJMlGNkiY/24c@XunchLQLx/suMDUGdvsWUJ0c2qTAxyA3tc1h10YQ8KH@JqVJDKp/Ibl1Zx8j/F0/V2wtbHGMKO1ee4wRwYPIgQrL5FQfaa9ggllRxLiIlguUC@pTXvVUbj43GiomGOAY6xkrv9upv94PiWA/GGBR2MBrjMduaZwxGPE9sF08z@h@G1zFMvMxcM9Sj0ejn/Z76H0j1Rb7dv/8yfwA "Charcoal – Try It Online") Link is to verbose version of code. Outputs the types in alphabetical order. Explanation: The compressed string contains a list of all the unique prefixes for a given type followed by that type. These are then filtered for the prefixes that match the input string and then the types are extracted. Previous 496 byte solution outputs the types in the order given in the question: ``` ≔⪪”↶37₂?γ"Π⎚«ζ∨↖↘o*&J›7M‽ ±pλ⁹MgΠf⊟V³!P¹y⁰κ⊘X⮌GQ⟧÷±X´VkGº↗DZwG³↘»§/V↑X″ypLKνN^I→λ↶” υ⭆⪪”}∨D¤Y1H∧2gW±²&JψAχ∕ κ2⊕m⁴η;δKE↘L⎚▷μ²θ[⌈J_;$⁼σ⊗}/¶C~Mv?"V↗7{<|´0⁹ï8'➙1≡⦃Iü◨Rqp⍘td‴⁼xYHïω⪫ψ PρRN:ζg↖Bï↑⪪ÀMmP;e″=y﹪⌊κAλ&↗↔ςJβ~‹τ¿�λ▶⊘Þ?{↥⊙↓⁷_G;›D⁸⦃℅⁹τωx➙UXVςυ;FZ@ºηW⸿⟦EI∕-↗Th_pEGOχ3↷⁻@ε∕Πg⸿“ΣA«CKL↙⁵O>?¤↷⊗KP⊘B{℅&:≕Xe↑HN⧴↖η‴El¡4hw⁻¬×�⍘~o⊕δ~⊕”¶⎇∧ι⊙⪪ι №θλ§υκω⭆⪪”}∧αf.M‴%iI»⁷⁰τ➙:⁼\p'↥'�fP{Pζ⊖№ ↑″⟲σfH940⁵êYS↙Y«9≕%Sm↙⁶|π✳σqD⟦➙γ[Z₂›1⊖0@⊕S6←ψqP⎇›w\;MW;5K⌕Yυλ³⁴↓↷◧T(gB±Wï…↙↖iº÷τ⎇≔2Φ←nYρa¤←⊕ê⪪vK∕Z.8Z73×ζ⊞”¶⎇⊙⪪ι №θλ⁺/§υκω ``` [Try it online!](https://tio.run/##fZLdbtpAFITv8xQjroxE2wfolSH8BOLEwhGRkG8We2VWLGfJet3EfXk6GxIlitreYAxnz858M9Ve@copez6nbWsaSYqTNSEZzJTxPWam2QcjDWa2j4@5V23LT9dJjZtKI3emdYK87au9qbB21QFF0NriUQXtMe4aXHvVcGZqdRU8h2bGa8z3rg24c/6o7GCEAQbDEbrhz6vcGwlJwUlpMnV61zOxupRM8SqPTFVYmFJKGXcWN9ho6XBfY26xMRjHy7U@YfqCB8WhQuHaUEaHScezHut9KcseqQ@lTA987nBnamw7zJ3d0Z5B1mHl4prfpaQ7rFSN1NKJw6JHRgn6uZS5dpFIPKVxL7g/cnCHVEdpxRMRYGzJJg7URGXxoFFYFBrX/LLHxDqsPFYGC0dsFNcYzHvcKmxUKRPFewIZhqik5vID3RG6ipZ5okJueBUBl5KbA9bKxB2CjSNuLB22cQ0jxqajR4nR0S/PMZC1OsXpI8NF5mhHYUEzWuKymn8HFCfMNJYGj1xMt7nGjDQdbg24VihJCLkj4IBprINHITHPUmKgD9qL8n2SSp2YEVLp3/I075FPWKWQPI1gh0O@puFGav2SdCMc@PrMH/9ZiTdZnnKdNc/@4tS88ooGLuK3l1AvskmMeFMds6fnt2qySjk5sQPuKTbBHfAlWjLWr2ndqo/SfQ7lo36v1WPOn2gycnaxCMofsexLif2LMZVyaczfeP0X1Ai57dpk8GPwhdg7svM589@RmaO@On/7Zf8A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Starts off by getting a list of all of the types, then works through all of the unique prefixes for each type, outputting the types for which the input contains those prefixes. The verbose code was generated by a program so it's probably not the optimal approach. [Answer] # [Python 3](https://docs.python.org/3/), 584 bytes ``` s="lambda s:['4C,sir1e8.!x7l1ew#az#z+rm*br1*H%-t%0rti$5l,x+.0J%#4tt+c%!dos#ni8b(!T7l#ld#iw#tl778V,y6*K*g*H2Kr#s%#3ar#D2tc#d&#4ku#ed#eno$Steel!/!on76q#g8ow6k*Di&!T+id2z*Ek1u#f*rb2Gr*b(0L6y#w&#Ghost!H,G,en&#5p#s6u#V*d*Gl$Electric!pd#hu#El#J2V2/-ud#Gr6l+On#h%#Fire!iz1o$3v#uf#sk#yg#P7n1e2Di8ns+ur2L*R(-bu8Om$Fairy!uf1*fa$Fighting!wr1ac#H*nk#Pr$Dragon!Dra'])or['Fire']" for i in"8t#97+S96,o95Grass!e94Bug!93Normal!e92o#91#M90#Ice!9/gn$Ground9.Pa$Psychic9-#Rock!9,a#9+e#9*i#9(at$Water9&g$Poison9%y$Flying9$'])+['9#','9!']*any(i in s for i in['".split('9'):s=s.replace(i[0],i[1:]) f=eval(s) ``` [Try it online!](https://tio.run/##bZdbc9o4FMff@RRQkXKJmlo2BjszeWibNtmmaTNNJzuzmc6OsIXRICRXlkucnf3s3SPfMHR5wfyOLOlc9NchLcxaSe/Xr@zihaDbZUz72fnjaPYOZ1wTFpwNnhaCsB2iz@j5VG@nS02m1yevzImjDR/6Aj@dnjkfT9DMmNPoZBCrDEkeLMeDbwuBRIz4DhmxWAQPuJhPb6bJ9Nq90Sg7QR7V6NI1EYpfotkmRyxGTKrhvWFMDF4PlFzMf6AkULv5ZnrJXw6@nfLYfZ6@35AcraZ66V7p6XLsfJoXaPcSXa1VZgbX@Aoz@RL5KcrmOXqYxtMrMXwvWGQ0jwZpjNY5ei/QR/fBff0qj9GVnovTLxKtT9AHrtmAPxM19H6ifIWyDSoSdLeQhLmXPJDZaa7dT9Ov41fLPPiyHX6gXBeDfEWmKzr8wJO14TIZ7DShEbqeyg2608NLTRMlB/A1@j5R@nFkFxl9f9FbKd3nfS5fBAaFi9P7cI5V6F9pmmUDFs7e5skg9D4rvaUCfrsKhQTdhg76I2KD8HUih1da5TIOz@7o8C4rojWPwlfoq4o2gxBTFJ4yFE45CsfUDP@khunwZTK8UzxTMjwphh9EAZsNh7Cr08dRiEZ4FA5G36dUFmO7rX7Wb3b4OHpxlqWCm/EoHE3Os4vsTLNU0IiN@aPzHfNHcv590ltdsJ9UjLPJL75NlTb9rMh6PZlv/46U1hD//kXf6RllqCifyggILlm5WpGdZSbm8rzXh8/fOMVT@4K1g0HzdDypv2Gnk2Y/8FiO56t@BkuyeLwap5NJ/@Ki@W0m1Yz2093L6UWflAYmMrYfkmouzTjF/VGSsyxj8fkIH0wNFhqZnIqOwUyqXVS@lTP3qolWo8/5dsl0v172vP9PZxP/vv6nfOXf0eQXwW9zsaQZzTUuiwBXueq5@I@fxe/Yww9M5r/zGX63plA0MmYa21rDPb9CTDAlazQvEX@mOq5IVQ69Bb7/kXNtBMNlzeBeAA/aqC4K8VtBMwPrtYg4@J19SjkDPxIABN8yQ1MV179d@DYwYqVZNaRekXj4T8ZiUcHaCTLDN3STS3oAffwWRmouxAGe4zseJ6zA1WFpJ15UXBmjjk1BYzo2hPgrNYYa2hh6rmMRj8C7PSP4PmVUq93R@66LP/wv9/D7DZVNkmCGGX6jl2qzBz5saUOjdY4brQI4h7X5EYMUQXKztWY7XEkAwKCCkJb1Hob4M4@VprJdxXMqxCGyLSMl@5Ez1g6spuh5XjNc7YfPSrYBt45HQ50JtrKaiEtlhMHzCi0hvQ1a4IdcpPyprkQvgPkklIpgWYNC/JEniSjSfLVqI2lf780c/GdpMr@bCP4rX1LT7KoO/czFV0r8D/fwlzjmZby6x2eGr4RS2yPq4wcuQPPyLTuyQPVRAGVFlpbebFEhyFiXBvbAKklNt3hnYUm3yqy72HfwJU8EM6bNpk/wZZ5ADag9cuGMqR282hSm7@E7pjMOKW/RDMPtEOfRpjmrvm8jckDm@JbKDRyh5hIDBl5ovmU0ZV0a2NV3oL1r1qhLCKUcUQlJbMTFAT8E39GkWWBOKrLmWrTMrZim4EDFmnV6cw@/WWqK63sNBltBiOkh8/EbQTf0mW470LoSrVXa2fR8UbFN15N5UEK6PRgJ0saEyFKIsDlM9MKxOpVyuYQBRyYC1QHHkzGwHZlc/I1JQyOlGscbi1dbdM6OTVCDTMV5zLC9zpvztfDt3D9BxvUhn9t8su0hhPQpWYCQVTlZBCAlKY@tQNQkxPdC7VIblnr5Koi9wCktS62ODSDqNJFsy0EMW0kq27Ve4FY2A0fs2OTBEdUrZqL1KD5SxmCGL8HVY4UOfIttsR/xOb5nbbx6wQJfsh30V02lQXPUC2yNQuXqVrOCEN/me60Nwb81ZNHekM2VRkCoVJGZFtmZQtAOuOhEgcvesslP6OFrmks76pDbvMmEHmMff5Ggd930QLN3CefoGe7CtnTDBb4uUiu1LQnwjabLZdFuM8Q3EAax3zhxHPygBFzQy84lQRxS/1IxO@Aufv/EkiTKTStkdXKJ41W2HCb7zQZtRb5UkrXiQxwfEg4@0E2HzfE1N1slBeueNeIsag4HTh4YAvyJRxtucvjZSBZxwE21WnWuGOgnyvP3fMgI/rou1ko3d1AZY@Cu5bE6xp7temS2bxWAzfA3KhMmaO0yIB@0BtKYbdYdHSXQZ1wrnTHahh46jHtGY90hQSmt9iZtUWgHlddlg6CluDdUF/mekJJs@fFRJNBR3Oqz/i3Uc1sX1X1HoKm4j@C/Gwzv9lPQWnws5JMt4M40flUFdJk/P3cLwrV6mWxp0ysS17ZNEv75NX1bAAHKtcr2kYDGAt6BbkWnrQfQWVwVcOvBn79GzJv@juBPNLVX5P5gEc@FC67TmAGB6mM/GeuQGX6ABlLbrrVdxscfodpZV2SAzmE1qvftLfGs/OkClKEzX4C/QF9cmFpWyzkBhxZnEP4DDJ3GDUQLtnhASU3T7JC7@A2DwwZ/DQpRWRr/odG4l0oL@rTfysy2f9BU5nDabZ7asT7@i6Y2hq13rQkSBZ7rpktqOUggXKFcclz91bTTB/UzFEqHhvWzVe@aNrNAw3HLdmbXER/i2xZ@14L/AA "Python 3 – Try It Online") The code decompresses into this: ``` lambda s: ['Bug' ] * any(i in s for i in [ 'Ca' ,'sir','Met','Pa' ]) +['Psychic' ] * any(i in s for i in [ 'xe' ,'Sl' ,'Mew','az','ze' ,'rmi','br' ,'Mi' ,'Hy' ]) +['Flying', 'Rock' ] * any(i in s for i in [ 'ty' ]) +['Flying', 'Ice' ] * any(i in s for i in [ 'rti' ]) +['Grass' ] * any(i in s for i in [ 'ela','xe' ,'Pa' ]) +['Psychic', 'Ice' ] * any(i in s for i in [ 'Jy' ]) +['Flying', 'Bug' ] * any(i in s for i in [ 'tte','cy' ]) +['Flying' ] * any(i in s for i in [ 'dos','nit','bat' ]) +['Water' ] * any(i in s for i in [ 'Te' ,'Sl' ,'ld' ,'iw','tle','Se' ,'St' ,'Va' ,'ya' ,'oi' ,'Ki','gi','Ho','Kr','sy']) +['Flying', 'Normal' ] * any(i in s for i in [ 'ear','Do' ,'tc' ,'dg' ]) +['Poison', 'Bug' ] * any(i in s for i in [ 'ku' ,'ed' ,'eno' ]) +['Steel' ] * any(i in s for i in [ 'gn' ]) +['Ground' ] * any(i in s for i in [ 'one','Sa' ,'oq' ,'gt','owa','oki','Dig' ]) +['Poison' ] * any(i in s for i in [ 'Te' ,'ido','zi' ,'Ek','Mu' ,'fi' ,'rbo','Gri','bat' ]) +['Water', 'Ice' ] * any(i in s for i in [ 'La' ,'oy' ,'wg' ]) +['Poison', 'Ghost' ] * any(i in s for i in [ 'Ha' ,'Ga' ,'eng' ]) +['Poison', 'Grass' ] * any(i in s for i in [ 'ep' ,'sa' ,'ou' ,'Vi','di' ,'Gl' ]) +['Electric' ] * any(i in s for i in [ 'pd' ,'hu' ,'El' ,'Jo','Vo' ,'gn' ]) +['Ground', 'Rock' ] * any(i in s for i in [ 'ud' ,'Gra','ole','On','hy' ]) +['Flying', 'Fire' ] * any(i in s for i in [ 'iz' ,'Mo' ]) +['Normal' ] * any(i in s for i in [ 'ev' ,'uf' ,'kha','yg','Pe' ,'Sn' ,'Meo','Dit','nse','uro','Li','Rat' ]) +['Water', 'Rock' ] * any(i in s for i in [ 'but','Om' ]) +['Fairy' ] * any(i in s for i in [ 'uf' ,'Mi' ,'fa' ]) +['Fighting' ] * any(i in s for i in [ 'wr' ,'Mac','Hi' ,'nk','Pr' ]) +['Dragon' ] * any(i in s for i in [ 'Dra' ]) or['Fire'] ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), score = 566 (566 bytes, 100%) > > -6 bytes because 3 Pokemons actually contain their types in their names (and other simplifications) > > > Even if a way has been found to answer this question by "encoding" the types in the casing of an arranged Pokedex, i tried to achieve 100% accuracy without using this trick while trying to outgolf the other 100% classic Javascript answer, and it turned out pretty well :) The input is the name of the Pokemon in lower case. The output are the corresponding types, with only the first character uppercased, and multiple types are separated by a space. There is also a trailing space if that's acceptable. ``` s=>`NormalDgAttIcaEarUfWthIaFeDodTuNseSkTauDitEvYgSn_BugRpiMetFrEdKuPaScEnoIns_GrassSauDdGloEpPaLsViExTan_RockUdAvOleNixOmaRhKabAe_WaterRtlOiPsLdIwTenSloSeaSeeWgOyKrNglOmaStaKabGiGyLapVa_GhostStlHauGen_PoisonSauEdKuEkArbNidBaDdOoViVenLsWeNtGriMuStlGenKo_FireHarVuEsWlRcPonRapGmFl_IceWgOyJyLapRti_DragonTin_ElectricHuGnVoLecJoPd_FlyingIzRfDgEarBatDodScDosAeRtiLtrNit_GroundDsOqDokDigGtUdAvOleNixCubOwaRh_FightingNkPriWrTmMac_PsychicBrAzSloWzPnExRmiJyMrMew_FairyEfUfMr_SteelGn`.split`_`.map(t=>(r=t.match(/.[a-z]+/g)).find(e=>RegExp(e,'i').test(s))?r[0]+" ":"").join`` ``` [Try it online!](https://tio.run/##hVdbb9vGEn7PryAkoJGi1KkLtA8F5MI@khUnvkFybBRtQA/JEbnmcpfZi2Tq/bydn9D@uf6RdJY3UYyL8yJpvtmd3Z3LN6Mn2IAOFcvN90JG@HU9/aqnJ4/XUmXAZ/GpMRchzEF9Wj@Y5ALOcSajO3utcZXegZ0xM9/8Fq@Ef2bjZc6u0JyrefTR3sIqnAt5IbS/UKD1itZGCy7n@S1c6ns2f74D4S9lmH6KTjc3HK/Z800Gy@QjBKfoP4BBtTT8ht3qy@hie4dixeUKYYX4EN8UH9V1zGn9ygBtWLBFcQn5PfiLRGqzMvw92AUK/1YyLQWd7a40T09VcM2iM5hFN/Ke3aO41A94bRaKXVnaRDs@Sv@cKXwP6t7O9QNfhrdSLCFfZOfcvwjLsz@4s5aG@TMFsRR3TPhzjqFRLHxvF@JeXmL4Qd5G/jkvmIgvdsv1LCYPnoEh363CmdSnSPsvjbpmhtwjrYhm@ubLTKYzFi/M3iP/scHNlpxCl4oTQ8au01vFHtRddgWhf6uLMGHhmTrdkXMedrdi/rzM2IfiSl3h1j8Hpor5@tP6Svkrg8gX4vFI55yZR//xKIN8ZKYnIzU19NuEyejd0e/w/e7z5F08Hh@tmYhGOD1ZYjx/zkf49jV7PT4yqM1Ij8e/qt9/@DwZeINfBoPx0ZNk4vHxK0UZlZmOmMiteYvPOfkEozGdMVKoLTfTdaUbj6fTaaP/dTIJyQEU7u@@G/z953@dzb//@p83qhb8Mpg0KyeDsecNxpPSxlEO0ZyuePzjeFJZf1UfMhi8EsFZQVed/vTzz69q49MfXg0CywPQYNWwTEmvyg7PZ5viBXSDwr4AhwlQZYgI1dBlSg0gRyk6ANuBiiq5ygLP118sU4bjsMxtz9@CMrILBBy0oVNaIHRfOcMh1ZbnZ2ggl1ElBNaQbq2wUjZnbBEjXkHNfVNIrYADKKBVinF@AOYsirEYVnXfGixRaYz8F0UfVmAMGGhgJzP3jBbQOYKS2/6@9YsopiD0sLkhqECmw/19UwgTO2xKz53FDgFNYdKJwu2wqrEaITcnLSJYJBWI1mwpM3JYF/hiEdsl/2enPABSekd/Y8hx7UpzWBZoLQcUtlreWJ6z5zqZBBMUd466lp9YHPMit@t166xq17ZUmG8VOxuAae7QeDaW/AVURhErfdNN@JhLmfVrg3HMuc2wh@dAYplWFV4BFI8uRoUlBZiD7HNYJk1yAEYs5mhMG6vIxhRY2coZyi1taVIrR6UZBaSVdRHZMG2qiZ7cFamGU8r3hlhpuWIZQo4dKKacJLpMsHY@qBBcQGoxl5xtIW4slmLCFD8AqAKSGtgbhkBRhlX07Uo0OgSAQwo7yPZIRrku887VSiDFHgJZd02AnOucnGV6YSKayJlw6m/iSqWDSJqewqAwEErZvO0QVxb7CiKHyEY4dB2@zfxYwYaYUvVQyTE7hHIpCmKRys0KiGxczVai5nKbu6fXBzYucnigZB/OIBaYMaKglhjKZlhrDNF2X7EGtUbqiK@jPiFF9Cj5AuiysodqbH3iR7ilQaFJFBojnCso21TLFZndM5tOKDCuvzRtgMtCm1autlOr4MWwHHdanydQtroeGqOIoQ9KQQxz4PKIcn1H7aR1XFLkjszaJFUQBEVzJ8drfH/FjeTUy4IO92L5iwbKLvaMcRxa07JGY7tUWLLQV4Q2kAL3Be@aBKStnDCTScGxWwYVRqUgOiBnYcqMpRA05JDK9brDza4kdl1ZJUUilTj0EYGR7GHuJL1vnL4BESOH@iVU2@R9nSYdXiK7GqFxHf2MFHRJyvWavbLsII1oQBW2K2XsmzrI1JGXUXK1oav7gA4LYjJ1MC88FeJ56BJqHwoXLQjsbtcJHFUKub5hPSY0q8zQY62Sun0ZraOurPL2NQXRf0QLav6rT@WQuzbRSeeIdUYMH3GD@4lhQ1OPctNVbfSJcg27VeuvOaj9@EWrC6q2dr8kpqdpsIpabYMw570DLKVX0yW@hXJ9AAJSWkNoCl7BbcELqTg8t@fSeMdCSyXkXtgs2kHu/NHevcEzepRqmnxLLG56EmxY/c8oZfqmaPYQR2410trDrdl2qpfkVhjs/wSspZpT2xjl05Nqep5Mqyl@lNeLho806b/tSMefx5PBH2IwpslaaKLuIy7jEf0VaMb4yeDd8U/HHk1ahNWTOP1VCNy353nT6Ql96pBi6k1pxahe8mZ07L3zRrURZ2LsvXnj/TgeH55U3XP89R8 "JavaScript (Node.js) – Try It Online") --- A little explanation: Every type is accompanied by a list of strings, that are as short as possible (2 to 4 characters) and that matches any part (ignoring the case) of the highest possible (when useful) number of corresponding Pokemons, unambiguously. Dual types are achieved by matching the 2 types separately. The casing in the long string is used to delimit the beginning of each value. I did the long string by hand, but i think that this is the shortest possible combination. I don't know of an official golfing way to compress the long string, so i tried to develop a custom program (by using 6 bits instead of 7 to store each "character", because the ASCII values of the long string are all comprised between 65 and 122), but sadly the gain in bytes was inferior to the length of my custom decompression code (a hundred bytes), so i gave up on the compression. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 57 bytes, accuracy 148/150, score ≈ 58.5509 ``` e€ØaḄḃW¹?⁴UÄị“Ɓ[0ḲTọŻZ4⁹ɗrƑkṭkẏḳoḂʠCṂtɠØƭ⁴Ṡ¬ỤþV⁶Ḳ¥;0ḥȧ»Ḳ¤ ``` [Try it online!](https://tio.run/##XVS/b9tGFN7fX5GhQKcWHboZaHEkn6gLT3fM8ShG7nS2rqQimhQoKg49xW6ADEVRdGqGFsiQoEuytEFhV0AHGw2a/hf0P@I@Sp06fd9Rd@/H972nR64su7s7d3vx5uaF7S@f9ZffZNdXX96ev0tvnvXbb2@f/vT@/KvP@stfTb/97q/t4ee351cffmze/7Dsr94u@z@@7y9/q/vLi39e@v3VRfvh5c2L92/peX/18vpNv3118@f09vx3en/9@oDCvP77l@vtcHp1d0Cx733yxb3bpz8f3DyPPoJ@@@7mOVUyu7vzUuHZhG008Gm3wynKzY74Y6YnrArwP4olKknUan5odQDJg5Q3pnSQMW3UjnmCJabmawc@M6hj7mCChsVqDl5qjGtGGh2cIgbCwZJFqbTgoQs0FyXEiyDHGcQ8CJ1qjSI2J2ZAM2OssQNy3xoHSexYozIY7QEjVq2Baa9e0puIHRcbussHSJgMkkLj6Z6VLClA8kBpW@2RV5bIvH6Qoqv@/1MNcjFXEa9y8AWO7EJ3e3JE5U/TMuYP6apEYwUmcJ/noZjFm9HXkO2oGehZ6tkWwloMoOYBX48hF6qewJQLXIn0BGHFNFtDzLRN0G9h6qSSjBArNVGmgICHJZoWgjRsNa9JU3VKn2PUyYJVECezeXq8hFCJHZJpS9dBrPnE2ZWDUKtMLMwYSSOfVVQwxEosMpsPyLOCN6S@KnnWsLYA5mkGEQt2yASL2CGbUNDjol4R@EW9dDu0JytyT4hkpdXGQIYY88rDUlBrvtEOPSfAOGmYr@oSDFbEdOpKCLGep8FQGXvsBDaQ1wJPqIZqZhh5R86zZAxJWWcrRdnWpTr1Gmqc5ZWbLFrKb/MK27qCEdMjbP3i4wDmap4qCOqg4QrWSHkCPM0VuRcOUjQw2SwhGaMoAzr4QnVrGknIbWLKDsZ2I3dHJ0PbQC35EwhIuUNEGM9iqSDS1jvqIOIyF3RxqoSpmyNAgdRtPXeAT1ye@2mLe5aamlYnPVJy0EvXGVvCmJuJqkrn9kweFzRugvsRNxuZQ6RGo2HcSMvDAfW4K5SuQBddoKphD@UaOzBMhlgOLsmQJVFBQzBWTeIsJGiDxu5GYRjoBNlyiJMYq7sNrFvWTBZUTfPpvZPFhDbpuKO5aOBRJx/uG2He5uxsEJoqpm2SCW8oXdqoNX0M@ZI1Kwg727C5SkDYlbZrms/W1ID4mJZ7StveIBlzn@Rxg0GCNcMfR6z0jMwANbHVjCQiXFNVENmjtCVxKXGrVgkwJC2Z384EJFLpkj0Bq2nxN@TAmY2HtCcUuqGNC7Q1XHJCFtaScQ3Ue6jkwiDtSGYyNcC/ "Jelly – Try It Online") A monadic link that takes a string argument and returns a list of strings. Taking inspiration from [@JanH’s Javascript answer](https://codegolf.stackexchange.com/a/265167/42248), this relies on the wording of the question that states that the casing of input and output can be specified in the answer. As such, this answer expects the input to be one of the following Pokémon: ``` BULBaSAuR IVySAuR VENuSAuR CHARMAnDER CHARMElEON CHaRIZaRD SQUIrTle WARTOrTle BLASToIse CATERPIe METAPOd BUTTerFREe wEEDLe kAKUNa BEeDRILl PiDgEY PIDGeOtTO PIdGeOT RATTaTa RATICaTe SPeArOW FeArOW EKAns ARBok PIKAchu RAIchu SANDShREw SANDSlASh NIDORan NIDORIna NIdoQUEen NIDORan NIDORIno NidOKIng CLEFaiRy CLEFabLe VUlPIX NINETaLES JIgGLYPuFf WIgGLYTuFf zUBat GoLBat OdDIsH gLOoM VILEpLUmE pARAs PARaSECt VeNONAt VEnOMOTh DIGlETt DUGtRIo MEOwTh PERSiAn PSYdUck GOLdUck MAnkey PRIMeape GROWLiTHE ARCAnINE POLiWag POLIWhIrl POlIWrAth ABRA KADABRA ALAKAZAM MAchop MAChoke MAChamp BELLSpROuT WEEPInBElL VICTReEBeL TeNTACOol TEnTACRUel GEodUDe GRAveLEr goLEm POnYTA RAPIdASH SloWpOke slOwBro MAgneMite MagnEton FARFEtCh'D dOdUO DoDrIO sEel DEwgOng GRIMer Muk SHELlDer CLOysTer gaSTly HauNTer geNGar oNIx DROWZEE HYPNO KRaBby KINgLer VOLTorb ELECTRode ExeggCUtE ExeggUToR CUbONe MARoWAk HITMOnlee HITMONchan LICKITuNg KOFFIng WEEZIng RHyhORn RhyDOn CHANsEy TANGElA KANGASKhAn HOrSea SEaDra GOLdEen SEAkIng STaRyu stArMie Mr. miMe ScyTHEr jyNX ELECTABuzz MAgMAR PINSIr TAUrOs MAGIkArp GyarAdOS LapRas DItTo EEvEe VAPOrEon JOLTeon FLArEON PORYgOn OManYtE OMasTaR KabUtO KAButOpS AERodACtYL SNORlAx aRTICuNO zaPdOS mOLTrES DRaTINI DRAGoNAIR DraGONiTE MEWTWO MEW ``` The casing of the Pokémon encodes a binary number. If this number is non-zero it is interpreted as a bijective base-16 number. This is then reversed, cumulative summed and then looked up into the list of powers. Zero matches the last power in the list, psychic. The powers are lower-case except for grass and ice which are title case, since as @ais523 discovered this gives the shortest compressed string. The precise compressed string here is different because of the different algorithm used. The two missed ones relate to four-letter double-power ones that are too short to encode their power in the casing. ## Detailed explanation ``` e€Øa | For each character, check whether it is a lowercase letter Ḅ | Convert from binary ¹? | If non-zero: ḃ ⁴ | - Then convert to bijective base 16 W | - Else wrap in a list U | Reverse list Ä | Cumulative sum ị“…»Ḳ¤ | Index into compressed string split at spaces ``` [Verification of accuracy](https://tio.run/#%23dZjNj@NIFcDv9VdwGGkvJcj3h@aAKkl12hPHztpOZ7s5VeJqxxvHlS3bk3GfZpaVVgIhBBxYJEAj2BGXXSSGFZpmEIdubYvlv0j/I8Mr20knmeXSSd7vVfn51av30R/zIEjfveP3n351@wXbvPls8@ank5vrH9@/@GZ8@9nm7c/vn//@7sVPSps3r53N2198@/aidv/i@rvfyrtfLTbXXy82//zl5s3fxebNp/992d1cfxp/9/L2i7uvYfnm@uXNV5u3X97@@@z@xT9g/c2rx7DNq//85eat@vXluzpsf/v5t78OHm@u/3T/4l83r25eVXENpCC7ub77HMSP7l6jzdtvvv3N5vrPYOP98z/gx7efP4KvJdB7dPvHjwup@nn/t7/a989/9@gxGP2jcr0E8sndzx7fvT5/966MO0kwZRFLJO5LFkV4JPxIhLgz1jvMJomFKlh7mr6voJ2lGa7iMx4m7/MzaiSZQg1350wuWehyiU98yTHunhJrSMIetVA9pzzgsGaP0oCaBmpk1L9i0s3hSZD6oQcqzNIumNVDTWx/kvgyDjiesBiegO0Px5p0Ao5aIJGx2GcTYjlmBtu4E7AoBlt3sKMT2xFaxFG5hLtKtvI5@McDk4hDrZEGpIyHPGYr4eZgSB0yMl1UrsDvGJZcSp6vKSztjB2HyxOLwtoqnnDuBjkv3LSmtKcDq@EBWyQh22cLMhgbDJXruAPrpB8E@7RDec/S9ACVG3jkux5PsSHAz8H20SO/59FzVG7mWMSxONbQen1uxo6Jyq2t0nsqLqg4qNzGFotjFrOtAraI4zCHoUpJIX8GHttnWpc5HFXK2F5xJsX6aGN7xIk0J6hSwSffx08KXMV0wcJdWGE6IGGEKjVM5FQsdmJidcQCVerwGgs2myeYBnwWS3@G4RUGBCSo0gA7/UNmES1DEEYQoNFc8jWEsUhCFwKJGD17btE1qrRyDBEzP8QBseeo0saG7wrJwp05htYzLRaiailHPpzsAdNChqrlDH6ScL5bWexuaK74cEw57FD5/5tXt5uL480FqtYyuMgO8XBv3zUHWuihKly@gF8yX6b4JPuLuzqFb1aKqo2cTSFc99kUgrXaxGdJsPKfFRf2bByMtI9QtQVbh3A7Ah4VxNAM6jCd2qjaxk98zwvSVXJ5uTvqbOMnmtfXz0fJySWqlfAk04rf05pkWk6mVcYXyZTF2/cqIuZq3GExqlVwXwTv077QM1zFpuv62TnuZSvT7WnRKarVcD8QYnkIPd0UQ1Sr4zM/4KsgWfKjVKfpdKWPlxTV4CoyQNk9zXVWxCIRqjVzAHG3x0bEYjbtglUtlUVFyOL9G37GDdMgQNsZXYp4foBpaA5NZ47qJdzzvYDH8S44e1o/oE6M6mXcSzyIdfGAxv3Y0gSqVyCViTXsub20Q2qu1XZVPOIy8iHitmRELdsnIarX8ChK3WS22CbNkX3ujmcLVK8rt@@TvqnnpIGHLFxAejrxvXmszgJD8gcBqoNXpL/kbMX34MjShkqE6i1l9Drw4zkvAqpvmRPdd04pqrchA8xYCBFXMGJ1SQgBhxolcFHgr5m3s9LU/QnzUKOck7kvgz2mTeaaDFCjklPJwCk53Vk1MgNtIkk8R40qJlPJlCNmc5VDSMciqKESuMsOwID0clbHJGALdsWWe6t0MiAXZIgayj@zuVgd@EcJUKOZowU/YF0lQY1WBtlydQRBghpQ36CHiVZw6PFRZae6bq8sM3FQs6Qq0soPp6B7qDWhdKSFHRroqFmGwId8yTmoHUd@17E47XDQqmCHhzGbCbF1baHkcMMhXVMEqFktdGTCj5VoCErWmIMWXEIu3MTl2BIQT0Xg9qlwxz2OmnVlw1PoGOQht8hTrlOJmg0Vinx5QD2h0yVqQsCJMIUilofMyAzPHYKaLagMK99V6T0HFoHCR@xT1GxjOxDrlTqDwuDiBEE8WZlwEK1SpjKV4kgjCsx1RwrUgqaBeSFf@lAhd7XHjjk4YUgADAGgViXXisEbx0ogpyBHrSpkQ3nJ49n8A/e4YBLrhMbd@Qc91KrhHjjwuNy7pjs2UauuoMoIh7QnelID3MA2350OjiicSKuJe3ztiXB7obQZxz269kyoIi11S@ES744STgIusEStNh4mDxUavqM2uGoOsaZawW27dkr1oAfq7TJUHJFG8Y6pp3R1M40chSGvQ8MWpLg/F9Euu3vMdoIUtav4lCWhWnWAQWhkq1VMhR47wh43@gxoHZshlLP9gBGG9gy1G7gHGegKerrdxe1BCrqgFLWb@DRdqdK7JafnI8NE7RYeSDadpts3HFisMwUT23gAfg4eXn2gGZ4OxpVLJXwmAmhVp3utyZmpOyABWi6kwt0LH0x1CpcPZKBRwfQZ97xZEu9KU2FUJu@OYwpa1fxXAg/6Pq2xIyzQgn49mYqQ7wpGdzw1DfWUOgQieIPtfATRa4kJWQBr4FM/Xoow4Pu56lRzhqaSgUaz0ICUFR6rGEoIOi2s@7OFHydAtrVH17oDzUkMDzi4UFxe7rU0eGCenKheplzOctnVPoMcdpGzMrbm6VzIXQ@UnbR1ms5NC54L3TtwVxzhedozFa2qKSSMHhpsNaIYEU2B1bDDQo8HrPAodojRpwEBVIeKACEXLeZ7lXQAmNiDOVEbg9OEjDjbBsSpKW0ODT@07PDpyh2wKetJBVpZlVX94l6VVW1iGRp0WJO1e7tFZJG9PjTodsxkmuyIw6w0AVDOwNI/zm1RTOTQh1OD7nwof/iDIdzvHcz7MSVe@kOlU8X2LIUaLfcHHxBBmYbghlb9SRo@y27zdouPU@MjIPU8nNk0ubo6jmzSASHoqOroLdl2dIR8CUEHcjXVhJGfPxN6fMPW1MNacB6JFNHO4Q4ZSzMC0lYbwXAgV1s3DElfWxC5gsmshPsp9GcuLCwKf9E1gpS4pg0qZayzlertHpITCCwGe0OP3vP3xitov2JHgBxuHH/KH8YiSp9mg2ANn8EMKdXMW9hyBmOkpJDiy9CVP4FkwPfLAH4CyYBntAGmMfkwLZ/oRKpRuVxVtU2mkKUf2jbTOvdUCENrbsIEnsZFSc0fakJfdq4yAzTngCMIhSMcQaDAbFqCSJ5C2tinIBnHMDhCM57DVXSA4fxicwWOg4accMhdbBanQa5SOJdQSF@kG5/roAVBFAoZsGc7623DtALyDJga9mDATCDZKrcXy5kFM2ZiKBvq@IKt1OHtPLadCdgoOz1ozIfgVLmdTAq8BLdKqjhUOGj7/NBXn8qHkOeZoxkasFYhg7jfo6QvDKIp97QLqSrvBd/WVMn6puE74GNo0od8Ha/36sWQTpwJmF9X/1RYH8j/Bw) [Answer] # Python 3, 888 Bytes, Accuracy 86/150, Score 1200 score is 1200.64... but that doesn't matter. Here's my pitiful attempt: ``` s="{'GasPs:BarIsrVsOiGomVpeBpWnVe,Fr:CaCeVpNtsGleAnPyRdMmFrn,FrFi:CidMts,Wtr:SrWoeBtePdkGdkPigPwlSeSlKbKgrHsSdGdnSkgSrMkVr,Bug:CrMadPs,BugFi:BrStr,BugPs:WdKuBrVotVm,FiNm:PgPeoPgtSawFrFtDdoDr,Nm:RtaRcMwPsnLigCnyKsTrDtoEvePynSrx,Ps:EasAbkNonNrNrGmMukKfgWzg,Et:PauRcVtbEteEaJtn,Gu:SswSshDltDtoCoMok,GuPs:NqnNk,Fiy:CaCa,FiyNm:JyWy,FiPs:ZbtGb,BugGas:PrsPs,Ft:MkPeMhMheMhpHoeHn,FtWtr:Pwh,Pcc:ArKaaAaDweHpoMtMew,PsWtr:TalTc,GuRc:GdeGeGlmOiRhnRd,PccWtr:SpSwoSre,EtSel:MeeMe,IceWtr:DggCsLr,GotPs:GtHnrGg,GasPcc:EgeEgr,Gas:Tga,FiyPcc:MM,IcePcc:Jn,FiWtr:Ga,RcWtr:OneOsrKuKt,FiRc:Aa,FiIce:Ac,EtFi:Zd,Dg:DtiDor,DgFi:Doe'}" for i in ",', '",":': '":s=s.replace(i[0],i[1:]) d=eval(s);h=lambda x:x[::len(x)//2] def f(s):r=[k for k in d if h(s)in d[k]][0];return[i for i in "Bug Dragon Electric Fairy Fighting Fire Flying Ghost Grass Ground Ice Normal Poison Psychic Rock Steel Water".split() if h(i)in r] ``` Uses the fact that the `s[::len(s)//2]` subset is pretty darn good for uniqueness, for both names and types. Stores everything in a big honking compressed dict, and fails to be good. [Answer] # Python 2, 1022 bytes, 100% I generated a hash of each name and only recorded the unique first characters, then for the types I used bitwise operations. It didn't work as well as I'd have hoped but here's my attempt anyway: ``` import zlib,base64,hashlib;d=lambda x:zlib.decompress(base64.b64decode(x)).split();h=d('eJwdkcsBBCEMQlt5JaiJv3LUaP8lLLMHnEQHhLjSoHfWJXawUsUTMQknjNYPxan2KI2XjFI4HXMd70aMyvtOXhfUH1EK85GdnYqEo1AHzRa1f1u6ri6uiOaLojI4L7iPLU5FsttwPzyR4pEyyZHPNKlyM/zpq8tiMwulMo7+Twzt25W2MLkm3cw6R5BQDFl9wsWy2kZLEr/I8NtbywwF6szDvKg5l5ap0mqVJls74lsWivry5mbNxMmHqyz7uuK+TdMUQrxQ1IFNKTszcTJT+a4qkZJIf0KSpsaXjaV+yZZzti5x+qar0On4PE6sUcyFhNXLOQNvjLTwgmfNZmtspp3O0Gvp4d7Tk33xJHRZkz7Y+QpHEHFLqoiheZ1AQZrNH4nfgPQ=');n=d('eJxNUYkNAyEMWyUjhHzQ/Rdr7EBV6STAefycyVILMQlx21vF8gxUjWbde2bMc5usEhePPkMVgGMexVgagkfPhidb0d2QxkeWFy7nLmHHa7tshbW9wBu00wsXLg/GLGEA/WWXuNkUjNPeWpsHpTHkY2G/ylIJHQw7s34a5kSh6S3+tMJoXJlPCHD/2C+VEz0V4KOahY7rj/25i+G+oJEN9xlM0bFCGJ51Qx5H45sixihAnxSaxmnOm5c67MzPYaSYdFI/t0MMk8dNLw8y4iSxyVL8C+8IYSA=');f=lambda x:','.join(v for i,v in enumerate('Grass Poison Fire Flying Water Bug Normal Electric Ground Fairy Fighting Psychic Rock Steel Ice Ghost Dragon'.split())if 2**i&next(int(v)for k,v in zip(h,n)if hashlib.md5(x).hexdigest()[:len(k)]==k)) ``` ]
[Question] [ There are a bunch of different casing conventions, like `camelCase`, `PascalCase`, `snake_case` etc. It's annoying juggling all of these, so instead of choosing one like a sensible person, why not cursedly mix all of them together? Your challenge is to, given a list of words (only containing lowercase letters), convert them to backwardS\_hybriD-snakE\_kebaB-cameL\_case. To do so: * The words are joined by alternating underscores and hyphens, starting with underscores. * Capitalise the last letter of every word but the last. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins! ## Testcases These are formatted as space-separated words ``` hello world -> hellO_world beans -> beans one two three four -> onE_twO-threE_four backwards hybrid snake kebab camel case -> backwardS_hybriD-snakE_kebaB-cameL_case test three words -> tesT_threE-words o n e l e t t e r -> O_N-E_L-E_T-T_E-r ``` [Answer] # [Python](https://www.python.org), 72 bytes ``` lambda s:re.sub(" (.*?) ",r"_\1-",s+"x ")[::-1].title()[:1:-1] import re ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY7BCoJAGITvPsXPnnZLBW8hRNfeISN29RfFdVf-XTGhN-kiRL1Tb5NhBF5mmA9mmPurG31lzfQo99mz92W0ex-1bFUhwaWEsesVZ8DjzUEAC4ldsiRioduyKzBxStMoOce-9hr5nJJvDOq2s-SB8Ld366g2npecVai1hcGSLpgQwZ8rlMatiDUIfrDgK0KE0va0Lsi8GSQVDqpRUV2AM7JBaFBJBblsUc_qcO4sH6Zp8Q8) #### How? Uses regular expression to substitute pairs of spaces. To make sure every space is handled the auxiliary string "x " is appended. The result is reversed, `title` cased and reversed back. The auxiliary string (which has absorbed one unwanted `title` casing) is removed. [Answer] # JavaScript (ES6), 50 bytes Expects and returns a list of ASCII codes. ``` a=>a.map((c,i)=>a[i+1]^32?c^32?c:C^=114:c^32,C=45) ``` [Try it online!](https://tio.run/##NU/BboMwDL3zFRanoHXR2LpLKzpNaF@wI6KSCaYwQlw52dC@nqWUWfKTn/38LH/hD3ojwzU8Om5p6YoFixPqCa9Kmd2QRVIND3l9fnl@MyscynOR5/vDje3KYv@aLccqAUh7spZhZrFturs1GkLn7yU7gjAzhF6IoONv2SRoxhml9dD/NjK04B2OBCM12IDBiWxET3dxIB82h3il/bcGBwQ2ZhxGlDSpE92xfKDplYfiBIadZ0va8kV9BhncRXfCU9mjlPFrpbXuVBXR1@vnZl3SZpu/B/WUrbH8AQ "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = list of ASCII codes a.map((c, i) => // for each value c at position i in a[]: a[i + 1] ^ 32 ? // if the next character is not a space: c ^ 32 ? // if the current character is not a space: c // leave it unchanged : // else: C ^= 114 // make C switch between '-' and '_' and use it : // else: c ^ 32, // inverse the case of the current character C = 45 // start with C = 45 (i.e. '-') ) // end of map() ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 13 bytes ``` Y`l `L\_-`. ``` [Try it online!](https://tio.run/##DcQxCkIxEAXAPqd4jWCj4ClsvIAgmN2fJ/lkTWATCZ4@OsU4x17lsg7Ha1z3aEC8PZ6neMZamWYNs7mloJTaQ6vEmA0jO4lX@3hQ2coUTx35q74n9CqFKFRRbPKm/e/8AQ "Retina – Try It Online") Link includes test cases. Explanation: Cyclically transliterates each space and the lower case letter before it. Since the two transliteration strings are the same length and the lower case letters appear exactly once each (via the shorthand `l`) they are simply transliterated to the upper case letters (`L`), however, there are two spaces in the transliteration string so they get alternately transliterated to `_` (which needs to be escaped in a transliteration) and `-` (which fortunately doesn't need to be escaped at the end of a string.) The best I could do in [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d) was 23 bytes: ``` T`l `L\_`. (_.+?)_ $1- ``` [Try it online!](https://tio.run/##DcRBCgIxDADAe16Rg4cVccEX@AGPHoU22Wbp0thAWim@vjqHcelHpTmfUTE@XiGuCEtYL/dzgNPtOmcWVcNhrglYqDawKtiHYc8ugrt9HJi2MshTw/xlPxK2SkWwCBPjRm/R/01@ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Since Retina doesn't have cyclic transliteration I just transliterate all of the spaces to `_`s and then fix up alternate `_`s to `-`s afterwards (which has to be done longhand as Retina 0.8.2 doesn't have step limits either). [Answer] # JavaScript, 52 bytes -3 bytes by emanresu A; -2 bytes by Arnauld. ``` s=>s.replace(/. /g,c=>c[0].toUpperCase()+'-_'[s^=1]) ``` [Try it online!](https://tio.run/##bcu/DoIwEIDx3ae4sNBGAZ1NWXwGJ4LmKMcfqb2mhxKfHnU1Lt/yy3fDJ4qNY5gzzy2tnVnFlJJHCg4tqSKHot9ZU9pqX@czn0OgeEIhpbdpdk0ruZhDrVfLXthR7rhXnUoGco5h4ejaROvj5ocbQi//gD3BvDDMQySCjh/x7452WjC2AsOriWML4nEimKjBBizeyX0q9F3XNw "JavaScript (Node.js) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 12 bytes ``` ṫ$RǐR₅‛_-ẎYp ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwi4bmrJFLHkFLigoXigJtfLeG6jllwIiwiIiwiW1wiYmFja3dhcmRzXCIsXCJoeWJyaWRcIixcInNuYWtlXCIsXCJrZWJhYlwiLFwiY2FtZWxcIixcImNhc2VcIl0iXQ==) -5 bytes thanks to emanresuA ## How? ``` ṫ$RǐR₅‛_-ẎYp ṫ # Tail extract, push a[:-1] and a[-1] $ # Swap R # Reverse each ǐ # Capitalize first letter of each R # Reverse each ₅ # Push length without popping ‛_- # Push "_-" Ẏ # Extend this string to the length Y # Interleave the list of words and each character of this string together p # Append the last item of the input (pushed earlier by tail extract) to this list # s flag joins this list to a string ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 25 bytes Anonymous tacit prefix function. Takes list of words. ``` 1⌊⍢⊃⍤↓⍢⌽∘∊⌈⍢⊃⍢⌽¨,¨'_-'⍴⍨≢ ``` [Try it online!](https://tio.run/##NYq9CsIwFIV3n8LtLnYQH8FFV3WXxNxaaWwkrVRXhVJLI4oIzuLQQXBxdemj3BepieBy/r7DVtITWybV3MNNgpFA0TRdKgsydyr2ZB6UXVwuP5TfKC@ozP/IjXXVqSuYekDmTaaiw73xKTuROf4uTzvXrx5lZzpex6O@1clgOG58CFBKBW1IlZYCWn6Hih1wZFFsC6gILUtS90gCja75aq0d42wWpkyL2G7BluuFsCGOWOhOIXLGrc/YEuXPY4Qv "APL (Dyalog Extended) – Try It Online") `≢` tally of words `'_-'⍴⍨` use that to cyclically reshape this string …`,¨` concatenate each of those to each of the following:  …`¨` on each word:   …`⍢⌽` while reversed (reverse back again when done):    …`⍢⊃` while the first character is extracted (put it back again when done):     `⌈` uppercase …`∘∊` **e**nlist (flatten), and then:  …`⍢⌽` while reversed (reverse back again when done):   `1`…`⍤↓` drop the first character, and then:    …`⍢⊃` while the first character is extracted (put it back again when done):     `⌊` lowercase [Answer] # [Pyth](https://github.com/isaacg1/pyth), 16 bytes ``` ts.e+@"-_"k_r_b3 ``` [Try it online!](https://tio.run/##K6gsyfj/v6RYL1XbQUk3Xik7vig@yfj//2il/LxUJR0FpZLyfDCVUZQK5qfllxYpxQIA "Pyth – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` í™í`l)„_-ÞøS¨ ``` Input as a list of words; output as a list of characters. [Try it online](https://tio.run/##yy9OTMpM/f//8NpHLYsOr03I0XzUMC9e9/C8wzuCD6347/U/WikpMTm7PLEopVhJRymjMqkoMwXIKM5LzE4F0tmpSYlJQDo5MTc1B0wXpyrFAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w2sftSw6vDYhR/NRw7x43cPzDu8IPrTiv5fO/@hopYzUnJx8JR2l8vyinBSlWJ1opaTUxLxiMCs/LxUoU1IOki/JKEoF8dLyS4sgyhKTs8sTi1KKgYIZlUlFmSlARnFeYjZIVXZqUmISkE5OzE3NAdPFqUqxsQA). **Explanation:** ``` í # Reverse each word in the (implicit) input-list ™ # Titlecase each reversed word í # Reverse each back ` # Pop the list, and push all words separated to the stack l # Lowercase the last/top one ) # Wrap the stack back into a list „_- # Push string "_-" Þ # Cycle it indefinitely: ["_","-","_","-","_","-",...] ø # Create pairs of the two lists, ignoring trailing items of the # longer (in this case infinite) list S # Convert this list of pairs to a flattened list of characters ¨ # Remove the trailing "_"/"-" # (after which the result is output implicitly) ``` [Answer] # [Python](https://www.python.org), ~~86~~ 80 bytes ``` lambda s,i=0:"".join("_-"[i:=~i]+w.title()for w in s[::-1].split())[:1:-1]+s[-1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY5BCsIwFET3nuKTVYK26E4CvYP7KpLYH_ptTEoSCYJ4ETcF0Tt5GyuK4GaGeTDDXB_9KbXeDTdTre_HZIrlc2XVQTcK4oyquWSs3HtynG0LVpOsLrSZ5jJRssiF8QEykINYS1ksNmXsLSUuRC0X7zyN9ajf3XMfyCVuOGvRWg_ZB9swISY_rlG5-Ee8Q0jZQ2oDIhh_DP8FteuyCk2E9qQDNRCd6hA61ErDTh3Qjhpx7Hw-DMPHXw) -6 bytes thanks to @xnor [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` ⭆θ⎇⁼ §θ⊕κ↥ι⎇⁼ ι§_-№…θκ ι ``` [Try it online!](https://tio.run/##bY1BCsIwEEX3nmLoKoH2BK6kuOhCENS1TJLBhqRpO2nVnj4mgjtXA3/@f0/3yHpEn9KZbVjEZcnnccJJzDVciQPyJo7zij6KCqoaDksXDL3LuwuaaaCwkBFOSlnDbZqINUYSVv6fl/yHqO5NTtpxzd52057afvx6XS7ldiHazJX7lBRq90I2EfpNsTUQAzoCRwoVaBzIQ/HuUvP0Hw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Similar approach to @Arnauld's JavaScript answer. ``` θ Input string ⭆ Map over characters and join ⎇⁼ §θ⊕κ If next character is a space then ↥ι Current character uppercased ⎇⁼ ι Else if current character is a space then §_- Literal string `_-` cyclically indexed by №…θκ Number of spaces in current prefix ι Else current character Implicitly print ``` I also tried an approach based on splitting and joining but I wasn't able to get it below 26 bytes. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 19 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` mxδmxhû_-*▒^\£<─~;! ``` Input as a list of words. [Try it online.](https://tio.run/##y00syUjPz0n7/z@34tyW3IqMw7vjdbUeTZsUF3Nosc2jKQ111or//0crZaTm5OQr6SiV5xflpCjFckUrJaUm5hWDWfl5qUCZknKQfElGUSqIl5ZfWgRRlpicXZ5YlFIMFMyoTCrKTAEyivMSs0GqslOTEpOAdHJibmoOmC5OBesqSS0uQTINaCvQgFgA) **Explanation:** ``` mx # Reverse each words in the (implicit) input-list δ # Titlecase each word mx # Reverse each word back h # Push the length of the list (without popping) û_- # Push string "_-" * # Repeat it the length amount of times ▒ # Convert it to a list ["_","-","_","-",...] ^ # Zip the two lists together, creating pairs # (including trailing ["_"],["-"] items) \ # Swap to get the input-list again £ # Pop and push its length < # Only leave that many items (to only keep the pairs, and # removing the trailing ["_"],["-"] items) ─ # Flatten this list of pairs ~ # Dump all strings separated to the stack ; # Discard the top ("_"/"-") one ! # Lowercase the last/top word # (implicitly join and output the entire stack) ``` [Answer] # [brev](https://idiomdrottning.org/brev), ~~161~~ 150 bytes ``` (fn(strse x (: word(neg-look-ahead eos))(as-list(fn `(,@(butlast x) ,(char-upcase(last x)))))(: ($ word)" "($ word)" ")(conc(m 1)"_"(m 2)"-")'" ""_")) ``` 325 with white space and test cases added: ``` (map (fn (strse x (: word (neg-look-ahead eos)) (as-list (fn `(,@(butlast x) ,(char-upcase (last x))))) (: ($ word) " " ($ word) " ") (conc (m 1) "_" (m 2) "-") '" " "_")) '("hello world" "beans" "one two three four" "backwards hybrid snake kebab camel case" "test three words" "o n e l e t t e r")) ``` [Answer] ## [Python 3](https://docs.python.org/3/), 165 bytes This is my first time having a go at this, so my answer is not gonna be great, but I found this really fun ``` lambda w:"".join([b if not i%2 else b[1:-1] for i,b in enumerate("_/-".join([s[::-1].title()[::-1] for s in w[:-1]]+[w[-1]]).split("/"))])+w[-1][::-1][:(len(w)+1)%2] ``` [Answer] # [QuadR](https://github.com/abrudz/QuadRS) `2g`, ~~37~~ ~~30~~ 29 bytes Takes space-separated words. ``` (\S) _(.*)(\S)_ \u1_ _\1\u2- ``` [Try it online!](https://tio.run/##FcbBCsMgDADQe74ix3awQfsruwqS1LQOnbJYkX59tl0e79MpqNnknjOCnx63@V8Pri8evFtcX@9mUXKuOKrmACxUGtQieI6KZ1QR3GtXYNrSIA0N48X6CtgKJcEkTIwbvSX/bGLr8QU "QuadR – Try It Online") PCRE **R**eplace as follows, `2` times, with non-`g`reedy patterns: | Target | Replacement | | --- | --- | | `(\S)`  non-space followed by space | `\u1_` uppercased non-space followed by underscore | | `(.*?)(\S)_` any run of characters followed by a non-space and an underscore | `_\1\u2-` an underscore, the run, the uppercased non-space, an underscore | [Answer] # [Factor](https://factorcode.org/), ~~89 84~~ 75 bytes ``` [ unclip [ odd? "-""_"? rot 1 cut* >upper append -rot glue ] reduce-index ] ``` [Try it online!](https://tio.run/##VY5Ba8MwDIXv@RWPHAs57LrCehy77DJ2KmUottqYOLIj26Sj9LdnLoyRCfRA0pM@ncnkoOvnx9v76zMoGeeQonc5O7kg8VxYDCdMlAeMrMIeLmBesG@aW4Ma83LDwN4HLEG9xf2v2zNJ2tRBGHkJyIMy4xyKbs1kxoXUJgzfvTqLJDRyZfbUw9BUwYYSbzYyp/x7q5LtPxIEDF@zOqo@QPdmPaKI8S7iiGDtAW3Xtl/tARoynmBK3uGlxMgKqioW3WNy8YVxgrIthjsnlq841VtRneQ6MGGKoX7GZIb1Bw "Factor – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 61 bytes ``` g()<<<${${4+${3%?}${3[-1]:u}$1`g $2 $1 ${@:4}`}:-$3} g _ - $@ ``` [Try it online!](https://tio.run/##FYrBCgIhFEX3fsVdvEAJFzazkoHmPyKagqcThILjFCR@uxmXczbnfre1Oalk81JN00SFynikMhzOtfuizdXulcziQSeQAZXZjnWpVtNQhccNGjQ3JYRDDIz8ichrYoaLe4J7vrmXB9/D9n8ggPHq5D5Gaj8 "Zsh – Try It Online") Recursive solution: ``` g() # define function g (braces optional since body is one line) <<<${${4+${3%?}${3[-1]:u}$1`g $2 $1 ${@:4}`}:-$3} # ${4+ } # if $4 is set, substitute # ${3%?} # $3, remove last character # ${3[-1]:u} # upper last character of $3 # $1 # $1 (either _ or -) # `g $2 $1 ${@:4}` # recurse, swapping _ and - # ${${ }:-$3} # else substitute $3 unchanged # <<< # print g _ - $@ # seed initial arguments ``` [Answer] # [Python 3](https://docs.python.org/3/), 95 bytes Honestly not a great submission, but I can't figure out a way to make it any smaller with this approach. ``` lambda l:''.join('-_'[i%2]+w[:-1]+(w[-1].upper(),w[-1])[i>len(l)-2]for i,w in enumerate(l))[1:] ``` [Try it online!](https://tio.run/##JcntCoMgGIbhUxFhqPQBtX/BdiJOxmu9kUtNrJCO3tX267ke7nBs0@LveXy8sgWnByC2Y6z@LMZzVr2ZNLdWFUl2VaMKnuQ59R4CRi7K3xPSPC16bkXVqnGJxJSJGE/Q7w4jbHgWIZtO5RCN3/jIJdXQzwnisNKS0OnQ0QyXVg8zXphRg77Qg0P7x4pUCZG/ "Python 3 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) + `-p055`, 26 bytes ``` s!(.) !uc$1.($|--?$/:_)!eg ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoicyEoLikgIXVjJDEuKCR8LS0/JC86XykhZWciLCJhcmdzIjoiLXAwNTUiLCJpbnB1dCI6Im8gbiBlIGwgZSB0IHQgZSByIn0=) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~109~~ 91 bytes *-18 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* ``` main(c,v)char**v;{for(;1[++v];c=!c)strlen(*v)[*v-1]-=32,printf(c?"%s_":"%s-",*v);puts(*v);} ``` [Try it online!](https://tio.run/##FcpBCoMwEADAtzRQSGJysL11ER8iUmRJqtAmsonbQ@nbV73MadC/EEU@05I0OjY4T2Qtwy9m0tAOTcMjYHdBUyq9Q9KWzWDZt6Pv7je30pJq1Nira3mqx6FX7iiwbrWcF/4iklOQ@s1SZwpBYt5oBw "C (gcc) – Try It Online") [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~32~~ 30 bytes ``` 55*ii:48*=?\$o30. -{:0$-}"F"+\ ``` [Try it online](https://tio.run/##S8sszvj/39RUKzPTysRCy9Y@RiXf2ECPS7faykBFt1bJTUk75v//ktTiEoWSjKLUVIXy/KKUYgA) **Explanation** ``` 55*i # init stack with 25 and first input i:48*=?\ # if next input is 32, move to row 2 $o30. # else print previous input and jump to next input handling - # subtract 32 from previous input (switch to uppercase) {:0$-} # get the 25 from bottom of stack and negate a copy for next iteration "F"+ # add "F" to get either "-" or "_" depending on sign of the 25 \ # move back to row 1 to print ``` [Answer] # BQN, 30 bytes ``` 1↓·∾≠⊸⥊⟜"-_"∾¨-⟜32⌾⊏⌾⌽¨⌾(¯1⊸↓) ``` [Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgMeKGk8K34oi+4omg4oq44qWK4p+cIi1fIuKIvsKoLeKfnDMy4oy+4oqP4oy+4oy9wqjijL4owq8x4oq44oaTKQoK4oCiU2hvd+KImEbCqCDin6gKImhlbGxvIuKAvyJ3b3JsZCIK4ouIImJlYW5zIgoib25lIuKAvyJ0d28i4oC/InRocmVlIuKAvyJmb3VyIgoiYmFja3dhcmRzIuKAvyJoeWJyaWQi4oC/InNuYWtlIuKAvyJrZWJhYiLigL8iY2FtZWwi4oC/ImNhc2UiCiJ0ZXN0IuKAvyJ0aHJlZSLigL8id29yZHMiCiJvIuKAvyJuIuKAvyJlIuKAvyJsIuKAvyJlIuKAvyJ0IuKAvyJ0IuKAvyJlIuKAvyJyIgrin6kKQA==) ## Explanation * `...¨⌾(¯1⊸↓)` for each non-last word of the input... + `-⟜32⌾⊏⌾⌽` uppercase last letter (literally by reversing and subtracting 32 from the first char) * `≠⊸⥊⟜"-_"∾¨` couple each word with alternations of `-` and `_` * `1↓·∾` join and drop first character [Answer] # [sed](https://www.gnu.org/software/sed/) w/ -E flag, 43 bytes ``` s/(.) /\U\1_/g s/([^_]*_){2}/\0-/g s/_-/-/g ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlWbSSrqtS7IKlpSVpuhY3tYv1NfQ0FfRjQmMM4_XTuYDc6Lj4WK14zWqjWv0YA12wWLyuPpAB0QLVueCmelJicnZ5YlFKsUJGZVJRZopCcV5idqpCdmpSYpJCcmJuag6QLE6FqAcA) [Answer] # [Ly](https://github.com/LyricLy/Ly), ~~25~~ 37 bytes ``` i0"_-"rsp[' =:' *lf-o[Ifprfr0]psp]>lo ``` [Try it online!](https://tio.run/##y6n8/z/TQCleV6mouCBaXcHWSl1BKydNNz/aM62gKK3IILaguCDWLif////8vFSFkvJ8hZKMotRUhbT80iIA "Ly – Try It Online") Revised code... I didn't read the rule saying space has to be translated to `-` and `_` alternating. ``` i - read input as codepoints 0"_-" - push "0" and delimiters r - reverse stack sp - save last and delete [ p] - loop over the 2-N chars ' = - push 0|1 from comparing curr char to " " : - duplicate result ' * - multiply result w/ " " (32) lf - pull prev char, flip top stack entries - - capitalizes if the curr char is " " o - write out char codepoint as a char [ 0]p - if/then, true if " " is curr char I - copy second to bottom stack entry fp - pull " " forward, delete rfr - reverse bottom two entries s - stash "_" or "-" > - switch stacks lo - load last char and print ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 154 bytes ``` filter f([char[]]$r){$s="_","-" ($r|%{[string]$c=$_ if(" "-eq$r[$i+1]){$c.ToUpper()}elseif(" "-eq$_){$s[$x+0] $x=($x+1)%2}else{$c.ToLower()}$i++})-join''} ``` [Try it online!](https://tio.run/##RU5BboMwELzzipXlKEaUqumdH/TYnBBCxqyLi2uTtStSpbydGhKphx3NamdmZ/IzUhjQ2lJ5wnXVxkYk0KJWg6S6aTjlNx4q1rInVrJMcPo93OoQybiPhquKt5nRggEr8cKp5qY4Ncmhnt/9eZqQRL6gDfivabe8ml@Llybj10okdsoPr7vq7nvbSiVfyiqWvPz0xh2Py6qBbUU9zJ5sz7K0dyhd2Jl3CHH2EAdCBO2/6S6Qapwl9QGGn45MD8HJEWHETnag5BfahAF3bcQQH/70oX/kggMEmybdEhJb/wA "PowerShell Core – Try It Online") Ungolfed: ``` filter f ( [char[]]$r # coerce input string to character array ) { $s = "_","-" # initialize space array to replace " " with "_" and "-" ( # () needed for -join '' $r | ForEach-Object{ [string]$c=$_ # [char] lacks .ToUpper(), .ToLower() - coerce back to [string] if(" " -eq $r[$i+1]){ # if next character in array is a space $c.ToUpper() # RETURN uppercase } elseif(" " -eq $_){ # if space is the current character $s[$x+0] # RETURN indexof space array. incl. "+0" in the index depth so we don't need to initialize $x $x=($x+1)%2 # x++ but modulus 2 } else{ $c.ToLower() # RETURN lowercase } $i++ # increment $i for lookahead } )-join'' # [char[]] back to [string]. implicit RETURN from function } ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 20 bytes ``` aR`. `{UC@a."_-"@Uv} ``` Takes input as a single command-line argument with words space-separated. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhZbEoMS9BQSqkOdHRL1lOJ1lRxCy2ohUlAVN7WjlZISk7PLE4tSihUyKpOKMlMUivMSs1MVslOTEpMUkhNzU3OAZHGqUixUDwA) ### Explanation ``` aR`. `{UC@a."_-"@Uv} a Command-line argument R Replace `. ` matches of this regex: any character followed by a space { } With this callback function: a The matched string @ 's first character UC Uppercased . Concatenated to v A number, initially -1 U Increment @ and use as a cyclical index into "_-" That string ``` [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, 39 bytes ``` gsub(/(.) /){$1.upcase+"_-"[($.+=1)%2]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6BUuyCpaUlaboWN9XTi0uTNPQ19DQV9DWrVQz1SguSE4tTtZXidZWiNVT0tG0NNVWNYmshyqG6FmzKz0tVKCnPVyjJKEpNVUjLLy2CyAAA) [Answer] # [Japt](https://github.com/ETHproductions/japt), 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ®ou qÃov ò mq'_ q- ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=rm91IHHDb3YK8iBtcSdfIHEt&input=WwpbIm8iICJuIiAiZSJdClsidCIgInciICJvIl0KWyJ0IiAiaCIgInIiICJlIiAiZSJdClsiZiIgIm8iICJ1IiAiciJdCl0) Input as an array of character arrays. Explanation: ``` ®ou qÃov ® à # For each word in the input: ou # Convert the last letter to uppercase q # Join to a string o # For the last word: v # Convert it to lowercase # Save as U ò mq'_ q- ò # Cut U into pairs of words m # For each pair: q'_ # Join to a single string with "_" in between q- # Join all those strings with "-" between ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-hP`](https://codegolf.meta.stackexchange.com/a/14339/), 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes input as a 2D character array. ``` ÇiUËouÃíUî"_-"¹c ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWhQ&header=uG1x&code=x2lVy291w%2b1V7iJfLSK5Yw&input=ImJhY2t3YXJkcyBoeWJyaWQgc25ha2Uga2ViYWIgY2FtZWwgY2FzZSI) ``` ÇiUËouÃíUî"_-"¹c :Implicit input of 2D character array U Ç :Pop last element, pass it through the following function & push back i : Prepend UË : Map the remaining elements of U o : Modify last u : Uppercase à : End map í : Interleave Uî"_-" : Mould "_-" to length of U ¹ : End prepend c : Flatten :Implicitly join and output last element ``` ]
[Question] [ Take a square matrix containing positive integers as input, and calculate the "rotated sum" of the matrix. **Rotated sum:** Take the sum of the original matrix and the same matrix rotated 90, 180 and 270 degrees. Suppose the matrix is: ``` 2 5 8 3 12 8 6 6 10 ``` then the rotated sum will be: ``` 2 5 8 8 8 10 10 6 6 6 3 2 3 12 8 + 5 12 6 + 8 12 3 + 6 12 5 = 6 6 10 2 3 6 8 5 2 10 8 8 26 22 26 22 48 22 26 22 26 ``` ### Test cases: Input and output separated by dashes, different test cases separated by a newline. Test cases in [more convenient formats can be found here](https://tio.run/##ZZExEsIwDAR7v@IeoCJKQoDxUzIu6KGjy@TtRqfY4JgiM7rzaSXHr8f7mfO6akph23Tfg5UhmCGYkmAdBfNxZsYu2Gh4zHSEH3t@FiyCq0Bn9lmtdqgTv2KYphwoL1aUyHjwGwDnnADFqADKFuD7NP0Rp26XtTfiNLrubor@YBXX05vgXkJW0Zq8ZEjrJYkfh2Oop8sfU2@26PK9WsPn9h2fVsf3VM8vD/Dj15s3@IgOHtGhI/7A/pLN2jl/AA). ``` 1 ------------- 4 1 3 2 4 ------------- 10 10 10 10 14 6 7 14 6 12 13 13 6 2 3 10 5 1 12 12 ------------- 45 37 24 45 24 30 30 37 37 30 30 24 45 24 37 45 14 2 5 10 2 18 9 12 1 9 3 1 5 11 14 13 20 7 19 12 2 1 9 5 6 ------------- 24 29 31 41 24 41 49 31 49 29 31 31 20 31 31 29 49 31 49 41 24 41 31 29 24 ``` ### Shortest code in bytes in each language wins. Explanations are highly encouraged! [Answer] # [Octave](https://www.gnu.org/software/octave/), 29 bytes ``` @(x)(y=x+rot90(x))+rot90(y,2) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0JTo9K2Qrsov8TSAMjRhLIqdYw0/6dpRBspmCpYWBsrGBoBKTMFMwVDg1jN/wA "Octave – Try It Online") ### Explanation This adds the input matrix with a 90-degree rotated version of itself. The result is then added with a 180-degree rotated version of itself. [Answer] # [Python 2](https://docs.python.org/2/), 78 bytes Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for golfing two bytes off my previous recursive approach. ``` f=lambda*l:l[3:]and[map(sum,zip(*d))for d in zip(*l)]or f(zip(*l[0][::-1]),*l) ``` [Try it online!](https://tio.run/##LYtLDsMgDESv4iWOXKkk6Q@pJ7FYUCFUJEJQmizay1OHduWZ5zflvT7n3Nca7slND@@6ZBIPxrrseXJFvbaJPrGoziOGeQEPMUMDCa30oH6Fj5aNOWiLJJ9alphXFVTMZVsVIlZmPRL0BCcCfZRkCVhfCW7SBWtJOxpa3CU5emyWsF4mFwHN3uF/0tSztV8 "Python 2 – Try It Online") or [See a test suite.](https://tio.run/##LY9LDoMwDET3nMLLBKUSCZS2kThJ5AUVRUXiJ6CL9vKpbbKK53k80azf473MLsa@Gdvp2bX56MdQemznLkztqvbPZH7DqvJO637ZoINhBgGjRtK9OkUoMHh/sagNbeLx2o8dGggh2MqAM3A1YAua0ECwdwMP0oQtTYxKGdlEj63ERczRyY2AuBmmE7HWyEQ@qE@b3NUpmSPLBEizLFheJUIsLiXQNoVXiSBilnFhbsKdpZHPYN2G@VC9Yq11/AM "Python 2 – Try It Online") --- ### [Python 2](https://docs.python.org/2/), 80 ~~81 83 85~~ bytes (non-recursive) Takes input [as a singleton list](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/11884#11884). ``` l=input() exec"l+=zip(*l[-1][::-1]),;"*3 print[map(sum,zip(*d))for d in zip(*l)] ``` [Try it online!](https://tio.run/##LYvLDoIwEEX3fMWEVYtjYgFfGL5k0oURjE1KabAk6s/XaXUzc@/Juf4dHrOrY7S9cX4NQhbja7yVdtN/jBeVpa3S1HV8JV7Kqin8Ylyg6erFc50wS4OU93mBAYyD30rqGIlItQg1wh5B7ThpBFInhDN3xopTQk2OSeKn2mwxq3lyZJDtBP@TrB601l8 "Python 2 – Try It Online") ### Code functionality Since this is quite length-ish to analyse it as a whole, let's check it out piece-by-piece: ``` f = lambda *l: # This defines a lambda-function that can accept any number # of arguments (the matrix) using starred expressions. l[3:] and ...X... or ...Y... # If l[3:] is truthy (that is, the length of the list is # higher than 3), return X, otherwise Y. [map(sum,zip(*d))for d in zip(*l)] # The first expression, X. [ ] # Start a list comprehension, that: for d in # ... Iterates using a variable d on: zip(*l) # ... The "input", l, transposed. zip(*d) # ... And for each d, transpose it... map(sum, ) # ... And compute the sum of its rows. # The last two steps sum the columns of d. f(zip(*l[0][::-1]),*l) # The second expression, Y. This is where the magic happens. f( ) # Call the function, f with the following arguments: zip(* ) # ... The transpose of: l[0][::-1] # ...... The first element of l (the first arg.), reversed. , # And: *l # ... l splatted. Basically turns each element of l # into a separate argument to the function. ``` And for the second program: ``` l=input() # Take input and assign it to a variable l. # Note that input is taken as a singleton list. exec"l+=zip(*l[-1][::-1]),;"*3 # Part 1. Create the list of rotations. exec" ;"*3 # Execute (Do) the following 3 times: l+= , # ... Append to l the singleton tuple: zip(* ) # ...... The transpose of: l[-1][::-1] # ......... The last element of l, reversed. print[map(sum,zip(*d))for d in zip(*l)] # Part 2. Generate the matrix of sums. print # Output the result of this expression: [ for d in ] # Create a list comprehension, that iterates # with a variable called "d" over: zip(*l) # ... The transpose of l. map(sum, ) # ... And computes the sum: zip(*d) # ... Of each row in d's transpose. # The last 2 steps generate the column sums. ``` **TL;DR:** Generate the list of matrices needed by rotating the input 3 times by 90-degrees and collecting the results. Then, get the sums of the columns of each matrix in the result's transpose. [Answer] # [Clean](https://clean.cs.ru.nl), 110 bytes ``` import StdEnv,StdLib r=reverse t=transpose z=zipWith(+) $m=[z(z(r b)a)(z(r c)d)\\a<-m&b<-r m&c<-t m&d<-r(t m)] ``` [Try it online!](https://tio.run/##TVHLasMwEDxHX7HQECwqQ2S7aQr2rT0UcsuhB0UH@dFWYNlGVgL1x9ddywoUBDszmtllpaptVDebvr62DRilu1mbobcOzq5@624My0mXxBa2uTV2bIgrnFXdOPSIp2LSw4d239EjJVtTiCmaIgslVdSDitb0clF5bHZlHlswuyqPHZYaWYSAyvnslHXkAXQ3XN0IBQiyEYJLyXxlkEoGImGQBQnhE4OjZCJlwBMPQRwY4OH7ey7z/BmlLFwvVr5E0iAgT30EKXbkwZL8a7HO4ntEi4sfGbwEG6JFSj1cTPw@axmS7Nfh3h0W4D6M1oOUZCMJKfDBB9iG1eff6rNVX@Mcv5/m159OGV2tZP2DPw "Clean – Try It Online") From the matricies: * `X = transpose(reverse M)`: 90-degree rotation * `Y = reverse(map reverse M)`: 180-degree rotation * `Z = reverse(transpose M)`: 270-degree rotation This zips the addition operator over `M` and `X`, as well as `Y` and `Z`, and then over the results. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes ``` Sum[a=Reverse@a,{a=#;4}]& ``` `` is [`\[Transpose]`](http://reference.wolfram.com/language/ref/character/Transpose.html). [Try it online!](https://tio.run/##RY4xDsIwDEWvYrVSJyPqNhQQKuoREIxVhwilokMYSmGJMjNyVI4Q7BLEEOX97@/8WD1djNXTcNahhxrC6W5bXR/Nw4w30@j364lO1@lO@S4Lh3G4Tm2KkMBiDwlC36ZdBxksG3DOkffINyGUAgWCio5CqBDWCKTEYCaeUiknGqxF5iJXDDFS/F9gKYOcSTzaIGxjikmsckYJ0a9KOor82z2n489oXuZo5b0PHw "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Julia 0.6](http://julialang.org/), 29 bytes ``` x*y=rotr90(y,x) !x=x+1x+2x+3x ``` [Try it online!](https://tio.run/##VU1Na4NAEL37K17oRaOUndXYyhLoj@gteFjCklXaWNZNO/56uyM5JPBghvc53r4G264r75djmGLoVL5UXGQ7PnJJXGoua14/Zj/9YRfc7O2Py0/UV8ipoqLAy6cfZiSIY5luuLgIC2LCt41hYAxXjLIC9doiDzZ6FxC9vSbbrzvHKRRZdl84EWoDjaZ/oBq0eAM1Jl3SoDpBfo30KYMDaOP1c0iLoKAN6B3d5kBnJCMCbYWpSyspF12GkyWpbb/@Aw "Julia 0.6 – Try It Online") I couldn't get below [LukeS's solution](https://codegolf.stackexchange.com/a/153695/4397) But in trying I did come up with this, which I think is kinda cute. First we redefine multiplication to be the rotate operation, where there first time is the number of times to rotate. So since julia multipes by juxtaposition then: `1x` becomes `rotr90(x,1)` and `3x` becomes `rotr90(x,3)` etc. Then we write out the sum. [Answer] # [Julia 0.6](http://julialang.org/), ~~28~~ 24 bytes ``` ~A=sum(rotr90.([A],0:3)) ``` [Try it online!](https://tio.run/##VY/BTsQgGITvfYrJ7gUSVKC1azV7aOLVeHA9NRwaZV1MlzaURk/76pVCqpFwYGa@4YfPqTNtOT@13pk3PWKfIazG6fHUDpo0QjEimKCUZdsUCeQP8SRRqD@3QIkdRJGyEkJC5GGvWiIontQtRMzlv75cfA6ZGHGHKkKokhHqCyB@Z4TrJV9mLtz6pIAHqlRqvtT7cToT13tX8WvS1Irx@5zS@dg71DAW66djdTz1X@Tl8Pj8emDYeP3tb4auNXbDcKkptjaQDuep8@aqM1ZjcMZ6Yz9iO4rOEppp@z7/AA "Julia 0.6 – Try It Online") ``` ~A=sum(rotr90.([A],0:3)) # ~ # redefine unary operator ~ A # function argument [A] # put input matrix A into a list with one element 0:3 # integer range from 0 to 3 rotr90.( , ) # apply function rotr90 elementwise, expand singleton dimensions rotr90.([A],0:3) # yields list of rotated matrices: # [rotr90(A,0), rotr90(A,1), rotr90(A,2), rotr90(A,3)] sum( ) # sum ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ZU+µUṚ+ ``` [Try it online!](https://tio.run/##y0rNyan8/z8qVPvQ1tCHO2dp////PzraSMdUxyJWJ9pYx9AIzDDTMdMxNIiNBQA "Jelly – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), 33 bytes ``` @(a)a+(r=@rot90)(a)+r(a,2)+r(a,3) ``` [Try it online!](https://tio.run/##RY5BC8MgDIXv@xU5Kg1i1HUrodD/MXqQMa8FKfv7LprCDpL38d5LPN5n/n5aWZ1zbTPZ5snUdavHuXgrOFWTMeiIthVD9lbMixAiQ0BIu3JCmBEeCJS4KxKPYn8DhTp4hruMyw7/rmA3vCgGeiIsV0YUj6oGSA/0zcHrvZEcf6FRk9i82/YD "Octave – Try It Online") ## Explanation: `(r=@rot90)` in an inline way of creating a function handle `r` used to rotate the matrix 90 degrees. If a second argument, `k` is given to `r` then it will rotate the matrix `k*90` degrees. So this is equivalent to the pseudo code: ``` a + rot90(a) + rot180(a) + rot270(a) ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 8 bytes ``` (⌽+⍉)⊖+⌽ ``` [Try it online!](https://tio.run/##RVDLasMwELznK/YoEQLa1VqyPsektAQMKeTUHyik1KE9tPde8w/9Gf2IOyunMRjvY8Yzsx6ex93DyzAen3b7cTidDvu5Xr4Ox/r6EeZHvF19/93W6ezr2/cW/Tw7rD@dUEe9d5FYrCZKxMH7ev5paCIRkuQdivYY/LrbQGG6cuNOV90sgkwRHNK7BgdTvJV/ksInE6s5wpnhH60Xio3dEbe93GW0o5hJlLSDvlIM7cnInm@DQA40A7PRVjO7EgGQnnsqTZlKu9oAbkGQQYKFMtxOAAVoWn8GdApFJuXFCt0yFwBQYxug0RoolBVXbqF1oRT7/g8 "APL (Dyalog Classic) – Try It Online") [Answer] # [MATL](https://esolangs.org/wiki/MATL), 9 bytes ``` i3:"G@X!+ ``` Try it at [MATL Online](https://matl.io/?code=i3%3A%22G%40X%21%2B&inputs=%5B2+5+8%3B3+12+8%3B6+6+10%5D&version=20.6.0) **Explanation** ``` i # Explicitly grab the input matrix 3:" # Loop through the values [1, 2, 3], and for each value, N: G # Grab the input again @X! # Rotate the value by 90 degrees N times + # Add it to the previous value on the stack # Implicitly end the for loop and display the resulting matrix ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 13 bytes ``` m+MCdC.u_CN3Q ``` [Try it online!](http://pyth.herokuapp.com/?code=m%2BMCdC.u_CN3Q&test_suite=1&test_suite_input=%5B%5B1%5D%5D%0A%5B%5B1%2C+3%5D%2C+%5B2%2C+4%5D%5D%0A%5B%5B2%2C+5%2C+8%5D%2C+%5B3%2C+12%2C+8%5D%2C+%5B6%2C+6%2C+10%5D%5D%0A%5B%5B14%2C+6%2C+7%2C+14%5D%2C+%5B6%2C+12%2C+13%2C+13%5D%2C+%5B6%2C+2%2C+3%2C+10%5D%2C+%5B5%2C+1%2C+12%2C+12%5D%5D%0A%5B%5B14%2C+2%2C+5%2C+10%2C+2%5D%2C+%5B18%2C+9%2C+12%2C+1%2C+9%5D%2C+%5B3%2C+1%2C+5%2C+11%2C+14%5D%2C+%5B13%2C+20%2C+7%2C+19%2C+12%5D%2C+%5B2%2C+1%2C+9%2C+5%2C+6%5D%5D&debug=0) [Answer] # [J](http://jsoftware.com/), ~~16~~ 15 bytes ``` [:+/|.@|:^:(<4) ``` [Try it online!](https://tio.run/##NYxBCsIwEEX3nuItlYaamaS1HRS8h9CNWMRNL9C7x0lQZvHhv/fnU8p663lYd977@26LHa/5VF7P98aKkIKh5MOvUAamQELU0xj9JP6p5CZIRAMyMVdNmNugAnHFSUIjF6Ty9t8dx2P5Ag) [Answer] # [R](https://www.r-project.org/), ~~69~~ 64 bytes ``` function(x,a=function(y)apply(y,1,rev))x+a(x)+a(a(x))+a(a(a(x))) ``` [Try it online!](https://tio.run/##PYpRCoAgEESvs0sbZFL0kYcRSRDKRCzW05sWxMC8NzCx2LUv9vImudMDk1b/yKhD2DNkEhS3G5E7DYy1Gj6@hiVE5xNYYHXoFB2DgZEmWkiSGCvmGjEgyXZ@AA "R – Try It Online") --- Attempt number three at codegolf. From 69 to 64 bytes thanks to Giuseppe! [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` ,t@QX!+ ``` Try it at [MATL Online!](https://matl.io/?code=%2Ct%40QX%21%2B&inputs=%5B2+5+8%3B3+12+8%3B6+6+10%5D&version=20.6.0) ### Explanation Port of my Octave answer. ``` , % Do twice t % Duplicate. Takes input (implicit) the first time @Q % Push 1 in the first iteration, and 2 in the second X! % Rotate by that many 90-degree steps + % Add % End (implicit). Display (implicit) ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 31 bytes ``` a->sum(i=1,4,a=Mat(Vecrev(a))~) ``` [Try it online!](https://tio.run/##NY7BDoIwEER/ZcKpTZaEhYqaBv7AqxfCoTFgSNQ0iCZe/PW6LXhod97uzLbezVN@9WFEg@Dy9vm6q6lhMuSak1vUebjMw1s5rb86OO9vH@WQt/Dz9FhEZhEyjNFB6Dru5WZCZVESTCJDqAl7AhsbFcuEq3gSCkUoLHZStnH5TwrEdiHKgg@E4@YQZVNwNfC6Pu4ti/W15Ez/4BQTW933OvwA "Pari/GP – Try It Online") [Answer] ## JavaScript (ES6), 77 bytes ``` a=>a.map((b,i)=>b.map((c,j)=>c+a[j][c=l+~i]+a[c][c=l+~j]+a[c][i]),l=a.length) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ṚZ$3СS ``` [Try it online!](https://tio.run/##y0rNyan8///hzllRKsaHJxxaGPz////oaEMTHQUjHQVTHQVDAyArVkch2tBCR8ESyAcKGwJZICFjMBOkCEgZmoBVAcWMgFrMgQJg1SBBqBawUrPYWAA "Jelly – Try It Online") Saved 1 byte thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) (also thanks to a suggestion for fixing a bug). ### How? ``` ṚZ$3СS || Full program (monadic). 3С || Do this 3 times and collect results in a list $ || –> Apply the last two links as a monad Ṛ || –––> Reverse, Z || –––> Transpose. S || Summation. ``` [Answer] # [Python 2](https://docs.python.org/2/), 76 bytes ``` f=lambda x,k=-2:k*x or[map(sum,zip(*r))for r in zip(x,f(zip(*x)[::-1],k+1))] ``` [Try it online!](https://tio.run/##ZVDLasMwEDxbX7FHKVXAK7lpasiXCB1cgolx/EBNQcnPu7uy6lAiEIxmZ2YHzffbZRrNsrSnazN8nRuIuj/tTd3vIkzBDc0sv38G/ehmuQtKtVOAAN0ITETdyjSIytX1Hr3u31Apv7AqskoKUThnNMA73aPXAv6OsxrQvLAHYuhi6YlmM25AgyVYAOdVG1utBvggU7XOUwCJkFfYJwe8zqbwleNSmLXmX2KujCXjVY1Hwp@5NDLOKTa/WY/PFrzdlLlZ8mX95s/fcvBeCFXT8u13WxmJKIo5dOMNAo0SWn4B "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` 3FÂø}3F‚øε`+ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f2O1w0@EdtcZujxpmHd5xbmuC9v//0dGGJjoKRjoKpjoKhgZAVqyOQrShhY6CJZAPFDYEskBCxmAmSBGQMjQBqwKKGQG1mAMFwKpBglAtYKVmsbEA "05AB1E – Try It Online") [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/attache), 20 bytes ``` Sum@MatrixRotate&0:3 ``` [Try it online!](https://tio.run/##VY5LC8IwEITv@RWLiKc9NG19gsWDV0H0GBYJpcFCfVAjKOJvr7uxhTYkMDP7JRPrvc3PRbMtXHktzNhhc3xeNjvr6/J1uHnri0m0ShpSHeFzBKOAlzGaCDuJkBBPYoS0l6YIM4Q5gk5lylozoRM5bcBebCR2yqJF4uErHMkwYiWgXiAsW5KVREmQAumuTnri6N8f6PaHOlxmdEakeCv1CVXb8nGv7NucKNh9XV69Ga2zEQ3GjoE@UTlSX1hn4PPmBw "Attache – Try It Online") ## Explanation ``` Sum@MatrixRotate&0:3 ``` `MatrixRotate&0:3` expands to, with input `x`, `MatrixRotate[x, 0:3]`, which in turn exapnds to `[MatrixRotate[x, 0], MatrixRotate[x, 1], MatrixRotate[x, 2], MatrixRotate[x, 3]]`. That is to say, it vectorizes over the RHS. Then, `Sum` takes the sum of all of these matrices by one level. This gives the desired result. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 17 bytes ``` {⍵+⌽∘⍉⍵+⌽∘⊖⍵+⍉⌽⍵} ``` [Try it online!](https://tio.run/##jZDBCsIwDIbvPkVua5HB2nXTPU5XmQgDhZ1EvMocVrwoPog7@jJ5kZqWHXYqloY0/xfyh@pDm26Out1vU9PqrtsZ505oxyXevti/0V5nxfAKBWlU2/HsGrw8/u5e4P1J/ZpCgkT7EZCDBDXpSTo7ySQ2oONYxHBNoUB5KwUlrCAkIUHk/pbkTo8MChBBlXGvOoYNRQEFeWE/MDKSfmwGkjOxhirMh4ozMvSADBUR@oDM7@U5Z6GFaMnji5iF@wE "APL (Dyalog Classic) – Try It Online") # APL NARS 34bytes ~~21~~17 chars ``` {⍵+⌽∘⍉⍵+⌽∘⊖⍵+⍉⌽⍵} ``` -2 chars thanks to ngn -2 chars because operator composite ∘ seems to have precedence on + it seems ⌽⍉a rotate a from 90°,⌽⊖a rotate a from 180°,⌽⍉⌽⊖a rotate a from 270° as ⍉⌽ If exist the operator p as: ``` ∇r←(g p)n;a;i;k a←⌽,n⋄r←⍬⋄i←0⋄k←⍴a⋄→C A: →B×⍳r≡⍬⋄r←g¨r B: r←r,⊂i⊃a C: →A×⍳k≥i+←1 r←⌽r ∇ ``` The operator p above would be such that if g is a 1 argument function (monadic?) it should be: ``` "g f a a a a" is "a ga gga ggga" ``` the solution would be pheraps 15 chars ``` g←{⊃+/⌽∘⍉ p 4⍴⊂⍵} a←2 2⍴1 3 2 4 g a 10 10 10 10 g 1 4 ``` But could be better one operator "composed n time" d such that "3 d f w" is f(f(f(w))). Now I wrote something but it is too much fragile without the need type checking. But i like more the operator q that repeat compose of f with argument m (it is not complete because the error cases of the types are not written) ``` ∇r←(n q f)m;i;k;l r←⍬⋄k←⍴,n⋄→A×⍳k≤1⋄i←0⋄→D C: r←r,⊂(i⊃n)q f m D: →C×⍳k≥i+←1 →0 A: l←n⋄r←m⋄→0×⍳n≤0 B: l-←1⋄r←f r⋄→B×⍳l≥1 ∇ ``` the solution would be 17 chars but i prefer it ``` g←{⊃+/(0..3)q(⌽⍉)⍵} ⎕fmt g a ┌2─────┐ 2 10 10│ │ 10 10│ └~─────┘ ⎕fmt g 1 4 ~ ``` [Answer] # [K4](http://kx.com/download/) / [K (oK)](https://github.com/JohnEarnest/ok), ~~23~~ 8 bytes **Solution:** ``` +/(|+:)\ ``` [Try it online!](https://tio.run/##y9bNz/7/X1tfo0bbSjPGWMFY2UjBVMFCwVjB0AhImQGhocH//wA "K (oK) – Try It Online") **Example:** ``` +/(|+:)\5 5#14 2 5 10 2 18 9 12 1 9 3 1 5 11 14 13 20 7 19 12 2 1 9 5 6 24 29 31 41 24 41 49 31 49 29 31 31 20 31 31 29 49 31 49 41 24 41 31 29 24 ``` **Explanation:** Thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn) for the simplified transformation technique. ``` +/(|+:)\ / the solution \ / converge ( ) / function to converge +: / flip | / reverse +/ / sum over the result ``` **Extra:** In Q this could be written as ``` sum (reverse flip @) scan ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~74 72~~ 66 bytes ``` ->a{r=0...a.size;r.map{|i|r.map{|j|(0..3).sum{i,j=j,~i;a[i][j]}}}} ``` [Try it online!](https://tio.run/##LcpNCoMwEIbhq8xSYTo4xv4h6UVCFilUSECQiAubtFdPJ8VZvXzzxO25l0mX08OlqDsicrT692uMNLslZZ@PCLmRr2pp3ebkMeiAXz86460J9iNXFpioMYYHhB7hjNxJWDR8Q7gjy8YSMoD6pwhGHqpQ2Au@IldXxYErgou1bfkB "Ruby – Try It Online") This works on an element-by-element basis, finding the associated elements mathematically, instead of rotating the array. The key part is `i,j=j,~i`, which turns (i, j) clockwise 90 degrees. -2 bytes thanks to Mr. Xcoder -6 bytes because of `sum` [Answer] # [Python 3](https://docs.python.org/3/), ~~105~~ 102 bytes 3 bytes thanks to Mr. Xcoder. ``` def f(a):l=len(a)-1;r=range(l+1);return[[a[i][j]+a[l-j][i]+a[l-i][l-j]+a[j][l-i]for j in r]for i in r] ``` [Try it online!](https://tio.run/##bU9BCoMwELz3FXs0mIJrrLUVXxJyEKptgkQJ9tDXp5sYoUghh5nZmZ3N8llfsxXeP4YRxqxn96mbBkvgjK3rXG@fQzblyFo3rG9npeylVtKovJfT2SgiEZEWKGGjIh1nBwa0BReh3qBfnLZrNmZSolKMnX44B6E4yJJDdRiRdOHQhKnggGXCNQd6WBwXVVG/0qhKthDBEBVJIC5ilCitxmQp/6zayrEgFNzYcLglO6H9ps2Ee2coK4vtiOhOP8MYJmsdmvwX "Python 3 – Try It Online") [Answer] # [Ruby](http://www.ruby-lang.org) 89 79 bytes -10 bytes thanks to Unihedron ``` ->m{n=m;3.times{n=n.zip(m=m.transpose.reverse).map{|i,j|i.zip(j).map &:sum}};n} ``` [Try it online!](https://tio.run/##pVJNT4NAEL33V0w4WE1ww7K0lTboDzCxF2@UmIpbhYSPsGDUwm9HOrO026S3XoaZefPevJ1QNe@//S7Y9PeP2T4PspVgdZJJNeQ5@0vK2yzIWF1tc1UWSrJKfstKyTuWbct9m9hpm@BUih24Waom67pV3vXhBCDEwKMhRjbmHuZDQYgNIrIPmWuDZ4xxxwYA7hB4rM643qEJc4wLHPBonHrcxSgomgggAsJcATPscYPpmrYRFrjGxcXeTBvHSjhGXBBC0ybiaoOkppkLrXbhbeRzRj6pow/ygJV/ckvOwdevEUaP@Ny8EF3FdYzbaS3NP9M8qcDcuAn5dxEWOOrxs1dSz8R9Yuj78BNCVsaOvqx/me9x8/KeqeLr/XjLScTkNv7at3XcDo2yqRVYST58l9ZQ13HojBNpS3Cqf@vhp66LN8WqtFE1iI6lRZLD1IZpd1Ta5J8FKe1C1LpOTP6UMq7lx@iNXydnjfloLghQFJ7AWj9bsATrZf0KQ2qQDrSu/wc) [Answer] # [Haskell](https://www.haskell.org/), ~~84 83~~ 67 bytes ``` z=zipWith e=[]:e f l=foldr(\_->z(z(+))l.foldr(z(:).reverse)e)l"123" ``` [Try it online!](https://tio.run/##bVBNT4NAED27v2LkBBEb9qOtNMGD1xp70KQH3NgmXYS4/QhQbfnzCLvYXah7mMB7b968mXRdfAkp67qKquywzMoUiSjmM4ESkFGyl5vcff@4f6zcyr3zPDnSUOXOvFEuvkVeCE940sGEOvVpVaT7o9w8idUZIjgcy9cyf97BtvhENz@pyEX72TBZAqcoOkOZih04i/nIASELAc7L4g0W81sHoe062zXKzR4QNC@BOMacg5nQAIxzZFgfKPfVb/Ni4gMb6nEAPgAOLNkFsp1Yi8FE1ani2aUlVjAmqlJdByQoEuhgWDxWMLb6ydVGSkPVUKJisLEx0AgNrDo1rO6yWWLF1s6dw7Rzvl5aRx/r6Box12rO9aCw0Oyg94HQVlGL0FZ4cMXWSqlIYF25s7VVvRnGECbDy@nNiNJQpWd4cIP2CpqxVaHu6@XHhtcB/5BetPB/L9ZXMZOlcwy7XBzVvw "Haskell – Try It Online") Thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni) and [totallyhuman](https://codegolf.stackexchange.com/users/68615/totallyhuman) for saving a lot of bytes! [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` F‡+↑4¡(↔T ``` [Try it online!](https://tio.run/##yygtzv7/3@1Rw0LtR20TTQ4t1HjUNiXk////0dGGJjpmOuY6hiaxOtFmOoZGOobGQATmGOkAmQZApqmOIVjGKDYWAA "Husk – Try It Online") ### Explanation ``` F‡+↑4¡(↔T) -- implicit input M, for example: [[1,0,1],[2,3,4],[0,0,2]] ¡( ) -- repeat infinitely times starting with M T -- | transpose: [[1,2,0],[0,3,0],[1,4,2]] ↔ -- | reverse: [[1,4,2],[0,3,0],[1,2,0]] -- : [[[1,0,1],[2,3,4],[0,0,2]],[[1,4,2],[0,3,0],[1,2,0]],[[2,0,0],[4,3,2],[1,0,1]],[[0,2,1],[0,3,0],[2,4,1]],[[1,0,1],[2,3,4],[0,0,2]],… ↑4 -- take 4: [[[1,0,1],[2,3,4],[0,0,2]],[[1,4,2],[0,3,0],[1,2,0]],[[2,0,0],[4,3,2],[1,0,1]],[[0,2,1],[0,3,0],[2,4,1]]] F -- fold (reduce) the elements (example with [[1,0,1],[2,3,4],[0,0,2]] [[1,4,2],[0,3,0],[1,2,0]]) ‡+ -- | deep-zip addition (elementwise addition): [[2,4,3],[2,6,4],[1,2,2]] -- : [[4,6,4],[6,12,6],[4,6,4]] ``` [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 132 bytes Let's take the recently added library function `transpose` for a spin! ``` (load library (d T transpose (d R(q((m #)(i #(c m(R(reverse(T m))(dec #)))( (q((m)(foldl(q(p(map(q((r)(map sum(T r))))(T p))))(R m 4 ``` The last line is an unnamed lambda function that performs rotation summation. To actually use it, you'll want to use `d` to bind it to a name. [Try it online!](https://tio.run/##XY7BbsIwEETvfMVIXMa32Akp/EaUH0iJI0WyibGhEl@f7hr1QE@e3Xk7nsd6e4W1pH1n2KYZYf3OU34dOGPEI0@3krbidRx4JyOOhiuOvCJyYPY/PhfPEdEYzv4qtgjFl4obLluYg@jEOCXdZaMK5RnlLBvlR6T6Dojodi7gHaTDCWcDtrCuih49bKPk4Y@xnxNawRy6z20nd1@wXY2QLCuJbR0cWk0ET7DVcf8vtYRt4ISxZ1wqhMu7lVr2nSuRrtFPlKgdhBK/17z9Fw "tinylisp – Try It Online") ### Ungolfed, with comments ``` (load library) (comment Get functions from the standard library) (comment Rotating a matrix by 90 degrees is just transpose + reverse) (def rotate (lambda (matrix) (reverse (transpose matrix)))) (comment This function recursively generates a list of (count) successive rotations of (matrix)) (def rotations (lambda (matrix count) (if count (cons matrix (rotations (rotate matrix) (dec count))) nil))) (comment To add two matrices, we zip them together and add the pairs of rows) (def matrix-add (lambda two-matrices (map row-sum (transpose two-matrices)))) (comment To add two rows of a matrix, we zip them together and add the pairs of numbers) (def row-sum (lambda (two-rows) (map sum (transpose two-rows)))) (comment Our final function: generate a list containing four rotations of the argument and fold them using matrix-add) (def rotated-sum (lambda (matrix) (foldl matrix-add (rotations matrix 4)))) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 8 bytesSBCS ``` +∘⍉∘⊖⍣3⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X/tRx4xHvZ0gsmvao97Fxo96V/xPe9Q24VFv36O@qZ7@j7qaD603ftQ2EcgLDnIGkiEensH/0xQMFQwf9W4x5EpTMFEwAbFMFMwUzBXAlKGRgqExCJkpGCkAGQYKpiD1QFEjAA "APL (Dyalog Unicode) – Try It Online") ### How it works ``` +∘⍉∘⊖⍣3⍨ ⍝ Input: matrix m ⍉∘⊖ ⍝ Rotate 90 degrees clockwise +∘ ⍝ Add the original matrix m ⍣3⍨ ⍝ Repeat 3 times, starting with m ``` --- # [J](http://jsoftware.com/), 12 bytes ``` (+|:@|.)^:3~ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NbRrrBxq9DTjrIzr/mtypSZn5CukKRgqGKoYgjnqurq66jBhEwUTFUMTBTMFcwUwZWikYGgMQmYKRgpAhoGCKUgrUNToPwA "J – Try It Online") Straightforward port of the APL answer above. [Answer] # Java 8, ~~135~~ ~~133~~ 131 bytes ``` a->{int l=a.length,r[][]=new int[l][l],i,j,k=0;for(;k<l*l;)r[i=k/l][j=k++%l]=a[i][j]+a[j][l+~i]+a[l+~i][l-++j]+a[l-j][i];return r;} ``` -4 bytes thanks to *@ceilingcat*. **Explanation:** [Try it online.](https://tio.run/##lVNdT4MwFH33VzRLTJhccLCJTsTEF9/0ZXtDHirrZqErpHQzy4J/fV7K5kfEZEsKtPdwTs5pbzO6pk5RMpnN8l0qaFWRJ8rl9owQLjVTc5oy8twsTSFO4oSk1mFG@yEiNT44Kk01T8kzkSQiO@rcb/E3IiLqCiYX@g1Uw4kkezdKIsEBHDLIo0E4L5QV5nfiQoR9FfMov0Q8i3LbPhdJRGOOq8Sm@IqF/cGbqfnGwrFtgwgHMZ6EiumVkkSF9S5sjZWrV4HG9v7WBZ@RJWa0JlpxuYgTqhZVv42oWaWtg0N021YJ@SptvdqUapP8KAIMa/hT9WF0slAAAVyDN@qQC8DzwRvi6AR9QGjQAV2BZ5j@yWZGKIrsAfgdst4NjI0ujDtQ9NJQve4omMIfNDkbhc6dQ1XkBz8t/25Bc8Qmw3ejthEmm0qzpVustFvi4Wshrd6jKpa3L7pnZ3gX3JXmwn1Qim4qd8ZYOS3aNrFof785XRrT4ggF6aaNyv8y@yj17hM) ``` a->{ // Method with integer-matrix as both parameter and return-type int l=a.length, // Dimensions of the input-matrix r[][]=new int[l][l], // Result-matrix of same size i,j,k=0; // Index-integers for(;k<l*l;) // Loop over the cells r[i=k/l][j=k++%l]= // Set the cell of the result-matrix to: a[i][j]+a[j][l+~i]+a[l+~i][l-++j]+a[l-j][i]; // The four linked cells of the input-matrix return r;} // Return the result-matrix ``` ]
[Question] [ [Inspired/mostly copied but I don't think it's a dupe](https://codegolf.stackexchange.com/questions/171884/overlapping-polyglots). [Also Inspired](https://codegolf.stackexchange.com/questions/102370/add-a-language-to-a-polyglot). In this challenge, you will create polyglots that include all languages from previous answers, *and* another language which you won't share and others must guess. The first language prints 1, the second prints 2, etcetera. For example, if the first answer was this: ``` print(1) ``` You could crack it as Python 3 (or numerous other languages), then you could write another answer that prints 2 in, say, Befunge-93: ``` 2<3 and print(1)#@.2 ``` [Try it online!](https://tio.run/##S0pNK81LT/3/38jGWCExL0WhoCgzr0TDUFPZQc/o/38A "Befunge-93 – Try It Online") Then, the next person to answer would first have to figure out that this was written in Befunge-93 before posting an answer that printed 1 in Python 3, 2 in Befunge-93 and 3 in a language of their choice. Feel free to share a crack if you don't want to post an answer. To keep this challenge fluid, you must reveal your language if it has been uncracked for a week, at which point anyone can post another answer. Please, be nice and try to post answers in languages which can be easily polyglotted. # Rules * The criteria for a valid programming language are the same as those of [The Programming Language Quiz, Mark II - Cops](https://codegolf.stackexchange.com/questions/155018/the-programming-language-quiz-mark-ii-): > > > + It has [an English Wikipedia article](https://en.wikipedia.org/wiki/Lists_of_programming_languages), [an esolangs article](http://esolangs.org/wiki/Language_list) or [a Rosetta Code article](http://rosettacode.org/wiki/Category:Programming_Languages) at the time this challenge was posted, or is on [Try It Online!](https://tio.run/#) (or [ATO](https://ato.pxeger.com)). Having an interpreter linked in any of these pages makes that interpreter completely legal. > + It must satisfy our rules on [what constitutes a programming language](http://meta.codegolf.stackexchange.com/a/2073/8478). > + It must have a free interpreter (as in beer). Free here means that anyone can use the program without having to pay to do so. > * Each answer must run in less than a minute on a reasonable PC. * Different versions of a language / languages with different flags / whatever are valid as long as you can get them to behave differently. However, flags must be revealed to avoid obscure combinations. * Cracking a submission consists of finding *any* programming language that prints the correct result, not just the intended one. If a submission is run in any language that was not declared or found to work, there are no requirements to do anything, and future answers must be valid in that language. ## I/O clarifications The program must output a decimal integer, optionally as a float with a `.0` afterwards. Any reasonable amount of leading/trailing whitespace is acceptable, as is stuff unavoidably printed by the interpreter, or formatting for the integer. Anything else is not. Ending with an error is allowed as long as that error is printed to stderr, and not standard output - it can't be printed with the number. ## Scoring The person with the most answers wins. [A chatroom's been created for this challenge](https://chat.stackexchange.com/rooms/136684/add-a-hidden-language-to-a-polyglot). [Answer] # 9. Deadfish~, 116 bytes, cracked by pxeger The previous answer was in [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), but I don't have enough reputation to comment yet. ``` 4+0# @ iiiiiiiiio print(8-(2*5-3)+(1/2)*10)#+++++P #++++++++++++++++++++++++++++++++++++++++++++++++++. 0+0# ^ 5_3 ``` Try it online in: * [Ruby](https://tio.run/##KypNqvz/30TbQFlBwUEhEwbyuQqKMvNKNCx0NYy0THWNNbU1DPWNNLUMDTSVtUEgQAFCkwT0uAzAFsVxmcYb//8PAA "Ruby – Try It Online") * [Jelly](https://tio.run/##y0rNyan8/99E20BZQcFBIRMG8rkKijLzSjQsdDWMtEx1jTW1NQz1jTS1DA00lbVBIEABQpME9LgMwBbFcZnGG///DwA "Jelly – Try It Online") * [Vyxal](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI0KzAjICBAIGlpaWlpaWlpaW9cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCkjKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCMgIF5cbjVfMyIsIiIsIiJd) * [Radvylf Should Not Be Allowed To Write Programming Languages](https://dso.surge.sh/#@WyJyYWlzaW4tYmF0d2FmZmxlIixudWxsLCI0KzAjICBAIGlpaWlpaWlpaW9cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCkjKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCMgIF5cbjVfMyIsIiIsIiIsIiJd) * [Headass](https://dso.surge.sh/#@WyJoZWFkYXNzIixudWxsLCI0KzAjICBAIGlpaWlpaWlpaW9cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCkjKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCMgIF5cbjVfMyIsIiIsIiIsIiJd) * [Python 3](https://tio.run/##K6gsycjPM/7/30TbQFlBwUEhEwbyuQqKMvNKNCx0NYy0THWNNbU1DPWNNLUMDTSVtUEgQAFCkwT0uAzAFsVxmcYDbQUA "Python 3 – Try It Online") * [brainfuck](https://tio.run/##SypKzMxLK03O/v/fRNtAWUHBQSETBvK5Cooy80o0LHQ1jLRMdY01tTUM9Y00tQwNNJW1QSBAAUKTBPS4DMAWxXGZxhv//w8A "brainfuck – Try It Online") * [Runic Enchantments](https://tio.run/##KyrNy0z@/99E20BZQcFBIRMG8rkKijLzSjQsdDWMtEx1jTW1NQz1jTS1DA00lbVBIEABQpME9LgMwBbFcZnGG///DwA) [Answer] # 11. Neutrino, 144 bytes ``` 4+0# @ iiiiiiiiio print(8-(2*5-3)+(1/2)*10+8-4*(2147483647*2%3))#+++++P #++++++++++++++++++++++++++++++++++++++++++++++++++. 0+0# ^ -1*-10+4_3 ``` Try it online in [Ruby](https://tio.run/##KypNqvz/30TbQFlBwUEhEwbyuQqKMvNKNCx0NYy0THWNNbU1DPWNNLUMDbQtdE20NIwMTcxNLIzNTMy1jFSNNTWVtUEgQAFCkwT0uAzAtsdx6Rpq6QItMIk3/v8fAA), [Jelly](https://tio.run/##y0rNyan8/99E20BZQcFBIRMG8rkKijLzSjQsdDWMtEx1jTW1NQz1jTS1DA20LXRNtDSMDE3MTSyMzUzMtYxUjTU1lbVBIEABQpME9LgMwLbHcekaaukCLTCJN/7/HwA), [Vyxal](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI0KzAjICBAIGlpaWlpaWlpaW9cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCs4LTQqKDIxNDc0ODM2NDcqMiUzKSkjKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCMgIF5cbi0xKi0xMCs0XzMiLCIiLCIiXQ==), [rSNBATWPL](https://dso.surge.sh/#@WyJyYWlzaW4tYmF0d2FmZmxlIixudWxsLCI0KzAjICBAIGlpaWlpaWlpaW9cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCs4LTQqKDIxNDc0ODM2NDcqMiUzKSkjKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCMgIF5cbi0xKi0xMCs0XzMiLCIiLCIiLCIiXQ==), [Headass](https://dso.surge.sh/#@WyJoZWFkYXNzIixudWxsLCI0KzAjICBAIGlpaWlpaWlpaW9cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCs4LTQqKDIxNDc0ODM2NDcqMiUzKSkjKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCMgIF5cbi0xKi0xMCs0XzMiLCIiLCIiLCIiXQ==), [Python 3](https://tio.run/##K6gsycjPM/7/30TbQFlBwUEhEwbyuQqKMvNKNCx0NYy0THWNNbU1DPWNNLUMDbQtdE20NIwMTcxNLIzNTMy1jFSNNTWVtUEgQAFCkwT0uAzAtsdx6Rpq6QItMIkHuggA), [brainfuck](https://tio.run/##SypKzMxLK03O/v/fRNtAWUHBQSETBvK5Cooy80o0LHQ1jLRMdY01tTUM9Y00tQwNtC10TbQ0jAxNzE0sjM1MzLWMVI01NZW1QSBAAUKTBPS4DMC2x3HpGmrpAi0wiTf@/x8A), [Runic Enchantments](https://tio.run/##KyrNy0z@/99E20BZQcFBIRMG8rkKijLzSjQsdDWMtEx1jTW1NQz1jTS1DA20LXRNtDSMDE3MTSyMzUzMtYxUjTU1lbVBIEABQpME9LgMwLbHcekaaukCLTCJN/7/HwA), [Deadfish~](https://tio.run/##S0lNTEnLLM7Q/f/fRNtAWUHBQSETBvK5Cooy80o0LHQ1jLRMdY01tTUM9Y00tQwNtC10TbQ0jAxNzE0sjM1MzLWMVI01NZW1QSBAAUKTBPS4DMC2x3HpGmrpAi0wiTf@/x8A). [FISHQ9+](https://dso.surge.sh/#@WyJmaXNocTkrIixudWxsLCI0KzAjICBAIGlpaWlpaWlpaW9cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCs4LTQqKDIxNDc0ODM2NDcqMiUzKSkjKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCMgIF5cbi0xKi0xMCs0XzMiLCIiLCIiLCIiXQ==). I created this interpreter to make testing easier for others, but it also works with the Kotlin implementation that pxeger's answer works with. Pxeger's post was (not intentionally) in [FISHQ9+](https://esolangs.org/wiki/FISHQ9%2B), using the kotlin interpreter `.jar` file supplied on the esolangs page, run with `java -jar`. When running the REPL and entering the code: ``` ######@######## downloads % java -jar FISHQ9P.jar >> 4+0# @ iiiiiiiiio print(8-(2*5-3)+(1/2)*10+8-4*(2147483647*2%3))#+++++P #++++++++++++++++++++++++++++++++++++++++++++++++++. 0+0# ^ 5_310 ``` It prints 10 (without a leading newline) after the code. To avoid making testing hell for everyone in future, I will shortly be adding a FISHQ9+ interpreter to DSO. This works because the `iiiiiiiiio` from answer #9 prints 9, but FISHQ9+ merges HQ9+'s `+` command in which increments it one more time to 10 before printing. Nothing else is printed. [Answer] # 10. FISHQ9+, 137 bytes, cracked by accident ``` 4+0# @ iiiiiiiiio print(8-(2*5-3)+(1/2)*10+8-4*(2147483647*2%3))#+++++P #++++++++++++++++++++++++++++++++++++++++++++++++++. 0+0# ^ 5_3 ``` The previous answer works in [Deadfish~](https://tio.run/##S0lNTEnLLM7Q/f/fRNtAWUHBQSETBvK5Cooy80o0LHQ1jLRMdY01tTUM9Y00tQwNNJW1QSBAAUKTBPS4DMAWxXGZxhv//w8A "Deadfish~ – Try It Online"). Try it online in: * [Ruby](https://tio.run/##KypNqvz/30TbQFlBwUEhEwbyuQqKMvNKNCx0NYy0THWNNbU1DPWNNLUMDbQtdE20NIwMTcxNLIzNTMy1jFSNNTWVtUEgQAFCkwT0uAzAtsdxmcYb//8PAA "Ruby – Try It Online") * [Jelly](https://tio.run/##y0rNyan8/99E20BZQcFBIRMG8rkKijLzSjQsdDWMtEx1jTW1NQz1jTS1DA20LXRNtDSMDE3MTSyMzUzMtYxUjTU1lbVBIEABQpME9LgMwLbHcZnGG///DwA "Jelly – Try It Online") * [Vyxal](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI0KzAjICBAIGlpaWlpaWlpaW9cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCs4LTQqKDIxNDc0ODM2NDcqMiUzKSkjKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCMgIF5cbjVfMyIsIiIsIiJd) * [Radvylf Should Not Be Allowed To Write Programming Languages](https://dso.surge.sh/#@WyJyYWlzaW4tYmF0d2FmZmxlIixudWxsLCI0KzAjICBAIGlpaWlpaWlpaW9cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCs4LTQqKDIxNDc0ODM2NDcqMiUzKSkjKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCMgIF5cbjVfMyIsIiIsIiIsIiJd) * [Headass](https://dso.surge.sh/#@WyJoZWFkYXNzIixudWxsLCI0KzAjICBAIGlpaWlpaWlpaW9cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCs4LTQqKDIxNDc0ODM2NDcqMiUzKSkjKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCMgIF5cbjVfMyIsIiIsIiIsIiJd) * [Python 3](https://tio.run/##K6gsycjPM/7/30TbQFlBwUEhEwbyuQqKMvNKNCx0NYy0THWNNbU1DPWNNLUMDbQtdE20NIwMTcxNLIzNTMy1jFSNNTWVtUEgQAFCkwT0uAzAtsdxmcYDnQIA "Python 3 – Try It Online") * [Brainfuck](https://tio.run/##SypKzMxLK03O/v/fRNtAWUHBQSETBvK5Cooy80o0LHQ1jLRMdY01tTUM9Y00tQwNtC10TbQ0jAxNzE0sjM1MzLWMVI01NZW1QSBAAUKTBPS4DMC2x3GZxhv//w8A "brainfuck – Try It Online") * [Runic Enchantments](https://tio.run/##KyrNy0z@/99E20BZQcFBIRMG8rkKijLzSjQsdDWMtEx1jTW1NQz1jTS1DA20LXRNtDSMDE3MTSyMzUzMtYxUjTU1lbVBIEABQpME9LgMwLbHcZnGG///DwA "Runic Enchantments – Try It Online") * [Deadfish~](https://tio.run/##S0lNTEnLLM7Q/f/fRNtAWUHBQSETBvK5Cooy80o0LHQ1jLRMdY01tTUM9Y00tQwNtC10TbQ0jAxNzE0sjM1MzLWMVI01NZW1QSBAAUKTBPS4DMC2x3GZxhv//w8A "Deadfish~ – Try It Online") --- My intended crack was Crystal before [version 0.31.0](https://github.com/crystal-lang/crystal/releases/tag/0.31.0), which is when Crystal got integer overflow checking by default. This also works with the version of Crystal on TIO, with `-D disable_overflow`: [Try it online!](https://tio.run/##Sy6qLC5JzPn/30TbQFlBwUEhEwbyuQqKMvNKNCx0NYy0THWNNbU1DPWNNLUMDbQtdE20NIwMTcxNLIzNTMy1jFSNNTWVtUEgQAFCkwT0uAzAtsdxmcYb////LzktJzG9@L@uy/@UzOLEpJzU@Pyy1KK0nPxyAA "Crystal – Try It Online"), but I didn't want to reveal that flag (which the rules would have required), so I chose to use an old version of Crystal instead. (this flag appears to have been removed entirely in the latest versions of Crystal: [Attempt This Online!](https://ato.pxeger.com/run?1=m708uaiyuCQxZ1e0kq6Lko6CUkpmcWJSTmp8fllqUVpOfrlS7IKlpSVpuhY3O020DZQVFBwUMmEgn6ugKDOvRMNCV8NIy1TXWFNbw1DfSFPL0EDbQtdES8PI0MTcxMLYzMRcy0jVWFNTWRsEAhQgNElAj8sAbHscl2m8McRBUHctgNIA)) [Answer] # 7. brainfuck, Exactly 100 Bytes, [cracked by aiden chow](https://codegolf.stackexchange.com/questions/247975/add-a-hidden-language-to-a-polyglot/247999#comment554554_247988) and [continued by Kevin Cruijssen](https://codegolf.stackexchange.com/a/247999/52210) The last answer was Python 3. ``` print(8 - (2 * 5 - 3) + (1/2) * 10)#+++++P #+++++++++++++++++++++++++++++++++++++++++++++++++++. 5_3 ``` [Answer] # 5. [Headass](https://esolangs.org/wiki/Headass), 34 bytes, cracked by emanresu A ``` print(8 - (2 * 5 - 3))#++++++P 5_3 ``` Previous answer was in [Radvylf Should Not Be Allowed To Write Programming Languages](https://dso.surge.sh/#@WyJyYWlzaW4tYmF0d2FmZmxlIixudWxsLCJwcmludCg4IC0gKDIgKiA1IC0gMykpXG41XzMiLCIiLCIiLCIiXQ==) Thanks emanresu A for adding my language to your web-site :D [Answer] # 1. Ruby, 9 bytes, [cracked by caird coinheringaahing](https://codegolf.stackexchange.com/a/247977/100664) ``` $><<$$/$$ ``` The answer to start things off. Should be fairly easy. [Answer] # 4. rSNBATWPL, 26 bytes ``` print(8 - (2 * 5 - 3)) 5_3 ``` [The previous answer was in Vyxal](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIkPjw8JCQvJCRcbjIrM18zIiwiIiwiIl0=) [Answer] # 12. [BitCycle](https://github.com/dloscutoff/esolangs/tree/master/BitCycle), 170 bytes, cracked by Dingus ``` 4+0#a /z@ iiiiiiiiio print(8-(2*5-3)+(1/2)*10+1+1+1+1+1+1+1+1+1+1+1-1-1-1-1-1-1-1-1-1-1-1)#!+++++P #++++++++++++++++++++++++++++++++++++++++++++++++++. 0+0#a ^ -1*-10+4_3 ``` Try It Online in [Ruby](https://tio.run/##KypNqvz/30TbQDlRQb/KQSETBvK5Cooy80o0LHQ1jLRMdY01tTUM9Y00tQwNtA2xQV2sUFNZURsEAhSUtUkGelwGYHfFcekaaukCLTaJN/7/HwA), [Jelly](https://tio.run/##y0rNyan8/99E20A5UUG/ykEhEwbyuQqKMvNKNCx0NYy0THWNNbU1DPWNNLUMDbQNsUFdrFBTWVEbBAIUlLVJBnpcBmB3xXHpGmrpAi02iTf@/x8A), [Vyxal](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI0KzAjYSAvekAgaWlpaWlpaWlpb1xucHJpbnQoOC0oMio1LTMpKygxLzIpKjEwKzErMSsxKzErMSsxKzErMSsxKzErMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEpIyErKysrK1AgIysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrLlxuMCswI2EgXlxuLTEqLTEwKzRfMyIsIiIsIiJd), [rSNBATWPL](https://dso.surge.sh/#@WyJyYWlzaW4tYmF0d2FmZmxlIixudWxsLCI0KzAjYSAvekAgaWlpaWlpaWlpb1xucHJpbnQoOC0oMio1LTMpKygxLzIpKjEwKzErMSsxKzErMSsxKzErMSsxKzErMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEpIyErKysrK1AgIysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrLlxuMCswI2EgXlxuLTEqLTEwKzRfMyIsIiIsIiIsIiJd), [Headass](https://dso.surge.sh/#@WyJoZWFkYXNzIixudWxsLCI0KzAjYSAvekAgaWlpaWlpaWlpb1xucHJpbnQoOC0oMio1LTMpKygxLzIpKjEwKzErMSsxKzErMSsxKzErMSsxKzErMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEpIyErKysrK1AgIysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrLlxuMCswI2EgXlxuLTEqLTEwKzRfMyIsIiIsIiIsIiJd), [Python 3](https://tio.run/##K6gsycjPM/7/30TbQDlRQb/KQSETBvK5Cooy80o0LHQ1jLRMdY01tTUM9Y00tQwNtA2xQV2sUFNZURsEAhSUtUkGelwGYHfFcekaaukCLTaJB7oVAA), [Brainfuck](https://tio.run/##SypKzMxLK03O/v/fRNtAOVFBv8pBIRMG8rkKijLzSjQsdDWMtEx1jTW1NQz1jTS1DA20DbFBXaxQU1lRGwQCFJS1SQZ6XAZgd8Vx6Rpq6QItNok3/v8fAA), [Runic Enchantments](https://tio.run/##KyrNy0z@/99E20A5UUG/ykEhEwbyuQqKMvNKNCx0NYy0THWNNbU1DPWNNLUMDbQNsUFdrFBTWVEbBAIUlLVJBnpcBmB3xXHpGmrpAi02iTf@/x8A), [Deadfish~](https://tio.run/##S0lNTEnLLM7Q/f/fRNtAOVFBv8pBIRMG8rkKijLzSjQsdDWMtEx1jTW1NQz1jTS1DA20DbFBXaxQU1lRGwQCFJS1SQZ6XAZgd8Vx6Rpq6QItNok3/v8fAA), [FishHQ9+](https://dso.surge.sh/#@WyJmaXNocTkrIixudWxsLCI0KzAjYSAvekAgaWlpaWlpaWlpb1xucHJpbnQoOC0oMio1LTMpKygxLzIpKjEwKzErMSsxKzErMSsxKzErMSsxKzErMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEpIyErKysrK1AgIysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrLlxuMCswI2EgXlxuLTEqLTEwKzRfMyIsIiIsIiIsIiJd), [Neutrino](https://tio.run/##y0stLSnKzMv//99E20A5UUG/ykEhEwbyuQqAciUaFroaRlqmusaa2hqG@kaaWoYG2obYoC5WqKmsqA0CAQrK2iQDPS4DsLviuHQNtXSBFpvEG///DwA) The code is ran under the `-u` flag. Very easy, definitely gonna get cracked within a few minutes. [Answer] # 2. Jelly, 11 bytes, [cracked by Steffan](https://codegolf.stackexchange.com/a/247978/66833) ``` $><<$$/$$ 2 ``` The previous answer was written in Ruby: [Try it online!](https://tio.run/##KypNqvz/X8XOxkZFRV9Fhcvo/38A "Ruby – Try It Online") [Answer] # 8. [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments), 105 bytes, [cracked by 00Her0](https://codegolf.stackexchange.com/a/248000/52210) ``` 4+0# @ print(8-(2*5-3)+(1/2)*10)#+++++P #++++++++++++++++++++++++++++++++++++++++++++++++++. 0+0# ^ 5_3 ``` Since *@AidenChow* cracks answers without posting a new one, I took the liberty to post the next in line. 1. [Try it online in Ruby.](https://tio.run/##KypNqvz/30TbQFlBwYGroCgzr0TDQlfDSMtU11hTW8NQ30hTy9BAU1kbBAIUIDRJQI/LAGx6HJdpvPH//wA) 2. [Try it online in Jelly.](https://tio.run/##y0rNyan8/99E20BZQcGBq6AoM69Ew0JXw0jLVNdYU1vDUN9IU8vQQFNZGwQCFCA0SUCPywBsehyXabzx//8A) 3. [Try it online in Vyxal.](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI0KzAjICBAXG5wcmludCg4LSgyKjUtMykrKDEvMikqMTApIysrKysrUCAjKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuXG4wKzAjICBeXG41XzMiLCIiLCIiXQ==) 4. [Try it online in Radvylf Should Not Be Allowed To Write Programming Languages.](https://dso.surge.sh/#@WyJyYWlzaW4tYmF0d2FmZmxlIixudWxsLCI0KzAjICBAXG5wcmludCg4LSgyKjUtMykrKDEvMikqMTApIysrKysrUCAjKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuXG4wKzAjICBeXG41XzMiLCIiLCIiLCIiXQ==) 5. [Try it online in Headass.](https://dso.surge.sh/#@WyJoZWFkYXNzIixudWxsLCI0KzAjICBAXG5wcmludCg4LSgyKjUtMykrKDEvMikqMTApIysrKysrUCAjKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuXG4wKzAjICBeXG41XzMiLCIiLCIiLCIiXQ==) 6. [Try it online in Python 3.](https://tio.run/##K6gsycjPM/7/30TbQFlBwYGroCgzr0TDQlfDSMtU11hTW8NQ30hTy9BAU1kbBAIUIDRJQI/LAGx6HJdpPNAqAA) 7. [Try it online in brainfuck.](https://tio.run/##SypKzMxLK03O/v/fRNtAWUHBgaugKDOvRMNCV8NIy1TXWFNbw1DfSFPL0EBTWRsEAhQgNElAj8sAbHocl2m88f//AA) [Answer] # 14. Vanilla TeX (initex), 256 bytes, mostly cracked by emanresu A ``` 1#+iiiiiiiiiokh-\catcode`\#=6\font\m=cmr10\m 14#\end; 4+0#a /z@ MoOMoOMoOMoOMoOMoOMoO print(8-(2*5-3)+(1/2)*10+1+1+1+1+1+1+1+1+1+1+1-1-1-1-1-1-1-1-1-1-1-1)#!+++++P #++++++++++++++++++++++++++++++++++++++++++++++++++. 0+0#a ^MoOMoOMoOMoOMoOMoOOOM -1*-10+4_3 ``` This is now available on ATO! > > You can run this on ATO [here](https://staging.ato.pxeger.com/run?1=m724JLViRbSSbmZeplLsgqWlJWm6FrcYGQyVtTNhID87QzcmObEkOT8lNSFG2dYsJi0_ryQm1zY5t8jQICaXy9BEOSY1L8Way0TbQDlRQb_KQcE33x8TcRUUZeaVaFjoahhpmeoaa2prGOobaWoZGmgbYoO6WKGmsqI2CAQoKGuTDPS4DMBOjMN0nL-_L5euoZYu0DUm8cZLipOSi6HBsQBKAwA). > > > Try it online in: 1. [Ruby](https://tio.run/##KypNqvz/31BZOxMG8rMzdGOSE0uS81NSE2KUbc1i0vLzSmJybZNziwwNYnK5DE2UY1LzUqy5TLQNlBMV9KscFHzz/TERV0FRZl6JhoWuhpGWqa6xpraGob6RppahgbYhNqiLFWoqK2qDQICCsjbJQI/LAOzEOEzH@fv7cukaaukCXWMSb/z/PwA) 2. [Jelly](https://tio.run/##y0rNyan8/99QWTsTBvKzM3RjkhNLkvNTUhNilG3NYtLy80picm2Tc4sMDWJyuQxNlGNS81KsuUy0DZQTFfSrHBR88/0xEVdBUWZeiYaFroaRlqmusaa2hqG@kaaWoYG2ITaoixVqKitqg0CAgrI2yUCPywDsxDhMx/n7@3LpGmrpAl1jEm/8/z8A) 3. [Vyxal](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIxIytpaWlpaWlpaWlva2gtXFxjYXRjb2RlYFxcIz02XFxmb250XFxtPWNtcjEwXFxtXG4xNCNcXGVuZDtcbjQrMCNhIC96QCBNb09Nb09Nb09Nb09Nb09Nb09Nb09cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCsxKzErMSsxKzErMSsxKzErMSsxKzEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xKSMhKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCNhIF5Nb09Nb09Nb09Nb09Nb09Nb09PT01cbi0xKi0xMCs0XzMiLCIiLCIiXQ==) 4. [rSNBATWPL](https://dso.surge.sh/#@WyJyYWlzaW4tYmF0d2FmZmxlIixudWxsLCIxIytpaWlpaWlpaWlva2gtXFxjYXRjb2RlYFxcIz02XFxmb250XFxtPWNtcjEwXFxtXG4xNCNcXGVuZDtcbjQrMCNhIC96QCBNb09Nb09Nb09Nb09Nb09Nb09Nb09cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCsxKzErMSsxKzErMSsxKzErMSsxKzEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xKSMhKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCNhIF5Nb09Nb09Nb09Nb09Nb09Nb09PT01cbi0xKi0xMCs0XzMiLCIiLCIiLCIiXQ==) 5. [Heada\*\*](https://dso.surge.sh/#@WyJoZWFkYXNzIixudWxsLCIxIytpaWlpaWlpaWlva2gtXFxjYXRjb2RlYFxcIz02XFxmb250XFxtPWNtcjEwXFxtXG4xNCNcXGVuZDtcbjQrMCNhIC96QCBNb09Nb09Nb09Nb09Nb09Nb09Nb09cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCsxKzErMSsxKzErMSsxKzErMSsxKzEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xKSMhKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCNhIF5Nb09Nb09Nb09Nb09Nb09Nb09PT01cbi0xKi0xMCs0XzMiLCIiLCIiLCIiXQ==) 6. [Python 3](https://tio.run/##K6gsycjPM/7/31BZOxMG8rMzdGOSE0uS81NSE2KUbc1i0vLzSmJybZNziwwNYnK5DE2UY1LzUqy5TLQNlBMV9KscFHzz/TERV0FRZl6JhoWuhpGWqa6xpraGob6RppahgbYhNqiLFWoqK2qDQICCsjbJQI/LAOzEOEzH@fv7cukaaukCXWMSDwwBAA) 7. [Brainf\*\*\*](https://tio.run/##SypKzMxLK03O/v/fUFk7EwbyszN0Y5ITS5LzU1ITYpRtzWLS8vNKYnJtk3OLDA1icrkMTZRjUvNSrLlMtA2UExX0qxwUfPP9MRFXQVFmXomGha6GkZaprrGmtoahvpGmlqGBtiE2qIsVaioraoNAgIKyNslAj8sA7MQ4TMf5@/ty6Rpq6QJdYxJv/P8/AA) 8. [Runic Enchantments](https://tio.run/##KyrNy0z@/99QWTsTBvKzM3RjkhNLkvNTUhNilG3NYtLy80picm2Tc4sMDWJyuQxNlGNS81KsuUy0DZQTFfSrHBR88/0xEVdBUWZeiYaFroaRlqmusaa2hqG@kaaWoYG2ITaoixVqKitqg0CAgrI2yUCPywDsxDhMx/n7@3LpGmrpAl1jEm/8/z8A) 9. [Deadfish~](https://tio.run/##lY5LCsIwFAD3OUUkmzbh2bx@RJCCFyj1AEENSUqLNJHalZePH3DVbpyZA4x12nbDo4cYkYnhR7j1oIyeTbDuqli9U13wsxprM04o1UiwZMp5eyClkEzT7HmkTWiXkfs0@DnZQ5LzCopUJJjlKUcpcE1YNWUb8eFEmfibLZHfxfNyrm0bAsjhfVNeihhf) 10. [FISHQ9+](https://dso.surge.sh/#@WyJmaXNocTkrIixudWxsLCIxIytpaWlpaWlpaWlva2gtXFxjYXRjb2RlYFxcIz02XFxmb250XFxtPWNtcjEwXFxtXG4xNCNcXGVuZDtcbjQrMCNhIC96QCBNb09Nb09Nb09Nb09Nb09Nb09Nb09cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCsxKzErMSsxKzErMSsxKzErMSsxKzEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xKSMhKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCNhIF5Nb09Nb09Nb09Nb09Nb09Nb09PT01cbi0xKi0xMCs0XzMiLCIiLCIiLCIiXQ==) 11. [Neutrino](https://tio.run/##y0stLSnKzMv//99QWTsTBvKzM3RjkhNLkvNTUhNilG3NYtLy80picm2Tc4sMDWJyuQxNlGNS81KsuUy0DZQTFfSrHBR88/0xEVcB0PASDQtdDSMtU11jTW0NQ30jTS1DA21DbFAXK9RUVtQGgQAFZW2SgR6XAdiJcZiO8/f35dI11NIFusYk3vj/fwA) 12. [BitCycle](https://tio.run/##lY5LDoIwFAD3PQWmG6B50gfVmBgSL0DwAI2KBWKjtATrQg9v/SSuYOPMHGCO2qm7ujTeI2X6hz2fQKrKKVs3B0nzpWytcbLLVTcglx1BQWVj6jURjNMqSB6boLDlONIP2rhwBWEaLyCLWIhJGsXIGU4Jk0Z0xj5sA8r@Zk74d3E3nivLggDG8L4R@8z7p@2dtubq4fYC) 13. [COW](https://tio.run/##S84v///fUFk7EwbyszN0Y5ITS5LzU1ITYpRtzWLS8vNKYnJtk3OLDA1icrkMTZRjUvNSrLlMtA2UExX0qxwUfPP9MRFXQVFmXomGha6GkZaprrGmtoahvpGmlqGBtiE2qIsVaioraoNAgIKyNslAj8sA7MQ4TMf5@/ty6Rpq6QJdYxJv/P8/AA) [Answer] # 21. PingPong, 294 bytes, cracked by Aiden Chow ``` 1# 2:0+:@ iiiiiiiiiokh \#+++++++++++++++O \font\m=cmr10\m14\end ;n+3e 4+0# MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOOOM h$1 o$ h$8 o$ print(8-(2*5-3)+(1/2)*10+1+1+1+1+1+1+1+1+1+1+1-1-1-1-1-1-1-1-1-1-1-1) #!+++++P #+++++++++++++++++++++++++++++++++.-#19$#& 0+0#;print{4} >8z@ S5^7^MOAOF -1*-10+4_3 ``` [Try it online!](https://tio.run/##jY5NC4JAFEX3/ooXI6EOU/P8IFMK27STCdoOtihTCWdEXBX9dhOhReWicy/c5T1NpYpGq6LvkYAbcRolUL3RtxIkoZ8IkFetOllvznWLXNboy1xdIFbUyw2fcgKpFv9UiBRKE0Gbw4TDGE1bqc4KmeU6AfNsauHStR3kFKfCJmMDmY2iB/hW/2XBCK5NMjf44B2P9w//CdvwnsAxyFZZKnZibzB02GDhn7y@fwE "PingPong – Try It Online") That's right, the code didn't change at all. Lol Try it online in [Ruby](https://tio.run/##jY69CsIwFEb3PMWVFGkaorn9wYoouriVCK6hglppkSZS6qAvH6vgoHbwfB@c9TTX/c05pLx6Y88laMo/UaBP1rS6nh/qBqWuMdaFOcLM8KggMZcUMqv@uVIZuTSVaf1U@GGQiIhxH8chC1By7JvoHQM6eKVt4Dv2l5GgOPXokMhn6SK9L2Gb5JM8Uyu1htJDsF6ntBMRGIguJd5Fzj0A) [Jelly](https://tio.run/##jY69CsIwFEb3PMWVFGkborn9wYoouriVCF1DHbTSaptI6aIvH6vgoHbwfB@c9ZyLur5Zi5RVb8ylBEXZJxLUyehONctD06JQDUaq0EdYaBYWJGKCQmrkP5cyJde20p2bcDfwYx56zMVp4PkoGA6ND84DOnql7eA79pcJpzh36JiIZ@kqua8hi/NZnsqN3ELpIBinV9KLcPR5nxLtQ2sf) [Vyxal](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIxIytpaWlpaWlpaWlva2ggXFwjKysrKysrKysrKysrKysrTyBcXGZvbnRcXG09Y21yMTBcXG0xNFxcZW5kIDtuKzNlXG40KzAjIE1vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT09PTVxucHJpbnQoOC0oMio1LTMpKygxLzIpKjEwKzErMSsxKzErMSsxKzErMSsxKzErMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEpICMhKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuLSMxOSQjJlxuMCswIyA+OHpAIFM1XjdeTU9BT0YgaCQxIG8kIGgkOCBvJFxuLTEqLTEwKzRfMyIsIiIsIiJd) [rSN](https://dso.surge.sh/#@WyJyYWlzaW4tYmF0d2FmZmxlIixudWxsLCIxIytpaWlpaWlpaWlva2ggXFwjKysrKysrKysrKysrKysrTyBcXGZvbnRcXG09Y21yMTBcXG0xNFxcZW5kIDtuKzNlXG40KzAjIE1vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT09PTVxucHJpbnQoOC0oMio1LTMpKygxLzIpKjEwKzErMSsxKzErMSsxKzErMSsxKzErMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEpICMhKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuLSMxOSQjJlxuMCswIyA+OHpAIFM1XjdeTU9BT0YgaCQxIG8kIGgkOCBvJFxuLTEqLTEwKzRfMyIsIiIsIiIsIiJd) [Heada\*\*](https://dso.surge.sh/#@WyJoZWFkYXNzIixudWxsLCIxIytpaWlpaWlpaWlva2ggXFwjKysrKysrKysrKysrKysrTyBcXGZvbnRcXG09Y21yMTBcXG0xNFxcZW5kIDtuKzNlXG40KzAjIE1vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT09PTVxucHJpbnQoOC0oMio1LTMpKygxLzIpKjEwKzErMSsxKzErMSsxKzErMSsxKzErMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEpICMhKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuLSMxOSQjJlxuMCswIyA+OHpAIFM1XjdeTU9BT0YgaCQxIG8kIGgkOCBvJFxuLTEqLTEwKzRfMyIsIiIsIiIsIiJd) [Python 3](https://tio.run/##jZA9C8IwFEX3/IonKdI0RPP6gRVRdHErEbqGOmilRZqU0kX/fI2Cg9rBcy/c9XDbW19ZEw0DUl6/sdcKNOWfKNAXa3rdrE9Nh1I3GOvSnGFleFSSmEsKmVX/VKmMtF1tej8VfhgkImLcx3nIApQcxyJGw4BOXmoH@Jb9ZSYoLj06JfJpuknvW8iTYlFkaqf2UHkI1nOTuiECA@FU4qP75QE) [Brainf\*\*\*](https://tio.run/##jY69CsIwGEX3PMUnKdI2RPP1Byui6OJWIriGitaWltJESl18@VgFB38Gz71w1nPqjrUur3ljLVJWvzBNBYqydySo0uhetcu87VCoFiNV6DMsNAsLEjFBITXyn0uZkktX695NuBv4MQ895uI08HwUDH@N/5wHdPRM28Fn7DcTTnHu0DERj9JVclvDPs5mWSo3cguVg2CcQckgwtHnQ0p0CK29Aw) [Runic Enchantments](https://tio.run/##jY69CsIwFEb3PMWVFGkaorn9wYoouriVCF1DHWqlRZpIqYsvH6vgoHbwfB@c9XQ305TOIeXNG3upQVP@iQJ9tqbX7bpsO5S6xVhX5gQrw6OKxFxSyKz650pl5No1pvdT4YdBIiLGfZyHLEDJcWxidAzo5JV2gO/YX2aC4tKjUyKfpZv0voU8KRZFpnZqD7WHYL1B6SAiMBBDSnyMnHsA) [Deadfish~](https://tio.run/##jY7NCoJAFEb38xQ3RkIdpub6Q0YUtWknE7gdjEhFCWfCXPXykwUtKhed74OzPUV5KqrmVnNrkbLmjbnUoCj7RIKqjO5Vuz63HQrVYqRKXcBKs7AkERMUUiP/uZQpuXaN7t2Eu4Ef89BjLs4Dz0fBcGx8dB7QySvtAN@xv8w4xaVDp0Q8SzfJfQtZnC/yVO7kHmoHwTiDkkGEo8@HlOgYWvsA) [FISHQ9+](https://dso.surge.sh/#@WyJmaXNocTkrIixudWxsLCIxIytpaWlpaWlpaWlva2ggXFwjKysrKysrKysrKysrKysrTyBcXGZvbnRcXG09Y21yMTBcXG0xNFxcZW5kIDtuKzNlXG40KzAjIE1vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT09PTVxucHJpbnQoOC0oMio1LTMpKygxLzIpKjEwKzErMSsxKzErMSsxKzErMSsxKzErMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEpICMhKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuLSMxOSQjJlxuMCswIyA+OHpAIFM1XjdeTU9BT0YgaCQxIG8kIGgkOCBvJFxuLTEqLTEwKzRfMyIsIiIsIiIsIiJd) [Neutrino](https://tio.run/##jY6xCsIwFEX3fMWTFGkbonlNixVRdHErEVxDHbTSIk2k1MWfj1FwUDt47oU73mOqW981xjqHlDVv7KUGTdknCvTZml63y2PbodAtproyJ1gYJiuSMkGhsOqfKlWQq3/tw5yHSZxxGbEQp0kUo2A4FD6YCOjopbaDb9lfJpziPKBjIp6mq/y@hn1WzspCbdQW6gDBBn5yP4RjzL1KepDOPQA) [BitCycle](https://tio.run/##jY7NCoJAGEX38xRfjIQ6TPn5Q0YUtWknE7QdDDJDKWfEbFEP32RBi34WnXvhbM@2bLNLdsyNQcrKF/pQgKTsHQFyr1Urq2lWNejJCkOZqx1MFAtyEjKPQqLFPxciIXVTqtaOue27EQ8cZuPQd1z0GP4a/zkHaO@ZtoLP2G8GnOLYon3iPUpn8XUO6ygdpYlYiCUUFoK2OsWdCEeXdynhJjDmpuu21Opk@PkO) [COW](https://tio.run/##jY69CsIwFEb3PMWVFGkaorn9wYoouriVCF1DHWqlRZpIKQi@fKyCg9rB831w1lPam3NIefPGXmrQlH@iQJ@t6XW7LtsOpW4x1pU5wcrwqCIxlxQyq/65Uhm5do3p/VT4YZCIiHEf5yELUHIcmxgdAzp5pR3gO/aXmaC49OiUyGfpJr1vIU@KRZGpndpD7SFYb1A6iAgMxJASHyPnHg) [TeX](https://TeX,%20278%20bytes:%20%5B%601#+iiiiiiiiiokh%20%5C#+++++++++++++++O%20%5Cfont%5Cm=cmr10%5Cm14%5Cend%20;n+3e%204+0#%20MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOOOM%20print(8-(2*5-3)+(1/2)*10+1+1+1+1+1+1+1+1+1+1+1-1-1-1-1-1-1-1-1-1-1-1)%20#!+++++P%20#+++++++++++++++++++++++++++++++++.-#19$#&%200+0#%20%3E8z@%20S5%5E7%5EMOAOF%20h$1%20o$%20h$8%20o$%20-1*-10+4_3%60%5D(https://staging.ato.pxeger.com/run?1=m724JLViRbSSbmZeplLsgqWlJWm6FrcYxQyVtTNhID87QyFGWRsV-CvEpOXnlcTk2ibnFhkaxOQamsSk5qUoWOdpG6dymWgbKCv45vsTg_z9fbkKijLzSjQsdDWMtEx1jTW1NQz1jTS1DA20DbFBXaxQU0FZEey0AAV0x2ICPV1lQ0sVZTUuA5BL7SyqHBSCTePM43z9Hf3dFDJUDBXyVYCUBZDi0jXU0gU6xSTeGBI80FBaAKUB)) [Brainf\*\*\*+](https://tio.run/##7Vzrk5vIEf@uv2JudRXAelha2xVHt2zl4thVrsS3js/JF8RRLIwkbAQYBu/Kiv52p3uGhxAPgWSf7yqHbQlBd09Pz697el6@NaPV58/Bhq187xEZXV1dfT8lV7JlMuXz52l/4KSX/35F5v1B8boh84XvsflatdbhdDJfTx/PqWeTH7zBI9p7PJj0ySv/ps3fm5tXvSB0PCY/HcmXD56MHikDefrwUnkwnQymVX9GlX8U0v@Oq/aaHCpbvsaj/vQv3/f/1JugptdPP/2V/Pzklz//8urmx5sXZAWW8L@Hr6fw1RtNH4xAlcfGo899smIsiGYPHy4dtopvx5a/fvj2o@9/emUuPWfhWNRjD/8Wmo73Irbev3bj6KXHaBiEFD57fbL2baQymeN70QwejEgUUMtZbEgQ@svQXJOF41LPXFNiRnAfRoyY4TJeg2BO7vnE8l0fDLbswYOX68APWc/hXyTaRPDsmW/TnrMgb8OYznoELnzmRcz0WMR/F17iZdAw9ENVkvInd2boFR74MQtiVnjkeIdPQLGlU@SDuscoau7lDznjh9hnVF1I24RktxUCdy/xk3iU2tQG0tQ0M5JRXl9fk70iVE16/uaNpD940uslFX4Rexa3Mv9t0wWYLdjIrpJXWsgirhMxWeNvDYUs/JAYWKirK2gntgkocKkqkhHqRpS4SSEoNPY@OYHMaMQMJChL1yRp/M53PFlzuGxnSN6h@IxFV4YZT3pp72po9b2iASgAKmrLwuamO3xPaVDWQKjIaylYZNdc39omuZ@Re22iYwnIORSWQOJMYmh6SypPhgDJ7KEirszSz1wzEla28I7DL1cCNTWgXR1mGHJE3cUQGsKme2rihS/G@Jyo/HWB3XKp6Rn4mAs4YO2L4JFJGEeB6zBZ6kuKNptd6kqBOrFJ2igtuFCDJWW15ScShaRc07IAn61oaKxMdyHs4Hg2vT8QZq3M0LSgjcAOXGJWsqJxer1A7k6h0S6BVpK17dVw/FAaSoq@u/5hNp9LBUpAci4b0X05K6EuomZordTDcmeiYDDLaKrXMBkIVxX00dzLMaeXs@KUIhO6UOuyuajZTNem8HGk7EvNnR4p26N3XLKwPY0M4MvcSEgbahnzMJd/gCLqOmtwBRG9MvrdNmfYFc1/t4KonrNhC6S6lG3hgFbp26RCGadSok4p1fQGGkwfZD8cbjz@r1xQYgU1veGs2Y86VtOL7jhCM8oDbXMzHNi/DQoTf@KSoL@TRWmDaaUfpy@F0iWXc30/MCAtqXe4atyd45MGXhjGUrZjHktqXDYDK2lAKwgcuJeDHPDVOI2AFdxDg@YFP3F00b1gE4gIj/HdnSoHzWV41hBCt63yzjHVRxnyn6lSyiELFAWf2gw5E0AIy@tkwN@UXgwOEcYLxY8qKQP@ovSclKQIpxPtATWFosto29fXsxKBnCVX9@A5PK5yJlQIRQmtq2RxtY8L403j8cQntXFFjFhwGs9nvGpwP0jAWKbdB9NeaEkCO4jP7cgVzWNH@f2gqur7sWQ/LNQVkEeYFgWIVjS9jaxVxk9ur8KbHPW6UrZGA3m16cDULQP3aQG8uYmKDdIQzJsbomj2GjH7obcirAvEDi71QpwFUitmNM3tqOtGKmSVcBuHEYwpxL0fONRWf/I9CGc4VDGBarsbkkWapvNfkWlRFUcmcGtZ/O4w2@M0hMzIzyv/jvxosdh0IeVcr03PjshzoYx9yGNZJON5FochjKbIM1S1QBhASggxVJ0U479ok6YuAiACRZQB0S89EckqjnlwfLXLBjSpUtx@MNDh3zvoHChGQkGkVPhFovIVBvCKvJo3EqTtTOX4Saj1qnCCdq2GdL/yaV1NRBPA8BRqwYuGWtRWgneJvhgPQy7Fa729uBDJuawtLrSts9Mv8u5KgEpXlIMEK6lEWltV@pc066L2g8vd69C3aISDbs@JVjDyvN0AuB0mADCXPswlqdp7E78xSi/B6xeZRh9qNOqT5x9i56MJTchm5Dak5vumUriNUu9KPStzqj2PatYGKtO9taU5E41ZZYmC@IuTpHstpd/USAcjxlSl8CWnqFLqYroTOXxKxKIyZ4P0kCn1MT3HjZgH2W05165e4/rBTlkmn36pgPRB15VPlRwn/WdiAIglHCo7sjIjcpyPV4sktRu2YMAZErLl8yScSWnFBeGaWKaHCcwthYYNqcXcDRHGHZMOFX3@5g2fuQBWqb53beejfhOwMIk@DVsR5vBN6BLAFbS1RCzczBqtUcaotQrTRmkGKrfEvUUDRv6D9M8RkG1La4fejgg@B8UnIVkwJRl1MvF1P51O4FLaciOq2SqOANpxBF0It8yMdKz0XgsQbEEFp4BJtWYdRaOzgEjAB5fTgIZGpzke23jKeJBJHabhooGgTgL4zXA7iv4WHkCOucAJbnCqK5zgDue6RNktopZ@ITj9BWad1iqZnNnyr10HAajoCV55vmd@Oe/8yh56ipce9dR2Hlvw3IE6be4pB@emYI3@jINK9KdUxA70qUuxhLu@hfzjiLf@P6dbeapl2riqxgfi7bK0czxmIeXtgukelAtJnuV7YCzKJ1T4spqMul1A61wohPn82QkJ4ODs9G/UBOp22V83WI/@gPUXgnUU3zI@Bf5tsB17URzgGBzLD2jIhWNlIrGkPFJnZC4hSucSwZdzCVptLp0A89HZMJ/Uz0SY0abXCrnq5Ngg3ZRq51MFlrTRVFfVye8M2QtcA08iwuQcjI5b8DpjIEsELCEw0gXrOjQO/GhyEmT43GfWUKOKhOCLzt4VsGPXYCfXZ/C19TkezI93BkkQf4kZ1ZEofoLeGi7I1ytf6bZjMwhwQXSiHHPf6Py@sGqW7chESDnOaBO9Br3CCnmNmutzVwcpNbWm3lCKumfyurqikwqyGcbShFHV9G8e4NrGNp6dQWgiSVt1CW4hxQpT@4SwFgcnBDWxHSkOzu4Nndre8GdnHbi0ZX@41fzQ5jtPRI@Pd2INN4iZnG94U/TdMdd7WddzerhV40Bc98CFmANRTSHrG/XJYuNfpwwTKtIxU8QlsCUNnU/dsRoxP6TENpnZBbDnJ5r70w2OBzV3bEgFGaSZbrJdgMkKuXPYityaESXTCWab3DadU8xb03a8U/OFCrdAJY4B3qp1wbcrP16uGKF1iWmyssx7I2hl3JmSl360k/t4esHOIin7O76szUP@65B@xFXcCVGvyQvTjWiHjm4rxO1@e0tJP/ls5XhLcgeOKZT8VYZXP5nrFPR8Q/RcEoXDCMqJeG9rU8jGqd0R4Z6PMDm73wjqVpjFIntdgopVObIaL6Tw9VwNyXWxAUskFEcQ/fqratXYr6SZEupaUL8xOf4H3XzLCY4U25bpuoDSLSq840hPwPWrQD0zQqJAxkraQhq0RZufGrjTMIRbDH87A6fn/AvVgvb4VtHvNYdyohLo0qlht3tteZz67/Q2XgLwmOnwXUDtORE1JfC0yIoK2426MCbjnHTypANrEhqAN7nbdU7@QyZqenYMXzRHSzJQyVnx0irQ1IwwDUO1tOks3RgKSinVhNnWnqRXMIzmUL8vsdkOL86xQ3Jm44yeY6EeVO2PDuPX6DDQ6CfPDIptaPOGOZPat8mWtXlT4lP3OgMKoA5PGskLZZxuQRU6tVxl3dOzC4fQvQNHWp8OLFkda6fVxDZblZ96m50TA7Ezz44iVEuyHa6MGW7A5PhDzs6TZZzKUKuf2UxPm92r6mTYguy7VmTk/rod2VWrQq/b6XbVioxvYa4kg5Spafowt7XGm0eXi8lSw8zp8d1hye7mbCPz3oG05N3va2/Yv73AdEKKa2m3oWm9p7i2NpeSXcdw31HeF9uzFcW3EcMTurxNF34M4f6EfVqej/VLN1GfuFOr0M273Rf@GmGVpgd7u@PLoBpMldG0dyaovmqX/uWAdDKIviCAuoGnHXD@25wf5jElO3FXG1EKco22cg8Oz1aXVYWzhnmPulMb3CM6nXmoO71Re@6h817@5Kz1KxP66/Roe3YSfA1P5b2uASqG50GiTTQ2w@VHhaiQvhfrKWpykf7nA@l/OnBxcH7w3mF7R134uUY/2BOtTXXcVAnpP4BVvYjZYvT0QhmH1LT3@HieZhh5ooaHe/j06JCf@OG36YFyB8@Loy4wLAKAGFg5Yx8nora9/wE) [RunR](https://tio.run/##jVhbd9pIEn5Gv6KMvUEYJMCOJxlsPJPNxOf4IcuecbL7YJxEoAZpLCRWLdmwDvvXs191t0Bc4sTOcUvVdfm6bl3K0JPBt29x4gtyLi4ujjp0YY@8rP7tW@ewERY/yX1Ag8PG5k@fBuMkzgbT3miadtqDaeflQMQ@nceNU2G9bLQP6X3S/5l//f57a5aGcWa/duyT4zPntN6wO62T@nGn3ejs@3X2/tbp8EBB@ydtg939cZ3Dzq9Hhy@sNiO9fP3f3@nm7NOrT@/7b/pXFMATyRGW11gsp3PsAMrLz6ffWi36EISS8M8j9ttfeI4zkc5Sgb80TlIKsmwmu62WkEnkxRPpJumk9Rjeh60/8/hPCyq8PAuStEsy82QS@ueUikh4UviUJTTLh1E4Ij@ZemFsWQ8etErqgec/eZgKuzaWtfq5ZYVjsmdpMhJSul46eXAjEU@ygC56dFKnJ6sySmIgEG6UTOzqR@lNRFdBpjSPUxfAL8ZhJC6rUFYpFIl5mNlw5bm1VJZHzN8DADcVnn8F/ptFPNqwe3ty16Rano2d1wrXLM9GAUR7NAqod0kFr8z8JM/cxzTMhD0KwNpqbfOCASRq8Ps5wVMPIpVhEiu/DtPkUYrUYg8WPoYHR/cJuMZR8uiOkmnLa/3y8uT07LTTsYpgxUL4kt5xmJqUx1F4LyhJw0kYe5GJnsvM/U0aQiBkXMtI5rNZkmZwXuyoLW@UhQ8CbADbJJGmSSoZOz0GItZuXRkf5zG4cYShCLwHgbyR9OG6X5M4DwI8zkf3TcQ2y9NYUpvA@K5/peD8I8kQMU0gdj@7fsVaHbSrrrXSPhHKk3adLIQ@EhkN8/FYsGv/rh5cL4qSkc2hrZhwqlC2m4azSXhU29qEIbtZcpOhOif2OsZLq3X8r93IdJ@Dg4BalXBsK6dRr0fVal1FXZ0EeyKSgtO2ooiK7bZ9h42KEdE0V6I6hD7HcoWVtS@PWyo3MnY7ss7PkXfkh3wKESOMSY7@lAVevB19ayjEDAYAdzNhEVqTsLXBK5XdfBR/OEFNcf7qJ07fda2pvIUfkumUraKiRewNI0HYg9GJZWXpgg/K3cDmAmuSqYNm4TfEBIiaxpLyONryKLBVrm1Ut6JoeqOmg2Ot4/DzNiylU1U7L66cRWgFtUHMOis4UiqmKDQapHAajdCtKBnjbRBrOReJ8M4DRDsKY9EMlSv50QQMTaXXqw3SGv2mDNyGdzBVYmg3uYV3qc322M2PoZ8FBZxUcDhtOxUyj7ImyykL770scKfevLxhOmG9ybo4GloT4EZJPBEyU2YtbWWWcHMdh7H/Gc0kzZS36vT1Kz3Nu1wSC/xdGkh@yAX15GOnA8@Vt1QnwubtnSFMSxQGMfVQRnPNpznifIrtttod5alKUtCG6HEVlceCc3GSelO6Of3QJ3VJShqcNtFoQpSJzCd8HMlJnVG10PHgRbmo8h0VJ5lSI72p4MZT3TRT1TjAzy7wUIAbWJQeq4J@UaTTtpusChcstwCbFS2KaJmryKHOOYiX6pALxwG/ElBW54b5dnHnRp7MrmNfzPtju3ajMg5ljwtuTgc94rwwdf40by7Y41z6SPRKueHYCKVBhD5zwK@uNk4vXpB@uyjjq6/UxnkUnZfl5htyc8ipHNqVKPoPH0SZuFPL/A7Ae2gDvoDPcLH/to@lSzWqnW@dZJbMbJUk5izrTFFUl/frBqyil@3UEW40Y/pyo5KP6epqJOTH0VPhpCXZR08Kw7KpHxbL@pfScaBXt9cSrlEUztjg2sVs/QI1VvikXUJ1SSdnZ6sdPO/RXlLu@Q9ejPpeh1D7HZMAas715@eGtFiRFts60MU4N9GsS1lgupsBwlo0xf7yA3cwyt7RE/4u4fj73u3Rk/L/8o4rW71PCwIKBaz4u/xSN6hQoBHfUiaGa2jnJqTqlisQMFE@htzhMRkVVaKaLMqhu36h8sv/al0u12v4w@c5BdWORkpevCBfRN6CGzVX/9Zt18RNSGGm@0MyowDXo8taK0NMBfe45FYWrmCh5DpN5dTvFlQGkPKNihlMGRP@RN0MkzT0S5quoUlnscqj1Xzg8vIWpfEms9t1tGuDYSXYh6C5umw9iLjjNJm@NWIqI9dia7lPtW5RMLkMFNuu8ocVqnXV7XK92cTOj42SwB6Jj7sSzvMS73cljp@X@EOnAt8UfyCyMktXA@tjkt4/F/xHQTyL8mwyyTHq8NwK3pQJuRSKdYJXP3wI1ZCHBo/kcgt7VwiAvldmYtSl6r957OX3zeuFJsCDKYP7T5t1eEOeINAMmpx/MpzOogWClMwk9ydWEISTQN87brWwpsbozatO64dUugIrV@j03KzceB2jK4bZos4DJ@wqlpKb1fSA/ogJiqmtssf1JbRdE7V2ravWjllPzHpq1pdmPTPrL2Z9ZdbXZv3VhE@jaajxeF8J/g2JoS/oA@6bpTTAUT8P8wkHWscBDlTBk/g8wCdKjol/oXMhUU23qeYBPLM@Wwq4W@CjgFkiv742ebRRFdPvlcULsE2/V2JrtoP1AbDsqvmw2s/SXDx7wCv13R3xt8uCE9VXXx8cYhlogXXb2hhqdkDZ4NgZ5jDLGU7uas4laSe99TKXP5lLHqpviDv7xC8cy5zBnzcBF@rUgyGyybaywXOvITolIhVE9cxEtbsmOopIBVEDa22ey9E3pR5V9ct8ueXiH8KjffCcHXi0D56zCW8w2MRXhreNbi31tVbsQs6cYjePnIJrseJa7FHW4Cut@Nlx1bzsqsVy18ohxHmuQHrVf158Lf@7llfi5aFng3UnKkRqcIrEOHsuf3bd/sOk2sqfi@/H56fSxwDFnRNkz6XS3qR2nj3TFtLLZzL9@6l0DCn@7LU3HY7p2cPXY7eYnq9jBCj09bWamxH15yZoDM2VjcCaOVprrn2MYRXDDP@HAH8R1PiD/f8) [><>](https://tio.run/##jY69CsIwFEb3PMWVFGkborn9wYoouriVCF1DHbSlRZpI7eTLxyg4qB083wdnPXV7a6xFyto35tKAouwTCao2elDd@tT1KFSHiar0GVaaxRVJmKCQG/nPpczJtW/14Gfcj8KUxwHzcR4FIQqGY@OjC4BOXmkH@I79ZcYpLj06JeJZusnuWyjSclHmcif30HgIxnPKnAjHkLuU5Bhb@wA) [xEec](https://tio.run/##jY69CsIwFEb3PMWVFGkborn9wYoouriVCF1DHWqkRZpI6SC@fKyCg9rB831w1nPTunIOKWve2EsNirJPJKizNb1q11XboVAtJkqbE6wMizVJmKCQW/nPpczJtWtM72fcj8KUxwHzcR4FIQqGY@OjC4BOXmkH@I79ZcYpLj06JeJZusnuWyjSclHmcif3UHsI1huUDSIcQz6kJMfYuQc) [Versert](https://tio.run/##jY5NC4JAFEX3/ooXI6EOU/N0JFMK27STCdoOtihDCTVMWhT99mkQWvSx6NwLd3nPteguRddrjQT8mNM4hepFeypBEfqOBHVsm17Vi33dIVc1ClU0B0gaGhSWoJxA1sp/KmUGpY3Q2mYiM9a5q5reiZjjeyELXOrg1Hc95BR/hf2MC2Q0iG7gU/2bCSM4t8nY4sY7Ge7v4gHL6JbCNsxneSZXcm0x9JixELtA6yc) [Answer] # 3. Vyxal, 15 bytes, cracked in literally 30 seconds by emanresu A ``` $><<$$/$$ 2+3_3 ``` The previous answer was written in Jelly. [Try it online in Jelly.](https://tio.run/##y0rNyan8/1/FzsZGRUVfRYXLSNs43vj/fwA "Jelly – Try It Online") [Try it online in Ruby.](https://tio.run/##KypNqvz/X8XOxkZFRV9FhctI2zje@P9/AA "Ruby – Try It Online") [Answer] # 6. Python 3, 46 bytes, [cracked by aiden chow](https://codegolf.stackexchange.com/questions/247975/add-a-hidden-language-to-a-polyglot/247983#comment554545_247983) and [continued by Nobody](https://codegolf.stackexchange.com/a/247988/100664) ``` print(8 - (2 * 5 - 3) + (1/2) * 10)#+++++P 5_3 ``` The previous answer was in [Headass](https://esolangs.org/wiki/Headass). For the sake of everyone else doing this: [Try it online in Ruby!](https://tio.run/##KypNqvz/v6AoM69Ew0JBV0HDSEFLwRTIMNZU0FbQMNQ30gQKGBpoKmuDQACXabzx//8A) [Try it online in Jelly!](https://tio.run/##y0rNyan8/7@gKDOvRMNCQVdBw0hBS8EUyDDWVNBW0DDUN9IEChgaaCprg0AAl2m88f//AA) [Try it Online in Vyxal!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJwcmludCg4IC0gKDIgKiA1IC0gMykgKyAoMS8yKSAqIDEwKSMrKysrK1BcbjVfMyIsIiIsIiJd) [Try It Online in rSNBATWPL!](https://dso.surge.sh/#@WyJyYWlzaW4tYmF0d2FmZmxlIixudWxsLCJwcmludCg4IC0gKDIgKiA1IC0gMykgKyAoMS8yKSAqIDEwKSMrKysrK1BcbjVfMyIsIiIsIiIsIiJd) [Try It Online in Headass!](https://dso.surge.sh/#@WyJoZWFkYXNzIixudWxsLCJwcmludCg4IC0gKDIgKiA1IC0gMykgKyAoMS8yKSAqIDEwKSMrKysrK1BcbjVfMyIsIiIsIiIsIiJd) [Answer] # 16. [RunR](https://esolangs.org/wiki/RunR), 286 bytes ``` 1#+iiiiiiiiiokh\#+++++++++++++++O\>#\catcode`\#=6\font\m=cmr10\m 14#\end; 4+0#a /z@ MoOMoOMoOMoOMoOMoOMoO print(8-(2*5-3)+(1/2)*10+1+1+1+1+1+1+1+1+1+1+1-1-1-1-1-1-1-1-1-1-1-1)#!+++++P #++++++++++++++++++++++++++++++++++++++++++++++++++. 0+0#a ^MoOMoOMoOMoOMoOMoOOOMS5^7^MOAOF -1*-10+4_3 ``` [Answer] # 17. [><>](https://tio.run/#%23jY9LC4JAFEb38ysmhkgdJmd8VCBGbdrJBG0vlvhACccwV/35KYwWplDnu8u7OKeo7qXWgtDqQ3MtgdAhErYE0qRLmyy/AAlXUDSqgzpM61ZwqOfg5kh4BHKVBfg3iwB5lJME248djho5vsG3Qre2Up2xYYZj@cw1qSFsx7QEp2JqbHImmfUxR/yd9wdLxHvheKwqZXTy43Ucyb08vI1hKhoQExZ7OXtnV@sn), 329 bytes, cracked by stasoid ``` 1#+iiiiiiiiiokh\#+++++++++++++++O\>#\catcode`\#=6\font\m=cmr10\m%\3e 14#\end; '; 4+0#a /z@ MoOMoOMoOMoOMoOMoOMoO 'n print(8-(2*5-3)+(1/2)*10+1+1+1+1+1+1+1+1+1+1+1-1-1-1-1-1-1-1-1-1-1-1)#!+++++P #++++++++++++++++++++++++++++++++++++++++++++++++++. 0+0#a ^MoOMoOMoOMoOMoOMoOOOMS5^7^MOAOF \ \ -1*-10+4_3 ``` Try it online in [Ruby](https://tio.run/##jY/NCoJAFEb38xQTQ6QOk44/FYhRm3YyQduLZWok4UyILerlpzBamEKd7y7v4pz6drxrzQktP6jLGQjtImBJIEubTOXFAUg0g5OSDVRRVtXcgWoMXoG4T6CQeYh/MwmRTx2SYvuxwrES/et8S3StS9kYC2a4VsA8kxrcdk2LO5QPjQ3OJKM2Zou/8/5gipxWOOmrChHvgmSexGItNm9jGIoGxLjFXs7@3tP6CQ) [Jelly](https://tio.run/##jY/NCoJAFEb38xQTQ6QOk44/FYhRm3YyQduLJWpk6UyIm3r5KYwWllDnu8u7OOdcVNVNa05o@UZdTkBoHwFLAlnaZiovDkCiGRyVbKGOsrrhDtRj8ArEfQKFzEP8m0mIfOqQFNv3FY6V@L7et0TXppStsWCGawXMM6nBbde0uEP50NjgTDLqYrb4M@8PpsjphJNvVSHiXZDMk1isxeZlDEPRgBi32NPZ33taPwA) [Vyxal](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIxIytpaWlpaWlpaWlva2hcXCMrKysrKysrKysrKysrKytPXFw+I1xcY2F0Y29kZWBcXCM9NlxcZm9udFxcbT1jbXIxMFxcbSVcXDNlXG4xNCNcXGVuZDsgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICc7XG40KzAjYSAvekAgTW9PTW9PTW9PTW9PTW9PTW9PTW9PICAgICAgICAgICAgJ25cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCsxKzErMSsxKzErMSsxKzErMSsxKzEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xKSMhKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCNhIF5Nb09Nb09Nb09Nb09Nb09Nb09PT01TNV43Xk1PQU9GICAgICAgXFwgICAgICAgICAgICAgICAgICAgIFxcXG4tMSotMTArNF8zIiwiIiwiIl0=) [rSN](https://dso.surge.sh/#@WyJyYWlzaW4tYmF0d2FmZmxlIixudWxsLCIxIytpaWlpaWlpaWlva2hcXCMrKysrKysrKysrKysrKytPXFw+I1xcY2F0Y29kZWBcXCM9NlxcZm9udFxcbT1jbXIxMFxcbSVcXDNlXG4xNCNcXGVuZDsgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICc7XG40KzAjYSAvekAgTW9PTW9PTW9PTW9PTW9PTW9PTW9PICAgICAgICAgICAgJ25cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCsxKzErMSsxKzErMSsxKzErMSsxKzEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xKSMhKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCNhIF5Nb09Nb09Nb09Nb09Nb09Nb09PT01TNV43Xk1PQU9GICAgICAgXFwgICAgICAgICAgICAgICAgICAgIFxcXG4tMSotMTArNF8zIiwiIiwiIiwiIl0=) [Heada\*\*](https://dso.surge.sh/#@WyJoZWFkYXNzIixudWxsLCIxIytpaWlpaWlpaWlva2hcXCMrKysrKysrKysrKysrKytPXFw+I1xcY2F0Y29kZWBcXCM9NlxcZm9udFxcbT1jbXIxMFxcbSVcXDNlXG4xNCNcXGVuZDsgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICc7XG40KzAjYSAvekAgTW9PTW9PTW9PTW9PTW9PTW9PTW9PICAgICAgICAgICAgJ25cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCsxKzErMSsxKzErMSsxKzErMSsxKzEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xKSMhKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCNhIF5Nb09Nb09Nb09Nb09Nb09Nb09PT01TNV43Xk1PQU9GICAgICAgXFwgICAgICAgICAgICAgICAgICAgIFxcXG4tMSotMTArNF8zIiwiIiwiIiwiIl0=) [Python 3](https://tio.run/##jZDBCoJAFEX38xUTQ6QOk05qBWLUpp1M0PZhiRpKOCMym/p5E6OFKdS5b3kX5776oQsl3bblhJYf1L0AQocI2BFIE52qLL8CCddwU1JDFaZVwx2o5uDmiHsEcpkF@DeLAHnUIQm2n3scKTG@QVuiuimlNrbMWFk@c01qcHtlWtyhfCpsMiaZ9WNO@HveHyyR0wvHY1UhorMfb@JIHMTxbQxTowExbrHO2bt0L38B) [Brainf\*\*\*](https://tio.run/##jY/NCoJAFEb38xTGEKnDpONPBWLUpp1M0PZi2agk4kyIbXr5KYwWllDnu8u7OOfcZpUsb6LWmmFSvVH1BTAZwmGNQWSdUHlxAhwvoFSygyYWTctcaKbgF4gFGAqZR8ZvZhEKiIszw7lvjETx7xt8S3RtK9mZK2p6dkh9i5jM8SybuYSNjY7OwpM@Zm985v3BHLm9cPqtynlyCNNlmvAt372MYSwaEGU2fToHR1/rBw) [Runic Enchantments](https://tio.run/##jY9PC4IwGIfv@xTGiNSx3PxTgRh16SYLur5YMo0k3ELs0pdfYXQwhXp@7/E9PE9zV5U0hmNSfdDXC2DSR8Aag8xbqYvyBDhZwFmrFupE1g1nUE8hKBEPMZSqiK3fzGIUEoZzy3tsrFSL4fW@Fbo1lWrtFbV9N6KBQ2zu@Y7LGeFjo6Nz8KSL2VvfeX8wR6wTzoaqQqSHKFtmqdiK3dsYxqIBUe7Sl3N4DIx5Ag) [Deadfish~](https://tio.run/##jY/NCoJAFEb38xQTQ6QOkzP@VCBGbdrJBG0vluiIEjphrnp5C6OFKdT57vIuzslUkuXlvWBdJwgtP@hrAYQOkbAlkCZtqjN1ARKuINd1C1WYVo3gUM3BVUh4BFSdBfg3iwB5lJME248djrQc3@C7RremrFtjwwzH8plrUkPYjmkJTsXU2ORMMutjjvg77w@WiPfC8VhVyujkx@s4knt5eBvDVDQgJiz2cvbObtc9AQ) [FISHQ9+](https://dso.surge.sh/#@WyJmaXNocTkrIixudWxsLCIxIytpaWlpaWlpaWlva2hcXCMrKysrKysrKysrKysrKytPXFw+I1xcY2F0Y29kZWBcXCM9NlxcZm9udFxcbT1jbXIxMFxcbSVcXDNlXG4xNCNcXGVuZDsgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICc7XG40KzAjYSAvekAgTW9PTW9PTW9PTW9PTW9PTW9PTW9PICAgICAgICAgICAgJ25cbnByaW50KDgtKDIqNS0zKSsoMS8yKSoxMCsxKzErMSsxKzErMSsxKzErMSsxKzEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xKSMhKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKy5cbjArMCNhIF5Nb09Nb09Nb09Nb09Nb09Nb09PT01TNV43Xk1PQU9GICAgICAgXFwgICAgICAgICAgICAgICAgICAgIFxcXG4tMSotMTArNF8zIiwiIiwiIiwiIl0=) [Neutrino](https://tio.run/##jY9BC4IwGIbv@xWLEalj6VIrEKMu3WRB1w9LdJGEW4hd@vNLjA6mUM/7Hb/D8yj5aOpSaWM4oeUHfbsCoX0EbAjkWZPrQp6BxEu4aNVAFedVzT2opuBLxAMCUhUR/s0sQgH1SIbd5xYnWgyv963QvfVsrDWzFk7IfJta3F3YDvcoHxsbnU0mXcwBf@f9wRx5nXA6VBUiOYbpKk3ETuzfxjAWDYhxh7XOwck35gU) [BitCycle](https://tio.run/##jY9BC4IwGIbv@xXGiNSxdKkVRFGXbrKg64dl00jKLWod6se3ouhgCvW83/E7PM@m0OIqDrkxDJPig9rvAJMqHCYYRKqFyvI14HEftkpqKMeiPDEfyjYEOWIhhlxmI@s3nREKiY9Ty7tNrVjx@lW@JTqeCqntIbV7bkQDh9jM6zku8wlrGm2cg1uvmIX1nfcHXeS/hJO6KufxMkoGScxnfP42hqZoQJS59OkcrgJj7uqoCyXPhl4e) [COW](https://tio.run/##jY9PC4IwGIfv@xSLEaljufmnAjHq0k0WdH2xZBpJ6EKEoC@/wuhgCvX83uN7eB6l78YIQssP@noBQvtIWBNQWat0XpyAxAs467qFKlZVIzhUU/ALJAICRZ1H@DezCAWUkwy7jw1OtBxe77tGt6asW2vFLM8JmW9TS7ie7QhOxdjY6Gwy6WL2@DvvD@aId8LpUFXK5BCmyzSRW7l7G8NYNCAmHPZyDo6@MU8) [TeX](https://TeX,%20369%20bytes:%20%5B%601#+iiiiiiiiiokh%5C#+++++++++++++++O%5C%3E#%5Ccatcode%60%5C#=6%5Cfont%5Cm=cmr10%5Cm%25%5C3e%2014#%5Cend;%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%27;%204+0#a%20/z@%20MoOMoOMoOMoOMoOMoOMoO%20%20%20%20%20%20%20%20%20%20%20%20%27n%20print(8-(2*5-3)+(1/2)*10+1+1+1+1+1+1+1+1+1+1+1-1-1-1-1-1-1-1-1-1-1-1)#!+++++P%20#++++++++++++++++++++++++++++++++++++++++++++++++++.%200+0#a%20%5EMoOMoOMoOMoOMoOMoOOOMS5%5E7%5EMOAOF%20%20%20%20%20%20%5C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%5C%20-1*-10+4_3%60%5D(https://staging.ato.pxeger.com/run?1=m724JLViRbSSbmZeplLsgqWlJWm6FrcYCw2VtTNhID87I0ZZGxX4x9gpxyQnliTnp6QmxCjbmsWk5eeVxOTaJucWGRrE5KrGGKdyGZoox6TmpVgrEAbq1lwm2gbKiQr6VQ4Kvvn-mAhFdR5XQVFmXomGha6GkZaprrGmtoahvpGmlqGBtiE2qIsVaiorgj0ToIDuPSKAHpcB2MFxmE719_cNNo0zj_P1d_R3g7g4BpunY7h0DbV0gW42iTeGhDw0AhZAaQA)) [Brainf\*\*\*+](https://tio.run/##7Vxtk9u2Ef6uX4Gc2iFpvZx0ttuMcrxp6tozntY513H7hWJYHgVJjCmSJkHfyap@u7sL8EUU3yU7TqaR7TuK3F3sLp5dLEDAd2a4/vTJ37K15z4mo@vr6z9MybVsmUz59GnaH9jJx3u3nvcH@c/t/KY/B1LLW9D/zPvqn@ZLz2XzjWptgulkvvnj/DHtTZ/059RdfEeaP9J3vSeDSd8klx//Ql55t8W/OWq35we2y@RvR/LVo6ejx8pAnl5eKY@mk8G07M@o9I/S/4Yb85ocm9fiM@5NuMI/FVW9vX3149Of/vzTq9vvb18IjedlRs97o@mjEej8xHj8qU/WjPnh7PJyZbN1dDe2vM3l2w@e9/GVuXLtpW1Rl13@NTBt90VkvXvtROFLl9HADyj87PXJxlsglclszw1ncGNEQp9a9nJL/MBbBeaGLG2HuuaGEjOE6yBkxAxW0QYEc3LXI5bneODZVQ9uvNz4XsB6Nv9Fwm0I955Bf/fsJXkbRHTWQyPwnhsy02Uh/557iB@DBoEXqJKU3bk3Azd3w4uYH7HcLds9vgOKrew8H9geoai5m93kjO8jj1F1Ke1ikv1OCNy/xJ/EpXRBF0CauGZGUsqbmxty0ISqSc/fvJH0R097vdjgF5FrcS/z7wu6BLf5W9lRMqOFLOLYIZM1/tRQyNILiIGNOrqCfmJbnwKXqiIZoU5IiRM3gkIj96Pty4yGzECConRNksY/e7YrazaXbQ/Jzyg@ZdGVYe8YdNrPFbT6QdMAFAAVXcjC56YzfEepX9RAqMitFCyyY27uFiZ5mJEHbaJjC8g5FJ5A4lRiYLorKk@GAMn0piI@qaefOWYovGzhFYdfpgRqakC/2sww5JA6yyHBfHSgJn7wwRjvE5U/zrFbDjVdA29zAUesfZFlUgnj0HdsJkt9SdFmsytdyVHHPkk6pQUXarCirLL9WKKQlGlaFOCxNQ2MtekshR9sd0EfjoRZazMwLegj8AOXmLasaJxez5E7U@i0K6CVZG13PRxfSkNJ0fc3383mcylHCUjOZCO6r2YF1IXUDKy1etzuTDQMbhlN9QomA@Gqgj6aczXm9HLanJJnwhBq3TYXNZvp2hR@NLR9pTnThrZdes8lC9/T0AC@NIyEtKGWMg8z@Ucooo69gVAQ2Sul3@8yhn3e/fdryOoZG/ZAokvRFzZolTyNDUo5lQJ1QqkmF9Bh@iD9YnPn8X/FhmIvqMkFZ02/VLGabnjPEZpSHmmbueHI/21QGMcTlwTjnSxaG0xL4zh5KJQuhJzjeb4B1U11wJXj7pyYNPCDaSxha4pYUhGyKVhJDVpB4MC5GmSAL8dpCKwQHhp0L8SJrYvhBbtAZHjM785UOeouw7WGkLoXKh8cE32UIf@aKKUcs0BT8FObIWcMCOF5nQz4k8KDwTHCeKP4o0zKgD8o3CcFKSLoRH@ApdB0EW2H@rpWLJCzZOoe3YfbZcGECqEooXWZLK52szDeNS4vfBIfl@SIJadxPcZNg@tBDMYi7SGYDlJLnNhBfOZHrmiWO4rPB2WmH@aSw7RQ1UCWYVo0IHrRdLeyVpo/ub9yTzLU60rRGzXk5a4DV7dM3Kcl8PouyndITTKv74i82yvEHKbekrQuEDu40nN5FkitiNGktqOOE6pQVcJlFIQwpxDXnm/ThfqD50I6w6mKCVS7/ZAskzKdfwtNi6o4M4FLy@JXx9UepyFkRn5ce/fke4tFpgMl52ZjuouQPBfKLI55LIukPM@iIIDZFHmGquYIfSgJIYeqk3z@F31SN0QARKCJIiD6hTuiWMU5D86v9umEJlGK@w8mOvz3HgYHiplQECklcRGrfI0JvKSu5p0EZTtTOX5iar0snaBfyyHdL71bZYnoApieghW8abCi0gg@JHpiPgy1FLd6d3EhinNZW15oO3uvX2TDlQCVrihHBVZsRGKtKv1TmnVR@9HV/nXgWTTESbdrh2uYed5tAdw2EwCYS@/nklQevXHcGIWHEPXLVKP3FRr1yfP3kf3BhC5kM3IXUPNdXSvcR0l0JZGVBtVBRNVrA8Z0721pzkRnlnkiJ/7iJOluS@m3FdLBiRFVKfySE1QpVTndDm2@JGJRmbNBeciU6pye4Uasg@x3nGtfrXH1ZKcoky@/lED6aOjKlkqaSf8ROwByCYfKnqzNkDTzcbNIbN2wBQOukJAdXyfhTEorLkjXxDJdLGDuKHRsQC3mbIlw7ph0MPT5mzd85QJYperRtV2MenXAwiL6NGyFWMPXoUsAV9BWErFgO6v1RhGj1jpIOqUeqNwTDxb1Gfk30j9HQLZtrR16OyL4HBSfhGTBFFfU8cLXw3Q6gY/SlhtRzdZRCNCOQhhCuGdmpKPRBz1AsAcVXAIm5Zp1FI3BAiIBH1xODRpqg6Y5t/GS8aiSOi7DRQeBTQL49XBrRH@LCCBNIXBCGJwaCieEw7khUQyLsGVcCE5viVWntY4XZ3b8176DAFT0hKg8PzI/X3R@4Qg9JUobI7VdxOYid6BO60fKwbklWG0846QS4ykRsQd9qkosEa5vof5oiNb/53IrK7XMBb5V4xPxdlXaORGzlLJ@wXIP2oUiz/JccBblCyr8tZqMul1A71wohHn83gkF4ODs8m9UB@p21V83WI9@h/VngnUY3TG@BP51sB25YeTjHBzb92nAhaMxoXilPFJnZC4hSucSwYdzCXptLp0A89HZMJ9Ur0SY4bbXCrnqpGmSbkqV66kCS9poqqvq5DeG7CW@A48zwuQcjI5b8NpjIIsFrCAx0iXrOjX2vXByEmT42mfaUaOSguCzrt7lsLOowE6mz@BL69OczJsHgziJv8SKqiGLn6C3hi/kq5UvDdux6fv4QnSiNIVveP5YWLbK1rAQUswz2kSvQK/wQmZRvT33VZBSE2/qNa2oBy6vshWDVJDNMJfGjKqmf/UE1za38eoMUhOJ@6pLcgsoGkwXJ6S1yD8hqYntSJF/9mhoV46GP9ob36Etx8Od5gULvvNEjPh4Jd7h@hGTsw1vir5vCr2XVSOni1s1jsR1T1yIORBVl7K@0pgsNv51qjDBkI6VIr4CW9HA/tgdqyHzAkoWJjO7APb8QvNwucF2wXJ7AaUggzLTibcLMFkh9zZbkzszpGQ6wWqT@6ZziXlnLmz31HqhJCxQiSbAW5Uh@HbtRas1I7SqMI3fLPPRCHoZd6ZkrTcOch9Ob9hexm1/w19r85T/OqAf8C3uhKg35IXphLTDQLcT4va/vldJP3hsbbsrcg@BKZT8RaZXP5ibBPR8Q/RcEo3DDMoO@Wi7oFCN00VHhLsewuTsccOvesMsXrJXFahoSsPbeCGFv8/VkFwXG7BEQdGA6NdfVKvacSWplFDXnPq1xfHf6fZrLnAk2LZMxwGU7lDhPUd6DK5fBOqpE2IFUlbSFtKgLfr81MSdpCHcYvjrmTg9579QLeiPr5X9XnMoxyqBLp06dnfQl83Uf6N30QqAx0yb7wJqz4moKYCnRVWU227UhTGe5ySLJx1Y49QAvPHVvnPxHzBh6dk5fFmfLclAJWflSytHUzHDNAzV0qazZGMoKKWUE6Zbe@JRwTDqU/2hxHo/vDjHD/GZjTNGjqV6ZNrvA8YvMWCg009eGRTb0OY1ayaVT@Mta/O6wqfqcQoUQB2eNJKXyjjZgip0avmW9UDPLhxC9w4ciT0dWFIbK5fVxDZblZ96m52TA3EwT48ilEta2FwZM9iCy/GLnJ4nSzmVoVa9spmcNntQ1cmwBdk3rcjIw007sutWjd600@26FRnfwlxKBiVT3fJh5muNd48u54ulmpXT5t1h8e7mdCPzwYG0@Nlva2/Yv1zftAOK79LuAtN6R/Hd2lyKdx3DdUd5n23PVhjdhQxP6PI@XXoRpPsT9mm5HtqXbKI@cadWbph3ur/4q4VVUh4c7I4vgmowVUbT3pmg@qJD@ucD0skg@owA6gaedsD5b319mOWU9MRdZUbJyTXayj06PFveVhnOatY9qk5t8IjodOah6vRG5bmHznv547PWr0wYr5Oj7elJ8A3clQ@GBjAMz4OE23BsBqsPClGhfM/bKSy5SP7zgeQ/Hbg4Oj/4YLODoy78XKPnH4jWpjpuqoTyH8CqXkRsOfr2QhkH1Fwc8PE6zTCyQg0P9/Dl0SE/8cMvkwPlNp4XR11gWgQAMdA44xAnwtre/wA) [RunR](https://tio.run/##jVhbd9pIEn5Gv6KDPUHYSIAvSRYbz2Qz8Tl@yLJnnOw@GCcRqJE0FhKrbtkwDvPXvV91t0AC4gR8kFRdl6/r1iWPPBE@PSWpz5lzfn6@32Xn9tiTzaen7t5hVHzSu3C4d1j9DIYXe0OwjiH7dbjXfzWcpIkcTvvjadbtDKe/DI@51T3ZG/LEP2M//jTOrJPDzp7H2n/9xj6kg@2/CndizbIokfYbxz46OHWOm4d2t33UPOh2Dru7vs7Ob3PvhdrMv9nm9n7i41odBfjzNtTB4MP16efXnz8M3g4uNeLhrk0PLad74ADzyZfjp3abfQwjwfDnMQrJn7hPJM9mGccvm6QZC6WciV67zUUae0kg3DQL2g/RXdT@I0/@sKDCy2WYZj0mpCfSCK7PeMw9wX0mUzbLR3E0Zn469aLEsu49aBWsD57/5VHG7cZENJpnlhVNmD3L0jEXwvWy4N6NeRLIkJ332VGTPVq1cZoAAXfjNLDrn4QX8J6CzLI8yVwAP59EMb@oQ1mtUMTnkbTh8zNrqSxT5sD2RLgZ9/xL8F8vknHF7s3RbYs1cjlx3ihcs1yOQ4j22Thk/QtW8Arpp7l0H7JIcnscgrXd3uQFA0jskJ7PGDx1zzMRpYny6yhLHwTPLPJg4WN4cHyXgmsSpw/uOJ22vfark6Pj0@Nu1yqClXDuC/aewtRieRJHd5ylWRREiReb6LnEPKjSEAIukoZkIp/N0kzCeYmjlryxjO452AC2xXiWpZkg7Owh5Il268r4JE/AjS2MeOjdc@SNYB@vBg2B/SDAk3x810JsZZ4lgnUYGN8PLhWcf6USEdMERu4n169Y68NO3bVW2gOuPGk3mYXQx1yyUT6ZcHLtP9WN68VxOrYptDUTThXKTstwthhu1bI2YciuTK8lyjiw1zFeWu2D/2xHpvccHATUqkUTWzmN9fusXm@qqKudYI3HglPa1hRRsd10brFQMyKa5gpUB9f7WK6wkvblQVvlhiS3I@v8HHnH/Ih2wROEMc0TVFjoJZvRt0acz2AAcKsJi9CahG0MX6vspq34owA1Rfmr7yh917Wm8hZ@SKdTsoqK5ok3ijnDGowGliWzBW2UuoFNBdZipg5ahd8QEyBqGUvK49TGQ1vlWqW6FUXTDxs6ONY6Dj9vw1I6VbXTxRWzGK2gMUxIZw1byvgUhcaGGZzGxuhWLJ3gaZhoOReJ8N4DRDuOEt6KlCvp1gQMTaXfbwyzBvtVGbiJbmGqxNBpgYX1WIfskZsfIl@GBZyMUzhtO@Mij2WL5JSFD54M3ak3Ly@YTthskS6KhtYEuHGaBFxIZdbSVmYpNddJlPhf0EwyqbzVZN@@scd5j0pigd@lgeRHVFCPPla68Fx5SXUiLN7cGsK0RCEQUw9lNNd8miPJp1juqNVxnqkkBW2EHldTecwpF4PMm7Lr448Dpk5TwYbHLTSaCGUi8oC2IyipJasXOu69OOd1OqOSVCo1wptyajz1qpm6xgF@coGHAqxgUXqsGvpFkU6bbrJqVLDUAmxStCiiZY4ih3XPQLxQm1w4DviVgLI6N8w3i1s39oS8Snw@H0zsxrXKOJQ9Drg5e9FnlBemzh/nrQV5nEofiV4rNxwboTSI0Gde0KOrjbOXL5l@Oi/ja67UJnkcn5Xl5hW5OeRUDm1LFP2HNqJM3KrL/BbA@2gDPofPcLD/uoulxxo0U1V3MktntkoSs5d1piiqS@tNA1bRy3aaCDeaMft6rZKP6OpoZMiP/cfCSUtm7z8qDMuWvlksm19L24Fe3V5LuMZxNCODaxeT9XPUWOGTTgnVBTs6PV2t4H6H9pJyz7/3EtT3OoTa75gEUHOuPz8zpMWKtNjUgS5GuYlmXcoC090MENKiKfbXH7iDUPb3H/G7hOPv@jf7j8r/y1uqbPU8LQgoFLDid/m1aVChQGM6pUwM19DOTEjVKVcgIKJ4iKjDYzIqqkQ1WZRDb/3Ayg9/N3pUrlfwh09zCqodjZR5yYL5PPYW1Kip@jdOuxZOQhZJ3R/SGQtxPLqktTbCVHCHQ25l4RIWSq7TVEr9XkElABmdqJjBlDHuB@pkCLLIL2m6giadxSqPVvOBS5d3KI230u400a4NhpXgAILm6LL1IOJOsnT6zoipjFyLreU@N3pFweQiVGzbyu9XqNZVt831toqdbg9LAjskPm1LOM9LfNiWOHhe4nedCnRS/I7ICpmtBtaHNLt7LvgPnNEsSrNJkGPUobkVvBkRcsEVa4BHP7qP1JCHBo/kcgt7lwiAPldmfNxj9f/S2EvP1eOFBcCDKYP6T4d0eCOaINAMWpR/IprO4gWClM4E9SdSEEZBqM8dt15YU2N09ajT@iGVrcCKFTo9Nys3XiXoipFcNGnghF3FUnKzmh7QHzFBEbVd9rg@hDZrotFp9NS1a65H5npsrifmemqur8z1tbm@Mdd/mPBpNIdqPN5Vgr8gMfQB/YL6ZikNsNUvozygQOs4wIEqeAKvB3hFyTHxL3QupKrpttQ8gHvSZwsOd3O8FBBL7DfXJvcrVTH9Xlm8BNv0eyW2Znux3gAu22o@rtZllvNnN3ip3rtjendZUKL66u2DQixCLbBuW5WhZguUDY6tYQ6znOGkruZcMO2kd5506ZW55KFmRdzZJX7uWGYP/rwFuFCnbgyRTHaUDZp7DdEpEVlBVPdEVKtroqOIrCBqYO3qvhx9UupRVT/Mlxsu/iE8tgueswWP7YLnVOENh1V8ZXib6NZS3xrFKuTMLrbzyCm4FiuuxQ5lh3SkFZ8tV83Lrlost63sQZzmCqRX8@fF1/K/aXklXh56KqxbUWFMDU4xn8jn8mfb7T9Mqo38Of9@fH4qfQxQnDmhfC6Vdia18@yeNpBePJPp30@lA0jRa69ddTimZw9vj71ier5KEKDI18dqbkbUn5ugMTTXKoE1c7TW3PiUwCqGGfqHAL0RNOiF/f8) [Answer] # 18. [xEec](https://esolangs.org/wiki/xEec), 271 bytes, cracked by 00Her0 ``` 1#+iiiiiiiiiokh \#+++++++++++++++O \font\m=cmr10\m14\end ;n+3e 4+0# MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOOOM print(8-(2*5-3)+(1/2)*10+1+1+1+1+1+1+1+1+1+1+1-1-1-1-1-1-1-1-1-1-1-1) #!+++++P #+++++++++++++++++++++++++++++++++. 0+0# >8z@ S5^7^MOAOF h$1 o$ h$8 o$ -1*-10+4_3 ``` Previous answer works in [><>](https://tio.run/##jY9LC4JAFEb38ysmhkgdJmd8VCBGbdrJBG0vlvhACccwV/35KYwWplDnu8u7OKeo7qXWgtDqQ3MtgdAhErYE0qRLmyy/AAlXUDSqgzpM61ZwqOfg5kh4BHKVBfg3iwB5lJME248djho5vsG3Qre2Up2xYYZj@cw1qSFsx7QEp2JqbHImmfUxR/yd9wdLxHvheKwqZXTy43Ucyb08vI1hKhoQExZ7OXtnV@sn). [Answer] # 20. [Versert](https://esolangs.org/wiki/Versert), 294 bytes ``` 1# 2:0+:@ iiiiiiiiiokh \#+++++++++++++++O \font\m=cmr10\m14\end ;n+3e 4+0# MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOOOM h$1 o$ h$8 o$ print(8-(2*5-3)+(1/2)*10+1+1+1+1+1+1+1+1+1+1+1-1-1-1-1-1-1-1-1-1-1-1) #!+++++P #+++++++++++++++++++++++++++++++++.-#19$#& 0+0#;print{4} >8z@ S5^7^MOAOF -1*-10+4_3 ``` #19 is [AsciiDots](https://tio.run/##jY7NCoJAGEX38xRfjIQ6TM3nD5lR2KadTNB2MEINh9AJddXLmwUt@ll07oWzPacu17owfTcMSMGLBYsT0C/MpQJF2TsS1Nk0varXed2iUDUGqmwKWDXML0nABIXUyH8uZUqurW56O@K254bcd5iNc89xUTD8Nf5zDtDJM20Pn7HfzDjFpUWnRDxKN9EtgUOYLbJUbuUOKgvBWKOiUYSjy8eU4OgPwx0). Fixed rSNBATWPL code according to [this](https://github.com/chunkybanana/do-stuff-online/pull/17). [Answer] # 13. COW 214 bytes, cracked by Dingus ``` 4+0#a /z@ iiiiiiiiiokhMoOMoOMoOMoOMoOMoOMoO print(8-(2*5-3)+(1/2)*10+1+1+1+1+1+1+1+1+1+1+1-1-1-1-1-1-1-1-1-1-1-1)#!+++++P #++++++++++++++++++++++++++++++++++++++++++++++++++. 0+0#a ^MoOMoOMoOMoOMoOMoOOOM -1*-10+4_3 ``` Pretty easy, should get cracked fast. I don't know enough languages :/. Try it online in: [Ruby](https://tio.run/##KypNqvz/30TbQDlRQb/KQSETBvKzM3zz/TERV0FRZl6JhoWuhpGWqa6xpraGob6RppahgbYhNqiLFWoqK2qDQICCsjbJQI/LAOzcOEzH@fv7cukaaukCXWMSb/z/PwA) [Jelly](https://tio.run/##y0rNyan8/99E20A5UUG/ykEhEwbyszN88/0xEVdBUWZeiYaFroaRlqmusaa2hqG@kaaWoYG2ITaoixVqKitqg0CAgrI2yUCPywDs3DhMx/n7@3LpGmrpAl1jEm/8/z8A) [Vyxal](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI0KzAjYSAvekAgaWlpaWlpaWlpb2toTW9PTW9PTW9PTW9PTW9PTW9PTW9PXG5wcmludCg4LSgyKjUtMykrKDEvMikqMTArMSsxKzErMSsxKzErMSsxKzErMSsxLTEtMS0xLTEtMS0xLTEtMS0xLTEtMSkjISsrKysrUCAjKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuXG4wKzAjYSBeTW9PTW9PTW9PTW9PTW9PTW9PT09NXG4tMSotMTArNF8zIiwiIiwiIl0=) [rSNBATWPL](https://dso.surge.sh/#@WyJyYWlzaW4tYmF0d2FmZmxlIixudWxsLCI0KzAjYSAvekAgaWlpaWlpaWlpb2toTW9PTW9PTW9PTW9PTW9PTW9PTW9PXG5wcmludCg4LSgyKjUtMykrKDEvMikqMTArMSsxKzErMSsxKzErMSsxKzErMSsxLTEtMS0xLTEtMS0xLTEtMS0xLTEtMSkjISsrKysrUCAjKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuXG4wKzAjYSBeTW9PTW9PTW9PTW9PTW9PTW9PT09NXG4tMSotMTArNF8zIiwiIiwiIiwiIl0=) [Heada\*\*](https://dso.surge.sh/#@WyJoZWFkYXNzIixudWxsLCI0KzAjYSAvekAgaWlpaWlpaWlpb2toTW9PTW9PTW9PTW9PTW9PTW9PTW9PXG5wcmludCg4LSgyKjUtMykrKDEvMikqMTArMSsxKzErMSsxKzErMSsxKzErMSsxLTEtMS0xLTEtMS0xLTEtMS0xLTEtMSkjISsrKysrUCAjKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuXG4wKzAjYSBeTW9PTW9PTW9PTW9PTW9PTW9PT09NXG4tMSotMTArNF8zIiwiIiwiIiwiIl0=) [Python 3](https://tio.run/##K6gsycjPM/7/30TbQDlRQb/KQSETBvKzM3zz/TERV0FRZl6JhoWuhpGWqa6xpraGob6RppahgbYhNqiLFWoqK2qDQICCsjbJQI/LAOzcOEzH@fv7cukaaukCXWMSD/QXAA) [Brainf\*\*\*](https://tio.run/##SypKzMxLK03O/v/fRNtAOVFBv8pBIRMG8rMzfPP9MRFXQVFmXomGha6GkZaprrGmtoahvpGmlqGBtiE2qIsVaioraoNAgIKyNslAj8sA7Nw4TMf5@/ty6Rpq6QJdYxJv/P8/AA) [Runic Enchantments](https://tio.run/##KyrNy0z@/99E20A5UUG/ykEhEwbyszN88/0xEVdBUWZeiYaFroaRlqmusaa2hqG@kaaWoYG2ITaoixVqKitqg0CAgrI2yUCPywDs3DhMx/n7@3LpGmrpAl1jEm/8/z8A) [Deadfish~](https://tio.run/##S0lNTEnLLM7Q/f/fRNtAOVFBv8pBIRMG8rMzfPP9MRFXQVFmXomGha6GkZaprrGmtoahvpGmlqGBtiE2qIsVaioraoNAgIKyNslAj8sA7Nw4TMf5@/ty6Rpq6QJdYxJv/P8/AA) [FISHQ9+](https://dso.surge.sh/#@WyJmaXNocTkrIixudWxsLCI0KzAjYSAvekAgaWlpaWlpaWlpb2toTW9PTW9PTW9PTW9PTW9PTW9PTW9PXG5wcmludCg4LSgyKjUtMykrKDEvMikqMTArMSsxKzErMSsxKzErMSsxKzErMSsxLTEtMS0xLTEtMS0xLTEtMS0xLTEtMSkjISsrKysrUCAjKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuXG4wKzAjYSBeTW9PTW9PTW9PTW9PTW9PTW9PT09NXG4tMSotMTArNF8zIiwiIiwiIiwiIl0=) [Neutrino](https://tio.run/##y0stLSnKzMv//99E20A5UUG/ykEhEwbyszN88/0xEVcBUEuJhoWuhpGWqa6xpraGob6RppahgbYhNqiLFWoqK2qDQICCsjbJQI/LAOzcOEzH@fv7cukaaukCXWMSb/z/PwA) [BitCycle](https://tio.run/##S8osSa5Mzkn9/99E20A5UUG/ykEhEwbyszN88/0xEVdBUWZeiYaFroaRlqmusaa2hqG@kaaWoYG2ITaoixVqKitqg0CAgrI2yUCPywDs3DhMx/n7@3LpGmrpAl1jEm/8//@//IKSzPy84v@6pQA) [Answer] # 15. BrainF\*ck+, 430 bytes, Should Be Very Easily Cracked By whqwert ``` 1#+iiiiiiiiiokh-\ #+++++++++++++++O\ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>14#+iiiiiiiiiokh-\catcode`\#=6\font\m=cmr10\m 14#\end; 4+0#a /z@ MoOMoOMoOMoOMoOMoOMoO print(8-(2*5-3)+(1/2)*10+1+1+1+1+1+1+1+1+1+1+1-1-1-1-1-1-1-1-1-1-1-1)#!+++++P #++++++++++++++++++++++++++++++++++++++++++++++++++. 0+0#a ^MoOMoOMoOMoOMoOMoOOOM -1*-10+4_3 ``` For this language it ends in an error, but that is supposed to be allowed. [Answer] # 19. [AsciiDots](https://tio.run/#%23jY7NCoJAGEX38xRfjIQ6TM3nD5lR2KadTNB2MEINh9AJddXLmwUt@ll07oWzPacu17owfTcMSMGLBYsT0C/MpQJF2TsS1Nk0varXed2iUDUGqmwKWDXML0nABIXUyH8uZUqurW56O@K254bcd5iNc89xUTD8Nf5zDtDJM20Pn7HfzDjFpUWnRDxKN9EtgUOYLbJUbuUOKgvBWKOiUYSjy8eU4OgPwx0), 278 Bytes, Cracked by stasoid ``` 1#+iiiiiiiiiokh \#+++++++++++++++O \font\m=cmr10\m14\end ;n+3e 4+0# MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOOOM print(8-(2*5-3)+(1/2)*10+1+1+1+1+1+1+1+1+1+1+1-1-1-1-1-1-1-1-1-1-1-1) #!+++++P #+++++++++++++++++++++++++++++++++.-#19$#& 0+0# >8z@ S5^7^MOAOF h$1 o$ h$8 o$ -1*-10+4_3 ``` Try it online in [Ruby](https://tio.run/##jY69CsIwFEb3PMWVFGkaorn9wYoouriVCK6hglppkSZS6qAvH6vgoHbwfB@c9TTX/c05pLx6Y88laMo/UaBP1rS6nh/qBqWuMdaFOcLM8KggMZcUMqv@uVIZuTSVaf1U@GGQiIhxH8chC1By7JvoHQM6eKVt4Dv2l5GgOPXokMhn6SK9L2Gb5JM8Uyu1htJDsF6ntBMRGIguJd5Fzj0A) [Jelly](https://tio.run/##jY69CsIwFEb3PMWVFGkborn9wYoouriVCF1DHbTSaptI6aIvH6vgoHbwfB@c9ZyLur5Zi5RVb8ylBEXZJxLUyehONctD06JQDUaq0EdYaBYWJGKCQmrkP5cyJde20p2bcDfwYx56zMVp4PkoGA6ND84DOnql7eA79pcJpzh36JiIZ@kqua8hi/NZnsqN3ELpIBinV9KLcPR5nxLtQ2sf) [Vyxal](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIxIytpaWlpaWlpaWlva2ggXFwjKysrKysrKysrKysrKysrTyBcXGZvbnRcXG09Y21yMTBcXG0xNFxcZW5kIDtuKzNlXG40KzAjIE1vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT09PTVxucHJpbnQoOC0oMio1LTMpKygxLzIpKjEwKzErMSsxKzErMSsxKzErMSsxKzErMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEpICMhKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuLSMxOSQjJlxuMCswIyA+OHpAIFM1XjdeTU9BT0YgaCQxIG8kIGgkOCBvJFxuLTEqLTEwKzRfMyIsIiIsIiJd) [rSN](https://dso.surge.sh/#@WyJyYWlzaW4tYmF0d2FmZmxlIixudWxsLCIxIytpaWlpaWlpaWlva2ggXFwjKysrKysrKysrKysrKysrTyBcXGZvbnRcXG09Y21yMTBcXG0xNFxcZW5kIDtuKzNlXG40KzAjIE1vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT09PTVxucHJpbnQoOC0oMio1LTMpKygxLzIpKjEwKzErMSsxKzErMSsxKzErMSsxKzErMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEpICMhKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuLSMxOSQjJlxuMCswIyA+OHpAIFM1XjdeTU9BT0YgaCQxIG8kIGgkOCBvJFxuLTEqLTEwKzRfMyIsIiIsIiIsIiJd) [Heada\*\*](https://dso.surge.sh/#@WyJoZWFkYXNzIixudWxsLCIxIytpaWlpaWlpaWlva2ggXFwjKysrKysrKysrKysrKysrTyBcXGZvbnRcXG09Y21yMTBcXG0xNFxcZW5kIDtuKzNlXG40KzAjIE1vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT09PTVxucHJpbnQoOC0oMio1LTMpKygxLzIpKjEwKzErMSsxKzErMSsxKzErMSsxKzErMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEpICMhKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuLSMxOSQjJlxuMCswIyA+OHpAIFM1XjdeTU9BT0YgaCQxIG8kIGgkOCBvJFxuLTEqLTEwKzRfMyIsIiIsIiIsIiJd) [Python 3](https://tio.run/##jZA9C8IwFEX3/IonKdI0RPP6gRVRdHErEbqGOmilRZqU0kX/fI2Cg9rBcy/c9XDbW19ZEw0DUl6/sdcKNOWfKNAXa3rdrE9Nh1I3GOvSnGFleFSSmEsKmVX/VKmMtF1tej8VfhgkImLcx3nIApQcxyJGw4BOXmoH@Jb9ZSYoLj06JfJpuknvW8iTYlFkaqf2UHkI1nOTuiECA@FU4qP75QE) [Brainf\*\*\*](https://tio.run/##jY69CsIwGEX3PMUnKdI2RPP1Byui6OJWIriGitaWltJESl18@VgFB38Gz71w1nPqjrUur3ljLVJWvzBNBYqydySo0uhetcu87VCoFiNV6DMsNAsLEjFBITXyn0uZkktX695NuBv4MQ895uI08HwUDH@N/5wHdPRM28Fn7DcTTnHu0DERj9JVclvDPs5mWSo3cguVg2CcQckgwtHnQ0p0CK29Aw) [Runic Enchantments](https://tio.run/##jY69CsIwFEb3PMWVFGkaorn9wYoouriVCF1DHWqlRZpIqYsvH6vgoHbwfB@c9XQ305TOIeXNG3upQVP@iQJ9tqbX7bpsO5S6xVhX5gQrw6OKxFxSyKz650pl5No1pvdT4YdBIiLGfZyHLEDJcWxidAzo5JV2gO/YX2aC4tKjUyKfpZv0voU8KRZFpnZqD7WHYL1B6SAiMBBDSnyMnHsA) [Deadfish~](https://tio.run/##jY7NCoJAFEb38xQ3RkIdpub6Q0YUtWknE7gdjEhFCWfCXPXykwUtKhed74OzPUV5KqrmVnNrkbLmjbnUoCj7RIKqjO5Vuz63HQrVYqRKXcBKs7AkERMUUiP/uZQpuXaN7t2Eu4Ef89BjLs4Dz0fBcGx8dB7QySvtAN@xv8w4xaVDp0Q8SzfJfQtZnC/yVO7kHmoHwTiDkkGEo8@HlOgYWvsA) [FISHQ9+](https://dso.surge.sh/#@WyJmaXNocTkrIixudWxsLCIxIytpaWlpaWlpaWlva2ggXFwjKysrKysrKysrKysrKysrTyBcXGZvbnRcXG09Y21yMTBcXG0xNFxcZW5kIDtuKzNlXG40KzAjIE1vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT01vT09PTVxucHJpbnQoOC0oMio1LTMpKygxLzIpKjEwKzErMSsxKzErMSsxKzErMSsxKzErMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEpICMhKysrKytQICMrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuLSMxOSQjJlxuMCswIyA+OHpAIFM1XjdeTU9BT0YgaCQxIG8kIGgkOCBvJFxuLTEqLTEwKzRfMyIsIiIsIiIsIiJd) [Neutrino](https://tio.run/##jY6xCsIwFEX3fMWTFGkbonlNixVRdHErEVxDHbTSIk2k1MWfj1FwUDt47oU73mOqW981xjqHlDVv7KUGTdknCvTZml63y2PbodAtproyJ1gYJiuSMkGhsOqfKlWQq3/tw5yHSZxxGbEQp0kUo2A4FD6YCOjopbaDb9lfJpziPKBjIp6mq/y@hn1WzspCbdQW6gDBBn5yP4RjzL1KepDOPQA) [BitCycle](https://tio.run/##jY7NCoJAGEX38xRfjIQ6TPn5Q0YUtWknE7QdDDJDKWfEbFEP32RBi34WnXvhbM@2bLNLdsyNQcrKF/pQgKTsHQFyr1Urq2lWNejJCkOZqx1MFAtyEjKPQqLFPxciIXVTqtaOue27EQ8cZuPQd1z0GP4a/zkHaO@ZtoLP2G8GnOLYon3iPUpn8XUO6ygdpYlYiCUUFoK2OsWdCEeXdynhJjDmpuu21Opk@PkO) [COW](https://tio.run/##jY69CsIwFEb3PMWVFGkaorn9wYoouriVCF1DHWqlRZpIKQi@fKyCg9rB831w1lPam3NIefPGXmrQlH@iQJ@t6XW7LtsOpW4x1pU5wcrwqCIxlxQyq/65Uhm5do3p/VT4YZCIiHEf5yELUHIcmxgdAzp5pR3gO/aXmaC49OiUyGfpJr1vIU@KRZGpndpD7SFYb1A6iAgMxJASHyPnHg) [TeX](https://TeX,%20278%20bytes:%20%5B%601#+iiiiiiiiiokh%20%5C#+++++++++++++++O%20%5Cfont%5Cm=cmr10%5Cm14%5Cend%20;n+3e%204+0#%20MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOOOM%20print(8-(2*5-3)+(1/2)*10+1+1+1+1+1+1+1+1+1+1+1-1-1-1-1-1-1-1-1-1-1-1)%20#!+++++P%20#+++++++++++++++++++++++++++++++++.-#19$#&%200+0#%20%3E8z@%20S5%5E7%5EMOAOF%20h$1%20o$%20h$8%20o$%20-1*-10+4_3%60%5D(https://staging.ato.pxeger.com/run?1=m724JLViRbSSbmZeplLsgqWlJWm6FrcYxQyVtTNhID87QyFGWRsV-CvEpOXnlcTk2ibnFhkaxOQamsSk5qUoWOdpG6dymWgbKCv45vsTg_z9fbkKijLzSjQsdDWMtEx1jTW1NQz1jTS1DA20DbFBXaxQU0FZEey0AAV0x2ICPV1lQ0sVZTUuA5BL7SyqHBSCTePM43z9Hf3dFDJUDBXyVYCUBZDi0jXU0gU6xSTeGBI80FBaAKUB)) [Brainf\*\*\*+](https://tio.run/##7Vzrk5vIEf@uv2JudRXAelha2xVHt2zl4thVrsS3js/JF8RRLIwkbAQYBu/Kiv52p3uGhxAPgWSf7yqHbQlBd09Pz697el6@NaPV58/Bhq187xEZXV1dfT8lV7JlMuXz52l/4KSX/35F5v1B8boh84XvsflatdbhdDJfTx/PqWeTH7zBI9p7PJj0ySv/ps3fm5tXvSB0PCY/HcmXD56MHikDefrwUnkwnQymVX9GlX8U0v@Oq/aaHCpbvsaj/vQv3/f/1JugptdPP/2V/Pzklz//8urmx5sXZAWW8L@Hr6fw1RtNH4xAlcfGo899smIsiGYPHy4dtopvx5a/fvj2o@9/emUuPWfhWNRjD/8Wmo73Irbev3bj6KXHaBiEFD57fbL2baQymeN70QwejEgUUMtZbEgQ@svQXJOF41LPXFNiRnAfRoyY4TJeg2BO7vnE8l0fDLbswYOX68APWc/hXyTaRPDsmW/TnrMgb8OYznoELnzmRcz0WMR/F17iZdAw9ENVkvInd2boFR74MQtiVnjkeIdPQLGlU@SDuscoau7lDznjh9hnVF1I24RktxUCdy/xk3iU2tQG0tQ0M5JRXl9fk70iVE16/uaNpD940uslFX4Rexa3Mv9t0wWYLdjIrpJXWsgirhMxWeNvDYUs/JAYWKirK2gntgkocKkqkhHqRpS4SSEoNPY@OYHMaMQMJChL1yRp/M53PFlzuGxnSN6h@IxFV4YZT3pp72po9b2iASgAKmrLwuamO3xPaVDWQKjIaylYZNdc39omuZ@Re22iYwnIORSWQOJMYmh6SypPhgDJ7KEirszSz1wzEla28I7DL1cCNTWgXR1mGHJE3cUQGsKme2rihS/G@Jyo/HWB3XKp6Rn4mAs4YO2L4JFJGEeB6zBZ6kuKNptd6kqBOrFJ2igtuFCDJWW15ScShaRc07IAn61oaKxMdyHs4Hg2vT8QZq3M0LSgjcAOXGJWsqJxer1A7k6h0S6BVpK17dVw/FAaSoq@u/5hNp9LBUpAci4b0X05K6EuomZordTDcmeiYDDLaKrXMBkIVxX00dzLMaeXs@KUIhO6UOuyuajZTNem8HGk7EvNnR4p26N3XLKwPY0M4MvcSEgbahnzMJd/gCLqOmtwBRG9MvrdNmfYFc1/t4KonrNhC6S6lG3hgFbp26RCGadSok4p1fQGGkwfZD8cbjz@r1xQYgU1veGs2Y86VtOL7jhCM8oDbXMzHNi/DQoTf@KSoL@TRWmDaaUfpy@F0iWXc30/MCAtqXe4atyd45MGXhjGUrZjHktqXDYDK2lAKwgcuJeDHPDVOI2AFdxDg@YFP3F00b1gE4gIj/HdnSoHzWV41hBCt63yzjHVRxnyn6lSyiELFAWf2gw5E0AIy@tkwN@UXgwOEcYLxY8qKQP@ovSclKQIpxPtATWFosto29fXsxKBnCVX9@A5PK5yJlQIRQmtq2RxtY8L403j8cQntXFFjFhwGs9nvGpwP0jAWKbdB9NeaEkCO4jP7cgVzWNH@f2gqur7sWQ/LNQVkEeYFgWIVjS9jaxVxk9ur8KbHPW6UrZGA3m16cDULQP3aQG8uYmKDdIQzJsbomj2GjH7obcirAvEDi71QpwFUitmNM3tqOtGKmSVcBuHEYwpxL0fONRWf/I9CGc4VDGBarsbkkWapvNfkWlRFUcmcGtZ/O4w2@M0hMzIzyv/jvxosdh0IeVcr03PjshzoYx9yGNZJON5FochjKbIM1S1QBhASggxVJ0U479ok6YuAiACRZQB0S89EckqjnlwfLXLBjSpUtx@MNDh3zvoHChGQkGkVPhFovIVBvCKvJo3EqTtTOX4Saj1qnCCdq2GdL/yaV1NRBPA8BRqwYuGWtRWgneJvhgPQy7Fa729uBDJuawtLrSts9Mv8u5KgEpXlIMEK6lEWltV@pc066L2g8vd69C3aISDbs@JVjDyvN0AuB0mADCXPswlqdp7E78xSi/B6xeZRh9qNOqT5x9i56MJTchm5Dak5vumUriNUu9KPStzqj2PatYGKtO9taU5E41ZZYmC@IuTpHstpd/USAcjxlSl8CWnqFLqYroTOXxKxKIyZ4P0kCn1MT3HjZgH2W05165e4/rBTlkmn36pgPRB15VPlRwn/WdiAIglHCo7sjIjcpyPV4sktRu2YMAZErLl8yScSWnFBeGaWKaHCcwthYYNqcXcDRHGHZMOFX3@5g2fuQBWqb53beejfhOwMIk@DVsR5vBN6BLAFbS1RCzczBqtUcaotQrTRmkGKrfEvUUDRv6D9M8RkG1La4fejgg@B8UnIVkwJRl1MvF1P51O4FLaciOq2SqOANpxBF0It8yMdKz0XgsQbEEFp4BJtWYdRaOzgEjAB5fTgIZGpzke23jKeJBJHabhooGgTgL4zXA7iv4WHkCOucAJbnCqK5zgDue6RNktopZ@ITj9BWad1iqZnNnyr10HAajoCV55vmd@Oe/8yh56ipce9dR2Hlvw3IE6be4pB@emYI3@jINK9KdUxA70qUuxhLu@hfzjiLf@P6dbeapl2riqxgfi7bK0czxmIeXtgukelAtJnuV7YCzKJ1T4spqMul1A61wohPn82QkJ4ODs9G/UBOp22V83WI/@gPUXgnUU3zI@Bf5tsB17URzgGBzLD2jIhWNlIrGkPFJnZC4hSucSwZdzCVptLp0A89HZMJ/Uz0SY0abXCrnq5Ngg3ZRq51MFlrTRVFfVye8M2QtcA08iwuQcjI5b8DpjIEsELCEw0gXrOjQO/GhyEmT43GfWUKOKhOCLzt4VsGPXYCfXZ/C19TkezI93BkkQf4kZ1ZEofoLeGi7I1ytf6bZjMwhwQXSiHHPf6Py@sGqW7chESDnOaBO9Br3CCnmNmutzVwcpNbWm3lCKumfyurqikwqyGcbShFHV9G8e4NrGNp6dQWgiSVt1CW4hxQpT@4SwFgcnBDWxHSkOzu4Nndre8GdnHbi0ZX@41fzQ5jtPRI@Pd2INN4iZnG94U/TdMdd7WddzerhV40Bc98CFmANRTSHrG/XJYuNfpwwTKtIxU8QlsCUNnU/dsRoxP6TENpnZBbDnJ5r70w2OBzV3bEgFGaSZbrJdgMkKuXPYityaESXTCWab3DadU8xb03a8U/OFCrdAJY4B3qp1wbcrP16uGKF1iWmyssx7I2hl3JmSl360k/t4esHOIin7O76szUP@65B@xFXcCVGvyQvTjWiHjm4rxO1@e0tJP/ls5XhLcgeOKZT8VYZXP5nrFPR8Q/RcEoXDCMqJeG9rU8jGqd0R4Z6PMDm73wjqVpjFIntdgopVObIaL6Tw9VwNyXWxAUskFEcQ/fqratXYr6SZEupaUL8xOf4H3XzLCY4U25bpuoDSLSq840hPwPWrQD0zQqJAxkraQhq0RZufGrjTMIRbDH87A6fn/AvVgvb4VtHvNYdyohLo0qlht3tteZz67/Q2XgLwmOnwXUDtORE1JfC0yIoK2426MCbjnHTypANrEhqAN7nbdU7@QyZqenYMXzRHSzJQyVnx0irQ1IwwDUO1tOks3RgKSinVhNnWnqRXMIzmUL8vsdkOL86xQ3Jm44yeY6EeVO2PDuPX6DDQ6CfPDIptaPOGOZPat8mWtXlT4lP3OgMKoA5PGskLZZxuQRU6tVxl3dOzC4fQvQNHWp8OLFkda6fVxDZblZ96m50TA7Ezz44iVEuyHa6MGW7A5PhDzs6TZZzKUKuf2UxPm92r6mTYguy7VmTk/rod2VWrQq/b6XbVioxvYa4kg5Spafowt7XGm0eXi8lSw8zp8d1hye7mbCPz3oG05N3va2/Yv73AdEKKa2m3oWm9p7i2NpeSXcdw31HeF9uzFcW3EcMTurxNF34M4f6EfVqej/VLN1GfuFOr0M273Rf@GmGVpgd7u@PLoBpMldG0dyaovmqX/uWAdDKIviCAuoGnHXD@25wf5jElO3FXG1EKco22cg8Oz1aXVYWzhnmPulMb3CM6nXmoO71Re@6h817@5Kz1KxP66/Roe3YSfA1P5b2uASqG50GiTTQ2w@VHhaiQvhfrKWpykf7nA@l/OnBxcH7w3mF7R134uUY/2BOtTXXcVAnpP4BVvYjZYvT0QhmH1LT3@HieZhh5ooaHe/j06JCf@OG36YFyB8@Loy4wLAKAGFg5Yx8nora9/wE) [RunR](https://tio.run/##jVhbd9pIEn5Gv6KMvUEYJMCOJxlsPJPNxOf4IcuecbL7YJxEoAZpLCRWLdmwDvvXs191t0Bc4sTOcUvVdfm6bl3K0JPBt29x4gtyLi4ujjp0YY@8rP7tW@ewERY/yX1Ag8PG5k@fBuMkzgbT3miadtqDaeflQMQ@nceNU2G9bLQP6X3S/5l//f57a5aGcWa/duyT4zPntN6wO62T@nGn3ejs@3X2/tbp8EBB@ydtg939cZ3Dzq9Hhy@sNiO9fP3f3@nm7NOrT@/7b/pXFMATyRGW11gsp3PsAMrLz6ffWi36EISS8M8j9ttfeI4zkc5Sgb80TlIKsmwmu62WkEnkxRPpJumk9Rjeh60/8/hPCyq8PAuStEsy82QS@ueUikh4UviUJTTLh1E4Ij@ZemFsWQ8etErqgec/eZgKuzaWtfq5ZYVjsmdpMhJSul46eXAjEU@ygC56dFKnJ6sySmIgEG6UTOzqR@lNRFdBpjSPUxfAL8ZhJC6rUFYpFIl5mNlw5bm1VJZHzN8DADcVnn8F/ptFPNqwe3ty16Rano2d1wrXLM9GAUR7NAqod0kFr8z8JM/cxzTMhD0KwNpqbfOCASRq8Ps5wVMPIpVhEiu/DtPkUYrUYg8WPoYHR/cJuMZR8uiOkmnLa/3y8uT07LTTsYpgxUL4kt5xmJqUx1F4LyhJw0kYe5GJnsvM/U0aQiBkXMtI5rNZkmZwXuyoLW@UhQ8CbADbJJGmSSoZOz0GItZuXRkf5zG4cYShCLwHgbyR9OG6X5M4DwI8zkf3TcQ2y9NYUpvA@K5/peD8I8kQMU0gdj@7fsVaHbSrrrXSPhHKk3adLIQ@EhkN8/FYsGv/rh5cL4qSkc2hrZhwqlC2m4azSXhU29qEIbtZcpOhOif2OsZLq3X8r93IdJ@Dg4BalXBsK6dRr0fVal1FXZ0EeyKSgtO2ooiK7bZ9h42KEdE0V6I6hD7HcoWVtS@PWyo3MnY7ss7PkXfkh3wKESOMSY7@lAVevB19ayjEDAYAdzNhEVqTsLXBK5XdfBR/OEFNcf7qJ07fda2pvIUfkumUraKiRewNI0HYg9GJZWXpgg/K3cDmAmuSqYNm4TfEBIiaxpLyONryKLBVrm1Ut6JoeqOmg2Ot4/DzNiylU1U7L66cRWgFtUHMOis4UiqmKDQapHAajdCtKBnjbRBrOReJ8M4DRDsKY9EMlSv50QQMTaXXqw3SGv2mDNyGdzBVYmg3uYV3qc322M2PoZ8FBZxUcDhtOxUyj7ImyykL770scKfevLxhOmG9ybo4GloT4EZJPBEyU2YtbWWWcHMdh7H/Gc0kzZS36vT1Kz3Nu1wSC/xdGkh@yAX15GOnA8@Vt1QnwubtnSFMSxQGMfVQRnPNpznifIrtttod5alKUtCG6HEVlceCc3GSelO6Of3QJ3VJShqcNtFoQpSJzCd8HMlJnVG10PHgRbmo8h0VJ5lSI72p4MZT3TRT1TjAzy7wUIAbWJQeq4J@UaTTtpusChcstwCbFS2KaJmryKHOOYiX6pALxwG/ElBW54b5dnHnRp7MrmNfzPtju3ajMg5ljwtuTgc94rwwdf40by7Y41z6SPRKueHYCKVBhD5zwK@uNk4vXpB@uyjjq6/UxnkUnZfl5htyc8ipHNqVKPoPH0SZuFPL/A7Ae2gDvoDPcLH/to@lSzWqnW@dZJbMbJUk5izrTFFUl/frBqyil@3UEW40Y/pyo5KP6epqJOTH0VPhpCXZR08Kw7KpHxbL@pfScaBXt9cSrlEUztjg2sVs/QI1VvikXUJ1SSdnZ6sdPO/RXlLu@Q9ejPpeh1D7HZMAas715@eGtFiRFts60MU4N9GsS1lgupsBwlo0xf7yA3cwyt7RE/4u4fj73u3Rk/L/8o4rW71PCwIKBaz4u/xSN6hQoBHfUiaGa2jnJqTqlisQMFE@htzhMRkVVaKaLMqhu36h8sv/al0u12v4w@c5BdWORkpevCBfRN6CGzVX/9Zt18RNSGGm@0MyowDXo8taK0NMBfe45FYWrmCh5DpN5dTvFlQGkPKNihlMGRP@RN0MkzT0S5quoUlnscqj1Xzg8vIWpfEms9t1tGuDYSXYh6C5umw9iLjjNJm@NWIqI9dia7lPtW5RMLkMFNuu8ocVqnXV7XK92cTOj42SwB6Jj7sSzvMS73cljp@X@EOnAt8UfyCyMktXA@tjkt4/F/xHQTyL8mwyyTHq8NwK3pQJuRSKdYJXP3wI1ZCHBo/kcgt7VwiAvldmYtSl6r957OX3zeuFJsCDKYP7T5t1eEOeINAMmpx/MpzOogWClMwk9ydWEISTQN87brWwpsbozatO64dUugIrV@j03KzceB2jK4bZos4DJ@wqlpKb1fSA/ogJiqmtssf1JbRdE7V2ravWjllPzHpq1pdmPTPrL2Z9ZdbXZv3VhE@jaajxeF8J/g2JoS/oA@6bpTTAUT8P8wkHWscBDlTBk/g8wCdKjol/oXMhUU23qeYBPLM@Wwq4W@CjgFkiv742ebRRFdPvlcULsE2/V2JrtoP1AbDsqvmw2s/SXDx7wCv13R3xt8uCE9VXXx8cYhlogXXb2hhqdkDZ4NgZ5jDLGU7uas4laSe99TKXP5lLHqpviDv7xC8cy5zBnzcBF@rUgyGyybaywXOvITolIhVE9cxEtbsmOopIBVEDa22ey9E3pR5V9ct8ueXiH8KjffCcHXi0D56zCW8w2MRXhreNbi31tVbsQs6cYjePnIJrseJa7FHW4Cut@Nlx1bzsqsVy18ohxHmuQHrVf158Lf@7llfi5aFng3UnKkRqcIrEOHsuf3bd/sOk2sqfi@/H56fSxwDFnRNkz6XS3qR2nj3TFtLLZzL9@6l0DCn@7LU3HY7p2cPXY7eYnq9jBCj09bWamxH15yZoDM2VjcCaOVprrn2MYRXDDP@HAH8R1PiD/f8) [><>](https://tio.run/##jY69CsIwFEb3PMWVFGkborn9wYoouriVCF1DHbSlRZpI7eTLxyg4qB083wdnPXV7a6xFyto35tKAouwTCao2elDd@tT1KFSHiar0GVaaxRVJmKCQG/nPpczJtW/14Gfcj8KUxwHzcR4FIQqGY@OjC4BOXmkH@I79ZcYpLj06JeJZusnuWyjSclHmcif30HgIxnPKnAjHkLuU5Bhb@wA) [xEec](https://tio.run/##jY69CsIwFEb3PMWVFGkborn9wYoouriVCF1DHWqkRZpI6SC@fKyCg9rB831w1nPTunIOKWve2EsNirJPJKizNb1q11XboVAtJkqbE6wMizVJmKCQW/nPpczJtWtM72fcj8KUxwHzcR4FIQqGY@OjC4BOXmkH@I79ZcYpLj06JeJZusnuWyjSclHmcif3UHsI1huUDSIcQz6kJMfYuQc) ]
[Question] [ ### Note this is a question primarily focusing on [data-structures](/questions/tagged/data-structures "show questions tagged 'data-structures'") ## Introduction Bacefook wants people to be friendlier! As such, they are implementing a new system to suggest friends! Your task is to help Bacefook to implement their new suggesting system. ### Specifications: Your program must be a REPL (read-eval-print loop) supporting 3 types of command: `FRIEND`, `SUGGEST` and `KNOW`. `FRIEND X Y` - Specifies that `X` and `Y` are friends in the social network. * If X is friends with Y, then Y is friends with X * Can, but doesn't have to have output * X is always friends with X `KNOW X Y` - Output a truthy value if X and Y are friends, falsy otherwise * `KNOW X X` will always output a truthy value `SUGGEST X Y` - Output a truthy value if X and Y should be friends, falsy otherwise. X and Y should be friends if: * X and Y are not friends * X and Y have at least 1 friend in common You are allowed to replace `FRIEND`, `SUGGEST` and `KNOW` with your own strings, but you must mention what string you have replaced each command with. Your program can take in input/produce output in any way desirable, as long as it is reasonably easy to recognize how it works. The number of people in the social network `N` is between 1 and 100,000, but there may be any number of "friend links" (edges). > > If you haven't noticed yet, this is a graph searching problem. The (likely) easiest (and possibly fastest) data structure to implement this in would be an adjacency matrix. > > > ### Test cases ``` FRIEND A B FRIEND A C FRIEND B D SUGGEST A B -> Falsy, as they are friends SUGGEST A D -> Truthy, as they share B as a common friend SUGGEST C D -> Falsy, they do not share a common friend KNOW D B -> Truthy, they are friends KNOW B C -> Falsy, not friends ============= FRIEND Tom Tim KNOW Tom Tim -> Truthy KNOW Tim Tom -> Truthy KNOW Tom Kit -> Falsy ============= KNOW Tim Kit -> Falsy FRIEND Tim Tom KNOW Tim Kit -> Falsy FRIEND Tom Kit SUGGEST Tim Kit -> Truthy ============= FRIEND X Y SUGGEST X Y -> Falsy since X is friends with X ``` [Here's some more test cases in image form](http://prntscr.com/epqrpe) ### Win condition This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins! [Answer] # SWI-Prolog, 62 47 41 bytes ``` X*Y:-X+Y;Y+X;X==Y. X?Y:-not(X*Y),X*Z,Y*Z. ``` Prolog isn't too often useful, but when it is it's just beautiful. We'll use `a+b` to notate that `a` is friends with `b`, `a*b` that `a` knows `b` and `a?b` that `b` should be suggested to `a` or not. The first line simply says that `X*Y` is true if either `X+Y`, `Y+X` or `X == Y` is true. This implements the symmetry of knowing eachother. Asking if there should be a suggestion is incredibly simple. We just ask if there is a `Z` such that `X*Y` is false and `X*Z` and `Y*Z` is true. Exactly as described in the challenge. If you save this as a file (e.g. `friends.pl`) and open SWI-Prolog with this file (`prolog -l friends.pl`) you get dropped into a REPL. You can assert friendships like this: ``` assert('a' + 'b'). assert('a' + 'c'). assert('b' + 'd'). ``` You can check if people know eachother or suggestion should be made: ``` 'a'*'b'. 'a'?'d'. ``` [Answer] # PHP, ~~138 133~~ 129 bytes PHP beats Mathematica - a rare occurence. ``` for(;$s=fgets(STDIN);$s>G?print$$a[$b]?$s<L:$s>L&&@array_intersect_key($$a,$$b):$$a[$b]=$$b[$a]=1)[,$a,$b]=explode(" ",trim($s)); ``` prints `1` for truthy, empty string for falsy. Run with `-nr` or [test it online](http://sandbox.onlinephpfunctions.com/code/8df62923b5dcce0b442117e6b89c2013aa50cfb2). needs PHP 7.1 for the list assignment; user names are case sensitive and should exclude `a`, `b`, `s`. **breakdown** ``` for(;$s=fgets(STDIN); # loop through input $s>G # 2. evaluate command ?print$$a[$b] # command KNOW: true if $$a[$b] ?$s<L # command SUGGEST: true if !$$a[$b] and array_intersect_key returns truthy :$s>L&&@array_intersect_key($$a,$$b) # command FRIEND: set keys in $$a and $$b :$$a[$b]=$$b[$a]=1 ) [,$a,$b]=explode(" ",trim($s)); # 1. parse user names to $a and $b ``` * `$s` has to be trimmed because it includes the newline character. * [`array_intersect_key`](http://php.net/array_intersect_key) has to be muted or it would yield warnings for empty `$$a` or `$$b`. * ~~+18~~ +15 bytes for all user names: Replace `$$a` with `$f[$a]` and `$$b` with `$f[$b]`. [Answer] ## CMD (Batch), 50 + 20 + 135 = 205 bytes * FRIEND.CMD ``` @for %%f in (%1.%1 %1.%2 %2.%2 %2.%1)do @set %%f=1 ``` * KNOW.CMD ``` @call echo(%%%1.%2%% ``` Prints `1` for friends, a blank line for strangers. * SUGGEST.CMD ``` @call set k=0%%%1.%2%% @set k=1&if %k%==0 for /f "tokens=2 delims=.=" %%f in ('set %1.')do @call set k=%%k%%%%%%f.%2%% @echo(%k:~1,1% ``` Prints `1` or a blank line. I think six consecutive `%`s might be a new personal best. [Answer] # Python 3, 122 118+2=120 bytes ``` l={} def f(*r):l[r]=l[r[::-1]]=1 k=lambda a,b:a==b or(a,b)in l s=lambda a,b:1-k(a,b)and any(k(a,z)&k(b,z)for z,_ in l) ``` Usage is exactly the same as ovs's answer. [Answer] # Python 3, ~~163~~ ~~149~~ 143+2=145 bytes -6 bytes thanks to @FelipeNardiBatista ``` l=[] def f(a,b):l.extend([(a,b),(b,a)]) k=lambda a,b:a==b or(a,b)in l s=lambda a,b:k(a,b)-1and{c for c,d in l if d==a}&{c for c,d in l if d==b} ``` Save it to a file and run it as `python3 -i file.py` Use - `f("a", "b")` instead of `FRIENDS a b` - `k("a", "b")` instead of `KNOW a b` - `s("a", "b")` instead of `SUGGEST a b` Falsey output : 0, set(), False Truthy output : non-empty set, True [Try it online](https://repl.it/Gjz0/8) --- 164 bytes when not using python interpreter as REPL: ``` f=[] while 1:c,a,b=input().split();i=(a,b)in f;f+=c=="f"and[(a,b),(b,a)]or[(i+(a==b),-i+1and{c for c,d in f if d==a}&{c for c,d in f if d==b})];print(f[-1][c=="s"]) ``` Uses - `f` for `FRIEND` - `s` for `SUGGEST` - anything else for `KNOW` [Try it online](https://repl.it/GjtK/4) [Answer] # Mathematica, 164 bytes ``` f={} p:=Union@@f i=Position[p,#][[1,1]]& m:=Outer[Boole@MemberQ[f,{##}]&,p,p] a=(#[[i@#2,i@#3]]/._@__->0)>0& F=(f=#~Tuples~2~Join~f;)& K=m~a~##& S=a[m.m,##]&&!K@##& ``` Defines three main functions `F`, `S`, and `K` with the desired behavior. For example, the sequence of commands ``` F@{David, Bob} F@{Bob, Alex} F@{Alex, Kitty} F@{Daniel, David} F@{David, Kit} S[David, Alex] S[Bob, Kitty] S[David, Kitty] S[David, Bob] K[David, Bob] F@{Kit, Kitty} S[David, Kitty] ``` is the last test case from the image linked in the OP; the `F` commands yield no output (the single semicolon seems a small price to pay for this), while the six `S` and `K` commands yield ``` True True False False True True ``` as desired. At any moment, `f` is the list of ordered pairs of the form `{A, B}` where `A` knows `B`, while `p` is the list of people appearing in some element of `f`. Calling `F@{A, B}` adds the four ordered pairs `{A, B}`, `{B, A}`, `{A, A}`, and `{B, B}` to `f`. Also, at any moment, `m` is the adjacency matrix of the underlying graph (a person is adjacent to themselves and to all their `F`riends); the rows and columns are indexed by `p`, and `i` converts a person to the corresponding row/column number. The helper function `a` takes a matrix and two people as inputs and looks up the entry of the matrix whose "coordinates" are the two people, returning `True` if the number is positive and `False` if it's zero. (It's also possible to call `a` when one of the input people isn't yet recognized—for example, making a KNOW or SUGGEST query before any FRIEND declarations, or asking about some poor person who has no friends; this throws errors, but the rule `/._@__->0` forces the output to be `False` anyway.) Calling `K[A, B]` therefore looks up whether `m[A, B]` is positive, which implements the `K`now verb. The matrix product `m.m` is the length-2-path matrix, containing the number of ways to go from one person to another along a path of length 2; this allows `S[A, B]` to implement the `S`uggest verb, as long as we additionally check by hand (`&&!K@##`) that the input people don't already know each other. Fun fact: for free, this implementation allows us to declare cliques of friends—the command `F@{A, B, C, D}` is equivalent to all of `F@{A, B}`, `F@{A, C}`, `F@{A, D}`, `F@{B, C}`, `F@{B, D}`, and `F@{C, D}` combined. [Answer] # [Python 2](https://docs.python.org/2/), 118 bytes ``` F=[] def s(f,c):c=set(c);r=c in F;return F.append(c)if f%2 else not r^(4 in[len(x|c)for x in F])if f else 2>len(c)or r ``` [Try it online!](https://tio.run/nexus/python2#hcxBC4IwGMbxu5/ivYQbSJR0MgxSCcJDH0AsZL2jgcyxrfLQd7elxerUbT@e/7thl1Z1cEYOhvCI0YSlBi1hdK1TBkLCbq3RXrV7zBulUJ7dJjjwWQzYGgTZWdBHsnJt1aIk/YNR3mnox@N6bKcy3rx2Rt2oh/tFtEiWNAlAaSEt4K1piW7uJyHV1RJKB0OWURVuwyjMwpoGnrln5lhMjH/jD7/W3HPhWPj4w6@fD457v/5n6Vm@@QQ "Python 2 – TIO Nexus") Since I couldnt find repl online tool for python 2, I've added the TIO Nexus(in REPL format). **Query for option and its possible output** 0 for Known - None 1 for Friends - True or False 2 for Suggest - True or False **Example of usage and sample output in an repl python interpreter.** ``` >>> F=[] >>> def s(f,c):c=set(c);r=c in F;return F.append(c)if f%2 else not r^(4 in[len(x|c)for x in F])if f else 2>len(c)or r ... >>> s(1,['A','B']) >>> s(1,['A','C']) >>> s(1,['B','D']) >>> s(2,['A','B']) False >>> s(2,['A','D']) True >>> s(2,['C','D']) False >>> s(0,['D','B']) True >>> s(0,['D','C']) False ``` [Answer] ## [GNU sed](https://www.gnu.org/software/sed/), 158 + 2(rn flags) = 160 bytes Since sed is a regex based language, there are no primitive types, not to mention abstract data structures. The network data is stored as free format text, in this case as redundant friend links like `A-B;B-A;`etc., which is then matched against various regex patterns. ``` G /^F/{s:. (.+) (.+)\n:\1-\1;\1-\2;\2-\1;\2-\2;:;h} /^K |^S /{s:(.) (.+) (.+)\n.*\2-\3.*:\1:;/^K$/p} /^S /s:(.) (.+) (.+)\n.*(.+)-(\2.*\4-\3|\3.*\4-\2).*:\1:p ``` **[Try it online!](https://tio.run/nexus/sed#bYyxDoMgFEV3voKhA9gAkXaCXQdGHYlzGQRS3bS/XnwP06RNutx3cnPPKz1RU6e2xUjK5JXX8NH4VvjWYmrrdWWNbOzjBYaj@zRQ1Jjk36JscHeTDXwwFoYXlVGA8Z8tXsG8BusO1o4ikubng1yKo2OYqQsr6SqNaSY/XTpp@HTvlNeQ4lLEMx4)** By design, sed runs the whole script for each input line. I recommend testing in interactive mode, to see the output of a command immediately after typing. **Usage:** there are no truthy / falsy values in sed, so the output convention I use is borrowed from bash, whereby a non-empty string is considered as truthy, and an empty string as falsy. * `F X Y` for `FRIEND X Y`. It has no output. * `K X Y` for `KNOW X Y`. Outputs 'K' as truthy, and nothing as falsy. * `S X Y` for `SUGGEST X Y`. Outputs 'S' as truthy, and nothing as falsy. **Explanation:** ``` G # append stored network data, if any, to the current input line /^F/{ # if command is 'F' (FRIEND), for ex. 'F X Y' s:. (.+) (.+)\n:\1-\1;\1-\2;\2-\1;\2-\2;: # generate friend links, for ex. 'X-X;X-Y;Y-X;Y-Y' h # store updated network data } /^K |^S /{ # if command is either 'K' (KNOW) or 'S' (SUGGEST), for ex. 'K X Y' s:(.) (.+) (.+)\n.*\2-\3.*:\1: # search friend link 'X-Y'. If found, delete pattern except the command letter. /^K$/p # if only letter K left, print it (command is 'K', 'X' and 'Y' are friends) } /^S / # if command is 'S', for ex. 'S X Y', but 'X' and 'Y' aren't friends s:(.) (.+) (.+)\n.*(.+)-(\2.*\4-\3|\3.*\4-\2).*:\1:p # search if 'X' and 'Y' have a friend in common (for ex. 'C'), and if so print #letter S. The search is for ex. 'C-X.*C-Y' and 'C-Y.*C-X'. ``` ]
[Question] [ In math, one way to figure out what the type of a given relation (linear, quadratic, etc) is to calculate the differences. To do so you take a list of y values for which the gap between the correspondent x values is the same, and subtract each one from the number above it, creating a list of numbers one shorter then the previous list. If the resultant list is completely composed of identical numbers, then the relation has a difference of 1 (it is linear). If they are not identical, then you repeat the process on the new list. If they are now identical, the relation has a difference of 2 (it is quadratic). If they are not identical, you simply continue this process until they are. For example, if you have the list of y values `[1,6,15,28,45,66]` for incrementally increasing x values: ``` First Differences: 1 6 1-6 =-5 15 6-15 =-9 28 15-28=-13 45 28-45=-17 66 45-66=-21 Second differences: -5 -9 -5+9 =4 -13 -9+13 =4 -17 -13+17=4 -21 -17+21=4 As these results are identical, this relation has a difference of 2 ``` ## Your Task Write a program or function that, when given an array of integers as input, returns the difference of the relation described by the array, as explained above. ## Input An array of integers, which may be of any length>1. ## Output An integer representing the difference of the relation described by the input. ## Test Cases ``` Input => Output [1,2,3,4,5,6,7,8,9,10] => 1 [1,4,9,16,25,36] => 2 [1,2,1] => 2 (when there is only one value left, all values are automatically identical, so the largest difference an array can have is equal to the length of the array-1) "Hello World" => undefined behavior (invalid input) [1,1,1,1,1,1,1,1,1] => 0 (all elements are already identical) [1, 3, 9, 26, 66, 150, 313, 610] => 6 ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score in bytes in each language wins for that language. Lowest score overall gets the green checkmark. [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes Thanks [Leo](https://codegolf.stackexchange.com/users/62393/leo) for letting me use his version that works for `[1,1,1,1,1,1]` ``` ←VE¡Ẋ- ``` [Try it online!](https://tio.run/##yygtzv7//1HbhDDXQwsf7urS/f//f7ShjomOpY6hmY6RqY6xWSwA "Husk – Try It Online") ### Explanation ``` ¡ Repeatedly apply function, collecting results in a list Ẋ- Differences VE Get the index of the first place in the list where all the elements are equal ← Decrement ``` [Answer] # JavaScript (ES6), 47 bytes ``` f=a=>-a.every(x=>i=!x)||1+f(a.map(n=>n-a[++i])) ``` ### Test cases ``` f=a=>-a.every(x=>i=!x)||1+f(a.map(n=>n-a[++i])) console.log(f([1,2,3,4,5,6,7,8,9,10])) // 1 console.log(f([1,4,9,16,25,36])) // 2 console.log(f([1,2,1])) // 2 console.log(f([1,1,1,1,1,1,1,1,1])) // 0 console.log(f([1,3,9,26,66,150,313,610])) // 6 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` `dta}x@q ``` [Try it online!](https://tio.run/##y00syfn/PyGlJLG2wqHw//9oQx0THUsdQzMdI1MdY7NYAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8D8hpSSxtsKh8H@sS8j/aEMdIx1jHRMdUx0zHXMdCx1LHUODWC6gsAmIaaZjZKpjbAYWMNIxBNNoECymYKyjYKmjYGSmo2AGxIamBkAhQ6CgGdA0AA). ### Explanation This compuntes consecutive differences iteratively until the result is all zeros or empty. The output is the required number of iterations minus 1. ``` ` % Do... while d % Consecutive diffferences. Takes input (implicitly) the first time t % Duplicate a % True if any element is nonzero. This is the loop condition } % Finally (execute before exiting the loop) x % Delete. This removes the array of all zeros @ % Push iteration index q % Subtract 1. Implicitly display % End (implicit). Proceed with next iteration if top of the stack is true ``` [Answer] # [R](https://www.r-project.org/), ~~50~~ 44 bytes ``` function(l){while(any(l<-diff(l)))F=F+1 F*1} ``` [Try it online!](https://tio.run/##K/qfZqP7P600L7kkMz9PI0ezujwjMydVIzGvUiPHRjclMy0NKKip6Wbrpm3I5Vb7P00jWcNQx9BMx8hCx8RUx8xMU/M/AA "R – Try It Online") Takes a `diff` of `l`, sets it to `l`, and checks if the result contains any nonzero values. If it does, increment `F` (initialized as `FALSE` implicitly), and returns `F*1` to convert `FALSE` to `0` in the event that all of `l` is identical already. [Answer] # Mathematica, 49 bytes ``` (s=#;t=0;While[!SameQ@@s,s=Differences@s;t++];t)& ``` *thanx @alephalpa for -6 bytes and @hftf -1 byte* and here is another approach from @hftf # Mathematica, 49 bytes ``` Length@NestWhileList[Differences,#,!SameQ@@#&]-1& ``` [Answer] # [Perl 6](https://perl6.org), 37 bytes ``` {($_,{@(.[] Z- .[1..*])}...*.none)-2} ``` [Try it online!](https://tio.run/##dY5BCsIwEEX3nmLALhL5DZ2kGSul4jksRVzUlVbRlZSePaabEkSZxcD8N5/36J9XCbc3ZRdqwqiyE8aDMm1Hx5xMy8ZsOj2ZuMxwH3qd2ynUq9d5flCKIWAPW6H0ENG6pjU1e7IJYeFQIsbYosIOXCwYJ1g5RwLr4f718M/71yxMkTAulluJhtG2gGMHSTQkfAA "Perl 6 – Try It Online") **Explanation:** The function takes the input as one list. It then builds a recursive sequence like this: the first element is the original list (`$_`), the next elements are returned by `{@(@$_ Z- .[1..*])}` being called on the previous element, and that is iterated until the condition `*.none` is true, which happens only when the list is either empty or contains only zeroes (or, technically, other falsey values). We then grab the list and subtract 2 from it, which forces it first to the numerical context (and lists in numerical context are equal to the number of their elements) and, at the end, returns 2 less than the number of elements in the list. The weird block `{@(@$_ Z- .[1..*])}` just takes the given list (`.[]` — so called *Zen slice* — indexing with empty brackets yields the whole list), zips it using the minus operator (`Z-`) with the same list without the first element (`.[1..*]`) and forces it to a list (`@(...)` — we need that because zip returns only a Seq, which is basically an one-way list that can be iterated only once. Which is something we don't like.) And that's it. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` -Iß$E?‘ ``` [Try it online!](https://tio.run/##y0rNyan8/1/X8/B8FVf7Rw0z/v//H22oo2Cso2Cpo2BkpqNgBsSGpgZAIUOgoJmhQSwA "Jelly – Try It Online") ## Explanation ``` -Iß$E?‘ Input: array A ? If E All elements are equal Then - Constant -1 Else $ Monadic chain I Increments ß Recurse ‘ Increment ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~10~~ 7 bytes ``` è@=ä-)d ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=6EA95C0pZA==&input=WzEsIDMsIDksIDI2LCA2NiwgMTUwLCAzMTMsIDYxMF0=) Relies on the fact that the result is guaranteed to be within the length of the input array. ## Explanation ``` è@=ä-)d Implcit input of array U @ For each value in U... =ä-) Update U to be equal to its subsections, each reduced by subtraction d Check if any values in that are truthy è Count how many items in that mapping are true ``` By the end, this will map the array `[1, 3, 9, 26, 66, 150, 313, 610]` to `[true, true, true, true, true, true, false, false]`, which contains `6` `true`s. ## Previous 10 byte version ``` @=ä-)e¥0}a ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=QD3kLSllpTB9YQ==&input=WzEsIDMsIDksIDI2LCA2NiwgMTUwLCAzMTMsIDYxMF0=) [Answer] # Java 8, ~~191 + 58 = 249~~ ~~198~~ 140 bytes. Thanks PunPun1000 for 51 bytes. Thanks Nevay for 58 bytes. ``` int f(int[]a){int x=a.length-1,b[]=new int[x];for(;x-->0;)b[x]=a[x+1]-a[x];return java.util.Arrays.stream(a).distinct().count()<2?0:1+f(b);} ``` [Try it Online!](https://tio.run/##jY/PboMwDMbP61PkmKgmItBmf1g37QF26hFxMBS6MAhVEjoqxLN3QVsvPSFLtmx/n/xzjWcMulOp68P39dTnjSpI0aC15BOVHlfWoVPFVWlHKupzmiEb527YIW9KfXRfgYA8zXa6/CGzYMiSqjM0GYLgLUxY7gc7TIe1yAKcl6Z0vdGk9od571TDP4zBi@XWmRJbiowflHVKF44yXnS99vU1eg9fxLqiOUumG@YfGjl36kBaD0v3zih9TDOC5mjZuHrYX6wrW971jp/8yjWaVvTGmZFRQAQxbGALEh7hCZ5BhBNjyRLnZlZLiLYQy6WeCMRS6V0stcWeKpIgJYhtCLGIQf6/NE3XXw) [Try it Online (198 byte version)](https://tio.run/##jY8xb4MwEIXn5ld4tMXFwpC4rVwPHTt0yhgxGGJSE2IibFIixG9PTZqoUidk6fmke9/pvUqd1bI5aVvtDtdTl9emQEWtnEOfythh4bzyprga61GJg24zRYYqQLTzpqbOt1od6Yf1m9uEDvJv@d626uLuHqyImK5UUtFa273/WjJxO5hLq7/RNFaZMCU@0J1x3tjCY0KLprPhl5KRVvuutSgWunYalU075UG9jEX/Vok@iki@7TOpgiyDRCwTd4RFJc6JGB8Ff0uhc2N26Bhq4hDe2P02Q6rdOzIsnjYX5/WRNp2np7DytcUlfsTM0MAggRRWsAYOz/ACr8DikRAxh1xNbg7JGlI@l0mAzbX@e3OxNKRKOHAObB1DylLg90rjeP0B) So, this is my first time posting here in PPCG (and the first time ever doing a code golf challenge). Any constructive criticism is welcome and appreciated. I tried to follow the guidelines for posting, if anything's not right feel free to point it out. Beautified version: ``` int f(int[] a) { int x = a.length - 1, b[] = new int[x]; for (; x-- > 0;) { b[x] = a[x + 1] - a[x]; } return java.util.Arrays.stream(a).distinct().count() < 2 ? 0 : 1 + f(b); } ``` [Answer] # Haskell, 46 bytes ``` g l|all(==l!!0)l=0|0<1=1+g(zipWith(-)l$tail l) ``` this simply recurses - `zipWith(-)l$last l` is the difference list of `l`. and `g` is the function that answers the question. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~98~~ 94 bytes ``` a->{int o=0,i,z=1;for(;z!=0;o++)for(i=a.length-1,z=0;i>o;a[i]-=a[--i])z|=a[o]^a[i];return~-o;} ``` [Try it online!](https://tio.run/##rZAxT8MwEIX3/opjS1TbjVMIIJNKLEgMTGWLgmTatLi4dpQ4RW0Jfz2cS6iQYKo4efCd7c/vvZXcSGrLwqzmr13ZPGs1g5mWdQ0PUhnYDwaAVTvp8GChjNSwwiescUqzRWNmTlnDHu29cXd9d6OMy/IJGEg7SSd7bMGmEVFkl3KxsFUgdmdpJOxwGPpOpZLpwizdC@V4JRJqYoXMVE5TmVGq8nD3jjubP/mhqArXVOaDWtF2Xpv4kthr75VurJrDGh0EU1cps8xykNWyDtEQ9DXd1q5YM9s4VuIVp01gmCxLvb2t0U1gijc4OIE9JxATGBM4J3BBICFwSeCKwDUBHrVhKDxvNAJ@IhyBHLkxIs89P/lmHgvh8enK@S/ef8H/Xj@/Q3h0Inx8SDhOfCI@oQhHHIfJMXSEJwd4O2i7Tw "Java (OpenJDK 8) – Try It Online") [Answer] # [Kotlin](https://kotlinlang.org), 77 bytes first post, tried to edit last answer on kotlin 2 times ;D ``` {var z=it;while(z.any{it!=z[0]})z=z.zip(z.drop(1),{a,b->a-b});it.size-z.size} ``` took testing part from @jrtapsell [TryItOnline](https://tio.run/##hVHBauMwEL3nK6ZhDxJMTJw03jatA4VmoVDYw/a27EFN5FZUkY006RIbf3t2JLdh2UN2jJH85r2Z8Zu3mqxxx3flwS3Fowl0@@BoJScrPqA8djHTloZufr8aq0WbKXfoDF2U7c/pr162ZZu1pmF86@tG5BI7hc@TlZo89/LGUBZMqydtOvrjVpGCjVUhwJMOdM@fIjYwrtnTEk7tESJa7ynBjMjRqNo72CnjhPIvYQl33qvD7Q/yxr2sJHQj4HhXFgzpXYASLBf7XomExzg1/EjkOMM5XuICC/yKV3iN@VQi8B@ckVxGWoGzBc4LJs/OkmeY/5fzz8P86Vk@zBGuuWiBUPCbL6YM5QwWafpCJi3b9WlHpYyNdiRbsp1qoOM7UA1O8HqS8xL6rDKWtE9JvvtA2WA/XERtFvSmdlvoh8KmApEKZyasdw0dhPxcQYyGl0LWiXGcHxpet96Oh8l60Dbov7hDmar2a7V5he4k/Xb38Li@X8IXQ2PZD9pRf/wD) [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~22~~ 17 bytes ``` {1=≢∪⍵:0⋄1+∇2-/⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/2tD2UeeiRx2rHvVutTJ41N1iqP2oo91IVx/Ir/3v9qhtAl4VXI/6pgLVuCk86t1saPAfAA "APL (Dyalog Classic) – Try It Online") Thanks to @ngn for -5 bytes! ## How? * `{ ... }`, the function * `1=≢∪⍵:0`, if every element is equal in the argument, return `0` * `1+∇2-/⍵`, otherwise, return 1 + `n` of the differences (which is `n-1`, thus adding one to it gives `n`) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` IÐĿEÐḟL ``` [Try it online!](https://tio.run/##y0rNyan8/9/z8IQj@10PT3i4Y77P////ow11LHSMzHXMTHQMjUxjAQ "Jelly – Try It Online") # Explanation ``` IÐĿEÐḟL Main link ÐĿ While results are unique (which is never so it stops at []) I Take the increments, collecting intermediate values # this computes all n-th differences Ðḟ Filter out E Lists that have all values equal (the first n-th difference list that is all equal will be removed and all difference lists after will be all 0s) L Take the length (this is the number of iterations required before the differences become equal) ``` -1 byte thanks to Jonathan Allan [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` [DË#¥]N ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/2uVwt/KhpbF@QKahjoKxjoKljoKRmY6CGRAbmhoAhQyBgmaGBrEA "05AB1E – Try It Online") **Explanation** ``` [ # start loop D # duplicate current list Ë # are all elements equal? # # if so, break ¥ # calculate delta's ] # end loop N # push iteration counter ``` [Answer] ## JavaScript (ES6), 58 bytes ``` f=a=>+(b=a.slice(1).map((e,i)=>e-a[i])).some(e=>e)&&1+f(b) ``` [Answer] # [Python 2](https://docs.python.org/2/), 65 bytes *-7 bytes thanks to Jonathan Allan.* ``` f=lambda l,c=1:any(l)and f([j-i for i,j in zip(l,l[1:])],c-1)or-c ``` [Try it online!](https://tio.run/##FcpBCsMgEEDRq8xSYYRMSoUGcpLgwhqkE6ajSDbJ5a1d/M3j1@v8FJ17z6vE73uPIJhWWqJeRmzUHbLZDseQSwPGA1jh5moEZaMl2IDJkS3NpV4b6/nfCeGB8EKYPYIf0XMaRAM9TcH2Hw "Python 2 – Try It Online") [Answer] # Dyalog APL, 19 bytes ``` ≢-1+(≢2-/⍣{1=≢∪⍵}⊢) ``` Explanation: ``` ≢ length of input -1+( ) minus 1+ ≢ length of 2-/ differences between elements ⍣ while {1=≢∪⍵} there is more than 1 unique element ⊢ starting with the input ``` [Answer] # [k](https://en.wikipedia.org/wiki/K_(programming_language)), 21 bytes ``` #1_(~&/1_=':)(1_-':)\ ``` This works in k, but not in oK, because oK's while loop runs before checking the condition (as opposed to first checking the condition, and then running the code). Therefore, in oK, the `1 1 1 1 1` example will not work properly. [Try oK online!](https://tio.run/##LYlLCoAwEEOvMiBohYhNa8dP8SZCd9248AZevc5CQj683NNzt1aPjsW9/cxyDsfoWCarq9XBEQERCxIUKzbsoM80YEMREqJmShBa/rJbImSHBIWomckbokGlH9sH "K (oK) – Try It Online") [![Running the k example with 1 1 1 1 1 1 in the k interpreter.](https://i.stack.imgur.com/phCLe.png)](https://i.stack.imgur.com/phCLe.png) Explanation: ``` ( ) \ /while( ~&/ / not(min( 1_=': / check equality of all pairs))) { (1_-':) / generate difference list / append to output } #1_ /(length of output) - 1 ``` [Answer] # [Haskell](https://www.haskell.org/), ~~66~~ ~~61~~ 60 bytes ``` z=(=<<tail).zipWith f=length.takeWhile(or.z(/=)).iterate(z(-)) ``` [Try it online!](https://tio.run/##ZY/LCoMwEEXX9SsG6SKBMTU@0gpm3z9wUVwETGswVbFZ5edt2k0h5TKbM2cY7qhek7Z2370ksm2dMpYyb9bOuDG5S6vnhxuZU5PuRmM1WTbmyUlSyozTm3KaeJJRuj@VmUHCsEByWDczOzjCHW4cCyyxwhoFnvGCDfK8j4zqQwUWNZai/7vmMYoSr6FEaBAKgSDC8DoPiAcovp@zDH56eg3VF@iWzQ7p/gY "Haskell – Try It Online") *Saved 5 bytes thanks to Christian Sievers* *Saved 1 byte thanks to proud-haskeller* `iterate(z(-))` computes the differences lists. `or.z(/=)` tests if there are non equal elements in those lists. `length.takeWhile` counts the differences lists with non equal elements. [Answer] # [Japt](https://github.com/ETHproductions/japt/), 7 bytes Same approach (but independently derived) as [Justin](https://codegolf.stackexchange.com/a/142473/58974) with a different implementation. ``` £=äaÃèx ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=oz3kYcPoeA==&input=WzEsNiwxNSwyOCw0NSw2Nl0=) --- ## Explanation Implicit input of array `U`. ``` £ à ``` Map over each element. ``` äa ``` Take each sequential pair (`ä`) of elements in `U` and reduce it by absolute difference (`a`). ``` = ``` Reassign that array to `U`. ``` èx ``` Count (`è`) the number of sub-arrays that return truthy (i.e., non-zero) when reduced by addition. [Answer] # TI-Basic, 19 bytes ``` While max(abs(ΔList(Ans ΔList(Ans IS>(A,9 End A ``` By default, variables start at zero. Also, never thought I'd be using `IS>(` for anything useful. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~70~~ 69 + 18 bytes *-1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)* ``` g=a=>i=>a.Distinct().Count()>1?g(a.Zip(a.Skip(1),(y,z)=>y-z))(i+1):i; ``` Must be given 0 when calling to operate correctly. Also included in byte count: ``` using System.Linq; ``` [Try it online!](https://tio.run/##XVDLTsMwEDw3X2FOtcU2ihsaHm2CUHkICSRED0jcjGuFFa4TYgf6UL89OI1aBGtpZz2zlmdX2oEsKtXUFk1OZivr1CJ8QPM5DoxYKFsKqfb0tNBaSYeFseGdMqpCGWwC4kNqYS252tUd04Z1wqEkXwXOyaNAQ9lB2gS9Fm5rIyf3N6ZeqEq8aTVB4zLoaF8Cae8ZyUlKTK31uMlTkWaYZiK8RuvQSEeZ91Ubjxm/zKkIX7H0efbhgTOgKyBrlmarwZoxisecXeC4OfjobFbt7GjK2o3/KN/vqBWhdCd5D1M/eaFV@KzE3O9IUcbIUWeNBb3eXn6p0KmdnndPw1mp0dE@9Fk4U@0O6ZKkWTtd@CQqq@iSeXcRY7//b4MubxsOQ4jhBEaQwCmcwTnwKOCe8EUCwxHESdD2cJ//Hc/Evm2YQJIAH0UQ8xgSHv0A "C# (.NET Core) – Try It Online") Explanation: ``` g = a => i => // Function taking two arguments (collection of ints and an int) a.Distinct() // Filter to unique elements .Count() > 1 ? // If there's more than one element g( // Then recursively call the function with a.Zip( // Take the collection and perform an action on corresponding elements with another one a.Skip(1), // Take our collection starting at second element (y, z) => y - z // Perform the subtraction ) )(i + 1) // With added counter : i; // Otherwise return counter ``` Iterative version 84 + 18 bytes: ``` a=>{int i=0;for(;a.Distinct().Count()>1;i++)a=a.Zip(a.Skip(1),(y,z)=>y-z);return i;} ``` [Try it online!](https://tio.run/##VVBNSwMxEL3vrxhPTXAb7DnNgtQPBAVxD4K3mE51MM2u@dB@0N@@Ji219B1mknkv4c0zYWw6j0MK5D6gXYeIS/FI7ltWTi8x9NrgcTzrrEUTqXNB3KNDT6baVpBhrA4Brvfnw6QgRB3JwE9Hc3jS5Bj/p06igrvkzPTh1qUlev1ucUouNjWUCgtQg1bNNl@A1JVcdJ5JLW4oRHImMp5tJZd7M5F0ecm10uKNeqZF@5XbhNdsXW@4atbjDZceY/IOSO4GWZ15CNGXBMj1Kcoz5veTLAJjewoUzPL@nUXxgnqek0LGOVwocMlafvaw4Ch@9RRxr14cPhJtbymyUT3iosWSK1uBasrS4ln7gGzFM05WdtWh7oY/ "C# (.NET Core) – Try It Online") [Answer] ## Clojure, 62 bytes ``` #(loop[c % i 0](if(apply = c)i(recur(map -(rest c)c)(inc i)))) ``` Nicely `=` can take any number of arguments, and a single argument is identical to "itself". `(apply = [1 2 3])` gets executed as `(= 1 2 3)`. [Answer] # [Pyth](https://pyth.readthedocs.io), 15 bytes ``` W.E.+Q=.+Q=hZ)Z ``` **[Verify all the test cases.](https://pyth.herokuapp.com/?code=W.E.%2BQ%3D.%2BQ%3DhZ%29Z&input=%5B1%2C6%2C15%2C28%2C45%2C66%5D&test_suite=1&test_suite_input=%5B1%2C4%2C9%2C16%2C25%2C36%5D%0A%5B1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%2C10%5D%0A%5B1%2C2%2C1%5D%0A%5B1%2C1%2C1%2C1%2C1%2C1%5D%0A%5B1%2C+3%2C+9%2C+26%2C+66%2C+150%2C+313%2C+610%5D&debug=0)** # How? ### Explanation #1 ``` W.E.+Q=hZ=.+Q)Z ~ Full program. W ~ While... .E.+Q ~ ... The deltas of Q contain a truthy element. =hZ ~ Increment a variable Z, which has the initial value of 0. = ~ Transform the variable to the result of a function applied to itself... .+Q ~ ... Operate on the current list and deltas. )Z ~ Close the loop and output Z. ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` ⁽¯İ~aL ``` [Try it online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4oG9wq/EsH5hTCIsIiIsIlsxLDIsMyw0LDUsNiw3LDgsOSwxMF1cblsxLDQsOSwxNiwyNSwzNl1cblsxLDIsMV1cblsxLDEsMSwxLDEsMSwxLDEsMV1cblsxLCAzLCA5LCAyNiwgNjYsIDE1MCwgMzEzLCA2MTBdIl0=) Explanation: ``` ⁽¯ # Single element lambda that gets the differences İ # Apply that and collect results until no change ~ # Filter by: a # Any truthy? L # Get the length of those ``` [Answer] # [J](http://jsoftware.com/), 21 18 bytes ``` 2#@(}.~.)2-/\^:a:] ``` [Try it online!](https://tio.run/##TYzNCoJAEIDvPsWYgSuN286aCw4KUtApOnQ1@yGS6NIDRL36thr@MMxhv2@/edrMZ6qNz1kYejMZNlAwhICggN3GEjaH3dbqoBQf@ZWRjpfHE1@5tpG3X0uoOOfSyVi@ORKtraPWd1LQouI5/@lFcSkFFUHpzkzaIRKUd27Iz9rlLZre9e63xwsaIFxhhmRQp5iYgYIGGh/djAUkCBmCNgjGLaXKIXLQkOp/qX7sDw "J – Try It Online") *-3 thanks to rdm!* [Answer] # [Perl 5](https://www.perl.org/), 83 + 1 (-a) = 84 bytes ``` sub c{$r=0;$r||=$_-$F[0]for@F;$r}for(;c;$i=0){$_-=$F[++$i]for@F;$#F--}say y/ //-$#F ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhuVqlyNbAWqWopsZWJV5XxS3aIDYtv8jBDShUC2RoWCdbq2TaGmhWA2VtgdLa2iqZMBXKbrq6tcWJlQqV@gr6@rpA/v//hgomCpYKhmb/8gtKMvPziv/r@prqGRga/NdNBAA "Perl 5 – Try It Online") Input as a list of numbers separated by one space. [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 11 bytes ``` W$D}ltoK)Ko ``` [Try it here!](http://pyke.catbus.co.uk/?code=W%24D%7DltoK%29Ko&input=%5B1%2C+3%2C+9%2C+26%2C+66%2C+150%2C+313%2C+610%5D&warnings=1&hex=0) [Answer] # Pyth, 10 bytes ``` tf!t{.+FQt ``` If we can index from 1, we can save a byte by removing the leading `t`. [Try it Online](http://pyth.herokuapp.com/?code=tf!t%7B.%2BFQt&input=[1%2C4%2C9%2C16%2C25%2C36]&debug=0) Explanation ``` tf!t{.+FQt f T Find the first (1-indexed) value T... .+FQt ... such that taking the difference T - 1 times... !t{ ... gives a set with more than one value in it. t 0-index. ``` ]
[Question] [ Given a binary message, and the number of parity bits, generate the associated parity bits. A parity bit is a simple form of error detection. It's generated by counting the number of `1`'s in the message, if it's even attach a `0` to the end, if it's odd attach `1`. That way, if there's a 1-bit error, 3-bit error, 5-bit error, ... in the message, because of the parity-bit you know the message has been altered. Although if there were an even number of bits altered, the parity stays the same, so you wouldn't know if the message has been changed. Only *50%* of the time you'd know if bits have been altered with one parity bit. ## Generate Parity bits To generate `n` parity bits for a given binary message: 1. Count the number of `1`'s in the message 2. Modulo by \$2^n\$ 3. Attach the remainder to the message For example, using three parity bits (n=3) and the message `10110111110110111`: 1. `10110111110110111` -> 13 `1`'s 2. \$13\mod2^3\$ -> 5 3. `10110111110110111` with 5 attached (in binary) -> `10110111110110111101` The last three digits act as parity bits. The advantage with parity bits is, that they can't detect errors only when a multiple of \$2^n\$ bits have been altered (ignoring messages which share the same permutations). With three parity bits, you can't detect errors when 8, 16, 24, 32, 40, ... bits have been altered. \$(1-\frac{1}{2^n})\%\$ of the time you'd know when bits have been altered, significantly more than with just one parity bit. ## Rules * Take as input a binary string or a binary array and an integer (`0<n`, the number of parity bits) * Output a binary string/binary array with `n` parity bits attached * The parity bits should be padded with zeros to length `n` * Leading zeros are allowed * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins ## Test Cases ``` [In]: 10110, 1 [Out]: 101101 [In]: 0110101, 2 [Out]: 011010100 [In]: 1011101110, 3 [Out]: 1011101110111 [In]: 0011001100111101111010011111, 4 [Out]: 00110011001111011110100111110010 ``` [Answer] # [Zsh](https://www.zsh.org/) `--extendedglob`, 37 bytes ``` local -Z$2 -i2 n=${1//10#/+1} <<<$1$n ``` [Try it online!](https://tio.run/##bU/LasMwELzrK5ZIBYlg7FVzCm4@pKUHJd46BlkKslryIN/uSrFbfIjEIoaZnRldh@M4UPSnCHSO5BpqWuv37GRCFy9SyURCcWZbWElxw7LEipdrvKsXrGuhV6P1B2OheBcaik6De1uqWJ1EKNyo2OwIWCFWgH8wo3RBL/lp4PVflFXzTGReerwIG8YYh/77cATrXUthy4yNmKozSGdqcJM2td3V1U4JKT8415/PvqPUnalsF6j3PzSAJdN0roUrBZ/gV/A97C@RhhjI9DlIL4Nma83Fw279PCNFjL8 "Zsh – Try It Online") The `-Z$2` flag does the heavy lifting. It automatically `% base**$2`, and fills in zeroes. EXTENDED\_GLOB `10#` is equivalent to regex `10*`. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~37~~ 36 bytes ``` ->n,d{n+"%0*b"%[d,n.count(?1)%2**d]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ6U6T1tJ1UArSUk1OkUnTy85vzSvRMPeUFPVSEsrJbb2f4FCWrSSgYGhIQwDSQgB4Rgq6SiYxP4HAA "Ruby – Try It Online") Thanks @dingledooper for -1 byte. [Answer] # [C (clang)](http://clang.llvm.org/), ~~79~~ \$\cdots\$ ~~74~~ 62 bytes ``` p;f(*b,n){for(p=0;*b|n;)printf("%d",*b?*b++&1&&++p:p>>--n&1);} ``` [Try it online!](https://tio.run/##fVHLboMwELznK1ZIQTyMCkl7aNykhyq3/EHJAYxJUNMNwpaKmvLrpTY2CVLVGq283hnPrBcWsVOGh76vaekFOUH/Up4br17HNMi/kPp1U6EsPWdeOCTIn4M8DN3EdcOwXtWbTRShm/i06xUJ3rMKPR8uM1BLFQKQXEjxuoc1XHZOEidJ7BDYOTpR35DrqgkDacyGqWvqsCdOR0fpQRmNckJgQWBJ4N7i7Jg1AfC25kzywpCMu7Yc3WNtOLHXBhr9pwG1xWMT7IxCWit25OyNN9YpbbeLtH18UfGgFSfn5XhbzRg8/Y4KC96qazG16ROI6pOfS2/s37@zheBaoRCGA9sfxMzAb0NXcmbwA2dPpzCgRfEXev3TJ0FgXqQY2bUB9QxJAP0bufQkmZ7tzJX4de5/6ae4tZQVzEWKSpxbpW7W9d@sPGUH0UcfPw "C (clang) – Try It Online") *Saved ~~a~~ ~~4~~ a whopping 16 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!* *Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* Inputs a wide char string and an integer. Outputs the result to `stdout`. [Answer] # Excel (ms365), ~~50~~ 47 bytes -3 Thanks to @[EngineerToast](https://codegolf.stackexchange.com/questions/252491/generate-parity-bits/252548#comment562308_252548) ``` =A1&BASE(MOD(LEN(SUBSTITUTE(A1,0,)),2^B1),2,B1) ``` [![enter image description here](https://i.stack.imgur.com/9p28e.png)](https://i.stack.imgur.com/9p28e.png) [Answer] # [Haskell](https://www.haskell.org/), ~~60~~ 42 bytes ``` b!n=b++[mod(sum b`div`2^(n-x))2|x<-[1..n]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P0kxzzZJWzs6Nz9Fo7g0VyEpISWzLMEoTiNPt0JT06imwkY32lBPLy829n9uYmaegq1CSr4Cl0JBUWZeiYKKQrShjoGOIRAaxCooKhjCJBDCOoaxMEElJSR9cGmwEqBeI7heFCkgNsBuAswKJBpkjjGGGzBoXC6CWYxKIxsAdxKcD3a7CZLbyTIEygP5lEvhPwA "Haskell – Try It Online") * saved 3 Bytes thanks to @Unrelated String suggesting using list comprehension. * saved 10 Bytes by @xnor by removing a redundant modulo. Please check [his answer](https://codegolf.stackexchange.com/a/252534/84844) which is still one byte shorter using a more direct approach. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~11~~ 10 bytes ``` ⌊∑$E%Π⁰↳›J ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLijIriiJEkRSXOoOKBsOKGs+KAukoiLCIiLCIwMTEwMTAxXG4yIl0=) "~~11~~ 10 bytes?!" I hear you say. Well you gotta remember that when it comes to doing things with base conversion I don't do the best - so keep that in mind when y'all start giving me golfing suggestions :p ## Explained ``` ⌊∑$E%Π⁰↳›J ⌊∑ # Sum of the 1s in the input binary $E% # Modulo'd by 2 to the power of n Π # Converted to binary ⁰↳ # Padded with spaces to make sure it's of length n ›J # With those spaces replaced with 0s and joined to the original binary input ``` [Answer] # [Factor](https://factorcode.org/), 62 bytes ``` [ dup bin> bit-count pick 2^ mod >bin rot 48 pad-head append ] ``` [Try it online!](https://tio.run/##fZCxbgMhDIZ3nuLP7VdBmiFqpaxVly5RpyqRCLg6lB4Q4NQhyrNfCKBMTS0ZG@zPP/K3VMmF@XP7/vH2AhmjUxFHCpZ@MMo0PHkZIoWS14eDSb8mEiKdJrKKIozDK2NnhmxnCHSCC8E7XPDAFigdohFLdOXKxUNmgdbBeYOeq0z1v7kqc/cGrrLabVjzWiuTb7F8Iav905EDZxc2f0FPHgdjN/lIvXKTTfBGHbHcY3Qam1xDcAmrNbzU/UBSQ3pPVmOXcR9MJnZQbvQub7RsvyephvkK "Factor – Try It Online") Takes input as `n msg`. ``` ! 3 "10110111110110111" dup ! 3 "10110111110110111" "10110111110110111" bin> ! 3 "10110111110110111" 94135 bit-count ! 3 "10110111110110111" 13 pick ! 3 "10110111110110111" 13 3 2^ ! 3 "10110111110110111" 13 8 mod ! 3 "10110111110110111" 5 >bin ! 3 "10110111110110111" "101" rot ! "10110111110110111" "101" 3 48 ! "10110111110110111" "101" 3 48 pad-head ! "10110111110110111" "101" append ! "10110111110110111101" ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), ~~8.5~~ 7.5 bytes (15 nibbles) ``` :$\<@\``@+^2@+ ``` Input and output both as arrays of `0`s and `1`s. ``` + # get the sum of arg1, + # and add it to ^2 # two to the power of @ # arg2, ``@ # convert to binary digits, \ # reverse them, <@ # take arg2 elements, \ # and reverse them back again # (so the last few steps effectively # pad the binary digits to arg2 digits), :$ # finally, append this onto arg1 ``` [![enter image description here](https://i.stack.imgur.com/cnsgy.png)](https://i.stack.imgur.com/cnsgy.png) [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` tsiW\2M&Bh ``` [Try it online!](https://tio.run/##y00syfn/v6Q4MzzGyFfNKeP//2hDBQMFQwUYaYjEhorEchkDAA) Or [verify all test cases](https://tio.run/##y00syfmf8L@kODM8xshXzSnjv0vI/2hDBQMFQyA0iOUy5IqGsiE4lsuICy6PRMdyGYNUwtSi0sgqYSYh@EAzTQA). ### Explanation ``` t % Implicit input: numeric vector. Duplicate s % Sum i % Input: number, n W % 2 raised to that \ % Modulo 2M % Push n again &B % Binary expansion with specified number of digits h % Concatenate horizontally. Implicit display ``` [Answer] # JavaScript (ES6), 53 bytes Expects `(binary_string)(n)` and returns another binary string. ``` s=>g=(n,k)=>k^n?g(n,-~k)+(~-s.split`1`.length>>k&1):s ``` [Try it online!](https://tio.run/##bYxBCsIwEEX3HqMLyaAJHXUlJN6ktNQ01oSkdILLXj1NrCuV4TMDb95/dq@O@nmcIvfhrtMgE0llJPNHC1LZxt9Mvvli4cAWToImN8YWW@G0N/GhlN0jXCn1wVNwWrhg2MAqrBHrChgC7L5QIXkyPP3C4m3J/PxHLvYn22Mpe@/SeAFIKw "JavaScript (Node.js) – Try It Online") ### Commented It's a little easier to build the output from right to left. This way, we can just append the input string on the last recursive call. ``` s => // outer function taking the binary string s g = (n, // inner recursive function taking n k) => // and a counter k which is initially undefined k ^ n ? // if k is not equal to n: g(n, -~k) + // do a recursive call with k + 1 ( // append one binary digit: ~-s.split`1` // to get the number of 1's, subtract 1 from the length .length // of the array obtained by splitting the input on 1's >> k & 1 // right shift by k positions and keep the LSB ) // : // else: s // append s and stop the recursion ``` [Answer] # [Python](https://www.python.org), 48 bytes ``` lambda a,b:b+bin(b.count("1")%2**a)[2:].zfill(a) ``` Finally, a use for `zfill`! [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3jdJscxJzk1ISFRJ1kqyStJMy8zSS9JLzS_NKNJQMlTRVjbS0EjWjjaxi9arSMnNyNBI1ITq3FhRlAtWkaRjpKBkYGhoAoZImVA5mOgA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` SBŻ⁹¡ṫC}⁸; ``` A dyadic Link that accepts a list of bits on the left and a positive integer on the right and yields a list of bits extended with the parity bits. **[Try it online!](https://tio.run/##y0rNyan8/z/Y6ejuR407Dy18uHO1c@2jxh3W////jzbUgcLY/0YGAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/z/Y6ejuR407Dy18uHO1c@2jxh3W/8MeNa05vPzQUn3NyP//o6OVDA0MDQ2UdBQMY7l0opVAHCAE8o3AfJAsBAOFjCFKQGqgGCIH0gKmQfpMYrli/xsDAA "Jelly – Try It Online"). ### How? ``` SBŻ⁹¡ṫC}⁸; - Link: bits, n S - sum (bits) -> count of ones B - to binary ¡ - repeat... ⁹ - ...times: chain's right argument = n Ż - ...action: prepend a zero -> count of ones as binary with n leading zeros } - using the right argument (n): C - complement -> 1-n ṫ - tail (from 1-indexed index 1-n) -> parity bits (including any necessary leading zeros) ⁸ - chain's left argument = bits ; - concatenate (parity bits) to (bits) ``` [Answer] # [Haskell](https://www.haskell.org/), 41 bytes ``` l!n=l++cycle(mapM(:[1])$0<$[1..n])!!sum l ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P0cxzzZHWzu5MjknVSM3scBXwyraMFZTxcBGJdpQTy8vVlNRsbg0VyHnf25iZp6CrUJKvgKXQkFRZl6JgopCtKGOgY4hEBrEKigqGMIkEMI6hrEwQSUlJH1wabASoF4juF4UKSA2wG4CzAokGmSOMYYbMGhcLoJZjEojGwB3EpwPdrsJktvJMgTKM4j9DwA "Haskell – Try It Online") Input and output are lists. Test case code [from AZTECCO](https://codegolf.stackexchange.com/a/252523/20260). Haskell doesn't have built-in binary operations, so we do things by hand. The `mapM(:[1])$0<$[1..n]` is one shorter than writing `mapM(\_->[0,1])[1..n]`, for taking the `n`-fold Cartesian product of `[0,1]`. Applying `cycle` then lets us modular index into it. [Answer] # [Rust](https://www.rust-lang.org), ~~120~~ 117 bytes * -3 bytes thanks to JSorngard ``` |k:Vec<_>,m|k.iter().copied().chain((0..m).rev().map(|j|k.iter().filter(|i|**i).count()&1<<j>0)).collect::<Vec<_>>(); ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jVLNUsIwEJ7xyFMsOUjCxE6rHpxS8C28IMOUmo6BNjBpyoXyJF446BN48lH0acwPBaZSNW22Xza737fd2ZdXWRZq954KyGMuMIFNxhSkMIS3UqVXd59ltQgfWBJNRzSvFh5XTGLiJcsVZ08GPJs07HteTjzJ1tqVxytczY-xKc8MqHjV73OTWgqFyWUQRfORT4wjy1iiwjByOiNMBk786-IjXUrAihVqmsQFozDjqqAgWVFmigAXMO6AXnjNku5YyVKHpHFmIt3hxDWhEFBAgR_oFxHqEq3VyxK0pZ45TGideX1AyFLrx0e0owUs-e-V_efCSd1Ya8s_7BMZp1NXsids_5_WmwbDz5L-qNjasyTtyk1bpx97fHvSY9Pk_XZdsB0PLNAIuVDdlwlsLFxJLlQmuhg9ik14v0X1AJnplUU9srziMBxCL-idnUkyaJDtqdLmeJrI7dZN8G7nvt8) [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 13 bytes ``` {x,(y#2)\+/x} ``` [Try it online!](https://ngn.codeberg.page/k#eJyFUEFuwyAQvPMKpPZgq8QY4h4KL8ipl9xcS8EudqykJjFEworStxeMg3JKD6NdZndmNbTsalEyvdD06w3bGwBbdn0tp9+RtTCDlu/UgSe7VvRHbvnEx7S6gW2ZkJyQvOYk5XNH6sqzc+senKZ86fM8jPxaQM3XQRWxiL1iQeBnua/OsXCOTxZc8YcAwGBvzEkzjBv1LTt1bDNtRHOQttmLoZNZo37w+SK16dWgMX2nxQfBnRzkKIxcncTYm2lV90aDcjNUDMI5IIIElJ8X44gQ+D5dYiJI7/MY/NEgAMH1o0tENHuSEMEiXvjnI/4AKc5zJg==) Takes input as a list of `0`s and `1`s (`x`) and an integer `y`. * `+/x` the "popcnt" of the input (i.e. the number of set bits) * `(y#2)\` "encode" the sum (using `(y#2)` guarantees the length of the result) * `x,` append the parity bits (and implicitly return) [Answer] # Python, ~~44 39 65~~ 40 bytes `m` should be a binary string, while `n` an int. Had to add 26 bytes all because OP didn't say that 0's had to be prefixed to the parity bits, but doesn't matter since Neil found a shorter solution. ``` lambda m,n:m+bin(m.count('1')+2**n)[-n:] ``` [Answer] # Java 8, ~~87~~ ~~73~~ 72 bytes ``` b->n->b+n.toString((n=1<<n)|n.bitCount(n.valueOf(b,2))%n,2).substring(1) ``` -14 bytes thanks to *@ceilingcat* [Try it online.](https://tio.run/##fVDBasMwDL3nK0RgYJPExN1Oa5rLYLDD2KHHsYPdJsVZqoRaDpSt3545icfYCgPLkqWnpyc3alBZs38fd62yFp6VwY8IwJIis4PGV4Uj04ra4Y5Mh@IxBMWWTgYP6b@YJ6TqUJ1SWMBlCTVsRp2VmJU6QUHdUmAMN7IokH@i0IYeOofEUAyqddVLzXS64vwG/S2s03ZpkXwEWEdebO9068UGzUNn9nD0e7CF@/UNFJ92AqDKEotlLqcj5XcQp3DL138RPit/ZWd0PqFXV@jFrojyqSdYGJqHx8RzN4Mv0c@Hz@Ln3kU86NQgAYYFtmdL1VF0jkTvy9Qiw8QTxYlO4nvwvhaq79sz0zwEyMOQy/gF) **Explanation:** ``` b->n-> // Method with String & Integer parameters and String return b // Return the given binary-String + // Appended with: n.toString( // Convert the following integer to a (binary-)String: (n=1<<n) // 1 bitwise left-shifted by `n` // (which is saved in `n` to reuse later on) | // Bitwise-ORed by: n.bitCount( // The amount of 1-bits n.valueOf(b,2)) // in the binary-String input %n // Modulo the `1<<n` we saved in variable `n`, // which is basically 2 to the power (input) `n` ,2) // (Use base-2 for the `n.toString`) .substring(1) // And remove the leading "1" ``` `n.toString(1<<length|value,2).substring(1)` is taken from [this Stackoverflow answer](https://stackoverflow.com/a/28198839/1682559). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes ``` Nθη✂⍘⁺X²θΣη²±θ ``` [Try it online!](https://tio.run/##PUy7CoAwENv9CscrKNji5ubmIoV@QS2HCvVVW/3880B0SEhCEjfZ4Dbribp1T7FPy4ABDtFkOsxrhOlXxs8OobUnmsjBCNqnE/R2c18V@SGK3KSFBywUo8fRRuQrIRqiOqsqKT8wv/QaSeXlHw "Charcoal – Try It Online") Link is to verbose version of code. Takes `n` as the first input. Explanation: ``` Nθ ``` Input `n` as a number. ``` η ``` Print the binary message. ``` ✂⍘⁺X²θΣη²±θ ``` Sum the bits in the binary message, add on `2ⁿ`, convert to binary, and print the last `n` digits. [Answer] # [*Acc!!*](https://github.com/dloscutoff/Esolangs/tree/master/Acc!!), 149 bytes ``` N Count b while _%52/48 { Write _%52 _+_%52*51-2496+N } _+N%4 Count p while _%4 { Count j while _%4/2*(p-j) { Write _/52/2^(p-1-j)%2+48 } _-_%4+N%4 } ``` Takes input as a binary string, followed by a space, followed by an integer in unary, followed by a newline. [Try it online!](https://tio.run/##S0xOTkr6/9@Pyzm/NK9EIUmhPCMzJ1UhXtXUSN/EQqGaK7woswTC54rXBlFapoa6RiaWZtp@XLVAIT9VE6jeArheE6A@iFgWQkzfSEujQDdLE2GmPtAOozigoCFQWNVI28QCZKIuUC3Y1Nr//w0MDA1hGEhCCAjHUAFEAAA "Acc!! – Try It Online") ### Explanation ``` # Read a character into the accumulator N # Since all the characters we'll need to handle have character codes less than 52, # we can store the most recently read character in _%52 and the number of 1 bits # in _/52 # While the most recent character code is >= 48 (i.e. a digit): Count b while _%52/48 { # Write that digit Write _%52 # Add 52 to the accumulator (i.e. add 1 to _/52) if the digit was a 1 _+(_%52-48)*52 # Clear the previously read character and read a new one _-_%52+N } # After reading a space, the above loop exits; _/52 is the number of 1 bits # in the input, while _%52 is 32 from the just-read space # In the next section, we want to distinguish among three cases: # - Reading a 1 (code 49) means keep the loop going # - Reading a newline (code 10) means output the parity bits # - Reading EOF (code 0) means exit the loop # These cases can be distinguished by taking the character code mod 4 # Read a character and add its character code mod 4 to the accumulator _+N%4 # While accumulator mod 4 is not zero, increment p (starting from 0) and: Count p while _%4 { # If accumulator mod 4 is >= 2 (meaning we just read a newline), # increment j (starting from 0) and loop while p-j is nonzero: Count j while (_%4/2)*(p-j) { # Write the jth parity bit, which is the bit in the 2^(p-1-j)'s place of # the number of 1 bits (stored in _/52) Write (_/52)/2^(p-1-j)%2+48 } # Clear the previously read character (mod 4) and read a new one (mod 4) _-_%4+N%4 } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` DSOIo%bI°+¦« ``` Inputs in the order \$b,n\$. Binary-I/O as strings. [Try it online](https://tio.run/##yy9OTMpM/f/fJdjfM181yfPQBu1Dyw6t/v/fwNDQAAi5jAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6H@XYP@IfNWkiEMbtA8tO7T6v87/6GglQwNDEDI0hDGUdIxjdaDiSjqGIDZYxgAoYwSTgWCoUgOQPBRDDTOAcoB6TGJjAQ). **Explanation:** ``` D # Duplicate the first (implicit) input binary-string SO # Sum the digits of the copy I # Push the second input-integer o # Pop and push 2 to the power this input % # Modulo the bit-sum by this b # Convert it to a binary-string I # Push the second input-integer again ° # Pop and push 10 to the power this input this time + # Add it to the binary ¦ # Remove the leading 1 « # Merge the two binary-strings together # (after which the result is output implicitly) ``` --- If we didn't had to retain the potentially leading `0`s of input binary-strings, this could have been 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) with an arithmetic addition approach: ``` Î׫DSO¹o%b+ ``` Inputs in the order \$n,b\$. Binary-I/O as strings. [Try it online](https://tio.run/##yy9OTMpM/f//cN/h6YdWuwT7H9qZr5qk/f@/EZeBoaEBEAIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCceh/g4jD0w@tdgn2j8hXTdL@r/M/OtpYR8nQwBCEDA1hDKVYnWhDqDiIbQRkAzkGYAmoBggGCZiAZQ0gGGqSAZQD1BELAA). **Explanation:** ``` Î # Push 0 and the first input-integer × # Repeat the 0 that many times as string « # Append it to the (implicit) input binary-string D # Duplicate it SO # Sum the digits of the copy ¹ # Push the first input-integer again o # Pop and push 2 to the power this input % # Modulo the bit-sum by this b # Convert it to binary + # Add the two binary strings together arithmetically # (after which the result is output implicitly) ``` [Answer] # [Rust](https://www.rust-lang.org/), ~~88~~ 58 bytes ``` |a,n|format!("{a}{:0n$b}",(a.split('1').count()-1)%(1<<n)) ``` [Try it online!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=634f45da728663e815bf803fe75c7469) This closure can be assigned to a variable of type `fn(&str,usize) -> String`. Edit: Saved 30 bytes with `split('1').count()` instead of converting to an integer, as in [Joost's](https://codegolf.stackexchange.com/users/79157/joost-k) [answer](https://codegolf.stackexchange.com/a/252607), thanks! [Answer] # [Pip](https://github.com/dloscutoff/pip), 28 bytes ``` a.(J(0*,bALTB($+a)%2Eb))@>-b ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJhLihKKDAqLGJBTFRCKCQrYSklMkViKSlAPi1iIiwiIiwiIiwiMDAxMTAwMTEwMDExMTEwMTExMTAxMDAxMTExMSA0Il0=) Holy crap, this is terrible. There must be a better way to go about this. This 100% golfable. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` pUx u2pV)¤ù0V ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=cFV4IHUycFYppPkwVg&input=WzAsMCwxLDEsMCwwLDEsMSwwLDAsMSwxLDEsMSwwLDEsMSwxLDEsMCwxLDAsMCwxLDEsMSwxLDFdCjQ) ``` pUx u2pV)¤ù0V Ux # Sum of the digits in U u ) # Modulo: 2pV # 2 to the power of V ¤ # Convert to base 2 ù0V # Left-pad with 0 until the length is V p # Add that string to the end of U # Print the array with no delimiter ``` Can be modified to run without `-P` for [15 bytes](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cFV4IHUycFYppPkwVims&input=WzAsMCwxLDEsMCwwLDEsMSwwLDAsMSwxLDEsMSwwLDEsMSwxLDEsMCwxLDAsMCwxLDEsMSwxLDFdCjQ) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 18 bytes ``` pz.[\0KE.B%/z\1^2K ``` [Try it online!](https://tio.run/##K6gsyfj/v6BKLzrGwNtVz0lVvyrGMM7I@/9/AwNDQxgGkhACwjHkMgEA "Pyth – Try It Online") ### Explanation: ``` pz print the first input with no newline KE evaluate the second input and store in K /z\1 number of occurrences of "1" in the first input % ^2K modulo 2 ^ K .B binary representation .[\0K pad with copies of "0" until length K and implicitly print ``` [Answer] # [Desmos](https://desmos.com/calculator), 58 bytes ``` f(l,n)=join(l,mod(floor(2mod(l.total,2^n)/2^{[n...1]}),2)) ``` \$f(l,n)\$ takes in a list of bits \$l\$, representing the binary message, and an integer \$n\$, representing the number of parity bits, and returns a list of bits representing the parity bits. [Try It Online](https://www.desmos.com/calculator/hctkd9cdha) [Try It Online - Prettified](https://www.desmos.com/calculator/knyhvb6jay) [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 77 bytes ``` param($s,$n)$s $l=($s-eq1).Count ($u=0..--$n|%{$l%2 $l=$l-shr1})[$n..1]+$u[0] ``` [Try it online!](https://tio.run/##fVHRaoMwFH33K4LcDl2NmG6vgqVssJdtrI9FinPpbLGxSyJbUb/d3aizDsYCl@TknHvuITkVn1yqjOc5TQvJW9iFVXtKZHJ0QHkgXFAW5CECyj@Y66@KUmjLgTIMfJ9SEPWsgny2MCLIqcoka9wNCN9n8RzKTRC3jWVFjkVweZFjs4CxwPYI80h/ZrY7JYMJGSC4kJ0Y5R5ZID2gXwrj1xeKboYBY02tTPdQPdlZmd343xr/fyS4mbEuqcl9Ie@SNKNPrweealJ1I/DlCAgs/nXCW/5GQgLbgdJyL96X6kHopZTJ2VCqnhF9fcannNuwtZteKbkqc438Fez@6APRyTbP61WpdHHsE8RRH8GsdZmmXCkzYQyCv0gceij2YvB3L/IuyggfDRQjfPlJM23u2MZq2m8 "PowerShell Core – Try It Online") Takes the binary string as an int array and returns an array of ints ### Explanations ``` $s # Returns $s as is $l=($s-eq1).Count # Counts the number of ones $u=0..--$n|%{$l%2;$l=$l-shr1}} # Gets the number as binary inverted (smallest bit on the left) $u[$n..1]+$u[0] # Returns the binary representation inverted. The $u[0] is to handle the case where $n=1 ``` [Answer] # [J](http://jsoftware.com/), 19 bytes ``` [,(]#2:)#:+/@[|~2^] ``` [Try it online!](https://tio.run/##dY1BC4JAFITv/oohIZNMXeukFFHQKTp0lYJFdmvD3Fq1Q4R/3ZSSVOgwb2C@9@ZdyoENg2Puw4AFF36liY31frspQ2t00D3f1P2xswxfhXc8lKam7VY2eDFcOOBSgdFUMIUrSzIai6dITpAcIrnlWRqA3XPxoHEFkUlQpcDBaZRJpbHoLL89JACp/pJ6tnMvaNKP2mz6u2n5n42Gk37S3p/V3xra9W6H2yOkfAM "J – Try It Online") This feels golfable, but I can't for the life of me figure out where without an entirely different approach. ## Explanation ``` [,(]#2:)#:+/@[|~2^] left: binary array. right: parity bit count +/@[ sum of bit array (number of 1s) |~ modulo 2^] 2^parity (]#2:) generate a number of 2s equal to parity bit count #: and use them to convert the above quantity to base 2 this generates the requisite padding [, concatenate them to the right of the binary array ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 46 bytes ``` v=>n=>v+(v.split`1`.length-1%2**n).toString(2) ``` [Try it online!](https://tio.run/##fY1BCoMwEEX3OUURConFmEm71Uv0AoqNaUqYiIZcPzVRXLSli8/nD483rz70yzCbyVfoHiqOTQxNi00bLjTwZbLGd9Bxq1D7ZwVnWZbIuHd3PxvUVLI4OFycVdw6TUdagAAQBaPA2Kmu8wLyweSjgJWSmdq3EOSHbMvKXg/jkS9xMu3ZiKxNnb7dtm9/oLUEiW8 "JavaScript (Node.js) – Try It Online") it was actually surprisingly easy in javascript [Answer] # [><>](https://esolangs.org/wiki/Fish), 88 bytes ``` 0l:3(?v1-@$"0"-:}+$10. $1-c1.>@@:aap:2(?v$2* ?v:2%$2,:1%-ab+2.>~%1[:2( l<0v?=gaa >n<>r]r ``` [Try it online](https://tio.run/##NYrLCsIwEEX3@YwyAbFOmBldDW2S/xAXUfABRaSF7Oyvj4Hi4hw43Ht/LU8zmvS4S5UxQ0cd6rcHpuCA8cYh5qylfFTaA2TvUlXxIAdlj@XaS4ir53Ob3TRQTeOjFBffQ5wvs5lhPRkuRMx/mjdtwT8) [Answer] # [R] 92 bytes ``` fun=\(s,n)paste0(s,paste(rev(+(intToBits(nchar(gsub("0","",s))%%2^n)[1:n]==1)),collapse="")) dat <- data.frame(s=sapply(tests, function(z) z[[1]]), n=1:4, out=outs) dat # s n out # 1 10110 1 101101 # 2 0110101 2 011010100 # 3 1011101110 3 1011101110111 # 4 0011001100111101111010011111 4 00110011001111011110100111110010 mapply(fun, dat$s, dat$n) == dat$out # 10110 0110101 1011101110 0011001100111101111010011111 # TRUE TRUE TRUE TRUE ``` ]
[Question] [ As you probably know, there have been [multiple](https://codegolf.stackexchange.com/questions/187586/will-jimmy-fall-off-his-platform) [lovely](https://codegolf.stackexchange.com/questions/187682/how-many-jimmys-can-fit) [Jimmy](https://codegolf.stackexchange.com/questions/187731/jimmy-needs-your-help) [challenges](https://codegolf.stackexchange.com/questions/187759/can-jimmy-hang-on-his-rope) [recently](https://codegolf.stackexchange.com/questions/188140/jimmy-needs-a-new-pair-of-shoes) popping up. In these challenges, you were challenged with our beloved friend's acrobatics skills. Now we've got a different challenge for you. Today you will be identifying different types of Jimmys! --- # Explanation There are three varieties of Jimmys: dwarf, acrobat, and bodybuilder. ``` This is dwarf Jimmy: o This is acrobat Jimmy: /o\ This is bodybuilder Jimmy: /-o-\ ``` These Jimmys are all great friends and they like to stand on the same line as each other. Your task is, given a Jimmy scene like so: ``` o /o\ o /-o-\/-o-\ o /o\ ``` Output the amount of dwarves, acrobats, and bodybuilders on the line, respectively. # The challenge * Take input in any reasonable form as a Jimmy scene, as shown in an example above. 1. The input string should be one line and optionally contains the three varieties of Jimmys and optional whitespace. 2. The string will not necessarily contain all of the Jimmy varieties or whitespace. 3. The string will not contain any characters not in `o/\ -` . 4. Any combination of Jimmy varieties is possible. This means that the same or different type of Jimmy can be next to each other. You must account for that. 5. Leading and trailing whitespace is optional and by no means required - your program should account for a string with or without leading and/or trailing whitespace. 6. The string should contain only valid Jimmys and whitespace. For instance, `---///---` is not allowed because it is not a valid Jimmy sequence. * Output three numbers: The count of dwarves, acrobats, and bodybuilders in the scene (in respective order). 1. This may be an output to the console as space-separated integers, or it may be a return value from a function as some sort of container (i.e an array type). 2. The output, in whatever format, must be ordered as mentioned in the top bullet above this rule. * Standard rules and loopholes apply. # Test cases ``` /-o-\ /-o-\ o/o\ /-o-\ /-o-\ /-o-\ OUTPUT: 1 1 5 o o /o\ o o o /o\ /o\ OUTPUT: 5 3 0 /-o-\ /-o-\ /-o-\/-o-\ o /o\/o\ /-o-\o /-o-\ /o\/-o-\ OUTPUT: 2 3 7 /-o-\ o /-o-\ o/o\ OUTPUT: 2 1 2 ``` If you'd like more test cases, use [this tool](https://tio.run/##ZY7LTsMwEEX3/oqrsohN25DCBoGC1EUlFrQgsQBEqyhtJ41F4okcV8DXB5uUh@Au7HncmTnNuyvZnHXd9e1DNp8unrLZ43R@dzO7R4pJgj86wmJfr8mCC9BbXjcVtXCMHRmyuSPhpeuGrYPNzZbrEZyufXlTst54b4rniKNRdMLLZfjGPPbBCkNfR7Q6Pk1EPxi3RFsZhuPwSKWEKNgigzZh947kP2R1IQKkpXZfOX9qMPjMX0tdESZ985dhmB4g455OHiDVt1EXqMjI3q9whfPkZ0tQY7VxX/1LrC3lL133AQ) to generate more random test cases. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest score in bytes wins. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 51 bytes ``` lambda s:((c:=s.count)('o')-c('/'),c('/o'),c('/-')) ``` [Try it online!](https://tio.run/##VYvNCoAgEIRfxdvuQuahSwS9iZcyoqBcST309JbRDw0Ds/sN4/Ywsa1qt6Wx1Wnp1n7ohG8QTdP60nC0gRAYSBoEBVTk4DslECW3zTbgiLN1MSCdRCjJUous77p1gYeyUKxPvwX/BrnM7wE "Python 3.8 (pre-release) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 50 bytes ``` x,y,z=map(input().count,'o/-') print x-y,y-z/2,z/2 ``` [Try it online!](https://tio.run/##ZU7NCsMgDL73KSSXtqATehzsLXb0MopQoTNSlGlf3tWuxeoScsj3l5hgJ9RD/ExqluS5OHmXXo4AED0NdH28X6ZT2jjb9bcRnba0Rc7avjGL0pZ4FmhgKx/oNjHZgKTiDJkgufKOHEXJ19oLCM0vjuDWlQBFQdT8VVTsKTOf/Du@AyeKyXGE7BiWn@OhhC8 "Python 2 – Try It Online") -10 bytes by converting lambda expression to a full program thanks to @xnor (removes the double-lambda nested thing and uses assignment instead) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), (12?) 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ċⱮ“-/o”H1¦ŻIṚ ``` A monadic Link accepting a list of characters which yields a list of integers, `[ dwarves, acrobats, and body-builders]` (save the `Ṛ` byte if we may specify our output) **[Try it online!](https://tio.run/##y0rNyan8//9I96ON6x41zNHVz3/UMNfD8NCyo7s9H@6c9f//fwV93XzdGAUQQLCgACwAE81X0M@PASK4RD6KBpAkiAsA "Jelly – Try It Online")** ### How? All Jimmys show a `o`; all non-dwarves show a `/`; all body-builders show two `-`. Count these up, halve the count of `-`, and perform subtraction to find the Jimmy counts: ``` ċⱮ“-/o”H1¦ŻIṚ - Link: list of characters “-/o” - list of characters ['-', '/', 'o'] Ɱ - map across right with: ċ - count occurrences = [n('-'), n('/'), n('o')] ¦ - sparse application... 1 - ...to indices: [1] -- i.e. n('-') H - ...action: halve = [n('-')/2, n('/'), n('o')] Ż - prepend a zero = [0, n('-')/2, n('/'), n('o')] I - incremental differences - = [n('-')/2, n('/')-n('-')/2, n('o')-n('/')] Ṛ - reverse - = [n('o')-n('/'), n('/')-n('-')/2, n('-')/2] ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~59~~ 55 bytes ``` $c=,0*3 $args|sls '/?-?o'-a|% m*|% le*|%{++$c[$_-1]} $c ``` [Try it online!](https://tio.run/##bVHbbsIwDH3PV1iRGS0kKhShSUgI/mOdEOq87SFg1jBtUttv70JaemNJZMnn2MeXXPiHMvtJxlT4DlvIK0y3ajFbCTxmH7awxsI02ukdT/WxmMBp5owhZ/P5HNMXPOjlaykwrUoh9oEAd1SwD5YK3FuHCuQNijTrBLrT@RxxMuTHsR0ow1Z/rWClYHHXdzrujlI4GRBjvh/U93tVYl/l2Vfp2npo0AN3lG8ajazHeDgdJ@NZYr@ruJ6liX1s9r@1cN1uCAVMIPeCSL8XSq/0pgBtSmdyn4qHmsrIfpurA57cX9esJyQGsiGlpi/Zashw02ZtmgwpRFn9AQ "PowerShell – Try It Online") Unrolled: ``` $counters=,0*3 $args|select-string '/?-?o'-AllMatches|% Matches|% Length|%{++$counters[$_-1]} $counters ``` [Answer] # [J](http://jsoftware.com/), ~~36~~ 25 bytes -11 bytes thanks to cole! ``` 2-/\0,~1 1 2%~1#.'o/-'=/] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jXT1Ywx06gwVDBWMVOsMlfXU8/V11W31Y/9rcilwpSZn5CukAbWBgL5uvm6MAgIg@Pn6@TGo8uhqEYLqqIYq5AMhmrL8GBQJdHlkRch8JJMR1mM4BCwAE80H6YMaBRbLR/VFfgy6m6HSmG7C5mNQuIC8@R8A "J – Try It Online") ## Original solution # [J](http://jsoftware.com/), 36 bytes ``` [:(-/@}:,-/@}.,{:)1 1 2%~1#.'o/-'=/] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o600dPUdaq10QKSeTrWVpqGCoYKRap2hsp56vr6uuq1@7H9NLgWu1OSMfIU0oAkgoK@brxujgAAIfr5@fgyqPLpahKA6qqEK@UCIpiw/BkUCXR5ZETIfyWSE9RgOAQvARPNB@qBGgcXyUX2RH4PuZqg0ppuw@RgULiBv/gcA "J – Try It Online") ## Explanation: ``` 'o/-'=/] compare the input with each one of "o/-" characters / the result is a 3-row matrix / 1#. add up each row to find the number of occurences of each character, the result is a vector of 3 items 1 1 2%~ divide the last item by 2 to find the number of bodybuilder Jimmys [:( ) use the result to construct the following vector: {: the last item , appended to -/@}. the difference of the second and the third items , appended to -/@}: the difference of the first and the second items ``` A sample [J](http://jsoftware.com/) session: ``` a=:' /-o-\ o /-o-\ o/o\' 'o/-'=/a 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 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 0 0 1 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1#.'o/-'=/a 5 3 4 1 1 2%~1#.'o/-'=/a 5 3 2 (-/@}:,-/@}.,{:)1 1 2%~1#.'o/-'=/a 2 1 2 ``` [Answer] # Excel as CSV, 130 bytes ``` ,=LEN(A3)-LEN(A4) =SUBSTITUTE(A1,"-o",""),=(LEN(A2)-LEN(A3))/2 =SUBSTITUTE(A2,"/o",""),=(LEN(A1)-LEN(A2))/2 =SUBSTITUTE(A3,"o","") ``` Insert input in space before first `,`, save as .csv, open in Excel. Outputs Dwarfs, Acrobats and Bodybuilders in `B1`, `B2` and `B3` respectively. --- **Excel, 244 bytes** ``` =LEN(SUBSTITUTE(SUBSTITUTE(A1,"-o",""),"/o",""))-LEN(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"-o",""),"/o",""),"o",""))&" "&(LEN(SUBSTITUTE(A1,"-o",""))-LEN(SUBSTITUTE(SUBSTITUTE(A1,"-o",""),"/o","")))/2&" "&(LEN(A1)-LEN(SUBSTITUTE(A1,"-o","")))/2 ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 20 bytes[SBCS](https://github.com/abrudz/sbcs) ``` 2-/2÷⍨@2+/'o/-x'∘.=⎕ ``` [Try it online!](https://tio.run/##fZDBSgMxEIbv@xRzm4PGdCNFEAo@yF4WS0QsjoQcWkpvUqttiiCFXrz05AuIUPDkm8yLrJPtlu1uxQlhd/7/y88k@cNA9Uf5gG4KXq5uiaevnYRnT7YwSpufLw4fV@ZEI2k1RJ6tz3qCFQIkVlAOy5QX3zgZ4ymKEbdDDp@CvqQ8fZP@2qFF4PAO3uV9ew@eQD6Fl/NjQfl54@TXctheCl6mbkV3PH9EusNJghBLK1IZ1FX3pClr@m22FndZHlJZ3SoZSFaLpaxhtP1D6LBHD104h44k1zMcTVMKe5XiuSqq1Kh5FdqRkmwk@SLOXPnHQ/117/g6CP9VTE7B/AI "APL (Dyalog Unicode) – Try It Online") [Answer] # [Kotlin](https://kotlinlang.org) ~~131~~ ~~130~~ ~~129~~ ~~121~~ ~~117~~ ~~97~~ ~~96~~ 88 bytes ``` fun String.j(b:Int=count{'-'==it}/2,a:Int=count{'/'==it})=listOf(count{'o'==it}-a,a-b,b) ``` [Try it online!](https://tio.run/##bY8/b8IwEMVn@BQnhIQtxUTqiBqkjkwMZczitKQ9SO9QfKhUKJ/dJQ40DtTTvd97vj97lgrJ@/JI8Co10sd8p4rFiiR74yPJeWZmWYbSpE@JjXHaYZ1V6GRdqivmDhubWFMkhQ6NvyySsgt4qWv789yNWWo4j0cl16AUJuA0IIGdf6N8ruh9e1I6BEaHS1gqUpPN1glMcaJjOHW9Vu6yuh7YObV2M268Tw2bHPrXa045j/WwHn7wDHzPOUT/jHs/DsU62uhhXgA3ym362iAwHi7LXfLW73H@f@e0R/8C "Kotlin – Try It Online") Edit - Wew, got it under 100! I doubt I can shrink it more, but only time will tell... Edit - Spoke too soon, dropped one more byte by using a list instead of a string Edit - minus 8 bytes thanks to AsoLeo suggesting using a extension function [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~39~~ 35 bytes *Edit:* -4 bytes thanks to [@FryAmTheEggMan](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) ``` ^((o)|(/o.)|(/-o-.)| )* $#2 $#3 $#4 ``` [Try it online!](https://tio.run/##K0otycxLNPz/P05DI1@zRkM/Xw9E6ubrAmkFTS0uFWUjBRVlYyA2@f8fJB6jAAIIFhSABWCi@Qr6@TFABJfIR9EAkgRxAQ "Retina – Try It Online") **Explanation:** A simple replace stage. It finds all matches of the regex `^((o)|(/o.)|(/-o-.)| )*` (which should result in one match - the whole string) and replaces it by the number of captures of groups 2, 3, and 4. Here is the regex broken down: ``` ^((o)|(/o.)|(/-o-.)| )* ^ start at the beginning of the string ( )* have any amount of Jimmy / spaces | | | select one of: (o) capturing group 2 - dwarf (/o.) capturing group 3 - acrobat (/-o-.) capturing group 4 - bodybuilder ``` We have to start with `^` or the end of the input counts as a match too. In the substitution syntax of Retina, `$n` references the nth capturing group, and the modifier `#` counts how many matches it made. [Answer] # [Python 3](https://docs.python.org/3/), ~~69~~ ~~66~~ ~~60~~ 56 bytes -4 bytes thanks to @Maarten Fabré ``` g=input().count b,c=g('/'),g('/-') print(g('o')-b,b-c,c) ``` [Try it online!](https://tio.run/##VUs5CsAgEOx9hZ0uuLFI7U@stDA2rgQt8nrjhhxkGJiLqUfbqKxjJJdL7U3DEqmXJoKJLmllFRgWVCDqnkvTM5ECDCZgNBHGkBYJvWR87sZVPC1JS37yHeh34JGjPwE "Python 3 – Try It Online") [Answer] # JavaScript, 55 bytes Searches the string using a regex pattern matching `o`, `o-`, or `o-\`; increments the corresponding count in an array, using the length of each match to determine the index. ``` s=>s.replace(/o-?\\?/g,m=>a[m.length-1]++,a=[0,0,0])&&a ``` [Try it online!](https://tio.run/##hVDRDkNAEHz3FfckhHNomj7hI/roJC56VHOsIO3n6xHC0ejO087u7dzMi71Zl7Vl0@MaHnzIg6ELws5peSNYxg0COKI0IoVdBSGLK0fwuuif2Essy2ZB7NoSianrbCAEeRJXLYO6A8EdAYWRG/e@LevCadknRWMRDJiitdYeCFB1vt/dkKlpapqUvKILcv9IIpDYHQGqDPbz7ZLSL7q@1L2d6K5fP5iYiIWF8eosNHGgJgBU9evLiP0zv/Pro6FfYcJsafgC "JavaScript (Node.js) – Try It Online") [Answer] # [Clojure](https://clojure.org/), 78 bytes ``` (defn ?[s](def c #(count(re-seq % s)))[(-(c #"o")(c #"/"))(c #"/o")(c #"/-")]) ``` [Try it online!](https://tio.run/##bVBJDoMwDLzzCitVpfiQ8gQeApxoEK1oXJKgPp9mISlLnYOtyXg8djfSc9Zy4crAa7L2ZqWxuPC77BVUtWl9BR1ceEezslxLYeQEVzCIWHPB3RcjhiGXDNciI4JhG@WAlAQGPkpBomngFxuASvLVjnLib1CGRVC3H1rVgdw7UCm2558jYcfaAVl/0E5/4@RsKiIZp9CfRCNMh8Uo8dOYnma/RmKdff69Ba1OC/7WD2VHBbzy90af3WViHnTIbgTi8gU "Clojure – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 63 bytes ``` Reverse@{a=(m=CharacterCounts@#)["-"]/2,b=m["/"]-a,m["o"]-a-b}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Pyi1LLWoONWhOtFWI9fWOSOxKDG5JLXIOb80r6TYQVkzWklXKVbfSCfJNjdaSV8pVjdRB8jIBzF0k2rV/gcUZeaVRKdFKymAgL5uvm5MjAICIAnk6@eDWChKMNQjiSrFxv4HAA "Wolfram Language (Mathematica) – Try It Online") 55 bytes if the pointless order requirement is dropped... [Answer] # [R](https://www.r-project.org/), 63 bytes Uses Regex matching to find and count the Jimmys. ``` library(stringr) str_count(scan(,''),c('(?<![/-])o','/o','/-')) ``` [Try it online!](https://tio.run/##K/r/PyczqSixqFKjuKQoMy@9SJMLyIhPzi/NK9EoTk7M09BRV9fUSdZQ17C3UYzW143VzFfXUdcHE7rqmpr/FdQVFBT0dfN1YxQQAMHP18@PQZVHYoPlUPWo//8PAA "R – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 25 bytes ``` {|-':|1 1 .5*+/x=\:"o/-"} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qukZX3arGUMFQQc9US1u/wjbGSilfX1ep9n@agpICEOjr5uvGxCggAJJAvn4@iIWiBEM9kqjSfwA "K (oK) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, 41 bytes ``` $_=1*s/o(?!\\|-)//g.$".1*s|/o||g.$".y/o// ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tZQq1g/X8NeMSamRldTXz9dT0VJDyhWo59fUwPmVOrn6@v/t3ZItNXQtP6vAAL6uvm6MQoIgODn6@fHoMqjq0UIckHY@UCIJpsfgyKBLo@sCJnPhWQZhrVgAZhoPkg51ASwWD6qm/NjYC6ECmM6AZu/QL7/l19QkpmfV/xf19dUz8DQ4L9uQQ4A "Perl 5 – Try It Online") Counts the number of times `o` appears without being followed by `\` or `-` to find the dwarves and removes them from the string. Then counts the number of times `/o` appears to find the acrobats and removes them from the string. Then counts the number of `o` remaining to determine the body builders. Inserts spaces between the numbers and implicitly outputs the result. [Answer] # [Ruby](https://www.ruby-lang.org/), 50 bytes ``` ->s{%w(o /o -o).map{|x|s.scan(/[\/-]?o/).count x}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664WrVcI19BP19BN19TLzexoLqmoqZYrzg5MU9DPzpGXzfWPl9fUy85vzSvRKGitvZ/gUJatJKCvm6@bkyMAgggMaEAIgIXB5kO5OZDFEGE81G1gRWABZRi/wMA "Ruby – Try It Online") [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 135 bytes ``` I =INPUT B I '-o' = :F(A) B =B + 1 :(B) A I '/o' = :F(D) A =A + 1 :(A) D I 'o' = :F(O) D =D + 1 :(D) O OUTPUT =+D ' ' +A ' ' +B END ``` [Try it online!](https://tio.run/##Vc2xCgMhDAbgWZ/i37xDRAqdDjIotnDL2eFuu6lzaYa@P15staWJYMwXyevJd36cS1EzaF5u26qjlMaxAanpOoRRqwiKsDipaYijDtV99yQeQKG5jKfqnbNwAqXGMp1V3lbZA7IJRtKGzxX1ZUmlwDt2O2r8qhbvRu8yPO9yvsB/HyrW5wE "SNOBOL4 (CSNOBOL4) – Try It Online") Removes `-o`, `/o`, and `o` from the string and increments the appropriate counters each time. Leaves behind a lot of arms and legs (`/-\`, `\`, and nothing). [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 118 bytes ``` : c -rot 0 tuck do over i + c@ 3 pick = - loop nip nip ; : f 2dup '/ c >r 2dup '- c 2/ -rot 'o c i - . r> over - . . ; ``` [Try it online!](https://tio.run/##bU/LDoIwELzzFRMuHEypwRtE4x/oAW7ceCjRuE0tJn49LhQtDzdt2pndnZ2tSZuruNT903UxCghNBluYtrihJNCr0miwQXHEDqphdg@BO5HCo7E38WLUiMpWIZAscdAjEAwiaSUDYtBwawh9sLL9P0TCY5VtMG9VodAIfZyy9JylMXxWZoZP4j19DCEFiRwuHCZJ@Ty/rHWkD/VTBC@6rKF8lljmp0VTPMq6uSsHA/Flqe8ZZQaO5vYpn5sdk2s3/xYl66f7AA "Forth (gforth) – Try It Online") ### Explanation * Get Count of `/`, `-`, and `o` characters * Bodybuilder is number of `-` characters divided by 2 * Acrobat is number of `/` characters minus the number of body builders * Dwarf is number of `o` characters minus the number of Acrobat and Bodybuilders ### Code Explanation ``` \ c counts the number of occurrences of the given character in a string \ stack usage is ( c-addr u1 w1 - u ) : c \ start a new word definition -rot 0 tuck \ sets up parameters for a counted loop do \ loop from 0 to string-length - 1 (inclusive) over i + \ get the address of the current character in the string c@ \ get the ascii value of the current character 3 pick = \ compare it to the character we're counting - \ subtract result from the accumulator (subtract because -1 = true in forth) loop \ end the loop nip nip \ remove extra values from the stack ; \ end the word definition \ Main function : f \ start a new word definition 2dup \ duplicate the string address and length '/ c >r \ count the number of '/' characters and stick the result on the return stack 2dup '- c 2/ \ count the number of '-' characters and divide by 2 -rot 'o c \ move the string to the top of the stack and count the number of 'o characters i - . \ calculate number of dwarf jimmy's and print r> over - . \ calculate number of acrobat jimmy's and print (drop '/' count from return stack) . \ print number of body-builder jimmy's ; \ end word definition ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` …-/oS¢ć;š0š¥R ``` This one could be **12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** by removing the `R` if an output-order of `[bodybuilder, acrobat, dwarf]` would have been allowed. [Try it online](https://tio.run/##yy9OTMpM/f//UcMyXf384EOLjrRbH11ocHThoaVB//8rgIC@br5ujAICIPj5@vkxqPLoahGC@QA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TpuSZV1BaYqWgZF@pw6XkX1oC4/1/1LBMVz8/@NCiI@3WRxcaHF14aGnQf51D2@z/KyjkKyjo58coQACQo6Cvm68bAyYgfCgAKuKCMCBSCAk4Px9sELI8ulqEIBfMwnx0WYhj4BLo8siKUB2HsAzDWmQ/AU0EKoeaABbLR3VzfgzMhZihgMdfIN9z5efnAwA). Minor equal-bytes alternative: ``` …-/oS¢R`;0)üα ``` [Try it online](https://tio.run/##yy9OTMpM/f//UcMyXf384EOLghKsDTQP7zm38f9/BRDQ183XjVFAAAQ/Xz8/BlUeXS1CMB8A) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TpuSZV1BaYqWgZF@pw6XkX1oC4/1/1LBMVz8/@NCioARrA83De85t/K9zaJv9fwWFfAUF/fwYBQgAchT0dfN1Y8AEhA8FQEVcEAZECiEB5@eDDUKWR1eLEOSCWZiPLgtxDFwCXR5ZEarjEJZhWIvsJ6CJQOVQE8Bi@ahuzo@BuRAzFPD4C@R7rvz8fAA). **Explanation:** ``` …-/o # Push string "-/o" S # Split to a list of characters: ["-","/","o"] ¢ # Count the occurrence of each character in the (implicit) input-string ć # Extract the head; pop and push head and remainder-list ; # Halve this head š # And prepend it back in front of the remainder-list 0š # Then also prepend a 0 ¥ # Get the deltas (forward differences) R # And reverse the list to get the required order of output-counts # (after which the result is output implicitly) …-/oS¢ # Same as above R # Reverse this list ` # Pop the list and push its values separately to the stack ; # Halve the top value on the stack 0 # Push a 0 ) # Wrap all values on the stack into a list ü # For each overlapping pair of values: α # Get the absolute difference between the two values # (after which the result is output implicitly) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~99~~ ~~98~~ 96 bytes -1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) ``` o,S,d,c;f(char*s){for(o=S=d=0;c=*s++;o+=c>93)d+=c==45,S+=c==47;printf("%d %d %d",o-S,S-d,d/=2);} ``` [Try it online!](https://tio.run/##bU/LasMwEDxHX7EIAnIs4dIHpRXKL7Sg5OZLkLDrQ73BSnMJ/nZHlrHiR1eCXY1mZ2eNKI3pOuSaW25kwczPqdm55FZgw1BpZdWTNGrn0lRiqsz@4yWxPiv1@sb1ULzLc1PVl4LRrYVwKUehuRaW20w9J7LtrlhZKIM6eHlyI5vY5PL663j4Ph4@gXJwiSSbgoV0/rs4RvOa@kdLiOfD76mqWegvGYU@MoEiz@EREwAz7KsZZcWfoP2gKAzoz4KFQ2f8WRJmrBkQpSfz11YGJOIYWke9AcbFOjjyH@ZHwtrdv8vj6K/t7g "C (gcc) – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 17 bytes ``` `-/o`f$vOḣ$½p0pṘ¯ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60-%2Fo%60f%24vO%E1%B8%A3%24%C2%BDp0p%E1%B9%98%C2%AF&inputs=%2F-o-%5C%20%20%20%20%20%2F-o-%5C%20%20%20%20%20%20%20%20%20%20%20%20%2F-o-%5C%2F-o-%5C%20%20%20o%20%2Fo%5C%2Fo%5C%20%20%20%20%2F-o-%5Co%20%2F-o-%5C%20%20%20%20%20%20%20%2Fo%5C%2F-o-%5C&header=&footer=) [Answer] # [Ly](https://github.com/LyricLy/Ly), 87 bytes ``` 0>0>0>i['-=[pl'o=[p<1+>0]pp0]p'/=[p<<1+>>0]p'o=[p<<<1+>>>0]psp]<s<l-:l+sp<l-u>' ou>' ou ``` [Try it online!](https://tio.run/##VUtJCsAwCPxKbh6KJL2WNB9J8oBCQCH00NdbbbrQUUdnBtshEpLVlgHXzA1IOc5TCpVZB7xpM8wZ6ZCmO9fYY8OlTZ117wkcDRLxSFic4btuXMbjkvNUtN@Afg8WmjwB "Ly – Try It Online") I think this could be shorter, but I've hit a brick wall at this point. At a high level, it counts the number of `-` (matched), `/` and `o` characters, then subtracts to remove duplicate counts before printing the results. First is initializes counters to `0` on three different stacks. ``` 0>0>0> ``` Then it reads the input onto the stack a codepoints, and loops over each character. The code also saved the current character to the backup cell with `s` so we can only count matched `-` characters. ``` i[ ... sp] ``` The first check increments the counter on the first stack if it's `-` and the previous character was `o`. That works since the characters are processes in reverse order. ``` '-=[pl'o=[p<1+>0]pp0]p ``` The second check increments the counter on the second stack anytime the code hits a `/` character. ``` '/=[p<<1+>>0]p ``` And the last check increments the counter on the third stack when the code finds a `o` character. ``` 'o=[p<<<1+>>>0]p ``` Once all the input has been scanned and counted, to code subtracts the number of matched `-` characters (bodybuilders) from the number of `/` characters to find the number of acrobats. ``` <s<l- ``` Then it remember the number of acrobats plus the number of bodybuilders by stashing the sum of the two in the backup cell. ``` :l+sp ``` Then is subtracts that from the number of `o` characters to get the final counter and prints it. ``` <l-u ``` The last bits just shift to the next counter and prints with a space appended. >' ou And does the same shift/print to output the last counter. ``` >' ou ``` ]
[Question] [ Your challenge is to write a program which, given a year, outputs the number of "Friday 13ths" in it. **Rules & Details:** * You can take input via `STDIN`, or as an argument passed to your program. * You should output the result to `STDOUT`. * You may assume that input will be a valid year, and does not pre-date the Gregorian calendar (undefined behaviour is permitted in these cases). * Calendar/Date libraries are allowed. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code (in bytes) wins. [(Related challenge link)](https://codegolf.stackexchange.com/questions/976/next-friday-the-13th) [Answer] # Mathematica ~~49 46 45 44~~ 42 As a **pure function**: 42 chars ``` DayName@{#,m,6}~Table~{m,12}~Count~Friday& ``` Example ``` DayName@{#,m,6}~Table~{m,12}~Count~Friday&[2013] ``` > > 2 > > > --- As a **named function**: 44 chars ``` f=DayName@{#,m,6}~Table~{m,12}~Count~Friday& ``` Examples ``` f[1776] f[2012] f[2013] f[2014] ``` > > 2 > > 3 > > 2 > > 1 > > > [Answer] ## Ruby, ~~49 48 47~~ 46 ``` f=->m{(1..12).count{|i|Time.gm(m,i,6).friday?}} ``` Edit: Shaved a character by going back a week, thanks to Jan, and another by switching from Time.new to Time.gm Edit: At the expense of obfuscating it a bit more, I can get to 46 with ``` f=->m{(1..12).count{|i|Time.gm(m,i,8).wday<1}} ``` [Answer] ## Powershell, ~~68~~ ~~63~~ ~~58~~ ~~52~~ 50 Thanks Iszi for the tip. ``` $n=$args;(1..12|?{!+(date $n-$_).DayOfWeek}).Count ``` Using the fact that if the 1st day in the month is Sunday, the 13th will be Friday. I've also tried: ``` (1..12|?{!+(date $args-$_).DayOfWeek}).Count ``` but it's not the same `$args` inside the script block. [Answer] ## bash ~~47~~ 36 ``` seq -f$1-%g-6 12|date -f-|grep -c ^F ``` Thanks @DigitalTrauma for saving 10 chars by using `seq` with default start to `1`. ~~``` date -f<(printf "%s\n" $1-{1..12}-6)|grep -c ^F ```~~ (Previous version using `echo` present a bug because of the empty line when `<(echo $1-{1..12}-6$'\n')`. So this function worked fine until today **is** a Friday. ### Lets see: ``` set -- 2013 seq -f$1-%g-6 1 12|date -f-|grep -c ^F 2 date -f<(printf "%s\n" $1-{1..12}-13)|grep -c ^F 2 ``` This is **locale** dependant, so if this don't work, you may have to ``` export LANG=C ``` or ``` LANG=C date -f<(printf "%s\n" $1-{1..12}-13)|grep -c ^F ``` ### Into a function; +7 -> 43 ``` f(){ seq -f$1-%g-6 12|date -f-|grep -c ^F;} f 2013 2 for i in {2010..2017};do echo $i $(f $i) ;done 2010 1 2011 1 2012 3 2013 2 2014 1 2015 3 2016 1 2017 2 ``` ### Bonus: +78 -> 121 From there, if my function become: ``` f(){ o=();for t in $(seq -f$1-%g-6 12|date -f- +%a,%b);do [ "${t:0:1}" = "F" ]&&o+=(${t#*,});done;echo ${#o[@]} ${o[@]};} ``` or ``` f(){ o=(); for t in $(seq -f$1-%g-6 1 12|date -f- +%a,%b);do [ "${t:0:1}" = "F" ]&&o+=(${t#*,}) done echo ${#o[@]} ${o[@]} } for i in {2010..2017};do echo $i $(f $i) ;done 2010 1 Aug 2011 1 May 2012 3 Jan Apr Jul 2013 2 Sep Dec 2014 1 Jun 2015 3 Feb Mar Nov 2016 1 May 2017 2 Jan Oct ``` [Answer] Not using any libraries or built-in date functions: # Golfscript – 51 ``` ~..({4/.25/.4/--@}2*2*\3*+- 14%' [3/=RI[)a%:*.'\=5% ``` > > `' [3/=RI[)a%:*.'` could as well be `'feefefgeeffgfe'` > > > # Python – ~~82~~ 79 Essentially the same algorithm. ``` l=lambda y:y/4-y/100+y/400 i=input() print"21232211321211"[(2*i+3*l(i)-l(i-1))%14] ``` Using [this trick](//codegolf.stackexchange.com/a/41742/11354), this can be golfed down further to: ``` l=lambda y:y/4-y/100+y/400 i=input() print 94067430>>(4*i+6*l(i)-2*l(i-1))%28&3 ``` --- > > This exploits the fact that, calender-wise, there are only 14 different years, which are distinguishable by their last day and whether they are leaping. `l` calculates the number of leap years up to its argument (if the Gregorian calendar extended backwards to the year 1). `(2*i+3*l(i)-l(i-1))%14` is short for `l(i)-l(i-1)+(i+l(i))%7*2`, where `l(i)-l(i-1)` tells us whether the argument is a leap year and `i+l(i)` sums up the shifts of the last day (one in a normal year, two in a leap year). > > > [Answer] ## R ~~76~~ ~~72~~ 57 ``` sum(format(as.Date(paste(scan(),1:12,1,sep="-")),"%w")<1) ``` [Answer] ## Python2.7 ~~90~~ 86 ``` from datetime import* s=c=0 exec's+=1;c+=date(%d,s,9).weekday()<1;'%input()*12 print c ``` Monday the 9th may not have quite the same ring to it but works just as well. Edit: A year and a half to notice that `date` is shorter than `datetime` :) [Answer] # C ~~301+~~ 287 ``` main(int x,char**v){char p[400],*a[]={"abbababbacaacbac","bacabbb","baabbaca","abbb","aabbacaac","abbbbcaac","abbbbaabb"},*b="adcadcadcaebcadcadcafbcadcadcagbcadcadcadc";int c=0,i,y=atoi(v[0]);for(i=0;i<42;i++)strcpy(&p[c],a[b[i]-'a']),c+=strlen(a[b[i]-'a']);printf("%d",p[y%400]-'`');} ``` Not the shortest answer, but uses no libraries. [Answer] # C (~~151~~ ~~145~~ ~~137~~ ~~131~~ 130 chars) I am surprised to see that there is only one other solution that doesn't use built-in calendar tools. Here is a (highly obfuscated) mathematical approach, also in C: ``` f(x){return(x+(x+3)/4-(x+99)/100+!!x)%7;}main(int x,char**v){int y=atoi(v[1])%400,a=f(y+1);putchar('1'+((f(y)&3)==1)+(a>2&&a-5));} ``` (The above compiles in GCC with no errors) # Alternative solution: C (287->215 chars) I rather enjoyed [Williham Totland's solution](https://codegolf.stackexchange.com/a/15812/7511) and his use of compression. I fixed two small bugs and tweaked the code to shorten its length: ``` main(int x,char**v){char p[400],*a[]={"1221212213113","213122221122131","12213113","22213113","22221122","2131"},*b="abababafcbababafdbababafebababab";*p=0;for(;*b;b++)strcat(p,a[*b-97]);putchar(p[atoi(v[1])%400]);} ``` [Answer] # PHP, 82 `<?for($i=1,$c=0;$i<13;$i++)$c+=(date("N",mktime(0,0,0,$i,1,$argv[1]))==7);echo $c;` Based on "Any month that starts on a Sunday contains a Friday the 13th, and there is at least one Friday the 13th in every calendar year." From <http://en.wikipedia.org/wiki/Friday_the_13th> [Answer] ## JavaScript, 70 ``` f=function(a){b=0;for(c=12;c--;)b+=!new Date(a,c,1).getDay();return b} ``` [Answer] # [APL (Dyalog APL)](https://www.dyalog.com/) with [cal](http://dfns.dyalog.com/n_cal.htm) from [dfns](http://dfns.dyalog.com/), 29 [bytes](http://meta.codegolf.stackexchange.com/q/9428/43319) ``` +/{13∊⍎,⍉3↑¯5↑⍉2↓cal⍵}¨⎕,¨⍳12 ``` [Try it online!](https://tio.run/nexus/apl-dyalog#e9TRnsb1qG@qc6R6Slpesfp/bf1qQ@NHHV2Pevt0HvV2Gj9qm3hovSmQBHKMHrVNTk7MedS7tfbQCqAmHSDZu9nQ6P@jjvb/aVyG5uZmXGlcRgaGRhDKGEKZAAA "APL (Dyalog APL) – TIO Nexus") `⍳ 12` the integers one through twelve `⎕ ,¨` take numeric input and prepend to each of the twelve numbers `{`…`}¨` on each of the pairs, apply the function…  `cal⍵` get a calendar for that year-month  `2 ↓` drop two rows (caption and days)  `⍉` transpose (so we can address columns instead of rows)  `¯5 ↑` take the last five (two digits for each of Friday and Saturday plus one space)  `3 ↑` take the first two (two digits for Friday plus a space)  `⍉` transpose (so we get reading order)  `,` ravel  `⍎` execute as APL expression (gives list of Fridays' dates)  `13 ∊` is thirteen a member of that list? `+/` sum the 12 Booleans --- Using [@Wrzlprmft's algorithm](https://codegolf.stackexchange.com/a/25663/43319), we can do it without libraries for 53 bytes: ``` '21232211321211'⊃⍨14|2 3 ¯1+.×⊢,0≠.=400 100 4∘.|-∘0 1 ``` `-∘0 1` subtract zero and one `400 100 4 ∘.|` division remainder table for the two years (across) divided by these numbers (down) `0 ≠.=` inner "product" with 0, but using ≠ and = instead of +.× `⊢ ,` prepend the unmodified argument year `2 3 ¯1 +.×` inner product with these numbers `14 |` division remainder when divided by fourteen `'21232211321211' ⌷⍨` index into this string [Answer] # k 64 characters ``` {+/6={x-7*x div 7}(.:')x,/:(".",'"0"^-2$'$:1+!:12),\:".13"}[0:0] ``` Reads from stdin [Answer] ## Common Lisp (CLISP), 149 ``` (print (loop for i from 1 to 12 count (= 4 (nth-value 6 (decode-universal-time (encode-universal-time 0 0 0 13 i (parse-integer (car *args*)) 0)))))) ``` [Answer] # C# ~~110~~ ~~101~~ ~~93~~ 92 ``` int f(int y){int c=0;for(int i=1;i<13;i++)c+=new DateTime(y,i,8).DayOfWeek>0?0:1;return c;} ``` # C# Linq 88 ``` int g(int y){return Enumerable.Range(1,12).Count(m=>new DateTime(y,m,8).DayOfWeek==0);} ``` Thanks to Jeppe Stig Nielsen for linq and suggestion of checking for sunday on the 8th. Thanks to Danko Durbić for suggesting `>` instead of `==`. [Answer] # PHP, 55 bytes ``` for(;++$i<13;)$c+=!date(w,strtotime($argn.-$i));echo$c; ``` Run with `echo <year> | php -nR '<code>'`. Basically the same that [Oleg](https://codegolf.stackexchange.com/a/15823/55735) tried and [Damir Kasipovic](https://codegolf.stackexchange.com/a/25487/55735) did, just with better golfing: Every month that starts with a sunday, has a Friday the 13th. So I loop through the months and count the first days that are sundays. **breakdown** ``` for(;++$i<13;) // loop $i from 1 to 12 $c+=! // 4. if result is not truthy (weekday==0), increment $c date(w, // 3. get weekday (0 stands for Sunday) strtotime( // 2. convert to timestamp (midnight 1st day of the month) $argn.-$i // 1. concatenate year, "-" and month ) ) ; echo$c; // output ``` [Answer] # K, 42 ``` {+/1={x-7*x div 7}"D"$"."/:'$+(x;1+!12;1)} ``` . ``` k){+/1={x-7*x div 7}"D"$"."/:'$+(x;1+!12;1)}'1776 2012 2013 2014 2 3 2 1 ``` [Answer] # Bash (52 47 characters) ``` for m in {1..12};do cal $m $Y;done|grep -c ^15 ``` [Answer] # Rebol, 63 ``` f: 0 repeat m 12[d: do ajoin["6-"m"-"y]if d/weekday = 5[++ f]]f ``` Usage example in Rebol console: ``` >> y: 2012 == 2012 >> f: 0 repeat m 12[d: do ajoin["6-"m"-"y]if d/weekday = 5[++ f]]f == 3 ``` Alternative solution which collects all the Friday 13th in given year is: ``` >> collect[repeat m 12[d: do ajoin["13-"m"-"y]if d/weekday = 5[keep d]]] == [13-Jan-2012 13-Apr-2012 13-Jul-2012] ``` [Answer] ## Bash and Sed, 39 ``` ncal $1|sed '/F/s/13/\ /g'|grep -c ^\ 2 ``` `ncal` prints a calendar for the given year with days of the week down the left. `sed` with a `/g` flag subs out all 13s with newlines `grep -c` counts the lines that start with " 2" (20 always follows 13) Thanks to @DigitalTrauma for finding a bug in my old version and proposing a solution! [Answer] # Scala, ~~76~~ 68 characters In 78 chars: `def f(y:Int)=0 to 11 count(new java.util.GregorianCalendar(y,_,6).get(7)==6)` Nothing out of ordinary, except for using magical numbers for `DAY_OF_WEEK = 7` and `FRIDAY = 6`. 68 character version: `def f(y:Int)=0 to 11 count(new java.util.Date(y-1900,_,6).getDay==5)` Yes, Java changed values of day of the week constants between API's. [Answer] # Python 195 / 204 Works only for previous years, because `monthdatescalendar` returns a calendar for the given year until *now*. I think there is a lot of optimizing potential left :). ``` import calendar, sys c=calendar.Calendar() f=0 for m in range(1,12): for w in c.monthdatescalendar(int(sys.argv[1]),m): for d in w: if d.weekday() == 4 and d.day == 13: f=f+1 print(f) ``` Another solution, works for every date but it isn't smaller: ``` import datetime,sys y=int(sys.argv[1]) n=datetime.date f=n(y,1,1) l=n(y,12,31) i=0 for o in range(f.toordinal(), l.toordinal()): d=f.fromordinal(o) if d.day == 13 and d.weekday() == 4: i=i+1 print(i) ``` [Answer] ## Perl 6, ~~55~~ 53 ``` {sum (1..12).map: {Date.new($_,$^a,1).day-of-week>6}} ``` Old answer: ``` {sum (1..12).map: {Date.new($_,$^a,13).day-of-week==5}} ``` [Answer] **Python(v2) 120** ``` import datetime as d,sys s=0 for m in range(1, 13): if d.datetime(int(sys.argv[1]),m,6).weekday()==4: s=s+1 print s ``` [Answer] ## Perl + lib POSIX 55 With the idea of not looking for `13th` but first, and as `sunday` is `0` this let save 3 chars! Thanks @ Iszi and Danko Durbić! ``` $==$_;$_=grep{!strftime"%w",0,0,0,1,$_,$=-1900}(0..11) ``` Could compute 2010 to 2017 (for sample) in this way: ``` perl -MPOSIX -pE '$==$_;$_=grep{!strftime"%w",0,0,0,1,$_,$=-1900}(0..11)' <( printf "%s\n" {2010..2017}) 11321312 ``` (Ok, there is no *newline*, but that was not asked;) ### Old post: 63 ``` $==grep{5==strftime"%w",0,0,0,13,$_,$ARGV[0]-1900}(0..11);say$= ``` ### In action: ``` for i in {2010..2017};do echo $i $( perl -MPOSIX -E ' $==grep{5==strftime"%w",0,0,0,13,$_,$ARGV[0]-1900}(0..11);say$= ' $i ); done 2010 1 2011 1 2012 3 2013 2 2014 1 2015 3 2016 1 2017 2 ``` [Answer] In **Smalltalk** (Squeak/Pharo flavour), implement this method in Integer (**86** chars) ``` countFriday13^(1to:12)count:[:m|(Date year:self month:m day:13)dayOfWeekName='Friday'] ``` Then use it like this: `2014countFriday13`. Of course, we could use a shorter name, but then it would not be Smalltalk [Answer] # C++ - Too many bytes :( I tried a solution which doesn't make use of any date libraries. I found a pretty cool (if I may say so myself) solution. Unfortunately I can't get it shorter than this, which really bugs me because it feels like there should be a better way. The solution hinges on [this algorithm](http://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Implementation-dependent_methods_of_Sakamoto.2C_Lachman.2C_Keith_and_Craver) which is only 44 bytes in itself. Unfortunately I need another 100 bytes to wrap it nicely... ``` #include<stdlib.h> main(int,char**v){int f=0,d,m,y;for(m=1;m<13;++m)d=13,y=atoi(v[1]),(d+=m<3?y--:y-2,23*m/9+d+4+y/4-y/100+y/400)%7-5||++f;return f;} ``` Output through the return code (in C++, using `cout` or `printf` or anything like that requires another `#include`, which would blow up the solution even more). Driver / test program: ``` # Make sure we're not running an old version rm doomsday.exe gcc doomsday.cpp -o doomsday.exe ./doomsday.exe 1776 echo 1766: $? ./doomsday.exe 2012 echo 2013: $? ./doomsday.exe 2013 echo 2013: $? ./doomsday.exe 2014 echo 2014: $? echo `wc doomsday.cpp -c` characters ``` Output of the driver program: ``` $ ./test_doomsday 1766: 2 2013: 3 2013: 2 2014: 1 150 doomsday.cpp characters ``` [Answer] # Clojure, ~~207~~ 187 bytes -20 bytes by getting rid of the `import`, and some whitespace I missed. ``` (import '[java.time LocalDate DayOfWeek])#(loop[d(LocalDate/parse(str %"-01-01"))c 0](if(=(.getYear d)%)(recur(.plusDays d 1)(if(and(=(.getDayOfMonth d)13)(= (.getDayOfWeek d) DayOfWeek/FRIDAY))(inc c)c))c)) ``` Starting on Janauary 1st of the given year, it loops over each day. If the day is Friday the 13th, it increments the count. It continues to loop until it reaches the next year. ``` (import '[java.time LocalDate DayOfWeek]) (defn count-friday-13ths [year] (loop [d (LocalDate/parse (str year "-01-01")) ; Starting date c 0] ; The count (if (= (.getYear d) year) ; If we haven't moved onto the next year... (recur (.plusDays d 1) ; Add a day... (if (and (= (.getDayOfMonth d) 13) ; And increment the count if it's Friday the 13th (= (.getDayOfWeek d) DayOfWeek/FRIDAY)) (inc c) c)) c))) ; Return the count once we've started the next year. ``` [Answer] # PHP, no builtins, 81 bytes ``` echo 0x5da5aa76d7699a>>(($y=$argn%400)+($y>102?$y>198?$y>299?48:32:16:0))%28*2&3; ``` Run with `echo <year> | php -nR '<code>'`. **breakdown** [Weekdays repeat every 400 years.](https://en.wikipedia.org/wiki/Doomsday_rule) In the results for 1600 to 1999 (for example), there is a 28-length period with just three gaps: ``` 0:2212122131132131222211221311 28:2212122131132131222211221311 56:2212122131132131222211221311 84:2212122131132131122 103: 131132131222211221311 124:2212122131132131222211221311 152:2212122131132131222211221311 180:2212122131132131222 199: 131132131222211221311 220:2212122131132131222211221311 248:2212122131132131222211221311 276:221212213113213122221122 300: 2131222211221311 316:2212122131132131222211221311 344:2212122131132131222211221311 372:2212122131132131222211221311 ``` After adjusting the year for these gaps, we can get the result with a simple hash: ``` $y=$argn%400;foreach([300,199,103]as$k)$y<$k?:$y+=16; echo"2212122131132131222211221311"[$y%28]; ``` Not short (95 bytes) but pretty. And we can golf * 4 bytes by using a ternary chain for the offset, * 8 bytes by converting the hash map from a base4 string to integer, * one more by using the hex representation, * and one by merging the expressions. [Answer] # C, 76 bytes A function that accepts a year and returns the count of Fridays the 13th for that year: ``` d(y){return(y+y/4-y/100+y/400)%7;}f(y){return(22>>d(y)&1|2)-(55>>d(y-1)&1);} ``` If a full program is really required, it comes in at **111** bytes, accepting a single argument and printing to standard out: ``` d(y){return(y+y/4-y/100+y/400)%7;}main(y,v)char**v;{y=atoi(*++v);putchar('0'+(22>>d(y)&1|2)-(55>>d(y-1)&1));} ``` # Explanation ``` int day_index(int year) { return (year + year/4 - year/100 + year/400) % 7; } int f(int year) { const char a[] = "2332322"; const char b[] = "1110110"; return a[day_index(year)] - b[day_index(year-1)]; } ``` We split the year into two parts (Jan-Feb and Mar-Dec) so that leap years don't disrupt the calculation. The helper function computes the weekday of New Year's Eve (0 = Sunday). We first use this to determine (in `a`) how many Fridays the 13th are in March-December. Then we use the weekday index of the preceding year to get the count from `b` for January and February. The golfed code uses a bit mask rather than a character array: `a` becomes `22` and `b` becomes `55`. # Demo The demo is [on Try It Online](https://tio.run/##TY5BDoIwEEX3nGKiwbTBaiESg0Wu4cYNaQGbYDGlmjTI1a0tbvyreTP/JcNJx7lzAlk86cY8tUI2sfsDsfuU0jBRiuMjm9u/RpZVVTA26TvDBOX5giT1C8xmt5aK90/RQDkaIYfdrYqkMnCvpUKvQQocTRH4tIMGFC62qTWcIS0KyuBHJWQ0D5QkgTH8lJCH9k6LVrE4QSyuarVdlC34F0MVs6U6R7P78Lavu9GRixqIvD96yaUhXv8C). ``` #include <stdio.h> int main(void) { for (int year = 1990; year < 2050; ++year) { printf("%d: %d\n", year, f(year)); } } ``` ``` 1990: 2 1991: 2 1992: 2 1993: 1 1994: 1 1995: 2 1996: 2 1997: 1 1998: 3 1999: 1 2000: 1 2001: 2 2002: 2 2003: 1 2004: 2 2005: 1 2006: 2 2007: 2 2008: 1 2009: 3 2010: 1 2011: 1 2012: 3 2013: 2 2014: 1 2015: 3 2016: 1 2017: 2 2018: 2 2019: 2 2020: 2 2021: 1 2022: 1 2023: 2 2024: 2 2025: 1 2026: 3 2027: 1 2028: 1 2029: 2 2030: 2 2031: 1 2032: 2 2033: 1 2034: 2 2035: 2 2036: 1 2037: 3 2038: 1 2039: 1 2040: 3 2041: 2 2042: 1 2043: 3 2044: 1 2045: 2 2046: 2 2047: 2 2048: 2 2049: 1 ``` ]
[Question] [ # Challenge You are given an array \$a\$ of integers. With a ***move*** you can **increase or decrease** an element of the array **by 1**. Your task is to ***equalize*** the array, that is make all the elements of the array equal by performing some *moves*. But that's not enough! You also want to make **as few *moves* as possible**. ## Input * A non-empty **array** \$a\$ of integers * Optionally, the **length** of \$a\$. ## Output * The **minimum number of *moves*** needed to *equalize* the array \$a\$. # Rules * **Standard rules** for [valid submissions](https://codegolf.meta.stackexchange.com/q/2419/82619), [I/O](https://codegolf.meta.stackexchange.com/q/2447/82619), [loopholes](https://codegolf.meta.stackexchange.com/q/1061/82619) apply. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **shortest solution** (in bytes) wins. As usual, don't let ridiculously short solutions in golfy languages discourage you from posting a longer answer in your language of choice. * This is not a rule, but your answer will be better received if it includes a link to test the solution and an explanation of how it works. # Examples ``` Input --> Output [10] --> 0 [-1, 0, 1] --> 2 [4, 7] --> 3 [6, 2, 3, 8] --> 9 [5, 8, 12, 3, 2, 8, 4, 5] --> 19 [1,10,100] --> 99 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 19 bytes ``` Tr@Abs[#-Median@#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2Yb8z@kyMExqThaWdc3NSUzMc9BOVbtf0BRZl6JQ5pDtaFBLReco2uoo2Cgo2CIJGSio2COxDXTUTDSUTDWUbBAEjQFcoG6IBJGYA5Qm2ntfwA "Wolfram Language (Mathematica) – Try It Online") For 1D integer array, `Tr` works the same way as `Total`. ## How? Simple application of triangle inequality. ... I originally intended to write the proof here, but then decide to look up <https://math.stackexchange.com> instead and found [The Median Minimizes the Sum of Absolute Deviations (The \$ {L}\_{1} \$ Norm)](https://math.stackexchange.com/questions/113270/the-median-minimizes-the-sum-of-absolute-deviations-the-l-1-norm). By knowing the name of the operator, this is an alternative 19-byte solution: ``` Norm[#-Median@#,1]& ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~50~~ 48 bytes Saved 2 bytes thanks to Arnauld ``` a=>a.sort((x,y)=>x-y,r=0).map(n=>r+=a.pop()-n)|r ``` [Try it online!](https://tio.run/##VczPDoIwDAbwu0@xcOpiRzYQ/8SUFzEeFh0JJsLs0MDT4wJcduvX39e@7M@GB7d@UF3/dHNDs6UamDTaPPQ8AIw4SapHNcn8bT10VPOebO57D1J1ElnONgTHA7H7fFt2kK05k9fdOkEDN6PvUhCR0MlaGRQahYm4aJHoAcVpOysTOKIoUJQozhtfEq4ixKdrpVhCfFVtXRPL8x8 "JavaScript (Node.js) – Try It Online") Sort the array ascending then sum: ``` a[last] -a[0] // moves to equalise this pair + a[last-1] -a[1] // + moves to equalise this pair + ...etc ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~29~~ 28 bytes *-1 byte thanks to nwellnhof* ``` {sum (.sort[*/2]X-$_)>>.abs} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/urg0V0FDrzi/qCRaS98oNkJXJV7Tzk4vMam49r81V3FipUKaRrShQawmnKNrqKNgoKNgiCRkoqNgjsQ101Ew0lEw1lGwQBI0BXKBuiASRmAOUJtprOZ/AA "Perl 6 – Try It Online") ### Explanation ``` { } # Anonymous code block .sort[*/2] # Get the median of the input array X-$_ # Subtract all elements from the median ( )>>.abs # Get the absolute of each value sum # Sum the values ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` ÅmαO ``` [Try it online!](https://tio.run/##yy9OTMpM/W/q5vL/cGvuuY3@/3X@RxsaxHJF6xrqKBjoKBgCmSY6CuZAykxHwUhHwVhHwQLIMQVSQFmIgBGYA1RmGgsA "05AB1E – Try It Online") **Explanation** ``` Åm # push median of input α # absolute difference with each in input O # sum ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), ~~7~~ 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` £xaXÃÍ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=o3hhWMPN&input=WzUsIDgsIDEyLCAzLCAyLCA4LCA0LCA1XQ) ``` £xaXÃÍ :Implicit input of array U £ :Map each X x : Reduce by U by addition after applying aX : Absolute difference with X Ã :End map Í :Sort :Implicit output of first element ``` [Answer] # JavaScript (ES6), ~~60~~ ~~56~~ 55 bytes *Saved 1 byte thanks to @Shaggy* ``` a=>a.map(r=k=>r=a.map(n=>m+=n>k?n-k:k-n,m=0)|m>r?r:m)|r ``` [Try it online!](https://tio.run/##fc5BDoIwEAXQvaeYJY0ttCAqJC0HMV00CEZLW1KMK@5eiSxMGnF2P/kvfx7qpabW38cnse7ahZ4HxYVKjRoTzzUXnq/BcmH23ArdWKJrTSw2nKLZCN/42qDZh9bZyQ1dOrhb0icXRiX8OoQgy4AQAXQXEcIwUAxMbpI8JgcMJ/l3pYjJEUOOocBwlhukikm5lJe/VpZ/wjJcyi9hVXgD "JavaScript (Node.js) – Try It Online") ### How? Unless there's some trick that I'm missing, computing the median in JS turns out to be longer. Probably around **65 bytes** because of the required callback for `sort()` to circumvent the default lexicographical sort and the rather lengthy `Math.abs()`: ``` a=>a.sort((a,b)=>b-a).map(n=>s+=Math.abs(n-a[a.length>>1]),s=0)|s ``` Instead of that, we try all values in the original array as the *equalizing* value. [Answer] # [Haskell](https://www.haskell.org/), 34 bytes ``` f l=minimum[sum$abs.(m-)<$>l|m<-l] ``` [Try it online!](https://tio.run/##JU3LCsIwELz7FXPIQWEjbbXqIfVHQg4RFIO7oZjm1n@Piz3Nk5l3LJ8nc2sv8CQpJ6niSxUTH@W4F3tw5s6rOMuhpTzXpWCC930XyNue0BF6pWfCVeFCGAgnwk3FqKDpZgx/obUxhJ3ElHVm/qa8wMDr98rObvuh/QA "Haskell – Try It Online") Finds the total distance of all elements to the median, testing each element in the list as the potential median and taking the smallest result. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ạÆṁS ``` [Try it online!](https://tio.run/##y0rNyan8///hroWH2x7ubAz@f7j9UdMa9///o6MNDWJ1uKJ1DXUUDHQUDEFsEx0FcxBtpqNgpKNgrKNgAeKZAmmgAoiIEZgDVGgaGwsA "Jelly – Try It Online") ### How it works ``` ạÆṁS – Full program. Takes an array A of integers as input from argument 1. Æṁ – Median. For odd-length A, middle element of S. For even-length A, the arithmetic mean of the two middle elements of S. Where S = A sorted. ạ – Absolute difference of each element with the median. S – Sum. ``` [Answer] # [Python 2](https://docs.python.org/2/), 46 bytes ``` lambda l,n:sum(l[-~n/2:l.sort()])-sum(l[:n/2]) ``` [Try it online!](https://tio.run/##TcxBDoIwFATQvaf4yzaZKi2gpMST4F9gDNGkFAJ14Yar10YS0@W8ycz8Cc/Jmzhcb9H14/3Rk4O363sUrlObPxnrjuu0BCFZqp1tUpZxXl4@0CA6XTC0bA9/UBpUgDSjzLkCXRgmpzPIgEpQw6jyok6UHvbS/EKa14xGxi8 "Python 2 – Try It Online") Takes the list length `n` as an argument. Computes the top-half sum minus the bottom-half sum by slicing the sorted list into the first `n/2` and last `n/2` elements. The expression `l[-~n/2:l.sort()]` is equivalent to computing `l.sort()`, which modifies the list in place, then doing `l[-~n/2:None]`, where the list slicing ignores upper bound of `None` that `l.sort()` produced. It might seem like the list was sorted too late to be sliced right, but Python seems to evaluate the slice arguments before "locking in" the list to be sliced. --- **[Python 2](https://docs.python.org/2/), 47 bytes** ``` lambda l,n:sum(abs(x-sorted(l)[n/2])for x in l) ``` [Try it online!](https://tio.run/##TczRCsIgGAXg@57iv1Q4o@m2GkVPsrzYWNLA6VCD9fQmBeHl@Q7nbO/4dFYmfbsnM67TPJKBvYTXysYpsL0KzsfHzAwf7FEqrp2nnRZLhqfNLzaSZoOoFQS/Hv5QCVANEgpNyS3orCBLOoEkqAH1Cm1ZdJnyw6@U35DnnULP0wc "Python 2 – Try It Online") The boring method of summing the distance of each value from the median. Takes the length `n` as an argument. --- **[Python](https://docs.python.org/2/), 51 bytes** ``` f=lambda l:l>l[l.sort():1]and l[-1]-l[0]+f(l[1:-1]) ``` [Try it online!](https://tio.run/##VY1BCsIwEEX3nmKWCU4kE62ViF5kyCJSgsKYlpqNp49BQcjyvc/jL@9yn7OrNV0kPm9TBPFyFZbda16L0p5CzBMIGwpG2IZtUsLkG@q6rI9cICkmG/R580dDCBaBOnlAGDtxRHAIe4RTp4cmWvub3BdaOrS7Dw "Python 2 – Try It Online") Sorts the list in place, then repeatedly adds the last (highest remaining) entry minus the first (lowest remaining) entry, and recurses on the list without these elements until only 0 or 1 remain. Usings `pop`'s gets the same length: `l.pop()-l.pop(0)+f(l)`. The `l.sort()` is stuck in a place where the `None` it returns has no effect. The slice `l[None:1]` is the same as `l[:1]` because `None`s in slices are ignored. --- **[Python](https://docs.python.org/2/), 54 bytes** ``` lambda l:sum(l.pop()-l.pop(0)for _ in l[1:l.sort():2]) ``` [Try it online!](https://tio.run/##VY3RCsIgGIXve4pzqfBvqLUKY0@yRixCGjgVZxc9vZMGgVeH7zscTvimt3cqm/6e7bQ8XxOsXj8Ls23wgfFmT8GNj3hgdrCD1LZdfUyMazXyHOLsEgwbpBj57fDHRhIEQVbyRLhU4kxQhCPhWumuiLLdK/WDMu3K3QY "Python 2 – Try It Online") A cute list comprehension that ignores the argument iterated over and modifies the list in place by repeatedly popping the first and last elements. We ensure that the list comprehension is done `len(l)//2` times by iterating over every other element of `l` skipping the first, done with `l[1::2]`. The `l.sort()` producing `None` can be stuck in the unused slice end argument. [Answer] # APL(Dyalog), 12 bytes ``` {⌊/+/|⍵∘.-⍵} ``` Brute forces by testing each number as the equalizer. Not sure if tacit is shorter, but I can't figure it out. [TIO](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/g8E1Y96uvS19Wse9W591DFDTxdI1xoqGCkYc2GTMQPJKFhglTNVsFAwBEkbARkmCqYA) [Answer] # TI-Basic, ~~18~~ 6 bytes ``` sum(abs(Ans-median(Ans ``` -12 bytes from [Misha Lavrov](https://codegolf.stackexchange.com/questions/173038/equalize-the-array/173052?noredirect=1#comment417510_173052) (I haven't used TI-Basic in a while and I forgot it's lists can do that) TI-Basic is a [tokenized language](http://tibasicdev.wikidot.com/one-byte-tokens). All tokens used in this answer are one byte. Takes input as `{1,2,3,4}:prgmNAME` Basically the same idea as most other answers: subtract through by the median, then take the sum. Explanation: ``` sum(abs(Ans-median(Ans sum( # 1 byte, Add up: abs( # 1 byte, the absolute values of Ans-median(Ans # 4 bytes, the differences between each element and the list's median ``` [Answer] # [Röda](https://github.com/fergusq/roda), 33 bytes ``` {|a|a|abs _-[sort(a)][#a//2]|sum} ``` [Try it online!](https://tio.run/##PYzNCoMwEITveYrFXhRW/KltpWDvfQYrktZYhJqEbDypz26NgjOXYfhmjGr40vNOwshgVQv3Al7LOHHnN0EdlqSM9XlQlSceRWk10dDPywYrA1aQrT@cBDRqe3DqpB6seypJ/zrrHxACCV146AUwgeaGxFNa8RXGr4PqmHNJbtz6209w9Np00u4lggfhAzx08E40Sgo2L0nMwgRjTFiGN3bFFM@YswvmmLiYriHDyx8 "Röda – Try It Online") Explanation: ``` {|a| /* Anonymous function with parameter a */ a| /* Push items in a to the stream */ /* For each _ in the stream: */ abs /* Abstract value of */\ _- /* the value from stream minus */\ [sort(a)][ /* the value in the sorted version of a at index */ #a//2 /* length of a / 2 (the median) */ ]| sum /* Sum of all values in the stream */ } ``` [Answer] # C (gcc), ~~100~~ 93 bytes ``` e(q,u,a,l,i,z)int*q;{i=1<<31-1;for(a=u;a--;i=z<i?z:i)for(l=z=0;l<u;)z+=abs(q[l++]-q[a]);q=i;} ``` Brute-force solution, tries to equalize with each element. Try it online [here](https://tio.run/##VZBdS8MwFIav7a84FITEneLSD3VLgwgqiII/YO4idtkM1G79mGhHf3tNm03MXc9znvdtkizYZFnfK1LiHiXmqLGlumguSn7QgqVpxALG19uKSLHnMgi4Fm2qb9u5pgPNRSumPE/3nLYTId9rUi7yyWQZlAu5pLwUmne96QNZVfKHLZYg4MCmHVoQWhAwhCkCO@HI4hjh@oRii64QQoQI4ea0SOwiMcg02GU4DiaedNzzvrZ6BY2qGzJczKYQhkPlqtg0H/Zbfe9U1qgVhYN3tqsMWhP/vH4rfARFjiEboCDEnw@34L8@@zAH//Hu6eXh3qfc6zxv6PyUuiDD78fS8Qj2HRBq3art@jjSy@NoQtQ8hWn4Z4euHbp26MqRK0euHLly7MqxK89cOXHlxJXZbLx2/ws). Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for golfing 7 bytes. Ungolfed: ``` e(q, u, a, l, i, z) int *q; { // function taking an array of int and its length; returns an int (extra parameters are variables and don't have to be passed when calling e()) i = 1 << 31 - 1; // construt the maximum value of a signed 4-byte integer for(a = u; a--; i = z < i ? z : i) // loop through the array, testing each element as the equalizer; if the number of moves is smaller than the current minimum, set it as the new minimum for(l = z = 0; l < u; ) // loop through the array ... z += abs(q[l++] - q[a]); // ... and sum the number of moves it takes to equalize each element q = i; // return the minimum number of moves } ``` [Answer] # [R](https://www.r-project.org/), 29 bytes ``` sum(abs(median(a<-scan())-a)) ``` [Try it online!](https://tio.run/##K/r/v7g0VyMxqVgjNzUlMzFPI9FGtzgZSGtq6iZqav43VbBQMDRSMFYwAjJMFEz/AwA "R – Try It Online") [Answer] # PHP, 69 bytes ``` function($a,$c){for(sort($a);$c-->$d;)$s+=$a[$c]-$a[+$d++];return$s;} ``` anonymous function. [Try it online](http://sandbox.onlinephpfunctions.com/code/5c2461fcd9f794c6a360dd11a5519eb60b5d7050). [Answer] # Java 8, 116 bytes With `java.util.List<Integer>` as parameter, which has a short sort-builtin, but is longer to retrieve a value at a given index: ``` L->{L.sort(null);int r=0,l=L.size(),k=l;for(;k-->0;)r+=Math.abs(L.get(k)-(L.get(l/2+~l%2)+L.get(l/2)>>1));return r;} ``` [Try it online.](https://tio.run/##dVBda8IwFH3frwjCIKFp1na6ybIW9jiovvg49hBrdLExleTW4cT99S7tihTHXi73fHA592zFQYTbVdkUWjiHZkKZ0w1CyoC0a1FING9hR6ACb72b1aA0y5WD51fv2kiboZxw7zrf@OFAgCrQHBmUoiYPs1POXGUBm1prwts7No2oTj2tviQmtEw1X1cW8zIMs4gTG6QzAR9MLB3O2UYCLknYb/ouCb71bUKCCyZZFhPCrYTaGmT5ueFtjn291D5HH@dQqRXa@efwAqwym7d3JMjvZyAd4DjqPuhRGNOIxkNmTB@H8IEm9J5Oh9SETmncsolfxnQy1GIa@3tRdMXR8Z/aupyd3nfLGLsk/bd937SRnwP9xVpx7EwZvmIdE65VsCB9nMXRgdyxqga2992ANjgPRk9oFBhW4Jz0Ic/NDw) With `int[]` (integer-array) as parameter, which has a long sort-builtin, but is shorter to retrieve a value at a given index: ``` a->{java.util.Arrays.sort(a);int r=0,l=a.length,k=l;for(;k-->0;)r+=Math.abs(a[k]-(a[l/2+~l%2]+a[l/2]>>1));return r;} ``` [Try it online.](https://tio.run/##ZVDBisIwFLz7FUFYSGmabbp1Vza0sB@gF4/SQ6xV28ZUkldBxP317muVpejlMTOPvMxMpc4qqLZ1l2vlHFmo0lwnhJQGCrtTeUGWPR0EklOc64woT6J2m@BwoKDMyZIYkpBOBem1woO8hVLzH2vVxXHXWKD4pL9gk5DpRHFdmD0cWJ1ouWsslXUQpKH0rJ8sFBy42jiq1nUW4NTvkf@r36LMH3CWpsLzpC2gtYZYeetk7@PUbjT6eNg5N@WWHDEKXYEtzX7wfM8BhQMqwiHBgwWChUyMlZh9jekni9gHm4@lGZsz0asRgpjNxjvBBN4LwyeNxS@1DT6HPZbDOf93ubo4KI68aYGfMABoQ196heYeDrv1p99k6hueI358cuv@AA) **Code explanation (of the array answer):** ``` a->{ // Method with integer-array as parameter and integer return-type java.util.Arrays.sort(a); // Sort the input-array int r=0, // Result-sum, starting at 0 l=a.length, // The length of the input-array k=l;for(;k-->0;) // Loop `k` in the range (length, 0]: r+= // Increase the result-sum by: Math.abs(a[k]- // The absolute difference of the `k`'th value of the array, (a[l/2+~l%2]+a[l/2]>>1)); // and the median of the array return r;} // And then return this result-sum ``` **General explanation:** 1. Sorts the input-list 2. Calculate the \$median\$ 3. Calculate the absolute difference of each value with this \$median\$ 4. Sum those The median of the array \$a\$ is calculated by: 1) Taking the sorted values at the (0-based) indices \$i\$ and \$j\$, which are calculated like this (using the `l/2+~l%2` instead of `l/2-(l+1)%2` trick to save bytes): \$j=\left\lfloor\frac{1/2}l\right\rfloor\$ \$i=\left\lfloor\frac{1/2}l\right\rfloor - ((l+1) \bmod 2)\$ Note that \$i=j\$ for odd-sized arrays. 2) And then adding these together, and integer-dividing them by 2 (using the `i+j>>1` instead of `(i+j)/2` trick to save bytes): \$median = \left\lfloor\frac{a[i]+a[j]}{2}\right\rfloor\$ After which we can use this \$median\$ to calculate the absolute difference with the current item, which we can use to calculate the total sum: \$\sum\limits\_{k=0}^{l} = \left\lvert a[k] - median\right\rvert\$ with \$l\$ being the length of the array \$a\$, and \$k\$ being the (0-based) index. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` δαOß ``` I know there is already [an existing 4-bytes 05AB1E answer](https://codegolf.stackexchange.com/a/173044/52210) using the median builtin `Åm`, but I decided to post this alternative 4-byter without this builtin. [Try it online](https://tio.run/##yy9OTMpM/f//3JZzG/0Pz///P9pQx9AAiAxiAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/3Nbzm30Pzz/v87/6GhDg1gdhWhdQx0DHUMQy0THHESZ6RjpGOtYgJimOhY6hiCeEZBhomMKEjPUMQSqNzCIjQUA). **Explanation:** ``` δ # Apply the following command double-vectorized on the given two arguments, # which will use the input-list twice implicitly, since the stack is empty: α # Absolute difference # i.e. [1,10,100] → [[0,9,99],[9,0,90],[99,90,0]] O # Sum each of these inner lists # → [108,99,189] ß # Pop and push the minimum of this list # → 99 # (after which this is output implicitly as result) ``` [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 18 bytes ``` Sum##Abs@`-#Median ``` [Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@z@4NFdZ2TGp2CFBV9k3NSUzMe@/X2pqSnG0SkFBcnosV0BRZl5JSGpxiXNicWpxdJqOQjRXtKFBrA5XtK6hjoKBjoIhiG2io2AOos10FIx0FIx1FCxAPFMgDVQAETECc4AKTWO5YmP/AwA "Attache – Try It Online") ## Explanation ``` Sum##Abs@`-#Median Median take the median of the input list Abs@`-# absolute difference with the original list Sum## sum of all elements ``` [Answer] # [J](http://jsoftware.com/), 15 bytes ``` [:<./1#.|@-/~"{ ``` Essentially the same as Shaggy's Japt solution. [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8D/aykZP31BZr8ZBV79Oqfq/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqCiYI5jGmoYKRgDOOYgTgKFjCuqYKFgiFIxAjIMFEw/Q8A "J – Try It Online") ## How it works? `|@-/~"{` - creates a table `/~` of absolute differences `|@-` of each number to all others `"{` ``` |@-/~"{ 6 2 3 8 0 4 3 2 4 0 1 6 3 1 0 5 2 6 5 0 ``` `1#.` sums each row ``` 1#.|@-/~"{ 6 2 3 8 9 11 9 13 ``` `[:<./` finds the smallest item (reduce by minimum) ``` ([:<./1#.|@-/~"{) 6 2 3 8 9 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~16~~ 11 bytes ``` I⌊EθΣEθ↔⁻ιλ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczLzO3NFfDN7FAo1BHIRjBdEwqzs8pLUkFKSkt1sjUUcjRhALr//@jo011FCx0FAyNdBSMdRSMwBwTHQXT2Nj/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 5 bytes thanks to @Arnauld. Explanation: ``` Eθ Map over input array Eθ Map over input array ι Outer value λ Inner value ⁻ Difference ↔ Absolute value Σ Sum ⌊ Minimum I Cast to string Implicitly print ``` [Answer] ## Visual C#, 138 bytes ``` int s=0;foreach(string i in a)s+=int.Parse(i);int x=s/a.Length;int o=0;foreach(string i in a)o+=Math.Abs(int.Parse(i)-x);Console.Write(o); ``` ungolfed: ``` int s = 0; // Takes a string array of arguments a as input foreach (string i in a) s += int.Parse(i); // s as sum of the array elements int x = s / a.Length; // calculating the target value of all elements int o = 0; // o as minimum number of moves foreach (string i in a) o += Math.Abs(int.Parse(i) - x); // summing up the moves to the target value Console.Write(o); ``` [Try it online!](https://tio.run/##dYyxCsIwFEV3vyJjQ2nVakEIHcTVQsHBQRyeMbYP2gTyolRKv/1ZxcHF7XLPuVdToknzndDW4vCkYDo10y0Qicq72kM3UICAWjwcXkUJaCMKfrJPZwFyYLRBULFQN@cN6OYLBQq0E6e4mIS0Ak8mQqnedl/QHNK9sXVoPoX7O3dxUUJo0u2Fot@fpJdq5yy51qRHj8FETioeR@acN7zMeMXZFNacvwA) [Answer] # PHP, 78 bytes Sorts the array, then loop through a copy, popping elements off the original and summing the absolute difference, that needs to be halved for the return. ``` function m($n){sort($n);foreach($n as$i)$r+=abs(array_pop($n)-$i);return$r/2;} var_dump( m([10]), m([-1, 0, 1]), m([4, 7]), m([6, 2, 3, 8]), m([5, 8, 12, 3, 2, 8, 4, 5]), m([1,10,100]) ); ``` Output: ``` int(0) int(2) int(3) int(9) int(19) int(99) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 38 bytes ``` ->a{a.map{|x|a.sum{|y|(y-x).abs}}.min} ``` [Try it online!](https://tio.run/##LctBDsIgFATQNZ7iJ2w0@RCgttqFXqRh8bto4gLT2DQpAc6OCC7nzcxnn31eHlk8KZB0tIZ4RJLb7kL08ezFcZE0bylJ93qnvMIyTVpZC4wxDupUQWgEhaCtrWqaXhFuf@maDAgGoUO4/5zD2LgvUN6tMjWUb182HPSYvw "Ruby – Try It Online") [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 94 bytes ``` #import<regex> int f(int c,int*a){int s=0,d=0;for(std::sort(a,a+c);c-->d;)s+=a[c]-a[d++];c=s;} ``` Port of the [PHP solution](https://codegolf.stackexchange.com/a/173068/89298). Kudos to [Titus](https://codegolf.stackexchange.com/users/55735/titus)! Input size of the array and a non-`const` mutable array. Output the minimum number of moves required to equalize the array. *-4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!* [Try it online!](https://tio.run/##VVDRasMgFH33Ky4MVl1MSbp1GzHxR7o@iNoiLDFEI2Ml354ZA13jw/Wec8/x4JV9n1@lnOcn0/Z28PWgr/qHI9N5uOClShrriyC3BbimoKop2MUO2HlVVS56sKAik4TJPOeKEZc14iTPuTipLDsz2Tg2xec7@T0qDbWxzg9atBz9c0FLbweOUmwrTIeDNYqgG4J4UtAqqR/7KOYcTNKsytRBWcBEH3BeUigolFv2jcLHlnmncKDwSuFzyx8jE@3r7JBANB@3ophRLiHFPXxiKN3LrsToLTwHqMCQuyn9RdrRQ13HZYe9M78aEwphr4QXmJBlsPvqdgxN8x8 "C++ (gcc) – Try It Online") [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), 84 bytes ``` :sort Go<c-r>=(line('$')-1)/2 <esc>dd@"kk0vg_"ayGqq0C<c-r>=abs(<c-r>"-<c-r>a) <esc>k@qq@q:%s/\n/+ $x0C<c-r>=<c-r>" <esc> ``` [Try it online!](https://tio.run/##K/v/36o4v6iEyz3fJlm3yM5WIyczL1VDXUVdU9dQU9@Iyya1ONkuJcVBKTvboCw9Ximx0r2w0MAZojgxqVgDzFLSBVOJmhD12Q6FhQ6FVqrF@jF5@tpcKhUwDRDFEEX//5tyWXAZGnEZcxkBGSZcpv91ywA "V (vim) – Try It Online") `<c-r>` is very helpful in finding the median and the whole calculation in general. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 52 bytes ``` ($a=$args|sort)|%{$_-$a[--$i]}|%{$s-=$_*($_-lt0)} $s ``` [Try it online!](https://tio.run/##PY/tCsIgFIb/exWHOAsNhdl3waD7iBij7AMGLV1UbF77Op1aIsj7PL7Kqa4P58PZlWWHR8ig6SQWGRb@FNpw9bVqkwZzg8XWGLzs4icGk2E@koTLOlVRYOiiEBspgJaWqf6cNlW/POZsrAYytqcTplMNi56smMw1UIHssueWxYwI1b9uzIHKs3@ZL1ltU9r0tYIWEmjYontWbl@7gwYazBcvmhPzr/Iu3MuawJDG37BlMUD5c8bd/g@odd8YiNi9AQ "PowerShell – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-ap`, 39 bytes ``` map$\+=abs$_-(sort{$a-$b}@F)[@F/2],@F}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/z83sUAlRts2MalYJV5Xozi/qKRaJVFXJanWwU0z2sFN3yhWx8Gttvr/f1MdBQsdBUMjHQVjHQUjMMdER8H0X35BSWZ@XvF/3cQCAA "Perl 5 – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 107 bytes ``` $f={param($i)$m=($i|sort)[[int](($i.count-1)/2)];($j+=$i.foreach({([math]::abs($m-$_))})|measure -sum).Sum} ``` [Try it online!](https://tio.run/##DchNCoMwEEDhq3QxixlKLHZpySm6DKFMJRKLYyQ/dKGePWb1@N4W/i4m75alVpj0vnFkQZgJRLccKcRMxsxrttjcjaGsWfX0eJJ9Ifzuus0pRMejxx2NcPZ2GPibEETBh@ikQxynEt1NpSLUvYuctV4 "PowerShell – Try It Online") # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 115 bytes ``` function f($i){$m=($i|sort)[[int](($i.Count-1)/2)];return($j+=$i.ForEach({([math]::Abs($m-$_))})|measure -Sum).Sum} ``` [Try it online!](https://tio.run/##DYqxCsIwFEV3vyJDhjykio4tHUR0EwTHUiTWtI00ibz3okjbb69Z7uFw7jt8DVJvhmGJZH0nbj9i44pVM2giccXQoXYjsWbbiE@wT3HR1itiTO@qFhrGpY2@YRu8aJW0MEpXJk4UkKGqrOdaJd8cQ/Sc7WC7h7pAwxG9kq91mdI54Ek3vRpV5TT3dZ4fHqSky@QdYIbJGU0Rjchu0cEmzbzM8/IH "PowerShell – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 52 bytes ``` f=a=>(v=a.sort((x,y)=>x-y).pop()-a.shift())?v+f(a):0 ``` [Try it online!](https://tio.run/##bYzBCsIwEAXvfkWOu7gJSbUqQuqHiIdQG20pTWhCab8@Br1Jjm9meINZTGjn3kc@uWeXktVGN7BoI4KbI8BKG@pm5RsK7zwgz@Ld2wiIt2VvweBVptZNwY2dGN0LLNyVfCDu/iBXxCQxVVBHYucCPhGriB2IXQqyzji//YLqO/JNncv0AQ "JavaScript (Node.js) – Try It Online") [Answer] **Kotlin Android, 200 bytes** ``` fun m(a:IntArray){var d=0;var s=0;var p=a.max()!!.times(a.size);var x =0;for(i in a.indices){x=a[i];d=0;s=0;while(d<a.size){if(x-a[d]<0)s=((x-a[d])*-1)+s;else s=((x-a[d]))+s;d++};if(p>s)p=s};print(p)} ``` [Try Online](https://rextester.com/live/SGDG37478) ]
[Question] [ # The plus-minus sequence The plus-minus sequence is one that starts with two seeds, `a(0)` and `b(0)`. Each iteration of this sequence is the addition and subtraction of the previous two members of the sequence. That is, `a(N) = a(N-1) + b(N-1)` and `b(N) = a(N-1) - b(N-1)`. **Objective** Produce the plus-minus sequence, in infinitude or the first `K` steps given `K`. You may do this using an infinite output program, a generator, or a function/program that gives the first `K` steps. The output order does not matter, so long as it is consistent. (I.e., `b(K) a(K)` or `a(K) b(K)`, with some non-numeric, non-newline separator in between.) The output must start with the input. ## Test cases For inputs `10 2` (of `a(0) b(0)`, this is a possible output for the first K approach (or a subsection of the infinite approach): ``` 10 2 12 8 20 4 24 16 40 8 48 32 80 16 96 64 160 32 192 128 320 64 384 256 640 128 768 512 1280 256 1536 1024 2560 512 3072 2048 5120 1024 6144 4096 10240 2048 12288 8192 20480 4096 24576 16384 40960 8192 49152 32768 81920 16384 98304 65536 ``` For inputs `2 20 10` (`a(0) b(0) k`): ``` 2 20 22 -18 4 40 44 -36 8 80 88 -72 16 160 176 -144 32 320 352 -288 ``` --- This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. ### Catalog The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 76983; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṄI;Sß ``` This is a recursive approach. Due to tail call optimization, the only limit is the ability to fit both integers into memory. Output is one list per line. [Try it online!](http://jelly.tryitonline.net/#code=4bmESTtTw58&input=&args=MiwgMTA) ### How it works ``` ṄI;Sß Main link. Argument: [b[n], a[n]] (n = 0 for original input) Ṅ Print [b[n], a[n]] to STDOUT. I Compute the increments of the list, i.e., [a[n] - [b[n]]. S Compute the sum of the list, i.e., b[n] + a[n]. ; Concatenate the results to the left and to the right. ß Recursively call the main link. ``` [Answer] ## Haskell, 19 bytes ``` a#b=a:b:(a+b)#(a-b) ``` Produces an infinite sequence of numbers. Usage example: ``` Prelude> take 20 $ 2#20 [2,20,22,-18,4,40,44,-36,8,80,88,-72,16,160,176,-144,32,320,352,-288] ``` [Answer] ## Python 2, 31 bytes ``` def f(a,b):print a,b;f(a+b,a-b) ``` Prints forever. Well, eventually you exceed the recursion limit, but that's a system limitation. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 10 bytes ``` `tDtswPdhT ``` This version will output an infinite number of elements in the plus-minus sequence. [**Try it Online!**](http://matl.tryitonline.net/#code=YHREdHN3UGRoVA&input=WzEwLDJd) (stop it after running due to infinite loop) **Explanation** ``` % Implicitly grab input as a two-element array [a,b] ` % do...while loop tD % Duplicate and display the top of the stack ts % Duplicate [a,b] and add them together w % Swap the top two elements on the stack P % Swap the order of b and a in preparation for diff d % Compute the difference between b and a h % Horizontally concatenate [a+b, a-b] T % Explicit TRUE to make it an infinite loop % Implicit end of the do...while loop ``` [Answer] # Julia, 25 bytes ``` a<|b=[a b]|>show<a+b<|a-b ``` Maximum syntax abuse. Julia is *weird*. [Try it online!](http://julia.tryitonline.net/#code=YTx8Yj1bYSBiXXw-c2hvdzxhK2I8fGEtYgoKMTA8fDI&input=) ### Alternate version, 29 bytes Note that the output will eventually overflow unless you call `<|` on a *BigInt*. Unfortunately, `show` will prefix each array with `BigInt` in this case. At the cost of four more bytes, we can generated whitespace-separated output for all numeric types. ``` a<|b="$a $b "|>print<a+b<|a-b ``` [Try it online!](http://julia.tryitonline.net/#code=YTx8Yj0iJGEgJGIKInw-cHJpbnQ8YStiPHxhLWIKCmJpZygxMCk8fDI&input=) ### How it works We define the binary operator `<|` for out purposes. It is undefined in recent versions of Julia, but still recognized as an operator by the parser. While `\` (not explicitly defined for integers) is one byte shorter, its high precedence would require replacing `a+b<|a-b` with `(a+b)\(a-b)` (+3 bytes) or `\(a+b,a-b)` (+2 bytes). When `a<|b` is executed, it starts by calling `show` to print **[a b]** to STDOUT. Then, `a+b<|a-b` recursively calls `<|` on the sum or the difference. Since the recursion is (supposed to be) infinite, the comparison `<` is never performed; it sole purpose is chaining the two parts of the code. This saves two bytes over the more straightforward alternative `([a b]|>show;a+b<|a-b)`. [Answer] # Pyth, ~~10~~ 9 bytes *Thanks to @isaacg for 1 byte.* ``` #=Q,s Q-F ``` Prints an infinite sequence of pairs. ``` $ pyth plusminus.p <<< "[10,2]" | head -n 15 [10, 2] [12, 8] [20, 4] [24, 16] [40, 8] [48, 32] [80, 16] [96, 64] [160, 32] [192, 128] [320, 64] [384, 256] [640, 128] [768, 512] [1280, 256] ``` [Answer] # C, 81 bytes ``` a,b;main(c){for(scanf("%d%d%d",&a,&b,&c);c--;a+=b,b=a-b-b)printf("%d %d\n",a,b);} ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 7 bytes Uses the **first-k** method. Input in the following for: ``` k [a, b] ``` Code: ``` FD=OsÆ‚ ``` Explanation: ``` F # For N in range(0, k). D= # Duplicate top of the stack and print without popping. O # Sum up the array. sÆ # Swap and perform a reduced subtraction. ‚ # Pair the top two elements. a, b --> [a, b] ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=RkQ9T3PDhuKAmg&input=MjAKWzEwLCAyXQ) [Answer] # k, 12 ``` {(+;-).\:x}\ ``` . ``` k){(+;-).\:x}\[10;10 2] 10 2 12 8 20 4 24 16 40 8 48 32 80 16 96 64 160 32 192 128 320 64 ``` Could also be called in the form of ``` k)10{(+;-).\:x}\10 2 ``` [Answer] ## APL, 37 chars ``` {⍺←3⊃3↑⍵⋄⎕←z←2↑⍵⋄⍺=1:⋄(⍺-1)∇(+/,-/)z} ``` Can be used as ``` {⍺←3⊃3↑⍵⋄⎕←z←2↑⍵⋄⍺=1:⋄(⍺-1)∇(+/,-/)z} 10 2 10 2 12 8 20 4 24 16 40 8 48 32 80 16 [...] ``` or ``` {⍺←3⊃3↑⍵⋄⎕←z←2↑⍵⋄⍺=1:⋄(⍺-1)∇(+/,-/)z} 10 2 6 10 2 12 8 20 4 24 16 40 8 48 32 ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 8 bytes ``` ô`αp‼+-∟ ``` [Try it online!](https://tio.run/##y00syUjPz0n7///wloRzGwseNezR1n3UMf//fyMFQwMA "MathGolf – Try It Online") Takes input in reverse order, but that's simply because that's how they are pushed onto the stack. Otherwise it'd be 1 byte longer. 2-3 bytes comes from the output. Without the need of actually printing one pair per line, the program could be `æ`‼+-∟` (fills the stack with the elements of the sequence indefinitely), or `É‼+-∟` (prints all elements of the sequence except the first one to debug, as long as `-d` flag is active). ## Explanation ``` ô ∟ do-while-true ` duplicate the top two items αp wrap last two elements in array and print ‼ apply next two operators to the top stack elements + pop a, b : push(a+b) - pop a, b : push(a-b) ``` [Answer] # Python 3.5, 55 43 bytes: ``` def q(a,b): while 1:print(a,b);a,b=a+b,a-b ``` Prints out the correct sequence seemingly forever. I have been able to let this go on for about 30 minutes without any error being raised, and the program had printed out 2301 digits for the first number, and 1150 digits for the second! Based on this, I guessing that, being provided sufficient hardware to run on, this can go on for WAY longer and print out WAY more digits, and also has theoretically no recursion limit, courtesy of the `while` loop! [Answer] # Reng v.3.2, 9 bytes (self-answer, non-competing) ``` ii¤ææö±2. ``` Takes two inputs (`a b`) and outputs `b a`. [Try it here!](https://jsfiddle.net/Conor_OBrien/avnLdwtq/) `i` takes input twice, `¤` duplicates the stack, `æ` prints a number and a space (and does so twice, there being two), `ö` prints a newline, `±` does what you might expect, and `2.` skips the next two characters, wrapping around the input getting characters. [Answer] ## Python 2.7, ~~56~~, 42 bytes: ``` a,b=input() while 1:print a,b;a,b=a+b,a-b ``` Simple loop that either prints forever(ish). [Answer] ## Batch, 54 bytes ``` @echo %1 %2 @set/aa=%1+%2 @set/ab=%1-%2 @%0 %a% %b% ``` Note that CMD.EXE is limited to 32-bit signed integers, so it will quickly overflow and print garbage and error messages. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 23 bytes (infinite) Edit: thanks to JoKing, the sequence version is now the shortest (also removed `.say` per clarification from OP: ``` {@_,{.sum,[-] |$_}...*} ``` [TIO:InfiniteSeq](https://tio.run/##K0gtyjH7n1upoJamYKvwv9ohXqdarzix0lqvuDRXJ1o3VqFGJb5WT09Pq/Y/UFghTcPQQMdIMzrO0CDW@j8A "Perl 6 – Try It Online") Old functional answer ``` ->\a,\b {(a,b).say;f(a+b,a -b)} ``` [TIO:InfiniteFunc](https://tio.run/##K0gtyjH7n1upoJamYPtf1y4mUScmSaFaI1EnSVOvOLHSOk0jUTtJJ1FBN0mz9r81F1eahqGBjpHmfwA "Perl 6 – Try It Online") Note that Perl 6 has no per se recursion limit, it is purely based upon memory available, so this will reach the millions before bombing out. [Answer] # [Rust](https://www.rust-lang.org/), 78 bytes ``` |a,b,k|{let mut x=(a,b);for _ in 0..k{println!("{:?}",x);x=(x.0+x.1,x.0-x.1)}} ``` [Try it online!](https://tio.run/##HY3BCoMwEETvfsXWU5ZuQ/TYIH5KsWAgqNuSRgjEfHu6OpcHj2Em7L9YHcM2eVYIuQHJOkdwMEA9JnrTcuRTbHuENCgxaN0nwAs8g9F6yd/gOa58U21@jqWlhFaKSZt70h0JH0IspZ7b9npwqqfeUGfQNqX@AQ "Rust – Try It Online") For fun, here's also an iterator that'll give you this sequence: ``` |a,b|(0..).scan((a,b),|x,_|{let i=*x;*x=(x.0+x.1,x.0-x.1);Some(i)}) ``` [Answer] # Factor, 62 bytes ``` :: f ( a b -- x ) a b "%s %s" printf a b + a b - f ; recursive ``` `recursive`, or else the callstack runs out too quickly. [Answer] # Ruby, 25 bytes Based on [xnor's Python solution](https://codegolf.stackexchange.com/a/76988/47581). Perhaps I'll make a generator in another answer, but this will print `a`, then `b`, then the new `a`, then the new `b`, ad infinitum. ``` f=->a,b{p a,b;f[a+b,a-b]} ``` [Answer] # Python 3, 42 bytes I wanted to write a generator for this function, and so I did. ``` def f(a,b): while 1:yield a,b;a,b=a+b,a-b ``` In Python 3, the sequence is generated in this way: ``` >>> gen = f(2, 20) >>> next(gen) (2, 20) >>> next(gen) (22, -18) >>> next(gen) (4, 40) >>> next(gen) (44, -36) >>> next(gen) (8, 80) ``` [Answer] ## Common Lisp, 57 ``` (lambda(a b)(loop(print`(,a,b))(psetf a(+ a b)b(- a b)))) ``` Uses `psetf`, which affects values to variables in parallel, and the simple `loop` syntax. [Answer] # bash + GNU coreutils, 75 bytes ``` a=$1 b=$2 for i in `seq $3`;{ echo -e "$a\t$b";c=$a;a=$((c+b));b=$((c-b));} ``` Invocation: ``` ./codegolf.sh 2 10 5 ``` [Answer] # CP/M 8080, 47 bytes z80 mnemonics but nothing the 8080 doesn't have, source commented once I decided to count the output rather than the input but terse function names retained, hand assembled so forgive the 'xx's where I know the number of bytes but haven't worked out the output addresses or offsets: ``` # setup ld c, 2 0e 02 # loop .s # update H (temporarily in B) ld a, h 7c add l 85 daa 27 ld b, a 46 # update L ld a, h 7c sub l 95 daa 27 ld l, a 6f # copy B back to H, output H ld h, b 60 call +o cd xx xx # output L ld b, l 45 call +o cd xx xx # repeat jr -s 18 xx # output a two-digit BCD value followed by a space .o # output high digit ld a, b 78 rra 1f rra 1f rra 1f rra 1f call +ob cd xx xx # output low digit ld a, b 78 call +ob cd xx xx # output a space ld e, #$20 1e 20 call 5 cd 00 05 # return ret c9 # output a single BCD digit .ob and #$f e6 0f add #$30 c6 30 ld e, a 5f call 5 cd 00 05 ret c9 ``` [Answer] # Clojure, 44 bytes ``` #(iterate(fn[[a b]][(+ a b)(- a b)])[%1 %2]) ``` Function that produces an infinite lazy sequence. [Answer] # Perl 5, 40 bytes requires `-E` (free) ``` sub a{say"@_";($c,$d)=@_;a($c+$d,$c-$d)} ``` ~~or (same length)~~ ``` $_=<>;{say;/ /;$_=$`+$'.$".($`-$');redo} ``` (I struck through the latter because it should have rounding errors for some iterations.) [Hat-tip.](/a/76988) But I suspect there must be a shorter Perl 5 solution. [Answer] # [RETURN](https://github.com/molarmanful/RETURN), 21 bytes ``` [¤.' ,$.' ,¤¤+2ª-F]=F ``` `[Try it here.](http://molarmanful.github.io/RETURN/)` Recursive operator-lambda. Usage: ``` [¤.' ,$.' ,¤¤+2ª-F]=F10 2F ``` # Explanation ``` [ ]=F declare function F for recursion ¤.' ,$.'␊, output top 2 stack items along with trailing newline ¤¤+2ª- get plus and minus of top 2 stack items F recurse! ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 26 bytes ``` :?!;1-r:n48*o:@@:nao:@+}-$ ``` Call with `a`, `b`, `n` on the stack, where `n` is the number of turns or a negative value for infinite output. Outputs `a` and `b` separated by a space. As an explanation, here is how the stack evolves during runtime : ``` abn nba nbaa naab naabb nabab nab+ +nab +n- +-n ``` You can try it on [the online interpreter](https://fishlanguage.com/playground) with a positive amount of turns but you will need to use the official python interpreter to test the infinite mode. > > > ``` > $ python fish.py -c ':?!;1-r:n48*o:@@:nao:@+}-$' -t 0.01 -v 10 2 -1 > 10 2 > 12 8 > 20 4 > 24 16 > 40 8 > 48 32 > 80 16 > 96 64 > 160 32 > 192 128 > 320 64 > 384 256 > 640 128 > 768 512 > 1280 256 > 1536 1024 > 2560 512 > 3072 2048 > 5120 1024 > 6144 4096 > 10240 2048 > 12288 8192 > 20480 4096 > 24576 16384 > 40960 8192 > 49152 32768 > 81920 16384 > 98304 65536 > 163840 32768 > 196608 131072 > 327680 65536 > 393216 262144 > 655360 131072 > 786432 524288 > 1310720 262144 > [...] > > ``` > > [Answer] ## Seriously, 12 bytes ``` ,,1WX■@│+)-1 ``` Outputs an infinite stream, format is `b(n) a(n)`, one pair of outputs per line. No online link because TryItOnline doesn't do so well with infinite loops. Explanation: ``` ,,1WX■@│+)-1 ,,1 push a(0), push b(0), push 1 W while loop: X discard the 1 (only used to make sure the while loop always runs) ■ print all stack elements, separated by spaces, without popping @│ swap, duplicate entire stack +) push a(n) + b(n) (a(n+1)) and move it to the bottom of the stack - push a(n) - b(n) (b(n+1)) 1 push 1 to make sure the loop continues ``` [Answer] # J, ~~16~~ 12 bytes ``` 0&(]+/,-/)~< ``` Produces only the first *k* values for the sequence based on the given seeds. Saved 4 bytes using the trick (or syntactic sugar) shown by @randomra in this [comment](https://codegolf.stackexchange.com/questions/91154/sylvesters-sequence/91170#comment222297_91170). ## Usage ``` f =: 0&(]+/,-/)~< 2 20 f 10 2 20 22 _18 4 40 44 _36 8 80 88 _72 16 160 176 _144 32 320 352 _288 ``` [Answer] # C#, 50 bytes ``` f=(a,b)=>{Console.WriteLine(a+" "+b);f(a+b,a-b);}; ``` Full source, including test case: ``` using System; using System.Numerics; namespace PlusMinusSequence { class Program { static void Main(string[] args) { Action<BigInteger,BigInteger>f=null; f=(a,b)=>{Console.WriteLine(a+" "+b);f(a+b,a-b);}; BigInteger x=10, y=2; f(x,y); } } } ``` The BigInteger data type is used so the numbers don't overflow and become 0. However, since it is a recursive solution, expect a stack overflow. ]
[Question] [ In the fewest bytes possible, determine whether the two values given each match one of the following: **First value** ``` 2 string or integer - whichever you prefer to case insensitive too case insensitive two case insensitive t0 case insensitive (t zero) ``` **Second value** ``` b case insensitive be case insensitive bee case insensitive b3 case insensitive ``` # Examples ``` 2 'Bee' true '2' 'b' true 'not to' 'be' false 'that is' 'the question' false ``` [Answer] # [Shakespeare](https://github.com/drsam94/Spl), 4778 Bytes *Note: this answer is not meant to be a serious competitor* ``` To Be or Not To Be, This is the Answer. Hamlet, the main player in our story. Horatio, Hamlet's guide through his internal struggles. The Ghost, a handsome honest bold fair gentle king. Claudius, the worthless usurper of the throne. Ophelia, who Hamlet always writes two. Polonius, the unfortunate third man caught between Hamlet and Claudius. Brabantio, the greater. Banquo, the lesser. Emilia, the greater. Egeus, the lesser. Othello, the greater. Orsino, the lesser. Tybalt, the greater. Titania, the lesser. Valentine, who doubled is greater. Viola, who doubled is lesser. Act I: A simple question in so many words. Scene I: Hamlet passes judgment over the cast. [Enter Hamlet and Horatio] Hamlet: Thou art the sum of a good healthy sunny warrior and a lovely day. [Exit Horatio] [Enter Claudius] Hamlet: Thou art the sum of The Ghost and warm cute brave trustworthy hero. [Exit Claudius] [Enter Ophelia] Hamlet: Thou art the sum of Claudius and a smooth spaceman. [Exit Ophelia] [Enter Polonius] Hamlet: Thou art the sum of Ophelia and a plum. [Exit Polonius] [Enter Brabantio] Hamlet: Thou art the sum of The Ghost and the sum of The Ghost and a rich kingdom. [Exit Brabantio] [Enter Banquo] Hamlet: Thou art the sum of Brabantio and The Ghost. [Exit Banquo] [Enter Emilia] Hamlet: Thou art the sum of Brabantio and the sum of joy and a gentle girl. [Exit Emilia] [Enter Egeus] Hamlet: Thou art the sum of Emilia and The Ghost. [Exit Egeus] [Enter Othello] Hamlet: Thou art the sum of Emilia and the sum of a cunning lover and the sweetest golden embroidered rose. [Exit Othello] [Enter Orsino] Hamlet: Thou art the sum of Othello and The Ghost. [Exit Orsino] [Enter Tybalt] Hamlet: Thou art the sum of Othello and the sum of happiness and fair fine heaven. [Exit Tybalt] [Enter Titania] Hamlet: Thou art the sum of Tybalt and The Ghost. [Exit Titania] [Enter Valentine] Hamlet: Thou art the sum of Tybalt and the sum of a happy day and a pony. [Exit Valentine] [Enter Viola] Hamlet: Thou art the sum of Valentine and The Ghost. [Exeunt] Scene II: The beginning of Horatio's interrogation. [Enter Hamlet and Horatio] Hamlet: Horatio: Open your mind. Art thou as good as Tybalt? If so, let us proceed to Scene IV. Art thou as good as Titania? If so, let us proceed to Scene IV. Art thou as good as Ophelia? If not, let us proceed to Scene XII. Scene III: Are we to? Horatio: Open your mind. Art thou as good as The Ghost? If so, let us proceed to Scene VII. Let us proceed to Scene XII. Scene IV: Can we go further than t? Horatio: Open your mind. Art thou as good as Claudius? If so, let us proceed to Scene III. Art thou as good as Valentine? If so, let us proceed to Scene VI. Art thou as good as Viola? If so, let us proceed to Scene VI. Art thou as good as Othello? If so, let us proceed to Scene V. Art thou as good as Orsino? If not, let us proceed to Scene XII. Scene V: Oone oor twoo? Horatio: Open your mind. Art thou as good as The Ghost? If so, let us proceed to Scene VII. Art thou as good as Othello? If so, let us proceed to Scene III. Art thou as good as Orsino? If so, let us proceed to Scene III. Let us proceed to Scene XII. Scene VI: Hamlet desperately searches for whOo?. Horatio: Open your mind. Art thou as good as Othello? If so, let us proceed to Scene III. Art thou as good as Orsino? If so, let us proceed to Scene III. Let us proceed to Scene XII. Scene VII: Knowing to, what to do? Horatio: Open your mind. Art thou as good as Brabantio? If so, let us proceed to Scene VIII. Art thou as good as Banquo? If not, let us proceed to Scene XII. Scene VIII: Learning what to Bleive. Horatio: Open your mind. Art thou as good as me? If so, let us proceed to Scene XI. Art thou as good as Emilia? If so, let us proceed to Scene X. Art thou as good as Egeus? If so, let us proceed to Scene X. Art thou as good as Polonius? If not, let us proceed to Scene XII. Scene IX: The Eend is nigh? Horatio: Open your mind. Art thou as good as me? If so, let us proceed to Scene XI. Let us proceed to Scene XII. Scene X: Wee may havee succeeeedeed. Horatio: Open your mind. Art thou as good as Emilia? If so, let us proceed to Scene IX. Art thou as good as Egeus? If so, let us proceed to Scene IX. Art thou as good as me? If not, let us proceed to Scene XII. Scene XI: Hamlet is at peace. Horatio: Thou art a beacon of happiness. Let us proceed to Scene XIII Scene XII: The demons have won. Horatio: Thou art nothing. Scene XIII: Hamlet opens up. Horatio: Hamlet! Open your heart. [Exeunt] ``` Outputs 0 if false, 1 if true. This could easily be shorter (and if people really want me to, the word lengths could be cut down), but to do so would be a slap to the face of good ol' Will. I've always felt Horatio is the unsung hero of Hamlet, so I made sure that he was the one to deliver the intense monologue to Hamlet where Hamlet has to ultimately prove that he is as good as Horatio (who represents the newline). The code itself is pretty simple. All of the characters sans Hamlet are ascii values (In order:`newline,space,0,2,3,B,b,E,e,O,o,T,t,V,v`) and then the code is a simple state machine (specifically, a [DFA](https://en.wikipedia.org/wiki/Deterministic_finite_automaton)) that transitions to `Scene XI` as an accept state and `Scene XII` as a reject state. [![This is the basic one I worked off of](https://i.stack.imgur.com/R9sMX.jpg)](https://i.stack.imgur.com/R9sMX.jpg). After making this, I just plugged it into Shakespeare, using the fact that I could drop down to the next state when they were numerically adjacent. I only tested it with the version of Shakespeare I linked in the title, but I believe we define a language by an implementation iirc. [Answer] # [Retina](http://github.com/mbuettner/retina), 28 * 1 byte saved thanks to @MartinBüttner. Quite possibly my quickest ever code-golf answer - 9 minutes after OP. Input parameters are comma-separated. Output is 1 for truthy and 0 for falsey. ``` i`^(2|t[ow]?o|t0),b(e?e?|3)$ ``` [Try it online.](http://retina.tryitonline.net/#code=aWBeKDJ8dFtvd10_b3x0MCksYihlP2U_fDMpJA&input=dHdvLGI) [Answer] # Pyth, 34 bytes ``` .A}Lrw1c2c." Wô-WûÄæ­§Òé } ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=.A%7DLrw1c2c.%22+W%08%C3%B4-W%C3%BB%C2%9B%02%C3%84%C3%A6%C2%AD%C2%A7%C2%84%C3%92%C2%92%C2%94%C3%A9%0A%C2%8A%7D%C2%83&input=t0%0Abe&debug=0) ### Explanation: ``` ."... packed string, gets decoded to: "2 TO TOO TWO T0 B BE BEE B3" c split by spaces c2 split into 2 lists: [['2', 'TO', 'TOO', 'TWO', 'T0'], ['B', 'BE', 'BEE', 'B3']] L for each list: w read a line r 1 convert it to uppercase } and test if it is part of this list list .A test if both return true ``` [Answer] # Pyth, 41 bytes ``` &xrw0c"2 to too two t0"dxrw0c"b be bee b3 ``` [Try it here!](http://pyth.herokuapp.com/?code=%26xrw0c%222+to+too+two+t0%22dxrw0c%22b+be+bee+b3&input=t0%0Abee&test_suite=1&test_suite_input=2%0Abee%0A2%0Ab%0Anot+to%0Abe%0Athat+is%0Athe+question&debug=0&input_size=2) Straightforward list lookup. Prints an empty list as falsy value and a non-empty list as truthy value. Looking or a better way tho, I don't really like this one. [Answer] # Oracle SQL 11.2, 86 bytes ``` SELECT 1 FROM DUAL WHERE:1 IN('2','to','too','two','t0')AND:2 IN('b','be','bee','b3'); ``` Returns one row for truthy and no row for falsey. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~39~~ 45 bytes Code: ``` “2€„…«Œ† t0“' ¡)Ilrk\U“b€ïÍÝ b3“' ¡)Ilrk\>X>* ``` [Try it online!](http://05ab1e.tryitonline.net/#code=4oCcMuKCrOKAnuKApsKrxZLigKAgdDDigJwnIMKhKUlscmtcVeKAnGLigqzDr8ONw50gYjPigJwnIMKhKUlscmtcPlg-Kg&input=VE8KQmVl) Uses CP-1252 encoding. Truthy is when a number is outputted and falsy is when nothing is outputted. **Non-competing version (39 bytes)**, works with the newest version: ``` “2€„…«Œ† t0“ð¡)IlkU“b€ïÍÝ b3“ð¡)Ilk>X>* ``` [Answer] ## ES6, ~~56~~ ~~48~~ 45 bytes ``` (...a)=>/^(2|t0|t[wo]?o),b(ee?|3)?$/i.test(a) ``` Saved 5 bytes thanks to @user81655. Saved 3 bytes from some further optimisation. Saved another 3 bytes thanks to @Patrick Roberts. `t[wo]?o` is the shortest regex I could think of to match all three homophones. If it's permitted to pass the two values as a single parameter array, then the rest parameter can become a normal parameter, saving another 5 bytes. [Answer] # Perl 6, ~~45~~ 44 bytes Thanks to the folks in IRC for helping me golf this down ``` {@_~~(~2|/:i^t[0|oo?|wo]$/,/:i^b[ee?|3]?$/)} ``` **usage** ``` > my &f = {@_~~(~2|/:i^t[0|oo?|wo]$/,/:i^b[ee?|3]?$/)} -> *@_ { #`(Block|309960640) ... } > f("2", "Bee") True > f("2", "b") True > f("not to", "be") False > f("that is", "the question") False ``` **Non-competing alternative, 54 bytes** This is a nice alternative to the above if you think regexes are gross, but it is a tad longer. It could be golfed down a couple more bytes but since it's non-competing I'll leave it as is. ``` {@_».lc~~(qw<to too two t0 2>.any,<b be bee b3>.any)} ``` [Answer] ## Python 2.7, 133 bytes ``` def e(a, b): c, d = """2,too,to,t0,two""","""be,b,bee,b3""" return a.lower() in c and b.lower() in d print e('2', 'bee') ``` Not sure if we're supposed to post solutions if there's a smaller version in the comments but here's my version in Python. Edit: Without the function it's only 73 bytes (and that's not even near the best answers. Forgive me I'm new ``` a, b = "to", "bee" print a in "2 too to t0 two" and b in "be b bee b3" ``` [Answer] ## Ruby, 53 55 52 bytes ``` f=->(a,b){/^(2|t[wo]?o|t0)$/i=~a&&/^b(e?e?|3)$/i=~b} ``` I'll be honest, this is my first attempt at trying to golf a problem. Function call in the form of `f.call(firstValue, secondValue)` `0` is Truthy, `nil` is Falsy. Test it [Here](https://repl.it/BlrV/2) [Answer] # Japt, 36 bytes ``` !Uv r"2|t(0|wo|oo?)" «Vv r"b(e?e?|3) ``` Maybe I missed something, but this should work completely. [Test it online!](http://ethproductions.github.io/japt?v=master&code=IVV2IHIiMnx0KDB8d298b28/KSIgq1Z2IHIiYihlP2U/fDMp&input=IlR3byIgImJlIg==) [Answer] ## Pyth, 39 bytes *-3 bytes by @FryAmtheEggman* ``` .A.b}rN1cY\@Q,."0Wѳ5YYÅJB"."3EW´l¢ï ``` Try it [here](http://pyth.herokuapp.com/?code=.A.b%7DrN1cY%5C%40Q%2C.%220W%C3%91%1A%0F%C2%B35YY%C3%85JB%22.%223EW%C2%B4l%C2%A2%04%C3%AF&input=%5B%22too%22%2C%22b3%22%5D&test_suite=1&test_suite_input=%22too%22%2C%22b3%22%0A%22tOO%22%2C%22Bee%22%0A%222%22%2C%22be%22%0A%22to%22%2C%22be+or+not+to+be%22&debug=0). [Answer] # Python, ~~85~~ 83 bytes @Manatwork saved me two bytes. This is pretty brute force, I'll look into regex solutions next. ``` lambda a,b:a.lower()in'2 to too two t0'.split()and b.lower()in['b','be','bee','b3'] ``` [Answer] ## PowerShell v3+, ~~74~~ 70 bytes ``` param($a,$b)+($a-in-split'2 to too two t0')*($b-in-split'b be bee b3') ``` Doesn't use regex. Takes two input, checks if the first one is [`-in`](https://technet.microsoft.com/en-us/library/hh847759.aspx) the array that's been dynamically created by the `-split` operator, converts that Boolean to an int with `+`, then multiplies that `*` with checking whether the second is `-in` the second array (which will automatically cast the Boolean as an int). This works because `x*y == x&y` if `x` and `y` can only be `1` or `0`. PowerShell by default is case-insensitive, so we get that for free. Will output `0` or `1` for falsey/truthy, respectively. Requires v3 or newer for the `-in` operator. Edit -- Saved 4 bytes by using unary -split [Answer] # Groovy, 52 bytes ``` f={x,y->"$x $y"==~"(?i)(2|t([wo]o?|0)) (b(ee?|3)?)"} ``` `==~` is a cool regex operator in groovy that checks for equality. Tests: [Regex101](https://regex101.com/r/vQ7wH8/2) test. ``` assert f('2', 'Bee') == true assert f('2', 'b') == true assert f('not to', 'be') == false assert f('that is', 'the question') == false ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 32 ~~41~~ ~~43~~ bytes ``` jk'^(2|t[ow]?o|t0),b(e?e?|3)$'XX ``` Same approach as [@DigitalTrauma's Retina answer](https://codegolf.stackexchange.com/a/71699/36398). Inputs are separated by a comma. Truthy output is a string with the two inputs lowercased; falsy is no output. [**Try it online!**](http://matl.tryitonline.net/#code=amsnXigyfHRbb3ddP298dDApLGIoZT9lP3wzKSQnWFg&input=VDAsYjM) ``` j % input as a string k % convert to lowercase '^(2|t[ow]?o|t0),b(e?e?|3)$' % regular expression to match the two inputs XX % match regular expression ``` [Answer] # C# 6, 132 bytes ``` bool t(string x,string y)=>new[]{"2","to","too","two","t0"}.Contains(x.ToLower())&&new[]{"b","be","bee","b3"}.Contains(y.ToLower()); ``` Ungolfed version (Only slightly more readable): ``` bool t(string x, string y) => new[] { "2", "to", "too", "two", "t0" }.Contains(x.ToLower()) && new[] { "b", "be", "bee", "b3" }.Contains(y.ToLower()); ``` [Answer] # Python 2, 67 bytes Uses Digital Trauma's regex. Input is a single string separated by a comma. Not sure if that format is allowed for input... ``` import re f=lambda x:bool(re.match('^(2|t[ow]?o|t0),b(e?e?|3)$',x)) ``` ]
[Question] [ Here's an easy one, with just enough complexity to make golfing non-trivial. ## Input 1. A list of non-negative numbers representing people waiting in line for Thanksgiving dessert. The first (leftmost) number is first in line, and the list can contain repeats (think of each number as a person's first name): ``` Note: Pie not part of actual input. ( ) __..---..__ ,-=' / | \ `=-. :--..___________..--; 6 4 3 1 2 3 0 \.,_____________,./ ``` 2. A non-empty subset of that list, representing a group of colluding friends who will ["chat and cut"](https://www.youtube.com/watch?v=Iqfizyjfv0s&t=29s) to skip ahead in line. All colluders will move just behind the friend already closest to the front of the line, but otherwise retain their relative positions. Everyone they skip past will also retain their relative position. ## Output The new list, after a successful (possibly multi-way) chat and cut. For example, in the list above, for a friend group of `0 2 4`, the output would be: ``` 6 4 2 0 3 1 3 ``` If the friend group was `4 3`, the output would be: ``` 6 4 3 3 1 2 0 ``` ### Notes This is code golf with standard site rules. * A single colluder `x` in the colluder list makes everyone in line with that number a colluder. * The list of people waiting may contain repeats. * The colluder list will not contain repeats. * The colluder list may not be sorted. * The colluder list will have between 2 and U items, where U is the number of unique elements in the queuer list. ## Test Cases The format is: 1. People in line. 2. List of colluders. 3. Output. ``` 5 4 3 2 1 0 3 1 5 4 3 1 2 0 1 2 1 3 1 9 1 9 1 1 1 9 2 3 1 2 3 4 5 4 5 1 2 3 4 5 7 6 1 5 2 4 3 4 5 6 7 6 5 4 1 2 3 7 6 1 5 2 4 3 1 2 3 7 6 1 2 3 5 4 7 6 1 5 2 4 3 3 6 7 6 3 1 5 2 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 5 4 5 4 1 2 3 4 5 4 ``` [Answer] # [J](http://jsoftware.com/), 12 bytes *-1 thanks to FrownyFrog!* ``` [/:OR\@e.-e. ``` [Try it online!](https://tio.run/##dY9fC4IwFMXf/RSHIlTKtT9qqAVSEARR4Ku@hRK99AH68OtuTRlFjN3BPb977tlDz1g4YFcixAocJd2E4dCcj7pdl9emq3uW9Exf9gzUmHd1u2XRYslfJxaTFsRBEPS3@xM5UigISKocUVUNMb0S6X@ZOm44yqwsCeAYDBgjKZFNQ9xxwjKmVxBH1XLCnsKYe5yi6Ywoqo5yPcdsKJQgQtotlkNuSaOY3cJz/KatNtEf72z87Q@tPGc1Kl9ZhzGhn1a/AQ "J – Try It Online") For `6 4 3 1 2 3 0` and `0 2 4`: ``` [/:OR\@e.-e. OR OR … \ each prefix of … @e. the bitmask of friends, or: OR\@e. after the first friend? (0 1 1 1 1 1 1) e. the bitmask of friends (0 1 0 0 1 0 1) - minus (0 0 1 1 0 1 0) [/: (stable) sort the people based on the list (6 4 3 1 2 3 0) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ΣåDi©}®‹ ``` -1 byte thanks to *@ovs*. [Try it online](https://tio.run/##yy9OTMpM/f//3OLDS10yD62sPbTuUcPO//@jTXVMdQx1jIDYGIgtY7miQSQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmWCvpJCYl6KgZA9kPGqbBGRUJoT@P7c4ovjwUpfMQytrD6171LDzf62Oocahlf@jo6NNdUx0jHWMdAx1DGJ1oo11DGNjdRSiow3BQkCujiVQGETChY2BOkyBgiASLGiuYwZUZwqUAhoFkdAxwy4F1o9dyhimB2oHTDWQBRY2BarF4qpYAA). **Explanation:** ``` Σ # (Stable) sort the first (implicit) input-list by: å # Check that the current item is in the second (implicit) input-list # (1 if truthy; 0 if falsey) Di } # Duplicate it, pop this copy, and if it's 1: © # Store 1 in variable `®` (without popping) (variable `®` is -1 by default) ®‹ # Check that the duplicated check is smaller than `®` # (1 if truthy; 0 if falsey) ``` Here the same TIOs with map instead of sort-by, so you can see any leading non-friends become `0`, all friends become `0` as well, and any non-friends after the first friend become `1`: [Try it online](https://tio.run/##yy9OTMpM/f//3NbDS10yD62sPbTuUcPO//@jTXVMdQx1jIDYGIgtY7miQSQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmWCvpJCYl6KgZA9kPGqbBGRUJoT@P7c1ovjwUpfMQytrD6171LDzf62Oocahlf@jo6NNdUx0jHWMdAx1DGJ1oo11DGNjdRSiow3BQkCujiVQGETChY2BOkyBgiASLGiuYwZUZwqUAhoFkdAxwy4F1o9dyhimB2oHTDWQBRY2BarF4qpYAA). [Answer] # [R](https://www.r-project.org/), ~~49~~ ~~47~~ ~~45~~ 42 bytes *Edit: -2 bytes, and then -3 more bytes, thanks to Giuseppe* ``` function(l,f)l[order(cummax(p<-l%in%f)-p)] ``` [Try it online!](https://tio.run/##dY/NCoMwEITvPsVCEQxEUBM81ScpPYT8oBA3JVlp@/Q2tS296GVhZ2c@duKqR0UKjV5oWN2CmqaAleeO@UuIxsZKL/OsHtXtXPtywtKx@sauqx901XPJBW95l2fDCpelJi@SFX/ohoIT9CChgwYEtCCK4iCehaOw2KIZsRfOHrKJ4D5ahIAWggMaLbg4WTQJEqlICZSPVpknKPpeA9LP6ie02w99Zjb7X7wLyE@F9QU "R – Try It Online") **Commented:** ``` function(l,f` # function with arguments: # l = line # f = friends p=l%in%f) # define p as TRUE at positions of friends in the line l[order # now output l, in the order of (lowest>highest): -( # minus (so now highest>lowest) p # 1 for each friend +2*!cumsum(p) # +2 for anyone ahead of the first friend ))] # (so, in the end, anyone ahead of all friends gets -2, # the friends get -1, # and anyone else behind the first friend gets zero). ``` --- **Previous approach: [R](https://www.r-project.org/), ~~67~~ ~~59~~ 54 bytes** *Edit: -8 bytes thanks to Giuseppe, then -5 more bytes thanks to Robin Ryder* ``` function(l,f,p=which(l%in%f))c(l[z<-c(1:p-1,p)],l[-z]) ``` [Try it online!](https://tio.run/##hY7BCoMwEETvfsVCERKIkKh4KPVLxEOICQmEVXRF6s/bVFp6aellYWfnzc58GK9J42BWag@3oqEwIovCiandfDCexTxg7jg3LHb7rTBMXadCiYn3InbF3vMjtoY1ohaVUKJMU/LMJUmmpebZ58EzlsMFGqihBAkVKKiy7AeehF9wdaIp4hucPGQXgs1bhBEtjA7IW3BzsDgssJCeaQEdZ6uHO2h6XUektzUGtGeHJmXK/y2OBw "R – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~79~~ 72 bytes ``` def f(x,y):m=min(map(x.index,y));print x[:m]+sorted(x[m:],cmp,y.count,1) ``` *-7 bytes thanks to @ovs* [Try it online!](https://tio.run/##FchBCsMgEAXQq2Q50k@oSbMx9CTiokSlLmaUxIKe3tC3fKXXb5ZlDB/iFKmhK8NvTkL8KdTmJD78U@3lTFKnZg27x5XPGjw1y8bh4II@H/knFVqNSHbDCysWaDwd7Art1LgB "Python 2 – Try It Online") [All testcases](https://tio.run/##XZFNa4QwEIbv@RVDTgkNsq51y1os7KVQ6KGwR9fDopEGNIpGcH@9nUn2g25CCPPMO2@SyXBxv73drmutG2jEoi4y6/LOWNGdB7FExtaaoHwftZtHC0uRdeXL1I9O12IpuqxUVTeoS1T1s3Uqlmt1nvQEOXDOU3iFBLYQw4YlELMQx0g2jMU@QeGehUVzjzQJyQTVKaP1iNgb7FCVIkArSsLOM7KOQ@1/SYCBkQsKnyXJ1SO5sfv5zzu@ibGmH4EeCcb6fYqmoTVO8JM9WS4zBjiwaUovg66wT9iMojDWiUqCL6bK1lh9LZSlx0Rung9LLktv2M8OfcIXeTCMaAmCFz@H47HkYBrS5Pn9VN3iHXnxefj6LrlUdCOef3BFsvUP). I take a unique approach here using Python's `sorted` function, which performs a stable sort. Might not be the shortest Python approach, but it is interesting. ``` def f(x,y): # x = input line, y = list of colluders m = min(map(x.index,y)) # index of the first colluder in line print x[:m] # The first m people do not change positions sorted( x[m:], # we sort the people after the first m cmp, # default comparison function y.count, # key function is y.count: returns 0 for numbers not in y # and 1 for numbers in y 1 # sort in descending order ) ``` [Answer] # [Haskell](https://www.haskell.org/), 59 bytes ``` (h:t)%c|all(/=h)c=h:t%c l%c=[x|b<-[1<0..],x<-l,elem x c/=b] ``` [Try it online!](https://tio.run/##lZBNDoIwEEb3nGIWkkAygsiP0dAjuHbRNAZqkxIHRYWEGO@OUFR06aZp30zfNxmd3Y6KqOscvaldWz4yIsdn2pWsB7a0yJaMt488nfMgXXiewDadEypSJbQgfZaL7tKoRt2AAecxQoQQIiwRAoSFQODB@xWacz2x0HTHA1ghJKYcm8og@R9PViEseSZqDuo6DjZkv1rMAO/cyDiSr9/DNfxFo7DMilPvKrNqu4fqWpxqmMG9qHZFrcGxXXjt4RPcPQE "Haskell – Try It Online") Test cases and inspiration from [ovs's solution](https://codegolf.stackexchange.com/a/215562/20260). We use `[1<0..]` to generate the list `[False,True]`. Having handled the prefix of non-colluding numbers, we then pass over the remainder twice, first to take colluding numbers, then to take non-colluding ones. A same-length alternative is: **59 bytes** ``` (h:t)%c|all(/=h)c=h:t%c l%c=[x|b<-[id,not],x<-l,b$elem x c] ``` [Try it online!](https://tio.run/##lZDLDoIwEEX3fMUsIIFkiA8eRiOf4NpF0xioTWgcHgokxPjvCAVEl26a9sz03MmkcXWTRF1np4fascQrJrJXUeqIqAeWMMgSEWtfydFl6op5UXNsjy5hYkqSGbQgeHdvZCMriICxAMFH8BC2CBuENUdgm/nl6XO/ME93BwPYIYS6HOjKIPkfL1bODVEQNVf5GAcbsqcWPcCc62tH@PV7uHq/aBRmscp7VxaXpwuUD5XXYMJTlWdVp2BbDkx7@AR3bw "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` e€»\_$Ụị⁸ ``` [Try it online!](https://tio.run/##y0rNyan8/z/1UdOaQ7tj4lUe7l7ycHf3o8Yd/w8vV4r8/z862lRHwURHwVhHwUhHwVBHwSBWRyHaEMYzBpOWCDFjsGpTkIC5joIZWNoULAMyhHRhhKkQnpGOsY6JjqmOSWws0G0g66GqwG6AWW0CNsYMyQAQ0xhVCGxmNNgoAA "Jelly – Try It Online") More or less a translation of xash's J answer. ``` e€ For each person in line, are they a friend? _ Subtract that from »\ $ its cumulative maxima, Ụ sort the indices, ị⁸ index back into the line. ``` `iⱮ»\_$Ụị` almost saves a byte by taking colluders on the left and the line on the right, but it doesn't succeed at preserving the order of duplicate colluders in cases such as `[1,2,3,4,5,4], [5,4]`. # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` iⱮṂœṖ⁸e¬¥Þ€F ``` [Try it online!](https://tio.run/##y0rNyan8/z/z0cZ1D3c2HZ38cOe0R407Ug@tObT08LxHTWvc/h9erhT5/390tKmOgomOgrGOgpGOgqGOgkGsjkK0IYxnDCYtEWLGYNWmIAFzHQUzsLQpWAZkCOnCCFNjY4GOAdkHFQZbCrPLBKzPDEkHiGmMKgQ2BAA "Jelly – Try It Online") [Answer] # [Factor](https://factorcode.org/), 62 bytes ``` [ '[ _ member? ] 2dup find . swapd cut rot partition 3append ] ``` [Try it online!](https://tio.run/##lVCxTsMwEN3zFY@pW0RiUgQIMVYsLIipqpCbXCSLxjb2Waiq@u3BTgkJ7cRg6d47v3t3r5U1G9e/vT6/rO7Ruj0@yGnawdNnIF2Th3XEvLdOaQYbs/M5k2fUptsqLaPa4yHLrjCwStvAPjvggAo3EChR4BrHDJEpBiTiu5sxIv6rfvAtlpGrIpu0/@PGWceIk3/yGTuj3@SUquUf5akWZ@wwD@jXWKzxjo66LbknbFA2waJVukEO/yVtgzownGFY6VixMhpCWkvxx6YvO2nHjEzgs5CS1RRSMSxcXhw2Dynp5mufAkk4dSZO/MZ0edQj8v4b "Factor – Try It Online") The extensive `sequences` library is quite helpful here. Takes `line cheaters` on the stack, and returns the modified line through the stack. Prints a garbage to stdout each time it is run. ### Ungolfed ``` [ ! ( line cheaters ) start anonymous lambda definition '[ _ member? ] ! ( line fun ) convert cheaters array to membership function 2dup find . ! ( line fun idx ) find index of first cheater swapd cut ! ( fun left right ) cut line at that index rot partition ! ( left cheaters rest ) partition the right into ! cheaters and non-cheaters, using the membership function 3append ! ( ans ) concatenate the three arrays ] ! end anonymous lambda definition ``` --- # [Factor](https://factorcode.org/), 74 bytes ``` [ dupd '[ _ member? 1 0 ? ] map dup cum-max swap v- zip sort-values keys ] ``` [Try it online!](https://tio.run/##hZBPT8JAEMXvfIp3Qw8ltkWMeOBouHAxnhpi1jJA4/aPnSmKhM9ed5e2oBHMXmbfzPzmzSxVLHlZPz9NZ49jKOY8ZizLLd6ozEgjVbIesChJWBKTcv8N2SYG03tFWUzc47yUJFtB8lzzQIgFD73pbIyVrkTyrNdFuIJOMkK8JiVkIJ7nhD6u6wiLqligH@EFKaWvVE7g4wYTzM3gwmYRV6mXqk/whxE2Hr6SAna6t1G6Ija@t4x5HSutjYUddrjFEKHhBIa0Nw@IOjVwfKvtXI2N0Fmdo8oS8ew6juS7d2@6whOS7yihyxxIbXSJZBlD42LfVEa/VDjSMT5HusPI7eJ3rqJG9Y0euC33DWnkWJdIB4rlnSe1ky6Twq7rPClsHP1/p/ZKP@/UaqfKH6T6Gw "Factor – Try It Online") Factor's standard library is feature-rich enough that it can almost directly replicate [xash's J solution](https://codegolf.stackexchange.com/a/215560/78410). Except that it's 5~10 times bloated byte-count-wise. ### Ungolfed ``` : glutton ( line cheaters -- line' ) ! takes two arrays on the stack ! and returns the cheated line as an array dupd ! duplicate line under cheaters '[ _ member? 1 0 ? ] map ! for each number in line, 1 if it is a cheater, ! 0 otherwise dup cum-max swap v- ! cumulative maximum minus self (of the above) zip sort-values keys ! sort line by the above ; ``` [Answer] # [Haskell](https://www.haskell.org/), 65 bytes ``` q!c|f<-(`elem`c),(h,t)<-span(not.f)q=h++((`filter`t)=<<[f,not.f]) ``` [Try it online!](https://tio.run/##lZDLDoIwEEX3fsWQuGjDYEQexgQ@wbULQoRgGxrLu2yM/45SQHTpppneO3PuZPK0uzMph6ExsicPLJIwyYoko0hyVDSwujotSVmpHadNmJsmIQkXUrE2UTQMgoijNmM6ND3rWQchRJGH4CI4CAcEG2EfI0T28nP0e1o1R3d7o3BE8LXtaWeE/C@v1DjeZJWU/Y2102Jj9tyiF1hyXc3wv6bH0vmVJmCRivLNKtL6fIW6FaWCLTxEfREqB2JQmO/wCR5e "Haskell – Try It Online") **Commented**: ``` q!c| f<-(`elem`c), -- f is a function to check whether a number is a colluder (h,t)<-span(not.f)q -- h is the longest prefix of non-colluders, t the remaining list = h++ -- the result is h and ... ( =<< -- ... the concatenation of the results of ... (`filter`t) -- ... filtering the remaining list by ... [f,not.f]) -- ... f and not f (colluders and not colluders in t) ``` --- # [Haskell](https://www.haskell.org/), 66 bytes With some inspiration from xnor's and AZTECCO's answers I came up with a pointfree function that is just 1 byte longer. ``` (takeWhile<>g.(not.)<>((.).g<*>dropWhile)).flip(all.(/=)) g=filter ``` [Try it online!](https://tio.run/##lZAxb4MwEIX3/IobOtiV4zQlpKoETF0zZ6CossAGKwd2jFn64@sG04h27HLyvXf3vZM7MV4kYtC9Nc7Dm/CCn8xgdAOEZAWlG5W/B@LFRZ47jTIrWk4G4znNCkI45W32WDTO2OhSyhVqSwQiJ7v8tt3mSqOXLlwnOckRcijLlMGBQcLgmcGewVPFoNzfuyTW11VL4nQ6Cy8MjtFOozND/i@v1Kra1AZxaqRbDpuzf0biAffcQ2Qcf23Pz@SvtAB7oYcbqxf29AHW6cHDA3xqe9a@AwVr3vIf4atWKNoxbGtrvwE "Haskell – Try It Online") In GHC version 8.4.1 and above `(<>)` is included in the Prelude, in the old version on TIO it has to be imported manually. [Answer] # [Racket](https://racket-lang.org/), 145 bytes ``` (λ(a b)(let([m(apply min(map(λ(x)(index-of a x))b))])(append(take a m)(call-with-values(λ()(partition(λ(x)(member x b))(drop a m)))append)))) ``` [Try it online!](https://tio.run/##jZDBTsMwDIbve4pf4jD7UIlSOrRnQRzcNYVoSRplYeuejXfglYrTTeLAkHaxbPnzZ8tJdnuT5wcn4R1pKVbUm8EGg2Gm7y8SdEzOZHr1JDG6M7wN5CWW5sRkQ2@mahwgmJg75jcunAk9ZdmblcAz7cS56mTzR3UU92kOZZYpSso22zFcVd74ziRMupGpT2NEGWa@6DThmfU6e4hOzi6ABqypxTMaPKHGI6@pQa3YH6heAG1iy6Xa/gc1amsVKfEG8oKNOloFdekFw@YecHHfAza3fdfb@DfTZ/wA "Racket – Try It Online") That's even longer than my Red solution :) It's insane that `partition` returns two separate values rather than a list with two sublists - that's why I need to use `call-with-values` and put `partition` within an additional lambda... [Answer] # [Ruby 2.7](https://www.ruby-lang.org/), 39 bytes ``` ->q,c{q.flat_map{c-[_1]!=c ?q-q-=c:_1}} ``` [Try it online!](https://tio.run/##hVFBboMwELzziim9GhTHoVEjuXmIa1XUBQWplXAwUiLg7RSvIaG95GJ7d2ZnZ@Rz@3kdSzkmb5aZzqbld@4@fvK666veJKrST9LgaBObSHOohmF0ReMaSKgIUCpj2DEIhi0DZ9hoBjVVXGtGOF8QQeerx@n@gwtSyTxI9wzuGV5oLCOWX7RQJuQBa1Z@wBIrobuX1byvdKSj4lIXxhVfS/Jb8MDbBA1OtQ84b1@665C@FewEEb7m3nyGiYzc3AGxzvBf3fuk70mL3JzQobcMpkfdTj8WP3dnWSrf0QOmAlJiSZU2p6p0OCJ@b7d7LmIcwnNn4iHGMP4C "Ruby – Try It Online") (40 bytes because TIO's Ruby version doesn't support numbered block parameters) Relies on the `Array::-` method, which returns all elements of the first array not present in the second. Given a queue `q` and colluders `c`, the ordered lists of non-colluders and colluders are `q-c` and `q-(q-c)`, respectively. ``` ->q,c{ q.flat_map{ # For each person in the queue c-[_1]!=c # Are they a colluder? ?q-q-=c # If they are the first colluder, replace them with all colluders (in same order as they appear in the queue) and remove remaining colluders from the queue in one fell swoop. Second and subsequent colluders will be replaced by an empty array. :_1 # If not a colluder, leave them alone } } ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 20 bytes ``` {x@<{(|\x)-x}x in y} ``` [Try it online!](https://tio.run/##ZYyxDoMwDER/5TbsgappCKg1A//RdkVCSHQ1Cvn21ETZWM7n5zuv7W/NeX5FncZIx0e51aRYNuwpR1LZZX6bfjndGqKADh4PONzFjGMhV1bzeMopFXlLBjnFwIDeTsGw1QtEf8WldsW@ZOtPqZM5/wE "K (oK) – Try It Online") An experiment in making a K port of [xash's J answer](https://codegolf.stackexchange.com/a/215560/75681) - please upvote his/hers solution! [Answer] # [Haskell](https://www.haskell.org/), ~~83~~ 72 bytes ``` import Data.List.Split q?c|h:t<-splitOneOf c q=id=<<h:filter(`elem`c)q:t ``` [Try it online!](https://tio.run/##lVA9b4MwEN35FTd0SKRrFGJMFATKkjFVhg4dEGos4girhvBhlqr/nfoMKclYWbLvvXfv3cmF6L6k1sOgyvrWGjgII1ZH1ZnVe62V8Zp9/lNEJn7tCJ4qebpCDk2iLkkcF9FVaSPbxVlqWZ7zZROZoellLztIIE05QoDAEDYIPsI6Q0j9O2Lu3s0cc92ciC1C6GTuFAr5Pz2nZvg8wt6QZV5@07q/yHZclvaZbG6p@y6jIXxIpJI9U@MQjoGNLYWqbGIp6rdPqFtVGXiBb1V/KFPAYr@E6Yf@xg9kRIY@bnCdeTaTzs4i5pB9rc5tvcUQqdefNMKjTqNHTDnccsHsfUyx6Bc "Haskell – Try It Online") * Longer than @xnor and @ovs great answers but I think it's worth posting because it's quite short and it has a simple and interesting approach. * Thanks to @ovs for the precious advices, saved a lot and looks more golfy now! ``` q?c ... = - infix function taking q-ueue and c-olluders lists |h:t&lt-splitOneOf c q - split queue at colluders id=<< - concat map : h:filter(`elem`c)q:t - first split, colluders and the remaining ``` [Answer] # [Perl 5](https://www.perl.org/), 75 bytes ``` sub{$f=1;map$_%1e5,sort map$_+1e5*++$r+1e9*($_~~@_&&($f=2)?1:$f),@{+shift}} ``` [Try it online!](https://tio.run/##fZLdTsJAEIXv@xSTZoEuHRKWWhQaYl/AO@@aplFssUba0i1GQuDSB/ARfZE62z9QidmLPTvnfDO7yWZh/mqX6x2LFqXcPu5pF876IWNBT4Q2yjQvoDqadByaJstJzIYGC45HN@j3DQIm/FbMWcTR3ZvyOY6Kw6F0tK0M4T6UxXx@l@aho0VpboAHno1XaOEEBY59BADPQlEJaD1B7tj3UauL4IkqroxZjbSikmrNKGH9RizqZre5M3nyzoBrnFIfmyy6AiUVgNN6nPLU1cTvKX@gOtFB9SRC/4WsZk4DWa174T1NDs4Lnbz0/Abx7I794fka31fQemewDbIlsvA94wuXBU5TB3eVFrCAPotUxGVLXluxNF7SODEGMECV4c14gFO56tbVZZbHSRHpvdHkRsLXxydAbySmEt4kKakj6JEBLttQluYAVxXVutpVL51rB@0pTcKgoK8VJyun/AY "Perl 5 – Try It Online") ``` sub{ $f=1; #f = 1 if first colluder not found, = 2 after 1st colluder map$_%1e5, #remove part used for sort, input elems remain in sorted order sort #sorts numerically as all elems have same number of digits now map #converts each elem in input queue to sum of: $_ #the elem itself +1e5 * ++$r #plus 100000 times the input rank in the queue +1e9 * ( #plus 1 billion times the "rank overriding number" which is: $_~~@_&&($f=2) #true if current elem is colluder (if so, set $f=2) ? 1 #...1 if colluder : $f #...or $f if not colluder (f is 1 before 1st colluder, 2 after) ), @{+shift} #input queue } ``` Works for input elems 0-99999 and for queues up to 10000 elems. Increase 1e5 and 1e9 to 1e8 and 1e16 accordingly (spending one more byte of code) to avoid this, after which computer memory size becomes a bottleneck for most setups I guess. [Answer] # JavaScript (ES10), 60 bytes Expects `(people)(subset)`, where `people` is an array and `subset` is a Set. ``` a=>b=>a.flatMap(i=>b.has(i)?j=a.filter(x=>j&b.has(x)):i,j=1) ``` [Try it online!](https://tio.run/##jZBBDoIwEEX3noKVaZMRrBUMJsUTuHJJWFQtWkKAAFFvj9OCkaAmtquZ@f/1dzJ5k82p1lW7KMqz6lLRSREdRSTdNJftXlZEY@1eZUM03WUC@zpvVU0eIsrm/eBB6VZDJhjtTmXRlLly8/JCUhL7sAYOK2CwTCgp1N05qJbEHFhCKXXM8TynVzHULWcTALNmMwzHAFu@AQzMDVHLvwE48v2x3ZaDfQAMqql9AwGSfRxjxAkCAgtBu1GZT7BvCX4irHqM6FMg6G8EHzI4LwR/6X7s4eN90xov0ra6Jw "JavaScript (Node.js) – Try It Online") Or [Try it with map()](https://tio.run/##jZBBDoIwEEX3noKVaZMRqRWMJsVDuCQsqhYtQSBAlNvjtGAkqIntpjPz/@tvU3mX9anSZbPIi7PqEtFJER5FKN2bLInGs3uVNdF0nwrpJjprVEVaEabzftBSutOQCka7U5HXRabcrLiQhEQ@rIHDChh4MSW5ejgH1ZCIA4sppY5Zy6XTqxjqvNkEwKzZDLdjgC3fAAZmb1HLvwE48v2x3ZaDfQAMqql9AwGSfRxjxAkCAgtBu1GZR7BvCX4irHqM6FMg6G8EHzI4LwR/6X78w8f9pjX@SNvqng) to get a better picture of the process. ### How? The variable `j` is initially set to `1`. We walk through the queue with [`flatMap()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap). Each identifier `i` that is not included in the group of friends is copied as-is: ``` b.has(i) ? … : i ``` As soon as a guy from the group of friends is reached, we append all friends at once in their order of appearance in the queue, and assign the result to `j`: ``` j = a.filter(x => j & b.has(x)) ``` Arrays holding at least two elements are turned into `NaN` when coerced to a number. So the next time a friend is encountered, `j & b.has(x)` will be falsy(1) and `filter()` will return an empty array. As a result, all following friends are ignored as expected. --- (1): It could actually be truthy if `j` is updated to a singleton array holding an odd identifier. But that would mean that there's only one friend in the queue, so the test `b.has(i)` would not be triggered another time in that case anyway. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~201~~ \$\cdots\$ ~~172~~ 171 bytes Saved ~~12~~ a whopping ~~29~~ 30 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` #define z 0;for(i=-1;++i<n; #define P&&printf("%d ",l[i] q;p;i;j;f(l,n,c,m)int*l,*c;{q=p=z!p P))for(j=m;j--;)l[i]==c[j]?q=p?q:i,l[i]^=p=-1:z)0>l[i]P^-1);z)i>=q&0<=l[i]P);} ``` [Try it online!](https://tio.run/##hVVdU@JAEHznV@zlSovgpM58gq7Rh6t79x3R8obBi7WsEbDkoPjrx21Ckp1o1FRZhJ7u3ukhcdB7QNzvv09plmkSG3EqZ0@LfpZ6vjw5yS607NW16@PjfJHp1azvHE2FA2qcTXrPMpeZfJSzvgINCHPXMAYKBii3z2mebr7l4tp1C8/HdC4fPU@6hTBNcfw4uTKUq@fzrPS6NXTPP9@4p5fF1@tbz3flxs0u0@fj04u0xFy525dN9ItjhAJhPoV2xbYnzGWOEUVFZCI1SczHhdBSmCA1o7iaFMujqQP97MoRzrnjuGUXrix5ux5n3mjH4Lve/D7T/dqqOEf544k5auv7fgyhuSIIIQAfTneyIWFFCsFnKHVJfSPmUhVUpNK0qJ8Bd27KZ9y5Qf1SEEDILUNrGUIEMferam2UPlGo6FAbQmLOig0jap2GUeMICfdkutho/Lddxl/4xqwn7tvSFf0ad@6bfOGb1L9Vq1umCmsddx22JsT9PqzQhxU1ejPvtmNVbaP0mWYgVrRcLe/UgaN8UAGoEFQEKgaVgBqCGr3n44GPPmAAGAJGgDFgAjgEZHxR@@uDYJlt6Mn8R/DdH9XtwNxDDQcMDiwcMji0cMTgyMIxg2MLJwxOLDxk8NDCIwaP3PeBsB0IWSC0gZAFQhsIWSC0gZAFQhsIWSC0gZAFQhsIWSC0gZAFQh5oIGidE65oWgYSW/KBAqAQKAKKgRKgIdCoS3GnK03lTGwKZKdAbApkp0BsCmSnQGwKZKdAbApkp0BsCmSnQGwKZKdAbArUTAH/3C8GYnH4QZ2b9a/gZn320/zFDgj@PXQqhd0mekrraqOUtxei8q@ee3teDZRLp@DyxXPYWcaofh1LxkRyglBaWIbupPx@mY2VZuCc5pj/7Rscip2o9KB5rF1Xvlt8OT3lisTrfbbK9IOxFMos@PPDlmuRS0ulXdnOgE2H2Nkgsgz4PkPdBz4p9TItWpgtMtLTZWcLCKg7Qmh6NW0vV280s6pl@EDWZh8edNNr83p0xSnTsNfhozw1pTMGQVc7Xvuywl1vt/@HM3X/sNx7r/8B "C (gcc) – Try It Online") Function takes a list of people waiting in line, its length, a list of colluding friends, and its length. Prints the new list to `stdout`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` ≔⁻θ⁻θηε≔⌕θ§ε⁰ζI…θζIεI✂⁻θηζ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DNzOvtFijUEcBzsjQ1NRRSNW05oKqcMvMSwGJO5Z45qWkVmik6igYgJRUAZUEFGXmlWg4JxYDicrknFTnjPwCkNoqTU1U2VQ0fnBOZnKqBpKdUD3//0dHm@somOkoGOoomOooGOkomOgoGMfqKEQbgnnGsbH/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⁻θ⁻θηε ``` Get the sublist of the colluding friends. This is actually calculated by removing the entries of colluding friends from the original list, then removing those entries from the original list. ``` ≔⌕θ§ε⁰ζ ``` Get the position of the first of the colluding friends in the original list. ``` I…θζ ``` Output everyone ahead of the first of the colluding friends. ``` Iε ``` Output the colluding friends. ``` I✂⁻θηζ ``` Output everyone else who wasn't ahead. (We already calculated this list but it actually costs a byte to save this rather than recalculating it.) [Answer] # [Red](http://www.red-lang.org), 124 bytes ``` func[a b][m: 0 until[m: m + 1 find b a/:m]rejoin[take/part a m - 1 collect[foreach c a[if find b c[keep c]]]difference a b]] ``` [Try it online!](https://tio.run/##bU@7bsMwDJytrzhkLYLEdZ0gHvIRWQkOskShSmzZEJTvdyU76VCUAx/HOz6i2OUmlli5Dot7BkMaPdPY4YhnSH4o6YgP1HA@WPTQh27kKPfJB0r6IYdZxwSdSXvUykzDICaRm6Jo8w0DTd69tYYeIjMMM1vvnEQJRlA28vJWbAcoZKMWX2jwmZcfmRrUrCqq1zoXuDAV98KazG2ZitvEZ5wyqc2tPGRt4FTIf/BV@w/ebOzXaP5NVKWYMEcfEmicBlt@L6HHbn/dwZV/wBUvPw "Red – Try It Online") ]
[Question] [ The challenge is simply; output the following six 2D integer arrays: ``` [[ 1, 11, 21, 31, 41, 51], [ 3, 13, 23, 33, 43, 53], [ 5, 15, 25, 35, 45, 55], [ 7, 17, 27, 37, 47, 57], [ 9, 19, 29, 39, 49, 59]] [[ 2, 11, 22, 31, 42, 51], [ 3, 14, 23, 34, 43, 54], [ 6, 15, 26, 35, 46, 55], [ 7, 18, 27, 38, 47, 58], [10, 19, 30, 39, 50, 59]] [[ 4, 13, 22, 31, 44, 53], [ 5, 14, 23, 36, 45, 54], [ 6, 15, 28, 37, 46, 55], [ 7, 20, 29, 38, 47, 60], [12, 21, 30, 39, 52]] [[ 8, 13, 26, 31, 44, 57], [ 9, 14, 27, 40, 45, 58], [10, 15, 28, 41, 46, 59], [11, 24, 29, 42, 47, 60], [12, 25, 30, 43, 56]] [[16, 21, 26, 31, 52, 57], [17, 22, 27, 48, 53, 58], [18, 23, 28, 49, 54, 59], [19, 24, 29, 50, 55, 60], [20, 25, 30, 51, 56]] [[32, 37, 42, 47, 52, 57], [33, 38, 43, 48, 53, 58], [34, 39, 44, 49, 54, 59], [35, 40, 45, 50, 55, 60], [36, 41, 46, 51, 56]] ``` What are these 2D integer arrays? These are the numbers used in a magic trick with cards containing these numbers: [![enter image description here](https://i.stack.imgur.com/OtNyd.png)](https://i.stack.imgur.com/OtNyd.png) The magic trick asks someone to think of a number in the range [1, 60], and give the one performing the magic trick all the cards which contain this number. The one performing the magic trick can then sum the top-left numbers (all a power of 2) of the given cards to get to the number the person was thinking of. [Some additional explanation of why this works can be found here.](http://www.mathmaniacs.org/lessons/01-binary/Magic_Trick/) ## Challenge rules: * You can output the six 2D integer arrays in any reasonable format. Can be printed with delimiters; can be a 3D integer array containing the six 2D integer arrays; can be a string-list of lines; etc. * You are allowed to fill the bottom right position of the last four cards with a negative value in the range `[-60, -1]` or character `'*'` instead of leaving it out to make the 2D integer arrays rectangular matrices (no, you are not allowed to fill them with `0` or a non-integer like `null`/`undefined` as alternative, with the exception of `*` since a star is also used in the actual cards). * The order of the numbers in the matrices is mandatory. Although it doesn't matter for the physical magic trick, I see this challenge mainly as a [matrix](/questions/tagged/matrix "show questions tagged 'matrix'")-[kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") one, hence the restriction on order. The order of the matrices themselves in the output list can be in any order, since it's clear from the top-left card which matrix is which. ## 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. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~63~~ 46 bytes ``` say grep(*+&2**$_,^61)[$_,*+5...*for ^5]for ^6 ``` [Try it online!](https://tio.run/##K0gtyjH7/784sVIhvSi1QENLW81IS0slXifOzFAzGkhraZvq6elppeUXKcSZxoIpoHoA "Perl 6 – Try It Online") Outputs as 2D arrays on multiple lines, with the last array of each one cut off if necessary. [Answer] # [Python 2](https://docs.python.org/2/), 76 bytes ``` r=range;print[[[i for i in r(61)if i&2**k][j::5]for j in r(5)]for k in r(6)] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8i2KDEvPdW6oCgzryQ6OjpTIS2/SCFTITNPoUjDzFAzM00hU81ISys7NjrLyso0FiSbBZE11QTzsqFqNWP//wcA "Python 2 – Try It Online") The method here is to create a list of all possible numbers `r(61)` and then whittle that down to the list of numbers for a card `i&2**k`. Then, by using list slicing, that 1D list of numbers is rearranged to the correct 6x5 card size `[card nums][j::5]for j in r(5)`. Then, this generator is just repeated for 6 cards `for k in r(6)`. --- While I could not find any solutions less than 76 bytes, here are two others that are also 76 bytes: ``` r=range;print[[[i for i in r(61)if i&1<<k][j::5]for j in r(5)]for k in r(6)] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8i2KDEvPdW6oCgzryQ6OjpTIS2/SCFTITNPoUjDzFAzM00hU83QxiY7NjrLyso0FiSbBZE11QTzsqFqNWP//wcA) This next one is inspired by [Jonathan Allan](https://codegolf.stackexchange.com/a/184867/81432). ``` k=32 while k:print[[i for i in range(61)if i&k][j::5]for j in range(5)];k/=2 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9vW2IirPCMzJ1Uh26qgKDOvJDo6UyEtv0ghUyEzT6EoMS89VcPMUDMzTSFTLTs2OsvKyjQWJJ2FkDbVjLXO1rcFmgYA) Any comments are greatly appreciated. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~12~~ 11 bytes -1 byte thanks to the master himself:) ``` 60:B"@fQ6eq ``` Explanation: ``` 60: % create a vector [1,2,3,...,60] B % convert to binary matrix (each row corresponds to one number) " % loop over the columns and execute following commands: @f % "find" all the nonzero entries and list their indices Q % increment everything 6e % reshape and pad with a zero at the end q % decrement (reverts the increment and makes a -1 out of the zero % close loop (]) implicitly % display the entries implicitly ``` [Try it online!](https://tio.run/##y00syfn/38zAyknJIS3QLLXw/38A "MATL – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` E⁶E⁵⪫E⁶§⁺§⪪Φ⁶¹&πX²ι⁵ν⟦*⟧λ ``` [Try it online!](https://tio.run/##NYkxC8IwEEb/ypHpIueg0C5OdRAqCAFHcQhtwIMjCWm0/vt4Dh0ej@9908uXKXlpzRWOFW8@Y0/wV0dwTRy3NNQxzuGLTt4LbuOehSteWGoo2B8IzlxXXsIQZ8wELq3ajwRsrSXolKg8zM481aIYMPrZU2tt/5Ef "Charcoal – Try It Online") Link is to verbose version of code. I tried calculating the entries directly but this was already 27 bytes before adjusting for the `*` in the bottom right. Outputs each row joined with spaces and a blank line between cards. Explanation: ``` E⁶ Loop over 6 cards E⁵ Loop over 5 rows E⁶ Loop over 6 columns Φ⁶¹ Filter over 0..60 where π Current value & Bitwise And ² Literal 2 X Raised to power ι Card index ⪪ ⁵ Split into groups of 5 § ν Indexed by column ⁺ Concatenated with * Literal string `*` ⟦ ⟧ Wrapped in an array § λ Indexed by row ⪫ Joined with spaces Implicitly print ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` 60L2вíƶ0ζε0K5ô®ζ ``` [Try it online!](https://tio.run/##ASIA3f9vc2FiaWX//zYwTDLQssOtxrYwzrbOtTBLNcO0wq7Otv// "05AB1E – Try It Online") **Explanation** ``` 60L # push [1 ... 60] 2в # convert each to a list of binary digits í # reverse each ƶ # multiply each by its 1-based index 0ζ # transpose with 0 as filler ε # apply to each list 0K # remove zeroes 5ô # split into groups of 5 ®ζ # zip using -1 as filler ``` # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` 6F60ÝNoôāÈϘ5ô®ζ, ``` [Try it online!](https://tio.run/##ASQA2/9vc2FiaWX//zZGNjDDnU5vw7TEgcOIw4/LnDXDtMKuzrYs//8 "05AB1E – Try It Online") **Explanation** ``` 6F # for N in [0 ... 5] do 60Ý # push [0 ... 60] Noô # split into groups of 2^N numbers āÈÏ # keep every other group ˜ # flatten 5ô # split into groups of 5 ®ζ # transpose with -1 as filler , # print ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` ṠMöTC5Wnünḣ60 ``` [Try it online!](https://tio.run/##yygtzv7//@HOBb6Ht4U4m4bnHd6T93DHYjOD//8B "Husk – Try It Online") ## Explanation ``` ḣ60 Range [1..60] ü Uniquify using equality predicate n bitwise AND: [1,2,4,8,16,32] M For each number x in this list, Ṡ W take the indices of elements of [1..60] n that have nonzero bitwise AND with x, C5 cut that list into chunks of length 5 öT and transpose it. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~82~~ ~~80~~ ~~78~~ 74 bytes ``` i=1 exec"print zip(*zip(*[(n for n in range(61)+[-1]if n&i)]*5));i*=2;"*6 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9PWUIErtSI1WamgKDOvRKEqs0BDC0xEa@QppOUXKeQpZOYpFCXmpadqmBlqakfrGsZmpinkqWVqxmqZampaZ2rZGlkraZn9/w8A "Python 2 – Try It Online") -4 bytes, thanks to Jonathan Allan [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 bytes ``` 6Æ60õ f&2pX)ó5 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVE&code=NsY2MPUgZiYycFgp8zU) ``` 6Æ Create a range from 0 to 5 (inclusive) and map each X into 60õ Elements in the range [1..60] f Where &2pX) The number bitwise AND with X is not 0 ó5 Split into 5 arrays, where each array contains every 5th element -Q flag is just for formatting purposes ``` [Answer] # JavaScript (ES6), ~~90~~ 88 bytes ``` _=>[1,2,4,8,16,32].map(n=>(g=i=>i<60?g(++i,i&n?m[y%5]=[...m[y++%5]||[],i]:0):m)(y=m=[])) ``` [Try it online!](https://tio.run/##DcjhCoIwFEDhpynu2G2olYR054OMEcN0XHGbZASC777273xndj@3DR9ev5eY3mOeKL9ImxobvOED6xavjVXBrRBJgycmzc@26j1Iycjn2Aezn@6WjFKqpJQFx2Essu0q0QUBOwUyVog8pLilZVRL8jBBGX8 "JavaScript (Node.js) – Try It Online") ### Commented ``` _ => // anonymous function taking no argument [1, 2, 4, 8, 16, 32] // list of powers of 2, from 2**0 to 2**5 .map(n => // for each entry n in this list: ( g = i => // g = recursive function taking a counter i i < 60 ? // if i is less than 60: g( // recursive call: ++i, // increment i i & n ? // if a bitwise AND between i and n is non-zero: m[y % 5] = // update m[y % 5]: [ ...m[y++ % 5] // prepend all previous values; increment y || [], // or prepend nothing if it was undefined so far i // append i ] // end of update : // else: 0 // do nothing ) // end of recursive call : // else: m // return m[] )(y = m = []) // initial call to g with i = y = m = [] // (i and y being coerced to 0) ) // end of map() ``` [Answer] # [Python 2](https://docs.python.org/2/), 73 bytes Inspiration taken from both [TFeld's](https://codegolf.stackexchange.com/a/184861/53748) and [The Matt's](https://codegolf.stackexchange.com/a/184865/53748). ``` k=32 while k:print zip(*zip(*[(i for i in range(61)+[-1]if i&k)]*5));k/=2 ``` **[Try it online!](https://tio.run/##K6gsycjPM/r/P9vW2IirPCMzJ1Uh26qgKDOvRKEqs0BDC0xEa2QqpOUXKWQqZOYpFCXmpadqmBlqakfrGsZmpilkqmVrxmqZampaZ@vbAo0CAA "Python 2 – Try It Online")** [Answer] # [C (gcc)](https://gcc.gnu.org/), 95 bytes ``` i,j,k;f(int o[][5][6]){for(i=6;i;)for(o[--i][4][5]=j=k=-1;j<60;)++j&1<<i?o[i][++k%5][k/5]=j:0;} ``` [Try it online!](https://tio.run/##bY9NboMwEIX3nMJylMqWISVRYNGx1YO4XlRQkrETXFGyijg7sSFV89O3Gs18M@9Nle2qalxgWx1O9RehP32NfrWnI6Y2ddAwbHvitdGF0aXh58Z3DFUJCDyWXmcZGr2Nc2WVU9karCxz4ELYl7WU@O51AIRwy3DBvUbsLYdhPH5iy/g5IUGTx6kPBrMNTN2GhR6/1r4jUxRUORCUJRAhkJN5/46wkbCyiIS9Je4oFyk333GPVNR3F7CG0eWmJjSd4oU/bPjBXDP9akj@2/to6Q33xzzPh2RIxgs "C (gcc) – Try It Online") Returns the matrices as a 3D int array in o. The last 4 matrices have -1 as their last value. Saved 2 bytes thanks to Kevin Cruijssen. Saved ~~7~~ 8 bytes thanks to Arnauld. [Answer] ## CJam (18 bytes) ``` 6{61{2A#&},5/zp}fA ``` [Online demo](http://cjam.aditsu.net/#code=6%7B61%7B2A%23%26%7D%2C5%2Fzp%7DfA). This is a full program which outputs to stdout. ### Dissection ``` 6{ }fA # for A = 0 to 5 61{2A#&}, # filter [0,61) by whether bit 2^A is set 5/z # break into chunks of 5 and transpose to get 5 lists p # print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 60&ƇⱮs€5LÐṂZ€ ``` A niladic Link which yields a list of (6) lists of lists of integers. (It outputs the using the default option of having no `*` or negative filler.) **[Try it online!](https://tio.run/##y0rNyan8/9/MQO1Y@6ON64ofNa0x9Tk84eHOpigg8/9/AA "Jelly – Try It Online")** ### How? Each matrix contains, in column-major order, the numbers up to \$60\$ which share the single set-bit with the top-left (minimal) number. This program first makes ***all*** \$60\$ possible ordered lists of numbers in \$[1,60]\$ which share ***any*** set-bit(s) with their index number. It then splits each into chunks of \$5\$ and keeps only those with minimal length - which will be the ones where the index has only a single set-bit (and hence also being its minimal value). Finally it transposes each to put them into column-major order. ``` 60&ƇⱮs€5LÐṂZ€ - Link: no arguments 60 - set the left argument to 60 Ɱ - map across ([1..60]) with: (i.e. [f(60,x) for x in [1..60]]) Ƈ - filter keep if: (N.B. 0 is falsey, while non-zeros are truthy) & - bitwise AND € - for each: s 5 - split into chunks of five ÐṂ - keep those with minimal: L - length Z€ - transpose each ``` --- Lots of 15s without realising the "minimal by length when split into fives" trick: ``` 5Ż2*Ɱ60&ƇⱮs€5Z€ 6µ’2*60&Ƈ)s€5Z€ 60&ƇⱮ`LÞḣ6s€5Z€ ``` ...and, while attempting to find shorter, I got another 13 without needing the trick at all: ``` 60B€Uz0Ts5ZƊ€ ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 88 bytes ``` Transpose@Partition[#~Append~-1,5]&/@Last@Reap[Sow[,NumberExpand[,2]]~Do~{,60},Except@0] ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 99 bytes ``` Transpose@Partition[#~FromDigits~2&/@Last@GatherBy[{0,1}~Tuples~6,#[[-k]]&],5]~Table~{k,6}/. 61->-1 ``` [Try it online!](https://tio.run/##FcvBCsIgGADgVxEGO2lmkLdCIurSYQdv4uEvxGSbDv07xJivbvTdvxnw7WbA8ILmT01niGVJxakBMgYMKZqu3nKar8EHLPXQc/WAgur@j/nyNeueiq3qzzK5UiXtjGGjtb2lR1s1PCdX15HKje@IFOzMRBtyiEi4Ir61Hw "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` 60B€Uz0µTs5Z) ``` [Try it online!](https://tio.run/##y0rNyan8/9/MwOlR05rQKoNDW0OKTaM0//8HAA "Jelly – Try It Online") Loosely based on [flawr’s MATL answer](https://codegolf.stackexchange.com/a/184878/42248). A niladic link which outputs a list of lists as required. [Answer] # [R](https://www.r-project.org/), 73 bytes ``` `!`=as.raw;lapply(0:5,function(i)matrix(c((a=1:60)[(!a&!2^i)>0],-1),5,6)) ``` I am not entirely sure if I have met the requirement for order, since R by default fills matrices by column, so the order such that it appears physically on the cards is the same as the way matrices are allocated in R. [Try it online!](https://tio.run/##K/r/P0ExwTaxWK8osdw6J7GgIKdSw8DKVCetNC@5JDM/TyNTMzexpCizQiNZQyPR1tDKzEAzWkMxUU3RKC5T084gVkfXUFPHVMdMU/P/fwA "R – Try It Online") [Answer] # T-SQL, (1,168 1,139 bytes) I just wanted to know I could do it. **Optimised version** ``` WITH g AS(SELECT 1 AS n UNION ALL SELECT n+1 FROM g WHERE n+1<61),B as(SELECT cast(cast(n&32 as bit)as CHAR(1))+cast(cast(n&16 as bit)as CHAR(1))+cast(cast(n&8 as bit)as CHAR(1))+cast(cast(n&4 as bit)as CHAR(1))+cast(cast(n&2 as bit)as CHAR(1))+cast(cast(n&1 as bit)as CHAR(1))as b FROM g),P as(SELECT * from (values(1), (2), (4), (8), (16), (32)) as Q(p)),S as(select distinct p,p+(substring(b,6,1)*1)*(case when p=1 then 0 else 1 end)+(substring(b,5,1)*2)*(case when p=2 then 0 else 1 end)+(substring(b,4,1)*4)*(case when p=4 then 0 else 1 end)+(substring(b,3,1)*8)*(case when p=8 then 0 else 1 end)+(substring(b,2,1)*16)*(case when p=16 then 0 else 1 end)+(substring(b,1,1)*32)*(case when p=32 then 0 else 1 end)as e from P cross apply B),D as(select * from S where e>=p and e<61),R as(select p,(row_number()over(partition by p order by cast(e as int)))%5 as r,e from D),H as(select k.p,'['+stuff((select','+cast(l.e as varchar)from R l where l.p=k.p and l.r=k.r for xml path('')),1,1,'')+']'as s from R k group by k.p,k.r)select stuff((select','+cast(x.s as varchar)from H x where x.p=z.p for xml path('')),1,1,'')from H z group by z.p ``` **Online demo** [Try it online!](http://www.sqlfiddle.com/#!18/d1905/1) **Verbose version - with notes as SQL comments** ``` WITH gen -- numbers 1 to 60 AS ( SELECT 1 AS num UNION ALL SELECT num+1 FROM gen WHERE num+1<=60 ), BINARIES -- string representations of binaries 000001 through 111111 as ( SELECT +cast( cast(num & 32 as bit) as CHAR(1)) +cast( cast(num & 16 as bit) as CHAR(1)) +cast( cast(num & 8 as bit) as CHAR(1)) +cast( cast(num & 4 as bit) as CHAR(1)) +cast( cast(num & 2 as bit) as CHAR(1)) +cast(cast(num & 1 as bit) as CHAR(1)) as binry FROM gen ), POWERS -- first 6 powers of 2 as ( SELECT * from (values(1), (2), (4), (8), (16), (32)) as Q(powr) ), SETELEMENTS -- cross apply the six powers of 2 against the binaries -- returns 2 cols. col 1 = the power of 2 in question. -- col 2 is calculated as that power of 2 plus the sum of each power of 2 other than the current row's power value, -- but only where a given power of 2 is switched "on" in the binary string, -- ie. where the first digit in the string represents 32, the second represents 16 and so on. -- That is, if the binary is 100100 then the number will be -- the sum of (32 x 1) + (16 x 0) + (8 x 0) + (4 x 1) + (2 x 0) + (1 x 0) -- but if the current row's power is 32 or 4, then just that number (32 or 4) is excluded from the sum. -- rows are distinct. as ( select distinct powr, powr+ (substring(binry,6,1) * 1) * (case when powr = 1 then 0 else 1 end) +(substring(binry,5,1) * 2) * (case when powr = 2 then 0 else 1 end) +(substring(binry,4,1) * 4) * (case when powr = 4 then 0 else 1 end) +(substring(binry,3,1) * 8) * (case when powr = 8 then 0 else 1 end) +(substring(binry,2,1) * 16) * (case when powr = 16 then 0 else 1 end) +(substring(binry,1,1) * 32) * (case when powr = 32 then 0 else 1 end) as elt from POWERS cross apply BINARIES ), DISTINCTELEMENTS -- purge calculated numbers smaller than the power of 2 or greater than 60 as ( select * from SETELEMENTS where elt >= powr and elt < 61 )--, , ROWNUMBERED -- for each power, number the rows repeatedly from 0 through 5, then back to 0 through 5 again, etc as ( select powr, (row_number() over (partition by powr order by cast(elt as int)))%5 as r, elt from DISTINCTELEMENTS ), GROUPEDSETS -- for each row number, within each power, aggregate the numbers as a comma-delimited list and wrap in square brackets - the inner arrays as ( select r1.powr, '['+stuff((select ',' + cast(r2.elt as varchar) from ROWNUMBERED r2 where r2.powr = r1.powr and r2.r = r1.r for xml path('')),1,1,'')+']' as s from ROWNUMBERED r1 group by r1.powr,r1.r ) select -- now aggregate all the inner arrays per power stuff((select ',' + cast(g2.s as varchar) from GROUPEDSETS g2 where g2.powr = g1.powr for xml path('')),1,1,'') from GROUPEDSETS g1 group by g1.powr ``` **Voila!** Note 1: Some of the logic pertains to rendering square brackets and commas. Note 2: Newer versions of SQLServer have more compact approaches to creating comma-delimited lists. (This was created on SQL Server 2016.) Note 3: Arrays for a given card are not sorted (which is ok per the spec). Numbers within an array are correctly sorted. In this case, each "card" of the question, renders its arrays on a separate row in the results. **Shorter to hard-code arrays?** Yes. Byte me. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 112 bytes ``` _=>" ".Select(x=>Enumerable.Range(1,60).Where(l=>(l&x)>0).Select((a,b)=>new{a,b}).GroupBy(i=>i.b%5,i=>i.a)) ``` [Try it online!](https://tio.run/##dY5NS8QwEIZRPNie/AkhqGQgBhX0spscBBXFkx72uKRhuhuJU0lbbbf0t9coonvZOT0z7wfj6jNX@@muJTevild0jXy4pfYNoy0Cznexp8akKfW01Ibv7R8cHjGuXjCkAtFp829Vz5ZWKC7k9TmoxRojiqCNCKcdmHT5jQgrC9CG8HNINIK6j1X7ftMLr41XxcmV/AELMM3ysopo3Vp82Mg2zBMrBbUhALAhz7bF/lvcQJ5li@gbfPKEom6ip5V6rDwJLhmX/d/bTBt2zIdOXo4cAGb5Vixt4/QF "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Red](http://www.red-lang.org), ~~108~~ 107 bytes ``` n: 32 until[b: collect[repeat k 60[if n and k = n[keep k]]]loop 5[print extract b 5 b: next b]1 > n: n / 2] ``` [Try it online!](https://tio.run/##Dc07CsMwEEXRPqt4O4hjYxeGZBFphyn0mYCQGAkxAe9eVnmae7vE8ZVIPPTEtuKvlgr5E6GWIsGoSxNnyDgWSj8onMapN5SySENm5lJrw06tJ7WHXNZdMHjsmB2dhucXPpgHxRMrj3ED "Red – Try It Online") [Answer] # APL+WIN, ~~65~~ 62 bytes ``` v←∊+\¨n,¨29⍴¨1↓¨(n⍴¨1),¨1+n←2*0,⍳5⋄((v=61)/v)←¯1⋄1 3 2⍉6 6 5⍴v ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/6XAZmPOrq0Yw6tyNM5tMLI8lHvlkMrDB@1TT60QiMPwtEEShhq5wFVGmkZ6Dzq3Wz6qLtFQ6PM1sxQU79MEyh@aL0hUMhQwVjB6FFvp5mCmYIpUGvZf6AV/9MA "APL (Dyalog Classic) – Try It Online") [Answer] **MATLAB, 155 bytes** ``` cellfun(@disp,cellfun(@(x)x-repmat(62,5,6).*(x>60),cellfun(@(x)reshape(find(x,30),[5 6]),mat2cell(dec2bin(1:62)-48,62,ones(1,6)),'Uniform',0),'Uniform',0)) ``` This could be shorter as multiple lines but I wanted to do it in one line of code. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` žOε60LDNo&ĀÏ5ι ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6D7/c1vNDHxc/PLVjjQc7jc9t/P/fwA "05AB1E – Try It Online") ]
[Question] [ Inspired by [this post](https://codegolf.stackexchange.com/questions/125117/diagonal-alphabet). For those marking this question as a duplicate I urge you to actually read the question to see that mine is a modification of the one linked. The one linked does not ask for an input and is to just print the alphabet diagonally. **The Challenge** Given an input between 1-26 inclusively, print the alphabet diagonally, but begin printing vertically at the index of the given input. **Examples** Given the input: ``` 16 ``` Your program should output: ``` 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 ``` Input: ``` 4 ``` Output: ``` a b c d e f g h i j k l m n o p q r s t v w x y z ``` Input: ``` 1 ``` Output: ``` 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 ``` Input: ``` 26 ``` Output: ``` 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 ``` **Scoring** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins. Good luck! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes ``` ↘✂β⁰N↓✂βη ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9R24xHc5rObXrUuOH9nnWP2iaDeee2//9vAgA "Charcoal – Try It Online") ### How it works ``` ↘✂β⁰N↓✂βη ✂β⁰N the alphabet from position 0 to the input ↘ print diagonally, down and to the right ✂βη the alphabet starting from the position of the input ↓ print downwards ``` This solution no longer works in the current version of Charcoal (most likely due to a bug fix), but the issue is resolved for 10 bytes with [`↘✂β⁰N↓✂βIθ`](https://tio.run/##S85ILErOT8z5//9R24xHc5rObXrUuOH9nnWP2iaDee/3rDy34/9/EwA). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` AvNI<‚Wysú, ``` First time trying 05AB1E, so I'm open to tips. [Try it online!](https://tio.run/##MzBNTDJM/f/fsczP0@ZRw6zwyuLDu3T@/zc0AwA) If a zero-indexed input from `0` to `25` is allowed, this can be 10 bytes by omitting the `<`. [Answer] ## JavaScript (ES2017), ~~73~~ ~~72~~ ~~71~~ 66 bytes *Saved some bytes thanks to @JustinMariner* ``` f=(n,x=26)=>x?f(n,x-1)+(x+9).toString(36).padStart(x<n?x:n)+` `:'' ``` [Answer] # Ruby, ~~51~~ ~~46~~ 43 bytes ``` ->n{(0..25).map{|x|(' '*x)[0,n-1]<<(x+97)}} ``` Returns a list of strings. Looks like the Python guys were on to something with their subscripts. -5 bytes by taking inspiration from Mr. Xcoder's improvement of ppperry's solution. Previous solution with `rjust` (51 bytes): ``` ->n{i=0;(?a..?z).map{|c|c.rjust i+=n>c.ord-97?1:0}} ``` [Answer] # Python 2, ~~61 58 57~~ 56 bytes ``` def f(i,j=0):exec"print(' '*~-i)[:j]+chr(97+j);j+=1;"*26 ``` -3 bytes thanks to Rod -2 more bytes thanks to Mr. Xcoder [Answer] # [Python 2](https://docs.python.org/2/), ~~62~~ ~~50~~ 57 bytes ``` x=input();n=m=1 exec"print'%*c'%(m,n+96);n+=1;m+=x>m;"*26 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8I2M6@gtERD0zrPNtfWkCu1IjVZqaAoM69EXVUrWV1VI1cnT9vSDCitbWtonattW2GXa62kZWT2/78pAA "Python 2 – Try It Online") Steals heavily from [this answer](https://codegolf.stackexchange.com/a/125144/65836) by Dennis. [Answer] # R, ~~99~~ 89 bytes *@MickeyT saved 10 bytes* ### function ``` function(x)for(i in 1:26)cat(paste(c(rep(" ",min(x,i)),letters[i]),collapse=""),sep="\n") ``` ### demo ``` f <- function(x)for(i in 1:26)cat(paste(c(rep(" ",min(x,i)),letters[i]),collapse=""),sep="\n") f(1) f(10) f(15) f(26) ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~72~~ 68 bytes ``` ^ z {2=` $` }T`l`_l`^. \D $.`$* $&¶ \d+ $* s`( *)( +)(?=.*¶\1 $) $1 ``` [Try it online!](https://tio.run/##K0otycxL/P8/jquKq9rINoFLJYGrNiQhJyE@JyFOjyvGhUtFL0FFS0FF7dA2rpgUbS4gm6s4QUNBS1NDQVtTw95WT@vQthhDBRVNLhXD//9NAA "Retina – Try It Online") Output includes trailing whitespace. Save 1 byte by deleting the space before the `$` if zero-indexing is allowed. Edit: Saved 4 bytes by using @MartinEnder's alphabet generator. Explanation: ``` ^ z {2=` $` }T`l`_l`^. ``` Insert the alphabet. ``` \D $.`$* $&¶ ``` Diagonalise it. ``` \d+ $* ``` Convert the input to unary as spaces. ``` s`( *)( +)(?=.*¶\1 $) $1 ``` Trim overlong lines so that no line is longer than the blank line at the end. [Answer] # Mathematica, 103 bytes ``` (T=Table;a=Alphabet[];c=Column)[c/@{T[""<>{T[" ",i],a[[i]]},{i,#}],T[""<>{T[" ",#],a[[i]]},{i,#,26}]}]& ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` 26Ḷ«’⁶ẋżØaY ``` [Try it online!](https://tio.run/##ASEA3v9qZWxsef//MjbhuLbCq@KAmeKBtuG6i8W8w5hhWf///zQ "Jelly – Try It Online") [Answer] # Common Lisp, 84 bytes ``` (lambda(x)(dotimes(i 26)(format t"~v,,,@a~%"(if(< i x)(1+ i)x)(code-char(+ i 97))))) ``` [Try it online!](https://tio.run/##FYoxCoAwEAS/cgjCHsZCC0Ww8CtnonhgiGgQK78e4zQDw9hdryMhYRc/O8HDcCGqXy4otR1jDaeXSLF4b2PMJG9ZQFeMpJTfpiLlbBvcUttNTuRAQ88/qek4fQ) [Answer] # [Python](https://docs.python.org/), 52 bytes Quite surprised nobody noticed the obvious approach was also as short as the others. ``` lambda k:[(i*" ")[:k-1]+chr(i+97)for i in range(26)] ``` [Try it online!](https://tio.run/##FcdLDkAwEADQq0xsTAkJEqKJk2BRnzI@06aphdNXvN2zr98NV0F3Q7jUPS0KTtkjJRFEopdnVozpvDuktG2ENg4IiMEp3lYsazEG64g9xgPH@WGIUeN/Yvt4FL9Q1B8 "Python 3 – Try It Online") # [Python](https://docs.python.org/), 53 bytes ``` lambda k:[min(k-1,i)*" "+chr(i+97)for i in range(26)] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHbKjo3M08jW9dQJ1NTS0lBSTs5o0gjU9vSXDMtv0ghUyEzT6EoMS89VcPITDP2f0FRZl6JhnpMnrpeVj5QX5oGiJ@ZV1BaoqEJAv8NzQA "Python 3 – Try It Online") [Answer] ## Haskell, ~~58~~ 54 bytes ``` f n=do m<-[1..26];([2..min n m]>>" ")++['`'..]!!m:"\n" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzYlXyHXRjfaUE/PyCzWWiPaSE8vNzNPIU8hN9bOTklBSVNbO1o9QV1PL1ZRMddKKSZP6X9uIlCBrUJBaUlwSZGCikKagsl/AA "Haskell – Try It Online") How it works ``` f n= -- input number is n do m<-[1..26] -- for each m from [1..26], construct a string and concatenate -- them into a single string. The string is: [2..min n m]>>" " -- min(n,m)-1 spaces, ++ -- followed by ['`'..]!!m -- the m-th char after ` : -- followed by "\n" -- a newline ``` Edit: @Lynn saved 4 bytes. Thanks! [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 69 bytes ``` n->{for(int a=0;a++<26;)System.out.printf("%"+(a<n?a:n)+"c%n",a+96);} ``` [Try it online!](https://tio.run/##LY3BisIwFEX3fsWjICTEhsEBQVt14cqFK5fDLJ4xKantS0lehEH67Z2OzOrCuZdzW3xiGQZL7f0xDfnWeQOmw5Tggp7gtQD4p4mR53gGf4d@7sSVo6fm6xswNkm@pwDt7NOZfaddJsM@kD4FSrm3sT4T28bGAzjYT1QeXi5E4YkB9x8VKlWvN5W8/iS2vQ6Z9TD72YliWSiBNR1xR1IVZknFCtV2I6txqt6nTqMxdmDxKf/AuBinXw "Java (OpenJDK 8) – Try It Online") [Answer] # [Gaia](https://github.com/splcurran/Gaia), 12 bytes ``` …26⊃§×¦₵a+†ṣ ``` [Try it online!](https://tio.run/##ASMA3P9nYWlh///igKYyNuKKg8Knw5fCpuKCtWEr4oCg4bmj//8xNQ "Gaia – Try It Online") ### Explanation ``` … Range 0..input-1 26⊃ Repeat the last number enough times to make it have length 26 §×¦ Turn each number into a string of that many spaces ₵a+† Add the corresponding letter to each ṣ Join with newlines ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~12~~ 11 bytes -1 as OP has now clarified that returning a list of strings is fine. Prompts for input. ``` ⎕A↑¨⍨-⎕⌊⍳26 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdJTMxPT8vMSck//@jtomP@qY6AqlDKx71rtAFch71dD3q3WxkBlL5XwEMEBq4DM24MMRMMIUMMYWMzAA "APL (Dyalog Unicode) – Try It Online") `⍳26` first 26 strictly positive **ɩ**ntegers `⎕⌊` minimum of input and those `-` negate those `⎕A↑⍨¨` for each letter of the **A**lphabet, take that many characters (from the rear, as all numbers are negative), padding with spaces as necessary --- `↑` convert list of strings into matrix (only in TIO link to enable readable output) [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~21~~ ~~17~~ 15 bytes ``` VlG+*d?>QNNQ@GN ``` Explanation: ``` VlG For each character in the alphabet (G) + Concatenate... *d Space (d) times... ?>QNNQ Ternary; if Q (input) is less than N, return N, else Q @GN The Nth character of the alphabet (G) ``` [Try it online!](https://tio.run/##K6gsyfj/PyzHXVsrxd4u0M8v0MHd7/9/QwMA "Pyth – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 72 bytes ``` n=>[..."abcdefghijklmnopqrstuvwxyz"].map((e,i)=>" ".repeat(i<n?i:n-1)+e) ``` Returns a list of strings. [Try it online!](https://tio.run/##ZctNDoIwEEDhfU8x6aqN0IRoXKjFg6AJFQYswrQC4k@4ezVxZdx@L68xkxmK3voxJldiqHQgnWZKKW5ORYlVfbbNpe3I@Ws/jLfp/ni@@FF1xguBkZU65cBVjx7NKOyO9nZDcSIXKMOWsSyJYBnBKoJk/Z0QdMoAoHA0uBZV62qBEub5R6qPqcZZyg@U/1XJ5Da8AQ "JavaScript (Node.js) – Try It Online") [Answer] # Mathematica, 67 bytes ``` SparseArray[x=#;{#,#~Min~x}->Alphabet[][[#]]&~Array~26,{26,#}," "]& ``` Returns a `SparseArray` of strings. To visualize, append `Grid@` in front. [Try it on Wolfram Sandbox](https://sandbox.open.wolframcloud.com) ### Usage ``` Grid@SparseArray[x=#;{#,#~Min~x}->Alphabet[][[#]]&~Array~26,{26,#}," "]&[5] ``` > > > ``` > a > b > c > d > e > f > g > > ⋮ > > z > > ``` > > [Answer] # [Python 2](https://docs.python.org/2/), 52 bytes ``` lambda n:['%*c'%(min(i+1,n),i+97)for i in range(26)] ``` [Try it online!](https://tio.run/##TYxBDoIwFAX3PcXbkLZQTdoYiCScBFhUpfqN/BLoxtNX4sI425nM8k6PyC6HbsgvP19uHtz2siivslAzsaLKGtaGqnOjQ1xBIMbq@T4pV@sxp2lLGzr0tjY4GVgDV49C/Npv0ArsLCtxghxYHp9xfwdFWv@bg0QJ1@QP "Python 2 – Try It Online") I'm assuming a list of strings is fine... Shortest I could get with recursion: ``` f=lambda n,i=0:i<26and['%*c'%(min(i+1,n),i+97)]+f(n,i+1)or[] ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 12 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` z{ē.-.Hχ@*Ot ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=eiU3QiV1MDExMy4tLkgldTAzQzdAKk90,inputs=NA__) [Answer] # [Python 3](https://docs.python.org/3/), 52 bytes ``` lambda n:[('%*c'%(i,i+96))[-n:]for i in range(1,27)] ``` [Try it online!](https://tio.run/##TYxBDsIgEADvvGIvDVCpCdVgJOlLKAfUotvo0lAuvh4bD8a5zmSWd3kkOtQ4jPUZXpdbALJO8Ka98kagwt3ZSOk6sj6mDAhIkAPdJ6FVf5K@lmktKwzgtFFwVKAV9MYz9qu/gWWwsWSkIvhIfD8nJBEFSin/Vcehhe1bPw "Python 3 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 50 bytes ``` i;f(n){for(;i<26;printf("%*c\n",i++<n?i:n,i+97));} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/TOk0jT7M6Lb9IwzrTxsjMuqAoM68kTUNJVSs5Jk9JJ1Nb2ybPPtMqD8iyNNfUtK79n5uYmaehqVDNpQAEaRqGZprWXLX/AQ) [Answer] # [Proton](https://github.com/alexander-liao/proton), 40 bytes Assuming that a list of Strings is fine. ``` k=>[(i*" ")[to~-k]+chr(i+97)for i:0..26] ``` [Try it online!](https://tio.run/##KyjKL8nP@59m@z/b1i5aI1NLSUFJM7okv043O1Y7OaNII1Pb0lwzLb9IIdPKQE/PyCz2f0FRZl6JhnpMnrpeVn5mnkaahqGZpqbmfwA "Proton – Try It Online") # [Proton](https://github.com/alexander-liao/proton), 49 bytes As ASCII-art instead: ``` k=>'\n'.join((i*" ")[to~-k]+chr(i+97)for i:0..26) ``` [Try it online!](https://tio.run/##KyjKL8nP@59m@z/b1k49Jk9dLys/M09DI1NLSUFJM7okv043O1Y7OaNII1Pb0lwzLb9IIdPKQE/PyEzzf0FRZl6JRpqGoZmm5n8A "Proton – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 66 + 18 bytes ``` n=>new int[26].Select((x,i)=>$"{(char)(i+97)}".PadLeft(i<n?i+1:n)) ``` Byte count also includes ``` using System.Linq; ``` [Try it online!](https://tio.run/##bZBBSwMxEIXv@RVj8ZDQutAiFd3uipRWxApiBQ/iIaZTO5BmNcnalmV/@5ptpXSt75LJzJd5jyh3pjKLVe7IfMB04zwuo2GmNSpPmXHRLRq0pGLWICZkvmLGjFyi@5QKf/usYBCktHQObrb1rlPLeelJwXdGM3iQZLjYjwq2L2uNc6MGZHwH7kYmX6KV7xoHztuQIE1hDkllktTgCgL02uu/RVOsA3O@7pBI0tNWwdVCWsGpfXkhylb0KGcTnHtOA3NN7e6VEaI6dIybAXZW9RE3@qsFaQTOwwASGIb/yTRGTxi2k0EuBJwkYHKtReNZ0bjVmvOQPKSyDutlQkTP2YSc5yIaZ3Yk1YKvIUn3Fi@WPG491kLER@uOsT9Qyf7D6@D3uDmEd2DJyqrbZ@esy3r9Hw "C# (.NET Core) – Try It Online") This returns a collection of strings, one for each line. If it's not allowed, the answer will swell by 17 bytes for `string.Concat()` and `\n` inside string Explanation: ``` n => new int[26] // Create a new collection of size 26 .Select((x, i) => // Replace its members with: $"{(char)(i + 97)}" // String of an alphabet character corresponding to the index .PadLeft(i < n ? i + 1 : n) // Add spaces to the left ) ``` [Answer] # [Pyth](https://pyth.readthedocs.io), 12 bytes ``` j.e+<*kdtQbG ``` **[Try it here!](https://pyth.herokuapp.com/?code=j.e%2B%3C%2akdtQbG&input=16&debug=0)** If lists of Strings are allowed, this can be shortened to [**11 bytes**](https://pyth.herokuapp.com/?code=.e%2B%3C%2akdtQbG&input=16&debug=0): ``` .e+<*kdtQbG ``` # [Pyth](https://pyth.readthedocs.io), 12 bytes ``` VG+<*dxGNtQN ``` **[Try it here!](https://pyth.herokuapp.com/?code=VG%2B%3C%2adxGNtQN&input=16&debug=0)** # [Pyth](https://pyth.readthedocs.io), 14 bytes ``` jm+<*d;tQ@Gd26 ``` **[Try it here.](https://pyth.herokuapp.com/?code=jm%2B%3C%2ad%3BtQ%40Gd26&input=16&debug=0)** If lists of Strings are allowed, this can be shortened to [**13 bytes**](https://pyth.herokuapp.com/?code=m%2B%3C%2ad%3BtQ%40Gd26&input=16&debug=0): ``` m+<*d;tQ@Gd26 ``` --- # How do these work? Unlike most of the other answers, this maps / loops over the lowercase alphabet in all 3 solutions. ### Explanation #1 ``` j.e+<*kdtQbG - Full program. .e G - Enumerated map over "abcdefghijklmnopqrstuvwxyz", with indexes k and values b. *kd - Repeat a space a number of times equal to the letter's index. < tQ - Crop the spaces after the input. + b - Concatenate with the letter. j - (Optional): Join by newlines. ``` ### Explanation #2 ``` VG+<*dxGNtQN - Full program. VG - For N in "abcdefghijklmnopqrstuvwxyz". xGN - Index of the letter in the alphabet. *d - Repeat the space a number of times equal to the index above. < tQ - But crop anything higher than the input. + N - Append the letter (at the end) ``` ### Explanation #3 ``` jm+<*d;tQ@Gd26 - Full program. m 26 - Map over [0...26) with a variable d. *d; - Space repeated d times. < tQ - Crop anything whose length is higher than the input. + @Gd - Concatenate with the letter at that index in the alphabet. j - (Optional): Join by newlines. ``` [Answer] # Haskell, 60 bytes ``` f n=unlines$scanl(\p c->take(n-1)(p>>" ")++[c])"a"['b'..'z'] ``` This is a function that returns the output as a String. [Try it online.](https://tio.run/##y0gszk7Nyfn/P00hz7Y0LyczL7VYpTg5MS9HI6ZAIVnXriQxO1UjT9dQU6PAzk5JQUlTWzs6OVZTKVEpWj1JXU9PvUo99n9uYmaegq1CSj6XgkJBaUlwSZFPnoKKQpqCyX8A) [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~16~~ 13 bytes *Saved 3 bytes thanks to @Oliver* ``` ;C£RiXiYmUÉ î ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=O0OjUmlYaVltVckg7g==&input=Mw==) [Answer] # q/kdb+, ~~33~~ 31 bytes **Solution:** ``` -1{(&[x-1;til 26]#'" "),'.Q.a}; ``` **Example:** ``` q)-1{(&[x-1;til 26]#'" "),'.Q.a}16; 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 ``` **Explanation:** Create a list of spaces (26) up to the length of the minimum of the input and the range of `0..25`), join with each letter of the alphabet, print to stdout. ``` -1{(&[x-1;til 26]#'" "),'.Q.a}; / solution -1 ; / print result to stdout and swallow return { } / lambda function .Q.a / "abcd..xyz" ,' / concatenate (,) each ( ) / do all this together &[ ; ] / minimum of each x-1 / implicit input (e.g. 10) minus 1 (e.g. 9) til 26 / 0 1 2 ... 23 24 25 '#" " / take " " each number of times (0 1 2 ) ``` **Notes:** * -2 bytes by rejigging the brackets [Answer] # Java 1.8 (without Lambda), 98 Bytes ``` void m(int i){int c=0,o=97;String s="";for(;c++<26;s+=c<i?" ":"")System.out.println(s+(char)o++);} ``` The logic is straightforward. Provides no input data validation, very bad! * Update: Function only! Thank you to @Olivier Grégoire ]
[Question] [ Special [Independence Day (USA)](https://en.wikipedia.org/wiki/Independence_Day_(United_States)) themed challenge for you today. You must write a program that prints this ascii-art representation of The American Flag. ``` 0 |--------------------------------------------------------- | * * * * * * #################################| | * * * * * | | * * * * * * | | * * * * * #################################| | * * * * * * | | * * * * * | | * * * * * * #################################| | * * * * * | | * * * * * * | |########################################################| | | | | |########################################################| | | | | |########################################################| | | | | |########################################################| |--------------------------------------------------------- | | | | | | | | | | | | | | | | ``` Trailing spaces on each line, as well as one trailing newline, are allowed. Note that this isn't quite the way the flag should look, but it's the closest I could get with ASCII. As usual, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so standard loopholes apply and shortest answer in bytes wins! [Answer] # Python 2, 113 bytes ``` for i in range(38):print i and"|"+["-"*57,(" * "*7)[i%2*2:][:(i<11)*23].ljust(56," #"[i%3])+"|"][1<i<21]*(i<22) ``` String slicing and modulo checks galore. [Answer] # CJam, ~~184~~ ~~120~~ ~~109~~ ~~101~~ ~~76~~ ~~74~~ ~~69~~ ~~67~~ ~~64~~ ~~62~~ 58 bytes ``` 0'-57*" #"56f*'|f+7*2>" * "50*22/W<Sf+..e&~J$]N'|+a37*.+ ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=0'-57*%22%20%20%23%2256f*'%7Cf%2B7*2%3E%22%20*%20%20%2250*22%2FW%3CSf%2B..e%26~J%24%5DN'%7C%2Ba37*.%2B). ### Idea The most interesting part of the flag is the stars and stripes pattern. If we repeat two spaces and a number sign 56 times and append a vertical bar to each, we get ``` | | #########################################################| ``` Repeating this pattern 7 times and discarding the first two lines, we obtain the stripes: ``` #########################################################| | | #########################################################| | | #########################################################| | | #########################################################| | | #########################################################| | | #########################################################| | | #########################################################| ``` Now, if we repeat the string `" * "` 50 times and split the result into chunks of length 22, we obtain the stars: ``` * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *   ``` The whitespace is a little off, but we can fix that by eliminating the last chunk and appending a space to the remaining ones. Now, if we superimpose stripes and stars, we get ``` * * * * * * #################################| * * * * * | * * * * * * | * * * * * #################################| * * * * * * | * * * * * | * * * * * * #################################| * * * * * | * * * * * * | ########################################################| | | ########################################################| | | ########################################################| | | ########################################################| ``` All that's left to do is adding two lines of 57 dashes, adding a column of 37 vertical bars and putting the cherry on top. ### Code ``` 0 e# Push a zero. '-57* e# Push a string of 57 dashes. " #"56f* e# Repeat each character in the string 56 times. '|f+ e# Append a vertical bar to each resulting string. 7* e# Repeat the resulting array of strings 7 times. 2> e# Discard the first two strings. " * "50* e# Repeat the string 50 times. 22/ e# Split the result into chunks of length 22. W< e# Discard the last, partial chunk. Sf* e# Append a space to each chunk. ..e& e# Twofold vectorized logical AND. e# Since all characters in the strings are truthy, this always selects e# the second character, painting the stars over the stripes. ~ e# Dump all resulting strings on the stack. J$ e# Copy the string of dashes. ] e# Wrap the entire stack in an array. N'|+a37* e# Repeat ["\n|"] 37 times. .+ e# Perform vectorized concatenation. ``` [Answer] # Brainf\*\*k, 3355 3113 1598 1178 782 bytes [What is this language?](https://en.wikipedia.org/wiki/Brainfuck) Here is the hand optimized version featuring 28 loops. I think I've taken this about as far as it will go. Here's the run at [ideone.com](http://ideone.com/1koQFX): ``` +++[>++++<-]>[>+++>+++>+++>++++++++++>+>++++<<<<<<-]>++++++>---->->>>.<--. <++++.>>---.>+++++++[<........>-]<<. <.<<<<+++++[>>.<.>..<<-]>>.<.>.<<++++[>>>........<<<-]>>>.>.>. <.<<<<+++++[>>...<.<-]+++++[>>.......<<-]>>.>>.>. <.<<<<++++++[>>.<.>..<<-]++++[>>........<<-]>>>>.>. <.<<...<<+++++[>.>...<<-]++++[>>>........<<<-]>>>.>.>. <.<<<<++++++[>>.<.>..<<-]++++[>>........<<-]>>>>.>. <.<<<<+++++[>>...<.<-]+++++[>>.......<<-]>>.>>.>. <.<<<<+++++[>>.<.>..<<-]>>.<.>.<<++++[>>>........<<<-]>>>.>.>. <.<<<<+++++[>>...<.<-]+++++[>>.......<<-]>>.>>.>. <.<<<<++++++[>>.<.>..<<-]++++[>>........<<-]>>>>.>. >>>+++[<<< <.>>>+++++++[<<<<........>>>>-]<<<.>. >>++[<< <.<<<<+++++++[>>........<<-]>>>>.>. >>-]<< >>>-]<<< <.>>>+++++++[<<<<........>>>>-]<<<.>. <.>>.>+++++++[<........>-]<<. >>++++++++[<<<.>.<.>.>>-] ``` --- ## How does this work? ``` 1: +++[>++++<-]>[>+++>+++>+++>++++++++++>+>++++<<<<<<-]>++++++>---->->>>.<--. 2: <++++.>>---.>+++++++[<........>-]<<. 3: <.<<<<+++++[>>.<.>..<<-]>>.<.>.<<++++[>>>........<<<-]>>>.>.>. 4: <.<<<<+++++[>>...<.<-]+++++[>>.......<<-]>>.>>.>. 5: <.<<<<++++++[>>.<.>..<<-]++++[>>........<<-]>>>>.>. 6: <.<<...<<+++++[>.>...<<-]++++[>>>........<<<-]>>>.>.>. 7: <.<<<<++++++[>>.<.>..<<-]++++[>>........<<-]>>>>.>. 8: <.<<<<+++++[>>...<.<-]+++++[>>.......<<-]>>.>>.>. 9: <.<<<<+++++[>>.<.>..<<-]>>.<.>.<<++++[>>>........<<<-]>>>.>.>. 10: <.<<<<+++++[>>...<.<-]+++++[>>.......<<-]>>.>>.>. 11: <.<<<<++++++[>>.<.>..<<-]++++[>>........<<-]>>>>.>. 12: >>>+++[<<< 13: <.>>>+++++++[<<<<........>>>>-]<<<.>. 14: >>++[<< 15: <.<<<<+++++++[>>........<<-]>>>>.>. 16: >>-]<< 17: >>>-]<<< 18: <.>>>+++++++[<<<<........>>>>-]<<<.>. 19: <.>>.>+++++++[<........>-]<<. 20: >>++++++++[<<<.>.<.>.>>-] ``` This program uses 10 memory locations: ``` 0: loop counter #1 1: loop counter #2 2: "*" ASCII 42 3: spc ASCII 32 4: "#" ASCII 35 5: "|" ASCII 124 6: "\n" ASCII 10 7: "0" ASCII 48, "-" ASCII 45 8: loop counter #3 9: loop counter #4 ``` ### Line 1 * This line sets up the ASCII characters in registers 2 through 7 (mostly). Some tweaking is done later. * This code first puts 3 in register 0, and then loops 3 times incrementing register 1 four times each loop: `+++[>++++<-]`. Then end result is that register 0 is 0, and register 1 is 12. * The 12 is used as the loop counter for the next loop. For 12 times through the loop, registers 2, 3, and 4 are incremented 3 times, register 5 is incremented 10 times, register 6 is incremented 1 time, and register 7 is incremented 4 times. At the end of this loop, they contain: R2(36), R3(36), R4(36), R5(120), R6(12), R7(48). After the loop register 2 is incremented 6 times, register 3 is decremented 4 times, and register 4 is decremented once. At this point, the values are: R2(42), R3(32), R4(35), R5(120), R6(12), R7(48). All but registers 5 and 6 contain their initial ASCII values. * Next register 7 is output, the `"0"` at the top of the flag! * Next register 6 is decremented twice to 10 (ASCII newline) and output. Done with the first line of the flag! ### Line 2 * First it increments register 5 by 4 which makes it `"|"` (ASCII 124) and outputs it. * Then it decrements register 7 by three changing it from `"0"` (ASCII 48) into `"-"` (ASCII 45) and outputs it. * Next it puts 7 into loop counter 3 (register 8) and loops 7 times, writing out 8 dashes each time for a total of 7\*8 = 56 dashes. * Finally it ends by outputting a newline. ### Line 3 * This line contains two loops. * The first loop writes `" * "` 5 times. * Then `" * "` is written * The second loop loops 4 times writing 8 `"#"` for a total of 32. * Then `"#"`, `"|"`, and `"\n"` are written. ### Lines 4 - 11 * These lines use the same technique as line 3 to write out the stars and stripes of the flag. ### Line 12 * This line starts a loop that runs 3 times. * The loop ends at line 17. ### Line 13 * Writes a strip that goes across the flag. * Uses a loop that runs 7 times writing `"#"` 8 times each time through the loop. ### Line 14 * The start of a loop that runs 2 times. ### Line 15 * Writes a strip that goes across the flag. * Uses a loop that runs 7 times writing `" "` 8 times each time through the loop. ### Line 16 * End of inner loop that started at line 14. ### Line 17 * End of outer loop that started at line 13. ### Line 18 * Draws bottom stripe of flag. ### Line 19 * Draws bottom border of flag. ### Line 20 * Draws the flagpole. * Loops 8 times, writing `"|"` and newline twice each time through the loop. [Answer] # JavaScript (*ES6*), 153 ~~156~~ Using template string, there is 1 newline that is significant and counted Test running the snippet below (being EcmaScript 6, Firefox only) ``` // TEST - Just for testing purpose,redefine console.log console.log = (...x) => O.innerHTML += x+'\n' // SOLUTION o=[0];for(o[r=1]=o[21]='-'[R='repeat'](57);++r<21;o[r]=" * "[R](7).substr(r%2*2,r<11&&23)+' #'[r%3][R](r<11?33:56)+'|')o[37]='';console.log(o.join` |`) ``` ``` <pre id=O></pre> ``` To be even more patriotic, here is the EcmaScript 5 version ``` // TEST - Just for testing purpose,redfine console.log console.log = function(x){ O.innerHTML += x+'\n' } // SOLUTION - 175 bytes for(o=(A=Array)(38),o[0]=0,r=2;r<21;r++)o[r]=A(8)[J='join'](" * ").substr((r&1)*2,r<11?23:0)+A(r<11?34:57)[J](' #'[r%3])+'|'; o[1]=o[r]=A(58)[J]('-'),console.log(o[J]('\n|')) ``` ``` <pre id=O></pre> ``` [Answer] # [///](https://esolangs.org/wiki////): 225 characters ``` /D/ddd//d/--------//H/hhh//h/########//S/sss//s/ //A/aaaaa//a/ * //b/|HHh| |SSs| |SSs| //p/| | | | /0 |DDd- |A * Hh#| | A Ss | |A * Ss | | A Hh#| |A * Ss | | A Ss | |A * Hh#| | A Ss | |A * Ss | bbb|HHh| |DDd- pppp ``` [Answer] # Ruby, ~~104~~ 102 bytes Using ideas from ManAtWork's Ruby answer with permission. ``` puts 0,s=?|+?-*57,(0..18).map{|i|?|+("# "[i%3]*(i>8?56:33)).rjust(56," * *"[i%2*2,4])+?|},s,'| '*16 ``` # Ruby, ~~127 121~~ 112 bytes Changed quotes to `?` used array instead of conditional for stripe colour. used conditional instead of formula for stripe length. ``` puts 0,s=?|+?-*57 19.times{|i|puts ?|+("# "[i%3]*(i>8?56:33)).rjust(56,i%2>0?" *":" * ")+?|} puts s,"|\n"*16 ``` The trick here is to draw the stripes (both red/`#` and white/`space`) to the correct length, then right justify them, padding with stars. Ruby's `rjust` allows us to specify the padding string, which alternates between `" * "` and `" *"`. **Original version, 127 bytes** ``` puts 0,s="|"+"-"*57 19.times{|i|puts("|"+((i%3>0?" ":"#")*((i+1)/10*23+33)).rjust(56,i%2>0?" *":" * ")+"|")} puts s,"|\n"*16 ``` [Answer] # SWI-Prolog, 275 bytes In a language of French origin, which is *kind of* fitting ``` a:-put(48),nl,b,c(0). b:-z,w(-,57). c(I):-nl,I=36;J is I+1,(I=19,b,c(J);I>19,z,c(J);I>8,z,(I mod 3=:=0,w(#,56);tab(56)),z,c(J);z,(I mod 2=:=0,tab(1),w('* ',5),put(42),tab(1);w(' *',5),tab(3)),(0=:=I mod 3,w(#,33);tab(33)),z,c(J)). z:-put(124). w(A,B):-writef('%r',[A,B]). ``` See the result [here](https://ideone.com/hDERz8) [Answer] # C, 235 211 208 205 203 198 197 186 bytes ``` i;x(){for(puts("0");i<37;i++){char b[58]="";i<21?memset(b,i%20?i%3&1?35:32:45,56),i&&i<10?memcpy(b," * * * * * * "+(i%2?0:2),23):0,b[56]=i%20?124:45:0;printf("|%.57s\n",b);}} ``` edit: added some of Cool Guy's suggestions and made use of ?: to replace some if statements. edit: removed overflow \0 prevention and used string length limiter in printf instead. edit: reworked both memset conditionals. edit: moved puts("0") inside the for header to remove its semicolon. edit: slight refactoring to get 11 more bytes. ]
[Question] [ In [Fewest (distinct) characters for Turing Completeness](https://codegolf.stackexchange.com/questions/110648/fewest-distinct-characters-for-turing-completeness), the goal is to find the minimum number of characters which make a language [Turing Complete](https://en.wikipedia.org/wiki/Turing_completeness)...in other words, allow it to do any computation possible with any other language. In this challenge, we'll be doing somewhat of the opposite, and finding the minimum number of characters, without which Turing Completeness is impossible. **Example:** In JavaScript, it is [well known](http://www.jsfuck.com/) that the characters `+!()[]` are all that's needed to write any JS program. We could try using just one of these characters, `+`, as a solution. However, I can get around this with something like: `eval("1\x2b2")`. So, I might add `"`, `'`, and `\` to the list. This would keep going until I find a small list of characters with which it is difficult or impossible to write any program with. **Rules:** * **You must be able to write a valid program without using any characters in your chosen set.** It doesn't need to do anything useful, it just can't error (this is to prevent a character set which includes a single character needed in any valid program) * Actual "Turing Completeness" isn't necessarily required, since languages like C impose things like maximum sizes for pointers which would rule out many languages. I won't set any specific requirements for "how" Turing Complete the threshold is, but be reasonable, and answers which use a clearly Turing Incomplete language or similar tricks should be downvoted * Like [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), competition is purely within a language, not between different ones **How this post works:** This is a sort-of-CnR. Since determining whether a subset of characters is required for TC-ness or not is itself a fun challenge, Robbers will have the task of trying to "crack" submissions by finding a way to achieve TC-ness without the chosen subset of characters (or proving such a task is impossible). Thus, Cops can fall into two categories: 1. Cop-cops: Submissions which are specifically designed to have a trick that still allows TC-ness, as a challenge to Robbers 2. Sort-of-cops: Submissions which do not have an intended crack, where the possible-TC-ness is either unknown or can be proven (it's recommended to say how certain you are that it's not crackable, to prevent Robbers from wasting their time on a likely impossible sort-of-cop) Here is an example of each: > > # Cop-cop: JavaScript, 4 characters > > > > ``` > +"'\ > ``` > > This is a known-crackable cop. The solution isn't super hard to find, but I hope you have fun with it! > > > And a non-cop-cop: > > # Sort-of-cop: JavaScript, 6 characters > > > > ``` > +S("'\ > ``` > > I'm 99% certain this is valid. > > > And a proven-non-cop-cop: > > # Sort-of-cop: JavaScript, 1114112 characters > > > > ``` > [all of unicode] > ``` > > Proof: Kinda obvious > > > **Scoring:** The winner of the cops' challenge, per language, is the smallest subset of characters required for Turing Completeness, which is not cracked within two weeks (at which point it becomes "safe"). **Robbers post:** [Robbers: Smallest subset of characters required for Turing Completeness](https://codegolf.stackexchange.com/questions/247537/robbers-smallest-subset-of-characters-required-for-turing-completeness) **Chat room:** <https://chat.stackexchange.com/rooms/136437/smallest-subset-of-characters-required-for-turing-completeness> [Answer] # Sort-of cop, Common Lisp, one character ``` ( ``` I am almost certain that no Turing Complete CL program can be written without an open paren: the language can easily be extended/modified such that, in the extended language, one can, but I don't think you can bootstrap such an extension without `(`. Programs can still be written, such as `1` or `nil`. This is characters, not octets in a file. [Answer] # Cop-cop: [R](https://www.r-project.org/), 3 bytes, [cracked](https://codegolf.stackexchange.com/a/247593/95126) by Cong Chen ``` (=< ``` [Try it online!](https://tio.run/##K/r/X8PW5v9/AA "R – Try It Online") I imagine this won't take long for one of the [R](https://www.r-project.org/) afficionados to crack... But, as a bonus, it looks like a grumpy face. (=< [Answer] # Sort-of-cop: [Desmos](https://desmos.com/calculator), 1 character ``` = ``` Took out variable/function declaration, which is essential in doing anything useful in Desmos. Would love to be proved wrong though. I have a more restrictive version if this happens to be cracked. [Answer] Round 2! # Actual Cop: [Python](https://www.python.org), 4 characters, cracked ``` :[ef ``` CPython 3.10.2 on Linux. This blocks all control flow and obvious workarounds. No [file encoding workarounds](https://codegolf.stackexchange.com/a/236832), please. (If you want, I can invent a language called *Pythom* which doesn't have the encoding syntax feature. Hopefully, though, this is a clear enough rule.) [Answer] # Sort-of-cop: Ada, 5 bytes `:wWlL` Ada is case insensitive, so letters count twice. `:` prevents defining constants, variables or arguments to functions, `wW` prevents "with"ing any packages that might have variables, and `lL` prevents any sort of loop variables. (There's still a `goto` statement, but without variables it's not enough.) [Answer] # Cop-cop, Haskell, 22 characters, [cracked by ais523](https://codegolf.stackexchange.com/a/247770/85334) ``` ({$                ` ``` Although this is more restrictive than my original maybe-cop, forbidding block comments and all non-line-break Unicode whitespace (that hyphen-looking one is `U+1680 OGHAM SPACE MARK`), I have worked through the possible crack I initially foresaw. ais's crack is a bit simpler than what I initially had in mind, but it works on the same principle of using lists for everything, and I realized something like it would work just about the moment I finished writing this possibly faulty Bitwise Cyclic Tag interpreter: ``` []#_=[] dataString#program|[[head]<*>[program]]==["0"],[programTail]<-[tail]<*>[program],[dataTail]<-[tail]<*>[dataString]=dataTail:dataTail#programTail dataString#program|[[head]<*>[dataString]]==["1"],[programTail]<-[tail]<*>[program],programNext<-[head]<*>[programTail],newData<-dataString++programNext=newData:newData#programTail dataString#program|[programTail]<-[tail]<*>[program]=dataString#programTail main=do[input]<-sequence[getLine];[[[dataString,program]]]<-pure[[read]<*>[input]];[[cycledProgram]]<-pure[[cycle]<*>[program]];print[dataString#cycledProgram] ``` [Try it online!](https://tio.run/##jVLBbsIwDL3vK1B7g1QqV2h22hEhJHazLBS1VolW0hJSMST@HdKsWdNx6E627Peen@McxeWLqurxAIwPHPCtEEbsjZaqjBtdl1qc7gBHEgVm83foS4icQ5RGyHzlU8gKswSMiwGSQaf40h7GIPeAlU/iQHTCUKDjPC3/5alPtvRtbP/vdo7HFF0/rHiWDCMWi4DIe8Cqj5Omp1zxV5LTOgmpeFGDVE1rLPNC55ZUTlCS2UhFuAYI3oH93shim1YTgPYL/kh0hPyWV1TsPNQjXXl86XVjVU0wIB5z7deJlmkasVn3IZ4 "Haskell – Try It Online") [Answer] # Actual Cop: [Python](https://www.python.org), 3 characters, cracked ``` :ef ``` CPython 3.10.2 on Linux. This blocks all control flow and obvious workarounds. No [file encoding workarounds](https://codegolf.stackexchange.com/a/236832), please. (If you want, I can invent a language called *Pythom* which doesn't have the encoding syntax feature. Hopefully, though, this is a clear enough rule.) [Answer] # Maybe-cop, Haskell, 4 characters, [cracked by pxeger](https://codegolf.stackexchange.com/a/247590/85334) ``` ($ ` ``` Defining functions is possible, but writing a program is [challenging](https://tio.run/##y0gszk7Nyfn/PzcxM8@2OLWwNDUvOTU@Ovb/fwA). Nevertheless, this doesn't feel airtight, as only the most straightforward infix opportunities are closed off. [Answer] # Sort-of-cop: [Headass](https://esolangs.org/wiki/Headass), 1 byte; [cracked](https://codegolf.stackexchange.com/a/247709/107310) by m90 ``` E ``` `E` allows you to access stored variables other than the four main registers, access other code blocks, and also halt the program on a dime by trying to reach out of bounds with it (though you can still halt without it) I'm not sure whether it is TC without it, because you can still loop / enter and exit loops with `{}:;)`, but I feel like the lang may be too constrained to allow you to do enough. Just a gut feeling not sure. # Sort-of-cop: [Headass](https://esolangs.org/wiki/Headass), 1 byte ``` } ``` On the opposite side of the coin, without matching loop brackets, there's no looping *within* each code block. This means you aren't able to loop through input or all of your stored variables, which makes me 90% sure that it isn't TC, since you can't store arbitrarily many variables. Looping is still possible with `E`, but the main registers are cleared. Additionally, variables have no upper limit, but encoding/decoding data would be hard probably. # Not a cop: [Headass](https://esolangs.org/wiki/Headass), 2 bytes ``` E} ``` If all else fails, remove all loops :) [Answer] # almost-certainly-not-cop, [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 1 character, [cracked by ais523](https://codegolf.stackexchange.com/a/247763/111305) ``` i ``` Without `i` in tinylisp, you cannot perform if statements, load the library, or construct a string from codepoints (which would give you access to `i` through `eval`ing code), which prevents any control flow from being possible. [Answer] ## Cop-cop: [Applesoft BASIC](https://www.calormen.com/jsbasic/reference.html), 1 byte ``` = ``` Prevents variable assignment, should be pretty easy to figure out. [Answer] ## Sort-of-cop: C (tcc), 6, 5 4 bytes (cracked by [**ais523**](https://codegolf.stackexchange.com/a/247574/104836)) ``` {(?% ``` -1 byte thanks to @RadvylfPrograms -2 byte thanks to @EngineerGaming To the best of my knowledge, C is not Turing complete with these restrictions. No control flow, as `if`, `while`, `for`, `switch`, function calls, etc. are ruled out by this subset. I am merely somewhat sure of this answer. There is probably a crack; I just do not know it. The `{` character is in this subset as there are hacky machine-code tricks that can be used to create a function definition without using `(`, but there are none that I know of that are do not use `{` or `(`. The `?` and `%` are to prevent (tri|di)graph tricks. [Answer] # Almost certainly not a cop - [Vyxal](https://github.com/Vyxal/Vyxal), 15 bytes, [cracked by me](https://codegolf.stackexchange.com/a/264437/100664) ``` {(ƛ⁽‡≬λ@∆ˆE'µøÞ ``` This was a pain. `†E` provide access to python. `'ƛµ` allow iterating over infinite lists. `{(` are loops. `@⁽‡≬λ` stop the definition of functions. `∆` deals with a certain ACE vulnerability that hasn't been patched yet. `ø` deals with `øV` which is replace until no change. And of course `Ė` (eval as vyxal) is necessary so there are no workarounds. Just to be on the safe side, I'm banning `Þ`, the delimiter for list digraphs which can be infinite. I'm pretty sure this blocks all infinite loops. [Answer] ## Sort-of-cop: Brainfuck, 1 byte ``` [ ``` Well, brainfuck needs this character to loop. This answer is quite boring. [Answer] ## Sort-of-cop: Brainflak, 1 byte ``` { ``` In effect, a translation of [my Brainfuck answer](https://codegolf.stackexchange.com/a/247540/104836). Without it, there is no looping. [Answer] # Sort-of-cop: [Charcoal](https://github.com/somebody1234/Charcoal), 3 characters ``` FUW ``` `F` and `W` prevent indefinite loops while `U` prevents access to Python. [Answer] # Sort-of-cop: [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 1 character ``` ` ``` Without this character you can't configure a stage, which means you can't add an indefinite loop. [Answer] # Sort-of-cop: [PARI/GP](https://pari.math.u-bordeaux.fr/), 1 character ``` ( ``` You can't call a function without `(`, which includes control flow functions like `if`, `while`, `for`. The only remaining control flow is list comprehension, but it can only loop over a list, whose size is known and finite. So every program terminates. [Answer] # Cop-cop: Batch, 2 characters, cracked ``` iI ``` Without these to form `if` (case-insensitive), you can't use conditional looping. This was originally a sort-of-cop but ended up becoming a cop-cop. For a sort-of-cop, `%!` should work to prevent accessing variables. [Answer] # Sort-of-cop: Python, 2 bytes `(` Probably impossible, no spaces and parentheses completely breaks Python, not even allowing imports. [Answer] ## Sort-of-cop: Nim, 1 byte (cracked by [the default](https://codegolf.stackexchange.com/a/247824/104836)) ``` : ``` Nim needs `:` to do to any control flow. Thus, as best I can tell, this is a valid if uninteresting answer to this question. I would love to be proven wrong. [Answer] ## Sort-of-cop: Racket, 2 bytes ``` ([ ``` To the best of my knowledge, this prevents Racket from being Turing complete by preventing the creation of any control flow, any function declaration, any arithmetic, etc. I might be wrong, as I am quite inexperienced with Racket. [Answer] # Sort-of-cop: [BitCycle](https://github.com/dloscutoff/Esolangs/tree/master/BitCycle), 3 characters ``` ~+= ``` I just took out all ways (I *think*) to do infinite looping and conditionals. Might be proved wrong by someone more experienced in BitCycle than me. [Answer] ## Sort-of-cop: LOLCODE, 1 byte (cracked by [ais523](https://codegolf.stackexchange.com/a/247774/104836)) ``` S ``` This prevents variable declaration, i.e. "I HAS VAR". [Answer] ## Sort-of-cop: [Headass](https://esolangs.org/wiki/Headass), 4 bytes ``` ^+-] ``` Posting this even though it's longer because it uses a different approach; Now you only have access to values 1 and 0 :P (and input i guess but that doesnt count) I think this is possible but I can't confirm it For fun, while I'm here, ## Sort-of-cop: [Headass](https://esolangs.org/wiki/Headass), 10 bytes ``` DR^+-[]<>( ``` I have no idea if this is possible. It'd be a computational model I am unfamiliar with. My main idea is something to do with using how many values are on the array somehow. You can technically still use value 0 but it might be tricky, since the only char that explicitly gives 0 here is `)`, which is used for control flow/conditionals, so that might get messy. [Answer] # Sort-of-cop: [C#](https://docs.microsoft.com/en-us/dotnet/csharp/), 3 characters ``` .=; ``` No .Equals() for you! # Answers cracked by the default: # Sort-of-cop, 1 byte ``` ; ``` # Sort-of-cop ``` = ``` No variables and no conditionals. There are a lot of these in C#. [Answer] ## Cop-cop: Elixir, 2 characters ``` d- ``` Without these characters you cannot create any function… maybe. [Answer] # Sort-of-cop: C#, 1 byte ``` ( ``` No calling main or other methods, functions, if or loops. Maybe this doesn't count, but you can still write library code. ``` using System; namespace Code; public class A { public string Greeting { get; set; } = "Hello "; public Func<string,string> GreetPerson => name => Test + name; public Func<int,int> Square => a => a*a; } ``` [Answer] # Sort-of-cop: [Knight](https://github.com/knight-lang/knight-lang), 3 characters ``` E=` ``` Takes out `EVAL`, variable assignment, and ``` (run shell command). Taking out variables should prevent Knight from being Turing complete. `E` is there to prevent the `EVAL` and `ASCII` strategy for running any Knight code (which would allow variable assignment), and ``` is there to prevent running Shell, which is Turing complete. [Answer] # Probably-a-Cop: [Go](https://go.dev/), 1 byte ``` ( ``` Functions can be anonymous in Go, but they must use a pair of parens to declare and call them. This prevents declaring `main()` as an entry point into a full program, as well as declaring/calling any new functions since Go doesn't have special lambda syntax. ]
[Question] [ Nepal’s flag ([Wikipedia](https://en.wikipedia.org/wiki/Nepalese_Flag), [Numberphile](http://www.numberphile.com/videos/nepal_flag.html)) looks very different from any other. It also has specific drawing instructions (included in the Wikipedia article). I want you guys to make a program which will draw the flag of Nepal. The user inputs the requested height of the flag (from 100 to 10000 pixels) and the program outputs the flag of Nepal. You can choose any way to draw the flag: everything from ASCII art to OpenGL. This is a popularity contest, so the winner will be the highest voted answer on the 1st of February, so don’t worry about length of code, but remember that shorter code may get more up-votes. There is only one requirement: you are not allowed to use web resources. Have fun :) ![image of the flag of Nepal from Wikimedia Commons](https://upload.wikimedia.org/wikipedia/commons/thumb/9/9b/Flag_of_Nepal.svg/394px-Flag_of_Nepal.svg.png) [Answer] # JavaScript, 569 537 495 442 characters (ASCII) ``` h="";M=Math;Z=M.max;Y=M.min;function d(a,b,r,s,t){n=M.sqrt(a*a+e*e);return n-(r+M.abs((M.atan2(a,e )/M.PI*b+t)%1-0.5)*s*n)}f=parseInt(prompt(),10);for(g=0;g<f;g++){for(k=0;k<2*f;k++)e=k/(0.5*f)-0.8 ,q=g/(0.25*f),u=q-1.08,v=q-1.29,z=e*e+u*u-0.3364,E=Z(-e-0.8,Y(Z(0.62*e+0.8-q,-2.06+q),Z(1*e+0.8+ 0.85-q,-3.87+q))),p=0>Y(d(q-2.91,6,0.38,0.7,10),Y(Z(e*e+v*v-0.3025,-z),Z(d(q-1.54,8,0.25,0.6,10.5) ,q-1.7)))?" ":-0.13>E?";":0>=E?"8":"",h+=p;h+="\n"}h ``` To run : copy-paste to browser console (eg: Chrome developer tools or Firebug) Result : ``` 8 8888 8888888 8888;88888 8888;;;;88888 8888;;;;;;;888888 8888;;;;;;;;;;;88888 8888;;;;;;;;;;;;;;88888 8888;;;;;;;;;;;;;;;;;88888 8888;;;;;;;;;;;;;;;;;;;;888888 8888;;;;;;;;;;;;;;;;;;;;;;;;88888 8888;;;;;;;;;;;;;;;;;;;;;;;;;;;88888 8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;88888 8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;88888 8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888888 8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;88888 8888;;;;;;;;;;;; ; ; ; ;;;;;;;;;;;;;;;;;;;;;;88888 8888;;; ;;;;; ;;;;; ;;;;;;;;;;;;;;;;88888 8888;;; ;;;;;; ;;;;;; ;;;;;;;;;;;;;;;;;;;888888 8888;;;; ;;; ;;; ;;;;;;;;;;;;;;;;;;;;;;;;88888 8888;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;88888 8888;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;88888 8888;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;88888 8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888888 8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;88888 8888;;;;;;;;;;;;;;;;;;;;;;8888888888888888888888888888888888888888888888888888888 8888;;;;;;;;;;;;;;;;;;;;;;;;888 8888;;;;;;;;;;;;;;;;;;;;;;;;;;888 8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;888 8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888 8888;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;888 8888;;;;;;;;; ;;; ;;; ;;;;;;;;;;888 8888;;;;;;;;;; ;;;;;;;;;;;;;888 8888;;;; ;;;;;;;;;888 8888;;;;;; ;;;;;;;;;;;;;888 8888;;;;;;; ;;;;;;;;;;;;;;;;888 8888;;; ;;;;;;;;;;;;;;888 8888;;;;; ;;;;;;;;;;;;;;;;;;888 8888;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;888 8888;;;;; ;;;;;;;;;;;;;;;;;;;;;;888 8888;;;; ;;;;; ;;;;; ;;;;;;;;;;;;;;;;;;;;;;;888 8888;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888 8888;;;;;;;;; ;;;; ;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888 8888;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888 8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888 8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888 8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888 8888888888888888888888888888888888888888888888888888888888888888888888888 888888888888888888888888888888888888888888888888888888888888888888888888888 ``` --- EDIT : added height as user input as ST3 suggested. it works best with big values (eg : 120) [Answer] # Mathematica Nepal's Interim Constitution - Schedule 1 (rel. to Article 6), pp. 260 and 262, provides 25 detailed instructions about how to construct the flag. (see <http://www.ccd.org.np/resources/interim.pdf>). The numbers in the comments refer to the corresponding instructions in the constitution. We will need functions to draw equilateral triangles and determine the distance from a point to a line: ``` ClearAll[triangle] triangle[a_?NumericQ,b_?NumericQ,c_?NumericQ,labeled_:True]:= Block[{x,y,pt,sqr},sqr=#.#&; pt[a1_,b1_,c1_]:=Reduce[sqr[{x,y}]==b1^2&&sqr[{x,y}-{a1,0}]==c1^2&&y>0,{x,y}]; {( (*Polygon[{{0,0},{a,0},{x,y}}]*) Polygon[{{-a/2(*0*),0},{a/2,0},{x-a/2,y}}]), If[labeled, {Text[Style[Framed[a,Background->LightYellow],11],{a/2,0}], Text[Style[Framed[b,Background->LightYellow],11],{x/2,y/2}], Text[Style[Framed[c,Background->LightYellow],11],{(a+x)/2,y/2}]},{}]}/.ToRules[pt[a,b,c]]] (*distance from point to a line *) dist[line_,{x0_,y0_}]:=(Abs[a x0+b y0+c]/.{x0-> m[[1]],y0-> m[[2]]})/Sqrt[a^2+b^2]; (* used below *) ``` The remaining code, with numbers referring to the instructions. By far, the most challenging part is to make the rays for the moon and the sun. `GeometricalTransformation` comes in handy for doing translations and rotations. ``` (*shape inside flag*) (*1*) w=100;a={0,0};b={w,0}; lAB=Line[{a,b}]; tA=Text["A",Offset[{-10,-20},a]]; tB=Text["B",Offset[{20,-20},b]]; (*2*) c={0,w 4/3};d={0,w}; lAC=Line[{a,c}]; tC=Text["C",Offset[{-10,20},c]]; lAD=Line[{a,d}]; tD=Text["D",Offset[{-10,0},d]]; lBD=Line[{b,d}]; (*3*) e=Solve[(x-w)^2+y^2==(w)^2&&y==w-x,{x,y}][[1,All,2]]; tE=Text["E",Offset[{15,0},e]]; (*4*) f={0,e[[2]]};tF=Text["F",Offset[{-10,0},f]]; g={w,e[[2]]};tG=Text["G",Offset[{15,0},g]]; lFG=Line[{f,g}]; poly={a,b,e,g,c}; (*5*)lCG= Line[{c,g}]; (*moon*) (*6*) lineCG=N[((f[[2]]-c[[2]])/w)x+c[[2]](*100*)]; h={w/4,0};tH=Text["H",Offset[{0,-20},h]]; i={h[[1]],lineCG/.x->h[[1]]};tI=Text["I",Offset[{10,0},i]]; lHI={Dashed, LightGray,Line[{h,i}]}; (*7*) j={0,f[[2]]+(c[[2]]-f[[2]])/2};tJ=Text["J",Offset[{-10,10},j]]; lineJG=N[((f[[2]]-j[[2]])/g[[1]])x+j[[2]]]; k={Solve[lineCG==j[[2]],x][[1,1,2]],j[[2]]};tK=Text["K",Offset[{10,10},k]]; (*k={Solve[lineCG\[Equal]c[[2]],x][[1,1,2]],j[[2]]};tK=Text["K",Offset[{10,10},k]];*) lJK={Dashed, LightGray,Line[{j,k}]}; (*8*)l={i[[1]],j[[2]]};tL=Text["L",Offset[{0,10},l]]; (*9*)lJG={LightGray,Dashed,Line[{j,g}]}; (*10*)m={h[[1]],(lineJG/.x-> h[[1]])};tM=Text["M",Offset[{0,10},m]]; (*11*)distMfromBD=dist[{1,1,-w(*100*)},m]; n={i[[1]],m[[2]]-distMfromBD};tN=Text["N",Offset[{0,0},n]]; (*ln=Abs[l[[2]]-n[[2]]];*) (*12*)o={0,m[[2]]};tO=Text["O",Offset[{-10,0},o]]; lM={Dashed,LightGray,Line[{o,{g[[1]],o[[2]]}}]}; (*13*) radiusLN=l[[2]]-n[[2]]; p={m[[1]]-radiusLN,m[[2]]};tP=Text["P",Offset[{0,10},p]]; q={m[[1]]+radiusLN,m[[2]]};tQ=Text["Q",Offset[{0,10},q]]; moonUpperEdge={White,Circle[l,radiusLN,{Pi,2 Pi}]}; moonLowerEdge={White,Circle[m,radiusMQ,{Pi,2 Pi}]}; (*14*)radiusMQ=q[[1]]-m[[1]]; (*15*)radiusNM=m[[2]]-n[[2]]; arc={Yellow,Circle[n,radiusNM,{Pi/7,6 Pi/7}]}; {r,s}=Solve[(x-l[[1]])^2+(y-l[[2]])^2==(radiusLN)^2 &&(x-n[[1]])^2+(y-n[[2]])^2==(radiusNM)^2,{x,y}][[All,All,2]]; tR=Text["R",Offset[{0,0},r]]; tS=Text["S",Offset[{0,0},s]]; t={h[[1]],r[[2]]}; tT={Black,Text["T",Offset[{0,0},t]]}; (*16*)radiusTS=Abs[t[[1]]-s[[1]]]; (*17*)radiusTM=Abs[t[[2]]-m[[2]]]; (*18 triangles*) t2=Table[GeometricTransformation[GeometricTransformation[triangle[4,4,4,False][[1]],RotationTransform[k Pi/8]],{TranslationTransform[t]}],{k,-4,3}]; midRadius=(Abs[radiusTM+radiusTS]/2-2); pos=1;table2=GeometricTransformation[t2[[pos++]],{TranslationTransform[#]}]&/@Table[midRadius {Cos@t,Sin[t]},{t,Pi/16,15 Pi/16,\[Pi]/8}]; (*19 sun*)u={0,f[[2]]/2};tU=Text["U",Offset[{-10,0},u]]; lineBD=N[(d[[2]]/w)x+d[[2]]]; v={-Solve[lineBD==u[[2]],x][[1,1,2]],u[[2]]};tV=Text["V",Offset[{10,0},v]]; lUV={LightGray,Dashed,Line[{u,v}]}; (*20*)w={h[[1]],u[[2]]};tW={Black,Text["W",Offset[{0,0},w]]}; (*21*) (*22*) t3=Table[GeometricTransformation[GeometricTransformation[triangle[9,9,9,False][[1]],RotationTransform[k Pi/6]],{TranslationTransform[w]}],{k,-3,9}]; midRadius3=(Abs[radiusTM+radiusTS]/2+2.5); pos=1; table3=GeometricTransformation[t3[[pos++]],{TranslationTransform[#]}]&/@Table[midRadius3 {Cos@t,Sin[t]},{t,0,2 Pi,2\[Pi]/12}]; Show[ Graphics[{Gray, (*1*)lAB,tA,tB, (*2*)lAC,tC,lAD,tD,lBD, (*3*)tE, (*4*)tF,lFG,tG,{Red,Opacity[.4],Polygon[poly]}, (*5*)lCG, (*6*)tH,lCG,tI,lHI, (*7*)tJ,lJK,tK, (*8*)tL, (*9*)lJG, (*10*)tM, (*11*)tN, (*12*)lM,tO, (*13*)moonUpperEdge,tP,tQ, (*14*)moonLowerEdge, (*15*)arc,tR,tS,tT, (*16*){White,Dashed,Circle[t,radiusTS(*,{0, Pi}*)]}, (*17*){White,Opacity[.5],Disk[t,radiusTM,{0, 2 Pi}]}, (*18 triangles*){White,(*EdgeForm[Black],*)table2}, (*19 sun*)tU,tV,lUV, (*20*)tW,{Opacity[.5],White,Disk[w,Abs[m[[2]]-n[[2]]]]}, (*21*)Circle[w,Abs[l[[2]]-n[[2]]]], (*22*){Black(*White*),EdgeForm[Black],triangle[4,4,4,False](*table3*)}, {White,(*EdgeForm[Black],*)table3}, (*23*) {Darker@Blue,Thickness[.03],Line[{a,b,e,g,c,a}]} }, Ticks-> None(*{{0,100},{0,80,120,130}}*), BaseStyle-> 16,AspectRatio-> 1.3,Axes-> True], (*cresent moon*) RegionPlot[{(x-25)^2+(y-94.19)^2<21.4^2&&(x-25)^2+(y-102.02)^2>21.4^2},{x,0,100},{y,30,130},PlotStyle->{Red,White}]] ``` The following flag, from the above code, is made according to the instructions in the constitution. Colors are modified to enable easier viewing of the construction lines. The letters refer to points and lines in the instructions. ![flag construction](https://i.stack.imgur.com/SPYBb.png) --- By the way, flags of the world can be called up directly within Mathematica. For example: ``` Graphics[CountryData["Nepal", "Flag"][[1]], ImageSize->{Automatic,200}] ``` ![Nepal](https://i.stack.imgur.com/xMudp.png) [Answer] # SVG, ~~1375~~, ~~1262~~, ~~1036~~, ~~999~~, ~~943~~, 939 ``` <svg> <defs> <style>.w{fill:white}</style> <g id="f"><path d="M1,1L1,20L18,20L6,10L17,10z" style="stroke:#003893;fill:#dc143c"/></g> <g id="m"><polygon points="1,0 -.5,.86 -.5,-.86"/></g> <g id="b"><polygon points="1,0 -.5,.86 -.5,-.86"/><polygon points="1,0 -.5,.86 -.5,-.86"transform="rotate(32)"/></g> <g id="t"><use xlink:href="#b"/><use xlink:href="#b"transform="rotate(60)"/></g> <g id="s"> <use xlink:href="#m"/> <use xlink:href="#m"transform="rotate(20)"/> <use xlink:href="#m"transform="rotate(45)"/> <use xlink:href="#m"transform="rotate(70)"/> <use xlink:href="#m"transform="rotate(90)"/> </g> </defs> <g transform="scale(.7)"> <use xlink:href="#f" x="5" y="6"transform="scale(19,23)"/> <use xlink:href="#t" x="2.8" y="7"class="w"transform="scale(70)"/> <path d="M157,292 A 40,35 0 1 0 237,292 43,45 0 1 1 157,292z"class="w"/> <use xlink:href="#s" x="5.6" y="8.9"class="w"transform="scale(35)"/> </g> </svg> ``` ![Chrome rendering](https://i.stack.imgur.com/aDQmH.png) SVG doesn't really have user input, AFAIK, so you can change the scale modifying this line: > > `<g transform="scale(.7)">` > > > [Answer] # Python ``` import turtle, sys from math import sqrt, sin, cos, pi height = int(sys.argv[1]) width = height / 4 * 3 turtle.screensize(width, height) t = turtle.Turtle() # the layout t.pencolor("#0044cc") t.fillcolor("#cc2244") t.pensize(width / 25) t.pendown() t.fill(True) t.forward(width) t.left(135) t.forward(width) t.right(135) t.forward(width / sqrt(2)) t.right(90) t.goto(0, height) t.forward(height) t.fill(False) t.penup() # the bottom star t.fillcolor("#ffffff") t.pencolor("#ffffff") t.pensize(1) radius = width / 5 x = width / 4 y = height / 4 t.goto(x + radius, y) t.pendown() t.fill(True) for i in range(24): t.goto(x + radius * (5 + (-1) ** i) / 6 * cos(i * pi / 12), y + radius * (5 + (-1) ** i) / 6 * sin(i * pi / 12)) t.fill(False) t.penup() # the top star radius = width / 9 x = width / 4 y = height * 2 / 3 t.goto(x + radius, y) t.pendown() t.fill(True) for i in range(28): t.goto(x + radius * (6 + (-1) ** i) / 7 * cos(i * pi / 14), y + radius * (6 + (-1) ** i) / 7 * sin(i * pi / 14)) t.fill(False) t.penup() # the moon radius = width / 5 x = width / 4 y = height / sqrt(2) t.goto(x + radius, y) t.pendown() t.fill(True) for i in range(30): t.goto(x + radius * cos(i * pi / 30), y - radius * sin(i * pi / 30)) for i in range(30): t.goto(x - radius * cos(i * pi / 30), y - radius / 2 * sin(i * pi / 30)) t.fill(False) t.penup() t.hideturtle() raw_input("press enter") ``` Uses python's Tk turtles, example of `python nepal.py 150` and `python nepal.py 200` respectively: ![image](https://i.stack.imgur.com/pGbYH.png) [Answer] # Python (+PIL), 578 Because I'm quite bored today.. ``` from PIL import Image,ImageDraw from math import* I,k,l,m,n,o,_=Image.new('P',(394,480)),479,180,465,232,347,255;D=ImageDraw.Draw(I);P,G=D.polygon,D.pieslice I.putpalette([_,_,_,0,0,_,_,20,60]) def S(x,y,r,e,l,b): p,a,h=[],2*pi/e,r*l;c,d=[0,-a/2][b],[a/2,0][b] for i in range(e):p+=[(x+r*cos(i*a+c),y+r*sin(i*a+c)),(x+h*cos(i*a+d),y+h*sin(i*a+d))] P(p,fill=0) P([(0,0),(393,246),(144,246),(375,k),(0,k)],fill=1) P([(14,25),(o,n),(110,n),(o,m),(14,m)],fill=2) S(96,o,68,12,.6,0) G([(31,90),(163,221)],0,l,fill=0) G([(28,68),(166,200)],0,l,fill=2) S(96,178,40,16,.7,1) I.show() ``` ![nepal](https://i.stack.imgur.com/dHAc3.png) [Answer] # PostScript Code: ``` .15 .15 scale % over-all scale % draw the red area and blue border 7 7 moveto 360 7 lineto 128 240 lineto 367 240 lineto 7 467 lineto closepath gsave % save the outline path for further use .86 .08 .24 setrgbcolor % crimson red fill % draw the red area grestore % get back the saved outline path 0 .22 .58 setrgbcolor % dark blue 14 setlinewidth stroke % draw the blue border 1 setgray % white % draw the lower sun 96 130 translate % coordinate origin of sun 69 0 moveto 12 { % 12 spikes 69 0 lineto 15 rotate 46 0 lineto 15 rotate } repeat closepath fill % draw the upper sun 0 167 translate % coordinate origin at center of sun 29 0 moveto 16 { % 16 spikes 29 0 lineto 11.25 rotate 42 0 lineto 11.25 rotate } repeat closepath fill % draw the crescent moon 0 24 65 180 0 arc % the lower arc 0 57 72 335 205 arcn % the upper arc closepath fill showpage ``` The flag size can be controlled by specifying the resolution in the Ghostscript call. Result (height of flag is 480 pixels, created by `gswin64c -r480 nepal.ps`): [![enter image description here](https://i.stack.imgur.com/SoQ3g.png)](https://i.stack.imgur.com/SoQ3g.png) Result (height of flag is 120 pixels, created by `gswin64c -r120 nepal.ps`): [![enter image description here](https://i.stack.imgur.com/fQwAd.png)](https://i.stack.imgur.com/fQwAd.png) ]
[Question] [ **The [bounty](https://codegolf.stackexchange.com/help/bounty) expires in 5 days**. Answers to this question are eligible for a +100 reputation bounty. [Adám](/users/43319/ad%c3%a1m) wants to **reward an existing answer**: > > [This](https://codegolf.stackexchange.com/a/270066/43319) well-explained answer is the first in APL here, and therefore qualifies for [this](https://codegolf.meta.stackexchange.com/a/17363/43319) bounty. > Originally from [a CMC I proposed for the last BMG event](https://chat.stackexchange.com/transcript/message/58426955#58426955) ## Challenge Given a non-negative integer \$n\$, create a 2D array of size \$2^n √ó 2^n\$ which is generated in the following manner: 1. Divide the matrix into four quadrants of size \$2^{n-1} √ó 2^{n-1}\$. 2. Visiting order of the four quadrants is defined to be the Z-shape (top-left, top-right, bottom-left, then bottom-right). 3. Recursively apply the ordering (steps 1-2) to each quadrant, until the ordering is defined for each cell in the matrix. 4. Visit each cell in the defined order, sequentially writing down 0, 1, 2, 3, ... to each cell. You can output 1-based instead of 0-based (add 1 to all cells in the examples below). Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Examples ``` n = 0: [[0]] n = 1: [[0, 1], [2, 3]] n = 2: [[0, 1, 4, 5], [2, 3, 6, 7], [8, 9, 12, 13], [10, 11, 14, 15]] n = 3: [[0, 1, 4, 5, 16, 17, 20, 21], [2, 3, 6, 7, 18, 19, 22, 23], [8, 9, 12, 13, 24, 25, 28, 29], [10, 11, 14, 15, 26, 27, 30, 31], [32, 33, 36, 37, 48, 49, 52, 53], [34, 35, 38, 39, 50, 51, 54, 55], [40, 41, 44, 45, 56, 57, 60, 61], [42, 43, 46, 47, 58, 59, 62, 63]] ``` Brownie points for beating or tying with my ~~9~~ 6 bytes in Jelly or 19 bytes in J. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` 4·πó>2ƒ† ``` [Try it online!](https://tio.run/##y0rNyan8/9/k4c7pdkZHFvw/3O7@/78xAA "Jelly ‚Äì Try It Online") Neil saved a byte. Thanks! ``` 4·πó n-th Cartesian power of [1,2,3,4] >2 Replace 1,2,3,4 with 0,0,1,1 ƒ† Group indices by values ``` For n=2, `4·πó>2` generates a list of 16 pairs: ``` 1: [0, 0] 2: [0, 0] 3: [0, 1] 4: [0, 1] 5: [0, 0] 6: [0, 0] 7: [0, 1] 8: [0, 1] 9: [1, 0] 10: [1, 0] 11: [1, 1] 12: [1, 1] 13: [1, 0] 14: [1, 0] 15: [1, 1] 16: [1, 1] ``` Then `ƒ†` turns this into a list of lists: * all indices where the value is `0 0`: namely `[ 1, 2, 5, 6]`, * all indices where the value is `0 1`: namely `[ 3, 4, 7, 8]`, * all indices where the value is `1 0`: namely `[ 9, 10, 13, 14]`, * all indices where the value is `1 1`: namely `[11, 12, 15, 16]`. The result is a Z-matrix. ## Why does this work? Suppose we bump the input up to \$n=3\$. How does our output compare to that for \$n=2\$? Let's call `4·πó>2` a function \$f\$. The list of 16 pairs above is the output of \$f(2)\$. By definition of the Cartesian power, \$f(3) = [0,0,1,1] \times f(2)\$ = ``` [[0] + x for x in f(2)] (indices 1..16) + [[0] + x for x in f(2)] (indices 17..32) + [[1] + x for x in f(2)] (indices 33..48) + [[1] + x for x in f(2)] (indices 49..64) ``` There are now 8 values for `ƒ†` to group the indices by, ranging from `[0,0,0]` to `[1,1,1]`. All indices in `1..32` end up in the first four groups, and because we repeated `[[0] + x for x in f(2)]` twice, `a[i+16]` is always in the same group as `a[i]`. Then, all indices in `33..64` end up in the last four groups, and their relative order is the same as the first half of the list (the only difference is they have `1` instead of `0` in front). Within each quadrant, the order is the same as it was in `f(2)`. So we get: ``` [0, 0, 0]: 1 2 5 6 17 18 21 22 [0, 0, 1]: 3 4 7 8 19 20 23 24 [0, 1, 0]: 9 10 13 14 25 26 29 30 [0, 1, 1]: 11 12 15 16 27 28 31 32 [1, 0, 0]: 33 34 37 38 49 50 53 54 [1, 0, 1]: 35 36 39 40 51 52 55 56 [1, 1, 0]: 41 42 45 46 57 58 61 62 [1, 1, 1]: 43 44 47 48 59 60 63 64 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~27~~ ~~23~~ 18 bytes ``` ‚âîÔº•Ôº∏¬≤ԺƂܮ‚Å¥‚Ü®Œπ¬≤œÖÔº©Ôº•‚äóœÖ‚Å∫ŒπœÖ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DN7FAIyC/PLVIw0hHwTOvoLTErzQ3CcjV1NRRcEosTtUwgdKZOgpGmiDRUk1rroCizLwSDefE4hKwCS75pUk5qSkapUDpgJzSYpDiUqBiTev//03@65blAAA "Charcoal ‚Äì Try It Online") Link is to verbose version of code. Explanation: Now a port of @tsh's Python answer. ``` ‚âîÔº•Ôº∏¬≤ԺƂܮ‚Å¥‚Ü®Œπ¬≤œÖ ``` Map the numbers up to 2‚Åø by converting them to base 2 and then interpreting the result as base 4. ``` Ôº©Ôº•‚äóœÖ‚Å∫ŒπœÖ ``` Vectorised add the doubled array to itself as a matrix. Previous ~~27~~ 23 byte answer uses a different approach that is interesting in its own right because some golfing languages have built-ins for things like group index by value or sort array by key. ``` ‚âîÔº•Ôº∏‚ťԺƂܮ¬≤√∑‚Ü®Œπ‚Å¥¬¶¬≤œÖÔº©Ôº•‚äï‚åàœÖ‚åïÔº°œÖŒπ ``` [Try it online!](https://tio.run/##HYw7DsIwEER7TuFyLZkmcpcqgJBSgHIFY69gJXsT@RO4vbFTzps3Yz8m2tX4WqeU6M3wMBss6xcjaCVm3kp@lvBqUUolLiYhDJ3nG@3kEA5CSujWDrI7RY6nJRJnuJqUj7@ZbcSAnNG1/KNQApTu3ond5D0UJaiN5Virrufd/wE "Charcoal ‚Äì Try It Online") Link is to verbose version of code. Explanation: ``` ‚âîÔº•Ôº∏‚ťԺƂܮ¬≤√∑‚Ü®Œπ‚Å¥¬¶¬≤œÖ ``` For each element in the final diagram, convert it to base 4, halve the digits, then convert from base 2. This gives the row number for that element. ``` Ôº©Ôº•‚äï‚åàœÖ‚åïÔº°œÖŒπ ``` For each row list the elements assigned to that row. [Answer] # [J](http://jsoftware.com/), 21 19 bytes Found Bubbler's solution. :-) ``` 2(*+/])4#.2#:@i.@^] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jTS0tPVjNU2U9YyUrRwy9RziYv9rcmmkJmfkO1inaSppGGgqZOopmP4HAA "J ‚Äì Try It Online") The first row is [A000695](http://oeis.org/A000695), the first column is the same but times two. In the comments Marc LeBrun notes that this is rebasing `n` from base 2 into base 4. So that's helpful with J: ``` 2(*+/])4#.2#:@i.@^] 2 i.@^] 0 1 ‚Ķ 2^n #: digits in base 2 0 0 0 0 0 1 ‚Ķ 1 1 0 1 1 1 4#. interpret as digits in base 4 0 1 4 5 16 17 20 21 2(*+/]) addition table of list*2 with list ``` [Answer] # [R](https://www.r-project.org/), ~~65~~ ~~63~~ ~~59~~ ~~57~~ 55 bytes ``` for(i in seq(l=scan()))T=T^4%x%2^rbind(0:1,2:3);log2(T) ``` [Try it online!](https://tio.run/##Vc1BCsIwEEDRvacYkMIMKLTRVbW3yLrQ1kQGyiROIgri2dO6Ebr98PhaPFyP4J8yZQ6CTPCBNA2yqcSwty5leOkQo9PigyIDCyT3wLn7ASQi29n@XL0r0@vIcsO6bQ6mPdFlDneDlsp395f12qOyZPTrlcoC "R ‚Äì Try It Online") Relies on the observation that each next iteration `N` relates to the previous iteration `P` by Kronecker product-like operation with the matrix `M` for `n=1`, but using summation instead of multiplication: ``` N = kronecker(4*P, M, FUN = "+") ``` Here, we transform the values with powers and logarithms in order to make use of the actual Kronecker product function, which is conveniently abbreviated as `%x%` operator. [Answer] # [Python 2](https://docs.python.org/2/), 81 bytes ``` R=[int(bin(x)[2:],4)for x in range(2**input())] for y in R:print[x+y*2for x in R] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8g2OjOvRCMpM0@jQjPayCpWx0QzLb9IoUIhM0@hKDEvPVXDSEsrM6@gtERDUzOWCyRXCZILsiooAuqMrtCu1DKC6wiK/f/fGAA "Python 2 ‚Äì Try It Online") [Answer] # [J](http://jsoftware.com/), 33 bytes ``` ,~@^~&2$4(/:[:<.@-:4#.inv])@i.@^] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/deoc4urUjFRMNPStoq1s9Bx0rUyU9TLzymI1HTL1HOJi/2typSZn5CukKRhAGOrqMAFDdAEjdAHj/wA "J ‚Äì Try It Online") The true insight of this idea is due to [Neil's excellent answer](https://codegolf.stackexchange.com/a/231027/15469). I'll mention a couple of other insights I had which didn't help with bytes but might be useful to others: 1. The deltas along each row follow a repeating pattern whose unique elements are <http://oeis.org/A007583>: 1, 3, 11, 43, 171... 2. Similarly the deltas going down each column follow <http://oeis.org/A047849>: 1, 2, 6, 22, 86, 342... ## how * `4...@i.@^]` Produces `0, 1, ... 4^n`, where n is the input. * `/:[:<.@-:4#.inv]` Sort those according to row number, which we get by converting to base 4, halving, and flooring. * `,~@^~&2$` Now shape that into a square matrix of side length `2^n`. [Answer] # [R](https://www.r-project.org/), ~~57~~ ~~52~~ 49 bytes *Edit: -8 bytes by changing to iterative approach with `scan()` for input (instead of recursive function)* ``` for(i in seq(l=2*scan())-1)F=t(cbind(F,F+2^i));+F ``` [Try it online!](https://tio.run/##K/r/Py2/SCNTITNPoTi1UCPH1kirODkxT0NTU9dQ0822RCM5KTMvRcNNx03bKC5TU9Na2@2/8X8A "R ‚Äì Try It Online") **Explanation** ~~Recursive function that~~ Each loop `i`creates two side-by-side copies of the columns of a matrix, adding ~~the maximum value of the first +1~~ `2^i` to the second copy, and then transposes it all. This creates the top left & top right copies of the last matrix (`F`), transposed: so, every second loop creates a full 'Z' of four copies of the last matrix, untransposed. So we need to loop twice the value of `n` times. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` 4*·∏∂b4:2·∏у† ``` [Try it online!](https://tio.run/##y0rNyan8/99E6@GObUkmVkYPd7QcWfD/cLv7///GAA "Jelly ‚Äì Try It Online") Pretty much a port of [Neil's Charcoal answer](https://codegolf.stackexchange.com/a/231027/68942), so go upvote them too. ``` 4*·∏∂b4:2·∏у† Main Link; take x 4* 4 ** x ·∏∂ [0, 1, 2, ..., 4 ** x - 1] b4 Convert to base 4 :2 Floor-divide by 2 ·∏Ñ Convert from binary ƒ† Group the indices by their corresponding values ``` This answer can be ported directly into yuno. # [yuno](https://github.com/hyper-neutrino/yuno), 9 bytes ``` 4* Äb4:2…ÆG ``` [Try it online!](https://yuno.hyper-neutrino.xyz/#WyIiLCI0KsqAYjQ6MsmuRyIsIiIsIiIsIiIsWyIzIl1d "yuno online interpreter") --- This approach is probably what Bubbler's 6-byter is going for, but a) I need to find how to get `0,0,1,1` in 3 bytes, and b) I need to figure out how to make the format valid without the `s2*$` being that long: # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` √ò.x2¬§·π󷪧s2*$ ``` [Try it online!](https://tio.run/##ARwA4/9qZWxsef//w5gueDLCpOG5l@G7pHMyKiT///8z "Jelly ‚Äì Try It Online") # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` ,Uz0$FU 2*·∏∂B√ß√æ`·∏Ñ ``` [Try it online!](https://tio.run/##y0rNyan8/18ntMpAxS2Uy0jr4Y5tToeXH96X8HBHy////40B "Jelly ‚Äì Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~49~~ 32 bytes ``` PositionIndex@Tuples[0|0|1|1,#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyC/OLMkMz/PMy8ltcIhpLQgJ7U42qDGoMawxlBHOVbtf0BRZl6JQ5qDa3JGvoOyWl1wcmJeXVBiXnpqtIGOcex/AA "Wolfram Language (Mathematica) ‚Äì Try It Online") Returns an `Association` where the values correspond with rows of the matrix (associations are ordered). For a traditional list-of-lists output, prepend `List@@` (+6 bytes). Port of Lynn's [Jelly solution](https://codegolf.stackexchange.com/a/231062/81203). --- Older solution: ``` Outer[#+##&,t=#~FromDigits~4&/@{0,1}~Tuples~#,t]& ``` [Try it online!](https://tio.run/##BcGxDkAwEADQj7mkiyYIq6QDVoJNDJemaKIldSZxv17vOaTdOCSrMa5V7B4yYYYEQEiqgNtwutpulm4uRareTOYfT891mJtB0iJiH6ynVK2q0fupQPCo0fOAfjNzJosl/g "Wolfram Language (Mathematica) ‚Äì Try It Online") [Answer] # ARM A32 machine code, 48 bytes ``` e3a0c000 e1a0215c e1b03152 112fff1e e02c3112 ec432b10 f2800e00 f2810590 f2211110 f480180d e28cc001 eafffff4 ``` Following the [AAPCS](https://github.com/ARM-software/abi-aa/blob/2bcab1e3b22d55170c563c3c7940134089176746/aapcs32/aapcs32.rst), this takes in r0 the address of an *array* of *array*s of 32-bit integers to be filled with the result, and takes n in r1. Assembly: ``` .section .text .code 32 .global zm zm: mov r12, #0 @ Initialise counter to 0 loop: asr r2, r12, r1 @ Shift counter right by n, to obtain the top half asrs r3, r2, r1 @ Shift that right by n again, to check for ending (2^2n) bxne lr @ If so, return eor r3, r12, r2, lsl r1 @ Exclusive-or cancels out the top half, to obtain the bottom half vmov d0, r2, r3 @ Place the two halves into a 64-bit SIMD&FP register vmull.p8 q0, d0, d0 @ Multiply by itself as polynomials over GF(2); @ because this is a ring of characteristic 2, (a+b)^2 = a^2 + b^2 holds, @ thus squaring doubles each exponent in the polynomial, spreading out the bits. @ Results go into Q0, which is also D0 and D1. vshl.i64 d0, #1 @ Shift the squared top half left by 1 ... vorr d1, d0 @ ... and combine by OR with the bottom half vst1.32 {d1[0]}, [r0]! @ Place the result into memory, advancing the pointer add r12, #1 @ Increment the counter b loop @ Repeat ``` (This should work on v7 or later from what I can tell, but in the testing setup I'm using (similar to [here](https://codegolf.stackexchange.com/questions/175236/sum-square-difference/231078#231078)), it gives 'instruction not supported' errors on versions lower than v8.4, which doesn't seem right.) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~¬†14 12¬†~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ### 9 byter ``` √ò.·πó·∏Ö4+√æ·∏§$ ``` **[Try it online!](https://tio.run/##ARwA4/9qZWxsef//w5gu4bmX4biFNCvDvuG4pCT///8z "Jelly ‚Äì Try It Online")** ##### How? Makes a table under \$x+2y\$ where both \$x\$ and \$y\$ are a prefix of the Moser‚ÄìDe Bruijn sequence. ``` √ò.·πó·∏Ö4+√æ·∏§$ - Link: n √ò. - bits -> [0,1] ·πó - Cartesian power (n) -> binary representations of [0..2^n-1] ·∏Ö4 - convert from base four -> first 2^n terms of the Moser‚ÄìDe Bruijn sequence $ - last two links as a monad, f(S): ·∏§ - double -> D=[2x for x in S] √æ - (s in S) table with (d in D): + - (s) add (d) ``` (Still no clue for the 6 byte code though!) --- ### 12 Byter -1 thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) (we can use 1-based values) ``` ƒ†;"FL+∆äZ∆ä‚Å∏¬°‚Å∫ ``` A monadic Link that accepts a non-negative integer and yields the matrix (using the 1-based values option). **[Try it online!](https://tio.run/##ASYA2f9qZWxsef//xKA7IkZMK8aKWsaK4oG4wqHigbr/w4fFkuG5mP//Mw "Jelly ‚Äì Try It Online")** (Footer formats as a Python list for clarity.) ##### How? Starts with `[[1]]` and repeatedly applies a function that creates the required new entries to the right (and then below, via the transposed matrix) by adding the number of current elements to each element. ``` ƒ†;"FL+∆äZ∆ä‚Å∏¬°‚Å∫ - Link: non-negative integer, n ƒ† - group indices (of implicit [n]) by value -> [[1]] (our initial M) ¬° - repeat... ‚Å∏ - ...number of times: chain's left argument -> n ∆ä - ...what: last three links as a monad, f(M): ∆ä - last three links as a monad, g(M): F - flatten L - length + - add to elements of M " - zip (rows of M) with (rows of that) and apply: ; - concatenation Z - transpose ‚Å∫ - repeat last link (i.e. repeat f() n more times) ``` [Answer] # Python 3 with numpy, ~~91~~ ~~87~~ ~~74~~ ~~70~~ ~~69~~ 67 bytes ``` lambda n:c_[s:=(c_[:1<<n]&(b:=1<<r_[:n]))@b]*2+s from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3nXMSc5NSEhXyrJLjo4utbDWAlJWhjU1erJpGkpUtkFUEFMiL1dR0SIrVMtIu5korys9VyCvNLahUyMwtyC8q0YIYtbqgKDOvRCNNw1hTEyKyYAGEBgA) `c_[:1<<n]` produces an array of the numbers 0 (inclusive) to 2n (exclusive), vertically. `r_[:n]` produces 0 (inc.) to n (exc.), horizontally, and the left shift makes the corresponding powers of 2, saved in `b`. The bitwise AND, with broadcasting, produces a table of values, splitting the numbers into their constituent bits. The matrix product (`@`) is equivalent to taking the dot product of each broken-down number with `b`; this squares each nonzero bit, changing powers of 2 into powers of 4, and adds them back up, producing a horizontal sequence 0, 1, 4, 5, 16, 17, 20, 21, ..., which is saved in `s`. `c_` makes a vertical version of that sequence, which is doubled and added to the original sequence, which (by broadcasting) produces a table of sums, which is the required result. --- Previously: ``` from numpy import* lambda n:(s:=vander([4],8)@unpackbits(mat(r_[:1<<n],uint8),0))+s.T*2 ``` `r_[:1<<n]` produces 0 (inc.) to 2n (exc.). It is passed to `mat` ("Interpret the input as a matrix"), which in particular makes it 2-dimensional, while also changing its type to `uint8`, which is necessary for the next function `unpackbits`, which breaks the numbers down into their binary representations, across the added dimension. `vander([4],8)` produces an array of powers of 4, which in the `@` (matrix multiplication) gets dot-producted with each binary vector, producing a similar `s` (transposed differently), and the rest is similar. [Answer] # [Haskell](https://www.haskell.org/), 61 bytes ``` f n|r<-iterate(>>= \x->[4*x,4*x+1])[0]!!n=[[x+2*y|x<-r]|y<-r] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hr6bIRjezJLUosSRVw87OViGmQtcu2kSrQgeItQ1jNaMNYhUV82yjoyu0jbQqaypsdItiaypB5P/cxMw829zEAl@FgqLMvBIFFYU0BeP/AA "Haskell ‚Äì Try It Online") Same idea as tsh's Python, but the list `r` (e.g. `[0,1,4,5,16,17,20,21]`) is created in a Haskell-y way. [Answer] # [Julia 1.0](http://julialang.org/), 42 bytes ``` !x=(x-=1)<0||(~n=n*2^2x.+!x;[~0 ~1;~2 ~3]) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/X7HCVqNC19ZQ08agpkajLs82T8sozqhCT1uxwjq6zkChztC6zkihzjhW839KZnFBTmKlhqKx5n8A "Julia 1.0 ‚Äì Try It Online") (one-indexed) [Answer] # JavaScript (ES6), ~~¬†89 86¬†~~ 79 bytes *Saved 7 bytes thanks to @tsh* ``` n=>[...Array(1<<n)].map((_,y,a)=>a.map(g=(k=1,x)=>k>>n?0:x&k|(y&k|g(k*2,x))*2)) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i5aT0/PsagosVLD0MYmTzNWLzexQEMjXqdSJ1HT1i4RzE231ci2NdSpAApk29nl2RtYVahl12hUAol0jWwtI6CMppaRpub/5Py84vycVL2c/HSNNA0DTU0uVBFDDBEjDBFjoDkA "JavaScript (Node.js) ‚Äì Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/)/MATLAB, 67 bytes ``` function x=f(n);x=1;for i=1:n;k=4^i/4;x=[x,k+x;2*k+x,3*k+x];end;end ``` [Try it online!](https://tio.run/##y08uSSxL/f8/rTQvuSQzP0@hwjZNI0/TusLW0Dotv0gh09bQKs8629YkLlPfBCgaXaGTrV1hbaQFJHWMQWSsdWpeCgj/T8ksLtBI0zDR1PwPAA "Octave ‚Äì Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 88 bytes ``` f 0=[[1]] f n=let(#)=zipWith(++);m=n-1;a=f m;[b,c,d]=map(map(+4^m))<$>[a,b,c]in a#b++c#d ``` [Try it online!](https://tio.run/##FYq7CgMhEAD7fMWCKRQN5Eg6s/cHV6cQA3sPOYkrkljdzxtTTDHM7PR9bym1FuCKzg3enwJkTFuVQuERyzPWXWqtLGO@DJYwAFs3m8WsHpmK/KPvL1bqcR4dmZ58zEBi1noRa2PqhtC3Ccon5goywE21Hw "Haskell ‚Äì Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~90...~~ 64 bytes ``` ->n{(k=0...2**n).map{|y|k.map{|x|k.sum{|z|[x,y][z%2][z/2]<<z}}}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWiPb1kBPT89ISytPUy83saC6prImG8KoADKKS3Ora6pqoit0KmOjq1SNgIS@UayNTVUtEPwvUEiLNo79DwA "Ruby ‚Äì Try It Online") ### Quick explanation: Every number can be expressed by interleaving the binary digits of the number of row and column. [Answer] # [Pip](https://github.com/dloscutoff/pip), 19 bytes ``` $+{TBg}FB4*^21MC Ea ``` [Try it here!](https://replit.com/@dloscutoff/pip) Or, here's a 20-byte equivalent in Pip Classic: [Try it online!](https://tio.run/##K8gs@P9fRbs6xCm91s3JRCvOyNDX2UhLK/H///@6wf@NAQ "Pip ‚Äì Try It Online") ### Explanation Inspired by [Neil's comment](https://codegolf.stackexchange.com/questions/231022/recursive-z-matrix#comment529704_231022) about interleaving bit patterns, we can simply map the x and y coordinates to the right value (example x = 5, y = 9): ``` 5 101 0 1 0 1 9 1001 1 0 0 1 10010011 147 ``` We're not going to use Pip's `WV` operator to do the interleaving, since it works left-to-right and doesn't fill in with zeros; instead, observe that an equivalent formula is to convert to base 4, multiply the y value by 2, and sum: ``` 5 101 1 0 1 10001 (2) = 101 (4) = 17 (10) 9 1001 1 0 0 1 10000010 (2) = 2002 (4) = 130 (10) 147 ``` So: ``` $+{TBg}FB4*^21MC Ea Ea 2^input MC Map this function to a grid of coordinate pairs of that size: {TBg} Convert each coordinate to binary FB4 Treat as base 4 and convert back to decimal * Multiply by ^21 list containing 2 and 1 (multiplying the row by 2 and the column by 1) $+ Sum ``` [Answer] # [Python 3](https://docs.python.org/3/) + numpy, 66 bytes ``` from numpy import* f=lambda m:c_[m and(f(m-.5),4**m//2+f(m-.5))].T ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1chrzS3oFIhM7cgv6hEiyvNNicxNyklUSHXKjk@OlchMS9FI00jV1fPVFPHREsrV1/fSBvK14zVC/lfUJSZVwJUYaCpyQVjGyKxjZDYxpqa/wE "Python 3 ‚Äì Try It Online") Mostly straight-forward recursion. Splits the 2x2 update into 2 1x2 updates with intermittent transpose. # [Python 3](https://docs.python.org/3/) + numpy, 68 bytes ``` from numpy import* f=lambda m:m and log2(kron(4**f(m-.5),c_[1:3])).T ``` [Try it online!](https://tio.run/##TcaxCoMwEADQ3a@48S6oqKmL0L/oJiJpJa3o3YUQB78@nQTf9MKZfio2Zx@VQQ4OJ6wcNCZT@Ofu@L044IHByQK7fjvcogo@jPHIVd1T@ZnHdrATUf3KIa6S0GNDVFxvb@9ut0T5Dw "Python 3 ‚Äì Try It Online") *Just noticed that @Kirill L.'s R answer uses the exact same idea.* By componentwise exponentiating adding in the original problem becomes multiplying so friend Kronecker can do the heavy lifting for us. Downside: will get numerically inaccurate pretty fast. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 18 [bytes](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` {(‚çâ‚àæ‚çâ+¬∑‚ↂ•ä)‚çü2‚çüùï©‚âç‚âç0} ``` [Try it here.](https://mlochbaum.github.io/BQN/try.html#code=RuKGkHso4o2J4oi+4o2JK8K34omg4qWKKeKNnzLijZ/wnZWp4omN4omNMH0KCkbCqDDigL8x4oC/MuKAvzM=) How it works: ``` {(‚çâ‚àæ‚çâ+¬∑‚ↂ•ä)‚çü2‚çüùï©‚âç‚âç0} ‚âç‚âç0 # Starting from a rank 2 array containing 0 ‚çüùï© # apply the preceding function ùï© times where ùï© is the input ‚çâ‚àæ # The transposed array joined to ‚çâ+¬∑‚ↂ•ä # the transposed array plus the number of elements ( )‚çü2 # applied twice ``` [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 10 bytes [SBCS](https://github.com/abrudz/SBCS) Port of [Lynn's Jelly answer](https://codegolf.stackexchange.com/a/231062/91267) ``` ‚çâ‚䢂å∏2|,‚ç≥‚éï‚ç¥4 ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9Tb@ahr0aOeHUY1Oo96Nz/qm/qod4sJAA&f=AwA&i=S@My5FJX50rjMoJQxgA&r=tio&l=apl-dyalog&m=tradfn&n=f) ``` ‚çâ‚䢂å∏2|,‚ç≥‚éï‚ç¥4¬≠‚Ű‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Ű‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚Ű‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚Å¢‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å£‚Å™‚Äè‚ņ‚Å™‚Å™‚ņ‚Å™‚Å™‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å£‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å¢‚Å™‚Äè‚ņ‚Å™‚Å™‚ņ‚Å™‚Å™‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚ŧ‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Ű‚Å™‚Äè‚ņ‚Å™‚Å™‚ņ‚Å™‚Å™‚ņ‚Å™‚Å™‚ņ‚Å™‚Å™‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Ű‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Å¢‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Ű‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå¬≠ ‚éï‚ç¥4 # ‚Äé‚Ű4 repeated n times ‚ç≥ # ‚Äé‚Å¢create a n-dimensional array with shape [4, 4, ..., 4] where value equals index , # ‚Äé‚Å£flatten 2| # ‚Äé‚ŧmodulo 2 ‚䢂å∏ # ‚Äé‚Å¢‚Űgroup by value and return indices for each group ‚çâ # ‚Äé‚Å¢‚Å¢transpose üíé ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Python 3](https://docs.python.org/3/) + [numpy](https://numpy.org/doc/stable/index.html), 113 bytes A very literal (and long) implementation of the spec. ``` lambda n:sum(tile(R(R(c_[:2,2:4].T,1<<i,0),1<<i,1)<<2*i,(1<<n+~i,)*2)for i in r_[:n]) from numpy import* R=repeat ``` [Try it online!](https://tio.run/##JYuxDsIgFAD3fsUbeUiMpU4N/YnGTRuDCvEl5UGQDl38dSQxN1xuuLSXd@Sh@ulWVxseLws8frYgCq1OzI3n/Tpqpcfzcryo3hhSJ/y7R2O0JCVa8eFLCqVGHzMQEENuHy/Y@RwD8BbSDhRSzEV285RdcrbUlImL8GJArD8 "Python 3 ‚Äì Try It Online") [Answer] # JavaScript (ES6), 72 bytes ``` f=(n,a=[0])=>n?f(n-1,a.flatMap(x=>[x*=4,x+1])):a.map(y=>a.map(x=>x+2*y)) ``` [Try it online!](https://tio.run/##JYlBCoMwEEX3nmKWGRODFle1k56gJxAXgzUlxSaiUiKlZ08DhQ/v8f6T37yNq1v2yof7lCzlCa@Y@npAMv5qha8axdrOvN94EZFMH0tqVZTNgHhm/cr1IPOXfEd5Kg/EZMMKwgFB3YGDC0GbKSXCpwAYg9/CPOk5PIQVDrErvukH "JavaScript (Node.js) ‚Äì Try It Online") Use the idea from [Lynn](https://codegolf.stackexchange.com/users/3852/lynn)'s [Haskell answer](https://codegolf.stackexchange.com/a/231061/44718) which saves many bytes on generating the list for iterate. Using base conversion as what my Python answer do will [make it much longer (79 bytes)](https://tio.run/##HYpBDoIwEADvvGJPZLdoVcINt4nvMMY0CGQNtKQYQ6O@vSqnmUzmbp92boJMj63ztzZ1nBwbtHzWWp9CsBFLpRxd9Ggn7BmvGyE2kueSH96V6v9hVxLROkQ2dpWFzVKUKhKlzgdAAYZ9DQJHhurHoiB4ZQCNd7MfWj34HjsUojr7pC8). [Answer] # Python 3.8 + numpy, ~~85~~ 84 bytes ``` import numpy;z=lambda n:n and numpy.block([[m:=z(n-1),m+(k:=4**~-n)],[m+2*k,m+3*k]]) ``` Not as clever as some of the other python ones, but shorter than the other python 3 ones. Also 0 returns a scalar instead of a list, not sure if that's allowed. [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Port of [tsh's Python solution](https://codegolf.stackexchange.com/a/231033/58974). ``` 2pU √ᬧn4 ¬£√ã+X√ë ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=MnBVIMekbjQKo8srWNE&footer=VmMg%2bSDyMnBOKW24&input=MwotUg) [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 62 bytes ``` n->matrix(2^n,,i,j,(g=k->fromdigits(binary(k-1),4))(i)*2+g(j)) ``` [Try it online!](https://tio.run/##DccxDoAgDADArzi2WgbRFZ9igjE0hYCkMujr0duuehXDtYfB9WK27JvKA3YvREKRgF0yW9Arn8LSbjikeH0hmRlpRQTB0U4MEbFXldIqBFj@fA "Pari/GP ‚Äì Try It Online") ]
[Question] [ Given an integer *k* and either a block of text, or a 2d array that the inner arrays may have unequal lengths (that resembles a block of text), rotate every character or element in the *k*-th column up or down to the next position that exists. ### Example Rotate the 20th column of the following text (1-based): ``` A line with more th**a**n k characters. A longer line with **m**ore than k character. A short line. Rotate here: ------**v**-- This is long enough**.** This is not enough. Wrapping around to **t**he first line. ``` Output: ``` A line with more th**t**n k characters. A longer line with **a**ore than k character. A short line. Rotate here: ------**m**-- This is long enough**v** This is not enough. Wrapping around to **.**he first line. ``` Rotating the *k*-th column of the same input where 35 < *k* < 42 would yield the input text unchanged. ### Rules * You may use raw text, an array of lines, a 2d array of characters, or any reasonable format to represent the data. You may also use data types other than characters. * The number of possible values of the data type of the elements must be at least 20 if your code length depends on it, otherwise at least 2. This could be a subset of the characters or other values supported in the native type. * Spaces and any kind of null values are just normal values, if you allow them in the input. You may also simply exclude them in the element type. * **Rule change:** You are allowed to pad the shorter arrays with a generic default value (such as spaces), if you prefer using arrays with equal lengths to store the data. * *k* could be 0-based or 1-based. It is guaranteed to be inside the longest line in the input (implying the input has at least one non-empty line). * You may choose whether it rotates up or down. * Either just rotate one position, or rotate *n* positions where *n* is a positive integer given in the input. * Shortest code wins. [Answer] # [Python 2](https://docs.python.org/2/), ~~111~~ ~~110~~ ~~109~~ ~~99~~ ~~98~~ ~~96~~ 94 bytes ``` lambda a,n:[l[:n]+(l[n:]and[L[n]for L in a[i:]+a if L[n:]][1]+l[n+1:])for i,l in enumerate(a)] ``` [Try it online!](https://tio.run/##hc6xTsQwDAbgnafwdq3aIpWNSAzsnRASQ8hgrsklutSu3BTE05ckAuk2okz//yX2@p0808Phnt6PiMvHjIA9KR21ItM1UZMySLOeNBnHAhMEAtRBmQ4hOJgKMHo0XabdqExbVOhjcZb2xQom22BrjlLU2DX69AwxkIWvkDwsLBaSR4IrnD0KnpOV7f7UQ2FMFyv/6V@8eZZUbQ1eOOXh4K1YBUM9n8NQmlcfNsi3/J7X5P3i64vbjjjdVm@C6xoyR@GdZkict7Dggmx/I00P42Or7mCVQDk8fgA "Python 2 – Try It Online") Takes input as a list of lines and 0-index column, and returns a list of strings. Column is rotated up 1. -11 bytes, thanks to Jo King [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 9 [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 2D block of text, then *k* (0-based or 1-based, depending on APL's current setting), then *n*. Positive *n* rotate up, negative *n* rotate down. The domain consists of either one of the following: 1. all Unicode characters, *except spaces*, leaving 1114111 allowed values, which is more than the required 20. 2. all numbers, *except 0*, leaving approximately 2129 allowed values, which is more than the required 20. Since APL requires 2D blocks to be rectangular, the input must be padded with spaces/zeros. This can be done automatically by entering `↑` to the left of a list of strings/numerical lists. ``` ⎕⌽@≠@⎕⍢⍉⎕ ``` [Try it online!](https://tio.run/##jVBBTgMxDLznFZUA9RTUcuRUBC9AlTi7u2ETsSSRNy3wAdpKLRIH7hYf4AVc/JR8ZHEWhIATlmyNMjMZyxBbXT9AGxpt7pPxtan7vFnHPj@95N37LG9pVuD@Ne@3AgrZj4aKKj8@j8@YWucN051Lluk2oOBkwTPdMFUWEKpksDsejwZt8I3B/3m@LJ0NmD4d5eUyJEiitwbNKZMeaqW1UHPrOqbSJYbJ@LBsbDH9In1IP7krhBhd0QOGpa9llVDWkYxrh913tDqZKH6bKolTfy5wfiH/TKRhUck8ODwStZp@AA "APL (Dyalog Extended) – Try It Online") (the apparent spaces are actually non-breaking spaces) `⎕` prompt for text block `⍢⍉` while transposed:  `@⎕` apply the following on the input'th row:   `@≠` at elements different from their prototype (space for characters, zero for numbers):    `⎕⌽` rotate "input" steps left # [APL (Dyalog Unicode)](https://www.dyalog.com/), 22+ [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") This version allows the full character set by using zeros as identifiable fill element. ``` 0~¨⍨↓⍉⎕⌽@(0≠⊢)@⎕⍉↑0,¨⎕ ``` [Try it online!](https://tio.run/##hY/BSgMxEIbveYoBlVpwJfXoqaW9eBJE8Dxu4ya4TcJsqnjxuFqxRZHexVNvPoGXPkpeZJ2sCHvrkAxk/u@fn6Avs@kDlq5o4mp9dh7rNyni85Nv5ON2E5ebWH/E5YK1@PozPJRx8RlfvvrDNOBx/S6PGFutG/Y00JYXvRGUxiq4N0HDzJGCoNHCLeQaCfOgqDruQaKcLRTtgv/YSjsKLZreFy5gUKAVqVPI2rrLMhYutamAT1oNyrp5oRPfUawLHeGK0HvDLJKb2ykEx/kKbgxV/2niRIrt90Bwhuh8cTxhu@SL1zn3vf0DJsXgFw "APL (Dyalog Unicode) – Try It Online") This of course means that zeros are not allowed in numeric arguments. The corresponding program for all numbers would have the three occurrences of `0` replaced by `' '` and thus use space as fill: ``` ' '~¨⍨↓⍉⎕⌽@(' '≠⊢)@⎕⍉↑' ',¨⎕ ``` If we truly want the full ranges of (even a mixture of) both characters and numbers, we could use null as fill: ``` n~¨⍨↓⍉⎕⌽@(n≠⊢)@⎕⍉↑⎕,¨⍨n←⎕NULL ``` And finally, if we wanted to include nulls and objects in the input domain, we could define a fill class and use instances of this as fills: ``` ~∘I¨⍨↓⍉⎕⌽@(~⊢∊I←⎕INSTANCES⊢∘C)@⎕⍉↑⎕,¨⍨⎕NEW⎕FIX':Class C' ':EndClass' ``` [Answer] # [Zsh](https://www.zsh.org/), ~~94 87 78 74 69~~ 68 bytes ***-7 bytes** by changing to an arithmetic ternary, **-9 bytes** by changing the character in-place (TIL), **-4 bytes** by inputting the index on stdin and the strings as arguments, **-5 bytes** by using a string instead of an array to store the rotating characters, **-1 byte** thanks to @pxeger letting me know `${c[])` allows arithmetic ternary.* ``` read i for s;c+=$s[i] c=$c[-1]$c for s;s[i]=${c[$#s<i?0:++j]}&&<<<$s ``` ~~[Old](https://tio.run/##LU87bwIxDN7zKz7RCHMCJG5ggWPv1qVSB8QQEkNCcwlKDuiD/vZrDuHBsr6X7Z9s@8wd5l/iZp1nJFYG3gVew0TBV@Xx4OcYyQEe9W4ja5GtO3TiEBPyWk83E5m3blcJXSa9ndc7SF096clEvuTGVdV43DSNzPc7axtRHIuZK9JimE5PO/mbV9L99Zcw7HM4QUGL4qDNs0iYGLivC7EHEYyol6BXRqs@ORe0ZRWQlVeGQB@WE8NlfMdLwjEahHgreG6jfzxIQwa92Rk6q7pBqdAp7xGT4URiuQC9D0y4tPsCgIqkixFGtQHWHS2JumQMDefEmdOVgWHFWelyUCkS/w "Zsh – Try It Online") [Old](https://tio.run/##LY@9bgIxEIR7P8UosbRBgMQVNHAobbo0kVKgK4y9YIPPRvYB@VGe/WIjplit5lvN7v5kO2YeMP8SN@s8I7Ey8C7wGiYKviqPO5/jSVb7aXQb2Yhs3X4Q@5iQ13q6eZF567qJ0KXT23nTQerJA7O2EYUvZq6AguVWPufWvS5W0@mx6@RvXkn3N15CXeRwxAkKWrRtS5uHSJgYeGwK2IEIRjRL0BujVyfOxe1ZBWTllSHQp@XEcBnf8ZJwiAYh3oqf@@jvv1HNoHc7w2DVUCcVBuU9YjKcSCwXoI9KwqXfFQNURoYYYVQfYN3BkmhKRi04J86crgzUFWely0FFJP4B "Zsh – Try It Online") [Old](https://tio.run/##LY8xb8IwEIV3/4onanFFNBIZWCBR125dKnWIMpj4wAbHRnYAtX8@tStuOJ2@9/Tu7jeZWTyMdYzISsNZz3voIPiuHBJPqCosZMGL2bayFsnY4ySOISLth3X7KlNn@5UY8jR0Vd1DDqunXJQ2U9nJl9TY981uvT73/XLZNI1M882XfIszLlAYRKbUPouEDp7nOgsHEEGLegv6YIzqwinTkZVHUk5pAn0bjgyb8BNuEaeg4cMj8zQG9/8SlQz6NG@YjJqKU2FSziFEzZHEdgP6Koq/jYcMQNkyhQCtRg9jT4ZEnTNKwzVy4nhnoKy4qiEflIvEHw "Zsh – Try It Online") [Old](https://tio.run/##LY89b8MgEIZ3fsUrF@UapZHioUtjq2u3LpU6RB6IuQQSDBE4ST/U3@5ClBsAPc9xL/wkM12NdYzISsNZz2voIPiiHBKPWC5RyYIrYb3mr7aSdSWSsbtR/E63S1bsQkRa94v2UaaN7eaiz6d@s6w7yH5@18W0mcqNfEiNfV29LBaHrpvNmqaRafpD3nPWLaUSZ1/SLQ44QqEXWVJ7LxI6eJ7qLLYgghb1M@iNMagjp0wHVh5JOaUJ9Gk4MmzCdzhH7IOGD9fM0xDc7cNUZtC7ecJo1Fg6FUblHELUHEk8r0AfxfjzsM0AlFvGEKDV4GHs3pCo84yy4BQ5cbwwUCJOqs8PykXiHw "Zsh – Try It Online") [Old](https://tio.run/##LU5BbsIwELz7FaNgsSBAIodeSqL22FsvlXpAOZh4g90mNrIDtP08tQMry5qdnZ2dv2hu3WK5uAVWGlZ0PiDu2lUt4942oq1lu9@UjWwfk8xmTu7lLFb2Zfu8Wn01zXxeVZWMt6W4GtszJrfeOt5BewHwRfWIPGKzQSHzoEisdZp/6kKWuYnGdqNIYHbn4R3iqK1bT0YRKr1wPA/sxphkXTJ6LZDuJjBtZJfcUv0oEto7vpUAFA4gghblE@iNMajvbImBVTqjeqUJ9Gk4MGzErz8HHL2G89fEx8H3UwjKHvRu1hiNGrNSYVR9Dx80BxJPW9BHnrjzcEgEKElG76HV4GDs0ZBIaej@4xQ4crhwxhRPqk2RUpH4Bw "Zsh – Try It Online")~~ [Try it online!](https://tio.run/##LU7LbsIwELz7K0bBYkGARA69lETtsbdeKvWAOJh4g90mNrID9KF@e2oDK8uanZ2dnZ9oxnY2n42BlYYVrQ@Im2ZRy7i1O9HUstmuyp1s7pPM1vK32cpJrOzT@nGx@Nj9TadVVck4zsXF2I5xNeus4w20FwCfVYfIA1YrFDIPisRap/mrLmSZm2hsO4gEJjce3iEO2rrl1ShCpRcOp57dEJOsTUbPBdLdBK4b2SW3VN@LhPaOxxKAwh5E0KJ8AL0wevWZLdGzSmdUpzSB3g0Hho349qeAg9dw/pL42PvuGoKyB72aJQajhqxUGFTXwQfNgcTDGvSWJ@7U7xMBSpLBe2jVOxh7MCRSGrr9OAaOHM6cMcWjalKkVCT@AQ "Zsh – Try It Online") Here are the keys to making this answer work: * `$array[0]` or `$string[0]` is always empty * `$array[n]` or `$string[n]` is empty if n is larger than the length of the array/string * `array[i]=c` or `string[i]=c` will replace the element/character. * In `$[$#s<i?0:++j]`, `j` is *not* incremented if `$#s<i`. --- In the original 94 byte answer, there was an interesting issue I came across involving using `<<<` to print. I had to use `echo` to get around it: ``` for s;echo $s[0,i-1]$c[$[$#s<i?0:++j]]${s:$i} ``` The reason for this can be seen here: ``` echo $ZSH_SUBSHELL # prints 0 <<< $ZSH_SUBSHELL # prints 1 ``` Here-strings are run in subshells because they are given as stdin to another program. If there is no program given, it is implicitly given to `cat`. You can see this with `<<< $_`. `<<< $ZSH_SUBSHELL` is similar to `echo $ZSH_SUBSHELL | cat`. Since we need to increment `j`, we can't be in a subshell. [Answer] # Java 8, ~~107~~ ~~106~~ ~~135~~ 107 bytes ``` k->m->{int s=m.length,i=-1;for(char p=0,t;i<s;t=m[i%s][k],m[i%s][k]=p<1?t:p,p=t)for(;m[++i%s].length<=k;);} ``` +29 bytes for a bug-fix.. 0-indexed; rotates down like the example. Input as a character-matrix; modifies the char-matrix instead of returning a new one to save bytes. [Try it online.](https://tio.run/##7VbNi9pAFL/7VzxsFxOMQaHbUmMsZUuhh17WQg/iIcZRxySTkHlxWcS/3Z3RF51GI7sU2ovCM@P7/r0PM6tgHXRWs2gXxoGU8DPgYtMAkBggD2GlpG6BPHbnhQiRp8L9TofBD4FswXLnktJDKmSRsHwQLoN8PBlPhkOYg7@LOsOkM9xwgSD9xI2ZWODS4X6n583T3NLakPldBz0@kB76yZjfyck4mjjHk58Nel@wnzmZj7Y28pJxu62F5G7gR57tbXdeQ@HIimmscBCcdcpnkCiI1ghzLhbjCQS2hguATKIl2BOUGR/Y9Nm0vracFiiKFXFFQhEj3hPxUNGSeImiVFFu6JXygOw1L6JnaMhyeoZkw4gnFbmtrVOfWUqeF4bV/866PmNJ1mVErMn23MMjWSHFRCPfpRFbP/vE79TQ@niuRvlF3jjlCpVzteJAEQXxC@IvL2F4azBhQH5ToNZvozkZEa@kXTaw9KZlM2MA0sowlMWek69yPK@08JhW77Pt3XbutnO3nft3O/eJVk6/MPXbl/tdD/jgg/pqt21Sur6P5hQ9KPpWAa3l3Qs8DXO6n9Fz2TvFf6/ozkgVgL/y/2F0Nst1Uz819q5@b6vWubGBM7JILsYwWyePmqeW/bnjJ6z3e6TbxunGtb@i7IGXoIGLrEAHdNsiuq0cri8gWcbyANMcfGh2mm6ufgdofbynAo6eJbLETQt0M2WAsbCOJvUqzcdU5cJmEKZxkYg@RH6zHV3Rh2PkyG43183XR5@7QZbFz8rODcKQZWjtwRrDeqgCxFww6B9KUY7rBf96WA61sbSF/Vd1oN5sdy8) **Explanation:** ``` k->m->{ // Method with integer and char-matrix parameters and no return-type int s=m.length, // Amount of lines in the matrix `s` i=-1; // Index-integer `i`, starting at -1 for(char p=0, // Previous-character, starting at 0 t; // Temp-char, uninitialized i<s // Loop as long as `i` is smaller than `s`: ; // After every iteration: t=m[i%s][k], // Set the temp to the `k`th character of the `i`'th line m[i%s][k]= // Replace the `k`'th character of the `i`'th line with: p<1? // If `p` is still 0: t // Set it to the temp we just set : // Else: p, // Set it to the previous-character instead p=t) // And then replace `p` with the temp for the next iteration for(;m[++i // Increase `i` by 1 before every iteration with `++i`, %s].length // And continue this loop until the length of the `i`'th line <=k;);} // is smaller than or equal to the input `k` ``` [Answer] # [R](https://www.r-project.org/), 62 bytes ``` function(L,n){L[A,n]<-rep(L[A<-L[,n]!=' ',n],2)[1+1:sum(A)];L} ``` [Try it online!](https://tio.run/##hY2xbsMgEIZ3P8V1AlRsNRmTeMjOFFXq4HqgNg6o8WEd5yZS1Wd3cVRl7QkdcPru@2kZ4FAuw4wdh4jSaFTfpjlqbA8luUnm96E0Tf4/1QJEvvVWNZvnzS7Nozyqdm9@FpMdMEgDNZxcP3dO0kfAXiemNF0CyyHSaFneVqftTUCXpNLX0LOvR3uT2HlL8qaU0kLkhtm0fVH7vCcDBITNDilepVGqyx7TBN3q5KZaCC3eUajiCJdshWtgD2MkB@wtwiesYtuxo1StTMSzo//QlUw@Et/BqjhFtuzAO3I7KO/1VZbFqw8J8lml4DDOZ18VjylGfgzfyE5TyJSlOGMPHHOmgyFQ@stYfgE "R – Try It Online") Takes input as a space-padded matrix of characters. Rotates upwards. All thanks to [Kirill L.](https://codegolf.stackexchange.com/users/78274/kirill-l)! # [R](https://www.r-project.org/), 74 bytes ``` function(L,n){substr(L[A],n,n)=rep(substr(L[A<-nchar(L)>=n],n,n),2)[-1] L} ``` [Try it online!](https://tio.run/##hY2xbsJADIb3ewqPFykXQUcUkNgzISQGxHAEhzsBduRz2qHqs6eXgOhYy4P96dP/y9hB7cZuoFYjk21KKr7TcE4qtjluTyVlsBbs7R@sHbXB57PYrOlplB/F0S1PpvkZOyvoL00kTDbzRWG2cM8ffEUN8GBB0OAJbjCF@FZRUjU5TFeU/9TJTIFFZ7EyO1avCAEFV@Dm@XTO7ENMkHcKBSQerqEyb0qsb3gQ3/cxW154oAso506ELkp6dYy/ "R – Try It Online") This submission predates the allowance of padded lines. Aliasing `substr` here won't work because we're calling `substr` and `substr<-` in the first line. I/O as a list of non-padded lines; rotates upwards. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 82 bytes ``` k=>a=>{var c='0';a.Where(b=>b.Count>k&&((b[k],c)=(c,b[k])).c>0).ToList()[0][k]=c;} ``` [Try it online!](https://tio.run/##hVBNawIxEL3nVwwe3ATcYI/tmqVSKLT0VAUP1kNMoxtWE0nGj1L627dJbK23DkOYmTzevHkqlCqY7nFv1chYHIwVGmdHTy8m4M@rGunrGLAC0bWilqL@PEgPShTDopJ81miv6VLUS/7g9hbrtt@ndDlvFwPFBFWDVDLGVT1kfOoSJ2Xz4SJOhaq@uooE9Mau5wvYGKsDCLjvkXFu4Giwga3zGrCRFlpIaqRC7QNPGGfX2v8HTcjQOI8ZyMmrQ4kaku47KHMcypJMGxMgZiIFbd1@3XBymVqHl@HMy90uSgbp48XvgC7u1LAyPvzu6PGpN1vK@GS3MUiLN1uwipBsXNSVrszX8oneaIX0JGp65Tc7RavG3ssPythfWZEVvbllNFPEbuYNanr2jz87Y/OiQf6@Yrb6CGcQveaNUXXf "C# (Visual C# Interactive Compiler) – Try It Online") Credit to @ASCIIOnly for suggesting `foreach` which led to a 12 byte savings! -8 bytes thanks to @someone! -1 byte thanks to @EmbodimentofIgnorance! [Answer] # [Ruby](https://www.ruby-lang.org/), 57 bytes ``` ->a,k{b=a.map{|i|i[k]}-[p];c=-2;a.map{|i|i[k]&&=b[c+=1]}} ``` [Try it online!](https://tio.run/##hc0xa8MwEAXgXb/iJpPSSJBuTVDAkK4ZSqCDMeasypFwLYmT3FIS/3bXCiXQqcdNj4/3aGy/507OfI/r/tJKFAOGy9VebdXXE69CvVOSP@3@5EUh20o9yk09TTPKQ3kqxYd1Oma0KrbK@CE8sK7C9ea5ZmFMEZA1zcvx0DSshGzhyyYDgycNyaCDHpRBQpU0RZGNd2dN/9Eso/GUblCwV58waTCa9Bb47T45ZydjIyyfS0E7P56NYPfU@XQP3whDsItC8qN7h@SXTQ2dpfi7Mf8A "Ruby – Try It Online") Takes input as an array of lines `a`. Rotates the text down at 0-based position `k`. Returns by modifying the input `a`. [Answer] # [K4](https://kx.com/download), 22 ~~41~~ bytes ## New Rules: **Solution:** ``` {+@[+x;y;.q.rotate 1]} ``` If the input is already padded to the maximum length, then this becomes much shorter. ## Old Rules: **Solution:** ``` {.[x;i;:;.q.rotate[1;x . i:(&y<#:'x;y)]]} ``` **Explanation:** Not sure if I'm missing something... 0 index, rotates up (change the `1` to `-1` for rotate down) ``` {.[x;i;:;.q.rotate[1;x . i:(&y<#:'x;y)]]} / the solution { } / lambda taking implicit x and y .[x; ;:; ] / index apply assignment back into x .q.rotate[1; ] / left rotate 1 character ( ; ) / two item list y / index to rotate #:'x / count (#:) each (') input y< / index less than ? & / indexes where true i: / assign to variable w x . / index into x i / indexes we saved as i earlier ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ʒg‹}U¹εXyk©diX®<èIèIǝ ``` Can definitely be golfed some more.. 0-indexed; input and output both as a list of strings. It rotates down like the example, but `<` can be replaced with `>` to rotate up instead. [Try it online](https://tio.run/##yy9OTMpM/f//1KT0Rw07a0MP7Ty3NaIy@9DKlMyIQ@tsDq/wBKLjc//HHtr9P1rJUSEnMy9VoTyzJEMhN78oVaEkIzFPIVshOSOxKDG5JLWoWE9JRwGkLD8vPbWIkGqo4uKM/KISsFqwQFB@SWJJqkJGalGqlYIuGJTp6oJkQjIyixWACGS6Qmpefml6BlgHslxefgmyVHhRYkFBJlB5YlF@aV6KQkk@0BWpCmmZRcUwK2O5DC0B) (footer joins the list by newlines, remove it to see the actual list output). **Explanation:** ``` ʒ } # Filter the (implicit) input-list by: g # Where length of the current string ‹ # is larger than the (implicit) input-integer U # Pop and store this filtered list in variable `X` ¹ε # Map over the first input-list again: Xyk # Get the index of the current string in variable `X` © # Store it in the register (without popping) di # If the index is not -1, so the current string is present in variable `X` X®<è # Get the (index-1)'th string in variable `X` Iè # Get the character at the index of the input-integer Iǝ # And insert it at the index of the input-integer in the current string ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, 18 bytes 0-based with input & output as a multi-line string. Rotates up by 1. There's gotta be a shorter method! ``` yÈr\S_Y¦V?Z:°TgXrS ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=echyXFNfWaZWP1o6sFRnWHJT&input=IkEgbGluZSB3aXRoIG1vcmUgdGhhbiBrIGNoYXJhY3RlcnMuCkEgbG9uZ2VyIGxpbmUgd2l0aCBtb3JlIHRoYW4gayBjaGFyYWN0ZXIuCkEgc2hvcnQgbGluZS4KUm90YXRlIGhlcmU6IC0tLS0tLXYtLQpUaGlzIGlzIGxvbmcgZW5vdWdoLgoKVGhpcyBpcyBub3QgZW5vdWdoLgpXcmFwcGluZyBhcm91bmQgdG8gdGhlIGZpcnN0IGxpbmUuIgoxOQ) ``` yÈr\S_Y¦V?Z:°TgXrS :Implicit input of string U & integer V y :Transpose È :Pass each line X at 0-based index Y through the following function & transpose back r : Replace \S : RegEx /\S/g _ : Pass each match Z through the following function Y¦V : Test Y for inequality with V ?Z: : If true, return Z, else °T : Increment T (initially 0) g : Index into XrS : X with spaces removed ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` z⁷⁹ịỴFṙ-ṁƲY⁸ṛ⁹¦" ``` A dyadic Link accepting a list of lines (lists of characters containing no newline characters) on the left and an integer on the right which returns a list of lines. **[Try it online!](https://tio.run/##hY2xCsIwGIT3PsWPe4s4urn4ACJIx1B/m2hNyt9U0a2zTyDuuougoZuC75G@SEyLuHrcdPdxt8Qs2zm3b6p7UxlbH2x9G1tzDK2p3te4qR7WnHzzPPecr16X2LkRZEIibIXmsFaEoDmTsIKEM2KJRiqiwDNKpkj/0JYsuCLdgVEwUZppBI6EQwg7bcIwmHJRgHc7CihVmfIo@KVS6V84I5bnwlOMVCnnoJX/RFgIKr4fbtD/AA "Jelly – Try It Online")** (footer splits on newlines, calls the Link, and joins by newlines again) ### How? ``` z⁷⁹ịỴFṙ-ṁƲY⁸ṛ⁹¦" - Link: lines L; index I e.g. example in question; 20 z⁷ - transpose L with filler '\n' ['AAART\nTW', ' oh\nhr', ...] ⁹ị - Ith item 'am\nv.\n\nt' Ỵ - split at newlines ['am', 'v.', '', 't'] Ʋ - last four links as a monad - i.e. f(X): F - flatten 'amv.t' - - -1 ṙ - rotate left by 'tamv.' ṁ - mould like X ['ta', 'mv', '', '.'] Y - join with newlines 'ta\nmv\n\n.' - -- call this C ⁸ - chain's left argument, L " - zip with - i.e. [f(L1,C1), f(L2,C2), ...]: ¦ - sparse application... ⁹ - ...to indices: chain's right argument, I ṛ - ...of: right argument, Cn ``` [Answer] # perl 5 (`-p`), 75 bytes k is 0-indexed, rotate down ``` s/.*//;$r="^.{$&}";s/ //;/$r(.)/;$c=$1;s/$r\K.(?=(?s:.)*?$r(.)|)/$1||$c/gme ``` [TIO](https://tio.run/##Vc3BSsQwEAbge55iWIK0C03sQYq7lOJ5byJ4ESHUsQlukzCZXQ/WVze2dREd5vT/HzMR6XiTc9Jqq/VeUrt5Vh/y6nOzT1rMiZZUqHJu@lbWcybp6aCKri26tFPltlvrqdSynibZ62HEnOtbcQdH5xHeHVsYAyGwZQ9v0FtDpmekpBYT/ID0h5ofav7RRSYbiFeoxH1gwwgWCXdQrTNWlXiwLsG8y1FAH06DPYvf1Ae@hEo8konRzcpQOPkX4ADKIrw6SpcfXyGyCz7l6rppmvgN) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 38 33 bytes Modifies the array in place (rules don't disallow) ``` {@^a.grep(*>$^b+1)[*;$b].=rotate} ``` [Try it online!](https://tio.run/##hZHNTuswEIX3fopRiW6b0loXFiyIiuAJkK6QWMAtcpppY3DsMJ7wI8Szl7FTwZIokqXjMz/nc4/kzvbdOxSMbwwrmFyBsx7h1XILXSAEbo2HJ9i0hsyGkaJW4gl@h/SbNTljG4izUat/gQ0jtEh4Dsv8vSyX6qa1EeRPTQF9GHatVt@qD/wt3pLpeysuQ2HwDXCQmQhbS/EwY1IpdQQ3IsoWzqGsCXKG1wjbQNltfT9wKq3lCrrBsW1shz7a4I2T1mTeFxDDuI@JhyIv0eUS4cWQNbVDSN0luhJ8l7lK@GWOOvbO8mxy7yel7kw/@xiF6XRRPJT6Knk/D2cl615vtxE5hT1ZWt/gGzapaRFGfQWnf6sk/Kld2DzBav9xuTZ6R9jP5hfFuj4@Ke/mVVH/1yvKiD/3lRrNs3GzxaFXmfFcD5wQ5DfrCZmtk8TcJsg57Q@7JmD0UwbC58FSAhaZ0gsQRiGndJTYiew4J6ed68dgfVntvwA "Perl 6 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 52 bytes ``` k=>a=>a.filter(b=>b[k]&&([b[k],a]=[a,b[k]]))[0][k]=a ``` [Try it online!](https://tio.run/##hY/dasMwDIXv/RS6am1owna5BQf6CmOwiyxQNXViN6kVbLXr22dx@gO7mhDo6PBxhI54wdgEN3Lm6WCmVk@9LnHuvHUDmyD3utxXfb1aySrNDda6wk2StVLVSz0LjVMhLhgggoad2MLgvIEfxxZOFAywRQ89NBYDNnNmzBNDvjPhPzSR0VLgBczFBzGyAWuCeYdsqUuWiU/rIsydQsF4Onc2F0/XEz/Nr4Dj6GYKA539AZjmmwZaF@Ljxu72DOooAHIO7iRVUnEcHMv1t18v6wlHedXl9eGvVbIL0crXNyVR3VJY4x/4SM4/2PtyDyxEQz7SYPKBOsmqmH4B "JavaScript (Node.js) – Try It Online") -7 bytes thanks to Shaggy! Didn't see a JavaScript answer yet! Port of my C# answer. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~34~~ ~~28~~ 21 bytes ``` θJη⁰≔ΦKDLθ↓℅ιζUMζ§ζ⊖κ ``` [Try it online!](https://tio.run/##hY5Ba8MwDIXv/RWiJweSsR3XnsLCYGNjZRR2KD0YR4tNEimTlXb0z2dO2KC3GYElve/Zz3krjm03TTsJpOYr266ex37Ys/E53KapjDE0ZB5Dpyhmh9hWQdBpYDIvSI36ZMphU/GZ0v0mdSDbmZCl4ZL8r3Z44L63VJtLDqU@UY3fc1uhE@yRFGvTZlm2nabDYbUuoQuEcA7qoWdBUG8JWnApqXUpQ7xZ5wvG1KD8R//C0bPowi6Ld1arCB4FN1As51QUs7L3IUKq@XVA4rHxi@NaI9Zr6UPsMISEW@GRalBOKRA@g8S/L4853N0fp@LU/QA "Charcoal – Try It Online") Link is to verbose version of code. Takes an array of strings as input. 0-indexed. Edit: Now that `PeekDirection` has been fixed, I can manipulate it directly. Explanation: ``` θ ``` Print the input strings. ``` Jη⁰ ``` Jump to the top of the column to be rotated. ``` ≔ΦKDLθ↓℅ιζ ``` Extract the cells that have been printed in. ``` UMζ§ζ⊖κ ``` Replace each printed cell with the value of the previous cell (cyclically). Conveniently the cell values are read at the time of the `PeekDirection` call so the fact that the `MapCommand` call writes new values into the cells doesn't matter. [Answer] # [Pip](https://github.com/dloscutoff/pip) `-rn`, 32 bytes ``` POgY#(g@_)>aFI,#gFiyAE@ySsg@i@ag ``` 0-indexed, rotates down. [Try it online!](https://tio.run/##hc0xC8IwEAXgPb/iwEXBFBx1kHSw4KSoIE4S6pkcahIuqdJfH9siXT1ueny8FyjkvN@Zy2Rq1HW21tV2PjEVteVGtcdoFCltcl4sRQlPcggfShZenhGS1Q4eUFvNuk7IseiNdwb5H@1ltJ7TAAtx8EknBIuMK5DDvaUUJ0sRuu9LAZ1vjC3EmDqfxvDMOgTqlGbfuBsk320i3InjbyNLdl8 "Pip – Try It Online") Filters to find the indices of all rows that are long enough to participate in the rotation. Then loops over those rows, swapping the appropriate character on each row with a temp variable `s`. Visiting the first row again at the end swaps the dummy value back out again. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` ZnÄ×$ịḟ¹ṙ-;ɗɗʋ€⁹¦⁶Z ``` [Try it online!](https://tio.run/##hc0xCsJAEAXQPuewnSCWWnkFEUS7JY7Z1bgbJhtEu4hdDhCs7LSxFDGkS6p4i@QiayKSVpji83n8WaPn7Y1ZyOJUJL0qi6vXJU@r9AyjMimTd1wf73WU5tc6ei5MlT0ObShuc2PG4AmJsBOaw1YRguZMwgYczog5GimwrcYo6SL9o60MuCL9hbY1UZppBI6EQ2vKRQDNtVOAUoUut62ulUp35YyY74tGMVKhXIJWzSeElaDgt2wG/Q8 "Jelly – Try It Online") 1-indexed. Rotates down. A monadic link that takes a right-padded list of Jelly strings (a list of lists of characters) as the first argument and k as the second. Spaces are forbidden in the input except as right padding, but all other characters are permitted. As implemented on TIO, the footer splits a single string input into a list of strings and right-pads it, but this is for convenience; as I understand it, the result of that step is permitted input for the main link per the rules. [Answer] # [GFortran](https://en.wikipedia.org/wiki/GNU_Fortran), 182 bytes Requires user to input `k` and `n` on the first line, where `k` is the column to rotate, and `n` is the number of rows of text. Subsequent inputs are the lines of text to be rotated. This was a pain to write! Fortran is so pedantic! [Try it Online.](https://tio.run/##hZDBTsUgEEX3fMXsCqZtfK58JV3wC8bENbbTQlqHZuDp51d41rqUTGBy78lcYAqc2FIzTz/Nvg/Osh0SsrxeVW3XNQw22fcVu87ITuk//6K4joLRjg/1UpM@WJRGklJiDOD7S9YLUUmjqtpIrzT35ZBLtyjhJ8ktYVtBpZJD0qfVRx171kijn8o@BmFy4q@3sad0DC32vj89wrMwsHpC@PLJwUdghOQswQLnpWNbmEAz8n9oIaPL33IHW/ESUn4cOGTsoLmvz6YRr85HyFWGAlK4za4Vp0ohneIb223zmbIcbjRCCjkTYfIcj4xv) ``` character(99),allocatable::A(:);character(1)r,s read*,k,n;allocate(A(n)) do i=1,n;read'(A)',A(i);r=A(i)(k:k) if(r.ne.' ')then;A(i)(k:k)=s;s=r;endif;enddo A(1)(k:k)=s;print'(A)',A;end ``` Original, ungolfed program here, with comments and compilation notes: [rotcol.f](https://gist.github.com/roblogic/d1175fa16fb4540910cc389a1e5374e6) Saved 20B by reading from stdin rather than a file. Saved 14B by using implicit integers for `i k n`. Saved 4B by cleanup of spaces and `::`. Saved 17B by simplfying logic, and cutting i/o formatting guff. ~~[203 bytes](https://rextester.com/RBEE63006)~~ ~~[199 bytes](https://tio.run/##hZBBboQwDEX3OYV3JCOIOl11QCxyhapS1ykYEkEd5GTa49PAULpsZCXW/0927CFwYkvVODySde2cZdslZHm7qdLOc@hssh8z1rWRtWr@/KviMgpG28tLeVFTSc2BozSSlBJ9AN9es35AhTSqUEZ61XC7PXKqJyX8IFkT6qLQgfUjhUIlh9ScVBub2HKD1Pthu/sgTP7Cr7ewp7TXL81mr@vzE7wIA7MnhG@fHHwGRkjOEkxwThH1xgQakf9DNzK6vKcd1OI1pDwqOGSsodrPV1WJN@cj5NiKAlK4j06LU6WQTvGd7bL4TFkOd@ohhdwTYfAcjx4/)~~ [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 19 chars ``` {⍉¯1⌽@{' '≠⍵}@⍺⍉↑⍵} { ↑⍵} ⍝ from nested vector of char vectors to char matrix (padding=space) { ⍉ } ⍝ transpose { @⍺ } ⍝ apply on row ⍺ (left argument) { ¯1⌽@{' '≠⍵} } ⍝ rotation towards the right only elements that are note spaces {⍉ } ⍝ transpose back ``` [Try it online!](https://tio.run/##hZA9TsNAEIX7nOJ1roziKBVVuAJCol45Y@8KZ9caj/lRRBspEkZQ0HMDKhokGo6yFzG7NhFpkoy2Gb3vzZtZVVfp8kFVruz7AqH85gVr321/PjL/9L1YJ0j89t13n48L330FwW9eYzcRupeBTi5QGUu4M6KxckwQrSxukGvFKhfi5iwZKGdL4lPwyDbasQxo7C@dKCFoYjpHOtRtmgbhSpsG4cXRIOvaUkd@T7FO9oRrVnVtAqvYtXYJcSGfUBhudmkT//w23jUGgcfw2TRsnLuqXdm/Ff7R2RQF4occMiML8w@YkZ0wz48kz3fJff8L "APL (Dyalog Unicode) – Try It Online") [Answer] # T-SQL, 195 bytes ``` WITH C as(SELECT rank()over(order by i)r,sum(1)over()c,*FROM @t WHERE len(x)>=@)SELECT isnull(stuff(c.x,@,1,substring(e.x,@,1)),t.x)FROM @t t LEFT JOIN c ON t.i=c.i LEFT JOIN c e ON e.r%c.c+1=c.r ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1031912/rotate-a-column)** ungolfed version ]
[Question] [ Non-metals typically\* have a fixed number of covalent bonds in every chemical they are part of. Given the number of bonds every element requires, output whether it's possible to construct a *single* molecule from the given chemicals, such that every atom has it's desired number of bonds. In other words, output if it's possible to construct a connected undirected multigraph without self-loops so that each node has the number of edges equal to the corresponding number listed in the input. ## Test Cases Falsey: * `[1]` A single element has nothing to bond with * `[4]` Atoms can not bond with themselves * `[1, 1, 1, 1]` Each atom is saturated after single bond, so it's impossible to connect all 4 of them together. It can form 2 pairs but not a single molecule. * `[0, 0]` Two separate helium "molecules" * `[1, 3]` * `[2, 3]` * `[1, 1, 1, 1, 1, 3]` Truthy: * `[1, 1]` (Hydrogen Gas: H-H → `1-1`) * `[4, 2, 2]` (Carbon Dioxide: O=C=O → `2=4=2`) * `[3, 3]` (Nitrogen Gas: N≡N → `3≡3`) * `[2, 2, 2]` (Ozone\*: \$\newcommand{\tripow}[3]{ \_{#1}{\stackrel{#2}{\triangle}}\_{#3}} \tripow{O}{O}{O}\$ → \$\tripow{2}{2}{2}\$) * `[0]` (Helium: He → `0`) * `[3, 2, 1]` (Nitroxyl: O=N-H → `2=3-1`) * `[3, 3, 3, 3]` (Tetrazete: \$\begin{array}{ccccccc}N&-&N& &3&-&3\\\ ||& &||& → &||& &||\\\ N&-&N& &3&-&3\end{array}\$) * `[4, 1, 1, 1, 1, 2, 2, 2]` * `[4, 2, 2, 1, 1]` * `[3, 3, 2, 1, 1]` Here are the Falsey/Truthy test cases as two lists of lists: ``` [[1], [4], [1, 1, 1, 1], [0, 0], [1, 3], [2, 3], [1, 1, 1, 1, 1, 3]] [[1, 1], [4, 2, 2], [3, 3], [2, 2, 2], [0], [3, 2, 1], [3, 3, 3, 3], [4, 1, 1, 1, 1, 2, 2, 2], [4, 2, 2, 1, 1], [3, 3, 2, 1, 1]] ``` ## Clarifications * You may assume the input is non-empty and all values are positive or zero. * You may choose any 2 distinct values for truthy or falsy, or output truthy/falsy using your language's convention (swapping is allowed). See the tag wiki [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") \*I've been told real chemistry is a lot more complex than this, but you can ignore the complexities in this challenge. [Answer] # [Python 3](https://docs.python.org/3/), ~~61 60 59 58~~ 51 bytes ``` lambda x:len(x)-2<~sum(x)%2*all(x)*sum(x)/2>=max(x) ``` [Try it online!](https://tio.run/##bU/LDoMgEDzXr@DSKIamgpxM7bFf0Jv1sE01miAaH4le@usUFFNNGzbszjDDQDP1RS1DlccPJaB6vgCNkcikN@ITu7y7odLTkfkghB78BZ/ZNa5g1JNq2lL2nnsD0WVT5GInr1sEqJQoSWhKUMLNRgmyZVBAUGDZ0HRm@1c113rGjDyNnMOSBQTlHmDs2Oh7O/TFT7SN4rOdmTHc3ThTgeWZVRvJUta7fc7Gx1dEd8YNwQknoV6U7KBef36iPg "Python 3 – Try It Online") -1 thanks to @Kevin Cruijssen -7 thanks to @xnor Uses theorem 2 from [this paper](https://www.semanticscholar.org/paper/On-Realizability-of-a-Set-of-Integers-as-Degrees-of-Hakimi/83b1608fb33eef2467a53f6ccffed559df7408dc). It says a degree sequence is realizable as a connected multigraph with no self-loops if and only if it is `[0]`, or: 0. All degrees are positive. 1. The sum of the degree sequence is even. 2. The biggest degree is less than or equal to the sum of the rest of the degrees. That is, `sum(x)-max(x)>=max(x)`, or equivalently `sum(x)/2>=max(x)` 3. The number of edges, which is half the sum of degrees, is greater or equal to \$n-1\$, where \$n\$ is the number of vertices. `~sum(x)%2*all(x)*sum(x)/2` is equal to `sum(x)/2` is the first two conditions are satisfied, and `0` otherwise. If it is equal to `0`, it implies `len(x)-2<0>=max(x)`, so `len(x)==1, max(x)==0` and therefore `x==[0]`. Otherwise, if the first two conditions are satisfied, it tests the third condition with `sum(x)/2>=max(x)`, and the fourth with `len(x)-2<sum(x)/2` (which is equivalent to `len(x)-1<=sum(x)/2` since these are integers according to the second condition). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 134 bytes Thanks to all for the motivation to immerse in graph theory! It is wonderful that there is a numerical criterion for connected multigraph. But I was wondering how it worked. So I didn’t make a port of the same theorem, but I found *an algorithm* that allows you to build a multigraph, if it's possible, or give a message that you can’t. Having studied [this article](https://arxiv.org/abs/2009.03747). Here is the full-code version of Theorem 7 from the paper. It takes list of degrees and print out: * Render of graph and `True`, if it's possible to make connected multigraph * Graph and `False`, if only non-connected result is possible * `None`, if list of degrees is non-graphic ``` multiGraphFromDegrees[degrees_List] := Module[{n = Length@degrees, graph = Graph[{}]}, data = MapThread[{#1, #2} &, {degrees, Range@n}]; While[n > 1, data = ReverseSortBy[data, First]; data[[1, 1]] -= 1; data[[n, 1]] -= 1; graph = EdgeAdd[graph, UndirectedEdge[data[[1, 2]], data[[n, 2]]]]; data = Select[data, #[[1]] > 0 &]; n = Length@data; ]; If[n > 0, Print["None"], Row[{graph, " Connected: ", ConnectedGraphQ@graph}] ]]; ``` Example `[1, 1, 1, 1, 1, 3]`: [![enter image description here](https://i.stack.imgur.com/CZX5X.png)](https://i.stack.imgur.com/CZX5X.png) Example `[3, 3, 3, 3]`: [![enter image description here](https://i.stack.imgur.com/foOG6.jpg)](https://i.stack.imgur.com/foOG6.jpg) Example `[6, 6, 4]`: [![enter image description here](https://i.stack.imgur.com/BDxKM.jpg)](https://i.stack.imgur.com/BDxKM.jpg) Example `[5, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1]`: [![enter image description here](https://i.stack.imgur.com/9JFlc.jpg)](https://i.stack.imgur.com/9JFlc.jpg) Note, that algorithm makes *some example* of graph, if it's possible. So for `[3,3,3,3]` we have not Tetrazet, but other valid chemical. Also result *may be non-planar*, but it's OK for chemicals too. And here is short version, directly answers the question of challenge (`True` or `False`): ``` (d=#;n=Length@#;Catch[While[n>1,d=ReverseSort[d];d[[1]]-=1;d[[n]]-=1;d=Select[d,#>0&];m=Length@d;If[n-m==2,Throw[False],n=m]]];d=={})& ``` If anyone is interested, I’ll describe the algorithm a little more. [Try it online!](https://tio.run/##VYw9C8IwFAB3f4VQKAopmOoWXikIguAgVnAIbwjNsyk0KaRBh9LfXit@oHDDwcFZFQxZFepSjRWMCw2RcHAgVwWTR2KrQmnkxdQNSZdxpuFEN/IdFa0PUqPQUnLEBPjT3NugoIbKqbMoW8Uo7Geoxf4qXWIBUnY2vr3LnWo6QubAIk43gH5YxuPR1y7klew5m/@yHnD2bZv/lr4YcHwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [R](https://www.r-project.org), ~~58~~ ~~51~~ 45 bytes *Edit: -6 bytes thanks to pajonk* ``` \(x,`+`=sum)max(+x^0-1,x)<=all(x)*+x/2*!+x%%2 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3dWM0KnQStBNsi0tzNXMTKzS0K-IMdA11KjRtbBNzcjQqNLW0K_SNtBS1K1RVjaCafqRpGGpypWmYgIhkDUMdMNSE8Ax0DDRh4sZQlhGcBVWrg5Az0DHSMYKrMwLrTk4s0VDSRYCYPCW4dqhSEyRtxkgWIUQN4LJGcF1AlToI1SZwxyDrA5uM5CGQDigf4v8FCyA0AA) Based on [xnor's comment](https://codegolf.stackexchange.com/questions/259143/is-it-a-valid-chemical#comment571503_259154) on [Command master's Python answer](https://codegolf.stackexchange.com/a/259154/95126): upvote that! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Uses [S. L. Hakimi's result](https://www.semanticscholar.org/paper/On-Realizability-of-a-Set-of-Integers-as-Degrees-of-Hakimi/83b1608fb33eef2467a53f6ccffed559df7408dc) as aired by [Command Master](https://codegolf.stackexchange.com/users/92727/command-master) in their excellent [Python answer](https://codegolf.stackexchange.com/a/259154/53748). ``` ẠȧSH_L’»ṀƲeŻ$ ``` A monadic Link that accepts a list of non-negative integers and yields `1` if a molecule may be formed or `0` if not. **[Try it online!](https://tio.run/##y0rNyan8///hrgUnlgd7xPs8aph5aPfDnQ3HNqUe3a3y////aGMdBQSKBQA "Jelly – Try It Online")** ### How? ``` ẠȧSH_L’»ṀƲeŻ$ - Link: non-empty list of non-negative integers, D Ạ - all (D)? -> 0 if any of D are zero S - sum (D) ȧ - (all?) logical AND (sum) H - halve (that) - call this X Ʋ - last four links as a monad - f(D): L - length (D) ’ - decrement Ṁ - maximum (D) » - (length-1) maximum (maximum(D)) - call this Y _ - (X) subtract (Y) $ - last two links as a monad - f(Q=that) Ż - zero range (Q) -> list of integers = [0..floor(Q)] (empty if Q < 0) e - (Q) exists in (that)? ``` [Answer] # JavaScript (ES6), 67 bytes Based on the theorem [found by @CommandMaster](https://codegolf.stackexchange.com/a/259154/58563). Returns `1` for falsy or `0` for truthy. ``` a=>a.some(v=>!(s+=v,k++,m>v?v:m=v)&a>'0',m=k=s=0)|2*k>s+3|s<m*2|s%2 ``` [Try it online!](https://tio.run/##jU/BToUwELzzFfWgtI9KSuGktp70C7xVDhsEn0KpYZ9NTPh3BC2Bd3vJpLs7nelOP8EDVsPH1@m2d2/11KgJlIYUna2pV/qKYqI8b5OEW@0f/Z1Vnt2AjkXMrWoVKsFGeWg1JvmID/YgR7yWU@V6dF2ddu6dxuYZOvwpY3YfGWKykhNTLEfGScAyCU5EYPOlylA31R/yoJ2vZUnKKG3c8ATVkQJRmuz3NhQYm3dGZ2Fee/MyfJ@OW56wvwhvzm2@RVgpEXgZ1IvkH8G7z7jzFeuUnRlX4pIPTL8 "JavaScript (Node.js) – Try It Online") [Answer] # [Thunno](https://github.com/Thunno/Thunno) `D`, \$ 21 \log\_{256}(96) \approx \$ 17.29 bytes ``` XDS2%!>xS2/xMxL1-ZPpP ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSSi1LsgqWlJWm6FlsjXIKNVBXtKoKN9Ct8K3wMdaMCCgIgclAlC1ZGG-soGOkoGMZCBAA) or [verify all test cases](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abRSilLsEs_qVJelpSVpuhZbI1yCjVQV7SqCjfQrfCt8DHWjAgoCIHKLXaO8IawFN49GRxvG6ihEm4AIQx0FKALxDHQUDKCixiDaCEojVIGRcWwsV3Q0TJOJjgJQnRGIaYzQBxMygIobQVWDlEAQVC-ywUj6TGA8QxSNMIFYiG8A) Based on [Command Master's answer](https://codegolf.stackexchange.com/a/259154/114446). Somehow passes all the test cases. Outputs \$0\$ for falsy and \$1\$ for truthy. #### Explanation ``` XDS2%!>xS2/xMxL1-ZPpP # Implicit input XD # Store input in x for later S2%! # Sum is even? > # Is the input greater than this? xS2/ # Divide the sum by 2 xM # Push the maximum of x xL1- # Get the length and decrement ZP # Pair together pP # Sum / 2 greater than or equal to both? # Implicit output ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` OÉ›¦IO;IàIg<‚@«P ``` Port of [*@CommandMaster*'s Python answer](https://codegolf.stackexchange.com/a/259154/52210), so make sure to upvote him/her as well! [Try it online](https://tio.run/##yy9OTMpM/f/f/3Dno4Zdh5Z5@lt7Hl7gmW7zqGGWw6HVAf//R5vomOgYQ2AsAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLf//DnY8adh1aVulvXXl4QWW6zaOGWQ6HVgf81/kfHW0YqxNtAsSGOmAIZBnoGID5xkDSCExC5XQgYgY6RrE6CtEQxSY6RiButDFUOYRnABYxAqsAyuhAZE3gxsDUgXVDrQWpgrFNdEzAulB5IFNiAQ). **Explanation:** ``` O # Get the sum of the (implicit) input-list É # Pop and check whether it's odd (0 if even; 1 if odd) › # Check for each value in the (implicit) input-list whether it's larger # (so the sum is even and none are 0) ¦ # Remove the very first check (for edge-case input=[0]) IO # Push the sum of the input-list again ; # Halve it ‚ # Pair Ià # the maximum of the input-list Ig< # with the length-1 of the input-list @ # Check [sum/2>=max, sum/2>=length-1] « # Merge this pair to the earlier list of checks P # Check if all are truthy by taking the product # (after which the result is output implicitly) ``` [Answer] # [Arturo](https://arturo-lang.io), 52 bytes ``` $[a][s:∑a(0=s%2)∧(>=s/2max a)∧(-size a 2)<s/2] ``` Thanks to S. L. Hakimi for solving the problem back in 1962 and @CommandMaster for finding the solution and explaining the relevant bits so clearly. [![running the above code on the test cases](https://i.stack.imgur.com/iltwm.gif)](https://i.stack.imgur.com/iltwm.gif) [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 13 bytes ``` ∑2¦$ṁ±*$:#←c≥ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6FtsfdUw0OrRM5eHOxkMbtVSslB-1TUh-1Ll0SXFScjFUzYKbm6INY7miTYDYUEcBioAcAx0FA4iYMZAyglAIFWAEEwLp11EAqjECsozhOqACBhBBI4hCkDQEQXQhm4fQYwLjGCLrgvEhTgcA) A port of [@Command Master's Python answer](https://codegolf.stackexchange.com/a/259154/9288). The flag `-e` set the interpreter to `CheckExistence` mode, which prints `True` if the computation has any result, and `False` otherwise. ``` ∑2¦$ṁ±*$:#←c≥ ∑2¦ Divide the sum of the input by 2. Fail if the remainder is not zero. $ṁ±* Multiply it by the sign of the minimum element of the input. ≥ Check if the result is greater than or equal to all items of the following list: $:#←c Prepend the length minus 1 to the input ``` --- # [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 18 bytes ``` ʷ{P↕1:Ð-:C0=+?}0U= ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6FttOba8OeNQ21dDq8ARdK2cDW237WoNQ2yXFScnFUCULbqZFG8ZyRZsAsaGOAhQBOQY6CgYQMWMgZQShoHImOgpAASMgyxguDRUwgAgaQRSCpCEoFmIdAA) This is extremely slow and takes up a lot of memory. The idea is to repeatedly delete one edge at a time, until the result equals to `[0]`. ``` ʷ{P↕1:Ð-:C0=+?}0U= ʷ{ } Repeat the following function until it fails: P Fails unless the result is all positive. ↕ Non-deterministically permute the list. 1:Ð- Decrement the first two elements of the list. :C0=+? Drop the first element of the list if it is zero. 0U= Check if the result is equal to [0]. ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 17 bytes Based on [Command Master's answer](https://codegolf.stackexchange.com/users/92727/command-master) ``` ∑₂?sṫ$∑≤?∑½?L‹≥WA ``` ``` ∑₂?sṫ$∑≤?∑½?L‹≥WA ∑₂ Is the sum of the list even? ?sṫ$∑≤ Sort list, swap and sum tail-removed part, is lesser than or equal? ?∑½?L‹≥ Is length of list - 1 greater than or equal to half of the sum WA Wrap stack, all truthy? ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiJHigoI/c+G5qyTiiJHiiaQ/4oiRwr0/TOKAueKJpVdBIiwiIiwiWzMsIDMsIDIsIDEsIDFdIl0=) [Answer] # TI-Basic, 28 bytes ``` max(dim(Ans)-1,max(Ans))≤min(Ans>0).5sum(Ans)not(fPart(.5sum(Ans ``` Takes input in `Ans`. Uses the same method as in [Command Master's Python 3 answer](https://codegolf.stackexchange.com/a/259154). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 67 bytes ``` Length@x-2<BitNot[Tr@x]~Mod~2*If[AllTrue[x,#>0&],1,0]*Tr@x/2>=Max@x ``` [Try it online!](https://tio.run/##dVBda8MgFH3Pr7hksIfWMWPz1DYl26AwWMce@iYyZDOLkDaQOHCE9q9nagw1@5CLXs85V@@5B65KceBKvvG@oPqVLbP@SRw/VJnrG7K@l@q5VnTf5Jqdd/X7mcweC3pXVfvmU1CNrjb4mqEEYTazmluyyXZc57p/aeRR0XjLq1Z8LWO2igqXPvBWtJBB1yUnBF1qtwSBD3vDCLBHF/Yk/ryoXIwcsfLTKtrWDZXmYUNJWGcwmKDBr8ww8zmCobWAoFQyQ8YQIyh@EWZFkbdjXKtysKNcGtjx7aeuJWLTxaRLB2GPE6@2kiF8bWgxqEvHWzIpDACjSMfH/sLcH//PKbAznVNATOf0kzCr/wY) A port of [@Command Master's answer](https://codegolf.stackexchange.com/a/259154/9288). Explicit Mathematica Code is ``` f[x_List] := Module[{len, bitNotSumMod, allPositive, halfSum, maxVal}, len = Length[x] - 2; bitNotSumMod = BitNot[Total[x]] ~Mod~ 2; allPositive = If[AllTrue[x, # > 0 &], 1, 0]; halfSum = Total[x] / 2; maxVal = Max[x]; len < bitNotSumMod * allPositive * halfSum >= maxVal ] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` ¬∨﹪Σ貋∧⌊θΣθ⊗⌈⊞Oθ⊖Lθ ``` [Try it online!](https://tio.run/##LY3BCsIwDIZfxWOEeRFvngYeNzfwOHaoXbCFNnFpK759jbrwB374vhDrjFg2odZRPGW4coZBoOelBIZbibDum91Rt8OUoKUFek8@buAvaLlwuQdUaN4/OJbkhieKySywKkcrGJGyOh3SI7vv3TbnWqfppG8081wPr/AB "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a valid chemical, nothing if not. Explanation: Based on @CommandMaster's Python answer. ``` θ Input list Σ Sum ﹪ Modulo ² Literal integer `2` ∨ Logical Or θ Input list ⌊ Minimum ∧ Logical And θ Input list Σ Sum ‹ Is less than θ Input list L Length ⊖ Decremented ⊞O Appended to θ Input list ⌈ Maximum ⊗ Doubled ¬ Logical Not Implicitly print ``` * `len(x) - 2 < ~sum(x) % 2 * all(x) * sum(x) / 2 >= max(x)` becomes * `~sum(x) % 2 * all(x) * sum(x) / 2 >= max(*x, len(x) - 1)` becomes * `~sum(x) % 2 * all(x) * sum(x) >= 2 * max(*x, len(x) - 1)` becomes * `not(~sum(x) % 2 * all(x) * sum(x) < 2 * max(*x, len(x) - 1))` becomes * `not(sum(x) % 2 or all(x) * sum(x) < 2 * max(*x, len(x) - 1))` becomes * `not(sum(x) % 2 or (min(x) and sum(x)) < 2 * max(*x, len(x) - 1))`. ]
[Question] [ Write a program/function that takes two integers in the range \$0\$ to \$255\$ inclusive, and returns whether the binary forms of the numbers are exactly one bit different. For example, \$1\$ and \$0\$ have binary forms `00000001` and `00000000`, which are one bit apart. Similarly, \$152\$ and \$24\$ are `010011000` and `000011000`, so they return true. ***However***, your code must be **pristine**, such that if any one bit in your program is flipped, it should throw an error. For example, if your program was the single byte `a` (`01100001`), then all the 8 possible modified programs: ``` á ! A q i e c ` ``` must throw an error. Make sure you are modifying by *bytes* (e.g. the `á` up there is actually representing the byte \$225\$, not the actual two byte character `á`). ### Test cases: ``` 0,1 => Truthy 1,0 => Truthy 152,24 => Truthy 10,10 => Falsey 10,11 => Truthy 11,12 => Falsey 255,0 => Falsey ``` ## Rules: * Provide a testing framework that can verify that your program is properly pristine, since there will be a lot of possible programs (number of bytes\*8), or else a complete proof of pristineness. + *Please* make sure your program is valid before you post it. * Output needs to be either truthy/falsey (either way around is fine), or else two distinct non-error values * Errors can be runtime, compiler, interpreter etc. [Answer] # [Python 2](https://docs.python.org/2/), 35 bytes ``` lambda a,b:(a^b)&-(a^b)in[a^b or[]] ``` [Try it online!](https://tio.run/##fVHdbsIgGL3nKYgmAyya0szEkHSXewLvms7QFidLpYSypW7Zs3dgrc65jRv4zl8OYA5u1@ikL5tKppPJpK/FvqgEFLTgWDwV5G5@3JTO/AYbm@V573UZ43OWAyA7WWK0TVEUEggAxirt4BbHlBE4hWGlD3BtX93ucCYZjf8hlwlN7o/8L6TPPXk9@SjqVl6T7Ez@dDLKkr@cyXJJb2IHFoApXMvWqxoLPdI6pSUIt90USqcILV4apTH64PGq@EQLL9sLhxtb4ZKQYCqh0nB4njAWygXACv0scS01HrMI4QCOw2ZbK2NkBdMzlHFvzSMUM5SdsQClKYpRHn3HIsbzU9glaOxa7iz2N8Pj3BGaDFW70OxdGTzLlJMW37Qh@WxFCIDOHnxZeP39o8rzl3/05@GV0ZuoVcURtdKcki962ZXSOG5E2/Zf "Python 2 – Try It Online") Uses the power-of-two check `n&-n==n`, eliminating the `n==0` false positive. For reference, these are the pairs of one-char binary operators that are one bit apart, making them hard to use: ``` + / - / * + % - < | < > ``` Fortunately, `&` and `^` are not among these. Also note that `==` can become `<=`, and `+` can become the comment character `#`. --- # [Python 2](https://docs.python.org/2/), 41 bytes ``` lambda a,b:bin(a^b).count(`+True`)is+True ``` [Try it online!](https://tio.run/##fVFBbsIwELz7FRYcbBMXxVGRUKT02Bdwi1JwElNcBcdyTBVa9e2pTUiA0tYn78zsaHZXH@2uVlFX1KVIJpNJV/F9XnLIaR7nUmH@kpN5UR@UxZtgZQ5iQ2Rz@nROnbL4gWUAiFYUGG0TFHgfAoA2Ulm4xSFlBE6hf8kTdG12dxxJRsN/yEVEo8cT/wvpfM@9jnzmVSNuSTaSPzsZZdFfndFiQe9sexaAKVyJxqlqAx3SWKkE8NOu3ZoShOZvtVsX@ozDZf6F5k625xbXpsQFIb6pgFLBfj2@zKX1gOHqVeBKKDx4ERIDOBTrbSW1FiVMRih1d7FZgEKG0hHzUJKgEGXBNRawODubXYyGrMXOYDcZHuqW0KiP2vpkH1LjWSqtMPguDclmS0IAtObowsLb8w8qx1/u6P79ltE7r2QZI2qEPjtf9KIthLax5k3TfQM "Python 2 – Try It Online") Taking [TFeld's](https://codegolf.stackexchange.com/a/182836/20260) `lambda a,b:bin(a^b).count('1')==1` and making it pristine by changing the 1's to `+True` and `==` to `is`. Thanks to Jo King for 1 byte. [Answer] # [Python 2](https://docs.python.org/2/), ~~72~~ ~~67~~ 50 bytes ``` lambda a,b:sum(map(int,'{:b}'.format(a^b)))is+True ``` [Try it online!](https://tio.run/##fVHRToMwFH3vVzTbQ9tRF0pcspDgo1@wN4JLgeJqoDSlM0zjt2Mrgzmn8sQ9556T03P1yR5aFQ1FW4pksVgMNW/ykkNO87g7NrjhGktlKXqP8w@0rlrTcIv5U04IkV2wM0cxOFnK4juWASB6UWBUJSjwhgQAbZwaVjikjMAl9F/yAJ3MHk4zyWj4D7mJaHT/xf9COt@z1pGPvO7ENclm8qeSURb9pYw2G3pjO7IALOFOdG6rNdAhnZVKAP/afS5VgtD6pZUKu77C7bfGWlPighAvKqBUcKzHj7m0HjBcPQtcC4UnL0JiAKdhX9VSa1HCZIbS2EmzAIUMpTPmoSRBIcqC71jA4uxsdjGashYH42@Mp7knNBqj9j7Zm9R4lUorDL5JQ7LVlhAArTm5sPD6/NOW4y93dP9jy@iV17KMETVCn50v@6IvhLax5l03fAI "Python 2 – Try It Online") -5 bytes, thanks to Jo King --- Returns `True`/`False` for for truthy/falsey. The program is basically the same as `lambda a,b:bin(a^b).count('1')==1`, but without numbers and other chars which work when bit-flipped. Works by making sure that almost everything is a named function (which are all quite pristine) The pristine test at the end flips a single bit (for every bit), and tries the function on an input. If that works (correct or not), that variation is printed. No printed programs = pristine function. [Answer] # Java 8, ~~68~~ ~~61~~ ~~56~~ 45 bytes ``` a->b->(a.bitCount(a^b)+"").equals(-~(a^a)+"") ``` -11 bytes thanks to *@EmbodimentOfIgnorance*, replacing [constant](https://docs.oracle.com/javase/8/docs/api/constant-values.html#org.w3c) `java.awt.Font.BOLD` with `-~(a^a)`. [Try it online.](https://tio.run/##lY8xa8MwEIV3/4ojk0RrEZt6SuKhgUCGThlLC2dHNnIVybFOgVDSv@6qxU2hS5Xt8d538F2HJ0y7/dtYa3QOnlCZ9wTAEZKqoQur8KS0aLypSVkjNlNYbg3JVg73cdCjtVqiKUtoYDViWlZpyVBUitbWG2L4WvG72YwLefSoHUs/QoXf1bhIglHvKx2MJrGTVXs4BFm2o0GZ9vkFcGgd/3IH2J0dyYOwnkQfVtKGNQL7Xp/ZnE8h43zxH5zx61UEXOQ/eP4Qw/@qzG/Do9Sv7lkegedF8efXS3IZPwE) **Explanation:** The shortest base function would be: ``` a->b->a.bitCount(a^b)==1 ``` [Try it online.](https://tio.run/##lY9Bi4MwEIXv/oo5GliDynpq9dCFhR568rhsYbQqsWkiZlKQpb/dTcG20EvT24P3De@bHs8Y9YfjXEs0BnYo1F8AYAhJ1NC7llsSkrdW1SS04t9LWG8VNV0zfvhBG61lg6oooIV8xqioogJ5JehLW0Uh7iuW58m8Ctz4YCvpxheHsxYHODmvsKRRqO7nF3DsDLtqApSToebEtSU@uJakCluOwyCnMGZLSBhbvYITdr/ygLP0hqefPvxDJX4P91K/uyepB55m2dOvl@Ay/wM) This is modified so there isn't a digit, `=`, nor one of the `+/*` operands in it for numeric calculations (so the `+` for String-concatenation is fine): The `+""` and `.equals` are to compare by `String.equals(String)` instead of `int==int`. NOTE: `Integer.equals(int)` could be used here, but would be more bytes, since both the `.bitCount` and `java.awt.Font.BOLD` are primitive `int` instead of `Integer`-objects, so an additional `new Integer(...)` would be required to transform one of the two to an `Integer`-object, before we could use the `.equals`. [Answer] # [C (gcc)](https://gcc.gnu.org/), 56 bytes ``` d(a,b){return(sizeof((char)d))^__builtin_popcount(a^b);} ``` [Try it online!](https://tio.run/##bZDBDoIwDIbvPEWPnWIiJnqZPIkRMsbQJTrI3Iwb4dlxSFCM9tC06ff/TctXJ877vkQWF6TVwlit8Ca9qCtEfmaalIRkeV5YeTFS5U3d8NoqgywrCO16qQxcmVQ4FEyfeAyDChahvh@OBNoIQgxTF3v6aqpaA3pIYU3Bwx422x2F5dJP8JtxI@M@jJszk7EWN3sxgS3Rx47QH8Aq8WgEN6IMEP45xmfBOE0hCeJvdQU42aczH/JFDTG@DpLP9i4aczQbr2nU9U8 "C (gcc) – Try It Online") Returns `0` if the pair differ by 1, non-zero otherwise. Slightly unusual for C, unless you consider it returning `EXIT_SUCCESS` if the pair differ by 1, any other value otherwise. Uses `sizeof((char)d))` to produce the constant `1` in a pristine way while also forcing the function name to be pristine. It then XORs that 1 with the popcount of the XOR of the arguments. Luckily the `^` symbol is easy to keep pristine, as is the very long identifier `__builtin_popcount`. Meanwhile, here is the script used to test the solution: ``` #!/bin/bash SOURCE_FILE=$1 FOOT_FILE=$2 TMP_SRC=temp.c LENGTH="$(wc -c <"$SOURCE_FILE")" BITS=$((LENGTH*8)) cat "$SOURCE_FILE" >"$TMP_SRC" cat "$FOOT_FILE" >>"$TMP_SRC" if gcc -w $TMP_SRC -o t.out >/dev/null 2>&1; then if ./t.out; then echo "Candidate solution..." else echo "Doesn't even work normally..." exit fi else echo "Doesn't even compile..." exit fi for i in $(seq 1 $BITS); do ./flipbit "$i" <"$SOURCE_FILE" >"$TMP_SRC" cat "$FOOT_FILE" >>"$TMP_SRC" if gcc -w $TMP_SRC -o t.out >/dev/null 2>&1; then echo "Testing flipped bit $i:" cat "$TMP_SRC" ./t.out >/dev/null 2>&1 STATUS=$? if [ "$STATUS" -eq 0 ]; then echo "It works!" exit elif [ "$STATUS" -eq 1 ]; then echo "It doesn't work..." exit else echo "It crashes" fi fi done ``` Which uses the `./flipbit` tool I wrote whose source is simply: ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int bittoflip = atoi(argv[1]) - 1; int ch; while ((ch = fgetc(stdin)) != EOF) { if (bittoflip < 8 && bittoflip >= 0) { putchar(ch ^ (1 << bittoflip)); } else { putchar(ch); } bittoflip -= 8; } return 0; } ``` The tricky bits were: * Whitespace: All whitespace (including newlines) have pristine twins that will work similarly * Comparison: `=` doesn't work well, since it can be a comparison in every case it could appear. Similarly `-` doesn't work well. Thus `^` is used to assert equality with 1. * Variable names: f would clash with b, so had to use d as the function name instead. [Answer] # [R](https://www.r-project.org/), ~~38~~ 37 bytes -1 byte thanks to Nick Kennedy. ``` dpois(log2(bitwXor(scan(),scan())),T) ``` [Try it online!](https://tio.run/##VYtBCsMgFET3/xQu/dSKSqWbHiOLQsiiTbEIQUu01BBydqsGCl29YebNnA25HIl5uzFa7yjnHFdItROwVEw2xFZDGG/uT8a1iKVI5EAkLH2fhmHLj5e3gU7@qejdxs/Vz7Q@KbIdiKzDvIGhghGJhZIR0agVU6eW6iR@abeKJlVNSuv6yIUg1Rm@ "R – Try It Online") (Thanks to Giuseppe for setting up the TIO properly.) [Proof that it is pristine](https://tio.run/##XZDRSsQwEEXf@xVDQZhAd9HCsiDrkx8gSB98ECVts9usMamZqe2y@O110kUUoZBm7p0zNxPneYLdCvK2D5bQhUOJteXxKUSkRntUxeVQqqhUnqVL8u8H37ANItyU26wPRKlKuu/dCcl8vDrj0TedjjhJ66/fqh/X9e32T/2o4JwBRLOAOJ7wTENNLP0FWPlUqkc9VuF@oUrAhK/Cox7xn1UGalqLGUt4gaOEF7T51A57Hckgm4nhDiRZ9pUk6zsTLRPK@AJymb4yMYaYJ11ljWakPlrPe8wfBoawh6sW0qttbZ1lK6mbzjRvpi2SIpjBsWBBtrWQ1s8@L0CWcuAOU6NEpOH98qvUXG42IJucvwE "R – Try It Online") (using [Nick Kennedy's checker](https://codegolf.stackexchange.com/a/182883/86301)). Outputs 0 for falsey, and a positive value for truthy, which I understand [is acceptable](https://codegolf.meta.stackexchange.com/a/2194/86301) since R will interpret these as False and True. Explanation: `bitwXor(a,b)` gives (as an integer) the bitwise XOR between `a` and `b`. To check whether it is a power of 2, check whether its log in base 2 is an integer. The function `dpois` gives the probability density function of the Poisson distribution: its value is 0 for non-integer values, and something positive for non-negative integers. The `T` is there because `dpois` requires a second argument (any positive real works, and `T` is interpreted as 1). If we insist on outputting to distinct values, the following version outputs FALSE or TRUE in 42 bytes (thanks to Giuseppe for -8 bytes): ``` dpois(log2(bitwXor(scan(),scan())),T)%in%F ``` and [is also pristine](https://tio.run/##XVDfS8MwEH7vX3EUBhfohhbGQOaT4KsgffBBlKxL15s1qbmr6xj@7fWyIYoQSPh@3ZeL0zTCeg75tg/E2IVdiRuSw1OIyLX1aIrLZUxRmRn52X2eJSSZmsHXQkHZ63KV9YE5oWz7vjsiu4/Xznn0dWsjjur/1ZP5UV3drP7gewOnDCC6c5DEI5542LCovwDSYxIe7aEKd@dUbZniq/BoD/hPqgMtL1SMJbzAXn@g0e7TdtjbyA7FjQK3oM2yr0SRb10kYdTxBeQ6fe5iDDFPvMlqK8h9JC8N5g@DQGhgtoX0a9pQR0Laum5d/ea2RWI0ZuhEY0G3dU5aPPu8AF3KTlpMRq3Iw/vlacxULpegm5y@AQ). [Try it online!](https://tio.run/##VYtBCsIwFET3/xTZFPIxhiQY3Lj2BC6E0oVWIoGSSBsxpfTsMUlBcPWGmTdjMuS0J@bt@mC9o5xzXCCWTsBcMNgp1Bqm/ub@ZFyymItIdkTC3Lax69b0eHk70cE/Fb3b8Ln6kZYnRbYBkV2wsa45pxUMFYxIzJSMiEqtmDrUVCbxS5uVNalKUlqXR8oEqY7wBQ "R – Try It Online") [Answer] # [R](https://www.r-project.org/), 83 bytes ``` t(identical(sum(.<-as.double(intToBits(Reduce(bitwXor,scan())))),sum(T^el(.[-T])))) ``` [Try it online!](https://tio.run/##K/r/v0QjMyU1ryQzOTFHo7g0V0PPRjexWC8lvzQpJ1UjM68kJN8ps6RYIyg1pTQ5VSMps6Q8Ir9Ipzg5MU9DEwR0QJpC4lJzNPSidUNiQUL/DY3MFYxMTf8DAA "R – Try It Online") [Proof that this is pristine](https://tio.run/##XZBhS8MwEIa/91ccBeECbdHBGMj8oj9AGP0gqJM0vdnMmtTk6jaGv71eCqIY8iHc@96TuzdM0xHWJeSMtiXH1uge4/iO1brUsWr92PSE1nHtby1H3FA7GsLG8uHBhyIa7VClU6Smeks9Vo9l/ZxKeZbkRN@NzrD1YjW4WC6Lq8VKZYOPMYlRD0N/wkgfLz05dKbTAY9C/G2z6sd1eb36U98rOGcAgWYQhxOe49hElv4CrFyV6kEfan83U33AhK/9Rh/wn1U@lI3FjAvYwl4WEDR9Sh6DDpGQ6chwAzJZ9pUk6zoKKRP5vpAAw6mkEHzIk64yoxnjECS6Heb3I4PfwUULaWvb2N6ylalNR@aN2iIpghl7FixIaDOpenJ5ARLKK3eYGmXEFPP8VGqSKEGinL4B "R – Try It Online") Working around the fact that `as.integer`, `as.double` etc. are only a bit away from `is.integer`, `is.double` etc. was the hardest bit. In the end, using `sum(T^el(.[-T])` as a way of both generating a one and checking that `as.double` has returned a >1 length vector was the best I could do. The wrapping `t` is to handle the fact that otherwise `identical` can become `ide~tical`. [Answer] # [Julia 0.7](http://julialang.org/), 20 bytes ``` (a,b)->ispow2(a⊻b) ``` [Try it online!](https://tio.run/##yyrNyUw0/59m@18jUSdJU9cus7ggv9xII/FR1@4kzf8FRZl5JTl5GmkaBjqGCiCgqamsEFJUWpJRyYWQNNQxwCNpaqRjZIJLEmiuAVSnW2JOcSq6pCFOYw11DI1w6TQyNdVBNfY/AA "Julia 0.7 – Try It Online") Here is a [pristine validator](https://tio.run/##bdY9ThtBAIbhFlapOACyR0HMmFmwbIk/YRB0qUCiSJNix8ssHnu9rGfX2BYSSKkiInEAuAGUqRIK7mIkCi7hGOq3/J7vAm93mDqzNZslslCt0k@CSsVemlTmxhdWCilqRU0oWdd1JZSav6Uf2iA2ZdyZj8SkhQ1sdhaMW96MhBBBx@i2CvddkV@MGtJMb5/bKlgg3CasEGrCGqEilFXCQ8IBoSO0hDFhRGhSwi@Ee4RfCSXhOmFIqAXhEaEn7BImhBFhTNh2hIuEO4RVwpBwjVASqj5hQNgiXCFUhBuEmjC8JlwmXCfcJNwl3CM8INxXhN8IJ4SGsE/YI@wQuibhKWFMeEU4IhwQesKiTnhCGBGOCUtCTzggzDcIjwlvCM8Je4R9wozwYovwO@E54Q1hQTgkvCQcecIlQkG4S7hJWCdsEjY6hAuE24QVQk1YI1SEskp4SDggdISWMCaMCM074RvhK@H0kfCe8CfhHeEvwt@Etw@ET4R/CF8I/xL@I3wWhEeEnrBLmBBGhDFh2xEuEu4QVglDwjVCGXwUcO5dVkqTTWSiizx1pRzr1R/Zqu5Zm9t@Xk5an92slJrN/gM) that tries running each modified anonymous function against some input, and neither passes successfully. Note that the code has a multi-byte unicode character, and some possible outputs from bit flipping are not even included, as those produce invalid UTF-8 strings. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 37 bytes ``` a=>b=>a!=b&((a^b)&-(a^b)).Equals(a^b) ``` The `a=>b=>` part cannot be changed, or else the function is invalid. In `a!=b`, the `=` cannot be changed since `int` cannot be converted to `bool`. [Try it online!](https://tio.run/##bc89C4MwEAbgvb/CLpKDWHKHmdpkq1PHQrdCIkoDotSPob8@jQqFaLMk93DvHSmHrBycL6a2vLh25L@H7bpG61p5o7RV2hyVTRkzTwtptlxwur4n0wxL4c@HR@/G6ubaitVMAEOA2BACb00SMMp3POfFX92PDXORtkpSruu84JjMR@nk3k/j63NALrYiiVMeSYiJtacIf6xWwTiFHCnqCVt5lPoC "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~128~~ ~~101~~ ~~77~~ ~~70~~ ~~61~~ 74 bytes *-27 bytes thanks to [Ascii-Only](https://codegolf.stackexchange.com/users/39244/ascii-only)* ``` a=>b=>{var d=Math.Log(a^b,(int)Math.E);return d.Equals((int)Math.Abs(d));} ``` [Try it online!](https://tio.run/##bc49C8IwEAbg3V/R8Q6qtMFONQGHOtXZTchHq4GaYpIKIv72GOsgto733Mt7J91SOh12g5EbdTf8omU6Dtr4VPR9x1jS0sApE5Q9btwmiu65P6/q/gT8KFKIQRylwtI2frAmUavqOvDOwXe5FQ4UYvkM5eJgtW9qbRpoIUfIIv9YhpEnlhcEgaxn/M5mf3VeEW/lZKqkKD4vhBc "C# (Visual C# Interactive Compiler) – Try It Online") You have to be quite creative to get numbers in C# without using literals. Only uses ^ operator. Variables a,b are all more than 1 bit away from each other and everything else is a keyword/name. [Answer] # JavaScript (ES6 in strict mode), 61 bytes ``` (y,z,e)=>eval(`(y${(e='^=z)*!(y&~-y)')!='^=z)*!(y&~-y)'||e}`) ``` [Try it online!](https://tio.run/##fY7RCoIwGEbvfYpfiLaFppN2FXbZE3Qdiv2WMVy4KcysVzcvgkJqtx@H851r3uW6aKqbCWt1wpG0GkGbpioM2XoSDZTpSG3QB8jSHXa5pBm1izvFlBzTnq18apfP0DLC/PkyDPjI2FioWiuJa6nOtKQAcQDAGYMogkPTmov15gSfiNhBcJEEkGxcDj698Ldjn0uNvwlnB586eOJwJEJ8Sv@8TKUgvonxBQ "JavaScript (Node.js) – Try It Online") or [Make sure that all modified programs are wrong](https://tio.run/##dZHdbuIwEIXveYohqtZ2Sa2CdqWqga4Quxd7V4lLREXqDpCK2NQxYQNNX52O89OllVaRovGcyTfHJ89xHmfKJlt3pc0TnvIURmDxZZdY5CxPmYhOigTqBrwIDyGK0R3m8YYveHFx5DhiD6ODuOzy4tvbVSGY6H7tvL5iuRBB1OksjeVbZ4l1HYEvhuDZcoN65dZVq9cTcOwA@NHHxNWjvhjCTVW0AwAa95Pa2UxK6UHz6FyYEW5O6tTZRK/k0pp0so6tl/j5iFRNd@y4gAfow3DoN4mallWGmw/ks0k0Z6zRtnGWkTioT84WjTXyv9OKlCqpgO0y9JxEORYF0PN1Q/hg9Ntznkq703/0xGiHfx1f/B91caSqDERUreP9H4MQBt/FIvQQZTF22FKOpWg2ltVbxU6tOVKWAM1iZXRmNvQ3zIoTNwReW6P7wU9gs21sMwoS0Fpj5wxuqUdOXZJi2xN0N0ZPD1A6UwfPxderXp8bSZbVGvGR3LmN4H48nf7@FYSfEnNra/bQav9gZac8nd4B) [Answer] # [Groovy](http://groovy-lang.org/), ~~47~~ 36 bytes ``` a,b->a.bitCount(a^b).equals(-~(a^a)) ``` [Try it online!](https://tio.run/##Sy/Kzy@r/J9mW/0/USdJ1y5RLymzxDm/NK9EIzEuSVMvtbA0MadYQ7cOyE3U1Pxfy8VVUJSZV5KTp5CmYaBjqInENdQxQOGaGukYmaCIADUYoAugGmGoY2iELGBkago09T8A "Groovy – Try It Online") Adapted version of [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s Java answer. [Answer] # MATLAB, 37 bytes ``` @(c,e)eq(nnz(de2bi(bitxor(c,e))),eye) ``` Sorry, no TIO link, because I can't get the test suite to work under Octave. Thanks @ExpiredData for some helpful comments. Test suite: ``` program = '@(c,e)eq(nnz(de2bi(bitxor(c,e))),eye)'; number_of_characters = nnz(program); success = []; for character_counter = 0 : number_of_characters for bit_no = 1:8 prog_temp = program; if(character_counter > 0) prog_temp(character_counter) = bitxor(double(prog_temp(character_counter)),2^(bit_no-1)); elseif(bit_no<8) % Test the unmodified program once continue end try eval(prog_temp); eval('ans(2,3)'); disp(prog_temp) success(end+1)=1; catch success(end+1)=0; end end end assert(nnz(success)==1) ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~77~~ 43 bytes *Thanks to Jo King for -33 bytes.* ``` {elems(i)eq(sum [+^](@_).polymod(+@_ xx*))} ``` This is equivalent to ``` {1 eq(sum [+^](@_).polymod(2 xx*))} ``` `1` was rewritten as `elems([""])`. `2` was rewritten as `sum(elems([""]),elems([""]))`; `elems(["",""])` might seem to work but `elems([""-""])` is also valid and seems to hang the tester. [Try it online!](https://tio.run/##VVDRSsMwFH3uvuJSwmztWtrhFOw6OkZBULcHRZC5jeo6rWvsTDJYKf0W2V/4AfsRv6TepPNBktzk3Jx7Tm42CcvO6y1P4HYyvo4e7bsosscTO3oY3vgtWgDhEMBJXSZZQrmRmsmnwbcUptZ8ZoQL09nkWUHzpWGFC9jtTk2zqk8cwVKqqts/319YL9VAR/zUPuwDwn25635rlTPou@DhwNjrQvcMPPdvempistcDdwD2AEjcAfIMZUvjcQH6EQYDKNHHaKBZoXClnh6jtaveEa7xSLiTsyVvbOeYkoqpVFOJC4XfJdZkCcWScO0jCumUpDOw5gEYHlh9ZJl@wyJCsqjz8sa4TAlWKAHtX8vSXPiHveF2oGvqkth0MM4hYQzdVyynl0hq7iyLxOowGt6PrhpBbZms4m0moKwklAFXha0e/wJELuIMNjHn6ccrCtW/ "Perl 6 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 20 bytes ``` b=>d=>[i=d^b][i--&i] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@TWqKQZvs/ydYuxdYuOtM2JS4pNjpTV1ctM/Z/cn5ecX5Oql5OfrpGmoaCgoGmhoKhpqaCvr5CSFFpSUYlF7oKQ6AKAzwqDE2NNDWMTPCZYQi0xRBqhltiTnEqdhV43QGU1TA0wmOGkakpwqU4bAG6VMEUWcV/AA "JavaScript (Node.js) – Try It Online") [validator by Arnauld, modified (not use strict)](https://tio.run/##XVBda8IwFH33V1zKWBOqQWWDsapD3B72NvCxVIw1asQmLo3dhvS3dzf9cGUUSnLPxz05R57zLDHybAdKb0WZpzAFIz4v0gji56lPwzJBAKfeZjrbTmeRnG5XmziSg8G9jL2w19tpQ87WIGUYgjtMwEnYSai9PVSjIKBw7QE46kbamuoOE3iqDi0BQImvRb0wYow5ozjsAhHaxYgurZFqz3ZGp4sDNw4iXQpLmuncEgorGMFk4jbR2i2rAjcCdtRSEd9vsDPPMgTH9c2anyYa5r@oBBGR8xNBh4Z/U4zae54yc1HvaqGVFd@WrLtC7@6K2sKjYeVHRo9jSsYPdN13usQIbkUrvBa0WVJU/4Tb5EAElgXQ7Eq0yvQJ69Z7l6kPpE6DD4AX8KMzNxk2BcIYbWIfnnGG4axMRTujEICPXwCCWV03S@j/1w27QeSuWkNv1XRjeB/z5fLt1etDtyR7MPoLWuzPrOgVZfkL) ]
[Question] [ A positive integer N is *K*-sparse if there are at least *K* 0s between any two consecutive 1s in its binary representation. So, the number 1010101 is 1-sparse whereas 101101 is not. Your task is to find the next 1-sparse number for the given input number. For example, if the input is 12 (`0b1100`) output should be 16 (`0b10000`) and if the input is 18 (`0b10010`) output should be 20 (`0b10100`). Smallest program or function (in bytes) wins! [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) disallowed. [Answer] # Pyth, 9 bytes * Borrowing the [`x & (x*2) != 0` algorithm](https://codegolf.stackexchange.com/a/48374/11259) from @alephalpha * Borrowing [Pyth boilerplate](https://codegolf.stackexchange.com/a/48357/11259) from @Jakube My first attempt at Pyth: ``` f!.&TyThQ ``` [Try it here](https://pyth.herokuapp.com/?code=f!.%26TyThQ&input=18&debug=0) ``` implicit: Q = input() f hQ find the first integer T >= Q + 1, that satisfies the condition: !.&TyT T & (T * 2) is 0 ``` [Answer] # CJam, ~~14~~ 11 bytes 3 bytes saved thanks to DigitalTrauma. ``` l~{)___+&}g ``` [Test it here.](http://cjam.aditsu.net/#code=l~%7B)___%2B%26%7Dg&input=12) ## Explanation ``` l~ "Read and eval input."; { }g "Do while..."; )_ "Increment and duplicate (call this x)."; __+ "Get two more copies and add them to get x and 2x on the stack."; & "Take their bitwise AND. This is non-zero is as long as x's base-2 representation contains '11'."; ``` This leaves the last number on the stack which is printed automatically at the end of the program. [Answer] # Python 2, 44 bytes This is a complete python program that reads in n, and prints the answer. I think it does quite well in the readability sub-competition. ``` n=input()+1 while'11'in bin(n):n+=1 print n ``` The test results: ``` $ echo 12 | python soln.py 16 $ echo 18 | python soln.py 20 ``` [Answer] # Pyth, ~~12~~ 11 bytes ``` f!}`11.BThQ ``` Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=f!%7D%6011.BThQ&input=12&debug=0). ``` implicit: Q = input() f hQ find the first integer T >= Q + 1, that satisfies the condition: !}`11.BT "11" is not in the binary representation of T ``` [Answer] # Mathematica, ~~41~~ 30 bytes Saved 11 bytes thanks to Martin Büttner. ``` #+1//.i_/;BitAnd[i,2i]>0:>i+1& ``` [Answer] # Perl, 31 ``` #!perl -p sprintf("%b",++$_)=~/11/&&redo ``` Or from the command line: ``` perl -pe'sprintf("%b",++$_)=~/11/&&redo' <<<"18" ``` [Answer] # APL, 18 bytes ``` 1∘+⍣{~∨/2∧/⍺⊤⍨⍺⍴2} ``` This evaluates to a monadic function. [Try it here.](http://tryapl.org/) Usage: ``` 1∘+⍣{~∨/2∧/⍺⊤⍨⍺⍴2} 12 16 ``` ## Explanation ``` 1∘+ ⍝ Increment the input ⍺ ⍣{ } ⍝ until ~∨/ ⍝ none of 2∧/ ⍝ the adjacent coordinates contain 1 1 in ⍺⊤⍨⍺⍴2 ⍝ the length-⍺ binary representation of ⍺. ``` [Answer] ## J, 20 characters A monadic verb. Fixed to obey the rules. ``` (+1 1+./@E.#:)^:_@>: ``` ### Explanation First, this is the verb with spaces and then a little bit less golfed: ``` (+ 1 1 +./@E. #:)^:_@>: [: (] + [: +./ 1 1 E. #:)^:_ >: ``` Read: ``` ] The argument + plus [: +./ the or-reduction of 1 1 E. the 1 1 interval membership in #: the base-2 representation of the argument, [: ( )^:_ that to the power limit of >: the incremented argument ``` > > The argument plus the or-reduction of the `1 1` interval membership in the base-2 representation of the argument, that to the power limit applied to the incremented argument. > > > I basically compute if `1 1` occurs in the base-2 representation of the input. If it does, I increment the input. This is put under a power-limit, which means that it is applied until the result doesn't change any more. [Answer] # Javascript, 25 19 Using the fact that, for a 1-sparse binary number, `x&2*x == 0`: ``` f=x=>x++&2*x?f(x):x ``` [Answer] # JavaScript (ES6), 39 ~~43~~ No regexp, no strings, recursive: ``` R=(n,x=3)=>x%4>2?R(++n,n):x?R(n,x>>1):n ``` Iterative version: ``` F=n=>{for(x=3;x%4>2?x=++n:x>>=1;);return n} ``` It's very simple, just using right shift to find a sequence of 11. When I find it, skip to next number. The recursive version is directly derived from the iterative one. **Ungolfed** and more obvious. To golf, the trickiest part is merging the inner and outer loops (having to init x to 3 at start) ``` F = n=>{ do { ++n; // next number for(x = n; x != 0; x >>= 1) { // loop to find 11 in any position if ((x & 3) == 3) { // least 2 bits == 11 break; } } } while (x != 0) // if 11 was found,early exit from inner loop and x != 0 return n } ``` [Answer] # Python 2, 37 bytes ``` f=input()+1 while f&2*f:f+=1 print f ``` Used the logic `x & 2*x == 0` for 1-sparse number. Thanks to @Nick and @CarpetPython. [Answer] # JavaScript, ~~75~~ ~~66~~ 62 bytes Thanks to Martin Büttner for saving 9 bytes and Pietu1998 for 4 bytes! ``` function n(a){for(a++;/11/.test(a.toString(2));a++);return a;} ``` How it works: it runs a `for` loop starting from `a + 1` as long as the current number is not 1-sparse, and if it is, the loop is interrupted and it returns the current number. To check whether a number is 1-sparse, it converts it to binary and checks whether it does not contain `11`. Un-golfed code: ``` function nextOneSparseNumber(num) { for (num++; /11/.test(num.toString(2)); num++); return num; } ``` [Answer] # Julia, 40 bytes ``` n->(while contains(bin(n+=1),"11")end;n) ``` This creates an anonymous function that accepts a single integer as input and returns the next highest 1-sparse integer. To call it, give it a name, e.g. `f=n->...`, and do `f(12)`. Ungolfed + explanation: ``` function f(n) # While the string representation of n+1 in binary contains "11", # increment n. Once it doesn't, we've got the answer! while contains(bin(n += 1), "11") end return(n) end ``` Examples: ``` julia> f(12) 16 julia> f(16) 20 ``` Suggestions and/or questions are welcome as always! [Answer] # Python, ~~39~~ 33 bytes Try it here: <http://repl.it/gpu/2> In lambda form (thanks to xnor for golfing): ``` f=lambda x:1+x&x/2and f(x+1)or-~x ``` Standard function syntax ~~turned out to be shorter than a lambda for once!~~ ``` def f(x):x+=1;return x*(x&x*2<1)or f(x) ``` [Answer] # [><> (Fish)](http://esolangs.org/wiki/Fish), 31 + 3 = 34 bytes ``` 1+:>: 4%:3(?v~~ ;n~^?-1:,2-%2< ``` Usage: ``` >python fish.py onesparse.fish -v 12 16 ``` 3 bytes added for the `-v` flag. [Answer] # JavaScript (ECMAScript 6), 40 By recursion: ``` g=x=>/11/.test((++x).toString(2))?g(x):x ``` # JavaScript, 56 Same without arrow functions. ``` function f(x){return/11/.test((++x).toString(2))?f(x):x} ``` [Answer] # Scala, 65 bytes ``` (n:Int)=>{var m=n+1;while(m.toBinaryString.contains("11"))m+=1;m} ``` (if a named function is required, solution will be 69 bytes) [Answer] # Java, 33 bytes. Uses the method in [this answer](https://codegolf.stackexchange.com/a/48421/84303) ``` n->{for(;(n++&2*n)>0;);return n;} ``` [TIO](https://tio.run/##HcyxDoMgFEDRna94UwNtNK0rqaNbJ8emA1UwWHwYeJo0hG@nptOZ7p3Vrqp5/JTBqRjhoSwmZpF0MGrQ0CXncQLD/6CQma3b29kBIik62L0dYTkq3lOwOD1foMIURWIdmHvBqk3GBy45Xi6n5oyivUohg6YtIKDMRbL@G0kvtd@oXo8FOeSmNvzWCCFZzuUH) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` λd⋏[›x ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOu2Tii49b4oC6eCIsIiIsIjEyIl0=) ## How? ``` λd⋏[›x λ # Open a lambda for recursion d # Double ⋏ # Bitwise AND the doubled input with the input [ # If this is truthy (non-zero): ›x # Increment and recurse ``` [Answer] ## Ruby, 44 ``` ->(i){loop{i+=1;break if i.to_s(2)!~/11/};i} ``` Pretty basic. A lambda with an infinite loop and a regexp to test the binary representation. I wish that `loop` yielded and index number. [Answer] # Matlab (77 74 bytes) ``` m=input('');for N=m+1:2*m if ~any(regexp(dec2bin(N),'11')) break end end N ``` Notes: * It suffices to test numbers `m+1` to `2*m`, where `m` is the input. * `~any(x)` is `true` if `x` contains all zeros *or* if `x` is empty [Answer] **C (32 bytes)** ``` f(int x){return 2*++x&x?f(x):x;} ``` Recursive implementation of the same algorithm as so many other answers. [Answer] # Perl, 16 bytes Combining the `x&2*x` from various answers (I think [Nick's](/a/48421) first) with [nutki's](/a/48364) `redo` yields: ``` perl -pe'++$_&2*$_&&redo' ``` Tested in Strawberry 5.26. [Answer] # Japt, 8 bytes ``` _&ZÑ}fUÄ ``` [Run it online.](https://ethproductions.github.io/japt/?v=1.4.6&code=XyZa0X1mVcQ=&input=MTI=) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly) ``` ‘&Ḥ¬Ɗ1# ``` A full program accepting a single, non-negative integer which prints a positive integer (as a monadic link it yields a list containing a single positive integer). **[Try it online!](https://tio.run/##y0rNyan8//9Rwwy1hzuWHFpzrMtQ@f///4ZmAA "Jelly – Try It Online")** ### How? Starting at `v=n+1`, and incrementing, double `v` to shift every bit up one place and bit-wise AND with `v` and then perform logical NOT to test if `v` is 1-sparse until one such number is found. ``` ‘&Ḥ¬Ɗ1# - Main Link: n e.g. 12 ‘ - increment 13 1# - 1-find (start with that as v and increment until 1 match is found) using: Ɗ - last three links as a dyad: Ḥ - double v & - (v) bit-wise AND (with that) ¬ - logical NOT (0->1 else 1) - implicit print (a single item list prints as just the item would) ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╦>ù╤x ``` [Run and debug it](https://staxlang.xyz/#p=cb3e97d178&i=12%0A18&a=1&m=2) It works using this procedure. The input starts on top of the stack. * Increment and copy twice. * Halve the top of the stack. * Bitwise-and top two elements on the stack. * If the result is truthy (non-zero) repeat the entire program. ]
[Question] [ We've all been told at some point in our lives that dividing by 0 is impossible. And for the most part, that statement is true. But what if there *was* a way to perform the forbidden operation? Welcome to my newest creation: `b`-numbers. `b`-numbers are a little bit like imaginary numbers: the main pronumeral involved represents an expression that isn't mathematically impossible (`i` represents \$\sqrt{-1}\$). In this case \$b\$ will be said to represent the expression \$\frac{1}{0}\$. From here, it is easy to determine what \$\frac{x}{0}\$ would equal: $$ \frac{x}{0} = \frac{x}{1} \cdot \frac{1}{0} = xb $$ ## The Task Given an expression involving a division by 0, output the simplified value in terms of \$b\$. Note that input will be in the form of `n/0` where n is any rational number or any `b`-number in decimal form. Leading 0s and trailing 0s wont be included. ## Example Input ``` 4/0 1/0 0/0 80/0 -8/0 1.5/0 2.03/0 -1/0 -3.14/0 b/0 3b/0 -b/0 121/0 ``` ## Example Output ``` 4b b 0 80b -8b 1.5b 2.03b -b -3.14b b 3b -b 121b ``` # Score This is code golf, so fewest bytes wins. Standard loopholes are forbidden. ## Leaderboards Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=191101; var OVERRIDE_USER=8478; var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}} ``` ``` body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> ``` [Answer] # Malbolge Unshackled (20-trit rotation variant), 3,62e6 bytes Size of this answer exceeds maximum postable program size (eh), so the code is [located in my GitHub repository](https://github.com/KrzysztofSzewczyk/codegolf-submissions/raw/master/191101.mu) (note: Don't copy the code using CTRL+A and CTRL+C, just rightclick and click "Save destination element as..."). ## How to run this? This might be a tricky part, because naive Haskell interpreter will take ages upon ages to run this. TIO has decent Malbogle Unshackled interpreter, but sadly I won't be able to use it (limitations). The best one I could find is the fixed 20-trit rotation width variant, that performs very well, **calculating (pretty much) instantly**. To make the interpreter a bit faster, I've removed all the checks from Matthias Lutter's Malbolge Unshackled interpreter. ``` #include <malloc.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char* translation = "5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72Fh" "OA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G\"i@"; typedef struct Word { unsigned int area; unsigned int high; unsigned int low; } Word; void word2string(Word w, char* s, int min_length) { if (!s) return; if (min_length < 1) min_length = 1; if (min_length > 20) min_length = 20; s[0] = (w.area%3) + '0'; s[1] = 't'; char tmp[20]; int i; for (i=0;i<10;i++) { tmp[19-i] = (w.low % 3) + '0'; w.low /= 3; } for (i=0;i<10;i++) { tmp[9-i] = (w.high % 3) + '0'; w.high /= 3; } i = 0; while (tmp[i] == s[0] && i < 20 - min_length) i++; int j = 2; while (i < 20) { s[j] = tmp[i]; i++; j++; } s[j] = 0; } unsigned int crazy_low(unsigned int a, unsigned int d){ unsigned int crz[] = {1,0,0,1,0,2,2,2,1}; int position = 0; unsigned int output = 0; while (position < 10){ unsigned int i = a%3; unsigned int j = d%3; unsigned int out = crz[i+3*j]; unsigned int multiple = 1; int k; for (k=0;k<position;k++) multiple *= 3; output += multiple*out; a /= 3; d /= 3; position++; } return output; } Word zero() { Word result = {0, 0, 0}; return result; } Word increment(Word d) { d.low++; if (d.low >= 59049) { d.low = 0; d.high++; if (d.high >= 59049) { fprintf(stderr,"error: overflow\n"); exit(1); } } return d; } Word decrement(Word d) { if (d.low == 0) { d.low = 59048; d.high--; }else{ d.low--; } return d; } Word crazy(Word a, Word d){ Word output; unsigned int crz[] = {1,0,0,1,0,2,2,2,1}; output.area = crz[a.area+3*d.area]; output.high = crazy_low(a.high, d.high); output.low = crazy_low(a.low, d.low); return output; } Word rotate_r(Word d){ unsigned int carry_h = d.high%3; unsigned int carry_l = d.low%3; d.high = 19683 * carry_l + d.high / 3; d.low = 19683 * carry_h + d.low / 3; return d; } // last_initialized: if set, use to fill newly generated memory with preinitial values... Word* ptr_to(Word** mem[], Word d, unsigned int last_initialized) { if ((mem[d.area])[d.high]) { return &(((mem[d.area])[d.high])[d.low]); } (mem[d.area])[d.high] = (Word*)malloc(59049 * sizeof(Word)); if (!(mem[d.area])[d.high]) { fprintf(stderr,"error: out of memory.\n"); exit(1); } if (last_initialized) { Word repitition[6]; repitition[(last_initialized-1) % 6] = ((mem[0])[(last_initialized-1) / 59049]) [(last_initialized-1) % 59049]; repitition[(last_initialized) % 6] = ((mem[0])[last_initialized / 59049]) [last_initialized % 59049]; unsigned int i; for (i=0;i<6;i++) { repitition[(last_initialized+1+i) % 6] = crazy(repitition[(last_initialized+i) % 6], repitition[(last_initialized-1+i) % 6]); } unsigned int offset = (59049*d.high) % 6; i = 0; while (1){ ((mem[d.area])[d.high])[i] = repitition[(i+offset)%6]; if (i == 59048) { break; } i++; } } return &(((mem[d.area])[d.high])[d.low]); } unsigned int get_instruction(Word** mem[], Word c, unsigned int last_initialized, int ignore_invalid) { Word* instr = ptr_to(mem, c, last_initialized); unsigned int instruction = instr->low; instruction = (instruction+c.low + 59049 * c.high + (c.area==1?52:(c.area==2?10:0)))%94; return instruction; } int main(int argc, char* argv[]) { Word** memory[3]; int i,j; for (i=0; i<3; i++) { memory[i] = (Word**)malloc(59049 * sizeof(Word*)); if (!memory) { fprintf(stderr,"not enough memory.\n"); return 1; } for (j=0; j<59049; j++) { (memory[i])[j] = 0; } } Word a, c, d; unsigned int result; FILE* file; if (argc < 2) { // read program code from STDIN file = stdin; }else{ file = fopen(argv[1],"rb"); } if (file == NULL) { fprintf(stderr, "File not found: %s\n",argv[1]); return 1; } a = zero(); c = zero(); d = zero(); result = 0; while (!feof(file)){ unsigned int instr; Word* cell = ptr_to(memory, d, 0); (*cell) = zero(); result = fread(&cell->low,1,1,file); if (result > 1) return 1; if (result == 0 || cell->low == 0x1a || cell->low == 0x04) break; instr = (cell->low + d.low + 59049*d.high)%94; if (cell->low == ' ' || cell->low == '\t' || cell->low == '\r' || cell->low == '\n'); else if (cell->low >= 33 && cell->low < 127 && (instr == 4 || instr == 5 || instr == 23 || instr == 39 || instr == 40 || instr == 62 || instr == 68 || instr == 81)) { d = increment(d); } } if (file != stdin) { fclose(file); } unsigned int last_initialized = 0; while (1){ *ptr_to(memory, d, 0) = crazy(*ptr_to(memory, decrement(d), 0), *ptr_to(memory, decrement(decrement(d)), 0)); last_initialized = d.low + 59049*d.high; if (d.low == 59048) { break; } d = increment(d); } d = zero(); unsigned int step = 0; while (1) { unsigned int instruction = get_instruction(memory, c, last_initialized, 0); step++; switch (instruction){ case 4: c = *ptr_to(memory,d,last_initialized); break; case 5: if (!a.area) { printf("%c",(char)(a.low + 59049*a.high)); }else if (a.area == 2 && a.low == 59047 && a.high == 59048) { printf("\n"); } break; case 23: a = zero(); a.low = getchar(); if (a.low == EOF) { a.low = 59048; a.high = 59048; a.area = 2; }else if (a.low == '\n'){ a.low = 59047; a.high = 59048; a.area = 2; } break; case 39: a = (*ptr_to(memory,d,last_initialized) = rotate_r(*ptr_to(memory,d,last_initialized))); break; case 40: d = *ptr_to(memory,d,last_initialized); break; case 62: a = (*ptr_to(memory,d,last_initialized) = crazy(a, *ptr_to(memory,d,last_initialized))); break; case 81: return 0; case 68: default: break; } Word* mem_c = ptr_to(memory, c, last_initialized); mem_c->low = translation[mem_c->low - 33]; c = increment(c); d = increment(d); } return 0; } ``` ## It's working! [![It's working!](https://i.stack.imgur.com/ZIxn7.png)](https://i.stack.imgur.com/ZIxn7.png) [Answer] # [PHP](https://php.net/), ~~65~~ ~~64~~ ~~61~~ 58 bytes -1 byte by using a `b` instead of `''` (empty string). Since "b"s are trimmed, it will be same as an empty string in this specific case. -3 bytes by using `substr` instead of `explode` to get first part of input. -3 bytes by using better methods to detect `1` and `-1`. ``` <?=($n=substr($argn,0,-2))?trim($n+1?$n-1?$n:b:'-',b).b:0; ``` [Try it online!](https://tio.run/##FckxDoAgDADAz5AgkSKoE0rY/IcsymAhgN@36nLL5TMTrd51DF29Q22lY3s5UGoJoxC@lXh91xvPEH5ssBy4DEIFqxcimJSZB/2k3GLCSrC9 "PHP – Try It Online") Tests: [Try it online!](https://tio.run/##TY9BDoIwEEX3PcWEkACRYgFNDJWw8wBu1QUlKCZaGlpWxqtbazFpu2jezP9/2hGD0PtGDAKhUPVSSajhhMCcaLMmUbpg7pA43HmMd54727qiyEjp2bxJuMxy7w3msPQYe5wXS/xCEbqOU992A8T/b7cSLCXwsuawnW7cLGOb1Lb6bhghOPZyfigw@UWrIKD6J8Uhr@XMpJpiG05JioskadR0fxptlTchx7@rYlWEo5QlGasI1W70mQcUvbVZ6jMKdR@51PjwBQ "PHP – Try It Online") If first part of input before "/" (we call it `$n`) is 0, prints 0. Else prints `$n` itself with any "b" at the end trimmed from it and special cases of -1 and 1 handled, so the "1" digit is not printed. And at the end appends a single "b". The trimming part is to make sure we don't get a double "b" at the end like "3bb". [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) I ended up stealing [Erik's](https://codegolf.stackexchange.com/a/191110/53748) `ṾṖ$İƑ¡` for this one (otherwise I'd also have 19)... ``` ṖṖv0ḢṾṖ$İƑ¡,Ạ¡”boḢ ``` A full program which prints the result. **[Try it online!](https://tio.run/##y0rNyan8///hzmlAVGbwcMeihzv3AZkqRzYcm3hooc7DXQsOLXzUMDcpHyj1//9/XWM9Q5MkfQMA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hzmlAVGbwcMeihzv3AZkqRzYcm3hooc7DXQsOLXzUMDcpHyj1/@HuLYfbHzWtifz/30TfgMsQiA2A2AJE6FqARPRMgaSRnoExSAQkr2usZwhSmwTExiBCF0QYGsHlgFwA "Jelly – Try It Online"). ### How? ``` ṖṖv0ḢṾṖ$İƑ¡,Ạ¡”boḢ - Main Link: list of characters S Ṗ - discard right-most (of S) Ṗ - discard right-most 0 - literal zero v - evaluate as Jelly code with right argument (0) - ... b is covert-to-base, so "nb0" gives [n] Ḣ - head ([n]->n or n->n) ¡ - repeat... Ƒ - ...# of times: is invariant under: İ - reciprocation (n->1/n) $ - ...action: last two links as a monad: Ṿ - un-evaluate (-1->"-1" or 1->"1") Ṗ - discard right-most ("-1"->"-" or "1"->"") ¡ - repeat... Ạ - ...# of times: all? , ”b - ...action: pair with a 'b' character o - logical OR with: Ḣ - head (S) (i.e. if we end with 0 use the 1st character of the input) - implicit print ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 32 bytes ``` {~m/^0/||S/[(\-|^)1|b]?\/0/$0b/} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv7ouVz/OQL@mJlg/WiNGtyZO07AmKdY@Rt9AX8UgSb/2f05mXmqxnZ2eWhqQKE6s/G@ib8BlCMQGQGwBInQtQCJ6pkDSSM/AGCQCktc11gNRSUBsDCJ0QYShEVAMAA "Perl 6 – Try It Online") A couple of regexes, one to check if the input is `0/0`, and the other to replace the trailing `/0` with just `b` (and to remove the old `b`, `1`, and/or `-1`) ### Explanation (old) ``` { } # Anonymous codeblock ~m/^0/ # Return 0 if the input starts with 0 || # Otherwise S/ / / # Substitute \/0 # The /0 ( )? # Optionally starting with <wb>1 # 1 or -1 |b # Or b b # With just b ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` ṖṖḟ”bȯ1VṾṖ$İƑ¡,Ạ¡”b ``` [Try it online!](https://tio.run/##y0rNyan8///hzmkgtGP@o4a5SSfWG4Y93LkPKKByZMOxiYcW6jzcteDQQpDU////dZP0DQA "Jelly – Try It Online") Full program. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~28~~ 24 bytes ``` b?/0 b ^0b 0 (^|-)1b $1b ``` [Try it online!](https://tio.run/##FYohDoBADAR93wHJIXq0d5DgkPziAk0QGARB8vfSFTNiZ5/zve5DvU/b7raOQkZNjIRS@3hQo07NfYqggQQLxAuWPIdLlooFnWtWfC2oEENa0H4 "Retina – Try It Online") First try at using Retina, so there's probably considerable room for golfing. [Answer] # [convey](http://xn--wxa.land/convey/), 47 bytes ``` ['b'} >>~^]] '-'[ 91+>##"@] {?~""@@<} ]11-^} ``` [Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiWydiJ31cbiA+Pn5eXV0gJy0nW1xuIDkxKz4jI1wiQF1cbns/flwiXCJAQDx9XG4gXTExLV59IiwidiI6MSwiaSI6Ii0xLzAifQ==) I would like to put off the space betwen the number and 'b' in the output but i dont know how to do it :( How it works (-3/0): [![enter image description here](https://i.stack.imgur.com/6z1cq.gif)](https://i.stack.imgur.com/6z1cq.gif) How it works (1/0): [![enter image description here](https://i.stack.imgur.com/zqhsP.gif)](https://i.stack.imgur.com/zqhsP.gif) [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~69~~ 66 bytes / ~~73~~ 70 bytes Python already had a solution [here](https://codegolf.stackexchange.com/a/191136/103772) but it didn't work properly on `-1/0`. That solution also uses regex while this one is vanilla python. ## Lambda version (66 bytes) ``` lambda x:{"0":0,"1":"b","-1":"-b"}.get(a:=x[:-2].strip("b"),a+"b") ``` [Try it online!](https://tio.run/##RY/RasMwDEXf9RXGL02Y7TnJBsGQ/kjXh3hzVsOWmtSFbGPfnklWywzWNbKkq5O@8uk8d31atml42T7GT/82itX9SCudVbKRTnqppKaH9vLXvIdcjW5YD063R3PJS0wVltRqfCDZ4pyu@SIGcZBPjxZbmxJtiT2L7vnHPBdtje04z7W6Mw33@hI7Fs3StFR1hLCm8JrZiFakyx5l4d6zg78ZlKS/T783/KdxrMepMJ0XEVUQcRbfiMY4is1qBwJPWuKcq6B2w36npirW9YbrAq4FyAcECYQIBRAYDwgObmiAKEBYQFBQkP4A "Python 3.8 (pre-release) – Try It Online") ## Print version (70 bytes) ``` print({"0":0,"1":"b","-1":"-b"}.get(a:=input()[:-2].strip("b"),a+"b")) ``` [Try it online!](https://tio.run/##RU/RagMhEHz3K2RfovQ0epeACPZHQh5yF9v64omxkBLy7dddA60wMzK7zq7lp32teXKlbst6jaECwFZqyk08wIA3A1jwMMMAii5qhqf@jE1cfEi5fDchT16NZ31rNRWBjXK4vJHIDaNYvJe4NB74CQ4UQjAIZ3qkI7b6SDJqM3Wz06Tt34N/2452hjNjH2vliafMX/mecTyvtdPAY76GHQ/vfCd7Id7jIuh7cjvsDbMIg3BEypGjj8i0ADlU7/NRZ8REpIhw/N78Ag "Python 3.8 (pre-release) – Try It Online") ## How it works : starting from a string `x`: * `x[:-2]` remove the `/0` part * `.strip("b")` remove any eventual `b` present in the string * `a:=` store our new string into `a` Then we check if our new sring is equal to any `"0"`, `"1"` or `"-1"`: * if True, `{...}.get()` will replace it by the appropriate string * else, we will print it inchanged adding `"b"` at the end of the string Thanks to ovs for reminding me that `str.strip` existed saving 3 bytes on each program [Answer] ## [Keg](https://github.com/JonoCode9374/Keg), 18B All credit is to Jono 2906. ``` __:b=;[b]^:\1=[_]^ ``` ## Explanation ``` __ # Take implicit input and remove the "trash" (/0). :b= # Is the last character equal to b? ; # Negate(decrement) this value. [b] # If the last character is not b, append b. ^ # Reverse the stack. :\1= # Is the first character equal to 1? [_] # If so, reduce the value. ^ # Reverse the stack back and implicit output. ``` [TIO!](https://tio.run/##y05N//8/Pt4qydY6Oik2zirG0DY6Pjbu/39dQyNDfQMA) [Answer] # [Python 3](https://docs.python.org/3/), 68 bytes ``` import re print(re.sub('^0b$','0',re.sub(r'(^1)?b?/0','b',input()))) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEolaugKDOvRKMoVa@4NElDPc4gSUVdR91AXQcqUqSuEWeoaZ9krw8UU09S18nMKygt0dAEgv//jZP0DQA "Python 3 – Try It Online") [Answer] # JavaScript (ES6), 45 bytes ``` s=>+(n=s.split`/`[0])?[n*n-1?n:'-'[~n]]+'b':n ``` [Try it online!](https://tio.run/##bc7LCsIwEIXhvS8yiWXSpFEohdgHCYFebKUSJsUUl756XLiT2X6L/5zn@B7z/Nr2Ayndl7K6kt2tEuSyynvcjqEevA6y93QmND11gOA/FEIFE3RU5kQ5xUXF9BCrgEutQcrTnxpWNastz9jyZXVlvVHa8h3@C1pl@O8Tq5Zn5Nk0v9XyBQ "JavaScript (Node.js) – Try It Online") ### Commented ``` s => // s = input: "numerator/0" +( // n = s.split`/`[0] // n = numerator, as a string ) ? // if n coerced to a Number is neither equal to 0 nor NaN: [ n * n - 1 ? // if abs(n) is not equal to 1: n // append the numerator : // else: '-'[~n] // append '-' if n = -1, or an empty string otherwise ] + 'b' // append 'b' : // else: n // just output the numerator because it's either "0" or // an expression that already contains 'b' ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~298~~ ~~263~~ ~~217~~ 179 bytes ``` i;f(char*s){for(i=0;s[i]-47&&(*s-49|s[1]-98||!printf("b"));)write(1,s+i,s[i++]!=98);}main(){char*s;gets(s);printf(*s-98&&*s-49|s[1]-47?*s-48?*s-45|s[1]-49?f(s),"b":"-b":"0":"b");} ``` [Try it online!](https://tio.run/##TY1BCoMwEEXPoouQUUMjWEwaxIOICyvGDrS2ZIQu1LOnsXXRxXyYD@/9XvT3bhq9R2N5f@tcQrDYp@NYSUMNtqIoGeMJiUKv1OSt0Gpdo5fDabY8vsYABt4O54HnGaWYBSZN26jSCsz26HDisPy8Zhxm4gTmgINTK8b@1EVZ75/65vnodG0DlIWpSyz2kOHCrtm8z@VJfgA "C (clang) – Try It Online") After a while, I actually managed to make this function the way you want. It's pretty big, I will say, I had to debug a lot. Thanks to ceilingcat for golfing 35 bytes, another 46 bytes, and another 38 bytes. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 37 bytes ``` ToExpression[""<>#~Drop~-2]b/.b^_->b& ``` [Try it online!](https://tio.run/##FYqxDsIgFEX3fgYknQQK1aSDNk3U3aRuDRpoqCWxpQEGp/468oZzhnvuouJsFhXtqNJ0SU93/23ehGDdOiB0bvF@827biZCaUf16k1aX6eHtGgdM2qm7zsqrMRofOixL1vUxt0@/fW0cCnRkVcEzVaYBkQYWesoWtKphgU5qyuGrMzWIgLjIDR1QgWT6Aw "Wolfram Language (Mathematica) – Try It Online") Takes a list of characters as input. [Answer] ## C, ~~209~~ ~~203~~ 137 bytes *-66 bytes thanks to ceilingcat* ``` char a[9];main(f){gets(a);f=strlen(a)-3;a[f+1]=0;printf((*a==55&a[1]==49&f==1?a[1]=98:*a==49&!f?*a=98:a[f]==98|*a==48&!f)?"%s":"%sb",a);} ``` [TIO](https://tio.run/##HY3BCsIwEER/RQuWRK22tIWkYcmHhB7W0K0FDZLmpn57XHsZZubtsL6avc/Z3zHu0OnRPHEJguR7ntIqUBqCNcXHFNhXrUFHp2aE2rziEhIJcUSAvi/RcQudLgmgsVvSavhD7vZk2XHmNV9p9dmAYiBtcViLgeVWnPnbN@eqvTTdtf4B) [Answer] # [naz](https://github.com/sporeball/naz), 64 bytes ``` 6a8m1s2x1v2m4a2x2v1x1f1r3x1v2e3x2v3e1o1f0x1x2f2m4a1o0x1x3f1o0x1f ``` **Explanation** (with `0x` commands removed) ``` 6a8m1s2x1v # Set variable 1 equal to 47 ("/") 2m4a2x2v # Set variable 2 equal to 98 ("b") 1x1f # Function 1 1r # Read a byte of input 3x1v2e # Jump to function 2 if it equals variable 1 3x2v3e # Jump to function 3 if it equals variable 2 1o1f # Otherwise, output it and jump back to the start of the function 1x2f2m4a1o # Function 2 # Set the register equal to 98 and output once 1x3f1o # Function 3 # Output once 1f # Call function 1 ``` [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, 37 bytes ``` sub /(^1|-\K1)?b?\/0/,?b sub /^0b/,?0 ``` [Try it online!](https://tio.run/##KypNqvz/v7g0SUFfI86wRjfG21DTPsk@Rt9AX8c@iQssEWeQBOQY/P9vom/AZQjEBkBsASJ0LUAieqZA0kjPwBgkApLXNdYDUUlAbAwidEGEoRFYK0jxv/yCksz8vOL/ugUA "Ruby – Try It Online") [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 96 bytes ``` #import<ios> int f(int r,int i){i-=~r;i||printf("-");i--*~-i&&printf("%d",i?:r);i&&printf("b");} ``` Takes as input an integer `r` denoting a real number and the coefficient of a multiple of \$b\$ `i`. Then "divides" by zero and does some hacking to avoid printing deviating results. [Try it online!](https://tio.run/##RY/BrsIgEEX3fAWpUUEhturCWKsfUrtQfH3OwkIQXYj46xVo1VncOzl3MpkRSvF/Idp2ABcltdmAvG4RNAbXJKhmQYFa4MVL5/B8Ku1JTRKe0Bw4n7w4jEYfODwlDHZr7aMfPPpJ14Y9lwM05C7hRJFF2FeARpRVOa9wEYlFdukYslmQNMgqKl9F7TDrbdFZR7N5sLDD5Sh6LXV8AnCB09zbBl/h8SdrYgSdfdsyrahPp1PaX4D7iiFUPme46zI/@Y3VzYjzQZPxvhn32CHXvgE "C++ (gcc) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 71 bytes ``` f(r,i){i-=~r;i||printf("-");i--*~-i&&printf("%d",i?:r);i&&printf("b");} ``` Same as my C++ solution but with less boilerplate. [Try it online!](https://tio.run/##RY7BDoIwEETv/YqGRGm1jYAeiEj8EOSA1eoeBFPRg7X8OrYFcQ8zkzebbQW/CNH3kigGVAPPO5XB53NXULeSBDygGXC@6DjM5z84OwUM9ltlqz882k3T24xvFdTk1cCJIo2wHQdbUZRFUuLcE430xjCkYyeRk9QrT70OmI22HmygceLM3TAZ8i4bRdwLgHMcZdZ2@AHvcyNJK@hqikVUUtsul3T8AR7Hl1DanuEhxXZzqu/PVlwrRcJDHY7YINN/AQ "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ¨¨ÐĀiáм'b«Dþi1K ``` [Try it online](https://tio.run/##ASUA2v9vc2FiaWX//8KowqjDkMSAacOh0LwnYsKrRMO@aTFL//8tMS8w) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/QysOrTg84UhD5uGFF/aoJx1a7XJ4X6ah9//aWp3/0Uom@gZKOkqGYNIATFpAKF0LiIyeKZg20jMwhohD1Ooa6xlC9CaBSWMIpQuhDI1AqmIB). **Explanation:** ``` ¨¨ # Remove the last two characters of the (implicit) input Ð # Then triplicate the string Āi # Pop one, and if it's NOT 0 (using Python-style truthify): á # Pop again and only leave the letters (in case it contains a "b") м # And remove those letters 'b« '# Then append a trailing "b" D # Duplicate it þ # Pop and only leave the digits i # If this is exactly 1: 1K # Remove the 1 # (after which the top of the stack is output implicitly as result) ``` [Answer] # Brainfuck, 25 bytes ``` >,[>,]<[-<+>]<+++[<]>[.>] ``` ## Explanation ``` >,[>,] read from stdin <[-<+>]<+++ add last two cells and add three ( ascii('/') + ascii('0') + 3 = ascii('b') [<]> move pointer to first char to output [.>] output until cell w/ value 0 ``` [Answer] # Symja, 85 bytes ``` d(x_):=If((e=StringReplace(x,"/0"->""))!="0",If(StringContainsQ(e,"b"),e,e<>"b"),"0") ``` [Try it Online!](https://symjaweb.appspot.com/input?i=d%28x%5f%29%3a%3dIf%28%28e%3dStringReplace%28x%2c%22%2f0%22%2d%3e%22%22%29%29%21%3d%220%22%2cIf%28StringContainsQ%28e%2c%22b%22%29%2ce%2ce%3c%3e%22b%22%29%2c%220%22%29%3bd%28%223b%2f0%22%29) I finally answered my own question! ]
[Question] [ Given a list of `1`s and `-1`s, determine whether or not it is a valid [OVSF code](https://en.wikipedia.org/wiki/Chip_(CDMA)#Orthogonal_variable_spreading_factor) (by outputting a truthy or falsey value). OVSF codes are defined as follows: * `[1]` is an OVSF code. * If `X` is an OVSF code, then `X ++ X` and `X ++ -X` are both OVSF codes. Here `++` is list concatenation, and `-` negates every element in the list. * No other lists are valid OVSF codes. You may assume the input list contains only `-1` and `1`, but you must handle the empty list correctly, as well as lists whose length is not a power of 2. Shortest code (in bytes) wins. # Test cases ``` [] -> False [1] -> True [-1] -> False [1, 1] -> True [1, -1] -> True [-1, 1] -> False [-1, -1] -> False [1, 1, 1, 1] -> True [1, 1, 1, 1, 1] -> False [1, -1, -1, 1, -1, 1, 1, -1] -> True [1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1] -> False [1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1] -> False [1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1] -> True ``` [Answer] ## Mathematica, ~~52~~ ~~47~~ 45 bytes Byte count assumes CP-1252 encoding and `$CharacterEncoding` set to `WindowsANSI` (the default on Windows installations). ``` ±___=!(±1=1>0) a__±b__/;a!==b!||{a}==-{b}:=±a ``` This defines a variadic function `PlusMinus`, which takes the input list as a flat list of arguments and returns a boolean, e.g. `PlusMinus[1, -1, -1, 1]` gives `True`. It's theoretically also usable as an operator `±`, but that operator is only syntactically valid in unary and binary contexts, so the calling convention would get weird: `±##&[1,-1,-1,1]`. It will throw a bunch of warnings that can be ignored. This will also throw a few warnings which can be ignored. There *might* be away to shorten the somewhat annoying `a!==b!||{a}==-{b}` part, but I'm not finding anything right now. Keywords like `SubsetQ` and `MatrixRank` are simply too long. :/ ### Explanation The solution basically defers all the tricky things to Mathematica's pattern matcher and is therefore very declarative in style. Apart from some golfitude on the first line, this really just adds three different definitions for the operator `±`: ``` ±___=False; ±1=True; a__±b__/;a!==b!||{a}==-{b}:=±a ``` The first two rows were shortened by nesting the definitions and expressing `True` as `1>0`. We should deconstruct this further to show how this actually defines a variadci function `PlusMinus` by only using unary and binary operator notation. The catch is that all operators are simply syntactic sugar for full expressions. In our case `±` corresponds to `PlusMinus`. The following code is 100% equivalent: ``` PlusMinus[___]=False; PlusMinus[1]=True; PlusMinus[a__,b__]/;a!==b!||{a}==-{b}:=PlusMinus[a] ``` By using sequences (sort of like splats in other languages) as the operands to `±` we can cover an arbitrary number of arguments to `PlusMinus`, even though `±` isn't usable with more than two arguments. The fundamental reason is that syntactic sugar is resolved first, before any of these sequences are expanded. On to the definitions: The first definition is simply a fallback (`___` matches an arbitrary list of arguments). Anything that isn't matched by the more specific definitions below will give `False`. The second definition is the base case for the OVSF, the list containing only `1`. We define this to be `True`. Finally, the third definition applies *only* to lists that can be decomposed into `X ++ X` or `X ++ -X`, and recursively uses the result for `X`. The definition is limited to these lists by ensuring they can be split into subsequences `a` and `b` with `a__±b__` and then attaching the condition (`/;`) that either `{a}=={b}` or `{a}==-{b}`. Defining `PlusMinus` as a variadic function in this weird way via an operator saves a whopping **5** bytes over defining a unary operator `±` on lists. But wait, there's more. We're using `a!==b!` instead of `{a}=={b}`. Clearly, we're doing this because it's two bytes shorter, but the interesting question is why does it work. As I've explained above, all operators are just syntactic sugar for some expression with a head. `{a}` is `List[a]`. But `a` is a *sequence* (like I said, sort of like a splat in other languages) so if `a` is `1,-1,1` then we get `List[1,-1,1]`. Now postfix `!` is `Factorial`. So here, we'd get `Factorial[1,-1,1]`. But `Factorial` doesn't know what to do when it has a different number of arguments than one, so this simply remains unevaluated. `==` doesn't really care if the thing on both sides are lists, it just compares the expressions, and if they are equal it gives `True` (in this case, it won't actually give `False` if they aren't, but patterns don't match if the condition returns anything other than `True`). So that means, the equality check still works if there are at least two elements in the lists. What if there's only one? If `a` is `1` then `a!` is still `1`. If `a` is `-1` then `a!` gives `ComplexInfinity`. Now, comparing `1` to itself still works fine of course. But `ComplexInfinity == ComplexInfinity` remains unevaluated, and *doesn't* give true even though `a == -1 == b`. Luckily, this doesn't matter, because the only situation this shows up in is `PlusMinus[-1, -1]` which isn't a valid OVSF anyway! (If the condition did return `True`, the recursive call would report `False` after all, so it doesn't matter that the check doesn't work out.) We can't use the same trick for `{a}==-{b}` because the `-` wouldn't thread over `Factorial`, it only threads over `List`. The pattern matcher will take care of the rest and simply find the correct definition to apply. [Answer] ## Haskell, 57 bytes ``` q=length f l=l==until((>=q l).q)(\s->s++map(*l!!q s)s)[1] ``` Given input list `l`, grows a OVSF code `s` by starting from `[1]` and repeatedly concatenating either `s` or `-s`, whichever makes the first element match that of `l`. Then, checks that the result is `l` at the end. This is checked once `s` has length at least that of `l`. Some alternatives recursive structures also happened to give 57: ``` (s%i)l|length l<=i=s==l|j<-2*i=(s++map(*l!!i)s)%j$l [1]%1 q=length s%l|q s>=q l=s==l|r<-s++map(*l!!q s)s=r%l ([1]%) q=length g s l|q s<q l=g(s++map(*l!!q s)s)l|1>0=s==l g[1] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ ~~16~~ ~~14~~ 11 bytes ``` ^2/Eam2µḊ¿Ṭ ``` Outputs `[1]` (truthy) for OVSF codes, `[]` (falsy) otherwise. [Try it online!](https://tio.run/nexus/jelly#@x9npO@amGt0aOvDHV2H9j/cueb/4fZHTWsi//@P5lIAguhYHQhtCGPowlmGOgrIbFQJCMIUQdcDwQgKh0EIpbooanFZgls1JTpR5WK5YgE "Jelly – TIO Nexus") ### Background Like [@LuisMendo's MATL answer](https://codegolf.stackexchange.com/a/106409/12012) and [@xnor's Python answer](https://codegolf.stackexchange.com/a/106426/12012), this submission verifies the input array "from the inside out". Every (non-overlapping) pair of elements of a OVSF code of length two or higher is essentially a copy of the the first pair, either with the same signs or with both signs swapped. Likewise, every (non-overlapping) 4-tuple of elements of a OVSF code of length four or higher is essentially a copy of the the first 4-tuple, either with the same signs or with both signs swapped. The same is true for 8-tuples, 16-tuples, etc., up to the length of the OVFS code. One way to verify this is to check all pairs for equality modulo the sign first, then remove the second element of each pair (which is now redundant information). If we repeat this process once more, we're essentially checking all 4-tuples. In the next iteration, we're comparing 8-tuples, etc. Finally, if all the required 2k-tuples were equal modulo the sign and the array has been reduced to a singleton, it is sufficient to check if the remaining element is a **1**. ### How it works ``` ^2/Eam2µḊ¿Ṭ Main link. Argument: A (array of 1's and -1's) µḊ¿ While dequeuing A (removing its first element) yields a non-empty array, execute the monadic chain to the left, updating A with the return value after each iteration. ^2/ Compute the bitwise XOR of each non-overlapping pair of elements of A. Note that 1 ^ 1 = 0 = -1 ^ -1 and 1 ^ -1 = -2 = -1 ^ 1. For an array of even length that consists of the same pairs modulo the sign, this returns either an array of 0's or an array of -2's. If the length is odd, it will also contain the last element, which is either a 1 or a -1. E Test the elements of the result for equality. This yields 1 if the array consists solely of 0's or solely of -2's, 0 otherwise. a Take the logical AND of the previous result and every element of A. This returns A if it passed the previous test, but replaces all of its elements with 0's otherwise. m2 Modulo 2; select every second element of A, starting with the first. At this point, the last return value can be: • [ ] if the input was empty • [ 1] if the input was a valid OVSF code • [-1] if the input was the negative of a valid OVSF code. • [ 0] in all other cases. Ṭ Untruth; yield an array with 1's at the specified indices. Indexing is 1-based in Jelly, so [1] returns [1], the array with a 1 at index 1. Since the indices -1 and 0 are non-canonical, the arrays [-1] and [0] are mapped to []. The empty array remains empty. ``` [Answer] # MATLAB/[Octave](https://www.gnu.org/software/octave/), 94 bytes ``` function a=f(r);n=nnz(r);m=log2(n);a=0;if fix(m)-m==0;for c=hadamard(n);a=a+all(r==c');end;end ``` This is using a new approach: The allowed OVSF codes of length `N` appear in the `log2(N)`-th [Walsh-matrix](https://en.wikipedia.org/wiki/Walsh_matrix), as they are basically defined by the same recursion: ![](https://latex.codecogs.com/gif.latex?H%282%5Ek%29%20%3D%20H%282%29%5Cotimes%20H%282%5E%7Bk-1%7D%29) Walsh matrices are special cases of the [Hadamard-matrices](https://en.wikipedia.org/wiki/Hadamard_matrix) of size `N x N` if `N` is a power of two. (There are also Hadamard matrices of other sizes.) MATLAB and Octave have a variety of built in functions that generate test matrices to test properties of numerical algorithms, among them is `hadamard()`. Fortunately for powers of two MATLAB's `hadamard()` usex exactly the construction of the Welsh-matrices. So this function first checks whether the inputs length is a power of two, and if it is, it checks whether it is a row of the corresponding size Welsh-matrix. [Try it online!](https://tio.run/nexus/octave#dU1BCgIxELv7irmILbqgXsu8RDwM7dQttFOoLat@vlYPHhYMySEkIQUvpwP8OK30P7uazRaa@FxqE6ocn7AwWBLJFRz7IAy@ia0hC/gQ@Q4zF@6wgqDISxVtEsZ8OyvRhvBogh@jh0p6SjjsuAGLMzlKVNy3BEh7ilEVRLvThsV91Km/AQ "Octave – TIO Nexus") [Answer] ## Python, 64 bytes ``` f=lambda l:[]<l[1::2]==[x*l[1]for x in l[::2]]*f(l[::2])or[1]==l ``` Splits the list into even-indexed elements and odd-indexed elements via slices. Checks if the result vectors are either equals or negatives by multiplying one by the sign forced by its first element. Then, does the same recursive check on the even-indexed elements. For the base case, if the check fails, rejects unless the list is `[1]`. The empty list is also specifically rejected to avoid an infinite loop. A different strategy like [my Haskell answer](https://codegolf.stackexchange.com/a/106414/20260) gives 66 bytes: ``` f=lambda l,i=1,s=[1]:l[i:]and f(l,i*2,s+[x*l[i]for x in s])or s==l ``` [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), ~~431~~ 385 bytes * -46 bytes by creating a new stack with l-2 elements so I can remove the `2-` from many places. ``` l[bb01. >rl2=?vl3=?vl2%?vl2-2,[r0501. 0v=1:< 0 < < < << / 1 0 ?!^ v|.!]@{r/ v&,2-2l< >&:?!v1-&l2-[l2,[{]rl2,[}]rl2,1+[{$:@$:@=?!v}]] l2-, ~v&,2-2lr .c1r8+eer]]}< ^ 1<>&:?!v1-&l2-[l2,[{]rl2,[}]rl2,1+[{$:@$:@0$-=?!v}]]79. ^ 1~<.a10r .c1ra+eer]]}< n; >&1+&v >&:?!v1-&l4-2,[}]l4-[r]l4-2,[{]l4-[r] .r~< ``` [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoibFtiYjAxLlxuPnJsMj0/dmwzPT92bDIlP3ZsMi0yLFtyMDUwMS5cbiAgICAgIDB2PTE6PCAgICAwIFxuPCA8ICA8IDw8ICAgICAgIC9cbiAgMSAgMFxuICAgPyFeICB2fC4hXUB7ci9cbiB2JiwyLTJsPFxuID4mOj8hdjEtJmwyLVtsMixbe11ybDIsW31dcmwyLDErW3skOkAkOkA9PyF2fV1dXG4gbDItLCB+diYsMi0ybHIgICAgICAgICAgICAgICAgIC5jMXI4K2Vlcl1dfTxcbl4gICAgMTw+Jjo/IXYxLSZsMi1bbDIsW3tdcmwyLFt9XXJsMiwxK1t7JDpAJDpAMCQtPT8hdn1dXTc5LlxuXiAgICAgICAgIDF+PC5hMTByICAgICAgICAgICAgICAgICAgICAgICAuYzFyYStlZXJdXX08XG5uO1xuPiYxKyZ2XG4gICAgID4mOj8hdjEtJmw0LTIsW31dbDQtW3JdbDQtMixbe11sNC1bcl1cbiAgICAgICAucn48IiwiaW5wdXQiOiIiLCJzdGFjayI6IjEgMSAxIDEgLTEgLTEgLTEgLTEgMSAxIDEgMSAtMSAtMSAtMSAxIiwibW9kZSI6Im51bWJlcnMifQ==) This took me wayyyy to long. Checking if 2 lists are equal is a pain in ><> [![enter image description here](https://i.stack.imgur.com/a5App.png)](https://i.stack.imgur.com/a5App.png) This code loops to check if 2 lists are equal: ``` l2-[l2,[{]rl2,[}]rl2,1+[{$:@$:@=?!v}]] ``` Basically, what we do is: * `l` gets the length of the stack * `l-2` is the total length of both lists. So you see `l2-` all over. * `(l-2)/2` is the length of one list, so you see `l2-2,` all over too. * `l2-2,[{]` moves the top list to a new stack, shifts it left, then pushes it back to the old list. This means a new value is the top one. * To shift the other list, it's a bit more complex. Since there is no command to push the bottom of the stack to a new list. We use `l2-[3]l2-2,[}]l2-[r]`. Reverse both lists, then shift the top half right, then reverse both lists together again. * Now we need to check if the top of both lists are equal. We now take `(l-2)/2+1` elements, so the entire top list but 1 of the bottom list. Then we shift left to 1 item from the bottom list to the top. Now we use the `$:@$:@` trick to compare them. In either case we need to shift the list back. this is copied twice. There is also this: ``` >&1+&v >&:?!v1-&l4-2,[{]l4-[r]l4-2,[{]l4-[r] .r~< ``` Which resets the list after the checking process, only needed if the process was aborted halfway though (they where not equal) [Answer] ## JavaScript (ES6), ~~85~~ 61 bytes ``` a=>(l=a.length)&&!(l&l-1)&a.every((e,i)=>e==a[j=i&-i]*a[i-j]) ``` Previous version which checked elements to ensure that they were `1` or `-1`: ``` a=>(l=a.length)&&!(l&l-1)&a.every((e,i)=>i?(j=i&-i)<i?e==a[j]*a[i-j]:e==1|e==-1:e==1) ``` Explanation: * The length cannot be zero * The length must be a power of 2 * The first element must be 1 * Elements in positions that are a power of 2 must be either 1 or -1 * Elements in other positions are the product of all the elements in the positions corresponding to the bitmask, e.g. `a[22] == a[2] * a[4] * a[16]`. Since `a[20] == a[4] * a[16]` has already been checked, only `a[22] == a[2] * a[20]` needs to be checked. * The above check gives degenerate results for `i` not having at least two bits set. In the case of zero bits set, it checks that `a[0] == a[0] * a[0]`, which is false for `a[0] == -1`, while in the case of one bit set, it checks that `a[i] == a[0] * a[i]`. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 34 bytes Translation of Jonah's solution. ``` {~^*((#1_2\#x){(x,x),'x,-x}/,1)?x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6qui9PS0FA2jDeKUa7QrNao0KnQ1FGv0NGtqNXXMdS0r6jl4kqLVjSIVahTMACydAxBLEMQS9cQJmioABc1VNCFs3Wh4gYQNop6BRQ9SAIGUENACEogmwlTq4uEMHTjVEKKUiQxiOUA3aM/ng==) [Answer] # [Haskell](https://www.haskell.org/), ~~106 91 87~~ 86 bytes ``` g n|n<1=[[1]]|m<-g(n-1)=foldl(\a b->[b++map(0-)b,b++b]++a)[]m++m f l=elem l$g$length l ``` The function `g` generates the `n` iteration of lists (relatively inefficiently, since `length $ g n == 3^n`, however if we'd delete the duplicates, we'd get `2^n`), `f` checks if our list is in any one of them. Thanks to @Zgrab for a few hints! [Try it online!](https://tio.run/nexus/haskell#LYixDsIgGAZ3n@IbOkAoiezFJ3BzRAaIQE1@/jaKcem7I4PJJXe5XsAHL8Y6Z7w/6qKLYG2kzRs9SNwDor64qFQNuzhrGefR0SsVpPN17FMG2USpgqYyUeLSVlCv4cmw2D/t1l5XxoT3un2HMpyZ8cf3Hw "Haskell – TIO Nexus") [Answer] # JavaScript (ES6), ~~130~~ ~~93~~ ~~87~~ ~~85~~ 83 bytes ``` f=a=>(b=a.slice(0,l=a.length/2),c=a.slice(l)+"",a==1||l&&b==c|b.map(i=>-i)==c&f(b)) ``` ## Demo ``` f=a=>(b=a.slice(0,l=a.length/2),c=a.slice(l)+"",a==1||l&&b==c|b.map(i=>-i)==c&f(b)),[[],[1],[-1],[1,1],[1,-1],[1,1,1,1],[1,1,1,1,1],[1,-1,-1,1,-1,1,1,-1],[1,1,1,1,-1,-1,-1,-1,1,1,1,1],[1,1,1,1,-1,-1,-1,-1,1,1,1,1,1,1,1,1],[1,1,1,1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1]].map(a=>console.log(`[${a}] -> ${!!f(a)}`)) ``` [Answer] # APL, 46 bytes ``` {0::0⋄⍵≡,1:1⋄⍬≡⍵:0⋄(∇Z↑⍵)∧(∇Y)∨∇-Y←⍵↓⍨Z←.5×⍴⍵} ``` Fairly straightforward: * Base cases: + `0::0`: if an error occurs, return 0 + `⍵≡,1:1`: if the input is exactly `[1]`, return 1 + `⍬≡⍵:0`: if the input is the empty list, return 0 * Recursive case: + `Z←.5×⍴⍵`: `Z` is half the length of the input + `Y←⍵↓⍨Z`: `Y` is the last half of the input (this fails if `⍴⍵` is uneven, triggering the exception handler) + `(∇Y)∨∇-Y`: either the last half of the list, or the negation of the last half of the list, must be an OVSF code + `(∇Z↑⍵)∧`: and the first half of the list must be an OVSF code. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~21~~ 20 bytes ``` `2eZ}yy=&=tn1>hh]1X= ``` [Try it online!](https://tio.run/nexus/matl#@59glBpVW1lpq2Zbkmdol5ERaxhh@/9/tKGOAhzpomHccrEA) Or [verify all test cases](https://tio.run/nexus/matl#S/ifYJQaVVtZaatmW5JnaJeREWsYYfvfJeR/dCxXtCEQ64IIQx0FKAXnQhAKB0kRBCMoTJ0IVbooyrCYilshmZpQ5WIB). ### How it works The code splits the array into two equal-length pieces: the first with the odd-indexed entries, the second with the even-indexed entries. The two pieces are forced to have equal length, with a padding zero in the second if needed. Then the code checks that 1. The corresponding entries of the two pieces are either all equal or all different; 2. No entry in the second piece is zero; 3. The length of the pieces exceeds 1. If these three conditions are met, the process is applied again on the first piece. If the loop is exited because the length was already 1, the input is an OFSV code. Else it is not. Condition 1 iterated is an equivalent version of the defining property of OVSF codes. For an array of say length 8, the straightforward approach would be to check that entries 1,2,3,4 are all equal or all different to entries 5,6,7,8 respectively (this is the defining property). But we can equivalently check that entries 1,3,5,7 are all equal or all different to entries 2,4,6,8 respectively; and this turns out to use fewer bytes. Condition 2 makes sure that the input length is a power of 2: if it's not, a padding zero will be introduced at some stage. ``` ` % Do...while loop 2e % Reshape as a two-row matrix, with a padding zero if needed % Row 1 contains the original odd-indexed entries, row 2 the % even-indexed Z} % Split matrix into two vectors, one corresponding to each row yy % Duplicate those two vectors = % Check if corresponding entries are equal or not &= % Matrix of all pairwise comparisons. This will give a matrix % filled with ones if and only if the previous check gave all % true or all false (condition 1) tn1> % Duplicate and push true if size exceeds 1, or false otherwise % (condition 3) hh % Concatenate condition 1, condition 3, and the original copy of % the second piece (condition 2). The resulting vector is truthy % if and only if it doesn't contain any zero ] % End 1X= % True if top of the stack is a single 1, false otherwise ``` [Answer] # Haskell, 66 bytes Yay, infinite lists! ``` o=[1]:(o>>= \x->[x++map(0-)x,x++x]) f l=l`elem`take(2*2^length l)o ``` Alternative versions: ``` o=[1]:(o<**>map(>>=flip(++))[map(0-),id]) f=Data.List.Ordered.hasBy(comparing length)o ``` [Answer] # [J](http://jsoftware.com/), 31 bytes ``` e.,.@1(],.~,],.-)^:[~0>.2<.@^.# ``` [Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/U/V09BwMNWJ19Op0gISuZpxVdJ2BnZ6RjZ5DnJ7yf02u1OSMfJAGK4U0BaBRYK4hhKtjZYgirWMVb4iiwFBHAUMgHlVPPEINkggWc3QUMFQihLHaA8EICtNyZAPi0TARduLWgs9hRGlHlfsPAA "J – Try It Online") We build everything and check if the input is a member. * `0>.2<.@^.#` Tells us how many iterations to build: Base 2 log of the length of the list. This will be the exact number of iterations for truthy cases. To handle non-power-of-2 lengths, we take the floor. To handle empty lists, we take the max with 0. * `,.@1` Seed the iterations with a table containing just 1. * `(],.~,],.-)` Build the next iteration per the definition: Input zipped with itself `,.~` catted with `,` the input zipped with its negative `],.-`. * `e.` Is the input a member of that list? [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 41 bytes ``` f:{$[2>#x;x~,1;{f[x]&|/x~/:-:\y}.2 0N#x]} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6pWiTayU66wrqjTMbSuTouuiFWr0a+o07fStYqprNUzUjDwU66IreXiSotWNIhVqFMwALJ0DEEsQxBL1xAmaKgAFzVU0IWzdaHiBhA2inoFFD1IAgZQQ0AISiCbCVOri4QwdONUQopSJDGw5QB71kIP) [Answer] ## Haskell, ~~69~~ 68 bytes ``` g x=any(elem x)$scanr(\_->concat.mapM(\y->[y++y,y++map(0-)y]))[[1]]x ``` Usage example: `g [-1,1]` -> `False`. Even more inefficient than [@flawr's answer](https://codegolf.stackexchange.com/a/106386/34531). It takes too much time and memory for 4 element lists. To see that the list of OVSF codes (with a lot of duplicates) is actually created, try: ``` take 10 $ c $ scanr(\_->concat.mapM(\y->[y++y,y++map(0-)y]))[[1]] [1..4] ``` which returns ``` [[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,1,-1,-1,1], [1,1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,1,-1,-1], [1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1], [1,1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,1,-1,-1], [1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,1,-1,-1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1]] ``` i.e. the list starts with all 16 element lists (4 times concatenated, because of `[1..4]`), continues with all 8 element lists and so on until it ends with `[1]`. Edit: @xnor saved a byte. Thanks! [Answer] # [Python 2](https://docs.python.org/2/), ~~78~~ 75 bytes ``` def f(x):l=len(x)/2;return[n*x[l]*f(x[:l])for n in x[l:]]==x[:l]>[]or[1]==x ``` [Try it online!](https://tio.run/nexus/python2#nZDNCsMgDMfP21PkIq1FGd3RYV9EcptCQeywHfj2Vi3DCd1lkM9/fskh8akNmD5QYaXVLhW3@8Pr7e2dckNQFoc0VcIiNYsHB7ODpApEKYs8KVy8GnMbMxEyoZBB0lLgJY4MPrkKh7XdN3d4TSfLFeMNd3b4N/nvVjtDcb28/Ow26MgKfAKydkCgD6z8l8Yd "Python 2 – TIO Nexus") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes ``` ⁽y↔≬y*≈MA=h ``` [Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigb154oaU4omseSriiYhNQT1oIiwiIiwiWzEsIC0xLCAtMSwgMSwgLTEsIDEsIDEsIC0xLCAxLCAtMSwgLTEsIDEsIC0xLCAxLCAxLCAtMV0iXQ==) or [Test suite.](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4oG9eeKGlOKJrHkq4omITUE9aCIsIiIsIltdXG5bMV1cblstMV1cblsxLCAxXVxuWzEsIC0xXVxuWy0xLCAxXVxuWy0xLCAtMV1cblsxLCAxLCAxLCAxXVxuWzEsIDEsIDEsIDEsIDFdXG5bMSwgLTEsIC0xLCAxLCAtMSwgMSwgMSwgLTFdXG5bMSwgMSwgMSwgMSwgLTEsIC0xLCAtMSwgLTEsIDEsIDEsIDEsIDFdXG5bMSwgMSwgMSwgMSwgLTEsIC0xLCAtMSwgLTEsIDEsIDEsIDEsIDEsIDEsIDEsIDEsIDFdXG5bMSwgMSwgMSwgMSwgLTEsIC0xLCAtMSwgLTEsIDEsIDEsIDEsIDEsIC0xLCAtMSwgLTEsIC0xXSJd) Returns 1 for truthy and 0 for falsy. ## Explanation Essentially compares the odd indices to even indices, then applying it again with even indices, until arriving with an empty list. ``` ⁽y # a lambda that returns the even indices only ↔ # apply to the input until empty, returning a new list containing # the values each time it was applied. Includes the input ≬ # a lambda that: y # uninterleaves (pushes odd indices then even indices) * # multiplies (vectorises) # - in the case that the length of the input is not a power of two, # it pads a 0 to the shorter list ≈ # then checks if all are equal M # map to each element A # check if all are truthy = # is the number equal to the input? (vectorises) # - -1 is always 0 # - 0 never appears in the input # - 1 is 1 if it satisfies OVSF code, otherwise 0 # - an input of [] returns [] h # get first element # - [] outputs 0 # - [-1,...] outputs 0 # - [1,...] outputs 1 if it is valid ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 47 bytes ``` {$[x~,1;1;(1=#?x*|x)&c=2*(d:-2!c:#x);o(d#x);0]} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6pWia6o0zG0NrTWMLRVtq/QqqnQVEu2NdLSSLHSNVJMtlKu0LTO10gBUQaxtVxcIVYaigZcCjqGQKwLJAwVwASIqQtm60I4hhAIZ8CUgVVBCBSFUClduByKZiySxClCEtPk4nK1MgCKGYBlDBRgbDCLy7UuTT2ECwD7EjCF) [Answer] # JavaScript (ES6), 80 ``` f=(l,k=[1])=>l+l==k+k||l[k.length]&&f(l,k.concat(k))|f(l,k.concat(k.map(v=>-v))) ``` Recursively builds and check each list up to the length of the input list, starting with `[1]`. Return value is JS truthy or falsey, specifically `1` or `true` if valid, `0` or `false` or `undefined` if not valid. **Test** ``` f=(l,k=[1])=>l+l==k+k||l[k.length]&&f(l,k.concat(k))|f(l,k.concat(k.map(v=>-v))) test=`[] -> False [1] -> True [-1] -> False [1, 1] -> True [1, -1] -> True [1, 1, 1, 1] -> True [1, 1, 1, 1, 1] -> False [1, -1, -1, 1, -1, 1, 1, -1] -> True [1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1] -> False [1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1] -> False [1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1] -> True` .split('\n') test.forEach(r=>{ input = r.match(/-?1/g)||[] check = r.slice(-4) == 'True' result = f(input) console.log(result, check, '['+input+']') }) ``` [Answer] ## Clojure, 118 bytes ``` (defn f[C](or(=(count C)1)(let[l(/(count C)2)[a b](split-at l C)](and(> l 0)(=(count b)l)(apply =(map * a b))(f a))))) ``` Splits input `c` into two halves `a` and `b` and checks if their element-wise products are all identical. If so, checks that the first half is valid sequence. This one is 142 bytes but I found it more interesting: ``` #((set(nth(iterate(fn[I](mapcat(fn[i][(concat i i)(concat i(map - i))])I))[[1][-1]])(loop[l(count %)i 0](if(< l 2)i(recur(/ l 2)(inc i))))))%) ``` `loop` calculates `log_2` of input's length, `iterate` generates sequences of that many iterations based on the definition. This returns the input argument if it is a valid sequence and `nil` otherwise. [Answer] # [Rust](https://www.rust-lang.org), 150 bytes ``` |m|f(m,1);fn f(k:&[i8],u:i8)->bool{let m=k.len()/2;k!=&[]&&(k==&[u]||f(&k[..m],u)&&(&k[..m]==&k[m..]||(f(&k[m..],-u)&&(0..m).all(|i|k[i]==-k[i+m]))))} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=rZLBToNAEIYTj32KaQ9kV3dRPDU0qyefgpAGcWk2LLSBxZgAr-HFSw969-yb6NM4lE1rMa09uAFm4f-_mSX5X16LqjTr9ySHLFI5obWWBhbirTIJn34-N1mTkIx5dIaOhKS-E6hpyCpfTSm_uV8u9QbIROpqifjl9SwdCycIHYekAjdV2GAHJw1cN0OO4nf7gmoaZK6LBrJxdHvGN5YrNFA30po0qkkDhWaO5SILKa62P93X2UeyLIAYWZp5HJWSgXxaydjIh3khy0obCioHJxiBXeRRxuMgBAZJpEtJ2UDxOskU1W-Fe0coBodBFPlR1V4nWKzr4CG4vXfl1OE7lu_Bf448gf_fXvva4NdCqLdtu1T2IfC7lIKAxS4oblTOS61iSSidbZFVoXKj8zGZ1C3U_i0-WiB3NlLYoR7Eq6UTZocIcT4QGTg_gmnz2A9rR-2oj_B63ddv) [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), ~~96~~ 75 bytes ``` +[1]. +L:-append(A,B,L),A\=[],(A=B;A-B),+A. []-[]. [A|B]-[C|D]:-C is-A,B-D. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/XzvaMFaPS9vHSjexoCA1L0XDUcdJx0dTxzHGNjpWR8PR1snaUddJU0fbUY8rOlY3Gqg42rHGCchyrnGJtdJ1Vsgs1gXq0XXR@/8/RltBG6SCC2IqF5ivawgV0YEzkIR0oMJgpVA@skIQghIwfShKdZEQLuOwqEG3CLdCJDGgYj0A "Prolog (SWI) – Try It Online") *-15 bytes thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)!* [Answer] # [Haskell](https://www.haskell.org/), ~~85~~ 82 bytes *-3 bytes thanks to [@Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni)* ``` f[x]=x<0 f x|n<-length x`div`2,y<-take n x,z<-drop n x=n<1||y/=z&&y/=map(0-)z||f y ``` [Try it online!](https://tio.run/##rVE9a8MwEN39K95Qgg0SjTtLa6du7WYMEbVcmyiysZRENvrvrtLUbaKU0qGg0@npfXBwjTBbqdQ814UruWPrpIbzmlEl9Ztt4DZVe9g8kJFRK7YSGo5MjFZD15/eXLPc@/GeT6tVuHeiT9c0m7yvMc5WGvsqjDTgKBIgLUqCR6GMzMgHzAN@GfYLpHnME0SS8ENvXGfVpZEuujjtfG4yr6jIQz/ru/0wxGUGjeq38D@Y/iHgmlsmDxFlkgyn5dRowTl0Z9HBI21Jl4FRfG0wCHei1UHb7@2zHZ407mCa7hiaUApthWF@Bw "Haskell – Try It Online") Not too short but efficient. ]
[Question] [ Given some positive integer \$n\$ that is not a square, find the fundamental solution \$(x,y)\$ of the associated [Pell equation](https://en.wikipedia.org/wiki/Pell%27s_equation) $$x^2 - n\cdot y^2 = 1$$ ### Details * The fundamental \$(x,y)\$ is a pair of integers \$x,y\$ satisfying the equation where \$x\$ is minimal, and positive. (There is always the trivial solution \$(x,y)=(1,0)\$ which is not counted.) * You can assume that \$n\$ is not a square. ### Examples ``` n x y 1 - - 2 3 2 3 2 1 4 - - 5 9 4 6 5 2 7 8 3 8 3 1 9 - - 10 19 6 11 10 3 12 7 2 13 649 180 14 15 4 15 4 1 16 - - 17 33 8 18 17 4 19 170 39 20 9 2 21 55 12 22 197 42 23 24 5 24 5 1 25 - - 26 51 10 27 26 5 28 127 24 29 9801 1820 30 11 2 31 1520 273 32 17 3 33 23 4 34 35 6 35 6 1 36 - - 37 73 12 38 37 6 39 25 4 40 19 3 41 2049 320 42 13 2 43 3482 531 44 199 30 45 161 24 46 24335 3588 47 48 7 48 7 1 49 - - 50 99 14 51 50 7 52 649 90 53 66249 9100 54 485 66 55 89 12 56 15 2 57 151 20 58 19603 2574 59 530 69 60 31 4 61 1766319049 226153980 62 63 8 63 8 1 64 - - 65 129 16 66 65 8 67 48842 5967 68 33 4 69 7775 936 70 251 30 71 3480 413 72 17 2 73 2281249 267000 74 3699 430 75 26 3 76 57799 6630 77 351 40 78 53 6 79 80 9 80 9 1 81 - - 82 163 18 83 82 9 84 55 6 85 285769 30996 86 10405 1122 87 28 3 88 197 21 89 500001 53000 90 19 2 91 1574 165 92 1151 120 93 12151 1260 94 2143295 221064 95 39 4 96 49 5 97 62809633 6377352 98 99 10 99 10 1 ``` Relevant OEIS sequences: [A002350](https://oeis.org/A002350) [A002349](https://oeis.org/A002349) [A033313](https://oeis.org/A033313) [A033317](https://oeis.org/A033317) [Answer] # [Piet](http://www.dangermouse.net/esoteric/piet.html), 612 codels Takes *n* from standard input. Outputs *y* then *x*, space-separated. Codel size 1: [![Pell's equation program with codel size 1](https://i.stack.imgur.com/iP0yG.png)](https://i.stack.imgur.com/iP0yG.png) Codel size 4, for easier viewing: [![Pell's equation program with codel size 1](https://i.stack.imgur.com/B4t3B.png)](https://i.stack.imgur.com/B4t3B.png) ## Explanation Check out [this NPiet trace](https://i.stack.imgur.com/GnXxc.png), which shows the program calculating the solution for an input value of 99. I'm not sure whether I'd ever heard of Pell's equation before this challenge, so I got all of the following from Wikipedia; specifically, these sections of three articles: * [Pell's equation § Fundamental solution via continued fractions](https://en.wikipedia.org/wiki/Pell%27s_equation#Fundamental_solution_via_continued_fractions) * [Methods of computing square roots § Continued fraction expansion](https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Continued_fraction_expansion) * [Continued fraction § Infinite continued fractions and convergents](https://en.wikipedia.org/wiki/Continued_fraction#Infinite_continued_fractions_and_convergents) Basically, what we do is this: 1. Get \$n\$ from standard input. 2. Find \$\lfloor\sqrt n\rfloor\$ by incrementing a counter until its square exceeds \$n\$, then decrement it once. (This is the first loop you can see in the trace, at top left.) 3. Set up some variables for calculating \$x\$ and \$y\$ from the continued fraction of \$\sqrt n\$. 4. Check whether \$x\$ and \$y\$ fit Pell's equation yet. If they do, output the values (this is the downwards branch about 2/3 of the way across) and then exit (by running into the red block at far left). 5. If not, iteratively update the variables and go back to step 4. (This is the wide loop out to the right, back across the bottom, and rejoining not quite halfway across.) I frankly have no idea whether or not a brute-force approach would be shorter, and I'm not about to try it! [Okay, so I tried it.](https://codegolf.stackexchange.com/a/183368/13959) [Answer] # [Piet](http://www.dangermouse.net/esoteric/piet.html), 184 codels This is the brute-force alternative I said (in [my other answer](https://codegolf.stackexchange.com/a/183329/13959)) that I didn't want to write. It takes over 2 minutes to compute the solution for *n* = 13. I really don't want to try it on *n* = 29... but it checks out for every *n* up to 20, so I'm confident that it's correct. Like that other answer, this takes *n* from standard input and outputs *y* then *x*, space-separated. Codel size 1: [![Pell's equation program (brute-force variant) with codel size 1](https://i.stack.imgur.com/txxr0.png)](https://i.stack.imgur.com/txxr0.png) Codel size 4, for easier viewing: [![Pell's equation program (brute-force variant) with codel size 4](https://i.stack.imgur.com/vB634.png)](https://i.stack.imgur.com/vB634.png) ## Explanation Here's the [NPiet trace](https://i.stack.imgur.com/zUmrH.png) for an input value of 5. This is the most brutal of brute force, iterating over both \$x\$ and \$y\$. Other solutions might iterate over \$x\$ and then calculate \$y=\sqrt{\frac{x^2-1}{n}}\$, but they're *wimps*. Starting from \$x=2\$ and \$y=1\$, this checks whether \$x\$ and \$y\$ have solved the equation yet. If it has (the fork at the bottom near the right), it outputs the values and exits. If not, it continues left, where \$y\$ is incremented and compared to \$x\$. (Then there's some direction-twiddling to follow the zig-zag path.) This last comparison is where the path splits around the mid-left. If they're equal, \$x\$ is incremented and \$y\$ is set back to 1. And we go back to checking if it's a solution yet. I still have some whitespace available, so maybe I'll see if I can incorporate that square-root calculation without enlarging the program. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes ``` ;1↔;Ċz×ᵐ-1∧Ċ√ᵐℕᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/39rwUdsU6yNdVYenP9w6QdfwUcfyI12POmYBOY9apgLJ///NTf5HAQA "Brachylog – Try It Online") ### Explanation ``` ;1↔ Take the list [1, Input] ;Ċz Zip it with a couple of two unknown variables: [[1,I],[Input,J]] ×ᵐ Map multiply: [I, Input×J] -1 I - Input×J must be equal to 1 ∧ (and) Ċ√ᵐ We are looking for the square roots of these two unknown variables ℕᵐ And they must be natural numbers (implicit attempt to find values that match those constraints) ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 34 bytes PARI/GP almost has a built-in for this: `quadunit` gives the [fundamental unit](https://en.wikipedia.org/wiki/Fundamental_unit_(number_theory)) of the [quadratic field](https://en.wikipedia.org/wiki/Quadratic_field) \$\mathbb{Q}(\sqrt{D})\$, where \$D\$ is the [discriminant](https://en.wikipedia.org/wiki/Discriminant_of_an_algebraic_number_field) of the field. In other words, `quadunit(4*n)` solves the Pell's equation \$x^2 - n \cdot y^2 = \pm 1\$. So I have to take the square when its norm is \$-1\$. I don't know what algorithm it uses, but it even works when \$n\$ is not square-free. Answers are given in the form `x + y*w`, where `w` denotes \$\sqrt{n}\$. ``` n->(a=quadunit(4*n))*a^(norm(a)<0) ``` [Try it online!](https://tio.run/##DYtBCoAwDAS/Ej0l0kILHtWnCAGt5GCsUd9fs4c5DLOVTeJRW4EZmsYFeb4/3j6VF8dBiQZeUS87kWlK1MplqN7mADmlAFKwk@fxj@2oFKCa6OtJD3FxFJe@9gM "Pari/GP – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 46 bytes ``` FindInstance[x^2-y^2#==1&&x>1,{x,y},Integers]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773y0zL8Uzr7gkMS85Nboizki3Ms5I2dbWUE2tws5Qp7pCp7JWxzOvJDU9tag4Vu1/QFFmXomCQ3q0mWHs//8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ ~~16~~ 14 bytes Saved a byte thanks to *Kevin Cruijssen*. Outputs `[y, x]` ``` ∞.Δn*>t©1%_}®‚ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8vXNT8rTsSg6tNFSNrz207lHDrP//LY0B "05AB1E – Try It Online") **Explanation** ``` ∞ # from the infinite list of numbers [1 ...] .Δ } # find the first number that returns true under n # square * # multiply with input > # increment t© # sqrt (and save to register as potential x) 1% # modulus 1 _ # logical negation ®‚ # pair result (y) with register (x) ``` [Answer] # Java 8, ~~74~~ ~~73~~ 72 bytes ``` n->{int x=1;var y=.1;for(;y%1>0;)y=Math.sqrt(-x*~++x/n);return x+" "+y;} ``` -1 byte thanks to *@Arnauld*. -1 byte thanks to *@OlivierGrégoire*. [Try it online.](https://tio.run/##RY/BTsMwEETv/YolUiUHKyZB6gXj/kF74QgcjOOAS@oUexPFqsKvhw0t4rLWeux5Mwc96OJQf86m1THCTjt/XgE4jzY02ljYLyvAEwbn38GwuuvfWgs@l3Q/rWhE1OgM7MGDgtkX2zP9hlFVctABkhKVbLrAZFpX21LmSe00foj4FZAV4@035@MduQWLffAw8gwynuQ0y8X7RDDyviKGztVwpIjsEuf5FXR@ybcQFqxT9xLco9qUdHCe/4rUp2H/VJevqxtV/mlULkW0R9H1KE7ki61njmcPL5hxLwy9v5ad5h8) **Explanation:** ``` n->{ // Method with double parameter and string return-type int x=1; // Integer `x`, starting at 1 var y=.1; // Double `y`, starting at 0.1 for(;y%1>0;) // Loop as long as `y` contains decimal digits: y= // Set `y` to: Math.sqrt( // The square-root of: -x* // Negative `x`, multiplied by ~++x // `(-x-2)` (or `-(x+1)-1)` to be exact) // (because we increase `x` by 1 first with `++x`) /n); // Divided by the input return x+" "+y;} // After the loop, return `x` and `y` with space-delimiter as result ``` [Answer] # R, ~~66~~ ~~56~~ ~~54~~ ~~53~~ ~~52~~ ~~47~~ 45 bytes a full program ``` n=scan();while((x=(1+n*T^2)^.5)%%1)T=T+1;x;+T ``` ~~-1 -2~~ thanks to @Giuseppe -7 thanks to @Giuseppe & @Robin Ryder -2 @JAD [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 40 bytes ``` ½©%1İ$<®‘¤$п¹;Ḋ$LḂ$?Ḟṭ@ṫ-ṚZæ.ʋ¥ƒØ.,U¤-ị ``` [Try it online!](https://tio.run/##AW8AkP9qZWxsef//wr3CqSUxxLAkPMKu4oCYwqQkw5DCv8K5O@G4iiRM4biCJD/huJ7hua1A4bmrLeG5mlrDpi7Ki8KlxpLDmC4sVcKkLeG7i/8s4oCcIC0@IOKAnSzDh8WS4bmYJAoxNTBSw4figqxZ//8 "Jelly – Try It Online") An alternative Jelly answer, less golfy but more efficient algorithmically when x and y are large. This finds the convergents of the regular continued fraction that approximate the square root of n, and then checks which solve the Pell equation. Now correctly finds the period of the regular continued fraction. Thanks to @TimPederick, I’ve also implemented an integer-based solution which should handle any number: # [Jelly](https://github.com/DennisMitchell/jelly), 68 bytes ``` U×_ƭ/;²®_$÷2ị$}ʋ¥µ;+®Æ½W¤:/$$ ¹©Æ½Ø.;ÇƬṪ€F¹;Ḋ$LḂ$?ṭ@ṫ-ṚZæ.ʋ¥ƒØ.,U¤-ị ``` [Try it online!](https://tio.run/##AaIAXf9qZWxsef//VcOXX8atLzvCssKuXyTDtzLhu4skfcqLwqXCtTsrwq7DhsK9V8KkOi8kJArCucKpw4bCvcOYLjvDh8as4bmq4oKsRsK5O@G4iiRM4biCJD/hua1A4bmrLeG5mlrDpi7Ki8KlxpLDmC4sVcKkLeG7i/8ww4fDhsKyPwos4oCcIC0@IOKAnSzDh8WS4bmYJAo1MDBSw4figqxZ//8 "Jelly – Try It Online") For example, the [solution for 1234567890](https://tio.run/##AYYAef9qZWxsef//VcOXX8atLzvCssKuXyTDtzLhu4skfcqLwqXCtTsrwq7DhsK9V8KkOi8kJArCucKpw4bCvcOYLjvDh8as4bmq4oKsRsK5O@G4iiRM4biCJD/hua1A4bmrLeG5mlrDpi7Ki8KlxpLDmC4sVcKkLeG7i//Dh///MTIzNDU2Nzg5MA) has 1936 and 1932 digits for the numerator and denominator respectively. [Answer] # JavaScript (ES7), 47 bytes ``` n=>(g=x=>(y=((x*x-1)/n)**.5)%1?g(x+1):[x,y])(2) ``` [Try it online!](https://tio.run/##DchBDoIwEEbhPaf4N5CZFqo14kKtHsS4IAgEQ6YGjCkxnr12877kPZtPs7Tz@HpX4h9d7F0Ud6HBhdTVEQUVKssbYaVMzbm9DhS05eMtlOudacex9zMJHOwJgjP2h6TWjG@GNJTC1tTIYVEUaL0sfurM5AeSEj0Jc/aLfw "JavaScript (Node.js) – Try It Online") Below is an alternate **49-byte** version which keeps track of \$x²-1\$ directly instead of squaring \$x\$ at each iteration: ``` n=>[(g=x=>(y=(x/n)**.5)%1?1+g(x+=k+=2):2)(k=3),y] ``` [Try it online!](https://tio.run/##DcjBCoJAEAbgu0/xX5KZXbPWskM19iDRQUyllNnQCCV69s3TB9@z/JRjNTxe77X6ex0aCSrFlVqZpKBZaNooG5PmvHIXZ1uarHRWMj5mTJ3sOJlvofEDKQTuBMUZ@8OitYxvhCWMwTbNsYJDHKPyOvq@TnvfkiZoSJmjX/gD "JavaScript (Node.js) – Try It Online") Or we can go the non-recursive way for **50 bytes**: ``` n=>eval('for(x=1;(y=((++x*x-1)/n)**.5)%1;);[x,y]') ``` [Try it online!](https://tio.run/##FcpBDoIwEEbhPaf4N8BMC2gXuKn1IsYFQTCaZkrAkBLj2ausXvLlvbq1W/r5Ob1rCfchjS6Juwxr56kcw0zRGUubI9I6qlgbPggr1bScG8v2GqvtVnLaT4GDsRCccdqrNeOT4Q9K4di0yGFQFOiDLMEPjQ8PkgojCXP2TT8 "JavaScript (Node.js) – Try It Online") [Answer] # TI-BASIC, ~~44~~ ~~42~~ 41 bytes ``` Ans→N:"√(N⁻¹(X²-1→Y₁:1→X:Repeat not(fPart(Ans:X+1→X:Y₁:End:{X,Ans ``` Input is \$n\$. Output is a list whose values correspond to \$(x,y)\$. Uses the equation \$y=\sqrt{\frac{x^2-1}{n}}\$ for \$x\ge2\$ to calculate the fundamental solution. The current \$(x,y)\$ pair for that equation is a fundamental solution iff \$y\bmod1=0\$. **Examples:** ``` 6 6 prgmCDGF12 {5 2} 10 10 prgmCDGF12 {19 6} 13 13 prgmCDGF12 {649 180} ``` **Explanation:** ``` Ans→N:"√(N⁻¹(X²+1→Y₁:1→X:Repeat not(fPart(Ans:X+1→X:Y₁:End:{X,Ans ;full logic Ans→N ;store the input in "N" "√(N⁻¹(X²+1→Y₁ ;store the aforementioned ; equation into the first ; function variable 1→X ;store 1 in "X" Repeat not(fPart(Ans End ;loop until "Ans" is ; an integer X+1→X ;increment "X" by 1 Y₁ ;evaluate the function ; stored in this variable ; at "X" and leave the ; result in "Ans" {X,Ans ;create a list whose ; values contain "X" and ; "Ans" and leave it in ; "Ans" ;implicitly print "Ans" ``` --- **Note:** TI-BASIC is a tokenized language. Character count does ***not*** equal byte count. [Answer] # [MATL](https://github.com/lmendo/MATL), 17 bytes ``` `@:Ut!G*-!1=&fts~ ``` [Try it online!](https://tio.run/##y00syfn/P8HBKrRE0V1LV9HQVi2tpLju/38jCwA "MATL – Try It Online") ### Explanation The code keeps increasing a counter *k* = 1, 2, 3, ... For each *k*, solutions *x*, *y* with 1 ≤ *x* ≤ *k*, 1 ≤ *y* ≤ *k* are searched. The process when some solution if found. This procedure is guaranteed to find only one solution, which is precisely the fundamental one. To see why, note that 1. Any solution *x*>0, *y*>0 for *n*>1 satisfies *x*>*y*. 2. If *x*,*y* is a solution and *x*',*y*' is a different solution then necessarily *x*≠*x*' *and* *y*≠*y*'. As a consequence of 1 and 2, * When the procedure stops at a given *k*, only *one* solution exists for that *k*, because if there were two solutions one of them would been found earlier, and the process would have stopped with a smaller *k*. * This solution is the fundamental one, because, again, if there were a solution with smaller *x* it would have been found earlier. ``` ` % Do...while @:U % Push row vector [1^2, 2^2, ..., k^2] where k is the iteration index t! % Duplicate and transpose. Gives the column vector [1^2; 2^2; ...; k^2] G* % Multiply by input n, element-wise. Gives [n*1^2; n*2^2; ...; n*k^2] - % Subtract with broadcast. Gives a square matrix of size n ! % Transpose, so that x corresponds to row index and y to column index 1=&f % Push row and column indices of all entries that equal 1. There can % only be (a) zero such entries, in which case the results are [], [], % or (b) one such entry, in which case the results are the solution x, y ts~ % Duplicate, sum, negate. This gives 1 in case (a) or 0 in case (b) % End (implicit). Proceed with next iteration if top of the stack is true; % that is, if no solution was found. % Display (implicit). The stack contains copies of [], and x, y on top. % The empty array [] is not displayed ``` [Answer] # [Python 2](https://docs.python.org/2/), 49 bytes ``` a=input()**.5 x=2 while x%a*x>1:x+=1 print x,x//a ``` [Try it online!](https://tio.run/##JYzBDsIgEAXvfMVKQtJWYoVoDyT4L2ipJWm3hGBcvx6pHt9k5sVPnjfUZdoSIASE5PDpGyUH1RoGYQLsutNVqIM9112N@Mp2cet9dAYriClgBi70aLhAWYkn/@CcF2d/ctPuB4ysZu85LB5IuI5uytDRKvbPSVLfu7JXl@EL "Python 2 – Try It Online") Finds `x` as the smallest number above 1 where `x % sqrt(n) <= 1/x`. Then, finds `y` from `x` as `y = floor(x / sqrt(n))`. [Answer] # [Haskell](https://www.haskell.org/), 46 bytes A straightforward brute force search. This makes use of the fact that a fundamental solution \$(x,y)\$ satisfying \$x^2 - ny^2 = 1 \$ must have \$y \leq x\$. ``` f n=[(x,y)|x<-[1..],y<-[1..x],x^2-n*y^2==1]!!0 ``` [Try it online!](https://tio.run/##Jca9DkAwFAbQV7kSA/JV3IqfQb1IU4mBEDSCoU28ew3OdJbx3qZ9D2Emq3Ti4NPXdUJznhv4P87ADVLYzA9SKTZRVIRjXC0pOq/VPhTTTF3ck5YoUaFGgxZcgBkswaUJHw "Haskell – Try It Online") [Answer] # C# (Visual C# Interactive Compiler), ~~70~~ 69 bytes ``` n=>{int x=1;var y=.1;for(;y%1>0;)y=Math.Sqrt(-x*~++x/n);return(x,y);} ``` Port of [my Java 8 answer](https://codegolf.stackexchange.com/a/183305/52210), but outputs a tuple instead of a string to save bytes. [Try it online.](https://tio.run/##RYzBCoJAFEX3fsVLEGYaNQ3a9ByXrWrVok0bs5EexEjjGCNRvz4pBq0OXO45dZfUHfldr@vi2vaXu4rZjzN4CQ1Ir2X5Im3ByRyflYFBpjk2rWE4RHmZIR/kobK39PgwliVu@RHCrTRHo2xvNHPxwPHtMZiUOQwk1whUyE02QggeAFDD/hXiUb6Q2bQDnAxZtSetGIlwe7ahaMYDR/8F) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` ‘ɼ²×³‘½µ⁺%1$¿;® ``` [Try it online!](https://tio.run/##ASkA1v9qZWxsef//4oCYybzCssOXwrPigJjCvcK14oG6JTEkwr87wq7///8yOQ "Jelly – Try It Online") A full program that takes a single argument `n` and returns a tuple of `x, y`. [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` ḟΛ¤ȯ=→*⁰□π2N ``` [Try it online!](https://tio.run/##ASIA3f9odXNr///huJ/Om8KkyK894oaSKuKBsOKWoc@AMk7///81 "Husk – Try It Online") ## Explanation ``` ḟΛ¤ȯ=→*⁰□π2N Input is n, accessed through ⁰. N Natural numbers: [1,2,3,4,.. π2 2-tuples, ordered by sum: [[1,1],[1,2],[2,1],[1,3],[2,2],.. ḟ Find the first that satisfies this: Λ All adjacent pairs x,y satisfy this: ¤ □ Square both: x²,y² ȯ *⁰ Multiply second number by n: x²,ny² → Increment second number: x²,ny²+1 = These are equal. ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 12 bytes ``` ökî²*)_°▼Þ√î ``` [Try it online!](https://tio.run/##ASgA1/9tYXRoZ29sZv//w7Zrw67CsiopX8Kw4pa8w57iiJrDrv//MTAKMjL/ "MathGolf – Try It Online") I'm throwing a Hail Mary when it comes to the output formatting. If it's not allowed, I have a solution which is 1 byte longer. The output format is `x.0y`, where `.0` is the separator between the two numbers. ## Explanation ``` ö ▼ do-while-true with popping k read integer from input î² index of current loop (1-based) squared * multiply the two ) increment (gives the potential x candidate _ duplicate TOS ° is perfect square Þ discard everything but TOS √ square root î index of previous loop (1-based) ``` I took some inspiration from Emigna's 05AB1E answer, but was able to find some improvements. If the separator I chose is not allowed, add a space before the last byte for a byte count of 13. [Answer] # APL(NARS), 906 bytes ``` r←sqrti w;i;c;m m←⎕ct⋄⎕ct←0⋄r←1⋄→3×⍳w≤3⋄r←2⋄→3×⍳w≤8⋄r←w÷2⋄c←0 i←⌊(2×r)÷⍨w+r×r⋄→3×⍳1≠×r-i⋄r←i⋄c+←1⋄→2×⍳c<900⋄r←⍬ ⎕ct←m r←pell w;a0;a;p;q2;p2;t;q;P;P1;Q;c;m r←⍬⋄→0×⍳w≤0⋄a0←a←sqrti w⋄→0×⍳a≡⍬⋄m←⎕ct⋄⎕ct←0⋄Q←p←1⋄c←P←P1←q2←p2←0⋄q←÷a L: t←p2+a×p⋄p2←p⋄p←t t←q2+a×q :if c≠0⋄q2←q⋄:endif q←t P←(a×Q)-P →Z×⍳Q=0⋄Q←Q÷⍨w-P×P →Z×⍳Q=0⋄a←⌊Q÷⍨a0+P c+←1⋄→L×⍳(1≠Qׯ1*c)∧c<10000 r←p,q :if c=10000⋄r←⍬⋄:endif Z: ⎕ct←m ``` Above there are 2 functions sqrti function that would find the floor square root and pell function would return Zilde for error, and is based reading the page <http://mathworld.wolfram.com/PellEquation.html> it would use the algo for know the sqrt of a number trhu continue fraction (even if i use one algo for know sqrt using newton method) and stop when it find p and q such that ``` p^2-w*q^2=1=((-1)^c)*Qnext ``` Test: ``` ⎕fmt pell 1x ┌0─┐ │ 0│ └~─┘ ⎕fmt pell 2x ┌2───┐ │ 3 2│ └~───┘ ⎕fmt pell 3x ┌2───┐ │ 2 1│ └~───┘ ⎕fmt pell 5x ┌2───┐ │ 9 4│ └~───┘ ⎕fmt pell 61x ┌2────────────────────┐ │ 1766319049 226153980│ └~────────────────────┘ ⎕fmt pell 4x ┌0─┐ │ 0│ └~─┘ ⎕fmt pell 7373x ┌2───────────────────────────────────────────────────────────┐ │ 146386147086753607603444659849 1704817376311393106805466060│ └~───────────────────────────────────────────────────────────┘ ⎕fmt pell 1000000000000000000000000000002x ┌2────────────────────────────────────────────────┐ │ 1000000000000000000000000000001 1000000000000000│ └~────────────────────────────────────────────────┘ ``` There is a limit for cycles in the loop in sqrti function, and a limit for cycles for the loop in Pell function, both for the possible case number are too much big or algo not converge... (I don't know if sqrti converge every possible input and the same the Pell function too) [Answer] # [Groovy](http://groovy-lang.org/), 53 bytes ``` n->x=1;for(y=0.1d;y%1>0;)y=((++x*x-1)/n)**0.5;x+" "+y ``` [Try it online!](https://tio.run/##BcFBCoAgEADAu68QIVAXzT10kvU1YXTRkIhdorfbzDF6f2RWemcLhQlz7cMKpYh7lgVLyk7IWgD2HNCtzXmf4pYZjDYg81PqGme7dbWY3PwB "Groovy – Try It Online") Port of [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s Java and C# answers [Answer] # Pyth, 15 bytes ``` fsIJ@ct*TTQ2 2J ``` Try it online [here](https://pyth.herokuapp.com/?code=fsIJ%40ct%2ATTQ2%202J&input=31&debug=0). Output is `x` then `y` separated by a newline. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes ``` {1//.y_/;!NumberQ[x=√(y^2#+1)]:>y+1,x}& ``` `√` is the 3-byte Unicode character #221A. Outputs the solution in the order (y,x) instead of (x,y). As usual with the imperfect `//.` and its limited iterations, only works on inputs where the true value of `y` is at most 65538. [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277v9pQX1@vMl7fWtGvNDcptSgwusL2Uccsjco4I2VtQ81YK7tKbUOdilq1/wFFmXklCg7p0YaWsf//AwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [><>](https://esolangs.org/wiki/Fish), 45 bytes ``` 11v +$\~:1 :}/!?:-1v?=1-*}:{*:@:{*: $ naon;> ``` [Try it online!](https://tio.run/##S8sszvj/39CwjEtbJabOypDLqlZf0d5K17DM3tZQV6vWqlrLygFEcKkoKOQl5udZ2/3//1@3TMEUAA "><> – Try It Online") Brute force algorithm, searching from `x=2` upwards, with `y=x-1` and decrementing on each loop, incrementing `x` when `y` reaches 0. Output is `x` followed by `y`, separated by a newline. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 69 bytes ``` n=>{for(int x=2,y;;x++)for(y=0;y<=x;y++)if(x*x-y*y*n==1)return(x,y);} ``` [Try it online!](https://tio.run/##NYwxC8IwEIX3/opYEJKmlbbg4vU6Ounk4OIipaG3RExTyCH@9pgKfXD34Lt7b5irYaZ4XuzQkfWlXFca1RuMFvuPebmViYBtyQBBa7Uixhq4wwCcABkZilBxwYVFbJQb/eKsDCUr@EbItg7CFgR1eKyTpVwm/krx69NPh9vbeUlq3@yw3m5C3B358UJ2lKTz08Pn2qQnBfEH "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 75 bytes ``` lambda i:next((x,y)for x in range(2,i**i)for y in range(x)if~-x**2==i*y**2) ``` [Try it online!](https://tio.run/##RczBasMwEEXRX9FSErfgmZFjO@AvabpQadwKWicYL@RNf91xuunqweHy7tv6dZttn8bL/p1/3j@yK@f5WlfvK1uYbourrsxuyfPn1SslxvKn27/WUKbflxqjjmOJ27Fhfyb5mbwqRsuJjh5pEEEUMSQhLdIhhw9ogwqqqKEJPaEd2qMD1mCCHUeGJazFOqzHBlJDEpKSjJRI7dvZ3Zcyrz7jJp9D2B8 "Python 3 – Try It Online") # Explanation Brute force. Using $$x<i^i$$ as an upper search bound, which is well below [the definite upper limit of the fundamental solution to Pell's equation](https://math.stackexchange.com/questions/1904192/bounding-fundamental-solution-of-the-pell-equation) $$x\leq i!$$ This code would also run in Python 2. However, the range() function in Python 2 creates a list instead of a generator like in Python 3 and is thus immensely inefficient. --- With inifinte time and memory, one could use a list comprehension instead of the iterator and save 3 bytes like so: # [Python 3](https://docs.python.org/3/), 72 bytes ``` lambda i:[(x,y)for x in range(i**i)for y in range(x)if~-x**2==i*y**2][1] ``` [Try it online!](https://tio.run/##RczNaoNAGIXhW5mlDm/B78eoAa/EupiQ2g60JkgWusmtW9NNVwceXs59e3zdZtun/n3/Tj@Xawr5PBQrWzndlrCGPIclzZ8fRY4x/9n2b2uZp@fbGqP2fY7bseMg4/6q0qsaFKPmREOLVIggihjiSI00yOEdWqGCKmqooye0QVu0wypMsOPIMMdqrMFarMMrXHDFDXe8Hs/hvuT5USTCVKSy3H8B "Python 3 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 64 bytes ``` f=lambda n,x=2,y=1:x*x-n*y*y-1and f(n,x+(x==y),y*(y<x)+1)or(x,y) ``` [Try it online!](https://tio.run/##DcrBCoAgDADQX/G4mR6MDhHtYwyRgloiBtvXm@f3irbz5bn3THd8jhQNO6HZKYVNrHi2atWHyMlkGDSBECk6taC74BTwrSBOsZd6cRvp4vI1QOzL@gM "Python 2 – Try It Online") Returns `(x, y)`. ]
[Question] [ Consider a grammar over the alphabet **{**`0`**,** `1`**,** `?`**,** `:`**}** defined by the [production rule](https://en.wikipedia.org/wiki/Production_(computer_science)#Grammar_generation) > > s → `0` ┃ `1` ┃ `0` `?` s `:` s ┃ `1` `?` s `:` s > > > Given a string generated from *s*, parse it as an expression where `?:` is right-associative (for example, `a?B?X:Y:c?d:e?f:g` means `a?(B?X:Y):(c?d:(e?f:g))`) and evaluate it with the following semantics: ``` eval(0) = 0 eval(1) = 1 eval(0?a:b) = eval(b) eval(1?a:b) = eval(a) ``` If the result is **0**, output some fixed value; if the output is **1**, output a different fixed value. Specify your chosen output values (e.g. `0`/`1`, or `False`/`True`) in your answer. ## Test cases ``` 0 -> 0 1 -> 1 0?0:1 -> 1 0?1:0 -> 0 1?0:1 -> 0 1?1:0 -> 1 0?1?0:1:1 -> 1 1?0?1:1:1 -> 1 1?0:1?0:1?1:1 -> 0 1?1?1:0?1?0:0:0:0 -> 1 1?0:1?0?1:1?1:0:1?1?1:1:1?0:1 -> 0 1?1?1:0?0?1:1:0?1:0:1?1?0?0:0:1?1:0:0?1?0:1:1?0:1 -> 1 0?0?1?0?0:1:0?0:0:0?0?1:1:1?0:1:0?0?0?1:0:0?1:1:1?1?0:1:1 -> 0 ``` ## Rules * You may not use language built-ins that interpret strings as code in some [programming language](http://meta.codegolf.stackexchange.com/a/2073/3852) and run it (such as JavaScript/Perl/Ruby/Python’s `eval`). * That said, your code doesn’t *actually* have to parse and then evaluate the input string. You can take any approach the achieves equivalent results and doesn’t violate the previous rule. * Your program will be checked against `perl -le 'print eval<>'`. * The shortest code (in bytes) wins. [Answer] ## [Retina](https://github.com/m-ender/retina/), 23 bytes ``` r-1=+`0\?.:|1\?(.):. $1 ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYApyLTE9K2AwXD8uOnwxXD8oLik6LgokMQ&input=MAoxCjA_MDoxCjA_MTowCjE_MDoxCjE_MTowCjE_MDoxPzA6MT8xOjEKMT8xPzE6MD8xPzA6MDowOjAKMT8wOjE_MD8xOjE_MTowOjE_MT8xOjE6MT8wOjEKMT8xPzE6MD8wPzE6MTowPzE6MDoxPzE_MD8wOjA6MT8xOjA6MD8xPzA6MToxPzA6MQowPzA_MT8wPzA6MTowPzA6MDowPzA_MToxOjE_MDoxOjA_MD8wPzE6MDowPzE6MToxPzE_MDoxOjE) (The first line enables a linefeed-separated test suite.) ### Explanation It's fairly simple actually. The input is reduced to the result by repeatedly (`+`) evaluating ternaries that contain only literals. To make sure this is done right-associatively, we look for matches from right to left (`r`) and replace only the last match we find (`-1=`). The regex itself either matches `0\?.:` and removes it (leaving only the stuff after `:`) or `1\?.:.` and replaces it with the value after the `?`. [Answer] # Haskell, ~~106 101 100 90~~ 83 bytes This heavily relies on pattern Haskell's pattern matching capabilities. First of all, we reverse the string such that we can just seach for the first occurence of `b:a?x` (which would normally read as `x?a:b`) and replace it with it's value. This automatically provides the *right associativity*. Here we make use of `x:xs` pattern. This is what the function `f` is doing. Then we basically apply `f` to it's output over and over again, until we have a single number (0 or 1) left. Thanks @Lynn for 12 bytes! ``` f(b:':':a:'?':x:l)|x>'0'=a:l|1>0=b:l f(x:l)=x:f l f x=x until((<2).length)f.reverse ``` [Answer] ## Brainfuck, ~~82~~ ~~64~~ 63 bytes ``` + [ ,>>,> +++++++[<---<<-[------>>]<-] << [ ->[<++>[+]] ] +>[>>] <<<- ] <. ``` The output is `\xff` for `0` and `\x00` for `1`. The brainfuck implementation must allow going to the left of the starting cell. This uses essentially the same approach as xsot's Python [answer](https://codegolf.stackexchange.com/a/89882/2537), but the branching is probably harder to follow compared with my initial 82-byte submission: ``` - [ + [ ->,,>+++++++[<--------->-] <[<++>[+]] < ] ,->,>+++++++[<[-------<]>>-->-] <[<] < ] >>. ``` (For this solution, the output is `\xfe` for `0` and `\xff` for `1`, and wider compatibility is achieved when the input ends with a newline.) If you can't be bothered to analyse xsot's solution, the idea is this: Proceed from left to right. If you see `1?` then greedily discard it. If you see `0?` then discard everything between that and the corresponding `:`. When `?` does not appear as the second character, stop looping and print the first character of the remaining string. So, the 82-byte solution actually mirrors that scheme pretty closely. The inner loop handles `0?`, just like xsot's inner loop. Some care is taken in order to enter the main loop without checking any input characters; i.e., we want to check whether the second character is `?` just once at the end of the main loop, and not also at the beginning before entering the main loop. The 63-byte solution essentially combines the inner and outer loops into one, which I suspected was possible given the similarity between those loops. The memory layout in the main loop could be described as: ``` [s] d c ``` where `[x]` means current cell -- the `s` starts as a dummy nonzero value that just indicates we are still looping, and is immediately overwritten with an input character (either `0` or `1`). The `d` cell holds the (negative) depth in case we are in the middle of a `0?`, otherwise `0`. The `c` is going to be either `?` or `:` or newline or EOF. After updating `s` and `c`, we handle the `0?` case by updating `d` accordingly and adjusting the pointer, otherwise we use the current value of `c` as the value of `d` in the next iteration, or stop if we are done. [Answer] ## Python 2, ~~76~~ ~~74~~ ~~73~~ 72 bytes ``` a=`id` for c in input()[::-1]:a=(c+a,a[ord(c)*7%9]+a[4:])[a>'?'] print a ``` With input as string literal to avoid `raw_`. The output is `0` or `1` followed by `<built-in function id>`. [Answer] ## GolfScript, 21 bytes ``` 2/-1%{)2%{0`=@@if}*}/ ``` This outputs `0` or `1`. Input is assumed to have a single trailing newline. Using `~` (which evaluates strings) would save a byte: ``` 2/-1%{)2%{~!@@if}*}/ ``` This is based on <http://golf.shinh.org/reveal.rb?The+B+Programming+Language/tails_1462638030&gs> . [Answer] # Python 2, 89 bytes ``` s=input() while'?'<=s[1:]: n=s<'1' while n:s=s[2:];n+=-(s[1]<'?')|1 s=s[2:] print s[0] ``` Input is taken as a string literal. [Answer] ## [Grime](https://github.com/iatorm/grime), ~~34~~ 31 bytes ``` E=d|d\?E.E e`\1|\1\?_.E|\0\?E._ ``` Prints `1` for truthy inputs and `0` for falsy ones. [Try it online!](http://grime.tryitonline.net/#code=RT1kfGRcP0UuRQplYFwxfFwxXD9fLkV8XDBcP0UuXw&input=MT8xPzE6MD8xPzA6MDowOjA) The last test case unfortunately runs out of memory on TIO. ## Explanation The right-associativity essentially means that in `a?b:c`, `a` is always either `0` or `1`, never a longer expression. I'll just recursively define a pattern that matches a truthy expression like that, and check the input against it. It's also unnecessary to check that every `:` is really a `:`, if the `?`s are all checked: there is an equal number of `?`s and `:`s in the input, and if some `?` is incorrectly classified as a `:`, the corresponding `:` will fail to match, and Grime's matching engine will backtrack. ``` E=d|d\?E.E E= Define nonterminal E (for "expression") as d| a digit, OR d a digit, \? a literal ?, E a match of E, . any character (will match a :), and E another match of E. e`\1|\1\?_.E|\0\?E._ e` Match entire input against this pattern (truthy expression): \1| a literal 1, OR \1\? a literal 1?, _ a recursive match of truthy expression, . any character (will match a :), and E| any expression, OR \0\?E._ the same, but with 0 in front, and _ and E swapped. ``` [Answer] # Haskell, ~~79 71 70 62 60~~ 56 bytes **Edit:** Thanks to @Zgarb for 3 bytes and to @nimi for 4 bytes! ``` e(x:'?':r)|a:_:s<-e r=last$e s:[a:tail(e s)|x>'0'] e x=x ``` This a recursive approach ~~that somewhat abuses the "some fixed value"-output rule~~. Edit: Getting rid of the tuples doesn't only save 8 bytes, it also yields a nicer output: `"0"` or `"1"`. **Ungolfed version:** ``` eval (x:'?':r1) = if x=='1' then (a, r3) else (b, r3) where (a,':':r2) = eval r1 (b, r3) = eval r2 eval (x:r) = (x,r) ``` **How does it work?** The `eval` function traverses the implicit tree of the expressions ``` eval 1?0?0:1:0?1:0 -> eval 1? : eval 0?0:1 eval 0?1:0 ``` and returns a tuple of the form `(result, rest)`. The first pattern `(x:'?':r1)` matches `x` to `'1'` and `r1` to `"0?0:1:0?1:0"`. Recursively applying `eval` to `r1` evaluates the sub-expression `0?0:1` and returns `(0,":0?1:0")`. Matching this to the pattern `(a,':':r2)` yields `a=0` and `r2=0?1:0`. This sub-formula is also recursively evaluated so that `b='0'` and `r3=""`. Check if `x` is `'1'` or `'0'` and return either `(a, r3)` or `(b, r3)`. [Answer] ## JavaScript (ES6), 53 bytes ``` f=s=>s[1]?f(s.replace(/0\?.:|1\?(.):.(?!\?)/,"$1")):s ``` Returns `0` or `1` for valid input; hangs for invalid input. Explanation: because reversing a string is awkward in JavaScript, my first 71-byte attempt worked by using a negative lookahead for a `?` which would otherwise disturb the associativity: ``` f=s=>s[1]?f(s.replace(/(.)\?(.):(.)(?!\?)/,(_,a,b,c)=>+a?b:c)):s ``` Since this was somewhat long I wondered whether I could improve matters by incorporating the decision making into the regexp. As it turned out, it wasn't an immediate success, as it also took 71 bytes: ``` f=s=>s[1]?f(s.replace(/0\?.:(.)(?!\?)|1\?(.):.(?!\?)/,"$1$2")):s ``` Then it occurred to me that `0?0:` and `0?1:` are always no-ops, without concern for associativity. This saved me almost 25%. [Answer] ## Perl, 32 + 1 (`-p` flag) = 33 bytes *Full credit to [@Mitch Swartch](https://codegolf.stackexchange.com/users/2537/mitch-schwartz), as his solution was 14 bytes shorter than mine!* *Thanks also to [@Neil](https://codegolf.stackexchange.com/users/17602/neil) who suggested a solution 1 byte longer than Mitch.* ``` s/.*\K(0\?..|1\?(.)..)/\2/&&redo ``` Needs `-p` flag, as well as `-M5.010` or `-E` to run. For instance : ``` perl -pE 's/.*\K(0\?..|1\?(.)..)/\2/&&redo' <<< "0 0?0:1 0?1?0:1:1 1?0:1?0?1:1?1:0:1?1?1:1:1?0:1 0?0?1?0?0:1:0?0:0:0?0?1:1:1?0:1:0?0?0?1:0:0?1:1:1?1?0:1:1" ``` **Explanations** : It basically reduces the blocks of `a?b:c` (starting from the end to be sure no `?` follows) into `b` or `c` depending on the truthness of `a`, over and over until the string only contains `1` or `0`. [Answer] ## Python 3, ~~93~~ 69 bytes ``` def f(s):z=s.pop;r=z(0);return s and':'<z(0)and(f(s),f(s))[r<'1']or r ``` Input is the string as a list of characters, output is either `"0"` or `"1"` ``` >>>f(list("0?0:1")) <<<"1" ``` --- Ungolfed version: ``` def parse(s): predicate = s.pop(0) if s and s.pop(0) == '?': left, right = parse(s), parse(s) if predicate == '0': return right return left return predicate ``` --- Another try, but with considerably more bytes: ``` i=input()[::-1] a=[i[0]] for o,z in zip(i[1::2],i[2::2]):a+=[z]if o<'?' else[[a.pop(),a.pop()][z>'0']] print(a[0]) ``` [Answer] # SED, 75 74 68 (40 + 1 for -r) 41 ``` : s,(.*)1\?(.):.,\1\2, s,(.*)0\?.:,\1, t ``` [Answer] # Bash + GNU utilities, 42 ``` rev|sed -r ': s/(.):.\?0|.:(.)\?1/\1\2/ t' ``` Similar idea to most of the other pattern-matching answers. [Ideone](https://ideone.com/5CMYYQ). ]
[Question] [ Given a number > 0, output the sum with all digits (1 .. n) concatenated and reversed and add them up. For example, with n = 6: The numbers 1 to 6 concatenated: ``` 123456 ``` Reversed: ``` 654321 ``` Adding them up together will result in: 777777. Another example is n = 11: ``` 1 2 3 4 5 6 7 8 9 10 11 > 1234567891011 ``` and ``` 11 10 9 8 7 6 5 4 3 2 1 > 1110987654321 ``` Adding them up together will result in `2345555545332`. This is also known as [A078262](https://oeis.org/A078262). Shortest code wins! [Answer] # 05AB1E, 7 bytes ``` LDRJsJ+ ``` [Try it online.](http://05ab1e.tryitonline.net/#code=TERSSnNKKw&input=Ng) ## Explanation ``` LDRJsJ+ L range from 1 .. input D duplicate R reverse JsJ convert both arrays to strings + add (coerces both strings to ints) ``` [Answer] # Jelly, 9 bytes ``` R,U$DF€ḌS ``` [![livecoding](https://i.stack.imgur.com/rOqhk.gif)](https://i.stack.imgur.com/rOqhk.gif)  [Answer] ## CJam, ~~15~~ 14 bytes Thanks to Martin for shaving a byte! ``` ri,:)_W%si\si+ ``` [Try it online!](http://cjam.aditsu.net/#code=ri%2C%3A)_W%25si%5Csi%2B&input=11) [Answer] ## Pyth, ~~12~~ 10 bytes ``` ssMjLk_BSQ ``` Thanks to [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for 2 bytes! `Q` is the input, `S` turns it into `[1, 2, ..., input()]`, `_B` bifurcates it over `_` (reverse) to create `[rng, rev(rng)]`, `jLk` maps it over `join` by `k` (which is the "empty string" variable), `sM` maps `int` over *this* resulting array, and `s` finally calculates the sum. [Answer] # Python 3, 74 Saved 6 bytes thanks to DSM. Nothing too exciting, join the ranges and then convert to ints and add them. ``` lambda x:sum(int(''.join(list(map(str,range(1,x+1)))[::i]))for i in(1,-1)) ``` [Answer] # JavaScript (ES6), ~~70~~ ~~67~~ 64 bytes ``` a=>(z=[...Array(a)].map((b,c)=>c+1)).join``- -z.reverse().join`` ``` Fixed to meet requirement, as old code was made under misunderstanding of the input. [Answer] # [Retina](https://github.com/mbuettner/retina), 71 * 7 bytes saved thanks to @daavko. * 3 bytes saved thanks to [version 0.7.3 features](http://chat.stackexchange.com/transcript/message/27728253#27728253) Because its blatantly the wrong tool for the job. ``` .+ $*a:$&$* +`^(a+)a\b(.*)\b1(1+)$ $1 $& $3 ?(\w)+ ? $#1 \d+:? $&$*c c ``` [Try it online.](http://retina.tryitonline.net/#code=LisKJCphOiQmJCoKK2BeKGErKWFcYiguKilcYjEoMSspJAokMSAkJiAkMwogPyhcdykrID8KJCMxClxkKzo_CiQmJCpjCmM&input=Ng) Works for inputs up to 6, but the online interpreter times out after that. [Answer] # Jolf, 9 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=K1AQzrN6alBfzrM) Replace `►` with `\x10`. ``` +P►γzjP_γ zj range 1...j γ γ = ^ ► ^ .join("") P as a number + P_γ and γ reversed ``` I *may* be able to golf it by moving around the type casting. [Answer] ## JavaScript (ES6), ~~67~~ 66 bytes ``` n=>(a=[...Array(n+1).keys()].slice(1)).join``- -a.reverse().join`` ``` Yes, that's a space. Ugh. At least @Downgoat helped me save a byte. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `s`, 5 bytes ``` ɾḂWvṅ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=%C9%BE%E1%B8%82Wv%E1%B9%85&inputs=11&header=&footer=) ``` ɾ range: [1 .. x] Ḃ pop x, push x, reversed(x) [bifurcate] W wrap the stack v for each ṅ join on "" s (flag) sum ``` -2 bytes thanks to Razetime [Answer] ## Seriously, 12 bytes ``` ,R;Rεj≈@εj≈+ ``` [Try it online!](http://seriously.tryitonline.net/#code=LFI7Us61auKJiEDOtWriiYgr&input=Ng) Explanation: ``` ,R;Rεj≈@εj≈+ ,R; push two copies of range(1, input()+1) R reverse one copy εj≈@εj≈ concatenate both and cast both to ints + add ``` [Answer] ## PowerShell, 35 bytes ``` param($a)+-join(1..$a)+-join($a..1) ``` Converts the input to ranges with `..`, then `-join`s them together, and adds 'em up. Will work for input numbers up to `138`, while `139` will give `Infinity`, and `140` and above will barf out an awesomely verbose casting error: ``` Cannot convert value "12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413 5136137138139140" to type "System.Int32". Error: "Value was either too large or too small for an Int32." ``` [Answer] # Pyth - 8 bytes ``` siRT_BSQ ``` [Try it online here](https://pyth.herokuapp.com/?code=siRT_BSQ&input=6&debug=0). [Answer] # JavaScript (ES6), 99 This adds digit by digit, so it can handle numbers well above the 53 bits of precision of javascript ``` n=>eval("for(a=b=c=r='';n;a+=n--)b=n+b;for(i=a.length;i--;r=c%10+r)c=(c>9)-(-a[i]-b[i]);c>9?1+r:r") ``` **Test** ``` f=n=>eval("for(a=b=c=r='';n;a+=n--)b=n+b;for(i=a.length;i--;r=c%10+r)c=(c>9)-(-a[i]-b[i]);c>9?1+r:r") // Less golfed U=n=>{ for(a=b=c=r=''; n; --n) b=n+b, a+=n; for(i=a.length; i--; r = c%10+r) c=(c>9)-(-a[i]-b[i]); return c>9? 1+r : r; } function test() { var n=+I.value R.textContent=f(n) } test() ``` ``` N: <input id=I value=11 oninput="test()"> -> <span id=R></span> ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 24 bytes ``` :1fLrcC,Lc+C=.,{,.:1re?} ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 13 bytes ``` :tP2:"wVXvU]+ ``` *EDIT (May 20, 2016) The code in the link uses `Xz` instead of `Xv`, owing to recent changes in the language.* [**Try it online!**](http://matl.tryitonline.net/#code=OnRQMjoid1ZYelVdKw&input=MTE) ``` : % range [1,2,...,n], where n is input tP % duplicate and flip 2:" ] % do this twice w % swap V % convert array of numbers to string with numbers and spaces Xv % remove spaces U % convert to number + % add the two numbers ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` LJDR+ ``` Explanation: ``` L # Pushes an array containing 1 .. [implicit] input J # Join the array to a string (eg. [1, 2, 3] -> 123) D # Duplicate the array R # Reverse the duplicate + # Add them together ``` [Try it online!](https://tio.run/nexus/05ab1e#@@/j5RKk/f@/2de8fN3kxOSMVAA "05AB1E – TIO Nexus") [Answer] # Bash + coreutils, 39 ``` eval echo {1..$1} + {$1..1}|tr -d \ |bc ``` Or: ``` bc<<<`eval printf %s {1..$1} + {$1..1}` ``` [Ideone.](https://ideone.com/r43Gyg) [Answer] # [Perl 6](http://perl6.org), 25 bytes ``` {([~] @_=1..$^n)+[R~] @_} ``` ``` { ( [~] # reduce with the string concatenation infix op: @_ = 1 .. $^n # the range 1 to input ( also stored in @_ ) ) + # add that to [R~] @_ # @_ reduced in reverse } ``` ### Usage: ``` for 6, 11, 12 -> $n { say {([~] @_=1..$^n)+[R~] @_}( $n ) } ``` ``` 777777 2345555545332 244567776755433 ``` [Answer] # R, ~~34~~ ~~60~~ 64 bytes ``` f=pryr::f;g=f(as.numeric(paste(x,collapse='')));f(g(1:n)+g(n:1)) ``` Assumes `pryr` package is installed. this gives `f` as a shorthand for creating functions. Edit added 26 bytes but returns a function that works, not something entirely wrong. Edit added another 4 bytes to handle cases above n=10 where strtoi (previously used) was returning `NA` [Answer] # Lua, 57 ``` a=''b=''for i=1,...do a=a..i b=b.. ...-i+1 end return a+b ``` [Answer] ## Lua, 53 Bytes This program takes `n` as a command-line argument. ``` s=""r=s for i=1,arg[1]do r,s=i..r,s..i end print(s+r) ``` I assumed that outputing a number with a decimal part of 0 was okay (in the form `777777.0` because this is the default way to output a number in lua (there's no distinction between integer and float) [Answer] # Perl 5, 37 bytes 25 bytes, plus 1 for `-p` and 11 for `-MList::Gen` ``` $_=<[.]1..$_>+<[R.]1..$_> ``` --- Previous solution, 40 bytes: 39, plus one for `-p` ``` @a=reverse@_=1..$_;$"=$\;$_="@a"+"@_" ``` [Answer] # Perl, 36 bytes Includes +1 for `-p` Run with on STDIN ``` perl -p reverse.pl <<< 6 ``` `reverse.pl` ``` $_=eval join"",map{abs||"+"}-$_..$_ ``` [Answer] ## Haskell, ~~57~~ ~~56~~ 48 bytes This could probably be golfed a bit more, but here it goes: ``` f x=read y+(read.reverse$y)where y=[1..x]>>=show ``` Edit: shaved off a space before the where. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 17 bytes ``` +/⍎¨∊¨⍕¨¨x(⌽x←⍳⎕) ``` `⎕` prompt for input `⍳`' enumerate until input `x←` store list in x `⌽` reverse x `x(`…`)` prepend reversed list with original list `⍕¨¨` convert each number of each list into character string `∊¨` make each list of character strings into single character strings `⍎¨` convert each character string into a number `+/` sum the two numbers. [Answer] # [Factor](https://factorcode.org/), 59 bytes ``` [ [1,b] dup reverse [ [ present ] map concat dec> ] bi@ + ] ``` [Try it online!](https://tio.run/##PYyxDsIwDER3vuJ2UKWsICE2xMKCmKoMrmugIqSpkyLx9cF0YDu9e3c34jJqvV5O5@MWLyqPRineJeMpGiUgqWSJBVmmWSJbsUiJNIsu@aeU8kk6mLZbOVdbtG7TefRzgspbTIWx/5e3XQKPkamgF94b6YYD1vCVKQQ09Qs "Factor – Try It Online") * `[1,b]` Create a range from 1 to the input, inclusive. * `dup reverse` Make a copy and reverse it. * `[ [ present ] map concat dec> ] bi@` Convert them both to numbers of concatenated numbers. * `+` Add. [Answer] # [Python 3](https://docs.python.org/3/), 79 bytes ``` a=''.join([str(i+1) for i in range(int(input()))]) print(int(a)+(int(a[::-1]))) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P9FWXV0vKz8zTyO6uKRII1PbUFMhLb9IIVMhM0@hKDEvPVUjM68EiAtKSzQ0NTVjNbkKiiAiJRqJmtoQOtrKStcwFij9/78ZAA "Python 3 – Try It Online") [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `s`, 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` RJNḲ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPVJKTiVFMSVCOCVCMiZmb290ZXI9JmlucHV0PTExJmZsYWdzPXNl) #### Explanation ``` RJNḲ # Implicit input R # Push [1..input] J # Join into a string N # Convert to integer Ḳ # Duplicate and reverse # Sum the stack # Implicit output ``` [Answer] # Mathematica, 64 bytes ``` Plus@@FromDigits/@#&[""<>ToString/@#&/@{#,Reverse@#}&[Range@#]]& ``` ]
[Question] [ Imagine that a list of integers describes the heights of some two-dimensional terrain as seen from the side. ``` Stamina: [ 4 4 4 4 4 4 3 3 3 3 2 2 2 - ] O /|\ / \ +---+ +---+ | | | | +---+ +---+---+ +---+ | | | | | | | +---+ +---+---+ +---+ +---+ | | | | | | | | | +---+ +---+---+ +---+---+ +---+ | | | | | | | | | | +---+---+ +---+---+---+ +---+---+---+ +---+ | | | | | | |OW!| | | |OW! STUCK!| | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+ | | | | | | | | | | | | | | | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+ Height: [ 6 2 1 2 5 6 1 2 3 5 1 1 1 4 ] ``` A climber is standing on the first piece of terrain. Her goal is to reach the far end. She has a stamina rating that determines the maximum height she can climb. Unfortunately, she has never heard of rappelling before, so she simply jumps off any cliffs she encounters. If she falls a greater distance than her current stamina, her stamina drops by one. ## Task Determine whether the climber can traverse the terrain. ## Rules * The climber moves strictly from left to right. * The climber must visit every piece of reachable terrain. * Stamina determines maximum climbing height. * Stamina decreases by one when fall height exceeds stamina — no matter how long the drop. * Zero is the minimum stamina. * The terrain is untraversable if the climber encounters a cliff above her that is taller than her current stamina level. * The terrain is traversable if the climber is able to stand on the last piece of terrain. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer with the fewest bytes (in each language) wins. ## Format * You must accept an integer (representing starting stamina) and a list of integers (representing heights) in [any reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). * You must output a truthy/falsy value. You may either use your language's convention for truthy/falsy or any two distinct values representing truthy and falsy. * Starting stamina will be \$\geq0\$. * The length of the list will be \$\geq2\$. * All heights in the list will be \$\geq1\$. ## Test cases The farthest reachable piece of terrain is in bold. | Truthy | What is this testing? | | --- | --- | | ``` 0, [1,1,1,1,**1**]0, [50,45,20,19,18,10,1,1,**1**]5, [1,6,11,16,21,26,**31**]100, [500,1,**100**]45, [20,**50**]4, [6,2,1,2,5,6,1,2,3,5,1,1,1,**3**]17, [59,61,47,64,23,34,21,22,25,29,**25**] ``` | ``` Flat terrain with 0 staminaDrops with 0 staminaArduous climb, barely doableLong drop, strong climberShort trek, excess staminaExample with a shorter cliff at the endRandomly generated ``` | | Falsy | What is this testing? | | --- | --- | | ``` 4, [6,2,1,2,5,6,1,2,3,5,1,1,**1**,4]0, [1,**1**,2,1,1]5, [30,28,22,18,13,9,7,9,**11**,14,22,23]6, [**40**,47,49,55,61,66,69,70,50,55]45, [79,48,41,70,76,85,27,12,31,66,13,**17**,94,77]31, [65,21,20,32,9,9,37,14,23,19,**32**,63] ``` | ``` ExampleSmall hill with no staminaValley with too many dropsEarly failureRandomly generatedRandomly generated ``` | [Answer] # JavaScript (ES6), 39 bytes Expects `(stamina)(list)`. Returns *false* for truthy and *true* for falsy. ``` n=>a=>a.some(v=>-n>a-(n-=n&&a-v>n,a=v)) ``` [Try it online!](https://tio.run/##fVLLboMwELz3KzglIA2R10@sCo79gt7SHFCa9KHUVCFF6tfTtdNDK5kIA5Z3Z3Zm5Pd@6sf9@e3zUofh@TAf2zm0Xc9rMw4fh3Jquzp0fV2Gug2rVV9PXUDfTlU174cwDqfD5jS8lOvt4/nr8vq9W1f3d38Lx7IoRFVuCb/PrqqyDUZAG0gB8qAGJJbbTeKzIK5bSIK0UJlOElfiRCVEhkpHKp5pcsVCc5H5GS1h4jz@K95dnagMhFwc6GEJ2sFqSAWlk0QJyfY8fyPuH3D9FLYP/WnMp3dbhV7Kk1LjjQSVgGyirpi2gofjN0aqk9icvcIyTovoTXsYE31aC8vYmCGfLGXsPHQDTbHRWTQchQOxkUTA44mnaziXIVAUEzApRQElWaaHckmoiteFj6xayqFhXxpR2PwD "JavaScript (Node.js) – Try It Online") ### Commented ``` n => // outer function taking the stamina n a => // inner function taking the array of heights a[], // re-used to store the previous height a.some(v => // for each height v in a[]: -n > // trigger some() if -n > a - v (i.e. n < v - a, a - ( // meaning that we can't climb) n -= // decrement n if: n && // it's not already 0 a - v > n, // and a - v is greater than n a = v // update a to v ) // NB: a - v is always NaN the first time ) // end of some() ``` [Answer] # Excel (ms365), ~~75~~, 64 bytes -11 bytes thanks to [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) [![enter image description here](https://i.stack.imgur.com/6VcDp.png)](https://i.stack.imgur.com/6VcDp.png) ``` =REDUCE(B1,A2:A5-A1:A4,LAMBDA(a,b,IF(b>a,-1,a-(-b>a)*(a>0))))>=0 ``` [Answer] # [R](https://www.r-project.org), ~~52~~ 49 bytes ``` \(s,t)any(Map(\(i)s<<-s-(-i>s)*!!s,d<-diff(t))<d) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hVHLSgMxFMWtX9F2lcgZyDsTmAoudKUbH7tuxrYDBRmkmQp-i5sq-FH6EX6DN0mVdiEyzGRycs6959y8vK63b930fTN0Vf0hZyxi4G3_zK7aRzZjKx6bpooVq1ankZ-MxxGLplqsuo4NnDcLXoSfR1_zdmCTTT-s2z4-LdexvX9Yjqaji7PLm_NZP-HHHRMYzZnE7uG_kBUwFkpABsgaUuwRbNE4SEIclIRy0OVMip08C4TIoMkKKmZ3-7QlIVEUbCpEq6a_YkOXSj4XCnASxsMZKA1tcjsFReYCfYn6R8rb67ufkP_0M_xgEuowqBZQdWqZxqAR4OlNyU32Ucy6xDQiGTUB1ibTzsERO6UmZG8QPsDUMDKdeYeaonhIcpQ11IOiBwPvs4bQ5N7m4AJaUfsA7bMBne6HIEc2yrVvt2X9Bg) Outputs `TRUE` if the terrain is untraversable, `FALSE` otherwise. [Answer] # [Haskell](https://www.haskell.org/), ~~66~~ 56 bytes With Joseph Sible-Reinstate Monica's suggestions: (doesn't change typing or behavior, except now it's a total function, which is a plus!) ``` s%(h:j@(i:_))=i-h<=s&&max 0(s-fromEnum(h-i>s))%j;_%_=1>0 ``` ##### Original: ``` f _[_]=True;f s(h:j@(i:_))=(i-h<=s)&&f(max 0$s-fromEnum((h-i)>s))j ``` [try it online](https://play.haskell.org/saved/jkfcP0wr) `f` has an intuitive type signature, and matches my reference implementation (on legal inputs). ``` f :: Int -> [Int] -> Bool ``` ``` basic :: Int -> [Int] -> Bool basic _ [] = True basic _ [h] = True basic s (h1 : hs@(h2 : _)) = (r <= s') && basic (s' - (if (-r) > s' then 1 else 0)) hs where r = h2 - h1 s' = max 0 s ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 77 bytes ``` param($s,$l)$args|?{if(($l-=$_)-ge0){$s-=+($l-gt$s)*!!$s}else{-$l-gt$s}$l=$_} ``` [Try it online!](https://tio.run/##pVLBbqMwFLznK5zKqqAFCbCB5BBtpKq97mrbW7WqKHXSVqRkMVErUb49O892SXaL9lJkno09b2beM9v6VTX6UVVVWNaN2vPVottvi6bYeFwHvPJ50az1@7fuaeV5vAoX/M4P1yryO67DxTltrVuu/bPplOteVVp1odvreQV0v@8nk6U3YXgCtvQiCnHADsMPGG@bnfL/xqSIMg1Ygjme453hjf6TlTrmDKeEwJxgTjCLEXgcORnHGUWfMdJwkoN07JQCqRgCxNSKm7Uwn0OVYsRAbvRRWgaAxFcGxgSJQjrr4EmoBXOav2ZAUvqqwAX5Y3eRHLr6D8i0QACazKwjcxFgh6ncRNNt6eyKEYrMmI1skRIZaWqLznCSEY/pMO2PZNtLyAGTUJaxhedInVFvQBlTuY6OnFFn5zCU5yN0BISl1LUYVCIxZWCI3FUi7D9HJ9lxRT57Z1d1c1mUj@H3@2dVtqwzzFy3xebppQC0vse6rJTGWr1tgVEPbMH4nQU2Su@qFhunfDWkseWQZVC3P64vdrqtN1bk19Kq0HO9K0ulNQPD9IMsVL8PWgPyRun2otAKyJNBKDwyeDJAL498fuL5aUVI0Qmao37S7/8A "PowerShell Core – Try It Online") Passes the obstacle list using splatting. Returns an empty array if traversable, `false` in PowerShell Non empty otherwise, `true` in Powershell [Answer] # [Rust](https://www.rust-lang.org), 90 bytes ``` fn f(a:&[i32],b:i32)->bool{a.len()<2||a[1]-a[0]<=b&&f(&a[1..],b-(a[0]-a[1]>b&&b>0)as i32)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lVJNb4JAEE16K79i9WAgeZj9Yhdsa_9HDQdoJDGh2CD2ov6SXjy0p_6i9td0FlAxPTWEXTJvZt6bx7x_1NtNc_wqKvaSrSo_YLvPbVOE8fcThQo_m00WKyVT5DO6gnCer9flLpuWS8q9l_t9thBpmC14ev-QTyaFP6HAdEr5oe-iocPnhORzHmQb5pocOoafm4NXrGvm52AZWL3cbMsmYKuKvS2fRwvP5-i-BPonBWvq7TLABYs4dATJIRKIGIL_yYzOXQwEQQZSQBqoYZLgl4ZtC84HqD71IJ7oCujj1JOKJCLHQbeir06zGpLYE0cCI6AtjIZUULqVJCFpkoTOfzFoyi6ycnNli2iTOiPO4GkKxSFjx-cMU0hg6XXW6FaEGtaYvkZzp1cniCKn3RgYqnN2UGRYcPbKJtAxtHBZ1iCm2SwEKW-riZfsSDSsHVYT2M8btZ5wKEniEijbylPuP1PIDEWmbOfdvtarqimrkT8u_N3s8QDmzuDBneN2wWjN3HoiDwLv4N31W3g8dvcv) Recursive approach [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ¥vDyÄ‹i<y1‹ˆ]¯P ``` Inputs in the order \$heights,stamina\$. [Try it online](https://tio.run/##yy9OTMpM/f//0NIyl8rDLY8admbaVBoCqdNtsYfWB/z/H22mY6RjCMSmOmZg2hjIMgRDk1guEwA) or [verify all test cases](https://tio.run/##hVA7TsQwEL1KlPoJeezxOJaQtuEAVDSRJUCi2IpipZXSUaA9AHegpqGhDSW32IuEZ2dXQIUifzLz5n38uLu73z4s@2nTd8fDS9dvpttdv8yv@6vp8/n49LG9nITH16HMb9dLf3GD@X0Zx1Fw@gpcQTeO0UEjvINkyABxf9sCg/Df4AXeENiJp8EGdcS1jSWyRN50BXCEAI9YKXgG3lbxQMzKkWECTTCFDwjaVDw8HWXupE7/cOmZS1rjl/Xg4IfKVmMFZCSumkWbRDgHUVcdaEaM1Y0ZjNgahZUCa6CUoQNUaiMZBhpMEBppA6QXsitS@okfWxiH4KmbEVJTDvWhWTLq8zHLNw). **Explanation:** ``` ¥ # Get the deltas (forward differences) of the first (implicit) input-list v # Pop and loop over each difference `y` of this list: D # Duplicate the current stamina # (which will be the second implicit input-integer in the first iteration) yÄ # Push the absolute value of difference `y` ‹i # If the stamina is smaller than the absolute `y`: < # Decrease the stamina by 1 y1‹ # Check if `y` is negative (it's a drop) or 0 (it's flat terrain) ˆ # Add that check to the global array ] # Close both the if-statement and loop ¯ # Push the global array P # Check if all are truthy by taking the product (aka, none were climbs) # (which is output implicitly as result) ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 16 bytes ``` R↔$∆çJᵐ{CᵈAc}-0≥ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hVAvTwMxHA32PsXlgnyX9Nf-2l4lwSGxlxNjGQYGYkMR7DIcAoeZYAGBnULyLXDbJ-G12zS59Nq-vn_t2-fd5OZ-OpqPvvqmnTaom3bSDKv1w_y67b4vd4vX091y8fNxsd28PJ5vN8uz8VNrds_r99nVeHbgrX5Pbk3dCw7fUHHnDdTDGkiCdBBzPPOZGSDcBFiBDXCExRRRoRkzVEoe1T4v655MHlj4rOTsuNqnOUojlQlBoBFBYR2cFmsLyw6J_39ctHSWgh5bOgPbZY9c3yEhcuTaWowZHOpeTQ7VBO9zgRAQSMy9iexvERO0g0qGY0DHRhHC9EKns9BYEeNQOWFJX6obOMu8BBdLossPSSi4Yf_qfw) This works in Nekomata v0.2.0.0, and uses some new built-ins. The flag `-e` set the interpreter to `CheckExistence` mode, which prints `True` if the computation has any result, and `False` otherwise. ``` R↔ Take the range from the starting stamina down to 1 $ Swap ∆ Get the deltas of the list of heights ç Prepend zero J Non-deterministically split the list into a list of sublists The concatenation of these sublists should be the original list ᵐ{ } For each sublist CᵈAc Replace each item except the head with its absolute value - Subtract (automatically vectorize and pad zeros) 0≥ Check if all items in the result are greater than zero ``` --- ## [Nekomata v0.1.1.0](https://github.com/AlephAlpha/Nekomata/tree/v0.1.1.0) + `-e`, 21 bytes ``` R↔$:t-i_0cJᵐ{CᵈAc}-0≥ ``` This is the original answer in Nekomata v0.1.1.0. ``` R↔ Take the range from the starting stamina down to 1 $ Swap :t-i_ Get the deltas of the list of heights 0c Prepend zero J Non-deterministically split the list into a list of sublists The concatenation of these sublists should be the original list ᵐ{ } For each sublist CᵈAc Replace each item except the head with its absolute value - Subtract (automatically vectorize and pad zeros) 0≥ Check if all items in the result are greater than zero ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 71 bytes ``` Length@a<2||(a[[2]]-a[[1]]<=b&&f[Rest@a,b-Boole[a[[1]]-a[[2]]>b&&b>0]]) ``` [Try it online!](https://tio.run/##jVJNa8JAEL33VwQP0kKE7Fc2tirSQ089lNLbdpFNiVXwAzQ9lOpvT9/srq1RC4XdnWRn3ps3L1m6elYtXT1/c83UuElaTuztsHmsVu/1bOwGfLe7dsZwa3sIzNrBsOx2p@a52tZjl5a9@/V6UZmQ64XKESrKUWbtTfO0ma9q0zEvm4969mk79u4qXE3NF0uT37VPEwCOsipLE6nShCOyPnaBnf1dj8sc95RD5IgcUVChOiGOLFm292crS@0UJWQbRZwehlOFVv5Z@NefOQQh2@2gPUdGakQJDBBCRoUg4DRjnyKp0YSN4M7ryjy4xfbEtn8qkWdK2KHyon8Cg/MiaPJegw@ytD@9rTIKFmeWyizMJ1GqVJg3h7CcCLyhdA9Y3oJppCVaSRbKNCAF2QEqRhNFGpLCSAgUaH3h26hoJzgE94KxhI6aRfiBKJOTdsFa6MIPiUJ18KT5Bg) Original Code is ``` f[a_List, b_Integer] := Length[a] < 2 || ( a[[2]] - a[[1]] <= b && f[ Rest[a], b - Boole[a[[1]] - a[[2]] > b && b > 0] ] ) ``` It defines a recursive function `f` that takes two arguments: a slice of integers `a` and an integer `b`. The function returns a boolean value that checks if the difference between consecutive elements in the slice is less than or equal to `b`. If the difference is greater than `b`, it deducts 1 from `b` for the next recursive call. [Answer] # [Python 3](https://docs.python.org/3/), 56 bytes ``` f=lambda s,n,m=0,*t:m<1or(s>=m-n)&f(s-min(s,n-m>s),m,*t) ``` [Try it online!](https://tio.run/##hVBLasMwFNz7FFoVu0xAf1mhyUWKFy5NaCCSTWwCPb07UtJui5H1NJqZN0/z9/o1ZbNt58N1TB@fo1iQkQ4Sr@s@vanp1i7HQ9rl7uXcLrt0yS0Ju3RcOiRyuu083agRq7hkkca5Pd3HK8Q0n3Iru27fCDHfLnltKYegAJXdbRLiXeH5DU05OgnroCVUhOqh5O@lq1wPxZOHVtAehriSD1klSjk0tjBp4ErNkmReabgi5m5YPVoaqkMRR3gFG@AttIGx1V5DM0jk/z8f@4iuKvwX1kjovtiUMQwiAldJb6s3m3uyrCyNbYRzJYT38GSW9ESew4QI28OqggePnrECFBNUPr05RbQIYWgIMamrA0gYzZYRJtSmprwpIW@GHw "Python 3 – Try It Online") Takes the stamina as first argument and the splatted terrain as consecutive arguments. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` ’¹¹?{ḷ<?N-N>? _Ɲçƒ<0 ``` Takes a comma-separated list of integers on the left-hand side and the starting stamina on the right-hand side. Returns 1 if stuck, 0 if traversable. Consists of two links. Link 1: Update stamina (set stamina to -1 if we can't keep going; dyadic with x = current stamina and y = fall distance) ``` <? If stamina < fall distance then ’¹¹?{ Decrement stamina if nonzero, else return stamina ḷ Else return current stamina N Negate stamina >? If - stamina > fall distance (i.e. if stamina < hill height) - Then return -1 (we're stuck) N Else return stamina ``` Link 2: Main link (dyadic with x = hill heights and y = starting stamina) ``` _Ɲ Take difference of consecutive elements of heights list çƒ Update stamina for each hill/fall we have to traverse <0 Return 1 if stamina is less than zero, or 0 if stamina is still nonnegative ``` [Answer] # MMIX machine language, 18 instrs (72 bytes) Assumes terrain is 0-terminated, and at least one part long. `bool __mmixware f(octa stamina, octa *terrain);` ``` 00000000: e2020001 8d030100 8dff0108 e7010008 Ä£¡¢⁽¤¢¡⁽”¢®ḃ¢¡® 00000010: 42ff000d 320403ff 4c040007 260403ff B”¡Æ2¥¤”L¥¡¬&¥¤” 00000020: 32040004 71040401 7a040004 26000004 2¥¡¥q¥¥¢z¥¡¥&¡¡¥ 00000030: f1fffff5 2604ff03 32040004 78020402 ȯ””ṫ&¥”¤2¥¡¥x£¥£ 00000040: f1fffff1 f8030000 ȯ””ȯẏ¤¡¡ ``` Disassembled: ``` f SETL $2,1 // rv = 1 0H LDO $3,$1,0 // start: curht = *terrain LDO $255,$1,8 // nextht = terrain[1] INCL $1,8 // terrain++ BZ $255,2F // if(!nextht) goto ret CMPU $4,$3,$255 BNP $4,1F // if(curht <= nextht) goto increase SUBU $4,$3,$255 // $4 = curht - nextht CMPU $4,$0,$4 // $4 = stamina <=> curht - nextht ZSN $4,$4,1 // $4 = stamina < curht - nextht ZSNZ $4,$0,$4 // $4 = (stamina < curht - nextht) && stamina SUBU $0,$0,$4 // decrement stamina if nonzero and drop is larger JMP 0B // goto start 1H SUBU $4,$255,$3 // increase: $4 = nextht - curht CMPU $4,$0,$4 // $4 = stamina <=> nextht - curht ZSNN $2,$4,$2 // rv &&= stamina >= nextht - curht JMP 0B // goto start 2H POP 3,0 // ret: return(rv, stamina, terrain) ``` A fairly simple algorithm. I could have put the return inline, but branches not taken are usually cheaper than branches taken in terms of time. The positioning of the second load before the increment is to decrease stalls, as the next usage of the incremented variable is in the next loop. It was cheaper in terms of instructions to do two loads per iteration instead of transferring the next height to the current height, but it would probably take longer on a real machine; my initial plan was to transfer, hence the lack of stores to `$255`. The reason for the usage of `$3`, `$4`, and `$255` as temp registers instead of some other combination is that `$3` and `$4` go on the register stack, and it's expensive to use that too much, but `$255` is a global scratch register. [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$24\log\_{256}(96)\approx\$ 19.75 bytes ``` lXz[{YDyZA<?1-y1<xsTX}xP ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhY7ciKqoqsjXSqjHG3sDXUrDW0qikMiaisCINJQVQv2R5vpGOkYArGpjhmYNgayDMHQJJbLBKIMAA) Port of Kevin Cruijssen's 05AB1E answer. #### Explanation ``` lX # Store an empty list in x (for later) z[ # Get the deltas of the first input {Y # Loop through with variable y: Dy # Duplicate and push y ZA # Absolute value of y <? # If it is less than the absolute value: 1- # Decrement it y # Push y again 1< # Is it less than 1? xs # Push x and swap TX # Append and store in x }x # After the loop, push x P # Take the product # Implicit output ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` ¹≔§η⁰ζFη«≧⁻∧θ‹ι⁻ζθθ¿›ι⁺ζθ⎚≔ιζ ``` [Try it online!](https://tio.run/##Rc4xC8IwEAXg2f6KN17gBKuoQ6fiIIJCcRWH0KZNIKSaVJGKvz1aK7jc8N4H70otfdlKG2PhjesoFVmSh2AaR3m3c5V6kGbMBKP/NHXrQVrgmUwO8jK6o2l0RwfjboGRu4qujL0KgQzjm1LPuAohhpslE1ODtl7JTvmBFPYvsLFKehqUskHh94gZx18xnlLGacVYM5aMBWPOSM/nOL3bNw "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for traversable, nothing if not. Explanation: ``` ¹ ``` Assume that the terrain is traversable. ``` ≔§η⁰ζ ``` Get the starting height. ``` Fη« ``` Loop through the heights. ``` ≧⁻∧θ‹ι⁻ζθθ ``` If this is a drop of more than the stamina then decrement the stamina. ``` ¿›ι⁺ζθ⎚ ``` If this is a climb of more than the stamina then clear the canvas. ``` ≔ιζ ``` (Otherwise) Save the current value as the previous value. [Answer] # [Ruby](https://www.ruby-lang.org/), 49 bytes ``` ->s,h{h.none?{|w|h,=*h;s<h-w&&s-=s<=>0;s<-h+h=w}} ``` [Try it online!](https://tio.run/##jVHLbgIxELv3KziB1DpVHpNko7L0QxCXSkU50apbhCrg27eewFZwq1b7iMf22Nqv/dvPuO1HsxpQj/V597F7fz2eDqeK/rG@DMtqDvP5YPph2a8sz6Y@1f5wPo@fs@3aYrZ2uF6bzcOERQuJ8BauwHVw9o4RmyrBEUrwDj4hTENnLwZNYu0VFdXQL/4BPFNLkkdUL74Dvy5ZwmSW1asgOUhGEviAIG2lh2fCwqdy99/DbGGMWfzDXG6Kuja7rxYsfKcLtHlAQeatXaVtnbIlUsVqLimIUTOmhES61iRyWz0XSAdxOswJHaNnOKZqIm5h0yLI@SoizgqxNbUIngkKQm4Zgv4VQolJxl8 "Ruby – Try It Online") [Answer] # [Java 8 (OpenJDK 8)](http://openjdk.java.net/), 157 ~~159~~ bytes > > -2 bytes thanks to @ceilingcat ! > > > Fun challenge and well presented too! I get the feeling it may be shorter to do it in Java in a more classic way (probably under 100 bytes), but i wanted to try it using only the inline Stream approach :) ``` (n,l)->l.stream().map(e->new int[]{e}).reduce(new int[]{l.get(0),n,1},(a,b)->new int[]{b[0],a[1]-(a[0]-b[0]>a[1]&a[1]>0?1:0),a[2]<1|a[0]+a[1]<b[0]?0:1})[2]>0 ``` [Try it online!](https://tio.run/##pZRRb5swEMff@ymsRpqMdiAbjAltRrWXSZOyp@4N8eAkTkbmQAROp6jjs6dnlml9WKBqggLm7Pv77ud/slVPyq/3utqufp72h4Upl2RpVNuSb6qsyPPNDSFlZXWzVktN5hgg@FnUtdGqImuKc6QCskWZ4GBLE8zL1s6@YsZGNxkx3j0mdE6ltcqi@JwY8ulEKzCen5mgtY1WO@oFO7Wn2s8q/cvtlxfPuvOCRq8OS03/BU2w0ZYyDyrgHVAFC@91ziJnBaicFz5VOPTde@beP7hbxh74HeaqPCxm/Ldb8dHFZ27ZA7vjnYczGTvdu3rPMM5lP9XliuwQCX20TVlt8oKoZtN6ZyCPx9bqXVAfbLDHaWsqejuZTMj35mB/HAkOb3sS/11pgjVlrxl@bhp1bAPVOpiUw/nyvHdrxAxEDCEDngKfAmdvU4yHqpLAUUJCyCGUEI2KcTZYYF8SY2MqYqAm7C8eF7icj71gESHErjd8Rjj6wz4abS4Z6C0FyUEkIAWEEUSiRxZCiCeS4n1Iu3fRF2Xat5joXa2JK2zFe63rjBQxCKcOh/NlBCkk@HXOEj2jUfLysrRgjrpIIY7dCUgJEuWdSTByjdGSFMQUBHdiiYQpHmQCHKn2m2AXaIdUQJKMbYIJl48s7n3CIAqRSApR0jOJ3G8YQ/IvGfx37U4v "Java 8 (OpenJDK 8) – Try It Online") --- It might be a bit hard to read so i'll try to explain a bit : Each element of the list of heights is `mapped` to a single-cell integer array containing the corresponding value. This change of type in the Stream allows the `reduce` to carry an array of integers (with a different length) throughout the different iterations. The `accumulator` of the reduce is a 3-cell integer array carrying : `[ height of previous position / current stamina / stuckness status ]` (we can't re-use the variable of the stamina parameter as itself, as it's forbidden in Java to rewrite in the Stream variables from outside of the Stream) Each iteration in the `reduce` calculates and stores the informations for the next iteration. And at the end, we just have to extract the "stuckness status" of the resulting array. Note : there are conditions to prevent the stamina from falling below zero, and for preserving the stuckness status until the end. Without these it would be bugged. [Answer] # [Haskell](https://en.wikipedia.org/wiki/Haskell), uncompetitive for now ``` traversable stamina terrain = length terrain == 1 || ((head terrain + stamina) >= (terrain !! 1)) && traversable (max (stamina - fromEnum ((head terrain - (terrain !! 1)) > stamina)) 0) (tail terrain) ``` I don't want golfing tips. It's uncompetitive for now, but I'll soon golf it, which will be PAINFUL. ]
[Question] [ **EDIT** I modified the wording of the rules to make some things which were implicit more explicit. I also added some emphasis to clear up some points of apparent confusion, and explicitly defined the option of making a standalone program instead of a function. The goal here is to make a function that takes a text file (or string) and transposes it so that lines become columns and vice versa. **Example:** ``` I am a text. Transpose me. Can you do it? ``` Results in: ``` ITC ra aan mn sy apo ou ts eed x o tm .ei .t ? ``` **The rules:** * You are allowed to assume that the only whitespace characters used are `" "` and `"\n"` and that there is no trailing whitespace on any line. * You may assume that the file is ASCII. Which endline marker you want to use is up to you.(CRLF or LF). It must work correctly on the example, but it should also work on **any** input that satisfies the above assumptions. * You might have to insert spaces (as in the example) where there were none in order to keep the columns in line. * Your result **must not** have trailing whitespace **on any line**. * The final newline character(for the last line) is optional. * **It should be either a function or a complete program.** If your **function** accepts a string, then it should return the results as a string. If it accepts a filename, then you return the name of the file where you saved the result. You are additionally allowed to write a **complete program** that accepts input from STDIN and outputs the correct result to STDOUT; if you do this, you must **not** output anything to STDERR. * Shortest procedure wins, but I will upvote any answer I like. Based on the rules, the output on the example is either 53 or 52 bytes long (for LF newlines) depending on whether the final newline is included or not. **Note:** It is not a specific requirement, but if your function, when run twice successively is not identical to the original(the final newline might be differ, and any empty lines at the end of the file will be deleted), then you are *probably* breaking one of the rules. [Answer] ## J (~~31~~ 40) ``` f=:3 :';(,&LF@dlb&.|.)&.><"1|:>LF cut y' ``` This is a function that takes a string, and returns a string (i.e. a character *vector* with linefeeds inserted in the right places, and not a matrix.) Edit: no trailing whitespace on any line. Test: ``` f=:3 :';(,&LF@dlb&.|.)&.><"1|:>LF cut y' string=:stdin'' I am a text. Transpose me. Can you do it? ^D $string 42 $f string 53 f string ITC ra aan mn sy apo ou ts eed x o tm .ei .t ? ``` [Answer] **Ruby 111** Golfed: ``` def f t;s=t.lines;s.map{|l|l.chomp.ljust(s.map(&:size).max).chars}.transpose.map{|l|l.join.rstrip+?\n}.join;end ``` Ungolfed: ``` def transpose_text(text) max_length = text.lines.map(&:size).max text.lines.map do |line| line.chomp.ljust(max_length).chars end.transpose.map do |chars| chars.join.rstrip + "\n" end.join end ``` Ruby has an array transpose function, so this simply pads the lines out, turns them into an array of characters, uses Ruby's Array#transpose function, then turns the array of characters back into lines. Golfing it was simply using single-character identifiers, removing spaces, using a temporary for text.lines, and putting the calculation for max\_length inline (there are no points for efficiency). [Answer] ## R, 171 ``` function(e){p=strsplit x=t(plyr::rbind.fill.matrix(lapply(p(p(e,"\n")[[1]],""),t))) x[is.na(x)]=" " cat(apply(x,1,function(y)sub(" *$","",paste(y,collapse=""))),sep="\n")} ``` Usage example: ``` text <- "I am a text. Transpose me. Can you do it?" (function(e){p=strsplit x=t(plyr::rbind.fill.matrix(lapply(p(p(e,"\n")[[1]],""),t))) x[is.na(x)]=" " cat(apply(x,1,function(y)sub(" *$","",paste(y,collapse=""))),sep="\n")})(text) ITC ra aan mn sy apo ou ts eed x o tm .ei .t ? ``` Trailing whitespace is removed. [Answer] **Python 2.7 (~~97~~ ~~79~~ ~~94~~ 90)** EDIT: Missed the function requirement; I'm fairly sure this will be improved on since I'm sort of a beginner here, but to start with; ``` c=lambda a:'\n'.join(''.join(y or' 'for y in x).rstrip()for x in map(None,*a.split('\n'))) ``` The code uses a simple `split` to split the string into a vector of rows. It then uses `map` with a function value as `None` (the unity function) and the splat operator to transpose and pad the vector (similar functionality to `zip_longest` in Python3) The rest of the code just maps `None` to space, trims and reassembles the matrix to a single string again. ``` >>> a = 'I am a text.\nTranspose me.\nCan you do it?' >>> c(a) 'ITC\n ra\naan\nmn\n sy\napo\n ou\nts\need\nx o\ntm\n.ei\n .t\n ?' >>> len("""c=lambda a:'\n'.join(''.join(y or' 'for y in x).rstrip()for x in map(None,*a.split('\n')))""") 88 # (+2 since `\n` is considered by `len` to be a single char) ``` [Answer] # Bash+coreutils+sed, 83 ``` eval paste `sed 's/.*/<(fold -w1<<<"&")/'`|expand -t2|sed 's/\(.\) /\1/g;s/ \+$//' ``` `fold` and `paste` do the important work. The rest is just formatting. Accepts input from stdin and outputs to stdout: ``` $ < tr.txt ./transposefile.sh ITC ra aan mn sy apo ou ts eed x o tm .ei .t ? $ < tr.txt ./transposefile.sh | ./transposefile.sh I am a text. Transpose me.? Can you do it $ ``` [Answer] **C (278 bytes)** *Edit: This actually breaks the rules, since it takes a filename in as an argument but writes to stdout. I'll edit it later to write to a file and then print the filename to stdout.* This is my first code golf ever, so have mercy. Some plain old C. Place the input in `test.txt` and let it run! `clang transpose.c -o transpose && ./transpose test.txt` ``` #import <stdio.h> #import <stdlib.h> #import <string.h> #define BUFFER_SIZE 1024 #define MAX(A,B) ((A)>(B)?(A):(B)) int main(int argc, char **argv) { char line[BUFFER_SIZE]; FILE *f; int nLines, maxLen; f = fopen(argv[1], "r"); while(!feof(f) && fgets(line, BUFFER_SIZE, f)) { nLines++; maxLen = MAX(maxLen, strlen(line)); } fclose(f); for (int charPos = 0; charPos < maxLen; charPos++) { f = fopen(argv[1], "r"); for (int linePos = 0; linePos < nLines; linePos++) { fgets(line, BUFFER_SIZE, f); printf("%c", charPos < strlen(line) && line[charPos] != '\xA' ? line[charPos] : ' '); } printf("\n"); fclose(f); } return 0; } ``` By using short variable names, removing gratuitous formatting, and allowing file handles to leak, and disabling all warnings this is reduced to 278 bytes. (Since this uses implicit imports, it may not link properly on all systems. Works on my machine!) ``` #import <stdio.h> int main(int C,char**V){char L[1024];int A,B,D,I,J,*F=fopen(V[1],"r");while(!feof(F)&&fgets(L,1024,F)){A++;D=strlen(L);B=B>D?B:D;}for(I=0;I<B;I++){F=fopen(V[1],"r");for(J=0;J<A;J++)fgets(L,1024,F)&&printf("%c",I<strlen(L)&&L[I]!='\n'?L[I]:' ');printf("\n");}} ``` [Answer] ## AutoHotkey 210 ``` f(i){ StringSplit,o,i,`n m:=0 loop % o0 { a:=A_index if (t:=Strlen(p:=o%a%))>m m:=t StringSplit,l%a%,o%a% } loop % m { a:=A_index,n:="" loop % o0 n.=(j:=l%A_index%%a%)=""?" ":j s.=Rtrim(n," ") "`n" } return s } ``` ### Test ``` text= ( I am a text. Transpose me. Can you do it? ) msgbox % f(text) ``` [Answer] # Ruby: 88 characters (Posted because it's shorter then the other Ruby solutions. Not checked whether my code introduces anything new compared to those. If you already posted a Ruby solution and you feel this is mostly a copy of yours, please comment and I will retire my answer.) ``` f=->t{l=t.split$/;r=[""]*m=l.map(&:size).max;l.map{|l|m.times{|i|r[i]+=l[i]||" "}};r*$/} ``` Sample run: ``` irb(main):001:0> f=->t{l=t.split$/;r=[""]*m=l.map(&:size).max;l.map{|l|m.times{|i|r[i]+=l[i]||" "}};r*$/} => #<Proc:0x99a9e68@(irb):1 (lambda)> irb(main):002:0> sample='I am a text. irb(main):003:0' Transpose me. irb(main):004:0' Can you do it?' => "I am a text.\nTranspose me.\nCan you do it?" irb(main):005:0> puts f[sample] ITC ra aan mn sy apo ou ts eed x o tm .ei .t ? => nil irb(main):006:0> puts f[f[sample]] I am a text. Transpose me. Can you do it? => nil ``` [Answer] # Bash, 124 bytes ``` D=`mktemp -d`;split -l1 - $D/;for F in $D/*;do grep -o . $F>$F+ done;paste $D/*+|sed -e's/\([^\t]\)\t/\1/g;s/\t/ /g;s/ *$//' ``` It reads standard input and writes standard output. Try it: ``` echo $'I am a text.\nTranspose me.\nCan you do it?' | script.sh ``` How it works: * `split` input into single lines (files in temporary directory `$D`) * split lines into single characters using `grep` (files \*+) * layout characters side-by-side using `paste` (TAB-separated columns) * remove alignment TABs, replace filler TABs with BLANKs, trim using `sed` Edit: * -9: Removed tidy-up code `;rm -r $D` (thanks Tim) * -2: use `+` instead of `_` as suffix and shorten `${F}_` to `$F+` * -3: remove prefix `L` from split result files [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 40 bytes ``` P`.+ ~L0$`. L,$.%'vs,$.(x$%=),`.+ m` *$ ``` [**Try it online!**](https://tio.run/##K0otycxLNPz/PyBBT5urzsdAJUGPy0dHRU9VvawYSGlUqKjaauqAJHMTFLRUuP7/91RIzFVIVChJrSjR4wopSswrLsgvTlXITdXjck7MU6jML1VIyVfILLEHAA "Retina – Try It Online") Based on [this program](https://tio.run/##K0otycxLNPz/390wgcs5gUtPm0tF25DLuSxBTw/C4VLy0VHRNikrBpJGOgl62kpxdQlcKgb//3sqJOYqJCqUpFaU6HHh5AAA) that I created to transpose any size of rectangle, which uses [Leo's suggestion](https://chat.stackexchange.com/transcript/message/43831903#43831903) for transposing a rectangle of a known size. Edit: Golfed more and no longer has trailing spaces on lines. [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 bytes ``` y mx1R ``` [Try it](http://ethproductions.github.io/japt/?v=1.4.5&code=eSBteDFS&input=IkkgYW0gYSB0ZXh0LgpUcmFuc3Bvc2UgbWUuCkNhbiB5b3UgZG8gaXQ/Ig==) [Run it twice](http://ethproductions.github.io/japt/?v=1.4.5&code=eSBteDFSCnkgbXgxUg==&input=IkkgYW0gYSB0ZXh0LgpUcmFuc3Bvc2UgbWUuCkNhbiB5b3UgZG8gaXQ/Ig==) - returns original string --- ## Explanation ``` y ``` Transpose the input ``` m R ``` Map over each line ``` x1 ``` Trim right [Answer] ### Ruby — 144 characters Here's my first attempt, golfed: ``` def f t t.split(?\n).each{|l|l<<' 'until l.size==t.split(?\n).map(&:size).max}.map{|x|x.split('')}.transpose.map{|l|l.join.rstrip}.join(?/n) end ``` For output, run `puts f text` where `text` is any multi-line string adhering to the rules above. The ungolfed version is below: ``` def text_transpose(text) lines = text.split(?\n) maxlen = lines.map(&:size).max lines.each { |line| line << ' ' until line.size == maxlen } .map { |line| line.split('') }.transpose .map { |char| char.join.rstrip }.join(?\n) end ``` For a similar, but ultimately better solution in Ruby, check out Wayne Conrad's code above. [Answer] **PHP 194** ``` function x($a){$a.="\n";$s=strlen($a);$i=0;while($c<$s)if($a{$c}!="\n")$b[$i++].=$a{$c++};else{$c++;for(;$i<$s;$i++)$b[$i].=" ";$i=0;}ksort($b);return rtrim(implode("\n",array_map("trim",$b)));} ``` Non-golfed: ``` function x($a) { $a.="\n"; $s=strlen($a); $i=0; while($c<$s) if($a{$c}!="\n") $b[$i++].=$a{$c++}; else{ $c++; for(;$i<$s;$i++) $b[$i].=" ";$i=0; } ksort($b); return rtrim(implode("\n",array_map("trim",$b))); } ``` This is my first golfing attempt, so please be kind! Also, tips/suggestions would be greatly appreciated! [Answer] ## MATHEMATICA 117 chars ``` t = "I am a text.\nTranspose me.\nCan you do it?"; f=(m=Length/@(f=Flatten[Characters/@StringSplit[#,"\n"],{{2},{1}}])//Max; StringJoin@@@(PadLeft[#,m," "]&/@f)//Column)& ``` [Answer] # Perl (92+1) reads stdin and writes to stdout. adding 1 to the score for `say` ``` @L=map[grep!/\n/,split//],<>;do{$_=join'',map shift@$_||$",@L;s/ +$//;say}while grep@$_>0,@L ``` [Answer] # CJam, ~~32~~ 25 bytes CJam is newer than this challenge, so this answer is not eligible for being accepted. Considerably shortened by user23013. ``` qN/_z,f{Se]}z{S+e`);e~N}% ``` [Test it here.](http://cjam.aditsu.net/#code=qN%2F_z%2Cf%7BSe%5D%7Dz%7BS%2Be%60)%3Be~N%7D%25&input=I%20am%20at%20ext.%0ATranspo%20se%20me.%0ACan%20you%20%20do%20it%3F) ``` qN/ "Read input, split into lines."; _z, "Transpose, get length (find maximum line length)."; f{Se]} "Pad each line to that length with spaces."; z "Transpose."; { }% "Map this block onto each line in the result."; S+ "Add a space to ensure there's at least one."; e` "Run-length encode."; ); "Discard the trailing run of spaces."; e~ "Run-length decode"; N "Push a newline."; ``` [Answer] # Javascript, 103 ``` s=>[...s].map((_,i)=>s.split` `.map(b=>r+=b[q=b[i]||q,i]||' ',r=q='')&&r.replace(/ *$/,q?` `:q)).join`` ``` *Less golfed* ``` s=>[...s].map( // we need 'i' ranging from 0 to the length of the longest input line // so we scan all the input string, that is surely longer // but we need to check that after some point the output must be empty (_, i) => ( r = '', // the current output row, starts empty q = '', // flag to check if we are beyond the longest line s.split('\n') // split in rows .map( b => ( // for each input row in b q = b[i] || q, // if there is a char at position i in b, i goes to q r += b[i] || ' ' // add to output the char at position i or a fill space ) ), q // if q is still '', we are beyond the longest input line ? r.replace(/ *$/,`\n`) // trim leading space and add newline : '' // no output ) ).join('') ``` **Test** ``` F= s=>[...s].map((_,i)=>s.split` `.map(b=>r+=b[q=b[i]||q,i]||' ',r=q='')&&r.replace(/ *$/,q?` `:q)).join`` function go() { var text=I.value var output = F(text) O.textContent = output } go() ``` ``` #I { width:50%; height:5em } ``` ``` <textarea id=I>I am a text. Transpose me. Can you do it?</textarea><br> <button onclick='go()'>Transpose</button> <pre id=O></pre> ``` [Answer] ## [Perl 5](https://www.perl.org/), 25 bytes Note that this uses ANSI escape sequences and as such does not work on TIO, you can however [see it in action here](https://asciinema.org/a/eOM9VLfMu4qfsLECNNlSlBbQi). ``` $"=" ";$_="[1;$.H@F" ``` ### Explanation This code first changes the [list separator (`$"`)](https://perldoc.perl.org/perlvar.html#%24LIST_SEPARATOR) value to be a vertical tab, followed by the ANSI escape sequence for 'go backwards 1 column' (`\x1b[1D`), then we set the implicitly printed variable `$_` to be a string that starts with the ANSI escape sequence for 'start printing at line 1 column `$.` (where `$.` is the current line of text)' (`\x1b1;$.H`) and interpolates the list `@F` (which is a list of all the characters on that line, populated by autosplit (`-a`) with an empty split pattern (`-F`)) which places the contents of `$"` in between each item, moving the cursor vertically down instead of continuing output after the previous character. [Try it online!](https://tio.run/##K0gtyjH9/19FyVaJWzra0EXJWiXeVgnIslbR83BwU/r/31MhMVchUaEktaJEjyukKDGvuCC/OFUhN1WPyzkxT6Eyv1QhJV8hs8T@X35BSWZ@XvF/3YLEHDcA "Perl 5 – Try It Online") [Answer] ## C++ (243 characters) Here's a function that takes and returns a string. I could've shaved a couple dozen chars, but decided to keep it as not-stupid code (runs fast, reads okay). Maybe I only decided to do that because this is my first code golf... I'm not hardcore enough yet :) ``` string f(string s){stringstream ss(s);vector<string> v;for(size_t i=0;getline(ss,s);++i){if(v.size() < s.size())v.resize(s.size());for(size_t j=0;j<s.size();++j){v[j].resize(i,' ');v[j].push_back(s[j]);}}s="";for(auto& i:v)s+=i+'\n';return s;} ``` With formatting: ``` string f(string s) { stringstream ss(s); vector<string> v; for(size_t i = 0; getline(ss, s); ++i) { if(v.size() < s.size()) v.resize(s.size()); for(size_t j = 0; j < s.size(); ++j) { v[j].resize(i, ' '); v[j].push_back(s[j]); } } s = ""; for(auto& i : v) s += i + '\n'; return s; } ``` [Answer] Python 2.7 - **115 chars**: oneliner: ``` >>> a 'I am a text.\nTranspose me.\nCan you do it?' >>> "".join(["".join(i)+'\n' for i in zip(*[x+" "*(len(max(a.splitlines(), key=len))-len(x)) for x in a.splitlines()])]) 'ITC\n ra\naan\nmn \n sy\napo\n ou\nts \need\nx o\ntm \n.ei\n .t\n ?\n' ``` and in a cleaner printing: ``` >>> print "".join(["".join(i)+'\n' for i in zip(*[x+" "*(len(max(a.splitlines(), key=len))-len(x)) for x in a.splitlines()])]) ITC ra aan mn sy apo ou ts eed x o tm .ei .t ? ``` **in 115 chars:** ``` >>> len(""""".join(["".join(i)+'\n' for i in zip(*[x+" "*(len(max(a.splitlines(), key=len))-len(x)) for x in a.splitlines()])])""") 115 ``` [Answer] ## GolfScript, 51 chars ``` n%.{,}%$-1=" "*:y;{y+y,<}%zip{n\+0{;).32=}do}%((;\+ ``` This is a first attempt; I suspect it can be improved. Most of the code is to comply with the padding and trailing space removal requirements — without them, just `n%zip n*` would suffice. Ps. The following **46**-character version will do the job for the given sample input, but will crash if any input column consists entirely of spaces: ``` n%.{,}%$-1=" "*:y;{y+y,<}%zip{0{;).32=}do]}%n* ``` I assume that's enough to disqualify it, even if the challenge doesn't explicitly say so. [Answer] # Scheme/Racket 113 The text: ``` (define t (list (string->list "I am a text.") (string->list "Transpose me.") (string->list "Can you do it?") )) ``` Without new lines and extra white spaces: ``` (define s(λ(v x)(if(= x 0)'()(cons(list->string(car v))(s(cdr v)(- x 1))))))(s(apply map list t)(length(car t))) ``` The user-friendly version ``` (define text (list (string->list "I am a text.") (string->list "Transpose me.") (string->list "Can you do it?") )) (define transpose (λ(text length) (if (= length 0) '() (cons (list->string (car text)) (transpose (cdr text) (- length 1))) ))) (transpose (apply map list text) (length (car text))) ``` [Answer] ## Haskell ``` import Data.List main = interact (unlines . transpose . lines) ``` It was so short, I needed to add in white space... [Answer] Python ~~89~~ 103 chars ``` def f(a):return'\n'.join([''.join(i).rstrip()for i in zip(*[j+' '*99 for j in a.split('\n')])]).rstrip() ``` I feel dirty. ~~90~~ 104 chars for industrial strength version. :^) [Answer] # Mathematica, 95 chars ``` f=""<>Riffle[Thread@PadRight@Characters@StringSplit[#,"\n"]//.{0->" ",{x___," "..}:>{x}},"\n"]& ``` [Answer] # K, 56 This should meet the spec now. Accepts a string, returns a string. ``` {`/:{$[" "=*|x;|(+/&\" "=|x)_|x;x]}'x@'/:!max@#:'x:`\:x} ``` . ``` k)f:{`/:{$[" "=*|x;|(+/&\" "=|x)_|x;x]}'x@'/:!max@#:'x:`\:x} k)f"I am a text.\nTranspose me.\nCan you do it?" "ITC\n ra\naan\nmn\n sy\napo\n ou\nts\need\nx o\ntm\n.ei\n .t\n ?\n" k)f f"I am a text.\nTranspose me.\nCan you do it?" "I am a text.\nTranspose me.\nCan you do it?\n" ``` [Answer] # Groovy, 98 chars ``` {i->o=[].withDefault{''};i.readLines().each{it.toList().eachWithIndex{c,d->o[d]+=c}};o.join('\n')} ``` [online](http://groovyconsole.appspot.com/script/5165882108018688) ungolfed: ``` {i-> o=[].withDefault{''};//create list with empty string as default value i.readLines() .each{ it.toList() //split every line to characters .eachWithIndex{ c,d->o[d]+=c //append to string from list with right index } }; o.join('\n')}//join list with newlines } ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 11 bytes ``` # aYcw1;.tY ``` [Try it online!](https://tio.run/##K6gsyfj/X1khMTK53NBaryTy/39PhcRchUSFktSKEj2ukKLEvOKC/OJUhdxUPS7nxDyFyvxShZR8hcwSewA "Pyth – Try It Online") Takes input as a string, outputs a list of lists # [Pyth](https://github.com/isaacg1/pyth), 25 bytes ``` # aYcw1=+Z1;jbcj"".n.tY)Z ``` Takes input as a string, outputs a string. [Try it online!](https://tio.run/##K6gsyfj/X1khMTK53NBWO8rQOispOUtJSS9PryRSM@r/f0@FxFyFRIWS1IoSPa6QosS84oL84lSF3FQ9LufEPIXK/FKFlHyFzBJ7AA "Pyth – Try It Online") [Answer] # J, ~~28~~ 26 Bytes Saved 2 bytes thanks to frownyfrog ``` t=.,@:(,&LF"1)@|:@:>@cutLF ``` Takes a string, returns a string. I'm not sure if there's a shorter version of the 'cutopen' ~~function~~ *verb* that I could use. There's also the shorter ``` t=.|:@:>@cutLF ``` But I'm not sure it falls within the OP's guidelines, as it returns an array of characters. ### How it works: ``` cutLF | Splits the input on new lines and boxes them @ | Composes verbs (as does @:, but they're not equal) > | Unboxes this, forming an array of the lines @: | |: | Transposes the array ( )@ | ,&LF | Appends a new line... "1 | To each row of the array @: | , | Flatten the result t=. | Assign this verb to t ``` The other version works the same, but doesn't convert the transposed array to a properly formatted string. ### Examples: ``` NB. Define a multi-line string text =: 0 : 0 I am a text. Transpose me. Can you do it? ) t text ITC ra aan mn NB. There's whitespace after the 'n' here, but I assume it doesn't count as trailing since it's part of the original string sy apo ou ts eed x o tm .ei .t ? t t text I am a text. NB. Again, whitespace here, but it's part of the argument of the second 't' (added by the first 't' to keep columns straight) Transpose me. Can you do it? ``` [Answer] # [Lua](https://www.lua.org), ~~203~~ 189 bytes ``` t={{}}i=1m=0(...):gsub(".",function(c)n=#t[i]if c=="\n"then i=i+1t[i]={}else t[i][n+1]=c end m=m<=n and n+1or m end) for x=1,m do for p=1,i do io.write(t[p][x]or" ")end _=m<=x or print()end ``` [Try it online!](https://tio.run/##TU89T8MwEN3zK05hcdTUIhkRJwYmdjZjIZO69ERtR44TgqL89nCuWsFyfh@n93zn0WxbwmVZV8LG4b2QUlYPn8P4IUpZ1sfRd4mCF13l8S4p0nSEDrF882U6WQ@EtGuyjstqz4OFjJXfNRo7sP4ADt0jejAMWQ0RXJar4shwxqZ2cAiQSc@EMqEgvyMlK5LqtZp1iCWUVc56z1kz5OVIPoksbvu9Ulda3N6c91XDBMQ/7A3FQaSKswu4VFHLXvvPnK4m/JVPrZS5l1Vu4XnLZqb1tr2AcWAg2TnJ4jUaP/SBz3dWFs/Gw08YL7ekp18 "Lua – Try It Online") I saw another Lua solution here, but I don't think there's a problem with posting 2 solutions on the same language. If there is, tell me :) ]
[Question] [ Your goal is to write a program that prints the following poem exactly as it appears here: ``` There was an old lady who swallowed a fly. I don't know why she swallowed that fly, Perhaps she'll die. There was an old lady who swallowed a spider, That wriggled and iggled and jiggled inside her. She swallowed the spider to catch the fly, I don't know why she swallowed that fly, Perhaps she'll die. There was an old lady who swallowed a bird, How absurd to swallow a bird. She swallowed the bird to catch the spider, She swallowed the spider to catch the fly, I don't know why she swallowed that fly, Perhaps she'll die. There was an old lady who swallowed a cat, Imagine that to swallow a cat. She swallowed the cat to catch the bird, She swallowed the bird to catch the spider, She swallowed the spider to catch the fly, I don't know why she swallowed that fly, Perhaps she'll die. There was an old lady who swallowed a dog, What a hog to swallow a dog. She swallowed the dog to catch the cat, She swallowed the cat to catch the bird, She swallowed the bird to catch the spider, She swallowed the spider to catch the fly, I don't know why she swallowed that fly, Perhaps she'll die. There was an old lady who swallowed a horse, She died of course. ``` The text must appear exactly as it does here, and fewest characters wins. Edit: Your program may not access the internet. [Answer] ## Perl 5.10, ~~392~~ ~~384~~ ~~372~~ ~~235~~ 369 (ASCII) / 234 (Unicode) The shortest ASCII version of this is 369 characters long: ``` @_=(fly,spider,bird,cat,dog);$_="There was an old lady who!ed a";for$P("",", That wrJand Jand jJinside her",", How absurd&",", Imagine that&",", What a hog&"){$p=$c;$c=$".shift@_;$t=$p?"She!ed the$c to catch the$p, $t":"I don't know why she!ed that$c, Perhaps she'll die. $_";$_.="$c$P. $t";s/&/ to! a$c/}s/!/ swallow/g;s/J/iggled /g;say"$_ horse, She died of course." ``` It started from this base program: ``` my @animals = qw(fly spider bird cat dog); my $buf = "There was an old lady who swallowed a "; for my $phrase ( "", ",\nThat wriggled and iggled and jiggled inside her", ",\nHow absurd&", ",\nImagine that&", ",\nWhat a hog&" ) { $previous = $current; $current = shift @animals; $trail = $previous ? "She swallowed the $current to catch the $previous,\n$trail" : "I don't know why she swallowed that $current,\n" . "Perhaps she'll die.\n\n$buf"; $buf .= "$current$phrase.\n$trail"; $buf =~ s/&/ to swallow a $current/; } say "$buf horse,\nShe died of course."; ``` The core idea is to keep the end of the rhyme and the beginning of the next one in `$trail`, augmenting it as we go along. It's made non-trivial by the need of a special case for the first use, and the attempt to re-use the animal name variable even in the animal-specific phrase. Further optimizations include: * one-character identifiers for everything * using barewords instead of quoted strings for the animal list * use of the accumulator `$_` for `$buf` to shorten most substitution operations even more (use of `@_` is by force of habit and doesn't win anything more than any other character) * including the preceding space directly inside the animal name variable (the space character taken from the `$"` variable) * regexp substitution to shorten the most common phrases: `' swallow'` and `'iggled '` * no code spacing whatsoever and all `\n` in string literals replaced with actual newlines All but the last optimization yield this: ``` @_ = (fly, spider, bird, cat, dog); $_ = "There was an old lady who!ed a"; for $P ( "", ",\nThat wrJand Jand jJinside her", ",\nHow absurd&", ",\nImagine that&", ",\nWhat a hog&" ) { $p = $c; $c = $" . shift @_; $t = $p ? "She!ed the$c to catch the$p,\n$t" : "I don't know why she!ed that$c,\nPerhaps she'll die.\n\n$_"; $_ .= "$c$P.\n$t"; s/&/ to! a$c/; } s/!/ swallow/g; s/J/iggled /g; say "$_ horse,\nShe died of course."; ``` Additionally, this golf is a victim of the underspecified encoding problem. As it—as of now—counts individual characters instead of bytes in a specified encoding, there's a big gain to be achieved by decoding the program source from UCS2 before starting. The final result isn't very readable anymore, but it's short all right. (234 characters, counted as a difference from `perl -E''` as usual) (I had to include the trailing newline back to make it valid UCS2) ``` $ perl -MEncode=from_to -e'$_="‰Åü„¥®Êô¨Á§¨Áç∞Ê•§Êï≤‚±¢Ê•≤Êê¨Êç°Áê¨ÊëØÊú©„¨§ÂºΩ‚âîʰ•Áâ•‚Å∑ÊÖ≥‚ŰÊ∏†ÊΩ¨Êê†Ê±°Êëπ‚Å∑ʰ؂֕Êê†ÊÑ¢„≠¶ÊΩ≤‚ëꂆ¢‚ਂਇ©îʰ°Áê†Áù≤‰©°Êπ§‚ÅäÊÖÆÊê†Ê©äÊ•ÆÁç©Êë•‚Å®Êï≤‚ਂਇ©àÊΩ∑‚ŰÊâ≥Áï≤Ê궂ਂਇ©âʵ°Êù©Êπ•‚ťʰ°Á궂ਂਇ©óʰ°Áê†ÊцʰØÊú¶‚à©Á¨§ÁÄΩ‚ë£„¨§ÊåΩ‚ê¢‚π≥ʰ©Êô¥‰Åü„¨§ÁêΩ‚ë∞„º¢Âç®Êî°Ê蓼ťʰ•‚룂ťʺ†Êç°Áë£Ê††Áë®Êî§ÁĨ‡®§Áꢄ®¢‰§†ÊëØÊ∏ßÁê†Ê≠ÆÊΩ∑‚Å∑ʰπ‚Å≥ʰ•‚Ö•Êê†Áë®ÊÖ¥‚룂∞äÂÅ•Áâ®ÊÖ∞Áå†Áç®Êîßʱ¨‚ŧʕ•‚∏䇮§Âº¢„¨§ÂºÆ„¥¢‚룂ëê‚∏ä‚륂àªÁ娂ò؂ťʺ°‚Ű‚룂ΩΩÁåØ‚ÑØ‚Å≥Áù°Ê±¨ÊΩ∑‚Ωß„≠≥‚Ωä‚Ω©Êùßʱ•ÊꆂΩß„≠≥ÊÖπ‚à§Âº†Ê°ØÁâ≥Ê©ìʰ•‚ŧʕ•Êê†ÊΩ¶‚Å£ÊΩµÁâ≥ÊîÆ‚àä";from_to($_,utf8,ucs2);eval' ``` A good thing there was a lot to golf from before resorting to Unicode, or it wouldn't be much fun. *Edit:* ~~can't find a way to copy/paste the 234-character version to this browser, so I'm leaving the 235-character one. Will fix this evening, when I get my hands on a real UTF8-aware clipboard.~~ found a way. [Quasi-proof on ideone.](http://ideone.com/lGxnl) [Answer] ## Perl, 120 94 chars Count includes call to the interpreter. You did say to reproduce it *exactly* as it does here ;) ``` perl -MLWP::Simple -E'($p=get("http://goo.gl/kg17j"))=~s#^.+?pr.*?de>|</co.*?re>.+$##sg;say$p' ``` ### N.B. This solution is what prompted the 'no-Internet' restriction. Let it be a lesson for future code-golf question specifications :) [Answer] # Vim, 373 keystrokes ``` iThere was an old lady who swallowed a fly. I don't know why she s<C-n> that f<C-n>, Perhaps she'll die. T<C-x><C-l><Left><C-w>spider<Esc>oThat wriggled <Esc>6hiand <Esc>3hy$u$ppbij<End>inside her. She s<C-n> the sp<C-n> to catch the f<C-n>, I<C-x><C-l><C-x><C-l><Esc>qqyapGp3jYPkk$Bqcwbird<Esc>+CHow absurd to sw<C-n><Backspace><Backspace> a b<C-n>.<Esc>qwyb5wvep$Bvepq@qcwcat<Esc>+CImagine that to sw<C-p> a cat.<Esc>@w@qcwdog<Esc>+CWhat a hog to sw<C-p> a dog.<Esc>@w@qcwhorse<Esc>+cGShe d<C-p>d of course. ``` Funny how exponential that scrambling is. [Answer] ## Python 3.x: 407 chars ``` import base64,zlib;print(zlib.decompress(base64.b64decode(b'eNrlkLFOxDAQRPt8xXTXoHwHdEhEot7L+myD8Z7snKz8Pd6LT7mgFFQIRGftPs/OzOBMMiiUQRESGIF4RnGCXCgEKYZBOIW5B7onsMTDhPcopTIzsjN33ORoUvShos8mOTpnJQ4hgL3pu2741rF89mySigwqWJK3NugmMu6eb+3tY648qrRafPniyDQ5TIKRptFdZ83kz+Q5+sQq8ViP0DFfEquZRrT9vnXdbI2v3fzCoPXs9dgHWR/NorpJWoH9oONCrr5vnf35TlisKryqGsGJ3TZS1/uN8EKurlu5/6k7Jymbm7f6kSEnjHKp0/4TSSOZgA==')).decode('utf8')) ``` [Answer] ## JavaScript (422) Works in the [SpiderMonkey interpreter versions](https://developer.mozilla.org/en/Introduction_to_the_JavaScript_shell) used by both [anarchy golf](http://golf.shinh.org/) and [ideone](http://www.ideone.com/5KomT). ``` for(a="fly0spider0bird0cat0dog0horse0How absurd0Imagine that0What a hog".split(i=0);p=print;p("I don't know why she swallowed that fly,\nPerhaps she'll die.\n")){p("There was an old lady who swallowed a",a[i]+(i?",":"."));i>4&&quit(p("She died of course."));i&&p(i>1?a[4+i]+" to swallow a "+a[i]+".":"That wriggled and iggled and jiggled inside her.");for(j=i++;j;)p("She swallowed the "+a[j]+" to catch the "+a[--j]+",")} ``` A bit more nicely formatted: ``` for (a = "fly0spider0bird0cat0dog0horse0How absurd0Imagine that0What a hog".split(i = 0); p = print; p("I don't know why she swallowed that fly,\nPerhaps she'll die.\n")) { p("There was an old lady who swallowed a", a[i] + (i ? "," : ".")); i > 4 && quit(p("She died of course.")); i && p(i > 1 ? a[4 + i] + " to swallow a " + a[i] + "." : "That wriggled and iggled and jiggled inside her." ); for (j = i++; j;) p("She swallowed the " + a[j] + " to catch the " + a[--j] + ","); } ``` [Answer] # [ink](https://github.com/inkle/ink), ~~370~~ ~~369~~ 354 bytes ``` LIST B=fly,spider,bird,cat,dog,horse VAR s=" swallow" -(i)~B=B(i) There was an old lady who{s}ed a {B}{.|,} {|That wriggled and iggled and jiggled inside her|How absurd|Imagine that|What a hog|She died of course.->END}{|.| to{s} a {B}.} -(k)~B-- {B: She{s}ed the {B+1} to catch the {B}, ->k }I don't know why she{s}ed that fly, Perhaps she'll die. \ ->i ``` [Try it online!](https://tio.run/##TdBBa8MgGAbgu7/io5duzAR2HaQw2WCBMcZatssuNtro4rRoigR1fz37QgvbSfHzfXlU22Gen9vtDlhzMBMNRy2kp3vtBe34SIXrqXI@SPJ@/wahWUGI3BgXV6S60tc/rGG4kJ2SXkLkAbgFZwQYLiaIyqVQpAAOiZVUZ1pIyjvFR4he971ZRlbAv@3XZa9tQAhgbX5yEfg@nLzI7TfvtZUwYkX@WHo4KNfnrZIgNMbcATp3Qm5dbR5fHkrKdYZxUZwNdUH2gOyqIondEQyehSM2JHZzW/A24MM7dTkqlFSbgZQWhLPrEQaLnKgmCH9RdCx/R16lV/wYltHamEVUk0/AvJ7nXw "ink ‚Äì Try It Online") ### Explanation ``` LIST B=fly,spider,bird,cat,dog,horse // Ink's "LIST"s aren't much like lists - they're more like enums. Here we create a list type stating what animals exist, and make a set containing none of them. VAR s=" swallow " // Pretty self-explanatory -(i)~B=B(i) // The i label keeps track of how many times we've visited it. We set B (the set) to be equal to the i-th item in B (the list type). There was an old lady who{s}ed a {B}{.|,} // Print the first line. {.|,} is a sequence - it's a period the first time it's encountered, and a comma every subsequent time. // Sequences can have more than one item in them, which is how we print the second line. When we get to the horse one, we terminate the program right away. {|That wriggled and iggled and jiggled inside her|How absurd|Imagine that|What a hog|She died of course.->END}{|.|to{s} a {B}}.} -(k)~B-- // Step back through the list type. {B: // A conditional - we execure the next two lines if B is non-empty. She{s}ed the {B+1} to catch the {B}, // Print the "she swallowed the..." line ->k // And repeat }I don't know why she{s}ed that fly, // Only reached when the conditional fails. Perhaps she'll die. \ // A backslash and a space to force an empty line. ->i // Back to the top ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~429~~ ~~424~~ 423 bytes -5 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) ``` c,*w[]={"384fly<1","I don't know why she5ed that fly<Perhaps she'll die.772","There was an old lady who5ed a ","She5ed the "," to catch the "," swallow"," to5 a ","\n","spider","bird","cat","iggled ",",7","3948<0"};U(char*s){for(;c=*s++;)c>47&c<65?U(w[c-48]):putchar(c);}f(){U("2fly.718<That wr;and ;and j;inside her.709<How absurd69.7=:<Imagine that6:.73:49<=dog<What a hog6dog.73dog4:<3:49<=horse<She died of course.7");} ``` [Try it online!](https://tio.run/##PVDLbsIwEPyVVQ4loRDxCHEepr2WW6WCeqAcjO3EaYON7CALIb6dbkDtZeyd3RnNLh/XnN9ufDT0293yEsyzpGrPdBqMghUIowcd/GjjwaszOCUXUkCnWAf90Lu0ih1dzw/aFkQjY0JmqFwraSV45oBpMK2AlokzWphezgAnPv6sZF9BZ4Czjqt/wnnWtsY/eouH5ksjuGMjpMXPvrECH5QhNnXdoh3@RgRhnicZnQTXchNyxezQRZfK2LDky6F7fi4j/pKQJ07Txesm9Fs@TrJdVBxPXT8c8qi8VmF02YTBDLeMyTSj635lb0umBdzhu2y0wySAm8ZkktM3vBHbu5MVaR6TZUFXB1Y3Wt6vlRYxmRdJTpfC1PSzN2OgTJ1iiR3EpKCPAWWskxTP059TgKmAmxNSMQkw163RHRxYozEfZkTiFw "C (gcc) ‚Äì Try It Online") [Answer] ### Ruby, 436 characters ``` w=" swallowed " f="There was an old lady who#{w}a " c=" to swallow a %s" b="dog","cat","bird","spider","fly" s=nil,"That wriggled and iggled and jiggled inside her","How absurd"+c,"Imagine that"+c,"What a hog"+c a=[] 5.times{k=g=b.pop;t,*s=s puts f+k+(t ??,:?.),t&&[t%k+?.,a.map{|x|y,k=k,x;"She#{w}the #{y} to catch the #{k},"}],"I don't know why she#{w}that fly,","Perhaps she'll die.","" a=[g]+a} puts f+"horse,","She died of course." ``` [Answer] ## Scala (~~706~~ ~~619~~ ~~599~~ 550 chars) ``` val L=Seq("fly","spider","bird","cat","dog") val M="\nThere was an old lady who %sed a %s," type S=String def s(l:S,a:S="",b:S="")=l.format("swallow",a,b) def p(l:S,a:S=""){println(s(l,a))} var i=0 var r=List[S]() L.map{a=>{p(M,a) if(i>0){p(Seq("","That wriggled and iggled and jiggled inside her.","How absurd","Imagine that","What a hog")(i)+(if(i>1)" to %s a %s."else""),a) r::=s("She %sed the %s to catch the %s,",L(i),L(i-1)) r.map(p(_))} p("I don't know why she %sed that fly,\nPerhaps she'll die.") i+=1}} p(M,"horse") p("She died of course.") ``` Using map instead of foreach allows to squeeze more chars... In codegolf, we don't care about performance, elegance (non-mutability) or logic... [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~503~~ 484 bytes ``` $i=" bird" $k=" swallowed" $g="She$k the" $h=" to catch the" $c="There was an old lady who$k a" $e=" to swallow a" $s=" spider" "$c fly." $c="`n$c" ($a="I don't know why she$k that fly,`nPerhaps she'll die.") "$c$s,`nThat wriggled and iggled and jiggled inside her." ($d="$g$s$h fly,") $a "$c$i,`nHow absurd$e$i." ($j="$g$i$h$s,") $d $a "$c cat,`nImagine that$e cat." ($b="$g cat$h$i,") $j $d $a "$c dog,`nWhat a hog$e dog.`n$g dog$h cat," $b $j $d $a "$c horse,`nShe died of course." ``` [Try it online!](https://tio.run/##VZExbsMwDEX3nIIQCKQFWt/Ae7MVaICukUVWUqJKgeTAyOldUvGQbhT53@c3fS0L1xY4pXdXKq8rxtHAFCuZHV6kbItNSUT69qP5CowXmAPLM8h4LuDs7MLWcqM5Bq4Mi21gM5REkCzdYQlFOCsSflCbb2813XONxNXsDDr4SffhYXbK6MzuBe1oDkAl72e4ZKGWcIe2RbGzAm@n/Mk12GvTwT4loMiDeVVDbDI9qnCp0fvEJNkInsrzVsfcJAbIJwy6lkaDHhuGvkHM0Ha/KH4fGn5qt0rIGLv83OURgyxUMW16PZEQh1/rY@YeGVmbnZqU0pdwsXPnJ5SKF/Rbw1sIxQsorUEO47WQaGou15r@c6HUxkLKD9NLEJQfcOUmzcGs6x8 "PowerShell Core ‚Äì Try It Online") It was a fun one! :) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~237~~ ~~222~~ ~~218~~ 224 bytes +6 bytes to fix a bug (In most verses the first line ends in a `,`) ``` ‚Äú¬§‚Ć√â¬æ¬£‚İ‚Äî√Ñ‚Äπ¬∑√ƂǨ‚Äú#¬©‚Ǩ‚Äú‚Ǩ√á‚Ǩ¬•‚Ǩ¬§‚Äû√謣√ƂǨ√ê 1ed‚Ǩ‚Ķ √ø,‚Äú¬Æ¬¶¬¶¬®.‚Ä¢Œ©\3¬Ø√ì√µ√î)V‚ÇÑH`¬´√Ö‚ÇÜ√©√ÖŒòŒì√•√≤‚Ä¢ƒá¬°Œ¥"√ø to 1 a √ø."√Ö\‚Äú‚Ǩ≈† wr0‚Ǩ∆í 0‚Ǩ∆í j0‚Äπ√¢‚Äö¬Æ.‚Äú≈°‚Äú‚Äö√é≈ì¬∑‚Ǩ‚Äö‚ͬ£.‚Äú¬™0≈°√∏0Œ¥K¬Æ√º‚Äú‚Äö√é 1ed‚Ǩ‚Ǩ √ø‚Ǩ‚Äû¬¨¬™‚Ǩ‚Ǩ √ø,‚Äú¬®Œ∑√≠√µ≈°Œµ‚Äúi¬•√ö't∆í‚Ǩ‚Äû√ù‚Äö√é 1ed‚Ǩ≈†¬§‚Ć,‚Äú¬™‚Äú‚Ñ¢¬°‚Äö√é'll‚Äî√á. ‚Äú¬™}√µ¬™.ŒπÀú.¬™¬ªT.‚Ä¢4∆µ‚Ä∫‚ÇÖ8zŒµ√öS‚Ä¢#‚ݬ®','..; ``` [Try it online!](https://tio.run/##TVFBSwJBFL73KwY9LIEMK3UI@gNBx6KTh4w8GIJQQhAEw@ImXSq0QywmrqboZhuEi1mR8F7rJZgfMX9kezNmxMCbN/O@933fvCmf5A@KhSRRogkPSrTxEj6hq4SvxC1WlZjCBEPljKiehuEioYg1CtDTgbpaeA1dA8Mbli0cGlif4SyjaUPo0xpwJTpymFuDZ2xghLere8qpbu3DI7rKucAhuvJONrCHLwT8qoEvxymcsUqZZVmeuHgK3dxCPW6z02Obknmd/W5HNnnFjhIehKTUjH0NFR5exQ2YGEMeeYKuLkJgxz6@2nK8DSF@LJFL686I5ExLC0YQ/F2Z1wzkBJ8win0Z0bEIPfSsyry@gOP9f6K4bUZq2gItUu2AbwBWqaTnW@MrpnaOEQRcTr@bHAJ439WjWp8T/5ty3I0zGaG3Q1dp@hYYWBmL880k@QE "05AB1E ‚Äì Try It Online") **Commented:** ``` ‚Äú¬§‚Ć√â¬æ¬£‚İ‚Äî√Ñ‚Äπ¬∑√ƂǨ‚Äú # push dictionary compressed string "fly spider bird cat dog horse" # # split on spaces ¬© # store the list of animals in the register ‚Ǩ‚Äú‚Ǩ√á‚Ǩ¬•‚Ǩ¬§‚Äû√謣√ƂǨ√ê 1ed‚Ǩ‚Ķ √ø,‚Äú # for each animal, push the string "there was an old lady who 1ed a √ø," # where √ø s replaced by the animal ¬Æ # push the list of animals again ¬¶¬¶¬® # remove the fly, the spider and the horse: ["bird", "cat", "dog"] .‚Ä¢Œ©\3¬Ø√ì√µ√î)V‚ÇÑH`¬´√Ö‚ÇÜ√©√ÖŒòŒì√•√≤‚Ä¢ # push alphabet compressed string "xhow absurdximagine thatxwhat a hog" ƒá # extract the first character "x" ¬° # split the remaining string on "x": ["how absurd", "imagine that", "what a hog"] Œ¥"√ø to 1 a √ø."√Ö\ # format the string "√ø to 1 a √ø." with a value from this list and one from the short animal list # => ["how absurd to 1 a bird.", "imagine that to 1 a cat.", "what a hog to 1 a dog."] ‚Äú‚Ǩ≈† wr0‚Ǩ∆í 0‚Ǩ∆í j0‚Äπ√¢‚Äö¬Æ.‚Äú # push compressed dictionary string "that wr0 and 0 and j0 inside her." ≈° # prepend this to the list ‚Äú‚Äö√é≈ì¬∑‚Ǩ‚Äö‚ͬ£.‚Äú # push compressed dictionary string "she died of course." ¬™ # append this to the list 0≈° # prepeand a 0 √∏ # zip both lists together 0Œ¥K # remove 0's in sublists # => [["there was an old lady who 1ed a fly,"], # ["there was an old lady who 1ed a spider,", "that wr0 and 0 and j0 inside her."], # ["there was an old lady who 1ed a bird,", "how absurd to 1 a bird."], # ["there was an old lady who 1ed a cat,", "imagine that to 1 a cat."], # ["there was an old lady who 1ed a dog,", "what a hog to 1 a dog."], # ["there was an old lady who 1ed a horse,", "she died of course."]] ¬Æ # push the list of animals again √º‚Äú‚Äö√é 1ed‚Ǩ‚Ǩ √ø‚Ǩ‚Äû¬¨¬™‚Ǩ‚Ǩ √ø,‚Äú # format the string "she 1ed the √ø to catch the √ø," with adjacent pairs of animals ¬® # remove the last string # => ["she 1ed the spider to catch the fly,", "she 1ed the bird to catch the spider,", "she 1ed the cat to catch the bird,", "she 1ed the dog to catch the cat,"] Œ∑ # take the prefixes of this list √≠ # reverse each prefix √µ≈° # prepend the empty string Œµ # map over the prefixes: ‚Äúi¬•√ö't∆í‚Ǩ‚Äû√ù‚Äö√é 1ed‚Ǩ≈†¬§‚Ć,‚Äú # push compressed string "i don't know why she 1ed that fly," ¬™ # append to the prefix ‚Äú‚Ñ¢¬°‚Äö√é'll‚Äî√á.\n‚Äú # push compressed string "perhaps she'll die.\n" ¬™ # append to the prefix } # end of map √µ¬™ # append an empty string to the list of prefixes .Œπ # interleave the list of prefixes with the earlier list Àú # flatten everything into a list of lines .¬™ # sentence-case each line ¬ª # join by newlines T # push 10 .‚Ä¢4∆µ‚Ä∫‚ÇÖ8zŒµ√öS‚Ä¢ # push compressed string "swallow iggled" # # split on the space ‚İ # in the poem replace every digit of 10 with the corresponding word in this list # 1 -> swallow, 0 -> iggled ¬® # remove a trailing newline ','..; # replace the first "," with a "." ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 195 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` √≥‚î§‚ô£‚â§j√ü¬°ŒµD<√áj√≤‚â°¬≤¬£c¬º√¨v‚î¥√Ö√¥‚ïë,¬∑~‚¢‚ïùEŒ¶5xZ&‚àöœÉ"√∏m√ø‚â°ZœÄv√Ö‚ï¶‚ô£1‚ô¶>‚ñÑ\¬¨‚óò¬°jS¬¢√≠‚ïû‚ïü‚ïö);4j‚Üïi¬¢s‚ô¶√©√á√∂y‚ĺac‚î¥√†√á‚𤋮ª-√≥¬ª√≥n√∫¬¢‚îÇg5Œµ√ø‚ï‚î¨b√Æ√¶¬¢k‚ĺf‚ïìfJ‚óã‚ñê‚ïê‚ïú<^Œì‚ñÄo‚ñÄŒînq‚ñë‚社±√Ñ&‚îÇ‚ô£‚Åø√¢m√ª‚ï£√á‚â°*@‚ò∫pG_‚Åø√∂‚î§mœÉ/V\‚îî?iq‚îå√ÆB¬Ω√ѬøL‚ïôN‚îꬣ√á‚╌¥2 0Œ¥r¬µL√§‚å°(‚å°‚ñÄ‚ï¨√†Œ¶‚å†t∆í√¨g" ‚å†ZH√≥ ``` [Run and debug it](https://staxlang.xyz/#p=a2b405f36ae1adee443c806a95f0fd9c63ac8d76c18f93ba2cfa7ec59bbc45e835785a26fbe522006d98f05ae3768fcb0531043edc5caa08ad6a539ba1c6c7c8293b346a12699b730482809479136163c18580caaf2da2afa26ea39bb36735ee98c9e6c2628c919b6b1366d6664a09decdbd3c5ee2df6fdfff6e71b0cae08e26b305fc836d96b980f02a400170475ffc94b46de52f565cc03f6971da8c42ab8ea84cd34ebf9c80f2eb322030eb72e64c84f528f5dfce85e8f4749f8d672220f45a48a2&i=&a=1) Unpacked, ungolfed, and commented, it looks like this. ``` `]q~*}8x9uA3_P0O`jX push ["fly", "spider", "bird", "cat", "dog"] and store in X register { start iteration over animal list `p{+P91{m@Lwe\Jk?!#8`Yp Store "There was an old lady who swallowed a " in Y register and print it .,.i!@+ Concatenate "." on the first iteration and "," thereafter to the animal P Print i{ On all iterations after the first, execute this block `r4uB2O'O(4XghNqE PhaMg^-riMgR{N>A8LfCNqh@Rn$=aHX|93@_5d?d7qp2-` Push "That wriggled and iggled and jiggled inside her. How absurd, bird. Imagine that, cat. What a hog, dog. She died of course" ',`?~nA${F"`R Replace "," with " to swallow a" .. / Split on string ". " iv@ Get the (i-1)th element where i is the iteration index '.+P Concatenate "." and print }M End of conditional block x2B Get adjacent pairs from x (list of animals) i( Keep first i pairs where i is the iteration index r{ Iterate over reversed list of pairs `_,m+"S3&#`p Print "She swallowed the " Ep Print the second animal from the pair `p<qr?t`p Print " to catch the " ',+P Concatenate "," to the first animal from the pair and print F End iterating block `;p(9Cv,77BzpP'kB|"`P Print "I don't know why she swallowed that fly," `%?/3.=iHiS6y!`P Print "Perhaps she'll die." zP Print a newline F End outer animal iteration. yp Print y register. ("There was an old lady who swallowed a ") `zvVH`P Print "horse," Print "She died of course." with an unterminated literal `AJt6Q.3+$! ``` [Run this one](https://staxlang.xyz/#c=%60%5Dq%7E*%7D8x9uA3_P0O%60jX++++++%09push+%5B%22fly%22,+%22spider%22,+%22bird%22,+%22cat%22,+%22dog%22%5D+and+store+in+X+register%0A%7B++++++++++++++++++++++++%09start+iteration+over+animal+list%0A++%60p%7B%2BP91%7Bm%40Lwe%5CJk%3F%21%238%60Yp%09Store+%22There+was+an+old+lady+who+swallowed+a+%22+in+Y+register+and+print+it%0A++.,.i%21%40%2B++++++++++++++++%09Concatenate+%22.%22+on+the+first+iteration+and+%22,%22+thereafter+to+the+animal%0A++P++++++++++++++++++++++%09Print%0A++i%7B+++++++++++++++++++++%09On+all+iterations+after+the+first,+execute+this+block%0A++++%60r4uB2O%27O%284XghNqE+PhaMg%5E-riMgR%7BN%3EA8LfCNqh%40Rn%24%3DaHX%7C93%40_5d%3Fd7qp2-%60%0A+++++++++++++++++++++++%09Push+%22That+wriggled+and+iggled+and+jiggled+inside+her.+How+absurd,+bird.+Imagine+that,+cat.+What+a+hog,+dog.+She+died+of+course%22%0A++++%27,%60%3F%7EnA%24%7BF%22%60R++++++%09Replace+%22,%22+with+%22+to+swallow+a%22%0A++++..+%2F+++++++++++++++%09Split+on+string+%22.+%22%0A++++iv%40++++++++++++++++%09Get+the+%28i-1%29th+element+where+i+is+the+iteration+index%0A++++%27.%2BP+++++++++++++++%09Concatenate+%22.%22+and+print%0A++%7DM+++++++++++++++++++%09End+of+conditional+block%0A++x2B++++++++++++++++++%09Get+adjacent+pairs+from+x+%28list+of+animals%29%0A++i%28+++++++++++++++++++%09Keep+first+i+pairs+where+i+is+the+iteration+index%0A++r%7B+++++++++++++++++++%09Iterate+over+reversed+list+of+pairs%0A++++%60_,m%2B%22S3%26%23%60p+++++++%09Print+%22She+swallowed+the+%22%0A++++Ep+++++++++++++++++%09Print+the+second+animal+from+the+pair%0A++++%60p%3Cqr%3Ft%60p++++++++++%09Print+%22+to+catch+the+%22%0A++++%27,%2BP+++++++++++++++%09Concatenate+%22,%22+to+the+first+animal+from+the+pair+and+print%0A++F++++++++++++++++++++%09End+iterating+block%0A++%60%3Bp%289Cv,77BzpP%27kB%7C%22%60P%09Print+%22I+don%27t+know+why+she+swallowed+that+fly,%22%0A++%60%25%3F%2F3.%3DiHiS6y%21%60P+++++%09Print+%22Perhaps+she%27ll+die.%22%0A++zP+++++++++++++++++++%09Print+a+newline%0AF++++++++++++++++++++++%09End+outer+animal+iteration.%0Ayp+++++++++++++++++++++%09Print+y+register.+%28%22There+was+an+old+lady+who+swallowed+a+%22%29%0A%60zvVH%60P++++++++++++++++%09Print+%22horse,%22%0A+++++++++++++++++++++++%09Print+%22She+died+of+course.%22+with+an+unterminated+literal%0A%60AJt6Q.3%2B%24%21&i=&a=1) [Answer] # [Zsh](https://www.zsh.org/) + coreutils, ~~406~~ 375 bytes ``` g()ls -t<>"She$d the $1 to catch the $2," set bird spider \ swallow iggled\ <<Z ${b=There was an old lady who${d=$3ed} a }fly.${5= I don't know why she$d that fly, Perhaps she'll die. $b}$2, That wr$4and $4and j$4inside her. `g $2 fly`$5$1, How absurd${6= to$3 a }$1. `g $@`$5cat, Imagine that$6cat. `g cat $1`$5dog, What a hog$6dog. `g dog cat`$5horse, She died of course. ``` [Try it online!](https://tio.run/##5VTBTuswELz7K1ZoJUAKkfqAnlrgCDckkJ5UccDNOnHAjavYKOoL/fa@dRyghSI4IRCXyPJOdmdG6/nn9CojwL3ZvVezORzQvsikP0nz0WgirrWqFTTSgazAGgIjaQGNtuAaaYxtFIGE3CxScQFkq10P95VtGLEAp9UaymvpAzARl6rWcu5CfdcYoFKl4pOD3LwkVSeM5mZNXRaFCfcVwdrxrj@XlWM0cONUXL3iovpW4C2w2kx3dx29r9AxLWtKxDkPkFP3UFOg0df76jbK4X6T8JMf30wej@RBM1mUlYodN/RxeZu8LOJe@EaXfrAPZItE/A2dJGhbbLrAxW0uUMS9sO3M/A1uaVs7FVnxbwQ2h8w@8F0qJqJdFXv7xsGBH53sMAQjYRxsksU/yY5wykfVvZybZ9djMtyACNmG7XT8LjNsaYyHipZMbBnyDdvj8VYb8EP5OF0yr6fQwqMQUvF7h0frKXVbsIDQ6BaPcbAeENgOx6wUDwMdHEToGcPePDUcds@L62FDcMCYV2uIw271GBF2jVEMed/71UQsH71SkBaCyjyH9JTdG@Hp6j8 "Zsh ‚Äì Try It Online") Tricks: * the `g` function creates the line as a file and then `ls` lists the files in the current directory in order of creation (`-t`), to avoid having to repeat the previous lines every time. + I used `<>` (which creates the file before the command is executed) instead of `>...;` because using multiple commands in a function requires `{}` around them * `set bird ...` assigns the words to `$1`, `$2`, etc. * `\ swallow` includes a space at the start of without needing to use quotes * `<<Z` starts a heredoc which is effectively a long interpolated string * `${b=There...}` is a shorthand form setting `b` to that string and substituting its value in * Indexed variables like `$1`, `$2`, etc. can be substituted without a space afterwards (rather than being interpreted as a variable called `5dog`, for example), so we prefer them as it allows us to include the space inside the assignment to avoid repeating it * `g $@`: since we set `$1` and `$2` to `bird` and `spider` respectively, we can pass all the numbered variables to `g` in one go with `$@` instead of `g $1 $2` (it ignores the extra ones, `$3` etc.) [Answer] ## Haskell, 515 498 *Score does not count newlines and spaces added for presentation.* ``` b c a="There was an old lady who swallowed a "++a++c++".\n" t r a=b(",\n"++r++" to swallow a "++a)a s(a,b)="She swallowed the "++a++" to catch the "++b++",\n" z=["fly","spider","bird","cat","dog"] h=[b"",b",\nThat wriggled and iggled and jiggled inside her",t"How absurd", t"Imagine that",t"What a hog"] v(g,p)=g++(=<<)s(zip p$tail p)++ "I don't know why she swallowed that fly,\nPerhaps she'll die.\n\n" main=putStr$(=<<)v(zip(zipWith($)h z)(tail$scanl(flip(:))[]z))++b ",\nShe died of course""horse" ``` ### Ungolfed: ``` type Animal = String type Comment = String beginning :: Animal -> Comment -> String beginning animal comment = "There was an old lady who swallowed a " ++ animal ++ comment ++ ".\n" ending :: String ending = "I don't know why she swallowed that fly,\nPerhaps she'll die.\n\n" to_swallow :: String -> Animal -> Comment to_swallow start animal = ",\n" ++ start ++ " to swallow a " ++ animal swallowed_to_catch :: (Animal, Animal) -> String swallowed_to_catch (a, b) = "She swallowed the " ++ a ++ " to catch the " ++ b ++ ",\n" animals :: [(Animal, Animal -> Comment)] animals = [("fly", const "") ,("spider", const ",\nThat wriggled and iggled and jiggled inside her") ,("bird", to_swallow "How absurd") ,("cat", to_swallow "Imagine that") ,("dog", to_swallow "What a hog") ] -- Turn [1,2,3,4,5] into [[1], [2,1], [3,2,1], [4,3,2,1], [5,4,3,2,1]] trail :: [a] -> [[a]] trail = tail . scanl (flip (:)) [] verses :: [String] verses = zipWith verse animals (trail $ map fst animals) verse :: (Animal, Animal -> Comment) -> [Animal] -> String verse (animal, comment) swallow_chain = beginning animal (comment animal) ++ concatMap swallowed_to_catch (zip swallow_chain (tail swallow_chain)) ++ ending poem :: String poem = concat verses ++ beginning "horse" ",\nShe died of course" main :: IO () main = putStr poem ``` [Answer] ## Python, 484 Ok, I did it but was pretty boring... The last sentence is always with "fly" so some chars were removed... ``` f,s,b,c,d=o='fly spider bird cat dog'.split() x='There was an old lady who swallowed a %s.\n' t=' to swallow a %s.\n' r=['That wriggled and iggled and jiggled inside her.\n','How absurd'+t%b,'Imagine that'+t%c,'What a hog'+t%d] t=("She swallowed the %s to catch the %s,\n"*4%(d,c,c,b,b,s,s,f)).split('\n') print("I don't know why she swallowed that fly,\nPerhaps she'll die.\n\n".join([x%f]+[x%o[i]+r[i-1]+'\n'.join(t[-i-1:])for i in range(1,5)]+[''])+x%'horse'+'She died of course.') ``` Less golfed version: ``` f,s,b,c,d = all = 'fly spider bird cat dog'.split() what = 'There was an old lady who swallowed a %s.\n' t = ' to swallow a %s.\n' comments = ['That wriggled and iggled and jiggled inside her.\n', 'How absurd' + t%b, 'Imagine that' + t%c, 'What a hog' + t%d] swallowed = "She swallowed the %s to catch the %s,\n" lines = (swallowed*4%(d,c,c,b,b,s,s,f)).split('\n') end = '''I don't know why she swallowed that fly, Perhaps she'll die.\n\n''' def who_catch_who(i): return '\n'.join(lines[-i-1:]) p = end.join([what % f] + [what % all[i] + comments[i-1] + who_catch_who(i) for i in range(1,5)] + ['']) print(p + what % 'horse' + 'She died of course.') ``` [Answer] # C, for fun (561 chars) *Score does not count newlines and spaces added for presentation.* Thanks to J B for his improvements! ``` #include <stdio.h> void main() { char *e = "\nShe swallowed the cat to catch the bird,\nShe swallowed the bird to catch the spider,\nShe swallowed the spider to catch the fly,\nI don't know why she swallowed that fly,\nPerhaps she'll die.\n\nThere was an old lady who swallowed a "; printf("%sfly.%sspider,\nThat wriggled and iggled and jiggled inside her.%sbird,\nHow absurd to swallow a bird.%scat,\nImagine that to swallow a cat.%sdog,\nWhat a hog to swallow a dog.\nShe swallowed the dog to catch the cat,%shorse,\nShe died of course.", e+191, e+128, e+85, e+41, e, e); } ``` [Answer] **C#, 556 chars** ``` class P{static void Main(){string a="There was an old lady who swallowed a ",b="I don't know why she swallowed that ",c="She swallowed the ",d=" to catch the ",e="Perhaps she'll die.\n\n",f="fly",g="spider",h="bird",i="cat",j="dog",k=",\n",l=".\n",m="to swallow a ",n=c+g+d+f+k,o=c+h+d+g+k,p=b+f+k,q=c+i+d+h+k,r=n+p,s=o+r,t=q+s,u=e+a;System.Console.Write(a+f+l+p+u+g+k+"That wriggled and iggled and jiggled inside her"+l+r+u+h+k+"How absurd "+m+h+l+s+u+i+k+"Imagine that "+m+i+l+t+u+j+k+"What a hog "+m+j+l+c+j+d+i+k+t+u+"horse"+k+"She died of course.");}} ``` [Answer] # Perl, 489 chars ``` sub Y{$t=pop;my$s;while($b=pop){$s.="She ${W}ed the $t to catch the $b,\n";$t=$b;}$s.=$l{fly}.$/;}$W='swallow';$w='iggled';$q=" to $W a";$o="There was an old lady who ${W}ed a";$h='hat';@f=qw/fly spider bird cat dog/;@l{@f}=("I don't know why she ${W}ed t$h fly, Perhaps she'll die.$/","T$h wr$w and $w and j$w inside her.","How absurd$q bird.","Imagine t$h$q cat.","W$h a hog$q dog.");map{$m=$f[$_];print"$o $m, $l{$m} ",$_?Y@f[0..$_]:'';}0..$#f;print"$o horse, She died of course.$/" ``` [Answer] # [PHP](https://php.net/), 344 bytes ``` <?=gzinflate(base64_decode("5VAxTsQwEOz9iu2uifIO6JA4iXovu2cbjPdk+2Tl96zjoLugFFQIRGfNjGdn5ug4MVTMgBEkEASkGaoTyBVDkMoECOcwj+YRSOKhwFuUqooZsuM7VXFYmnAwT5wcXnLjDyEAeR6NOX7rUL544jSoWs1q8taGhkeCu+fr+vYxqxrUeDTPX7LwagVFYMIyuQVb4v1Ej5NPNJgHPYCnfE3UYqz8yu5Fbvg28Ocev6yentRD72h95O646af0Xr2p6255+0p/eAcSO5iX5oTgxG5XUHJvBeq6W9plzP+wlpOUuafSbwRyhkmuio0f")); ``` [Try it online!](https://tio.run/##BcHJcoIwAADQf/Gkw6FKSZBpOx1UQC0QZBN66QAmrBIQw/bz9r0ma16vz@@vdM5rUkVPvIyjDkPh74YTesPLBfDl0e0ug4JmKWc8y8kJwbMs5AHtGZ/EhXUrOd6tJDgXVGepql5OtkbMQrvVgKWC4btGulNKRXZKLaLutPMPpUGVPUqGggttB/1kg8q8ltLfjhmiH6jhvZYHFwxJUOvFYVJkbEMTBeLD04EgFA69dpt2@4y0rMR7xpEH14djOz48fHCtQNSHKPXV0DhN7OLHQr9RCmBa5jk9WuG@Jsq7F7bzdmJAjfuU36IE93DC9dM@iHwmAQQFGJF18OAbyAPArZs3LCcOAnkAqJuOGgi847nf4RZepaaaLW6oGuSxiDjxYE9ZeWc5XZPFavXxev0D "PHP ‚Äì Try It Online") # [PHP](https://php.net/), 405 bytes ``` <?=strtr("0fly. 106That wr8and 8and j8inside her. 23107, How absurd57. 274623109, Imagine that59. 2947, 27462310dog, What a hog5dog. 2dog49, 2947, 27462310horse, She died of course.",["There was an old lady who swallowed a ","I don't know why she swallowed that fly, Perhaps she'll die. ","She swallowed the ","spider to catch the fly, "," to catch the "," to swallow a ","spider, ",bird,"iggled ",cat]); ``` [Try it online!](https://tio.run/##XVDPS8MwFL7nr3jkMoVQOu3WFRWv7iZs4EE8vDVZE41NSTJC//r60k1kXh7k@/W@l0EP0/T4/BSij/6Gl0c7FmxZrvcaIyS/wV7CPD43pg9GKtDKF@zuflnWgr24BHgIJy9XNYF1tc5EI9j2GzvTK4gUs2qIaiqS/wqk6wR7yxsQtOtW9CYJzYqs11LtfFCC7bQCaZQEd4TWnQgruHjneyqjIGEA7MFZCRblCEk7CAmtdYkcCFzwLUjXLyJ89dQ46RECBf5pck2g0wV7VV7jEDK/sDbvLBijgN0/vcqpYaAP8RAdtBhbPcNzCnHX6AW4JJw7nd1ZfDBeCm66zlI2F2T7uH2Yph8 "PHP ‚Äì Try It Online") [Answer] # Bubblegum, 255 bytes ``` 0000000: e0 04 85 00 f7 5d 00 2a 1a 08 a7 55 8e 22 31 d2 ‚îÇ √†...√∑].*..¬ßU."1√í 0000010: cb f7 30 fa 52 4d 88 81 61 e4 be 9d c2 f0 0e f8 ‚îÇ √ã√∑0√∫RM..a√§¬æ.√Ç√∞.√∏ 0000020: dc c9 de 24 63 c9 1f c7 f7 71 e4 ed 40 68 0e d2 ‚îÇ √ú√â√û$c√â.√á√∑q√§√≠@h.√í 0000030: cd 76 d8 d9 0d 61 78 f7 40 cf 23 95 48 e9 be 27 ‚îÇ √çv√ò√ô.ax√∑@√è#.H√©¬æ' 0000040: aa 75 57 ff 51 9e 1f 1f 25 d8 93 4d 18 69 c9 01 ‚îÇ ¬™uW√øQ...%√ò.M.i√â. 0000050: 12 16 ec c1 ff e0 01 7e fa ea 1e cc 84 d7 58 b8 ‚îÇ ..√¨√Å√ø√†.~√∫√™.√å.√óX¬∏ 0000060: 47 d4 40 b4 ff c7 64 a9 2f 07 bf 7b f4 25 74 94 ‚îÇ G√î@¬¥√ø√ád¬©/.¬ø{√¥%t. 0000070: af da 8a fc 0c 18 81 58 b8 3c 2e 97 c0 9d e8 27 ‚îÇ ¬Ø√ö.√º...X¬∏<..√Ä.√®' 0000080: 3e 02 8a d2 1b 7c 94 cc cb f4 05 7c c7 77 f3 75 ‚îÇ >..√í.|.√å√ã√¥.|√áw√≥u 0000090: ea 7e 02 d6 3a 84 5c 4e 1f 88 e7 03 9a 1d 3f 13 ‚îÇ √™~.√ñ:.\N..√ß...?. 00000a0: a6 9f 2e cf be 77 16 be f1 5f 01 52 cf 13 89 b3 ‚îÇ ¬¶..√è¬æw.¬æ√±_.R√è..¬≥ 00000b0: f3 8a f7 90 18 08 50 99 27 f7 83 d2 a4 32 08 76 ‚îÇ √≥.√∑...P.'√∑.√í¬§2.v 00000c0: ef b4 99 6c 80 dd 1a 47 04 26 fe b1 02 b3 d4 e7 ‚îÇ √ج¥.l.√ù.G.&√欱.¬≥√î√ß 00000d0: 3d 44 3a 64 64 46 39 77 35 61 6b 6c 7b 68 34 db ‚îÇ =D:ddF9w5akl{h4√õ 00000e0: 51 75 39 2e bc 46 8e 96 d1 8a 4c 79 f4 7a 7b e0 ‚îÇ Qu9.¬ºF..√ë.Ly√¥z{√† 00000f0: f5 44 85 eb ef 68 d5 22 26 4a 2a ef fc 60 00 ‚îÇ √µD.√´√Øh√ï"&J*√Ø√º`. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~453 442 427~~ 387 bytes * **@nore saved 11 bytes:** Thanks a ton!!: pointed `¬£` used before was a double byte char!! * saved 15 bytes: `swallow` shorthand * **@nore saved 40 bytes!!!!!** THANKS A LOT!!! * @Zachary T saved 1 byte: space between `in` and `"..."` removed * Thanks to notepad++'s find and replace tool. ;) ``` r="%2(:0)That wr66j5 inside her(_1)How absurd+1({3)Imagine that+3(}4)What a hog+4(~4*3)}horse)She died of course." for i in"}~3*1){!{~1*0)_!_~0*2):!:^2)$%!~She7ed the !%There was an old lady who7ed a !$Perhaps she'll die(\n!* to 3ch the !^I don't know why she7ed that !+ to7 a !(.\n!),\n!0spider!1bird!2fly!3cat!4dog!65 and !5iggled!7 swallow".split("!"):r=r.replace(i[0],i[1:]) print r ``` [Try it online!](https://tio.run/##JZBPi8IwEMXvfopJUTZppfSfCgXv621hhT24KrGJTXazSUkipYj96m6KlzkM7/fevOkGL4wunk@7jRYFrjOyF9RDb9frnxVI7STjILjF55y8mx7oxd0sS3J8L8nuj7ZSc/CBSEr8qMjXxFIQpk0qPFZxSR7CWMfJp@DAJGdgrtCYW1il0exqLMiQET3GMs7JHd3HPM7IGZ3HLC5IjepTQeYLNAZ6E1gfTNBiH67h0FMHVINRDBRlA/TCTBIKaP7BraCdAyf4m1JTLP7WKAZvoGzEy@W0A2b0m4dfHUr1YpjUr4zQACVBvJnMcBpQsgwjc114hUX5RVqGiqsaUNlQjypmWrRehWMYoJVsW8UZ2oDrqVKmj1LXKelxhCJS261NLe8UbTiWh@y4lIe8PpJZZ6X2YJ/Pfw "Python 2 ‚Äì Try It Online") [Answer] # Groovy, 475 bytes ``` b="swallowed" a="There was an old lady who $b a" c="I don't know why she $b that fly,\nperhaps she'll die." d="She $b the" e=" to catch the" f=" to swallow a" g="iggled" h=" spider" i=" fly" j=" dog" k=" cat" l=" bird" m="$d$h$e$i," n="$d$l$e$h," o="$d$k$e$l," print""" $a$i. $c $a$h, That wr$g and $g and j$g inside her. $m $c $a$l, How absurd$f$l. $n $m $c $a$k, Imagine that$f$k. $o $n $m $c $a$j, What a hog$f$j $d$j$e$k, $o $n $m $c $a horse, She died of course.""" ``` Nothing too interesting, just a lot of string interpolation. Golfing tips on this one are welcome! [Answer] # tcl, 451 bytes ``` lassign {\ swallowed fly, spider " to catch the " bird cat iggled " to swallow a"} W f s c b a i w puts "[set t "There was an old lady who$W a "]fly. [set I "I don't know why she$W that $f Perhaps she'll die. "]$t$s, That wr$i and $i and j$i inside her. [set S "She$W the "]$s$c$f $I$t$b, How absurd$w $b.[set v \n$S$b$c$s,\n$S$s$c$f\n$I]$t$a, Imagine that$w $a. [set X $S$a$c$b,$v$t]dog, What a hog$w dog. ${S}dog$c$a, $X\horse, She died of course." ``` Available to run on: <http://rextester.com/live/GXF89639> (10th attempt) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 349 bytes = Script:9 + Archive:340 ``` tar xOf t ``` [Try it online!](https://tio.run/##5VRBTsMwELz7FStxCEhp3lAJCegJpCJxdu1NbHC9ke0QUvH3sG6C2qIeOCEQN3t2PDszB7fUY4gGnRsvxbIQjwYDQi8jSA/kNDipB@gNQeylc8zWIKF2QyVWoMkXCV489cwYgGWOWMnIlImleMBgZBvzvHAOtMVKfHNRbK3GUDKbxfpgm8Zl3Gs4Oj7PZ@sjs4GFK7H@4gVnKUgESiZl9tje3k/k2NigS3HHC@QmdkFnG/N8np6znPFTw599/LJ4vJIXbWVjPU6KJ/l4fC6emngHv1NLf7gHTU0pnrKSBEPNaQs8PNeCnngHt/sy/0NbhkLEyRU/00A1KOoYq0SxFFfwDmtMi2vyCT1vg8UNBYUiyQA7VRMwJm4zw1inVwm3UJcJLoC61HaJvwPmyA3fQAZl7CsHsDsc8/u3@xrSOH4A "PowerShell ‚Äì Try It Online") The Powershell script to create the archive `t` (see TIO): ``` ( @' There was an old lady who swallowed a fly. I don't know why she swallowed that fly, Perhaps she'll die. ...... There was an old lady who swallowed a horse, She died of course. '@ ) | Set-Content f -Force tar zcfo t f Get-ChildItem f,t # output info about archive size ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 295 bytes ``` BinaryDeserialize@ByteArray@ToCharacterCode@"8C:xœ√•PAN√É0<√£W√¨¬≠—(√Ø€R‘8o¬≥[√õ√Öx+;••√∞n√ñq¬™6(N√Ñ√çš√è√é√å√æ√£√°√Öqb(˜#H H'ê † … Ža√™√çê√Ñ√ùoQŠ*&√àŽ√ØT¬£√ɬ± ;√≥√å√â√°9W~ê√ß√û˜√Ø √ägOœ:U¬´YI√û√öP√±Hp√∑<-o¬≥¬™Aç{¬≥√ø’…+ 7cs¬ºŸ√®q√∞‰:√≥¬®√∞ê/‰jŒ…_√ò¬≠√à_¬æ√Æ√±√ã√™√©I=√¥Ž√ñGnެ´~Jo√ïš√Æ–¬∑¬≠√¥‡w ¬±ùy¬≠NN√¨z%¬∑V¬†¬¶¬ª¬•ù√á√ºk9I™[*√ΩF G√§¬¢X√ø T√ø”\"" ``` [Try it online!](https://tio.run/##DY7RS1NxAIUpsM16UNDQsOiyKIcS9WQ6DTYnuvWwZswsDMavedFbuduuF3IGEuhVZ26taGtOZ9mybDrnuMIeNIVz/rB1387Ddz6@GaFPyzNCVyKiHtSUqC6564NKVGjxIXlW1hTxRpmX3YNxXfZomoi7Q6p3WmgiosuaV52U3Y5er2sOW9wNegJcvN88wOI4D1DGNycr@NDxBJ97VZgT3KQx192PDDJNPIoyG0Opx2kL2LnEJPLX@IkprvOMRe7QiL10Infhlk@y@1paO5G@gmUJRmMzUoIlJluQtm4FuzqKta47XEWKlRCKXET1cj9Ny5PgTt/4QttFC/zDbeRYucG1qcfYco1h/7mf28wHWfW9ZW3grnoTJkoeJN/D5Dm@wGjrbm@4dN32IDKLU3znXoxHSLhoYs9mrfQ9JF5hHUaYOZS5ejVswxkPWeVHK@6v/yGPraDsSBQp7C88UpnpQJ6HyKJm4cdYeSehikIc5YA9wIP5htuoPcUP/MYJdlHgCk@bXvf5sTHRxX/D0kg7f@HnM543hqy6ry8cjnr9Pw "Wolfram Language (Mathematica) ‚Äì Try It Online") This solution is a 46-byte decompressor `BinaryDeserialize@ByteArray@ToCharacterCode@"..."` acting on a 248-byte array masquerading as an ASCII string. Transferring this string between different programs is a bit tricky. TIO, for instance, blows this solution up into 416 bytes using UTF-8 encoding instead of keeping the ASCII string. To get the minimal 295-byte solution, save the text in a variable `text` and run ``` BinaryWrite["ThereWasAnOldLady.wl", Join[ ToCharacterCode["BinaryDeserialize@ByteArray@ToCharacterCode@\""], Normal[BinarySerialize[text, PerformanceGoal -> "Size"]] /. {34 -> Sequence[92, 34]}, ToCharacterCode["\""]]] ``` then execute the generated file on the command-line with ``` wolframscript -print -f ThereWasAnOldLady.wl ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~512~~ 493 bytes -19 bytes thanks to ceilingcat ``` *s[]={"That wriggled and iggled and jiggled inside her.","How absurd to swallow a bird.","Imagine that to swallow a cat.","What a hog to swallow a dog.","fly","spider","bird","cat","dog","horse"};r(i,x){return i&&r(i-1,!printf("She swallowed the %s to catch the %s,\n",s[i+4],s[i+3],x&&puts(s[i-1])));}f(i){for(i=0;printf("There was an old lady who swallowed a %s.\n",s[i+4]),i<5&&puts("I don't know why she swallowed that fly,\nPerhaps she'll die.\n",r(i++,1)););puts("She died of course.");} ``` [Try it online!](https://tio.run/##XVDBbsIwDL3zFV6klWYUBNp26riP26Qh7cB6CE3aZAtJlaQqqOLbmcOKBsvBsWPnvedXTuuyPJ0e/KZY9mQtWYDOqbrWggMzHK7SryFXxisuQAo3Ixl5tR2wrW8dh2DBd0zr@AJb5Xjsr3asVkZAiNA3EyULceAjNhhIW9@2ua1ju9IHjL5BSodJhMUL/2LEEYzSOi/IMXepyva0dyK0zoBKEnyYLrK7xikTqpS8S3GBxy0CVvc@UiJWKYc6@zQk8xs1eSrO12OR7ZOkaYNPsZwuCkppfqxSRfvKIv5ynl/g12iIgI55NAus5qAZP0An7RUpQ4rZHwXN1MvzAE9WuLEZB/g2uH4nD@D/6UWb0AxU@CacZI2PA2OtgStxxkQ5k0m2QIE0/4WMG2OXg62gtC3aNCMo/4SCYceUSSn0I8BTpTQ/J4N583x0PP0A "C (gcc) ‚Äì Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~516~~ 408 chars -108 chars by not restricting the allowed characters to CJK Unified Ideographs Extension B ``` "ÓÄàÛç´úÒê∂ÜÚÖè†Úû±¢ÒæáúÚÇ∫∏Û∞®ëÚâ∂úÛãäï°ùà≤∫æÒíùßÚù≤âÙ屨ÙàôΩÛóòµÛÜà™Û©ô≥ÚèêóÒ†≤øÛòÖπÚô¥≤ÚüùéÚèàÆ´õÆÚº∂≤ÛõâºÒöõºÒ©ùÜÒ¶àøÛ°∂àÚßäÑÚø¢≠ÒºµÇÒ¥£∞륶Òπø≥Ûê£áÒÇùèÛíÖßÙÉúÅÚñªåÚè∑æÛ†âµÛïΩá†ÉóÛè¢πóøÑêΩ¢ÛíàèÚêÑèÚÇøüÚ醸Ûå≥èÒì¨∞ÙåéáÚóøÄÙáú†ÒôèºÚö∞¨ÙÇííÛò°ΩÙà≤ÇÒ∏≠àÚñç®ÚÑÅôÚä•àÒπàßÚÄáîÚ¨ü™ïÉùÛØòíÆ®âÚµõôÛü©∂ÚùÇèÒ⢺ÒíøæªúíÙàè∏Ûú±øÚ®ô®üå®ÙİΩú¥ÇÒ∑ü†º∏ØÚû∫ØÚ™∞©ÚáøôÙå±äÚñÄ∏Ûõ©Øê∏ùÒï¶Äóå¨Û±©≤Ú©π∂Ò¶àÑÒÄßêøÇâÛ∞§ßÒ±û©Ûáà∂üù´ÙéüÉºßïÒπΩñÚ•§≠ÛÖ•ö≠õ®ÒØñÖ•µ∞Ó£øÛóÅÑÒú§àÒõ©æÚà∫ºÒ©íâßìßÒ≥°†ö®Ö¨ÆæÙã°àÒ≠Ç≠ÛßöùÛ¨¶ÄÚΩû≤Û≥∑ëÚïöíÛ≤´¨Ûú£°ÛåáôÒÄø∫ó®ªÒÖé±ÙàôÜÚå£≥ÛØëÄÛØ©åÛ©ÑÄÛ¥æèÚÇɪÛ∫ùºÚÄô£Û´¥ãÒ∂è©Û¶≠ÖÚπ∂ÆÛπù≠Úò£µÚææ≤ÚÄè†∞ÆÑùúü¥Ñî§â∏≥∞†Ú¶≥´ëáàÛØÉùÒÆ™∑ÒêºáÛêîèÛø†≤êܨÛé∞ñÚÖÅïÒùæó¶¥ÉÛ∏´£ÚáãøÒ¶â¨Ú±íéÛóò°Û∂Ü£•™ÅÛùñåÛ™¨Ç≠°éÛÑéïÛù£òÙÄïπÒòéìö¢óÛ∂ߥÒÑ©ìÙÇ™éÒë¶≥Ú¨™≥Ø®ØÛõ©ÉñöûÛï´ØÒó≠øÒãßâÙÄ••Òô©§ùë∏Ûá±åÙÖßπÚ∞ñÄÛèÉãÚû∂òÚöì¶Ûå∂ôëå®Ò≥¶¥Úº´∞ÚüªñÚÇ™∑ôÑ¢Ú´ìéÒÑûõÛãπÜÛæúßÙäªûÛÑëÄÒõòÅÚÅÄ∂•®™Ú∂ì£ìåÉÒõëïÒü≤ßÛë§£Ú䆨ÚÜπ†Ú∑†∂ÛúöπÙÄ∑¶Ú•º¥Òªπöù∞ß©¢ÄÒêöåë®Æôé¢ÒüèäÛ∂ذÛïÑÇ≤öÜÛ∂ñâ۶ħÚîΩêÚπ≥úÛ¨î®ÙѰ°ÒÅ∂èñûëÚÑ≥ü¶≠äÒÜñúÒó∫ÑÒᣢÒπì®Ò©ΩÖÒ≥åæÚ≥ôôÒΩŪó≤µÛéò∫†ΩéÚÄñªÛåáôùóÄÒ∂ߥÛ∑±≥Ú©±Ñ¢†äÚºíê∂å•û∞™™â∞ÒüÜØÚçê≥ïüÑÒ¥¥ïÚöòôÛ≠ÆõÛ≥ùºÒº£ÆÒâ∏ÖÚº∫¥êªôÚóäéÒ´ê™Ú∞ä¶Ûª≠∏ô°§ߨöïöæÙçê†Û¢ä¨ÒÇëΩÚü¨Å∂ãèÒÆòéÛæô∫"√á≈Ω√°√°-‚Ä¢GŒ±m‚Ä¢Œ≤‚ÇÜB≈Ωm&",.' "‚İ"ÓÄîùπáÚù¢áÛ∞¨æÛπ≠üÚ™ÑôÒóúÇÚó°Öû¶ÇÚΩáéÙå°±Ûº≥•Úºµâ∞ãàÚ®óÑ•ÖåÛ´†ùÛîåìÛÑØáÚëçòÛè≥ä∂ÉÄÚ±º∫õí¥Ò•ª≥Ú≤âåÒ£µÜÛæ±ßÚº£πæ±´†ÉÄÛ∂∏¶Òùó∑Ûê∑ÆÛú≥Ñ∫∫Öª≤ÜÛ≥àÜÛÖ±ÉÚû†©Ò¥∏πÛ¨ÆΩÚ´ØåÚ∞∂¢Òùâ´ÒÜ•¶Ûüæ®ÚóïºûÖÄÚòÇ®ÙÅå£ß§ÄÚöÇÖÒíé†ÙÉ∑ÜÛñ±éòº®¨øäÛôµ≤Òè≠âÒºÄÄ"√á≈Ω√°√°-‚Ä¢GŒ±m‚Ä¢Œ≤bT‚ÄûAa‚İ.√è ``` [Try it online!](https://tio.run/##bdRL0qqIHQXweVaRuoNkkvQekkk2kA10V2XQg64MsgFEEFA@8PEpoiLgg4eiIiiKog5u9bQXcRfQ9X8wvzHzjM78d06df//nx59@/tf3719@F1T@2M6wW7RINj2aHxf4VGYk3q6cRj3Sihl32kPwHRWy2xP7TkhOptX68VCr9oOt8Zlb6oZjOyeza6GXvXgsl2SfMnIdg0x1D9vpnqoi46lW4WRaYey0MFBf7BcqhW2JXosdVmcRT8sUeqcAy1fO3aWComNyXw7r5qxBo7tO5uXJnnbm4UMBr2mxuSjBeknQfSy4r5rUlUwSXy4Z3ov13MRBkta6oZD1Empl5qFtVjRJk1rs93nsP2o1E/G6U2n0EZHUsKm9VrFUQxKUT0rcDQybDh/GfdhHGp2nNrtxQY5ooraosP96wn3Wr1XzyrPjiyI7AlePasF/wOwk4sX1oLoeaH470CaNSXnZb7M2jYQrT@MDdK8ODgMBLD3hY5xRXBZvEwmFsAsvUeN0FeJxHrOiFuA629pwm1CFQywfI1qvdiyvJ7CbRngYybA@p78vX2w1JJytVJzGT1Jvb@a@BuEgxNz3YBLJkOyfdcdXcSfuOJw4nAQCPeYZ55ceDSd9zrYJz5Y@64qNwusGVnRH2Ti@a26Rvsz50BP4EOscSwKfnm/q5p1vTkWCveTtqYOFGXOwk6ks9lw6Oxovz/R8ZiSYHqR7CZyZCyfpE1baFfLUoyDfQk9R@dB0cL@5YLdSuPtp8svLoNtK2EhHJDeG6DwtCE5Nvm6XpHReGGgJHfvGe3o@F60lrDcNdkY6bxIRdr7BkjFkZzmuhWGJY2MAk4XFRXhCKR7U4sbAXpBTssnhEB3eVTRhNJnzcHtAa/fCTqjVwnqNdrwCp3dl5ajXclhSOhLYbHZoXoxpMghYL2zo6RHmwYmqbUrufUTi5gK2tKDtwEBpPuVO2eLnLKzb9zlLPQGn4wY1hALW0YaKwRIGehOnvSG6Wci91ZLa3oFapUcXr@DZpKyFS0Dr6oT3cgJOGkK8ELA70aEX7cE2FuiabS4OPg8lEbJJi4uRxoGwos9Hl8p8xslnVEu@j43ChNG8R1LuQrBrY2s0Q@smobJcYDmIMH7ImOtPym0bH407WNmZjfENvIdBwuj@vz2AYwn4NuTLMaf4KMHCa1PV70Khr2GebmCjpei2DvTRzWHoSng6DWkytnm3n3LuVFgt96hdZapuJ@jebbLaBm67G0rbAd93V7D9FYTJBIaTZ/3R9XjRTlDsPchNGlB0TNyPDX7aty9flV8fX/2v/l@/CYt//Hb85R2/Zd/E1t9/ffzypy9/@eHPf/zDl2@C/761T3BKhZyFwmny5HLn0kay0ZqJZPkyzAORHopR6/6Rq3xN1VmDtKNSZEmwlnXeeg5/6gOWDgr1PsZs5m0omgIdqxtM@ydc33PKNB2X53fHx5CqZQnP4/Z9SwIX1wAd68Ldy55nuQS3mwz3rMW52mL52KS5F@PpWnKyf9D2oFNaLNDRtthaB@w@I7KGFcxlgcZiVDf0JYQrgSaijH3Dq5uXFo@OBoyrCJJXm@1zhuZOw0oQ/r/NT//8Jsz/9uPb5Iev5vfv/wU "05AB1E ‚Äì Try It Online") This exploits the fact that this is an old question that counts in chars. # Version without using UTF-16 strings, 925 bytes ``` ‚Ä¢*‚Ñ¢w8?√°Z–º<r¬º√ã}√àdE√Ñ≈∏‚ǨKŒ≤;‚Äô√å√∑`‚ÇÜN√ãr;O√ô–ΩŒõ¬§√∏oE~√ù√π√á?}6√Ö¬±T√∑EƒÅ2¬≤√Ø√°pK|¬Ø√ê‚ĆÀúCY√Æ√¢√ÄJ¬Ø√ê‚ÇÖ‚ÄúŒªÀú'=\‚ÇÉ0ÀÜN‚ÄπBM¬©–ºe¬Ω√å¬Ω√ú√ô√à?QXt‚Äù v¬¥q√ò√∫!√æ3$√≤≈°p√¥/‚Äî√®i_√∞@tŒ≥¬µ√∞B}¬ØS‚ÇÑ6¬¥>√ùN¬ØŒ∂l√ß√¶‚ݬº¬∂¬ßƒÅj]\0√æGwN‚ÇÅ<√¢X1o∆µ[√íg¬≥K√ì‚Äπ√¨‚Äö√º√ø‚ÇÉ1E¬Æ√åŒ∑ í(Œî√ÉŒª√ãX≈íl¬µV#‚ÇÉ √鬧√ù¬¥√∂√∑Œµ_%C+z√ù-C-‚Ƭ¨‚Äòm√∂¬πz‚àç¬≥«ùq‚Ć‚ǨT í‚Äû2≈æU√û>√謩Œπ‚Äπ√≥‚â†√ø√∂√¨‚ÇÜ–Ω‚Äî‚ÇÉ\–ºƒÅ9√æ6jŒ©√õŒ≥‚Äû‚ǨL√ô√ê¬æYm9√Æ√Æa√º¬±¬µ≈í≈æ√ñ¬ª≈∏√¶√ó√ß√Æ√≥√∫¬Æ√π≈Ω√ä>√î‚ÇÑG√∑5Œõ‚Äös√ô‚ÇÜ=√∏Hl√£sP√è√ò\¬¨¬ªE‚ƬØ√Ñ√á≈†P@¬°≈†√Å*√ë‚ÇÅo∆µ¬∞e√∏¬æ√ô‚ÇÇ√é√¶‚ÇÇ.√Ç(‚ÇÖ‚ÄùuCDr‚İ‚ÇÉO√æR‚ÇÉ√Ü-&√ë√¢√Ä‚ÇÑÀúg¬æ√æ;q‚İ8}5,z‚ÄîH√∑‚Äπ}√ûj√¥&‚ÄûHKF√à‚↌ò√∫ƒÜ0¬∏aJ+b√†G√àz√û√âY4w-/√ä‚İŒ±_√ô$!i¬±‚Äî√æq9«ù*S–Ω«ùŒ∏eBQ√ëK+}‚Ä∞√ù‚Ä∞‚Äî‚İŒ©¬∂Œ£x¬¢32D√ì‚Ćv¬™‚Ä∞√ç%–∏t5≈æ*|√é√¶)¬≥‚ÇѬ°N√ΩX–Ω¬¶¬Æ√á√É√æ¬∏.¬∏√≤8r¬¢‚Ä∫¬ße‚Ä∫√å"P‚ÇÜ∆µƒÅ√ë√ñ¬∫jŒ£~√Ø` ‚àû√•≈íw√Ø√¨s√ê¬∫‚àäƒÅ‚Ä∞≈†¬Æ#¬∏–≤P=j√ª‚àä√ï√á√´√§√ª–º‚ÄîsJT«ù‚Äî∆í–≤¬º√™Œπ‚Äò√ô‚Ƭ®Œì√µƒáI√é√•≈°¬¢4√ª6√©‚Ä∫a‚Ñ¢√åV¬Ω∆∂‚â†√É√ël√´√∞Œ≤‚Ä∞¬´Àúp:‚Ñ¢¬∞¬Ω‚Äú¬∞2√Ø$¬£√§Œ∂g≈∏ ¬ØŒõ√øƒÜ‚Äû‚Ķ√ª‚â†Q¬≥¬π√Æ√®√Øu√∏√â‚ÇŬ¶√Å√ùl^¬®{√ä}–º√Å√±‚ÇÑ<–ΩŒò√Ø√∑@√£r1√¥√ë√å–Ω√ﬥ‚Ķ+√ï√ª√íO}√∂NŒ∑√Ü√ü√£‚Äò√≥√∑√ü0x√•1_|¬£√íŒ∂√úqz√ö¬ºW^√ï√¶√ìt\[≈°IvŒµ¬©l√∏‚Äö√ï‚àäH‚àûO≈í∆µ≈í‚Ä∫√∂;¬ªE¬æ∆∂ƒáƒÄ#8lr√†QÀúa√߬Ω>¬¨Œª√ì‚Ñ¢¬æ¬≤√≥p√∂Œ∑¬ºƒÄ-√¶ƒÜ‚ÄûWp6m‚Äù^t√∏gO√µŒõ¬¶‚â†√Ö√∫√ëDŒ≤= íRJŒ∂√£‚ÇÇ4N,]√ÑK√•√≠‚Ä¢‚ÇÜB≈Ωm&",.' "‚݂Ģv≈Ω¬≤~¬≥√ñƒÄw`]¬¨√™‚ÇÇR‚àûv¬≥√øk√ò√¶!Xh¬§li¬£4ƒÜdC¬µ A√´p U√é‚Äò¬±6 íŒπ√©¬µ√û3Y>√ù{#r9‚Ä∫¬Ω, √•<≈°*√•$‚ÄùW¬µ->M√©‚ÇÖ√•ÀÜ√≠√èV"¬£¬≥¬ß`%kI≈Ω¬≤,‚İ√®Œ±¬≤‚Äö‚Ķ √ôP¬ß¬¢‚àû>r‚Äù‚àç(+ƒÄ~‚àä¬≥Œ≤¬®√îX3√É√∞√ò¬≥≈æÀú√ª—Ç√ái√∫√â,9Œ©√ç√åJ√∂Œµ≈°¬¢‚↬´¬º‚ÄúUP¬∫i]¬§z¬•‚Ä¢bT‚ÄûAa‚İ.√è ``` [Try it online!](https://tio.run/##HZR5UxNpEMb/51Mg4LFccknBcqggK8LKoaiwgoAlxYKh5BIsNNQkQAiIIgFdkITNQQJIJCEhyUCSoaqfDFSRqqnsV5gvwvb4RyaVN/N2P/3rp/vNWO/Lgb7LS1VwZquzzsmy23D8lYpVjlIMH/Uwv6rDrCyqRm@jEqhQhQ0sIdKjGk1N@Dha0YyNVFzZpG2Ib@qmYcMx5m/rSzFHh22I1CUMRRSAD47hxg/kwxdVsCettR04gBNCw68T45wqWJVo0nq9qlM1zhQkTU2qcFzzkPZSsT6KY4k/VmzAfLu1fVwVbGkTdDSCdZxcgVSchYDsGMbRTVVYw@5AN/x3xpUgheCv0ZPvsWqcLaWjatiayKeEddiBRxUcFKMw7SQMg12dBZDuTzapRkMlnO2Fb85Cz2Hpp2AjVlkDvKrwHTGcsqzCOjrAkhK5sNxQ1jCjRPGxXbboKPQ0k/9Nx2cmYKMjhBFRQt1Xa3OmYMurzeN6iaOsDyFMx1Oq@RMFz20jfMo42y4sqrBVJEtPsFWNZdpTjrWkQXXBjlMO5GXGqTgXxgk6U7GEoRxS6aCyh00lyBc5wp@M5QtJHUPlDPSgFzE6pJBskSV8o6gswoN/uOQDBHHC6o/lOBarweFm7yNyS9nk6sawwVmqINbr4BprwTLWO8lL0TpNuA@zmJftLXfIIdthyMYKg2JG5O@DSJJ21YjPjNRozIfxxq9O2t7W3htlxqy5GdIj/oIp7xpWtH5z4qS1ny9KFYzAUaa/lTvF5dUjwnXrsTWIo2tcWH3jHzAzBIV7nDAVkNjbkPMS9vswT2ELCx0lk3k3scgBlMNubGRdGaBDrfvSSPm5LftxKn5uU8S@mlasNOboVcEPGz80inxhj8KK6x05i4vuaR22T9AP7Y1PV1Pi@C1Zyv6glfMbBVkpOZoQb0/FycPo5jEDicR8EhEoGyWnKpzQTh8/sZTRwgDPQgkD1/iNTgYV1zR8PWmqeQtu2TLJ3veOcZNOVPNiwsDJZDsdZJKYCrRUDSLKp/jK4fexjWgqxjLHGtrOWfHamSUV4AH8oZlinVFzP3aVVYQS8w9YpFt2kLME0VLssYpeHlssPaX4WVgzzwxWdBzRrwQ4H@0nrcO/8wvkJzaTlfxF8GWRC9tKuF8W03gwNnGaMGmOEjysaMHeSkE6ZtvswvcWIha46@SBATbdC9p9j0V9Ksa/DhlSJc/@OpcYuQPXaCGOmMFSKo6vdMSxcriyKCzNeoSblAhM@BcurZYgIvi34B3chd0fWIdFCcM6MoXvFHv2gq94sDre@Vx2PJhQQrSng6gN4VcGVc9Mm2XLGTtcIx@uYJuSdBZOzCeEzDLdKOytSWsvdiheTV4e0FWtaInXT3AYYSVCsYSQB8@vSp8Nlw6xV1@MQ@xvRoj3l0cDN4cTrNxTAlUXlkcNLMvFzi5pyu3CbCPc@MkLkntdI8eHrmXk5l9PT8vQjC44J@Q4BaYpiG8JYbKni7z4wRcfsdwJPjx9zcvKc6X9b9rWDZCrJGF6VUuh9LvYH057gs9MhA5LLyzKMfZ4b20Vd/C6ep85Wq55LJ6bDnel7MiGO4v1PqNQXvVDbrlxDu6kCT@x/DSDXNyunZ6rrx9oMnJZEnaVQ@Lef@cmpGOjhXbYseatap5LG6@gGzkJYZp5UlAJ0C7W2ovZMX6sU1CWklZE/zNifoBJLOSW87L5hKUGxhfSDMeMaJ/YpdYnLXQy0EXbU@RmAC/bmOndXk6dj@XLy/8B "05AB1E ‚Äì Try It Online") [Answer] ## Java 758 chars Here is my Java effort ( 758 chars ) ``` public class Poem{public static void main(String[] args){String s1="swallowed",st="There was an old lady who "+s1+" a |.",d1="Perhaps she'll die.",d2="She died ofcourse.",e="I don't know why she " + s1 + " that fly,\n";String[] a={ "fly","spider","bird","cat","dog","horse"};String[] q={ "","That wriggled and iggled and jiggled inside her.","How absurd |","Imagine that |","What a hog |",null};for(int i=0;i < a.length;i++){print(st.replace("|",a[i]));if(q[i]==null){print(d2);break;}if(!q[i].isEmpty()){ print((q[i].replace("|","to swallow a " + a[i])).trim());for(int j=i;j > 0;j--){print("She swallowed the " + a[j] + " to catch the " + a[j - 1] + ",");}}print(e + d1 + "\n");}} static void print(String value){System.out.println(value);}} ``` [Answer] # Java, 655 bytes ``` public class M{public static void main(String[]P){String S="swallowed",T="There was an old lady who "+S+" a |.",e="I don't know why she "+S+" that fly,\n";String[]a={"fly","spider","bird","cat","dog","horse"};String[]q={"","That wriggled and iggled and jiggled inside her.","How absurd |","Imagine that |","What a hog |",null};for(int i=0;i<a.length;i++){p(T.replace("|",a[i]));if(q[i]==null){p("She died of course.");break;}if(!q[i].isEmpty()){p((q[i].replace("|","to swallow a "+a[i])).trim());for(int j=i;j>0;j--){p("She swallowed the "+a[j]+" to catch the "+a[j-1]+",");}}p(e+"Perhaps she'll die.\n");}}static void p(String v){System.out.println(v);}} ``` This is a **golfed** version of [this answer](https://codegolf.stackexchange.com/a/3712/55550). There's over 100 bytes saved on minor things. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 369 366 bytes ``` Ôº°‚Äù‚Üì0*)Ôº¢‚éöD¬≥9;7Ôº±7‚à®-f¬∂_¬≤œá‚Å∂Ôºõ‚Üßl‚Å∫I¬¥‚Äù¬¶Œ±Ôº°‚ÄúV√óq‚ñ∂¬≤‚ñ∑O‚âï‚¶É0j‚Üñ‚ñ∑(œÑ‚éá‚¶Ñ4œâ\`j0Ôº¥‚ÅπœàÔº©2b1z√ºœÅ√Ä‚Üë‚Äπ‚Ū√™¬£Ôº°Ôº∫‚ÄπÔºüÔº§OR¬ß1œÜ‚Äù¬¶Œ≤Ôº°‚ü¶spider¬¶bird¬¶cat¬¶dog‚ü߬¶ŒªÔº°,¬∂¬¶ŒΩÔº°‚ü¶‚Äù‚Ü∂7‚éáÔº©Ôº∞Ôº∂pŒ∏Œ∏‚™™‚ûôÔº≥¬≤p‚∏øH‚Å∏‚úÇŒΩ‚Äñ2‚Üñ¬≤œÜ‚ÜònœÑME‚¶ÑÔº¢‚ÜìŒælÔº¶‚ŵy‚Äù¬¶‚Äù‚Ü∂7Nl@;‚™´Œª38ԺƂàﬥ‚âï‚Å∫)¬≥ n√Ăĥ‚¶É‚Äù¬¶‚Äù‚Ü∂7‚Üꬥ<7ÔºπKÔº¢YœánÔº∫-‚ÜñÔºµ‚éáŒπ\HUŒ∏%Ôºõ‚üß‚Äù¬¶‚Äù‚Ü∂7‚à߬߂ĥ‚üßO√óœÜ¬¢\`*NQ¬∂G‚Å∫$œÄ‚ÄΩŒæat‚Äù‚üߌºÔº°‚Äù‚Üì/!Ôº∫m‚™´‚üߌ±√ĂŪԺ∂Œµ>‚ü≤‚Äù¬¶œÉÔº°‚ÄùÔΩú‚ÄΩaÔº£-‚Å¥t;Z‚åï‚Äù¬¶œÑÔº°‚ÄúY‚ஂÜ∑ur1Ôº¢ÔºØ#√øk¬ª‚ŪœÖv‚ÄΩ‚åä‚Üêzœâ‚Üò^‚Äù¬¶Œ∑‚Å∫Œ±Œ≤Ôº¶‚Å¥¬´‚Å∫‚Å∫‚Å∫Œ±¬ßŒªŒπŒΩ¬ßŒºŒπÔº¶‚Æå‚Ķ‚Å∞Œπ¬´‚Å∫‚Å∫‚Å∫‚Å∫œÉ¬ßŒª‚Å∫Œ∫¬πœÑ¬ßŒªŒ∫ŒΩ¬ª‚Å∫‚Å∫‚Å∫œÉ¬ßŒª‚Å∞œÑŒ≤¬ª‚Å∫Œ±Œ∑ ``` [Try it online!](https://tio.run/##bVG9bsIwEN55ilMWHMkgKnXrxFY2RJE6lA5HbGIXYyPbkKKKZ0/PSQFTMSSx7r5fp1LoK4embach6NqyYqmkl9BgALTgjACD4gSNchAaNMY1UgBCwQHLl8GFtDGn8crOQDg7jLC1riHGCYKSGSsqjEBIvrJz6RXuQwIMjQGhJdFXllTXN9WPIuy1kL7gxVp7QZ8KI72Fq4tPDibz5x3X5txlcmu8rmuTElsB2fHr76xtIAegyuOkULxScFyHg6e018JUN/n3iNkOa21lX@YOQ@F6yHtaIShX3wModwJQ9F0W/e3fHcl0tyEDJBHSrtRlGbOlcj5Iap9U6BYFuA1U7kDDMSEVIQdzr21kUyEY8nVJk43z7LmEnwHAbXd5kE/jzAr5zQzXZclteR3s0oD4AKQAbCGPknzYAm0t2aRbdqKPZNMTONy002DLn4jDY5l5bmlAP7KzOT9MGDL0pKd3tc53TRWN2rYdHdtRML8 "Charcoal ‚Äì Try It Online") Link to the verbose version of the code. ]
[Question] [ Very heavily inspired by this challenge [Code Golf: Your own pet ASCII snake](https://codegolf.stackexchange.com/questions/156245/code-golf-your-own-pet-ascii-snake) - I thought making it horizontal would add an extra layer of complexity. An example horizontal snake: ``` 0 0 0 0 0 000 00 0 00 000 0 0 000 0 0 0 00 0 000 ``` And the rules are: 1. Exactly 5 lines of characters are printed 2. Each line is exactly 30 characters long, consisting of a combination of spaces and the character you choose to draw your snake with 3. Your snake starts on line 3 4. The next line to be used for drawing your snake must be randomly chosen from your current line, one line above (if you're not already on line 1) or one line below (if you're not already on line 5). * These choices must be equally weighted. So if you are on line 1, you have a 50% chance to stay on line 1 and a 50% chance to move to line 2. If you are on line 2, you have a 33% chance to move to line 1, a 33% chance to stay on line 2 or a 33% chance to move to line 3 5. Your snake **does not** need to visit every single line. [Answer] # JavaScript (ES6), 98 bytes *Saved 7 bytes thanks to @KevinCruijssen* Returns an array of 5 strings. ``` f=(y=2,a=[...' 0 '])=>a[0][29]?a:f(y+=(Math.random()*(y%4?3:2)|0)-!!y,a.map((v,i)=>v+=i-y&&' ')) ``` [Try it online!](https://tio.run/##FctLDoIwEADQq5SFdEbaCUE3klRO4AmQxYSPlkBLgDRp4t1R1y9v5MBbu9pl1853/XEMBqIpFJuaiKQQuRCyQXPnOm/q4tZUXA4QMwMP3t@0suv8DHiGeLpWl7LAT446SaJimnkBCMr@csiM1TFNpZCIR@vd5qeeJv@CAZBGbx3Ip/vbFw "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // given: y = 2, // y = current line (0-indexed) a = [...' 0 '] // a[] = array of 5 lines ) => // a[0][29] ? // if all columns have been processed: a // stop recursion and return a[] : // else: f( // do a recursive call with: y += ( // the updated value of y, to which we add -1, 0 or 1: Math.random() * // pick a random value in [0,1) (y % 4 ? // if y is neither 0 or 4: 3 // multiply it by 3 : // else: 2 // multiply it by 2 ) | 0 // force an integer value ) - !!y, // subtract either 0 or 1 a.map((v, i) => // for each value v at position i in a[]: v += i - y && ' ' // append either '0' if i = y or a space otherwise ) // end of map() ) // end of recursive call ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` P| F³⁰«0≡ⅉ²M‽²↑±²M‽²↓M⊖‽³↓ ``` [Try it online!](https://tio.run/##bc6xCoMwFIXh2TzFxSkBC6KbXV0tpdBCx0u81kBMJKY6FJ89NdJ26vqfbziyRyct6hCap/ZqdMp4Xt3IeSVRZ5ACQCqOrLMOeJkLeLHkvKM0jz2ZFuVlD/zOxT5KnAiKCho7E7@gae3AC5FBdR0j3@cTPdDTlv@w2i4mwpY63B59RE3S0UDGU/vVpfhxlqxsDSEcZv0G "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` P| ``` Print some padding to force 5 lines of output. ``` F³⁰« ``` Repeat 30 times. ``` 0 ``` Print a zero (and move horizontally). ``` ≡ⅉ²M‽²↑ ``` If the Y-coordinate is 2, move up randomly by 0 or 1. ``` ±²M‽²↓ ``` If it's -2, move down randomly by 0 or 1. ``` M⊖‽³↓ ``` Otherwise move down randomly by -1, 0 or 1. [Answer] # Perl, 68 bytes ``` perl -E '$%=2;s:$:$n++%5-$%&&$":emg,$%-=!!$%+rand!($%%4)-3for($_=$/x4)x30;say' ``` This doesn't feel optimal at all. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` 3µ’o1r‘«5¥$Xµ30СṬ€o⁶z⁶Y ``` [Try it online!](https://tio.run/##ATMAzP9qZWxsef//M8K14oCZbzFy4oCYwqs1wqUkWMK1MzDDkMKh4bms4oKsb@KBtnrigbZZ//8 "Jelly – Try It Online") ## Explanation ``` 3µ’o1r‘«5¥$Xµ30СṬ€o⁶z⁶Y || Niladic full program. || 3 || Starting from 3... µ µ30 || ... Execute 30 times... С || ... And collect the results in a list. ’o1r‘«5¥$X ||--| Monadic "Helper" function. ’o1 ||--| The current integer, decremented OR 1. r X ||--| Grab a random item from the range from ^ to... ‘«5 ||--| ... The number incremented, capped to 5 (uses maximum). ¥$ ||--| Syntax elements. Used for grouping links. Ṭ€ || Untruth each. o⁶ || Logical OR with a single space. z⁶ || Transpose with filler spaces. Y || Join by newlines. ``` [Answer] # [R](https://www.r-project.org/), 138 bytes ``` m=matrix(" ",30,5) m[1,3]=0 x=3 s=sample for(i in 2:30)m[i,x<-x+(-1)^(x==5)*s(0:1,1)*x%in%c(1,5)+(s(3,1)-2)*x%in%2:4]=0 write(m,"",30,,"") ``` [Try it online!](https://tio.run/##LY3LCsIwEADv@YoQKGzaDeRhL8H9kqJQpELAVEkK7t/HKJ4G5jBTWsuU16MkBiUVBouzFnlxGC5kBVMQleqaX49N3J8Fkky79DFYnZeEfDY8gXH6Ckw067GCjQ6dHnlI@3AD12sTVAjdGf/XPp6@7XdJxwYZ1e/aoVv7AA "R – Try It Online") Handily outgolfed by [plannapus](https://codegolf.stackexchange.com/a/156459/67312) [Answer] # Python 3, 144 bytes *@Ruts, @Turksarama, and @mypetlion have been very helpful in reducing bytes* ``` import random m=[list(' '*30)for y in range(5)] l=2 for i in range(1,30): m[l][i]=0 l+=random.randint(~-(l<1),l<4) for j in m: print(*j) ``` Will try and improve on this. Fun challenge! [Answer] # [R](https://www.r-project.org/), ~~120~~ 114 bytes ``` m=matrix r=m(" ",30,5) x=3 for(i in 1:30){r[i,x]=0;x=x+sample(-1:1,1,,m(c(0,rep(1,13)),3)[,x])} write(r,"",30,,"") ``` Thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312) for the additional 6 bytes! Uses a table of probabilities as follows: ``` > matrix(c(0,rep(1,13)),3) [,1] [,2] [,3] [,4] [,5] [1,] 0 1 1 1 1 [2,] 1 1 1 1 1 [3,] 1 1 1 1 0 Warning message: In m(c(0, rep(1, 13)), 3) : data length [14] is not a sub-multiple or multiple of the number of rows [3] ``` where each columns corresponds to a case, i. e. column 1 is picked if the snake is in row 1, giving probabilities 0, 1/2 and 1/2 to pick respectively -1 [go down], 0 [stay still] and 1 [go up] (`sample` automatically normalize the probabilities to 1), column 2 for row 2 gives probabilities 1/3, 1/3 and 1/3, etc... [Try it online!](https://tio.run/##HYxBCgIxDADvfUXpKcEILcHLSl@yeFiWCgGjS1wwIL69lj0NA8NY71p12U08WFVIMRFnumDwyuH@MpAoz1gmzvi1WchvNV@9@um96PZocC5ToUKksEImaxsMZURinEeMv/Ax2RsYpeM8gL3/AQ "R – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), ~~22~~ 21 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` 3ā'∑∫⁵╗ž⁴H1ΧGI5χ⁴-ψ+; ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=MyV1MDEwMSUyNyV1MjIxMSV1MjIyQiV1MjA3NSV1MjU1NyV1MDE3RSV1MjA3NEgxJXUwM0E3R0k1JXUwM0M3JXUyMDc0LSV1MDNDOCslM0I_,inputs=eSUyMGElMjB4,v=0.12) Explanation: ``` 3 push 3 ā push an empty array - the canvas '∑∫ 30 times do, pushing counter | stack = 3, [], 1 ⁵ duplicate the Y coordinate | stack = 3, [], 1, 3 ╗ž at those coordinates insert "+" | stack = 3, ["","","+"] ⁴ duplicate from below | stack = 3, ["","","+"], 3 H decrease | stack = 3, [...], 2 1Χ maximum of that and 1 | stack = 3, [...], 2 G get the item 3rd from top | stack = [...], 2, 3 I increase it | stack = [...], 2, 4 5χ minimum of that and 5 | stack = [...], 2, 4 ⁴- subtract from the larger a copy of the smaller value | stack = [...], 2, 2 ψ random number from 0 to pop inclusive | stack = [...], 2, 2 + add those | stack = [...], 4 ; and get the array back ontop | stack = 4, ["","","+"] implicitly output the top item - the array, joined on newlines ``` [Answer] # Japt, ~~31~~ 29 bytes Returns an array of lines. ``` 30ÆQùU±[2V=Jõ VVJò]mö i3 gUÃy ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=MzDGUflVsVsyVj1K9SBWVkryXW32IGkzIGdVw3k=&input=LVI=) [Answer] # [Japt](https://github.com/ETHproductions/japt), 26 bytes ``` 30ÆQùU=U?5õ f_aU <2Ãö :3Ãy ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=MzDGUflVPVU/NfUgZl9hVSA8MsP2IDozw3k=&input=LVI=) [Answer] # [Python 2](https://docs.python.org/2/), 127 bytes ``` from random import* s=['']*5 n=3 r=range(5) exec"for i in r:s[i]+=' 0'[i==n]\nn=choice(r[n and~-n:n+2])\n"*30 print'\n'.join(s) ``` [Try it online!](https://tio.run/##Dcy9CoMwFIbhPVcRXOIPLaK4COdKkgwljfUU/BKOGdqlt546vcMDb/6WPWGqdZN0aHngeYWPnKT06iRrjO8XBZqV0KWv2C6dip8Ymi2JZs3Qsp6W/UBGj8YyEbwDKOyJQ2zFQl/T3w0rhsl3Dk0/jyoLoxgHc38nRnt2tf4B "Python 2 – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/) with Statistics Package, 99 bytes It also works in MATLAB with the Statistics Toolbox. ``` p=3;for k=1:29 p=[p;p(k)+fix(randsample(setdiff([1 pi 5],p(k)),1)-3)/2];end disp(['' (p==1:5)'+32]) ``` [**Try it online!**](https://tio.run/##FcxBCoQgFADQfadw5//kECotZsSTiAtJBWkmPxlDt7faP15djvBPvZPVJtedrVZ@1Hsg68gQrDjmcsIettjCj74JWjpiyRmcZFTY7MWDUEh8aZyUN2mLQyyNwHHOgOzdzchHrTz2fgE "Octave – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 28 bytes *Saved 9 bytes thanks to ETHproductions* ``` 3k 29Æp5õ f_aUgY)<2Ãö ¡QùXÃy ``` [Try it online!](https://tio.run/##AS0A0v9qYXB0//8zawoyOcOGcDXDtSBmX2FVZ1kpPDLDg8O2CsKhUcO5WMODef//LVI "Japt – Try It Online") [Answer] # SmileBASIC, ~~107~~ ~~105~~ ~~103~~ 89 bytes ``` FOR I=0TO 29FOR J=0TO 5LOCATE I,J?" 0"[Y+2==J]NEXT Y=Y+RND(3)-1D=Y/3>>0Y=Y-D-D*RND(2)NEXT NEXT ``` This answer is more interesting than the vertical one because of the (literal) edge cases. ## 64 bytes, without printing spaces: ``` FOR I=0TO 29LOCATE,Y+2?0; Y=Y+RND(3)-1D=Y/3>>0Y=Y-D-D*RND(2)NEXT ``` I also found a few variations of line 2 with the same length: ``` Y=Y+RND(3)-1D=Y/3>>0Y=Y-D-D*RND(2)NEXT Y=Y+RND(3)-1D%=Y/3Y=Y-D%-D%*RND(2)NEXT Y=Y+RND(3)-1Y=Y-Y DIV 3*(RND(2)+1)NEXT Y=Y+RND(3)-1Y=Y/3OR.Y=Y-D-D*RND(2)NEXT ``` The integer division of Y/3 is used to check if Y is outside the valid range, as well as getting the sign. [Answer] # Java 8, ~~177~~ 170 bytes ``` v->{int a[][]=new int[5][30],c=0,r=2;for(;c<30;r+=Math.random()*(r%4>0?3:2)-(r>0?1:0))a[r][c++]=1;String R="";for(int[]y:a){for(int x:y)R+=x<1?" ":"~";R+="\n";}return R;} ``` -7 bytes thanks to *@OlivierGrégoire*. **Explanation:** [Try it online.](https://tio.run/##LVDBboMwDL3vK6xIk5JREJTtQpr2C9oDk3bJcsgC3eggoBBYEWK/zsJAsiU/W35@fjfZS79ucn3LvmdVyraFsyz0@ABQaJubq1Q5XBYI8GpNoT9B4be6yKAn1HUnly5aK22h4AIaGMy9fxzdNkguuGA6/1m4@IvgcSh2ioU7w/b0WhtM1SEOqfHYWdqvwEid1RUmT9g8Ph/DU5zsiY@Nq6IkJERyI7jyPMEiuklJGUL/RAu/GBJJxg3BPRlI6rH7ITohQAn6RdRB9K4RnUxuO6MhpdNMV/1N91E6/dsb/fJf5WzA6x0uHPFqwdDavArqzgaNm9hSYx0orLuyJJsf0/wH) ``` v->{ // Method with empty unused parameter and String return-type int a[][]=new int[5][30], // Integer-matrix of size 5x30 c=0, // Column, starting at index 0 r=2; // Row, starting at index 2 for(;c<30; // Loop `c` 30 times r+=Math.random()*(r%4>0?3:2)-(r>0?1:0)) // After every iteration: change `r` with -1,0,1 randomly // If `r` is 0: random [0;2)-0 → 0,1 // If `r` is 4: random [0;2)-1 → -1,0 // If `r` is 1,2,3: random [0:3)-1 → -1,0,1 a[r][c++]=1; // Fill the cell at indices `r,c` from 0 to 1 String R=""; // Result-String, starting empty for(int[]y:a){ // Loop over the rows of the matrix for(int x:y) // Inner loop over the individual column-cells of the matrix R+=x<1? // If the value of the cell is still 0: " " // Append a space : // Else (it's 1): "~"; // Append the character R+="\n";} // After every row, Append a new-line return R;} // Return the result-String ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 134 130 bytes ``` r,x,y=3,a[31],m;f(){for(x=0;x<31;x++){m?putchar(x==30?10:a[x]-m?32:48):(a[x]=y);r=rand();y+=y==1?r%2:y==5?-r%2:1-r%3;}++m<6&&f();} ``` [Try it online!](https://tio.run/##HY3BDsIgGIPve4pdXEBYAkONgf3hQZYdCLq5A9PgNJBlz47DS/O1SVtbj9am5GmgEQQ1neA9dWpAeB2eHgVgKrSCq0AIXp1@fRb7MDkHwTRn0nShr50WjTxdsUTZQsTKgzfzDWEVCUQArv2hkTucdZ2J7yrURohrL1W1n6ktTfNSOjPNKIPxo6Vlvjpm/nY9Ltfi/R9dJndHDGNV5GKxFekH "C (gcc) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 123 bytes ``` from random import* i,*a=2, exec("a+=i,;i+=randint(-(i>0),i<4);"*30) for x in range(5):print(''.join(' 0'[x==i]for i in a)) ``` [Try it online!](https://tio.run/##FcyxDsIgGEXhnacgXeCnaIjVxUpfxDgQpXpNCoQw0KdHmc7y5aS9fGKYWltz3Hh24fUPthRzUQxaOXvSzFf/lIMbLfSM0XaFUORBYjGkcTvTPKjJEFtj5pUj9NHbywtdU@5SiOM3IkjBjbhXa/HoEl06otZ@ "Python 3 – Try It Online") Generate an array of integers, then convert it to each row. # [Python 2](https://docs.python.org/2/), 120 bytes ``` from random import* i=2;a=[] exec"a+=i,;i+=randint(-(i>0),i<4);"*30 for x in range(5):print''.join(' 0'[x==i]for i in a) ``` [Try it online!](https://tio.run/##FcyxDsIgGEXhnacgXYC2GlJ1EX9fpOlAlOptUiCEAZ8ey3SWLyf@8jf4qdY1hZ0n699HsMeQcs9Ak7E0L8wV9@rsQBgNBmoKPsuTxFOrEY@rMl1/0WwNiRcO3z4fJ2/qHtMBhThvAV4KrsVciLA0iAatqvUP "Python 2 – Try It Online") For Py2, redundant parens for `exec` and `print` can be removed, but the syntax in the 2nd line is invalid. Outgolfing both [Py2 submission by Rod](https://codegolf.stackexchange.com/a/156396/78410) and [Py3 submission by linemade](https://codegolf.stackexchange.com/a/156376/78410). [Answer] # [Ruby](https://www.ruby-lang.org/), ~~98~~ 77 bytes ``` ->{a=(0..4).map{" "*30} x=2 30.times{|i|a[x][i]=?@ x+=rand(3-17[x])-30[x]} a} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf16460VbDQE/PRFMvN7GgWklBScvYoJarwtaIy9hAryQzN7W4uiazJjG6IjY6M9bW3oGrQtu2KDEvRcNY19AcKKqpa2wApGq5Emv/F5SWFCuk6SUn5uT8BwA "Ruby – Try It Online") A lambda returning an array of strings. My initial impulse was to generate the columns and transpose them, but it's much easier to just avoid that step. I would have liked to initialize `a` with `[" "*30]*5`, but that would make shallow copies of the strings, resulting in a very fat, non-slithery snake. ~~I could have used a constant like `D` as the increment (for the same byte count), but Ruby would have complained every time I assigned it. I decided I prefer decreasing readability by reusing `i` mid-loop to having a bunch of Debug warnings to ignore.~~ ~~I also would have liked to save a few bytes with `loop{x+=rand(3)-1;(0..4)===x&&break}`, but that would have caused a bias on the edges: 1/3 chance to turn back inward, 1/3 chance to stay, and 1/3 chance to go out of bounds for a while before eventually random-walking back in (that is, "stay").~~ *-20 bytes:* Use Ruby's `Integer#[]` to create tiny conditionals, ensuring correct movement weightings for all 5 positions. This replaces a loop-break pattern (with a nonzero chance of failing to halt) for a huge savings. *Thanks, [Eric Duminil](https://codegolf.stackexchange.com/users/65905/eric-duminil)!* -1 byte: Initialize `a` with `(0..4).map` instead of `5.times`, thanks again to [Eric Duminil](https://codegolf.stackexchange.com/users/65905/eric-duminil). ``` ->{ a = (0..4).map{ " " * 30 } # a is the return array: 5 strings of 30 spaces x = 2 # x is the snake position 30.times{ |i| # For i from 0 to 29 a[x][i] = ?@ # The ith position of the xth row is modified x += rand(3 - 17[x]) - 30[x] # Using bit logic, add rand(2 or 3) - (0 or 1) } a # Return the array of strings } ``` [Answer] # [Perl 6](http://perl6.org/), 85 bytes ``` .join.say for [Z] ((' ',' ',0,' ',' '),{.rotate(set(0,+?.[0],-?.[4]).pick)}...*)[^30] ``` [Try it online!](https://tio.run/##K0gtyjH7/18vKz8zT684sVIhLb9IIToqVkFDQ11BXQeEDXSgLE2dar2i/JLEklSN4tQSDQMdbXu9aINYHV0gZRKrqVeQmZytWaunp6elGR1nbBD7/z8A "Perl 6 – Try It Online") The long parenthesized expression is a lazy sequence generated from the initial element `(' ', ' ', 0, ' ', ' ')`, the first vertical strip of the output. Each successive strip/list is generated from the preceding one by calling its `rotate` method, with the offset randomly chosen from a set containing `0`, `1` (if the first element is nonzero), and `-1` (if the fifth element is nonzero). The matrix of horizontal strips is transposed with the `[Z]` operator, turning it into a list of vertical strips, each of which is then `join`ed into a single string and output with `say`. [Answer] # Scala, 207 Bytes ``` val b=Array.fill(150)('.') def s(y:Int,x:Int)={val r=Random.nextInt(6) val z=y+(if(y>3)-r%2 else if(y<1)r%2 else r/2-1) b(z*30+x)='$' z} (3/:(0 to 28))(s(_,_)) b.mkString("").sliding(30,30).foreach(println) ``` sample: ``` ...................$$$...$.$$. .$$$..............$...$.$.$... $...$$$..$...$$.$$.....$...... .......$$.$.$..$.............. ...........$.................. ``` degolfed: ``` val buf = List.fill(150)('.').toBuffer def setRowCol (y:Int, x:Int): Int = { val r = Random.nextInt(6) val z = y + ( if (y>3) -(r%2) else if (y<1) (r%2) else r/2-1 ) buf (z * 30 + x) = '$' z } (3 /: (0 to 28)(setRowCol (_, _)) println buf.mkString ("").sliding(30,30).foreach(println) ``` My unique invention - well, I haven't read the other solutions so far, is, to generate a Random (6) which is implicitly two Randoms, (2\*3). If away from the border, I use the values of r/2 (0,1,2) and → (-1,0,1) tell me, to go up or down. If at the border, I can avoid the character costly call of another random, and just take the modulo(2), to decide, should I stay or should I go. Let's see the other solutions. :) [Answer] # Perl, ~~83~~ 101 bytes ``` perl -E '$l=3;map{map$s[$_-1].=/$l/?0:" ",1..5;$l-=1-int 3*rand;$l=~y/60/51/}1..30;say for@s' ``` New: Without probability issue at the borders: ``` perl -E '$l=3;map{map$s[$_-1].=/$l/?0:" ",1..5;$l=int($l<2?1+2*rand:$l>4?6-2*rand:$l-1+3*rand)}1..30;say for@s' ``` Ungolfed: ``` $l=3; #start line map{ map $s[$_-1].=/$l/?0:" ",1..5; #0 at current char and line, space elsewhere $l-=1-int 3*rand; #up, down or stay $l=int( $l<2 ? 1+2*rand : $l>4 ? 6-2*rand : $l-1+3*rand ) #border patrol } 1..30; #position say for@s #output result strings/lines in @s ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 133 bytes ``` $a=(,' '*30),(,' '*30),(,' '*30),(,' '*30),(,' '*30);$l=2;0..29|%{$a[$l][$_]=0;$l+=0,(1,($x=1,-1),$x,$x,-1)[$l]|Random};$a|%{-join$_} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyXRVkNHXUFdy9hAU4dIlrVKjq2RtYGenpFljWq1SmK0Sk5stEp8rK0BUEbb1kBHw1BHQ6XC1lBH11BTR6UChIAskLKaoMS8lPzcWmuVRKBW3az8zDyV@Nr//wE "PowerShell – Try It Online") Constructs a 2D array of 30 spaces wide by 5 lines tall. *(NB - if someone can come up with a better effective way to initialize this array, I'll <3 you forever.)* Sets helper variable `$l` to `2` (this is used for what line the previous snake segment was on). Then loops from `0` to `29`. Each iteration, we set our snake element to `0`. Then we index into a complicated array with `Get-Random` that selects out whether we go up or down or stay the same. That's added back into `$l`. Finally, we loop through the five elements of `$a` and `-join` their inner elements into a single string each. Those five strings are left on the pipeline, and the implicit `Write-Output` gives us newlines for free. [Answer] # Clojure, 123 bytes Here come the parens: ``` (let[l(take 30(iterate #(max(min(+(-(rand-int 3)1)%)4)0)3))](doseq[y(range 5)](doseq[x l](print(if(= y x)0" ")))(println))) ``` Ungolfed version: ``` (let [l (take 30 (iterate #(max (min (+ (- (rand-int 3) 1) %) 4) 0) 3))] (doseq [y (range 5)] (doseq [x l] (print (if (= y x) 0 " "))) (println))) ``` Builds a list of the different heights of the snake body, then iterates from 0 to 4. Whenever a height matches the current row it prints a 0, otherwise a blank. Not letting the heights exceed the boundary really costs bytes. Also recognizing when a new line is in order is more byte-intensive as it should be. One could easily write a single `doseq`, making a cartesian product of the x's and y's but then one does not know when to print a new line. [Answer] # Python3 +numpy, ~~137~~ 132 bytes Not the shortest python submission, not the longest, and definitely not the fastest. ``` from pylab import* j=r_[2,:29] while any(abs(diff(j))>1):j[1:]=randint(0,5,29) for i in r_[:5]:print(''.join(' #'[c] for c in j==i)) ``` **update** Using `numpy`'s diff command saved 5 bytes for testing if the snake is a valid pattern, compared to calculating the difference manually with `j[1:]-j[:-1]`. [Answer] # C (gcc), 80 76 72 71 bytes ``` a[5][30],i,r;f(){for(r=2;i<30;r+=rand()%3-1)a[r=r>4?4:r<0?0:r][i++]=1;} ``` [Try it online!](https://tio.run/##TU7LCoMwELz7FUGQJEQhVr0YUz8kzSHYWlbQlq038dvTaKU4p2UeO9Nlz67z3pnKmkLaFFJUPeNL/0KG@qKgKaRCodFNd8aTIsu5M6jxWrZljY1sZY3WgBBW52r1MM1kdDAxHi0RCfjswRnGB5Ocq50L/48jlGwJ0FIRaCpFhAC@S7/02TQE07CtEWLgf3XDG4Peszjp4tQZsGawLZW0poQeRWfXbYoPdo1W/wU) [Answer] # [R](https://www.r-project.org/), 95 bytes ``` x=3;l=1:5 write(t(replicate(30,{y=ifelse(x-l,' ',0);x<<-sample(l[abs(x-l)<2],1);y})),'',30,,'') ``` Next line `x` is always chosen from lines that are no more than 1 away from current line (`l[abs(x-l)<2]`). Using `replicate` instead of a `for` cycle saves some bytes needed for matrix initialization and manipulation and requires the use of the `<<-` operator when assigning to the global variable `x`. [Try it online!](https://tio.run/##K/r/v8LW2DrH1tDKlKu8KLMkVaNEoyi1ICczORHINjbQqa60zUxLzSlO1ajQzdFRV1DXMdC0rrCx0S1OzC3ISdXIiU5MKgbJadoYxeoYalpX1mpq6qir6wD1AinN////AwA "R – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes ``` Y30F©ð5×0®ǝs<DÌŸ4ÝÃΩ}\)ζ» ``` [Try it online!](https://tio.run/##AS8A0P8wNWFiMWX//1kzMEbCqcOwNcOXMMKux51zPETDjMW4NMOdw4POqX1cKc62wrv//w "05AB1E – Try It Online") **Explanation** ``` Y # push the initial value 2 30F # 30 times do © # store a copy of the current value in register ð5× # push 5 spaces: " " 0®ǝ # insert 0 at the position of the current value s<DÌŸ # push the range [current-1 ... current-1+2] 4Ýà # keep only numbers in [0 ... 4] Ω # pick one at random }\ # end loop and discard the final value )ζ # transpose the list » # join by newlines ``` ]
[Question] [ The [Vigenère cipher](http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher) was a simple polyalphabetic cipher that basically applied one of several Caesar ciphers, according to a key. Basically the letters in the key indicate which shifted alphabet to use. To that end there was a simple tool, called the *Vigenère square:* [![enter image description here](https://upload.wikimedia.org/wikipedia/commons/thumb/2/25/Vigen%C3%A8re_square.svg/600px-Vigen%C3%A8re_square.svg.png)](http://en.wikipedia.org/wiki/File:Vigen%C3%A8re_square.svg) Here each row is a separate alphabet, starting with the corresponding letter of the key. The columns then are used to determine the ciphered letter. Decryption works in very much the same fashion, only vice-versa. Suppose we want to encrypt the string `CODEGOLF`. We also need a key. In this case the key shall be `FOOBAR`. When the key is shorter than the plaintext we extend it by repetition, therefore the actual key we use is `FOOBARFO`. We now look up the first letter of the key, which is `F` to find the alphabet. It starts, perhaps unsurprisingly, with `F`. Now we find the column with the first letter of the plaintext and the resulting letter is `H`. For the second letter we have `O` as the key letter and the plain text letter, resulting in `C`. Continuing that way we finally get `HCRFGFQT`. **Task** Your task now is to decipher messages, given a key. However, since we have outgrown the 16th century and have computers we should at least support a slightly larger alphabet: ``` abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ``` The construction of the Vigenère square is still very much the same and the cipher still works in the same way. It's just a bit ... unwieldy to give here in full. **Input** Input is given on standard input as two separate lines of text, each terminated by a line break. The first line contains the key while the second contains the ciphertext. **Output** A single line, containing the deciphered message. **Winning condition** Since encryption is sometimes regarded as a weapon, the code should be short to facilitate easy smuggling. The shorter the better, as it reduces the likelihood of discovery. **Sample input 1** ``` Key miQ2eEO ``` **Sample output 1** ``` Message ``` **Sample input 2** ``` ThisIsAKey CoqKuGRUw29BiDTQmOpJFpBzlMMLiPb8alGruFbu ``` **Sample output 2** ``` ThisWorksEquallyWellWithNumbers123894576 ``` A week has passed. The currently shortest solution has been accepted. For those interested, in our contest we had the following submissions and lengths: > > 130 – Python > > 146 – Haskell > > 195 – C > > 197 – C > > 267 – VB.NET > > > And our own solutions that weren't ranked with the others: > > 108 – Ruby > > 139 – PowerShell > > > [Answer] ## Golfscript -- 48 chars ``` n%~.,@*\{\(123,97>91,65>+58,48>+:|?@|?\-|=}%\0<+ ``` No tricks in this one! [Answer] ## MS-DOS 16bit .COM file - 87 bytes Base64 encoded binary ([following this link for a decoder](http://www.motobit.com/util/base64-decoder-encoder.asp)) ``` v1cBi8/oQACJ/ovv6DkAi9msitAqF3MDgMI+gMJhgPp6dguA6jqA+lp2A4DqK80hO/d0IkM563TW69YsYXMIBCB9AgQrBBqqtAHNITwNdev+xLIKzSHD ``` [Answer] ## APL (45) ``` ∆[⍙⍳⍨¨⌽∘∆¨(⍴⍙←⍞)⍴1-⍨⍞⍳⍨∆←⎕D,⍨⎕A,⍨⎕UCS 96+⍳26] ``` Explanation: * `∆←⎕D,⍨⎕A,⍨⎕UCS 96+⍳26`: generate the alphabet (numbers (`⎕D`) follow letters (`⎕A`) follow lowercase letters (`⎕UCS 96+⍳26`, the unicode values from 97 to 122). * `1-⍨⍞⍳⍨∆`: read a line (the key), find the position of each character in the alphabet, and subtract one (arrays are one-based by default, so shifting by those values directly would shift the alphabet one too far). * `(⍴⍙←⍞)⍴`: read another line (the message), and repeat the indices of the key so that it has the length of the message. * `⌽∘∆¨`: rotate the alphabet by the indices belonging to the key * `⍙⍳⍨¨`: look up each character in the message in the corresponding shifted alphabet * `∆[`...`]`: look up the given indices in the normal alphabet, giving the corresponding characters. [Answer] ## Ruby - 132 127 122 109 100 characters ``` a,b=*$< c=*?a..?z,*?A..?Z,*?0..?9 (b.size-1).times{|i|$><<c[c.index(b[i])-c.index(a[i%(a.size-1)])]} ``` [Answer] ## Python - 122 chars ``` from string import* L=letters+digits R=raw_input K,T=R(),R() F=L.find print"".join(L[F(i)-F(j)]for i,j in zip(T,K*len(T))) ``` [Answer] ## J, 65 characters ``` v=:4 : 'a{~x(62|[:-/"1 a i.[,.#@[$])y[a=.a.{~62{.;97 65 48+/i.26' ``` Doesn't completely meet the spec since it's defined as a verb rather than taking input, but I'm posting it anyway with the intention of fiddling with it at a later date. Usage: ``` 'miQ2eEO' v 'Key' Message 'CoqKuGRUw29BiDTQmOpJFpBzlMMLiPb8alGruFbu' v 'ThisIsAKey' ThisWorksEquallyWellWithNumbers123894576 ``` [Answer] ## Perl, 95 chars Perl 5.010, run with `perl -E`: ``` %a=map{$_,$n++}@a=(a..z,A..Z,0..9);@k=<>=~/./g; $_=<>;s/./$a[($a{$&}-$a{$k[$i++%@k]})%62]/ge;say ``` [Answer] ## Python - ~~144~~ ~~143~~ ~~140~~ ~~136~~ 125 characters Probably not the best, but hey: ``` from string import* l=letters+digits r=l.find q=raw_input k=q() print"".join(l[(r(j)-r(k[i%len(k)]))%62]for i,j in enumerate(q())) ``` [Answer] ## Golfscript - 65 chars Still needs to be golfed more. For now, T is the text, K is the Key, L is the list of letters ``` n%):T,\~*:K;''26,{97+}%+.{32^}%10,{48+}%++:L;T{L\?K(L\?\:K;-L\=}% ``` [Answer] ## K,81 61 ``` k:0:0;,/$(m!+(`$'m)!+{(1_x),1#x}\m:,/.Q`a`A`n)[(#v)#k]?'v:0:0 ``` . ``` k)k:0:0;,/$(m!+(`$'m)!+{(1_x),1#x}\m:,/.Q`a`A`n)[(#v)#k]?'v:0:0 ThisIsAKey CoqKuGRUw29BiDTQmOpJFpBzlMMLiPb8alGruFbu "ThisWorksEquallyWellWithNumbers123894576" ``` [Answer] ## Perl, 115 chars ``` $a=join'',@A=(a..z,A..Z,0..9);$_=<>;chop;@K=split//;$_=<>;s/./$A[(index($a,$&)-index($a,$K[$-[0]%@K]))%@A]/ge;print ``` [Answer] ## Golfscript - 92 characters ``` n%~\.,:l;{0\{1$+\)\}%\;}:&;26'a'*&26'A'*&+10'0'*&+\@.,,{.l%3$=4$?\2$=4$?\- 62%3$\>1<}%\;\;\; ``` Probably much longer than it needs to be. Still trying to get my head around GS. Heres the "ungolfed" and commented version ``` n%~\.,:l; {0\{1$+\)\}%\;}:&; # This would be sortof an equivalent for range applied to strings 26'a'*&26'A'*&+10'0'*&+\@., # This mess generates the dictionary string, # l = len(key) # 0 dictionary (letters + digits) # 1 key # 2 text { # 3 index . #+1 Duplicate the index # Find the index of the key letter l% #+1 Indice modulo key 3$ #+2 Duplicate the key = #+1 Get the key letter 4$? #+1 Search the letters index # Find the index of the text letter \ #+1 Get the index 2$ #+2 Get the text = #+1 Get the text letter 4$? #+0 Search the letters index # 3 key index # 4 letter index \- #+1 get the index of the new letter 62% #+1 wrap the index around the dictionary 3$ #+2 Get the dictionary \> #+1 remove the first part of the dict around the target letter 1< #+1 remove everythin after }% \; \; \; ``` [Answer] ## VBA, 288 Doesn't quite beat the listed VB.NET score (but I'm getting close): ``` Sub h(k,s) v=Chr(0) Z=Split(StrConv("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",64),v) a=Split(StrConv(s,64),v):b=Split(StrConv(k,64),v) For l=0 To Len(s)-1 j=l Mod Len(k) g=0 For i=0 To 62:g=g+i*((Z(i)=b(j))-(Z(i)=a(l))):Next x=x &Z(IIf(g<0,g+62,g)) Next s=x End Sub ``` **Usage:** ``` Sub test() k = "ThisIsAKey" s = "CoqKuGRUw29BiDTQmOpJFpBzlMMLiPb8alGruFbu" h k, s MsgBox s End Sub ``` Thanks to [Joey](https://codegolf.stackexchange.com/users/15/joey) for the tip! [Answer] **C,186** A bit late but .. (lines broken to avoid horizontal scrollbar). ``` char a[99],*s,*t;k,j;main(int m,char**v) {for(;j<26;++j)a[j]=32|(a[j+26]=65+j), a[52+j]=48+j;while(*v[2]) putchar(a[s=strchr(a,v[1][k++%strlen(v[1])]) ,t=strchr(a,*v[2]++),s>t?t-s+62:t-s]);} ``` Nonbroken lines ``` char a[99],*s,*t;k,j;main(int m,char**v){for(;j<26;++j)a[j]=32|(a[j+26]=65+j),a[52+j]=48+j;while(*v[2])putchar(a[s=strchr(a,v[1][k++%strlen(v[1])]),t=strchr(a,*v[2]++),s>t?t-s+62:t-s]);} ``` A discussion about the process of golfing this code can be found here: <http://prob-slv.blogspot.com/2013/04/code-golf.html> [Answer] ## JavaScript 248 ``` var v= 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' function d(k,c){var a,b,o,x a=k.charAt(0) x=v.indexOf(a) b=v.substr(x)+v.substring(0,x) o= v.charAt(b.indexOf(c.charAt(0))) k=k.substr(1)+a c=c.substr(1) return (c)?o+d(k,c):o} ``` [Answer] # Uiua, 42 characters ``` A←⊂/⊂⊞+"aA"⇡26+@0⇡10 &p⊏-∩(⊗∶A)↯△,∶&sc&scA ``` -4 thanks to Unrelated String [Answer] ## Haskell (169) ``` import List main=do c<-y;t<-y;putStrLn$map((k!!).(`mod`62))$zipWith(-)(g t)(cycle$g c) k=['a'..'z']++['A'..'Z']++['0'..'9'] y=getLine f(Just x)=x g=map$f.(`elemIndex`k) ``` [Answer] # J: 91 characters ``` [:{&{.&t({&t"0&(({.t=.1|.^:(i.62)a.{~(97+i.26),(65+i.26),48+i.10)&i.)"0@:$~#)|:@(i."1.,"0)] ``` For example: ``` g=:[:{&{.&t({&t"0&(({.t=.1|.^:(i.62)a.{~(97+i.26),(65+i.26),48+i.10)&i.)"0@:$~#)|:@(i."1.,"0)] 'ThisIsAKey' g 'CoqKuGRUw29BiDTQmOpJFpBzlMMLiPb8alGruFbu' ThisWorksEquallyWellWithNumbers123894576 ``` [Answer] # [Scala](http://www.scala-lang.org/), 156 bytes Golfed version. [Try it online!](https://tio.run/##RU/LasMwELz7K5ZA0Aq7ovTWBhdy6MkuodSn3lRnU@TIsoiUktj4212pSulp57EMM66VWi7DZ0eth1epDNDFk9k72FoLU5bBt9TgnxDf/UmZryIdXj7fAJQLVkUThCl@1iUyyfzARsbzHNk24o@E7yN@ZHzTiFHZGEiyF@1gvDJnqfUVKy4OWvpQgIte2qmVjlAVXUivEWuhzJ4uuwMqfvdPOp7XwqmR@Pp2Z9EfU715gd8BFZSwqui6yhJvIu/V2wO97P60E7mz9sHwYRA0PMg2ZHhtMFk8m5cf) ``` (K,T)=>{val L=('a'to'z')++('A'to'Z')++('0'to'9');T.zip(Stream.continually(K).flatten).map{case(i,j)=>L((L.indexOf(i)-L.indexOf(j)+L.size)%L.size)}.mkString} ``` Ungolfed version. [Try it online!](https://tio.run/##TVDLTsJAFN33K05IzMwEbIw7TTBh4aoYYuzK3dje1sHptGkHAxi@vd4yLbC753VfXaat7vv6a0uZx5s2DrT35PIOq6bBXwTkVMC32nVF3VYyecaHb40rF0inUk0FlucE8KstLHlPbcecFFrA1xBHoTCfM14F/CnUxZ6b0vjBLR6C@CQu2prpqR3ng/WsyjQ@mkbyeNJVnNXOG7fT1h5kouLCas44FYYAcaX5JGS6I0izwFZh@TJqwFrKdWxcTvtNIY3CPa6QnXOGllzpvxXurvUYP11G/IRXRAMXhfUTXn@W0GE24nTAlXl/pNfNxLXU7axn4ebV/OKhf8P9vHUyWFR06vt/) ``` object Main extends App { def transform(K: String, T: String): String = { val letters = ('a' to 'z') ++ ('A' to 'Z') val digits = '0' to '9' val L = letters ++ digits (T.zip(Stream.continually(K).flatten)) .map { case (i, j) => L((L.indexOf(i) - L.indexOf(j) + L.length) % L.length) } .mkString } val K = "Key" val T = "miQ2eEO" val result = transform(K, T) println(result) } ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 136 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 17 bytes ``` LẎZƛ÷kr₀Ǔ:£~ḟǓ∇_ḟ¥i ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9cyIsIiIsIkzhuo5axpvDt2ty4oKAx5M6wqN+4bifx5PiiIdf4bifwqVpIiwiIiwibWlRMmVFT1xuS2V5Il0=) Bitstring: ``` 0110000111010001100100100100100010010101101010000010110100010111011110111110110000101100000011001010100000111000011100111110110100111001 ``` Takes message then key ## Explained ``` LẎZƛ÷kr₀Ǔ:£~ḟǓ∇_ḟ¥i­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌­ LẎ # ‎⁡Repeat the key to the length of the message Z # ‎⁢Zip each character in the message to the extended key ƛ # ‎⁣To each pair: kr₀Ǔ # ‎⁤ Push the string a-zA-Z0-9 :£ # ‎⁢⁡ and store a copy in the register ÷ ~ḟ # ‎⁢⁢ Find the position of the key character, not popping the alphabet string Ǔ # ‎⁢⁣ Rotate the alphabet string left that many times ÷ ∇_ # ‎⁢⁤ Put the message character at the top of the stack, followed by the rotated alphabet ḟ # ‎⁣⁡ Find the index of the message character in that alphabet ¥i # ‎⁣⁢ And index into the original alphabet string 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). ]
[Question] [ In convolutional neural networks, one of the main types of layers usually implemented is called the **Pooling Layer**. Sometimes, the input image is big (and therefore time consuming especially if you have a big input set) or there is sparse data. In these cases, the objective of the Pooling Layers is to reduce the spatial dimension of the input matrix (even though you would be sacrificing some information that could be gathered from it). A Max-Pooling Layer slides a window of a given size \$k\$ over the input matrix with a given stride \$s\$ and get the max value in the scanned submatrix. An example of a max-pooling operation is shown below: [![enter image description here](https://i.stack.imgur.com/6WbWu.png)](https://i.stack.imgur.com/6WbWu.png) In the example above, we have an input matrix of dimension 4 x 4, a window of size \$k=2\$ and a stride of \$s=2\$. # Task Given the stride and the input matrix, output the resulting matrix. # Specs * Both the input matrix and the window will always be square. * The stride and the window size will always be equal, so \$s=k\$. * The stride is the same for the horizontal and the vertical direction * The stride \$s\$ will always be a nonzero natural number that divides the dimension of the input matrix. This guarantees that all values are scanned by the window exactly once. * Input is flexible, read it however you see fit for you. * Standard loopholes are not allowed. # Test Cases ``` Format: s , input, output 2, [[2, 9, 3, 8], [0, 1, 5, 5], [5, 7, 2, 6], [8, 8, 3, 6]] --> [[9,8], [8,6]] 1, [[1, 2, 3], [4, 5, 6], [7, 8, 9]] --> [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 4, [[12, 20, 30, 0], [8, 12, 2, 0], [34, 70, 37, 4], [112, 100, 25, 12]] --> [[112]] 3, [[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]] --> [[20, 23, 26], [47, 50, 53], [74, 77, 80]] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answers in bytes wins! [Answer] # [Python 3](https://docs.python.org/3/), 101 ~~108~~ bytes ``` def f(m,w):r=range(0,len(m),w);return[[max(sum([x[i:i+w]for x in m[j:j+w]],[]))for i in r]for j in r] ``` Thanks to Jo King and Jonathan Allan for some more bytes off! [Try it online!](https://tio.run/##JYxBDoIwEEXXcopZtnEWIIpYwxE4waQLElst2EIqBDx9bTGZ5M9/efnTd36NrgzhoTRoZnHlwje@c0/FcnwrxyyP7O7VvHhHZLuNfRbLaCMjzHGVevSwgXFgqRd9BBJJcp6wSdjvRv9/QwsNEJ0QbgglQi0RKEcoEC7xUot5RYhGlVodnd2spMzS0JCGWLEbZy6yw@SNm5lmLcLAefgB "Python 3 – Try It Online") Alternate (longer) version as a single Lambda expression: [Try it online!](https://tio.run/##RdA9bsMwDIbhPafQKKEaov/UgE8ieHDRpHUQOYGbwunp3Zfp0I2gHnwUefu5f17nsG2n/jK2t/dRNbt2@r@2S7@M88dR7@3lOOtm7Gq6Wtv40F/fTddHnbrpZR1O10U91DSrVs/dmcZg62CMtCdpL09x/iuNJtlsra91b5WzylsVrIpWJauyVcWqw2BVfeVRAMJBHMaBHMrBXBHkDlRIj/SShfRIj/RIn0V5Mj3SIwMyIIOMRQZkSKICqQEZkAEZkREZkVF@GEVFUiMyIiMyIhMyIRMyBVFJ1kEmZEImZEJmZEZmLyqTmpFZNkdmZEZmZEEWJ6qQWpAFWZBFjoQsyII87Idht/Zhd1um@a5Pz/ua7Rc "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` »⁹/Z$⁺ ``` A dyadic Link accepting the matrix (list of lists) on the left and the window size on the right which yields a matrix (list of lists). **[Try it online!](https://tio.run/##y0rNyan8///Q7keNO/WjVB417vr//390tJGOgqWOgrGOgkWsjkK0gY6CoY6CKRCBeEDaXEcBqMIMxLMAqgGrNIuN/W8EAA "Jelly – Try It Online")** Or see [all windows of a 24\*24 grid pooled at each possible granularity](https://tio.run/##TZY9bh1HEIRznWIChQ/w7vzPCXwHEwyVELqAQx7GcCZAiQBJgAP6JrzI03xdtaSCwe7sm/6rqu55T58@f/77fn/5@fr8/Y@/Pr4@/7j//@@fL/@8fv3y9Pr838u3l2/3@0N66PmWSt1r3lLfz5y1@trrvKXRbqnt7zN73/fve5@yVi23tPa3cz/7sff7/Bx7bft8PH64pYfG531kZZkTZuzj1W55X/v4ud3XvT8Pvff9PXWFOffZNmRfSeNQyLQixLnN65Rp28@Mu2x3uDj03rZJxjXV8tt2mbbrddhl1u/YjKqK@owQ@RBQZLCqTbOPFIfcxeftumwXZfl9Gdx9vi6FjlDTqwFshKBYsurOfCxhn5rCpB1mZGO99Duu8rYrpMB3AwZYaafRXLlDEI2MZlXWqwnP3t6pBMgw7@YAG9ah7DkfvDVX0gVsU4hs2uBkTGUWx1BZF3CcCUoNBK6XKyS1yftUSsHrtlnQPiJEHXIPONDNETCGH8R3WiGAxVpOaSJm9lP0Ui10wx3CbdiVCDFPRSc7sgqtL5mTGcVTQajEVOaL9kO24zRvFjPV0kNnjhD0wVtmFG6hDmcf7bTUH8mgkRaVAwb9hFvCR0sOt28lfIQAe0JE104rySpBCijoUs@c4osMS9MzLYVZlk08qyjv5Y0L8KM4qojOJuwQSAFOl/vsAXJRDJikQpWEohWZCqRR21sV0EVnQlcxB81djFDhATfZmBN2uoMvgYaILQ1kwD6AFxcIs7nxobtZvFQUmQxljfYRI9wAxjRAKBGAuwdRduv1GDDqi/UbVacUBfZhuox58QzysEBVAAkCVA/98zoDElQZY1EhulqsuoIo8FD28T4M3lDHk@WlvkivCUDAye4VhtGIIaS@aBrWgX2R4E6HqKYfnKeVtzyn4l7Iv4k4y4b2LbzHBJaimgo@PQyWp2S2SqZlQJYx1Od7S05zQErLQwghNytwKQQcTCuBn@CDrMkW@rs5iEq63F/K6e786YmbHYb5xRyzokLrxRfoIeVkt9Ew9mGapZJ2qcl045pnpLlEM4DmEK6AOjT2oLX7puu@i6tnT7uU1HQ2wl63n@dRuYBtnsZUrUkbAswCITRtBS23YzXNgNP8jOlcHHJ5qmbZBSpD36u4AFuOUDg9AO4AQucui5iWSue7yvJ1uU5lfvqWjOnrvmJ/6krCdQze6WFxSnBMzJi4xS1nMENp178QUw29DPa4XH0hI53WH9PjPRQFlUB7Y47hcn96/AU "Jelly – Try It Online") ### How? ``` »⁹/Z$⁺ - Link: M, k $ - last two links as a monad - i.e. f(X) where X is initially M / - reduce (X)... ⁹ - ...in chunks of: chain's right argument (k) » - ...by: (left) maximum (right) (this vectorises across the k rows) Z - transpose the resulting matrix ⁺ - repeat the last link - i.e. f(that result) ``` [Answer] # [Octave](https://www.gnu.org/software/octave/) with Image Package, 38 bytes ``` @(M,s)blockproc(M,[s s],@(b)max(b(:))) ``` [Try it online!](https://tio.run/##LZFBasMwEEX3PYWWFghjSSPJqinkAj1ByCI2zaYtDk0pvb37RirYBmne/PnzvW/f15@34/YyjuNxGl7dw64f@/Z@/9o3TueHeVzcaVjt5/V3WIdna@1xG87BmepMdGZezOSMdybxLPotzlDNi5mdPjD5wpV9os23WlyMtAag0qAK4TtBPaAYeaem0W7aIdJVtEaTLMZrxU9chKQYGtI0uqHQZv8ParbwWrWD13ddD@FBvAoA@YKszqzdRVAdnQ8XpA8KuA66JFyo3WmEizoQTl1Gooi5O40aApzACZzAiTpjBUFP4EQ3ghO4BJc0ULhEVElX0HThElyCS3AZLsPlsJisKcNl3RUuw2W4XHtixZM0egWuaIr6nzQUuAJX4OaJAKM9/gA "Octave – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~15~~ 14 bytes *-1 byte, thanks @Bubbler* The left argument is the matrix and the right argument is the stride. ``` >./@,;.3~2 2&$ ``` [Try it online!](https://tio.run/##VZDNSsQwFIX3PsWHDI6DY83NTW6SEUUQXLnyFcRB3fgGvno9GWYjpaU9zfn9Xi@X7ZGHA1v2JA66bxee315f1sfl7ml/v/hvJl9t1t0FFx/vnz9cFwobMgOni2DU09WEhZAuPHYcyWeC3Xwtjk/I/mmYpBOekEo/fenFC03PphMmyFIiV/2c9HKmD5lvTtZZZkXmIfsu1ATalDLHpCBmYA2T/phuWRwZOblM3RxkBe/kMYO44ZL0mcIrHjOIq9GgJIpRMkWOyl8pQVHMThnURNUQmepUBdIgQW3UTh1EIozQPpqmEMobRCM6MWbdZrRMc5raa0rVabROG/Q0m/v6Bw "J – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~13~~ 12 bytes ``` >./\&|:^:2~- ``` [Try it online!](https://tio.run/##VZDNSgMxFIX3fYoPKdairbm5yU1S0I3gypVrcSMWdeMLiK8@npRuZJhh5kzO79dysd8cuTuw4YbEQfduz8Pz0@Nyv799ufw5vB7y727Zrli9v318c1UorMkMnK7jRj1dTVgI6cJjy5F8Jtj1597xCdk/DcvkhCek0k9fevFC07PphAmylMhVPye9nOlD5uuTdZZZkXnIvgs1gTalzDEpiBlYw6Q/plsWR0ZOLlM3B1nBO3nMIG64JH2m8IrHDOJqNCiJYpRMkaPyV0pQFLNTBjVRNUSmOlWBNEhQG7VTB5EII7SPpimE8gbRiE6MWbcZLdOcpvaaUnUardMGPc3mvvwB "J – Try It Online") ... When I said "`;.3` is the right tool for the job", I was wrong. This challenge is so simple that an alternative method can get to fewer bytes. ### How it works ``` >./\&|:^:2~- Left argument: matrix, Right argument: stride (s) - Negate the right argument ^:2~ Run the thing twice, with flipped arguments: (now the left is -s, right is matrix) &|: Transpose both the matrix and -s (transpose on -s is no-op) >./\ Run "reduce by max" on each of non-overlapping intervals of length s, in the primary dimension By running this twice, we achieve max pooling in two dimensions ``` [Answer] # [Python 2](https://docs.python.org/2/), 68 bytes ``` lambda M,k:eval("map(lambda*l:map(max,zip(*[iter(l)]*k)),*"*2+"M))") ``` [Try it online!](https://tio.run/##hZHLbsJADEX3@YoRqySdReadIOUT@ALKIlVBRAQaBfr8eXqvh64r5TH2HNvX9vx9O75d7P3QP9@n4fzyOqiNPq33H8NUrs7DXGZnPa1pnIcv/TPOZb0db/ulnKpdfaoqXa9q@7TaVNWqun8ex2mvzLpQJ73RSz9e5vdbWRVqsf2hRG4ch@t1v9zU0veLLdS8jBcY9m612m7x6bRyWrU7mI1WRquAhxb@SSsQkVYLRsi4o7ntdJvdsAtDjxHY0esli8Qliety0D9I4QUCYiHF4W0epcX3MB2oxHvEeToMb00Dlw1EH7V4KByPuS8r8h91pTfpoGMsXpOrGDAGkGEqYCZJCWrosi7LXNQD0vpc1EojlvMCabus3oF0LAuSqp3M1cWs3XGeID1ID9KD9FQoTXlk9SA9uwTpQQaQgRsCGWSKge1wYSADyAAygIwgI8hoSUWuDWRk5yAjyAgydnmSycgakDWBTJwvl88hgUwgE8i2yYOVGbi/nqlPdIkeiU2Z/QU "Python 2 – Try It Online") --- **74 bytes** ``` lambda M,k:eval("zip(*map(lambda*N:map(max,*N*2),*k*[iter("*2+"M)])))]))") ``` [Try it online!](https://tio.run/##JYpNDoIwEIXXcopJVzN1FlIVkIQjlAsgixohNuWnIcSol69Uk/fy8uV9/r0@5kmFvrqGwYy3uwHNruyeZkDxsR7laDz@H1mXEUbzYllLRSydbOzaLSik2gtNLVGsoKChggYVw4XhyJATAx4YUobzlkjb5gybkUUqGIqfmVGb9PMCDuwEmP6ME5XJzi92WrFHzeCIwhc "Python 2 – Try It Online") I can't even ... [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 20 bytes ``` {⌈⌿⍤2⌈/⍵}⊢⍴⍨4⍴÷⍨∘≢,⊣ ``` [Try it online!](https://tio.run/##jZK/ThtBEMb7e4rtMNJG8f731WmAAqQ43cmFpchpQEmLkCuQZQ4OJYqQ0tAYCncUEEWiQSJvMi/ifDN7yA5RAMm79uz@5pv5Zj38svvm4/5w9/OnxcGQJl87dDyj5uf671/U3NHJEZ1O31Jzaam5slTPjHLKKk/N8RD3vKi5BT8uDv5L4lqgOYLbDlJYe97W0YjHRWc1eX0ltZ4tU3Pa9AcyNdWXbUXE0/phTpPvlR1gf0U1SWRair6ELxin03vxlTPGz/W1GGGM1JzR2fnmDtWHD9eOJt8Q9d@/w/5hY7O/QP4eqKiiyNy4WFg1UnuFk51/55yt/s72WlVZrUqtnFa9gVZVVyujVcCHI3wnrUBEjnpghIyDwZqi5kJVVal7@QpnhXmqbSTZMeFFVXSS6JRLkRewwv@jC9yiVYfVbVuTszZ0kEl8Dw3PB4ZvTRdHNjC6UpsDmc1fFfIcrNhte5JZiNuStbBMrmrAGECGpYGZJCW5pzL3aVmL@wNpfW7CiknL8wVpy@zGgXRcFiS7cPIOLmYvjucP0oP0ID1Izx2KSQ9VD9Kza5AeZAAZ@EVBBplwYDv8wCADyAAygIwgI8homYr8zCAjOwcZQUaQscyTTUaeCKoJZOJ585@FhwQygUwge93loGUO7tE39yi9SU@SnzL/Bw "APL (Dyalog Unicode) – Try It Online") I'm pretty sure converting the dfn part into an atop `(⌈⌿⍤2⌈/)` should work (and save a byte), but there seems to be an [anomaly](https://tio.run/##SyzI0U2pTMzJT///X@NRT8ejnv2PepcYAVn6mo@6Fj3q3fKod4UJkDq8Hch41DHjUecinUddi/@nPWqb8Ki371HfVE//R13Nh9YbP2qbCOQFBzkDyRAPz@D/QP25QFVmCmZgYzYbm3EZKaQp5HIZg0gA) that prevents me from running multiple test cases with that version. ### How it works ``` {⌈⌿⍤2⌈/⍵}⊢⍴⍨4⍴÷⍨∘≢,⊣ left: stride (s), right: matrix ÷⍨∘≢ a = size of matrix divided by stride ,⊣ Concatenate a with s 4⍴ Create a length-4 array (a s a s) ⊢⍴⍨ Reshape the matrix into a 4-dimensional array with shape a,s,a,s { } Pass the result into the dfn... ⌈/⍵ Take the max through the 4th axis (shape: a,s,a) ⌈⌿⍤2 Take the max through the 2nd axis (shape: a,a) ``` APL also has an operator called "Stencil" `⌺` that is similar to J's "Subarrays" `;.3`, but it has a weird starting location, making it clunky to use for this challenge. [Answer] # [J](http://jsoftware.com/), 23 bytes ``` (#@];~@$1{.~[)>./@,;.1] ``` [Try it online!](https://tio.run/##PVDLSgNBELznKwoNxGBcpx/TPZOgBARPnrxKTmJQL36AkF9faxKQZpaZ2q5H9/d8Na2OeNhihQ0Ktjx3E55eX57nm@v9YXfaL@V3Or2tH6f7/WY3yWFeL7D4eP/8geIIZy156zA0kgX1XEksiDTicWkXtsvt12SwC@D/fFFogRVQoZ1fvJgj@U12CCEpBVr580I2kjtreTZVvp22QeNGVAjKEBKDkE9eQBJC9T68lBzaGNSHqgaUkRu0jxgmMErayGAVFiOGcZYOL3CBK5yOTF/hAWfIBu@oBZUrUFRDZSCuIlATtaF2REEIgpvhUhzBvIFIREP0MWwKUpGG5OxcIsdJZEN2tDL/AQ "J – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ôεø¹ôεZ ``` -1 byte thanks to *@Grimy*. Stride as first input and matrix as second input. [Try it online](https://tio.run/##FdA9TgMxEEDhnlP4AFNk/jdXYbUFSBRUFFwtkaBNeq60vKlsyZ@ePf76fnv//DjP5@3v/vx5/M76ep7@su8XWSrLZLmskJWySlbL2g5Z@5XDAQiFKEZBilKY9iDd2CENadNCGtKQhrQaZTQNaUhHOtLnWqQjPUc5VUc60pGBDGQgY14Yo4JqIAMZyEAmMpGJTB@VMw4ykYlMZCILWciyUUW1kDWTIwtZyEI2snVUU21kIxvZ80nIRjZyuxzHPw) or [verify all test cases](https://tio.run/##LZG9TsNAEIR7P8XK9Rb3fzZNmggpFT2WiyAoaAJSkjIPREMFiDrpeSUzs2fJlm9vv92dHb8d90@vL0u@73eH9/PpeCf9Zrfd9LI/PNvx@qFd/3A@Icnccvv6@779Xj/5fVwuF73@bJZp8kGD0@jUzToNytCOMWnFfdWEwOPaO6chA5jnLnTTFFRGlagyzCqTU/EqGQ8jfKsKiMJoAGNkWUu95SJzyYoMq4aNYHxnugTCBMrErV3sbg2hTyrzKEu8oEahSIFKMZkJfZqwYPPXYSbOVI@swOtbbw/GA/JsAMxXa8zJY1MT2IsqQIbURgVTH7gwyDA2zRFk5FiQ1BrNmFia4khDQCaQCWQCmajQVknomkAm7gYygcwgMy0Gmc26zHXoOMgMMoPMIAvIArIEUoW@gyzcHGQBWUCWsflXvXmPrhVkpav8ezQJZAVZQQ4OdsZ/). **Explanation:** ``` ô # Split the rows of the (implicit) input-matrix into # the (implicit) input-integer amount of groups # i.e. [[12,20,30,0],[8,12,2,0],[34,70,37,4],[112,100,25,12]] and 2 # → [[[12,20,30,0],[8,12,2,0]],[[34,70,37,4],[112,100,25,12]]] ε # Map each group of rows to: ø # Zip/transpose; swapping rows/columns # i.e. [[12,20,30,0],[8,12,2,0]] → [[12,8],[20,12],[30,2],[0,0]] ¹ô # Split the columns into the input-integer amount of groups as well # i.e. [[12,8],[20,12],[30,2],[0,0]] → [[[12,8],[20,12]],[[30,2],[0,0]]] ε # Inner map over each block: Z # And get the flattened maximum of the block # i.e. [[12,8],[20,12]] → 20 # (after which the result is output implicitly) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes ``` BlockMap[Max,#2,{#,#}]& ``` [Try it online!](https://tio.run/##dZJPSyNBEMXv/SmKHvDUgfT/DBoJelrBXdFjZw5DGDVoYkjmsCB@9viqOrrsQchkpqp/Vf1edW/68XnY9ON61R8f58er17fVy22/K7f9X9M4896Y5qM7O47DYbzuD8PhYdzTnLQzVAr@WkPe0KxDODVkDUX8OMI7GwKROJqBMbRUnuOOJpNLlLdmVteQUlxbipUSz@kgvaQ6S3X7XfgjtVSVUxSkGygHWR7P9CRDcqfQg8q8jtLACcurdoqUi9zNun978rdis@Xk1In1kwBxK3Za7oDH1r0sGAvIgrJJmmbZirW0VZ/jbqwLrAt1cyeeHM8QpGurCw/SO5kkWNbvZdo@VRcerAcbwAawAWxglWIvoG8AGdivnEcAG8FGPjmwUYYa2RQfJNgINoKNIBPIBDI5phIfZuAuiScANoFNYFNb55qtnAv6ZrCZp83XgocFMoPMIGdTDHmp6phlHP7LPgsVeSJLGuRaoM@Vutuvt2N5LI2hxnU0n1PjOzqjxWJBin5tdm/7Edd1vX0qiqh@3Q@71341cIJ0KZouLum/u41Yo72hd73cappwaApiDYE1NvoDctBB3zz8@a274yc "Wolfram Language (Mathematica) – Try It Online") [Answer] # dzaima/APL, ~~14~~ 12 bytes ``` ⊣t¨t←⌈/⍬∘⍮⍛⍴ ``` [Try it online!](https://tio.run/##NVA7SkRBEMw9RYW7gTj9mZ6Z4yzIgqBgsJEHkEVcMREEQxMDMfIEHmUu8qx@YtYzXdX12d1en1/e7a5udsuyn/fP8@H98PNxyOnxeDFPn/P4Ok9f8/Q2T9/LfHrhRrHHRjFg6FtsCgQVlVNFgyI4dXRuY3v2x5BkCHfGnROdmEbM@Ef4ilBogRWU9UQ@19Ecjf8NzofwW0qBVgL@6Zb0NEIJrAK0kuYGsRDJW2IQh5AWkJaXKDFSUcmjlkE9z2q6U0bp0JF2TGA8bKARy6AW6caYccALXOAKp3Ia9AoPON12@EAtqCxIUTN8pTmWFagNtaMOREEIQrkMVuYIug9EQ3TEyORNsi5FMzRWwZoZr6F1tIFetssv "APL (dzaima/APL) – Try It Online") [Answer] # JavaScript (ES6), 85 bytes Takes input as `(s)(matrix)`. ``` s=>m=>m.map((r,y)=>r.map((v,x)=>(r=M[Y=y/s|0]=M[Y]||[])[x=x/s|0]>v?0:r[x]=v),M=[])&&M ``` [Try it online!](https://tio.run/##hZLdasJAEIXvfYq9kgS2mv1PCrFP4AOUJRditbSokaSECL57embWVupNIUF399sz58zkczNs@m33cf56OrVvu2lfT329OuJZHDfnLOvkJa9XXVoMcsQi6@p1fK0vy/5aNPS3uV5jk8exHnlrNbwUz10cm3rI5brG0Xy@nrbtqW8Pu8Whfc/2mc6zGLUUlRRGirKRIhZSKCkcHlrhN0gBwtOqBMOkb5o8ny2XIsZKlukIe7O/6orUFV83xFjWZaXAStVd5h/sQdmyMi5o2DV4i5s93rstDYQCnUPF0oaiU1VgSztCf6vj4LGCoQqpF5oj31xxPzhxRVp4VaqqwChAiqSBqcAlyVOVfGrSIn8gtU0mNMfU1GOQukppDEhDZUFSCsOzMD5lMTQDkBakBWlBWnLIIS1ULUhLqUFakA6ko6mCdNxjR3FoyCAdSAfSgfQgPUivifI0apCekoP0ID1IX6XOBsVDgmoAGajf9MFQk0AGkAFkWdzHzH0wP7nJI3tjT3w/JH76Bg "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` NθIE⪪EAE⪪ιθ⌈λθE§ι⁰⌈Eι§νμ ``` [Try it online!](https://tio.run/##TdDNSsQwFIbhvVeRZQoRmv/KrMTVLBTBZemijgMW2tqprczd1/fMMGhWyTkPX3Jy@Gznw1fbb9t@nNblZR3ej7M@Fbu717kbF/3Ufi/6uZ3029R3190F6sKov3Jn1OlSOHfDOui@KIpbZdKPy378OJ4Flf@QtCjduqNRQ3Fdu22rvVF1XRpljXJGcQpGRaOSUdmoqqH7QFMAwkIsxoIsysJsFmQrdkiHdJKFdEiHdEiXRDkyHdIhPdIjvVyL9EgfRXlSPdIjPTIgAzIgg7wwiAqkBmRABmRARmRERmT0oqKMg4zIiIzIiEzIhExOVCI1IZNMjkzIhEzIjMxWVCY1IzMyI7N8EjIjM7Iqm6bZ7n/6Xw "Charcoal – Try It Online") Link is to verbose version of code. Outputs each maximum on its own line, with matrix rows double-spaced. Explanation: ``` Nθ Input the stride A Input matrix E Map over rows ι Current row ⪪ θ Split (horizontally) into windows E Map over windows λ Current window ⌈ Take the maximum ⪪ θ Split vertically into windows E Map over windows E§ι⁰ Map over horizontal maxima Eι Map over windowed rows §νμ Get windowed cell ⌈ Take the maximum I Cast to string for implicit print ``` `E§ι⁰Eι§νμ` is effectively the nearest Charcoal has to a transpose operation, although obviously I can at least take the maximum of the transposed column in situ. [Answer] # [Python 3](https://docs.python.org/3/), ~~275~~ ~~196~~ ~~184~~ ~~163~~ ~~159~~ 111 bytes ``` def f(s,m):r=range(len(m)//s);return[[max(b for k in range(s)for b in m[i*s+k][j*s:][:s])for j in r]for i in r] ``` [Try it online!](https://tio.run/##VZHNboMwEITvfQofIbUU/B9S9UkQh0SFliSQCFKpfXo6s06l9oBZrz/Pzq5v3/eP6@TW9a3rVV8seiz38@t8mN674tJNxVhut0v5Mnf3z3lqmvHwVRxVf53VWQ2TytxSMnFkYmyGzfJ8bpvTZtm3zX5p5ewkcMtwyOF6m4fpXvSF0appsFitXIvYaxW0igyTVjut6rYty6df3BLHUgPHMbFKKyOXAnf4J1ETiZ1IOO7@qngpCsjissNXPWDJPbYOVOI59DwThqemQsoGov8kHSWzFSsVH42IHfFZ8zI@k8sYMAaQoRYwk6QGTdTZmKUWDYG0Ple10pZliyBtne07kI5lQdK2k1G4mM07jgCkB@lBepCeDqUrD1UP0rNNkB5kABk4VJBBniWwHc4YZAAZQAaQEWQEGS2pyEmDjOwcZAQZQcY6jzIZeVeoJpCJA@Z7cUggE8gEcldxsusP "Python 3 – Try It Online") Thanks to: - @randomdude999 for saving me 12 bytes - @Jitse for saving 48 bytes [Answer] # [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ó╚←XF«≡ûÖçx ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=a2c81b5846aef096998778&i=[[2,+9,+3,+8],+[0,+1,+5,+5],+[5,+7,+2,+6],+[8,+8,+3,+6]]+2%0A[[1,+2,+3],+[4,+5,+6],+[7,+8,+9]]+1%0A[[12,+20,+30,+0],+[8,+12,+2,+0],+[34,+70,+37,+4],+[112,+100,+25,+12]]+4%0A[[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]]+3&a=1&m=2) ### Unpacked (13 bytes) and explanation ``` X/{Mx/{:f|Mmm X Save window size to register X / Take groups of X rows { m Map block over groups: M Transpose (gets list of column segments) x/ Take groups of X column segments (our windows) { m Map block over windows: :f|M Flatten and take maximum ``` Leaves the result on the stack, since arrays print as strings. That makes the output hard to determine. [Here's a pretty version.](https://staxlang.xyz/#c=X%2F%7BMx%2F%7B%3Af%7CMmmF%7CuP&i=[[2,+9,+3,+8],+[0,+1,+5,+5],+[5,+7,+2,+6],+[8,+8,+3,+6]]+2%0A[[1,+2,+3],+[4,+5,+6],+[7,+8,+9]]+1%0A[[12,+20,+30,+0],+[8,+12,+2,+0],+[34,+70,+37,+4],+[112,+100,+25,+12]]+4%0A[[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]]+3&a=1&m=2) [Answer] # [Ruby](https://www.ruby-lang.org/), 57 bytes ``` ->m,w{g=->r{r.transpose.each_slice(w).map &:max};g[g[m]]} ``` [Try it online!](https://tio.run/##PdHrSsMwGAbg/15FfolCVppzq2w3UoLU0VXBaumUKWPXXt/3yxRaStIn3ynL1/PPetium92kT@dxu9kt56X6XPr34/xxHKqh3788Hd9e98Pd6b6a@lndPkz99@Vx7MZuyvmyzurQdZ3VqtXKadVkrbpaK6NVwMMVvkkriMhVAyMy5qxtvinnjQBH4OWk2CS2BVTmX8JZJHB462tA2bsuHc4n/sdhzw3Dv6bGlg2kiOb/gpVCrdRzzSvFShctj@E1JYGBMUCGUcBMkuhM35aSLGOxFEjrSz4rjVgOANK2pXAH6ZgWkgU7GZSLpWzHAUF6SA/pIT0rlH48onpIzwYhPWSADBw5ZJApBrbDG4AMkAEyQEbICBktVeQ9QEZ2DhkhI2RsyxCTkWtA1ASZOFreJocEmSATZFPzhlxefwE "Ruby – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 24 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` mòY=UÊzV)Õc òYp)®rwÃòV y ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bfJZPVXKelYp1WMg8llwKa5yd8PyViB5&input=W1syLCA5LCAzLCA4XSwgWzAsIDEsIDUsIDVdLCBbNSwgNywgMiwgNl0sIFs4LCA4LCAzLCA2XV0KNAotUQogLS0%2bIFtbOSw4XSwgWzgsNl0) ``` U.m("ò", // split each row by.. Y = U.l().z(V)) // input size / s .y() // transpose .c() // flatten .ò(Y.p()) // split in Y*Y chunks .m(function(Z) { return Z.r("w") }) // max of each .ò(V) // rematrix .y() // retranspose ``` ]
[Question] [ ## What is the Ultraradical? The [ultraradical](https://en.wikipedia.org/wiki/Bring_radical), or the Bring radical, of a real number \$a\$ is defined as the only real root of the quintic equation \$x^5+x+a=0\$. Here we use \$\text{UR}(\cdot)\$ to denote the ultraradical function. For example, \$\text{UR}(-100010)=10\$, since \$10^5+10-100010=0\$. ## Challenge Write a full program or a function, that takes a real number as input, and returns or outputs its ultraradical. ## Requirements No standard loopholes are allowed. The results for the test cases below must be accurate to at least 6 significant digits, but in general the program should calculate the corresponding values for any valid real number inputs. ## Test Cases 9 decimal places rounded towards 0 are given for reference. Explanation is added for some of the test cases. ``` a | UR(a) ---------------------------+--------------------- 0 | 0.000 000 000 # 0 1 | -0.754 877 (666) # UR(a) < 0 when a > 0 -1 | 0.754 877 (666) # UR(a) > 0 when a < 0 1.414 213 562 | -0.881 616 (566) # UR(sqrt(2)) -2.718 281 828 | 1.100 93(2 665) # UR(-e) 3.141 592 653 | -1.147 96(5 385) # UR(pi) -9.515 716 566 | 1.515 71(6 566) # 5th root of 8, fractional parts should match 10 | -1.533 01(2 798) -100 | 2.499 20(3 570) 1 000 | -3.977 89(9 393) -100 010 | 10.000 0(00 000) # a = (-10)^5 + (-10) 1 073 741 888 | -64.000 0(00 000) # a = 64^5 + 64 ``` ## Winning Criteria The shortest valid submission in every language wins. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 20 bytes ``` Root[xx^5+x+#,1]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2Yb8z8oP78kuuL9pIUVcabaFdrKOoaxav8DijLzShz8otOiDWJjuRA8QxSeLio3uLCoJNooFlWJKwo3IBOFaxGnYahvqolmqIGBgSHQ2v8A "Wolfram Language (Mathematica) – Try It Online") Still a built-in, but at least it isn't `UltraRadical`. (the character `` is displayed like `|->` in Mathematica, similar to `=>` in JS) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ;17B¤ÆrḢ ``` [Try it online!](https://tio.run/##y0rNyan8/9/a0Nzp0JLDbUUPdyz6//@/oQEA "Jelly – Try It Online") **How it works:** * Constructs the list `[a, 1, 0, 0, 0, 1]` by prepending `a` to the binary representation of `17`. Why this list? Because it corresponds to the coefficients we are looking for: ``` [a, 1, 0, 0, 0, 1] -> P(x) := a + 1*x^1 + 0*x^2 + 0*x^3 + 0*x^4 + 1*x^5 = a + x + x^5 ``` * Then, `Ær` is a built-in that solves the polynomial equation `P(x) = 0`, given a list of coefficients (what we constructed earlier). * We are only interested in the real solution, so we take the first entry in the list of solutions with `Ḣ`. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 60 bytes ``` f=lambda n,x=0:x!=(a:=x-(x**5+x+n)/(5*x**4+1))and f(n,a)or a ``` [Try it online!](https://tio.run/##XYlBCsIwEEX3niLuZpJGJ7XVUMhhRkpQ0GkIXaSnj7oQoosP772ftvW2yMmnXGsMD35eZ1bSlUBT2QfgKRQLRevRFCN4hFG/ZTAOkWVWEaRjXLLimvJdVohgHRE5Qtx9S8uuYfsj/eHifO8/G87N8dfrCw "Python 3.8 (pre-release) – Try It Online") Newton iteration method. \$ x' = x - \frac {f(x)} {f'(x)} = x - \frac {x^5+x+n} {5x^4+1}\$ While using \$ \frac {4x^5-n} {5x^4+1} \$ is mathematically equivalent, it makes the program loop forever. --- Other approach: # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 102 bytes ``` lambda x:a(x,-x*x-1,x*x+1) a=lambda x,l,r:r<l+1e-9and l or(m:=(l+r)/2)**5+m+x>0and a(x,l,m)or a(x,m,r) ``` [Try it online!](https://tio.run/##NYy7CgIxEAB7vyJlNtlgogheMH6JTeQ8FDYPlivWr4@eYDMMDEx/r89Wj@fOY0m3Qbnc56wkZi3oxIgL@KUNsMvpH5GQI1/Ihoebcp0Vqca6xKTJMuwPYMzJFitXv8XtRFig8U8LMozOr7rqRbvgvQ8eYHwA "Python 3.8 (pre-release) – Try It Online") Binary search, given that the function `x^5+x+a` is increasing. Set the bounds to `-abs(x)` and `abs(x)` is enough but `-x*x-1` and `x*x+1` is shorter. BTW Python's recursion limit is a bit too low so it's necessary to have 1e-9, and the `:=` is called the walrus operator. [Answer] # JavaScript (ES7), 44 bytes A safer version using the same formula as below but with a fixed number of iterations. ``` n=>(i=1e3,g=x=>i--?g(.8*x-n/(5*x**4+5)):x)`` ``` [Try it online!](https://tio.run/##bc5BDoIwEIXhvSeZGWwZlBJiUly5cGHiESAIBUNaI8T09tWtabdfXl7@Z/fp1v49vzZh3WMIow5WNzDrYjjujfa6mYU4G5A1eWFzUOSJykwhnjy2beidXd0yyMUZGIERd/9SRCJiOhCxVBHfum2SlzTfr/Ex1FlNBEX@u4pDOFHCiWDm9JITD1VJpLKqRAxf "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES7), ~~43~~ 42 bytes Newton's method, using \$5x^4+5\$ as an approximation of \$f'(x)=5x^4+1\$. ``` n=>(g=x=>x-(x-=(x+n/(x**4+1))/5)?g(x):x)`` ``` [Try it online!](https://tio.run/##bc5BCsIwEIXhvSeZmZB0Km0pQurKhQvBI7TUNiolEVtkbh/dSrL9eDz@5/AZ1vH9eG3ah9sUZxu97cBZsZ1oEG1BlC9AiCpVIhY1Hh0IHgT7Po7Br2GZzBIczMCIu38pE9Ep7YnY1Alfhu1uTnm@ntNjaFVLBOWvENMQzpRwJpg5v@TMQ1MR1aqpEOMX "JavaScript (Node.js) – Try It Online") ### How? We start with \$x\_0=0\$ and recursively compute: $$x\_{k+1}=x\_k-\frac{{x\_k}^5+x\_k+n}{5{x\_k}^4+5}=x\_k-\frac{x\_k+\frac{n}{{x\_k}^4+1}}{5}$$ until \$x\_k-x\_{k+1}\$ is insignificant. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~11~~ 10 [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") -1 thanks to dzaima Anonymous tacit prefix function. ``` (--*∘5)⍣¯1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X0NXV@tRxwxTzUe9iw@tN/yf9qhtwqPevkd9Uz39H3U1H1pv/KhtIpAXHOQMJEM8PIP/pynAgQEXEscQiaNriCKjZ2JoYmRobGpmhKzGSM/c0MLIAoSRVRvrGZoYmloamZkaI6u21DM1NDU3NDM1M0MSNkQ4QdfQAMEBsqEckLABWJmhgbmxuYmhhYUFAA "APL (Dyalog Unicode) – Try It Online") `(`…`)⍣¯1` apply the following tacit function negative one time:  `-` the negated argument  `-` minus  `*∘5` the argument raised to the power of 5 In essence, this asks: *Which \$x\$ do I need to feed to \$f(x)=-x-x^5\$ such that the result becomes \$y\$.* [Answer] # [R](https://www.r-project.org/), 43 bytes ``` function(a)nlm(function(x)abs(x^5+x+a),a)$e ``` [Try it online!](https://tio.run/##PYzRCsIwDEV/JRQfEtpJN@bYi36JDGpZIaDd7Cr072v6oA8JOZeTm2qAK9TwiT7zFtFRfL7wj4Xc48CyXHTRjoyj01rDlpCBI3i0BnoDnczxThkHEljLjr0cOxuY9bycB5Fss2zT7W@3bBqleRqJvMsovupuykBAln91j4rqFw "R – Try It Online") `nlm` is an optimization function, so this searches for the minimum of the function \$x\mapsto |x^5+x+a|\$, i.e. the only zero. The second parameter of `nlm` is the initialization point. Interestingly, initializing at 0 fails for the last test case (presumably because of numerical precision), but initializing at `a` (which isn't even the right sign) succeeds. [Answer] # [R](https://www.r-project.org/), 56 bytes ``` function(x)(y=polyroot(c(x,1,0,0,0,1)))[abs(Im(y))<1e-9] ``` [Try it online!](https://tio.run/##HcJRCoAgDADQ62yg4D6LPEBniD4sEgJzogbu9AvivarRa3zz2W/OMBDEF05SmTucMAwZ9yNE3MLRYH1AEBe67LRrC6UkAUtuJmci6gc "R – Try It Online") Thanks to @Roland for pointing out `polyroot`. I have also realised my previous answer picked a complex root for zero or negative \$a\$ so now rewritten using `polyroot` and filtering complex roots. [Answer] # [J](http://jsoftware.com/), 14 bytes ``` {:@;@p.@,#:@17 ``` [Try it online!](https://tio.run/##VVDNSsQwEL73KT70sAi7w0z@JqmsBAVP4sEXWES6LCJUbMFDffea2ojuhIHJ9zchr/MFbY7Yt9hgC0Zbeke4e3q4n6c2X@d3ytvLNovOV00zdsOIPYGJlxJ0L6c@3@CYJ8JX3mFqq4jLWSfBgUm9ixpX4CA4B4ScOCPWB7NoY5QgWrWGVKKJSxedMCdrV8qSOPHJBG9LZLloCr66EnnxKsGHUFw/cw0UXsTeWhbbNI@3hPHUDR2ePzqMfY/hrf@kUpVb38sMQy4lw@4PLmjJspRUY0rnci5rpH4S/7eoVScxRhyC@6UbzN8 "J – Try It Online") J has a built in for solving polynomials... `p.` The final 4 test cases timeout on TIO, but in theory are still correct. ## how The polynomial coefficients for J's builtin are taken as a numeric list, with the coefficient for `x^0` first. This means the list is: ``` a 1 0 0 0 1 ``` `1 0 0 0 1` is 17 in binary, so we represent it as `#:@17`, then append the input `,`, then apply `p.`, then unbox the results with raze `;`, then take the last element `{:` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~53~~ 41 bytes ``` ->a{x=a/=5;99.times{x-=a/(x**4+1)+x/5};x} ``` [Try it online!](https://tio.run/##FYhBCoMwEADvviIIgsZk3W0VI6I/6AvEQwqKPQihKmxR357qYYZhvtv758fG69bu3NisKeqqgvUzD8vO@hoxS5mnlKScFWfNp@80ISIhoLqhC33rZdcJBnYxJeohJUKhCMtnmZMxBrCH2br94CNw27qIMIJqFFq34o4w6liNHfd9cPo/ "Ruby – Try It Online") Using Newton-Raphson with a fixed number of iterations, and the same approximation trick as [Arnauld](https://codegolf.stackexchange.com/a/193399/18535) [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), ~~34~~ ~~32~~ ~~26~~ 24 bytes ``` a->-solve(X=0,a,a-X-X^5) ``` [Try it online!](https://tio.run/##K0gsytRNL/j/P1HXTrc4P6csVSPC1kAnUSdRN0I3Is5U8////wA "Pari/GP – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` ΔyIy4m>/+5/- ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3JRKz0qTXDt9bVN93f//jfUMTQxNLY3MTI0B "05AB1E – Try It Online") Newton's method. [Answer] # k4, ~~33~~ 31 bytes ``` {{y-(x+y+*/5#y)%5+5*/4#y}[x]/x} ``` newton-raphson computed iteratively until a number is converged on edit: -2 thanks to ngn! --- whoops, got this all wrong... # ~~K (oK), 10 bytes~~ ``` {-x+*/5#x} ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 24 bytes ``` a->polrootsreal(x^5+x+a) ``` [Try it online!](https://tio.run/##LUxLCoMwFLzK4MpgEvIS85FSL1JayKIWQWqILuzp00i7GJh/inkWr1QmXEsUY1qXvK77lp9xaY@H7Y4uslJiSsunjRAjUp7fe6XNKRpMbWSM46Y4iENUkOyphyYD63S1tPQUoAMh6MBhJPUEO2g4a2o8SEsWnlytu7pW54s676DUX0DRz/AGvq5DCHd2@QI "Pari/GP – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), 25 bytes ``` @(a)fzero(@(x)x^5+x+a,-a) ``` [Try it online!](https://tio.run/##PYzBCsIwEETvfsmG2rCzySbpQeiHiBCkuRZEJPjz0aTiYQZmhnn7/ZlfWyuXa1spm/LeHjutVE296VSnfJ6zaYXYnAqh2zwc1sMLnAYZpdiIJKmrZ2fhoYsEdWNerEIjgoYw3nyQ@MAy/zPjV0UXPVL60toH "Octave – Try It Online") [Answer] # [Maplesoft Maple](https://www.maplesoft.com/support/help/), 23 bytes ``` f:=a->fsolve(x^5+x+a=0) ``` Unfortunately, there is no online Maple compiler/calculator out there AFAIK. But the code is pretty straightforward. [Answer] **C,118b/96b** ``` #include<math.h> double ur(double a){double x=a,t=1;while(fabs(t)>1e-6){t=x*x*x*x;t=(x*t+x+a)/(5*t+1);x-=t;}return x;} ``` 118 bytes with original function name and with some extra accuracy (double). With bit hacks may be better, but unportable. 96 bytes with fixed iterations. ``` double ur(double a){double x=a,t;for(int k=0;k<99;k++){t=x*x*x*x;x=(4*x*t-a)/(5*t+1);}return x;} ``` Actually, our function is so good we can use better adaptations of Newton's method. Much faster and practical implementation (150 bytes) would be ``` #include<math.h> double ur(double a){double x=a/5,f=1,t;while(fabs(f)>1e-6){t=x*x*x*x;f=(t*(5*t*x+5*a+6*x)+a+x)/(15*t*t-10*a*x*x*x+1);x-=f;}return x;} ``` I checked it works, but I'm too lazy to find out how much more fast it would be. Should be at least one more order faster as Newton's. [Answer] # MMIX, 68 bytes (17 instrs) (jelly-style xxd -g4) ``` 00000000: e0043ff0 e0034014 79010001 3b01013f ṭ¥?ṅṭ¤@Þy¢¡¢;¢¢? 00000010: e8013ff0 c1020100 10ff0202 10ffffff ċ¢?ṅḊ£¢¡Ñ”££Ñ””” 00000020: 1001ff02 10ffff03 e4010020 04ffff04 Ñ¢”£Ñ””¤ỵ¢¡ ¥””¥ 00000030: 06010100 140101ff 11020102 5b02fff6 ©¢¢¡Þ¢¢”×£¢£[£”ẇ 00000040: f8020000 ẏ£¡¡ ``` **Disassembly** ``` bringr SETH $4,#3FF0 // one = 1. SETH $3,#4014 // five = 5. ZSNN $1,$0,1 // x = (a neg? 0 : 1) SLU $1,$1,63 // x <<= 63 ORH $1,#3FF0 // x |= 1. [now x = a neg? 1. : -1.] 0H SET $2,$1 // loop: px = x FMUL $255,$2,$2 // t = px *. px FMUL $255,$255,$255 // t = t *. t FMUL $1,$255,$2 // x = t *. px FMUL $255,$255,$3 // px = px *. five INCH $1,#20 // x *.= 4. (bit trick: add two to exponent) FADD $255,$255,$4 // t = t +. one FSUB $1,$1,$0 // x = x -. a FDIV $1,$1,$255 // x = x /. t FCMPE $2,$1,$2 // px = epsilon_comp(x, px) PBNZ $2,0B // iflikely(px) goto loop POP 2,0 // return x ``` I used WolframAlpha to simplify Newton's method for this. It said that \$\def\d{{\rm d}}x-{x^5+x+a\over{\d\over \d x}x^5+x+a}\$ simplified down to \$4x^5-a\over5x^4+1\$. The convergence test here is a builtin epsilon-convergence, so `rE` must be set by the calling function. For faster convergence, change `ORH $1,#3FF0` to ``` SLU $255,$0,1 // 3BFF0001 ;”¡¢ shift left to erase sign INCH $255,#8020 // E4FF8020 ỵ”⁰ unbias exponent PUT rD,0 // F7010000 ẋ¢¡¡ prep dividend DIVU $2,$255,5 // 1F02FF05 þ£”¦ take approximate fifth root CSN $2,$255,$255 // 6002FFFF `£”” and use that if we are >1 INCH $2,#7FE0 // E4027FE0 ỵ£¶ṭ rebias exponent SRU $255,$2,1 // 3FFF0201 ?”£¢ shift right again OR $1,$1,$255 // C00101FF Ċ¢¢” or sign and guess ``` [Answer] # Excel (Insider Beta), 59 bytes ``` =h(a1,1) h =LAMBDA(a,x,IF(a=x^5+x,x,h(a,(a/(x^5+x))^0.2*x))) in name manager ``` 1 byte for name h in name manager, 49 bytes for formula for h, 9 bytes for calling h. Uses successive approximations using the 5th root of a/(x^0.5+x) times x. Initial call uses 1 for x. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~61~~ 60 bytes ``` import StdEnv $a=iter 99(\x=(3.0*x^5.0-a)/inc(4.0*x^4.0))0.0 ``` [Try it online!](https://tio.run/##PYzBTsMwEETv/YpVVKkJSow3thNHIpzggMStR1wkk7olUuKixED5eYxTVxx2dmdW87rBaOvH0/5zMDDq3vp@/DhNDrZu/2i/Vmvd9s5M0DSpOrcpI/Tm/CoILXR229su5ZcgaJZRQv3W6dBt4SV1ZnY5bJTd5JC095DksI5ZoqyySaYULB7uisued6vvdzOZaBZE4OWAixQYT468RCaqMkQlqVGWcpkcGEGOoikrwcKrIQJFjZWoqtCikUAjjtJ/T/Ea1azmKKUkdOd/u8Ogj7Mvnp79w4/VY98F8/YH "Clean – Try It Online") Newton's method, first implemented in [user202729's answer](https://codegolf.stackexchange.com/a/193380/18730). # [Clean](https://github.com/Ourous/curated-clean-linux), 124 bytes ``` import StdEnv $a= ?a(~a)with@x=abs(x^5.0+x+a);?u v|u-d==u=u|v+d==v=v= ?(u+if(@u< @v)0.0d)(v-if(@u> @v)0.0d)where d=(v-u)/3E1 ``` [Try it online!](https://tio.run/##PY1Na4NAEIbv@RWDBLKLH91VVw3NRg/NodBbjjWFjZpG0E2JrrEQ@tNrVy1hmI/3GeadrCqEHOpLrqoCalHKoay/LtcW9m2@k91iKTjEAv0IfCvbc9JzcWxQ/8EcYvamwM@xgu6u7JxzxdW9M/XQ6YAYKbM8oURtIOkwcUiOUWdPZPsgt3NxLSDneqPwk7ejw74V@jeHd9QWTWvBKpUrCwy@BcOC5cyMVKbSwGkKo4aNPfXmsJjtJjFa6BcW0LHYdB596rvUY4GrkeuENHKjMS3wHOpTtnYD5unV2mGUhTRgQaCvyOxAZjtCHprQfxR6oU@jKHLIYfjNTpX4bAb79W14@ZaiLjMtjn8 "Clean – Try It Online") A "binary" search, narrowing the search area to the upper or lower 99.6% of the range between the high and low bounds at each iteration instead of 50%. [Answer] # [Python 3](https://docs.python.org/3/) + sympy, 72 bytes ``` lambda y:float(sympy.poly("x**5+x+"+str(y)).all_roots()[0]) import sympy ``` [Try it online!](https://tio.run/##HcvBCoMwDADQu18hPSUtiEO8CH6JG6MyikJqQpuD@foKe/cnpgdfU0vru1HM@y/2tiTiqFAtiw3CZOBu7@dwBxeqFjDEIRJ9C7NWwG38YHdm4aL9/zQp56WQ4IXYHg "Python 3 – Try It Online") [Answer] # TI-Basic (TI-83), 12 bytes ``` solve(X^5+X+Ans,X,0 ``` # TI-Basic (TI-89), 13\* bytes ``` solve(x^5+x=-a,x)→f(a) ``` \*Not completely sure how to score ti-89 programs/functions [Answer] # [Scala](http://www.scala-lang.org/), 74 bytes Using Newton-Raphson with a fixed number of iterations, and the same approximation trick as [@Arnauld](https://codegolf.stackexchange.com/a/193399/18535) Golfed version. [Try it online!](https://tio.run/##NVBda8MwDHzPrzgKA3tNUntbaJLiwGCP29PYUxnFzZI2I184bucR8tszO2UIHTokTjoNuazlXDV9pzQGR8JG6nN48Lzu@F3kGm@yajF6wFdRorGESHUaUjwrJX/371pV7emTpvhoKw2BcXZzJZHpS3c51gUV41UqGCE30Y5w6A5JQsOyU4XMz@NBZCYQRG6IuV9izena0E007cw0263AVdao2v6iByv/Wg2aBJwxxlnIfCzAHQQLFqYnnProux/y4NqRJZxtH7dPPI7jkNFF86b3fwVGGIhs6QC9daTrlgyruzApEQQZXLFy0/Y3xPjWnqH0pjR5Lidv/gM) ``` def f(a:Double)={var x=a/5;(1 to 99).foreach{_=>x-=(a/(x*x*x*x+1)+x)/5};x} ``` Ungolfed version. [Try it online!](https://tio.run/##TVBdS8MwFH3PrzgMhETbmqhjbaEDwUd9Ep9ERlbbrdIv0kwjo7@9Jm3d9pCTe@49997D7VJZymEoqrZRGp1jQSX1PtgQ0my/slTjRRY1jgT4zHJUllCpdl2MR6Xk7/urVkW9@2Ax3upCIxmVwLcskcd4ag7bMkOyPkWQjk0iJ1MwY/IWyzlHBXSDKGJB3qhMpnscsbFNcxm2wU9AXQs1uMb53UAwC4ZdTOvn35CJndwVdXvQnd39XHSa@oJzLnjAPYwgHPgjZqalgnlomx9658pLSwRf3a8eRBiGAWfjzGnehWdz9tzaG@mypt3iKohy@P4aLlg4tb02NR5yahhj5N9yT3oyDH8) ``` import scala.math._ object Main { def main(args: Array[String]): Unit = { val f: Double => Double = a => { var x = a / 5 (1 to 99).foreach { _ => x -= (a / (x * x * x * x + 1) + x) / 5 } x } val inputs = List(-100010.0, 0.0, 1.0, -1.0, exp(1), pow(2, 0.5), 1073741888.0) inputs.foreach { x => println(s"%.9f --> %.9f".format(x, f(x))) } } } ``` ]
[Question] [ There are an abundance of questions involving drawing shapes using asterisks - so I thought, with so many asterisks out there, we should draw one, using the ASCII table. ## Challenge Your task is to write a program or function which takes no input, and outputs this exact text: ``` ! "# $% &' () *+ ,- ./ 01 23456789:;<=>?@ABCDEF GHIJKLMNOPQRSTUVWXYZ[ \]^_ `a bc de fg hi jk lm no pq rs tu vw xy z{ |} ~ ``` For reference, [this site](http://www.ascii-code.com/) lists the complete ASCII table. # Rules * The output should be the exact text, as shown above. Leading/trailing whitespace is allowed. * Standard golfing loopholes apply - no reading this ASCIIrisk from the internet, etc. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution (in bytes) wins. [Answer] # [Python 3](https://docs.python.org/3/), 110 bytes ``` s='%c';print(('\n'.join(['%10c%c']*9+[s*21]*2+[' '*(8-i)+s*2+' '*i+s*2for i in range(9)]))%(*range(32,128),)) ``` Generates the template ``` xx xx xx xx xx xx xx xx xx xxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxx xxxx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx ``` with `%c` for `x`, then uses string interpolation on `range(32,128)` to insert the ASCII values into the pattern. [Try it online!](https://tio.run/nexus/python3#JYlLDoIwEECvMptmPkVD6wZiPEntwhAw42IwhfuXEnbvU7cXugmf/6K2E@Hb8P5b1SihC/3UVpbRp01iyBJ9QkCh4absW/IITfXEZS2goAblY9@ZRs7MjuSyR@xCHLhjrvUA "Python 3 – TIO Nexus") Python 2 is one byte longer, with longer tuple unpacking but shorter `print`. ``` s='%c';print('\n'.join(['%10c%c']*9+[s*21]*2+[' '*(8-i)+s*2+' '*i+s*2for i in range(9)]))%tuple(range(32,128)) ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~54~~, 50 bytes ``` ¬ ~9ñ9É 11|á ñ2ñ20lá ñ$18é 9ñ^y|Ehé Pf xxywk$hP>ñd ``` [Try it online!](https://tio.run/nexus/v#@39ojUKd5eGNloc7FQwNaw4v5Dq80QiIDHLATBVDi8MrFYDycZU1rhmHV3IFpClUVFSWZ6tkBNgd3pjy/z8A "V – TIO Nexus") Unlike usual, this program does not contain any unprintable characters. Explanation: ``` ¬ ~ " Insert the entire printable ASCII range 9ñ ñ " 9 times: 9É " Insert 9 spaces at the beginning of this line 11| " Move to the 11'th column on this line á<CR> " And append a newline after the 11'th column ``` Now the buffer looks like this: ``` ! "# $% &' () *+ ,- ./ 01 23456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` Now we build up the middle: ``` 2ñ ñ " Two times: 20l " Move 20 characters to the right (because 'l' == 'right', duh) á<CR> " Append a newline ``` Here's where it gets a little weird. ``` $ " Move to the end of this line 18é " Insert 18 spaces before the last character 9ñ " Repeat the following 9 times: ^ " Move to the first non-whitespace character y| " Yank all the whitespace before the current character. " We'll call this the "Leading whitespace register" E " Move to the end of the current WORD (up to before a space) h " Move back one character é<CR> " And insert a newline before the current character P " Paste the leading whitespace for indentation f " Move forward to a space xx " Delete two characters " (Note how we are inbetween the two bottom branches right now) yw " Yank everything upto the next branch (all spaces) " We'll paste this on the line up so that we can yank it again later " To keep track of how far apart the branches are k$ " Move up a line and to the end of that line hP " Move back a character and paste the whitespace we yanked > " Indent this line by one space ñ " End the loop ``` Here's an important note. The `>` command is actually an *operator*, which means it doesn't do anything without an argument, the text to operate on. For example, ``` >_ "Indent the current line >> "Indent the current line >j "Indent the current and next line >G "Indent every line ``` But since this command is in a loop, we can save a character by not giving an operator. At the end of a loop, if any operator is pending it will fill in `_` (the current line) as an argument implicitly. Now I'll admit this loop is a little weird, and it can be hard to keep track of what all text should look like at any given moment. So you can use [this simpler program](https://tio.run/nexus/v#@39ojUKd5eGNloc7FQwNaw4v5Dq80QiIDHLATBVDi8MrFQ43HN4YV1njmnF4JVdAmkJFRWV5tkpGgN3////NAA) to see what it will look like after **N** loops. If you set it to 9, you can see that we have a little bit of extra text to get rid of. (Just the current line). So we delete the current line with `dd`. But wait! You know how I said that operators have to take an argument which is sometime implicitly filled in? Arguments are also implicitly filled at the end of the program. So rather than `dd` or `d_` (which are equivalent), we can simply to `d` and let V fill in the `_` for us. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~40~~ ~~38~~ ~~37~~ ~~36~~ 35 bytes ``` žQ2ô376S3*£`2ôvyN·ð×ýð«}rsJ2äsr)˜.c ``` [Try it online!](https://tio.run/nexus/05ab1e#ATIAzf//xb5RMsO0Mzc2UzMqwqNgMsO0dnlOwrfDsMOXw73DsMKrfXJzSjLDpHNyKcucLmP//w "05AB1E – TIO Nexus") **Explanation** ``` žQ # push the printable ascii chars 2ô # split into pairs 376S # split the number 376 into a list of digits 3* # multiply each by 3 to get [9,21,18] £ # divide the pairs of ascii chars into # pieces of these sizes ` # flatten list to stack 2ô # split the "legs" of the asterisk into pairs of pairs v # loop over the pairs of pairs yN·ð×ý # join the pairs by index*2 spaces ð« # append a space } # end loop rs # move the middle section to top of stack J2ä # convert to a string split into 2 pieces sr # rearrange the stack in the correct order )˜ # wrap in a flattened list .c # pad each element with spaces on either side ``` [Answer] # [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/index.html), 899 bytes ``` ill be honest with you i expect a big solitude i guess i had a guilt my own idea being:i was real alone,i was a lonely human also,i am still o,i guess i was expecting a shift i figured,surely i know i am tired of silence now i dreamed for a shift a magical desire cant come i am barely a man,so i guess i see why a woman i see ignores myself i know i am awful o,a night of passion and a moment of love i am truly the foolish person,every time i am saying i may recapture a love o,i think i can,i think i can i really do know i am unfit o,i notice a lot,i think i know i am unfit o,a novel,or perhaps poetry in code,i do enjoy the writing and i shudder and i wonder in a moment i was a weirdo,i was a freak,or like,i am creepy o,i think i was a misfit i know i am,really o,i ought not concern myself and sure,i am still some joyless man i focused and i tried a lasting solace and joy is nearby for me ``` [Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?ZVNbktwwCPz3KTiAT5DbMBa2yOjhEtI6Pv2msXc2s5UfVyGgaZq2pkQPoViLWKdDe6SzjklJ/uyydGJ66EZWk/YRBO/bEDNSihyQ3IamPuWT6lFIg6BctGy/lA42asKJOAF7vh@YPEgnxZG5TJysIsOZrGtKkwcvfC@/OQAPjRZ17Zi/6jaahNnwBZDSs9SDLpCuSFBdyTRJWWS6MwE0MhJrbd84TJk3XUAviKGNFi6dlpp9RUA9@EL3sjJbpX@8TISO6KmjIvn1olupTYzyaZLW6Z0VH@vw1ZiKbrE7v53NtBbi4hpmTC3Xe6ofX/N7Gxjfo4A1tLdIuzSrZZYPaUholhvd@HR9FERP6L3w3iHMJTSwXNAetTxRgA1/RpjkB8KcUN/4jrJqvzpL7brcWP2t9f9SrIZpaYbAoBl5N9qrdBDVAlGDnx8zpPyu91JHUz/r5AJAwDhCkEZ3dNTiATpf0kwv8xyiLdRvL62g//ShSZ9y@2hpIvv5Y@@7Nqs51zf28738VVuHXwb7gi2M08rrkE7JnfbmUvwMEB@bJDdEvnRc6zIMFrs36E0lwGKJ7TIv/h52HZF0AdSoCLfHeTkyy@fng8Nf) Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols. This poem is...depressing. 😟 [Answer] # [Python 3](https://docs.python.org/3/) ~~170~~ ~~165~~ ~~155~~ 147 bytes I've golfed this so much, I've forgotten how it works... ``` i=b=0 for x in range(32,127):a=x%2<1;c=x>90;d=x<50;print(end=[' '*9*d,['\n'+' '*(8-i),' '*~-i][b]][c]*a+chr(x)+'\n'*(x==70or d*x%2));b^=a;i+=b*c*a ``` [**Try it online!**](https://tio.run/nexus/python3#FY1LDsIgFAD3noKNAR40oTWmVvq8CGLCp1U2aIgLVl4d291MMsm0hB7VYX0XUknKpLj8XNhpkP0w8qvDehzmXgest0npiHU@K/0pKX/ZkiMaSihMEKWh90zFbuzSJS4p2fDXJWu8tSZYcCK8Cqtc7CGwijiq7RlhG3Cu/QOdTgI9BHCt/QE) [Answer] ## JavaScript (ES6), ~~156~~ … ~~115~~ 114 bytes Sadly, the infamous `String.fromCharCode()` costs 19 bytes. ``` f=(x=y=k=1)=>k<96?String.fromCharCode(x-22?y/2^5&&(y>9?x-y+1>>1&&22-y-x>>1:x/2^5)?32:31+k++:(x=!++y,10))+f(x+1):'' console.log(f()) ``` ### Formatted and commented ``` f = ( // given: x = // - x = current column y = // - y = current row k = 1 // - k = current ASCII character code, minus 31 ) => // k < 96 ? // if we havent't reached character #127 (96 + 31): String.fromCharCode( // let's compute the next character x - 22 ? // if x is not equal to 22 (end of line): y / 2 ^ 5 && ( // if y doesn't equal 10 or 11 (horizontal bar): y > 9 ? // and either y is greater than 9: x - y + 1 >> 1 && // and we are not located on one of the 22 - y - x >> 1 // bottom diagonals : // or y is less or equal to 9: x / 2 ^ 5 // and x doesn't equal 10 or 11 (vertical bar) ) ? // then: 32 // append a space : // else: 31 + k++ // append the next ASCII character : // else: (x = !++y, 10) // increment y, reset x and append a LineFeed ) + f(x + 1) // do a recursive call with x + 1 : // else: '' // stop recursion ``` [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~153~~ 151 bytes ``` [32,49,2|?space$(9)+chr$(a)+chr$(a+1)][2|X=Y[a,a+20|X=X+chr$(c)]a=a+21?X][0,8|X=space$(8-d)[0,1|X=X+chr$(a+e)]X=X+space$(d*2)[2,3|X=X+chr$(a+f)]a=a+f?X ``` It's really just a series of FOR-loops and casting an int to a character (`chr$()`). Sample output: ``` ! "# $% &' () *+ ,- ./ 01 23456789:;<=>?@ABCDEF GHIJKLMNOPQRSTUVWXYZ[ \]^_ `a bc de fg hi jk lm no pq rs tu vw xy z{ |} ~ ``` [Answer] # [Perl](https://www.perl.org/), 113 bytes 112 bytes of code + `-l` flag. ``` sub g{chr$c+++32}print$"x9,&g,&g for 0..8;print map&g,0..20for 0,1;print$"x-$_,&g,&g,$"x(16+2*$_),&g,&g for-8..0 ``` [Try it online!](https://tio.run/nexus/perl#U1YsSC3KUdDN@V9cmqSQXp2cUaSSrK2tbWxUW1CUmVeiolRhqaOWDkQKaflFCgZ6ehbWYAmF3MQCoDhQwMgALKNjaA3ToasSD9GjA@RoGJppG2mpxGsijNG10NMz@P8fAA "Perl – TIO Nexus") [Answer] # PHP, ~~110~~ ~~105~~ ~~103~~ ~~93~~ 91 bytes ``` for(;$c<95;$y+=!$x%=21)echo" "[$x],chr(31+($y%11<9&(max($y,10)-abs(9.5-$x++))%11<9?:++$c)); ``` prints a leading newline. Run with `-nr` or [test it online](https://tio.run/nexus/php#HcmxDkAwEADQ3V@QI3c5xBFDteJDxEBDughhqa8vMb48M5zuDNtxoQZrVKvh4T4Gn/a10GrdkUTJCH7KrbuwEUZ4UhGjMtxn/yGXiop5uVGVbQGemej/oWMGS6RDeAE). The basic principle is adopted from Arnauld, but this iterates. And it takes good advantage from PHP´s implicit typecasts: NULL to int for string index, float to int for `%`, boolean to int for `&` and for `+=`. **explanation with pseudo code** ``` If $x is 0, print a newline. ("\n"[$x] is newline for $x=0; empty for every larger $x) if $y is neither 9 nor 10 (not middle part: $y<9|$y>10 <=> $y%11<9) AND distance to center == abs(9.5-$x) (in [0.5,1.5,..,10.5]) -> lower part: abs($y-10-distance)>1 => ($y-distance)%11<9 (this works because $y is always <20) upper part: $x<9|$x>10 <=> distance>1 <=> 10-distance<9 => (10-distance)%11<9 (this works because % has negative results for negative first operands) both parts: $y>9?$y:10 <=> max($y,10) // $a?:$b evaluates to $a if $a is truthy, to $b else // and the ternary condition evaluates to 1 if the coords are not in the shape then print chr(31+1) = space else print chr(31+incremented $c) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 53 bytes ``` js.e@[+L*9;cb2c2b.e+*-8Ydj*yYdZcL2cb4)kcsrdC127,18 60 ``` A program that prints the result. [Try it online!](https://tio.run/nexus/pyth#@59VrJfqEK3to2VpnZxklGyUpJeqraVrEZmSpVUZmRKV7GOUnGSimZ1cXJTibGhkrmNooWBm8P8/AA "Pyth – TIO Nexus") **How it works** `srdC127` creates a list of the printable ASCII characters and concatenates this to a string. `c....,18 60` splits this string at indices `18` and `60`, giving a list of three strings corresponding to the different parts of the output: the top, the middle and the bottom. `.e` begins an enumerated map over the strings with the strings as `b` and their indices as `k`. `[...)` creates a list containing the desired action for each part of the diagram. The correct action is chosen by indexing into the list with the current index, using `@...k`. * *Top* `cb2` splits the string into pairs of characters, and `+L*9;` prepends `9` spaces to each pair. * *Middle* `c2b` splits the string into two equal-length strings. * *Bottom* `cL2cb4` splits the string into groups of four characters, and each group into pairs. `.e` begins an enumerated map, with the string pairs as `Z` and their indices as `Y`. `j*yYdZ` joins the pairs on `2*Y` spaces, and `+*-8Yd` prepends `8-Y` spaces. `js` merges all the results and joins the resulting list on newlines. This is then implicitly printed. [Answer] # [Haskell](https://www.haskell.org/), 144 bytes ``` b!n=[1..n]>>b ('*':r)#(a:s)=a:r#s (a:r)#s=a:r#s r#s=r p="**" f=unlines([" "!9++p]!9++["*"!21]!2++[" "!(8-n)++p++" "!(2*n)++p|n<-[0..8]])#[' '..] ``` [Try it online!](https://tio.run/nexus/haskell#LYnLCsMgFET3foWPhS8ijatUan6iS3FhoIFAexFNdv13a0IXM8yZ0xYCPozGQJznBQmuuCuSieSq9MkVVlHf/al/6vEFZU@Vomj1B7w3eFURKKbkrnWOZweqKLFjJPbc3YhpANmt1hdZddEXHkO4GTPFKFngmBsT2ydtgD3Ox/7cC17bDw "Haskell – TIO Nexus") **Explanation:** `b!n=[1..n]>>b` defines a function `!` which repeats a list or string `b` `n`-times. `unlines([" "!9++p]!9++["*"!21]!2++[" "!(8-n)++p++" "!(2*n)++p|n<-[0..8]])` uses this function to draw an asterisk of asterisks (Oh, the irony!): ``` ** ** ** ** ** ** ** ** ** ********************* ********************* **** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ``` `#` is defined as a function which consecutively replaces `*` in a string with chars from a given list. It's called with the above asterisk of asterisks and `[' '..]` which is an infinite list of all characters starting with the space `' '`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes (noncompeting) ``` GH↑χ→⁴↓χ→¹¹↓⁴←χ↘χ←⁴↖⁹←²↙⁹←⁴↗χ←⁹↑⁴→⁹ ↓¤γ ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9nuXv96x41DbxfPujtkmPGrc8apsMZh7aeWgnkA0WmQASmQEiJoD50x41AuUmHNr0qG0mhAkWng5VARSYCBYAmrdTAWjIoSXnNv///183EQA "Charcoal – Try It Online") AST provided for explanation, `χ` being the preinitialized variable for `10`. [Answer] # J, 63 ~~(not competing)~~ ``` a.{~32>.31+20 21$(* +/\),(9 21&$@{.,1:,1:,}.)(+.1&|."1)|.=|i:10 ``` the expression evaluates right to left thus: * `i: 10` counts from -10 to +10 * `|` take abs to get +10 to 0 back to +10 * `=` self classify to get V shape of 1's in a block of 0's * `|.` reverse row order to get /\ shape * `( +. 1&|."1 )` hook expression shifts each row right by one and OR's with original * `( 9 21&$@{. , 1: , 1: , }. )` nested forks to put in horizontals and stretch top * `,` to raze the block into a linear sequence for cumulation * `( * +/\ )` cumulate and multiply with self * `20 21 $` revert shape to a block 20 rows of 21 elements * `31 +` add 31 because first 1 should be a space char code 32 * `32 >.` floor at 32 * `a. {~` pick chars from ascii built-in [Answer] # Ruby, 91 bytes ``` ->{(-11..8).map{|i|["%s"*21,"%#{9-i}s%s%#{i*2+1}s%s","%10s%s"][i/2<=>-1]}*$/%[*' '..?~,$/]} ``` **Ungolfed** ``` ->{(-11..8).map{|i| #For each line ["%s"*21, #If i/2==-1 make a format string of 21 %s "%#{9-i}s%s%#{i*2+1}s%s", #If i/2>-1 make a format string %{9-i}s%s%{i*2+1}s%s "%10s%s"][i/2<=>-1] #If i/2<-1 make a format string %10s%s }*$/% #Join the format strings with newlines $/ then use sprintf operator % [*' '..?~,$/] #to replace the %s with *' '..'~' and a newline for last corner. } ``` [Answer] I missed an answer in C# so... # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 175 174 bytes ``` _=>{var r="";for(int i=0,j,d=32,s=1;i<54;i++)for(j=0;j++<"*#4#4#4#4#4#4#4#4#+K)%1###/#%#-#'#+#)#)#+#'#-#%#/###1#"[i]-33;)r+=(char)(i%2<1?32:d++)+(s++%21<1?"\n":"");return r;} ``` [Try it online!](https://tio.run/##bU9BasMwELz7FULCVKrsJLbTS2Slh0IvpVDooYc2BCHbqUwiwUoJlOC3u3IKKZTOwO4yM8uy2ufaQTuiCL1X3qMXcDtQh2RSzpc6wQcVjEYnZxr0rIyl7Gr9hia8fvnQHmaPR6trH8DYXYZ@@hp1SCbjVq7PJwUIJMaic0CNDcjIRdZnjazKzMtCmPpuKQznbPJ7uRA95zW@Jcs/5E8sLQghc5KSnNwQTlgkj1MelXl0CoLfzSavKsGAS6o/FTBq0rIu7qty1cQTnHrO07KICv6weIUxE9CGI1gEYhhF8t97D856t29nb2BCSzsal5i4BofLNIzf "C# (.NET Core) – Try It Online") * 1 byte saved thanks to Kevin Cruijssen! [Answer] # [Tcl](http://tcl.tk/), 209 bytes ``` proc I {} {incr ::i} proc A {} {time {append a [$::F %c [I]]} 21;puts $a} set i 31 time {puts [[set F format] %10c%c [I] [I]]} 9 A A time {puts [$F %[expr 32-[I]/4]c%c $i [I]][$F %[expr $i/2-45]c%c [I] [I]]} 9 ``` [Try it online!](https://tio.run/##XYyxCoMwFEX3fMUd4ijWaIemk4vgN4QMIU0hUDXEFAqSb081dpDytvPuOUG/UnJ@1hiwRqx20h6c20gy7DIMdjRYlXNmekBBUM57FBpikDKC1Xf3DguoimQxARZNTQ4lcyF22uM5@1EFiaK@6EP@BW6k2@5s0C0vzMd5NKzcRlUrd4XabJze1FasbK/yL5jSFw "Tcl – Try It Online") --- # [Tcl](http://tcl.tk/), 212 bytes ``` proc I {} {incr ::i} proc A {} {time {append a [$::F %c [I]]} 21;puts $a} set i 31 time {puts [[set F format] %10c%c [I] [I]]} 9 A A time {puts [$F %[expr (129-[I])/4]c%c $i [I]][$F %[expr $i/2-45]c%c [I] [I]]} 9 ``` [Try it online!](https://tio.run/##XYwxCoMwAEX3nOIPEdpBbKwdTCcXwTOEDCFNIVA1xBQK4tlTjR2k/O3x3wv6FaPzo0aHecFsB@3BuV1Igk2CwfYGs3LODA8oCMp5i0xDdFIuKNndvcMEqhYymQCLKyO7krgQG23xHH2vgkTGLnqXf4GaNOuOBl3zwnycx4mVdb7ezkUlN4vaJB0e1BZlXt3kXzPGLw "Tcl – Try It Online") ## # tcl, 213 ``` proc I {} {incr ::i} set F format proc A {} {time {append a [$::F %c [I]]} 21;puts $a} set i 31 time {puts [$F %10c%c [I] [I]]} 9 A A time {puts [$F %[expr (129-[I])/4]c%c $i [I]][$F %[expr $i/2-45]c%c [I] [I]]} 9 ``` [demo](http://rextester.com/LFEB11678) --- # tcl, 214 ``` proc I {} {incr ::i} set F format proc A {} {time {append a [$::F %c [I]]} 21;puts $a} set i 31 time {puts [$F %10c%c [I] [I]]} 9 A A time {I;puts [$F %[expr (129-$i)/4]c%c $i [I]][$F %[expr $i/2-45]c%c [I] [I]]} 9 ``` # [demo](http://rextester.com/JEMW16013) --- # tcl, 227 ``` proc I {} {incr ::i} set F format proc A {} {time {append ::a [$::F %c [I]]} 21} set i 31 time {puts [$F %10c%c [I] [I]]} 9 A set a $a\n A puts $a time {I;puts [$F %[expr (129-$i)/4]c%c $i [I]][$F %[expr $i/2-45]c%c [I] [I]]} 9 ``` # [demo](http://rextester.com/JBUH59594) ## # tcl, 236 ``` proc I {} {incr ::i} set F format proc A {} {time {append ::a [$::F %c [I]]} 21} set i 31 time {puts [$F %10c%c [I] [I]]} 9 set a "" A set a $a\n A puts $a time {I;puts [$F %[expr (129-$i)/4]c%c $i [I]][$F %[expr $i/2-45]c%c [I] [I]]} 9 ``` # [demo](http://rextester.com/GPUF93611) --- # tcl, 237 ``` proc I {} {incr ::i} set F format proc A {} {time {set ::a $::a[$::F %c [I]]} 21} set i 31 time {puts [$F %10c%c [I] [I]]} 9 set a "" A set a $a\n A puts $a time {I;puts [$F %[expr (129-$i)/4]c%c $i [I]][$F %[expr $i/2-45]c%c [I] [I]]} 9 ``` # [demo](http://rextester.com/OMYQ85419) --- # Alternative approach with same size: ``` proc I {} {incr ::i} set F format proc A b {time {upvar $b c;set c $c[$::F %c [I]]} 21} set i 31 time {puts [$F %10c%c [I] [I]]} 9 set a "" A a set a $a\n A a puts $a time {I;puts [$F %[expr (129-$i)/4]c%c $i [I]][$F %[expr $i/2-45]c%c [I] [I]]} 9 ``` # [demo](http://rextester.com/IOBOX27151) ## # Tcl, 288 ``` lassign {set while puts format incr expr} S W P F I E $S i 31 $W \$i<48 {$P [$F %10c%c [$I i] [$I i]]} $S a "" $W {[$I i]<71} {$S a $a[$F %c $i]} $S a $a\n $W \$i<92 {$S a $a[$F %c $i];$I i} $P $a $W \$i<128 {$P [$F %[$E (129-$i)/4]c%c $i [$I i]][$F %[$E $i/2-45]c%c [$I i] [$I i]]; $I i} ``` [demo](http://rextester.com/LCYE76159) --- # tcl, 297 bytes (naïve attempt) ``` set i 31 while \$i<48 {puts [format %10c%c [incr i] [incr i]]} set a "" while {[incr i]<71} {set a $a[format %c $i]} set a $a\n while \$i<92 {set a $a[format %c $i];incr i} puts $a while \$i<128 {puts [format %[expr (129-$i)/4]c%c $i [incr i]][format %[expr $i/2-45]c%c [incr i] [incr i]]; incr i} ``` [demo](http://rextester.com/OBDN21372) [Answer] # [Stax](https://github.com/tomtheisen/stax), 33 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ¬♣╘╣Ye╗}Ω╩Ñ╬↓ï|§≈b↕£♠╨z▐₧3→ÿ≡Δ:╔♫ ``` [Run and debug it](https://staxlang.xyz/#p=aa05d4b95965bb7deacaa5ce198b7c15f762129c06d07ade9e331a98f0ff3ac90e&i=) Uses a similar idea to the 05AB1E answer. [Answer] # Python 2.7, ~~194~~ 188 bytes ``` k,l,c,s,r=8,0,chr,' ',range;o=''.join(map(chr,r(32,127))) for i in r(0,18,2):print s*9+o[i:i+2] print o[18:39]+'\n'+o[39:60] for i in r(60,95,4):print s*k+o[i:i+2]+s*l+o[i+2:i+4];k-=1;l+=2 ``` [Answer] # [Jq 1.5](https://stedolan.github.io/jq/), 180 bytes ``` foreach((range(9)|[9,2]),(range(2)|[0,21]),(range(9)|[8-.,2,.+.,2]))as$r({s:[range(32;127)]|implode};.r=$r|.p=""|until(.r==[];.p+=" "*.r[0]+.s[:.r[1]]|.s =.s[.r[1]:]|.r=.r[2:]);.p) ``` Expanded ``` foreach ( # instruction sequence: [indent, count] (range(9)|[9,2]), # 9 rows of 2 characters indented 9 spaces (range(2)|[0,21]), # 2 rows of 21 characters (range(9)|[8-.,2,.+.,2]) # 9 rows of 4 characters with varying indent ) as $r ( {s:[range(32;127)]|implode} # state = ascii string ; .r = $r # current instruction | .p = "" # print string for this row | until(.r==[]; # until current instruction is exhausted .p += " "*.r[0] + .s[:.r[1]] # add to print string | .s = .s[.r[1]:] # remove from state | .r = .r[2:] # remove from instruction ) ; .p # emit print string ) ``` [Try it online!](https://tio.run/##RYtBDoIwFAWvQoiLVtofqAsF0pM0XRBFxWBbW4gL69WtHzVx92Yy73JL6Wh93@3PhPjOnHpS06hqJjRlPyFQlExUf7MkOw5MMChgSWkXVp48QqO@wUa0ldhSHYerG@2hf7bg5cpHcDLP42ymYSRopNItuELmWb4Gr0pdQFANrkrrCCGTiB9qEL3EKRpN8UJTelk3DdaExLmZx5EPxs0Tgu/u3M4Twhs "jq – Try It Online") [Answer] # Slashes ([///](https://esolangs.org/wiki////)), 324 bytes ``` ! "# $% &' () *+ ,- .\/ 01 23456789:;<=>?@ABCDEF GHIJKLMNOPQRSTUVWXYZ[ \\]^_ `a bc de fg hi jk lm no pq rs tu vw xy z{ |} ~ ``` The first (default) action in Slashes is 'print', so the string is printed. The `/` and `\` must be escaped by proceeding `\`s. [Answer] # Java 8, ~~176~~ ~~173~~ 172 bytes ``` v->{for(char i=54,j,d=32,s=1;i-->0;)for(j=0;j++<"#1###/#%#-#'#+#)#)#+#'#-#%#/###1%)K+#4#4#4#4#4#4#4#4#*".charAt(i)-33;)System.out.print((i%2<1?d++:32)+(s++%21<1?"\n":""));} ``` Port of [*@Charlie*'s C# .NET answer](https://codegolf.stackexchange.com/a/128012/52210), so make sure to upvote him. -4 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##XZDBboMwDIbvfQqLCC1ZgDbQXRrYtPO0Xir1su2QBdjCaKhIQJoqnp2Zrafpl@Lktxz7c6NGFTfl16xb5Rw8K2MvKwBjfdXXSlewX54AY2dK0PS4hJFJ9KYVHs4rbzTswUIB8xjfX@qup1gNpthETVQWWRq5QkiT322l4Zwt@abYyIbzPLgl23/iTywUhJA1CUlMbggnDMXxFqOzxowgQaI/Vf/oqWFxlkl2@Ha@OiXd4JNzj71r6jgPU5GLhyDUrzbYYQgiE6boZOmuxDHkNMsF4Dy8twhw5filPOEO6MHjTx8vb6DY3wJsoqkd2vbKPs0/) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~119~~ 117 bytes -2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) ``` f(c){for(c=0;c<95;c++)printf("%*c%s",c&1?:c<18?10:c<60?:c&2?c/2-30:24-c/4,c+32,c&c<18|c==38|c>58&!(c-63&3)?"\n":"");} ``` [Try it online!](https://tio.run/##FYpBDoIwFAXXcgt/QtNaGkoLBCnYi7gxL6lhYTXoDjl7rZuZTDJQdyClwCG28Fw5Zu0wnTsHKcVrXeIncCpPKN9UgTV@xNQMvtHZvc7FjEdtlNWjaRXqtoK0Jp//7Yt5tpmXbmBHDtVbZoWna6SRSLg9PW5L5KLYikPgwhV7@gE "C (gcc) – Try It Online") ]
[Question] [ Given a vector of \$n\$ values \$(x\_1,x\_2,x\_3,\ldots,x\_n)\$ return the determinant of the corresponding [Vandermonde matrix](https://en.wikipedia.org/wiki/Vandermonde_matrix) \$V(x\_1, x\_2, \ldots, x\_n) = \begin{bmatrix}1 & x\_1 & x\_1^2 & x\_1^3 & \ldots &x\_1^{n-1} \\1 & x\_2 & x\_2^2 & x\_2^3 & \ldots &x\_2^{n-1} \\ \vdots & & & \vdots & & \vdots \\ 1 & x\_n & x\_n^2 & x\_n^3 & \ldots & x\_n^{n-1}\end{bmatrix}\$. This determinant can be written as: \$\det V(x\_1, x\_2, \ldots x\_n) = \prod\_\limits{1 \leqslant i < j \leqslant n} (x\_j - x\_i)\$ ### Details Your program/function has to accept a list of floating point numbers in any convenient format that allows for a variable length, and output the specified determinant. You can assume that the input as well as the output is within the range of the values your language supports. If you language does not support floating point numbers, you may assume integers. ### Some test cases Note that whenever there are two equal entries, the determinant will be `0` as there are two equal rows in the corresponding Vandermonde matrix. Thanks to @randomra for pointing out this missing testcase. ``` [1,2,2,3] 0 [-13513] 1 [1,2] 1 [2,1] -1 [1,2,3] 2 [3,2,1] -2 [1,2,3,4] 12 [1,2,3,4,5] 288 [1,2,4] 6 [1,2,4,8] 1008 [1,2,4,8,16] 20321280 [0, .1, .2,...,1] 6.6586e-028 [1, .5, .25, .125] 0.00384521 [.25, .5, 1, 2, 4] 19.3798828 ``` [Answer] # Jelly, 5 bytes ``` œc2IP ``` `œc2` gets all combinations without replacement of length 2. `I` computes the difference list of each of those pairs, yielding a list like `[[1], [2], [3], ..., [1]]`. We take the `P`roduct. [Try it here!](https://tio.run/##y0rNyan8///o5GQjz4D///9H6xmZ6uiZ6hjqGOmYxAIA) --- In modern Jelly, `Œc` works as a short form of `œc2`, so `ŒcIP` is a 4-byte solution. [Answer] # Mathematica, 30 bytes ``` 1##&@@(#2-#&@@@#~Subsets~{2})& ``` This is an anonymous function. Expanded by Mathematica, it is equivalent to `(1 ##1 & ) @@ Apply[#2 - #1 & , Subsets[#1, {2}], {1}] &`. `1##&` is an equivalent for `Times` (thanks tips page), which is applied to each distinct pair of elements from the input list, generated by `Subsets[list, {2}]`. Note that `Subsets` does not check for uniqueness of elements. [Answer] # Ruby, ~~49~~ 47 bytes ``` ->x{eval(x.combination(2).map{|a,b|b-a}*?*)||1} ``` This is a lambda function that accepts a real valued, one-dimensional array and returns a float or an integer depending on the type of the input. To call it, assign it to a variable then do `f.call(input)`. We get all combinations of size 2 using `.combination(2)` and get the differences for each pair using `.map {|a, b| b - a}`. We join the resulting array into a string separated by `*`, then `eval` this, which returns the product. If the input has length 1, this will be `nil`, which is falsey in Ruby, so we can just `||1` at the end to return 1 in this situation. Note that this still works when the product is 0 because for whatever reason 0 is truthy in Ruby. [Verify all test cases online](https://repl.it/BtEQ/1) Saved 2 bytes thanks to Doorknob! [Answer] ## J, 13 bytes ``` -/ .*@(^/i.)# ``` This is a monadic function that takes in an array and returns a number. Use it like this: ``` f =: -/ .*@(^/i.)# f 1 2 4 6 ``` ## Explanation I explicitly construct the Vandermonde matrix associated with the input array, and then compute its determinant. ``` -/ .*@(^/i.)# Denote input by y # Length of y, say n i. Range from 0 to n - 1 ^/ Direct product of y with the above range using ^ (power) This gives the Vandermonde matrix 1 y0 y0^2 ... y0^(n-1) 1 y1 y1^2 ... y1^(n-1) ... 1 y(n-1) y(n-1)^2 ... y(n-1)^(n-1) -/ .* Evaluate the determinant of this matrix ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 9 ``` !G-qZRQpp ``` [**Try it online!**](http://matl.tryitonline.net/#code=IUctcVpSUXBw&input=WzEsMiw0LDgsMTZd) This computes a matrix of all differences and then keeps only the part below the main diagonal, making the other entries `1` so they won't affect the product. The lower triangular function makes the unwanted elements `0`, not `1`. So we subtract `1`, take the lower triangular part, and add `1` back. Then we can take the product of all entries. ``` t % take input. Transpose G % push input again - % subtract with broadccast: matrix of all pairwise differences q % subtract 1 ZR % make zero all values on the diagonal and above Q % add 1 p % product of all columns p % product of all those products ``` [Answer] ## Pyth, ~~15~~ ~~13~~ ~~12~~ 11 bytes ``` *F+1-M.c_Q2 ``` ``` Q take input (in format [1,2,3,...]) _ reverse the array: later we will be subtracting, and we want to subtract earlier elements from later elements .c 2 combinations of length 2: this gets the correct pairs -M map a[0] - a[1] over each subarray +1 prepend a 1 to the array: this does not change the following result, but prevents an error on empty array *F fold over multiply (multiply all numbers in array) ``` Thanks to [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625) and [@Pietu1998](https://codegolf.stackexchange.com/users/30164/pietu1998) for a byte each! [Answer] # Mathematica, 32 bytes ``` Det@Table[#^j,{j,0,Length@#-1}]& ``` I was surprised not to find a builtin for Vandermonde stuff. Probably because it's so easy to do it oneself. This one explicitly constructs the transpose of a VM and takes its determinant (which is of course the same as the original's). This method turned out to be significantly shorter than using any formula I know of. [Answer] ## Haskell, 34 bytes ``` f(h:t)=f t*product[x-h|x<-t] f _=1 ``` A recursive solution. When a new element `h` is prepended to the front, the expression is multiplied by the product of `x-h` for each element `x` of the list. Thanks to Zgarb for 1 byte. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 19 bytes ``` {×/-∊(⍳≢⍵)↓¨↓∘.-⍨⍵} ``` Dfn producing the pairs, then taking the product. `↓∘.-⍨⍵` all pairs (with repeats) `(⍳≢⍵)` range from 1 to the length of the input `↓¨` drop 1 2 3 4... elements to avoid repeats `-∊` flatten and negate `×/` take the product [Try it online!](https://tio.run/##TYw9CsJAFIT7nGJKLfJ0dxP/bhPNRsHFiEZUxFaiEBAstLGxsrMQL6A3eReJq1GUxxu@GZgJhsYN54GJu66eJXoQ6jDPI15tF499xeV0U@LsyusTZ7cyr3b3sxVOD@RydrbZMnfyCALSnnI4OyLC/SKULxSm8ag/hok7gTFztCcJBnGCnh5ptErOu2VVQhRs@xHUv4f3I/gf/mYeGj@CqFlTBQmQBCmQB/JBNVAd1AA1P6uvUNoX8rX3Rr8YeQI "APL (Dyalog Extended) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~12 9~~ 8 bytes ``` ΠṁhṠzM-ḣ ``` [Try it online!](https://tio.run/##ASMA3P9odXNr///OoOG5gWjhuaB6TS3huKP///9bMSwyLDMsNCw1XQ "Husk – Try It Online") (Apparently the only one of the three which was correct) -3 bytes by calculating difference instead of pairs. -1 from Jo King ## Explanation ``` ΠṁhṠzM-ḣ Ṡz zip the input with ḣ prefixes M- subtract the input from each ṁh remove first element of each, join Π product ``` [Answer] # Matlab, 26 bytes (noncompeting) Straightforward use of builtins. Note that (once again) Matlab's `vander` creates Vandermonde matrices but with the order of the rows flipped. ``` @(v)det(fliplr(vander(v))) ``` [Answer] # Perl, 38 ~~41~~ bytes Include +1 for `-p` Give the numbers on a line on STDIN. So e.g. run as ``` perl -p vandermonde.pl <<< "1 2 4 8" ``` Use an evil regex to get the double loop: `vandermonde.pl`: ``` $n=1;/(^| ).* (??{$n*=$'-$&;A})/;*_=n ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 35 bytes ``` a->matdet(matrix(#a,,i,j,a[i]^j--)) ``` [Try it online!](https://tio.run/##TYxBCsIwEEWvEuomgZ/BJI3Whb1IqTCglRSVULrQ09ektVKGYd77DD/yEPQ9Tp04T6zrJ4/X2yjTGcJb7hgI6MFNaC@91kpNHOPjI1noWsQhvMaERZZCdJKVgmgaA5vGtYm1cd7MlMJ8LMzPlgeHbYJyg/Cr/NMS1QZhDtn2IAOyIAcqQR50AB1BFei0dufUpjV2Lp3ZY@lu1fQF "Pari/GP – Try It Online") [Answer] ## Rust, 86 bytes ``` |a:Vec<f32>|(0..a.len()).flat_map(|x|(x+1..a.len()).map(move|y|y-x)).fold(1,|a,b|a*b); ``` Rust, verbose as usual... Explanation will come later (it's pretty straightforward, though). [Answer] ## Haskell, 53 bytes ``` f x=product[x!!j-x!!i|j<-[1..length x-1],i<-[0..j-1]] ``` Usage example: `f [1,2,4,8,16]` -> `20321280`. Go through the indices `j` and `i` in a nested loop and make a list of the differences of the elements at position `j` and `i`. Make the product of all elements in the list. Other variants that turned out to be slightly longer: `f x=product[last l-i|l<-scanl1(++)$pure<$>x,i<-init l]`, 54 bytes `import Data.List;f i=product[y-x|[x,y]<-subsequences i]`, 55 bytes [Answer] ## CJam, 16 bytes ``` 1l~{)1$f-@+:*\}h ``` In response to [A Simmons' post](https://codegolf.stackexchange.com/a/74972/21487), despite CJam's lack of a combinations operator, yes it is possible to do better :) -1 byte thanks to @MartinBüttner. [Try it online](http://cjam.aditsu.net/#code=1l~%7B%291%24f-%40%2B%3A*%5C%7Dh&input=%5B1%202%203%204%205%5D) | [Test suite](http://cjam.aditsu.net/#code=e%23%20Executes%20the%20program%2014%20times%20for%2014%20test%20cases%2C%0Ae%23%20printing%20the%20result%20after%20each%0A%0A14%7B%0A%0A1l~%7B%291%24f-%40%2B%3A*%5C%7Dh%0A%0A%5DoNo%7D*&input=%5B-13513%5D%0A%5B1%202%5D%0A%5B2%201%5D%0A%5B1%202%203%5D%0A%5B3%202%201%5D%0A%5B1%202%203%204%5D%0A%5B1%202%203%204%205%5D%0A%5B1%202%204%5D%0A%5B1%202%204%208%5D%0A%5B1%202%204%208%2016%5D%0A%5B0%20.1%20.2%20.3%20.4%20.5%20.6%20.7%20.8%20.9%201%5D%0A%5B1%20.5%20.25%20.125%5D%0A%5B.25%20.5%201%202%204%5D%0A%5B1%202%202%203%5D) ``` 1 Push 1 to kick off product l~ Read and evaluate input V { }h Do-while loop until V is empty ) Pop last element of V 1$ Copy the prefix f- Element-wise subtract each from the popped element @+ Add the current product to the resulting array :* Take product to produce new product \ Swap, putting V back on top ``` [Answer] ## JavaScript (ES6), 61 bytes ``` a=>a.reduce((p,x,i)=>a.slice(0,i).reduce((p,y)=>p*(x-y),p),1) ``` I tried an array comprehension (Firefox 30-57) and it was 5 bytes longer: ``` a=>[for(i of a.keys(p=1))for(j of Array(i).keys())p*=a[i]-a[j]]&&p ``` The boring nested loop is probably shorter though. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` η-€¨˜P ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3HbdR01rDq04PSfg//9oQx0jHWMdEx3TWAA "05AB1E – Try It Online") **Commented**: ``` η # prefixes of the input - # subtract those from the input € # for each sublist: ¨ # remove the last element (i=j) ˜ # flatten the list P # take the product ``` There are a few alternatives at the same length, such as [`ηõš-˜P`](https://tio.run/##yy9OTMpM/f//3PbDW48u1D09J@D//2hDHSMdYx0THdNYAA). [Answer] # [Desmos](https://www.desmos.com/calculator), 10+39=49 bytes ``` n=a.length \prod_{i=1}^n\prod_{j=i+1}^n(a[j]-a[i]) ``` [View it in Desmos](https://www.desmos.com/calculator/byvx36hbva) There's not a lot to be golfed here other than "caching" `a.length` in an array, but I would like to point out that Desmos can handle the `...` notation in arrays! [Answer] # [Japt](https://github.com/ETHproductions/japt) v1.4.5, 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` à2 ®rnÃ× ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.5&code=4DIgrnJuw9c&input=WwpbMSwyLDIsM10KWy0xMzUxM10KWzEsMl0KWzIsMV0KWzEsMiwzXQpbMywyLDFdClsxLDIsMyw0XQpbMSwyLDMsNCw1XQpbMSwyLDRdClsxLDIsNCw4XQpbMSwyLDQsOCwxNl0KWzAsLjEsLjIsLjMsLjQsLjUsLjYsLjcsLjgsLjksMV0KWzEsLjUsLjI1LC4xMjVdClsuMjUsLjUsMSwyLDRdCl0tbVI) (includes all test cases) ``` à2 ®raÃ× :Implicit input of array à2 :Combinations of length 2 (using v1.4.5 avoids a bug here in later versions) ® :Map r : Reduce by n : Inverse subtraction à :End map × :Reduce by multiplication ``` [Answer] # [Python 3](https://docs.python.org/3/), 91 bytes (does NOT work yet) ``` lambda x:eval("*".join([str(b-a) for a,b in combinations(x,2)]))or 1 from itertools import* ``` [Try it online!](https://tio.run/##DcsxDgIhEEDR3lNMtoINkixqY@JJVotBlzgGGAITs54eKX718stP3pxPPdzuPWLyL4T9un0xqmme7Icpq7VJVf6IGgJXQOOBMjw5ecooxLmp3Tj90HrocgiVE5BsVZhjA0qFq8y9VMqiglqtuxiwo8WAM3AeX@9/ "Python 3 – Try It Online") Port of [Alex A.](https://codegolf.stackexchange.com/a/74795/109916)'s answer. Fixing currently. [Answer] # [Factor](https://factorcode.org) + `math.matrices math.matrices.laplace`, 45 bytes ``` [ dup length vandermonde-matrix determinant ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZYwxCsJAFER7TzEXyILBgOgBxMZG0igWn90fE9xs1s2PKOJJbNKYO-U2Lqa0ecMMzHsPBWlpQj8e8v12t1nhwsGxRcvXjp3mFjVJqSJC9deUJW9JM3xgkYcPlROsZ0-oNIPKMEeKBV6fTopkOSZHmM7DsjtLiRs5w6FuIpOf7w7DEpfKUbScptOgyVqoqfT9lF8) [Answer] # CJam, 32 bytes ``` 1q~La\{1$f++}/{,2=},{~-}%~]La-:* ``` I'm sure someone can golf this better in CJam... The main issue is that I can't see a good way of getting the subsets so that uses up most of my bytes. This generates the power set (using an idea by Martin Büttner) and then selects the length-2 elements. [Answer] # [R](https://www.r-project.org/), 41 bytes ``` function(v)det(outer(v,1:sum(v|1)-1,"^")) ``` [Try it online!](https://tio.run/##K/ofpmCj@z@tNC@5JDM/T6NMMyW1RCO/tCS1SKNMx9CquDRXo6zGUFPXUEcpTklT83@YRrKGoY4REBpranKFaegaGpsaGoNYxamFGgY6hjpJlbYGeoZgSaM4DV0jKyOgNgA "R – Try It Online") I was surprised not to see an R answer here! [Answer] # [Perl 5](https://www.perl.org/) `-pa`, 36 bytes ``` $\=1;map$\*=$q-$_,@F while$q=pop@F}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lxtbQOjexQCVGy1alUFclXsfBTaE8IzMnVaXQtiC/wMGttvr/f0MFIwUTBYt/@QUlmfl5xf91CxIB "Perl 5 – Try It Online") [Answer] # [Arn](https://github.com/ZippyMagician/Arn), [27 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn) ``` ùW®š¡'‡ùHÓáâ§○iò;êñ⁺bì&B"$7 ``` [Try it!](https://zippymagician.github.io/Arn?code=Knsqdnt2LTp7fVwue31cW18gX3sue30tPi0tKCg6cykj&input=MC4yNSAwLjUgMSAyIDQ=) # Explained Unpacked: `*{*v{v-:{}\.{}\[_ _{.{}->--((:s)#` ``` * ... \ % Fold with multiplication after mapping { % Begin block * ... \ v{ % Block with key of `v` v % Variable with identifier `v` - % Minus _ % Variable intialized to STDIN; implied :{ % Head } % End block _ % Implied .{ % Beheaded } [ % Begin sequence _ % Entry equal to STDIN _{ % Block with key of `_` (needed otherwise the first `_` will be grabbed) _ % Last entry; implied .{ % Beheaded } -> % Of length -- % Reduced by one ( % Begin expression ( _ % Implied :s % Split on spaces ) % End expression # % Length ) % Implied ] % End of sequence; implied ``` Had to fix a few major bugs I only found because of this challenge! Also made me consider adding a few quality of life features (including an upgrade to precedence and `#` automatically casting to a vector). Speaking of bugs, I am 100% certain this works on the downloadable version, and it should be working on the online version very soon. ]
[Question] [ ## Background I have a ladder leaning on a wall, and a remote-controlled robot that can climb it. I can send three different commands to the robot: * `UP`: the robot takes one step upwards. If it was on the highest step, it trips over, falls down and explodes. * `DOWN`: the robot takes one step downwards. If it was on the lowest step, nothing happens. * `RESET`: the robot returns to the lowest step. I can also send a series of commands, and the robot will execute them one by one. Your task is to predict its movements. ## Input Your inputs are a positive integer `N`, representing the number of steps in the ladder, and a non-empty string `C` over `UDR`, representing the commands I have sent to the robot. You can assume that `N < 1000`. The robot is initialized on the lowest step of the ladder. ## Output It is guaranteed that at some point, the robot will climb over the highest step and explode. Your output is the number of commands it executes before this happens. ## Example Consider the inputs `N = 4` and `C = "UDDUURUUUUUUUDDDD"` The robot, denoted by `@`, moves along the 4-step ladder as follows: ``` |-| |-| |-| |-| |-| |-| |-| |-| |-| |@| |-|| |-| |-| |-| |-| |-| |@| |-| |-| |@| |-| |-|| |-| |@| |-| |-| |@| |-| |-| |@| |-| |-| |-|v |@| U |-| D |@| D |@| U |-| U |-| R |@| U |-| U |-| U |-| U |-|# Boom! ``` The remaining commands are not executed, since the robot has exploded. The explosion took place after 10 commands, so the correct output is `10`. ## Rules and scoring You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. ## Test cases ``` 1 U -> 1 1 DDRUDUU -> 4 4 UDDUUUUURUUUUDDDD -> 7 4 UDDUURUUUUUUUDDDD -> 10 6 UUUUUDRUDDDDRDUUUUUUDRUUUUUUUDR -> 20 10 UUUUUURUUUUUUURUUUUUUUURUUUUUUUUUUUUUU -> 34 6 UUUDUUUUDDDDDDDDDDDDDDRRRRRRRRRRRUUUUUU -> 8 6 UUUDUUUDURUDDDUUUUUDDRUUUUDDUUUUURRUUDDUUUUUUUU -> 32 20 UUDDUDUUUDDUUDUDUUUDUDDUUUUUDUDUUDUUUUUUDUUDUDUDUUUUUDUUUDUDUUUUUUDUDUDUDUDUUUUUUUUUDUDUUDUDUUUUU -> 56 354 UUDDUUDUDUUDDUDUUUUDDDUDUUDUDUDUDDUUUUDUDUUDUDUUUDUDUDUUDUUUDUUUUUDUUDUDUUDUDUUUUUDUDUUDUDUDUDDUUUUUUUDUDUDUDUUUUUDUDUDUDUDUDUDUDUUDUUUUUURUUUDUUUUDDUUDUDUDURURURUDUDUUUUDUUUUUUDUDUDUDUDUUUUUUDUDUUUUUUUDUUUDUUDUDUDUUDUDUDUUUUUUUUUUDUUUDUDUUDUUDUUUDUUUUUUUUUUUUUDUUDUUDUDUDUUUDUDUUUUUUUDUUUDUUUDUUDUUDDUUUUUUUUDUDUDUDUDUUUUDUDUUUUUUUUDDUUDDUUDUUDUUDUDUDUDUUUUUUUUUDUUDUUDUUUDUUDUUUUUUUUUUUDUDUDUDUUUUUUUUUUUUDUUUDUUDUDDUUDUDUDUUUUUUUUUUUUDUDUDUUDUUUDUUUUUUUDUUUUUUUUUDUDUDUDUDUUUUUUDUDUDUUDUDUDUDUUUUUUUUUUUUUUUDUDUDUDDDUUUDDDDDUUUUUUUUUUUUUUDDUDUUDUUDUDUUUUUUDUDUDUDUDUUUUDUUUUDUDUDUUUDUUDDUUUUUUUUUUUUUUUUUUDUUDUUDUUUDUDUUUUUUUUUUUDUUUDUUUUDUDUDUUUUUUUUUDUUUDUUUDUUDUUUUUUUUUUUUDDUDUDUDUUUUUUUUUUUUUUUDUUUDUUUUDUUDUUDUUUUUUUUUUUDUDUUDUUUDUUUUUUDUDUDUUDUUUUUUUUUUUUDUUUDUUDUDUDUUUUDUDUDUDUDUUUUUUUUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUUU -> 872 ``` [Answer] ## CJam, ~~26~~ ~~25~~ 22 bytes ``` 0l{i"()~ "=~0e>_}%ri#) ``` Input format is the instructions on the first line and the ladder height on the second. [Test it here.](http://cjam.aditsu.net/#code=0l%7Bi%22()~%20%22%3D~0e%3E_%7D%25ri%23)&input=UUUUUDRUDDDDRDUUUUUUDRUUUUUUUDR%0A6) ### Explanation ``` 0 e# Push a 0 - the initial position of the robot. l e# Read the instructions. { e# Map this block over the instruction... i e# Convert to character code. D -> 68, U -> 85, R -> 82. "()~ "= e# We use these as cyclic indices into this array. Note that the values e# modulo 4 are 0, 1 and 2, respectively. So U -> ) (increment), e# D -> ( (decrement), R -> ~ (bitwise NOT, i.e negated and decrement). ~ e# Evaluate the character as code. 0e> e# Clamp to non-negative numbers. So D can't go below 0, and since R is e# guaranteed to yield something negative, this resets it to zero. _ e# Duplicate, so we keep one copy of the current position on the stack. }% e# Since this was a map, the result will be wrapped in an array. ri e# Read the ladder height and convert it to an integer. # e# Find its first occurrence in the list of positions. ) e# The result is off by one, so we increment it. ``` [Answer] # C, ~~83~~ 71 + 4 = 75 bytes Thanks [@Josh](https://codegolf.stackexchange.com/users/13877/josh) for showing me the [K&S style](https://codegolf.stackexchange.com/a/40266/48943), which allowed 8 bytes off !! ``` f(i,s,z,a)char*s;{z-=*s<82?z>0:*s>82?-1:z;return z-i?f(i,s+1,z,a+1):a;} ``` Explaining: ``` f(i,s,z,a)char*s;{ // function needs one integer and one "string" z-= // z is the bot's height *s<82? // if 'Down' z>0 // then subtract 1 when z>0 or nothing otherwise :*s>82? // else if 'Up' -1 // increase height z-=-1 :z; // else reset z=z-z return z-i? // if z is not the max height f(i,s+1,z,a+1) // try next step :a; // else print how many calls/steps were made } // end of function ``` Example call: ``` f(1,"U",0,1); // I've added 4 bytes in the score because of ",0,1" ``` Live test on [**ideone**](http://ideone.com/SBaQbt) [Answer] # JavaScript (ES6), ~~54~~ 53 bytes ``` n=>c=>(f=p=>n-p?f({D:p&&p-1,U:p+1}[c[i++]]|0):i)(i=0) ``` ## Explanation Uses a recursive function internally. ``` var solution = n=>c=>( f=p=> // f = recursive function, p = position of robot on ladder n-p? // if p != n f({ // execute the next command D:p&&p-1, // D -> p = max of p - 1 and 0 U:p+1 // U -> p = p + 1 }[c[i++]] // get current command then increment i (current command index) |0 // R -> p = 0 ) :i // else return the current command index )(i=0) // initialise p and i to 0 for the first recurse ``` ``` N = <input type="number" id="N" value="354" /><br /> C = <input type="text" id="C" value="UUDDUUDUDUUDDUDUUUUDDDUDUUDUDUDUDDUUUUDUDUUDUDUUUDUDUDUUDUUUDUUUUUDUUDUDUUDUDUUUUUDUDUUDUDUDUDDUUUUUUUDUDUDUDUUUUUDUDUDUDUDUDUDUDUUDUUUUUURUUUDUUUUDDUUDUDUDURURURUDUDUUUUDUUUUUUDUDUDUDUDUUUUUUDUDUUUUUUUDUUUDUUDUDUDUUDUDUDUUUUUUUUUUDUUUDUDUUDUUDUUUDUUUUUUUUUUUUUDUUDUUDUDUDUUUDUDUUUUUUUDUUUDUUUDUUDUUDDUUUUUUUUDUDUDUDUDUUUUDUDUUUUUUUUDDUUDDUUDUUDUUDUDUDUDUUUUUUUUUDUUDUUDUUUDUUDUUUUUUUUUUUDUDUDUDUUUUUUUUUUUUDUUUDUUDUDDUUDUDUDUUUUUUUUUUUUDUDUDUUDUUUDUUUUUUUDUUUUUUUUUDUDUDUDUDUUUUUUDUDUDUUDUDUDUDUUUUUUUUUUUUUUUDUDUDUDDDUUUDDDDDUUUUUUUUUUUUUUDDUDUUDUUDUDUUUUUUDUDUDUDUDUUUUDUUUUDUDUDUUUDUUDDUUUUUUUUUUUUUUUUUUDUUDUUDUUUDUDUUUUUUUUUUUDUUUDUUUUDUDUDUUUUUUUUUDUUUDUUUDUUDUUUUUUUUUUUUDDUDUDUDUUUUUUUUUUUUUUUDUUUDUUUUDUUDUUDUUUUUUUUUUUDUDUUDUUUDUUUUUUDUDUDUUDUUUUUUUUUUUUDUUUDUUDUDUDUUUUDUDUDUDUDUUUUUUUUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUUU" /><br /> <button onclick="result.textContent=solution(+N.value)(C.value)">Go</button> <pre id="result"></pre> ``` [Answer] ## Haskell, 65 bytes ``` x%'U'=x+1 x%'D'=max(x-1)0 x%_=0 f n=length.fst.span(<n).scanl(%)0 ``` Usage example: `f 4 "UDDUURUUUUUUUDDDD"` -> `10`. `%` adjusts the current position on the ladder, `scanl` makes a list of all positions, `fst.span(<n)` takes the part before the explosion and `length` counts the steps. [Answer] # Perl, 47 + 2 = 49 bytes ``` $z-=-/U/||$z&&/D/;$z*=!/R/;$^I<=$z&&last}{$_=$. ``` Requires the `-p` flag, `-i$N` for latter height and a newline separated list of moves: ``` $ perl -pi10 ladderbot.pl <<<< $'U\nU\nU\nU\nU\nU\nR\nU\nU\nU\nU\nU\nU\nU\nR\nU\nU\nU\nU\nU\nU\nU\nU\nR\nU\nU\nU\nU\nU\nU\nU\nU\nU\nU\nU\nU\nU\nU' 34 ``` How it works: ``` # '-p' wraps the code in (simplified): # while($_=<>) {...print $_} $z-=-/U/||$z&&/D/; # Subtract -1 if UP. subtract 1 if DOWN $z*=!/R/; # If R then times by zero $^I<=$z&&last # Break while loop if N is reached }{ # Eskimo operator: # while($_=<>){...}{print$_} $_=$. # `$.` contains number of lines read from input. ``` Deparsed: ``` LINE: while (defined($_ = <ARGV>)) { $z -= -/U/ || $z && /D/; $z *= !/R/; last if $^I <= $z; } { $_ = $.; } continue { die "-p destination: $!\n" unless print $_; } -e syntax OK ``` [Answer] # JavaScript (SpiderMonkey 30+), ~~65~~ 64 bytes ``` (n,s,i=0)=>[for(c of s)if(i<n)c<'E'?i&&i--:c>'T'?i++:i=0].length ``` --- ### How it works We first set the variable `i` to 0. This will keep track of how many steps the robot has climbed up. Then for each char `c` in the input string, we run the following logic: 1. If `i` is larger than or equal to `n`, don't do anything. 2. If `c` is `"D"`: * If `i` is 0, leave it as is. * Otherwise, decrement it by 1. 3. If `c` is `"U"`, increment `i` by 1. 4. Otherwise, set `i` to 0. By cutting off if `i>=n`, we avoid adding any more items to the array after the robot has reached the top. Thus, we can simply return the length of the resulting array. [Answer] # JavaScript (ES6), 65 bytes ``` (n,s)=>[...s].map(_=>i=_<'E'?i&&i-1:_>'T'?i+1:0,i=0).indexOf(n)+1 ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~37~~ 34 bytes ``` Oj"t@4\1=?Q}6M?x0}qt0>*]]]N$h=f1)q ``` [**Try it online!**](http://matl.tryitonline.net/#code=fmoidEA0XDE9P1F9Nk0_eDB9cXQwPipdXXQxRz0_Ll1dTnExJA&input=MzU0ClVVRERVVURVRFVVRERVRFVVVVVERERVRFVVRFVEVURVRERVVVVVRFVEVVVEVURVVVVEVURVRFVVRFVVVURVVVVVVURVVURVRFVVRFVEVVVVVVVEVURVVURVRFVEVUREVVVVVVVVVURVRFVEVURVVVVVVURVRFVEVURVRFVEVURVRFVVRFVVVVVVVVJVVVVEVVVVVUREVVVEVURVRFVSVVJVUlVEVURVVVVVRFVVVVVVVURVRFVEVURVRFVVVVVVVURVRFVVVVVVVVVEVVVVRFVVRFVEVURVVURVRFVEVVVVVVVVVVVVVURVVVVEVURVVURVVURVVVVEVVVVVVVVVVVVVVVVVURVVURVVURVRFVEVVVVRFVEVVVVVVVVVURVVVVEVVVVRFVVRFVVRERVVVVVVVVVVURVRFVEVURVRFVVVVVEVURVVVVVVVVVVUREVVVERFVVRFVVRFVVRFVEVURVRFVVVVVVVVVVVURVVURVVURVVVVEVVVEVVVVVVVVVVVVVVVEVURVRFVEVVVVVVVVVVVVVVVVRFVVVURVVURVRERVVURVRFVEVVVVVVVVVVVVVVVVRFVEVURVVURVVVVEVVVVVVVVVURVVVVVVVVVVVVEVURVRFVEVURVVVVVVVVEVURVRFVVRFVEVURVRFVVVVVVVVVVVVVVVVVVVURVRFVEVURERFVVVUREREREVVVVVVVVVVVVVVVVVVVERFVEVVVEVVVEVURVVVVVVVVEVURVRFVEVURVVVVVRFVVVVVEVURVRFVVVURVVUREVVVVVVVVVVVVVVVVVVVVVVVVRFVVRFVVRFVVVURVRFVVVVVVVVVVVVVVRFVVVURVVVVVRFVEVURVVVVVVVVVVVVEVVVVRFVVVURVVURVVVVVVVVVVVVVVVVERFVEVURVRFVVVVVVVVVVVVVVVVVVVURVVVVEVVVVVURVVURVVURVVVVVVVVVVVVVVURVRFVVRFVVVURVVVVVVVVEVURVRFVVRFVVVVVVVVVVVVVVVURVVVVEVVVEVURVRFVVVVVEVURVRFVEVURVVVVVVVVVVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVURVVVVVRFVEVVVVVVVV) ### Explanation Position is 0-based. Each new position is pushed onto the stack keeping the older positions. So the stack size represents the number of movements up to now, plus 1. A loop is used to process each command. The loop ~~is exited when position reaches ladder height~~ processes all commands, even after the explosion (idea taken from [Martin's answer](https://codegolf.stackexchange.com/a/74571/36398)). The final result is given by the index of the first position that equals the ladder height. ``` O % push a 0: initial position (0-based) j % take first input (commands) as a string " % for each command t % duplicate current position @ % push command 4\ % modulo 4. This gives 1, 2, 0 for 'U','R', 'D' 1=? % if result equals 1 (command 'U') Q % increase position by 1 } % else 6M? % if result was nonzero (command 'R') x0 % delete current position and push 0 } % else (command 'D') q % decrement by 1 t0>* % turn negative values into 0 ] % end if ] % end if ] % end for each N$h % pack all numbers in the stack into an array = % implicitly read second input: ladder height f1)q % find first position equal to that, and subtract 1. % Implicitly display ``` [Answer] # Python 2, ~~63~~ 62 bytes ``` f=lambda n,s,h=0:h^n and-~f(n,s[1:],-[2%~h,~h,0][ord(s[0])%4]) ``` For example, `f(4, 'UDDUURUUUUUUUDDDD')` is `10`. xnor found an even shorter expression: `2%~h` is really cool :) [Answer] ## PowerShell, ~~86~~ 79 bytes ``` param($a,[char[]]$b)$b|%{$d++;if(($c-=((1,0)[!$c],-1,$c)[$_%4])-ge$a){$d;exit}} ``` A slight retooling of my [When does Santa enter the basement?](https://codegolf.stackexchange.com/a/73396/42963) answer. Takes input `$a` and `$b`, explicitly casting `$b` as char-array. We then loop with `|%{...}` over all of `$b`. Each iteration we increment our counter `$d`. Then, an `if` statement to check whether we've hit the top with `-ge$a`. If so, we output `$d` and `exit`. The `if` statement is constructed from a pseudo-ternary created by assigning `$c` minus-equal to the result of several indexes into an array. We have a trick that the ASCII values of `D`, `R`, and `U` correspond to `0`, `2`, and `1` when taken modulo-4, so `$_%4` serves as our first index. If it's `R`, that sets `$c` equal to `$c-$c`, doing the reset. If `U`, that means we need to go up, so the `$c-(-1)` result. Otherwise it's a `D`, so we need to check if we're already at the bottom (that's the `!$c` - in PowerShell, "not-zero" is "true" or `1`) and set `$c` equal to `$c-0` or `$c-1` respectively. Edit - Saved 7 bytes by using minus-equal assignment rather than direct assignment [Answer] # Perl 5, 61 bytes Includes two bytes for `-F -i`. (`-M5.01` is free.) Input of the integer (e.g. 10) is as `perl -M5.01 -F -i10 robot.pl`; input of the ladder commands is as STDIN. ``` for(@F){($i+=/U/)-=/R/?$i:$i&&/D/;$j++;last if$^I<=$i}say$j ``` [Answer] # Vitsy, 44 bytes There probably could be some reductions - I'll figure out some more things if I can. ``` 0vVWl:X[4M1+mDvV-);]lvXv?v-N vD([1-] v1+ vX0 ``` Explanation (in progress): ``` 0vVWl:X[4M1+mDvV-);]lvXv?v-N 0v Save 0 as our temp var to edit. V Save the input as a global var. W Grab a line of STDIN. l Push the length of the stack. : Clone the stack. This is for later use. X Remove the top item of the stack (we don't need the length right now. [ ] Do the stuff in the brackets infinitely. 4M Modulo 4. 1+ Add one. m Go to the line index as specified by the top item of the stack. Dv Duplicate the top item, save it in the temp var. V-); If the top value is equal to the input number, exit the loop. l Push the length of the stack. vXv Dump the temp var, then save the top item. ? Rotate back to the original stack. v- Subtract the top item (the original length) by the temp var (new length) N Output the top item of the stack of the number. vD([1-] v Push the temp variable to the stack. D([ ] If this value is not zero... 1- Subtract one from it. v1+ Push the temp variable to the stack, then add one to it. vX0 Dump the temp var and replace it with zero. ``` [Try It Online!](http://vitsy.tryitonline.net/#code=MHZWV2w6XFs0TXtdWzErbUR2Vi0pO11sdlh2P3YtTgp2RChbMS1dCnYxKwp2WDA&input=VVVERFVVRFVEVVVERFVEVVVVVURERFVEVVVEVURVRFVERFVVVVVEVURVVURVRFVVVURVRFVEVVVEVVVVRFVVVVVVRFVVRFVEVVVEVURVVVVVVURVRFVVRFVEVURVRERVVVVVVVVVRFVEVURVRFVVVVVVRFVEVURVRFVEVURVRFVEVVVEVVVVVVVVUlVVVURVVVVVRERVVURVRFVEVVJVUlVSVURVRFVVVVVEVVVVVVVVRFVEVURVRFVEVVVVVVVVRFVEVVVVVVVVVURVVVVEVVVEVURVRFVVRFVEVURVVVVVVVVVVVVVRFVVVURVRFVVRFVVRFVVVURVVVVVVVVVVVVVVVVVRFVVRFVVRFVEVURVVVVEVURVVVVVVVVVRFVVVURVVVVEVVVEVVVERFVVVVVVVVVVRFVEVURVRFVEVVVVVURVRFVVVVVVVVVVRERVVUREVVVEVVVEVVVEVURVRFVEVVVVVVVVVVVVRFVVRFVVRFVVVURVVURVVVVVVVVVVVVVVURVRFVEVURVVVVVVVVVVVVVVVVEVVVVRFVVRFVERFVVRFVEVURVVVVVVVVVVVVVVVVEVURVRFVVRFVVVURVVVVVVVVVRFVVVVVVVVVVVURVRFVEVURVRFVVVVVVVURVRFVEVVVEVURVRFVEVVVVVVVVVVVVVVVVVVVVRFVEVURVREREVVVVRERERERVVVVVVVVVVVVVVVVVVUREVURVVURVVURVRFVVVVVVVURVRFVEVURVRFVVVVVEVVVVVURVRFVEVVVVRFVVRERVVVVVVVVVVVVVVVVVVVVVVVVEVVVEVVVEVVVVRFVEVVVVVVVVVVVVVVVEVVVVRFVVVVVEVURVRFVVVVVVVVVVVURVVVVEVVVVRFVVRFVVVVVVVVVVVVVVVUREVURVRFVEVVVVVVVVVVVVVVVVVVVVRFVVVURVVVVVRFVVRFVVRFVVVVVVVVVVVVVVRFVEVVVEVVVVRFVVVVVVVURVRFVEVVVEVVVVVVVVVVVVVVVVRFVVVURVVURVRFVEVVVVVURVRFVEVURVRFVVVVVVVVVVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVRFVVVVVEVURVVVVVVVU&args=MzU0) (big test case) [Answer] # PHP, 88 bytes This generates some (3+2n where n is the number of commands run) notices but that doesn't matter for golfing, right? ``` <?php for(;$x++<$argv[1];)switch($argv[2][$i++]){case R;$x=2;case D;--$x?--$x:0;}echo$i; ``` ungolfed: ``` <?php # actually 1 byte shorter not as a function for(;$x++<$argv[1];) # not initialising the $x causes a notice but still works # post increment $x by 1 regardless of the command (saves us writing a U case) switch($argv[2][$i++]) # get next command, increment number of commands {case R; # R gets treated as a constant with value 'R'. and a notice $x=2; # falling through to D which will double decrement so set to 2 case D; # same trick as R --$x?--$x:0;} # decrement once then again if >0 echo$i; # output ``` [Answer] # Python, 121 bytes ``` def f(a,n): i=c=0 while i<n:i={'U':lambda x:x+1,'D':lambda x:0 if x==0 else x-1,'R':lambda x:0}[a[c]](i);c+=1 return c ``` [Answer] # JavaScript, ~~131~~ 106 Bytes- I know this won't win a Code Golf competition, but this was a fun and stupid solution to implement: ``` l=>s=>Function('i=c=0;'+s.replace(/./g,x=>`c++;i${{R:"=0",U:`++;if(i>=${l})re‌​turn c`,D:"--"}[x]};`))() ``` I kinda went the opposite of a "functional" route by making a dynamically-generated imperative solution, any instance of an instruction is replaced with an increment or decrement, and a counter increment. Thanks to Cycoce for saving me 29 bytes! [Answer] # Python 3, 90 Saved 6 bytes thanks to DSM. Pretty simple right now. ``` def f(c,n): f=t=0 for x in c: f+=1|-(x<'E');f*=(x!='R')&(f>=0);t+=1 if f>=n:return t ``` Test cases: ``` assert f('U', 1) == 1 assert f('DDRUDUU', 1) == 4 assert f('UDDUUUUURUUUUDDDD', 4) == 7 assert f('UDDUURUUUUUUUDDDD', 4) == 10 assert f('UUDDUUDUDUUDDUDUUUUDDDUDUUDUDUDUDDUUUUDUDUUDUDUUUDUDUDUUDUUUDUUUUUDUUDUDUUDUDUUUUUDUDUUDUDUDUDDUUUUUUUDUDUDUDUUUUUDUDUDUDUDUDUDUDUUDUUUUUURUUUDUUUUDDUUDUDUDURURURUDUDUUUUDUUUUUUDUDUDUDUDUUUUUUDUDUUUUUUUDUUUDUUDUDUDUUDUDUDUUUUUUUUUUDUUUDUDUUDUUDUUUDUUUUUUUUUUUUUDUUDUUDUDUDUUUDUDUUUUUUUDUUUDUUUDUUDUUDDUUUUUUUUDUDUDUDUDUUUUDUDUUUUUUUUDDUUDDUUDUUDUUDUDUDUDUUUUUUUUUDUUDUUDUUUDUUDUUUUUUUUUUUDUDUDUDUUUUUUUUUUUUDUUUDUUDUDDUUDUDUDUUUUUUUUUUUUDUDUDUUDUUUDUUUUUUUDUUUUUUUUUDUDUDUDUDUUUUUUDUDUDUUDUDUDUDUUUUUUUUUUUUUUUDUDUDUDDDUUUDDDDDUUUUUUUUUUUUUUDDUDUUDUUDUDUUUUUUDUDUDUDUDUUUUDUUUUDUDUDUUUDUUDDUUUUUUUUUUUUUUUUUUDUUDUUDUUUDUDUUUUUUUUUUUDUUUDUUUUDUDUDUUUUUUUUUDUUUDUUUDUUDUUUUUUUUUUUUDDUDUDUDUUUUUUUUUUUUUUUDUUUDUUUUDUUDUUDUUUUUUUUUUUDUDUUDUUUDUUUUUUDUDUDUUDUUUUUUUUUUUUDUUUDUUDUDUDUUUUDUDUDUDUDUUUUUUUUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUUU', 354) == 872 ``` [Answer] # PHP, 129 bytes ``` function r($h,$s){$i=0;$c=1;while($x=$s[$i++]){if($x=='U'){$c++;}elseif($x=='D'){--$c<1?$c=1:0;}else{$c=1;}if($c>$h){return$i;}}} ``` Not winning, but fun to create. PHP seems to dislike empty parts in the ternary operator (it throws a Syntax Error), so I had to put a `0` there. Ungolfed version: ``` function r($h,$s) { // $h - height of ladder; $s - instructions $i = 0; // Instruction index $c = 1; // Position on ladder while ($x = $s[$i++]){ // Set $x to current instruction and increment index if ($x == 'U'){ // If instruction is U... $c++; // Increment ladder position } elseif ($x == 'D') { // If instruction is D... --$c < 1 ? $c = 1 : 0; // Decrement ladder position, if under 1 set to 1 } else { // If instruction is anything else (in this case R) $c = 1; // Reset ladder position } if ($c > $h) { // If ladder position is larger than height... return $i; // Return current instruction index } } } ``` [Answer] # PHP, 113 bytes Smaller version of <https://codegolf.stackexchange.com/a/74575/13216> ``` function r($h,$s){$i=0;$c=1;while($x=$s[$i++]){$c+=($x=='U'?1:($x=='D'?($c>1?-1:0):1-$c));if($c>$h){return $i;}}} ``` Ungolfed: ``` // $h - height of ladder; $s - instructions function r($h,$s) { $i = 0; $c = 1; while ($x = $s[$i++]) { $c += ( $x=='U'? 1 : ( $x=='D'? ( $c>1? -1 : 0 ): 1-$c ) ); if ($c > $h) { return $i; } } } ``` [Answer] # Pyth, 19 bytes ``` x.u@[tWNNhN00)CYz0Q ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=x.u%40[tWNNhN00%29CYz0Q&input=UUDDD%0A3&test_suite_input=U%0A1%0ADDRUDUU%0A1%0AUDDUUUUURUUUUDDDD%0A4%0AUDDUURUUUUUUUDDDD%0A4%0AUUUUUDRUDDDDRDUUUUUUDRUUUUUUUDR%0A6%0AUUUUUURUUUUUUURUUUUUUUURUUUUUUUUUUUUUU%0A10%0AUUUDUUUUDDDDDDDDDDDDDDRRRRRRRRRRRUUUUUU%0A6%0AUUUDUUUDURUDDDUUUUUDDRUUUUDDUUUUURRUUDDUUUUUUUU%0A6%0AUUDDUDUUUDDUUDUDUUUDUDDUUUUUDUDUUDUUUUUUDUUDUDUDUUUUUDUUUDUDUUUUUUDUDUDUDUDUUUUUUUUUDUDUUDUDUUUUU%0A20%0AUUDDUUDUDUUDDUDUUUUDDDUDUUDUDUDUDDUUUUDUDUUDUDUUUDUDUDUUDUUUDUUUUUDUUDUDUUDUDUUUUUDUDUUDUDUDUDDUUUUUUUDUDUDUDUUUUUDUDUDUDUDUDUDUDUUDUUUUUURUUUDUUUUDDUUDUDUDURURURUDUDUUUUDUUUUUUDUDUDUDUDUUUUUUDUDUUUUUUUDUUUDUUDUDUDUUDUDUDUUUUUUUUUUDUUUDUDUUDUUDUUUDUUUUUUUUUUUUUDUUDUUDUDUDUUUDUDUUUUUUUDUUUDUUUDUUDUUDDUUUUUUUUDUDUDUDUDUUUUDUDUUUUUUUUDDUUDDUUDUUDUUDUDUDUDUUUUUUUUUDUUDUUDUUUDUUDUUUUUUUUUUUDUDUDUDUUUUUUUUUUUUDUUUDUUDUDDUUDUDUDUUUUUUUUUUUUDUDUDUUDUUUDUUUUUUUDUUUUUUUUUDUDUDUDUDUUUUUUDUDUDUUDUDUDUDUUUUUUUUUUUUUUUDUDUDUDDDUUUDDDDDUUUUUUUUUUUUUUDDUDUUDUUDUDUUUUUUDUDUDUDUDUUUUDUUUUDUDUDUUUDUUDDUUUUUUUUUUUUUUUUUUDUUDUUDUUUDUDUUUUUUUUUUUDUUUDUUUUDUDUDUUUUUUUUUDUUUDUUUDUUDUUUUUUUUUUUUDDUDUDUDUUUUUUUUUUUUUUUDUUUDUUUUDUUDUUDUUUUUUUUUUUDUDUUDUUUDUUUUUUDUDUDUUDUUUUUUUUUUUUDUUUDUUDUDUDUUUUDUDUDUDUDUUUUUUUUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUUU%0A354&debug=0&input_size=2) or [Test Suite](http://pyth.herokuapp.com/?code=x.u%40[tWNNhN00%29CYz0Q&input=UUDDD%0A3&test_suite=1&test_suite_input=U%0A1%0ADDRUDUU%0A1%0AUDDUUUUURUUUUDDDD%0A4%0AUDDUURUUUUUUUDDDD%0A4%0AUUUUUDRUDDDDRDUUUUUUDRUUUUUUUDR%0A6%0AUUUUUURUUUUUUURUUUUUUUURUUUUUUUUUUUUUU%0A10%0AUUUDUUUUDDDDDDDDDDDDDDRRRRRRRRRRRUUUUUU%0A6%0AUUUDUUUDURUDDDUUUUUDDRUUUUDDUUUUURRUUDDUUUUUUUU%0A6%0AUUDDUDUUUDDUUDUDUUUDUDDUUUUUDUDUUDUUUUUUDUUDUDUDUUUUUDUUUDUDUUUUUUDUDUDUDUDUUUUUUUUUDUDUUDUDUUUUU%0A20%0AUUDDUUDUDUUDDUDUUUUDDDUDUUDUDUDUDDUUUUDUDUUDUDUUUDUDUDUUDUUUDUUUUUDUUDUDUUDUDUUUUUDUDUUDUDUDUDDUUUUUUUDUDUDUDUUUUUDUDUDUDUDUDUDUDUUDUUUUUURUUUDUUUUDDUUDUDUDURURURUDUDUUUUDUUUUUUDUDUDUDUDUUUUUUDUDUUUUUUUDUUUDUUDUDUDUUDUDUDUUUUUUUUUUDUUUDUDUUDUUDUUUDUUUUUUUUUUUUUDUUDUUDUDUDUUUDUDUUUUUUUDUUUDUUUDUUDUUDDUUUUUUUUDUDUDUDUDUUUUDUDUUUUUUUUDDUUDDUUDUUDUUDUDUDUDUUUUUUUUUDUUDUUDUUUDUUDUUUUUUUUUUUDUDUDUDUUUUUUUUUUUUDUUUDUUDUDDUUDUDUDUUUUUUUUUUUUDUDUDUUDUUUDUUUUUUUDUUUUUUUUUDUDUDUDUDUUUUUUDUDUDUUDUDUDUDUUUUUUUUUUUUUUUDUDUDUDDDUUUDDDDDUUUUUUUUUUUUUUDDUDUUDUUDUDUUUUUUDUDUDUDUDUUUUDUUUUDUDUDUUUDUUDDUUUUUUUUUUUUUUUUUUDUUDUUDUUUDUDUUUUUUUUUUUDUUUDUUUUDUDUDUUUUUUUUUDUUUDUUUDUUDUUUUUUUUUUUUDDUDUDUDUUUUUUUUUUUUUUUDUUUDUUUUDUUDUUDUUUUUUUUUUUDUDUUDUUUDUUUUUUDUDUDUUDUUUUUUUUUUUUDUUUDUUDUDUDUUUUDUDUDUDUDUUUUUUUUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUUU%0A354&debug=0&input_size=2) ### Explanation: ``` x.u@[tWNNhN00)CYz0Q implicit: z = input string, Q = input number .u z0 reduce z: for each char Y in z manipulate N = 0 with: [ ) create a list with tWNN * N-1 if N>0 else N hN * N+1 0 * 0 0 * 0 @ CY replace N by the ord(Y)-th element (mod 4) .u .u give us a list with all intermediate values of N x Q print the index of Q in this list ``` [Answer] ## Java, 250 bytes ``` int cmds(int n, String s) { int steps=1; int count=0; for (int i=0;i< s.length();i++) { count++; char c=s.charAt(i); switch(c){ case 'D': steps=(steps==1)?1:--steps; break; case 'R': steps=1; break; case 'U': ++steps; break; } if(steps>n) return count; } return 0; } ``` [Answer] # C, 91 bytes No warnings with `gcc -Wall`. Recursion and comma-separated expressions. `r.c` contains bare function: ``` int r(int N,int n,int s,char*C){return*C&&s<=N?s+=*C&2?-s:*C&1?1:-1,r(N,n+1,s?s:1,C+1):n;} ``` Commented, ``` int r(int N, // number of steps on ladder int n, // result, seed with 0 int s, // current step, seed with 1 char *C // command string ) { return *C&&s<=N ? // still reading commands and still on ladder? s+= // increment step value by... *C&2? // bit test if 'R' but not 'U' or 'D'. -s // negate to 0, will set to 1 in call if needed :*C&1? // Not 'R', is it 'U'? 1 // 'U', add 1 :-1, // Must be 'D', subtract 1 r(N,n+1,s?s:1,C+1) // Recursive call, and fix case where s==0. :n; // end of string or fell off ladder } ``` For reference, ``` 'U'.charCodeAt(0).toString(2) "1010101" 'D'.charCodeAt(0).toString(2) "1000100" 'R'.charCodeAt(0).toString(2) "1010010" ``` `roboladder.c` wrapper, ``` #include <stdio.h> #include <stdlib.h> #include "r.c" int main(int argc, char * argv[]) { int N = atoi(argv[1]); int n = r(N,0,1,argv[2]); int check = atoi(argv[3]); printf("%d : %d\n", n, check); return 0; } ``` `Makefile` for testing, ``` run: @gcc -Wall robotladder.c -o robotladder @./robotladder 1 U 1 @./robotladder 1 DDRUDUU 4 @./robotladder 4 UDDUUUUURUUUUDDDD 7 @./robotladder 4 UDDUURUUUUUUUDDDD 10 @./robotladder 6 UUUUUDRUDDDDRDUUUUUUDRUUUUUUUDR 20 @./robotladder 10 UUUUUURUUUUUUURUUUUUUUURUUUUUUUUUUUUUU 34 @./robotladder 6 UUUDUUUUDDDDDDDDDDDDDDRRRRRRRRRRRUUUUUU 8 @./robotladder 6 UUUDUUUDURUDDDUUUUUDDRUUUUDDUUUUURRUUDDUUUUUUUU 32 @./robotladder 20 UUDDUDUUUDDUUDUDUUUDUDDUUUUUDUDUUDUUUUUUDUUDUDUDUUUUUDUUUDUDUUUUUUDUDUDUDUDUUUUUUUUUDUDUUDUDUUUUU 56 @./robotladder 354 UUDDUUDUDUUDDUDUUUUDDDUDUUDUDUDUDDUUUUDUDUUDUDUUUDUDUDUUDUUUDUUUUUDUUDUDUUDUDUUUUUDUDUUDUDUDUDDUUUUUUUDUDUDUDUUUUUDUDUDUDUDUDUDUDUUDUUUUUURUUUDUUUUDDUUDUDUDURURURUDUDUUUUDUUUUUUDUDUDUDUDUUUUUUDUDUUUUUUUDUUUDUUDUDUDUUDUDUDUUUUUUUUUUDUUUDUDUUDUUDUUUDUUUUUUUUUUUUUDUUDUUDUDUDUUUDUDUUUUUUUDUUUDUUUDUUDUUDDUUUUUUUUDUDUDUDUDUUUUDUDUUUUUUUUDDUUDDUUDUUDUUDUDUDUDUUUUUUUUUDUUDUUDUUUDUUDUUUUUUUUUUUDUDUDUDUUUUUUUUUUUUDUUUDUUDUDDUUDUDUDUUUUUUUUUUUUDUDUDUUDUUUDUUUUUUUDUUUUUUUUUDUDUDUDUDUUUUUUDUDUDUUDUDUDUDUUUUUUUUUUUUUUUDUDUDUDDDUUUDDDDDUUUUUUUUUUUUUUDDUDUUDUUDUDUUUUUUDUDUDUDUDUUUUDUUUUDUDUDUUUDUUDDUUUUUUUUUUUUUUUUUUDUUDUUDUUUDUDUUUUUUUUUUUDUUUDUUUUDUDUDUUUUUUUUUDUUUDUUUDUUDUUUUUUUUUUUUDDUDUDUDUUUUUUUUUUUUUUUDUUUDUUUUDUUDUUDUUUUUUUUUUUDUDUUDUUUDUUUUUUDUDUDUUDUUUUUUUUUUUUDUUUDUUDUDUDUUUUDUDUDUDUDUUUUUUUUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUUU 872 @wc -c r.c ``` [Answer] # Mathematica, ~~114~~ 120 bytes ``` (d=#~Max~1-1&;u=#+1&;r=1&;s=StringToStream@ToLowerCase@#;l=1;t=1;While[(l=ToExpression[s~Read~Character]@l)<=#2,t++];t)& ``` Anonymous function, which takes the two arguments (C,N). Careful using this, as it doesn't close the stream it opens. Also it assigns all its variables globally. Edited to replace `d=#-1&` with `d=#~Max~1-1&`, so that robie doesn't go digging. [Answer] # Mathematica, 112 Bytes ``` i=0;First@Position[ToExpression["{"<>#~StringReplace~{"U"->"i++,","D"->"i=i~Max~1-1,","R"->"i=0,"}<>"0}"],#2-1]& ``` [Answer] ## Clojure, ~~92~~ 84 bytes Counts `n` to zero instead zero to `n`, can utilize `take-while pos?`. ``` #(count(take-while pos?(reductions(fn[p o](if o(min(o p 1)%)%))%(map{\U -\D +}%2)))) ``` Original: ``` #(count(take-while(partial > %)(reductions(fn[p o](if o(max(o p 1)0)0))0(map{\U +\D -}%2)))) ``` Maps 2nd argument `U` to `+`, `D` to `-` and others to `nil`. Reducing function runs `(operand position 1)` with non-null `operand` and `0` otherwise. Takes values until we are higher than the 1st input argument and counts how many we've got. [Answer] # Mathematica, 67 bytes ``` (p=i=0;While[p<#,p=Switch[#2[[++i]],"U",p+1,"D",1~Max~p-1,_,0]];i)& ``` Unnamed functions of two arguments, a positive integer and a list of characters, that returns a positive integer. A more straightforward `While` implementation than the other Mathematica entries, that manages to result in a more competetive length. ]
[Question] [ When writing a message with fridge magnets, you'll often find yourself substituting a `1` for an `I`. In this challenge, your goal is to find out if a message can be written using the letters of another message. The allowed substitutions are: ``` A = 4 B = 8 C = U E = M = W = 3 G = 6 = 9 I = 1 L = 7 N = Z O = 0 R = 2 S = 5 ``` For example, the message `CIRCA 333` can be rearranged to spell `ICE CREAM`, where the first two `3`s are rotated 180 degrees to make two `E`s, and the last `3` is rotated 90 degrees counterclockwise to make an `M`. Whitespaces can be included in the messages, but they should not be accounted for in your solution, as they're made by placing the magnets on the fridge. ## Input Two strings (or character arrays). All messages will match `^[A-Z0-9 ]+$` ## Output Truthy if the two input strings are valid rearrangements of each other, falsey otherwise. ## Examples ``` ["CIRCA 333", "ICE CREAM"] => true ["DCLV 00133", "I LOVE CODE"] => true ["WE ARE EMISSARIES", "33 423 3315542135"] => true ["WE WANT ICE CREAM", "MET CIRCA 334 MEN"] => true ["I HAVE ICE CREAM", "HAVE 2 ICE CREAMS"] => false ``` ## More thruthy examples These are all the 15+ letter words that map to another word. Some are trivial substitutions, but I included all that I found. ``` ["ANTHROPOMORPHISE","ANTHROPOMORPHISM"] ["ANTIPHILOSOPHIES","ANTIPHILOSOPHISM"] ["CIRCUMSTANTIALLY","ULTRAMASCULINITY"] ["DECENTRALIZATION","DENEUTRALIZATION"] ["DIMETHYLNITROSAMINE","THREEDIMENSIONALITY"] ["INSTITUTIONALISE","INSTITUTIONALISM"] ["INTERCRYSTALLINE","INTERCRYSTALLIZE"] ["INTERNATIONALISE","INTERNATIONALISM"] ["OVERCENTRALIZATION","OVERNEUTRALIZATION"] ["OVERCENTRALIZING","OVERNEUTRALIZING"] ["PREMILLENNIALISE","PREMILLENNIALISM"] ["TRANSCENDENTALIZE","TRANSCENDENTALIZM"] ``` As this is a code golf challenge, the shortest solution wins! I will accept the shortest solution in 7 days from posting. Happy golfing! [Sample solution, non-golfed](https://tio.run/##bZNda6NAFIav4684681EKsHPfBSyYO1sK8QEtG2gIsWkk63UGNEJ7LLsb8/OqNHZNDfiPO9z5ujRKX7Tj0Nunk7pvjiUFCpapvlPSaqOmwrm8Ce7jbIYdocSMkjzNh4l1TZN345FQcptUpEbpOmGadnjyXSG/ta1EXJQPEqYkb8PkYWUlloCdRht8Z2Ap508FehdL7sCfu7kZ4G6vYwZJr8oxxHykQpozS8mis@Fvmjga8b6yx74wjCvd8HcaJUHURnzdNbXj8Xw4SKcfQnHwr6e8N56Nw1doF4/jYWAJ508Eeiil5cCfu3kV4Eue3klYK2TNYGuejkQsNHJhkCDXg4FbHeyLdCQy@9kB9sPsv184wJN6ZGmh3yYqLBRbqVBwv7mZFSSIku2ZIiAj5GVDTaMb67wdAcZYeUKfJvXd/Uug5LQY5nDjySriDSozwWhlJT8cCRc4Kiqjwp/zCaMecB3rINNvbpoXPG2KuhKk5Uk@ZTOzZg5Z6kkFezw0aEi7VlpFMmuF7gOmKYpqyB7LgY3wI4vxypE8r27eAFN09sQFqsXlq/ucROvMTgBBux7YegEHg65ZZoAYBn8ynbVbdsydNPuCtbO8gn6NqzAx09wfggLfLxsXA8eHdbtP7UmRs9COY4lPqs9qeqp7NlUmvdDEYKbmkdazO6Q2q31eh3D/Dub1ZWP3RapZ1tRpNPpHw "Python 3 – Try It Online") ## Related * [My daughter's alphabet](https://codegolf.stackexchange.com/questions/25625/my-daughters-alphabet "My daughter's alphabet") * [Foam bath letters](https://codegolf.stackexchange.com/questions/151083/foam-bath-letters "Foam bath letters") **EDIT**: Made an error in the substitutions, had `G = 6` and `6 = 9` as separate substitutions, merged them into one. [Answer] # [Python 2](https://docs.python.org/2/), ~~145~~ ~~131~~ ~~130~~ ~~129~~ 125 bytes ``` lambda*a:all(len({sum(map(w.count,x))for w in a})<2for x in'A4 B8 CU EMW3 G69 I1 L7 NZ O0 R2 S5'.split()+list('DFHJKPQTVXY')) ``` [Try it online!](https://tio.run/##XY5LT4NAFIX3/ooTNsxo0wADvqKLEUZL5aGAoMYNPogkvFJoWmP87QhGbXVzk3PyfTm3eete60rrs9OHvkjLx@d0Nz1Oi4IULxV5b5clKdOGrKZP9bLqJmtKs3qBFfIK6Qc90ca0HpLMdZwdwryBcBOGi/0j2CqcA3j38BUEGkJDnrZNkXeE7hV52xHZOp/NL6@uo/j2Tqa0bxZ51SEjkmkHJgdjTJpAsk0BMxDclejOL2GZTgxFUb8ROH48UL4ltqFEgAdi@McOQx7YIhxZxgDo2niHBdUwdE1lxj8t4V6EzfCguSLCz1s6XOFtGzZmfNj/I3w12qYLJdp/Ag "Python 2 – Try It Online") Alt: # [Python 2](https://docs.python.org/2/), 125 bytes ``` lambda*a:len({(x,sum(map(w.count,x)))for x in'A4 B8 CU EMW3 G69 I1 L7 NZ O0 R2 S5'.split()+list('DFHJKPQTVXY')for w in a})<23 ``` [Try it online!](https://tio.run/##XY5LT4NAFIX3/ooTNswoaYABX9HFCKNFeSggqHGDDyIJUFJoijH@dqSN2urmLk6@75zbvHdvs1of8tPHocyqp5dsNzsuX2vyQXqlXVSkyhqynDzPFnWn9JTSfDZHj6KWuYGzQ1i3EF7KcLF/BEeDewD/AYGKUEdkypO2KYuO0L2yaDsi2@fTy6vrmzi5u5fXRcuxCNknPdHZ0MyLukNOJMsJLQ7GmKRAciwBKxTck@jOL2FbbgJV1b4RuEEyUoEttqFUgIdi/M6JIh46IlqxjAEw9NUdFzTTNHSNmf@0lPsxNsOj5okYP28Z8IS/bTiY8nH/j7BO9E0WSXT4Ag "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~99~~ ~~72~~ 71 bytes ``` ->a{!!a.map{|x|x.tr("0-9UZMW","OIREASGLBGCNE").chars.sort-[" "]}.uniq!} ``` [Try it online!](https://tio.run/##VY4xT8MwFIR3fsXLm0BKrCROBgaQjGsVS3EixaWRsDyYiqoMQElTqSjJbw8uBSqWN9x39@7a/dPntL6ZolvXB4Ejr27bD4fhQLr2EuPo@uFRNRhiJWvB9Ly4m/NS4BVZbVy7I7v3tosMAtqR7N9ePoJxMga5rDkDSimGgJIL4D6r0IYXBme8WEIcJz8QimrpeTUTJ9wIYLUAoaTWrJZCH12UAkCWHq//muR5liY0/ws0rFzAucYHlFjA74gMlChPXgn3zLf9s34r6VnTaC15dqtNP3QDbGFtOjtOXw "Ruby – Try It Online") Takes an array of strings, assumes input in uppercase as in all test cases. -1 byte golfed by benj2240. [Answer] # JavaScript (ES6), ~~102~~ 100 bytes Takes input as two arrays of characters in currying syntax `(a)(b)`. Returns a boolean. ``` a=>b=>(g=s=>s.map(c=>'648UD3F6H1JK73Z0PQ25TUV3'[parseInt(c,36)-9]||c).sort().join``.trim())(a)==g(b) ``` [Try it online!](https://tio.run/##jY/BboJAFEX3/YoXN84kdQQGbLsYEoLTOK1oC4hJjYkjBaJRIAztyn@ntMbWpE3s5i3uzTm5byvfpYqrTVn38uI1aVLWSGavmY0yppityF6WKGZ2d2Dezob0fjDSHx5v6Iv29GxY4Syi3UUpK5WIvEbxNR3g3t3ycIgxUUVVI0y2xSZfrUhdbfYIYyQxYxla4yYuclXsErIrMpSiBSGk4wrfdYBS2lniYyJcDq7PHa9NMPT7UFdvydUf6NAdR6Bp@jkL42nU4tMhv0TPOTg@B@6JIHB8wYNvCaUAYBqftx2mW5Zp6NT6h2/uTEI4n39sPB7C6U0TPD65pBIwctovfpu@YuOnCE6mVO5U0nwA "JavaScript (Node.js) – Try It Online") ### How? Using the helper function **g()**, for each input **s**: * Digits **0** to **8** and letters **X**, **Y** and **Z** are left unchanged. Everything else is explicitly translated. ``` 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ .........648UD3F6H1JK73Z0PQ25TUV3... ``` Code: ``` s.map(c => '648UD3F6H1JK73Z0PQ25TUV3'[parseInt(c, 36) - 9] || c) ``` * We sort the characters (which brings all spaces at the beginning), join them and remove all leading whitespace. Code: ``` .sort().join``.trim() ``` Finally, we compare both outputs. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 42 bytes ``` T` dUZMW`_\OIR\EASG\LBGCN\E %O`. ^(.*)¶\1$ ``` [Try it online!](https://tio.run/##VY1NCsIwFIT3PcUjWKhSStO0B4jpowaaFpLaggSNoAs3LsSzeQAvVlN/KG5mMd/HzO18v1yPYxgZF4@dg9N2pwZ3sK3UFrmpbL2uRGMxCFuXBPsoWS2fD0sX40iE1IIDY4zEQKRAEBq5IgEpRd1DmtIvgbrtPWxL9GxA4BoBlTSGa4lmUhgDgDyb0u/RosgzyoqPPfCmg3nd2wo7@H3noLDxooQN9yd/3rvJ5s6QFw "Retina 0.8.2 – Try It Online") Takes input on separate lines, but Link includes test cases and header. Explanation: ``` T` dUZMW`_\OIR\EASG\LBGCN\E ``` Map all the letters to a minimal set, deleting the spaces. ``` %O`. ``` Sort each string into order. ``` ^(.*)¶\1$ ``` Compare the two values. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 49 [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") -1 thanks to ngn. Anonymous tacit prefix function. ``` (≡/(⍋⌷¨⊂)¨)(,¨⎕D,'UMWZ ')⎕R('OIREASGLBGCEEN',⊂⍬) ``` [Try it online!](https://tio.run/##bY7BSsNAEIbvPsWQyyaQYpNNHmDdDO1KNgu7aQMWDwWpl4JevSoUrKbowQfw1oPg0XseZV8kTkWpFi/DzPB9M//8ejm4uJkvry77PvT3r8ehbx/840e39evbqNtGYUzt5qWI2UQ3Z8AiGmzIjLIo3Kg8GUnEisVE@/Yt6hd@9eTbDUHK@PVd98796pkmZyXVeqxcvwDqTp2p2CyQykoBnPMghkBJBElndXDOjn5ThSynMBwm3xiUZkqkKfAQbBCERUCtnBNWodvxnANAlu4qfUryPEsTnv@jNqKqYR@CVI01/ETMQGN1aCkYC8ryR/rapPudI@kT "APL (Dyalog Unicode) – Try It Online") `⎕R` PCRE **R**eplace:  `'UMWZ '` these five characters  `⎕D,` preceded by the digits  `,¨` separately (make each into a string rather than being a single character)  with:  `⊂⍬` nothing  `'OIREASGLBGCEEN',` preceded by these characters `(`…`)` apply the following tacit function to that:  `(`…`)¨` apply the following tacit function to each:   `⊂` enclose it (to treat it as a whole)   `⍋⌷¨` use each of the indices that would sort it to index into the whole string (sorts)  `≡/` are they identical? (lit. match reduction) [Answer] # [Python 2](https://docs.python.org/2/), 108 bytes ``` lambda a,b:g(a)==g(b) g=lambda s:sorted('85930A4614012B3C4D5EF6378GH9AI2J3KL7'[int(c,36)]for c in s if'!'<c) ``` [Try it online!](https://tio.run/##VY9Bb4IwGIbP81d864U24QC0oJKxpCvdZANNwOjBeQAcjGQDA1z89awQjdnlS/O8T7633/nSfze1NRTe5/CT/manFFI9c0ucEs8rcUZmpXflnds1bf91wtrCXlKDM8dkhmm9UMF8W746dL54Wy15YL3Tj3CuHaq6x7lOHXIsmhZyqGrooCq0R@0pJ8PIVNNIDxiJIBYcKKVIBxQICSKWPEJEx8gX4Q4Mw7xmEG52Kt74ckr3EngsQUZBkvA4kMkoUQoAzBqn2mnaNrNMat/8PV9v4d6h/Ehu4fYDBpFcT2oAK66q/pkTse4sQeTozh7OrTp2PEfXvGdNL7B6kuEP "Python 2 – Try It Online") There are 23 equivalence classes of characters. Using the 36-character string `'85930A4614012B3C4D5EF6378GH9AI2J3KL7'`, we map each character to its equivalence class (ignoring spaces), then sort the resulting array. Two strings are equivalent iff the resulting lists are equal. [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~38~~ ~~36~~ ~~33~~ 30 bytes Takes input as an array of 2 strings. ``` ®d`z³m`i`oiglbg`í)Ôu)ñ xÃr¶ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=rmRgepqzbWBpYG9pnIZnbGJnYO0p1HUp8SB4w3K2&input=WyJDSVJDQSAzMzMiLCJJQ0UgQ1JFQU0iXQ==) or [run all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=Tq6uZGB6mrNtYGlgb2mchmdsYmdg7SnUdSnxIHjDcrY=&input=WyJDSVJDQSAzMzMiLCJJQ0UgQ1JFQU0iXQpbIkRDTFYgMDAxMzMiLCAiSSBMT1ZFIENPREUiXQpbIldFIEFSRSBFTUlTU0FSSUVTIiwgIjMzICAgNDIzICAgIDMzMTU1NDIxMzUiXQpbIldFIFdBTlQgSUNFIENSRUFNIiwgIk1FVCBDSVJDQSAzMzQgTUVOIl0KWyJJIEhBVkUgSUNFIENSRUFNIiwgIkhBVkUgMiBJQ0UgQ1JFQU1TIl0KLVI=) 3 bytes saved thanks to [ETHProductions](https://codegolf.stackexchange.com/users/42545/ethproductions) ``` ®d`z...m`i`o...g`í)Ôu)ñ xÃr¶ :Implicit input of array U ® :Map each Z d : For each pair of characters in the following string, : replace all occurrences of the 1st character in Z with the 2nd `z...m` : The compressed string "znewem" i : Prepend `o...g` : The compressed string "oireasglbg" í : Interleave 0-based indices ) : End prepend Ô : Reverse u : Convert to uppercase ) : End replace ñ : Sort x : Trim à :End map r :Reduce ¶ : By testing equality ``` [Answer] # Java 10, ~~262~~ ~~260~~ ~~258~~ ~~216~~ ~~208~~ 174 bytes ``` a->b->n(a).equals(n(b));String n(String s){return s.chars().mapToObj(x->x<48?"":"OIREASGLBG.......ABCDEFGHIJKLENOPQRSTCVEXYN".split("")[x-48]).sorted().reduce("",(a,b)->a+b);} ``` -2 bytes thanks to *@Arnauld*. -76 bytes thanks to *@OlivierGrégoire*. [Try it online.](https://tio.run/##jZDBTuMwEIbvPMXIJ1vbWLRJJUQhqzQ1JdA0kFRlV4iDk6ZLSuKE2IEi1GcvprRiV9pDLMsezz/zyf@s@As3VounbZJzKcHnmXg/AljpNG1UltNlIxKVlYJe7IOzSNWZ@NNpVTMsyzzlwrZhCeew5YYdG7bAnND0ueG5xALHhAy@ykHgfSDJe52qphYgafLIa4kJLXg1K4N4hdeGvT6zTn4idIoCL2RONJ4Mx/RrOUN3xC7Gl97V9YRNg5vbMJq5c/br9xRRWeWZwgiR@7VhnTwQKstapQvNrtNFk6Ra6mDeiYlh8x8xGWy2Az0KvasmzrMEpOJKXy9ltoBCD2r/2/sH4ORzaLAbHxTaqUhfdw9MBjshepMqLWjZKFrpHpULXNAl5VWVv2HkeqHrgGmaiBxSnsvA1d58RFohRu5kDsfH3X8YMAnmGhOMWEvKHQMnZMB8L4qc0GPRN8w0dbfV@zz1T7v9vtXrmv323DtnOoO/XB0kn83g4N8Cn01bIj24dLS5/xB3@d63Eu2Jm6PN9gM) **Explanation:** ``` a->b-> // Method with two String parameters and boolean return-type n(a).equals(n(b)) // Return if both Strings are equal in the end String n(String s){ // Separated method with String as both parameter return-type return s.chars() // Loop over all characters as integers .mapToObj(x->x<48?// If the current character is a space: "" // Replace it with an empty String to skip it : // Else: "OIREASGLBG.......ABCDEFGHIJKLENOPQRSTCVEXYN".split("")[x-48] // Convert multi-substitution characters to a single one .sorted() // Sort all of the converted characters .reduce("",(a,b)->a+b);} // And join all of them together as single String ``` [Answer] # [R](https://www.r-project.org/), 123 bytes ``` function(x,y=chartr("48UMW36917Z025","ABCEEEGGILNORS",gsub(" ","",x)))all(g(y[1])==g(y[2])) g=function(z)sort(utf8ToInt(z)) ``` [Try it online!](https://tio.run/##ZY5Na4NAEIbv@RXDnnZgD@pqmx48bM2SLvgBmkZoycEK2oBo0BVi/7xd@xWkcxiGd5533unnyp@rsS31uWvplU1@@V70uqfE3T5HOb97sO9fLMcjjIjHQEq536swTtKMsHoY3ygBsyHsiohF09CaTq/2CX1/GZwT4qb2/65/4ND1mo662h461Woj4NwUl0sz0eY8aFpSEqg0EMA5JwyICiQEqRQRQbaB7zLMLgiPYFn2DwRhcjRcspNrLJcgUgkyUlkmUiWzhebcLF1n6SbF9jzXsbn3z5iL@AC3eGOM5AF@n3MhkvHao@BJmC9Wli/FuWkZQWRQ4fwJ "R – Try It Online") `utf8ToInt` converts a string into a vector of Unicode code points. ~~`!sd(a-b)` is one byte shorter than `all(a==b)`~~ but that doesn't help here because I'm actually dealing with integers and not logicals. [Answer] # [J](http://jsoftware.com/), 56 bytes ``` -:&(-.&' '/:~@rplc'0123456789UMWZ';"0'OIREASGLBGCEEN'"1) ``` [Try it online!](https://tio.run/##VY7RSsNAEEXf@xWXPHQsmHQ3m6hNEVy3Y13INrBbG9rXYhERFD/AX4/b2FD7MANz58yd@94lGR1wX4FwDYEqVprB@PqpS6vxVZqNCTStfh6@vz72JGSuivLm9m724todzRNBjfWsw7J@XBrmFSVy0k1GGL3u3z5BxnqjoZQiHEDWcHRm7ei0Xph6AyHksEfdbCLSLHggWob2DHY2BO0thx5UCkCRH3s0l2VZ5FKV/25avVrj/O5443iNIU4BF6OecItnHb9e0r2Un8Uw0P20jaHMn@sWXhs22lP3Cw "J – Try It Online") ## Explanation: `&` for both left and right arguments `-.&' '` removes spaces from the input, `rplc` replaces `'0123456789UMWZ';"0'OIREASGLBGCEEN'"1` the characters in the input by substitution of the chars in the left column with the ones in the right one: (here transposed for saving space) ``` |:'0123456789UMWZ';"0'OIREASGLBGCEEN' ┌─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐ │0│1│2│3│4│5│6│7│8│9│U│M│W│Z│ ├─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┤ │O│I│R│E│A│S│G│L│B│G│C│E│E│N│ └─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘ ``` `/:~@` and sorts the resulting strings `-:` are the sorted strings equal? ## My initial solution: # [J](http://jsoftware.com/), 77 73 bytes ``` -:&(1#.(' '-.~])e."1[:(,a.,.@-.,)'EMW3','G69',9 2$'A4B8CUI1L7NZO0R2S5'"1) ``` [Try it online!](https://tio.run/##VY7dSsNAEIXv@xSHKE4CmyWbTdQGBNftWBfyA5vaUMULkRbxxjfw1eM2GqoXMzAz3zlnPsZI0gE3FQgCGapQqYT19f2YVhexOpMxgVL59ZLsZaSeq1i8SiFvUykS4mbQJGh9uSSxRH5Opri7to9O1VftU5f5vC8pUsmYLLDYv71/gqzz1kBrTTiAnOUQxaah3/PK1ltkmZrvqLttQLoVz8TAMJ7Bjet74x33E6g1gCI/9mCuyrLIlS7/aAbTbnCKO2oa3mB@p0DD7Yw7PJiQ@p@eVvlp2c/0NO3CU/bHdQdvLFvjafwG "J – Try It Online") ## Explanation: `(' '-.~])` removes spaces from both arguments and `e."1` tests each character for membership in the follwing table: `[:(,a.,.@-.,)'EMW3','G69',9 2$'A4B8CUI1L7NZO0R2S5'"1` the reference: ``` EMW3 G69 A4 B8 CU I1 L7 NZ O0 R2 S5 . . . All other symbols one in a row ``` `1#.` adds up the comparison tables for each argument `-:&` do they match? [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 55 bytes ``` {[eq] .map:{sort TR/0..9UZMW/OIREASGLBGCNEE/~~m:g/\S/}} ``` [Try it online!](https://tio.run/##VY5BS8NAFITv/ophEVEo2SSbCK14WLePupBNYDdtwBqkh8aLoTX1Ukr71@O2VYuXd5hv5s2sl93Hfd9ucdPgsd/Nl581gnaxHu02q@4LpeVhEAynL6bihbYk3SR7mqiciB8O7eidvzq@3/ebxRbN7fXbHZpVdzVnSlslIYRgAzCtCMpHDasHno1VNkMYRj8QWTHzvBjTGVcEaQlktHPSanJHlxAAkvh4/dcoTZM4EulfoJJ5iUuNDxgq8TsigaH87NV4lr7tn/WkxBfNsfqh/wY "Perl 6 – Try It Online") Works with an arbitrary number of strings. [Answer] # [Python 2](https://docs.python.org/2/), 111 bytes ``` lambda*t:2>len({`sorted(s.translate(dict(map(None,map(ord,'48UMW36917Z025 '),u'ABCEEEGGILNORS'))))`for s in t}) ``` [Try it online!](https://tio.run/##XY5Na4NAEIbv/RWDF9ciRV3tF7Sw3Qzpgh@gaYTSQ2xVKphVdD2U0t9uNBDEzmEYXp6Hedsf9d1IZyyfPsY6O37m2bV6dJ7rQpLfQ990qshJf6O6TPZ1pgqSV1@KHLOWhI0szPloutzU3fu3IKW3D/bdu@V4oBvmoLMXjojbrfDDKE50Y5pD2XTQQyVB/Rlj21VSQUkGjYuYM6CUaiYMmuAIPEYWaMbVwmy4vwfLsi8Q@NF@4qINrrAUgcUIGIgkYbHA5ExTCgCuM@/pje15rmNT77@YsnAHy/dZDHAHl3YuBBiuHAGvbCqxVs6Rs4SJZown "Python 2 – Try It Online") # 116 bytes ``` lambda a,b:g(a)==g(b) g=lambda s,y='4A8BUCMEWE3E6G9G1I7LZN0O2R5S ':y and g(s.replace(y[0],y[1:2]),y[2:])or sorted(s) ``` [Try it online!](https://tio.run/##XY5Na4NAFEX3@RUPN5kBKTqj/RBcTCePdEAjaBqhqYuxGltIVdSNv96akjZpN@/C5Rzua8fhvanZdPBfp6P@zAsN2sy9imjq@xXJ6aLyz31vjv7SEfePzzLEFDnerh/WtroLXjZWxGI3gaU3gq4LqEh/05XtUb@VZNxbmTnubY9ldE7mZbTpoG@6oSxIT6e2@6gHOBBDqlgK4JwbJhhKIsgYRWjQxS@xksEOLMs@IxBEu5mKVngNpQgiRsBQJYmIFSYnlnMAcNjpzgu26zrM5u4/LRWbLVyGZy3ELfy85UCIm2tDwZOY9/8I3w27dIlBpy8 "Python 2 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 105 bytes ``` lambda a,b:X(a)==X(b) X=lambda s:sorted(("ABCEEEGGILNORS"+c)["48UMW36917Z025".find(c)]for c in s if' '<c) ``` [Try it online!](https://tio.run/##XZJfb5swFMXf@RRXfrGtIpSEZH@isYlRr0MKiQRdE43w4BCzolGCbKKtYnz2zEDWir1Y1rm/c6597eq5fjyV9iVz9peCPx2OHLh5WO4Ip46zIwdq7JyrrpbqJGtxJAS5nz3G2N2dv1pvwgjdpDRG83ffgq395v307ffJbIGsLC@PJKVJdpKQQl6CgjzDgD@k9JI/VToKpDCMWqg65UoocDDGeyNGnh96Lti2jUxAvsfAC5kboAScj1DLs9DIrbd6gMlkemVgtXnQ2OaWjagtAzdkwAI/itzQZ1EH2zYAzGfdqntMF4v5bGov/vdt3fU9vPbWvoDdw7@TzSFg65HFh6@uPsLI0SuzVy0aHBkvlDD0XUd3h1gKSwku00ci8T5GxLr5RLuYYdNbSdftTx9AsQmdlVo/5OlcKUKhH7SWulm/JFuqKvK6yEuhkcQwOkg/sMlL9UvIEbo0uplcC87LxgHctcV9VQp1LmpdzYhOob1WybysSYYz0vDWbA4t1fVmIFsg4nclUv1tltAMkS21AJoYfeF5gUy0@cmfURIPvOMMTNJievkL "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~39~~ 34 bytes ``` ØB“¡Œ5a`@ẓRɼ9ẓ“%-/İ"aU5®’ṃyḟ⁶ṢɗⱮ⁸E ``` [Try it online!](https://tio.run/##y0rNyan8///wDKdHDXMOLTw6yTQxweHhrslBJ/dYAimgoKqu/pENSomhpofWPWqY@XBnc@XDHfMfNW57uHPRyemPNq571LjD9f///9FK4a4KjkGuCq6@nsHBjkGersFKOgpKxsYKCgomRiBSwdjY0NTUxMjQ2FQpFgA "Jelly – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~38~~ 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εðK.•2Θ`ĆĀÑεÉ•u6«•B/óÕ¦•…CN9«‡{}Ë ``` [Try it online](https://tio.run/##yy9OTMpM/f//3NbDG7z1HjUsMjo3I@FI25GGwxOBQp1AgVKzQ6uBlJP@4c2Hpx5aBmQ@aljm7GcJEl1YXXu4@///aKVwVwXHIFcFV1/P4GDHIE/XYCUdJWNjBQUFEyMQqWBsbGhqamJkaGyqFAsA) or [verify all test cases](https://tio.run/##bZK9SgNBEIBfZdn6UJNLBG1k3QxmcH/C7l4kBkEFCxsVNIKIkEoQKwvBVos0NoL4AjlrH8IXiXN3OZOLNre333w7P3t3en5weHw0ueR4cja4WGd846oVcTu4mO4mXx/p2/bS9/Cl/vW0/3n7OUwfCN0RGKyOX2nZXE7f08fxiF6/hyNp1jL6fH2T3k@iSb/PJTopWBzHPOIogUkHQvO9iPV5S6ouW1mpFTGmbJfCtgVFdAeYcMBAo/fCIXiS4pgx1qhnT0pZazYb9Vrc/PV3hAlsViTiGgIrG2gwDaZQkbUF1Zo3c1CfIV@YlLDtbMdq6zpt9EDmAtK/ItJWWW9pyZutolLM2km0D1lUKNUjMVHBCS28TBQaDL3p7YAEQwGFuyKgNSS2wEAyjwoRacx2T9FRZ73QaLI2qUmALGQ8mXSkzIvGBwxJKGg@0gLSpRjASdejXpUqklbRLsyJRlQzVtA0I31g92eoDP43VkVGs7WoZigXO47@EaXAGCzLL6BpeTpnPKWkawwibz/6w0jd@wE). **Explanation:** ``` ε # Map each value in the (implicit) input-list by: ðK # Remove all spaces .•2Θ`ĆĀÑεÉ• # Push compressed string "abemwgilorsuz" u # To uppercase: "ABEMWGILORSUZ" 6« # Append a 6: "ABEMWGILORSUZ6" •B/óÕ¦• # Push compressed integer 48333917025 …CN9« # Append "CN9": "48333917025CN9" ‡ # Transliterate; map all characters in "ABEMWGILORSUZ" in the # map-string to "48333917025CN9" at the same indices { # Then sort all characters } # Close the map Ë # And check if both are equal (which is output implicitly) ``` [See this 05AB1E tip of mine (sections *How to compress strings not part of the dictionary?* and *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•2Θ`ĆĀÑεÉ•` is `"abemwgilorsuz"` and `•B/óÕ¦•` is `48333917025`. ]
[Question] [ *The shortest code to pass all possibilities wins.* In mathematics, the [persistence of a number](http://en.wikipedia.org/wiki/Persistence_of_a_number) measures how many times a certain operation must be applied to its digits until some certain fixed condition is reached. You can determine the additive persistence of a positive integer by adding the digits of the integer and repeating. You would keep adding the digits of the sum until a single digit number is found. The number of repetitions it took to reach that single digit number is the additive persistence of that number. **Example using 84523:** ``` 84523 8 + 4 + 5 + 2 + 3 = 22 2 + 2 = 4 It took two repetitions to find the single digit number. So the additive persistence of 84523 is 2. ``` You will be given a [sequence](http://en.wikipedia.org/wiki/Sequence) of positive integers that you have to calculate the additive persistence of. Each line will contain a different integer to process. Input may be in any [standard I/O methods](https://codegolf.meta.stackexchange.com/q/2447/62402). For each integer, you must output the integer, followed by a single space, followed by its additive persistence. Each integer processed must be on its own line. ## Test Cases --- **Input Output** ``` 99999999999 3 10 1 8 0 19999999999999999999999 4 6234 2 74621 2 39 2 2677889 3 0 0 ``` [Answer] ## K - 29 Chars Input is a filename passed as an argument, 29 chars not including filename. ``` `0:{5:x,-1+#(+/10_vs)\x}'.:'0:"file" ``` * 35 -> 31: Remove outside function. * 31 -> 29: Remove parens. [Answer] **Python 84 Chars** ``` while 1: m=n=int(raw_input());c=0 while n>9:c+=1;n=sum(map(int,str(n))) print m,c ``` [Answer] ## Haskell, 100 characters ``` p[d]=0 p d=1+(p.show.sum$map((-48+).fromEnum)d) f n=n++' ':shows(p n)"\n" main=interact$(f=<<).lines ``` [Answer] ## Python (93 bytes) ``` f=lambda n,c:n>9and f(sum(map(int,str(n))),c+1)or c while 1:n=int(raw_input());print n,f(n,0) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~10~~ 15 bytes +5 bytes for horrible I/O requirement ``` m(wΓ·,LU¡oΣdr)¶ ``` [Try it online!](https://tio.run/##yygtzv7/P1ej/NzkQ9t1fEIPLcw/tzilSPPQtv///1siAJehAZcFl6ElVsBlZmRswmVuYmZkyGVsyWVkZm5uYWHJZQAA "Husk – Try It Online") ### Explanation To support multiple inputs, we need to use `m(₁r)¶` (where `₁` is the function doing the interesting computation): ``` m(₁r)¶ -- expects newline-separated inputs: "x₁␤x₂␤…␤xₙ" ¶ -- split on newlines: ["x₁","x₂",…,"xₙ"] m( ) -- map over each string ( r) -- | read integer: [x₁,x₂,…,xₙ] (₁ ) -- | apply the function described below ``` The function `₁` does the following: ``` wΓ·,LU¡(Σd) -- input is an integer, eg: 1234 ¡( ) -- iterate the following forever and collect results in list: ( d) -- | digits: [1,2,3,4] (Σ ) -- | sum: 10 -- : [1234,10,1,1,1,… U -- keep longest prefix until repetition: [1234,10,1] Γ -- pattern match (x = first element (1234), xs = tail ([10,1])) with: · L -- | length of xs: 2 , -- | construct tuple: (1234,2) w -- join with space: "1234 2" ``` [Answer] ### bash, 105 chars ``` while read x do for((i=0,z=x;x>9;i++))do for((y=0;x>0;y+=x%10,x/=10))do : done x=$y done echo $z $i done ``` Hardly any golfing actually involved, but I can't see how to improve it. [Answer] ## Haskell - 114 ``` s t n|n>9=s(t+1)$sum$map(read.(:[]))$show n|1>0=show t f n=show n++" "++s 0n++"\n" main=interact$(f.read=<<).lines ``` [Answer] ## Ruby, 85 Chars ``` puts $<.map{|n|v=n.chop!;c=0;[c+=1,n="#{n.sum-n.size*48}"] while n[1];[v,c]*' '}*"\n" ``` I had to borrow the "sum-size\*48" idea from Alex, because it's just too neat to miss (in Ruby at least). [Answer] ## Golfscript, 40 chars ``` n%{.:${;${48-}%{+}*`:$,}%.,1>\1?+' '\n}% ``` [Answer] ## J - 45 Chars Reads from stdin ``` (,' ',[:":@<:@#+/&.:("."0)^:a:)&><;._2(1!:1)3 ``` [Answer] ## c -- 519 **(or 137 if you credit me for the framework...)** Rather than solving just this one operation, I decided to produce a framework for solving **all persistence problems**. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> typedef char*(*O)(char*); char*b(char*s){long long int v=0,i,l=0;char*t=0;l=strlen(s);t=malloc(l+2); for(i=0;i<l;i++)v+=s[i]-'0';snprintf(t,l+2,"%lld",v);return t;} int a(char**s,O o){int r;char*n;n=o(*s);r=!strcmp(*s,n);free(*s); *s=n;return r;} int main(int c, char**v){size_t l, m=0;char *d,*n=0;O o=b;FILE*f=stdin; while(((l=getline(&n,&m,f))>1)&&!feof(f)){int i=0;n=strsep(&n,"\n"); d=strdup(n);while(!a(&n,o))i++;printf("%s %d\n",d,i);free(d);free(n);n=0;m=0;}} ``` **Only the two lines starting from `char*b` are unique to this problem.** It treats the input as strings, meaning that leading "0"s are not strip before the output stage. The above has had comments, error checking and reporting, and file reading (input must come from the standard input) striped out of: ``` /* persistence.c * * A general framework for finding the "persistence" of input strings * on opperations. * * Persistence is defined as the number of times we must apply * * value_n+1 <-- Opperation(value_n) * * before we first reach a fixed point. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../getline.h" /* A function pointer type for operations */ typedef char*(op_func)(char*); typedef op_func* op_ptr; /* Op functions must * + Accept the signature above * + return a point to a newly allocated buffer containing the updated str */ char* addop(char*s){ int i,l=0; long long int v=0; char *t=NULL; /* protect against bad input */ if (NULL==s) return s; /* allocate the new buffer */ l = strlen(s); t = malloc(l+2); if (NULL==t) return t; /* walk the characters of the original adding as we go */ for (i=0; i<l; i++) v += s[i]-'0'; //fprintf(stderr," '%s' (%d) yields %lld\n",s,l,v); snprintf(t,l+2,"%lld",v); //fprintf(stderr," %lld is converted to '%s'\n",v,t); return t; } /* Apply op(str), return true if the argument is a fixed point fo * falsse otherwise, */ int apply(char**str, op_ptr op){ int r; char*nstr; /* protect against bad input */ if ( NULL==op ) exit(1); if ( NULL==*str ) exit(4); /* apply */ nstr = op(*str); /* test for bad output */ if ( NULL==nstr ) exit(2); r = !strcmp(*str,nstr); /* free previous buffer, and reasign the new one */ free(*str); *str = nstr; return r; } int main(int argc, char**argv){ size_t len, llen=0; char *c,*line=NULL; op_ptr op=addop; FILE *f=stdin; if (argc > 1) f = fopen(argv[1],"r"); while( ((len=getline(&line,&llen,f))>1) && line!=NULL && !feof(f) ){ int i=0; line=strsep(&line,"\n"); // Strip the ending newline /* keep a copy for later */ c = strdup(line); /* count necessary applications */ while(!apply(&line,op)) i++; printf("%s %d\n",c,i); /* memory management */ free(c); free(line); line=NULL; llen=0; } } ``` A little more could be saved if we were willing to leak memory like a sieve. Likewise by `#define`ing return and the like, but at this point I don't care to make it any uglier. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~21~~ 17 bytes ``` {⍵≤9:0⋄1+∇+/⍎¨⍕⍵} ``` -4 bytes from Jo King. [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qHeuJQIoGHMBBQwNFAxBtIWCAZhriRUomIAkzYyMTRSMQCxzEzMjQwjT2BJCG5mZm1tYQE01AJqm8ahvqlsQkAgI0HzUNsHQyMJcwdjkf/Wj3q2POpdYWhk86m4x1H7U0a6t/6i379CKR71TgVK1/9OAioECj7qaH/WuedS75dB640dtE4HmBAc5A8kQD8/g/2kKSI7jSlMwNAASFiAGdvcDZUCOB1JglwNpY5AY1M1AlgEA "APL (Dyalog Unicode) – Try It Online") ``` {s←+/⍎¨⍕⍵⋄⍵≤9:0⋄1+∇s} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qHeuJQIoGHMBBQwNFAxBtIWCAZhriRUomIAkzYyMTRSMQCxzEzMjQwjT2BJCG5mZm1tYQE01AJqm8ahvqlsQkAgI0HzUNsHQyMJcwdjkf3UxkKOt/6i379CKR71TH/VufdTdAiI7l1haGQDZhtqPOtqLa/@nAdUBVT3qan7Uu@ZR75ZD640ftU0Emhcc5AwkQzw8g/@nKSA5kitNwdAASFiAGNj9AZQBeQJIgX0ApI1BYlC3A1kGAA "APL (Dyalog Unicode) – Try It Online") ## Explanation ``` {s←+/⍎¨⍕⍵⋄⍵≤9:0⋄1+∇s} ⍵ → input ⍕⍵ convert ⍵ to string ⍎¨ execute each character(getting digits) +/ reduce to sum of digits s← assign to s ⍵≤9: if number is single digit 0 return 0, stop recursion 1+∇s Otherwise return 1+f(sum) ``` [Answer] ## J, 74 chars ``` i=:<;._2(1!:1)3 i&((],' ',":@(0 i.~9<[:".([:":[:+/"."0)^:(i.9)))@>@{~)i.#i ``` ### Edits * **(86 → 83)** Some Caps `[:` to Ats `@` * **(83 → 79)** Unneeded parentheses * **(79 → 75)** Changing `0".` to `".` simplifies things * **(75 → 74)** Better Cutting ### E.g ``` i=:<;._2(1!:1)3 74621 39 2677889 0 i&((],' ',":@(0 i.~9<[:".([:":[:+/"."0)^:(i.9)))@>@{~)i.#i 74621 2 39 2 2677889 3 0 0 ``` [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 16 bytes **Solution:** ``` {x,#1_(+/10\)\x} ``` [Try it online!](https://tio.run/##y9bNS8/7/7@6QkfZMF5DW9/QIEYzpqLWyMzc3MLCUuH/fwA "K (ngn/k) – Try It Online") **Explanation:** ``` {x,#1_(+/10\)\x} / the solution { } / lambda taking implicit x ( )\x / iterate until convergence 10\ / split into base-10 (123 => 1 2 3) +/ / sum 1_ / drop first result (iterate returns input as first result) # / count length of result x, / prepend x (original input) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` żDS$Ƭ€Ẉ’ƊK€Y ``` [Try it online!](https://tio.run/##y0rNyan8///oHpdglWNrHjWtebir41HDzGNd3kB25P///y0RQEfB0EBHwQJIWWIFOgpmRsYmOgrmJmZGhjoKxkABIzNzcwsLIMMAAA "Jelly – Try It Online") Takes input as a list of integers. [+3 bytes](https://tio.run/##y0rNyan8///h7i1hh7Ye3eMSrHJszaOmNQ93dTxqmHmsyxvIjvz//7@SkpIlAnAZGnBZcBlaYgVcZkbGJlzmJmZGhlzGllxGZubmFhaWXAZAIwA) to input as a multiline string. +3 bytes (or +6) for restrictive I/O formats, yay ## How it works ``` żDS$Ƭ€Ẉ’ƊK€Y - Main link. Takes a list l on the left Ɗ - To l: $ - Group the previous 2 links into a monad f(n): D - Digits S - Sum Ƭ€ - Over each n in l, repeatedly apply f(n) until a fixed point, yielding [n, f(n), f(f(n)), ...] Ẉ - Get the length of each loop ’ - Decrement each ż - Zip the loop lengths with l K€ - Join each by spaces Y - Join by newlines ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `aj`, ~~9~~ 8 bytes ``` ƛ⁽∑↔L‹"Ṅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJhaiIsIiIsIsab4oG94oiR4oaUTOKAuVwi4bmEIiwiIiwiOTk5OTk5OTk5OTlcbjEwXG44XG4xOTk5OTk5OTk5OTk5OTk5OTk5OTk5OVxuNjIzNFxuNzQ2MjFcbjM5XG4yNjc3ODg5XG4wIl0=) Explanation: ``` # Treat all the inputs as a list (`a` flag) ƛ # On each item (n) in that list ⁽ # Create a single element lambda ∑ # That sums the digits of a number ↔ # Apply that function on n until it doesn't change # and return the intermediate values in a list L # Get the length of that list ‹ # Decrement it to ignore the last time the function is called " # Pair that with n Ṅ # Join the pair by a space # Join the mapped inputs by new lines (`j` flag) # Implicitly print ``` [Answer] I think this is about the best I can come up with. **Ruby 101 Chars** ``` f=->(n){n.sum-n.size*48} $<.each{|l|i=0;i+=1 while(i+=1;n=f[(n||l.chop!).to_s])>10 puts "#{l} #{i}"} ``` [Answer] **PARI/GP 101 Chars** ``` s(n)=r=0;while(n>0,r+=n%10;n\=10);r f(n)=c=0;while(n>9,c++;n=s(n));c while(n=input(),print(n," ",f(n))) ``` Unfortunately, there's no input function for GP, so i guess this lacks the IO part. :( Fixed: Thanks Eelvex! :) [Answer] **Javascript - 95** ``` i=prompt();while(i>9){i=''+i;t=0;for(j=0;j<i.length;j++)t+=parseInt(i.charAt(j));i=t;}alert(t); ``` EDIT: Whoops does'nt do the multi-lines [Answer] # J, 78 ``` f=:[:+/"."0&": r=:>:@$:@f`0:@.(=f) (4(1!:2)~LF,~[:":@([,r)".@,&'x');._2(1!:1)3 ``` Recursive solution. Reads from stdin. **Writes to stdout**, so cut me some slack - it does take an extra 18-ish characters. [Answer] ## Perl - 77 characters ``` sub'_{split//,shift;@_<2?0:1+_(eval join'+',@_)}chop,print$_,$",(_$_),$/for<> ``` [Answer] ### scala 173: ``` def s(n:BigInt):BigInt=if(n<=9)n else n%10+s(n/10) def d(n:BigInt):Int=if(n<10)0 else 1+d(s(n)) Iterator.continually(readInt).takeWhile(_>0).foreach(i=>println(i+" "+d(i))) ``` [Answer] # [JavaScript](https://nodejs.org), ~~57~~ 47 bytes *-10 bytes thanks to @l4m2!* ``` f=(s,c=0)=>s>9?f(eval([...s+""].join`+`),++c):c ``` [Try it online!](https://tio.run/##fdDRCoMgFAbg@z1FeKXYTC0sB7YHGYPCVRSRY45e39XVwqz/@jv/4ZyhnmurP/37e53Mq3GuVdDGWlGkSlvKewubuR7hgxBiMQBPMph@qnCFYow1ummnzWTN2JDRdLCFQP4DEIq2SZIovXicUV9tOfN5cahXTnftMpi1ZOGZzwVPs4MFC@c@zzPBWdiHeCrPTt1xLvK8KIIzoUfS88@4Hw "JavaScript (Node.js) – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 11 bytes ``` hÅ_Σ]▀£(k ? ``` [Try it online!](https://tio.run/##y00syUjPz0n7/z/jcGv8ucWxj6Y1HFqska1g//@/JQJwGRpwWXAZWmIFXGZGxiZc5iZmRoZcxpZcRmbm5hYWllwG/wE "MathGolf – Try It Online") ~~Incredibly inefficient, but we don't care about that. Basically, using the fact that the additive persistence of a number is smaller than or equal to the number itself.~~ Uses the fact that the additive persistence is less than or equal to the number of digits of the number. Passes all test cases with ease now. The input format, while suboptimal for some languages, is actually the standard method of taking multiple test cases as input in MathGolf. Each line of the input is processed as its own program execution, and output is separated by a single newline for each execution. ## Explanation (using `n = 6234`) ``` h push length of number without popping (6234, 4) Å loop 4 times using next 2 operators _ duplicate TOS Σ get the digit sum ] wrap stack in array this gives the array [6234, 15, 6, 6, 6] ▀ unique elements of string/list ([6234, 15, 6]) £ length of array/string with pop (3) ( decrement (2) k ? push input, space, and rotate top 3 elements to produce output (6234 2) ``` [Answer] # Julia, 92 (29) bytes ``` f(n)=n>9&&(f∘sum∘digits)(n)+1 ``` Edit: With correct printing it's 92: ``` f(n)=n>9&&(f∘sum∘digits)(n)+1 while(n=parse(Int128,readline()))≢π println("$n ",f(n)%Int)end ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~8~~ 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ªwæMε∞ö?îm⌐ ``` [Run and debug it](https://staxlang.xyz/#p=a677914deeec943f8c6da9&i=99999999999%0A10%0A8%0A19999999999999999999999%0A6234%0A74621%0A39%0A2677889%0A0&a=1) +3 bytes thanks to @Khuldraeseth (the first answer didn't have compliant output) [Answer] # [Jq](https://stedolan.github.io/jq/) `-r`, 52 bytes ``` [while(length>1;explode|map(.-48)|add|@text)]|length -r # take one number per line, converting it to a string explode # the character codes |map(.-48) # subtract ascii zero from each |add # sum the elements |@text # back to text, (shorter than # tostring and tojson) while(length>1; ) # produces *all* the intermediate # results while the string length>1 [ ] # collected into an array |length # the length of these results ``` Not answering the multiplicative persistence now because jq doesn't have a `product` builtin :) [Jq play it!](https://jqplay.org/s/HjHvWmd9d7) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ε.ΓSO}g}ø» ``` -3 bytes thanks to *@Steffan* Input as a list of integers. [Try it online.](https://tio.run/##yy9OTMpM/f//3Fa9c5OD/WvTaw/vOLT7//9oSwTQMTTQsdAxtMQKdMyMjE10zE3MjAx1jC11jMzMzS0sLHWAOkxMjYxjAQ) **Explanation:** ``` ε # Map each integer in the (implicit) input to: .Γ # Loop until the integer no longer changes, # keeping all intermediate steps in a list: S # Convert the integer to a list of digits O # Sum those digits together }g # After the inner loop: pop and push the length }ø # After the outer map: zip/transpose it with the (implicit) input to create a # list of pairs » # Join each pair by a space, and then the list of strings by newlines # (after which the result is output implicitly) ``` [Answer] # [Knight](https://github.com/knight-lang/knight-lang), 54 bytes ``` ;=iP;=r 0;W<1Li;=s 0;Wi;=s+sA Ai=iGi 1Li;=i+""s=r+1rOr ``` [Try it online!](https://tio.run/##rVltV9vKEf5s/4rFOdhavySSoOfcWsgckgscTgnkQtJ8ADcRsgx7KsuuJMOlhP71dGb2RSvbpE17@SBpd@f12dmZWRMPbuP4@yuRxelykuwV5UTMX9@NmvZMKm5qU3H5uEhWiHKR3damSjGTNJNkKrKEpSlL59ktPZpm9uPZp/fMq4aXHy@YXw3/enDBdqvh0dk79ks1vPjEvIr46PTSoj37dGqRfjp7f3D5F6fgzMFHm/3L@xM3qweXoFYuxndRzrq8YrCpwFYjYjRiu9Xa2eFnXMxgkTz6xvB7b2@FBtUQDboJNGnKkbBG8/b8/JSI8LFPTg7RN8uQi2NJAPyWrfdRukw4v8rGvNkkP2BXrsbhRevw/Mj5HoTiQxDmzA0@73mnIggL/MR3rzhgByIUx4LRgui1WkWY97z8PP/OgbkVSHldEJhEMxai5KDZBPWLKC8Sh7OnZkNkJRNBswGzZEqfdafLLIYZYo5hXM4W/WKRXfnj8Mntu88goyFAHNHD28WJN29QvFiwhztRJsUiipNmA77TxIF5YHekGX3Wui6vs@vpdc6enq/GDh@@anEypSGmzDHWhqzzqsOZFKFnt2D2OoPpXk/OgJ2NJC0Se@JZmhPfJfHf2XSes2w5u0nyQtnDHFFMxK0otVTQju54feORfHeZ57Ie6yrLez3OBqzjdkAFWio4y5NymWdMB49ko/gJVm24j3IR3aSJtgKMSOcPSe7EoE8bwr59Y9q4mEYxAfGlwxU8YoPrIvT6sEehmV6xDo@jClsgySbLhYNbyhSmAwajdYNlciikNGnGdadT2dTqyE0DZvDAGMVACCQT@AbLFlFRsvIuAWFRXgKx2oCuRhQ3NOboiTbWOmMvGgtPj9NGNyowyHwM3VLMMzAbI9Ydg2mxRqRYLhYIONdRpWds@O34A9gtsFGGDuVFBnEMiQ0jV1kuUfnYMadfThzhBCa5ISY3NFMHGeVF6aqDdqOpUZrOY2fX7XscHcRp4wQ5mC3TNMofbUer/bmwtudDx1hGChX/MlvhJhUeqlBJYZOnB4dv3339bev013PLYVvsjdgo11@Xu1UTfHxy@YLEMslJZJRN2D@WkR6i2Htbxc66CgnAccdgcbIBC2LerTPXaZ4pVebLDHcoUMm5W84LR@dKOgAQ2qWIGa3eLKdX/u5Y2SE3uk3pwRhQLOBYlVMHSMH/7TSdtHTeoeLURyGrAuBQGAGy7En9Nbo95u3U/UTnMRb3WavMl0kLYtDMY0jC/DSCDIILLYysVgUC@om@q/pEcHx5O5@nsHJTR@BFXyu3fuRQ9@c9ss28WTMzRRuzP9RGCNpynqaObWqfuX2oEP@DydmayViF3x98OOtjLZaBBsOTK891XQgncAWGelSIfyZfSoavwIpRy1tEAEZ9fPj03Ak9XdIxw2FVxxc9ffnaAYKjk9PDLptCcgwaJrSVPkzDcbTop0lGHYCFlW6fJGZw7l4CY5URaxOWNiw4jqBeAmrxHmERQFERuGjyRjxbrOwAgSTGVQpBmMQY1RQPoozvnC4gs9ZtAUZM/cVYpzoHnSFDLZIgRECxX4MszNvklBKvOsZayPKAqnBFQW1pmWPpos70asyfqjCDBopyu1R8AYrrsnPIeA5vu79P8a@i/ACUIFVidJuUKTSVTpv2so07hCVyIjIeiKnj0H5iQxDf5WhLH@KUc7nNoRtstBVenNoAqe9Q6pOdI2YDBUig7UWQVO6srHxb@SPpzcq7agU5bYgNzVegwWiA@AsX80WSOZbifitvUasAVoUzWSkhHkPf3f2F5lVz4ciOZAqmT9ApaOEgZPvY3wE59A40Qh2gWoeXA5OsF1IrhCcWKLmCG@SQLoIaJXRD5ts9SwVj5clv4EnyO7RxeNrX/Nyq7TrdHbYwk60Rnq6FB2hJ67hY5L92hqpP3BDIJvOpCtQ6o7bYwRrEdREajXZ51ViupUPNeknNobNdIGP9MKwzA5zQ@th6IZPyVkWqF7C8JFGmxL5UwlTNsndA5RaFwnmFAh4MefFB0OR@1qBj7TZduAYDJB3LNvea2u2GNmv7dbcAexwYcaaPWm6ZvywLvfsmJmSvJw3qGYMoT0K@xJSMoWVtj@ymG/XdlrdXpIa@n@lY8uWeY/9Lh0FuAFHhNJ7yUHvp882hGkelfqmu0@tVMHH9jbI4dKN9epcqRyi/BmvRaUU7tup1eyVTt9qdDSislucNOHTXcJD7ugmF2QbXukQT2kKIAWqQQxky7FzDJQ@JgsGA5CmgqGSubrREtKyd/jc/BObNZmC2f8i0vZnpb4RmzSF5daA53/YyULBL1EM28AzKRAvQe3DOBh6cMc8m9n@Seg/SY402DJGU9A71jKshJ6D9kauw9jm1K92Q8G@uHghaJFfgjkAJFksMfOOV4S7Jk07Bsjn00CItRcYeokfAjU3mcCctk9skB57FPEuyUkR4i4CTPGcPCbuL7hMgVIKQvGSzKFtC@Dy@xln07gYRBygIiWKZlvijASk3CU@TDGwarXIFMpvPkKyIR3kvU7ovG2LI9mpULt3PoxRr4yN4nU3SZMK@VmZ/NVKe8Es2ZpaSypkRChsM9JgTeUORdi3Tn00e3KNgXSl8mPRqeTGsZ8V9Zh/@PfsYIOtQ/S7XZpJgn9UaRZrsMysbogxXcuqS68s6gLRbIVQbqwsawaHE0JpP5kM2S2bxAsMsY6Ov@/@vK6M/wJWRdmVrgy@h8kW5sv8y@lLrBpNxeZ/VCHxD4esCurXJzmpg3NOZxxZgzGtX6Q992VQb9m1OlUoM/7f/hl/lIEuM4Q86Q5u61uau0oZV1q0v//RFRve21U0G6Rq124xJhUSDEsdhjdtKk8iBFL2eYZMmfwb35K9edqNZ847ZvYtiO6l37Uhq8e/7wx0LlmN5ZQitDqtnF6D1O1KmLh59cxZ2ag3tpQR6RWiwWvL8TSVvh5s@wDfcuzT5HxoiNAzfuBWxaf5NO2T3Rj54iFp7HjZJ1CDI@JeL9CKKnjoJoH2STCNIkuCZ7jBFBotiQj8iRXEJZaqzHXew58QZzl64xaIwUwOhG1Q/JMwikWGzyqL8Nu6T0G4Xvu85/lxF90v8N4/jkjX1a9zzd@/PG//@DQ) [Answer] # [Ly](https://github.com/LyricLy/Ly), 21 bytes ``` 0s+1[pSy,![lu;]&+l`s] ``` [Try it online!](https://tio.run/##y6n8/9@gWNswuiC4UkcxOqfUOlZNOyehOBYoDAA "Ly – Try It Online") A pretty straight forward interpretation of the challenge rules this time. ``` 0s+1[pSy,![lu;]ç] 0s - initialize the backup cell to 0 (iteration count) + - load input number, absorbing the 0 on the stack 1 - push a truthy value to enter loop [p ] - infinite loop S - convert number on top of stack to digits y - push the number of digit (stack size) `! - decrement and convert truthiness [ ] - if/then, executes is number is a single digit lu; - load backup cell, print as number, end program &+ - sum the digits on the stack l`s - load backup cell (iterations) increment and save ``` ]
[Question] [ Given an integer \$n \geq 2\$, print a triangle of height \$n\$ of (triangles of height \$n\$ of asterisks), as in [this SO question](https://stackoverflow.com/q/69796358/257418). For \$n=2\$, print: ``` * *** * * * ********* ``` For \$n=3\$, print: ``` * *** ***** * * * *** *** *** *************** * * * * * *** *** *** *** *** ************************* ``` For \$n=4\$, print: ``` * *** ***** ******* * * * *** *** *** ***** ***** ***** ********************* * * * * * *** *** *** *** *** ***** ***** ***** ***** ***** *********************************** * * * * * * * *** *** *** *** *** *** *** ***** ***** ***** ***** ***** ***** ***** ************************************************* ``` And so on. Some rules: * I write "print", but a function returning a string or list of lines is fine too. * Trailing whitespace on each line is allowed, but not leading whitespace. * Trailing blank lines are allowed. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): write the shortest program you can, measured in bytes. [Answer] # [Python 3](https://docs.python.org/3/) with [numpy](https://numpy.org/doc/1.21/), ~~79~~ 74 bytes ``` lambda n:where(kron(*[c_[:n]>=abs(r_[1-n:n])]*2),*'* ') from numpy import* ``` [Try it online!](https://tio.run/##FcnBCsIwDADQu1@RW5Oigu42mD9Sx@i0ZdU1KbEi@/qqx8crW12EuxaHa1t9nu8euP8sQQM@VRitu02u5/Ey@PmFOrnTgX@k0Z5pb40FQ7uokoHfuWyQchGttkVRWBMHSAwRO@qhaOKKxhwfkhj/R9S@ "Python 3 – Try It Online") -5 thanks to ovs, with the use of `where`. Step-by-step example of how it works: ``` >>> from numpy import* >>> (n:=2) 2 >>> (Y:=c_[:n]) array([[0], [1]]) >>> (X:=r_[1-n:n]) array([-1, 0, 1]) >>> (Z:=Y>=abs(X)) # Broadcasts. array([[False, True, False], [ True, True, True]]) >>> (A:=kron(*[Z]*2)) # Listify, double, and unpack to give the same argument twice. array([[False, False, False, False, True, False, False, False, False], [False, False, False, True, True, True, False, False, False], [False, True, False, False, True, False, False, True, False], [ True, True, True, True, True, True, True, True, True]]) >>> (B:=where(A,*"* ")) # Select asterisk for true and space for false. array([[' ', ' ', ' ', ' ', '*', ' ', ' ', ' ', ' '], [' ', ' ', ' ', '*', '*', '*', ' ', ' ', ' '], [' ', '*', ' ', ' ', '*', ' ', ' ', '*', ' '], ['*', '*', '*', '*', '*', '*', '*', '*', '*']], dtype='<U1') ``` [Answer] # [J](http://jsoftware.com/), 37 31 bytes ``` ' *'{~[:,./^:2[:*/~i.>:/|@i:@<: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1RW01Kvroq109PTjrIyirbT06zL17Kz0axwyrRxsrP5rcqUmZ@QrpCkYQRjq6jABY3QBE5jAfwA "J – Try It Online") *-6 after seeing the phrase "Kronecker product" in m90's python answer, realizing that's what I was doing, and finding a golfier implementation in [this essay](https://code.jsoftware.com/wiki/Essays/Kronecker_Product).* [Answer] # [MATL](https://github.com/lmendo/MATL), ~~29~~ ~~16~~ 15 bytes ``` ZvG:!<~PtX*42*c ``` [**Try it online!**](https://tio.run/##y00syfn/P6rM3UrRpi6gJELLxEgr@f9/YwA) ### How it works Consider input `3` as an example. The stack is shown upside down, with the most recent element below. ``` Zv % Implicit input. Symmetric range % STACK: [1 2 3 2 1] G: % Push input again. Range % STACK: [1 2 3 2 1], [1 2 3] ! % Transpose % STACK: [1 2 3 2 1], [1 2 3] <~ % Less than?, negate; element-wise with broadcast % STACK: [1 1 1 1 1 0 1 1 1 0 0 0 1 0 0] P % Flip vertically % STACK: [0 0 1 0 0 0 1 1 1 0 1 1 1 1 1] tX* % Duplicate. Kronecker product % STACK: [0 0 0 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 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1] 42* % Multiply by 42 (ASCII for '*'). Convert to char % Implicit display. Char 0 is displayed as space % STACK: [' * ' ' *** ' ' ***** ' ' * * * ' ' *** *** *** ' ' *************** ' ' * * * * * ' ' *** *** *** *** *** ' '*************************'] ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~160~~ ~~153~~ 148 bytes ``` p(c,n){n&&p(putchar(c),n-1);}r;t;l;i;f(n){for(r=0;r<n*n;p(10,1))for(t=r/n,l=r++%n,p(32,(n+~t)*(n*2-1)),i=t-~t;i--;p(32,n+~l))p(32,n+~l),p(42,l-~l);} ``` [Try it online!](https://tio.run/##VZDRbsIwDEXf@YoICeq0jqAFNmmm2ocMHqpAWaTMVGmmTavKp69LCwzIS2zf42vLWh207roKNLJseDqtoPr0@r1woCWySiW1jjxZMlRCQMqjA5fPya05ZqognWMqZV/1uZsx2twlyYSxgkWGwMnJyxg4zoKTRJN7dfJklKJBD7KV8haGrmWGVoWQ2s6wFx@FYZCiGYnw@oLf175@24pcNBkucIkrfMLnlgYgrCGgpwzv9t@BmdMlXIva/OyPJQz9cnbJ4nNKIkkG7jrpOo2Dx3niIG/pX61c0EsY98Rkt@ExCpY3ub8VPVjZAEIW9yeNL/@dG0R5hHa9el292Mf6hiO8ou2o7X51aYtD3amvPw "C (gcc) – Try It Online") *Saved 7 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* [Answer] # [C (gcc)](https://gcc.gnu.org/), 107 bytes ``` m,x,y;f(n){for(y=n*n;y--;)for(x*=x=m=2*n-1;x--;)putchar(abs(x%m-n+1)+y%n<n&abs(x/m-n+1)+y/n<n?42:x?32:10);} ``` [Try it online!](https://tio.run/##XcxBDoIwEEDRvccgwcwADVJwQ224iJvapGhiR0M1tiFc3QomLmT53@Jr1msdoy18EYQBwtHcBgiSMhKBMYFL@kx6aSXPiFXCL3p/PvRZDaBODnxqGeUV5iGlA22/VP6onKlreOu7mrfVDsUUrboQ4LgxwFHMIwfJkRIUM9RraNaw/4cpvrW5qt5F9voA "C (gcc) – Try It Online") -1 byte by [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~91~~ ~~86~~ 84 bytes -2 bytes thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn)! ``` lambda n:[f"{(o%n*'**'+'*').center(w:=2*n-1)*(o//n*2+1):^{w*w}}"for o in range(n*n)] ``` [Try it online!](https://tio.run/##FchLCsIwEADQvacYCpKZKVrabiTQk/iBqIkWdBKGQJDSs0f6li/98jvKeEpaw3SpH/e9Px2IPYdmwbgXNsymNWzo@PCSvWKx08By6Ikxdp3w0PZkb0vhsq5NiAoRZgF18vIoLHStW@qWAUeyO4Cks2RUqn8 "Python 3.8 (pre-release) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 76 bytes ``` ->n{(0...n*n).map{|i|((?**(i%n*2+1)).center(j=n*2-1)*(i/n*2+1)).center j*j}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNAT08vTytPUy83saC6JrNGQ8NeS0sjUzVPy0jbUFNTLzk1ryS1SCPLFiiga6gJlNJHlVLI0sqqrf1fUFpSrJAWbRzLxaWsYVQBVKqgYFIRZ6RrUqFt@B8A "Ruby – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` NθFθF⊕⊗ι«J×⊖⊗θ⁻κι×θιG↗↘θ* ``` [Try it online!](https://tio.run/##ZYqxDsIgFADn8hWkExgcXdqVpSYaY@oHtIgtEXiFgsYYvx2xujndXXJi7LyATqfU2CmGfTS99MTRGl3A4yx4YWOFl0baIM@EQ@x1pqKU4icqttFMLZBWGTkTLv9HRynDO2XjTK4Mq099Z7dUjYoD6McAllSn6aiGMTBccbjbn@etXJX5e6W0SeubfgM "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` Fθ ``` Loop over each row. ``` F⊕⊗ι« ``` Loop over each of the `2i+1` triangles in each row. ``` J×⊖⊗θ⁻κι×θι ``` Jump to the (bottom left of the) triangle. ``` G↗↘θ* ``` Draw the triangle. 24 bytes if a leading blank line is allowed: ``` NθFθ«M×⊖⊗θ⊗ιθF⊕⊗ι«G↖↙θ*← ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05orLb9IAchQqObi9M0vS9UIycxNLdZwSU0uSs1NzStJTdFwyS9NygHShZqaOgowTiaIA9LPCTbAMw9TPVAJ2FjOgPycyvT8PA2r0AKf1LQSHQUrl/zyPAizUEdBSUsJZA7EeiuQMIhby1X7/7/pf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` Fθ« ``` Loop over each row. ``` M×⊖⊗θ⊗ιθ ``` Jump to the end of the row. ``` F⊕⊗ι« ``` Loop over each of the `2i+1` triangles in each row. ``` G↖↙θ* ``` Draw the triangle. ``` ← ``` Move to the next triangle. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~82~~ 74 bytes ``` ->n{(r=1.step n+=n-1,2).map{|x|r.map{|y|((?**y).center(n)*x).center n*n}}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWqPI1lCvuCS1QCFP2zZP11DHSFMvN7GguqaipgjCqKzR0LDX0qrU1EtOzStJLdLI09SqgHEU8rTyamtr/xeUlhQrpEUbx/4HAA "Ruby – Try It Online") Good golfers copy, great golfers steal. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 25 bytes ``` d‹£²ʁƛ?%›‛***Ḣ¥⋏n?ḭd›*¥²⋏ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=d%E2%80%B9%C2%A3%C2%B2%CA%81%C6%9B%3F%25%E2%80%BA%E2%80%9B***%E1%B8%A2%C2%A5%E2%8B%8Fn%3F%E1%B8%ADd%E2%80%BA*%C2%A5%C2%B2%E2%8B%8F&inputs=3&header=&footer=) I think mirroring might help, but cannot think of how [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `C`, 15 bytes ``` ƛd‹?ɾ×*vømøĊ*;f ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=C&code=%C6%9Bd%E2%80%B9%3F%C9%BE%C3%97*v%C3%B8m%C3%B8%C4%8A*%3Bf&inputs=3&header=&footer=) ``` ƛ ; # Map 1...n to... ?ɾ # 1...input... ×* # Asterisks vøm # Each palindromised øĊ # Centered * # Repeated... d‹ # (2 * value) - 1 times f # Flatten # (C flag) output centered ``` 17 bytes without the flag by appending a `øĊ`. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~18 17~~ 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ÇÑÄ ïÈçYçÑ ûUÌÃû ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=x9HECu/I51nn0SD7VczD%2bw&input=MwotUg) ``` o_ÑÄ - range [0..input] *2+1 ï - pair each with itself È - then pass pairs by f(X,Y) ç - repeat result X times YçÑ - repeat '*' Y times ûNÑÉ - centre pad Ãû - centre pad all ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~111~~ 100 bytes ``` f=lambda n,b=['*'],p=1:p>2 and b or f(n,[f'{2*r*l+l:^{(2*n-1)**p}}'for r in range(n)for l in b],p+1) ``` [Try it online!](https://tio.run/##dYyxCsIwFAD3fsXbkrzGIamDBOKPFIWEGi3E1/DoIqXfHttFdHC9O6685sdE3alwrcnn8IxDANLR9wLFRRdvXDlbCDRAhIkhSdJ9EotFxtxmd12kRToYhVjWVaQtYRgJOND9JkntIO8gbrPWqPopkrTKNQCFR5olq@bLdH/N8cfUNw "Python 3.8 (pre-release) – Try It Online") Nowhere near the best Python 3 answers, but it's got recursion. See [my answer](https://stackoverflow.com/a/69804532/8164958) on the source SO question for an ungolfed version with the same mechanisms. *-11 bytes thanks to @ovs* [Answer] # [R](https://www.r-project.org/), 82 bytes ``` function(n)write(c(" ","*")[1+(z=outer(c(n:1,2:n),1:n,"<="))%x%z],1,(2*n-1)^2,,"") ``` [Try it online!](https://tio.run/##DcgxCoAwDAXQ3VOUQCFf45C6FT2J6CIWXCKUiuLlq298uSY39q6my7ZynMaGOx9l543JkVBLmLXjdzqvsud/LaqEaBCNJjROBPjHv4uocGitV6xBhAg1cUCTeED9AA "R – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), 39 bytes ``` YPZ0Xa-_.1X_M\,a(J*Z_M_*^yMMy)TRt"* "Jn ``` [Replit!](https://replit.com/@dloscutoff/pip) Or, here's a 41-byte equivalent in Pip Classic: [Try it online!](https://tio.run/##K8gs@P8/MiDKICJRN17PMCLeN0YnUaPaSysqsdY3Xiuu0te3UjMkqERJS0HJK@/////GAA "Pip – Try It Online") ### Explanation We create a structure out of 0's and 1's and then use it for both the micro- and macro-structure of the desired output. ``` YPZ0Xa-_.1X_M\,a a First command-line argument \, Inclusive range from 1 to that number M To each element of that range, map this function: a-_ a minus the function argument 0X That many 0's _ Function argument 1X That many 1's . Concatenate those two strings PZ Palindromize Y Yank the resulting list of strings into the y variable ``` For example, with an input of 3, `y` is `[00100; 01110; 11111]`. ``` (J*Z_M_*^yMMy)TRt"* "Jn MMy Map this function to each character of each string in y: y Take another copy of y ^ Split it into a list of lists of characters _* Multiply each character by the function argument M To each sublist of the resulting list, map this function: Z_ Transpose J* Join each sublist of the transposition into a single string ( )TR Transliterate the result: t Replace characters "10" "* " with characters "* " Jn Join on newlines ``` [Answer] # [Julia 1.0](http://julialang.org/), 68 bytes ``` ~n=2n-1 !n=[' '^(2n^2-j*~n-i)*rpad('*'^~i,~n)^~j for i=1:n,j=1:n][:] ``` [Try it online!](https://tio.run/##HYg9CgMhFAZ7T/G28oe1UEgjeJJlBcEEnsgX2SSQNF7dJDvFwEx9Nc7uPedA9LBOLIibJJmUR/K2mgHL2hw9FyWNTIPXAZ1Gpdv9II4uYK1/71vY5/mIQS5cBP0o/Ogtf9TC@ux@MJ4NSosryvwC "Julia 1.0 – Try It Online") I wish Julia had a `center` function output is a list of lines [Answer] # [Kotlin](https://kotlinlang.org), 186 bytes ``` val p={n:Int->for(p in n downTo 1)for(l in n downTo 1)for(g in n-1 downTo 1-n)for(c in n-1 downTo 1-n)print(when{p+Math.abs(g)<=n&&l+Math.abs(c)<=n->'*' g!=1-n||c!=1-n->' ' else->'\n'})} ``` [Try it online!](https://tio.run/##lVfNbuM2EL77KcY5JJJqy0iyKApjHaBdtEWALnJYH/dCS7QlRCYVklqvkfgB9kH6Yn2RdIak/mw5aYVAoocfPw6HMx@ZR2mKXLzOZnAvysrMQUiT5WIDa6nAZBxSvmZVYcBwbSBhmmuQaoR4JiAXhm@4ikf0@5PizPDUD8w1JDLlsJHFGpKMFQUXGz4nYGZMqeezGfVTd6wNSx75d0QhJE7kdvY0u7n9@ZfrG4IvVY72goNcg/FtbWf8M//GRccPEP/8@PtmAqVCA7AGjSPtvDzfZAYEEQUNE/3q9NiVacNVrh91OME2srv1fHmApwqjkEvhVvwHrlQs6gnn1kZP5BtR5FqR@6N2VD8dgtsTgvqJjgw1YdfQM0Xtq7UipH015qj/OHsEAy@3hi5Jny4693TW@OHsGt9a75trhzfiMNB7pj/qf4Ywdq3dzwDITtD/nKKGg9Tf0Lc@PeiJV@d9HHDurKvR@0@d3f/B457j73g84P@7jp8uI/q/j03IX0UKWgIWNnyRWw6qQmVoc/Uedio3HC5sDl9MYFWRvqwrkZAaEExxUylBwslAo7hgAxO/yFE0UWBQYlFpck3INbbBSBnX7EvF8oIG7DKcRJcsQcUSwFmS2YF@HEqo3PHUTY4qDQVnaX/YKeWqYOLRT88Ur0laIAmb1@opifHcL5WkX2dSkewTuFRyo9gW9rLCU0BMYMuZrhTqPcrjao8wp4m/fy@ZSOkY8MGBXW4y5N9uuTAIQjuRJVzrQFTbFVdzPHpMCM@jEYAXDJrddVL0SmZQkIXGID9VueITiOMYwXTSBL6T3PAjUrkTSwnXIRH2KP02@Nj6kTWb53MRP0fW0FmGjZJVabdatPwtn2e0qJZyet2QTp2l4e6zJ7KotsIdP9zNNekC01yXBdvbXjw7FUtwOTHcr@1x1UV6DzQIztPuEe1D0MXi7tXHt5u@O6oLtCBa8QRyo@kYrs/NuAtDd3bc5h7lrI0S4rxLfUbb4ab1nODTugN6QAq1y3U9LXq3s260KBv1NnpHYR915LbdgdZmazzoorDC8J7xPOqruY/dT5@ZyWK20m6fQ/i4GJ0eMz6bLi@tq@2YAahznHjqUdM7uIqujqAugONFswZ4eRlgq7exCyQ@OObjhea256u4gkM4OoCreipUW9mfGcayqerk5LZX3/FciW8RHWBRv35jBZSLZzHHIp/eITxwtdBWFtmKAdvG2nrlYu3JgN1tGu3Tc9nZkfDjQlxeFq0lIcv0jsK5GS9w5MtLYr9ow5BQELCFITiEh1ebb0u1R91xSkvZW2murnRz9YVPDC2Y/U688BbLSxsgUnAsJZSvdV5gsgrZ3FMnDouRk5U9HmSlQFdlSXKbgrLX4NFxtvu9wKynPoNuuYykAKfMMFhYP//C/ArC8Tg2EiMeuMwuA0KEXmEfROvnhKQZZSQXtvLrSdAjhz29/tPsB2yaJAu4UhL1e5kpuWOrgofeJ7sdhQgufmN0QOA/Fhg3iqCn0@OL2rGbsDeiNt@GdhrSGbV3yUgpNXr9Fw "Kotlin – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ·ÅÉεIL'*×.Bí€û×}˜.c ``` [Try it online](https://tio.run/##ASkA1v9vc2FiaWX//8K3w4XDic61SUwnKsOXLkLDreKCrMO7w5d9y5wuY///Mw) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VQeWvn/0PbDrYc7z209tM5HXevwdD2nw2sfNa05vPvw9NrTc/SS/@sc2mb/P9pIx1jHJBYA). **Explanation:** ``` · # Double the (implicit) input-integer ÅÉ # Push a list of all odd numbers smaller than or equal to this 2*input ε # Map over each odd integer: IL # Push a list in the range [1,input] again '*× '# Repeat "*" each integer amount of times as string .B # Box this list of strings, adding trailing spaces to make them all of # equal length í # Reverse each so the spaces are leading €û # Palindromize each string × # Repeat each the current odd integer amount of times }˜ # After the map: flatten the list of lists .c # Join this list of strings by newlines, and centralize it # (after which it is output implicitly as result) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` L'*×j.ºиøā·<ט.C ``` [Try it online!](https://tio.run/##ASMA3P9vc2FiaWX//0wnKsOXai7CutC4w7jEgcK3PMOXy5wuQ///Mw "05AB1E – Try It Online") ``` L -- range from 1 to n '*× -- repeat "*" that many times j -- pad to length n with spaces to the left .º -- self-intersected mirror и -- for each string, make a list of n copies ​ ø -- transpose to get the rows of the big triangle ​​ ā -- get the range from 1 to the number of rows (n) ​·< -- double and decrement to get a list of the first n odd numbers ​× -- repeat each string in the i-th row 2*i-1 times ​˜ -- flatten into a list of lines ​.C -- center and join by newlines ``` [Try it with step-by-step output!](https://tio.run/##dZE9TsNAEIV7TjFyE4iSSIEOQUXLJdbesbNhPWvtThSlg5oD0HAPEGVCR8MZuIiZdXAcW2Ea74/fN2/nuaBSg3V9D4NKvKICIfeuhDmwA7qGZHKbJJMzGI13L4OfsULFcjECXsiiVLQBNiWGTiW17IkqpSPYIhW8AIK1kU@oVIYhnvMC5S7nHgFm248jRECbTw0x@oAZo4bSeO98XwLw/d5JcucBVSad2BsqJuL1AUGBNYHB5eIjc5UZGJf6eXyG3YGTsMwnVC5gtFogN3a9W4fIiOvUFCAdZIoWDyyBRE5bn08t7kAYTD2e0apM0Uduwz@ni6G3vb3t280ept0qtfIm0qAx81gicWuze2hE58bLhsBp/dcmnGA39H3kbdJHEwRDDctMJT5xCJdjM52fSP@Y9vXaZGEVM5IQxF3nzBr6Txq1sztIMoyhN09cOjGQboBw3RPW9dUv) ]
[Question] [ Given a string of N, S, E and W, output a bearing (angle clockwise from North in degrees), correct to 5 decimal places. In [traditional compass notation](https://en.wikipedia.org/wiki/Points_of_the_compass#16-wind_compass_rose "Wikipedia article on points of the compass"), a string is made up of only 2 of these characters (like NNW or ESE). **Here you must also accept strings that contain all 4 (like WNNNSE)**. Using only 2 symbols allows humans to intuitively understand the meaning. Allowing 4 symbols makes it horrible to read, but allows shorter ways of describing a bearing to a given accuracy. *(As pointed out in the [comments](https://codegolf.stackexchange.com/questions/99906/north-by-north-by-north-by-south-east?noredirect=1#comment242720_99906) by [user2357112](https://codegolf.stackexchange.com/users/12647/user2357112), it turns out you can prove that for any given bearing, the 4 symbol string will be exactly the same length as the 2 symbol string, so I've based this challenge on a false assumption. Hopefully this lack of a practical purpose doesn't detract from your enjoyment of the challenge...)* The exact method is described below, and is equivalent to the traditional notation (it expands on it rather than changing it). # Input * The input is a single string containing only the characters `NESW`. * The input may be a sequence of characters if you prefer, provided this does not include any preprocessing. For example, taking a nested list `[N, [E, [S, [W]]]]` to help with the order of processing is not permitted. * Taking different characters is not permitted. You may not take a string of `1234` instead of `NESW`. # Output * The output must be a decimal number or string representation of one (not a rational/fraction). * Trailing zeros do not need to be displayed. If the bearing is `9.00000`, then the output `9` also counts as correct to 5 decimal places. * The output is in the range [0, 360). That is, including 0 but excluding 360. * Correctness is checked by rounding the output to 5 decimal places. If the bearing is 0.000005, this rounds to 0.00001. Outputs 0.00001 and 0.000005 are both correct. * Output in scientific notation for some inputs is acceptable. For example, `1e-5` instead of `0.00001`. # Conversion * The single character compass points `N`, `E`, `S`, and `W` correspond to 0, 90, 180, and 270 degrees respectively. * Prepending one of these to a string results in the bearing that bisects the bearing of the single character and the bearing of the original string. * The closest of the two possible bisecting bearings is chosen, so that NE represents 45 degrees, not 225 degrees. * This is unambiguous except where the angle to be bisected is 180 degrees. Therefore `NS`, `SN`, `WE`, and `EW` correspond to undefined bearings, and the input will never end in any of these. They may however appear anywhere else in the input string, as this causes no ambiguity. * If the final two characters are identical, the final character will be redundant as the bisection will return the same bearing. Since this adds nothing to the notation, your code does not need to handle this. Therefore `NN`, `EE`, `SS`, and `WW` correspond to undefined bearings, and the input will never end in any of these. They may however appear anywhere else in the input string. # Examples ``` N: 0 E: 90 S: 180 SE: halfway between S and E: 135 NSE: halfway between N and SE: 67.5 NNSE: halfway between N and NSE: 33.75 NNNSE: halfway between N and NNSE: 16.875 NNNNSE: halfway between N and NNNSE: 8.4375 ``` # Test cases A submission is only valid if it gives correct output for all of the test cases. Note that the test cases push to the limits of what can be handled with double precision. For languages that default to single precision, you will probably need to spend the bytes to specify double precision in order to get correct outputs. Test case outputs are shown rounded to 5 decimal places, and also to arbitrary precision. Both are valid outputs. ``` WNE 337.5 337.5 WEN 337.5 337.5 WEWEWEWEWEWEWEWEWEWEWEN 330.00001 330.000007152557373046875 NESWNESWNESWNESWNESWNESWNESW 90 89.99999932944774627685546875 NNNNNNNNNNNNNNNNNNNNNNNE 0.00001 0.0000107288360595703125 NNNNNNNNNNNNNNNNNNNNNNNW 359.99999 359.9999892711639404296875 SNNNNNNNNNNNNNNNNNNNNNNNE 90.00001 90.00000536441802978515625 SNNNNNNNNNNNNNNNNNNNNNNNW 269.99999 269.99999463558197021484375 ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The score is the length of the source code in bytes, and the shortest wins. --- # Pedantry > > I made the mistake of thinking that "North by North West" was a valid compass direction. A happy mistake, since it led to a challenge idea, but I then discovered from the [Wikipedia page](https://en.wikipedia.org/wiki/Points_of_the_compass#32-wind_compass_points "Section on the 32-wind compass points"): > > > *"The title of the Alfred Hitchcock 1959 movie, North by Northwest, is actually not a direction point on the 32-wind compass, but the film contains a reference to Northwest Airlines."* > > > It also turns out that the method used for this challenge is only consistent with traditional compass points up to and including the 16 point compass. The 32-wind compass described on that page is subtly different and I have conveniently overlooked its existence for this challenge. > > > Finally, for anyone who thinks I should use "Southeast" instead of "South East", it [seems to be a regional difference](https://english.stackexchange.com/questions/73712/is-there-some-difference-between-north-east-and-northeast "English Language & Usage Stack Exchange"). > > > [Answer] # JavaScript (ES6), ~~84~~ ~~80~~ ~~78~~ ~~74~~ 72 bytes *Saved a byte thanks to @Titus, 1 thanks to @Neil* ``` f=([c,...s],b="NESW".search(c))=>b*90-(s[0]?(b-=f(s)/90)-4*(b*b>4):0)*45 ``` It took a while, but I think I've finally perfected the formula... ### Test snippet ``` f=([c,...s],b="NESW".search(c))=>b*90-(s[0]?(b-=f(s)/90)-4*(b*b>4):0)*45 g=(s,n)=>console.log('f("'+s+'"):',f(s),"expected:",n) g("N", 0) g("NE", 45) g("E", 90) g("SE", 135) g("S", 180) g("SW", 225) g("W", 270) g("NW", 315) g("WNE", 337.5) g("WEN", 337.5) g("WEWEWEWEWEWEWEWEWEWEWEN", 330.00001) g("NESWNESWNESWNESWNESWNESWNESWNESWNESWNESWNESWNESWNESW", 90) g("NNNNNNNNNNNNNNNNNNNNNNNE", 0.00001) g("NNNNNNNNNNNNNNNNNNNNNNNW", 359.99999) g("SNNNNNNNNNNNNNNNNNNNNNNNE", 90.00001) g("SNNNNNNNNNNNNNNNNNNNNNNNW", 269.99999) ``` ### Explanation Let's start with the simplest case: a single-char string. The result is simply its (0-indexed) position in the string `NESW`, multiplied by 90. For a two-char string, the result lies halfway between the result of the first char and the result of the second. However, there's a catch: if the absolute difference between the two is greater than 180 (e.g. `NW` or `WN`), we must 180 to the angle so that it's not pointing the opposite direction. For any longer string, the result lies halfway between the result of the first char and the result of the rest of the string. This can be generalized in the following way: * If the input is a single char, return its index in the string `NESW` times 90. * Otherwise, return the index of the first char in the string `NESW` times 45, plus half the result of the rest of the string; add an extra 180 if the absolute difference between the two is greater than 90. [Answer] ## C#6, ~~226~~ ~~217~~ ~~207~~ 185 bytes ``` using System.Linq;double N(string s){double b=f(s.Last());foreach(var c in s.Reverse()){b=(b+f(c)+(b-f(c)>2?4:f(c)-b>2?-4:0))/2;b=(b+4)%4;}return b*90;}int f(char x)=>"NESW".IndexOf(x); ``` Edit: -10 bytes by "borrowing" idea from ETHproductions's submission -22 bytes thanks to @Titus Ungolfed ``` // Call this method double N(string s){ // Initialize bearing with last direction double b=f(s.Last()); // Do backward. Doing last direction once more doesn't impact result foreach(var c in s.Reverse()){ // Average current bearing with new bearing, adjusted with wrapping b=(b+f(c)+(b-f(c)>2?4:f(c)-b>2?-4:0))/2; // Make bearing back to range [0,4) b=(b+4)%4; } // Change from "full circle = 4" unit to degree return b*90; } // helper method to convert direction to bearing. This returns bearing with full circle = 4. int f(char x)=>"NESW".IndexOf(x); ``` [Answer] # PHP, ~~95~~ ~~88~~ ~~86~~ ~~100~~ ~~127~~ ~~104~~ 101 bytes * -7 bytes with the null coalescing operator * -2 bytes by not replacing `N` (and more, because that allows to put the translation to the loop head: `N` is truthy, but evaluates to `0` in the calculation.) * +41 bytes for fixing the bisection (*cough*) * -7 bytes directly and -16 indirectly inspired by @ETHproductions´ code * -3 bytes by replacing `strtr` with one of my bit jugglings --- ``` for($i=strlen($s=$argv[1]);$i--;$p=($q+$p=$p??$q)/2+2*(abs($q-$p)>2))$q=ord($s[$i])/.8+3&3;echo$p*90; ``` This is officially the first time ever that I use the null coalescing operator. Run with `-r`. ## PHP 7.1 Negative string offsets in the upcoming PHP version will save 12 bytes: Replace `strlen($s=$argv[1])` with `0` and `$s` with `$argv[1]`. --- [Answer] ## Python 3, 133 113 bytes Just improving on @L3viathan's answer because I just made this account and therefore can't make comments yet. ``` d={"N":0,"E":.5,"S":1,"W":1.5} def B(s): b=d[s[-1]] for c in s[::-1]:b=(b+d[c])/2+(abs(b-d[c])>1) return b*180 ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~48~~ ~~42~~ ~~37~~ 32 bytes Saved 6 bytes thanks to Emigna. Saved 5 bytes thanks to Titus' idea to work on range [0,4[ and multiply by 90 at the end. Saved 5 bytes thanks to Adnan's mastery of ancient xor/modulo metamorphosis. So every angle is reduced from range [0,360[ to range [0,4[ throughout the execution. Result is then multiplied by 90 and displayed. ``` Ç30^5%R¬U¦vXy+;DX-Ä0›2*+4%U}X90* It can be divided into two sequentially called subprograms. First program: convert input string into an array of the corresponding angles in range [0,4[ Ç Take the ascii value of all input characters 30^5% Dark ascii manipulation that yields [0,1,2,3] for [N,E,S,W] Now we have an array of integers in range [0,4[. Second program: actually compute the final angle R Reverse the array ¬ Take the first value (the last of the non-reversed array) U Pop it from the stack and set X to the same value ¦ Strip the first element v For each remaining element Xy+; Compute the average value between the leftmost value and X DX-Ä0› Push 1 if angular distance cast to integer is > 0 (i.e. if it is >= 1), 0 otherwise. It's equivalent to checking >= 90 degrees 2*+ Multiply by 2 (=2 if angular distance is >= 1 and 0 otherwise) and add it to the formerly computed average value. It's equivalent to multiplying by 180 4% Perform mod 4. It's equivalent to performing mod 360 U Store the result back to X } End for, mandatory if input has only one character X90* Push X*90 and implicitly display it ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w4czMF41JVLCrFXCpnZYeSs7RFgtw4Qw4oC6MiorNCVVfVg5MCo&input=TkVTV05FU1dORVNXTkVTV05FU1dORVNXTkVTV05FU1dORVNXTkVTV05FU1dORVNXTkVTVw) Potential axes of golfing: * Not sure if that mod 4 is required (it would save 2 bytes). All test cases work without it, but maybe there exists a tricky case. A mathematical proof to either validate it or nullify it would be top-notch. * There is no implicit stuff besides displaying the result (closing quote marks, closing brackets). [Answer] # Python 3, ~~146~~ ~~145~~ ~~117~~ ~~107~~ ~~97~~ ~~94~~ ~~93~~ 92 bytes ``` f(s):u='NESW'.find(s[0])*90;return(u+f(s[1:]))/2+180*(abs(u-‌​f(s[1:]))>180)if s[1:]else u ``` Call `f` with the string. [Answer] # C, 184 bytes ``` double h(char c){return ((c=='E')+(c=='S')*2+(c=='W')*3);}double d(char*s){double f=h(*s);if(s[1]){double t=f;f=(f+d(s+1)/90)/2;if(((t-f)>1)||((f-t)>1))f+=2;if(f>=4)f-=4;}return f*90;} ``` **Ungolfed** ``` // a helper function double direction_(char ch) { if (ch=='N') return 0.; else if (ch=='E') return 90.; else if (ch=='S') return 180.; else return 270.; } // this is the main function to call double direction(char* str) { double fAngle = direction_(str[0]); if (str[1]) { double tmp = fAngle + direction(str+1); if (tmp>=360.) tmp-=360.; tmp/=2; if (((tmp-fAngle)>90.) || ((tmp-fAngle)<-90.)) { // check if we need to take the "other side"; if the resulting angle is more than 90 degrees away, we took the wrong on if (tmp>=180.) tmp-=180.; else tmp+=180.; } fAngle = tmp; } return fAngle; } ``` [Answer] ## R, 172 146 bytes ``` z=rev((0:3*90)[match(scan(,""),c("N","E","S","W"))]);p=z[1];l=length(z);for(i in 2:l)p=(p+z[i])/2+(abs(p-z[i])>180)*180;if(l<2)p=z;sprintf("%f",p) ``` **Ungolfed** ``` z=rev((0:3*90)[match(scan,""),c("N","E","S","W"))]); #1 p=z[1]; #2 l=length(z) #3 for(i in 2:l)p=(p+z[i])/2+(abs(p-z[i])>180)*180; #4 if(l<2)p=z #5 sprintf("%f",p) #6 ``` **Explained** 1. Read input from stdin * Match input by index to `c("N","E","S","W")` * From matched indices: match to the vector of degrees `0:3*90` (instead of `c(0,90,180,270)`) * Reverse and store as `z` 2. Initialize `p` to the degree equivalent to last char in input 3. Store length of input as `l` 4. Iteratively, calculate the closest of the two possible bisecting bearings. 5. If only one input is given, set `p` to `z` 6. Format and print [Try the test cases on R-fiddle](http://www.r-fiddle.org/#/fiddle?id=We13B66f&version=1) (note that this is a function due to `scan` not working on R-fiddle) [Answer] # Haskell, ~~109 105~~ 103 bytes ``` h=180 a#b|abs(a-b)<h=n|n>h=n-h|1>0=n+h where n=(a+b)/2 -- calculates the new "mean" on the cirlce f 'N'=0 -- translates characters to angles f 'E'=90 f 'S'=h f _=270 foldr1(#).map f -- traverses the whole string ``` Thanks for -2 byte @xnor! [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), ~~55~~ ~~45~~ 38 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ### Solution Requires `⎕IO←0`, which is default on many systems. Asks for direction. ``` 360|÷○÷180×12○(+÷(|+))/¯12○○2÷⍨'NES'⍳⍞ ``` ### Explanation Goes around the problem by converting each letter to a complex number 1∠*θ* ⇔ *a* + *b · i*, then doing a sum reduction from right-to-left (APL's forte) while normalizing at each step. The final *θ* is then converted to degrees and normalized to be within [0, 360): `'NES'⍳⍞` the indices of each input letter in "NES"; N→0, E→1, S→2, anything else→3 `○2÷⍨` convert to angles in radians; *θ* = *π* · ***x***∕2 `¯12○` convert to complex numbers on the unit circle; *ei · θ* `(`...`)/` reduce the list with... (i.e. insert the function between the elements of...)  `+÷(|+)` ... the normalized sum; ***x****n* - 1 + ***x***n∕|***x****n* - 1 + ***x***n| `12○` convert to angle; *θ* `÷○÷180×` convert to degrees; 1∕*π* · 1∕180 · ***x*** `360|` division remainder when divided by 360 [TryAPL online!](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20%7B360%7C%F7%u25CB%F7180%D712%u25CB%28+%F7%28%7C+%29%29/%AF12%u25CB%u25CB2%F7%u2368%27NES%27%u2373%u2375%7D%A8%27WNE%27%20%27WEN%27%20%27WEWEWEWEWEWEWEWEWEWEWEN%27%20%27NESWNESWNESWNESWNESWNESWNESWNESWNESWNESWNESWNESWNESW%27%20%27NNNNNNNNNNNNNNNNNNNNNNNE%27%20%27NNNNNNNNNNNNNNNNNNNNNNNW%27%20%27SNNNNNNNNNNNNNNNNNNNNNNNE%27%20%27SNNNNNNNNNNNNNNNNNNNNNNNW%27&run) ### Anecdote If input and output was as orthogonal complex units, the entire solution would be just: ``` (+÷(|+))/ ``` The rest of the code is parsing input and formatting output. [Answer] # Common Lisp, ~~347~~ 327 bytes *Thanks to @Titus for taking off a few* This can probably be golfed more, but at least it works (I think): ``` (defun d(c)(if(eql c #\N)0(if(eql c #\E)1(if(eql c #\S)2(if(eql c #\W)3)))))(defun m(a b)(if(> a b)(rotatef a b))(if(<(+(- 4 b)a)(- b a))(+(/(+(- 4 b)a)2)b)(+(/(- b a)2)a)))(defun f(s)(let((c))(setf c(d(char s(1-(length s)))))(do((a)(p(-(length s)2)(1- p)))((< p 0))(setf a(char s p))(setf c(m(d a)c)))(format t"~5$"(* c 90)))) ``` Usage: ``` * (f "WNE") 337.50000 NIL ``` Function `d` takes a character `N`, `E`, `W`, or `S` and returns the appropriate degree. Function `m` gets the approprate combined degree of two given directions. Function `f` iterates through the provided string, computes the appropriate degree, and prints it as a floating point. [Answer] # Befunge, ~~183~~ ~~181~~ 175 bytes ``` >~#+:#25#%6*#/`#2_$>5%4*:00p"Z}"4*:***20g#v_+2/00g10g-:8`\0\-8`+!v v5:+*:*:"d"/+55+5$_^#!:\p01/**:*4"}Z":p020<%**:*"(2Z"+**5*:*"0}"!< >5>+#<%#56#58#:*#/+\#5:#5_$$$,,,".">:#,_@ ``` [Try it online!](http://befunge.tryitonline.net/#code=Pn4jKzojMjUjJTYqIy9gIzJfJD41JTQqOjAwcCJafSI0KjoqKioyMGcjdl8rMi8wMGcxMGctOjhgXDBcLThgKyF2CnY1OisqOio6ImQiLys1NSs1JF9eIyE6XHAwMS8qKjoqNCJ9WiI6cDAyMDwlKio6KiIoMloiKyoqNSo6KiIwfSIhPAo-NT4rIzwlIzU2IzU4IzoqIy8rXCM1OiM1XyQkJCwsLCIuIj46IyxfQA&input=U05OTk5OTk5OTk5OTk5OTk5OTk5OTk5OVw) **Explanation** This follows a similar algorithm to many of the other answers, only it's using fixed point calculations emulated with integers since Befunge doesn't support floating point. Thanks to [@Titus](https://codegolf.stackexchange.com/users/55735/titus) for the ASCII-to-int routine. ``` ~ : 5 6* ` _$ while ((c = getchar()) > 30) // ends with any ctrl char or EOF > + 2 %6 / 2 push(c / 2 % 6 + 2) // partial conversion to int do { 5% dir = pop() % 5 // completes the conversion to int 4*:00p dir *= 4; lowres_dir = dir // used by the 180-flip calculation "Z}"4*:*** dir *= 22500000 // this is 90000000 / 4 20g_ if (!first_pass) { +2/ dir = (dir+last_dir)/2 // last_dir is second item on stack 00g10g- diff = lowres_dir - last_lowres_dir :8`\0\-8`+!! flip = diff>8 || -diff>8 "}0"*:*5**+ dir += flip * 180000000 // add 180 degrees if we need to flip "Z2("*:**% dir %= 360000000 // keep within the 360 degree range } 020p first_pass = false :"Z}"4*:**/10p last_lowres_dir = dir / 22500000 \ last_dir = dir // saved as second item on stack :!_ } while (!stack.empty()) $ pop() // this leaves the final dir on top 5+55+/ dir = (dir + 5)/10 // round down to 5 decimal places "d":*:*+ dir += 100000000 // add a terminating digit while (true) { // convert into chars on stack :55 + % 6 8 * +\ : _ push(dir%10+'0'); if (!dir) break > < 5 5 : /+ 5 5 dir /= 10 } $$$ pop() x 3 // drop the chars we don't need ,,, putchar(pop()) x 3 // output first three chars "." push('.') // add a decimal point >:#,_@ while(c=pop()) putchar(c) // output the remaining chars ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~30~~ 27 bytes ``` 90×(4|2÷⍨+-4×2<∘|-)/'NES'⍳⎕ ``` [Try it online!](https://tio.run/##fY89TwJBEIZ7fsV1q9HD/ZqdXWNLS0NBfYGcIV48c1xjgM4ofhyxMdhYaGVvCAmJFf9k/8g552FiAcxmMjuZ99l3J7pKwv51lKTnYS@JhsNBr/Szl0Hqb595w0/v4tLx9fxAj@V66YvPo1Cv5/LMT1/H4eEJa7c6zBdfRJSkLWOifDET/umbTUbsmNGgyoxEC@YfPmiypL6XsZgFvngL8izqx5dBngZUGjnxI5L6@/eMrrEvVqcsvWD@8YbF0SChZ1Y0ziYN1m23WB4ohU2gptX@32w7tYA3eRUoQAKgQsW1sUgQLdLdlURa13S/oaTTGlEbicYC/NHbo/ph7Sg4SmuV4eAAuRJyN1TZKaj9rJMohFFOcy1d7dXZY@Y2@4EyWgvLpUMLAozcw1V@0mz200YBWOGQS6GtVgg/ "APL (Dyalog Classic) – Try It Online") ]
[Question] [ **This question already has answers here**: [Numbers with Rotational Symmetry](/questions/77866/numbers-with-rotational-symmetry) (43 answers) Closed 1 year ago. ## Background You are working for some board-game manufacturer and need to produce wooden tiles with the numbers from 0 to *n* engraved on them for some game. However, without further ado, some tiles would become indistinguishable, e.g., `6` and `9`. To avoid this, you have to equip numbers that can be confused with others (and only those) with a disambiguating dot, e.g., you would have tiles like `9.` or `6089.`. Unfortunately, you need to use some old, yet programmable wood-engraving device for this, whose interface is so broken that you have to encode every character of the program by hand in an unspeakably tedious process. Fortunately the device understands every existing programming language. Thus you are looking for the shortest program that prints such tiles. ## Actual task Write the shortest program that: * Takes a positive integer *n* as input. How the input is read is up to you. * Prints each of the numbers from 0 to *n* (0 and *n* included) exactly once in an order of your choice, separated by a single whitespace character (including newline). The numbers are to be printed without leading zeros. * Appends a dot (.) to every number that turns into another, valid number upon rotation by π (180 °), even if that number is larger than *n.* Your typeface’s 0 and 8 are rotation-symmetric and the 9 is a rotated 6. The 2 and 5 are distinct upon rotation; the 1 is not rotation-symmetric. Numbers with leading zeros are not valid. ## Examples Each of the following numbers has to be printed exactly this way: * `2` * `4` * `5` * `6.` * `8` * `9.` * `16` * `60` * `66.` * `68.` * `69` * `906` * `909.` * `8088.` * `9806.` * `9886` * `9889.` [Answer] # CJam, ~~46~~ ~~44~~ ~~43~~ 42 bytes ``` l~),{_A%g1$s_6890s-!\_69s_W%erW%=!&&'.*N}/ ``` I think there's some room for improvement. [Test it here.](http://cjam.aditsu.net/) ## Explanation ``` l~),{_A%g1$s_6890s-!\_69s_W%erW%=!&&'.*N}/ l~ "Read an eval input."; ), "Get range from 0 to n."; { }/ "For each..."; _ "Get a copy of the integer."; A%g "Ends with digit other than 0?"; 1$s_ "Get another copy, convert to string, get a copy."; 0689s-! "Contains rotation-safe digits?"; \ "Swap with other copy."; _ "Get another copy."; 69s_W%er "Swap 6 and 9."; W% "Reverse."; =! "Is different from original?"; && "AND all three conditions."; '.* "If true, push a period (else, an empty string)."; N "Push a newline."; ``` [Answer] # CJam, ~~46 45 43~~ 42 bytes ``` ri){Is___69`96`erW%=!\6809`-!&IA%g&'.*N}fI ``` I think it can be golfed a little more. Takes `n` from STDIN. [Try it online here](http://cjam.aditsu.net/) [Answer] ## [Pyth](https://github.com/isaacg1/pyth) - 34 ~~38~~ ``` VhQJ`N+J*\.&nJX_J`69`96&eN!-J"0689 ``` I must give thanks to @Sp3000 for helping me remove 4 bytes. I originally had an additional check `&@JK` which made sure there was a 6 or 9 in the number, but after perusing the answers before posting, I read his answer and noticed that my identical translation and reversal already took care of that. Also thanks to @isaacg for pointing out that strings are iterables, and you can use set operations on them. Also for making the current code ;) Explanation: ``` : (implicit) Q=eval(input()) VhQ : for N in range(Q+1): J`N : J=str(N) +J*\. : J + "." * ... &nJX_J`69`96 : J!=translate(reversed(J),"69","96") and... &eN : N%10 and... !-J"0689 : not(setwise_difference(J, "0689")) ``` [Answer] ## APL 66 ``` ∊' ',¨{a←⌽'0.....9.86'[⎕D⍳b←⍕⍵]⋄'.'∊a:b⋄('0'=⊃a)∨⍵=⍎a:b⋄b,'.'}¨0,⍳ ``` ***Explanation:*** ``` ¨0,⍳ applies the function to each number 0-n a←⌽'0.....9.86'[⎕D⍳b←⍕⍵] inverts 6s and 9s, leaving 8s and 0s, and replacing other numbers with dots. Reverses vector after substitution. '.'∊a if there is a dot in the number.... ('0'=⊃a) .. or if the number starts with 0... ⍵=⍎a or if the (inverted) number is the same as original :b then print the original number b,'.' else print a dot in the end ∊' ',¨ Finally to give the result in the asked format i add a single space after each result and join them all ``` Try it on [tryapl.org](http://tryapl.org/?a=%2C/%27%20%27%2C%A8%7Ba%u2190%u233D%270.....9.86%27%5B%u2395D%u2373b%u2190%u2355%u2375%5D%u22C4%27.%27%u220Aa%3Ab%u22C4%28%270%27%3D%u2283a%29%u2228%u2375%3D2%u2283%u2395VFI%20a%3Ab%u22C4b%2C%27.%27%7D%A80%2C%u237370&run) *Note that in the online interpreter the ⍎ function doesn't work so i had to substitute it with 2⊃⎕VFI which does the same in this case, executes and returns the number, given a string.* [Answer] # Perl 5, 53 bytes ``` say$_,"."x(!/[1-57]|0$/&&reverse!=y/96/69/r)for 0..<> ``` [Online demo.](http://ideone.com/LNerEO) Uses the Perl 5.10+ `say` feature, so needs to be run with `perl -M5.010` (or `perl -E`) to enable it. (See [this meta thread.](https://codegolf.meta.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions)) Reads input from stdin, prints to stdout. [Answer] # Python 2, ~~130~~ ~~116~~ 113 bytes ``` def f(n):S=`n`;n and f(n-1);print S+"."*all([n%10,set(S)<=set("0689"),(u""+S[::-1]).translate({54:57,57:54})!=S]) ``` Defines a function `f` which prints the numbers to STDOUT, in ascending order. This time I thought I'd take a leaf out of @feersum's book with `.translate` :) Expanded: ``` def f(n): S=`n` n and f(n-1) # Recurse if not 0 print S+"."*all([n%10, # Not divisible by 10 set(S)<=set("0689"), # Consists of 0689 (u""+S[::-1]).translate ({54:57,57:54})!=S]) # When rotated is not itself ``` --- Previous solution: ``` def f(n):S=`n`;print S+"."*all([n%10,set(S)<=set("0689"),eval("S[::-1]"+".replace('%s','%s')"*3%tuple("6a96a9"))!=S]);n and f(n-1) ``` Thanks to @xnor for showing me the `.replace` trick some time ago. [Answer] # C#, ~~343~~ 309 characters *Way* too long, but anyway: ``` namespace System.Linq{class C{static void Main(){int n=int.Parse(Console.ReadLine());for(int i=0;i<=n;i++){var b=i+"";var c=b.Replace("6","9");Console.Write(b+(b.All(x=>x=='0'|x=='8'|x=='6'|x=='9')&!b.EndsWith("0")&!(b.Count(x=>x=='6')==b.Count(x=>x=='9')&new String(c.Reverse().ToArray())==c)?". ":" "));}}}} ``` How does it work? To add a period to the number, it must match the following requirements: * Consists only of `0`, `8`, `6` and `9`. * Does not end with a zero. * Is not the same number when you rotate it: + If a number has an equal amount of `6`s and `9`s, and + if `c` = the number with all `6`s replaces with `9`s, + and reversed `c` == `c`, + then: the rotated number is the same as the number itself. The numbers are separated by a space. Code with indentation: ``` namespace System.Linq { class C { static void Main() { int n = int.Parse(Console.ReadLine()); for (int i = 0; i <= n; i++) { var b = i + ""; var c = b.Replace("6", "9"); Console.Write(b + (b.All(x => x == '0' | x == '8' | x == '6' | x == '9') & !b.EndsWith("0") & !(b.Count(x => x == '6') == b.Count(x => x == '9') & new String(c.Reverse().ToArray()) == c) ? ". " : " ")); } } } } ``` [Answer] # M (MUMPS) - ~~72~~ 70 ``` R n F i=0:1:n W !,i S r=$TR($RE(i),69,96) W:r=+r*r'=i*'$TR(i,0689) "." ``` Most built-in commands and functions in M have abbreviated versions. I've used the full names below. `READ n` - Read a string from the keyboard and store it in `n`. `FOR i=0:1:n` - Loop from zero to `n`, incrementing `i` by 1 each time. (The remainder of the line constitutes the body of the loop.) `WRITE !,i` - Print a newline followed by the value of `i`. `SET r=$TRANSLATE($REVERSE(i),69,96))` - Reverse `i`, replace nines with sixes and sixes with nines, and store that in `r`. `WRITE:r=+r*r'=i*'$TRANSLATE(i,0689) "."` * `:` - Denotes a postconditional expression, so the `WRITE` command is only executed if `r=+r*r'=i*'$TRANSLATE(i,0689)` evaluates to a truthy value. * `r=+r` - Check that `r` doesn't have a leading zero. The unary `+` operator converts a string to a number, which strips leading zeroes if there are any. * `*` - Multiplication operator. M has no order of operations; all binary operators are evaluated in the order they appear from left to right. * `r'=i` - Check that `i` isn't the same as it's flipped version `r`. * `'$TRANSLATE(i,0689)` - Remove all zeros, sixes, eights, and nines from `i`, and check that there's nothing left. (`'` is the logical negation operator.) * `"."` - Finally the argument to the `WRITE` command (a literal string). **Edit:** Made it a little shorter by abusing the multiplication operator. Previous version: ``` R n F i=0:1:n W !,i S r=$TR($RE(i),69,96) I '$TR(i,0689),i'=r,r=+r W "." ``` [Answer] # APL, 53 characters [`∊{⍵,'. '↓⍨∨/(3≡⊃i)(5∊i),⍵≡'9608x'[i←⌽'6908'⍳⍵]}∘⍕¨0,⍳`](http://tryapl.org/?a=%u220A%7B%u2375%2C%27.%20%27%u2193%u2368%u2228/%283%u2261%u2283i%29%285%u220Ai%29%2C%u2375%u2261%279608x%27%5Bi%u2190%u233D%276908%27%u2373%u2375%5D%7D%u2218%u2355%A80%2C%u2373100&run) ``` 0,⍳N numbers 0..N {...}∘⍕¨ format each number as a string and do the thing in curly braces inside the braces ⍵ is the current string '6908'⍳⍵ encode '6' as 1, '9' as 2, '0' as 3, '8' as 4, and all others as 5 ⌽ reverse '9608x'[A] use each element of A as an index in '9608x': effectively: swap '9'←→'6', preserve '08', mask other digits ⍵≡ does it match the original string? this is the first boolean condition, two more to come 5∊i did we have a digit other than '0689'? 3≡⊃i is the first of i (that is, the last of ⍵) a '0' (encoded as 3)? ∨/ disjunction ("or") over the three conditions, returns 0 or 1 '. '↓⍨ drop 0 or 1 elements from the beginning of the string '. ' ⍵, prepend ⍵ ∊ flatten the results to obtain a single output string ``` [Answer] # C# 205 ~~209~~ C# doesn't have to be so long... more or less, a port of my JavaScript answer ``` class P{static void Main(string[]a){for(int n=int.Parse(a[0]);n>=0;--n){string p="",u=n+p;int e=n%10;foreach(var d in u)p=(d<56?d!=54?d>48?e=0:0:9:120-d-d)+p;System.Console.WriteLine(e!=0&p!=u?u+".":u);}}} ``` **Ungolfed** ``` class P { static void Main(string[] a) { for (int n = int.Parse(a[0]); n >= 0; --n) { string p = "", u = n + p; int e = n % 10; foreach (var d in u) p = (d < 56 ? d != 54 ? d > 48 ? e = 0 : 0 : 9 : 120 - d - d) + p; System.Console.WriteLine(e != 0 & p != u ? u + "." : u); } } } ``` [Answer] # Ruby, 81 ``` ?0.upto(*$*){|x|puts x.reverse.tr('69','96')!=x&&x=~/^[0689]+$/&&/0$/!~x ?x+?.:x} ``` Input is taken from the command line. Generates a list of `String`s from `0` to `n`. It loops trough them and prints them. It appends a dot if all conditions are satisfied: * reversing the number and replacing the `6`s with `9`s doesn't yield the original * the number only consists of the digits `0`, `6`, `8` and `9` * the number doesn't end with `0` [Answer] # sed, 467 Longer than C#... I pretty much completed this when @edc65 pointed out that answers need to process numbers 0-n and not just n. Adding the sed code to increment 0-n adds a LOT more code, as this task is ill-suited to arithmetic-less sed. ``` :l /^[0689]*$/{ h s/$/:/ :x s/([0-9]):(.*)/:\2\1/ tx s/:// y/69/96/ G /^([0-9]+)\n\1/be s/^[^0].*/&./ :e s/.*\n// } p s/\.// s/[0-9]/<&/g s/0//g;s/1/_/g;s/2/__/g;s/3/___/g;s/4/____/g;s/5/_____/g s/6/______/g;s/7/_______/g;s/8/________/g;s/9/_________/g :t s/_</<__________/ tt s/<//g s/_// :b s/__________/</g s/<([0-9]*)$/<0\1/ s/_________/9/;s/________/8/;s/_______/7/;s/______/6/ s/_____/5/;s/____/4/;s/___/3/;s/__/2/;s/_/1/ s/</_/g tb s/^$/0/ /^0$/by bl :y c\ 0 p ``` As per the OP, ordering doesn't matter, so we work downwards from n to 0. ### Output: ``` $ sed -rnf rotproof.sed <<< 100 | grep "\." 99. 98. 89. 86. 68. 66. 9. 6. $ ``` [Answer] # bc, 158 After [doing this purely in sed](https://codegolf.stackexchange.com/a/42963/11259) using all string and regex operations with no native arithmetic, I was curious to see how this would look the other way around, i.e. all arithmetic and logic operations and no string/regex: ``` for(i=read();i+1;r=0){p=1 for(x=i;x;x/=A){d=x%A if(x==i&&!d)p=0 if(d==6||d==9)d=F-d else if(d%8)p=0 r=r*A+d} if(r==i)p=0 print i-- if(p)print "." print "\n"} ``` Output is sorted in descending order. ### Output: ``` $ bc rotproof.bc <<< 100 | grep "\." 99. 98. 89. 86. 68. 66. 9. 6. $ ``` [Answer] # JavaScript (ES6) 101 ~~104 106 109~~ A function with n as argument, output via console.log **Edit** using %10 to test for leading 0 **Edit 2** `for` reorganization, I don't need array comprehension after all **Edit 3** modified (again) the check for leading 0 ``` F=n=>{ for(;e=~n;console.log(e*l&&p-n?n+'.':n),--n) for(d of(p='')+n)p=(l=d<8?d-6?-d?e=0:0:9:24-d-d)+p } ``` **Ungolfed** and easier to test ``` F=n=> { o = ''; for( ; ~n; --n) // loop on n decreasing to 0 (~n is 0 when n==-1) { e = ~n; // init to a nonzero value, zero will mark 'invalid digit' p = ''; // build rotated number in p for(d of '' + n) { // l is the current digit, on exit will be the first digit of p l = d < 8 ? d != 6 ? d != 0 ? e = 0 // invalid char found, no matter what : 0 : 9 // 6 become 9 : 24 - d - d; // calc 8 => 8, 9 => 6 p = l + p; } // e==0 if invalid char, l==0 if leading 0 o += ' ' + ( e * l && p-n ? n+'.' : n); } console.log(o); } F(100) ``` *Output* ``` 100 99. 98. 97 96 95 94 93 92 91 90 89. 88 87 86. 85 84 83 82 81 80 79 78 77 76 75 74 73 72 71 70 69 68. 67 66. 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9. 8 7 6. 5 4 3 2 1 0 ``` [Answer] # Bash + coreutils, 105 ``` for((i=0;i<=$1;i++));{ [ ${i//[0689]/} ]||[ $i = `rev<<<$i|tr 69 96` ]||((!${i: -1}))||d=. echo $i$d d= } ``` ### Test: ``` $ ./rotproof.sh 100 | grep "\." 6. 9. 66. 68. 86. 89. 98. 99. $ ``` [Answer] ## AWK: 120 ``` {a[a[6]=9]=6;a[8]=8;for(j=a[0]=0;j<=$0;++j){r="";for(i=j;i;i=int(i/10))r=r a[i%10];print(j~/[^0689]|0$/||j==r)?j:j"."}} ``` Read the n value from stdin. Test: > > C:\AWK>gawk -f revnum.awk|grep \. > > 100 > > ^Z > > 6. > > 9. > > 66. > > 68. > > 86. > > 89. > > 98. > > 99. > > > [Answer] # Rebol - 195 ``` for n 0 do input 1[b: copy a: form n d: c: 0 parse reverse a[any[m:"6"(change m"9"++ c)|"9"(change m"6"++ c)|"0"|"8"| skip(++ d)]]print rejoin [b either all[d = 0 c > 0 a != b a/1 != #"0"]"."{}]] ``` Ungolfed + some annotations: ``` for n 0 do input 1 [ b: copy a: form n d: c: 0 ; reverse number and rotate "6" & "9" ; and do some counts (c when "6" or "9" and d when != "0689") parse reverse a [ any [ m: "6" (change m "9" ++ c) | "9" (change m "6" ++ c) | "0" | "8" | skip (++ d) ] ] print rejoin [ b either all [ d = 0 ; only has 0689 digits c > 0 ; must have at least one "6" or "9" a != b ; not same when reversed a/1 != #"0" ; does not "end" with zero ] "." {} ; if ALL then print "." else blank {} ] ] ``` [Answer] # Python - 152 ``` for i in range(input()+1):print`i`+("."*all([j in"0689"for j in`i`])and`i`[-1]!="0"and`i`!=`i`.replace("9","x").replace("6","9").replace("x","6")[::-1]) ``` [Answer] # JavaScript - 168 129 119 113 111 108 ``` F=n=>{for(;~n;n--){r='';for(c of""+n)r=(c-6?c-9?c:6:9)+r;console.log(r-n&&!/[1-57]/.test(r)&&n%10?n+".":n)}} ``` > > 4 5 6. 8 9. 16 60 66. 68. 69 906 909. 6090 9806. 9886 9889. > > > Or readable version: ``` F=n=>{for(;~n;n--){ r='';for(c of ""+n)r=(c-6?c-9?c:6:9)+r; // rotate console.log( // output, new-line is added // original number, and // append dot only if number is different than its rotated version and no un-rotatable digit is present and there is no zero at the end r-n && !/[1-57]/.test(r) && n%10 ?n+".":n )}} ``` I am not very happy with the regex, any ideas? **Edit**: Learned neat trick with `~` and `for (... of ...)` from @edc65 **Edit2**: Reorganized conditions **Edit3**: applied suggestions by @edc65 [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~38~~ ~~37~~ ~~30~~ 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÝεÐSUT%ĀiŽR!XåPiÐ69‡RÊi'.«]» ``` [Try it online.](https://tio.run/##ATgAx/9vc2FiaWX//8OdzrXDkFNVVCXEgGnFvVIhWMOlUGnDkDY5w4LigKFSw4ppJy7Cq13Cu///MTAwMA) **Explanation:** ``` Ý # Inclusive 0-based range: [0, (implicit) input] ε # Map each integer to: Ð # Triplicate the current integer SU # Convert it to a list of digits, and pop and store it in variable `X` T%Āi # If the current integer contains no trailing zeros ŽR!XåPi # And if the current integer only consists of the digits [0689] Ð69‡RÊi # And if the current integer is not the same when its 6s and 9s # are swapped and then the total is reversed '.« # Concat a '.' # Implicit else: use the top of the stack (the duplicate current integer) ] # Close all three ifs and the map » # Join the resulting list by newlines (and output implicitly) ``` Additional explanation for some parts: ``` T%Āi # Check if the integer contains no trailing zeros: T # Push 10 (T is a builtin for 10) % # Modulo Ā # Trutified: 0 remains 0 (falsey), everything else becomes 1 (truthy) # i.e. 12 % 10 → 2 → 1 (truthy) # i.e. 68 % 10 → 8 → 1 (truthy) # i.e. 70 % 10 → 0 → 0 (falsey) (70 remains as is) # i.e. 609 % 10 → 9 → 1 (truthy) # i.e. 808 % 10 → 8 → 1 (truthy) ŽR!XåPi # Check if the integer only consists of the digits 0, 6, 8 and/or 9: ŽR! # Push 6890 (Ž is a builtin for 2-char compressed integers, where R! is 6890) X # Push variable `X` (the list of digits) å # Check for each of these digits if they're in "6890" P # Take the product of that list # i.e. [1,2] → [0,0] → 0 (falsey) (12 remains as is) # i.e. [6,8] → [1,1] → 1 (truthy) # i.e. [6,0,9] → [1,1,1] → 1 (truthy) # i.e. [8,0,8] → [1,1,1] → 1 (truthy) Ð69‡RÊi # Check if the integer with 6s and 9s swapped and then reversed isn't unchanged: Ð # Triplicate the integer 69 # Push 69  # Bifurcate (short for Duplicate & Reverse) ‡ # Transliterate (in `a` replace all characters `b` with characters `c`) R # Reverse Ê # Check for inequality # i.e. 68 → "68" → "98" → "89" → 68 != "89" → 1 (truthy) (68 becomes "68.") # i.e. 609 → "609" → "906" → "609" → 609 != "609" → 0 (falsey) (609 remains as is) # i.e. 808 → "808" → "808" → "808" → 808 != "808" → 0 (falsey) (808 remains as is) ``` [Answer] # Perl - 84 ``` for(0..$ARGV[0]){s/6/x/g;s/9/6/g;s/x/9/g;printf"$_%s\n",$_=~/^[0689]+[689]$/?".":""} ``` [Answer] # Powershell, ~~111~~ 102 bytes ``` param($s)$s+'.'*!($s-match'[1-57]|0$|'+-join$(switch -r($s[($s.Length-1)..0]){'0|8'{$_}'6'{9}'9'{6}})) ``` Explained test script: ``` $f = { param($s) # input string $l=$s.Length # length of the string $c=$s[($l-1)..0] # chars of the string in the reversed order $d=switch -r($c){ # do switch with regex cases for each char '0|8'{$_} # returns the current char if it equal to 8 or 0 '6'{9} # returns 9 if the current char is 6 '9'{6} # returns 6 if the current char is 9 } # returns array of new chars (contains 0,6,8,9 only) $s+'.'*!( # returns s. Add '.' if not... $s-match'[1-57]|0$|'+-join$d # $s contains chars 1,2,3,4,5,7 or # ends with 0 or # equal to string of $d ) } @( ,('2' ,'2' ) ,('4' ,'4' ) ,('5' ,'5' ) ,('6.' ,'6' ) ,('7' ,'7' ) ,('9.' ,'9' ) ,('16' ,'16' ) ,('60' ,'60' ) ,('66.' ,'66' ) ,('68.' ,'68' ) ,('69' ,'69' ) ,('906' ,'906' ) ,('909.' ,'909' ) ,('8088.','8088') ,('9806.','9806') ,('9886' ,'9886') ,('9889.','9889') ) | % { $e,$s = $_ $r = &$f $s "$($r-in$e): $r" } ``` Output: ``` True: 2 True: 4 True: 5 True: 6. True: 7 True: 9. True: 16 True: 60 True: 66. True: 68. True: 69 True: 906 True: 909. True: 8088. True: 9806. True: 9886 True: 9889. ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 27 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç▒≈♣▌╬"÷╜─B↓«âpø←╚S☼ì>♫è;&╛ ``` [Run and debug it](https://staxlang.xyz/#p=80b1f705ddce22f6bdc44219ae8370001bc8530f8d3e0e8a3b26be&i=100&a=1) Unpacked, ungolfed, and commented, it looks like this. ``` 0p print 0 with no line break F for each [1 .. n] execute the rest of the program, where n is the input zP print a newline q peek and print the iterating variable without newline A%!C modulo 10, and cancel iteration if zero (this cancels for multiples of 10) _$cc convert iterating value to string and duplicate it twice on the stack 7R6-$ construct the string "123457" |&C if the character intersection is truthy, cancel the iteration r reverse string 69$:t map 6 and 9 characters to each other =C if this rotated string is equal to the original, cancel iteration print "." with no newline (this comment precedes the instruction because it's an unterminated literal) ". ``` [Run this one](https://staxlang.xyz/#c=0p+++++%09print+0+with+no+line+break%0AF++++++%09for+each+[1+..+n]+execute+the+rest+of+the+program,+where+n+is+the+input%0A++zP+++%09print+a+newline%0A++q++++%09peek+and+print+the+iterating+variable+without+newline%0A++A%25%21C+%09modulo+10,+and+cancel+iteration+if+zero+%28this+cancels+for+multiples+of+10%29%0A++_%24cc+%09convert+iterating+value+to+string+and+duplicate+it+twice+on+the+stack%0A++7R6-%24%09construct+the+string+%22123457%22%0A++%7C%26C++%09if+the+character+intersection+is+truthy,+cancel+the+iteration%0A++r++++%09reverse+string%0A++69%24%3At%09map+6+and+9+characters+to+each+other%0A++%3DC+++%09if+this+rotated+string+is+equal+to+the+original,+cancel+iteration%0A+++++++%09print+%22.%22+with+no+newline+%0A+++++++%09%28this+comment+precedes+the+instruction+because+it%27s+an+unterminated+literal%29%0A++%22.&i=100&a=1) ]
[Question] [ Given a nonnegative integer, return whether it is a three digit number ending in one, in any consistent integer base. In other words, the number needs to be represented in base-N, N being an integer greater than zero. ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins. * Since unary behaves weirdly, the behavior with input 310 is undefined. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are prohibited. ## Examples True: ``` 5 73 101 1073 17 22 36 55 99 ``` False: ``` 8 18 23 27 98 90 88 72 68 ``` A handful of large numbers: ``` 46656 true 46657 true 46658 true 46659 true 46660 true 46661 false 46662 false 46663 true 46664 false 46665 true 46666 true 46667 false 46668 false 46669 false 46670 true 46671 true ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` bRṫ€3ċJ ``` Returns the number of bases (non-zero being truthy, zero being falsy) in which the input is a three digit number ending in one. [Try it online!](https://tio.run/##y0rNyan8/z8p6OHO1Y@a1hgf6fb6f3TP4XYg2/3//2hTHQVzYx0FQwNDEAFmmusoGBnpKBib6SiYAqUtLXW4FCyA4kCsYARUACSBSiyBXEsDHQULIG0OVG5mAVSmVZSYl56qYWJmZgrUDaTMjTQV0EAsAA "Jelly – Try It Online") ### How it works ``` bRṫ€3ċJ Main link. Argument: n R Range; yield [1, ..., n]. b Base; convert n to bases 1, ..., n. ṫ€3 Tail each 3; remove the first two elements of each digit array. J Indices of [n]; yield [1]. ċ Count the number of times [1] appears in the result to the left. ``` [Answer] # JavaScript (ES7), ~~43~~ ~~40~~ 39 bytes ``` f=(n,b)=>n<b*b?0:n%b==1&n<b**3|f(n,-~b) ``` ### Test cases ``` f=(n,b)=>n<b*b?0:n%b==1&n<b**3|f(n,-~b) console.log('[Truthy]') console.log(f(5)) console.log(f(73)) console.log(f(101)) console.log(f(1073)) console.log(f(17)) console.log(f(22)) console.log(f(36)) console.log(f(55)) console.log(f(99)) console.log(f(46656)) console.log(f(46657)) console.log(f(46658)) console.log(f(46659)) console.log(f(46660)) console.log(f(46663)) console.log(f(46665)) console.log(f(46666)) console.log(f(46670)) console.log(f(46671)) console.log('[Falsy]') console.log(f(8)) console.log(f(18)) console.log(f(23)) console.log(f(27)) console.log(f(98)) console.log(f(90)) console.log(f(88)) console.log(f(72)) console.log(f(68)) console.log(f(46661)) console.log(f(46662)) console.log(f(46664)) console.log(f(46667)) console.log(f(46668)) console.log(f(46669)) ``` ### Commented ``` f = (n, // given n = input b) => // and using b = base, initially undefined n < b * b ? // if n is less than b²: 0 // n has less than 3 digits in base b or above -> failure : // else: n % b == 1 & // return a truthy value if n is congruent to 1 modulo b n < b**3 | // and n is less than b³ (i.e. has less than 4 digits in base b) f(n, -~b) // or the above conditions are true for some greater value of b ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~50~~ 47 bytes -2 bytes thanks to [@LeakyNun](https://codegolf.stackexchange.com/users/48934/leaky-nun) -1 byte thanks to [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis) ``` lambda n:any(i>n/i/i>n%i==1for i in range(2,n)) ``` [Try it online!](https://tio.run/##LY/BCoMwDIbve4pcBhUCs61NV8E9yS6Oza2wRREvPr1LjYfmC/9fPsi0Lp@R/TZ09@3b/x7PHrjteTX5xpd8kXnOXWeHcYYMmWHu@f0yDrmqthJyCQNC9Ai2tmXsa0RwDsETQpA6JYSrxPKc1E7qJHuqJRZG@UrChiiQIiqOMO2gWmEVTuEVjSIo1EJqOdSklqiWaNsTwDRnXgwjDKac9Ac "Python 3 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~41~~ 40 bytes ``` f n=or[mod n k==1|k<-[2..n],k^2<n,n<k^3] ``` *Thanks to @Zgarb for golfing off 1 byte!* [Try it online!](https://tio.run/##FcZLCoMwFEbhrdxBB4p/g4nNQ9BVdCgRhCpK9Co@6KR7tzo4nK9vttCO43l2xOW8VtP8IaZQlvIXimelhGCPUKuCwUWoM39OzcBU0nLs732lBx08Dtxul6Zmoa2fvxTd6iiqNGwGmcqrGxZKITPQGnkOB@mgMiiL3CFP4RysgnGekoSqlzHaCHHNSh/H5x8 "Haskell – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` ≥ℕ≜;?ḃ₍Ṫt1 ``` [Try it online!](https://tio.run/##JcwxCgIxEIXh21i9IplsZhIsvIdioRZaCILYiNjERdjC0s5KsLGy1DN4is1FojtbzMcw8M98O1us9uvNksohn185pcHxey@5eeT6mpvbcNS@Tzld2s9zZ0uZeIiDNfY/3SIggmN4jxgRYAPIgQQxIBqEACFwQMXsWRW1v8RONqpVSXVqpXpVW9a2/8bairZip2X8Aw "Brachylog – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 8 bytes Saved 3 bytes thanks to *Adnan*. ``` Lв3ù€θ1å ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f58Im48M7HzWtObfD8PDS//8NjcwB "05AB1E – Try It Online") **Explanation** ``` Lв # convert input to bases [1 ... input] ʒg3Q} # keep only elements of length 3 €θ # get the last item of each 1å # is there any 1? ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` bRµL€żṪ€3,1e ``` [Try it online!](https://tio.run/##y0rNyan8/z8p6NBWn0dNa47uebhzFZA21jFM/f//v6GBuTEA "Jelly – Try It Online") [Answer] # Mathematica, 43 bytes ``` !FreeQ[IntegerDigits[#,2~Range~#],{_,_,1}]& ``` [Try it online!](https://tio.run/##FcaxCoMwFAXQbylCpwuaF2JehoKDFLq1XUUklKfNYIY0m@ivp@1w4Kw@v2X1Obx8mS/ldE0ij@EWsyyS@rCE/Bkq0PH0cZGjGrFNmKD28VzuKcRcd3PdbQZWQzXq5x8LIugWxsA5MBSDNMjCMVwDZlhCy3v5Ag "Wolfram Language (Mathematica) – Try It Online") or [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9GtKDU1MNozryQ1PbXIJTM9s6Q4WlnHqC4oMS89tU45Vqc6Xidex7A2Vu1/QFFmXom@Q5q@A1gy2sTMzNRMB0iaG8b@BwA "Wolfram Language (Mathematica) – Try It Online") (large numbers) *Martin Ender saved 3 bytes* [Answer] ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes ``` Or@@Array[x~Mod~#==1<x/#^2<#&,x=#]& ``` [Try it online!](https://tio.run/##FcbRCsIgFAbghxF29YPziPMIE@wBou5jA6lGu9gC8cKI9uquXXzwLTG/nkvM8z3WyddLCuGUUvzcynZ@PzbhveqLFCP1okHxYmjqNc1rlmGS4WtgNVSr/o5YEEF3MAbOgaEYpEEWjuFaMMMSOv7VHQ "Wolfram Language (Mathematica) – Try It Online") Explicitly checks whether **n % i = 1** and **i2 < n < i3** for any possible base **i**. For golfing purposes, the inequality is rearranged to **1 < n/i2 < i**, so that it can be chained onto the equality. [Answer] # [Clean](https://clean.cs.ru.nl), ~~58~~ 56 bytes ***-2*** thanks to [Dennis](https://codegolf.stackexchange.com/questions/150785/is-this-a-three-digit-number-ending-in-one/150791?noredirect=1#comment368776_150791) ``` import StdEnv @n=or[n>m^2&&n<m^3&&n rem m==1\\m<-[2..n]] ``` [Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4zLIc82vyg6zy43zkhNLc8mN84YSCkUpeYq5NraGsbE5NroRhvp6eXFxv4PLkkE6rNVcFCwtPz/LzktJzG9@L@up89/l8q8xNzM5GIA "Clean – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` €;1ṠMo↓2Bḣ ``` [Try it online!](https://tio.run/##ASAA3/9odXNr///igqw7MeG5oE1v4oaTMkLhuKP///80NjY2MQ "Husk – Try It Online") Pretty close to [the Jelly answer of Dennis](https://codegolf.stackexchange.com/a/150794/32014). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~21~~ ~~20~~ 14 bytesSBCS -5 thanks to @ngn. Purely arithmetic solution (doesn't actually do any base conversions) and thus very fast. ``` 3∊⊢(|×∘⌈⍟)⍨1↓⍳ ``` [Try it online!](https://tio.run/##Jc4xCsIwFMbx3VN8ow5CkzQvyQWcHL1AwdqloFQcBOdSigHBQRcRnLp7A73Ju0htn0N@vOH7Q7JdOV8fs3Jb9P2G64vhpuX2NT19b9zc@dxwfM44dorrK8f3MPp0Fs5AJWp44@GgNQzBWoQAcHxgVR3yybD0UB7aQDsEj5DAezgN8rJaZOVeZimRJYw60YthlBJRiVo0YipaUVqSlqQlaZ20Tv3/tMyqIp/8AA "APL (Dyalog Unicode) – Try It Online") `⊢(`…`)⍨1↓⍳` on one dropped from the **ɩ**ndices 1…argument and the argument, apply:  `|` the division remainders  `×∘⌈` times the rounded-up  `⍟` logN Argument `3∊` is three a member of that? [Answer] # [Pyth](https://pyth.readthedocs.io), 10 bytes ``` }]1>R2jLQS ``` **[Verify all the test cases.](https://pyth.herokuapp.com/?code=%7D%5D1%3ER2jLQS&test_suite=1&test_suite_input=73++%0A101+%0A1073%0A17%0A22%0A36%0A55%0A99++%0A8%0A18%0A23%0A27%0A98%0A90%0A88%0A72%0A68&debug=0)** [Answer] # [Husk](https://github.com/barbuz/Husk), 15 bytes ``` V§&o=1→o=3LṠMBḣ ``` [Try it online!](https://tio.run/##ASEA3v9odXNr//9Wwqcmbz0x4oaSbz0zTOG5oE1C4bij////MjM "Husk – Try It Online") ### Explanation ``` V§&(=1→)(=3L)ṠMBḣ -- implicit input, for example: 5 ṠMB -- map "convert 5 to base" over.. ḣ -- range [1..5] -- [[1,1,1,1,1],[1,0,1],[1,2],[1,1],[1,0]] V -- does any of the elements satisfy the following §&( 1 )( 2 ) -- apply functions 1,2 and join with & (logical and) =3L -- is length equals to 3? =1→ -- is last digit 1? ``` [Answer] # PHP, 48+1 bytes ``` while(++$b**2<$n=$argn)$n%$b-1|$n>$b**3||die(1); ``` exits with `0` for falsy (or input `3`), `1` for truthy. Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/afc2cbb631c1ff4a37d62ddacaa77d5c49e5c348). [Answer] # C, 60 bytes A function that returns non-zero if the argument can be represented as a three-digit number ending in 1: ``` i,j;f(n){for(j=0,i=sqrt(n);i>cbrt(n);)j+=n%i--==1;return j;} ``` Note: this works with GCC, where the functions are built-in. For other compilers, you probably need to ensure that the argument and return types are known: ``` #include<math.h> ``` # Explanation The lowest base in which `n` is represented in 3 digits is `⌊∛n⌋`, and the lowest base in which `n` is represented in 2 digits is `⌊√n⌋`, so we simply test whether the number is congruent to 1 modulo any bases in the 3-digit range. We return the count of the number of bases satisfying the condition, giving a non-zero (truthy) or zero (falsy) value as appropriate. # Test program Pass any number of inputs as positional parameters: ``` #include<stdio.h> int main(int c,char**v) { while(*++v) printf("%s => %d\n", *v, f(atoi(*v))); } ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 19 bytesSBCS [Dennis' method](https://codegolf.stackexchange.com/a/150794/43319). ``` (⊂,1)∊2↓¨⊢⊥⍣¯1¨⍨1↓⍳ ``` [Try it online!](https://tio.run/##Jc4xCsJAEAXQPqf4pYJCdpOd3b2AlaUXCBjTBJSIha1FkIWAYG2jCOksvEGOMheJm7HYx8zwP2xxqJfbc1Hvq3HccXubcbgs1JyvQXN7H3oOTw5v7l7DR8Wt61U8c/eN6aE3sBlUquKbBgutkRGMgfcAdw9smlOZxKSDctAZtIV38Cmcg9UgJ6lVUR8llhMZwqQVnegnKRWVqMVMzEUjSpekS9Il6VrpWvX/07poqjL5AQ "APL (Dyalog Unicode) – Try It Online") `(⊂,1)∊` Is `[1]` a member of `2↓¨` two elements dropped from each of `⊢⊥⍣¯1¨⍨` the argument represented in each of the bases `1↓⍳` one dropped from the **ɩ**ndices 1 through the argument? [Answer] # [Julia](http://julialang.org/), 31 bytes ``` n->any(i>n/i^2>n%i==1for i=2:n) ``` [Try it online!](https://tio.run/##LYxBCsIwEEX3nmIoFRKI2KTNxAjpRUShoIVIGaXowtPHaaeLzPv8H97zO@UBy5gKHfqBfir3dMw319M@p2TH1ww5uTPpskSCTHDxBkJrwDZ2OWsMBpwz0KIBz3OMBk5c83M8O54j59hwzQz8FZkdokdBEGxlXIGNwAqcoBV0Ai8QC4plU6NYgliCve4A3nOmz0SqqglqNSrSutK7B93LHw "Julia 0.6 – Try It Online") [Answer] # [Pyt](https://github.com/mudkip201/pyt), ~~35~~ 33 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage) ``` ←ĐĐ3=?∧∧:ŕĐ2⇹Ř⇹Ľ⅟⌊⁺3=⇹Đ2⇹Ř%*ž1⇹∈; ``` Explanation: ``` ←ĐĐ Push input onto stack 3 times 3=? : ; If input equals 3, execute code after the question mark;otherwise, execute code after the colon. In either case, afterwards, execute the code after the semicolon ∧∧ Get 'True' : Input not equal to 3 ŕ Remove 'False' Đ2⇹Ř Push [2,3,...,n] ⇹Ľ⅟⌊⁺ Push [floor(log_2(n))+1,floor(log_3(n))+1,...,floor(log_n(n))+1] 3= Is each element equal to 3 ⇹ Swap the top two elements on the stack (putting n back on top) Đ2⇹Ř Push [2,3,...,n] % Push [n%2,n%3,...,n%n] * Multiply [n%x] by the other array (i.e. is floor(log_x(n))+1=3?) ž Remove all zeroes from the array 1⇹∈ Is 1 in the array? ; End conditional Implicit print ``` [Try it online!](https://tio.run/##K6gs@f//UduEI0BobGv/qGM5EFkdnXpkgtGj9p1HZwCJI3sftc5/1NP1qHGXsS2ID5VS1Tq6zxDIetTRYf3/v7kxAA) [Answer] # [><>](https://esolangs.org/wiki/Fish), 42 bytes ``` 1<v?)}:{*::+ n~\1-:::**{:}):?!n~:{:}$%1=:? ``` [Try it online!](https://tio.run/##S8sszvj/39CmzF6z1qpay8pKmyuvLsZQ18rKSkur2qpW08peMa/OCshSUTW0tbL///@/bpmREQA "><> – Try It Online") Returns `10` for truthy, `00` for falsey. ]
[Question] [ Your goal is to create a function or a program to reverse the bits in a range of integers given an integer \$n\$. In other words, you want to find the [bit-reversal permutation](https://en.wikipedia.org/wiki/Bit-reversal_permutation) of a range of \$2^n\$ items, zero-indexed. This is also the OEIS sequence [A030109](https://oeis.org/A030109). This process is often used in computing Fast Fourier Transforms, such as the in-place Cooley-Tukey algorithm for FFT. There is also a [challenge](https://codegolf.stackexchange.com/questions/12420/too-fast-too-fourier-fft-code-golf) for computing the FFT for sequences where the length is a power of 2. This process requires you to iterate over the range \$[0, 2^n-1]\$, convert each value to binary and reverse the bits in that value. You will be treating each value as a \$n\$-digit number in base 2 which means reversal will only occur among the last \$n\$ bits. For example, if \$n = 3\$, the range of integers is `[0, 1, 2, 3, 4, 5, 6, 7]`. These are ``` i Regular Bit-Reversed j 0 000 000 0 1 001 100 4 2 010 010 2 3 011 110 6 4 100 001 1 5 101 101 5 6 110 011 3 7 111 111 7 ``` where each index \$i\$ is converted to an index \$j\$ using bit-reversal. This means that the output is `[0, 4, 2, 6, 1, 5, 3, 7]`. The output for \$n\$ from 0 thru 4 are ``` n Bit-Reversed Permutation 0 [0] 1 [0, 1] 2 [0, 2, 1, 3] 3 [0, 4, 2, 6, 1, 5, 3, 7] ``` You may have noticed a pattern forming. Given \$n\$, you can take the previous sequence for \$n-1\$ and double it. Then concatenate that doubled list to the same double list but incremented by one. To show, ``` [0, 2, 1, 3] * 2 = [0, 4, 2, 6] [0, 4, 2, 6] + 1 = [1, 5, 3, 7] [0, 4, 2, 6] ⊕ [1, 5, 3, 7] = [0, 4, 2, 6, 1, 5, 3, 7] ``` where \$⊕\$ represents concatenation. You can use either of the two methods above in order to form your solution. If you know a better way, you are free to use that too. Any method is fine as long as it outputs the correct results. ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest solution wins. * Builtins that solve this challenge as a whole and builtins that compute the bit-reversal of a value are not allowed. This does not include builtins which perform binary conversion or other bitwise operations. * Your solution must be, at the least, valid for \$n\$ from 0 to 31. [Answer] # [Haskell](https://www.haskell.org/), ~~40~~ 37 bytes ``` f 0=[0] f a=[(*2),(+1).(*2)]<*>f(a-1) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P03BwDbaIJYrTSHRNlpDy0hTR0PbUFMPxIq10bJL00jUNdT8n5uYmadgq5CbWOAbr6BRUJSZV6KXpqkQbahjpGOsYxL7HwA "Haskell – Try It Online") Thanks to @Laikoni for three bytes! [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 8 bytes Code: ``` ¾)IF·D>« ``` Explanation: ``` ¾ # Constant for 0. ) # Wrap it up into an array. IF # Do the following input times. · # Double every element. D # Duplicate it. > # Increment by 1. « # Concatenate the first array. ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=wr4pSUbCt0Q-wqs&input=Mw). [Answer] # MATL, ~~13~~ ~~12~~ ~~10~~ ~~9~~ 8 bytes ``` 0i:"EtQh ``` [**Try it Online**](http://matl.tryitonline.net/#code=MGk6IkV0UWg&input=Mw) **Explanation** ``` 0 % Push number literal 0 to the stack i:" % Loop n times E % Multiply by two t % Duplicate Q % Add one h % Horizontally concatenate the result % Implicit end of loop, and implicitly display the result ``` --- For the sake of completeness, here was my old answer using the non-recursive approach (9 bytes). ``` W:qB2&PXB ``` [**Try it Online**](http://matl.tryitonline.net/#code=VzpxQjImUFhC&input=Mw) **Explanation** ``` W % Compute 2 to the power% ofImplicitly thegrab input (n) and compute 2^n : % Create an array from [1...2^n] q % Subtract 1 to get [0...(2^n - 1)] B % Convert to binary where each row is the binary representation of a number 2&P % Flip this 2D array of binary numbers along the second dimension XB % Convert binary back to decimal % Implicitly display the result ``` [Answer] # J, ~~15~~ 11 bytes ``` 2&(*,1+*)0: ``` There is an alternative for **15 bytes** that uses straight-forward binary conversion and reversal. ``` 2|."1&.#:@i.@^] ``` ## Usage ``` f =: 2&(*,1+*)0: f 0 0 f 1 0 1 f 2 0 2 1 3 f 3 0 4 2 6 1 5 3 7 f 4 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 ``` ## Explanation ``` 2&(*,1+*)0: Input: n 0: The constant 0 2&( ) Repeat n times starting with x = [0] 2 * Multiply each in x by 2 1+ Add 1 to each , Append that to 2 * The list formed by multiplying each in x by 2 Return that as the next value of x Return the final value of x ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` 2ṗ’UḄ ``` [Try it online!](https://tio.run/##y0rNyan8/9/o4c7pjxpmhj7c0fL//39jAA "Jelly – Try It Online") -1 thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis). [Answer] # Octave, 37 bytes ``` @(n)bin2dec(fliplr(dec2bin(0:2^n-1))) ``` Creates an anonymous function named `ans` that can simply be called with `ans(n)`. [**Online Demo**](http://ideone.com/1jopEJ) [Answer] # Python 2, ~~56~~ ~~55~~ 54 bytes ``` f=lambda n:[0][n:]or[i+j*2for i in 0,1for j in f(n-1)] ``` Test it on [Ideone](http://ideone.com/Smw0nC). *Thanks to @xnor for golfing off 1 byte!* [Answer] # Java, ~~422~~ 419 bytes: ``` import java.util.*;class A{static int[]P(int n){int[]U=new int[(int)Math.pow(2,n)];for(int i=0;i<U.length;i++){String Q=new String(Integer.toBinaryString(i));if(Q.length()<n){Q=new String(new char[n-Q.length()]).replace("\0","0")+Q;}U[i]=Integer.parseInt(new StringBuilder(Q).reverse().toString(),2);}return U;}public static void main(String[]a){System.out.print(Arrays.toString(P(new Scanner(System.in).nextInt())));}} ``` Well, I finally learned Java for my second programming language, so I wanted to use my new skills to complete a simple challenge, and although it turned out *very* long, I am not disappointed. I am just glad I was able to complete a simple challenge in Java. [Try It Online! (Ideone)](http://ideone.com/fy1xGj) [Answer] ## Mathematica, ~~56~~ 33 bytes Byte count assumes an ISO 8859-1 encoded source. ``` ±0={0};±x_:=Join[y=±(x-1)2,y+1] ``` This uses the recursive definition to define a unary operator `±`. [Answer] # Perl, ~~46~~ 45 bytes Includes +1 for `-p` Give input number on STDIN ``` #!/usr/bin/perl -p map$F[@F]=($_*=2)+1,@F for(@F=0)..$_;$_="@F" ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḥ;‘$$¡ ``` *Thanks to @EriktheOutgolfer for golfing off 1 byte!* [Try it online!](https://tio.run/##y0rNyan8///hjiXWjxpmqKgcWvj/vzEA "Jelly – Try It Online") ### How it works ``` Ḥ;‘$$¡ Main link. No arguments. Implicit argument / initial return value: 0 ¡ Read an integer n from STDIN and call the link to the left n times. $ Combine the two links to the left into a monadic chain, to be called with argument A (initially 0, later an array). Ḥ Unhalve; yield 2A. $ Combine the two links to the left into a monadic chain, to be called with argument 2A. ‘ Increment; yield 2A + 1 ; Concatenate 2A and 2A + 1. ``` [Answer] # Pyth - 11 bytes ``` ushMByMGQ]0 ``` [Test Suite](http://pyth.herokuapp.com/?code=ushMByMGQ%5D0&test_suite=1&test_suite_input=0%0A1%0A2%0A3&debug=0). [Answer] # Javascript ES6, ~~65~~ ~~53~~ 51 bytes ``` f=(n,m=1)=>n?[...n=f(n-1,m+m),...n.map(i=>i+m)]:[0] ``` Uses the recursive double-increment-concat algorithm. Example runs: ``` f(0) => [0] f(1) => [0, 1] f(2) => [0, 2, 1, 3] f(4) => [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] ``` [Answer] # Python 3, ~~67~~ 59 bytes *Thanks to @Dennis for -8 bytes* ``` lambda n:[int(bin(i+2**n)[:1:-1],2)//2for i in range(2**n)] ``` We may as well have a (modified) straightforward implementation in Python, even if this is quite long. An anonymous function that takes input by argument and returns the bit-reversed permutation as a list. **How it works** ``` lambda n Anonymous function with input n ...for i in range(2**n) Range from 0 to 2**n-1 bin(i+2**n)[:1:-1] Convert i+2**n to binary string, giving 1 more digit than needed, remove '0b' from start, and reverse int(...,2) Convert back to decimal ...//2 The binary representation of the decimal value has one trailing bit that is not required. This is removed by integer division by 2 :[...] Return as list ``` [Try it on Ideone](https://ideone.com/Atgesv) [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 12 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Requires `⎕IO←0` which is default on many systems. ``` 2⊥⊖2⊥⍣¯1⍳2*⎕ ``` `2⊥` from-base-2 of `⊖` the flipped `2⊥⍣¯1` inverse of from-base-2 of `⍳` the first *n* integers, where *n* is `2*` 2 to the power of `⎕` numeric input [TryAPL online!](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20%u2206%u21900%20%u22C4%202%u22A5%u22962%u22A5%u2363%AF1%u23732*%u2206%20%u22C4%20%u2206%u21901%20%u22C4%202%u22A5%u22962%u22A5%u2363%AF1%u23732*%u2206%20%u22C4%20%u2206%u21902%20%u22C4%202%u22A5%u22962%u22A5%u2363%AF1%u23732*%u2206%20%u22C4%20%u2206%u21903%20%u22C4%202%u22A5%u22962%u22A5%u2363%AF1%u23732*%u2206&run) --- For comparison, here is the other method: ``` (2∘×,1+2∘×)⍣⎕⊢0 ``` `(` the function train...  `2∘×` two times (the argument)  `,` concatenated to  `1+` one plus  `2∘×` two times (the argument) `)⍣` applied as many times as specified by `⎕` numeric input `⊢` on `0` zero [Answer] # [Ruby](https://www.ruby-lang.org/), 51 bytes ``` f=->n{n<1?[0]:(a=f[n-1].map{|i|i*2})+a.map(&:next)} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y6vOs/G0D7aINZKI9E2LTpP1zBWLzexoLomsyZTy6hWUzsRxNVQs8pLrSjRrP1voleSmZtarJCSrwBUwsVZUFpSrKCkXJ1Zq6Brp6BcnRadGVurxJWal/IfAA "Ruby – Try It Online") [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), ~~11~~ 8 bytes ``` 2/|!2|&: ``` [Try it online!](https://tio.run/##y9bNS8/7/z/Nyki/RtGoRs3qf5q6obai6X8A "K (ngn/k) – Try It Online") ``` x:3 / just for testing &x / that many zeroes 0 0 0 2|&x / max with 2 2 2 2 !x#2 / binary words of length x, as a transposed matrix (0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 1 0 1 0 1 0 1) |!x#2 / reverse (0 1 0 1 0 1 0 1 0 0 1 1 0 0 1 1 0 0 0 0 1 1 1 1) 2/|!x#2 / base-2 decode the columns 0 4 2 6 1 5 3 7 ``` `&` is the last verb in the composition so we need a `:` to force it to be monadic [Answer] # [Ruby](https://www.ruby-lang.org/), ~~57 47~~ 39 bytes ``` ->n{[*0...2**n].sort_by{|a|a.digits 2}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOlrLQE9Pz0hLKy9Wrzi/qCQ@qbK6JrEmUS8lMz2zpFjBqLb2f4FCWrRRLBeIMoZQJrH/AQ "Ruby – Try It Online") 3 years later, 18 bytes golfed. [Answer] # Julia, ~~23~~ 22 bytes ``` !n=n>0&&[t=2*!~-n;t+1] ``` Rather straightforward implementation of the process described in the challenge spec. [Try it online!](http://julia.tryitonline.net/#code=IW49bj4wJiZbdD0yKiF-LW47dCsxXQoKZm9yIG4gaW4gMDozCiAgICBAcHJpbnRmKCIlZCAtPiAlc1xuIiwgbiwgIW4pCmVuZA&input=) [Answer] # Pyth, 8 bytes ``` iR2_M^U2 ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=iR2_M%5EU2&input=3&test_suite_input=0%0A1%0A2%0A3&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=iR2_M%5EU2&input=3&test_suite=1&test_suite_input=0%0A1%0A2%0A3&debug=0) ### Explanation: ``` iR2_M^U2Q implicit Q (=input number) at the end ^U2Q generate all lists of zeros and ones of length Q in order _M reverse each list iR2 convert each list to a number ``` [Answer] ## Clojure, 78 bytes Just following the spec... ``` (defn f[n](if(= n 0)[0](let[F(map #(* 2 %)(f(dec n)))](concat F(map inc F))))) ``` [Answer] # PHP, 57 bytes ``` while($i<1<<$argv[1])echo bindec(strrev(decbin($i++))),_; ``` takes input from command line parameter, prints underscore-delimited values. Run with `-nr`. **recursive solution, 72 bytes** ``` function p($n){$r=[$n];if($n)foreach($r=p($n-1)as$q)$r[]=$q+1;return$r;} ``` function takes integer, returns array [Answer] ## JavaScript (Firefox 30-57), 48 bytes ``` f=n=>n?[for(x of[0,1])for(y of f(n-1))x+y+y]:[0] ``` Port of @Dennis♦'s Python 2 solution. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ 13 bytes ``` 2pU Ǥw ú0U Í ``` [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=MnBVIMekdyD6MFUgzQ==&input=LW1SClsxLCAyLCAzLCA0LCA1XQ==) ### Unpacked & How it works ``` 2pU o_s2 w ú0U n2 2pU 2**n o_ range(2**n).map(...) s2 convert to binary string w reverse ú0U right-pad to length n, filling with '0' n2 convert binary string to number ``` Straightforward implementation. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 9 bytes ``` (⍋,⍨)⍣⎕⊢0 ``` [Try it online!](https://tio.run/##HYw9CsJAEIX7PcV2o5DAbuIPWHiXJWEluBjZpBFJJxoTN9hYWqiNFxAh4GXmInGSYt68x/dm1Nb48U6ZdOVHRmVZEnXY3JIUj1fBsDzpboSu9tC9x@hehLB6io4AQ9dIvPyg0NTdgwcE@7GA7gNYVkS/lCMLGji6e25VrDf@koTl/Q318PywZDW6dgHpGrA@gFaJoR8tYVt0gudcMNkrlywYdsAlD1k4@AmlGeUpD/mc@X8 "APL (Dyalog Classic) – Try It Online") `⎕` evaluated input `(` `)⍣⎕⊢0` apply the thing in `(` `)` that many times, starting with `0` `,⍨` concatenate the current result with itself `⍋` indices of a sort-ascending permutation [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 25 bytes ``` {[X+] 0,|(0 X(2 X**^$_))} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OjpCO1bBQKdGw0AhQsNIIUJLK04lXlOz9n9BaYlCmgaQbWenl5ZboqGuamBUoa6pkJZfpBBnYf0fAA "Perl 6 – Try It Online") # [Perl 6](https://github.com/nxadm/rakudo-pkg), 42 bytes ``` {0,{$^p+^($_-$_/2+>lsb ++$)}...$_}o 1+<*-1 ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2kCnWiWuQDtOQyVeVyVe30jbLqc4SUFbW0WzVk9PTyW@Nl/BUNtGS9fwvzVXQWmJQhpQoaadnV5abomGuqqBUYW6pkJafpFCnIX1fwA "Perl 6 – Try It Online") Incrementing an integer simply flips a sequence of least-significant bits, for example from `xxxx0111` to `xxxx1000`. So the next bit-reversed index can be obtained from the previous one by flipping a sequence of most-significant bits. The XOR mask can be computed with `m - (m >> (ctz(i) + 1))` for `m = 2**n` or `m = 2**n-1`. [Answer] # TI-BASIC, 26 bytes ``` Input A:{0:For(I,1,A:2Ans:augment(Ans,1+Ans:End:Ans ``` Prompts the user to input *n*. Outputs the bit-reversal permutation as is specified in the challenge. **Explanation:** ``` Input A ;prompt the user for "n". store the input into A {0 ;leave {0} in Ans For(I,1,A ;loop A times 2Ans ;double Ans and leave the result in Ans augment(Ans,1+Ans ;add 1 to Ans and append it to the previous result ; leave the new result in Ans End ;loop end Ans ;leave Ans in Ans ;implicit print of Ans ``` **Examples:** ``` prgmCDGF25 ?1 {0 1} prgmCDGF25 ?3 {0 4 2 6 1 5 3 7} ``` **Note:** TI-BASIC is a tokenized language. Character count does *not* equal byte count. [Answer] # [Desmos](https://desmos.com/calculator), 71 bytes ``` f(n)=[total(mod(floor(2i/2^{[1...n]}),2)2^{[n-1...0]})fori=[0...2^n-1]] ``` Straightforward implementation of the challenge (convert to binary, then reverse), but probably optimizable with actions... [Try It On Desmos!](https://www.desmos.com/calculator/icphgaiuxq) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/thym4i9rks) [Answer] # [Factor](https://factorcode.org/), 43 bytes ``` [ { 0 } [ 2 v*n dup 1 v+n append ] repeat ] ``` [Try it online!](https://tio.run/##JcsxDoJAEEbhnlP8tRqCxkoPYGxsjNWGYoQRiTCMswOJGs@@amxfvnehygdLp@P@sNugJ7/mE/9SxI1NuEPk@8hScUTDwkZd@yRvB4lQY/eHWiv@P42k@bptlhVYI9DiXKaAFwq8EbDCNBPUo2KJaS4gVZYaJYyVyVGmnhR5@gA "Factor – Try It Online") [Answer] # x86, 31 bytes Takes a sufficiently large `int[] buffer` in `eax` and *n* in `ecx`, and returns the buffer in `eax`. Implements the concatenating algorithm given in the challenge statement. It may be possible to save bytes by incrementing the pointers by 4 instead of using array accesses directly, but `lea`/`mov` is already pretty short (3 bytes for 3 regs and a multiplier). ``` .section .text .globl main main: mov $buf, %eax # buf addr mov $3, %ecx # n start: xor %ebx, %ebx mov %ebx, (%eax) # init buf[0] = 0 inc %ebx # x = 1 l1: mov %ebx, %edi dec %edi # i = x-1 lea (%eax,%ebx,4), %edx # buf+x l2: mov (%eax,%edi,4), %esi # z = buf[i] sal %esi # z *= 2 mov %esi, (%eax,%edi,4) # buf[i] = z inc %esi # z += 1 mov %esi, (%edx,%edi,4) # buf[x+i] = z dec %edi # --i jns l2 # do while (i >= 0) sal %ebx # x *= 2 loop l1 # do while (--n) ret .data buf: .space 256, -1 ``` Hexdump: ``` 00000507 31 db 89 18 43 89 df 4f 8d 14 98 8b 34 b8 d1 e6 |1...C..O....4...| 00000517 89 34 b8 46 89 34 ba 4f 79 f1 d1 e3 e2 e7 c3 |.4.F.4.Oy......| ``` ]
[Question] [ # The Objective Build a random number generator whose range is \$\left[0,1\right) \cap \mathbb{Q} .\$ This is, build a random number generator that can produce any value that's: 1. at least \$0 \,;\$ 2. not \$1\$ or greater; and 3. expressible as the ratio of two integers. --- # What's the fuss? This RNG is weird. Its range is nowhere *connected*, but is *dense* in the interval! --- # The probability mass function We define an ordering for all values that the RNG can return, such that each return value \$ x\$ can be associated with an index \$ i .\$ Then, the probability of returning \$x\_i\$ should be \$P\left(x\_i\right) = {\left(\frac{1}{2}\right)}^{i} .\$ Since $$ \sum\limits\_{i=1}^{\infty}{{\left(\frac{1}{2}\right)}^{i}} = 1 \,, $$ this yields a total probability of \$1 ,\$ where the numbers earlier in the ordering are significantly more likely than numbers later in the ordering. The ordering is: 1. Start with the first value, \$ \frac{0}{1}.\$ 2. Increment the numerator. 3. If the numerator equals the denominator, then: * reset the numerator to \$ 0 ;\$ and * increment the denominator. 4. Add the value to the ordering *if* it's not equivalent to a value already in the ordering. * For example, \$\frac{2}{4}\$ is constructed after \$\frac{1}{2} ,\$ so it's *not* added to the ordering. 5. Go back to Step (2). For example, the first few values and their corresponding probabilities are: $$ \begin{array}{r|c|c|c|c|c|c|c|c|c|c} \textbf{Index}~\left(i\right) & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & \cdots \\\hline \textbf{Value}~\left(x\right) & \frac{0}{1} & \frac{1}{2} & \frac{1}{3} & \frac{2}{3} & \frac{1}{4} & \frac{3}{4} & \frac{1}{5} & \frac{2}{5} & \frac{3}{5} & \frac{4}{5} & \cdots \\\hline \textbf{Probability}~\left(P\right) & \frac{1}{ 2} & \frac{1}{ 4} & \frac{1}{ 8} & \frac{1}{ 16} & \frac{1}{ 32} & \frac{1}{ 64} & \frac{1}{ 128} & \frac{1}{ 256} & \frac{1}{ 512} & \frac{1}{1024} & \cdots \end{array} \_{\large{.}} $$ --- # Rules 1. There is no input. The RNG outputs a number upon invocation. 2. You must use rational number arithmetic. In particular, `X` must be represented as a rational number. If your language doesn't natively support it, use a pair of integers. For example, in Haskell, `Rational` is a valid type. 3. As long as the numerator and the denominator are distinguishable, the output format doesn't matter. 4. As this is a code-golf, the shortest code in bytes wins. [Answer] # JavaScript (ES6), 81 bytes Returns \$p/q\$ as `[p,q]`. ``` f=(p=0,q=1)=>Math.random()<(g=(a,b)=>b?g(b,a%b):a)(p,q)/2?f(++p-q?p:!++q,q):[p,q] ``` [Try it online!](https://tio.run/##FclNDoIwEEDhPacYFyYzaUFkCVRO4AmMiylQxGB/gLgxnr3W1Uu@9@Q3b/06@z23bhhjNAq9KmVQZ1KXK@@PYmU7uBdSi5NCljq57ibUko@aaib0MtCp6gwK4fPQ@fogREhW39K5R@NWtKCgbMBCC9W/QhB8MoDe2c0tY7G4CQ0SNdk3/gA "JavaScript (Node.js) – Try It Online") Or [Try some statistics!](https://tio.run/##TY9PT8MwDMXv@xTmMNVW2mxDCKRu2U5wQxw4jh6S/qNjS9I2QqBpfPXi0sO4JPZ7T/7ZB/2p@7xrfEisK8phqBR6tYxbtSK1fdbhXXbaFu6EtMFaoY4N62ZXo4n13FCqCX3c0uJ2V6EQPml3Pr0RomUt3bOTDZXrsA86KDhfYrCgYLnmbwOr8p4LIQjOM4A9@BhayNivkNasVJ3OufMgIFpE/LajOo7aj9aYTH6u7Xp2meXO9u5YyqOr8cUcyjzIj/K7/@OT7F0XkE8AQ6C20ySTQTJVOiN50h4n7HbCMzqFkX3lyOBeQ9fYGkl6XTzaAh@IE/hvswUfd0ecfGq@ygJvRz@aRyQPrrEYvdmIaPgF) ### How? We recursively build the fractions \$p/q\$ in the relevant order, but without any explicit deduplication, until a random number picked in \$[0,1[\$ is greater than or equal to \$gcd(p,q)/2\$. If \$p\$ and \$q\$ are not coprime, we have \$gcd(p,q)/2\ge1\$, which always triggers the recursive call. This is the expected behavior because the corresponding fraction must be discarded. If \$p\$ and \$q\$ are coprime, we have \$gcd(p,q)/2=1/2\$, which is the desired probability of triggering the next call. ### Commented ``` f = ( // f is a recursive function taking: p = 0, // p = numerator, starting at 0 q = 1 // q = denominator, starting at 1 ) => // Math.random() < // pick a random number in [0,1[ (g = (a, b) => // g is a recursive function computing the gcd of 2 integers b ? // if b is not equal to 0: g(b, a % b) // recursive call with (b, a mod b) : // else: a // return a )(p, q) / 2 ? // if our random number is less than gcd(p, q) / 2: f( // do a recursive call: ++p - q ? p // increment p if p < q - 1 : !++q, // otherwise: set p to 0 and increment q q // ) // end of recursive call : // else: [p, q] // stop recursion and return [p, q] ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~74~~ 67 bytes Probably not the golfiest solution for Ruby, but it was the first thing that sprung to mind. Increment the counter `$.` (starts at 0) each time `rand` is at least 0.5 to determine the index, then determine the list of rationals and output the right one. -7 bytes from histocrat. ``` d,*a=1r $.+=1until rand<0.5 a|=(0...d+=1).map{|n|n/d}until p *a[$.] ``` [Try it online!](https://tio.run/##KypNqvz/P0VHK9HWsIhLRU/b1rA0ryQzR6EoMS/FxkDPlCuxxlbDQE9PLwUopamXm1hQXZNXk6efUgtRV6CglRitohf7/z8A "Ruby – Try It Online") [Answer] # [Julia](https://julialang.org), ~~61~~ ~~49~~ 71 bytes ``` p>q=rand()<.5 ? (p<q-1 ? (while gcd(p+=1,q)!=1 end;p>q) : 1>q+1) : p//q ``` In un-golfed form, this reads ``` function f(p,q) # define the function if rand() < 0.5 # flip a coin. if p < (q - 1) # if the coin gives heads, check if p < (q - 1) while gcd(p+1, q) != 1 # if the greatest common divisor or p+1 and q is not equal to 1 p = p + 1 # we increment p, because otherwise we'd get a fraction we already saw. end return f(p, q) # recursively call f(p, q) (where p has been incremented) else return f(1, q+1) # if p is not greater than q - 1, we recursively call f(1, q+1) end else return p//q # If the coin flip gives tails, we return the Rational number p//q end end ``` Now let's check to make sure we did this right: ``` julia> using UnicodePlots; data = [0>1 for _ in 1:10_000_000]; histogram(data) ┌ ┐ [0.0 , 0.05) ┤▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 5000106 [0.05, 0.1 ) ┤ 0 [0.1 , 0.15) ┤ 1168 [0.15, 0.2 ) ┤▇ 82600 [0.2 , 0.25) ┤ 0 [0.25, 0.3 ) ┤▇▇ 313684 [0.3 , 0.35) ┤▇▇▇▇▇▇▇▇ 1250427 [0.35, 0.4 ) ┤ 39124 [0.4 , 0.45) ┤ 310 [0.45, 0.5 ) ┤ 0 [0.5 , 0.55) ┤▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 2498798 [0.55, 0.6 ) ┤ 168 [0.6 , 0.65) ┤ 19403 [0.65, 0.7 ) ┤▇▇▇▇ 625484 [0.7 , 0.75) ┤ 77 [0.75, 0.8 ) ┤▇ 166131 [0.8 , 0.85) ┤ 2473 [0.85, 0.9 ) ┤ 47 └ ┘ Frequency julia> for frac in [(0//1), (1//2), (1//3), (2//3), (1//4), (3//4), (1//5), (2//5), (3//5), (4//5), (1//6), (5//6)] freq = count(x -> x == frac, data)/length(data) println("P($(frac)) ≈ $freq") end P(0//1) ≈ 0.5000106 P(1//2) ≈ 0.2498798 P(1//3) ≈ 0.1250427 P(2//3) ≈ 0.0625484 P(1//4) ≈ 0.0313065 P(3//4) ≈ 0.0156477 P(1//5) ≈ 0.0077772 P(2//5) ≈ 0.0039116 P(3//5) ≈ 0.0019398 P(4//5) ≈ 0.0009654 P(1//6) ≈ 0.0004828 P(5//6) ≈ 0.0002473 ``` Notice that `P(5//6) ≈ 0.5 * P(1//6)` as required since `2//6`, `3//6`, and `4//6` are reducible fractions. [Try it online!](https://repl.it/repls/ZanyNiftyConditional) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 27 bytes ``` i⊃⍸1=∘.(>×∨)⍨⍳2+i←1+⍣{?2}¯1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkGXGlAsvr/o569mY@6mh/17jC0fdQxQ0/D7vD0Rx0rNB/1rnjUu9lIOxOoylD7Ue/ianuj2kPrDf/XgowAaX3UuzX6Ue@kR12L9IFM69haoMguHcNU08PbQZo7FwFFax/17Eg7BDIJKA4A "APL (Dyalog Unicode) – Try It Online") Thanks to @ngn for this function. Since this is not strictly *my* answer, I'll keep the older answer below this one. Uses `⎕IO←0`. The function returns a pair in the form `denominator numerator`. ### How: ``` i⊃⍸1=∘.(>×∨)⍨⍳2+i←1+⍣{?2}¯1 ⍝ Dfn ¯1 ⍝ Literal -1 {?2} ⍝ Roll. Since IO is 0, this will roll either 0 or 1 ⍣ ⍝ Power. Repeats the function to the left until the right argument is 0. 1+ ⍝ 1 plus. The whole expression above will result in 1+1+1+...-1; ⍝ each iteration has a 50% chance of being the last one. i← ⍝ Assign the result to i ⍳2+ ⍝ Generate the vector [0..2+i] ⍨ ⍝ Use it as both arguments (⍺ and ⍵) to the fork: ∘.(>×∨) ⍝ For each element of the left argument (⍺), apply: (⍺ > ⍵) × (⍺ ∨ ⍵); ⍝ This will result in a matrix of 0s (if ⍵>⍺) and the GCDs between ⍺ and ⍵. 1= ⍝ Check which elements are 1 (where ⍺ is coprime with ⍵) ⍸ ⍝ Find the coordinates (which will be denominator and numerator) of truthy values i⊃ ⍝ pick the i-th element. ``` --- Old answer: # [APL (Dyalog Unicode)](https://www.dyalog.com/), 55 bytes ``` {(?0)<2÷⍨∨/⍵:∇∊((⊂0,2⊃⍵+1),⊂1 0+⍵)[1+(⊃⍵)<¯1+2⊃⍵]⋄⍵}0 1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1rD3kDTxujw9ke9Kx51rNB/1LvV6lFH@6OOLg2NR11NBjpGj7qagYLahpo6QL6hgoE2kKcZbaitAZHQtDm03lAbqir2UXcLkKo1UDD8n/aobcKj3r5HfVM9/YGyh9YbP2qbCOQFBzkDyRAPz@D/aQA "APL (Dyalog Unicode) – Try It Online") [Statistics](https://tio.run/##SyzI0U2pTMzJT///qKO9KLX4UduE5PzSvJLUIoVMIJFYkpmfV/xfITE9HSjzqHcNl4KVW36RQrKClWeewqPezQhFXAogAFSoA1LZ1VStYW@gaWN0ePuj3hWPOlboP@rdagW041FHl4YGUNpAx@hRVzNQUNtQUwfIN1Qw0AbyNKMNtTUgEpo2h9YbakNVxSo86m4BWri11kDBEOgI17wUoDu4FCBOrn7Uu0sH4RSInZ2LQMof9ewAuin6UW/3o7aJQFYsyKP/YX60TDUFAA) Terribly inefficient port of [@Arnauld's answer](https://codegolf.stackexchange.com/a/194342/74163), so go upvote him. [Answer] # [PHP](https://php.net/), 139 bytes ``` for($r=rand()/(getrandmax()+1),$b=$p=1;$r<1/$p*=2;)for($f=0;!$f;)for(++$a-$b?:++$b&&$a=1,$f=$i=1;++$i<=$a;$f&=0<$b%$i+$a%$i);echo+$a."/$b"; ``` [Try it online!](https://tio.run/##TZFBboMwEEX3PoWLppFd0gS6jHFzh27TKDJgiqXUWLYjRapydjoQIPECPX/PfP0ZXOv6Yu9aRwh4HS7nGKikh6MgYKL2KprODkqe4RGk6TxlYGytryhmgk5c0KfyWU1TTv8IxdOVpxCVj4yLHi0YeOmVrRnfsh8dB/xVV8bTnK@hlOBkLsAX@Rbcm/wQfGxpZCZeoLnf0hTUO5T7HUK5WoGS@RorwGAnSqaQoAQ0K5kVUL6CwXL8cqGrtkPeJFsoE9EP2aaxcRxMiWlO1Vkri0nJ02s4THBM0/vDxQYdGSguJioXcguZhRr0uxGifOhwDbMrikMimnxNqzf2eZH0gbtvm4zr16pq6WJAVXgM8Emh6i42zlsfrUP0J6fquWONf5LTDU2W6tH41v8D "PHP – Try It Online") [Answer] # [J](http://jsoftware.com/), 41 bytes ``` [:({[:~.@,(i.%x:)"0@i.@+&2)>:^:(?@2)^:_@0 ``` [Try it online!](https://tio.run/##DcNBCsIwEAXQfU7xCeokWMOQ5YA2ILhy5bZQkZpihLY0UBAFrx598J5FO@qxFxAqMOR/53C8nE@lEfNp5OtCZZJbv8RqDsmF7cbbg7Ri6uBtK9fAxSqV47ykHEHjMsScOlL5Nt6nIb0jkVKxe0zoNcN4xgpsyw8 "J – Try It Online") At a high-level, I stole ValueInk's idea for first flipping a coin until it comes up heads, and using that number to index into the ordered list of rationals. [Answer] # [MATL](https://github.com/lmendo/MATL), 31 bytes ``` `rEk}@EU:2M&\v1M/t1<fw6#uX&@)Z) ``` Output is numerator, then denominator. [Try it online!](https://tio.run/##y00syfn/P6HINbvWwTXUyshXLabM0Fe/xNAmrdxMuTRCzUEzSvP/fwA) Or [check relative frequencies](https://tio.run/##y00syflvmGpspfQ/ocg1u9bBNdTKyFctRq3M0Fe/xNAmrdxMuTRCzUEzSvO/YmxsmWKAoqWTckRpSbF@RkSwUU6GcQZQBgA) in 1000 realizations (header and footer added; one more byte necessary in main code; TIO running time about 30 seconds). Format is: `num den freq`, each row corresponding to a number. Note that relative frequencies are increasingly imprecise down the table, because the corresponding numbers occur less often. Here is a set of relative frequencies obtained from 100000 realizations (offline compiler): ``` 0 1 0.49828 1 2 0.25022 1 3 0.12643 2 3 0.0611 1 4 0.03128 3 4 0.01657 1 5 0.00814 2 5 0.00383 3 5 0.00206 4 5 0.00099 1 6 0.00047 5 6 0.00024 1 7 0.0002 2 7 6e-05 3 7 6e-05 4 7 5e-05 5 7 2e-05 ``` [Answer] # WDC 65816 machine code, 77 bytes Hexdump: ``` 00000000: 6407 6405 e607 3b85 09e2 31a2 039a 6869 d.d...;...1...hi 00000010: b248 6300 ca10 fac2 30a5 091b a501 102c .Hc.....0......, 00000020: e605 a505 c507 d006 6405 e605 80d6 a607 ........d....... 00000030: 8609 c509 f00f 9004 e509 80f4 488a 38e3 ............H.8. 00000040: 01aa 6880 ebc9 0100 d0d6 80ba 60 ..h.........` ``` Assembly: ``` STZ $07 STZ $05 earlier_loop: INC $07 loop: TSC STA $09 SEP #$31 LDX #$03 TXS PLA ADC #$B2 rngloop: PHA ADC $00,s DEX BPL rngloop REP #$30 LDA $09 TCS LDA $01 BPL done after_rng: INC $05 LDA $05 CMP $07 BNE someplace STZ $05 INC $05 BRA earlier_loop someplace: LDX $07 gcd: STX $09 CMP $09 BEQ gcd_end BCC gcd_else SBC $09 BRA gcd gcd_else: PHA TXA SEC SBC $01,s TAX PLA BRA gcd gcd_end: CMP #$0001 BNE after_rng BRA loop done: RTS ``` ## I/O: * RNG seed in $01-$04 (32 bits, anything but 0) * output is in $05 (numerator), $07 (denom.) * overwrites $00, $09 * assumes 16-bit accumulator on entry * messes with the stack so best called with all interrupts disabled This was more difficult than I first expected. I misread the challenge description and skipped the part about repeats not being counted. The 65816 doesn't have any built-in RNG or floating point math, and it doesn't even have integer multiply/divide. I used the [RNG algorithm from cc65](https://github.com/cc65/cc65/blob/master/libsrc/common/rand.s#L49), a 6502 C compiler, and adapted it a bit (made it smaller). Then I used the [z80 GCD algorithm from Rosetta Code](https://rosettacode.org/wiki/Greatest_common_divisor#Z80_Assembly) and translated it into 65816 assembly. Here's a sample of outputs after running for some number of iterations: ``` 0/1: 0x60e4 = 24804 1/2: 0x3122 = 12578 1/3: 0x187c = 6268 2/3: 0x0c7d = 3197 1/4: 0x05bd = 1469 3/4: 0x0313 = 787 ``` As you can see, each next fraction is about half as likely as the previous one. There isn't a good online 65816 "IDE", but I'm working on making one. For now, if you want to test this, you can write a small bit of wrapper code which logs outputs of the subroutine into a table in RAM and view that table with a debugging SNES emulator (I recommend bsnes-plus). Big thanks to @p4plus2 and @Alcaro for help with optimizing the code. [Answer] # Javascript ES6, 98 chars ``` g=(x,y)=>y?g(y,x%y):x for(x=y=1;y;++x)for(y=0;y<x;++y)if(Math.random()<.5==g(x,y))y=alert(y+"/"+x) ``` ### Demo with `console.log` instead of `alert`: ``` g=(x,y)=>y?g(y,x%y):x for(x=y=1;y;++x)for(y=0;y<x;++y)if(Math.random()<.5==g(x,y))y=console.log(y+"/"+x) ``` ### Probability check: ``` g=(x,y)=>y?g(y,x%y):x f=()=>{for(x=y=1;y;++x)for(y=0;y<x;++y)if(Math.random()<.5==g(x,y))return y+"/"+x} r={} for(q=0;q<32768;++q)r[x=f()]=~~r[x]+1 console.log(Object.keys(r).sort((x,y)=>r[y]-r[x]).map(x=>x+" "+r[x]).join` `) ``` ``` .as-console-wrapper.as-console-wrapper{max-height:100vh} ``` [Answer] # [ink](https://github.com/inkle/ink), 137 bytes ``` =r ~temp e=0 -(d)~e++ ~temp n=-1 -(l)~n++ {e-n:{RANDOM(0,c(e,n)<2):{n}/{e}->->}->l}->d ==function c(a,b) {b: ~return c(b,a%b) } ~return a ``` [Try it online!](https://tio.run/##PcixCsIwFEDRPV/xFiGhCbYFl9AUBFcV/IM2fUKxvkpIp5D8eoxQHO4dzkyvrIDbdSOPTjDVgwPVs7ALdHBqWl0IdonZOJY8vj@ApmaKTyJhVe1ERjXFFpGoWEBFOjzOt8v9ymtpOUoSXSt0oHgMGFWv@rKlNDFjnhtZP68Elg9yFCyMmiWHfnM/GuVwKBj/NOT8BQ "ink – Try It Online") Okay, strap in, this was an adventure. My first attempts at solving this with a full program rather than a function (well, it's a stitch rather than a function, but the point still stands) failed horribly. The logic was sound, but for some reason I was getting `1/3` more than twice as often as `1/2`, and that pattern held for more than 2000 test runs - that wasn't the only place where it failed, but it was the most noticable. So I broke the code down into parts. I ungolfed it, I added debug messages, it didn't work. I ported the core logic to python, as faithfully as I possibly could, and it worked fine. To simplify the testing process, I changed a minor detail to allow me to call my code multiple times during a single run of a program (used a separate variable rather than a readcount for some logic, because readcounts can't be reset). I ran my code a few hundred times as part of a single program, rather than running the program a few hundred times. And suddenly it worked. So I figured the problem was related to the readcount I was using - those have been known to act up at times. So I went back to having my code be a full program, but kept the new variable. And it went back to not working. So I figured, okay, maybe the RNG isn't uniform over the course of multiple runs of a program, but tends towards uniformity if called repeatedly in a single program. That sounded vaguely reasonable - well it kinda didn't, but I was getting desperate. So I wrote two small programs to test my hypothesis - one that generated 100 random values (which I ran once), and one which generated a single random value (which I ran 100 times). And they both gave me about 50 `0`s and 50 `1`s. At my wits' end at this point, I had no idea what was going on, and frankly I still have no idea where to even begin when it comes to figuring it out. So I'm posting a stitch. It would be 18 bytes shorter if I could have it be a full program (code is [here](https://tio.run/##y8zL/v9fVyNFs64kNbdAIc9W15BLVyNHsy5PW5urOkU3z6o6yNHPxd9Xw0AnWSNFJ0/TxkjTqjqvVr86pVbXTtcOSOQAcQqXrW1aaV5ySWZ@nkKyRqJOkiZXdZIVV11RaklpEUgoSSdRFShYCxdK/P8fAA)), but even though the logic would be entirely identical, that appears to not work as it should, and any change I try to make only serves to break it in a different way. Only the gods know why, and they surely envy my ignorance. With that rant out of the way, there are some neat tricks in the code, so let's look at it. The basic idea is that after each number is generated, we have a 50% chance of outputting it, and a 50% chance of continuing to the next number - this strategy wasn't obvious to me at first, but looking at it it becomes obvious that each output will be half as likely as the one before, twice as likely as the next one, and equally as likely as the all the subsequent values combined - which is exactly what we want. Now that `RANDOM` call doesn't obviously look like a 50/50 thing. Well, let's look a bit deeper. You'll notice that its second parameter is actually a boolean expression - meaning it will only ever be `0` or `1`. If it's `1`, `RANDOM` will output either `0` or `1` with equal probability, meaning we have a 50% chance of outputting the current numerator and denominator (it happens if `RANDOM` would generate a non-zero value), while if it's `0` we effectively skip a number. So what is that `c` function then? Well, if you look further down, you'll find it's Euclid's algorithm for finding the greatest common divisor of two numbers. If that's greater than `1`, we won't want to output the number - there's another representation of that number with a strictly smaller numerator and denominator, so we've already skipped that number. But if it is `1`, it's a number we may want to output, so we check if the GCD is `1`, plug the result of the comparison into the `RANDOM` call, and call it a day. conveniently enough, anything is a divisor of `0`, so if the numerator is `0` we will skip the number if the denominator isn't `1`. Which happens to be exactly what we want. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~29~~ 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ®1‚[0L+Ð5°D<Ýs/Ωs¿;@#`αi>®0ǝ ``` Inspired by [*@Arnauld*'s approach](https://codegolf.stackexchange.com/a/194342/52210). [Try it online](https://tio.run/##ATEAzv9vc2FiaWX//8KuMeKAmlswTCvDkDXCsEQ8w51zL86pc8K/O0AjYM6xaT7CrjDHnf//) or [see the counts of 100 outputs](https://tio.run/##AWsAlP9vc2FiaWX/0YJEIkxvb3Agw78gdGltZXM6IixG/8KuMeKAmlswTCvDkDXCsEQ8w51zL86pc8K/O0AjYM6xaT7CrjDHnf99fVwKfSknLMO9RMOZwqnCosKuw7jDrc6j0L1S4oKEzrJ9wrs//w) (it's a bit too slow to do more than 100 in TIO.. >.>). **Explanation:** NOTE: 05AB1E doesn't have a builtin to get a decimal in the range \$[0,1)\$, so instead I create a list in the range \$[0,1)\$ in increments of \$0.00001\$ manually, and get a random value from this list. ``` ®1‚ # Push -1 and 1, and pair them: [-1,1] [ # Start an infinite loop: 0L+ # Increase only the first value by 1 (by adding [1,0]) Ð # Triplicate this pair 5° # Push 10 to the power 5: 10,000 D< # Duplicate it, and decrease the copy by 1 to 9,999 Ý # Create a list in the range [0,9999] s/ # Swap to get the duplicated 10,000, and divide each item by it: # [0, 0.00001, 0.00002, 0.00003, ..., 0.99997, 0.99998, 0.99999] Ω # Pop and push a random item from this list s # Swap to get one of the pairs at the top again ¿ # Get the greatest common divisor (gcd) of the values in this pair ; # Halve it @ # If the random value is larger than or equal to this: # # Stop the infinite loop `αi # If the absolute difference between the two values in the pair is exactly 1: > # Increase both values in the pair by 1 ®0ǝ # And then replace the first value with -1 # (after the loop, output the pair at the top of the stack implicitly) ``` ]
[Question] [ In this challenge you and your friends are debating on which case is better, uppercase or lowercase? To find out, you write a program to do this for you. Because esolangs scare your friends, and verbose code scares you, your code will need to be as short as possible. --- ## Examples ``` PrOgRaMiNgPuZzLeS & CoDe GoLf 0.52 uppercase DowNGoAT RiGHtGoAt LeFTGoat UpGoAT 0.58 uppercase Foo BaR Baz 0.56 lowercase ``` --- ## Specifications The input will consist only of ASCII characters. All non-alphabetic characters should be ignored. There will be at least 1 character of each case The output should be the amount of the case that appears the most often over the total amount of alphabetic characters. It should be a decimal accurate to *at least* 2 decimal places. If uppercase appears more often, the output should end with `uppercase`, or `lowercase`. There will never the the same amount of uppercase and lowercase characters. [Answer] # JavaScript (ES6) 87 bytes **Edit** 1 byte saved thx ETHProductions **Edit** 1 more byte saved thx l4me An anonymous function. Long, but I didn't find a way to golf this more ``` s=>(l=t=0,s.replace(/[a-z]/ig,c=>l+=++t&&c>'Z'),l/=t,l<.5?1-l+' upp':l+' low')+'ercase' ``` **Less golfed** ``` s=>( // arrow function returning the value of an expression // here I use comma for clarity, // in the golfed version it's all merged in a single expression t = 0, // counter for letters l = 0, // counter for lowercase letters s.replace( /[a-z]/ig, // find all alphabetic chars, upper or lowercase c => // execute for each found char (in c) l += ++t && c>'Z', // increment t, increment l if c is lowercase ), l /= t, // l is the ratio now ( l < .5 // if ratio < 1/2 ? (1-l) +' upp' // uppercase count / total (+" upp") : l +' low' // lowrcase count / total (+" low") ) + 'ercase' // common suffix ) ``` [Answer] # CJam, 47 45 bytes ``` q__eu-\_el-]:,_:+df/" low upp"4/.+:e>"ercase" ``` [Try it online.](http://cjam.aditsu.net/#code=q__eu-%5C_el-%5D%3A%2C_%3A%2Bdf%2F%22%20low%20upp%224%2F.%2B%3Ae%3E%22ercase%22&input=PrOgRaMiNgPuZzLeS%20%26%20CoDe%20GoLf) Not golfing for too long... ### Explanation ``` q e# Read input. __eu- e# Get only the lowercase characters. \_el- e# Get only the uppercase characters. ]:, e# Get the lengths of the two strings. _:+ e# Sum of the lengths. df/ e# Lengths divided by the sum of the lengths. " low upp"4/.+ e# Append the first number with " low" and the second " upp" :e> e# Find the maximum of the two. "ercase" e# Output other things. ``` [Answer] ## [Japt](http://ethproductions.github.io/japt/?v=master&code=QT1VZiJcdyIgbCAvVWYiW0EtWmEtel0iIGwpPr0/QSsiIGxvdyI6MS1BKyIgdXBwIiArYIDW0A==&input=Ind3VyI=), 58 bytes ``` A=Uf"[a-z]" l /Uf"[A-Za-z]" l)>½?A+" low":1-A+" upp" +`ÖÐ ``` (Note: SE stripped a special char, before `Ö`, so please click the link to get the proper code) [Answer] # [R](https://www.r-project.org/), ~~133 123 118 108 106 105~~ 104 bytes Golfed down 10 bytes thanks to @ovs,8 thanks to @Giuseppe, and 10 again thanks to @ngm. At this point it's really a collaborative effort where I provide the bytes and others take them off ;) ``` function(x)cat(max(U<-mean(utf8ToInt(gsub('[^a-zA-Z]',"",x))<91),1-U),c("lowercase","uppercase")[1+2*U]) ``` [Try it online!](https://tio.run/##ZY7hS4NAGMa/@1e8nNDu6hw5WKywwBqzwNYw/bJhcLNTBHcnejLznzfNZkUfXnjg5fd7nqKNwTLauBKRSqXANYmYwgdW48AyDpwJXKl44csnoXBSVns82b0xo7GNbTihCNGaEOvaJNQ0AkIjjDJ55EXESo4oqvL8O5OdeTE7D0LS6nameCGY4nDqhL18/wCcSZHwgtxo@rhgsCJAvbmzdc7O/2XDwd10TkKKTm0lz28RIv/ogRw3/ez7ZSGaFmO0KV4Sjz2n62RTbRuXv8IZPMglB0e6MSL65XQ@g9HVE0t5XDvS9sFLnUfVJQUuX/mOZAqCvP8M2OIvtpIS7pnXXTP8r2Cc1X4C "R – Try It Online") [Answer] # [MATL](https://esolangs.org/wiki/MATL), 49 ~~50~~ bytes Uses [current version (4.1.1)](https://github.com/lmendo/MATL/releases/tag/4.1.1) of the language, which is earlier than the challenge. ``` jt3Y2m)tk=Ymt.5<?1w-YU' upp'h}YU' low'h]'ercase'h ``` ### Examples ``` >> matl > jt3Y2m)tk=Ymt.5<?1w-YU' upp'h}YU' low'h]'ercase'h > > PrOgRaMiNgPuZzLeS & CoDe GoLf 0.52 uppercase >> matl > jt3Y2m)tk=Ymt.5<?1w-YU' upp'h}YU' low'h]'ercase'h > > Foo BaR Baz 0.55556 lowercase ``` ### Explanation ``` j % input string t3Y2m) % duplicate. Keep only letters tk=Ym % duplicate. Proportion of lowercase letters t.5<? % if less than .5 1w- % compute complement of proportion YU' upp'h % convert to string and append ' upp' } % else YU' low'h % convert to string and append ' low' ] % end 'ercase' % append 'ercase' ``` [Answer] # Julia, ~~76~~ 74 bytes ``` s->(x=sum(isupper,s)/sum(isalpha,s);(x>0.5?"$x upp":"$(1-x) low")"ercase") ``` This is a lambda function that accepts a string and returns a string. To call it, assign it to a variable. Ungolfed: ``` function f(s::AbstractString) # Compute the proportion of uppercase letters x = sum(isupper, s) / sum(isalpha, s) # Return a string construct as x or 1-x and the appropriate case (x > 0.5 ? "$x upp" : "$(1-x) low") * "ercase" end ``` Saved 2 bytes thanks to edc65! [Answer] # [Perl 6](http://perl6.org), ~~91 70 69 63~~ 61 bytes ``` {($/=($/=@=.comb(/\w/)).grep(*~&' 'ne' ')/$/);"{$/>.5??$/!!1-$/} {<low upp>[$/>.5]}ercase"} # 91 ``` ``` {$/=m:g{<upper>}/m:g{\w};"{$/>.5??$/!!1-$/} {<low upp>[$/>.5]}ercase"} # 70 ``` ``` {"{($/=m:g{<upper>}/m:g{\w})>.5??$/!!1-$/} {<low upp>[$/>.5]}ercase"} # 69 ``` ``` {"{($/=m:g{<upper>}/m:g{\w})>.5??"$/ upp"!!1-$/~' low'}ercase"} # 63 ``` ``` {"{($/=m:g{<:Lu>}/m:g{\w})>.5??"$/ upp"!!1-$/~' low'}ercase"} # 61 ``` Usage: ``` # give it a lexical name my &code = {...} .say for ( 'PrOgRaMiNgPuZzLeS & CoDe GoLf', 'DowNGoAT RiGHtGoAt LeFTGoat UpGoAT', 'Foo BaR Baz', )».&code; ``` ``` 0.52 uppercase 0.580645 uppercase 0.555556 lowercase ``` [Answer] # C#, 135 bytes Requires: ``` using System.Linq; ``` Actual function: ``` string U(string s){var c=s.Count(char.IsUpper)*1F/s.Count(char.IsLetter);return(c>0.5?c+" upp":1-c+" low")+"ercase";} ``` With explanation: ``` string U(string s) { var c = s.Count(char.IsUpper) // count uppercase letters * 1F // make it a float (less bytes than (float) cast) / s.Count(char.IsLetter); // divide it by the total count of letters return (c > 0.5 ? c + " upp" // if ratio is greater than 0.5, the result is "<ratio> upp" : 1 - c + " low") // otherwise, "<ratio> low" + "ercase"; // add "ercase" to the output string } ``` [Answer] ## Python 2, ~~114~~ 110 bytes ``` i=input() n=1.*sum('@'<c<'['for c in i)/sum(c.isalpha()for c in i) print max(n,1-n),'ulpopw'[n<.5::2]+'ercase' ``` [Answer] # Pyth - 40 bytes This is the first time i've ever used vectorized string formatting which is pretty cool. ``` Kml-zrzd2eS%Vm+cdsK" %sercase"Kc"upp low ``` [Test Suite](http://pyth.herokuapp.com/?code=Kml-zrzd2eS%25Vm%2BcdsK%22+%25sercase%22Kc%22upp+low&test_suite=1&test_suite_input=PrOgRaMiNgPuZzLeS+%26+CoDe+GoLf%0ADowNGoAT+RiGHtGoAt+LeFTGoat+UpGoAT%0AFoo+BaR+Baz&debug=1). [Answer] ## Mathematica, ~~139~~ 105 bytes ``` a=ToString;If[(b=1.#~(c=StringCount)~Alphabet[]/c[#,_?LetterQ])<.5,a[1-b]<>" upp",a@b<>" low"]<>"ercase"& ``` [Verbose code is scary](https://codegolf.stackexchange.com/q/67712/33208#comment164146_67712), but I'll have to live with it... [Answer] # PHP, 140 129 characters My first round of golf -- not too bad for a 'standard' language, eh? :-) Original: ``` function f($s){$a=count_chars($s);for($i=65;$i<91;$i++){$u+=$a[$i];$l+=$a[$i+32];}return max($u,$l)/($u+$l).($u<$l?' low':' upp').'ercase';} ``` Shortened to 129 characters thanks to @manatwork: ``` function f($s){$a=count_chars($s);for(;$i<26;$u+=$a[$i+++65])$l+=$a[$i+97];return max($u,$l)/($u+$l).' '.($u<$l?low:upp).ercase;} ``` With comments: ``` function uclcratio($s) { // Get info about string, see http://php.net/manual/de/function.count-chars.php $array = count_chars($s); // Loop through A to Z for ($i = 65; $i < 91; $i++) // <91 rather than <=90 to save a byte { // Add up occurrences of uppercase letters (ASCII 65-90) $uppercount += $array[$i]; // Same with lowercase (ASCII 97-122) $lowercount += $array[$i+32]; } // Compose output // Ratio is max over sum return max($uppercount, $lowercount) / ($uppercount + $lowercount) // in favour of which, equality not possible per challenge definition . ($uppercount < $lowercount ? ' low' : ' upp') . 'ercase'; } ``` [Answer] # Ruby, 81+1=82 With flag `-p`, ``` $_=["#{r=$_.count(a='a-z').fdiv$_.count(a+'A-Z')} low","#{1-r} upp"].max+'ercase' ``` It's lucky that for numbers between 0 and 1, lexicographic sorting is the same as numeric sorting. [Answer] # Common Lisp, 132 bytes ``` (setq s(read-line)f(/(count-if'upper-case-p s)(count-if'alpha-char-p s)))(format t"~f ~aercase"(max f(- 1 f))(if(> f .5)"upp""low")) ``` [Try it online!](https://tio.run/##RYwxDgIxDAS/YqXBLgyioKWg4AH8wAq2LlLuEpKcQBT39RBoKKaa2fUx1Nw7Vm0PqFhU7hzDomR4QJ/WpXGw3ZqzFvZSlTNU@guJeRL2k5SfIEJLZZYGzW0Gm2j5jhzO8gJDhiPYaILhGQz2J3Lj2bmYno6o92tKcJHb4P0B) [Answer] ## Seriously, 58 bytes ``` " upp"" low"k"ercase"@+╗,;;ú;û+∩@-@-;l@ú@-l/;1-k;i<@╜@ZEεj ``` Hex Dump: ``` 22207570702222206c6f77226b2265726361736522402bbb2c3b3ba33b 962bef402d402d3b6c40a3402d6c2f3b312d6b3b693c40bd405a45ee6a ``` It only works on the downloadable interpreter...the online one is still broken. Explanation: ``` " upp"" low"k"ercase"@+╗ Put [" lowercase"," uppercase"] in reg0 ,;;ú;û+∩@-@- Read input, remove non-alpha ;l@ Put its length below it ú@- Delete lowercase l Get its length / Get the ratio of upper/total ;1-k Make list [upp-ratio,low-ratio] ;i< Push 1 if low-ratio is higher @ Move list to top ╜@Z Zip it with list from reg0 E Pick the one with higher ratio εj Convert list to string. ``` [Answer] # Pyth, 45 bytes ``` AeSK.e,s/LzbkrBG1s[cGshMKd?H"upp""low""ercase ``` [Try it online.](http://pyth.herokuapp.com/?code=AeSK.e%2Cs%2FLzbkrBG1s%5BcGshMKd%3FH%22upp%22%22low%22%22ercase&input=DowNGoAT+RiGHtGoAt+LeFTGoat+UpGoAT&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=AeSK.e%2Cs%2FLzbkrBG1s%5BcGshMKd%3FH%22upp%22%22low%22%22ercase&test_suite=1&test_suite_input=PrOgRaMiNgPuZzLeS+%26+CoDe+GoLf%0ADowNGoAT+RiGHtGoAt+LeFTGoat+UpGoAT%0AFoo+BaR+Baz&debug=0) ### Explanation ``` rBG1 pair of alphabet, uppercase alphabet .e map k, b over enumerate of that: , pair of b lowercase or uppercase alphabet /Lz counts of these characters in input s sum of that and k 0 for lowercase, 1 for uppercase K save result in K eS sort the pairs & take the larger one A save the number of letters in and the 0 or 1 in H s[ print the following on one line: cG larger number of letters divided by shMK sum of first items of all items of K (= the total number of letters) d space ?H"upp""low" "upp" if H is 1 (for uppercase), otherwise "low" "ercase "ercase" ``` [Answer] # CoffeeScript, 104 characters ``` (a)->(r=1.0*a.replace(/\W|[A-Z]/g,'').length/a.length)&&"#{(r>.5&&(r+' low')||(1-r+' upp'))+'ercase'}" ``` coffeescript was initially trying to pass the intended return value as an argument to the "r" value, which failed and was super annoying because r was a number, not a function. I got around it by placing an `&&` between the statements to separate them. [Answer] # Pyth, ~~54~~ 53 One byte saved thanks to @Maltysen ``` K0VzI}NG=hZ)I}NrG1=hK;ceS,ZK+ZK+?>ZK"low""upp""ercase ``` [Try it online](https://pyth.herokuapp.com/?code=K0VzI%7DNG%3DhZ%29I%7DNrG1%3DhK%3BceS%2CZK%2BZK%2B%3F%3EZK%22low%22%22upp%22%22ercase&input=Foo+BaR+Baz&test_suite=1&test_suite_input=PrOgRaMiNgPuZzLeS+%26+CoDe+GoLf%0ADowNGoAT+RiGHtGoAt+LeFTGoat+UpGoAT%0AFoo+BaR+Baz&debug=0) ``` K0 " Set K to 0 " (Implicit: Set Z to 0) Vz " For all characters (V) in input (z): I}NG " If the character (N) is in (}) the lowercase alphabet (G): =hZ " Increment (=h) Z ) " End statement I}NrG1 " If the character is in the uppercase alphabet (rG1): =hK " Increment K ; " End all unclosed statements/loops c " (Implicit print) The division of e " the last element of S,ZK " the sorted (S) list of Z and K (this returns the max value) +ZK " by the sum of Z and K + " (Implicit print) The concatenation of ?>ZK"low""upp" " "low" if Z > K, else "upp" "ercase" " and the string "ercase". ``` [Answer] # Ruby, 97 characters ``` ->s{'%f %sercase'%[(l,u=[/[a-z]/,/[A-Z]/].map{|r|s.scan(r).size}).max.fdiv(l+u),l>u ?:low: :upp]} ``` Sample run: ``` 2.1.5 :001 > ['PrOgRaMiNgPuZzLeS & CoDe GoLf', 'DowNGoAT RiGHtGoAt LeFTGoat UpGoAT', 'Foo BaR Baz'].map{|s|->s{'%f %sercase'%[(l,u=[/[a-z]/,/[A-Z]/].map{|r|s.scan(r).size}).max.fdiv(l+u),l>u ?:low: :upp]}[s]} => ["0.520000 uppercase", "0.580645 uppercase", "0.555556 lowercase"] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 28 bytes ``` ʒ.u}gság/Dò©_αð„Œ„›…#'ƒß«®èJ ``` [Try it online!](https://tio.run/##AVcAqP8wNWFiMWX//8qSLnV9Z3PDoWcvRMOywqlfzrHDsOKAnsWS4oCe4oC64oCmIyfGksOfwqvCrsOoSv//UHJPZ1JhTWlOZ1B1WnpMZVMgJiBDb0RlIEdvTGY "05AB1E – Try It Online") --- ``` ʒ.u}g # filter all but uppercase letters, get length. ság/ # Differential between uppercase and input length. Dò© # Round up store result in register w/o pop. _α # Negated, absolute difference. ð # Push space. „Œ„›… # Push "upper lower" # # Split on space. 'ƒß« # Concat "case" resulting in [uppercase,lowercase] ®èJ # Bring it all together. ``` [Answer] # Java 8, ~~136~~ 130 bytes ``` s->{float l=s.replaceAll("[^a-z]","").length();l/=l+s.replaceAll("[^A-Z]","").length();return(l<.5?1-l+" upp":l+" low")+"ercase";} ``` -6 bytes creating a port of [*@ProgramFOX*' C# .NET answer](https://codegolf.stackexchange.com/a/67855/52210). [Try it online.](https://tio.run/##hVDBSsNAEL33K4Y9SEJMxIMXY5RoaTyksaT10lJhTTdx63Q37G5abMm3x43mVBBhBt7MvBnemy3dU3@7@ewKpFrDlHJxGgFwYZgqacEg60uAuVFcVFA4A9BuaPutTRvaUMMLyEBABJ32708lSmoAIx0oVqO9EyM6ZPVG/eOaXBLiBshEZT4cN8SrCL1zXuwvz3mKmUYJB@@Cm4drHz0CTV2T2x6gPBDXI0wVVDMStl34q6tu3tHqGuTtJd/AzhocPKzW1B3MfWnDdoFsTFDbiUHhiKBwyEy9VDmd8qyaNctjyuZwAU9yzCCRaUncnxf8vT2WhyyR8QJynjwbiwykbLJI@s@81v3k3xMTKeGR5jaPA7cdtd03) **Explanation:** ``` s->{ // Method with String as both parameter and return-type float l=s.replaceAll("[^a-z]","").length(); // Amount of lowercase l/=l+s.replaceAll("[^A-Z]","").length(); // Lowercase compared to total amount of letters return(l<.5? // If this is below 0.5: 1-l+" upp" // Return `1-l`, and append " upp" : // Else: l+" low") // Return `l`, and append " low" +"ercase";} // And append "ercase" ``` [Answer] ## REXX, 144 bytes ``` a=arg(1) l=n(upper(a)) u=n(lower(a)) c.0='upp';c.1='low' d=u<l say 1/((u+l)/max(u,l)) c.d'ercase' n:return length(space(translate(a,,arg(1)),0)) ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 72 bytes ``` $_=(($u=y/A-Z//)>($l=y/a-z//)?$u:$l)/($u+$l).$".($u>$l?upp:low).'ercase' ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lZDQ6XUtlLfUTdKX1/TTkMlB8hJ1K0CcuxVSq1UcjT1gQq0gbSeipIekGmnkmNfWlBglZNfrqmnnlqUnFicqv7/v1t@voJTYhAQV/3LLyjJzM8r/q9b8F/X11TPwNAAAA "Perl 5 – Try It Online") [Answer] # [Kotlin](https://kotlinlang.org), 138 bytes ## Code ``` let{var u=0.0 var l=0.0 forEach{when{it.isUpperCase()->u++ it.isLowerCase()->l++}} "${maxOf(u,l)/(u+l)} ${if(u>l)"upp" else "low"}ercase"} ``` ## Usage ``` fun String.y():String =let{var u=0.0 var l=0.0 forEach{when{it.isUpperCase()->u++ it.isLowerCase()->l++}} "${maxOf(u,l)/(u+l)} ${if(u>l)"upp" else "low"}ercase"} fun main(args: Array<String>) { println("PrOgRaMiNgPuZzLeS & CoDe GoLf".y()) println("DowNGoAT RiGHtGoAt LeFTGoat UpGoAT".y()) println("Foo BaR Baz".y()) } ``` [Answer] # Pyth, ~~40~~ 39 bytes ``` Jml@dQrBG1+jdeS.T,cRsJJc2."kw񽙽""ercase ``` [Try it here](http://pyth.herokuapp.com/?code=Jml%40dQrBG1%2BjdeS.T%2CcRsJJc2.%22kw%F1%BD%99%BD%22%22ercase&input=%22DowNGoAT+RiGHtGoAt+LeFTGoat+UpGoAT%22&debug=0) ### Explanation ``` Jml@dQrBG1+jdeS.T,cRsJJc2."kw񽙽""ercase m rBG1 For the lower and uppercase alphabet... l@dQ ... count the occurrences in the input. J cRsJJ Convert to frequencies. .T, c2."kw񽙽" Pair each with the appropriate case. eS Get the more frequent. +jd "ercase Stick it all together. ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~134~~128 bytes ``` Filter F{$p=($_-creplace"[^A-Z]",'').Length/($_-replace"[^a-z]",'').Length;$l=1-$p;(.({"$p upp"},{"$l low"})[$p-lt$l])+"ercase"} ``` [Try it online!](https://tio.run/##fVJhT8IwEP0Mv@LSVN3CikCiURcSUTL8gGIQv7hMM8cBS5q1bl00zP12bBli0EiTJu27d6/v7irFO6bZAjlnkUhx5eVJpGKRwAQzVS/qNapyyRG6cGnZbm17b3TBsch9OpqPw9v4bn6fPy2H@ACHcC36CAMxnBGHtJonHcilxDQKMyS2@yu/L97vBqI3gXE8uFH6pGCI3mQgQgWP0kQqkbN9Ip4QcBWO9V5W7FPgpqp/2KNqaWp7n@pMVGvN29XbMj/hAAqo1/Rdd0v3iL74rcA1AH5IjBROK7AdaMzAKWY5XzPXGZ/gGdSYwMTA/m2oFsHFxVjkydTypyJ/5RhYmzyWouRhhMR/brHzZtAgztGR7XTsSjzLZ7P4w4j/oYds2WPLKsHdMUJosXm@BFpUEiVxN363ZTB8@5bVsbJerryYK0zBK6jsWvSFRT@v9dhTsLbWHGIyV4tjE98xsxN2Ke@2GZWu1bQKQqUZCykdfeSm86S0fSoZV5QHdoNsBlGuzA9dfQE "PowerShell Core – Try It Online") Thanks, [Veskah](https://codegolf.stackexchange.com/users/78849/veskah), for saving six bytes by converting the function to a filter! [Answer] # [Tcl](http://tcl.tk/), 166 bytes ``` proc C s {lmap c [split $s ""] {if [string is u $c] {incr u} if [string is lo $c] {incr l}} puts [expr $u>$l?"[expr $u./($u+$l)] upp":"[expr $l./($u+$l)] low"]ercase} ``` [Try it online!](https://tio.run/##VY9NSwMxFEX3@RWXEEQRdN@FolM6XYy1jHVjO4sQ0iGQzgv5oNIhv31MC4W6ePDePW9xblR2mpwnhQoBoz1IB4VtcNZEiADOO4xmX5LozdDDBCQIdQ4H5ZEy@w8t3VCbM3MpBmz1r/MQ6UXYV349np7vRXoU9qFDco7PrsDeAEtH3mmvZNB5usgVScbX/rNv5YdZ9ev0c2r0F@5Q0VyjpmbPGZ/TcVXT2watqZexbBGNXmxqkhHf7kzK04II77Itc@IsY7yY7gYRZqwq1fP0Bw "Tcl – Try It Online") [Answer] # APL(NARS), 58 char, 116 bytes ``` {m←+/⍵∊⎕A⋄n←+/⍵∊⎕a⋄∊((n⌈m)÷m+n),{m>n:'upp'⋄'low'}'ercase'} ``` test: ``` h←{m←+/⍵∊⎕A⋄n←+/⍵∊⎕a⋄∊((n⌈m)÷m+n),{m>n:'upp'⋄'low'}'ercase'} h "PrOgRaMiNgPuZzLeS & CoDe GoLf" 0.52 uppercase h "DowNGoAT RiGHtGoAt LeFTGoat UpGoAT" 0.5806451613 uppercase h "Foo BaR Baz" 0.5555555556 lowercase ``` [Answer] # C, 120 bytes ``` f(char*a){int m=0,k=0,c;for(;isalpha(c=*a++)?c&32?++k:++m:c;);printf("%f %sercase",(m>k?m:k)/(m+k+.0),m>k?"upp":"low");} ``` test and result: ``` main() {char *p="PrOgRaMiNgPuZzLeS & CoDe GoLf", *q="DowNGoAT RiGHtGoAt LeFTGoat UpGoAT", *m="Foo BaR Baz"; f(p);printf("\n");f(q);printf("\n");f(m);printf("\n"); } ``` results ``` 0.520000 uppercase 0.580645 uppercase 0.555556 lowercase ``` It suppose Ascii character set. [Answer] Javascript 80 characters I'm bad at this but here was my go at Javascript: ``` a=(s)=>{let a=0,b=0;for(c in s)s[c]==s[c].toUpperCase()?a++:b++;return a/(a+b);} ``` Readable version: ``` a=(s)=>{ let a=0,b=0; for(c in s) s[c]==s[c].toUpperCase()?a++:b++; return a/(a+b); } ``` Function is called with: `a('hEllO')` which outputs `0.4` for example. I feel like there must be a way to condense the arrow function or something with the words return or toUpperCase that I can do. ]
[Question] [ Given a list of integers, group the elements which occur most first, then group the next most and so on until each unique element in the list has been grouped once. --- # Examples: **Input:** `[1,2,3]` **Output:** `[[1,2,3]]` --- **Input:** `[1,1,1,2,2,3,3,4,5,6]` **Output:** `[[1],[2,3],[4,5,6]]` --- **Input:** `[1,1,1,4,5,6,6,6,7,7,8,8,8,8,8,8,8,9,5,6,5,6,5,6,5,6,-56]` **Output:** `[[6, 8],[5],[1],[7],[9,4,-56]]` --- **Input:** `[]` **Output:** `[]` --- **Input:** `(empty input)` **Output:** `ERROR/Undefined/Doesn't matter` --- # Rules * Groupings must go from maximal frequency to minimal frequency. * Internal order of the groupings are arbitrary (E.G. example 3 could have `[8,6]` instead). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count wins. # Related * [Sort the distinct elements of a list in descending order by frequency](https://codegolf.stackexchange.com/questions/17287/sort-the-distinct-elements-of-a-list-in-descending-order-by-frequency) [Answer] ## Mathematica, 43 bytes ``` Union/@SortBy[l=#,f=-l~Count~#&]~SplitBy~f& ``` [Try it online!](https://tio.run/##y00sychMLv6fbvs/NC8zP0/fITi/qMSpMjrHVlknzVY3p845vzSvpE5ZLbYuuCAnEyhVl6b2P6AoM69EwUEhHYirDXUUIMhER8FUR8EMhszByAIbsoSpxCR1Tc1q/wMA "Mathics – Try It Online") (Using Mathics.) Alternatively: ``` SortBy[Union[l=#],f=-l~Count~#&]~SplitBy~f& ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~8~~ 7 bytes ``` _{M.g/Q ``` [Try it online!](http://pyth.herokuapp.com/?code=_%7BM.g%2FQ&input=%5B1%2C1%2C1%2C4%2C5%2C6%2C6%2C6%2C7%2C7%2C8%2C8%2C8%2C8%2C8%2C8%2C8%2C9%2C5%2C6%2C5%2C6%2C5%2C6%2C5%2C6%2C-56%5D&debug=0) 1 byte thanks to FryAmTheEggman. [Answer] # [Python 2](https://docs.python.org/2/), ~~145~~ 141 bytes ``` import collections as c,itertools as i;o=lambda n:lambda l:l[n] print[map(o(0),g)for _,g in i.groupby(c.Counter(input()).most_common(),o(1))] ``` [Try it online!](https://tio.run/##VcxBCsIwEAXQvafIMoFYrNhqK648RikljbUOJDMhnS56@liLC@XxYT4fJiz8IjymBD5QZGHJucEyEE7CTMJq4CEykdsqXOnmjO8fRmD9PVztGmx3IQJy402QJA9Kj@pJUXR6FIACsjHSHPpF2uxOM64vJWCYWSqVeZq4s@Q9oVSaZK5Um1KT64@TLnS5Oa8uf6pt@82@KNs3 "Python 2 – Try It Online") This is my first submission after years of reading. > > It basically it puts all the elements into a [Counter](https://docs.python.org/2/library/collections.html#collections.Counter) (dictionary of how many of each element in the list) and [.most\_common()](https://docs.python.org/2/library/collections.html#collections.Counter.most_common) puts the items in decending frequency order. After that, it's just a matter of formatting the items into the right list. > > > Saved 4 bytes thanks to [ovs](https://codegolf.stackexchange.com/questions/126159/group-a-list-by-frequency/126200?noredirect=1#comment310701_126200). [Answer] ## JavaScript (ES6), ~~95~~ 101 bytes ``` a=>a.map(x=>(o[a.map(y=>n+=x!=y,n=0)|n]=o[n]||[])[x*x+(x>0)]=x,o=[])&&(F=o=>o.filter(a=>a))(o).map(F) ``` ### How? For each element ***x*** of the input array ***a***, we compute the number ***n*** of elements of ***a*** that are different from ***x***: ``` a.map(y => n += x != y, n = 0) | n ``` We use the indices ***n*** and ***x*** to fill the array ***o***: ``` (o[n] = o[n] || [])[x * x + (x > 0)] = x ``` ***Edit***: Because JS doesn't support negative array indices, we need the formula `x * x + (x > 0)` to force positive indices. This gives us an array of arrays containing the unique elements of the original list, grouped by frequency and ordered from most frequent to least frequent. However, both the outer array and the inner arrays potentially have many empty slots that we want to filter out. We do this with the function ***F***, applied to ***o*** and each of its elements: ``` F = o => o.filter(a => a) ``` ### Test cases ``` let f = a=>a.map(x=>(o[a.map(y=>n+=x!=y,n=0)|n]=o[n]||[])[x*x+(x>0)]=x,o=[])&&(F=o=>o.filter(a=>a))(o).map(F) console.log(JSON.stringify(f([1,2,3]))) // [[1,2,3]] console.log(JSON.stringify(f([1,1,1,2,2,3,3,4,5,6]))) // [[1],[2,3],[4,5,6]] console.log(JSON.stringify(f([1,1,1,4,5,6,6,6,7,7,8,8,8,8,8,8,8,9,5,6,5,6,5,6,5,6,-56]))) // [[6, 8],[5],[1],[7],[9,4,-56]] console.log(JSON.stringify(f([]))) // [] ``` [Answer] # [PHP](https://php.net/), 85 bytes ``` <?$r=[];foreach(array_count_values($_GET)as$k=>$v)$r[$v][]=$k;krsort($r);print_r($r); ``` [Try it online!](https://tio.run/##VY4/C8IwFMT3fo43JNAOgq1KjA5SxEWXbiGEUFJbKk14/QMufmvnGDMpPw4OjnvvXOv8/uhalxhEiwqNszh1w528SnW9VZdTSVkC6lxWXKzSL@s0T4vIJrD9YxezX2V5IZkH5EKyxqLRdUs0on6q2s7DpBb9mM1I4geqR@j5ARYKKGCRQnLoWY9jmEQAKXPYhQpG7/17sFkd7pkP "PHP – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes ``` QɓċЀĠṚị ``` [Try it online!](https://tio.run/##y0rNyan8/z/w5OQj3YcnPGpac2TBw52zHu7u/n@4Hcg7OunhzhlAOvL//2guhWhDHSMd41gdMAsEjUB8IDTRMdUxQxIH88HQHAgtUKAlWA4Z65pC9MZyxQIA "Jelly – Try It Online") [Answer] ## Clojure, 74 bytes ``` #(for[[_ g](sort-by(comp - key)(group-by val(frequencies %)))](map key g)) ``` Looks quite verbose :/ [Answer] # [Perl 6](https://perl6.org), 43 bytes ``` *.Bag.classify(-*.value).sort».value».key ``` [Test it](https://tio.run/##hVDLasMwELzrK/ZggpzKgqaN8zAJTSGnvi6lUIwJqqMUU8UWlh1qQr6st/6Yu5KT0J7KsGh3NTO7kpalCtvaSNiFPI3ItoFeWqwlzNo@vxXvPFXCmGzT0KDPd0LV0uemKKvvr67C80M2rRPeVNJUMAOV5dJQn2@Fnu4JgHV/eHq8W75GWC1fFvfgrciB2P4zSiKilcjhwukjsinKo1UwBwpT9Kdeluu68hlM3VTqyU8t00quffDBzshMsJZSqwbs9ic@76UiL/IsFYrBWfNvl2v8FVzQ1G9wbgL1Vt0s@zC6j90/JAefL8pSNOTQxpdswK4SmM0hPuYsIZhZDGyNuGZDFp44CYsdK@66Z7IrHUaI8R9M3N3vCIYnw5DBGN2GGNZ7hDFBM0tA746U/AA "Perl 6 – Try It Online") ## Expanded: ``` * # WhateverCode lambda (this is the input) # [1,1,1,2,2,3,3,4,5,6] .Bag # turn into a Bag # (1=>3,5=>1,4=>1,3=>2,6=>1,2=>2).Bag .classify(-*.value) # classify by how many times each was seen # {-2=>[3=>2,2=>2],-3=>[1=>3],-1=>[5=>1,4=>1,6=>1]} .sort\ # sort (this is why the above is negative) # {-3=>[1=>3],-2=>[3=>2,2=>2],-1=>[5=>1,4=>1,6=>1]} ».value\ # throw out the classification # ([1=>3],[3=>2,2=>2],[5=>1,4=>1,6=>1]) ».key # throw out the counts # ([1],[3,2],[5,4,6]) ``` [Answer] # Bash + GNU utilities, 71 61 ``` sort|uniq -c|sort -nr|awk '{printf$1-a?"\n%d":",%d",$2;a=$1}' ``` Input as a newline-delimited list. Output as a newline-delimited list of comma-separated values. [Try it online](https://tio.run/##S0oszvj/vzi/qKSmNC@zUEE3uQbEUdDNK6pJLM9WUK8uKMrMK0lTMbS1TbRX0lFNUbJSiskDUjoqRtaJtiqGter//xtygaAJlymXGRiaA6EFCrQEyyFjXVMzAA). [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` 9B#uw3XQP ``` Input is a column vector, using `;` as separator. **[Try it online!](https://tio.run/##y00syfn/39JJubTcOCIw4P//aENrEDSxNrU2A0NzILRAgZZgOWSsa2oWCwA "MATL – Try It Online")** ### Explanation ``` 9B#u % Call 'unique' function with first and fourth outputs: unique entries and % number of occurrences w % Swap 3XQ % Call 'accumarray' with anonymous function @(x){sort(x).'}. The output is % a cell array with the elements of the input grouped by their frequency. % Cells are sorted by increasing frequency. Some cells may be empty, but % those won't be displayed P % Flip cell array, so that groups with higher frequency appear first. % Implicitly display ``` [Answer] # k, 22 bytes ``` {x@!x}{(>x)@=x@>x}#:'= ``` [Try it online.](http://johnearnest.github.io/ok/?run=%7Bx%40%21x%7D%7B%28%3Ex%29%40%3Dx%40%3Ex%7D%23%3A%27%3D1%201%201%204%205%206%206%206%207%207%208%208%208%208%208%208%208%209%205%206%205%206%205%206%205%206%20-56) ([AW's k](https://kparc.com) seems to require an extra `@` before the `#`, but oK does not.) Explanation: ``` = /group identical numbers in a map/dict #:' /get number of times each number is repeated /this is almost the answer, but without the inner lists { x@>x} /order "number of times" greatest to least = /group them (to make the smaller groups) (>x)@ /get the actual numbers into place {x@!x} /get values of the map/dict it's in ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` ọtᵒ¹tᵍhᵐ²| ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@Hu3pKHWycd2gkkezMebp1waFPN///RhjogaKJjqmMGhuZAaIECLcFyyDje1Cz2fxQA "Brachylog – Try It Online") ### Explanation ``` Example input: [2,1,1,3] ọ Occurences: [[2,1],[1,2],[3,1]] tᵒ¹ Order desc. by tail: [[1,2],[3,1],[2,1]] tᵍ Group by tail: [[[1,2]],[[3,1],[2,1]]] hᵐ² Map twice head: [[1],[3,2]] | Else (Input = []) Input = Output ``` [Answer] # Mathematica, 79 bytes ``` Table[#&@@@f[[i]],{i,Length[f=GatherBy[Sort[Tally@#,#1[[2]]>#2[[2]]&],Last]]}]& ``` **input** > > [{1, 1, 1, 4, 5, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 9, 5, 6, 5, 6, 5, > 6, 5, 6, -56}] > > > **output** > > {{8, 6}, {5}, {1}, {7}, {-56, 9, 4}} > > > [Answer] # [R](https://www.r-project.org/), ~~84~~ 77 bytes *-7 bytes thanks to mb7744* ``` unique(lapply(x<-sort(table(scan()),T),function(y)as.double(names(x[x==y])))) ``` Reads from stdin; returns a list with subvectors of integers in increasing order. If we could return strings instead of ints, then I could drop 11 bytes (removing the call to `as.double`), but that's about it. R's `table` function does the heavy lifting here, counting the occurrences of each member of its input; then it aggregates them by count (`names`). Of course, that's a string, so we have to coerce it to an integer/double. [Try it online!](https://tio.run/##K/r/vzQvs7A0VSMnsaAgp1Kjwka3OL@oRKMkMSknVaM4OTFPQ1NTJ0RTJ600L7kkMz9Po1IzsVgvJb8UJJ@XmJtarFERXWFrWxmrCQT/DRVA0ETBVMEMDM2B0AIFWoLlkLGuqdl/AA "R – Try It Online") [Answer] # JavaScript (ES6), ~~100~~ ~~98~~ ~~96~~ 93 bytes *Saved 2 bytes thanks to @Neil (plus he fixed an edge-case bug in my code). Saved 3 more bytes thanks to @TomasLangkaas.* ``` a=>a.sort().map((_,n)=>a.filter((v,i)=>i-a.indexOf(v)==n&v!=a[i+1])).filter(a=>a+a).reverse() ``` **Test cases** ``` f= a=>a.sort().map((_,n)=>a.filter((v,i)=>i-a.indexOf(v)==n&v!=a[i+1])).filter(a=>a+a).reverse() console.log(JSON.stringify(f([1,2,3]))) console.log(JSON.stringify(f([1,1,1,2,2,3,3,4,5,6]))) console.log(JSON.stringify(f([1,1,1,4,5,6,6,6,7,7,8,8,8,8,8,8,8,9,5,6,5,6,5,6,5,6,-56]))) console.log(JSON.stringify(f([]))) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~6~~ 5 bytes ``` ↔k#¹u ``` [Try it online!](https://tio.run/##yygtzv5flZpbfGhnbn7xo6bG/4/apmQrH9pZ@v///@hoQx0jHeNYHSANgkYgHhCa6JjqmMFFwTwwNAdCCxRoCZZDxrqmIJ2xsQA "Husk – Try It Online") -1 byte from Leo. ## Explanation ``` ↔k#¹u u uniquify the input k#¹ key on frequency in input ↔ reverse ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÙΣ¢}R.γ¢ ``` [Try it online](https://tio.run/##yy9OTMpM/f//8Mxziw8tqg3SO7f50KL//6MNdUDQRMdUxwwMzYHQAgVaguWQsa6pWSwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf8Pzzy3@NC64kOLaoP0zm0Gs/7X6vyPjjbUMdIxjtUB0iBoBOIBoYmOqY4ZXBTMA0NzILRAgZZgOWSsawrSGaujpBQLAA). **Explanation:** ``` Ù # Uniquify the (implicit) input-list Σ # Sort this uniquified list by: ¢ # Get its count in the (implicit) input-list }R # After the ascending sort: reverse it to make it descending .γ # Then adjacently group each value by: ¢ # Its count in the (implicit) input-list # (after which the result is output implicitly) ``` The `.γ` could have been `.¡` for the same result. `.¡` is the group-by builtin, and `.γ` is the adjacently group-by builtin. But since we use a sort first, the result ends up buying the same. Unfortunately, 05AB1E lacks a sort & group-by as single builtin, so we'll have to do it in two steps instead (like most existing answers tbh). [Answer] # [Factor](https://factorcode.org/), 63 bytes ``` [ histogram unzip swap zip expand-keys-push-at values reverse ] ``` [![Running the above code in Factor's REPL with some test cases](https://i.stack.imgur.com/kLRWO.png)](https://i.stack.imgur.com/kLRWO.png) ## Explanation ``` ! { 1 1 1 2 2 3 3 4 5 6 } histogram ! H{ { 1 3 } { 2 2 } { 3 2 } { 4 1 } { 5 1 } { 6 1 } } unzip ! { 1 2 3 4 5 6 } { 3 2 2 1 1 1 } swap ! { 3 2 2 1 1 1 } { 1 2 3 4 5 6 } zip ! { { 3 1 } { 2 2 } { 2 3 } { 1 4 } { 1 5 } { 1 6 } expand-keys-push-at ! H{ { 1 V{ 4 5 6 } } { 2 V{ 2 3 } } { 3 V{ 1 } } } values ! { V{ 4 5 6 } V{ 2 3 } V{ 1 } } reverse ! { V{ 1 } V{ 2 3 } V{ 4 5 6 } } ``` [Answer] # [Python 3](https://docs.python.org/3/), 85 bytes ``` def f(l): r=[[]for _ in l] for x in{*l}:r[-l.count(x)]+=x, return[*filter(bool,r)] ``` [Try it online!](https://tio.run/##VYvBCsIwEETv/Yo9JnVbEG2thX5JCIKaYGBJypJCpPjtMe1JeczhMTPzO76CP@X8NBasIDlWwJNS2gaGGzgPpCvYJBVZa/qMrBpqH2HxUSSpD1PCcjFxYa9q6ygaFvcQCFnqPLMrMyvUETfO2GG/cykMf1z37jdN12sp8xc "Python 3 – Try It Online") -12 thanks to tips from @ovs! [Answer] # [V](https://github.com/DJMcMayhem/V), ~~60~~, 54 bytes ``` Úòͨ¼¾©î±/± ±òHòø pkJjòú! Ǩ^ƒ ©î±/o Îf ld|;D òV{Jk ``` [Try it online!](https://tio.run/##K/v///Csw5sO9x5acWjPocZD@w6tPLzu0Eb9QxsVDm08vMkDKLVDgasg2ysLyNqlyHW4/dCKuEPNCodWHmoEK8znOtyXppCTUmPtwnV4U1i1V/b//4ZcIGjCZcplBobmQGiBAi3BcshY19QMAA "V – Try It Online") Hexdump: ``` 00000000: daf2 cda8 bc81 bea9 eeb1 2fb1 20b1 f248 ........../. ..H 00000010: f2f8 200a 706b 4a6a f2fa 210a c7a8 5e83 .. .pkJj..!...^. 00000020: 20a9 81ee b12f 6f0a ce66 206c 647c 3b44 ..../o..f ld|;D 00000030: 0af2 567b 4a6b ..V{Jk ``` As much as I love V, I'm pretty sure this is the worst possible language for the task. Especially considering it has no support for lists, and basically no support for numbers. Just string manipulation. [Answer] # [Ruby](https://www.ruby-lang.org/), 62 bytes ``` ->a{a.group_by{|e|a.count(e)}.sort_by{|x,_|-x}.map{|_,i|i|[]}} ``` [Try it online!](https://tio.run/##VY3BCoMwEETv/Yo9trAGqkbtwf5ICCEWLR5aJVVQknx7uqalWB6zh53ZHTM3a@jqkFy11exuhnlUzWpd6zS7DfNzOrYnz16DmeJ6QeWSxbOHHq1T2LveCel9GKET4owbKZFhjhwLKaGugQyJINJtZAg5Akcg77A7ivFISVR/XKK3V8J/rwuESqLgJGoRJSmni5j4FHyTMrwB "Ruby – Try It Online") There has got to be a shorter way to do this. [Answer] ## C#, 119 bytes Just a quick stab at it: ``` using System.Linq; a=>a.GroupBy(x=>x) .GroupBy(x=>x.Count(),x=>x.Key) .OrderBy(x=>-x.Key) .Select(x=>x.ToArray()) .ToArray() ``` [Answer] # [R](https://www.r-project.org/), 66 bytes ``` (l=lapply)(l(split(x<-table(scan()),factor(-x)),names),as.integer) ``` [Try it online!](https://tio.run/##VclLCoAwDEXRrXSYgBUEv6CLiVKlEGtpO9DVx@pIOVx48III8MTkPV8IDNGzTXCOOtHMBuJCDhCLlZZ0BNBn3o52E7GgWFqXzGYCSqUetWpU@@qy/md4v2@6aUVu "R – Try It Online") If in the output the integers may be in string format, can drop to **48 bytes** (as mentioned in @Giuseppe's answer). --- Ungolfed: ``` input <- scan(); # read input x <- table(input); # count how many times each integer appears, in a named vector y <- split(x, factor(-x)) # split the count into lists in increasing order z <- lapply(y, names) # access the the original values which are still # attached via the names lapply(z, as.integer) # convert the names back to integers ``` [Answer] **PowerShell, 77, 70 bytes** ``` ($a=$args)|group{($a-eq$_).count}|sort n* -Des|%{,($_.group|sort -u)} ``` NB: To see that these results are correctly grouped (since visually there's no deliniation between the contents of each array), you may wish to append `| write-host` to the end of the above line. **Acknowledgements** Thanks to: * [TessellatingHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler) for saving 7 bytes by massively refactoring / rewriting to a way more golfed approach. --- **Previous** *77 bytes* ``` param($x)$x|group|sort count -desc|group count|%{,($_.group|%{$_.group[0]})} ``` [Answer] # [Perl 5](https://www.perl.org/) `-pa`, 89 bytes ``` map$k{$_}++,@F;$_="@{[sort{$k{$b}-$k{$a}}keys%k]}";s/\S+ /$&.'| 'x($k{1*$&}!=$k{1*$'})/ge ``` [Try it online!](https://tio.run/##K0gtyjH9/z83sUAlu1olvlZbW8fBzVol3lbJoTq6OL@opBoknlSrC6ISa2uzUyuLVbNja5Wsi/VjgrUV9FXU9NRrFNQrNIAKDLVU1GoVbSEs9VpN/fTU///NFEwVTBSMgdAICA1B8F9@QUlmfl7xf11fUz0DQ4P/ugWJAA "Perl 5 – Try It Online") [Answer] # Groovy, 71 bytes ``` {a->a.groupBy{a.count(it)}.sort{-it.key}.values().collect{it.unique()}} ``` I actually just learned about groupBy after creating this. I didn't know collect wasn't my only choice. --- ``` { a-> // [1,2,1,2,3,3,3,6,5,4] a.groupBy{ a.count(it) // [2:[1,2,1,2],3:[3,3,3],1:[6,5,4]] }.sort{ -it.key // [3:[3,3,3],2:[1,2,1,2],1:[6,5,4]] }.values().collect{ // [[3,3,3],[1,2,1,2],[6,5,4]] it.unique() } // [[3],[1,2],[6,5,4]] } ``` ]
[Question] [ If you don't know what the [Tower of Hanoi](https://en.wikipedia.org/wiki/Tower_of_Hanoi) is, I'll explain it briefly: There are three rods and some discs each of which has a different size. In the beginning all discs are on the first tower, in sorted order: The biggest one is at the bottom, the smallest at the top. The goal is to bring all the discs over to the third rod. Sounds easy? Here's the catch: You can't place a disc on top of a disc that is smaller than the other disc; you can only hold one disc in your hand at a time to move them to another rod and you can only place the disc on rods, not on the table, you sneaky bastard. ### ascii example solution: ``` A B C | | | _|_ | | __|__ | | A B C | | | | | | __|__ _|_ | A B C | | | | | | | _|_ __|__ A B C | | | | | _|_ | | __|__ ``` # Challenge There are three rods called A,B and C. (You can also call them 1,2 and 3 respectivly if that helps) In the beginning all n discs are on rod A(1). Your challenge is to verify a solution for the tower of hanoi. You'll need to make sure that: 1. In the end all n discs are on rod C(3). 2. For any given disc at any given state there is no smaller disc below it. 3. No obvious errors like trying to take discs from an empty rod or moving discs to nonexistant rods. (the solution does not have to be optimal.) # Input Your program will receive two inputs: 1. The number of discs n (an integer) 2. The moves which are taken, which will consist of a set of tuples of: (tower to take the currently uppermost disc from),(tower to take this disc to) where each tuple refers to a move. You can choose how they are represented. For example something like the following ways of representing the solution for n=2 which I've drawn in ascii above. (I'll use the first one in the test cases, because it's easy on the eyes): "A->B ; A->C ; B->C" [("A","B"),("A","C"),("B","C")] [(1,2),(1,3),(2,3)] "ABACBC" [1,2,1,3,2,3] # Output * Truthy, if the conditions that can be found under "challenge" hold. * Falsy, if they don't. # Test cases: ### True: ``` n=1, "A->C" n=1, "A->B ; B->C" n=2, "A->B ; A->C ; B->C" n=2, "A->C ; C->B ; A->C ; B->C" n=2, "A->C ; A->B ; C->B ; B->A ; B->C ; A->C" n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C" n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C ; B->C" ``` ### False: *3rd one suggested by @MartinEnder, 7th by @Joffan* ``` n=1, "A->B" n=1, "C->A" n=2, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C" n=2, "A->B ; A->C ; C->B" n=2, "A->C ; A->B ; C->B ; B->A" n=2, "A->C ; A->C" n=3, "A->B ; A->D; A->C ; D->C ; A->C" n=3, "A->C ; A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C" n=3, "A->C ; A->B ; C->B ; A->B ; B->C ; B->A ; B->C ; A->C" n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; C->B" n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C" n=4, "A->B ; A->B ; A->B ; A->C ; B->C ; B->C ; B->C" ``` This is [code-golf](https://codegolf.stackexchange.com/questions/tagged/code-golf), shortest solution wins. Standard rules and loopholes apply. No batteries included. [Answer] ## [Retina](https://github.com/m-ender/retina), ~~167~~ ~~165~~ ~~157~~ ~~150~~ 123 bytes This totally looks like a challenge that should be solved with a single regex... (despite the header saying "Retina", this is just a vanilla .NET regex, matching valid inputs). ``` ^(?=\D*((?=(?<3>1+))1)+)((?=A(?<1-3>.+)|B(?<1-4>.+)|C(?<1-5>.+)).(?=A.*(?!\3)(\1)|B.*(?!\4)(\1)|C.*(?!\5)(\1)).)+(?!\3|\4)1 ``` Input format is the list of instructions of the form `AB`, followed by `n` in unary using the digit `1`. There are no separators. Output is `1` for valid and `0` for invalid. [Try it online!](http://retina.tryitonline.net/#code=JWBeKD89XEQqKCg_PSg_PDM-MSspKTEpKykoKD89QSg_PDEtMz4uKyl8Qig_PDEtND4uKyl8Qyg_PDEtNT4uKykpLig_PUEuKig_IVwzKShcMSl8Qi4qKD8hXDQpKFwxKXxDLiooPyFcNSkoXDEpKS4pKyg_IVwzfFw0KTE&input=QUMxCkFCQkMxCkFCQUNCQzExCkFDQ0JBQ0JDMTEKQUNBQkNCQkFCQ0FDMTEKQUNBQkNCQUNCQUJDQUMxMTEKQUJBQ0JDQUJDQUNCQUJBQ0JDQkFDQUJDQUJBQ0JDMTExMQpBQjEKQ0ExCkFCQUNDQjExCkFDQUJDQkJBMTEKQUNBQzExCkFDQUNBQkNCQUNCQUJDQUMxMTEKQUNBQkNCQUJCQ0JBQkNBQzExMQpBQ0FCQ0JBQ0JBQkNDQjExMQpBQkFDQkNBQkNBQ0JBQkFDQkNCQUNBQkNBQkFDMTExMQpBQkFCQUJBQ0JDQkNCQzExMTE) (The first two characters enable a linefeed-separated test suite.) Alternative solution, same byte count: ``` ^(?=\D*((?=(?<3>1+))1)+)((?=A(?<1-3>.+)|B(?<1-4>.+)|C(?<1-5>.+)).(?=A.*(?!\3)(\1)|B.*(?!\4)(\1)|C.*(?!\5)(\1)).)+(?<-5>1)+$ ``` This can possibly be shortened by using `1`, `11` and `111` instead of `A`, `B` and `C` but I'll have to look into that later. It might also be shorter to split the program into several stages, but where's the challenge in that? ;) ### Explanation This solution makes heavy use of .NET's balancing groups. For a full explanation [see my post on Stack Overflow](https://stackoverflow.com/a/17004406/1633117), but the gist is that capturing groups in .NET are stacks, where each new capture pushes another substring and where it's also possible to pop from such a stack again. This lets you count various quantities in a string. In this case it lets us implement the three rods directly as three different capturing groups where each disc is represented by a capture. To move discs around between rods we make use of a weird quirk of the `(?<A-B>...)` syntax. Normally, this pops a capture from stack `B` and pushes onto stack `A` the string between that popped capture and the beginning of this group. So `(?<A>a).(?<B-A>c)` matched against `abc` would leave `A` empty and `B` with `b` (as opposed to `c`). However, due to .NET variable-length lookbehinds it's possible for the captures of `(?<A>...)` and `(?<B-A>...)` to overlap. For whatever reason, if that's the case, the *intersection* of the two groups is pushed onto `B`. I've detailed this behaviour in the "advanced section" on balancing groups [in this answer](https://stackoverflow.com/a/36047989/1633117). On to the regex. Rods `A`, `B` and `C` correspond to groups `3`, `4` and `5` in the regex. Let's start by initialising rod `A`: ``` ^ # Ensure that we start at the beginning of the input. (?= # Lookahead so that we don't actually move the cursor. \D* # Skip all the instructions by matching non-digit characters. ( # For each 1 at the end of the input... (?=(?<3>1+)) # ...push the remainder of the string (including that 1) # onto stack 3. 1)+ ) ``` So e.g. if the input ends with `111`, then group 3/rod `A` will now hold the list of captures `[111, 11, 1]` (the top being on the right). The next bit of the code has the following structure: ``` ( (?=A...|B...|C...). (?=A...|B...|C...). )+ ``` Each iteration of this loop processes one instruction. The first alternation pulls a disc from the given rod (onto a temporary group), the second alternation puts that that disc onto the other given rod. We'll see in a moment how this works and how we ensure that the move is valid. First, taking a disc off the source rod: ``` (?= A(?<1-3>.+) | B(?<1-4>.+) | C(?<1-5>.+) ) ``` This uses the weird group-intersection behaviour I've described above. Note that group `3`, `4` and `5` will always hold substrings of `1`s at the end of the string whose length corresponds to the disc's size. We now use `(?<1-N>.+)` to pop the top disc off stack `N` and push the intersection of this substring with the match `.+` onto stack `1`. Since `.+` always necessarily covers the entire capture popped off `N`, we know that this simply moves the capture. Next, we put this disc from stack `1` onto the stack corresponding to the second rod: ``` (?= A.*(?!\3)(\1) | B.*(?!\4)(\1) | C.*(?!\5)(\1) ) ``` Note that we don't have to clean up stack `1`, we can just leave the disc there, since we'll put a new one on top before using the stack again. That means we can avoid the `(?<A-B>...)` syntax and simply copy the string over with `(\1)`. To ensure that the move is valid we use the negative lookahead `(?!\N)`. This ensures that, from the position where we want to match the current disc, it's impossible to match the disc already on stack `N`. This can only happen if either a) `\N` will never match because the stack is completely empty or b)`the disc on top of stack`N`is larger than the one we're trying to match with`\1`. Finally, all that's left is ensuring that a) we've matched all instructions and b) rods `A` and `B` are empty, so that all discs have been moved onto `C`. ``` (?!\3|\4)1 ``` We simply check that neither `\3` nor `\4` can match (which is only the case if both are empty, because any actual disc *would* match) and that we can then match a `1` so that we haven't omitted any instructions. [Answer] # Java "only" ~~311 272 263 261 260 259~~ 256 bytes Saved ~~39~~ countless bytes due to @Frozn noticing an older debug feature as well as some clever golfing tricks. Golfed version ``` int i(int n,int[]m){int j=0,k=0,i=n;Stack<Integer>t,s[]=new Stack[3];for(;j<3;)s[j++]=new Stack();for(;i-->0;)s[0].push(i);for(;k<m.length;k+=2)if((t=s[m[k+1]]).size()>0&&s[m[k]].peek()>t.peek())return 0;else t.push(s[m[k]].pop());return s[2].size()<n?0:1;} ``` ungolfed with explanation and pretty printed stacks at each step ``` /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package codegolf; /** * * @author rohan */ import java.util.Arrays; import java.util.Stack; public class CodeGolf { //golfed version int i(int n,int[]m){int j=0,k=0,i=n;Stack<Integer>[] s=new Stack[3];for(;j<3;j++)s[j]=new Stack();for(;i-->0;)s[0].push(i);for(;k<m.length;System.out.println(Arrays.toString(s)),k+=2)if(!s[m[k+1]].isEmpty()&&s[m[k]].peek()>s[m[k+1]].peek())return 0;else s[m[k+1]].push(s[m[k]].pop());return s[2].size()==n?1:0;} /** Ungolfed * 0 as falsy 1 as truthy * @param n the number of disks * @param m represents the zero indexed stacks in the form of [from,to,from,to] * @return 0 or 1 if the puzzle got solved, bad moves result in an exception */ int h(int n, int[] m) { //declarations int j = 0, k = 0, i = n; //create the poles Stack<Integer>[] s = new Stack[3]; for (; j < 3; j++) { s[j] = new Stack(); } //set up the first tower using the "downto operator for (; i-- > 0;) { s[0].push(i); } //go through and perform all the moves for (; k < m.length; System.out.println(Arrays.toString(s)), k += 2) { if (!s[m[k + 1]].isEmpty() && s[m[k]].peek() > s[m[k + 1]].peek()) { return 0;//bad move } else { s[m[k + 1]].push(s[m[k]].pop()); } } return s[2].size() == n ? 1 : 0;// check if all the disks are done } /** * @param args the command line arguments */ public static void main(String[] args) { //test case System.out.println( new CodeGolf().h(3,new int[]{0,2,0,1,2,1,0,2,1,0,1,2,0,2})==1?"Good!":"Bad!"); } } ``` The ungolfed version has a feature where it will print out what the stacks look like at each step like so... ``` [[2, 1], [], [0]] [[2], [1], [0]] [[2], [1, 0], []] [[], [1, 0], [2]] [[0], [1], [2]] [[0], [], [2, 1]] [[], [], [2, 1, 0]] Good! ``` [Answer] # Python 2, ~~186~~ ~~167~~ ~~158~~ ~~135~~ ~~127~~ ~~115~~ ~~110~~ 102 bytes ``` n,m=input() x=[range(n),[],[]] for a,b in m:p=x[a].pop();e=x[b];e and 1/(p>e[-1]);e+=p, if x[0]+x[1]:_ ``` Takes input on STDIN in the following format: ``` (1,[(0,1),(1,2)]) ``` That is, a Python tuple of the number of discs and a Python list of tuples of `(from_rod,to_rod)`. As in Python, the surrounding parentheses are optional. Rods are zero-indexed. For example, this test case: ``` n=2; "A->B ; A->C ; B->C" ``` would be given as: ``` (2,[(0,1),(0,2),(1,2)]) ``` If the solution is valid, outputs nothing and exits with an exit code of 0. If it is invalid, throws an exception and exits with an exit code of 1. Throws an `IndexError` if moving to a nonexistant rod or trying to take a disc off a rod that has no discs on it, a `ZeroDivisionError` if a disc is placed on top of a smaller disc, or a `NameError` if there are discs left on the first or second rods at the end. *Saved 13 bytes thanks to @KarlKastor!* *Saved 8 bytes thanks to @xnor!* [Answer] # [Retina](https://github.com/m-ender/retina), ~~84~~ 80 Bytes -5 bytes thanks to Martin Ender ``` ~ ~$' $ ABC {`^(.)(.*)( ~+)\1 $3$2$1 }`^(\W+)(\w)(.*)(?<=\1~+|\w)\2 $3$1$2 ^AB ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYAp-CiB-JCcKJApBQkMKe2BeKC4pKC4qKSggfispXDEKJDMkMiQxCn1gXihcVyspKFx3KSguKikoPzw9XDF-K3xcdylcMgokMyQxJDIKXkFCIA&input=QUN-CkFCQkN-CkFCQUNCQ35-CkFDQ0JBQ0JDfn4KQUNBQkNCQkFCQ0FDfn4KQUNBQkNCQUNCQUJDQUN-fn4KQUJBQ0JDQUJDQUNCQUJBQ0JDQkFDQUJDQUJBQ0JDfn5-fgpBQn4KQUNBQ34KQUNCQ34KQ0F-CkFCQUNDQn5-CkFDQUJDQkJBfn4KQUNBQ35-CkFDQUNBQkNCQUNCQUJDQUN-fn4KQUNBQkNCQUJCQ0JBQkNBQ35-fgpBQ0FCQ0JBQ0JBQkNDQn5-fgpBQkFDQkNBQkNBQ0JBQkFDQkNCQUNBQkNBQkFDfn5-fgpBQkFCQUJBQ0JDQkNCQ35-fn4KQUJBQn4KQUNBQkNCQUNCQUJDQUNDQUNBfn5-) (plus 5 bytes for line-by-line tests) The code simulates a full game. * Input is given as `ACABCBACBABCAC~~~`. `~~~` means three discs. * First four lines convert the input to the game format: `ACABCBACBABCAC ~~~ ~~ ~ABC`. In the beginning the A rod has all 3 discs, and B and C rods are empty. * Next we have a loop of two steps: + Take the first letter in the line, which indicates the next source rod. Find this rod, and take the last disc on in. Remove the letter and move the disc to the stark (pick it up). In out example, after the first step, the text will look like: `~CABCBACBABCAC ~~~ ~~ABC`. + In the second stage we find the target rod, and move the disc there. We validate the rod is empty, or has a bigger disc at the top: `ABCBACBABCAC ~~~ ~~AB ~C`. * Finally we confirm the A and B rods are empty - this means all discs are in C (there's an extra space at the last line). [Answer] # Python 2.7, ~~173~~ ~~158~~ ~~138~~ ~~130~~ ~~127~~ 123 bytes: ``` r=range;a,b=input();U=[r(a,0,-1),[],[]] for K,J in b:U[J]+=[U[K].pop()]if U[J]<[1]or U[K]<U[J]else Y print U[-1]==r(a,0,-1) ``` Takes input through the stdin in the format `(<Number of Discs>,<Moves>)` where `<Moves>` is given as an array containing tuples corresponding to each move, which each contain a pair of comma separated integers. For instance, the test case: ``` n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C" ``` given in the post would be given as: ``` (3,[(0,2),(0,1),(2,1),(0,2),(1,0),(1,2),(0,2)]) ``` to my program. Outputs an `IndexError` if the 3rd condition isn't met, a `NameError` if the 2nd condition isn't met, and `False` if the 1st condition isn't met. Otherwise outputs `True`. [Answer] # VBA, ~~234~~ ~~217~~ ~~213~~ 196 bytes ``` Function H(N,S) ReDim A(N) While P<Len(S) P=P+2:F=1*Mid(S,P-1,1):T=1*Mid(S,P,1) E=E+(T>2):L=L+T-F For i=1 To N If A(i)=F Then A(i)=T:Exit For E=E+(A(i)=T)+(i=N) Next Wend H=L+9*E=2*N End Function ``` Input format for moves is a string with an even number of digits (012). Invocation is in spreadsheet, =H([number of discs], [move string]) The array A holds the rod position of the various discs. A move is simply updating the first occurrence of the "From" rod number into the "To" rod number. If you encounter a "To" rod disc first, or no "From" rod disc, it's an invalid move. The total "rod value" of A is held in L, which needs to end at 2N. Errors are accumulated as a negative count in E. In common with other solutions, "moving" a disc from a tower to the same tower is not forbidden. I could forbid it for another 6 bytes. ## Results Function result in first column (the last n=3 case is my addition using an extra rod). ``` TRUE 1 02 TRUE 1 0112 TRUE 2 010212 TRUE 2 02210212 TRUE 2 020121101202 TRUE 3 02012102101202 TRUE 4 010212012021010212102012010212 FALSE 1 01 FALSE 1 20 FALSE 2 02012102101202 FALSE 2 010221 FALSE 2 02012110 FALSE 2 0202 FALSE 3 0202012102101202 FALSE 3 0201210112101202 FALSE 3 02012102101221 FALSE 3 0103023212 FALSE 4 0102120120210102121020120102 FALSE 4 01010102121212 ``` [Answer] # php, 141 bytes ``` <?php $a=$argv;for($t=[$f=range($a[++$i],1),[],[]];($r=array_pop($t[$a[++$i]]))&&$r<(end($t[$a[++$i]])?:$r+1);)$t[$a[$i]][]=$r;echo$t[2]==$f; ``` Command line script, takes input as the height then a series of array indexes (0 indexed) e.g. 1 0 2 or 2 0 1 0 2 1 2 for the 1 or 2 height shortest test cases. Echos 1 on true cases and nothing on false ones. Gives 2 notices and 1 warning so needs to be run in an environment that silences those. [Answer] # JavaScript (ES6), 108 ``` n=>s=>!s.some(([x,y])=>s[y][s[y].push(v=s[x].pop())-2]<v|!v,s=[[...Array(s=n)].map(_=>s--),[],[]])&s[2][n-1] ``` **Input format:** function with 2 arguments * arg 1, numeric, number of rings * arg 2, array of strings, each string 2 characters '0','1','2' **Output:** return 1 if ok, 0 if invalid, exception if nonexisting rod **Less golfed** and explained ``` n=>a=>( // rods status, rod 0 full with an array n..1, rod 1 & 2 empty arrays s = [ [...Array(t=n)].map(_=>t--), [], [] ], // for each step in solution, evaluate function and stop if returns true err = a.some( ([x,y]) => { v = s[x].pop(); // pull disc from source rod // exception is s[x] is not defined if (!v) return 1; // error source rod is empty l = s[y].push(v); // push disc on dest rod, get number of discs in l // exception is s[y] is not defined if(s[y][l-2] < v) return 1; // error if undelying disc is smaller }), err ? 0 // return 0 if invalid move : s[2][n-1]; // il all moves valid, ok if the rod 2 has all the discs ) ``` **Test** Note: the first row of the Test function is needed to convert the input format given in the question to the input expected by my function ``` F= n=>s=>!s.some(([x,y])=>s[y][s[y].push(v=s[x].pop())-2]<v|!v,s=[[...Array(s=n)].map(_=>s--),[],[]])&s[2][n-1] Out=x=>O.textContent+=x+'\n' Test=s=>s.split`\n`.map(r=>[+(r=r.match(/\d+|.->./g)).shift(),r.map(x=>(parseInt(x[0],36)-10)+''+(parseInt(x[3],36)-10))]) .forEach(([n,s],i)=>{ var r try { r = F(+n)(s); } catch (e) { r = 'Error invalid rod'; } Out(++i+' n:'+n+' '+s+' -> '+r) }) Out('OK') Test(`n=1, "A->C" n=1, "A->B ; B->C" n=2, "A->B ; A->C ; B->C" n=2, "A->C ; C->B ; A->C ; B->C" n=2, "A->C ; A->B ; C->B ; B->A ; B->C ; A->C" n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C" n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C ; B->C"`) Out('\nFail') Test( `n=1, "A->B" n=1, "C->A" n=2, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C" n=2, "A->B ; A->C ; C->B" n=2, "A->C ; A->B ; C->B ; B->A" n=2, "A->C ; A->C" n=3, "A->B ; A->D; A->C ; D->C ; A->C" n=3, "A->C ; A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C" n=3, "A->C ; A->B ; C->B ; A->B ; B->C ; B->A ; B->C ; A->C" n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; C->B" n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C" n=4, "A->B ; A->B ; A->B ; A->C ; B->C ; B->C ; B->C"`) ``` ``` <pre id=O></pre> ``` ]
[Question] [ It is often said, that all programmers should be able to write a "hello world" program in any programming language after a few glances on that language (And [quicksort](https://codegolf.stackexchange.com/questions/2445/implement-quicksort-in-brainf) after a few more glances). As the [Conway's Game of Life](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) is Turing complete (so it qualifies as a general-purpose programming language), the problem is self-explanatory: Create a "Hello World!" application using only Conway's Game of Life! The only valid entry is an **initial state** for the Conway's Game of Life, which: * **does not contain** any recognizable shape resembling the text "Hello World!" * **will contain** a recognizable shape resembling the text "Hello World!" within a reasonable number of cycles (it should not run for more than a couple of minutes on a good PC - this enables billions of cycles and should be enough) * the area where the "Hello World!" text will appear **should be empty** in the initial state! (Otherwise the problem would be way too easy) If no one manages to do it, we might reduce this requirement to "mostly empty" **Scoring:** **The winner will be based on the number of upvotes in approximately one week after the first valid submission.** Guidelines for voting: * more elaborate and beautiful output should be worth more * output which is stable over many cycles should be worth more than one which fades away to be unrecognizable in the next cycle. * a solution locked into a perpetual cycle, or starting from an interesting pattern is worth the most, because it proves intelligent design of the state, and not just random trial and error with a reverse simulation. **The entry should be in a format readable by at least one of the [notable simulators](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life#Notable_Life_programs) or an online simulator which the answerer links to. Links (to an animation or a simulator set to the initial state) are also accepted, even encouraged. If the output is not visible within a few cycles, the entry should specify after which cycle will the result be visible.** --- ***Edit:*** There can be some slight tolerance in the phrase to be generated. It can be "`Hello, World!`", "`hello, world`" "`HELLO WORLD!`" etc. [Answer] My first attempt to this, a relatively simple solution. It fires a couple of glider barrels. Each pair of gliders turns into a block, which then form the text. This process takes about 16000 generations (you can set a frame skip or use the superstep button in my simulator). [Direct Link](http://copy.sh/life/?pattern=hello_world_copy). Move around with right mouse, zoom with mouse wheel. [Link to .rle file (also works with Golly)](http://copy.sh/life/examples/hello_world_copy.rle) Image of the pattern 32:1: ![Image of the pattern 32:1](https://i.stack.imgur.com/WcCcs.png) ]
[Question] [ Given a list of integers, your task is to output the second largest value in the first *k* elements, for each *k* between 2 and the length of the input list. In other words, output the second largest value for each prefix of the input. You can output an arbitrary value for the first element (where *k* = 1), or simply omit this value, as there isn't a second maximum for a list of 1 element. You may assume there are at least 2 elements in the input. Shortest code wins. ## Examples ``` Input: 1 5 2 3 5 9 5 8 Output: 1 2 3 5 5 5 8 Input: 1 1 2 2 3 3 4 Output: 1 1 2 2 3 3 Input: 2 1 0 -1 0 1 2 Output: 1 1 1 1 1 2 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` ηεà\à ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3PZzWw8viDm84P//aEMdBVMdBSMdBWMwwxJMWsQCAA "05AB1E – Try It Online") Returns `[]` (arbitrary value) for first. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~9~~ 7 bytes Saved a byte or two thanks to @Zgarb ``` mȯ→hOtḣ ``` Returns `0` for the first "second maximum" ### Explaination ``` -- implicit input, e.g [1,5,3,6] ḣ -- prefixes [[],[1],[1,5],[1,5,3],[1,5,3,6]] t -- remove the first element [[1],[1,5],[1,5,3],[1,5,3,6]] mȯ -- map the composition of 3 functions O -- sort [[1],[1,5],[1,3,5],[1,3,5,6]] h -- drop the last element [[],[1],[1,3],[1,3,5] → -- return the last element [0,1,3,5] -- implicit output ``` [Try it online!](https://tio.run/##yygtzv7/P/fE@kdtkzL8Sx7uWPz///9oQx1THSMdYyBpCcQWsQA "Husk – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 54 bytes ``` lambda x:[sorted(x[:i])[-2]for i in range(2,1+len(x))] ``` [Try it online!](https://tio.run/##HYtBDsIgEEX3noJdIU4ToZooiSehLDAFJcGhQRZ4ehxczM//72X2b31lVD3c157c@7E51rT55FL9xpvR0QozKxtyYZFFZMXh03MF8pg88iaE7cOl4YyRcAEFC@WN7mqBiCQy2AJn2vQJJ5hHkLBWH9heIlaWYFpxgsCT@Lfefw "Python 2 – Try It Online") [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 4 bytes ``` poil ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FksK8jNzlhQnJRdDBRbcNIo21DHVMdIxBpKWQGwRywUUMQSKgMSMdUyAfCMg30BHF0QAJWIhWgE) ``` p Prefix o Sort i Init (remove the last element) l Last ``` Accidentally, [poil means hair in French](https://en.wiktionary.org/wiki/poil). [Answer] ## JavaScript (ES6), ~~58~~ ~~51~~ 50 bytes *Saved 1 byte thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)* Appends `undefined` for ***k = 1***. ``` a=>a.map(e=>(b=[e,...b]).sort((a,b)=>b-a)[1],b=[]) ``` ### Test cases *NB: This snippet uses `JSON.stringify()` for readability, which -- as a side effect -- converts `undefined` to `null`.* ``` let f = a=>a.map(e=>(b=[e,...b]).sort((a,b)=>b-a)[1],b=[]) console.log(JSON.stringify(f([1, 5, 2, 3, 5, 9, 5, 8]))) // 1 2 3 5 5 5 8 console.log(JSON.stringify(f([1, 1, 2, 2, 3, 3, 4]))) // 1 1 2 2 3 3 console.log(JSON.stringify(f([2, 1, 0, -1, 0, 1, 2]))) // 1 1 1 1 1 2 ``` [Answer] # [Python 2](https://docs.python.org/2/), 45 bytes ``` f=lambda l:l[1:]and f(l[:-1])+[sorted(l)[-2]] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIccqJ9rQKjYxL0UhTSMn2krXMFZTO7o4v6gkNUUjRzNa1yg29n9BUWZeCVA@2lDHVMdIxxhIWgKxRawmF5KUIVAKJGmsY4IsYQSUMNDRBRFAFbGa/wE "Python 2 – Try It Online") The right side of the code is self-explanatory. However, what do we put to the left of the `and`? Because we are concatenating parts of a list recursively, we need the left side to be truthy if `l` has 2 or more elements, and an empty list otherwise. `l[1:]` satisfies this criterion nicely. [Answer] # [Pyth](https://pyth.readthedocs.io), 8 bytes ``` m@Sd_2._ ``` **[Try it online!](https://pyth.herokuapp.com/?code=m%40Sd_2._&input=%5B1%2C5%2C2%2C3%2C5%2C9%2C5%2C8%5D&debug=0)** or **[Try the Test Suite!](http://pyth.herokuapp.com/?code=m%40Sd_2._&input=%5B1%2C+5%2C+2%2C+3%2C+5%2C+9%2C+5%2C+8%5D&test_suite=1&test_suite_input=%5B1%2C5%2C2%2C3%2C5%2C9%2C5%2C8%5D%0A%5B1%2C+1%2C+2%2C+2%2C+3%2C+3%2C+4%5D%0A%5B2%2C+1%2C+0%2C+-1%2C+0%2C+1%2C+2%5D&debug=0)** --- # How? This outputs the first element of the list as the first value in the list, as per the spec *You can output an arbitrary value for the first element*. ``` m@Sd_2._ - Full program with implicit input. m ._Q - Map over the prefixes of the input with a variable d. Sd - Sorts the current prefix. @ - Gets the element... _2 - At index - 2 (the second highest). - Print implicitly. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ḣJṢ€Ṗ€Ṫ€ ``` [Try it online!](https://tio.run/##y0rNyan8///hjsVeD3cuetS05uHOaWByFZD8//9/tKGOgqmOgpGOgjGYYQkmLWIB "Jelly – Try It Online") The first value will be 0, always, and the following numbers will be the second maximums of each prefix. ## Explanation ``` ḣJṢ€Ṗ€Ṫ€ Input: array A J Enumerate indices, [1, 2, ..., len(A)] ḣ Head, get that many values from the start for each, forms the prefixes Ṣ€ Sort each Ṗ€ Pop each, removes the maximum Ṫ€ Tail each ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~87~~ 86 bytes ``` a->{int x,y=x=1<<-1;for(int c:a){if((c>x?x=c:c)>y){x=y;y=c;}System.out.print(x+" ");}} ``` [Try it online!](https://tio.run/##ZY9Nb4MwDIbv@RVWT0GDaHSbtJWPHXbeqceqhyyFKgwSlBgEQvx2Fihbt86K4sTvY@t1wVse6DpTxelzklWtDULhaqxBWbK8UQKlVuxNK9tUmYkIqZuPUgoQJbcW3rlUMBACLlbBIkeXWi1PUDmZ7tFIdT4cgZuz9RwNa2BmkYY@PPmw9eFhebws97MX/aPChbqA7jzeItsFufchuKSZX5mRrA6NbDlmfywuvVIhY8wZNL/9fS8dO/lwTCGHZOJBOrgvdH6fdEkYx0EY5drME0DsuDfInFKRdq9dInbCS3tv6JI@6hMRjfveYlYx3SBzThTS7m4DGy8ax@m6S864EFmNdDZzLd/2lor@LDeS6Qs "Java (OpenJDK 8) – Try It Online") [Answer] # J, 13 bytes ``` _2&{@/:~ ::#\ ``` [Try it online!](https://tio.run/##y/r/P81WL95IrdpB36pOwcpKOYaLKzU5I18hTcFQwVTBSMEYSFoCscX//wA) The first element is always 1. # Explanation ``` _2&{@/:~ ::#\ \ Apply to prefixes _2&{@/:~ Sort and take second-to-last atom /:~ Sort upwards _2 { Take second-to-last atom :: If there's an error (i.e only one atom) # Return the length of the list (1) ``` [The space matters.](http://code.jsoftware.com/wiki/Vocabulary/coco) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` Ṣ-ịƊƤ ``` [Try it online!](https://tio.run/##y0rNyan8///hzkW6D3d3H@s6tuT/4fZHTWu8gTjy//9oLs5oQx0FUx0FIx0FYzDDEkxaxOpApAzBUhBZIDIBixuBxQ10FHQhFEgRUCIWAA "Jelly – Try It Online") Outputs the first value of the input as the first value in the output. This can be removed for adding [one byte](https://tio.run/##y0rNyan8///hzkW6D3d3H@s6tuThjq7/h9sfNa3xBuLI//@juTijDXUUTHUUjHQUjMEMSzBpEasDkTIES0FkgcgELG4EFjfQUdCFUCBFQIlYAA). ## How it works ``` Ṣ-ịƊƤ - Main link. Takes l on the left Ƥ - Generate the prefixes of l Ɗ - Run the following code over each prefix: Ṣ - Sort the prefix -ị - Take the -1th index. - Jelly lists are 1 indexed and modular. This means that the 0th index of a list is the final element and -1 the second to last element ``` [Answer] # [Scala](http://www.scala-lang.org/), ~~58~~ 46 bytes ``` x=>2 to x.size map(x take _ sortBy(-_)apply 1) ``` [Try it online!](https://tio.run/##bcyxCsIwAATQvV9xYwJRbKugQgt1E/QLREqsKURjGpogqeK3x2TW4W65x9mOKx6Gy010DkcuNYR3Ql8tGmPwzp5cod/iIK077bU7o6rR6AlV8FVdwA3wcytfAg9uiIfjd4EWdhjdbiKzlnJj1IScBjNK7ZQmPUlfJGcrVrAy9iZmTSnNfkQeRTIlW/7Zi7gv2CxVhAl8whc "Scala – Try It Online") Takes a List as an argument, and returns a Vector. -12 bytes from user. [Answer] # [Zsh](https://www.zsh.org/), 32 bytes ``` for x;a+=($x)&&<<<${${(On)a}[2]} ``` [Try it online!](https://tio.run/##qyrO@J@moanxPy2/SKHCOlHbVkOlQlNNzcbGRqVapVrDP08zsTbaKLb2vyYXV5qCoYKpgpGCMZC0BGILsIghUAQkZqxgAuQbAfkGCrogAijxHwA "Zsh – Try It Online") Reverse `O`rder `n`umerically, `<<<` print the `[2]`nd element. [Answer] # [Desmos](https://www.desmos.com), 44 bytes ``` f(x)=[x[1...i].sort[i-1]fori=[2...x.length]] ``` [Try it on Desmos!](https://www.desmos.com/calculator/08zdna8fty) [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` ƒıṠṫt ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNiU5MiVDNCVCMSVFMSVCOSVBMCVFMSVCOSVBQnQmZm9vdGVyPSZpbnB1dD0xJTJDJTIwNSUyQyUyMDIlMkMlMjAzJTJDJTIwNSUyQyUyMDklMkMlMjA1JTJDJTIwOCZmbGFncz1l) Uses `[]` as the (arbitrary) first value. #### Explanation ``` ƒıṠṫt # Implicit input ƒ # Prefixes of the input ı # Map over this list: Ṡ # Sort this list ṫt # Second-last item # Implicit output ``` [Answer] # [C# (Mono)](http://www.mono-project.com/), 81 bytes ``` using System.Linq;a=>a.Select((_,i)=>a.Take(++i).OrderBy(n=>n).Skip(i-2).First()) ``` [Try it online!](https://tio.run/##nY/fS8MwEMff@1ccPiUsDa4qKLV9cDhRFAcVfBCRmN3kWJtokipj9G@vaYvg8@C4X9x97nvap401tm89mQ@odj5gkyf/K3lP5itPEl0r72GV7BMfVCAN35bW8KDIMB6by9boSzLh5VX8LS5sXaMOZI2XN2jQkZa316Zt0Kn3GofpsoQNFNCrolSywmGcsTdBfKif1BbZbEZcPro1uqsdM0VpuKy29MkozbhckvOBcd5HfYt4xtYonx0FjJqR@eDiG/LORolHAqJtmMEfGFXCfi7gTEAm4GRMLkZ/3nHO84Ng8xE28aKdHkjKRtKxgHQKA3ZCdUnX/wI "C# (Mono) – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` a₀ᶠb{okt}ᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P/FRU8PDbQuSqvOzS2ofbp3w/3@0oY6pjpGOMZC0BGKL2P9RAA "Brachylog – Try It Online") [Answer] ## Batch, 123 bytes ``` @set/af=s=%1 @for %%n in (%*)do @call:c %%n @exit/b :c @if %1 gtr %s% set s=%1 @if %1 gtr %f% set/as=f,f=%1 @echo %s% ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 15 bytes ``` (2⊃⍒⊃¨⊂)¨1↓,\∘⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/FR2wQNo0ddzY96JwHJQysedTVpHlph@Khtsk7Mo44Zj7oWARUpGCkYKhgoHFoPIg0VjAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes Found another 5-byter, *very* different from [Erik's solution](https://codegolf.stackexchange.com/a/138521/59487). The arbitrary value is the first element of the list. ``` ηε{Áθ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3PZzW6sPN57b8f9/tKGOqY6RjjGQtARii1gA "05AB1E – Try It Online") --- # Explanation ``` ηε{Áθ - Full program that reads implicitly from STDIN and outputs to STDOUT. η - Push the Prefixes of the list. ε - Apply to each element (each prefix): { - Sort the prefix list. Á - Shift the list to the right by 1, such that the first element goes to the beginning and the second largest one becomes the last. θ - Get the last element (i.e. the second largest) - Print implicitly. ``` --- Let's take an example, to make it easier to understand. * First we get the implicit input, let's say it's `[1, 5, 2, 3, 5, 9, 5, 8]`. * Then, we push its prefixes using `η` - `[[1], [1, 5], [1, 5, 2], [1, 5, 2, 3], [1, 5, 2, 3, 5], [1, 5, 2, 3, 5, 9], [1, 5, 2, 3, 5, 9, 5], [1, 5, 2, 3, 5, 9, 5, 8]]`. * Now, the code maps through the list and sorts each prefix using `{` - `[[1], [1, 5], [1, 2, 5], [1, 2, 3, 5], [1, 2, 3, 5, 5], [1, 2, 3, 5, 5, 9], [1, 2, 3, 5, 5, 5, 9], [1, 2, 3, 5, 5, 5, 8, 9]]`. * We then take the very last element and move it to the beginning: `[[1], [5, 1], [5, 1, 2], [5, 1, 2, 3], [5, 1, 2, 3, 5], [9, 1, 2, 3, 5, 5], [9, 1, 2, 3, 5, 5, 5], [9, 1, 2, 3, 5, 5, 5, 8]]`. * Of course, now the code gets the last element of each sublist using `θ` - `[1, 1, 2, 3, 5, 5, 5, 8]` (the first one being the arbitrary value. [Answer] # [CJam](https://sourceforge.net/p/cjam), 16 bytes ``` {_,,:)\f{<$-2=}} ``` [Try it online!](https://tio.run/##S85KzP2fU/e/Ol5Hx0ozJq3aRkXXyLa29n9dakqs9f9oQwVTBSMFYyBpCcQWsQA "CJam – Try It Online") Returns first element for first. -2 thanks to [Challenger5](https://codegolf.stackexchange.com/users/61384/challenger5). [Answer] # [R](https://www.r-project.org/), 54 49 bytes Thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) -5 bytes. I did not know this feature of `seq()`. ``` for(i in seq(x<-scan()))cat(sort(x[1:i],T)[2],"") ``` [Try it online!](https://tio.run/##K/r/Py2/SCNTITNPoTi1UKPCRrc4OTFPQ1NTMzmxRKM4v6hEoyLa0CozVidEM9ooVkdJSfO/IZcplxGXMZC0BGKL/wA "R – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~12~~ 10 bytes The output array consists of the first element in the input array followed by the desired sequence. ``` £¯YÄ n< g1 ``` [Test it](http://ethproductions.github.io/japt/?v=1.4.5&code=o69ZxCBuPCBnMQ==&input=WzEsNSwyLDMsNSw5LDUsOF0=) --- ## Explanation Implicit input of array `U`. ``` £ ``` Map over `U`, where `Y` is the current index. ``` ¯YÄ ``` Slice `U` from `0` to `Y+1`. ``` n< ``` Sort descending. ``` g1 ``` Get the second element. Implicitly output the resulting array. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~19~~ 10 bytes *Thanks to Luis Mendo for shaving off 9 bytes!* ``` "GX@:)SP2) ``` Try it [here](https://matl.suever.net/?code=tn2w2%24%3A%22t%40%3A%29SP2%29w%5Dx&inputs=%5B1%205%202%203%205%209%205%208%5D&version=20.2.2). ### Explanation ``` "GX@:)SP2) " for all the values in the input G get input X@:) get values up to the iteration SP sort it in descending order 2) get the second value implicit end of loop and output ``` [Answer] # [k](https://en.wikipedia.org/wiki/K_(programming_language)), 13 bytes ``` {x(>x)1}'1_,\ ``` [Try it online!](https://tio.run/##y9bNz/7/P82qukLDrkLTsFbdMF4n5n@aup6VuoGVkn5Kapl@cUlKZp7Sf0MFUwUjBWMgaQnEFlyGCoZAPkjEWMGEywjIM1DQBRFAYQA "K (oK) – Try It Online") ``` ,\ /sublists of increasing lengths (scan concat) 1_ /remove the first sublist { }' /for each sublist: (>x) / indices to permute sublist into largest to smallest 1 / get second index x / get sublist[that index] ``` [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm), ~~10~~ 8 bytes *-2 bytes thanks to ETHproductions.* ``` ∙p»îS2~ª ``` [Try it online!](https://tio.run/##y8/I/f//UcfMgkO7D68LNqo7tOr//2hDHQVTHQUjHQVjMMMSTFrEAgA "Ohm – Try It Online") ~~Uh, this is odd but I don't know how else to push a negative number...~~ I don't *really* know Ohm. :P [Answer] # [Factor](https://factorcode.org/) + `grouping.extras`, 41 bytes ``` [ head-clump rest [ 1 kth-largest ] map ] ``` [Try it online!](https://tio.run/##PY9NCsIwEEb3PcXnAVq0Vah6AHHjRlyVLkKMbehfTKaglJ49Tqh0hvkgb95i8hKSBusf9@vtckJlh9HovkrUh6xwcOo9ql4qh05QnTgSpB1p6WCsIvoaq3vCOZoicE3Y4YAUGeeRJ8eMDRguKHS@ioEGnmHPGhZxhX8tZbJFHCKs5lVbOo1mX6BW4hnLduwMrHKEgjcN1XErbBXeJR9vUPqQ/APZJP4H "Factor – Try It Online") * `head-clump rest` Prefixes without the first * `[ 1 kth-largest ] map` Map each to the second-largest element [Answer] # [Arturo](https://arturo-lang.io), ~~45~~ 44 bytes ``` $->a->map..2size a=>[last chop sort take a&] ``` [Try it](http://arturo-lang.io/playground?YDp6y0) ``` $->a-> ; a function taking an argument a map..2size a => [ ; map over the indices of a sans the first few last ; the last element chop ; of a block without its last element sort ; sorted take a & ; prefix of input given current index ] ; end map ``` [Answer] # Mathematica, 45 bytes ``` Sort[s[[;;i]]][[-2]]~Table~{i,2,Length[s=#]}& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvs/OL@oJLo4OtraOjM2NjY6WtcoNrYuJDEpJ7WuOlPHSMcnNS@9JCO62FY5tlbtf0BRZl6JgkNadLWhjoKpjoKRjoIxmGEJJi1qY/8DAA "Mathics – Try It Online") [Answer] # [Swift 3](https://www.swift.org), 67 bytes ``` func g(l:[Int]){print((1..<l.count).map{l[0...$0].sorted()[$0-1]})} ``` **[Test Suite.](http://swift.sandbox.bluemix.net/#/repl/598db322de80147f1a9d2322)** # [Swift 3](https://www.swift.org), 65 bytes ``` {l in(1..<l.count).map{l[0...$0].sorted()[$0-1]}}as([Int])->[Int] ``` **[Test Suite.](http://swift.sandbox.bluemix.net/#/repl/598db37ede80147f1a9d2323)** --- ### How to run these? The first one is a complete function that takes the input as a function parameter and prints the result. You can use them exactly as shown in the testing link. I decided to add instructions though, because the second type of function is used very rarely and most people don't even know of its existence. **Usage:** ``` g(l: [1, 1, 2, 2, 3, 3, 4] ) ``` The second one is an anonymous function, like lambdas. You can use it exactly as you'd do it Python, declaring a variable `f` and calling it: ``` var f = {l in(1..<l.count).map{l[0...$0].sorted()[$0-1]}}as([Int])->[Int] print(f([1, 1, 2, 2, 3, 3, 4])) ``` **or** wrap it between brackets and call it directly (`(...)(ArrayGoesHere)`): ``` print(({l in(1..<l.count).map{l[0...$0].sorted()[$0-1]}}as([Int])->[Int])([1, 1, 2, 2, 3, 3, 4])) ``` ]
[Question] [ [Suzhou numerals](https://en.wikipedia.org/wiki/Suzhou_numerals) (蘇州碼子; also 花碼) are Chinese decimal numerals: ``` 0 〇 1 〡 一 2 〢 二 3 〣 三 4 〤 5 〥 6 〦 7 〧 8 〨 9 〩 ``` They pretty much work like Arabic numerals, except that when there are consecutive digits belonging to the set `{1, 2, 3}`, the digits alternate between vertical stroke notation `{〡,〢,〣}` and horizontal stroke notation `{一,二,三}` to avoid ambiguity. The first digit of such a consecutive group is always written with vertical stroke notation. The task is to convert a positive integer into Suzhou numerals. ## Test cases ``` 1 〡 11 〡一 25 〢〥 50 〥〇 99 〩〩 111 〡一〡 511 〥〡一 2018 〢〇〡〨 123321 〡二〣三〢一 1234321 〡二〣〤〣二〡 9876543210 〩〨〧〦〥〤〣二〡〇 ``` **Shortest code in bytes wins.** [Answer] # [R](https://www.r-project.org/), 138 bytes I'll bet there's an easier way to do this. Use `gsub` to get the alternating numeric positions. ``` function(x,r=-48+~x)Reduce(paste0,ifelse(58<~gsub("[123]{2}","0a",x),"123"["一二三",r],'0-9'["〇〡-〩",r])) "~"=utf8ToInt "["=chartr ``` [Try it online!](https://tio.run/##XZDNaoNAFIX3PkW5Xah0BH9iqxAfoNvSnWRh7dgGiik6glAqsyuFvER/bJM3CHmd8T3snUnQ2GEWw3fPvefcKfpsbvVZladsucqNmhSRNQsumtq8ofdVSo3npGTUJsuMPpXU8IN581BWdwbEjustXtxXIGAnQGqTABKIodvxbr/udu9AigXRbSvUYxD8TfAPS/CtpKapQQNRxbLgdnWdMw3bovQxKVjRZ4bu6Ob52XCwT5NwQhGij@SuP@WfgreS@/aUtxhB8jCc8i3ew/xTg8P8o7X/r9SeuNtOMNaUu1xU8I2a6XqeO/TKrv1a8C/8G1QeJ6BmNooGjeDfUinfKkMYXF36UqjWUrE3gv8K/qPyjGIM0P8B "R – Try It Online") [Answer] # JavaScript, 81 bytes ``` s=>s.replace(/./g,c=>(p=14>>c&!p)|c>3?eval(`"\\u302${c}"`):'〇一二三'[c],p=0) ``` [Try it online!](https://tio.run/##dZDdTsIwGIbPvYrZGGkT2LqNCTNpvRAxYamFaBbWMOBETXpGTLgJf6ZwB4Tb6e5jdv4w0mLzHfTgeb8873efLJKcTe/ErDPJbnk1IlVOaO5OuUgTxqHneuM2IxQK4ncpZeenAj0yGl7xRZLCIRgM5iEOzh7YExiiy5aSy3Iry92q3D63rtlNWxCMKpZN8izlbpqN4QgCHzh/DyHH8xwlX05MpoH2jN5sYkFkYa9KFiYWYQsrtKqJxbGFbfTYbnu5Q7cjLSKbLP4pgv0@sIosNazk2hIIwjD42dwI7FZKvumz6@CR/TrS/c0YESXf62D9t/zjfu8iqnMYHBxkreSnkh/fXZqstq2@AA "JavaScript (Node.js) – Try It Online") Using `14>>c` saves 3 bytes. Thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld). [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 46 bytes ``` /[1-3]{2}|./_T`d`〇〡-〩`^. T`123`一二三 ``` [Try it online!](https://tio.run/##K0otycxLNPz/Xz/aUNc4ttqotkZPPz4kISXhcUP744aFuo8bVibE6XGFJBgaGSc82dHwZFfPkx2d//8bchkachmZcpkacFlaAtmGXKYgAQNDCy6gSmMjQxBlAqItLczNTEEsAwA "Retina – Try It Online") Link includes test cases. Explanation: ``` /[1-3]{2}|./ ``` Match either two digits 1-3 or any other digit. ``` _T`d`〇〡-〩`^. ``` Replace the first character of each match with its Suzhou. ``` T`123`一二三 ``` Replace any remaining digits with horizontal Suzhou. 51 bytes in [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d): ``` M!`[1-3]{2}|. mT`d`〇〡-〩`^. T`¶123`_一二三 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7w31cxIdpQ1zi22qi2Ro8rNyQhJeFxQ/vjhoW6jxtWJsTpcYUkHNpmaGScEP9kR8OTXT1PdnT@/2/IZWjIZWTKZWrAZWkJZBtymYIEDAwtuIBKjY0MQZQJiLa0MDczBbEMAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` M!`[1-3]{2}|. ``` Split the input into individual digits or pairs of digits if they are both 1-3. ``` mT`d`〇〡-〩`^. ``` Replace the first character of each line with its Suzhou. ``` T`¶123`_一二三 ``` Join the lines back together and replace any remaining digits with horizontal Suzhou. [Answer] # [Perl 5](https://www.perl.org/) `-pl -Mutf8`, ~~53~~ 46 bytes *-7 bytes thanks to Grimy* ``` s/[123]{2}|./OS&$&/ge;y//〇〡-〰一二三/c ``` [Try it online!](https://tio.run/##K0gtyjH9/79YP9rQyDi22qi2Rk/fP1hNRU0/PdW6Ul//cUP744aFuo8bNjzZ0fBkV8@THZ36yf//G3IZGnIZmXKZGnBZWgLZhlymIAEDQwsuoDnGRoYgygREW1qYm5mCWAb/8gtKMvPziv/r5hT813X@r@tbWpJmAQA "Perl 5 – Try It Online") ### Explanation ``` # Binary AND two consecutive digits 1-3 (ASCII 0x31-0x33) # or any other single digit (ASCII 0x30-0x39) with string "OS" # (ASCII 0x4F 0x53). This converts the first digit to 0x00-0x09 # and the second digit, if present, to 0x11-0x13. s/[123]{2}|./OS&$&/ge; # Translate empty complemented searchlist (0x00-0x13) to # respective Unicode characters. y//〇〡-〰一二三/c ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 120 bytes ``` s->{for(int i=0,p=0,c;i<s.length;)s[i]+=(p>0&p<4&(c=s[i++]-48)>0&c<4)?"A䷏乚䷖".charAt(c+(p=0)):(p=c)<1?12247:12272;} ``` [Try it online!](https://tio.run/##VVDLbsIwELzzFatIIFsJVpImBfIAIc49cUQcXJOAaXCi2KFCiG/orYf@COr/8B@pA5THYb2z493RaNZ0S7vrxUfNN0VeKljrmVSKZyStBFM8F2SSC1ltkjJssYxKCW@UC9i3AIrqPeMMpKJKt23OF7DRf2iqSi6WsznQcinxeRXgXyViK1rO5kNI41p2h/s0LxEXCnhsW4UuFvJIkiwRS7UKsZzxuRmjYmh3isjrIBZrxjTnXa@PNcciD4@M8en4dfr9OR2/DdKojxViJtJiGAe6MRw5I8d1vV6g354bHurwbOnmUyVSSYivTgEMx7Bu8AG7/h379h0PBo/7Dwf@07Xt9B/23JcX13mavSdi0O@9@g1lG2fqcDHd5HUxfrYdXMzjm/dLvCDjhicqnzSBlCXdIRxeV1JCGUsKheSNmu6kSjYkrxQptLZKkdF2bBlAW7aFYTValkg@r5Hpw@vlodXUof4D "Java (JDK) – Try It Online") ## Credits * -3 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) [Answer] # JavaScript (ES6), ~~95 89~~ 88 bytes *Saved 6 bytes thanks to @ShieruAsakoto* Takes input as a string. ``` s=>s.replace(i=/./g,c=>'三二一〇〡〢〣〤〥〦〧〨〩'[i=112>>i&c<4?3-c:+c+3]) ``` [Try it online!](https://tio.run/##dZFPboJAFIf3noKwqBArf8VK06EHaVyQEQ2GiJGm67czTbxEa7F4A@N1HvfAV6hiZnQyi1l8v5fvN28efoQZX8XL9/4inUTVlFUZCzJjFS2TkEdazEzDnD1yFnTLw2d53JQHQFgjfCF8I2wRfhByhB3CL0KBsO@@xcy2nSCIH/jL4NXt8@ce77ljveLpIkuTyEjSmTbVVFtVzkfXFdNUaGhHZFrowpCBiDmehJFcLmKeJWGkvhYx35ewPV3Z7SJ37XajhSeT@Z0ilj1SpSLNdxeSgOO6TjO5FThuaCu0KgremE@RwX9GiNSL3NZvyd8fPQ29v5ylXn1IUa98V3dps2RbnQA "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 102 bytes ``` f=0 for i in input():f=i in'123'and 9-f;print(end='〇一二三〤〥〦〧〨〩〡〢〣'[int(i)+f]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P83WgCstv0ghUyEzD4gKSks0NK3SbEFcdUMjY/XEvBQFS90064KizLwSjdS8FFv1xw3tT3Y0PNnV82RH5@OGJY8blj5uWPa4YfnjhhWPG1Y@blj4uGHR44bF6tEgHZma2mmxmv//W1qYm5maGBsZGgAA "Python 3 – Try It Online") [mypetlion](https://codegolf.stackexchange.com/users/65255/mypetlion) reminded me of a trivial golf. -4 bytes. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~181~~ 165 bytes All octal escapes can be replaced by the equivalent single-byte characters (and are counted as one byte each), but used for readability and because otherwise it breaks TIO and SE with invalid UTF-8. ``` import StdEnv u=map\c={'\343','\200',c} ?s=((!!)["〇":s++u['\244\245\246\247\250']])o digitToInt $[]=[] $[h:t]=[?(u['\241\242\243'])h:if(h-'1'<'\003')f$t] f[]=[] f[h:t]=[?["一","二","三"]h: $t] ``` [Try it online!](https://tio.run/##NY@/asMwEId3P4UiDGcTB/wvLZiILOkQ6FBIN1mDsKNYYEkhlgulFLKVQh8o9HWa56iiYjp8d7/j7huu6fdcO2Xasd8jxaV2Uh3NyaKdbR/0SzASxY91Q96gLsoCEqjzNIWkeQ/WA4mi2Sym@Of8gathPh@p35alZ@m589zX@TIFxmKDWnmQ9tlstQ1CyghlvnWV9WkdTWLmyT0FsLirpIi6BWSwgjpNC4hFaFkgJlP8mxRfL2ec4Ov311@9fGLWVchfup3l/gmCQkQhyzJg7rcRPT8MbrF9dJtXzZVspuGp51aYk7oB "Clean – Try It Online") An encoding-unaware compiler is both a blessing and a curse. [Answer] # [Red](http://www.red-lang.org), 198 171 bytes ``` func[n][s: charset"〡〢〣"forall n[n/1: either n/1 >#"0"[to-char 12272 + n/1][#"〇"]]parse n[any[[s change copy t s(pick"一二三"do(to-char t)- 12320)fail]| skip]]n] ``` [Try it online!](https://tio.run/##VYwxTsMwFIb3nOLpdWmFKmyHtE0GDsFqeYgSm1qNHMs2QyWGbAiJSwCXqLhOco8QDwhn@///ve9zsp2fZMtFpqpZvZiGG8F9Bc25dl4GHIfPcfgah29Uvau7Dgw397QCqcNZOlgyPG6QIA/9PjJAGTsyuIsXwTcL/4ZC2CjLDK/NlXMf5eZZQtPbKwTwW6ubC063Yfr5mG7v2PbbP1vY7RdjzshO1boTr@Av2gphxGydNgEUIMXsP6eFFUkpSFLKcsWkULFWEHpKX1meM7oeHtZLeToeirgRnH8B "Red – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 38 bytes ``` 9Rż“øƓ“œ%“øƈ’;-25+⁽-EỌœị@DżD<4«Ɗ‘×¥\ƊƊ ``` [Try it online!](https://tio.run/##y0rNyan8/98y6OieRw1zDu84NhlIHZ2sCuF0PGqYaa1rZKr9qHGvruvD3T1HJz/c3e3gcnSPi43JodXHuh41zDg8/dDSmGNdx7r@A42xMDczNTE2MjQAAA "Jelly – Try It Online") [Answer] # C, 131 bytes ``` f(char*n){char*s="〇〡〢〣〤〥〦〧〨〩一二三",i=0,f=0,c,d;do{c=n[i++]-48;d=n[i]-48;printf("%.3s",s+c*3+f);f=c*d&&(c|d)<4&&!f?27:0;}while(n[i]);} ``` [Try it online!](https://tio.run/##PU5LasMwEN3rFKmgRrKdIvmT2FVNDxKyCHKUGFI3RClduIbZlUIv0X97g9DryPdwJTfkwfA@8wZGjldS9r0icr3Y@TVtBtYFNvBo4MXAq4E3A@8GPgx8Gvgy8G3gpztA9/vcHZ5wWBUsVHZkWIrytpFFPauCYD5OMlE6Pajtrqr3iuDzi1jjUAfSjwNFhSqkX3oekQ8lvUo870xdR9NLJtr7dbVZEndNRdvfLKqa0AaNLNx/Iz2bJHMx@P/marnXRNNjx0FZK05ue2f3GB@TFrU9R5yjKEUpQ3luNUepCxjPEI/iOOKOEsd5Np2kTrE/ "C (gcc) – Try It Online") Explanation: First of all - I'm using char for all variables to make it short. Array `s` holds all needed Suzhou characters. The rest is pretty much iterating over the provided number, which is expressed as a string. When writing to the terminal, I'm using the input number value (so the character - 48 in ASCII), multiplied by 3, because all these characters are 3 bytes long in UTF-8. The 'string' being printed is always 3 bytes long - so one real character. Variables `c` and `d` are just 'shortcuts' to current and next input character(number). Variable `f` holds 0 or 27 - it says if the next 1/2/3 character should be shifted to alternative one - 27 is the offset between regular and alternative character in the array. `f=c*d&&(c|d)<4&&!f?27:0` - write 27 to f if c\*d != 0 and if they are both < 4 and if f isn't 0, otherwise write 0. Could be rewritten as: ``` if( c && d && c < 4 && d < 4 && f == 0) f = 27 else f = 0 ``` Maybe there are some bytes to shave off, but I'm no longer able to find anything obvious. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes ``` 9Ḷ;-26ż“/Ẉ8‘+⁽ȷc¤ṃ@ɓD_2ỊŒgÄFị"+⁽-FỌ ``` [Try it online!](https://tio.run/##y0rNyan8/9/y4Y5t1rpGZkf3PGqYo/9wV4fFo4YZ2o8a957YnnxoycOdzQ4nJ7vEGz3c3XV0UvrhFreHu7uVQNK6QFbP/4c7Nikc2qpwdI9CmMLh9kdNaxRUFNz//zdUMDRUMDJVMDVQsLQEsg0VTEECBoYWCoZGxsZGhiDKBERbWpibmYJYBgA "Jelly – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg) `-p`, ~~85~~ 61 bytes *-13 bytes thanks to Jo King* ``` s:g[(1|2|3)<((1|2|3)]=chr $/+57;tr/0..</〇〡..〩一二三/ ``` [Try it online!](https://tio.run/##K0gtyjH7/7/YKj1aw7DGqMZY00YDyoi1Tc4oUlDR1zY1ty4p0jfQ07PRf9zQ/rhhoZ7e44aVT3Y0PNnV82RHp/7//4ZchoZcRqZcpgZclpZAtiGXKUjAwNCCy9DI2NjIEESZgGhLC3MzUxDL4F9@QUlmfl7xf90CAA "Perl 6 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, 71 bytes ``` $_=gsub(/[1-3]\K[1-3]/){|x|(x.ord+9).chr}.tr"0-<","〇〡-〩一二三" ``` [Try it online!](https://tio.run/##KypNqvz/XyXeNr24NElDP9pQ1zg2xhtM6WtW11TUaFTo5RelaFtq6iVnFNXqlRQpGejaKOkoPW5of9ywUPdxw8onOxqe7Op5sqNT6f9/Qy5DQy4jUy5TAy5LSyDbkMsUJGBgaMFlaGRsbGQIokxAtKWFuZkpiGXwL7@gJDM/r/i/bgEA "Ruby – Try It Online") [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 67 bytes ``` {,/(0N 3#"〇一二三〤〥〦〧〨〩〡〢〣")x+9*<\x&x<4}@10\ ``` [Try it online!](https://tio.run/##XVFvboIwHP3OKRq2LLp/tCCbgB92gl1ATSCbOKLSBbqJMS79ZpZ4CXU4vIHxOuUerBSJsH5p8/r63u@9ju78oZ9lrjm/VRrwGWgXMqPL9EDT4yo9fDP6w2jM6I7RX0YTRveMrhndMLqVm9GNcd3pRVdRp7V4QrCX2dB0AVK1lg6AAkJn8j4eAM//xC8O8bB/DzgBTAOPDEJAMAjJK/4gYOqRt3x3cTBxCPH8oSQpnEJCiZjzy@7sK@CykWXjkdWwXccbW5E1s4JmfyGRLgLlsvjka7mfY6iG8TQCVvUqzDPEAtZhFeZhlwI2jCrMc@9P2uifdumq127iqjFE7ZrxUrSYFIKqpqnoLHhc8XJF9ZvyfV5pwalQxNdsxbnwN9qPD3rOg6eBE/FpOzHLmSvyZX8 "K (ngn/k) – Try It Online") `10\` get list of decimal digits `{` `}@` apply the following function `x&x<4` boolean (0/1) list of where the argument is less than 4 and non-zero `<\` scan with less-than. this turns runs of consecutive 1s into alternating 1s and 0s `x+9*` multiply by 9 and add `x` juxtaposition is indexing, so use this as indices in... `0N 3#"〇一二三〤〥〦〧〨〩〡〢〣"` the given string, split into a list of 3-byte strings. k is not unicode aware, so it sees only bytes `,/` concatenate [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 117 bytes ``` FromCharacterCode[12320+(IntegerDigits@#/. 0->-25//.MapIndexed[{a___,c=#2[[1]],c,b___}->{a,c,#,b}&,{0,140,9}+7648])]& ``` [Try it online!](https://tio.run/##FY5BC4IwGIb/SiBE0afbN13pwQiKwEPQfQyZc6UHNdYOgey32zw9Dw/v4R2U68ygXK/V8iqXu52Ga6es0s7Y69QagSxl9LCrRmfext76d@@@l4gkGxqfY8YJSR7qU42t@ZlWzKqua9BlxIRAKUFDE4KPz7MKHkHjtzBTwIxC4Q@nY5bLvdwuT9uPTrzIZUZABMaBh0ERHIGvgWIO4UjKcEW2sshPR74a9XL5Aw "Wolfram Language (Mathematica) – Try It Online") Note that on TIO this outputs the result in escaped form. In the normal Wolfram front end, it will look like this:[![picture of notebook interface](https://i.stack.imgur.com/KFRmf.png)](https://i.stack.imgur.com/KFRmf.png) [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 107 bytes, 81 chars ``` n=>{var t="〇一二三〤〥〦〧〨〩〡〢〣";var b=0;return n.Select(k=>t[k+(b+=k>0&k<4?1:b)%2*9]);} ``` [Try it online!](https://tio.run/##XZDfSsMwFIev26cIAyVxtWxzIpq2XgwVYYKwCy/GLtKYbaFdikk6J6OQOxF8Cf/rGwxfJ3uP2noxxMvD@X6/83Go2qWZZGWuuJiAwZ3SbIbdv5Pfy9KUUc0zofwzJpjk9B/R5@IGuzQlSoFLmU0kmYGl6yhNNKdgnvFrcEG4gErLKjUcASInCtWIM66OEzqFcyKB0vl4DLgACyjYLehzpQMudATRsu21vY6353W9A2@/QKhK1mmnV0llKfOvJNcM/hYgXC0Kx3WKjcFpLmiwqfPOT0Q@Y5LEKQvolMgoWoSlCKNlLaHDhjX365VZfz@uVw/WvFrzZs27NR/WfFrzZc2TNc/WvDRwzcdhC0umcymA8Aes/hRMwkgPkyaMm2EStbaToHvcPorRVmfncIRwUWK3KH8A "C# (.NET Core) – Try It Online") Saved 17 bytes thanks to @Jo King # Old Answer # ~~[C# (.NET Core)](https://www.microsoft.com/net/core/platform), 124 bytes, 98 chars~~ ``` n=>{var t="〇一二三〤〥〦〧〨〩〡〢〣";var b=0<1;return n.Select(k=>{b=k>0&k<4?!b:0<1;return b?t[k]:t[k+9];});} ``` [Try it online!](https://tio.run/##XZDNSsNAFIXXyVOMXUiCY2i1InaSdFFUhApCFy5KF5Nx2g5JJzgzqZUSmJ0IvoT/@gbF15m@R5y4KMXNhcv9zrmHQ@Q@yQWtCsn4BAzupaIz5G5vQS/PMkoUy7kMzimngpF/RJ/xW@SSDEsJrkQ@EXgGlq4jFVaMgHnObsAlZtyTSljVcASwmEi/RpyxfY7J1JtjAaQqxmPAOFh4nN6BPpMqZFzFnr9swRY8gIewDY/hUen7VlmrnZ4NlWc0uBZMUe/PwEf2UDquU24SnBWchBs7eHHKixkVOMloSKZYxPEiqngUL@sQKmoY/bBe6fXP03r1aPSb0e9Gfxj9afSX0d9GPxv9YvRrA9V8EjXDFhJUFYIDHgxo3ZWXWrckSuPmbhq2uztJZwtKumqYjjp27J2MUOmjskJuWf0C "C# (.NET Core) – Try It Online") Takes input in the form of a List, and returns an IEnumerable. I don't know if this input/output is ok, so just let me know if it isn't. # Explanation How this works is that it transforms all the integers to their respective Suzhou numeral form, but only if variable `b` is true. `b` is inverted whenever we meet an integer that is one, two, or three, and set to true otherwise. If `b` is false, we turn the integer to one of the vertical numerals. [Answer] # [Japt](https://github.com/ETHproductions/japt), 55 bytes ``` s"〇〡〢〣〤〥〦〧〨〩" ð"[〡〢〣]" óÈ¥YÉîë2,1Ãc £VøY ?Xd"〡一〢二〣三":X ``` [Try it online!](https://tio.run/##y0osKPn/v1jpcUP744aFjxsWPW5Y/LhhyeOGpY8blj1uWP64YcXjhpVKXIc3KEXDFcQqKRzefLjj0NLIw52Hmw@tO7zaSMfwcHMy16HFYYd3RCrYR6QADVz4ZEcDUP2TXT1ALU92dCpZRfz/H22ow2UIxEamOlymBjpclpYgPlDAFCxqYGgB5BsZGxsZgmkTMMPSwtzMFMQ0iOXSDcoFAA "Japt – Try It Online") It's worth noting that TIO gives a different byte count than my [preferred interpreter](https://ethproductions.github.io/japt/?v=1.4.6&code=cyJcdTMwMDdcdTMwMjFcdTMwMjJcdTMwMjNcdTMwMjRcdTMwMjVcdTMwMjZcdTMwMjdcdTMwMjhcdTMwMjkiCvAiW1x1MzAyMVx1MzAyMlx1MzAyM10iIPPIpVnJw67rMiwxw2MKo1b4WSA/WGQiXHUzMDIxXHU0ZTAwXHUzMDIyXHU0ZThjXHUzMDIzXHU0ZTA5IjpY&input=WzEsCjExLAoyNSwKNTAsCjk5LAoxMTEsCjUxMSwKMjAxOCwKMTIzMzIxLAoxMjM0MzIxLAo5ODc2NTQzMjEwXQotUm0=), but I see no reason not to trust the one that gives me a lower score. Explanation: ``` Step 1: s"〇〡〢〣〤〥〦〧〨〩" Convert the input number to a string using these characters for digits Step 2: ð Find all indexes which match this regex: "[〡〢〣]" A 1, 2, or 3 character ó à Split the list between: È¥YÉ Non-consecutive numbers ® à For each group of consecutive [1,2,3] characters: ë2,1 Get every-other one starting with the second c Flatten Step 3: £ For each character from step 1: VøY Check if its index is in the list from step 2 ? If it is: Xd"〡一〢二〣三" Replace it with the horizontal version :X Otherwise leave it as-is ``` [Answer] # [R](https://www.r-project.org/), 104 bytes ``` function(x,`[`=chartr)"a-jBCD"["〇〡-〩一二三",gsub("[bcd]\\K([bcd])","\\U\\1","0-9"["a-j",x],,T)] ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQichOsE2OSOxqKRIUylRN8vJ2UUpWulxQ/vjhoW6jxtWPtnR8GRXz5MdnUo66cWlSRpK0UnJKbExMd4aYIamko5STExoTIwhkGGgawnUCzRESaciVkcnRDP2f5qGuqG6prICHACN5QIJoogCBYH2gMSNTFHFFz1uWAoSNzVAFV8KdCFI3NISVXwlEEHMR7YAYj7UalM0qaVIthsYWiDkwLaDwuFxwwqwmUbGxkZwvSBdu3oeNywGhg1QJdQEoBoThCK4mscNS0AqQWywGywtzM1MQQrB3gI7e8XjhuWPG5aB3YNQDHTAfwA "R – Try It Online") An alternative approach in R. Makes use of some Perl-style Regex features (the last `T` param in substitution function stands for `perl=TRUE`). First, we translate numerals to alphabetic characters `a-j`, then use Regex substitution to convert duplicate occurrences of `bcd` (formerly `123`) to uppercase, and finally translate characters to Suzhou numerals with different handling of lowercase and uppercase letters. Credit to J.Doe for the preparation of test cases, as these were taken from [his answer](https://codegolf.stackexchange.com/a/177544/78274). [Answer] # C#, 153 bytes ``` n=>Regex.Replace(n+"",@"[4-90]|[1-3]{1,2}",x=>"〇〡〢〣〤〥〦〧〨〩"[x.Value[0]-'0']+""+(x.Value.Length>1?"一二三"[x.Value[1]-'0'-1]+"":"")) ``` [Try it online!](https://tio.run/##hVDPToMwHL7zFE0vgwgE2KbiHGqMnmZi1OiBcGiwIgkrpAWDmUt6Mya@hP/1DRZfp3sPhDHdLrLv0OT3/enva32m@THFRcZCEoDTW5biYU9anvQznKf6CQ6yCNGDPKGYsTAmrCcRNMQsQT4G@@UcR3gvSUxpJIESfoQYA8c0Digazpiar8BSlIY@uInDS3CEQiKzlJb7XA8gGjDlz7dIVDjMiL8dxSRQQe13wFVJgX5B@k5ZD@dlySQq68hkDUJ1F7odzTa8O9fU2t7IVK0xVPO@AwW/F/xJ8GfBXwR/FfxN8HfBPwT/FPwLurl@jqIMu4antYyWV961Js85fYBJkF475g6cTvj0@3E6eVgEzFlAM6vIFoSKUvSW@ku/v6Rf0DDFg5BguXqAbCpK73@xUbW6TWrXaFJtu3lvcy2r3bZWOTorLPbmxnq3MtU95xhL9TmWih8) ]
[Question] [ We've recently reached the threshold of 10,000 questions on PPCG. Hooray! Let's celebrate this with a simple challenge. ## Input Two integers \$A\$ and \$B\$, both in \$[1..9999]\$, such that \$A+B<10000\$. ## Task Your task is to add one single digit to one of these integers or one single digit to both of them such that \$A+B=10000\$. If adding a digit to both \$A\$ and \$B\$, it need not necessarily be the same digit. The new digit can be added at the beginning, at the end or anywhere in the middle of the original integer. However, you can't add a leading zero. *Example:* For \$A=923\$, the following transformations are valid: $$\color{red}1923\\92\color{red}73\\923\color{red}8$$ But these ones are **invalid**: $$\color{red}{0}923\\\color{red}{10}923\\9\color{red}{4}2\color{red}{7}3$$ Given \$A=923\$ and \$B=72\$, there are two possible solutions: $$923\color{red}8 + 7\color{red}62 = 10000\\92\color{red}73 + 72\color{red}7 = 10000$$ ## Output You must print or output a list of all possible solutions. For the above example, the expected output would be `[[9238,762],[9273,727]]`. ## Rules * I/O can be processed in any reasonable, unambiguous format. You may use strings, lists of digits, etc. instead of integers. * The input is guaranteed to have at least one solution. * You are allowed not to deduplicate the output. However, it would be appreciated if the test code is deduplicating it with some post-processing, for instance in the *footer* section of TIO. * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge. ## Test cases ``` Input --> Output 934, 654 --> [[9346,654]] 737, 628 --> [[7372,2628]] 9122, 88 --> [[9122,878]] 923, 72 --> [[9238,762],[9273,727]] 998, 3 --> [[9968,32],[9987,13]] 900, 10 --> [[9900,100],[9090,910]] NB: solutions such as [9000,1000] are NOT valid (more than one digit added to 10) 363, 632 --> [[3673,6327],[3638,6362]] 288, 711 --> [[2881,7119],[2882,7118],[2883,7117],[2884,7116],[2885,7115],[2886,7114], [2887,7113],[2888,7112],[2889,7111]] 365, 635 --> [[365,9635],[1365,8635],[2365,7635],[3365,6635],[4365,5635],[5365,4635], [6365,3635],[7365,2635],[8365,1635],[9365,635],[3065,6935],[3165,6835], [3265,6735],[3465,6535],[3565,6435],[3665,6335],[3765,6235],[3865,6135], [3965,6035],[3605,6395],[3615,6385],[3625,6375],[3635,6365],[3645,6355], [3655,6345],[3675,6325],[3685,6315],[3695,6305],[3650,6350]] ``` [Answer] # [Haskell](https://www.haskell.org/), ~~99 97 82~~ 81 bytes -16 bytes thanks to [Delfad0r](https://codegolf.stackexchange.com/users/82619/delfad0r?tab=profile) (taking inputs as a list, using abusing that we don't need to deduplicate -> n can always be in *[0,4]* & using a clever combination of input-format and `ap`)! ``` filter((==1e4).sum).mapM([read.(take n<>(c:).drop n)|c<-['0'..'9'],n<-[0..4]]<*>) ``` [Try it online!](https://tio.run/##TVBBbtswELzrFQOhgKTEImIpsWVD8iUF2kN6ylElAlpa2UIoUiCpugH69rrrnEoSuzPAzmCHZ@XfSevrOM3WBXxVQYmX0Qd8nhRmOSID8hzW6A8Yop56DNaB@zLrsVNhtCb6X/9K03hydplZn9aHjA1YPxpWX8jhFznPEg874Nv3Z4Tz6MHP2MATHXmv3EcUsYR@q2nWhE5pvceAto235TaWK7TxpqhiKWU0oMHP6zDqQC5Nm2ZNj5nwy5SJSc0/0taR6kUa1DvB1Ie022eid3aGyf50dd4mD4kQyS6RK8PsQYhHKeu7Q3adFC/c4GbyhnRewmtwLwYCJ8vlYl3vMwZ6NOTR1DVOFJ6tCWSCx@VMjiLcZlu1Oko2Uri/R8J3j@MNxsgPXBj5s70gvX30l8@MSq7ao5TZlbOCY0a7dVGg4l6U2BbRblehjMpNiU1ZREVVYbteM39i/vS3G7Q6@WvezfM/ "Haskell – Try It Online") [Answer] # [R](https://www.r-project.org/), 96 bytes ``` function(a,b)(w<-grep(gsub("",".?",a?b),1:1e4?9999:0)?r<-1e4-w)[w+a<2&r+b<2] "?"=paste "+"=adist ``` [Try it online!](https://tio.run/##JcrJDoMgFAXQPV9BWDQQsWFwwmD4kKYLaK26scYhfj592Lc69963xhHbPH6O@bVP35l6Hhg9bT6s/UKH7QiUEE7ujnDvAuOylX3hDFwrmFttDjE/2ePMvFW3NQtWPRFxpFv8tveIZKTz72nbIxqpEYJjKRgCSyBkcBqU5rhWDFgr6JW@foxpONaphRlCktEFx1VZJKsG9lrK66Mqodfl3zpZsfgD "R – Try It Online") ## Explanation (ungolfed) ``` function(a,b){ # Regex inserting ".*": (998,3) => ".?9.?9.?8.? .?3.?" regex <- gsub("",".?",paste(a,b)) # Positions matching in the whole vector of strings that add to 10K ("1 9999", "2 9998", "3 9997", "4 9996", ...) w <- grep(regex,paste(1:1e4,9999:0)) # 10K minus these matching positions r <- 1e4-w # Form position-string vector of ('pos1 10K-pos1', 'pos2 10K-pos2', ...) paste(w,r)[ # Filter only those positions where the edit distance between the matched numbers and the originals are less than 2 adist(w,a)<2 & adist(r,b)<2 ] } ``` We assign `?` to `paste`. That lets us do something cool: `a<-b?c<-d` does inline assignments within the `paste` call, which we couldn't do with any other operator than `?`, since it has [lower precedence](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Syntax.html) than `<-`. Now as @JoKing kindly pointed out, there can be cases like `900 10` where two insertions could take place such as `9100 8100`. So we filter out matches where the number of characters in either number has increased by more than 1. The quick way to do this is with the [Levenshtein edit distance](https://en.wikipedia.org/wiki/Levenshtein_distance) `adist` which we bind to `+`. [Answer] # Pyth, ~~28~~ ~~27~~ ~~25~~ ~~24~~ ~~22~~ 20 bytes ``` fq^;4sT*FmvsmXLkdThl ``` Try it online [here](https://pyth.herokuapp.com/?code=fq%5E%3B4sT%2AFmvsmXLkdThl&input=%5B%22998%22%2C%20%223%22%5D&debug=0), or verify all the test cases [here](https://pyth.herokuapp.com/?code=%7Bfq%5E%3B4sT%2aFmvsmXLkdThl&test_suite=1&test_suite_input=%5B%22934%22%2C+%22654%22%5D%0A%5B%22737%22%2C+%22628%22%5D%0A%5B%229122%22%2C+%2288%22%5D%0A%5B%22923%22%2C+%2272%22%5D%0A%5B%22998%22%2C+%223%22%5D%0A%5B%22363%22%2C+%22632%22%5D%0A%5B%22288%22%2C+%22711%22%5D%0A%5B%22365%22%2C+%22635%22%5D&debug=0) - the test suite deduplicates the result by prepending a `{`. Input is as a list of strings. ``` fq^;4sT*FmvsmXLkdThldQ Implicit: Q=eval(input()), T=10 Trailing d, Q inferred m Q Map each input string, as d, using: ld Take the length of d m h Map 0 to the above (inclusive), as k, using: X d Insert into d... k ... at position k... L T ... each number [0-9] s Flatten the result v Convert each back to an integer *F Take the cartesian product of the result (this generates all possible pairs of mutated numbers) f Keep the pairs, as T, where... sT ... the sum of the pair... q ... is equal to... ^;4 ... 10,000 (; == 10 here, so this is 10^4) ``` *Edit 4: Saved another 2 bytes, thanks to Mr Xcoder - `v` vectorises by default, and `L` uses `m` underneath, so mapping over range is implied, making the `U` unneccesary too* *Edit 3: Introduced to global use of `;` operator to retain access to 10 to save 2 bytes, thanks to FryAmTheEggman and issacg:* ``` fq^T4sT*FmvMsmXLkdUThl ``` *Edit 2: I forgot the sum operator exists, how embarassing...* *Edit 1: Previous version accepted a list of integers as input, performing string conversions manually, for 27 bytes:* ``` fq10000+FT*FmvMsmXLk`dUThl` ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 64 bytes ``` ->\a{grep {all (a Z~$_)X~~/^(.*)(.*)$0.?$1$/},(^1e4 Z(1e4...1))} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtf1y4msTq9KLVAoToxJ0dBI1Ehqk4lXjOirk4/TkNPSxOEVQz07FUMVfRrdTTiDFNNFKI0gKSenp6hpmbt/@LESoU0jWhLYxMdBTNTk1hN6/8A "Perl 6 – Try It Online") This is a port of [G B's answer](https://codegolf.stackexchange.com/a/173097/76162) using a regex to check if the numbers are valid. Thanks to **nwellnhof** for porting it. ## Old answer, ~~127 110~~, 88 bytes *-22 bytes thanks to nwellnhof!* ``` ->\a{grep {all ~<<a Z∈.map:{.comb.combinations(.comb-1..*)>>.join}},(^1e4 Z(1e4...1))} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtf1y4msTq9KLVAoToxJ0ehzsYmUSHqUUeHXm5igVW1XnJ@bhKYyMxLLMnMzyvWAPN0DfX0tDTt7PSy8jPzamt1NOIMU00UojSApJ6enqGmZu3/4sRKhTSNaEtjEx0FM1OTWE3r/wA "Perl 6 – Try It Online") Anonymous code block that takes in a list of two numbers and returns a list of pairs of numbers. Rather than fiddle about with inserting the digits in, this solution checks every combination of numbers that sum to 10000 and filters that the given numbers are part of the pair. ### Explanation: ``` ->\a{ # Anonymous code block that takes an argument a grep ... ,(^1e4 Z(1e4...1)) # Filter from all pairs that add to 10000 { ~<<a # Stringify the contents of a .map:{ # Map the pair to .comb # The digits of the number .combinations(.comb-1..*) # The combinations of the digits >>.join # Each combination joined # Note that combinations preserve order # "123" -> (12,13,123) } all Z∈ # Zip that each element of a is an element of the combination } } ``` [Answer] # [R](https://www.r-project.org/), ~~179 161 150~~ 144 bytes ``` function(a,b,w=g(a),r=rep(g(b),e=1e4))paste(w,r)[w+r==1e4] g=function(x,n=sum(x|1)){for(i in 0:n)for(j in 0:9)F=c(F,append(x,j,i)%*%10^(n:0));F} ``` [Try it online!](https://tio.run/##TY7LasMwEEX3/orpIjDTTsCqkzaPauufCCnIsuwoNIpQ/Aik@XZXdkPp7t7DvXDCUMHHfKhapxt7dqi44F7WqIiDDMZjjQWxkcIsiLy6NAZ7DrTrX4Ic4T6p5d/5yk5e2hNevwXRrToHtGAdpBtHYzn@ljXlUmPOynvjyng6sqXZ80ykn@g2KdE2vw@HaAX/rKAguEE30VGSttDtnsrWf1mtGlNiR3u4J8kBNa454wUxaHzjZUw00Vde8Wqi7yxYPGjGcfPYZjHR8AM "R – Try It Online") 35 bytes saved by @JayCe and @Giuseppe. ### Explanation Helper function g gets all possible insertions. ``` g <- function(x, # Input vector of digits n=sum(x|1) # Length of x ) { for(i in 0:n) # i is the insertion point for(j in 0:9) # j is a digit from 0 to 9 # Dot product of vector of digits with insert and 10^(n:0) performs the # conversion to integer (and gets rid of the leading 0s) F=c(F,append(x,j,i)%*%10^(n:0)) # F is a non-reserved built-in alias to FALSE (numerically 0) F } ``` Main function. ``` f <- function(a, # Input vectors of digits b, w=g(a), # Get all possible insertions for a r=rep(g(b),e=1e4) # Insertions for b replicated 1e4 times each ) paste(w,r)[w+r==1e4] # paste and w+r recycle w to match length of r # Lots of duplication! ``` I've noticed after the fact that this is essentially the same logic as the [Pyth](https://codegolf.stackexchange.com/a/172987/79980) answer. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~93~~ 91 bytes ``` ->a,b{(1..r=10000).map{|x|/^(.*)(.*:)\1.?\2(.*)(.*):\3.?\4$/=~[a,x,b,y=r-x]*?:&&[x,y]}-[p]} ``` [Try it online!](https://tio.run/##LcfRCsIgGIbh866igxhz/Dp11pZguxA10IOdBSIEyrZu3aT2wQfvE98@l0UV/HDg15YREhWjdYi8XFi3tPXPlnSoXiLDyGz4QSTNUCkuvfpoBwk8ZBVxst0sm0YnyHbHOti9hPOi73yAkdvTrwcBt6s4QCkw@m8@TTAyZssX "Ruby – Try It Online") Try every single number up to 10000, and use the regex to check if the numbers match. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 30 bytes ``` DµJṬ€k€jþ9ݤ;9R¤;€$ḌF)ŒpS=ȷ4ƊƇ ``` [Try it online!](https://tio.run/##y0rNyan8/9/l0FavhzvXPGpakw3EWYf3WR7dfWiJtWUQkAAKqDzc0eOmeXRSQbDtie0mx7qOtf///9/c2FzHzMgCAA "Jelly – Try It Online") Kind of clumsy because Jelly has no insertion. # Explanation ``` Given [a, b]. Dµ ) Get [digits(a), digits(b)] then map: JṬ€k€jþ9ݤ;9R¤;€$ḌF Generate all the insertions. Œp Cartesian product: get all pairs. S=ȷ4ƊƇ Filter for: sum equal to ȷ4 (10000). Given e.g. [6,3,5]: J Get [1,2,3]. Ṭ€ Get [[1], [0,1], [0,0,1]]. k€ Split input with these: gets us [[6],[3,5]] , [[6,3],[5]] , [[6,3,5],[]] jþ9ݤ Join table-wise with [0..9] → [[[6,0,3,5], [6,3,0,5], [6,3,5,0]], [[6,1,3,5], [6,3,1,6], [6,3,5,1]], …] ;9R¤;€$ Append the prefixings of the input by [1..9]. [[1,6,3,5], [2,6,3,5], [3,6,3,5]]… ḌF Undigits all, and flatten. ``` [Answer] # Python 3, ~~165 160 153 125~~ 117 bytes * Saved 5 bytes thanks to @JackBrounstein suggestion to remove `set` from the return value, as the output can contain duplicates. * Saved 7 by replacing `range(len(s))` with `range(5)`. * Saved 23 bytes thanks to @Eric Duminil's suggestion to replace `itertools` with nested list comprehensions (and removing a space). * Saved 8 thanks to @Jo King's suggestion to replace nested list comprehension with a single loop and modulus operator. ~~Using `itertools` and a simple helper function.~~ Accepts strings as input, returns a set of ints as output. ``` c=lambda s:[int(s[:i%5]+str(i//5)+s[i%5:])for i in range(50)] lambda a,b:{(i,j)for i in c(a)for j in c(b)if i+j==1e4} ``` [Answer] # PHP, ~~162~~ 159 bytes lovely example for a generator function! ``` function f($n){for($n+=.1;$n>=1;$n/=10)for($d=-1;$d++<9;)yield strtr($n,".",$d)/10|0;}foreach(f($argv[1])as$x)foreach(f($argv[2])as$y)$x+$y-1e4||print"$x+$y\n"; ``` takes input from command line arguments; prints duplicates. Run with `-nr '<code>` or [try it online](http://sandbox.onlinephpfunctions.com/code/0f1dd364e7171aa81b9c1d0c87dabe2c7d2f96a1). [Answer] # Pyth, 18 bytes ``` fqsT^;4*FsMvXLRRTT ``` [Demonstration](http://pyth.herokuapp.com/?code=fqsT%5E%3B4%2aFsMvXLRRTT&input=%22934%22%2C%22654%22&test_suite_input=%5B%22934%22%2C+%22654%22%5D%0A%5B%22737%22%2C+%22628%22%5D%0A%5B%229122%22%2C+%2288%22%5D%0A%5B%22923%22%2C+%2272%22%5D%0A%5B%22998%22%2C+%223%22%5D%0A%5B%22900%22%2C%2210%22%5D%0A%5B%22363%22%2C+%22632%22%5D%0A%5B%22288%22%2C+%22711%22%5D%0A%5B%22365%22%2C+%22635%22%5D&debug=0), [test suite](http://pyth.herokuapp.com/?code=%7BfqsT%5E%3B4%2aFsMvXLRRTT&input=%22934%22%2C%22654%22&test_suite=1&test_suite_input=%5B%22934%22%2C+%22654%22%5D%0A%5B%22737%22%2C+%22628%22%5D%0A%5B%229122%22%2C+%2288%22%5D%0A%5B%22923%22%2C+%2272%22%5D%0A%5B%22998%22%2C+%223%22%5D%0A%5B%22900%22%2C%2210%22%5D%0A%5B%22363%22%2C+%22632%22%5D%0A%5B%22288%22%2C+%22711%22%5D%0A%5B%22365%22%2C+%22635%22%5D&debug=0) (test suite is deduplicated with leading `{`). The input is in the form of a list of two strings. `XLRRTT`: L and R perform nested maps. Since there are 3 of them, we will perform a triply nested map of the `X` function. In this case, the `X` function will insert a character at a designated position into a string. The string is the input, which is implicit and placed by the first `R`. The character ranges over `0 ... 9`, so we have all possible inserted digits, and is placed by the `L`. The range is given by `T`, which is implicitly set to `10`, which is implicitly treated as `[0 ... 9]`. The position ranges over `0 ... 9`, which is sufficient, because inserting a number after the 10th position will never be useful. Duplicate results are fine. The range is placed by the second `R`, and given by the second `T`. `v`: Nested cast strings to ints. `sM`: Flatten the second level of lists, leaving us with a list of all possible numbers after digit insertion, for each of the input numbers. `*F`: Take the Cartesian product of the two lists of possible numbers. `fqsT^;4`: Filter on the pairs whose product is `10000`. `;` takes the value of `10` here, as `T` is in use as the filter variable, and `;` always as the value of the variable which is in use. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~30~~ ~~29~~ ~~25~~ 23 bytes Takes input as an array of strings, outputs an array of arrays of strings. ``` £L²ôs f_à øX rï k@L²aXx ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=o0yy9HMgZl/gIPhYCnLvIGtATLJhWHg=&input=WyI5MjMiLCI3MiJdCi1R) --- ## Explanation ``` £L²ôs f_à øX £ :Map each X L : 100 ² : Squared ô : Range [0,L²] s : Convert each to a string f_ : Remove elements that return false à : All combinations of current element øX : Contains X? rï k@L²aXx r :Reduce by ï : Cartesian product k@ :Remove each X that returns true (not 0) L² : 100 squared a : Absolute difference with Xx : X reduced by addition ``` [Answer] # Javascript (Node) - 183 136 123 Bytes **123 Bytes thanks to Shaggy** ``` a=>b=>(o={},g=(s,h)=>[...s+0].map((y,x)=>{for(y=10;y--;)h(s.slice(0,x)+y+s.slice(x))}))(a,x=>g(b,y=>1e4-x-y?0:o[+x]=+y))&&o ``` **136 Bytes thanks to Arnauld** ``` e=(h,c,i=h.length+1,j)=>{for(;i--;)for(j=10;j--;)c(h.slice(0,i)+j+h.slice(i))} f=(a,b,c=[])=>e(a,n=>e(b,m=>1E4-n-m||c.push([+n,+m])))||c ``` **Old Code** Not proud of it, but figured I'd submit anyways. Creates a string prototype function akin to map which takes up the bulk of the bytes. Function just iterates through both permutations, and finds when 1000-a-b is 0. Takes input as strings. ``` String.prototype.e=function(c){let h=this,L=h.length,i,j;for(i=0;i<=L;i++)for(j=0;j<=9;j++)c(h.slice(0,i)+j+h.slice(i,L));} f=(a,b,c=[])=>a.e(n=>b.e(m=>1E4-n-m?c:c.push([+n,+m])))?c:c ``` [Try it online!](https://tio.run/##bcyxboMwEIDhPU8RebJlYwVDIZSYTt3YOkYZwDHYlrEROJWqqs9OIVKXiul0/6c703w2s5j0GKK2aaWNnL/LZfkIk3Y9HScffPgaJZW8ezgRtHdQoG8rw1HxoPRMaq6ola4Pimhiys5PUPNTqS@8LjXGaAtmDebCi9KsQUBFZ6uFhCeiETb4b9WkRqj8OXQcNqQlgl9viFcNldDxql3HwKv4PY1cNLyJV0HHx6zgFTuChxtCaGuL8G72VlLre9hBUCQpICB7ScH6@fAP8yQH5Agydt7TImZs4/O@smTDnO1hkj0xS3aVrR@30zh@6vIL) **Ungolfed** ``` String.prototype.e=function(c) { let h=this,L=h.length,i,j; for(i=0;i<=L;i++) for(j=0;j<=9;j++) c(h.slice(0,i)+j+h.slice(i,L)); } f=(a, b, c=[]) => a.e(n => b.e(m => 1E4-n-m ? c : c.push([+n,+m]) ) ) ? c : c ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` œcL’$$€ċ"⁹o⁼"Ạ ȷ4ḶṚĖDçƇ ``` A monadic link accepting a list of lists of digits (e.g. for the example of 923 and 72 the input is `[[9,2,3],[7,2]]`) **[Try it online!](https://tio.run/##AUIAvf9qZWxsef//xZNjTOKAmSQk4oKsxIsi4oG5b@KBvCLhuqAKyLc04bi24bmaxJZEw6fGh/9Ew4fhuIz//zkyMywgNzI "Jelly – Try It Online")** (footer makes it so I/O is a pair of two integers in and a [formatted] list of pairs of integers out) Or see the [test-suite](https://tio.run/##y0rNyan8///o5GSfRw0zVVQeNa050q30qHFn/qPGPUoPdy3gOrHd5OGObQ93zjoyzeXw8mPt/4/ucTnc/nBHz7EuoOKjkx7unAGkgSgLRDXMUdC1U3jUMDfrUeO@Q9sObfv/Pzra0thER8HM1CSWSyfa3NgcyDayALEtDY2MdBQsIGwjYx0FcyMw09JCR8EYxDI2AwqaGYNFjSyAouaGhhBxU5C4aWwsAA "Jelly – Try It Online"). ### How? Checks all the pairs of "numbers" (lists of digits) which sum to 10000 for validity by forming all ways to choose n-1 digits from those "numbers" maintaining order; and keeps those which are valid (where validity also allows for the "number" under test to be equal to the original "number"). ``` œcL’$$€ċ"⁹o⁼"Ạ - Link 1, is piar valid?: pairToCheck, originalInputPair € - for each list of digits in pairToCheck: e.g. [9,2,3] $ - last two links as a monad: $ - last two links as a monad: L - length 3 ’ - decremented 2 œc - choices of that many items [[9,2],[9,3],[2,3]] ⁹ - chain's right argument (originalInputPair) " - zip with: (i.e. apply the following f(x,y) *respectively* across the results above and the originalInputPair) ċ - count occurrences " - zip with (this time with an implicit right argument of originalInputPair) ⁼ - equal (non-vectorising version) o - locgical OR (vectorising version) i.e. we now have: [OR(isOneDigitLonger(item1),isEqual(item1)), OR(isOneDigitLonger(item2),isEqual(item2))] Ạ - all? ȷ4ḶṚĖDçƇ - Main Link: list (pair) of lists of digits ȷ4 - literal 10^4 -> 10000 Ḷ - lowered range -> [0,1,2,...,9998,9999] Ṛ - reversed -> [9999,9998,...,2,1,0] Ė - enumerate -> [[1,9999],[2,9998],...,[9998,2],[9999,1],[10000,0]] (N.B. last is redundant, but this does not matter) D - to decimals -> [[[1],[9,9,9,9]],[[2],[9,9,9,8]],...,[[9,9,9,8],[2]],[[9,9,9,9],[1]],[[1,0,0,0,0],[0]]] Ƈ - filter keep those for which this is truthy: ç - call last link as a dyad (with a right argument of the pair of lists of digits) ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 24 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ⌐çΘ♠╖øû°-h∟ñµ%üw▲∞Ç╫[½π= ``` [Run and debug it](https://staxlang.xyz/#p=a987e906b70096f82d681ca4e62581771eec80d75babe33d&i=[%22934%22,+%22654%22]%0A[%22737%22,+%22628%22]%0A[%229122%22,+%2288%22]%0A[%22923%22,+%2272%22]%0A[%22998%22,+%223%22]%0A[%22363%22,+%22632%22]%0A[%22288%22,+%22711%22]%0A[%22365%22,+%22635%22]&a=1&m=2) Those program takes its two inputs as an array of strings, like this. ``` ["934", "654"] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` ΦE×χφI⟦ι⁻×χφι⟧⌊Eι№E⊕LλΦλ⁻ξρ§⟦θη⟧μ ``` [Try it online!](https://tio.run/##ZY0xC8IwEIV3f0XGC0RI6yDiJIVCwYKDW@kQ0sMcJKmmqfTfx6bo5G2P773vtFFBj8qmdAvkI9RkIwZo1RPu5HCCQgpWSCm5YJWaInQkWEt@nv458Z7zjZKb3eZYy9U4r94cGq8DOvQRB7iif0QDNg@@P@1PvAgWeAaX2PgBF@hegpleMMfznVM6lYfdsUz7t/0A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` χ 10 φ 1000 × Multiply E Map over implicit range ι ι Current value ⁻×χφ Subtract from 10000 ⟦ ⟧ Pair of values I Cast to string Φ Filter ι Current pair E Map λ Current value L Length ⊕ Increment E Map over implicit range λ Current value Φ Filter over characters ξ Range value ρ Character index ⁻ Subtract ⟦θη⟧ Original inputs as a list μ Index of current value § Get input at that index № Count matching values ⌊ Minimum Implicitly print each pair double-spaced ``` In case you didn't understand that, it runs through all the pairs of values that add to 10000 (as strings), then counts how many times each input matches against the result of deleting up to 1 character from the respective value. If the minimum count is nonzero then both inputs matched and this is a possible solution. [Answer] # [Ruby](https://www.ruby-lang.org/), 110 bytes Accepts strings as input, returns an array of array of integers. Based on the [python](https://codegolf.stackexchange.com/a/173002/65905) version. For a given integer, `C` creates an array of numbers that can be created by adding a digit. The lambda iterates over every possible pair and selects the one whose sum is 10000. ``` C=->n{(0..49).map{|i|([n[0...i%5],i/5,n[i%5..-1]]*'').to_i}} ->(a,b){C[a].product(C[b]).select{|i,j|i+j==1e4}} ``` [Try it online!](https://tio.run/##VcoxDoIwGEDh3VOwmLZaflstCkNZOEbTGEBISrQgwmCgZ68QXdxevrx@LN6@lj5McU4LMmUq19D17W0sB5ypQhN4VfeqHKbZ0GY2@0ZKXgnnNpkMUzthBiASAo@8W44ZK6sWAbONNDWHiFq1JEDItd4hRGBor8Y53wW1QslJIBqgcySQhtGa5@bLjK3M2Z8e43jVC@c/9h8 "Ruby – Try It Online") [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 0ìε.œʒg3‹}εU9ÝεXDgiìësý}}}˜}`âʒOT4mQ ``` Can without a doubt be golfed substantially.. Especially inserting the digits, including a leading/trailing one. [Try it online](https://tio.run/##AUoAtf8wNWFiMWX//zDDrM61LsWTypJnM@KAuX3OtVU5w53OtVhEZ2nDrMOrc8O9fX19y5x9YMOiypJPVDRtUf99w6r/WzI4OCwgNzExXQ) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeV/g8Nrzm3VOzr51KR040cNO2vPbQ21PDz33NYIl/TMw2sOry4@vLe2tvb0nNqEw4tOTfIPMckN/F97eJXOoW32/6OjLY1NdMxMTWJ1FKLNjc11zIwsQExLQyMjHQsI08hYx9wIzLK00DEGMwwMdAwNQCxjM2MdM2OwrJGFhY65oSFE1BQoahobCwA) (`ê` in the footer is to Uniquify & Sort). **Explanation:** ``` 0ì # Prepend a 0 before each of the input numbers ε } # Map each to: .œ # Take all possible partitions ʒg3‹} # Only keep those of length 1 or 2 ε } # Map each partition to: U # Pop and store the partition in variable `X` 9Ý # List in the range [0, 9] ε } # Map each of those digits to: X # Get the variable `X` Dgi # If it's a single number (length == 1): ì # Prepend `X` before this digit ë # Else (length == 2): sý # Join both numbers in `X` with the current digit } # Close the if-else ˜ # Flatten the list of lists ` # Now push both lists to the stack â # Create all possible pairs (cartesian product) ʒ # Filter this list of pairs by: O # Take the sum of the two numbers T4m # Push 10000 (10^4) Q # And check if they are equal ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 43 bytes ``` ⌐ƛ⟨⟩n£¥Lʀ(x|n¬₀r(¥CC←x nSṀṅIJ));ḣhẊ'∑k2= ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%8C%90%C6%9B%E2%9F%A8%E2%9F%A9n%C2%A3%C2%A5L%CA%80%28x%7Cn%C2%AC%E2%82%80r%28%C2%A5CC%E2%86%90x%20nS%E1%B9%80%E1%B9%85IJ%29%29%3B%E1%B8%A3h%E1%BA%8A%27%E2%88%91k2%3D%20%20%20&inputs=%22288%2C711%22&header=&footer=%3BU) Takes input of the form: `"a,b"` **Explanation:** ``` ?⌐ƛ⟨⟩n£¥Lʀ(x|n¬₀r(¥CC←x nSṀṅIJ));ḣhẊ'∑k2= # full program ?⌐ # split implicit input on "," ƛ⟨⟩n£¥Lʀ(x|n¬₀r(¥CC←x nSṀṅIJ)); # "insert" lambda map over input ḣh # unlist them Ẋ # cartesian product [a,b]*[c,d]=[[a,c],[a,d],[b,c],[b,d]] '∑k2 # filter lambda, sum of pair == 10000 ``` The insert lambda can definitely be improved, but I am having trouble figuring out a way to map it instead of explicitly loop over it. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes ``` LŻœṖ€z⁶ZjþØDVẎṢḊ)p/S⁼ȷ4ƊƇ ``` [Try it online!](https://tio.run/##AUIAvf9qZWxsef//TMW7xZPhuZbigqx64oG2WmrDvsOYRFbhuo7huaLhuIopcC9T4oG8yLc0xorGh/9Ew4f//zkyMywgNzI "Jelly – Try It Online") Not the shortest Jelly solution here but maybe someone can golf this? I am stumped ]
[Question] [ Given a string of the characters `+=-` where there is at least one `=`, insert positive integers between all the symbols and at the start and the end such that the math equations are satisfied. For example, given the input ``` +-=-= ``` you need to insert positive integers A through F like this ``` A+B-C=D-E=F ``` such that the equations are all satisfied, i.e. `A + B - C` and `D - E` and `F` are all the same number. There are many possible ways to do this since, as long as the equations work out, any set of positive integers may be used. Each line here is a possible valid output to input `+-=-=`: ``` 2+3-4=6-5=1 1+1-1=2-1=1 4+2-4=4-2=2 100+1-10=182-91=91 89+231-77=1024-781=243 ``` Note that the value of the expressions is not required to be a positive integer like the inserted numbers are. For example, given input `-=-` the outputs `1-10=8-17` (evals to -9) and `10-1=17-8` (evals to 9) are both equally valid. Of course for some inputs such as `=` it's impossible to have a negative as the expression since only positive numbers like `5=5` can be inserted. Note also that zero is not a positive integer. **The shortest code in bytes wins.** You may output the numbers as a list instead of inserting them directly into the string. If you do output the string there may be spaces separating symbols and numbers. So, for input `+-=-=`, outputting ``` 2, 3, 4, 6, 5, 1 ``` or ``` 2 + 3 - 4 = 6 - 5 = 1 ``` is equivalent to outputting ``` 2+3-4=6-5=1 ``` ## Test Cases ``` Input | One Possible Output = | 1=1 == | 2=2=2 += | 1+3=4 =+ | 2=1+1 -= | 30-10=20 =- | 1=2-1 =-= | 3=7-4=3 =+= | 2=1+1=2 === | 100=100=100=100 +=- | 3+2=7-2 -=+ | 7-2=3+2 +=+ | 3+3=3+3 -=- | 1-10=8-17 --= | 60-1-1=58 ++= | 60+1+1=62 -+= | 60-9+1=52 +-= | 60+9-1=68 +-=-= | 2+3-4=6-5=1 --=-- | 2-1-1=2-1-1 ==-== | 47=47=50-3=47=47 =++=+-=-+=--= | 3=1+1+1=3+1-1=1-1+3=5-1-1=3 +--++-=-+-+- | 35+10-16-29+20+107-1000=5-4+3-2+1-876 ====== | 8=8=8=8=8=8=8 ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 58 bytes ``` [-+] $&1 \B((\+1)|(-1))* $._$*1$#3$*1$#2$*_$& +`1_ 1+ $.& ``` [Try it online!](https://tio.run/nexus/retina#PUxJDsIwDLz7G4QozchIgbMvXHgERelD@HuZcVHVemLPdm2vbX87PlbqsPXZ2oqxfJuPZelWbrP0US6PxHvps1TDNqbZANW672ERBiLMic5fh2jxThZ8pXKnBmrOgecQyTpzXJWklzeTqTvy4qfC7JQDSYf0kEUjWlYdKuEWpxnJH9VQMv55Pyddx/YD) Alternative solution at the same byte count: ``` ((\+)|(-))* $._$*1$#3$*1$#2$*_$& +`1_ ([+-])1* $+1 1+ $.& ``` [Try it online!](https://tio.run/nexus/retina#PUxJDsIwDLz7G4QqychIgbPPPAJQ@hD@HmZcVLV2ZvW1PvdV6xvtW721buU2Sx/l8sh9L32WzbCPaVZf8E8bzGDYAKPbWmERBm6Yczt/EcnSnSr4yiWmB3rOgedwU3X2CNVklpzN9B3J@Olg3lQCKYf8UEQjWVERHSGKM4zUj9NQM/59PydTB/oB "Retina – TIO Nexus") ### Explanation The basic idea is to turn all the `+`s and `-`s into simple `+1` and `-1` operations and then to prepend a sufficiently large number that makes all the equations work. To make the equations match, we can simply prepend the same number to each of them, and then reduce it by one for each `+1` and increase it by one for each `-1` after it. Since we'll be working with unary numbers, the only catch is that the first number needs to be large enough that we can reduce it by 1 enough times. ``` [-+] $&1 ``` We start by inserting a `1` after each `-` or `+`. ``` \B((\+1)|(-1))* $._$*1$#3$*1$#2$*_$& ``` The `\B` ensures that these matches are either at the beginning of the input, or between a `=` and a `+` or `-`, i.e. all the positions where we want to insert the leading number of an expression. The `((\+1)|(-1))*` part then simply counts the number of `+1`s and `-1`s in groups `2` and `3` respectively. Now let's break down the substitution string: ``` $._$*1 # For each character in the current string, insert a 1. This is # an offset which is the same for each expression and is guaranteed # to be large enough that all subsequent +1s can be cancelled. $#3$*1 # For each -1, insert a 1. $#2$*_ # For each +1, insert a _. $& # Re-insert the string of +1s and -1s. ``` ``` +`1_ ``` Repeatedly drop `1_` from the string, applying the required cancellation from the `+1`s. ``` 1+ $.& ``` Finally, replace all the strings of `1`s with their lengths to convert from unary to decimal. [Answer] # [Python 2](https://docs.python.org/2/), 76 bytes ``` lambda e:sum([[len(e+s)-2*s.count('+')]+[1]*len(s)for s in e.split('=')],[]) ``` [Try it online!](https://tio.run/nexus/python2#LY3RDoMgDEXf9xW8AZaabI8mfgny4DZMSBTNwO93pTUkl9ve03YZp2udt/d3VnEo52a8X2M2EYrFV1f6z37majRoG8A/Q9fCYpf9p4pKWcW@HGsiYCTA@WCvFsUWpXyc1djhoY5fylVFp6eq3WKivTzxTo9NgB2QIDtkkaZAQiETwF5oaTEKjCIr4K38U468kkpZSuPUo4U3h8A1PbnWDoY/ "Python 2 – TIO Nexus") [Answer] # Python 2, ~~199~~ ~~179~~ ~~178~~ ~~172~~ ~~162~~ ~~158~~ ~~156~~ ~~152~~ 151 bytes Way too long, but the solution was easy to create. ``` from itertools import* i=input() k='%s' s=k+k.join(i)+k for p in product(*[range(1,65537)]*-~len(i)): if eval((s%p).replace('=','==')):print s%p;break ``` [**Try it online**](https://tio.run/nexus/python2#FcpBCsIwEADAs3lFKJRsWlsQqYKSl4iHWLeyJk3CJvXo12s9z6wTx1lSQS4x@ixpTpFLI8hQSEsBLZxRdVYiG9e6/h0pAOnWiSmyTJKCTByfy1igubENL4TD/jQMx7O@N93X43/ri9jRJPFjPUCuk@4Zk7cjgjJqr4xRW0lMochNrw9G69a1Ml31Aw) This will try every possibility until it finds a solution. The program is extremely slow. It also performs the string replacement every iteration. The "172" edit made it *drastically* slower, since rather than starting with a small range it starts at the max. For example, the inputs `-=` or `=+` have to try 2\*\*32 attempts before reaching a solution. To speed up the program, use the version with 178 bytes from the edit history. [Answer] # JavaScript (ES6), ~~92~~ 82 bytes *Golfed 8 bytes with a trick from @xnor* ``` let f = x=>x.split`=`.map(q=>(x+q).length-2*~-q.split`+`.length+[...q,''].join(1)).join`=` ``` ``` <input oninput="if(/^[+=-]+$/.test(value))O.innerHTML=f(value)" value="="><br> <pre id=O>1=1</pre> ``` The trick here is to insert a `1` after every `+` or `-`, then prepend to each expression the number that makes the expression equal the length of the input. This way we can guarantee that the number is always positive; since there's always at least 1 `=` in the string, the number of `+`s can never reach the length of the string, so the remainder is always at least `1`. You can verify this by typing in an arbitrary number of `+`s in the snippet above. [Answer] # [Python 2](https://docs.python.org/2/), ~~120~~ 119 bytes -1 byte thanks to mbomb007 ``` a=['1'+(n and('1'.join(n)+'1'))for n in input().split('=')] print'='.join(`max(map(eval,a))-eval(c)+1`+c[1:]for c in a) ``` [Try it online!](https://tio.run/nexus/python2#JcwxCsMwDIXhvafwJgnVAa8FnSQEItwEXBLFpG7o7V2bwhu@5f1VZYQAjObUntg4vI5kaMTNROtxOnOpL38K0vDOWyoIAjTd8pmsNP4v865f3DXjcul2VyLfgZE4zBzH8Jh6LPaYUq0gzMJePIv3Aj8 "Python 2 – TIO Nexus") or [Verify all test cases](https://tio.run/nexus/python2#LY7dCoQgEIXvewrvnGE06DboSSJI@gGXMnFr2Yt993YcQzmeGT/PeM/Lqlbw2FbKdb1uNEFQLszAtn4dPkBAYo@4HkkF5XnX77j5E3SncahUWs4rBS4KPu7uC7uLsHzcZhyizQYmpGakqW/aIQdNOcjhnb2X0BCvE/I3YvLhVN7onzb5Z3fP2UZ3WUgcsVhxVqQ0C1QoKwSJL3RpCUqCWlGyj8rJ91YiuSyh/Jx7HPhwlqTmVablgcMf "Python 2 – TIO Nexus") First I insert `1` in every position, to check the highest value, then add it as offset on every equation. This work because you can't add negative numbers, so the minimum result is given by the amount of `+` in the equation that only have `+`. [Answer] # GNU Prolog, 156 bytes ``` x(L,R,V)-->{E#>0},({L=[E|R],E=V};x(L,[E|R],X),("+",{V#=X+E};"-",{V#=X-E})). q(L,R,V)-->x(L,T,V),({T=R};"=",q(T,R,V)). s(Q,L):-q(L,[],_,Q,[]),fd_labeling(L). ``` ## Explanation We've got a bunch of equations to solve, so why not use an actual equation solver? `x` is basically an equation evaluator for equations of the form `+-+`; in addition to the equation itself, it has two additional arguments (a difference list `L,R` that contains the values of the equation, and a value `V` that the equation evaluates to). As usual in Prolog, it can be used any way round (e.g. you can specify `V` and get an `L,R`, specify `L,R` and get a `V`, specify both and verify that the value is correct, or specify neither in which case appropriate constraints will be placed on both `V` and `L,R`). The "current element" of `L,R` is named `E`, and we also include an assertion that `E` is greater than 0 (because the question requires the use of positive numbers). This function is slightly more verbose than I'd like, e.g. I had to write the `[E|R]` pattern match/unmatch twice, due to the fact that lists are right-associative but addition and subtraction are left-associative. Sadly, we need to use an actual list, rather than inventing our own left-associative list type out of cons cells, for `fd_labeling` to work. `q` is similar to `x`, but also includes `=`. It basically just calls `x`, and itself recursively. Incidentally, it's a very clear demonstration of how difference lists work, showing that you can concatenate two difference lists `L,T` and `T,R` into a single difference list `L,R`. The basic idea is that a difference list is a partial function that takes an argument `R` and returns a value `L` which is `R` with the list itself prepended to it. Thus, by identifying the argument of one difference list and the return value of another, we can compose the functions, and thus concatenate the lists. Finally, `s`, which is the funciton that actually solves the task in the question, is a wrapper function that calls `q` with arguments. We convert the difference list to a regular list by supplying `[]` as its argument, and use `fd_labeling` to find a solution to the equation we built up. (By default, it appears to like setting values to 1 if there's no reason to set them to something else. However, it can be configured; `value_method(random)` gives more "interesting" solutions than putting 1s everywhere, for example, and is still very fast.) ## Sample output With the program as written: ``` | ?- s("=++=+-=-+=--=", V). V = [3,1,1,1,3,1,1,3,1,1,5,1,1,3] ? ``` If I make the program a bit longer to add a `value_method(random)`, the outcome varies, but looks something like this: ``` | ?- s("=++=+-=-+=--=", V). V = [68,6,12,50,85,114,131,45,3,26,71,1,2,68] ? ``` In both cases, the `?` at the end of the output means that there may be more than one solution. (Of course, in this case, we know that there's a *lot* more than one solution!) [Answer] # Mathematica, 116 bytes ``` Join@@(Prepend[#^2,1-Min[Tr/@c]+Tr@#]&/@(c=Characters@StringSplit["0"<>#<>"0","="]/."+"->-1/."-"->1/."0"->Nothing))& ``` Pure function taking a string as input and returning a list of positive integers. Basic strategy: we only ever add 1 and subtract 1, and we choose the initial numbers in each expression to make everything equal. `c=Characters@StringSplit[#,"="]/."+"->-1/."-"->1` would split the input string at every equals sign, then replace each `+` by `-1` and each `-` by `1`. However, if there's an equals sign at the beginning or end, then it would get ignored. Therefore we artificially add a new character at each end (`"0"<>#<>"0"`) and make it go away after the string-splitting is complete (`/."0"->Nothing`). The total of each sublist now equals an integer that we can put in front of the `+`s and `-`s to make each expression equal. `1-Min[Tr/@c]` is the smallest integer that we can add to each total to make them all positive. So `Prepend[#^2,1-Min[Tr/@c]+Tr@#]&` takes each sublist (the `^2` turns all their entries to `1`) and prepends its total shifted by this smallest compensating integer. The resulting lists are `Join`ed together to produce the output. [Answer] # Ruby, 76 ``` ->s{(?1+s.gsub(/./){|a|a+?1}).split(?=).map{|e|e[0]="#{5**8-eval(e)}";e}*?=} ``` The target value for the expressions is fixed at `5**8` minus 1 for golfing reasons! Originally I was using `s.size+1` minus 1. **Ungolfed in test program** ``` f=->s{(?1+s.gsub(/./){|a|a+?1}). #add a 1 at the beginning and after every symbol split(?=). #split into an array of expressions at = signs map{|e| #for each expression string e[0]="#{5**8-eval(e)}";e #change the first number to 5**8-eval(e) }*?= #and rejoin the strings } puts f["="] puts f["=="] puts f["+="] puts f["=+"] puts f["-="] puts f["=-"] puts f["=-="] puts f["=+="] puts f["==="] puts f["+=-"] puts f["-=+"] puts f["+=+"] puts f["-=-"] puts f["--="] puts f["++="] puts f["-+="] puts f["+-="] puts f["+-=-="] puts f["--=--"] puts f["==-=="] puts f["=++=+-=-+=--="] puts f["+--++-=-+-+-"] puts f["======"] ``` **Output** ``` 390624=390624 390624=390624=390624 390623+1=390624 390624=390623+1 390625-1=390624 390624=390625-1 390624=390625-1=390624 390624=390623+1=390624 390624=390624=390624=390624 390623+1=390625-1 390625-1=390623+1 390623+1=390623+1 390625-1=390625-1 390626-1-1=390624 390622+1+1=390624 390624-1+1=390624 390624+1-1=390624 390624+1-1=390625-1=390624 390626-1-1=390626-1-1 390624=390624=390625-1=390624=390624 390624=390622+1+1=390624+1-1=390624-1+1=390626-1-1=390624 390624+1-1-1+1+1-1=390625-1+1-1+1-1 390624=390624=390624=390624=390624=390624=390624 ``` [Answer] # PHP, ~~207~~ ~~204~~ ~~197~~ 114 bytes direct approach: much shorter and faster ``` foreach(explode("=",$argn)as$t)echo"="[!$c],strlen($argn)+($c=count_chars($t))[45]-$c[43],@chunk_split($t,!!$t,1); ``` Run with `echo '<input>' | php -nR '<code>'` or [test it online](http://sandbox.onlinephpfunctions.com/code/e9e5994384ad48acf69d3f4a59265b9960ae26fb). **breakdown** ``` foreach(explode("=",$argn)as$t) // loop through terms echo // print ... "="[!$c], // 1. "=" if not first term strlen($argn) // 2. maximum number +($c=count_chars($t))[45] // + number of "-" -$c[43], // - number of "+" @chunk_split($t,!!$t,1); // 3. each operator followed by "1" ``` * `!$c` is true in the first iteration, cast to `1` for string indexing; `"="[1]` is empty. After that, `$c` is set and `!$c` false, cast to `0` and `"="[0]` is the first character. * The maximum value for any term needs not exceed the number of pluses +1; so we´re definitely safe with the length of the input. All terms will evaluate to that. * [`chunk_split($s,$n,$i)`](http://php.net/chunk_split) inserts `$i` after every `$n` characters of `$s` - and at the end. To prevent empty terms turning to `1`, an error is forced by setting the chunk length to `0`. [Answer] # [Röda](https://github.com/fergusq/roda), ~~112~~ ~~110~~ 109 bytes ``` f x{[(`:$x:`/"=")()|{|p|p~=":",""a=p;a~=`\+`,""b=p;b~="-","";["=",#x-#b+#a];{(p/"")|{|o|[o,"1"*#o]}_}}_][1:]} ``` [Try it online!](https://tio.run/nexus/roda#RY49DoMwDIVnOIVlOkCDVXUl4iQh4kcCqUMLqjogJenVqWnroAzPzy@f7W2C1Zm8q05r1V2wxiIvvPOLX941Vlgi9vWi@3fdNapjN7AbOKI90oaBMlspG1TWW@3y5YK487M3c4lXPGezDW0IrTXXyobt3t8e4NLEpEmys1/5qxKvfkriSTR@iGRESRglnThFIsGV4CSFoqOQkr@TLOZmXM2DOeGFB0Pq2@IXz9ovSxMLHhyYsQRsXmg1TPlYaDDYPNBCgGl@wpiG7QM "Röda – TIO Nexus") The split function did not work as I intended with this program. For example, `split("", sep="")` returns one empty string instead of nothing. How is that logical? Due to this the program is nearly 20 bytes larger than what it could be if the split semantics were ideal. The idea of this answer is that we know that the length of the input string must be greater or equal to the value of the equation, so we define the value of the equation to be the length of the string. For every part of the equation, we think every operator being `+1` or `-1` and subtract and add them to value of the equation. Ungolfed: ``` function f(x) { /* Adds ":"s around the string to prevent "=" being split wrong. */ [split(`:$x:`, sep="=") | for p do p ~= ":", "" /* Removes colons. */ a := p; b := p /* Initializes a and b to be p. */ a ~= "\\+", "" /* The lengths of a and are now equal to the */ b ~= "-", "" /* numbers of "-" and "+" characters in x. */ push("=", #x-#b+#a) /* Prints "=" and the value of the equation */ /* minus number of "+"s plus number of "-"s. */ split(p, sep="") | for o do /* For each operator: */ push(o) /* Prints the operator. */ push(1) if [o != ""] /* Prints 1 unless the operator is "". */ done done][1:] /* Removes the first character of the output ("="). */ } ``` ]
[Question] [ Since Euclid, we have known that there are infinitely many primes. The argument is by contradiction: If there are only finitely many, let's say \$p\_1,p\_2,...,p\_n\$, then surely \$m:=p\_1\cdot p\_2\cdot...\cdot p\_n+1\$ is not divisible by any of these primes, so its prime factorization must yield a new prime that was not in the list. So the assumption that only finitely primes exist is false. Now let's assume that \$2\$ is the only prime. The method from above yields \$2+1=3\$ as a new (possible) prime. Applying the method again yields \$2\cdot 3+1=7\$, and then \$2\cdot 3\cdot 7+1=43\$, then \$2\cdot 3\cdot 7\cdot 43+1=13\cdot 139\$, so both \$13\$ and \$139\$ are new primes, etc. In the case where we get a composite number, we just take the least new prime. This results in [A000945](http://oeis.org/A000945). ### Challenge Given a prime \$p\_1\$ and an integer \$n\$ calculate the \$n\$-th term \$p\_n\$ of the sequence defined as follows: $$p\_n := \min(\operatorname{primefactors}(p\_1\cdot p\_2\cdot ... \cdot p\_{n-1} + 1))$$ These sequences are known as *Euclid-Mullin*-sequences. ### Examples For \$p\_1 = 2\$: ``` 1 2 2 3 3 7 4 43 5 13 6 53 7 5 8 6221671 9 38709183810571 ``` For \$p\_1 = 5\$ ([A051308](http://oeis.org/A051308)): ``` 1 5 2 2 3 11 4 3 5 331 6 19 7 199 8 53 9 21888927391 ``` For \$p\_1 = 97\$ ([A051330](http://oeis.org/A051330)) ``` 1 97 2 2 3 3 4 11 5 19 6 7 7 461 8 719 9 5 ``` [Answer] # JavaScript (ES6), ~~45~~ 44 bytes Takes input as `(n)(p1)`, where \$n\$ is 0-indexed. ``` n=>g=(p,d=2)=>n?~p%d?g(p,d+1):--n?g(p*d):d:p ``` [Try it online!](https://tio.run/##TYxRC4IwFEbf@xX3wWA3p5RQkTZ96ldE4HBqC9kuGr2M9dfXfOvp4xwO30t@5NLNmt6ZsaoPgwhG1KNgxJUoUNSm@dJWNeMq0gOWWWZW2CksVUmhuhccjhwu50c@2PkmuycjEDW4DUAUTIOAfQUarnCKk6YInTWLnfp8siNrJUsceZ447TGmiRuYRkboW6zixX8bhcfwAw "JavaScript (Node.js) – Try It Online") ### Commented ``` n => // n = 0-based index of the requested term g = ( // g is a recursive function taking: p, // p = current prime product d = 2 // d = current divisor ) => // n ? // if n is not equal to 0: ~p % d ? // if d is not a divisor of ~p (i.e. not a divisor of p + 1): g(p, d + 1) // increment d until it is : // else: --n ? // decrement n; if it's still not equal to 0: g(p * d) // do a recursive call with the updated prime product : // else: d // stop recursion and return d : // else: p // don't do any recursion and return p right away ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes This produces and infinite output stream. ``` λλP>fW ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3O5Di8/tDrBLC///34jLDAA "05AB1E – Try It Online") (link includes a slightly modified version, `λ£λP>fW`, which instead outputs the first \$n\$ terms) ### Explanation Very straightforward. Given \$p\_1\$ and \$n\$, the program does the following: * Starts with \$p\_1\$ as an initial parameter for the infinite stream (which is generated using the first `λ`) and begins a *recursive environment* which generates a new term after each interation and appends it to the stream. * The second `λ`, now being used *inside* the recursive environment, changes its functionality: Now, it retrieves all previously generated elements (i.e. the list \$[\lambda\_0, \lambda\_1, \lambda\_2, \ldots, \lambda\_{n-1}]\$), where \$n\$ represents the current iteration number. * The rest is trivial: `P` takes the product (\$\lambda\_0\lambda\_1\lambda\_2 \cdots \lambda\_{n-1}\$), `>` adds one to this product, and `fW` retrieves the minimum prime factor. [Answer] # [J](http://jsoftware.com/), 15 bytes -10 bytes thanks to miles! Returning the sequence up to n (zero-indexed) – thanks to [@miles](https://codegolf.stackexchange.com/users/6710/miles) ``` (,0({q:)1+*/)^: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NXQMNKoLrTQNtbX0NeOs/mtyKXClJmfkK1gopCkYQZiWQKYpQtTS/D8A "J – Try It Online") # [J](http://jsoftware.com/), 25 bytes Returns the `n` th item ``` _2{((],0{[:q:1+*/@])^:[]) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/442qNTRidQyqo60KrQy1tfQdYjXjrKJjNf9rcilwpSZn5CtYKKQpGEGYlkCmKULU0vw/AA "J – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 56 bytes ``` i=input();k=1 while 1: k*=i;print i;i=2 while~k%i:i+=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9M2M6@gtERD0zrb1pCrPCMzJ1XB0IpLIVvLNtO6oCgzr0Qh0zrT1ohLASxXl62aaZWpbWv4/7@lOQA "Python 2 – Try It Online") --- ## Commented ``` i=input() # the initial prime k=1 # the product of all previous primes while 1: # infinite loop k*=i # update the product of primes print i # output the last prime i=2 # starting at two ... while~k%i: # find the lowest number that divides k+1 i+=1 # this our new prime ``` [Try it online!](https://tio.run/##XY/RagMhEEXf/YoLJdA2sLB5CQ34MTaa7rDGER2z9CW/vtG4pZB5GRjPXM/EX5k4HNaVNIVY5P0Db5DJgQIJGY@Y6OrUrEf06q8xsS1nAV9gfIPcjbjkTme1TOQdxlPDKVxaloNnjgrzp6YtqERr6vwlb4toPQiogVykqj1Bb7JsTiB9@HPKYpJQ@IGp2MIYhkHhaXGfd3SqRJWwPYEXVzNCuX67VCd1w9KNrMuY96MCaK9b@692MuVqkRDc0n9f16/jAw "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` P‘ÆfṂṭµ¡ ``` A full program (using zero indexing) accepting \$P\_0\$ and \$n\$ which prints a Jelly representation of the list of \$P\_0\$ to \$P\_n\$ inclusive. (As a dyadic Link, with `n=0` we'll be given back an integer, not a list.) **[Try it online!](https://tio.run/##AR4A4f9qZWxsef//UOKAmMOGZuG5guG5rcK1wqH///81/zg "Jelly – Try It Online")** ### How? ``` P‘ÆfṂṭµ¡ - Link: integer, p0; integer n µ¡ - repeat the monadic chain to the left n times, starting with x=p0: P - product of x (p0->p0 or [p0,...,pm]->pm*...*p0) ‘ - increment Æf - prime factors Ṃ - minimum ṭ - tack - implicit print ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` GDˆ¯P>fß ``` First input is \$n\$, second is prime \$p\$. [Try it online](https://tio.run/##yy9OTMpM/f/f3eV026H1AXZph@f//2/GZQoA) or [very some more test cases](https://tio.run/##yy9OTMpM/V9m4Vppr6SQmJeioGTvB2Q9apsEZFX6/Xd3Od12aH2AXdrh@f9rdQ5t@R9tpGOqY2keCwA) (test suite lacks the test cases for \$n\geq9\$, because for \$p=2\$ and \$p=5\$ the builtin `f` takes too long). **Explanation:** ``` G # Loop (implicit input) n-1 amount of times: Dˆ # Add a copy of the number at the top of the stack to the global array # (which will take the second input p implicitly the first iteration) ¯ # Push the entire global array P # Take the product of this list > # Increase it by 1 f # Get the prime factors of this number (without counting duplicates) ß # Pop and only leave the smallest prime factor # (after the loop: implicitly output the top of the stack as result) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~12~~ 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Struggled to get this one right so may have missed something that can be golfed. Takes `n` as the first input and `p1`, as a singleton array, as the second. Returns the first `n` terms. Change `h` to `g` to return the `n`th 0-indexed term instead. ``` @Z×Ä k Î}hV ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFrXxCBrIM59aFY&input=OQpbOTdd) ``` @Z×Ä k Î}hV :Implicit input of integer U=n & array V=[p1] @ :Function taking an array as an argument via parameter Z Z× : Reduce Z by multiplication Ä : Add 1 k : Prime factors Î : First element } :End function hV :Run that function, passing V as Z, and : push the result to V. : Repeat until V is of length U ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 56 bytes ``` ,|$ $* "$&"{~`.+¶ $$¶_ )`\b(__+?)\1*$ $.1$* 1A` .$ \* , ``` [Try it online!](https://tio.run/##K0otycxLNPz/X6dGhUtFi0tJRU2pui5BT/vQNi4VlUPb4rk0E2KSNOLjte01Ywy1gGr0DIHKDB0TuPRUuLhitLh0/v835TLSMQYA "Retina – Try It Online") Takes input as the number of new terms to add on the first line and the seed term(s) on the second line. Note: Gets very slow since it uses unary factorisation so it needs to create a string of the relevant length. Explanation: ``` ,|$ $* ``` Replace the commas in the seed terms with `*`s and append a `*`. This creates a Retina expression for a string of length of the product of the values. ``` "$&"{ )` ``` Repeat the loop the number of times given by the first input. ``` ~`.+¶ $$¶_ ``` Temporarily replace the number on the first line with a `$` and prepend a `_` to the second line, then evaluate the result as a Retina program, thus appending a string of `_`s of length 1 more than the product of the values. ``` \b(__+?)\1*$ $.1$* ``` Find the smallest nontrivial factor of the number in decimal and append a `*` ready for the next loop. ``` 1A` ``` Delete the iteration input. ``` .$ ``` Delete the last `*`. ``` \* , ``` Replace the remaining `*`s with `,`s. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 54 bytes ``` f=(p,n,P=p,F=n=>-~P%n?F(n+1):n)=>--n?f(p=F(2),n,P*p):p ``` [Try it online!](https://tio.run/##Fc1BC4JAEIbhe79iDgYzuQYKUWmTN8/eI1DMjUJmB40uYn99c08fPHzwvttvO3XjSz@JuEfvvWVUI6ZmNRULX5NfvZWyQolTyoVWSKS0qFxhRuG4U8rVWzeigrNwy8zBnI932gAEFE4LuZwKieNAAJ2TyQ39fnBPbCxGsy4GolkWAl7XhjwtDRX@Dw "JavaScript (Node.js) – Try It Online") **Ungolfed** ``` F=(p,n=2)=> // Helper function F for finding the smallest prime factor p%n // If n (starting at 2) doesn't divide p: ?F(n+1) // Test n+1 instead :n // Otherwise, return n f=(p,n,P=p)=> // Main function f: --n // Repeat n - 1 times: ?f(p=F(P+1),n,P*p) // Find the next prime factor and update the product :p // Return the last prime ``` [Answer] # bash +GNU coreutils, 89 bytes ``` IFS=\*;n=$1;shift;for((;++i<n;));{ set $@ `factor $["$*+1"]|cut -d\ -f2`;};echo ${@: -1} ``` [TIO](https://tio.run/##S0oszvj/39Mt2DZGyzrPVsXQujgjM63EOi2/SEPDWls70ybPWlPTulqhOLVEQcVBISEtMbkkv0hBJVpJRUvbUCm2Jrm0REE3JUZBQTfNKMG61jo1OSNfQaXawUpB17D2////5v9NAQ) [Answer] # Ruby 2.6, 51 bytes ``` f=->s,n{[s,l=(2..).find{|d|~s%d<1}][n]||f[l*s,n-1]} ``` `(2..)`, the infinite range starting from 2, isn't supported on TIO yet. This is a recursive function that takes a starting value `s` (can be a prime or composite), returns it when n=0 (edit: note that this means it's zero-indexed), returns the least number `l` that's greater than 1 and divides `-(s+1)` when n=1, and otherwise recurses with `s=l*s` and `n=n-1`. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 15 bytes This is a fairly simple implementation of the algorithm which uses Extended's very helpful prime factors builtin, `⍭`. [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKNdIe1/9aPerTqPupof9a411D48XR/IrX3Uu/hR39RHXYuAJEjZ/zQuIy5zAA "APL (Dyalog Extended) – Try It Online") ``` {⍵,⊃⍭1+×/⍵}⍣⎕⊢⎕ ``` **Explanation** ``` {⍵,⊃⍭1+×/⍵}⍣⎕⊢⎕ ⊢⎕ First get the first prime of the sequence S from input. { }⍣⎕ Then we repeat the code another input number of times. 1+×/⍵ We take the product of S and add 1. ⍭ Get the prime factors of product(S)+1. ⊃ Get the first element, the smallest prime factor of prod(S)+1. ⍵, And append it to S. ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` é|G╝╓c£¼_ ``` [Run and debug it](https://staxlang.xyz/#p=827c47bcd6639cac5f&i=2+7%0A5+7%0A97+6&a=1&m=2) Takes `p0` and (zero-indexed) `n` for input. Produces `pn`. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~54~~ 53 bytes ``` p;f(x,n){for(p=x;--n;p*=x)for(x=1;~p%++x;);return x;} ``` [Try it online!](https://tio.run/##HYxBCoMwEEXXeopBsCRNssiqyDQ36UZiI0I7HaLSgNijN01dfXj897wZvc@ZMYikSW7hFQW7hMYQ8tkl@QfJWfxwq1RCifG@rJEg4Z6f/URCbnU10QJsNRDW1ex7CqJph0bDia0sqDRAEDiwCARX6MooJYFjEY8vtMONikAagjhKsoh77i5fHx79OGfz/gE "C (gcc) – Try It Online") *-1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~33~~ 32 bytes *-1 byte thanks to nwellnhof* ``` {$_,{1+(2...-+^[*](@_)%%*)}...*} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1olXqfaUFvDSE9PT1c7LlorVsMhXlNVVUuzFiiiVfu/OLFSIU3DSDM6zjzWmgvCMwXyLOA8S3Mg1zLW@j8A "Perl 6 – Try It Online") Anonymous code block that takes a number and returns a lazy list. ### Explanation: ``` { } # Anonymous codeblock ...* # That returns an infinite list $_, # Starting with the input { } # Where each element is 1+(2... ) # The first number above 2 %%* # That cleanly divides [*](@_) # The product of all numbers so far -+^ # Plus one ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 45 bytes ``` (p,n)->s=p;for(i=2,n,s*=p=divisors(s+1)[2]);p ``` [Try it online!](https://tio.run/##FcoxCsMwDEbhq/x0slp5iKGUkioXMR4CwUWLI6zSqXd3k@XBg8/WrvFto0JGMG4UFxeb696DSuLGfhWTTb/qe/fgt4lyKjTbyKdpEEyMJ8O6tk/IxmgFF8TlSA3nEtEPhldEToz7oR@ljD8 "Pari/GP – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 49 bytes ``` g 1 g a b=b:g(a*b)([c|c<-[2..],1>mod(a*b+1)c]!!0) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfpmCrEPM/XcGQK10hUSHJNskqXSNRK0lTIzq5JtlGN9pITy9Wx9AuNz8FJKxtqJkcq6hooPk/NzEzD6i1oCgzr0RBRaEkMTtVwVxBI03BSPP/v@S0nMT04v@6yQUFAA "Haskell – Try It Online") Returns the infinite sequence as a lazy list. ### Explanation: ``` g 1 -- Initialise the product as 1 g a b= -- Given the product and the current number b: -- Return the current number, followed by g -- Recursively calliong the function with (a*b) -- The new product ( ) -- And get the next number as [c|c<-[2..], ]!!0 -- The first number above 2 1>mod c -- That cleanly divides (a*b+1) -- The product plus one ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` !¡ö←p→Π; ``` [Try it online!](https://tio.run/##ARwA4/9odXNr//8hwqHDtuKGkHDihpLOoDv///85N/84 "Husk – Try It Online") For input `m`,`n` outputs the `n`-th term in the sequence starting with `m`. Drop the initial `!` (for 7 bytes) to output the entire infinite sequence ([this link](https://tio.run/##ASEA3v9odXNr/@KGkTEw4oKB/8Khw7bihpBw4oaSzqA7////OTc) selects the first 10 elements from the infinite list). If both input & output are flexible enough (input: list of just the first term, output: infinite sequence) we could get down to [6 bytes](https://tio.run/##ASIA3f9odXNr/@KGkTEw4oKB/8Khw7bihpBw4oaSzqD///9bOTdd). ]
[Question] [ Let's define a sequence: The **n digit summing sequence** (n-DSS) is a sequence that starts with **n**. If the last number was **k**, then the next number is **k + digit-sum(k)**. Here are the first few n-DSS: ``` 1-DSS: 1, 2, 4, 8, 16, 23, 28, 38, 49, 62, 70... 2-DSS: 2, 4, 8, 16, 23, 28, 38, 49, 62, 70, 77... 3-DSS: 3, 6, 12, 15, 21, 24, 30, 33, 39, 51, 57... 4-DSS: 4, 8, 16, 23, 28, 38, 49, 62, 70, 77, 91... 5-DSS: 5, 10, 11, 13, 17, 25, 32, 37, 47, 58, 71... 6-DSS: 6, 12, 15, 21, 24, 30, 33, 39, 51, 57, 69... 7-DSS: 7, 14, 19, 29, 40, 44, 52, 59, 73, 83, 94... 8-DSS: 8, 16, 23, 28, 38, 49, 62, 70, 77, 91, 101... 9-DSS: 9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99... ``` For 1, this is [A004207](https://oeis.org/A004207), although the first few digits are different due to a slightly different definition. For 3, it's [A016052](https://oeis.org/A016052); for 9, [A016096](https://oeis.org/A016096). Today's challenge is to find the lowest n digit sum sequence that a given number appears in. This is called the "Inverse Colombian Function", and is [A036233](https://oeis.org/A036233). The first twenty terms, starting with 1 are: ``` 1, 1, 3, 1, 5, 3, 7, 1, 9, 5, 5, 3, 5, 7, 3, 1, 5, 9, 7, 20 ``` Some other good test cases: ``` 117: 9 1008: 918 ``` You only have to handle integers greater than 0, and you can take input and output in any standard format. As usual, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in each language wins. [Answer] # [Haskell](https://www.haskell.org/), ~~104~~ ~~64~~ 63 bytes **(-26 thanks to H.PWiz, additional -14 thanks to Sriotchilism O'Zaic, additional -1 thanks to cole)** This is a function. ``` f x=[y|y<-[1..],x==until(>=x)(foldr((+).read.pure)<*>show)y]!!0 ``` [Try it online!](https://tio.run/##FcxBDoMgEADAr6y3XdsS9Oz6EcOBRAhERIIaIenfaToPGKfPzYTQmoXCS/3W6bMMQqh3Yb7j5QPOXAjtEdaM@CKRjV5FurOhqZ9PdzxUVdfJtmsfgSFlHy/cdQIL/2iUitoP "Haskell – Try It Online") --- Explanation: ``` (foldr((+).read.pure)<*>show) ``` Sequence of composited functions that returns y+digital sum of y. Converts to string first, then does some monad gymnastics to get the sum of the characters and the original number (thanks to Cole). The `<*>` operator in this context has type and definition ``` (<*>) :: (a -> b -> c) -> (a -> b) -> c f <*> g = \x -> f x (g x) ``` so we can write the above as ``` \x -> foldr ((+) . read . pure) x (show x) ``` This `read . pure` converts a `Char` into a number, so `(+) . read . pure :: Char -> Int -> Int` adds a digit to an accumulated value. This value is initialized to the given number in the fold. ``` until (>=x) {- digital sum function -} y ``` `until` repeatedly applies a function to its result (in this case, the y+digital sum y) until it meets a requirement specified by a function in the first argument. This gives the smallest y-DSS element that's greater or equal to x. ``` [y | y<-[1..]; x == {- smallest y-DSS element >= x -} ] ``` Infinite lazy list of y's such that the smallest y-DSS element >= x is actually x. Uses Haskell's list comprehension notation (which I'd also totally forgotten about, thank y'all). ``` f x = {- aforementioned list -} !! 0 ``` First element of that list, which is the smallest y that satisfies the requirement of the challenge. [Answer] # [Python 2](https://docs.python.org/2/), ~~73~~ 71 bytes -2 bytes thanks to [Erik](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer). ``` n=input();k=K=1 while n-k:K+=k>n;k=[k+sum(map(int,`k`)),K][k>n] print K ``` [Try it online!](https://tio.run/##LU3LCoMwELzvVyyeFC0Y@8SS3uwlh156E0GrASU1hm2k9evTSHsYZpiZ3TGL7SeduXbqJA@CwGk@aDPbMDorLjiDdz88JeqNykXM1UV7u1Txax7DsTHhoG1SqzqKElGVPq3AkPdQOP8L/sd3mmUOiJaWlRDlR7a4LsKqW2ksFrdrQTTRr/Ag2SjHIIMt7GAPBzgCYx5pevoC "Python 2 – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 44 bytes ``` ->\a{+(1...{a∈($_,{$_+.comb.sum}...*>a)})} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtf1y4msVpbw1BPT6868VFHh4ZKvE61Sry2XnJ@bpJecWluLVBGyy5Rs1az9n9xYqWCkkq8lYKSjh5Qd1p@kQJIo5GBjqGhuY6hgYGF9X8A "Perl 6 – Try It Online") Naive solution that checks every sequence until it finds one that contains the input ### Explanation: ``` ->\a{ } # Anonymous code block taking input as a +(1...{ }) # Find the first number a∈( ) # Where the input is an element of ... # The sequence $_, # Starting with the current number { } # Where each element is $_+ # Is the previous element plus .comb.sum # The digit sum *>a # Until the element is larger than the input ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 51 bytes ``` ->n{(1..n).find{|i|i+=i.digits.sum while i<n;i==n}} ``` [Try it online!](https://tio.run/##DcvRCoIwFADQd7/iIgy07LJFUFTrR8QHc1teWLdojgjnty9fztv5xPsvO513N54rhcg1OmIzJ0q01YSGHjQFDPEJ35G8BbryhbTmZcntZg172YBSxxUpTx3afhjBvCBxKgDecQpQCnkIZxCmBAEtN@Bw6L2vuO4Kyyb/AQ "Ruby – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` D+ƒ$С€œi⁸Ḣ ``` [Try it online!](https://tio.run/##ASAA3/9qZWxsef//RCvGkiTDkMKh4oKsxZNp4oG44bii////Ng "Jelly – Try It Online") Full program. [Answer] # [MATL](https://github.com/lmendo/MATL), 18 bytes ``` `@G:"ttFYAs+]vG-}@ ``` [Try it online!](https://tio.run/##y00syfn/P8HB3UqppMQt0rFYO7bMXbfW4f9/Q0NzAA "MATL – Try It Online") Or [verify the first 20 values](https://tio.run/##y00syflvZGCl5BDhVfE/wcHLSqmkxC3SsVg7tsxLt9bhf6zLfwA). ### Explanation For input `i`, this keeps increqsing `n` until the first `i` terms of `n`-th sequence include `i`. It is sufficient to test `i` terms for each sequence because the sequence is increasing. ``` ` % Do...while @ % Push iteration index, n. This is the firsrt term of the n-th sequence G: % Push [1 2 ... i], where i is the input " % For each (i.e., do the following i times) tt % Duplicate twice FYA % Convert to digits s % Sum + % Add to previous term. This produces a new term of the n-th sequence ] % End v % Concatenate all terms into a column vector G- % Subtract i, element-wise. This is the do...while loop condition (*). } % Finally (this is executed right before exiting the loop) @ % Push current n. This is the output, to be displayed % End (implicit). A new iteration will start if all terms of (*) are nonzero % Display (implicit) ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 106 bytes ``` : f >r 0 begin 1+ dup begin dup i < while dup begin 10 /mod >r + r> ?dup 0= until repeat i = until rdrop ; ``` [Try it online!](https://tio.run/##TY1BDoIwEEX3nuLFLYqtGw0qHoSwUNtCE6RNA/H4tSXGsHozb@bnGxemft@ZjBgrDHVA8NSdHZEFava/JU@WK5/eDnrlpeDwdirnCkLNPZ/EjXmc7EDQXj@mFPwLFZznEo8CSaNcS2PbVCspA@WWHVuawTnfkl4M5ea1eClPFQvWUojzYhOzjl8 "Forth (gforth) – Try It Online") ### Code Explanation ``` : f \ start a new word definition >r \ store the input on the return stack for easy access 0 \ set up a counter begin \ start an indefinite loop 1+ dup \ add 1 to the counter and duplicate begin \ start a 2nd indefinite loop dup i < \ check if current value is less than the input value while \ if it is, continue with the inner loop dup \ duplicate the current value begin \ innermost loop, used to get the digit-wise sum of a number 10 /mod \ get quotient and remainder of dividing by 10 >r + r> \ add remainder to current list value ?dup 0= \ check if quotient is 0 until \ end the innermost loop if it is repeat \ go back to the beginning of the 2nd loop i = \ check if the "last" value of the current list = the input value until \ if it does, we're done rdrop \ remove the input value from the return stack ; \ end the word definition ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 13 bytes ``` fqQ.W<HQ+ssM` ``` [Try it here](https://pythtemp.herokuapp.com/?code=fqQ.W%3CHQ%2BssM%60&input=117&debug=0) or check out the **[test suite](https://pythtemp.herokuapp.com/?code=fqQ.W%3CHQ%2BssM%60&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A117%0A1008&debug=0)**. --- ### How it works ``` fqQ.W<HQ+ssM` Full program. Takes input Q from STDIN, writes to STDOUT. f{...} Loop over 1,2,3,... and find the first number to yield truthy results when applying the function {...} (whose variable is T = the current integer). qQ.W<HQ+ssM` The function {...}, which will be analysed separately. .W Functional while. While condition A is true, do B. <HQ Cond. A (var: H - starts at T): Checks if H is less than Q. +ssM` Func. B (var: G - G & H are the same): If A, G & H become G+digit sum(G) The last value of this functional while will be the least possible number N in the T-DSS that is greater than or equal to Q. If N = Q, then Q ∈ T-DSS. Else (if N > Q), then Q ∉ T-DSS. q That being said, check whether N == Q. ``` In most languages, it would be easier to loop on the set of the natural numbers, find the first \$n\$ terms of the \$k\$-DSS (because the digit sum is always at least \$1\$ so the repeated addition of this type of quantity cannot result in a value smaller than \$n\$) and check if \$n\$ belongs in those first \$n\$ terms of the \$k\$-DSS. In Pyth, however, the available control-flow structures actually make it easier to generate terms until a certain condition is met, rather than a fixed number of terms. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` DS+)i$ƬṖṪ ``` A monadic Link accepting a positive integer `n` which yields a positive integer, `a(n)`, the Inverse Colombian of `n`. **[Try it online!](https://tio.run/##y0rNyan8/98lWFszU@XYmoc7pz3cuer///@GBgYWAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##AUEAvv9qZWxsef//RFMrKWkkxqzhuZbhuar/xbzDh@KCrFpH//9saXN0KHJhbmdlKDEsIDIxKSkgKyBbMTE3LCAxMDA4XQ "Jelly – Try It Online"). ### How Effectively we work backwards, repeatedly looking for the value we added to until we cannot find one: ``` DS+)i$ƬṖṪ - Link: integer n Ƭ - Repeat until a fixed point, collecting up: $ - last two links as a monad - f(n): ) - left links as a monad for each - [g(x) for x in [1..n]]: D - decimal digits of x S - sum + - add x i - first (1-indexed) index of n in that list, or 0 if no found Ṗ - pop of the rightmost value (the zero) Ṫ - tail ``` Using `13` as an example... ``` D ) = [[1],[2],[3],[4],[5],[6],[7],[8],[9],[1,0],[1,1],[1,2],[1,3]] S = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4] + = [ 2, 4, 6, 8, 10, 12, 14, 16, 18, 11, 13, 15, 17] i 13 = .......................................... 11 i 11 = .................................... 10 i 10 = ............... 5 i 5 = not found = 0 i 0 = not found = 0 Ƭ -> [13, 11, 10, 5, 0] Ṗ = [13, 11, 10, 5] Ṫ = 5 ``` [Answer] # [Python 2](https://docs.python.org/2/), 85 bytes ``` f=lambda n,a=[]:n in a and a.index(n)or f(n,[k+sum(map(int,`k`))for k in a]+[len(a)]) ``` [Try it online!](https://tio.run/##RctBCsIwEIXhvaeY5QwN0nSjCD1JCHQkiYY00xAr6OljqwuXj/975b3eFxlaC@PM@eoYRPFo7EUgCjCwOOBjFOdfKLRUCCjKpO7xzJi5YJRVTWkiCltL34/tzOwFmSy1UjcAJmAk2EXcRWW5edRq0GQPPxFQ6xP9R9@fqX0A "Python 2 – Try It Online") This certainly works for all the test cases, plus all of the 1..88 entries given at OEIS; but still I'm not quite sure it's *provably* correct. (This is one of my complaints regarding the Church Of Unit Testing :)). [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 13 bytes ``` ╒môk(É∙Σ+=k/) ``` [Try it online!](https://tio.run/##y00syUjPz0n7///R1Em5h7dkaxzufNQx89xibdtsfc3//w25jLiMuUy4TLnMuAwNzbkMDQwsAA "MathGolf – Try It Online") Great challenge! It caused me to find a few bugs within the implicit pop behavior of MathGolf, which added 1-2 bytes to the solution. ## Explanation (using input \$3\$) ``` ╒ range(1,n+1) ([1, 2, 3]) mô explicit map using 6 operators k( push input-1 to TOS É start block of length 3 (repeat input-1 times) ∙Σ+ triplicate TOS, take digit sum of top copy, and add that to second copy This transforms the array items to their respective sequences instead Array is now [1, 2, 4, 2, 4, 8, 3, 6, 12] = get index of element in array (the index of 3 is 6) k/ divide by input (gives 2) ) increment (gives the correct answer 3) ``` To prove that this will always work, it is easy to see that `n <= input`, because `input` is the first element of the `input`th sequence. I have technically not proved that this solution is always valid, but it does pass every test case that I have tested. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` L.ΔIGÐSO+})Iå ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fR@/cFE/3wxOC/bVrNT0PL/3/39DQHAA "05AB1E – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/) 14.0+, ~~61~~ 48 bytes ``` Min@Position[Range@#//.j_/;j<#:>j+DigitSum@j,#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zczzyEgvzizJDM/LzooMS891UFZX18vK17fOstG2couSzukyMEzryQ1PbXIJTM9s6TYIUtHOVbtf0BRZl5JtLKuXZoDkFsXnJyYV1fNZahjpGOsY6JjqmOmY65joWOpw2VoaA4kDAwsuGr/AwA "Wolfram Language (Mathematica) – Try It Online") As of version 14.0, [`DigitSum`](https://reference.wolfram.com/language/guide/SummaryOfNewFeaturesIn140.html#2094113477) finally exists. Since TIO is on 12.0.1, the linked version uses `Tr@IntegerDigits` (+8 bytes) instead. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 86 bytes ``` import StdEnv $n=hd[i\\i<-[1..]|n==while((>)n)(\j=j+sum[toInt d-48\\d<-:toString j])i] ``` [Try it online!](https://tio.run/##PYzBCoJAFEX3fcVbhCilaCVqNK1qEbRz6bgYHKsR5xk6FkHf3jRNETwu91wep2prhlp2fGxrkEygFvLa9Qpyxfd4m0yRXHghKBUbv4iCoHwiIfeLaGvX3XroubQhzWwYZaG6Ayrg/iqllG/8tepy1Qs8Q1N6otS5YsZKwJXsClP4uBZh6QEhps/B3NJmbEtie2bxu8R2/P9kFo0BHMfooij5mLIfhWFqMUr1qzq17Dxo/3DUuwcyKarhDQ "Clean – Try It Online") Expanded: ``` $ n // function `$` of `n` is = hd [ // the first i // integer `i` \\ // for i <- [1..] // each integer from 1 upwards | // where n == // `n` is equal to while ((>) n) ( // the highest value not more than `n` from \j = j + sum [ // `j` plus the sum of toInt d - 48 // the digital value \\ // for each d <-: toString j // digit in the string form of `j` ] // where `j` is the previous term ) // of the sequence i // starting with term `i` ] ``` It bothers me that `digitToInt d` is longer than `toInt d-48` [Answer] # [C (gcc)](https://gcc.gnu.org/), 102 bytes ``` f(n,i,s){for(i=1;n^s;)for(s=i++;s<n;){char*p,j=0,l=asprintf(&p,"%d",s);for(;j<l;)s+=p[j++]-48;}n=~-i;} ``` [Try it online!](https://tio.run/##VY5NT8JAEIbP8is2S2p27WC6hdLishoPmJgoB@1NNCHdVpbg0rD1RMpfry0hzXh7Zub9mGz0nWVNUzALBhw/FvsDM0pI@@Uk7wanjO9LN7eSH7PN@nBTwlYFsFNrVx6MrQp2XQL1NG3dsjPI7XwnufNV@bH1/c/RJJG1VaeRkXUzNDbb/eqczF2lzf52cz8Y6rwwNifp4j1lS0gXb6@cXJJpwTzNV5UinvbcylJYQsGW/KxSqsMHSu/oqnp6fH4hzOa5JnTYXSmnfNCGkJ@1sYyT4@Dq3CBAcHnhEPEYxj1P0D6CqOcp0sQQ95wg/QxmPYsAmYXAQ4iixBhfJihYRFg2RTUixp4El85QQBhAGKAX4n/fBa1PJO2ibv4A "C (gcc) – Try It Online") [Answer] # JavaScript, 65 bytes ``` n=>eval('for(i=p=1;n-p;p=p>n?++i:p)for(j=p;j;j=j/10|0)p+=j%10;i') ``` [Try it online!](https://tio.run/##ZctBDsIgEIXhvadwYwrBKrjROE49S1PBMBCYtKYr747gysTVn7wvj8Z1XKbZ86tP@WGLw5JwsOsYRefyLDwyGkg9AyMP6a6Uv7JsQshAQEhHo99askLaGQ2@k6VxqLdwO2kISskppyVHe4j5KcJ@60SQEja/qzHnttf8idaXL9VWKx8 "JavaScript (Node.js) – Try It Online") --- It also works as C, but cost one more byte # [C (gcc)](https://gcc.gnu.org/), 66 bytes ``` i,p,j;f(n){for(i=p=1;n-p;p=p>n?++i:p)for(j=p;j;j/=10)p+=j%10;n=i;} ``` [Try it online!](https://tio.run/##dcuxDsIgFIXhvU9BmjSBABFcNF6pL@LS0NAAFm@qiUPTVxfBWacz/N@xcrI2Zy9QBHA0sdXdF@oNGg1JIqDBPl049ydktQSDECDsjFYMuQmdVpCMhy3Pg080MrI21cXyj@e9gsg5I7j49HS07UYie9KN19QKEgVx5cCg@Zm1PlRQ5j9R6vg1ZSva8tu62zA9snx9AA "C (gcc) – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~83~~, 82 bytes ``` n=>Enumerable.Range(1,n).First(x=>{for(;x<n;x+=(x+"").Sum(c=>c-48));return x==n;}) ``` [Try it online!](https://tio.run/##ZYw9C8IwFAB3f0Xo9ELb0ICgkL5sdnLSwbmGRALtE/IBAfG3xzqKwy3HcSb2Jvo6ZTKjp9RtaOYYVkJ9orzaMN8XKy4zPSzIjriYfIgJCuqXewZQZSRVWoTSNg0X17yCQW36/ZFzFWzKgVhBJPXmVe1uwSd79mTBgdyCXyEPf2oYvp/6AQ "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~15~~ 14 bytes The ternary to handle cases where `input=output` is annoying me! ``` @Ç?X±ìx:XÃøU}a ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QMc/WLHseDpYw/hVfWE&input=MTE3) ``` @Ç?X±ìx:XÃøU}a :Implicit input of integer U @ :A function taking an integer X as its argument Ç : Map each Z in the range [0,U) ? : If Z>0 X± : Increment X by ì : Convert X to digit array x : Reduce by addition :X : Else X à : End map øU : Contains U } :End function a :Return the first integer that returns true when passed through that function ``` [Answer] # [cQuents](https://github.com/stestoltz/cQuents), 18 bytes ``` #|1:#bN;A =A?Z+UDZ ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/X7nG0Eo5yc/akcvW0T5KO9Ql6v9/QwMA "cQuents – Try It Online") ## Explanation ``` =A?Z+UDZ second line - helper function first input = A second input = n =A first term is A ? mode=query, return true if n in sequence, false if n not in sequence each term in the sequence equals Z+ previous term + U ) sum ( ) D ) digits ( ) Z previous term #|1:#bN;A main program first input = A (user input) second input = n #|1 n = 1 : mode=sequence, return the nth term in the sequence # ) conditional - next term equals next N that evaluates to true N increments, any terms that evaluate to true are added to the sequence conditional ( ) b ) second line ( ) N;A N, A ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~14~~ 10 bytes -4 thanks to @H.PWiz ``` V£⁰m¡SF+dN ``` [Try it online!](https://tio.run/##yygtzv7/P@zQ4keNG3IPLQx2007x@///v6E5AA "Husk – Try It Online") [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 99 bytes ``` : f >r 0 begin 1+ dup begin dup i < while dup 20 for 10 /mod >r + r> next + repeat i = until r> . ; ``` [Try it online!](https://tio.run/##TU1LDoIwEN1zirdHsYMhgCgnYaNSoAm2pJbo7bEdlJhMOu/b6Yx1w77vwlqWEzrUFgI32SsNitHO05cEpHDGa1CjZJYK@B5I4PAwbSjGsDW0fLuA5CSvzlcumLVTY7ASVP6Gk09ntPS3EtwtqmiVkBIIrfGVX2I0ZvI@uz7ZgHZhjvxmDHLGJdNVyVjcMiXTVERE@fZxgzIiIYp/gYrlAw "Forth (gforth) – Try It Online") Largely similar to [reffu's submission (106 bytes)](https://codegolf.stackexchange.com/a/188668/78410). The golfed parts are: * Digit sum calculation (-6) * Final cleanup (-1) by printing some garbage to stdout. (No problem because the result is returned on the top of the stack.) ### How it works ``` : dsum ( n -- n+digitsum ) \ Sub-function. Given n, add its digit sum to n. dup \ Copy n to form ( n m ) -> extract digits from m and add to n 20 for \ Repeat 20 times (a 64-bit int is at most 20 digits) 10 /mod >r + r> \ n += m%10, m = m/10 next + ; \ End loop and discard 0 : f ( n -- ans ) \ Main function. >r \ Move n to the return stack, so it can be referenced using `i` 0 begin 1+ \ Initialize counter and loop starting from 1 dup begin \ Copy the counter (v) and loop dup i < while \ break if v >= n dsum \ v += digit sum of v repeat \ End loop i = until \ End loop if n == v r> . ; \ Cleanup the return stack so the function can return correctly \ `r> .` is one byte shorter than `rdrop` ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` NθW¬№υθ«UMυ⁺κΣκ⊞υ⊕Lυ»I⊕⌕υθ ``` [Try it online!](https://tio.run/##TY29DsIgFEbn8hSMl6QOnRwYSUyaaNPEJ8CWCCk/LeXqYHx2BF1cz3dyvknLOAVpc@79imlAd1MRNsbJUxurKAwhgQjoE2BLN8YYfZHmIlcRnJN@rnS0uMPS0is6WIrBSTPiruvU@ykqp3xSM5yVv6dCv8abjNGUqJB7gn/rZH7ResV4zl13zIeH/QA "Charcoal – Try It Online") Link is to verbose version of code. Uses @ChasBrown's algorithm. If that turns out to be invalid, then for 29 bytes: ``` NθW¬№υθ«≔⊕LυηW‹ηθ≧⁺Σηη⊞υη»ILυ ``` [Try it online!](https://tio.run/##Tc29DoIwFIbhGa6i42mCA5MDk2EiQdLoFVRsOE1KgZ4eHYzXXsGfxPEbnu/tUYd@0i6lxs8cOx4vJsAiq/yO1hkB3RShnthH4EIsUkrxyLMDkR08NL4PZjQ@miu0xg8RgaUsBK48@/rWEAG@qTjq@SNPdsAIyjEV4swj4A8pJtxC23jmKti1W2uKf/eySqks92l3cy8 "Charcoal – Try It Online") Link is to verbose version of code. Works by calculating the first member of each digit summing sequence not less than `n`. Explanation: ``` Nθ ``` Input `n`. ``` W¬№υθ« ``` Loop until we find a digit summing sequence containing `n`. ``` ≔⊕Lυη ``` The next sequence begins with one more than the number of sequences so far. ``` W‹ηθ ``` Loop while the member of the sequence is less than `n`. ``` ≧⁺Σηη ``` Add the digit sum to get the next member of the sequence. ``` ⊞υη ``` Push the final member to the list. ``` »ILυ ``` Print the number of lists computed until we found one containing `n`. [Answer] # [Red](http://www.red-lang.org), 103 bytes ``` func[n][m: 1 loop n[k: m until[if k = n[return m]s: k foreach d to""k[s: s + d - 48]n < k: s]m: m + 1]] ``` [Try it online!](https://tio.run/##RYxBCsMgFAX3OcXDbSjEUGiQ9hLdfv4iJEqD8RvUnN8auuhuZhaT7FrfdiXunEF1pywkTMFAY4/xgJA3CDilbDttDh6v1pItZxIEzga@czHZeflgRYlKeWoxo296w31iwRPtkTlcox6auSZ72LlAMA6gI20Ccs2UYsalpWH3AwetH38ehql@AQ "Red – Try It Online") [Answer] # [CJam](https://sourceforge.net/p/cjam), 25 bytes ``` q~:T,{[){__Ab:++}T*]T&}#) ``` [Try it online!](https://tio.run/##S85KzP3/v7DOKkSnOlqzOj7eMclKW7s2RCs2RK1WWfP/f0NDcwA "CJam – Try It Online") [Answer] # [Gaia](https://github.com/splcurran/Gaia), 16 bytes ``` 1⟨⟨:@<⟩⟨:Σ+⟩↺=⟩# ``` [Try it online!](https://tio.run/##S0/MTPz/3/DR/BVAZOVg82j@ShDj3GJtEKttly2QUgYqMDCwAAA "Gaia – Try It Online") Returns a list containing the smallest integer. ``` 1⟨ ⟩# % find the first 1 positive integers where the following is truthy: = % DSS equal to the input? ↺ % while ⟨:@<⟩ % is less than the input ⟨:Σ+⟩ % add the digital sum to the counter ``` # [Gaia](https://github.com/splcurran/Gaia), 16 bytes ``` 1⟨w@⟨:):Σ++⟩ₓĖ⟩# ``` [Try it online!](https://tio.run/##S0/MTPz/3/DR/BXlDkDCStPq3GJt7UfzVz5qmnxkGpBWBsoamgMA "Gaia – Try It Online") Uses the observation made by [Mr. Xcoder](https://codegolf.stackexchange.com/a/188662/67312). It's not shorter than the other, but it's an interesting approach nonetheless. ``` 1⟨ ⟩# % find the first 1 integers z where: Ė % the input (n) is an element of w@⟨:):Σ++⟩ₓ % the first n terms of the z-th Digital Sum Sequence ``` # [Gaia](https://github.com/splcurran/Gaia), 16 bytes ``` ┅ẋ⟨@⟨:):Σ++⟩ₓĖ⟩∆ ``` [Try it online!](https://tio.run/##S0/MTPz//9GU1oe7uh/NX@EAxFaaVucWa2s/mr/yUdPkI9NAdEfb//@GBgYWAA "Gaia – Try It Online") Third approach not using `N-find`, `#`, but still relying on the same observation as the middle approach. Returns an integer rather than a list. [Answer] ## [Clojure](https://clojure.org/), 106 bytes ``` #(loop[j 1 i 1](if(= j %)i(if(< j %)(recur(apply + j(for[c(str j)](-(int c)48)))i)(recur(inc i)(inc i))))) ``` [Try it online!](https://tio.run/##NY3BCsIwEETv/YoBEXYRoSmCPeiXlB7CmkhCTcK2Pfj1sVacy7yBByNTjqu6WunhPDwONOVchgiDADNS8HRHxJHDF287kjpZlWwp0xsnRPJZB6F5UUQe6UwhLRC@9Mwc/nZIgm38ak/TUNEEetmyHZPkJHYBqU1Phw6dYQzGXGHath83v9YP "Clojure – Try It Online") This is 99 bytes but results in Stack Overflow on larger inputs (maybe tweaking the JVM would help): ``` #((fn f[j i](if(= j %)i(if(< j %)(f(apply + j(for[c(str j)](-(int c)48)))i)(f(inc i)(inc i)))))1 1) ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 75 bytes ``` n=>{int a=0,b=0;for(;b!=n;)for(b=++a;b<n;)b+=(b+"").Sum(x=>x-48);return a;} ``` [Try it online!](https://tio.run/##ZcixCsIwFIXh3aeonRLSSiKChdub0cnNwTk3JJDBFNIECuKzxziqw4H/fHYd7RrqpUQ7h5iHNu2xRtTPlp1BORBK8EtiQHuMwD9JKIQBmtslgYxE3/PDrTzYhnobTxOH5HJJsTPwqrC7p5DdNUTHPFOcf8PxF5Q6/5GUU7P6Bg "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [ink](https://github.com/inkle/ink), ~~130~~ 127 bytes ``` -(l) +(i)[+]->l *(w)[{i}] ~temp n=w -(o){n<i: ~n+=s(n) ->o }{n>i:->w}{w} ==function s(n) {n>9: ~return n%10+s(n/10) } ~return n ``` [Try it online!](https://tio.run/##5YuxjsIwEET7/YptEDbBgVwHImmuuormmhOiiMCAhbMbOTZRFDm/Hqxr7iNO04zemzH0nD@Dc5q8Hdb4/XXEK@uOlh4fNV2tRkNt8B3e2KX6zPGHAzb1kPRLo2d0gdA/TIet47urG7R8qa0d8lkJKyETRp6ys6osrEQvT6OJZ5i8blqksgclWI50MHuYKCs7QRJUxRBHqsxeVX0c@whleQt08YYJfxdJ7tLBaR8cIS2KbZb4pthKiH94ngv4L/mANw "ink – Try It Online") * `-3 bytes` by converting to a full program which takes unary input. This feels too long to not be golfable. ### Ungolfed ``` // This program takes unary input. It passes through the same choice prompt as long as it recieves 1, and execution begins when it recieves 2 -(input_loop) +(input_value)[+] -> input_loop // When this option (option 1) is selected, its read count is incremented. We can access this via the "input_value" variable. We then return to the prompt by going back to the "input_loop" gather *(which_sequence)[{i}] // When this option (option 2) is selected, execution begins. Its read count also serves to keep track of which DSS we're checking. ~temp current_value = which_sequence // The initial value for the n-DSS is n, of course. -(sequence) // {current_value < input_value: // If we're still below the value we're looking for, we might find it. ~ current_value += digit_sum(current_value) // To get the next number, we add the current number's digit sum -> sequence // Then we loop } {n > i: -> which_sequence} // If we get here, we're at or above our target number. If we're above it, we know it's the wrong sequence and move on to the next one by going back up to option 2. This increments its read count. {which_sequence} // If we get here, we've found the target number, so we output the sequence's number. // End of main stitch, program ends. // A function to calculate the digit sum of a number == function digit_sum(n) == {n > 9: // If given a number greater than 9, recurse ~ return (n % 10) + digit_sum(n / 10) } ~ return n // Otherwise, return the input (it's a single digit) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~80~~ ~~79~~ 78 bytes ``` i,j;r;v;f(n){for(r=v=n;i=--r;v=n-i?v:r)for(;i<n;)for(j=i;i+=j%10,j/=10;);n=v;} ``` [Try it online!](https://tio.run/##LY7BTsNADETv@YqoUqRddVZdp2mbYgwfUnpAKUGOxBYtKAeifHtwECc/e@wZd@G965ZFMXDmkXuX/NTfs8sySmKVEGwsKejz@JD9qrA@Jv6jQZR1K0NFEcNOKLLnJCPPy8erJuenQtN3mS9XmQg19mhwwBEntDjDbohANWgPakAH0BF0ArWgM@pVtSbGduZiDVutVKKlf@nP27132e/@ySRvj2x98ZmNe7epmlsZnsrq9pI2yBe9wvateM/FvPwC "C (gcc) – Try It Online") -2 from ceilingcat [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=sum -p`, 57 bytes ``` map{$;=$_;"@F"-($_+=sum/./g)or$\||=$;while"@F">$_}1..$_}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/z83saBaxdpWJd5aycFNSVdDJV7btrg0V19PP10zv0glpqbGVsW6PCMzJxUkb6cSX2uopwckq///NzQwsPiXX1CSmZ9X/F/X11TPwNAASPtkFpdYWYWWZOaADPqvW5AIAA "Perl 5 – Try It Online") ]
[Question] [ Your task is to write a program which prints following four verses extracted from the lyrics from The Beatles' song "Hey Jude" (© Sony/ATV Music Publishing LLC): ``` Hey Jude, don't make it bad\n Take a sad song and make it better\n Remember to let her into your heart\n Then you can start to make it better\n \n Hey Jude, don't be afraid\n You were made to go out and get her\n The minute you let her under your skin\n Then you begin to make it better\n \n Hey Jude, don't let me down\n You have found her, now go and get her\n Remember to let her into your heart\n Then you can start to make it better\n \n Hey Jude, don't make it bad\n Take a sad song and make it better\n Remember to let her under your skin\n Then you'll begin to make it\n \n ``` **BUT** The only input you are allowed to use to construct these four verses is this list of tokens: ``` "Hey Jude, don't" " make it bad" " be afraid" " let me down" "Take a sad song and make it better" "You" " were made to go out" " and get her" " have found her, now go" "Remember to" "The minute you" " let her" " into your heart" " under your skin" "Then" " you" " can start" "'ll" " begin" " to make it" " better" ``` Note that some tokens have a space preceded and that enclosing quotes are not part of the tokens. You are free to use any format for the list and to rearrange the order of the tokens. Your generated output has to **exactly** match the above four verses. Note that`\n` is used for newlines and an **extra newline** is added after each verse. You can use [this file](https://gist.githubusercontent.com/arbego/9700a8fc3705b208ffaf942abb15d089/raw/b73efd3dd6619b5c5d5a98f71839a0e5e09aaecb/heyjudegolf.txt) (MD5: `4551829c84a370fc5e6eb1d5c854cbec`) to check your output against. You can use following railroad diagram to understand the structure of the verses (each element represents a token): [![enter image description here](https://i.stack.imgur.com/pogsf.png)](https://i.stack.imgur.com/pogsf.png) Shortest code in bytes wins. Happy golfing. [Answer] # JavaScript (ES6), 108 bytes ``` a=>`01 4 9bc efgjk 02 567 abd efijk 03 587 9bc efgjk 01 4 9bd efhij `.replace(/./g,n=>a[parseInt(n,36)]) ``` [Try it online!](https://tio.run/##VZDNbsIwEITvfooVFxIpBVoKtKrg3PZY9VIhJDbxxjE4NrIdEE@fOuSn5WbPznxj7wHP6DIrT/5BG051vq5xvdnPHtkze00zRrk4HBmbPbHFcsUw5UGRN2XOFi@rO0@baRyFPDC2n1g6Kcwomk6mItHrDW5PaB19aB/pZL6Md3GdGe2MookyIsqjLQMYvdMVPitOCXCjx36UNCKUeCSQHlLknZISYG5R9ndFHkoKoYtule8mguCQgzNaAGr@hyHvyba@H1N1iAtZChZO4A0IA6bq65usCAVFH4ICzwS5qcIgiAlocwmRdvhFJZUp2YDpnlIErtSVJ7gObeqOJ3XoDEMbNLR9b8AHzE12R6kHWnf6R8tQg/NDcqzUsCfRB5tvdRsYhrc9sF0cv7H6Fw "JavaScript (Node.js) – Try It Online") --- # Alternate version, 114 bytes A slightly better compression, but sadly ruined by the larger decompression code. ``` a=>`835fc3cbbd3 84db3db4bbdb3 85cd1cc3cbbd3 835fc4bbcb3 `.replace(/./g,n=>a[n='0x'+n,i=n%8&&n%8-2+i]+[` `[n>>3]]) ``` [Try it online!](https://tio.run/##VZDNboJQEIX3PMXEpKIRtS2amDSwbrpsumkIifdnQCrMNZeL1qengwJtN4Q5Z853YL7EWdTKFie3JKOxzaJWRPF@F24zFSopdejtNlqGWm54kDxtlX5So9ftsaPY8fYri6dSKJytV@s8oCgWCUX@47e/oKCI6GE3nfJj@bwo0kWy9/YJxXGYpvNWGapNiavS5LNslngAk1e8wlujMQBtyHeToBOhEkeEwoEUulckgsisKIa5RAcVcuhCd@WjiwiohYbaUA6C9C8GnUN73/s0TY@4oEVe0QjOQG7ANEN9l8254DCE4CDOCJlp2GAxADIXjtzNd6ywkmgZ03/KgbkFNQ7hOraV/3gFcSebljVhh17GM@Ym18eCRlr/9oemBEHtxqRfluOd8iHY/VZ/gdG83cFL5/MXr/0B "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 42 bytes ``` ;⁷“Ṙç€ṘḋḷŒø|Ṁ2kḤ⁽⁼SƁẒVṿẎj]ð⁵ṀƒƤ)÷Ƒ¦Ẋ½Iɠ⁻’ṃ ``` [Try it online!](https://tio.run/##RVDBSsNAEP2VIZcg9OTVH1CPKoJID1t3mqZNdiHZWAIeGr0pCPak4MFD0YsHL9KkWoQGA37G7o/E2TTa08ybN2/e2x1iEKR1vWOyuZk86uK@fDGXr1R1fqPz@fe0zC90Mdke6XxmsqXJPg@rTC@mx7r40ovbYbd8M9k7bVTTarZVzqu71bNeXK@Wez9PJvswkwddXNV1fersYgr7CccOcClc5XTAhZCNEHwFPcZdwkcWMogZh1gKD5jgmxVUCiO7dYAhhj2MQEkLIUAFgzUFvlASUplENGGRao4OUDQcjZt6xgTEqmXpyJ9FAzc21ALrR8xvop204jFGSAKOVuhJkMlaZ6N6myBkCqEvEoX/tonglLnJFo980Vp4bWcfESJ9zXiNB@wcoS9JZE92QMgx2RHluEHgdH8B "Jelly – Try It Online") Hardcoding version. Input: ``` ["Hey Jude, don't", ' make it bad', 'Take a sad song and make it better', 'Remember to', ' let her', ' into your heart', 'Then', ' you', ' can start', ' to make it', ' better', ' be afraid', 'You', ' were made to go out', ' and get her', 'The minute you', ' under your skin', ' begin', ' let me down', ' have found her, now go', "'ll"] ``` [Answer] # [Ruby](https://www.ruby-lang.org/) + `-p`, ~~177~~ ~~136~~ ~~120~~ ~~118~~ ~~115~~ 109 bytes (full program) ``` $_="abvevjlmvopqtuvvacvfghvklnvopstuvvadvfihvjlmvopqtuvvabvevjlnvoprstv".gsub(/./){|c|(eval$_)[c.ord-97]||$/} ``` [Try it online!](https://tio.run/##VY/NasMwEIRfZTGBJJDEx9JD76XH0EsJIaytta1allL9mVD31euu5JbQk9jZb2a0NlS3eV5dngqsIsV3NURz/fAhRqxj03axV5oVlxURG9n9YxZPIqzzsTi0LlSb8lBuP6d62lBEtbpsT/XBWLF/fDhP06r8mudT8Uw3eAmCdiCMXvtiV8CAPYH0UKFIY0WAjUWZB0UeBmJ21Dy@JhLBoQBndAuoxd1N3pNl6M2E5BzJEi8FgTfQGjAhlyVLy6FdZqHDSNCYwCorO9BmZJg3RxpoqMiyOxV3nCV18AS3JV7dM6TmBpYtC2hzC@exNWuul3pJSM@fvUYNzi/0Wqnl7jaT6b@/Ry1yvuv8ba5eGu3m/fUH "Ruby – Try It Online") -41 bytes: Switch from using variables to using characters as array indexes -16 bytes: Switch to a more convenient input format -1 byte: No space needed between `puts` and `"abv...` -1 byte: Use `$/` global instead of `?\n` literal -3 bytes: Use `gsub(/./)` instead of `.chars.map` -6 bytes: Call with `-p` and make use of `$_`. *Thanks [Pavel](https://codegolf.stackexchange.com/users/60042/pavel)!* Each character in the magic string represents an index into the input array. ~~I need the variable `z` so that I only read from STDIN once.~~ I could save some cost from IO by writing a lambda accepting an array and returning a string. This requires an extra `v` at the end, because it's not getting a free newline from `-p`. # [Ruby](https://www.ruby-lang.org/), ~~162~~ ~~110~~ ~~108~~ 105 bytes (function) ``` ->z{"abvevjlmvopqtuvvacvfghvklnvopstuvvadvfihvjlmvopqtuvvabvevjlnvoprstvv".gsub(/./){|c|z[c.ord-97]||$/}} ``` [Try it online!](https://tio.run/##VVK5TsQwFOzzFU8BaVlpjxJRLDWioEA0aHcLJ35JTBw7@Iqyx7eHl80BdPbMmxl7bOOTtst23fr5dI5ZEjB8ySro@tv5EFgasrwIpVSE2BvCQyaKfzODpp8w1oUQb3Lrk4ftZrs8X9LLaZ9utOHrp8fj5XK/vV47p0tUdrePAOIXbOHVc1wB12rh4lUPQsVKBOEgYXxEEgSWGSamvUQHFZKoUQPy0UsYWMbBapUDU/zXBp1DM8x9aj9aNGiQRjiC05Br0H6K77U5BRSTCAoWEDLtiSBwBUo3JBnId6ywStCQzXiUgnyF8g6hndPkPz@hKJNIQxgzUy7Zk80NtqVQs9u4@uOWMgXWzcqFlHNP@STsrzU2MJO3HqJjFBm0XjrYQbYfnoOwO3jTrhBUnq@hasFKRLr2GriwtWQt1XtQZJJpKo4Y04LCRgrVV2MgCCsSIYVro9o7C0PE8BniAx0K4sNB0WLZ/QA "Ruby – Try It Online") [Answer] # Java 8, ~~241~~ ~~233~~ ~~141~~ ~~140~~ 138 bytes ``` a->{a.add("\n");"01E4E9;<E>?@CDEE02E567E:;=E>?@CDEE03E587E91<E>?@CDEE01E4E91=E>?ABCEE".chars().forEach(i->System.out.print(a.get(i-48)));} ``` **Explanation:** [Try it online.](https://tio.run/##fVNNb9pAEL33V4x8iS2Bg/kmBieErBRVbQ5NL1Xbw2AvsGB2kb0GoYjfTscf4CWHWvjAvPdm3nx4jXtsqh2X62hzDmNMU/iOQn58ARBS82SBIYe3/C/AXokIQntNEjfTInanSYLHbyLV43edCLkMAB2fqCd66Zdq1CKEN5AwgTM2gw90MYps64@0HN9qeazLRv6YBY9PsxfGWm3W6w/Ygz@5RjqsNxywkVdzCo2XM6bPM8YsN1xhktqOu1AJw3Bli2bwfkw137oq0@6ObGkb3SXXhHSHjuP4p7Nf@ttl85j8VTaL7rbUu1028/svOmXf0g1tyQ/wn8Y/DyV1Mc1x23rlR/iaRbwBkZJ32mrA/T14Rd78sajkhoPQMMeoBNsGOOeAiwRFBXUMKOYatpyyHmQJdmvwZ54TIcUIUiWXgDKq63BNey0lvVryS2VlrG/UOPCEkzDioBUsFdBIS9LAIOXJab6wumQdGuAK9xwWKiMO4Q2Q6kCJSt6o5v3gW76d84TqVBNqwYPRz4psCJlpDseLT88D/9M4rg68NowNjG5A5cKEGJhcdtCBicEhh1S@IKUbUY3U60Jw4@IS78Gjoa099eHJiIco8@u6VhzAtEbv4rgKD@H5ZuXLa/kRzAyEmqiWWB1KC15uhMVi8xMvUA9Y8S2ezv8A) ``` a->{ // Method with ArrayList<String> parameter and no return-type a.add("\n"); // Add a new-line as last item (index 21) to the input-List "01E4E9;<E>?@CDEE02E567E:;=E>?@CDEE03E587E91<E>?@CDEE01E4E91=E>?ABCEE".chars().forEach(i-> // Loop over the bytes of this String above System.out.print( // Print: a.get(i-48)));} // The String in the list at index `i-48` ``` It basically converts the ASCII characters `0` (48) through `E` (69) to the 0-indexed indices `0` through `21` with the `i-48`. [Answer] # Python 3, ~~162~~ ~~147~~ ~~144~~ ~~142~~ ~~138~~ 127 bytes ``` lambda k,x=b'ABVCVDEFVGHIJKVVALVMNOVPEWQVGHRJKVASVVMTOV':"".join([(k+['\n',' '])[i-65]for i in x+x[5:16]+x[:4]+b'VDEWQVGHURJ']) ``` [Try It Online](https://tio.run/##RVDPT8IwFL7zV7zs0hGGiVE4kHBARRFFFLHGjB062m11W0tKJ/DXz9dN4un1fe/7le5ONtPqqr9tZp2MN3XBypgzyIPjOCaTG3pL76b39GH2OH@idPJMFy9L@jr9fENohdDkndLFeknJyPMuvrVUfujnvZBsFAkIkKgbyv5wECXagASp4Ng7hoPR5TDCObqOejFB/8btYzVHer0zUlk/8UNvJk4wr7gIgGtFrBd4ULJcgLQQM47r2m0M9ozDXqsUmOL/DGGtMEhaiVKUsTBgtXMohIXMHToe1rEaTroyiDDjAtaZUI6FoBtbpmBv2xPqz@ZuO/t33BNYYph0lb5a4UEYgWwunCrVoKtG5Aqm5wIuDEqpKiv@8irFsWdTaJ9L1cak7tFpi5cCv@LQHDL2IyDRKHFuASh9wCC8kKLwom63/gU) Special thanks to [user202729](https://codegolf.stackexchange.com/users/69850/user202729) and [Pavel](https://codegolf.stackexchange.com/users/60042/pavel). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~142~~ ~~68~~ ~~66~~ 65 bytes ``` `¶)•7/è¸ĀuVI{è:÷MDS.₁bö¼d@ÉÃƶõî›Λðë’OŒβι"žHƒö>“ÃaÈǝõöÓ∍¿þœθÀ•2ôèJ ``` [Try it online!](https://tio.run/##TVA7S8NQFP4rhyxFKL5ABAdxcKgFEVQEEcEbc5qGJvdCcmMpLtEudXBpJ1EXp4IgIhqrSIUcW7f8iPyRePNAnS7ne/Ld@SWmL2CaHkXhTBLcLc/RMBp9Bf7exikNV@h1c31nNjk/0ymMPow1uqDuNKQXekiC9/iaHuk@Ca62Jv34KX7TJuPatE/hahLcUJdR7/tWKUMaJL3L6JPGk0E8okCVLNIzDetpeqBVbFurggYOayFYEnRm5LeOwBous4rLRgkOgiHaPLt3MzEDjxngCW4C48ZfAEqJbqbaF35ubqOLijYQpABTgPBljmcuUwU3Czk02QlCQ/gKVlAVuGgreUZto4OOjq4KyOubKs/ivkTolB32vxyLqx5FuAphbtGlQpU9B72WxcuU/P3NOGYcPFk6atiBum9gVY3mFVn@iVlYsyHl3pLINx/@AA "05AB1E – Try It Online") -74 bytes thanks to EriktheOutgolfer, using a base-255 compressed string. -2 bytes by reversing the compressed string to prevent having to concatenate three 0's -1 byte thanks to EriktheOutgolfer, by switching two items in the input array in order to avoid the leading 0's, and thus removing the Reverse *R* command. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 115 bytes ``` ^ 12F5F:<=F?@ADEFF13F678F;<>F?@CDEFF14F698F:<=F?@ADEFF12F5F:<>F?@BCDF¶ {`1(?=.*¶(.*)) $1 ^(.*)¶.* $1 }T`1-E`0-D F ¶ ``` [Try it online!](https://tio.run/##VY/dTsJAEIXv5ynmwgRooLH@ICqIStkYL01vvCEsdmgb2t1ku7UhxtfqA/TF6ixIjHczZ75z9qwhmynZdSsILsS1uJvOxPzxKVwKEVyK8c1E3E8fWFkclCsxvp38Y44eRzwvQtE28LUO@vOZ77VN3/cGAzgLYOWmtvE9t3xH62C0XJ@PQhDQNl33Qnt8rWIaYqxVzwIWckeYWdzIGHBDKLdGZjzmZLEgpmoFkWMkljLGUqsEpYr/fGQtGXjXFWBNhvgQE1qNiUZd8QMOTjgsZQpT@Um41RVrvA9R6ZpBeKOCig0Z9kGUckamKku4d6H5yZspTmXJ8CoNJ3MKWw5KucuUcyo4mj6kwtI6qpfn7l8J312r39pw6v0D "Retina 0.8.2 – Try It Online") Takes input as a newline-delimited list of strings. [Answer] # [Stax](https://github.com/tomtheisen/stax), 59 58 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` îòÖ╥╬╬╞:,y╓ønä⌠╦╒ï╦≤x◘‼ε╩ⁿ◙ΓZ►e«qpôr╡"╣Ü≥┤╢┴;╡ÑkAú0:=;m╠╠x ``` [Run and debug it](http://stax.tomtheisen.com/#c=%C3%AE%C3%B2%C3%96%E2%95%A5%E2%95%AC%E2%95%AC%E2%95%9E%3A%2Cy%E2%95%93%C3%B8n%C3%A4%E2%8C%A0%E2%95%A6%E2%95%92%C3%AF%E2%95%A6%E2%89%A4x%E2%97%98%E2%80%BC%CE%B5%E2%95%A9%E2%81%BF%E2%97%99%CE%93Z%E2%96%BAe%C2%ABqp%C3%B4r%E2%95%A1%22%E2%95%A3%C3%9C%E2%89%A5%E2%94%A4%E2%95%A2%E2%94%B4%3B%E2%95%A1%C3%91kA%C3%BA0%3A%3D%3Bm%E2%95%A0%E2%95%A0x&i=%5B%22Hey+Jude%2C+don%27t%22+%22+make+it+bad%22+%22+be+afraid%22+%22+let+me+down%22+%22Take+a+sad+song+and+make+it+better%22+%22You%22+%22+were+made+to+go+out%22+%22+and+get+her%22+%22+have+found+her%2C+now+go%22+%22Remember+to%22+%22The+minute+you%22+%22+let+her%22+%22+into+your+heart%22+%22+under+your+skin%22+%22Then%22+%22+you%22+%22+can+start%22+%22%27ll%22+%22+begin%22+%22+to+make+it%22+%22+better%22%5D&a=1) The corresponding ascii representation of the same program is this. ``` `ORIpY$T&z{m6Y=>mR)_ .VQ)eN70e[:0yO8j$^RN[ Bp{IN/$|"3^;G#^&lv!`FAx+@]p ``` ``ORIpY$T&z{m6Y=>mR)_ .VQ)eN70e[:0yO8j$^RN[ Bp{IN/$|"3^;G#^&lv!`` is a compressed literal with a value of `"CDBGBLNOBQRSVWBBCEBHIJBMNPBQRUVWBBCFBHKJBLNOBQRSVWBBCDBGBLNPBQRTUVBB"`. The characters represent indexes into the token table. This program adds another token to represent a newline. It's not in the input, but added during execution. The rest of the program works like this. ``` F for each character, execute the rest of the program A integer literal 10, character code of newline x+ append 10 to the input array @ get element at index, using wrap-around the list is size 22, and B is 66, so B gets the first token ] wrap the result in a singleton array. this effectively turns 10 into "\n" p print without newline ``` [Answer] # C (gcc) function, 139 bytes ``` i,m;f(char**s){for(i=0;i<68;)m="AB@E@JLM@OPQTU@@AC@FGH@KLN@OPSTU@@AD@FIH@JLM@OPQTU@@AB@E@JLN@OPRST@@"[i++],printf(m^64?"%s":"\n",s[m-65]);} ``` [Try it online!](https://tio.run/##VZFtb9owFIU/419xZalq0qbqNm1oWopm@kIppW9AP1SUSSZxglVsV3YyhBC/nd24dIGv5zk@597r5CRPks1GRirOgmTG7dGRC1eZsYFsfYnlWfNnHKoWbZ@zK9br37GHx6fRM2PtC9a57rLb/j0qQ69css5Nd8/z8aZyDIYjxuhYHh9PoncrdZEF6k/z@2964Ogv@qpp5MbqpPljEsbrjeJSB@GK@GnAjb99nUALVoR2xRJ6ZSoiSI0@LGjUaDROTwHahILibwJkAVOeet2DcwRTATyzXO7IFyjPRQFKYNBC1@CS0FGVw8HxFJzROXCd1tmiKIRFe@W9IvTFlB9vvdDB1IWwAu2pgMJAbsCU9ZTXAOio8nLsnvmgLeoimPG/AjJTIkcWgTYLTKg8leOG0IFQQk2Fxej6ZQ8nnmGl1GUhYLkdqCK32yX3ivoo4vVN5bSIuK3nu0OG7VjgoXuT@j@79zV6Z9sHdC/39n9EJeEaXPGZ6uUnQg/n8x3fwH9KLnfuPkQJh9reudZH3uqPDuv4U30mWeDCmKw3/wA) [Answer] # [Red](http://www.red-lang.org), 133 bytes ``` foreach c{abzezjlmzopqtuzzaczfghzklnzopstuzzadzfihzjlmzopqtuzzabzezjlnzoprstzz}[prin either c =#"z"["^/"][t/(to-integer c -#"a"+ 1)]] ``` [Try it online!](https://tio.run/##VY9BT8MwDIXv@xVWdhiITRNXJO6I48QFVUVyG7cNbZORuFQL4rcXJwVNnCI/f@85z5NeTqShKDf8AIV6ogs8T5r2oJ3dsdooGLEnMAwV6jRWBNh4NHkYiGEkYWcr40siEQJqCM62gFZf3cRMXqBXNyXnTJ5kqQnYQevATflYsrQS2mUWOvwkaNwkqih7sG4WWDYnGmmsyIs7He4ky9iJCS5r/HDNMFYuiOxFQJ@vSJ5YsxZ6Y9eE9PzZa7QQeKV3w7D2bjOZ/vtbapVzr3JpnCesO6i/sIoU34cxuvMHTzFiHZu2i/1gRQlZ0bEx3T9m9STCB47xuzh7Y4EMSwuo4XGroirU21GVBR9v2B2kFrV5d9gqVHdwf1uWy/ID "Red – Try It Online") Ungolfed `t` is a block with the list of tokens ``` s:{abzezjlmzopqtuzzaczfghzklnzopstuzzadzfihzjlmzopqtuzzabzezjlnzoprstzz} foreach c s[ ; for each character in s prin either c = #"z" ; if it's a 'z' ["^/"] ; print CR [t/(to-integer c - #"a" + 1)] ; otherwise find which token to print ] ; by mapping its offset to the alphabet ``` [Answer] # [D](https://dlang.org/), 166 bytes ``` import std.algorithm,std.range;T f(T)(T[]s){return"abvevjlmvopqtuvvacvfghvklnvopstuvvadvfihvjlmvopqtuvvabvevjlnvoprstvv".map!((int a){return(s~["\n"])[a-97];}).join;} ``` [Try it online!](https://tio.run/##VVI9b4MwEJ3Lr7iyBCSatapQ96pjxVJRhiM@wAnYqW2Moij96@kZaJsOlnXv3nv3YYvrVQ5HbRxYJ7bYt9pI1w1ZiAyqlvICmqRIk6KsbHo25EajYqw9@X0/eH38dKP3uPNN2/lDrxixMyJ8I7t/nEUTGMY67@PtgMf7JJHKAf44J/arjD9UXKUlPjw9Vvkl3e61VPnliqPTYOEZyih@oRO8joIyEFptXJxFMQx4IJAOahRzXBNgY1AuUU8OBmL6pEJcBDKCRQFWqxZQiT8Dco5MYL3rcRZPZIjTgoBbaDXocSkZVC0bdwsdOvQEjR4ZZigDpSemh9QbDTTUZNhgLt@xn1SjIzitNfobH16JDgnDCJqlFpuyfAbtQarVZb5/PXao@BlXxabv1z20Cz00v864JuY5oyqPIq9lWIBUSQrn6O7mS/CROo/uJv4XlDSJTdM8uly/AQ "D – Try It Online") [Answer] # Mathematica, 102 bytes ``` ""<>Append[#," "][[36^^ajikrj7lg8pya7wgtt43pvrilsik1dea1uht6mx3go33m4mjj02hb4wi9w3~IntegerDigits~23]]& ``` Pure function. Takes a list of strings as input and returns a string as output. Just encodes all the token indices, similarly to other answers. [Answer] # [Ruby](https://www.ruby-lang.org/), 97 bytes ``` ->a{112.times{|i|$><<a[i%7-1+i%28/7*5]*("0@Xg(44k$,Xg0@Tz"[i/7].ord>>~i%7&1)+$/*(i%7/6+i%28/27)}} ``` [Try it online!](https://tio.run/##RY9Pb4JAEMXv/RQTovUfihhberDEY9Nj40FDOCzdATbCbrIsNVbtV6fDgvG0O/Pe@72MrpNzk74385BdfH@1MKLE6nIV10G42bBIDIO5PxPD1ZsXTF/i6dhZbvfZeL0@Dtx9ttzufp1IeEG8UJqH4R/Zn/3JbOBNx/T1XrvkKpjcbk0aRc4HnuGz5ugCV3JkHPfJgZIdEYSBhHE7Jwgs1Ux0U4EGSiT7SbbzrjUzqBiHSskMmOQPABqDunUdVG3DJ9RIMkcwCjIFqu4qc/aDkKqawjlqF6Q6kWylFphRZ96RvrDEMkFNAFufE0/I2iCc@47iYQYhqYcETRumuy4qobhdVkche4p974xRUfSXZ50BvpmEytwRBO1v7G32zjhu/gE "Ruby – Try It Online") Saved a few bytes with a different approach to most other answers. The number of possible tokens in each line is as follows ``` Line number Tokens 1 4 2 5 3 5 4 7 ``` The magic string contains one character per line, which is interpreted as a bitmap of which of up to 7 available tokens is to be printed for each of the 16 lines of the song. `a[i%7-1+i%28/7*5]` iterates through the tokens of each line, shifting by 5 for each new line, and with an offset of 1 to account for the fact that the first line has only 4 tokens. For lines 1-3 only the 64's through 4's bits are used - not using the 2's and 1's bits avoids printing tokens from the next line. for line 4, all 7 bits from 64's to 1's are used. [Answer] # Deadfish~, 4275 bytes ``` {{i}ddd}iic{iii}dc{ii}c{{d}i}ic{iiii}iic{iiii}iiic{dd}iiicic{dddddd}iiic{d}ddc{{i}ddd}ddc{i}icdc{{d}iii}dc{{i}dd}dddc{{d}ii}ddddc{{i}dd}dddc{d}ddc{i}cddddddc{{d}iii}ic{{i}ddd}iiic{i}ic{{d}ii}ddddc{iiiiii}iiiiiicdciiic{{d}i}c{{i}ddd}iiiic{i}iiic{i}cddddddc{{d}iii}ic{iiiiii}iiiiic{dddddd}dddddc{{i}dd}iiic{dd}iiciiic{{d}iii}iic{{i}dd}iiicddddcdc{d}iiic{{d}iii}dc{iiiiii}iiiiic{i}iiic{d}c{{d}iii}iic{{i}dd}dddc{d}ddc{i}cddddddc{{d}iii}ic{{i}ddd}iiic{i}ic{{d}ii}ddddc{iiiiii}iiiiiiciiic{i}iiiiicc{d}dddddc{i}iiic{{d}}ddddc{{i}ddd}iic{ii}dc{i}ddc{d}iic{i}ddc{d}dciiic{i}iiic{{d}ii}ddc{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}iiiiiic{d}iiic{i}iiiiic{{d}ii}ddddc{{i}ddd}iicdddc{i}iiic{{d}ii}ddc{{i}ddd}iiiciiiiiciiiiiicdddddc{{d}ii}ic{{i}d}dc{d}ciiiiiicdddc{{d}ii}ddc{{i}ddd}iicdddcddddc{ii}dddciic{{d}}ddddddc{{i}ddd}iiiic{ii}cdddc{i}dc{{d}ii}iic{{i}d}dc{d}ciiiiiic{{d}ii}dddddc{{i}ddd}dddcddc{i}iiic{{d}ii}iic{{i}dd}iiicic{dd}ic{ii}dddciic{{d}ii}ddddc{{i}dd}iiiicdddddc{{d}ii}ic{{i}dd}dddc{d}ddc{i}cddddddc{{d}iii}ic{{i}ddd}iiic{i}ic{{d}ii}ddddc{iiiiii}iiiiiiciiic{i}iiiiicc{d}dddddc{i}iiic{{d}}ddddcc{iiiiii}iic{iii}dc{ii}c{{d}i}ic{iiii}iic{iiii}iiic{dd}iiicic{dddddd}iiic{d}ddc{{i}ddd}ddc{i}icdc{{d}iii}dc{{i}dd}dddc{{d}ii}ddddc{iiiiii}iiiiiiciiic{{d}iii}ic{iiiiii}iiiiiciiiiic{i}iic{dd}iiic{i}ddcdddddc{{d}i}c{{i}dd}dc{ii}iiciiiiiic{{d}ii}dddddc{{i}d}dddc{dd}iic{i}iiic{d}dddc{{d}iii}ic{{i}dd}dddc{d}ddciiicic{{d}iii}ic{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}ic{i}ddc{{d}ii}ic{{i}dd}dciiiiiicdc{{d}ii}ddddc{iiiiii}iiiiic{i}iiic{d}c{{d}iii}iic{{i}ddd}icddc{i}iiiiic{{d}ii}ddddc{{i}ddd}iicdddc{i}iiic{{d}}ddddc{{i}ddd}iiiic{ii}cdddc{{d}iii}ic{{i}dd}dddcddddciiiiic{i}dddcdc{d}dddddc{{d}iii}ic{{i}d}dc{d}ciiiiiic{{d}ii}dddddc{{i}ddd}iiiiiic{d}iiic{i}iiiiic{{d}ii}ddddc{{i}ddd}iicdddc{i}iiic{{d}ii}ddc{{i}dd}iiiiic{d}iiic{d}cic{i}iiic{{d}ii}ddc{{i}d}dc{d}ciiiiiicdddc{{d}ii}ddc{{i}dd}iiic{d}iicddciiiiic{{d}}c{{i}ddd}iiiic{ii}cdddc{i}dc{{d}ii}iic{{i}d}dc{d}ciiiiiic{{d}ii}dddddc{iiiiii}iiiiiiciiiciiciiciiiiic{{d}ii}iic{{i}dd}iiiicdddddc{{d}ii}ic{{i}dd}dddc{d}ddc{i}cddddddc{{d}iii}ic{{i}ddd}iiic{i}ic{{d}ii}ddddc{iiiiii}iiiiiiciiic{i}iiiiicc{d}dddddc{i}iiic{{d}}ddddcc{iiiiii}iic{iii}dc{ii}c{{d}i}ic{iiii}iic{iiii}iiic{dd}iiicic{dddddd}iiic{d}ddc{{i}ddd}ddc{i}icdc{{d}iii}dc{{i}dd}dddc{{d}ii}ddddc{{i}ddd}iiiiiic{d}iiic{i}iiiiic{{d}ii}ddddc{{i}dd}dddc{d}iic{{d}iii}ic{{i}ddd}ddc{i}ic{i}ddc{d}ic{{d}}c{{i}dd}dc{ii}iiciiiiiic{{d}ii}dddddc{{i}ddd}iic{d}iiic{ii}ic{dd}iiic{{d}iii}ic{{i}ddd}c{i}dciiiiiic{d}iiic{d}c{{d}iii}iic{{i}ddd}iicdddc{i}iiic{{d}iii}c{d}ddc{{i}dd}ddcic{i}ddc{{d}i}iiic{{i}ddd}ic{i}ddc{{d}ii}ic{iiiiii}iiiiic{i}iiic{d}c{{d}iii}iic{{i}ddd}icddc{i}iiiiic{{d}ii}ddddc{{i}ddd}iicdddc{i}iiic{{d}}ddddc{{i}ddd}iic{ii}dc{i}ddc{d}iic{i}ddc{d}dciiic{i}iiic{{d}ii}ddc{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}iiiiiic{d}iiic{i}iiiiic{{d}ii}ddddc{{i}ddd}iicdddc{i}iiic{{d}ii}ddc{{i}ddd}iiiciiiiiciiiiiicdddddc{{d}ii}ic{{i}d}dc{d}ciiiiiicdddc{{d}ii}ddc{{i}ddd}iicdddcddddc{ii}dddciic{{d}}ddddddc{{i}ddd}iiiic{ii}cdddc{i}dc{{d}ii}iic{{i}d}dc{d}ciiiiiic{{d}ii}dddddc{{i}ddd}dddcddc{i}iiic{{d}ii}iic{{i}dd}iiicic{dd}ic{ii}dddciic{{d}ii}ddddc{{i}dd}iiiicdddddc{{d}ii}ic{{i}dd}dddc{d}ddc{i}cddddddc{{d}iii}ic{{i}ddd}iiic{i}ic{{d}ii}ddddc{iiiiii}iiiiiiciiic{i}iiiiicc{d}dddddc{i}iiic{{d}}ddddcc{iiiiii}iic{iii}dc{ii}c{{d}i}ic{iiii}iic{iiii}iiic{dd}iiicic{dddddd}iiic{d}ddc{{i}ddd}ddc{i}icdc{{d}iii}dc{{i}dd}dddc{{d}ii}ddddc{{i}dd}dddc{d}ddc{i}cddddddc{{d}iii}ic{{i}ddd}iiic{i}ic{{d}ii}ddddc{iiiiii}iiiiiicdciiic{{d}i}c{{i}ddd}iiiic{i}iiic{i}cddddddc{{d}iii}ic{iiiiii}iiiiic{dddddd}dddddc{{i}dd}iiic{dd}iiciiic{{d}iii}iic{{i}dd}iiicddddcdc{d}iiic{{d}iii}dc{iiiiii}iiiiic{i}iiic{d}c{{d}iii}iic{{i}dd}dddc{d}ddc{i}cddddddc{{d}iii}ic{{i}ddd}iiic{i}ic{{d}ii}ddddc{iiiiii}iiiiiiciiic{i}iiiiicc{d}dddddc{i}iiic{{d}}ddddc{{i}ddd}iic{ii}dc{i}ddc{d}iic{i}ddc{d}dciiic{i}iiic{{d}ii}ddc{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}iiiiiic{d}iiic{i}iiiiic{{d}ii}ddddc{{i}ddd}iicdddc{i}iiic{{d}ii}ddc{{i}dd}iiiiic{d}iiic{d}cic{i}iiic{{d}ii}ddc{{i}d}dc{d}ciiiiiicdddc{{d}ii}ddc{{i}dd}iiic{d}iicddciiiiic{{d}}c{{i}ddd}iiiic{ii}cdddc{i}dc{{d}ii}iic{{i}d}dc{d}ciiiiiic{{d}ii}iic{{i}ddd}dcc{{d}iii}ddddddc{iiiiii}iiiiiiciiiciiciiciiiiic{{d}ii}iic{{i}dd}iiiicdddddc{{d}ii}ic{{i}dd}dddc{d}ddc{i}cddddddc{{d}iii}ic{{i}ddd}iiic{i}ic ``` ]