text
stringlengths 180
608k
|
---|
[Question]
[
**This question already has answers here**:
[Calculate ISBN-13 check digit](/questions/342/calculate-isbn-13-check-digit)
(55 answers)
Closed 5 years ago.
A barcode of EAN-13 [symbology](https://en.wikipedia.org/wiki/Barcode#Symbologies) consists of 13 digits (0-9). The last digit of this barcode is its check digit. It is calculated by the following means (the barcode `8923642469559` is used as an example):
1. Starting from the second digit, sum up all alternating digits and multiply the sum by 3:
```
8 9 2 3 6 4 2 4 6 9 5 5 9
| | | | | |
9 + 3 + 4 + 4 + 9 + 5 = 34
|
34 × 3 = 102
```
2. Then, sum up all of the remaining digits, but do not include the last digit:
```
8 9 2 3 6 4 2 4 6 9 5 5 9
| | | | | |
8 + 2 + 6 + 2 + 6 + 5 = 29
```
3. Add the numbers obtained in steps 1 and 2 together:
```
29 + 102 = 131
```
4. The number you should add to the result of step 3 to get to the next multiple of 10 (140 in this case) is the check digit.
If the check digit of the barcode matches the one calculated as explained earlier, the barcode is valid.
---
More examples:
`6537263729385` is valid.
`1902956847427` is valid.
`9346735877246` is invalid. The check digit should be 3, not 6.
---
Your goal is to write a program that will:
1. Receive a barcode as its input.
2. Check whether the barcode is valid
3. Return 1 (or equivalent) if the barcode is valid, 0 (or equivalent) otherwise.
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in terms of bytes wins.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~45 40~~ 37 bytes
```
->n{(n+n.scan(/.(.)/)*''*2).sum%10<1}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWiNPO0@vODkxT0NfT0NPU19TS11dy0hTr7g0V9XQwMaw9n@BQlq0koWlkbGZiZGJmaWpqaVSLBdE0NjcyMLS0NLYxMjQSCn2PwA "Ruby – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 55 bytes
```
lambda s:not sum(int(i)*d for i,d in zip(s,[1,3]*7))%10
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYKi@/RKG4NFcjM69EI1NTK0UhLb9IIVMnRSEzT6Eqs0CjWCfaUMc4VstcU1PV0OB/QRFIYZqGkoWlkbGZiZGJmaWpqaWSpiYXVhkLoMx/AA "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 10 bytes
```
εNÉ·>*}OTÖ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3Fa/w52Htttp1fqHHJ72/7@FpZGxmYmRiZmlqaklAA "05AB1E – Try It Online")
**Explanation**
```
ε } # apply to each digit
NÉ # is the current index odd?
·> # double and increment(yielding 1 or 3)
* # multiply by the current number
O # sum all modified digits
TÖ # is evenly divisible by 10
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes
```
Check[#~BarcodeImage~"EAN13";1,0]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d85IzU5O1q5zimxKDk/JdUzNzE9tU7J1dHP0FjJ2lDHIFbtv76DQrWSmamxuZEZEFsaW5gq6SgoGVoaGFmamlmYmJsYmYMELI1NzMyNTS3MzY1MzJRqY/8DAA "Wolfram Language (Mathematica) – Try It Online")
A port of my [EAN-8 answer](https://codegolf.stackexchange.com/a/148208/74672).
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~29~~ 26 bytes
```
{:1[.comb «*»(1,3)]%%10}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2sowWi85PzdJ4dBqrUO7NQx1jDVjVVUNDWr/FydWKqRpqMRrKqTlF3GZmRqbG5kBsaWxhakOl6GlgZGlqZmFibmJkbkOl6WxiZm5samFubmRiZn1fwA "Perl 6 – Try It Online")
-3 bytes if a list of digits is acceptable.
### Explanation
```
{ } # Anonymous Block
.comb # Split into characters
«*»(1,3) # Multiply with 1 and 3 alternately
:1[ ] # Sum (conversion from base 1 is shorter than sum())
%%10 # Check if divisible by 10
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-!`, 14 bytes
```
¬Ë*(Ev ª3Ãx %A
```
---
```
¬Ë*(Ev ª3Ãx %A Full prgram.
¬ Convert to array -_-
Ë Map
* Multiply current number by
(Ev ª3Ã 1 if index is even, else 3
x sum
%A mod 10?
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=rMsqKEV2IKozw3ggJUE=&input=Ijg5MjM2NDI0Njk1NTkiIC0hCgo=)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 15 bytes
```
0=10|⊢+.×1 3⍴⍨≢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///38DW0KDmUdcibb3D0w0VjB/1bnnUu@JR56L/aY/aJjzq7XvUN9XT/1FX86H1xo/aJgJ5wUHOQDLEwzP4/6PeVdWPerdaqYcUlaaqP@puUXdLzClOVa89tCLt0AoNCwVLBSMFYwUzBRMgbQKkLRVMgdBSU8MMSBkrmAOFzaC0JZC2UDDV1DAEMg3AAqZASQugPnOwfnNNDZAakDHmQNoUKGUO1gkU0QQA "APL (Dyalog Unicode) – Try It Online")
Anonymous train, outputs 1 for True and 0 for False. TIO links to a prettified version of the output.
Totally not helped at all by @ngn or @dzaima (thanks guys).
### How:
```
0=10|⊢+.×1 3⍴⍨≢ ⍝ Main fn
≢ ⍝ Tally the argument (will always be 13)
1 3⍴⍨ ⍝ Reshape the vector (1 3) to 13 elements
⊢+.× ⍝ Multiply the original vector by that, then sum
10| ⍝ Modulo 10
0= ⍝ equals 0
```
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
```
lambda x,k=1,a=0:f(x/10,4-k,a+x*k)if x else a%10<1
```
[Try it online!](https://tio.run/##nctNCsIwEEDhq8xGaDRifmcyYm/iJmKDJbUW7SKePoYewcXbfPCW7/p4zaYm6OFap/i83SMUmXstY6/OqSsnraQ7ZhkPZZ/FmKDAMH0GiDutLvqfZXmP8wqpC2wsOuOQvWchm6C3ZLDFNvhNNCvDHoMjZ2gTtg7J@kDUTlF/ "Python 2 – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~23~~ 22 bytes
```
.(.)
$&$1$1
.
$*
M`
1$
```
[Try it online!](https://tio.run/##DcqrEYAwDABQnzkCVxA9mm8zAYodikBgEBz7l4rn3nt993P2Ke2t55QXwBkLFsiAKxwNCvZeg9iExEI1wJSdbAiuCiU2CrUqLuQQLOas1X3sHw "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 1 byte thanks to Martin Ender's comment on @Leo's Retina answer to the EAN-8 question. Explanation:
```
.(.)
$&$1$1
```
Triplicate alternate digits.
```
.
$*
```
Convert each digit to unary.
```
M`
```
Count the number of character boundaries, which is one more than the number of characters.
```
1$
```
Check for divisibilty by 10, but allow for the 1 we just added.
[Answer]
# Java 8, ~~69~~ ~~67~~ 62 bytes
```
n->{int s=0,m=3;for(;n>0;n/=10)s+=n%10*(m^=2);return s%10<1;}
```
-5 bytes thanks to *@OlivierGrégoire*.
-1 byte thanks to [my own 1-year old answer for the *Is my barcode valid?* challenge](https://codegolf.stackexchange.com/a/148269/52210), and *@OlivierGrégoire* to remind me of it.. xD
[Try it online.](https://tio.run/##hY7BbsIwEETvfMVeKjltCYkd27GM@YKWC8eqSCYEFJqsUewgVSjfnpqWa4W0c9jZ2dE72Yudn/ZfU9Va7@HdNnidATQY6v5gqxrWtxVg51xbW4SKtA6PgImO9hgVxwcbmgrWgGBgwvnqGt/Bm@y1M0wfXE80rjKNC5NniX8x@JRnz6TbGprovg5Dj@Cjtcz1ON1qz8OujX332otr9tBFLrIJfYPHj0@wyR/U5tuHukvdENJzPIUWCaYVKRVloqCFUJyrt@QX9d@w4ExSEaVYyR@Fc5VRxUVZyILKR2HFCiEZL6WMKPfwOBunHw)
**Explanation:**
```
s->{ // Method with long parameter and boolean return-type
int s=0, // Sum, starting at 0
m=3; // Multiplier, starting at 3
for(;n>0; // Loop as long as the input is not 0 yet
n/=10) // After every iteration: integer-divide the input by 10
s+= // Increase the sum by:
n%10* // The last digit of the input multiplied by:
(m^=2); // either 1 or 3 (alternating every iteration)
return s%10<1;} // Then return whether the sum is divisible by 10
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
D0;s2Sḅ3⁵ḍ
```
[Try it online!](https://tio.run/##y0rNyan8/9/FwLrYKPjhjlbjR41bH@7o/f//v4WlkbGZiZGJmaWpqSUA "Jelly – Try It Online")
-4 bytes thanks to Kevin Cruijssen (semi-port @Dennis)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~11~~ 10 bytes
```
!es*V*jT7l
```
Accepts input as a list of digits. Try it online [here](https://pyth.herokuapp.com/?code=%21es%2AV%2AjT7l&input=%5B8%2C9%2C2%2C3%2C6%2C4%2C2%2C4%2C6%2C9%2C5%2C5%2C9%5D&debug=0), or verify all test cases at once [here](https://pyth.herokuapp.com/?code=%21es%2AV%2AjT7l&test_suite=1&test_suite_input=%5B6%2C5%2C3%2C7%2C2%2C6%2C3%2C7%2C2%2C9%2C3%2C8%2C5%5D%0A%5B1%2C9%2C0%2C2%2C9%2C5%2C6%2C8%2C4%2C7%2C4%2C2%2C7%5D%0A%5B9%2C3%2C4%2C6%2C7%2C3%2C5%2C8%2C7%2C7%2C2%2C4%2C6%5D&debug=0).
```
!es*V*jT7lQQ Implicit: Q=eval(input())
Trailing QQ implied
jT7 10 in base 7 - yields [1,3]
* lQ Repeat the above len(input) times
*V Q Vectorised multiply the above with the input
s Take the sum
e % 10
! Logical not
```
*Edit: saved a byte by replacing `,1 3` with `jT7`*
[Answer]
# [R](https://www.r-project.org/), 65 bytes
```
function(b,y=b%/%10^(12:0)%%10)!sum(y[-1],y[(1:6)*2]*2)%%-10+y[1]
```
[Try it online!](https://tio.run/##FYtBCsMgEEX3vUUXgqYJdUadcQI5idhFCkIXTaBtFp7emsWDz/u8TytLK8f2/L32Ta9jXVZ1V2AfGnC2RvVprt/jrWuaII81aZjJDJgH7OcE9lYT5FZ0FHTk0ZOEIOZSNAXHSB1xMZwCxKIEip498inEeWIXInPPTPsD "R – Try It Online")
] |
[Question]
[
There's a confusing factor in the '[Curious](/help/badges/91/curious)' badge. The "Positive question record".
`(total questions - negative questions - closed - deleted)/total questions` is the formula of the question record. (negative, closed and deleted 'stack' with each other. that means if a question is negative and closed, it counts as two minus.)
Luckily, you know a list of your questions. Make a program that calculates your question record.
# The Input
You will be given an array of question datas. A question data is made of 2 datas.
* The votes (integer)
* The state (`o`(open), `c`(closed), `d`(deleted), `b` (closed *and* deleted) is the default, You may change the type and the characters for each states.)
# Examples
* `[[-1,'o'],[1,'o']]` => `0.5` (2 total, 1 minus points)
* `[[-1,'d'],[2,'c']]` => `-0.5` (2 total, 3 minus points)
* `[[-1,'b']]` => `-2` (1 total, 3 minus points)
* `[[23,'o'],[7,'c'],[7,'c'],[-1,'o'],[-5,'b'],[-11,'d'],[-3,'d'],[-3,'b'],[-15,'b']]` => `-0.77778`(The precision is 5 digits past decimal point, rounded half-up. fractions are acceptable) (Oh my, my question record is horrible.)
* `
('Minus points' is the sum of negative, closed and deleted.)
# Rules
* Format of input is your choice. You don't necessarily need to use the format in the Examples.
[Reference](https://meta.stackexchange.com/questions/290545/how-is-a-positive-question-record-calculated)
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 8 bytes
I've been waiting to use dc's feature, that the input is both data and code, for quite some time.
```
0d?n47Pp
```
The idea behind the script is that all of the number crunching will be done by the question's state representation, a valid input string. The main script's task is then to initialize the counters, read the input (and execute it as code at the same time), and print the result when done, as a fraction.
Here are the strings I use to represent the state. The OP allows non-char types!
* '`o`' -> "1r[1-]sX0>X**0-**+r1+r"
* '`c`' -> "1r[1-]sX0>X**1-**+r1+r"
* '`d`' -> "1r[1-]sX0>X**1-**+r1+r**rr**"
The extra "**rr**" part at the end changes nothing, it is there to differentiate the `d` state from `c`.
* '`b`' -> "1r[1-]sX0>X**2-**+r1+r"
**[Try it online!](https://tio.run/nexus/dc#@2@QYp9nYh5Q8P@/kbGCYVG0oW5scYSBXYSBrnaRoXaRgjmyoCE@wXhDbPrjTZFFjeBqDbEYUQSUMCZGHGEMNtMB)** The default input there is the last example.
**Test run:** from the 2nd example. Negative numbers in dc are given with `_` as the minus sign. This is allowed by this meta [consensus](http://meta.codegolf.stackexchange.com/a/10100/59010).
```
dc -f question_record.dc <<< "_1 1r[1-]sX0>X1-+r1+rrr 2 1r[1-]sX0>X1-+r1+r"
-1/2
```
---
**Explanation of the script:**
```
0d
# push 0 twice. The bottom cell will keep track of the number of questions, and the
#top cell of the sum part of the score.
?
# read input, which in this case is actually pairs of (data, code), that do all the
#number crunching
n47Pp
# print the 2 cells as a fraction: print top, print '/' (ASCII 47), print bottom
```
**Explanation of the state's representation:** I take the `c` state as example code
The stack at the start of this snippet is composed of the two bottom counters, plus the integer data (the votes) that was pushed on top before this. The snippet contains both the integer value of the state (minus points) and the dc code needed to apply it.
```
1r[1-]sX0>X1-+r1+r
```
I work with the following iterative algorithm (pseudo-code) to calculate the "positive question record":
```
result = 0
# main script: `0`
sum = 0
# main script: `d`
for each input question; do
# main script:`?`
sum += 1
# snippet: `1`
sum -= v (0 if total votes are positive, 1 if negative)
# snippet: `r[1-]sX0>X`
sum -= minus_points (based on state)
# snippet: `1-`, or `0-`, or `2-`
result++
# snippet: `r1+`
done
result = sum / result
# main script:`n47Pp`
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
F<0S÷LC
```
**[Try it online!](https://tio.run/nexus/jelly#@@9mYxB8eLuP8//D7Y@a1vz/H82lEB2ta6gTbaBjEBurEw1jxXLpQMSBGCxhBJLQNUSVgfONjOEmmMMUojCRrNA1hesFMZDs0DXGYMNUmSLZFwsA "Jelly – TIO Nexus")**
Each entry in the input is a list of the vote count (an integer) and the status (a list). The status is a list of two integers, effectively a negated bit-flag:
```
open: [ 0, 0]
closed: [-1, 0]
deleted: [ 0,-1]
closed & deleted: [-1,-1]
```
The tally of **(negativeQuestions + closed + deleted)** is then just the number of negative numbers and the final formula is then rearranged as **1-((negativeQuestions + closed + deleted)/totalQuestions)**:
```
F<0S÷LC - Main link: list as described above, d
F - flatten d into a single list
<0 - less than 0 (vectorises)
S - sum
L - length of d
÷ - divide
C - complement (1 minus that)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
˜0‹O¹g/(>
```
[Try it online!](https://tio.run/nexus/05ab1e#@396jsGjhp3@h3am62vY/f8fHW1krBNtoGMQG6sTbQ5i6RqiMXUN4Qp0TcFcmLghmAeRMcZgw1Qh9MQCAA "05AB1E – TIO Nexus")
Uses Jonathan Allan's [algorithm](/a/112293/41024), so the inputs for the state are as follows:
```
open: [ 0, 0]
closed: [-1, 0]
deleted: [ 0,-1]
closed & deleted: [-1,-1]
```
Explanation:
```
˜0‹O¹g/(> "The program."\
˜ "Deep-flatten the list."\
0‹O "Check how many numbers are negative."\
¹g "Push the original list's length."\
/ "Float-divide top two stack items."\
(> "Push the complement of ToS."\
```
[Answer]
# Haskell, 70 57 bytes
13 bytes saved thanks to @Laikoni!
```
f=fromIntegral.length
v#s=(f v-(f.filter(<0))v+sum s)/f v
```
## Input format
2 lists of same length, the first containing the vote counts, the second containing the question statuses where open is 0, closed/deleted is -1 and closed+deleted ist -2.
## Readable
```
record :: [Int] -> [Int] -> Float
record v s = fromIntegral (length v - (length.filter(<0)) v + sum s)
/ (fromIntegral.length) v
```
## Explanation
Nothing special. Number of votes minus the number of negative questions plus the sum of the statuses, using the input format.
This solution gets inflated quite a bit because Haskell requires the arguments of a real divison to both be real numbers. In this case, they are Integers instead, so we have to call `fromIntegral` on them.
[Answer]
# [Python 3](https://docs.python.org/3/), 35 bytes
```
lambda d:1-str(d).count('-')/len(d)
```
Unnamed function taking a list, `d`.
**[Try it online!](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqiQYmWoW1xSpJGiqZecX5pXoqGuq66pn5OaBxT5X5JaXFKsYKsQraAQHa1rqBNtoGMQG6ujEA1jxnIpwIAOVAkQQ9QYgdToGuJShEXGyBhhgzlMNxob2RW6pnCTwDLItusaY3LgCk2xuSCWiystv0gB5GeFzDwwXWzFxVlQlAkMFRBPE8ZJg3DhfM3/AA "Python 3 – TIO Nexus")**
Each entry in `d` is a list of the vote count (an integer) and the status (a list). The status is a list of two integers, effectively a negated bit-flag:
```
open: [ 0, 0]
closed: [-1, 0]
deleted: [ 0,-1]
closed & deleted: [-1,-1]
```
The tally of **(negativeQuestions + closed + deleted)** is then just the number of negative numbers, which is shortest to count by counting the hyphens in `d` cast to a string. The final formula is then rearranged as **1-((negativeQuestions + closed + deleted)/totalQuestions)**
---
### Python 2, 35 bytes
```
lambda d:1-1.*`d`.count('-')/len(d)
```
Same approach, but uses the `__repr__` shorthand ``...`` and multiplies by `1.` to cast the count to a float.
[Answer]
# [Python 3](https://docs.python.org/3/), 42 bytes
```
lambda d:sum(1-s-(v<0)for v,s in d)/len(d)
```
[Try it online!](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqiQYlVcmqthqFusq1FmY6CZll@kUKZTrJCZp5CiqZ@TmqeRovm/oCgzr0QjTSM6WtdQxyBWJxpExmpq/gcA "Python 3 – TIO Nexus")
---
**Input**: `[[votes, status],[votes, status],...]`
* open : 0
* closed : 1
* deleted : 1
* closed and deleted : 2
Example : `[[-1,0],[1,1],[0,2]]`
[Answer]
# [Röda](https://github.com/fergusq/roda), 38 bytes
```
f a{[-#[a()|[0]for i if[i<0]]/#a*3+1]}
```
[Try it online!](https://tio.run/nexus/roda#@5@mkFgdrascnaihWRNtEJuWX6SQqZCZFp1pYxAbq6@cqGWsbRhb@z83MTNPoZpLAQjSNKLBNAgYGesoGIAQXMRcR0HXkIAIhIsiYgpRBMRIqiDKUMSMsQphaoWbBxaL1eSq/Q8A "Röda – TIO Nexus")
It's a function that takes one argument, an array, that has three values per each question: the vote count, close status and delete status. Statuses are either -1 (closed or deleted) or 0 (not closed or not deleted).
Explanation:
```
f a{[-#[a()|[0]for i if[i<0]]/#a*3+1]}
f a{ } /* function f with parameter a */
a()| /* push values in a to the stream */
for i /* for each value in the stream: */
if[i<0] /* if the value is negative: */
[0] /* push 0 to the stream */
[ ] /* return: */
#[ ] /* number of values in the stream */
- /* negated */
/#a*3 /* divided by number of questions */
+1 /* plus 1 */
```
Example:
```
main {
f([
23, 0, 0,
7, -1, 0,
7, -1, 0,
-1, 0, 0,
-5, -1, -1,
-11, 0, -1,
-3, 0, -1,
-3, -1, -1,
-15, -1, -1
])
}
```
[Answer]
# JS: 108 bytes
Note the first slice argument should be 1 if not running from a script. I figured that the scores don't need to be associated with each post since the effect stacks anyway.
Call by script:
`node code.js totalQs numOpen numClosed numDeleted score1 score2 ...`
The code:
`[t,o,c,d,...s]=process.argv.slice(2).map(v=>parseInt(v));console.log((t-c-d-s.reduce((c,v)=>v<0?c+1:c,0))/t)`
## Explanation needed?
`[a, ...b] = [1,2,3]` gives `a==1, b==[2,3]`
`process.argv.slice(2)` gets all the arguments except the first (path to node and script respectively).
`.map(v=>parseInt(v))` converts each element to a number. Hopefully nobody tries NaN inputs ;).
`s.reduce((c,v)=>v<0?c+1:c,0)` loops over `s` (scores) with a function taking the counter `c` and value `v`. If `v` (the score of any post) is `<0` then we `+1` our counter to get the number of negative posts.
`(t-c-d-numberNegative) / t` is the total, minus closed, minus deleted, minus negative, divided by total.
[Answer]
# Octave, ~~45~~ ~~43~~ ~~42~~ 37 bytes
OP has just said in a comment that it's OK to take the state of questions on this format:
```
Open: 0
Closed: -1
Deleted: -1
Closed+Deleted: -2
```
That makes the challenge quite a bit simpler:
```
@(v,s)(rows(v)-v<0-sum(s))/rows(v)
```
---
Old answer, from when the rules were a bit more strict.
```
@(v,s)((r=nnz(s))-nnz([v<0,s<100,s<99]))/r
```
This takes two variables as input, the votes, `v` and the state `s`, both as row vectors. It counts the number of rows, subtracts the total amount of negative votes, the number of close votes and the number of delete votes, then finally divides by the number of questions again.
[Answer]
# Mathematica, 32 bytes
```
1-Count[#,a_/;a<0,∞]/Length@#&
```
Anonymous function. Takes a list of pairs of integers and states, where the states are translated from the problem output specification as shown below:
```
o: {0, 0}
c: {-1, 0}
d: {0, -1}
b: {-1, -1}
```
Returns a rational number as output. The Unicode character is U+221E INFINITY for `\[Infinity]`. The algorithm used is conceptually similar to those of other answers.
[Answer]
## JavaScript (ES6), ~~53~~ 46 bytes
```
a=>a.reduce((r,[v,s])=>r-(v<0)-s,l=a.length)/l
```
Takes the state as `0` for a closed NOR deleted question, `1` for a closed XOR deleted question, `2` for a closed AND deleted question.
[Answer]
## Batch, 99 bytes
```
@set/ar=n=o=0,c=d=-1,b=-513
@for %%v in (%*)do @set/a"r+=%%v>>9,n+=1
@set/ar+=n/=2
@echo %r%/%n%
```
Takes input as a single list of votes (limited to ±500 per question) and statuses. Prints an unreduced fraction. 218 bytes to print using decimals:
```
@set/ar=n=o=0,c=d=-1,b=-513
@for %%v in (%*)do @set/a"r+=%%v>>9,n+=1
@set/a"n/=2,r=r*200000/n+200001,r+=r>>31,r>>=1
@if %r:-=% geq 100000 echo %r:~,-5%.%r:~-5%&exit/b
@set/a"r+=(r>>31|1)*1000000
@echo %r:~,-7%0.%r:~-5%
```
] |
[Question]
[
Your task is to write the shortest possible Pong game without human interaction, so AI plays vs AI. I assume all of you know Pong, just to make sure, this is the target (just as running code):
<http://www.youtube.com/watch?v=xeEFMhdnR6c>
**The following game rules apply:**
1. No ASCII "graphics".
2. You must actually have code to count the scores, even if the AI never scores.
3. It must be possible to adjust the size of the output window/area in some way to any (reasonable) size. Which means you must include some form of output scaling.
4. No need for a menu or other features of the game, just what's in the video.
**The following [play fair](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) rules apply as well:**
* No language specifically designed for code golfing.
* You may only use standard libraries offered by the language of your choice. No external library downloading, no jQuery, no full-sized game-libraries.
Exception: if no library for graphical output is available with the default offering of the language of your choice, you are allowed to use a library that offers basic graphical output similar to what other languages include in their basic library set.
* `import` statements (or however they are called in your language) can be skipped in the character count.
* Doorknob-rule: The paddles may not be bigger than 15% of the game area.
**Bonus points:**
* -50 if you include sound. External sound sources (e.g. wav) do not need to be added to the char count and may be downloaded during execution. If you choose to copy & paste the data into the code, only the actual data is allowed to be skipped for character count.
* Another -150 (for -200 total) if you do not use external sounds but generate it. Generate means: you have some form of sound synthesizing, copy & pasting e.g. wav data does not count.
[Answer]
# Pure HTML and CSS, 355 characters
```
<div class=p></div><div style="height:300px"></div><div class=p></div><div id=b></div>0-0<style>.p{width:99px;height:20px;background:#000}*{margin:0}#b{position:absolute;background:#F00;width:20px;height:20px;animation-name:b;animation-duration:3s;animation-iteration-count:infinite;left:40px}@keyframes b{from{top:20px}50%{top:300px}to{top:20px}}</style>
```
You may need an up-to-date or beta browser for the CSS `animation` properties.
[Here is a fiddle](http://jsfiddle.net/bvt8E/embedded/result/), with `-webkit-` vendor prefixes added so that it works in latest Chrome.

The ball just bounces back and forth. The AIs are extremely smart and know not to move.
The `0-0` at the bottom is the score, and you can resize the window.
[Answer]
# Scratch, 1605 – 50 = 1555
~~I don't know how to count the score here and~~ it doesn't meet the "resizing the window" rule... I just thought it was fun. Some unrealistic speed though, and one known bug: if the ball hit the bar at an almost vertical angle, it will somehow get trapped.
Edit: updated score as per [community consensus](http://meta.codegolf.stackexchange.com/a/5013/12205).
The bars will only move if the ball is moving towards its direction. I could make it always move, but I think that would be too boring.
Sprite1: the "ball"

Sprite2: the right vertical "bar" (don't know what it's called)

Sprite3: the left vertical "bar": essentially the same as Sprite2, except the first `if` condition, which is changed to `direction of Sprite1 < 0`
Note: you can change the "intelligence" of the AI by changing the glide speed. They will move slower, so higher chance of missing the ball.
Sprite4 and Sprite5 are two white vertical bars placed on either side of the "field". They have no scripts.
Code used for byte counting: (Using snippet to hide code)
```
when green flag clicked
set [score1 v] to [0]
set [score2 v] to [0]
forever
go to x: (0) y: (0)
wait (1) secs
point in direction (pick random (70) to (290))
repeat until <<touching [Sprite4 v] ?> or <touching [Sprite5 v] ?>>
move (10) steps
if <touching color [#000] ?> then
play sound [pop v]
point in direction (((360) - (direction)) + (pick random (-5) to (5)))
end
if <touching [edge v] ?> then
if on edge, bounce
point in direction ((direction) + (pick random (-5) to (5)))
end
end
play sound [216090__richerlandtv__bad-beep-incorrect v]
if <touching [Sprite4 v] ?> then
change [score1 v] by (1)
end
if <touching [Sprite5 v] ?> then
change [score2 v] by (1)
end
end
when green flag clicked
forever
if <[0] < ([direction v] of [Sprite1 v])> then
if <([y position v] of [Sprite1 v]) > [140]> then
glide (.1) secs to x: (x position) y: (140)
else
if <([y position v] of [Sprite1 v]) < [-140]> then
glide (.1) secs to x: (x position) y: (-140)
else
glide (.1) secs to x: (x position) y: ([y position v] of [Sprite1 v])
end
end
end
end
when green flag clicked
forever
if <([direction v] of [Sprite1 v]) < [0]> then
if <([y position v] of [Sprite1 v]) > [140]> then
glide (.1) secs to x: (x position) y: (140)
else
if <([y position v] of [Sprite1 v]) < [-140]> then
glide (.1) secs to x: (x position) y: (-140)
else
glide (.1) secs to x: (x position) y: ([y position v] of [Sprite1 v])
end
end
end
end
```
Note: Code automatically generated using [scratchblocks generator](http://scratchblocks.github.io/generator/), modified as somehow the generator doesn't correctly handle decimal numbers (treating .1 as 0).
See it run online [here](http://scratch.mit.edu/projects/19002979/).
[Old version](http://scratch.mit.edu/projects/19000484/) (the bars move randomly).
A screenshot:

[Answer]
# HTML / JavaScript, 476
```
<body onload="for(p in r=c.getClientRects()[0])top[p[0]]=c[p]=r[p];t=c.getContext('2d');t.T=t.fillText;t.R=t.fillRect;A=B=0;a=b=h/2;H=h/9|0;x=w/2;y=h/2;v=w/550;z=h/250;setInterval('x<w/3&&(a+=a<y?3:-3);x>2*w/3&&(b+=b<y?3:-3);y<0|y>h?z=-z:0;x<8&&y>a&&y<a+H||x>w-8&&y>b&&y<b+H?v=-v:0;x+=v;y+=z;(x<0?++A:x>w?++B:0)&&(x=w/2,y=h/2);with(t)clearRect(0,0,w,h),R(x,y,5,5),R(2,a,6,H),R(w-8,b,6,H),T(A,H,9),T(B,w-H,9)',16)"><style>*{margin:0;width:100%;height:100%}</style><canvas id=c>
```
**Un-golfed:**
```
<body>
<style>*{margin:0;width:100%;height:100%;}</style>
<canvas id="c"></canvas>
<script>
// Resize canvas
for(p in r=c.getClientRects()[0])top[p[0]]=c[p]=r[p];
// Get drawing context
t = c.getContext('2d');
// Shorter names
t.T=t.fillText;t.R=t.fillRect;
// Scores
A=B=0;
// Paddles position
a=b=h/2;
H=h/9|0;
// Ball position
x=w/2;
y=h/2;
// Ball velocity
dx=w/550;
dy=h/250;
setInterval(function() {
// Process AI
x<w/3&&(a+=a<y?3:-3);
x>2*w/3&&(b+=b<y?3:-3);
// Wall collisions
y<0|y>h?dy=-dy:0;
// Paddle collisions
x<8&&y>a&&y<a+H||x>w-8&&y>b&&y<b+H?dx=-dx:0;
// Update ball position
x+=dx;
y+=dy;
// Update score if the ball is behind the paddle.
// If so, reset the ball position
(x<0?++A:x>w?++B:0)&&(x=w/2,y=h/2);
with(t){
// Clear screen
clearRect(0,0,w,h);
// Draw ball
R(x,y,5,5);
// Draw paddles
R(2,a,6,H);
R(w-8,b,6,H);
// Draw scores
T(A,H,9);
T(B,w-H,9);
}
},16);
</script>
</body>
```
] |
[Question]
[
Given an arbitrary array of octets, and an offset measured in bits, the goal is to bitwise left rotate the array by the specified number of bit positions as if the entire array were a single contiguous number. Byte order is big-endian.
As an example, given the (not zero terminated) ASCII string `abcd` and a shift of 5 bits. we turn this array of bytes:
```
01100001 01100010 01100011 01100100
```
into this one:
```
00101100 01001100 01101100 10001100
```
Notice that the bits propagate to the left from byte to byte and that they wrap back around.
Now that I think you've all got the idea, the rules:
* Your program should accept an arbitrary unsigned integer (**"number of bits to shift" non-negative, possibly zero, limited only by the size of the standard integer type**) and a raw stream of octets of arbitrary length (**you may assume the length is strictly positive**). How you accept these is up to you (**file,stdin,parameter are all acceptable**). Your program should output the shifted bytes in an analogous manner (**i.e. file,stdout,return value**).
* "Cut-and-paste" style code is **not allowed**. That is, you can't rely on your user to set the value of a certain variable before calling your code.
* The byte ordering is **big-endian**.
* Shortest code wins.
**EDIT: It's clear now I should have restricted the input output format a bit more. The solutions that are using ASCII 0s and 1s directly aren't very interesting unfortunately.**
[Answer]
## C 89
Shifting is done in-place in `*s` array. `l` is array length and `f` is number of bits to shift.
```
void f(char*s,l,f){while(f--)for(int i=0,j,c=*s<0;s[j=i++]<<=1,s[j]+=i%l?s[i]<0:c,i<l;);}
```
[Answer]
# C#, ~~321~~ ~~308~~ 304 bytes
```
var y=System.Text.Encoding.UTF8.GetBytes(args[1]).ToList();int i=int.Parse(args[0]),m,j=0;for(;i>7;y.RemoveAt(0),i-=8)y.Add(y[0]);byte c=0,u;for(m=8-i;j<y.Count;j++){u=(byte)((255<<m&y[j])>>m);if(j<1)c=u;y[j]<<=i;if(j>0)y[j-1]|=u;}y[^1]|=c;Console.Write(System.Text.Encoding.UTF8.GetString(y.ToArray()));
```
Dropped 13 bytes thanks to awesome suggestions from **Kevin**, and another 4 bytes with suggestions from **ceilingcat**!
Uncompressed version below. This uses C# v9 [top-level statements](https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/top-level-statements) feature, so the program below compiles into an executable. Program expects two arguments: bits and bytes in a form of a UTF8 string (e.g., execute is as `./program 5 abcd`).
```
// get bytes from the provided provided (assumed in UTF8)
var y = System.Text.Encoding.UTF8.GetBytes(args[1]).ToList();
int i = int.Parse(args[0]), m, j = 0; // i - how many bits to shift
// rotate full bytes first if bits >= 8
for (; i > 7; y.RemoveAt(0), i -= 8) // drop the first byte
y.Add(y[0]); // append first byte to the end
byte c = 0, u; // c keeps the bits to wrap around from first byte to the last
// u will be used to shift bits between neighboring bytes
// now i < 8 guaranteed
for (m = 8 - i; j < y.Count; j++)
{
u = (byte) ((255 << m & y[j]) >> m); // bits to shift
if (j < 1) c = u; // if we are on the first byte, store them in c
y[j] <<= i; // shift the byte
if (j > 0) y[j - 1] |= u; // shift the cutoff bits to prev byte
// if current byte is not the first byte
}
y[^1] |= c; // wrap around the bits
// and output
Console.Write(System.Text.Encoding.UTF8.GetString(y.ToArray()));
```
[Answer]
## Sed, 35 bytes
```
:a
s/1-\(.\)\(.*\)/-\2\1/
ta
s/.//
```
Takes input on stdin, as number of bits to shift by in unary, followed by `-`, followed by the binary stream, without spaces. e.g.
```
echo 11111-01100001011000100110001101100100 | sed -f a.sed
```
outputs
```
00101100010011000110110010001100
```
[Answer]
## Perl, 33 (32 + 1 for `-p`)
```
1while(s/1-(.)(.*)/-$2$1/);s/.//
```
Takes input on stdin, as number of bits to shift by in unary, followed by -, followed by the binary stream, without spaces. e.g.
```
echo 11111-01100001011000100110001101100100 | perl -pe '1while(s/1-(.)(.*)/-$2$1/);s/.//'
```
[Answer]
# APL (1)
it's a builtin
```
5⌽0 1 1 0 0 0 0 1 0 1 1 0 0 0 1 0 0 1 1 0 0 0 1 1 0 1 1 0 0 1 0 0
0 0 1 0 1 1 0 0 0 1 0 0 1 1 0 0 0 1 1 0 1 1 0 0 1 0 0 0 1 1 0 0
```
[Answer]
## APL (23)
```
{2⊥⍉(8,⍨⍴⍵)⍴⍺⌽,⍉⍵⊤⍨8/2}
```
This is a function that takes the rotation as its left argument and the byte array as its right argument (as numbers).
```
5{2⊥⍉(8,⍨⍴⍵)⍴⍺⌽,⍉⍵⊤⍨8/2}97 98 99 100
44 76 108 140
```
[Answer]
# C, 142 bytes
It's huge :(
Input is taken from parameters, `puts` shifted string to stdout.
```
main(int d,char**v){d=strtoul(v[1],0,10);while(d--){v[1]=v[2]+1;**v=*v[2];strcpy(v[2],v[1]);while(*(v[1]++));*v[1]--=0;*v[1]=**v;}puts(v[2]);}
```
[Answer]
# Python, 43 42 bytes
Takes shifts and data from stdin, returns shifted data in stdout.
Input format is `<shift_amount>\n<data>`
```
a=-input();b=raw_input();print b[a:]+b[:a]
```
[Answer]
# q (18)
depending on how picky you are about exact output format and launch, i can get it down to 18 in q:
```
$ ls -l shift*.q
-rw-r--r-- 1 daviaaro ccM504 19 Jan 8 16:05 shift1.q
-rw-r--r-- 1 daviaaro ccM504 22 Jan 8 16:07 shift2.q
-rw-r--r-- 1 daviaaro ccM504 25 Jan 8 16:07 shift3.q
$ cat shift1.q
(rotate)."I*"$.z.x
$ q shift1.q 5 "01100001011000100110001101100100" <&-
"00101100010011000110110010001100"
$ cat shift2.q
-1(rotate)."I*"$.z.x;
$ q shift2.q 5 01100001011000100110001101100100 <&-
00101100010011000110110010001100
$ cat shift3.q
-1(rotate)."I*"$.z.x;
\\
$ q shift3.q -q 5 01100001011000100110001101100100
00101100010011000110110010001100
$
```
of course, it helps that the actual function happens to be in the standard lib :)
all three interpret two command-line args as int and string and rotate the string by the int
the first case just shows the string representation of the string (a (mostly) pasteable notation)
the second and third cases print it
in the first two cases, i'm relying on q to quit itself when run without stdin
the third case has an explicit quit command (and an extra command-line arg to suppress the REPL welcome message, which is automatically suppressed in the other cases due to stdin being closed)
note btw that the byte counts from ls include newlines, even on the two one-line files, and since q is fine with code files that are missing their last newline, the actual counts are 18, 21, and 24
ETA:
how do you feel about this?
```
$ q<<<'5 rotate 01100001011000100110001101100100b'
00101100010011000110110010001100b
$
```
is it valid? how would you count it? (the `b` is q's notation for a binary vector/bitstring. if you prefer, it would also work on the string version at the cost of an extra character)
[Answer]
**C# (210)**
```
void r(byte[] a, int n){string s="";for(int i=0;i<a.Length;i++)s+=Convert.ToString(a[i],2).PadLeft(8,'0');s=s.Substring(n)+s.Substring(0,n);for(int i=0;i<a.Length;i++)a[i]=Convert.ToByte(s.Substring(i*8,8),2);}
```
This is a function 'r' in C# that takes a byte[] and an integer n.
It does in-place rotation, so the original array is rotated, and nothing is returned.
I convert the byte array to string of bits, rotate, and convert back to bytes.
It seems like a cheat, but the requirements does not prevent it.
The pretty code is following:
```
void r(byte[] a, int n)
{
string s = "";
for (int i = 0; i < a.Length; i++)
s += Convert.ToString(a[i], 2).PadLeft(8, '0');
s = s.Substring(n) + s.Substring(0, n);
for (int i = 0; i < a.Length; i++)
a[i] = Convert.ToByte(s.Substring(i * 8, 8), 2);
}
```
[Answer]
# Python 3, 40 Bytes
```
s,n=open(0);print(n[int(s):]+n[:int(s)])
```
[Try It Online!](https://tio.run/##K6gsycjPM/7/v1gnzza/IDVPw0DTuqAoM69EIy8aRBZrWsVq50VbQdixmv//m3IZGBoaAIEhhAZiCA3hAxEA)
This is basically a port of Oberons answer, and takes the same input from stdin as his Python 2 solution:
```
in:
5
01100001011000100110001101100100
out:
00101100010011000110110010001100
```
this is also my first post on this site, happy to be here!
] |
[Question]
[
*Inspired by [this question](https://stackoverflow.com/questions/18806914/how-many-pairs-are-in-this-array-of-strings)*
Your challenge is very simple: take input in the form of `lookupString string1 string2 ... stringN` and output how many pairs of strings there are.
But there's a catch! There are two ways of interpreting "pairs." The first way is combinations. For example,
```
1 2 3 4
orange orange apple orange orange
```
(the first `orange` is the lookup string) has 3 pairs of oranges, since there is #1 and #3, #3 and #4, and #1 and #4.
The second way of interpreting it is adjacent pairs. For example, the same input would have a result of 1 with this interpretation, since there's only one pair in which both oranges are next to each other. (#3 and #4)
You must write two programs, one with the first interpretation and another with the second. Your score is the sum of the length of the two programs. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest score wins.
[Answer]
# J, 24 characters
### Anywhere - ~~14~~ 11
```
2!+/}.{.=;:
```
is 2 choose (`2!`) sum (`+/`) of the beheading (`}.`) of the first row (head) (`{.`) of the self-classification (`=`) of the words (`;:`) of its argument
beheading means "drop the first element and return the rest".
### Adjanced - 13
```
+/2*/\}.{.=;:
```
is the sum (`+/`) of products (ANDs) within each two-element prefix (`2*/\`) of the beheading (`}.`) of the head (`{.`) of the self-classification (`=`) of the words (`;:`) of its argument
ex:
```
s=.'pear pear apple pear pear'
+/#\2}.#~{.=;:s
3
+/2*/\}.{.=;:s
1
```
[Answer]
# Python 3, 48 + 59 = 107
## Anywhere – 48
```
s,*L=input().split()
c=L.count(s)
print(c*~-c/2)
```
## Adjacent – 59
```
s,*L=input().split()
print(list(zip(L,L[1:])).count((s,s)))
```
[Answer]
# Ruby, 38 + 45 = 83
### Anywhere: 38
* -2 chars: Two statements was shorter than one.
```
l,*a=gets.split
p (n=a.count(l))*~-n/2
```
### Adjacent: 45
* -2 chars: Borrowed `x==[l,l]` from Doorknob.
* -2 chars: `find_all` => `select`
* -12 chars: `select` => `count`
```
l,*a=gets.split
p a.each_cons(2).count([l,l])
```
[Answer]
# Mathematica ~~33+42 = 75~~ 31+40 = 71
**Program 1**
```
Binomial[Count[Rest@#, #〚1〛, 2] &
```
Example
```
Binomial[Count[Rest@#, #〚1〛, 2] &[{"orange", "orange", "apple", "orange", "orange"}]
```
>
> 3
>
>
>
---
**Program 2**
```
Count[Partition[Rest@d, 2, 1], {e = #〚1〛, e}] &
```
Example
```
Count[Partition[Rest@d,2,1],{e=#〚1〛,e}] &[{"orange","orange","apple","orange", "orange"}]
```
>
> 1
>
>
>
[Answer]
## Ruby, 46 + 58 = 104
Posting my own solution first as I always do:
**Anywhere - ~~49~~ 46**
```
l,*a=gets.split;p ((1..a.count(l)).inject:*)/2
```
**Adjacent - ~~65~~ 58**
```
l,*a=gets.split;c=0;a.each_cons(2){|x|c+=1if x==[l,l]};p c
```
`l,*a` stolen from daniero :P
[Answer]
# R : 82
### Anywhere: 38 characters
```
a=scan(,"")
choose(sum(a[-1]==a[1]),2)
```
`sum(a[-1]==a[1])` returns the number of corresponding item and `choose` computes the corresponding binomial coefficient.
### Adjacent: 44 characters
```
a=scan(,"")
sum(diff(which(a[-1]==a[1]))==1)
```
`which(a[-1]==a[1])` returns the indices of the matching items, `diff` computes the difference between those indices and `sum(...==1)` returns the number of differences being 1 (i. e. the number of pairs of adjacent matching items).
[Answer]
# K, 20 + 44 = 64
### Anywhere: 20
```
{-1++/a~\:*a:" "\:x}
```
### Adjacent: 44
```
{+/min'(*h)~/:/:(2*!-_-(#a)%2)_a:1_h:" "\:x}
```
.
```
k){-1++/a~\:*a:" "\:x}"orange orange apple orange orange"
3
k){+/min'(*h)~/:/:(2*!-_-(#a)%2)_a:1_h:" "\:x}"orange orange apple orange orange"
1
```
[Answer]
# JavaScript - 166 chars
```
F=function(A){return A.match(RegExp(A.split(' ')[0], 'g')).length-1}
G=function(A){C=0;R=A.split(' ').splice(1);for(i=0;i<R.length-1;i++)R[i]==R[i+1]?C++:0;return C}
```
Edited to be separate functions.
] |
[Question]
[
~~Write a program that outputs the number 0.~~
That's a bit trivial, isn't it?
Let's sort all distinct permutations of your code in lexicographical order. When **any** of these codes are run, it should output the its location in the array (0-indexed or 1-indexed).
This means that your code must be the lexicographically smallest permutation of your code possible.
For example, if your code is `ABB`, then `ABB` -> 0; `BAB` -> 1; `BBA` -> 2.
## Rules
* Out of all distinct permutations of your code, it must be the lexicographically smallest.
* Your program must be at least **3** bytes long.
* "Output" represents any acceptable output: on the stack, to STDOUT, as a return value, as an exit code, etc.
* Your program is to not take any form of input.
* This is [code-bowling](/questions/tagged/code-bowling "show questions tagged 'code-bowling'"), so **longest** code wins.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), bytes = score
```
...
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fT0/v/38A "brainfuck – Try It Online")
**How it works**: this program only has one distinct permutation and it outputs 0. It trivially satisfies all the other restrictions. The score can be made arbitrarily large by adding more `.`.
[Answer]
# [Python 2](https://docs.python.org/2/), score = arbitrary
```
000
```
[Try it online!](https://tio.run/##K6gsycjPM/r/38DA4P9/AA "Python 2 – Try It Online")
Returns through exit code, which is always `0`.
The source code is `0` repeated arbitrary many times. Since there's only 1 permutation of the source code, the permutation number is always `0`.
[Answer]
# [!@#$%^&\*()\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), 548+++ bytes
```
#^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
[Try it online!](https://tio.run/##S03OSylITkzMKcop@P9fOW4UjAL84P///wA "!@#$%^&*()_+ – Try It Online")
This can also be just`#^^`. # prints and ^ increments. Please tell me if this is not lexicographic order, instead of downvoting.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), Arbitrarily large number of bytes.
```
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
```
[Try it online!](https://tio.run/##S0n@/99gFIyCUTDswf@C/wA "dc – Try It Online")
No matter how many `0`s you write, it will leave a `0` on the stack, which is an acceptable output form for the challenge. (The `p` in the TIO footer prints the stack so you can see what it is.)
Of course, the only permutation is the program itself.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 3 bytes (3 distinct permutations)
Outputs via unary, with a different set of output: `2 -> 3 -> 4`.
```
00\
```
[Try it online!](https://tio.run/##y00syUjPz0n7/9/AIOb/fwA)
## Explanation
```
00\
00 Push 2 0's
\ Swap (resuting in 2 0's)
0\0
0 Push 0
\ Swap
0 Push 0 (3 0's)
\00
\ Swap the empty stack (appends 2 0's)
0 Push 0
0 Push another 0 (resulting in 4 0's)
```
] |
[Question]
[
The basis vectors for geometric algebra are
$$(e\_0=1), e\_1, e\_2,\dots,e\_n$$
They all square to 1 (we do not consider vectors which square to -1 or zero)
$$e\_i \cdot e\_i = 1$$
They are associative and anticommutative (except \$e\_0=1\$ which is associative and **commutative**)
$$e\_i \cdot e\_j =-e\_j \cdot e\_i \: \; (i\neq j); \;and\; i,j > 0$$
For example, this product is simplified to
$$e\_1 \cdot e\_3 \cdot e\_3 \cdot e\_5\cdot e\_4 \cdot e\_5 \\
= e\_1 \cdot (e\_3 \cdot e\_3) \cdot (e\_5\cdot e\_4) \cdot e\_5 \\
= e\_1 \cdot (1) \cdot (-e\_4\cdot e\_5) \cdot e\_5 \\
= e\_1 \cdot (-e\_4) \cdot (e\_5 \cdot e\_5) \\
= e\_1 \cdot (-e\_4) \cdot (1) \\
= - e\_1 \cdot e\_4$$
(note that the simplified product is sorted by the index of \$e\$)
**Challenge**
If a product of basis vectors is represented by a signed integer where each bit is 1 if the vector is present, or 0 if the vector is not present
$$\begin{align}
0101011 & = e\_0 \cdot e\_1 \cdot e\_3 \cdot e\_5 \\
& = e\_0^1 \cdot e\_1^1 \cdot e\_2^0 \cdot e\_3^1 \cdot e\_4^0 \cdot e\_5^1 \cdot e\_6^0 \\
-0101011 & = -e\_0 \cdot e\_1 \cdot e\_3 \cdot e\_5
\end{align}$$
**Given two signed integers \$a\$, \$b\$ (you can choose the numeric encoding for negative values), output the product \$c= a \:. b\$**
The input is only 2 signed integers. There are many [ways to encode signed integers](https://en.wikipedia.org/wiki/Signed_number_representations). You can pick anyone, but the input is only 2 variables.
Note that \$| c |= |a|\; XOR \; |b|\$ , but the tricky part is to find the sign.
If the language doesn't allow its integer type to encode signed zeros (\$-00000\$), the code should return \$-00001\$ (because \$-e\_0^0=-e\_0^1=-1\$)
Because \$x=e\_0 \cdot x=x \cdot e\_0\$, then \$x=x \;OR\; 1\$, so is equally valid to return 0 or 1 for \$e\_0\$
You should at least calculate for 4 basis vectors \$e\_0=1, e\_1, e\_2, e\_3\$
[Here is a multiplication table generator](https://bivector.net/tools.html) (to check the right answers), which also offers code in C++, C#, Python and Rust (the webpage requires to manually specify how many vectors square to 1,-1 and 0. You can set 3 (or more) positive, 0 negative, and 0 Zero)
Here is [Rosetta code in many languages](https://rosettacode.org/wiki/Geometric_algebra) for geometric algebra
Example:
given a, b:
$$a=e\_1 \cdot e\_2=00110$$
$$b=e\_2 \cdot e\_3=01100$$
possible products are:
$$c=a.b=e\_1 \cdot e\_3=01010$$
$$c=b.a=-e\_1 \cdot e\_3=-01010$$
note that $$b.b=-e\_0^0=-1 =-00000$$
So, the sign has to be calculated even if the number is 00000, because \$+00000 \neq -00000\$
Example: \$a=-e\_2=-00100\\
b=-e\_1 \cdot e\_2=-00110\\
c=a.b=(-1 \cdot e\_2)(-1 \cdot e\_1 \cdot e\_2)\\
=(-1) \cdot (e\_2)(-1) \cdot (e\_1 \cdot e\_2)\\
= (e\_2 \cdot e\_1)\cdot e\_2\\
=(-e\_1 \cdot e\_2)\cdot e\_2\\
=(-e\_1) \cdot (e\_2\cdot e\_2)\\
=-e\_1=-00010\$
but \$b.a=00010\$
\$e\_0=1\$ and -1 are scalars and commute with any basis vector (do not anticommute), so negative signs on the input can be treated as in standard multiplication of integers: \$-\*-=+\\
+\*-=-\*+=-\$
Example: \$a=e\_1\cdot e\_2 \cdot e\_3=01110\\
b=-e\_1 \cdot e\_2=-00110\\
c=a.b=(e\_1e\_2e\_3)(-e\_1e\_2)\
=-(e\_1e\_2e\_3)(e\_1e\_2)\\
=-(-e\_1e\_2e\_1e\_3e\_2)\\
=-(e\_1e\_1e\_2e\_3e\_2)\\
=-(e\_1e\_1)(-e\_2e\_2e\_3)\\
=e\_3=01000\\
\\
b.a=e\_3=01000\$
Note that on this case, \$b.a=a.b\$, so the basis vectors \$e\_i\$ anticommute, but it doesn't means that always \$b.a=-a.b\$
---
This is not part of the challenge, but I would appreciate suggestions on how should be encoded vectors which square to -1 or 0
This Pyhton code generates the right answers
# [Python 3](https://docs.python.org/3/), 11427 bytes
```
"""3D Projective Geometric Algebra.
Written by a generator written by enki.
"""
__author__ = 'Enki'
import math
class R300:
def __init__(self, value=0, index=0):
"""Initiate a new R300.
Optional, the component index can be set with value.
"""
self.mvec = [0] * 8
self._base = ["1", "e1", "e2", "e3", "e12", "e13", "e23", "e123"]
#self._base = ["0001", "0010", "0100", "1000", "0110", "1010", "1100", "1110"]
if (value != 0):
self.mvec[index] = value
@classmethod
def fromarray(cls, array):
"""Initiate a new R300 from an array-like object.
The first axis of the array is assumed to correspond to the elements
of the algebra, and needs to have the same length. Any other dimensions
are left unchanged, and should have simple operations such as addition
and multiplication defined. NumPy arrays are therefore a perfect
candidate.
:param array: array-like object whose length is the dimension of the algebra.
:return: new instance of R300.
"""
self = cls()
if len(array) != len(self):
raise TypeError('length of array must be identical to the dimension '
'of the algebra.')
self.mvec = array
return self
def __str__(self):
if isinstance(self.mvec, list):
res = ' + '.join(filter(None, [("%.7f" % x).rstrip("0").rstrip(".") + (["",self._base[i]][i > 0]) if abs(x) > 0.000001 else None for i,x in enumerate(self)]))
#res = ' + '.join([x for i,x in enumerate(self)])
else: # Assume array-like, redirect str conversion
res = str(self.mvec)
if (res == ''):
return "0"
return res
def __getitem__(self, key):
return self.mvec[key]
def __setitem__(self, key, value):
self.mvec[key] = value
def __len__(self):
return len(self.mvec)
def __invert__(a):
"""R300.Reverse
Reverse the order of the basis blades.
"""
res = a.mvec.copy()
res[0] = a[0]
res[1] = a[1]
res[2] = a[2]
res[3] = a[3]
res[4] = -a[4]
res[5] = -a[5]
res[6] = -a[6]
res[7] = -a[7]
return R300.fromarray(res)
def Dual(a):
"""R300.Dual
Poincare duality operator.
"""
res = a.mvec.copy()
res[0] = -a[7]
res[1] = -a[6]
res[2] = a[5]
res[3] = -a[4]
res[4] = a[3]
res[5] = -a[2]
res[6] = a[1]
res[7] = a[0]
return R300.fromarray(res)
def Conjugate(a):
"""R300.Conjugate
Clifford Conjugation
"""
res = a.mvec.copy()
res[0] = a[0]
res[1] = -a[1]
res[2] = -a[2]
res[3] = -a[3]
res[4] = -a[4]
res[5] = -a[5]
res[6] = -a[6]
res[7] = a[7]
return R300.fromarray(res)
def Involute(a):
"""R300.Involute
Main involution
"""
res = a.mvec.copy()
res[0] = a[0]
res[1] = -a[1]
res[2] = -a[2]
res[3] = -a[3]
res[4] = a[4]
res[5] = a[5]
res[6] = a[6]
res[7] = -a[7]
return R300.fromarray(res)
def __mul__(a,b):
"""R300.Mul
The geometric product.
"""
if type(b) in (int, float):
return a.muls(b)
res = a.mvec.copy()
res[0] = b[0] * a[0] + b[1] * a[1] + b[2] * a[2] + b[3] * a[3] - b[4] * a[4] - b[5] * a[5] - b[6] * a[6] - b[7] * a[7]
res[1] = b[1] * a[0] + b[0] * a[1] - b[4] * a[2] - b[5] * a[3] + b[2] * a[4] + b[3] * a[5] - b[7] * a[6] - b[6] * a[7]
res[2] = b[2] * a[0] + b[4] * a[1] + b[0] * a[2] - b[6] * a[3] - b[1] * a[4] + b[7] * a[5] + b[3] * a[6] + b[5] * a[7]
res[3] = b[3] * a[0] + b[5] * a[1] + b[6] * a[2] + b[0] * a[3] - b[7] * a[4] - b[1] * a[5] - b[2] * a[6] - b[4] * a[7]
res[4] = b[4] * a[0] + b[2] * a[1] - b[1] * a[2] + b[7] * a[3] + b[0] * a[4] - b[6] * a[5] + b[5] * a[6] + b[3] * a[7]
res[5] = b[5] * a[0] + b[3] * a[1] - b[7] * a[2] - b[1] * a[3] + b[6] * a[4] + b[0] * a[5] - b[4] * a[6] - b[2] * a[7]
res[6] = b[6] * a[0] + b[7] * a[1] + b[3] * a[2] - b[2] * a[3] - b[5] * a[4] + b[4] * a[5] + b[0] * a[6] + b[1] * a[7]
res[7] = b[7] * a[0] + b[6] * a[1] - b[5] * a[2] + b[4] * a[3] + b[3] * a[4] - b[2] * a[5] + b[1] * a[6] + b[0] * a[7]
return R300.fromarray(res)
__rmul__ = __mul__
def __xor__(a,b):
res = a.mvec.copy()
res[0] = b[0] * a[0]
res[1] = b[1] * a[0] + b[0] * a[1]
res[2] = b[2] * a[0] + b[0] * a[2]
res[3] = b[3] * a[0] + b[0] * a[3]
res[4] = b[4] * a[0] + b[2] * a[1] - b[1] * a[2] + b[0] * a[4]
res[5] = b[5] * a[0] + b[3] * a[1] - b[1] * a[3] + b[0] * a[5]
res[6] = b[6] * a[0] + b[3] * a[2] - b[2] * a[3] + b[0] * a[6]
res[7] = b[7] * a[0] + b[6] * a[1] - b[5] * a[2] + b[4] * a[3] + b[3] * a[4] - b[2] * a[5] + b[1] * a[6] + b[0] * a[7]
return R300.fromarray(res)
def __and__(a,b):
res = a.mvec.copy()
res[7] = 1 * (a[7] * b[7])
res[6] = 1 * (a[6] * b[7] + a[7] * b[6])
res[5] = -1 * (a[5] * -1 * b[7] + a[7] * b[5] * -1)
res[4] = 1 * (a[4] * b[7] + a[7] * b[4])
res[3] = 1 * (a[3] * b[7] + a[5] * -1 * b[6] - a[6] * b[5] * -1 + a[7] * b[3])
res[2] = -1 * (a[2] * -1 * b[7] + a[4] * b[6] - a[6] * b[4] + a[7] * b[2] * -1)
res[1] = 1 * (a[1] * b[7] + a[4] * b[5] * -1 - a[5] * -1 * b[4] + a[7] * b[1])
res[0] = 1 * (a[0] * b[7] + a[1] * b[6] - a[2] * -1 * b[5] * -1 + a[3] * b[4] + a[4] * b[3] - a[5] * -1 * b[2] * -1 + a[6] * b[1] + a[7] * b[0])
return R300.fromarray(res)
def __or__(a,b):
res = a.mvec.copy()
res[0] = b[0] * a[0] + b[1] * a[1] + b[2] * a[2] + b[3] * a[3] - b[4] * a[4] - b[5] * a[5] - b[6] * a[6] - b[7] * a[7]
res[1] = b[1] * a[0] + b[0] * a[1] - b[4] * a[2] - b[5] * a[3] + b[2] * a[4] + b[3] * a[5] - b[7] * a[6] - b[6] * a[7]
res[2] = b[2] * a[0] + b[4] * a[1] + b[0] * a[2] - b[6] * a[3] - b[1] * a[4] + b[7] * a[5] + b[3] * a[6] + b[5] * a[7]
res[3] = b[3] * a[0] + b[5] * a[1] + b[6] * a[2] + b[0] * a[3] - b[7] * a[4] - b[1] * a[5] - b[2] * a[6] - b[4] * a[7]
res[4] = b[4] * a[0] + b[7] * a[3] + b[0] * a[4] + b[3] * a[7]
res[5] = b[5] * a[0] - b[7] * a[2] + b[0] * a[5] - b[2] * a[7]
res[6] = b[6] * a[0] + b[7] * a[1] + b[0] * a[6] + b[1] * a[7]
res[7] = b[7] * a[0] + b[0] * a[7]
return R300.fromarray(res)
def __add__(a,b):
"""R300.Add
Multivector addition
"""
if type(b) in (int, float):
return a.adds(b)
res = a.mvec.copy()
res[0] = a[0] + b[0]
res[1] = a[1] + b[1]
res[2] = a[2] + b[2]
res[3] = a[3] + b[3]
res[4] = a[4] + b[4]
res[5] = a[5] + b[5]
res[6] = a[6] + b[6]
res[7] = a[7] + b[7]
return R300.fromarray(res)
__radd__ = __add__
def __sub__(a,b):
"""R300.Sub
Multivector subtraction
"""
if type(b) in (int, float):
return a.subs(b)
res = a.mvec.copy()
res[0] = a[0] - b[0]
res[1] = a[1] - b[1]
res[2] = a[2] - b[2]
res[3] = a[3] - b[3]
res[4] = a[4] - b[4]
res[5] = a[5] - b[5]
res[6] = a[6] - b[6]
res[7] = a[7] - b[7]
return R300.fromarray(res)
def __rsub__(a,b):
"""R300.Sub
Multivector subtraction
"""
return b + -1 * a
def smul(a,b):
res = a.mvec.copy()
res[0] = a * b[0]
res[1] = a * b[1]
res[2] = a * b[2]
res[3] = a * b[3]
res[4] = a * b[4]
res[5] = a * b[5]
res[6] = a * b[6]
res[7] = a * b[7]
return R300.fromarray(res)
def muls(a,b):
res = a.mvec.copy()
res[0] = a[0] * b
res[1] = a[1] * b
res[2] = a[2] * b
res[3] = a[3] * b
res[4] = a[4] * b
res[5] = a[5] * b
res[6] = a[6] * b
res[7] = a[7] * b
return R300.fromarray(res)
def sadd(a,b):
res = a.mvec.copy()
res[0] = a + b[0]
res[1] = b[1]
res[2] = b[2]
res[3] = b[3]
res[4] = b[4]
res[5] = b[5]
res[6] = b[6]
res[7] = b[7]
return R300.fromarray(res)
def adds(a,b):
res = a.mvec.copy()
res[0] = a[0] + b
res[1] = a[1]
res[2] = a[2]
res[3] = a[3]
res[4] = a[4]
res[5] = a[5]
res[6] = a[6]
res[7] = a[7]
return R300.fromarray(res)
def ssub(a,b):
res = a.mvec.copy()
res[0] = a - b[0]
res[1] = -b[1]
res[2] = -b[2]
res[3] = -b[3]
res[4] = -b[4]
res[5] = -b[5]
res[6] = -b[6]
res[7] = -b[7]
return R300.fromarray(res)
def subs(a,b):
res = a.mvec.copy()
res[0] = a[0] - b
res[1] = a[1]
res[2] = a[2]
res[3] = a[3]
res[4] = a[4]
res[5] = a[5]
res[6] = a[6]
res[7] = a[7]
return R300.fromarray(res)
def norm(a):
return abs((a * a.Conjugate())[0]) ** 0.5
def inorm(a):
return a.Dual().norm()
def normalized(a):
return a * (1 / a.norm())
e1 = R300(1.0, 1)
e2 = R300(1.0, 2)
e3 = R300(1.0, 3)
e12 = R300(1.0, 4)
e13 = R300(1.0, 5)
e23 = R300(1.0, 6)
e123 = R300(1.0, 7)
if __name__ == '__main__':
#print("e1*e1 :", str(e1*e1))
#print("pss :", str(e123))
#print("pss*pss :", str(e123*e123))
a = [R300(1.0, i) for i in range(0, 8) ]
b = [-1 * x for x in a]
a = a + b
print("Vectors:")
[print(str(x)) for x in a ]
print("Products")
def javascriptCode(a,b):
def ArnauldEncoding(x):
answer= str(x)
if answer[0]=="-":
return answer[1:]+"1"
else:
return answer+"0"
return "".join(["console.log(\"0b",ArnauldEncoding(a) , "\",\"*\",\"0b" , ArnauldEncoding(b),"\",\"=\",","f(0b" , ArnauldEncoding(a) , ")(0b" , ArnauldEncoding(b) , ").toString(2), \"== \",\"" , ArnauldEncoding(a * b),"\")"])
def RubyCode(a,b):
return "".join(["[","0b",str(a),",","0b",str(b),"],"]).replace("0b-","-0b")
if True:
Productos = ["".join([str(x),"*",str(y),"=",str(x * y)]) for x in a for y in a]
#Productos = [javascriptCode(x,y) for x in a for y in a]
#Productos = [RubyCode(x,y) for x in a for y in a]
#Productos = [str(x*y) for x in a for y in a]
Origen = ["1e1", "1e2", "1e3", "1e12", "1e13", "1e23", "1e123"]
Destino = ["0010", "0100", "1000", "0110", "1010", "1100", "1110"]
Reemplazo = dict(zip(Origen, Destino))
Binario = Productos
for key in sorted(Reemplazo, key=len, reverse=True): # Through keys sorted by length
Binario = [x.replace(key,Reemplazo[key]) for x in Binario]
[print(x) for x in Binario]
a = a
```
[Try it online!](https://tio.run/##7Vpbj9u4FX73r2AVLEaaSK5k@bIYwEXTJCj2YbdBNmgfJoZBW/SYiSwZlDSx8@fTw4suR6YnsZMCvTnBSCQPz/Xj4ZHE/bHc5ln85ctg4DhO/Iq8EfkHti75IyN/ZfmOlYKvyYv0ga0EHQ4G/xC8LFlGVkdCyQPLmKBlLsintptlH/lQMhsMlktaAXuxXJI5uXkNAzeDAd/tc1GSHS23g8E6pUVB3sZheDcg8EvYhiyXPOPlcukWLN345JGmFZuHPuFZwg7z0NOU8gdCfgFSTksG2mTsk@I0bMZJc/e3fcnzjKY@KbeMrHPQIWNZqXmSNQXNGSlYST7xcqtFDrtimnup03D3yNZg0X24ILfkZzy2XNGCyUEncnziMP13pP7Gukc3It0a1Z2xs2g4PeuxCsNQ8YFLqK5RqK5wMe3ItM21Hpf9LVu@Ia6yjfxhTrqORJbdK6csQLCiRUSq8WcVNYDGNk@aqG1EvqNC0KO7TgufqNuvhkrNIuB9RR6k/CMj@UriD6BWT30HEdtwUZSEHnhB8o2KoZpBoA2qVDuWkDKHuArBCgitakkqlrIdxLlomNWzNaBBT6DNGEsKOWNLAfVyuKA7RlKWPZTbIXmRHUkOvYIkHJgVAKSWHxWScFOSKltvafbAEs2z2OZVmmiOBUA@BcP2crHI2aSo1ltQnNAk4bKnBaqcu6vSku9TvlbU0rs8Y8mQ/Fbt3hy14YUSLJVim1xIlwLzDfit5QSgTngC/h6S1pd3eyroTvO4O/U6@bTNi9py6VzpjMbqnvPaBXInWFmJ7E7FlWdFSbM1k9R4OfbXESAMsOJ6XXyCaFdjR2JUtiRlD6qCctDy3XHPXguRC/fGKAwSNSx2FaAFVjRPIPjgx7TGQ2vLDeLY/930TL3xrBlASWtGtBcUwQAtGJ3VilKYpNYxB0zmRe0yt@Htk5QXZd9sVsg8Sp6Tm@GHnGfuhqclE@5vkMt8cu86Pw1nG4f8RA7eEJaL4HvXCZ32fuh4MNe9dxy/zS/3fLG45@RPJFx4Uhu6KtyDJ9vDUP4iWEPgbCmDANQI9w8QYsjysOgAzlpnb@F5SNVnJ7reH56c3syW0u6AAXmh1nUHoz44IOFCwhQMgsWePTIhY2lxEhC0zkQAcxUBqHZz4l0VPfBYP6AwY9CJ4wMrecl2zQb1kXUTXQcEOpvC8KI7vTidbja5Dhc8/SQVd9gB9E9RZZSol4/xAtphwXdyj6U4R6sF@5ZJx/akyZ8ZUCsjFwlkRLNMAEiQLFYpTVhhX@86LFRpMlzn@2Nn2cOY3EphGC6oN9K9Ee4d6d4R7o11b4x7x7I3oHBF3RPTPcHdU9M9xd0z0z1b9D2s/NVufUDccfOriqZWB8uBU@@@gWWylmk9gWFeHs2GkYvv8GhfaePSUxONTycWn556b2x1de3TkcWnJzGcWeL9dY@@zLMP1YNMGza3NqOnvn2Z8g2kn6Th0E0bPwingR2ogR2pwb8Qqhcj9ZfsMU@rM26tB0@9@iuFVM718L@rQ@3@tLvzRy385RJKOJlc/ZXFn79WlsUvi9yH5nlrL/KkkkWwzaOwiZVQ@rgrT@6kLs9Kn2zSnJb2DQ1cX0GVtfIuC8lKP93IyMAmvpIRuVXLWLVGujXSrVi34BJAa6xbY92a6NZEt6a6NdWtmW7ZMlQj0IgPG/EdESMkIkaqjZFqEyRwipSZWTDWsDHix8j6EImfIusjJH7WiO8oM9WtiVV8rMXHSPwEiZ8i54dI/Aw5P0LWj5D1Y6v4sRY/RuJHyPkREj9Dzg@R@CmyfoKsj63iJ1r8BImPkfgZcn6ExE@R80Nk/RhZP7KKn2rxUyR@hpwfI/Ej5PwJEj9G1ofI@sgqfqbFz5D4KbJ@gpw/RtbHyPkjJD5C4kOL@LNpTQ4vl0KlNNDPJLdutjvIVzy9bHdpkrkgBXx9uTYL9OtLq1k@37cMGuBfCufItn4m3wDLc0BEYPsPgFcXSDRLLgaSsioCgS7VpkkLvVP/GZJpTQKaNhOmvQm65jIzlE9Uoz/NjHin0DFTxzZh456wuDMhRhO6klXeatSvRzps4x7bUdeG0akN44WF7xhpOrLZF3XUjRYWjrVuQc8CzDtaWPKBYRsithFStGtJ1wsxMmBc@@REi1FnzrRWpatYiBT7Jtj@gPT3/xrrf7zGOldHXVAr4erotAK6uua5una5fiNIkrPPTy@SxPIoKt@Zw1qTH6Pqt@o/5ukJuF3@9NTxgP2FlvGk/b2WWWP211sGEfYnXbOQ7A@8Bub2516DevvLBIOJC6pFFUBVLao79AK0Wp2N7e/V6unYwuRS0PWPCy8wvDK8wVPhDZ4Kb/BUeIOnwhs8Fd7gqfAGT4U3@ObwduIovjWQ3xVQo8sKIKh2cNrJEwU8iVyz71Kz0VtiZwoCS@BM9WCJmik1LCEzJYklXqZ@sQTLFDuWSJmi6LJcql7@XOMjU4WdwXd/pAV3f6RFdn@khXV/pMV0f6QFdH@kRTMe@QYfFZCjrsPRuRS/OvuYai9E7PWBfbu37972zfgyP6it7lqsPD@Hle/7dvP9728vrz8KSErX4eHcnhDYARHYERHYIRHYMRHYQRHYURFcDgu1RV4Li@C/BxZZLnboC0ldRIB7XJmdafsJyvU8@SRJbm9JOJycfrjlZ5mpr4OuN1QE3ulM2U9T/pkl1unyCToifwQ@mgEYwCIwV5rmRsPQJ/A8z0aoZwQ9MeqJoSfCRGPZhakmkhPumqqJuG8GOnBZMWR0x2RVOCc3y@WO8my5vNEWPNsLKNVch0W3oG1zrsTx1Zd81WtOGNSU@6LolBYt5Sg@JbxtibuEt4ZaR5jKk1at0tzT5xVkGSnkwR4XOn/2iMbMShKrekQfa1CHGuiiYUSbdGi0@Luqdoo7Ryt3r7ulJgfP67Aw/M2sN/o7UGFmNRj4QB9psRZ8X77ME9Zbm5LghcholSavs3We8OwBhODyl2bFJyb0OYkDProhz4CoUcDvfO4Ezt1JIVdjTZNFd4vnTuQgKnWK4@l5zy0nLRzHHBZx1nlW5CkbpvmD@94JV47fN4l6xCfOe8d/79yqv0AEPX2yledrojn8hX8b106n2XnuOS5qdFjmv5dCdow8nwDPOVG8rQxlHaKEe86iF7@31epoidyJF@5BYWm7DBP1fGVA3Za8F/DfGwq2T@mauTAUAEEAFKZQh1i@E1UnEgZQeaGOFdZyNAp851ZzPsLtXN8ewIijt0AIlbfHDt7VYkOMe/A8@McLGTT@uXyq0vr267Pao6GCP7BMn9jUpzUjfVwz0uc1I3NgMzInNiNzZDPqndl8xYoSsro5r3nVOc3OQRu2g5h@ltwSvi7dz3zvakX9WlDnxNVfeEYFl8SNK5oxaftHpqwvclHCrtEwV2eP5qnkKfTJnrlEi3dHnpF3W5FXD1tJUZiJ8nCvPmiHFnYr/P7QQFEeamrkqDNMnYCYGa3rTDY8nKNRGXUw@PLlnw "Python 3 – Try It Online")
[Answer]
# JavaScript (ES6), ~~73~~ 65 bytes
Expects `(a)(b)`, two integers where the least significant bit holds the sign (\$0\$ for positive, \$1\$ for negative) and all other bits are used to store the absolute value.
Returns the product \$c\$ in the same format.
```
a=>b=>a^b^(g=a=>(b/=2)&&(h=n=>b&!!n&&!h(n&~-n))(a)^g(a>>1))(a>>2)
```
[Try it online!](https://tio.run/##jY2xDoIwEIZ3nqIszd0AtqxyfQl3kitCwZDWQONkfPVa4yAxMXH7vtz/5S58461f52usfDgPaaTEZCwZ7mwHjrKAPVCDUsJEPp9kWXopywm8fFQeERg7B2yMfrExDSYWJJRVSmt1LOxbMmcp@uC3sAz1EhyMwKJthRZ3oRDsh@sYTnGdvYMG8SvZzfb5v8mvL@kJ "JavaScript (Node.js) – Try It Online")
### How?
We compute the product \$p\$ of \$a\$ and \$b\$ as follows:
* We start with \$p=a\operatorname{xor}b\$. This immediately gives the correct absolute value and initializes the sign according to the signs of \$a\$ and \$b\$.
* For each set bit in \$b\$ at index \$i>0\$, we invert the sign bit of \$p\$ if there's an odd number of set bits in \$a\$ at an index greater than \$i\$.
### Commented
```
a => b => // (a, b) = input integers
a ^ b ^ ( // compute a XOR b XOR ...
g = a => // ... the result of the recursive function g, taking a:
(b /= 2) && // divide b by two; this is shorter than a right shift
// and will eventually evaluate to zero because of
// arithmetic underflow
( h = n => // h is another recursive function counting the bits
// set in n, provided that the LSB of b is set:
b & !!n && // stop if the LSB of b is not set or n = 0
!h(n & ~-n) // otherwise, invert the result and do a recursive
// call where the least significant bit set in n
// is cleared
)(a) ^ // initial call to h with n = a
g(a >> 1) // XOR the result with a recursive call to g with
// floor(a / 2)
)(a >> 2) // initial call to g with floor(a / 4), which discards
// the sign bit and the 1st bit of the absolute value
```
[Answer]
# JavaScript (ES6), 42 bytes
(standing on Arnauld's shoulders)
Using same encoding as Arnauld. That is:
Expects `(a)(b)`, two integers where the least significant bit holds the sign (\$0\$ for positive, \$1\$ for negative) and all other bits are used to store the absolute value. Returns the product \$c\$ in the same format.
```
a=>b=>a^b^(g=x=>x&&x^g(x/2))(g(a/4)&b/2)&1
```
Explanation:
* really it's `a=>b=>a^b^(g=x=>x&&x^g(x>>1))(g(a>>2)&(b>>1))&1`
but using divisions instead of rightshifts to save a char each
(taking advantage of the fact that the recursion stops on arithmetic underflow--
same crazy trick as Arnauld-- and that fractional parts are discarded
by bitwise operators
* since (b>>1) was changed to (b/2), the parens can be removed around
the b/2 since / binds tighter than &
* and & binds tighter than ^ so no parens needed there either
* start with `a^b`, same explanation as Arnauld.
* `g(x)` is "xor of all rightshifts of x", i.e. `g(x) = x^(x>>1)^(x>>2)^...`
* note that `g(x)&1` is the parity of the number of bits set in `x`
* each bit position in `g(a>>2)&(b>>1)` is the parity
of the number of swaps involving that position in (the magnitude part of) `b`,
so the desired parity of the total number of swaps
will be the parity of the number of bits set in `g(a>>2)&(b>>1)`;
that is, `g(g(a>>2)&(b>>1))&1`.
[Answer]
# [Python 3](https://docs.python.org/3/), 69 bytes
```
def g(a,b):
r=a^b;b&=-2
while a:a>>=1;r^=a&b&1;b=b>>1^b&1
return r
```
[Try it online!](https://tio.run/##DcoxCsMwDEDRPafQZGxIQUq2GPkoBom6SaC4QbiEnt719N/wr187PnXt/VlesHuZNWwTGEvWqI4fywT3cb4LyCYpMUXLLE4dRWVNifLg@Ev7WgXrl521@d2jIhLhDAOjGEL/Aw "Python 3 – Try It Online")
The lowest bit is the sign. There is no test script and all GA packages I found are really hard to apply here, so I did not test this thoroughly. Please let me know if this is incorrect.
I'm not a code golfer, but anyone feel free to use this solution and code-golfify it.
It took me a while to come up with this algorithm... a bit hard to explain.
Does it makes sense to store the sign bit? In the end positive and negative have to be combined anyway?
Some explanation:
```
def g(a, b):
r = a ^ b
b &= -2 # I think the sign bit needs to be cleared
while a:
a >>= 1 # iterate through all bits
r ^= a & b & 1 # modify sign of result
b = (b >> 1) ^ (b & 1) # iterate through bits of b, but lowest bit is XOR or all bits so far
return r
```
The lowest bit of `b` is used as an aggregator of all its bits with XOR. It's tracking the parity - comparable to counting tail bits in more direct solutions. It took some thought to show that this equivalent.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~98 ...~~ 62 bytes
```
->c,w,d,x{[c^d,w*x*(~k=0)**((0..c+d).sum{|x|c[x]*k+=d[x-1]})]}
```
[Try it online!](https://tio.run/##VZDdisIwFITvfQpRxDQ9CSdeukYfJETJj4KIKFuLcdvuq9emP1Kvzsx8zATym9tXfZI12zp4godQKLf38KSBkv@LxIRSQpBzl/qEZ/m1KEPpVND0kkqvAhO6SnRVK4UWBaAVqEHFAzFoNBsDNiKTaex0TIiu1cPONbdl/WLrEMXYfTGB2K@2btDdyMd93ht8H4yTIYqZ5ldzL0oDtnTg5UkZbmwGZiO3CLbVNmr9c88f2ZT4De52bL1cJulsgfNCNc24EfjjdsjIqvnF89@xsrOFq@o3 "Ruby – Try It Online")
Input: `[abs(a),sign(a),abs(b),sign(b)]`
Output: `[abs,sign]`
Thanks Arnauld for the idea of splitting input and for shaving a couple of bytes.
### How it works:
The sign is determined by the number of hops: example: `e3*(e1e2) = -e1e3*(e2) = (-e1)*(-e2e3) = e1e2e3`
In this case e3 must "hop" over e1 and e2 to get to its own place, and for an even number of hops the sign is positive.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
bD€¨0ìï©C`^s€θ·<P®€S`.sR‚ζOÆ.±!P*¨ì
```
Input as two integers where the trailing bit of its binary representation represents the negative (`0`) or positive (`1`) (i.e. input `24` is `-12`/`-1100` and input `25` is `12`/`1100`).
[Try it online](https://tio.run/##MzBNTDJM/f8/yeVR05pDKwwOrzm8/tBK54S4YiD/3I5D220CDq0DMoMT9IqDHjXMOrfN/3Cb3qGNigFah1YcXvP/f7ShsY6RaSwA) or [verify some more test cases](https://tio.run/##MzBNTDJM/V9WaV@Z5PKoac2hFcVA8tyOQ9tttNR1Du9VUtA4vF9T4VHbJAUl@8r/UDUGh9ccXn9opXNCHFx1wKF1QGZwgl5x0KOGWee2@R9u0zu0UTFA69CKw2v@6/yPjjY01jEyjdVRiDY00jEyATOMYQwjqJSRCVQExICImMJETKEipjqGEMogNhYA).
**Explanation:**
```
b # Convert both integers in the (implicit) input-pair to a binary
# string
D # Duplicate this pair of binary strings
۬ # Remove the trailing bit from each
0ìï # Prepend a "0", and cast it to an integer
# (empty strings become "0", everything else remains the same)
© # Store this in variable `®` (without popping)
C # Change these binary strings to integers
` # Pop and push both values separated to the stack
^ # Bitwise-XOR them together
s # Swap to get the pair of binary strings again
€θ # Leave just the trailing bits
# Convert the 0 to -1:
· # Double both: 0→0; 1→2
< # Decrease both by 1: 0→-1; 2→1
P # Take the product of this as our starting sign
® # Push the binary string from `®` again
€S # Convert both to a list of bits
` # Pop and push the lists separated to the stack
.s # Get the suffices of the second one
R # Reverse this list of suffices
‚ # Pair the two lists together
ζ # Zip/transpose, swapping rows/columns,
# implicitly using a space filler if they're of unequal lengths
O # Sum each inner-most list
# (the spaces are counted as 0 in the legacy version)
Æ # Reduce both lists by subtracting
.± # Get the sign of this (-1 if <0; 0 if ==0; 1 if >0)
! # Get the factorial of this: -1 if -1; 1 if 0 or 1)
P # Take the product of these values
* # Multiply it to our initial sign value
¨ # Remove the trailing "1" from this sign value
ì # And prepend this "" or "-" in front of the XOR-ed value
# (after which it is output implicitly as result)
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 102 bytes
```
\d\b
0
^'0P`\d+
(.+)-
-$1
+r`((0|(?<-3>1)|(1))*)((0)|1)((?<-7>.)*\*.*)1(?=(.)*)
$#3*-$1$#5$6_
--|\*.+
```
[Try it online!](https://tio.run/##TdTNbhNBEMTx@75GLOFd6x9NKQIukLwCD2BBQOHAhUPE0e9u9mOmqy5Z70zPxOnq/N5///vz96fu9@vb9dfUpu8f2rfX69tlOj9eZiZOmi7vr@dzu51fvvD0rPl21jwv87o037Q@1uXPz4/zcl0el1nnl6/n9WWeTg9Py3r69PDx9OnHBLd1/zLd71o0aWlNbXuobY/15/Gm4@149L1jke0U/Rj9HP0gbRT1fY39bX07tP7S/bFfcHzaSo6t1mqtyqtOrqtd@m34OnwfvpAWZ1yrqN0L1vftG26P48r90161b7VWa1VedXJd7dJvw9fh@/CFtDjjWkXt3tu2f8P9cYTQxjc8tlqrtSqvOrmudum34evwffhCWpxxraL2@BOOlFUpq1JWpaxKWZWyKmVVyuopyynLKcspyynLKcspS@6hjh6qeqjqoaqHqh6qeqjqoaqH6j2Ueyj3UO6h3EO5h3IP/Q2POVTNoWoOVXOomkPVHKrmUDWH6nMoz6E8h/IcynMoz6E8h4o5PFJWpaxKWZWyKmVVyqqUVSmrpyynLKcspyynLKcspyynzAYcXTg6cXTj6MjRlaMzR3eOHTqGdAzqGNYxsGNox@CO4R0dPCweJg@bh9HD6mH2sHsM@Aj5CPoI@wj8CP0I/gj/6ABiATGB2ECMIFYQM4gdZEBISEhQSFhIYEhoSHBIeEgHEYuIScQmYhSxiphF7CIDRkJGgkbCRgJHQkeCR8JHOpBYSEwkNhIjiZXETGInGVASUhJUElYSWBJaElzS8j@pz7HFxGRiMzGaWE3MJnaTASchJ0EnYSeBJ6EnwSfhJx1QLCgmFBuKEcWKYkaxowxICUkJSglLCUwJTQlOUc5xnwqLiknFpmJUsaqYVewqA1ZCVoJWwlYCV0JXglfs638 "Retina – Try It Online") Link includes test cases. Assumes the input is in the binary form as generated by the program linked in the question. (Save 9 bytes if the inputs are always padded and 7 bytes if they never include e₀). Explanation:
```
\d\b
0
```
Remove e₀ if it appears.
```
^'0P`\d+
```
Pad both numbers to the same length. (Note that when run on a test suite, all of the numbers in the suite are padded to the same length.)
```
(.+)-
-$1
```
If the second number is negative, negate both numbers.
```
+r`((0|(?<-3>1)|(1))*)((0)|1)((?<-7>.)*\*.*)1(?=(.)*)
$#3*-$1$#5$6_
```
For each `1` bit in the second number, working from e₁ upwards, use a .NET balancing group to find the matching bit in the first number and another .NET balancing group to count the parity of the `1` bits before that bit. If the parity is odd, negate the first number. Toggle the matching bit in the first number and replace the `1` bit in the second number with a `_` (golfier than a `0`).
```
--|\*.+
```
Remove any double negatives and the second number (which is now zero at this point).
[Answer]
# Python 3, 768 bytes
i got a bit stuck on this one, wanted to post anyways in case someone else has an idea.
instead of counting bits this uses 'rewriting rules' and a dictionary to rewrite substrings of the e-string iteratively until the expression is simplified and cant be rewritten anymore.
the main problem im having is converting from integer to string and back takes a lot of bytes. the second problem is encoding the dictionary takes a lot of bytes.
main function is m(), the for -15 to 16 loop is a test loop. note i consider 0000 to be equivalent to 0001 since \$e\_0^0 = e\_0^1\$
```
rules = {'11':'','22':'','33':'','10':'-01','13':'-31','20':'-02','21':'-12','30':'-03','31':'-13','32':'-23','3-':'-3','2-':'-2','1-':'-1','0-':'-0','--':'',}
def dorules(s):
for r in rules.keys():
s=s.replace(r,rules[r]).replace(' ','')
return s
def b2e(x):
s='-' if x<0 else ''
for i in range(1,3):
if abs(x) & (2**i):
s += str(i)
return s
def e2b(x):
s=0
for i in x:
try: s|=2**int(i)
except: pass
b=bin(s)[2:].zfill(4)
if x=='': return b
if x=='-': return '-'+b
if int(x)<0: return '-'+b
return b
def m(i,j):
s=['',b2e(i)+b2e(j)]
while True:
s += [dorules(s[-1])]
if s[-2] == s[-1] or s[-3] == s[-1]: break
return s[-1]
def sign(x): return '-' if int(x)<0 else ''
for i in range(-15,16):
for j in range(-15,16):
c=e2b(m(i,j))
print(sign(i)+bin(abs(i))[2:].zfill(4)+'*'+sign(j)+bin(abs(j))[2:].zfill(4)+'='+c)
```
] |
[Question]
[
So I ran into this progressive/idle game cleverly called [Idle Dice](https://www.kongregate.com/games/Luts91/idle-dice). Has a variety of random effects applied to a pretty typical progression formula game. Warning, time sink! Play at your own risk.
However after you have 5 dice (summed the usual way) along with some bonuses for various matches (pair, two pair, three of a kind, etc), but after that you eventually get *multiplier* dice. These five dice are all multiplied against the total rolled by the first five dice and multiplicatively combine with each other.
Even later on you get access to a roulette wheel which can (if it lands on the right wedges) "skip 10 minutes." Sometimes longer, but all intervals are some multiple of 10 minutes.
# Your task:
Given the multiplier dice I have, how much will I make when I land on the "skip 10 minutes" wedge of the roulette wheel (figuring I can calculate the 20 minute and 1 hour wedges from there)? We'll ignore any upgraded multipliers and focus solely on the flat base values of each die (incremental games, being what they are, get to obscenely large values in a hurry).
## Input
* Five values in any reasonable format. Each value represents the number of faces of each of the five multiplier dice.
+ Missing dice can either be explicitly specified (as 0) or left absent, your choice as long as it is made clear how your program accepts it.
+ You can assume input values of 0, 2, 4, 6, 8, 10, 12, 20, and 100 will be used.
+ For example an input of `[6,6,4,2]` would indicate that there are 2 six-sided multiplier dice, 1 four sided, and 1 two sided, while `6 6 4 2 0` would also be acceptable.
## How the dice roll
* All ten dice are rolled once a second
* The five base dice are summed
* The sum is multiplied by each of the five multiplier's dice's face value
* That total is multiplied by the score bonus (if any)
## The dice
* The five basic (six sided) dice will be assumed all present.
## Score bonus values:
We'll assume the following score multipliers (which apply to the face results of the base 5 dice, not the multiplier dice):
* Pair: 2
* Triplet: 7
* Two-Pair: 5
* Four of a Kind: 60
* Straight: 20
* Full House (pair + triplet): 30
* Five of a Kind: 1500
[This page](http://datagenetics.com/blog/january42012/index.html) has the odds listed out for the likelyhood of any given result, except a straight for some reason, which is `240/7776` (what's called a Large Straight, rather than a Short Straight).
**Note:** My original test cases were computed using an incorrect value of 2600/7776 odds for a Pair (correct value should be 3600). Given the existing answers, I am not fixing this.
## Output:
Compute the *expected average total* over a 10 minute period (600 rolls) based on the inputs provided, assuming all dice are uniformly distributed. Output need only be accurate to the nearest whole value, but more precision is allowed.
## Test cases
*Two extra decimal-fractions of precision included for convenience.*
```
[2] -> 111643.52
[4] -> 186072.53
[6] -> 260501.54
[8] -> 334930.56
[10] -> 409359.57
[12] -> 483788.58
[20] -> 781504.63
[100] -> 3758665.12
[2,2,2] -> 251197.92
[4,2,2] -> 418663.19
[6,6,6] -> 3191143.90
[2,2,2,2,2] -> 565195.31
[6,6,6,6,6] -> 39091512.83
[10,8,6,4,2] -> 24177799.48
[100,20,2,2,2] -> 133197695.3
[100,20,12,2,2] -> 577190013.02
[100,20,12,10,8] -> 6349090143.23
[100,100,100,100,100] -> 24445512498226.80
```
[Answer]
# [R](https://www.r-project.org/), ~~50~~ 32 bytes
```
function(M)prod(M/2+.5)*691250/9
```
[Try it online!](https://tio.run/##bUxBCoAgELz3io5uWa1LiUFf6BWF0MUi6v2moGESwzKzs7NzWl1OjdW3Wa5tN2yG49xXNndUtwNUchQ0YDdazRZGAIXnPrAMrAILjCIm6XUwKuIOsSjRkjukmfyW3AVy5db@Dbh6Tvj5CZb493xDYmYDYB8 "R – Try It Online")
-17 Bytes thanks to Nick Kennedy, and thanks to Jonathan Allan for suggesting a precision fix, with no byte loss!
Ignores any missing bonus dice. Just a brute force approach.
Works pretty well, but `integers` get promoted to `doubles` once we get past the 2-billion mark (`2^31-1`), leading to a loss of precision.
Because the "regular" and "bonus" dice are independent, \$E[RB]=E[R]E[B]\$, easing the calculations to simply calculating \$E[B]\$ (which is again the `prod` of the expected values of each die) and scaling by \$E[R]\$, easily calculated from the given test cases.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
‘HPד¡LT⁼þd+’÷Ø%
```
[Try it online!](https://tio.run/##y0rNyan8//9RwwyPgMPTHzXMObTQJ@RR457D@1K0HzXMPLz98AzV////RxsaGOig4VgA "Jelly – Try It Online")
```
‘ Add 1 to each input element
H Halve; this is the expected value of each die.
P Product.
ד¡LT⁼þd+’ Multiply by 319670173900294.
֯% Divide by 2^32.
319670173900294/2^32 is approximately 74429.01234615,
the expected value of the dice before the multiplier.
```
By the [law of total expectation](https://en.wikipedia.org/wiki/Law_of_total_expectation), the expected product of independent random values is the product of the expected values. The expected value of each n-sided multiplier die is simply (n+1)/2.
[Answer]
# JavaScript, 35 bytes
Port of Giuseppe's R solution.
```
a=>a.map(n=>x*=++n/2,x=74429.01)&&x
```
[Try It Online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLzexQCPP1q5Cy1ZbO0/fSKfC1tzExMhSz8BQU02t4n9yfl5xfk6qXk5@ukaaRrShgYEOGo7V1PwPAA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~19~~ 18 bytes
```
rÈ*°Y/2}6028750/81
```
*-1 byte thanks to @Shaggy*
[Try it online!](https://tio.run/##y0osKPn/v@hwh9ahDZH6RrVmBkYW5qYG@haG//9HGxoY6KDhWAA "Japt – Try It Online")
With slightly less precision: 17 bytes
```
rÈ*½*(YÄ}74429.01
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
>;P•₅·e•*81/
```
Port of [*@lirtosiast*'s Jelly answer](https://codegolf.stackexchange.com/a/180739/52210) combined with [*@JonathanAllan*'s comment](https://codegolf.stackexchange.com/questions/180722/average-idle-dice-rolling#comment435619_180739) (which states \$6028750/81 == 964600\*600/6/6/6/6/6\$).
[Try it online](https://tio.run/##yy9OTMpM/f/fzjrgUcOiR02th7anAhlaFob6//9HGxoY6BgZ6Bga6QBhLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/O@uARw2LHjW1HtqeCmRoWRjq/9f5Hx1tFKsTbQLEZkBsAcSGBiACJGoEZhmASCMdIAQphNJmOkAIE0cWg4obGuhYAJkmYAmgETpGBnB1UK4hJh@kCyqAhmNjAQ).
**Explanation:**
```
> # Increase each value in the (implicit) input-list by 1
# i.e. [100,20,12,2,2] → [101,21,13,3,3]
; # Halve each value in the list
# i.e. [101,21,13,3,3] → [55.5,10.5,6.5,1.5,1.5]
P # Take the product of this list
# i.e. [55.5,10.5,6.5,1.5,1.5] → 7754.90625
•₅·e•* # Multiply it by the compressed integer 6028750
# i.e. 7754.90625 * 6028750 → 46752391054.6875
81/ # Then divide it by 81
# i.e. 46752391054.6875 / 81 → 577190013.0208334
# (and output implicitly as result)
```
[See this 05AB1E answer of mine (section *How to compress large integer?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•₅·e•` is `6028750`.
] |
[Question]
[
# Introduction
Given a String containing an arithmetic expression, your task is to output a truthy or falsey value based on whether it contains unmatched parentheses.
---
## Input
Your program should take in a String containing an arithmetic expression. It may take input in any way except assuming it to be present in a pre-defined variable. Reading from file, input box, modal dialog box etc. is fine. Taking input as function argument is allowed as well!
---
## Output
Your program should output a truthy or falsey value based on whether the input String contains any unmatched parentheses. It may output in any way except except writing to a variable. Writing to file, screen, console, terminal etc. is allowed. Outputting with function `return` is allowed as well!
---
## Rules
* For the purpose of this challenge, a parentheses is defined as any one of `[`, `{`, `(`, `)`, `}`, `]`. A parentheses is said to be unmatched if it does not have any corresponding opening/closing parentheses. For example, `[1+3` *does* contain unmatched parentheses.
* Ordering of parentheses does not matter in this challenge. So, `]1+3[` does not contain any unmatched parentheses. `{[)(}]` doesn't, as well.
* The input String will only contain following characters : `{`, `[`, `(`, `)`, `]`, `}`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `0`, `+`, `-`, `*`, `/` and `^`.
* Your program should output a truthy value if the input String contains an unmatched parentheses.
* Your program should output a falsey value if the input String does not contain an unmatched parentheses.
* You must specify the truthy and falsey values in your post.
* The input String will never be empty.
* If the input String does not contain any parentheses, your program should output falsey value.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
---
## Test Cases
```
Input -> Output
"{" Truthy
"{{{{}}" Truthy
"{[]}" Falsey
"[]][" Falsey
")()()()(" Falsey
"1+4" Falsey
"{)" Truthy
"([)]" Falsey
"(()" Truthy
"2*{10+4^3+(10+3)" Truthy
"-6+[18-{4*(9-6)}/3]" Falsey
"-6+[18-{4*)9-6](/3}" Falsey
```
---
## Winning Criterion
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
---
## Note
I'll be adding a similar challenge but in which *order will matter*, after some time! Stay Tuned!
[Answer]
# [Python 2](https://docs.python.org/2/), 47 bytes
```
lambda s:map(s.count,'([{')!=map(s.count,')]}')
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYKjexQKNYLzm/NK9ER10julpdU9EWRUwztlZd839BUWZeiUKahjpQAReCEw2SRPCjY2OjkfmaGhCILGaobYJihCYyz0ir2tBA2yTOWFsDSBujyOmaaUcbWuhWm2hpWOqaadbqG8dil9YESsdq6BuD3A0A "Python 2 – Try It Online") Test cases from musicman523.
Checks if list of counts for each type of open paren matches that for the corresponding close parens.
The program is one byte longer
```
q=input().count
print map(q,'([{')!=map(q,')]}')
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 10 bytes
```
žuS¢2ô€ËP_
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6L7S4EOLjA5vedS05nB3QPz//7pm2tGGFrrVJlqalrpmsRr6xrUA "05AB1E – Try It Online\"")
-4 thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan).
`1` for truthy, `0` for falsey.
Its main power point is the `žu` builtin.
Explanation:
```
žuS¢2ô€ËP_
žu Push '()<>[]{}'
S Split into individual chars
¢ Count occurrences of each char in the input. For <>, the count will always be 0
2 Push 2
ô Split the array into pieces of that length, corresponding to respective matching brackets
€ Map next command over the chunks
Ë Check if all elements are equal. If equal, it means that the corresponding bracket type is matched. <> will always be matched, since they will never occur in the input, so they'll both always have 0 occurrences
P Take the product of the boolean values. <> won't affect this, since it would always be 1
_ Logically negate, convert 1 to 0 and non-1 (always 0 in this case) to 1
```
[Answer]
# [Python 2](https://docs.python.org/2/), 61 bytes
Saved 4 bytes thanks to WheatWizard!
```
lambda s:any(s.count(i)^s.count(j)for i,j in['{}','[]','()'])
```
[Try it online!](https://tio.run/##bY5hC4IwEIa/9yv2bXdOM51IBf2SdYIV0qSmqH2Q4W9fg4gmxMHd@9wDx/XzdO9M7prT2T3q5@VWs/FYmxnG7bV7mQk0Vt/YYtMNTMct00Zxu/CYK/INkBO6ftBmYg1wy3HzA0VLyIpIhYzwqXCXiWJ1AkPKI5vtRFFJAX7KlUtKobJ9YosIDkmJSyrpv0avCVLpX3Nv "Python 2 – Try It Online")
[Answer]
# Python 3, ~~62~~ 61 bytes
Surprisingly pythonic for codegolf.
```
lambda x:all(x.count(y)-x.count(z)for y,z in("[]","()","{}"))
```
*-1 byte thanks to @musicman523*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
ċЀ“[]{}()”s2E€ẠṆ
```
[Try it online!](https://tio.run/##y0rNyan8//9I9@EJj5rWPGqYEx1bXauh@ahhbrGRK1Dk4a4FD3e2/f//X0nXTDva0EK32kRL01LXLFZD37hWCQA "Jelly – Try It Online")
`1` is truthy, `0` is falsey.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
!'[](){}'=sHeda
```
This outputs `1` if unmatched, `0` if matched.
[**Try it online!**](https://tio.run/##y00syfmf8F9RPTpWQ7O6Vt222CM1JfG/S8h/9Wp1LvXq6NhaIBUdGxsNpDQ1IBDINNQ2AUlrAgmNaM1YIGWkVW1ooG0SZ6ytAaSNQTK6ZtrRhha61SZaGpa6Zpq1@saxKKKaQNFYDX1joBUA "MATL – Try It Online")
### Explanation
```
! % Implicitly input string. Tranpose into vertical vector of chars
'[](){}' % Push this string
= % Compare for equalty, with broadcast
s % Sum of each column. This gives the count of each char of '[](){}'
He % Reshape as a two-row column (in column-major order)
d % Difference of the two entries of each column
a % Any: gives true (1) if some entry is nonzero, false (0) otherwise
% Implicitly display
```
[Answer]
# Javascript, 71 bytes:
```
x=>['()','[]','{}'].some(a=>x.split(a[0]).length!=x.split(a[1]).length)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 58+1 = 59 bytes
+1 byte for the `-n` flag.
```
f=->c{$_.count c}
p %w"() [] {}".any?{|s|f[s[0]]!=f[s[1]]}
```
[Try it online!](https://tio.run/##TYjBCoJAEEDv8xWrFey4rLqtSB2sDxmmKMGjhSYh4377ZnSJd3iPN0z3OW6SYZWyfewae2ple83bx9S/VBvgqXbvVKMiVhLS/NbPZ1nGpaORSuak@YZjDjEKCHEAYiZA/QOcqUAQNCHDPhNXmurijV7tEWxtyB2sVJk@2hpD4fnv4fpYFz58AA "Ruby – Try It Online")
[Answer]
## Javascript 57 bytes
```
x=>(g=z=>x.split(z).length,g`(`-g`)`|g`[`-g`]`|g`{`-g`}`)
```
Starting from asgallant's solution.
Matching returns 0. Non-matching returns non-zero.
[Answer]
# [Python 2](https://docs.python.org/2/), 85 bytes
I can definitely golf this using subtraction instead but I'm running out of time. D:
```
lambda s,c=str.count:(c(s,'(')!=c(s,')'))or(c(s,'{')!=c(s,'}'))or(c(s,'[')!=c(s,']'))
```
[Try it online!](https://tio.run/##bY5RC4IwEMff@xT2tDunmU6kAj/JWmCGFNSUbT2E7LOvlWAT4h7ufr//cdzwMtdeFq6rj@7ePM6XJtJJW2ujNm3/lOYALeiEAMF1/Z2QIPZqsuNsbWD5bIW3blA3aaIOPturH3BhQ@ZC8JARpgpdTsvFCQypiMd8S8sTo@A7W2RpRXm@S8cyhn1aoc2Y@B@jjwVkzL/m3g "Python 2 – Try It Online")
[Answer]
## PowerShell, 95 86 bytes
```
param($s)$h=@{};[char[]]$s|%{$h["$_"]++};$h.'['-$h.']'-or$h.'('-$h.')'-or$h.'{'-$h.'}'
```
[Try it online!](https://tio.run/##VY7BCoMwEETv@YoQYpOYptZGpEUK/Y@QihQhB4sSDz2s@fbUKD2UhX0zs3PYafz0fnb9MEQC5IgIGBsSjbUmUfB9ki5ltVVE2twIm3jJoTzL6qklX6m3m6qlKa8KqpzfVC1Coe1/LNbY8kIHsqAMEMYHDHHqfPfmdBbU3R8QGvNynV//oPOSAXWG0JZYKUND3YkZphIsU6NPgu9e/DzsPrCIccC0RSF@AQ)
Previous version
```
param($s)switch([char[]]$s){'('{$k++}')'{$k--}'['{$l++}']'{$l--}'{'{$m++}'}'{$m--}}$k-or$l-or$m
```
[Try it online!](https://tio.run/##VY7RCoMwDEXf/YoibrZ2xbmKbN9SuiEiOKYodeBDlm/vEvc0AvceTvKQZd76sA79OMYU0lOSgvPI7bx33Er@hrnS9X6iOKVTnvtSQHXW9d1qSW33nWm0q64G6kLeTKOwtP5fK9JelhbTT3KARIijgLi0oZ1ktqp1e767QbpuaAP9QQZymUP20hpzxWAM5o5gZOMZ2ADBxAYZyCBdzoGWFFMUAkX2SDB@AQ)
[Answer]
# C#, 87 bytes
```
using System.Linq;s=>s.Count(c=>c=='['|c=='{'|c=='(')==s.Count(c=>c==']'|c=='}'|c==')')
```
Pretty self explanatory, just test to see if the of left parenthesis equals the count of right parenthesis.
[Answer]
# PHP>7.1, 124 Bytes
```
$t=!!$p=preg_replace("#[\d+/*^-]#","",$argn);for(;$p;$p=substr($p,1,-1))$t*=chr(($o=ord($p[0]))%5?$o+2:$o+1)==$p[-1];echo$t;
```
Instead of #`[\d+/*^-]` you can use `[^]{()}[]` or `[^\p{Pe}\p{Ps}]`
[IntlChar::charMirror](http://php.net/manual/en/intlchar.charmirror.php) `IntlChar::charMirror($p[0])==$p[-1]` instead of `chr(($o=ord($p[0]))%5?$o+2:$o+1)==$p[-1]` checks not if the char is an openining or closing punctation so we can not use it without additional check `&$p[0]<$p[-1]` +8 Bytes
[Online Version](http://sandbox.onlinephpfunctions.com/code/09a4ff10b2cb3093424f07d6579805575f99709e)
# [PHP](https://php.net/), 151 bytes
A full Regex Solution
```
for($c=$t=!!$p=($r=preg_replace)("#[^]{()}[]#","",$argn);$p&&$c;)$p=$r(["#^{(.*)}$#","#^\[(.*)]$#","#^\((.*)\)$#"],[$a="$1",$a,$a],$p,1,$c);echo$t&!$p;
```
[Try it online!](https://tio.run/##NY5BCsMgFET3vUW@n6CtKWRtpAcxWkRsXJTkI9mFHLtrq4XCbB7MG4YSlelBiS7o87JqMAcX52hvgwNVXlvmGDTuuuuQNMesKcflmSO9fYiCAzPONsNYBhJA/laEQup7DEpUCTM3wNzB71dxYmsxN5tG9k@80SwqWmnQa8CxLdVYiSRHiUGoGNKGe19/qFI@6zYEH1L8Ag "PHP – Try It Online")
[Answer]
# Visual Basic.Net, ~~218~~ 192 Bytes
```
function t(m as string,v as string)
return Len(m)-Len(m.Replace(v,""))
end function
function b(q as String)
return not(t(q,"{")=t(q,"}")and t(q,"[")=t(q,"]")and t(q,"(")=t(q,")"))
end function
```
[Answer]
## Clojure, 65 bytes
```
#(let[f(frequencies %)](some not(map =(map f"[{(")(map f"]})"))))
```
So long keywords :/ Returns `nil` for falsy and `true` for truthy.
[Answer]
## [Retina](https://github.com/m-ender/retina), 26 bytes
```
O`.
+`\(\)|\[]|{}
[^*-9^]
```
[Try it online!](https://tio.run/##TYixDQIxDAB774FkxwpPSPTiJ6BkAMdRKChoKBCd37OHSDTcFSfd@/F5vu7jgNc@bv0I3CtW2qvobg4gLcSt6RgGNnEHE3UQVQHCn5C4gBGcg6UTl5YZZzNBXFnSJVoJuMWVfMn692g@xSX7Fw "Retina – Try It Online")
### Explanation
```
O`.
```
Sort all characters so that corresponding brackets are adjacent (since neither `\` nor `|` can appear in the input).
```
+`\(\)|\[]|{}
```
Repeatedly remove pairs of matching brackets.
```
[^*-9^]
```
Try to match any remaining brackets (the regex matches anything that isn't a `^` or in the ASCII range from `*` to `9` which, among the valid input characters, are only the 6 brackets). If we find any, that means that there was an unmatched one. The result will be a positive integer if the input was unbalanced, `0` otherwise.
[Answer]
# Javascript, ~~149~~ 140 bytes
New solution incorporates bitwise operators (Thanks, arjun) and calculates if they are *not* equal, and uses or instead of and.
```
function f(x){return x.split("(").length!=x.split(")").length|x.split("{").length!=x.split("}").lengt|x.split("[").length!=x.split("]").length}
```
I don't yet have a snippet for this, so I'm not sure it works yet.
## OLD SOLUTION:
```
function f(x){return !(x.split("(").length==x.split(")").length&&x.split("{").length==x.split("}").length&&x.split("[").length==x.split("]").length)}
```
Checks if there are the same amount of one bracket and another, and then returns the opposite.
```
function f(x){return !(x.split("(").length==x.split(")").length&&x.split("{").length==x.split("}").length&&x.split("[").length==x.split("]").length)}
/*"{" Truthy
"{[]}" Falsey
"[]][" Falsey
")()()()(" Falsey
"1+4" Falsey
"{)" Truthy
"([)]" Falsey
"2*{10+4^3+(10+3)" Truthy
"-6+[18-{4*(9-6)}/3]" Falsey
"-6+[18-{4*)9-6](/3}" Falsey*/
console.log(f("{"));
console.log(f("{[]}"));
console.log(f("[]]["));
console.log(f(")()()()("));
console.log(f("1+4"));
console.log(f("{)"));
console.log(f("([)]"));
console.log(f("2*{10+4^3+(10+3)"));
console.log(f("-6+[18-{4*(9-6)}/3]"));
console.log(f("-6+[18-{4*)9-6](/3}"));
```
] |
[Question]
[
I see from [this SMBC comic](http://www.smbc-comics.com/comic/puzzle-time) that Zach Weinersmith is offering a generous 14 points to anybody who can find a way of generating the following series:
```
0, 1, 4, -13, -133, 52, 53, -155
```
Now, we all know that there are infinite ways of generating any given numeric series, so Zach is clearly just giving those points away. But what's the *shortest* code that will do it?
I'll be particularly impressed if anyone can beat 25 bytes, particularly in a non-golfing language, since that's what it takes to write the following reference implementation in Python:
```
0,1,4,-13,-133,52,53,-155
```
The output can be in whichever format works best for you:
1. a program that spits out plaintext representation of signed decimal numbers
2. an expression that evaluates to a static sequence of numeric objects with these values (as in my Python example)
3. an expression for `f(n)` that returns the `n`th value of the sequence. You can choose a zero-based or one-based convention for `n` as you wish and need not worry what the expression produces subsequent to the known elements. (By "expression" here, I mean let's not count the characters in the function prototype itself, and let's say you can assume `n` is pre-initialized.)
Longer sequences (including infinite sequences) are permitted provided the first 8 elements match Weinersmith's DH Series above. The ninth and subsequent elements, if present, can be anything at all.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
“ĊĊḊḢṬ3gƈ¢‘I
```
[Try it online!](https://tio.run/nexus/jelly#@/@oYc6RriNdD3cA0aKHO9cYpx/rOLToUcMMz///AQ "Jelly – TIO Nexus")
### Explanation
```
“ĊĊḊḢṬ3gƈ¢‘ String representing code points
I Consecutive increments
```
[Answer]
# PHP, 75 Bytes
0-Indexing
prints a underscore separeted string till the n th value
```
<?=+$e;for(;$i++<$argn;)echo _,$e+=[185,1,7-4*$e-log($e)^0,-17,-120][$i%5];
```
[Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zNTay5rK3@29jb6utkmqdll@kYa2Sqa1tA5a11kxNzshXiNdRSdW2jTa0MNUx1DHXNdFSSdXNyU/XUEnVjDPQ0TU0B2Ijg9holUxV01jr//8B "PHP – TIO Nexus")
## Expanded
```
<?=+$e; #Output zero 0 th value
for(;$i++<$argn;) # loop till reach input n
echo _,$e+=[185,1,7-4*$e-log($e)^0,-17,-120][$i%5];
# Output and assign the next value in sequence
```
## Steps depending on mod 5 start with 1
1: plus 1
2: plus 7 minus 4 times last value minus natural logarithm of last value cast to int
3: minus 17
4: minus 120
0: plus 185
[Natural logarithm](http://php.net/manual/en/function.log.php)
## PHP, 33 Bytes
prints a string representation
```
<?="[0,1,4,-13,-133,52,53,-155]";
```
[Try it online!](https://tio.run/nexus/php#@29jb6sUbaBjqGOio2toDMLGOqZGOqYgpqlprJL1//8A "PHP – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes
```
•3—ι]½ý.¢Σ”•6¡4'-:.¥
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UcMi40cNU87tjD209/BevUOLzi1@1DAXKGp2aKGJuq6V3qGl//9HG@gY6pjo6Boag7CxjqmRjimIaWoaCwA "05AB1E – Try It Online")
**Uses:** 16364176412061856164208
**Replace the 6's with commas (split on 6):**
`['1', '3', '417', '4120', '185', '1', '4208']`
**Replace 4's with negative symbol:**
`['1', '3', '-17', '-120', '185', '1', '-208']`
**Undelta.**
---
Simpler approach (turned out worse):
`•5Û€ïÛ†!eŽΓ•8BR7¡6'-:`
[Answer]
# Jelly, 17 Bytes
```
153B-*“¡¢¥Æ⁵45ɓ‘×
```
[Try it online!](https://tio.run/nexus/jelly#ASAA3///MTUzQi0q4oCcwqHCosKlw4bigbU0NcmT4oCYw5f//w "Jelly – TIO Nexus")
**Explanation:**
```
153B-*
```
decode the signs from the binary digits of 153
```
“¡¢¥Æ⁵45ɓ‘
```
the magnitudes of the numbers represented as a code-page index list
```
√ó
```
elementwise multiplication
[Answer]
# Python 3, 37 bytes
```
for i in 'ÝÞáÐXđĒB':print(ord(i)-221)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
"ÈÉÌ»Cüý-"ÇƵ%-
```
[Try it online!](https://tio.run/##ASAA3/8wNWFiMWX//yLDiMOJw4zCu0PDvMO9LSLDh8a1JS3//w "05AB1E – Try It Online")
**Explanation**
```
"ÈÉÌ»Cüý-" # push this string
Ç # convert to code points
∆µ%- # subtract 200 from each
```
### Previous 15 bytes solution
```
•∍ÉΣ-ú—("o•3ô¬-
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UcOiRx29hzvPLdY9vOtRwxQNpXygkPHhLYfW6P7/DwA "05AB1E – Try It Online")
**Explanation**
```
•∍ÉΣ-ú—("o• # push the number 1551561591420222072080
3ô # split into pieces of 3
¬- # subtract the first element from all elements
```
[Answer]
# [Neim](https://github.com/okx-code/Neim), 11 + 1 (`-n`) = 12 bytes
```
0Œ≥4œÄùêçùê≤ùêç./ùï•ùêç
```
[Try here](http://178.62.56.56:80/neim?code=0%CE%B34%CF%80%F0%9D%90%8D%F0%9D%90%B2%F0%9D%90%8D.%2F%F0%9D%95%A5%F0%9D%90%8D&n=true)
Note: might not work in the future. For reference, this works for commit [db32a5e](https://github.com/okx-code/Neim/commit/db32a5e120d9e2fd669201d35e66c657704ee99d).
Explanation:
```
0Œ≥4œÄùêçùê≤ùêç./ùï•ùêç Push 0
γ Push 1
4 Push 4
π Push 13
ùêç Negate
ùê≤ Push 133
ùêç Negate
. Push 52
/ Push 53
ùï• Push 155
ùêç Negate
```
[Answer]
## Mathematica, 79 bytes
```
s={-22,-83,408,-489,-25};i=2;While[i!=-1,t=Join[{i},Accumulate[s]+i];i--;s=t];s
```
[Try it online!](https://tio.run/nexus/mathics#BcHNCkBAEADgV@FGZopFraYprk5uDtseJDLlp@w6ybOv71s5JI5fVApQl1DlGrDSDaCqPxJWNG6yL0ZixgI895ec5pUPunl@jmef/GKczcSSIJJjb8mlYbjl9FG7hh8 "Mathics – TIO Nexus")
in order to run on mathics the original code needs 2 more bytes
[Answer]
# ><>, 26 bytes
```
'!ñð7¯À½¼'80g-nao90.
```
Standard unicode solution, same as the other answers. Sad I couldn't get to 25.
] |
[Question]
[
The [formula](http://en.wikipedia.org/wiki/Cyclic_number#Construction_of_cyclic_numbers) on the wiki article for cyclic numbers can be used to generate cyclic numbers in any base. Using this formula, or any other appropriate formula, **compute** the first ten cyclic numbers in base 10. (The numbers cannot simply be stored and read out, even if the encoding is obscure or novel.)
Repeated cyclic numbers, for example 142857142857, should be avoided if possible.
Output can include `0.` if desired, but it is not required. Each number to be delimited by line, space, comma, etc.
The program which is the shortest and which follows the rules as closely as possible will be declared the winner.
[Answer]
## GolfScript (30 29 chars)
As `xxd` output:
```
0000000: 2207 1113 171d 2f3b 3d61 6d22 7b2e 2831 "...../;=am"{.(1
0000010: 305c 3f2e 402f 2b60 283b 6e7d 25 0\?.@/+`(;n}%
```
This illustrates the importance of making codegolf problems take input so that the results can't be effectively hard-coded.
[Answer]
## GolfScript (45 44 43 chars but less hard-coded)
```
110,{:^(.[-1{.10*^%}^*]?={10^(?.^/+`(;n}*}/
```
This implementation just uses a bound on the possible primes and performs a naïve (but golfed) primitive root check to filter.
[Online demo](http://golfscript.apphb.com/?c=MTEwLHs6XiguWy0xey4xMCpeJX1eKl0%2FPXsxMF4oPy5eLytgKDtufSp9Lw%3D%3D)
[Answer]
### GolfScript, 60 53 50 characters
```
107,{))9)1$?.(@)/+`(;.,,{)1$~*`1$.+\?0<}%0-!\n+*}%
```
A plain loop, checking strings for cyclical identity.
Output:
```
142857
0588235294117647
052631578947368421
0434782608695652173913
0344827586206896551724137931
0212765957446808510638297872340425531914893617
0169491525423728813559322033898305084745762711864406779661
016393442622950819672131147540983606557377049180327868852459
010309278350515463917525773195876288659793814432989690721649484536082474226804123711340206185567
009174311926605504587155963302752293577981651376146788990825688073394495412844036697247706422018348623853211
```
[Answer]
## Python 77 bytes
```
p=0;exec"p+=2\nif len(set(10**i%~p for i in range(p)))/p:print-10**p/~p\n"*54
```
Output:
```
142857
588235294117647
52631578947368421
434782608695652173913
344827586206896551724137931
212765957446808510638297872340425531914893617
169491525423728813559322033898305084745762711864406779661
16393442622950819672131147540983606557377049180327868852459
10309278350515463917525773195876288659793814432989690721649484536082474226804123711340206185567
9174311926605504587155963302752293577981651376146788990825688073394495412844036697247706422018348623853211
```
[Answer]
# Mathematica 51 67
```
Cases[Range@110,p_/;10~MultiplicativeOrder~p==p-1:>Round[10^(p-1)/p]]
```
>
> {142857, 588235294117647, 52631578947368421, 434782608695652173913, 344827586206896551724137931, 212765957446808510638297872340425531914893617,
> 169491525423728813559322033898305084745762711864406779661,
> 16393442622950819672131147540983606557377049180327868852459,
> 10309278350515463917525773195876288659793814432989690721649484536082474226804123711340206185567,
> 9174311926605504587155963302752293577981651376146788990825688073394495412844036697247706422018348623853211}
>
>
>
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** [Update the question](/posts/4321/edit) so it's [on-topic](/help/on-topic) for Code Golf Stack Exchange.
Closed 12 years ago.
[Improve this question](/posts/4321/edit)
This was given to me by a friend of mine, it prints out 0 through 9. We have been quite puzzled over this. Does anyone know why this works?
```
#include <iostream>
using namespace std;
void x(int a)
{
*(&a-1) += a;
}
int main()
{
for(int i = 0; i < 10; ++i)
{
x(8);
i = 0;
cout << i << endl;
}
}
```
[Answer]
First of all, the line `*(&a-1) += a;` is undefined behavior, so this could do anything depending on compiler version, flags used, alignment of the stars, etc.
That said, the reason why it works in your case is probably because `&a-1` happens to point to the return address of `x`, and incrementing it by `8` causes the `i = 0;` to be skipped.
[Answer]
The reason this works is because your compiler passes the `a` parameter on the stack. Before the parameter, the code pushes the return address of the method onto the stack:
```
004A0008 | 00000008 ; a parameter
004A0004 | 00401200 ; return addr
004A0000 | ...
```
The `&a` part of the expression points to the *address* of the parameter on the stack, in this case I've used `004A0008`. The `a-1` then subtracts `sizeof(int)` from that address, giving you `004A0004`. The `*` dereferences that address, so its value can be edited. This means that when you add 8 to the value at `004A0004`, it alters the return address. When the method returns, it ends up 8 bytes ahead of where it should have been, skipping the `i=0`.
] |
[Question]
[
Given a string, determine if it is an int, a float or neither.
# Examples
* 123 - int
* 62727.0033 - float
* 644c.33 - neither
Your code should output a different value depending on which it is. For example it could return "i" for int, "f" for float and "n" for neither.
# Details
The following are floats:
```
1.00 -0.0 1.0
```
The following are not floats:
```
1e3 1.0ec3 -1e3 1e-3 1e+3 --1.0 +1.0 NaN 1.0.0 1. .1 -001.1
```
The following are ints:
```
42 -2 -0
```
The following are not ints:
```
042 00
```
In short, the rule for floats is that it is a sequence of digits following by a `.` followed by a sequence of digits. Optionally `-` is prepended. If it starts with `0` then the `.` must follow directly afterwards.
The rule for ints is that it is a sequence of digits where the first digit is not `0`. The only exception is that `0` and `-0` are ints.
Either sort of number can have `-` optionally prepended to it.
You can assume the input will only contain printable-ASCII.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~46~~ 39 bytes
Anonymous tacit prefix function. Returns 3 for float, 2 for int, and empty list for neither.
```
≢¨'^-?(0|[1-9]\d*)(\.\d+)?$'⎕S{⍵.Names}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HnokMr1ON07TUMaqINdS1jY1K0NDVi9GJStDXtVdQf9U0Nrn7Uu1XPLzE3tbj2f9qjtgmPevsedTU/6l3zqHfLofXGj9omglQFOQPJEA/P4P9p6oZ6BgbqXGnqugZ6YNoQSqUaQ3mpyWCWLkwkVRdKa0PEdaE6tKG0X6IfVCeEb2BiBKbAHAhbF0IaqAMA "APL (Dyalog Unicode) – Try It Online")
**S**earches for the PCRE pattern `^-?(0|[1-9]\d*)(\.\d+)?$` then returns the name of the whole match and of each matched sub-pattern. Finally, the length of each (`≢¨`) list of names is returned. Since floats fill both sub-patterns, we get 3, while ints skip the last sub-pattern and thus give 2. Non-matches give an empty list.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 87 bytes
```
lambda s:"-if"[getattr(re.match(r'-?(0|[1-9]\d*)(\.\d+)?$',s),'lastindex',0)]
import re
```
[Try it online!](https://tio.run/##HYpNDoIwEEb3nmJCTNpK2wziQkkMN@ACwKJKkSb8NGUWmnh3pCbzve9NZvyHhmXOrz5s/b3ZRjM9OgNrkSjXJ/XLkiEKPFg9GXoOPDBVcvzWmbq1TXcSvNFNl4ryyOQqJBvNSm7u7JtJFO3BTX4JBMFu/RKAwM2QZBoRFGqELMbmse0zB/V3qyLSfVXxnkZUpopPu13OoPZBwN0QE7360REXhQ9uJk6y5yTE9gM "Python 3.8 (pre-release) – Try It Online")
Straight-forward regular expression. Python wrapper feels a bit clumsy, though.
Returns 'i','f' and '-'. If we are ok with 1,2 and 0 instead that would save 7 bytes.
Details:
`re.match` only matches at the beginning, no `^` required. Annoyingly, Python returns two different object types, depending on whether there is a match or not. To work around this we use the cumbersome `getattr` which allows us to specify a fallback for non existent attributes.
[Answer]
# [Haskell](https://www.haskell.org/), ~~95..~~ 61 bytes
```
f l=[1|(n,_)<-reads l,x<-["-0",show$round n],x==l||l==show n]
```
[Try it online!](https://tio.run/##XYzBCsIwEETv/Yol9KCQhG6qB6H5B@9FJNCWFtdEUsUe8u/RenJ7nDczb3TzrSfKeQCyLaadl9d9o2LvuhlILo1qhaqEnMfwLmN4@Q78RS7WUkpk7Yq/IN/d5MFCFwp4xMk/oYRBoPhPFUuKl4q3pjJGFOytNwfU/FJrPODxtLGuI6bhFuwNt5x5DQZqTjT@pPkD "Haskell – Try It Online")
* As pointed out by @Peter Cordes there are floating point issues.
* Saved 18 Bytes by removing type hint to *reads* , thanks to @Unrelated String !
* Thanks to @Wheat Wizard for saving another 8 Bytes by applying *do notation*!
* Saved again 6 Bytes by @Wheat Wizard with a great use of list comprehension.
Returns:
*[]* = neither
*[1]* = Int
*[1,1]* = Float
We can return:
*""* = neither
*"1"* = Int
*"11"* = Float
By adding 2Bytes and building a [Char] list instead of [Int].
Or an integer 0,1 or 2 by applying sum to the result for +3
*f l* uses list comprehension conditional trick :
If *reads* finds a number then we use *(!)* to determine its type.
If it fails it return an empty list , hence list comprehension is empty.
*(!)* compares value found with input reconverting it to string
We sum to get a consistent value for *neither* , we would get 0 or empty list
9 Bytes could be saved if we haven't to handle -0
[Answer]
# [QuadS](https://github.com/abrudz/QuadRS), 31 bytes
Equivalent of [my APL answer](https://codegolf.stackexchange.com/a/244050/43319).
```
≢¨⍵
^-?(0|[1-9]\d*)(\.\d+)?$
⍵N
```
[Try it online!](https://tio.run/##KyxNTCn@//9R56JDKx71buWK07XXMKiJNtS1jI1J0dLUiNGLSdHWtFfhAkr6/f9vqGdgAAA "QuadS – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 35 bytes
```
^-?(0|[1-9]\d*)(?<1>\.\d+)?$|.+
$#1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP07XXsOgJtpQ1zI2JkVLU8PextAuRi8mRVvTXqVGT5tLRdnw/39DI2MuMyNzI3M9AwNjINPEJFnP2BgA "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs `2` for float, `1` for integer and `0` for everything else. Explanation:
```
^-?(0|[1-9]\d*)(?<1>\.\d+)?$|.+
```
Try to match an integer with an optional decimal fraction. Capture both the integer and the fraction (if it's present) in capture group `1`. If the input is neither then simply match it all without capturing anything.
```
$#1
```
Output the number of captures of capture group `1`.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 56 bytes
Takes a single number as a string; outputs 0 for other, 3 for integer, and 4 for float
```
("$args"-match"^-?(0|[1-9]\d*)(\.\d+)?$")+$matches.Count
```
[Try it online!](https://tio.run/##XZFdb4IwFIav5VcY0g0YlsD0ZjGNLmYmu5gu81KdqXj8WBAYbbMlwG9npUWdJuScntPnPR80TX4gY3uIogpt26SdV7aJaLZjJj5SHu7NTzyw/WIe4KflYvPg2AtvsXGdATIdFykCmDdKRMyr0kAZMBHxN5rKSkPbmvI9ZFbH0t9rzGGn4nGUUG45BuLAOFPsMJ@I41qOQqQu8HxfYtj3aicjy@m//KYQctiQXtm5gnuPNarMFde94QLo6mIQ1gfcxIC1c1USB6qlq92ETrSkmUMaL5DGVz39q3Z@Kff5UPvrjU7rFXe50UKxHkTeoJXXTCXT0Mi1UN@eSv5TFe26SAudsXv5WGh1STGXzN9nI8F4cpyuv6R@Ocxf41RwglaXIW/69Z9DLmhEmiL9mQhDYOwWw/B9IkYRZeywPYSUH5KYXB583hDL0miVRnn@FcWYV38 "PowerShell – Try It Online")
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) (Alternate Regex), 56 bytes
```
("$args"-match"^-?((?!0)\d+|0)(\.\d+)?$")+$matches.Count
```
[Try it online!](https://tio.run/##XZFdb4IwFIav5Vc40g0IQsr0zjS6mJl4MV3mpTpT6/FjQWC0ZEuA385KizpNyDk9p897PmgS/0DKDxCGFdq1STuvbBPRdM9N70QFO5if3sC2Bw/YWW7dAjv20pcHZ4BMx0WKAO6P4iwSVWmgFHgWijeayEpD25qJA6RWx9LfJBKwV/E4jKmwHAMJ4IIrdphPs9NGjkKkLvAxlpiH/drJyHL6r78JMAFb0is7N3DvuUaVueG6d1wAXV0MWH3wmhg87VyV9ALV0tVuSqda0swhjR9Ig1VPfNMOl3KfD7W/3ui8XvGYGy0U6UHkDVr7zVQyDY1cC/XtueQ/VdGui7TQBXuSj4XW1xR3yeJ9Psq4iE@zzZfUr4b5JEoyQdD6OuRdv/4LExkNSVOkP88YA87vMQ@@z8QopJwfd0dGxTGOyPXBFw2xKo1WaZSXX1GMRfUH "PowerShell – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 55 bytes
```
≔⁰ηFS≡ι-≔∨¬η¹⁵η.≔⎇⊖↔⁻⁸η¹⁵¦⁵η0≔⎇›²η⁷|⁸ηη≔|⁹⎇Σιη⁶η§00121η
```
[Try it online!](https://tio.run/##Zc/LasMwEIXhvZ9i8GoEcpADvWblUihZ9ALpC6jyJBY4chmNmpbSZ1eduGko3Z//Y8Z1lt1g@5ybGP0moNHQqUWxHhhwGV6TrIR92KBSEHdeXAfoFXwWzkaCsiqv4Sd8ZHwYBDuloT5TkzKNZqfRM3Gw/IG35Ji2FIRabF7i0CchvPchRbzcp@qgaPgLmf/QHZMVYpzvdxouNNx42flI4zmTNAEtrW3q5bc/ra40HLFV2o7PjYGG82P4VTyN/ws2sgwtvWNpTD2vywO9yLkyM5Ort/4b "Charcoal – Try It Online") Link is to verbose version of code. Outputs `2` for float, `1` for integer and `0` for everything else. Explanation: Implements a state machine (see below).
```
≔⁰η
```
Start in state 0.
```
FS≡ι
```
Switch over the input string's characters.
```
-≔∨¬η¹⁵η
```
`-` transitions from state `0` to state `1` and from any other state to state `15`.
```
.≔⎇⊖↔⁻⁸η¹⁵¦⁵η
```
`.` transitions from states `7` or `9` to state `5` and from any other state to state `15`.
```
0≔⎇›²η⁷|⁸ηη
```
`0` transitions from states `1` or `2` to state `7` and from any other state to the result of a bitwise OR with `8`.
```
≔|⁹⎇Σιη⁶η
```
Any other digit transitions by the result of a bitwise OR with `9` and any other character transitions to state `15` (obtained via a bitwise OR of `6` with `9`).
```
§00121η
```
Look up the acceptance value of the final state, modulo 5. State `13` is reached for floats. State `7` is reached for `0` and state `9` is reached for other integers. States `0`, `1`, `5` and `15` cover everything else. Transition table:
| | - | . | 0 | \d | X | Pattern |
| --- | --- | --- | --- | --- | --- | --- |
| 0 | 1 | 15 | 7 | 9 | 15 | ^ |
| 1 | 15 | 15 | 7 | 9 | 15 | ^- |
| 5 | 15 | 15 | 13 | 13 | 15 | ^-?(0|[1-9]\d+)\. |
| 7 | 15 | 5 | 15 | 15 | 15 | ^-?0 |
| 9 | 15 | 5 | 9 | 9 | 15 | ^-?[1-9]\d+ |
| 13 | 15 | 15 | 13 | 13 | 15 | ^-?(0|[1-9]\d+)\.\d+ |
| 15 | 15 | 15 | 15 | 15 | 15 | |
[Answer]
## [Go](//go.dev), 135 bytes
```
package n
import."strconv"
func f(s string)byte{if _,e:=Atoi(s)
e==nil{return'i'}
if _,e:=ParseFloat(s,64)
e==nil{return'f'}
return'n'}
```
## [Go](//go.dev), 418 bytes
Some people have mentioned that the code above doesn't pass all test cases. I realized that the rules in the question don't actually match rules used by programming languages on what qualifies as an integer or float. For example, the rules say that `1e3` is not a float, but in reality it is:
```
package main
import (
"fmt"
"strconv"
)
func main() {
f, err := strconv.ParseFloat("1e3", 64)
fmt.Println(f, err) // 1000 <nil>
}
```
So I made an edit to handle these rules:
```
package n
import."strconv"
func f(s string)byte{if s[0]=='0'&&s[1]!='.'{return'n'}
if len(s)>=3&&s[:2]=="-0"&&s[2]!='.'{return'n'}
if s[0]=='-'{}else if s[0]>='0'&&s[0]<='9'{}else{return'n'}
if s[len(s)-1]>='0'&&s[len(s)-1]<='9'{}else{return'n'}
for _,r:=range s{if r=='-'{}else if r=='.'{}else if r>='0'&&r<='9'{}else{return'n'}}
if _,e:=Atoi(s);e==nil{return'i'}
if _,e:=ParseFloat(s,64);e==nil{return'f'}
return'n'}
```
Test:
```
package n
import (
"fmt"
"testing"
)
type testType struct {
in string
out byte
}
var tests = []testType{
{"+1.0", 'n'}, {"--1.0", 'n'}, {"-0", 'i'}, {"-0.0", 'f'}, {"-001.1", 'n'},
{"-1e3", 'n'}, {"-2", 'i'}, {".1", 'n'}, {"00", 'n'}, {"042", 'n'},
{"1.", 'n'}, {"1.0", 'f'}, {"1.0.0", 'n'}, {"1.00", 'f'}, {"1.0ec3", 'n'},
{"123", 'i'}, {"1e+3", 'n'}, {"1e-3", 'n'}, {"1e3", 'n'}, {"42", 'i'},
{"62727.0033", 'f'}, {"644c.33", 'n'}, {"NaN", 'n'},
}
func TestNumber(t *testing.T) {
for _, test := range tests {
out := f(test.in)
if out != test.out {
fmt.Printf("%v %c %c\n", test.in, test.out, out)
}
}
}
```
[Answer]
# Mathematica, 93 bytes
```
Which[#~(a=StringMatchQ)~(b=RegularExpression)[c="-?([1-9]\\d*|0)"],0,#~a~b[c<>"\\.\\d+"],1]&
```
`Which`, being Mathematica's if-elseif chain. Just tests if the argument matches a regular expression for ints, then floats, all wrapped up in a lambda / pure function.
0 = int
1 = float
Null = neither
# Mathematica, 81 bytes
Using the "a different value" Mathematica is fine returning complex symbols:
```
#~(a=StringMatchQ)~(b=RegularExpression)[c="-?([1-9]\\d*|0)"]-#~a~b[c<>"\\.\\d+"]&
```
Parenthesis and square brackets remain for order of operations.
-False + True = int
False - True = float
0 = neither
] |
[Question]
[
Are there any tricks to shorten defined function names like setInterval, onkeydown, onkeyup, createLinearGradient or even return?
When using it more than once it's nice to put it as a string into a variable and reuse it afterwards but most functions I only need once.
I know that ES6 has arrowed functions - maybe there is an apporach?
[Answer]
There is a rather clever trick for shortening method names for a particular object that I first learned about during the first JS1k competition. See [Martijn Haverbeke's page](https://marijnhaverbeke.nl/js1k/) about it, under "Mechanized Abbreviation".
The idea is that you iterate over the keys of the object and apply a hash function *h(k)* to each of the keys in order to compute an alias for the key. With some trickery you can make sure to only apply the aliasing to keys referring to function values (i.e. only if `typeof o[k] == 'function'`), but of course this costs some extra characters. If only one of the keys being aliased hash to the same value, then you can use the abbreviated name unambiguously. If there are collisions you have to fall back to the full name (since the order of iteration is undefined).
When using this trick, remember that it's a trade-off between length of hash function (expression) and number of collisions. Of course, this approach is only helpful when you use a lot of long-name methods on one particular object (e.g. canvas code). For a paricular snippet that you want to golf, it could be useful to find the number of occurrences of each identifier and put together something like [this](http://demoseen.com/crunch.html) page, to simplify the search for a good hash function.
This trick could be used with global functions since the global object is `this` at the global scope (or even shorter, `windows` = `window.top` = `top` in a web environment). Also, another thing to keep in mind with frequent use of methods on one object is the `with` statement.
[Answer]
There are a lot of different cases here. I'll try to address as many as I can think of, but others might spot a few additional ones.
For starts, `return` is not a function. It's a keyword. So you're out of luck there. (Unless you can write your function in a single statement, in which case ES6 arrow functions make the return implicit, like `f=s=>s.length` instead of `f=s=>{return s.length;}`.)
For static-like functions such as `setInterval` or `Math.sin` you can just give them a new name:
```
t=setInterval
s=Math.sin
```
If you want to call a function on an object repeatedly, you'll have to work a bit harder though. For instance if you want to use `s.charCodeAt` multiple times on a string `s`, then you *cannot* do:
```
c=s.charCodeAt
c(1)
c(2)
...
```
Because if invoked like this, `c` will not know it's `this`-context. The simplest option here is to store `c` as a property of `s`:
```
s.c=s.charCodeAt
s.c(1)
s.c(2)
```
If you're using this *very* often though, you don't want to write the `s.` every time. To get rid of that, you'll need to write your own function. Using ES6 notation:
```
c=i=>s.charCodeAt(i)
c(1)
c(2)
```
Note however that this requires that you always want to call it on the *same* `s`. However, if you want to use a shortened member function on several objects, you can make those parameters:
```
c=(o,i)=>o.charCodeAt(i)
c(s,1)
c(t,2)
...
```
Then there's also the option to modify the prototype to patch the function into *every* instance of a class, but I'd have to look up the details.
[Answer]
ES6 can be the answer regarding function definition, with arrow functions, array comprehension and closure expressions
ECMAScript 5:
```
function z(a) {
statement; statement; ...
return value;
}
```
ECMAScript 6
```
z=a=> {
statement; statement; ...
return value;
}
// or
z=a=> expression
```
*Example* Factorial
```
function f(n) { for(r=1;n;n--;) r*=n; return r } // Iterative
function f(n) { return n>1 ? n*f(n-1) : 1 } // recursive
f=n=> n>1 ? n*f(n-1):1// ES6 recursive
```
] |
[Question]
[
String is given in form of a variable. Let's call that variable `s`. It is known that the string looks like a calculation expression using `+`, `-`, `*`, `/`. There's no parentheses.
**Calculate the expression inside the string** and store the result in variable `r` (you can assume it's already declared). All the divisions can be performed without remainders (`4-6*3/8` is invalid because 8 is not divisible by 3). Length of string is not limited. String can't contain `0`.
Challenge is not supposed to give advantage for some languages, so I decided to change some math rules:
Operators precedence is a little bit different than it is in math and programming language expressions: multiplication/division is still higher than addition/substraction. However, if there're some multiplications/divisions in a row, it is performed right-to-left. Addition/substraction is preformed left-to-right.
Sample `s` and `r`:
`2+5-6/9*8+7` -> `2`
`1/3*6-6` -> `12`
The shortest code (in bytes) wins.
[Answer]
# Mathematica (41)
```
s = "2+5-6/9*8+7";
ToExpression@StringReplace[s,"/"->"^-1 "]
```
>
> 2
>
>
>
Correct me if I'm wrong
[Answer]
## Ruby, 24
```
r=eval s.gsub ?/,'**-1*'
```
Thank you to @ybeltukov for the Mathematica technique. I *thought* there might be a substitution that could be used to leverage `eval` and yours was much simpler than the crazy regexes I was trying!
This shortcut effectively changes the operator precedence in `s` to what the question requires. It has the side effect of sometimes resulting in a `Rational` object type (e.g. `2/1` == `2`). The results are correct for the cases I've tried.
[Answer]
# Perl 5, ~~27~~ 20
```
s/(.)\//1\/$1*/g;print eval
```
**Edit:**
```
s/\//**-1*/g;$r=eval
```
---
Assuming the input of:
>
> $\_ = "2+5-6/9\*8+7";
>
> > $r = 2
>
>
>
and
>
> $\_ = "1/3\*6-6";
>
> > $r = 12
>
>
>
This regex is based in the mathematical theory of `@ybeltukov`, I'm new to regex so it probably could be much better.
[Answer]
## JavaScript (213 characters compacted, 133 if I'm willing to sacrifice my soul)
For clarity, this is the code *before* I compacted it down ([JS-Fiddle of it](http://jsfiddle.net/IQAndreas/5W3nQ/)):
```
function math(match, leftDigit, operator, rightDigit, offset, string) {
var L = parseInt(leftDigit)
var R = parseInt(rightDigit)
switch (operator)
{
case '*': return R*L;
case '\/': return R/L;
case '+': return L+R;
case '-': return L-R;
}
};
multAndDivRegex = /(\-?\d+)([\*\/])(\-?\d+)(?=[^\*\/]*$)/; //Right to left
addAndSubRegex = /(\-?\d+)([\+\-])(\-?\d+)/; // Left to right
while(multAndDivRegex.test(str)) {
str = str.replace(multAndDivRegex, math);
}
while(addAndSubRegex.test(str)) {
str = str.replace(addAndSubRegex, math);
}
```
Here it is compacted down to 213 characters (containing some extra help from [**Toni Almeida**](https://codegolf.stackexchange.com/users/11123/toni-almeida)) ([JS-Fiddle of it](http://jsfiddle.net/IQAndreas/5W3nQ/5/)):
```
function m(x,l,o,r){
L=~~l;R=~~r;
return o=='*'?R*L:o=='/'?R/L:o=='+'?L+R:L-R
}
for(M=/(\-?\d+)([\*\/])(\-?\d+)(?=[^\*\/]*$)/;M.test(s);s=s.replace(M,m));
for(A=/(\-?\d+)([\+\-])(\-?\d+)/;A.test(r=s);s=s.replace(A,m));
```
Since I'm ending lines with semi-colons, all *removable* whitespace was ignored for character counting, but left in for clarity.
I can get it down to 133 characters if I use `eval()`, but that's not how I roll... ([JS-Fiddle](http://jsfiddle.net/IQAndreas/5W3nQ/6/))
```
function m(x,l,o,r){return o=='*'?~~r*~~l:~~r/~~l}for(M=/(\-?\d+)([\*\/])(\-?\d+)(?=[^\*\/]*$)/;M.test(s);s=s.replace(M,m));r=eval(s)
```
This solution would mean that people can enter ANY JavaScript code they want! The 303 character version does not execute any JavaScript; it only does math.
[Answer]
## **Python 3, 35**
```
r=int(eval(s.replace("/","**-1*")))
```
## **Python 3, 30**
If you are not scared of floating point value, try this one.
```
r=eval(s.replace("/","**-1*"))
```
Both of them evaluate the string `s` and store the result in variable `r`
[Answer]
## [GTB](http://timtechsoftware.com/gtb "GTB"), 6
```
x?_)→R
```
6 chars and 6 bytes
**EDIT** - now that the original question has changed, here's some bloated code:
```
@iS_,"*")\\iS_,"/$_4;I,1,l?A;)-1:s;A;,2I,1)+A;&s;A;,1I→_&x?_)→R
```
I think I did a pretty good job; I made it only 63 characters ;) more than 1,000% bloat
] |
[Question]
[
Take a classic Boolean function with 4 variables, and perform a [Karnaugh simplification](http://en.wikipedia.org/wiki/Karnaugh_map) (you can use any other method of Boolean algebra to arrive to the simplest form). The catch is: the result has to be displayed as a circuit diagram using ASCII graphics! (in a text-mode grid display, not just characters painted in arbitrary orientations in arbitrary positions)
You can choose how to evaluate input; it can be a form of `0000001011111110` as copied directly from the truth table, its 16 bit integer representation, etc.
This example 
simplifies to this 
For which you have to draw the circuit diagram out of ASCII characters.
Standard code-golf rules apply. The ASCII graphics can be as beautiful or as ugly as you like, but the diagram has to be unambiguously identifiable at first glance.
[Answer]
## Python, 609 chars
```
N=input()
M=[[(255,['A']),(3855,['B']),(13107,['C']),(21845,['D'])]]
U=[1]*65536
for f,a in M[0]:U[f]=0
s=lambda x:x if x else''
L=1
B=65535
while all(f-N for f,a in sum(M,[])):
K={}
for f,a in M[L-1]:
if U[f^B]:K[f^B]=[u'ᐂ',u'│']+a;U[f^B]=0
for i in range((L+1)/2):
for f,a in M[L-1-i]:
A=max(len(x)for x in a)
for g,b in M[i]:
if U[f&g]|U[f|g]:
d=[u'├'+u'─'*(A-1)+u'┐']+map(lambda x,y:s(x)+' '*(A-len(s(x)))+s(y),a,b)
if U[f&g]:K[f&g]=[u'ᗝ']+d;U[f&g]=0
if U[f|g]:K[f|g]=[u'ᗣ']+d;U[f|g]=0
M+=[K.items()]
L+=1
print '\n'.join([a for f,a in sum(M,[])if f==N][0])
```
Functions are specified by listing their truth table values as a binary input. The first bit is the output for ABCD=0000, the second bit is the output for ABCD=0001, and the last bit is the output for ABCD=1111. Does a brute-forceish search for the minimal circuit that computes the function. It never shares subcomputations, so it will always be a tree. `M[L]` contains a list of functions computable with `L` gates, represented as a pair (function,array of strings) where the function is computable with the circuit drawn by the strings when printed one per line. To make sure we get the minimum circuit, we run in increasing `L` order and `U` keeps track of which functions we've already found a circuit for.
```
$ echo 0b1110000000000111 | ./gates.py
ᗣ
├───┐
ᐂ ᗝ
│ ├──┐
ᗣ ᗝ A
├──┐├─┐
ᗣ Aᗣ B
├─┐ ├┐
ᗝ B CD
├┐
CD
```
I used some awesome [Unified Canadian Aboriginal syllabics](http://en.wikipedia.org/wiki/List_of_Unicode_characters#Unified_Canadian_Aboriginal_syllabics) unicode glyphs for the gates, and box drawing glyphs for the connections. Yes, you heard right: **\**Unified Canadian Aboriginal*\***! If they don't display correctly in your browser, upgrade your unicode-fu. (They look awesome in my terminal; they are a bit misaligned on stackexchange.)
Depending on the input, could be fast or could take up to ~1/2 hour.
You might need to add something like `# -*- coding: utf-8 -*-` to the start of the program if running as a script.
] |
[Question]
[
First save the following text into a file called `marks.csv`
```
Smith,6,9,24
Jones,9,12,20
Fred,5,9,20
```
Each line contains a students name and three marks they scored. Find the top student by simply summing the three marks and then output their name. In this case the output is:
```
Jones
```
I would like to see somebody beat my Python solution but any language will be allowed :) If anybody beats my Python solution I will accept their answer but for now I will just accept the shortest code.
[Answer]
# K, 37
```
m[0;*>+/1_m:("SIII";",")0:`marks.csv]
```
[Answer]
## Cat (5 characters)
```
Jones
```
You don't specify that the code has to work on other datasets as well ;-)
Save code in a file `FILE` and execute with:
```
cat FILE
```
[Answer]
## *Mathematica*, 44
```
SortBy[Tr/@Import@"marks.csv",First][[-1,2]]
```
If I were allowed to save the data in *Mathematica*'s native format in a file named `z` I could use:
```
SortBy[Tr/@<<z,First][[-1,2]]
```
[Answer]
## Ruby 1.9 (~~71~~ 62)
```
$><<open('marks.csv').max_by{|l|eval l[/,.*/].tr ?,,?+}[/\w+/]
```
[Answer]
**PHP, ~~103~~ 95**
I know PHP is not the best tool for this problem, however I would appreciate any tip to improve my answer :)
First version (103)
```
<?$h=fopen('marks.csv','r');for(;$f=fgetcsv($h);$m[$f[0]]=array_sum($f));echo array_search(max($m),$m);
```
Improved version, inspired by @Leigh's solution (95) - considering low error level:
```
<?$h=fopen('marks.csv',r);for(;$f=fgetcsv($h);$m[array_sum($f)]=$f[0]);ksort($m);echo end($m);
```
Easier to read version:
```
<?
$h=fopen('marks.csv',r);
for(; $f=fgetcsv($h); $m[$f[0]]=array_sum($f));
echo array_search(max($m),$m);
```
Thanks
[Answer]
## PHP, ~~97~~ 93
Original
```
foreach(file('marks.csv')as$l){$x=str_getcsv($l);$r[array_sum($x)]=$x[0];}ksort($r);echo end($r);
```
Inspired by milo5b
```
for($f=fopen('marks.csv','r');$l=fgetcsv($f);)$r[array_sum($l)]=$l[0];ksort($r);echo end($r);
```
And how to run without tags.
`cat golf.php | php -a`
[Answer]
# Mathematica 59 49 53 chars
```
Sort[{Tr@Rest@#, #[[1]]} & /@ Import@"marks.csv"][[-1, 2]]
```
Because csv is a subject to various interpretations, I'm including the exact file contents of o.csv:
```
{{"Smith", 6, 9, 24}, {"Jones", 9, 12, 20}, {"Fred", 5, 9, 20}}
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~146~~ ~~134~~ 133 bytes
(feedback welcome)
```
s=a=>eval(a.split`,`.slice`1`.join`+`);_=>(""+require("fs").readFileSync("marks.csv")).split`
`.sort((a,b)=>s(b)-s(a))[0].split`,`[0]
```
[Try it online!](https://tio.run/##PY2xDoIwFEV3PoPpvVAaIGpiSBkdXB2NsQUaLZaW9DX8fkVj3E5yc86d1KpoCGaJpfOjTrMKLxLyMpv4ZAd2ZM0uO3unacO6YU2VnYIe2f6zVLJNJJTo9KosKE6LNVEyycmaQcta8skbJwuJ7eAdeau59Q@Au@ggz4vvFf6sbLN8iACK9Sg6gh5LAoV4rW7/8MYIiCm9AQ "JavaScript (Node.js) – Try It Online")
[Answer]
## Python, 82
```
print max((sum(eval(m)),n)for n,m in(l.split(',',1)for l in open("marks.csv")))[1]
```
[Answer]
## R, 58
```
j=read.csv("marks.csv",F);j[which.max(rowSums(j[,2:4])),1]
```
Alternatively (62 characters):
```
j=read.csv("marks.csv",F);j[which.max(apply(j[,2:4],1,sum)),1]
```
[Answer]
**Awk, 64**
```
$ awk -F, '{s=$2+$3+$4;if(s>m){m=s;n=$1}}END{print n}' marks.csv
```
[Answer]
# k (47 chars)
Allows for ties
```
(*x)'&(|/i)=i:+/'+:1_x:("SIII";",")0:`marks.csv
```
[Answer]
This might be orthodox and first of it kind on Code golf. Below will work find under circumstances where CSV file - been imported into as a table ( External Table) on Oracle.
M := Marks.csv Table
a-d := CSV Fields
PLSQL **60** Characters
```
SELECT a,max(b+c+d) FROM M WHERE ROWNUM<=1 GROUP BY a,b,c,d;
```
[Answer]
***C#*** Two different versions
***Version:1 245*** Characters
```
using System;using System.Linq;namespace X{class Y{static void Main(){Console.Write((from l in System.IO.File.ReadAllLines("m.csv")let x =l.Split(',')select new{f=x[0],a=x.Skip(1).Sum(Z=>Int32.Parse(Z))}).OrderByDescending(p=>p.a).First().f);}}}
```
***Version:2 214*** Characters
```
using System;using System.Linq;namespace X{class Y{static void Main(){Console.Write(System.IO.File.ReadAllLines("m.csv").OrderByDescending(z=>z.Split(',').Skip(1).Sum(y=>Int32.Parse(y))).First().Split(',')[0]);}}}
```
] |
[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/207007/edit).
Closed 3 years ago.
[Improve this question](/posts/207007/edit)
## The problem
You just got a new job, hurray! You expect to be given various interesting tasks, and be able to learn a lot in the next few months.
Good news, your boss gave you your first work this morning. You are now in charge of... Writting adresses on envelopes. Yay.
Fortunatelly, you are not required to write everything by hand : there is a software for this, in which you can enter the address as plain text.
However, the software is not really well-made and very old. When you opened the files, every information was scared on several lines, and do not fit anymore on the envelope format you were given.
Definitely not wanting to repare this by hand, you decide to write a small programm that will put the data back in the right format for you.
---
## Your task
Distribute the input on the right amount of lines.
Each line should have **the same amount of inputs (regardless of their size in characters)** when possible, and if not, the number of line with different lengths should be limited to its minimum.
Meaning that the distribution is to be made in terms of `inputs` and not `characters`.
For cases where two solutions are possible (7 inputs on 3 lines for example), the algorithm should maximise the number of inputs in the first lines (starting from the top). There is an example for this very case.
---
## Input format
```
N M
string0
string1
string2
string3
string4
string5
...
string(N-1)
```
Where :
`N` is an `int` and corresponds to the number of fragments in which the data was scattered.
`M` is an `int` and corresponds to the number of lines in which the data should be. You may assume that `M<=N` if necessary.
`string0` ... `string(N-1)` are `string`s that can contain **any *non-control* ASCII character, including spaces** and end with `[space]\n`. You thus **do not need do add spaces between the strings in the output.**
You may also assume that there is no horizontal length limit.
**They do not contain any line break except the final one.**
---
## Examples
```
Input Output
```
```
3 1 string0 string1 string2
string0
string1
string2
```
```
5 3 AA BBB
AA C DDDDD
BBB EEEE
C
DDDDD
EEEE
```
```
8 2 AAAAA BBB C DDD
AAAAA EE FFF GGGG HH
BBB
C
DDD
EE
FFF
GGGG
HH
```
```
8 3 AAA BBB CCC
AAA DDD EEE FFF
BBB GGG HHH
CCC
DDD
EEE
FFF
GGG
HHH
```
```
7 3 string0 string1 string2
string0 string3 string4 string5
string1 string6
string2
string3
string4
string5
string6
```
---
## Test cases
```
5 3
This
is
the
first
test case
```
```
8 6
Good Night, Good night!
Parting
is
such sweet
sorrow,
that I shall
say good night
till it be morrow.
```
```
8 3
I
am starting
to
run
out
of
ideas for
test cases.
```
### Expected outputs:
```
This is //2 strings [This ] and [is ]
the first //2 strings [the ] and [first ]
test case //1 string [test case ]
```
```
Good Night, Good night! Parting //2 strings [Good Night, Good night! ] and [Parting ]
is such sweet //2 strings [is such ] and [sweet ]
sorrow, //1 string [sorrow, ]
that I shall //1 string [that I shall ]
say good night //1 string [say good night ]
till it be morrow. //1 string [till it be morrow. ]
```
```
I am starting to //3 strings
run out of //3 strings
ideas for test cases. //2 strings
```
---
## Rules
Please mark your answer as : **Language - XX bytes**.
It is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the winner is the answer with the smallest score in bytes.
It would also be very nice if you could provide even briefs explainations, as it is always very enlightning to read this kind of post.
---
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ 21 bytes
This is my first **05AB1E** program (In fact this is my first golfing using golfing language), so please, if you have any notes, tips or improvements - I would love to get some in the comments section.
**Program:**
```
`rs/î©\õ.gGs«N®%0Qi¶«}}
```
**Explaination:**
```
`rs/î©\õ.gGs«N®%0Qi¶«}}
` Push each element of the input to the stack
r Reverse the stack
s Swap the first two values in stack (which are the numbers)
/ Division between both numbers in order to get the number of words in each line
î Round up
© Store that value in the register
\ Remove that number from the stack (remove head)
õ Push empty string to pass over the first iteration
.g Push the length of the stack (which is the number of words)
G } Loop from 1 to The length of the stack
s Swap the two words in the head of the stack
« Concatenate
N Push counter_variable
® Push the number we saved in the register (number of words per line)
% Modulo (To check if we need to concatenate a newline)
0Q Equals zero
i } If true
¶ Push newline
« Concatenate
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/oahY//C6QytjDm/VS3cvPrTa79A6VYPAzEPbDq2urf3/P9pCx1hHyVNBSUcpMVehuCSxqCQzLx3ELckHkUWleSAqv7QETKWByMyU1MRihbT8IrCy1OISheTE4tRiPQWl2P8A)
**Saving 2 bytes** with the help of @KevinCruijssen:
```
`rs/îUõ.gGs«NX%_i¶«}}
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/oahY//C60MNb9dLdiw@t9otQjc88tO3Q6tra//@jLXSMdZQ8FZR0lBJzFYpLEotKMvPSQdySfBBZVJoHovJLS8BUGojMTElNLFZIyy8CK0stLlFITixOLdZTUIr9DwA)
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 18 bytes
Anonymous tacit infix lambda. Takes `N` as right argument and `M` as left argument. Prompts stdin for strings as list of character vectors.
```
{,/⍺⍬⍴⎕,(⍺|-⍵)⍴⊂⍬}
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsb/ah39R727HvWuedS75VHfVB0NIK9G91HvVk2QQFcTUKb2v@Z/Y4U0BQsudU8FdQX1xFyF4pLEopLMvHQQtyQfRBaV5oGo/NISMJUGIjNTUhOLFdLyi8DKUotLFJITi1OL9RTU/@UXlGTm5xX/1y0GAA "APL (dzaima/APL) – Try It Online")
`{`…`}` "dfn"; left and right arguments are `⍺` and `⍵`:
`⊂⍬` enclose the empty list to treat it as a whole
`(`…`)⍴` cyclically **r**eshape it to the following length:
`-⍵` negate the number of inputs
`⍺|` division remainder when divided by the number of output lines
`⎕,` concatenate that many empty list to the string from stdin
`⍺⍬⍴` reshape to `M` rows and as many columns as needed
`,/` concatenate across
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 15 bytes
Anonymous lambda. Takes `N`, `M`, and `strings` as arguments.
```
{,/'(&~y!!x)_z}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlpHX11Dra5SUbFCM76q9n9atIW1sbWGkqeCkrVSYq5CcUliUUlmXjqIW5IPIotK80BUfmkJmEoDkZkpqYnFCmn5RWBlqcUlCsmJxanFegpKmrH/AQ "K (ngn/k) – Try It Online")
`{`…`}` lambda; `x` is `N`, `y` is `M`, `z` is `strings`:
`(`…`)_z` cut list of strings before the following indices:
`!x` enumerate strings
`y!` division remainder when divided by target number of lines
`~` mask indicating zeros
`&` indices of trues in mask
`,/'` concatenate elements of each list
] |
[Question]
[
Your task: given an integer `n`, output an embedded triangle to the `nth` depth.
Standard methods of input and output, input in any convenient format, output should be as a string. Examples are 0-indexed, you can use 1-indexed if you want. Standard loopholes apply
The left and right sides of each figure is 2^n, when 0 indexed. The top is twice that.
Examples:
```
n=0
--
\/
n=1
----
\/ /
\/
n=2
--------
\/ / /
\/ /
\ /
\/
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
This is NOT a duplicate of the [Embedded Hexagons!](https://codegolf.stackexchange.com/q/115715/64159) challenge. I don't think any answers from that question could be trivially copied over to this one.
[Answer]
# [Retina](https://github.com/m-ender/retina), 44 bytes
```
^
\/
+`( *)/1
$1/$1 $1/
*`.
-
;+(*G`
\\..
\
```
[Try it online!](https://tio.run/nexus/retina#@x/HFaPPpZ2goaClqW/IpWKor2KoACS5tBL0uHS5rLU1tNwTuGJi9PS4FGL@/zc0NAQA "Retina – TIO Nexus")
I only want to print successful replacements, but I don't really know how to do that.
As I'm no longer allowed to add another answer, here's a Batch answer for 192 bytes:
```
@echo off
set d=-
set l=\
set r=/
for /l %%i in (1,1,%1)do @call set r=%%r%%%%d:-= %%/&call set d=%%d%%-%%d%%
echo -%d%
:l
echo %l%%r%
set l= %l%
set r=%r:~2%
if not "%r%"=="" goto l
```
And here's a JavaScript (ES7) port of @lanlock4's excellent Mathematica answer for 124 bytes:
```
f=
n=>[...Array(2**n+1)].map((_,i)=>[...Array(2<<n)].map((_,j)=>i?i+~j?i>j?` `:i+j-(i+j&-i-j)?` `:`/`:`\\`:`-`).join``).join`
`
```
```
<input type=number min=0 oninput=o.textContent=f(this.value)><pre id=o>
```
And here's a Charcoal answer for 16 bytes:
```
FENX²ι«ιι↙↙ι↑↖ι→
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzexQMMzr6C0xK80Nym1SEchIL88tUjDSEchU1NTU6GaizOgKDOvRCNT0xqF6Ztflqph5ZJfnueTmlaCkIQLgQyAqwstQFIRWoAhH5SZngEypPb/f@P/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
N Input number
E Map over implicit range
² Literal 2
ι Current index
X Exponentiate
F « Loop over resulting powers of 2
ι Print right
ι Print right again
↙ Move down and left
↙ι Print down and left
↑ Move up
↖ι Print up and left
→ Move right
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
NαWα«X²ι↙AX²⁻ι¹β↙β↑↖β→A⁻α¹α
```
[Try it online!](https://tio.run/nexus/charcoal#@/9@z7pzG9/v2X5u46HV7/fsOLTp3M5HbTPf71kI5jxq3H1u56Gd5zYBxUDExEdt00D0JKACkNxGoNzG//@NAQ "Charcoal – TIO Nexus")
Just modified my submission from the hexagon challenge a bit to make a triangle.
[Answer]
## Mathematica, 105 bytes
```
""<>Table[Which[i<1,"-",i==j,"\\",IntegerQ@Log2[i+j-1]&&j>i,"/",1>0," "],{i,0,2^#},{j,2*2^#}]~Riffle~"\n"&
```
where `\n` is replaced with a newline.
Explanation: Makes an array of characters (indexed from *i* = 0 to 2^*n* vertically, *j* = 1 to 2^(*n*+1) horizontally) according to these rules:
* If `i<1` (so *i* = 0), put a `"-"` (for the top row)
* If `i==j`, put a `"\"` (escaped, for the left-hand side)
* If `Log2[i+j-1]` is an integer (so *i*+*j*-1 is a power of 2) and `j>i`, put a `"/"` (for the other edges)
* And put `" "` everywhere else.
Then `""<>...~Riffle~"\n"&` turns this array into a string.
[Answer]
# JavaScript ([JavaScript Shell](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Introduction_to_the_JavaScript_shell)), ~~136~~ 132 bytes
```
t=2**readline();p=print;p(v='-'.repeat(t*2));for(y=0;y<t;y++)p(' '.repeat(y)+'\\'+v.replace(/-/g,(_,i)=>i&-~i?' ':'/').slice(y*2+1))
```
Try it:
```
readline = () => prompt();
print = (...args) => output += (args.join(' ') + '\n');
output = '';
t=2**readline();p=print;p(v='-'.repeat(t*2));for(y=0;y<t;y++)p(' '.repeat(y)+'\\'+v.replace(/-/g,(_,i)=>i&-~i?' ':'/').slice(y*2+1))
document.write(`<pre>${output}</pre>`);
```
[Answer]
# C, 200 bytes
```
#define P printf(
i,j,k,l;f(n){for(i=0,k=pow(2,n);i++<k;)P"--");for(i=0;i<k;++i){l=P"\n%*c",i+1,92);for(j=0;j<n;++j)if(2*(int)pow(2,j)+1-i>l)l+=P"%*c",2*(int)pow(2,j)+1-i-l,47);P"%*c",2*k-i-l+1,47);}}
```
[Try it online!](https://tio.run/nexus/c-gcc#bY7BDoIwDIbvPAXBmLRuSwBNjJn4DDyAF6LOdJuTiMYD4dXFIsQTPTVfv/ZvvzhfDIVLXMb1g8LTQETSSie9NhCwNfcHUJFKV9T3N@QyoCYh9k5jmSiVoJ4ETcyEIGx9USbHsFydEkkik7t8dCw7dh/YsUgG8hVwGo5HLYpM0cGjF7z8W52ZKy83W9R/wQ2IEwbYdT3r8a2iABi1UcxlIEVdv54N8D/86QSzOZjPwTV3Xf85GV9dm1752xc)
[Answer]
## JavaScript (ES6), ~~108~~ ~~95~~ ~~93~~ 92 bytes
```
let f =
n=>(g=x=>y>1<<n?'':x<2<<n?' /\\-'[y?~x+y?+!(k=x+y,x<y|k&-k-k):2:3]+g(x+1):`
`+g(!++y))(y=0)
console.log(f(0))
console.log(f(1))
console.log(f(2))
console.log(f(3))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 45 bytes
I made it! (It's a fun challenge, I don't get why they VTC'd it)
```
<oLð×ε¨'\«}IL<oð×ε¨'/«}JDgU.sR2ô€нøJ»X>'-×s‚»
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fJt/n8IbD089tPbRCPebQ6lpPH5t8uIA@UMDLJT1UrzjI6PCWR01rLuw9vMPr0O4IO3Xdw9OLHzXMOrT7/39TAA "05AB1E – Try It Online")
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 22 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
╵rH2;^/L ×;+n}l\nL-×;∔
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXUyNTc1JXVGRjUyJXVGRjI4JXVGRjEyJXVGRjFCJXVGRjNFJXVGRjBGJXVGRjJDJTIwJUQ3JXVGRjFCJXVGRjBCJXVGRjRFJXVGRjVEJXVGRjRDJXVGRjNDJXVGRjRFJXVGRjJDLSVENyV1RkYxQiV1MjIxNA__,i=NQ__,v=8)
## Explanation
```
'rH2;^/L ×;+n}l\nL-×;∔
' increment input integer n
r range 0..n
H } push an empty string and start a loop
2;^ get 2^i
/ antidiagonal of that length
L get width(don't pop)
×;_ add that many spaces to the left
n overlap with prev iteration
l get height(don't pop)
\ create a diagonal of that length
n and overlap with the created sides
L get width(don't pop)
-×;∔ add that many minuses to the top
```
[Answer]
# PHP, 137 Bytes
```
for(;$i<1+2**$a=$argn;++$i)for($n=0;$n<$m=2**($a+1);$s[]=2**++$n)echo$n%$m?"":"\n",$i?$i-1!=$n?$i<=$n&in_array($i+$n,$s)?"/":" ":"\\":"-";
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/c071aa00200b2f5ca62527bf9eed574af1976189)
Expanded
```
for(;$i<1+2**$a=$argn;++$i)
for($n=0;$n<$m=2**($a+1);$s[]=2**++$n) # fill array for sum compare after loop
echo$n%$m?"":"\n", # print line feed
$i # false for first line
?$i-1!=$n # row number - 1 equal column print \
?$i<=$n&in_array($i+$n,$s) # if row number lte column and sum of both in array print /
?"/"
:" " # else print space
:"\\"
:"-"; # fill first line
```
A recursive way for 199 Bytes
```
function f($a){global$r;for(;$i<1+2**$a;$i++)for($n=0;$n<$m=2**($a+1);$n++)$r[$i][$n]=$i?$i-1!=$n?$i<=$n&&$i+$n==2**($a+1)?"/":" ":"\\":"-";$a?f($a-1):0;}f($argn);echo join("\n",array_map("join",$r));
```
] |
[Question]
[
*Inspired by [this challenge](https://codegolf.stackexchange.com/questions/58556/just-repeat-yourself)*
Given a number `m`, output a program that prints out the string `Do not repeat yourself`.
Now for the challenging part: Each program the original code prints out has to have the byte at place `m*n` be the same as `m*n + 1` and the same as `m*n + 2` .... all the way down to `m*n + m - 1`.
(In case you can't tell, that means it has to be blocks of identical bytes `m` long)
Example (that only demonstrates the repetition rule, *not* the output):
```
2
aassdd
3
mmmyyy nnnaaammmeee iiisssfffrrreeeddd
27
111111111111111111111111111
```
##Scoring:
* Your program's score is the `x / (min(y, 10)^3)`, where `y` is the number of correct programs it outputs, and `x` is the sum of the lengths of all of the correct programs it outputs and `y > 1`. Lowest score wins.
##Other notes:
* Your code doesn't have to fulfill any such restrictions on letters repeating.
* Your programs (that you output) *cannot* take input of any sort.
* The input will always be a positive integer greater than 1.
* Your code needs to work for at least one integer greater than 1.
[Answer]
# CJam, 3165 / 10³ = 3.165
```
{
"Do not repeat yourself"]sX/z_&
6)H7+G0+B8+H7+E8+G0+D8+9)C8+9)A7+E8+G0+B9+H7+K7+D8+J7+9)A8+I6+]{c}/
"Do not repeat yourself"]sZ/z_&
"Do not repeat yourself"]s3D&3D&3D&3D&3D&/z_&
"Do not repeat yourself"]s1F&1F&1F&1F&1F&1F&1F&/z_&
"Do not repeat yourself"]sB/z_&
"Do not repeat yourself"]sD/z_&
"Do not repeat yourself"]sF/z_&
"Do not repeat yourself"]sH/z_&
"Do not repeat yourself"]sJ/z_&
}`1>W<N/
e# Uncomment this line to count total length:
e# ee{~,*}%:+p [L]
ri\1$=f*
```
Works for inputs 1, 2, 3, 5, 7, 11, 13, 15, 17, 19.
Total length is 3165.
The program for input 2 is from [here](https://codegolf.stackexchange.com/questions/58556/just-repeat-yourself/58573#58573), credits to Super Chafouin.
## Example: output for 11
```
"""""""""""DDDDDDDDDDDooooooooooo nnnnnnnnnnnooooooooooottttttttttt rrrrrrrrrrreeeeeeeeeeepppppppppppeeeeeeeeeeeaaaaaaaaaaattttttttttt yyyyyyyyyyyooooooooooouuuuuuuuuuurrrrrrrrrrrssssssssssseeeeeeeeeeelllllllllllfffffffffff"""""""""""]]]]]]]]]]]sssssssssssBBBBBBBBBBB///////////zzzzzzzzzzz___________&&&&&&&&&&&
```
Explanation:
```
"""""""""""...""""""""""" Push five empty strings, a long string,
and five more empty strings.
]]]]]]]]]]]sssssssssss Collect them all in a list. Put that list in
10 more layers of list, for good measure.
Convert this to a string, to just get the long one.
BBBBBBBBBBB/////////// Split into chunks of size
11/(11/(.../(11/(11/11))))) = 11.
This gets us:
["DDDDDDDDDDD" "ooooooooooo" ...]
zzzzzzzzzzz Transpose eleven times, i.e. once. We now have:
["Do not..." "Do not..." ... "Do not..."]
___________&&&&&&&&&&& Push eleven more copies, and get the unique elements.
This gets us:
["Do not..."]
```
[Answer]
# [Gammaplex](http://esolangs.org/wiki/Gammaplex), 2080 / 10³ = 2.08
```
X"Y#gmftsvp"2v
Ev2"!sfqfbu!z<
R>upo!pE#YYs"v
>1-swSs>swrsvS
? v +=^?w-1<"
^ws<J0s11X"0F<
```
Note that it firstly displays a `0` when it is run. That's just the Gammaplex way of echoing the number you are going to input. And it prints the newline as `◙`, which shares the same code point with a newline in CP437.
Gammaplex renders the string in a window which couldn't be copied. So here is an equivalent CJam program to make testing easier:
```
"/
ERrXX\"Do not repeat yourself\"X"qie*
```
Example for m=3:
```
///
EEERRRrrrXXXXXX"""DDDooo nnnooottt rrreeepppeeeaaattt yyyooouuurrrssseeelllfff"""XXX
```
In Gammaplex, only the position of the first newline is used to determine the line length. So it is the same as the following:
```
///
EEE
RRR
rrr
XXX
XXX
"""
DDD
ooo
nnn
ooo
ttt
rrr
eee
ppp
eee
aaa
ttt
yyy
ooo
uuu
rrr
sss
eee
lll
fff
"""
XXX
```
Then it works in the obvious way as a 2D language.
[Answer]
## [ferNANDo](http://esolangs.org/wiki/FerNANDo), 8745/103 = 8.745
```
7 - - - - D C B A
- - - - E D C B A
T D D
U E E
D T U
T B E
U C C
C T U
T B E
U B T
V E T
B U V
A A
I A A
I I
T I B
U I T
V T B
B U V
J I B
J J
T J C
U J T
V T C
C U V
I J C
I I
T I D
U I T
V T D
D U V
3
5 5
AD D D
AC C C
AB B B
AA A A
AD
AC
AB
AA
0 0 7 5 0 5 5 5
AA AA
AA
AB AB
AB
AC AC
AC
AD AD
AD
3 5
3
5 5
3
5 5
2 5 5
AH D D
AG C C
AF B B
AE A A
AH
AG
AF
AE
0 0 2 2 5 0 7 2
AE AE
AE
AF AF
AF
AG AG
AG
AH AH
AH
3 5
3
5 5
3
5 5
AL D D
AK C C
AJ B B
AI A A
AL
AK
AJ
AI
0 0 7 5 0 5 0 5
AI AI
AI
AJ AJ
AJ
AK AK
AK
AL AL
AL
3 5
3
5 5
3
4 3 3
AP D D
AO C C
AN B B
AM A A
AP
AO
AN
AM
0 0 3 2 4 2 4 0
AM AM
AM
AN AN
AN
AO AO
AO
AP AP
AP
2 2
3 2
3
2 2
3
5 5
AT D D
AS C C
AR B B
AQ A A
AT
AS
AR
AQ
0 0 7 5 0 0 5 5
AQ AQ
AQ
AR AR
AR
AS AS
AS
AT AT
AT
3 5
3
5 5
3
4 3 3
AX D D
AW C C
AV B B
AU A A
AX
AW
AV
AU
0 0 3 2 4 0 4 0
AU AU
AU
AV AV
AV
AW AW
AW
AX AX
AX
2 2
3 2
3
2 2
3
5 5
4 3 3
BB D D
BA C C
AZ B B
AY A A
BB
BA
AZ
AY
0 0 7 5 0 4 5 5
AY AY
AY
AZ AZ
AZ
BA BA
BA
BB BB
BB
3 5
3
5 5
3
BF D D
BE C C
BD B B
BC A A
BF
BE
BD
BC
0 0 7 2 0 0 2 2
BC BC
BC
BD BD
BD
BE BE
BE
BF BF
BF
2 2
3 2
3
2 2
3
5 5
4 3 3
BJ D D
BI C C
BH B B
BG A A
BJ
BI
BH
BG
0 0 7 5 0 1 0 4
BG BG
BG
BH BH
BH
BI BI
BI
BJ BJ
BJ
1 5 5
3 5
3
5 5
3
BN D D
BM C C
BL B B
BK A A
BN
BM
BL
BK
0 0 7 2 0 0 2 0
BK BK
BK
BL BL
BL
BM BM
BM
BN BN
BN
2 2
3 2
3
2 2
3
5 5
4 3 3
2 5 5
BR D D
BQ C C
BP B B
BO A A
BR
BQ
BP
BO
0 0 5 5 2 0 2 4
BO BO
BO
BP BP
BP
BQ BQ
BQ
BR BR
BR
3 5
3
5 5
3
BV D D
BU C C
BT B B
BS A A
BV
BU
BT
BS
0 0 7 2 0 2 2 2
BS BS
BS
BT BT
BT
BU BU
BU
BV BV
BV
2 2
3 2
3
2 2
3
5 5
4 3 3
BZ D D
BY C C
BX B B
BW A A
BZ
BY
BX
BW
0 0 7 5 0 4 4 4
BW BW
BW
BX BX
BX
BY BY
BY
BZ BZ
BZ
3 5
3
5 5
3
CD D D
CC C C
CB B B
CA A A
CD
CC
CB
CA
0 0 7 2 0 2 0 2
CA CA
CA
CB CB
CB
CC CC
CC
CD CD
CD
2 2
3 2
3
2 2
3
5 5
4 3 3
CH D D
CG C C
CF B B
CE A A
CH
CG
CF
CE
0 0 7 5 0 5 4 5
CE CE
CE
CF CF
CF
CG CG
CG
CH CH
CH
3 5
3
5 5
3
5 5
6 5
2 5 5
CL D D
CK C C
CJ B B
CI A A
CL
CK
CJ
CI
0 0 6 2 1 2 3 2
CI CI
CI
CJ CJ
CJ
CK CK
CK
CL CL
CL
1 5 5
3 5
3
5 5
3
5 5
CP D D
CO C C
CN B B
CM A A
CP
CO
CN
CM
0 0 7 5 0 0 1 1
CM CM
CM
CN CN
CN
CO CO
CO
CP CP
CP
1 5 5
3 5
3
5 5
3
CT D D
CS C C
CR B B
CQ A A
CT
CS
CR
CQ
0 0 7 2 0 2 2 2
CQ CQ
CQ
CR CR
CR
CS CS
CS
CT CT
CT
2 2
3 2
3
2 2
3
5 5
4 3 3
CX D D
CW C C
CV B B
CU A A
CX
CW
CV
CU
0 0 7 5 0 0 4 4
CU CU
CU
CV CV
CV
CW CW
CW
CX CX
CX
3 5
3
5 5
3
DB D D
DA C C
CZ B B
CY A A
DB
DA
CZ
CY
0 0 7 2 0 0 0 2
CY CY
CY
CZ CZ
CZ
DA DA
DA
DB DB
DB
2 2
3 2
3
2 2
3
5 5
DF D D
DE C C
DD B B
DC A A
DF
DE
DD
DC
0 0 7 5 0 0 0 1
DC DC
DC
DD DD
DD
DE DE
DE
DF DF
DF
1 5 5
3 5
3
5 5
3
5 5
6 5
4 3 3
2 5 5
DJ D D
DI C C
DH B B
DG A A
DJ
DI
DH
DG
0 0 3 2 4 0 6 2
DG DG
DG
DH DH
DH
DI DI
DI
DJ DJ
DJ
3 5
3
5 5
3
5 5
4 3 3
2 5 5
DN D D
DM C C
DL B B
DK A A
DN
DM
DL
DK
0 0 5 5 2 4 2 4
DK DK
DK
DL DL
DL
DM DM
DM
DN DN
DN
3 5
3
5 5
3
DR D D
DQ C C
DP B B
DO A A
DR
DQ
DP
DO
0 0 7 2 0 2 2 2
DO DO
DO
DP DP
DP
DQ DQ
DQ
DR DR
DR
2 2
3 2
3
2 2
3
5 5
4 3 3
DV D D
DU C C
DT B B
DS A A
DV
DU
DT
DS
0 0 7 5 0 4 4 5
DS DS
DS
DT DT
DT
DU DU
DU
DV DV
DV
3 5
3
5 5
3
DZ D D
DY C C
DX B B
DW A A
DZ
DY
DX
DW
0 0 7 2 0 2 0 0
DW DW
DW
DX DX
DX
DY DY
DY
DZ DZ
DZ
2 2
3 2
3
2 2
3
5 5
4 3 3
ED D D
EC C C
EB B B
EA A A
ED
EC
EB
EA
0 0 7 5 0 1 4 5
EA EA
EA
EB EB
EB
EC EC
EC
ED ED
ED
1 5 5
3 5
3
5 5
3
5 5
6 5
2 5 5
EH D D
EG C C
EF B B
EE A A
EH
EG
EF
EE
0 0 6 2 1 0 3 0
EE EE
EE
EF EF
EF
EG EG
EG
EH EH
EH
1 5 5
3 5
3
5 5
3
5 5
EL D D
EK C C
EJ B B
EI A A
EL
EK
EJ
EI
0 0 7 5 0 1 1 1
EI EI
EI
EJ EJ
EJ
EK EK
EK
EL EL
EL
1 5 5
3 5
3
5 5
3
EP D D
EO C C
EN B B
EM A A
EP
EO
EN
EM
0 0 7 2 0 2 2 2
EM EM
EM
EN EN
EN
EO EO
EO
EP EP
EP
2 2
3 2
3
2 2
3
5 5
4 3 3
ET D D
ES C C
ER B B
EQ A A
ET
ES
ER
EQ
0 0 7 5 0 1 0 4
EQ EQ
EQ
ER ER
ER
ES ES
ES
ET ET
ET
1 5 5
3 5
3
5 5
3
EX D D
EW C C
EV B B
EU A A
EX
EW
EV
EU
0 0 7 2 0 2 0 0
EU EU
EU
EV EV
EV
EW EW
EW
EX EX
EX
2 2
3 2
3
2 2
3
5 5
FB D D
FA C C
EZ B B
EY A A
FB
FA
EZ
EY
0 0 7 5 0 5 1 5
EY EY
EY
EZ EZ
EZ
FA FA
FA
FB FB
FB
1 5 5
3 5
3
5 5
3
4 3 3
FF D D
FE C C
FD B B
FC A A
FF
FE
FD
FC
0 0 3 2 4 0 4 0
FC FC
FC
FD FD
FD
FE FE
FE
FF FF
FF
2 2
3 2
3
2 2
3
5 5
FJ D D
FI C C
FH B B
FG A A
FJ
FI
FH
FG
0 0 7 5 0 5 5 5
FG FG
FG
FH FH
FH
FI FI
FI
FJ FJ
FJ
3 5
3
5 5
3
FN D D
FM C C
FL B B
FK A A
FN
FM
FL
FK
0 0 7 2 0 0 2 2
FK FK
FK
FL FL
FL
FM FM
FM
FN FN
FN
2 2
3 2
3
2 2
3
5 5
FR D D
FQ C C
FP B B
FO A A
FR
FQ
FP
FO
0 0 7 5 0 1 1 1
FO FO
FO
FP FP
FP
FQ FQ
FQ
FR FR
FR
1 5 5
3 5
3
5 5
3
FV D D
FU C C
FT B B
FS A A
FV
FU
FT
FS
0 0 7 2 0 0 0 0
FS FS
FS
FT FT
FT
FU FU
FU
FV FV
FV
2 2
3 2
3
2 2
3
5 5
4 3 3
2 5 5
FZ D D
FY C C
FX B B
FW A A
FZ
FY
FX
FW
0 0 5 5 2 0 2 4
FW FW
FW
FX FX
FX
FY FY
FY
FZ FZ
FZ
3 5
3
5 5
3
GD D D
GC C C
GB B B
GA A A
GD
GC
GB
GA
0 0 7 2 0 0 0 2
GA GA
GA
GB GB
GB
GC GC
GC
GD GD
GD
2 2
3 2
3
2 2
3
5 5
4 3 3
GH D D
GG C C
GF B B
GE A A
GH
GG
GF
GE
0 0 7 5 0 4 4 4
GE GE
GE
GF GF
GF
GG GG
GG
GH GH
GH
3 5
3
5 5
3
GL D D
GK C C
GJ B B
GI A A
GL
GK
GJ
GI
0 0 7 2 0 0 0 2
GI GI
GI
GJ GJ
GJ
GK GK
GK
GL GL
GL
2 2
3 2
3
2 2
3
5 5
4 3 3
GP D D
GO C C
GN B B
GM A A
GP
GO
GN
GM
0 0 7 5 0 0 0 4
GM GM
GM
GN GN
GN
GO GO
GO
GP GP
GP
3 5
3
5 5
3
5 5
6 5
2 5 5
GT D D
GS C C
GR B B
GQ A A
GT
GS
GR
GQ
0 0 6 2 1 0 1 0
GQ GQ
GQ
GR GR
GR
GS GS
GS
GT GT
GT
1 5 5
3 5
3
5 5
3
5 5
GX D D
GW C C
GV B B
GU A A
GX
GW
GV
GU
0 0 7 5 0 1 0 5
GU GU
GU
GV GV
GV
GW GW
GW
GX GX
GX
1 5 5
3 5
3
5 5
3
5 5
6 5
2 5 5
HB D D
HA C C
GZ B B
GY A A
HB
HA
GZ
GY
0 0 6 2 1 2 1 2
GY GY
GY
GZ GZ
GZ
HA HA
HA
HB HB
HB
1 5 5
3 5
3
5 5
3
5 5
HF D D
HE C C
HD B B
HC A A
HF
HE
HD
HC
0 0 7 5 0 0 5 0
HC HC
HC
HD HD
HD
HE HE
HE
HF HF
HF
3 5
3
5 5
3
5 5
2 5 5
HJ D D
HI C C
HH B B
HG A A
HJ
HI
HH
HG
0 0 2 2 5 0 7 2
HG HG
HG
HH HH
HH
HI HI
HI
HJ HJ
HJ
3 5
3
5 5
3
5 5
HN D D
HM C C
HL B B
HK A A
HN
HM
HL
HK
0 0 7 5 0 1 1 1
HK HK
HK
HL HL
HL
HM HM
HM
HN HN
HN
1 5 5
3 5
3
5 5
3
HR D D
HQ C C
HP B B
HO A A
HR
HQ
HP
HO
0 0 7 2 0 2 2 2
HO HO
HO
HP HP
HP
HQ HQ
HQ
HR HR
HR
2 2
3 2
3
2 2
3
5 5
HV D D
HU C C
HT B B
HS A A
HV
HU
HT
HS
0 0 7 5 0 0 0 0
HS HS
HS
HT HT
HT
HU HU
HU
HV HV
HV
3 5
3
5 5
3
HZ D D
HY C C
HX B B
HW A A
HZ
HY
HX
HW
0 0 7 2 0 2 2 2
HW HW
HW
HX HX
HX
HY HY
HY
HZ HZ
HZ
2 2
3 2
3
2 2
3
5 5
4 3 3
ID D D
IC C C
IB B B
IA A A
ID
IC
IB
IA
0 0 7 5 0 4 4 4
IA IA
IA
IB IB
IB
IC IC
IC
ID ID
ID
3 5
3
```
Works for all inputs 1 through 15, 1 through 10 are counted in the score.
***Update:** reduced the size of the generator from ~16k down to 6.1k.*
---
**Sample output for m=3:**
```
777 777
333
555 555
444 333 333
000 777 333 333 111 444 222 111
000 777 777 000 555 777 555 777
000 333 777 333 000 111 000 111
333 555
000 777 777 111 444 333 555 222
000 777 777 111 444 444 555 777
000 777 777 333 000 777 000 111
000 111 777 000 111 111 000 000
111 555 555
222 222
333
000 777 777 000 000 777 777 000
```
] |
[Question]
[
Everybody loves golfing code. Code is written in English (eh...). Therefore, everybody loves golfing English!
Your task is to write a program or function that takes a string as input, and then returns or prints the golfed version. There will be no newlines or tabs in the input.
This is how you golf a string. The order matters!
1. Remove spaces directly before and after punctuation: `"Hey there", he said ; he ' s a cat. -> "Hey there",he said;he's a cat.` The following count as punctuation: `.,?!"':;()`
2. Replace `he/she/it is`, case insensitive, with `he's/she's/it's`: `It is unfortunate that she is not coming ever. -> It's unfortunate that she's not coming ever.`
3. Words that start with capital letters in a sentence can be moved against the preceding word (omitting the space): `The farmer told Fred that he should leave. -> The farmer toldFred that he should leave.`
4. Trailing and leading spaces should be removed: `[ ]It's raining.[ ]-> It's raining.` Ignore the brackets (annoying auto-formatting).
5. Remove repeated punctuation *that is the same*: `""Here''s the cake",, said Fred..! -> "Here's the cake",saidFred.!`
If we were to golf the first paragraph of this challenge, the output would be:
>
> Everybody loves golfing code.Code is written inEnglish(eh.).Therefore,everybody loves golfingEnglish!
>
>
>
This is code golf––or rather English golf––so shortest code in bytes wins!
**Here is one all encompassing test case:**
Input: `" You are crazy"",, , , she said. It is unfortunate that Margaret had to say that... she is a Martian!.`
Output: `"You are crazy",she said.It's unfortunate thatMargaret had to say that.she's aMartian!.`
[Answer]
## Retina, 65 bytes
```
+` *([.,?!"':;()])\1* *| ([A-Z])| +$|^ +
$1$2
i`(s?he|it) is
$1's
```
Regex replacement and then a simple trim
The magic regex is:
```
*([.,?!"':;()])\1* *| ([A-Z])| +$|^ +
```
[Try it online!](http://retina.tryitonline.net/#code=K2AgKihbLiw_ISInOjsoKV0pXDEqICp8IChbQS1aXSkKJDEkMgogKyR8XiArCgppYChzP2hlfGl0KSBpcwokMSdz&input=IiAgICBZb3UgYXJlIGNyYXp5IiIsLCAsICwgc2hlIHNhaWQuIEl0IGlzIHVuZm9ydHVuYXRlIHRoYXQgTWFyZ2FyZXQgaGFkIHRvIHNheSB0aGF0Li4uIHNoZSBpcyBhIE1hcnRpYW4hLg)
[Answer]
# V, 77 bytes
```
Ó *¨[.,"':;?!()]© */±
Óã¨s¿heüit©ús is/'s
Óó«úeõ
Ó^ *ü *$
Ó¨[.,"':;?!()]©±*/±
```
Way longer than I'd like.
[Try it online!](http://v.tryitonline.net/#code=w5MgKsKoWy4sIic6Oz8hKCldwqkgKi_CsQrDk8Ojwqhzwr9oZcO8aXTCqcO6cyBpcy8ncwrDk8OzwqvDumXDtQrDk14gKsO8ICokCsOTwqhbLiwiJzo7PyEoKV3CqcKxKi_CsQ&input=IiAgICBZb3UgYXJlIGNyYXp5IiIsLCAsICwgc2hlIHNhaWQuIEl0IGlzIHVuZm9ydHVuYXRlIHRoYXQgTWFyZ2FyZXQgaGFkIHRvIHNheSB0aGF0Li4uIHNoZSBpcyBhIE1hcnRpYW4hLgoiWW91IGFyZSBjcmF6eSIsc2hlIHNhaWQuSXQncyB1bmZvcnR1bmF0ZSB0aGF0TWFyZ2FyZXQgaGFkIHRvIHNheSB0aGF0LnNoZSdzIGFNYXJ0aWFuIS4)
[Answer]
# JavaScript ES6, ~~102~~ ~~92~~ ~~61~~ ~~65~~ 95 bytes
```
x=>x.replace(/ *([.,?!"':;()])( *\1 *)*| ([A-Z])/g,"$1$3").replace(/(he|it) is/g,"$1's").trim()
```
Works on the last testcase. Saved a lot of bytes thanks to Downgoat! Impressive.
[Answer]
# Python 3.5, 213 bytes:
```
import re;R=re.sub;W=lambda G:G.group(0);print(R(r'(\W)\1+',lambda f:W(f)[0],R('\s*[^\s\w]\s*|\s*[A-Z]',lambda f:W(f).strip(),R('((I|i)t|(s|S)?(h|H)e) is',lambda i:W(i)[:[*W(i)].index(" ")]+"'s",input().strip()))))
```
Uses 3 regular expressions in a row with `re.sub` in conjunction with Python's `str.strip()` built in to golf the input English sentence.
[Try It Online! (repl.it)](https://repl.it/CaJg/1)
[Answer]
# ~~Bash 74~~ Sed 65 + 4 bytes
65 bytes for the script and 4 for the `r` and `f` flags.
~~`sed -r "s/\s*([.,?\!\"\':;\(\)A-Z])(\1|\s)*/\1/g;s/(he|she|it) is/\1\'s/i"`~~
`s/\s*([,.?\!\"\':;\(\)A-Z])(\1|\s)*/\1/g;s/(he|she|it) is/\1\'s/i`
Usage: Enter text, press enter and then `Ctrl` + `D` (send EOF).
] |
[Question]
[
**This question already has answers here**:
[Self-Interpreting Interpreter](/questions/585/self-interpreting-interpreter)
(8 answers)
Closed 8 years ago.
Duplicate? I knew somebody must've done this before.
---
Programming a programming language in itself is something that has interested me since I knew what a programming language was. So I thought I'd create a Code Golf challenge for you.
## Challenge
Create an interpreter for a given programming language, programmed entirely in itself. The interpreter should be able to run any valid program in that language, including itself.
### Inputs:
The program can take it's input as a file passed as a parameter (e.g. `python myfile.py`) or as lines from stdin (`cat myfile.py | python`).
### Outputs:
Whatever an interpreter would normally output, on the correct streams (stdout, stderr etc.)
## Specifications
* The code needs to be written in an interpretable language, and serve as an interpreter for its own language.
* It can't use an `eval()` function to interpret code.
* It must run any valid program in that language. If the language allows external modules (or includes), it must be able to read those modules.
* This task is code golf. The submission with the least characters that is correct wins. In case of a tie, the solution that was submitted first wins.
### Loophole remover:
* Yes, if you can interpret Java, Bytecode or HQ9++ in themselves, go ahead!
* In JavaScript / ES, using HTML tags such as `<script>` is not allowed.
[Answer]
# [Nothing](https://esolangs.org/wiki/Nothing), 0 chars
The source code is an empty file. It does nothing, like any Nothing program, therefore it is the correct execution of every such program.
[Answer]
# JavaScript ES6, 44 bytes/chars
```
s=>document.write(`<${t='script>'}${s}</`+t)
```
Defines a function, taking the code string as a parameter.
**How it works:**
This function simply takes the code, wraps it in `<script>` tags, and writes it into the page. It doesn't use the `eval` function at all - the browser simply runs the code when the new `<script>` element is inserted into the page.
**Tested in the FireFox console on the `about:blank` page as follows:**
```
(s=>document.write(`<${t='script>'}${s}</`+t))("alert('hi')")
```
*Yes, this is probably a loophole and as such I don't really expect to win. (It's impossible to beat the Nothing answer, anyway...)*
*If anything, hopefully it shows how it is possible to evaluate code in javascript without the use of the `eval` function.*
] |
[Question]
[
The challenge is to write a brainf\*\*\* program that searches sequentially through memory for the first **NON-zero** cell.
The program should start somewhere in fairly low memory (there will probably be some overhead/counters/etc.). Once the program starts checking cells, it should continue to the right, checking every cell in sequence until it reaches the first non-zero cell, then stop.
Testing will be performed for several random cells and values. Examples might look like: m(13) = 1, or m(144) = 137, or m(983) = 231. The actual values will be randomly generated once and used for all entries. The cell values of 1 and 255 will also be tested.
Scoring - ***different from the usual***
- code golf, lowest score wins
- in the case of a tie, earlier entry wins
- any continuous series of identical commands that changes pointer position or cell value counts as 1 point.
```
> 1 point
> > 1 point
> > > > > > > > > > > > > > > > > > > > > > > > > > 1 point
< < < < < < < < < < < 1 point
+ + + + + + 1 point
- - 1 point
[ opening a loop = 1 point
] closing a loop required, so 0 points
one point for EACH input or output
. . 2 points
. . . . . . 6 points
, 1 point
, , 2 points (not that anyone would ever do this)
```
The python 3 program I will use for scoring is found here:
<http://pastebin.com/RJi72BHa>
[Answer]
# ~~11~~ 24 Points
Edit: Now, we do not change the value that is there and do not output it. This now behaves as expected for 255 as well.
```
+[-[[-<<+>>]<<+>>-<]>+]-<<[->>+<<]>>
```
This program searches for the first non-zero byte and exits. We expect the first value pointed at to be 0, and we require that the pointer be at least at cell 1 to begin with ("The program should start somewhere in fairly low memory").
Here's a little test, no funky interpreter required:
```
[ Search for the first non-zero cell ]
[ http://codegolf.stackexchange.com/q/54432/31054 ]
[We require moving one cell to the right from the left end ] >
[Testing code: ]
>>>>>>>>> [... any number of > ...] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
[ASCII code '0'] ++++++[-<++++++++>]
<<<<<<<<< [... the same number of < ...] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
[Find it and stop: ]
+[-[[-<<+>>]<<+>>-<]>+]-<<[->>+<<]>>
>[Output, for checking: ]<
.
```
Example run:
```
~ Me$ bf f.bf
0
```
[Answer]
**Command count: 12
Golf score: 10**
`+[-[<-<]>+]>`
This is my first attempt for a Brainfuck program
This seems to work fine. the program was inspired from the answer of Brainsteel(Though seems to be highly optimized and hardly the same program)
My first attempt(Without brainsteels answer also it solves the negative 1 problem in brainsteel and my answer) was:
`+[>[[<+>-]>]<[->+<]>]<<[->+<]>-`
With Command count: 31
Golf score: 25
[Answer]
## 18 bytes, 15 points
```
>+[>[<-]<[->+<]>]>
```
Code requires to have at least two 0s before searched value.
It finds any number, **even -1** and **doesn't change it**.
[Answer]
# 12 bytes, 8 points
`+[-->>[<]<+]`
* Does not change the non-0 cell value
* Does not work if the non-0 cell is the 1st or 2nd cell
* Stops on the second cell before the non-0 cell (e.g. `[][][pointer][][non-0][][]`)
or...
`+[-->>[<]<+]>>` (14b 9pts) which *will* stop on the non-0 cell
[Answer]
Here is my attempt. After doing it, I see that it is similar to other entries.
```
+[-[[-]>-<]>+]< has 15 commands not including part that puts number in memory
does not maintain original value
stops at P for value 1~254
stops at P-1 for value = 255
```
] |
[Question]
[
In this challenge, you'll need to edit a grid of characters to make a program that does a task, while ensuring that you leave a lasting mark on the grid.
# Task
The task to perform is determined by when you answer. Specifically, for the `n`th answer, divide `n` by 5, and if the remainder is...
* 0. Read a positive integer from STDIN (or closest alternative) and print its square.
* 1. Print the value of n9-n8+n7-...-n2+n-1.
* 2. Read a string from STDIN (or closest alternative) and print it, reversed.
* 3. Print the name of the language being used.
* 4. Print the first 99 Fibonacci numbers, with some delimiter.
In all cases, "print" means to STDOUT or closest alternative. Leading or trailing whitespace is okay. A full program is required, not just a function.
# Answering (please read before posting)
>
> This is a "sequential answering" challenge. Answers have a specific order. If the previous answer, chronologically, was titled **Answer `n`**, your answer should be titled **Answer `n+1`**.
>
>
>
All answers are 100 characters (in printable ASCII) long, divided into ten rows. Each row is separated by a newline. I have already posted the first answer.
Once an answer has been verified by another user (in a comment), any user, except for the one who gave the previous answer, can submit the next answer, pursuant to the following rules:
For each answer after the first, change at least one character (but not newlines) in the previous answer to another printable ASCII character achieve the correct task. You may not add, remove, or move any characters. You may use any language with a readily available compiler or interpreter.
Furthermore, you must specify one character you changed to be your "mark". You want to maximize the longevity of your mark. If your mark is first changed by the answer five after yours, its lifespan is 4 (four other answers left it untouched). If no one ever removes your mark, then the lifespan is the total number of other answers after it.
If you answer multiple times, you may have multiple existing marks at once.
If your answer is found incorrect, please delete it if there are no subsequent valid answers. Otherwise, do not delete or change your answers.
# Scoring
Your score is the sum of your marks' longevities, divided by the total number of characters you changed. Subtract 5% from your score for each answer past the first.
For example, suppose I answer three times. First with 5 changes and a mark longevity of 3, then 4 changes and 20, then 1 change and a longevity of 7. My score is now
((3 + 20 + 7) / (5 + 4 + 1)) \* (100% - 10%) = 2.7.
[Answer]
# Answer 2, CJam, 6 changed
```
"lass Fun{
public
static
void main(
String[]
args) {
System.out
.print(0);
}
}";lW%
```
The mark is the `;` in the last line.
[Test it here.](http://cjam.aditsu.net/)
[Answer]
# Answer 5, Deadfish, changes 4
Deadfish has no input, thus the *closest alternative to STDIN* is that the number is already stored in the counter. Note that the language can't handle numbers over 255, so the "input" must be between 0 and 15 inclusive.
The `j` in `statjc` is the mark.
```
var Fun,
publjc,
statjc,
v=2; f3r(
S =[1,1];
v<99;){
S[v]=S[v-1
]+S[v++-2]
o
alert(S)
```
[Answer]
# Answer 3, CJam, 8 changed
```
"lass Fun{
public
static
void main(
String[]
args) {
System.out
.print(0);
}
";"CJam"
```
Changed the mark (`;`) from Answer 2.
My mark is the second `"` on the last line.
[Test it here.](http://cjam.aditsu.net/)
[Answer]
# Answer 6, CJam, changes 13
```
"var Fun,
publjc,
";8638UY5"
v=2; f3r(
S =[1,1];
v<99;){
S[v]=S[v-1
]+S[v++-2]
o
alert(S)";
```
[Try it online here](http://cjam.aditsu.net/)
My mark is the last `;`
[Answer]
# Answer 4, JavaScript, 56 changed
```
var Fun,
public,
static,
v=2; for(
S =[1,1];
v<99;){
S[v]=S[v-1
]+S[v++-2]
}
alert(S)
```
Removed the previous mark. My mark is the `}` in the second-to-last line. Unfortunately, JavaScript rounds the really big FIbonacci numbers, but I think it works. (Note that there should be a leading space and 2 trailing spaces that are automatically removed.)
[Answer]
# Answer 7, [><>](http://esolangs.org/wiki/Fish), changes 14
```
i:0( !#?^
publjc,
";8638UY5o
v=2; f3r:
S =[1,1];
v<99;){ !
S[v]=S[v-?
]+S[v++-2l
o
alert(S)"~
```
My mark is the `#` on the first line.
[Answer]
## Answer 1, Java
```
class Fun{
public
static
void main(
String[]
args) {
System.out
.print(0);
}
}
```
] |
[Question]
[
Create the shortest script that organizes all the logs by month and date.
# Rules
**Syntax**
```
organize <folder to scan> <folder to place logs>
```
* folder cannot be root
* the two folder should be different and not contain one another
**Behaviour**
The script should scan all the \*.log files in `<folder to scan>` and copy them to `<folder to place logs>` in sub-folders corresponding to the year and month of the last modified time of the log file, named like `year_month`.
Example:
```
organize /var/log/apache2 /temp/logs
```
would give folder structure like this:
```
/temp/logs/
|-- 2014_01
|-- 2014_02
|-- 2014_03
|-- 2014_04
|-- 2014_05
```
**Languages, environment**
All languages and OSs are permitted but need to be specified.
But since this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question, script languages (python, bash, windows batch) will be more fit from the start.
[Answer]
## Bash - 79 bytes
```
stat -c" $2/-%n-%y" $1/*.log|awk -F- '{d=$1$3"_"$4;system("mkdir"d";cp "$2d)}'
```
[Answer]
## Batch - 104 bytes
```
@cmd/von/c"for /r %1 %%a in (*.log)do @set a=%%~ta&set a=!a:~6,4!_!a:~3,2!&mkdir %2\!a!© %%a %2\!a!"
```
[Answer]
## Powershell (124 bytes)
```
Get-ChildItem $($s+"\*.log")|%{$n=$d+"\"+$_.LastWriteTime.ToString("yyyy_MM");if(!(Test-Path $n)){md $n}mi $($s+$_.Name) $n}
```
Has the added bonus of scanning for only .log files in the given folder if there are multiple file types. If not, then I can knock this down to 112. $s is the full source folder path, and $d is the destination folder path.
[Answer]
# Cobra - 223
**OS: Any with Mono/.NET**
Because this is the perfect task for an obscure compiled language! < /sarcasm>
```
class P
def main
a,b=CobraCore.commandLineArgs[1:]
for f in Directory.getFiles(a,'*.log')
m=b+File.getLastWriteTime(f).toString('yyy_MM')
Directory.createDirectory(m)
File.copy(f,m+f[f.lastIndexOf('/'):],true)
```
[Answer]
## Bourne Shell / FreeBSD 9.2+ - 92(83) bytes
```
#!/bin/sh
ls -lD"%Y_%m" $1/*.log|cut -wf6-|while read A B;do mkdir $2/$A;cp $1/$B $2/$A;done
```
] |
[Question]
[
as some of you may know, n-queens problem is a set of algorithm puzzle that given a 'n x n' where n is the board size of a (let's say) chessboard, and the main goal is for the n queens (where n is the number of the queens) not be able to 'attack' one another in the board.
now I have a set of **console code** where user can input the board size (with an exception of less than 4x4), and the program will display one solution for the board size inputted. here's the code sample in C++:
```
#include <windows.h>
#include <iostream>
#include <string>
using namespace std;
class point
{
public:
int x, y;
point() { x = y = 0; }
void set( int a, int b ) { x = a; y = b; }
};
class nQueens
{
public:
void solve( int c )
{
_count = c;
int len = (c + 1) * (c + 1);
_queens = new bool[len]; memset( _queens, 0, len );
_cl = new bool[c]; memset( _cl, 0, c );
_ln = new bool[c]; memset( _ln, 0, c );
point pt; pt.set( rand() % c, rand() % c );
putQueens( pt, c );
displayBoard();
delete [] _queens; delete [] _ln; delete [] _cl;
}
private:
void displayBoard()
{
system( "cls" );
const string t = "+---+", q = "| Q |", s = "| |";
COORD c = { 0, 0 };
HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE );
for (int y = 0, cy = 0; y < _count; ++y)
{
int yy = y * _count;
for ( int x = 0; x < _count; x++ )
{
SetConsoleCursorPosition( h, c ); cout << t;
c.Y++; SetConsoleCursorPosition( h, c );
if (_queens[x + yy]) cout << q; else cout << s;
c.Y++; SetConsoleCursorPosition( h, c );
cout << t; c.Y = cy; c.X += 4;
}
cy += 2; c.X = 0; c.Y = cy;
}
}
bool checkD( int x, int y, int a, int b )
{
if ( x < 0 || y < 0 || x >= _count || y >= _count ) return true;
if ( _queens[x + y * _count] ) return false;
if ( checkD( x + a, y + b, a, b ) ) return true;
return false;
}
bool check( int x, int y )
{
if ( _ln[y] || _cl[x] ) return false;
if ( !checkD( x, y, -1, -1 ) ) return false;
if ( !checkD( x, y, 1, -1 ) ) return false;
if ( !checkD( x, y, -1, 1 ) ) return false;
if ( !checkD( x, y, 1, 1 ) ) return false;
return true;
}
bool putQueens( point pt, int cnt )
{
int it = _count;
while (it)
{
if ( !cnt ) return true;
if ( check( pt.x, pt.y ) )
{
_queens[pt.x + pt.y * _count] = _cl[pt.x] = _ln[pt.y] = true;
point tmp = pt;
if ( ++tmp.x >= _count ) tmp.x = 0;
if ( ++tmp.y >= _count ) tmp.y = 0;
if ( putQueens( tmp, cnt - 1 ) ) return true;
_queens[pt.x + pt.y * _count] = _cl[pt.x] = _ln[pt.y] = false;
}
if ( ++pt.x >= _count ) pt.x = 0;
it--;
}
return false;
}
int _count;
bool* _queens, *_ln, *_cl;
};
int main( int argc, char* argv[] )
{
nQueens n; int nq;
while( true )
{
system( "cls" );
cout << "Enter board size bigger than 3 (0 - 3 to QUIT): "; cin >> nq;
if ( nq < 4 ) return 0;
n.solve( nq ); cout << endl << endl;
system( "pause" );
}
return 0;
}
```
now, as the code only display **one solution** only, where 4x4 should have more than one solution available, your challenge is to make the code to be able to display **more than one solution** should it's possible, and displaying the 'graphic' solution (console is recommended). C++ is recommended, but other programming language is more than welcome. Good luck!
[Answer]
## PHP
Using a simple recursive approach.
```
<?
function q($n,$t=[],$r=1,$S=str_repeat){
foreach($r>$n?$t:[]as$v)echo$f=$S('+---',$n)."+\n",$S('| ',$n)."|\n"|$S(' ',$v*4-2).q;
for(;$s<$n?$r-$s^abs($c=$p-$t[$s++])&&$c:q($n,$t+[$r=>$p],$r+1)?:$n>=$p+=$s=1;);echo$f;
}
q(4);
```
Sample output for `$n=4`:
```
+---+---+---+---+
| | q | | |
+---+---+---+---+
| | | | q |
+---+---+---+---+
| q | | | |
+---+---+---+---+
| | | q | |
+---+---+---+---+
+---+---+---+---+
| | | q | |
+---+---+---+---+
| q | | | |
+---+---+---+---+
| | | | q |
+---+---+---+---+
| | q | | |
+---+---+---+---+
```
[Answer]
# Mathematica
The positions of *n* queens on an *n* x *n* chessboard can be represented as a permutation of *n*.
For example,
The permutation, {3, 1, 4, 2},
is shorthand for the idea that there are 4 queens at
{{row3, col1}, {row1, col2}, {row4, col3}, {row2, col4}.
`array[{3, 1, 4, 2}]` returns the complete array, with 1' s now representing queens.
>
> {{0, 1, 0, 0}, {0, 0, 0, 1}, {1, 0, 0, 0}, {0, 0, 1, 0}}
>
>
>
This could be displayed as a grid through `Grid@array[{3, 1, 4, 2}]`.

or as a board, using `board[{3, 1, 4, 2}]`. The black squares are those occupied by a queen.

`solutionQ[{3, 1, 4, 2}]` displays the board and whether or not that board is a solution.

```
array[pos_]:=ReplacePart[ConstantArray[0,{l=Length[pos],l}],Partition[Riffle[pos,Range[Length[pos]]],2]/.{{a_,b_}:> ({a,b}-> 1)}]
board[pos_]:=ArrayPlot[array[pos],ImageSize->120,Mesh-> True]
solutionQ[pos_]:=
Module[{b,safeQ, len=Length[pos],files},
b=array[pos];
safeQ[b1_]:=(Max[Tr/@Table[Diagonal[b1,k],{k,-(len-2),len-2}]])<2;
{board[pos],safeQ[b]\[And]safeQ[Reverse/@b]}]
solutions[gridSize_]:=Cases[solutionQ/@Permutations[Range[gridSize]],{_,True}][[All,1]]
```
## Results
```
Table[Print[n , " queens solutions: ", Row@solutions[n]], {n, 4, 6}]
```

---
```
Table[Print[ "Number of solutions in a ", n, " by ", n, " table: ", solutions[n] // Length],
{n, 7, 8}]
```
>
> Number of solutions in an 7 by 7 table: 40
>
> Number of solutions in an 8 by 8 table: 92
>
>
>
[Answer]
## Python 2.7
Nice object-oriented solution:
```
class Queen(object):
def __init__(self, row, col):
self.row = row
self.col = col
@property
def u(self):
'Return the SW-NE diagonal by starting row'
return self.col + self.row
@property
def v(self):
'Return the NW-SE diagonal by starting column'
return self.col - self.row
class Solver(object):
'''
Solver which iterates over solutions. Each iterator produces a
string representation of a valid solution.
'''
def __init__(self, n):
self.n = n
self.queens = [Queen(r, 0) for r in range(n)]
def __iter__(self):
return self
def next(self):
self.step()
while not self.is_valid():
self.step()
# Draw the solution
line = ('+---' * self.n) + '+\n'
text = line
for row in range(self.n):
text += '| %s |\n' % ' | '.join(' Q'[c == self.queens[row].col] for c in range(self.n))
text += line
return text
def step(self, _row=None):
'Increment the solution one step'
if _row == -1:
raise StopIteration
if _row is None:
_row = self.n - 1
self.queens[_row].col += 1
if self.queens[_row].col == self.n:
self.queens[_row].col = 0
self.step(_row - 1)
def is_valid(self):
'Return True if the queens are all safe'
qc = len(self.queens)
return all(len(set(getattr(q, p) for q in self.queens)) == qc for p in ['row', 'col', 'u', 'v'])
if __name__ == '__main__':
n = int(raw_input('Enter n:'))
for s in Solver(n):
print(s)
```
[Answer]
# Haskell ([ideone](http://ideone.com/hgky6N))
```
import System.Environment (getArgs)
data Board = Board {
field :: [Int],
size :: Int
}
-- | Checks whether the board has a conflict
conflict :: Board -> Bool
conflict b = any (==x) xs || step (-1) x xs || step 1 x xs
where (x:xs) = field b
step _ _ [] = False
step s p (x:xs)
| (s+p) == x = True
| otherwise = step (s+p) p xs
-- | Returns all boards one can get by placing a queen in the next column
place :: Board -> [Board]
place b = place' b 1
where place' b s
| s > size b = []
| conflict newboard = rest
| otherwise = newboard:rest
where newboard = Board newfield (size b)
newfield = s:(field b)
rest = place' b (s+1)
-- | Returns all boards one can get for the n-th queen problem
placeAll :: Int -> [Board]
placeAll n = foldl (>>=) [Board [] n] (replicate n place)
-- | Creates a String from a board
prettyPrint :: Board -> String
prettyPrint b = unlines.map prettyLine.field$b
where prettyLine n = replicate (n - 1) '.' ++ "@" ++ replicate ((size b) - n) '.'
-- | Shows the first two solutions obtained by placeAll
main = do
[s] <- getArgs
mapM_ putStrLn . map prettyPrint . take 2 . placeAll . read $ s
```
Sample output
```
$ runghc nqueens.hs 12
...........@
........@...
..........@.
.@..........
.........@..
.......@....
.....@......
...@........
......@.....
....@.......
..@.........
@...........
..........@.
........@...
...........@
.@..........
.........@..
.......@....
.....@......
...@........
......@.....
....@.......
..@.........
@...........
$ time runghc nqueens.hs 48
..............................................@.
...........................................@....
...............................................@
.............................................@..
.........................................@......
............................................@...
..........................................@.....
........................................@.......
......................................@.........
....................................@...........
.......................................@........
.....................................@..........
...................................@............
.................................@..............
...............................@................
..................................@.............
................................@...............
..............................@.................
............................@...................
..........................@.....................
.............................@..................
...........................@....................
.........................@......................
.......................@........................
.....................@..........................
........................@.......................
......................@.........................
....................@...........................
..................@.............................
................@...............................
...................@............................
.................@..............................
...............@................................
.............@..................................
...........@....................................
..............@.................................
............@...................................
..........@.....................................
........@.......................................
.@..............................................
.........@......................................
.......@........................................
.....@..........................................
...@............................................
......@.........................................
....@...........................................
..@.............................................
@...............................................
...............................................@
.............................................@..
...........................................@....
..............................................@.
.........................................@......
............................................@...
..........................................@.....
........................................@.......
......................................@.........
....................................@...........
.......................................@........
.....................................@..........
...................................@............
.................................@..............
...............................@................
..................................@.............
................................@...............
..............................@.................
............................@...................
..........................@.....................
.............................@..................
...........................@....................
.........................@......................
.......................@........................
.....................@..........................
........................@.......................
......................@.........................
....................@...........................
..................@.............................
................@...............................
...................@............................
.................@..............................
...............@................................
.............@..................................
...........@....................................
..............@.................................
............@...................................
..........@.....................................
........@.......................................
.@..............................................
.........@......................................
.......@........................................
.....@..........................................
...@............................................
......@.........................................
....@...........................................
..@.............................................
@...............................................
runghc nqueens.hs 48 0,16s user 0,02s system 93% cpu 0,189 total
```
[Answer]
Ocaml :
```
let print_list list =
List.iter print_int list;
print_newline();;
let infect x y list =
let rec infect_rec x y n = function
[] -> false
| a :: r -> if (y = a) then true
else if ( y = a + x - n ) then true
else if ( y = a - x + n ) then true
else infect_rec x y (n-1) r in
infect_rec x y (x-1) list;;
let rec add_queen x n queen =
if x > n then print_list queen
else
for i = 1 to n do
if (infect x i queen) = false
then add_queen (x+1) n (i :: queen)
done
;;
add_queen 1 8 [];;
```
[Answer]
My short but quite readable Python solution:
```
def nqueens(n):
def state(n):
return set((i,j) for i in range(n) for j in range(n))
def move(i,j,n):
line = lambda ci,cj: set((i+d*ci,j+d*cj) for d in range(-n,n+1))
return line(1,0) | line(0,1) | line(1,1) | line(1,-1)
def solve(n1, s=state(n), r=()):
if n1==0: yield tuple(sorted(r))
for x in s: yield from solve(n1-1, s-move(x[0],x[1],n), r+(x,))
return solve(n)
```
The state of computation is represented as possible moves, and a move as the possibilities is going to remove from current state, so applying a move to a state is just set difference.
Can also generate all the solutions.
Printing the (first) solution:
```
def sol2str(s,n):
return '\n'.join(' '.join('X' if (row,col) in s else '.' for col in range(n)) for row in range(n))
n = 8
print(sol2str(next(nqueens(n)),n))
. . . . . X . .
X . . . . . . .
. . . . X . . .
. X . . . . . .
. . . . . . . X
. . X . . . . .
. . . . . . X .
. . . X . . . .
```
[Answer]
This solution is a slight trolling, but since it's not specified what solutions are considered to be the same, I guess it should qualify :). Let the original program be compiled as `queens`. Then the extension is:
```
#!/bin/bash
queens "$@" >tmpfile
cat tmpfile
tac tmpfile
```
**Explanation:** A mirrored solution is obviously also a solution. And it must be different from the original one: Pick a queen not positioned in the middle row from the original solution and Let `(x,y)` be its position (so `y != n-y-1`). Then the original and mirrored solutions differ at `(x,n-y-1)`. There is a queen at `(x,n-y-1)` in the mirrored solution, but the position must be empty in the original one.
[Answer]
**Groovy**
```
s = (0..7).permutations().findAll{
def x=0,y=0
Set a=it.collect{it-x++}
Set b=it.collect{it+y++}
a.size()==it.size()&&b.size()==it.size()
}
```
Delivers a list of all queen solutions like this:
```
[ [4, 7, 3, 0, 6, 1, 5, 2],
[6, 2, 7, 1, 4, 0, 5, 3],
... ]
```
For graphical representation add:
```
s.each { def size = it.size()
it.each { it.times { print "|_" }
print "|Q"
(size-it-1).times { print "|_" }
println "|"
}
println ""
}
```
which looks like this (2 examples of the 92 solutions):
```
|Q|_|_|_|_|_|_|_|
|_|_|_|_|_|_|Q|_|
|_|_|_|Q|_|_|_|_|
|_|_|_|_|_|Q|_|_|
|_|_|_|_|_|_|_|Q|
|_|Q|_|_|_|_|_|_|
|_|_|_|_|Q|_|_|_|
|_|_|Q|_|_|_|_|_|
|_|_|_|_|Q|_|_|_|
|_|Q|_|_|_|_|_|_|
|_|_|_|_|_|Q|_|_|
|Q|_|_|_|_|_|_|_|
|_|_|_|_|_|_|Q|_|
|_|_|_|Q|_|_|_|_|
|_|_|_|_|_|_|_|Q|
|_|_|Q|_|_|_|_|_|
```
**Explanation**:
My first Groovy experiment. I am loving the closures and the conciseness of this language!
Lets take it apart:
```
(0..7).permutations()
```
// returns a list of all permutations of the sequence [0,1,2,3,4,5,6,7]
```
.findAll{
```
Find and return all elements for which the following closure returns true
Here is how we check if all queens are safe:
```
def x=0,y=0
Set a=it.collect
```
Transform all integers in the permutations using the closure:
```
{ it-x++ }
```
We need to check if 2 queens are on the same diagonal.
Mathematically a diagonally rising line is: y = x + const
```
Set b=it.collect{it+y++}
```
A falling line is y = -x + const
Our closures return const = x+y (or x-y respectively)
We add them to a Set to find duplicates. A Duplicate means 2 queens have the same function (are on the same diagonal).
```
a.size()==it.size()&&b.size()==it.size() }
```
The last statement in the closure returns true if there are no duplicates, so all queens are safe!
] |
[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/2052/edit).
Closed 5 years ago.
[Improve this question](/posts/2052/edit)
Write a program that print sum of as many Fibonacci numbers as possible.
There is a limit in that your program should not run more than 10s on 2GHz single core PC. (equivalents are acceptable, for instance you have twice as many time on 1GHz PC).
Memory consumption is not limited, but provide details, if you exceed normal values.
Your program has to work with different input values.
Output can be calculated modulo 10^i, but i has to be at least 9 digits.
Other types of results are also welcome as long as they are presented with 9 digits and are not trivially calculated.
Post source, language input value and result.
[Answer]
## Python, 7 chars
It turns out that the period of *G(i)=F(i) mod 10^9* is *1.5e9* exactly. So when adding them up, we can group them into groups of size *1.5e9*, each of which will have the same sum (mod 10^9). Turns out, that sum is 0. So if we take N to be any multiple of *1.5e9*, the sum of the first N fibonacci numbers is 0. So:
```
print 0
```
will, given an argument `i`, print the sum of the first `i * 1.5e9` Fibonacci numbers. Super fast and works for an arbitrarily large `i`.
[Answer]
Compensating for my cores being 2.5GHz by allowing just under 8 seconds,
```
public class FiboSum
{
public static void main(String[] args)
{
long now = System.currentTimeMillis();
System.out.println("Taking F(1) = F(2) = 1, F(n) = F(n-1) + F(n-2):");
long n = 0, x = 1, y = 1, N = 1000000000;
// x = F_n, y = F_{n+1}
while (System.currentTimeMillis() - now < 7800)
{
n++;
long t = (x*x + y*y) % N;
x = x * (2*y - x) % N;
y = t;
}
System.out.println("\\sum_{r=1}^{2^"+n+"} F(r) = " + (N+x+y-1)%N + " mod " + N);
}
}
```
Output:
```
Taking F(1) = F(2) = 1, F(n) = F(n-1) + F(n-2):
\sum_{r=1}^{2^94900480} F(r) = 755986263 mod 1000000000
```
And no sign of Binet's formula or any closed form evaluation of the sum, even though there is a trivial one.
---
As a closely related point of interest, note that we can use the identity `F(m+n) = F(m+1) F(n) + F(m) F(n+1) - F(m) F(n)` to compute the `n`th Fibonacci number in `O(lg n)` arithmetic operations. Replace `int` and `long` with a suitable BigInteger implementation to taste. I've made this tail-recursive.
```
static long Fibo(int n)
{
if (n > 92) throw new ArithmeticException("Overflow");
long Fm = 1, Fmp = 1;
long Fn = 0, Fnp = 1;
while (n > 0)
{
if ((n & 1) == 1)
{
long t = Fmp * Fn + Fm * (Fnp - Fn);
Fnp = Fmp * Fnp + Fm * Fn;
Fn = t;
}
long t = Fm * (2*Fmp - Fm);
Fmp = Fmp*Fmp + Fm*Fm;
Fm = t;
n >>= 1;
}
return Fn;
}
```
Or if SML is your cup of tea then
```
fun fibo x =
let fun f 0 _ _ Fn _ = Fn
| f n Fm Fmp Fn Fnp =
let val Fm2 = Fm * (2 * Fmp - Fm)
val Fmp2 = Fmp * Fmp + Fm * Fm
in if (n mod 2 = 0)
then f (n div 2) Fm2 Fmp2 Fn Fnp
else f (n div 2) Fm2 Fmp2 (Fmp * Fn + Fm * (Fnp - Fn)) (Fmp * Fnp + Fm * Fn)
end
in f x 1 1 0 1
end;
```
Detailed reasoning at <http://www.cheddarmonk.org/Fibonacci.html>
[Answer]
Knowing that the sum of the fibbonacci series diverges, I can print the result rather trivially with 16 characters in Javascript.
```
alert(Infinity);
```
Ok, ok, enough glibness. This probably doesn't meet your criterion about trivial calculation. Here is my full version in Javascript:
```
var old = new Date().getTime();
var fib1 = 1, fib2 = 1, sum = 0;
while(new Date().getTime() - old < 2){
sum = fib1 + fib2;
fib1 = fib2;
fib2 = sum;
}
alert(sum);
```
What it alerts is unpredictable, it ranges from 1e+100 to Infinity for me.
And here it is golfed (91 chars):
```
o=new Date().getTime();f=1,g=1,s=0;while(new Date().getTime()-o< 2){s=f+g;f=g;g=s}alert(s);
```
[Answer]
Okay. I took this question as find every fib from fib(0) to fib(n) and take the sum: what's the biggest n you can deal with in 8 sec?
```
#!/usr/bin/env clisp
(defun sum (list)
(setf s 0)
(loop for foo in list do
(setf s (+ s foo))
)
s
)
(defun fib-list (n)
(loop for x from 1 to n do
(setf *fibs* (append *fibs* (list (sum (last *fibs* 2)))))
)
)
(defun test ()
(progn
;; variable initializations
(setf n 12000)
(setf ti (get-universal-time))
(setf tf (get-universal-time))
(loop while (<= (- tf ti) 8) do ; while the end time minus the start time
; is less than 8 sec...
(progn
(print n)
(setf *fibs* '(1 1))
(setf ti (get-universal-time)) ; record the start time
(fib-list n)
(print (sum *fibs*))
(setf tf (get-universal-time)) ; record the end time
(setf n (+ n 25))
)
)
(print "MAXIMUM NUMBER......")
(print n)
)
)
(test)
```
Now. this only uses one optimization: my fib calculating method, which uses a list to minimize the repetition of calculations.
The test routine reports that this code can deal with an n of 13000 in 8 seconds under win7 on a 2.35Ghz chip. I discount my dual-cores because clisp is a single-threaded process which derives no benefit therefrom.
no fancy math here, just ANSI CLISP and brute force "trivial calculation".
] |
[Question]
[
I found [this](https://youtu.be/ZYj4NkeGPdM?si=5kgpgIe8zDgfYZsK&t=2658) YouTube video with a table on it showing some card suits with ampersands. You might not understand what it is about, but I still want to make a challenge about it.
The input is two suits, being one of the following:
```
heart
diamond
spade
club
```
You can do anything for any other input.
Then the output is their 'game sum':
1. If both suits are red (heart/diamond), then:
* Up to one heart promotes to a spade
* Up to one diamond demotes to a club
2. Output in order of priority (spade > heart > diamond > club).
Leading and trailing whitespace is allowed.
Example input:
```
spade
heart
```
Example output:
```
spade and heart
```
Use any language. This is code-golf, so shortest code in bytes wins.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 58 bytes
```
O^`
h.+¶[hd]
spade $&
[td]¶d.+
$& club
( .+)?¶(.+ )?
and
```
[Try it online!](https://tio.run/##RcxRDsIgDIDh956iD3NhIeEKO4IPPi4zQ0vCEkUzt6txAC6GsVJ4Kn/Tj83ta7D5pC4LGszn6wLe6BQnTzN83pYcdj1MO80pktHQ9Xh/HDdQaPQwpqiMxmEEtIEw5z/QyBOkGEjQap@vQLW9s9sOwKNKKZYSIqWLLOtqW7NuKb5tyg@/u8pLsC1vgSVZfQE "Retina 0.8.2 – Try It Online") Takes input on separate lines but link is to test suite that splits on `+` for convenience. Explanation:
```
O^`
```
Sort in reverse order.
```
h.+¶[hd]
spade $&
```
Prefix `spade` if `heart` is followed by either `heart` or `diamond`.
```
[td]¶d.+
$& club
```
Suffix `club` if either `heart` or `diamond` are followed by `diamond`.
```
( .+)?¶(.+ )?
and
```
Keep only the first and last words and join them with `and`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
„‰áš¸#©¢O<i®“spade†Ú“#.;}{R„ €ƒÀý
```
Input as a pair of strings.
[Try it online](https://tio.run/##AVYAqf9vc2FiaWX//@KAnuKAsMOhxaHCuCPCqcKiTzxpwq7igJxzcGFkZeKAoMOa4oCcIy47fXtS4oCeIOKCrMaSw4DDvf//WyJoZWFydCIsImRpYW1vbmQiXQ) or [verify all test cases](https://tio.run/##yy9OTMpM/a9UXJCYkqqQkZpYVKKQkpmYm5@XopCcU5qkpHx4cVmlvZLCo7ZJCkr2lS7/HzXMe9Sw4fDCowsP7VA@tPLQIn@bzEPrHjXMARvxqGHB4VlAjrKedW11EFCtwqOmNccmHW44vPe/zn8A).
**Explanation:**
```
„‰áš¸ # Push dictionary string "heart diamond"
# # Split it on spaces: ["heart","diamond"]
© # Store this pair in variable `®` (without popping)
¢ # Count how many times each occurs in the (implicit) input-pair
O # Sum those counts together
<i # If it's 2:
# (this is only truthy for the following four pairs: dd,dh,hd,hh)
® # Push ["heart","diamond"] again from variable `®`
“spade†Ú“ # Push dictionary string "spade club"
# # Split it on spaces as well: ["spade","club"]
.; # Replace the first "heart" with "spade" and first "diamond"
# with "club" in the (implicit) input-pair
} # Close the if-statement
# (the implicit else uses the implicit input-pair)
{R # Sort the pair in descending order (sort + reverse)
„ €ƒ # Push dictionary string " and"
À # Rotate it once to the left to " and "
ý # Join the pair with " and " as delimiter
# (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 `"heart diamond"`; `“spade†Ú“` is `"spade club"`; and `„ €ƒ` is `" and"`.
[Answer]
# JavaScript (ES6), 80 bytes
*-6 thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)*
Inspired by [Neil's method](https://codegolf.stackexchange.com/a/269117/58563).
Expects `([a, b])`.
```
c=>(/[dt],h/.test([b,a]=c.sort())?"spade":a)+" and "+(/d,[dh]/.test(c)?"club":b)
```
[Try it online!](https://tio.run/##fZDBToQwEIbvPMWEC21A8LyG3ZsvsEeWmNJ2dzFI11JMjPENTLx41PfwefYFfARsS2FFcQ90pvN/0/mZW/JAGirLg7qoBePdNu1oukRJxlQe7ZNY8UahrIhIntK4EVIhjFd@cyCM@wuCQx9IzcAPUcKijO1z10E1RKu28BcF7qioG1HxuBI7JPl9W0qO/G3j41hywq7Liq8fa4oucazEWsmy3iEjHSpCOUrQZh1i2ITQJymgOMTJLgJ0EwGJoIhAtEoLS3jyACquQPJGc1uUGTnHV7osuWplDQRC8N1X2Jja3HSYm8mRbU/Nq7CC4Ovz9fj@ps8AFhAcP14g0JAZeeU9Y9zZXehKH1MXzVZs5g26WcdENoVRZSW5E7r4E3C1kdlzItWEsBXP64U5Cz0w6M5Cfx0tDOqchQnw7/yhc87B8BMnxrkYCuOYE3Fycgb668YCnn1@zomVneo82PBbOzPdEcPo6SK/AQ "JavaScript (Node.js) – Try It Online")
### Commented
```
c => // c[] = input array
( //
/[dt],h/ // if a is "heart" and b is
.test( // either "heart" or "diamond",
[b, a] = // where a and b are sorted such
c.sort() // that a > b:
) ? //
"spade" // use "spade" as the left output
: // else:
a // use a
) + //
" and " + // append " and "
( //
/d,[dh]/ // if b is "diamond" and a is
.test(c) ? // either "diamond" or "heart":
"club" // use "club" as the right output
: // else:
b // use b
) //
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 34 bytes
```
ṢṚµĖ41,3ḥⱮỊẸoḂƲȧ"ȯ"“ɓ¤PⱮ»Ḳ¤j“ and
```
* [Try it online!](https://tio.run/##AVwAo/9qZWxsef//4bmi4bmawrXEljQxLDPhuKXisa7hu4rhurhv4biCxrLIpyLIryLigJzJk8KkUOKxrsK74biywqRq4oCcIGFuZCD///8iZGlhbW9uZCIsImhlYXJ0Ig "Jelly – Try It Online")
* [Test suite](https://tio.run/##y0rNyan8///hzkUPd846tPXINBNDHeOHO5Y@2rju4e6uh7t25D/c0XRs04nlSifWKz1qmHNy8qElAUDJQ7sf7th0aEkWUEghMS9F4f@jhrkPd047tITL2xokpmunABSxPtzOBeQl55QmAamUzMTc/LwUICsjNbGoBEgXFySmpIJ1Tjc63P6oaU3kfwA)
A full program that takes a single list of two strings and prints the result to STDOUT.
*Thanks to @JonathanAllan for suggesting a technique that ultimately saved a byte!*
## Alternative [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes
```
ṢṚµOḢ€ọ2¬Ẹo_J$ƲḂȧ"ȯ"“ɓ¤PⱮ»Ḳ¤j“ and
```
* [Try it online!](https://tio.run/##AV0Aov9qZWxsef//4bmi4bmawrVP4bii4oKs4buNMsKs4bq4b19KJMay4biCyKciyK8i4oCcyZPCpFDisa7Cu@G4ssKkauKAnCBhbmQg////ImhlYXJ0IiwiZGlhbW9uZCI "Jelly – Try It Online")
* [Test suite](https://tio.run/##y0rNyan8///hzkUPd846tNX/4Y5Fj5rWPNzda3RozcNdO/LjvVSObXq4o@nEcqUT65UeNcw5OfnQkoBHG9cd2v1wx6ZDS7KAQgqJeSkK/x81zH24c9qhJVze1iAxXTsFoIj14XYuIC85pzQJSKVkJubm56UAWRmpiUUlQLq4IDElFaxzutHhdqDNkf8B)
A full program that takes a single list of two strings and prints the result to STDOUT.
*Thanks to @JonathanAllan for pointing out a bug!*
This works because of the following pattern:
```
╔═══════════════════════════╦════╦═════╦═════╦═════╗
║ First character ║ c ║ d ║ h ║ s ║
╠═══════════════════════════╬════╬═════╬═════╬═════╣
║ Codepoint ║ 99 ║ 100 ║ 104 ║ 115 ║
╠═══════════════════════════╬════╬═════╬═════╬═════╣
║ ọ2 ║ 0 ║ 2 ║ 3 ║ 0 ║
╠═══════════════════════════╬════╬═════╬═════╬═════╣
║ Subtract 1, or not, mod 2 ║ 1 ║ 1 ║ 0 ║ 1 ║
╠═══════════════════════════╬════╬═════╬═════╬═════╣
║ Subtract 2, or not, mod 2 ║ 1 ║ 0 ║ 1 ║ 1 ║
╚═══════════════════════════╩════╩═════╩═════╩═════╝
```
## Explanation
```
Ṣ | Sort
Ṛ | Reverse
µ | Start a new monadic chain
O | Convert to codepoints
Ḣ€ | Head of each
ọ2 | Number of times divisible by 2
Ʋ | Following as a monad:
¬Ẹ | - Any non-zero
o_J$ | - Or (the result of ọ2 from before minus the indices)
Ḃ | Mod 2
ȧ" | And zipped (with the reverse sorted input)
ȯ"“ɓ¤PⱮ»Ḳ¤ | Or zipped with "spade club" split at spaces
j“ and | Join with " and " (the last ” is implicit)
```
[Answer]
# [Perl 5](https://www.perl.org/) `-n`, 77 bytes
```
$,=" and ";/[dt] [dh]/&&s/heart/spade/+s/diamond/club/;say reverse sort/\S+/g
```
[Try it online!](https://tio.run/##NY2xDsIgFEV3v@KFNF1q@@rQifQTnBxbY1CIbVKBAJr486I@YCHnkHvAKrcN8baYh@XWrTqAR0BoAF3H5jDOgfFY7UcGQktgHCcZzjDJ5Yx17XFRwgX0VkiFjUe5iofREm/b84rcizc49VLOK/Dmt5tPDd4jry7dWCGPlAGdu8T/LmN@Khv9s6MzB4kpSFiCZCnIdzkpRlGRkhVP4X@SK0JKiMqehMYfY8NqtI/tcej6Qx9b/QU "Perl 5 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~52~~ 49 bytes
```
F²⊞υS⪫E⌈⟦υ⮌υ⟧⎇›⁼§hdκ§ι⁰⊙sc№Συλ§⪪spadeclub⁵κι and
```
[Try it online!](https://tio.run/##TY5BSwNBDIXv/RXDnBJYQQqeehIRqSAUt7fiIe5Ed3B2ZpudlPbXT1NE8BB4efl4L8NIMhRKrX0VcbBGt9NlBO3cNs9a@yoxfwPiZrUzVeG1xAxvNNuc46QTHAx95xPLwqD4gZ3bs2SSC7wIU2WB56NSWuCxbnPgM/gx@M79GPjnxM7d423PF/DLYNenotbVW7yanxD/0f2cYjVupsBD0k/DH/A3MN447ygH5@3l1kKkqeSwGpmktrtTugI "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F²⊞υS
```
Input the two strings.
```
E⌈⟦υ⮌υ⟧⎇›⁼§hdκ§ι⁰⊙sc№Συλ§⪪spadeclub⁵κι and
```
Sort them in descending order, then unless one the two strings contains `s` or `c`, change the first string from `heart` to `spade` and the second from `diamond` to `club`, then join the results with `and`.
[Answer]
# [Uiua](https://www.uiua.org), ~~76~~ 72 bytes
```
$"_ and _"⍜(⊟∩□|⊏⍖.)(∘|(⊙⊙;|⊙;)≍,,∩(("club"|"spade")=@h⊢),)×∩(∊:"hd"⊢),,
```
[Test pad](https://uiua.org/pad?src=0_7_1__RiDihpAgJCJfIGFuZCBfIuKNnCjiip_iiKnilqF84oqP4o2WLiko4oiYfCjiipniipk7fOKKmTsp4omNLCziiKkoKCJjbHViInwic3BhZGUiKT1AaOKKoiksKcOX4oipKOKIijoiaGQi4oqiKSwsCuKGrzRfNF8zIOKKnijiioI64oqZ4oqC4pahIEYg4oipwrDilqEsLCkuIHsic3BhZGUiICJoZWFydCIgImRpYW1vbmQiICJjbHViIn0K)
Naïve solution to the problem (if anyone can golf this more, comment please)
] |
[Question]
[
Specifically, this references JavaScript, a programming language that happens to be one you can run on StackExchange/StackOverflow. However, you may use any programming language to do this challenge. **This is not actual JS golfing, but merely a "code-golfable" challenge. Actual complete parsing of JS is not needed.**
An example of JS looks like this (try running all the snippets in here):
```
const constant = 1
var value = 2
for (let i = 0; i < 21; i++) {
value += constant + value // Addition
}
// Print the value
document.write(value)
```
Problem is, I want my code size to be a bit smaller. So, I could rename the variables to make it look like this:
```
var a = 1
var b = 2
for (let i = 0; i < 21; i++) {
b += a + b // Addition
}
// Print the value
document.write(b)
```
Notice how the variables have been changed to one letter, and the `const` keyword has been shortened to `var`. Then, we can remove most spaces and all comments:
```
var a=1
var b=2
for (let i = 0; i < 21; i++) {
b+=a+b
}
document.write(b)
```
(Again, this is not "complete" compression, and is just a challenge.)
So, here are the rules (look at the test case; it will make more sense):
* The keywords `const` , `let` , `var` , `while`, and `for` are not variables (notice the spaces!) and should not be changed, with the exception of `const` , which should be changed to `var` for shortening.
* A variable is defined as the longest string of characters that contain only the characters `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$`, not including the rule above. Furthermore, a variable is a variable if and only if one variable is preceded with `const` , `let` , or `var` (with spaces).
* All variables with the same name must be renamed into a single character variable (one of `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$`). All variables with different names must have different values in the result. You may assume that there are no more than 50 unique variables, so only one character is required.
* A single-line comment is all the characters at or after `//`
* All single-line comments should be removed.
* All spaces that are not within keywords must be removed. (Not newlines!)
* **After all of this,** remove any empty lines. This includes comment removal.
* Compact numbers! If a number is an integer, it is defined a number, but with a `.` and all zeros at the end.
* If an integer has more than two zeros, write the number before the final zeros (before the dot), an `e`, then the number of zeros (`30000` to `3e4`, `1515000` to `1515e3`). This is optional for two zeros. While this is not complete, it would be too complicated to compact numbers well.
* You should output all other characters normally.
There is only one test case, but it is a strange one!
## Test case:
```
// Hello world, but stranger!
// funny spacing
const m = 72000.00 / 1000
var h = String.fromCharCode(m)
let string = " world!" // Value to print
var l
for (let i = 1.00000; i < string.length; i++) {
// Number prototype to throw off some lazy variable detection
Number
console.log(string[i]) // Print each value
l += string[i]
}
string = string.split("").join("<br>")
h = l.toUpperCase()
document.write("<!DOCTYPE html><i>" + h.toUpperCase() + " " + string + "</i>")
```
## Result:
```
var m=72e3/1e3
var h=String.fromCharCode(m)
let s=" world!"
var l
for(let i=1;i<s.length;i++){
Number
console.log(s[i])
l+=s[i]
}
s=s.split("").join("<br>")
h=l.toUpperCase()
document.write("<!DOCTYPE html><i>"+h.toUpperCase()+" "+s+"</i>")
```
Notice `Number`! This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
# [Python 3](https://python.org), 501 ~~483 488 492~~ bytes
```
import re
def G(m):b=m.group;return b(1)+f'e{H(b(2))}'+b(3)
E='\n'
I='\\g<1>'
H=len
C='abcdefghijklmnopqrstuvwxyz'
C=[*C,*C.upper(),*'_$']
def S(A):
s=lambda p,r='':re.sub('(?m)'+p,r,A);A=s('const ','var ');V=re.findall('(?m)(?:let|var) (\w+)\s',A);V.sort(key=H)
for D in V:A=s(D,C.pop())if~-H(D)else C.remove(D)or A
A=s('//.*| *$');A=s('^ *');A=s(' ?([=+*\\-\(\)<>/]+) ?',I);A=s(r'(?:\.0+)([^\d])',I);A=s('; +',';');F=A=s(r'(\d)(0+)([^\d])',G);A=s(E*2,E)
while F!=A:F=A;A=s(E*2,E)
print(A.strip())
```
[Try it online!](https://tio.run/##VVNdb9owFH33r7hElWwnqfnoQ6dAQCiw0qdV6oY0ETolYEhoEmdOUta13V9n18Cq1S@J7zn3nnPt6/K5TlRx9anUh5VaS9@yrHYbZjLLFOyVztYuxE0NVa2jYit1ixCEPU7IShVVDU2RmrQZ@HDd63Q6otOBNnTxjzxFGhKM39c6LbZio1UeJJEOkM6ue5wAZPJYGFGkWSe5lgUoMI@yRkKtoES0JkDAVNsVZKM0MJOXYkoX1XD1cTM4FxKZLLZ1giHH4fCCImYZryqTIlNbduIt0iU3QnemPsholaACapqEXQGOD@888kbeTZ5FqjJLa2ZZXOxUWjBrEOuhhR2ZdneFqNW3spQ6iCrJ8KTWatXksqjFXqe1RHZr8iX4@v1uCkmdZ8NBOrTAgeRjGkYsY91AZ3mMDNqpEcJLOqR5qXQNWpK13MANy7kX@7nYatWUfS3rRhcQsy53NlS@zFjMepy/USdmV5xMfRoWlNziJ9wOukNKZj4eHAl8GsUrrLdN0t1jlheq/Kmrunna/3r@TRFe2IFrB6IxPhl3bfrjgi6PBu7ZmHsEKj@L8ngdQelqn1JPS1E1MaNslHPqYNAd8/7Yrxg9zQ91qblZyvtzH7mbtFhHWXbis5GHN/2KOAcW7h0eVtSkz0WFnbNH@ezP8NDNSEwgLWDumcITNxClKhnn6ebP5YxNuMwqCYHQMldPEvfIHxM4mmi3hf0K9gU9m3oA@98vjNjCd@wwvAxZyAfD9hIHakTd2xOu0aIXio7D2eIhXC/5O0L74GBbfSz02T9TwzVn/1NvTtSp3XOn2MI@STMJn1v@2MOUD9DxAbCxMDNgmjrcM/Pg@OEv)
I somehow managed to half the number of bytes from when I first started shortening... never done that before
Anyway, I used a lot of regex to replace the strings properly. To test, just make the variable `A` contain the javascript code. Then, at the end, print `A`.
Changes:
-4 bytes by using flag in pattern instead thanks to @Unmitigated
-5 bytes by inlining the for loop thanks to @Julian
+11 bytes to use standard I/O methods. Made this so much uglier and some fixes
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~137~~ 134 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
¶¡ε„//¡нðÚð¡εD'¬¿Qi'¢Ž}.γžj'$«©så}}˜Ćü2εнð«D„¢Ž†³#ð«Qàiyθˆë¨}D¯ÙskDdi®èë\]JõK».γ'.Qyd~}εDdiÐïQiï}D'.å≠iγ`D¨_ig'es}J]JDI‚ε'"¡ιθ€…"ÿ"}`:
```
I/O as a multi-line string.
Some minor notes:
1. The space at `for (` is removed as well, unlike the test cases.
2. Variables that are already a single letter (e.g. `i`) are still counted as any other variable, and therefore replaced with another letter in alphabetical order.
3. Assumes the input JavaScript snippet will never start with a double quote `"`.
[Try it online](https://tio.run/##VVFNaxNBGL7vr3g7CpsQ2U17EWqaS1bQerDBDxANdpOdZKfO7oTdqaHKSvBQ8ObVIpIKlUiKLZRIRWthxp4Ki79h/0h8p60V5zT7PO/zMe@K1G8zOpupr2o7nxbDD66rtn8f6X29pfcN5NlqVx03ma0@nhxlTn5w8nPNvqom6nOqd7Ls9P2vTf1jIZ8ajZp46GAGi@FIHVwxSFOP2EZ@eLqpJ2qceWpPv0ufeQFTX/RYT560lvX0jvqOvrbT3AheZZgYMP1W7zWZ3ss829E7xZsRyw9WPTV@yno2TbPl1rJ3uxhu5VObYMdv@WHxercYfiL6mGSri7MZIcR14RblXMBAJDy4Bu11CalM/LhHkznLQnqxbFkdEacSIliC6wvVatWpVsGFebxZz/0EQsTvyYTFPaebiKgR@klDBLQUlS0ATs8MkcQpch4zRwCNH/p8nYIU0EdWWmCBMeNWVyRQMjKGinnMwnMDP2oXPg6ncU@GCFUqZXhpOmLfQERGz/w2PzOVYSIGILpdSEVEgfsvNv7xAZW0I5mIrXPlXwL7mmOeKzh1uOiVzjMfs1bZdF4xVYH6nRDNsL4RcKgsweWYlVmXz73om/Y5kyVCys6aYHGJ1NpJneBuzN64I8WDfp8mDT@lJVx1IDrrEY2lM0iYpDg8591t3H@0chNCGfF6jdUJVCD8X4YIMcUNdZGOSM3F4TL@5D8)
**Explanation:**
```
¶¡ # Split the (implicit) multi-line input-string on newlines
ε # Map over each line:
„//¡ # Split it on "//"
н # Only keep the first value of each list
ðÚ # Trim any leading/trailing spaces
ð¡ # Then split it by spaces
# (note: builtin `#` fails for lines that are lacking spaces)
ε # Map over each space-splitted substring:
D # Duplicate the current substring
'¬¿Qi } '# If it's equal to dictionary string "const"
'¢Ž '# Push dictionary string "var" instead
.γ } # Then adjacent group-by the characters of the substring:
žj # Push builtin string "abc...xyzABC...XYZ012...789_"
'$« '# Append "$"
© # Store this in variable `®` (without popping)
s # Swap so the current character is at the top
å # Check if this character is in this string
} # Close the inner map
˜ # Flatten it to a single list of strings
Ć # Enclose; append its own head (which we'll discard later)
ü2 # Pop and push its overlapping pairs
ε # Map over each overlapping pair:
н # Pop and push the first item of the pair
ð« # Append a space
D # Duplicate it
„¢Ž†³ # Push dictionary string "var let"
# # Split it on the space: ["var","let"]
ð« # Append a space to each: ["var ","let "]
Qài # If either is equal to the earlier pushed string:
yθ # Push the last item of the pair
ˆ # Pop and add it to the global array
ë # Else:
¨ # Remove the appended space again
} # Close the if-statement
D # Duplicate the string
¯ # Push the global array
Ù # Uniquify it
s # Swap so the copy of the string is at the top
k # Get the index of this string in the global array
# (or -1 if it's not in it)
D # Duplicate this index
di # If it's non-negative:
® # Push variable `®` ("a-zA-Z0-9_$")
è # Index the index into this string
ë # Else:
\ # Discard the index from the stack
] # Close the open if-else and nested maps
J # Join each inner list back together to a line
õK # Remove any empty lines
» # Join it back by newlines
.γ # Adjacent group-by characters again:
'.Q '# Check if it's equal to a "."
yd # Check if it's a digit
~ # OR to check if either of these two is truthy
}ε # After the adjacent group-by: map over the substrings:
D # Duplicate the current substring
di # Pop the copy, and if it's an integer:
Ð # Triplicate it
ï # Pop one copy, and cast it to an integer
Qi # Pop the top two, and if their values are the same:
ï # Cast it to an integer
}D # After this if, duplicate the result
'.å≠i '# Pop the copy, and if it does NOT contain a ".":
γ # Group to adjacent equal digits
` # Pop and push the groups to the stack
D # Duplicate the last one
¨ # Remove one of its digits
_i # If it's 0 (including "00"; "000"; etc.):
g # Pop and push its length
'e '# Push an "e"
s # Swap the length and "e" on the stack
}J # After the if-statement: join the stack back together
] # Close the still open if-statements and map
J # Join everything back together
D # Duplicate the string
I‚ # Pair the copy with the input-string
ε # Map over this pair of multi-line strings:
'"¡ '# Split it on '"'
ι # Uninterleave it into two parts
θ # Pop and keep the last part
€ # Map over each string in this list:
…"ÿ" # Surround it with leading/trailing '"'
}` # After the map: push both lists of strings to the stack
: # Replace them, to fix spaces within double-quotes
# (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 `"const"`; `'¢Ž` is `"var"`; and `„¢Ž†³` is `"var let"`.
] |
[Question]
[
Print the following text and nothing else:
```
<html>
<body>
<p>HTML is kinda annoying</p>
</body>
</html>
I'm happy I'm not a web developer.
```
The catch? Your code must fit the template: `print(<?>)`, where `?` can be any group of characters. You can paste your completed code (with the `print(<>)` part) into [this Scastie](https://scastie.scala-lang.org/WxSQQcXFTe2vTE0yqOmXnA) to test it. When posting an answer, please mark it as a spoiler.
Here is the sbt configuration:
```
scalaVersion := "2.13.6"
addCompilerPlugin("org.typelevel" %% "kind-projector" % "0.13.0" cross CrossVersion.full)
scalacOptions ++= Seq(
"-language:higherKinds",
"-Ydelambdafy:inline",
"-deprecation",
"-encoding", "UTF-8",
"-feature",
"-unchecked",
"-language:postfixOps"
)
libraryDependencies ++= Seq(
"org.scala-lang.modules" %% "scala-xml" % "2.0.0",
"org.scastie" %% "runtime-scala" % "1.0.0-SNAPSHOT"
)
```
Beware, while the configuration provides one hint, some of these are red herrings.
This is the md5 hash of my solution: `5aa91599e4a8e194b5097b36bdb3dabf`. N.B. it looks like the hash didn't work well with newlines and certain other characters - it may have skipped over them entirely.
Hints:
>
> Types are involved near the end, at least in the solution I had.
> `>` is a single token that isn't part of the XML, and it's not a method or field.
>
>
>
hyper-neutrino and pxeger found answers, but they use workarounds that I didn't intend to be used and should have thought of while writing the question. ~~I'll award a [**500 rep bounty**](https://codegolf.meta.stackexchange.com/questions/5243/list-of-bounties-with-no-deadline/23562#23562) to another answer, provided they meet certain criteria.~~ [This](https://scastie.scala-lang.org/0PuNBwskSbmCj2Yx9uDNAw) is the solution.
[Answer]
>
>
> ```
> print(<html>
> <body>
>
> <p>HTML is kinda annoying</p>
>
> </body>
> </html>)
> print("\nI'm happy I'm not a web developer.")
> //>)
> ```
>
>
>
>
Probably not intended :)
[Answer]
>
>
> ```
> print(<html>
> <body>
>
> <p>HTML is kinda annoying</p>
>
> </body>
> </html> + "\nI'm happy I'm not a web developer.")
> def x = (<x />)
> ```
>
> [Try it on Scastie!](https://scastie.scala-lang.org/4UMBzYxrTMOlpGs1Zmf5ZQ)
>
>
>
] |
[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/123279/edit).
Closed 6 years ago.
[Improve this question](/posts/123279/edit)
This is a throwback challenge. You will choose an old computer system and an old language created for that system.
# The challenge
Pick an old computer system that was made before the year 2000. In a programming language that was created to run on that system, print said system's logo.
Example systems, their languages, and their logos:
* [Atari ST](https://en.wikipedia.org/wiki/Atari_ST) - [GFA BASIC](https://en.wikipedia.org/wiki/GFA_BASIC) - [Atari logo](http://www.matmoo.com/wp-content/uploads/2010/09/Atari.png)
* [Apple ][](https://en.wikipedia.org/wiki/Apple_II) - [Applesoft BASIC](https://en.wikipedia.org/wiki/Applesoft_BASIC) - [Full logo](https://www.loveroms.com/assets/img/consoles/logos/apple-ii-gs.png) or [Apple only](http://www.logodesignlove.com/images/classic/apple-logo-rob-janoff-01.jpg)
* [IBM PC](https://en.wikipedia.org/wiki/IBM_Personal_Computer) - IBM [`COMMAND.COM`](https://en.wikipedia.org/wiki/COMMAND.COM) or [BASIC-80](https://en.wikipedia.org/wiki/Microsoft_BASIC#BASIC-80) - [IBM logo](https://mamedev.emulab.it/etabeta/fast/files/ibmpcjr/0000.png)
# The rules
* You may not download the logo/icon from the internet or read it from the filesystem.
* You must use graphics to print the logo - no ASCII art.
* The icon's size must be at least 20 pixels by 20 pixels.
* Your program will not take any input and will clear the screen, print the logo, and exit normally.
* If the logo includes colors, your program must print the logo in the same colors, unless your system does not have a color display.
* The computer must not shut down.
* [Your system must have a logo.](https://chat.stackexchange.com/transcript/message/37729543#37729543)
* If the logo includes text (e.g. the `Apple ][` in the [Apple logo](https://www.loveroms.com/assets/img/consoles/logos/apple-ii-gs.png)), you only need to print the image part (e.g. the actual colored Apple).
# The winner
As with [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the submission with the least bytes wins!
[Answer]
## [GFA BASIC](https://en.wikipedia.org/wiki/GFA_BASIC) on Atari ST, 27 bytes
This is a manually edited source code in .LST format. It contains unprintable characters: `[SO]` and `[SI]` stand for ASCII characters #14 and #15 respectively. Both lines ends with `CR`.
```
DEFTEXT,,,32
TEXT0,28,"[SO][SI]"
```
This will draw a 28x26 Atari logo, which is part of the Atari ST system font.
[](https://i.stack.imgur.com/ntfRQ.png)
[Answer]
# [Applesoft BASIC](//en.wikipedia.org/wiki/Applesoft_BASIC) on the [Apple ][](//en.wikipedia.org/wiki/Apple_II), ~~365~~ 361 bytes
```
1GR:POKE-16302,0:I=0:O=15:P=1:Q=1:FORY=7TO47:I=I-1:IF(I<=0)THENI=7:READC:COLOR=C
2IF(Y<21)THENO=O-((21-Y)/12):GOTO4
3O=O+P-1:P=P*Q:Q=Q+0.002
4HLINO,39-O ATY:NEXT:DATA12,13,9,1,3,6:COLOR=0:HLIN16,22 AT7:HLIN18,20 AT8:HLIN16,22 AT47:HLIN18,20 AT46:VLIN14,34 AT32:VLIN15,33AT 31:VLIN16,32 AT30:VLIN18,30 AT29:VLIN22,26 AT28:COLOR=12:FORA=0TO3:VLINA,A+4 AT22-A:NEXT
```
Output and actual logo:
 
] |
[Question]
[
Your task is to write a program that will filter out some characters in a string, so that the remaining spells out (part of) the other string.
Let's say we received the string "123456781234567812345678", and the second string is "314159".
First, we put a pointer on the second string:
```
314159
^
```
So the pointer is now on 3, and we replace the not-3 characters with a hashtag until the first 3:
```
##3456781234567812345678
```
We then move the pointer to the next character until we have iterated through the string.
# Specs
* You may use any character to replace "#", and the first string will not contain the hashtag (or the replaced hashtag).
* The second string will always be longer than enough.
* Both strings will only contain ASCII printable characters (U+0020-U+007F).
# Testcases
```
input1: 123456781234567812345678
input2: 314159
output: ##3#####1##4####1###5###
input1: abcdefghijklmnopqrstuvwxyz
input2: dilemma
output: ###d####i##l##############
```
[Answer]
# Python 3, 69
```
def f(a,b,c=''):
for x in a:y=x==b[0];c+=x*y or'#';b=b[y:]
return c
```
Uses the hash for the replacement char, and take the original and replacement as a and b respectively.
Test case:
```
assert f('123456781234567812345678', '314159') == '##3#####1##4####1###5###'
```
[Answer]
# Javascript ES6, 46 bytes
```
a=>b=>a.replace(/./g,x=>x==b[i]?(i++,x):0,i=0)
```
Uses `0` as the replacement char.
[Answer]
# C#6, 112 bytes
```
string c(string h,string n)=>h==""?"":h[0]==n[0]?h[0]+c(h.Substring(1),n.Substring(1)):"#"+c(h.Substring(1),n);
```
Recursive function, takes haystack h (input1) and needles n (input2).
* If Haystack is empty, return it.
* if first characters of haystack and needle are equal, keep the first character and call recursively while skipping the first char on both parameters
* else return the replacement character (fixed to # here) followed by a recursive call again skipping the first character from haystack only.
Major factor for the length is the long name of Substring, but it's not long enough (compared to the number of usages) that a wrapping function would help to reduce further.
[Answer]
# Python, 115 Bytes
```
n,f=input()
for a in str(f):
x,r=0,""
for b in str(n):
if x==0and b==a:c,x="#",1
else:c=b
r+=c
n=r
print n
```
[Answer]
# Ruby, 44 bytes
If someone helps me golf it down by any amount, then I can say crossed-out 44 is still 44
```
->s,r{s.gsub(/./){$&==r[0]?(r[0]='';$&):?#}}
```
[Answer]
# Perl, 77 bytes
```
sub _{$p=substr$f,0,1,''}($_,$f)=@ARGV;_;print map{$_ eq$p?_&&$_||$_:'#'}/./g
```
[Answer]
# ùîºùïäùïÑùïöùïü, 18 chars / 23 bytes
```
îⓢ⒨≔í⟨Ḁ?(Ḁ⧺,$):0)⨝
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=%5B%22123456781234567812345678%22%2C%22314159%22%5D&code=%C3%AE%E2%93%A2%E2%92%A8%E2%89%94%C3%AD%E2%9F%A8%E1%B8%80%3F%28%E1%B8%80%E2%A7%BA%2C%24%29%3A%E2%8D%98%23%29%E2%A8%9D)`
Ayyy not bad. Uses 0 as the replacement char. It's just the same algorithm that I used in my JS answer.
[Answer]
I realize that there's already another JS-based solution posted using the `.replace` method that's shorter, but I'd like to submit my answers anyways...
## CoffeeScript, 55 bytes
Builds a string and returns it:
```
f=(a,b,i=0,s='')->s+=c==b[i]&&b[i++]||'#'for j,c of a;s
```
## JavaScript, 53 bytes
Operates on an array of characters from the original string:
```
f=(a,b,i=0)=>[...a].map(c=>c==b[i]?b[i++]:`#`).join``
```
[Answer]
# C, 81 bytes
```
A[99];char*b=A,*a=A+50;main(){gets(a),gets(b);while(*a)putchar(*a++^*b?35:*b++);}
```
[Answer]
# Haskell, 56 bytes
```
""%_="";(a:b)%l|a==head(l++"é")=a:b%(tail l)|0<1='#':b%l
```
[Answer]
## Mathcad, [tbd] bytes
[](https://i.stack.imgur.com/GTIDM.jpg)
---
Mathcad byte equivalence to be determined. Note that the programming operators "while", "break" and "on error" only require 1 key-combination to enter (ctl-], ctl-{ and ctl-', respectively) - they cannot be typed verbatim. What you see in the image is exactly what gets entered onto the Mathcad worksheet and the results are live - change a or b, or the function arguments, and the results update accordingly.
[Answer]
## PowerShell v2+, 72 bytes
```
param($a,$b)$i=0;-join([char[]]$a|%{if($_-ceq$b[$i]){$_;$i++}else{'#'}})
```
Takes input `$a` and `$b`, sets `$i` to `0` (our pointer). Then, we cast `$a` as a char-array and pump it through a loop `|%{...}`. Each iteration, we check if the current character is case-sensitive-equal to the character in `$b` under the pointer. If it is, add it to the pipeline with `$_` and increment our counter. Otherwise, add a `'#'` to the pipeline. All of those characters are then gathered up `(...)` and `-join`ed into one string, which is then re-placed onto the pipeline. Output is implicit.
### Example
```
PS C:\Tools\Scripts\golfing> .\filter-this-string.ps1 "Programming Puzzles & Code Golf" "PPCG"
P###########P#########C####G###
```
[Answer]
## PHP(271)
This is my first php code so it is stronly likely that it can be golfed more
```
function g($s,$b){$r='';foreach(str_split(strrev($b))as $i) $r='([^'.$i.']*?)(?:([^'.$i.']$)|'.$i.$r.')';$line=preg_replace_callback('/'.$r.'/',function ($m) {$a='';for($i=1;$i<count($m);$i=$i+2)$a=$a.$m[$i].$m[$i+1].'#';return $a;},$s);echo substr($line,0,strlen($s));}
```
* I used non-recursive regex where I am certain that a recursive breakthrough is available.
* Test it
```
<?php
g("uuuuaaaaavabbbbccccd","abcd");
function g($s,$b){$r='';foreach(str_split(strrev($b))as $i) $r='([^'.$i.']*?)(?:([^'.$i.']$)|'.$i.$r.')';$line=preg_replace_callback('/'.$r.'/',function ($m) {$a='';for($i=1;$i<count($m);$i=$i+2)$a=$a.$m[$i].$m[$i+1].'#';return $a;},$s);echo substr($line,0,strlen($s));}
```
+ In/Outputs
```
uuuuaaaaavabbbbccccd
abcd
uuuu#aaaava#bbb#ccc#
```
[Answer]
# Java, 136 bytes
```
void i(int[]a,int[]b){int i=0,j=0,n=a.length;for(;i<b.length;i++)for(;j<n;j++)if(a[j]==b[i]){j++;break;}else a[j]=0;for(;j<n;)a[j++]=0;}
```
### Ungolfed
```
void i(int[] a, int[] b) {
int i = 0, j = 0, n = a.length;
for (; i < b.length; i++)
for (; j < n; j++)
if (a[j] == b[i]) {
j++;
break;
} else a[j] = 0;
for (; j < n; ) a[j++] = 0;
}
```
### Notes
* Uses the `NUL` character as replacement, any of the first 10 would do. If you wanted a visible replacement character, this would be one byte longer.
* Input are two integer arrays of charcodes. `int[]` is one byte shorter than `char[]`.
### Outputs
```
Input 1: 123456781234567812345678
Input 2: 314159
Output: 3 1 4 1 5
Input 1: abcdefghijklmnopqrstuvwxyz
Input 2: dilemma
Output: d i l
Input 1: 314asd159asdasd
Input 2: 314159
Output: 314 159
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 5 bytes
Code:
```
.o²g£
```
Explanation:
```
.o # Overlap function.
12345 and 1456 yields:
1 456
² # Get the second input.
g # Take the length.
£ # Take the substring [0:length] and implicitly output.
```
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=Lm_CsmfCow&input=MzE0MTU5CjEyMzQ1Njc4MTIzNDU2NzgxMjM0NTY3OA)
[Answer]
# Python 3, 197 bytes
I was determined to solve this with regex, and I did. I did not really think it would be short.
```
def f(n,h):r=re.match(("([^{}]*)(.)"*len(n)).format(*n),h).groups();return"".join([i if i in n else"#"for i in"".join(["".join(d)for d in zip(["#"*len(i)for i in r[::2]],r[::-1][::2][::-1])])])
```
Ungolfed:
```
def fs(needle, haystack):
rx = "([^{}]*)(.)"
rx *= len(needle)
rx = rx.format(*needle)
r = re.match(rx, haystack).groups()
nd = r[::-1][::2][::-1]
hs = r[::2]
hs = ["#" * len(i) for i in hs]
nh = "".join([i if i in needle else "#" for i in "".join(["".join(d) for d in zip(hs, nd)])])
return nh
```
I wanted to do it with regex so I can do it again in Factor which, as a point-free functional language, does not do explicit looping. Haskell also does not do explicit looping and the Haskell solution does not use pattern matching but I don't understand the Haskell solution.
[Here's what I used to come up with the regex](https://regex101.com/r/fL2fT5/1).
[Answer]
# Python 3.5, 67
```
def f(a,b):b=[*b];return"".join(y==b[0]and b.pop(0)or"#"for y in a)
```
Ungolfed:
```
def f(a, b):
b = [*b] #Convert string to list; yeah Python 3.5
c = []
for y in a:
if y==b[0]:
c.append(b.pop(0))
else:
c.append("#")
return "".join(c)
```
Try it [here](https://repl.it/CO1y/2)
[Answer]
# PHP, 65 bytes
```
function f($s,$t){for(;a&$c=$s[$i++];)echo$c==$t[$k]?$t[$k++]:_;}
```
[Answer]
## REXX, 97 bytes
```
arg a b
o=
do while b>''
parse var b n+1 b
parse var a p (n)h+1 a
o=o||translate(p,,p)h
end
say o
```
As usual, readability is severely hampered by skipping every possible whitespace and abuttal operator.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 9 years ago.
[Improve this question](/posts/24862/edit)
It is wartime, and rationing is taking place in certain regions of your country. Your cities' region is one such region. The city chooses to give everyone the same amount, but in reality, larger people need more food. Chances are, a 200lb man is going to be eating more than that 7lb baby over there. The city, realizing that some people need more food, hires you, their best computer programmer, to solve the issue. They want you to write a program that will divvy up the food appropriately.
Being a smart programmer, you have developed a formula that gives an approximation of how much someone will eat based on their weight.
`EAT = (WEIGHT - 1) / 20 + 1`
For example, a 124 pound man will eat 7.125 units of food. Knowing that the food is served in packages of 1, and it would be irrational to cut them up, you can round the food units.
Each day, every person eats that many food units. If somebody goes for five days straight with less than that much food per day, they die of starvation.
You will receive population data in this form: `Population*Weight`, so if you receive `700*180`, you know that their are 700 180lb men in the city. Your city has 100,000 units of food stored away.
For every day your city goes without anyone dying, you get one point. Whoever has the most points wins. Make sure you output how many days your city lasted before someone died.
Here is the input:
`1000x90
2500x80
3000x150
2500x200`
Edit: So, the rule "For every day your city goes without anyone dying, you get one point" was terribly abused. Rule change here: if *anybody* dies, then game over. No more counting.
[Answer]
# Ruby, 100003 days/points (~274 years), 5 days before *someone* dies
>
> For every day your city goes without anyone dying, you get one point.
>
>
>
I shall abuse this rule as much as possible!
>
> Make sure you output how many days your city lasted before someone died.
>
>
>
Ok, I did. You didn't say anything about that affecting your score.
```
#input = STDIN.read
input = "1000x90
2500x80
3000x150
2500x200" # temporary debugging tool
food = 100000
input = input.split.map{|x| x.split('x').map &:to_i }
onlyPersonToFeedWeight = input.sort_by! {|a|
a[1] # weight of person
}.first[1] # find the lightest weighing person
foodForOnePerson = ((onlyPersonToFeedWeight - 1) / 20.0 + 1).ceil # EAT = (WEIGHT - 1) / 20 + 1
# you can see where this is going
daysNobodyDied = 0
daysSomeoneDied = 0
# first kill off all these overweight people
daysNobodyDied += 4
food -= foodForOnePerson
daysSomeoneDied += 1 # it's only all but one person in the city, don't worry
# I have a good feeling about this now
# ... I'm evil
loop {
daysNobodyDied += 4
food -= foodForOnePerson
if food >= 0
daysNobodyDied += 1
else
daysSomeoneDied += 1
break
end
}
puts "Survived for #{daysNobodyDied} days"
puts "There were #{daysSomeoneDied} days in which someone died"
puts "The first person died on day 5"
```
Output:
```
Survived for 100003 days
There were 2 days in which someone died
The first person died on day 5
```
I suggest you read the comments in the code first; they're quite amusing. ;) (Code is intentionally verbose.)
The strategy is simple:
* On the first five days, only feed the lightest person (on the fifth day). Then everyone else dies so you don't have to worry about them.
* Continue to starve this poor man with no friends or family by only feeding him once every five days until you run out of food.
* The man will probably die before you run out of food since it will now last 274 years.
Does this make me evil or something?
Oh, and by the way, if he was lying down the whole time, [he'd have a better than even chance that a bird would poop in his mouth](http://m.wolframalpha.com/input/?i=100003%20days). (Assuming the birds didn't starve.) Thanks for the... interesting fact, @Synthetica :-P
] |
[Question]
[
**CHALLENGE**
This is a fastest-code challenge.
Count how many n-dimensional [hypercubes](https://en.wikipedia.org/wiki/Hypercube) with n=1,2,3,4 exist, with vertices labeled with either 1 or 0, such that there does not exist any rectangle formed by 4 vertices such that one diagonal is 1-1 and the other diagonal is 0-0. To be more clear, the forbidden rectangles have the form:
```
10 or 01
01 10
```
Note that we are talking about all rectangles, not just the faces of the hypercube.
For example in the cube:
```
0*---1*
/| /|
0----0 |
| 0--|-0
|/ |/
1*---0*
```
there is an invalid rectangle formed by the four vertices marked with a star (\*), although all faces are valid.
The list of all known expected results is at [OEIS A000609](https://oeis.org/A000609). This is actually a conjecture, but a probable one. For more information and some "hints", see the BACKGROUND section.
The count for n=1,2,3,4 must be repeated in a loop 40 times (just to have more resolution on the measured time), and the results for n=1,2,3,4 (4,14,104,1882 respectively) printed on the first round of the loop only.
You should provide a link for tio.run.
[Here](https://tio.run/##jVZtb9owEP7s/AqvFRU0dCSsraYBlbbPW7/syyQWTXmlLsHQJHSgjt/O7sUJcZk6EMJ395wf353tM/HVLI73@3Ol43ydpHJcVolavn@4c9qmQunZa1uSq@jIpnSFNuc8STOlU/nt8497MfTa@pev34Xv4cdxwF0@R901jLfXvyoZZX2JNs3D5VPPeXEEinM5kd6I5QJkf@Q4IlsWsosWRSgMY6lhcN2eI2CiUJnsPk1VAKoQc@lOZAEcopDjMVGIHbAcVl/UxCChxxxl5IgyeQEw0hRptS40TU7zMj1YILodZ7QIlaawwmIW92X8EBbyEuTnadDko0ethVXmQ8LZsG2LMltbWGpeTofBlKsZvEL0EjBTKgW6ER9ZbDxXm20ffxYGXyHdfT1xY2lbSwstLbK02NISS1uVFRRUmk@zeRVvXgWbd41jvXucihcAjJXBnL2Ade@g@wFvmsBUDfTIon1GNFlgGMsbGJozAqU1DCTivne1vJJ@D6cLrFCNN1x8GmGg8zYnLuN6OZG3NLEpdNnEZVLC8OosBBSFRZAHgxXctCrrnkEkazB3kp/6rI@7v@ZoOILMN@cdhLHZckw/IBNHYzyHtefw2HPInlgESB0csaSEToEmgFKYc0fwHxunIyZoX@tiC7Mq1IFrjcKYzxj@mjK9QMvIpIciXS5yhygJ5GgMgKVpACHipa6UXqe0Elxd/KU7eJ7qRGXt6U3xf3Mw8Muz/reHDQOfXzUDL@Lo4LYyUv5WVfwgu4DWodWTRByWqfQ@1arYTOe41VdQjS2LsOaKJX/UuEVFGlK3abH4Ryz/IvHeJhkekXgNCQZ1Wigf3mDxTw3l@g2Sk/O5OYnkOB1WdmYM2Q29ayg6mNxNyx6/srvbFpi0wLadL3UTBR2gwaQ5QTtzgJ36nD2HeQgT4CnEFxBev7A3aoORBUY2GFtgbIOJBSY9U068XrzohCkuLsw6E57FeijfkR5Zd/PQz@z6UlqcFfLnpbnu5Aatg/retNUDXRerRy8dXqu8dN2R4RgMDAu/vd4mg0/PtAMCxaFXTrxNx/u4wf8Upl/Kuzvp31IpKCDzOPjQ182T2DwSYOKnsXmZ6g8u3@pA9XqaGnPf9PVOnq9pUU2WHv2pwK9j/zHY7/8C) is my best in C (about 30 s).
**BACKGROUND (optional)**
I have asked a question related to this challenge at [mathoverflow](https://mathoverflow.net/q/462613/136218). See the links within that question and especially the one related to the [generation of the rectangles](https://math.stackexchange.com/q/4851044/573047).
Another possible idea is using the inclusion-exclusion principle: see [this question](https://math.stackexchange.com/q/4853953/573047).
**SCORE**
I will make a first rough placement list based on the time shown in the tio.run link provided, in the "Debug" section, "User time".
Some time later a more precise one with times tested on my machine, since performance on tio.run may vary over time.
**RECORDS**
There will be another record list if someone is able to compute the case n = 5 or more in a reasonable time (let's say less than 10 minutes for n = 5 and 3 days for n = 6). In this case it may be that I won't double check, so I will trust your claim. I personally computed the case n = 5 in about 5 minutes with a slightly modified version of the above linked C software (which took 8 minutes).
**STANDINGS**
| FASTEST CODE | USER | LANGUAGE | BEST TIME ON MY MACHINE |
| --- | --- | --- | --- |
| 1 | 138 Aspen | Rust | 0.1364747 s |
| 2 | gsitcia | Python | 0.1462836 s |
| 3 | user1502040 | Python | 1.0249261 s |
| 4 | Level River St | Ruby | 1.3259241 s |
| 5 | Me | C | 25.888948 s |
| "n RECORD" | USER | LANGUAGE | RECORD and TIME MY PC |
| --- | --- | --- | --- |
| 1 | gsitcia | Python | n = 7 in 1h 19m 26s |
| 2 | gsitcia | Python | n = 6 in 1.946 s |
| 3 | 138 Aspen | Rust | n = 6 in 2h 45m 24s |
| 4 | user1502040 | Python | n = 6 in 22h 6m |
| 5 | gsitcia | Python | n = 5 in 0.156 s |
| 6 | 138 Aspen | Rust | n = 5 in 1.947 s |
| 7 | user1502040 | Python | n = 5 in 25.372 s |
| 8 | Level River St | Ruby | n = 5 in 27.900 s |
| 9 | Me | C | n = 5 in ~480 s |
The time for "n RECORD" is for a single computation of the specified value for n.
[Answer]
# Python + python-sat (about 1 second on my machine)
```
import itertools
from pysat.solvers import Glucose4
def count_cubes(n):
clauses = []
for (x, y, z) in itertools.combinations(range(1 << n), 3):
e0_p = y & (~x)
e0_n = x & (~y)
e0 = e0_p | e0_n
e1_p = z & (~x)
e1_n = x & (~z)
e1 = e1_p | e1_n
if e0 & e1:
continue
w = x ^ (e0 | e1)
x, y, z, w = x + 1, y + 1, z + 1, w + 1
clauses.append([x, w, -y, -z])
clauses.append([-x, -w, y, z])
if not clauses:
assert n == 1
clauses.append([-1, 1, -2, 2])
with Glucose4(bootstrap_with=clauses, incr=True) as m:
count = 0
while m.solve():
count += 1
model = m.get_model()
m.add_clause([-v for v in model])
return count
for t in range(40):
for n in range(1, 5):
r = count_cubes(n)
if t == 0:
print(n, r)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), n=5 in 25 seconds on TIO
```
N=5
f=->n=1,a=[0]{return if n>N
#generate rectangles
u=[]
(6**(n-1)).times{|i|
j=i*6
p=q=r=s=0
t=0
n.times{
k=j%6
p=p<<1|(k&1); q=q<<1|(41>>k&1); r=r<<1|(25>>k&1); s=s<<1|(26>>k&1)
t=k if k>3
j/=6
}
u<<[p,q,r,s] if t>4
}
#check colourings
b=[]
[0,(1<<2**n/2)-1].product(a,a).each{|z|c,d,e=z
e=(e^c)|d<<2**n/2
h=false
u.each{|w|p,q,r,s=w
g=e>>p&1
h = g!=e>>q&1 && g==e>>r&1 && g!=e>>s&1
break if h
}
b<<e unless h
}
p b.size*2
f[n+1,b]
}
f[]
```
[Try it online!](https://tio.run/##NZFNboMwEIX3PoWrqAioQ2OasCnDEXIBRCUgw09IHbBBURNydmoMWdie93lmPE@WQ/Y3TUc4kAK2kQDOUoh3yUNiP0hB64KK6Eg2JQqUaY9UYt6norygIgPECbED17XFljuO19e/qB5jPRJKz1C7gT5b6ECCgp2Oe7OLNU@HlDZwfg9M1EIbhny0G4s737SDzqg9j6KFSJCG@IcXUaAWEizEtOmhmWduoi9q9PkT5v5PvYYwjFvWMclUMuf00Z48ySavMG9ofr1cB1mLUpFsthXvmM3D0Hdd8ek7W554rbyehry3U5Y6HqZ59RjvY85ODOGuuyPY@JM74@lVpFkFRXpROL@9VtzGdQK4LfOVgFHUWtyIigIt32bSWZxalr6dhVyFuVFamORMYmq8Vqu/LAyRDkL/jNLsSUlLM0/Vd3R9UsTig7Ms0YaLOJmmfw "Ruby – Try It Online")
# [Ruby](https://www.ruby-lang.org/), n=4 repeated 40 times in 1.3 seconds on TIO
```
N=4
printoutput=true
f=->n=1,a=[0]{return if n>N
#generate rectangles
u=[]
(6**(n-1)).times{|i|
j=i*6
p=q=r=s=0
t=0
n.times{
k=j%6
p=p<<1|(k&1); q=q<<1|(41>>k&1); r=r<<1|(25>>k&1); s=s<<1|(26>>k&1)
t=k if k>3
j/=6
}
u<<[p,q,r,s] if t>4
}
#check colourings
b=[]
[0,(1<<2**n/2)-1].product(a,a).each{|z|c,d,e=z
e=(e^c)|d<<2**n/2
h=false
u.each{|w|p,q,r,s=w
g=e>>p&1
h = g!=e>>q&1 && g==e>>r&1 && g!=e>>s&1
break if h
}
b<<e unless h
}
p b.size*2 if printoutput
f[n+1,b]
}
40.times{f[];printoutput=false}
```
[Try it online!](https://tio.run/##TVLbboMwDH3PV2SahoClXdN1fRnmE/oDiElAzaV0achF1Vr67V1ImbSHJD7Hx44dR9ny537fwYZI1QlzskZaA0ZZJDUsUgGcFZCt8qtCY5WgXU1FuiPPDQpUhUGqsDKFaI6oiYUsJ@E2jkOx4FG0NN036uvYjYTSA3Tx1p0SBlCgYeVs43cx65xJaQ@Hl623JMgk4WPYBzz6pAMMHm14mj4YBcoz648/RoN@MNsH49MY6Kea@/Sdenx4gyn/zS2bJJlkA1NM55PGpBtyI89Vi1VPq9PxZN2LNJqUU1vZioU8SdZxLN7W0YLnS6lOe1uZsGBFtMSiaq/jZazYniFcXHaEEL@qaNz/BTmuhbo4apzuniPO41wBnB/1NYBpKgPuQUuBNk8TMwScBoHzTkDNwHu0A15cKix8r@3cX5kkSK1wk9GOu1EiabnU3QXj9ST7N29SZ@KVszJ3/W9W8zzqLP/8/yd86bf7/Rc "Ruby – Try It Online")
This is a recursive function which takes the solution for the previous `n`, makes a cartesian product of two copies, calculates all rectangles that bridge between them, then checks the colourings of these bridging rectangles. Because the solution for the previous `n` is known to be free of illegal colourings, it is only necessary to check rectangles that span the new dimension. This approach means there are only `1882 x 1882 = 3541924` colourings to check for `n=5` instead of `2**32 = 4 billion.` Also we only calculate colourings where the most significant bit is `0` which halves the number of calculations; the remaining colourings are the same but with all the 0's and 1's flipped. Precalculating the rectangles before checking colourings also helps.
[Answer]
# [Rust](https://www.rust-lang.org/), n=4 repeated 40 times in 0.6 seconds on TIO
A port of [@Level River St's Ruby answer](https://codegolf.stackexchange.com/a/270004/110802) in Rust.
---
[Try it online!](https://tio.run/##nVXbjtowEH0uXzGs1MimKQWW8rABPmEf@7LaopA1S4B1gi@t1G2@nY6dC3YSWqkWimX7zJkzFxuhpbpckoxLBY8PoGX6i8EK5tFgsOPwFqecUHgfAI4TU/CmFeQi5WqTaZXjYgVKaBZ5gPgBvrFkqRfzNZ7/YMnwafJcQgRLNjvNE5VmnExDCCy@ml1iWuLtZ5cJ2EDKYTIezyeo5kNLwi4@yUrD/zgpBoWN1rPjVTJCE461rGMKPY7qcJtlpzpR6Q44rOGxWpaSlBa8dudlS5fZIkgdgvehTfowe00m0ioTiw1Cxnn2kxAOn2FKIZag72fUcVv7OCBRCiNYRN4RsQkJLeRcTqKcJEULMgmh@tGow2kSP7luu0XijoTa5IjwA3x0JZiR43YOyyVM4TeQIwQYiI84I@LcIOZTWK@hDycQJxrc7OstnEScvOIWt3BYxSNW8b4Vixkm9KOPLrzVAb6s3Eivp8iqkHXeYtXjXMs9IVgMLAQWQVLaNm/1zbZ7y56v9zCPU2EifcLqkakJt/qWvUKpmdy2ChJTPGs2ThUTxO0jC3gxgLh72ADYXwC1LvO4EAbfIaGY/peusKjXzAS87950z72bPKMk0D0aasJXJGOm9LkpfdSLMw5fYWgFI/JsmwSCwBjXm8LZbJCyp52cBtjf0GXGVrD42G9ZDP69g@zDW/TbssdYj7DiRi97jYfcI@/hvbqx2yc@JHfvxV2Ink7M/G@MYNY8sZ2HmcMnqB/nbdh@l4vL5Q8)
```
const N: usize = 4;
fn main() {
let mut print_output = true;
let mut a: Vec<u64> = vec![0];
rec_function(1, &mut a, &mut print_output);
for _ in 0..40 {
print_output = false;
rec_function(1, &mut a, &mut print_output);
}
}
fn rec_function(n: usize, a: &mut Vec<u64>, print_output: &mut bool) {
if n > N {
return;
}
let mut u: Vec<(u64, u64, u64, u64)> = vec![];
for i in 0..6_u64.pow((n - 1) as u32) {
let mut j = i * 6;
let (mut p, mut q, mut r, mut s) = (0, 0, 0, 0);
let mut t = 0;
for _ in 0..n {
let k = j % 6;
p = p << 1 | (k & 1);
q = q << 1 | (41 >> k & 1);
r = r << 1 | (25 >> k & 1);
s = s << 1 | (26 >> k & 1);
if k > 3 {
t = k;
}
j /= 6;
}
if t > 4 {
u.push((p, q, r, s));
}
}
let mut b: Vec<u64> = vec![];
let pairs = [0, (1 << (1 << (n - 1))) - 1];
for &c in pairs.iter() {
for &d in a.iter() {
for &e in a.iter() {
let e = (e ^ c) | d << (1 << (n - 1));
let mut h = false;
for &(p, q, r, s) in &u {
let g = e >> p & 1;
h = g != (e >> q & 1) && g == (e >> r & 1) && g != (e >> s & 1);
if h {
break;
}
}
if !h {
b.push(e);
}
}
}
}
if *print_output {
println!("{}", b.len() * 2);
}
rec_function(n + 1, &mut b, print_output);
}
```
[Answer]
# [Python 3 (+Numpy)](http://python.org/) (n=4 repeated 40 times in 0.15 seconds, n=6 in 2.5 seconds on TIO)
```
import itertools
import functools
from collections import Counter
import time
import numpy as np
@functools.lru_cache(None)
def gen_rectangles(n):
x = []
for t in itertools.product([
(0,0,0),
(1,1,1),
(0,0,1),
(1,1,0),
(0,1,0),
(1,0,1),
], repeat=n):
a = b = c = 0
for a1, b1, c1 in t:
a, b, c = a*2+a1, b*2+b1, c*2+c1
if a < b < c:
x.append((a, b, c, a^b^c))
return x
def mask(n, k):
return ((1<<(1<<n))-1)//((1<<(1<<k))+1)
def swap_parts(n, k1, k2):
m1 = mask(n, k1)
m2 = mask(n, k2)
m12 = m1 ^ m2
ma = m1 & ~m2
mb = ~m1 & m2
d = 2**k2 - 2**k1
return m12, ma, mb, d
def swap(x, m12, ma, mb, d):
xs = x & m12
a = x & ma
b = x & mb
return x ^ xs ^ (a>>d) ^ (b<<d)
def flip_parts(n, k):
m = mask(n, k)
k1 = 1 << k
return m, k1
def flip(x, m, k1):
a = x & m
b = (x >> k1) & m
return (a << k1) | b
@functools.lru_cache(None)
def parts(n):
return [flip_parts(n, k) for k in range(n)], [swap_parts(n, k1, k2) for k2 in range(n) for k1 in range(k2)]
def reduce(x, n):
fp, sp = parts(n)
for p in fp:
x1 = flip(x, *p)
if x1 < x:
return x1, 0, p
for p in sp:
x1 = swap(x, *p)
if x1 < x:
return x1, 1, p
def make_order(d):
d = {a:b[0] for a,b in d.items()}
C = Counter(d.values())
empty = d.keys() - d.values()
l = []
while empty:
i = empty.pop()
j = d.get(i, None)
if j is None: continue
l.append(i)
k = C[j] - 1
if k == 0:
empty.add(j)
else:
C[j] = k
return l
@functools.lru_cache(None)
def gen_cubes(n):
if n == 0:
return [0, 1]
if n == 1:
return [0, 1, 2, 3]
prev = gen_cubes(n-1)
half = 2 ** (n-2)
k = 2 ** (n-1)
full = 2 ** k - 1
n1 = n - 1
bad = {}
good = []
for x in prev:
bc = bin(x).count('1')
if bc > half:
bad[x] = full ^ x, 2, full
continue
t = reduce(x, n1)
if t:
bad[x] = t
continue
good.append(x)
order = make_order(bad)
compatible = {}
masks = []
for a,b,c,d in gen_rectangles(n):
if b >= k or c < k: continue
a, b, c, d = 1 << a, 1 << b, 1 << (c-k), 1 << (d-k)
masks.append((a|b, c|d, a, d, b, c))
num_good = sum(1 for b in good for t in masks if b & t[1] in (t[3], t[5]))
prev = np.array(prev, dtype=np.uint64)
for b in good:
l = prev
for ma, mb, pa1, pb1, pa2, pb2 in masks:
q = b & mb
if q == pb1:
pa = pa1
elif q == pb2:
pa = pa2
else:
continue
l = l[l&ma != pa]#[a for a in l if a&ma != pa]
compatible[b] = list(map(int, l))
for x in reversed(order):
pre, disc, p = bad[x]
l = compatible[pre]
if disc == 0:
l = [flip(i, *p) for i in l]
elif disc == 1:
l = [swap(i, *p) for i in l]
else:
l = [p ^ i for i in l]
compatible[x] = l
out = []
for x, l in compatible.items():
x <<= k
out.extend(x|i for i in l)
return out
def count_cubes(n):
if n == 0:
return 2
if n == 1:
return 4
prev = gen_cubes(n-1)
half = 2 ** (n-2)
k = 2 ** (n-1)
full = 2 ** k - 1
n1 = n - 1
bad = {}
good = []
for x in prev:
bc = bin(x).count('1')
if bc > half:
bad[x] = full ^ x, 2, full
continue
t = reduce(x, n1)
if t:
bad[x] = t
continue
good.append(x)
order = make_order(bad)
compatible = {}
masks = []
for a,b,c,d in gen_rectangles(n):
if b >= k or c < k: continue
a, b, c, d = 1 << a, 1 << b, 1 << (c-k), 1 << (d-k)
masks.append((a|b, c|d, a, d, b, c))
num_good = sum(1 for b in good for t in masks if b & t[1] in (t[3], t[5]))
prev = np.array(prev, dtype=np.uint64)
for b in good:
l = prev
for ma, mb, pa1, pb1, pa2, pb2 in masks:
q = b & mb
if q == pb1:
pa = pa1
elif q == pb2:
pa = pa2
else:
continue
l = l[l&ma != pa]#[a for a in l if a&ma != pa]
compatible[b] = len(l)
for x in reversed(order):
pre, disc, p = bad[x]
compatible[x] = compatible[pre]
return sum(compatible.values())
if __name__ == '__main__':
t = time.time()
for i in range(7):
print(i, count_cubes(i))
print(f'{time.time() - t:.1f} seconds 0-6')
t = time.time()
for _ in range(40):
gen_cubes.cache_clear()
parts.cache_clear()
gen_rectangles.cache_clear()
for i in range(5):
gen_cubes(i)
print(f'{time.time() - t:.3f} seconds 0-4 x40')
```
[Try it online!](https://tio.run/##7Vhtb5xIDP6@v2JOJyVDSrbLJu1J0SY6qd/vD6ANGmA2IcAw5aUlatq/ntqGYRhu0@ak@5iNKOCxn7GN/RiqH9v7Sl08P2elruqWZa2s26oqmtUoOHQqGQSHuipZUhWFTNqsUg0bNT5VnQIrY9BmpTTXqiv1IxMNU3q1@nuCWhd1FyUiuZf8n0pJb5XKA7uTKqoBWqi7QjZceVcrBr@eXbNwT5eHqmbgobJOrnVdpV3S8pAU8Mc3Pvx5vhUEPvzNBagRLDU2rkawxLAme5/VUkvRXhsf8SfAzxiOBI7NJEWXReCzGI4kQN9ba0JmsOaTkTjbviNVOJM6nJNgUs4OsMUOttixxIXo10JrqVLORzCfidv4NvE8Uqtl29WK9SvKcimanCuf5aPr4yrnwW6Hh/K888B7/34S5J73LvAG4@ar0JEWddsQBDiZb0ecMoAQJvBg2LrczoXbURiQNGC3sD5IMHcoOWE/jAhT@YNERisFyfbsLN@yczoHc/8B1AccOCABqfWW9/5izZRVA3A9wMPqyjw/uhd0G5vb2EkiOA2Wt4yLm5vUw4t4t0vH9ByKbJ4ek5l5DoYU5JisgO12LHeCwMxZKPKdknnlejg5yHt2c4MKk9Q8TkHgsPDE4t923uiyWxHhMhqq5RxLuIYWlaAPjRAeLYlBdTvXHUSBFYHafoi1ltDCEqM1Lhy0zxoNARrPpvbXCHDQtgF6TKXJ1pn25v0CazvWu81iHiQ4uvGZdoGbJbApof8GHCDw2G25jKo6lTU3hYdl/E1cxeFmP7CDH@PW6RpIrWy49520PoHWyKs8XX8RRQeUODa0LHX7COvpOpePIIV@sCqkUVjO/HqfFXIwsf5msE6ita40t6E9EOqdbHnms6E@ZlE/sKwh6RVMAdVmqpPTcmE4KLMmOcYQPuzBP4fGQA4U6WZv8EakKX@wALJopKtGcNdu1xSvmixJF8@GCnihFl6YsoeqCPaOUnBcyWdAKxeDqq7lF/BrttH5SIH3ojggcbGzMwbSkQPzmWhUPHRFYaT5lDKFVaim21hQ@Qw1cldVqTsce6wk9MV6HONoiTPFe2@dYEHx0@DUeaygcUNuXjEn17BX2GO2yTPgPQoYbxy1f5VCCyazlg6czRbTb9qj/TUmhmoqrB8AqauIWqcWA7RhLalKLdoshsqfsoUU3LjpgtbzEz/FpL3w8mFSxG6g6GBLGNRAq0fqf5q8qWF2kNA5Hs88Oc89c52e5zYt5Jmd4U8I9JT6iJAOsGPjw9tUND70pit5QEEQe5B0ej0aQiW/T1gbBnsU8ja8AMJuww/7EW4sWqXXoq7FI8d72LJ91PIahF2m2o@XlnqnjWxqsGDRynndMZNW48uMxjcZLbZ4tZ18c4vgM705TaN2lvfP2H4A4eqT74KmQ@CSSGFtti/abBc2S445WoAm2iIsTuB15Q8E2v8ZiqGOMLCC3tDs4spimWIMYyz1ImtaXsJcgfz6rPA8t30hnbJuZMqppmd1CImGp5M1UGQ4GofWcR7FbCdQ3s8rGO2O0C4NCpqeGQ05ciOjcPYrJ60GIDgCQFPylwDLHJOZBlLJjhrMAiF2GBin6toF3fmYdTVTN0N0Nsah38zAGEHWsm@JSJ7muzsvy6A1DHCizFcPj@1v5sbl27B4GxZvw@JtWLx@WEjFi/9nQixJ9di0GHkKC2ZGqvbzYwVuR5ESpYwiTN1pFJUiU1F0OniB7Yz//7PGf7j1O7PffX85DkPZ4OSY02w2VRwuHk6/zQCB29qrdXD4zhoJaU8btjn/ODLUS3tHdu/LzWzziX/X9L0QJYUU9exjiL49X1hzGeAFpUXgHzy3dCz/Z78L@MIJ@JL1lxsI@vn5Jw "Python 3 – Try It Online")
Based on [@Level River St's Ruby answer](https://codegolf.stackexchange.com/a/270004/95116). The main difference is that this answer exploits additional symmetry.
As a simple example, consider a single square of the hypercube. There are 3 cases:
* All four vertices are colored the same (2 cases like this (flip))
* A single vertex is colored differently (8 cases like this (flip/rotate))
* 2 adjacent vertices are colored 1 (4 cases like this (rotate only))
This answer considers the symmetries of the n-1 hypercube, drastically reducing the amount of work necessary (in the case of n=6, it reduces 94572 cases to only 63 cases)
] |
[Question]
[
**This question already has answers here**:
[Minimum perimeter of an area [duplicate]](/questions/18349/minimum-perimeter-of-an-area)
(11 answers)
[Find the Squarish Root](/questions/167149/find-the-squarish-root)
(36 answers)
Closed 2 years ago.
## Input:
An integer `n`
## Output:
A string `A * B`
## Example
`12`
Possible 2 divisible numbers: `12 * 1`, `6 * 2`, `4 * 3`
```
12-1 = 11
6-2 = 4
4-3 = 1
```
4 and 3 has the minimal absolute difference of 1
Therefore, Output:
`4 * 3`
*Order of the numbers does **not** matter*
*This challenge idea was taken from a puzzle in Clash of Code in <https://www.codingame.com>*
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!
[Answer]
# [Python 2](https://docs.python.org/2/), 74 bytes
```
def f(x):q=[i for i in range(1,1+x)if x%i<1];q=q[len(q)/2];print q,"*",x/q
```
[Try it online!](https://tio.run/##BcHBCoMwDADQ@74iCINkK5T2pq5fIh4GNhqQaEoP3dd3792/elwae98yA2OjydIiwFcBAVEoX90zBhfejYShPeUT1tmSLWdWNPJxne8iWsHc8Bpc89YZR3owhkj9Dw "Python 2 – Try It Online")
[Answer]
# Python 2, 55 bytes
```
f=lambda n,m=1:n%m|(m*m<n)and f(n,m+1)or`n/m`+" * "+`m`
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWN83TbHMSc5NSEhXydHJtDa3yVHNrNHK1cm3yNBPzUhTSNIDC2oaa-UUJefq5CdpKCloKStoJuQlQ7eoFRZl5JRppGoZGmppccI4ZMsfQWFMTohxmKwA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
KḂZµƒε;h×YṄ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJL4biCWsK1xpLOtTtow5dZ4bmEIiwiIiwiMTIiXQ==)
-2 thanks to lyxal
```
K # Factors
ḂZ # Zipped with reverse
µ ;h # Minimum by
ƒε # Reduced by abs. diff.
×Y # Interleave with '*'
Ṅ # Join by spaces
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 13 bytes
```
ÆDżU$ạ/ÞḢj”*K
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLDhkTFvFUk4bqhL8Oe4biiauKAnSpLIiwiIiwiIixbIjEyIl1d)
-1 byte thanks to a golf from lyxal ported by emanresu A
-1 byte thanks to emanresu A
```
ÆDżU$ạ/ÞḢj”*K Main Link
ÆD Divisor List
żU$ Interleaved with its reverse
Þ Sorted by
ạ/ Absolute Difference
Ḣ Get the first one
j”* Join on "*"
K Join on spaces
```
[Answer]
# [Python](https://www.python.org), 104 bytes
```
lambda n:'%d * %d'%min([(x,n/x)for x in[i for i in range(1,n)if(n/i)%1==0]],key=lambda x:abs(x[0]-x[1]))
```
[Try it Online!](https://tio.run/##Tc3LDoIwEIXhvU8xm4YZg4FqvJH0SWoXJVCdKANBFuXpERNNuvv@zTnDPD16OSzB3JaX7@rGg1SZamALqslUx4IWYy5FpNCPEIHFMnzJK2H0cm9R50IcUAompY0pncuf7Wx@e7Hy9RujLd0uWu2IlmFkmTDgkWjz9ynxOfEl8TWxLtPQaezXiw8)
[Answer]
# Python, 96 bytes
```
f=lambda x:(lambda y:str(z:=y[len(y)//2])+" * "+str(x//z))([i for i in range(1,x) if x/i==x//i])
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 52 bytes
```
f=(n,i=n**.5|(-n)**.5)=>n%i?f(n,i+1):i+' * '+(n/i|0)
```
[Try it online!](https://tio.run/##HYlBCoMwEAC/speSXdOkLVIPtmkf4QuCGtkiG4mhJ/@eamFgBubjv37tEy/ZSBzGEtwOypmdVJW9b2iEjiD3khO/w7H0jVrWCipQGuXC25VKiAmQwYGpmwcwPB38Q2uCPsoa59HOcUK2OXY5sUxIdvFDl33KWBNoUC2oXQGZqPwA "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 41 bytes
```
f=(n,i=n**.5|0)=>n%i?f(n,i+1):i+' * '+n/i
```
[Try it online!](https://tio.run/##FYhBCsIwEAC/shfJbqPRUvRQjT6iLwhtU1bKbkmDJ/8eIwzMMO/wCfuYeMsn0Wku0VdQjuyladz1eyH/lAO/4v/Zlnq2BhowVs5coiZABg/tHRgeHrpbDWsJRpVd19mtuiC7rENOLAuS28I05JAydgQWTA@mKiITlR8 "JavaScript (Node.js) – Try It Online")
For positive number only.
[Answer]
# [Factor](https://factorcode.org/) + `math.primes.factors`, 73 bytes
```
[ divisors dup reverse zip [ first2 - abs ] infimum-by "%d * %d"vprintf ]
```
[Try it online!](https://tio.run/##HY2xDoIwFEV3v@KGhMUEEhn1A4yLi3EiDKV91RdpwfcKif58RaY7nHNyvbFplHy/Xa7nI4JJz3oSDqS134jiRRJpgNJ7pmhJYVRHq5sLP8q6ieMDp92hyS0cL6z/zs0ThBYSJXx5QgvPoqlBBdMrOnD0HOZQ9R8UpcMepSuW9Twmjy5bMwz5Bw "Factor – Try It Online")
```
! 12
divisors ! { 1 2 3 4 6 12 }
dup ! { 1 2 3 4 6 12 } { 1 2 3 4 6 12 }
reverse ! { 1 2 3 4 6 12 } { 12 6 4 3 2 1 }
zip ! { { 1 12 } { 2 6 } { 3 4 } { 4 3 } { 6 2 } { 12 1 } }
[ first2 - abs ] infimum-by ! { 3 4 }
"%d * %d"vprintf !
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 38 bytes
```
n->vecmin([abs(d-n/d)|d<-divisors(n)])
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P0/Xriw1OTczTyM6MalYI0U3Tz9FsybFRjclsyyzOL@oWCNPM1bzf0FRZl6JRpqGoZGm5n8A "Pari/GP – Try It Online")
] |
[Question]
[
**Problem**
Starting with a set of 10 coins at the start where all coins are tails up, and given n number of integers \$x\_1, x\_2, x\_3... x\_n\$ representing n rounds of coin flipping.
At each round, we randomly flip \$x\_i\$ number of coins at random. i.e Coins that were heads become tails, and vice versa. Within each round, every coin can be flipped at most once, i.e no repeats.
**Objective**
Write the shortest function that takes as input a list of integers, and calculates the expected number of heads at the end of all rounds.
Assume that the inputs will always correct, i.e every element is between 0 to 10.
Example 1:
```
# 3 coins chosen at random were flipped over one round, hence E(Heads) = 3
Input = [3]
Output = 3
```
Example 2:
```
# 5 coins chosen at random were flipped in the first round
# At the second round, only 1 was random flipped with 50% chance of
# picking a head/tail. E(Heads) = 0.5*6 + 0.5*4
# Hence E(Heads) = 5
Input = [5, 1]
Output = 5
```
[Answer]
# [Python 2](https://docs.python.org/2/), 40 bytes
```
r=0
for c in input():r+=c-r*c/5.
print r
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8jWgCstv0ghWSEzD4gKSks0NK2KtG2TdYu0kvVN9bgKijLzShSK/v@PNtVRMIwFAA "Python 2 – Try It Online")
Let \$Z\_i, 1 \le i \le 10 \$ be random variables indicating the state of the \$i\$-th coin after all flips, \$1\$ for heads and \$0\$ for tails. The number we are interested in is:
$$
E \left[ \sum\_{i=1}^{10} Z\_i \right] = \sum\_{i=1}^{10} E \left[ Z\_i \right] = 10 E\left[ Z\_1 \right]
$$
(We can do these two equalities because the expected value is linear and all \$Z\_i\$ are identically distributed)
This means it is enough to compute the expected value for a single coin, which leads to the following program, where the formula can be simplified to the above:
```
r=0.0
for c in input():r=r*(10-c)/10+(1-r)*c/10
print r*10
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8jWQM@AKy2/SCFZITMPiApKSzQ0rYpsi7Q0DA10kzX1DQ20NQx1izS1koFMroKizLwShSItQ4P//6NNdRQMYwE "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
Uses a formula I got by [plugging sympy into my Python solution](https://tio.run/##HcxNCsIwEEDh/Zxidp3UWAVxU@hJxEWbHwzYyTCJYE4fi5u3@eBJq6/Mt97TLlkrlrZLA/AhYqRiZkBdroAxKzpMjGXW0@LOOrrL/bBQP8qoAKKJK0V6jP/DdHTL70LDajfrrLdhME8zha@s7MmY3n8).
```
5(/æ¦PO5(*
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fVEP/8LJDywL8TTW0/v@PNtUx1DGMBQA "05AB1E – Try It Online")
$$
\sum\_{A \subseteq X, A \ne \emptyset} (-5)^{1-\left| A \right|} \prod\_{a\in A} a = -5 \sum\_{A \subseteq X, A \ne \emptyset} \prod\_{a\in A} {a \over -5}
$$
where \$X\$ is the multiset \$\left\{ x\_1, x\_2, \cdots, x\_n\right\}\$.
```
5(/ # divide each value by -5
æ¦ # get all non-empty subsets
P # take the product of each subset
O # sum all values
5(* # multiply result by -5
```
---
A direct port of the Python answer is the same length:
```
Îv1y5/-*y+
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cF@ZYaWpvq5Wpfb//9GmOoY6hrEA "05AB1E – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), 29 bytes
```
x=>x.reduce((a,b)=>a+b-a*b/5)
```
[Try it online!](https://tio.run/##BcFLCoAgEADQvSeZKTMihDZ6EXEx2hhFZfSj29t7C710xXM@7uYdSjLlM/ZTJ49PZACSAY2lOjRUhVZjiXm/8spqzRM44XovhdOy88KrjQ5gYxMwIpYf "JavaScript (V8) – Try It Online")
Based on [ovs](https://codegolf.stackexchange.com/users/64121/ovs)'s answer.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
λ₌+*5/-;dR
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%CE%BB%E2%82%8C%2B*5%2F-%3BdR&inputs=%5B5%2C1%2C1%5D&header=&footer=)
port of 05AB1E answer’s formula
and also, wholesomely rekted by lyxal with 5 bytes saved
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
÷5CPC×5
```
[Try it online!](https://tio.run/##y0rNyan8///wdlPnAOfD003///8fbaxjGAsA "Jelly – Try It Online")
$$
5\times(1-\prod\_{i=1}^n 1-{x\_i \over 5})
$$
Read this from right to left to get the Jelly code. The formula is derived from the same sympy output as the 05AB1E answer. This has a nice symmetry to it as `C×5` is the inverse of `÷5C`.
---
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
Port of my Python answer
```
+_×÷5ɗɗ/
```
[Try it online!](https://tio.run/##y0rNyan8/187/vD0w9tNT04/OV3/////0aY6hrEA "Jelly – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 9 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
0ë{‼+*5/-
```
Port of [*@Yousername*'s JavaScript answer](https://codegolf.stackexchange.com/a/235275/52210), which is based on [*@ovs*' answers](https://codegolf.stackexchange.com/search?q=user%3A64121+inquestion%3A235258).
[Try it online.](https://tio.run/##y00syUjPz0n7/9/g8OrqRw17tLVM9XX//zfmMtUxBGEdQwA)
**Explanation:**
```
0 # Start with 0
ë # Push the input-integers as float-array
{ # Foreach over these floats:
‼ # Apply the following two commands separated to the stack:
+ # Sum the top two values
* # Multiply the top two values
5/ # Divide the product by 5
- # And then subtract it from the sum
# (after the loop, the entire stack is output implicitly as result)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
≔⁰ηFθ≧⁻×ι⊖∕η⁵ηIη
```
[Try it online!](https://tio.run/##JcyxCsJADADQ3a/ImMAJOnTqJHYtiLiVDsc1NoH2qpezvx@Hzg9ekljSFhf3m5nOGS8BhNrTeyuAX4I@fg546iwVe80/C/DSlQ01QMep8Mq58oSd7joxSoCGiI7mUTRXvEerKESt@zA0Aa7j6Od9@QM "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @ovs' Python solution, except with a slightly rearranged formula `r-=c*(r/5-1)` which saves a byte when written in Charcoal.
```
≔⁰η
```
Start with zero heads.
```
Fθ
```
Loop through the numbers of flips.
```
≧⁻×ι⊖∕η⁵η
```
Calculate the expected number of heads.
```
Iη
```
Output the expected number of heads.
] |
[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/219190/edit).
Closed 3 years ago.
[Improve this question](/posts/219190/edit)
# Introduction
## Book cipher
A [Book cipher](https://en.wikipedia.org/wiki/Book_cipher) is a very unique method of a [encipher](https://en.wikipedia.org/wiki/Cipher). Here's how's it done:
* You have a book / a document or a article (something full of text, the more pages of text the better).
* You have a message to convey (a secret, of some sort)
* You simply-put read trough the text and the secret message *(may come from input, or reading it from 2 separate files)* - split it into words *(so, separate spaces, commas and [dots])* **so, ',' , '.' and spaces is the only requirement, how is not really that hugely important** and you keep the count of how many words there are in the text, now input the **secret message *(note, the secret's words must be in the text, so if you secret was "My Secret" then, the words "My" and "Secrets" must both exist in the text.***) and output the position of the inputted **secret message**. (E.g if the word "My" was nearly at the first page, maybe the 20th Word in the text, the program should print out '20'. Same with the word "Secrets", if that maybe were later, (let say the 93th word in the text) then your program should print out '93'.
**Note the data type of input and output:**
output numbers: Integers.
Input numbers: Integers
( **Excluding if the secret actually contains a number, then it does not need to be treated as a int. Can be a plus if it does but is not necessary.**)
### Mini Example:
document.txt - file that contains text.
Secret: "My Secret"
(in the text, this is the 20th and the 93th word) (Note, this is only a made up secret, it is not from a real file, or a real input) a more better example is below.
## Program input:
You enter "My Secret"
## Program output:
>
> 20
>
>
>
>
> 93
>
>
>
`And, again - you enter those numbers(**Integers**):`
>
> 20 93
>
>
>
## Program outputs:
>
> My
>
>
>
>
> Secret
>
>
>
*this is just to show how input and outputs are related to each other.*
For reference (if needed) You have a Python3 implementation available at my GitHub page, to see a book cipher in action
here: [GitHub - Book cipher in Py3](https://github.com/loneicewolf/Book-Cipher-Python)
* Why is this challenge interesting?
I personally think this is a educational (and interesting) challenge ( one might also exercise, because of how simple it might seem to make, but really took myself - literally **years** to even **know** **how** **to** **implement** this correctly)
Interesting article to get some background of what Cicada3301 is (**not my site**) - <https://www.clevcode.org/cicada-3301/>
[Wikipedia: Cicada3301](https://en.wikipedia.org/wiki/Cicada_3301)
I created this challenge both to, see other peoples methods of solving this (you are free to use any programming language!) and also - how long it would take others (For me, really I think it took more than 4 years actually - even in Python3. It looks simple but, for me - *really not*)
* A motivating fact: There are **still** so little info (especially on example codes) on the internet(at least by the time writing this challenge) about just, book cipher ***implementations***
# Challenge
I would highly suggest making dedicated functions for this challenge
* (instead of writing all code in the main() function - but it's totally fine to have it all in main!)
### Operation:
Here's how the program should read, process, and output the result:
First, take the text (the book/document, with the lots of text, (**not the secret**))
and:
**Note: The text can either be entered or read from a file. You choose this.**
1. read it (From a file, or enter it as input)
2. split it into words (by, I.e detecting '.', spaces(' '), and commas ',')
(Or if you already have split the input & are ready to move on to step 3, do that :) )
3. count the number of words.
Repeat this process with the Secret input part.
So, the input secret part should be:
* read it (from, again a file or enter it as input)
* split it (i.e if your input was "My Secret" - split it into words like so: "My" "Secret")
### My Python3 implementation only separate spaces.
The Key sequence - this is the n*th* words your text contains, e.g the 93th word in above example "Secrets".
### The winner will be chosen by how short the code is. (So, the shortest code = **win**)
# Example Input and Output
`example file used 'document1.txt'in this section is available at the GitHub page.`
`as well as the Python3 file used in the example below.`
`The output of your program should match the output of the Python3 program.`
# Input:
`python3 bookcipher.py`
>
> input text: a house with a Bob inside
>
>
>
# Output:
>
> you entered these words:
> ['a', 'house', 'with', 'a', 'Bob', 'inside']
>
>
>
>
> 2
>
>
>
>
> 3
>
>
>
>
> 5
>
>
>
>
> 2
>
>
>
>
> 0
>
>
>
>
> 30
>
>
>
# Input again: (decrypting)
>
> input key-sequence sep. With spaces: 2 3 5 2 0 30
>
>
>
>
> a
>
>
>
>
> house
>
>
>
>
> with
>
>
>
>
> a
>
>
>
>
> Bob
>
>
>
>
> inside
>
>
>
[Answer]
# [R](https://www.r-project.org/), 112 bytes
```
function(x,t,w=function(x)el(strsplit(x,"[^a-zA-Z]")))`if`(is.integer(x),Reduce(paste,w(t)[x]),match(w(x),w(t)))
```
[Try it online!](https://tio.run/##XZDNasMwDIDveQqRXmxw@wCDHPYKO650rWsridfE9myFJH35zAbTjIEO@vk@IRS2u3OPq1p9j6HZ2skqMs6yRZCYm73kOLBIIfrBUBrW5y95fL4fPy815/xm2hsz8WQsYYch0eID9aSQeRkJxcyIn5cLF6Mk1bM5A7nH@Ua4UFNTbyL8TEY94B7cbKF1C6RWb7SxHYwrDPK5wogxyg7BWJAQUQUk@J5GnxntulNdFaJsTJHUApZRXVUHQKvC6il5b1XJUTd/PsEKLfJ9fGeyrHGXS/5PfuFFf1HbLw "R – Try It Online")
**Ungolfed code**
```
book_cypher=function(x,t){ # define book_cyper function with args:
# x=either the message (if it's text) or the code (if it's a vector of integers)
# t=the text of the book
w=function(x){ # we need to split-up strings into words in 3 places, so we
# define the helper function 'w' to do this:
el( # get the first 'el'ement of
strsplit(x,"[^a-zA-Z]")) # splitting the argument on any character except a-z and A-Z
# (note that with the clarified challenge rules we can also do this with [., ]
# to split only on dots, commas & spaces)
} #
# now the main function body:
if(is.integer(x)){ # if the agument is of type 'integer' we need to decode:
Reduce(paste,w(t)[x]) # split the text using helper function 'w',
# and select the elements at indices given by the argument
# ('Reduce(paste())' is just a golfy way of joining the elements
# back together into a space-separated string)
} else { # otherwise, we need to encode:
match(w(x),w(t))) # split the message and the text using helper function 'w',
# and use 'match' to find the indices of the elements of the split text
# that match each element of the split message.
}
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 36 (14?) [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
**36 bytes** if we must write a program/function which encodes if given a string and decodes if given a list of integers:
```
Ñi@€Ñ}
“. , ”yḲ¹Ƈ
ị€Ç}K
⁸ŒṘ€FḊm3$⁼¤ŀ
```
A full program accepting two arguments:
* the message string or list of integers; and
* the book text.
which prints either a list of integers (when given a message string) or the decrypted message (if given a list of integers).
**[Try it online!](https://tio.run/##y0rNyan8///wxEyHR01rDk@s5XrUMEdPQUfhUcPcyoc7Nh3aeayd6@HubpBke60316PGHUcnPdw5A8h3e7ijK9dY5VHjnkNLjjb8//9fyVChODW5KLVEITe1uDgxPVXpv1JIRmYxjKuQnJNYXKyQkVgMVJeTpmdopKMAZJcDnQCiDRXyixSMFPJLMlKLEAaVZOSnFOspAQA "Jelly – Try It Online")**
---
**14 bytes** if we *only* need to write an encoder:
```
“. , ”yḲ¹Ƈ)iⱮ/
```
A dyadic Link accepting a list `[message, book_text]` which yields a list of integers.
**[Try it online!](https://tio.run/##y0rNyan8//9Rwxw9BR2FRw1zKx/u2HRo57F2zcxHG9fp////P1opJCOzWCE3tbg4MT1VITknsbhYISOxWKE4NSdNz9BIRwHILgcaA6INFfKLFIwU8ksyUouACpKLUkuAOksy8lOK9ZR0FJQMEYJg45RiAQ)**
[Answer]
# [Husk](https://github.com/barbuz/Husk), 32 bytes
```
?ö;msm€₁⁰₁ö;m!₁⁰mrwo√←²
wm(?c' √
```
[Try it online!](https://tio.run/##yygtzv7/3/7wNuvc4txHTWseNTU@atwAJEEiihBeblF5/qOOWY/aJhzaxFWeq2GfrK4A5P///1@pJCOzWAGIcisVilOTi1JLFHJTi4sT01OVoHKFpZnJ2QpJRfnleQpp@RUgtRmZKZl56SAtOYlVlTANCpl5CokwQ7JKcwtAalLy0/WUAA "Husk – Try It Online")
If input is a string of letters/words: encodes to string of integers:
input: `"this is my secret message"`+book, output: `"1 5 7 12 9"`
If input is a string of integers: decodes to string of words:
input: `"1 5 7 12 9"`+book, output `"this is my secret message"`
([try it](https://tio.run/##yygtzv7/3/7wNuvc4txHTWseNTU@atwAJEEiihBeblF5/qOOWY/aJhzaxFWeq2GfrK4A5P///1/JUMFUwVzB0EjBUum/UklGZrFCYWlmcrZCUlF@eZ5CWn6FAlAoIzMlMy9dIbdSISexqlIhN7W4ODE9VSEzTyFRoTg1uSi1RCGrNLcApCYlP11PCQA))
---
[Encoder](https://tio.run/##yygtzv7/P/dR05pHTY2PGjcAyUObuMpzNeyT1RUedcz6//@/UklGZrECEOVWKhSnJhellijkphYXJ6anKkHlCkszk7MVkoryy/MU0vIrQGozMlMy89JBWnISqyphGhQy8xQSYYZkleYWgNSk5KfrKQEA) (15 bytes) and [Decoder](https://tio.run/##yygtzv7/3zpX8VFT46PGDYc2cZXnatgnqys86pj1////aEMdUx1zHUMjHcvY/0olGZnFCoWlmcnZCklF@eV5Cmn5FQpAoYzMlMy8dIXcSoWcxKpKhdzU4uLE9FSFzDyFRIXi1OSi1BKFrNLcApCalPx0PSUA) (15 bytes) would total 30 bytes as separate programs (with 9 bytes of shared code).
[Answer]
# [J](http://jsoftware.com/), 23 bytes
```
(i.~cut@rplc&', . ')~;:
```
[Try it online!](https://tio.run/##RVFBasMwELzrFUMPdQOOyDkltGmhUCgE2n5AluVIjaMNklzjS77urpSEHgSr1czszOpnvpNVh80aFWqssOazlHj9/HibH5w86yE9h1Ov76saEtXi/LieF6IlvZEMXokXamBVhIKlIRok2ptkTcDoksW2d9qAPLiFvQqt8XWpR6MKykX8mjAhDt5PUmx9C0/JOr/HkQLjWDoq10I1NCSmqlRjV6hc@9LAEtmFYu5lXiY5H11ryqyLMdX35Zbc0chcTRnnqwSl08CvE3hCJkl80RVg2ILz/yoSu1Dky/MVX@MdLWWlg6dRSvFtOVZMxLm4aChwHImcTaFxCZp8N8Sc0RUDLj0Jjk4lVuHVYrR5ds7FEjn6dYmkjeId5rA90SGLDKebx3iYxEIYbYkNaXSobt9SfkNd9MpmqvkP "J – Try It Online")
This takes the document text as the left argument and the string of words as the right argument.
The main verb:
* `;:` Chops the secret string into boxed words
* `rplc&', . '` Replaces commas and periods with space.
* `cut` Cuts the remaining text on spaces into a boxed list of words.
* `i.~` Finds the index of each input word within that list.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~154~~ 147 bytes
Thanks to ceilingcat for the -7.
I'm assuming from the challenge that I can have a pre-split array of secret words and that the indexes must be 1-based.
Takes an array of the word list and a string which contains one or more 1-based indexes or words, and returns the inverse of each word/index. These may be mixed: for example, if `my test` returns `5 10`, then `my 10` returns `5 test`. The words are case-sensitive.
How it works:
```
f(char **a, char *s) {
int i,t,v;
char *u;
for(
t=NULL; // initialize the tokenizer
t=strtok(t?NULL:u=strdup(s),"., "); // tokenize the input on first call
printf(v?"%s ":"%d ",v?:i+1)) // print either string or index
for(
v=(i=atoi(t))?a[i-1]:(i=0); // integer or string?
!v*a[i]&&strcmp(t,a[i]); // if string, search for match
i++);
}
```
```
i,t,v;f(a,s)int*a;{for(t=0;t=strtok(t?0:strdup(s),"., ");printf(v?"%s ":"%d ",v?:i+1))for(v=(i=atoi(t))?a[i-1]:(i=0);!v*a[i]&&strcmp(t,a[i]);i++);}
```
[Try it online!](https://tio.run/##bVNLc9owEL77V2zdCUiOCDZJ80B1ObUzncn01hPhoMiyUWwsaklQyNCfXirZQNo0Ho21j293P2lXfFBwvt9LYsiK5ogRjWVtIkafc9Ugk8bUpNo0RpXITOKxEzO7RBqT8IJAiOmycfAcrSbhmYZwHJ5lEJLVZCzPE4x9ilWKZMqMkshgPGFTOUhmY2eKMX23ipw@6/VcVr5YIkO8iqk8P8d0t38va17ZTMBHbTKpLuafgn9MlXz0tsARgAWTNVopmWF4DgC@fL3/DFFBnei9ksBTGhMoCVTexuesgUhPZ6kH@y80c6nBLQZGaBOSo/0quY5vb2EUj5K7GK7cSi6T65sXQBt4QDnpAGQe6jO9xn/7fn/fijsCUcTcz3auaPMWncUGtOCNcCcUWrNCvBRO4APcQDKCu7eSdzm3r3OGrmk/rOSlFx4bta69kKuffuvcc5nJunips9h4a8W27X6i4eBtLPO/jqOXnuxi2YZDmCm/eU4nPpGhge9Jjoo0V0tRo3BodTPUriFimEluhmvVZC2PJsRdMwH8HLmJoWB9F38VwlSyFqhnCfSeCBSYQt4IgayLcMND26BGrGWdIecMWp2lnFWV4siNJgEtt0LlEDFMTyXKUwk5KCmUbgzheHtV@kbVg88dx04rN9dp2n@o@xgOWv8h7h8xbFrOUttpu@BU0j0uCu5WYGmNRqE/sn@EzuTfQAs7euhfQZv/g7anoA7HK6UF6kjuQFRaHOC2Zo@VAKPANwD8pUtVs2bjSwS7/W@eV6zQ@8HicrQfrP8A "C (gcc) – 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/195663/edit).
Closed 4 years ago.
[Improve this question](/posts/195663/edit)
## Challenge
* Construct `n` strings, each with three distinct letters, chosen randomly with equal probability.
* Print the proportion `k/n` where `k` is the number of strings such that all three characters are in ascending order. Print also those `k` strings.
## Input
* The only input is `n` (and thus it must be a positive integer).
## Outputs
* The proportion `k/n` must be truncated to two decimal places.
* The strings that are in ascending order of letters.
## Requirements
* The letters must come from the English alphabet.
* You cannot print the value of `k`.
## Examples
* Input: `6`, Output: `0.16 agh`
* Input: `1`, Output: `1.00 suv`
* Input: `9`, Output: `0.22 hls jqr`
## How to Win
* Fewest number of bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 31 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
13 bytes to cater for the truncation requirement!
```
ØaẊ⁸СḊḣ€3ṢƑƇðL÷+⁵×ȷ2ḞṾs2j”.Ḋṭ⁸
```
A monadic link which, given an integer, yields a list.
**[Try it online!](https://tio.run/##AVEArv9qZWxsef//w5hh4bqK4oG4w5DCoeG4iuG4o@KCrDPhuaLGkcaHw7BMw7cr4oG1w5fItzLhuJ7hub5zMmrigJ0u4biK4bmt4oG4/8OHS///MTY "Jelly – Try It Online")** (footer joins the list with spaces)
---
If (1) we remove the truncation requirement and (2) "The letters must come from the English alphabet" implies that we may choose any subset of three or more such letters then this 16 works:
```
“ḃ»Ẋ⁸С⁼ƇḢ$ðL÷;⁸
```
[Try this one](https://tio.run/##ATQAy/9qZWxsef//4oCc4biDwrvhuorigbjDkMKh4oG8xofhuKIkw7BMw7c74oG4/8OHS///MTAw "Jelly – Try It Online") (only uses A, B, and C)
---
If we may also avoid the unobservable creation of all the strings as part of of our code. then this 15 works:
```
6ẋX€ỊƇ“ḃ»ẋðL÷;⁸
```
[Try this one](https://tio.run/##ATEAzv9qZWxsef//NuG6i1jigqzhu4rGh@KAnOG4g8K74bqLw7BMw7c74oG4/8OHS///MTAw "Jelly – Try It Online") (only uses A, B, and C, and does not create any unordered strings)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 25 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
;ÆBö3Ãf_¶ñ
u»UÊ/N)h2)ú0,4
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O8ZC9jPDZl%2b28Qp1u1XKL04paDIp%2bjAsNA&input=Ng)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 26 bytes
```
FNQKO.PG3IqKSK=ZhZK;.RcZQ2
```
[Try it online!](https://tio.run/##K6gsyfj/380v0NtfL8Dd2LPQO9jbNiojyttaLyg5KtDo/38LAA "Pyth – Try It Online")
Does what OP wants, +4 bytes due to truncation requirement.
## How it works
```
FNQKO.PG3IqKSK=ZhZK;.RcZQ2
FNQ - For N in Input
K - K is equal to
O.P 3 - A random permutation length 3 of...
G - The lowercase alphabet
IqKSK - If K is sorted
=ZhZ - Increment Z (which is autoinitialized to 0)
K - Implicitly print K
; cZQ - End loop, float division of Z by the input
.R 2 - Round to 2 decimal points
```
# [Pyth](https://github.com/isaacg1/pyth), 24 bytes
```
FNQI!O6=ZhZSO.PG3;.RcZQ2
```
[Try it online!](https://tio.run/##K6gsyfj/380v0FPR38w2KiMq2F8vwN3YWi8oOSrQ6P9/CwA "Pyth – Try It Online")
Cheat answer but since it only saves two bytes im not gonna bother. Also +4 due to truncation
[Answer]
# [Python 3](https://docs.python.org/3/), 131 bytes
It seems like having to print the string complicates the program...
```
from random import*
n=int(input())
o=[]
a=['a','b','c']
x=0
for i in range(n):
o+=[sample(a,3)]
x+=a==o[-1]
print('%.2f'%(x/n),o)
```
[Try it online!](https://tio.run/##FYxBDsIgEADv@wouDWBRq40Xk30J4YBalER2CWKCr8f2MJnTTP7VF9PceyicRPH0WBVT5lJ3QBipqkj5W5XWwGgdeLTSSyNvK3fpoOEEgYuIItLWPxdF@gqCR7Qfn/J7Ud7M2oFoI3pEtvuTg1y2sxwO5yAH1Y6kDeveL9Mf "Python 3 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 44 bytes
```
((4j2":%~),@,~[:u:97+26/:~@?~]#3:)1#.0=?@$&6
```
[Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NTRMsoyUrFTrNHUcdOqirUqtLM21jcz0reoc7OtilY2tNA2V9Qxs7R1U1Mz@a3JxFaUWlmYWpSqo55XmphZlJqtzFSXmpeTnZlalAu3hSk3OyFdIUzA0wMcyMkOwFBDM/wA "J – Try It Online")
Note: This one does not actually construct the strings (the one below does) but its output has an identical probability distribution. I agree with Nick Kennedy on this point.
---
# [J](http://jsoftware.com/), 48 bytes
```
(];~4j2":(%~#))[:<@u:"1[:(97+(-:/:~)"1#])26?~#&3
```
[Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NWKt60yyjJSsNFTrlDU1o61sHEqtlAyjrTQszbU1dK30reo0lQyVYzWNzOzrlNWM/2tycRWlFpZmFqUqqOeV5qYWZSarcxUl5qXk52ZWpQLt4kpNzshXSFMwNMDHMjJDsBQQzP8A "J – Try It Online")
Note: Because the required output does not have a homogeneous data type, J requires us to box it.
] |
[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/190250/edit).
Closed 4 years ago.
[Improve this question](/posts/190250/edit)
## Background
Joe is working on his new Brainfuck answer on Codegolf. The algorithm he's using to solve the challenge is a bit complicated, so Joe came up with idea of simplifying his Brainfuck notation to make programming easier and faster.
## The challenge
Let's look at snippet written by Joe a moment ago:
```
0+++++1+++++0[3+0-]+1[3-2+1-]2[1+2-]3[0-3[-]]
```
This program was meant to check for equality of #0 and #1 cells in memory. Your task is to create a preprocessor for Joe, that will replace **single digits** from input with '>' and '<' characters, so the memory pointer will slide to cell specified.
## Input
You may take input from any source - function parameter, standard input, or any other device. The input might be in form of a stream, string, or a byte array.
The input may contain characters from all over the ASCII range, but can't contain brainfuck memory pointer instructions (`<` & `>`).
All the digits you see in the input are expected to be placed here just for your program.
## Output
As Joe didn't write his preprocessor yet, he had to make the code interpretable by hand. That's the result he got:
```
+++++>+++++<[>>>+<<<-]+>[>>-<+<-]>[<+>-]>[<<<->>>[-]]
```
There are pretty much no restrictions on output - if the input has braces unbalanced, just copy them over in unbalanced amount to the output.
## Bonus tasks
If you think the challenge is too boring in current form, you might want to complete these tasks aswell for slight byte count reduction, and more fun obviously:
* Optimize out nonsense related to memory operations, like digits at the end of input or clustered digits (just take the last one) **- 20% of byte amount when completed**
* Minify Brainfuck output (remove clustered `+-`, `><`, non-brainfuck, comments and other kind of stuff) **- 20% of byte amount when completed**
## Rules
* Standard loopholes are forbidden by default
* Default I/O rules apply
* Programs are scored by their size in bytes.
* Solving additional tasks reduces the score.
* If anything is unclear, please let me know down in the comments
* Scoring of bonus tasks may increase (but not decrease!) in the future.
## Opening bid - C, 144 bytes
```
p,c,x;void g(v){x=v?'<':'>';if(v<0)v*=-1;while(v--)putchar(x);}main(){while((c=getchar())!=-1)if(isdigit(c)){c-=48;g(c-p);p=c;}else putchar(c);}
```
This program should make pretty much everything clear on the input and output side of this challenge, it doesn't implement any bonus tasks though.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jellywiki/Code-page)
```
V©_¥®N,$Ø<xµ¹e?ØD)
```
A full program. Assumes (like everyone else has) that no actual Brainfuck evaluation has to be made (no balancing of unbalanced brackets)
**[Try it online!](https://tio.run/##y0rNyan8/z/s0Mr4Q0sPrfPTUTk8w6bi0NZDO1PtD89w0fz//7@SgTYIGIJJg2hjbQPdWG3DaGNdI21D3VijaENtI91Y42gDXeNo3dhYJQA "Jelly – Try It Online")**
### How?
```
V©_¥®N,$Ø<xµ¹e?ØD) - Main Link: list of characters, s
) - for each character, c, in s:
ØD - digits = "0123456789"
? - if...
e - ...condition: (c) exists in? (digits)
µ - ...then: monadic link:
® - recall from register (initially 0)
¥ - last two links as a dyad i.e. f(c, ®):
V - evaluate (c)
© - (copy to the register)
_ - subtract (®) i.e. x = value(c) - register
$ - last two links as a monad i.e. f(x):
N - negate (x)
, - pair with (x) -> [-x,x]
Ø< - list of characters = "<>"
x - repeat (vectorises) - negatives act like 0
¹ - ...else: identity - i.e. f(c) -> c
- implicit (smashing) print
```
[Answer]
# JavaScript (ES6), 63 bytes
```
s=>s.replace(/\d/g,n=>'<>'[+(p<n)].repeat(p<n?n-p:p-n,p=n),p=0)
```
[Try it online!](https://tio.run/##HYlLCsMgFACPo2Je4mdXojmIdSHGhBZ5Sgy9vq2dxcAw7/AJLV6vegOWPfXD9GZsm69Uc4iJLs99OSc0lqyWOE7risyPm8I9YkOojwo4VYPsJ8F6LNhKTnMuJz0oEXwg/xZOcwGeS6dBcQleOckVeO0EaAfeE8b6Fw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 48 bytes
```
{$!=0;S:g{\d}=['<','>'][$/>$!]x abs +$!-($!=$/)}
```
[Try it online!](https://tio.run/##Hcq7CsJAEEDRX5mFwVXGIfsAC83mJyzHKSIamwRCFiEh5NvXxy1Odcfn1J/KsMCug1RWNMldrufXentsSWxtj7axKlg1aHSG9p6B0PD@@2F12EpuF@gg9@9pLI5@@b9OIjlW8hI5kGcN4imwRnEchVU/ "Perl 6 – Try It Online")
Substitutes all digits with the appropriate character repeated the difference between the previous amount of times
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, ~~20~~ 16 bytes
```
r\d@Tî< +'>pT=Xn
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=clxkQFTuPCArJz5wVD1Ybg&input=IjArKysrKzErKysrKzBbMyswLV0rMVszLTIrMS1dMlsxKzItXTNbMC0zWy1dXSI)
Saved 4 bytes porting a comment by tsh on Arnauld's solution which I've been told results in valid BF output.
```
r\d@Tî< +'>pT=Xn :Implicit input of string
r :Replace
\d :Digits (RegEx /\d/g)
@ :Pass each match X through a function
Tî< : T (initially 0) time repeat "<"
+ : Append
'>p : Repeat ">"
T=Xn : Convert X to an integer and assign it to T for the next match
```
[Answer]
# Python 3.6, ~~93~~ ~~90~~ ~~83~~ ~~79~~ 77 bytes
```
p=0
for s in input():
try:a=int(s)-p;s='>'*a+'<'*-a;p+=a
except:0
print(s)
```
[Try it online](https://tio.run/##JYrLCsMgEADvfoU3kywLq95M7Y8sHqSkNBezqIXm6@1rGOY0cvbHUfwYEkndj6qb3stHefZpDkr3eoYc99KnNqOsLZqrWTKYi1kwrwIxK729bpv0QEpL/Z9jEHyxvxJ7IExg2aMDi8mxBYfJM6FnTOkN)
Thanks to @JonathanAllan for -2 bytes.
---
Old version 90 bytes:
```
p=0
for s in input():
if '/'<s<':':a=int(s);print('>'*(a-p)+'<'*(p-a));p=a
else:print(s)
```
Thanks to @EmbodimentofIgnorance for -3 bytes.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~19~~ 18 bytes
```
εDdi®α„><®y©@è×]J¦
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3FaXlMxD685tfNQwz87m0LrKQysdDq84PD3W69Cy//8NtEHAEEwaRBtrG@jGahtGG@saaRvqxhpFG2ob6cYaRxvoGkfrxsb@19XNy9fNSayqBAA "05AB1E – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~103~~ 99 bytes
```
x=>{int i=48;foreach(var g in x)Write(g<58&g>47?new string(g-i<0?'>':'<',Math.Abs(i-(i=g))):g+"");}
```
[Try it online!](https://tio.run/##Jcu7CoMwFIDhvU8RHGpCekq8lIpGxQfo3CFksEHjWSKY0Aqlz25v//Bvn/FgPG6dCTg76cOCzjZjva1180QXCNZ5UY3zMvRmovd@IZagIyu7LhgGauWp2NsmP7dueJC/phZQijZu4jKW8eHSh@nY3TxFoFhbxlhpeRSx6rVVu5FGgn9Lfhcq4wI0T1QGKU9ApyrhKehMCcgUaP1h2xs "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 27 bytes
```
\d(\D*)
$*>$1$&$*<
+`<>|<$
```
[Try it online!](https://tio.run/##HcQxCoAwDADAve8Iog2BpFlLJ3@RBhR0cHEQR/8e0Rvu2u/jXCP6NvY5TwlyA4EBck241PZUSBGMH/lnU2RyFFMqKOTFBAu5GpMaub8 "Retina 0.8.2 – Try It Online") Explanation:
```
\d(\D*)
```
Match a digit and then all intervening non-digits.
```
$*>$1$&$*<
```
Slide the memory pointer to the desired cell, then after the intervening code, slide it back to the initial cell.
```
+`<>|<$
```
Cancel out any overlapping slides and delete any trailing slides.
[Answer]
# Pyth, 34 bytes
```
VzI}N."09IÒ"p*\<Zp*\>KsN=ZK.?pN)
```
With unprintable string `\x96\x02` between `."09I` and `Ò`
Explained:
```
Vz # For N in input
I}N."09IÒ" # If N is in the packed string 1234567890
p*\<Z # Print Z * "<"
p*\>KsN # K = int(N) and print ">" * K
=ZK # Z = K
.?pN) # Else print N
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/185056/edit).
Closed 4 years ago.
[Improve this question](/posts/185056/edit)
So glad I found this cool site. Wanted to try sharing a coding challenge a friend gave me, an interview question. Usually it is written in java, but you can use whatever language you want, just have fun!
**Challenge:** write efficiently and securely a program that creates an array of n threads that communicate with each other, where each thread, for simplicity, represents a number between 1,...,100. Oh, and it has to be randomly initialized.
Here comes the fun part: each thread looks at its neighbours(i-1,i+1) and:
* If its number is smaller than the number of both of his neighbours(i-1,i+1), it increments itself.
* If its number is larger than the numbers of both of his neighbours, it decrements itself.
* If its number is equal or between the numbers of its neighbours, it keeps the number the same.
So far not fun, right? So let's also make it a circular array! (the first element in the array and the last element in the array are neighbours) the tricky parts are: each thread should not change its number before its neighbors finished checking it.
The program performs m rounds of checks.
**Input:** For program logic, you can take the input from the user, or define it, doesn't matter.
**Output:** first line should print the starting state of the array. Second line should print all of the numbers in the array after each thread did one check. Third line should print the numbers in all of the array after each thread did a second test(second round) and so on.
Might be quite tricky in the beginning, but have fun with it!
The winner will be the one who can write the shortest code, and in case of a tie, cool algorithmic tricks or functional utilization of the java language will be awarded extra points!
---
First post here, will try to post more cool stuff for you to enjoy!
Really like this site.
I posted it a while ago, but forgot my credentials while being abroad so I couldn't log in to the site and fix the previous post. Hoping that this one is according to the standards of the site and more than that, I really hope you'll enjoy this cool coding gamexercise.
Good luck to all and most importantly - enjoy!
As kevin well-said: 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.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
FтLΩˆ}>µ¯©=´vy®N<N>‚èy.SDPiн+ë\}ˆ}¼
```
Takes `n` as first input, and `m` as second. Doesn't use any threads, since 05AB1E has none.
[Try it online.](https://tio.run/##AUEAvv9vc2FiaWX//0bRgkzOqcuGfT7CtcKvwqk9wrR2ecKuTjxOPuKAmsOoeS5TRFBp0L0rw6tcfcuGfcK8//8xMAoxNQ)
**Explanation:**
```
F } # Loop the (implicit) input `n` amount of times:
тL # Push a list in the range [1,100]
Ω # Pop and push a random value from this list
ˆ # Pop and add it to the global array
> # Increase the second (implicit) input `m` by 1
µ # Loop until the counter_variable is equal to that:
¯ # Push the global array
© # Store it in the register (without popping)
= # Print it with trailing newline (without popping)
´ # And clear the global array
v # Loop over each item of the array that is still on the stack:
N< # Get the index-1
N> # And the index+1
‚ # Pair them together
® è # Index both into the previous array we stored in the register
# (NOTE: 05AB1E has automatic wrap-around when indexing)
y.S # Compare both of them to the current integer `y`
# (-1 if `y` is larger; 1 if `y` is smaller; 0 if equal)
D # Duplicate this pair
Pi # If the product is 1 (only true for [1,1] and [-1,-1]):
н # Only leave the first element of the duplicated pair
y + # And add it to the current integer `y`
ë # Else:
\ # Discard the duplicated pair, so `y` is at the top of the stack
}ˆ # After the if-else: add it to the global array
}¼ # After the inner loop: increase the counter_variable by 1
```
[Answer]
# Java 8, 229 bytes (lambda without threads)
```
n->m->{int a[]=new int[n],b[],i=n,t;for(;i-->0;)a[i]=(int)(Math.random()*100)+1;for(;m-->=0;a=b)for(System.out.println(java.util.Arrays.toString(a)),b=a.clone(),i=n;i-->0;)b[i]+=(t=a[(n+~i)%n]-a[i])*(a[-~i%n]-a[i])>0?t<0?-1:1:0;}
```
[Try it online.](https://tio.run/##bVA9b8IwFNz5FV4q2RBbTiUWgoOqSpU6MDFGGV5CQk2T5yh5oUII/nrqlI8ubO90d7p7t4cDyP32e8gr6Dq2BounCWMdAdmc7T2rerKVKnvMyTpUH7dj@YlU7Io2eCZ6d9j1ddHeRXHMSmYGlHEt45NFYpCkBosf5u8E0yBL0sAaDCgqXcsjK2WsIwGJTQ33EsHXQF@qBdy6motpqLWYhVdt7bVGR2AyMeLNsaOiVq4n1bTeWiH/L/jWtnDsFLkNeW7HQYggM6DyymHBxVjhnp357JnhZCDhOLtY8YKpHAuJKYdEXuwDx3pFS72S4SJc6Og8RBM/YNNnlR/wtuPB2S2r/bb8GpykDMS4M2OlgqapjjzUQkGeFw3xcC6iP@7JLzfm7po/TK9X03lyHn4B)
# Java 8, 299 bytes (full program without threads)
```
interface Main{static void main(String[]A){int n=new Short(A[0]),m=new Short(A[1]),a[]=new int[n],b[],i=n,t;for(;i-->0;)a[i]=(int)(Math.random()*100)+1;for(;m-->=0;a=b)for(System.out.println(java.util.Arrays.toString(a)),b=a.clone(),i=n;i-->0;)b[i]+=(t=a[(n+~i)%n]-a[i])*(a[-~i%n]-a[i])>0?t<0?-1:1:0;}}
```
[Try it online.](https://tio.run/##VY/LbsIwFER/JZtKNokte9ENqUH5AFZZWl7cPCgOyTVyLlQIwa@npqiVupzRkebMABcQ4dTj0B2XxSP1cQ9tn@1uMwH5NrsE32UTeGQ1RY@f1lX8lrgMDfZfWX0IkVhllePF9K/RqQHrfrrEW3RFY13hDRZU7kNkpRdio0oO1jvDEsLZDuggI2AXJsZXWime6xc7JdaoEkzDn7m@ztRPMpxJnpIVjciG9ESeyY@yihGus6TwMmbAedEYkO0YsGf8qfC73aTt3DAyYBnmD8/f0ImnEF8xsOLh//JGbelDbYVe67Uq7/dlWbRa9Ps3)
**Explanation:**
```
n->m->{ // Method with two integer parameters and no return-type
int a[]=new int[n],// Create an array of size `n`
b[], // Temp array, uninitialized
i=n, // Index-integer, starting at `n`
t; // Temp integer, uninitialized
for(;i-->0;) // Loop `i` in the range (`n`, 0]:
a[i]=(int)(Math.random()*100)+1;
// Fill the `i`'th item in the array with a random integer in
// the range [1, 100]
for(;m-->=0; // Loop `m` times:
a=b) // After every iteration: replace array `a` with `b`
for(System.out.println(java.util.Arrays.toString(a)),
// Print array `a` with trailing newline
b=a.clone(), // Create a copy of array `a` in `b`
i=n;i-->0;) // Inner loop `i` in the range (`n`, 0]:
b[i]+= // Increase the `i`'th item in array `b` by:
(t=a[(n+~i)%n]-a[i])
// Calculate a[i-1] minus a[i] (temporarily stored in `t`)
*(a[-~i%n]-a[i])
// Multiply it by a[i+1] minus a[i]
>0? // If this is positive:
t<0? // If `t` is negative:
-1 // Decrease b[i] by 1
: // Else (`t` is positive):
1 // Increase b[i] by 1
: // Else (a[i-1]-a[i] and a[i+1]-a[i] are pos/neg or neg/pos,
// or one of the two is 0)
0;} // Leave b[i] the same by adding 0
```
# Java 10, ~~569~~ 537 bytes (full program with threads)
```
import java.util.concurrent.*;class M{C[]c;CyclicBarrier b;int n,m,i;public static void main(String[]a){new M().t(a);}void t(String[]a){m=new Short(a[1]);c=new C[n=new Short(a[0])];for(;i<n;)c[i]=new C(i++);b=new CyclicBarrier(n,()->{System.out.println(java.util.Arrays.toString(c));});for(var x:c)new Thread(x).start();}class C implements Runnable{int v=100,i,q,L,R,t;C(int I){i=I;v*=Math.random();v++;}public void run(){try{for(;q++<=m;R=c[-~i%n].v,t=v<L&v<R?1:v>L&v>R?-1:0,b.await(),v+=t)L=c[(n+~i)%n].v;}catch(Exception ex){}}public String toString(){return""+v;}}}
```
As mentioned earlier in a comment, without threads is much shorter..
[Try it online](https://tio.run/##VZBBb@MgEIX/Coq0FRSC7MNeQkiljfZQKb04e7N8wMS7IbWxi8c0kZX@de/E6aHlAjO8N/rmnUw0y9PhdZpc07UByAkbcgBXS9t6O4RQeZCPytam78mLcX7c5oVV24utnf1lQnBVIKVyHogXjXCqG0r8IT0YwCu27kAatNE9BOf/5YVho6/e51GUSaCGqeusgq@SRt9E@yMiUZOnBVN27mxz/@0nKVih/raBKrf2itncFXcddZwzVd6Lr7DUC8qWmzGaQDq9WMzuW3FeWdZxfZaRL8hC7S89VI1sB5AdYkHtaYeo7Jv@Nv3PMVTmQM9M4s4IhaJ7WluCmdZVgwn2JBu8N2Vdjbekok6TRDjxJnYiE6CQFrvPbHT6WcVH/WLgKIPxh7bBcZFzdf2MdU4qDBjdCOEyzpu/cb7Wjcq0zZcf7ocvZBSg43r3ENfZU7qKG3xtsqdlukpEKc27cUgpItfAdmiinn84NvsQ3YA90t9nW3XgWk@qMxuveKaJTGkypT//Aw) (with `class M` is replaced with `class Main`, since it won't work on TIO if the class isn't called exactly `Main`..)
**Explanation:**
```
import java.util.concurrent.*; // Required import for CyclicBarrier
class M{ // Class:
C[]c; // Array of our Runnable cells on class-level
CyclicBarrier b; // A CyclicBarrier
int n, // Size of the array
m, // Amount of cycles
i; // Index, implicitly starting at 0
public static void main(String[]a){
// Mandatory main method:
new M() // Create an instance of this class
.t(a);} // And call the non-static method below:
void t(String[]a){ // Non-static method for the actual program:
m=new Short(a[1]); // Fill the amount of cycles `m` with the second argument
c=new C[n=new Short(a[0]) // Fill the size `n` with the first argument
]; // Create the array of that size
for(;i<n;) // Loop over all cells in the array:
c[i]=new C(i++); // And create a new instance for each cell
b=new CyclicBarrier(n, // Create the CyclicBarrier of size `n`
()->{ // Which will do the following before every cycle:
var p=""; // Create a String to print, starting empty
for(var x:c) // Loop over the cells
p+=x.v+" "; // Append the cell's value and a space to the String
System.out.println(p);});
// Print the String with trailing newline
for(var x:c) // Loop over the cells again:
new Thread(x) // Create a new thread for this Runnable cell
.start();} // And start the thread
class C // Inner class for the cells
implements Runnable{ // which implements the Runnable interface
int v=100, // The value of this cell, starting at 100
i, // The index of this cell
q, // A counter for the cycles
L,R, // Values of the left and right neighbors
t; // Incremental integer
C(int I){ // In the constructor of the cell:
i=I; // Set the index `i` on the given index
v*=Math.random();v++;} // And set `v` to a random integer in the range [1,100]
public void run(){ // Override the Runnable run method:
try{ // Mandatory try-catch for InterruptedException
for(;q++<=m; // Loop `m+1` times using the cycle-counter `q`
; // After every iteration:
R=c[-~i%n].v, // Get the value in the right-neighboring cell
t=v<L&v<R? // If this cell's value is smaller than both neighbors:
1 // Set the incremental to 1
:v>L&v>R? // Else-if this cell's value is larger than both neighbors:
-1 // Set the incremental to -1
: // Else (value is smaller than or equal to one neighboring cell
// and larger than or equal to the other neighboring cell):
0, // Set the incremental to 0
b.await(), // Wait until all cells in this BarrierCycle are done
v+=t) // And only then increase/decrease the value with the incremental
L=c[(n+~i)%n].v; // Get the value in the left-neighboring cell
}catch(Exception ex){}}}}// Mandatory try-catch for InterruptedException
```
[Answer]
# Javascript, 209 bytes
```
for(a=[],l=n=prompt();n;)a[--n]=(M=Math).floor(M.random()*100+1);for(console.log(a),m=prompt();--m;)b=a.slice(),b.forEach((e,i)=>b[i]+=e<M.min(x=b[(i-1+l)%l],y=b[(i+1)%l])?1:e>M.min(x,y)?-1:0),console.log(a=b)
```
This program, upon running, will prompt the user twice. First for `n`(number of threads, but instead made with arrays), second for `m`(number of checks).
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 198 bytes
```
n=>m=>{int[]z=new int[n],g;int i=n,a;for(var k=new Random();i>0;z[--i]=k.Next(1,101));for(;m-->0;z=g){g=z.ToArray();i=0;for(Print(z);i<n;g[i]+=(a=z[(n+~i)%n]-z[i])*(z[-~i%n]-z[i++])>0?a<0?-1:1:0);}}
```
[Try it online!](https://tio.run/##LY3BasMwEETv/QpfCtraCtI161XIJcdSSm9GB@HGZgleg@IkrULy665sehneDDNMe9btmefDRdqaZar27cSjLOhcR7OQG8jds218IjneigXFVz1mKJikCtiNUV1DLE5r4TPI9zgoQHYGU6M1ezpt3o8/k7KVNRZgHeCg9VKgHu49pc3XuI8x/C47MmvjI@YLlXJQC/YN@5JUoNQoKZ8Mr@J1yiG8qXzy5H9flh6c2YXa7LTd2q0BfDxmfOmUNQayAM5/ "C# (Visual C# Interactive Compiler) – Try It Online")
] |
[Question]
[
Make a function that increments a number using only bitwise, loops, and conditions.
**Rules:**
1. All entries must be as per the language spec defined below.
2. Scoring is not of code length, but of the points for each operation given below.
3. The entry point is `inc(a)`, for "increment and return a".
4. Lowest score wins.
See the example to help with scoring.
**Language Spec (strict JS subset):**
All input is assumed to be signed 32-bit integers, with input being in the range [-231+1, 231-2] ([interval notation](https://en.wikipedia.org/wiki/Interval_notation#Notations_for_intervals)), with the upper bound to give room for the increment. All output is assumed to be within the range [-231+2, 231-1].
Whitespace is never syntactically significant beyond separating literals, keywords, and newline-ended comments. Booleans for conditions can and may be implicitly converted to integers, with `1 == true` and `0 == false`. All variables are passed by value (as they are all primitives).
Cost is given for each element, with "per use" implied.
Comments: (0 pts)
```
/* like this */
// or this
```
Numeric or variable literal: (0 pts)
```
i, someVariable, 2, etc.
```
Boolean literal: (0 pts)
```
true // == 1, implicit conversion
false // == 0, implicit conversion
```
* Note: Integer to boolean conversion is as follows (in pseudocode):
```
if 0: true
else: false
```
Grouping: (0 pts)
```
(foo && bar);
```
Function declaration: (0 pts)
```
function foo() { ... } // braces required
function bar(a) { ... }
```
Declare variable: (0 pts)
```
var a;
```
Assignment: (1 pt)
```
var a = 1; // semicolon required to terminate statement
a = 2; // only needs declared once
var b = a;
// b = a = 3; // cannot assign in right side of statement
var c = a << 5;
var d = a ^ (c << 5);
```
Equality/Inequality: (1 pt)
```
x == 1; // equality
x != 1; // inequality
x > y; // greater than
x >= y; // greater than or equal to
x < y; // less than
x <= y; // less than or equal to
```
Logical operators: (1 pt)
* `!a` (not)
* `a && b` (and, returns 1 if both are true, 0 otherwise)
* `a || b` (or, returns 1 if either are true, 0 otherwise)
Bitwise operators: (1 pt)
* `~a` (not)
* `a & b` (and)
* `a | b` (or)
* `a ^ b` (exclusive or)
* `a << b` (arithmetic left shift)
* `a >> b` (arithmetic right shift)
* `a >>> b` (logical right shift)
Augmented assignment: (2 pts)
```
a &= b; // example
```
If statement: (condition value + 1 pt)
```
if (condition) { ... }
if (x == 2) { ... } // worth 2 pts
if (x) { ... } // x is nonzero, worth 1 pt
```
If-Else statement: (condition value + 2 pts)
```
if (condition) { ... } else { ... }
```
While statement: (condition value + 2 pts)
```
while (condition) { ... }
while (x == 2) { ... } // worth 3 pts
while (x) { ... } // evaluation same as in if, worth 2 pts
```
Do-While statement: (condition value + 2 pts)
```
do { ... } while (condition); // semicolon required
```
Return statement: (number of points for statement on right + 1 pt)
```
return foo; // semicolon required, worth 1 pt
return a & b; // worth 2 pts
```
Function call: (number of parameters + 2 pts)
```
foo(); // worth 2 pts
bar(1, 2) // worth 2 + 2 = 4 pts
```
Operator precedence (first to last performed):
1. `( ... )`
2. `~`/`!` (right-to-left)
3. `<<`/`>>`/`>>>` (left-to-right)
4. `>`/`<`/`>=`/`<=` (left-to-right)
5. `==`/`!=` (left-to-right)
* Note: `1 == 1 == 1` works out to `0 == 1` which is `0`.
6. `&` (left-to-right)
7. `^` (left-to-right)
8. `|` (left-to-right)
9. `&&` (left-to-right)
10. `||` (left-to-right)
**Example scoring:**
This (ficticious) example would score 14 points. See comments for details.
```
function inc(a) {
var b = a; // adds 1 pt for assignment
if (!a) return 0; // adds 3 pts: 2 for if and 1 for return
while (a & b) { // adds 3 pts: 2 for while and 1 for `&`
b >>= a ^ b; // adds 3 pts: 2 for augmented assignment, 1 for `^`
a = b << 1; // adds 2 pts: 1 for assignment, 1 for `<<`
}
return a ^ b; // adds 2 pts: 1 for return, 1 for `^`
}
```
[Answer]
# 10
Works for negative numbers.
```
function inc(x)
{
if(x & 1) // 1 + 1
return inc(x >>> 1) << 1; // 1 + 3 + 1 + 1
return x | 1; // 1 + 1
};
```
[Answer]
# 11 points (also works for negative numbers)
```
function inc(a) {
var t = 1; // 1 pt
while (a & t) { // 3 pts
a &= (~t); // 3 pts
t <<= 1; // 2 pts
}
return a|t; // 2 pts
}
```
I thought this was supposed to actually increment the number it was called on, but I am not familiar with a way to pass integers by reference in JS.
[Answer]
# 11 (Works for negatives)
```
function inc(a) {
for(var b=1;a&b;b<<=1) {
a=a^b;
}
return a^b
}
```
[Answer]
## 10 (works for negative numbers)
```
function inc(a)
{
var c = 1; // 1
while (c) // 2
{
var s = a ^ c; // 2
c = (a & c) << 1; // 3
a = s; // 1
}
return a; // 1
}
```
[Answer]
# 10 (13 if it must work for negative numbers)
```
function inc(a){
var m=1; // 1pts
while((a & m)==m){ // 4pts
m=(m<<1)|1; // 3pts
}
return a^m; // 2pts
}
```
] |
[Question]
[
# Physics Challenge
This program should be able to solve for ANY two of the following variables the user wants to solve.
1. s (displacement)
2. v (velocity)
3. u (initial velocity)
4. a (acceleration)
5. t (time)
At start the user must choose **two** variables they want to solve for and what variables they can supply. You are limited to using the following equations.
# Equations Permitted

(<http://en.wikipedia.org/wiki/Equations_of_motion>)
The entrant with the least amount of code and posts the quickest will win.
# Rules
1. This is code-golf. The shortest code wins.
2. Your program must terminate in reasonable time for all reasonable inputs.
3. You are allowed to transform the equations algebraically if need be
4. The program must be able to interpret a variable of which the user cannot supply (See Example 2)
# Input Example
The program will start and ask which variable the user will like to calculate:
(s, v, u, a, t) - the user selects this via a char type or string.
It then supplies all values for the other unknowns and the program will solve for the variables.
## Example 1:
```
*What would you like to calculate? (s, v, u, a, t)*
Input: a, u // This could also be s,v s,u, s,a v,u (ANY COMBINATION)
*Enter value for s:*
Input: 7 // The input will always be random
*Enter value for v:*
Input: 5
// Repeat for others
//program calculates
Var a = answer
Var u = answer
```
## Example 2:
```
*What would you like to calculate? (s, v, u, a, t)*
Input: a, t
*Enter value for u:*
Input: 5
*Enter value for s:*
Input: UNKNOWN
*Enter value for v:*
Input: 7
*The answers for a and t are 464 and 742*
```
# Edit
I think everyone here is overcomplicating the question. It simply asks to solve any 2 variables from the list of (s, v, u, a, t) and solve them using the equations. As the programmer you must be able to allow values to be taken for the variables that are not being solved. I will clarify that the program must be able to solve **for any** variable supplied by the user on startup. I also removed the somewhat **correct** equation s=v/t because people are becoming confused by it.
[Answer]
## Maple, 41 chars
```
s:=i->solve({v=u+a*t,s=(u+v)*t/2,op(i)}):
```
(Formulas used: **#1** and **#3**. These are sufficient to let Maple derive the rest.)
This defines a function `s` that takes in a set of initial conditions and solves the equations of motion for those initial values. For example, the command:
```
> s({ u = 1, v = 2, t = 3 });
```
outputs:
```
{a = 1/3, s = 9/2, t = 3, u = 1, v = 2}
```
---
### Notes:
You generally need to specify three initial values for a unique solution; if you don't provide enough, Maple will try to give you a **partial solution**:
```
> s({ u = 1, v = 2 });
3 t
{a = 1/t, s = ---, t = t, u = 1, v = 2}
2
```
(Yes, that's an ASCII art fraction there. Even in text mode, Maple tries to typeset your math nicely.)
**No solution** is return for overspecified or otherwise unsolvable inputs; for example, `s({ u = 1, v = 2, t = 0 });` outputs nothing.
If **multiple solutions** exist, Maple will generally try to return all of them:
```
> s({ u = 1, s = 0, a = -1 });
{a = -1, s = 0, t = 2, u = 1, v = -1},
{a = -1, s = 0, t = 0, u = 1, v = 1}
```
Sometimes, the output may contain `RootOf()` expressions, as in:
```
> s({ u = 10, s = 1, a = -1 });
2
{a = -1, s = 1, t = RootOf(2 - 20 _Z + _Z , label = _L3), u = 10,
2
v = 10 - RootOf(2 - 20 _Z + _Z , label = _L3)}
```
As far as Maple's concerned, this is a perfectly good solution, but if you want to turn it into something readable for us mere humans, use `allvalues()`:
```
> allvalues(s({ u = 10, s = 1, a = -1 }));
1/2 1/2
{a = -1, s = 1, t = 10 - 7 2 , u = 10, v = 7 2 },
1/2 1/2
{a = -1, s = 1, t = 10 + 7 2 , u = 10, v = -7 2 }
```
Alternatively, you can specify the initial conditions as floating-point values, e.g. `u = 10.0`, which will cause Maple to return purely numerical solutions instead:
```
> s({ u = 10.0, s = 1, a = -1 });
{a = -1., s = 1., t = 0.1005050634, u = 10., v = 9.899494937},
{a = -1., s = 1., t = 19.89949494, u = 10., v = -9.899494937}
```
Finally, note that, since Maple is a computer algebra system, it allows you to specify **arbitrary equations** in the input. For example, if we didn't care about the specific initial velocity, but only about the change in velocity, we could just specify e.g. `v = u + 1` and get the partial solution:
```
> s({ v = u + 1 });
{a = 1/t, s = t v - 1/2 t, t = t, u = v - 1, v = v}
```
We can even **extend the physics model** if we want, as in:
```
> s({ f = m * a, u = 0, f = 1, m = 10, t = 5 });
{a = 1/10, f = 1, m = 10, s = 5/4, t = 5, u = 0, v = 1/2}
```
[Answer]
## Golf-Basic 84, 58 characters
Executed from a TI-84 calculator
```
i`Cp`S,V,U,A,T@C=1d`U+AT@C=2d`UT+.5AT²@C=1d`"V="@C=2d`"S="
```
**Sample Run**
```
?1
?S=UNKNOWN
?V=UNKNOWN
?U=5
?A=4
?T=2
V=
13
```
[Answer]
## [GTB](http://timtechsoftware.com/?page_id=1309 "GTB"), 43
```
`C,S,V,U,A,T@C=1$~"V="~U+AT#~"S="~UT+.5AT²&
```
**Sample Runs**
Solve for V
```
?1
?UNKNOWN
?UNKNOWN
?5
?4
?2
V=
13
```
Solve for S
```
?2
?UNKNOWN
?UNKNOWN
?5
?4
?2
S=
18
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 5 years ago.
[Improve this question](/posts/2469/edit)
Write the "fastest" program to print an incrementing series of squares from a given input to a given input.
Example input:
```
-2
7
```
Example output:
```
4, 1, 0, 1, 4, 9, 16, 25, 36, 49
```
When using a "cryptic" language, please post the pseudocode, in addition to your program.
The entries will be judged on the most efficient algorithm.
[Answer]
The tag says "code-challenge", but I don't see any challenge. Just some mathematics we studied when I was about 12.
```
import java.util.*;
public class IncSquares
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int min = in.nextInt();
int max = in.nextInt();
int sq = min * min;
System.out.print(sq);
while (min < max) {
sq += (min << 1) + 1;
min++;
System.out.print(", " + sq);
}
System.out.println();
}
}
```
[Answer]
**Python**
```
print ", ".join(`x*x` for x in range(int(raw_input()), int(raw_input())+1))
```
[Answer]
## C
Since my usual language interpreter has a one-second startup time already, I chose not to use it here.
```
#include <stdio.h>
int main(void) {
int start, end, i;
scanf("%d\n%d", &start, &end);
for (i = start; i <= end; i++) {
printf("%d", i*i);
if (i != end)
printf(", ");
}
return 0;
}
```
[Answer]
## Ruby
```
a,b=*$<.map(&:to_i)
p (a+1..b).reduce([a**2]){|m,x|m<<m[-1]+x+x-1;m}*?,
```
[Answer]
# Jelly 12 bytes
```
+³’µ²
_N‘RÇ€
```
---
**Explanation**
```
+³’µ²
³’ -Decrement the first argument
+ -Sum it
µ -Groups the functions prior to this
² -Square the result
_N‘RÇ€
_ -Subtract the two arguments
N -Negate the difference
‘ -Increment the difference
R -Generate Range from Difference
Ç€ -Map range with above function
```
[Try it online!](https://tio.run/##ASQA2/9qZWxsef//K8Kz4oCZwrXCsgpfTuKAmFLDh@KCrP///y0y/zc "Jelly – Try It Online")
[Answer]
```
(z + 1)^2 = z^2 + (2z + 1)
```
We already know `z^2`, and 2z is simply `z<<1`.
```
(z + 1)^2 = (z^2) + (z << 2 + 1)
```
---
Now just memorize this trick if you want to list squares in your head.
If you've got an arbitrary [two-digit] square (to do in your head), `z^2`, do this:
```
z^2 = (z-n)*(z+n) + n^2
```
Or:
```
23^2 = (23-3)*(23+3) + 3^2
23^2 = 20*26 + 9
23^2 = 520 + 9
23^2 = 529
```
Works even "faster" with larger numbers, relative to you doing `97*97` in your head. Have fun showing off.
] |
[Question]
[
Languages, such as C++, have introduced a new comparison operator: `<=>`.
This operator returns -1, 0, or 1† when comparing two items together:
* −1 means the left-hand side is smaller,
* 0 when both values are equal,
* +1 means the right-hand side is smaller.
Here is what I have been coming up with in x86-64:
```
556: 48 8b 15 d3 04 00 00 mov 0x4d3(%rip),%rdx # 0xa30 (left handside)
55d: 33 c0 xor %eax,%eax
55f: 48 3b 15 9a 04 00 00 cmp 0x49a(%rip),%rdx # 0xa00 (right handside)
566: 74 08 je 0x570
568: 0f 9f c0 setg %al
56b: d1 e0 shl %eax
56d: 48 ff c8 dec %rax
570: 48 89 45 90 mov %rax,-0x70(%rbp) # output
```
The `mov` and `cmp` instructions are not important here since these could as well all be registers. At some point, though, you would have had to load those registers. They are there to show all the details. So my code uses five instructions at the moment.
The final result is expected to be a 64 bits integer.
Two challenges:
* Reduce the number of instructions
* Avoid the need for a branch without increasing the number of instructions
The top winner is the one with the smallest number of instructions. Eliminating the branch adds a bonus point. So two answers with the same number of instructions, the one without a branch wins.
---
†: The C++ and possibly other implementations of `<=>` do not mandate specific values, but refer to the sign. The C++ implementation of `<=>` returns *any* negative value, a (mathematically speaking) sign-less value (i. e. `0` [zero]), or *any* positive value.
[Answer]
If you specifically want to return -1, 0 or 1 as a 64-bit integer, then I believe you can follow your `cmp` instruction with a sequence such as this:
```
0: 0f 9f c0 setg al
3: 0f 9c c1 setl cl
6: 28 c8 sub al, cl
8: 48 0f be c0 movsx rax, al
```
The final 64-bit value can be stored in any register, not just `rax` of course.
[Answer]
Comparing unsigned integers can be done in three instructions:
```
0: 0f 97 c1 seta cl
3: 48 19 c0 sbb rax, rax
6: 08 c8 or al, cl
```
[Answer]
Assuming I can use non-instruction data for free, this can be done in 3 extra instructions:
```
xor %rax,%rax
cmp %rsi,%rdi // assume this is free
cmovl s2,%rax
cmovg s1,%rax
// in another section
s1: .long 1, 0
s2: .long -1, -1
```
[Demo on Godbolt](https://godbolt.org/z/6d8Wbhbrb), which has another approach that uses constant data.
[Answer]
```
cmp esi, edi
seta al
sbb al, 0
movsx rax, al
```
Like Neil's but I found after writing
] |
[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/253918/edit).
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
>
> Original close reason(s) were not resolved
>
>
>
[Improve this question](/posts/253918/edit)
For the purpose of this challenge a rectangular piece of ASCII art is *Mondrian* if it [looks the same upside down](https://www.bbc.com/news/entertainment-arts-63423811).
#### What does "looks the same" mean?
A *feature* is any orthogonally connected region of at last 5 characters. A *Mondrian feature* is any feature that appears in the same picture upside down. (This includes the possibility of the feature being rotationally symmetric in which case the feature counts as its own upside-down appearance.)
A picture is *Mondrian* if each of its characters is part of at least one Mondrian feature.
#### Your task:
Write a function or program that given a rectangle of ASCII characters returns it upside down if it is Mondrian and unchanged otherwise. If the entire picture is rotationally symmetric (such that it is Mondrian but has no upside-down state) the program or function should die horribly. You are free to choose amongst crash, hang, run forever, error out or simply end without output.
You may assume that the input is a clean rectangle of size at least 2x2.
This is code-golf. Standard rules apply, except despite this more or less being a binary decision you *cannot* do the usual truthy / falsy shenanigans.
You can take input in any reasonable format, e.g. newline separated string, list of lines, array of characters, but must output in the same format.
#### More clarifications on "upside down":
* We mean (180-degree) rotation, not mirroring.
* Characters are atoms, for example `p` upside down is `p`, not `d`.
Also: Features are allowed to overlap. (They do in both Mondrian examples below.)
#### Examples:
Mondrian:
```
-+-----+--
| |
=#=====#==
-+-----+--
*|./*
-+=+-
=#-#=
.|*/.
```
Explanation (possible list of Mondrian features) for 2nd example:
```
-+=+-
=#-#=
*
-
=
.|*
./*
=
-
*
```
Not Mondrian:
```
-___---
//O////
~/|\.~~
./ \...
```
Mondrian impostor (not Mondrian):
```
----
||||
----
||||
~~~~
```
Die horribly:
```
-
/ \
|
\
|
\ /
-
```
[Answer]
# [J](http://jsoftware.com/), 114 bytes
```
-.@(-:g)#,=&#[:~.@;@,(g=.|.@|:^:2)([:(#~4<#&>)@(</.~[:+./ .*^:_~1>:|@-/~)$j./@#:I.@,)@:="2]|.!.(u:0)~[:>@,@{<@i:@$
```
[Try it online!](https://tio.run/##XVBtS8MwEP5@v@K2jrXpmstWRNhtGUFlIIiC@K3tisheEQS3fRBD/npNJmrnAzmSu@eFy64Zd3hUXXZ4HMfQpXiFmjHGDIfI/kjC68e7eSPJJJLXIsp0PyrYkZmYLFlrsmQsLzgXScFJ5C6mUX8mTDJV5AoekEJKF1y70YytkcqJ3o6UifiWTCYM625eWepQcuSh8IKZyczn1GzZ9BoB91eESU/mLH451an5EwqH5f6gCQvG5cvmzaywmlCdA4QXxk/vx8PmI4YTLSw0BDmQAb4CWgywoCMd4Gt7LNqy1KJK/VQPpKfLSHt1qgLnO2n@/Lr/F1TXtXcCpR6UBzhlS3IO/I@URHRuHzLBerRuzuMv4Ga7PLNH74wlWPAl7FCiCj0BzRc "J – Try It Online")
The basic approach is the only mildly interesting part, so I will explain that without breaking down the J mechanics, which are straightforward, could likely be golfed further, though it wouldn't be terribly interesting without a high-level strategy change as well.
1. Do the 180 rotation.
2. Check where it is equal to the input.
3. Also check every possible 2d sliding of the input. You can imagine it as two sheets of paper, keeping the edges aligned, sliding the top one in every direction where there is still any overlap.
4. For each of these, we then have a boolean matrix showing which elements are equal. But we only care about connected `1` islands of length 5 or more.
5. To find these, we turn the `1`s into coordinates and compute an adjacency matrix, taking their transitive closure, grouping by equal rows, and only keeping "sets" of equal rows of length 5 or more. This is part is done [here](https://tio.run/##lY7BCoJQFET37ytGjdTS6zMi8GYiBUEQLdqKSYiSRhilu/DXTRHax2GYmc0wZecp7MYrhT1dFyrpOTYMHRYkuJdN2J2P@y5iQ2uXvjYNzNDwHWojnpMDml04ad2AP6HttOakJCfU@ECh1ZnitCU8i/SOqqmRZ9e6eWUo6uzxZvy9J7L0ViGHSmtKFoiHf1K4GJA9rhh81Jjl2IXED2F2Xw "J – Try It Online").
6. We combine all these valid coordinates we've found for every slid position, take their uniq, and see if it has as many elements as the input. If so, we are Mondrian.
7. Finally, we check if the rotation is equal to the input directly, and filter away our input if it is.
[Answer]
# Python3, 730 bytes:
```
E=enumerate
v=lambda x:[[i[j]for i in x[::-1]]for j,_ in E(x[0])]
t=lambda x:{(x,y):k for x,a in E(x)for y,k in E(a)}
V=lambda b,x,y:0<=x<len(b)and 0<=y<len(b[0])
F=''.join
M='\n'.join
P=lambda x:M(W[max(i for i,_ in E(x[0])if all(y[:i].lstrip()==''for y in x)):].strip()for W in x)
def f(b):
B,C=t(b),t(c:=v(v(b)))
q,r=[(i,I,[i])for i in B for I in C if B[i]==C[I]],[]
while q:
(x,y),(X,Y),p=q.pop(0)
if len(p)>4:r+=[p]
for j,k in[(1,0),(0,1),(-1,0),(0,-1)]:
if V(b,J:=x+j,K:=y+k)and V(c,Q:=X+j,W:=Y+k)and(J,K)not in p and B[(J,K)]==C[(Q,W)]:q+=[((J,K),(Q,W),p+[(J,K)])]
if{B[j]for k in r for j in k}=={j for k in b for j in k}:
if P([*map(F,b)])==P([*map(F,c)]):f(b)
return M(map(F,v(v(b))))
return M(map(F,b))
```
[Try it online!](https://tio.run/##dVNNT@MwED2vf8UIDtitkzR8SCsL76EIJEDswoWC3KhKaLq4TRM3DWwqSv96d@yUwq5gDs7MvDfj57FjFtVjkR98N@V6fSrT/GmalnGVkmeZxdNkGEMtlNJqHI2KEjToHGolhBdGLjHmA5s6pbXqRCwi1XvVC635gokJWF7N4w2P2XDBJ00Ys1dy@1aTcKwQnWNZH2dpThMW50PAcNGEdgdyJvf2/HGhc3Il9/r5xr9@3/aK9tQ0rql2@@p/9OkRxFlGF0royM/mVakNZRI7Ok3ubIyJyN8gNttrsmSYjmCEkgSBLj@RFbq8og9CPtNn9BkjMOOlVFTzc650xLbj6joh59Y9AVTQRVTKE3UeRVxFBP486iyFGTYGNzFO7/g940bOfFMY2sHOtsyOwLAfh6JsS2WwDpr520EqGvIOFnZ4iKv3Fnghi2xbW35LE34hZN0e80shF@2JG@4tfeA3Qt5htifkfZOlF/yS5UVlFRuwtK5yOSeb3vAetp2hCuqy3GW4aW9I@Apww5fu5sm4iy4bsdadvEr5MoYtlHyERHPWa6pa09jQM55gPynf4weMhb0HJJZp9VTmcEUb6O0iEPoPwew6CUHCzs4O8dqeNVwJLMGaXYncldZw/ciwBcm@tJ/WEoIWYrLtIdnblVjeCqChHDiKNxgMsJAEwa8AjayCZd9frYgfQN/3/YZ62FAtb4n2wVuhNZwjxwEPdWEpEKcQHVxQLekD7utQS7MvsyoGSRGXQzrEB/ptc3ylWjqC7Tsc6axKS/qzyFMOQ39uMl1R@wsxvDFiSp1XdES3nZIQRwm74SfI/pfIgUM6nyCHXyJHDnmM89/z9V8)
] |
[Question]
[
**This question already has answers here**:
[Follow a linked list](/questions/216196/follow-a-linked-list)
(51 answers)
Closed 1 year ago.
>
> Yes, this is very similar to [this question](https://codegolf.stackexchange.com/q/216196/107299). However, that concerns infinite linked lists, and you do not need to handle out of bounds indexes in that question.
>
>
>
You are in a strange city, looking for the fabled [Nineteenth Bakery](https://chat.stackexchange.com/rooms/123853/the-nineteenth-bakery), where it is said they sell the most delicious deleted posts. The order of shops here is strange. Each street has a number of shops on it, but they are not numbered in order. Instead, each shop has a number `n`, indicating that the next shop is `n` shops form the beginning of the street.
For example, consider the street `s`, which is like this: `[1,4,3,-1,2]`.
To find shop number 3, you first start with the first shop on the street, shop #1. In this case, `s[0]` is `1`. That means that shop #2 is at index `1`. `s[1]` is `4`, meaning shop #3 is at index 4. If an index is `-1` or is greater than the bounds of the array, that means that there is no "next" shop. A shop may reference a shop already visited. For example, if you are at shop #10 and the next shop has been visited and is #5, that means shop #5 is *also* shop #11.
## The Task
You are given a positive number `n` and a street, which is a non-empty list of numbers. `n` may be 1 or 0-indexed. You are to follow the path of shops until you get to shop #`n`. Then output the index (0, or 1-indexed) of shop #`n` in the list. If there is no shop #`n`, output any consistent value that is not a positive integer (i.e negative integers, `null`, `undefined`, etc.).
## Examples (Array indexes 0-indexed, `n` 1-indexed)
```
2, [3,-1, 8, 2] -> 3
1, [13, 46] -> 0
4, [1,2,3,4] -> 3
5280, [8] -> -1
3, [2,0,2,-1] -> 2
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
# JavaScript (ES6), 38 bytes
Expects `(0-indexed-array)(1-indexed-n)`. Returns `NaN` if the shop is not found.
```
a=>g=(n,i=0,q=+a[i])=>--n?g(n,q):i+q-q
```
[Try it online!](https://tio.run/##dc/dCsIgFMDx@57CS2XH5lcxAteDDC9krbEYmi16fXNGGyzy8pwf/4M3@7JT@xjuT@r8pYtXHa2ue40dDJpB0IVtBkN0Tak792kayGkoAg2x9W7yY7cffY@vuOGgQALlIAzBkhCUXlkitdu4bFAFaHZicXLruASkjmZeE8wXx34ciHRXmezU/16VU@jTO8iKJZoc5VsogKUk5WaG60fE1mXxDa6O8vgG "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array
g = ( // g is a recursive function taking:
n, // n = remaining number of shops
i = 0, // i = current position, starting at 0
q = +a[i] // q = value stored at a[i] (next shop),
// forced to NaN if undefined
) => //
--n ? // decrement n; if it's not 0:
g(n, q) // recursive call with q as the new position
: // else:
i + q - q // return either i or NaN (if q is NaN)
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 7 bytes
```
{x y/0}
```
[Try it online!](https://ngn.bitbucket.io/k/#eJw1j7FugzAQhnc/xQ0dQLJj++ykDpYqdejaKRtCCgUTUBKTgiuBovTZ65Bmu+/7/zvpmuw6wczFjZBddn3J598ha2AFk933R5vsm7I72cnOdkiLG9nlCVoJGhQwCZhaXdydtAubu1GLEVYq0JvUigVVXMK4pJ/5Gl+3lpqYfxaPqwgiVphMLRaEcNKGcBkzzqu+dof+1KzGUFZHN1Vt6Q9uVfVn/v3jxtD1fuSoldmueWgd8513wTkfWvZVHt0wE/IxlefLyY2QvA9DOUPnazdFFOwx1RQ8yCekBCnkijJJwVDAAtgbKBIpl4rGpxYhiL4LilRR/V9ZoxFRmgWZJLGdIxWxw+Ti8A8ojGCT)
Takes the array (`y`) and `n` (`x`) 0-indexed. Returns `0N` (the integer null) if the shop is not found.
Successively indexes into the array `x` times, starting with the first index (hence the `0`). The value at that index is then used as the index for the next iteration. Out-of-bound indexes return `0N`, the integer null. Only the last value is returned, representing the index of the n-th shop.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Jelly does not like bounds!
```
1³JiⱮ¤ḣṪƊ⁴¡
```
A full program that accepts a non-empty list of integers, the shop's pointers (1-indexed), and a non-negative integer, the path-length (i.e. "0-indexed \$n\$"), and prints the resulting (1-indexed) index or `0` if the path-length is not possible.
**[Try it online!](https://tio.run/##y0rNyan8/9/w0GavzEcb1x1a8nDH4oc7Vx3retS45dDC////RxvpmOuYAaGpjrGOSex/cwA "Jelly – Try It Online")**
### How?
```
1³JiⱮ¤ḣṪƊ⁴¡ - Main Link: shops, path_length
1 - one -> the initial value of Current, used below
¡ - repeat...
⁴ - ...times: path_length
Ɗ - ...action: last three links as a monad - f(Current):
¤ - nilad followed by link(s) as a nilad:
³ - shops
J - range of length -> Valids=[1,2,...,number_of_shops]
Ɱ - for s in shops:
i - 1-indexed index of s in Valids or 0 if not there
-> s or 0 if s is out of bounds
ḣ - head to (1-indexed) index Current
Ṫ - tail (Note: an empty list yields 0) -> new value of Current
- implicit print of Current
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 61 bytes
```
\d+
$*
;
;1;
+`1;1(1)*(;(?<-1>1*,?)*(1*))
;$3$2
1*;(1*).*
$.1
```
[Try it online!](https://tio.run/##FcgxDsIwEATAft/hwr4ckdd2FFmLko@kAAkKGgrE/00oZz7P7@t9H@N4TAgGQRSmG8XIZFFxv1640Xw/RUsJCjUU0PTnbAgzx6CaZ@9ekcXmbUVV8erNFyxl7eooqs6z8g8 "Retina 0.8.2 – Try It Online") Link includes test cases. Takes `n` as 0-indexed but the shops are 1-indexed. Explanation:
```
\d+
$*
```
Convert to unary.
```
;
;1;
```
Start with the shop at index `1`.
```
+`1;1(1)*(;(?<-1>1*,?)*(1*))
;$3$2
```
Until either `n` is zero, the index is zero, or the index is out of range, replace the index with the value at that index and decrement `n`.
```
1*;(1*).*
$.1
```
Extract the final index and convert it to decimal.
[Answer]
# [J](http://jsoftware.com/), 14 bytes
```
1 :'{&u&0 ::_'
```
[Try it online!](https://tio.run/##RcsxC4MwEAXgvb/i0cEopJK7aNWAk@DUqX8ggzQUF6dO/vj0QQaH43Hfu9vzvTUJc4CBhUPgPFos79eaBcGc1a@ihmhyc/ts3wMeM2pvo1iMFtokSCkcC/Honkhw161AmR3RF4zEkWuvw1REKcp/RRQWmv8 "J – Try It Online")
*If "index error" is allowed for my out of bounds value, I can do -4 bytes*
* 0-index for both
* Returns `_` (infinity) for out of bounds.
] |
[Question]
[
What general tips do you have for golfing in [Keg](https://github.com/JonoCode9374/Keg)? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Keg (e.g. "remove comments" is not an answer).
Please post one tip per answer.
[Answer]
# Brackets autocomplete
This is my biggest tip for anyone golfing in Keg: when writing programs, brackets used in loops or if-statements are automatically balanced if there are unclosed brackets.
For example:
```
(9|0.)
```
Can be shortened to:
```
(9|0.
```
And:
```
{:1=[1.]}
```
Can be shortened to:
```
{:1=[1.
```
[Answer]
## Use Unicode characters when possible
In Keg, you can represent large constants using simply Unicode characters. [Sometimes](https://codegolf.stackexchange.com/questions/192715/output-a-super-mario-image/192736#192736) this is really hard to do, sometimes it is [easy](https://codegolf.stackexchange.com/a/189501/85052) and can lead to creative solutions. And there is almost nothing to say about this; this is a canonical feature for golfed Keg programs.
[Answer]
## Using the `;` operator
The `;` operator in Keg can be very powerful. For example for building NOT gates for if statements;
```
11$-[Blah|Blah2]
```
Can be golfed into:
```
1;[Blah|Blah2]
```
[Answer]
# There's A Dictionary!
[Like](https://github.com/Adriandmen/05AB1E/blob/master/lib/reading/dictionary/words.ex) [other](https://github.com/maxbergmark/mathgolf/blob/master/resources/dictionary.py) [golfing](https://github.com/DennisMitchell/jellylanguage/blob/master/jelly/dictionary.py) [languages](https://github.com/barbuz/Husk/blob/master/dictionary.tsv "dictionary.tsv"), Keg has a built-in ~60.5k word (~6.05 times better than 05AB1E's) dictionary that is available to be used. There are 6 ways to access the goodness that is `words.txt`:
* Standard Spaceless Strings (Done with backticks)
* Standard Spaceful Strings (Done with `¶`)
* SCC-Only Spaceless Strings (Done with `‘`)
* SCC-Only Spaceful Strings (Done with `“`)
* Special Spaceless Strings (Done with `„`)
* Special Spaceful Strings (Done with `¬´`)
**Note that when the terms *spaceful* and *spaceless* are used, they refer to whether or not the string will place spaces between string compression codes when expanding.**
I feel like I should take the time to explain what **S**tring **C**ompression **C**odes are:
Every word within the Keg dictionary has a two byte code associated with it. These range from `00` through to `‚Ü´‚Ü´`. When the uncompressor sees a string, it will go through and expand each SCC with it's corresponding word from the dictionary (for example, `H%` is `Hello`, `c¬°` is `World` and `5∆≥` is `Good`). Even though all of the examples had uppercase letters, there are words starting with lower case letters.
## Obtaining SCCs
The best and easiest way to find out what the required SCCs for programs is to navigate to `uncompress.py` and run the program (preferably in some sort of terminal/something that *isn't* IDLE). "But that's a *library*, not a user-friendly program!", I hear you say. Well, when run by a user as a program, it will branch into `if __name__ == "__main__"` and run a helpful session for golfing. If a word is in the dictionary, the corresponding SCC will be printed (single character SCCs start with `0`), otherwise, `-1` will be printed. Here's an example session:
```
Enter a search term: Hello
H% [43, 66]
Enter a search term: world
⬥ [188]
Enter a search term: Keg
-1
Enter a search term: keg
‚Üêz [130, 35]
Enter a search term: Um
-1
Enter a search term: Keg
-1
Enter a search term: isn't
4üÑÇ [4, 239]
Enter a search term: in
-1
Enter a search term: the
0 [0]
Enter a search term: dictionary
V¬ø [57, 88]
```
Don't mind the fact that Keg isn't in the dictionary.
[Answer]
# Use Functions where possible
Functions are defined using `@` and store code that would potentially be repeated many times.
] |
[Question]
[
This is an answer chaining puzzle, where each answer must add on to the last.
The \$n\$th submission must output its own source code in the \$n\$th language and the \$n−1\$ languages before it.
A language can be either a dialect or a major version of a language, so Python version 2.121 is only counted as version 2 and Common Lisp and Clojure are considered different languages. This excludes compiler flags.
You can post 2 answers in a row, but have to use different languages.
The winner of this puzzle is the person to submit the second-to-last quine if there have been no new quines for a week. The aim of this puzzle is to go on as long as it can, so if you want the green tick, you'll have to respect that.
Have fun.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 187 bytes
```
var s=1
<0?"":"var s=1{0}<0?{1}{1}:{1}{3}{1};Write(s,(char)10,(char)34,(char)39,s)//.1+d*fao;!?l{1}var s=1{1}ar*3dr{2}";Write(s,(char)10,(char)34,(char)39,s)//.1+d*fao;!?l"var s=1"ar*3dr'
```
[Try it online!](https://tio.run/##S8sszvj/vyyxSKHY1pDLxsBeSclKCcqtNqgFClQb1gKRFYgyBrGsw4syS1I1inU0kjMSizQNDaAMYxMYw1KnWFNfX89QO0UrLTHfWtE@B6gNZqZhbWKRlnFKUbVRrRI5RsEcpwQxRv3/fwA "><> – Try It Online")
[Try C# Online](https://tio.run/##Sy7WTS7O/P@/LLFIodjWkMvGwF5JyUoJyq02qAUKVBvWApEViDIGsazDizJLUjWKdTSSMxKLNA0NoAxjExjDUqdYU19fz1A7RSstMd9a0T4HqA1mpmFtYpGWcUpRtVGtEjlGwRynBDFG/f9/AA "C# (Visual C# Interactive Compiler) – Try It Online")
Let's add a 2D language, why not?
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 63 bytes
```
var s="var s={0}{1}{0};Write(s,(char)34,s)";Write(s,(char)34,s)
```
Just to start it off.
[Try it online!](https://tio.run/##Sy7WTS7O/P@/LLFIodhWCUJVG9RWG9YCSevwosySVI1iHY3kjMQiTWMTnWJNJWyC//8DAA "C# (Visual C# Interactive Compiler) – Try It Online")
] |
[Question]
[
>
> This is the Robbers' thread. [Cops' thread is here](https://codegolf.stackexchange.com/q/173383/78410).
>
>
>
## Background
[Boggle](https://en.wikipedia.org/wiki/Boggle) is a board game where the players have to find English words on a 4-by-4 board of random alphabets. Words can be constructed by selecting sequentially adjacent cells on the board. ("adjacent" means horizontally, vertically or diagonally adjacent.) Also, same cell can't be used more than once in a word.
The following is an example board:
```
I L A W
B N G E
I U A O
A S R L
```
On this board, `BINGO`, `ORANGE` and `WEARS` are valid words, but `SURGE` and `RUSSIA` are not:
* `SURGE` : There's no adjacent pair on the board having `RG`.
* `RUSSIA` : `S` cannot be used twice.
**Modified Boggle** is a modified version of Boggle, with the following rules:
* The board size is `m`-by-`n`, where `m` and `n` can be any positive integer.
* Each cell can contain any one byte between 0 and 255 inclusive.
* **A cell can be used more than once, but not twice in a row.**
Using the example board above, in addition to `BINGO`, `ORANGE` and `WEARS`, `LANGUAGE` becomes a valid string (since `G` is used twice, but not twice in a row) but `RUSSIA` is still not (due to `SS` pair).
Here is another example using a code fragment. The string `from itertools import*\n` can be found on the following board, but not `from itertoosl import*` or `from itertools import *`:
```
f i ' ' s
r t m l
e o o p
\n * t r
```
Note that you need two `o`'s in order to match the `oo` sequence.
---
## Robber's challenge
Pick a cop's submission which isn't yet cracked or marked safe. In the given language, find a **full program** that fits in the code board which outputs some string that fits in the output board. **The program's length should be equal or less than given, and the output's should be equal or greater.**
## Scoring for robbers
Each successful crack counts as a score of 1. The user with the greatest score wins.
## Robber example & formatting
```
# Japt, code 8 bytes, output 21 bytes, [Bubbler](link-to-cops-post)
`líÏ`íÏl
[Try it online!](link-to-tio)
The output is `112624120720504040320`.
```
---
## Modified Boggle verification script
All of the scripts below have an example input with it.
[Script for character string(code/output) & boggle.](https://tio.run/##bZBNasMwEIX3c4pZFYv8kNBdSnIRY7ArjxNRRRKSTBxKztCT9BQ5mDuy3KaFgmVJ7/G@GY27xpM1z@PYeXtGabUmGZU1AdXZWR@xpa7pdWyVjADBS9yjMq6PhYBXezxqYqGsIPrrDvByUixsd5itdeMcmbaYAwJokOTiDl0TAmhlqPE53lmP3l4YPUcZlv01DTEx2BUvszRjNwKAOw6M0GSKHCw3lVhsQVv71jt2fvVfBIpiKqWWMpUi05/JN5GKDBap6hQsZbVuWu5cgLNB5Yns8V1hjtO/cVQd0m2qMPF5XEz8C1gMGZH8h5OkIUnlKr1otV3idJi3Rbrz4u/bzm42qxs@PRoH55WJRRrJTwGBB9yIcaz1/fP@UaefhlpDOvD@BQ "Python 3 – Try It Online") This does not support multi-line string. The input format is
* a single line of string (either code or output), followed by
* the raw boggle board.
[Script for character string with byte-value boggle.](https://tio.run/##bZHvTsIwFMW/36e4fnFtgGVgIorBF5kLzK1AtbRNV8KI4Rl8Ep@CB8PelX8mJtu69tdzznpmd35l9MPxuHBmjZVRSlReGt2gXFvjPNZiUW6Ur2XlARpXzZTUosEpSu2Z1HbjGecEwlJuXM1ajgvjsA0bMHnTSfphpD7v7NCMkCv1UrCLIecFvJvlUgnyKcC73QRwu5JhYTjBiNLSWqFrllP2bc7JPW2skmEsOIi2EtZP0JZNA5RQumhMGme2pIqmISbyVLSe3APlL6elU2CScIBQDp1bCc2iMs8K3huCMuZzYwO5qYo1wvMuS/YryhJ6sxau9IJFZ06xnTCvirSsayY5WNPIWP4UvyRGufhXjnKBAu@mmCT7LqdLCXUG3782vTYaEb@SS3X5gM41GPaxezkNPZqHO1xnHGmExR7vr58P1tEPoWIuARxfMePH4wjm6vBz@IY5PRVkiDjM4PkRcZSNYfQwDtOnXw "Python 3 – Try It Online") Use this if the target string is printable but has one or more newlines in it. The input format is
* the number of lines for the string,
* raw string (possibly multi-line), then
* the boggle board as byte values.
[Script for byte-value string & boggle.](https://tio.run/##hVHRasIwFH2/X3H3sjaopVVQ53A/UvrQtamGxSQkKVaG397dNE43GAxSbnJOzzm5N@bij1qtxrGz@oSNlpI3XmjlUJyMth5b3tW99K1oPICzDe6xFMqnA8NOWxxQKFqm9ynLnJGCagXv@nCQPPxagbeXHeD5KAgodhiprDaGqzb914oBHxpu/A5N7RxIoXhto3HQWH0OqmhKMZHP@OCDO7Hs9QbdApOEAVCbjjwkV2lUlnnFZgVIrT96Q8yPplPHPZuyxLwJWVz1J25rz9PozELsJCybKqvbNhUMjHYijnGPnwKjnP8pR9Ehx6c9Jsl1yplSaNLk@9tmNkSjwD@Y@@jKRehrUcxx2tzKLJzpo/VNRzaS1RWfH9cHY8ODhMHcAxi@Yc7G8WWNRb7F5WqDy3xDeyTkcdpCjkgVCA0QBIrgLw "Python 3 – Try It Online") Use this if the target string contains one or more unprintable characters. The input format is
* a single line of string (either code or output) as byte values, followed by
* the boggle board as byte values.
[Answer]
# JavaScript, code 1342 bytes, output 3 bytes, [Scrooble](https://codegolf.stackexchange.com/a/173397/78410)
```
[][[[]+![]][+![]][+![]]+[[]+[][[]]][+![]][!+[]+!+[]+!+[]+!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]][[[]+[][[[]+![]][+![]][+![]]+[[]+[][[]]][+![]][!+[]+!+[]+!+[]+!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]]][+![]][!+[]+!+[]+!+[]]+[!![]+[][[[]+![]][+![]][+![]]+[[]+[][[]]][+![]][!+[]+!+[]+!+[]+!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]]][+![]][+!+[]+[+![]]]+[[]+[][[]]][+![]][+!+[]]+[[]+![]][+![]][!+[]+!+[]+!+[]]+[[]+!![]][+![]][+![]]+[[]+!![]][+![]][+!+[]]+[[]+!![]][+![]][!+[]+!+[]]+[[]+[][[[]+![]][+![]][+![]]+[[]+[][[]]][+![]][!+[]+!+[]+!+[]+!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]]][+![]][!+[]+!+[]+!+[]]+[[]+!![]][+![]][+![]]+[!![]+[][[[]+![]][+![]][+![]]+[[]+[][[]]][+![]][!+[]+!+[]+!+[]+!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]]][+![]][+!+[]+[+![]]]+[[]+!![]][+![]][+!+[]]]([[]+[![]]][+![]][+!+[]]+[[]+![]][+![]][!+[]+!+[]]+[[]+!![]][+![]][!+[]+!+[]+!+[]]+[[]+!![]][+![]][+!+[]]+[[]+!![]][+![]][+![]]+[[][[]]+[][[[]+![]][+![]][+![]]+[[]+[][[]]][+![]][!+[]+!+[]+!+[]+!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]]][+![]][!+[]+!+[]+[!+[]+!+[]]]+[+[![]]]+[[+![]]+![]+[][[[]+![]][+![]][+![]]+[[]+[][[]]][+![]][!+[]+!+[]+!+[]+!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]]][+![]][!+[]+!+[]+[+![]]])()
```
[Try it online!](https://tio.run/##zVRLDsIgEN17is6qEGJv4EnGSdogMTVYTNv0@ghFDVqs3clmCPOGN5834dJMzSD79jbuO3NSVjpTHIr6aJEQkQQgEUZWeKfH6OUH4eOWJsRGBFuQkPVfydOs7gVABlUFnnBJZf1BFMPJHt69yeAPnux0SveWqXrLeRObq4Htoq5I9HUm62uA85mNsDHqpofP8YV6IKslfIjLbV2NfXtlfCdNNxitKm3OrCyFmhrN/B/Lub0D "JavaScript (Node.js) – Try It Online") and [Verify the code boggle online!](https://tio.run/##zVLLbsIwELz7KzaXKlYAgXqjoj9i@ZAmDlgNtuU4Iqji29N1HCCUlHJrpDxndmf2YXN0O61e27aweg@ZLkuROalVBXJvtHWQiyKtS5fLzBFS2Qw2IJWpXUyJsVK5uBQqRpxS8qG321JgAOPE2eOawGEnEVitIVCL1Bih8rgXoEQ0mTBuDSatKlJKJVIb0gttweoDWvWpKBb4hWic10CWvvVQL7ukhGAHFUr4okIiW3KarEip9WdtkBn0E1fC0c5KzjJvJVS9FzZ1Ig7C1Lt2iSzjizTHyrFrXckwoQ18SQjpYjQdZAHi1Dl0@jgmVLwVSJog4fkr46HGQ2zuO5qvZtB99K/E/@ON15kObCD5CV6uhQ/2dDGg8A5L2raMM8Z4EjHO2eCZeNBz/IJHiY@7f4TYgcAzTHD9L/NxVcyIoglUFXTCz5jrH0JDerSHW3Q0@IfO5PY03ttEt3c/bx531UTPL/XBin6dyeNjwLr3ZBY7ZHF67Dy@UE80qUPYL5cSHGxCfBBJeEy/AQ "Python 3 – Try It Online")
Outgolfing by 101 bytes :)
The point is that we can avoid most of the parens by using brackets instead (at the cost of a few bytes), and we just need two pairs of parens to do the function call.
For example, `([]+true)[1]` is equivalent to `[[]+true][0][1]`, and `!+[]+!+[]+[]+(!+[]+!+[])` (the code to generate "22") is equal to `!+[]+!+[]+[!+[]+!+[]]`.
Since `alert` is not available in Node, the TIO link shows the generated function instead.
### How it works
```
False = ![] // false
f = [[]+![]][+![]][+![]] // 'f'
a = [[]+![]][+![]][+!+[]] // 'a'
l = [[]+![]][+![]][!+[]+!+[]] // 'l'
s = [[]+![]][+![]][!+[]+!+[]+!+[]] // 's'
True = !![] // true
t = [[]+!![]][+![]][+![]] // 't'
r = [[]+!![]][+![]][+!+[]] // 'r'
u = [[]+!![]][+![]][!+[]+!+[]] // 'u'
e = [[]+!![]][+![]][!+[]+!+[]+!+[]] // 'e'
Undefined = [][[]] // undefined
n = [[]+[][[]]][+![]][+!+[]] // 'n'
i = [[]+[][[]]][+![]][!+[]+!+[]+!+[]+!+[]+!+[]] // 'i'
fill = [][f+i+l+l] // Array.prototype.fill
c = [[]+fill][+![]][!+[]+!+[]+!+[]] // 'c'
o = [!![]+fill][+![]][+!+[]+[+![]]] // 'o'
open = [[][[]]+fill][+![]][!+[]+!+[]+[!+[]+!+[]]] // '('
close = [[+![]]+![]+fill][+![]][!+[]+!+[]+[+![]]] // ')'
func = fill[c+o+n+s+t+r+u+c+t+o+r] // Function
code = func(a+l+e+r+t+open+[+[![]]]+close) // 'Function("alert("+NaN+")")'
```
Have some fun comparing this to the [original JSFxxk conversion table](https://github.com/aemkei/jsfuck/blob/master/jsfuck.js).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 27 bytes, output = 2 bytes, [Shieru Asakoto](https://codegolf.stackexchange.com/a/173406/58563)
```
s=4n;s%=s;7n;console.log(s)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f@/2NYkz7pY1bbY2jzPOjk/rzg/J1UvJz9do1jz/38A "JavaScript (Node.js) – Try It Online")
or [Verify the code boggle](https://tio.run/##bZFNboMwEIX3PsVsUuEGIshPoUH0IigL6jjEqmNbtqMQVTl7Osa0aaVKIGAe73szHnP1R61W9/vB6hMwLSVnXmjlQJyMth72/NCdpd8L5glxlkEDQpmzTygxViifSK4SrFNK3nXfS44/tDvi7XVL4HIUWCi2EKVFZwxX@2QCUMIHxo3fgumcI1Io3tloP2gLVl8warIiLOoLPvjAQJXWU2nC5pQQnMAhIjQVjW2@o/OCSK0/zgaVX/Mkjns6RomUhSiuziduO8@TCKYhdTS2bLfo9tg5Tq2diCfUwKeAaOf/2kEcgN/GhJGPx4TEv4D5EBFBfyihNIRSm4WJsiKF8WV6zMM33nh9y1GN4u4GT4/Gf@3pJ4DCG@T0fnfNWtVu1ri6VDVDQeOWpO4Th8tZiCyjzWxDJKvTpXsuShzFqWqdlzPSK1tWm2JVEZfUm2WZv5Skocgq1sUrWatUNEW1Wn4B)
[Answer]
# Javascript (REPL), code 1443 bytes, output 3 bytes, <https://codegolf.stackexchange.com/a/173395>
```
+[+[![]]+[]+[]+[]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]]
```
Outputs `NaN`. There are quite a lot of ways to pad once you know how `NaN` can represent in JSFuck.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 53 bytes, output = 41 bytes, [Shieru Asakoto](https://codegolf.stackexchange.com/a/173390/58563)
```
console.log(1n+1n+1n<<(1n<<1n+1n<<1n+1n<<1n<<1n<<1n))
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/OT@vOD8nVS8nP13DME8bjGxsNEAElA2nYFhT8/9/AA "JavaScript (Node.js) – Try It Online") or [Verify the code boggle](https://tio.run/##bVJBbsMgELzzij1VICdWrN4Spx@xfHDxOkElgAArjqq83V2M06RSJTDrHWZmF3C3eLbmfZ4Hby8grdYoo7ImgLo46yP0OHSjjr2SkbHgJRxBGTdGLpjzykSu0XDKC8E@7emkkTY0LYv@tmdwPStKVHvIUNk5h6bnq4BgOEl0cQ@uC4FpZbDzmT5YD95eyWqlkljGS5xi0iBUHNbUKrsTjFEHgSRSUZnY7FpRVExb@zU6Ql764QGjWKzURiYrNOMFfReRZ2GRXBdiI9uy66ly6toGlU/oCN8KMh3/pYMaAO@Lw6JPx0SKfwWKKUsk/Imk1JRSzTZ1tK02sATrUqR/mjQecEYz2N7h7Vn4yz39Ggj4gJ2YZ0mxpYvR9sQrUyyjrnn6rPHv8ph0bZJ2G8F0MBU9AyyLuj78AA) or [Verify the output boggle](https://tio.run/##bZHRboMgFIbveYpztUi6NqDWapfuRYwXTmlLZoEgpjZLn90dxK1dsgQjnp//@89Bc3NnrZJpOlp9gUZ3nWic1KoHeTHaOmjFsR4618rGEdLbBg4glRlcRImxUrmoEyrCOqXkQ59OncADZUWcve0JXM8SC3wPQdrUxgjVRguAEjE2wrg9mLrvSSeVqG2wH7UFq68YtVgRFvSNGJ1noErfltKCZZQQnKBHhG8qGEtW0RUnndafg0HlaZ6oF47OUfK18VFCDRdhayeiAKY@dTaWTbWpW@wcp9a9DDd0gC8JwS7@tYM8grjPCTMfrwmJfwGrMSC8/lB8afSlcu0nWvNXmDfLa@W/8cH1Iwc1iNUdXh6NP/2n3wAK78DoNHEWszzdccZ2WZzzbVIwXDxO8jiOi23C0ixJkyxXJPVqSuIdK1hGMhbzNCdbPFeobw)
This computes:
$$3\times2^{1\times4\times4\times2\times2\times2}=\\3\times2^{128}=\\1020847100762815390390123822295304634368$$
Which can also be done in **49 bytes**:
```
console.log(1n+1n+1n<<(1n<<1n+1n+1n+1n+1n+1n+1n))
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/OT@vOD8nVS8nP13DME8bjGxsNEAEjIuMNDX//wcA "JavaScript (Node.js) – Try It Online") or [Verify the code boggle](https://tio.run/##bVLBbsMgDL3zFT5NoLRRo93adD8S5ZARp0WjgICoqaZ@e2ZCunbSJCcBP957No67xbM17/M8eHsBabVGGZU1AdTFWR@hx6EbdeyVjIwFL@EIyrgxcsGcVyZyjYZTXgj2aU8njXSgaVn0tz2D61lRotpDhsrOOTQ9XwUEw0mii3twXQhMK4Odz/TBevD2SlYrlcQyXuIUkwah4rCmVtmdYIw6CCSRisrEZteKomLa2q/REfLSDw8YxWKlNjJZoRkv6LuIPAuL5LoQG9mWXU@VU9c2qHxDR/hWkOn4Lx3UAHhfHBZ9uiZS/CtQTFki4U8kpaaUarapo221gWWxfoq0p4fiAWc0g@0d3p6Fv8zp10DAB@zEPEtaWxqMtidemWKJuubp9di@Bo1M0kkjmA6mol8Ay6KuDz8)
] |
[Question]
[
## Statement
Given N distinct integers, output them in order such that
* for any integer J from 2 to N,
+ for any K>0 obtainable by dividing J by 2 (rounding down) at least one time,
- the Jth integer output is larger than the Kth if and only if the division by 2 that gave K (*i.e., the last division*) divided an odd integer.
Note: this is for one-based index, as in common language, because it makes the statement less hairy. The motivating code below uses zero-based indexes.
This is a code golf. Output is a list of integers.
## Example
Given the first 10 primes (in any order), the output must be in this order
`17 7 23 3 13 19 29 2 5 11`
which, when rewritten as a binary tree, gives:
```
17
/---------------\
7 23
/-------\ /------\
3 13 19 29
/-\ /
2 5 11
```
Note: when walking up in this tree towards its root, the parent is obtained by dividing the (one-based) index by two. The statement's *"odd"* and *"larger"* correspond to node at index J being compared to one of it's ancestor node at index K situated on the left and above.
## Motivation
This allows search in a static list by *monotomy*, simpler and typically faster than dichotomy.
```
// Search t in table *p of length n (with n<=MAX_INT/2 and n>=0)
// Returns the index (zero-based), or -1 for not found
// Assumes table *p is in monotomic order (see below)
int monotomy(const int *p, int n, int t) {
int j;
for( j = 0; j<n; j += (p[j]<t)+j+1 )
if( p[j]==t )
return j;
return -1;
}
// Return 1 iff table *p is in correct order for monotomy
// Table *p of length n is zero-based.
int monotomic(const int *p, int n) {
int j,k,m;
for( j = 2; j<n; ++j)
for ( m = k = j; (k /= 2)>0; m = k)
if ( (p[j-1]>p[k-1]) != (m%2) ) // zero-based indexes
return 0; // incorrect order
return 1; // correct order
}
// monotomy demo
#include <stdio.h>
int main(void) {
const int p[] = { 17, 7, 23, 3, 13, 19, 29, 2, 5, 11, };
#define n (sizeof(p)/sizeof(*p))
int t, i, j;
printf("monotomic = %d\n", monotomic(p, n) );
for( t = i = 0; t<9999; ++t )
if( ( j = monotomy(p, n, t) )>=0 )
printf( "%d\n", p[++i, j] );
if ( i!=n )
printf("Incorrect\n");
return 0;
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 9 bytes
```
JBÇṙ€1ỤỤịṢ
```
[Try it online!](https://tio.run/##y0rNyan8/9/L6eHOmY@a1hg@3L0EjLof7lz0////aFMdBXMdBWMdBSMdBUNDIAYyDYEiRiAhSyDbMhYA "Jelly – Try It Online") Explanation:
```
J Create a range 1-(length of input array).
B Convert all the elements to binary.
ṙ€1 Rotate each element left by 1.
ỤỤ Find each element's position within the sorted list.
ịṢ Apply that permutation to the sort of the input.
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 27 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
âX→δ╦Q),/BΦ♪ó╟&íY╧ù@T¶`&é²╞
```
[Run it](http://stax.tomtheisen.com/#c=%C3%A2X%E2%86%92%CE%B4%E2%95%A6Q%29%2C%2FB%CE%A6%E2%99%AA%C3%B3%E2%95%9F%26%C3%ADY%E2%95%A7%C3%B9%40T%C2%B6%60%26%C3%A9%C2%B2%E2%95%9E&i=%5B29%2C23%2C19%2C17%2C13%2C11%2C7%2C5%2C3%2C2%5D&a=1)
This is the ascii representation of the same program.
```
o]wrEc%c:Gvsc:Gh-|m[@Q]/{fr{~FLc
```
The general idea is to sort the list, then calculate the first output as a function of the array length. Then queue the prefix and suffix for the same algorithm. The 0-based index of the next output is always `min(N-high(N)/2, high(N)-1)`. `high()` clears all but the highest set bit.
```
o] Sort input, and embed array in array.
w While; loop over the rest of the program
rE Reverse, then explode array to stack.
This makes each element a separate
stack entry.
c% Length of this array chunk
c:Gvsc:Gh-|m Calculate array index of output using
given formula.
[ Copy current working array chunk.
@Q Read at the calculated index, and output
but leave on the stack.
]/ Split the working chunk into two.
{f Remove any resulting empty chunks.
r{~F Push the remaining new smaller chunks to
the input stack. This will
effectively put them at the end of
the queue.
L Combine all stack values into one list
c Copy queue for use as while condition
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~54~~ ~~53~~ ~~29~~ ~~15~~ 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
Credit to @Neil for simplifying the structure of the program so much that another 14 bytes have been saved (half of my original trimmed down post), and @recursive (creator of the Stax language) for streamlining the array manipulation to save 4 bytes.
```
óÆV¶┘Év▲♫☼»
```
[Run and debug it online](http://stax.tomtheisen.com/#c=%C3%B3%C3%86V%C2%B6%E2%94%98%C3%89v%E2%96%B2%E2%99%AB%E2%98%BC%C2%BB&i=%5B5+7+3+2+11+13+17+23+29+19%5D&a=1)
About Stax:
From the [first public golfing of Stax](https://codegolf.stackexchange.com/questions/155152/a-zealous-quick-brown-fox-jumped-along-the-groovy-spiral/155291/#155291):
>
> Stax is normally written in the printable ASCII character set.
>
>
>
This 11 byte submission is [packed](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) into a variant of the CP437 character set. The corresponding ascii representation takes 13 bytes:
```
oc%{:B|(m|o@m
```
>
> Stax is a stack based language, but it has two data stacks, "main" and "input". Most operations use the main stack, but input starts on the input stack. Stax instructions are mostly one or two character ascii sequences. Most of them are overloaded, meaning their behavior is determined by the top few values on the stack(s).
>
>
>
### Detailed explanation
This program does not use recursion. Instead, it uses a transform of the array [1..`n`](where `n` is the size of the input vector) to generate the necessary indexes such that when the input array is first sorted and then indexed with this array, it will give the correct result. Check the code for details.
For example, if `n` is 10, the transformed array is
```
[[1], [0, 1], [1, 1], [0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1], [0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 0, 1]]
```
which, if the final `1` in each of the embedded array is dropped, is simply a description of the path to walk from the root to the `n`th node, with `0` meaning going down the left branch and `1` going down the right. (This is the idea behind my original approach but I have made it much more complicated than needed)
Stax has the handy `|o` to transform it to the 0-based index array I need (credit to @Neil for directly sorting the embedded array without converting back to integer, as well as a much more efficient way to manipulate the array of the binary representation to achieve what I have in mind. The algorithm is now identical to that in his [own answer in Jelly](https://codegolf.stackexchange.com/questions/155358/sorting-for-search-by-monotomy/155458#155458). ):
```
[6, 3, 8, 1, 5, 7, 9, 0, 2, 4]
```
This submission takes 48 steps in total for `n`=10.
The code has been much trimmed down by @Neil and further trimmed down by @recursive as I am not familiar with code golfing in general and this is my first submission in PPCG.
```
o Sort input array
c Duplicate sorted array
% Size of the input array, denoted by `n` hereinafter
{ m Map range [1..n] (inclusive) with block (lambda){
:B Map the variable to its binary representation (as integer)
It also works if `:B` is replaced with `|B` which returns a string of the binary representation.
|( And then rotate the array by 1 bit
}
|o Get the destination index of each element if array were to be sorted
This gives the index array needed
@ Index the sorted input array with the index array
m Print all elements of the array
One element on each line
```
---
If I am not mistaken, this is the second appearance of Stax (edit: within the first 5, confirmed by the @recursive) as a golfing language for a public challenge in PPCG. I really appreciate Stax and I want to express my respect and gratitude to its creator, @recursive.
[Answer]
## JavaScript (ES6), ~~176~~ ~~144~~ 104 bytes
```
a=>a.sort((a,b)=>a-b).map((_,i)=>(i+1).toString(2).slice(1)+1).map((e,_,b)=>a[[...b].sort().indexOf(e)])
```
After reading @WeijunZhou's answer I realised that he was over-complicating his bit-twiddling and came up with a simple JavaScript port. Previous 144-byte recursive version:
```
f=(a,l=a.length,n=1,...r)=>n>l?l?[a[p=Math.min(l-n/4,n/2-1)],...f(...r,a.slice(0,p),p,n/=2,a.slice(p+1),l-p-1,n)]:[]:f(a.sort((a,b)=>a-b),l,n*2)
```
Explanation: Having sorted the array, the position of the root of the binary tree is calculated. The array is then split into its left and right halves and these subarrays are queued to processes the remaining positions. Example: For the sorted array `2,3,5,7,11,13,17,19,23,29` the root is in position 6. The first element of the result is therefore `17`. The array is then split into `2,3,5,7,11,13` for the second element and `19,23,29` for the third element. For the array `2,3,5,7,11,13` the root is in position 3. The second element of the result is therefore `7`. The array is then split into `2,3,5` for the fourth element and `11,13` for the fifth element. The array `19,23,29` then provides the element `23`, `2,3,5` provides `3` and `11,13` provides `13`. Meanwhile the rest of the elements have been split into 1-element arrays which are in the correct order for the rest of the result.
[Answer]
# Perl, ~~69~~ 68 bytes
Includes `+1` for `a`
```
perl -aE '$_=(sort{$a-$b}@F)[$n++]for sort@G=map{sprintf"%b1",++$m}@F;say"@G"' <<< "2 3 5 7 11 13 17 19 23 29"
```
] |
[Question]
[
I have the following code which I've written to emulate Newton's method for deriving the square root of a number:
```
r=(x,y)=>
(z=((y=y||x)*y-x)/(2*y)>1e-15)?
r(x,y-(y*y-x)/(2*y)):y
```
Where `r(37)` would result in `6.08276253029822` which is great given the limitations of my browser.
I'd like to golf this code further seeing there's some repetition here, not to mention, I'd also like to reduce my error limit (the `1e-15`). This is the furthest I've gotten. Can anyone help? If possible I'd love to eliminate the need of the error limit without resulting in a "maximum stack call size exceeded" error...
This is for a blog post I'm working on JavaScript and alternatives to native methods. I'll give a special shout out on the blog post to the persons who can help me out.
Thanks in advance.
[Answer]
# Golfed only, -23 bytes
ES6 supports [default parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters).
>
> **Default function parameters** allow formal parameters to be initialized
> with default values if no value or `undefined` is passed.
>
>
>
So, we can replace `y=y||x` with just `r=>(x,y=x)`.
`(y*y-x)/(2*y)` can be rewritten as `y/2-x/2/y`. And since this expression appears twice in the code, we can assign it to a new variable ***z***.
We get:
```
r=(x,y=x)=>(z=y/2-x/2/y)>1e-15?r(x,y-z):y
```
As suggested by **ETHproductions** in the comments, we now can save 2 more bytes by multiplying ***z*** by 2:
```
r=(x,y=x)=>(z=y-x/y)>2e-15?r(x,y-z/2):y
```
```
r=(x,y=x)=>(z=y-x/y)>2e-15?r(x,y-z/2):y
console.log(r(37))
```
---
# Alternate version, -26 bytes
To save more bytes, another approach is to just iterate *enough times* rather than using a test on the result.
That could be done that way:
```
r=(x,y=k=x)=>(k/=2)?r(x,y/2+x/2/y):y
```
```
r=(x,y=k=x)=>(k/=2)?r(x,y/2+x/2/y):y
console.log(r(37))
```
We start with `k = x` and divide it by 2 at each iteration. No matter the initial value of ***x***, we will eventually reach 0 because of [arithmetic underflow](https://en.wikipedia.org/wiki/Arithmetic_underflow).
The good thing about this method is that the number of iterations doesn't heavily rely on the value of ***x***. For instance, we'll get 1142 iterations for ***x = 1020*** and 1009 iterations for ***x = 10 -20***. In both cases, we iterate far too many times than necessary, without exceeding the default maximum number of iterations of common browsers.
Some more notes:
* The error is negligible for ***x > 10 -215*** and quickly grows below this bound.
* For the same byte count and less iterations, we can divide by 9 instead. In that case, a safe bound is ***x > 10 -124***.
* Unlike `Math.sqrt()`, this method does not return `NaN` for negative numbers or `±Infinity` (and neither does the original code).
[Answer]
This is almost similar to "@Arnauld Alternate version" and has same bytes with that, but this can work in `x < 1e-215`
```
r=(x,y=k=9)=>k?r(x,(y+x/y)/2,k/=2):y
```
] |
[Question]
[
A company is arranged in a heirarchical structure, with a layer of workers at the bottom. Each worker is managed by a manager. Consequently, each manager is managed by another manager until there is a company "boss". Each manager is restricted to managing, at most, `x` workers. For a company of size `y` calculate the number of managers required (including the boss)
Function should take two inputs.
Eg non-golfed definition:
`calc_num_managers(num_workers, num_workers_per_manager)`
You can assume that the number of workers per manager will be greater than 1.
Examples:
* A company with 0 workers needs 0 managers
* If the company has 4 workers, and each manager can manage 8 workers, then there is 1 manager.
* If the company has 4 workers, and each manager can manage 4 workers, then you need 1 manager
* If the company has 12 workers, and each manager can manage 8 workers, then there are 3 managers:
[](https://i.stack.imgur.com/9i7Yg.png)
[Answer]
## C, C++, Java, C#, D : ~~73~~ 69 bytes
-4 bytes thanks to Zacharý
Due to the similarities between theses languages, this answer works for each.
Maybe it works in processing too, but i can't test
```
int c(int w,int p){int r=0;do{w=(w+p-1)/p;r+=w;}while(w>1);return r;}
```
Here is an optimized version in **D : 62 bytes** thanks to Zacharý
```
T c(T)(T w,T p){T r;do{w=(w+p-1)/p;r+=w;}while(w>1);return r;}
```
T here is a type for template metaprogramming. This function is callable with `c(4,8);`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
Ṃ÷⁴Ċ0Ṃ’$?µÐĿḊS
```
[Try it online!](https://tio.run/##y0rNyan8///hzqbD2x81bjnSZQBkPmqYqWJ/aOvhCUf2P9zRFfz//39Do/8WAA "Jelly – Try It Online")
[Answer]
# JavaScript, ~~46~~ 43 bytes
If scheme isn't solvable, there will be stack exeeded error
-3 bytes `ceil` trick inspired by *Cows quack*
```
f=(w,m)=>(r=0|(w+m-1)/m,r>1&&(r+=f(r,m)),r)
//test
;[[0,1],[4,8],[4,4],[12,8],[8,3],[10,3]]//0;1;1;3;4;7
.map(e=>console.log("w="+e[0]+" m="+e[1]+" result="+f(e[0],e[1])))
```
## Requirements
`w` count of workers, non-negative integer
`m` count of max workers per manager, positive integer
[Answer]
# [Perl 5](https://www.perl.org/), 44 + 1 (-n) = 45bytes
```
$t=<>;$m+=$_=1+int$_/$t while($_>1);say$m|$_
```
[Try it online!](https://tio.run/##K0gtyjH9/1@lxNbGzlolV9tWJd7WUDszr0QlXl@lRKE8IzMnVUMl3s5Q07o4sVIlt0Yl/v9/Qy6Lf/kFJZn5ecX/dX1N9QwMDf7r5gEA "Perl 5 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
ΣtU¡(⌈/
```
[Try it online!](https://tio.run/##yygtzv7//9ziktBDCzUe9XTo//8PAA "Husk – Try It Online")
Repeatedly (`¡`) takes the ceiling (`⌈`) of the division (`/`) of the number of workers by the number of workers per manager and sums (`Σ`) all the unique results (`U`).
] |
[Question]
[
What general tips do you have for golfing in BBC BASIC? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to BBC BASIC (e.g. "remove comments" is not an answer).
[Answer]
Spaces after keywords are optional because of tokenisation. For example:
```
INPUT answer$
PRINT answer$
IF answer$ = 'Hi' THEN
PRINT 'Hi!'
ENDIF
```
Can be shortened to
```
INPUTanswer$
PRINTanswer$
IFanswer$='Hi'THEN
PRINT'Hi!'
ENDIF
```
The corollary of this is, a variable name cannot start with a keyword. So `PRINTa` is not a valid variable name. However `printa` is.
Spaces *before* keywords can be more tricky. Variable names can end with a keyword, so if variable name and keyword are run together they will be interpreted as a variable name.
For example the following gives a "no such variable" error because the variable `aPRINT` is not defined:
```
a=7
IF7=aPRINT"seven"
```
By rearranging this can be avoided:
```
a=7
IFa=7PRINT"seven"
```
This is a trivial example, but frequently rearranging an expression to end in a number or bracket instead of a variable name will enable you to eliminate a trailing space.
[Answer]
Use VDU codes to perform graphics tasks.
All graphics in BBC basic was performed via machine-specific ASCII control characters. The `VDU` command exists to enable you to pass ASCII characters direct to the video controller.
For example in `PLOT101,500,300` (draw a rectangle whose diagonal corners are the last position of the graphics cursor and the new point 500,300) can be subsituted by `VDU25,101,500;300;` The coordinates are followed by `;` because they are double byte values. We can also replace `25,101,` by `25881;` which is the 16-bit little-endian representation of these 2 bytes.
Although this actually makes things longer when you have only one PLOT statement, if you have several it is shorter. When you have a long string of VDU codes every PLOT can be replaced by `25,` (or if you declare `a=25` simply by `a,`)
Here's an example of this technique: <https://codegolf.stackexchange.com/a/26732/15599>
Note that this is not just limited to `PLOT`. `MODE, GCOL, COLOUR, ORIGIN etc` can all work out shorter when expressed as a series of numeric values in a long `VDU` statement.
[Answer]
Choose your interpreter well.
Very few of us have access to an original BBC micro, There's a whole range of interpreters at <http://www.bbcbasic.co.uk/bbcbasic.html> . Each implementation is slightly different.
My preferred interpreter is the first one on the list, "BBC Basic for Windows" written by RT Russell and available for Linux through Wine. It covers virtually all the features of original BBC Basic, including for example sound through the windows API, and has many enhancements. Its IDE and help are easy to use and feature packed.
It frequently allows you to omit colons between statements (which other implementations also do to some extent, but less) and it does not require you to number the lines of your program. On the downside, it only handles strings up to 255 characters and the evaluation version is restricted to 16k memory.
The other major family of BBC basics is Brandy Basic and its derivatives. Written in C, this is extremely portable, but has less features. For example it does not include sound, and rather than simply ignoring sound commands the program crashes. It is however able to handle longer strings than R T Russell's implementation so I have used it on occasion. There is no modern IDE, but it replicates BBC Basic's commandline fairly well (so it's not difficult to use *if* you are already familiar with BBC Basic.)
[Answer]
Use FN instead of PROC or GOSUB
GOSUB is very old fashioned. it requires a line number, so you have the following:
```
GOSUB90
.
.
90 dosomething
RETURN
```
7 characters to call, 8 characters to define and return.
PROC doesnt require a line number. Here you have
```
PROCa(x,y,z)
.
.
DEFPROCa(x,y,z)
dosomething
ENDPROC
```
5 characters to call (excluding arguments), 13 characters to define and return
With FN you have
```
q=FNa(x,y,z)
.
.
DEFFNa(x,y,z)
dosomething
=1
```
5 characters to call (excluding arguments, but including the obligatory use of the return value.) 8 characters to define and return
FN wins pretty much all the time, especially if you can make use of the return value. If you have no arguments you can omit the brackets.
[Answer]
**Use Abbreviated Keywords**
Surprised this wasn't mentioned before, but BBC Basic supports abbreviated versions of keywords so that, eg:
`1 FOR X=1 TO 10 STEP 2:PRINT X:NEXT X`
Can be rewritten as (omitting space where possible too):
`1F.X=1TO10S.2:P.X:N.X`
Some keywords don't have abbreviations (eg, `IF`). The complete list is in the BBC Basic manual chapter 48, there's a handy copy [here](https://www.ncus.org.uk/dsbbcoms.htm) too.
The most surprising part is that abbreviations for some functions include the opening parenthesis, eg: `PRINT MID$("HELLO",3,2)` is abbreviated as `P.M."HELLO",3,2)` - note the closing parenthesis is required even though the opening one was abbreviated away.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 10 years ago.
[Improve this question](/posts/12216/edit)
This puzzle works for any programming language that has the same `//` single-line and `/* ... */` multi-line comments that C++, C# and Java do.
You are debugging an application. You find a fishy block of code, which you comment out and replace with some new code:
```
/*
code block A
*/
code block B
```
After some debugging, you find that you need to step through block A again to see how it worked. This requires quite a lot of cursor movement:
```
← remove “/*” here
code block A
/* ← change “*/” to “/*” here
code block B
*/ ← add “*/” here
```
This is very laborious if you need to keep switching between block A and block B. So you decide to find a better way.
Place combinations of asterisks and slashes before block A, between the blocks, and after block B, such that you can flip between block A and block B by adding/removing only one character in one place. You may assume that the code blocks A and B do not contain any `/*` or `*/`.
There are two possible solutions.
[Answer]
Toggle commented out blocks by adding/removing the last slash on the first line:
```
/**/
code block A
/*/
code block B
/**/
```
Bonus solution, toggle this one by adding/removing the first slash on the first line:
```
//*
code block A
/*/
code block B
/**/
```
] |
[Question]
[
Print the biggest-size subset of strings in the input that are all permutations of each other. If there are ties, any one will do. If no strings are permutations of each other (for example, only one string was given or the strings contain distinct characters), this is just one of the strings. If no strings were passed in , do not output anything or output an empty list.
Test cases:
```
Input => Output
["ABCDE", "EDBCA", "XYZ", "ZYX", "ZXY"] => ["XYZ", "ZYX", "ZXY"]
["A"] => ["A"]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
.¡{}éθ
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f79DC6trDK8/t@P8/WsnRydnFVUlHQcnVxcnZEcSIiIwCUVGREWAqIlIpFgA "05AB1E – Try It Online")
```
.¡ } # group the input strings by:
{ # sort (all permutations of each other will be identical when sorted)
é # sort the groups by length
θ # output the last (longest) group
```
[Answer]
# T-SQL, 267 bytes
SQL queries was totally made to solve this type of question
```
SELECT top 1WITH TIES x FROM(SELECT(SELECT a FROM(SELECT
top 999substring(x,number+1,1)a,*FROM
@,spt_values WHERE type='P'and number<len(x)ORDER BY a)c
WHERE x=t.x for xml path(''),type).value('.','char(9)')v,x FROM @ t)z
ORDER BY-count(*)over(PARTITION BY v),-len(x)
```
**[Try it online](https://rextester.com/GXJZ40415)**
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), ~~6~~ 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
üñ ñl
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=/PEg8Ww&input=WyJBQkNERSIsICJFREJDQSIsICJYWVoiLCAiWllYIiwgIlpYWSJdCi1R)
```
üñ ñl :Implicit input of array
ü :Sort & group by
ñ : Sorted strings
ñ :Sort by
l : Length
:Implicit output of last element
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 36 bytes
```
{max .classify(~*.comb.sort){*}||''}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OjexQkEvOSexuDgzrVKjTksvOT83Sa84v6hEs1qrtqZGXb32vzVXWn6RgkZOZl5qsaZCNZeCQnFipUKahp5rmKOPJlft/2glRydnF1clHQUlVxcnZ0cQIyIyCkRFRUaAqYhIpVguoDoQGQsA "Perl 6 – Try It Online")
Output an empty string for an empty input. If we could output something else, for example `-Inf`, then this could be:
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 31 bytes
```
*.classify(~*.comb.sort){*}.max
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfSy85J7G4ODOtUqMOyM7PTdIrzi8q0azWqtXLTaz4b82Vll@koJGTmZdarKlQzaWgUJxYqZCmoeca5uijyVX7P1rJ0cnZxVVJR0HJ1cXJ2RHEiIiMAlFRkRFgKiJSKZYLqA5ExgIA "Perl 6 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 19 bytes
```
0({>\:#&>)/:~&></.]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DTSq7WKslNXsNPWt6tTsbPT1Yv9rcnGlJmfkK6Qp2FjrxRsCdTk6Obu4KkRERim4ujg5OypERUYoREVEqsPVqTuq/wcA "J – Try It Online")
*-2 bytes thanks to FrownyFrog*
Similar approach to Grimmy's answer.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~79~~ 77 bytes
```
lambda A,S=sorted:A and max([[y for y in A if S(x)==S(y)]for x in A],key=len)
```
[Try it online!](https://tio.run/##dYu9CsMgGEX3PsWHk4JTx4KD@XkCF03qYFGpNNFgM8SntySUQqGd7r2ce5ay3lM8V8@udTLzzRrgVLBnyquzFw4mWpjNhsexgE8ZCoQIHIIHgTfCmMCF6B1sB9D04QqbXCR1ySGu4PGIeNN2PaKApBr26Lum5XsZlDxCKqTJ6Yfweb7Nv8LX1KS@AA "Python 2 – Try It Online")
2 bytes thx to [wilkben](https://codegolf.stackexchange.com/users/88089/wilkben).
The `A and...` is only required to deal with the empty input.
[Answer]
# [Clojure](https://clojure.org/), 54 bytes
```
#(some val(sort-by(comp count val)>(group-by sort %)))
```
Returns `nil` for empty input.
[Try it online!](https://tio.run/##S87JzyotSv2vkZKappD2X1mjOD83VaEsMQfIKCrRTarUSM7PLVBIzi/NKwEJa9pppBfllxYAZRRAKhRUNTU1/2tyaRQUZeaV5ORppClEKzk6Obu4KukoKLm6ODk7ghgRkVEgKioyAkxFRCrFaqJrwhAC8v8DAA "Clojure – Try It Online")
] |
[Question]
[
Your challenge is to create the longest run of characters with incrementing Unicode codepoints in a [pristine program](https://codegolf.stackexchange.com/questions/63433/programming-a-pristine-world) as you can. To keep things simple, I'll abridge the definition for this challenge to be "any program which produces no errors but will error if any one character is removed".
Let's define a codepoint run as any contiguous substring of N characters, where `1 <= N <= program length`, where the Unicode/UTF-8 codepoints increment by 1 for each character.
For example: `abc`, `<=>`, `{|`, and `ƐƑƒƓƔ` are all codepoint runs.
Your program (must be a standalone program) doesn't have to be purely a codepoint run. Instead, **its score will be the length in *characters* of the longest codepoint run in its source code**. A program `dabc`'s score would be 3.
**Note that your program does not need to actually output anything, as long as it does not error.**
* Compiler warnings do not count as errors
* Your program does not need to (but still can) error if more than 1 contiguous character is removed
* Your program may take input only if the contents of the input do not affect whether or not the program errors
* Any code which is not part of the longest codepoint run is ignored in the scoring
* Highest score, as in code golf, is per-language
[Answer]
# [Python 3](https://docs.python.org/3/), run of 1,114,111
```
#coding:utf
assert len(open(__file__).read(1061))==1061
"""
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼʽʾʿˀˁ˂˃˄˅ˆˇˈˉˊˋˌˍˎˏːˑ˒˓˔˕˖˗˘˙˚˛˜˝˞˟ˠˡˢˣˤ˥˦˧˨˩˪˫ˬ˭ˮ˯˰˱˲˳˴˵˶˷˸˹˺˻˼˽˾˿̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼͇͈͉͍͎̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆͊͋͌̕̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮͯ͘͜͟͢͝͞͠͡ͰͱͲͳʹ͵Ͷͷͺͻͼͽ;Ϳ΄΅Ά·ΈΉΊΌΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώϏϐϑϒϓϔϕϖϗϘϙϚϛϜϝϞϟϠϡϢϣϤϥϦϧ"""
```
[Try it online!](https://tio.run/##FdV1t@R1AYDxY@vqsTtxMXYNBFFUFBW7u2tFWEJxF2FRMae7u7v7zp2euTPnfLt/L2nFf57PS3ieeu7W4zdv3Hv79p0P33zkiRuP3f/srUcvPfTMM9efvnXHk9dvXLn51PO5du3RJ568fu3a1buevv7QI1fuufu@e65efeCB/3vp8uXLL3jhi178kpe@7OWvuPTKV1169Wte@7rXv@GNb3rzW976tre/453vevd77njv5Tvf9/4PfPDK1Q99@CMfvetjd9/z8Xs/8cn7PvXpz9z/2c898PkvfPHBL335K1/92te/8c1vffs73/3e93/wwx/9@Cc//dnPf/HLX/36N7/93bXfP/SHhx@5/uhjjz/xxz89@ecbN5/6y9PP3Hr2r3/7@3P/@Oe//v2f/wIbsAMHcAIXcAMP8AIf8IMACIIQCIMIiIIYiIMESIIUSIMMyIIcyIMCKIISKIMKqIIaqIMGaIIWaIMO6IIe6IMBGIIRGIMJmIIZOANzcA4WYAlWYA02YAt2YA8O4AIcwQnaoB06oBO6oBt6oBf6oB8GYBCGYBhGYBTGYBwmYBKmYBpmYBbmYB4WYBGWYBlWYBXWYB02YBO2YBt2YBf2YB8O4BCO4BhO4BTO4Bmcw3O4gEu4gmu4gVu4g3t4gBfwCE/IhuzIgZzIhdzIg7zIh/wogIIohMIogqIohuIogZIohdIog7Ioh/KogIqohMqogqqohuqogZqohdqog7qoh/pogIZohMZogqZohs7QHJ2jBVqiFVqjDdqiHdqjA7pAR3TCNmzHDuzELuzGHuzFPuzHARzEIRzGERzFMRzHCZzEKZzGGZzFOZzHBVzEJVzGFVzFNVzHDdzELdzGHdzFPdzHAzzEIzzGEzzFM3yG5/gcL/ASr/Aab/AW7/AeH/AFPuITsRE7cRAncRE38RAv8RE/CZAgCZEwiZAoiZE4SZAkSZE0yZAsyZE8KZAiKZEyqZAqqZE6aZAmaZE26ZAu6ZE@GZAhGZExmZApmZEzMifnZEGWZEXWZEO2ZEf25EAuyJGcqI3aqYM6qYu6qYd6qY/6aYAGaYiGaYRGaYzGaYImaYqmaYZmaY7maYEWaYmWaYVWaY3WaYM2aYu2aYd2aY/26YAO6YiO6YRO6Yye0Tk9pwu6pCu6phu6pTu6pwd6QY/0xGzMzhzMyVzMzTzMy3zMzwIsyEIszCIsymIszhIsyVIszTIsy3IszwqsyEqszCqsymqszhqsyVqszTqsy3qszwZsyEZszCZsymbsjM3ZOVuwJVuxNduwLduxPTuwC3ZkJ27jdu7gTu7ibu7hXu7jfh7gQR7iYR7hUR7jcZ7gSZ7iaZ7hWZ7jeV7gRV7iZV7hVV7jdd7gTd7ibd7hXd7jfT7gQz7iYz7hUz7jZ3zOz/mCL/mKr/mGb/mO7/mBX/AjPwmbsAuHcAqXcAuP8Aqf8IuACIqQCIuIiIqYiIuESIqUSIuMyIqcyIuCKIqSKIuKqIqaqIuGaIqWaIuO6Iqe6IuBGIqRGIuJmIqZOBNzcS4WYilWYi02Yit2Yi8O4kIcxUnapF06pFO6pFt6pFf6pF8GZFCGZFhGZFTGZFwmZFKmZFpmZFbmZF4WZFGWZFlWZFXWZF02ZFO2ZFt2ZFf2ZF8O5FCO5FhO5FTO5Jmcy3O5kEu5kmu5kVu5k3t5kBfyKE/KpuzKoZzKpdzKo7zKp/wqoIIqpMIqoqIqpuIqoZIqpdIqo7Iqp/KqoIqqpMqqoqqqpuqqoZqqpdqqo7qqp/pqoIZqpMZqoqZqps7UXJ2rhVqqlVqrjdqqndqrg7pQR3XSNm3XDu3ULu3WHu3VPu3XAR3UIR3WER3VMR3XCZ3UKZ3WGZ3VOZ3XBV3UJV3WFV3VNV3XDd3ULd3WHd3VPd3XAz3UIz3WEz3VM32m5/pcL/RSr/Rab/RW7/ReH/SFPuqTsRm7cRincRm38Riv8Rm/CZigCZmwiZioiZm4SZikSZm0yZisyZm8KZiiKZmyqZiqqZm6aZimaZm26Ziu6Zm@GZihGZmxmZipmZkzMzfnZmGWZmXWZmO2Zmf25mAuzNGcLJtltxyW03JZbstjeS2f5bcCVtAKWWErYkWtmBW3ElbSSllpK2NlrZyVtwpW0SpZZatiVa2aVbcaVtNqWW2rY3WfP@rt2/8D "Python 3 – Try It Online")
The triple-quoted contains the entire Unicode range except for the null byte `\0` which terminates a program. (Thanks to Chas Brown for suggesting triple-quoting, which allowed 13 more characters.) The TIO link uses a shortened version; assume that the number 1061 is replaced with the code length.
The program opens itself and checks that it has the appropriate length, which guards against any deletion. No one-character deletion can disable this logic in the code. Lowering either the number of characters read or the number checked for equality will make the assertion fail.
I'm not totally sure if all Unicode characters except '\0' are valid in Python code, and I haven't been able to test it. Maybe this is system dependent. Please let me know if this fails at some point.
We can also do this without reading the file:
```
s="""
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼʽʾʿˀˁ˂˃˄˅ˆˇˈˉˊˋˌˍˎˏːˑ˒˓˔˕˖˗˘˙˚˛˜˝˞˟ˠˡˢˣˤ˥˦˧˨˩˪˫ˬ˭ˮ˯˰˱˲˳˴˵˶˷˸˹˺˻˼˽˾˿̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼͇͈͉͍͎̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆͊͋͌̕̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮͯ͘͜͟͢͝͞͠͡ͰͱͲͳʹ͵Ͷͷͺͻͼͽ;Ϳ΄΅Ά·ΈΉΊΌΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώϏϐϑϒϓϔϕϖϗϘϙϚϛϜϝϞϟϠϡϢϣϤϥϦϧ"""
assert len(s)==999
```
[Try it online!](https://tio.run/##DdUFF6/3AADgoxlHd85Vm2bq4mK6u3sYw2yzOzH57@7u7u6Oc37d70e6PF/ieezJJx569JH77ty5fevGjRtPeerTnv6MZz7r2c@567nPu@v5L3jhi178kpe@7OWveOWrXv2a177u9W@4@4033vTmt7z1bffc@/Z3vPNd737Pe9/3/vs@8MEPffgjNz/6sY/f@sQnP3X/pz/z2c99/gtf/NKXv/LVr339G9/81re/893vff8HP/zRj3/y05/9/Be/fOBXv/7Ng7/93UO//8MfH/7TI48@9ufHbz/xl7/@7e9P/uOf//r3f/4LbMAOHMAJXMANPMALfMAPAiAIQiAMIiAKYiAOEiAJUiANMiALciAPCqAISqAMKqAKaqAOGqAJWqANOqALeqAPBmAIRmAMJmAKZmAOFmAJVmANNmALdmAPDuAITuAMLuAKbdAOHdAJXdANPdALfdAPAzAIQzAMIzAKYzAOEzAJUzANMzALczAPC7AIS7AMK7AKa7AOG7AJW7ANO7ALe7APB3AIR3AMJ3AKZ3AOF3AJV3ANN3ALd3APD/AIT/AML/CKbMiOHMiJXMiNPMiLfMiPAiiIQiiMIiiKYiiOEiiJUiiNMiiLciiPCqiISqiMKqiKaqiOGqiJWqiNOqiLeqiPBmiIRmiMJmiKZmiOFmiJVmiNNmiLdmiPDuiITuiMLuiKbdiOHdiJXdiNPdiLfdiPAziIQziMIziKYziOEziJUziNMziLcziPC7iIS7iMK7iKa7iOG7iJW7iNO7iLe7iPB3iIR3iMJ3iKZ3iOF3iJV3iNN3iLd3iPD/iIT/iML/hKbMROHMRJXMRNPMRLfMRPAiRIQiRMIiRKYiROEiRJUiRNMiRLciRPCqRISqRMKqRKaqROGqRJWqRNOqRLeqRPBmRIRmRMJmRKZmROFmRJVmRNNmRLdmRPDuRITuRMLuRKbdROHdRJXdRNPdRLfdRPAzRIQzRMIzRKYzROEzRJUzRNMzRLczRPC7RIS7RMK7RKa7ROG7RJW7RNO7RLe7RPB3RIR3RMJ3RKZ3ROF3RJV3RNN3RLd3RPD/RIT/RML/TKbMzOHMzJXMzNPMzLfMzPAizIQizMIizKYizOEizJUizNMizLcizPCqzISqzMKqzKaqzOGqzJWqzNOqzLeqzPBmzIRmzMJmzKZmzOFmzJVmzNNmzLdmzPDuzITuzMLuzKbdzOHdzJXdzNPdzLfdzPAzzIQzzMIzzKYzzOEzzJUzzNMzzLczzPC7zIS7zMK7zKa7zOG7zJW7zNO7zLe7zPB3zIR3zMJ3zKZ3zOF3zJV3zNN3zLd3zPD/zIT/zML/wqbMIuHMIpXMItPMIrfMIvAiIoQiIsIiIqYiIuEiIpUiItMiIrciIvCqIoSqIsKqIqaqIuGqIpWqItOqIreqIvBmIoRmIsJmIqZmIuFmIpVmItNmIrdmIvDuIoTuIsLuIqbdIuHdIpXdItPdIrfdIvAzIoQzIsIzIqYzIuEzIpUzItMzIrczIvC7IoS7IsK7Iqa7IuG7IpW7ItO7Ire7IvB3IoR3IsJ3IqZ3IuF3IpV3ItN3Ird3IvD/IoT/IsL/KqbMquHMqpXMqtPMqrfMqvAiqoQiqsIiqqYiquEiqpUiqtMiqrciqvCqqoSqqsKqqqaqquGqqpWqqtOqqreqqvBmqoRmqsJmqqZmquFmqpVmqtNmqrdmqvDuqoTuqsLuqqbdquHdqpXdqtPdqrfdqvAzqoQzqsIzqqYzquEzqpUzqtMzqrczqvC7qoS7qsK7qqa7quG7qpW7qtO7qre7qvB3qoR3qsJ3qqZ3quF3qpV3qtN3qrd3qvD/qoT/qsL/pqbMZuHMZpXMZtPMZrfMZvAiZoQiZsIiZqYiZuEiZpUiZtMiZrciZvCqZoSqZsKqZqaqZuGqZpWqZtOqZreqZvBmZoRmZsJmZqZmZuFmZpVmZtNmZrdmZvDuZoTuZsLuZq2Sy75bCclstyWx7La/ksvxWwglbIClsRK2rFrLiVsJJWykpbGStr5ay8VbCKVskqWxWratWsutWwmlbLalsdq/v/Ue964PbtBx9/4u6HH3zkntv33rp18@bNO3f@Bw "Python 3 – Try It Online")
There isn't a way to delete a character from the assertion line while keeping it syntactically valid and preserving the length number.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), Score: 1114076
```
var s=@"Insert all characters from character 36 then on";if(s.Length!=1114076)throw new Exception();
```
[Try it online!](https://tio.run/##RccxCsJAEAXQq3xTJYWSRYlFCNhYBLzEMkzchTgrM0Pi7dcyr3tkZ7Jc6xYVNj2aWYzVEdcVlKJGclbDouVzHNcBnlhQpBnz0trlxfL2dJpCCLf@PnSetOwQ3vH8EX89F2m7sdY/ "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# x86 machine code, score: 1,114,112
```
E9 81 F7 42 00 00 01 02 ... F4 8E BF BF C3
```
In assembly:
```
main:
jmp $+4388742 # i.e. to the end
.byte 0,1,...,0xF4,0x8F,0xBF,0xBF
end:
ret
```
The code that is executed is just a relative jump followed by a return. All the unicode codepoints are in between.
If the jump itself or any of the first three bytes of its offset are deleted, then the unicode codepoints are executed as code until it crashes. If any byte after that is removed, then it jumps past the end of the program and eventually crashes.
] |
[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/182505/edit).
Closed 4 years ago.
[Improve this question](/posts/182505/edit)
Telephones in the United States (and perhaps some other places) have letters associated with some of the numbers.
```
2 = A, B, C
3 = D, E, F
4 = G, H, I
5 = J, K, L
6 = M, N, O
7 = P, Q, R, S
8 = T, U, V
9 = W, X, Y, Z
```
No letters are associated with the number 0 or 1.
Your challenge: Given any phone number in seven-digit or ten-digit format, return English words or phrases into which it could be translated using the code above. Spaces do not matter.
So, for example
873-5377 can be translated to “useless” or “trek-err” and possibly a few others depending on your words list.
For the purposes of this contest,
1. All digits in the phone number must be used and must be translated into letters. This means that phone numbers containing 0s or 1s can not be translated.
2. If your operating system or programming environment has a built-in words list (/usr/share/dict/words or the equivalent), go ahead and use it. Otherwise, you can assume that a word list has been downloaded to a convenient directory. However, (a) no-preprocessing of the dictionary to limit it to seven and ten letter words or anything like that, and (b) you have to open the dictionary and load the words yourself; you can’t just pass a variable that contains a list of words.
3. If your dictionary includes proper nouns, it’s OK to have them in your output.
4. You can not assume that your input is an integer. The number 213-867-5309 might be input as (213) 867-5409 or 2138675309. Strip all non-numerical characters and make sure what’s left is a seven or ten-digit integer.
5. Your answer can be a function or a complete program, but no snippets.
FOR EXTRA CREDIT
6. You may implement a version of the code that replaces rule 1 with a more forgiving test — you may leave up to 2 numbers as numbers while changing all the other numbers to words. If you choose this path, the code must complete a comprehensive search and not do something trivial like leaving the first two numbers as numbers while doing word substitution on the rest. Obviously in this variation, phone numbers with up to two 0s and 1s may be translated.
Using the same test number as above, rule 6 gives us the answers "us-elf-77", "us-ekes-7", and others in addition to the answers above.
TEST NUMBERS
Show us what you get for 868-454-6523 and 323-454-6503.
SCORING
Shortest code wins, but if you’ve implemented rule 6 you can cut your length in half. I also plan to call out interesting solutions or solutions from verbose languages that might have won if their command names were shorter.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 207 bytes
```
þ"! ! ABC DEF GHI JKL MNO PQRS TUV WXYZ"S#sSèU
"€‚ƒ„…†‡ˆ‰Š‹ŒŽ•–—™š›œžŸ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîï"©vyV®vYy«"“ÿ“".Vu}})
ʒg¹þgQ}
ʒ´vXNèyåˆ}¯P}
¹þg7Q¹þgTQ&i´¯}
```
[Try it online!](https://tio.run/##HY83T0JhAEV3fsXnMzE66GCwjfZekGLZNDHEycFIwvCST0TsDeydKk3ALqiQ3JvnoP/i@yNIXM49yZ3OwuLM7PxcucyiViWqRHtHp@jq7hG9ff1iYHBIDI@MijHLuFXY7A4xMTk1rVmrF62M202a8qSVPP/2K3mtZEzJWyWDvz4lc0bF8obf@FIypGRAyUPlDRlBJQtGwCga7wgihDAiiCKGO8SRQBIppJFBFjk84BFPeMYLXvGGd@RRwAc@8YUiSpRcpocr9HKVPq5xnRvc5Ba3ucNd7nGfB/QzwEMe8ZgnPOUZz3nBS17xmje8ZZAhhhlhlDHeMc4Ek0wxzXtmmNWQcLkdyLim3EhpSl6yVIHW4FjS9TrTj9@JPItOi15RPLsmRxh3M/rr05Ed003/X4vlf2yWmvlKRFYvl2vbWs11zS1N9Y2t5sY/ "05AB1E – Try It Online")
**(1)** The first line of the code, will replace each number in the input with the corresponding set of possible letters.
```
þ # Only digits of input.
"! ! ABC DEF GHI JKL MNO PQRS TUV WXYZ" # Push keypad letters.
S# # Split into list and on spaces.
sS # Split input into digits.
èU # Push indexes of digits and store in X.
```
**(2)** The second line of the code, will push every possible dictionary word that is stored in 05AB1E. It accomplishes this by pushing all pairings of the dictionary encrypted characters and converting them to their dictionary stored equivalents. There are 100 unique dictionary characters, and 100\*100 unique pairs of them. This means we are getting access to a total of 10,000 words from the 05AB1E dictionary.
**(3)** The third line of the code, will filter the dictionary by the length of the number of digits in the input.
**(4)** The fourth line of the code, will filter again the words from the dictionary which match the filter of possible letters outlined by line #1.
**(5)** The final line of the code, will simply return an empty array provided that the input was not 7 or 10 digits long after parsing.
---
Using no external libraries/files, this code can detect any word that is in the 05AB1E dictionary. More specifically, if the input is limited to 7 characters the following list:
```
["ABILITY", "ABRAHAM", "ABSENCE", "ACADEMY", "ACCEPTS", "ACCOUNT", "ACCUSED", "ACHIEVE", "ACQUIRE", "ACROBAT", "ACRYLIC", "ACTIONS", "ACTRESS", "ADAPTED", "ADAPTER", "ADAPTOR", "ADDRESS", "ADOPTED", "ADVANCE", "ADVERSE", "ADVISED", "ADVISOR", "AFFAIRS", "AFFECTS", "AFRICAN", "AGAINST", "AIRFARE", "AIRLINE", "AIRPORT", "ALABAMA", "ALBANIA", "ALBERTA", "ALCOHOL", "ALGEBRA", "ALGERIA", "ALLEGED", "ALLERGY", "ALLOWED", "ALREADY", "ALTERED", "AMATEUR", "AMAZING", "AMBIENT", "AMENDED", "AMERICA", "AMONGST", "AMOUNTS", "AMPLAND", "ANAHEIM", "ANALYST", "ANALYZE", "ANATOMY", "ANCIENT", "ANDORRA", "ANDREAS", "ANDREWS", "ANGELES", "ANIMALS", "ANOTHER", "ANSWERS", "ANTENNA", "ANTHONY", "ANTIGUA", "ANTIQUE", "ANTONIO", "ANXIETY", "ANYBODY", "ANYMORE", "ANYTIME", "APPAREL", "APPEALS", "APPEARS", "APPLIED", "APPLIES", "APPROVE", "AQUATIC", "ARCHIVE", "ARISING", "ARIZONA", "ARMENIA", "ARRANGE", "ARRIVAL", "ARRIVED", "ARRIVES", "ARTICLE", "ARTISTS", "ARTWORK", "ASPECTS", "ASSAULT", "ASSISTS", "ASSUMED", "ASSUMES", "ASSURED", "ATLANTA", "ATTACKS", "ATTEMPT", "ATTRACT", "AUCTION", "AUDITOR", "AUSTRIA", "AUTHORS", "AVERAGE", "AWARDED", "AWESOME", "BACKING", "BAGHDAD", "BAHAMAS", "BAHRAIN", "BALANCE", "BALLOON", "BANGBUS", "BANGKOK", "BANKING", "BANNERS", "BAPTIST", "BARBARA", "BARGAIN", "BARRIER", "BASKETS", "BATTERY", "BEACHES", "BEARING", "BEATLES", "BECAUSE", "BECOMES", "BEDDING", "BEDFORD", "BEDROOM", "BEIJING", "BELARUS", "BELFAST", "BELGIUM", "BELIEFS", "BELIEVE", "BELONGS", "BENEATH", "BENEFIT", "BENNETT", "BERMUDA", "BERNARD", "BESIDES", "BETTING", "BETWEEN", "BEVERLY", "BICYCLE", "BIDDING", "BIGGEST", "BILLING", "BILLION", "BINDING", "BIOLOGY", "BIZARRE", "BIZRATE", "BLANKET", "BLESSED", "BLOCKED", "BLOGGER", "BLOWING", "BLOWJOB", "BOATING", "BOLIVIA", "BONDAGE", "BOOKING", "BOOLEAN", "BORDERS", "BOROUGH", "BOTTLES", "BOULDER", "BOUQUET", "BOWLING", "BRACKET", "BRADLEY", "BRANDON", "BREASTS", "BRIDGES", "BRIEFLY", "BRISTOL", "BRITAIN", "BRITISH", "BRITNEY", "BROADER", "BROKERS", "BROTHER", "BROUGHT", "BROWSER", "BUDGETS", "BUFFALO", "BUILDER", "BUKKAKE", "BURNING", "BUTTONS", "CABINET", "CALCIUM", "CALGARY", "CALLING", "CAMERAS", "CAMERON", "CAMPING", "CANDLES", "CAPABLE", "CAPITAL", "CAPITOL", "CAPTAIN", "CAPTURE", "CARDIAC", "CARDIFF", "CAREERS", "CAREFUL", "CARRIED", "CARRIER", "CARRIES", "CARROLL", "CARTOON", "CASINOS", "CASTING", "CATALOG", "CAUSING", "CAUTION", "CEILING", "CENTERS", "CENTRAL", "CENTRES", "CENTURY", "CERAMIC", "CERTAIN", "CHAMBER", "CHANCES", "CHANGED", "CHANGES", "CHANNEL", "CHAPTER", "CHARGED", "CHARGER", "CHARGES", "CHARITY", "CHARLES", "CHARLIE", "CHARTER", "CHASSIS", "CHEAPER", "CHECKED", "CHELSEA", "CHESTER", "CHICAGO", "CHICKEN", "CHINESE", "CHOICES", "CHRONIC", "CIRCLES", "CIRCUIT", "CITIZEN", "CLAIMED", "CLARITY", "CLASSES", "CLASSIC", "CLEANER", "CLEANUP", "CLEARED", "CLEARLY", "CLIENTS", "CLIMATE", "CLINICS", "CLINTON", "CLOSELY", "CLOSEST", "CLOSING", "CLOSURE", "CLOTHES", "CLUSTER", "COACHES", "COASTAL", "COATING", "COLEMAN", "COLLECT", "COLLEGE", "COLLINS", "COLOGNE", "COLORED", "COLOURS", "COLUMNS", "COMBINE", "COMFORT", "COMMAND", "COMMENT", "COMMONS", "COMPACT", "COMPANY", "COMPARE", "COMPETE", "COMPILE", "COMPLEX", "COMPUTE", "CONCEPT", "CONCERN", "CONCERT", "CONCORD", "CONDUCT", "CONFIRM", "CONNECT", "CONSENT", "CONSIST", "CONSOLE", "CONSULT", "CONTACT", "CONTAIN", "CONTENT", "CONTEST", "CONTEXT", "CONTROL", "CONVERT", "COOKIES", "COOKING", "COOLING", "COPYING", "CORNELL", "CORNERS", "CORRECT", "COSTUME", "COTTAGE", "COUNCIL", "COUNSEL", "COUNTED", "COUNTER", "COUNTRY", "COUPLED", "COUPLES", "COUPONS", "COURAGE", "COURIER", "COURSES", "COVERED", "CREATED", "CREATES", "CREATOR", "CREDITS", "CRICKET", "CRITICS", "CROATIA", "CRUCIAL", "CRUISES", "CRYSTAL", "CUISINE", "CULTURE", "CUMSHOT", "CURIOUS", "CURRENT", "CUSTODY", "CUSTOMS", "CUTTING", "CYCLING", "DAMAGED", "DAMAGES", "DANCING", "DEALERS", "DEALING", "DEBORAH", "DECADES", "DECIDED", "DECIMAL", "DECLARE", "DECLINE", "DEFAULT", "DEFECTS", "DEFENCE", "DEFENSE", "DEFICIT", "DEFINED", "DEFINES", "DEGREES", "DELAYED", "DELETED", "DELIGHT", "DELIVER", "DEMANDS", "DENMARK", "DENSITY", "DEPENDS", "DEPOSIT", "DERIVED", "DESERVE", "DESIGNS", "DESIRED", "DESKTOP", "DESPITE", "DESTINY", "DESTROY", "DETAILS", "DETROIT", "DEUTSCH", "DEVELOP", "DEVIANT", "DEVICES", "DEVOTED", "DIAGRAM", "DIAMOND", "DIETARY", "DIGITAL", "DIPLOMA", "DISABLE", "DISCUSS", "DISEASE", "DISPLAY", "DISPUTE", "DISTANT", "DIVERSE", "DIVIDED", "DIVORCE", "DOCTORS", "DOLLARS", "DOMAINS", "DONATED", "DOUGLAS", "DRAWING", "DRESSED", "DRESSES", "DRIVERS", "DRIVING", "DROPPED", "DURABLE", "DYNAMIC", "EARLIER", "EARNING", "EASTERN", "ECLIPSE", "ECOLOGY", "ECONOMY", "ECUADOR", "EDITING", "EDITION", "EDITORS", "EDWARDS", "EFFECTS", "EFFORTS", "ELDERLY", "ELECTED", "ELECTRO", "ELEGANT", "ELEMENT", "ELLIOTT", "EMBASSY", "EMERALD", "EMPEROR", "ENABLED", "ENABLES", "ENDLESS", "ENEMIES", "ENGAGED", "ENGINES", "ENGLAND", "ENGLISH", "ENHANCE", "ENJOYED", "ENLARGE", "ENQUIRY", "ENSURES", "ENTERED", "ENTRIES", "EPISODE", "EQUALLY", "EROTICA", "ESCORTS", "ESSENCE", "ESTATES", "ESTONIA", "ETERNAL", "ETHICAL", "EVENING", "EVIDENT", "EXACTLY", "EXAMINE", "EXAMPLE", "EXCERPT", "EXCITED", "EXCLUDE", "EXECUTE", "EXHAUST", "EXHIBIT", "EXISTED", "EXPECTS", "EXPEDIA", "EXPENSE", "EXPERTS", "EXPIRED", "EXPIRES", "EXPLAIN", "EXPLORE", "EXPORTS", "EXPOSED", "EXPRESS", "EXTENDS", "EXTRACT", "EXTREME", "FABRICS", "FACTORS", "FACTORY", "FACULTY", "FAILING", "FAILURE", "FALLING", "FANTASY", "FARMERS", "FARMING", "FASHION", "FASTEST", "FATHERS", "FEATURE", "FEDERAL", "FEEDING", "FEELING", "FEMALES", "FERRARI", "FICTION", "FIFTEEN", "FIGHTER", "FIGURED", "FIGURES", "FILLING", "FILTERS", "FINALLY", "FINANCE", "FINDING", "FINDLAW", "FINGERS", "FINLAND", "FINNISH", "FIREFOX", "FISHING", "FISTING", "FITNESS", "FITTING", "FLIGHTS", "FLORIDA", "FLORIST", "FLOWERS", "FOCUSED", "FOCUSES", "FOLDERS", "FOLDING", "FOLLOWS", "FOOTAGE", "FOREIGN", "FORESTS", "FOREVER", "FORMATS", "FORMING", "FORMULA", "FORTUNE", "FORWARD", "FOUNDED", "FOUNDER", "FRAMING", "FRANCIS", "FREEBSD", "FREEDOM", "FREIGHT", "FRIENDS", "FUCKING", "FUJITSU", "FUNDING", "FUNERAL", "FURTHER", "FUTURES", "GABRIEL", "GADGETS", "GALLERY", "GARBAGE", "GARDENS", "GATEWAY", "GAZETTE", "GENERAL", "GENERIC", "GENESIS", "GENETIC", "GENUINE", "GEOLOGY", "GEORGIA", "GERMANY", "GETTING", "GILBERT", "GLASGOW", "GLASSES", "GLUCOSE", "GOURMET", "GRAMMAR", "GRANTED", "GRAPHIC", "GRATUIT", "GRAVITY", "GREATER", "GREATLY", "GREGORY", "GRENADA", "GRIFFIN", "GROCERY", "GROUNDS", "GROWING", "GUITARS", "HABITAT", "HALIFAX", "HAMBURG", "HAMPTON", "HANDJOB", "HANDLED", "HANDLES", "HANGING", "HAPPENS", "HARBOUR", "HARMFUL", "HARMONY", "HARVARD", "HARVEST", "HAZARDS", "HEADERS", "HEADING", "HEADSET", "HEALING", "HEALTHY", "HEARING", "HEATHER", "HEATING", "HEAVILY", "HEIGHTS", "HELPFUL", "HELPING", "HERSELF", "HEWLETT", "HIGHEST", "HIGHWAY", "HIMSELF", "HISTORY", "HITACHI", "HITTING", "HOBBIES", "HOLDERS", "HOLDING", "HOLIDAY", "HOLLAND", "HOPKINS", "HORIZON", "HORMONE", "HOSTELS", "HOSTING", "HOTMAIL", "HOTTEST", "HOUSING", "HOUSTON", "HOWEVER", "HUNDRED", "HUNGARY", "HUNTING", "HUSBAND", "HYGIENE", "HYUNDAI", "ICELAND", "IGNORED", "ILLEGAL", "ILLNESS", "IMAGINE", "IMAGING", "IMPACTS", "IMPLIED", "IMPLIES", "IMPORTS", "IMPOSED", "IMPROVE", "INCLUDE", "INDEXED", "INDEXES", "INDIANA", "INDIANS", "INDICES", "INDUCED", "INFANTS", "INITIAL", "INJURED", "INQUIRE", "INQUIRY", "INSECTS", "INSIDER", "INSIGHT", "INSTALL", "INSTANT", "INSTEAD", "INSULIN", "INSURED", "INTEGER", "INTENSE", "INTERIM", "INVALID", "INVITED", "INVOICE", "INVOLVE", "IRELAND", "ISLAMIC", "ISLANDS", "ISRAELI", "ITALIAN", "JACKETS", "JACKSON", "JAMAICA", "JANUARY", "JEFFREY", "JELSOFT", "JESSICA", "JEWELRY", "JOHNSON", "JOINING", "JOURNAL", "JOURNEY", "JUMPING", "JUSTICE", "JUSTIFY", "KARAOKE", "KATRINA", "KEEPING", "KENNEDY", "KENNETH", "KEYWORD", "KILLING", "KINGDOM", "KISSING", "KITCHEN", "KNIGHTS", "KNOWING", "LABELED", "LANDING", "LAPTOPS", "LARGELY", "LARGEST", "LASTING", "LATINAS", "LAUNDRY", "LAWSUIT", "LAWYERS", "LEADERS", "LEADING", "LEARNED", "LEASING", "LEATHER", "LEAVING", "LEBANON", "LECTURE", "LEGALLY", "LEGENDS", "LEISURE", "LENDERS", "LENDING", "LEONARD", "LESBIAN", "LESSONS", "LETTERS", "LETTING", "LEVITRA", "LEXMARK", "LIBERAL", "LIBERIA", "LIBERTY", "LIBRARY", "LICENCE", "LICENSE", "LICKING", "LIGHTER", "LIMITED", "LINCOLN", "LINDSAY", "LINKING", "LISTING", "LIVECAM", "LIVESEX", "LOADING", "LOCALLY", "LOCATED", "LOCATOR", "LOCKING", "LODGING", "LOGGING", "LOGICAL", "LONGEST", "LOOKING", "LOTTERY", "LUGGAGE", "MACHINE", "MADISON", "MADNESS", "MADONNA", "MAGICAL", "MAILING", "MAILMAN", "MANAGED", "MANAGER", "MANDATE", "MANUALS", "MAPPING", "MARILYN", "MARKERS", "MARKETS", "MARKING", "MARRIED", "MARTIAL", "MASSAGE", "MASSIVE", "MASTERS", "MATCHED", "MATCHES", "MATTERS", "MATTHEW", "MAXIMUM", "MEANING", "MEASURE", "MEDICAL", "MEDLINE", "MEETING", "MELISSA", "MEMBERS", "MEMPHIS", "MENTION", "MERCURY", "MESSAGE", "METHODS", "MEXICAN", "MICHAEL", "MIDWEST", "MILEAGE", "MILLION", "MINERAL", "MINIMAL", "MINIMUM", "MINOLTA", "MINUTES", "MIRACLE", "MIRRORS", "MISSILE", "MISSING", "MISSION", "MISTAKE", "MIXTURE", "MOBILES", "MODULAR", "MODULES", "MOLDOVA", "MOMENTS", "MONITOR", "MONSTER", "MONTANA", "MONTHLY", "MORNING", "MOROCCO", "MOTHERS", "MOUNTED", "MOZILLA", "MUSCLES", "MUSEUMS", "MUSICAL", "MUSLIMS", "MUSTANG", "MYANMAR", "MYSIMON", "MYSPACE", "MYSTERY", "NAMIBIA", "NATIONS", "NATURAL", "NAUGHTY", "NEAREST", "NEITHER", "NERVOUS", "NETWORK", "NEUTRAL", "NEWPORT", "NIAGARA", "NIGERIA", "NIPPLES", "NIRVANA", "NORFOLK", "NOTHING", "NOTICED", "NOTICES", "NOVELTY", "NOWHERE", "NUCLEAR", "NUMBERS", "NUMERIC", "NURSERY", "NURSING", "OAKLAND", "OBESITY", "OBJECTS", "OBSERVE", "OBVIOUS", "OCTOBER", "OFFENSE", "OFFERED", "OFFICER", "OFFICES", "OFFLINE", "OLYMPIC", "OLYMPUS", "ONGOING", "ONTARIO", "OPENING", "OPERATE", "OPINION", "OPPOSED", "OPTICAL", "OPTIMAL", "OPTIMUM", "OPTIONS", "ORDERED", "ORGANIC", "ORIGINS", "ORLANDO", "ORLEANS", "OUTCOME", "OUTDOOR", "OUTLETS", "OUTLINE", "OUTLOOK", "OUTPUTS", "OUTSIDE", "OVERALL", "PACIFIC", "PACKAGE", "PACKARD", "PACKETS", "PACKING", "PAINFUL", "PAINTED", "PANTIES", "PARENTS", "PARKING", "PARTIAL", "PARTIES", "PARTNER", "PASSAGE", "PASSING", "PASSION", "PASSIVE", "PATCHES", "PATENTS", "PATIENT", "PATRICK", "PATTERN", "PAYABLE", "PAYMENT", "PAYROLL", "PENALTY", "PENDANT", "PENDING", "PENGUIN", "PENSION", "PENTIUM", "PEOPLES", "PERCENT", "PERFECT", "PERFORM", "PERFUME", "PERHAPS", "PERIODS", "PERMITS", "PERSIAN", "PERSONS", "PHANTOM", "PHILIPS", "PHOENIX", "PHRASES", "PHYSICS", "PICKING", "PICTURE", "PIONEER", "PIRATES", "PISSING", "PLACING", "PLANETS", "PLANNED", "PLANNER", "PLASTIC", "PLAYBOY", "PLAYERS", "PLAYING", "PLEASED", "PLUGINS", "POCKETS", "PODCAST", "POINTED", "POINTER", "POKEMON", "POLYMER", "PONTIAC", "POPULAR", "PORSCHE", "PORTION", "POSSESS", "POSTAGE", "POSTERS", "POSTING", "POTTERY", "POULTRY", "POVERTY", "POWERED", "PRAIRIE", "PRAYERS", "PRECISE", "PREDICT", "PREFERS", "PREMIER", "PREMIUM", "PREPAID", "PREPARE", "PRESENT", "PRESSED", "PRESTON", "PREVENT", "PREVIEW", "PRICING", "PRIMARY", "PRINTED", "PRINTER", "PRIVACY", "PRIVATE", "PROBLEM", "PROCEED", "PROCESS", "PRODUCE", "PRODUCT", "PROFILE", "PROFITS", "PROGRAM", "PROJECT", "PROMISE", "PROMOTE", "PROPHET", "PROPOSE", "PROTECT", "PROTEIN", "PROTEST", "PROUDLY", "PROVIDE", "PUBLISH", "PULLING", "PURPOSE", "PURSUIT", "PUSHING", "PUTTING", "PUZZLES", "QUALIFY", "QUALITY", "QUANTUM", "QUARTER", "QUERIES", "QUICKLY", "QUIZZES", "RADICAL", "RAILWAY", "RAINBOW", "RAISING", "RALEIGH", "RANGERS", "RANGING", "RANKING", "RAPIDLY", "RATINGS", "RAYMOND", "REACHED", "REACHES", "READERS", "READILY", "READING", "REALITY", "REALIZE", "REALTOR", "REASONS", "REBATES", "REBECCA", "REBOUND", "RECEIPT", "RECEIVE", "RECIPES", "RECORDS", "RECOVER", "REDHEAD", "REDUCED", "REDUCES", "REFINED", "REFLECT", "REFORMS", "REFRESH", "REFUSED", "REGARDS", "REGIONS", "REGULAR", "RELATED", "RELATES", "RELEASE", "RELYING", "REMAINS", "REMARKS", "REMOVAL", "REMOVED", "RENEWAL", "RENTALS", "REPAIRS", "REPLACE", "REPLICA", "REPLIED", "REPLIES", "REPORTS", "REPRINT", "REQUEST", "REQUIRE", "RESERVE", "RESOLVE", "RESORTS", "RESPECT", "RESPOND", "RESTORE", "RESULTS", "RESUMES", "RETIRED", "RETREAT", "RETURNS", "REUNION", "REUTERS", "REVEALS", "REVENGE", "REVENUE", "REVERSE", "REVIEWS", "REVISED", "REWARDS", "RICHARD", "ROBERTS", "ROLLING", "ROMANCE", "ROMANIA", "ROUGHLY", "ROUTERS", "ROUTINE", "ROUTING", "ROYALTY", "RUNNING", "RUNTIME", "RUSSELL", "RUSSIAN", "SAILING", "SAMPLES", "SAMSUNG", "SATISFY", "SAVINGS", "SCANNED", "SCANNER", "SCHEMES", "SCHOLAR", "SCHOOLS", "SCIENCE", "SCORING", "SCRATCH", "SCREENS", "SCRIPTS", "SEAFOOD", "SEASONS", "SEATING", "SEATTLE", "SECONDS", "SECRETS", "SECTION", "SECTORS", "SECURED", "SEEKERS", "SEEKING", "SEGMENT", "SELLERS", "SELLING", "SEMINAR", "SENATOR", "SENDING", "SENEGAL", "SENIORS", "SENSORS", "SERIOUS", "SERVERS", "SERVICE", "SERVING", "SESSION", "SETTING", "SETTLED", "SEVENTH", "SEVERAL", "SHADOWS", "SHAKIRA", "SHANNON", "SHARING", "SHELTER", "SHEMALE", "SHERIFF", "SHERMAN", "SHIPPED", "SHOPPER", "SHORTER", "SHORTLY", "SHOWERS", "SHOWING", "SHUTTLE", "SIEMENS", "SIGNALS", "SIGNING", "SILENCE", "SILICON", "SIMILAR", "SIMPSON", "SINGING", "SINGLES", "SISTERS", "SITEMAP", "SITTING", "SKATING", "SKILLED", "SMALLER", "SMILIES", "SMOKING", "SOCIETY", "SOLARIS", "SOLDIER", "SOLOMON", "SOLVING", "SOMALIA", "SOMEHOW", "SOMEONE", "SOONEST", "SOURCES", "SPANISH", "SPATIAL", "SPEAKER", "SPECIAL", "SPECIES", "SPECIFY", "SPENCER", "SPIRITS", "SPONSOR", "SPRINGS", "SPYWARE", "STADIUM", "STANLEY", "STARTED", "STARTER", "STARTUP", "STATING", "STATION", "STATUTE", "STAYING", "STEPHEN", "STEVENS", "STEWART", "STICKER", "STOMACH", "STOPPED", "STORAGE", "STORIES", "STRANGE", "STREAMS", "STREETS", "STRETCH", "STRIKES", "STRINGS", "STRIPES", "STUDENT", "STUDIED", "STUDIES", "STUDIOS", "STUFFED", "STYLISH", "SUBJECT", "SUBLIME", "SUCCEED", "SUCCESS", "SUCKING", "SUGGEST", "SUICIDE", "SUMMARY", "SUNRISE", "SUPPORT", "SUPPOSE", "SUPREME", "SURFACE", "SURFING", "SURGEON", "SURGERY", "SURNAME", "SURPLUS", "SURVEYS", "SURVIVE", "SUSPECT", "SWEDISH", "SYMBOLS", "SYSTEMS", "TABLETS", "TACTICS", "TALKING", "TARGETS", "TEACHER", "TEACHES", "TEENAGE", "TELECOM", "TELLING", "TENSION", "TERRACE", "TERRAIN", "TESTING", "TEXTILE", "TEXTURE", "THEATER", "THEATRE", "THEOREM", "THERAPY", "THEREBY", "THEREOF", "THERMAL", "THOMSON", "THOUGHT", "THREADS", "THREATS", "THROUGH", "THUNDER", "TICKETS", "TIFFANY", "TIMOTHY", "TOBACCO", "TODDLER", "TONIGHT", "TOOLBAR", "TOOLBOX", "TOOLKIT", "TOPLESS", "TORONTO", "TORTURE", "TOSHIBA", "TOTALLY", "TOUCHED", "TOURING", "TOURISM", "TOURIST", "TOWARDS", "TRACKED", "TRACKER", "TRACTOR", "TRADING", "TRAFFIC", "TRAGEDY", "TRAILER", "TRAINED", "TRAINER", "TRANSIT", "TRAVELS", "TREATED", "TRIBUNE", "TRIBUTE", "TRIGGER", "TRINITY", "TRIUMPH", "TROUBLE", "TRUSTED", "TRUSTEE", "TSUNAMI", "TUESDAY", "TUITION", "TUNISIA", "TURKISH", "TURNING", "TWISTED", "TYPICAL", "UKRAINE", "UNIFIED", "UNIFORM", "UNKNOWN", "UNUSUAL", "UPDATED", "UPDATES", "UPGRADE", "UPSKIRT", "URUGUAY", "USUALLY", "UTILITY", "UTILIZE", "VACCINE", "VAMPIRE", "VANILLA", "VARIETY", "VARIOUS", "VARYING", "VATICAN", "VEHICLE", "VENDORS", "VENTURE", "VERIZON", "VERMONT", "VERSION", "VESSELS", "VETERAN", "VICTIMS", "VICTORY", "VIETNAM", "VIEWERS", "VIEWING", "VILLAGE", "VINCENT", "VINTAGE", "VIOLENT", "VIRTUAL", "VIRUSES", "VISIBLE", "VISITED", "VISITOR", "VITAMIN", "VOLTAGE", "VOLUMES", "WAITING", "WALKING", "WALLACE", "WANTING", "WARMING", "WARNING", "WARRANT", "WARRIOR", "WASHING", "WATCHED", "WATCHES", "WEAPONS", "WEARING", "WEATHER", "WEBCAMS", "WEBCAST", "WEBLOGS", "WEBPAGE", "WEBSITE", "WEBSTER", "WEDDING", "WEEKEND", "WEIGHTS", "WELCOME", "WELDING", "WELFARE", "WESTERN", "WHEREAS", "WHETHER", "WICHITA", "WILLIAM", "WILLING", "WINDOWS", "WINDSOR", "WINNERS", "WINNING", "WINSTON", "WISHING", "WITHOUT", "WITNESS", "WORKERS", "WORKING", "WORKOUT", "WORRIED", "WORSHIP", "WRAPPED", "WRITERS", "WRITING", "WRITTEN", "WYOMING", "YOUNGER", "ZEALAND"]
```
For 10 characters, you'd be able to detect:
```
["ABORIGINAL", "ABSOLUTELY", "ABSORPTION", "ACCEPTABLE", "ACCEPTANCE", "ACCESSIBLE", "ACCOMPLISH", "ACCORDANCE", "ACCOUNTING", "ACCREDITED", "ACCURATELY", "ACDBENTITY", "ACTIVATION", "ACTIVITIES", "ADAPTATION", "ADDITIONAL", "ADDRESSING", "ADJUSTABLE", "ADJUSTMENT", "ADMISSIONS", "ADOLESCENT", "ADVANTAGES", "ADVENTURES", "ADVERTISER", "AFFILIATED", "AFFILIATES", "AFFORDABLE", "AFTERWARDS", "AGGRESSIVE", "AGREEMENTS", "ALEXANDRIA", "ALGORITHMS", "ALLOCATION", "AMBASSADOR", "AMENDMENTS", "ANALYTICAL", "ANNOTATION", "ANTARCTICA", "ANTIBODIES", "APARTMENTS", "APPARENTLY", "APPEARANCE", "APPLIANCES", "APPLICABLE", "APPLICANTS", "APPRECIATE", "APPROACHES", "ARCHITECTS", "ARTIFICIAL", "ASSESSMENT", "ASSIGNMENT", "ASSISTANCE", "ASSOCIATED", "ASSOCIATES", "ASSUMPTION", "ATMOSPHERE", "ATTACHMENT", "ATTEMPTING", "ATTENDANCE", "ATTRACTION", "ATTRACTIVE", "ATTRIBUTES", "AUSTRALIAN", "AUTHORIZED", "AUTOMATION", "AUTOMOBILE", "AUTOMOTIVE", "AZERBAIJAN", "BACKGROUND", "BANGLADESH", "BANKRUPTCY", "BASKETBALL", "BEASTALITY", "BEHAVIORAL", "BENEFICIAL", "BESTIALITY", "BIOLOGICAL", "BIRMINGHAM", "BLACKBERRY", "BOUNDARIES", "BRITANNICA", "BURLINGTON", "BUSINESSES", "CALCULATED", "CALCULATOR", "CALIFORNIA", "CAMCORDERS", "CANDIDATES", "CAPABILITY", "CARTRIDGES", "CATEGORIES", "CHALLENGED", "CHALLENGES", "CHANCELLOR", "CHARACTERS", "CHARITABLE", "CHARLESTON", "CHRISTIANS", "CHRONICLES", "CIGARETTES", "CINCINNATI", "CITYSEARCH", "CLASSIFIED", "COLLEAGUES", "COLLECTING", "COLLECTION", "COLLECTIVE", "COLLECTORS", "COLUMNISTS", "COMMENTARY", "COMMERCIAL", "COMMISSION", "COMMITMENT", "COMMITTEES", "COMPARABLE", "COMPARISON", "COMPATIBLE", "COMPLAINTS", "COMPLEMENT", "COMPLETELY", "COMPLETING", "COMPLETION", "COMPLEXITY", "COMPLIANCE", "COMPONENTS", "COMPRESSED", "COMPROMISE", "CONCEPTUAL", "CONCERNING", "CONCLUSION", "CONDITIONS", "CONDUCTING", "CONFERENCE", "CONFIDENCE", "CONFIGURED", "CONNECTING", "CONNECTION", "CONNECTORS", "CONSIDERED", "CONSISTENT", "CONSISTING", "CONSORTIUM", "CONSPIRACY", "CONSTANTLY", "CONSTITUTE", "CONSTRAINT", "CONSULTANT", "CONSULTING", "CONTACTING", "CONTAINERS", "CONTAINING", "CONTINUING", "CONTINUITY", "CONTINUOUS", "CONTRACTOR", "CONTRIBUTE", "CONTROLLED", "CONTROLLER", "CONVENIENT", "CONVENTION", "CONVERSION", "CONVICTION", "COORDINATE", "COPYRIGHTS", "CORRECTION", "CORRUPTION", "COUNSELING", "CREATIVITY", "CUMULATIVE", "CURRENCIES", "CURRICULUM", "CUSTOMIZED", "DECORATING", "DECORATIVE", "DEFINITELY", "DEFINITION", "DELEGATION", "DELIVERING", "DEMOCRATIC", "DEPARTMENT", "DEPENDENCE", "DEPLOYMENT", "DEPRESSION", "DESCENDING", "DESCRIBING", "DESIGNATED", "DETERMINED", "DETERMINES", "DEVELOPERS", "DEVELOPING", "DIAGNOSTIC", "DICTIONARY", "DIFFERENCE", "DIFFICULTY", "DIMENSIONS", "DIRECTIONS", "DISABILITY", "DISCIPLINE", "DISCLAIMER", "DISCLOSURE", "DISCOUNTED", "DISCOVERED", "DISCRETION", "DISCUSSING", "DISCUSSION", "DISPATCHED", "DISPLAYING", "DISTRIBUTE", "DOCUMENTED", "DOWNLOADED", "EARTHQUAKE", "ECOLOGICAL", "EDITORIALS", "EFFICIENCY", "ELECTRICAL", "ELECTRONIC", "ELEMENTARY", "EMPLOYMENT", "ENCOURAGED", "ENCOURAGES", "ENCRYPTION", "ENDANGERED", "ENGAGEMENT", "ENROLLMENT", "ENTERPRISE", "EQUIVALENT", "ESPECIALLY", "ESSENTIALS", "ESTIMATION", "EVALUATING", "EVALUATION", "EVENTUALLY", "EVERYTHING", "EVERYWHERE", "EXCELLENCE", "EXCEPTIONS", "EXCITEMENT", "EXECUTIVES", "EXHIBITION", "EXPERIENCE", "EXPERIMENT", "EXPIRATION", "EXPLAINING", "EXPLICITLY", "EXPRESSION", "EXTENSIONS", "EXTRACTION", "FACILITATE", "FACILITIES", "FAVOURITES", "FEDERATION", "FELLOWSHIP", "FORMATTING", "FORWARDING", "FOUNDATION", "FRAGRANCES", "FREQUENTLY", "FRIENDSHIP", "FUNCTIONAL", "GENERATING", "GENERATION", "GENERATORS", "GEOGRAPHIC", "GEOLOGICAL", "GIRLFRIEND", "GOVERNANCE", "GOVERNMENT", "GRADUATION", "GREENHOUSE", "GREENSBORO", "GUARANTEED", "GUARANTEES", "GUIDELINES", "HARASSMENT", "HEADPHONES", "HEALTHCARE", "HELICOPTER", "HIGHLIGHTS", "HISTORICAL", "HORIZONTAL", "HOUSEHOLDS", "HOUSEWARES", "HOUSEWIVES", "HUMANITIES", "HUNTINGTON", "HYPOTHESIS", "IDENTIFIED", "IDENTIFIER", "IDENTIFIES", "IMMIGRANTS", "IMMUNOLOGY", "IMPORTANCE", "IMPOSSIBLE", "IMPRESSION", "IMPRESSIVE", "INCENTIVES", "INCOMPLETE", "INCREASING", "INCREDIBLE", "INDICATING", "INDICATION", "INDICATORS", "INDIGENOUS", "INDIVIDUAL", "INDONESIAN", "INDUSTRIAL", "INDUSTRIES", "INFECTIONS", "INFECTIOUS", "INFLUENCED", "INFLUENCES", "INITIATIVE", "INNOVATION", "INNOVATIVE", "INSPECTION", "INSTALLING", "INSTITUTES", "INSTRUCTOR", "INSTRUMENT", "INSULATION", "INTEGRATED", "INTERESTED", "INTERFACES", "INTERNSHIP", "INTERSTATE", "INTERVIEWS", "INTRODUCED", "INTRODUCES", "INVESTMENT", "INVITATION", "IRRIGATION", "JAVASCRIPT", "JOURNALISM", "JOURNALIST", "KAZAKHSTAN", "KILOMETERS", "LABORATORY", "LANDSCAPES", "LAUDERDALE", "LEADERSHIP", "LEGITIMATE", "LIKELIHOOD", "LIMITATION", "LIMOUSINES", "LITERATURE", "LITIGATION", "LOUISVILLE", "LUXEMBOURG", "MACROMEDIA", "MADAGASCAR", "MAINSTREAM", "MAINTAINED", "MANAGEMENT", "MANCHESTER", "MASTERCARD", "MEANINGFUL", "MECHANICAL", "MECHANISMS", "MEDICATION", "MEDITATION", "MEMBERSHIP", "METABOLISM", "MICROPHONE", "MILFHUNTER", "MILLENNIUM", "MINISTRIES", "MITSUBISHI", "MODERATORS", "MONITORING", "MONTGOMERY", "MOTIVATION", "MOTORCYCLE", "MOZAMBIQUE", "MULTIMEDIA", "MYSTERIOUS", "NATIONALLY", "NATIONWIDE", "NAVIGATION", "NETWORKING", "NEWSLETTER", "NEWSPAPERS", "NOMINATION", "NOTTINGHAM", "OBITUARIES", "OBJECTIVES", "OBLIGATION", "OCCASIONAL", "OCCUPATION", "OCCURRENCE", "OFFICIALLY", "OPERATIONS", "OPPOSITION", "ORGANIZING", "ORIGINALLY", "PAPERBACKS", "PARAGRAPHS", "PARAMETERS", "PARLIAMENT", "PARTICULAR", "PASSENGERS", "PERCENTAGE", "PERCEPTION", "PERFORMING", "PERIPHERAL", "PERMISSION", "PERSISTENT", "PERSONALLY", "PETERSBURG", "PHARMACIES", "PHENOMENON", "PHILOSOPHY", "PHOTOGRAPH", "PHYSICALLY", "PHYSICIANS", "PHYSIOLOGY", "PITTSBURGH", "POLYPHONIC", "POPULARITY", "POPULATION", "PORTSMOUTH", "PORTUGUESE", "POSSESSION", "POSTPOSTED", "POWERPOINT", "PREDICTION", "PREFERENCE", "PRESCRIBED", "PRESENTING", "PREVENTING", "PREVENTION", "PREVIOUSLY", "PRINCIPLES", "PRIORITIES", "PRIVILEGES", "PROCEDURES", "PROCEEDING", "PROCESSING", "PROCESSORS", "PRODUCTION", "PRODUCTIVE", "PROFESSION", "PROGRAMMER", "PROGRAMMES", "PROHIBITED", "PROJECTION", "PROJECTORS", "PROMOTIONS", "PROPERTIES", "PROPORTION", "PROTECTING", "PROTECTION", "PROTECTIVE", "PROVIDENCE", "PROVINCIAL", "PROVISIONS", "PSYCHIATRY", "PSYCHOLOGY", "PUBLISHERS", "PUBLISHING", "PUNISHMENT", "PURCHASING", "QUALIFYING", "QUANTITIES", "QUEENSLAND", "QUOTATIONS", "REASONABLE", "REASONABLY", "RECIPIENTS", "RECOGNISED", "RECOGNIZED", "RECOMMENDS", "RECORDINGS", "RECREATION", "RECRUITING", "REDUCTIONS", "REFERENCED", "REFERENCES", "REFLECTION", "REGARDLESS", "REGISTERED", "REGRESSION", "REGULATION", "REGULATORY", "RELATIVELY", "RELAXATION", "RELOCATION", "REMARKABLE", "REMEMBERED", "REPOSITORY", "REPRESENTS", "REPRODUCED", "REPUBLICAN", "REPUTATION", "REQUESTING", "RESEARCHER", "RESISTANCE", "RESOLUTION", "RESPECTIVE", "RESPONDENT", "RESPONDING", "RESTAURANT", "RESTRICTED", "RETIREMENT", "REVELATION", "REVOLUTION", "RICHARDSON", "SACRAMENTO", "SCHEDULING", "SCIENTIFIC", "SCIENTISTS", "SCREENSHOT", "SECURITIES", "SELECTIONS", "SEPARATELY", "SEPARATION", "SETTLEMENT", "SIGNATURES", "SIMPLIFIED", "SIMULATION", "SITUATIONS", "SOUNDTRACK", "SPECIALIST", "STATEMENTS", "STATIONERY", "STATISTICS", "STRATEGIES", "STRENGTHEN", "STRUCTURAL", "STRUCTURED", "STRUCTURES", "SUBJECTIVE", "SUBMISSION", "SUBMITTING", "SUBSCRIBER", "SUBSECTION", "SUBSEQUENT", "SUBSIDIARY", "SUBSTANCES", "SUBSTITUTE", "SUCCESSFUL", "SUFFICIENT", "SUGGESTING", "SUGGESTION", "SUNGLASSES", "SUPERVISOR", "SUPPLEMENT", "SUPPORTERS", "SUPPORTING", "SURPRISING", "SURROUNDED", "SUSPENSION", "SYSTEMATIC", "TECHNICIAN", "TECHNIQUES", "TECHNOLOGY", "TELEVISION", "TERRORISTS", "THEMSELVES", "THEREAFTER", "THOROUGHLY", "THREATENED", "THROUGHOUT", "THUMBNAILS", "THUMBZILLA", "TOURNAMENT", "TRACKBACKS", "TRADEMARKS", "TRADITIONS", "TRANSCRIPT", "TRANSEXUAL", "TRANSITION", "TRANSLATED", "TRANSLATOR", "TRAVELLING", "TREATMENTS", "TREMENDOUS", "ULTIMATELY", "UNDERLYING", "UNDERSTAND", "UNDERSTOOD", "UNDERTAKEN", "UNEXPECTED", "UNIVERSITY", "UZBEKISTAN", "VALIDATION", "VARIATIONS", "VEGETABLES", "VEGETARIAN", "VEGETATION", "VETERINARY", "VIETNAMESE", "VIOLATIONS", "VISIBILITY", "VOCABULARY", "VOCATIONAL", "VOLKSWAGEN", "VOLLEYBALL", "VOLUNTEERS", "VULNERABLE", "WALLPAPERS", "WARRANTIES", "WASHINGTON", "WATERPROOF", "WEBMASTERS", "WELLINGTON", "WIDESCREEN", "WIDESPREAD", "WILDERNESS", "WITHDRAWAL", "YUGOSLAVIA"]
```
It works for other lengths too, but I thought I'd specifically mention the ones within the spec that it will indeed work for. For example 227 results in:
```
["ABS", "BAR", "BBS", "CAP", "CAR", "CAS", "CBS"]
```
If the winner of this challenge is being chosen by shortest code, I can make this 140 bytes shorter if needed.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 217 bytes
```
n=>n.Where(c=>c>47&c<58).Select(c=>", , abc def ghi jkl mno pqrs tuv wxyz".Split()[c-48]).Aggregate(new[]{""},(a,b)=>a.SelectMany(c=>b.Select(d=>c+d)).ToArray()).Where(x=>File.ReadAllText("a.txt").Contains($@"
{x}
"))
```
Expects the dictionary in a file named `a.txt`.
[Try it online!](https://tio.run/##NY9dS8MwGIXv@ytCEEkwy1DbWdgaLOLAC0HcwIuxizR920WzdKapazf222uH8@7wHDgfqh6pWvfzxqpZ7Z22JXt5ts0WnMwMXJAQRdLbRFj@sQEHRCVCifDhWs2imPIFGFD@DDFDDMlMoRwKVG40@vwyaGsrtPt2NfLND9q33QHzxc5oT@hKjcJ4TXlalg5K6YFY2K/WR4xPjEiW0UTIS/qrtN25Iftvy4cJNzmlfFmlzsmODPJvXJuIuTbA30HmqTFLaD3BkvvWY8qfKuultjW5esTBsT0FmNJ@GozHb8NPTwqCbydxGIWT6O5@sKb9Lw "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [VDM-SL](https://raw.githubusercontent.com/overturetool/documentation/master/documentation/VDM10LangMan/VDM10_lang_man.pdf), ~~313~~ ~~395~~ ~~385~~ ~~289~~ 278 bytes
```
f(i)==let m={'2'|->"abc",'3'|->"def",'4'|->"ghi",'5'|->"jkl",'6'|->"mno",'7'|->"pqrs",'8'|->"tuv",'9'|->"wxyz"},d=IO`freadval[set of ?],q=[i(p)|p in set inds i&i(p) in set dom m]in let r in set d("f").#2 be st forall x in set inds q&len(q)=len(r)and r(x)in set elems m(q(x))in r
```
Turns out IO is easier than I thought!
Still expensive because of building the map (I'm sure there'll be a good map comprehension for it I've just not thought of it yet) and could save further bytes if the string was guaranteed to only contain values in the domain of the map
### Explanation:
```
f(i)==
let m=..., /* m is a map of char to seq of char */
d=IO`freadval[set of ?] /* d is the file read function that will read a set of something */
q=[i(p)|p in set inds i&i(p) in set dom m] /* q is a sequence comprehension defined by
take the values in i where i is in the domain
of our map m */
let r in set d("f").#2 /* let r be a value in my dictionary of words (read from the file f) */
be st /* such that */
forall x in set inds q&len(q)=len(r) /* the length of q and r are the same */
and r(x)in set elems m(q(x)) /* for every char in q the char in
r at that position is in the range of the
map for that char in q */
in r /* return r*/
```
] |
[Question]
[
Near the middle of the semester in chemistry, we get problems like:
>
> Convert 1.283850057 to Scientific Notation
>
>
>
and
>
> Convert 3.583✕106 to Standard Notation
>
>
>
This is just stupid busy work for people who already know how to do this. So…
## The Challenge
Given an input in any reasonable, convenient format, in either standard notation or scientific notation, output the same number in the other notation. However, note that `e` will not be accepted in place of `*10^`, as this gives a significant advantage to languages with builtins with `e`.
***If not otherwise specified,*** standard notation will take this format:
```
x (an integer)
xxxxxxxxxx (a large integer with no more than 10 digits)
x.xxxx (a float)
x.xxxxxxxxxx (a float with no more than 10 x's after the decimal point)
```
While scientific notation will take this format:
```
x*10^x
x.zzzz*10^z (x will be >= 1)
x*10^-x
x.zz*10^-xx (x will be >= 1)
```
## I/O
Input will never contain more than 10 leading+10 trailing digits, and you may decide how to deal with trailing zeroes after the decimal point. The exponent will never be so large as to max out your language's allowance for large numbers. You should only need to handle up to about 1010.
```
input => output
---scientific to standard---
4.5*10^7 => 45000000
1*10^0 => 1
8.9*10^-2 => 0.089
1.0001*10^5 => 100010
9.999999*10^9 => 9999999000
4.00038*10^2 => 400.038
---standard to scientific---
7354 = 7.354*10^3
385.43 => 3.8543*10^2
0.32 = 3.2*10^-1
0.00044 => 4.4*10^-4
0.053 => 5.3*10^-2
```
As always, standard loopholes are disallowed. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest bytes wins!
[Answer]
# [R](https://www.r-project.org/), 70 bytes
```
function(s)sub("e","*10^",format(eval(parse(t=s)),sc=!grepl("\\^",s)))
```
[Try it online!](https://tio.run/##PctBCsIwEIXhvafQWc1ILBObUBf2JkWIJRGhtiWTev2YUHD5f7wXczjeLzls85jey4xCsj0RPCg4a36ACkv8uIT@6yZcXRSPqRciJWN/ekW/TgjDUHbFKAcE09h67IAOpXTDzLqC3cFUaG9VrrtwFWP@YVug/AM "R – Try It Online")
An anonymous function. Takes input as a string and outputs as a string.
This function evaluates the string `eval(parse(t=s))`, then `format`s it, with the flag `scientific` set to whether the string contains a `^` or not. Then it replaces `e` with `*10^` to match the right output spec.
[Answer]
# [Python 3](https://docs.python.org/3/), 100 bytes
```
lambda a:eval(a.replace("*10^","e+"))if type(a)==str else re.sub("0*e\+?0*","*10^","%e"%a)
import re
```
[Try it online!](https://tio.run/##NcxRCsIwEEXR/64iDBQmqYQRKwUhuJEiTHWKgbQNaRS6@lhBfx/n3bjl5zKfyuj6EngaHqz4Im8OyDZJDHwXBHOkGxxAGtDajypvUZC1c2tOSsIqKoldXwMCGembK5kd/z61QM268lNcUt5dicnPGUeE1p6/ptub1X8kS0Rtq3X5AA "Python 3 – Try It Online")
[Answer]
## JavaScript (ES6), ~~83~~ 80 bytes
```
a=>(r=a.split(N='*10^'))[1]?+r.join`e`+'':(+a).toExponential().replace(/e\+?/,N)
```
An anonymous function. Takes input as a string and outputs as a string.
[Answer]
# [Python 2](https://docs.python.org/2/), 87 bytes
```
lambda s:eval(s.replace('^','**'))if'^'in`s`else re.sub('e\+?','*10^','%e'%s)
import re
```
[Try it online!](https://tio.run/##VZDRasMgFIbv8xTCKCbdejA5SnTQ7UXKaLoaFkjTELPBnj7zmOkyr8Tv@/@jjt/zx32olvZ4Wvrmdrk2zD3br6bPHUx27Jt3m/M3/sT3e14UXev33XB2Z9s7yyYL7vOSc3t6fCWlFGTuLN@5Iutu432avbOMUzfMrM25BEVOzQv2wI4vTCoRVpaMkriIvPwDGgyhQxWZAKHNJgi@J6RVStPJptuACYskE6X1yPy7hKQu1OSlcVL4gaizZNWoZGCsBr8lGRNErUDibxRBK4mhLQkCsFrTCFV4WLlhfryUcTCE7oPcchW7FeD6LcsP "Python 2 – Try It Online")
[Answer]
# Excel VBA, 80 Bytes
Anonymous VBE immediate window function that takes input from cell `[A1]` and outputs to the VBE immediate window.
```
v=Evaluate("="&[A1]):e=Int(Log(v)/2.3):?IIf(Instr([A1],"^"),v,v*10^-e &"*10^"&e)
'' Or
v=Evaluate("="&[A1]):e=Int(Log(v)/2.3):?IIf(Instr([A1],"^"),v,v/(10^e)&"*10^"&e)
'' Or
[B1]="="&[A1]:v=[B1]:e=Int(Log(v)/2.3):?IIf(Instr([A1],"^"),v,v*10^-e &"*10^"&e)
'' Or
[B1]="="&[A1]:e=[Int(Log10(B1))]:?IIf(Instr([A1],"^"),[B1],[B1]/(10^e)&"*10^"&e)
```
] |
[Question]
[
In *Applied Cryptography* by Bruce Schneier (which I have been reading quite a lot recently), a protocol for splitting secrets is discussed. Here is a brief description:
>
> 1. Trent generates a random byte string, *R*, the same length as the message, *M*.
> 2. Trent XORS *M* with *R* to make *S*.
> 3. He gives *R* to Alice and *S* to Bob.
>
>
>
---
Your task is to, given an input, split the input into two output files or print the split secret to STDOUT. One output/part of output should contain the random string; the other should contain the original input XOR'd with the random string. Input and output may be to/from files or to/from STDIN/STDOUT. Outputting to STDERR is also allowed.
There are a few restrictions, however:
1. Your program must take 1 input (1 input filename & 2 outputs if doing file I/O), and output the random string and the original string XOR'd with that random string into the other.
2. Your program must be cryptographically secure. All random number generators must be cryptographically secure. For example, `/dev/random` is fine, but the Mersenne Twister (usually `randint(number,number)` is *not*. Any random number generator must be *explicitly* cryptographically secure.
* If you want to know anything more about what "cryptographically secure" means, check [here](https://crypto.stackexchange.com/questions/39186/what-does-it-mean-for-a-random-number-generator-to-be-cryptographically-secure).
3. Standard rules and loopholes apply.
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes will win.
May the best coder prosper...
[Answer]
# Bash + coreutils + openssl, 91 bytes
```
0000000: 63 3d 22 6f 70 65 6e 73 73 6c 20 65 6e 63 20 2d c="openssl enc -
0000010: 61 65 73 2d 31 32 38 2d 63 74 72 20 2d 4b 20 24 aes-128-ctr -K $
0000020: 28 78 78 64 20 2d 70 73 20 2d 6c 20 31 36 20 2f (xxd -ps -l 16 /
0000030: 64 65 76 2f 72 61 6e 64 6f 6d 29 20 2d 69 76 20 dev/random) -iv
0000040: 30 22 0a 24 63 3c 24 31 0a 74 72 20 01 2d ff 20 0".$c<$1.tr .-.
0000050: 5c 30 3c 24 31 7c 24 63 3e 26 32 \0<$1|$c>&2
```
Takes a filename as argument and splits the secret to STDOUT and STDERR. Input and output are in raw binary format.
### Sample run
```
$ cat input.txt
Bruce
$ bash split input.txt 2> >(xxd -ps >& 2) | xxd -ps
d5725c26aa3b
97002945cf31
$ printf %02x $[0xd5725c26aa3b ^ 0x97002945cf31] | xxd -r -ps
Bruce
```
[Answer]
# JavaScript (ES6), ~~77~~ 76 bytes
```
let f =
M=>[R=crypto.getRandomValues(new Uint8Array(M.length)),M.map((c,i)=>c^R[i])]
let g = m => console.log(f([...m].map(c=>c.charCodeAt())).map(x=>`[${x.join(", ")}]`).join(",\n"))
g("Secret message")
g("\0\0\0\0\0\0\0\0")
```
I think this is what's being asked for. It takes in an array of bytes and outputs `[random bytes, XORed message]`. I'm assuming that `crypto.getRandomValues` is cryptographically secure (else I don't know why it exists), and that `Math.random` isn't. Otherwise I could save 28 bytes.
[Answer]
## Haskell, 178 Bytes
```
import System.Entropy
import qualified Data.ByteString as B
import Data.Bits
main|f<-B.init=do b<-B.getLine;r<-getEntropy.B.length$f b;B.putStrLn.pack.B.zipWith xor r$f b;print r
```
Unfortunately, I can't quite think of a way to do this without three big imports.
More readable version:
```
main=do b<-B.getLine
r<-getEntropy . B.length $ B.init b
B.putStrLn . pack . B.zipWith xor r $ f b
print r
```
Basically, it reads a line from stdin, makes a random number with that length and then prints the xor'd version and the random number
[Answer]
# Ruby, ~~88~~ 76 bytes
Edit: I guess the outputs don't have to be *strings* strings?
```
m=gets.bytes
p r=`head -c#{m.size}</dev/random`.bytes,m.zip(r).map{|a,b|a^b}
```
[Answer]
# Python 3, 85 bytes
```
import os
s=input()
k=os.urandom(len(s))
print(list(k),[j^ord(i)for i,j in zip(k,s)])
```
The only part that might need explaining is the list comprehension (`[j^ord...]`)
It combines the input with the random key (`zip([1,2,3],[4,5,6])==[(1,4),(2,5),(3,6)]`)
and xors them together.
[Answer]
# Java, 292 bytes
Not sure if 100% correct
```
enum e{;public static void main(String[]a){java.security.SecureRandom r=new java.security.SecureRandom();byte[]b=a[0].getBytes(),c=new byte[b.length],d=new byte[c.length];int i=-1;r.nextBytes(c);while(++i<b.length)d[i]=(byte)(b[i]^c[i]);System.out.println(new String(c)+"\n"+new String(d));}}
```
Takes the input as first argument, outputs key and XOR'ed string to STDOUT separated by newlines.
Ungolfed with comments:
```
enum e {
;
public static void main(String[] a) {
java.security.SecureRandom r = new java.security.SecureRandom(); // Secure random
byte[] b = a[0].getBytes(), c = new byte[b.length], d = new byte[c.length]; // 3 arrays
int i = -1; // Index
r.nextBytes(c); // Key
while (++i < b.length) d[i] = (byte) (b[i] ^ c[i]); // XOR the input with key
System.out.println(new String(c) + "\n" + new String(d)); // Output key and XORed string
}
}
```
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/73739/edit).
Closed 7 years ago.
[Improve this question](/posts/73739/edit)
### [The Inspiration](http://ubaydinoyatov.github.io/clockclock/)
## The Challenge
I'm tired of seeing the same old-same old clock in my top-right-hand corner of my screen. It's time for a new clock. While the clock clock sated my lack of interesting clock for a little while, it simply will do no longer. Your job: make a better, more interesting clock.
## The Rules
Make a clock, provided that:
* Output is either graphical or directed to STDOUT or equivalent.
* You do not use ASCII numbers as the output (don't just print out the time).
* It must run continuously until stopped by closing the window or by CTRL-C or equivalent.
* It may NOT print out an infinite amount of lines (if using STDOUT).
* It must be human-readable, in any way.
* It must be accurate to 1/10th of a second to the system clock, and update with any changes to the system clock (so if I change system settings, it will update to my system clock).
* Your program cannot exceed 1024 bytes.
## Pop-con Objectives
The voters should keep in mind the following:
* ### Creativity should be valued above all.
* The better the explanation, the greater the up-votes.
[Answer]
## Bash
```
watch -tn.1 date +%T\|figlet
```
Yeah, yeah, I know it's not golf (28 bytes!), but I do like the minimalism:
[](https://i.stack.imgur.com/ffhrJ.gif)
`watch` is a tool provided by the `procps` package that repeatedly runs a command every <specified interval of time> and outputs the updated results. (An example of where this is handy: `watch -n.1 ls -lh ~/downloads/foo` to view the progress of a download.)
The `-t` flag for `watch` represents `--no-title`, as otherwise it would look like this:
[](https://i.stack.imgur.com/c90XL.png)
The `-n 0.1` flag simply means "update every 0.1 seconds."
Then comes the command that we're `watch`ing over. First, `date +%T` prints the date in the desired format (`date` comes from coreutils):
```
%T time; same as %H:%M:%S
```
Then this is piped to `figlet` (unsurprisingly provided by the `figlet` package), which converts STDIN to ASCII art.
```
(| | _ _ _, _| _
| | / \_| | / / | /|/| / | / \_
\/|/\_/ \/|_/ \__/\/|_/ | |_/ \/|_/\_/
(|
_/ _/ _/
_/_/_/ _/ _/ _/_/_/ _/_/ _/ _/_/ _/_/_/_/ _/_/_/
_/ _/ _/ _/ _/_/ _/ _/ _/_/ _/ _/_/
_/ _/ _/ _/ _/_/ _/ _/ _/ _/ _/_/
_/_/_/ _/ _/ _/_/_/ _/_/ _/ _/_/ _/_/_/
_| | | | _)
_ \ | __ \ _ \ _` | __| __| __ \ | __ \ _` | __|
( | __| | | __/ ( | | | | | | | | | ( |\__ \
\___/ _| _| _|\___|\__,_|\__| \__|_| |_|_|_| _|\__, |____/
|___/
_
o_|_|_ _|_|_ _ |_o _ | __|_ ._ .__ _ .__.._ _
\/\/| |_| | |_| |(/_ | |(_||(/_|_ |_)|(_)(_||(_|| | |o
_| | _|
```
] |
[Question]
[
ROT-128 is a variant of ROT-13, where instead of cycling through the 26 letters, you cycle through the 256 possible bytes. Your task is to create a program that outputs the ROT-128 of its own source. The outputted program *must* also be a valid program and output the original program.
## Scoring
This is code golf, so least number of bytes wins! Ties are broken by number of votes.
[Answer]
# GolfScript, ~~64~~ 48 bytes
```
{ºî»`'.~'+.{128^}%\](}.~û:n;৮þ§«®û±²¸Þý¥Üݨý®þ
```
*Thanks to @MartinBüttner for golfing off 16 bytes!*
[Try it online!](http://golfscript.tryitonline.net/#code=e8K6w67Cu2AnLn4nKy57MTI4Xn0lXF0ofS5-w7s6bjvDoMKnwq7DvsKnwqvCrsO7wrHCssK4w57DvcKlw5zDncKow73CrsO-&input=)
### Output
```
û:n;৮þ§«®û±²¸Þý¥Üݨý®þ{ºî»`'.~'+.{128^}%\](}.~
```
[Try it online!](http://golfscript.tryitonline.net/#code=w7s6bjvDoMKnwq7DvsKnwqvCrsO7wrHCssK4w57DvcKlw5zDncKow73CrsO-e8K6w67Cu2AnLn4nKy57MTI4Xn0lXF0ofS5-&input=)
### Verification
```
$ LANG=en_US
$ cat quine.gs
{ºî»`'.~'+.{128^}%\](}.~û:n;৮þ§«®û±²¸Þý¥Üݨý®þ
$ golfscript quine.gs
û:n;৮þ§«®û±²¸Þý¥Üݨý®þ{ºî»`'.~'+.{128^}%\](}.~
$ golfscript quine.gs | golfscript
{ºî»`'.~'+.{128^}%\](}.~û:n;৮þ§«®û±²¸Þý¥Üݨý®þ
$ diff -s quine.gs <(golfscript quine.gs | golfscript)
Files quine.gs and /dev/fd/63 are identical
```
[Answer]
# Self-Modifying Brainf\*ck, 74 bytes
```
<[<]>[<++++[>++++<-]>[<++++++++>-].>]
```
(The second half of the program is the same as above, except in ROT-128)
Just thought I would post this as a) a kickstart for ideas, and b) showing that it is possible to do without an insanely large program.
] |
[Question]
[
Let's say you've got a table of data:
```
meter_id date 0000 0600 1200 1800
0 030915 10 20 30 40
1 030915 15 7 49 2
```
where the last four columns are meter readings at different times. You want to output
```
meter_id date time reading
0 030915 0000 10
0 030915 0600 20
```
etc.
Your input and output will *not* have headers, unlike in this example. The set of columns you'll transpose will be provided as numeric arguments to your program, from 1 onwards. Input is stdin and output is stdout.
So here's an example of it actually being used.
```
$ ./tpose 3 4 5 6
```
Stdin:
```
0 030915 10 20 30 40
1 030915 15 7 49 2
```
Stdout:
```
0 030915 3 10
0 030915 4 20
0 030915 5 30
0 030915 6 40
1 030915 3 15
1 030915 4 7
1 030915 5 49
1 030915 6 2
```
The third column contains values from 3 to 6. This is because the reading is from columns 3 to 6 from the input table.
Happy golfing.
[Answer]
# kdb k, 101 bytes
```
1@"\n"/:{"\n"/:{" "/:(r@&{~#&x=a}'!#r),(,$1+a@x),,c@x}'!#c::(r::" "\:x)@a::-1+.:'.z.x}'-1_"\n"\:0::0;
```
**Me:** *(reads the word "transpose" in the title)* K will be perfect for this! It'll kick everything else's hind!
*20 minutes and 101 bytes later*
**Me:** Idiot.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~88~~ 84 bytes
Input is tab-separated. Annoyingly, Ruby `gets` pulls from files whose names match those from `ARGV`, but those don't exist so the program errors out. To work around this, I have to use `STDIN.gets` to get the actual correct input.
-4 bytes by remembering that I don't actually need to use `scan` since I'm only matching the pattern once per line anyways, so `=~` for a single regex match saves bytes.
```
($_=~/(\d+ \w+ )(.*)/;i=-1;puts$2.split.map{|s|"#$1#{$*[i+=1]} "+s})while STDIN.gets
```
[Try it online!](https://tio.run/##PchBC4IwFADg8@tXhO4wHc23uRUi3rp06VK3jCiSGhhIm0io/fXXre/4vfvbh4izS/XNeH0XUA8CEi7TJCtdtVJl1wfPtPRd64J8Xbtx8lMUMxWPLD05UanzDJHwczI8XdssD8ftbi8fTfBECJhjoSwoBI2QIxhcqH9a2IApQFNOhiytfw "Ruby – Try It Online")
[Answer]
# Perl 5, 87 bytes
```
perl -E'while(<STDIN>){@f=(0,split);@i=0..$#f,@i[@ARGV]=0;say"@f[grep$_,@i] $_ $f[$_]"for@ARGV}'
```
[Answer]
# Haskell (195 bytes)
```
import System.Environment
main=do s<-getArgs>>=return.map(\a->read a-1);interact$unlines.map unwords.t s.map words.lines
t g r=[[a!!j|j<-[0..length a-1],not$j`elem`g]++show(j+1):[a!!j]|a<-r,j<-g]
```
Ungolfed Haskell (398 bytes):
```
import System.Environment
import Prelude
main = do js <- getArgs >>= return . map (\a -> read a - 1)
interact $ unbr . (`tpose` js) . br
br = map words . lines
xs `excludingFrom` es = [xs !! j | j <- [0..length xs - 1], not $ j `elem` es]
tpose rows js = [row `excludingFrom` js ++ [show (j+1)] ++ [row !! j] | row <- rows, j <- js]
unbr = unlines . map (foldr1 $ \t a -> t++"\t"++a)
```
[Answer]
# [PHP](https://php.net/), 90 bytes
```
while($r=fgetcsv(STDIN,0,' '))foreach($argv as$a)if($a|0)echo"$r[0] $r[1] $a {$r[$a-1]}
";
```
Input and output with [single space delimiter](https://codegolf.stackexchange.com/questions/60185/transpose-columns-in-table/187363#comment144859_60185).
[Try it online!](https://tio.run/##PcixCsIwFIXhvU9xKYEmUOGmSStFxcXFxUU36RBC0hSEhlTqoD77NZPLx39ODJH2x5h9henhOEsHP7qnXVZ@vZ3OlxrrCioh/JycsYEzk8YVzMKMmHxeHxTOhrlk6Y4DZGXWwDsXMxs5fItyR4SACnvZgkRoEBSCxkL@zxa2oHtoSJGmlrof "PHP – Try It Online")
# [PHP](https://php.net/), 109 bytes
```
while($r=preg_split("/\s+/",fgets(STDIN),0,1))foreach($argv as$a)if($a|0)echo"$r[0]\t$r[1]\t$a\t{$r[$a-1]}
";
```
Or with I/O exactly as shown above, using fixed width columns.
[Try it online!](https://tio.run/##XYq9CsIwFIX3PkUJGRKs9Ma2SlFxcXFx0c0WCSVtCoWGJOigPvs1ASfP8J0fjtEGdwcT@NTjpBi1e2PVcHdmGj0jeeMWOcn6QXnHLtfj6cwzyATn/WyV7DSj0g6PVDoq@diH9gauOj0Tam/QNj6YiCYb/wqZyqVoPwnZIkL6ExRQiyoVcVhFFBElJOL/UYW8iUNZxy8WWGKF6y8 "PHP – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 56 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous prefix lambda. Takes column numbers for "transposition" as right argument and [prompts via stdin for filename](https://codegolf.stackexchange.com/questions/60185/transpose-columns-in-table#comment449337_60185) of table.
```
{(t[;⍵~⍨⍳≢⍉t]⌿⍨≢⍵),(⍪,⍨⍵⍴⍨≢),t[;⍵]⊣t←↑(∊∘⎕D⊆⊢)¨⊃⎕NGET⍞1}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/@vXlKQX5yqV1JRov6ob6pfQGjIo94Vj7qa1A0UDIwNLA1NFQwNFIwMFIwNFEwM1BXUDeHCpgrmCiaWCkbq/6s1SqKtH/VurQNp7d38qHPRo97OkthHPftBAiDeVk0djUe9q3TACrY@6t0CkdDUgWiMfdS1uORR24RHbRM1HnV0PeqYAXSLy6OutkddizQPAZ3TDHKbuyvQbfMMa/@DnQxS3ttnDJELDnIGkiEensFcXEAGUA6sRsFYwUTBVMHsP9yTAA "APL (Dyalog Unicode) – Try It Online")
`{`…`}` "dfn"; right argument (column numbers) is `⍵`:
`⍞1` prompt for file name from stdin and juxtapose with `1` (indicating that we want a list of strings)
`["tpose",1]`
`⎕NGET` **get** the **n**ative file's (content,encoding,newline)
`[["0 030915 10 20 30 40","1 030915 15 7 49 2"],"UTF-8-NOBOM",[10]]`
`⊃` pick the first of those (content)
`["0 030915 10 20 30 40","1 030915 15 7 49 2"]`
`(`…`)¨` apply the following tacit function to each line:
`∊` the characters that are members
`∘` of
`⎕D` the set of **d**igits
`[[1,0,1,1,1,1,1,1,0,1,1,0,1,1,0,1,1,0,1,1],[1,0,1,1,1,1,1,1,0,1,1,0,1,0,1,1,0,1]]`
`⊆` indicate the sub-partitions of
`⊢` the line
`[["0","030915","10","20","30","40"],["1","030915","15","7","49","2"]]`
`↑` up the rank by mixing the list (rank 1) of lists into a matrix (rank 2)
`[["0","030915","10","20","30","40"],`
`["1","030915","15","7" ,"49","2" ]]`
`t←` assign that to `t` (for **t**able)
`⊣` discard that in favour of
`t[;⍵]` all rows of the subset of columns of `t` enumerated in the argument
`[["10","20","30","40"],`
`["15","7" ,"49","2" ]]`
`,` ravel (flatten that)
`["10","20","30","40","15","7","49","2"]`
`(`…`)` apply the following tacit function to that:
`≢` the tally of elements
`8`
`⍵⍴⍨` use that to reshape the number of columns to be "transposed"
`[3,4,5,6,3,4,5,6]`
`,⍨` to that, append
`⍪` the table-fied (made into single-column table) argument (the "transposed" columns)
`[[3,"10"],`
`[4,"20"],`
`[5,"30"],`
`[6,"40"],`
`[3,"15"],`
`[4,"7" ],`
`[5,"49"],`
`[6,"2" ]]`
`(`…`),` prepend the following:
`≢⍵` the tally of columns to be "transposed"
`4`
…`⌿⍨` use that to vertically replicate the rows of…
`t[;`…`]` all rows of the following columns of the table:
`⍉t` transpose the table
`[["0" ,"1" ],`
`["030915","030915"],`
`["10" ,"15" ],`
`["20" ,"7" ],`
`["30" ,"49" ],`
`["40" ,"2" ]]`
`≢` the tally of rows
`6`
`⍳` **ɩ**ndices until that
`[1,2,3,4,5,6]`
`⍵~⍨` except the "transposed" column numbers
`[1,2]`
`[["0","030915"],`
`["1","030915"]]`
`[["0","030915"],`
`["0","030915"],`
`["0","030915"],`
`["0","030915"],`
`["1","030915"],`
`["1","030915"],`
`["1","030915"],`
`["1","030915"]]`
`[["0","030915",3,"10"],`
`["0","030915",4,"20"],`
`["0","030915",5,"30"],`
`["0","030915",6,"40"],`
`["1","030915",3,"15"],`
`["1","030915",4,"7" ],`
`["1","030915",5,"49"],`
`["1","030915",6,"2" ]]`
] |
[Question]
[
1. Your program must output atleast half of its sourcecode in reverse. Any single part of the sourcecode as long as it is one single block of neighbouring characters.
2. Your program should not take any input (from user, filename, network or anything).
3. The output has some additional constraints. The character position (first character is #1) on the output is either a fibonacci-sequence number (1, 1, 2, 3, 5, 8, 13, 21, ...) or not (4, 6, 7, 9, 10, 11, 12, ...), and this is the constraints:
* 3.1 Every third fibonacci-sequence number output position must be a letter (a-z|A-Z). Starting at fibonacci-sequence number #2 (output char|byte pos: 1, 5, 21, ...).
* 3.2 Every third fibonacci-sequence number output position must be a number (0-9). Starting at fibonacci-sequence number #3 (output char|byte pos: 2, 8, 34, ...).
* 3.3 Every third fibonacci-sequence number output position must be a symbol !(0-9|a-z|A-Z). Starting at fibonacci-sequence number #4 (output char|byte pos: 3, 13, 55, ...).
4. The output must contain exactly all of these three phrases in any place as long as the other rules is not broken (case sensitive): `Fibonacci is so QUINE!`, `3 is more than {4}`, `{'{"\}`
This is code-golf, shortest sourcecode in bytes wins! Good luck, have fun!
[Answer]
# Befunge '98, 91 characters
Was formerly 104, then 101. Saved another 10 chars by moving the "Fi...E!" sentence to output position 89 using `'E'` (instead of `' '` at 55), and moving the actual code into the space this opened up, with a slightly improved print loop.
```
"!ENIUQ os si iccanobiF"f6*>:;#-1,g0;#:_ "}\"f:4++"{'{",,0$,,,,@"}4{ naht erom si 30" b >0a
```
produces the following output (fibonacci positions marked):
```
a0> b "03 is more than {4}"@,,,,$0,,"{'{"++4:f"\}" _:#;0g,1-#;:>*6f"Fibonacci is so QUINE!{'{"\}
--- - - - - - - -
| | | |
| | |
| | |
```
This snippet outputs all of itself, except for the first character, in reverse order. Then it appends `{'{"\}` to the output, yielding a total of 96 chars including 98.9% of the code.
* Positions 1, 5, 21 and 89 are each occupied by `'a'`, `'b'` or `'E'`.
* Positions 2, 8 and 34 each have a `'0'`.
* In positions 3, 13 and 55, we find `'>'`, `' '` and `';'`, all symbols according to the definition given by Plarsen.
There are 3 completely unused cells, and all of `b >0a` is utterly useless code, only there for the aesthetics of `a0> b 0`. There may (still) be room for optimization.
Since String mode means pushing a reverse string to the stack and then pop/print-ing it forward, writing them in reverse order is totally natural in Befunge.
## Breakdown
1. `f6*` calculates 90, the index of the last character in the source. It's 15 \* 6.
2. `>:` means 'head east and duplicate the top of stack value'. Stack [ ... 90 90 ].
3. `;...;` skips over the code in between.
4. `#:_` skips the `:`, then pops TOS and heads back west if not 0. Stack [ ... 'F' 90].
5. Now RTL: `,g0;#:` duplicates TOS, skips entry to the `;` portal, gets the character at (TOS, 0) and prints it.
6. Still RTL: `:;#-1` decrements TOS, skips `;` and duplicates TOS. Execution continues at step 2.) Stack [ ... 89 89 ]
7. Once the TOS counter is down to 0, `_` lets us through.
8. We push the third required string , whereby we have to calculate the `'"'` because there is no escaping in Befunge. `f:4++` is 15 + 15 + 4. The commas write it back out from the stack. I had to insert `0$` there (push 0 then pop/discard) to meet the requirement.
9. `@` terminates.
] |
[Question]
[
**This question already has answers here**:
[Generate Pascal's triangle](/questions/3815/generate-pascals-triangle)
(68 answers)
Closed 10 years ago.
Write a function which for any given input array of numbers and a row number r, returns the r-th vector or array where each subsequent vector or array is constructed from the previous following the rules used in [Pascal's Triangle](http://en.wikipedia.org/wiki/Pascal%27s_triangle). For example, for an input vector of [3 1 2] and a row number of 1 (indicating the 'next' row), the correct return vector or array is [3 4 3 2].
As an example, a Clojure solution to this problem might be:
```
(defn pascals-trapezoid-row [r n]
(last (take (+ n 1) ((fn p [c] (cons c (lazy-seq (p (flatten (conj [(first c)] (map #(apply +' %) (partition 2 1 c)) [(last c)] )))))) r))))
```
The winning and accepted solution will be the one with the fewest number of characters in the solution code. Legibility is not a requirement. You're on your honor as to whether or not your proposed solution actually works, but remember that while cheaters often win nobody likes them very much, and karma is real (except in Fortran). Solutions must be posted by 07-Jan-2014 at 12:00 noon Eastern Standard Time (-5 timezone) to be considered. Extra credit (i.e. upvotes) will be awarded by me (and perhaps others) for interesting or novel solutions, including but not limited to those done in unusual languages, one-liners, unbelievably ugly solutions, unbelievably beautiful solutions, and anything I happen to like. I will not downvote any answer, although I make no guarantees about what others may do.
GO!
[Answer]
## Golf-Basic 84 - 10 characters
Executed from a TI-84 calculator.
```
i`N,Rd`N11
```
**Sample run**
```
?(3;1;2) <== Array of numbers
?1 <== Row number
3432
```
[Answer]
## APL (16 / 14)
```
{{2+/0,⍵,0}⍣⍺⍨⍵}
```
Takes the vector as the right argument, and the row number as the left argument, like so:
```
1{{2+/0,⍵,0}⍣⍺⍨⍵}3 1 2
3 4 3 2
2{{2+/0,⍵,0}⍣⍺⍨⍵}3 1 2
3 7 7 5 2
3{{2+/0,⍵,0}⍣⍺⍨⍵}3 1 2
3 10 14 12 7 2
```
If I get to take input from the keyboard, instead of as a function, I can shave off two characters:
```
{2+/0,⍵,0}⍣⎕⍨⎕
```
Takes the vector on the first line and the row number on the second.
[Answer]
### GolfScript, 14 characters
```
{[0\{.@+\}/]}*
```
Takes input (vector plus number of rows) on top of stack and replaces that by the result. Example (also [online](http://golfscript.apphb.com/?c=WzMgMSAyXSAxICAgIHtbMFx7LkArXH0vXX0qICAgICAgcApbMyAxIDJdIDIgICAge1swXHsuQCtcfS9dfSogICAgICBwClszIDEgMl0gMyAgICB7WzBcey5AK1x9L119KiAgICAgIHA%3D&run=true)):
```
[3 1 2] 3 {[0\{.@+\}/]}* # -> [3 10 14 12 7 2]
```
[Answer]
## R, 45
```
function(x,r){for(i in 1:r)x=c(x,0)+c(0,x);x}
```
Example usage:
```
fun <- function(x,r){for(i in 1:r)x=c(x,0)+c(0,x);x}
fun(c(3, 1, 2), 1)
[1] 3 4 3 2
fun(c(3, 1, 2), 2)
[1] 3 7 7 5 2
fun(c(3, 1, 2), 5)
[1] 3 16 37 50 45 28 11 2
```
[Answer]
## Ruby, 51
```
a=eval$_;a.pop.times{a<<j=0;p a.map!{|i|(v=j)+j=i}}
```
Run from command line with `[array,R]` as input. It shows each increment of `R` along the way. The last line is the solution.
For example, if the array is `[3,1,2]` and `R=7`:
```
$ ruby -ne 'a=eval$_;a.pop.times{a<<j=0;p a.map!{|i|(v=j)+j=i}}' <<< [3,1,2,7]
[3, 4, 3, 2]
[3, 7, 7, 5, 2]
[3, 10, 14, 12, 7, 2]
[3, 13, 24, 26, 19, 9, 2]
[3, 16, 37, 50, 45, 28, 11, 2]
[3, 19, 53, 87, 95, 73, 39, 13, 2]
[3, 22, 72, 140, 182, 168, 112, 52, 15, 2] <-- answer
```
For the same char count but different calling convention:
```
lambda{|a,r|r.times{a<<j=0;a.map!{|i|(v=j)+j=i}};a}
```
[Answer]
## iX2Web, 94
```
**iX2004FB 800345MTAJ Tj18fAkwDQ oxMAlSPXx8 CTANCjIyCU 89W05dKjEx fEMJMA0KMw lbT118XzAJ MA0K=*
```
Not likely to beat my Golf-Basic solution. Makes up for it with pretty GUI and output. Windows only.
] |
[Question]
[
**This question already has answers here**:
[Who's that Pokémon? [closed]](/questions/9037/whos-that-pok%c3%a9mon)
(9 answers)
Closed 10 years ago.
Your task is simple: given a number as an input, you have to print the English name of the chemical element with that atomic number, up to and including ununoctium. For example, for an input of 77, your program has to print `Iridium`, and nothing else.
You can use any language, but no library (or other, in-built feature) which includes the names of the elements is allowed, your program has to store or generate the names on its own. Use names in [wikipedia](http://en.wikipedia.org/wiki/Periodic_table_%28large_version%29) for the spelling of the names of the elements.
Shortest code wins, not sooner than 1 days after first valid answer.
[Answer]
## Tcl, 567 ~~577~~
```
puts [lindex [zlib i =SÑä\ ü(EH¡Îmöêþý2û0%C¤éÆæï¿Tï¢r\"§ÔVOÔfÝçzgQáA\;¸Í¸.ß÷>^´Dcb´¯CÊ®èp2ÞxG£QËvåª2ì§k¤±èµ4åJzî\v2axqÊ^w¶\töÏäªÒ£%`M15g+Ð4¶ù\vÉþ\]júiÓ\t¡êDí:Ð.¦86¦ñùÒû¦ëhÞmv\;ºçÔ\}þ45Q\;â&º¼éb®~_׬®5ftÐ`y»\fÅ´VN`ͺðmHDË6«6jßÈþ&1åüÙý\n»sFO\\\n¥ÜË¿Ñeú0^y@Z\\*ÏP<ÙDuIåVâªC<_f\]ôãÉС¸Â+@ÔvAÏ1Í2úLBFèÕîE`7¡:j^jÊëó^PÒÑF·IG(¦cî*Lj´Í\nìÑ-äùH1Ç=Òçoriñ2rÁaÍØ4Ê1xۯسe\{ú5llîer\ ³ÒÛ¡åxÖ\nþ(>ܶÔbYGì-Ú\vW5F\{бM- Ý\$0\ Ï3iG£ä\r/\{¾UÞÜa^jæ·Ùùaú?±äþ] [gets stdin]]
```
Who said that you can not embed binary data in your program code?
(`zlib` requires Tcl 8.6)
base64 encoded version:
```
cHV0cyBbbGluZGV4IFt6bGliIGkgPVPRkuRcIAj8FX+NKBOtRUihzm326v79EDL7MCVDpOnG5u+/VO+i
clwip4rUVk/UZt3ngXqTZw5R4ZRBD1w7uM24Lt/3Pl60RBtjYrSvQ8qu6HAyjh0Brd54R6NRy3blqjLs
p2uksei1NOVKAQF67lx2MmF4cQbKXpqBHXe2XHQO9gYGz+Sq0qMln2BNMTVnKwfQNLb5XHbJ/lxdF2r6
aZzTXHSh6kTtAQY60C6mgYSeODam8fnS+5oGputo3m2Ydp5cO7rn1Fx9/jQ1UVw74iaHExG6j4K86WKu
jH5f16wBrjVmdBmP0GCTeRu7XGbFlbSPVk5gzbrwbUhEyxs2qzZq38j+JjHlA/wb2f1cbrtzRk9cXFxu
A6Xcjsu/0WX6MF55QI9aXFwql88FilA82UR1SeUeVuKdqpBDPF9mXF30jOPJ0JqhuMIrQIzUdkGai88x
zTL6TEJG6NUY7kVgmjcDoZI6al5qyuvzXoRQ0tFGt0maRyimDmPuKkxqtM2NXG7sltEYLeT5SDHHPdLn
b3JpGIDxMnLBYc0H2Ag0h8oxeNuHr9gQs2Vce4n6NWxsmgLuZY5yB1wgF7PS26HleNZcbv4oPty2F9QQ
nGJZR+wHgi3aGVx2VzVGGFx70LFNjhctoN1cJJcwlVwgzzOGaRZHo+RcchYvDlx7vghV3p/chWFeaua3
HgPZ+WH6P7HkHf4HXSBbZ2V0cyBzdGRpbl1d
```
**History**:
* changed compression mechanism. Saves me 10 chars.
[Answer]
## Python, 69 + 536 = 605 (lazy solution)
I took the liberty of not capitalizing the names of the elements. That allows me to shave off extra 41 bytes. zlib is most likely not the best compressor for plaintext, it takes 1292 bytes down to 536.
**python file:**
```
import zlib
print (eval(zlib.decompress(open('a').read())))[input()]
```
**data file `a` (b64 encoded for web):**
```
eJxNVNGS5CAI/Jd5vj+62gdUJlpDMIU6t9mvPzSQ2YetZVCbpmny9/H488hnkrohzxCpjF0DKj1f
UUA5ybKhSp3XIkhYAZfuT+v3eQVPGlUK4zzGdavVdL3fYWNsVww09sJX3AqVuK4euTb9k9FmetBz
yKyXySFBtuti7dAMKgJFA4rAVquXDgb/BgbLxix1dzK8gdKZqMX6qgGor77iC2lljgMnhZ/CUf9t
4FpsKLsXAGmoTyYBJLRkmJUW55ecR18FZIRiTJoqx/2Kz97lin6KqBBXzKUGo1rpDAn5agxjZrSX
Mnr2gpJd50NZeseq7Xt1ECFZ5+Wj0SQFSmOvfC5somFUiqIt+t/INnWfXQC7Q/o2w8UroiUPgYY1
nVaNf8WHaoLurAa74+CQepiukCq5MTqKSZDOpo+tfq5kgPd5z4NuMe8sje5KZXg6qJKe7pvh4K31
ZVu5dazNdRIf1kGgWl38KqU5EpQ4ZGmWb08QwjwLpe06l+VS8mlC6xNjCira4toUATbjio8LYr+b
1z24Zeu/Doa48RgPbcE5jn4XU3rFoKMPVDf55futK1OeVew6FlYVHP6pzjbfISc19NuK1XB/HuCf
4M19elAUzVpII/heI+gnY/OPRxYfhW/ujqWz+yaB7CpScmtX5L75UHQRUelaycGDfWWehFLfn/yB
vlZU1Pm7izjPmur1+VXj+vH1H5EjvoY=
```
[Answer]
### GolfScript, 577 characters
```
~(
'ž�®Ñ/ž!Z!Ó1ã„9î¸dÊÓªí[o@ÁlD®�K®ÆšTB˜Þ6(ËH¼¡)ßÝ•|O¨U˜É/Œ�DÚvU$.âxŠ²¤Æ³n’t8[¢êqHyÍlÂSbYÈ*1~˜|†ï¨ŸÊ*Þk0âg%&‘Ÿ¶2ö¼Eë˜Áaq[¦Ä;ø7[–ί_ªtë½¢Ÿ\‰`Ãö”{ÉOUÈÜ¿Ò‰Fös–ß<µ‰x�#¶w+ìÊ®¼äH$̪¦ùoh�7™ÐbÙÑîâóÂø8Ö;•9ÁÃ)T°¤vWOUð~È¡jžK¯V¹8K?«à‚ª–0)ÚFj]îõc„ ¼´¢�Ã#æ¯Uƒ¡Mh$Šº^9V$Ùš`½†2±Žžk™+®5ª.„bC x%XJ<ç†78N¥5á2ù@<ù��ž£ªØ¸ÅÆŒç™ Î½¨ñøŽjZ±@,, íªluzÀ¡‹ØÈ[$5† S¾,‰‚TÊ_"ñÍÈ�» Úïº @ð_D«�.kX©(0ÎX]®c´c.Åm,‰æªQ)•‚t®§>‰j)tŸ.Z!�|0Ň̢‰ùc êš™‡ãÂÓT<xsY(ª2!¦93㜤¡�Ç"mÎç£COKcÎ}¶!0Ö·£—sÂÞíÛê”[lœX£€Ã6{È‚¡�ˆFâóVP8‡4�ës†´ïç]Ó{±éˆñz~bºs8¿U/ªY²Öm4 ÍP3CI7‹'
{32-}%218base 32base{96+}%''+'j'/'ium`'*'`'/=([32-]\+
```
Base64 encoded version:
```
fignnp2u0S+eIVoh0zHjhDnuuGTK06rtW29AwWxEroFLrsaaVEKY3jYoy0i8oSnf3ZV8T6hVmMkv
jIFE2nZVJC7ieIqypMazbpJ0OFui6nFIec1swlNiWcgqMX6YfIat76ifyireazDiZyUmkZ+2Mva8
ReuYwWFxW3+mxDv4N1uWzq9fqnTrvaKfXIlgw/aUe8lPVcjcv9KJRvZzlt88tYl4nSO2dyvsyq68
5EgkzKqm+W9okDeZ0GLZ0e7i88L4ONY7lTnBwylUsKR2V09V8H7IoWqeS69WuThLP6vggqqWMCna
Rmpd7vVjhKC8tKKdwyPmr1WDoU1oJIq6XjlWJNmaYL2GMrGOnmuZK641qi6EYkMgeCVYSjznhjc4
TqV/NeEy+UA8+YGNnqOq2LjFxoznmSDOvajx+I5qWrFALCwg7apsdXrAoYvYyFskNYYgU74siYJU
yl8i8c3IncK7oNrvuqBA8F9Eq50ua1ipKDDOWF2uY7RjLsVtLInmqlEplYJ0rqc+iWopdJ8uWiGQ
fDDFh8yiifljIOqamYfjwtNUPHhzWSiqMiGmOTPjnKShkMcibc7no0NPS2POfbYhMNa3o5dzrcLD
nu3b6pRbbJxYo4DDNnvIgqGdiEbi81ZQOIc0getzhrTv513Te7HpiPF6fmK6czi/VS+qf1my1m00
IM1QM0NJN4snezMyLX0lMjE4YmFzZSAzMmJhc2V7OTYrfSUnJysnaicvJ2l1bWAnKidgJy89KFsz
Mi1dXCsNCg==
```
It also does the capitalization correct. No libraries, no zlib, just base encoding. With a little bit tweaking it might be possible to shave off a few chars.
] |
[Question]
[
**This question already has answers here**:
[Outputting ordinal numbers (1st, 2nd, 3rd)](/questions/4707/outputting-ordinal-numbers-1st-2nd-3rd)
(49 answers)
Closed 10 years ago.
Assuming 'lol' with a variavle number of 'o's. Print a the following phrase:
```
What does 1st, 2nd, 3rd, 4th ... 'o' stand for?
```
Examples:
```
lol -> What does 1st 'o' stand for?
loooool -> What does 1st, 2nd, 3rd, 4th, 5th 'o' stand for?
```
So far I managed to write a 128 characters solution in Perl:
```
$l=(<>=~tr/o//);print"What does ";print$_,$_==1?'st':$_==2?'nd':$_==3?'rd':'th',$_<$l?', ':''for(1..$l);print " 'o' stand for?";
```
and a 123 characters solution in Haskell:
```
p 1="1st";p 2="2nd";p 3="3rd";p n=show n++"th";main=putStr$"What does "++(foldr(++)"'o' stand for?"[p i++", "|i<-[1..23]]);
```
How short can you write it?
[Answer]
### GolfScript, 82 characters
```
"What does "\,2-,{)..10/10%1=!\10%`"123"\?)*"thstndrd"2/=+}%", "*" 'o' stand for?"
```
Works even for >100 'o's, [test it online](http://golfscript.apphb.com/?c=Oydsb29vb29vb29vb29vb29vb29vb29vb29sJwoKIldoYXQgZG9lcyAiXCwyLSx7KS4uMTAvMTAlMT0hXDEwJWAiMTIzIlw%2FKSoidGhzdG5kcmQiMi89K30lIiwgIioiICdvJyBzdGFuZCBmb3I%2FIgoK&run=true).
[Answer]
## Python, 112
```
print'What does '+', '.join(`n+1`+['th','snrtdd'[n::3]][n<3]for n in range(len(raw_input())-2)),"'o' stand for?"
```
[Answer]
## Perl 104 (+1) bytes
```
s/l?ol?/($`?', ':"What does the ").++$n.((0,st,nd,rd)[$n%(10<<($n%100<20))]||th)/ge;s/$/ 'o' stand for?/
```
Correctly handles `11th, 12th, 13th`, `21st, 22nd, 23rd`, `111th, 112th, 113th` etc. Takes input from stdin, and requires a `-p` command line switch:
```
$ echo loooool| perl -p loool.pl
What does the 1st, 2nd, 3rd, 4th, 5th 'o' stand for?
$ echo looooooooooooooooooooooooooooooooooooooooool| perl -p loool.pl
What does the 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th, 14th,
15th, 16th, 17th, 18th, 19th, 20th, 21st, 22nd, 23rd, 24th, 25th, 26th, 27th, 28th, 29th,
30th, 31st, 32nd, 33rd, 34th, 35th, 36th, 37th, 38th, 39th, 40th, 41st, 42nd 'o' stand for?
```
If it is not required that `21st, 22nd, 23rd` be reported correctly (as in the example code), this can be reduced to **87 bytes**:
```
s/l?ol?/($`?', ':"What does the ").++$n.((0,st,nd,rd)[$n]||th)/ge;s/$/ 'o' stand for?/
```
---
## PHP 107 bytes
```
What does the <?for(;$argv[1][++$n]>l;$f=', ')echo$f,$n,date(S,~-$n%(10<<($n%100<20))*9e4)?> 'o' stand for?
```
Input is taken by command line argument:
```
$ php loool.php loooool
What does the 1st, 2nd, 3rd, 4th, 5th 'o' stand for?
$ php loool.php looooooooooooooooooooooooooooooooooooooooool
What does the 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th, 14th,
15th, 16th, 17th, 18th, 19th, 20th, 21st, 22nd, 23rd, 24th, 25th, 26th, 27th, 28th, 29th,
30th, 31st, 32nd, 33rd, 34th, 35th, 36th, 37th, 38th, 39th, 40th, 41st, 42nd 'o' stand for?
```
Once again, if correctly handling `n>20` is not required, this can be reduced to **87 bytes**:
```
What does the <?for(;$argv[1][++$n]>l;$f=', ')echo$f,date(jS,~-$n*9e4)?> 'o' stand for?
```
[Answer]
## R - 158 characters
```
f=function(s){n=1:(nchar(s)-2);v=c("st","nd","rd",rep("th",7));cat("What does the",paste0(n,c(v,rep("th",10),rep(v,8))[n],collapse=", "),"\"o\" stand for?")}
```
Works until 100 "o"s.
Usage:
```
f("looooooooooooooooooooooooooooooooool")
What does the 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th, 14th, 15th, 16th, 17th, 18th, 19th, 20th, 21st, 22nd, 23rd, 24th, 25th, 26th, 27th, 28th, 29th, 30th, 31st, 32nd, 33rd, 34th "o" stands for?
```
] |
[Question]
[
# Input variables:
(Names are just examples, they don't need to be named like this)
* `GrandTotal` - integer to divide
* `SplitCount` - number of output integers required
* `UpperLimit` - highest valid value for any one output integer
* `LowerLimit` - lowest valid value for any one output integer
# Valid Output:
Outout must be a random set of `SplitCount` integers, each between `UpperLimit` and `LowerLimit` (your language's RNG is fine), the sum of which is `GrandTotal`.
The output should be uniformly random in that any valid output should be equally likely. For example input of [8,3,4,2] has the following six valid outputs:
1. 2,3,3
2. 3,2,3
3. 3,3,2
4. 2,2,4
5. 2,4,2
6. 4,2,2
Each output should have, therefore, 1/6 chance of occurring.
The order of the output matters: 5,8,7 is not an equal set to 5,7,8. Both outputs must be equally likely if either is possible.
(This does mean that output where all three integers are the same is less likely output to one where all three are different: Given `GrandTotal`=6, `SplitCount`=3, `UpperLimit`=4, `LowerLimit`=1, a set including 1, 2 and 3 can appear in 6 different configurations, while a set of all 2s can only appear in one, making it 6 times as likely that *one of* the varied sets will appear, rather than the set of 3 2s.)
# Valid Input:
Any input variables should work, assuming that the following is true
1. `UpperLimit` \* `SplitCount` >= `GrandTotal`
2. `LowerLimit` \* `SplitCount` <= `GrandTotal`
3. all input variables are positive integers.
## Tie-Breaker
Submissions that accept invalid input but return output as though it was the closest valid input would win a tie-breaker. (eg `GrandTotal`=10, `SplitCount`=2, `UpperLimit`=3, `LowerLimit`=2 returning [5,5] treats the `UpperLimit` variable as though it was the lowest valid input, rather than what it was.) Closest here means change as few variables as possible, and change those variables by the smallest possible integer. Ideally, change the latest possible variable(s) (here, `SplitCount` could have been changed to make input valid, but `UpperLimit` is a later variable.)
# Sample in-out range
| GrandTotal | SplitCount | UpperLimit | LowerLimit | Possible Output Range |
| --- | --- | --- | --- | --- |
| 11 | 2 | 7 | 4 | 4,7;5,6;6,5;7,4 |
| 8 | 3 | 11 | 2 | 2,3,3;3,2,3;3,3,2;2,2,4;2,4,2;4,2,2 |
| 13 | 2 | 8 | 4 | 8,5;7,6;6,7;5,8 |
| 16 | 2 | 8 | 4 | 8,8 |
| 16 | 2 | 10 | 4 | 10,6;9,7;8,8;7,9;6,10 |
| 16 | 4 | 10 | 4 | 4,4,4,4 |
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 49 bytes
```
RandomChoice@Pick[t=Range@##3~Tuples~#2,Tr/@t,#]&
```
[Try it online!](https://tio.run/##ZcgxDoIwGEDhnWs0YfqNLSXKgmnCBYiykQ61FmmEYqBMhF69FnRz@97rhW1VL6yWwje5vwrzGPqiHbRUrNTyVds8vKdiCFFXze9OTQ4lUI1HZgHx2JejNrZGh0sxzMZOrBL3TtUNYwgIxpjz2N2kMG6JFoIhhQTSFYLJJjhvzoCGIGT/dP/Z7tOfCf5F@o1o9R8 "Wolfram Language (Mathematica) – Try It Online")
Input `[GrandTotal, SplitCount, LowerLimit, UpperLimit]`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŸIãʒOQ}Ω
```
Inputs in the order `UpperLimit,LowerLimit,SplitCount,GrandTotal`.
[Try it online](https://tio.run/##yy9OTMpM/f//6A7Pw4tPTfIPrD238v9/cy4TLiMuQ0MA) or [verify all test cases (without the `}Ω`)](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCaFjx/6M7Ig8vPjXJPyLwf63O/@hocx0THSMdQ8NYnWhDQyDLWMcCyLSAiBojmGYgBQZobBMQOxYA).
**Explanation:**
```
Ÿ # Take the first two (implicit) inputs and push a list in the range
# [LowerLimit,UpperLimit]
Iã # Create all combinations of a size of the third input SplitCount using
# the cartesian product
ʒ # Filter this list of lists by:
O # Sum the list
Q # Check if it's equal to the fourth (implicit) input GrandTotal
}Ω # After the filter: pop and leave a random list
# (which is output implicitly as result)
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 116 bytes
*-12 bytes thanks to `Jitse`*
Accepts input in the form of `GrandTotal,SplitCount,UpperLimit,LowerLimit`.
Returns a randomly picked range, as a tuple, from a list of possible ranges.
```
lambda g,s,u,l:r.choice([p for p in i.product(range(l,u+1),repeat=s)if sum(p)==g])
import random as r,itertools as i
```
[Try it online!](https://tio.run/##bc3BboMwEATQe75ijra6iuISJQiJL6EcHDDEksGrtX3o15MQNWoPPb6d0Q5/53tcq5plm9qvLdjlNlrMlKhQaOQ43KMfnOoYUxQw/Ap/ZIljGbISu85OBSofRpM4dja3SfsJqSyKddvOvT74haNkPLtjXGAThHx2kmMMaaff9s8zIREKIewTXWcM4ZNwJZx7QlcTKsLruNNUr7T@Sc3lP5rTH5/f7psDwOLXrCb1u6r19gA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 49 bytes
```
r@s1Js2rzjCBf{++g2==}f{{g1j~[}al}sa-.3 0x/rn1.+si
```
[Try it online!](https://tio.run/##TYxNCsIwEIXX6SmCGxedaCaJbSUooq68gIvaRYUqLUW0QRBLvXqdVBEZ5ve9@Y73pi7c7V709YWLjI/EcmStyPbbFrnkmqvOlWOeZof0WvTNyuHOqeZZbdanNgzParHoTm17xuqVdnnduVxMNJePaXPBSejKvkdkisXMcLFkBmI7g8hGMLMxmCBhmnndawo0aKtBDZW6VTQbqoZmSlABamIlH1YyMDzLM5MAo3/tu6P8HFCSc05OUuhrTl8ovcX8LAaGeAM "Burlesque – Try It Online")
```
r@s1 # Range from lowerLimit to upperLimit and save to 1
Js2 # Duplicate grandTotal and save to 2
rz # Range [0, grandTotal]
jCB # Combinations of SplitCount
f{++g2==} # Filter for sum == grantTotal
f{{g1j~[}al} # Filter for all elements in range
sa-.3 0x/rn # Generate infinite list of random numbers [0, len)
1.+si # Take 1 and select it
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 164 bytes
```
echo>0
seq 1 $2|xargs -I, sh -c "rm ,;seq $4 $3|xargs -i sh -c \"<\$((,-1)) sed s/^/{}\ />>,\""
<$2 tr \ +|sed s/+$//|bc|pr -mt $2 -|grep $1$|cut -d\ -f1|shuf -n1
```
[Try it online!](https://tio.run/##Nc3BCoIwHAfgcz7Fj7GD4saaCR0S773DCHRO7WDZphC0nv1fUZ2/w9c2YSRydrzW2yS4GzR4Ee@NHwLkUSCMkBbMTxCHD/MSfPf3848NqwxPUyF1liG4DkGd1ONpoOpaGMaSihdYPAyQx6/nXKnY2jh7yGl5n5Bx8G4G1zzadYHszAay1zGMaw950USkNRW0p/IF "Bash – Try It Online")
[Answer]
# JavaScript (ES6), 85 bytes
Expects `(count, lower, upper)(total)`.
```
(n,a,b)=>g=(t,k=n,s=t,...o)=>k?g(t,k-1,s-=q=a-Math.random()*(~b+a)|0,...o,q):s?g(t):o
```
[Try it online!](https://tio.run/##bY/dTsIwFIDveYpjYkLrzppViBJm8cpL4wMsSyijwNhcYSsSMuer4ykzxAtu2n7f@ek5W/2lm6zOdy6s7NKcV@rMKtS44Gq2VsxhoSpslEMhhCVXvK69DCU2odorHb5rtxG1rpb2k/EH9rMINP@OLum459PG5/OpPcfJACCREh9xjPCcokeY4IiElD3KUR@d/OHTLZTRFcc9DtKBWNn6TWcbxhJnnS4RMnuoHEJpj6ZGOOx2pk45qBm0VFwaB43TDhS0XUyCypmXOZkopusFZBT5VxBwaC8FhTnFsLRErj7RSUzZK3bjJ84uU3CxtXnFhjjkMXSQaUcTGurXER03eWnYHXWhoB8moWdKHcOfK1EVDfex2JrMCRIN8yEuGls7xq9LF36vzFaNLY0o7ZpEAHNg923fKe34nHO/5/8kEh0//wI "JavaScript (Node.js) – Try It Online")
(NB: The function is likely to stack overflow on some test cases. The above test includes some extra recovery code.)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes
```
NθNηNζ≔⊕⁻NζεI‽ΦEXεη⁺﹪÷ιXε…⁰ηεζ⁼Σιθ
```
[Try it online!](https://tio.run/##XY3JCoMwEIbveQqPE7Bgl5un0gU8WKR9gtQEDWTRLBZ8@XSkLUjnMMzHfPNP2zPXWqZSqswQwy3qp3Aw0pKsuf/jGfnovewMVKZ1QgsTBIdamuhhLdI8myk2gQeNkybAifkAd2a41XCVKqBUswEa@8JJ5FmPdqMwprY8Kotp4SwnyQVIXPwsDOgEFIv@if/@uYyRKQ@PqEEijnSpMqVtQfZkRw5pM6k3 "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order GrandTotal, SplitCount, LowerLimit, UpperLimit. Explanation:
```
NθNηNζ
```
Input the grand total, split count and lower limit.
```
≔⊕⁻Nζε
```
Input the upper limit and calculate the length of the inclusive range from the lower limit to the upper limit.
```
I‽ΦEXεη⁺﹪÷ιXε…⁰ηεζ⁼Σιθ
```
Generate the Cartesian product of the split count number of inclusive ranges, filter out those whose sum isn't the desired grand total, and output one uniformly at random.
] |
[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/226238/edit).
Closed 2 years ago.
[Improve this question](/posts/226238/edit)
I'm currently working with a branchless language which does not have native Less-Than, Greater-Than or Equal-To functions. I do however have `min`, `max` and `abs` functions and standard arithmetic (`+`, `-`, `/` and `*`) available to me.
I'd like to create these three functions (as `L(a, b)`, `G(a, b)` and `E(a, b)` respectively, which will output `0` for `false` and `1` for `true`. So, for example, `L(3, 7)` would return `1` for `true` whereas `G(3, 7)` would return `0` for `false`, and `E(3, 7)` would also return `0`, etc.
The `min` and `max` functions only allow you to pass two parameters, `a` and `b`, and then spits out the respective minimum or maximum of the two parameters. The `abs` function takes the one parameter and returns the absolute value.
I've postulated that given that the `min(a, b)` is equivalent to:
`L(a,b) * a + (1 - L(a,b)) * b`
It would stand to reason that:
`L(a,b) = (min(a,b) - b) / (a - b)`
and similarly:
`max(a,b) = G(a,b) * a + (1 - G(a,b)) * b`
therefore:
`G(a,b) = (max(a,b) - b) / (a - b)`
But this is where I get stumped because, I'm not sure how to account for the possibility of `a-b` equalling `0` in both instances, which as a result stumps me on how to approach the `E(a, b)` function.
So my question is this... Given that I only currently have access to basic arithmetic functions as well as `min(a,b)`, `max(a,b)` and `abs(a)`, and because of the language being branchless (therefore no loops), is there a way to programmatically account for the `a-b` divide-by-zero issue such that if I do have a scenario where `a == b` that these functions can return zero for either `L()` or `G()`, otherwise output the original equations I have derived, and also be able to provide code for `E(a, b)`?
Given that this is fairly generic (hey, I've written it in psuedocode!) I'd appreciate some insight on how to proceed. In this case, the solution needs to work with both integers as well as floats.
Context: This is research for a personal project I'm working on relating to binary registers, thus the need for 1's and 0's for output and I'm kinda stuck at this point.
[Answer]
# Integers and round-to-zero integer division
```
// 1 if x >= y, 0 otherwise
GE(x, y) = (x - y + 1) / (abs(x - y) + 1)
LE(x, y) = GE(y, x)
E(x, y) = GE(x, y) * LE(x, y)
L(x, y) = LE(x, y) - E(x, y) = 1 - GE(x, y)
G(x, y) = GE(x, y) - E(x, y) = 1 - LE(x, y)
```
If `x - y` is negative, `x - y + 1` has smaller magnitude than `abs(x - y) + 1`, so the division rounds to 0.
If `x - y` is zero or higher, `x - y + 1` is the same as `abs(x - y) + 1`, so the result is 1.
# Integers and floored integer division
```
GE(x, y) = (x - y + abs(x - y) + 1) / (abs(x - y) * 2 + 1)
```
If `x - y` is negative, the numerator is fixed at 1, but the denominator is at least 3. Therefore the result is zero.
If `x - y` is zero or positive, the numerator and the denominator are the same, so the result is 1.
# Floating-point numbers
MarcMush pointed out a possible use of `eps`, the smallest representable number greater than 0. GE can be implemented for floating-point numbers using it:
```
GE(x, y) = (max(x - y, -eps) + eps)/(abs(x - y) + eps)
```
I haven't found any way without `eps` or the floor function. (If `floor` is available, flooring the second solution works for floats.) tsh pointed out that we can't get a (true) discontinuous function from a bunch of continuous functions, so I'm pretty sure it is impossible without `eps` or an additional built-in that provides discontinuity.
Assuming an IEEE floating-point representation, the solution above is expected to give exact results (exactly 0 or exactly 1) for all non-NaN, non-infinite floating-point values of `x` and `y`.
[Answer]
This answer only works on integer values :)
## Test Zero
We all know that
$$ (t+1)(t-1)=t^2-1 $$
$$ t\cdot t-(t+1)(t-1)=1 $$
As long as \$t\$ is integer.
$$ t\cdot t-|t+1|\cdot|t-1| = \begin{cases}
1 & t\ne 0 \\
-1 & t = 0\\
\end{cases} $$
So we have:
```
isZero(t) = (t*t-abs(t+1)*abs(t-1)+1)/2
```
## Build others
And then, you can have
```
GreaterThanOrEqual(a, b) = isZero(max(b-a, 0))
LessThanOrEqual(a, b) = GreaterThanOrEqual(b, a)
Equal(a, b) = GreaterThanOrEqual(a, b) * LessThanOrEqual(a, b)
GreaterThan(a, b) = GreaterThanOrEqual(a, b) - Equal(a, b)
LessThan(a, b) = LessThanOrEqual(a, b) - Equal(a, b)
```
[Answer]
Assuming floor division:
E(x,y) = (1 - abs(x-y)) / (1 + abs(x-y))
L(a,b) = E(min(a,b), a) - E(a,b)
G(a,b) = E(max(a,b), a) - E(a,b)
] |
[Question]
[
Employers love to see their employees working hard, while the employees would love to work less, especially those with a monthly rather than hourly payment.
The laziest of employees are thinking about the world where every month starts with the same weekday and it makes them wonder if they would work more or less.
The greediest of employers are thinking about the world where every month starts with the same weekday and it makes them wonder if their employees would work more or less.
Your task (as a lazy employee or greedy employer, you choose) is to write the shortest program or function that given weekday every month must start outputs the number of working and weekend days.
## Input
* Weekday identificator. This can be a 0- or 1-based index, case-insensitive shortname (`Mo/Mon`, `Tu/Tue` etc) or case-insensitive full name (`Monday`, `tuesday` etc) as long as you specify the format.
## Output
* One of the following output formats allowed:
1. A string of single space/comma/semicolon separated values.
2. A list of values.
3. A multi-line string of values with a trailing line break allowed.
* The output format must be consistent.
* 2 values must present in the output: number of working days in base 10 and number of weekends in base 10.
## Rules
* Assume the year is 365 days.
* Workdays are Monday, Tuesday, Wednesday, Thursday and Friday.
* Week starts with Monday.
* No national weekends are accounted.
* 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
```
Input | Output
--------+--------
Monday | 269 96
Tue | 269,96
3 | 269 96 // 1-based index
3 | 262, 103 // 0-based index
fr | 251;114
5 | 247 118 // 0-based index
sunday | 258;107 // 0-based index
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 37 bytes
```
lambda d:(k:=ord('```grvk'[d]),365-k)
```
Monday is `0`, returns a tuple `(weekend days, weekdays)`.
**[Try it online!](https://tio.run/##BcFLCoAgEADQdZ3CXTNQK@mD0Ekq0Ji0sFQGCTq9vZe@fMYgp8TFzmu5zbOTEaTAqzkyQaO1dvz6ZqENWzn0ncdiIwsSVxBsgjtgRFVXia@QwQIhlh8 "Python 3.8 (pre-release) – Try It Online")**
[Answer]
# JavaScript (ES6), ~~34~~ 33 bytes
Takes input as a 0-based index. Returns `[weekend_days, working_days]`.
```
i=>[w=96|'5621'[i-3]*11%24,365-w]
```
[Try it online!](https://tio.run/##Fcy7DoIwFADQna@4A6YtrwgVjI86ujlB4kBIQChaQ1oDVAbk26tOZzvP6l0NdS9eoy9Vw03LjGCnfGK75IPiJApRLnxaOGG4ijYeTWJ/KkyreiyAwfoAAo6w/eG6BGYLoFZyUB0POnXHpT2LBbA9o4uSmeZX3mQPfe5FWo2pligY9G0Y/5UD1ANKFrIHe26xIEtJrMV8AQ "JavaScript (Node.js) – Try It Online")
### How?
The minimum number of weekend days \$w\_i\$ being \$96\$, we can just store the difference \$d\_i=w\_i-96\$ for each possible input and output \$[96+d\_i, 365-(96+d\_i)]\$.
This gives:
$$[0,0,0,7,18,22,11]$$
It's worth noting that \$96=2^5+2^6\$ and each value above is less than \$2^5\$, which means that we can compute \$96\text{ OR }d\_i\$ instead of \$96+d\_i\$ and still get the correct result.
We use the following formula to convert \$i\$ to \$d\_i\$:
$$d\_i=(x\_i\times11)\bmod 24$$
where \$x\_i\$ consists of a single decimal digit:
$$[0,0,0,5,6,2,1]$$
Hence the JS code:
```
96 | '5621'[d - 3] * 11 % 24
```
For \$i<3\$, `'5621'[d-3]` is *undefined* and `'5621'[d-3]*11%24` results in *NaN*. But because we use a bitwise OR, this is coerced to \$0\$ and returns \$96\$ as expected.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to Erik the Outgolfer (use of printing in a full-program mode)
```
ị“```grvk‘Ṅ365_
```
Monday is `1`, prints `weekend days` then `weekdays` to STDOUT.
**[Try it online!](https://tio.run/##y0rNyan8///h7u5HDXMSEhLSi8qyHzXMeLizxdjMNP7////mAA "Jelly – Try It Online")**
---
I am not sure how to build data for Jelly's hash function, `ḥ`, but maybe that would be better...
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.•OζΛ¦•IèÇ<D365αì
```
0-indexed (`0 = Monday; 6 = Sunday`), returns `[working_days, weekend_days]`.
[Try it online](https://tio.run/##yy9OTMpM/f9f71HDIv9z287NPrQMyPI8vOJwu42LsZnpuY2H1/z/bwwA) or [verify all test cases](https://tio.run/##yy9OTMpM/W92bJKfvZLCo7ZJCkr2//UeNSzyP7ft3OxDy4Asv8MrDrfbuBibmZ7beHjNf53/AA).
**Explanation:**
```
.•OζΛ¦• # Push compressed string "aaahswl"
Iè # Index the input-integer into it
Ç # Convert the character to its unicode value
< # Decrease that by 1
D365α # Create a copy, and get its absolute difference with 365
ì # Prepend this (and output the result implicitly)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•OζΛ¦•` is `"aaahswl"`.
] |
[Question]
[
**This question already has answers here**:
[Partial Sum of Harmonic Sequence!](/questions/123173/partial-sum-of-harmonic-sequence)
(42 answers)
Closed 6 years ago.
You are given a very special gun with a full magazine.
Let `n` be the initial number of bullets in the magazine and `i` the number of bullets left.
That gun is really unreliable, hence each time you shoot, you have a `i/n` chance to successfully shoot. The fewer bullets you have left, the more tries it requires to shoot.
The goal is to find the average number of attempts to shoot before running out of ammo.
### Example
You start with 3 bullets (`n=3`). Your first shot is always successful. You have now 2 bullets left. You will shoot first with a probability of `2/3` and misfire with `1/3`. The probability of emptying your magazine in just 3 tries (no misfires) is `(3/3) * (2/3) * (1/3)`.
The average number of tries before emptying your magazine for this example is `5.5`.
### Test Cases
```
f(2) = 3.000
f(3) = 5.500
f(4) = 8.330
f(10) ~= 29.290
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
L/O
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fR9///39DAwA "05AB1E – Try It Online")
or as a [Test suite](https://tio.run/##MzBNTDJM/V9TVln530ff/3@l0uH9VgqH9yvp/DfiMuYy4TI0AAA)
**Explanation**
```
L # range [1 ... n]
/ # divide n by each in above list
O # sum
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~22~~ 21 bytes
```
f n=sum$(n/)<$>[1..n]
```
**[Try it online (TIO)!](https://tio.run/##y0gszk7Nyfn/P00hz7a4NFdFI09f00bFLtpQTy8v9n9uYmaegq1CQVFmXomCikKagqHBfwA)**
---
Previous, more self-explanatory version:
```
f n=sum[n/i|i<-[1..n]]
```
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm), 4 bytes
```
D@/Σ
```
[Try it online!](https://tio.run/##y8/I/f/fxUH/3OL//w0NAA "Ohm – Try It Online")
Inspired by [Emigna's answer](https://codegolf.stackexchange.com/a/123945/58974)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~6~~ 4+1= 5 bytes
Inspired by [Emigna's 05AB1E solution](https://codegolf.stackexchange.com/a/123945/58974).
+1 byte for the `-x` flag.
```
õ@/X
```
[Try it online](http://ethproductions.github.io/japt/?v=1.4.5&code=9UAvWA==&input=MTAKLXg=)
[Answer]
# PHP, 37 Bytes
```
for(;$i++<$argn;)$s+=$argn/$i;echo$s;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ2toYP0/Lb9Iw1olU1vbBixmralSrG0LZuqrZFqnJmfkqxRb//8PAA "PHP – Try It Online")
[Answer]
# [Aceto](https://github.com/aceto/aceto), ~~41~~ 34 bytes
Based on [Emigna's insight](https://codegolf.stackexchange.com/a/123945/58974)
Could almost definitely be golfed more.
```
9jpX
{:s_=1(
&_L+&l@
iM!l
rLz@
```
### Rough explanation
Part 1: Making a range and dividing by each of the numbers:
```
{:s
&_L
iM!l
rLz@
```
Part 2: Summing them up
```
_=1(
+&l@
```
Part 3: Printing, exiting, and making sure we don't visit this earlier
```
9jpX
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 11 bytes
```
rid_,:)f/:+
```
[Try it online!](https://tio.run/##S85KzP3/vygzJV7HSjNN30r7/39DAwA "CJam – Try It Online")
Inspired by [Emigna's answer](https://codegolf.stackexchange.com/a/123945/58974)
[Answer]
# jq, 30 characters
```
. as$n|[range(1;.+1)|$n/.]|add
```
Sample run:
```
bash-4.4$ jq '. as$n|[range(1;.+1)|$n/.]|add' <<< 10
29.289682539682538
```
[Try in jq‣play](https://jqplay.org/s/9GnepHRjOL)
[Answer]
# JavaScript (ES6), ~~44~~ ~~34~~ ~~27~~ 26 bytes
[Also](https://codegolf.stackexchange.com/a/123946/58974) inspired by [Emigna's 05AB1E solution](https://codegolf.stackexchange.com/a/123945/58974).
```
f=(n,i=n)=>i&&n/i+f(n,--i)
```
(Look at me , going for recursion over array mapping for once!)
---
## Try it
```
f=(n,i=n)=>i&&n/i+f(n,--i)
oninput=_=>o.innerText=f(+i.value)
o.innerText=f(i.value=1)
```
```
<input id=i type=number><pre id=o>
```
] |
[Question]
[
Output an infinite sequence of positive integers, such that, for each element in the sequence, all positive integers that have not yet been output have a positive probability of being chosen, and no value is repeated.
For example, if the first integer is `3`, then `3` may not be output again, but all other positive integers have a positive probability of being chosen for the second integer.
## Acceptable output methods
* Writing to STDOUT, with a consistent, unambiguous separator between integers (such as a newline), with output prior to termination of the program
* A named or unnamed function which returns an infinite iterable (such as a Python generator)
* A named or unnamed function which outputs the sequence one integer at a time each time it is called within a single execution of the program
* A named or unnamed function or program which outputs the next integer in the sequence when called with the previous integer(s) as its sole argument(s) (the first call may either take no arguments or take a seed argument, which may be included in the arguments to later calls)
## Rules
* There will be no input except an optional seed value, which will be an infinite sequence of random bits.
* Submissions must be capable of producing different outputs given different initial conditions (outputting the same sequence every time is not acceptable).
* Each element of the sequence must be chosen randomly out of the valid elements (positive integers not already present in the sequence).
* You may assume that you have infinite memory available.
* You may assume that any real numbers returned by a PRNG are infinite-precision. In other words, if you have a function called `rand` that returns a random value in `[0, 1)`, you may assume every real value in that interval has a positive probability of being chosen, rather than just the subset of the reals that are representable with floats.
* Each integer must be output in a finite amount of time after the last integer (so you can't wait until program termination to output part of the sequence). The first integer must be output in a finite amount of time after the program is started or the function is called.
[Answer]
# Python 3, ~~137~~ ~~127~~ ~~123~~ ~~138~~ ~~117~~ ~~99~~ 98 bytes
>
> A named or unnamed function which returns an infinite iterable (such as a Python generator)
>
>
>
```
from random import*
def f(x=[],y=1):
while y in x or.5<random():y+=1
yield y;yield from f(x+[y])
```
* -10 bytes by putting the conditional in one line (Thanks, @Dennis)
* -4 bytes by initializing `r` at the beginning of the loop
* +15 bytes by remembering numbers can contain zeroes...
* -21 bytes by renaming `randint`, and moving the condition in the head of the inner loop
* -18 bytes by switching to a functional paradigm
* -1 bytes by moving from `or ...>.5` to `.5<random()` (thanks, @JonathanAllan)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
`x1r/XktGm
```
[Try it online!](https://tio.run/nexus/matl#@59QYVikH5Fd4p77/3@0sYKJgpmCoUHs17x83eTE5IxUAA "MATL – TIO Nexus")
### Explanation
A candidate output, say **n**, is generated as `ceil(1/r)`, where `r` is uniformly distributed on the interval (0,1). This ensures that every positive integer has a positive probability of being chosen as **n** (assuming infinite precision for `r`).
If **n** coincides with any of the previous numbers (taken as input) the process is repeated.
```
` % Do...while
x % Delete. This deletes the candidate number from the preceding iteration.
% In the first iteration it takes input implicitly and deletes it.
1 % Push 1
r % Push random number uniformly distributed on (0,1)
/ % Divide
Xk % Round up (ceil). This is the candidate output. It will only be valid
% if it's not present in the input
t % Duplicate
G % Push input: forbidden numbers
m % Ismember. This will be used as loop condition
% End (implicit). If condition is true, next iteration
% Display (implicit)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~93~~ 87 bytes
-3 bytes thanks to Uriel (move `r=1` to beginning of the loop to avoid initialisation)
```
from random import*
a=[]
while 1:
r=1
while r in a or.5<random():r+=1
a+=[r];print r
```
**[Try it online!](https://tio.run/nexus/python2#JY4xDoJAFET7PcUkNirRgIkNul7CklB8cQkfYXczrPHk1ohaTSZ5bzKrq0sQ3OjkgUFHTWgDkagyID4Zw@Qm09t8bhlGUPx9CR1jYNoasVVtXp0ODkVpQFsY/CuhftkN3B/Pf2m9KZl9AclsxfoUqT6BM7RFfznk5e@DQb9A89uHXSNN5z4)**
Keeps adding one while the number is either unavailable or a coin flip comes up heads.
Low numbers have much more probabilistic weight than high numbers.
[Answer]
## JavaScript, 62 bytes
A full program that picks a single random value in **[0 .. 1]** and expressed it as a [continued fraction](https://en.wikipedia.org/wiki/Continued_fraction), omitting elements that have been encountered before. This would produce a really infinite sequence if the initial value had an infinite precision. In practice, we are limited to what can be expressed in IEEE-854 format.
```
for(x=Math.random(),o=[];;)o[n=1/x|0,x=1/x-n,n]||alert(o[n]=n)
```
### Demo
Here is a demo limited to 50 values and writing to the console instead.
```
for(x=Math.random(),o=[],i=0;i<50;)o[n=1/x|0,x=1/x-n,n]||console.log(o[i++,n]=n)
```
[Answer]
# [Aceto](https://github.com/aceto/aceto), ~~29~~ 21 bytes
>
> Writing to STDOUT, with a consistent, unambiguous separator between integers (such as a newline), with output prior to termination of the program
>
>
>
```
p<LL
v`O
I?<\
0MLCnO
```
1. Push a zero, increment it and go in a random direction. Two of the directions lead back to the random direction field, one leads back to incrementation (so it is incremented a random amount of times).
2. When the fourth choice is made, we memorize and immediately load the value, then check whether it's contained in the stack already. If so, we jump to the origin and try again.
3. Otherwise, we load the value twice (once for printing, once for storage), print it and a newline and go back to the origin.
Massively favours low numbers, but there is a small chance for it to print any number at any point.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 23 bytes
```
yes \ |nl|xargs shuf -e
```
[Try it online!](https://tio.run/nexus/bash#@1@ZWqwQo1CTl1NTkViUXqxQnFGapqCb@v//17x83eTE5IxUAA "Bash – TIO Nexus")
`yes \` prints infinite spaces, `nl` numbers lines, `suff -e` shuffless lines without repetition.
[Answer]
# [Python 2](https://docs.python.org/2/), 39 bytes
```
f=lambda l,s:sum({1/s//1}-l)or f(l,s/2)
```
[Try it online!](https://tio.run/nexus/python2#JYwxDsMgEAR7XnElSHGIXVq6t0TEhgQJDovDleNnpyZYVLs7Gm11GEx8rQbCjWfeozxGzVqP5xBUyuBk43pS1cct5QLZ0JqiCMi2SCVcU57g6eJvK6eHmgUAY9fuPZoHQID97Bpb9lSAWgtfPOisP0rDYpaP/QM "Python 2 – TIO Nexus")
Takes a list `l` of previous outputs (as a set) and a seed `s` that's a random real from 0 to 1.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 17 bytes
```
aA=(1/Mr)c)<0?A:ß
```
[Try it online!](https://tio.run/nexus/japt#@5/oaKthqO9bpJmsaWNg72h1eP7//9GWOgrGOgpGOgqGsV/z8nWTE5MzUgE "Japt – TIO Nexus")
[Answer]
# Java 8, 136 bytes
```
import java.util.*;()->{Set s=new HashSet();for(int n;;s.add(n))System.out.print(!s.contains(n=new Random().nextInt(-1>>>1))?n+";":"");}
```
**Explanation:**
[Try it here.](https://tio.run/nexus/java-openjdk#PY@xTsNADIb3PIXJdAZ6UldODWs70IGMiMFcru1ViS/KOaVVlWcPbkEsln751@fPsevTIHCkE9lRYmsfXeFbyhneKPK1AIgsYdiRD7C9RYBTig14g07TVOjIQhI9bIFhBbPBRXWtg0BecfiGNeWDJq3v0mAUBuxcttQ0hhHrS5bQ2TSK7QddmodsfWLR29nwHfBO3KTOoOVwlo1WFsuqqpaIr/xUPpcvZYlumt1NpB@/WhX587l7dkoytSh7//EJhL8vsP33n@Yf) (Wait 60 seconds for the TIO to time-out to see the result.)
```
import java.util.*; // Required import for the Set, HashSet, and Random
()->{ // Method without parameters nor return-type
Set s=new HashSet(); // Set to keep track of numbers we've already outputted
for(int n;; // Loop infinitely
s.add(n)) // And every time we output a random number, add it to the Set
System.out.print( // Output:
!s.contains( // If we haven't outputted it yet:
n=new Random().nextInt(-1>>>1))?n+";"
// A random number (range of int: 0 - 2³²)
: // Else:
""); // Output nothing
} // End of method
```
[Answer]
## Haskell, ~~60~~ ~~59~~ 56 bytes
```
((a:b)#h)(n:r)|n=a:((h++b)#[])r|q<-a:h=(b#q)r
[1..]#[]
```
Takes the seed as an infinite list of `Bool`.
Usage example: `([1..]#[]) [True,False,False,True,True,False,True,True,False,True,False,True,True,False,False,False,False,False,False,True....]` -> `[1,4,3,5,2,7,8,6,15,...]`.
[Try it online!](https://tio.run/nexus/haskell#HYyxCoMwGIR3n@LADn@Qii24hGZx6V5HcYgkomgSjVkKvnuauh3ffXez2ZwPaL9H0Kb8SKuciUSSDyyfGFnu2WmF5ERTUSTW9cyf@@su@SRoyHfms1F0j7LsUxWNnC0ElMsArDrg0Fol4K/fA2SWNqi3tqhrBs7RNc6t/d/e/GwDbghy0XhWVYrjNY8/ "Haskell – TIO Nexus")
Start with the list `[1..]`. If the next element from the seed is `False`, skip the next element of the list. If it's a `True`, output the current element, remove it from the list and start from the beginning. `h` keeps track of the skipped elements and is prepended (-> `h++b`) to the list of available numbers in the `True` case.
[Answer]
## Clojure, ~~112 (or 119)~~ 114 bytes
Update, uses `1 / (rand)` to get an "infinite" range of [bigints](https://clojuredocs.org/clojure.core/bigint):
```
#(filter pos?(map first(reductions(fn[[v p]r](if(p r)[0 p][r(conj p r)]))[0#{}](for[i(range)](bigint(/(rand)))))))
```
Original:
```
#(filter pos?(map first(reductions(fn[[v p]r](if(p r)[0 p][r(conj p r)]))[0 #{}](for[i(range)](rand-int 2e9)))))
```
I'm hoping to see an alternative approach. Anyway, this will generate integers between 1 and 2e9, Java's integers are signed to the "real" maximum is 2147483647, which is 7 bytes longer expression (`Integer/MAX_VALUE` is even longer). `0` is used as an indication of a duplicate values and are filtered from the output sequence.
[Answer]
# Clojure, 100 bytes
```
(fn[](let[a(atom[])](filter #(if-not(some #{%}@a)(swap! a conj %))(repeatedly #(bigint(/(rand)))))))
```
This function returns an infinite sequence of integers. To get the `n`th number of this series:
```
(nth (fn[]...) n)
```
To get the first `n` terms of this series:
```
(take n (fn[]...))
```
***EDIT:*** Golfed 11 bytes (Thanks @NikoNyrh!) and added 3 bytes (changed `int` to `bigint`, to improve accuracy).
[Answer]
# JavaScript ES6, repeating call, 50 Bytes
```
c={0:9};f=_=>c[~~_]|Math.random()<.9?f(-~_):c[_]=_
```
[Answer]
# JavaScript REPL, 48 bytes
```
for(o=[];;)o[n=1/Math.random()|0]||alert(o[n]=n)
```
[Answer]
# APL, 33 bytes
```
∇P
S←⍬
→2/⍨S∊⍨X←⌊÷1-?0
S,←⎕←X
→2∇
```
[Answer]
## Mathematica, 83 bytes
```
s=5;l={};t=1;While[t<30,If[l~FreeQ~s,Print@s];l~AppendTo~s;s=RandomInteger@100;t++]
```
starting with 5
[Try it online!](https://tio.run/nexus/mathics#@19sa2qdY1tda11ia2gdnpGZkxpdYmNsoOOZFp1T51aUmhpYV6wTUJSZV@JQHGudU@dYUJCalxKSX1dsXWwblJiXkp/rmVeSmp5a5GBoYGBdoq0d@///17x83eTE5IxUAA "Mathics – TIO Nexus")
] |
[Question]
[
**This question already has answers here**:
[Run-Length Encoding [duplicate]](/questions/1015/run-length-encoding)
(19 answers)
Closed 8 years ago.
# Overview
>
> Run-length encoding — sequences in which the same data value occurs in many consecutive data elements are stored as a single data value and count
>
>
>
When using [run-length encoding](https://en.wikipedia.org/wiki/Run-length_encoding):
```
Input: ABBBCCACB
Output: 1A3B2C1A1C1B
```
This sample has an output that is larger than the input.
---
Instead, it can be simplified for binary inputs by removing the data value in the result,
```
Input: 10001110101
Output: 1331111
```
which is significantly smaller. This works because, logically, if the there is a "next subset" then it must be of a different data value than the current subset. Since there are only two possible values (1 and 0), you always know the "next" data value subset.
---
# Challenge
Implement binary run-length encoding demonstrated above.
* Take input through STDIN or suitable alternative.
* Output to STDOUT or suitable alternative.
---
# Examples
```
In: 101011101011000011
Out: 11113111242
In: 01001010001
Out: 11211131
In: 000000000
Out: 9
```
You may assume that no subsets will be longer than 9 characters (there won't be 10 adjacent zeroes).
[Answer]
# Pyth - 5 bytes
```
hMrz8
```
[Test Suite](http://pyth.herokuapp.com/?code=hMrz8&input=10001110101%0A01001010001%0A000000000&debug=0).
[Answer]
# Stuck, 5 bytes
```
soT]y
```
Takes a binary string as input and outputs an array.
## Explanation
```
soT]y
s get input string
o run-level encoding
T zip
] flatten
y pops the data values off
```
[Answer]
# Ruby, ~~37~~ 29 bytes
```
->s{s.gsub(/0+|1+/){$&.size}}
```
Test:
```
->s{s.gsub(/0+|1+/){$&.size}}["10001110101"]
=> "1331111"
```
[Answer]
# CJam, 6 bytes
```
le`s2%
```
[Try it here](http://cjam.aditsu.net/#code=le%60s2%25&input=101011101011000011).
[Answer]
## Haskell, 39 bytes
```
import Data.List
(show.length=<<).group
```
Unfortunately `group` is in `Data.List`, so I need the `import`.
Usage example: `(show.length=<<).group $ "101011101011000011"` ->
`"11113111242"`.
] |
[Question]
[
**General constraints**:
* Your program should not take any input.
* Your program should output words, 1 word/line.
* Only capital letters (A-Z) in the output.
* A word must be atleast 2 letters in length.
* A word can never be a palindrome. That is forbidden.
Rules for word-manipulations, **one or more** of these operations in **any individual order** for each new line:
1. Change one or more letter(-s) in the word 1 char distance (example: A->B, F->E) from the previous word. 'A' can **not** be 'Z' and 'Z' can **not** be 'A'.
2. Insert the letter "A" at any position.
3. Remove any letter at any position.
**Output validation**:
*Your program must output the following words: **OUTPUT, YOUR, SOURCECODE, TODAY** atleast (but not limited to) once each, in any order.*
**Sourcecode validation**:
The **first** and the **last** letter of all output words should also be part of your sourcecode in the same order as scopes: first and last letter for the first word has the highest scope, example pseudo-code:
```
<any or no code><first letter, first word>
<any or no code><first letter, second word>
<any or no code><,... ...,><any or no code>
<last letter, second word><any or no code>
<last letter, first word><any or no code>
```
1. For any word # where the actual word number **is** a fibonacci-number, the first and last letters must be **lower-case** in the sourcecode.
2. For any word # where the actual word number **is not** a fibonacci-number, the first and last letters must be **upper-case** in the sourcecode.
There is no restriction of the actual letters in the sourcecode, they can be inside strings or part of a command or anything, it is only the order that counts.
**Example valid output** (only the words YOUR and TODAY in the example):
```
YOUR
XOUAS
WOAAT
VOBAU
UOCAV
TODAW
TODAX
TODAY
```
**Example valid sourcecode for the above output**:
Since words 1, 2, 3, 5 and 8 in the example output is "fibonacci words", their first and last letter-representation in the sourcecode is lower case, leaving us with this constraint on the sourcecode:
```
yxwVuTTtyXWvUtsr
```
There could be any code around or between the letters in the sourcecode as long as the representation is there somewhere in that order.
This is code-golf, smallest sourcecode size in counted bytes wins. Competition ends: 2014-02-31.
[Answer]
## Golfscript, ~~211~~ 210
```
stuVwXYoOOOOoOOOOOOOoOOOOOOOUTTTTYXWVUTSRQPONmLKJIHGFeDCBB
{.2$<@@>{)}%+}:b;
'ROURCeCodeS'{95&}%
'()[]+\+); '7*';"OUSB" "A"+-3b "A"+'+'-3b '13*+'-2b '6*+';"UTOBUU" ;"TOCAV" ;"TODAW" '+'))[]++ '2*+
' '/{~n 1$}%-4<(@
```
Newlines added only for clarity, and can be removed. The last bits of the letter string are the name of the function and inside `'ROURCeCodeS'`.
[Test online](http://golfscript.apphb.com/?c=c3R1VndYWW9PT09Pb09PT09PT09vT09PT09PT1VUVFRUWVhXVlVUU1JRUE9ObUxLSklIR0ZlRENCQnsuMiQ8QEA%2Beyl9JSt9OmI7J1JPVVJDZUNvZGVTJ3s5NSZ9JScoKVtdK1wrKTsgJzcqJzsiT1VTQiIgIkEiKy0zYiAiQSIrJysnLTNiICcxMyorJy0yYiAnNiorJzsiVVRPQlVVIiA7IlRPQ0FWIiA7IlRPREFXIiAnKycpKVtdKysgJzIqKycgJy97fm4gMSR9JS00PChA)
Output:
```
SOURCECODE
TOURCECOD
UOURCECO
VOURCEC
WOURCE
XOURC
YOUR
OUSB
OUTCB
OUTDCB
OUTEDC
OUTFED
OUTGFE
OUTHGF
OUTIHG
OUTJIH
OUTKJI
OUTLKJ
OUTMLK
OUTNML
OUTONM
OUTPON
OUTPPO
OUTPQP
OUTPRQ
OUTPSR
OUTPTS
OUTPUT
UTOBUU
TOCAV
TODAW
TODAX
TODAY
```
[Answer]
# Java, 1091 1039 bytes
Probably not very good, but I'll give it a try. (Formatting worse will give less Bytes, but for now, let's leave it)
edit 1: used names for Vars to make comment shorter.
```
public class t {
public static void main(String[] V){
StringBuilder w = new StringBuilder("SOURCECODE");
X(w);
for(int Y=0; Y<6; Y++){
w.deleteCharAt(4);
w.setCharAt(0,(char)(w.charAt(0)+1));
X(w);
}
w.deleteCharAt(0);
for(int o=0;o<2;o++){
w.setCharAt(2,(char)(w.charAt(2)+1));
w.append('A');
w.append('A');
X(w);}
for(int O=0;O<20;O++){
if (O<15) w.setCharAt(3,(char)(w.charAt(3)+1));
w.setCharAt(4,(char)(w.charAt(4)+1));
if (O<19) w.setCharAt(5,(char)(w.charAt(5)+1));
X(w);}
w.deleteCharAt(6);
X(w);//o
for(int O=0;O<6;O++){
if (O<5) w.setCharAt(0,(char)(w.charAt(0)+1));
w.setCharAt(1,(char)(w.charAt(1)-1));
X(w);}
for(int O=1;O<4;O++){
w.deleteCharAt(2);//o
if (O<3) w.insert(4, 'A');
X(w);}
for(int O=0;O<5;O++){
if (O<3) w.setCharAt(2,(char)(w.charAt(2)+1));
w.setCharAt(4,(char)(w.charAt(4)+1));
X(w);}
//OOOOPQRsTTTTTTTTTT
//yxwVuTTtTTTTtTTAAAAAaAAAAAAAAAAAAaAAREEEEEEE
}
static void X(StringBuilder b){System.out.println(b.toString());}}
```
outputs:
```
SOURCECODE
TOURECODE
UOURCODE
VOURODE
WOURDE
XOURE
YOUR
OUSAA
OUTAAAA
OUTBBBA
OUTCCCA
OUTDDDA
OUTEEEA
OUTFFFA
OUTGGGA
OUTHHHA
OUTIIIA
OUTJJJA
OUTKKKA
OUTLLLA
OUTMMMA
OUTNNNA
OUTOOOA
OUTPPPA
OUTPQQA
OUTPRRA
OUTPSSA
OUTPTTA
OUTPUTA
OUTPUT
PTTPUT
QSTPUT
RRTPUT
SQTPUT
TPTPUT
TOTPUT
TOPUAT
TOUAAT
TOAAT
TOBAU
TOCAV
TODAW
TODAX
TODAY
```
[Answer]
# Mathematica ~~226~~ ~~221~~ 217
A little bit longer than GolfScript:
```
yxwV;
u:O_~T~OO_:=T[Print@FromCharacterCode@Select[O,#>64&]TSRQp;O+Sign[OO-O],u=OO]
"YOUR"
oOOOOOOOOOPQRsSSSEEDcBA(TT=ToCharacterCode)@"XOA@@S"~T~TT@"TODA@Y"~T~TT@"OUTPUT"t;
TT@"PTUQA?=T>@"~T~TT@"SOURCECODE"uVWXYyXWvUtsr;
```
Output:
```
YOUR
XOAS
WOBAT
VOCAU
UODAV
TODAW
TODAX
TODAY
TODAY
SPEBAX
RQFCBW
QRGDCV
PSHEDU
OTIFET
OUJGFT
OUKHGT
OULIHT
OUMJIT
OUNKJT
OUOLKT
OUPMLT
OUQNMT
OURONT
OUSPOT
OUTPPT
OUTPQT
OUTPRT
OUTPST
OUTPTT
OUTPUT
PTUQAT
QSURBSA
RRURCARB
SQURCBQAC
SPURCCAPBD
SOURCDBOCE
SOURCECODE
```
`ClearAll[T]` is necessary after usage.
[Answer]
## Windows Batch File, 557
```
::yxwVuTTtSRQPoOOOOOOOoOOOOOOOOPQRSsSSSS
::EDCBaATTTTTTTTTTTtTTTTTTTtUVXXyXWvUtsr
echo YOUR
echo XOUAS
echo WOAAT
echo VOBAU
echo UOCAV
echo TODAW
echo TODAX
echo TODAY
echo SPEBAX
echo RQFCBX
echo QRGDCV
echo PSHEDU
echo OTIFET
echo OUJGFT
echo OUKHGT
echo OULIHT
echo OUMJIT
echo OUNKJT
echo OUOLKT
echo OUPMLT
echo OUQNMT
echo OURONT
echo OUSPOT
echo OUTPPT
echo OUTPQT
echo OUTPRT
echo OUTPST
echo OUTPTT
echo OUTPUT
echo PTUQAUT
echo QSURBAUT
echo RRURCBAUT
echo SQURCCBTA
echo SPURCDCSBA
echo SOURCECRCB
echo SOURCECQDC
echo SOURCECPDD
echo SOURCECODE
```
[Answer]
## [GTB](http://timtechsoftware.com/?page_id=1309), 403
```
]yxwVuTTtSRQPoOOOOOOOoOOOOOOOOPQRSsSSSS\EDCBaATTTTTTTTTTTtTTTTTTTtUVXXyXWvUtsr[~"YOUR~"XOUAS~"WOAAT~"VOBAU~"UOCAV~"TODAW~"TODAX~"TODAY~"SPEBAX~"RQFCBX~"QRGDCV~"PSHEDU~"OTIFET~"OUJGFT~"OUKHGT~"OULIHT~"OUMJIT~"OUNKJT~"OUOLKT~"OUPMLT~"OUQNMT~"OURONT~"OUSPOT~"OUTPPT~"OUTPQT~"OUTPRT~"OUTPST~"OUTPTT~"OUTPUT~"PTUQAUT~"QSURBAUT~"RRURCBAUT~"SQURCCBTA~"SPURCDCSBA~"SOURCECRCB~"SOURCECQDC~"SOURCECPDD~"SOURCECODE
```
[Answer]
**[C/C++] 1239 chars**
Concept solution.
```
main() {
// yxwVuTTtSRQPoOOOOOOOoOOOOOOOOPQRSsSSSS
// EDCBaATTTTTTTTTTTtTTTTTTTtUVXXyXWvUtsr
printf("YOUR\n");
printf("XOUAS\n");
printf("WOAAT\n");
printf("VOBAU\n");
printf("UOCAV\n");
printf("TODAW\n");
printf("TODAX\n");
printf("TODAY\n");
printf("SPEBAX\n");
printf("RQFCBX\n");
printf("QRGDCV\n");
printf("PSHEDU\n");
printf("OTIFET\n");
printf("OUJGFT\n");
printf("OUKHGT\n");
printf("OULIHT\n");
printf("OUMJIT\n");
printf("OUNKJT\n");
printf("OUOLKT\n");
printf("OUPMLT\n");
printf("OUQNMT\n");
printf("OURONT\n");
printf("OUSPOT\n");
printf("OUTPPT\n");
printf("OUTPQT\n");
printf("OUTPRT\n");
printf("OUTPST\n");
printf("OUTPTT\n");
printf("OUTPUT\n");
printf("PTUQAUT\n");
printf("QSURBAUT\n");
printf("RRURCBAUT\n");
printf("SQURCCBTA\n");
printf("SPURCDCSBA\n");
printf("SOURCECRCB\n");
printf("SOURCECQDC\n");
printf("SOURCECPDD\n");
printf("SOURCECODE\n");
}
```
[Answer]
# PHP: ~~321~~316 bytes
I can't take much credit for this; all I did was compress and base64 encode the word sequence in [Timtech's answer](https://codegolf.stackexchange.com/a/18421/11006).
```
<?php //yxwVuTTtSRQPoOOOOOOOoOOOOOOOOPQRSsSSSSEDCBaATTTTTTTTTTTtTTTTTTTtUVXXyXWvUtsr
echo gzinflate(base64_decode("Nc5JDsAgCEDRPbdStHMLInS4/0UqNd3wvokJPGQCN1mocFEICifFYGCE4QSlFK5v3t98oHKO7SFlwHhDkTHhCVynnAxI5yErkC3j4KzT6Gzz5OzL7Bzr4tC2OrxvTjl2R+hwKpOjzJ3SkU7taMcUWK2EZqkm0UPEBL+qpRVGDe3uVglrbNkWYcb25c+S8E9O6U9K+QU="));?>
```
**Edit:** Moving the comment to the end allows a few characters to be shaved off:
```
<?php echo gzinflate(base64_decode("Nc5JDsAgCEDRPbdStHMLInS4/0UqNd3wvokJPGQCN1mocFEICifFYGCE4QSlFK5v3t98oHKO7SFlwHhDkTHhCVynnAxI5yErkC3j4KzT6Gzz5OzL7Bzr4tC2OrxvTjl2R+hwKpOjzJ3SkU7taMcUWK2EZqkm0UPEBL+qpRVGDe3uVglrbNkWYcb25c+S8E9O6U9K+QU="));//TTtSRQPoOOOOOOOoOOOOOOOOPQRSsSSSSEDCBaATTTTTTTTTTTtTTTTTTTtUVXXyXWvUtsr
?>
```
] |
[Question]
[
Find the shortest regex that matches all non-radioactive elements and nothing else in the Periodic Table of Elements. This is the inverse of [Regex for Finding Radioactive Elements](https://codegolf.stackexchange.com/questions/18011/regex-for-finding-radioactive-elements)
Radioactive Elements
```
'Technetium','Promethium','Polonium','Astatine','Radon','Francium','Radium','Actinium','Thorium','Protactinium','Uranium','Neptunium','Plutonium','Americium','Curium','Berkelium','Californium','Einsteinium','Fermium','Mendelevium','Nobelium','Lawrencium','Rutherfordium','Dubnium','Seaborgium','Bohrium','Hassium','Meitnerium','Darmstadtium','Roentgenium','Copernicium','Ununtrium','Flerovium','Ununpentium','Livermorium','Ununseptium','Ununoctium'
```
Non-radioactive Elements
```
'Hydrogen','Helium','Lithium','Beryllium','Boron','Carbon','Nitrogen','Oxygen','Fluorine','Neon','Sodium','Magnesium','Aluminium','Silicon','Phosphorus','Sulphur','Chlorine','Argon','Potassium','Calcium','Scandium','Titanium','Vanadium','Chromium','Manganese','Iron','Cobalt','Nickel','Copper','Zinc','Gallium','Germanium','Arsenic','Selenium','Bromine','Krypton','Rubidium','Strontium','Yttrium','Zirconium','Niobium','Molybdenum','Ruthenium','Rhodium','Palladium','Silver','Cadmium','Indium','Tin','Antimony','Tellurium','Iodine','Xenon','Caesium','Barium','Lanthanum','Cerium','Praseodymium','Neodymium','Samarium','Europium','Gadolinium','Terbium','Dysprosium','Holmium','Erbium','Thulium','Ytterbium','Lutetium','Hafnium','Tantalum','Tungsten','Rhenium','Osmium','Iridium','Platinum','Gold','Mercury','Thallium','Lead','Bismuth'
```
* Scored by character count in the regex.
* Use standard Perl regex (just no specialized functions).
* Assume all lower case.
* You only need to count the characters of the regex itself.
Note if you used a program to get you started and maybe post how well it did. I'll post my best attempt as an answer to get started/show an example.
Edit:
Apparently Bismuth is radioactive, but since I'm assuming the universe would die from heat death before it was ever much of a problem I'm not going to worry about it now.
[Answer]
**Character count 94**
```
y|^v|h.[lfdn]|^t[^eh]|[^te]i[rodnts]|[lp].t[^o]|ru?[bs]|ll|^..ro|^[^r][^u].{1,4}$|ca..i|ma|s.l
```
[Answer]
I was tempted (and am still debating internally) to vote to close this as a duplicate of your other regex golf question on the basis that the optimal solutions are within a constant of each other, as witness:
## 70 chars
```
^(?!no|c?u|ra|.*(e.[kht]|[^l][gecv]i|[^c]oh?[rn]iu|f.r|ac|sta|bn|has))
```
[Answer]
Small improvement on qw3n's solution (**93 characters**):
```
y|^v|h.[lfdn]|[^te]i[rodnts]|[lp].t[^o]|ru?[bs]|ll|^..ro|^[^r][^u].{1,4}$|ca..i|ma|s.l|tan|gs
```
Basically got rid of `^t[^eh]` (7 characters) clause and replaced with `tan|gs` (6 characters). Also I count qw3n's solution as 94 characters, not 95.
] |
[Question]
[
# What is the shortest way to secure a site with Javascript?
I am new to Code Golfing, and this is what I've come up with so far. I bet that this could be improved though:
## Challenge:
>
> Make a script which redirects `http://` to `https://` with the least bytes of code
>
>
>
## Attempts:
Original code (150ish BYTES!):
```
if (window.location.protocol != "https:") {
window.location.href =
"https:" + window.location.href.substring(window.location.protocol.length);
}
```
My code so far (68 bytes):
```
var l=location;':'==l.protocol[4]&&(l.href=l.href.replace(':','s:'))
```
Updated, thanks to @mypronounismonicareinstate (52 bytes):
```
l=location;l["protocol"][5]||(l["protocol"]="https")
```
Thanks to @arnauld (45 bytes):
```
(l=location)[p='protocol'][5]||(l[p]='https')
```
This works, thanks to @anderskaseorg (38 bytes):
```
with(location)protocol='https'+href[4]
```
However, this last answer would not be commonly used on a real site
Could this be minified more?
[Answer]
# ~~39~~ 38 bytes
```
with(location)protocol='https'+href[4]
```
### How it works
* If `location.href` starts with `http:`, this assigns `location.protocol = 'https:'`.
* If `location.href` starts with `https:`, this assigns `location.protocol = 'httpss'`. According to the [specification](https://html.spec.whatwg.org/multipage/history.html#dom-location-protocol), this should have no effect because `httpss` is neither `http` nor `https`. Firefox obeys this specification. Chrome seems to try to find an external app to open the `httpss` scheme ([bug](https://bugs.chromium.org/p/chromium/issues/detail?id=678633)).
] |
[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/178579/edit).
Closed 5 years ago.
[Improve this question](/posts/178579/edit)
I don't know if something like this exists already (and I'm not finding the right key words) but if not, it felt like it could be an interesting coding puzzle.
The challenge is, to take an arbitrarily nested list (no more than 2 deep), and display the content in a terminal in 2 dimensions in a 'pretty' manner. Each 'top level' dictionary element should read left - right, and the nested content for each top level index should be displayed vertically in line with its index position.
### Example input:
```
[["A"], ["B", "C"], ["D"], ["E", "F", "G"], ["H"]]
```
### Expected output (option 1):
```
A B D E H
C F
G
```
### Expected output (option 2):
In this case, 'stacks' should be as close to centralised as possible, so there is a similar amount of content above and below the top level left-to-right content.
```
E
A B D F H
C G
```
### Example input 2
List contents (for the purpose of this challenge) can be any length, but will always be the *same* length. e.g.
```
[["ABC"], ["BCD", "CDE"], ["DEF"], ["EFG", "FGH", "GHI"], ["HIJ"]]
```
Would also be valid, and should be rendered in similar fashion to example 1:
```
EFG
ABC BCD DEF EFG HIJ or ABC BCD DEF FGH HIJ
CDE FGH CDE GHI
GHI
```
Other input considerations (updated in response to comments):
* The indexes of the top level, and nested lists will never be empty.
Criteria:
* The solution should take a list of lists (nested 1 deep).
* The format of the output is flexible, but it should be clear which elements of the list are distinct at the top level (left to right, in my example separated by spaces) and which elements of the sublists are which (top to bottom, separated vertically on successive lines in my example).
* Each item in a sublist inside the list should be printed aligned with each other in the vertical direction.
* I don't care about speed/complexity/byte count, so at the highest level the criteria will be considered met by any code that can produces the desired 2D output. The winner is therefore a `popularity-contest`, in that most votes wins (edit: now that answers have started being added the winner will be the answer with the most votes 1 week from today, but new answers would always be welcome).
Bonus points:
* How 'pretty' the output is, I'll leave to you. Whether you want it to 'cascade' from the top most character as example 1, or a pseudo-centrally aligned output as example 2. Any other creative solutions are also welcomed.
* Code which can handle variable length strings in any position.
---
I'm particularly interested in Python solutions, but anything goes.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 112 107 105 bytes
-1 byte thanks to [@Kevin](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
Despite the controversy in the comments, I gave it a shot. It's my first ever codegolf submission and I had a lot of fun making it.
Tips & tricks are more than welcome!
```
a=>{o=['','',''];for(b of a)for(c=3;c--;)o[c]+=(b[c]?b[c]:' '.repeat(b[0].length))+' ';return o.join`\n`}
```
[Try it online!](https://tio.run/##TczJCsIwEAbgu08RcklDFwRvhijWbvoKMWCMqQslI7F6EZ@9tk0PwjAz/MN8d/VWT@1ujza2cDZdzTvFVx/ggpBoLMlqcMEJQY0UHVbNF0zHMaMgtAx5cOrHemhLgkjizMOotg/nMmmMvbRXSsP@wJxpX84iSO5ws8eDPX47DfYJjUkauAR1IATeYBkhgVMcIbz1e@ZHPkTF0EofVFhKStns3yAHS0IPpdN7us1GLMsnLi8msChHsqxGtNpN7G7v4e4H "JavaScript (Node.js) – Try It Online")
[Answer]
# Golfed - [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
z“”G
```
[Try it online!](https://tio.run/##y0rNyan8/7/qUcOcRw1z3f///x8dreTo5KwUq6MQreTk7KKko6Dk7OIK4bu4ukEYrm7uIAk3dw8Q5e7hCRH28PRSio0FAA "Jelly – Try It Online")
# Pretty Printing with boxes - [Python 3](https://docs.python.org/3/), 656 bytes
```
def f(matrix):
length = max(map(len, matrix))
lengths = []
for index in range(len(matrix)):
matrix[index] = ([""] * -((len(matrix[index]) - length) // 2) + matrix[index] + ([""] * ((length - len(matrix[index])) // 2)))
hlength = max(map(len, matrix[index]))
lengths.append(hlength)
matrix[index] = [item.ljust(hlength) for item in matrix[index]]
horiz = ["─" * e for e in lengths]
print("┬".join(horiz).join("┌┐"))
for row in list(zip(*matrix))[:-1]:
print("│".join(row).join("││"))
print("┼".join(horiz).join("├┤"))
print("│".join(col[-1] for col in matrix).join("││"))
print("┴".join(horiz).join("└┘"))
```
[Try it online!](https://tio.run/##fZC7TsMwFIbn9CmOPNm9CtgqMdB7eQXLQ0SdxlXrRGkQpRPqzMCQgYGRkZGRp8mLhGPHTSlELMnxOf/3n0v8mIaRviqKhQwgoBs/TdSO9RveWuplGsI1bPwdpmOKiTa4OjvWtyjgouEFUQJKL@QOv5D4eimN/mhn/Lwy5lYlEKOcEAFN6NAfUldm0IGyAYNeDy4ZtOCcb1W8xc2oFvnl43AzsBf@t1IFoNCt1vXjWOoFdRyr2YGrVG6669X9Nq1kYG@BeXOKMwDvFEaJ2huQ5NkTwemllUujdW1RFSdKpxQlH6S7ipSmFmNljOnnPHshZlTDJtGDpRXOsFcxbR6PzvudC2EuX9kdnB0iJ7ODydu9K91Xfdu3PHu3yj@Gd9GaYzO7C8anzWvaVPBnfZcsz15RWASUc3IzGBLRxnMNhiPSBjIcjcv3aDwpg/FkagqT6cz8prN5mZ7Nb4kQrPgG "Python 3 – Try It Online")
# Pretty Printing original (even spacing) - [Python 3](https://docs.python.org/3/), 371 bytes
```
def f(matrix):
length = max(map(len, matrix))
for index in range(len(matrix)):
matrix[index] = ([""] * -((len(matrix[index]) - length) // 2) + matrix[index] + ([""] * ((length - len(matrix[index])) // 2)))
hlength = max(map(len, matrix[index]))
matrix[index] = [item.ljust(hlength) for item in matrix[index]]
for row in list(zip(*matrix)):
print(" ".join(row))
```
[Try it online!](https://tio.run/##fVDNjsIgED7Xp5jMCbRqordNPGh/3VcgHJpILaalDWLs7st3oVSjm81eYPh@hm@m@zJVq7bDcBIllKQpjJY9/ZgFtVBnU8EOmqK3cEcsEMLE01lQthqkOonenqALdRZO8WjgOgS@ZqOK206EIXKYw5K8SCeawhL8lxTWa9hQWMC7f/H0j3YXbrT86jPZXcSg@m@Ip@GPpEwa0azqy@1qSPWINU5scTfwm4H7bej27qhaWtO37Mj8dRedlsoQBFxdWqmI1VI6lIQx3B8i5CEwPEQxhoBRnPh3nKS@SNLMEWmWuyvLjx7Oj5/IOR1@AA "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands)
Since this is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), I wasn't entirely sure how to answer (might have been best to not answer at all, but I figured I'd gave it a shot anyway). I've added two answers below: one [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") submission I would normally post and one 'pretty output' submission with multiple options (which isn't golfed whatsoever, might do so as well later on). *If the rules have been clarified I will update (or delete) accordingly.*
### Code-golf submission (7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)):
```
ннgð×ζ»
```
(Based on the current test cases, so assumes all string items are of the same length.)
Outputs in a similar matter as the first examples in the test cases of the challenge description.
[Try it online](https://tio.run/##yy9OTMpM/f//wt4Le9MPbzg8/dy2Q7v//4@OVnJ0claK1YlWcnJ2UdJRcnZxBfNcXN3AtKubO1DUzd0DSLp7eILFPDy9lGJjAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXiCkmdeQWmJlYKSvY6Sf2kJhK3z/8LeC3vTD284PP3ctkO7/@sc2mb/Pzo6WslRKVYnWslJSUfJGcxyAZOuQL4bELuDeR5KsbE6CiDFThBFTs4uIA0urhAtrm4QTW7uIG3uHiCNHp4QrZ5eQM2xAA).
**Explanation:**
```
н # Take the first inner list of the (implicit) input
# i.e. [["ABC"],["BCD","CDE"],["DEF"],["EFG","FGH","GHI"],["HIJ"]] → ["ABC"]
н # Pop and take the first string of that
# i.e. ["ABC"] → "ABC"
g # Pop and get it's length
# i.e. "ABC" → 3
ð× # Push a space character " " and increase it to that size
# i.e. 3 → " "
ζ # Zip/transpose (swapping rows/columns) of the (implicit) input,
# with the spaces-string as filler
# i.e. [["ABC"],["BCD","CDE"],["DEF"],["EFG","FGH","GHI"],["HIJ"]] and " "
# → [["ABC","BCD","DEF","EFG","HIJ"],[" ","CDE"," ","FGH"," "],[" "," "," ","GHI"," "]]
» # Join by newlines (which implicitly joins inner lists by spaces)
# → "ABC BCD DEF EFG HIJ\n CDE FGH \n GHI "
# (and output the result implicitly)
```
---
### 'Pretty output' submission with options:
Here we take an additional integer input as input, and 'pretty print' the output based on the option:
```
1: ABC BCD DEF EFG HIJ
CDE FGH
GHI
2: GHI
CDE FGH
ABC BCD DEF EFG HIJ
3: EFG
ABC CDE DEF FGH HIJ
BCD GHI
4: CDE EFG
ABC DEF FGH HIJ
BCD GHI
```
As for the code (it's not golfed or properly tested whatsoever, as can be seen quite easily XD):
```
i
ннgð×ζ»
ë¹<i
ннgð×ζR»
ë¹Íi
ннgð×ζøε2ä}DεθR}ø»,€нø»,
ë¹4Qi
ннgðשζøεD®¢._}ø»
ë
¹"Option ÿ is not available."
```
[Try it online](https://tio.run/##yy9OTMpM/f8/k0vhwt4Le9MPbzg8/dy2Q7u5Dq8@tNMGVTQIKny4F1X88I5zW40OL6l1Obf13I6g2sM7Du3WedS05sJeMAusxSQQWcuhlRBNLofWHVqkFw/WAVTGpXBop5J/QUlmfp7C4f0KmcUKefklColliZk5iUk5qXpK//8bc0VHKzk6OSvF6kQrOTm7KOkoObu4gnkurm5g2tXNHSjq5u4BJN09PMFiHp5eSrGxAA) or [see all options in action](https://tio.run/##yy9OTMpM/W/i6uei5F9Qkpmfp3B4v5WSzv9MLoULey/sTT@84fD0c9sO7eY6vNrPBlUwCCJ6uBdV@PCOc1uNDi@pdTm39dyOoNrDOw7t1nnUtObCXhALpMEkEFnDoZUQLS6H1h1apBdfC1XFpeCnpJBZrJCXX6KQWJaYmZOYlJOqp/S/Fgh0Dm2z/x8dreTo5KwUqxOt5OTsoqSj5OziCua5uLqBaVc3d6Com7sHkHT38ASLeXh6KcXGAgA).
[Answer]
# [PHP](https://php.net/), ~~162~~ 160 bytes
Even though this isn't code-golf, here's the golfed version anyway:
```
function($t){$r=0;while($b=array_column($t,$r,0)){if($r++==$y=0)$a=$b;foreach($a as$k=>$x)printf("% -".max(array_map('strlen',$t[$y++]))."s ",$b[$k]);echo"
";}}
```
[Try it online!](https://tio.run/##jZFda8IwFIavza8I4QwTmolzl1k2/Girm2ARdrNSSiztWtS2pJUp4m93Vjum7PPm5D0neZ9DePM439895HGOQ60z7eswz3SZpK@0zQSkch@t0qBMspRCybagZVu8xckipDCTSmu18YNssVpW1xw0bzO2TSIK2jCkhI1sM1ASZiLKdKiCmILCqoC5vIc1y3WSlhElV/iatJZqTU@8pcppsyj1IkybHEoXNobhMdYiBSYcZi7MPSbCIM4IImK32wsEZViUBZbYRQ3XJV3iceySHuGY9E96cDrMamRVxT4NhsTz@IWp85PLHn7v69WPe/3B0Towa7Np1XbLPgcMRzVi9PgbxPqLMvrkPJ2Dbjq3hBNrMjnUc9yh604vtjhO3/anz2Pz5R@7@JcP1ouRJxD6iBfXUajioDDDW9SAlB61QI0qNOwMHd@cjAXa7d8B "PHP – Try It Online")
And ungolfed:
```
function nested( $t ) {
$r = 0;
while ( $b = array_column( $t, $r, 0 ) ) {
if ( $r++ === 0 ) $a = $b;
$y = 0;
foreach( $a as $k => $x ) {
$l = max( array_map('strlen', $t[$y++] ) );
printf( "% -". $l ."s ", $b[$k] );
}
echo "\n";
}
}
```
Tests:
```
[["A"], ["B", "C"], ["D"], ["E", "F", "G"], ["H"]],
[["A"], ["B2", "C"], ["D"], ["E", "FGH", "G"], ["H"]],
[["ABC"], ["BCD", "CDE"], ["DEF"], ["EFG", "FGH", "GHI"], ["HIJ"]],
[["ABC"], ["BCD", "CDEF"], ["DEF"], ["EFG", "FGH", "GHIII"], ["HIJK"]],
[["ABC123","FOO","BCD", "CDEF","BAR"], ["BCD", "PPCG_RULEZ"], ["DEF"], ["EFG", "FGH", "GHIII","BCD", "CDE"], ["HIJK"]]
```
This will line up columns for strings of any length. Also, any number of rows will display fine too.
Output:
```
A B D E H
C F
G
A B2 D E H
C FGH
G
ABC BCD DEF EFG HIJ
CDE FGH
GHI
ABC BCD DEF EFG HIJK
CDEF FGH
GHIII
ABC123 BCD DEF EFG HIJK
FOO PPCG_RULEZ FGH
BCD GHIII
CDEF BCD
BAR CDE
```
[Answer]
## Python 3, 153 chars
Tried desperately to get this to work with a list comprehension, but here is my attempt.
```
l=len;p=print
for j in range(l(max(x,key=l))):
for i in range(l(x)):
if(l(x[i])>j):p(x[i][j],end=' ')
else:p(' '*l(x[i][0]),end=' ')
p()
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 205 bytes
Without LINQ.
Takes in a jagged array and prints the junk out.
```
p=>{var i=p.Length;int q,j=0;for(q=0;q<i;q++){var z=p[q].Length;j=z>j?z:j;}var s="";for(q=0;q<j;q++){for(var k=0;k<i;){try{s+=p[k++][q]+" ";}catch{s+=new string(' ',p[0][0].Length+1);}}s+="\n";}return s;};
```
[Try it online!](https://tio.run/##bZJdb4IwFIavx6846Y0QmNF93KziMlHUxSVLdrELxgUiahELtMVFCb@dtX5El9A2Pc05z/v2Iw35fZiyqC44oSv42nMRbbEWJgHn8MnSFQu2pQaQFfOEhMBFIGTYpWQBHwGhuqGKAG5Bwx4XTHp4vudbcFr3YQ52ndn9chcwIHbWnkV0JdaYUAG5FdsdvEyZnsuY9wjOTdM4kgc783L/Asf2oR@/Hl5iXKkitxG6kcUnmUqo6kYmN9LLKAXbl9yUThvT9KWdiQDhKgxEuFZ5Gv2eT6m3oGVlXseX47yn2TVwVUkK/VApYpEoGAWOK1xj7XpPSOQabLh6ec8yjY9vcmmKkc5ws6NUloDeBg6CqgHu@v89j/TAGSILkDMcoSbNQ5NmOHIb4ccmeOSOkYXc8UTO48m0@WhPTcrJ9F3Rd5p2@j9tJ6U8TaL2NyMimhEa6XNdyQ0Da5Xs9bIgi4QHyTL4Aw "C# (.NET Core) – Try It Online")
] |
[Question]
[
# Challenge
Given a single letter (a-z) as input, output the 2 lines of Blackalicious' *[Alphabet Aerobics](https://youtu.be/MvPnM2Q1nwU)* that correspond to that letter (ignoring the intro & outro).
---
## Rules
* You may take input by any reasonable, convenient means as long as it's permitted by [standard I/O rules](https://codegolf.meta.stackexchange.com/q/2447/58974).
* Input must either be case insensitive or consistently uppercase or lowercase.
* Output may be a newline separated string or an array/list of two strings.
* Output must be formatted (capitalisation, punctuation, etc.) exactly as it appears in the test cases below.
* Trailing spaces and newlines are not allowed.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so lowest byte count wins.
---
## Test Cases
Each code block below is what should be output for each letter a-z, respectively.
```
Artificial amateurs, aren't at all amazing
Analytically, I assault, animate things
```
```
Broken barriers bounded by the bomb beat
Buildings are broken, basically I'm bombarding
```
```
Casually create catastrophes, casualties
Canceling cats got they canopies collapsing
```
```
Detonate a dime of dank daily doin' dough
Demonstrations, Don Dada on the down low
```
```
Eating other editors with each and every energetic
Epileptic episode, elevated etiquette
```
```
Furious, fat, fabulous, fantastic
Flurries of funk felt feeding the fanatics
```
```
Gift got great, global goods gone glorious
Gettin' godly in his game with the goriest
```
```
Hit em high, hella height, historical
Hey holocaust hints, hear 'em holler at your homeboy
```
```
Imitators idolize, I intimidate
In a' instant, I'll rise in a' irate state
```
```
Juiced on my jams like Jheri curls jockin' joints
Justly, it's just me, writing my journals
```
```
Kindly I'm kindling all kinds of ink on
Karate kick type Brits in my kingdom
```
```
Let me live a long life, lyrically lessons is learned
Lame louses just lose to my livery
```
```
My mind makes marvelous moves, masses
Marvel and move, many mock what I've mastered
```
```
Niggas nap knowing I'm nice, naturally
Knack, never lack, make noise nationally
```
```
Operation, opposition, off not optional
Out of sight, out of mind, wide beaming opticals
```
```
Perfected poem, powerful punchlines
Pummeling Petty powder puffs in my prime
```
```
Quite quaint quotes keep quiet it's Quannum
Quarrelers ain't got a quarter of what we got, uh
```
```
Really raw raps, risin up rapidly
Riding the rushing radioactivity
```
```
Super scientifical sound search sought
Silencing super fire saps that are soft
```
```
Tales ten times talented, too tough
Take that, challengers, get a tune up
```
```
Universal, unique, untouched
Unadulterated, the raw uncut
```
```
Verb vice lord victorious valid
Violate vibes that are vain, make em vanish
```
```
Why I'm all well, what a wise wordsmith just
Weaving up words, weeded up on my workshift
```
```
Xerox, my X-radiation holes extra large
X-height letters and xylophone tones
```
```
Yellow-back, yak mouth, young ones' yaws
Yesterday's lawn yardsale, I yawned
```
```
Zig-Zag zombies, zooming to the zenith
Zero in, zen thoughts, overzealous rhyme ZEA-LOTS!
```
[Answer]
# [PHP](https://php.net/), 1678 bytes
```
<?=ucfirst($argn),strtr(explode(_,gzinflate(base64_decode("LVXJktw2DL3rK5BTX3qqtPV2tGMn8ZKyHTuJ44uKEiGJFkXKXNTWfH0eNXMYDQiCWB4e0C6o/qoqEnPB0fkj3dgcAhVUaejEYz5kL0y1hWultyO9IeG9iDocSRiFJ3TKB984O7Gh9uZU6ak9G8mS2o1OTK2dW2q5yF5GpSVs4Z/a3f5IrfDJLb05zLvhDQaN8DHpOsfw3hXCB2eXsT5Sl26CqrNfhelY5wNuPQ02IA7shbGLqqmzWovFwxGHCzwIkmpmsj1JYSZ8FJxLmx9Inocxe8XzBREKdUHpry70SkhBl5S5tHdD2t6bApHsqSSWKljn6a5OxKIbgYAkXsuN2JQDh2v2elGal3AlXpS3ko/EmtcCYHBQPyKHwE106oxQfYE/0Ua9H4QJqPOa/aajcygC2fYR2fasAz4MXFJKsCuuvlF92MseANGRBm3bCmcrAcaF0zmFyH5HOFQ5WImCcxoVrgWQSOnD1wCrOjQqEM+4HMYjjQzo8MUB/cUDlHutsj+A7mi17UT0gcY8+GR6o0N6CLRLkGU7O8gzt3ZrZhWKhJOSVqtHTqTJg5qVLDh7Y0gcKPcBFePioDU55Rn5Qa0c+uVDAZCuwOxC80bfxexJq4np7Vgq6qLTnr7bbkJp3y1yyd4iq0RNFQ64SSnOiHl3KgC05OHsTOWbXD4TbYKEG9Abkk9Q5xNdsnc3BJ+uE4VtYXqJ5x5Z4f2UD9LOYBP8IpM1UUpfBog94ujN7RTWtb+gZOTKN8Mye5+gRnPrp5S0RZHBJn9wUW7NRnMuaRZTTfNtZVjSbFewfMaA1dmfSbcTDFpOWoMXKJvuY4EykAUMQ8myUcMgPBmx0GTsHZWlIs0Vj0wRHXLL3hnRTTiCq6R3EXGZjE3IG1AfRs1SQjiSXRbrVdjFvodNgArHKvsQQwLLP7HjvB9QA6BWEiPNYk5zAvYD7LLnLqCFi+X5iO+97KOmJZpu1HmdfYzzvA/wR3B0S/eyxG3fP0O+OIxsE1Vg+hFFHvC1oaaJeYGo0Iq92Z+iMCbO2ad4c6yxeUR+eJoMAbNbKFOKCa97ojuSjmPDqVlO3PG3gMcgX05xSScFgmR/qedRc9GPkJyQyoouqFWFrYlLSb5TbNLOrMhj0ZHnG1aBxy4J2WeMv+nwzCfLXjnQGWHoVKSt520fmqqmgFWJeYBQwRMDwWAthbSNvqS+nDDU3VjB1VAiRWwW1BOiYSTaGLDHVyjFpIWS/odzN4JwfxshsZfLIjlMBaBG4B1DU7a0XkFG6ySEsG8HWisls3+U1WD9qtr6OcdV5M/swHCvWPF+bManucHA3LEgjjuiAl0Hee7w6WcslETy7F8WK4oHnLselthcYAEU+yxDO/kR26sp7c9j0nx9SACDeGmR1MQ/g8Nw3QbOvj487SHMUwiptYD656bxS4AVFy51g1Ts/aHd6byJiebzCcLZDHSpD9DcffZfHUopNjBFC+zy7SZ9ta8j3Jp9ch6+iYEe8cujMHmP1iYKY0oB3yMbdcq+lZYACA50Sh1GTXYtH7kCgm7cMOLfXr94eP/hy+df/gc=")))[ord($argn)%32-1],[in,at,er,al,es,th,ou,on,ic,ar]);
```
[Try it online!](https://tio.run/##LZXHyuSIAYTv8xiDDfOjXlo5MB4vymrFVg7LMijnLLWkPvit9zz72/j8VUEdqqipmn796/epmr7kyzIuP5d8GpetHspv/@F/6obzYPmP71/@ES/l8ONr@vX7l9///an/sadFvazbt/@Bj9u6LdvyLT@nbszybz9v5bseii7e8m9JvOY4@jPL0/@Sr6oXyO12wJyKLArGOAEyz9vTgzdRG8hIuSRnl1F0V/halIU2UALd8QsJzPVACzmzZn0GzUEWH@/zOPPDkwGLtkGyMqUrz43zhg/fWKuCF1T5e7ddBvXIRarmxtS2akFGHIWhSNQgxIraIxePW0okexseIcNR4MyHZ@wSMHGyvRWN7jFSYI@l4GQ1AbG3@qo4M9ZJTpqMtTiQKmAZOA9WB7M7GGfnRS@qvAuxQ9@fJgg/aGKtElGd5/7tjy/hOEWJfR@Ptp/6tYHk0I5IQT7V/qQew5ieORm8GYtXMlealosA7bZiOszGNinj4A1P6ElaZ9v2la4Z8BgzTuWRlCHdBuuuw7LJVfALzjsx7hC6CyYbacc7328pG0qM@bwU6eAhEB9Pswj5O@jGlISa8vw04nscN@lVsnARWnARr/Qb1QJBVlZ231@dQMHamtO6aDE9krB9utBpLIDvXrgkTDIEE/MfPZueo7eUvmkbAwcd7GI05sxrACppYdOY75HUXOaeulwn7dvaADTR1xDhOmCZhiQgWvgI6jirWmoruoRBlu8NiZao8pVKNmxv3iRnduQSmz2Vq4jw06U8U0bIn/XIuRhmDZgZgymwexwdsfthnCwJJsWZn/KMDhPhlTM@q86wEEnSyhNyQdeVofUMWrpg4qhtD0YtdYhSsiBmSKtj@EnAoU4SKrxI0UnbUiZ26tk6pAgjAzuPelsYzDJ2YhFawC5HqUbIPMnHpEGuOxXMWFLo3uiE5fhbApTRZ7N0UrtyDCit4blMmA1akcTIA3W4PqFbg7bHVuQ4hb5FXmMnQn4UWkxDWV/YSepwwmT4oxYo8msPUf5qaVczyf5yU618Mv0Jis4qRX73WEGvAQ9LClQVqQbLcWp2xi2ED8So4ZGHCNGFtUK22dR2YCWLlzXCa8z0kl4k5bWa5qGqT0JqXgxl0jjj8/VTD1vsTb9CjlDVQZ1ZoQYCrDYAilCMXo6mHZL6rAjf7xd9PyyEAe17fp0iUjxBAzAe58pDXglUgiC9WGiMYzkPxRF8zBQcAbXGJgYcZ2iKX2fuWkAujxqd6IkiGAobU8TY7HbTP7nZ6wzkKSKllpYBiJ22nQplb93nPLNSSny28mVe47jPgi8sYafaCeYkumosWtWAkTSIUMycFyrDfq69gOF4s4UaNIMp@tLoKfaGwWDRf460FPzPfIx5WBp3@PRWJbb@mm1g4DgX8RoG8uja8g8fYow6tJ1YVDnJuxphevj2fczeOiofxblWa1Soj6bTmJgRUQbiXCIGg1YQ8cvmV5GU/HrtVgRwIZ@j5m3BjTTzMO2@HhL78p8CkGjxsKcSjah82TR7TXeglOfEgfvp2vHORQikr6CjNKhr3m1VGtK8C1wnZ9xbC8bXiUipBhxOyqZZLhd7C9LMe0nqB2ImxqtBScKWNPeopy3kcAxPThulPeHCoBJy1nssZXhyyXWevNlUjTjJnjiKS4siKiR3nPSGEVjgfRF2RG0x2SDyRKUVDtQhn5Pp3mhS/4TqUAnBkUEuLcnSGeiikGZpDLQrSHSCcJOIli17ItUMtQgWCs2f9@oCsuJepj@@fnx8/DEu2f9P5Z8I/Bv05@2PerjF2y1fbnF3y9fbVt3G/TYOtzq9xcufH99//fprGH9L47TK/wY "PHP – Try It Online")
# [PHP](https://php.net/), 1952 bytes
```
<?=ucfirst($argn),explode(_,strtr("rtif8i3 am1eurs, 9en't 1 3l amaz0g
An3yt83ly, I assault, anim1e 50gs_roken b9ri2s b6nded by 5e bomb be1
Build0gs 9e broken, bas83ly I'm bomb9d0g_asu3ly cre1e c1astroph4, casu3ti4
Cancel0g c1s got 5ey canopi4 collaps0g_et71e a dime of dank daily do0' d6gh
Dem7str1i7s, D7 Dada 7 5e down low_10g o52 editors wi5 each and ev2y en2get8
Epilept8 episode, elev1ed etiquette_uri6s, f1, fabul6s, fantast8
Flurri4 of funk felt feed0g 5e fan18s_ift got gre1, glob3 goods g7e glori6s
Gett0' godly 0 his game wi5 5e gori4t_it em high, hella height, histor83
Hey holocaust h0ts, he9 'em holl2 1 y6r homeboy_mit1ors idolize, I 0timid1e
In a' 0stant, I'll rise 0 a' ir1e st1e_u8ed 7 my jams like Jh2i curls jock0' jo0ts
Justly, it's just me, writ0g my j6rn3s_0dly I'm k0dl0g 3l k0ds of 0k 7
K91e k8k type Brits 0 my k0gdom_et me live a l7g life, lyr83ly l4s7s is le9ned
Lame l6s4 just lose to my liv2y_y m0d mak4 m9vel6s mov4, mass4
M9vel and move, many mock wh1 I've mast2ed_iggas nap know0g I'm n8e, n1ur3ly
Knack, nev2 lack, make noise n1i73ly_p21i7, oppositi7, off not opti73
Out of sight, 6t of m0d, wide beam0g opt83s_2fected poem, pow2ful punchl04
Pummel0g Petty powd2 puffs 0 my prime_uite qua0t quot4 keep quiet it's Quannum
Qu9rel2s a0't got a qu9t2 of wh1 we got, uh_e3ly raw raps, ris0 up rapidly
Rid0g 5e rush0g radioactivity_up2 scientif83 s6nd se9ch s6ght
Silenc0g sup2 fire saps 51 9e soft_34 ten tim4 t3ented, too t6gh
Take 51, ch3leng2s, get a tune up_niv2s3, unique, unt6ched
Unadult21ed, 5e raw uncut_2b v8e lord v8tori6s v3id
Viol1e vib4 51 9e va0, make em vanish_hy I'm 3l well, wh1 a wise wordsmi5 just
Weav0g up words, weeded up 7 my workshift_2ox, my X-radi1i7 hol4 extra l9ge
X-height lett2s and xyloph7e t74_ellow-back, yak m65, y6ng 74' yaws
Y4t2day's lawn y9ds3e, I yawned_ig-Zag zombi4, zoom0g to 5e zeni5
Z2o 0, zen 56ghts, ov2ze36s rhyme ZEA-LOTS!",[in,at,er,al,es,th,ou,on,ic,ar]))[ord($argn)%32-1];
```
[Try it online!](https://tio.run/##LVXbbtw2EH3XV0yNFmsDMqDb3pCmQS5u6yRtkiZt0wSBwJVGEi2KVEhq1/JD/7rP6aHsh@UOh8O5HJ4Zjd347ccnYzdGbK2xpeXRWC91e/7vVfn7mw/Xz68uHkXfC9vqx2d3Z4@iJz/B/vFUNdI6f74cXMR8OypT83kZO2@9PT@Di2YncxJDypN1Me1ZrzyllCvoxF3SRk91PvtdruaYrkk4JyblYxJa4gqtk9aV1vSs6bC3MnN02OiaazrMtGY6mOFAB06jZ5NUNWzhnw6LfUwH4YJbul4Ni@EeBqVwU9BVluG9SgXyNGNXxFSFEy@L6LnQFaukxamj1njEgb3QZpQFVUYpMTo4Yr@FB0G1HJhMQ7XQPRYJ57VJVlRv2i56wcMWEVK5RekvtvRC1IK2IfPanDQpcypTRDLrjLiW3lhHJ7kmFlUHBGriYzYT66xlv4uuRql49DviUTqgHBMrPqYAg738OrH3XE5WbhCqSfETh0ktG6E96txFP6vJWhSBbJsJ2TasPBYGLiEl2KU7V8rGL2W3gCimVplDjr2pAcaWwz6EiH5BOFTZmhoFJ9RJHAsgEdKHrxZWhS@lJx5w2HYxdQzosGKD98UFlLvLo1@BbmeUqcTkPHWJd8F0T6twEWhnIMu8sZAHPpi5HKRPA06yNkrecSBN4uUg65Sja01iRYnzqBgHK6XISsfID2pp8V7OpwBpB8y2NMx0IwZHSvZML7tMUjVZ5ejGVD1KuzHIJXqJrAI1pV/hJKQ4IObJSg/QgoeN1bkrk/qBaD0knIDekFyAOulpG73aI3i/68nPI9MzXHfICvf7pK3NADbBLzI5BkqpbQuxQRw124XCqnBblIxcea@5jl4HqPG4xX1KyqBIb4I/uMjmcqYhqWkQfUHD/siwpMEcwfIBDVZEvwXdQjBoOWg1bqBsOnUpykAWMPQZ16VsW@FIi5F6bU6oLBSpd7ik08kit@iVFlWPLbhKahERl0mbgLwG9WFUjhmEmMw4Gif9IjYNbDxU2ObRm8kHsNw9OzbLBjUAalmjpVkMoU/AfoCdNVx5POFoeIixnrJmUjROuupUUkRvp2FYGvgtODqH8zrDadM8QD5atGw5Sc/0dRKJx2p8QT3zCFHiKZbHfjcJrachejftLStMHpGs7jtDwGzvs5BiwOsU6I6kp67k8FhWnPAbwWOQL6FpDDsJgkR/yIdWs5PrIFlRSyMqL4/Sz@U0ZuQqyTrMzJwcBh053mMUOMwSH71H@@sK11ywxNwFnRGG1mmYes40vswL8hiV6AcIOTwxEPTGkA/T6EN4lzWauupyuGozpIjJgnr8pBmJlhrscTlK0WGghH@/qToQ7k8taszlLA0OQwGoEXhPvswOdNyBjMbWEPwyHeiYyzr6SxoF1h/loXjI8SiSB3aguY8Y8a4ru/u@QcOcMCDiBVGBVwd5TvDpBgyUQPLobxZHFA84Fz0sMbnAAiiWXoa2dx2mV5mZ2zhoPl4GgEG8MEgK4ltv0Vz7lqOPl/dzCP3kfXhaQH07K3wJMOL8tiiRijldHhY6z6KnYbOGsNEtbYsVNCcX/VP4rBYzmKIEZvm8r12@jCOc6qVzLj@Jlu7w5ZHovDtjAoXRpYDvjrVcR58yQwAEG1qHF0ZN5pjdcQ4EbTejxT9dPb18/ebD@@/O4s9Sx8LHbGOhYnax72IzxUbHsoqF/XJx8RmoPHyHf8izy/TLo2/f/tPmssLHhP8H "PHP – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~1052~~ 1050 bytes
```
Oị“>ḤĖwỌḞaỌHtṂþÐṿɼ×ƙ\ṀẸqė\ȧIɓịżʂñ"ḃ⁺ụPE4ĿɲɗŀГ¡Ƭ£`BrjŒ⁷ḷḊwṡxṙṀrẇp[ṣİ|ḲṬ⁹ⱮØẎ9ṙ“¡Npḥ8Þṿfeṗẋ⁶ż⁹ẎUøịẹYḄnṁ7ZMnb~pOṙɗḣ(Œøṙụ;ḥ⁸ƇṚỊsẎʋðỴİc⁽Ċ“jɲḷȦẒḲƑzRṀ7¥(æċȧƭḶZṘḄƤ`¬?^ḞƙṾƲq“S£÷ƑØQQʠaƭỴȤ_TỴkɦṛ¥gṄĿ²ṆḍḣṾ2ɓṘ ,“¡ẏŒpḌBḢ/c{ḶẒẠf%nM⁼ṃṫQʂrɱṿ¬4ɱUƘMẸṛŻƬÑ“¡Ɱ1ṣḞµ⁶ỌrTXçYṗ$Ȥẋ-ocñƲ“ѳ{gøUƤ5]ẈṂȮɦµṂTœỌŒ1/Ẇ~œy2¦æƲȧ€ƝGb“€ẉ⁹6¬ƁṡLæẏẏẹyƈ"ð~¢5_Ɲḣ⁸¶mẇn⁷S9EṃẈM'}0ⱮƁṘṢŀ"¬U#~+ẋV“.¹ṗẸ6æAWḣ⁺tɼZĿẓṃẎ⁽C#ẇṣṡẆX½⁵ỵ€⁼µþȦ/]ȥṪ1“~Ṇẇ{KH9kẉḊẠ¢ỊẇLṖṛPḤ£\tkŻbḍṀPJ¡ȧṚ~QNNØ}ȷṬ“¢jÇṘ4ḥs"⁼ụ¦ṣƭRḤḍḄ$Ẉ9⁷JÞ,ẹƓ3ṡọRƓṃØ×ẠȮḞẹ+hṫ}5[ĿpQƇ(“-G>ɦɼ⁽⁷ĿtḌŒƤifLƥƒẠḄḊɲɲðṭŀRṚ-*ƭṭyƝ(Ṙḣ“¡o|ỤṛỊ iżẈṄʂtÞ⁵x⁵ⱮṫE⁾Ḋ`ıĖẹjp½ḳ{HlọḣoẎ“-ḃ]"ṅỊȮmJỵṖ<)ỴƝD_wȤ⁺ḣ4Mœnu⁴jḅȦ5“©ẆẸṡA*ßx⁹ƤƝO¹ṣUṡ4ė-ƲȤ⁾ḃKhTẸ⁵ḅ-⁻nẊẈ"nwỴß⁼ ɗ“ṡṖḟYIɱẉcẓ⁻tŻƊẎ- ṡİȮgṅƝ×`®*çq¡þ⁹Xe“µÑe0Ƭ¦w$ƊIḶ1\"Ɗø,7v&€/$jṠƝȧḋẓœẆĠc“¢ȷCṁ$°ṬḅṿkėḣC{AịB£AtṅẊRWGḂ2µ9ḌUḣœ⁵mⱮṛ⁷ṙḄḟkẆ¦œ“ƭÆ|ƤBċȦlĊæʠȥiƒ.nżṘḃọṬµṛHⱮW^ṗɲḄbX{ḊṾ3ḃʂ5⁸Ẇẓ)ẹ“¦+8ɼġtịḂZṄ⁽ƙḍṄØM.ƙḞȥU$ݶr¡ṅ¦3Ṗ£|ƘẎẋḌF÷ẋ⁵“⁹ƓBrḍṆdmṫ©ⱮĠ£ƬƘḟ}ėm9ʂaȧQ÷ɲṭẒḃĿƒỊ,ṛ0¬¿Ɠẉṛr!rƑWĠƭ¢/,⁼ẋ'o“@⁶⁵*ƊÇṡḳƈ/ƒĿĠỌ59KɼẸṅ¦⁶Ġƙ'ƒjḶV¡Pḃ÷Ḷıʋʋḣ³8Ẇs“ȷṪjLZ÷\ĠṫĊɼƒiB½mṾf÷²ṭ³¦ṇḷµœ¢żA¢,Mḷȷ¢æⱮBḥṿḥ£İ“¡EȷịḢ/"µİ3ȧÆỴʂJ]Uƈ{Ṙ]¿þLÞƇe/ẏ⁸ƒ÷œTḃṠyuṫḍ0ɠẸ“¢ṂṖ^YḳN:⁵ẓ⁴⁸ịṚ(NṫCṭḂḷcʂW¦ṅƇẓḷ¥b⁵QSYŀ⁽×»
```
[Try it online!](https://tio.run/##HVUJUxNJGP0rLLIrIggoqOxuuQssKyKgIMghKMKCciPiIstRJJwGL5IqEg8g5JiUGiiukOlJIFXdM10z@RedP8K@nqpAUkn3973vvfe9GegdGpo6P78nEmuZ@a@3hBrSNyZF4q1Qt57irXpCECc7Yx8FSVlJ5uWfOgSZF5r6Qvd2mJE7lgcXjWTayQ6yhbqQcWgiEb5fVaKnrEPLa8yzj6hKd3iUBrsqxgcMd8YRFyperklBdl4L8gnlxoW2MvZIkKC@PyPUQ0GiGQfJHOwxn9Del@GMXaN@TKjhm2wLSPp6BfEKbS3jODGSOItjzUwFEqGRNqEujgjiuNFeN9I9N3YP1y2vUIO5hhtH0C8R/g2FMg6VrwjyWSRcL3E9vcb2ReJY3@/JOE51FxoOWIcAaipCcwMTX/@vEUhv0HAuU/Q1M8J3hXrSLogP7Xioi0b/eAzKOMY544cvcP8BDbI4X2e@hoa0/ymOJ47N0JMmvA1aiiBfaPiZIIt6imLeZaG@A0TcvQpCiS8r355YaB8MN6Z@WyHUQGHPNDpKNJq/7@eRuowjKciCID8a0s5x6wCs0GiJddDMfXWQBw2MBI@ydbsQuCwGvQBIY@AMuo43tbJIG1jMMUMgsmC0hx3wQxxm6/Ro@hlTm3motFNoq5Df3LMUGsOHJgNqvzXcxYVCW54zPFNXqcIUfmhGMs4o37zdjfv4JLQ30OQ6jXIHNK5loPCD/SJTfDWb7c/RQOkTvomBIQI9GYb6I7DFg7IqOZC2WndxtgiI5W2fIAFjPptGmy/MXQbOh@hwhRJbffU6U8pb7CrahJVs11NC89gV3kPDygsoK2cmoHG5lZ5mHDGRiAEeiKMxdmYqhZ1mWJDvxag5JzXQVqbvVpcNAj7sCZZpAObAt7WCbIDP@9gNGuyYGDQS3VIvMn@/hu6YEZhorqG@nvlmzbi0LggPDDD09pXAZy@zpVCJMIXmQb7biCK22Is5mLQMY9ewrXxQwz3XJNTEu0Yuh2A@hhH95h40w6@Xn0Po2dJHemqsga/kokfB7VuWYsH8GCyupybgEsPNQ/19tTzMpUfQAmNgCw/hbLJrzMO/nwvyYESyO8U3c23rBm17jM6IRAgTYtysfiNpq76Ydk6wLZD2Gn9QA/2rMo4zlOzSD/QNYBoYo6dCPZquHgJqlBqVxAMYYqAzW5AlVDP3hmtAOvj7/RKMzzf/ejJphmRIqMGSOsMz8irjOB4Q6pKplEok3yCVbd6d8jy2jc6Eh/jmPSl4sBnflujeAtgtZANZuPu8CYelrupSQcaRGBEa5FrNHkF@HbNt8J5leVFW8goF1e22O9gT7U0PfILjE1gQnH9fkIUD@r65h31c4pvM20X38ljkBd1hZ0DQ2iuRxdh6bxFSTJnM4a47WMTijmzuYmr@jX9/gacKcwYE8fNNuEFFCHmwKNqy7u@xzWDGK5FHORQyRAEVmzqoy0SqnC5HZFXQYPmEpEtzNbbcFqrzKo2VQc1mnDCAMzZss/9FBifSS6q6DY8uUwW/zn/lu2x5hocqkEnKkO5iStpvhvu5@8oIhJQSL0h1SFQu8JdqlGp5jO2R2bbY3TotjU7OruFU2lmKbbT591yCuhK5cvmmldR3JmSwqk6E3SLshoiT5l9kvror8vOWGW7O0ffpyTgCiyxRBT7eoMEZLsMbK4tR/mZxO6xjMh@gqadi3K6x/M8wbEW/AZXup0EexR11e1b3DpelnU/NSAOLAyjZtSN4QU/B1wlXPuYoolGawp5gU8mX8Z/G@XqL7ue7NFCYL7dNW7s4ilZ/IurQNA86rUgPqEd8tZC79ZTuR4yVlt21krbZgBknUeDTRe6GG08e0h0s@wJQqyf6QXotjSGC9Ogm2HmJunLNvw/UtrN4ByqRH7rLSnJ3fwU9xThnfSwuI32XHsmVX8EzhMYMDw0YyXIayK@Tz5Q4DTAFQyPWEUAp/Kd49NmrWIXiku1AYTaN6fvXzAhbhpvTzprOZr46DUU7aYqd1bItvtKLGP4gn2NuFjc8TVJq4p96BURgt8jyy@WQ/kNyQ5LHeDAe1f8q10Xa/1iqjU7kc249blRKmlUn0PWknS0S@RIej8hTwA9341LDgzZjHvIzL02cn5@X/w8 "Jelly – Try It Online")
-2 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
Accepts uppercase.
Ironic that ~~only the first three bytes do the real work~~ this program doesn't do any real work, isn't it?
*(tfw when it takes you more than an hour and a half but the result is perfect)*
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~2232~~ ~~2214~~ 2176 bytes
This is an anyonymous function with one huge string hardcoded. The different outputs are separated by a `)` which is then used in `strsplit`.
```
@(n)strsplit("Artificial amateurs (...) overzealous rhyme ZEA-LOTS!",')'){n-96}
```
[Try it online!](https://tio.run/##TVXbbtxGDP0VNi@ygPVrgaIo0CTOxbk0SXM39DIrURKzI44yl93IRb/dPZx1iwK2di6cIXl4eCb02R357m787fcLbVOOafWSLx48jFlG6cV5covLXGLakYusTSaHP1/Xb0WnTh@q81uWHovbjq7JpeSKz7BXsbOUZ9il9lEMB1bauxiFY6J9KDrwQPsNFozpsqc9u9zpoyJ@sDPmkvb13A4H09kJXTdLNXfRrNrHLpW63kc2f73LDqmEdWZE3dfdLJw6fey0Z48zZpNoCtlc46DTsMKC@uC9W5PdesU5qF3naJCFKYw0OD3gI3A1BNEG3zLNnV7xEhQeXRb87ugqKF25wRF@LbUhnJR8OLVPYAHnAYuReJAcgMNJ8kzs@hmADcRHjhuxcpwYoHb6ZBXPK4bEq6Qw8I7Y8xGRwTjL98I5c/u0RAkFvkeX7bMv/n6qBoZd9NQXQz5ZJmNBJiP7jA8biDVOGCPAPrXPZMwVnckQ3dHkwx5UmEIYDDVlW6kOO30G/4bFFAbgIkqzwMYBsZqY3TsF85vb55KJFxhM845mBtT4YgIPOAQwrL6dPkdF5uBD70rK2NGczNxFauw0SgT0wMItlIjpwvuwtdeLZFfxlCF4uWWjIo7KIgOw6vRayTVYSRmQYLMBh6MktpBtI1qtsQkwXxTpgS6qt2z0zS2JvByYXqBqQn2JPtG30B8s62/Bwuv0BUI1@ktusGlxL4jgFKUW3K5BsGiU1L4UHe45fLCh7Vs/2aTWRlCaoJ2@dDWkg/QHytvK9Ai3JQsX18F6GsLSvmLzhPiORlQfcJmXEa79Fu@7xXNKoCWhLB4gKg@dvrL6GEP4PlofgEQOdrXdFbf29UYLQqLFHWC0uHhkO0BLOFpbLWhza6nXdaNS13ZsQ3ES8NBpRpGuG0QG48yRh/YPmSaXSN1KBw0ny92AUOC9w2ou0UJG7ur6A1asG8jXscVBGqxiWhvNLNs3K5/bbkdhXUOS@/E4wjZj7WzZ6ZuSDdx0pls4zyxBVEkGNuVZam@uVcpS@5bjyL112Rp42eF7wkrxtBbtZ5TNsn9bluUsKG/RBpsZDYh4LeP4b6XWCPVo3xVBLb8XB7rgJ2RgemBeMRaUsNLmXXGqZekUgxjR5CAz7JtzKzo7HQGjBV6hPVlnIZkyt39yLXV0J/yvKA@YDfdltakMBumf8l@fx5JMkrE3SHB9lqPkrX1fgCWlXlir@KPhk0k0JbAG6pRM7KDO76FH2tv5VE@MApFO8Iq77W2wWRhz@8GBeZQh@WhCG2GuwHMHngX8V@n8YFW1cxDqGTmwTmxvDcQPGecCqSlr@1GNk8l5JKsmefaLG/rZyPxR3YAHx4hQb7cMAQTKVHL7ieOejuAXKB4HG@WzctHRecHpTxK89dlR9vy/FI5A/p50EJ0j3rI0t5/nc@Nav56gX7tzIRwoBFqe4CAtJnrWUp1@Znc0mFCFugVriC0IhYWztmD5gFIArC8cw4@drX25tLJUTpvWISb@gacFXYAXodMvl2fJRC9D940hqNCPzeO1M13Gm8Wp/YrYwulyXxtncwf0Y8nQXCimUVy5weoJ/P3K1piD20A/7/BKbXhTgXNVT5hALNobmS5v3ES3eHHFWv82hNoqkAvD@pYVOXd6gxTIQLu1ks@VLbCGKMRb0NMgj/MG3bl58vDy1ZsP7396sGvapv1LL3/5@e9f7wZJ68V40fRN2979Aw "Octave – Try It Online")
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~1038~~ ~~992~~ 991 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
Ƨ, "&↑A○f8▓⁵√¹⅟²px∫Uw2ƧΚιx,═hνtεI =*f⅞aG░‛I:┘'┘‽ΟΨ▲cμ⌠└ιŗY]š⅝&◄⅞▓æCæ»TUΓ↔τ┼≥{_‰ī(*#ģ↑ι<d^¹≈4┘¡ēY←z▓Β6→y⌠$<\ē⁵owD╬#οīλ3ņ┼┘Τ‰±╥μΛš^»KƧ↑³g(y.℮ēDī*█┘E>Ν,±→ø¶ΦKƨS⅝p□D>mƨYψCκΧū╥ō⌠d#╗ΞΡ⅝¬℮te%ΝH↑]ÆυΔ⅔;ΦVO⁹}≈Rōøυ#»→▒⁄w⌡σX╔⁾560yķψ┌λTHļķ:‛ļ:Ι≠sē8□v׀N‽MXσ&⁶┌■ qŗ3C‽Βσ4:Mk{∆▒ΨƧB ;uΡ│ΣV«ŗ╤f⌡E│?æ^νΠ‚H2ō6J>uΓηΣg.R╗|$R‼↑⅞▓^tlM║⁄bd9↔▒┐^Υ|πc⁷ø○āΟ‰□28O╤>V]lαÆøΡω┼|hΦWīūEξ5M¾(Y□ξ§+d¼r▒ģƧ╔ūl■ΡΝž@h∑κ⁸<K▼α≈βī‚⁰⁽N∙!⅟EΜ²█V¾>ΩΒEt═δ√qΛ≡w]ē↔Π⁾ΤXΒ7←η╬¶┌‰RVDΥζVΒ±%÷¤ν↔2Ζ'∙;σ¶▓m⁾ΧqΥ-Ƨυ)┐`θ∫%ψτ:←√′\Ay+‰≡≈ÆMāT┼5eτ^²─κGΘ⁷¾ayψJΘ׀G↓⅜!╔¡┌*«η[░≤k║ŗ«ΘθλΖ○Η▓|ūΕ╚↓ψƧ⅜λO¶μ⁽φ⁹╝╔Z⁽╥Σ←°e+)l$»≡≡m*≡ΞΤ‽|°eŗ)3²žΛ@crO1G└ZPvƧē√≡ΣGα.Σē╝Γ⌠ķa3J¹∞'√ā⅛νξwΤ³░ κē=mģσ↔║¶øø$!π+≡⁵⁴y▒'R≥Æķ+²⁸ēΖ⁄⅛↑↑A▲}<I‼⌠Ξ′╤Β¬C+■∫ο½⅞ΝL,#rΞ█↕ο∫8rL°νnc▼Γ)═^{Φ⅟ε³‛℮lƧčGP¾3◄Ω╗g2FAm׀λ$╗→rWΖ17⅜⌡◄Ič εt≥q℮′?Æ>┐Τ'ņ¬V→⅔O¼■┼q,‼Β∆∆№ģW■°~¬l⁹ōJbbΘpRņžψ∞ζč╥⁵σθ≈≥⁸¤JÆε5]○¾f׀№ģ§:⅝æT¡⁷ΛΖΨ≤⅝χυ¼š:ÆΛ½±FυΚξū^ΧģƧ'↑KžΨ⁄²I;:χ~Ν(»%γp‽iξC⅝°§Ω≤lδ¦┼}℮≠lχ3╬L¦⁴Ο:gBš╔¶¤:ģMC%u÷⁴┘žYƧΣ0‛⁶0Δ.e_?[─9Νκ⅔⁷}ΦW#_↓δv≥╔Z⅞y4‽ūψqiΖW⁴ƨΡφ%7√‰η²¤š⁷╥⅞5┼/⅜ΔοΦR¾§l¶←∞‰σl1⅛!⁄⁴′νιvk⅓⁴⅛▓ε↑δ@╗ \η!└⅝S0┌²⁰≥¦⁵‘┐Θz,Ww#Θ⁾
```
sub-1000!
Splitting what is a word and what's a character took a while...
Explanation:
```
Ƨ, push ", "
"...‘ push https://gist.github.com/dzaima/3053b8f0222593b8fc4f5cd177ae6dec and replace all `ŗ`s with ", "s
┐Θ split on "|"
z,W get inputs index in the lowercase alphabet
w gets that item from the array
#Θ split on `"` (becuase quote has a single-char push command)
⁾ sentence case (uppercases the 1st letters)
```
[Try it here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMUE3JTJDJTIwJTIyJTI2JXUyMTkxQSV1MjVDQmY4JXUyNTkzJXUyMDc1JXUyMjFBJUI5JXUyMTVGJUIycHgldTIyMkJVdzIldTAxQTcldTAzOUEldTAzQjl4JTJDJXUyNTUwaCV1MDNCRHQldTAzQjVJJTA5JTNEKmYldTIxNUVhRyV1MjU5MSV1MjAxQkklM0EldTI1MTglMjcldTI1MTgldTIwM0QldTAzOUYldTAzQTgldTI1QjJjJXUwM0JDJXUyMzIwJXUyNTE0JXUwM0I5JXUwMTU3WSU1RCV1MDE2MSV1MjE1RCUyNiV1MjVDNCV1MjE1RSV1MjU5MyVFNkMlRTYlQkJUVSV1MDM5MyV1MjE5NCV1MDNDNCV1MjUzQyV1MjI2NSU3Ql8ldTIwMzAldTAxMkIlMjgqJTIzJXUwMTIzJXUyMTkxJXUwM0I5JTNDZCU1RSVCOSV1MjI0ODQldTI1MTglQTEldTAxMTNZJXUyMTkweiV1MjU5MyV1MDM5MjYldTIxOTJ5JXUyMzIwJTI0JTNDJTVDJXUwMTEzJXUyMDc1b3dEJXUyNTZDJTIzJXUwM0JGJXUwMTJCJXUwM0JCMyV1MDE0NiV1MjUzQyV1MjUxOCV1MDNBNCV1MjAzMCVCMSV1MjU2NSV1MDNCQyV1MDM5QiV1MDE2MSU1RSVCQksldTAxQTcldTIxOTElQjNnJTI4eS4ldTIxMkUldTAxMTNEJXUwMTJCKiV1MjU4OCV1MjUxOEUlM0UldTAzOUQlMkMlQjEldTIxOTIlRjglQjYldTAzQTZLJXUwMUE4UyV1MjE1RHAldTI1QTFEJTNFbSV1MDFBOFkldTAzQzhDJXUwM0JBJXUwM0E3JXUwMTZCJXUyNTY1JXUwMTREJXUyMzIwZCUyMyV1MjU1NyV1MDM5RSV1MDNBMSV1MjE1RCVBQyV1MjEyRXRlJTI1JXUwMzlESCV1MjE5MSU1RCVDNiV1MDNDNSV1MDM5NCV1MjE1NCUzQiV1MDNBNlZPJXUyMDc5JTdEJXUyMjQ4UiV1MDE0RCVGOCV1MDNDNSUyMyVCQiV1MjE5MiV1MjU5MiV1MjA0NHcldTIzMjEldTAzQzNYJXUyNTU0JXUyMDdFNTYweSV1MDEzNyV1MDNDOCV1MjUwQyV1MDNCQlRIJXUwMTNDJXUwMTM3JTNBJXUyMDFCJXUwMTNDJTNBJXUwMzk5JXUyMjYwcyV1MDExMzgldTI1QTF2JXUwNUMwTiV1MjAzRE1YJXUwM0MzJTI2JXUyMDc2JXUyNTBDJXUyNUEwJTIwcSV1MDE1NzNDJXUyMDNEJXUwMzkyJXUwM0MzNCUzQU1rJTdCJXUyMjA2JXUyNTkyJXUwM0E4JXUwMUE3QiUwOSUzQnUldTAzQTEldTI1MDIldTAzQTNWJUFCJXUwMTU3JXUyNTY0ZiV1MjMyMUUldTI1MDIlM0YlRTYlNUUldTAzQkQldTAzQTAldTIwMUFIMiV1MDE0RDZKJTNFdSV1MDM5MyV1MDNCNyV1MDNBM2cuUiV1MjU1NyU3QyUyNFIldTIwM0MldTIxOTEldTIxNUUldTI1OTMlNUV0bE0ldTI1NTEldTIwNDRiZDkldTIxOTQldTI1OTIldTI1MTAlNUUldTAzQTUlN0MldTAzQzBjJXUyMDc3JUY4JXUyNUNCJXUwMTAxJXUwMzlGJXUyMDMwJXUyNUExMjhPJXUyNTY0JTNFViU1RGwldTAzQjElQzYlRjgldTAzQTEldTAzQzkldTI1M0MlN0NoJXUwM0E2VyV1MDEyQiV1MDE2QkUldTAzQkU1TSVCRSUyOFkldTI1QTEldTAzQkUlQTcrZCVCQ3IldTI1OTIldTAxMjMldTAxQTcldTI1NTQldTAxNkJsJXUyNUEwJXUwM0ExJXUwMzlEJXUwMTdFQGgldTIyMTEldTAzQkEldTIwNzglM0NLJXUyNUJDJXUwM0IxJXUyMjQ4JXUwM0IyJXUwMTJCJXUyMDFBJXUyMDcwJXUyMDdETiV1MjIxOSUyMSV1MjE1RkUldTAzOUMlQjIldTI1ODhWJUJFJTNFJXUwM0E5JXUwMzkyRXQldTI1NTAldTAzQjQldTIyMUFxJXUwMzlCJXUyMjYxdyU1RCV1MDExMyV1MjE5NCV1MDNBMCV1MjA3RSV1MDNBNFgldTAzOTI3JXUyMTkwJXUwM0I3JXUyNTZDJUI2JXUyNTBDJXUyMDMwUlZEJXUwM0E1JXUwM0I2ViV1MDM5MiVCMSUyNSVGNyVBNCV1MDNCRCV1MjE5NDIldTAzOTYlMjcldTIyMTklM0IldTAzQzMlQjYldTI1OTNtJXUyMDdFJXUwM0E3cSV1MDNBNS0ldTAxQTcldTAzQzUlMjkldTI1MTAlNjAldTAzQjgldTIyMkIlMjUldTAzQzgldTAzQzQlM0EldTIxOTAldTIyMUEldTIwMzIlNUNBeSsldTIwMzAldTIyNjEldTIyNDglQzZNJXUwMTAxVCV1MjUzQzVlJXUwM0M0JTVFJUIyJXUyNTAwJXUwM0JBRyV1MDM5OCV1MjA3NyVCRWF5JXUwM0M4SiV1MDM5OCV1MDVDMEcldTIxOTMldTIxNUMlMjEldTI1NTQlQTEldTI1MEMqJUFCJXUwM0I3JTVCJXUyNTkxJXUyMjY0ayV1MjU1MSV1MDE1NyVBQiV1MDM5OCV1MDNCOCV1MDNCQiV1MDM5NiV1MjVDQiV1MDM5NyV1MjU5MyU3QyV1MDE2QiV1MDM5NSV1MjU1QSV1MjE5MyV1MDNDOCV1MDFBNyV1MjE1QyV1MDNCQk8lQjYldTAzQkMldTIwN0QldTAzQzYldTIwNzkldTI1NUQldTI1NTRaJXUyMDdEJXUyNTY1JXUwM0EzJXUyMTkwJUIwZSslMjlsJTI0JUJCJXUyMjYxJXUyMjYxbSoldTIyNjEldTAzOUUldTAzQTQldTIwM0QlN0MlQjBlJXUwMTU3JTI5MyVCMiV1MDE3RSV1MDM5QkBjck8xRyV1MjUxNFpQdiV1MDFBNyV1MDExMyV1MjIxQSV1MjI2MSV1MDNBM0cldTAzQjEuJXUwM0EzJXUwMTEzJXUyNTVEJXUwMzkzJXUyMzIwJXUwMTM3YTNKJUI5JXUyMjFFJTI3JXUyMjFBJXUwMTAxJXUyMTVCJXUwM0JEJXUwM0JFdyV1MDNBNCVCMyV1MjU5MSUyMCV1MDNCQSV1MDExMyUzRG0ldTAxMjMldTAzQzMldTIxOTQldTI1NTElQjYlRjglRjglMjQlMjEldTAzQzArJXUyMjYxJXUyMDc1JXUyMDc0eSV1MjU5MiUyN1IldTIyNjUlQzYldTAxMzcrJUIyJXUyMDc4JXUwMTEzJXUwMzk2JXUyMDQ0JXUyMTVCJXUyMTkxJXUyMTkxQSV1MjVCMiU3RCUzQ0kldTIwM0MldTIzMjAldTAzOUUldTIwMzIldTI1NjQldTAzOTIlQUNDKyV1MjVBMCV1MjIyQiV1MDNCRiVCRCV1MjE1RSV1MDM5REwlMkMlMjNyJXUwMzlFJXUyNTg4JXUyMTk1JXUwM0JGJXUyMjJCOHJMJUIwJXUwM0JEbmMldTI1QkMldTAzOTMlMjkldTI1NTAlNUUlN0IldTAzQTYldTIxNUYldTAzQjUlQjMldTIwMUIldTIxMkVsJXUwMUE3JXUwMTBER1AlQkUzJXUyNUM0JXUwM0E5JXUyNTU3ZzJGQW0ldTA1QzAldTAzQkIlMjQldTI1NTcldTIxOTJyVyV1MDM5NjE3JXUyMTVDJXUyMzIxJXUyNUM0SSV1MDEwRCUwOSV1MDNCNXQldTIyNjVxJXUyMTJFJXUyMDMyJTNGJUM2JTNFJXUyNTEwJXUwM0E0JTI3JXUwMTQ2JUFDViV1MjE5MiV1MjE1NE8lQkMldTI1QTAldTI1M0NxJTJDJXUyMDNDJXUwMzkyJXUyMjA2JXUyMjA2JXUyMTE2JXUwMTIzVyV1MjVBMCVCMCU3RSVBQ2wldTIwNzkldTAxNERKYmIldTAzOThwUiV1MDE0NiV1MDE3RSV1MDNDOCV1MjIxRSV1MDNCNiV1MDEwRCV1MjU2NSV1MjA3NSV1MDNDMyV1MDNCOCV1MjI0OCV1MjI2NSV1MjA3OCVBNEolQzYldTAzQjU1JTVEJXUyNUNCJUJFZiV1MDVDMCV1MjExNiV1MDEyMyVBNyUzQSV1MjE1RCVFNlQlQTEldTIwNzcldTAzOUIldTAzOTYldTAzQTgldTIyNjQldTIxNUQldTAzQzcldTAzQzUlQkMldTAxNjElM0ElQzYldTAzOUIlQkQlQjFGJXUwM0M1JXUwMzlBJXUwM0JFJXUwMTZCJTVFJXUwM0E3JXUwMTIzJXUwMUE3JTI3JXUyMTkxSyV1MDE3RSV1MDNBOCV1MjA0NCVCMkklM0IlM0EldTAzQzclN0UldTAzOUQlMjglQkIlMjUldTAzQjNwJXUyMDNEaSV1MDNCRUMldTIxNUQlQjAlQTcldTAzQTkldTIyNjRsJXUwM0I0JUE2JXUyNTNDJTdEJXUyMTJFJXUyMjYwbCV1MDNDNzMldTI1NkNMJUE2JXUyMDc0JXUwMzlGJTNBZ0IldTAxNjEldTI1NTQlQjYlQTQlM0EldTAxMjNNQyUyNXUlRjcldTIwNzQldTI1MTgldTAxN0VZJXUwMUE3JXUwM0EzMCV1MjAxQiV1MjA3NjAldTAzOTQuZV8lM0YlNUIldTI1MDA5JXUwMzlEJXUwM0JBJXUyMTU0JXUyMDc3JTdEJXUwM0E2VyUyM18ldTIxOTMldTAzQjR2JXUyMjY1JXUyNTU0WiV1MjE1RXk0JXUyMDNEJXUwMTZCJXUwM0M4cWkldTAzOTZXJXUyMDc0JXUwMUE4JXUwM0ExJXUwM0M2JTI1NyV1MjIxQSV1MjAzMCV1MDNCNyVCMiVBNCV1MDE2MSV1MjA3NyV1MjU2NSV1MjE1RTUldTI1M0MvJXUyMTVDJXUwMzk0JXUwM0JGJXUwM0E2UiVCRSVBN2wlQjYldTIxOTAldTIyMUUldTIwMzAldTAzQzNsMSV1MjE1QiUyMSV1MjA0NCV1MjA3NCV1MjAzMiV1MDNCRCV1MDNCOXZrJXUyMTUzJXUyMDc0JXUyMTVCJXUyNTkzJXUwM0I1JXUyMTkxJXUwM0I0QCV1MjU1NyUyMCU1QyV1MDNCNyUyMSV1MjUxNCV1MjE1RFMwJXUyNTBDJUIyJXUyMDcwJXUyMjY1JUE2JXUyMDc1JXUyMDE4JXUyNTEwJXUwMzk4eiUyQ1d3JTIzJXUwMzk4JXUyMDdF,inputs=eg__) or [test all test-cases!](https://dzaima.github.io/SOGLOnline/?code=eiU3QiUyQyUyMSUyMU8lRjhP,inputs=QSV1MDFBNyUyQyUyMCUyMiUyNiV1MjE5MUEldTI1Q0JmOCV1MjU5MyV1MjA3NSV1MjIxQSVCOSV1MjE1RiVCMnB4JXUyMjJCVXcyJXUwMUE3JXUwMzlBJXUwM0I5eCUyQyV1MjU1MGgldTAzQkR0JXUwM0I1SSUwOSUzRCpmJXUyMTVFYUcldTI1OTEldTIwMUJJJTNBJXUyNTE4JTI3JXUyNTE4JXUyMDNEJXUwMzlGJXUwM0E4JXUyNUIyYyV1MDNCQyV1MjMyMCV1MjUxNCV1MDNCOSV1MDE1N1klNUQldTAxNjEldTIxNUQlMjYldTI1QzQldTIxNUUldTI1OTMlRTZDJUU2JUJCVFUldTAzOTMldTIxOTQldTAzQzQldTI1M0MldTIyNjUlN0JfJXUyMDMwJXUwMTJCJTI4KiUyMyV1MDEyMyV1MjE5MSV1MDNCOSUzQ2QlNUUlQjkldTIyNDg0JXUyNTE4JUExJXUwMTEzWSV1MjE5MHoldTI1OTMldTAzOTI2JXUyMTkyeSV1MjMyMCUyNCUzQyU1QyV1MDExMyV1MjA3NW93RCV1MjU2QyUyMyV1MDNCRiV1MDEyQiV1MDNCQjMldTAxNDYldTI1M0MldTI1MTgldTAzQTQldTIwMzAlQjEldTI1NjUldTAzQkMldTAzOUIldTAxNjElNUUlQkJLJXUwMUE3JXUyMTkxJUIzZyUyOHkuJXUyMTJFJXUwMTEzRCV1MDEyQioldTI1ODgldTI1MThFJTNFJXUwMzlEJTJDJUIxJXUyMTkyJUY4JUI2JXUwM0E2SyV1MDFBOFMldTIxNURwJXUyNUExRCUzRW0ldTAxQThZJXUwM0M4QyV1MDNCQSV1MDNBNyV1MDE2QiV1MjU2NSV1MDE0RCV1MjMyMGQlMjMldTI1NTcldTAzOUUldTAzQTEldTIxNUQlQUMldTIxMkV0ZSUyNSV1MDM5REgldTIxOTElNUQlQzYldTAzQzUldTAzOTQldTIxNTQlM0IldTAzQTZWTyV1MjA3OSU3RCV1MjI0OFIldTAxNEQlRjgldTAzQzUlMjMlQkIldTIxOTIldTI1OTIldTIwNDR3JXUyMzIxJXUwM0MzWCV1MjU1NCV1MjA3RTU2MHkldTAxMzcldTAzQzgldTI1MEMldTAzQkJUSCV1MDEzQyV1MDEzNyUzQSV1MjAxQiV1MDEzQyUzQSV1MDM5OSV1MjI2MHMldTAxMTM4JXUyNUExdiV1MDVDME4ldTIwM0RNWCV1MDNDMyUyNiV1MjA3NiV1MjUwQyV1MjVBMCUyMHEldTAxNTczQyV1MjAzRCV1MDM5MiV1MDNDMzQlM0FNayU3QiV1MjIwNiV1MjU5MiV1MDNBOCV1MDFBN0IlMDklM0J1JXUwM0ExJXUyNTAyJXUwM0EzViVBQiV1MDE1NyV1MjU2NGYldTIzMjFFJXUyNTAyJTNGJUU2JTVFJXUwM0JEJXUwM0EwJXUyMDFBSDIldTAxNEQ2SiUzRXUldTAzOTMldTAzQjcldTAzQTNnLlIldTI1NTclN0MlMjRSJXUyMDNDJXUyMTkxJXUyMTVFJXUyNTkzJTVFdGxNJXUyNTUxJXUyMDQ0YmQ5JXUyMTk0JXUyNTkyJXUyNTEwJTVFJXUwM0E1JTdDJXUwM0MwYyV1MjA3NyVGOCV1MjVDQiV1MDEwMSV1MDM5RiV1MjAzMCV1MjVBMTI4TyV1MjU2NCUzRVYlNURsJXUwM0IxJUM2JUY4JXUwM0ExJXUwM0M5JXUyNTNDJTdDaCV1MDNBNlcldTAxMkIldTAxNkJFJXUwM0JFNU0lQkUlMjhZJXUyNUExJXUwM0JFJUE3K2QlQkNyJXUyNTkyJXUwMTIzJXUwMUE3JXUyNTU0JXUwMTZCbCV1MjVBMCV1MDNBMSV1MDM5RCV1MDE3RUBoJXUyMjExJXUwM0JBJXUyMDc4JTNDSyV1MjVCQyV1MDNCMSV1MjI0OCV1MDNCMiV1MDEyQiV1MjAxQSV1MjA3MCV1MjA3RE4ldTIyMTklMjEldTIxNUZFJXUwMzlDJUIyJXUyNTg4ViVCRSUzRSV1MDNBOSV1MDM5MkV0JXUyNTUwJXUwM0I0JXUyMjFBcSV1MDM5QiV1MjI2MXclNUQldTAxMTMldTIxOTQldTAzQTAldTIwN0UldTAzQTRYJXUwMzkyNyV1MjE5MCV1MDNCNyV1MjU2QyVCNiV1MjUwQyV1MjAzMFJWRCV1MDNBNSV1MDNCNlYldTAzOTIlQjElMjUlRjclQTQldTAzQkQldTIxOTQyJXUwMzk2JTI3JXUyMjE5JTNCJXUwM0MzJUI2JXUyNTkzbSV1MjA3RSV1MDNBN3EldTAzQTUtJXUwMUE3JXUwM0M1JTI5JXUyNTEwJTYwJXUwM0I4JXUyMjJCJTI1JXUwM0M4JXUwM0M0JTNBJXUyMTkwJXUyMjFBJXUyMDMyJTVDQXkrJXUyMDMwJXUyMjYxJXUyMjQ4JUM2TSV1MDEwMVQldTI1M0M1ZSV1MDNDNCU1RSVCMiV1MjUwMCV1MDNCQUcldTAzOTgldTIwNzclQkVheSV1MDNDOEoldTAzOTgldTA1QzBHJXUyMTkzJXUyMTVDJTIxJXUyNTU0JUExJXUyNTBDKiVBQiV1MDNCNyU1QiV1MjU5MSV1MjI2NGsldTI1NTEldTAxNTclQUIldTAzOTgldTAzQjgldTAzQkIldTAzOTYldTI1Q0IldTAzOTcldTI1OTMlN0MldTAxNkIldTAzOTUldTI1NUEldTIxOTMldTAzQzgldTAxQTcldTIxNUMldTAzQkJPJUI2JXUwM0JDJXUyMDdEJXUwM0M2JXUyMDc5JXUyNTVEJXUyNTU0WiV1MjA3RCV1MjU2NSV1MDNBMyV1MjE5MCVCMGUrJTI5bCUyNCVCQiV1MjI2MSV1MjI2MW0qJXUyMjYxJXUwMzlFJXUwM0E0JXUyMDNEJTdDJUIwZSV1MDE1NyUyOTMlQjIldTAxN0UldTAzOUJAY3JPMUcldTI1MTRaUHYldTAxQTcldTAxMTMldTIyMUEldTIyNjEldTAzQTNHJXUwM0IxLiV1MDNBMyV1MDExMyV1MjU1RCV1MDM5MyV1MjMyMCV1MDEzN2EzSiVCOSV1MjIxRSUyNyV1MjIxQSV1MDEwMSV1MjE1QiV1MDNCRCV1MDNCRXcldTAzQTQlQjMldTI1OTElMjAldTAzQkEldTAxMTMlM0RtJXUwMTIzJXUwM0MzJXUyMTk0JXUyNTUxJUI2JUY4JUY4JTI0JTIxJXUwM0MwKyV1MjI2MSV1MjA3NSV1MjA3NHkldTI1OTIlMjdSJXUyMjY1JUM2JXUwMTM3KyVCMiV1MjA3OCV1MDExMyV1MDM5NiV1MjA0NCV1MjE1QiV1MjE5MSV1MjE5MUEldTI1QjIlN0QlM0NJJXUyMDNDJXUyMzIwJXUwMzlFJXUyMDMyJXUyNTY0JXUwMzkyJUFDQysldTI1QTAldTIyMkIldTAzQkYlQkQldTIxNUUldTAzOURMJTJDJTIzciV1MDM5RSV1MjU4OCV1MjE5NSV1MDNCRiV1MjIyQjhyTCVCMCV1MDNCRG5jJXUyNUJDJXUwMzkzJTI5JXUyNTUwJTVFJTdCJXUwM0E2JXUyMTVGJXUwM0I1JUIzJXUyMDFCJXUyMTJFbCV1MDFBNyV1MDEwREdQJUJFMyV1MjVDNCV1MDNBOSV1MjU1N2cyRkFtJXUwNUMwJXUwM0JCJTI0JXUyNTU3JXUyMTkyclcldTAzOTYxNyV1MjE1QyV1MjMyMSV1MjVDNEkldTAxMEQlMDkldTAzQjV0JXUyMjY1cSV1MjEyRSV1MjAzMiUzRiVDNiUzRSV1MjUxMCV1MDNBNCUyNyV1MDE0NiVBQ1YldTIxOTIldTIxNTRPJUJDJXUyNUEwJXUyNTNDcSUyQyV1MjAzQyV1MDM5MiV1MjIwNiV1MjIwNiV1MjExNiV1MDEyM1cldTI1QTAlQjAlN0UlQUNsJXUyMDc5JXUwMTRESmJiJXUwMzk4cFIldTAxNDYldTAxN0UldTAzQzgldTIyMUUldTAzQjYldTAxMEQldTI1NjUldTIwNzUldTAzQzMldTAzQjgldTIyNDgldTIyNjUldTIwNzglQTRKJUM2JXUwM0I1NSU1RCV1MjVDQiVCRWYldTA1QzAldTIxMTYldTAxMjMlQTclM0EldTIxNUQlRTZUJUExJXUyMDc3JXUwMzlCJXUwMzk2JXUwM0E4JXUyMjY0JXUyMTVEJXUwM0M3JXUwM0M1JUJDJXUwMTYxJTNBJUM2JXUwMzlCJUJEJUIxRiV1MDNDNSV1MDM5QSV1MDNCRSV1MDE2QiU1RSV1MDNBNyV1MDEyMyV1MDFBNyUyNyV1MjE5MUsldTAxN0UldTAzQTgldTIwNDQlQjJJJTNCJTNBJXUwM0M3JTdFJXUwMzlEJTI4JUJCJTI1JXUwM0IzcCV1MjAzRGkldTAzQkVDJXUyMTVEJUIwJUE3JXUwM0E5JXUyMjY0bCV1MDNCNCVBNiV1MjUzQyU3RCV1MjEyRSV1MjI2MGwldTAzQzczJXUyNTZDTCVBNiV1MjA3NCV1MDM5RiUzQWdCJXUwMTYxJXUyNTU0JUI2JUE0JTNBJXUwMTIzTUMlMjV1JUY3JXUyMDc0JXUyNTE4JXUwMTdFWSV1MDFBNyV1MDNBMzAldTIwMUIldTIwNzYwJXUwMzk0LmVfJTNGJTVCJXUyNTAwOSV1MDM5RCV1MDNCQSV1MjE1NCV1MjA3NyU3RCV1MDNBNlclMjNfJXUyMTkzJXUwM0I0diV1MjI2NSV1MjU1NFoldTIxNUV5NCV1MjAzRCV1MDE2QiV1MDNDOHFpJXUwMzk2VyV1MjA3NCV1MDFBOCV1MDNBMSV1MDNDNiUyNTcldTIyMUEldTIwMzAldTAzQjclQjIlQTQldTAxNjEldTIwNzcldTI1NjUldTIxNUU1JXUyNTNDLyV1MjE1QyV1MDM5NCV1MDNCRiV1MDNBNlIlQkUlQTdsJUI2JXUyMTkwJXUyMjFFJXUyMDMwJXUwM0MzbDEldTIxNUIlMjEldTIwNDQldTIwNzQldTIwMzIldTAzQkQldTAzQjl2ayV1MjE1MyV1MjA3NCV1MjE1QiV1MjU5MyV1MDNCNSV1MjE5MSV1MDNCNEAldTI1NTclMjAlNUMldTAzQjclMjEldTI1MTQldTIxNURTMCV1MjUwQyVCMiV1MjA3MCV1MjI2NSVBNiV1MjA3NSV1MjAxOCV1MjUxMCV1MDM5OHphV3clMjMldTAzOTgldTIwN0UlRjhw) (warning: can take a while)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 1071 bytes
```
x';!x'%¨AλḞ↕¥βα, »Ṅ'tαt◄l²Za;ṅȦẏ£₇,İ⌊⌋§,ẋZȦṅ´%ḃ⁸ṙż⁸rḃ6ΔbΨËŀ⁶⁶bȦ†;Ḃ⌉säeḃ⁸►,ḃĿ¦İ'mḃβø»)%¥◄£Ẏα¢ȧ×ẏ₅,ŀY4s;Cȧc₇gc₂ȧ≥*εyẏ⁹X∫cẊ←ρ%ż‡ṪeαŸ]1₀fḋ₄k◄ΨdżḊİ'ÿ#G;żδτÖ$,Ḋo¬ḟ×DΦε÷~←ẇ%Eȧ:ØoŸḊ*ωwȧ‼Äd√ṘżẎ₃;£Γφ£⁹&,⁷ŻË□=Ṫ%Γ2u,⌈Λ,£Γü,ẋ=Λ;Flÿ»Jθ Ḟ₂<f¦τḞŻ€εψ=Ȧ%GïΓ≥*Ġτ,⌊⁶lσ₀sżȯ γĿ‰;GẎτ'Ŀ? ¹¬ï gÄmẆwËgø₅t%Hit¦mıḣ,Ż¦Γ□±h,Ïσ»Ψ;Hey«₈öÿ#İ,ä> 'em«‼jαtÿrȮ³₆γ%żẊo¹do∟z,ݹẊz…;Inα'ŸȦṪ,İ'∟l²Ë↕α'≥×8ṡṫ%ȷ;Jd₀¬mΨj≥₄←↕JhĖiŀ?üȷ<θ↕'ȷȷ5;ȷΨJ,¹t's⌋≈ṁm, ẇJγyȷ⌋l%◄/↓İ'mŻ?¹◄lȷk∫θ ΞkΦ;Ka►†ẏ<kγPβ>∫↕γy□<D%←Ṫṁm∟ıα«g←‡,γ₇Ψï◄⌊J$¹sλ≥e;LȦm¦oμW⌋'←ø†oγy£?√%MΨΔ`mφkŀ₂↑ṁØs,□ṡ▲;λ%√ÄdṁØ,Ṁẏ□KΦωζİ've⁶2₃%ȷNgasη@p⌋Ẇηİ'mẏ[ ,£γa;γŻK, ṅṘ←<,ṁ^□ȯ,ṄOṅ◄%ẎO,₀pΠΦ,Öf⁰t⁷ṗΦ;üt₀fŻḣg,øo₀fṁ%,ωχẎ₈Ġ£ρŀs%⁶ḟ3₉□m,λḟ>Ẏπ±⁷¬;Püψ⁷~ÿ/†ẇṖ,Γ%Ṗ¹¬mΨpṘβ%₂Q₈",□□‰Π<□□"¹t'sμQψ⌋n;⌊Q→Ėsα↕'t≥*α□ṙ_₀fωζẇe≥*, uh%γ⌊lrȧwrȧφ,Ÿṙİüp⁷¿δ;⌋□1ε□↔₁ḋ₂¥ωτ%üṗṠ₂ŀ‡{⁵θ∂ä#żġḢ;ẋ≥lṗ€⌈β⁵ȧφȦ…äeḞJs%Tλ$₂nïż◄/…,θσ□ö↔;ȧΣȦ…,ŀ½¦Ės,ġṪαŸ≥ üp%λ"⁵,ÿÜÜ,żμX;ÿ₈U⌋₇/, Ë►ω²¥Ξ%⁸βV√[⁷Övȷ⌈⁰ẏ←d;£×V√↕₆₅Ȧ…äeż▼ ,ṁ^¦m□▼´%Ẇ¿İ'm◄lẆ⌉,ωζαẇ≈eÖrżΔ#⌋≈;ẇψ▼üpẇ., wẊ)ρ ΦγyȮk⌋⌈≤%⌋XΞ, mΨX-żσ↕«½*Ξτa←⁴;X-hġ`λƒζȦ xy⌊₂₉£Yø%«ωŀ-₆k,γ⌋ẏ«Ḣu, γμȯε'ÿ?ws;ŸΨY'sĿwnŸψ⌐Ȧ¦,İ¥;ω%Zig-ZagŀΓḂs, zo₂σ†oεŻΩh;żZr↕,ΩΩŻ⁰↔s,√oż◄↑Ξ¿ψZEA-LOTS!¨-96ṁ½
```
[Try it online!](https://tio.run/##NVX9b9NWFP1XzIcXDb0OjW1omwvdNBhb2QZobCtF@yhraaENRU1ZKZOQbUKatBWwlbmwTaVZqBtoRZOUNnZiFOk9e/JP13@D3z/SnRc0KR8vfi/3nnvuueeN3ciN7@3dzBj7bmZ0Xv2Y2qm3Igt/8DVqUJ1pvJ36@cw01aflcn6CNwaHjNS/G7tp6z6vSHuOhTW5OC8XF/g6S1sLg9jx7/KXeurdkZaX@o@jAN9T@HmUHl6iqliITGnt4nUpdqW5aqSeLRdLOfF05PVfpNNiWIUd7oa1TBZLagiPt9/U@Rog8Eraukd1/k@8LpYBQtp3WWReeDdnfBKv/wxAo/iw43VZWjtEO7PqhOUPyOLGz2lrXhYeJJYORGY59Z@PUD3yvn9b2ubl1FuQdn4c8ak6HAWpN4/conPglBEF9DLJC@cgQM1P8s3UeyKWT5BLO6J5G/HS1px@Ml7/UDyajDwcOZSUZpDdDER@WBb/TP1HCNe6J@07Bq/QUlIAa5b/BpNWM2qLBemUjwGKTktHbjC5WKS/mDomAkXmMfrL@HRCdHi7nzxN9cW2ey9zN8ljHbWlvUk7SfFY7OqnxBYtqZLD1STPVEOs3YnkDkrLRUG8pdF22JFmzTgFKEk@E3b6NO7zTbGljYp8Nm0VZsTCqPBA5rT@2ZVp7mbDeupVWNTmLgI7ZV4fY@J@coe3qWp8NjLLN6RdFLugKKwx8fS4lhnJ4pkZXIVSRGcqfsG3pV2gbV2VD@L84UlZfHILcuE@HtySpmt8fo3qmchTknmOjQwOQGEgpfAHNlCOWH4/9dGqDT1uGv3DKIdvZql6FVtoF9jHyf6x0LkSmX0iiJu95OFJJm7GzfeMuEnVfsb96UwO8pSlYupbWaahYf20PRs38XBCR8cPy8KSUlrU7uO@EnncHIdewDitjJNrnB6CJKFUSKl3nLbPUuM4thXG7Vkw03tCVzLwn6vwqCCsQ50bowqcWWYEFuag@i0ERlv6D3I/R23gHzG@iN0sdycp@A5IMjgP/s3VSUTllT5IR/@SqvTwp2xSGMfI2LYs/IYU4lGOIStokU7DoLaOk5Bad4elvqkE75RPk5uUaBdl/TICKRyB/EDhV6NDOWp@dB350HJqduerdf@ipjS3PWTQdtQ@DYb8u5AtAPUioPUDwsVbWOXPYANl6NDQGYZeXKdVcplwLkurNg09p/4y6BLBtJqoCD5SGWXCm@zOl2/pLCklc91RKIarvJJYkZnTAQ4T9Y60S0iTZcp9nhxXIjV5HSH5pnFWBEkRy9uic7jbhbnUdxgt6fhSGoYergMuNXRwdA7B9yt@1Mus0Wrv6/X@rgwoOIdQiwvXDLTinCz8Hjo5qivFTHftot4l9vGPCrGiD7lG1AbTbozp6OTi/MRUvD6Dd1JgkTK3sCaC6wpnh14aSmVO@W3aUTkLD6VtdW3F5muoPK@LAASl/iqeoJ9m@Vdp7UCvRVs8PRAFYTn1/jEw9Eg4gYMYbmUHDRxS6ZRXul2PXOnP6eepfRBhrokteJlSsOky8jDvTlnsIrURr1Ol@xd4I38FJ3VyLFSepywPGTTA1qm9H9GZ6Ii/xd8MRhcMGKIDBr9Rldhzh5mmDKqVlHgD18EKmuVR41sI7iJKFs4vaobQmprSXOHBMAxOLKttMIrZh5n8jxoonUDrqgnW0m1JoO6IVoF3lAjV1OEH7gGmeKc6mMfAjghnCrAeHng9v2BnDv1zAoDH8i2mzcBJ3kwsDXaMiX4xrs4BUempjtUArTAN6hjoiQJQgyttg786RCtJfkgNp/XSGOgZC8s/Ufvf32k3drWbs8o4MWh2iVcuCE/nG0kpMntQy7gaZDU19/kG@nSDwVEJxko7uCX6ZnJG5FH1QiYXdmauRZ4S2YPY5a5yuzUjKemDV0Z7BodGI5OWcN/lmHYLY2EDlRr4nahNz8Zw0wxOASWjZ/QM5m7V0EjMevHPyW6TMf60wjtJcfDkxz1fnDn/9T5e7fngKDjlr/b29i79Bw "Husk – Try It Online")
Another lazy answer using built in compression.
] |
[Question]
[
As preparation for the nth Exodus, Noah decides to write a program that will decide If he will let animals on his ark. However, Noah wants to go back to grass roots. Thus he decides that the program should be as small and as simple as possible.
**GOAL:**
Recreate the [Contrabulous Choosematron](https://theinfosphere.org/Contrabulous_Choosematron), in a way that follows evangelical stories.
**INPUT:**
The program is simple, and elegant, and takes in 2 inputs:
The species of animal [String]
and The animal's gender [boolean]
**OUTPUT:**
The program then puts out Either 'Y' or 'N', Which determines whether or not the given animal is allowed onto the ark.
**RULES:**
Only one Animal of each species and gender is allowed on the ark. No more.
Your output can be any set of boolean values (true false, yes no, y n, yin yang) so long as they're easily distinguishable.
If your program should want to accept a list of input, rather than use STDIN, that's fine. However, each output has to be in corresponding order of the input (FIFO), as well as be in the exact same format as the input.
**This is a golf, so the lowest byte count wins, good luck**!!!!
**EXAMPLE:**
>
> "Monkey" true<
>
> y
>
> "Monkey" false<
>
> y
>
> "Monkey" false<
>
> n
>
> "Monkey with symbols" false<
>
> y
>
> "monkey" true<
>
> n
>
>
>
This is valid, as your program doesn't need to distinguish that `Monkey`, and `monkey with symbols` are the same thing species, however, `Monkey` and `monkey` are very much the same thing, and so the last critter would be denied.
[Answer]
# Perl, ~~15~~ 13 bytes
Includes +1 for `-n`
Input on STDIN (or 1 or more filenames as argument like `cat`), one animal and gender per line in any consistent notation. Prints a line with 1 for true, an empty line for false
```
perl -M5.010 -n ark.pl
```
`ark.pl`
```
say!${+lc}++
```
[Answer]
# Python 2, 72 bytes
Takes input as a list of strings of the form "animalname T". The idea is it just uses each string as an identifier and should only print true if the string has not occurred in the list so far.
```
def f(l):k=map(str.lower,l);print[j not in k[:i]for i,j in enumerate(k)]
```
Try it [here](http://ideone.com/kqhy5A)!
[Answer]
# Python, ~~54 52~~ 50 bytes
```
def f(s,l={}):x=s.lower();r=x in l;l[x]=1;return r
```
Test case is at [**ideone**](http://ideone.com/Tm8w9K)
This borrows [this neat idea](https://codegolf.stackexchange.com/a/92588/53748) from @gowrath, but extends it by using the fact that when a function is defined with a default argument that is mutable, like a dictionary, it acts as a memoisation (the object retains state between function calls).
Saved 2 bytes by returning None for truthy ("Y") and 0 for falsey ("N").
Save 2 more by (confusingly) returning False for truthy ("Y") and True for falsey ("N").
[Answer]
# Perl (35 + 1 for -p) 36
Takes input from STDIN, one animal per line in the form `animal T`. Where `T` is anything you want to be used for the gender (e.g. `T`/`F`, `M`/`F`). You could even have multi-character genders, or more than 2 genders (e.g. `male`/`female`/`apache helicopter`).
Includes all character on the line, so if you're inputting from a file you need a newline after the last animal.
```
$\=($a{lc()}?N:Y);$a{lc()}=1;$_='';
```
[Answer]
## PowerShell v3+, 33 bytes
```
$a=@();$args|%{$_-notin$a;$a+=$_}
```
Takes input as command-line arguments of strings of the form `Animal Gender` where `Gender` is (pretty much) any identifier you want. Sets an empty array `$a`, then loops through the input arguments. Places the Boolean result of the `-notin` operator on the pipeline, and adds the current element into the `$a` array. PowerShell by default is case-insensitive when comparing strings, so `Monkey f`, `monkey f`, `mOnKeY F` and other variations will all evaluate as the same.
The resulting Booleans are left on the pipeline, and output via implicit `Write-Output` happens at program completion.
### Example
```
PS C:\Tools\Scripts\golfing> .\noahs-upgraded-ark.ps1 'Monkey m' 'Monkey f' 'Monkey f' 'Monkey with symbols m' 'monkey m'
True
True
False
True
False
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 16 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)
Case sensitive solution:
```
(⍳⍴)∊(∪⍳⍨)
```
`(⍳⍴)` which indices
`∊` are member of
`⍳⍨` each entry's first occurrence in the list
Unfortunately, case-insensitivity is bulky:
```
(⍳⍴)∊(∪c⍳c←819⌶)
```
`c←819⌶` assign the lowercase function to *c*
`c⍳c` is the same as `⍳⍨c`. See explanation above.
[TryAPL online!](http://tryapl.org/?a=f%u2190%28%u2373%u2374%29%u220A%28%u222A%u2373%u2368%29%20%u22C4%20f%20%28%27mon%27%20%27M%27%29%28%27mon%27%20%27F%27%29%28%27mon%27%20%27F%27%29%28%27mons%27%20%27M%27%29%28%27mon%27%20%27M%27%29&run) (casing is not supported on TryAPL)
[Answer]
## Groovy 43 Bytes
```
{s->y=[];s.collect{!y.contains(it)&&y.add(it)}}
```
Try it here: <https://groovyconsole.appspot.com/edit/5147446497771520>
It uses a list of tuples as the input:
```
z = [new Tuple('Monkey',true), new Tuple('Monkey',false), new Tuple('Monkey',true), new Tuple('Bee',true)]
```
Which results in:
```
[true, true, false, true]
```
The add function in groovy always returns true, and in groovy tuples have inherent comparison ability for primitive objects, so the contains actually works well for strings and integers without changing it.
So, basically just check if the list contains it and add it to the list.
* If the list already contains it we get (false && N/A)
* If it does not we get (True && True) and it is added to the running list.
This is all you really need to accomplish this, if you want to tell me to turn it into a closure or something as well it would probably cap out at approximately 45-50 bytes in Groovy.
[Answer]
# Java, ~~246~~ 218 bytes
Lowered byte count thanks to Kevin!.
Takes STDIN as input, outputs weather or not the animal is allowed to board.
```
import java.util.*;class B{public static void main(String[]a){List l=new ArrayList();Scanner s=new Scanner(System.in);for(;;){String b=s.nextLine().toLowerCase();l.add(b);System.out.println(l.contains(b)?"n":"y");}}}
```
[Answer]
# Swift 2.2 169 bytes
I did not accept input from standard in I just passed an array of dictionaries to function x.
### Golfed
```
var a=[String]();let x={(d:[[String:Bool]]) in for r in d{for(s,t)in r{let y=s.lowercaseString+t.description;a.append(y);print(a.indexOf(y)==(a.count-1) ? true:false)}}}
```
### UnGolfed
```
var a=[String]();
let x={(d:[[String:Bool]]) in
for r in d{
for(s,t)in r{
let y=s.lowercaseString+t.description;
a.append(y);
print(a.indexOf(y)==(a.count-1) ? true:false)
}
}
}
```
### Input
```
x([["Monkey":true],["Monkey":false],["monkey":true],["Zebra":true]])
```
---
Also just for giggles did a crappy javascript version since I did not see anyone else do a javascript one.
## JS (ES6) 125 bytes
### Golfed
```
a=[],i=0,j=0;y=(r)=>{for(;j<r.length;j+=2){var y=r[j].toLowerCase()+r[j+1];a[i]=y;console.log(a.indexOf(y)==i++?true:false)}}a=[],i=0,j=0;y=(r)=>{for(;j<r.length;j+=2){var y=r[j].toLowerCase()+r[j+1];a[i]=y;console.log(a.indexOf(y)==i++?true:false)}}
```
### UnGolfed
```
a=[],i=0,j=0;
y=(r)=>{
for(;j<r.length;j+=2){
var y=r[j].toLowerCase()+r[j+1];
a[i]=y;
console.log(a.indexOf(y)==i++?true:false)
}
}
```
### Input
```
y(["Monkey", true, "Monkey", false, "monkey",true,"zebra",false])
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
ŒuŒQ
```
[Try it online!](https://tio.run/##y0rNyan8///opNKjkwL/H24/Ounhzhn//0dHq/vm52WnVqrrKBjG6iggcQ1wcxXKM0syFIorc5Pyc4rhcrkIg2IB "Jelly – Try It Online")
Each animal in the list (argument) is `[species, gender]`, where `gender` can either be `1` for male or `0` for female. Output is a list of `0`s and `1`s, where `0` means "not allowed" and `1` means "allowed". This is a function, and therefore a footer has been added to show the actual result.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~50~~ 48 bytes
```
->a,*s{a.map{|x|x[0].upcase!
(s<<x).count(x)<2}}
```
[Try it online!](https://tio.run/##jY5LCsMgFAD3nuJ1laRYKV2b3qAnEBcmKA2NH/KUKknObqG7dNXtMAyzpKFU09fLXdEzropZFdYtb1lcJUthVKhPpEXOc8dGn1xsc8dv@14nF1KEHgQBEM3Du5cuDYW4JC3pkRk14x8Q3lN8AhY7@Bl/DHvoE0lIACO@D7LWDw "Ruby – Try It Online")
A lambda accepting an array of `[animal, gender]` pairs and returning a boolean array.
-2 bytes: Initialize the list of seen animals as a splat arg
```
->a,*s{ # s is the list of animals seen so far, initially []
a.map{ |x| # x is the current animal
x[0].upcase! # Transform x's name in place to uppercase
(d<<x).count(x)<2 # Add x to s, and return true if s has only 1 instance of x
}
}
```
] |
[Question]
[
Write a program that converts a mathematical expression to words, evaluates the expression, and prints how the equation would be spoken aloud.
**Input**
* The input must only contain numbers and the symbols `+`, `-`, `*`, and `/`. There cannot be any whitespace in the input.
* The input does not say what the expression is equal to.
**Output**
* While order of operations must be followed in determining the numerical answer in the expression, it is not necessary to indicate this in the output (for this reason, the input cannot contain parentheses).
* Numbers must be printed in capital letters. Operations must be printed in lower case.
* Numbers must be printed in the order that they appear in the input. Then the word `equals` must be printed, then the answer.
* Numbers in the output can be negative. The word negative is written in capital letters.
* Operations and numbers must be separated by a space. There cannot be any space after the last letter is printed.
* `+` in the input gets converted to `plus` in the output. `-` in the input gets converted to `minus` in the output. `*` in the input gets converted to `times` in the output. `/` in the input gets converted to `divided by` in the output.
* Division by 0 is not allowed.
* When division results in a decimal, the number should be rounded to three decimal places and read `X POINT X X X` where the `X`s are replaced by numbers.
* Negative numbers should have `NEGATIVE in front of them.
* For simplicity, all numbers must have absolute value less than 1000.
* `0` is `ZERO` (not `NOUGHT`, `OH`, etc).
**Samples**
Inputs
```
1+2
2-3
6*2-4/1
1+1-1*1/1
2/3
413-621
```
Outputs
```
ONE plus TWO equals THREE
TWO minus THREE equals NEGATIVE ONE
SIX times TWO minus FOUR divided by ONE equals EIGHT
ONE plus ONE minus ONE times ONE divided by ONE equals ONE
TWO divided by THREE equals ZERO POINT SIX SIX SEVEN
FOUR HUNDRED THIRTEEN minus SIX HUNDRED TWENTY-ONE equals NEGATIVE TWO HUNDRED EIGHT
```
---
This is code golf, fellas. Standard CG rules apply. Shortest code in bytes wins.
[Answer]
# JavaScript ES6, ~~255~~ ~~247~~ ~~237~~ ~~225~~ 219 bytes
```
s=>(s+'='+ +eval(s).toFixed(3))[h=(a,b,l)=>' '+[a,...btoa(b).split`z`][l],t='replace'](/\D/g,l=>h('divided by',`¶)³:eºÌæ{¬Íê®j[3¦§·<`,'*+-/=.'.indexOf(l)))[t](/\d/g,l=>h('ZERO',`8Ñ3Mc³LtD1NQÅ!Q3HóHED71tó4D`,l))
```
I'll resume golfing tomorrow. Gotta sleep :/
Base encoding may cause issues. If it does, I'll add a pastebin and possibly a hex dump.
If you find any issues (or the spec changes) don't hesitate to tell me, I'll fix it as soon as possible.
## Explanation
```
s=> // Function with argument "s"
(s+'=' // Add an equal sign to the input
+ +eval(s).toFixed(3) // Add the value of the expression rounded to 3 places
)[h=(a,b,l)=> // Function h with args a,b, and l
// Return...
' '+ // A space added to...
[a,...btoa(b).split`z`] // Base decode the compressed words
[l] // Grab the correct word
,t='replace' // Alias replace command
](/\D/g, // Replace non-digits with...
l=>h( // Function h
'divided by',`¶)³:eºÌæ{¬Íê®j[3¦§·<`, // Base encoded words
'*+-/=.'.indexOf(l) // Replace operator with correct word
)
)[t]( // Replace again
/\d/g,l=> // Replaces Digits with...
h('ZERO',`8Ñ3Mc³LtD1NQÅ!Q3HóHED71tó4D` // Base encoded words
,l // The associated number
)
)
```
[Answer]
## Python 3, 268 224bytes
```
a=input()
o=eval(a)
print(*[{i:j for i,j in zip('*+-./=1234567890','times,plus,minus,POINT,divided by,equals,ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,ZERO'.split(','))}[i] for i in a+'='+('%.'+str(3*(int(o)!=o))+'f')%o])
```
A dictionary lookup for each item assuming numbers are only evaluated between 0-9. Would appreciate some feedback on this.
Explanation:
The following formats the output string with the required decimals based on the fact that in python integers evaluate as equal to the equivalent float. e.g. 1.0 == 1 Which I use to identify integer numbers.
```
('%.'+str(3*(int(o)!=o))+'f')%o
('%.0f')%o if o is an integer
('%.3f')%o if o is a decimal
```
---
edit: Dictionary generators!
[Answer]
# Pyth, ~~170~~ ~~143~~ 141 bytes
```
jdm@c"ZERO,ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,plus,minus,times,divided by,POINT,equals"\,x+jkm`kUT"+-*/.="d++z\=?q>2J`.Rvz3".0"<2JJ
```
Evaluates the input and if it ends with ".0", strips it. Then loops through a list with the numbers, then looks with their word representation.
[Answer]
# Python 2, ~~281~~ ~~223~~ ~~221~~ 219 + 5 bytes
run with: "python -Qnew golf.py" to enable float divisions
```
a=raw_input()
print" ".join("ZERO%ONE%TWO%THREE%FOUR%FIVE%SIX%SEVEN%EIGHT%NINE%NEGATIVE%times%plus%equals%minus%POINT%divided by".split("%")[ord(i)-48]for i in a+','+("%.3f"%eval(a)).replace("-",")").replace(".000",""))
```
4 bytes off thanks to Zach Gates
[Answer]
# Python 2, 628 + 5 bytes
run with: "python -Qnew golf.py" to enable float divisions
this one should spell correctly the numbers
```
import re
a=raw_input()
d,x="ZERO%ONE%TWO%THREE%FOUR%FIVE%SIX%SEVEN%EIGHT%NINE%TEN%ELEVEN%TWELVE%THIR%FOUR%FIF%SIX%SEVEN%EIGH%NINE%TWENTY%THIRTY%FORTY%FIFTY%SIXTY%SEVENTY%EIGHTY%NINETY%NEGATIVE%times%plus%equals%minus%POINT%divided by".split("%"),[]
for i in re.split("([.),/*+-])",a+','+("%.3f"%eval(a)).replace("-",")").rstrip('0').rstrip('.')):
r=""
if len(i)>2:
x+=[d[int(i)//100],"HUNDRED"];i=i[1:].lstrip("0")
if len(i)>1:
z=int(i)
if z<20:r+=d[z]+["","TEEN"][z>12];i=""
else:r+=d[z//10+18]+["-",""][i[1]<"1"];i=i[1].strip("0")
if i:
c=d[ord(i)-48]
if i<"0":x+=[c]
else:r+=c
if r:x+=[r]
print" ".join(x)
```
# Test
```
1+2
ONE plus TWO equals THREE
2-3
TWO minus THREE equals NEGATIVE ONE
6*2-4/1
SIX times TWO minus FOUR divided by ONE equals EIGHT
1+1-1*1/1
ONE plus ONE minus ONE times ONE divided by ONE equals ONE
2/3
TWO divided by THREE equals ZERO POINT SIX HUNDRED SIXTY-SEVEN
413-621
FOUR HUNDRED THIRTEEN minus SIX HUNDRED TWENTY-ONE equals NEGATIVE TWO HUNDRED EIGHTEEN
```
] |
[Question]
[
I'm a *huge* video game music fan. One of my favorite OSTs is that from [Kingdom Hearts](https://en.wikipedia.org/wiki/Kingdom_Hearts), by [Yoko Shimomura](https://en.wikipedia.org/wiki/Yoko_Shimomura).
# The challenge
Create a program or function that takes two arguments in any format: an abbreviated Kingdom Hearts game and a boss in that game. It must return the name of the song that plays for that boss. The program should handle any input case, but you can decide what case the output will be. You may assume the input is always valid. Here is a list of all the valid inputs:
```
Game Boss Song
1 Ansem Guardando nel Buio
1 Riku Forze de Male
1 Sephiroth One Winged Angel
1 Kurt Zisa The Deep End
1 Unknown Disappeared
2 Organization XIII The 13th Struggle, Dilemma, Reflection
2 Xemnas I A Fight to the Death
2 Xemnas II Darkness of the Unknown
2 Sephiroth One Winged Angel
2 Lingering Sentiment Rage Awakened
CoM Organization XIII The 13th Struggle
CoM Marluxia 1 Graceful Assasin
CoM Marluxia 2 Scythe of Petals
CoM Marluxia 3 Lord of the Castle
CoM Riku Replica The Force in You
CoM Ansem Revenge of Chaos
BBS Master Xehanort Black Powder
BBS Terra vs Master Xehanort Rage Awakened
BBS Vanitas Enter the Darkness
BBS Ventus vs Vanitas The Key
BBS Vanitas Remnant Enter the Void
BBS Terranort Dismiss
BBS Mysterious Figure Dark Impetus
Coded Riku Riku
Coded Pete Rowdy Rumble
Coded Maleficent Vim and Vigor
Coded Sora's Heartless Guardando nel Buio
Coded Roxas The Other Promise
Days Xion Vector to the Heavens
Days Riku Another Side
DDD Anti Black Coat Nightmare Dread of Night
DDD Ansem I L'Eminenza Oscura I
DDD Ansem II L'Eminenza Oscura II
DDD Xemnas L'Oscurita dell'Ignoto
DDD Young Xehanort L'Impeto Oscuro
DDD Armored Ventus Nightmare Eye of Darkness
DDD Julius The Encounter
```
# Scoring
Your score is *not* your byte count. You do not need to implement the entire list, but you *must* implement at least 10 items. Your score is `byte count / # of items implemented`. For instance, say you write a 90-byte program that implements 25 items of the above table. Your score would be `90/25=3.6`. Lowest score wins.
# Bonus
* -1 off your score of you implement an additional item, from Final Fantasy:
```
Game Boss Song
XV Behemoth Omnis Lacrima
```
**AND** make it so that any other requested bosses from `XV` return `TBD`.
* -0.5 if your code also takes in the games `1.5` and `2.5`, which take the same bosses as `1` and `2` but return the song name followed by `(Orchestrated)`.
* Another -0.5 if your program accepts bosses from `CoM` and `Days` when given `1.5` and accepts bosses from `Coded` and `BBS` when given `2.5`. It must return the songs followed by `(Orchestrated)`.
If you know of any other significant bosses I left out, let me know in the comments.
Also, I'm hoping I'm not the only person here who has *memorized* all of these songs...
[Answer]
# Ruby ~~134~~ 131/10=13.1
```
->g,b{"Rowdy Rumble|Dread of Night|Riku|One Winged Angel|Rage Awakened|Vim and Vigor|The Key|The 13th Struggle".split(?|)[b.ord%8]}
```
This is a lambda function, which takes arguments for the game and the boss. The argument for the game is actually ignored by the code, but the OP has clarified that the argument cannot be eliminated.
In fact it only uses the first letter of the boss's name. the ASCII code is taken modulo 8 (this gives the same answer for a given letter, regardless of case) and one of 8 song titles is returned. As two song titles appear twice, this covers a total of 10 elements:
```
Game Boss Array Song
index
Coded Pete 0 Rowdy Rumble
DDD Anti Black Coat Nightmare 1 Dread of Night
Coded Riku 2 Riku
1 Sephiroth 3 One Winged Angel
2 Sephiroth 3 One Winged Angel
2 Lingering Sentiment 4 Rage Awakened
BBS Terra vs Master Xehanort 4 Rage Awakened
Coded Maleficent 5 Vim and Vigor
BBS Ventus vs Vanitas 6 The Key
CoM Organization XIII 7 The 13th Struggle
```
It was a lucky coincidence that the Ascii codes for L and T give the same result modulo 8, so both incidences of Rage Awakened could be covered.
Call the function as in this test program:
```
f=->g,b{"Rowdy Rumble|Dread of Night|Riku|One Winged Angel|Rage Awakened|Vim and Vigor|The Key|The 13th Struggle".split(?|)[b.ord%8]}
B=gets #get boss name from stdin
puts f.call("dummy",B) #call function, and output return value to stdout
```
[Answer]
# Pyth, 144/10 = 14.4
```
@c"|L'Impeto Oscuro|Riku|Eye of Darkness|Disappeared||Another Side|Forze de Male|Dread of Night|Rowdy Rumble|One Winged Angel"\|%.hrzZ11
```
Incredibly simple hash table, with the 'coincidence' of re-using the song 'One Winged Angel' twice. The above program recognizes the following items correctly:
```
ddd young xehanort | L'Impeto Oscuro
coded riku | Riku
ddd armored ventus nightmare | Eye of Darkness
1 mysterious figure | Disappeared
days riku | Another Side
1 riku | Forze de Male
ddd anti black coat nightmare | Dread of Night
coded pete | Rowdy Rumble
1 sephiroth | One Winged Angel
2 sephiroth | One Winged Angel
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 7 years ago.
[Improve this question](/posts/53547/edit)
**Your Goal**: Estimate pi to at least 10 decimal places. The format is your choice - it can output as a number, as a string, as an output to STDOUT, etc.
Seems easy, right? But wait, it's not as simple as it seems...
**The Rules**: You get exactly 10 function calls (this includes operators). These functions cannot be ones that naturally induce or define pi, such as the arc-trig functions or a function converting degrees to radians (this also includes any function that operates as a "solver", such as one that can find roots of `sin(x)`). If your language has complex number capabilities, this capability cannot be used. All functions must be part of your languages built-in functions or within a standard library (loading the library does not count as an operation, but it must be a standard library, not just a popular one).
All function calls must be crucial to your code - this means that you cannot use division by one, or factorial of two. You also cannot use any literal (except for three digits in the form of one, two, or three integers)\*, reading of files of any sort, or a code's ability to convert itself into values (such as a function to get the name of a variable as a string).
\*Note: an exception is made for format strings for languages that require them for output. However, only formats, not actual contents, can be found in the format strings, so you can have `printf("%f%f",x,y)`, but not `printf("%f.%f",x,y)`.
Loops may be used, but will eat up your function calls - the 10 function calls are calls, not total functions used. Assignment does not count as an operation, but operations such as array slicing (including obtaining a single value from an array) count, in which case a[1] would count as two bytes (for `[]`).
If you think you've found a loophole for the rules, then it's also against the rules. This is *not* a challenge for finding the best bending of the rules, or the best way of abusing a minor oversight in the challenge question... if your instinct is to call it a "loophole", then post it as a comment to help close it.
**Scoring**: This is code bowling, so you're after the highest score. But it's not the total number of bytes in your code that is being counted.
Instead, it's the sum of bytes in the functions being used. That is, if you use `4*cos(2/3)` (which happens to be approximately 3.14355), then you have three functions - `*`, `cos`, and `/`, with the total being 5 bytes. If you were to use, for instance (using Julia), `sum(map(n->1/n,1:4))`, then the operations are `sum`, `map`, `/`, and `:`, for 8 bytes... but as 1/n is being called four times, it uses 7 function calls (`sum`, `map`, four instances of `/`, and `:`). User-made functions do not count towards either the function call allowance or the byte count (note: functions used *in* those user-made functions *do* count).
**Additional emphasis**: The point, here, is to find the best way to abuse your language's longest built-in/standard function names in the context of calculating pi. More digits of pi aren't necessary, but I will personally be more likely to upvote an answer that gets more digits than necessary.
Remember, since you're after long function names, you should probably avoid unary and binary operators, as most of these have full function equivalents (in Julia, for instance, `*` can be replaced by `prod`).
**Quick Summary**: You have 10 built-in function calls (includes operators/subroutines/etc). You must estimate pi to 10 decimal places. You can use a *total* of 3 characters for integer literals (so you can have 1 and 36, or 1 and 2 and 3, or 328, but you can't have 22 and 49). Score is count of built-in function name bytes (if the user defines the name, it doesn't count). No functions that calculate or use pi directly. No complex numbers. This is not a challenge to find loopholes.
[Answer]
# R, ~~34~~ 42 Points
I think I have complied with all the rules and scored it correctly.
**Edit** Turns out not complying with the rules in the first place was a bit of a bonus.
Use this formula to calculate pi `(63/25)x((17+sqrt(5)*15)/(7+sqrt(5)*15))`
```
# set up the required numbers
a<-5
b<-2
# Calculate 5^.5 * 15 3 Operations 11 Bytes
c<-prod(sqrt(a),sum(a,a,a))
# Calculate (17 + c) / (7 + C) 3 Operations 7 Bytes
d<-sum(a,a,a,b,c)/sum(a,b,c)
# Calculate (63/25)*d 3 Operations 19 Bytes
pi<-prod(as.double(paste0(b,'.',a,b)),d)
# Output pi showing all digits 1 Operations 5 Bytes
strwrap(pi)
```
Test run
```
> a<-5
> b<-2
> c<-prod(sqrt(a),sum(a,a,a)) # 3 Operations 11 Bytes
> d<-sum(a,a,a,b,c)/sum(a,b,c) # 3 Operations 7 Bytes
> pi<-prod(as.double(paste0(b,'.',a,b)),d) # 3 Operations 19 Bytes
> strwrap(pi) # 1 Operations 5 Bytes
[1] "3.14159265380569"
```
[Answer]
## C#
Exactly 10 function calls and 3 numeric literals.
```
using System;
using System.Linq;
namespace ConsoleApplication2
{
internal class Program
{
private static void Main(string[] args)
{
/*3:*/
int a = 3; //0 calls: 0
/*14->15:*/
int b = 14; //0 calls: 0 + 0 = 0
/*14:*/
int c = (b)++; //1 call: 0 + 1 = 1
/*926:*/
int d = 926; //0 calls: 1 + 0 = 1
/*53:*/
int e = (a*c) + (a*a); //3 calls: 1+3 = 4
//3*14 + 3*3 = 42+9 = 51
e++; //1 call: 4 + 1 = 5
e++; //1 call: 5 + 1 = 6
/*5:*/
char f = e.ToString().ToCharArray().First(); //3 call: 6 + 3 = 9
Console.WriteLine("{0}.{1}{2}{3}{4}{5}", a, c, b, d, e, f); //1 call: 9 + 1 = 10
}
}
}
```
Outputs: 3.1415926535
[Answer]
# C, 23 bytes
I think this is correct now...
```
#include <stdio.h>
#include <math.h>
main()
{
double pi= (double)22 / 7; /* 1 */
pi+=sin(pi); /* 1 + 3 bytes = 4 */
pi+=sin(pi); /* 1 + 3 bytes = 4 */
pi+=sin(pi); /* 1 + 3 bytes = 4 */
pi+=sin(pi); /* 1 + 3 bytes = 4 */
printf("%.10f", pi); /* 6 bytes = 6 */
return 0;
}
```
[Answer]
# Racket, 72 bytes
Gotta love those verbose built-in names!
```
((lambda() ; lambda is a Racket-defined function too, 6 bytes
(define-values (a b) (integer-sqrt/remainder 491)) ; 13 (define-values) + 22 (integer-sqrt/remainder) = 35 (on this line alone). a and b are 22 and 7 respectively
(define-values (q) (/ a b)) ; 13 (define-values) + 1 (/) = 14
(define-values (c) (+ (sin q) q)) ; 13 + 1 + 3 = 17
(+ (sin c) c) ; 1 + 3 = 4
)) ; total: 6 + 35 + 14 + 17 + 4 = 72
```
With the amount of precision that `in-exact` numbers in Racket have, this is actually equal to pi such that `(- pi (lambda...)` outputs `0.0`.
Also, I know this is a realllllllllllly old challenge. But all of the current challenge answers do horribly in comparison to this bowl, so I had to do it.
] |
[Question]
[
# Puzzle
There are some mirrors located throughout a grid. A ray of light enters the grid from some position. It travels through the grid in a straight line trying to escape. On encountering with a mirror it changes its course by 90 degrees. This continues to happen until it breaks free from the maze. The challenge is simply this: **Guide the light ray to an exit.**
---
# Elements
* **Grid** - The grid is a square composed of *n x n* blocks. A block is either empty or contains a mirror.

* **Mirror** - Both faces of the mirror are reflective. They have two orientations - 45o left or right(see figure).

* **Light ray** - It always travels straight and reflects from the mirror surface upon incidence (i=r=45o).
---
# Code
* **Input** - The user will input 3 values - *n*, *m* and *s*.
*n* represents the value of grid's length (no of blocks). You are free to choose the type of this value; It could be a string, integer, float or any other data type. This cannot be zero/empty.
*m* is a sequence of two values indicating where the mirrors are and what their orientations will be. You are free to choose the sequence type. For example, if *0* and *1* are the two orientations of the mirror and each block in the grid is marked from 1 to n2, you may input a sequence such as *{(5,0), (3,1), (6,0),...}*. Since you're free to choose this type, you may even squeeze them in to a string and decode it properly. In other words, it only needs to be legible to your code. This can be zero for no mirrors.
*s* represents the starting position of the light ray. Again, you may choose this type based on the rest of your code. Any form of data is valid.
*NOTE* The user is responsible for inputing the correct values. If they enter an invalid value such as placing a mirror out of the grid or not providing a starting position, your code doesn't have to deal with it.
* **Process** - Calculate the position from which the light ray will emerge out of the grid. You are free to mark your grid (or not) in any way you like. The same goes with start and exit positions. Include these details in your answer below. How you represent these data will influence the output. See scoring rubrics for details.
* **Output** - Display the emerging position of the light ray. Detailed output can score more. See scoring rubrics for details.
You are free to use any libraries or extensions to implement *any part* of the maze, but not the *entire* maze. The only restriction here is this: if the library is for GUI, or implementing the Grid or anything like that it's fine. If it already contain a preset grid with mirrors (highly unlikely), you *can't* use it.
# Scoring
* **+64** for keeping your code less than 10 kilobytes (10240 bytes).
* **-2** for every byte after the 10240th byte
* **+16** for including the path of the ray in the output. Any representation is OK, but explain it in the answer. You may mark your grid with numbers, alphabets or in any other way you like.
* **+64** for drawing the grid with the solution (see figure). It could be a GUI or CLI! The drawing must *at least* include the grid and the ray of light from start to exit. Numbers, markings and everything else are optional. If you do this, you shouldn't add the +16 points above.
* **+128** for inventing partially reflective mirrors. These mirrors will guide the light in to two locations. One that is perpendicular to the original ray and one that passes straight through them. You may of course combine multiple mirrors like these with the normal ones for added effect. There may be 2 exit rays for this type of mirrors which you *must* display in your solution. If you choose to do this, change the user input *m* to suit the code accordingly (it must be a sequence of 3 elements rather than 2, the third value being the type of mirror). See figure below.
* **+128** for inventing the absorber mirror. Absorber mirror absorbs the light ray and stops it from exiting the grid. The solution to this case should be something like 'LIGHT RAY ABSORBED!' (you can show anything as long you explain it in the answer below.) Everything else is same as the partially reflective mirror shown above.
* **+128** for inventing the laser mirror. A laser mirror's reflection will destroy any other mirror that is in it's way. So, if the light strikes a laser mirror(m1) and then falls on another mirror (m2), it (m2) will be destroyed. The ray now travels straight as if that block is empty. Everything else is same as the partially reflective mirror shown above.
* **+128** for inventing a new kind of mirror and explaining its action. Make it really cool. ;)
TIE BREAKER: In case of a tie, the shortest code shall win. If by some strange coincidence, that happens to be the same, the winner shall be decided based on how many numbers there are in the code (every single digit of integers, floats and even numbers in variables) - the least one wins!
# Example
The first one is a typical solution with a GUI output. It marks the positions as integers from 1 to 12 and shows the path of the ray along with 2 mirrors. The second one shows the partially reflective mirror (bonus points) that has 2 exit rays. The third example is a CLI output model (this one is tough!). It shows the same thing as our GUI. The normal output without any diagrams (no bonus) could be as short as a single number or any value (eg: 7 or G) indicating from where the ray has emerged. The way you chose to name the positions must be included in your answer.

```
^
__:___ ______ ______ ______ ______
| : | | | | |
<...|..\\..|.<....|..\ | | |
|______|______|__:__ |______|______|
| | | : | | |
| | | ^ | | |
|______|______|__:___|______|______|
| | | : | | |
....|..>...|......|../ | | |
|______|______|______|______|______|
| | | | | |
| | | | | |
|______|______|______|______|______|
/ = normal mirror
// = partially reflecting mirror
```
[Answer]
## T-SQL(2012+) Score ~~512~~ 640
I hope this fits in the rules. I implemented the 3 mirrors + a super absorber. I didn't count the super absorber as a cool extra.
The input is three variables.
One int and two tables for mirror and start.
The mirror table has columns for X, Y, Orientation(-1/1) and Type (1-4)
-1 is Left and 1 is Right
Type 0 is standard, 1 is laser, 2 is partial, 3 is absorber and 4 is super absorber
**EDIT:** 5 is laser splitter and 6 is a splitter. These will split the beam in both directions.
The start table has columns for start X and Y, Direction(1-4) and Laser Flag(0/1)
Direction 1 is north, 2 is east, 3 is south and 4 is west.
It will handle more than one start point.
A function to handle mirrors. Run once.
```
DROP FUNCTION M;
GO
CREATE FUNCTION M(@d INT,@O INT,@t INT,@L INT) RETURNS TABLE AS RETURN
SELECT IIF(d=0,4,d)d, l FROM (
SELECT (@d+(@o*(IIF(@d%2=0,-1,1)))+4)%4d,isnull(@t,0)%2l WHERE @L=0 AND @o is not null and isnull(@t,0)not in(3,4)
UNION ALL
SELECT @d, @l WHERE isnull(@t,2)=2 OR (@l=1 AND @t<>4)
UNION ALL
SELECT (@d+(-@o*(IIF(@d%2=0,-1,1)))+4)%4,isnull(@t,0)%2 WHERE @L=0 and @t in(5,6)
)m
```
The grid setup and query
```
-- Set up Maze
DECLARE @n INT = 5
DECLARE @m TABLE (X INT, Y INT, O INT, T INT)
DECLARE @s TABLE (X INT, Y INT, D INT, L INT)
INSERT INTO @m VALUES (1,5,-1,0),(1,1,-1,0),(2,1,1,2),(3,1,1,2),(4,1,1,1),(2,3,-1,5),(4,3,-1,3),(4,5,-1,4),(4,2,1,0),(3,4,1,6);
INSERT INTO @s VALUES (0,5,2,0);
-- Solve Maze
WITH S AS (
SELECT x,y,d,l,Geometry::Parse(CONCAT('LINESTRING (',px,' ',py,',',x,' ',y,')')).STBuffer((l+1)/30.)g
FROM(
SELECT x+(d.d+1)%2*-SIGN(d.d-3)x,y+d.d%2*-SIGN(d.d-2)y,d.d,d.l,x px,y py
FROM @s s OUTER APPLY(SELECT O, T FROM @m m WHERE s.x=m.x and s.y=m.y)x CROSS APPLY(SELECT d,l FROM M(s.d,x.o,x.t,s.l))d
)g
UNION ALL
SELECT x,y,d,l,Geometry::Parse(CONCAT('LINESTRING (',px,' ',py,',',x,' ',y,')')).STBuffer((l+1)/30.)g
FROM(
SELECT x+(d.d+1)%2*-SIGN(d.d-3)x,y+d.d%2*-SIGN(d.d-2)y,d.d,d.l,x px,y py
FROM S OUTER APPLY(SELECT O, T FROM @m m WHERE s.x=m.x and s.y=m.y)x CROSS APPLY(SELECT d,l FROM M(s.d,x.o,x.t,s.l))d
WHERE s.X>0 AND s.X<=@n AND s.Y>0 AND s.y<=@n
)g
)
,E AS (SELECT *FROM(VALUES(\),(\),(\),(\),(\),(\),(\),(\),(\),(\))E(N))
,N AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT\)) N FROM E e1,E e2,E e3)
SELECT CONCAT('Exits into ',x,', ',y,' from the ',CASE d WHEN 1THEN'south'WHEN 2THEN'west'WHEN 3THEN'north'WHEN 4THEN'east'END),null
FROM S
WHERE s.X=0 OR s.X>@n OR s.Y=0 OR s.y>@n
UNION ALL
SELECT 'Beam'O,Geometry::UnionAggregate(g)G FROM S --Draw Line
UNION ALL
SELECT CONCAT('Mirror Type ',T),Geometry::Parse(CONCAT('LINESTRING (',x+(ABS(o)/3.),' ',y+(o/3.),',',x-(ABS(o)/3.),' ',y-(o/3.),')')).STBuffer(.06) FROM @m WHERE T NOT IN(3,4,5,6) --Draw Mirrors
UNION ALL
SELECT 'Blocker',Geometry::Parse(CONCAT('LINESTRING (',x+(ABS(o)/(-T+8.)),' ',y+(o/(-T+8.)),',',x-(ABS(o)/(-T+9.)),' ',y-(o/(-T+9.)),')')).STEnvelope() FROM @m WHERE T IN(3,4) --Draw Blockers
UNION ALL
SELECT CONCAT('Mirror Type ',T),Geometry::Parse(CONCAT('MULTILINESTRING ((',x+.33,' ',y+.33,',',x-.33,' ',y-.33,'),(',x+.33,' ',y-.33,',',x-.33,' ',y+.33,'))')).STBuffer(.06) FROM @m WHERE T IN(5,6) --Draw Splitters
UNION ALL
SELECT 'Grid',Geometry::UnionAggregate(g) FROM (
SELECT Geometry::Parse(CONCAT('LINESTRING (',x1,' ',y1,',',x2,' ',y1,',',x2,' ',y2,',',x1,' ',y2,',',x1,' ',y1,')'))g -- Draw Grid
FROM (SELECT TOP(@n) N-.5x1,N+.5x2 FROM N)x,(SELECT TOP(@n) N-.5y1,N+.5y2 FROM N)y
)g
OPTION (MAXRECURSION 10000)
```
The output
Query Results tab SSMS

Spatial Results tab SSMS

[Answer]
C# 1669 chars, i implemented everything i think except msges(like laser has escpaed, laser got absorberbed etc...). ITS ALSO ANIMATED!
So its works like this, create a project called mirror and copy all of this into Form.cs.
When you press the form with your mouse it takes the variables entered into the textbox to start everything , so dont click before you enter them. The variables are as follow:
```
20 2 0 0 5 0 8
```
The first number is the grid size, the second number is the direction the laser will be going 0 is left, 1 is up, 2 is right and 3 is down. Then come the X Y starting position of the laser and after that you got 3 numbers for every object, first two being the X and Y position of the object and the third being the type of the object:
```
2 = /
3 = \
4 = //
5 = \\
6 = O (absorber)
7 = X (laser mirror)
8 = T (random teleport)
```
I dont consider my special object as worthy of the extra points since it isnt very cool. Also side note the thread doesnt finish properly so you need to kill the process (gotta save dat space). Here is a cool one to test it out
```
40 2 0 0 10 0 3 10 10 2 5 10 4 4 10 5 0 10 6 4 5 2 15 5 5 15 20 2 10 20 7 8 20 3 6 20 2 4 20 4 2 20 5 35 5 8 25 5 5 25 25 2 18 25 6
```
CODE
```
using System;using System.Collections.Generic;using System.Drawing;using System.Windows.Forms;using System.Threading;namespace mirror{partial class Form1:Form{public Form1(){InitializeComponent();this.Load+=l;}int[,]g=new int[1,1];int i;List<int[]>d=new List<int[]>();void l(object ss,EventArgs k){SetStyle(ControlStyles.AllPaintingInWmPaint,true);SetStyle(ControlStyles.OptimizedDoubleBuffer,true);this.Width=this.Height=800;TextBox t=new TextBox();this.Controls.Add(t);this.Click+=(p,e)=>{t.Hide();string[]s=t.Text.Split(' ');i=o(s[0]);g=new int[i,i];d.Add(new int[]{o(s[1]),o(s[2]),o(s[3]),0});g[d[0][1],d[0][2]]=1;for(int j=4;j<s.Length;)g[o(s[j++]),o(s[j++])]=o(s[j++]);Thread x=new Thread(r=>{while(true){for(int c=0;c<d.Count;c++){try{got:if(d[c][0]==0)d[c][1]--;if(d[c][0]==1)d[c][2]--;if(d[c][0]==2)d[c][1]++;if(d[c][0]==3)d[c][2]++;if(d[c][3]==0){int l=d[c][0];int z=g[d[c][1],d[c][2]];if(z==2)d[c][0]=l==0?3:l==1?2:l==2?1:0;if(z==3)d[c][0]=l==0?1:l==1?0:l==2?3:2;if(z==4)d.Add(new int[]{l==0?3:l==1?2:l==2?1:0,d[c][1],d[c][2],0});if(z==5)d.Add(new int[]{l==0?1:l==1?0:l==2?3:2,d[c][1],d[c][2],0});if(z==6){d.RemoveAt(c);continue;}if(z==7)d[c][3]=1;if(z==8){Random rr=new Random();d[c][1]=rr.Next(i);d[c][2]=rr.Next(i);}if(z>1)goto got;}g[d[c][1],d[c][2]]=1;}catch(Exception){}}this.Invalidate();Thread.Sleep(100);}});x.Start();};string[]ar=new string[]{" ","*","/",@"\","//",@"\\","O","X","T"};this.Paint+=(h,v)=>{Graphics z=v.Graphics;for(int q=0;q<i;q++)for (int w=0;w<i;w++){z.DrawRectangle(Pens.Black,new Rectangle(q*20,w*20,20,20));z.DrawString(ar[g[q,w]],this.Font,Brushes.Black,new Point(q*20+8,w*20+8));}};}int o(string s){return int.Parse(s);}}}
```
non golfed: <http://pastebin.com/sNa0aK7f> , <http://horobox.co.uk/u/vajura_1414782718.rar> exe
Also hope you like it was fun to make! :)
] |
[Question]
[
I want to write x86 assembler code that can be used to boot your computer from and dims NumLock. This means
* you cannot rely on glibc or any other of these "comfi" libraries
* you cannot rely on the Linux kernel
* we will test your code by dumping it onto a virtual floppy and boot a VM from it
* goal is to switch on and off NumLock so quickly that it appears dimmed
* it's okay if everything fits into the bootloader and loops endlessly
Solution with most votes wins.
[Answer]
I haven't tested this (VirtualBox doesn't pass through its virtual keyboard LEDs onto the physical keyboard, and I'm not on a PC I can reboot currently). But I think it should probably work and is probably quite minimal.
There may be [some additional setup](http://courses.engr.illinois.edu/ece390/books/artofasm/CH20/CH20-2.html) that needs to be done on the keyboard controller for these commands to work. If so it would be essentially trivial to add to the code below...
```
[bits 16]
[org 0x7c00]
mov al, 0xed
out 0x60, al
mov al, 0x07
out 0x60, al
mov al, 0xed
out 0x60, al
mov al, 0x00
out 0x60, al
jmp $$
times 510 - ($ - $$) db 0
dw 0xaa55
```
Compile with `nasm -f bin -o floppy.img numlock.asm`.
Will give this a real test and tweak accordingly later (if someone else wants to try and/or tweak it feel free).
] |
[Question]
[
[Goldbach's conjecture](http://en.wikipedia.org/wiki/Goldbach%27s_conjecture) states that every even number > 4 is the sum of two prime numbers. Although this conjecture is not yet proven, similar results have been proven for other series of numbers. For example, every even number can be written as the sum of two [practical numbers](http://en.wikipedia.org/wiki/Practical_number).
# The Challenge
Given a number N, return a set of positive integers such that every even number in the interval [4,N] can be written as the sum of two numbers in the set. Furthermore, the set generated must contain as few elements as possible, otherwise this challenge would be trivial.
Shortest answer wins.
# Detailed Example
For N=24, one possible output is {2,4,8,10,12}. This is because it contains the fewest number of elements possible (5). Also, every even number {4,6,8,... 24} can be written as the sum of exactly two of the members of the set.
```
4=2+2
6=2+4
...
12=8+4
14=10+4
...
24=12+12
```
# Examples
Here are some examples. There may be many valid outputs for each input, but only a few are listed.
```
4:{2}
6:{2,4} or {1,3}
9:{2,4} #pay attention to how the odd number is handled
10:{2,4,6} or {2,3,5}
12:{2,4,6}
24:{2,4,8,10,12}
26:{1,3,7,11,13}
```
[Answer]
## GolfScript (53 chars)
```
~2/),3>[2][1 3]]({2*:x;{:S{x<},{x\-S+.&}/}%}/{,}$0=n*
```
A major speed optimisation results from a bit of duplicate-trimming, at a cost of 3 chars:
```
~2/),3>[2][1 3]]({2*:x;{:S{x<},{x\-S+.&$}/}%.&}/{,}$0=n*
```
---
NB Let `f(2n)` be the size of the optimal set for `[4..2n]`. Then `f(2n) <= f(2n+2) <= f(2n) + 1`. The first inequality is obvious from the definition; the second is easily seen by taking any optimal set `S_{2n}` for `[4..2n]` and taking the union with `{n+1}`, or indeed with `{2n+2-x}` for any `x in S_{2n}`.
This suggests a greedy algorithm, which the first revision of this answer implements. However, that greedy algorithm turns out to be incorrect. The unique optimal set for `[4..20]` is `{2,4,8,10}`, which is not a subset of either of the two optimal sets for `[4..26]`: `{1,3,7,11,13}` and `{2,4,8,12,14}`.
My current solution assumes that every optimal set will contain only odd numbers or only even numbers. I haven't proven this, but given that `odd + even = odd` a set which mixes parities is wasting possible pairs.
[Answer]
# J block, 106 characters
```
f=.3 :0
n=.0
while.1
do.for_z.>,{n#<>:i.y
do.if.0=$(+:2+i.<:<.-:y)-.+/~z
do.z
return.end.end.n=.>:n
end.
)
```
As usual for J programs, very memory hungry. The algorithm is as simple as can be: for each length n, for each combination z of n values, if that combination covers the whole set, return that combination.
# Ruby, ~~116~~ 112 characters
```
f=->x{0.upto(x){|n|(1..x).to_a.combination(n){|z|return z if
[]==4.step(x,2).to_a-z.flat_map{|i|z.map{|j|i+j}}}}}
```
(whitespace insignificant)
Ruby version of the algorithm, built-in deduplication, much more memory-efficient due to the use of enumerators in place of arrays (though J seems to optimise this somewhat), surprisingly not much larger than the J version.
results:
```
4-5 :[2]
6-9 :[2, 4]
10-13:[2, 4, 6]
14-21:[2, 4, 8, 10]
22-29:[2, 4, 8, 12, 14]
30-39:[2, 4, 8, 12, 16, 18]
40-45:[2, 4, 6, 12, 18, 20, 22]
```
] |
[Question]
[
John is writing a program that finds the best route from A to B using public transport. For a given pair of origin and destination the program calculates a set of routes with departure time and arrival time, such as this:
```
10:12 11:45
10:15 11:50
10:22 12:05
10:25 12:00
```
As you see, the output may include a few routes that are superfluous in the sense that there is another route that starts later and ends earlier. Such routes are certainly never wanted by the user since he cat get out later to arrive sooner.
Your task, if you choose to accept it, is to write a program that prunes a set of routes such that all superfluous rules are eliminated.
## Input
The input is a list of newline separated pairs of whitespace separated departure and arrival time in military format (hh:mm). Such a pair is called a *route*.
You may assume that all times are in the same day and that the arrival time is always later than the departure time. You may also assume that the list is orderer by departure times.
## Output
The output is the same list as the input without redundant routes. A redundant route is a route for which another route exists in the list that has a later departure and an earlier arrival time. There must exist an order to remove all redundant routes such that in each step you can show the route that makes the removed route redundant. You don't have to output that order.
## Extra credit
Prove or disprove that for each list of input routes there exists exactly one set of output routes.
## Restriction
* Usual codegolf rules apply
## Scoring
To score, apply the function that gives an upper bound to your solutions complexity with your solution's total number of characters. Normalize your bounding function such that a solution length of two character yields a score of two.
For example, if your solution has 24 characters and a complexity of *O(2n)*, your score is 4194304. If your solution has 123 characters and a complexity of *O(n2)* your score is 7564. If your solution has 200 characters and a complexity of *O(n\**log*n)*, your score is 734.
I use this scoring method in order to encourage people to implement efficient solutions.
[Answer]
## Perl 47 (+1) bytes • O(n) ⇒ 48 score
```
$#a-=2until$a[-/ \K/]lt$';push@a,$`,$'}{print@a
```
Adding one byte for the `-n` option, as per the [OP's instructions](https://codegolf.stackexchange.com/questions/9177/#comment18075_9177).
Sample input:
```
10:30 11:00
10:33 11:18
10:42 11:10
10:47 11:18
10:49 11:26
10:50 11:09
11:00 11:20
11:01 11:28
11:11 11:31
11:21 11:49
11:23 11:53
11:29 12:09
11:36 12:08
11:41 12:15
11:46 12:06
11:53 12:23
11:56 12:32
12:01 12:30
12:04 12:47
12:05 12:25
```
Sample output:
```
$ perl -n prune-connections.pl < in.dat
10:30 11:00
10:50 11:09
11:00 11:20
11:01 11:28
11:11 11:31
11:21 11:49
11:23 11:53
11:46 12:06
11:53 12:23
12:05 12:25
```
Input generator (PHP):
```
<?php
for($t = strtotime('10:30'); 20 > $i; $i++) {
$r = rand(15, 45)*60;
echo date('H:i', $t), ' ', date('H:i', $t+$r), PHP_EOL;
$t += rand(0, 10)*60;
}
?>
```
**Lemma:**
If a route  is invalidated by some other route  where , and no other route between  and  invalidates , then  invalidates all routes from  to .
Because the routes are sorted by departure time, and ,  must necessarily have a later departure time than . Then, in order to invalidate ,  needs only to have an earlier arrival time. If there were a route between  and  which was not invalidated by , it would have an earlier arival time than , and hence, would have already invalidated .
Therefore, a linear time algorithm, which only checks if the current route invalidates the previous route is sufficient to solve the problem. When an invalidation is found, the route before the invalidated route must also be checked, until a route is not invalidated (or no valid routes remain). Because a route can only be invalidated once, no more than  routes will be invalidated in this manner.
Note that it is important that the invalid routes actually be *removed* from the list. If they are simply marked invalid (or set to `null`, etc.), this will result in  complexity, in the case that each new route invalidates all previous routes.
Proof that only one solution exists follows directly from the law of transitivity. If a route  is invalidated by , and  is invalidated by ,  is also invalidated by . In order for multiple solutions to exist, it must be possible to invalidate  without invalidating , but any route that invalidates  will also invalidate , and will lead to the same solution.
[Answer]
### GolfScript, 26 characters, 26 score
```
n%-1%{6>[0$m]$0=:m=},-1%n*
```
The solution assumes a list sorted on departure time on input (as noted in the problem description) and also prints a sorted list (if this restriction can be dropped we may save 3 chars).
The code traverses the list backwards and removes any connection where the arrival time is larger than the minimum arrival time processed so far.
```
n% # split input at newlines
-1% # reverse list
{ # filter list...
6> # take arrival time of current item
[0$m] # make an array consisting of that arrival time and the minimum
# up to now, contained in variable m. Note since m is not initialized
# the array will consist of a single item in the first iteration
$ # sort that array (consisting of one or two items)
0= # take first item, i.e. minimum arrival time
:m # save to variable m
= # compare current item to m and select if both are equal
}, # ... end of filter list
-1% # reverse list again
n* # join items with newline
```
The code can be tested [online](http://golfscript.apphb.com/?c=OyIxMDoxMiAxMTo0NQoxMDoxNSAxMTo1MAoxMDoyMiAxMjowNQoxMDoyNSAxMjowMCIKCm4lLTElezY%2BWzAkbV0kMD06bT19LC0xJW4qCg%3D%3D&run=true).
[Answer]
## Python 82 • O(n) = 82
New to code golfing. Dunno if I am breaking any rules.
```
i=-1
while len(a)>-i:
if a[i][6:]<a[i-1][6:]:a.pop(i-1)
else:i-=1
print ''.join(a)
```
The algorithm is to iterate from the back of the list, removing the previous line if it has a later arrival time or moving the pointer to the previous line otherwise.
Note: The definition of redundant routes given by the OP is taken to the word, so neither of the two routes which have the same arrival times but different departure times are removed.
[Answer]
## APL ~~107~~ ~~57~~ 52 . O(n) = 52
```
T m
r←m
m←⍎(,0 5↓m)~':'
l:m←(n←(2≤/m),1)/m
r←n⌿r
→(~×/n)/l
r
```
The input m variable could be simply typed in as follows for the first example below:
```
m←4 11⍴'10:12 11:4510:15 11:5010:22 12:0510:25 12:00'
```
or it could be read in programatically from a number of sources eg text file.
The line before the start of the loop converts the character input (m) of arrival times to 4 digit numbers. The loop is then using sequential ≤ on those times to do the pruning. Tested on the following:
```
10:12 11:45 10:12 11:45 10:12 11:45 10:12 11:45
10:15 11:50 10:15 11:50 10:15 11:50 10:15 11:50
10:22 12:05 10:22 12:05 10:22 12:05 10:22 12:05
10:25 12:00 10:25 12:00 10:25 12:00 10:25 12:00
=========== 10:30 11:55 10:30 11:55 10:30 11:55
10:12 11:45 =========== 10:35 12:10 10:35 12:10
10:15 11:50 10:12 11:45 =========== 10:40 11:40
10:25 12:00 10:15 11:50 10:12 11:45 ===========
10:30 11:55 10:15 11:50 10:40 11:40
10:30 11:55
10:35 12:10
```
] |
[Question]
[
# Definitions
The common methods to generate consecutive composites are
$$\overbrace{(n+1)! + 2, \ (n+1)! + 3, \ \ldots, \ (n+1)! + (n+1)}^{\text{n composites}}$$
$$\overbrace{n!+2,n!+3,...,n!+n}^{\text{n-1 composites}}$$
$$\overbrace{n\#+2,n\#+3,…n\#+n}^{\text{n-1 composites (Primorials)}}$$
---
A less common method involves the [Chinese Remainder Theorem](https://en.wikipedia.org/wiki/Chinese_remainder_theorem) (CRT).
For example, define a list of \$n\$ [pairwise coprimes](https://en.wikipedia.org/wiki/Coprime_integers#:%7E:text=A%20stronger%20condition%20on%20a,4%20are%20not%20relatively%20prime.) \$p\_1, p\_2, \ldots, p\_n\$.
>
> A set of integers can also be called coprime if its elements share no common positive factor except 1. A stronger condition on a set of integers is **pairwise coprime**, which means that \$a\$ and \$b\$ are coprime for every pair \$(a, b)\$ of different integers in the set. The set \$\{2, 3, 4\}\$ is coprime, but it is not pairwise coprime since 2 and 4 are not relatively prime.
>
>
>
Create a set of \$n\$ congruences
\begin{align\*}
x + 1 &\equiv 0 \pmod{p\_1} \\
x + 2 &\equiv 0 \pmod{p\_2} \\
&\vdots \\
x + n &\equiv 0 \pmod{p\_n}
\end{align\*}
By CRT, there exists a unique solution \$x\$ which satisfies this sequence of \$n\$ consecutive [composite numbers](https://en.wikipedia.org/wiki/Composite_number):
$$x + 1, x + 2, \ldots, x + n$$
>
> A **composite number** is a positive integer that can be formed by multiplying two smaller positive integers. Equivalently, it is a positive integer that has at least one divisor other than 1 and itself.
>
>
>
---
# Challenge
Given pairwise coprime inputs, find the smallest range of consecutive composite numbers.
**Input**
A list of \$n\$ pairwise coprimes.
**Output**
A sequence of \$n\$ consecutive composite numbers.
# Test Cases
These cases were derived from this [test](https://tio.run/##nZVtb9s2EIC/@1fcOgyQYSYNJbua46pAEfRDgbobAg8FlgYGLdEWMYrU9OKoC/zX5x31Ylm2E0AzDPtwPN49PN4d/auN7@9/FsqXecDh/SaKr8MPg1YRsSxEzX6rRQB3WqXczzOx5Xc6inUqMp5@E1l4d7@whMrA13EiIr5UeZQ@PBIwOsnVEJ4HgJ8o/meZQbmIWlxP@EEsCMwJZDyKUV7GMk@XanbYJZTIUuuSDYGvf3z5MmxNU54tc2GhIR3OYFDq1zqBElCABzcz/HtvuFAYjRq4bqgSUjSIRjgKcxLqYNs5vni8YJ0K6@DwyhIwQsgTsyiXBh6/XTe76ihv38LHOJY/IAs53IVC8ZTDPY@YUAFPYBFyjRF6nzqD2FzXdnYhF9XKxQwEWAoF8zNjc0bcetnyJLNKH/FLRubY1c0eEoQbXjSqfuOTdRYEpkiKav1k0ZecJRdPU6e2jKAbD3NcbDL@ef77b/eLj18X8CnYYNpZym8Pa2soRgJCFsdcpZBpWHHgf@dMGlkrDnpdXlZZG4ABcimI0ahyo0hBadM6dUP91DheaExFquWWE8DagcIrRsok2bQV3/CEwFMo/NB4YDLVwACtsTu1gtUPwJ68BmtuVqvoGNjPDAyTslRVKMMm3qeCRbHkt7UeXEIpsR0DkcssxaiIYN/AEzY8kjue7RCsJ2xojwJTQQWJpYY2I3ALSgvc7QF1p/S6CfJNy3XCIibjkN1i3SITf3ie6@ChGFHiPnqekW9QIpXSRoqDFsVa7SDZQY3ijjwXO/K5Skz62Kv@xRosc/eYohVbLasejtu2ppMhfICb4y1HBWcmQD2SsLLKjp517Br3fhTXhk0HgOeduz2v5fmJQ/NZJZz91VXvBl1pd2H20TIL3otjoD5PO1zNmY7C4/tg8qOytfXmlz@D7@pNO4m7zdRn@NSd@erM3Q1OrF99DBBib4KbsWg14Rrw78o@fsqgfcvwPHW449fMZtV7hgd5tomzqyxefQy7W4ndzJL/jbBqEX4l014Iq5cQnF4ITktQT4Y@FOVu4pxDjHtBjDs3QSbE7QNR7ibjc4hJL4hJC@EQzAXOJadnOkoXZHKhLGi/uqBnCTF3gzwUhSlSEXtKHEocl4wpGTtk7JIJ2k3JO0reucTFoduvomlVTrRhT3iWJwpbHJtu/6@/lmyT7q@e9lcShwX@Rv8B).
| n | pairwise coprimes | consecutive composites |
| --- | --- | --- |
| 2 | 2, 3 | 8,9 |
| 3 | 7, 11, 23 | 1792, 1793, 1794 |
| 4 | 2, 3, 5, 7 | 158, 159, 160, 161 |
| 5 | 3, 7, 10, 13, 23 | 47928, 47929, 47930, 47931, 47932 |
Added a JavaScript (V8) [tool](https://tio.run/##RcnRCsIgGIbhW3EHgTIbWxEV9ncjYwc6dP0iGs6tg9i12wZRRx/v91g5y7GP@Ez7@ZKzAeoZ3N8mROp0Igi1wJuvnPZDeggsS/YzC1g2wv7VbrqJBN9ix9U6tuNJvB7oNFUF1CyBWn@5U1xCEmioLKBhUacpemKkG7VYlm@mOK2V@@DH4HTlwkANbQ@cHDk5cXLm5NoxJvIH) to validate if the input numbers are pairwise coprime.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly)
```
V+€J%ÞfÞẒƇḢ
```
A monadic Link that accepts a list of pairwise coprime integers and yields a run of the same number of consecutive composites.
**[Try it online!](https://tio.run/##ASkA1v9qZWxsef//VivigqxKJcOeZsOe4bqSxofhuKL///9bNywgMTEsIDIzXQ "Jelly – Try It Online")**
### How?
Uses the Chinese Remainder theorem in the most naive way possible, systematic search.
```
V+€J%ÞfÞẒƇḢ - Link: Coprimes
V - Digit-smash {Coprimes}
(e.g. [2, 11, 17] -> 21117 -- N.B. V >= Product+Max so is sufficient*)
J - 1-indexed indices {Coprimes} -> [1..n=length(Coprimes)]
€ - for each {v in [1..2P]}:
+ - {v} add {[1..n]} (vectorises)
Þ - sort by:
% - modulo {Coprimes} (vectorises)
Þ - sort by:
f - keep those which are in:
Ƈ - {Comprimes} for which:
Ẓ - is prime?
Ḣ - head
```
---
\* Thanks to [Leo](https://codegolf.stackexchange.com/users/62393/leo) for this proof that the digit concatenation performed by `V` is guaranteed to be greater than or equal to the product plus the maximum that we may need to search through:
The concatenation \$a|b\$ of two positive numbers \$a\$ and \$b\$ is equal to \$a\times c + b\$, where \$c\$ is the first power of \$10\$ larger than \$b\$ (i.e. \$c = 10^{\lfloor 1 + \log\_{10}{b} \rfloor}\$).
Since \$c \ge b + 1\$ we get \$a|b \ge a \times (b + 1) + b = a \times b + a + b\$.
As such the concatenation of two numbers is always at least as large as their product plus their sum. This then extends to more terms as each of the operations, concatenation and taking a product, may be applied in succession.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 67 bytes
```
((r=Range@Tr[1^#])+ChineseRemainder[-r,#,If[Or@@PrimeQ@#,Tr@#,1]])&
```
[Try it online!](https://tio.run/##FYrBCsIwEER/RQhIiys1DVI9FAKePKmlt1Ah2DXNITmsuYV@e9xeHjNvJti0YLDJf2xxfakq6gcbHeqRjHyLqT7cFh/xhwO/fJyRzJFAwP1rHqT1k3zAlxYwEkNOU70v7GLaNdo1OucW1Ar5AldmB1JCu3W2cIaOkwK2J5BqG9ZS/g "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ā∞sδ+ʒp≠P}.ΔIÖP
```
[Try it online](https://tio.run/##AS0A0v9vc2FiaWX//8SB4oiec860K8qScOKJoFB9Ls6UScOWUP//WzcsIDExLCAyM10) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf@PND7qmFd8bov2qUkFjzoXBNTqnZtyaN3haQH/a3X@R0cb6RjH6kSb6xga6hiBWEC@jqmOOZBlrAMUNdAxNAZJxAIA).
**Explanation:**
```
ā # Push a list in the range [1, (implicit) input-length]
∞ # Push an infinite positive list: [1,2,3,...]
s # Swap so the [1,length] list is at the top again
δ # Pop both lists, and apply double-vectorized:
+ # Add the values together
ʒp≠P} # Filter, and remove all overlapping lists that contain primes
.Δ # Then find the first list that's truthy for:
IÖ # Check for each value whether its divisible by the input-value at the
# same position
P # Check whether this is truthy for all of them
# (after which the found result is output implicitly)
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 63 bytes
```
.+
*_,$:&*
/\b((_+)_+),\1*\2\b|,(?!(__+)\3+\b)/+%`$
_
L$`,
$.%'
```
[Try it online!](https://tio.run/##K0otycxLNPyvqhGcEOOi/V9Pm0srXkfFSk2LSz8mSUMjXlsTiHRiDLVijGKSanQ07BU14oEiMcbaMUma@tqqCSpc8Vw@Kgk6XCp6qur/D23j0lH4b6SjYMwFInQUTHUUzLnMdRQMDXUUjIwB "Retina – Try It Online") Takes input on separate lines but link is to test suite that converts from and to comma separated for convenience. Explanation: Brute force, so last test case was omitted for speed.
```
.+
*_,$:&*
```
Convert each input to unary and append its index.
```
/\b((_+)_+),\1*\2\b|,(?!(__+)\3+\b)/+`
```
While there is a non-composite output or an output that isn't divisible by an input, ...
```
%`$
_
```
... increment all of the outputs.
```
L$`,
$.%'
```
Delete the inputs and convert the outputs to unary.
[Answer]
# C (gcc), ~~563~~ 461 bytes
*-102 bytes, thanks to @ceilingcat*
The GNU Multiple Precision Arithmetic Library. [GMP](https://gmplib.org/)
```
#import<gmp.h>
i;f(a,b)int a[];{mpz_t c[b],d[i=b],e,f,g,h,j,k;mpz_inits(e,f,g,h,j,k,0);for(mpz_set_ui(f,1);i--;mpz_mul(f,f,c[i]))mpz_inits(c[i],d[i],0),mpz_set_ui(c[i],a[i]),mpz_set_si(d[i],~i);for(;++i<b;mpz_add(e,e,g))mpz_divexact(j,f,c[i]),mpz_invert(k,j,c[i]),mpz_mul(g,d[i],k),mpz_mul(g,g,j);for(mpz_mod(e,e,f);i--;)mpz_probab_prime_p(c[i],15)?mpz_add_ui(g,e,i+1),i=!mpz_cmp(g,c[i])?mpz_add(e,e,f),0:i:0;for(;b/i;gmp_printf("%Zd ",h))mpz_add_ui(h,e,-i--);}
```
[Try it online!](https://tio.run/##TVHtbsIwDPzPUzCmSYnqbi2sYiMw3mNVhfqVYmhKBYVNq9ijr7MbNviTxOfc@U5O3SJNu@4eTb3bN/PC1I/rtwEqLWJIJFbNMA4j1Zr6a9UM0zCJIAtxQVcOGgpYwwa2irtYYXMQNyh4UundXnDzkDerIwoNvlTouj3BHEsCNKQhRlJeJbjmIREJwA25x2P@/I8eUPQfv9GOUo6D86RXj7OMzORQWOkMT/lnnDZi8zcR7MRTvm/ElvxeQTZWWAfbW6SAzTWR2Vl9bQP1Q@r9LokTutDkq9oa9gO5vPjhEAVR0PEl4OKO4dTUhPWzl7e2tQRvhjPPxkqeUNFmWLlqtBg9vGfDEaxttIvymlguWZHq3PHaTIyVkMN2wEUVRmEQLdr2BV7P0I5hQucUfB/GE1tDAFN6TYBQD/wJN86qJ5chMcfAn54hIJA9cQMXnsJ5oNBxZKtFxXlLjqLqIy1yNCIv50H3k@oyLg6d@9G5JcWg0/wC)
] |
[Question]
[
There is an asdfmovie video about a pie flavoured pie. Someone also made an edited version with more pies, so I created this challenge.
The input is a positive integer.
The code should first output the following string:
```
I baked you a pie!
Oh boy, what flavour?
```
Then, the next line should be `PIE` (input number of times) + `flavour.`.
Next, print a blank line.
After that, ASCII-art pies should be drawn.
Here is what a size-1 pie looks like.
```
_________
/ \
-----------
\ /
-------
```
Size-2 pie:
```
_____________
/ \
---------------
\ /
-----------
```
Size-3 pie:
```
_________________
/ \
-------------------
\ /
---------------
```
Each pie starting from size-2 should be four characters longer on each line than the pie one smaller.
The program should draw (input number + 1) pies, seperated by newlines, with increasing sizes (1 at the top, 2 directly below it, etc).
The pies should be centred.
Examples:
Input 1
```
I baked you a pie!
Oh boy, what flavour?
PIE flavour.
_________
/ \
-----------
\ /
-------
_____________
/ \
---------------
\ /
-----------
```
Input 2
```
I baked you a pie!
Oh boy, what flavour?
PIE PIE flavour.
_________
/ \
-----------
\ /
-------
_____________
/ \
---------------
\ /
-----------
_________________
/ \
-------------------
\ /
---------------
```
Input 3
```
I baked you a pie!
Oh boy, what flavour?
PIE PIE PIE flavour.
_________
/ \
-----------
\ /
-------
_____________
/ \
---------------
\ /
-----------
_________________
/ \
-------------------
\ /
---------------
_____________________
/ \
-----------------------
\ /
-------------------
```
This is code-golf, so use any language, shortest code wins.
[Answer]
# [Perl 5](https://www.perl.org/) + `-M5.10.0 -na`, 169 bytes
```
say"I baked you a pie!
Oh boy, what flavour?
","PIE "x$_,"flavour.
",map{$i=" "x("@F"-$_)," __",_ x($#a=7+4*$_),"
$i/ @a \\
$i----",$j="-"x$#a,"
$i \\@a/
$i $j
"}0..$_
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoic2F5XCJJIGJha2VkIHlvdSBhIHBpZSFcbk9oIGJveSwgd2hhdCBmbGF2b3VyP1xuXCIsXCJQSUUgXCJ4JF8sXCJmbGF2b3VyLlxuXCIsbWFweyRpPVwiICBcIngoXCJARlwiLSRfKSxcIiBfX1wiLF8geCgkI2E9Nys0KiRfKSxcIlxuJGkvIEBhIFxcXFxcbiRpLS0tLVwiLCRqPVwiLVwieCQjYSxcIlxuJGkgXFxcXEBhL1xuJGkgICRqXG5cIn0wLi4kXyIsImFyZ3MiOiItTTUuMTAuMFxuLW5hIiwiaW5wdXQiOiIxXG4yXG4zXG4xMiJ9)
[Answer]
# JavaScript (ES6), 176 bytes
Builds the output recursively, from bottom to top.
```
f=(n,p,s=`I baked you a pie!
Oh boy, what flavour?
`)=>~n?f(n-1,-~p,s+=n?"PIE ":`flavour.
`)+`
_2_
/ 0 \\
--1--
\\0/
1`.replace(/^|\d/gm,i=>" -_"[+i].repeat(i?7+n*4:p*2)):s
```
[Try it online!](https://tio.run/##LYtBC4IwGEDv@xVfnrbcNCsIhOmpQ6e6Z7mlM1e2DbUiiP66GXR78N67yIfsila7nhlbqmGoODbU0Y6LDZzkVZXwsneQ4LSaoG0NJ/ui8KxlD1UjH/bepkgQnnxMWmHDIso@4@xzk3q7zRq8WPyzYMx8gSCf5yiEGWQZYixiDI00CxFAJIJWuUYWCofHd1aG5xvVPPGA5d7e14efVbLHOl35ZrqM3XROSNwNhTWdbVTQ2DOu8IKQ4Qs "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
p, // p = left-padding counter
s = // s = header string
`I baked you a pie!\n` + //
`Oh boy, what flavour?\n` //
) => //
~n ? // if n is greater than -1:
f( // do a recursive call:
n - 1, // decrement n
-~p, // increment p
s += n ? "PIE " // append "PIE " to s if n != 0
: `flavour.\n` // or the final part otherwise
) + ( // end of recursive call
`\n` + // \
` _2_\n` + // | this is our pie template
`/ 0 \\\n` + // |_ where digits 0, 1 and 2
`--1--\n` + // | are used as placeholders
` \\0/\n` + // | for repeated characters
` 1` // /
).replace( // replace in the template:
/^|\d/gm, // each beginning of line and
i => // each digit with:
" -_"[+i] // one of these characters
.repeat( // repeated:
i ? // if this is a digit:
7 + n * 4 // 7n + 4 times
: // else (left padding):
p * 2 // 2p times
) // end of repeat()
) // end of replace()
: // else:
s // return the header string
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 126 bytesUTF-8 (87*†*) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage))
```
Ý·ε5+'_×1ú'/'-6y+×D„ \s¨¨2ú).B.º}˜.c…PIEIиðý.•FóG ñ•ÁDŠ“I baked€î€…Èš!
Ohíå,€Àÿ?
ÿÿ.
ÿ
```
[Try it online.](https://tio.run/##yy9OTMpM/f//8NxD2021z21Vjz883fDwLnV9dd1Ku8PTXR41zFOIKT604tAKo8O7NPWc9A7tqj09Ry/5UcOyAE9Xzws7Dm84vFdJIS0nsSy/tEjJ5eiCRw1zPBWSErNTUx41rTm8DkgA1R7uOLpQkcs/4/Daw0t1QOINh/fbcx3ef3i/HheQ@v/fGAA)
*‚Ć: Could be **86 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** by using `.‚Ä¢F√≥G √±‚Ä¢√Å` instead of `" flavour"`, but the longer one is cheaper in UTF-8 encoding..* üòí
[Try it online.](https://tio.run/##yy9OTMpM/f//8NxD2021z21Vjz883fDwLnV9dd1Ku8PTXR41zFOIKT604tAKo8O7NPWc9A7tqj09Ry/5UcOyAE9Xzws7Dm84vFfvUcMit8Ob3RUObwSyDje6HF3wqGGOp0JSYnZqyqOmNYfXAQmgjsMdRxcqcvlnHF57eKkOSLzh8H57rsP7D@/X4wJS//8bAwA)
**Explanation:**
```
√ù # Push a list in the range [0, (implicit) input]
· # Double each value in this list
5+ # Then add 5 to each value
ε # Map over each 2v+5 value `y`:
'_√ó '# Push a string of that many "_"
1√∫ # Prepend a leading space
'/ '# Push "/"
'-y>√ó '# Push a string with y+1 (2v+6) amount of "-"
D # Duplicate it
„ \ # Push string " \"
s # Swap so the duplicated "-"-string is at the top again
¨¨ # Remove two "--" (2v+4 amount of "-")
2√∫ # And pad two leading spaces instead
) # Wrap all five strings into a list
.B # Add trailing spaces to make all strings the same length
.º # Mirror each line with overlap
}Àú # After the map: flatten the list of lists of lines
.c # Add leading spaces to centralize all lines,
# and join all lines with newline delimiter
…PIE # Push string "PIE"
I–∏ # Repeat it the input amount of times as list
√∞√Ω # Join it with space delimiter
.•FóG ñ• # Push compressed string "flavour "
Á # Rotate it to " flavour"
D # Duplicate it
Š # Tripleswap the top three values on the stack
“I baked€î€…Èš! # Push dictionary string "I baked you a pie!
Ohíå,€Àÿ? # Oh boy, what pie?
ÿÿ. # ÿÿ.
#
ÿ # ÿ",
# where the ÿ are one by one filled with the strings on the stack
# (after which it is output implicitly as result)
```
[See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•FóG ñ•` is `"flavour "` and `“I baked€î€…Èš!\nOhíå,€Àÿ?\nÿÿ.\n\nÿ` is `"I baked you a pie!\nOh boy, what pie?\nÿÿ.\n\nÿ"`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 88 characters, 140 bytes
```
NθI baked you a pie!¶Oh boy, what flavour?¶×PIE θflavour.D⎚DF⁺⁵⊗…⁰⊕θ«←×_ι↓ /P⊕ι↘-\⊖ι↙»‖B
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6Fjd73u9Zd26Hp0JSYnZqikJlfqlCokJBZqrioW3-GQpJ-ZU6CuUZiSUKaTmJZfmlRfaHth2eHuDpqnBuB1RE7_2eJY_6ZgHJ93uWPWrc9ahx66Ou6Y8agOwNj7qmnttxaPWjtgmHp8ef2_mobbKC_vs9YGEgZ4ZuzKOuaSDWzEO7HzVMe79nEcRNUKetiFbS1c0rUYpdaAwRAAA) Explanation:
```
Nθ
```
Input the number of PIEs.
```
I baked you a pie!¶Oh boy, what flavour?¶×PIE θflavour.D⎚
```
Output the desired text.
```
D
```
Output an extra blank line.
```
F⁺⁵⊗…⁰⊕θ
```
Loop over the half pie widths.
```
«←×_ι↓ /P⊕ι↘-\⊖ι↙»
```
Draw the left half of a pie to the canvas.
```
‖B
```
Reflect to complete the pies.
Would be 83 SBCS bytes using string compression:
```
Nθ”(KRC¿~8◨±⦄⊕⁰↙]V⊕ACY>|⊙C↙∕›…<·DÞ↖pÞ”×PIE θflavour.D⎚DF⁺⁵⊗…⁰⊕θ«←×_ι↓ /P⊕ι↘-\⊖ι↙»‖B
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZDBSsQwFEVxOfMVz6wykKogguhC0LooOFqKOyuSdl6nxTTppEmHIn6JmxFGcOf_-DWmtjqDZhO4991zX_LynuZcp4qL1erNmsw7_tzJA1lZc23LBDVdTE7HoS6koSSAhD_iDFplgUNV4G4sb3JIVMtgmXMDmeCNsvosluQ3dVuUWFMSBpdAGCwmG9wwvdfN-rasqLsvBHJNt4RMaaChsDU9YuArmwic0YjLOdIDBoFMNZYojRMd2h14Go96_skVZobB0P_gyouu_Mf11VIyILDf1Y-mVpii-na2mf8SUTHPHZR4cUw2lo9_I1PVYJ_otnDK8zjCTGBqzq0xqDPRutet6ySth2__uCNeI0jH9qQh96-Hvf4F) Link is to verbose version of code.
] |
[Question]
[
The wizard is determined to pose the most challenging challenge yet for which he believes the previous solution techniques will not work. He decides to go multidimensional.
If there is a number line with \$x = 10\$ then your task is to prove this. If you do so you win. In this situation, for your code to be correct, it must correctly identify at least one such number line.
As before, the wizard will not let you choose a number larger than \$9\$. This might still be OK as you might still find 10 points and in fact the only way to win is to have found all 10 points with values 9 or less on one of the number lines.
Your goal is to devise a strategy to play at the minimum expected cost. You should report your mean cost. To reiterate, your code should always find a line with 10 points less than or equal to 9 if one exists.
# Score
The score for your code is the expected cost to run it to completion. The lower the score the better.
[Answer]
# [Python 3 (PyPy)](http://pypy.org/), score = 3615.3653049197464
```
def f(w):
for i in range(100):
x = w.guess(i, 1.7858708219134063)
if (6 <= x <= 7) or (x >= 2 and w.guess(i, 4.818513589137271) >= 6): w.guess(i, 9)
print(Wizard().use(f))
```
[Try it online!](https://tio.run/##bVJNc4IwEL3zK/aY2JYSrUId6a1XL@1MDx2HsRhsLAYmCSP0z9uNMJQoO3xMNm/ffrwtG/NdyNlD2ZTN@SyOZaEMqK3cFUfPS/Ot1vAhfrdq91alKdeavNYpL40oJF16gFYixEW2/h3PIEmEFCZJiOZ51uGt2aOfFtpADIHrVVxzQ2hP0Z7H4muN0Z9tqb794bvnhDEKWaEgASGhcwUB3bjB@SVYY7N8R4YkxZHQCQuuKWq6aWlr6@vyb/oq95UdjXXfg7iHZrTXuximk0nT30gsQVdHcoAVNBfyQ0@e60@xoT1UZBYdAwuWWJDQ3BWlxyluKiVB9oVVmndl4bOOcRJog@qu2lwPrqydvkXO4V1V3PWPyjU0o5rbiEvCVsvRO2dUttQbFL8sn9v8eJ4vxbc/13PpEzyuPc@OJyOnrmM7COGuzD9xjUqd/FZklJf5YTSPwiCasmc2ewoWM0cpsoBVjDH4CSkgL6nhBbUHXK8hzZMfsWjOZvMIWcJpiIuLsAVdDkHP1PNKJaQhbdOE@lbTjNLz@Q8 "Python 3 (PyPy) – Try It Online")
[Try it online! (exact)](https://tio.run/##jVbbbts4EH33VxAo0JCyJItOEztFXaAF@moEKLCFYRgBdUuE2JQgyY2Y3X57dobU3XZ2/WCIo5kzl3M8dKbKp1ReL7P87S05ZGlekoMonyaTMIpJxqm0lS25rbhdsc8TAp8kJop8JYqbI35aJ7Iixhks@q2wfTtAK7x3pF05kjcggnwhHklz4jcPAT58JnlUHnNJPO1YH6iacY9ZlrAoVdxRzBx9OHLPUbw@BxYW7wbpwaeVLVjv6E8D22emr/IpkY@0rbRurE5VHA901DiJobqKJJLkQj5GlHPGZuh3r93OO0wmHwaJcEoMRnFPH49RUUAbTI@L/ENqgz7XJR6O@zKhUtmkmfs6XG13@mnTPsl0pdKVmRSWACmwiAJojEKIZj2OQkR3ZNpagAMwno7cJHNFlkUSQELWWhViKEcNMNQljE2LoXoYMsU6Okg8Gq3oCqumwkvVnVamq0IVtIFnSzot5xXitEBiEZRpnog9rdhspk1ZnoZ09BISmimHOOR1jVInebW6OMhg9AieJsBWOuY1yeg6tDcha2gWUoGGCPC83jREb@6hsPVmukV1McP0NzCh4owuwAWFcVZ26P195P2uMwwM/FcwsJaVLE9k2dXV7/Pb7Dsquy5c2Vsjb2a7rrsz@iZ0IGgQ@EjyjHxsTXNtmqMJEGAswV4UBfkrCuamHhzTw0Mik/LhgRbRPoZmoLCetNHoViieoUm10jIYMI0W4rkXX3eGKanBsp7tGsJ6Zj2E/D8g8IX13AsQYdj6/3435fS3WzVJ4Vn10yZllNcwpxj4km4NSAOwGxQdZZej4ytdw98m/o9NzJP6w64aKn4lZfD0owhEFtEfVRBlZZLKGikDh4Hfz2MQIK/vOf48iLzU3hcYHnO7BiLrjdfa8qiIStr1ac7nohOI9oamTQeIsUaKhqW@sOqr7q6z6H0DwXcjvHa1sH5wk35F9pE0PK/ZECwXSRH1R9wtSvwN6xBDbrIbtzWFtTfY5piJ497rQGs@xrTLbvDHIqpb70@uzNWw0JOhN5/YDH3YVU/enk149zbSuug3PEyzRmr2SVFS3JWm/1rVG8ZOK1o3k1@nMmInPJnArcN3g1e4@XVxc8uCFeeNOsKV3VuU3oizLjkCD66zdoHqq6W/209cgLAMxOWdYpsKgd3M0mk0RfHZ5rM0ow4/O/zXluIBw@SD7u8FCWjDcKE20xpn0z8CFFZ7n8b7VJT0KpHxFRsLq5pR/HvWzz0/k/xV5GEbKmz4D3g5u/8/svvc8wDCtyx4GNdE8a0FPOpvx2eOYFPBZhQPYGXGWl/JMX2p@cYr5cU1y4G7i@XNcuEt5/yOX3/ybq/by5Peki9w9@DXguH/WFqRrysyJwKu/yb@k7vkyxt@fbOE8MV8AXcg@NzCSBqPO8hv7t1uP1Lm6gHGjL29/Qs)
[Answer]
# R / Rcpp: 3531.3 ± 1.803
On average, the policy accrues ~3042.27 from searching number lines, and ~489 from resetting. Evaluated on 15 million simulated games. Bounds are a 95% bootstrap confidence interval with 10,000 iterations.
## Method
The policy generated for this problem was learned using the same genetic algorithm that I used in my solution to [Strategy: The cunning cousin witch](https://codegolf.stackexchange.com/q/251528/114139). You can find a more detailed description of the method and policy representation there.
The difference is that for this problem I learned two policies simultaneously. For each set of 100 number lines, the first policy was active during number lines 1 - 89, and the second policy was active during number lines 90 - 100. This gave the first policy an opportunity to search more optimally early in the set of number lines, while the second policy could focus on controlling the risk of needing a new set of number lines.
## Learned Policies
The first policy is active for the first 89 number lines, attempts to minimize the cost of searching. On average, this policy passes on 2.00 number lines that would have been possible to complete per episode.
The first policy is approximately
$$
\begin{bmatrix}
0.00 & 1.80\\
0.50 & 0.00\\
2.30 & 1.66\\
3.44 & 2.10\\
3.46 & 2.24\\
4.76 & 2.41\\
5.45 & 9.00\\
7.37 & 9.00\\
7.77 & 9.00\\
9.00 & 3.32\\
\end{bmatrix}
$$
The second policy is active during the last 11 number lines, and searches the number line more aggressively in order to offset the additional cost of not completing the game in time. On average, this policy passes on 1.11 number lines that would have been possible to complete per episode.
The second policy is approximately
$$
\begin{bmatrix}
0.00 & 2.96\\
0.76 & 0.40\\
1.84 & 0.98\\
3.31 & 1.30\\
3.08 & 1.00\\
4.60 & 9.00\\
9.00 & 9.00\\
6.21 & 9.00\\
6.06 & 9.00\\
6.79 & 2.14\\
\end{bmatrix}
$$
## Gene Importance
To better interpret the policies, it is useful to be able to measure how much each of the genes in those policies contributes to the overall score. For this problem, the matrix representing a policy is a chromosome, and each matrix address is a gene.
The problem of how to assign a fixed contribution to each gene can be thought of as a cooperative game because each gene's contribution to the overall score is mediated by all the other genes in the chromosome.
For an example of how genes affect each other, notice that in the second policy, \$p\_{2}\$, that \$p\_{2}(1, 1) = 0.40\$. Because \$p\_{2}(0, 1) = 2.96 > 0.76 = p\_{2}(1, 0)\$, the policy will never search the number line using \$p\_{2}(1, 1)\$. We may say that \$p\_{2}(1, 1)\$ has a contribution of zero since it is never used, but that is only because of the joint relationship between \$p\_{2}(0, 1)\$ and \$p\_{2}(1, 0)\$. A better option might be to assign the contribution of \$p\_{2}(1, 1)\$ jointly to both \$p\_{2}(0, 1)\$ and \$p\_{2}(1, 0)\$. But how much total to each?
To solve this problem I calculated the contribution of each gene using Shapley additive values (SHAP values). Relevant to this problem, SHAP values have the property that the sum of all gene contributions equals the chromosome's total value, and that each gene's SHAP value equitably accounts for the conditional relationships between all the other genes.
The SHAP values for both policies are shown below compared against a trivial policy that searches the number line in units of one. The interpretation of an address in the SHAP value matrix, \$s(x, y)\$, is, "Replacing address \$p(x, y)\$ in the trivial policy with its value in the learned policy changes the policy's total score by \$s(x, y)\$ on average."
The SHAP value matrix for the first policy is approximately
$$
\begin{bmatrix}
-0.53 & -318.01\\
148.98 & -0.75\\
-1.04 & -10.96\\
0.69 & -48.22\\
-2.68 & -86.70\\
-28.58 & -65.90\\
-51.29 & -239.74\\
17.75 & -357.69\\
-3.87 & -258.72\\
0.39 & -67.08\\
\end{bmatrix}
$$
The SHAP value matrix for the second policy is approximately
$$
\begin{bmatrix}
0.49 & -19.24\\
9.60 & 4.60\\
6.43 & 2.90\\
-0.21 & -3.16\\
-0.55 & -1.97\\
-4.93 & -27.43\\
11.70 & -52.22\\
-1.75 & -37.09\\
16.48 & -27.57\\
39.71 & -4.86\\
\end{bmatrix}
$$
Recall that these SHAP values are in comparison to the trivial policy of searching in units of one, not to a random policy. Given that the score of the trivial policy is about 4994.913, and the sums of both SHAP matrices are about -1373.944 and -89.07059 respectively, adding the values together gives 4994.913 - 1373.944 - 89.07059 = 3531.898, which is nearly the score we get from evaluating the learned policy directly.
Note: Because this is a minimization problem, more negative SHAP values are better since they represent a decrease in total cost.
## Code
The code used to run the genetic algorithm is nearly equivalent to my solution linked at the top of this answer, so here I include only the code used to define the algorithm itself where it differs from my previous implementation.
**Rcpp code to Define the Genetic Algorithm**
```
//* Generate Chromosome
// [[Rcpp::export]]
NumericVector generateChromosome() {
NumericVector chrom (40);
for(int i = 0; i < 20; i++){
if(i == 0 | i == 10){
chrom[i] = 0;
} else {
chrom[i] = chrom[i - 1] + Rcpp::runif(1, 0.0, 2.0)[0];
}
}
for(int i = 20; i < 40; i++){
chrom[i] = Rcpp::runif(1, 0.0, 2.0)[0];
}
return(Rcpp::clamp(0.0, chrom, 9.0));
}
//* Chromosome to Policy
// [[Rcpp::export]]
NumericMatrix chromToPolicy(NumericVector x) {
NumericVector policy = clone(x);
policy[0] = 0.0;
policy.attr("dim") = Dimension(20, 2);
return(as<NumericMatrix>(policy));
}
//* Evaluate Chromosome
//* Note: The cost of resetting (1000) isn't hardcoded here
//* Instead, the number of resets per episode is counted
//* The cost penalty is applied in a chromosome fitness function instead
// [[Rcpp::export]]
NumericMatrix evaluatePolicy(
NumericVector x,
int iters,
int maxCost = -1
) {
//Convert chromosome to policy
NumericMatrix policy = chromToPolicy(x);
//Run episodes
NumericMatrix out (iters, 6);
bool earlyStop = false;
for(int i = 0; i < iters; i++){
//Initialize values
NumericVector points = setPoints();
double lineSearched = 0;
int ptsFound = 0;
int lineCount = 1;
int polNum = 0;
//Begin episode
bool done = false;
while(!done) {
//Step forward if in policy
if(policy(ptsFound + polNum, 0) >= lineSearched){
lineSearched += policy(ptsFound + polNum, 1);
if(lineSearched > 9){
lineSearched = 9;
}
out(i, 0) += pow(2, lineSearched);
ptsFound = sum(points <= lineSearched);
} else {
//Otherwise, reset
//Code result
if(sum(points <= 9) == 10){
out(i, 4) += 1;
} else {
out(i, 2) += 1;
}
//Reset values
points = setPoints();
lineSearched = 0;
ptsFound = 0;
//Increase line count
lineCount += 1;
if(lineCount == 101){
lineCount = 1;
polNum = 0;
out(i, 1) += 1;
} else {
//Integer division -> floor(lineCount / 10)
if(lineCount / 10 + 1 > 9){
polNum = 10;
}
}
}
//Reset when line searched but fewer than 10 points found
if(lineSearched == 9 & ptsFound < 10){
//Code result
out(i, 3) += 1;
//Reset values
points = setPoints();
lineSearched = 0;
ptsFound = 0;
//Increase line count
lineCount += 1;
if(lineCount == 101){
lineCount = 1;
polNum = 0;
out(i, 1) += 1;
} else {
//Integer division -> floor(lineCount / 10)
if(lineCount / 10 + 1 > 9){
polNum = 10;
}
}
}
//Exit conditions
if(ptsFound == 10){
out(i, 5) += 1;
done = true;
}
//Early stop condition
if((maxCost >= 0 & out(i, 0) >= maxCost)){
out(i, 0) = NA_REAL;
earlyStop = true;
done = true;
}
}
if(earlyStop){
break;
}
}
//Return
return(out);
}
```
**R Code for the SHAP Algorithm**
```
# Characterize trivial policy
trivChrom <- c(0:9, 0:9, rep(1, 20))
trivOut <- evaluatePolicy(trivChrom, 15000000, 1000000)
trivOut <- mean(trivOut[, 1] + 1000 * trivOut[, 2])
# Characterize full policy
x <- readRDS(r"minPolicy_3472_121.rds")
evOut <- evaluatePolicy(x, 15000000, 1000000)
evOut <- mean(evOut[, 1] + 1000 * evOut[, 2])
# Initialize parameters
tol <- 5
iters <- 500
# Shapley algorithm
shapVals <- rep(0, length(x))
t <- 0
while(TRUE){
# Increment t
t <- t + 1
# Permute the gene order
geneOrder <- sample(1:length(x), length(x), replace = FALSE)
# Calculate shap value
shapPol <- trivChrom
v <- rep(NA, length(x) + 1)
v[1] <- trivOut
for(j in 1:length(x)){
if(abs(evOut - v[j]) < tol){
v[j + 1] = v[j]
} else {
shapPol[geneOrder[j]] = x[geneOrder[j]]
shapEv = evaluatePolicy(shapPol, 100000, 10000000)
shapEv = mean(shapEv[, 1] + 1000 * shapEv[, 2])
v[j + 1] = ifelse(is.na(shapEv), v[j], shapEv)
}
shapVals[geneOrder[j]] = (t - 1) / t * shapVals[geneOrder[j]] + (1 / t) * (v[j + 1] - v[j])
}
# Exit conditions
if(t >= iters){
break
}
}
```
```
[Answer]
# Python, average cost = 3498 +/- 5
Shamelessly steals the policy from Renaldi (thanks!), but always applies it to the number line with the highest probability of having 10 points instead of going through them one at a time. I tried to incorporate the backup policy, but that ended up making things worse. I'm not sure why my Gittin's Index answer doesn't work very well; I guess some assumption must be subtly violated or I have a bug somewhere.
```
import heapq
import functools
import random
import numpy as np
from scipy.stats import binom
def logsumexp(x):
m = x.max()
return np.log(np.sum(np.exp(x - m))) + m
@functools.lru_cache(None)
def log_p_win(a, n):
k = np.arange(n, 11)
u = np.zeros(k.shape) if a == 0 else binom(k, a / 10).logpmf(n)
d = binom(k - n, (9 - a) / (10 - a))
t = np.zeros(11 - n)
for i in range(11 - n):
t[i] = logsumexp(u + d.logpmf(i))
return t[-1] - logsumexp(t)
policy = [
[0, 0.5, 2.3, 3.44, 3.46, 4.76, 5.45, 7.37, 7.77, 9],
[1.8, 0, 1.66, 2.1, 2.24, 2.41, 9, 9, 9, 3.32],
]
while True:
mean_cost = 0
sse_cost = 0
queue = []
done = True
trials = 0
cost = 0
while True:
if done or not queue:
if not done:
cost += 1000
lines = [
[random.uniform(0, 10) for _ in range(random.randrange(11))]
for _ in range(100)
]
del queue[:]
for i, _ in enumerate(lines):
heapq.heappush(queue, (-log_p_win(0, 0), 0, 0, i))
done = False
v, n, a, i = heapq.heappop(queue)
if a <= policy[0][n]:
a = min(9, a + policy[1][n])
else:
continue
cost += 2 ** a
n = sum(1 for x in lines[i] if x <= a)
if n == 10:
done = True
trials += 1
d = (cost - mean_cost)
mean_cost += d / trials
sse_cost += d * (cost - mean_cost)
if trials % 100 == 0:
print(trials, mean_cost, np.sqrt(sse_cost) / trials)
cost = 0
continue
if a == 9:
continue
v = -log_p_win(a, n)
heapq.heappush(queue, (v, n, a, i))
```
[Answer]
# Python, score ~= 3922
Repurposes some of my code from the Witch challenge. Uses a Gittins Index strategy, where the cost of resetting is estimated empirically.
```
import heapq
import functools
import random
import numpy as np
from scipy.stats import binom
bound = 16153
samples = 50
g = np.linspace(0, 9, samples)
def logsumexp(x):
m = x.max()
return np.log(np.sum(np.exp(x - m))) + m
def init_trans(samples):
print("computing transition matrix...\n")
trans = np.full((samples, 10, samples, 11), float('-inf'))
g = np.linspace(0, 9, samples)
for i0 in range(samples - 1):
print(f"computing row {i0} of {samples}", end='\r', flush=True)
g0 = g[i0]
for n in range(10):
k = np.arange(n, 11)
u = np.zeros(k.shape) if i0 == 0 else binom(k, g0 / 10).logpmf(n)
for i1 in range(i0 + 1, samples):
g1 = g[i1]
d = binom(k - n, (g1 - g0) / (10 - g0))
for m in range(n, 11):
v = d.logpmf(m - n)
trans[i0,n,i1,m] = logsumexp(u + v)
print()
trans -= trans.max(axis=-1, keepdims=True)
trans = np.exp(trans)
trans /= trans.sum(axis=-1, keepdims=True)
return trans
trans = init_trans(samples)
@functools.lru_cache(None)
def gittins_value(i0, n0, v0):
if n0 == 10:
return (0, None)
if i0 == samples - 1:
return (v0, None)
v = v0
i = None
for i1 in range(i0 + 1, samples):
v1 = sum(trans[i0,n0,i1,n1] * (2 ** g[i1] + gittins_value(i1, n1, v0)[0]) for n1 in range(n0, 11))
if v1 <= v:
v = v1
i = i1
return (v, i)
@functools.lru_cache(None)
def gittins_index(i0, n0):
low = 0
high = bound
best_action = i0 + 1
while high - low >= 1e-9:
mid = low + 0.5 * (high - low)
v, i1 = gittins_value(i0, n0, mid)
if v == mid:
low = mid
else:
high = mid
best_action = i1
return high, best_action
mean_cost = 0
reset_cost = bound
queue = []
reset = True
trials = 0
cost = 0
while True:
if reset:
lines = [
[random.uniform(0, 10) for _ in range(random.randrange(11))]
for _ in range(100)
]
del queue[:]
for i, _ in enumerate(lines):
heapq.heappush(queue, gittins_index(0, 0) + (i,))
reset = False
v, a, i = heapq.heappop(queue)
if v > 1000 + reset_cost:
cost += 1000
reset = True
continue
cost += 2 ** g[a]
n = sum(1 for x in lines[i] if x <= g[a])
if n == 10:
reset = True
trials += 1
mean_cost += (cost - mean_cost) / trials
reset_cost += (cost - reset_cost) / (trials + 100)
cost = 0
print(trials, mean_cost)
continue
if a == samples - 1:
reset = not queue
continue
heapq.heappush(queue, (gittins_index(a, n) + (i,)))
```
] |
[Question]
[
Given a random code written using Brainfuck commands. You program should translate that code into the following ascii art: each Brainfuck command represents as `5x9` array of `A` and `B` symbols. All commands are concatenated with `5x3` arrays of `A` symbols. Symbols `A` and `B` you choose yourself.
For example, when input is `><+,.[]` your program might output:
```
== == = = = = = = =
== == = = =
== == = = = = = = =
== == = = = = =
== == = = = = = = = =
```
Or
```
@@ @@ @ @ @ @ @ @ @
@@ @@ @ @ @
@@ @@ @ @ @ @ @ @ @
@@ @@ @ @ @ @ @
@@ @@ @ @ @ @ @ @ @ @
```
Or even
```
..ooooooooooooooooo..ooooooo.ooooooooooooooooooooooooooooooooo.o.o.ooooooo.o.o.oo
oooo..ooooooooo..ooooooooooo.ooooooooooooooooooooooooooooooooo.ooooooooooooooo.oo
ooooooo..ooo..oooooooooo.o.o.o.o.ooooooooooooooooooooooooooooo.ooooooooooooooo.oo
oooo..ooooooooo..ooooooooooo.ooooooooooo.ooooooooooo.ooooooooo.ooooooooooooooo.oo
..ooooooooooooooooo..ooooooo.oooooooooo.oooooooooooooooooooooo.o.o.ooooooo.o.o.oo
```
And etc. Trailing spaces and `A` symbols are allowed.
It is guaranteed that the input will consist only of the symbols `>` `<` `+` `,` `.` `[` `]`.
This is a code-golf challenge so the shortest solution wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 57 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“ṾÆxÑ3øḤC⁵ịJYSLẇɱ⁼’Bs3ŒBJṫ⁴Ɗ¦z1m€0Ṛs€9
⁽HṠ,17ḥⱮịⱮ¢j€⁶ẋ3¤Y
```
A full program accepting a string as the first program argument that prints the result, using `0` for ink and `1` for no ink.
**[Try it online!](https://tio.run/##AYsAdP9qZWxsef//4oCc4bm@w4Z4w5Ezw7jhuKRD4oG14buLSllTTOG6h8mx4oG84oCZQnMzxZJCSuG5q@KBtMaKwqZ6MW3igqww4bmac@KCrDkK4oG9SOG5oCwxN@G4peKxruG7i@KxrsKiauKCrOKBtuG6izPCpFn/w4fhuaMxS///IixbKys@KzxdPi4i "Jelly – Try It Online")** (The footer just replaces the `1`s with spaces to make it easier to inspect.)
### How?
```
“...’Bs3ŒBJṫ⁴Ɗ¦z1m€0Ṛs€9 - Link 1: no arguments
“...’ - 43552819895870853685529620449548093603391
B - in binary
s3 - split into chunks of length 3
-> columns of the bottom half of 5 of the 7 characters
the '[' and '>' are created using reflection later
the comma is reversed too, we'll use its reflection
¦ - sparse application...
Ɗ - ...to indices: last three links as a monad:
J - range of length
⁴ - 16
ṫ - tail (covers the columns containing ',' and '.')
ŒB - ...apply: bounce ("something" -> "somethingnihtemos")
z1 - transpose with filler 1 (fills where we didn't reflect)
m€0 - reflect each (constructing our ']', '>', and ',')
Ṛ - reverse
-> a list of the lines of a representation (without
any spacing) of ",.+<][>+.," where the first
comma is reversed.
s€9 - split each line into chunks of length 9
⁽HṠ,17ḥⱮịⱮ¢j€⁶ẋ3¤Y - Main Link: list of characters, C
⁽HṠ,17 - [19206,17]
Ɱ - map across C with:
ḥ - hash with salt 19206 and domain [1,2,...,17]
-> maps: ".[,+<]>" to 2,6,10,13,14,15,17
¢ - call Link 1 as a nilad
Ɱ - map across the lines of the result with:
ị - index into
-> 1-indexed and modular, so e.g. 17 gets the 7th item,
the part of the line for a '>'.
¤ - nilad followed by links as a nilad:
⁶ - space character
ẋ3 - repeated three times
j€ - join each list of line parts with three spaces
Y - join with newline characters
- implicit, smashing print
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 73 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
T>740SúÂX4úD‚„1 9∍ª1D‚7bš9j3δ._Ðí)εû.B}X3úĆS4ú€ûÐ3èÀ4ǝ‚«Ž5¹.IIÇ52%èø3ð×ý»
```
Uses spaces for \$A\$ and `1` for \$B\$.
It could definitely be golfed by using a different approach, but this will do for now.
[Try it online.](https://tio.run/##AYUAev9vc2FiaWX//1Q@NzQwU8O6w4JYNMO6ROKAmuKAnjEgOeKIjcKqMUTigJo3YsWhOWozzrQuX8OQw60pzrXDuy5CfVgzw7rEhlM0w7rigqzDu8OQM8Oow4A0x53igJrCq8W9NcK5LklJw4c1MiXDqMO4M8Oww5fDvcK7//8rLC48PltdKysr)
**Explanation:**
Step 1: Create a list of all shapes:
Step 1a: top halve of `<`:
```
T> # Push 11 (10 increments by 1)
740S # Push 740 as list: [7,4,0]
ú # Pad the "11" with that many leading spaces:
# [" 11"," 11","11"]
```
Step 1b: top halve of `>`:
```
 # Bifurcate it (short for Duplicate & Reverse copy):
# ["11"," 11"," 11"]
```
Step 1c: top halve of `+`:
```
X # Push 1
4ú # Pad it with 4 leading spaces: " 1"
D‚ # Pair it with a copy of itself: [" 1"," 1"]
„1 # Push string "1 "
9∍ # Enlarge it to size 9: "1 1 1 1 1"
ª # Append it to the pair:
# [" 1"," 1","1 1 1 1 1"]
```
Step 1d: top halve of `]`:
```
1D‚ # Push pair [1,1]
7bš # Prepend "111" (7 as binary string): [111,1,1]
9j # Prepend spaces until all are length 9:
# [" 111"," 1"," 1"]
δ # Map over each string:
3 ._ # Rotate it 3 times towards the left:
# [" 111 "," 1 "," 1 "]
```
Step 1e: top halve of `[`:
```
Ð # Triplicate the list
í # Reverse each inner string:
# [" 111 "," 1 "," 1 "]
```
Step 1f: palindromize all of the top halves pushed thus far to get the full shapes:
```
) # Wrap the items on the stack into a list
ε # Map over each inner list:
û # Palindromize the list to add the bottom halves
.B # Box: add trailing spaces to each line up to the longest line
} # Close the map
```
Step 1g: `.`:
```
X # Push 1
3ú # Pad it with 3 leading spaces: " 1"
Ć # Enclose; append its own head: " 1 "
S # Convert it to a character-list: [" "," "," ","1"," "]
4ú # Pad each with 4 spaces:
# [" "," "," "," 1"," "]
€û # Palindromize each inner string
# [" "," "," "," 1 "," "]
```
Step 1h: `,`:
```
Ð # Triplicate the list
3è # Pop one and leave its 4th string: " 1 "
À # Rotate it once towards the right: " 1 "
4ǝ # Replace the 5th string with this:
# [" "," "," "," 1 "," 1 "]
‚ # Pair the shapes for `.` and `,` together
« # Merge them to the earlier list of shapes
```
We now have a list of all shapes (with an additional shape for `[` due to the triplicate instead of duplicate we've used in step 1e, which will be ignored in (but is necessary for) step 2.
[Try just step 1 online.](https://tio.run/##yy9OTMpM/f8/xM7cxCD48K7DTREmh3e5PGqY9ahhnqGC5aOO3kOrDEF886SjCy2zjM9t0Ys/POHwWs1zWw/v1nOqjTA@vOtIWzBQ06OmNYd3H55gfHjF4QaT43OBWg6t/v/fzkZbRy86FgA)
Step 2: Use the input to get the correct shapes from this list:
```
Ž5¹ # Push compressed integer 1459
.I # Get the (0-based) 1459'th permutation of the list of shapes:
# It converts shape-order `<>+]][.,` to `<]>+,].[`
I # Push the input-string
Ç # Convert it to a list of codepoints
# "><+,.[]" would become [62,60,43,44,46,91,93]
52% # Modulo-52 each: [10,8,43,44,46,39,41]
è # 0-based modular index it into the list of shapes
# (the implicit modular indexing acts as modulo-8: [2,0,3,4,6,7,1])
```
[Try just steps 1 and 2 online.](https://tio.run/##AXcAiP9vc2FiaWX//1Q@NzQwU8O6w4JYNMO6ROKAmuKAnjEgOeKIjcKqMUTigJo3YsWhOWozzrQuX8OQw60pzrXDuy5CfVgzw7rEhlM0w7rigqzDu8OQM8Oow4A0x53igJrCq8W9NcK5LklJw4c1MiXDqP//PjwrLC5bXQ)
Step 3: Convert the list of shapes to the correct format and output it as result:
```
ø # Zip/transpose the list of shapes; swapping rows/columns
3ð× # Push a string of 3 spaces: " "
ý # Join each inner list with this delimiter
» # Then join the list of lines by newlines
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž5¹` is `1459`
[Answer]
# [J](http://jsoftware.com/), ~~272~~ 236 bytes
```
l=.|."1 r =.5 9&$@((36$2)&#:)51545900568
p=.5 9&$@((27$2)&#:)4202837
d=.,&(9$0)@}:c=.|.((2 9&$@((15$2)&#:)2050),3 9$0)
m=.|."1 n =.5 9&$@((43$2)&#:)1445260697621
{&' #'@>@(,.&.>/)({&(r;l;p;c;d;n;m;5 3$0)@('><+,.[]_'&i.))"0@((,'_'&,)/) y
```
-36 bytes by using Catalogue `{` instead of Agenda `@.`
[Try it online!](https://tio.run/##TY3LasMwEEX3@oohMZKGionejq1Y@D@MycJpaEuShuxK2m93bRC0y8s9nPMxn6FrwUELer509E0bAw/oKEDDq15KFyuLfNtiMMGHRusQ9@z@99u6/N5qu3c1O3WkuGwqjf1PO63GBSqwCQW2OmhUDlaMXUv29i/rXSGN98FGHZs6WsOeXMBW9LmXijjlHconl490Sfc0pVO6pWsK4Na2FPnwomgYj4K/E@JGL1YllqVwh/A1I2Ov09snnEEM45gPA6ks5l8 "J – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 257 bytes
```
lambda s:'\n'.join(list(map(lambda i:print("111".join([list(map(lambda s:str(s)[3:],map(bin,[0x9FFF9EFFFFFF57AB,0xF9F9FEFFFFFF7FFB,0xFF0FEAAFFFFF7FFB,0xF9F9FEFF7FBF7FFB,0x9FFF9EFEFFFF57AB])))[i][(p:="><+,.[]".index(c))*9:(p+1)*9]for c in s])),[0,1,2,3,4])))
```
I don't know why it gives me an TypeError, but it works :)
[Try it online!](https://tio.run/##XY/BDoIwDIZfhexipwthokEWIcGEvsTcAVHjjI6FEYNPjxPxoOuhyde/Xzr77C6NiTe2HR7ZfrhV98OxCpyY7c0svDbawE27Du6VhWmmhW216YBwzsknIv8zTriuBUdlLBR784M2TEZ9iohpieNbJ8WORT2mviaUII4IIyyL4gdNqQR3XzS5yq9LUUqlVhKsyEi@XbBQKhJqczz1UFM6TwXYBfddnZs2qANtAud3/FmMsyWL2eptGD6fewCRajtacuLpCw "Python 3.8 (pre-release) – Try It Online")
] |
[Question]
[
Help! I printed a bunch of rational numbers with no spaces or other delimiters other than the `/` in the fractions. There is, however, good news! All the numbers are positive. There are no improper fractions, every numerator is less than its denominator and any integers are represented directly, not as fractions. Any non-integers greater than 1 are represented as an integer followed by a fraction. Every fraction is reduced to lowest terms, no numerator and denominator have any common factors other than 1.
Using this information, and given a string that I've printed, I need you to tell me what the original numbers could have been. If there are multiple possibilities, I want to know all of them.
## Examples
given as `input` => `output`.
`1` => `1`
`1/2` => `1/2`
`12/3` => `1`,`2/3` and `1 2/3` (or, equivalently, `5/3`)
`2/34` => `2/3`,`4` (cannot be `2/34` because 2 and 34 share a factor of 2)
`12/35` => `12/35` and `1 2/35` and `1`,`2/35` and `1`,`2/3`,`5`
`12/345/678/9` => `1`,`2/3`,`4`,`5/6`,`7`,`8/9` and `5/3`,`29/6`,`71/9` and `5/3`,`45/67`,`8/9` and ...
## Rules
You can assume there is at least one valid way to delimit the input.
Your results can contain improper or mixed fractions, you can represent 5/3 as `5/3` or `1 2/3`. You can use any kind of delimiters, as long as each type of delimiter (start and end of a list, between numbers, between integer and fraction in a mixed fraction, between numerator and denominator in a fraction) is unique and consistent. You can take input from stdin, or function parameters, or command line options. You can print your results, or return them from a function, or even just leave them in a variable.
[Answer]
# [Haskell](https://www.haskell.org/), 480 bytes
```
c""=[]
c('/':x)=c x
c x|(f,b)<-span(/='/')x=f:c b
i x[]=[[x]]
i x(y:z)=(x:y):z
s[x]=[[[x]]]
s(x:y)=[p|s<-s y,p<-[i x s,[x]:s]]
m[[b],[c]]=[[b++'/':c]]
m[[a,b],[c]]=[[a++'+':b++'/':c],[a,b++'/':c]]
m([b]:((c:d:e):f))=map((b++'/':c):)$m$(d:e):f
m([a,b]:((c:d:e):f))=[p++s|s<-m((d:e):f),p<-m[[a,b],[c]]]
m((x:y):z)=map(x:)$m$y:z
l=length
o i=[o|s<-sequence$map s$c$i,and[n<d&&gcd n d==1|i<-[1..l s-1],
let[n,d]=read<$>[last$s!!pred i,s!!i!!0]],
and[l(s!!i)>1|i<-[1..l s-2]],o<-m s]
```
[Try it online!](https://tio.run/##VZDbjsIgGITveQraNAop2q17JsUXIVwgoJKltCvdpBrfvQu6B70g@TPzMczPXoYP49w0qTxnXACF5tWcjpgpOIJ4zmhLNrhZhF56VLFo4pFtqYIbYOHIBeN8FCLN6EhPmKGRHjE9gRDl6CVTgHBRGe/PISbBI@mbBY9XYCARoCEiLecbQbgS6damLFMLddUl@XdkdMo5/QNIcm9oFFMoQopqajDdYsxa2SP0i2CKi7ZAVzPRKfue531ZhtSzRT8cTnVve6R3fva85o@X2Lg/cMwZvxv2oIOW8e6yr/n8Ml6ZIpIwFKqwRHrNfaNns53S0EPNWH228Uvq5dLBsKgFAdCZgXuiBTsYqZtizZ0MQxGyrD8YDS2Jk82yB5HYlOdQUvD6LmkV7S6Wh0FMrbSe9Qfrh6LL61X1@PRcvby@Ve/59A0 "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/), 650 bytes
```
chunks""=[]
chunks('/':xs)=chunks xs
chunks xs|(front,back)<-span(/='/')xs=front:chunks back
insert x[]=[[x]]
insert x(y:ys)=(x:y):ys
splits[x]=[[[x]]]
splits(x:xs)=[p|s<-splits xs,p<-[insert x s,[x]:s]]
merges[[b],[c]]=[[b++'/':c]]
merges[[a,b],[c]]=[[a++'+':b++'/':c],[a,b++'/':c]]
merges([b]:((c:d:e):f))=[(b++'/':c):s|s<-merges$(d:e):f]
merges([a,b]:((c:d:e):f))=[p++s|
s<-merges((d:e):f),p<-merges[[a,b],[c]]]
merges((x:xs):ys)=map(x:)$merges$xs:ys
origins input=[m|s<-sequence$map splits$chunks$input,
and[length(s!!i)>1|i<-[1..length s-2]],
and[n<d&&gcd n d==1|i<-[1..length s-1],
let[n,d]=read<$>[last$s!!pred i,s!!i!!0]],m<-merges s]
```
[Try it online!](https://tio.run/##ZZHdbuMgEIXveQoSWQnIJN50t90Whb4I4oLYNEGxKetxJEfKu2cH23Gl9o6Z@c78HE4Wzq6u7/fydAlnWC6VNmR8s3Wxlj1wNYa0BzK/buyj/QydONjyzPcbiDawQqGA96CGkpzYRBDiA7i2o702SuvemDnBrvKKI1gvrxxfhECsfQfIIJhIM2WQSLvoeIM0L6VwDxH3G/3oRUGgQgJqSOPaowOtD0bo0qRmhzxPB2EwF634Klss52s5UyJVv0sY9pOMlbKSjssPjvuwB8QlpNVGMGMj8SVMs75JY57DjdBZxCYRT1f92HFuNTox2NbYiBHPpqE9DBZ@tv6InlAf4qVTuhkcc/8uLpQuQwkd7cvGH8oGTBBqQ6VrF47dicFi4fn77ubR3d12O2YpbJ6MmcCwr1arY1nRQCulfpK7BNau00FURrXOVvvsXdcWugybx9ZV1Is0ZrH4hU2bx8EUzL2xPqjY@tBl0ynL3VPx@89z8fL3tXhb3v8D "Haskell – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~188~~ 185 bytes
```
f=([c,...x],y='')=>c?f(x,y+c)-f(x,y+[,c])-f(x,y+' '+c):y.split`,`.some(e=>e.replace(/(?:[1-9]\d* ?)??(?:([1-9]\d*)\/([1-9]\d*))?$/,g=(_,a,b)=>+a>=b|!_?1:a?g(1,b%a,a):b-1||''))||print(y)
```
[Try it online!](https://tio.run/##Tc7disIwEAXge59CwSUzOk2If6td0jxILTWNqXRxd0tbxELevRvQolfzzTkXM9/mZlrbVHUX3fbDUCpILXHO7xn1ijFUidUl3KlfWoweSMlmo9mUhSLueVtfq@5EJ97@/ThwKnG8cfXVWAcCdJzK6JAdz4upRq3DDmOAR/Ey6rmgi4KcDBXh9NIkqvCzXMvY6AtIKj4MGYyLSHofnkPv66b67aDH4WtSApMMH1OsRq3E@smgzVu6ffNmK3afe3EI0fAP "JavaScript (V8) – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[Bubble sorting in progress](/questions/92753/bubble-sorting-in-progress)
(13 answers)
Closed 7 years ago.
Your task is to create a program that performs a [bubble sort](https://en.wikipedia.org/wiki/Bubble_sort) on a given array until it is sorted.
---
## Algorithm
In order to qualify as a bubble sort, the program must operate as follows:
* Each pass goes through the array, looks at every two adjacent elements in turn, and potentially swaps them.
* Each pass goes through the array in the same direction and without gaps. There are no partial passes - each pass must go through the whole array.
* The program must never compare or swap array elements that aren't adjacent.
* A sufficient (and finite) number of passes must be performed, such that the output array is guaranteed to be sorted. (E.g. you can safely stop if there was a whole pass without any swaps, or after `len(array)` passes have been made, etc.)
---
## Rules
1. You must provide a sufficient explanation for how your answer does a bubble sort.
2. You may *not* use built-in or standard library sorting algorithms. You must make your own code.
3. Your program should take an array of numbers as input and output them in the correct order.
* Input: `10 5 9 2 . . . (and so on)`
* The program should *always* output the sorted array.
* Output can be an array returned by the program when run, or it can modify the input array in-place.
* Output can also be the correctly ordered values separated by whitespace.
4. Speed does not matter as much as if the program functions.
---
## Test Cases
* `10 5 9 2 1 6 8 3 7 4` (you can format it differently depending on your language)
* `1 2 5 4 3`
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
## Haskell, ~~55~~ 53 bytes
```
f(a:b:c)=min a b:f(max a b:c)
f x=x
foldr(\_->f)=<<id
```
Usage example: `foldr(\_->f)=<<id $ [3,1,6,4,3,8,3,1,1,2]` -> `[1,1,1,2,3,3,3,4,6,8]`. [Try it online!](https://tio.run/nexus/haskell#@5@mkWiVZJWsaZubmaeQqJBklaaRm1gBZiVrcqUpVNhWcKXbpuXnpBRpxMTr2qVp2trYZKb8z00EqrdVKCjKzCtRUFFIV4g21jHUMdMx0THWsdABsQ11jGL/AwA "Haskell – TIO Nexus").
How it works: `f` does one iteration by keeping the minimum of the first two elements and appending a recursive call with the maximum of the first two elements and all the other elements. It stops when there are less than two elements in the list. The main function calls `f` `length <input>` times by iterating over the input list via `fold` but ignoring the elements.
[Answer]
# Octave, ~~77~~ 75 bytes
```
i=1;while any(diff(x)<0),i=mod(i,rows(x)-1)+1;x(i:i+1)=sort(x(i:i+1));end,x
```
A crude first attempt. I'm sure I'll be able to golf this a bit. Takes input as a row vector.
**Explanation:**
```
i=1; % Initialize iterator to 1;
while % Start loop
diff(x) % diff(x) creates a vector with the difference between
% adjacent elements
diff(x)<0 % Checks if there are less than 0 (unsorted vector)
any(diff(x)<0) % True if there's at least one negative difference
i=mod(i,rows(x)-1)+1 % i++, but loop around if it's equal to the number of rows
x(i:i+1)=sort(x(i:i+1); % Take two adjacent elements, sort them and put them back in
end,x % End loop and display result
```
[Answer]
## SmileBASIC, 79 bytes
```
DEF S A
FOR Z=0TO I
FOR I=1TO LEN(A)-1SWAP A[I-(A[I-1]>A[I])],A[I]NEXT
NEXT
END
```
This one is pretty simple. It just runs `LEN(A)` (actually LEN(A)+2 just in case) iterations of bubble sort, which is guaranteed to sort the array.
The only slightly interesting part is how I avoided using IF/THEN:
`SWAP A[I-(A[I-1]>A[I])],A[I]`. If the two adjacent values are in the wrong positions (if `(A[I-1]>A[I])` is true), it swaps `A[I-1]` with `A[I]`, otherwise it swaps `A[I-0]` with `A[I]`, which does nothing.
[Answer]
# [Perl 6](http://perl6.org/), 44 bytes
```
{.[*]=.[1,0]if [<] $_ for |(.[1..*]Z$_)xx$_}
```
Takes an array of numbers, and modifies it in-place (so that it is sorted after calling the lambda).
### How it works
```
{ } # A lambda taking one argument.
# e.g [a,b,c]
.[1..*]Z$_ # Zip it with itself offset by one.
# e.g. (b,a),(c,b),(d,c)
|( )xx$_ # Repeat this by the input's length.
# e.g. (b,a),(c,b),(d,c),(b,a),(c,b),(d,c),(b,a),(c,b),(d,c)
for # For each of those pairs:
if [<] $_ # If its 1st element is less than the 2nd:
.[*]=.[1,0] # Swap their values.
```
This works because the elements of a Perl 6 array are actually mutable item containers (akin to pointers in C except that they hide themselves well). So in the list we iterate over, each pair consists of two item containers from the array.
[Answer]
**Javascript ~~98~~, ~~97~~, 91 Bytes**
edit: removed unneeded semicolon and fixed broken code. Also moved some variable declarations and increments around.
```
x=>{for(h=1;h--;){for(i=d=0;d<x.length;i=d++){if(x[i]>x[d]){y=x[i];x[i]=x[d];x[d]=y;h=1}}}}
```
Ungolfed:
```
x=>{
for(h=1;h--;){
for(i=d=0;d<x.length;i=d++){
if(x[i]>x[d]){
y=x[i];
x[i]=x[d];
x[d]=y;
h=1
}
}
}
}
```
Explanation:
```
x=>{
for(h=1;h--;){ //set the change tracker, h, to true. On the start of each loop, evaluate it, then decrement it.
//If true, sets to false. If false, exits the loop and sets it to -1.
for(i=d=0;d<x.length;i=d++){ //i and d are our array indexers. They're both set to null for the first loop, then on subsequent loops i is set to d, then d is incremented.
// Therefore, on each subsequent loop, d will be 1 more than i.
if(x[i]>x[d]){ //if the previous value, i, is greater than the current value, d, switch their places using the temporary variable y.
y=x[i];
x[i]=x[d];
x[d]=y;
h=1 //set the change tracker to true.
}
}
}
}
```
It's rather simple and embarrassingly long, so any suggestions are greatly appreciated!
[Answer]
# Python 2, 104 bytes
Straightforward implementation.
```
L=input()
while L!=sorted(L):
for i in range(len(L)-1):
if L[i]>L[i+1]:L[i],L[i+1]=L[i+1],L[i]
print L
```
[**Try it online**](https://tio.run/nexus/python2#@@9jm5lXUFqioclVnpGZk6rgo2hbnF9Ukpqi4aNpxaWQll@kkKmQmadQlJiXnqqRk5oHFNc1BEpxZqYp@ERnxtoBCW3DWCsQWwfCtoVQIF4sV0FRZl6Jgs///9GmOiY6xjpGOoaxAA)
While not sorted, for each index in the list, swap with next item if greater.
] |
[Question]
[
**This question already has answers here**:
["99 Bottles of Beer"](/questions/64198/99-bottles-of-beer)
(168 answers)
Closed 7 years ago.
**EDIT** It is not clear how answers to the question of compressing a long text, without cumulative properties are relevant to golfing a short cumulative strong, any more than general Lempel Ziv techniques are relevant to code-golfing. Take note that the complexity of 99 bottles of beer is not O(Sqrt(n))
Knuth suggested the notion of theoretical [complexity of songs](https://en.wikipedia.org/wiki/The_Complexity_of_Songs) (Knuth, Donald E. "The complexity of songs." Communications of the ACM 27.4 (1984): 344-346.), noting that most cumulative songs are O(sqrt(n)).
Cumulative songs never showed up in PPCG. The challenge this time is [Chad Gadya](https://en.wikipedia.org/wiki/Chad_Gadya), a famous cumulative song in Aramaic and Hebrew, sung in cumulation of the [seder](https://en.wikipedia.org/wiki/Passover_Seder). The lyrics can be found, e.g., [here](http://www.piyut.org.il/textual/348.html) (blue text). (There are slight variations, so use this one, copied below).
To state the obvious, Chad Gadya belongs in the complexity class of the famous "Läuschen und Flöhchen" tale by the [Grimm brothers,](https://en.wikipedia.org/wiki/Brothers_Grimm) and some other more or less famous English songs, i.e., O(sqrt n).
The challenge is to write a program, in any programming language, that produces the song, each verse in its own line. The program takes no input, and cannot cheat by using, e.g., `wget`. A greater challenge is to make the solution so small that it can fit in a twitter message. (I bet no one here would be able to meet this challenge)
A short such program could be useful for twitter/sms holiday greetings. Please minimize the number of bytes (not characters). Output should be in UTF8.
**Why is this interesting?**
* Knuth paper on the the complexity of cumulative songs
* Song is *very* short; standard tricks would not help.
* Space savings in [Niqqud](https://en.wikipedia.org/wiki/Niqqud) is an extra challenge.
* Repetitions are not only due to the cumulative nature of the song.
* The twitter objective seems impossible.
* The song itself is quite short, much shorter than other songs that have been posted here. Compression of short text is more challenging than that of long text.
**Output**
```
חַד גַּדְיָא, חַד גַּדְיָא דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא שׁוּנְרָא, וְאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא כַלְבָּא, וְנָשַׁךְ לְשׁוּנְרָא, דְּאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא חוּטְרָא, וְהִכָּה לְכַלְבָּא, דְּנָשַׁךְ לְשׁוּנְרָא, דְּאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא נוּרָא, וְשָׂרַף לְחוּטְרָא, דְּהִכָּה לְכַלְבָּא, דְּנָשַׁךְ לְשׁוּנְרָא, דְּאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא מַיָּא, וְכָבָה לְנוּרָא, דְּשָׂרַף לְחוּטְרָא, דְּהִכָּה לְכַלְבָּא, דְּנָשַׁךְ לְשׁוּנְרָא, דְּאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא תוֹרָא, וְשָׁתָה לְמַיָּא, דְּכָבָה לְנוּרָא, דְּשָׂרַף לְחוּטְרָא, דְּהִכָּה לְכַלְבָּא, דְּנָשַׁךְ לְשׁוּנְרָא, דְּאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא הַשּׁוֹחֵט, וְשָׁחַט לְתוֹרָא, דְּשָׁתָה לְמַיָּא, דְּכָבָה לְנוּרָא, דְּשָׂרַף לְחוּטְרָא, דְּהִכָּה לְכַלְבָּא, דְּנָשַׁךְ לְשׁוּנְרָא, דְּאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא מַלְאַךְ הַמָּוֶת, וְשָׁחַט לְשׁוֹחֵט, דְּשָׁחַט לְתוֹרָא, דְּשָׁתָה לְמַיָּא, דְּכָבָה לְנוּרָא, דְּשָׂרַף לְחוּטְרָא, דְּהִכָּה לְכַלְבָּא, דְּנָשַׁךְ לְשׁוּנְרָא, דְּאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא הַקָּדוֹשׁ בָּרוּךְ הוּא, וְשָׁחַט לְמַלְאַךְ הַמָּוֶת, דְּשָׁחַט לְשׁוֹחֵט, דְּשָׁחַט לְתוֹרָא, דְּשָׁתָה לְמַיָּא, דְּכָבָה לְנוּרָא, דְּשָׂרַף לְחוּטְרָא, דְּהִכָּה לְכַלְבָּא, דְּנָשַׁךְ לְשׁוּנְרָא, דְּאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
```
If you find it hard to deal with Hebrew and Aramaic (tough luck...), try first getting your hands dirty with [Läuschen und Flöhchen](https://www.google.co.il/search?client=ubuntu&channel=fs&q=L%C3%A4uschen%20und%20Fl%C3%B6hchen&ie=utf-8&oe=utf-8&gfe_rd=cr&ei=9VYgV4CQM6WG8Qe_77-gCg), and then proceed to the real challenge.
A related, but different question is that of ["99 Bottles of Beer"](https://codegolf.stackexchange.com/questions/64198/99-bottles-of-beer). If you care about complexity, you would notice that the theoretical complexity of bottles of beers is different from that of the [two farthing kid.](https://en.wikipedia.org/wiki/A_Kid_for_Two_Farthings_%28film%29)
[Answer]
# Python 2, ~~633 603 589~~ 584 bytes (384 chars)
Note: the file must begin with a 3-byte “UTF-8 BOM” (EF BB BF), which Stack Exchange does not seem to preserve.
```
v="נָשַׁךְ הִכָּה שָׂרַף כָבָה שָׁתָה".split()+["שָׁחַט"]*4
c=', '.join(["חַד גַּדְיָא"]*2)
b=" דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. "+c
print c+b
e='אָכְלָה לְגַדְיָא,'+b
for i,t in enumerate("שׁוּנְרָא|כַלְבָּא|חוּטְרָא|נוּרָא|מַיָּא|תוֹרָא|שׁוֹחֵט|מַלְאַךְ הַמָּוֶת|הַקָּדוֹשׁ בָּרוּךְ הוּא".split('|')):
print'וַאֲתָא '+(t if i!=7else'הַשּׁ'+t[4:])+' וְ'+e
e=v[i]+' לְ'+t+', דְּ'+e
```
Output:
```
חַד גַּדְיָא, חַד גַּדְיָא דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא שׁוּנְרָא וְאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא כַלְבָּא וְנָשַׁךְ לְשׁוּנְרָא, דְּאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא חוּטְרָא וְהִכָּה לְכַלְבָּא, דְּנָשַׁךְ לְשׁוּנְרָא, דְּאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא נוּרָא וְשָׂרַף לְחוּטְרָא, דְּהִכָּה לְכַלְבָּא, דְּנָשַׁךְ לְשׁוּנְרָא, דְּאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא מַיָּא וְכָבָה לְנוּרָא, דְּשָׂרַף לְחוּטְרָא, דְּהִכָּה לְכַלְבָּא, דְּנָשַׁךְ לְשׁוּנְרָא, דְּאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא תוֹרָא וְשָׁתָה לְמַיָּא, דְּכָבָה לְנוּרָא, דְּשָׂרַף לְחוּטְרָא, דְּהִכָּה לְכַלְבָּא, דְּנָשַׁךְ לְשׁוּנְרָא, דְּאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא הַשּׁוֹחֵט וְשָׁחַט לְתוֹרָא, דְּשָׁתָה לְמַיָּא, דְּכָבָה לְנוּרָא, דְּשָׂרַף לְחוּטְרָא, דְּהִכָּה לְכַלְבָּא, דְּנָשַׁךְ לְשׁוּנְרָא, דְּאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא מַלְאַךְ הַמָּוֶת וְשָׁחַט לְשׁוֹחֵט, דְּשָׁחַט לְתוֹרָא, דְּשָׁתָה לְמַיָּא, דְּכָבָה לְנוּרָא, דְּשָׂרַף לְחוּטְרָא, דְּהִכָּה לְכַלְבָּא, דְּנָשַׁךְ לְשׁוּנְרָא, דְּאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
וַאֲתָא הַקָּדוֹשׁ בָּרוּךְ הוּא וְשָׁחַט לְמַלְאַךְ הַמָּוֶת, דְּשָׁחַט לְשׁוֹחֵט, דְּשָׁחַט לְתוֹרָא, דְּשָׁתָה לְמַיָּא, דְּכָבָה לְנוּרָא, דְּשָׂרַף לְחוּטְרָא, דְּהִכָּה לְכַלְבָּא, דְּנָשַׁךְ לְשׁוּנְרָא, דְּאָכְלָה לְגַדְיָא, דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. חַד גַּדְיָא, חַד גַּדְיָא
```
How it works:
I first create a list of all the nouns and verbs. It's in a string with a separator because that's a lot cheaper, byte-wise. I also have the ending piece in a variable.
The first part of the first line (חד גדיא, חד גדיא) is already contained at the end, so i just slice it and prepend.
Each of the next lines follows the same format, so i keep a running variable `e` (for end) of the part that gets copied, and just print the part that changes.
The line of השוחט needs to be special-cased.
Code shortened to use BOM by suggestion of Anders Kaseorg and msh210, and optimized with some tricks from msh210's answer.
[Answer]
# Perl 5, 632 bytes
```
$g="חַד גַּדְיָא";$g.=", $g";$\="דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. $g";@a=split b,"שׁוּנְרָאbכַלְבָּאbחוּטְרָאbנוּרָאbמַיָּאbתוֹרָאbשׁוֹחֵטbמַלְאַךְ הַמָּוֶתbהַקָּדוֹשׁ בָּרוּךְ הוּאbגַדְיָא";@c{@a}=@a;$c{'שׁוֹחֵט'}="הַשּׁוֹחֵט";@d=qw/אָכְלָה נָשַׁךְ הִכָּה שָׂרַף כָבָה שָׁתָה/;push@d,('שָׁחַט')x3;print$g.$";for$i(0..8){$/="\nוַאֲתָא $c{$a[$i]}, וְ$d[$i] לְ$a[$i-1], ";$/.="דְּ$d[$i-$_] לְ$a[$i-$_-1], "for 1..$i;print$/}
```
[Answer]
# Python 2, 331 bytes
(This source contains non-printable bytes, so it is presented as a hexdump that can be decoded with `xxd -r`.)
```
00000000: efbb bf70 7269 6e74 2278 01ed 54b5 6145 ...print"x..T.aE
00000010: 310c ec33 85fb c08e 3f0b 7c66 6668 c2ec 1..3....?.|ffh..
00000020: 39a4 7572 3917 8630 932b 4ba6 23bf a74d 9.ur9..0.+K.#..M
00000030: b9d0 aad1 8ad8 bb42 0eb5 2d97 5ada 318f .......B..-.Z.1.
00000040: 2c18 9456 4eb5 8189 3216 8646 4b18 ca62 ,..VN...2..FK..b
00000050: dd6a 99ab 1bac aee4 4cdb 461b 5a17 8bed .j......L.F.Z...
00000060: 68f6 cc6b d1b6 70f8 025c 30c7 ba71 d7af h..k..p..\0..q..
00000070: b5c0 fb46 0470 47eb a84b a8bb 187b 186b ...F.pG..K...{.k
00000080: 467b 282b 09c2 b7f2 eea2 0529 c278 d623 F{(+.......).x.#
00000090: d450 84b5 8e1c 9275 2cd0 33ff 0512 9bbc .P.....u,.3.....
000000a0: ad95 0453 0364 57ac e79c 3a41 d67f cd8b ...S.dW...:A....
000000b0: 116f 0b7d 58eb 3eba 15b6 4d1d dfd4 2e32 .o.}X.>...M....2
000000c0: feb7 865c 72d0 b6a3 6fa3 8bba ecd9 468e ...\r...o.....F.
000000d0: 92eb 339e 664f 3798 b84a 1e61 01dd c6f3 ..3.fO7..J.a....
000000e0: 8d6c 27db f71b 9f8d afa1 5d8b 25ff 2b1c .l'.......].%.+.
000000f0: 3ad3 5618 5c30 af69 9177 9211 e5e5 94be :.V.\0.i.w......
00000100: ee97 d323 4f27 87b1 5c72 085e 9773 dd3c ...#O'..\r.^.s.<
00000110: 16d9 3ac9 956a 7f58 b2f9 fb5b 12ab ca10 ..:..j.X...[....
00000120: a0c4 61c2 3302 b9b8 5996 1e89 f9f9 e741 ..a.3...Y......A
00000130: 91bf e181 e407 720b 7329 ec60 222e 6465 ......r.s).`".de
00000140: 636f 6465 2827 7a69 7027 29 code('zip')
```
[Answer]
# GolfScript, 577 bytes
```
"חַד גַּדְיָא, חַד גַּדְיָא. ":d"דִּזְבַן אַבָּא בִּתְרֵי זוּזֵי. "d+"\n"+:c"גַדְיָא,שׁוּנְרָא,כַלְבָּא,חוּטְרָא,נוּרָא,מַיָּא,תוֹרָא,שׁוֹחֵט,מַלְאַךְ הַמָּוֶת,הַקָּדוֹשׁ בָּרוּךְ הוּא"","/:y;"אָכְלָה,נָשַׁךְ,הִכָּה,שָׂרַף,כָבָה,שָׁתָה,שָׁחַט,שָׁחַט,שָׁחַט"","/:x;9,{"וַאֲתָא "\.6="הַ"""if\.y\1+=\", וְ"\.x\=\" לְ"\.y\=\,-1%{", דְּ"\.x\=\" לְ"\.y\=\;}%". "c}%
```
Store the nouns and actions in variables by splitting strings.
Using a list of lists of increasing sizes, each in descending order - `[[1],[2,1],[3,2,1]...]` - print the first and subsequent lines of each stanza using those index values.
] |
[Question]
[
**This question already has answers here**:
[How do I alias member functions in Python?](/questions/26831/how-do-i-alias-member-functions-in-python)
(7 answers)
Closed 8 years ago.
In Python it is often necessary to use `str.replace(a,b)`, however `.replace` is rather long and feels unnecessary. So is there a shorter alternative to `str.replace`.
Alternatively is there a similar trick to how you can use `r=range` for golfing for `str.replace`?
## Example code for golfing
```
m=input()
f="hello"
print m.replace('t','Ushd')
print m.replace('h','gyhj')
print f.replace('o','%£&')
```
[Answer]
```
r=str.replace;print r('abc','b','c')
```
The magic is real.
[Shortening str.replace()](https://codegolf.stackexchange.com/questions/60238/shortening-str-replace?noredirect=1#comment144890_60238)
[Answer]
### Regex Replace
You can use [`re.sub`](https://docs.python.org/2/library/re.html#re.sub), but it will take several uses to pay off if you're only doing it one character at a time.
```
import re
s="hello"
r=s.replace('h','m')
r=re.sub('h','m',s)
```
### Translate
You may also wish to look at [`string.translate`](https://docs.python.org/2/library/string.html#string.translate), which can be used for large numbers of single-character replacements. **Requires Python 3.** If using Python 2, `maketrans` is required first. For an example, [see here.](https://stackoverflow.com/a/21038977/2415524) In Python 3, it's used like this (taking a literal dictionary of ASCII values):
```
print("hello".translate({104:109}))
```
Output:
```
mello
```
] |
[Question]
[
### Challenge
Your goal is to write a program which will output the 8 measurements of a rectangle, with only some measurements in the input. Your program should throw an error if it cant be done.
Here is what each measurement means:
```
| left
| | centerX
| | | right
| | | |
| v v v
| _____________
| ^ | | <---top
| | | |
| | | |
|height | | | <---centerY
| | | |
| | | |
| v |_____________| <---bottom
|
| <----width---->
|________________________________________
```
### Input/Output Formats:
Input is in the form of some measurements of a box, one on each line. Output should be all 8 measurements of the corresponding box (or an error if the given measurements can not be used to find the other measurements).
For example, an input of
```
left 6
centerX 10
top 40
height 20
```
should print out
```
left 6
right 14
top 40
bottom 20
centerX 10
centerY 30
width 8
height 20
```
This is code-golf, so the shortest code wins.
[Answer]
### Python 2 with SWI Prolog ('typical' install), on Windows, 595 565 bytes.
```
import sys,subprocess as w;o='left right top bottom centerX centerY width height'
g={k:v for k,v in [l.strip().split() for l in sys.stdin.readlines()]};s='L,R,T,B,C,D,W,H';
open('t','w').write(
":-use_module(library(clpfd)).\nr(%s):-L#=R-2*(R-C),L#=R-W,L#=C-W//2,B#=T-2*(T-D),B#=T-H,B#=D-H//2,%s."%
(s,','.join('writeln(%s)'%x for x in s.split(','))));r='\n'.join([a+' '+b for (
a,b) in zip(o.split(),w.check_output("swipl -q -f t -t r(%s)."%(','.join(g.get(
x,x[0].replace('centerY','d').upper()) for x in o.split()))).split('\r\n'))])
print '!' if '_' in r else r
```
e.g. with a text file for input, containing:
```
right 14
centerX 10
top 40
height 20
```
it does this:
```
D:\>type rectin.txt|c:\python27\python.exe d:\rect.py
left 6
right 14
top 40
bottom 20
centerX 10
centerY 30
width 8
height 20
```
And in the error condition if the contents of the stdin file are not enough to calculate the other values, it does this:
```
D:\>type rectin.txt|c:\python27\python.exe d:\rect.py
!
```
*NB. It relies on swipl.exe being in the PATH*
### Explanation
I started writing in Python, got bored of expressing all the possible combinations of relationship (each one can be derived from three different combinations). I thought "must be a job for Prolog". So I installed a Prolog, headed for a tutorial, and got something that just about works. It's this:
```
:-use_module(library(clpfd)).
r(L,R,T,B,C,D,W,H):-
L#=R-2*(R-C),
L#=R-W,
L#=C-W//2,
B#=T-2*(T-D),
B#=T-H,
B#=D-H//2,
writeln(L),
writeln(R),
writeln(T),
writeln(B),
writeln(C),
writeln(D),
writeln(W),
writeln(H).
```
It uses the [clpfd library](http://www.swi-prolog.org/man/clpfd.html) (part of the 'typical install' requirement), which provides 'declarative integer arithmetic'. This gives the big advantage that I only need to define Left in terms of (Right and CenterX), (Right and Width), (CenterX and Width). From that, it can derive Right, Center and Width. (Same with the vertical set Top/Bottom/CenterY/Height).
This also means I don't have to check which specific values are provided; I give all the available values and placeholders for the rest, and it either calculates the answers, or outputs some unknown variable placeholders.
Being extremely novice at Prolog, handling STDIN was too much for me right now, so I wrapped it with Python. I don't have an ungolfed version of the Python, but it's not doing anything too amazing; it reads STDIN into a dictionary of {measurement:value} pairs, then puts them in the preset order the Prolog code is expecting, merged with the uppercase first letter of the unknowns.
(There's an annoyance where all the measurements are unique by first letter, except centerX and centerY, so it replaces centerY with D).
Then it writes the Prolog script out to a file, shells out to Prolog to run it and read the result, parses the number output and pairs them up with the measurements in order.
Then checks if any of the outputs were uncomputable and throws an error (`!`), otherwise prints the result.
[Answer]
# MFC, 212
```
void P(int l,int t,int r,int b){CRect R(l,t,r,b);POINT c=R.CenterPoint();TRACE("Left:%d Top:%d Right:%d Bottom:%d CenterX:%d CenterY:%d Width:%d H:%d",R.left,R.top,R.right,R.bottom,c.x,c.y,R.Width(),R.Height());}
```
# MFC, 213
```
void P(int l,int t,int r,int b){CRect R(l,t,r,b);CPoint c=R.CenterPoint();TRACE("Left:%d Top:%d Right:%d Bottom:%d CenterX:%d CenterY:%d Width:%d H:%d",R.left,R.top,R.right,R.bottom,c.x,c.y,R.Width(),R.Height());}
```
Outputs the result to Visual Studio's Debug Output Window.
Example:
```
P(12,7,23,30);
```
outputs
```
Left:12 Top:7 Right:23 Bottom:30 CenterX:17 CenterY:18 Width:11
```
Uncondensed format:
```
void P(int l, int t, int r, int b)
{
CRect R(l, t, r, b);
CPoint c= R.CenterPoint();
TRACE("Left %d Top:%d Right:%d Bottom:%d CenterX:%d CenterY:%d Width:%d H:%d", R.left, R.top, R.right, R.bottom, c.x, c.y, R.Width(), R.Height());
}
```
] |
[Question]
[
**This question already has answers here**:
[Death By Shock Probe: That's a lot of dice](/questions/49461/death-by-shock-probe-thats-a-lot-of-dice)
(45 answers)
Closed 8 years ago.
You're sitting in the school cafeteria, microwaving your food like you always do around lunch. Suddenly the programming devil rises from the ashes of your burnt food and proposes a challenge:
>
> Sup guys, I have a challenge.
>
>
>
How did this happen? What did you ever do wrong? Was it that one bad macro in C?
The programming devil demands a game of dice:
>
> I demand a game of dice.
>
>
>
Strictly speaking, it is not a game of dice. The programming devil just wants you to calculate the mean value of throwing a die `n` times. The programming devil's twist is that the die can, and always will, have a number of faces larger than `n`.
## Challenge:
Write a program which calculates and outputs the mean value of `n` throws with a die with a number of faces greater than `n`.
## Input:
Two positive integers. The first argument determines the number of throws, the second argument the number of faces of the die. There is no empty input - always two integers.
## Output:
The mean value of throwing the dice `n` times rounded to the closest integer.
## Requirements:
* No output if the number of faces of the die is less than or equal to the number of throws.
* The values returned from throwing the die has to be random (*as close as we can get to random, that is*)
The programming devil thinks this is great and will restore the burnt food of the programmer which writes the shortest code in bytes to solve his challenge:
>
> This is a great challenge. I will restore your food if you propose the shortest program in bytes to me.
>
>
>
[Answer]
# TI-BASIC, ~~16~~ ~~20~~ 19 bytes
Straightforward. The +8/-1 consensus on meta is that mixing inputs is allowed—so `Ans`, from command-line input, is the number of faces, and `N` is the number of throws.
```
Input N
If N<Ans
int(mean(1.5+int(Ansrand(N
```
[Answer]
# [Ostrich 0.7.0](https://github.com/KeyboardFire/ostrich-lang/releases/tag/v0.7.0-alpha), ~~18~~ 23 chars
Two solutions, identical in length:
```
:x;.,{;xR*C}%_+*\/o2/+F
\:x{.R*C\}*;]_+*x/o2/+F
```
Edit: +5 characters to each because I forgot to round to the nearest integer.
They both actually simulate rolling the dice (and thus have non-constant output), which seems to be the intent of the challenge.
Explanation of #1:
```
:x; store the number of faces in x, pop from stack
., create range from 0 to [number of rolls] (while keeping #rolls on stack)
{...}% map over that range...
; discard the number
xR* generate a float between 0 and [number of faces]
C take ceil, which will make this an int between 1 and [#faces]
_+* reduce by {+} (_ is the syntax for a single-instruction block) a.k.a. sum
\/ swap top two stack elements (bringing the number of rolls to the top),
then divide, resulting in the average
```
Explanation of #2:
```
\ bring the number of rolls to the top
:x store number of rolls in x, but don't pop from the stack
{...}* that many times...
. duplicate the number of faces
R*C get the random number as described in #1
\ stick that under the number of faces again, so [#faces] is still on top
; discard the extra [#faces]
]_+* wrap stack in an array, sum
x/ divide by [#rolls]
```
[Answer]
# APL, 13 bytes
```
{0⍕⍺÷⍨+/?⍵⍴⍺}
```
This creates an unnamed dyadic function where the left argument `⍺` is the number of throws and the right argument `⍵` is the number of die faces. Here we sum (`+/`) `⍺` random numbers between 1 and `⍵` (`?⍵⍴⍺`) and divide that by `⍺` (`⍺÷⍨`). The result is rounded to the nearest integer (`0⍕`).
You can [try it online](http://tryapl.org/?a=f%u2190%7B0%u2355%u237A%F7%u2368+/%3F%u2375%u2374%u237A%7D%20%u22C4%205%20f%2021&run).
Note that this still produces output even when the number of throws is greater than the number of faces. But per the challenge rules, that does not constitute valid input (*"The die can, and always will, have a number of faces larger than `n`."*).
[Answer]
# Pyth - 17 bytes
I'm sure it can be shorter, but the checking is stopping me from putting it in a lambda.
```
I>QKvz.RcsmhOQKKZ
```
[Try it here online.](http://pyth.herokuapp.com/?code=I%3EQKvz.RcsmhOQKKZ&input=5%0A10&debug=0)
## Or if the second interpretation of the rules is correct, 12 bytes.
Same thing but in a lambda.
```
M.RcsmhOHGGZ
```
[Try it here online](http://pyth.herokuapp.com/?code=M.RcsmhOHGGZ%0A%0AgvzQ&input=5%0A10&debug=0).
] |
[Question]
[
What is the shortest amount of code that can find the minimum of an inputted polynomial? I realize that you can import packages like Numpy and others, but using only user defined functions, what is the shortest way to do this? For example, if 6x6 + 4x3-12 is entered (ignore parsing issues), what would be the shortest amount of code to find the minimum value?
[Answer]
## Python - 202 Bytes
```
D=lambda p:[i*p[i]for i in range(1,len(p))]
A=lambda p,x:p>[]and p[0]+x*A(p[1:],x)
def N(p):f=D(p);s=D(f);x=1.;y=-x;exec'x-=A(f,x)/A(s,x);y-=A(f,y)/A(s,y);'*99;return A(p,x),A(p,y)
print min(N(input()))
```
*11 bytes saved due to [@xnor](https://codegolf.stackexchange.com/q/50777?noredirect=1#comment120139_50780).*
Input is taken from stdin, and is expected to be in the following format: [*x0*, *x1*, *x2*, ...]. For example, the sample in the problem description would be entered as `[-12, 0, 0, 4, 0, 0, 6]`.
---
**Functions**
*D* - Calculates the derivative of a polynomial *p*.
*A* - Applies a polynomial *p* to the value *x*.
*N* - Uses Newton's Method to calculate local minima/maxima of a polynomial *p*.
*Note:* For higher order polynomials, there may be several local minima. In these cases, this function is not guaranteed to find the global minimum.
---
**Sample Usage**
```
$ echo [-12, 0, 0, 4, 0, 0, 6] | python poly-min.py
-12.6666666667
```
] |
[Question]
[
## The challenge:
Given an integer *N*, *1 < N < 2³¹*, write code that uses the C preprocessor
to determine whether *N* is prime, and produces a "Hello world" program if N is prime,
or an error otherwise. Make the code as short as possible.
It's not very hard, so don't worry that there are so many rules; most
of them are boilerplate.
The following sample code (in `example.c`) works for *N < 100*:
```
#include <stdio.h>
int main() {
#if (N%2!=0 && N%3!=0 && N%5!=0 && N%7!=0) || (2==N || 3==N || 5==N || 7==N)
printf("Hello world!");
#else
Walkmen;
#endif
}
```
23 is prime but 99 is not, so:
```
c:\golf\preprime>gcc -std=c99 -DN=23 example.c
c:\golf\preprime>a
Hello world!
c:\golf\preprime>gcc -std=c99 -DN=99 example.c
example.c: In function 'main':
example.c:6:1: error: 'Walkmen' undeclared (first use in this function)
Walkmen;
^
example.c:6:1: note: each undeclared identifier is reported only once for each function it appears in
c:\golf\preprime>
```
## Rules
* *1 < N < 2147483648*
* *N* will be defined in a macro named `N`. `N` will be written using only the characters `0123456789` and will not begin with `0`.
* The code will be compiled with the command `gcc -std=c99 -DN=<number> <filename>.c [-o <outfile>]`
* If *N* is prime, a valid C99 program must be successfully compiled. When executed, the program's output to `stdout` must be precisely `Hello world!` followed by zero or more newlines.
* If *N* is composite, `gcc` must emit a compiler error. A linker error is not acceptable.
* You may not utilize any GCC extensions.
* You may not assume anything about the name of any file.
* Note: It is not allowed to use implicit types or implicit function declarations.
* Neither `gcc` nor any "Hello world" program may take more than 20 seconds to execute on a typical computer.
* Shortest code length in UTF-8 bytes wins.
For reference, my ungolfed implementation is 571 bytes. Happy golfing!
[Answer]
## 441 characters
OK, here is another approach — this time breaking things down into a giant binary tree of tests. I was hoping this could be done recursively, but the C preprocessor doesn't support recursive functions...so I did this as a fallback.
**Algorithm:** This tests `N` for divisibility by 2 and by all odd numbers up to the square root of 2³². (Note: That's a bit of overkill, because it need only test potential divisors up to the square root of 2³¹, but it's easier to stick to powers of 2.)
```
#define A(x) (N%(x)||N==x)
#define B(x) A(x)&A(x+2)&A(x+4)&A(x+6)
#define C(x) B(x)&B(x+8)&B(x+16)&B(x+24)
#define D(x) C(x)&C(x+32)&C(x+64)&C(x+96)
#define E(x) D(x)&D(x+128)&D(x+256)&D(x+384)
#define F(x) E(x)&E(x+512)&E(x+1024)&E(x+1536)
#define G(x) F(x)&F(x+2048)&F(x+4096)&F(x+6144)
#define H(x) G(x)&G(x+8192)&G(x+16384)&G(x+24576)
#include <stdio.h>
int main(){
#if A(2)&H(3)&H(32771)
printf("Hello world!");
#else
Walkmen;
#endif
}
```
**Notes:**
1. The value `32771` is really just `3+32768`.
2. Yes, the parentheses around `x` in `N%(x)` are indeed needed (but not in `N==x`).
3. Compiles as per instructions and obeys rules of output.
4. Elapsed time for each test of `N` (e.g., each invocation of the compiler) is about 1/6 second on my machine.
[Answer]
# boost/preprocessor, 355
```
#ifndef I
#include "boost/preprocessor.hpp"
#include "boost/preprocessor/slot/counter.hpp"
#include "stdio.h"
#define I BOOST_PP_COUNTER
#define F(z,x,d){int a[((x|d<<8)<2||(x|d<<8)==N||N%(x|d<<8))-1];}
int main(){
#include __FILE__
printf("Hello world!");}
#elif I<182
BOOST_PP_REPEAT(256,F,I)
#include BOOST_PP_UPDATE_COUNTER()
#include __FILE__
#endif
```
[boost/preprocessor](http://www.boost.org/doc/libs/1_56_0/libs/preprocessor/doc/index.html) is part of the boost extension to the standard library for preprocessor programming.
We need both the BOOST\_PP\_REPEAT and the BOOST\_PP\_COUNTER + self-include approaches because of the limitations of the system.
gcc only supports a nested include depth of 200, so the counter approach alone is insufficient.
BOOST\_PP\_REPEAT is limited to repeating 256 times, so it doesn't work alone either.
With both approaches together we get up to 51200 repetitions; we need only 46340 (sqrt 2^31) to cover all possible primes.
To actually cause compilation failure we need to generate some code whoses validity depends on primality (since we can't chain together an #if if we're using #includes). The easiest way is to declare an array who's length depends on N%i, since negative array lengths produce a gcc compiler error.
As a bonus the number of error messages is equal to the number of factors :).
### Examples
```
$ gcc -std=c99 -DN=24 primes.c
In file included from primes.c:8:
primes.c: In function ‘main’:
primes.c:11: error: size of array ‘a’ is negative
primes.c:11: error: size of array ‘a’ is negative
primes.c:11: error: size of array ‘a’ is negative
primes.c:11: error: size of array ‘a’ is negative
primes.c:11: error: size of array ‘a’ is negative
primes.c:11: error: size of array ‘a’ is negative
$ gcc -std=c99 -DN=23 primes.c && ./a.out
Hello world!
```
] |
[Question]
[
We all know the standard order of operations for math functions
([PEMDAS](http://www.mathsisfun.com/operation-order-pemdas.html)),
but what if we instead evaluated expressions left-to-right?
## The Challenge
Given a string through standard input or through command line args, find the difference between the traditional evaluation (PEMDAS) and the in-order (left-to-right) evaluation of that expression.
## Details
* You will be given a string in a format such as:
```
"1 + 2 * 3 ^ 2 - 11 / 2 + 16"
```
* To simplify things, there will be:
+ a space between each number and operator
+ no leading or trailing spaces
+ no decimal numbers or negative numbers (non-negative integers only)
+ no operators beyond +(plus), -(minus), \*(multiply), /(divide), ^(exponentiation)
+ no parens to worry about
+ you may remove the spaces if it's easier for you to handle, but no other modification of the input format will be allowed.
* You must provide the **absolute value** of the difference between the two evaluations of the string
* Your division can either be **floating-point or integer division** - both will be accepted
* Your program **can not use any sort of expression evaluation library**.
*To clarify - any sort of **built-in** eval function in which your language evaluates a string that is valid code for the same language **IS** acceptable*
* Explanations of your code are preferred
* Shortest code by byte count wins
* Winner will be chosen Saturday (July 19, 2014)
## Examples:
**A: 1 + 2 \* 3 ^ 2 - 11 / 2 + 16 (using floating-point division)**
* In traditional order of operations:
```
1 + 2 * 3 ^ 2 - 11 / 2 + 16 --> 1 + 2 * 9 - 11 / 2 + 16 -->
1 + 18 - 5.5 + 16 --> 29.5
```
* In-order traversal yields:
```
1 + 2 * 3 ^ 2 - 11 / 2 + 16 --> 3 * 3 ^ 2 - 11 / 2 + 16 -->
9 ^ 2 - 11 / 2 + 16 --> 81 - 11 / 2 + 16 -->
70 / 2 + 16 --> 35 + 16 -->
51
```
* Resulting difference: 51 - 29.5 = **21.5**
**B: 7 - 1 \* 3 ^ 2 + 41 / 3 + 2 \* 9 \* 2 (using integer division)**
* In traditional order of operations:
```
7 - 1 * 3 ^ 2 + 41 / 3 + 2 * 9 * 2 --> 7 - 1 * 9 + 41 / 3 + 2 * 9 * 2 -->
7 - 9 + 13 + 18 * 2 --> 7 - 9 + 13 + 36 -->
47
```
* In-order traversal yields:
```
7 - 1 * 3 ^ 2 + 41 / 3 + 2 * 9 * 2 --> 6 * 3 ^ 2 + 41 / 3 + 2 * 9 * 2 -->
18 ^ 2 + 41 / 3 + 2 * 9 * 2 --> 324 + 41 / 3 + 2 * 9 * 2 -->
365 / 3 + 2 * 9 * 2 --> 121 + 2 * 9 * 2 -->
123 * 9 * 2 --> 1107 * 2 -->
2214
```
* Resulting difference: 2214 - 47 = **2167**
[Answer]
### GolfScript, 84 characters
```
' '/.{?}:^;(~\2/{~~\~}/\{\?}:^;-1%'^'{[`{2$?0<!{@~\~@~`}*}+/]}:C~-1%'*/'C'+-'C~~-abs
```
This version does integer division and therefore yields a different result for the first test case. You may try the code [here](http://golfscript.apphb.com/?c=OyIxICsgMiAqIDMgXiAyIC0gMTEgLyAyICsgMTYiCgonICcvLns%2FfTpeOyh%2BXDIve35%2BXH59L1x7XD99Ol47LTElJ14ne1tgezIkPzA8IXtAflx%2BQH5gfSp9Ky9dfTpDfi0xJScqLydDJystJ0N%2Bfi1hYnMK&run=true).
```
> 1 + 2 * 3 ^ 2 - 11 / 2 + 16
21
> 7 - 1 * 3 ^ 2 + 41 / 3 + 2 * 9 * 2
2167
```
*Code with comments:*
```
' '/. # split the input at spaces and save a copy for each evaluation
# LTR evaluation
{?}:^; # define ^ to be the power operator
(~\ # convert the left most string (first operand) into a number
2/{ # loop over the rest in pairs of two
~ # split pair
~ # evaluate second item of tuple (i.e. numeric operand)
\~ # apply the operator to two items on stack
}/ # end loop
# standard evaluation
\{\?}:^; # redefine ^ to be the rtl power operator
-1% # -1% .... -1% reverse the input in order to handle right associativity
'^'
{ # {...}:C~ define code-block C and apply it to the string '^'
[`{ # stringify the argument in order to add it to the internal
# code-block. afterwards loop over the input array and collect
# the results in an array
2$?0<! # if the second top item on the stack is one of the provided operators
{
@~ # take the first operand and convert to number
\~ # take the second operand and convert to number
@~ # apply the operator
` # stringify result
}* # end if
}+/]
}:C~
-1%
'*/'C # afterwards apply the same code-block for operators * and /
'+-'C # and then for operators + and -
~~ # flatten the resulting array and convert the result to a number
-abs # take absolute difference between the two evaluation methods
```
[Answer]
## Haskell, 281 256 characters
```
(x:o:y:z)%p|p o=(show(m o(read x)$read y::Float):z)%p|1<3=x:o:(y:z)%p;z%_=z
m"+"=(+);m"-"=(-);m"*"=(*);m"/"=(/);m"^"=(**);m _= \a->abs.(a-)
l=(%(\_->1<3))
t e=foldl(%)e$map(\w->(`elem`w).head)["^","*/","+-"]
d e=l$l e++"~":t e
main=interact$concat.d.words
```
Brief explaintaion:
* `%` reduces an expression, so long as the operator meets some predicate `p`
* `show(m o(read x)$read y::Float)` applies an operator to the two string arguments, producing a string result
* `m` maps a string to an operator; note the string `"~"` is mapped to absolute difference
* `l` computes left-to-right order by applying `%` once, with a predicate that is always true
* `t` computes traditional order by repeatedly applying `%` with tests that match operators first of higher precedence, then lower
* `d` computes the two values, then forms a new expression with operator `~` and computes that
Runs:
```
& echo "1 + 2 * 3 ^ 2 - 11 / 2 + 16" | runhaskell 34599-EvalOrder.hs
21.5
& echo "7 - 1 * 3 ^ 2 + 41 / 3 + 2 * 9 * 2" | runhaskell 34599-EvalOrder.hs
2178.3333
```
*(Second result differs from example above because this code always computes in floating point.)*
[Answer]
# Perl 204 (203 + 1 for the `-p` flag)
LOL using `eval` got boring (`s/\^/**/g;$_=eval"("x(()=/\d+/g).s/(\d+)/\1)/rg."-($_)"`) as I saw Calvin's Hobbies's comment on the eric\_lagergren's [answer](https://codegolf.stackexchange.com/a/34611/21202) so here's an non-eval method:
```
$d='([-\d.]+)';$s=$t=$_;map{$o=$_;$s=~s|$d (.) $d|($1*$3,$1+$3,0,$1-$3,$1**$3,$1/$3)[ord($2)%6]|e,$t=~s|$d ([\\$o]) $d|($1*$3,$1+$3,'',$1-$3,$1**$3,$1/$3)[ord($2)%6]|eg for$t=~/./g}'^/*-+'=~/./g;$_=$s-$t
```
**Ungolfed:**
```
# shortcut
$d = '([-\d.]+)';
# initial values for the traditional and sequential evaluation
$s = $t = $_;
# split the list of operators and loop throught them
map {
# store current operator in $o
$o=$_;
# repeatedly evaluate the input string until the calculations are done
for($t=~/./g) {
# Here is an array with calculated all operators and I pick the correct element
# ord($2)%6 is never 2 so I put 0 in that position of the array
$s=~s|$d (.) $d|($1*$3,$1+$3,0,$1-$3,$1**$3,$1/$3)[ord($2)%6]|e;
$t=~s|$d ([\\$o]) $d|($1*$3,$1+$3,'',$1-$3,$1**$3,$1/$3)[ord($2)%6]|eg
}
} ('^/*-+'=~/./g);
# subtract the traditional evaluation form the in-order one
$_ = $s - $t
```
This solution uses floating point calculations.
**Output:**
```
$ PS1='\n\$ '
$ ./order.pl <<<"1 + 2 * 3 ^ 2 - 11 / 2 + 16"
21.5
$ ./order.pl <<<"7 - 1 * 3 ^ 2 + 41 / 3 + 2 * 9 * 2"
2178.33333333333
```
[Answer]
## Python 208
```
d=x=input();z=2;u='('*(((len(x)-len(x.replace(' ','')))/2)+1);d=x=d.replace(r'^','**');x=x.split();p=u+''.join(")".join(x[i:i+z]) for i in range(0,len(x),z))+")";m=eval(p)-eval(d);m=m*-1 if 0>m else m;print m;
```
---
Calvin'sHobbies comment::
```
import re;e=input().replace('^','**');print abs(eval(e)-eval(e.count(' ')/2*'('+re.sub('(\d) ',r'\1)',e)))
```
---
**Explanation:**
```
# variable d = x, and x = user input
d = x = input()
# variable z = 2
z = 2
# I take the length of the string 'x' (aka the equation we're solving) with
# *all* whitespaces removed (it's the 'len(x.replace(' ', '')...' part) and
# subtract that from 'len(x)' which is the vanilla length of our equation
# I divide the total by two and add one for reasons I'll explain in a minute
# the '(' * part means to make a string with as many '(' as I get from multiplying
# so '(' * 5 = '(((((', '(' * 3 = '((('
u = '(' * (((len(x) - len(x.replace(' ', ''))) / 2) + 1)
# Here I replace the caret with **, because in Python ^ == **
# I also split the string by whitespaces, but only for x;
d = x = d.replace(r'^','**'); x = x.split();
# I set the variable p = to the result of joining the list (aka array) that
# I just made with the .split() in the above section first with a ')' on every
# second character (e.g. [1,2,3,4,5,6] would be 1,2),3,4),... etc. I do it like
# this because in our math equation we'll (hopefully) follow the pattern of
# num op num op num op... etc. I insert parenthases because I'm using PEMDAS
# to my advantage by grouping each set of numbers in the order I want them
# to be completed. The initial ''.join simply rejoins all elements into a
# complete string (basically removes the commas that are left over from
# converting a list -> string). I add a '(' to the end because every 2nd
# character would skip the final one
p = u + ''.join(")".join(x[i:i + z]) for i in range(0, len(x), z)) + ")"
# I eval() both p and d. eval() will run arbitrary code, so you can pass it a
# string and it will act as if the string is code, so while print '1+1' would
# usually result in TypeError (or Value? I forget), print eval('1+1') would
# print '2', I have to do them separately because eval() thinks I wanna
# subtract two string for whatever reason
m = eval(p) - eval(d)
# Here I make use of Python's ternary operators by saying this:
# if 0 > m:
# m = m * -1
# else:
# m
# which means that if m is negative, multiply it by -1 to make it
# a positive number so we can get the absolute value. If it's not negative
# then we can just have m and not do anything with it
m = m * -1 if 0 > m else m
# Print m :)
print m
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 9 years ago.
[Improve this question](/posts/25199/edit)
This is a pretty cool CodeGolf challenge in the sense that you're only going to have a limited amount of time to do it. You need to build a program that "mines" StackOverflow unicoins. In order to do this, you need to perform just two HTTP requests. I'm not going to say how, to add to the fun.
The first person to do this gets a -10 on their score. Good luck! Also, if your doing this in JavaScript or similar, you don't need to account for the target browser's XSS, etc. prevention.
[Answer]
# Javascript, 104 (114 chars - 10 bonus)
[All due credit here](https://askubuntu.com/a/441860). Simply posting this to get the "first answer" -10 bonus ;-).
```
p='$.post("/unicoin/'
setInterval(p+'rock",function(o){'+p+'mine?rock="+o.rock,StackExchange.options.user)})',2e4)
```
[setInterval](https://developer.mozilla.org/en/docs/Web/API/window.setInterval) accepts both functions and strings of code. After susbtituting the variable *p*, the following gets executed every 20 seconds:
```
$.post("/unicoin/rock", function(o) {
$.post("/unicoin/mine?rock=" + o.rock, StackExchange.options.user)
}
```
---
Edits are welcome. I don't know [javascript](/questions/tagged/javascript "show questions tagged 'javascript'") well enough to really competitively golf this.
] |
[Question]
[
Your task is to create a program that computes every combination of the operations written in a .TXT file.
**Example TXT File:**
```
1
+
2
/
3
```
**Example Output:**
```
1+2/3=1
1+3/2=2
2+1/3=1
2+3/1=5
3+2/1=5
3+1/2=2
1/2+3= //See bonuses. If your program does not feature float, leave blank result.
1/3+2= //See above.
2/1+3=5
2/3+1= //See above.
3/2+1= //See above.
3/1+2=5
```
**Specs**:
* Every line of the .TXT file must contain a number **or** an operation;
* The minimum length for the .TXT file is 5 lines;
* The operations must be computed from left to right. E.g. `4+4/2` results in `4`;
* Your program should feature `+`, `-`, `*` and `/` operations;
* Your program should work with any valid input of any valid length.
**Scoring:**
Code length is your starting score, but not the only parameter. Here's a short list of bonuses you can achieve to lower your score. The user with the lowest score wins.
* Implement `^`: **-20**;
* Implement `log` (in base *e*): **-30**;
* Implement `logn` (where *n* is any positive base): **-50** (only **-20** if you achieved the `log` bonus);
* Implement `e` (and the number in the line below is the exponent of 10. So `1e4`=`10000`): **-20**;
* Can handle negative values: **-10**;
* Can handle float values: **-20**;
* There are no digits (`0123456789`) in the code: **-10**;
* There is no call to `eval` or equivalent: **-20**;
* All of the above: **-100**.
For a total of **-250** bonus points.
Good luck!
[Answer]
# Mathematica (-4 = 246 - 250)
*Update:* operation `e` instead of the number representation with `e`.
*Update2:* reading from the file.
```
i = "1.txt";
w@"log"=r=Real;
e_~p~c_:=(g[x_r,w@c=c]~g~y_r:=#;p)&@e
y~Log~x~p[x+y,"+"][x-y,"-"][x/y,"/"][x*y,"*"][x*10^y,"e"][x^y,"^"]~"logn";
x_r~g~r:=Log@x
w@y_:=N@ToExpression@y
g[,x_]:=x
f@x_r:=s~Print~x
f@Fold[g,s=#<>"=";,w/@#]&/@Permutations@ReadList[i,String];
```
File:
```
1
+
2
/
3
```
Output:
```
1+2/3=1.
1+3/2=2.
1/2+3=3.5
1/3+2=2.33333
2+1/3=1.
2+3/1=5.
2/1+3=5.
2/3+1=1.66667
3+1/2=2.
3+2/1=5.
3/1+2=5.
3/2+1=2.5
```
File:
```
-1
^
2
e
3
logn
4
log
```
Output:
```
-1e2^4logn3log=2.81943
-1e2^4loglogn3=2.65196
-1e3^2logn4log=2.29916
-1e3^2loglogn4=1.89411
-1e3^4logn2log=3.68545
-1e3^4loglogn2=4.78822
-1e4^2logn3log=2.81943
-1e4^2loglogn3=2.65196
2^-1e3logn4log=1.50027
2^-1e3loglogn4=1.31783
2^-1e4logn3log=2.04804
2^-1e4loglogn3=1.94981
2^3logn4e-1log=-1.89712
2^3logn4loge-1=0.0405465
2^3loge-1logn4=-1.13287
2^3loglogn4e-1=0.0528098
2^4e-1logn3log=-0.849063
2^4e-1loglogn3=-0.687244
2^4logn3e-1log=-1.37685
2^4logn3loge-1=0.0925734
2^4loge-1logn3=-1.16766
2^4loglogn3e-1=0.0928245
2e-1logn3^4log=1.52735
2e-1log^4logn3=1.73268
2e3logn4^-1log=-1.70163
2e3logn4log^-1=0.587671
2e3log^-1logn4=-1.46309
2e3loglogn4^-1=0.683487
2e4logn3^-1log=-2.19884
2e4logn3log^-1=0.454785
2e4log^-1logn3=-2.08708
2e4loglogn3^-1=0.479139
2logn3^-1e4log=9.6709
2logn3^-1loge4=4605.61
2logn3^4e-1log=-4.14483
2logn3^4loge-1=-0.184224
2logn3e-1^4log=-11.0526
2logn3e-1log^4=58.2928
2logn3e4^-1log=-8.74978
2logn3e4log^-1=0.114289
2logn3log^-1e4=-21712.7
2logn3log^4e-1=0.00449933
2logn3loge-1^4=4.49933*10^-6
2logn3loge4^-1=-0.000217127
2logn4^-1e3log=7.6009
2logn4^-1loge3=693.147
2logn4^3e-1log=-4.38203
2logn4^3loge-1=-0.207944
2logn4e-1^3log=-8.9872
2logn4e-1log^3=-26.8849
2logn4e3^-1log=-6.21461
2logn4e3log^-1=0.160911
2logn4log^-1e3=-1442.7
2logn4log^3e-1=-0.0333025
2logn4loge-1^3=-0.000333025
2logn4loge3^-1=-0.0014427
2log^-1e3logn4=5.24728
2log^-1e4logn3=8.71723
2log^-1logn3e4=3336.14
2log^-1logn4e3=264.383
2log^3e-1logn4=-2.45411
2log^3logn4e-1=-0.079315
2log^4e-1logn3=-3.43036
2log^4logn3e-1=-0.133446
2loge-1^3logn4=-5.77604
2loge-1^4logn3=-9.71807
2loge-1logn3^4=34.8402
2loge-1logn4^3=-7.13719
2loge3^-1logn4=-4.71851
2loge3logn4^-1=0.211931
2loge4^-1logn3=-8.05
2loge4logn3^-1=0.124224
2loglogn3^-1e4=-29974.7
2loglogn3^4e-1=0.00123874
2loglogn3e-1^4=1.23874*10^-6
2loglogn3e4^-1=-0.000299747
2loglogn4^-1e3=-3782.39
2loglogn4^3e-1=-0.001848
2loglogn4e-1^3=-0.00001848
2loglogn4e3^-1=-0.00378239
3^-1e2logn4log=0.928001
3^-1e2loglogn4=0.905028
3^-1e4logn2log=2.45982
3^-1e4loglogn2=3.02001
3^2logn4e-1log=-1.84202
3^2logn4loge-1=0.0460561
3^2loge-1logn4=-1.09312
3^2loglogn4e-1=0.0567841
3^4e-1logn2log=1.10457
3^4e-1loglogn2=1.06479
3^4logn2e-1log=-0.45573
3^4logn2loge-1=0.184686
3^4loge-1logn2=-1.18625
3^4loglogn2e-1=0.213568
3e-1logn2^4log=2.20856
3e-1logn4^2log=-0.282015
3e-1log^2logn4=0.267803
3e-1log^4logn2=1.07121
3e2logn4^-1log=-1.4145
3e2logn4log^-1=0.706966
3e2log^-1logn4=-1.25596
3e2loglogn4^-1=0.796204
3e4logn2^-1log=-2.69953
3e4logn2log^-1=0.370435
3e4log^-1logn2=-3.36583
3e4loglogn2^-1=0.297104
3logn2^-1e4log=8.74978
3logn2^-1loge4=-4605.61
3logn2^4e-1log=-0.460342
3logn2^4loge-1=0.184224
3logn2e-1^4log=-7.3681
3logn2e-1log^4=11.5128
3logn2e4^-1log=-9.6709
3logn2e4log^-1=0.103403
3logn2log^-1e4=21712.7
3logn2log^4e-1=0.00449933
3logn2loge-1^4=4.49933*10^-6
3logn2loge4^-1=0.000217127
3logn4^-1e2log=4.83776
3logn4^-1loge2=23.2586
3logn4^2e-1log=-2.76776
3logn4^2loge-1=-0.0465173
3logn4e-1^2log=-5.07034
3logn4e-1log^2=6.42709
3logn4e2^-1log=-4.37258
3logn4e2log^-1=0.228698
3logn4log^-1e2=-429.948
3logn4log^2e-1=0.00540964
3logn4loge-1^2=0.000540964
3logn4loge2^-1=-0.0429948
3log^-1e2logn4=3.25409
3log^-1e4logn2=13.152
3log^-1logn2e4=-1356.82
3log^-1logn4e2=-6.78412
3log^2e-1logn4=-1.52528
3log^2logn4e-1=0.0135682
3log^4e-1logn2=-2.7792
3log^4logn2e-1=0.0542729
3loge-1^2logn4=-3.18625
3loge-1^4logn2=-12.745
3loge-1logn2^4=103.066
3loge-1logn4^2=2.53804
3loge2^-1logn4=-3.38977
3loge2logn4^-1=0.295005
3loge4^-1logn2=-13.4234
3loge4logn2^-1=0.0744968
3loglogn2^-1e4=73701.6
3loglogn2^4e-1=0.0000338917
3loglogn2e-1^4=3.38917*10^-8
3loglogn2e4^-1=0.000737016
3loglogn4^-1e2=1474.03
3loglogn4^2e-1=0.000460242
3loglogn4e-1^2=0.0000460242
3loglogn4e2^-1=0.147403
4^-1e2logn3log=1.07498
4^-1e2loglogn3=1.0641
4^-1e3logn2log=2.07516
4^-1e3loglogn2=2.46505
4^2e-1logn3log=-0.849063
4^2e-1loglogn3=-0.687244
4^2logn3e-1log=-1.37685
4^2logn3loge-1=0.0925734
4^2loge-1logn3=-1.16766
4^2loglogn3e-1=0.0928245
4^3e-1logn2log=0.985097
4^3e-1loglogn2=0.892428
4^3logn2e-1log=-0.510826
4^3logn2loge-1=0.179176
4^3loge-1logn2=-1.26573
4^3loglogn2e-1=0.20562
4e-1logn3^2log=-0.362939
4e-1log^2logn3=-0.159149
4e2logn3^-1log=-1.69629
4e2logn3log^-1=0.589523
4e2log^-1logn3=-1.62963
4e2loglogn3^-1=0.613635
4e3logn2^-1log=-2.48205
4e3logn2log^-1=0.402893
4e3log^-1logn2=-3.05208
4e3loglogn2^-1=0.327646
4logn2^-1e3log=6.21461
4logn2^-1loge3=-693.147
4logn2^3e-1log=-0.223144
4logn2^3loge-1=0.207944
4logn2e-1^3log=-4.82831
4logn2e-1log^3=-4.16891
4logn2e3^-1log=-7.6009
4logn2e3log^-1=0.131563
4logn2log^-1e3=1442.7
4logn2log^3e-1=0.0333025
4logn2loge-1^3=0.000333025
4logn2loge3^-1=0.0014427
4logn3^-1e2log=4.37258
4logn3^-1loge2=-23.2586
4logn3^2e-1log=-1.83741
4logn3^2loge-1=0.0465173
4logn3e-1^2log=-4.14
4logn3e-1log^2=4.28489
4logn3e2^-1log=-4.83776
4logn3e2log^-1=0.206707
4logn3log^-1e2=429.948
4logn3log^2e-1=0.00540964
4logn3loge-1^2=0.000540964
4logn3loge2^-1=0.0429948
4log^-1e2logn3=3.89449
4log^-1e3logn2=9.49455
4log^-1logn2e3=-471.234
4log^-1logn3e2=-29.7315
4log^2e-1logn3=-1.50127
4log^2logn3e-1=0.0594631
4log^3e-1logn2=-1.90823
4log^3logn2e-1=0.14137
4loge-1^2logn3=-3.59718
4loge-1^3logn2=-8.55208
4loge-1logn2^3=-23.1661
4loge-1logn3^2=3.23492
4loge2^-1logn3=-4.48912
4loge2logn3^-1=0.222761
4loge3^-1logn2=-10.437
4loge3logn2^-1=0.0958128
4loglogn2^-1e3=2122.09
4loglogn2^3e-1=0.0104643
4loglogn2e-1^3=0.000104643
4loglogn2e3^-1=0.00212209
4loglogn3^-1e2=336.343
4loglogn3^2e-1=0.00883964
4loglogn3e-1^2=0.000883964
4loglogn3e2^-1=0.0336343
```
Description:
* The function `w[y]` converts string `y` to the number if `y` is not an operation.
* The pattern `g[g[x,c],y]` is converted to `x+y`, `x-y`, etc depending on the operation `c`. Otherwise it stay a symbolic expression.
* `f[x]` prints `x` only if it is a number.
[Answer]
## GolfScript 21 (51 characters -10 for handling negatives -20 for handling ^)
```
"#{File.read('a.txt')}"'^'/'?'*"\n"/(20@2/{(}%+''++~
```
Explanation:
Suppose `a.txt` contains "2+3/1\*4" (separated by new lines).
```
"#{File.read('a.txt')}" # Read in 'a.txt' as a string
'^'/'?'* # Replace all '^' with '?' to handle exponent. This works by splitting the string on '^' and then folding on '?'.
"\n"/ # Split on newlines, so that we have an array of characters
(20@ # Pull out the first element of the array, push a 20 (ASCII value for space) and rearrange stack
```
At this point, the stack will look like `2 20 '+3/1*4'`.
```
2/ # Group by 2
```
So the stack looks like `2 20 [['+','3'],['/','1'],['*','4']]`.
```
{(}% # Map each element of the array to the tail of the tuple followed by its head.
```
So the stack looks like `2 20 [['3'], '+', ['1'], '/', ['4'], '*']`
```
+''++ # Concatenate, stringify, and concatenate. Note that adding '' to an array flattens it.
```
So we are left with `'2 3 + 1 / 4 *'`.
```
~ # Finally, evaluate the string, since we were left with valid GolfScript.
```
This works with negatives, but accomplishes none of the other bonuses.
[Answer]
### GolfScript, score 54 (104 characters, bonus for neg., ^, e)
```
n%[[]]\{n/`{`{^2$<\@^>++}+\:^,),/}+%}/.&{2/1\{0='+-*/^e'\?0<&}/},{?}:^;{10\?*}:e;{."="+[n]@+2/{~~\~}/n}/
```
The input is given on STDIN.
**Example**
For input `1 2 3 + e`:
```
3+2e1=50
3e2+1=301
2+3e1=50
2e3+1=2001
2+1e3=3000
2e1+3=23
3+1e2=400
3e1+2=32
1+3e2=400
1e3+2=1002
1+2e3=3000
1e2+3=103
```
**Commented code with basic building blocks**
```
# split input
n%
# generate all permutations of the input (I'm working on a shorter implementation)
[[]]\{n/`{`{^2$<\@^>++}+\:^,),/}+%}/
# remove any duplicates (occur if same number/operator is given more than once)
.&
# filter for those permutations where each second element is an operator
{2/1\{0='+-*/^e'\?0<&}/},
# define operators ^ and e
{?}:^;
{10\?*}:e;
# Loop over all permutations
{
.
# make string representation
"="+
# reorder expression from ltr-infix into stack order and execute operations
[n]@+2/{~~\~}/
# add newline
n
}/
```
[Answer]
**Javascript, 338 characters**
Handles `e`, negative values, and floats, bonus -50, **score 288**.
```
function g(a,p,r){a.length<1?r.push(p):a.map(function(c){g(a.filter(function(x){return x!=c}),p.concat(c),r)})}
x=[];y=[];x.push(readline());while(n=readline()){x.push(readline());y.push(n)}k=[];l=[];g(x,[],k);g(y,[],l);
l.map(function(y){k.map(function(x){r=x[0];s=r;y.map(function(b,i){n=b+x[i+1];s=s+n;r=eval(r+n);});print(s+'='+r)})})
```
Example [here](http://ideone.com/8AdvFu).
[Answer]
# Ruby 177 characters
* Implemented `^`: **-20**
* Handles negative values: **-10**
* No eval: **-20**
### Total: 127
```
$<.map{|x|x=~/\d+/&&x.to_i||x.chomp}.permutation{|x|$_=x*'';a,*b=x;puts$_+"=#{b.each_slice(2).reduce(a){|m,(o,y)|[m+y,m-y,m*y,m/y,m**y]["+-*/^".index o]}}"if~/^-?\d+(\W-?\d+)*$/}
```
Run with the input file as command line argument or give input on stdin.
Chopped up for readability:
```
$<.map{|x|x=~/\d+/?x.to_i: x.chomp}
.permutation{|x|
$_=x*''
a,*b=x
puts $_+"=#{
b.each_slice(2).reduce(a){|m,(o,y)|[m+y,m-y,m*y,m/y,m**y]["+-*/^".index o]}
}" if ~/^-?\d+(\W-?\d+)*$/}
```
[Answer]
# APL, score 36
156 chars - 20 (^) - 50 (logn) - 20 (e) - 10 (negative) - 20 (float) = 36
```
{⍺←{⍵[{1≥⍴⍵:⊃,↓⍵⋄⊃⍪/⍵,∘∇¨⍵∘~¨⍵}⍳⍴⍵]}⋄e←{⍺×10*⍵}⋄⍪,(↓⍺v/⍨~d)∘.{(,⍵,⍪⍺,'='),{⍎⍕⍵,⍺}/⌽(⍎↑⍵),↓'+-×÷*⍟e'['+-*/^le'⍳∊1⌷¨⍺],⍪1↓⍵}↓⍺v/⍨d←2|⍳⍴v←('\S+'⎕S'&')⍵⎕ntie 0}
```
Without any instructions to the contrary, I made `logn` an infix operator, as you would type it on a calculator, so that log2(16) is `2` `logn` `16`.
**Source**
```
⍝ main function; ⍵ is the file to read
{
p←{1≥⍴⍵:⊃,↓⍵⋄⊃⍪/⍵,∘∇¨⍵∘~¨⍵} ⍝ permutation matrix (taken from "dfns")
q←{⍵[p⍳⍴⍵]} ⍝ all permutations of the given vector
e←{⍺×10*⍵} ⍝ 'e' function as required
v←('\S+'⎕S'&')⍵⎕ntie 0 ⍝ read input file and split on spaces
d←2|⍳⍴v ⍝ bitmap of odd indices of input vector
n←v/⍨d ⍝ odd-index values: the numbers
o←v/⍨~d ⍝ even-index values: the operators
⍝ f will be called for each permutation of operators and numbers;
⍝ ⍺ is the (shuffled) list of operators; ⍵ of numbers
f←{
⍝ translate the operators into APL
⍝ a trick is used to recognize 'logn' by its first letter only
t←'+-×÷*⍟e'['+-*/^le'⍳∊1⌷¨⍺]
⍝ prepare the list of operations to perform, in reverse order,
⍝ followed by a single scalar with the value of the first number
m←⌽(⍎↑⍵),↓t,⍪1↓⍵
⍝ fold over the previous vector, executing every operation in order
r←{⍎⍕⍵,⍺}/m
⍝ return the result, preceded by a representation of the operation
(,⍵,⍪⍺,'='),r
}
⍝ generate all permutations of operators and of numbers; call f on
⍝ every combination (outer product); ravel and tabulate the result
⍪,(↓q o)∘.f↓q n
}
```
**Examples**
Input file:
```
-2.5
/
3
^
4
```
Output:
```
{paste golfed code here} 'a.txt'
-2.5 / 3 ^ 4 = 0.4822530863
-2.5 / 4 ^ 3 = ¯0.244140625
3 / -2.5 ^ 4 = 2.0736
3 / 4 ^ -2.5 = 2.052800957
4 / -2.5 ^ 3 = ¯4.096
4 / 3 ^ -2.5 = 0.4871392899
-2.5 ^ 3 / 4 = ¯3.90625
-2.5 ^ 4 / 3 = 13.02083333
3 ^ -2.5 / 4 = 0.01603750748
3 ^ 4 / -2.5 = ¯32.4
4 ^ -2.5 / 3 = 0.01041666667
4 ^ 3 / -2.5 = ¯25.6
```
Input file:
```
2.5
e
3
logn
4
```
Output:
```
{paste golfed code here} 'b.txt'
2.5 e 3 logn 4 = 0.1771838201
2.5 e 4 logn 3 = 0.1084874404
3 e 2.5 logn 4 = 0.2022289117
3 e 4 logn 2.5 = 0.08888300898
4 e 2.5 logn 3 = 0.1538078748
4 e 3 logn 2.5 = 0.1104756749
2.5 logn 3 e 4 = 11989.77847
2.5 logn 4 e 3 = 1512.941595
3 logn 2.5 e 4 = 8340.437671
3 logn 4 e 2.5 = 399.0350129
4 logn 2.5 e 3 = 660.9640474
4 logn 3 e 2.5 = 250.6045754
```
] |
Subsets and Splits