text
stringlengths 180
608k
|
---|
[Question]
[
\$BB\$ is the [busy beaver function](https://en.wikipedia.org/wiki/Busy_beaver), an uncomputable function.
Write a program which when given an integer \$n\$ as input, will output \$BB(n)\$, with at least \$\frac 2 3\$ probability. You can do whatever (return something wrong, infinite loop, explode, etc.) in other cases.
To help you compute it, you're given a function that randomly returns 0 or 1 (false or true, etc.). You can decide the exact probability that it returns 0, but all returns of calls should be independent.
Shortest code wins.
# Notes
* The exact definition of BB doesn't matter much so not clearly defined above.
* If you encode some code into the randomness, they add nothing to length of your solution(actually it's hard to define code and data here). You should, when constructing the coin, show the code, though.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 68 66 bytes
```
lambda x:eval(sum(r()for _ in"X"*4**900).to_bytes(225,"big")[:99])
```
[Try it online!](https://tio.run/##RY7BasJQEEX3/YqQVRJKeTNz582MXyKISEJtK6iRmIp@fXztol1cuJtzOJfH/DWexS/Tshz70/DeV/fV/tYfm@v3qZma9mOcql11ONfrukPXRUrt2zzuhse8vzbM@loPh8@63awitu3ySxIJGCxmpplN7GfIkcVCc2JL0IwIB5MjNEDkpg4KcidoYleFkBATA8hKUiyqxcqZPAWRkWqBhLn8gKuBX/7LNP2FMZWwJw "Python 3.8 (pre-release) – Try It Online")
-2 bytes thanks to @l4m2
`r` is the random function. Its probability of outputting one encodes a 99-byte code snippet, which is evaluated. This code snippet can then read much more data from the randomness, and basically you can encode any program you want into the randomness stream.
[Here is a practical demonstration](https://tio.run/##VU5dC4MwDHzvrwh9SsomzH0gMv0lA1HWuoJtpXZDf72rUx/2EJLLXS7XT@Hl7Dnr/ay8M@Br@4xNm975AIKZoYUCGj5ypuOgbUgWXdVMQQ4Y2QNvdMuJ@ch2tWmedf4zidVKTAWm15sQnbSLmOAIJyK4F5AKvQCmise83sGYy0/dIQ5vgx5JOQ9V/Air1UUI3G1ERkRl@YeT4LZU@3aLRnPvY25UmMb5Cw "Python 3.8 (pre-release) – Try It Online")
Example (less than) 99-byte snippet:
```
eval((sum(r()for _ in"X"*2**88001)>>80000).to_bytes(1000,"big")[99:])
```
As you can see, there is no limit to what kind of code we can run
To actually solve the busy beaver problem, the rest of the randomness is dedicated to just storing the answers to the question (that is, the busy beaver numbers).
The probability of failure depends on the first calculation. I *think* it succeeds with more than 2/3 probability, but i could be wrong. I'll check and add a proof later. Nevertheless, if it fails the criteria, this only results in some adjusting to the magic constants.
For the encoding of the busy beaver numbers, we first use the following encoding (I'm using a list of primes as an example)
`[2,3,5,7,...]`
Is converted into
`110111011111011111110...`
Finally, in order to account for the table-maker's dilemma, we replace`1` with `10` and `0` with `01`, resulting in
`101001101010011010101010011010101010101001...`
Then we execute the following code:
```
def get_raw_bit(p):
# A lot of tries
tries = 2**(2**p)
hits = sum(r() for _ in range(2**tries))
hits >> (tries - p)
def get_bit(p):
code_len = 1000
get_bit(code_len + 2*p)
pos = 0
p = -1
while pos < x:
count = 0
while get_bit(p:=p + 1):
count+= 1
print(count)
```
] |
[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/213767/edit).
Closed 3 years ago.
[Improve this question](/posts/213767/edit)
You know those riddles where every letter is swapped for another letter?
E.g. you get a text like
```
JME JG EPP IFAPE EPJE CJPPPC BP,
UIJCG JC EPP EFE GPJB EJIP EJ EJIP,
F EPJIG MPJEPPPP AJUC BJL UP
GJP BL MICJIJMPPJUIP CJMI.
```
and are supposed to find out that it stands for
```
OUT OF THE NIGHT THAT COVERS ME,
BLACK AS THE PIT FROM POLE TO POLE,
I THANK WHATEVER GODS MAY BE
FOR MY UNCONQUERABLE SOUL.
```
This example was created by the following replacement matrix:
```
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ODSXHKARFYGNBIQTJVCEWZMULP
```
Try to unscramble any given text by doing a letter frequency analysis. Assume that the most common letters in the given input are (left to right):
`EARIOTNSLCUDPMHGBFYWKVXZJQ`
* Replace the most common letter in the input by E, the next most common by A, and so on
* Producing a correctly unscrambled text is actually outside the scope of this challenge. That is, we assume that you get a correct result if only the input is large enough. (Testcase 1)
* If there is insufficient data, your return value must be consistent with the data provided. (Testcase 2)
* You may expect uppercase text only. It can contain digits, punctuations etc., which are not scrambled and to be output as is.
This is a code golf, shortest answer in bytes wins. Standard loopholes apply.
## Testcase 1 - The shortest completely solvable one
```
CCCCCCCCCCCCCCCCCCCCCCCCCCPPPPPPPPPPPPPPPPPPPPPPPPPIIIIIIIIIIIIIIIIIIIIIIIIFFFFFFFFFFFFFFFFFFFFFFFEEEEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLLLLLLPPPPPPPPPPPPPPPPPPPPFFFFFFFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGEEEEEEEEEEEEEEEEEIIIIIIIIIIIIIIIITTTTTTTTTTTTTTTMMMMMMMMMMMMMMJJJJJJJJJJJJJAAAAAAAAAAAAAAAAAAAAAAAWWWWWWWWWWDDDDDDDDDBBBBBBBBBBBBBBBFFFFFFTTTTTJJJJWWWIIP
```
must output
```
EEEEEEEEEEEEEEEEEEEEEEEEEEAAAAAAAAAAAAAAAAAAAAAAAAARRRRRRRRRRRRRRRRRRRRRRRRIIIIIIIIIIIIIIIIIIIIIIIOOOOOOOOOOOOOOOOOOOOOOTTTTTTTTTTTTTTTTTTTTTNNNNNNNNNNNNNNNNNNNNSSSSSSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLCCCCCCCCCCCCCCCCCUUUUUUUUUUUUUUUUDDDDDDDDDDDDDDDPPPPPPPPPPPPPPMMMMMMMMMMMMMHHHHHHHHHHHHGGGGGGGGGGGBBBBBBBBBBFFFFFFFFFYYYYYYYYWWWWWWWKKKKKKVVVVVXXXXZZZJJQ
```
## Testcase 2
`HALLO WORLD` must output `??EEA<space>?A?E?`:
* The 3 Ls turn into E
* The 2 Os turn into A
* The remaining letters are each replaced by an undefined permutation of the letters "RIOTN", without any of these repeating.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 185 bytes
```
c=>(l={},[...c].map(i=>l[i]=(l[i]|0)+1),e=Object.entries(l).sort((a,b)=>b[1]-a[1]).map(i=>i[0]).filter(i=>parseInt(i,36)>9),[...c].map(i=>"EARIOTNSLCUDPMHGBFYWKVXZJQ"[e.indexOf(i)]||i))
```
[Try it online!](https://tio.run/##XY3BboJAFEV/xbB6L4WJponRxZBgbQsWHYta205YDHRInqFIhokxkX47xYUbNyc5d3HuQZ1UkxuqrXeadAXvcu5DyS9/rmSM5Sn7VTUQ90tJKYcr2yE@jNDVXGQHnVumK2tIN1Aia47GAig3Q@5ncpR6qgfeEiSHvRRUWm2uXivT6KiyQO7jGP0p3l06z0ESie1qEz/t5utl@Dp7@dq/fXx@L94dqRlVP/osCiBM25YQu9pQHyvACYM4FoO9SOK50@// "JavaScript (V8) – Try It Online")
Doesn't currently pass the second test case, but instead is based on OP's description of how the unscrambling works. The test case seems to be incorrect at the moment, as some groups of letters (like `F` or `P`) repeat letters.
**Explanation:**
```
c=>( // Define arrow function with argument c
l={}, // Create an empty object l
[...c].map(i=> // For each character i in c...
l[i]=(l[i]|0)+1), // Increment l[i] (the number of times i appears)
e=Object.entries(l) // Format l as an array ["x", <number of times "x" appears>] in variable e
.sort((a,b)=>b[1]-a[1]) // Sort e so most common characters are first
.map(i=>i[0]) // Get rid of number of times appeared
.filter(i=>parseInt(i,36)>9), // Filter out non-letters using base 36 conversion :)
[...c].map(i=> // For each character i in c...
"EARIOTNSLCUDPMHGBFYWKVXZJQ"[ // Get the nth item from the frequency chart...
e.indexOf(i)] // Where n is the index of i in e
||i)) // Unless it isn't a letter, where i stays i
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes
```
“@u@Rṭ$3=ỊẈṘ’œ?ØA;0
QfØAċ@ÞðṚiⱮị¢ðo
```
[Try it online!](https://tio.run/##ddK9TsMwEAfwnac4RYwRQmJEiDqu4/qwqVsIpewggSoxMbBVLCA6shSEGJgBtWPpRuBBkhcJTkppPpzf4ljy/W2fc3E6GFwnSTx8blw1utHsfX1rJ5rfR5930WwcDx9/HnbDMdneXOucmfF71Ahfwkk0ezqPpx/RfPT1Gk4uk/A2vnnrJ4lzUqtf57hGz@7IKrA5tDio6lZ0ynRJu2i/QOXJnL0V/CeWWn/4gp9hqaZBKSXEc1xwaC1dR9Tw7ZiVtLHtZknkFZX48tlK71ZoqsI8Yrf6ZZpLXtHibFl8mmNWCqHTFreIlG3otbuymU5RMUAOTGsQPtHMfCEDiuauFDztQiYQSDkgzdYxnwHX6AFDYWaYja6fVgoOytSnnQKCgUlACYFehHDU4ElQgqJApTUGppyiEhvOLw "Jelly – Try It Online")
Like Redwolf Programs' JS solution, this technically fails both given test cases, but seems to be consistent with the intent of the challenge.
] |
[Question]
[
*Related to, but not a duplicate of, [this challenge](https://codegolf.stackexchange.com/questions/74830/read-an-analog-clock).*
## Basics
This is a clock:
```
******
** | **
** | **
* | *
* | *
* | *
* | *
* | *
* | *
* |_______ *
* *
* *
* *
* *
* *
* *
* *
** **
** **
******
```
Let's note some of the basic properties:
1. It's a circle, 40\*20 (width\*height) characters, made up of asterisks.
2. There are two hands: a minute hand made of 9 pipe characters (`|`); and an hour hand made of 7 underscores (`_`). I.e., in this example the time is 3:00
If a clock weren't arranged in right angles, it might look something like this:
```
******
** **
** | **
* | *
* | *
* | *
* | *
* | *
* | *
* |_ *
* _ *
* _ *
* _ *
* *
* *
* *
* *
** **
** **
******
```
This represents 4:55.
What's happened here is:
1. We determine the destination (see the diagram below).
2. We determine the number of spaces to delimit by. This will either be 0, 1, or 2 (see the table below).
3. We draw the line by using the respective character (`|` for minute, `_` for hour).
4. We then cut off the line at the number of characters (9 for minute, 7 for hour), including spaces, from the center of the circle along the x-axis. If we reach the edge of the clock, we stop anyway:
```
******
| ** **
*| | **
* | | *
* | | *
* | | *
* | | *
* | | *
* | | 1234567| *
* | |_ | *
* |987654321 _ | *
* _ | *
* _| *
* *
* *
* *
* *
** **
** **
******
```
For the sake of completeness, here's a diagram of all possible angles. This applies to minute-hands too: they won't go more specific than 5-minute intervals.
```
**→0←*
↓* ** ↓
** →11 1←*
* *
*↓ ↓*
* →10 2← *
* *
* *
* ↓
↓ • 3
9 ↑
↑ *
* *
* *
* →8 4← *
*↑ ↑*
* *
** →7 5←*
↑* ** ↑
*→6←**
```
The number of spaces to reach each point is as follows:
```
+-------+----------------------------------------+
| Point | No. of spaces to delimit with to reach |
+-------+----------------------------------------+
| 1 | 1 |
+-------+----------------------------------------+
| 2 | 2 |
+-------+----------------------------------------+
| 3 | 0 |
+-------+----------------------------------------+
| 4 | 2 |
+-------+----------------------------------------+
| 5 | 1 |
+-------+----------------------------------------+
| 6 | 0 |
+-------+----------------------------------------+
| 7 | 1 |
+-------+----------------------------------------+
| 8 | 2 |
+-------+----------------------------------------+
| 9 | 0 |
+-------+----------------------------------------+
| 10 | 2 |
+-------+----------------------------------------+
| 11 | 1 |
+-------+----------------------------------------+
| 0 | 0 |
+-------+----------------------------------------+
```
Note that it is asymmetrical. However, if you wish, you can also take input with the clock flipped vertically, horizontally or both, e.g.
```
*→○←**
↓** **↓
**→○ ○←**
* *
*↓ ↓*
* →○ ○← *
* *
* *
* ↓
↓ • ○
○ ↑
↑ *
* *
* *
* →○ ○← *
*↑ ↑*
* *
**→○ ○←**
↑** **↑
**→○←*
```
(flipped horizontally)
Similarly, when two hands overlap (see below) both hands would usually be aligned to the top of the top-left of the four centre squares. When requesting a flipped input, the centre location will also be flipped accordingly. Note that you cannot mix the two: if you want a flipped input, all aspects, including the centre-point *and* the angle anchors, will be flipped. (On these example diagrams, the centre-point is represented with the centre dot `•`)
For this challenge:
* The minute hand will always be a multiple of five
* The hour hand will always be on the base of the hour (e.g. even if it is 5:59, the hour hand will be exactly on 5)
* Only valid times will be given, and the size of the clock will be constant
* If the hour hand and minute hand are on the same line, the hour hand (`_`) will be used for the first seven characters, followed by `|` for two more, e.g.:
```
******
** **
** **
* *
* *
* *
* *
* *
* *
* _ *
* _ *
* _ *
* _ *
* | *
* *
* *
* *
** **
** **
******
```
would represent 8:40.
## Challenge
Given a clock in this format, output the time displayed on the clock. The time should be in 12-hour format (i.e. not starting at 12), but the top number can be 0 or 12, as you wish.
## Rules
* You can return the time as an array of `[hours, minutes]`, a string delimited by some character, or any other reasonable format. You must return pure, base-10 numbers, though: hex representations (0-A instead of 0-11) or other replacements for numbers are disallowed.
* Results can be padded by whitespace or zeros if you wish (e.g. 01:12 instead of 1:12)
* The characters mentioned here must be the ones used by your program. Your submission cannot require substitution of these characters for something else, e.g. take a clock with '`#`' for the hour hand. Further, the input will always contain the spaces at the start of lines, but spaces after the clock (on the right of the diagram) are optional, e.g.:
```
******
** | **
** | **
* | *
* | *
* | *
* | *
* | *
* | *
* |_______ *
* *
* *
* *
* *
* *
* *
* *
** **
** **
******
(select this!)
```
* Input can be taken as an array of lines or a single newline-delimited string. [Standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~51~~ 50 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•4D-aÕΩ/Ȱøcû'a•žAвè'_kI•5₁¦M5₅϶ÊäÄVd‰•558вè'|k5*‚
```
Input as a single multi-line string without trailing spaces; output as a pair of `[hours, minutes]`.
-1 byte by switching to the legacy version, where the max/min works on character-lists, based on the ordinal codepoint values of the characters. (In the new version it will simply return the first character instead..)
[Try it online](https://tio.run/##MzBNTDJM/f//UcMiExfdxMNTz63UP9xxaMPhHcmHd6snAoWP7nO8sOnwCvX4bE8gz/RRU@OhZb5AqvVw/6Fth7sOLzncEpbyqGEDSNLUAqQ0KttU61HDrP//lZSUFFCAFhhwIQsgs7kQgjUK6DrBklDl6LJACWRpTHmQNJJV2PUjKcBmghaqADYz0JQQYQpQTTxBJUAQT1gJiiJcSpAUoXuZYJgQCHTypFHTAEZawJlIUJMUMKUBAA) or [verify all test cases](https://tio.run/##MzBNTDJM/W9waGGZkmdeQWmJlYKSTqWOkn9pCYRjX/n/UcMiExfdxMNTz63UP9xxaMPhHcmHd6snAoWP7nO8sOnwCvX47Eogz/RRU@OhZb5AqvVw/6Fth7sOLzncEpbyqGEDSNLUAqQ0KttU61HDrP86h7bZ/1dSUlJAAVpgwIUsAKZqIGwuFEG4BJKkFrJpNcgmE5bWQnVLDarLCCtAk0ZXQLaSeAjAo0SBsClkKcHwMhkK8CghSholuhXQohtTAYoEIkkZEJfOFDDSWQ12i7WwRx@6n2oIBFkNwTCtIRhxNUTEbY0CMemMmBQST0wiiicmncWPpjPCFlPiJ0rDlDbFTDwhJfGETIknZFE8IS/XDPl0Bqw5AQ).
Assumes these below are all the clock arms:
```
******
** | **
** | | | **
* | 0 1 *
* B 0 1 *
* | B 0 1 | *
* A B 0 1 2 *
* A B 0 1 2 *
* A B012 *
* yx333333|| *
* ||99999##z 5 4 *
* 8 7 6 5 4 *
* 8 7 6 5 4 *
* | 7 6 5 | *
* 7 6 5 *
* 7 6 5 *
* | 6 | *
** | **
** | **
******
```
Where:
* `0-B` represents the hour-arms for the hours `0` to `11`;
* `|` represents the tips of the minute-arms;
* `xyz` represents the -multiple- cents, where `x` is the center for `0,1,2,3,4,5,11`; `y` is the center for `7,8,10`; and `z` is the center for `6,9`;
* `#` are overlapping hour-numbers (for 7&9 and 8&9 respectively).
If they are incorrect (which is likely, since I have multiple centers, and the challenge description is a bit confusing tbh..), the code can easily be modified to correct the arms. The approach will remain the same, I'd just have to adjust the indices in the compressed lists in that case.
**Explanation:**
Checks at the following positions in the input-string:
```
******
** **
** l a b **
* *
* L A B *
* k c *
* K C *
* *
* *
* D d *
* j J *
* *
* I E *
* i e *
* *
* H G F *
* h f *
** g **
** **
******
```
It will first get a list of all characters in the uppercase positions of the graph above (in alphabetical/clock order), and will use the first 0-based index in this list where it finds a '\_' as the hour. It will do the same with the lowercase positions and '|', after which it will multiply this by 5 as the minutes.
```
•4D-aÕΩ/Ȱøcû'a• '# Push compressed integer 78119436285968343280298302466166
žAв # Converted to base-512 as list: [123,128,193,296,402,502,495,489,388,317,180,118]
è # Get the characters at those indices in the (implicit) input-string
'_k '# Get the first index of an '_'
•5₁¦M5₅϶ÊäÄVd‰• # Push compressed integer 103082336338078574425677583851482
558в # Converted to base-558 as list: [63,70,162,298,439,534,557,519,421,315,145,56]
I è # Get the characters at those indices in the input-string
Z # Get the maximum character in this list (without popping the list),
# which will always be the '|'
k # Get the index of this '|' in the list
5* # Multiply that by 5
‚ # And pair both integers together
# (after which it is output implicitly as result)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•4D-aÕΩ/Ȱøcû'a•` is `78119436285968343280298302466166`; `•4D-aÕΩ/Ȱøcû'a•žAв` is `[123,128,193,296,402,502,495,489,388,317,180,118]`; `•5₁¦M5₅϶ÊäÄVd‰•` is `103082336338078574425677583851482`; and `•5₁¦M5₅϶ÊäÄVd‰•558в` is `[63,70,162,298,439,534,557,519,421,315,145,56]`.
] |
[Question]
[
This challenge is a sequel to [Letter Boxed Validator](https://codegolf.stackexchange.com/questions/183213/letter-boxed-validator).
The New York Times has a daily online game called [Letter Boxed](https://www.nytimes.com/puzzles/letter-boxed) (the link is behind a paywall; the game is also described [here](https://www.polygon.com/2019/2/1/18205854/new-york-times-crossword-letter-boxed-puzzle-game)), presented on a square as follows:
[](https://i.stack.imgur.com/9g0e2m.png)
You are given 4 groups of 3 letters (each group corresponds to one side on the picture); no letter appears twice. The aim of the game is to find words made of those 12 letters (and those letters only) such that:
* Each word is at least 3 letters long;
* Consecutive letters cannot be from the same side;
* The last letter of a word becomes the first letter of the next word;
* All letters are used at least once (letters can be reused).
In this challenge, you are given the letters, and a dictionary. The goal is to output a valid solution, which minimizes the number of words used. If there is no solution, any consistent output is acceptable.
For the input `{{I,C,O}, {M,R,E}, {G,N,S}, {A,P,L}}`, a valid solution is PILGRIMAGE, ENCLOSE. Another valid solution is SOMNOLENCE, EPIGRAM. The following are not valid:
* PILGRIMAGE, ECONOMIES (can't have CO since they are on the same side)
* GRIMACES, SOPRANO (L has not been used)
* PILGRIMAGE, ENCLOSURE (U is not one of the 12 letters)
* ENCLOSE, PILGRIMAGE (last letter of 1st word is not first letter of 2nd word)
* CROPS, SAIL, LEAN, NOPE, ENIGMA (number of words is not minimal)
## Input
Input consists of a dictionary, and of 4 groups of 3 letters. It can be in any suitable format.
## Output
A list of words giving a solution to the challenge. There may be several acceptable solutions: you should output at least one, but may output several if you want.
## Test cases
The test cases use [this dictionary](https://raw.githubusercontent.com/robinryder/misc/master/words.csv). If using a large dictionary is too difficult on [TIO](https://tio.run/), you may use instead the dictionary `{PILGRIMAGE, ENCLOSE, SOMNOLENCE, EPIGRAM, ECONOMIES, GRIMACES, SOPRANO, ENCLOSURE, CROPS, SAIL, LEAN, NOPE, ENIGMA, OVERFLOWS, STACK, QUESTIONABLY, QUARTZ, ZIGZAG, GHERKIN, CODE, GOLF, NO, I, DO, NOT, IN}`, but your code should in principle work on a larger dictionary.
Note that the solution is not necessarily unique; these are possible solutions.
Input=`{{I,C,O}, {M,R,E}, {G,N,S}, {A,P,L}}`.
Solution: PILGRIMAGE, ENCLOSE
Input:`{{OSA}, {FVK}, {WEL}, {CTR}}`.
Solution: OVERFLOWS, STACK.
Input: `{{BCD}, {FGH}, {JKL}, {MNP}}`.
No solution.
Input: `{{AQT}, {LUI}, {BOE}, {NSY}}`.
Solution: QUESTIONABLY
Input: `{{QGN}, {ZUR}, {AHK}, {ITE}}`.
Solution: QUARTZ, ZIGZAG, GHERKIN.
## Scoring:
This [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score in bytes wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 38 bytes
```
iⱮⱮL>2ƊƇẠƇ’:3IẠƲƇŒPU=ḢɗƝẠ$ƇFQL=ʋƇ12ịḷḢ
```
[Try it online!](https://tio.run/##PY0xSwMxFMf3@xTlcKyD7WZpIU1zabxcXi65a@ntDpZuTm7V5cBuLiJYEJcuIiiCxYJLMaDf4u6LnEkEIcn/938v7//mp4vFRdOc1S/P9vBBx1ybsvp4MGW9vDvuMoevpvy6kXm/2j5@35q1LR2YMkp5/2dlyqNOtVtV23fbbPabeX352W4F5915vVy3e/XyvnU4aFnu7TdBtXvbb@qrp1nTMAyJIlRoJHkAGkWTeEo4zlQwxKOIjk9inggZoDTjORsCEXoWpFQUuULjmGWkCSXjVLEEURK2QyIwB@1IQyKAW@/LklGFEkcYBCSMaMt@DHvUIBUS8J@QKzeGFUjfRYxb4QQJKwLk3ypGE2QBJkRFHKb@Z4ZwbDXNic4YCDTkM2@RygoLBaMFom73mKiYuTgMIxdHgUc@3D7M3hF4lzkrwl8 "Jelly – Try It Online")
A dyadic link taking the flattened letters as left argument and the dictionary as right. Returns a list of strings of one of the shortest solutions, or a zero if there is no solution.
Full explanation to follow once it’s a bit better golfed.
] |
[Question]
[
**Background:**
This question is a remix of the one that I made previously on this forum. The only difference with this one is: the range is significantly larger, AND dynamic. Details below!
Also, I'm typing this question incredibly quickly, so if there are any grammatical errors, I do apologize and ask if anyone would edit the question to clear any vagueness. Nonetheless, the original question is posted here: [The Missing Number Revised](https://codegolf.stackexchange.com/questions/150000/the-missing-number-revised)
**Question:**
Given a minimum bound M, a maximum bound N, and a String of randomly concatenated integers [min, max), min (M) to max (N) exclusive, there is a number missing in the sequence. Your job is to write a program that will calculate this missing number.
Doing this problem by hand on smaller Strings, such as examples 1 and 2 below are obviously very easy. Conversely, computing a missing number on incredibly large datasets involving three-digit, four-digit, or more numbers would be incredibly difficult. The idea behind this problem is to construct a program that will do this process FOR you.
**Important Information:**
One thing that appeared as rather confusing when I posted this problem last night was: what exactly a missing number is defined as. A missing number is the number INSIDE of the range specified above; NOT necessarily the digit. In example 3, you will see that the missing number is 7, even though it appears in the sequence. There are 3 places the DIGIT 7 will appear in a series of [0, 30): “7”, “17”, and “27”. Your objective is to differentiate between these, and discover that 7 is the missing NUMBER (inside of example 3). In other words, the tricky part lies in finding out which sequences of digits are complete and which belong to other numbers.
Another very important factor in this: there are some input situations where there are *multiple solutions*! Your job will be to print out ALL numbers that are missing in the sequence. I cannot provide insight as to WHY they have multiple solutions; I only know they may exist.
**Input:**
The input is a single Integer T: the amount of test cases.
For each test case, there is an Integer M: the minimum number in the sequence, another Integer N: the maximum number in the sequence (thus M < N at ALL times), a String S, containing integers from M to N - 1 inclusive, or M to N exclusive (in other words, [M, N)). These integers, as stated above, are scrambled up to create a random sequence. There are NO delimiters (“42, 31, 23, 44”), or padding 0’s (003076244029002); the problems are exactly as described in the examples.
As stated above, M is ALWAYS lower than N, and the maximum range of numbers is < 100,000. |N - M|.
**Winning Criteria:**
Whoever has the fastest, and lowest memory usage will be the winner. In the miraculous event that a time ties, lower memory will be used for the time breaker. Please list Big O if you can!
**Examples:**
(Examples 1-6 are just for demonstration. Your program needn't to handle them.)
[Here is a pastebin link of the examples.](https://pastebin.com/wub1wtDk)
**TEST DATA**
Please keep in mind the way you're to read in the data: Digit D represents how MANY test cases there are, the next lines will follow with integers M and N, then String S. I just wanted to clear it up. I also apologize for the incredibly large pastebin. Good luck!
Data: [Test Data - Github repository](https://github.com/JoshuaCrotts/TheMissingNumberV2TestData)
[Answer]
# Clean - Complexity Unknown
*Currently works, explanation and further optimization in progress*
```
module main
import StdEnv, StdLib, System.IO
:: Position :== [Int]
:: Positions :== [Position]
:: Digit :== (Char, Int)
:: Digits :== [Digit]
:: Number :== ([Char], Positions)
:: Numbers :== [Number]
:: Complete :== (Numbers, Positions)
decouple =: snd o unzip
//lcouple :: (.a -> .b) (.a, .c) -> (.b, .c)
lcouple fn (arg, oth) :== (fn arg, oth)
getCases :: Int *World -> ([(String, [[Char]])], *World)
getCases n world
# (range, world)
= evalIO getLine world
# range
= fromString range
# spacePos
= elemIndex ' ' range
| isNothing spacePos
= abort "invalid input, expected space in range\n"
# (a, b)
= splitAt (fromJust spacePos) range
# (a, b)
= (toInt (toString a), toInt (toString (tl b)))
# numbers
= [(fromString o toString) number \\ number <- [a..(b-1)]]
# (string, world)
= evalIO getLine world
| n > 1
# (cases, world)
= getCases (n - 1) world
= ([(string, numbers) : cases], world)
= ([(string, numbers)], world)
singletonSieve :: Complete -> Complete
singletonSieve (list, sequence)
| sequence_ == sequence
= reverseSieve (list, sequence)
= (list_, sequence_)
where
singles :: Positions
singles
= [hd pos \\ (_, pos) <- list | length pos == 1]
list_ :: Numbers
list_
= map (app2 (id, filter notInOtherSingle)) list
where
notInOtherSingle :: Position -> Bool
notInOtherSingle pos
= not (isAnyMember pos (flatten (filter ((<>) pos) singles)))
sequence_ :: Positions
sequence_
= foldr splitSequence sequence singles
reverseSieve :: Complete -> Complete
reverseSieve (list, sequence)
| sequence_ == sequence
= (list, sequence)
= (list_, sequence_)
where
singles :: Positions
singles
= [hd pos \\ pos <- [[subSeq \\ subSeq <- sequence | isMember subSeq p] \\ (_, p) <- list] | length pos == 1]
//= [hd pos \\ pos <- | length pos == 1]
list_ :: Numbers
list_
= map (app2 (id, filter (\b_ = (notInOtherSingle b_) && (hasContiguousRun b_)))) list
where
notInOtherSingle :: Position -> Bool
notInOtherSingle pos
= not (isAnyMember pos (flatten (filter ((<>) pos) singles)))
hasContiguousRun :: Position -> Bool
hasContiguousRun pos
//= any (any (isPrefixOf pos) o tails) sequence_
= and [isMember p (flatten sequence_) \\ p <- pos]
sequence_ :: Positions
sequence_
= foldr splitSequence sequence singles
splitSequence :: Position Positions -> Positions
splitSequence split sequence
= flatten (map newSplit (map (span (not o ((flip isMember) split))) sequence))
where
newSplit :: (Position, Position) -> Positions
newSplit ([], b)
# b
= drop (length split) b
| b > []
= [b]
= []
newSplit (a, b)
# b
= drop (length split) b
| b > []
= [a, b]
= [a]
indexSubSeq :: [Char] Digits -> Positions
indexSubSeq _ []
= []
indexSubSeq a b
# remainder
= indexSubSeq a (tl b)
| isPrefixOf a (map fst b)
= [[i \\ (_, i) <- take (length a) b] : remainder]
//= [[i \\ _ <- a & (_, i) <- b] : remainder]
= remainder
missingNumber :: String [[Char]] -> [[Char]]
missingNumber string numbers
# string
= [(c, i) \\ c <-: string & i <- [0..]]
# locations
= [(number, indexSubSeq number string) \\ number <- numbers]
# digits
= [length (indexSubSeq [digit] [(c, i) \\ c <- (flatten numbers) & i <- [0..]]) \\ digit <-: "0123456789-"]
# missing
= flatten [repeatn (n - length i) c \\ n <- digits & (c, i) <- [(digit, indexSubSeq [digit] string) \\ digit <-: "0123456789-"]]
# (answers, _)
= until (\e = e == singletonSieve e || length [(a, b) \\ (a, b) <- fst e | length b == 0 && isMember a (candidates missing)] > 0) singletonSieve (locations, [indexList string])
# answers
= filter (\(_, i) = length i == 0) answers
= filter ((flip isMember)(candidates missing)) ((fst o unzip) answers)
where
candidates :: [Char] -> [[Char]]
candidates chars
= moreCandidates chars []
where
moreCandidates :: [Char] [[Char]] -> [[Char]]
moreCandidates [] nums
= removeDup (filter (\num = isMember num numbers) nums)
moreCandidates chars []
= flatten [moreCandidates (removeAt i chars) [[c]] \\ c <- chars & i <- [0..]]
moreCandidates chars nums
= flatten [flatten [moreCandidates (removeAt i chars) [ [c : num] \\ num <- nums ]] \\ c <- chars & i <- [0..]]
Start world
# (number, world)
= evalIO getLine world
# (cases, world)
= getCases (toInt number) world
= flatlines[flatten(intersperse [', '] (missingNumber string numbers)) \\ (string, numbers) <- cases]
```
[Try it online!](https://tio.run/##zZpdbyNHdoavh7@iYQM2GUyPq7v6o3qwY2Bj52ICZ21kLnIhEwNK4swQkUhFpPwR@LdHeZ5qfkiasTcJfBHszpLsrjp1Pt7znnNKe3G1XKzv7683l3dXy@J6sVpPVtc3m9td8WZ3@U/rn577@d3qnM9ft7vl9YvX308mL18WP2y2q91qsy5evnpVnL1e7@YPn27Hx4ef@d23q/erXX4@/ebD4vZ5wabZ8cV@R/6el//t7vp8eTuuP3PD/PlJ/Oy0Yr9x/JF3frO5vrla7pbj3v2qR5snl8uLzR2Lilcvi@36stgUd@v/XN1MJl99dbV/g6Dpi0VRfl28OJ/59Xnx4mLm7@mL8/x9clj6bl1MF7fvnxeb3YfZeCqPjk8mk/fL3TeL7XKrUKwu/uHfNrdXl1nW2fTN7na1ZunZaOV8hqHjgtlp47r42SeTZ58X09vF@v3y@fhgNnn27FWx/Glx9fr7gtXfrdbL09K8Mq94d7u5Hg86PPy82N4sLpZ4ZRRxtbx@vb5c/lJ8yX/2a34rVtu/YYLbHq1enIuQz1ZrDl5dFqv1zd3uebH85WZ5sVtejmt5Osr5cf1Z1hsPno/6bm@uVru/7nATav3z3XZ3lD47qfdg/XS30W187G1YzJ4XT59Nd1esn83cux6DnjefTR8YvykO62f7RcWPPx6@/aUszhYvXkzPy2o2n2cdtvvg/F1n/0aIvi4qVrDrwpg92MSuYySn66Isqtlhn9adHY/Z6w2IiixjfhLyyXUP3j@bbHkF7jfrN6vlTxnAx0wAaYfvT5dNr1ZbYrdd/sfdcn2xnGnK4cfbAiwffmRdb9lyu13@3tZX47O3p4dvZ5OfPyxv2T2em3PgmIqnp2OoPlwWN5utIZki40Y8EBRFFr8VV8v1@92HvAC1KgKUzypOVLB/kmVdL26A0M1NXUxXl8@Ld6urHSFeb3av19/v0OhNPng2y9Inz/ZKPnu64KG6uvEfN5urTy27yZnBubzhxO1f17/@yzKjSn2n764Wu90SntjrMZ3@5evZaODeAxm5J8c/8dLh@ZjMm6vL2zGJ3uxfHP19EDeZPArV74Hh78Tzj6DwJ0b/afD9MBnPtnfnWOij/TeeHi2VnfY@3r@9mR@hcwTO/JPIefbVV5868c8B2fTHc9xFpj8FyfnbWfHFF8X0w2L7zWa9W72/29xt//Vu7YvZ/zMoPvtIyU8f/9Gy/fE6eLH@Fff4P6vtD7fLd6tfvn83ngQPL1ZXHvkA2RYWivHZMaw3J21PiMrhMlgIMpLP/tS0gUYfLXho9Km7wfzTMU8k@utBpnDuweGiZb38@U1ekX9NqXvrDBQ8MsXY1c0R1LNRlLg45tgxnY5ibFMOqpx6nNljDU/Lp2fzfVX9vDgfXX55u0GRPe7HI/Or34pzKtrZfFx1dj4fs3T@UNri/yjMfXt5i/lksrLxeDPmMAaNjdChL3xkycOVb7O8rNLDxwsPpPdZ2sxeLm/zMY8XjK3C2N8ccbkYQ/KOWrNvO87OVgc@WWU@2S3@fXm0boFlcwr18aAjrYzb3rpjUXzxYP9H6189VHNyvdoKw0Pn@7LYNy2HzlBXHL4/WTw2Bqe@5/P9k30HdJE1QKkL1Hh5WP1Fsco0G168GNudq83FYo@YvG0U9/yR99YPD5w97p72x2dZlzl6o6C9x6YP5ZzlBfOnyp0y/tgLPVIzL8xbsyWfhaqOTdv1aSg/y@fu/TJm/F7U2e3yZrnYrcfma68NZ15k9RU@amuwLg7BOpvmh4@tP2j9wPzfU2ZsIBfr7c95/Hg7YuoOqryiQjB6FMtcUx@3Y5S1YxE6G/MrY3D8hlric3kqVOfKCFaVI2subEDXl6vLxY6Cu/fHbE7@hVnxUfd3CDkDSDb0O5ut0bx57qX3FowOPRS4PaZfHZ2Z1ZidFp/WPmG1T@k2c9V2dxjDjmKOdPdgz4kfHmbDwxUXPBrVvd7cLr958iKTxqHEPllwkv3JlPto/dlclO6rLZm8@Wn57d3NqbL@yFt8dIyMP4@wdufsY5knJR8h@Mmq6XgaM9Rq3DFDzYv5/JhGo5gnGf7ps04mHE/73xxbnF3AagiZ78lgzwTbYlTnj/R5NnmzWzBJnobbA@X8D6bbj8ash1PWOB2O0o7D1qsim3iFmO3BRkiJWG1vbIOLsy@fF1/OKQR/QK6zMSE/Gtk0Ms9s9/ftJBRVCJMUhlCFrq762DTt0MZq6KrUxVDBEt1QN6lv6r6th6YehiHWqe1TH7ohRYgktkNV1@zsh5Y3CSl9SkMf4xCb2HRtyxpWpr7vmjpV7dArPvZdG7o@Dm1TVXVbtSE1fV2lJtRdF9Ai1U3XRfToh9g3TRfTwP5Qt23fDD3nsK/t0qSs21Dwb1KHqqxiqlPDrogNfeV/6qouqyGWVd@WqIpmoY5djGUnC5ZVxQ6@B8QPvKmHtqwCz9NQdUPVlLErE9trbO2UkdoS9atUVZ2qI7hNHJDqkFSFVeXQVk2suq7s2qoLddWWfSibpkR7VjZ5QxfrpkEcWlcsZ2Eb@3IIZWxTW1U4vKyrqhx6bEKTuq6Gsh74QLMqomNddqGs8VzH/9Yl6tUJDSo2cCSy6jDw37buMQa5qa@bgXcc2QxV25dY1zUx4IEOGyKKIizwu1cMKtYsbyqiz5KKQ5oaA3B7O9SIr3Cbx/RDGflGmFLZsswfPf4KseJ0rETrwL7YIT6FSiXxpFFBoNo3eIhj8XCIvkxlSn3sURKXVSATL4cSUVFXDWjVdnxPmB96YlVrEh5J2NHwAM8BJYAkCJqqU39clKomoXrVNACJlToDsTgW33EYPhQOsQkEj9W1mCEGoQSGsTJ@FQHoG91FGPRrg94DSYEmXdXxENM4BzeAnBREOG9KtqA4auKvlvCV7tP1PXhBXT1NopA7nJmaEiuUjpcGF5J/WF76rxaJfG30cBX6BOANv/HkKL1QpqokXeveQCAYrTpdgkJAOZapEUSobQxDDdb7qgS4Bg6w4@DKnO7EWGcoyVswAAShCDTlvWL1YSUC0VCX9B1YJcx9508ghh0EvRTVKITNpD12cKxxjXU3lA0xBPqRsyvTUvIw4sTao0njMoo7I8u7HGD3YnwGTiCNSI@eIwAOfEV4W/O3ystxZgMVlVIBayEnfYEQggPkWEHgUFosIoJP3iMH3fvIs2gOmqL8q8poqg85yOSt8Riwbihb8YBWmNglCUrCqCBF5AjLoTKjWuWkEk7E7fjHhEIUqKsTQlBWZzZGxgVD6RkB53MqbuugQN@SjbBl2cE85B3oCeWAMXggk5nkpXNIOxgZVsIDbU@@DLUKdCPq5RRTOtuLNFiyVIK0B5B8QtJ0nbGSdkIgLGWfIA8SrOyVX0nPnpsdLiSTaYh0vIftIoOlKN1VnsnRdaaRRr4KPQagDNjjLGxgAYsQZAIE0jlWql5nLSHhUt4wPzLbeVxIxBiSic0E2gwFQAoTiBznsJfqAvsOkByeBL0AgBA0oo2ADUQokZVwaN9pD88JpGEilxrovtMByXd8EoYGK9vUk1t8AulmYC9xI5lAMQSPXxJ46dmXOJMMVqtcOqhlZA@yTNJUm2v8hlbUiYD0VAfKGWeTGtHIW6nACODAZKsWuvGd/YkIU0g5C0oRHr3yoTGrmzpHIYPjYcFW@Ti1Vzb69sq2EhAC8d0qo/f8Fn3xVdJmg8YeQkOBRl4v/SEHH6IHlMRa/DFIOOhCLTPxWxlCvfUjSOzZ04GORHDbRp34B3nBieiOHGzugkyP/sFaxjq@N517kF3lAo2fKn4Tz@gneg@uUT9iFfST/jDesgnv0bPVn@ynT8AebMOXNDM8I16u4VlyDYlg@SS1WIc@LXtcgw0QMM84U4bqtQUfErsO3RpoI3XK4PmgfAu8xIoeyITk0InPTl9jo6xfGVuTCAyKTexIgzHnXHCXwCKARrb@Rw9xgl8b5FDtLB@cb9zRTV9FMc2nPrG8ILOVdztxw7pK3KAneO57/VtntiWHy5x25oHxJdade41F8AxsbpTL2o7Y1MpjvaRDfGhbWC@mWDuYT@ir3/BZwpddUD/Oz9hHVm8s@VerrznJM7DQki8UPPawH7zQTPIpsek37NXH4kmf4vse/Ca7r2h8xSa/KUGNMenFitjmnzZyRq@udmDE1l4KSrIDkjitZLwT/8jLdZpYtOa6dpn/Uo35ZXvAe/UU45XvzFuxI1fIL8ZQLGozZwWxKMeIcd5jW8r5wBqqQZ/7Nuw0F@Qbac1Y2xSwJzej5mvQfuzEp6mWf8CGJMxeahpn6D905F1rbvXGmvPYk8B903muscYnxjGIXzlM/8gF4lo/KsdmkGfwDw0acvBLIzfpJ37re3Gqj4Jy5Zpow8E@fGbMxVLyLDEg13Kmse6MlzUDHPUWFfYhl2kCHc1RfcI7cx/sdeZq7z5sEXPms7b4rlFWtHHlDPMY3@RcMV52ouivbwZzU3vFjet4Z44ZI3EnJ5unys0xYj26t3JNMs7EkHgk9@tP@S7zlTrg81bsmNv4odYX4tuaILaQZ/UGZ03mJPTQnlaM2e1wtjXHfJO3xHkyL/QN8WjkSPFgvhkDMEgeJO1o9a18zFrPjp4hLswbsW@sAkNdZKijv6zxSO6Fejug2qbZEYK@JNJM02vRx5JgtuV1a09OM027Qp2hNlNO6fN4RoWl1SRh@C/DH21LtMDTtkQHNnoOB8aIGOoybQZjCI0cM5Dtqz0Wdtg59PYFtOO2LhHegKJoBui8mRrRzYa0c@SiuRjsFhr6SKDAQ46nDjp22ID2DiLjwESL0dod2bMiDKsYVtEE03FM0hYGmGRjSXFCTq/98BQpjqgYMDAgGlbrPZ12AhAim14lkD70qE5RkCzmMsgEWxgnYtpiRzQMb9jKCmRDJzRMFFZmQTorGs4QgCnOduigF6PHI8wMp3R9ztLUdOYi9ADIcG5rc0UXV1NXaXkxgU38ahzCqD32zsivnWuJB@JwF9ElzOxTigPxAEMRPVpmx0DSlhHCuY0lrWMhw2dN4bGNdHhXIL0MsfZ4QsAcQC2nYwUGrGfixcLa6Z0zcWXtLBptAHVM4wiXh8LgTEyHy/yDh2vqTetgBE9UOovIYbWnYhVNB9zPB51N7vTpAAKIzEMbYCUZ6SxrrwUGVIqQrSMwPRVmowQ2ewcALDmeKud1AvB0QMSzAMjeG2QM45UGzaujSwjjdUeYQAbUELQjyyEgAtg5nuFGx9VIL5C0bAjekfKMU1kLYsEIbXrTRCjW649WvKMvFZSkxGe0GehEg0XGDfQO4oa2E78kbzWwAbLHb3bFbIF9nXo4nP4lhDaHqhFmtXgHapGGoTM1hxgcKqjtUDpdHgQ3RCDukJFUCaAyzeMroavZqK5lKOZBRNPUVbHk3UjjbNwZFW8xkIjzaTDoLaF7uswQxxsYmsSorsTUaDb8pN6YsQP9JGnUOgcApoESCmOigiBmu28yUqnrtN/kfAPRRIFIdwsGcnBoCBu8AypJM@FCGtGAEuaB5KGdyClCCDmFhBEWJB1lRkhWDldAVLQk87Dz@oi6OPRO6vlqxUuk7AYBQ9oRWpIWd6NbQ9bR7TWZCdACJ1KI8QO0CYngKPBGsIEgGSrM4V8kI40kYb7AjZFsYgOEDBTJGyYJsnWgwclKSYriF6ChJa028A2EQFaCQOm3hyGS9CA2sIEey0xAEB3eQEiDDIxpnExtG7z3CjKp4zZgIvC0biYy7jN/KKCBwxtRxyvJGZmtMCJAUInEGo1w7T0cvRaPiWanGKxhmMZyMhIRMg@Egp/IF7TVWXIwhpOmsGmX6QUToL0Bd0tudP5wCH50EMSx8F4TMRxjB2gi4IDGi4vWpCW9oQ2aPnpPMpqoN14agjSA3cqx0GJq8l0iaYmZNO0AdKQYmEhvYBVtMSyLJtBu/sPGoMF4a8jXGXRcANypFFCSZdYptnvrJTOAKHYIE4qecZU/oneiZDkZ7xqvjkYIyBJUBDp9soGHiLdGUV2BGaD00o0wQUrQnOTH/EfLIdkTMGRAGdG7UJJeTXqVw7EBSmcZiRRwGmDwEjPrBZp7wwPFQfZdDmAvWWMEykWPBSwSTy@rSoONUYomFumtF@ErKIzykbwIo3SQrq1EimEBWsFP5gINIE4krqYr1A5OvC20vMPdZiD13dovt/BBQ9S6FfJhFuQVp5I1sEcn9SYHdEHpxa6FN2k4emI1LyVwIcrIQDHwKDibtKKyUpkHMYCPQSFZZzmEOcUH3W1uUSpzE8u9HYF4Dbr@wjhKB3nXQDbCTN0A1CDegSY1DUsHrxl4ic4GGv/wmpkS2POol86tDSY9mK4lc6az1ktKpmXWJi@t@9HsPt@YD3ZNqOwFqXcXdLgY5X7g2pjE2A@sahmLtq6xltdZB4iG3tCQSU2Mh3YKgrYR/YCOrpGaWdue2dPhD1iEvPKuO9lzUSrkNr5bzKBxHgWvyJlNzT4C5l0MzQTkAeryVbk1ma9wTb4VTrYzuNdaT@EmgyAiCkFtjZH6MSnYHwTMERFkWJ9vtMksemp7omyYxIaTiOxgzpG9IkWrUKP1Nqj3Ph/zmehDO14UAxDciPza/oMKALXKp0mOZcqmjve5G0M5CKu1beytrfAPPvevAkn4QBWmqK1Tp57en3ndRxnqdEXs8juypLfDJCFBUI4njVovYwF1exTMR5XWfhKShiaIt2QZtZsD69zsmc5RWkkZnBgBu9lYEM/W1nUwDwbBASjJSVLAa0sSkYB2GoZ7bARzB4VyGOI9aiXLay/dRms8OId2KJgcfY4OkU4249E/dcTcY5IbOIJyq2ttsCmUtX8zCWhArthy2CdysqTtn0jYwLHkQLJDxa5o0bD7sku0wENbUAYkxSvswPwg3PADoIVeg42UM0NEAqGlTBJXgYFPgwnIMG1bHYJQ8IIXro723Ll8Wm9s00mdWOf@2@aelqXJnY0X4K1/KQJCMgTOxIe9Qww0x6xvZxWoM1jNGnsLwDjYpXgjL/FipENQtJhScpJ/b4rOLvY9oqeBBPmHqq717wiqw2sbmUa59uZtvgyXi8SqQKD2UArIHNutPEol@yXwAfcRW5s0Z5bKw@kEDAOswIGWO9FkEy3sBpmaDqyRFrwPxi@DvYBzW09RMGfIdnLSsm@HB9SDdNtIMtbB2r96mOAjpwIpHC15wzyD0aYqcZjzAdCiuNkrEZ8AI7f@OYGVuQmxOXBiQXRv0HFwbrUt3DC6Tct/Xby7Wrzf3pfv7rarzfq@/HAPtTXX9@X2vur4uPx1vbheXbDi9Xf3P1wtdu82t9f5x7cP34z/z@378vy/AQ "Clean – Try It Online")
[Answer]
# C++: A naive brute-force solution
Try to split the string in any possible way where all number are within the range and do not repeat. If there is only one number missing, add it to the set of answers.
While I tried to optimise the code, I did not put any heuristics or optimisations to the algorithm. The solution is so slow, that it can only handle the 1st and the 3rd test case. It can be used as a baseline when comparing "speed" and to show how a better algorithm implemented in a slower language can beat a worse solution in a faster language.
```
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
class missing_number_solver
{
static constexpr int max_digit_len = 6;
long int n, m;
std::vector<long int> digits;
std::vector<long int> used;
long int used_count = 0;
std::set<long int> results;
void f(size_t pos)
{
if (pos == digits.size())
{
if (used_count == m - n - 1)
{
auto idx = std::find(used.begin(), used.end(), false) - used.begin();
results.insert(n + idx);
}
return;
}
bool negate = false;
if (digits[pos] < 0)
{
negate = true;
pos++;
}
long int acc = 0;
for (int i = 0; i < max_digit_len && pos + i < digits.size(); i++)
{
if (digits[pos + i] < 0)
{
// Minus sign. Stop.
break;
}
acc = 10 * acc + digits[pos + i];
auto number = negate ? -acc : acc;
if (number < n || number >= m)
{
continue;
}
if (used[number - n])
{
continue;
}
used[number - n] = true;
used_count++;
f(pos + i + 1);
used[number - n] = false;
used_count--;
if (i == 0 && digits[pos] == 0)
{
// Leading zero. Do not consume more digits.
break;
}
}
}
public:
missing_number_solver(long int n, long int m, std::string str) :
n(n), m(m)
{
for (char c : str)
{
digits.push_back(c == '-' ? -1 : c - '0');
}
}
std::set<long int> solve()
{
used = std::vector<long int>(m - n, false);
f(0);
return results;
}
};
int main()
{
int t;
std::cin >> t;
for (int i = 0; i < t; i++)
{
long int n, m;
std::string s;
std::cin >> n >> m;
std::cin >> s;
auto results = missing_number_solver(n, m, s).solve();
for (auto result : results)
{
std::cout << result << ' ';
}
std::cout << std::endl;
}
}
```
[Try it online!](https://tio.run/##dZZbbxtHEoWfyV8xwAIRtXIrfe8eS9a@7OMu9iGPQSBQ1EgehBeBF8NI4r8e73eGF1GOI4DiTHd11alTp6o5e3kxz7PZ16//6Jez@e6xa2771Wa77qaLu/Hr2qdutl2tz1em8@fVut9@fGO26bZ34/FsPt1smkW/2fTL5/vlbvHQre83q/mnbj3@fTzabKfbftbMVsvNtvv8sm765bZZTD/fP/bP/fZ@3i2bD02@GY9H89XyedhdvmsWNzr5@P79Hsrtce@uGY5tZP/9/d2me7w5c6b3@9lqx@OHxp7Ogf3s0Lrb7OZ7r59W/WPzNNn0v3X32@Zltbkcj0hj1D81E96aDx8OEK5lMrlke9gfDM6DfWgWjWmWfJxs9kaj6W67avrHz4AZcDz1y8fh2PVD99wvJ5fvBsTXHcs8P03nm@4SH@cmN4OnA@brfrnp1tvJsrmS3/3ml/FgsN2tl3r/Ql6jh9Vq3iy75@m2I/jg@OaQ1z6hn0nvl@a2saeUTtbb9W4wHmFydXVyeSJ5Opvt2R2NnlbrZqK1fljh6/abcv/wg2gVXLbecIn11dUbQl@Ryf6E7kDmjz82/@2Xu02z6Z@X181P29XL9bDxgKJ/PTCh/3t8zjb/HKBeNd/4HUyH0uz1i/Eh9381Rife69zN@AjrYHVLef/443jmjoqfgUPxW8B1rwU5KuTnwwHU8cvfH9D/b63PS/GqNVVEK0@TI69XaO7m7zycSn/mwpjX5Hpp16pM57rQ2lvq/9NNH2n55rduvbpu/g13q@3Q57tF1yxW6@5Y3L@UZPiQ4cvuYd7P3o9H350ek/OBcHpevNs3DlNLwfm6bN4PYp0saZjFZHFo2EGIs4/TdaPyye4orAOsl93m4/3DdPbrZKbsLsyFqu0wnkHVhb24vDkh/d7QGFBODtFE5bGnv51Jk2EQHJt5aJKJHb73Lfo6fgj1hULsR6RaXRNUb9vT4Jr1y@bubr/wvV7bHpvo9/MGPYzU0RvqhpKfOx3@vdodVvd2Q3ccgBLt@xVTGOpzeX3gZjg5oDw7DsEHP6eK7MOtdtvm9vZoxdNFc3EowVuL4YUJOd8zNv76NY8t7W3H1bbW2exdCTGmNgXXZldzsC6mnFsfa4m@JN9G37Zt8DWVWmxua3A@hNQ67zlZ2sROxUuptS0htCGGmFPCBstaSo6@utQWuQ8lJ5tLaFN0zieXbI3Fuxqtz9mCovqYcwBHaUOJMYfact76lEpsC3E4l3Idm9baxsRkxya7ZHJwBtcmp9bktjUlVlNcNClFjJxJuTW1rSZmb3LJhpist4aUTPLexDaYnKvJVXt828B@MqkWA3iTQsGGswE/EfuaiMFe8MSt@G5NLE6oeA6GREz2@EoFn94k63i3YAVTBF/BzvPsC755V6w2E9OzDt6WT@GZ87UlFphryPgJPMu/ZZ8zwhxYA1@xxJF/Z8mBb/AW@ca2RrCANclHUfwEXriqypmzkTNthD8w4ivLzsEhOLKDK2LCP9yBJXGG5wTHWbjFY4j4z@yDN4MtChMfH0y1Cez4Ieds4aqCH6wZrhLPMesMvh01cKyTf83UM@gb3K1shI9aWfEkPlRvOFe9wJnEJ@cRCfmQG1yiZNaol2xYq7Kx4Ha8R3Kt4EmckQ05FKdaEZP1WJQLHFK7DLZYscnywXor/2CgFjWCA58Fjgq5lyyuyTEojmpLDSoalDbJo7aqOXHRXUWLFexx4B8c0gm8RvykrFrCa1XdwSaugjTNtzihngmfiW8aBt1g56QbcKLnUsSvdCoOyIe4RX2g@lLrrLOqhVUMco7yi22mNl7@sPdgpj45iANpCttW/QRe8QZnFS6zFT7iD9rHV1Et@XjhVU@yhhYS/ZLQTmWPwQEf7Af2o3gjX3EsPYlTuC/otxZpR/WVNnnPxFdNirQibfNRjsQowgoXmdoyuYij89hG9Z5ykP7xR49U1S6p15WX@h9cXv0FD/ROFU5p3GlPfSvtaFZovqiG0qJyJpaVFjVjpHH2ya0O/YBNRCfSNLrN6gXNm6oeUH2la7jRvFG/WuVPnnBaveYP2gB/4WzkTMniD4zsJfVWUa2Jx5mK7mNWXNUaTlRHK/1qhokfzQLpWjzKD/XRfGD@VCsM8BI1m8QT7@JeOhVHVn41a@BXfMJHUc2lpapY0oBmLTFV66x6UVPpiHyzzuGXqwSM6lFxwp56H@1l9WrROXKR5tTPykV7Ub44rzlk1cdwM/SK6kUMalTFTaveVL7SjezYU4@pRtKdZrL6VH6HGmEP9qRZU1Vnakg9qs6LT827YV4JA5wnaUe9DQ9eXEjfuhOkLfxl3TnMyWEmgUP5JGkMzsWL7hz1m@aWdF7VF@KGekTNSOlB/aYaoEH6oCqPJG41j7FV7KAY0oX6RtpXrexwo4@5J4cLtuU12LFrHZe2s6xypfBHQzvPTRkdV150aFqXPJL2wXuyGRufhl8GLa0JeZ4r3HlGKrc/9fMM@dBygIStLldPlbjTDdcz17jhIaBV57jEua89@AN3Ap3jKDWTkwuHXuMWj05XnDYJEp1@DTCASI3gTIw28GsA9fNjxDgmKAgBz1XFjRjcIEN0yW8C4@QN/7hFxc4ENOQ0hyllC/JhTFETkkWFGqAO1Xt8RwnA6GYzTsIHNCgMPNWxa7wfA9EHxirVcrh2A21wxm3jWm//nD3Np8@br@Z/4f8 "C++ (gcc) – Try It Online")
In addition, this is how a test case with multiple solutions looks like:
```
1 22
1212345678910111314151617181920
```
As I understand, the output should be:
```
12 21
```
as the original sequence must be one of:
```
[1, 2, 12, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20] # missing 21
[1, 21, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20] # missing 12
[12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20] # missing 21
```
[Answer]
# JavaScript (ES6)
Quite slow, but I think it can solve the test cases.
Not all test cases present at the moment, I'll try to put all of them later.
```
Time=fun=>{
var t0 = performance.now(), t1=t0, t2
console.log(fun(msg=>console.log(msg, (t2=t1,t1=performance.now(),t1-t2))))
var t = performance.now()-t0
return t<1e3 ? t+' ms':t/1000+' sec'
}
function Missing(str, ll,hl)
{
var can, seq, num, i1, i2, s1, s2
var rec = span =>
{
var num
if (!seq[span]) return 1
if (seq[span] == '_') ++span
if (seq[span] == '-')
{
++span
num = -seq[span++]
while (num < hl && num >= ll)
{
if (!values[num])
{
values[num] = 1
if (rec(span)) return 1
values[num] = 0
}
if (!num) return;
if (seq[span] == '_' || seq[span] == '-') return;
num = -seq[span++] +num*10
}
}
else
{
num = +seq[span++]
while (num < hl && num >= ll)
{
if (!values[num])
{
values[num] = 1
if (rec(span)) return 1
values[num] = 0
}
if (!num) return;
if (seq[span] == '_' || seq[span] == '-') return;
num = +seq[span++] +num*10
}
}
}
find=num=>{
var i1,i2
if (num < 0)
{
i1 = seq.indexOf(num)
if (i1<0) return i1
i2 = seq.lastIndexOf(num)
return i2 == i1 ? i1 : -1;
}
else
{
// take care of false positives when there is a '-' before the number
// so much slower respect to the other branch
var rx = new RegExp('[^-]'+num)
i1 = (' '+seq).search(rx)
if (i1 < 0) return i1
i2 = seq.slice(i1).search(rx)
return i2 < 0 ? i1 : -1;
}
}
for (can = ll; can < hl; ++can)
{
if (str.indexOf(can) < 0) return can;
values = {}
values[can] = 1
seq = str
for (num = ll; num < hl; ++num)
{
if (!values[num])
{
i1 = find(num)
if (i1 >= 0)
{
i2 = i1+(''+num).length
if (seq[i1-1] == '_') --i1;
if (seq[i2] == '_') ++i2;
s1 = seq.slice(0,i1), s2 = seq.slice(i2)
seq = s1 ? s2 ? s1+'_'+s2 : s1 : s2
values[num] = 1
num = ll-1
}
}
}
// console.log('REC',can,seq)
if (rec(0)) return can
}
}
Test = [["229272120623131992528240518810426223161211471711",0,30],
["11395591741893085201244471432361149120556162127165124233106210135320813701207315110246262072142253419410247129611737243218190203156364518617019864222241772384813041175126193134141008211877147192451101968789181153241861671712710899168232150138131195104411520078178584419739178522066640145139388863199146248518022492149187962968112157173132551631441367921221229161208324623423922615218321511111211121975723721911614865611197515810239015418422813742128176166949324015823124214033541416719143625021276351260183210916421672722015510117218224913320919223553222021036912321791591225112512304920418584216981883128105227213107223142169741601798025",0,250],
["1342319526198176611201701741948297621621214122224383105148103846820718319098731271611601912137231471099223812820157162671720663139410066179891663131117186249133125172622813593129302325881203242806043154161082051916986441859042111711241041590221248711516546521992257224020174102234138991752117924457143653945184113781031116471120421331506424717816813220023315511422019520918114070163152106248236222396919620277541101222101232171732231122301511263822375920856142187182152451585137352921848164219492411071228936130762461191564196185114910118922611881888513917712153146227193235347537229322521516718014542248813617191531972142714505519240144",0,250],
["80901062173445953196186301456692487427529429993285787069831233591227347952858217788973393434655233831877642815971961376506739541125150847218402660459824663618793744638964202557497582411568",0,100],
["1302797101187197126231292239133232171515415180252611104191857114450179111134201662662932221381232833721819553193151235255288382951611921896841051718124164119345781124629128526219276169113296142414667176120182159236229724224516532275167119911243329243153024688191841282382655120729228164986223079108216327276103148145142108302692092566328429021116692173174253143279251205351277329821214010060691392141981836583611522942572022622786840551472342675428024419426414125827112277297170168186160110274722278115694901142861021820190220247252137158289448121233277249250155149270135481781852131754322187701628221622313210925442210224106118208268228260259299563117313621524812441579558157591322615020323724028718891772125199273808916247116862811074974204225999613626323152211312397519621734172206200",0,300],
["201-1382843613319717171212-193-175-591897023633-61234-11828-6108969023295-104-18916914-36-893-23126175-85-9611811654113-158-198208-250126-95143166-65160215-70-44-202-194158-16324475-2011514516537-90-358511742-211-97-139162219-29221-18135-12-60-22516-222-312288-217-102137-2092095274-190-87249-105-249157-6916430-116-15360225100-178-218-129-141248-111-224220224159237-128-137-79-38-18798-51-238-173-203109532429200223625180188-226112-142216-242150-1231038-228-887379154-210101130-5323115199-15623180-20710425-245-186-147102-247240233194168-112228148592144964-149-100-52193129152-34-1134043128123-172110-6363144-21922746-151-174-140-19299-206161-12268141-214-805067206-46-5195-237-5813-40-130-170122-229-16558213-184-47174-161190-13487115-115-23-235-143-201078382222-57-67205-18-81-427278-179-11-162-244-86-83-8421-11927-120204-71-50138-136-1991359165-126173-76448-62206229-99179-164-110-220-146-17697-22376146-49184-236-37-91-43-419671127-54-23269-480-451313817023821721015322617613-3224286-182186-144-233-216-24016313977-98-230192155-101182183-14889-19714018581-166-114-1502189-27-212-17-92121-1-23918732-132-215-205-21-33-15961-1275-15-196-39-56-154-243-6820256-89191239145-191178-55-208-9347-16-41-221-152-2839-18310-241-117-169-75-103-73-16716744241-248125-64119-30120-94-177-234-195-13-21324734198-14571569255-26149-107-13111-121-125-171-77-204-157-25-168-66127-19-200172-78105147-7213212466177-155-135-185-24-109181230-227-7424619-106142111-246-22074111494-7-160-9106-10-133-18024531-145211-124-3-188-82136-22235-10818203134",-250,250],
["-615-631-765-659-699-748-714-554-451-569-898-462-676-721-459-578-522-493-668-686-728-603-455-587-815-537-492-639-842-485-747-832-768-899-471-900-893-598-626-757-682-501-620-614-549-770-824-527-539-755-596-452-821-591-572-857-895-776-836-503-773-590-575-568-633-737-702-514-510-724-592-739-790-846-732-536-579-775-479-688-687-740-794-650-637-636-518-791-611-473-497-675-758-697-548-655-559-534-736-677-860-543-733-723-805-831-670-608-883-502-600-583-467-867-613-612-621-861-731-866-793-460-798-505-595-771-769-486-718-570-813-749-685-496-630-819-886-785-870-807-516-744-680-653-719-859-717-681-880-476-674-582-667-489-865-876-695-495-703-841-707-711-777-760-848-837-517-532-784-465-693-894-520-678-862-818-487-743-782-597-477-562-519-586-839-700-538-710-566-746-565-546-466-456-811-599-822-772-602-480-810-494-751-550-640-665-508-809-581-840-560-863-526-454-725-683-632-660-729-594-457-753-759-816-609-706-800-891-877-617-628-715-651-833-547-558-817-734-698-735-647-762-589-855-541-774-792-875-838-574-652-864-482-673-619-799-780-851-783-666-644-742-812-872-641-622-662-535-814-803-856-720-722-498-826-500-524-858-897-512-490-610-808-529-694-528-506-804-701-761-561-679-634-834-738-545-712-605-623-878-588-882-513-461-828-624-509-854-616-823-458-472-705-488-767-556-523-533-779-829-654-849-464-830-499-763-504-585-580-852-730-474-657-557-692-727-801-825-844-542-661-892-820-656-704-835-563-672-690-709-750-689-766-604-553-551-868-577-726-478-663-642-752-463-745-716-483-481-696-671-869-625-618-564-881-648-573-691-606-786-843-788-827-797-888-795-874-584-796-787-778-806-847-593-507-764-879-635-889-521-887-511-713-884-754-873-470-601-646-552-530-845-525-567-627-491-629-669-741-469-484-571-853-850-453-576-708-871-789-885-658-664-643-802-515-684-540-555-896-756-607-638-645-531-468-475-649-781-890",-900, -450],
["183205152228238-164156229248-187-189-207-112-128134-245231568-246-4760213-7266-1961240-141199233138-226-12421763-159125-208239-195225146-51-45105-24794-126-165-37-1456-40143109-75-222-116-70165110-214-11151-127-17411923779-864-720-2031573215875-65190-27187191878218613723286-218176-34-90-123182-153-38218-7618-173-205227198-25010710624430148-25-198-14824778-239-215597-21749206-121-1681627711456-35-101-18201-235-88-19124171200-194-78-125-138127216168-248174128153181-41299117811-146-171212850-20615021-1301189-69-152-117-23422367-43-6823-23273140-231195-220-44-197-211-64219121185-134-96-2217076-58-107-80222117-14-119-111111-102-7735197169-99-1324817326-163-223113-240-190-7917513957-154-103-66101126-298149145-1764351-28-2291372-135-202-118-175188-42-161975216153-109210172-862202653992132-85-1-1391099-738962-56103-180-97154-131-249-105-93-53-5550-89160-160204-104-114-3946-6374-170-17-18520398-59-36-177-94-238-2345-219177-243-15755-82-20115-149108-200-31-71135220234142844104-1934061-32236-166-6081-137-156180-1675436-182-9270179192-221-20180-120124-2372237-8716243-147-1692731-21-224-83-136-67-199214-49-241235224-212-233-16-210226167195833171-84245-11341-614488-19213014-10619612316312-74211-129133-10813169-155-41-144-133-183-98193-213-57958325-12164-24-230-54-50-142-244-30141249-122-2155-204215-942152990-91194-95100-11017-5-1812893-186-1396-242-140-179-188-236-151-228-216-2093-3147-11511224-48-62207-162-15024634-26-15813647120116208-100-19209242221-178-15-184-33-81159230-172-227-52-61184-225-461024418938122166-143",-250,250],
]
function go() {
var t, i = 0;
var Solve = _ => {
var [s,a,b] = Test[i++]
console.log(a,b,s)
setTimeout(_=> {
t = Time(_ => Missing(s,a,b));
console.log('Solved in',t);
if (Test[i]) setTimeout(Solve, 100);
}, 100)
}
setTimeout(Solve, 100)
}
```
```
<button onclick="go()" >Test</button>Expect a total time of less than 3 minutes for all test cases in chrome
```
] |
[Question]
[
Programs often list outcome statistics, such as this:
* 54% of participants received an award
* 69% of participants got a promotion
* 85% of participants increased their salary
These percentages are the result of dividing *a*/*x*, where both *a* and *x* are whole numbers, and the result is rounded to the nearest hundredth.
Your task is to, given a set of percentages of arbitrary length and an arbitrary precision to which these percentages are rounded, find the three smallest whole numbers *x* of participants which could result in the given statistics.
To standardize answers, let's presume your input percentages are given as floating or fixed point decimals (your choice) like 0.54 and 0.69, and a precision given as an integer such as 2 meaning two digits past the decimal point.
For the above statistics, the first smallest number of participants is 13, and the 7, 9, and 11 participants had each of the given outcomes. Thus, 13 would be the first number in a set of three output numbers.
The winner will be the shortest piece of code counted in bytes. Any rounding method is acceptable in solutions, but solutions that offer solutions for multiple rounding schemes (floor, ceiling, or nearest) are encouraged.
**Another example in Ruby**
```
percentages = [ 0.5, 0.67, 0.83, 1.0 ]
precision = 2
smallest_group_size(percentages, precision) # Should produce [6, 12, 18]
```
[Answer]
# [Python 3](https://docs.python.org/3/), 80 bytes
```
lambda l,p:[i for i in range(1,10**p)if[round(round(e*i)/i,p)for e in l]==l][:3]
```
[Try it online!](https://tio.run/##JcpLCsMgEADQq8xSZbAa6YeAJ7EuDNF2wKpIsujpLdLNW732Pd61mJHsc@Tw2fYAGdvqCFLtQEAFeiivyDRqJUTjlFyvZ9nZ3yiIXwgbnz3Onr212bvV@NE6lYMl5pS8Iih5u08fBkFL5REWzscP "Python 3 – Try It Online")
[Answer]
# JavaScript (ES6), 84 bytes
Takes input in currying syntax `(a)(p)`, where ***a*** is an array of percentages and ***p*** is the precision.
```
a=>p=>(b=[],g=n=>b[2]?b:g(n+1,a.some(x=>((n*x+.5|0)/n).toFixed(p)-x)||b.push(n)))(1)
```
### Test case
```
let f =
a=>p=>(b=[],g=n=>b[2]?b:g(n+1,a.some(x=>((n*x+.5|0)/n).toFixed(p)-x)||b.push(n)))(1)
console.log(f([ 0.5, 0.67, 0.83, 1.0 ])(2))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes
```
3µNLN/².ò¹åPi¼N])
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f@NBWPx8//UOb9A5vOrTz8NKAzEN7/GI1//@PVjDQM9UBEmbmINLCWEfBUM9AIZbLCAA "05AB1E – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 37 bytes
```
{3↑x/⍨((⍺⍕⍵)≡⍺⍕⊢÷⍨(⌊.5+⍵×⊢))¨x←⍳10*⍺}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24Rq40dtEyv0H/Wu0NB41LvrUe/UR71bNR91LoRyuhYd3g6SfNTTpWeqDZQ7PB0opql5aEUFUPej3s2GBlpApbX//xsppCkY6JkCsZk5kLAwVjDUM1AAAA "APL (Dyalog Unicode) – Try It Online")
] |
[Question]
[
Inspired by [this](https://codegolf.stackexchange.com/questions/138068/kill-it-with-fire) and [this](https://codegolf.stackexchange.com/questions/138108/will-i-make-it-out-in-time) which was inspired by the first question.
I've set my farmers' fields on fire, but unfortunately they saw me do it! If I don't deal with this situation they could report me and then I'd get arrested! So, that shouldn't be too hard. All I have to do is kill them with fire!
The field will be an `m*n` grid with odd `m` and `n` where both are one greater than a multiple of 4. The farmer starts out in the middle of the field. Each "tick", the farmer can move to an adjacent square (edge or corner) and any space on fire will ignite every grid adjacent to it in a 3x3 space (edge or corner again).
Note: fires and farmers can move diagonally.
The grid will be given as some 2D array of 3 unique values: `F`ire, `.`Wheat, and `H`uman (Farmer). For example:
```
F...F
F...F
FFHFF
F...F
F...F
```
*the farmer is doomed to DIE! >:-D*
It would be easy if I could just light a fire right beside the farmer and set him on fire. However, he knows I am in the field with him and he has a gun. If he sees me, I'm dead. So, I can't light the fire within half of the distance between him and the edge, of him. Essentially, if you floordiv the width of the grid by 4, I must be within that many spaces from the edge, and same with the height.
I am immune to fire so I don't have to worry about getting myself out.
The question is:
## Given a field with wheat, a farmer in the center, and potentially existing fires around the field, how many fires do I need to light to guarantee I can kill the farmer?
### Test Cases
These test cases have input represented by a `F . H` grid and output as a single integer. You may take input in any other reasonable format and output a single integer.
```
FFFFF
F...F
F.H.F => 0, the farmer is doomed to die in 2 ticks anyway
F...F
FFFFF
FFFFF
F....
F....
F....
F.H.. -> 1 (just light a fire on the far right side of him)
F....
F....
F....
FFFFF
.....
.....
..H.. -> 4 (to ensure his demise, you would need to light 4 points around the perimeter (with rotational symmetry). Any 4 will do.
.....
.....
```
# Rules
* Standard Loopholes apply
* You can take an array of 2 values if you would like, where you infer the farmer's position from the size (since the farmer will always be in the center)
[Answer]
# [Python 3](https://docs.python.org/3/), 672 bytes
```
e=enumerate;H='H';F='F'
def f(m):
q=m[0];h=len(m);w=len(q);o=0;g=lambda m,c:{(k,l)for i,r in e(m)for j,v in e(r)for k in range(i-1,i+2)for l in range(j-1,j+2)if v==c and k>=0and k<h and l>=0and l<w};n=lambda m,c,d:[[c if(k,l)in g(m,c)-g(m,d)else m[k][l]for(l,v)in e(r)]for(k,r)in e(m)];s=lambda m:H in[q]+[m[h-1]]+[r[0]for r in m]+[r[w-1]for r in m];l=lambda m:all(H not in r for r in m)
while 1:
a=m
while not(s(a)or l(a)):a=n(n(a,H,F),F,1)
if l(a):return o
else:o+=1;z(m,a,h,w)
def z(m,a,h,w):
for i in(0,h-1):
for j,v in e(a[i]):
if v==H:m[i][j+(h-1)//2]=F;return
for j in(0,w-1):
for i,v in e(r[j] for r in a):
if v==H:m[i+(w-1)//2][j]='F';return
```
[Try it online!](https://tio.run/##fVJdk5sgFH3WX8GkD4EJcc32TZc@Ov4HygNNMGIAjbpx205/e3pBm2R3Z8oMF87hcrgfdD/HunVfr1fFlHu1qpejyku2Ltd5wdbFOj6oClXYkiyOzszyVOQ1M8oBk09hcyZ5y9L8yIy0Pw4SWbrPfuMTNaRqe6QpTIcU@HvY0MsM@wBPHvTSHRXW2x3Vm@dAmzvdAN0ArSt0YWyPpDug0zeWhvWlDtgs2LxMf3L3EAc9ZJzvka5COKB5xMCSrV8ORJlBIctPghsBr2JDL2SJLeAT7ckSusiHm2xWQnT8LDbc8nq7E7DpoSw@7pCqDcQEJw9Ubu73pTG4RK4dQ5bo7kXiaKq1UWgHxY4ks2BnApzxgCXxtYGFZJI57LCkJS0ILegOrkZQIn@Y9Wp87R1qgfIpZu2G7fJfkLKkNZ1I6OgdwlOhTxABTikk5JnoXa8k1yKw0dyFMrPA8GaDvfvT07NgRT6/Oos1s9j0IKZvjeeNuOcsP@lu8LSIgqP/gYvyVduu7UfUdb12YxyrN2k7owbG49VqVfgRF0mSeFsmt70fcE7fOyUfbPmJCfbxchKof7Z82MOAcxHHPqshZLnElsUIhk0RQ5xf0H8/2ZAMndEjXn13K0IE@oICHtAwQsJHkB1bBN9HAnwLunMlknnBNiUzG1DlMbn@BQ "Python 3 – Try It Online")
It's very long (I've done my best to golf it), and the solution is not optimal. Here is the general idea:
1. First, let's see if the farmer burns in the original situation. The matrix `a` is filled with `F`s when the fire grows and with `H`s if the farmer can reach a position (`a=n(n(a,H,F),F,1)`).
2. If the farmer escapes (`s(a)`), look a the border of `a`. There must be at least a `H`. It takes `(h-1)/2` ticks to reach the top or the bottom, and `(w-1)/2` ticks to reach the left or right border. As soon as we find a `H` on the top, we put a fire at `(h-1)/2` cases on its left. In `(h-1)/2` ticks, an `F` will be there and it may also "burn" other `H`s. The same applies for the left and right borders.
The solution is not optimal because:
* there are some edge cases, in particular when a fire will burn two borders of the field.
* considering top and bottom borders before right and left borders is not necessarily the best solution
* going from left to right and top to bottom to find a `H` is not necessarily the best solution.
] |
[Question]
[
# Cyclic Polyglot Challenge
*This is the robbers thread. You can find the cops thread [here](https://codegolf.stackexchange.com/questions/129866/cyclic-polyglot-challenge-cops).*
## Cyclic Polyglot
A N-element cyclic polyglot is a complete program that can be run in N different languages. In each language, when the program is run with no input (possibly subject to [this exception](https://codegolf.meta.stackexchange.com/a/5477/9486)), it should print the name of a language to STDOUT. Specifically, if the program is run in the Kth language, it should print the name of the (K+1)th language. If the program is run in the Nth language (that is, the final language in an N-element cycle), it should print the name of the first language.
An example might be useful.
```
a = [[ v = 7, puts('Befunge') ]]
__END__
= print("Ruby")
-->*+:292*++,,@
--3 9
--7 *
--^,:-5<
```
Running this program with Lua prints the string "Ruby". Running this program in Ruby prints the string "Befunge". Running this program in Befunge prints the string "Lua", completing the cycle. This program constitutes a 3-cycle consisting of Lua, Ruby, and Befunge.
The same language cannot appear twice in a cycle, and different versions of the same language (such as Python 2 and Python 3) cannot appear in the same cycle as one another.
## Cops
Your challenge is to write an N-cyclic polyglot, where N is at least 2. Then, you must add, replace, and delete some number of characters to the program to produce an M-cyclic polyglot, where M is strictly greater than N. You should then post the shorter, N-cyclic polyglot (and the languages it runs in), as well as the number of characters you changed to produce the longer polyglot. Your score is N, the number of languages in your shorter cycle.
The robbers will try to identify your longer cycle. If, after seven days, no one has successfully cracked your solution, you should edit your answer declaring that it is safe. You should also post your longer M-cyclic polyglot at this time.
## Robbers
Given a cop's N-cyclic polyglot and the number of characters they added to produce a larger polyglot cycle, your goal is to produce that larger cycle. If you can produce a longer cycle by adding, deleting, or replacing as many characters as the cop did *or fewer characters*, you have cracked the cop's polyglot. Your score is the length of the new cycle you've created. Your new polyglot need not be the same as or even similar to the cop's secret polyglot; it only needs to be larger than their existing one.
Your solution may also be cracked. If another robber comes along and produces a cycle strictly longer than yours, starting from the same cop's polyglot, they have stolen your points.
## Valid Programming Languages
Since this challenge indirectly involves guessing programming languages used by other participant's, the definition of a programming language for the purposes of this challenge will be a little more strict than the usual definition. A programming language used in this challenge must satisfy all of the following conditions.
* The language must satisfy the [usual PPCG requires for a programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073).
* The language must have either a [Wikipedia article](https://en.wikipedia.org/wiki/Main_Page), an [Esolangs article](http://esolangs.org/wiki/Main_Page), or a [Rosetta Code article](http://rosettacode.org/wiki/Category:Programming_Languages) at the time this challenge was posted.
* The language must have a freely available interpreter or compiler.
## Final Notes
* The code you write should be a standalone program in every language that it is intended to run in. Functions or code snippets are not allowed.
* Your program will be given no input through STDIN. Likewise, your program should print nothing to STDERR.
* A cop's score is the number of languages in the cycle of the polyglot they posted. The cop should post the languages that the posted polyglot runs correctly in, as well as the number of characters they added to produce a longer polyglot. They are *not* responsible for posting the languages the longer, hidden polyglot runs in until their answer is safe.
* A robber's score is the number of languages the modified polyglot runs in. As with the cop, the robber should post the list of languages the polyglot runs correctly in.
* The number of characters changed should be computed in Levenshtein distance.
[Answer]
# [mdahmoune](https://codegolf.stackexchange.com/a/129967/65836), added Ruby, Levenshtein = 10
```
#include<stdio.h>
#define print(a) main(){int z[1];if(sizeof(0,z)==4)printf("C(gcc)");else printf("Perl5");}
print($=?"Ruby":"C++(gcc)")
```
Cycle is `C -> Perl5 -> Ruby -> C++ -> C`
I don't really know what I did (and I really don't know why it's valid in C and C++), I just ripped it off [this answer](https://codegolf.stackexchange.com/a/7280/65836).
C (gcc): [Try it online!](https://tio.run/##S9ZNT07@/185My85pzQl1aa4JCUzXy/Djks5JTUtMy9VoaAoM69EI1FTITcxM09DsxrIU6iKNoy1zkzTKM6sSs1P0zDQqdK0tTXRBCtN01By1gCaqamkaZ2aUww1ACgakFqUYwoUrOWCGKlia68UVJpUqWSl5KytDdXy//@/5LScxPTi/7rlAA "C (gcc) – Try It Online")
Perl5: [Try it online!](https://tio.run/##K0gtyjH9/185My85pzQl1aa4JCUzXy/Djks5JTUtMy9VoaAoM69EI1FTITcxM09DsxrIU6iKNoy1zkzTKM6sSs1P0zDQqdK0tTXRBCtN01By1khPTtZU0rROzSmGGgAUDQDZBBSs5YIYqWJrrxRUmlSpZKXkrK0N1fL/PwA "Perl 5 – Try It Online")
Ruby: [Try it online!](https://tio.run/##KypNqvz/XzkzLzmnNCXVprgkJTNfL8OOSzklNS0zL1WhoCgzr0QjUVMhNzEzT0OzGshTqIo2jLXOTNMozqxKzU/TMNCp0rS1NdEEK03TUHLWSE9O1lTStE7NKYYaABQNSC3KMQUK1nJBjFSxtVcKAlquZKXkrK0N1fL/PwA "Ruby – Try It Online")
C++ (gcc): [Try it online!](https://tio.run/##Sy4o0E1PTv7/XzkzLzmnNCXVprgkJTNfL8OOSzklNS0zL1WhoCgzr0QjUVMhNzEzT0OzGshTqIo2jLXOTNMozqxKzU/TMNCp0rS1NdEEK03TUHLWAJqpqaRpnZpTDDUAKBqQWpRjChSs5YIYqWJrrxRUmlSpZKXkrK0N1fL/PwA "C++ (gcc) – Try It Online")
] |
[Question]
[
>
> ### Disclaimer
>
>
> It is bad practice to draw out your molecules in 2 dimensions because that is not how they are. I chose to do this in 2D because it is easier to explain.
>
>
> Note that the bond angles are wrong too: the angle in CH4 is 109.5°, not 90° as I said and the bond angle in NH4 is 107°. BHCl2 does have a bond angle of 120° and is 2D, however.
>
>
>
## Challenge
Given the formula of a simple molecule as input, output a truthy value if the molecule is polar (asymmetrical) or a falsey value if the molecule is non-polar (symmetrical).
## Determining Polarity
To determine whether a molecule is polar or not, we will have to look at its shape. For the purposes of this challenge, we will assume that molecules are 2D.
To demonstrate how to determine the polarity of a molecule, let us use three examples: methane (CH4), ammonia (NH3) and BHCl2.
### CH4
Firstly, lets take the centre molecule, carbon. Carbon is in group four of the periodic table so it has four outer shell electrons, as shown below:

Now, we add the hydrogen atoms (each hydrogen atom supplies its own electron to make a pair):

Since there are no lone pairs of electrons, we can draw it with 90° between each bond since all bonds repel equally:

We can now see that methane is symmetrical so it is ***non-polar***.
### NH3
Like above, we take the centre molecule, nitrogen and draw out its outer shell electrons:

Adding the hydrogen atoms, we notice that there is a lone pair of electrons:

Since the lone pair is closer to the atom, it repels more than a bonding pair, so the angle between the bonds is smaller:

Evidently, NH3 is not symmetrical, so it is ***polar***.
### BHCl2
Taking boron as the centre molecule, we draw the three outer electrons:

We then add the hydrogen and the chlorines:

There are no lone pairs, so the bonds repel equally, forming an angle of 120°:

Although, the shape is symmetrical, the hydrogen atom makes the molecule asymmetrical, so BHCl2 is ***polar***.
## Rules
Built-ins which access molecule information are disallowed. You may access periodic table data using built-ins or without adding the file to your byte count. This data may be stored however you wish.
Input will only ever be a valid simple molecule: a single central atom (p-block element) which comes first in the formula and up to eight outer atoms (hydrogen, fluorine, chlorine, bromine, iodine, astatine) which only use single bonds.
You will never get a polyatomic ion or a molecule with co-ordinate (dative covalent) bonds as input. For example, with `NH4`, there would be a single unpaired electron, so the only for NH4 to form a stable molecule would be to lose the extra electron and become an ion (a polyatomic ion, since there is more than one atom in the ion).
If there are multiple lone pairs, they have to be spaced as far as possible from each other. For example, two lone pairs will have to be opposite from each other.
***If there are non-polar and polar isomers of a molecule (e.g. SiF2Cl2) you should assume the molecule is non-polar.***
## Examples
```
Input -> Output
OH2 -> Falsey
CCl4 -> Falsey
OF4 -> Truthy
CH4 -> Falsey
NH3 -> Truthy
BHCl2 -> Truthy
```
## Winning
Shortest code in bytes wins.
[Answer]
# [Python 3](https://docs.python.org/3/), 296 bytes
```
import P,re,itertools
r="[A-Z][a-z]?"
f=re.findall(r,re.sub("(%s)(\d)"%r,lambda g:g.group(1)*int(g.group(2)),input()))
print(all(any(any(q[:len(q)//i]*i==q for i in range(2,len(q)))for q in[j[i:]+j[:i]for i in range(len(j))])<1for j in itertools.permutations(f+['e']*-(len(f)-P.a[f.pop(0)]>>1))))
```
[Try it online!](https://tio.run/##XZBdb9sgFIav41@BkKpC6tAl3YdkzZ2SSK1601pKr8a4IAp2iQgQIIuyab/dg6RY0y4svdb7PJwD9hTejL7rjzK8AWOFRpBIbQ@BBGlgCaCDGHAP2qoY/cM0xJ5Se7y0JrYjQ45OBoFa4gTfIIyLQu6scQH4ky/Oh4IaKL5bbzgYc9f5KjUkpp90yvp3uCmdKOM5LhijfOFqSOeT74zyyS/2DRZt7QRppd5wpZCLLPGHNYLoymP0Y4PhlSvfR3RVRzpnDhZN8VjqgPLvDOPyvE7cERfWpS6dxvXp/O1ppeIl9/j2VrKxrOs9aI0DEkgNHNedQLPyAmCcin0s6JbKit1saSXZf3BCtxgz/HWamm1qhvsRK9zuEHh8be1Re0OvxTUbT85SiycN4bQl1lj0AbP7@2mciPuex3f8XYzgAlbgroxhGcPHFJ5j@JTCSwyfU3iI4UsKc5Xplcx4k/FVxpcq8488848i83M/CCIbC5eNJz1M0NlYrbPxOhhPWXgdVmrWWVjILDQmC/NwMf70K/mgZks1@ws "Python 3 – Try It Online")
-29 bytes thanks to ovs
Prints `False` or `True`.
This requires a dict of all p-block element symbols to the number of valence electrons they have. `H` is not necessary since it will only be one of the surrounding atoms. The dict is stored in `P.py` as a variable named `a` (it's written in the input for TIO and then placed into a Python file by the header)
] |
[Question]
[
Your task is to generate the "Primitive and Basic" numbers, which are made like so:
Start with **110**. Take the digits of its base-1 representation (**110 = 11**) and interpret them as base-2 digits. This gives **12 = 110**. Now, add the second prime number – **310** – to the result. This will give you **410**, which is our first "Primitive and Basic" (**PB**) number, or **PB(1)** (you can now see where I got the name from).
Next, take **410 = 1002** and interpret the digits of its base-2 representation as base-3 digits. This gives **1003 = 910**. Add the third prime number – **510** – to the result, which gives **1410**. That's the second **PB** number, or **PB(2)**.
You can see where this is going: take **1410 = 1123** and interpret the digits of its base-3 representation as base-4 digits. This gives **1124 = 2210**. Add the fourth prime number – **710** – to the result, which gives **2910**.
This continues on and on forever.
In general, **PB(n)** is equal to **PB(n-1)**, converted to base **n** and from base **n+1** to integer, plus the **(n+1)**th prime.
The first few terms of this sequence are:
```
4, 14, 29, 52, 87, 132, 185...
```
You must write a function or program that creates these numbers. It must take a positive integer **n** as input, and return **PB(n)**.
## I/O:
```
1 -> 4
5 -> 87
```
## Rules and specs:
* Your program must be able to handle all **PB** numbers below **231-1**.
* Standard loopholes apply.
* The input may be 0-indexed or 1-indexed, whichever you prefer.
* The input is guaranteed to be a valid index.
* The output must be in base 10.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
*Unfortunately, there isn't an OEIS sequence for this. You can propose to OEIS to add this sequence in if you want.*
[Answer]
# Ruby, 126 bytes
```
require("prime")
->n{o=4
(2..n).map{|i|j=i+1
r=[]
(r.unshift o%i;o/=i)while o>0
o=r.inject{|s,k|s*j+k}+Prime.first(j)[-1]}
o}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
’ß1¹?bḅ‘+‘ÆN$
```
[Try it online!](https://tio.run/nexus/jelly#@/@oYebh@YaHdtonPdzR@qhhhjYQH27zU/n//78pAA "Jelly – TIO Nexus")
### How it works
```
’ß1¹?bḅ‘+‘ÆN$ Main link. Argument: n
’ Decrement; yield n-1.
¹? If n-1 is non-zero:
ß Recursively call the main link with argument n-1.
Else:
1 Yield 1.
b Convert the result to base n.
ḅ‘ Convert from base n+1 to integer.
‘ÆN$ Increment n and yield the (n+1)-th prime.
+ Add the results to both sides.
```
[Answer]
# Mathematica, 66 bytes
```
Fold[IntegerDigits[#,#2-1]~FromDigits~#2+Prime@#2&,4,2~Range~#+1]&
```
Unnamed function taking a single (1-indexed) integer argument and returning an integer.
`Fold[...,4,2~Range~#+1]` iterates a function of two arguments, with the first argument beginning at `4` and thereafter set to the output of the previous iteration, while the second argument iterates over the set {3,4,...,`#`+1} (where `#` is the original integer argument).
The function in question is `IntegerDigits[#,#2-1]~FromDigits~#2+Prime@#2`. First, `IntegerDigits[#,#2-1]` converts the first argument into a list of its digits when written in the previous base; then, `...~FromDigits~#2` converts that list of digits back into an integer, assuming the digits are now in the current base. Finally, the `#2`th prime is added to the result.
[Answer]
# [Perl 6](http://perl6.org/), 95 bytes
```
{my $b=1;(4,{grep(*.is-prime,2..*)[++$b]+.polymod($b xx*).&{sum $_ Z*($b+1 X**0..*)}}...*)[$_]}
```
Zero-based indexed.
### Explanation:
Since the language's built-in `.base` and `.parse-base` methods are string-based, they only work up to base 36. So in order to fulfill the task requirement that large inputs must be supported, the base conversion is done as follows:
* `.polymod($b xx *)`: Convert the current number to a list representing its digits in base `$b`.
* `sum $_ Z* ($b+1 X** 0..*)`: Interpret the resulting digits as a number in base `$b+1`.
] |
[Question]
[
**This question already has answers here**:
[Print this diamond](/questions/8696/print-this-diamond)
(133 answers)
Closed 7 years ago.
Inspired by [**this**](https://codereview.stackexchange.com/questions/134184/java-diamond-with-numbers), print an ascii diamond pattern built using `0-9`.
**Rules**
* Input `n` should be between `0-9`, anything outside that range is undefined
* The diamond should be padded with spaces
* The middle line should always have no padding and be the only line to contain `n`, in the center
* Print to stdout
* As always, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
**Test Cases**
* n = 0
```
0
```
* n = 1, print
```
0
010
0
```
* n = 2, print
```
0
010
01210
010
0
```
* n = 9, print
```
0
010
01210
0123210
012343210
01234543210
0123456543210
012345676543210
01234567876543210
0123456789876543210
01234567876543210
012345676543210
0123456543210
01234543210
012343210
0123210
01210
010
0
```
[Answer]
# Vitsy, 50 bytes
I don't think I'm done golfing yet!
```
VVHr1mV{V2*1+\[2m]
:Xru
v&VvD([D\[' 'O]]-H1ml\NaOY
```
Explanation:
```
VVHr1mV{V2*1+\[2m]
V Pop n, set n as the global final variable (GFV).
V Push the GFV to the current stack.
H Pop n, pop o, push each item of the range from o to n.
r Reverse the current program stack.
1m Call the method on line index 1.
V{ Push the GFV to the bottom of the current stack.
V2*1+ Push the GFV*2+1 to the stack.
\[ ] Pop n, do the stuff in brackets n times.
2m Call the method on line index 2. Note that this is necessary due
to an unknown bug.
:Xru
: Clone the current stack, pushing a second stack to the stack
stack and jumping to it.
X Pop n and discard.
r Reverse the current stack.
u Pop the current stack and concatenate it to the previous.
v&VvD([D\[' 'O]]-H1ml\NaOY
v Pop n, save as a temporary variable.
& Push a new stack to the stack stack and jump to it.
V Push the GFV.
v Push the temp var, clear the temp var memory.
D([ ] If the top item is not zero, do the stuff in brackets.
This is necessary as all loops always apply once.
D\[' 'O] Peek n, output n spaces.
- Pop n, pop o, push o-n.
H Pop n, pop o, push each item of the range from o to n.
1m Call the method at line index 1.
l\N Output all numbers in this stack.
aO Output a newline.
Y Pop and discard the current stack from the stack stack.
```
[Try it online!](http://vitsy.tryitonline.net/#code=VlZIcjFtVntWMioxK1xbMm1dCjpYcnUKdiZWdkQoW0RcWycgJ09dXS1IMW1sXE5hT1k&input=&args=OQ)
] |
[Question]
[
Given a mapping from the integers from 1 to N to the integers from 1 to N, determine if the mapping is surjective, injective, bijective, or nothing.
You may choose any character/digit for the four outputs.
# Specs
Input format: `n, arrays of pairs` (`n` is the highest number in the domain and range)
For example, if the first number is `3`, then both the domain and the co-domain are `{1,2,3}`.
For example, `{i+1 | i from 1 to 9}` (n=10) is represented by `10, [[1,2],[2,3],...,[9,10]]`.
The input **may** contain duplicate.
# Testcases
```
2, [[1,2],[2,1]] => bijective
2, [[1,1],[1,2]] => surjective
3, [[1,1]] => injective
3, [[1,2],[2,3]] => injective
4, [[1,2],[2,2],[3,2],[4,2]] => nothing
2, [[1,2],[1,2]] => injective
3, [[1,1],[1,2],[1,3]] => surjective
2, [[1,1],[1,1],[2,2]] => bijective
```
[Answer]
# Pyth - ~~10~~ ~~9~~ 13 bytes
```
im&{IdqSQSdE2
```
Takes domain and codomain separately as allowed by comments in OP.
[Test Suite](http://pyth.herokuapp.com/?code=im%26%7BIdqSQSdE2&test_suite=1&test_suite_input=2%0A%5B%5B1%2C+2%5D%2C+%5B2%2C+1%5D%5D%0A2%0A%5B%5B1%2C+1%5D%2C+%5B1%2C+2%5D%5D%0A3%0A%5B%5B1%5D%2C+%5B1%5D%5D%0A3%0A%5B%5B1%2C+2%5D%2C+%5B2%2C+3%5D%5D%0A4%0A%5B%5B1%2C+2%2C+3%2C+4%5D%2C+%5B2%2C+2%2C+2%2C+2%5D%5D%0A2%0A%5B%5B1%2C+1%5D%2C+%5B2%2C+2%5D%5D&debug=0&input_size=2).
[Answer]
# Pyth, 15 bytes
```
+!-SQJeC{E*2{IJ
```
The output is identified by:
```
nothing : 0
surjective: 1
injective : 2
bijective : 3
```
In pseudocode,
```
Q=input() # pre-initialized var, 'n'
+ sum( # sur=1,in=2,thus bi=sur+in=3,no=0
! not( # if 'filtrate'=[], true/surjective
-SQ filter(range(1,Q), # filter codomain by range
JeC{E J=transpose(deduplicate(input()))[-1]
)) # find the "redundant" range, may corrspnd to diffrnt args
*2{IJ 2*invariant(J,deduplicate)
) # if J(redundnt range) invariant undr dduplicatn, true/injectiv
```
[Test suite](http://pyth.herokuapp.com/?code=q%2B%21-SQJeC%7BE%2A2%7BIJE&test_suite=1&test_suite_input=2%0A%5B%5B1%2C2%5D%2C%5B2%2C1%5D%5D%0A3%0A2%0A%5B%5B1%2C1%5D%2C%5B1%2C2%5D%5D%0A1%0A3%0A%5B%5B1%2C1%5D%5D%0A2%0A3%0A%5B%5B1%2C2%5D%2C%5B2%2C3%5D%5D%0A2%0A4%0A%5B%5B1%2C2%5D%2C%5B2%2C2%5D%2C%5B3%2C2%5D%2C%5B4%2C2%5D%5D%0A0%0A2%0A%5B%5B1%2C2%5D%2C%5B1%2C2%5D%5D%0A2%0A3%0A%5B%5B1%2C1%5D%2C%5B1%2C2%5D%2C%5B1%2C3%5D%5D%0A1%0A2%0A%5B%5B1%2C1%5D%2C%5B1%2C1%5D%2C%5B2%2C2%5D%5D%0A3&debug=0&input_size=3)
Currently, the test suite returns two False's, namely for case 2 and case -2 (second-to-last). This has to do with the definition of "injective", and will be discussed with the OP.
[Answer]
# Python, ~~85~~ 82 bytes
The methodology here is basically:
* Remove duplicate points
* Check if the cardinality of the image of the domain + cardinality of domain is equal to twice the number of points
+ If true -> injective -> return 1
* Check if the cardinality of the image of the domain is equal to the cardinality of the codomain
+ If true -> surjective -> return 2
* If both true -> bijective -> return 3
* If neither -> nothing -> return 0
```
def f(n,t):l=len;d,c=zip(*set(t));x=l(set(c));return(x+l(set(d))==l(c)*2)+(x==n)*2
```
---
## Test Cases
```
print(f(2, [(1,2),(2,1)])==3)# => bijective
print(f(2, [(1,1),(1,2)])==2)# => surjective
print(f(3, [(1,1)])==1)# => injective
print(f(3, [(1,2),(2,3)])==1)# => injective
print(f(4, [(1,2),(2,2),(3,2),(4,2)])==0)# => nothing
print(f(2, [(1,2),(1,2)])==1)# => injective
print(f(3, [(1,1),(1,2),(1,3)])==2)# => surjective
print(f(2, [(1,1),(1,1),(2,2)])==3)# => bijective
```
---
**Update**
* **-3** [16-05-26] Multiplied by 2 instead of adding
] |
[Question]
[
For this challenge, you need to print out the fingerings for various brass instruments.
The notes an instrument can play (as well as their fingerings) are listed below:
```
Cornet Baritone
Trumpet Bugle French Horn Euphonium Tuba
A#0 0
B0
C1 1234
C#1 134
D1 234
D#1 14
E1 24
F1 4
F#1 23
G1 12
G#1 1
A1 2
A#1 0 0
B1 123 1234 24
C2 13 134 4
C#2 23 234 23
D2 12 124 12
D#2 1 14 1
E2 2 24 2
F2 0 4 0
F#2 123 23 23
G2 13 12 12
G#2 23 1 1
A2 12 2 2
A#2 1 0 0
B2 2 24 12
C3 0 4 1
C#3 23 23 2
D3 12 12 0
D#3 1 1 1
E3 123 2 2 2
F3 13 0 0 0
F#3 23 12 23 23
G3 12 1 12 12
G#3 1 2 1 1
A3 2 0 2 2
A#3 0 1 0 0
B3 123 2 12 12
C4 13 0 1 1
C#4 23 23 2 2
D4 12 12 0 0
D#4 1 1 1 1
E4 2 2 2 2
F4 0 0 0 0
F#4 23 2 23 23
G4 12 0 0 12 12
G#4 1 2 1 1
A4 2 0 2 2
A#4 0 1 0 0
B4 12 2 12
C5 1 0 0 1
C#5 2 23 2
D5 0 12 0
D#5 1 1 1
E5 2 0 2 2
F5 0 0 0
F#5 23
G5 12 0
G#5 1
A5 2
A#5 0
```
# Input
* A single string with a name of an instrument. You can assume the name will always be one of the 7 listed above.
* A note, which can be a single string or a string and integer. You can assume the note will match one of the notes listed above.
# Output
* The fingering for the note on that instrument. This can either be a list of integers (one for each digit), or a single integer.
* If the instrument cannot play a given note (listed as blank above), return `"Impossible"`
# Test Cases
```
Cornet D#3 Impossible
Cornet E3 123
Trumpet G4 12
Trumpet B4 12
Trumpet F#5 23
Bugle F#5 Impossible
Bugle G5 0
Bugle G1 Impossible
French Horn B1 123
French Horn C3 0
French Horn E5 2
French Horn A#5 Impossible
Baritone A#5 Impossible
Baritone A#2 0
Baritone B2 24
Baritone B1 1234
Euphonium F2 4
Tuba A#0 0
Tuba B0 Impossible
Tuba C1 1234
Tuba B1 24
Tuba G#4 1
Tuba B4 Impossible
```
# Notes
* Trumpet and Cornet have the same fingerings, as well as Baritone and Euphonium
* These ranges aren't comprehensive. I've tried to stick to the "standard" notes, but instruments can often go below (pedal notes) or above.
* The notes listed are in concert pitch
* You'll notice that there are a lot of patterns between the fingerings. Finding those patterns is critical to golfing this well.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in your favorite language wins!
[Answer]
# Ruby, 292
```
->i,n{t='nberlu'.index(i[-2])%5
u,v=t<2?[4,24]:[13,123]
a=[]
'!&)+-259>EQR'.tr(?+,t==3??+:?)).bytes{|i|a[i,1]=[0,2,1,12,23,u,v,14,124,234,134,1234]}
p=n[0].ord*13/8%12+n[-1].to_i*12+n.size
p<17&&p-=1
f=a[x='i]udw'[t].ord-p]
('&!-!2'[t]..'QRKK>'[t])===x.chr&&p!=12&&(t<4||1>f)?f:"impossible"}
```
**Explanation**
The table below shows more clearly the similarities and differences between the instruments. Basically, a fingering of 0 corresponds to one of the harmonics of the main tube. Not all harmonics are available on all instruments. For example the French horn is the only one to use the 9th harmonic. Differences are apparent by spaces in the table, or highlighted with `*`
The bugle is simplest and has no valves. The other instruments have at least 3 valves. Valves are used to add bits of tube to the basic instrument to lower the pitch. Valve 2=-1 semitone, Valve 1=-2 semitones, Valve 3=-3 semitones, and valve 4 (if present) is -5 semitones. Valve 4 extends the range of the lower instruments, and is also used as an alternative fingering `4` or `24` for notes which are fingered as `13`or `123` on instruments without a 4th valve.
All the notes from a particular harmonic downwards are fingered in the same way, up until the next harmonic down is reached. The harmonics are quite closely spaced in the upper range, but get sparser in the lower range. At the start of the code a table is built from the highest harmonic downwards by repeatedly inserting a complete set of 12 fingerings into the array. Some fingerings are unused because another harmonic is encountered before the lower fingerings are required. This data is not overwritten, it is pushed to the end of the array, so the end of the array contains a lot of garbage, but this does not matter.
Then all we have to do is transpose the input to the right place on the table and return the fingering. Also, we have to check if the note is in range. Rather than do this with the note itself, I do it with the position in the table of fingerings. This uses a more limited range of values.
```
Corn Bari
Trum Bug HornEuphTuba
No ASC char harmonic
49 0 82 R fundamental (repeat for tuba)
48 0 0 81 Q fundamental (not available on tuba)
47 12341234
46 134 134
45 234 234
44 124
43 14 14
42 123* 123*24 24
41 13* 13* 4 4
40 23 23 23 23
39 12 12 12 12
38 1 1 1 1
37 2 2 2 2
36 0 0 0 0 69 E 2nd harmonic
35 123* 123*24 24
34 13* 13* 4 4
33 23 23 23 23
32 12 12 12 12
31 1 1 1 1
30 2 2 2 2
29 0 0 0 0 0 62 > 3rd harmonic
28 23 23 23 23
27 12 12 12 12
26 1 1 1 1
25 2 2 2 2
24 0 0 0 0 0 57 9 4th harmonic
23 12 12 12 12
22 1 1 1 1
21 2 2 2 2
20 0 0 0 0 0 53 5 5th harmonic
19 1 1 1 1
18 2 2 2 2
17 0 0 0 0 0 50 2 6th harmonic
16 23 23 23 23
15 12 12 12 12
14 1 1 1 1
13 2 2 2 2
12 0 0 0 0 45 - 8th harmonic
11 2* 12 12
10 0* 1 1 43 + 9th harmonic
9 2 2 2
8 0 0 0 41 ) 10th harmonic
7 1 1 1
6 2 2 2
5 0 0 0 38 & 12th harrmonic
4 23 23
3 12 12
2 1 1
1 2 2
0 0 0 33 ! 16th harmonic
```
**commented in test program**
```
#penultimate letter of instrument
range 16th harmonic
#n 0 baritone A#1-F5 A#5
#b 1 tuba A#0-A#4 A#4
#e 2 trumpet,cornet E3-A#5 A#6
#r 3 french horn B1-F5 F5
#l 4 bugle G4-G5 C7
#u 0 euphonium
g=->i,n{
t='nberlu'.index(i[-2])%5 #translate instrument into code above according to penultimate letter of name
u,v=t<2?[4,24]:[13,123] #select fingerings for 4 valve or 3 valve instruments
a=[] #empty fingerings table
'!&)+-259>EQR'. #list of harmonics as ascii codes + =9th harmonic, only on french horn
tr(?+,t==3??+:?)). #if not french horn, delete the + and replace with duplicate of symbol before it )
bytes{|i|a[i,1]= #for each value in the string, insert a complete table of 12 fingerings into a,
[0,2,1,12,23,u,v,14,124,234,134,1234]}#pushing garbage fingerings to the end
p=n[0].ord*13/8%12+ #pitch of note depends on note name
n[-1].to_i*12+n.size #+12*octave number. Length of string is 1 longer for sharp, so add this also.
p<17&&p-=1 #for tuba, consider pitch lowered by 1 if below D#1 to skip over the 124 fingering
f=a[x='i]udw'[t].ord-p] #subtract p from 'i]udw'[t].ord to find x, the position of the fingering in the table. Assign the actual fingering to f
('&!-!2'[t]..'QRKK>'[t])===x.chr&& #if x is in the range for the instrument
p!=12&& #and the note is not B0 (missing for tuba, completely out of range for other instruments)
(t<4||1>f)? #and the instrument is not a bugle (or if it is, the fingering is 0)
f:"impossible" #return the fingering. Otherwise return impossible.
}
[['Cornet','D#3'], #Impossible
['Cornet','E3'], #123
['Trumpet','G4'], #12
['Trumpet','B4'], #12
['Trumpet','F#5'], #23
['Trumpet','A#5'], #0
['Trumpet','B5'], #Impossible
['Bugle','F#5'], #Impossible
['Bugle','G5'], #0
['Bugle','G1'], #Impossible
['Bugle','C4'], #Impossible
['Bugle','G4'], #0
['Bugle','C6'], #Impossible
['French Horn','A#1'], #Impossible
['French Horn','B1'], #123
['French Horn','C3'], #0
['French Horn','E5'], #2
['French Horn','F5'], #0
['French Horn','F#5'], #Impossible
['French Horn','A#5'], #Impossible
['Baritone','A#5'], #Impossible
['Baritone','A#2'], #0
['Baritone','B2'], #24
['Baritone','A1'], #Impossible
['Baritone','A#1'], #0
['Baritone','B1'], #1234
['Euphonium','F2'], #4
['Euphonium','F5'], #0
['Euphonium','F#5'], #Impossible
['Tuba','A#0'], #0
['Tuba','B0'], #Impossible
['Tuba','C1'], #1234
['Tuba','C#1'], #134
['Tuba','D1'], #234
['Tuba','D#1'], #14
['Tuba','B1'], #24
['Tuba','G#4'], #1
['Tuba','A#4'], #0
['Tuba','B4']].each{|c| #Impossible
puts c
puts g[c[0],c[1]]
puts
}
```
] |
[Question]
[
If you have ever travelled with kids more than about 20 minutes, you will have no doubt heard cries of **"Are we there yet?"** and **"How much further?"**
So we play games like *"I Spy"* to help pass the time as the miles go by.
There is a variation on *"I Spy"* whereby instead of spotting arbitrary named things, you must spot integers in strictly ascending order. Numbers are everywhere - licence plates, street names and numbers, street signs, adverts and so on - the list goes on; so this would appear to be a trivial game, so there are some restrictions to make this more challenging\*:
* Each number must be spied in isolation - if the next number you need to spy is 7 and you see house number 17 then this does not count. However license plate 7ABC123 would be OK.
* In general, numbers may be considered "in isolation" if they are separated by any non digit separator, though there are some exceptions
* Fractions cannot be used. For example if you see a road sign saying "Albuquerque ¾ mile" (or even "Albuquerque 3/4 mile") you would not be able to spy either the "3" or the "4"
* Conversely if you see a date written as "3/4/2015" you may spy any of the "3", "4" or "2015"
* Decimals are a bit tricky. If you see "Ford Escort 1.3 litre", the 1.3 here counts a non-integer and the "1" and "3" parts cannot be used in isolation. However if you see "Ford Mustang 5.0 liter", you may spy this as a 5, because even though 5.0 is written as a decimal it is in fact a whole number.
* You may only spy numbers seen outside of the vehicle - so the ascending seconds of a your car's digital clock may not be spied. If you are lucky enough to see such a clock outside of the vehicle, then you may spy those ascending seconds until you can no longer see them (or they wrap to the next minute)
* You may see descending countdown seconds at a pedestrian crossing. Because numbers must be spied in ascending order, you will only be able to spy at most one number per pedestrian crossing.
* Numbers with leading zeros can be spied - for example the "020" in a London phone number would be acceptable as 20.
### Challenge
The kids have already got bored of this game, so they want a program to play it for them. This program must do the following:
* Read input from an unbounded stream. This will most likely be STDIN or equivalent pipe, though (theoretically at least) something like a TCP session could be used. Function parameters or command-line options generally won't work as there will be limits to how much data is passed. However some kind of pointer or reference to an unbounded stream would be OK.
* The input stream will consist of random printable ASCII characters, as generated by `tr -dc '[:print:]' < /dev/urandom` on Linux. The input will generally not have newlines (these are control characters and not printable), so the input will effectively be one unbounded-length line.
* Spy ascending integers appearing in the stream starting at 0. This spying is subject the rules of the game above. In particular:
+ Numbers may only be spied if they are isolated, i.e. separated by non-digits
+ Numbers with leading zeros must be spied
+ No numbers may be spied from a substring `<sep>n/m<sep>`, where `<sep>` is any legal separator other than `/`
+ Decimals of the form `<sep>n.0*<sep>` (where 0\* indicates 0 or more zeros) should be spied, but decimals with non-zero fractional parts should not be spied. Numbers in dotted decimals such as IP addresses where there is more than one `.` should be spied.
* For output, we need to keep track of what we have spied to so far. Every spied number should be output when it is spied. However we don't want to see a long stream of ascending numbers, so each number output must overwrite the previous one in some way. This may be achieved using escape characters, backspaces, output to some kind of textbox or any other method appropriate to your language.
* The program will continue spying until either the input stream ends, or until interrupted by the user (e.g. `CTRL`-c or button click)
* Your counter must be able to count up to at least 2^31-1. Above that, behavior may be undefined.
### Examples
```
0 1 2 3 4 5 6 7 8 9 10 will spy up to 10
0a1b2c3d4e5f6g7h8i9j10 will spy up to 10
10 9 8 7 6 5 4 3 2 1 0 will spy up to 0
0 1 1 1 1 1 2 2 2 2 2 will spy up to 2
00 01 023 4 5 will spy up to 1
0 1 2 3/4 5 will spy up to 2
0 1 2 3/4/2015 5 6 will spy up to 6
0 1 2 3.1415 4 5 6 will spy up to 2
0 1 2 3.000 4 5 6 will spy up to 6
0 1 2 192.168.0.3 4 will spy up to 4
Output from `tr -dc '[:print:]' < /dev/urandom` or equivalent will spy up forever (or until interrupted)
```
---
\*This game is harder than you might think - I tried it yesterday driving through the Bay Area for 2 hours and only got as far as 14.
[Answer]
# sh, 170
```
tr -cs 0-9/. '\n'|
grep -vxEe"[0-9]+/[0-9]+" -e"[0-9]*\.0*[1-9][0-9]*"|
sed -r 's/^([0-9]*)\.0+$/0\1/'|
tr -s /. '\n'|
awk -vORS="\r" '$1==l{l=$1+1;print l-1}END{print "\n"}'
```
] |
[Question]
[
# The obstacle course
You are currently stuck in some kind of course and you have to escape. However, if you do not choose the fastest way then the exit will close in front of you. Your challenge is to find the fastest route in an obstacle course.
**Input**
Your input consists of a list with lists in it, a 2D grid containing only positive integers. For example, it might look as follows:
eg. `[[0,1,2],[0,3,5],[2,6,1]]` which visually looks like:
```
0 1 2
0 3 5
2 6 1
```
Each number represents the time that is needed to pass the location. For example, `(1,2)` takes 6 seconds to pass. Your code can take for granted that no conversions of the input have to be made to make it a list that works with your language.
**Computing**
Your starting position will also be `(1,1)`, which in the input above is 2. You *have to* include those seconds in your final answer. From your starting position your goal is to work to `(xmax, ymax)`, which in the input above is `(3,3)`. You have to find the fastest route to get there, so the sum of your numbers must be minimal.
*Note for example understanding: the grid is from 1 and on-wards, (0,0) is not the starting position. (1,1) is bottom left and (3,3) is top right in this example.*
**Output**
Your code must output the minimal time it takes to reach the top right corner from the bottom left corner. In the input above this is `2 + 0 + 0 + 1 + 2 = 5` seconds. Your code should output nothing else than a whole integer.
**Additional specifications**
* Your may not move diagonally; only left, right, down, up
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins
* The grid wont always be square, but the start will always be connected to the end
* minimum input is a 1x1 grid
* grid will only contain positive integers
To sum up the given example:
```
Input: [[0,1,2],[0,3,5],[2,6,1]] // any format you like
Output: 5
How:
2 + 0 + 0 + 1 + 2 = 5
```
[Answer]
# Matlab, ~~207~~ 199 bytes
Given the matrix with all the times `A`, the idea is using a new `B` matrix that has every entry set to `Inf` except the initial entry. Then we generate a new matrix `C` where we apply following formula to each pair of coordinates `(i,j)`
```
C(i,j) = min( B(i,j), B(i-1,j)+A(i,j), B(i+1,j)+A(i,j), B(i,j-1)+A(i,j), B(i,j+1)+A(i,j) );
```
This means: either B(i,j) already represents the minimum time to get to `(i,j)` or we can get to `B(i,j)` quicker via one of the neighbours.
Then we replace B with C and repeat this step enough times (until nothing changes anymore), and `#rows + #columns` is an upper bound for this.
After that, we just need to print the top right element (or in *matrix-speak*: bottom right) element.
This idea is basically stolen from the Floyd-Warshall algorithm.
Note that for doing this, I need also to consider some technical details, namely that I should not access elements outside the matrix, that is why I need the zero padding and shift of coordinates.
```
a=input('');
[r,c]=size(a);
A=padarray(a,[1,1]);
C=A+Inf;C(2,2)=A(2,2);
for i=1:r+c
B=C;
for i=2:r+1;
for j=2:c+1;
v=[-1,1];
C(i,j)=min([B(i,j)-A(i,j),B(i+v,j)',B(i,j+v)]+A(i,j));
end;
end;
end;
disp(A(r+1,c+1))
```
Input: We need to reverse the order of the rows due to indexing, so the example given would be
```
[[2,6,1];[0,3,5];[0,1,2]]
```
or alternatively
```
[2,6,1;0,3,5;0,1,2]
```
So for this example we get following intermediate steps that will show the progression quite nicely (I removed the padding):
```
2 Inf Inf
Inf Inf Inf
Inf Inf Inf
2 8 Inf
2 Inf Inf
Inf Inf Inf
2 8 9
2 5 Inf
2 Inf Inf
2 8 9
2 5 10
2 3 Inf
2 8 9
2 5 10
2 3 5
```
PS: I love challenges like this one=)
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 8 years ago.
[Improve this question](/posts/55958/edit)
This is a challenge for the people using **Swift 2.0 beta 6**, it's not code golf, but it's a programming puzzle so I'm pretty sure this belongs here. The basic idea is: Make it compile. There are more details and a very nicely formatted playground [at the Github project](https://github.com/Kametrixom/The-Swift-Make-It-Compile-Challenge). Previous challenges are there as well, all set up to tinker. Solutions are included for the previous challenges, as they all have been solved.
## Rules
* You can't modify the given lines
* You can't insert anything between the given lines
* You can't provide custom functions for ones that are in the standard library, according to the syntax-hightlighed picture. This applies to the inverse as well.
* The given lines are not allowed to produce a warning (on default warning settings). However the code you append is allowed to produce warnings.
* The code may or may not crash at runtime, it only has to compile
## The Code
```
func doIt(inout s: D) {
if case self = isUniquelyReferenced(&s),
self.`self` = true where self {
self.`self` = { [unowned x = [self, 7] as Self] n in
print(x + n)
} as () -> ()
}
}
```
## The Picture
[](https://i.stack.imgur.com/SvduO.png)
## Winner
The first one posting an answer that compiles and conforms to all the rules above wins and gets an entry in the projects Hall of Fame.
## EDIT: Hint
Upon submission of [Chris Goldsby](https://twitter.com/GoldsbyChris)'s 99% solution, he received the following hint:
>
> The syntax highlighting of
>
>
>
```
protocol P {
typealias P
var p : P { get }
}
```
[Answer]
I'm posting this answer on behalf of [Chris Goldsby](https://twitter.com/GoldsbyChris) who managed to submit a
# 99% Solution ([Gist](https://gist.github.com/cgoldsby/b4f8a8ccf8550ffbd1a1)):
```
typealias D = NonObjectiveCBase
func ~=(left: Any, right: Bool) -> BooleanType {
return true
}
func +(left: Any, right: Any) -> String {
return ""
}
protocol 🐢: class, BooleanType, ArrayLiteralConvertible {
var `self` : () -> () { get set }
}
extension 🐢 {
typealias Element = Any
internal init(arrayLiteral elements: Any...) {
self.init()
}
//
func doIt(inout s: D) {
if case self = isUniquelyReferenced(&s),
self.`self` = true where self {
self.`self` = { [unowned x = [self, 7] as Self] n in
print(x + n)
} as () -> ()
}
}
//
}
```
Only the snytax highlighting of `D` doesn't match. That's remarkable as it is!
# 100% Solution
EDIT: Two days later he submitted [the following full solution](https://gist.github.com/cgoldsby/20fd0719a18954c8d58d), congrats!:
```
private func ~=(left: Any, right: Bool) -> BooleanType {
return true
}
private func +(left: Any, right: Any) -> String {
return ""
}
protocol Challenge4: class, BooleanType, ArrayLiteralConvertible {
typealias D
var `self` : () -> () { get set }
func doIt(inout s: D)
}
private extension Challenge4 where D == NonObjectiveCBase {
typealias Element = Any
init(arrayLiteral elements: Any...) {
self.init()
}
//
func doIt(inout s: D) {
if case self = isUniquelyReferenced(&s),
self.`self` = true where self {
self.`self` = { [unowned x = [self, 7] as Self] n in
print(x + n)
} as () -> ()
}
}
//
}
```
] |
[Question]
[
A [covering array](http://math.nist.gov/coveringarrays/coveringarray.html) is an `N` by `k` array in which each element is one of {0, 1, ..., v-1} (so `v` symbols in total), and for any `t` columns chosen (so an `N` x `t` array) contains all possible `v^t` tuples at least once. The applications of Covering Arrays range from software and hardware testing, interaction testing, and many other fields. A research question (and which will be a follow-up to this question) is to find the minimal Covering Array of given `t`,`k`,and `v`; an analogue of this would be designing a software system with the minimal number of tests required to test all `t`-way interactions of the system. Only for `t=v=2` is the optimal case known for all `k` (some values of `t` and `v` have some optimal CA designs for one value of `k`, but this is not the common case).
Here, we focus on validation of Covering Arrays, as this is a very time-consuming process for very large Covering Arrays.
**Input:** A file that contains the Covering Array. The format is described in **Scoring** below.
**Output:** `Valid` if the input is a valid covering array, and `Invalid` if it is not.
**Goal:** in any language you want, write a program that validates if the input is a covering array in the *fastest* time. I will run programs on my machine, which is a Mac Pro 3.5 Ghz 6-Core Intel Xeon E5 (2013) with 16 GB RAM (1866 MHz).
**Rules:**
1. Any language is allowed, as long as it can read from a file, where the filename is given as input.
2. All you need to print is `Valid` or `Invalid`, nothing else.
3. No third-party libraries; you can only use the libraries/modules that are already built-in to the language.
4. No use of the Internet for validation (i.e., the validation must be done within the program itself).
5. You are allowed to have multi-threading/multi-core solutions. However, I will test it on the machine described above.
6. If your program requires a compilation, describe in your answer what compilation options that you selected (i.e., like `g++ -O3 validator.cpp ca.5.6^7.txt`).
**Scoring**: the total score is the total amount of time in milliseconds to produce all of the valid outputs. I will test your program against a number of CAs, and it reports the total amount of time required to execute validation of all sample CAs as input. The CAs will be selected from [this link](http://math.nist.gov/coveringarrays/ipof/ipof-results.html) (the text files are provided there, and is linked to from the first link above also).
The format of the files posted there is provided as follows: the first line of the file is `N`, the name of the file is ca.`t`.`v`^`k`.txt, and the next `N` rows of the file contain `k` space-separated integers.
Fastest code (i.e., lowest score) wins!
**Edit**: after looking at some sample covering arrays on the site, the format is not entirely consistent. If you can change (or provide the file) the format to match the format described above, that would be very helpful.
[Answer]
# C, 7.29min for ca.5.4^64.txt on an Intel Core i5-4570 + 8GB ram
### Update: Sometimes gives wrong results
I've compiled it with `gcc -O3 cav.c -o cav`. Simply run it with the CA file's name as first (and only) parameter.
In my case: `./cav ca.2.2^4.txt`
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
int t, v, k, N; /* initial parameters */
uint16_t *ca; /* The CA */
uint16_t *cia; /* Column index array - the columns we selected to compare */
uint8_t *combos;
int num_combos; /* Size of the combo 'hash map' (see compareColumns()) */
int ipow(int base, int exp) /* basic integer pow function 'stolen' from StackOverflow ;) */
{
int result = 1;
while(exp)
{
if(exp & 1)
result *= base;
exp >>= 1;
base *= base;
}
return result;
}
char compareColumns(int base, int child)
{
int pos = base, maxpos = k - child, child_dec = child - 1;
if(child == 0)
{
while(pos != maxpos)
{
cia[child] = pos++;
memset(combos, 0, num_combos);
int rv = 0; /* The offset in the CA for the current row */
int n;
for(n = 0; n < N; n++) /* For every row */
{
int key = 0; /* This is basically a HashMap key, using the same algorithm that you use for accessing 2D data in a 1D array. */
int df = 1; /* Dimension factor - needed for the hash-map-key-like algorithm */
int i;
for(i = 0; i < t; i++) /* For every selected column */
{
key += df * ca[cia[i] + rv]; /* Calculate the key */
df *= v;
}
combos[key] = 1; /* Set the 'boolean' at 'key' in the 'hash map' to 1 */
rv += k;
}
if(memchr(combos, 0, num_combos) != NULL) /* If there are still any 0s (any needed combinations that aren't found), exit immediately! */
return 0;
}
}
else
{
while(pos != maxpos)
{
cia[child] = pos++;
if(!compareColumns(pos, child_dec))
return 0;
}
}
return 1;
}
int main(int argc, char **argv)
{
/* Fetch user input & allocate memory */
sscanf(argv[1], "ca.%d.%d^%d.txt", &t, &v, &k);
FILE *file = fopen(argv[1], "r");
fscanf(file, "%d", &N);
int num_vals = k * N, i;
num_combos = ipow(v, t);
ca = (uint16_t*)malloc(num_vals * sizeof(uint16_t));
cia = (uint16_t*)malloc(t * sizeof(uint16_t));
combos = (uint8_t*)malloc(num_combos * sizeof(uint8_t));
for(i = 0; i < num_vals; i++)
{
int val;
fscanf(file, " %d", &val);
ca[i] = val;
}
fclose(file);
/* The main algorithm implementation */
if(compareColumns(0, t - 1))
printf("Valid!\n");
else
printf("Invalid!\n");
/* Free memory */
free(combos);
free(cia);
free(ca);
return 0;
}
```
I'll try to explain: I'll begin with compareColumns: if it has children (int child), it goes through (allmost) all the columns and kicks off a new call to compareColumns after each step, which itself then walks from the last position of its parent until the end (minus it's own children) of the CA. However, if the function is called with no children (child = 0), it will take all the selected rows and generate something like a hash map key from it. This key will then be used to set a specific cell of the array combos to 1. At the end, it checks if all cells of 'combos' are 1 (i.e. if all combinations appeared at least once). If all cells are 1, it will proceed. If at least one cell is 0, it will abort immediately and print "Invalid!".
[Answer]
**Python solution**
Uses multiprocessing package to test validity of each v-set of columns selected from the input matrix.
Download from [here](https://github.com/jkklapp/covering_arrays_validator).
Run:
`$ python main.py ca.t.v^k.txt`
[Answer]
## [Fantom](http://fantom.org/)
Mostly just a brute force solution, except it does a few preliminary checks ahead of time and uses a binary search to find tuples in each sub-array. I think Fantom optimizes most built in stuff, like the sorts and array manipulations, pretty well under-the-hood. *Note*: Replaces "-" with : "0" for simplicity.
## To Run
Download Fantom from the link in the title, and set up your system variables using instructions [here](http://fantom.org/doc/docTools/Setup).
Save in a file called isCA.fan
run as `fan isCA.fan "pathToFile"`
```
class isCA
{
public static Void main(Str[] args){
Int start := Duration.nowTicks;
//Initialize everything
path := "file:" + args.first
params := path.split(File.sep.chars.first).last.split('.')
t := Int.fromStr(params[1])
params = params[2].split('^')
v := Int.fromStr(params[0])
k := Int.fromStr(params[1])
StrArray := File(Uri.fromStr(path)).in.readAllLines[1..-1]
array := StrArray.map |Str line -> Str[]| {line.replace("- ", "0 ")[0..-2].split(' ').map |Str s ->Int| {Int.fromStr(s)}}
//echo("t: $t\n v: $v\nk: $k")
//Comparison function
compare := |Int[] a, Int[] b -> Int| {
Int i := 0
result := -1
done := false
while(i < a.size - 1 && !done){
if(a[i] != b[i]){
result = a[i] <=> b[i]
done = true
}
i++
if(!done){
return a[i] <=> b[i]
}
}
return result
}
//Basic checks to speed up the Not Valid time
array = array.sort(compare).unique
//Each column contains each value
k.times|Int i|{
vals := Range(0, v, true).toList
array.each |Int[] row|{
vals.remove(row[i])
}
if(!vals.isEmpty){ respond(false, start)}
}
//umm, I guess I'll start with the brute-force method until I think of something better
vals := Range(0,v,true).toList
tuples := permutations(vals)
temp := [,]
t.times{ temp.add(1)}
(k - t).times{ temp.add(0) }
colBins := permutations(temp).unique
colBins.each |Int[] bin| {
//Construct columns
smallArray := array.map |Int[] row -> Int[]|{
r := [,]
row.each |Int a, Int index|{ if(bin[index] == 1){r.add(a)}}
return r
}
tList := tuples.dup
Int cols := t
//Binary search the array
while(cols >= v){
smallArray.sort(compare)
found := [,]
tList.each|Int[] tuple, Int index|{
Int find := smallArray.binarySearch(tuple, compare)
//echo("Found $tuple at $find in $smallArray")
if(find >= 0){found.add(index)}
}
//Remove first col and try again
smallArray = smallArray.map|Int[] a -> Int[]| {return a[1..-1]}
cols--;
//ignore tuples we already found
tList = tList.findAll|Int[] list, Int index -> Bool| {!found.contains(index)}
}
if(!tList.isEmpty){
echo("Cols $bin does not contain $tList")
respond(false, start)
}
}
respond(true, start)
}
private static Void respond(Bool b, Int start){
if(b) echo("Valid")
else echo("Not Valid")
echo("Time: " + (Duration.nowTicks() - start))
Env.cur.exit
}
private static Int[][] permutations(Int[] a){
result := [,]
recurse([,], a, result)
return result
}
private static Void recurse(Int[] pre, Int[] a, Int[][] results){
//echo("Recursing $pre\nwith $a")
if(a.isEmpty) {
results.add(pre)
return
}
for(Int i := 0; i < a.size; i++){
d := a.dup
d.removeAt(i)
recurse(pre.dup.add(a[i]), d, results )
}
}
}
```
] |
[Question]
[
You should write a program or function which given a text as input outputs or returns the sum of the following three integers:
* Number of lowercase `x`'s which are not part of a cross-formation.
* Number of uppercase `X`'s which are not part of a cross-formation.
* Number of cross-formations which are made of neither `x` nor `X`.
A cross-formation is 5 copy of the same character positioned to each other in the following manner:
```
A A
A
A A
```
Cross-formations can overlap with each other.
Detailed example
```
Input:
x-x+x+X++
-x-x+x++asd
x-x+x+X+
Info:
There is 1 x and 2 X's not in cross-formation and
there are 2 cross-formations of +'s as shown here:
+ +X+
+x+
+ +X+
Output:
5
```
## Input
* A string containing only printable ascii characters (codepoint 32-126) and newlines.
* The string will contain at least one printable character.
## Output
* A single positive integer, the sum of the number of occurrences for the three property.
## Examples
After each output the values of the 3 properties (`x`'s, `X`'s and crosses) are provided in parens but note that those are not part of the output.
```
Input:
a
Output:
0 (0,0,0)
Input:
x xxx
X x
x xxx
Output:
5 (4,1,0)
Input:
########
#####
########
Output:
4 (0,0,4)
Input:
a-a-a
0a0a
a-a-axXxX
0a0a
a-a-a
Output:
9 (2,2,5)
Input:
a c efghi
ab defgh
a c e ghij
abcd fgh
abc e g
Output:
2 (0,0,2)
Input:
/\/\/\/\/\/\/\
\/\/\/\/\/\/\/
#####x-x+x+X++
#####-x-x+x++###XX
#####x-x+x+X+
/\/\/\/\/\/\/\
\/\/\/\/\/\/\/
Output:
10 (1,4,5)
Input:
xxxxxxxxxx
xxxxxxxXX
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxx
Output:
5 (3,2,0)
```
This is code-golf so the shortest entry wins.
[Answer]
# JavaScript (ES6) 234 ~~246~~
Longer than I expected ...
Run snippet to test (in Firefox)
```
// Golfed
F=t=>t.split('\n').map((r,j,t)=>(
[...r].map((c,i)=>(
f=c==r[i+2]&c==u[i+1]&c==v[i]&c==v[i+2],
c!='x'&c!='X'?z+=f
:(++z,f?k[j+[,i]]=k[2+j+[,i]]=k[1+j+[,i+1]]=k[j+[,i+2]]=k[2+j+[,i+2]]=1:0)
)),v=u,u=r),
k={},u=v=z=0)&&z-Object.keys(k).length
// Ungolfed
U=t=>{
var k={}, u=0,v=0,z=0, t=t.split('\n')
t.forEach((r,j)=> {
[...r].forEach((c,i)=> {
x = c=='x'|c=='X' // is any X
f = c==r[i+2] & c==u[i+1] & c==v[i] & c==v[i+2] // is in a formation
if (x)
{
++z
if (f)
{ // remember the position of X involved in a formation, avoid counting duplicates more tha once
k[j+[,i]]=k[2+j+[,i]]=k[1+j+[,i+1]]=k[j+[,i+2]]=k[2+j+[,i+2]]=1
}
}
else
{
z+=f
}
})
v=u,u=r
})
return z-Object.keys(k).length
}
// TEST
Out=s=>OUT.innerHTML=OUT.innerHTML + s;
['a','a a\n a\na a','x xxx\n X x\nx xxx', 'x-x+x+X++\n-x-x+x++asd\nx-x+x+X+'
,'########\n#####\n########','a-a-a\n0a0a\na-a-axXxX\n0a0a\na-a-a'
,'a c efghi\nab defgh\na c e ghij\nabcd fgh\nabc e g'
,'/\\/\\/\\/\\/\\/\\/\\\n\\/\\/\\/\\/\\/\\/\\/\n#####x-x+x+X++\n#####-x-x+x++###XX\n#####x-x+x+X+\n/\\/\\/\\/\\/\\/\\/\\\n\\/\\/\\/\\/\\/\\/\\/'
,'xxxxxxxxxx\nxxxxxxxXX\nxxxxxxxxxx\nxxxxxxxxxx\nxxxxxxxxxx\nxxxxxxxx']
.forEach(t=>Out(t+'\n<b>'+F(t)+'</b>\n\n'))
```
```
b { color: #00f }
```
```
<pre id=OUT></pre>
```
[Answer]
## C (562 b)
---
**Golfed Code:**
```
int main(){wchar_t *q,*y,*w,*b,a[50][50];int l,c,t,i,j,u,v,h,s,x,r;l=c=i=0;do l=(t=wcslen(q=_getws(a[i++])))>l?t:l;while(t);for(j=0;j/l<i-1;j++)c+=(x=((t=*(b=a[u=j/l]+(v=j%l)))==120|t==88|t==344|t==376))&(s=(((t&(h=0xff))!=(*(b+2)&h))|((t&h)!=(*(w=a[u+1]+(v+1))&h))|((t&h)!=(*(y=a[u+2]+v)&h))|((t&h)!=(*(y+2)&h))))?(t==(t&h)):(x?0*(*b=*(b+2)=*w=*y=*(y+2)=(t+256)):(((t&h)==(*(b+2)&h))&((*w&h)==(*y&h))&((*(y+2)&h)==(*y&h))&((*y&h)==(t&h))?(r=(t==(t&h))+(*(b+2)==(t&h))+(*w==(t&h))+(*y==(t&h))+(*(y+2)==(t&h)))+0*(*b=*(b+2)=*w=*y=*(y+2)=t+256):0));printf("%d",c);}
```
**unpacked Code:**
```
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main(){
wchar_t *q,*y,*w,*b, a[50][50];int l,c,t,i,j,u,v,h,s,x,r;l=c=i=0;
do
l=(t=wcslen(q=_getws(a[i++])))>l?t:l;
while (t);
for(j=0;j/l<i-1;j++)
c+=(x=((t=*(b=a[u=j/l]+(v=j%l)))==120|t==88|t==344|t==376 ))&(s=(((t&(h=0xff))!=(*(b+2)&h))|((t&h)!=(*(w=a[u+1]+(v+1))&h))|((t&h)!=(*(y=a[u+2]+v)&h))|((t&h)!=(*(y+2)&h))))?(t==(t&h)):(x?0*(*b=*(b+2)=*w=*y=*(y+2)=(t+256)):(((t&h)==(*(b+2)&h))&((*w&h)==(*y&h))&((*(y+2)&h)==(*y&h))&((*y&h)==(t&h))?(r=(t==(t&h))+(*(b+2)==(t&h))+(*w==(t&h))+(*y==(t&h))+(*(y+2)==(t&h)))+0*(*b=*(b+2)=*w=*y=*(y+2)=t+256):0));
printf("%d",c);getch();
}
```
] |
[Question]
[
# The Setup
Most of us are familiar with crossword numbering, which follows three basic rules:
1. in a character grid consisting of blacks and whites (see below), any maximal contiguous horizontal or vertical chain of whites with length ≥ 2 is considered a word
2. any white at the leftmost end of a horizontal word and/or at the topmost end of a vertical word is called a "starter"
3. starters are assigned numbers (sequential integers starting with 1) scanning through the grid in standard English reading order (starting at the top left of the grid, scanning right-fast, down-slow to the bottom right of the grid)
A "crossword" generally refers to any *n*-by-*n* square grid of blacks and whites, with *n* ≥ 2, containing at least one black and at least one word, and containing no whites that do not belong to at least one word.
Some additional properties that a crossword may or may not possess:
* a crossword is called **singly connected** if every white in the grid can be connected to every other white in the grid by moving north, east, south, and west (not diagonally) along a path consisting entirely of whites
* a crossword is called **proper** if every white belongs to exactly two words (one horizontal, one vertical)
* a crossword is called **symmetric** if for all *x* = 1..*n*, *y* = 1..*n*, the grid cell at (*x*,*y*) is a white if and only if the grid cell at (*n*+1-*x*,*n*+1-*y*) is a white, given 1-based indexing
Most run-of-the-mill cryptic crosswords are singly-connected and symmetric, but not proper. Many newspaper crosswords are proper, singly-connected, and symmetric.
The figure below also shows a proper, singly-connected, symmetric crossword.
```
Crossword
w/o #s w/ #s (mod 10)
################## 12##################
# ###### #### 3 45#678######90####
# #### 1 2 #34567 ####
### ###### 8 ###9 ######
## #### #### ##0 123####456####
# # ## ## #7 #8 ##90 12##
## ## # 3 ##4 ##5 #6 78
#### ##### 9 ####0 #####1
# ## #### ## #234##5 67####8 ##
# # ## ### #9 01 #2 ##34 ###
### ## # # ###5 ##6 7#8 90#
## #### ## # ##1 ####2 3 ##4 #
##### #### 56 7#####8 ####90
# ## ## 1 #23##4 5##6
## ## # # ##7 8 ##9 #0 #
#### #### ## ####1 ####2 3 ##
###### ### ######45678###9 01
#### # ####23 #45
#### ###### # ####6 ######7 #8
################## ##################9
```
# The Problem
...other than finding a crossword puzzle challenge [that hasn't already been done](https://codegolf.stackexchange.com/questions/tagged/crossword). :P
Recall the [crossword numbering](https://codegolf.stackexchange.com/questions/318/crossword-numbering) challenge from days of yore, which accepts a crossword as input and produces clue numbering as output. Here we consider its younger (and significantly harder) cousin by reversing input and output:
*Given a series of across/down clue numbers, generate a crossword puzzle whose numbering (per the canonical rules) yields these clue numbers.*
For example, consider the clue numbers as input:
**Across** `3,5,6,7,8,9` **Down** `1,2,3,4,5,A`
Two crosswords with compliant numbering are:
```
A B
6x6 7x7
w/o #s w/ #s w/o #s w/ #s
______ ______ _______ _______
|## # #| |##1#2#| |#######| |#######|
|# | |#3 4| |# ## ##| |#1##2##|
| ## | |5 ##6 | |# # # | |# #3 #4|
| ## | |7 ##8 | | # # | |5 #6 # |
| #| |9 A #| | # # | | #7 #8 |
|# # ##| |# # ##| | ## ##| |9 ##A##|
¯¯¯¯¯¯ ¯¯¯¯¯¯ |#### ##| |#### ##|
¯¯¯¯¯¯¯ ¯¯¯¯¯¯¯
```
Solution **A** is singly-connected and symmetric, while **B** is neither. Solution **A** is also notably more compact, having only 14 blacks, while solution **B** has 29 blacks.
Note that you do not need to worry about what letters could/would go into any whites. This challenge is purely geometric in nature.
There are of course many trivial ways of generating compliant crosswords, which takes us to the interesting matter of...
# Scoring
[This 600-textline file](http://pastebin.com/6RsNXcTX) contains 300 sets of across/down clue numbers for crosswords in the format
>
> [across clue numbers for set 1, separated by spaces]
>
> [down clue numbers for set 1, separated by spaces]
>
> [across clue numbers for set 2, separated by spaces]
>
> [down clue numbers for set 2, separated by spaces]
>
>
> ...
>
>
> [across clue numbers for set 300, separated by spaces]
>
> [down clue numbers for set 300, separated by spaces]
>
>
>
Your objective is to write a program that generates a valid crossword for each set of across/down clue numbers and computes the resulting number of blacks.
The program should produce all 300 crosswords in 30 minutes or less running on a [modern computer](http://www.iit.edu/ots/computer_vendor_info.shtml).
By setting a constant in the program or passing a command line argument, the program should be able to output the crossword grid (solution) for the *k*th input set given *k* ∈ 1..300, and you should display representative output (the black/white grid) for at least *k* = 1 and *k* = 300 along with your answer. The output can be text- or graphics-based, with or without clue numbers shown (preferably *with*, mod 36 for text-based graphics), and with any embellishments you desire. (This is simply for validation and showmanship.)
The output should also indicate whether the crossword is proper, singly-connected, and/or symmetric.
Your program's score is the sum total number of blacks over all 300 solutions. **The program that produces the lowest total number of blacks is the winner.**
## per-crossword Bonuses
For any of the 300 crosswords (solutions) generated by your program:
* if a crossword is **proper**, multiply its black count by **0.6**
* if a crossword is **singly connected**, multiply its black count by **0.85**
* if a crossword is **symmetric**, multiply its black count by **0.75**
* if **any two** of the above conditions apply for a crossword, multiply its black count by **0.4**
* if **all three** of the above conditions apply for a crossword, multiply its black count by **0.25**
You may only claim one bonus per crossword.
The score for each crossword should be rounded up to the nearest integer.
Note that all of the input sets in the problem correspond to randomly-generated small(ish) singly-connected, proper, symmetric crosswords, hence I guarantee the existence of at least one such a solution.
Feel free to raise any questions or concerns in the comments section.
Happy crosswording. :)
[Answer]
## Python, total score 127,634(!)
This was a good excercise in humility. The score claimed above is using a fairly naive construction algorithm. I also tried implementing a slightly optimized brute force search, but while this managed to solve a few of the smaller crosswords in the 1-100 range (13x13 or less) it struggled with most and had no chance with the larger ones.
## Crossword class
Nothing fancy here...
```
import itertools
import math
import copy
import sys
def read_crosswords(filename):
crosswords = []
with open(filename, 'r') as f:
for across, down in zip(f, f):
alist = list(map(int, across.rstrip().split()))
dlist = list(map(int, down.rstrip().split()))
crosswords.append(XWord(alist, dlist))
return crosswords
def solve_crosswords(filename, solver, display=()):
crosswords = read_crosswords(filename)
total_score = 0
for x, i in zip(crosswords, itertools.count(1)):
print("Crossword {0}... ".format(i), end="")
sys.stdout.flush()
assert(solver(x))
score = x.score(); details = ["score = {0}".format(score)]
if x.is_symmetric(): details.append("symmetric")
if x.is_proper(): details.append("proper")
if x.is_connected(): details.append("connected")
print("done! ({0})".format(", ".join(details)))
if i in display: x.print_grid()
total_score += score
print("Total score: {0}".format(total_score))
return crosswords
def flood_fill(grid, x, y, colorA, colorB):
if grid[x][y] != colorA: return
grid[x][y] = colorB
flood_fill(grid, x-1, y, colorA, colorB)
flood_fill(grid, x+1, y, colorA, colorB)
flood_fill(grid, x, y-1, colorA, colorB)
flood_fill(grid, x, y+1, colorA, colorB)
class XWord:
B,W,U = range(3)
def __init__(self, across, down):
self.grid = [] # grid (2D array with black border)
self.n = 0 # grid size (excluding border)
self.num_clues = max(across + down) # number of clues
self.across = [(i+1) in across for i in range(self.num_clues)] # acrossness bool array
self.down = [(i+1) in down for i in range(self.num_clues)] # downness bool array
def print_grid(self, numbers=True):
"""Print the grid."""
i = 1
for y in range(1,self.n+1):
for x in range(1,self.n+1):
if self.grid[x][y] == XWord.B: print("#",end="")
elif self.grid[x][y] == XWord.W:
across = (self.grid[x-1][y] == XWord.B) and (self.grid[x+1][y] == XWord.W)
down = (self.grid[x][y-1] == XWord.B) and (self.grid[x][y+1] == XWord.W)
if numbers and (across or down):
print("{0}".format(i % 10), end="")
i += 1
else: print(" ", end="")
else: print("?", end="")
print()
def is_symmetric(self):
"""Whether the grid is symmetric."""
for y in range(1,self.n+1):
for x in range(1,self.n+1):
if self.grid[self.n+1-x][self.n+1-y] != self.grid[x][y]:
return False
return True
def is_proper(self):
"""Whether the grid is proper."""
for y in range(1,self.n+1):
for x in range(1,self.n+1):
if self.grid[x][y] == XWord.W:
if not ((self.grid[x-1][y] == XWord.W or self.grid[x-1][y] == XWord.W) or
(self.grid[x][y-1] == XWord.W or self.grid[x][y+1] == XWord.W)):
return False
return True
def is_connected(self):
"""Whether the grid is connected."""
grid = copy.deepcopy(self.grid); filled = False
for y in range(1,self.n+1):
for x in range(1,self.n+1):
if grid[x][y] == XWord.W:
if not filled:
flood_fill(grid, x, y, XWord.W, XWord.B)
filled = True
else:
return False
return True
def score(self):
"""The grid score."""
blacks = 0
for y in range(1,self.n+1):
for x in range(1,self.n+1):
if self.grid[x][y] == XWord.U:
raise Exception("Incomplete grid!")
elif self.grid[x][y] == XWord.B:
blacks += 1
symmetric = self.is_symmetric()
proper = self.is_proper()
connected = self.is_connected()
if (symmetric and proper and connected): multiplier = 0.25
elif (symmetric and (proper or connected) or proper and connected): multiplier = 0.4
elif proper: multiplier = 0.6
elif symmetric: multiplier = 0.75
elif connected: multiplier = 0.85
else: multiplier = 1.0
return int(math.ceil(float(blacks) * multiplier))
```
## Naive solver
This generates a height two sequence, splits it into sections and wraps it round to fill the smallest possible square. Across clues are extended as far as possible to minimize blacks, but other than that there's not much cleverness. The solutions are never connected or proper and in practice never symmetric.
```
class XWord:
def simple_solver(self):
"""Naive solver. Converts to a height 2 sequence and wraps round."""
# generate a string sequence that we'll expand later
# a=start across, b=start both, c=continue across, d=start down, _=optional space, =space
seq = []
for a,d in zip(self.across, self.down):
if a:
if len(seq) > 0:
if seq[-1] in "ab": seq.append("c")
seq.append(" ")
seq.append("a" if not d else "b")
else:
if len(seq) > 0:
if seq[-1] in "bd": seq.append("_")
seq.append("d")
if len(seq) > 0 and seq[-1] in "ab": seq.append("c")
# fit sequence into a square with grid size 3n-1 for minimal n
n = 0; rows = seq
while len(rows) > n:
n += 1; x = 0; rows = []
while x < len(seq):
if seq[x] in "_ ": x+=1
y = min(x+3*n-1,len(seq))
if seq[y-1] in "ab": y-= 1
rows.append("".join(seq[x:y]).rstrip(" _"))
x = y
# generate grid
self.n = 3*n-1
self.grid = [[XWord.B for i in range(self.n+2)] for j in range(self.n+2)]
y = 1
for row in rows:
x = 1; across = False
for s in row:
if s in "abcd" or across and s in "_": self.grid[x][y] = XWord.W
if s in "bd": self.grid[x][y+1] = XWord.W
if s in "ab": across = True
x += 1
for x in range(x,self.n+1):
if across: self.grid[x][y] = XWord.W
y += 3
return True
```
This runs almost instantaneously and generates an amusingly high score.
```
>>> solve_crosswords('crossword.txt', XWord.simple_solver,[1,300])
Crossword 1... done! (score = 121)
1 2#3 4#5 6 7
# # # # # # #
##############
8#9#01#2 #3
# ## #### ###
##############
4 #56#7 #8 9 0
#### #### # #
##############
1#2#3 #4 #56
# ######## ##
##############
7 8 9#0 #1 #2
# # #########
Crossword 2... done! (score = 192)
Crossword 3... done! (score = 203)
...
Crossword 299... done! (score = 666)
Crossword 300... done! (score = 645)
1 2#3 4 5 6#7 8#90 1 2 3#45 6 7
# # # # # # # ## # # # ## # # #
################################
8 9#0 1 2#34#5 #6 #7 #8 9#0 #1
# # # # ## ########## # #### ##
################################
2 #34#56#7 #89 0 1#23#45#6 #7
#### ## ##### # # ## ## # ######
################################
89#0 #1 2#34#5 #6 #7 #8 9#0 #1 2
# #### # ## ########## # #### #
################################
3#4#56 7 8 9 0 1 2 3 4#56 7 8#9
# ## # # # # # # # # ## # # ###
################################
0 #1 #2 #3 #4 #5 6#7 #8 9#0 1 2
############### # #### # # # # #
################################
3 4#5 6#78#90 1 2#3 #4 #5 #6 #7
# # # ## ## # # ############# #
################################
8 9#0 1 2 3 4#5 #6 #78#9 0 1 2
# # # # # # ######## # # # # ##
################################
3 #45#67#89#0 #12#34 5#6 #7 #8
### ## ## ##### ## # ##########
################################
9 #01 2 3 4#5 6#7 #8 #9 #0 #1 2
#### # # # # # #### ######## # #
################################
34 5#6 #7 #8
# # ############################
Total score: 127634
```
## Slow solver
The brute force solver traverses the grid square by square and decides at each point whether to start new clues, continue existing clues or block clues. Before continuing, it confirms that this choice is compatible with the current view of the grid. There are a number of other optimizations applied whenever we know that the grid is symmetricm, proper or connected.
* **Symmetric**: we apply all updates symmetrically and check halfway that half of the across clues and at least half of the overall clues have been processed.
* **Proper**: we check for properness whenver we update the grid.
* **Connected**: we disallow a completely black row.
Note that there's even a bit of overoptimisation: we currently disallow proper crosswords that begin with a black row, though strictly these are allowed (though I'm not sure they should be). Also, we allow the user to specify the maximum number of black squares to look for to speed up the search.
```
class XWord:
def slow_solver(self, n, symmetric=False, proper=False, connected=False, max_blacks=None):
"""Brute force solver with some optimizations. Too slow for much more than 10x10."""
def _slow_solve(x, y, alist, dlist, updates, all_black_row, max_blacks):
found = True
# Early exits
if connected and x == 1:
if all_black_row: return False
else: all_black_row = True
if symmetric and x == 1:
if y == self.n // 2 + 1:
self.across_halfway = self.across.count(True) - alist.count(True)
if alist.count(True) < self.across_halfway: return False
if y == (self.n + 1) // 2 + 1:
if 2 * len(alist) > self.num_clues: return False
if alist.count(True) != self.across_halfway: return False
# Apply updates and detect more inconsistencies
undo = []
for (i,j,C) in updates:
# update square
if self.grid[i][j] == C:
pass
elif self.grid[i][j] == XWord.U:
self.grid[i][j] = C
if C == XWord.B: max_blacks -= 1
undo.append((i,j))
else:
found = False # inconsistent
break
if proper and C == XWord.W:
if self.grid[i-1][j] == XWord.B and self.grid[i+1][j] == XWord.B or \
self.grid[i][j-1] == XWord.B and self.grid[i][j+1] == XWord.B:
found = False
break
elif C == XWord.W:
if self.grid[i-1][j] == XWord.B and self.grid[i+1][j] == XWord.B and \
self.grid[i][j-1] == XWord.B and self.grid[i][j+1] == XWord.B:
found = False # lone black square
break
# update mirror image
if symmetric and (i != self.n+1-i or j != self.n+1-j):
if self.grid[self.n+1-i][self.n+1-j] == C:
pass
elif self.grid[self.n+1-i][self.n+1-j] == XWord.U:
self.grid[self.n+1-i][self.n+1-j] = C
if C == XWord.B: max_blacks -= 1
undo.append((self.n+1-i,self.n+1-j))
else:
found = False
break
# Are we finished?
if found:
if y > self.n and len(alist) == 0: return True
elif y > self.n or max_blacks < 0: found = False
# Select next square type and recurse
if found:
nextx = x + 1; nexty = y
if nextx > self.n: nextx = 1; nexty += 1
found = len(alist) > 0 and _slow_solve(nextx, nexty, alist[1:], dlist[1:], self._start_clue_updates(x, y, alist[0], dlist[0]), False, max_blacks)
found |= _slow_solve(nextx, nexty, alist, dlist, self._continue_clue_updates(x, y), False, max_blacks)
found |= _slow_solve(nextx, nexty, alist, dlist, self._block_clue_updates(x, y), all_black_row, max_blacks)
# Undo updates on error
if not found:
for (i,j) in undo:
self.grid[i][j] = XWord.U
return found
# in future, this should try a few values of n until we get one that works.
self.n = n
self.grid = [[XWord.U if (0<i<self.n+1) and (0<j<self.n+1) else XWord.B for j in range(self.n+2)] for i in range(self.n+2)]
if max_blacks is None:
max_blacks = self.n * self.n - 2 * max(self.across.count(True), self.down.count(True))
found = _slow_solve(1, 1, self.across, self.down, [], False, max_blacks)
return found
def _start_clue_updates(self, x, y, across, down):
updates=[(x, y, XWord.W)]
if across:
updates.insert(0,(x-1, y, XWord.B))
updates.append((x+1, y, XWord.W))
elif self.grid[x-1][y] == XWord.B:
updates.insert(0,(x+1, y, XWord.B))
if down:
updates.insert(0,(x, y-1, XWord.B))
updates.append((x, y+1, XWord.W))
elif self.grid[x][y-1] == XWord.B:
updates.insert(0,(x, y+1, XWord.B))
return updates
def _continue_clue_updates(self, x, y):
updates=[(x, y, XWord.W)]
if self.grid[x-1][y] == XWord.B:
updates.insert(0,(x+1, y, XWord.B))
updates.append((x, y-1, XWord.W))
elif self.grid[x][y-1] == XWord.B:
updates.insert(0,(x, y+1, XWord.B))
updates.append((x-1, y, XWord.W))
return updates
def _block_clue_updates(self, x, y):
updates=[(x, y, XWord.B)]
return updates
```
Unfortunately this is too slow to solve all but a few of the smaller crosswords in the puzzle file.
```
>>> xs = read_crosswords('crossword.txt')
>>> xs[0].slow_solver(13,True,True,True)
True
>>> xs[0].print_grid()
#12##########
3 4#56789###
0 1 ###
##2 ####
#3 #4 ####
#5 6 ####
#####7 #####
####8 9012#
####3 #4 #
####5 6 ##
###7 89
###0 #1
##########2 #
>>> xs[0].score()
18
```
] |
[Question]
[
Your task is to take as input an English noun and output its plural. To win the challenge you must trade off code length against accuracy.
Entries will be scored according to this comma-separated list of [95642 English nouns and their plurals](https://gist.github.com/anonymous/2e26552ad78d29489bd9). Your score is the length of your code in bytes, **plus** the number of nouns in this file that it does **not** correctly pluralise. If you manage to correctly pluralise every single line in the file then you may apply a **50% bonus**. (I don't expect anyone to claim this, but you never know.) The lowest score wins.
Every line in the file consists of a word composed of letters `[a-z]`, followed by `,`, followed by the plural, which is also composed of letters `[a-z]`.
Please note that the data in the file is pretty terrible. It was scraped from Wiktionary using someone else's script. There are duplicates, there are things that are not real words, and there are entries that are clearly completely wrong. But none of this matters from the point of view of the challenge. The goal is to produce a program that will correctly reproduce the plurals *as written in this file*; their correspondence or otherwise to correct English plurals is irrelevant. Also please note that, like any dictionary, the provided file contains its fair share of offensive terms.
Input and output may be performed in any way you find convenient. (Function parameters, command-line input, etc.)
To evaluate your score you will probably need to write some testbed code that iterates over the provided file. Please include this in your answer. This code need not be in the same language as your pluralising program, and should not be golfed. (It should be readable, so we can verify that it works.)
A useful tip: while developing your code, you will probably find it helpful to modify your testbed code so that it prints out every line for which your function fails. That way you can easily see which additional cases you need to consider.
**Illustrative examples**
the Python code
```
def p(a):
return a+'s'
```
is 24 bytes. However, if we run it through the following evaluation function
```
def testPlural(func):
badLines = 0
with open("simpleNouns.csv") as file:
for line in file:
noun, plural = line.rstrip().split(',')
if plural != func(noun):
badLines += 1
return badLines
```
then we can see that it fails in 11246 cases, giving a score of 24 + 11246 = **11270**.
However, if we update the function to
```
import re
def p(a):
a+='s'
return re.sub('ys$','ies',a)
```
then its length has increased to 58 bytes, but it now fails in only 7380 cases, giving a score of 58 + 7380 = **7438**.
[Answer]
I'll start us out with something simple.
# Javascript 232+2730=2962
```
w=prompt();r="ay,ays;ey,eys;oy,oys;y,ies;us,i;um,a;is,es;x,xes;man,men;s,ses;sh,shes;ch,ches;z,zes".split(";");for(i=0;i<r.length;i++){b=r[i].split(",");if(w.slice(-b[0].length)==b[0])return w.slice(0,-b[0].length)+b[1];}alert(w+"s")
```
Uses a small list of replacement rules. Fails 2730 test cases out of 95642.
[Answer]
## Python, 262+2606 = 2868
Small improvement over Peter Olson's answer. Perhaps can be better reimplemented in other language.
```
import re
def p(n):
s=n
for a in r'fe;ves lf;lves ([iln])um;\1a ([cgil])us;\1i (?<![ar])is;es man;men ea;eae (?<!f)ix;ices ((?<!k)s|x|sh|ch|z|j);\1es ((?<=.)[^aeiou])y;\1ies (?<!s);s'.split():
b,c=a.split(';')
n=re.sub(b+'$',c,n)
if n!=s:break
return n
```
] |
[Question]
[
A station model is a diagram for recording the weather at a certain place and time.
# Challenge
You must write the shortest code possible to graphically output a simplified (explained later) station model.

# Ticks
A tick is a line on the wind barb. A 50 knot tick is a triangle. A 10 knot tick is a line. A 5 knot tick is half the length of a 10 knot tick. The windspeed is indicated by summing the ticks, using the largest value symbols whenever possible. The ticks start at the end of the line and are arranged in descending order of size toward the circle. An exception is 5 knots, where the tick is placed a short distance away from the end (to avoid ambiguity with 10 knots.)
Here is some pseudocode to calculate the ticks required
```
set f=int(s/5)
set t=int(f/2)
f=f-(t*2)
set ft = int(t/5)
t=t-(ft*5)
```
Where f is the number of 5 knot ticks, t is the number of 10 knot ticks and ft is the number od 50 knot ticks. (This rounds down to the nearest 5, but your code should round up or down, whichever is nearer.) Note that there is only ever one 5 knot tick.
# Other
You may only display two things on your station model: wind speed and direction. These must be supplied by the user: hardcoding is not permitted. The wind speed must be a positive integer in knots while the wind direction must be in letters (e.g. NNE, W, ESE). 16 points of the compass will be considered (up to three letters.) See <http://en.wikipedia.org/wiki/Points_of_the_compass>
The 50 knots tick must be as in the picture above.
Set cloud cover to clear (the circle must be empty.)
The highest wind speed allowed is 201 knots (round it to 200).
Since the wind ticks only increase in imcrements of 5, round all wind speeds to the nearest 5.
As always, since this is code golf, the shortest code wins.
# Examples
All of the following have a cloud cover of clear.

20 knots, SW (225°)

15 knots, N (0°)
# Test cases
50 knots, NNE
0 knots
12 knots S
112 knots WNW
[Answer]
# BBC BASIC, 273 ASCII characters (not golfed yet)
Emulator at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html>
Parsing the direction is a dirty hack. I simply take a walk through a cartesian grid for each letter input. They aren´t echoed to the screen, and the input is terminated when a space is received.
As this is codegolf, I don't bother to normalise the direction vector. Therefore the size of the symbol drawn is dependent on the number of characters input. The proportions are the same for all inputs, however. Also, for the 3-letter inputs the angle is 4 degrees closer to the diagonal than it should be. For example, NNE is atan(0.5)=26.57 degrees instead of the correct 22.5 degrees, but it is barely noticeable. Both these points could be corrected for about 20-30 characters.
After the direction, the speed is input (this is echoed to the screen and terminated with a newline.)
```
x=0
y=0
REPEAT
d=GET :REM get character from keyboard
x+=(d=87)-(d=69) :REM d=87 evaluates to -1 if "W", d=69 is -1 if "E"
y+=(d=83)-(d=78) :REM d=83 evaluates to -1 if "S", d=69 is -1 if "N"
UNTILd=32
x*=20 :REM boost the sizes of x and y
y*=20 :REM normalization code would go here
INPUTs
s=INT(s/5+.5) :REM divide s by 5 and round to nearest int. 50-tick=10, 10-tick=2, 5-tick=1
MOVE600,500 :REM move to centre of circle
PLOT145,x,y :REM draw circle centred at 600,500 with 600+x,500+y on its edge. cursor remains at the latter position.
IFs=0END :REM exit if wind=0
DRAWBY 9*x,9*y :REM draw the shaft of the arrow, 9 units long, from current position
IFs>1 MOVEBY x,y :REM if rounded windspeed >5 move one more space out.
WHILEs>1 :REM while there are still 50-ticks and 10-ticks to draw
MOVEBY 2*y,-2*x :REM move 2 units clockwise of the shaft
PLOT1-(s>9)*80,-2*y-x,2*x-y :REM draw a diagonal line back to the shaft. If s is 10 or over, plot mode 81 will take the last 2 positions of the graphics cursor and draw a triangle.
s-=2-(s>9)*8 :REM Decrement s by 2 or 10, according to the last barb drawn.
ENDWHILE
IFs MOVEBY -x,-y:DRAWBY x/2+y,y/2-x :REM If s=1 draw the 5-tick. Unlike the other ticks, it is drawn from its root outwards.
```
**Output**
All the test cases from the quesion are shown, plus two more to illustrate 2-letter directions:
```
50 knots, NNE
0 knots
12 knots S
112 knots WNW
195 knots SE
5 knots SW
```
In order to show them all together, I didn't clear the screen between runs. The different sizes (but constant proportions) of the arrows can be seen.

] |
[Question]
[
[Loopy](http://www.chiark.greenend.org.uk/~sgtatham/puzzles/js/loopy.html) is a puzzle game from the collection of Simon Tatham. The previous link contains a javascript implementation of a Loopy puzzle generator. I suggest everybody who wants to attempt this challenge to solve a couple of puzzles manually to understand how they are supposed to work.
Here are [instructions](http://www.chiark.greenend.org.uk/~sgtatham/puzzles/doc/loopy.html) on how to solve a Loopy puzzle:
>
> ## Chapter 23: Loopy
>
>
> You are given a grid of dots, marked with yellow lines to indicate
> which dots you are allowed to connect directly together. Your aim is
> to use some subset of those yellow lines to draw a single unbroken
> loop from dot to dot within the grid.
>
>
> Some of the spaces between the lines contain numbers. These numbers
> indicate how many of the lines around that space form part of the
> loop. The loop you draw must correctly satisfy all of these clues to
> be considered a correct solution.
>
>
> In the default mode, the dots are arranged in a grid of squares;
> however, you can also play on triangular or hexagonal grids, or even
> more exotic ones.
>
>
> Credit for the basic puzzle idea goes to Nikoli [10].
>
>
> Loopy was originally contributed to this collection by Mike Pinna, and
> subsequently enhanced to handle various types of non-square grid by
> Lambros Lambrou.
>
>
> [10] <http://www.nikoli.co.jp/puzzles/3/index-e.htm> (beware of Flash)
>
>
>
The goal of this task is to write your own Loopy puzzle generator. Since graphics are way too complicated, you have to output a generated puzzle in ASCII like the example puzzle of size 7×7 below. The advantage of the output format described here is that you can output your puzzle into a line printer and solve it with a pen.
```
+ + + + + + + +
2 3
+ + + + + + + +
2 2 3
+ + + + + + + +
2 2 1 3
+ + + + + + + +
2 1 2
+ + + + + + + +
2 1 2 3 3
+ + + + + + + +
3 2 1
+ + + + + + + +
2 2
+ + + + + + + +
```
## Input specification
Your program shall receive as input:
* An integer parameter in the range `2` to `99`, `x` (width)
* An integer parameter in the range `2` to `99`, `y` (height)
* An integer parameter in the range `0` to `9`, `d` (difficulty)
If you choose to implement the deterministic option, your program shall further receive as input:
* A positive integer parameter, `s` (seed)
In submissions written in languages that have the notion of program or command line arguments, the input shall be provided as a set of program arguments. The invocation will be like this:
```
program <x> <y> <d> <s>
```
where `<s>` is left out if you do not choose to implement the deterministic option.
In submissions written in languages that have the concept of an invocation URL (i.e. the URL the program is called at), input shall be provided as a set of URL parameters like this:
```
http://site.example/program?x=<x>&y=<y>&d=<d>&s=<s>
```
where the `&s=<s>` part is left out if you do not choose to implement the deterministic option.
In languages that fit into neither category, input is to be received in an implementation defined way. Hard coding input is not an acceptable implementation defined way, except if your language provides no mean to receive input.
Your program shall terminate and generate output as specified below for each combination of parameters with meaningful values. The behavior of your program is unspecified if any parameter is missing, invalid, or outside of the specified range.
## Output specification
Your program shall output a square-grid Loopy puzzle formatted as described above with an implementation-defined line terminator. Your implementation may fill each line with an arbitrary amount of trailing whitespace characters.
The grid shall have `x`×`y` cells where `x` and `y` are the width and height parameters specified further above. The puzzle your program generates shall have exactly one solution.
The difficulty of the problems your program generates shall depend on the `d` parameter, where a `d` value of `0` shall generate easy problems and a `d` value of `9` shall generate hard problems. Please document how the difficulty of the problems you generate changes depending on the `d` parameter.
If you choose to implement the deterministic option, the output of your program shall only depend on the value of the input. Different values for `s` shall yield different puzzles with a high probability for the same combination of `x`, `y`, and `d`. If you do not choose to implement the deterministic option, the output of your program shall be different every time the program is executed with a high probability. You can assume that the program is not executed more than one time per second.
## Scoring
The score of your program is the number of characters in its source except for omittable whitespace characters and omittable comments. You are encouraged to indent your submission so it's easier to read for the others and to comment your solution so its easier to follow.
Your submission may violate some of the rules described above. Please document specific rule violations and add the corresponding penalty to your score. Rule violations not documented here make your submission invalid.
* Your program contains instances of undefined behavior or violations of your language's rules (128)
* Your program ignores the `d` parameter but generates hard puzzles (256)
* Your program does not terminate or crashes in rare cases (512)
* Your program ignores the `d` parameter but generates easy puzzles (1024)
* Your program generates puzzles with more than one solution (2048)
* Your program generates unsolvable puzzles in rare cases (4096)
## Judgement
The winner of this contest is the submission with least score. I reserve the right to disregard submissions that violate the spirit of this contest or that cheat.
[Answer]
# Python3, 1004 bytes:
```
from random import*
from itertools import*
R=range
def U(D,B,x,y,X,Y):
try:D[B[x][y]]=D.get(B[x][y],[])+[B[X][Y]]
except:1
def O(b,s,e,x,y,n=[],r=[]):
if[]==s:yield e;return
j,k=s[0];J,X=j*(y+1)+k,(j+1)*(y+1)+k;K,Y=J+1,X+1
if len(p:={(J,X),(K,Y),(J,K),(X,Y)}-{*r})>=b[j][k]:
for i in combinations(p,b[j][k]):
T=p-{*i}
if all(q not in n for q in T):
E=eval(str(e))
for A,B in T:E[A].remove(B);E[B].remove(A)
if all(len(E[A])>1 for A in E):yield from O(b,s[1:],E,x,y,n+[*i],r+[*T])
def f(x,y,d):
while 1:
s=[0]*(x*y-(L:=int((x*y/2)*d/10)))+[randint(1,3)for _ in R(L)];shuffle(s);b=[s[i:i+y]for i in R(0,len(s),y)];k=-1
B=[[(k:=k+1)for _ in R(y+1)]for _ in R(x+1)];D={}
for Y in R(y+1):
for X in R(x+1):U(D,B,X,Y,X,Y+1);U(D,B,X,Y,X+1,Y);U(D,B,X,Y+1,X,Y);U(D,B,X+1,Y,X,Y)
for _ in O(b,[(X,Y)for X in R(x)for Y in R(y)if b[X][Y]],D,x,y):return'\n'.join([' '.join(['+']*len(H))+'\n'+' '+' '.join([' ',str(u)][u>0]for u in G)for H,G in zip(B,b)]+[' '.join(['+']*len(B[0]))])
```
[Try it online!](https://tio.run/##bVJNT@MwEL33V/hWTzJAswgJJTISUSsQIK1UsVIrr7VqqQNu0yQ4Kdss6m/vetxuyWEPsT0zbz7y3lRt81YWl9eV3e8zW66ZnRULd5l1Vdom6HmfabRtyjKvT@6xcLhX3VvojP3gQ0xxiy1OcApxjzW2jYcylVslW6XE8PxVN/xoolQQuthEyalSPaa3L7pq4shX@s7nWKP2tQohFVp3UEWTSSVEHbdG5wumE6ubjS16bIkrUcuBSh5wIpYBb8MIwhXypbv/WckjTsVDGOEkjKgSy3XBq1h8cpcEyF3YnQ/46E76gd3ZZ2B3cCPmcqnkSrn2LCstM8wU7KVcz00xa0xZ1LzCI4RGZOxZVC7V7Ojt2szynL@zomwor/Al3un5fECzkdAfs5zXjeUawLsIc4upR8UjeavOrV6XH5qnkIxkejJvD/BjE/ofAsNNdKhA@SM4kuUF9MTKKFY4OpAbysA4et31rMBzn3EKLGi4328m1yyiMWvh2A34NmjP@FMsTNFwMi6@QbC4iAYATkzaGApEeAnU/xf1H/MnUEn9tsmyXPMakrmQtTSxCVt1YnPMB0jT14CtQ6/EmVOIpUJKvorFysnXqUdqqo69JTsZis/dUaDpF84zTL7JFzY@7KmTmD7nSDoOtx7TjoO2peOgqHccO/kJiFPpN6bbCLqTgFNoflx1HBLzEB9Wt/@z6J8vS1Nw2WenV9hXAfFx72glROhiYSfO@kjrsgElNzcDT8aGWt35rvd4R8YfU/EU56DC/5VOnZ4ACvaVJc0yfoVXeA2w/ws)
As `d` increases, the number of numeric cells also increases.
] |
[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/15906/edit).
Closed 10 years ago.
[Improve this question](/posts/15906/edit)
When I'm at a store and I pay for something in cash, I always try to give as exact change as possible in order to minimize the number of coins I have left in my wallet afterwards.
Your task is to build a program that will automate this process for me.
Your program will accept as input:
* a line containing a single decimal number representing the price of an item.
* a line consisting of a list of pairs of numbers, each pair representing the value of a denomination of coin or bill, and then the current amount of that denomination that I have in my wallet.
* a line consisting of a list of denominations that the cashier has (you may assume they have an unlimited amount of each).
For example, the following input:
```
21.36
0.01 6 0.05 2 0.10 3 0.25 4 1.00 1 2.00 2 5.00 1 20.00 5
0.01 0.05 0.10 0.25 1.00 2.00 5.00 10.00 20.00 50.00 100.00
```
represents that I'm buying an item costing $21.36, and I have six pennies, two nickels, three dimes, four quarters, one loonie, two toonies, one five-dollar bill, and five 20-dollar bills.
Your program will then output the following:
* the change that I should give to the cashier.
* the change that the cashier will give me in return. You must optimize this as well in order to have a good solution.
* the list of coins and bills still left in my wallet.
* the total number of coins and bills left in my wallet after the transaction.
In this case, the optimal output is:
```
0.01 6 0.05 2 0.10 2 0.25 4 20.00 1
0.10 1 1.00 1 2.00 2 5.00 1 20.00 4
12
```
because I have exact change and this configuration uses the most coins to give that change. The second line is blank because no change was given in return.
Note that your program must support unconventional denominations such as `0.04` or `15.32`, if they are part of the input. You are not guaranteed that every denomination will be a multiple or factor of another, except that every denomination will be a multiple of the lowest one, so that there is always a valid solution. You may assume that I will always have enough money to pay for the item whose price is listed.
In a few days, I will be posting a suite of 1,000 test cases for this program. Your program will be scored by the sum of the total number of coins and bills left in my wallet for each test case, with shorter code being a tie-breaker.
[Answer]
I think I have a Python 3 solution that should work for any test case. It took me quite a few tries to get something that wouldn't explode for certain degenerate inputs. It's still pretty slow for some large inputs where you have thousands of coins in your wallet to start, but I don't think it's possible to do much better in those cases (you must search a very large set of possible combinations of payment and change).
I've made two version of my solution, one that minimizes the number of coins you end up with in your wallet at the end (as per the current scoring rule), and another that minimizes the number of coins you are given in change (which is equivalent to minimizing the number of coins in your wallet at the end plus the number of coins you paid with, which Joe Z. has been considering changing the scoring rule to). You can switch which version is run by moving the leading `#` for the comment in the `if __name__ == "__main__"` block to the previous line. Both versions are based on of the same recursive change making algorithm (in the `make_change` function), they just run it with slightly different inputs.
The code exploits the effect that Cruncher noted in the question's comments, that the best overall algorithm is to give all your money to the cashier and then get ideal change for your final balance back. What my code does is give all the money to the cashier, then charge a "cost" to the solution for each coin or bill returned to the customer. The best solution is the one with the combined cost for its bills and coins. Later I do some cleaning up, and eliminate any payments that get directly returned using the same bills or coins.
For the version optimized for the original scoring rule, the cost is 1 for every coin or bill. For the alternative scoring rule, the cost is 0 for bills and coins that were originally in the customer's wallet (and are being returned), and 1 for anything that needs to come from the cashier's drawer.
The core algorithm is a depth-first search for combinations of coins that yield exact change. Larger coins are tried first, and more of them before fewer. This means the first result we find will be the "greedy" one (though we keep searching and may find a better result later).
The interesting part of the algorithm is that it keeps track of the cost of the best result found so far, and stops searching for more results down any branch that costs more than that that result. This lets it avoid considering a lot of possible combinations that require too much from the cashier (like thousands of pennies).
I do get a different optimal result for the example case given in the question, but it is in fact better for the current scoring rule (I pay several extra small bills and get a single $50 in change). My output is:
```
0.01 6 0.05 2 0.10 2 0.25 4 1.00 1 2.00 2 5.00 1 20.00 3
50.00 1
0.10 1 20.00 2 50.00 1
```
For the alternate scoring rule I get the same result shown in the question.
I've not made much effort at minimizing the number of characters in this code, though some parts were written in terse, code-golf style before I got more distracted by performance issues and correctness. I think I've factored out the all the repeated code into separate functions, but let me know if you see any obvious improvements.
```
def make_change(value, coins, best_cost=float("inf")):
if value == 0:
return [], 0
best_solution=None
for i, (coin, count, cost) in enumerate(coins):
max_num = min(count, value//coin, best_cost//cost if cost else float("inf"))
for num in range(max_num, 0, -1):
coin_value = num*coin
coin_cost = num*cost
if coin_cost < best_cost: # this is always true the first iteration, but may not be later
solution, solution_cost = make_change(value-coin_value, coins[i+1:],
best_cost-coin_cost)
if solution is not None:
best_solution = [(coin, num)] + solution
best_cost = coin_cost + solution_cost
return best_solution, best_cost
def parse():
value = int(input().replace(".",""))
wallet = dict(zip(*[iter(map(int,input().replace(".","").split()))]*2))
cashier = list(map(int,input().replace(".","").split()))
return value,wallet,cashier
def print_output(pay, change, final_wallet):
print(" ".join("{:.2f} {}".format(coin/100, count) for coin, count in pay if count != 0))
print(" ".join("{:.2f} {}".format(coin/100, count) for coin, count in change if count != 0))
print(" ".join("{:.2f} {}".format(coin/100, count) for coin, count in final_wallet if count != 0))
def solve(value, wallet, coins):
result, cost = make_change(value, coins)
pay=[]
change=[]
for coin, count in result:
if coin in wallet:
if wallet[coin] > count:
pay.append((coin, wallet[coin] - count))
elif wallet[coin] < count:
change.append((coin, count - wallet[coin]))
del wallet[coin]
else:
change.append((coin, count))
pay.extend(wallet.items())
pay.sort()
change.sort()
result.sort()
return pay, change, result
def minimize_wallet(value, wallet, cashier):
wallet_value = sum(coin*count for coin,count in wallet.items())
coin_dict = wallet.copy()
coin_dict.update((coin, wallet_value//coin) for coin in cashier)
coin_list = [(coin, count, 1) for coin, count in sorted(coin_dict.items(), reverse=True)]
return solve(wallet_value-value, wallet, coin_list)
def minimize_change(value, wallet, cashier):
wallet_value = sum(coin*count for coin,count in wallet.items())
coin_list = [(coin, count, 0) for coin, count in wallet.items()]
coin_list.extend((coin, wallet_value//coin, 1) for coin in cashier)
coin_list.sort(key=lambda x: (-x[0], x[2]))
return solve(wallet_value-value, wallet, coin_list)
if __name__ == "__main__":
print_output(*minimize_wallet(*parse()))
#print_output(*minimize_change(*parse())) # use this if the scoring rules are changed
```
I'd also like to suggest a testcase that is likely to break many implementations:
```
1.00
100.00 10000
0.01 0.05 0.10 0.25 1.00 2.00 5.00 10.00 20.00 50.00 100.00 999999.00
```
This testcase comes with a story I like to call "The bank robber and the debt limit":
>
> One day, Alice robbed a bank. She made a clean getaway with exactly one million dollars in $100 bills. On her way home from the bank, she stopped off at a convenience store to buy a candy bar, but realized that she had not brought her wallet with her, so the only money she had was her bag of stolen money (ten thousand $100 bills will fit snugly in a decent sized backpack if they're shrink wrapped). She hoped the clerk would be willing to break a $100 bill.
>
>
> Unbeknownst to Alice, Bob the convenience store clerk had been recently laid off as a worker at the US Mint. He had worked for several months this past spring and summer preparing high-denomination platinum coins in case they would be the only way for the US Government to make its interest payments without Congress increasing the debt limit. It turned out the coins were not needed, so their existence was never acknowledged. When he was told his job was being cut, Bob decided he would keep on of the coins he had worked so hard on. He smuggled out a single $1,000,000-denominated coin in his box of personal effects.
>
>
> Sadly for everyone involved, Bob was showing off his million dollar coin to a coworker when Alice came to his register to see if he'd give her $99 in change for her $1 candy bar. Alas, seeing the coin, Alice's compulsion to receive the smallest amount of change possible got the better of her. She misinterpreted the text on the coin saying it was "0.999999 pure Platinum" to mean it was worth that fraction of its face value. If that was the case, it would be exact change for her candy bar if she paid Bob with her backpack full of money. She'd go from having 10,000 bills to having just one coin!
>
>
>
Can your code satisfy Alice? Expected output:
```
100.00 10000
999999.00 1
999999.00 1
```
] |
[Question]
[
## Objective
Given an arbitrary chessboard as standard input (in which each piece is on a square), produce as standard output a list of moves needed to regularize, or set up, the chessboard. The moves need not be legal, yet no piece may be placed above another. The program must warn about any missing or additional pieces; in the latter case, the program need not produce a list of moves.
A regular chessboard is a chessboard having sixteen pieces in their initial positions described in the [Laws of Chess](http://www.fide.com/component/handbook/?id=124&view=article) section of the *FIDE Handbook*. A partially regular board is a chessboard missing at least one of the regular board's sixteen pieces or including one or more additional pieces in ranks 3-6 (consisting of empty squares in the regular board) yet otherwise regular.
## Input format
### Description
Eight lines of eight characters each make up a chessboard. A hyphen (`-`) represents an empty square. The last line's first character represents the regular position of white's king's rook (a1 in algebraic notation) and is always a black square; both its adjacent squares are white squares (see Figure 1).
Each kind of piece has a distinct uppercase or lowercase letter for identification (see Figure 2). No two pieces having the same letter (excepting pawns) are present in a regular board, and white and black have exactly eight pawns each.
### Figure 1: regular board
```
rnbkqbnr
pppppppp
--------
--------
--------
--------
PPPPPPPP
RNBKQBNR
```
### Figure 2: piece names, counts, and letters
```
Piece Count White Black
--------------------------------
King 1 K k
Queen 1 Q q
Bishop 2 B b
Knight 2 N n
Rook 2 R r
Pawn 8 P p
```
## Output format
The program shall output one line per move. Each move follows the format `<source><target>`, where `<source>` is the algebraic notation for an occupied square and `<target>` is the algebraic notation for an unoccupied square. (Note: Algebraic notation is described in [Appendix C](http://www.fide.com/component/handbook/?id=125&view=article) to the *FIDE Handbook*.) For example, the program shall output `a4a5` to move the piece on square `a4` to square `a5`.
The generated moves shall fully regularize the chessboard if possible. If any pieces are missing from the board, the program shall output the moves necessary to partially regularize the board and then a line containing 'M' followed by the letters of all such pieces. An 'M' line shall not be output unless there is at least one missing piece.
If any additional pieces exist on the board, the program shall either a) leave them in ranks 3-6, partially regularizing the board or b) entirely omit the list of moves from its output, even if pieces are missing. The former option (a) may not be possible in some input cases. The program shall output a line containing 'A' followed by the letters of all additional pieces after all other output (including an 'M' line if present). An 'A' line shall not be output unless there is at least one additional piece.
## Score
The program's score shall be the product of its character count and the total number of moves taken for the ten test cases in `regboards.txt`.
## Test cases
I have posted **[regularizable and nonregularizable test cases](https://gist.github.com/1210316)** on Gist. On jsFiddle, I have posted the **[test case generator/move checker](http://jsfiddle.net/plstand/RRQqt/)** to help you check your solution. Put the board in the first box and the move list in the second box (including neither an 'M' nor an 'A' line) and click "Make Moves" to execute the moves your program has generated. To see examples of valid output, you can run my **[ungolfed solution](http://jsfiddle.net/plstand/ryN6Z/)** on the test cases (taking 482 moves).
[Answer]
## Python, score 150552 = 306 moves \* 492 chars
```
import os,re
B=os.read(0,99)
R='rnbkqbnr-'+8*'p'+37*'-'+8*'P'+'-RNBKQBNR'
def P(x,y):print'%c%d%c%d'%(97+x%9,8-x/9,97+y%9,8-y/9)
F={}
M=''
t=B.find('-',18,56)
for x in range(71):
if R[x]>'@':
if R[x]==B[x]:B=B[:x]+'-'+B[x+1:]
else:
y=B.find(R[x])
if y<0:M+=R[x]
else:F[x]=y;B=B[:y]+'-'+B[y+1:]
A=re.sub(r'[-\n]','',B)
if M:print'M',M
if A:print'A',A
else:
while F:
p=[x for x in F if x not in F.values()]
if p:x=p[0];y=F[x];P(y,x);del F[x]
else:x=min(F);P(F[x],t);F[x]=t
```
The code records a list of moves `F` which will regularize the board. This list is made by choosing a piece from the input board `B` to go to each location of the final board `R`, and 'crossing it off' of the input board. Any missing or additional pieces are computed as a side effect of this computation. Then the moves from `F` are made, using the temporary location `t` to break any cycles.
] |
[Question]
[
## Background
You know how in text editors and just text fields in general, there's always that blinking bar where you type? Yeah, simulate typing there.
You'll be given 3 inputs: The current text field, the position of the cursor, and the input sequence.
Here's an example:
```
Hello, World!
5
[U];[U];[B];[B];[B];[B];[B];[U];i;[R];[R];[R];[R];[R];[R];[R];[R];[R];[B];.
=> Hi, World.
```
Firstly, the number 5 tells us that the cursor is here, represented by the asterisk: `Hello*, World!`. If you take the string as zero-indexed, and choose the left side, you will find the cursor's starting point.
Next, we have 2 `[U]`s. `[U]` is a special input, representing undo. However, there is nothing to undo, so nothing happens.
Then, we have 5 `[B]`s. `[B]` is another special input, representing backspace. This tells us to erase 5 characters to the left of the cursor, one at a time. This gives `*, World!`.
Next, we have `[U]`. This tells us to cancel out the previous input (if there's anything to cancel out). If you have two `[U]`s, then you cancel out the last two instructions before the `[U]`s. Logic extends to all number of `[U]`s. Cancelling out the previous input, we have `H*, World!`.
Next, we have `i`. If there are no square brackets around the character, just add it to the text as a string, to the left of the cursor: `Hi*, World!`.
Now, we have 9 `[R]`s. `[R]` represents Move Cursor Right, so we move the cursor right 9 times: `Hi, World!*`. Note how it only actually takes 8 `[R]`s to get to the end, so the final `[R]` doesn't do anything.
Now, a `[B]`. This gives us `Hi, World*`.
Finally, `.`. This gives us `Hi, World.`.
//
The list of special inputs is shown here:
```
[B] = Backspace
[U] = Undo
[R] = Move Cursor Right
[L] = Move Cursor Left
```
Of course, within reason, you can change these special inputs (as long as it won't conflict with any non-special inputs.)
//
With regards to other rules:
* Left or Backspace when the cursor is furthest left does nothing.
* Right when the cursor is furthest right also does nothing.
* Undo when there's nothing to undo also does nothing.
In terms of undoing, `[L];[U]` and `[R];[U]` moves the cursor to its original position, before the `[L]` or `[R]`. `[B];[U]` reverts the backspace.
In terms of stacking undos, *an undo will not undo another undo*. That is, considering the following:
`z;a;b;[U];[U];c;[U];[U]`
The first two undos would get rid of a and b. The third would get rid of c. Finally, the last undo would get rid of the z. You can think of it like a stack, where every undo removes itself and the input below it.
However, in the special case the previous input does nothing:
`a;[R];[U]`
The undo should also do nothing.
## Your Task
* Sample Input:
1. The current text field
2. The position of the text cursor (<= length of current text field)
3. The input sequence
Wrt the input sequence, in my examples I have used a string where each instruction is separated by semicolons. You can take the input sequence in any reasonable format - but note that the no input can contain this character. You can expect the non-special inputs and the text field to contain no `\n`s or `\t`s. They will also not contain any `[B]`s (and other), `[`, or whatever you're using for making the special input unique.
* Output: Return the final text field, after the sequence has been executed.
**Test Cases**
```
Input => Output
Hello, World!
5
[U];[U];[B];[B];[B];[B];[B];[U];i;[R];[R];[R];[R];[R];[R];[R];[R];[R];[B];.
=> Hi, World.
This is [tag:code-golf], so shortest answer wins.
13
[R];[R];[R];[R];[R];[R];[B];c;h;s;[U];a;[R];[R];[B];[B];[R];L;[U];[L];llenge;[R];r;[L];[B];[R];[B];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[B];[B];[B];[B];[B];b;[R];[R];[L];[U];[R];[R];response or ;[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[B];[B];[B];[B];ill accepted as answer.;[U];ill be accepted as answer!
=> This is [tag:code-challenge], so best response or answer will be accepted as answer!
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins. (# of bytes)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 145 bytes
Not sure if it breaks the rules to have the special commands as integers. `U=0, L=-1, R=1, B=8`
The only reason `B=8` is because the control code for backspace is `\x08` lol
```
->s,l,i{i[(x=i.index 0)-[1,x].min..x]=[]while[]!=[0]&i
i.map{|e|l=l.clamp 0,s.size;e.ord==e ?e<5?l+=e:(s[l-=1]=''if l>0):(s[l,0]=e;l+=e.size)}
s}
```
[Try it online!](https://tio.run/##lVHRatswFH33V9yUUifMFvZKoYuqBPq0hzyVlT0oojjyTSxQLKPrkmxpvj3V1GRjELYWfPA5517pXK788@LHYSnmh3xCmc3MzsjhVhhm2hq3F/PiYpTLMtsqtjYtY1slpNo0xqJUAyGn80JdmcSwddXtXvDFCsu0rdYdFBkxMj@Ra4HM@Zrruy9TfXcztZ@Ezj@PhyRtLkol0tQswU6KUbSyQgnkoQfj6dE@of0h5sEKe0oACARcPjHduHUXpA3yV4X17skEbU46NjDqrOmHKU9HpxFRhgiRyhSmsEsfUxCTMCyk95HdBvYQ2XVgs8jKvURZKhWu9DAG3IeY7rknWMq4MZVgWx@@orUug@/O23qQ3CTyUfGI@zMIvuHyQf0foZsl3xpDED7ZV6uxdjXmK2eXKgNyQI3zPVIPVUsb9LAxLbGkvE7@daXmDac4RvWXHxH47G30meLWYrvCaPponFp@/9@LM3tY/KnOjts6ao/UuZYQnIePxbwz3lgLldbY9VhDRcftsbenCbUFnikPXgE "Ruby – Try It Online")
# [Ruby](https://www.ruby-lang.org/), 153 bytes
Version that uses characters only in case the above answer breaks the rules: `U=\x00, L=\x01, R=\x03, B=\x08`
```
->s,l,i{i[(x=i.index"\0")-[1,x].min..x]=[]while[]!=[?\0]&i
i.map{|e|l=l.clamp 0,s.size;c=e.ord;c<9?c<5?l+=c-2:(s[l-=1]=''if l>0):(s[l,0]=e;l+=e.size)}
s}
```
[Answer]
# Q, 248 bytes
```
w:{s:{x like"[[]",y,"[]]"};if[10=(@:)z;z:";"vs z];while[z[0]~"[U]";z:1_z];$[0=(#:)z;x;not(^:)r:(*:)(&:)s[z;"U"];w[x;y;_[z _ r;r-1]];s[o:z 0;"R"];w[x;(#:)[x]&y+1;1_z];s[o;"L"];w[x;0|y-1;1_z];s[o;"B"];w[x _ y-1;0|y-1;1_z];w[#[y;x],o,_[y;x];y+1;1_z]]}
```
**ungolfed**:
```
wp: { [text; cursor; input]
if[10h=type input; input: ";" vs input]; // convert semicolon-delimited string to list of strings
special: {x like "[[]",y,"[]]"}; // function to check whether a string is like e.g. "[E]"
while[input[0]~"[U]"; input: 1 _ input]; // remove leading undo's since there's nothing to undo
if[not null rm: first where special[input; "U"]; // find the first "[U]" operation -- re-call this function after removing it and the preceding operation
: wp[text; cursor; _[input _ rm;rm-1]];
];
if[0=count input; : text]; // base case -- return text if there are no more operations
op: input 0;
if[special[op; "R"]; // re-call this function with 1 added to cursor (capping at length of text)
: wp[text; count[text]&cursor+1; 1_input]];
if[special[op; "L"]; // re-call this function with 1 removed from the cursor (capping at 0)
: wp[text; 0|cursor-1; 1_input]];
if[special[op; "B"]; // re-call this function with a) the character before the cursor removed from text and b) 1 removed from the cursor (capping at 0)
: wp[text _ cursor-1; 0|cursor-1; 1_input]];
: wp[ #[cursor;text],op,_[cursor;text]; cursor+1; 1_input]; // re-call this function with the characters added after the cursor in text
}
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 228 bytes
```
def f(s,c,Z,d=[]):
for i in Z:d=d[:-1]if i[0]and'T'<i[1]else d+[i]
for S,D in d:
if S:
if'Q'<D:c=min(c+1,len(s))
elif'K'<D:c=max(c-1,0)
else:s=s[:(f:=max(c-1,0))]+s[c:];c=f
else:s=s[:c]+D+s[c:];c+=len(D)
return s
```
[Try it online!](https://tio.run/##nVRdb9owFH3nV9zy4kS4iPAxuqTRpIqHTuNla9GkRkZyYwcsMjuyU3Xtn28dJ0BgVKJDXGL53Gvfc84lxUu5VnJ0Vei3N8YzyDyDU/yAWZwQP@xApjQIEBIeQhazJLwMiMhAJANCJUP36FokAeG54cB6iSB1wR2eVSXM1oPNvquedoF@outZmMZ/hPTSXoBzLj3j@xXIcwv/aGD610svAzxoEMNDE5sk9LKwhfmkZ5I0JFEaZ512Wkp6sy3Ui6s7ZvYgzcsnLcE4kgXVhntCFr7rDIwl6xY7thbrmyIXpYci1GSBIwEoQS5jv@mO6NOi4JJ5XoArSWpa7uNa@yB5gEWTuW2w06HGcF1aJ9D9Whiw36SkqzBVjF@uVJ4RDEaBWStdclMCleaZa3gW0vQRDka4ZtdNfpHoZNxYYaJ1ZKJkQSJ6sO/CrucOS@Ykyq2AK@42tdvYpuye58bNv/G4R6uTF/tszU2hpJ0qa8jnrjnzepHnQNOUFyVnQE2jYt81UWGP/AR80fX9OD5hS7qmtVC1N4@VL20KO48@PBm1fO9@h42QjAJTEpWQiw2HgtuJ0UoKUBIK8fpKMbxspHr@1sWDneVtkvMm/lewxZFon6yHj23YZtg3CKyozkUKpVJWlfLJyviyqbMWLmrF94K01YBKjiM12jqi0der6TIYQg/Goy@TahXDeDwd2hXCw2kjG9qN9VayE6PatHM4qHZ/sq9qVx@fcmzGnJxXdyLG7ne0RE6Z0TJw9AJLbbIcHtC/5XmuMPxWOmcXCE92fBcn7G3xFGf/o/p1E7eiuaVv7y@0kPa1aZ7skBuD/Ld3 "Python 3.8 (pre-release) – Try It Online")
The first `for` loop uses the stack `d` to get rid of all the undos. The second `for` loop loops over each instruction and modifies the string `s` accordingly. Almost definitely still golfable.
Inputs: list of tuples: (opcode, string). The opcode is 1 if the string is a special command, and 0 otherwise. Ex: `[(1, 'R'), (1, 'U'), (0, 'hi')]` This may be stretching the acceptable input format a bit, so I made a version which can accept the input format that the OP used:
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 267 bytes
```
def f(s,c,Z,d=[]):
for i in Z.split(';'):g='['in i;i=i[1]if g else i;d=d[:-1]if g and'T'<i else d+[(g,i)]
for S,D in d:
if S:
if'Q'<D:c=min(c+1,len(s))
elif'K'<D:c=max(c-1,0)
else:s=s[:(f:=max(c-1,0))]+s[c:];c=f
else:s=s[:c]+D+s[c:];c+=len(D)
return s
```
[Try it online!](https://tio.run/##nVRdb9owFH3nV9zy4kS4qOFj7ZJGkyoeOo2XrUWTGgXJTZxgkdmRnaqjf769cQKkjEp0iEuse67vxzmXlJtqpeT4qtSvrynPIHMMTegDTcModv0eZEqDACHhYWjKQlQOCYjr5yGJCDpFIEIRebHIIAdeGI6eNEwj/7z1MZmSe3ItGjAdRE5OhRs3ee/orM6cYhnA6Lv6iQfyk1zP/CT8I6STDDxacOkY161BXiD8o4XZXyc59@hFixjum9BEvpP5HcyNByZK/DhIwqzXDUviwWwLDcK6xgwTaV49aQnGclEybbgjZOnazsAgJ/awIwWxLi0WBDsEIEE2Yu@0KYasLLlMHcejNXHNWPZjW/sg@AJJayK3DfZ6zBiuKxSM3K@EAfxGFcv9RKX8PFdFFlMwCsxK6YqbCpUwz1zDs5BmSKg3ps10/ehXHBy1GyQmWAUmiBZxwN75reF5brFoHgcFEphz69TWsQ3ZPU@1m3/tcY/WmRf7aM1NqSRuFgryuTInlhdFASxJeFnxFJhpWRzaJmrskR@Bz/quG4ZHZElWrCGq0eax1qU7wk6jDzOTju7977AWMmWQKkkqKMSaQ8lxY7SSApSEUry8MAqbtVTP3/r0Yid5d8h5a/9L2OKAtE/eh49l2EbgOwRypguRQKUUslI9IY2bdRO1sNYwviekywbUdByw0eWRjL9eXS69EQxgMv4yrU8hTCaXIzwROrpsaSO7td5SdmRV23beLyr6p/tb3duHWQ7FmMen3TtiE/s7XhLLzHjp2fE8HG26HL0b/5YXhaLwW@kiPSN0upt3cUTezpzi5H/UsGniVrRVhli/1ELia9M84ZIbQ9zXNw "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 88 bytes
```
Sθ≔⁻LθNηWS≡ι´⟲≔∧υ⊟υι⊞υιFυ≡ι´←≧⁺‹ηLθη´→≧⁻‹⁰ηη´⮌≔⁺✂θ⁰±⊕η¹✂θ⁻LθηLθ¹θ≔⁺⁺✂θ⁰⁻Lθη¹ι✂θ⁻LθηLθ¹θθ
```
[Try it online!](https://tio.run/##nVKxTsMwEN39FQeTIwVExVYmRqQWVcCGGFz3GltyndTn0AGxMjFU/AB/0IFP4kfCOaQQ1A6AlJPtu3fvXe5OGxV0qVzTXPiqjtcxWF/IZXYmzols4eXY@prkCH0RDftzaHGX9WKKQWb8NoxdGesQZJ8iy4BWNmoD0mbwILQihMP317fDIXTU534m6xwmZSXrxGSZaYZzVbs4hElNJkWT81HMywAM2kv5tGbKsao@Wa9sYaKcuJpyGCGRNOnsqu/K3Sa@7Ca2v9tlniT0j4zN83f1SUJeO6tRLnNg7CUWKiI3QQdcoI84kyYpDti@cDvtTAq95yBlLPuN6MvtaO6lG7S9/I/oo5jw8GKaf9PcGEvA321UxVCXMzwqSje/y4FKIFOGiBRBeVphgJX1dCwGp4Kbut82z0ILI0jwCgj1w98a30dtjOcpnOPisHWG1rGFfJ2/tS19z6Y9xLqT/HwHpKr0PGnetr/J/FLeOgdKa6x4OUBR173jtogUm@Ke8IFoju7dBw "Charcoal – Try It Online") Link is to verbose version of code. Takes the input sequence as a list of newline-terminated strings where `⟲` is undo, `←` is left, `→` is right, and `⮌` is backspace. Explanation:
```
Sθ≔⁻LθNη
```
Input the starting string and position, but calculate the position as a count from the end of the string, because that remains invariant under insertion and deletion.
```
WS
```
Loop through each command string.
```
≡ι´⟲≔∧υ⊟υι⊞υι
```
If it's a `⟲` then remove the previous command if any otherwise add the command.
```
Fυ≡ι
```
Loop through the remaining commands.
```
´←≧⁺‹ηLθη
```
Handle left.
```
´→≧⁻‹⁰ηη
```
Handle right.
```
´⮌≔⁺✂θ⁰±⊕η¹✂θ⁻LθηLθ¹θ
```
Handle backspace.
```
≔⁺⁺✂θ⁰⁻Lθη¹ι✂θ⁻LθηLθ¹θ
```
Handle everything else.
```
θ
```
Output the resulting string.
] |
[Question]
[
I'm trying to solve a [CSS challenge](https://cssbattle.dev/play/141). It contains a rotated leaf shape (looks like an eye). Score for the challenge depends on amount of characters of the code. Here's my way to make a leaf shape:
```
div {
width: 200px;
height: 200px;
border-radius: 99% 0;
rotate: 45deg;
background: #d9d9d9;
}
```
```
<div></div>
```
Here's my whole solution for the challenge if you need a bigger picture:
```
* {
background:#E3516E;
}
p {
height:99px;
width:99px;
background:#d9d9d9;
border-radius:0 0 81q;
margin:-31px;
}
[i] {
rotate:45deg;
margin:55px 142px;
border-radius:99%0;
}
p+p {
margin:-30px 316px;
scale:-1;
}
```
```
<p><p i><p>
```
Minified version of the above:
```
<p><p i><p><style>*{background:#E3516E}p{height:99;width:99;background:#d9d9d9;border-radius:0 0 81q;margin:-31}[i]{margin:55 142;rotate:45deg;border-radius:99%0}p+p{margin:-30 316;scale:-1
```
Is there any way with less code for the eye shape? Maybe with clip-path, borders or something like that? Please help.
[Answer]
# 77 bytes
```
<p style=width:5em;height:5em;border-radius:99%0;rotate:45deg;background:#080
```
```
<p style=width:5em;height:5em;border-radius:99%0;rotate:45deg;background:#080
```
* Use a `p` tag instead of a `div`
* Omit the closing `>`
* Remove all white space within the CSS
* Use an inline `style` attribute
* Use `em` instead of `px` for units of measurement
* Use 3 digit hex colours instead of named colours
* Omit the last `;`
You can save another byte using `4rad` in place of `45deg`, but the angle won't be *exactly* right:
```
<p style=width:5em;height:5em;border-radius:99%0;rotate:4rad;background:#080
```
] |
[Question]
[
In [this question](https://codegolf.stackexchange.com/q/247699/) I asked you to determine if a run ascending list could be made. It was code-golf so naturally most the answers are very slow. But what if we want it to be *fast*. In this challenge I ask you to solve the same task except your goal will be to minimize asymptotic time complexity.
Here's the challenge restated:
>
> A *run ascending list* is a list such that runs of consecutive equal elements are strictly increasing in length.
>
>
> In this challenge you will be given a list of \$n\$ positive integers, \$x\_i\$, as input. Your task is to determine if a run ascending list can be made from the numbers \$1\$ to \$n\$ with each number \$k\$ appearing *exactly* \$x\_k\$ times.
>
>
>
## Rules
You should take as input a non-empty list of positive integers. You should output one of two distinct values. One if a run ascending list can be made the other if it cannot.
Your answers will be scored by their worst case asymptotic time complexity with respect to the *size* of the input.
The size of an input list \$x\_i\$ will be considered to be \$\sum\_{n=0}^i 8+\lfloor\log\_2(x\_i)\rfloor\$ bits. Although you are allowed to use formats that do not have this exact memory usage for convenience.
The brute force algorithm has a complexity of \$O(2^n!)\$.
The tie breaker will be [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
## Testcases
Inputs that cannot make a run ascending list
```
[2,2]
[40,40]
[40,40,1]
[4,4,3]
[3,3,20]
[3,3,3,3]
```
Inputs that can make a run ascending list a potential solution is given after the `,` for clarity but is not necessary for you to compute.
```
[1], [1]
[10], [1,1,1,1,1,1,1,1,1,1]
[6,7], [1,1,1,1,1,1,2,2,2,2,2,2,2]
[7,6], [2,2,2,2,2,2,1,1,1,1,1,1,1]
[4,4,2], [1,3,3,1,1,1,2,2,2,2]
[4,4,7], [1,3,3,1,1,1,2,2,2,2,3,3,3,3,3]
[4,4,8], [1,3,3,1,1,1,2,2,2,2,3,3,3,3,3,3]
```
[Answer]
Python, I'm not sure of the exact complexity. Probably exponential in the worst case.
```
import itertools
bad = set()
def run_ascending(sizes, low=1, prev=0):
if not any(sizes):
return True
if any(0 < x < low for x in sizes):
return False
key = (low, prev) + tuple(sorted(n for n in sizes if n))
if key in bad:
return False
for i, s in enumerate(sizes):
if not s:
continue
if s == prev:
prev = 0
continue
s = sizes[i]
for k in itertools.chain((s,), range(low, (s + 1) // 2)):
sizes[i] -= k
r = run_ascending(sizes, k + 1, sizes[i])
sizes[i] += k
if r:
return True
bad.add(key)
return False
```
] |
[Question]
[
It's mentioned last time that, in [Hearts](https://en.wikipedia.org/wiki/Black_Lady),
>
> Each round every player gets a non-negative amount of *points*. The sum of the points is 26, and at least one player gets 13 or more points.
>
>
>
Actually, it's the game part:
1. Average the 52 cards (♠♡♢♣ \* 23456789 10 JQKA) to the 4 players
2. The player with a ♣2(the smallest value) starts the first hand
3. The player who play a largest value with same suit to the hand starter on `i`-th hand (`1<=i<=13`):
* Add 1 to his point for each ♡ in this hand
* Add 13 to his point if ♠Q is in this hand
* starts `(i+1)`th hand (`1<=i<=12`)
There's some playing rules:
1. On the first hand, ♣2 should be played.
2. If possible, no ♡ or ♠Q on the first hand.
3. If possible, non-starter should play starter's suit
4. If possible, the hand starter can't play ♡ if it isn't played.
Now given the point of 4 players, generate a valid game that lead to the point result. You can assume that it's possible. Output is flexible, you can choose any 52 values to mean the 52 cards (This is the explained output below, so there's no fear that you have to encode the output in a specific way)
Sample:
```
Input 13 0 0 13
Hand1 ♣5 [♣2] ♣3 ♣4
2[♣9] ♣8 ♣7 ♣6
3[♣A] ♣10 ♣J ♣Q
4[♣K] ♡10 ♡J ♡Q
5[♢7] ♢5 ♢4 ♢6
6[♢A] ♢3 ♡A ♢2
7[♢K] ♡8 ♡7 ♡6
8[♢Q] ♡5 ♡4 ♡3
9[♢J] ♡2 ♠4 ♡9
10[♢10]♡K ♠6 ♠7
11[♢9] ♠8 ♠10 ♠9
12[♢8] ♠J ♠A ♠K
13[♠3] ♠5 ♠2 ♠Q
[ ]
```
Sample:
```
Input 26 0 0 0
Hand1 ♣5 [♣2] ♣3 ♣4
2[♣9] ♣8 ♣7 ♣6
3[♣A] ♣10 ♣J ♣Q
4[♣K] ♡10 ♡J ♡Q
5[♢7] ♢5 ♢4 ♢6
6[♢A] ♡K ♢3 ♢2
7[♢K] ♡8 ♡7 ♡6
8[♢Q] ♡5 ♡4 ♡3
9[♢J] ♡2 ♡A ♡9
10[♢10]♠5 ♠6 ♠7
11[♢9] ♠8 ♠10 ♠9
12[♢8] ♠J ♠A ♠K
13[♠Q] ♠4 ♠3 ♠2
[ ]
```
Sample:
```
Input 23 1 1 1
Hand1 ♣4 [♣2] ♣3 ♣5
2 ♡2 ♣8 ♣7 [♣6]
3 ♡3 ♣10 ♣J [♣9]
4 ♡4 ♣A [♣Q] ♣K
5 ♡6 [♡5] ♢4 ♢6
6[♡A] ♢2 ♢3 ♢5
7[♡7] ♢7 ♢8 ♢9
8[♡8] ♢10 ♢J ♢Q
9[♡9] ♢K ♢A ♠Q
10[♡10]♠5 ♠6 ♠7
11[♡J] ♠8 ♠10 ♠9
12[♡Q] ♠J ♠A ♠K
13[♡K] ♠4 ♠3 ♠2
[ ]
```
Here a `[]` means starter, which you needn't output. Also it's absolutely not a game that would happen in real play, but it's just valid.
This is code-golf, shortest code in each language wins.
[Answer]
# [Python](https://www.python.org), 676 bytes
```
R=range
def f(s):
c,y=[0,13]+([2,1,2,2][(i:=s[0]==14):i+3],[2,2,1])[s[0]%2]+[1]*8,[]
r=p=0
for j,i in enumerate(c):
r+=i
if r==s[p]:y.append(j+1);r=0;p+=1
p,t=y[:-1],c[2:5]
h=[[(1,12)]+[(0,12),(0,11)]+[(0,9-x)for x in R(10)],[(1,0)]+[(2,x+1)for x in R(12)],[(1,11),(0,10)]+[(3,0),(3,1)]+[(1,x+1)for x in R(9)],[(1,10),(2,0)]+[(3,12-x)for x in R(11)]]
for i in R(len(p)):
k=p[i]
if i==0:h[0][k],h[1][1]=h[1][1],h[0][k]
if i==1:q=p[0];h[1],h[2]=h[1][:q]+h[1][q+1:k+1]+[h[2][k-1]]+h[1][k+1:],h[2][:q]+[h[1][q]]+h[2][q:k-1]+h[2][k:]
if i==2:h[2],h[3]=h[2][:-1]+[h[3][-1]],h[3][:k]+[h[2][-1]]+h[3][k:-1]
h[2][2:5]=[sorted(h[2][2:5]).pop(1-i)for i in t]
return h
```
[Attempt This Online!](https://ato.pxeger.com/run?1=zVbJjuM2EEWCXNpfwXEQmLTKhin3qgYPuWU5pZEbQTQESW7LiyRTNNqdwXzIIJfO-lFznC9JFSkv3UkGyC2AbVJVr-rVRso__9k8uXldPX_44i4vZqxJbVvwNqttAfO0yluR9M6y1Oat6scwhXO4gEu4gmu4ATmB7-AH-B6-7o_bZlU63oe-6J2129Ih_OP7Z_j4_jf8_orfX15iGltWjs_631bN1iXs7WAwXtRlxfmADaLWWV66Yi3EeLXYto5fAIoFm9WWkZyVFfMhinfME7rUusIq2TvzEHhI18W9rbdVTtCi2q4Lm7qC_1Q2fBjSory6KPjgGxSxwZCXSk1EoI8kslvPfunZ4RCi7jNMQveNRnzHbSKftV6YyFdLL00UcOYl7p9SAr6ApXgZ6jEFITDFM7-9JxJ1VOm9Vz0xiHksqwrLoCkCVs6YR_8LnBWrtmAj6SMgIASrih3x5HNf2-B7XFZ5sePrdMeDQBx6iekMryJMeXgx7IyivmbMYIdosrJ5kS3vfdtez9dJ_6riMWBahUEOz_9rR9M87-xPKggdARy9_89Lagu3tRU7xutL-InkIJwHKiZtNH9MlOYTyITe_D1eitZQlBvIXsUnTuMRwkSYO6IJ_Bo6znBxfCoiOR1yJJMT8QIh_ti62ej6w-e_3ymbVg-Fz2LGw6UCT9hikFMTcR2DhBhio3mZqBb5lJLnIimjqQFUotoITfKvYjxX0gyvQWMprWrUJIzIAsqXk5H5ebCRKnHBzlk8g7oxydM4bZqiyvkCj_itVZPbJqLJa8CpJ52MpIFMx8kFup8rrbkEGWMZqJi4AVpk93wz2gni3hHzHcf0MVo0mHh9DDtkONXHnR4dQCgX4aaIB_wNXuVrq5u9EaFi2NvI-BU5mpvutATJqqh4E07FUjW6NKEOdMclcywlXlEwx1riR3UrdPIDUiYbNJ2Y23nQxh002ZjIbzaRTJaRxJhIqZdYvk6D0iSYeLQOcK9F0SYhaNgvkyNhnJAIzabERLaj4HxqNPn2Gp0s94Qd35S84B57RlJqn9Jtjccs5weJGDd1w-WoFIcqOXM4a_NuWD9Lv2Q_Fq0rq4fezNZreuNYV9erlpXrBl0Oe1na0v1kev5U4AO50rO6ZqeCxtb5NnNcD_3sczmF-IqauX8-_9SDCLfNmpM7gYW5ZPSS4siCJyRk5lU6ocQFVeKNkgbbjYY-hqp2FIePlqbAb_bT7219Ag6TPcWhOYneqNMbmyQw8wuO1P7tTXUKXIO3pHo3YLO0XBU53vnhn4R3igOEtvut6K6F5-ew_gU)
Takes the input as a reverse sorted list of scores. Returns a list of the cards in each hand, ordered by round. Cards are encoded as `(suit, value)`, where `suit` and `value` are indexes of `"♠♣♢♡"` and `['2','3','4','5','6','7','8','9','10','J','Q','K','A']` respectively. Works by rearranging the master arrangement
```
Hand 1 ♣A [♣2] ♣K ♣Q
2 [♠A] ♢3 ♠Q ♢2
3 [♠K] ♢4 ♡2 ♡A
4 [♠J] ♢5 ♡3 ♡K
5 [♠10] ♢6 ♣3 ♡Q
6 [♠9] ♢7 ♣4 ♡J
7 [♠8] ♢8 ♣5 ♡10
8 [♠7] ♢9 ♣6 ♡9
9 [♠6] ♢10 ♣7 ♡8
10 [♠5] ♢J ♣8 ♡7
11 [♠4] ♢Q ♣9 ♡6
12 [♠3] ♢K ♣10 ♡5
13 [♠2] ♢A ♣J ♡4
[ ]
```
as needed to give the correct score.
Interestingly, I believe there are only 87 unique test cases. This is based on the assumption that `[n,n,n,1]` is an impossible score, as it is impossible for the lowest scoring hand to win a trick without gaining a score of two or having an illegal move prior. However, I'm not confident in this assumption, so may need to alter my solution if proven wrong.
I'm very confident that there is a better master arrangment and rearrangment method, and will update if I find it.
# Explanation
```
R=range
def f(s):
c,y=[0,13]+([2,1,2,2][(i:=s[0]==14):i+3],[2,2,1])[s[0]%2]+[1]*8,[] # Find the scoring arrangment per round
r=p=0
for j,i in enumerate(c): # Find which rounds the next player takes over winning tricks
r+=i
if r==s[p]:y.append(j+1);r=0;p+=1
p,t=y[:-1],c[2:5] # Rounds the next player takes over, adjustment needed at end to account for scoring arrangment
h=[ # Master hand arrangment
[(1,12)]+[(0,12),(0,11)]+[(0,9-x)for x in R(10)],
[(1,0)]+[(2,x+1)for x in R(12)],
[(1,11),(0,10)]+[(3,0),(3,1)]+[(1,x+1)for x in R(9)],
[(1,10),(2,0)]+[(3,12-x)for x in R(11)]
]
for i in R(len(p)):
k=p[i]
if i==0:h[0][k],h[1][1]=h[1][1],h[0][k] # Rotation from first player to second player
if i==1:q=p[0];h[1],h[2]=h[1][:q]+h[1][q+1:k+1]+[h[2][k-1]]+h[1][k+1:],h[2][:q]+[h[1][q]]+h[2][q:k-1]+h[2][k:] # Rotation from second player to third player
if i==2: # Rotation from third player to fourth player
h[0],h[3]=h[0][:p[0]+1]+h[3][p[0]+1:],h[3][:p[0]+1]+h[0][p[0]+1:]
h[2],h[3]=h[2][:-1]+[h[3][-1]],h[3][:k]+[h[2][-1]]+h[3][k:-1]
h[2][2:5]=[sorted(h[2][2:5]).pop(1-i)for i in t] # Adjusting arrangment of third player to match scoring arrangment per round
return h
```
] |
[Question]
[
For a computer vision app I want to do a mapping of an image, in such a way that every pixel fit [hilbert curve](https://en.wikipedia.org/wiki/Hilbert_curve), instead of conventional layout. So task could be as follows:
---
## Task description
Given square 2D image `A` with side `2^^N`, (`N>0`), with common Z-order, or row-major representation of pixels in RAM. I need to run a hilbert curve through this image (Like a digital camera, where photodiodes are soldered in a hilbert curve and numbered and accessed in a 1-d ordered manner). Then pixels along this curve just layed down as a regular scanline in image B. So now any consequent samples in output array B now should represent spatially close points in input array A.
---
## Example for `N=2`
[](https://i.stack.imgur.com/RiLeE.png)
```
Input: array A (imagination of 2D image)
0 1 E F
3 2 D C
4 7 8 B
5 6 9 A
Input: array A (1D actual layout in memory)
0 1 E F 3 2 D C 4 7 8 B 5 6 9 A
Output: array B (answer)
0 1 2 3 4 5 6 7 8 9 A B C D E F
```
Note, that values inside arrays are "values". In this example, for array B accidentally they became same as indices. So basically I want index mapping function B[i]=A[?], e.g B[2](https://i.stack.imgur.com/KdtBj.png) = A[E].
Hope code golfing helps.
---
## Example for N=9:
Taken popular 512\*512 test image.
Each pixel was threated as 32bit integer, in RGBA format and algorithm proceeded:
Input:
[](https://i.stack.imgur.com/KdtBj.png)
Output:
[](https://i.stack.imgur.com/vL4lG.jpg)
---
## Reverse question:
Here is [reversed-task question on codegolf](https://codegolf.stackexchange.com/questions/101871/hilbertify-an-image).
In terms of that question, I want to do opposite transform: "I want to *Reravel* image A, then *Unravel* to image B".
In terms of examples of that question: I want to take *photo the lion* on the camera with hilbert-curved-sensor (look *Output* array for lion photo) and get that long "scanline of spatially close pixels" (Input for lion photo, in that question)
---
## Reference implementation:
If i take `d2xy()` function [from LGPL sources found here](https://people.sc.fsu.edu/~jburkardt/c_src/hilbert_curve/hilbert_curve.html) I may write a following program, which works, but maybe not its best way:
```
#include "hilbert_curve.h"
int main(){
int *A,*B,i,x,y;
for(i=0;i<(1<<(N<<1));++i){
d2xy(N,i,&x,&y);
B[i]=A[y*(1<<N)+x];
}
}
```
---
## Resources:
* [Spatial indexing with Quadtrees and Hilbert Curves](http://blog.notdot.net/2009/11/Damn-Cool-Algorithms-Spatial-indexing-with-Quadtrees-and-Hilbert-Curves)
* [`hilbert` function, which returns a rendering of Hilbert Curves](http://people.cs.aau.dk/~normark/prog3-03/html/notes/fu-intr-2_themes-hilbert-sec.html#fu-intr-2_hilbertprog_title_1)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 38 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
U1¦U;$;;UN$
Ll2’ð⁽Ƭb3’s2Ç⁸¡⁵DW¤;+\Ḋœị
```
A monadic Link accepting a square matrix of side \$2^n\$, \$n\$ a positive integer which yields an array of the inputs elements in Hilbert curve order.
**[Try it online!](https://tio.run/##HY@tTsRAFIX9PsWIdVTs/ZlhN7VIgmsQpYYEQ@pQOGqWBCQKSUJQCAzJJgTThgfZvsjwTcXJzT33nG/a25u@v8@5kfGjqdd13VysV@e9zg@v09c8/E778fPa2O50epyHw/g2D99nl@N7fXJ1PDz9vRx/nnPObRukCsFRRKkKcVeFtEH4ybtV1QblYmiLTkkwIzPhJysJoSuFQVfoRvZYWDDiZkmwCQyhI8UlHdkju@@WBESBbFwN17gaKcf3bUkoZOEFY2qZMI2XnOlxSdBVOoqrhVW6pB3fl39RyApZ6ShXKylYXr7Duu4f "Jelly – Try It Online")**
### How?
First we create `[row, column]` index deltas describing the U shape with an initial right move (i.e into the \$n=1\$ matrix's top-left corner from the left) - that is `[[0, 1], [1, 0], [0, 1], [-1, 0]]`.
Then we repeatedly perform a transform keeping the current list of deltas to describe the bottom-right quarter of the next and adding the other three quarters as copies with reversed deltas (swapping row changes with column ones where necessary and negating directions of the new top-right quarter).
Finally we prepend a starting index of `[1,0]` (to the left of the top-left of our [1-indexed] matrix), cumulatively reduce by addition to get the indexes, discard the `[1, 0]` and index into the input.
### How?
```
U1¦U;$;;UN$ - Link 1, transform deltas to next size: list of current deltas
U1¦ - reverse the first delta (makes bottom-left)
U;$ - reverse each of those and concatenate with that (adds top-left)
; - concatenate with the input (adds bottom-right)
UN$ - reverse each of the input deltas and negate (makes top-right)
; - concatenate (adds top-right)
Ll2’ð⁽Ƭb3’s2Ç⁸¡⁵DW¤;+\Ḋœị - Main Link: square matrix (of side 2^n), M
L - length of M
l2 - log base 2 (=n)
’ - decrement
ð - start a new dyadic chain (i.e. f(n-1, M))
⁽Ƭ - compressed literal = 4258
b3 - to base 3 = [1,2,2,1,1,2,0,1]
’ - decrement = [0,1,1,0,0,1,-1,0]
s2 - split into twos = [[0,1],[1,0],[0,1],[-1,0]]
¡ - apply repeatedly...
⁸ - ...number of times: chain's left argument, n-1
Ç - ...what?: last Link as a monad
- - gets all deltas
¤ - nilad followed by link(s) as a nilad:
⁵ - literal ten
D - to decimal digits = [1,0]
W - wrap = [[1,0]]
; - concatenate with the deltas
+\ - cumulative reduce using addition (N.B. Ä wont work here)
Ḋ - dequeue (drop the [1, 0] leading index)
œị - multi-dimensional index into M
```
] |
[Question]
[
Dina loves most numbers. In fact, she loves every number that is not a multiple of n (she really hates the number n). For her friends’ birthdays this year, Dina has decided to draw each of them a sequence of n−1 flowers. Each of the flowers will contain between 1 and n−1 flower petals (inclusive). Because of her hatred of multiples of n, the total number of petals in any non-empty contiguous subsequence of flowers cannot be a multiple of n. For example, if n=5, then the top two paintings are valid, while the bottom painting is not valid since the second, third and fourth flowers have a total of 10 petals. (The top two images are Sample Input 3 and 4.)[](https://i.stack.imgur.com/2SnZt.png)
Dina wants her paintings to be unique, so no two paintings will have the same sequence of flowers. To keep track of this, Dina recorded each painting as a sequence of n−1 numbers specifying the number of petals in each flower from left to right. She has written down all valid sequences of length n−1 in lexicographical order. A sequence a1,a2,…,a(n−1) is lexicographically smaller than b1,b2,…,bn−1 if there exists an index k such that ai=bi for i < k and ak < bk.
***What is the kth sequence on Dina’s list?***
**Input**
The input consists of a single line containing two integers n (2≤n≤1000), which is Dina’s hated number, and k (1≤k≤1018), which is the index of the valid sequence in question if all valid sequences were ordered lexicographically. It is guaranteed that there exist at least k valid sequences for this value of n.
***Output***
Display the *k*th sequence on Dina’s list.
```
Sample Input 1
4 3
Sample Output 1
2 1 2
```
---
```
Sample Input 2
2 1
Sample Output 2
1
```
---
```
Sample Input 3
5 22
Sample Output 3
4 3 4 2
```
---
```
Sample Input 4
5 16
Sample Output 4
3 3 3 3
```
[Answer]
## Haskell, 87 bytes
```
n#k=[d|d<-mapM id$[1..n]<$[2..n],all(\x->mod x n>0)$p d]!!k
p(x:y)=scanl(+)x<>p$y
p x=x
```
Uses 0-based indexing. Needs the latest version of `Prelude` which is not installed on TIO, hence an additional `import`.
[Try it online!](https://tio.run/##Vce7DoIwFADQna@4pB0gCoFGFkOZXJ0ckeHGEm3o4wYwKYn/XuOG08l54TKNxkRtyc8rXHDF8jZa/Zz9m6Jjk@zVR7WFRbqCVryvy9INLe/FzyMak91D0VmvIIDrqpwTqCFNp4SycN5yuTzQmeyQh7YjviUEQYZoUTuQoHwCQLN2K3A4MbGbYNVuDRP1X@smfgE "Haskell – Try It Online")
```
d|d<-mapM id$[1..n]<$[2..n] -- keep all 'd' from the lists of numbers [1..n] of
-- length n-1
, all(\x-> ) -- where all elements 'x' from
p d -- the sums of the subsequences of 'd'
mod x n>0 -- are not a multiple of n
[ ]!!k -- pick the 'k'th element
p(x:y)=scanl(+)x<>p$y -- the sums of subsequences are calculated by
-- prepending the cumulative sums of the list to
-- a recursive call with the tail of the list
p x=x -- base case for recursion: empty list
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
’ṗ`Ẇ§%ẠʋƇ⁸ị@
```
A dyadic Link accepting `n` on the left and `k` on the right.
**[Try it online!](https://tio.run/##ASkA1v9qZWxsef//4oCZ4bmXYOG6hsKnJeG6oMqLxofigbjhu4tA////Nf8yMg "Jelly – Try It Online")** (no way this will work for large n, but would in theory)
### How?
```
’ṗ`Ẇ§%ẠʋƇ⁸ị@ - Link: integer n, integer k
’ - decrement n -> n-1
` - use for both arguments of:
ṗ - Cartesian power (all (n-1)^2 flower sequences - lex order)
⁸ - chain's left argument, n (as right argument for...)
Ƈ - filter keep those (sequences) which are truthy under:
ʋ - last four links as a dyad (f(sequence, n)):
Ẇ - all ((n-1)n/2) contiguous sublists (of the sequence)
§ - sum each
% - modulo (n)
Ạ - all? (all non-zero?)
@ - with swapped arguments (i.e. f(k, listOfValidSequences)
ị - index into (1-based)
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~74~~ 68 bytes
```
{([X] (1..^$^a)xx$a-1).grep(!*[^*X.. ^*].grep:{$_&.sum%%$a})[$^b-1]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1ojOiJWQcNQTy9OJS5Rs6JCJVHXUFMvvSi1QENRKzpOK0JPTyFOKxYsYlWtEq@mV1yaq6qqklirGa0Sl6RrGFv7vzixUiFNw0THWNOaC8I20jGEs011jIyQOIZmmtb/AQ "Perl 6 – Try It Online")
Anonymous code block that returns a list of numbers, or an integer in the case of \$n=2\$.
### Explanation:
```
{([X] (1..^$^a)xx$a-1).grep(!*[^*X.. ^*].grep:{$_&.sum%%$a})[$^b-1]}
{ } # Anonymous code block
([X] (1..^$^a)xx$a-1) # From all n length sequences of 1 to n-1
.grep( ) # Filter by
! .grep:{ } # None of
*[^*X.. ^*] # All partitions (including empty lists)
$_ # Are non-empty
&.sum%%$a # And the sum is divisible by n
[$^b-1] # Get the kth index of the list
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes
```
NθI↨§Φ…Xθ⁻θ²Xθ⊖θ¬ΦθΦλ¬﹪Σ✂↨ιθνλ¹θ⊖ηθ
```
[Try it online!](https://tio.run/##TY05DsIwEEX7nMLlWDIFS5eKRUgpEkXkBMYZEUteiGMDtzc2IYju6/83b8TAnbBcxViZe/BN0Fd0MNKyaJ00Ho588nDgE8LeV6bHF5yl8gm5cHNDaO0z44zU0oQphw2ljPzqEwqHGo3HPknz1Fi/KNL@TWrua9sHZaELGjolBc6PJSNjOjSMJGydHdlEP7Z//7BMZYy7YhtXD/UG "Charcoal – Try It Online") Link is to verbose version of code. Works by taking the range \$ n^{n-2} \ldots n^{n-1}-1 \$ in base \$ n \$ and filtering out illegal sequences (including ones with zero digits). Explanation:
```
N Input `n` as a number
θ Save in variable
θ `n`
X To the power
θ `n`
⁻ Minus
² 2
… Ranged up to
θ `n`
X To the power
θ `n`
⊖ Decremented
Φ Filtered `i` by
¬ Not
θ Implicit range `0` .. `n-1`
Φ Filtered `l` by
λ Implicit range `0` .. `l`
Φ Filtered `m` by
¬ Not
Σ Sum
ι `i`
↨ Converted to base
θ `q`
✂ Sliced
ν From `m`
λ To `l`
¹ Step 1
﹪ Modulo
θ `n`
§ Indexed by
η Second input `k`
⊖ Decremented
↨ Converted to base
θ `n`
I Cast to string
Implicitly printed
```
] |
[Question]
[
Given an inconsistently indented piece of html code your task is to return the same text but correctly indented
* Indent space = 4
* Assume input will be non-empty.
* Input can be taken as string or array/list of lines
* Opening and closing tags must be on the same line as long as there is not any other tag inside. `<td></td>`
* Assume there will be only html tags, no text elements whatsoever
* All opening tags that aren't self-closing will have closing tags, and will be given in the correct nesting order. Self-closing tags will be closed with `/>`
* Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply
**Example and test-cases**
```
Input
--------------
<table>
<tr>
<td>
</td>
<td></td></tr></table>
Output
----------
<table>
<tr>
<td></td>
<td></td>
</tr>
</table>
```
---
```
Input
------------
<div>
<ul>
<li></li><li></li></ul>
<ul>
<li></li>
<li></li>
</ul><div><table>
<tbody>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</tbody></tbody></table>
</div>
</div>
Output
--------------------
<div>
<ul>
<li></li>
<li></li>
</ul>
<ul>
<li></li>
<li></li>
</ul>
<div>
<table>
<tbody>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</tbody>
</table>
</div>
</div>
```
---
```
Input
--------------
<div><img src=""/><p></p><input/><input/></div>
Output
-------------
<div>
<img src=""/>
<p></p>
<input/>
<input/>
</div>
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 101 bytes
```
L`<.*?>
T`¶`_`<(.+)¶</\1
^.+
$&/
{`(( *)((?!.*(</|/>)))?.+)/¶(.+)
$1¶$2$#3*4* $5/
(</.+>/)
$1
/$
```
[Try it online!](https://tio.run/##jVDBasMwDL3rKzJqiu2ARbb2Jpwf2HHHsTnFgQbCBsUtlO678gH5scyKWeqWHqaD9Cy992T70Ibuq6mm6dWR0bWFNzcO7tORNKUaB8L3Cj5MCWKNcHFSFlpJWT8ZLQl/0Cql6kjEcWA@iGocxLNYveiNLsQWoYgRmaa0yFNAAdNEvjvZeXQNOvYWqO8sIacFIPdvSHe6PyZkiEXzEgrNrm8tAIXdtz@zmMK@bXxEFA6Zc9hHcUyZ/aMetzET8jzZMT/tWIwpeDbw96fk8F8aJtuspjctN5h/M5Vf "Retina – Try It Online") Explanation:
```
L`<.*?>
```
List just the tags.
```
T`¶`_`<(.+)¶</\1
```
Join matching pairs of tags.
```
^.+
$&/
```
Add a marker to the end of the first line.
```
{`(( *)((?!.*(</|/>)))?.+)/¶(.+)
$1¶$2$#3*4* $5/
```
Copy the indentation from each line to the next, adding 4 spaces if the current line is an opening tag.
```
(</.+>/)
$1
```
But if the next line (which is now the current line) is a closing tag then delete 4 spaces.
```
/$
```
Delete the marker once it reaches the last line.
[Answer]
# [Python 2](https://docs.python.org/2/), 170 bytes
```
def f(o,i=-4):
s,c,n,h,l=" <\n "
for t in"".join(o.split()).split(c):
if'/'==t[:1]:i-=4;h+=(n+i*s)*(l!=t[1:])+c+t
else:h+=n+i*s+c+t;i+=4-4*('/'in t);l=t
print h[4:]
```
[Try it online!](https://tio.run/##jVDLbsMgEDyHr6BcAn7ESuQTBv9I6kNibEGFwLK3lfL1Ltit5UQ9lMPuMrMzCzs8QHt3mWfV9binPjMyLxlHeMrazGU6s5Jg8e4wJgj3fsSAjSPk9OGNo/40DdYAZeynaIPyYPpjcZQSrvzccJPLstKppC41ycQSat8Cc@YNS9sU0KGzU8cDv9ARqkwqy7xMaDAxDgOrrASEh9E4wPpa8mbuKSFEKPNVI/x0xKetkbCmFkUMW1FE/KnpRffbiXZVFC1DBNzutqsREnD36hHFAnR3U6ESMO6cQQdxCDv7v7AIFzth5Fe72L/O2IwFqGigXm@rw3/bitV2l9c/bS9YtrmmsFw2fwM "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 174 bytes
```
import re
def F(I):
m=x=0
n,s,b='\n/<'
for d in re.findall(r'<(.*?>)',I):
if d[0]==s:print(n+' '*~-m*4)*x+b+d,;m-=1;x=1
else:print n+' '*m*4+b+d,;x*=s in d;m+=not s in d
```
[Try it online!](https://tio.run/##jZFNbsMgEIXX4RQjb/ybkFRdxeDuIvUMbRd2wTUSYAuTytn06i4U1XWiLmKJmWH43gPMcLFdrx/mWaihNxYMR4y3cEqe0yMCRSe6R6CLsWho/KoxiRG0vQEGQjt21wrNaikTE5Nklz1VaVx44Ua0wF72b5SOx8EIbROdxxBnX1uVPabZlDc5K0q1pYdyoge04XLkAYQAOiwwU0ZHvxcrVU51byHM5lMSRRFh4rMKQagPGM07jSJckaEi2A2hh7PFfxl7EsHVR86yQkQKt@rDUmDfv4JudL8kWlVeFI5j60byCiFim55dvJjYjtfMVcSalbPtnNiFlf1/Pd/GK6FfD3aeD3ssxsQyb8BuZ8HhXgwH21UOd1pO8PM3Q3Jvkc7f "Python 2 – Try It Online")
[Answer]
# JavaScript 115 Bytes
```
s=>(n=c=-1,m=f=>"\n"+" ".repeat(4*c)+f,s.replace(/<\/?|\/>/g,w=>w[1]?(n?k=m(w):k=w,n=1,c--,k):m(w,n=0*c++)).trim())
```
I lost the original code so whoops no explanation on this one. It's short though so think of it as a reversing challenge :)
Adds some newlines, but it is correctly tabbed.
[Answer]
# PHP, 141bytes
```
preg_match_all("%(<.*>)%U",$argn,$m);foreach($m[1]as$t)echo!$p|($p=$t[1]!="/")?str_pad("\n",($t[-2]!="/"?$p?++$i:$i--:$i+!$p=0)*4-3):!$i--,$t;
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/abe368d34ca1f4f67d3fe52839aedb04dc2356cf).
] |
[Question]
[
A while ago, I posted a challenge asking to determine whether or not it's possible to arrange arbitrary rectangles to fill a rectangular space, [here](https://codegolf.stackexchange.com/q/96901/42649). That got answers, so clearly it was too easy. (Just kidding, it was fairly challenging, congrats to the answerers :D)
# Challenge
Given a bunch of arbitrary shapes (consisting of 1x1 square tiles) (up to 100 with a combined area of at most 1000), can you arrange them to fill a rectangular space, without rotations or reflections?
A shape is valid as input if it has at least 1 tile and all tiles are connected to each other by edges. For example:
Valid:
```
XXX
X X
XXX
```
Invalid:
```
XXX
X
XX
```
The shapes will be represented in input by using a non-whitespace character `X`, spaces, and newlines. Individual shapes will be separated by two newlines (i.e. split on `\n\n`). You can choose to use LF, CR, or CRLF as a newline. Alternatively, you can choose to use LF or CR as a single newline and CRLF as a double-newline for separating shapes. Please specify in your answer what you choose.
For example, this would be the input format for a 2x2 square and a 3x3 "donut":
```
XX
XX
XXX
X X
XXX
(Optional trailing newline or double-newline)
```
The output should be either any truthy value or a consistent falsy value (but not an error). For example, you may output the valid arrangement if one exists or false, but you cannot error if there is no valid arrangement, neither can you output different values for having no valid arrangement.
# Test Cases
## Test Case 1
```
XXXX
X X
XX X
X
X
X
TRUE
```
Valid Arrangement:
```
XXXX
XYYX
XXYX
```
## Test Case 2
```
XXXX
XX
X
FALSE
```
## Test Case 3
```
XXXXXX
X X X
X XXX
XX
X
X
X
TRUE
```
Valid Arrangement:
```
XXXXXX
XYXZZX
XYXXXA
```
## Test Case 4
```
XX
X
X
XX
XXX
X
X
X
TRUE
```
Valid Arrangement:
```
XXYZ
XYYZ
AAAZ
```
# Notes
* Each shape must be used exactly once in the arrangement
* Shapes may not be rotated or reflected
* The input can contain multiple identical shapes; in this case, each of those still needs to be used exactly once; that is, if two 5x3 rectangles are given in the input, two 5x3 rectangles must appear in the arrangement
[Answer]
# [Python 2](https://docs.python.org/2/), 434 bytes
```
lambda s:F([[' ']*sum(map(lambda s:len(s[0]),s)) for _ in' '*sum(map(len,s))],s)
L=len
R=range
def F(a,s):
if not s:return len(set(tuple(l)for l in a if'X'in l))==len(set(tuple(l)for l in zip(*a)if'X'in l))==1
c=s[0];h,w=L(c),L(c[0])
for i in R(L(a)-h):
for j in R(L(a[0])-w):
T=1;A=[l[:]for l in a]
for y in R(h):
for x in R(w):
C=c[y][x]
if C>' ':T&=A[y+i][x+j]<'!';A[y+i][x+j]=C
r=T and F(A,s[1:])
if r:return r
```
[Try it online!](https://tio.run/##dZAxb8IwEIVn/CuuS22DkUrHpK6EkJiYEEMk16pcSEpQMJETBOmfT8@GQJHSDLbv7r3PLy6benuwr20mP9rC7L82BqpozpSiQPWwOu7Z3pTsNilSyyr1ormoOIfs4OATcovauzS1fqZxIQuJFVlKZ@x3SjZpBnNmcBARyDOwhxqJLq2PzkIApzWrj2WRsoJ7dIFoMCilCcVTwbmU/@p@8pINDX8QTwispY8bb8VJLtiaC1x8fBKy5964ZAtm@HiLqQa@ubs1vXB88n1YyUk8lapQkb4n0zjwVXNxBEJAnC@NYB3ATK5Vo9VZ@wL/e/aO7xWtnuVUNaMcB6OdfqNPNP5TyxmynVyBsRt8tKmo1CTC2AHgukdzbelyW0PGFFE0wY8KmgCELcFNC9/3VXfUCCF9LrTdNKRPdIV3eMBG5@i9qAcSfBfBNWMHeCCIq739BQ "Python 2 – Try It Online")
Takes input as a list of lists.
Returns `True` or `None`
Assumes that each line in a shape is padded to the length of that shape.
(based on my [answer](https://codegolf.stackexchange.com/a/146642/38592) to [Do the figures fit?](https://codegolf.stackexchange.com/questions/110921/do-the-figures-fit))
] |
[Question]
[
**This question already has answers here**:
[Dames, do some math!](/questions/61463/dames-do-some-math)
(2 answers)
Closed 7 years ago.
Scrolling through social media, one might encounter something like this:
[](https://i.stack.imgur.com/U880i.jpg)
We can see that, following PEMDAS order of operations, the answer is clearly 1*1* 9.
For the sake of this challenge, PEMDAS means that multiplication will occur before division, so `a/b*c = a/(b*c)`, not `(a/b)*c`. The same goes for addition and subtraction. For example, using PEMDAS, `1-2+3 = -4`, but using PEMDSA, `1-2+3 = 2`.
However, the answer quickly changes if we use some other order of operations, say PAMDES: now the answer is 1*2*.
### The challenge
Given an expression and an order of operations, output the value it equals.
### Input
The input will contain two parts: the expression and the order of operations.
The expression will contain only `[0-9] ( ) ^ * / + -`. This means that it will contain only integers; however, you may not use integer division, so `4/3=1.33` (round to *at least* two decimal places), not `1`.
The order of operations may be taken in any reasonable format. For example, you may take a string array of operations (ex. `["()", "^", ... ]`), or something like `PEMDAS`. Parenthesis will always have the highest priority, and will therefore always come first in the input.
### Output
The inputted expression evaluated and rounded to at least two decimal places.
### This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
### Test cases
```
PEMDAS 4*3-2+1 = 9
PDEMAS 2*4^3+2 = 130
PMDASE 17^2-1*2 = 1
PSEMAD 32*14/15-12+5^3+1/2 = 1.736
PEMDAS 6/2*(1+2) = 1
PEDMAS 6/2*(1+2) = 9
PDMSEA 2*(1*13+4)^3 = 39304
```
1. No joke: many thought the answer was 1.
2. Here we are using the "for the sake of this challenge" PEMDAS rules.
[Answer]
# Maxima, ~~61~~ 67 bytes
```
f(O,E):=(for i:1 thru 5 do infix(O[7-i],i*20,i*20),eval_string(E));
```
A function that takes operators as a list of strings and the expression and returns the result.
[Try it online!](https://tio.run/nexus/maxima#@5@m4a/jqmllq5GWX6SQaWWoUJJRVKpgqpCSr5CZl5ZZoeEfba6bGauTqWVkACY0dVLLEnPii0uKMvPSNVw1Na3/cxUA2SUaaRrRShqaSjpK@kCsBcS6QBwHxNpKsTpKRloahlqGxtommnHGSkBdXP8B "Maxima – TIO Nexus")
Example:
```
f(["()","^","*","/","+","-"],"4*3-2+1");
```
result: `9`
] |
[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/105564/edit).
Closed 7 years ago.
[Improve this question](/posts/105564/edit)
**Preface**
The available keys are the keys of the A through G and A minor through G minor.
**The Challenge**
Create a program that creates and saves to a playable audio file a "song" of using (uniformly distributed) random chords. The song must be of length `n` and in key `k`. The chords in each "song" must conform to the key. If you don't know what belongs in a particular key, the image below may help.
[](https://i.stack.imgur.com/5Tgde.jpg)
**Rules and Guidelines**
* Must conform to key
* Chords must be chosen randomly with even distribution
* Assume each chord is held for 1 beat in 4:4 time at 120 bpm, therefore each chord lasts .5 seconds
* The same chord is allowed to be selected multiple times in a row, though it must be randomly
* The program should theoretically be able to generate a "song" of any positive time value
* Assume `n > 1` in all cases
* Input will be a length n (in seconds) and a key k as a major or minor key `A, Amin, B, Bmin, etc`
* Output must be in the form of a playable audio file
### Examples (as strings)
```
[key], [length] -> [output]
C, 1 -> Dmin, F
B, 6 -> D# min, C# min, F#, G# min, E, B, F#, C# min, C# min, D# min, E, G# min
```
[Answer]
# JavaScript (ES6) + [synth-js](https://www.npmjs.com/package/synth-js), 303 bytes
```
k=>l=>eval("for(m=/(.)(#?)(m?)/.exec(k),W=synth.WAV,w=new W,g=m[3]?[2,1,2,2,1,3,1]:[2,2,1,2,2,2,1],s=W.semitone(m[1]+4+m[2]),n=0;n<l*2;n++)for(r=Math.random()*7|0,c=i=g.reduce((u,h,j)=>u+(j<r)*h,0);c-i<12;c+=g[r++%7]+g[r++%7])w.writeNote({note:W.note(s+c),time:.5,amplitude:.25},[],1,c-i<9);w.toBlob()")
```
### De-obfuscated:
```
(key) => (length) => {
let match = /(.)(#?)(m?)/.exec(key),
W = synth.WAV,
wav = new W,
// if minor, use minor gaps else major gaps
gaps = match[3] ? [2, 1, 2, 2, 1, 3, 1] : [2, 2, 1, 2, 2, 2, 1],
// get semitone index of scale root
semitone = W.semitone(match[1] + 4 + match[2]);
// 2 notes per second
for (let note = 0; note < length * 2; note++) {
// choose 1 of 7 random chords
let random = Math.random() * 7 | 0,
// get number of half steps from scale root to chord root
initial = gaps.reduce(
(sum, half, index) => sum + (index < random) * half,
0);
// of every tetrad, maximum of 11 half steps from root to 4th is possible
// tetrads composed of thirds, so add two gaps for every increment
for (let current = initial; current - initial < 12; current += gaps[random++ % 7] + gaps[random++ % 7]) {
// write note data as binary
wav.writeNote({note: W.note(semitone + current), time: .5, amplitude: .25}, [], 1, current - initial < 9);
}
}
// return blob of wav binary data
return wav.toBlob();
}
```
For those of you who might ask *"Why isn't* `new Audio(URL.createObjectURL(...))` *part of your byte-count?"*, [according to MDN](https://developer.mozilla.org/en-US/docs/Web/API/Blob):
>
> A `Blob` object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The `File` interface is based on `Blob`, inheriting blob functionality and expanding it to support files on the user's system.
>
>
>
Since this function returns a `Blob` with MIME-type `audio/wav`, it qualifies as a "playable audio file" as requested in the specification for the challenge.
## Demo:
```
f=
k=>l=>eval("for(m=/(.)(#?)(m?)/.exec(k),W=synth.WAV,w=new W,g=m[3]?[2,1,2,2,1,3,1]:[2,2,1,2,2,2,1],s=W.semitone(m[1]+4+m[2]),n=0;n<l*2;n++)for(r=Math.random()*7|0,c=i=g.reduce((u,h,j)=>u+(j<r)*h,0);c-i<12;c+=g[r++%7]+g[r++%7])w.writeNote({note:W.note(s+c),time:.5,amplitude:.25},[],1,c-i<9);w.toBlob()")
h=
()=>new Audio(URL.createObjectURL(f(k.value)(l.value))).play()
```
```
<script src=//unpkg.com/synth-js/dst/synth.min.js></script>
<input id=k value=B>
<input id=l value=1>
<button type=button onclick=h()>Play</button>
```
If you want to verify that all chords which can be randomly chosen are correct, here is a table of all possible chords below, given valid input:
```
function markup(key) {
let match = /(.)(#?)(m?)/.exec(key),
numerals = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII'],
gaps = match[3] ? [2,1,2,2,1,3,1] : [2,2,1,2,2,2,1],
semitone = synth.WAV.semitone(match[1] + 4 + match[2]),
string = ' ' + key + ':\n';
for (let root = 0; root < 7; root++) {
let initial = gaps.reduce(
(sum, half, index) => sum + (index < root) * half,
0),
index = root;
string += ' ' + numerals[root] + ': ';
for (let current = initial; current - initial < 12; current += gaps[index++ % 7] + gaps[index++ % 7]) {
string += synth.WAV.note(semitone + current) + ' ';
}
string += '\n';
}
string += '\n';
return string;
}
let keys = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
let html = '<pre>';
html += 'Major Scales:\n';
keys.forEach(key => {
html += markup(key);
});
html += 'Minor Scales:\n';
keys.forEach(key => {
html += markup(key + 'm');
});
html += '</pre>';
document.write(html);
```
```
<script src=//unpkg.com/synth-js/dst/synth.min.js></script>
```
] |
[Question]
[
### The Definition
Given an integer `x`, a version series is a set of digits (base 10) from which any `x`-length subset of consecutive members is unique compared to all other possible subsets of the same length (a unique "version").
### The Task
Write a function which, when passed some subset length `x`, produces a version series, considering a scoring determined by the sum of the total number of characters outputted by inputs 1 through 10 (so, `f(1) + f(2) + ... + f(10)`).
### Further rules
* The output must always be the same for a specific `x`.
* Please do not change your algorithm (except for corrections) after posting and try to avoid using others' work.
### Examples
Let `f(x)` be the function which returns the version series.
```
>>> f(3)
0010111
```
Note that this is a valid version series as all possible consecutive subsets of length 3 (`001`, `010`, `011`, `111`) are unique. This would obviously be a terrible score, however.
```
>>> f(3)
0123456789876543210
```
This is another valid version series, with a slightly better score. This is valid for the same reasoning as before.
```
>>> f(3)
001010011110111
```
This is clearly not valid; the subsets `001`, `010`, `101`, `111` all occur more than once.
### Trivia
I have referred to this as a version series as it may be used to identify a range of compatible versions by taking a larger subset of consecutive values within the full set to identify a range of compatible versions that lie therein.
### Verifier (in Java)
```
import java.util.Scanner;
import java.util.ArrayList;
public class Checker {
public static void main(String[] args) throws Exception {
int substringLength = Integer.parseInt(args[0]);
Scanner sc = new Scanner(System.in);
sc.useDelimiter("");
ArrayList<Character[]> active = new ArrayList<Character[]>();
Character[] current = new Character[substringLength],
compare, prev;
for (int i = 0; i < substringLength; i++) {
current[i] = sc.next().charAt(0);
}
for (int index = 0; sc.hasNext(); index++) {
for (int k = 0; k < index; k++) {
boolean differ = false;
compare = active.get(k);
for (int j = 0; j < substringLength; j++) {
differ = differ || compare[j].compareTo(current[j]) != 0;
}
if (!differ)
throw new Exception("Match found for subset " + index);
}
active.add(current);
prev = current;
current = new Character[substringLength];
for (int k = 1; k < substringLength; k++) {
current[k - 1] = prev[k];
}
current[substringLength - 1] = sc.next().charAt(0);
}
System.out.println("Input is a valid version series.");
}
}
```
Compile this as Checker.java, and call with `program <x> | java Checker <x>`, where `x` is your input (obviously, the input to your program is flexible).
If you are unable (or unwilling) to use Java, you may implement your own verifier, as long as you post it with your answer and show that it works.
[Answer]
# Python 2, score: 11111111155
Score: `sum(10**x+x-1 for x in range(1,11))`
This program obtains the maximum possible score for any given `x`.
```
def f(x):
s="0"*x
while 1:
for c in "1234567890":
p=s+c
if p[len(p)-x:]not in s:
s=p
break
else:
break
return s
```
[**Try it online**](https://repl.it/EeoR/2)
This takes a long time to run for large inputs (like 6), because it's building strings thousands or millions of characters long. It also maintains a set of substrings and checks if a possible next substring is contained in it. It's not very efficient. I first tried a recursive solution, as well as a solution with a fixed number of iterations or something, but this was my working one.
### Explanation:
I solved this by recognizing a pattern in the optimal solutions for `x=1,2`, which I created by hand as below. I roughly implemented the method I used to create `f(2)` in the function above, except that I just did zero last altogether.
```
1 0123456789
2 00102030405060708091121314151617181922324252627282933435363738394454647484955657585966768697787988990
```
This algorithm tries every number in order, with zero last. Failing to do zero last will result in an early termination. `f(2)`, for example, would stop at `00102030405060708090`, because all possible values starting with `0` have been exhausted. When doing this by hand, I simply started with `f(1)`, added zeros between each digit, then went to every combination starting with a `1` (leaving out zero), then twos (leaving out zero and one), etc. Essentially, the algorithm must try the digit that you started with last.
The score is `sum(10**x+x-1 for x in range(1,11))`.
I used this formula to compute the score, because the output for all values `1-10` would probably take many days (months?) to complete. The highest I received the output for was `f(6)`, which took ~10-15 minutes. It'd take at least 10000 times that for `f(10)`. The lengths of `s` and `p` go from `1` to `10**x`. The `for` loop runs exactly 10 times, no matter what.
### Output:
They are slightly different than above because zeros are done last:
```
1 0123456789
2 00112131415161718191022324252627282920334353637383930445464748494055657585950667686960778797088980990
3 000111211311411511611711811911012212312412512612712812912013213313413513613713813913014214314414514614714814914015215315415515615715815915016216316416516616716816916017217317417517617717817917018218318418518618718818918019219319419519619719819919010210310410510610710810910022232242252262272282292202332342352362372382392302432442452462472482492402532542552562572582592502632642652662672682692602732742752762772782792702832842852862872882892802932942952962972982992902032042052062072082092003334335336337338339330344345346347348349340354355356357358359350364365366367368369360374375376377378379370384385386387388389380394395396397398399390304305306307308309300444544644744844944045545645745845945046546646746846946047547647747847947048548648748848948049549649749849949040540640740840940055565575585595505665675685695605765775785795705865875885895805965975985995905065075085095006667668669660677678679670687688689680697698699690607608609600777877977078878978079879979070870970088898808998908098009990900
```
*I was going to make a pastebin of `f(6)`, but it's past the maximum size limit a guest can create.*
[**Validator**](https://repl.it/Eeql/1) - Counts how many unique subsets there are. If the result is `10**x`, it's correct.
[Answer]
# BruteForce
Tries to brute force every single possible combination using luck. Note that it does use the same seed all the time, so output is the same. Takes a single input in the `args` array to specify `i`.
```
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class BruteForce {
private static Random rand = new Random(123);
public static void main(String[] args) throws Exception {
int length = Integer.valueOf(args[0]);
List<List<Character>> used = new ArrayList<>();
StringBuilder out = new StringBuilder();
List<Character> put2 = new ArrayList<>();
for(int i = 0; i < length-1; i++) {
char one = (char) rand(48, 57);
out.append(one);
put2.add(one);
}
used.add(put2);
long last;
last = 0;
for(int i = length-1; ; i++) {
last = System.currentTimeMillis();
List<Character> put = new ArrayList<>();
do {
if(last+1000 < System.currentTimeMillis()) {
System.out.println(out.toString());
return;
}
put.clear();
for(int j = i-1; j >= i-length+1; j--) {
put.add(out.charAt(j));
}
put.add((char) rand(48, 57));
} while(used.contains(put));
used.add(put);
out.append(put.get(length-1));
}
}
public static int rand(int min, int max) {
return rand.nextInt((max - min) + 1) + min;
}
}
```
] |
[Question]
[
# Extended Train Swapping Problem
### Part 1: Normal Train Swapping Problem
In the 1996 CCC (Canadian Computing Competition), the first Stage 2 problem was a Train Swapping Problem. You can visit the link [here](http://cemc.uwaterloo.ca/contests/computing/1996/stage2/21a-prob.html "here"). Essentially, you have a bunch of numbered trains, and you want to find out how many train swaps you need to get them in order, and each train swap operation allows you to swap two adjacent trains. Since train carriages can run either way, nobody cares about the fact that the train carriages face the other way when swapped. This is pretty easy; all you need to do is:
>
> Find the number of steps to bubble-sort it; it's the most efficient sorting algorithm when you can only make adjacent element swaps
>
>
>
So, I made a harder one.
### Part 2: How this challenge works
Essentially, you can now swap more than just adjacent trains. With a longer rotating platform, you can swap the position of multiple trains. For example, with a rotating platform of length 4, you can swap both the inner and outer pairs at the same time, so `1 2 3 4` becomes `4 3 2 1`. Here are some examples for different rotating platform sizes:
```
Length 2:
1 2 3 4 5
---
1 3 2 4 5
Length 3:
1 2 3 4 5
-----
1 4 3 2 5
Length 4:
1 2 3 4 5
-------
4 3 2 1 5
```
Essentially, you're just inverting a sublist of the entire train. To clarify, in each move, you can only swap *exactly* `N` trains.
### Part 3: Specifications
## Input
Your input must take in two things: the length of the rotating platform, and the order of the train carriages. You may also require the number of train carriages if you wish. The order of the train carriages is given by an ordered list of numbers (each number representing a train carriage), so you can read the input as space-separated integers, newline-separated integers, an array, etc.
## Output
You must output the optimal (minimum) number of swaps needed to get the carriages all into the order `1 2 3 ... N`. If there is no solution, output `-1`, `No solution`, or some other consistent message. You may not output to stderr.
## Scoring
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so scoring is in bytes. The solution with the lowest number of bytes as of September 1st, 2016 will be the accepted one.
## Examples
**Problem 1**
**Input**
```
4
2
1 3 2 4
```
**Output**
```
1
```
**Explanation**
This is pretty trivial; with a rotating platform of length 2, it's the same as the normal train swapping problem. Swap the `2` and the `3`.
**Problem 2**
**Input**
```
4
3
1 3 2 4
```
**Output**
```
No solution (or an equivalent consistent message).
```
**Problem 3**
**Input**
```
9
3
1 4 5 6 3 8 7 2 9
```
**Output**
```
4
```
**Explanation**
```
1 4 5 6 3 8 7 2 9
-----
1 4 5 6 3 2 7 8 9
-----
1 4 5 2 3 6 7 8 9
-----
1 4 3 2 5 6 7 8 9
-----
1 2 3 4 5 6 7 8 9
```
[Standard loopholes apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
Good luck!
**EDIT 1**: Made the input format more flexible. Thanks to @Mego!
**EDIT 2**: Clarified that a rotating platform of length 4 swaps both the inner *and* outer pairs. Thanks to @TimmyD!
**EDIT 3**: Clarified that you must make permutations of length `N` exactly, not at most. Thanks to @Zgarb!
[Answer]
# Perl, 120 bytes
Includes +6 for `-Xapi` (`-` and space are counted too because both the `-i` and the `$'` in the code make it impossible to combine the options with `-e`)
Run with the input on STDIN and the platform length after the `-i` option, e.g.
```
perl -Xapi3 trains.pl <<< "1 4 5 6 3 8 7 2 9"
```
Prints `-2` if there is no solution
`trains.pl`:
```
1until$_=$n++*$z{pack"W*",@F}||-!grep!$z{$_}++&&/.{$^I}(??{!\$z{$`.reverse($&).$'}})$/s,keys%z,pack"W*",1..@F;$_--
```
if `N <= 9` then you can gain 5 more bytes:
```
1until$_=$n++*$z{join"",@F}||-!grep!$z{$_}++&&/.{$^I}(??{!\$z{$`.reverse($&).$'}})$/,keys%z,join"",1..@F;$_--
```
] |
[Question]
[
## Introduction and Motivation
I'm mainly active on [Cryptography.SE](https://crypto.stackexchange.com/) and as such have already stumbled across the question: "How the hell am I supposed tools like cado-nfs to *do* stuff!?". They are super-complicated tools for a super-complicated task: [Factoring](https://en.wikipedia.org/wiki/Factorization) large integers and computing large-scale [discrete logarithms](https://en.wikipedia.org/wiki/Discrete_logarithm).
Now I'm standing here (in a metaphoric sense) and I am asking you:
Please give us poor cryptographers a usable tool. :(
This question in particular is about the *discrete logarithm problem* which was broken by [Logjam](https://security.stackexchange.com/a/89702/71460), is frequently used in the world of online security and you're supposed to solve it (as far as current technology goes)!
## Specification
### Input
Your input will be three (potentially) large numbers: A [generator](https://en.wikipedia.org/wiki/Generating_set_of_a_group), a [prime](https://en.wikipedia.org/wiki/Prime_number) and an argument. The integer encoding should be hex or decimal big-endian. Additionally you may require arbitrary generator and prime dependent state (a bunch of pre-calculations and stuff). The generators, primes and arguments for the score evaluation will **not** be public. But there will be several arguments for one set of generators and primes so caching does make sense here.
### Output
The output is supposed to be one (potentially large) integer, the discrete logarithm of the argument to the base of the generator in the field defined by the prime. Additionally you may output intermediate state that will speed-up future calculations.
### What to do?
Using any library, tool and language you like (no online-services), hit the lowest time of execution for calculating the (correct) discrete logarithm. The parameters will be:
* There will be three pairs of random ([safe](https://en.wikipedia.org/wiki/Safe_prime)) prime and an appropriate (small) generator
* Each pair will receive three distinct (random) arguments, for the latter two, intermediate state will speed things up significantly
* The tests will be run on an [AWS EC2 c4.large instance](https://aws.amazon.com/en/ec2/instance-types/)
* The tests will use 332-bit (100 decimal digit) primes and arguments
### Who wins?
This is fastest-code so the fastest code wins!
Submissions are evaluated earliest three days after lack of activity (these evaluations cost money!) and clearly inefficient submissions will not be evaluated at all.
**OS:** The submittant has the choice between the default Amazon-provided OSes which are [Windows Server](https://en.wikipedia.org/wiki/Windows_Server) (2003 R2 - 2012 R2 Base), [Red Hat Enterprise Linux](https://en.wikipedia.org/wiki/Red_Hat_Enterprise_Linux) 7.2, [SUSE Linux Enterprise Server](https://en.wikipedia.org/wiki/SUSE_Linux_Enterprise_Server) 12 SP1, [Ubuntu Server](https://en.wikipedia.org/wiki/Ubuntu_(operating_system)#Ubuntu_Server) 14.04 LTS, [Debian 8 Jessie (community AMI)](https://en.wikipedia.org/wiki/Debian), [CentOS (6 or 7; community AMI)](https://en.wikipedia.org/wiki/CentOS) additionally the submittant *can* link to or provide instructions on using / creating a custom Amazon Machine Image (AMI) for testing
Installation instructions or links to those need to be provisioned.
## (Potentially) Helpful resources:
* [Cado-NFS](http://cado-nfs.gforge.inria.fr/)
* [The GNFS](https://en.wikipedia.org/wiki/General_number_field_sieve), the mainly used algorithm for this
[Answer]
Cado-nfs is the right tool to use.
It provides abstract enough way of handling any case, but relies on input specific optimizations that cannot be done by the program anyway.
There is no general (applicable to anything with same efficiency) solution (even theoretical one) for NFS that can be implemented in program at the moment.
Judging by the work done in CADO-nfs, simply coming up with a good enough algorithm for just 100 digit number would take several months of research before any programming can be done.
You should ask around on CADO-nfs forums, there were at least couple of tests mentioning 103-104-digit algorithms, that might be more useful.
If nfs is not a strict requirement, you could mention it in question.
Sadly, I cannot comment yet; and no, I am far from specialist in any of the areas.
] |
[Question]
[
In chemistry class, we were learning about titrations, and attempting one as a lab. We were using phenolphthalein as the indicator for the titration, so on top of grading the lab normally, my teacher held a little contest to see who had the lightest shade of pink, and thus the most accurate transition.
Your task is to write a program that acts like the teacher and judges the titrations.
# Specs
As input, you take a list of RGB triples in any sane format representing the titration of each student. ex: `["D966FF", "ECB3FF", "AC00E6"]`. You will be guaranteed that if converted to [HSL](https://en.wikipedia.org/wiki/HSL_and_HSV), the hue is `285` and the saturation is `100`.
The conversion for RGB to HSL lightness is the average of the max and min of the normalized RGB components (`*100` for a percentage).
Now the teacher is a human being and therefore cannot measure the lightness of the solution perfectly, so before you do any of the things described below, randomly change the lightness value of each of the titrations by `±3`, uniformly distributed.
If a titration has a lightness value greater than `94`, it is too light to visibly see that all the acid has neutralized. Therefore, the first output is a list, sorted in descending order, of all the titrations whose RGB triples, when converted to HSL, yield a lightness value less than 94. This represents the results of the contest.
The other output is a list of all the people who have failed the lab. This includes the people with the lightness values greater than `94`, but also people whose lightness values are less than or equal to `65` because these people's titrations are too inaccurate.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** win.
# Test Cases
*These test cases all assume that the error is always 0 for ease in checking if your program is correct. The results from your program should be different each time you run it.*
```
["D966FF", "ECB3FF", "AC00E6"] -> ["ECB3FF", "D966FF", "AC00E6"], ["AC00E6"]
["EDB8FF", "D761FF", "9100C2", "FBEFFF"] -> ["EDB8FF", "D761FF", "9100C2"], ["FBEFFF", "9100C2"]
["F5D6FF"] -> ["F5D6FF"], []
```
[Answer]
# Pyth, ~~35~~ 34 bytes
Input already converted to decimal.
```
L+O32+eSbhSbf<yTJ495Qf|gyTJ<yT347Q
```
[Test suite.](http://pyth.herokuapp.com/?code=L%2BO32%2BeSbhSbf%3CyTJ495Qf%7CgyTJ%3CyT347Q&test_suite=1&test_suite_input=%5B%5B217%2C+102%2C+255%5D%2C+%5B236%2C+179%2C+255%5D%2C+%5B172%2C+0%2C+230%5D%5D%0A%5B%5B237%2C+184%2C+255%5D%2C+%5B215%2C+97%2C+255%5D%2C+%5B145%2C+0%2C+194%5D%2C+%5B251%2C+240%2C+255%5D%5D%0A%5B%5B245%2C+214%2C+255%5D%5D&debug=0)
## Previous 35-byte version:
Input already converted to decimal.
```
L+O32+eSbhSbf<yT495Qf|gyT495<yT347Q
```
[Test suite.](http://pyth.herokuapp.com/?code=L%2BO32%2BeSbhSbf%3CyT495Qf%7CgyT495%3CyT347Q&test_suite=1&test_suite_input=%5B%5B217%2C+102%2C+255%5D%2C+%5B236%2C+179%2C+255%5D%2C+%5B172%2C+0%2C+230%5D%5D%0A%5B%5B237%2C+184%2C+255%5D%2C+%5B215%2C+97%2C+255%5D%2C+%5B145%2C+0%2C+194%5D%2C+%5B251%2C+240%2C+255%5D%5D%0A%5B%5B245%2C+214%2C+255%5D%5D&debug=0)
**Verify that the third testcase is not the same for each run.**
Sample input/output:
```
input:
[[217, 102, 255], [236, 179, 255], [172, 0, 230]]
output:
[[217, 102, 255], [236, 179, 255], [172, 0, 230]]
[[172, 0, 230]]
```
## Explanation
```
(max/255 + min/255)/2 + random[-0.03 .. 0.03] >= 0.94
(max/255 + min/255) + random[-0.06 .. 0.06] >= 1.88
max + min + random[-15 .. 15] >= 479.4
max + min + random[0 .. 31] >= 494.4
max + min + random[0 .. 31] >= 495
(max/255 + min/255)/2 + random[-0.03 .. 0.03] <= 0.65
(max/255 + min/255) + random[-0.06 .. 0.06] <= 1.30
max + min + random[-15 .. 15] <= 331.5
max + min + random[0 .. 31] <= 346.4
max + min + random[0 .. 31] < 347
L+O32+eSbhSbf<yT495Qf|gyT495<yT347Q
@memoized
L def y(b):
+O32 return random(range(32)) +
+eSb b.sort[-1] +
hSb b.sort[0]
f Q filter for elements in Q as T:
<yT495 y(T) < 495
(implicitly printed)
f Q filter for elements in Q as T
|gyT495 y(T) >= 495 or
<yT347 y(T) < 347
(implicitly printed)
```
Before you complain that it calls random three times, hence having inconsistent outputs from the function, note that the function is memoized.
Before you complain that different students with the same colour always produce the same outcome, note that the question never said that the random generator must be independent. It must only be uniform.
] |
[Question]
[
## Congratulations!
You have just been hired by a Fortune 499 company specializing in oil drilling.
Your job is to write a program to determine the optimum placement of OilRUs' drill (represented by a single alphabetical character of your choice, I use a capital "O" in the examples), given a length of piping, and a two-dimensional Ground Composition Analysis(Henceforth, "GCA") of the area.
However, due to the limited amounts of fossil fuels in the region, copious amounts of bureaucracy, and a recent influx of environmentalists, you must write your program in the fewest bytes possible.
Your program is expected to return the GCA with an Oil drill and piping in the optimal position, as defined below.
---
### Rules:
1. Input will be composed of an integer, followed by a new-line-separated GCA.
2. The GCA will be composed exclusively of the following characters, representing the surface, dirt, and oil respectively:
* =
* .
* ~
3. The first line of the GCA will always contain exclusively surface tiles, and all layers below that will contain a mixture exclusively of dirt and oil.
4. The GCA will be at least 4 lines of 3 characters, but will not exceed 64 lines of 256 characters each. Every input will contain at least one oil tile.
5. Multiple, adjacent oil tiles on the same row create a 'pool', where all tiles are collected if a pipe tile replaces any of them.
6. Every GCA will have at least one valid solution. See Clarification section for examples.
* For GCAs with multiple equivalent solutions, the solution closest to the surface wins.
* For GCAs with multiple equivalent solutions at the same depth, the one closest to the left-hand side wins.
* A single, larger pool with the same volume as multiple smaller ones are viewed as equivalent. For example, two pools of four tiles are equivalent to a single pool of eight tiles.
* Volume of oil retrieved outweighs the above three points. If a superior solution exists at a deeper level, or further rightward, that solution is to be the one returned by the program.
7. You may not use any purpose-created built-ins for finding oil reserves, whether they're supplied by OilRUs, WeDrill4U, or any third parties.
8. Your program must complete its execution within a reasonable time frame (~30 minutes or less).
9. Standard Loopholes apply.
---
### Clarification:
* The integer portion of the input represents the maximum number of pipes available. They do not all need to be used.
* Optimum position is defined in this challenge as the first valid place the drill can be set that intersects the largest amount of oil tiles/pools.
* Oil tiles replaced by pipe tiles are still collected, even though they don't show up in the output.
Rule 6 Examples:
```
Equal (assuming you were given 3+ pipes)
===== =====
..~.. .....
..~.. .....
..~.. ..~~~
```
But:
```
Loses Wins
===== =====
..... .....
..... .~~~. ** Solution closer to the surface. (Rule 6.1)
.~... .....
.~... .....
.~... .....
```
Also:
```
Wins Loses
===== =====
..... .....
..~~. ...~~ ** Solutions are at the same depth,
..~~. ...~~ ** but one is further left. (Rule 6.2)
..... .....
```
---
### Test Cases
Note: The text shown (denoted by the preceding two asterisks and continuing to the end of that line) in some of the test case outputs below is there for illustrative purposes only. Your program is not expected to print anything apart from OilRUs' drill, pipe, and the GCA.
Input:
```
4
===============================
..~~....~~.....................
~~........~~~...~~~~~~.........
.....~~~~.....~~~..~~..........
..............~~~...~...~~~..~.
..~~~..~~...~~.....~~....~~~...
.........~~..~...~~..........~.
.......~~...~......~~~.........
..~..........~...........~.....
.........~~.............~......
...~.........~~~~.........~....
...........~..........~........
```
Output:
```
================O==============
..~~....~~......|..............
~~........~~~...|~~~~~.........
.....~~~~.....~~|..~~..........
..............~~|...~...~~~..~.
..~~~..~~...~~.....~~....~~~...
.........~~..~...~~..........~.
.......~~...~......~~~.........
..~..........~...........~.....
.........~~.............~......
...~.........~~~~.........~....
...........~..........~........
```
---
Input:
```
2
===============
..~~~.~~.......
..~.....~~~~~~.
.~~~.....~~~...
..~~~..~~..~~~.
.~~...~~~....~.
```
Output:
```
========O======
..~~~.~~|......
..~.....|~~~~~.
.~~~.....~~~... ** Leftmost tile in pool (Rule 6.2)
..~~~..~~..~~~.
.~~...~~~....~.
```
---
Input:
```
5
===
~.~
...
~.~
```
Output:
```
O==
|.~
|.. ** Leftmost solution wins (Rule 6.2)
|.~
```
---
Input:
```
55
============
............
............
...~.~~..~..
..~~......~.
.....~~~....
..~~~...~~..
...~~~~~~~..
```
Output:
```
===O========
...|........
...|........
...|.~~..~..
..~|......~.
...|.~~~....
..~|~...~~..
...|~~~~~~..
```
---
Input:
```
6
============
............
............
..~~........
...~..~~~~..
............
...~........
```
Output:
```
======O=====
......|.....
......|.....
..~~..|.....
...~..|~~~.. ** Even though there is a solution closer to the left,
............ ** the solution highlighted here takes priority because it is
...~........ ** closer to the surface. (Rule 6.1)
```
---
[Answer]
# Java, 287 bytes
```
void a(int d,char[][]a){int b=a.length-1,c=0,e=d=b>d?d:b,f=0,i=0,j,k,g,h,l,m=a[0].length;for(;i<m;i++){g=0;h=0;for(j=1;j<=d;j++){l=0;for(k=0;k<m;k++)if(a[j][k]!=46)l++;else if(k<i)l=0;else break;g+=k==i?0:l;h=l>0?j:h;}if(g>c||g==c&&h<e){c=g;e=h;f=i;}}for(j=0;j<=e;a[j][f]=j++>0?'|':79);}
```
### Ungolfed
```
void gcaAnalysis(int pipes, char[][] soil) {
int soilDepth = soil.length - 1, bestCount = 0, bestDepth = pipes = soilDepth > pipes ? pipes : soilDepth, bestX = 0, x = 0, y, k, curCount, curDepth, curLayerCount, width = soil[0].length;
for (; x < width; x++) {
curCount = 0;
curDepth = 0;
for (y = 1; y <= pipes; y++) {
curLayerCount = 0;
for (k = 0; k < width; k++)
if (soil[y][k] != 46) curLayerCount++;
else if (k < x) curLayerCount = 0;
else break;
curCount += k == x ? 0 : curLayerCount;
curDepth = curLayerCount > 0 ? y : curDepth;
}
if (curCount > bestCount || curCount == bestCount && curDepth < bestDepth) {
bestCount = curCount;
bestDepth = curDepth;
bestX = x;
}
}
for (y = 0; y <= bestDepth; soil[y][bestX] = y++ > 0 ? '|' : 79);
}
```
### Note
* Well... this took half an alphabet of variable names, but it works i guess...
* Results are written back into `a` (aka `soil` in the ungolfed code).
### Output
```
================O==============
..~~....~~......|..............
~~........~~~...|~~~~~.........
.....~~~~.....~~|..~~..........
..............~~|...~...~~~..~.
..~~~..~~...~~.....~~....~~~...
.........~~..~...~~..........~.
.......~~...~......~~~.........
..~..........~...........~.....
.........~~.............~......
...~.........~~~~.........~....
...........~..........~........
========O======
..~~~.~~|......
..~.....|~~~~~.
.~~~.....~~~...
..~~~..~~..~~~.
.~~...~~~....~.
O==
|.~
|..
|.~
===O========
...|........
...|........
...|.~~..~..
..~|......~.
...|.~~~....
..~|~...~~..
...|~~~~~~..
======O=====
......|.....
......|.....
..~~..|.....
...~..|~~~..
............
...~........
```
] |
[Question]
[
The keypad on my office phone has the following layout:
```
[1] [2] [3]
/.@ ABC DEF
[4] [5] [6]
GHI JKL MNO
[7] [8] [9]
PQRS TUV WXYZ
[*] [0] [#]
+ _
```
### Task:
Write a program that, given an input string, returns a list of instructions that my fingers need to follow in order the type/dial the message/number.
### Rules:
* 3 fingers (1,2 & 3) start on keys [4], [5] and [6]. This starting position is 0.
* The only instruction a finger receives is its new relative location.
* Once a key has been pressed, that is the finger's new starting position. Fingers do not return to their 'home row'.
* Moving a finger up the keypad's column is -1, -2 or -3, depending on where it was last used.
* Moving a finger down the keypad's column is 1, 2 or 3, depending on where it was last used.
* Keeping a finger on the same key means there is no movement (0). It is not included.
* Words which require a double letter (like 'OO' in 'BOOK' or 'DE' in CODE) will need a pause (P) between letters.
* When using Pause, the finger is not specified.
* A finger can only press the keys in its own column (1,4,7,\*) (2,5,8,0) (3,6,9,#)
* Typing certain letters requires multiple keypresses. To type 'F', 3 needs to be pressed 3 times.
* Input is not case sensitive.
* Input characters not available on the keypad should be ignored. (Hyphens and parenthesis of a phone number, for example)
* Input will either be alpha or numeric - not a mixture - so no need to switch between input methods mid-stream.
* When entering numbers, Pauses aren't necessary.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins.
### Update
To slightly simplify matters, [\*] and [#] can be ignored. These will not feature in the input. But I'll buy you a beer if you do include them and get lowest byte count! (If you're in London ;-))
### Output:
A list of instructions, in the following format:
```
[direction] [finger_number] [new_relative_location], ...
```
Whitespace between instructions is optional.
### Test cases:
```
(123)-957 -> -11, -21, -31, 32, 21, 12
555-9273 -> 2,2,2,31,-21,11,-32
CODE GOLF -> -21,2,2, 3,3,3, -31, P, 3,3, 23, 1, 31,3,3, -22,2,2, -31,3,3
Code Golf -> -21,2,2, 3,3,3, -31, P, 3,3, 23, 1, 31,3,3, -22,2,2, -31,3,3
```
[Answer]
# Python 2, 423 bytes (no \*/# support)
```
k='/.@~ABC~DEF~GHI~JKL~MNO~PQRSTUV~WXYZ+~~~ '
d='123456789~0'
g={c:(i/12,i%12/4,i%4)for i,c in enumerate(k)}
g.update(((c,(i/3,i%3,0))for i,c in enumerate(d)))
del g['~']
def f(s):
s,a=[c for c in s[::-1].upper() if c in g],[]
q=[1,1,1]
while s:
y,x,r=g[s.pop()]
n,m,_=(9,9,9)if not s else g[s[-1]]
v=y-q[x]
q[x]=y
a+=[(v<0)*'-'+`x+1`+(v!=0)*`abs(v)`]+r*[`x+1`]+(c in k and(y,x)==(n,m))*['P']
print','.join(a)
```
[Answer]
### Java, 701
```
static void main(String a[]){int q[]={1,1,1},w[]={0,0,0},f=9,n=0,p=1,x,y,r,l=0,d;String c,i=String.join(" ",a),o="";i=i.replaceAll("[^A-Za-z0-9/.@*#+ ]+", "").toUpperCase();String[]v="1/.@|4GHI|7PQRS&2ABC|5JKL|8TUV|0 &3DEF|6MNO|9WXYZ".split("&");for(;l<i.length();){c=""+i.charAt(l++);for(x=0;x<3;x++)if(v[x].contains(c)){n=x;String[]b=v[x].split("\\|");for(y=0;y<b.length;y++)if(b[y].contains(c)) {w[x]=y;p=b[y].indexOf(c);}}if(f==n&&q[f]==w[f]){if(i.matches("[^0-9]+"))o+="P,";for(r=0;r<p;r++)o+=(f+1)+",";}else{d=w[n]-q[n];if(d!=0)o+=d;for(r=0;r<p;r++){o=new StringBuilder(o).insert(d==0?o.length():o.length()-1,n+1).toString();d=0;o+=",";}}q[n]=w[n];f=n;}System.out.print(o.replaceAll(",$",""));}}
```
### Completely unoptimised and ungolfed
A starting point
```
public class Keypad {
public static void main(String a[]){
int fingerRow[] = {1,1,1}, nextFingerRow[]=new int[3], finger=-1, nextFinger=0, repeat=1;
String input = String.join(" ",a), out="";
input=input.replaceAll("[^A-Za-z0-9/.@*#+ ]+", "").toUpperCase(); //strip nonsense
System.out.println(input);
boolean numbersOnly = input.charAt(0)>47 && input.charAt(0)<58;
String[] columns = "1/.@|4GHI|7PQRS&2ABC|5JKL|8TUV|0 &3DEF|6MNO|9WXYZ".split("&");
for (int l=0;l<input.length();l++) {
// current letter
String letter = ""+input.charAt(l);
// find finger
for (int i=0; i<3; i++) {
if (columns[i].contains(letter)) {
nextFinger = i;
// find row
String[] buttons = columns[i].split("\\|");
for (int j=0; j<buttons.length; j++) {
if (buttons[j].contains(letter)) {
nextFingerRow[i]=j;
repeat=buttons[j].indexOf(letter);
}
}
}
}
// both same && letter? Add Pause.
if (finger==nextFinger && fingerRow[finger]==nextFingerRow[finger]){
if (!numbersOnly) out += "P,";
for (int r=0; r<repeat;r++) {
out += (finger+1)+",";
}
}
else {
// work out previous to current
int distance = nextFingerRow[nextFinger] - fingerRow[nextFinger];
if(distance!=0) out+=distance;
// add finger
for (int r=0; r<repeat;r++) {
out = new StringBuilder(out).insert(distance==0?out.length():out.length()-1, nextFinger+1).toString();
distance=0;
out+=",";
}
}
fingerRow[nextFinger] = nextFingerRow[nextFinger];
finger = nextFinger;
}
System.out.println(out.replaceAll(",$",""));
}
}
```
### Sample run
```
CODE GOLF
-21,2,2,3,3,3,-31,P,3,3,23,1,31,3,3,-22,2,2,-31,3,3
```
] |
[Question]
[
It's almost Christmas, so Santa has to plan his route. You're helping him, for reasons unknown.
Santa needs help planning the route and wants you to give him a solution, but since you're all ungrateful and unwilling to give to the man who has given you so much, so have decided to give him a program with as few bytes as possible to accomplish the following.
The houses Santa needs to visit can be represented by coordinates on the Cartesian plane (the coordinates of the houses need not be integers, there cannot be more than 1 house at any point, and there is no house at the origin). These coordinates will be the input. Starting at the origin, Santa will visit each coordinate and then return to the origin.
Santa rides his sleigh at a constant one unit per second in a straight line between houses. However, when Santa crosses any lattice point (a point with integer x and y coordinates) he stops for one second to eat a cookie (the initial and final crossings of the origin do not count, though crossing it on the path between, say, `(-1,-1)` and `(1,1)` would). When he stops at a house, he spends five seconds to deliver a present (so he spends six seconds at houses on lattice points).
Write a program that takes as its input a set of coordinates and prints the **smallest** number of seconds Santa needs to deliver all of the presents to the houses and return to the origin, rounded to three digits. Take 25% off your code if it also prints any order of coordinates Santa visits that minimizes the time.
---
**Test cases**
```
(1,1) (2,4) (2,2)
==> 14.301
==> (Bonus) (1,1) (2,2) (2,4)
(3,4) (2,-1) (0,-3.5) (1,6)
==> 27.712
==> (Bonus) (0,-3.5) (2,-1) (3,4) (1,6)
```
This is code golf. Standard rules apply. Shortest code in bytes wins.
---
Note that this *is* a modification of the Travelling Salesman Problem, so your program does not need to terminate in any reasonable amount of time for an unreasonable number of inputs (this is a problem in O(n!) after all).
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 198 bytes (264 bytes - 25% bonus)
Managed to actually get this sucker into a Whatever block by inlining the helper functions from the original version.
```
*.permutations.map({([+] -1,5*@_,|(for (0,0),|@_ Z |@_,(0,0) ->((\i,\j),(\x,\y)){my ($s,\p)=0,i.Rat.nude[1]*j.Rat.nude[1]*abs(i -x).Rat.nude[0];(i+(x -i)*$_/p)%%1&&(j+(y -j)*$_/p)%%1&&$s++ for ^p;sqrt(abs(i -x)²+abs(j -y)²)+(p??$s!!abs(j.Int -y.Int))})),@_}).min
```
[Try it online!](https://tio.run/##VY7daoNAEIXvfYoJGJlxZ7ca2t5IGm9728uqEUsVVqrZugaUJC/VR@iLWU2hPzdzzvkGDseU3dv91IzgVbCFyVem7JpjX/T60FrVFAZPmIgMZMh3fpzzGatDBxhwQHyOc3iG@fI1g3xATDWnNTGmA6cj0WluRtdyamgbsFZPRa/a42uZhJlf/0vFi0UNcqBfGmQRaoEDSE2@m98YWq9Dz8Na4Aiy/stcKwQsy/Ymsu9djz91nx9i8TXIcfYk0Ox2rl2trlA9tv38WIToQsRxfiHV6HaKHFuMUCEkSchhxpBs@PZbNlkGFDnO9AU "Perl 6 – Try It Online")
No doubt there are still a few little improvements that can be made. Trickiest part was figuring out how to calculate the number of lattice points crossed. The solution I went with uses the denominators of each X coordinate to calculate an iteration interval that is guaranteed to hit each whole number along with X axis, thus allowing a check for landing on a lattice point. There is a catch, of course, that if there is no movement along X then the lattice points crossed will be the absolute value of the floor value of each Y coordinate.
This will be, nonetheless, very tricky for languages that don't have built in rationals, because of floating point errors (I can already see the .1 + .2 = .3 issue cropping up if any two X or Y coordinates are 10 apart).
Ungolfed version:
```
* # Whatever block, takes a list of coordinates
.permutations.map({ # Get all combinations and to each of them ...
( # Implicitly return a list consisting of
[+] # The sum of
-1, # -1 (to discount lattice +1 on return to origin)
5*@_, # 5 * number of coordinates (or stops)
|(for # each value in the loop across
(0,0),|@_ Z |@_,(0,0) # the coordinates (zipping with the origin
# first/last for the return)
->((\i,\j),(\x,\y)) { # deconstructing into i,j,x,y
my ($s,\p)=0, # set S (lattice stops) to 0
i.Rat.nude[1] # set P (x check interval) to denominator of i
*j.Rat.nude[1] # times denominator of p (psuedo lcm)
*abs(i -x).Rat.nude[0]; # times x-diff numerator (bc Rat simplification)
(i+(x -i)*$_/p)%%1&& # check X is whole, if so,
(j+(y -j)*$_/p)%%1&& # check Y is whole, if so,
$s++ # increment S (trip crossed a lattice point)
for ^p; # do the checks for 0 to P
sqrt( # implicitly return
abs(i -x)²+abs(j -y)² # the distance
)+(p # plus, if X values were different,
??$s # S value, else
!!abs(j.Int -y.Int) # Y difference = vertical lattice crossings
)
}
) #
,@_) # And the permutation
.min # Find best (smallest) time
```
I'll probably add a more readable version because this golfing got unreadable fast.
] |
[Question]
[
Write a program that fills in the paths of a grid of characters (ASCII 20-7E) according to the following rules.
The path is governed by eight directional characters: `-`, `|`, `/`, `\`, `&`, `@`, `%`, and `*`, as specified in the table below. The direction of the path will change when it reaches one of the eight above characters. Note that the direction the pointer is moving will always be on a line, forming an angle to the x-axis with radian measure `kπ/4` for integer `k`.
```
- Move right
| Move down
/ Move up/right
\ Move down/right
& Move left
@ Move up
% Move down/left
* Move up/left
```
The program starts at the top left of the grid, which is either `-`, `\`, or `|` and the pointer will move in the direction specified.
The objective of the program is to draw the path that the program takes by filling in whitespace according to the direction that the program is traveling. Any whitespace the pointer encounters is filled in, but if the pointer encounters a character not described above, the character is ignored (or put on the stack, if you choose to implement in the bonus).
The program ends when the pointer reaches the edge of the initial "box" the grid was in without hitting another directional character. This initial box does not contain any blank lines on the perimeter of the grid.
It should be noted that a specific point on the grid may change between the beginning and end of the program. For example, if the initial grid is `- &`, then by the time the pointer reaches `&`, the grid will be `--&`. Then the pointer will move one to the left, encounter `-`, and move to the right. It will not encounter an empty space, as the original grid suggests.
One of the things that might happen with this program is the appearance of infinite loops. Trivially, `-&` would be an infinite loop if the program were allowed to run indefinitely.` To counter this, your program must terminate within a reasonable amount of time.
The input to the program is a set of characters with a `-`, `\`, or `|` as the first character in the first line. There cannot be any trailing or leading newlines.
*Sample input*
```
- h %
| &( &f |
#
r @ )
5
```
*Sample output*
```
-----h-----%
|&&&(&&&&f% |
|# @%
| r @ )
5
```
---
**Bonus**
If your program prints the non-directional characters the pointer encounters separated from the modified grid by a newline, multiply your byte count by 0.9.
---
This is code golf, so standard rules apply. Shortest code in bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 347\*.9 = 312.3 bytes
```
def R(I):
i=x=y=F=V=0;h=len(I);w=max([len(j)for j in I]);I,m,n,E,e,C=[[k for k in j.ljust(w)]for j in I],-1,"","-|/\\&@%*","10011m11m00mm1mm",""
while 0<=x<w!=0<=y<h!=len(I)**4>i:
if I[y][x]==" ":I[y][x]=C
c=I[y][x]
if c in E:H=2*E.index(c);exec"F,V="+e[H]+","+e[H+1];C=c
elif c!=" ":n+=c
x+=F;y+=V;i+=1
for i in I:print"".join(i)
print n
```
[Try it online!](https://tio.run/##TU/BjoIwED3brxi70bRQWWp2L@BsTIxGrnvwghw2WEIRqlE2QOK/s4V1k22amffezOt0rl2dX8yy708qg08W8YCAxhY73OEB/TDHUhkrhw1WXy2LB1bw7HKDArSBKOFhJCphxFYoscE4PsNQPA/FwiuL73vNGp78M4iFFJQKuni8Ho/z9cyxWPq@lJW9vl9VsqqsRAk0uS4V@CtsV80Ube5W@fT5H8d5@9ABmegMorhL4jZBpECDP7IhkxSfZOxKh@nbYI9LZ@tpc1ItS3moWpXSnTggdVW8T1w7eACuTMINpmSiysE6HZ827qC0Lu7CzsVDqF2UZNxWj5sF15s2NaVecdGGaU5gFMD0n4zafRZgTz4EmJEHwJxZNM9seBB4GXUgv@kGawBO3q0tlkHi3a@lrhk9Gsp5/wM "Python 2 – Try It Online")
To comply with standard rules, a function is defined. The function's input is a list of strings representing the input (see the tio.run footer). Non-directional characters are printed, program terminates after a lot of steps (to halt on inputs like `-&`).
] |
[Question]
[
# Description
You, an armchair cryptanalyst, have noticed that the first letters of each word in your neighbor's mail (yes, you read it -- how else would you know if he's plotting something?) look very suspicious put together. To make sure that his mail is safe to send to its destination, you need to first decode these messages. You could check one or two, but your neighbor has many correspondences, and so you determine the best solution is to write a program to do the decoding for you.
Because you're sure that this neighbor is up to no good, you make your program assuming that most of the encoded words are actual words in English. You know that the backups of your backups of your backups are taking up a lot of room on your single drive (paranoia doesn't necessitate intelligence), and so you want to write this program in as little space as possible to minimize the space it takes up when you back it up thrice (it is important, after all).
---
# Description
You are to output what you think is the solution to a given [Affine Cipher](https://en.wikipedia.org/wiki/Affine_cipher). In short, Affine ciphers are encoded by the following formula for each character in the plaintext: `C ≡ aP + b (mod 26)` where `a` and `b` are constants, `C` is the ciphertext letter, and `P` is the plaintext letter. In this case, the letter "a" has the value of 0, "b" 1, and so on and so forth.
# Rules
1. With reference to my previous equation, in the ciphers you will be decoding `a` will *only* be a number coprime with 26.
2. For testing the validity of decoded words, you may use a dictionary of your choosing (note that "i" and "a" should be words listed; the validity of the other letters do not matter, but I recommend making only "i" and "a" valid).
3. If you choose to use a dictionary, you must be able to read from a text file and use it as a dictionary (i.e. you shouldn't be restricted to one dictionary). You may accomplish this by taking input of a filename and reading that file or hard-coding in a filename. This is so that every program can use the same dictionary for the test cases. This dictionary will be a text file with a word on each newline, all in lowercase.
4. In each message, if you are using a dictionary, you should account for **three** words not matching a word in English; any more and the decoding is wrong. If you are not using a dictionary, this number should be constant but may be different (so long as you obtain correct answers for the test cases). If there is no output with fewer than three wrong words, you are not to give an output.
5. When you output your decoding, you should output the one you think is most correct (i.e. the one that has the most English words).
6. If you do **not** use a dictionary, claim a `-100 byte` bonus on your submission.
7. When testing words to see if they are valid, check only contiguous alphabetical characters (e.g. you'd test `#affineciphers` as one word but `pa$$word` as two: `pa` and `word`). Words will not necessarily be of one case.
8. Your program must work for all of the test cases, but not be hardcoded for them. In theory, if I add another test case (one within reason), your program should be able to decode it.
9. Though it would be nice if you did so, optimizing for speed is unnecessary and will net you no bonuses.
10. Although I would like to test your program, it does not have to have a free or online interpreter.
11. If you do not use a dictionary, you may not read external files (i.e. the logic used to determine whether a word is a word in the English language or not must be contained within the program).
## Sample encoding
Here's a sample of encoding, done with simple numbers (`a = 3, b = 2`)
`foobar`
First, we express our input numerically
`6, 15, 15, 2, 0, 18`
Then we multiply by `a`
`18, 45, 45, 12, 0, 54`
Optionally reduce to least positive residue
`18, 19, 19, 12, 0, 2`
Add `b`
`20, 21, 21, 18, 2, 4`
Now we reduce to least positive residue (there is no reduction to do for this case, though) and convert to text
`tyyrbd`
## Input
You should be able to handle any characters, but the only encoded characters will be alphabetical ones (both capital and lowercase).
## Output
You should output what your program thinks to be the decoded cipher, with the case matching that of the input and any non-alphabetical character remaining (i.e. don't change the case and strip the input of non-alphabetical characters when you output)
---
## Test Cases
Input followed by expected output. [Here](http://pastebin.com/yJn7Mrgg) is the dictionary you are to use (if you are using one). Save it as `dictionary.txt` (or whatever you want, really), and input its name for testing. This dictionary should have almost all the words in the test cases, with some left out intentionally to test if your program will still output.
**Test Case 1:**
```
@nLWc@ wc! m neCN.
@tHIs@ is! a teST.
```
**Test Case 2:**
```
Yeq lkcv bdk xcgk ez bdk uexlv'm qplqgwskmb.
You lead the race of the world's unluckiest.
```
**Test Case 3:**
```
Ugifc ism ozsmvd kpync g fssw st ryceco sb estbcnny.
Maybe you should write a book on pieces of confetti.
```
**Test Case 4:**
```
Nh wrteq tfwrx, tgy t yezvxh gjnmgrxx stpgx / Nh xrgxr, tx qwzjdw zk wrnuzfb p wty yejgb, / Ze rnsqpry xznr yjuu zsptqr qz qwr yetpgx / Zgr npgjqr stxq, tgy Urqwr-vteyx wty xjgb.
My heart aches, and a drowsy numbness pains / My sense, as though of hemlock I had drunk, / Or emptied some dull opiate to the drains / One minute past, and Lethe-wards had sunk.
```
---
# Notes
The `-100 byte` bonus is subject to increase (i.e. more bytes will be subtracted) if I deem it to be too low. If it's not low enough (i.e. it's too much of a bonus), I will not change it provided that there are answers that have claimed it already.
I will add an ungolfed reference solution (to show how I would attempt the problem) if this question doesn't get any answers soon or if there is popular demand (let me know if you would like a reference solution).
[Answer]
# Java 8, 608
```
import java.nio.file.*;import java.util.*;import java.util.function.*;s->{try{List<String>d=Files.readAllLines(Paths.get("d"));int v=java.util.stream.IntStream.range(0,676).mapToObj(I->new int[]{I,(int)Arrays.stream(s.toLowerCase().split("[^a-z]+")).map(u->{char[]x=new char[u.length()];for(int i=x.length;i-->0;)x[i]=(char)(((u.charAt(i)-'a')*(I%26)+I/26)%26+'a');return new String(x);}).filter(d::contains).count()}).max((m,n)->m[1]-n[1]).get()[0],a=v%26,b=v/26;s.chars().forEach(h->System.out.print((char)(h>='a'&&h<='z'?((h-'a')*a+b)%26+'a':h>='A'&&h<='Z'?((h-'A')*a+b)%26+'A':h)));}catch(Exception e){}}
```
This is a bunch of imports, and then a lambda expression. Runnable, readable code follows:
```
import java.nio.file.*;
import java.util.*;
import java.util.function.*;
public class C {
static final Consumer<String> f = s -> {
try {
List<String> d = Files.readAllLines(Paths.get("d"));
int v = java.util.stream.IntStream.range(0, 676).mapToObj(I -> new int[]{I, (int) Arrays.stream(s.toLowerCase().split("[^a-z]+")).map(u -> {
char[] x = new char[u.length()];
for (int i = x.length; i-- > 0;) {
x[i] = (char) (((u.charAt(i) - 'a') * (I % 26) + I / 26) % 26 + 'a');
}
return new String(x);
}).filter(d::contains).count()}).max((m, n) -> m[1] - n[1]).get()[0],
a = v % 26,
b = v / 26;
s.chars().forEach(h -> System.out.print((char) (h >= 'a' && h <= 'z' ? ((h - 'a') * a + b) % 26 + 'a' : h >= 'A' && h <= 'Z' ? ((h - 'A') * a + b) % 26 + 'A' : h)));
} catch (Exception e) {
}
};
public static void main(String[] args) {
f.accept("@nLWc@ wc! m neCN.");
}
}
```
The dictionary should be stored in a file named "d", with no extension. One word per line.
] |
[Question]
[
Given a list of integer points in an *n*-dimensional space, output the [geometric median](https://en.wikipedia.org/wiki/Geometric_median). Note that the output is not necessarily integer. Your answer must be precise to at least two digits after the decimal point.
You may assume that *n* < 16 and that every component of each point fits in a 32-bit signed integer.
You may write a program or a function. You may take input and give output in any reasonable format. You may optionally pass *n* as a separate argument, instead of having to deduce it.
You must implement an algorithm to compute the geometric median, and not brute force over the output domain.
Examples:
```
(5), (14), (10), (7) -> any 7 <= x <= 10 is valid
(2, 3), (8, 4), (12, -3), (0, 0), (0, 0) -> (2.17, 1.29)
(0, 0, 3), (20, 7, 3), (13, 14, 15) -> (13.18, 7.94, 7.23)
(2, 20, 3, 30), (20, 2, 20, 2), (1, 2, 3, 4) -> (5.46, 5.12, 6.84, 8.06)
```
The answer is only unique if the set of points do not lie on a line. If the answer is not unique, you may return any valid answer.
[Answer]
# Matlab, ~~77~~ 75
I just use the definition of the geometric median with a numerical minimization. In this case I make use of the Nelder-Mead simplex algorithm. It sould always converge as we try to find the minimum of a convex function (according to Wikipedia).
```
n=@(m)trace((m'*m).^.5);f=@(m)fminsearch(@(y)n(bsxfun(@minus,m,y)),m(:,1))
```
Old version:
n=@(m)sum(diag(m'\*m).^.5);f=@(m)fminsearch(@(y)n(bsxfun(@minus,m,y)),m(:,1))
The input format is a matix with the input vectors as columns, e.g:
```
m = [[2; 20; 3; 30],[20; 2; 20; 2],[1; 2; 3; 4]];
```
] |
[Question]
[
## Brief
* Print an ASCII representation of a binary search tree.
* You should write your own minimum implementation logic of a BST (node, left, right, insert)
```
(50,30,70,20,80,40,75,90) gives:
__50__70__80__90
| |
| |__75
|
|__30__40
|
|__20
```
## Detailed requirements
* Items are inserted into the tree in the order in which they are in the list
* All node values are right aligned in columns.
* Right nodes are joined using `__`
* Right nodes are represented along the horizontal and appear directly to the right of the parent node
* Right nodes are separated by a minimum of 2 underscores (\_\_)
* Left nodes are joined using `|` and `|__` on the next line
* Left nodes are represented along the vertical and appear under and to the right of the parent (ie, next column).
* Left nodes are separated by a a minimum of a blank line (discounting pipes (|) linking child to parent)
* The vertical pipes joining 2 left nodes should be in the column directly under the last character of the parent node (see samples)
* Column width is determined using something like `max(col_values[]).toString().length() + 2`
* Branching left always adds a new row to the tree diagram
* 2 separate (left) branches never appear on the same line (right\_\_right\_\_right is OK)
* The root node may optionally be prefixed with `__` (Removing it just about doubled my test code!)
* Input is a set of positive and/or negative integers
* You do not need to deal with duplicate values (drop/ignore them)
* I'm not placing many restrictions on trailing whitespaces:
+ You may have trailing whitespaces after the last node on a line
+ You may have trailing whitespace after a `|` on the empty lines
+ No whitespace between nodes when when branching right
* Standard loopholes and T&Cs apply
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in bytes wins!
I'm aware that this is a potential duplicate, but I think I've been specific enough in my requirements that it should pose new challenges.
## Sample Input/Output
* Input
```
(50,40,30,20,10)
```
* Output
```
__50
|
|__40
|
|__30
|
|__20
|
|__10
```
* Input
```
(10,20,30,40,50)
```
* Output
```
__10__20__30__40__50
```
* Input
```
(50,700,30,800,60,4,5,10,20,2,500,850,900,950,870,35,1,-10)
```
* Output
```
__50__700__800__850__900__950
| | |
| | |__870
| |
| |___60__500
|
|___30___35
|
|____4____5___10___20
|
|____2
|
|____1
|
|__-10
```
[Answer]
# Java 1286 1106 1100 bytes
Here's an easy entry to beat ;-)
Pretty messy. I traverse the tree, populating a 2d array with the node values (and left branch pipes), and a size array with the maximum column widths. Then print the node array using size array to determine correct horizontal spacing. I look forward to seeing a better way of doing this.
```
class N{N l,r;int v,i,h,g,b,e,c,j;String[][]a=new String[10][10];int[]w=new int[10];String o="",p="";N(int x){v=x;}void i(int n){if(n>v)if(r==null)r=new N(n);else r.i(n);else if(n<v)if(l==null)l=new N(n);else l.i(n);}void p(N node){a[b][h]=""+node.v;if(w[h]<a[b][h].length())w[h]=a[b][h].length();if(node.r!=null){h++;p(node.r);h--;}if(node.l!=null){b++;while(g<b)a[++g][h]="|";h++;p(node.l);if(a[--g][--h].equals("|"))g--;}}void d(){for(e=-1;++e<a.length;){o="";for(j=-1;++j<a[0].length;){p=a[e][j];if(p!=null)if(p.equals("|")){for(i=0;i++<w[j]-p.length()+2;)o+=" "; o+=p;}else for(i=0;i++<w[j]+2;)o+=" ";else for(i=0;i++<=w[j]+1;)o+=" ";}if(!o.trim().equals(""))System.out.println(o);o="";for(c=-1;++c<a[0].length;){p=a[e][c];if(p!=null)if(p.equals("|")){for(i=0;i++<w[c]-p.length()+2;)o+=" ";o+=p;}else{for(i=0;i++<w[c]-p.length()+2;)o+="_"; o+=p; }else for(i=0;i++<=w[c]+1;)o+=" ";}if(!o.trim().equals(""))System.out.println(o);}}public static void main(String[]a){String[]q=a[0].split(",");N t=new N(Integer.parseInt(q[0]));for(int i=0;i++<q.length-1;)t.i(Integer.parseInt(q[i]));t.p(t);t.d();}}
```
```
__50__700__800__850__900__950
| | |
| | |__870
| |
| |___60__500
|
|___30___35
|
|____4____5___10___20
|
|____2
|
|____1
|
|__-10
```
**Ungolfed**
```
class N {
N leftNode, rightNode;
int index, loop, curRight, curDown, maxDown, row,col;
String[][] nodes = new String[10][10];
int[] colWidths = new int[10];
String line = "", node="";
```
`N(int index) {
this.index = index;
}
void i(int newValue) {
if (newValue > index) {
if (rightNode == null) {
rightNode = new N(newValue);
}
else {
rightNode.i(newValue);
}
}
else if (newValue < index) {
if (leftNode == null) {
leftNode = new N(newValue);
}
else {
leftNode.i(newValue);
}
}
}
void p(N node) {
// Push current node
nodes[maxDown][curRight] = ""+node.index;
// Keep track of max column widths
if (colWidths[curRight] < nodes[maxDown][curRight].length()) {
colWidths[curRight] = nodes[maxDown][curRight].length();
}
// Branch right
if (node.rightNode != null) {
curRight++;
p(node.rightNode);
curRight--;
}
// Branch left
if (node.leftNode != null) {
maxDown++;
while (curDown<maxDown){
nodes[++curDown][curRight] = "|";
}
curRight++;
p(node.leftNode);
if (nodes[--curDown][--curRight].equals("|")) { //following the ladder back up
curDown--;
}
}
}
void d() {
for ( row = -1; ++row < nodes.length;) {
// Sloppy. Inject extra rows to extend pipes (double spacing)
line = "";
for (int col = -1; ++col < nodes[0].length;) {
node = nodes[row][col];
if (node!=null){
if (node.equals("|")) {
for (loop=0; loop++< colWidths[col] - node.length() + 2; ){
line+=" ";
}
line+=node;
}
else {
for (loop=0; loop++< colWidths[col] + 2;){
line+=" ";
}
}
}
else {
for (loop=0; loop++<=colWidths[col]+1;){
line+=" ";
}
}
}
if (!line.trim().equals("")){
System.out.println(line);
}
line="";
for ( col = -1; ++col < nodes[0].length;) {
node = nodes[row][col];
if (node!=null){
if (node.equals("|")) {
for (loop=0; loop++< colWidths[col] - node.length() + 2;){
line+=" ";
}
line+=node;
}
else {
for (loop=0; loop++< colWidths[col] - node.length() + 2;){
line+="_";
}
line+=node;
}
}
else {
for (loop=0; loop++<=colWidths[col]+1;){
line+=" ";
}
}
}
if (!line.trim().equals("")){
System.out.println(line);
}
}
}
public static void main(String[]a){
String[] values = a[0].split(",");
N t=new N(Integer.parseInt(values[0]));
for (int i=0;i++<values.length-1;)
t.i(Integer.parseInt(values[i]));
t.p(t);
t.d();
}
}`
] |
[Question]
[
## Introduction
What you have to do is, given an an ASCII diagram of a chemical, output the chemical formula.
## Rules
Your code must not access the internet and may not use a stored library of molecules. You may have a library of elements.
You must verify all of the elements included in the formula are real, with all elements needed to be required found here:

If there are invalid elements in the formula, you must output: `Invalid elements in diagram`.
Order the formulae using the [Hill system](https://www.cas.org/training/stneasytips/subinforformula1.html): carbon then hydrogen then the other elements alphabetically.
Any library/text file of elements is not needed to be included in the byte count.
## Examples
**H2O**
```
H-O-H
```
or
```
H H
\ /
O
```
**CO2**
```
O=C=O
```
**H4N**
```
H
|
H-N-H
|
H
```
## Winning
The winning code is the shortest program in bytes
## Leaderboard
```
/* Configuration */
var QUESTION_ID = 52630; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
/* App */
var answers = [], page = 1;
function answersUrl(index) {
return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
if (data.has_more) getAnswers();
else process();
}
});
}
getAnswers();
var SIZE_REG = /\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;
var NUMBER_REG = /\d+/;
var LANGUAGE_REG = /^#*\s*([^,]+)/;
function shouldHaveHeading(a) {
var pass = false;
var lines = a.body_markdown.split("\n");
try {
pass |= /^#/.test(a.body_markdown);
pass |= ["-", "="]
.indexOf(lines[1][0]) > -1;
pass &= LANGUAGE_REG.test(a.body_markdown);
} catch (ex) {}
return pass;
}
function shouldHaveScore(a) {
var pass = false;
try {
pass |= SIZE_REG.test(a.body_markdown.split("\n")[0]);
} catch (ex) {}
return pass;
}
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
answers = answers.filter(shouldHaveScore)
.filter(shouldHaveHeading);
answers.sort(function (a, b) {
var aB = +(a.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0],
bB = +(b.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0];
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
answers.forEach(function (a) {
var headline = a.body_markdown.split("\n")[0];
//console.log(a);
var answer = jQuery("#answer-template").html();
var num = headline.match(NUMBER_REG)[0];
var size = (headline.match(SIZE_REG)||[0])[0];
var language = headline.match(LANGUAGE_REG)[1];
var user = getAuthorName(a);
if (size != lastSize)
lastPlace = place;
lastSize = size;
++place;
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", user)
.replace("{{LANGUAGE}}", language)
.replace("{{SIZE}}", size)
.replace("{{LINK}}", a.share_link);
answer = jQuery(answer)
jQuery("#answers").append(answer);
languages[language] = languages[language] || {lang: language, user: user, size: size, link: a.share_link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 50%;
float: left;
}
#language-list {
padding: 10px;
width: 50%px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<div id="language-list">
<h2>Winners by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
```
[Answer]
## PHP, 205 bytes
```
function($f)use($l){for($a=preg_split('#(?=[A-Z])#',eregi_replace('[^a-z]','',$f));++$i<count($a);)if($l[$a[$i]]++===null)die('Invalid elements in diagram');foreach($l as$k=>$v)echo$v?$k.($v>1?$v:''):'';};
```
The array of elements is stored in the `$l` variable in the following form:
```
$l = ['C' => 0, 'H' => 0, 'Ac' => 0, …, 'Zr' => 0];
```
Here is the ungolfed version:
```
function ($formula) use ($elementsList)
{
$linearFormula = preg_replace('#[^a-z]#i', '', $formula); // Remove everything except the letters in the formula
$elementsInFormula = preg_split('#(?=[A-Z])#', $linearFormula); // Split the formula before each uppercase letter, with an additional empty element in the first position
for ($i = 1; $i < count($elementsInFormula); ++$i)
{
// Check if the element is valid
if (!isset($elementsList[$elementsInFormula[$i]])) {
die('Invalid elements in diagram');
}
// Increment the associated counter
++$elementsList[$elementsInFormula[$i]];
}
// Print the raw formula
foreach ($elementsList as $element => $number)
{
if ($number > 0) {
echo $element;
if ($number > 1) {
echo $number;
}
}
}
};
```
] |
[Question]
[
Australia (and many countries) has a perferential voting system,
where voters, number the candidates from 1 - n, where n is the number of candidates,
in order of preference.
Until a candidate gets a absolute majority of votes, the number 1 votes for the candidate with minimum count of number 1 votes, are redistributed to their next preference.
Full detail can be found at <http://www.eca.gov.au/systems/single/by_category/preferential.htm>, under the **The Full Preferential Count**
Implement a system that takes in a array of voting slips.
where a voting slip is a array, where each index is a candidate ID, and the element at that index is the voters preference number for that candidate.
Eg:
for a 3 candidates with, 7 voting slips, input could be:
```
votes =
2 1 3
1 2 3
3 2 1
1 3 2
1 2 3
2 3 1
3 2 1
```
You may take this input in your languages preferred 2D array like data structure.
Example function: (matlab)
```
function winningParty = countVotes (votes)
[nVotes, nParties] = size(votes)
cut = zeros(1,nParties) % no one is cut at the start
while(max(sum(votes==1))<=0.5*nVotes) %while no one has absolute majority
[minVotes, cutParty] = min(sum(votes==1) .+ cut*nVotes*2) %make sure not cut twice, by adding extra votes to cut party
votes(votes(:,cutParty)==1,:)--; % reassign there votes
cut(cutParty) = true;
votes
end
[winnersVotes, winningParty] = max(sum(votes==1))
```
Output:
```
octave:135> countVotes(votes)
nVotes = 7
nParties = 3
cut =
0 0 0
minVotes = 1
cutParty = 2
votes =
1 0 2
1 2 3
3 2 1
1 3 2
1 2 3
2 3 1
3 2 1
winnersVotes = 4
winningParty = 1
ans = 1 %This is the only line i care about
```
---
EDIT:
In cases of tie for lowest portion of primary share, either can be removed.
There can be no tie for winning candidate. Winner must have strictly greater than 50% of votes.
[Answer]
## ~~Python 3,~~ ~~173~~ ~~146~~ Python 2, 125(see below)
**Original version, 173:**
```
C=sorted(S[0]);C[-1]=0
while C:
v={i:sum(i==min(C,key=s.__getitem__)for s in S)for i in C};c=max(C,key=v.get);C.remove(min(C,key=v.get))
if v[c]*2>len(S):C=print(v[c],c+1)
```
Expects input in this form:
```
S=[
[2, 1, 3],
[1, 2, 3],
[3, 2, 1],
[1, 3, 2],
[1, 2, 3],
[2, 3, 1],
[3, 2, 1],
]
```
and prints number of votes and the winning candidate:
```
4 1
```
**Commented version:**
```
# create a list of the (still available) candidates;
# these will be used as indexes and therefore have to start at 0 instead of 1
C=sorted(S[0]);C[-1]=0
# start a loop with some condition that's easily stoppable later
while C:
# for each slip s, find the (still available) candidate with the best vote; count these for each (still available) candidate
v={i:sum(i==min(C,key=s.__getitem__)for s in S)for i in C}
# find the candidate with the highest number of votes
c=max(C,key=v.get)
# remove the candidate with the lowest number of votest
C.remove(min(C,key=v.get))
# somebody with more than 50 % of the votes (=slips) already?
if v[c]*2>len(S):
# if yes, then print votes and candidate number
# (the print function returns None, which makes the condition of the loop fail)
C=print(v[c],c+1)
```
**EDIT After clarification of output by OP:**
```
C=sorted(S[0]);C[-1]=0
while C:v={i:sum(i==min(C,key=s.__getitem__)for s in S)for i in C};c=max(C,key=v.get);C.remove(min(C,key=v.get))
print(c+1)
```
(The loop runs to exhaustion of candidates, which is no problem, because the number of votes is not neeeded.)
**EDIT 2, newest version, Python 2, 125:**
Python 2 `range` yields a list, which is shorter than the construction I had to use for Python 3.
Also, `c` need not at all times be the candidate with tho most votes -- it's only important at the end. At the end, there is only one candidate left, so `c` just has to be *some* candidate (I use `C[0]`), because that must be the right one at the end.
That means that the name `v` is use only once. Replacing that usage with the definition of `v` saves some more characters.
```
C=range(len(S[0]))
while C:c=C[0];C.remove(min(C,key={i:sum(i==min(C,key=s.__getitem__)for s in S)for i in C}.get))
print c+1
```
[Answer]
### GolfScript, 37 characters
```
.0=,({.0={`{\0==}+1$\,,}$1>`{&}+%}*0=
```
Input (on stack) is a list of votes where elements can be e.g. numbers or strings. [Example](http://golfscript.apphb.com/?c=WwogIFsiQmVybmFyZCIgIkFyY2hpYmFsZCIgIkNocmlzIl0KICBbIkFyY2hpYmFsZCIgIkJlcm5hcmQiICJDaHJpcyJdCiAgWyJDaHJpcyIgIkJlcm5hcmQiICJBcmNoaWJhbGQiXQogIFsiQXJjaGliYWxkIiAiQ2hyaXMiICJCZXJuYXJkIl0KICBbIkFyY2hpYmFsZCIgIkJlcm5hcmQiICJDaHJpcyJdCiAgWyJCZXJuYXJkIiAiQ2hyaXMiICJBcmNoaWJhbGQiXQogIFsiQ2hyaXMiICJCZXJuYXJkIiAiQXJjaGliYWxkIl0KXQoKLjA9LCh7LjA9e2B7XDA9PX0rMSRcLCx9JDE%2BYHsmfSslfSowPQ%3D%3D&run=true):
```
[
["Bernard" "Archibald" "Chris"]
["Archibald" "Bernard" "Chris"]
["Chris" "Bernard" "Archibald"]
["Archibald" "Chris" "Bernard"]
["Archibald" "Bernard" "Chris"]
["Bernard" "Chris" "Archibald"]
["Chris" "Bernard" "Archibald"]
]
.0=,({.0={`{\0==}+1$\,,}$1>`{&}+%}*0=
# => either Archibald or Bernard (because of tie)
```
] |
[Question]
[
Given a set of bit vectors \$A\$ and a binary matrix \$M\$, we can define the set \$MA = \{ Mx : x \in A \}\$, where \$ M x \$ is the result of the [matrix multiplication](https://en.wikipedia.org/wiki/Matrix_multiplication) of \$ M \$ by \$ x \$ over \$\mathbb{F}\_2\$, the field with two elements.
Given the set \$ A \$ and the set \$ M A \$, your task is to recover a possible value for \$ M \$ in as little time as possible.
Note that since these are sets, they are unordered.
# Scoring
For all pairs of integers \$ 0 < a \leq 15\$, \$a < b \leq 32\$, I produced a random \$32 \times b\$ binary matrix \$M\$, a set \$ A \$ of size \$2^a\$ with random vectors of size \$ b \$, and calculated \$ M A \$.
Your score is the time you take to solve all these samples.
# I/O
Your program will recieve input from stdin in the following format:
```
t
b1 n1
x1 x2 x3 x4 ... xn1
y1 y2 y3 y4 ... yn1
...
bt nt
x1 x2 x3 x4 ... xnt
y1 y2 y3 y4 ... ynt
```
`t` is the number of instances of the problem you are required to solve. For each instance, you will get the number `b`, the number of bits in the input, and `n`, the number of vectors. In the next line, you will get `n` integers \$0 \leq x < 2^b\$, whose binary representation is the input vectors. In the following line, you will get the `n` integers \$0 \leq x < 2^{32}\$ whose binary representation is the vectors in \$MA\$.
You are to output `t` lines to stdout in the format
```
x1 x2 ... x32
x1 x2 ... x32
...
x1 x2 ... x32
x1 x2 ... x32
```
each containing 32 integers \$0 \leq x < 2^b\$ representing the rows of \$ M \$.
# Example
For the input
```
1
7 16
5 14 21 23 26 36 38 45 55 74 76 80 95 100 109 123
114917382 260133574 340793034 1730627271 1755714561 1818746903 2816946300 2860390058 3157685360 3190685792 3599242337 3720917681 3919737131 4067636519 4180906999 4260521953
```
A possible matrix is
```
48 43 76 13 102 126 98 125 88 51 76 69 72 27 76 115 89 11 33 29 0 96 64 87 64 39 48 118 61 115 78 43
```
Under this matrix, `0000101` (5), for example, comes out to be `01101100011001111110000000010111` (1818746903)
# Rules
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
* The programming language you use must be freely available.
* Add instructions on how to compile and run your code.
* The code will be timed on my computer which has Intel Core i7-9700 with 8 threads and 32GB RAM.
* You may not exploit the PRNG (e.g. find its seed and from that find which matrices were generated).
* You may assume all other properties implied by the generation method (e.g. that `n` is a power of two, or that the sets are given sorted).
This is the code used to generate the samples (on stdout, stderr just logs the matrices, which of course won't be provided to your program):
```
#include <set>
#include <assert.h>
#include <random>
#include <iostream>
#define maxv(b) (b==32?-1u:(1u<<b)-1u)
uint32_t matmul(uint32_t M[32], uint32_t x) {
uint32_t ans = 0;
for (int i = 0; i < 32; i++) ans |= ((uint32_t)__builtin_parity(M[i] & x)) << (31-i);
return ans;
}
std::mt19937 rng(time(0));
int main() {
std::cout << "360\n";
for (int a = 1; a <= 15; a++) {
for (int b = a+1; b <= 32; b++) {
std::set<uint32_t> A;
uint32_t M[32];
for (int i = 0; i < 32; i++) {
M[i] = std::uniform_int_distribution<uint32_t>(0, maxv(b))(rng);
std::cerr << M[i] << ' ';
}
std::cerr << '\n';
std::set<uint32_t> MA;
for (int i = 0; i < 1<<a; i++) {
uint32_t x;
do x = std::uniform_int_distribution<uint32_t>(0, maxv(b))(rng); while (A.count(x));
A.insert(x);
MA.insert(matmul(M, x));
}
assert(A.size()==MA.size());
std::cout << b << ' ' << (1<<a) << '\n';
for (uint32_t a : A) std::cout << a << ' ';
std::cout << '\n';
for (uint32_t a : MA) std::cout << a << ' ';
std::cout << '\n';
}
}
}
```
```
]
|
[Question]
[
Once upon a time I wanted to order custom tokens for a board game. They say they can do it, and then they present me their price list. I was confused because they charge per inch of head movement, and I have no idea how much will my tokens cost.
**INPUT:** a 2d grid:
* `|`,`-`,`\`,`/` are straight cuts. Each has a length of 1.
* `┌`,`┐`,`└`,`┘` are 90 degree corner cuts. Each has length of 1.\$^1\$
* `#`,`@` are 45 and 135 degree corner cuts respectively. Each has a length of 1.20.
* `+`,`X` are perpendicularly intersecting cuts. Each has a length of 1.
* `>`,`v`,`<`,`^` are the cut ends. Each has a length of:
+ 1.50, if the arrow points at the diagonal cut,
+ 1, if the arrow points at the beginning of next cut,
+ 0.50 otherwise.
* ABC...**UVWYZ**abc...xyz are the cut start points given in that order. They have a length of:
+ 0.50, if no other already made cuts are neighboring them,
+ 1.50, if if the cut begins next to the diagonal cut,
+ 1 otherwise.
**OUTPUT:** Distance that a head will move with up to 2 significant digits.
Assume that:
* The company doesn't count distance from resting position to starting point of the first cut,
* Each cut is made only once (intersections cut twice on the same character),
* All grids are valid,
* The head moves from the end of a cut to the beginning of another cut in a straight line.
Obviously no [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default), and the shortest code in each language wins!
**TEST CASES:**
```
```
Output: 0
```
A> B>
```
Output: 4
```
A------v
^------B
```
Output: 16
```
A┌┐^
└┘└┘
```
Output: 7.5
```
#B┐
|\v
A<#
```
Output: 11.4
*(Note: First the head cuts bottom-left triangle, then moves its head to the beginning of top-right triangle cut. 45 degree corners take continuations first instead of new cuts.)*
```
A-@<--┐
^ \ |
└--B@-┘
```
Output: 21.15
```
A-┐ ┌--┐ ┌-┐ ┌--┐ C-┐ ┌--┐ ┌-┐ ┌--┐
^ | | | | | | | ^ | | | | | | |
└-+-+--┘ └-+-+--┘ └-+-+--┘ └-+-+--┘
| | B | | | D |
└-┘ ^-┘ └-┘ ^-┘
```
Output: 138.41
```
#-#
A X
X \
@ @-#
v
```
Output: 13.5
```
A> F> K> P> U> a>
B> G> L> Q> V> b>
C> H> M> R> W> c>
D> I> N> S> Y> d>
E> J> O> T> Z> e┐
<---------------┘
```
Output: 104.29
\$^1\$ If needed, replace this with a set of your choice.
]
|
[Question]
[
The inspiration for this code golf puzzle is the [Bridge and Torch problem](https://en.wikipedia.org/wiki/Bridge_and_torch_problem), in which ***d*** people at the start of a bridge must all cross it in the least amount of time.
The catch is that at most two people can cross at once, otherwise the bridge will crush under their weight, and the group only has access to one torch, which must be carried to cross the bridge.
Each person in the whole puzzle has a specified time that they take to walk across the bridge. If two people cross together, the pair goes as slow as the slowest person.
There is no set number of people that must cross the bridge; your solution MUST work for any value of ***d***.
You needn't use standard input for this problem, but for the sake of explaining the problem, I will be using the following input and output format for the explanation. The first number, ***d***, is the number of people at the start of the bridge. Then, the code will scan for ***d*** numbers, each representing the speed of a person.
The code output will be the LEAST amount of time required to cross everyone from the start of the bridge to the end of the bridge, while meeting the criteria explained earlier.
Here are some input cases and output cases and the explanation for the first input case. It is up to you to derive an algorithm from this information to solve the problem in the fewest bytes of code possible.
**input**
```
4
1 2 5 8
```
**output**
```
15
```
To reach this output, the people must cross in the following way.
```
A and B cross forward (2 minutes)
A returns (1 minute)
C and D cross forward (8 minutes)
B returns (2 minutes)
A and B cross forward (2 minutes)
```
Here's another test case to guide you along your way.
**input**
```
5
3 1 6 8 12
```
**output**
```
29
```
Rules:
1. Assume that the input will not be sorted, and you must do so on your own (if you need to)
2. The number of people in the puzzle is not fixed at 4 (N >= 1)
3. Every group and individual crossing must have a torch. There is only one torch.
4. Each group must consist of a maximum of only 2 people!
5. No, you may not jump off the bridge and swim to the other side. No other tricks like this ;).
[Answer]
## Python 3, ~~100~~ 99 bytes
a recursive solution
```
f=lambda s:s[0]+s[-1]+min(2*s[1],s[0]+s[-2])+f(s[:-2])if s.sort()or 3<len(s)else sum(s[len(s)==2:])
```
*Thanks to @xnor for [this paper](https://page.mi.fu-berlin.de/rote/Papers/pdf/Crossing+the+bridge+at+night.pdf)*
*Thanks to @lirtosiast save 2 bytes, @movatica save 1 bytes and to @gladed pointing at that my previous solution doesn't work*
use the following trick to evaluate something in lambda function `s.sort() or s` here we compute sort and return the result of the test `s.sort()or len(s)>3`
## Ungolfed
```
def f(s):
s.sort() # sort input in place
if len(s)>3: # loop until len(s) < 3
a = s[0]+s[-1]+min(2*s[1],s[0]+s[-2]) # minimum time according to xnor paper
return a + f(s[:-2]) # recursion on remaining people
else:
return sum(s[len(s)==2:]) # add last times when len(s) < 3
```
## Results
```
>>> f([3, 1, 6, 8, 12])
29
>>> f([1, 2, 5, 8])
15
>>> f([5])
5
>>> f([1])
1
>>> f([1, 3, 4, 5])
14
```
[Answer]
# Python 2, ~~119~~ ~~114~~ ~~112~~ ~~119~~ ~~110~~ ~~100~~ 95 bytes
I have been advised to separate my answers out.
A solution using `Theorem 1, A2:09` [of this paper xnor linked](https://page.mi.fu-berlin.de/rote/Papers/pdf/Crossing+the+bridge+at+night.pdf). To quote the paper (changing it to zero-indexing): `The difference between C_{k-1} and C_k is 2*t_1 - t_0 - t_{N-2k}.`
```
lambda n,t:t.sort()or(n-3)*t[0]*(n>1)+sum(t)+sum(min(0,2*t[1]-t[0]-t[~k*2])for k in range(n/2))
```
**Ungolfing:**
```
def b(n, t): # using length as an argument
t.sort()
z = sum(t) + (n-3) * t[0] * (n>1) # just sum(t) == t[0] if len(t) == 1
for k in range(n/2):
z += min(0, 2*t[1] - t[0] - t[-(k+1)*2]) # ~k == -(k+1)
return z
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 39 bytes
```
{2≥≢⍵:⊃⍵⋄(⊃∘⌽+⊃+(∇1↓⊢)⌊(∇2↓⊢)+2×2⊃⌽)⍵}∨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v9roUefSR52LHvVutXrU1QykHnW3aIBYHTMe9ezVBrK0NR51tBs@apv8qGuR5qOeLhDXCMrVNjo83QikumevJlBv7aOOFf/THrVNeNTb96hvqqc/UOrQeuNHbROBvOAgZyAZ4uEZ/D9NwVjBUMFMwULB0IgrDcg0UjBVsACydExBhCGQMFEwBcsYg1gA "APL (Dyalog Extended) – Try It Online")
A tacit function which includes a recursive dfn.
### How it works: the idea
My solution is based on subproblem analysis. Given the crossing times \$ t\_1, t\_2, \cdots, t\_n \$ sorted in ascending order, there are two possibly optimal ways to help the worst person cross the bridge:
1. \$ (t\_1, t\_n) \rightarrow t\_1 \$: net effect is \$ t\_n \$ crossing, and the cost is \$ t\_n + t\_1 \$.
2. \$ (t\_1, t\_2) \rightarrow t\_2 \rightarrow (t\_{n-1}, t\_n) \rightarrow t\_1 \$: net effect is \$ t\_{n-1} \$ and \$ t\_n \$ crossing, and the cost is \$ t\_1 + 2t\_2 + t\_n \$.
Let's say \$ T\_k \$ be the optimal time to cross the first \$k\$ people. Then, for the first \$k\$ people crossing, we can choose between "use (1) and let \$ k-1 \$ remaining people cross" and "use (2) and let \$ k-2 \$ remaining people cross", which becomes
$$
\begin{aligned}
T\_k &= \min(T\_{k-1} + t\_n + t\_1, T\_{k-2} + t\_1 + 2t\_2 + t\_n) \\
&= t\_1 + t\_n + \min(T\_{k-1}, T\_{k-2} + 2t\_2)
\end{aligned}
$$
### How it works: the code
```
{2≥≢⍵:⊃⍵⋄(⊃∘⌽+⊃+(∇1↓⊢)⌊(∇2↓⊢)+2×2⊃⌽)⍵}∨
∨ ⍝ Descending sort to get [t_n .. t_1]
{ } ⍝ Pass on to recursive function
2≥≢⍵:⊃⍵ ⍝ Base case: If input length ≤ 2, return the first element
⍝ [t_1] → t_1, [t_2 t_1] → t_2
(⊃∘⌽+⊃+(∇1↓⊢)⌊(∇2↓⊢)+2×2⊃⌽)⍵ ⍝ Recursive case
( 1↓⊢) ⍝ Choice 1: Drop 1 to get [t_{n-1} .. t_1]
∇ ⍝ Recursive call to get T_{n-1}
(∇2↓⊢) ⍝ Choice 2: Drop 2 and recurse to get T_{n-2}
+2×2⊃⌽ ⍝ and add 2×t_2
⌊ ⍝ Minimum of two choices
⊃∘⌽+⊃+ ⍝ Add common terms t_1 and t_n
```
---
Using DP to solve the recursive problem costs a few more bytes:
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 44 bytes
```
⊃⊃(+∘(⊃∘⌽+⊃⌊2∘⊃+2×2⊃⌽),⊢)/(¯2∘↓,∘⊂0~⍨¯2∘↑)∨⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97f@jrmYg0tB@1DFDA8TumPGoZ682iNXTZQTidTVrGx2ebgQW2aup86hrkaa@xqH1YLm2yTpgJU0GdY96V8AEJ2o@6ljxqG8qyAIuIE7nsnLLL1LIVLDyzFN41LvZlEtBIY3LyjUvBSgMUvA/nctYwVDBTMFCwdCIy1DBSMFUwYJLx5RLxxDIM1YwUTAFAA "APL (Dyalog Extended) – Try It Online")
A full program.
### How it works: the code
```
∨⎕ ⍝ Descending sort the given array
(¯2∘↓,∘⊂0~⍨¯2∘↑) ⍝ Set up the initial element for reduce
⍝ e.g. [12 8 6 3 1] → [12 8 6 (3 1)]
¯2∘↑ ⍝ Take the last two elements
⍝ If input length is 1, ↑ becomes "overtake" and yields [0 n]
0~⍨ ⍝ Remove zeros to undo "overtake"
⊂ ⍝ Enclose to make it the initial item
¯2∘↓,∘ ⍝ Append to the original array with last two elements dropped
(+∘(⊃∘⌽+⊃⌊2∘⊃+2×2⊃⌽),⊢)/ ⍝ Reduce by the logic, right to left
2∘⊃+2×2⊃⌽ ⍝ Choice (2):
2∘⊃+ ⍝ T_{k-2} +
2×2⊃⌽ ⍝ 2*t_2
⊃ ⍝ Choice (1): T_{k-1}
(⊃∘⌽+ ) ⍝ Common term: + t_1
+∘ ⍝ + t_n
,⊢ ⍝ Prepend the resuting value T_k to the DP array
( )/ ⍝ Reduce by the function above
⊃⊃ ⍝ Remove the layering and take the first element (which is T_n)
```
[Answer]
# Ruby, ~~94~~ ~~133~~ ~~97~~ ~~96~~ ~~101~~ ~~96~~ 99 bytes
I have been advised to separate my answers out.
This is a solution based on the algorithm described in `A6:06-10` of [this paper on the Bridge and Torch Problem](https://page.mi.fu-berlin.de/rote/Papers/pdf/Crossing+the+bridge+at+night.pdf).
**Edit:** Fixing a bug where `a=s[0]` is not yet defined when `a` is called at the end if `s.size <= 3`.
```
->s{r=0;(a,b,*c,d,e=s;r+=a+e+[b*2,a+d].min;*s,y,z=s)while s.sort![3];r+s.reduce(:+)-~s.size%2*s[0]}
```
**Ungolfing:**
```
def g(s)
r = 0
while s.sort![3] # while s.size > 3
a, b, *c, d, e = s # lots of array unpacking here
r += a + e + [b*2, a+d].min
*s, y, z = s # same as s=s[:-2] in Python, but using array unpacking
end
# returns the correct result if s.size is in [1,2,3]
return r + s.reduce(:+) - (s.size+1)%2 * s[0]
end
```
[Answer]
# [Python 2](https://docs.python.org/2/), 89 bytes
```
lambda t:t.sort()or reduce(lambda x,c:x+[min(x[-2]+x[1]*2,x[-1])+c+x[0]],t[2:],t[:2])[-1]
```
[Try it online!](https://tio.run/##LYzNDoIwEITvPMUcW1mNVDDahCepPSA/sYm0BGuCT49b5TKZ@b7NTp/4CF6tQ31bn8147xpEHQ@vMEchw4y5795tLza1UKuX3IzOi8Xslc0XU9idIh6FlXnL@2gtRaN0Sq2sTGYd@JMjBDgPkwHCnAgF4Uy4cFGWoK6SfoaxIlRsmBbVRise3JNP@N8I/KZkkVApM6sxzc5HiEE4PkmJukaQ6xc "Python 2 – Try It Online")
Uses the same formulation as [my APL answer](https://codegolf.stackexchange.com/a/199440/78410), except that direct reduction turns out shorter in this case. Incidentally, this wins against all the previous entries (except APL).
[Answer]
# Scala, ~~113~~ 135 (darnit)
```
def f(a:Seq[Int]):Int={val(s,b)=a.size->a.sorted;if(s<4)a.sum-(s+1)%2*b(0)else b(0)+Math.min(2*b(1),b(0)+b(s-2))+b(s-1)+f(b.take(s-2))}
```
Ungolfed somewhat:
```
def f(a:Seq[Int]):Int = {
val(s,b)=a.size->a.sorted // Sort and size
if (s<4) a.sum-(s+1)%2*b(0) // Send the rest for cases 1-3
else Math.min(b(0)+2*b(1)+b(s-1),2*b(0)+b(s-2)+b(s-1)) + // Yeah.
f(b.take(s-2)) // Repeat w/o 2 worst
}
```
Tester:
```
val tests = Seq(Seq(9)->9, Seq(1,2,5,8)->15, Seq(1,3,4,5)->14, Seq(3,1,6,8,12)->29, Seq(1,5,1,1)->9, Seq(1,2,3,4,5,6)->22, Seq(1,2,3)->6, Seq(1,2,3,4,5,6,7)->28)
println("Failures: " + tests.filterNot(t=>f(t._1)==t._2).map(t=>t._1.toString + " returns " + f(t._1) + " not " + t._2).mkString(", "))
```
Not great in general, but maybe not bad for a strongly-typed language.
And begrudging thanks to xnor for spotting a case I didn't catch.
[Answer]
# Ruby, ~~104~~ ~~95~~ 93 bytes
I have been advised to separate my answers out.
This is a solution based on [my Python 2 solution](https://codegolf.stackexchange.com/a/75782/47581) and `Theorem 1, A2:09` of [this paper on the Bridge and Torch Problem](https://page.mi.fu-berlin.de/rote/Papers/pdf/Crossing+the+bridge+at+night.pdf).
```
->n,t{z=t.sort!.reduce(:+)+t[0]*(n>1?n-3:0);(n/2).times{|k|z+=[0,2*t[1]-t[0]-t[~k*2]].min};z}
```
**Ungolfing:**
```
def b(n, t) # using length as an argument
z = t.sort!.reduce(:+) + t[0] * (n>1 ? n-3 : 0)
(n/2).times do each |k|
a = t[1]*2 - t[0] - t[-(k+1)*2] # ~k == -(k+1)
z += [0, a].min
end
return z
end
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 34 bytes
```
W>l=SQ3=+Zs[hQ.)QhS[y@Q1+hQ.)Q;+Zs
```
There's probably some way to write it as a reduce or some other functional magic, but I've spent enough time doing high school programming coursework today that actually writing anything resembling good code is a nice change of pace.
[Try it online!](https://tio.run/##K6gsyfj/P9wuxzY40NhWO6o4OiNQTzMwIzi60iHQUBvMsQYK//8fbaxjqGOmY6FjaBT7L7@gJDM/r/i/bgoA "Pyth – Try It Online")
] |
[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 6 years ago.
[Improve this question](/posts/135784/edit)
I majored in computer science in the area of communication technologies and I fluently speak Python, Java, C, Bash, Matlab, Octave and some others. But you guys know things I have never ever heard about like "Fish" or "R" or "Whitespace" or some kind of crazy things. Sometimes these languages are not even build by ASCII letters but by some crazy signs.
My question is: How do you get by all these things? I mean: At what point of your programming career did you say to yourself that you want to do some task in "Fish" or whatever? I mean what is the point or what was the purpose or... I am simply extremely confused by the fact that programming langues besides the big common ones (C, C++, C#, Java, Python, Lisp, JavaScript...) even exist but why in the world did you learn them so well that you can solve difficult problems with 8 Bytes of code??
PS: If someone finds a better tag, please add it mine is bad but I can't think of a better one
]
|
[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/130149/edit).
Closed 6 years ago.
[Improve this question](/posts/130149/edit)
Let us play a little golfing game.
Given a single line of N space separated numbers from STDIN, one must output those numbers on N lines.
So far, I came up with the three following bash solutions :
* `xargs -n1` (9)
* `tr \ \\n` (8)
* `fmt -1` (6)
Can anyone do better? I am eager to learn new tricks
[Answer]
Bash (22)
```
read X;printf %d\\n $X (thanks to manatwork but without literal NL)
```
`~~30 read -aX;printf "%d\n" ${X[\*]}
26 read X;echo -e ${X// /\n}
28 printf "%d\n" $(</dev/stdin)
27 printf "%d\n" $(</dev/fd/0)
26 printf %d\n $(</dev/fd/0)
23 read X;printf "%d\n" $X~~`
] |
[Question]
[
Creating a golfing language can be hard. Let's help budding golfing language creators out and provide some helpful tips on how to create one.
I'm looking for tips on:
1. The design process
2. Implementation
3. Community engagement
One tip per answer would be appreciated, and tips like "don't create a new language, use an existing one" *probably* aren't very helpful.
You don't need to have created a golfing language to answer this question. Feel free to answer from personal experiences or from general observations.
See also [Tips for launching a language](https://codegolf.meta.stackexchange.com/questions/14927/tips-for-launching-a-language) for when you are done creating your language.
[Answer]
Here are some suggestions. Sorry that this partially overlaps with other answers, which have been posted as I was writing this.
## Design process
1. One possibility (by all means not the only one) to decide which features (functions, data types, etc.) your language *L* should have is to **base it on another language** *B* that you have been using for long. That way you already have a good idea which functions of *B* are used most often, and therefore should be included in your language *L*, and you can assign shorter names in *L* to functions that are commonly used in *B*.
Examples:
* *L* = MATL: *B* = MATLAB/Octave.
* *L* = Pyth: *B* = Python.
* *L* = Japt: *B* = JavaScript.
* *L* = Brachylog: *B* = Prolog.
* *L* = Husk: *B* = Haskell.
* *L* = ShortC: *B* = C.
* *L* = V: *B* = Vim.
2. Decide which "**paradigm**" your language will use. Some examples are
* Stack-based (Cjam, MATL, 05AB1E);
* Tacit (Jelly);
* Prefix notation (Pyth);
* Infix notation (Pip, Japt);
* Fixed arity (Pyth);
* Variable arity (CJam, MATL, Japt).
These decisions are quite independent from item 1. For example, MATL's function `f` has the same functionality as MATLAB's `find`, but is used differently in that it pops its inputs from the stack and pushes its outputs onto it, whereas MATLAB uses normal function arguments which can be stored in variables.
3. Incorporate functions **from other golfing languages** that you find useful. Don't let item 1 (if applicable) limit language *L*'s definition.
4. Be prepared to **add functions in the future**. As you (or others) use the language, you will find things it would be nice to add. So reserve some of the "namespace" for future expansion. For example, don't use up all your single-character names at once.
## Implementation
5. Write the compiler (or interpreter) for your language *L* in a language *C* **that you know well** (often *C* = *B*).
6. The compiler is most often actually a **transpiler** into another language *T* (which can be the same as *B* or *C*). Language *T* should have a **free implementation**. That way it is viable to have an **online** compiler for your language. The compiler will be a program in *C* that takes source code in *L* to produce transpiled code in *T*, and then calls *T*'s compiler/interpreter to run the transpiled code.
A natural choice is *C* = *T*. Examples:
* *L* = Japt: *B* = *C* = *T* = JavaScript.
* *L* = Jelly: *C* = *T* = Python (and Jelly is inspired by J; but perhaps not so much as to claim that *B* = J).
* *L* = MATL: *B* = *C* = *T* = MATLAB/Octave.
## Community engagement
7. Host your compiler/interpreter in a **public repository** such as [GitHub](https://github.com/), so people can easily download it, create bug reports, suggest new features or even contribute with code.
8. Write **good documentation**. That helps users understand your language better. Besides, I found that task more rewarding than I expected. I recommend writing the specification while you are designing the language, not at the end. That way consistency between language behaviour and its specification is ensured.
9. Ideally the documentation should include some **quick reference** (table or summary), so experienced users don't have to go to the full documentation simply because they have forgotten the name or the syntax of a function they know.
10. Create an **[esolangs](https://esolangs.org/wiki/Main_Page) page** with basic information about your language.
11. Create a **chat room** where people can ask and discuss about the language. Visit it often.
12. **Answer questions** in your language, with **explanations** about how the code works. You'll want to do that anyway (it's your language, you will find it fun to use), but this also helps get people curious about your language, and shows some of the language's properties, which might get people interested.
13. If you chose to base your language *L* on a language *B* (see item 1) that is **general-purpose and well known**, users of *B* will find it easy to switch to *L*, which will allow them to provide short answers (in *L*) with minimal effort (coming from *B*).
[Answer]
Here's a couple of random hints.
# Choose your built-in commands and values carefully
Especially when your language is new, it's tempting to add lots of functionality that you think may be useful at some point.
If that turns out to be false, you'll have a mostly useless command taking up a valuable spot in your language's namespace.
Rebinding the symbol breaks backward compatibility and may invalidate existing answers on this site.
That's not the end of the world since we're talking about weird recreational languages, but if it happens frequently, your users will have a hard time keeping up with the changes.
As a hypothetical example, testing whether a given number is prime is probably a good choice for a one-symbol function, since primes come up a lot in golf challenges.
Testing whether it's a square or a power of 2 can be useful, but not as often.
Testing whether it's a perfect number most likely doesn't warrant a one-symbol command.
You'll get a sense of what generally useful things the language is missing by using it.
# Minimize the number of incorrect programs
By an incorrect program I mean one that produces any kind of error: syntax error, type mismatch, division by zero etc.
Every error is an opportunity for your language to do something useful instead.
Syntax error due to a missing parenthesis?
Allow it to be implicit in some way (like at the beginning or end of line).
Division by zero throws an error?
Consider having it return infinity or NaN instead, or allow errors to be caught and used for flow control.
A type mismatch is usually a sign of a function that's not generic enough.
Ideally, every function should accept every type of input and do something useful with it, unless there's a good reason not to.
There are several common tactics for this:
* Overloading. For example, `+` can be addition on numbers and concatenation on lists. This seems to be the most popular option.
* Vectorization. If `+` is given lists, it can perform addition element-wise. Jelly uses vectorization extensively.
* Coercion. If `+` is given non-numbers, it can convert them into numbers implicitly. For example, 05ab1e allows numbers and strings to be used mostly interchangeably.
* Keep the error if you have a good use for it. In Brachylog, arithmetic operations only work on numeric types. Since it's a logic programming language based on Prolog, they can be used backwards or to generate input-output pairs, and in those cases it's essential that the input can't suddenly be a list or string.
[Answer]
I never created a language myself, but I can partially answer number 3 (I will make this a community wiki, so feel free to add more).
Some tips after the core part of your language is done:
* Have a [GitHub](https://github.com/)/[GitLab](https://about.gitlab.com/) project where you can link to, including a wiki-page/README of your language in general (what it's made for, how to compile and run it locally, etc.), and a short description of each of its builtins.
* Ask *@Dennis* in [talk.tryitonline.net chat](https://chat.stackexchange.com/rooms/44255/talk-tryitonline-net) to add your language to [the online compiler TIO](https://tio.run/#).
* Add your language to the [Showcase of Languages](https://codegolf.stackexchange.com/questions/44680/showcase-of-languages) to expose it to the community.
* Possibly create [a chat room](https://chat.stackexchange.com/) so people have a place to report bugs, discuss improvements, or talk about golfing strategies in your language.
* Create a [tips](/questions/tagged/tips "show questions tagged 'tips'") page for your language, and perhaps post a few tips as answers to get it started.
* Start answering challenges here on CGCC in your language, so people seeing it for the first time might become interested. Answering well-known challenges like [Hello World](https://codegolf.stackexchange.com/questions/55422/hello-world), ["Never Gonna Give You Up"](https://codegolf.stackexchange.com/questions/6043/were-no-strangers-to-code-golf-you-know-the-rules-and-so-do-i); [Default Quine](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good); [Prime checker](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime); [Fizz-Buzz sequence](https://codegolf.stackexchange.com/questions/58615/1-2-fizz-4-buzz); [Odd or Even](https://codegolf.stackexchange.com/questions/113448/is-this-even-or-odd); etc. are all great challenge to introduce your new language, and let people who see it get a general feel for what's possible in your language.
Apart from those and some other popular challenges, just answering any new challenge is also a great way to expose your language, since people tend to look at new challenges more often than existing ones.
[Answer]
It strikes me that the most important design decision is what the underlying paradigm of the golfing language is.
Here are some possible types of language:
* Stack based
* Array based
* Object based
* Functional
* Imperative
* Declarative
Indeed you might even have a mixture of these, or something else entirely like a two dimensional language, automata, regex, machine language or a Turing machine and so on.
This is important because it will greatly affect the syntax of the language and in some ways how concisely code can be written.
---
## Edit: Follow Up
I thought that I would show how the design and implementation phases of creating a language actually work in practice. I realise that's it's more than one tip in this answer and it's lengthy I hope that's ok.
**Design Considerations**
I wanted the following things out of my new language:
* Quick to implement (or prototype)
* Flexible and concise syntax, perhaps with a view to Golfing
* Can do useful things, not just a toy language
I plumped for some version of Forth, because it would satisfy the first two critera. It would also have to be interpreted at least for prototyping, compiling is out because it would take too much development time.
In terms of it doing useful things, it absolutely had to have the following traits:
* Ability to call functions
* Arithmetic and logic operations
* Manipulation of numbers and strings
* Loops and conditional structures
* Stack manipulation
And because it's Forth I thought the following would be kind of cool:
* Multiple data stacks
* Ability to 'pass in' function literals to be executed inside functions (kind of functional style)
**Implementation Details**
Firstly, I would leverage my knowledge and use a language I know well for the interpreter: PHP - at least for the prototyping stage.
Next I needed the interpreter to be able to recognise (tokenise) these four things:
* String Literals: `'hello world'`
* Numeric Literals: `3.1415`
* Labels (for function names) `drop`
* symbols (representing atomic actions): `#@$^`
The simplest solution for tokensing the program is to use regex. Also because I wanted concise syntax labels would be strictly alphabetic. I would also need some sort of separator to remove ambuiguity in tokenising, I left a space and comma free for that.
So with all that in mind I could create a fat-free Forth syntax. For example:
```
1.5,2.7,3,4add add add;
```
would push four numbers on to the stack, and call a function `add` three times and then return `;`.
Once tokenised the interpreter can then consume tokens one by one and act accordingly.
One consequence of using regex, is that it's unable to handle a nested syntax. So I would need to manage nested loops in some way. The way to do this is to look for the start of loops (token) and find the corresponding end and record somehow in the start token where the end is and vice-versa. That way the interpreter could jump around loops and conditionals very easily. A stack would be needed to know which token closes which opening token.
Functions I would just manage as simply labels, or named positions in the token stream. When a function is executed, the position is looked up and interpretation continues from there. I would return from the function using a `;` token. This would also require a function call stack to handle nested function calls - and return back to the calling position in the token stream.
For the fancy stuff, such as passing in function literals, the idea would be to push a string literal containing the code fragment on to the data stack e.g:
```
'2+;'apply;apply:`;
```
So to break the above down, `'2+;'` is a string literal containing the code fragment (push 2 and add to top item on data stack). A function called `apply` is then called. The function definition begins `apply:` and a backtick actually pops the string literal and executes it in its own brand new context. Once the fragment has been executed and returns, the function then continues.
The interpreter would handle this by separating out the parsing and tokenisation from the actual execution. That way the literal code fragment can be parsed when pulled off the stack, and that new context passed into the Executing function, using PHP's scoping to handle the new context's scope. The only fly in the ointment is that to be able to call a function from the code fragment, it would need to be able to access the parent's context. For example:
```
'dotproduct;'walkarray;walkarray:...`...;dotproduct:...;
```
Next for multiple data stacks that would be easy. I would have just one main data stack where all the action happens and provide atomic actions that can push and pull to other named data stacks. That should greatly simplify operations with vectors or arrays of numbers.
I also wanted conditional loops with the condition either at the beginning or end or just infinite loops. So I chose `[...]` for an if condition, `[...)` and `(...]` for conditional loops and `(...)` for infinite loop.
Lastly, some features that are missing: general mathematical functions, extensive string handling, goto and breaking out of loops and conditions. Although it is possible to break out by returning in a function by using `func:(...[;]...)`.
Anyway, here's the semi-golfed prototype, and hopefully semi readable, enjoy!
[Try it online!](https://tio.run/##jVZtc@I2EP7Or3BAjayzTDCXfkEIuOn0mny4a6bTTzUucXwCfBjb8UsDAfrTS1eyeQ2@CcPYK@nZZ1e7q5Xjabzt9uNprG1vbrQv91/vtYe7B@3z73/8ead9@fTL3f3XX2uw8lvuB4FI5pH2MAXJj9MaTCM3mYS8btE2/UhvaRtnUczwI4NXxzJag4E1sIzh0BqyOgP4JIie3EBDM4qeWa2GZtx2GHqWz5pYCC/PxMiLwkwsMn33ViYIAfg4D73Mj0JtvxQn0YSi2E1EmO0UgYysahr8bBRTFFCUO9y2Har@YEguoTiKOXaTxF2OQMTFbJyIyWjuZt505AaBXm/ow2@GPmzCk/TJWrdd8/WT@ZdjgIz15oc@wWTdNPqNOi1dmRNmo5SikFL0QtGYoonD0ZxpEMEsmonQT4UyNY4SHfm8xZDfRR73ojyE/aQExoZBUGyDz2jKdTS2ke/0bzs6elGS1dF1FErximNM@u3OR0IIBSy/7aOJXOigVL4cZVX6lbjzC0YLUyt/DHGUeLvlcG5dX6uRYTm2BWPcwQQFdomwHNgNrLGNpA7cJxGk72FWTDZer4/HOjBHtiRkZ0hyhnQAmdvy7wMc8qWjiChF5YdMfBIFWpoluZfliSh8SgTI4aEKzgsFSmFzVFTn9YdKAbJYQkahOxcy6EV5FcVc1nJ1UVXb5zsTpboH8VOSDMeJUQIzfpoK8ApycbLkEAKKb6cZpEas3mzq1IWzvRFWxIxtCocSbpvt8sR8i4pdqwWfy/R4cHa/FxKUS79vmxbFuMQrnAs5ghQy9MSR20Tfpbxflbv0VdG1Id2FdEvQTJXECVJu5YC2TqMhoRCEFUqkItReEQ01zTbvi4IEk3LXxwafoPi6UI8r5ZVelN6M9PhOIgaUvGcYFbq9t7rdd@v2pK7Yw6FP2khAmPVCkH2OFcWWh@nUH2flAt0b@BF9t3tOL90s@I7ZqkjgsMVRqmPTuPlwvf672/sJU@SSK87HLiCAe3HEvTzI4h830HEZlCVuquA3MVrIeOBLWXDB3beB5CeBvKz1707L3Ju/DLzaAa92wErOET7b2yu0BKYa4FI2wGUXLeApGyAs7WBN9Mo2RW2/VhCjc@JZmY65SCZCl40m4xD2URoHPqRn0YRWRO3y6siIU7W5BibCm0Z74ougPi6OXklXBbPPnIT5K0jdSp66XLWEzWUnHFzcLAp0uAGKS6LM44HFtKp4CD6DXURBIUmQIk4qtjLY5Rwe@/ow9vs3oQNdJh8OQRPOnGxAVapH6YN6z0X6g@J7BLrKr5@SnO7uCnLMoo6mGm1e4KsMisTrmRZRF5tMeX0YwndXnPjQ7JIiqfvBM2HbLZYohn8OIvhuk4@O3hq0B4@W2Ro4rWFryCSg08AUN9h/USyvinRrfv4f "PHP – Try It Online")
[Answer]
## Remember to add implicit input/output
In my opinion, a golfing language (whether successful or not) should always have some kind of implicit input/output. This applies to Jelly, 05AB1E, and pretty much every competitive golfing language.
I'll take CJam as an example. CJam doesn't have an all-purpose implicit input; it has input-reading instructions like `l` and `q`, and then if the input isn't just a string, it's followed by a `~`. That's how Pyth gained the upper hand than CJam.
If you are trying to make a competitive golfing language, try to avoid making your input type-dependent, otherwise you'll be needing type conversion every time you take input (which is pretty wasteful).
## Types of implicit input
For my purpose I could only think of two types of implicit input: Taking the whole input as an argument (e.g. GolfScript & Pyth), and cycling the implicit inputs for the operators of the program (e.g. 05AB1E and Jelly). The former is a basic form of implicit input, but still allows you to win some challenges. For the latter, you need to think carefully about how this system works, otherwise it would not help programmers.
## Implicit output
Implicit output is another very important design feature of a golfing language. For example, [Element](https://github.com/PhiNotPi/Element) isn't very well-designed, as you need a backtick (output the whole stack) every time at the end of the program.
Currently there are only two types of implicit output: full implicit output (the thing that Jelly & GolfScript/CJam uses) and top implicit output (the one that
Pyth and 05AB1E uses). Both of them are perfectly competive, however under my very unscientific testing, top implicit output languages seem to require extra joins at the end.
>
> I never used Jelly/GolfScript/CJam, but when I compare 05AB1E's implicit top output and MathGolf's implicit full joined output, I personally prefer top output tbh. Many times I have to clean up the stack if I only want to output a single item or single list in MathGolf. [Here an example answer](https://codegolf.stackexchange.com/questions/157897/duck-duck-goose/186337#186337). Although I certainly see your point, and in some cases [it's indeed useful](https://codegolf.stackexchange.com/questions/182305/return-the-closest-prime-number/182362#182362). Maybe I'm just too used to output top after starting with MathGolf, but I personally prefer just implicit top in most cases. – Kevin Cruijssen
>
>
>
[Answer]
## Be a polyglot programmer
If you know 1 language, you can steal the good stuff from 1 language.
If you know 2 languages, you can steal the good stuff from 2 languages.
Likewise, if you know many languages, you can steal the good stuff from many languages.
Therefore, while you are designing a golfing language, it's beneficial to learn a lot of programming languages (which will help you create a good golfing language).
[Answer]
# Useful integer constants
Of course your golfing language has syntax that can represent any integer constant, but some integers are more useful than others. You want the useful ones to be available as a single byte. A couple of obstacles to this goal:
* With a traditional decimal format, only the numbers 0 through 9 can be represented in one byte. Some non-single-digit numbers, particularly 10 and -1, are very useful.
* If you have to put multiple integer literals next to each other in your code, you'll probably need an extra byte for a separator (which doesn't carry any meaning and is therefore a Bad Thing™). I think this problem occurs more often in prefix languages (like Pyth and Charcoal), but I imagine stack-based languages would suffer from it too. In Pip, it crops up when defining a list of numbers.
There are a few strategies to address these issues. Jelly, for example, represents -1 as `-` and interprets leading `0`s as separate numbers. You could even write your integer literals in duodecimal with a [signed digit system](https://en.wikipedia.org/wiki/Signed-digit_representation), which would make -1 and 10 into single-digit numbers. But the most straightforward approach is to have dedicated one-byte builtins for the most useful integer constants. Even some of the single-digit integers can use such aliases, due to the second point above.
## Some data
I did a survey of 150 of my Pip golf submissions to see which integer literals or builtins were used most often. Here are the numbers that appeared at least twice:
```
0 ||||||||||||||||||||||||||||||||||||||||||||||| 47
1 ||||||||||||||||||||||||||||||||| 33
2 |||||||||||||||||||||||||||| 28
10 |||||||||||||| 14
-1 |||||||||||| 12
3 |||||||||||| 12
8 ||||||| 7
9 ||||||| 7
4 ||||| 5
5 ||||| 5
6 |||| 4
26 |||| 4
100 |||| 4
7 ||| 3
32 ||| 3
64 ||| 3
1000 ||| 3
16 || 2
50 || 2
127 || 2
```
This list fits pretty closely with what I would expect (though I didn't think 3 would be so common). It's possible the figures will skew a bit differently depending on the language (for example, 2 will be more common if you need it for operations like "convert to base 2," "modulo 2," etc., and less important if you have builtins for those operations); but I think the overall ranking will stay pretty consistent. So:
## Suggestions
* These numbers should be representable by some one-byte syntax: -1, 10
* Consider adding one-byte aliases for these numbers if numeric literals are likely to occur next to each other: 0, 1, 2, and maybe 3, 8, 9
* Consider adding shorter aliases for these numbers if you have codepage space to spare: 26, 100, 1000, and maybe 16, 32, 64, 127
Again, there are a few ways of doing aliases. You can simply have a constant that always evaluates to that number. Pip has variables preinitialized to useful values, which can be updated through the program; for example, `i` starts at 0, which makes `++i` useful for counting things. Jelly has atoms that evaluate to the third, fourth, fifth (etc.) command-line arguments, but if that many arguments aren't provided, they evaluate to useful constants instead.
## What about other types?
I've only run the numbers on integers, but here are some gut feelings about strings and lists that deserve golfy syntax:
* Should have single-byte builtins: empty string, empty list, space, and probably newline
* Should have one- or two-byte syntax: uppercase alphabet, lowercase alphabet, common regex patterns if your language has regex, and maybe some common lists like [0], [1], [0, 1], [1, 0], and [-1, 1]
[Answer]
## Be patient while implementing your golfing language
>
> This tip might be too obvious for some people, but I see the necessity for posting this tip, since I am surprised to see many golfing language implementors abandon their golfing language long before the language is complete.
>
>
>
If you want to make a good golfing language, you should be patient while you are implementing it.
It usually takes 3-4 years in order to make a good golfing language, adding 500 or so built-ins with lots of trial-and-error. During this period, you must be persistent and resilient, and continue implementing the language anyway. Nothing great happens overnight. You always need a bit of patience while you are implementing your golfing language.
Trust me, anyone can make a good golfing language - it just takes a lot of patience to do so. Besides, other CGCC users will always be excited in learning your golfing language, so don't be discouraged if you feel your language isn't that good yet! It's going to get better as you implement it, so continue implementing your language nonetheless. :P Besides, it's perfectly fine if the language doesn't turn out to be that good, at least you had a good time implementing the language.
Furthermore, after you complete this 3-4 year period, you may still continue maintaining/developing your golfing language, depending on how good you want to make your golfing language.
[Answer]
This relates to the implementation phase
# Decide Upon How the Language Will Be Executed
The two most common options to implement your language are a) interpretation and b) transpilation.
*Interpretation* is where your language is executed step by step. In other words, you write all the processesing logic behind the language.
*Transpilation* is when you turn your language into another language. This is like translating it into another language.
Transpilation is much easier to implement than interpretation, but interpretation allows for more flexibility.
[Answer]
## Making your language high-level (e.g. starting from Mathematical notation) is probably a good starting point.
Have you heard of APL (which is based on Matrices and its operations)? It's an early target for code golfers to golf in, and it's quite concise.
Mathematics is a formalized system to express stuff in a high-level way. So if you want your language to be easy to use (attracting code golfers) and concise, you should probably find an existing mathematical notation to start with. Also, it will (probably) help users to be engaged with your language (since it's high-level, easy to learn and easy to use).
## Examples of golfing languages
For example, Husk is a langauge which incorporates a lot of Haskell elements, like lazy evaluation and function composition; Haskell is a kind of mathematical notation by itself that has evolved from lambda calculus. Husk is very concise and catches up/beats the concise golfing languages, using *just* a set of 256 instructions.
(Jelly is a language based off APL, and it's quite competitive; I guess it's fairly obvious here.)
## Would making the language high-level always attract users?
A counter example of being high level attracting more users is probably Prolog. I don't know exactly why people don't use Prolog, but it might be because people are too used to the mainstream languages and refure to switch. And Prolog is quite concise, due to its functional nature.
## The implementation process
Being high level usually means that you have to spend a lot more of your time implementing it, since the higher-level a language becomes, the higher the abstraction level goes. And that usually means a lot of code need to be written for the abstraction.
If you are lazy and don't feel like writing a lot of code just for making your golfing language, you don't have to. Just implement a lower-level language.
## How do I design the language though?
You have a plethora of methods of parsing instructions. But the usual method is to parse it as infix/tacit, since Traditional Mathematical Notation is infix.
[Answer]
## Make the syntax of your constants short
For strings, you can have implicit quotes or compressed strings. Or even, you can make 2-character compressed strings or directly index into your golfing language's built-in list of common English words.
Or built-ins for common strings (including the empty sting) may be feasible.
For integer arrays, you can create a packed array form (btw Stax has a form like this). For string arrays, you can introduce a special form (Like in Jelly) that introduces compressed strings next to each other.
For numbers, you can do something like 05AB1E's `Ƶ`, which provides a shorthand on a lot of small integers. Or like in @DLosc's tip, you can add built-ins for common numbers.
The above are merely suggestions.
## Some Recommendations
* Make sure that the syntactical shortening is appropriate for your language.
+ For example, the implicit trailing quote is somewhat useful in Jelly. However, in 05AB1E, it is only useful when you print a constant string at the end of execution. SOGL is an improvement of this. Since there are implicit *preceding* quotes, you can do a lot more things with one less byte.
* Another thing about blocks. Most modern stack-based golfing languages already merge them with the higher-order commands that take a block or two as arguments, so this can also be seen as an example of shortening the syntax of your constants.
+ By the way, you can merge it before the block (like 05AB1E) or after the block (like Stax) and use implicit braces at the start or the end of the program. Which form do you think will be useful in more tasks? ;p
+ However, you can also attempt to shorten the block syntax. For example, MathGolf has shortened blocks from 1 all the way to 8. And you can also try to implicitly group your blocks (like in Husk; during the parsing process, functions are implicitly grouped into functions with correct types.)
[Answer]
## Use the corpus
*Credits go to [@Lynn](https://github.com/DennisMitchell/jellylanguage/issues/69) for creating this method.*
Basically, if you have enough answers in your golfing language on SE, you can use a corpus to analyze your language and optimize its golfiness. Use a SEDE query, and analyze it with a script.
A couple things to note:
* 1-grams reflect the general usefulness of the 1-byte commands in your language. The higher the frequency, the more useful it is. Basically, if a 1-byte builtin is rarely used, or never used here, then it's better to add it as a 2-byte builtin. A maximum frequency of 15 is a good metric for a 2-byte builtin.
+ If you leave enough room for your 1-byte builtins, then there would be more room to add more useful builtins in the future.
* 2-grams are basically golfing opportunities, stuff that you can make into 1 byte. Again, if these occur frequently enough, like more than 15 occurences, for example, it would be nice to add as a 1-gram.
* 3-grams and 4-grams reflect the parts where most people are wasting bytes on. So if a pattern occurs frequently enough, it would be great as a 2-byte builtin.
## Tips on using the corpus
* Investigate thoroughly. Understand the exact reason why an occurence is so frequent, when you are in doubt. Read the SE answers involving this occurence.
* Consider using the 1-grams list as an insight to the 2-gram occurences.
* The number 15 used here is just as an example. The actual number should be determined by yourself, since some languages are not used as often as other languages on SE.
* The commands added should make sense to you, i.e. it doesn't look like a random combination that you won't use unless in specific circumstances.
[Answer]
## Tips for overloading
* Try not to use up every overloading space you have right away ([Unless you're really good at overloading](https://github.com/dzaima/SOGLOnline)). You should be prepared for adding new overloads to your language.
* Don't overload if vectorization makes sense. Vectoriation is a really common operation. For example, vectorization is the most common 1-byter in both [Jelly](https://github.com/DennisMitchell/jellylanguage/issues/69) and [Vyxal](https://github.com/Vyxal/Vyxal/issues/14#issuecomment-1042668140), and these two are very different languages. This should show how prominent vectorization is in golfing languages.
+ For example, `+` should definitely be vectorized, because it makes sense to do so. If you overload it, you end up wasting bytes in codegolf due to an unnecessary use of a vectorization prefix.
* Sometimes, it can be hard to track down your overloads, especially if you have a lot of them. So, it can be helpful to make a table of all of your overloads, to see which instructions could be overloaded, which operations are duplicated, etc.
+ Another trick when you're designing the language. You can first list every instruction you want to overload (without actually introducing overloads). Then, try to merge all the commands you have into fewer operations (in a way that makes sense to you).
* When you don't know what things to overload in your language, generating a 1-gram corpus of a popular golfing language will lead you to some interesting ideas.
[Answer]
## Length of the builtins: 1 byte vs. 2 bytes
Here, I will attempt to provide some concrete suggestions for @Zgarb's answer upon deciding whether a builtin should be made as 1 byte or 2 bytes.
Maintaining a fairly large 1-byte space is very important. If you run out of 1-byte opcode spaces, you might find it difficult to add new golfy syntax forms, and 1-byte builtins for frequent 2-byters to your language.
Here are my obsevations on this topic:
* If it is a fundemental built-in that is commonly associated with a basic datatype in your language, a 1-byte builtin would be helpful.
+ For example, a built-in that maps an input list by a block should definitely be a 1-byte builtin.
+ Similarly, common mathematical operations, like modulus and addition, should be 1-byte as well.
+ Same thing with list concatenation.
* If you find yourself unable to solve some challenges without this builtin, or you think it is cumbersome without it, consider adding it as a 2-byte builtin. Or a 1 byte builtin if you use it frequently enough.
* If this is something you would not normally do given the datatypes to your builtin, it should defintely make it a 2-byte builtin. You can always make it a 1-byte builtin, if it is used frequently enough.
+ For example, converting the input from a unix timestamp to a formatted string probably deserves a 2-byte builtin.
## Ideas
* If some substring comes up often in a lot of answers, consider first making it a 2-byte builtin.
+ If it is already 2 bytes, make it 1 byte. The divmod builtin in Jelly is a good example. It combines a pretty common occurence of taking the quotient and the remainder into a single builtin.
* If your language uses an ASCII codepage, then you need to be even more careful on builtins. Consider heavy overloading on one-byte builtins, to pack the largest number of fundemental bultins.
* A fairly effective method, as mentioned by @mousetail below, is analyzing the frequencies of the builtins of an existing golfing language, and then decide upon the length of the builtin based on its frequency. This would ensure that your built-ins are optimally packed based on the frequencies.
[Answer]
## Code it using another programming language you already know very well
You can then create a script in that language to run the programme made using the golfing language you invented.
] |
[Question]
[
# The Challenge
I was looking into small code examples for a specific language as a small tutorial and came accross a simplified Blackjack that should be implemented. In this Challenge you will have to implement a full Blackjack game, with 5 Decks.
# The Game
You are playing against a Dealer and he has 5 Decks of Poker playing cards.
A pokerdeck contains the cards "2♠","3♠",...,"K♠","A♠","2♥",...,"A♥",...,"A♣", which may be represented by their values for 2-10, Jack-King is all 10, Ace is 11.
The gamecycle begins with the Dealear giving a card to you, and one to him self. Your goal now is to reach 21, by adding the values of the cards, that the dealer gives you.
After recieving a card, you have two options:
1. Stay: You decide, to not be dealt additional cards, therefore determining your score for the round: the sum of cards. For example: you have a 2, a 10, and a 8, and you decide to stay, then your score for the round is 20.
2. Hit: You decide to be dealt an additional card. This can lead to three cases:
* The total sum of your cards is under 21: Nothing really happens. Here you could again decide wether to stay or to hit again.
* The total sum of your cards is exactly 21: This is the best score you can get, and makes you automatically stay. If you get 21, with 2 cards (i.e.: 10 + Ace, this is called a "Blackjack") you automatically win. Else there is still possibilities for a draw.
* The Total sum of your cards exceeds 21: You busted. this is automaticaly a loose.
This is done, until you decide to stay/bust/get blackjack. Then its the Dealers turn, if you havent busted. The dealer does exactly the same. He stays/hits normally, until his score is above 17 (This is his strategy for winning). If the Dealer busts, meaning his score is above 21, you automatically win, if you havent busted yourself.
After this both you and the Dealer should have a score (i.e.: Player 20, Dealer 18). In this case the person with the higher score wins. If you draw, you draw.
# The Strategy
The best strategy for the game looks like this:
[](https://i.stack.imgur.com/fw5Jc.jpg)
Our case is slightly easier, as you cant Double and Split.
## Additional notes
You may decide how to handle user input (there should obviously be some, due to the way this game is reactive), and how to do output. The carddrawing should be random, and semi-nonreproducible (C example would be: `srand(time(0))`).
## Rules
Standard Golf rules. Shortest byte amount wins. As this is random, there arent really any good testcases, but it should look something like this:
```
~$ ./blackjack
You got [10]
Dealer got [7]
Suggested: Hit
[s]tay
[h]it
h
You got [3]
Suggested: Hit
[s]tay
[h]it
h
You got [7]
Suggested: Stay
[s]tay
[h]it
s
Dealer got [9]
Dealer got [10]
Dealer busted. You won.
Another round? [y/n]: y
Next round:
You got[10]
...
```
***Unexpected input may result in undefined behaviour.***
# Extra
Try and include Split/DoubleDown in both userinput and Suggested moves :) Good Luck.
# Notes
If my explanation of the game was satisfying for you needs [here](https://en.wikipedia.org/wiki/Blackjack) is the Wikipedia page, to the game.
]
|
[Question]
[
In scientific computing, it is often desirable to decompose some large domain into smaller "subdomains", then parallelize the computation by performing the work on each subdomain in parallel and the interaction of a subdomain with its neighboring subdomains. Since these interactions are typically data sync points, minimizing their size improves the scalability of the code to very large machines.
Consider a domain consisting of an N-dimensional Cartesian grid, where `N` is between 1 up to 6, inclusive. The minimum extent of this grid is at the coordinate `(0,0,...0)`, and the maximum extent is likewise `(n,n,...,n)` (note that `n` may be very large!).
Your goal is to partition the domain into `m` non-overlapping hyperslabs (N-D rectangles) such that the sum of the surface area of all subdomains is minimized, and the ratio of surface areas of any two subdomains is approximately unity (within 10% of an optimal solution or as close as possible).
**Inputs**
Your program should take from any input source 3 positive integer numbers: `n`, `N`, and `m`. You may assume that `m` is smaller than the total volume of the domain (i.e. a valid solution can be found). As mentioned earlier, `n` can be quite large. For the purposes of this challenge, you may assume it to fit in your language's natural integer type, or a signed 32-bit integer (whichever is larger). Error checking of inputs is not required.
**Outputs**
Your program should output to any output sink a set of `m` hyperslabs describing the produced partition (order does not matter).
A hyperslab description must contain enough information to reconstruct the minimum and maximum extents of the hyperslab in the coordinates of the global domain, i.e. you can either output these values directly, or output the centroid+width in each dimension, etc.
None of the output hyperslabs can be empty (i.e. contain 0 volume). Note that every hyperslab edge must be at an integer increment.
The union of all outputted hyperslabs must cover the entire domain.
The output does not need to be deterministic (i.e. concurrent runs with the same inputs need not give the same outputs, so long as all outputs are valid).
**Examples**
Note that the example outputs for these inputs may not necessarily match what your code produces. Hyperslabs are specified by the min/max extent in each dimension.
```
input:
4, 1, 1
output:
[(0),(4)]
```
~
```
input:
4, 1, 2
output:
[(0),(1)], [(1),(4)]
sidenote:
typically in a "real" partitioner, this would be a bad partition since one subdomain contains more work than the other.
However, for the purposes of this challenge this is a perfectly valid output.
```
~
```
input:
4, 1, 2
output:
[(0),(2)], [(2),(4)]
sidenote:
an alternative "better" valid output for the same inputs as above.
```
~
```
input:
4, 2, 2
output:
[(0,0),(2,4)], [(2,0),(4,4)]
```
~
```
input:
1000000, 6, 7
output:
[(0, 0, 0, 0, 0, 0),(428571, 333333, 1000000, 1000000, 1000000, 1000000)],
[(428571, 0, 0, 0, 0, 0),(1000000, 500000, 500000, 1000000, 1000000, 1000000)],
[(0, 333333, 0, 0, 0, 0),(428571, 1000000, 500000, 1000000, 1000000, 1000000)],
[(0, 333333, 500000, 0, 0, 0),(428571, 1000000, 1000000, 1000000, 1000000, 1000000)],
[(428571, 500000, 0, 0, 0, 0),(1000000, 1000000, 500000, 1000000, 1000000, 1000000)],
[(428571, 0, 500000, 0, 0, 0),(1000000, 500000, 1000000, 1000000, 1000000, 1000000)],
[(428571, 500000, 500000, 0, 0, 0),(1000000, 1000000, 1000000, 1000000, 1000000, 1000000)]
```
**Scoring**
This is code golf; shortest code wins. Standard loopholes apply. You may use any built-ins so long as they weren't specifically designed to solve this problem. Your code should be able to run in a reasonable amount of time (say, 10 minutes on whatever hardware you have on hand, assuming `m` isn't too large)
]
|
[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/58451/edit).
Closed 8 years ago.
[Improve this question](/posts/58451/edit)
Welcome Back to the Future's fans and enthusiastic codegolfers.
Let's begin with this simple statement : [Marty arrives in 2015 in one month (On october the 21st !)](http://istodaythedaymartymcflyarriveswhenhetravelstothefuture.com/). Therefore I propose we use the time remaining to pay him and the saga the best homage we can.
## Task
Marty left for 2015 on *October* the *26*, *1985*. Thus, you will have to write 3 code snippets of respective length 10, 26 and 85 in the language of your choice. Once executed, I'd like to see a visual representation of at least one of the 3 following symbols of Back to the Future :
**The Delorean**
[](https://i.stack.imgur.com/g6cRJ.jpg)
**The Logo**
as seen here :
[](https://i.stack.imgur.com/v565r.jpg)
Or (since Marty arrives in 2015 in the 2nd movie), the Grays Sports Almanac :
[](https://i.stack.imgur.com/XiLxN.jpg)
I don't excpect a copy of those images which are just examples. I expect your creatives ways to display one of those symbols from the Back to the Future franchise.
## The rules
* This is a popularity contest that will stop at the [end of the countdown (i.e. october 21st)](http://istodaythedaymartymcflyarriveswhenhetravelstothefuture.com/). Highest upvoted answer by then wins.
* You have to stick to one language for the three snippets.
* The 3 snippets can act separately to produce 3 results or together and produce one bigger result.
* You can use any language you'd like, even [Piet](http://www.dangermouse.net/esoteric/piet.html) if you want.
* You can of course use a language that have already been used as long as the result clearly differs from the first answer.
* The visual representation can be anything you'd like, from ASCII art to producing a JPG file. It can even be an animation if you feel like it.
## Additional Information
* [Refrain from using the standards loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
* Be creative ! We have seen that we can [tweet mathematical art](https://codegolf.stackexchange.com/questions/35569/tweetable-mathematical-art), you can even [draw with your CPU](https://codegolf.stackexchange.com/questions/33059/draw-with-your-cpu) so show me the best of your language.
The format of the answer can follow something along the line :
**Snipet length 10**
```
some_code;
...
```
**Snippet length 26**
```
some_more_code;
```
**Snippet length 85**
```
some_final_code;
...
```
**Output**
The output or a link to the output.
]
|
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 8 years ago.
[Improve this question](/posts/53429/edit)
A friend of mine got this question during an interview.
The interview ended with no luck for him, but still, we're very curious to hear the solution. The question is as follows:
Modify the code below (change 3 lines maximum) so the function will return the length of the longest sequence of the same bit, if you would flip one bit in the given array.
Note: the method's parameter is a bits array.
For example: take the bits array: "11001001010". By flipping the 5th bit from "1" to "0", we'll get: "11000001010" and the result would be: 5.
```
private static int solution(int[] a) {
int n = a.length;
int result = 0;
int i;
for (i = 0; i < n - 1; i++) {
if(a[i] == a[i + 1])
result = result + 1;
}
int r = 0;
for (i = 0; i < n; i++) {
int count = 0;
if(i > 0) {
if(a[i - 1] != a[i])
count = count + 1;
else
count = count - 1;
}
if(i < n - 1) {
if(a[i + 1] != a[i])
count = count + 1;
else
count = count - 1;
}
if(count > r)
r = count;
}
return result + r;
}
```
]
|
[Question]
[
Let the characters `0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ` represent the particles of 36 [immiscible](http://en.wikipedia.org/wiki/Miscibility) fluids, each more [dense](http://en.wikipedia.org/wiki/Density) than the last. So the `0` fluid is the least dense and floats on all the others, while `Z` is the densest and always sinks.
Let `#` represent a solid particle that cannot move at all..
Consider a rectangular grid of some of these 37 characters, with anything out of bounds treated as `#`. Gravity will want to stabilize them with the least dense fluids on top and the most dense on the bottom.
Our procedure for stabilization is:
1. Choose a random grid cell *c* that is not a `#` and has a density greater than that of at least one of the 3 neighboring cells on the layer below it ([southwest, south, and southeast](http://en.wikipedia.org/wiki/Moore_neighborhood)) that is not a `#`.
Stop procedure if no such choice exists.
2. Let *d* be a cell randomly sampled from these valid neighboring cells with the least densities.
3. Swap the values at *c* and *d*.
4. Repeat procedure until it has stopped.
# Example
Running the procedure on
```
A01
#10
020
```
might start out step 1 by selecting the `A`. There is only one cell below it with smaller density so the next grid would be
```
101
#A0
020
```
The procedure might continue on as
```
101 100 000 000
#00 #01 #11 #01
A20 A20 A20 A21
```
The last arrangement being stable.
# Challenge
Write a program that takes in a rectangular string of the 37 characters via stdin, command line, or function call. Initially, the given grid should be printed to stdout, but each time `Enter` is hit, one swap (step 3) should be done and the grid reprinted, separated from the last grid by an empty line. When the grid with no more possible swaps is printed (the end of the procedure) the program immediately ends.
* Grid dimensions will be 1×1 at minimum, and have no maximum size (as limited by `Int.Max` or computer memory). The grid is not always square.
* You can assume valid input. The grid will always be perfectly rectangular, containing only uppercase alphanumeric characters and `#`.
* You may use a key besides `Enter` if it is more convenient.
* Your program must follow [something equivalent to] the stabilization procedure, including using [pseudo]randomness for steps 1 and 2.
* In the input (but not the output) underscores (`_`) may be used instead of newlines.
# Scoring
This is code-golf, so the shortest code [in bytes](https://mothereff.in/byte-counter) wins. There are bonuses however.
**Bonus 1 - Horizontal periodic boundary conditions: (minus 30 bytes)**
Instead of treating the left and right out of bounds areas as `#`, connect them with [PBC](http://en.wikipedia.org/wiki/Periodic_boundary_conditions). There should be an option in your code where changing something like `0` to `1` or `False` to `True` enables or disables the PBC.
**Bonus 2 - Graphics instead of text: (minus 100 bytes)**
Instead of using blocks of text, use images (of any common truecolor format). Represent `0...Z` with 36 distinct but related colors, e.g. a gradient from white to dark blue, and `#` with some other distinct color like dark red.
The program behaves the same way except now an image is either saved to a file (it may be the same file each time) or displayed to the screen for each grid swap in place of any textual output. The input may still be textual or some valid image, your choice.
Whether you do this bonus or not, giving output examples is highly encouraged.
[Answer]
## Python, 300 298 chars
```
import random
C=random.choice
R=raw_input
G=list(R().replace('_','\n'))
S=w=G.index('\n')
while S:
print''.join(G);S=[];R()
for i,c in enumerate(G):
B=[(d,j)for j,d in enumerate(G[i+w:i+w+3])if'/'<d<c]
if B:S+=[(i,[i+w+j for d,j in B if d==min(B)[0]])]
if S:i,B=C(S);j=C(B);G[i],G[j]=G[j],G[i]
```
Run it like `cat inputfile - | fluid.py`. The input file should be a single line using `_` as a line separator.
] |
[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/6284/edit).
Closed 6 years ago.
[Improve this question](/posts/6284/edit)
Back when I was a freshman in highschool taking chemistry, I'd look at the periodic table of elements and spell dirty words out with the number of the elements (HeCK would be 2619, 2-6-19).
I was thinking about this the other day when I saw an amazing shirt that spelled out BeEr (4-68)
So my codegolf challenge is shortest program to output a list of words you can spell with the periodic table of elements AND the number code that would represent that word.
/usr/share/dict/words or whatever dictionary you want to use for the word list. If you're using a "non-standard" word list, let us know what it is!
[Answer]
## GolfScript (339 303 302 301 294 chars)
```
n/{{{32|}%}:L~['']{{`{\+}+'HHeLiBeBCNOFNeNaMgAl
PSClArKCa TiVCrMnFe
ZnGaGeAsSeBrKrRbSrYZr
MoTcRuRhPdAgCd
TeIXe
BaLaCePrNdPmSmEuGdTbDy
ErTm
Lu
TaWRe
IrPtAuHgTl
AtRnFrRaAcThPaU
AmCm
EsFmMd
LrRfDbSg
MtDsRg
UutFl
Lv'{[1/{.0=96>{+}*}/]}:S~:^/}%.{L}%2$?.){=S{^?}%`+p 0}{;{L.,2$<=},.}if}do}%;
```
With credit to [PhiNotPi](https://codegolf.stackexchange.com/users/2867/phinotpi) whose observation on unnecessary elements allowed me to save 33 chars.
This is IMO much more idiomatic GolfScript than the previous recursive approach.
Note that I allow words in the dictionary to be mixed case (`L` is a function to lower-case text on the assumption that it doesn't matter if non-alpha characters get broken) but reject any with apostrophes or accents.
Since this is code golf, I've optimised for code length rather than speed. This is horrendously slow. It expects the word list to be supplied at stdin and outputs to stdout in the format:
```
"ac[89]"
"accra[89 6 88]"
"achebe[89 2 4]"
...
```
(lower-casing any mixed-case input words for which it finds a match).
If you're more interested in the elements than the numbers per se, for the low low price of 261 253 chars you can use
```
n/{{{32|}%}:L~['']{{`{\+}+'HHeLiBeBCNOFNeNaMgAlPSClArKCaTiVCrMnFeZnGaGeAsSeBrKrRbSrYZrMoTcRuRhPdAgCdTeIXeBaLaCePrNdPmSmEuGdTbDyErTmLuTaWReIrPtAuHgTlAtRnFrRaAcThPaUAmCmEsFmMdLrRfDbSgMtDsRgUutFlLv'[1/{.0=96>{+}*}/]/}%.{L}%2$?.){=p 0}{;{L.,2$<=},.}if}do}%;
```
which gives output like
```
"Ac"
"AcCRa"
"AcHeBe"
...
```
[Answer]
# Ruby - 547 393
New version, thanks for the suggestions:
```
e='HHeLiBeBCNOFNeNaMgAlSiPSClArKaCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo'.scan(/[A-Z][a-z]*/).map &:upcase
r="(#{e.join ?|})"
$<.each{|w|(i=0;i+=1 until w=~/^#{r*i}$/i
$><<w;p$~.to_a[1..-1].map{|m|e.index(m.upcase)+1})if w=~/^#{r}+$/i}
```
---
```
e=%w{h he li be b c n o f ne na mg al si p s cl ar ka ca sc ti v cr mn fe co ni cu zn ga ge as se br kr rb sr y zr nb mo tc ru rh pd ag cd in sn sb te i xe cs ba la ce pr nd pm sm eu gd tb dy ho er tm yb lu hf ta w re os ir pt au hg tl pb bi po at rn fr ra ac th pa u np pu am cm bk cf es fm md no lr rf db sg bh hs mt ds rg cn uut fl uup lv uus uuo}
x = "(#{e.join(?|)})"
regex = /^#{x}+$/i
File.foreach('/usr/share/dict/words'){|w|
if w=~/^#{x}+$/i
puts w
i=1
i+=1 until w=~/^#{x*i}$/i
puts $~[1..-1].map{|m|e.index(m.downcase)+1}.join ?-
end
}
```
uses regexes. slow, and much room for improvement but i must go now :-)
[Answer]
## Python 710 (357 + 261 + 92)
```
e=". h he li be b c n o f ne na mg al si p s cl ar k ca sc ti v cr mn fe co ni cu zn ga ge as se br kr rb sr y zr nb mo tc ru rh pd ag cd in sn sb te i xe cs ba la ce pr nd pm sm eu gd tb dy ho er tm yb lu hf ta w re os ir pt au hg tl pb bi po at rn fr ra ac th pa u np pu am cm bk cf es fm md no lr rf db sg bh hs mt ds rg cn uut fl uup lv uus uuo".split()
i=e.index
def m(w,p=("",[])):
if not w:return p
x,y,z=w[0],w[:2],w[:3]
if x!=y and y in e:
a=m(w[2:],(p[0]+y,p[1]+[i(y)]))
if a:return a
if x in e:
b=m(w[1:],(p[0]+x,p[1]+[i(x)]))
if b:return b
if z in e:
c=m(w[3:],(p[0]+z,p[1]+[i(z)]))
if c:return c
f=open('/usr/share/dict/words','r')
for l in f:
x=m(l[:-1])
if x:print x[0],x[1]
f.close()
```
There's sure to be room for improvement in there somewhere. It's also worth noting that the second level of indentation uses the tab character.
It takes just over 5 seconds (on my computer) to go through the whole dictionary, producing output like this:
```
acaciin [89, 89, 53, 49]
acacin [89, 89, 49]
acalycal [89, 13, 39, 6, 13]
...
```
By adding another **18** characters, you can get output with the right capitalization:
```
e=". H He Li Be B C N O F Ne Na Mg Al Si P S Cl Ar K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe Cs Ba La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn Fr Ra Ac Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr Rf Db Sg Bh Hs Mt Ds Rg Cn Uut Fl Uup Lv Uus Uuo".split()
i=e.index
def m(w,p=("",[])):
if not w:return p
w=w.capitalize()
x,y,z=w[0],w[:2],w[:3]
if x!=y and y in e:
a=m(w[2:],(p[0]+y,p[1]+[i(y)]))
if a:return a
if x in e:
b=m(w[1:],(p[0]+x,p[1]+[i(x)]))
if b:return b
if z in e:
c=m(w[3:],(p[0]+z,p[1]+[i(z)]))
if c:return c
OUTPUT:
AcAcIIn [89, 89, 53, 49]
AcAcIn [89, 89, 49]
AcAlYCAl [89, 13, 39, 6, 13]
...
```
You can also check individual words:
```
>>> m("beer")
('beer', [4, 68])
```
[Answer]
## Python - 1328 (975 + 285 chars of code + 68 dictionary code)
```
t1={'c':6,'b':5,'f':9,'i':53,'h':1,'k':19,'o':8,'n':7,'p':15,
's':16,'u':92,'w':74,'v':23,'y':39}
t2={'ru':44,'re':75,'rf':104,'rg':111,'ra':88,'rb':37,
'rn':86,'rh':45,'be':4,'ba':56,'bh':107,'bi':83,
'bk':97,'br':35,'os':76,'ge':32,'gd':64,'ga':31,
'pr':59,'pt':78,'pu':94,'pb':82,'pa':91,'pd':46,
'cd':48,'po':84,'pm':61,'hs':108,'ho':67,'hf':72,
'hg':80,'he':2,'md':101,'mg':12,'mo':42,'mn':25,
'mt':109,'zn':30,'eu':63,'es':99,'er':68,'ni':28,
'no':102,'na':11,'nb':41,'nd':60,'ne':10,'np':93,
'fr':87,'fe':26,'fl':114,'fm':100,'sr':38,'kr':36,
'si':14,'sn':50,'sm':62,'sc':21,'sb':51,'sg':106,
'se':34,'co':27,'cn':112,'cm':96,'cl':17,'ca':20,
'cf':98,'ce':58,'xe':54,'lu':71,'cs':55,'cr':24,
'cu':29,'la':57,'li':3,'lv':116,'tl':81,'tm':69,
'lr':103,'th':90,'ti':22,'te':52,'tb':65,'tc':43,
'ta':73,'yb':70,'db':105,'dy':66,'ds':110,'at':85,
'ac':89,'ag':47,'ir':77,'am':95,'al':13,'as':33,
'ar':18,'au':79,'zr':40,'in':49}
t3={'uut':113,'uuo':118,'uup':115,'uus':117}
def p(s):
o=0;b=0;a=[];S=str;l=S.lower;h=dict.has_key;L=len
while o<L(s):
D=0
for i in 1,2,3:exec('if h(t%d,l(s[o:o+%d])) and b<%d:a+=[S(t%d[s[o:o+%d]])];o+=%d;b=0;D=1'%(i,i,i,i,i,i))
if D==0:
if b==3 or L(a)==0:return
else:b=L(S(a[-1]));o-=b;a.pop()
return '-'.join(a)
```
For the dictionary part:
```
f=open(input(),'r')
for i in f.readlines():print p(i[:-1])
f.close()
```
[Answer]
## C, 775 771 chars
```
char*e[]={"h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","uut","fl","uup","lv","uus","uu",0};
b[99],n;
c(w,o,l)char*w,*o,**l;{
return!*w||!strncmp(*l,w,n=strlen(*l))&&c(w+n,o+sprintf(o,",%d",l-e+1),e)||*++l&&c(w,o,l);
}
main(){
while(gets(b))c(b,b+9,e)&&printf("%s%s\n",b,b+9);
}
```
**Input**: Word per line, must be lowercase. `usr/share/dict/words` is fine.
**Output**: Word and numbers, e.g.: `acceptances,89,58,15,73,7,6,99`
**Logic**:
`c(w,o,l)` checks the word `w`, starting with element `l`.
Two-way recursion is used - if the first element matches the head of the element list, check the remainer of `w` against the full element list. If this match fails, check the word against the tail of the list.
The buffer `o` accumulates the element numbers along the successful path. After a match, it will contain the list of numbers, and is printed.
**Issues**:
The list isn't encoded efficiently - too much `"` and `,`". But this way it's easy to use. I'm sure it can be much improved, without too much cost in code.
] |
[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/23383/edit).
Closed 8 years ago.
[Improve this question](/posts/23383/edit)
# Code Golfed Tetris
Inspired by a [popularity-question](/questions/tagged/popularity-question "show questions tagged 'popularity-question'") [(Re)Implementing Tetris](https://codegolf.stackexchange.com/questions/11175/reimplementing-tetris) and a [challenge on SO](https://stackoverflow.com/questions/3858384/code-golf-playing-tetris) 3 years ago *when PCG did not yet exist*, the classy tetris has yet to live again in the art-work of PCG's golfers. So here are the features:
## Required:
* Game must be playable.
* Playfield or blocks are 10 in width and 20 in height
* Complete [7 tetrominoes](http://tetris.wikia.com/wiki/Tetromino) are involved
* Controls on the current tetromino: Right and Left Navigator, Tetromino rotator (*Can be only clockwise*), & Hard drop.
## Bonuses:
* **-50** Distinguished color for each tetromino
* **-50** Distinguished texture for each tetromino

*Provide a photo of the output for those who can't emulate 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/13071/edit).
Closed 8 years ago.
[Improve this question](/posts/13071/edit)
## Algorithm for nesting submited jobs to reduce paper roll usage.
Working with a 36" large format printer, with paper roll as source (150feet=45meters).
With a delay loop on print server queue: waiting 30 seconds before printing in case another job are comming too.
At begining of (perl) print script, it do a list of paper sizes as an output from `gs -sDEVICE=bbox`, with all pages of all jobs in last 30 seconds and return only one indexed list of page sizes, like:
### Input sample
```
0:807.4780x562.6371
1:562.6370x807.4780
2:1700.0000x4251.0000
3:550.6150x786.1020
4:594.0000x840.9060
5:504.7200x761.0000
6:368.3280x761.0000
7:1193.0000x1685.0000
```
All values are in 1/72 inches (postscript dot).
The roll is `36 x 72 = 2592` dot with but have 15dot margin.
The orientation of roll is: `Y=<width; max 2562 dots>` and `X=<length: max not specified but ~127Kdots>`. So when start printing, the top-left corner is one right side of printer and sheet is going out from the *top of postscript page*.

The goal of the challenge is to build the quicker algorithm to choose **the smallest** paper length to cut out from the roll and the way of nesting all pages on this paper sheet (adding a little fixed space between plots for cutter)... and having smallest number of cut (see drawing: *reducing cut*).
### Fixed Variables
```
ROLL WIDTH = 36 x 72
PRINTER MARGIN = 15 x 2
PLOT SEPARATION = 15
```
**Important:** The pages may have to be re-ordered and rotated in order to find the best arrangment.
Desired output: First paper length alone on first line, than all page, one by line, in format: `<Index>:<X offset>x<Y offset><Rotation flag (R)`
### Output sample
```
4281
0:1715x0
1:1715x577R
2:0x0
3:1715x1400R
...
```
Note: This sample may be wrong: I'm not sure now if `R` are rightly placed or have to be inversed. That's doesn't matter in that:
* `R` stand for rotation and is a flag. But his meaning stay free it could be used to say *to rotate* or *to not rotate* (the rotation angle could be `90°` or `270°`, as you prefer;-).
### Number of cuts
This have to be calculated only for **separating** plots, not do finalize margins. This mean: *One separation = one cut, not two*. But the rush have to be dropped!
In others word: border added could be *separator/2* to *plotter margin*.
A cut have to be **straight** and **end to end** on a dimension of a sheet or already cutted sheet.
# Goal:
**The winner** will be the first to offer a full useable implementation of its algorithm able to process upto 20 rectangles in less than 30 seconds. (With shebang or command line sample). Any language commonly used in production is acceptable. (meaning: no brainf@#k, but lisp could be accepted.)
**Bonus** if in case of one fixed size of paper length due to one big plot, all other jobs are placed in the meaning of **reducing** number of paper **cut**.
]
|
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/504/edit)
From [SO](https://stackoverflow.com/q/4897280/88622).
You are given an array with positive and negative integers. Write a function to change the elements order in the array such that negative integers are at the beginning, the positive integers are at the end and two integers that have the same sign don't change order.
Example:
* **Input** 1,7,-5,9,-12,15
* **Output** -5,-12,1,7,9,15
* **Input** 1,-2,-1,2
* **Output** -2, -1, 1, 2
Constraints: O(n) time limit and O(1) extra memory.
]
|
[Question]
[
**This question already has answers here**:
[Generate any random integer](/questions/42786/generate-any-random-integer)
(21 answers)
Closed 7 years ago.
You have to create a code which prints
```
:)
```
a random number of times from 1 to 255 inclusive. Your output may not contain any whitespace.
**Your score :**
The count in bytes
**EDIT** : Also show 3 outputs of your code
[Answer]
# JavaScript (ES6), 25
```
":)".repeat(new Date%256)
```
**Outputs (REPL):**
```
> ":)".repeat(new Date%256)
":):):):):)"
> ":)".repeat(new Date%256)
":):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)"
> ":)".repeat(new Date%256)
":):):):):):):):):):):):):):):):):):):):):):):):):):):)"
```
[Answer]
## C - 116 (including artistic whitespace)
```
x,i; main
(){ srand
(time
(0));
for (x=
rand() %256;
i<x; i++)
printf(":)");}
```
I never get to do ASCII art code, and the 65 needed characters in the code are already running long as is... This was actually harder than I thought it would be because of the small number of characters to work with and the density of the code. Gets the point across at least.
**Boring version:**
```
x,i;main(){srand(time(0));for(x=rand()%256;i<x;i++)printf(":)");}
```
**Note** - Auto code counts are going to be off because I had to replace 8 tabs with spaces to get it to look the same in the code window. You can verify my count [here](http://pastebin.com/2NXZ2WqT) if you want.
**Edit:** Oops, forgot to post output (newlines added for legibility).
```
comintern@fidel ~ $ ./a.out
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):)
comintern@fidel ~ $ ./a.out
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
comintern@fidel ~ $ ./a.out
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):)
```
[Answer]
# GolfScript, 12 characters
```
":)"256rand*
```
Nothing really interesting here.
[Answer]
# Scala REPL 1337
Scala makes everyone happy. Need 266 votes to lower the score.
```
("""
:^) :^( :^[ :^] :^D :^P :^b :^&
:o) :o( :o[ :o] :oD :oP :ob :o&
:O) :O( :O[ :O] :OD :OP :Ob :O&
:) :( :[ :] :D :P :b :&
;^) ;^( ;^[ ;^] ;^D ;^P ;^b ;^&
;o) ;o( ;o[ ;o] ;oD ;oP ;ob ;o&
;O) ;O( ;O[ ;O] ;OD ;OP ;Ob ;O&
;) ;( ;[ ;] ;D ;P ;b ;&
=^) =^( =^[ =^] =^D =^P =^b =^&
=o) =o( =o[ =o] =oD =oP =ob =o&
=O) =O( =O[ =O] =OD =OP =Ob =O&
=) =( =[ =] =D =P =b =&
8^) 8^( 8^[ 8^] 8^D 8^P 8^b 8^&
8o) 8o( 8o[ 8o] 8oD 8oP 8ob 8o&
8O) 8O( 8O[ 8O] 8OD 8OP 8Ob 8O&
8) 8( 8[ 8] 8D 8P 8b 8&
B^) B^( B^[ B^] B^D B^P B^b B^&
Bo) Bo( Bo[ Bo] BoD BoP Bob Bo&
BO) BO( BO[ BO] BOD BOP BOb BO&
B) B( B[ B] BD BP Bb B&
%^) %^( %^[ %^] %^D %^P %^b %^&
%o) %o( %o[ %o] %oD %oP %ob %o&
%O) %O( %O[ %O] %OD %OP %Ob %O&
%) %( %[ %] %D %P %b %&
@^) @^( @^[ @^] @^D @^P @^b @^&
@o) @o( @o[ @o] @oD @oP @ob @o&
@O) @O( @O[ @O] @OD @OP @Ob @O&
@) @( @[ @] @D @P @b @&
X^) X^( X^[ X^] X^D X^P X^b X^&
Xo) Xo( Xo[ Xo] XoD XoP Xob Xo&
XO) XO( XO[ XO] XOD XOP XOb XO&
X) X( X[ X] XD XP Xb X&
^__^
""".replaceAll("\n","").replaceAll("x|X",":)")
.replaceAll("(:|=|8|B|;|%|@)+",":")
.replaceAll("[^:]+","\\)")
.substring(0,new scala.util.Random().nextInt(256)*2))
```
## Output 1
```
res32: String = :)
```
## Output 2
```
res33: String =
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):)
```
## Output 3
```
res34: String =
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
```
FYI, the code to generate all smileys is the following:
```
for(i <- ":;=8B%@X"; j <- "^oO".toIterator.map(_.toString) ++ List(""); k <- ")([]DPb&") yield (i.toString+j.toString+k.toString)
// eyes nose or nothing mouth
```
[Answer]
## Python 23
```
print':)'*(id(9)/8%256)
```
**Demo**
```
D:\temp>smiley.py
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):)
D:\temp>smiley.py
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):)
D:\temp>smiley.py
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):)
```
[Answer]
# Java 72 lines 1,832 bytes and ~50 seconds runtime
Me and my buddy pair programmed (Agile Methods ftw) this golfed Java Enterprise solution.
```
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
public class EnterpriseJavaSolution {
public static class BodyPart {
private char[] part = new char[2];
public BodyPart (String part) {
this.part = part.toCharArray();
}
public String toString() {
return new String(part);
}
}
public static class Eyes extends BodyPart {
public Eyes () {
super(":");
}
}
public static class Mouth extends BodyPart {
public Mouth () {
super(")");
}
}
public static class Face extends BodyPart {
/**
* So generic, much parts
*/
public Face (List<BodyPart> parts) {
super(parts.toString());
}
}
public static void main (String[] args) {
SecureRandom seed = new SecureRandom();
//Very random, dont use all RAM though!!
SecureRandom reallyRandom = new SecureRandom(seed.generateSeed((int) (Runtime.getRuntime().maxMemory() / 2.0)));
byte[] randomNumber = new byte[1];
reallyRandom.nextBytes(randomNumber);
ArrayList<Face> smilees = new ArrayList<Face>();
//Why are Java bytes signed! Such inconvenience
for (int numSmilee = 0; numSmilee <= Math.abs(randomNumber[0] * 2.0); numSmilee++) {
ArrayList<BodyPart> bits = new ArrayList<BodyPart>(new Integer((int)2.0)); //Optimal
bits.add(new Eyes());
bits.add(new Mouth());
smilees.add(new Face(bits));
}
//TODO: make N-tier solution for printing
System.out.println(smilees.toString().replaceAll("[^:)]",""));
}
}
```
I've timed the runtime and given some example output below. I'm satisfied at the production readiness of this code.
```
$ time java EnterpriseJavaSolution
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
real 0m53.678s
user 0m4.380s
sys 0m48.568s
$ time java EnterpriseJavaSolution
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
real 0m51.928s
user 0m4.218s
sys 0m46.704s
$ time java EnterpriseJavaSolution
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
real 0m55.480s
user 0m4.074s
sys 0m50.621s
```
[Answer]
# PowerShell 21, 17
```
":)"*(Random 256)
```
>
> PS C:\Users\DocMax> ":)"\*(Random 256)
> :):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
>
>
> PS C:\Users\DocMax> ":)"\*(Random 256)
> :):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
>
>
> PS C:\Users\DocMax> ":)"\*(Random 256)
> :):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
>
>
>
**Edit:** Removed `Get-` following Rynant's awesome news-to-me input. It's not often that PowerShell is competitive at code golf.
[Answer]
## C 50 48 44 (with the suggestion from @urogen and @n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳)
*Note I liked what @Comintern, so tried to do something similar with my answer*
```
/*
Uninitialized c will always randomized to an address range (assuming system
supports ASLR.
Recursion instead of loop to reduce code length
As whitespace is not counted, organized the code to represent a smiley character
*/
main(a
,
c)
{c &&
main (
printf (
":)" )
,( c&
255
)
-1);}
```
**Demo**
```
D:\temp>Smiley.exe
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):)
D:\temp>Smiley.exe
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):)
D:\temp>Smiley.exe
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):)
```
**IDEONE**
<http://ideone.com/ZWPjqS>
[Answer]
# Befunge 98 - 20 bytes (with unicode)
```
?1+:'ÿ`!j@"):",,>
@
```
`?` sends the IP in a random direction, either left, right, up, or down. After doing so, I increment a counter and compare it to 255: `1+:'ÿ`!`. `j@` will exit if this is the 256th time. `"):"` is the frowny face that I'm supposed to print, and `,,` prints it (output: `:)`). The `>` is to ensure that if the IP goes left, it will change directions and go right.
On each iteration, there is a `2/3` probability that the loop will exit. This means that the probability that comparing to `255` is needed (assuming perfect random) is
[```
(1/3)255 = 1/46336150792381577588313262263220434371406283602843045997201608143345357543255478647000589718036536507270555180182966478507
```](http://www.wolframalpha.com/input/?i=%281/3%29**%28255%29)
Is that close enough to zero to justify not comparing to 255 (it would save me 10 bytes, bringing me down to 10 bytes)? For comparison, this number is about `2.158 × 10-122`. The number of atoms in the universe is about `1080`. The [Planck length](http://en.wikipedia.org/wiki/Planck_length), the smallest measurable length (as in the universe does not allow for smaller), is `1.616199(97) × 10-35 m`. This means that if this number were the size of the Planck length, the Planck length would be about
[```
8.5×1059 × diameter of the observable universe (93 billion light-years)
```](http://www.wolframalpha.com/input/?i=%281.61619997979797979797979797*10**-35+meters%29*%2846336150792381577588313262263220434371406283602843045997201608143345357543255478647000589718036536507270555180182966478507%29)
First output:
```
:)
```
Second output:
```
:):)
```
Third output:
```
:):):):):)
```
---
Alternatively, if I am allowed to print null characters, then this works, for **19** bytes:
```
?,,":)"_@#-ÿ':+1
@
```
---
Exploit (you say random times in the range `0-255`, so I'll choose random in the range `0-126`, saving 1 more byte):
```
?1+:'~`!j@"):",,>
@
```
[Answer]
# J - 18 char
Surprisingly, there is a subtle behaviour in the J interpreter that prevents a quick 12 character solution: the interpreter's REPL output is truncated after 256 characters, so you have to print directly to stdout to "do it right".
```
1!:2&4^:(?256)':)'
```
Explained:
* `1!:2&4` - Print to stdout (file handle 4)...
* `^:(?256)` - ... a random number of times less than 256...
* `':)'` - ... the string `:)`.
Examples:
```
1!:2&4^:(?256)':)'
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
1!:2&4^:(?256)':)'
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
1!:2&4^:(?256)':)'
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
```
And, for posterity, here's the 12 char solution which generates the string but is unable to display it right.
```
':)'$~2*?256
```
We take the random int, multiply it by 2, and then create a string that long, cyclically pulling characters from `:)`. Yes, this is shorter than copying the string.
[Answer]
# Ruby, 18
(with help from manatwork, David Herrmann, and Victor)
```
$><<':)'*rand(256)
```
`:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)`
`:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)`
`:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)`
[Answer]
## perl ~~20~~, 17 characters
Thanks to [skibrianski](https://codegolf.stackexchange.com/users/15955/skibrianski) for shaving 3 characters.
```
say":)"x rand 256
```
Sample execution:
```
$ perl -M5.10.0 -e 'say":)"x rand 256'
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):)
$ perl -M5.10.0 -e 'say":)"x rand 256'
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):)
$ perl -M5.10.0 -e 'say":)"x rand 256'
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):)
$ perl -M5.10.0 -e 'say":)"x rand 256'
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
```
[Answer]
# PHP | 30 bytes
```
<?=str_repeat(':)',rand()%256)
```
[Answer]
# Python 2.7 - 45 bytes
```
print':)'*__import__('random').randint(0,255)
```
(Originally this printed `:)\n`, the newline was removed upon OP's clarification)
The (slightly) more idiomatic way to do this is
```
from random import*
print ':)'*randint(0,255)
```
which is... also 45 bytes, but I figured "why not make it a one-liner?"
Three sample outputs:
```
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
```
```
:):):):):):):):):):):):):):):)
```
```
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
```
[Answer]
# Mathematica 35
```
Row@Table[":)", {RandomInteger@255}]
```
---
**Examples**

[Answer]
# Pure Bash, 41
```
printf -va %$[RANDOM>>7]s;echo ${a// /:)}
```
Sample outputs:
```
$ printf -va %$[RANDOM>>7]s;echo ${a// /:)}
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
$ printf -va %$[RANDOM>>7]s;echo ${a// /:)}
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
$ printf -va %$[RANDOM>>7]s;echo ${a// /:)}
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
$
```
[Answer]
## APL: 12 characters
```
(?255)⍴⊂':)'
```
In this code, `?255` generates a random number between 1 and 255. The `⍴` function repeats the argument to the right this number of times. The expression `⊂':)'` encpsulates the string `:)` into a single object, since otherwise the expression `3⍴':)'` would yield `:):` as opposed to `:) :) :)`.
Edit: The behaviour of this function depends on the value of `⎕IO`. If it's set to 0 (the default in many versions of APL) then `?255` will return a value in the range 0-254. If it is 1, the return value with be in the range 1-255.
[Answer]
# Python - 21
The randomness is stretching the rules a fair bit, but each run will probably be different.
```
print':)'*(id(1)%255)
```
And some example runs:
```
> python -c "print ':)'*(id(1)%255)"
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
> python -c "print ':)'*(id(1)%255)"
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
> python -c "print ':)'*(id(1)%255)"
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
```
[Answer]
## Groovy (37 29 characters, @Michaël Demey's suggestion)
```
print":)"*(Math.random()*255)
```
*The initial solution was:*
```
print":)"*(new Random().nextInt(256))
```
[Answer]
## R, 34
```
cat(rep(":)",runif(1)*256),sep="")
```
[Answer]
# Pure ZSH - 32
```
repeat $[RANDOM%256] echo ":)\c"
```
Output 1:
```
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
```
Output 2:
```
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
```
[Answer]
# (PHP/Python/Perl/Javascript/others)-Polyglot - 0 bytes
---
---
Output 1:
Output 2:
Output 3:
You never specified a distribution for the random variable denoting the number of times, so this outputs from the [degenerate one](http://en.wikipedia.org/wiki/Degenerate_distribution) with the entire mass on zero. This is fine under the [definition of range](http://en.wikipedia.org/wiki/Range_(mathematics)) where it is equal to the codomain of a function, rather than its image.
Alright, it's a huge cheat, but since the `id(9)` code was successful despite not being guaranteed uniform, I figured this isn't entirely unclever.
Also compiles in C under some compilers. See [discussion here](http://www.ioccc.org/1994/smr.hint).
[Answer]
## Javascript - 51 characters
Thanks to @grc and @DocMax for shaving 3 characters.
```
for(i=0|Math.random(t='')*256;i--;)t+=':)';alert(t)
```
4 Outputs:
```
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
```
```
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
```
```
:):):):):):):)
```
```
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
```
[Answer]
**Ruby (25 Chars)**
```
rand(256).times{$><<":)"}
```
Wanted to try my hands at ruby. What better way than a codegolf ;)
[Answer]
**q - 17 bytes**
```
(2*1?255)[0]#":)"
```
or a second way:
```
(2*rand 255)#":)"
```
[Answer]
## R 37
To mirror @Sven Hohenstein's [more correct solution](https://codegolf.stackexchange.com/a/23177/3862), added `cat(<>,sep="")`:
cat(rep(':)',sum(sample(0:1,255,T))),sep="")
Including @Plannapus' suggestion (I'm an R user, not an R expert!):
```
cat(rep(':)',sample(0:255,1)),sep="")
```
Tested on [R-Fiddle](http://www.r-fiddle.org/#/).
```
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
```
[Answer]
### Julia, 23
```
print(":)"^rand(0:255))
```
Usage:
```
julia> print(":)"^rand(0:255))
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
julia> print(":)"^rand(0:255))
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
julia> print(":)"^rand(0:255))
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
```
[Answer]
Haskell (50)
```
fmap(\a->concat$replicate a":)")$randomRIO(0,255)
":):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)"
fmap(\a->concat$replicate a":)")$randomRIO(0,255)
":):):):):):):):):):):):):):):):):):):):):):):):):):):):)"
fmap(\a->concat$replicate a":)")$randomRIO(0,255)
":):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)"
```
[Answer]
# C++ 104 84 107
```
#include<iostream>
int main(){int *a=new int;a+=2;*a%=256;std::cout<<*a;while(*a-->0)std::cout<<":)";}
```
**:(** I think I'll never beat other languages in golfing !
Anyway...**OUTPUT**
**#1**
```
:):):):):):):):):):):):):):):):):):):):):):)
```
**#2**
```
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
```
**#3**
```
:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)
```
[Answer]
# Java - 59 bytes
```
int n=255;while(n--*Math.random()>0)System.out.print(":)");
```
Note that you asked for "shortest code", not shortest complete program. On each run of the loop, there is a `1/7036874417766` probability that the loop exits (see [How many double numbers are there between 0.0 and 1.0?](https://stackoverflow.com/a/2978945/1896169)). To make this a more even distribution, simply do
```
int n=0;n+=Math.random()*256;while(n-->0)System.out.println(":)");
```
Sample run: <http://ideone.com/ZLppjR>
Output #1:
`:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)`
Output #2:
`:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)`
Output #3:
`:):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):):)`
yes the outputs are identical. I'm not going to run the program until I get an output that is not identical; it would take too long.
---
Complete program (104 chars):
```
class c{public static void main(String[]a){int n=255;while(n--*Math.random()>0)System.out.print(":)");}}
```
---
Original method (92 chars):
```
String s="";for(int i=255;Math.random()*i-->0;)s+="x";System.out.print(s.replace("x",":)"));
```
] |
[Question]
[
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, [visit the help center](/help/reopen-questions).
Closed 11 years ago.
Find a way to output a large integer with few characters. Solutions will be scored based on the magnitude of the number and shortness of code.
EDIT: Let's impose a time limit of a minute on sensible hardware, where sensible is a PC you can buy off the shelves.
[Answer]
# JavaScript (10)
```
alert(1/0)
```
Prints "Infinity", did I win? :)
[Answer]
## bc (1 character)
```
9
```
Without a scoring method, this has a fair magnitude/length ratio indeed.
[Answer]
### bash (41)
approx. 10,000,000 digits:
```
ulimit -t 60;while true;do echo -n 5;done
```
[Answer]
## Python 18 characters
```
print hex(8**9**9)
```
It's about 290 million digits.
Turns out python `print` of decimal numbers is really slow, but `hex` is fast:
```
> time python -c "print hex(8**9**9)" | wc
1 1 290565371
real 0m40.514s
```
[Answer]
## Ruby - 8 chars
```
p $$**$$
```
260120641601536 digits, today on my system. ($$ is the process ID).
[Answer]
```
while(1){print 1}
```
Time to write is `O(n)` compared to length of output number.
[Answer]
## C 86 (including NL)
```
main(i){
char b[8<<14];
memset(b,'9',8<<14);
for(i=0;i<8<<15;i++)
write(1,b,8<<14);
}
```
Prints 34\_359\_973\_368 digits on my i7 620M. Challenge this score!
```
$ gcc -O3 a.c; time ./a.out | wc -c
34359738368
real 0m31.974s
user 0m0.500s
sys 0m41.031s
```
[Answer]
### bash, 35 chars, unimaginably big number
The question doesn't specify the output representation, so I'm going to go charging far past any of the numbers output by previous answers (and way way way past even Graham's number):
```
for((i=999;i--;))do printf 9→9;done
```
An even shorter answer, although with a smaller number (still larger than Graham's number) is:
(12 chars)
```
echo 3→3→3→3
```
[Answer]
## Mathematica, 5
```
10! !
```
10 factorial, factorial. Prints 22,228,104 digits in about 30 seconds on my machine.
[Answer]
**PHP**
1,500,050,000,000 digits in 53.383 seconds (1.5 trillion digits) in 61 characters:
```
$a=bcpow('1000','10000');for($i=0;$i<50000000;$i++)echo $a;
```
[Answer]
### LISP (18)
10,000,000 digits in few seconds (SBCL).
```
(expt 10 10000000)
```
[Answer]
## Clojure - 28 chars (for unreasonably large numbers)
Strategy is to repeatedly apply the function f(x)=x^x. Works fine because Clojure automatically uses BigInteger arthmetic when this starts to overflow the normal integer range.
```
(nth(iterate #(expt % %)X)Y)
```
Choose X and Y depending on how unreasonably large you want the answer to be and how long you want it to run....:
For X=2:
```
Y=0 -> 2
Y=1 -> 4
Y=2 -> 256
Y=3 -> about 3.2*10^619 (in less than 1ms)
Y=4 -> unreasonably large
```
For X=9:
```
Y=0 -> 9
Y=1 -> 387420489
Y=2 -> about 10^320000000
Y=3 -> ermmm..... even bigger than unreasonably large?
```
A couple of things to note:
* `(iterate #(expt % %)X)` creates an infinite lazy sequence of ridiculously large exponentials. Y just determines which term of the sequence you want to look at (as you can see above, even the very early terms get very large very fast...)
* if not already imported you need to (use 'clojure.contrib.math) for the expt function
[Answer]
## Bash, 10 characters
```
seq -s9 $$
```
2011.8 digits per code character today on my machine.
[Answer]
Python: 83 characters, 32,089,643 digit number on my PC in a minute
```
import sys
sys.setrecursionlimit(1e9)
def p(n):sys.stdout.write(str(n));p(n*9)
p(9)
```
Note that it will either run out of time (in which case kill it) or eventually throw stack overflow errors, so you need to pipe stderr to `/dev/null`.
[Answer]
### Windows PowerShell(7)
I guess this is cheating, but techncially the value printed *is* an integer:
```
'9'*9e6
```
Exactly 9000000 digits.
Can be made larger with (19):
```
'9'*[int]::MaxValue
```
but raises an OutOfMemoryException on my poor 32-bit machine. This, however, will work fine as long as it's left running:
```
for(){write-host -n 9}
```
[Answer]
## PHP, 115 characters:
```
<? $f=fopen("/tmp/int.txt","w");for($i=$t=0;$i<2.4e7;$i++,$t++){if($t>1e4){fputs($f,$a);$t=0;}$a.=$i;}fputs($f,$a);
```
Outputs at least 1,024,000,00 characters to /tmp/int.txt.
File size (after running): <http://codepad.viper-7.com/rgDglK>
**Output to Screen, 76 characters**
```
<? for($i=$t=0;$i<2.4e7;$i++,$t++){if($t>1e4){echo $a;$t=0;}$a.=$i;}echo $a;
```
Has the ability to output 208, 896, 814, 305 characters, tested but unconfirmed through the output. You can confirm it by only calculating the length of the output through the second link. Each page may require a few refreshes due to errors.
Output: <http://codepad.viper-7.com/rJJerv> (Will crash the page eventually)
Length: <http://codepad.viper-7.com/zWxX0C>
Both the file size verification and the length verification take less than a minute on my old laptop, the output verification crashes the brower ~20 seconds into loading. The question did not state that the script had to work via command line, so I would not expect it to give perfect results when run that way.
[Answer]
`alert(Number.MAX_VALUE); : 1.7976931348623157e+308`
`<script>function f(m){n=1;for(i=1;i<=m;i++){n*=i;}return n;}alert(f(f(9)));</script> : Infinity`
[Answer]
```
time echo "7^7^7" | bc
...
29571409790619889611503701095991663965767866370599610471047901915338\
37220795832889549191447357443319063581523185421788310894001395744859\
694202869611751580402966282378932933502849310357073612870132343
real 0m58.837s
user 0m56.220s
sys 0m0.028s
```
on a 1.6 Mhz Pentium M.
[Answer]
```
cat /dev/sda
```
It's a 256-base Integer with 640,135,028,736 digits on my 640GB hd.
Too bad some are non-printable.
[Answer]
Hmm, lets see, the largest "decimal number" I could generate
on Linux, 2.4GHz Intel/Core2 w/2GB RAM, needing:
```
real 0m51.341s
user 0m1.820s
sys 0m5.644s
```
keeping user time far below 60s.
## Perl, 15 characters
```
print 1,"0"x2e9
```
gives a number staring with **100000...** and with about 2,000,000,000 (2 billion) zeros in total.
Regards
rbo
---
Tested with
```
time perl -e 'print 1,"0"x2e9'>out
```
on a good hard drive.
[Answer]
# Ruby - 12 chars
**7.5e+306 / character of code**
**25.7 digits / character of code**
```
p 9e307.to_i
```
[Answer]
Based on @M28 's answer
**PHP 10 chars**
```
echo 9e999
```
[Answer]
## C
```
printf("-infinity");
```
What's your definition of "large"?
[Answer]
## PHP, 18
```
<?for(;1;print9){}
```
=D
[Answer]
## Ruby, 11
`p 9 while 1`
Or you can omit the `9` and pretend that it's outputting in the ascii representation of the number "0x0A0A0A0A..."
[Answer]
# Factor, 137 characters
```
USING: calendar kernel io math.order sequences ;
58 seconds hence
99999 "9" <repetition> concat
[ dup write over now after? ] loop 2drop
```
With comments,
```
! calendar => seconds hence now
! kernel => dup over loop 2drop
! io => write
! math.order => after?
! sequences => <repetition> concat
USING: calendar kernel io math.order sequences ;
! Push the stop time (58 seconds after now). This leaves 2 extra seconds
! for starting and stopping the script.
58 seconds hence
! Push a long string of "9"s. The best length is near 99999.
99999 "9" <repetition> concat
[
! Write the very long string of "9"s.
dup write
! If the stop time is after now, then loop.
over now after?
] loop
! Empty the data stack.
2drop
```
This script tries to print as many "9" digits as possible, without exceeding the time limit of one minute. The number of digits changes from run to run.
Output is **10 ^ 4\_765\_052\_349 - 1**, if I must display the number in an *xterm*.
```
$ time ~/park/factor/factor scratch.factor | tee out
99999999999999999999999999999999999999999999999999999999999999999999999999999999
99999999999999999999999999999999999999999999999999999999999999999999999999999999
...
999999999999999999 0m58.56s real 0m15.63s user 0m26.21s system
$ wc -c out
4765052349 out
```
Output is **10 ^ 22\_843\_571\_562 - 1**, if I never display the number.
```
$ time ~/park/factor/factor scratch.factor | wc -c
22843571562
0m58.32s real 0m50.27s user 0m19.50s system
```
Additional notes:
* Each `write` converts the string (Unicode codepoints) to a byte array (UTF-8). This conversion might waste time inside the loop. A faster program might make a byte array before the loop, and write the byte array inside the loop; but I cannot write a byte array to the default output stream, which is a character stream. I would have to use many characters to open a binary stream.
* A faster program might call *setitimer(2)* and handle *SIGALRM* after 58 seconds. I did not find a short way to call *setitimer(2)* from Factor.
[Answer]
# Haskell (code: 22 chars, output: 309 digits)
```
main=print$floor 1e309
```
This outputs:
179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216
Any higher exponent yields the same result, as 1e309 gets interpreted as Infinity, and this is apperantly the maximum result of `floor`.
[Answer]
# Haskell (20 characters)
```
main=print.floor$1/0
```
[Answer]
## Brainfuck, 4
Of course the answer is in base 256
```
-[.]
```
C-C after a minute. Will print a number about 255^1e10.
[Answer]
# Perl 6, 14 bytes
```
.print for^Inf
```
There is a pattern in this integer. I would name it a waterfall because it looks like one.
] |
[Question]
[
# Challenge
In this challenge, you are to code in any language a program or function that will take a string and replace certain characters within it with different characters.
# Input
The input is the same for both functions and full programs:
```
[string] [char1] [char2]
```
* `string` will be an indefinite line of characters surrounded by quotation mars, such as "Hello, World!" or "1 plus 2 = 3".
* `char1` will be a single character within `string`.
* `char2` will be a single character not necessarily in `string`.
# Output
```
[modified string]
```
Your output will take `string` and replace all instances of `char1` with `char2`, then output the result as `modified string`. Case should be ignored, so the input `"yolO" o u` should output `yulu`.
# Examples
**Input**
```
"Hello, World!" l r
```
**Output**
```
Herro, Worrd!
```
---
**Input**
```
"Slithery snakes slurp Smoothies through Silly Straws" s z
```
**Output**
```
zlithery znakez zlurp zmoothiez through zilly ztrawz
```
---
**Input**
```
"Grant Bowtie: Only the best future bass artist ever" : -
```
**Output**
```
Grant Bowtie- Only the best future bass artist ever
```
---
**Input**
```
"019 + 532 * 281 / ? = waht/?" / !
```
**Output**
```
019 + 532 * 281 ! ? = waht!?
```
# Other details
This is code golf, so the shortest answer (in bytes) at the end of the week (the 14th of September) wins. Also, *anything not specified in this challenge is fair game,* meaning that stuff I don't explain is up to you.
[Answer]
# Vim, 18 keystrokes
```
$bD:s/<C-R>"<Left><BS>/<Right>/i<CR>x$x
```
Assuming the cursor is on the first column of the first line, and the open file contains this:
```
"yolO" o u
```
The file will end up containing:
```
"yulu"
```
[Answer]
# JavaScript ES6, 28 bytes
```
(s,a,b)=>s.replace(a,b,'gi')
```
Firefox only as it uses a mozilla-specific feature.
[Answer]
# Pyth, 10 bytes
```
XQr*2w4*2w
```
Try in online: [Demonstration](http://pyth.herokuapp.com/?code=XQr%2A2w4%2A2w&input=%22Hello%20World%21%22%0Al%0Ar&test_suite_input=%22Hello%2C%20World%21%22%0Al%0Ar%0A%22Slithery%20snakes%20slurp%20Smoothies%20through%20Silly%20Straws%22%0As%0Az%0A%22Grant%20Bowtie%3A%20Only%20the%20best%20future%20bass%20artist%20ever%22%0A%3A%0A-%0A%22019%20%2B%20532%20%2A%20281%20%2F%20%3F%20%3D%20waht%2F%3F%22%0A%2F%0A%21&debug=0&input_size=3) or [Test Suite](http://pyth.herokuapp.com/?code=XQr%2A2w4%2A2w&input=%22Hello%20World%21%22%0Al%0Ar&test_suite=1&test_suite_input=%22Hello%2C%20World%21%22%0Al%0Ar%0A%22Slithery%20snakes%20slurp%20Smoothies%20through%20Silly%20Straws%22%0As%0Az%0A%22Grant%20Bowtie%3A%20Only%20the%20best%20future%20bass%20artist%20ever%22%0A%3A%0A-%0A%22019%20%2B%20532%20%2A%20281%20%2F%20%3F%20%3D%20waht%2F%3F%22%0A%2F%0A%21&debug=0&input_size=3)
### Explanation:
```
Q read a line and evaluates (reads a string with quotes)
w reads a char: a (actually reads a line)
*2 make it twice as long: aa (repeat the char)
r 4 capitalize this string: Aa
*2w read another char and repeat it: bb
X replace the letters Aa by bb in Q
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 29 bytes
```
i`(.)(?=.*\1 (.)$)|"|....$
$2
```
For scoring purposes each line goes in a separate file, but for convenience you can run the above from a single file with the `-s` flag.
As this is just a single regex replacement, you can [test it here](http://regexstorm.net/tester?p=(.)(%3f%3d.*%5c1+(.)%24)%7c%22%7c....%24&i=%22Slithery+snakes+slurp+Smoothies+through+Silly+Straws%22+s+z&r=%242&o=i).
The regex consists of three parts, one to do the substitution and two to clean up the rest of the input. This is the substitution part:
```
(.) # Match a character and capture it in group 1.
(?= # Lookahead to ensure that this is the character we're searching for.
.* # Consume arbitrary characters to move to the end of the string.
\1 (.)$ # Ensure we can match the captured character, then a space, then
# another character and then the end of input. That other character
# is captured in group 2.
)
```
This match is replaced by `$2`, i.e. the character to be substituted in.
The other two possibilities are either to match a `"`, or to match the last four characters of the input. In either case group two is empty, so the replacement string `$2` evaluates to an empty string and the match is simply removed from the input. This cleans up the quotes and the characters at the end.
`i`` simply activates case insensitive matching.
[Answer]
# gawk - 48
```
IGNORECASE=gsub(/"/,_),gsub($(NF-1),$NF)+(NF-=2)
```
That IGNORECASE hurts...
*How to use*
In bash enter: `awk 'IGNORECASE=gsub(/"/,_),gsub($(NF-1),$NF)+(NF-=2)'`
Then enter a string in quotes and the two characters. In front of some characters ("[" and "(" I know of) you have to enter a backslash, because awk would try to interpret them as regular expression instead.
[Answer]
# Octave, 28
An anonymous function using built in functions.
```
@(W,T,F)strrep(lower(W),T,F)
```
Assuming it is stored in `f` we can call it as follows:
```
f('Slithery snakes slurp Smoothies through Silly Straws','s','z')
```
[Answer]
## R, 28
```
function(s,c,r)gsub(c,r,s,T)
```
Had the order of the arguments been (c,r,s), I thought of doing
```
functional::Curry(gsub,i=T)
```
`functional` is a 3rd-party package whose `Curry` functional allows redefining function arguments: here, returns a function like `gsub` but with the modified `ignore.case = TRUE`.
[Answer]
# CJam, ~~18~~ 17 bytes
Kind of awkward handling the quotes and upper vs. lower case. But I believe it works for all cases:
```
l'"%~S%(eu_el+\er
```
[Try it online](http://cjam.aditsu.net/#code=l'%22%25~S%25(eu_el%2B%5Cer&input=%22Slithery%20snakes%20slurp%20Smoothies%20through%20Silly%20Straws%22%20s%20z)
Thanks to @Dennis for golfing 1 byte.
Note that this is a full program that takes the input exactly as specified in the question. I can make this shorter if the input requirements are interpreted more flexibly.
Explanation:
```
l Get input.
'"% Split at quotes. This separates the string from the remaining arguments,
and gets rid of the quotes.
~ Unwrap the list. We now have two strings on the stack, the input text
and a string containing the two letters.
S% Split the string containing the two letters.
( Pop off the first ("source") letter.
eu Convert it to upper case.
_el Copy and convert to lower case.
+ Concatenate the two, giving us a string with upper and lower case.
\ Swap the second ("target") letter to top.
er Transliterate.
```
[Answer]
# Scala, 59 bytes
```
(s:String,a:Char,b:Char)=>(s"(?i)$a"r).replaceAllIn(s,""+b)
```
An anonymous function that uses `s""` alongwith `""r` to dynamically build a case-insensitive regex.
[Answer]
# Ruby, 17 bytes
```
f=->s,*r{s.tr *r}
```
For example:
```
> f["Hello there!", ?e, ?a]
=> Hallo thara!
```
[Answer]
# PowerShell, 33 30 Bytes
```
param($a,$b,$c)$a-replace$b,$c
```
Expects input via command-line argument. PowerShell has many built-in case-insensitive operators that just tack on an `i` in front of the usual operator -- here as `-ireplace` instead of `-replace` -- so the case-insensitive matching was actually pretty easy.
```
PS C:\Tools\Scripts\golfing> .\string-shenanigans.ps1 "Hello, World!" l r
Herro, Worrd!
PS C:\Tools\Scripts\golfing> .\string-shenanigans.ps1 "Slithery snakes slurp Smoothies through Silly Straws" s z
zlithery znakez zlurp zmoothiez through zilly ztrawz
PS C:\Tools\Scripts\golfing> .\string-shenanigans.ps1 "019 + 532 * 281 / ? = waht/?" / !
019 + 532 * 281 ! ? = waht!?
```
Saved 3 bytes thanks to [briantist](https://codegolf.stackexchange.com/users/30402/briantist)
[Answer]
# Pyth, ~~7~~ 19? / 15 bytes
```
jwcjrz1cwrz0rz1
```
[Example Input](https://pyth.herokuapp.com/?code=jwcjrz1cwrz0rz1&input=S%0Aq%0ASlithery+snaKEs+slurp+Smoothies+through+Silly+Straws&debug=0)
(My second Pyth program, ever). Any tips on golfing are welcome. A lot of the bytes are going to the repeated `rz1/rz0`. I could chop some of these I could be guaranteed the case.
---
If quotes are *required*, a slightly larger 19-byte program handles that:
```
jwcjrz1c:w1_1rz0rz1
```
---
## Explanation:
This basically. Takes a string:
```
Slithery snaKEs
```
Then, chops all lowercase instances of the the character to replace.
```
['Slithery ','naKE','']
```
Then joins with the uppercase instance:
```
Slithery SnaKES
```
Then chops on the uppercase instance:
```
['','lithery ','naKE']
```
Then joins with the *new character*:
```
qlithery qnaKEq
```
[Answer]
# Pyth - 11 bytes
A simple regexp solution with case insensitive. Will try to translate to Retina if I get it to compile.
```
:Q+"(?i)"ww
```
[Test Suite](http://pyth.herokuapp.com/?code=%3AQ%2B%22%28%3Fi%29%22ww&input=Hello+World%21%0Al%0Ar&test_suite=1&test_suite_input=%22Hello%2C+World%21%22%0Al%0Ar%0A%22Slithery+snakes+slurp+Smoothies+through+Silly+Straws%22%0As%0Az%0A%22Grant+Bowtie%3A+Only+the+best+future+bass+artist+ever%22%0A%3A%0A-%0A%22019+%2B+532+%2a+281+%2F+%3F+%3D+waht%2F%3F%22%0A%2F%0A%21&debug=0&input_size=3).
[Answer]
# mSL, 68 bytes
```
$replace($gettok($1-,-3-1,32),$gettok($1-,-2,32),$gettok($1-,-1,32))
```
[Answer]
## Bash 4.0+, 21 bytes
Command-line arguments.
```
tr ${2^}${2,} $3<<<$1
```
[Answer]
# C#, 93 120 124 123 bytes
```
class A{static void Main(string[]a){System.Console.Write(a[0].Replace(a[1].ToLower(),a[2]).Replace(a[1].ToUpper(),a[2]));}}
```
Not sure if I can golf this much better than this, but surprisingly low byte count for C# =D
**EDIT:** Thanks, Reto Koradi for pointing out the case sensitivity.
**EDIT 2:** More stuff I missed out on. Maybe doing this during a break in work isn't the best time.
[Answer]
# Shell 15 bytes:
```
sed s/$1/$2/gi
```
Save as `submission.sh` and run as:
```
$ echo "Hello, World" | ./submission.sh h e
eello, World
```
## Explanation:
sed (stream editor) has a substitute command, which parses standard input and substitutes string $1 for string $2. The `g` modifier substitutes globally in the input string, and `i` modifier produces a case-insensitive match.
# Old Solution:
## Shell, 14 bytes `submission_1.sh`
```
tr $2 $3<<<$1
```
Call with
```
$ ./submission_1.sh 'hello there!lgge lfewf lger3%#@ %@#T @EG' l r
herro there!rgge rfewf rger3%#@ %@#T @EG
```
## Alternate, Shell 9 bytes: `submission_2.sh` (May be too rule-bendy)
```
tr $1 $2
```
Call with
```
$ ./submission_2.sh l r <<<'hello there!lgge lfewf lger3%#@ %@#T @EG'
herro there!rgge rfewf rger3%#@ %@#T @EG
```
### Explanation
tr by default (without any flags) replaces all chars in the first set with the chars in the second set, completing the operation with the data on standard input.
I'm using this to my advantage by calling TR with the arguments in the correct order, and (in the alternate submission) taking advantage of the handling of standard input by Bourne Shell (sh) to pass standard input to tr without any additional code.
[Answer]
# Sed, 43 Chars
```
:;s/(.)(.*\1 (.))$/\3\2/I;t;s/(. .$|")//g
```
Invoked with the -r flag for extended regex.
[Answer]
# C++ 11, Stand-alone: 213 202 198 bytes
Since I haven't seen a solution on C++ yet, I decided to try something myself.
This is my first version and I will try to optimize it later.
Source code running:
Live Version: [213](https://ideone.com/clQm5s)
[202](https://ideone.com/8z59pA)
[198](https://ideone.com/Zq0oMw) bytes
```
#include <algorithm>
#include <iostream>
using namespace std;int main(){string a;getline(cin,a);char b,c;cin.get(b);cin.get(c);replace_if(begin(a),end(a),[b](char d){return!((d-b)%32);},c);cout<<a;}
```
.
## Only the replace function: 121 110 107 bytes
```
getline(cin,a);cin.get(b);cin.get(c);replace_if(begin(a),end(a),[b](char d){return!((d-b)%32);},c);cout<<a;
```
.
Feedback is welcome.
[Answer]
# Python, 58 bytes
Uses case-insensitive regex for substitution.
```
from re import*
lambda s,t,u:compile(escape(t),I).sub(u,s)
```
[Answer]
# Javascript ES6, 54 chars
```
f=s=>s.replace(/(.)(?=.* \1 (.)$)/ig,"$2").slice(1,-5)
```
[Answer]
# PHP, 44 Bytes
```
<?=str_ireplace($argv[2],$argv[3],$argv[1]);
```
Called from the command line via `php golf.php "Grant Bowtie: Only the best future bass artist ever" : -`
[Answer]
## Python 2.7, 117 bytes
```
def r(s): print ''.join([list(s)[-1] if x.lower() == list(s)[-3] else x if x != '\"' else '' for x in list(s)][:-4])
```
Python certainly won't compare to other golfing languages for this challenge, but nothing beats it for list (in)comprehensions.
If you want it to be a 'standalone' program it increases the size to about 120
```
import sys
if __name__ == "__main__":
l, y, z = sys.argv[1:]
print ''.join([z if x.lower() == y else x for x in l])
```
[Answer]
# Shell, ~~34~~ ~~27~~ 35 bytes
```
#!/bin/sh
echo $1|sed "s/$2/$3/gi"
```
[Answer]
# Lua, 36 bytes
```
a=arg[1]:gsub(arg[2],arg[3])print(a)
```
[Answer]
# Gema, 40 characters
```
"*" ? ?=@subst{\\C@quote{?}=@quote{?};*}
```
Sample run:
```
bash-4.3$ gema '"*" ? ?=@subst{\\C@quote{?}=@quote{?};*}' <<< '"Hello, World!" l r'
Herro, Worrd!
```
[Answer]
# O, 31 bytes
```
i`' /l3-{' \++}d`'"-"(?i)"@+@%p
```
[Answer]
# Perl, 33 chars (without !#) 48 (including !#)
```
#!/usr/bin/perl
($_,$b,$c)=@ARGV;
s/$b/$c/i;
print;
```
My first golf, one of my first perl programs. Probably could be golfed a little more
] |
[Question]
[
In [bash](/questions/tagged/bash "show questions tagged 'bash'"), this code posts `String to post` to `http://www.example.com/target`:
```
curl -d "String to post" "http://www.example.com/target"
```
**NOTE:** You should use **`http://www.example.com/target`** as the URL to `POST` to, without any change.
I think all other languages that I have knowledge in need a lot more code than this. I'm not blaming other languages. Let's see the interesting answers that reduce the effort.
Your task is to write the shortest code possible to send a **`POST`** request to a sample server, **`http://www.example.com/target`**, and the request data should be the string **`String to post`**.
[Answer]
# Bash: 90 characters
No external tools, just pure `bash`.
```
echo 'POST /target HTTP/1.0
Content-length:14
String to post'>/dev/tcp/www.example.com/80
```
[Answer]
# Rebol (51 chars)
```
write http://www.example.com/target"String to post"
```
Above works in Rebol 3. Below is a Rebol 2 version (63 chars):
```
read/custom http://www.example.com/target[post"String to post"]
```
[Answer]
# Powershell v3 - 58
```
iwr http://www.example.com/target -b "String to post"-me 3
```
[Answer]
# Javascript, 84
```
with(XMLHttpRequest())open('POST','//www.example.com/target'),send('String to post')
```
Try in the console of any page served over plain HTTP.
[Answer]
### newLISP - 58 characters
```
(post-url "http://www.example.com/target""String to post")
```
[Answer]
# Smalltalk (Smalltalk/X), 64 71
```
HTTPInterface post:'http://www.example.com/target'with:'String to post'
```
[Answer]
# Bash - 63 chars
```
wget --post-data="String to post" http://www.example.com/target
```
[Answer]
## PHP - 100 bytes
```
<?fwrite(fsockopen('www.example.com',80),'POST /target HTTP/1.0
Content-length:14
String to post');
```
I apologize for any similarities to [manatwork's bash solution](https://codegolf.stackexchange.com/a/21765), but I believe that this is the shortest way to do it.
[Answer]
## Lua (texlua), 73 bytes
```
require("socket.http").request("www.example.com/target","String to post")
```
[Answer]
# Tcl - 85 chars
```
package require http
http::geturl "//www.example.com/target" -query "String to post"
```
[Answer]
## Game Maker Language (GMStudio), 66
```
http_post_string("http://www.example.com/target","String to post")
```
[Answer]
# VBScript: 114 characters
```
dim x:set x=createobject("MSXML2.ServerXMLHTTP")
x.open"post","http://example.com/target"
x.send"String to post"
```
[Answer]
# Python 2: 80 chars
Just using the standard library:
```
import urllib2 as u
u.urlopen("http://www.example.com/target","String to post")
```
For an extra char, you can make the import less unusual.
```
import urllib2
urllib2.urlopen("http://www.example.com/target","String to post")
```
[Answer]
# jQuery, 58
`$.post("http://www.example.com/target", "String to post");`
[Answer]
# ùîºùïäùïÑùïöùïü, 47 chars / 51 bytes (noncompetitive)
```
ɟŏ`//www.example.com/target⍪String to post
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=false&input=&code=%C9%9F%C5%8F%60%2F%2Fwww.example.com%2Ftarget%E2%8D%AAString%20to%20post)`
Uses jQuery's `post` function.
[Answer]
## Actionscript 3, 201
```
var aRV:URLVariables = new URLVariables();
aRV.STRING = "my string";
var aR:URLRequest = new URLRequest("http://www.example.com/target");
aR.method = URLRequestMethod.POST;
aR.data = aRV;
var aL = new URLLoader();
aL.load(aR);
```
no error handling
[Answer]
# Batch/Powershell - 118 Chars
If you need to post from a Windows batch file or avoid changing ExecutionPolicy:
```
powershell -Command "(New-Object Net.WebClient).UploadString('http://www.example.com/target', 'p1=String%20to%20Post')"
```
[Answer]
# PHP, 198 bytes
This is shamefully large...:
```
<?fopen('http://www.example.com/target','rb',0,stream_context_create(array('http'=>array('method'=>'POST','header'=>'Content-Type: application/x-www-form-urlencoded','content'=>'String to post'))));
```
At least I answered!
[Answer]
# Bash, 69 bytes
```
lwp-request -m POST -b http://www.example.com/target "String to post"
```
You can read about the `lwp-request` command here: <http://linux.about.com/library/cmd/blcmdl1_POST.htm>
I think that the answer given by @manatwork is a much more neat and compatible version.
] |
[Question]
[
[(related)](https://codegolf.stackexchange.com/questions/18028/largest-number-printable)
Your challenge is to output the highest number you can. You can output as a number or as a string. You must output something that matches the regex `^\d+$`, as in only 0-9.
# The Twist
Your source code must be:
1. Same forwards and backwards
2. 3 bytes long
3. The middle byte must be different from the other two
Example valid:
```
0_0
)-)
m.m
xvx
W$W
@\@
```
Example invalid:
```
mnop
l__l
___
T_+
O_o
0_o
```
**Snippets are allowed**, you don't need a full program / function.
# Highest number outputted wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 103000
```
ȷ*ȷ
```
[Try it online!](https://tio.run/##y0rNyan8///Edq0T2///BwA "Jelly – Try It Online")
### How it works
`ȷ` denotes an scientific-notational number, as in `2ȷ6` for `2000000`. Without digits on either side, it defaults to a value of `1000`. `*` is exponentiation, giving 10001000.
[Answer]
# Polyglot (26 Langs), 9000000000
### Works With:
### APL, AWK, Arcyou, C#, CJam, Convex, Excel, Google Sheets, J, Japt, Java, JavaScript, MATL, MATLAB, Perl 5, Perl 6, PHP, PowerShell, Python, R, RProgN, TI-BASIC, VB, VB.NET, VBA, VBScript
This is a polyglot, if it works in your language add it to the list
```
9e9
```
or
```
9E9
```
or (Pretty much only for TI-BASIC)
```
9ᴇ9
```
[Try it Online.](https://tio.run/##K8ssLk3M0U1KLM5M1s1LLdHNzc/L///fNz@lNCdVwZEruDRJwTcxM48ruLK4JDVXzzk/rzg/J1UvvCizJFXDMtVSk8s1L0UBqAxMQ/T9/w8A) (VB.Net)
*(dependant on language)*
* Added APL and J thanks to @Adám
* Added Python thanks to @VoteToReopen
* Added Japt thanks to @Shaggy
* Added Perl 5/6 thanks to @bradgilbertb2gills
* Added PowerShell thanks to @tessellatingheckler
* Added C# thanks to @TheLethalCoder
* Added Visual Basic Family
* Added R thanks to @JarkoDubbeldam
* Added AWK, Arcyou, CJam, Convex, MATL, MATLAB, PHP, RProgN, TI-Basic
* Added Java thanks to @KevinCruijssen
* Added Excel and Google Sheets
>
> Note: With formatting, supported by: Clojure, Common Lisp, Crystal, D, Go, Haskell, Java, Julia, Kotlin, Lua, Maxima, NIM, Racket, Rexx, Ruby, Rust, Scala
>
>
>
[Answer]
# Brainfuck, 255
```
-+-
```
Assuming 8-bit bounded cells.
---
Per [this meta consensus](https://codegolf.meta.stackexchange.com/questions/2447/), `the contents of the tape post-execution may be used as a Turing machine's output`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 1.001001001001001e+299 = 100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100
Found a bigger one thanks to ETHproductions informing me that strings were permitted.
```
LçL
```
[Try it](http://ethproductions.github.io/japt/?v=1.4.5&code=TOdM&input=)
---
## Explanation
* `L` is the Japt constant for the number `100`.
* The `ç` method, which takes string `s` as an argument, when applied to a number `n`, repeats `s` `n` times. If a number is passed as the argument, it's cast to a string.
* So, reading `LçL` backwards, it's "100 repeated 100 times".
---
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 100! (93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000)
```
!т!
```
[Try it online!](https://tio.run/##MzBNTDJM/f9f8WKT4v//AA "05AB1E – Try It Online")
`т` is the constant 100 and the first `!` is just ignored.
[Answer]
# Mathematica, 387420489
this one
```
9^9
```
# Mathematica, 3265920
```
9!9
```
[Answer]
# Vim, 999999999
```
9i9
```
Since *snippets are allowed*, this works in vim as well as V, so you'll have to hit escape after this.
[Try it online!](https://tio.run/##K/v/3zLT8v9/AA "V – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), `10e100`
```
°т°
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0IaLTYc2/P8PAA "05AB1E – Try It Online")
*also it looks more like a uterus than a face...*
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 10
```
?z?
```
The challenge specifically asks to "output" the number, and the only way to do that in QBIC is using `?`. So this prints `z` (which is 10 in QBIC) followed by 2 newlines.
A slightly more relaxed take on the rules would give us this snippet:
```
z^z
```
which is good for 10,000,000,000. It doesn't output anything (in fact, it doesn't even assign the result), but as a 3-byte `ABA` snippet it reaches the highest number possible.
[Answer]
# Japt, 2550
```
#ÿ#
```
3 bytes in extended ASCII, where `ÿ` has code 255. `#` gets it's code and returns it, while the second `#` returns simply 0, because nothing follows it.
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=I/8j)
# Japt, 91
Really bad score. That's just an experiment
```
;I;
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=O0k7)
```
;I;
; Alternative variables mode
I Constant for 91
; Command separator - does nothing
```
# Japt, ~`1e+102` (cheating?)
Probably not valid answer, because Japt is transpiled to JS which automatically converts numbers to scientific notation.
```
LeL
```
It's basically 100^100.
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=SWVJ&input=)
[Answer]
# [Braingolf](https://github.com/gunnerwolf/braingolf), 126
```
#~#
```
[Try it online!](https://tio.run/##SypKzMxLz89J@/9fuU75/38A "Braingolf – Try It Online")
Yep, that's as high as Braingolf can go under these restrictions.
## Explanation:
```
#~ Pushes codepoint of ~ (126)
# Does nothing
Implicit output of last item on stack
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 39916800
```
ḟjḟ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO@VlA/P///ygA "Brachylog – Try It Online")
### Explanation
```
ḟ Factorial: the Input is a free variable, so it considers that its input is 0
j Juxtapose: 11
ḟ Factorial: 39916800
```
[Answer]
# [Psi](https://psi.vazkii.us/index.php), 99980001
[](https://i.stack.imgur.com/wkP3x.png)
Not super inventive. And it's probably cheating.
I'd love to use Operator: Power instead, but the "base" and "power" arrows are different colors, making it not symmetrical.
[Answer]
# [Aceto](https://github.com/aceto/aceto), 387420489
Since snippets are allowed,
```
9F9
```
*may* push 9^9 on the stack, depending on where in the code it is. An example of it working would be:
```
9F9
p
```
(the `p` merely prints, you could replace it with a nop and it would still work)
[Answer]
# [Yabasic](http://www.yabasic.de), 2^1024
I have no idea why, but it works. See the TIO link
```
0/0
```
[Try it online!](https://tio.run/##dY87T8QwEIT7@xWjk5BAQofD8TiQ0FVXUAASHAXlJnGSlZJ15Acn//pgm4IKF6v1erwzX6SaHDfLQk/qSi17ED4dS4/12VbtNqpbY7V6P7zg9e14eCxdKcdBIxRhY6aJpAU7GBljmuoW3kCLC1bDD@RT0eiMnVJrumTx/JH3YTItd5zkp0ELZsvidXtZ9pPD1280nHgck4t8a@tBEiFhqrXFyF5bGjEa6dM1GQkqhXPHvaS1DYm/QMs9e5fzuIa1@PxQDMR48mxk88cUTcBEEU7n2ImnjpluJps5M4MJfg6FoXzIZ19db29u7@53D6rMklNB/kdTleHyAw "Yabasic – Try It Online")
*Note: the `Print` command converts any number with a length greater than 10 digits to scientific notation, so a `Using` command is used to print the value without converting it to scientific notation*
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 9000000000
An anonymous and rather boring function that takes no input and outputs 9000000000
```
9e9
```
which scores 9000000000
[Try it Online](https://tio.run/##y00syfn/3zLV8v9/AA)
### Far more Interesting, but cheaty approach
Takes input and implicitly converts it to a numeric value which it divides by 0, which, for *almost* any input returns `Inf` (Infinity) *which does not fit the regex requirement*
```
0/0
```
[Try It Online](https://tio.run/##y00syfn/30Df4P9/9ZB8hcy8tMy8zJJKhcS8FIWk1Mr8vBRFdQA)
***I tested 47 languages over 3 hours to find this***
] |
[Question]
[
It seems flags are a trend now, so what better place to start an account? I thought bars could use a twist to them, so I found this flag.
Produce the following in the console output the fewest possible bytes:
```
+----------------------------------+
|XXXXX |
|XXXXXXXX |
|XXXXXXXXX-------------------------+
|XXXXXXXXXXX |
|XXXXXXXXXXX |
|XXXXXXXXX-------------------------+
|XXXXXXXX |
|XXXXX |
+----------------------------------+
```
This crude rendition of the flag is 36 x 10 characters. A trailing newline on the last line is optional. You may use any language you choose. If it is an obscure language, please post a link to the language in your answer.
[Answer]
# SQL (PostgreSQL flavour), ~~284~~ ~~244~~ ~~232~~ ~~210~~ 175 bytes
A HUGE Thank You to @manatwork for essentially the whole thing now.
A nice verbose language that still came in under the byte size of the flag, with a bit of a margin :)
Basically builds the half of the flag with using parameters. This is cross joined with 1 and -1 giving us both halfs of the flag and a means to order it by negating the number of #'s in the row.
```
SELECT rpad(rpad(L,X,'X'),35,P)||R FROM(VALUES('|',12,' ','|'),('|',10,'-','+'),('|',9,' ','|'),('|',6,' ','|'),('+',1,'-','+'))F(L,X,P,R),(values(-1),(1))G(O)ORDER BY(12-X)*O
```
Formatted and commented
```
SELECT rpad(rpad(L,X,'X'),35,P)||R --Build each row from parameters
FROM(VALUES -- Parameters for each row
('|',12,' ','|'), -- Start Char, Num of #, Pad Char, End Char
('|',10,'-','+'),
('|',9,' ','|'),
('|',6,' ','|'),
('+',1,'-','+')
)F(L,X,P,R),
(values(-1),(1))G(O) -- Cross join with order modifier
ORDER BY(12-X)*O -- Order by modified number of #
```
[Answer]
# CJam, 44 bytes
```
8T5@9B]_W%+{I'|'+?'XI*34"- "I=e]"+||"I=N}fI
```
*(Thanks to @Dennis, @Jakube and @Optimizer for -1 byte each)*
```
8T5@9B] Push [0 5 8 9 11]
_W%+ Add its reverse, to give [0 5 8 9 11 11 9 8 5 0]
{...}fI For each I in the above array...
I'|'+? Push "+" if I == 0 else "|"
'XI* Push I "X"s
34"- "I=e] Pad the "X"s to length 34 with "-" if I%3 == 0 else " "
"+||"I= Push "+" if I%3 == 0 else "|"
N Push a newline
```
[Answer]
## Python 2, 80
```
for n in 0,5,8,9,11,11,9,8,5,0:print'|+'[n<1]+'X'*n+'- '[n%3]*(34-n)+'+||'[n%3]
```
Instead of iterating over the row numbers, iterate over the number of `X`-symbols directly. The stripes happen where `n` is `0` or `9`, which are the only multiples of 3, and so can be checked by the value `n%3` (thanks Sp3000).
This can surely be shortened in Python 3 by converting the list of numbers to a bytes object.
[Answer]
# CJam, ~~52~~ ~~51~~ 50 bytes
```
8U5@9B]34X$f-]z87Zb"X ||X-++X-+|"4/f=..*1fm>_W%+N*
```
*Thanks to @Sp3000 for golfing off 1 byte!*
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=8U5%409B%5D34X%24f-%5Dz87Zb%22X%20%7C%7CX-%2B%2BX-%2B%7C%224%2Ff%3D..*1fm%3E_W%25%2BN*).
### How it works
```
8U5@9B] e# Push [0 5 8 9 11] (`@` rotates on top).
34X$f- e# Subtract each integer from 34.
]z e# Wrap and zip. This pushes [[0 34] [5 29] [8 26] [9 25] [11 23]].
87Zb e# Push [1 0 0 2 0] (87 in base 3).
"X ||X-++X-+|"4/
e# Push ["X ||" "X-++" "X-+|"].
f= e# Select for each. This pushes ["X-++" "X ||" "X ||" "X-+|" "X ||"].
..* e# Twofold vectorized repetition.
e# EXAMPLE: [9 25]"X-+|".* -> "XXXXXXXXX-------------------------+|"
1fm> e# Rotate each string one character to the right.
_W% e# Copy the resulting array and reverse the order of its lines.
+N* e# Concatenate and join by linefeeds.
```
[Answer]
## JavaScript (ES6), ~~147~~ ~~132~~ ~~127~~ ~~111~~ 106 bytes
```
[0,5,8,9,11,11,9,8,5,0].map(v=>console.log('|+'[+!v]+'X'.repeat(v)+' -'[z=+!(v%3)].repeat(36-v)+'|+'[z]))
```
### Demo
As it is ES6, it only works in Firefox at the moment.
```
// DEMO: redefine console.log to have output inside the snippet
// Taken from https://codegolf.stackexchange.com/a/52411/22867
console.log = (...x) => O.innerHTML += x + '\n';
// Actual program
[0,5,8,9,11,11,9,8,5,0].map(v=>console.log('|+'[+!v]+'X'.repeat(v)+' -'[z=+!(v%3)].repeat(36-v)+'|+'[z]))
```
```
<pre><output id=O></output></pre>
```
[Answer]
## C, 157 155 151 146 bytes
```
i;f(){for(char b[36];i<10;printf("%c%.34s%c\n",i++%9?124:43,b,i%3?124:43))memset(b,i%3?32:45,34),i%9?memset(b,120,35253>>((i<5?5-i:i)%4*4)&15):0;}
```
edit: I moved the string length inside of the format string and found two bytes.
edit: Added Cool Guy's recommendation and found four bytes.
edit: Removed the array and replaced it with a 4-bit packed short that's shifted to get the 'x' lengths
[Answer]
# CJam, ~~60~~ ~~54~~ ~~50~~ ~~48~~ 45 bytes
Compared to the previous version, I realized that one of the 5 entries in my descriptors was always the same, which was kind of pointless. Using a fixed value for it:
```
"++-0|| 5|| 8|+-9|| B"4/_W%+{1/~~'X*34@e]\N}/
```
[Try it online](http://cjam.aditsu.net/#code=%22%2B%2B-0%7C%7C%205%7C%7C%208%7C%2B-9%7C%7C%20B%224%2F_W%25%2B%7B1%2F~~'X*34%40e%5D%5CN%7D%2F)
*Thanks to @aditsu and @Sp3000 for some related help in chat this morning.*
The basic approach here is that I have 4 character descriptors for the pattern of each line, where the characters in the descriptor are:
* First character.
* Last character.
* Right fill character.
* Repeat count for left fill character.
The left fill character, which was part of the descriptor in earlier versions of this solution, is always `X`, so it is now not part of the descriptor anymore.
These descriptors are specified for the top 5 lines, and repeated for the bottom 5 lines in reverse order.
Explanation:
```
"++-0|| 5|| 8|+-9|| B"
Descriptors for top 5 lines, as described above.
4/ Split into 5 descriptors of 4 characters each.
_W% Repeat the 5 descriptors in reverse order.
{ Loop over lines/descriptors.
1/ Split descriptor string into array with 5 one-character strings.
~ Unwrap the array.
~ Evaluate last entry in descriptor, which is the count.
'X Left fill character.
* Repeat left fill character by given count.
34@e] Pad to 34 characters using right fill character.
\ Swap last character to top.
N Add a newline.
}/ End loop over lines/descriptors.
```
[Answer]
## Python 3, 282 bytes/characters
```
f,l,h=lambda a:a in{0,35}and '+'or'-',lambda a:a%3 and'|'or'+',lambda a:a and(a<10 and 'X'or'-')or'|';print("\n".join("".join(x)for x in[[k in{0,9}and f(j)or j==35 and l(k)or k%3 and(j==0 and'|'or j<[0,6,9,0,12,12,0,9,6][k]and'X'or' ')or h(j)for j in range(36)]for k in range(10)]))
```
Output is, of course:
```
+----------------------------------+
|XXXXX |
|XXXXXXXX |
|XXXXXXXXX-------------------------+
|XXXXXXXXXXX |
|XXXXXXXXXXX |
|XXXXXXXXX-------------------------+
|XXXXXXXX |
|XXXXX |
+----------------------------------+
```
I'm sure there's a much shorter way to do this in Python.
[Answer]
# Ruby, 78
```
"@EHIKKIHE@".each_byte{|i|puts"+|"[i/65]+?X*(i-64)+" -"[i%3]*(98-i)+"|+"[i%3]}
```
A copy of Rinkattendant's / Xnor's idea of iterating over the lengths of the strings of X's. Except instead of using an array, I have compressed them into a string.
# Ruby, 96
Original plain vanilla approach
```
(0..9).each{|i|puts (i%9<1??+:?|)+(?X*("@EHIKKIHE@"[i].ord-64)).ljust(34,"- "[i%3])+"+||"[i%3]}
```
**Ungolfed**
```
(0..9).each{|i|
puts (i%9<1??+:?|) #first character + or |
+(?X*("@EHIKKIHE@"[i].ord-64)).ljust(34,"- "[i%3]) #print quantity of X's according to string, then right justify with - or space
+"+||"[i%3]} #last character + or |
```
[Answer]
## Ruby, ~~156~~ 155 chars
```
h=[5,8,9,11];l=34;t=?++(?-*l)+?+;puts t;2.times{h.each{|c|if c==9 then j='-+' else j=' |';end;print(?|,((?X*c).ljust(l,j[0])),j[1],?\n)};h.reverse!};puts t
```
I used an array, `h`, with the values `[5, 8, 9, 11]`, so I can use `2.times { h.each { code }; h.reverse }` because the flag is symmetrical horizontally. I also use 34 many times in the code, so it is assigned to `l`. `?x` is shorthand for `"x"`.
[Answer]
## Swift 1.2, 157 bytes
Can be run in a playground, or from a file using `swift file.swift` in Terminal.
```
let z="-----",x="XXX",y=" ",g=y+y,w=z+z+z+z+"----+",e=g+g+g+y+" |",c="|XX"+x,d=["+"+z+z+w,c+g+e,c+x+y+e,c+x+"X-"+w,c+x+x+e]
print("\n".join(d+reverse(d)))
```
[Answer]
# PHP, 135 bytes
Lets play around with `printf`:
```
<?$A='|%-34s|
|%-34s|';$B="|%'--34s|";printf("+%'-34s+
$A
$B
$A
$B
$A
+%'-34s+",'',$a=XXXXX,$b=$a.XXX,$c=$b.X,$d=$b.XX,$d,$c,$b,$a,'');
```
Maybe there are some edges that I've left behind that can be cut.
But it was fun!
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 41 bytes
```
»'ꜝ»12τƛ\X*34↲n9=[ð\-V\+|\|]+\|p;\+17-mpm
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%C2%BB%27%EA%9C%9D%C2%BB12%CF%84%C6%9B%5CX*34%E2%86%B2n9%3D%5B%C3%B0%5C-V%5C%2B%7C%5C%7C%5D%2B%5C%7Cp%3B%5C%2B17-mpm&inputs=&header=&footer=)
```
12τ # Base-12 digits of...
»'ꜝ» # 9119 (so 5,8,9,11)
ƛ ; # Mapped to...
\X* # That many Xs
34↲ # Padded to width of 34
n9=[ ] # If it's a 9...
ð\-V\+ # Replace all spaces with -s and append a +
|\| # Else append a |
+\|p # Prepend a |
\+ # '+'
17- # Append 17 -s
m # Mirror the result
p # Prepend that to the rest
m # Mirror the lot.
```
[Answer]
## Sed - 228
```
s/.*/eeeeee\neeeeee/
s/e/------/g
s/^-/+/
s/-$/+/
s/-\n-/+\n+/
s/\n/\nabcddcba/
s/\([a-d]\)/|XXXXX\1\1\1\1\1\1\n/g
s/\([a-d]\)/\1\1\1\1\1/g
s/Xbbb/XXXX/g
s/Xcccc/XXXXX/g
s/Xdddddd/XXXXXXX/g
y/abcd/ - /
s/ \n/|\n/g
s/-\n/+\n/g
q
```
Because of the way sed works, this requires a line of input to output the flag.
[Answer]
## Haskell, 233 bytes
```
putStr$uncurry((.toEnum).replicate)=<<foldl1(++)(((++)=<<reverse)$zipWith zip[[1,11,23,1,1],[1,9,25,1,1],[1,8,26,1,1],[1,5,29,1,1],[1,34,1,1]][[124,88,32,124,10],[124,88,45,43,10],[124,88,32,124,10],[124,88,32,124,10],[43,45,43,10]])
```
[Answer]
# [Deadfish~](https://github.com/TryItOnline/deadfish-), 558 bytes
```
{iiii}iiicii{ccc}ccccddc{ddd}c{{i}i}ic{ddd}ddddddccccc{dddddd}iiii{cc}ccccccccc{{i}d}iicd{{d}d}c{{i}i}ic{ddd}ddddddcccccccc{dddddd}iiii{cc}cccccc{{i}d}iicd{{d}d}c{{i}i}ic{ddd}ddddddccccccccc{dddd}ddd{cc}ccccc{{i}dd}dcd{{d}d}c{{i}i}ic{ddd}dddddd{c}c{dddddd}iiii{cc}ccc{{i}d}iicd{{d}d}c{{i}i}ic{ddd}dddddd{c}c{dddddd}iiii{cc}ccc{{i}d}iicd{{d}d}c{{i}i}ic{ddd}ddddddccccccccc{dddd}ddd{cc}ccccc{{i}dd}dcd{{d}d}c{{i}i}ic{ddd}ddddddcccccccc{dddddd}iiii{cc}cccccc{{i}d}iicd{{d}d}c{{i}i}ic{ddd}ddddddccccc{dddddd}iiii{cc}ccccccccc{{i}d}iicd{{d}d}c{iii}cii{ccc}ccccddc
```
[Try it online!](https://tio.run/##rZJBDoAwCARf5KMMq5Gzxw1vR2iNB2ONTSXhwNJZmhYsM1bdt8mdGmGRokoRsUgBhABMyOiZ1golsl/qlBLmCdVGACkLyCDaDk2THodqkeLFFzykN5xx9mH4l8kD6OClf3q1jp/LxbhthfsB "Deadfish~ – Try It Online")
] |
[Question]
[
*CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?*
```
6779686932717976703238326711110010511010332671049710810810111010310111558327311032116111100971213911532991049710810810111010310144321211111173910810832981013297115107101100321161113211211410511011632116104101321021111081081111191051101033211810111412132115112101991059710832657868321161141059910712132657868321159711610511510212110511010332801141051091013278117109981011144646463332651141013212111111732103111108102101114115321141019710012163
```
**Your task is to output this 442-digit Prime Number**
**Rules**
Your code must not contain any odd decimal digits. So numbers 1,3,5,7,9 (ASCII 49,51,53,55,57) are forbidden.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The shortest code in bytes wins.
So... what is so special about this prime number anyway?
You may find this out yourselves. If you don't, I'll tell you next week!
**EDIT**
Since this challenge is going to close, I will give a hint to my friend @xnor:
The challenge IS the number (this is why it is called "Prime Challenge")
[Answer]
# [R](https://www.r-project.org/), 195 bytes
(SPOILER IF YOU WANT TO FIGURE IT OUT YOURSELF)
>
>
> ```
> cat(utf8ToInt("CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?"),sep="")
> ```
>
>
>
>
[Try it online!](https://tio.run/##NY3BCoJAFEV/5eYiFcR1BBGiFUFki35g1KcOjjPyZizm6y2DdofL4R5ellq4aHbt7mmu2kVBXhYnXMrbGVvkppG6Q94LpUh3ZPe4ajjTCB9a1P85gTdzqBQqgrADNV8FE0vt4HpCa5Qy7/XoRexhJ6qlUMjuBRzLevA/tMJJ2/pVe7AcCfd5rIjTNN0gY1oT6IxqiS2YROOPQZxYmg5BEC/LBw "R – Try It Online")
Not the golfiest language to use for [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'"), but it does the trick.
[Answer]
# x86-16 machine code, IBM PC DOS, 206 bytes
Binary:
>
>
> ```
>
> 00000000: be24 01b1 aaac d40a 5086 e0d4 0a05 3030 .$......P.....00
> 00000010: 86e0 3c30 7402 cd29 86e0 cd29 5804 30cd ..<0t..)...)X.0.
> 00000020: 29e2 e2c3 434f 4445 2047 4f4c 4620 2620 )...CODE GOLF &
> 00000030: 436f 6469 6e67 2043 6861 6c6c 656e 6765 Coding Challenge
> 00000040: 733a 2049 6e20 746f 6461 7927 7320 6368 s: In today's ch
> 00000050: 616c 6c65 6e67 652c 2079 6f75 276c 6c20 allenge, you'll
> 00000060: 6265 2061 736b 6564 2074 6f20 7072 696e be asked to prin
> 00000070: 7420 7468 6520 666f 6c6c 6f77 696e 6720 t the following
> 00000080: 7665 7279 2073 7065 6369 616c 2041 4e44 very special AND
> 00000090: 2074 7269 636b 7920 414e 4420 7361 7469 tricky AND sati
> 000000a0: 7366 7969 6e67 2050 7269 6d65 204e 756d sfying Prime Num
> 000000b0: 6265 722e 2e2e 2120 4172 6520 796f 7520 ber...! Are you
> 000000c0: 676f 6c66 6572 7320 7265 6164 793f golfers ready?
>
> ```
>
>
>
>
Listing:
>
>
> ```
>
> BE 0124 MOV SI, OFFSET TXT ; string offset
> B1 AA MOV CL, 170 ; string length
> CHAR_LOOP:
> AC LODSB ; AL = next char
> D4 0A AAM ; AL = AL % 10, AH = AL / 10
> 50 PUSH AX ; save units digits
> 86 E0 XCHG AH, AL ; swap digits
> D4 0A AAM ; AL = AL % 10, AH = AL / 10
> 05 3030 ADD AX, '00' ; ASCII convert
> 86 E0 XCHG AH, AL ; swap digits
> 3C 30 CMP AL, '0' ; is highest digit a '0'?
> 74 02 JZ TWODIG ; if so, don't display leading zero
> CD 29 INT 29H ; display hundreds digit
> TWODIG:
> 86 E0 XCHG AH, AL ; swap digits
> CD 29 INT 29H ; display tens digit
> 58 POP AX ; restore units digit
> 04 30 ADD AL, '0' ; ASCII convert
> CD 29 INT 29H ; display units digit
> E2 E2 LOOP CHAR_LOOP ; loop until end of string
> C3 RET ; return to DOS
> TXT:
> DB 'CODE GOLF & Coding Challenges: In today',27H,'s challenge, '
> DB 'you',27H,'ll be asked to print the following very special '
> DB 'AND tricky AND satisfying Prime Number...! Are you golfers ready?'
>
> ```
>
>
>
>
[](https://i.stack.imgur.com/PMWGJ.png)
[Answer]
# [Io](http://iolanguage.org/), 186 bytes
>
>
> ```
>
> "CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?"foreach(print)
>
> ```
>
> [Try it online!](https://tio.run/##NY3RCoIwGEZf5auLLAgfoJsQrQhCe4W5/dPh3GSbxZ5@qdDd4ePwHWVT2pdNdcOjed1xQGmFMh3KnmlNpiN/wdMgWMFi5sH/8xnRzpnWaAnMDyQWBZNTJiD0BGm1tt/16EMuwk/EFdMo6grBKT7EDT0Lysu4am@nRkI9jy25PM93KBytCXRWS3IejpiI1720C/D@uKVOKf0A "Io – Try It Online")
>
>
>
## Explanation
>
> Io's default syntax for defining strings actually defines a "sequence", that is basically a list of ord codes.
>
>
>
>
> During foreach, Io treats every character of the sequence as it's respective ord code (don't believe it? try [`"abc"at(0)`](https://tio.run/##y8z//18pMSlZSSGxRMNAU6GgKDOvJCfv/38A))
>
>
>
>
>
> ```
>
> "..." // The big string, from other answers
> foreach( ) // For every codepoint in this string:
> print // output this codepoint without a newline
>
> ```
>
>
>
>
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 93 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
”›ˆ‚³...!€™”‘€ƒ‘D”Âïªï:€†”‘ƒËŠˆ‘“ÿ & ÿƒÜ's›Ý,€î'll€ï‹Ð€„…¢€€„—‚ÒƒÑ ÿÐËy ÿËØing ÿ€îŠˆersŽä?“ÇJ
```
[Try it online.](https://tio.run/##yy9OTMpM/f//UcPcRw27Trc9aph1aLOenp7io6Y1j1oWgYVnANnHJgFpFyD3cNPh9YdWHV5vBVLQsACi4Nikw91HF4B0z3jUMOfwfgU1hcP7gYJz1IuBph6eqwNUfHidek4OiF7/qGHn4Qlg7fMeNSw7tAjEhPKmAO0/PAmocyLQgMMTDndXgujuwzMy89KBLLAxIItSi4qP7j28xB5kW7vX//8A)
**Explanation:**
>
>
> ```
> ”›ˆ‚³...!€™” # Push (titlecased) dictionary string "Prime Number...! Are"
> ‘€ƒ‘D # Push (uppercased) dictionary string "AND" and duplicate it
> ”Âïªï:€†” # Push (titlecased) dictionary string "Coding Challenges: In"
> ‘ƒËŠˆ‘ # Push (uppercased) dictionary string "CODE GOLF"
> “ÿ & ÿƒÜ's›Ý,€î'll€ï‹Ð€„…¢€€„—‚ÒƒÑ ÿÐËy ÿËØing ÿ€îŠˆersŽä?“
> # Push (regular) dictionary string "ÿ & ÿ today's challenge, you'll be asked to print the following very special ÿ tricky ÿ satisfying ÿ you golfers ready?",
> # where the `ÿ` are automatically filled with the strings on the stack
> Ç # Convert each character to its codepoint integer
> J # And join all those together
> # (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 `"Prime Number...! Are"`; `‘€ƒ‘` is `"AND"`; `”Âïªï:€†”` is `"Coding Challenges: In"`; `‘ƒËŠˆ‘` is `"CODE GOLF"`; and `“ÿ & ÿƒÜ's›Ý,€î'll€ï‹Ð€„…¢€€„—‚ÒƒÑ ÿÐËy ÿËØing ÿ€îŠˆersŽä?“` is `"ÿ & ÿ today's challenge, you'll be asked to print the following very special ÿ tricky ÿ satisfying ÿ you golfers ready?"`.
>
>
>
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 133 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
As will be the case with every solution to this, all credit here belongs to [Giuseppe](https://codegolf.stackexchange.com/a/209807/58974)!
```
`CODE GOLF & CoÜA Câ%s: In Üþs å¡e, y'¥ ¼ k pÎC e èÄg vy special AND Éky AND Ñsfyg PÎX Num¼r...! A y goÓÈs Î%y?`mc
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=YENPREUgR09MRiAmIENv3EEgQ%2bKKCCVzOiBJbiCR3P5zIOWQoQVlLCB5jCelILwghmuCIJEgcM5DIJBlIOiEjcRnIHaAeSBzcGVjaWFsIEFORCDJjmt5IEFORCDRi3NmeYhnIFDOWCBOdW28ci4uLiEgQZwgeYwgZ2/TyHMgziV5P2BtYw&input=IkNPREUgR09MRiAmIENvZGluZyBDaGFsbGVuZ2VzOiBJbiB0b2RheSdzIGNoYWxsZW5nZSwgeW91J2xsIGJlIGFza2VkIHRvIHByaW50IHRoZSBmb2xsb3dpbmcgdmVyeSBzcGVjaWFsIEFORCB0cmlja3kgQU5EIHNhdGlzZnlpbmcgUHJpbWUgTnVtYmVyLi4uISBBcmUgeW91IGdvbGZlcnMgcmVhZHk/Ii5tKCJjIik)
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), ~~177~~ 141 bytes
```
`CODE GOLF & Coding Challenges: In nL;'s r⊂;, you'll be 0⑵; to a⑱; the 1⟱; 0K; 4∀; AND ⬨⑺; AND Q&; Prime Number...! Are you :G;ers 1⑾;?`÷^(ⁿ.
```
[Try it online!](https://tio.run/##y05N//8/wdnfxVXB3d/HTUFNwTk/JTMvXcE5IzEnJzUvPbXYSsEzTyHPx1q9WKHoUVeTtY5CZX6pek6OQlKqgsGjiVutFUryFRIfTdwIZGSkKhg@mg9kGXhbK5g86miwVnD0c1F4tGbFo4m7IOxANWuFgKLM3FQFv9LcpNQiPT09RQXHolSQqQpW7tapRcVAMybus7ZPOLw9TuNR4369////6ybnAgA "Keg – Try It Online")
Yeah, it the same technique as everyone else. Now with string compression.
[Answer]
# [Python 2](https://docs.python.org/2/), 202 bytes
```
print''.join(`ord(x)`for x in"CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?")
```
Spoiler tag misinterprets the backticks and anyway, it's probably not necessary any more.
[Try it online!](https://tio.run/##NY3LCsIwEEV/5dqFrSBduHQj0qoIon5CYzNtozFTJvGRr69WcHe5HM7pY@jYLYahF@NCmuZXNi6rWHT2nlUNC94wLilO5Qa702GLKQrWxrUoOmUtuZb8EnuHwFrF1KP@33NEfqTW4kJQ/kb6i@BXQegIDVvLr1H0JInwPdVGWayPJYKY@hZ/06tgfBNH7CzmTjg@7heSPM8nWAuNCbRsGxIPIaXjKpkNwwc "Python 2 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~118~~ 175 bytes
```
jkCM"CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?
```
[Try it online!](https://tio.run/##dVDBTsMwDP0Vw4Fd0BQnTdJwQVMHCAkGv9Ct2VaWtVPbgfr1xU4L7IIb1Zb97PfsU9/th@HjkL1eZ2/LB3h6e3mEG8jqoqx2kO3zEHy18@0dPFfQ1UXez1rY/KRvoa/PsxBg7SFvD74gCJyasuqg23vY1iHUXzzo0zc9tCe/KfMAi9USuqbcHPoYtnlXttueYe9NefSwOh/XvpnP51ewaDxTwK4OW9@00Pi86O@HwVjrTGqckhats8YKJVWqpLFIJgQKTQ6FiimROPql8eGYj4HW1GIVZZRENGMrQSUqR1UlnfunN0moQ2I0S@AIIDyDyJEKjcJyh/idzZ5eMmlDMxZEEntQxHEjE5u72AFxZE9YmuThFAhkeTrKozW1TU06cTEHF@MqFyUGM6WO@uIGfySpmMQJFxVZ0kGznZu4E8Of4pPqiMTLG0g@zLSAnMTyCUckixQENuob "Pyth – Try It Online")
Due to a rushed answer, my original source didn't give the correct number. I was only checking the first and last numbers and assumed the rest was correct.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~202~~ 196 bytes
Saved 6 bytes thanks to [Manish Kundu](https://codegolf.stackexchange.com/users/77516/manish-kundu)!!!
>
>
> ```
> print(*map(ord,"CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?"),sep='')
> ```
>
>
>
>
[Try it online!](https://tio.run/##NY3LCsIwFAV/5diFtVK6cSeIlPpAEPUX0ua2DU2TcBOVfH21grvDMMxxMfTWbKbJsTJhtR6FW1mWeVLdD0ec79cTlqisVKZD1QutyXTkt7gYBCtFTD2aP84R7TPVGjVB@IHkV8Gvi9ATWqu1fc@hF3GEd9QooVHeDgismiH@phdB@TbO2oPVSLg9x5q4KIoFSqb5Ap3VLbEHk5Bxn2S5J7dL02yaPg "Python 3 – Try It Online")
Port of [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)'s [R answer](https://codegolf.stackexchange.com/a/209807/9481).
[Answer]
# [Deadfish~](https://github.com/TryItOnline/deadfish-), 1442 bytes
```
{{i}ddddd}iiiicicciicdddciicddciiicddddddcdciiiiicddddddciiiiiiciicddcdcic{d}iiiciiicdciciiiiicdddddcdciiiicicddddddccccdccicdciiiiicddddccdcicdciiiccdciiiicicddddddcdciiiiciiiiicddcddddddcdc{i}ddc{d}iiicdc{i}ddc{d}iiicdcicccdcicdciiicddcdciccciiiicciiicdddddcdciiiiicddddcddccdciiicdcdcciiiiicdddddccccdcc{i}dcddcddddddcicdciiciiiiiic{d}iicciiiicddcdc{i}dddcc{d}iicdciiiiciiiiicddcddddddcdc{i}ddc{d}iiicdc{i}ddc{d}iiicdcicccdcicdciiicddcdciciiiccdcdcdcicdcccccciiiiiicddddciiiiiic{d}iicdc{i}ddc{d}iiicdc{i}ddcdddddcdc{i}dddcdc{d}iiicdciciicdc{i}dddcddcddddddcciiiicddddcdc{i}dddcddddddcdciccdcciiicdcdcciiiiicdddddccciicdcdccicdcciiicdddcdciiiiicddddccdcicciiiiicdddcdcdcciiiiicdddddcdciiiicdddcdciciicdcdcdciicdccccdc{i}ddc{d}iiicdc{i}ddc{d}iiiccccc{i}ddc{d}iicdciiiiicddddccdcicdciiiccdcdcc{i}dddc{d}iiicdciccciiicdddcicdciicdcdcciiiicddddccicdcdcic{i}ddcc{d}iicdciiiiiciiiicddcddddddcdc{i}ddcdddddcdciiiicdciicicddciicdddddcdcdcciiiiicdddddcciiicdddcdciiiiiciiiicc{d}iicdc{i}dddcddddddcicdciicdciiiicdciicicddciicdddddcdcdcciiiiciiiicddcddddddcciiiiicdddddcdciiiiicddddcciiiicddddcdciicdcicdccdciiiiicddddccdcicdciiiccdciiiiiic{d}iicicciiicdddcdciiiiicddddcdc{i}dc{d}iicdciciicdciiiiicic{d}iiicciiiiiicddddddcdc{i}dccdc{d}iiicdciccciiicciicddciicddciicdddcccdciiiicdcddddcciiicdddcdciciicdcdcicdcccccciiiiiicddddcdcdcdciiicddccccdc{i}ddc{d}iiicdciicdcdciccciiicdddcciiiicddcdcdcciiicdddcdcic{i}ddcddcddddddcdccicicdciiiiicdddc{d}{d}i{c}cc
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~213~~ ~~211~~ ~~210~~ 211 bytes
```
f(){for(char*s="CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?";*s;)printf("%d",*s++);}
```
[Try it online!](https://tio.run/##NY/RSsNAFESfzVeMAW2S1nyAQaSkKoK0/sJ2926ydJMt926VpfTbY1PwbRgOcxj91Gk9TbYozzZwoXvFlbzk7W7zho/d1zse0Qbjxg5tr7ynsSN5xueIGIxKC4H@r1dI4bTwHnuCkgOZK4IjuzEi9gQbvA@/89APcYIcSTvlsd5uENnpQ7pFUdGJTTP2zW4gbE/Dnriu63usmWYFuuAtsYBJmfSaN5U05c1ji/zB5KtKlsuyuUyDcmNRZufs7vquyS7THw "C (gcc) – Try It Online")
[Answer]
# [PHP](https://php.net/), 200 bytes
>
>
> ```
>
> while($c=ord("CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?"[$i++]))echo$c;
>
> ```
>
>
>
>
[Try it online!](https://tio.run/##NY3RisIwFER/ZVbKqij9AHeXIlWXBdF9Fx9ictsEr024iUq@vlrBl@EwHGaCDf13FZ55t45pUugfL2YyqverNX732w0@UXvjuha1VczUtRQX@OuQvFF5HKHf9RzZX8fMOBFUPJN5KgjiuoRkCY1n9vdh6EaSEQNppxjL3QpJnD7nF0aVXGzyoP2LuxB218uJpCzLDyyFhgu0nhuSCCFlcjU6FG42O06npK0v9FffPwA "PHP – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 237 bytes
>
>
> ```
> s="CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?";o=o
> for((i=0;i<${#s};i++));do printf %d \'"${s:$i:${#o}}";done
> ```
>
>
>
>
[Try it online!](https://tio.run/##NY7BSsNAGITvPsWYRtNSCZ4Tg5S0iiCtD@Blk/03WbrdLftvlaXk2WMiehtmPmamEdyPI1dJfdju8Hp4f8E9aie17VD3whiyHXGBN4vgpIgZo/23HxDdJTMGDUHwkeSE4Oy1DQg9QTlj3Pdc9EU@gs/UamGw2W8RvG6P8VeyCJpVnLEPr0@E/eXUkM/z/BYbT/MEOmcUeYYnIeNzUrrK3Sjnl0tdPZb6Kb0ueCj1er1alfLvgcKdxGeWpFcuUl1MiBuGZIotjeMP "Bash – Try It Online")
Port of [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)'s [R answer](https://codegolf.stackexchange.com/a/209807/9481).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 121 bytes
>
>
> ```
> '€ƒuð.ø’CODE GOLF & Cod±µ Cí¤ÁÛ¡¾: In ƒÜ's ›Ý, €î'½ž €ï ‹Ð €„ …¢ €€ „— ‚Ò ƒÑÿÐËyÿËØ±µ P؆e Nuîв¡...! A‚™ €î Šˆ²¡s Žä?’ÇJ
> ```
>
>
>
>
[Try it online!](https://tio.run/##JY67DgFhEIVfZTS2kX0Ajci6hIj1CoRCQ7FR6H4iFJq1UbgHEZV7IkGCZE5W4y3@F1n/ruqcbyZzztStYqla8TxNtncfp4GTjpsUY8NMJClt5lIUJqNe5jNfycCeN2hhyit@RSlTo4@DmWaRFA/MI6QScND46b4Ce1TzO2zfS7FQsOV1AO2dgoUUQyUTOH7KAG/Y6DeV9DEK2goYSbGsUL6BA2y@8ErX9RDF1Y3srP9l5C6/XX9lkfvEJqYeRy/reT8 "05AB1E – Try It Online")
>
>
> ```
> '€ƒuð.ø’...’ÇJ # trimmed program
> '€ƒ # push "and"...
> u # uppercase...
> .ø # surrounded by...
> ð # spaces
> # (ÿ in the long compressed string gets implicitly replaced with this)
> J # join...
> Ç # charcodes of...
> ’...’ # "CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?"
> # implicit output
> ```
>
>
>
>
The hardest part of this wasn't writing the code, it was trying to get the Markdown to work.
[Answer]
# [Perl 5](https://www.perl.org/), 190 bytes
>
> `say"CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?"=~s/./ord$&/ger`
>
>
>
[Try it online!](https://tio.run/##NY1BSgNBEEWv8g2SbLQnLrIRJISJiqCJV@hM10yaVLqGqo7SG49u6wjuHp/HfyMpr2o1X2btfvuI5/3rE@ZoJcQ0oD16ZkoD2T1eErIEXxaG7n@@QZHLghkHgrcThV8Fo8aUkY@EXpjlczr6IC2wkbroGZvdFlljdyp/aD5H68ukvWs8E3aX84HUOXeFjdKUwCDckxqUfCjr2cOXNa4RDdfzZiCt9VvGHCVZvX1bueXd8gc "Perl 5 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 108 bytes
>
> ``¬⋎ »₅`⇧ `& ⟩₆ →ṗ: In ¬¾'s ɾṖ, λ•'ll be •₇ to ⟑Ẇ λλ ∧ṫ ƛ² ¬∪ AND ¦Ṡy AND ¶⊍ing ʁ꘍ ƛṅ...! λ∆ λ• »₅ers €æ?`+Cṅ`
> Needed to optimize the string little to compress it well
>
>
>
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60%C2%AC%E2%8B%8E%20%C2%BB%E2%82%85%60%E2%87%A7%60%20%26%20%E2%9F%A9%E2%82%86%20%E2%86%92%E1%B9%97%3A%20In%20%C2%AC%C2%BE%27s%20%C9%BE%E1%B9%96%2C%20%CE%BB%E2%80%A2%27ll%20be%20%E2%80%A2%E2%82%87%20to%20%E2%9F%91%E1%BA%86%20%CE%BB%CE%BB%20%E2%88%A7%E1%B9%AB%20%C6%9B%C2%B2%20%C2%AC%E2%88%AA%20AND%20%C2%A6%E1%B9%A0y%20AND%20%C2%B6%E2%8A%8Ding%20%CA%81%EA%98%8D%20%C6%9B%E1%B9%85...!%20%CE%BB%E2%88%86%20%CE%BB%E2%80%A2%20%C2%BB%E2%82%85ers%20%E2%82%AC%C3%A6%3F%60%2BC%E1%B9%85&inputs=&header=&footer=)
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), 195 bytes
>
>
> ```
> ;=s" CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?"W=sGsT LsO++''As'\'
> ```
>
>
>
>
[Try It Online!](https://tio.run/##lVhrc9s2Fv2@vwLmphYh0rSc6XQnkmmP4ziZTBM5G7vN7EpKDIKQxJoiFT5sqxL3r3fvBV@gXk7zIUMBB/eFcx/wH@yBxTzy5slRELriL@6zOCa/Bt5kmlxFURgR8ZSIwI2J/LXMcsAnFsWiua@cKVGf0yDxZs/jbpJIsNmSh0GcRClPwkhndJlMvdiKwzTiwmYZ7HjzL1MvEfGccaEX@zOW8Kl@/FUfDEfDwTCG9aw7Mlb/HHwdBqO2PgxWLyhtH9NsLsQ97EYiSaOAKMIHndFqFaS@n@XCHJPbHbr0RUKY7VjiSXBdgdNeIQKP2LbNzvGjq0Js5duKUwds1xmosXwRTJIpNdmAj2iWhOC4F0y2WpVlMhzk9j@frm7swaiXh@p35qdiGScs8TiZ4y3oDl061kZ4emOI4gOLwIdOj51KMYX@HjOM3D9uy/UBG1mlrJ431jkt7OGZ4msWpYEMexQ@kkA85ozIXOGkky3rO7yTQqx6E3D9dOaIaAeu3ATc6zD0BQt2AKvdrGDVBwhGxPyKeHno1kgWp3OUbkpR31yWMOBa7qiiZIszxe/63DZPit9N0IYb5YIKE999NK9AMOKB1SzgIhznXituHB4qxgMf868yCii8CkERkg3@lFyvs@n27YgOLo7@O2ofmycV5dnhIV4wytS1Ww210cxNZ/PKmbvSmRcyPzN6l/nJtHbloLb18JA1rm2i4oiKO2gCs5zM8zSe6rhKe3mqXPV/f//5uv/xqn9rL7MiYd67IkjWOPCc@wN29Oe3Ef7fOXr1DUKwHgApFIzN9rHJQxCwqRkfedQbe4DLQ5TjMFBgrjcJUI7iyaDGjCpq5gbvQGEGP4SeSzoHeD@l5b06QdW6rN/9FtwH4WNAvMoy0mqY1rprxly6QMv4KtH9UXoNXWMzpBDQIl0YXSdVsVFzirmuwpXyfM0Zgymlg2ZQg/fCj5rwWervhbebcNd7UL2st/AmGpdQivrIkqkFvAm4IvUY/N51SdolC4IwIaAK7oQ4C/KniEINTA3dv6m7VvgTe1YfiE/9UNE3Dx/366vFr1YHOjvt0B9yvt3@Ae/F0zwMkKQsEdIgkoRQGwMxAb49CALGiQiM9HdUklP13nbWm7MGqkH8mvZ9aIj7ea9U74r4/aKk0pzzKKRRQsoKgu12LQc0BOtU29cZpLzC@WdCycMZmCnkEUurgvE3T6nBwbUyOtAcnw0OUsixmdJztNaIwhwXD29G7XM6PDk2X0paYTSAWY5KJNCAw0o@xDArH@4QrLWwLfHVqqW18IPWLtVDKxY9sGrmBcAkl3xPQyCUCHiY4rJwu@TFkmV321q6tL@ZR@ZJh65WnbWaVQwI@2oWOnFXAAqFm6UHQbUuKxJzwaD3qBXoGcZXo9Zexlco9VJhseiucIq5N4uAd1lmR@J76kVC18axRs0ljshyy1G2@NTz3W/zKOQiRtTb3/qXt@@v@zd1b34LNWBfa1ZYkl8wTOaVmIGjdDp508qs2lN4dd6VWWesLHqcM0bgPI3zMf5wYT52T3k5G7vlbDy2pUVWaQoqOxjvoNNHD3p3MCEsmqQzHDheLF3jJCOghIzRS@ioDjbSnsgDO6aZcscYCJ2bjinWRgpY4mtjBYqzWf4dsJmwnfwbVMc235xd5QHdsqwKVVWWvIprqD3xwkDXjEpqFR6HlCOnPMoMWzOJZjhWLqPq4oa2UZuunT8ETywvlvw1YVzKxoUqEomJFydCukiXENoT7FXlA2ntLaFrfTCJzFIY8hxI1CfGE39BoBcQPmUR/IKZxQ@DCdSkXk0QNrIdRSMEpupc6tUWSQYvUN1R8oCqtaceo/L3Rm8rDbR@SB5QMhTK1HfRVqnCPYBaqWQVBpyaVQi0T5qpU/useJJpmunYr9PxWEQW8/2Q6zCAuyEGiekdYEQHJnITKO/Ak5I6YPh9jxvg6iNknNBPoAvLHfmSszC3vniQ@Now0CjlNrdi34MXYsckR/VkX1YaTjPVss@5ZY3WPfZD8PXnl69@fvXLv16@@qUtVyMWuOEMw6aev9JMZp9hyFgjtDWkddFCSJXoeXgLqxy1u4EB56WZuSRrHIWzS2DAZejCoFm8nWi3NFe9TosXuIsEZzbVyNfSSKYuXeZLxeNS/q9u38ntqg81ndvhqPZveagoiJZ48taruII9qBTIt1bzAdRAfqiQ6LFqSJlMKvoNcuusGt8awS4tixM3TBPrMYLGDQLzPKcma8Tsuimo1lpI04ZD@TwsyAZMO98hv2QjQGh3K@YOe@M/7qhZzUyqJQZQFItIfV3YaAvfGs4fbSDxXbAN2d5AYl/ehjzeQMrXwBbkT5syw@12ft1Ayql7C/K0QlZUKY/gRFAdUc@c7T4z2XXmfPcZLPlbzxxWZ3RW5nXj7zTnxbFuI/NWzx5jXWczI3vKsXzX3BYwW4E1ags@aVcrUKk875uJzKzife7YlX6nIfxLJXyJ3bPXSNoeXUu3rWR@n4uApm@fsa3B4pu@v1MOyaDVdptO45FmYvlXfpYVjJV/pUQhq5WmNaN2UyhwpYry0DOqXNvd1FyBy1aPY/05M2CqLE2ADkcNbtQmGS724rph/K@lVrzm0x1wEJ2yisDE8jB4CZ3wL/jXs2ONXF6/uSLvrj@8JYcEmgGObNA/fLRFxF0QCC9Kly1aMQ4W@bJJFmHagtcedHMW38NzAR6dc3AjgbFIwIQHLfoRBT2IaEHiueAe88lF/w0BX/n9Qn7GMNXG4wXCPkXwrCr@MghT2QG5gAcVqCCT0IeWHxMctBfn2hc7fhffkg/xtWG0Whdxa9j6Pw)
] |
[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/15648/edit).
Closed 6 years ago.
[Improve this question](/posts/15648/edit)
It's getting to be that time of year, and I figured I might as well post the first winter-themed question :)
Your challenge is to **build a snowman.**
How, you ask? Well, you decide! You can do ASCII art, you can animate it, you can golf the code, you can make the code that generates the snowman itself a snowman, you can generate a colored image; be creative!
This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so the answer with the most upvotes at the end of December will win. (If an answer surpasses the winner in upvotes, then it will become the new winner.) The winning answer will get the magical green check mark!
[Answer]
**JavaScript/HTML: 454 Characters**
Thanks @Doorknob for the idea
*Snowman Sitting in the Snow*
Here it is running:
<http://jsfiddle.net/au35H/1/>
Code-golfed:
```
<html><head><script>(function(){for(var f=[".",",","*"," "," "],e=["☃",2],n=[16,8],t=[],r,u,i=0;i<n[1];i++){for(r=[],u=0;u<n[0];u++)r.push(" ");t.push(r)}setInterval(function(){for(var r=[],u=[],i=0;i<n[1];i++)r.push(t[i].join(""));for(document.body.innerHTML=r.join("\n"),i=0;i<n[0];i++)u.push(f[Math.floor(Math.random()*f.length)]);t.pop(),t.splice(0,0,u),t[n[1]-1][e[1]]=e[0]},500)})();</script><body style="font:80px monospace;white-space:pre">
```
[Answer]
I just *know* someone is going to post this eventually, so **1 character** in HTML:
```
☃
```
(That's a Unicode snowman; U+2603)
It's pretty hard to see, so here's **23 characters**:
```
<p style=font-size:99>☃
```
Renders as this on my browser:

Or, I could be evil and use the deprecated and terrible `font` tag for **15 characters**:
```
<font size=99>☃
```
It renders smaller for some reason.

(of course, these HTML files aren't valid, but latest Chrome (31.0.1650.57 as of writing) gladly accepts them)
[Answer]
Polyglot, 1 character
```
8
```
Sorry.
[Answer]
## MSBuild
Save the following project file as **snowman**:
```
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="x">
<Target Name="x">
<Exec Command="start http://unicodesnowmanforyou.com"/>
</Target>
</Project>
```
The task was to *build* a snowman, so:
```
msbuild snowman
```

[Answer]
This is a bit of a cheat as it is mostly reusing some existing code, but it's a slightly modified version of a C++ AMP realtime GPU path tracer I wrote.

Most of the interesting code is here but there's some utility code in a couple of other files for setting up D3D, setting up the window etc.
```
#include "app.h"
#include "d3d11device.h"
#include <vector>
#include <fstream>
#include <chrono>
#include <iostream>
#include <initializer_list>
#include <random>
#include <cassert>
#include <cmath>
#include <amp.h>
#include <amp_graphics.h>
#include <Xinput.h>
#include <amputils.h>
using namespace std;
using namespace renderer;
using namespace concurrency;
using namespace concurrency::direct3d;
using namespace concurrency::graphics;
using namespace concurrency::graphics::direct3d;
using namespace concurrency::fast_math;
using namespace DirectX;
using namespace amputils;
namespace {
template<typename T, size_t N>
size_t ArraySize(T (&)[N]) {
return N;
}
vector<char> LoadFile(const char* filename) {
ifstream file(filename, ios_base::binary);
return vector<char>(istreambuf_iterator<char>(file), (istreambuf_iterator<char>()));
}
struct SimpleVertex
{
float x, y, z;
};
class Sphere
{
public:
Sphere(const Vector3& center_, float radius_) restrict(amp, cpu) : center(center_), radius(radius_) {}
Vector3 GetCenter() const restrict(amp, cpu) { return center; }
float GetRadius() const restrict(amp, cpu) { return radius; }
// Used for sampling a light from a point
Vector3 Sample(const Vector3& p, float u1, float u2, Vector3& normal) const restrict(amp, cpu);
float Pdf(const Vector3& p, const Vector3& /*wi*/) const restrict(amp, cpu) {
Vector3 pToCenter = center - p;
float sinThetaMax2 = radius * radius / Dot(pToCenter, pToCenter);
float cosThetaMax = sqrt(max(0.1f, 1.f - sinThetaMax2));
return UniformConePdf(cosThetaMax);
}
private:
Vector3 center;
float radius;
};
class DifferentialGeometry
{
public:
DifferentialGeometry() restrict(amp, cpu) : p(0.0f), n(0.0f) {}
DifferentialGeometry(const Vector3& p_, const Vector3& n_) restrict(amp, cpu) : p(p_), n(n_) {}
const Vector3& GetPoint() const restrict(amp, cpu) { return p; }
const Vector3& GetNormal() const restrict(amp, cpu) { return n; }
private:
Vector3 p;
Vector3 n;
};
bool IntersectP(const Ray& ray, const Sphere& sphere, float& t) restrict(amp, cpu)
{
const auto v = ray.GetOrigin() - sphere.GetCenter();
const auto a = Dot(ray.GetDirection(), ray.GetDirection());
const auto minusB = -2.f * Dot(ray.GetDirection(), v);
const auto c = Dot(v, v) - Square(sphere.GetRadius());
const auto discrim = (Square(minusB) - 4.f * a * c);
if (discrim < 0.f) {
return false;
}
const auto sqrtDiscrim = sqrt(discrim);
const auto tMax = minusB + sqrtDiscrim;
if (tMax < 0.f) {
return false;
}
const auto denominator = 1.f / (2.f * a);
const auto tMin = minusB - sqrtDiscrim;
t = (tMin < 0.f ? tMax : tMin) * denominator;
return true;
}
bool Intersect(const Ray& ray, const Sphere& sphere, float& t, DifferentialGeometry& dg) restrict(amp, cpu)
{
const auto v = ray.GetOrigin() - sphere.GetCenter();
const auto a = Dot(ray.GetDirection(), ray.GetDirection());
const auto minusB = -2.f * Dot(ray.GetDirection(), v);
const auto c = Dot(v, v) - Square(sphere.GetRadius());
const auto discrim = (Square(minusB) - 4.f * a * c);
if (discrim < 0.f) {
return false;
}
const auto sqrtDiscrim = sqrt(discrim);
const auto tMax = minusB + sqrtDiscrim;
if (tMax < 0.f) {
return false;
}
const auto denominator = 1.f / (2.f * a);
const auto tMin = minusB - sqrtDiscrim;
t = (tMin < 0.f ? tMax : tMin) * denominator;
Vector3 p = ray(t);
dg = DifferentialGeometry(p, Normalize(p - sphere.GetCenter()));
return true;
}
inline Vector3 Sphere::Sample(const Vector3& p, float u1, float u2, Vector3& normal) const restrict(amp, cpu) {
Vector3 pToCenter = center - p;
Vector3 wc = Normalize(pToCenter);
Vector3 wcX(0.0f), wcY(0.0f);
CoordinateSystem(wc, wcX, wcY);
float sinThetaMax2 = radius * radius / Dot(pToCenter, pToCenter);
float cosThetaMax = sqrt(max(0.1f, 1.f - sinThetaMax2));
float tHit;
DifferentialGeometry dg;
Ray r(p, UniformSampleCone(u1, u2, cosThetaMax, wcX, wcY, wc));
if (!Intersect(r, *this, tHit, dg))
tHit = Dot(pToCenter, Normalize(r.GetDirection()));
normal = dg.GetNormal();
return dg.GetPoint();
}
class Primitive
{
public:
Primitive(const Sphere& s_, const Vector3& color_) restrict(amp, cpu) : s(s_), color(color_) {}
const Sphere& GetSphere() const restrict(amp, cpu) { return s; }
const Vector3& GetColor() const restrict(amp, cpu) { return color; }
private:
Sphere s;
Vector3 color;
};
struct CameraSample
{
CameraSample(float x_, float y_) restrict(amp, cpu) : x(x_), y(y_) {}
float x, y;
};
class StratifiedSampler
{
public:
explicit StratifiedSampler(int n) restrict(amp, cpu) : mN(n) {}
int GetNumSamples() const restrict(amp, cpu) { return mN * mN; }
CameraSample Sample2D(amputils::Rng& rng, int i) restrict(amp, cpu) {
float dxy = 1.0f / mN;
float xOff = static_cast<float>(i % mN);
float yOff = static_cast<float>(i / mN);
return CameraSample((xOff + rng.GetUniform()) * dxy, (yOff + rng.GetUniform()) * dxy);
}
private:
StratifiedSampler& operator=(const StratifiedSampler&);
int mN;
};
class Camera
{
public:
Camera(int filmWidth, int filmHeight)
: mPos(0.0f, 0.0f, -20.0f),
mYaw(0.0f),
mPitch(0.0f),
mWorldToCamera(XMMatrixLookAtLH(XMVectorReplicate(0.0f), XMVectorReplicate(1.0f), XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f))),
mCameraToWorld(XMMatrixInverse(nullptr, mWorldToCamera.GetXMMATRIX())),
mProjection(XMMatrixPerspectiveFovLH(3.1415f * 0.333f, 1.0f, 1e-2f, 1e3f)),
mInverseProjection(XMMatrixInverse(nullptr, mProjection.GetXMMATRIX())),
mFilmWidth(filmWidth),
mFilmHeight(filmHeight)
{
UpdateMatrices();
}
const Matrix4& GetWorldToCamera() const restrict(amp, cpu) { return mWorldToCamera; }
const Matrix4& GetCameraToWorld() const restrict(amp, cpu) { return mCameraToWorld; }
const Matrix4& GetProjection() const restrict(amp, cpu) { return mProjection; }
const Matrix4& GetInverseProjection() const restrict(amp, cpu) { return mInverseProjection; }
void RotateCam(float yaw, float pitch)
{
mYaw += yaw;
mPitch = Clamp(mPitch + pitch, 3.14f * -0.45f, 3.14f * 0.45f);
UpdateMatrices();
}
void TranslateCam(const Vector3& trans)
{
mPos += trans;
UpdateMatrices();
}
Ray GenerateRay(int x, int y, int i, StratifiedSampler& samp, amputils::Rng& rng) const restrict(amp, cpu) {
auto camSamp = samp.Sample2D(rng, i);
const float fx = (camSamp.x + float(x)) / float(mFilmWidth);
const float fy = (camSamp.y + float(y)) / float(mFilmHeight);
const Vector4 rayFilm(2.0f * fx - 1.0f, 2.0f * fy - 1.0f, 0.0f, 1.0f);
const Vector4 rayFilmCam = Project(rayFilm, GetInverseProjection());
const Vector4 rayFilmWorld = Transform(rayFilmCam, GetCameraToWorld());
const Vector4 rayStartWorld(mPos.x(), mPos.y(), mPos.z(), 1.0f);
const Vector4 rayDirection(rayFilmWorld - rayStartWorld);
return Ray(Vector3(rayStartWorld.e(0), rayStartWorld.e(1), rayStartWorld.e(2)), Vector3(rayDirection.e(0), rayDirection.e(1), rayDirection.e(2)));
}
private:
void UpdateMatrices()
{
XMMATRIX cam = XMMatrixLookAtLH(XMVectorSet(mPos.x(), mPos.y(), mPos.z(), 1.0f), XMVectorSet(mPos.x(), mPos.y(), mPos.z() + 1.0f, 1.0f), XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f));
XMMATRIX rot = XMMatrixMultiply(XMMatrixRotationY(mYaw), XMMatrixRotationX(mPitch));
mWorldToCamera = XMMatrixMultiply(cam, rot);
mCameraToWorld = XMMatrixInverse(nullptr, mWorldToCamera.GetXMMATRIX());
}
Vector3 mPos;
float mYaw, mPitch;
Matrix4 mWorldToCamera;
Matrix4 mCameraToWorld;
Matrix4 mProjection;
Matrix4 mInverseProjection;
int mFilmWidth, mFilmHeight;
};
class Scene;
class SceneView
{
public:
int GetNumPrims() const restrict(amp, cpu) { return prims.extent.size(); }
const Primitive& GetPrim(int i) const restrict(amp, cpu) { return prims[i]; }
const Camera& GetCamera() const restrict(amp, cpu) { return camera; }
const Primitive& GetLight() const restrict(amp, cpu) { return light; }
private:
friend class Scene;
explicit SceneView(const Camera& camera_, const vector<Primitive>& prims_, const Primitive& light_)
: camera(camera_),
prims(prims_.size(), prims_),
light(light_)
{
}
Camera camera;
array_view<const Primitive> prims;
Primitive light;
};
class Scene
{
public:
explicit Scene(int filmWidth, int filmHeight, const initializer_list<Primitive>& prims_)
: camera(filmWidth, filmHeight),
prims(prims_.begin(), prims_.end()),
light(Sphere(Vector3(50.0f, 50.0f, -50.0f), 5.0f), Vector3(0.75f, 0.75f, 0.67f))
{
}
SceneView GetView() const
{
return SceneView(camera, prims, light);
}
Camera& GetCamera() { return camera; }
const Camera& GetCamera() const { return camera; }
const Primitive& GetLight() const { return light; }
Primitive& GetPrimitive(int i) { return prims[i]; }
private:
Camera camera;
vector<Primitive> prims;
Primitive light;
};
}
Scene MakeScene(int filmWidth, int filmHeight)
{
auto prims = {
Primitive(Sphere(Vector3(0.0f, 0.0f, 1100.0f), 1000.0f), Vector3(0.61f, 0.78f, 1.0f)),
Primitive(Sphere(Vector3(0.0f, -1010.0f, 0.0f), 1000.0f), Vector3(0.85f, 0.85f, 0.85f)),
Primitive(Sphere(Vector3(-2.0f, -6.5f, 2.0f), 4.0f), Vector3(0.85f, 0.85f, 0.85f)),
Primitive(Sphere(Vector3(-2.0f, -1.5f, 2.0f), 3.0f), Vector3(0.85f, 0.85f, 0.85f)),
Primitive(Sphere(Vector3(-2.0f, 2.8f, 2.0f), 2.0f), Vector3(0.85f, 0.85f, 0.85f)),
Primitive(Sphere(Vector3(-2.0f, 2.8f, 0.0f), 0.2f), Vector3(0.05f, 0.05f, 0.05f)),
Primitive(Sphere(Vector3(-2.5f, 3.5f, 0.3f), 0.2f), Vector3(0.05f, 0.05f, 0.05f)),
Primitive(Sphere(Vector3(-1.5f, 3.5f, 0.3f), 0.2f), Vector3(0.05f, 0.05f, 0.05f))
};
return Scene(filmWidth, filmHeight, prims);
}
class App : public IApp {
public:
App(void* hwnd, int width, int height);
~App();
void Update(bool mouseButtons[2], int mouseX, int mouseY) override;
private:
void UpdateControllerState();
void UpdateTexture(unsigned t);
Device mDevice;
// No copy or assignment
App(const App&);
App operator=(const App&);
ID3D11VertexShaderPtr mVs;
ID3D11PixelShaderPtr mPs;
accelerator_view mAcceleratorView;
texture<float_4, 2> mAmpTex;
ID3D11Texture2DPtr mD3dTex;
ID3D11ShaderResourceViewPtr mTexView;
ID3D11SamplerStatePtr mSamplerState;
ID3D11InputLayoutPtr mInputLayout;
ID3D11BufferPtr mQuadVertexBuffer;
ID3D11BufferPtr mQuadIndexBuffer;
chrono::time_point<chrono::high_resolution_clock> mLastFrameTime;
Scene mScene;
XINPUT_STATE mControllerState;
vector<amputils::Rng::SeedValue> mRngSeeds;
};
App::App(void* hwnd, int width, int height) :
mDevice(hwnd, width, height),
mAcceleratorView(create_accelerator_view(mDevice.GetD3D11Device())),
mAmpTex(width, height, mAcceleratorView),
mD3dTex(get_texture(mAmpTex)),
mLastFrameTime(chrono::high_resolution_clock::now()),
mScene(MakeScene(width, height)),
mRngSeeds(mAmpTex.extent.size())
{
auto vs = LoadFile("simplevs.cso");
mDevice.GetD3D11Device()->CreateVertexShader(vs.data(), vs.size(), nullptr, &mVs);
auto ps = LoadFile("simpleps.cso");
mDevice.GetD3D11Device()->CreatePixelShader(ps.data(), ps.size(), nullptr, &mPs);
CD3D11_SHADER_RESOURCE_VIEW_DESC resViewDesc(mD3dTex, D3D11_SRV_DIMENSION_TEXTURE2D);
mDevice.GetD3D11Device()->CreateShaderResourceView(mD3dTex, &resViewDesc, &mTexView);
CD3D11_SAMPLER_DESC samplerDesc(D3D11_DEFAULT);
mDevice.GetD3D11Device()->CreateSamplerState(&samplerDesc, &mSamplerState);
D3D11_INPUT_ELEMENT_DESC elems[] = {
{ "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
mDevice.GetD3D11Device()->CreateInputLayout(elems, ArraySize(elems), vs.data(), vs.size(), &mInputLayout);
SimpleVertex quadVerts[] = {
{ -1.0f, 1.0f, 0.0f },
{ 1.0f, 1.0f, 0.0f },
{ 1.0f, -1.0f, 0.0f },
{ -1.0f, -1.0f, 0.0f },
};
CD3D11_BUFFER_DESC vbDesc(sizeof(quadVerts), D3D11_BIND_VERTEX_BUFFER);
D3D11_SUBRESOURCE_DATA vbData = { quadVerts, 0, 0 };
mDevice.GetD3D11Device()->CreateBuffer(&vbDesc, &vbData, &mQuadVertexBuffer);
uint16_t quadIndices[] = { 0, 1, 2, 2, 3, 0 };
CD3D11_BUFFER_DESC ibDesc(sizeof(quadIndices), D3D11_BIND_INDEX_BUFFER);
D3D11_SUBRESOURCE_DATA ibData = { quadIndices, 0, 0 };
mDevice.GetD3D11Device()->CreateBuffer(&ibDesc, &ibData, &mQuadIndexBuffer);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<unsigned int> dis;
for_each(begin(mRngSeeds), end(mRngSeeds), [&gen, &dis](amputils::Rng::SeedValue& seedValue) {
seedValue = amputils::Rng::SeedValue(dis(gen), dis(gen), dis(gen), dis(gen));
});
amputils::Rng rng(amputils::Rng::SeedValue(dis(gen), dis(gen), dis(gen), dis(gen)));
StratifiedSampler sampler(4);
for (int i = 0; i < sampler.GetNumSamples(); ++i) {
auto samp = sampler.Sample2D(rng, i);
cout << samp.x << ", " << samp.y << "\n";
}
}
App::~App() {
}
bool IsShadowed(const Ray& ray, const SceneView& scene) restrict(amp, cpu)
{
auto lightT = FLT_MAX;
if (!IntersectP(ray, scene.GetLight().GetSphere(), lightT))
return true;
for (auto i = decltype(scene.GetNumPrims())(0); i < scene.GetNumPrims(); ++i)
{
const auto& sphere = scene.GetPrim(i).GetSphere();
float t = FLT_MAX;
if (IntersectP(ray, sphere, t) && t < lightT) {
return true;
}
}
return false;
}
template<int RecursionDepth>
inline Vector3 TraceRay(const Ray& ray, const SceneView& scene, Rng& rng, int sampIdx) restrict(amp, cpu)
{
Vector3 color(0.1f, 0.1f, 0.25f);
auto nearestT = FLT_MAX;
DifferentialGeometry nearestDg;
Vector3 nearestDiffuseColor(0.0f);
for (auto i = decltype(scene.GetNumPrims())(0); i < scene.GetNumPrims(); ++i)
{
const auto& sphere = scene.GetPrim(i).GetSphere();
float t = FLT_MAX;
DifferentialGeometry dg;
if (Intersect(ray, sphere, t, dg) && t < nearestT) {
nearestT = t;
nearestDg = dg;
nearestDiffuseColor = scene.GetPrim(i).GetColor();
}
}
if (nearestT < FLT_MAX) {
// Direct lighting
StratifiedSampler sampler(4);
auto samp = sampler.Sample2D(rng, sampIdx);
Vector3 lightNormal(0.0f);
const auto lightPos = scene.GetLight().GetSphere().Sample(nearestDg.GetPoint(), samp.x, samp.y, lightNormal);
const auto L = Normalize(lightPos - nearestDg.GetPoint());
if (IsShadowed(Ray(nearestDg.GetPoint() + L * 1e-3f, L), scene))
color = Vector3(0.0f);
else
color = nearestDiffuseColor * Dot(nearestDg.GetNormal(), L) * scene.GetLight().GetColor();
// Indirect lighting
auto indirectSamp = sampler.Sample2D(rng, sampIdx);
auto indirectDirLocal = CosineSampleHemisphere(indirectSamp.x, indirectSamp.y);
Vector3 normalZ = nearestDg.GetNormal();
Vector3 normalX(0.0f), normalY(0.0f);
CoordinateSystem(normalZ, normalX, normalY);
auto indirectDirWorld = normalX * indirectDirLocal.x() + normalY * indirectDirLocal.y() + normalZ * indirectDirLocal.z();
Ray indirectRay(nearestDg.GetPoint() + nearestDg.GetNormal() * 1e-3f, indirectDirWorld);
auto indirectColor = TraceRay<RecursionDepth - 1>(indirectRay, scene, rng, sampIdx) * CosineHemispherePdf(Dot(indirectDirWorld, nearestDg.GetNormal()), 0.0f);
color += indirectColor * nearestDiffuseColor;
}
return color;
}
template<>
inline Vector3 TraceRay<0>(const Ray& /*ray*/, const SceneView& /*scene*/, Rng& /*rng*/, int /*sampIdx*/) restrict(amp, cpu)
{
return Vector3(0.0f);
}
const int Height = 512;
const int Width = 512;
inline float_4 RaytraceScene(int x, int y, const SceneView& scene, Rng& rng) restrict (amp, cpu)
{
float_4 totalIrradiance = 0.0f;
StratifiedSampler sampler(4);
for (int samp = 0; samp < sampler.GetNumSamples(); ++samp)
{
auto ray = scene.GetCamera().GenerateRay(x, y, samp, sampler, rng);
totalIrradiance += ToFloat4(TraceRay<4>(ray, scene, rng, samp));
}
totalIrradiance *= 1.0f / sampler.GetNumSamples();
return totalIrradiance;
}
void App::UpdateTexture(unsigned t)
{
auto sceneView = mScene.GetView();
auto ampTexView = writeonly_texture_view<float_4, 2>(mAmpTex);
auto rngSeedsView = array_view<const amputils::Rng::SeedValue, 2>(ampTexView.extent, mRngSeeds);
parallel_for_each(mAcceleratorView, mAmpTex.extent, [ampTexView, sceneView, t, rngSeedsView](index<2> idx) restrict(amp) {
//Rng::SeedValue rngSeed(rngSeedsView[idx].z1 + t, rngSeedsView[idx].z2 + t, rngSeedsView[idx].z3 + t, rngSeedsView[idx].z4 + t);
Rng rng(rngSeedsView[idx]);
ampTexView.set(idx, RaytraceScene(idx[1], idx[0], sceneView, rng));
});
}
void App::UpdateControllerState()
{
for (DWORD i = 0; i < 4; ++i)
{
// Simply get the state of the controller from XInput.
ZeroMemory(&mControllerState, sizeof(mControllerState));
DWORD dwResult = XInputGetState(i, &mControllerState);
if (dwResult == ERROR_SUCCESS)
return;
}
}
float GetThumbstickAmount(const int rawVal)
{
const int inputDeadzone = static_cast<int>(0.24f * float(0x7FFF)); // Default to 24% of the +/- 32767 range.
const int deadzoneVal = abs(rawVal) < inputDeadzone ? 0 : rawVal + inputDeadzone * Sign(rawVal);
return float(deadzoneVal) / float(0x7FFF - inputDeadzone);
}
void App::Update(bool /*mouseButtons*/[2], int /*mouseX*/, int /*mouseY*/)
{
static const auto startTime = chrono::high_resolution_clock::now();
auto frameTime = chrono::high_resolution_clock::now();
auto frameMs = chrono::duration_cast<chrono::milliseconds>(frameTime - mLastFrameTime);
//float frameS = chrono::duration_cast<chrono::milliseconds>(frameTime - startTime).count() * 1e-3f;
mLastFrameTime = frameTime;
UpdateControllerState();
float xRot = GetThumbstickAmount(mControllerState.Gamepad.sThumbRX) * float(frameMs.count()) * -1e-3f;
float yRot = GetThumbstickAmount(mControllerState.Gamepad.sThumbRY) * float(frameMs.count()) * 1e-3f;
mScene.GetCamera().RotateCam(xRot, yRot);
Vector4 camForward = mScene.GetCamera().GetCameraToWorld().GetRow(2);
Vector4 camStrafe = mScene.GetCamera().GetCameraToWorld().GetRow(0);
float forward = GetThumbstickAmount(mControllerState.Gamepad.sThumbLY) * float(frameMs.count()) * 5e-3f;
float strafe = GetThumbstickAmount(mControllerState.Gamepad.sThumbLX) * float(frameMs.count()) * 5e-3f;
Vector4 camTranslate = camForward * forward + camStrafe * strafe;
mScene.GetCamera().TranslateCam(Vector3(camTranslate.x(), camTranslate.y(), camTranslate.z()));
/*
auto movingSpherePos = Vector3(sin(frameS), cos(frameS), cos(frameS)) * 5.0f;
mScene.GetPrimitive(6) = Primitive(Sphere(movingSpherePos, 3.0f), Vector3(0.6f, 0.6f, 0.05f));
*/
UpdateTexture(static_cast<unsigned>(frameTime.time_since_epoch().count()));
mDevice.ClearDefaultRenderTarget();
mDevice.SetDefaultRenderTarget();
ID3D11DeviceContextPtr deviceContext;
mDevice.GetD3D11Device()->GetImmediateContext(&deviceContext);
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
deviceContext->IASetInputLayout(mInputLayout);
deviceContext->IASetIndexBuffer(mQuadIndexBuffer, DXGI_FORMAT_R16_UINT, 0);
ID3D11Buffer* vbs[] = { mQuadVertexBuffer.GetInterfacePtr() };
UINT strides[] = { sizeof(SimpleVertex) };
UINT offsets[] = { 0 };
deviceContext->IASetVertexBuffers(0, ArraySize(vbs), vbs, strides, offsets);
deviceContext->VSSetShader(mVs, nullptr, 0);
deviceContext->PSSetShader(mPs, nullptr, 0);
ID3D11ShaderResourceView* srvs[] = { mTexView.GetInterfacePtr() };
deviceContext->PSSetShaderResources(0, ArraySize(srvs), srvs);
ID3D11SamplerState* samplers[] = { mSamplerState.GetInterfacePtr() };
deviceContext->PSSetSamplers(0, ArraySize(samplers), samplers);
deviceContext->DrawIndexed(6, 0, 0);
ID3D11ShaderResourceView* emptySrvs[] = { nullptr };
deviceContext->PSSetShaderResources(0, ArraySize(emptySrvs), emptySrvs);
mDevice.Present();
cout << frameMs.count() << endl;
}
unique_ptr<IApp> CreateApp(void* hwnd, int width, int height) {
return unique_ptr<IApp>(new App(hwnd, width, height));
}
```
[Answer]
# Befunge 93
```
>" )__:__( @"v
v"@'--( : )--'"<
>" )^_^( @"v
v"@ _[_]_ "<
>" _ @"v
@ v_v#!-"@":<
>$ 91+,:!v
>,: !#v_^
^ <
```
Ouput:
```
_
_[_]_
(^_^)
'--( : )--'
(__:__)
```
Change one character for infinite snowmen:
```
>" )__:__( @"v
v"@'--( : )--'"<
>" )^_^( @"v
v"@ _[_]_ "<
>" _ @"v
@ v_v#!-"@":<
>$ 91+,:!v
>,: !#v_^
v <
```
How it works: stores the characters in the snowman on the stack. @ symbolizes a new line. Then, loops through all the characters; if it is an @, print a new line: `91+,`, otherwise, print the character. Then, it checks if the end has been reached. If it has, it exits the loop: `#v_^`.
---
# Ascii art versions
```
>")__:__( @"v
v <
> v
vv"@'--( : )--'"<vv
v v_
>" )" "^" v
v"@ ""(" "^""_" <
>" " v
v "_[_]_" <<
>> v
v <
_ >" ":"@ ": ::v _
| | v :: :" _"< | |
| |=====> v=====| |
=======v "@" +0 <=======|
>> v
v <
%v< o o <v
%v< 0 0 &%
%> v
v "@" : <
>> v
v +0+0:,+19$<_v#!-<
_____>0+!#v_v#+0!:,<@@@@ _____
@@@@@@@$0 <@>0+0+0+0+0+ ^@@@@@
```
Outputs the exact same thing. Can also be changed to infinite snowman:
```
>")__:__( @"v
v <
> v
vv"@'--( : )--'"<vv
v v_
>" )" "^" v
v"@ ""(" "^""_" <
>" " v
v "_[_]_" <<
>> v
v <
_ >" ":"@ ": ::v _
| | v :: :" _"< | |
| |=====> v=====| |
=======v "@" +0 <=======|
>> v
v <
%v< o o <v
%v< 0 0 &%
%> v
v "@" : <
>> v
v +0+0:,+19$<_v#!-<
_____>0+!#v_v#+0!:,<@@@@ _____
@@@@@@v$0 <@>0+0+0+0+0+ ^@@@@@
```
] |
[Question]
[
Using a language of your choice write a program that takes a string as an input, and returns the string encrypted.
# Algorithm:
You should assume that each character is always encoded in a byte and is ASCII-based. The extended ASCII codes are mapped to whatever is the default code page in use by the system.
You should encrypt the code in the following way:
code of first character +1, code of second character +2, code of third character +3 .....
Extended ASCII codes are based on this table:
<http://www.asciitable.com/>
Shortest code wins.
[Answer]
# BrainFuck: 21
```
>,[+<[->+>+<<]>.>+>,]
```
Assumes EOF=zero
```
echo -n 'My secret password is 123456!' | beef encrypt.bf
==> N{#wjiym}*{mv36HJLNPR>
```
[Answer]
# C — ~~67~~ ~~56~~ 49 characters
During compilation it might warn that `q` is missing a type...
```
q;main(p){for(;p=~getchar();)putchar(q++%255-p);}
```
Thanks to Josh for the significantly shorter rewrites!
```
$ echo 'My secret password is 123456!' | ./_encrypt
N{#wjiym}*{m����v3}�6HJLNPR>(
```
Confirm it handles the rollover from 255 to 1 correctly by encrypting 343 `x`s and checking for no `x`s in the output:
```
$ echo xxxxxxx | sed -e 's/x/xxxxxxx/g' -e 's/x/xxxxxxx/g' | ./_encrypt | grep -o x | wc -l
0
```
[Answer]
# Befunge 98 - 15 bytes
```
:~+'U3*%1+,1+#@
```
Keeps a counter (starting at 0) and adds that to the `~` input. Then, computes `255` (as `85 * 3` in the form of `'U3*`), then mods (`%`). Then, it adds `1` and prints it, then adds one to the counter, then uses `#` to skip over the `@`. At the end of the input, the IP goes the other way and hits the `@`, ending the program.
Alternatively, if your interpreter supports unicode, this 14 byte (13 char) solution works:
```
:~+'ÿ%1+,1+#@
```
Sample run (in command prompt, so some of the unicode characters are actually some ascii value):
```
This string will be encrypted using the predetermined method!2.7182818284590452353602874713526624
```
Output:
```
Ujlw%y{zrxr,äw{|1tx4zäzèÆèÅüü>öôèÉèDÖÄîHÖ£ÉÉÆóöó₧¢íÖÖVñ¥¡ó¬á^pmwrzu|v~yÇ}⌂ä|üâüâåàëäçÄÄîÉïÄæÅöòÆò
```
[Answer]
## GolfScript ~~20~~ ~~19~~ ~~15~~ 12
```
{0)255%:0+}%
```
This assigns a variable to the character `0`, which allows us to not define it on the first iteration of the mapping. I love that you can do that in GolfScript! Each iteration of the mapping increments the `0` variable, and adds it to subsequent characters of the string (which is treated like an array).
This alternate 20-character GolfScript solution using `zip` encounters an interesting issue:
```
.,,]zip{~)255%+}%''+
```
Try it [here](http://copy.sh/golfscript/?c=ImhlbGxvIHdvcmxkIgouLCxdemlwe34pMjU1JSt9JScnKw==). [This standard online interpreter](http://golfscript.apphb.com/), however, treats `zip` differently for an array containing a string and an array. See [this](http://copy.sh/golfscript/?c=WyJ6aXAiIFsxIDIgM11demlwIHAKW1sxIDIgM10gInppcCJdemlwIHA=) vs [this](http://golfscript.apphb.com/?c=WyJ6aXAiIFsxIDIgM11demlwIHAKW1sxIDIgM10gInppcCJdemlwIHA=). I'm not sure if an alternate version of Ruby or GolfScript is being used, or which one is considered canonical, but the second interpreter can be resolved with 2 characters:
```
.,,[\]zip{~)255%+}%''+
```
I also like a different solution for 23 characters:
```
1\{(@.@255%+\)@.}do]''+
```
[Answer]
## J, 21 characters
```
a.{~1+256|(+i.@#)a.i.
```
Usage (borrowing Yimin's test text):
```
a.{~1+256|(+i.@#)a.i.'My secret password is 123456!'
N{#wjiym}*{m????v3}?6HJLNPR>
```
[Answer]
# Python2.7 (67 chars)
```
import sys;print''.join([chr((ord(x)+1)%256)for x in sys.argv[1]])
```
[Answer]
## JavaScript, 90c
```
~~`t.split("").map(function(c,a){return String.fromCharCode(c.charCodeAt(0)+a+1)}).join("")`~~
```
```
[].map.call(t,function(c,a){return String.fromCharCode(c.charCodeAt(0)+a%255+1)}).join("")
```
[Fiddledee](http://jsfiddle.net/z92nQ/1/)
[Answer]
# **Javascript/JScript: 72 to 105 chars**
Here is a Javascript/JScript attempt at making a version of this code.
I'm aware that there is another Javascript code, but that one relies on recent Javascript implementations.
That is a bad thing!!!
That code is invalid in ie8< without polyfills.
Here is my version:
```
function $(c){for(var i=0,l=c.length,o='';i<l;o+=String.fromCharCode(c.charCodeAt(i++)+i&255));return o;}
//function call, 105 chars, absolutely valid!
function $(c){for(i=0,l=c.length,o='';i<l;o+=String.fromCharCode(c.charCodeAt(i++)+i&255));return o;}
//function call, no var keyword, 101 chars, completely valid!
function $(c){for(i=0,l=c.length,o='';i<l;o+=String.fromCharCode(c.charCodeAt(i++)+i));return o;}
//function call, 97 chars, most likely invalid!
c='';//here goes input, output is in var `o`, dont count this line
for(i=0,l=c.length,o='';i<l;o+=String.fromCharCode(c.charCodeAt(i++)+i&255));
//no function call, input goes to var c, 77 chars of pure working code! valid for sure!
c='';//here goes input, output is in var `o`, dont count this line
for(i=0,l=c.length,o='';i<l;o+=String.fromCharCode(c.charCodeAt(i++)+i));
//no function call, input goes to var c, no char wrapping after 255, 73 chars of probably invalid code
```
---
@toothbrush gave me this answer:
```
i=0;while(i<c.length)c[i]=String.fromCharCode(c.charCodeAt(i++)+i%255+1)
```
It changes the original string and is only **72** bytes!
I don't know why he has `%255+1` in the end when `&255` does the same job, is faster and shorter.
But I will keep the original answer intact.
---
Consider this and test it with a Javascript/JScript interpreter.
I know that the 73 char version and the 97 char function call version will be invalid, but its still here!
If you will be using the code in a production environment (website), use the 105 chars long and consider changing the function name to something else (or you might have problems with jQuery and MooTools).
[Answer]
# Python3 (99 chars)
```
e=''
i=0
for c in __import__("sys").argv[1]:
i=(i+1)%255
e+=chr(ord(c)+i)
print(e)
```
## Example
`python encrypt.py password` outputs `qcvw|uyl`
[Answer]
## CoffeeScript, ~~73~~ 64 chars
`t.replace /./g,(c,a)->String.fromCharCode c.charCodeAt()+a%255+1`
~~`[].map.call(t,(c,a)->String.fromCharCode c.charCodeAt(0)+a%255+1).join ""`~~
Example: `"Test string".replace /./g,(c,a)->String.fromCharCode c.charCodeAt()+a%255+1` outputs `Ugvx%y{zrxr`
Coffee to Javascript converter (paste in right box): <http://js2coffee.org/>
As per Ismael Miguel's comments, this method should work in IE 5.5+.
[Answer]
## Ruby functional, 67
```
puts ARGV[0].bytes.map.with_index(1){|b,i|b+i%255}.map(&:chr).join
```
Example:
```
$ ruby encrypt.rb password
=> qcvw|uyl
```
[Answer]
# Julia 51 (-4 if in place is allowed)
```
g(s)=([s.data[i]+=(i-1)%255+1 for i=1:length(s)];s)
g(s)=[s.data[i]+=(i-1)%255+1 for i=1:length(s)] # in place version
julia> g("a"^256) # ^ operator repeats strings
"bcdefghijklmnopqrstuvwxyz{|}~\x7f��������������������������������������������������������������������������������������������������������������������������������\0\x01\x02\x03\x04\x05\x06\a\b\t\n\v\f\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\e\x1c\x1d\x1e\x1f !\"#\$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`b"
```
[Answer]
## GolfScript, 27 characters
```
[.,,\]zip[{{+}*255%1+}/]''+
```
Hmmm...seems a bit long. Maybe I should stick to J.
[Answer]
## Haskell, ~~77C~~ 59C
```
import Data.Char
e s=h s 1
h""_=""
h(x:s)i=(chr(mod((ord x)+i)128)):h s(i+1)
```
v2
```
import Data.Char
e s = map chr(zipWith(+)(map ord s)[1..])
```
I am assuming that input doesn't need to be on STDIN.
Example run:
```
*Main> e "hello"
"igopt"
```
[Answer]
# Erlang: 60C
Not the smallest or prettiest, but this one can be run standalone in the command line.
Set T to your text.
```
{S,_}=lists:mapfoldl(fun(C,I)->{C+I,(I+1)rem 255}end,1,T),S.
```
Yields:
"qcvw|uyl"
[Answer]
# Rebol, 58 chars
```
s: input forall s[s/1: mod(index? s)+(to-integer s/1)256]s
```
[Answer]
**Groovy, 53 Characters**
```
i=0;args[0].chars.collect{(char)it+(++i%255)}.join()
```
[Answer]
# Ruby, ~~45~~ 39 bytes
```
gets.chars{|c|putc(c.ord+$.)%256;$.+=1}
```
[Answer]
# Perl, 54 char
```
$i=1;print map{chr((ord()+$i++)%256)}split//,$ARGV[0];
```
Example:
```
perl encrypt.pl password
> qcvw|uyl
```
[Answer]
# Dart, 68
```
f(s,{i=1})=>new String.fromCharCodes(s.runes.map((c)=>(c+i++)%255));
```
Example:
```
f('My secret password is 123456!');
> N{#wjiym}*{mv3}6HJLNPR>
```
] |
[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/4419/edit).
Closed 6 years ago.
[Improve this question](/posts/4419/edit)
I once hacked `upstart` on my Ubuntu box so that a colored, themeable ASCII Tux displayed on the screen with the boot messages scrolling beneath him. I'm curious to see what kind of ASCII art Linux Penguins you can come up with.
* It must fit in a 80 x 25 terminal, without using the bottom line (thus 80 x 24)
* Compact source code
* Bonus: use color
* Bonus: use variations on the standard Tux
**Edit**: As a clarification, by "compact source code" I meant smallest source code *per number of lines of output*. The answers so far have been good but it would be fun to get a diversity of penguins going.
[Answer]
## Many script languages, 6 UTF-8 bytes
It doesn't print ASCII art, but...
```
"üêß"
```
The character in the quote is the [unicode character penguin (U+1F427)](http://www.fileformat.info/info/unicode/char/1f427/index.htm) (if you want to see the penguin above, [download the Symbola font](http://users.teilar.gr/~g1951d/)). It looks like this (but a lot smaller):

[Answer]
Instead of attempting to print a given penguin, I hacked together a program to reduce ASCII art to a minimum production string in Python. I could do some crazy hacks with metaprogramming the environment to define variables for re-used strings, but this is good enough for now. It's Sunday, what can I say.
# ASCII compiler - 882 - Python
---
```
#!/usr/bin/env python
import sys, re
d = "".join(sys.stdin.readlines()) # get all text (WARNING... BIG INPUTS POSSIBLE)
d = re.sub(r' +[\r\n]','',d) # strip trailing spaces
i,j,c,o,f=0,0,d[0],"""#!/usr/bin/python
# -*- coding: UTF-8 -*-
print \"""",False # set up vars
while (i <= j) and (j < len(d)): # while the head cursor (j) is in bounds
if(d[j] == c): j+=1 # if we are in a repetition be gready
else:
if c == "\\": c = "\\\\" # generate repr()s of special case strings
elif c == "\n": c = "\\n"
elif c == "\r": c = "" # bump \n\r
elif c == "\"": c = "\\\""
if((j-i)-9 > 0): # if the sequence is long enough to justify a repetition
if(o): o += "\"+"
o += "\""+c+"\"*{0}+\"".format(j-i)
else: o += (c*(j-i)) # else just print the sucker
i = j
c = d[j]
o += "\"" # system assumes an open quote at all times, close it
print o
```
Usage: cat ./tux.txt | python ./encode.py
# My Tux - 1009 chars with spaces
---
```
..- - .
' `.
'.- . .--. .
|: _ | : _ :|
|`(@)--`.(@) |
: .' `-, :
:(_____.-'.' `
: `-.__.-' :
` _. _. .
/ / `_ ' \ .
. : \\ \
. : _ __ .\ .
. / : `. \
: / ' : `. .
' ` : : : `.
.`_ : : / ' |
:' \ . : '__ :
.--' \`-._ . .' : `).
..| \ ) : '._.' :
; \-'. ..: /
'. \ - ....- | '
-. : _____ | .'
` -. .'-- --`. .'
`-- --
```
# Compiled Tux - 878 - Python
---
```
print " "*20+"..- - .\n"+" "*19+"'"+" "*8+"`.\n"+" "*18+"'.- . .--. .\n"+" "*17+"|: _ | : _ :|\n"+" "*17+"|`(@)--`.(@) |\n"+" "*17+": .'"+" "*5+"`-, :\n"+" "*17+":("+"_"*5+".-'.' `\n"+" "*17+": `-.__.-' :\n"+" "*17+"` _."+" "*4+"_. .\n"+" "*16+"/ / `_ ' \\"+" "*4+".\n"+" "*15+". :"+" "*10+"\\\\ \\\n"+" "*14+". : _"+" "*6+"__ .\\ .\n"+" "*13+". /"+" "*13+": `. \\\n"+" "*12+": /"+" "*6+"'"+" "*8+": `. .\n"+" "*11+"' `"+" "*6+":"+" "*10+": : `.\n"+" "*9+".`_ :"+" "*7+":"+" "*10+"/ ' |\n"+" "*9+":' \\ ."+" "*6+":"+" "*11+"'__ :\n"+" "*6+".--' \\`-._"+" "*4+"."+" "*6+".' :"+" "*4+"`).\n"+" "*4+"..|"+" "*7+"\\ )"+" "*10+": '._.' :\n ;"+" "*11+"\\-'."+" "*8+"..:"+" "*9+"/\n '."+" "*11+"\\ - "+"."*4+"- |"+" "*8+"'\n"+" "*6+"-."+" "*9+": "+"_"*5+" |"+" "*6+".'\n"+" "*8+"` -."+" "*4+".'--"+" "*7+"--`. .'\n"+" "*12+"`--"+" "*16+""
```
**Edit 1**: Sadly, while this is efficient for large ASCII art files, as with many compression schemes its performance is lackluster to say the least when presented with very small inputs. The "standard" penguin featured thus far "compresses" to 100 chars of Python which while much better than Brainf\*ck is still nothing to brag about considering that the penguin itself is a mere 75 chars by my count.
**Edit 2**: Also as with many compression schemes the incremental gain is minimal. When I tested my compiler against several ASCII files I seem to get a mere 9-10% improvement over the source.
**Edit 3**: Re: kolmogorov complexity. After some quality time thinking and attempting to golf the base penguin, I have come to the conclusion that the optimal representation is 87 characters long, adding 12 to the actual penguin.
```
print """ .--.
|o_o |
|:_/ |
// \ \
(| | )
/'|_ _/'\
\___)=(___/"""
```
The python string repetition syntax for one character, say `"a"*5`, consumes `4+log10(n)` characters in the best case (non-special characters) and `5+log10(n)` for characters such as the newline or tab which require the string "\n" not a quoted single char. Therefor to achieve a compression greater than 0%, a character repetition greater than 9 characters in length must exist. `(assuming that the repetition is part of a substring which must be terminated with a quote and added to with + and restarted with the same symbols, thus adding 4 to the cost of a repetition)` A trivial examination of the penguin above reveals that no such string exists, therefore no compression is possible using string repetition and the best one can do is leverage the tripple quoted string syntax to represent newlines in one char not two.
**Edit 4**: Fixed edit 3 to reflect the relatively high probability of repetitions internal to some superstring, requiring a repetition like `"+'a'*15+"` which is of length `6+len(repr(a))-2+log10(n)`, updated compiler. (the -2 is required because repr() double-quotes everything)
**Edit 5**: Grabbed the ASCII art collection [HERE](http://www.roysac.com/roy_asciishow.asp), and threw together the BASH script below. Pulled a 12% compression average over the entire collection.
```
#!/bin/bash
l=$(find ./art/ -type f)
len=$(find ./art/ -type f | wc -l)
s=0
for i in $l; do
chars=$(cat $i | wc -c)
out=$(cat $i | python ./encode.py | wc -c)
c=$(calc "1-(($out-42)/$chars)" | sed s/'~'/''/g)
s=$(calc "$s+$c")
cat $i | python ./encode.py | python 2> /dev/null
echo -e "$i, $c\t|$?"
done;
echo $(calc "$s/$len")
```
**Edit 6**: Added the UTF-8 specification header to all compiler output and removed those chars from the test script's count because they are spec-required.
[Answer]
## Haskell - 14 characters
```
main=putStr"."
```
The penguin this program displays is in the far distance.
[Answer]
## brainfuck, 311 chars (44.4 sc/ol)
(where "sc/ol" stands for "source characters per output line")
```
++++++++++[>++++++>++++>++++>+>+++>+++++++++>++++++++++++>+++++++++++
<<<<<<<<-]>>>>>++....<<++++++.-..+.>.>...>>++++.>+.<<+++++.>>.<<<.>>.
<<<.>...>>.<<<<<<--.>>>>>.<<<+.>>.>>.<<<.>..<<..>>...>---.<.>.<<.>.<<
<.>>>>>.<<.....>>.<<.<<<+.>>.<.<--.>>>>>.<+++.<...>.<<<.<.>>>>---.<<.
>>.+++...<<<<++.<+++.>-.>>>>...<<<.
```
Same tux as CMP:
```
.--.
|o_o |
|:_/ |
// \ \
(| | )
/'|_ _/'\
\___)=(___/
```
I inserted CRs to get rid of the scrollbar, but I didn't count them.
It's most probably still not optimal. I leave the maths to someone else. It's all in the choice of initial numbers/characters (to save increments and decrements) and in which order to place them (to save pointer moves).
[Answer]
## Brainfuck - 378
```
++++[>++++++++<-]>[>+>++>+++>++++<<<<<+>-]<[>+<-]++++++++++
>....>++++++++++++++.-..+.<<.
>...>>>>----.-------------.<-.>.<<<<.>>>>+++++++++++++.<<<<<.
>...>>>>.<<------.>.<<+.<.>>>>.<<<<<.
>..>..<...>>>---.<<<.>>>.<<<<.
>.>-------.>>>.<<<<.....>>>>.<<<<.>+.<<.
>>++++++.<+++++++.>>>>.<+++.<<<-------...>>>.<<.<+++++++.>>>---.<<<<.
>>>>.+++...<<------.>+++.<-.>>...<<+++++++.<<.
```
Prints this:
```
.--.
|o_o |
|:_/ |
// \ \
(| | )
/'|_ _/'\
\___)=(___/
```
Hand coded from an image I found on wikipedia. Unfortunately I have no facility to provide color.
[Answer]
Try:
```
#!/bin/bash
sudo apt-get install cowsay
echo | cowsay -f tux.cow "Welcome"
```
This returns the exact same ascii as in the first answer.
[Answer]
This was inspired by @trinithis's answer with the small penguin in the distance. Getting a little closer, it appears he has turned to the side:
# Bash – 7 characters
```
echo \&
```
[Answer]
## Brainfuck - 446 (441 if omit `>>>>>.` which prints `\n`)
```
++++++++[>++++++>>++++>>>-------->+>++++<<<<<<<<-]>-[->+>>++>++>
++++<<<<<]>>.....>+......>>>++.<<<<....<.>......>>--.>>.>...<<.<
<<.<.>>>.<<..<.>>>.<<.>>>.>.>...<<.<<<...>..<...>>>.>.>...<<.<<<
..<.>..>>.>>>..<<.>.<<<<...<.>.<.>>....>.<<.>>.>>.<<<<..<.>.<.>>
>.<....<<.>>>.<<.>>.>>.<<<<.<.>.<.>........>>.<<.>>.>>.>.<<.>>.<
<.>>........<<.>>.<<.>.<<<<<.>.>>.>.>>........<<.<<<<.>.>>.>>.<.
<<<..>>.<........<<.>..>>>.>.<<.<...<<.>......>>.<...<<.>>>>>.
```
This prints
```
______
/ \
| /\ /\ |
| __ |
| / \ |
/ /____\ \
/ /\____/\ \
/ / \ \
| | | |
/ \| |/ \
| \________/ |
\___/ \___/
```
Therefore, it's `37.1667` (`36.75` if the code printing last `\n` is omitted) letters per line.
[Answer]
# PHP, 1 byte
Tux in a distance
```
.
```
Thanks to [original](https://codegolf.stackexchange.com/a/4467/67571) by [Thomas Eding](https://codegolf.stackexchange.com/users/1708/thomas-eding)
[Try it online!](https://tio.run/nexus/php#@6/3/z8A "PHP – TIO Nexus")
] |
[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/21465/edit).
Closed 9 years ago.
[Improve this question](/posts/21465/edit)
You are to post an answer you posted that exploited a loophole in the challengers question. Bonus points if it caused them to rewrite the question.
For example, one challenge was to write a program that such that if a random character is removed, it still works, and your score is how many characters it fails on. Some one posted the empty program, since then it would fail on no characters (though the compiler would fail) and the question had to be changed. He was unrightly down-voted, so I hope he sees this challenge.
This is a popularity contest, so whoever gets the most votes wins!
[Answer]
In my answer to [Loophole for other challenge](https://codegolf.stackexchange.com/questions/21465/loophole-for-other-challenge/21485#21485), I deliberately exploit the fact that the poster didn't specify that the answer had to be responding to another question. This made my answer recursive and self-referential.
I also golfed my answer (even though it was a popularity contest). 0 bytes of code.
[Answer]
[Render a version of the BBC Micro owl logo](https://codegolf.stackexchange.com/questions/19214/render-a-version-of-the-bbc-micro-owl-logo/19273#19273)
I used curl to grab the challenge page and outputted an answer posted by someone else.
[Answer]
In [Weirdest way to produce a stack overflow](https://codegolf.stackexchange.com/questions/21114/weirdest-way-to-produce-a-stack-overflow), i submitted an answer that opened a web browser and displayed stackoverflow.com.
[Answer]
In [Shortest Program to Sort a List of numbers into Odd and Even Category](https://codegolf.stackexchange.com/q/20139/8856), the question clearly states:
>
> ... The Size of the program is the size of the body of the function, i.e. excluding the size of the function signature.
>
>
>
I thought, "Why such a bizarre and specific rule?" And as I was trying to golf down my initial submission, it dawned on me--default parameter values! According to the [language spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-function-definitions), they're definitively not part of the function body, so I went ahead and submitted [my final solution](https://codegolf.stackexchange.com/a/20396/8856): a function whose body is a single character. That *must* have been what the OP wanted!... right?...
Needless to say, it did not win. :/
After accepting another answer, the challenger did eventually add a footnote as to why the one-character solution wasn't considered. The rules of the challenge, however, still remain unchanged (as of the time of this post). So, in the strictest interpretation of the rules, who would *you* say actually won? ;]
[Answer]
In [Write a hash function for Morse Code](https://codegolf.stackexchange.com/questions/19727/write-a-hash-function-for-morse-code/19745#19745), the OP didn't specifically exclude negative or floating point values which are entirely usable as hashes. Using this loophole, I was able to get a better than "perfect" score of 236. There was much griping, but the OP never changed the question, despite promising to, and the loophole was subsequently exploited by almost every other poster!
[Answer]
In the question <https://codegolf.stackexchange.com/questions/21391/output-with-1-on-stdout-using-a-0-byte-source-code>, it states that it will give a bonus of -500 bytes if we output '1' to the console using a source-code file which is 0 bytes long.
My answer is [this](https://codegolf.stackexchange.com/questions/21391/output-with-1-on-stdout-using-a-0-byte-source-code/21397#21397) one and 'abuses' the null devices in windows and linux.
The question wasn't rewritten, but this answer gave me a pretty big hole to go to the gold (the -500 byte bonus). Why? Because the null devices have ALWAYS 0 bytes in size and are guaranteed to exist!
[Answer]
Quoting [this question](https://codegolf.stackexchange.com/questions/20996/add-without-addition-or-any-of-the-4-basic-arithmetic-operators):
>
> Your goal is to add two input numbers without using any of the following math operators: +,-,\*,/.
>
>
> Additionally, you can't use any built-in functions that are designed to replace those math operators.
>
>
>
I posted [this answer](https://codegolf.stackexchange.com/a/21029/3755), it was not very popular though. Quoting from my answer:
>
> And, as suggested by @Ismael Miguel (althought he was not exactly suggesting this), by really abusing the rules underspecification, we can note that only +, -, \* and / operators were forbidden, but += was not, so it is allowed (it is not a built-in function either, since it is not even a function). This way, we can express the instruction with just 4 characters (and it will always work with negatives and non-integers too for both values):
>
>
>
```
y+=x
```
[Answer]
In the same question that @Victor refered ([Add without addition (or any of the 4 basic arithmetic operators)](https://codegolf.stackexchange.com/questions/20996/add-without-addition-or-any-of-the-4-basic-arithmetic-operators)), i gave [this](https://codegolf.stackexchange.com/questions/20996/add-without-addition-or-any-of-the-4-basic-arithmetic-operators/21035#21035) asnwer.
Basicly it "ABUSES" the Javascript internal casting to integer of the boolean values.
---
And This question itself exploits a loophole: there is NOTHING saying we can't refer to the same question in the answers. Or the number of answers. Or the number of answers from the same question.
] |
[Question]
[
The Riemann R function is as follows:
$$R (x)=\sum \_{n=1}^{\infty } \frac{\mu (n) \text{li}\left(x^{1/n}\right)}{n}.$$
This uses the [Möbius function](https://en.wikipedia.org/wiki/M%C3%B6bius_function) as well as the [logarithmic integral](https://en.wikipedia.org/wiki/Logarithmic_integral_function).
From Wikipedia, the Möbius function is defined so that for any positive integer \$n\$, \$μ(n)\$ is the sum of the primitive nth roots of unity. It has values in \$\{−1, 0, 1\}\$ depending on the factorization of \$n\$ into prime factors:
* \$μ(n) = +1\$ if \$n\$ is a square-free positive integer with an even number of prime factors.
* \$μ(n) = −1\$ if \$n\$ is a square-free positive integer with an odd number of prime factors.
* \$μ(n) = 0\$ if \$n\$ has a squared prime factor.
The logarithmic integral is defined as:
$$\operatorname{li}(x) = \int\_2^x \frac{dt}{\log t}.$$
An alternative way to compute the Riemann R function is via the [Gram series](https://math.stackexchange.com/questions/1506980/could-someone-explain-how-the-gram-series-relates-to-riemanns-function). That is:
$$R(x) = 1 + \sum\_{k=1}^{\infty}\frac{(\ln x)^k}{k k!\zeta(k+1)}.$$
The function \$\zeta()\$ is the [Riemann zeta function](https://codegolf.stackexchange.com/questions/119596/calculate-the-value-of-zetas?rq=1).
# Challenge
Write code that computes \$R(x)\$ for \$x\$ up to \$10^{31}\$. The output may have a margin of error of up to 1.
# Test cases
Here are the answers for \$10^i\$ for \$i = \{1, 2, \dots, 31\}\$.
```
1 4.56458314100509023986577469558
2 25.6616332669241825932267979404
3 168.359446281167348064913310987
4 1226.93121834343310855421625817
5 9587.43173884197341435161292391
6 78527.399429127704858870292141
7 664667.447564747767985346699887
8 5761551.86732016956230886495973
9 50847455.4277214275139488757726
10 455050683.306846924463153241582
11 4118052494.63140044176104610771
12 37607910542.2259102347456960174
13 346065531065.82602719789292573
14 3204941731601.68903475050075412
15 29844570495886.9273782222867278
16 279238341360977.187230253927299
17 2623557157055978.00387546001566
18 24739954284239494.4025216514448
19 234057667300228940.234656688561
20 2220819602556027015.40121759224
21 21127269485932299723.733864044
22 201467286689188773625.159011875
23 1925320391607837268776.08025287
24 18435599767347541878146.803359
25 176846309399141934626965.830969
26 1699246750872419991992147.22186
27 16352460426841662910939464.5782
28 157589269275973235652219770.569
29 1520698109714271830281953370.16
30 14692398897720432716641650390.6
31 142115097348080886394439772958.0
```
Your code doesn't need to be fast, but ideally it should complete in under a minute.
# Related challenges
* [Möbius function](https://codegolf.stackexchange.com/questions/69993/the-m%C3%B6bius-function?noredirect=1&lq=1)
* [Riemamn zeta function](https://codegolf.stackexchange.com/questions/119596/calculate-the-value-of-zetas?rq=1)
---
# Precision
You will need 128 bit floats to represent the output. In C `__float128` from `quadmath.h` is the simplest way (`long double` will most likely be 80 bits). Other languages may have standard libraries to support 128 bit floats (e.g Decimal in Python). [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenges are judged *per language* so there is no penalty in using whatever is needed for your favorite langauge.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 8 bytes
```
RiemannR
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PygTyMnLC/ofUJSZV@KQ5mBokGBpyYXgoXNR@Bpg1XHGhpr/AQ "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 40 bytes
```
x->1+suminf(k=1,log(x)^k/k/k!/zeta(k+1))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWNzUqdO0MtYtLczPz0jSybQ11cvLTNSo047L1gVBRvyq1JFEjW9tQUxOqXjctv0gjT8FWwVBHwRiIC4oy80o0lAwN4pQU8hSUFHTtgESaBpCfpwnTtGABhAYA)
Using the [Gram series](https://math.stackexchange.com/q/1506980/99103).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~193 183 173 165 154~~ 145 bytes
```
typedef _Float128 X;X logq();i,k;r(X x,X*y){for(X a=*y=k=1,q;k<187;*y-=(ldexp(a*=logq(x)/k++,-k)-a)/q)for(i=23,q=0;--i;)q+=(i%2?k:-k)*pow(i,~k);}
```
[Try it online!](https://tio.run/##NY5NT4QwEIbv/IrJGkyntLtbOLixVG/evXEwmoavbcpXESNkgz9dBBJPM5P3fSZPyss0XZZh6vIsL@DjpWr1IMILJDKBqi0dQWmYlT1JYGQJnfBWtNuhFZ2UVYI5aWNxeZB04opUWT52RFO1oyOebBAwbpFrPDncSKPCiDl1lpwbiS5QxPjhs31cS7Rrv4lhPxblvNyZumv7IXZfOqv1cD1en7xam4bgzYP9UTOAUUKaOAqlCQKENQBIYJLb7Mlq4oihu4k4IzK4n3DPun6FC3IQ53c/A/8Yha/FW3NghsHemL15@U2LSpefC6/@Dda1/gM "C (gcc) – Try It Online")
This estimates the Riemann R function from the Gram series. Note that this uses a horribly obfuscated but faster converging implementation of the Riemann zeta function.
$$\zeta(s)=\frac{1}{1-2^{1-s}}\sum\_{n=1}^{\infty}\frac{(-1)^{n+1}}{n^s}$$
-1 thanks to @Simd. -8 thanks to @c--.
Slightly golfed less:
```
typedef _Float128 X;
X logq();
i,k;
r(X x,X*y){
for(X a=*y=k=1,q;k<200;){
/* estimate the Riemann zeta function */
for(i=99,q=0;--i;)
q+=(i%2?k:-k)*pow(i,~k);
*y-=(ldexp(a*=logq(x)/k++,-k)-a)/q
}
}
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 44 bytes
```
Þ∞KƛƛÞ∞K$›eĖṠ2l≬₈vḞ≈c*n¡*?∆Lne$/;∑;2l≬₈vḞ≈c›
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnuKInkvGm8abw57iiJ5LJOKAumXEluG5oDJs4oms4oKIduG4nuKJiGMqbsKhKj/iiIZMbmUkLzviiJE7Mmziiazigoh24bie4omIY+KAuiIsIiIsIjEwIl0=)
I think this is correct. [Might be 38 if there's an exact limit convergance somehow](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnuKInkvGm8abw57iiJ5LJOKAumXEluG5oDJs4oG94omIYypuwqEqP+KIhkxuZSQvO+KIkTsybOKBveKJiGPigLoiLCIiLCIxMCJd).
Precision is met by having a) things evaluated to 256 decimal places when approximating and b) exact values used until an approximation is needed. Good luck getting this to return an actual answer in the time we have left in the universe. The algorithm should be correct though.
## Explained
The main idea to find the sums of things with an infinite upper bound is to check every overlapping pair of items in an infinite list of the sum applied from `1..1`, `1..2`, `1..3`, and so on until the pair has all the same items. This is basically checking for convergence manually.
```
Þ∞Kƛ...;2l≬₈vḞ≈c›
Þ∞Kƛ ; # Calculate the gram series for all possible upper bounds
2l # get all the overlapping pairs
≬₈vḞ≈c # and get the first where the items to 256 decimal places are the same
› # increment
```
```
ƛÞ∞K$e›ĖṠ2l≬₈vḞ≈c*n¡*?∆Lne$/;∑ # Note that the context variable is set to whatever number in a prefix in the prefix is being gram seriesed is being zeta'd
Þ∞K # To each prefix of an infinite list of positive integers
$e›ĖṠ2l≬₈vḞ≈c # Zeta function
* # times k
n¡* # times k!
?∆Lne$/ # log(input) ** k divided by above
;∑ # sum the result of apply to each k
```
```
$e›ĖṠ2l≬₈vḞ≈c # the top of the stack is the prefix list
$e› # each number in each prefix to the power of k + 1
Ė # reciprocal of each number in each prefix
Ṡ # sum of each prefix
2l # overlapping pairs of sums
≬₈vḞ≈c # first item where pair is all the same to 256 decimal places.
```
[Answer]
# [Python](https://www.python.org) + [SymPy](https://SymPy.org), ~~103~~ 99 bytes
```
lambda x:1+Sum(ln(x)**k/k/gamma(k+1)/zeta(k+1),(k,1,oo)).evalf(50)
from sympy import*;k=Symbol('k')
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY27boMwFED3fsXdfK_jAKaqVKViz85aRXISTFy_kDEV9Fe6IEXtP_VvOpDpnOmc799hybcY1rtu3n-mrPevfxen_PmqYD7IXTt5dAFn4tyWtuyV9wrtTlL51eXNBFohRYxERfepnMaXip50ih7GxQ8LGD_ElPmbbdrFn6NDZhk9VkcdExgwAZIKfYdSPNd0GJIJGZlGkBWcmBhzQkOF-5jGjLVgwEgwgoYJjbLi3NCjt64b_wE) Takes ~30s on ATO for all 31 test cases.
* Thanks to Simd for posting [this chat message](https://chat.stackexchange.com/transcript/message/62679526#62679526)
* -4 thanks to ceilingcat
[Answer]
# [Julia](https://julialang.org), ~~141 138 133 125~~ 81 bytes
```
h(x,a=big(1.))=1-sum(k->(a*=log(x)/k)/sum(n->(-1)^n/n/n^k,1:99)/k*(1-2^-k),a:200)
```
-44 thanks to @MarcMush
[Try it online!](https://tio.run/##FYlBDsIgEADvfQXH3QaEraeS4MGDzyDBqBShYGqb8HvEmdvM@0jBUW1tgcqduQcPdEI0JL7HClFcwI0mFQ8VZUT5j7lHQWiz7NrISc9znyOQmKyIyJ2elML2KhsLhvSZBtb5bCHvKQNbgJS9Bn9Lxe0QEBkOz/xoPw "Julia 1.0 – Try It Online")
Slightly less golfed.
```
function h(x)
B=BigFloat
a=y=B(1);
for K=1:200
q=0;
k=B(K);
for n=1:99
q-=(-1)^n/n/n^k
end;
a*=log(x)/k;
y+=a/q/k*(1-2^-k)
end;
y
end
```
# [Julia](https://julialang.org) using zeta() builtin, ~~209~~ 205 bytes
```
using Base.MPFR
function h(x)B=BigFloat;a=y=B(1);for K=1:187 k=B(K);a*=log(x)/k;z=B();ccall((:mpfr_zeta,:libmpfr),Int8,(Ref{BigFloat},Ref{BigFloat},Int8),z,k+1,Base.MPFR.ROUNDING_MODE[]);y+=a/k/z end;y end
```
[Try it online!](https://tio.run/##VY9LC8IwEITv/RU5ZjVYgwelIZfiAxEfFDyJSqxtjY2p1BRsxd9ek4OCe1iYYdj95lopKeizbauH1BkKxSPpLTfTyEsrHRtZaHTBTwh5KLOpKoRhgtc8xBRYWpRowWlAR0OUW2sBTHS4KjKb93PWWAtYHAulMA5u97Q8NokRJFDy5BSQuTYjgqMkfX2Pv8m/cgkgDcm7lPzIetF6uxrPV7Pjcj2e7PbA6i4Xfu43KNFnVrvdOjhp4QbUQ3bupdRGaWzL0P7h@wBLAASey38A "Julia 1.0 – Try It Online")
Slightly golfed less.
```
using Base.MPFR
function h(x)
B=BigFloat;
a=y=B(1);
for K=1:187
k=B(K);
a*=log(x)/k;
z=B();
ccall((:mpfr_zeta,:libmpfr),Int8,(Ref{BigFloat},Ref{BigFloat},Int8),z,k+1,Base.MPFR.ROUNDING_MODE[]);
y+=a/k/z
end;
y
end
```
[Answer]
# [Python](https://www.python.org) + [mpmath](https://mpmath.org/), 28 bytes
```
from mpmath import*
riemannr
```
[Attempt This Online!](https://staging.ato.pxeger.com/run?1=NY5BCsIwEEX3OcXsmoRakgoigjcRIWBrR8wkTKYLz-KmGz2FF_E2FkuX__F5_z_f-SFDoml6jdJv9p-eU4SYY5ABMObEYhVjFwMRL5XvKebmkgscYedUnxgQkIADXTvt621rDgogM5Loyjs4V_WcoQhrNM39NhbRrfmzVay9sxbNjMyysd75AQ)
## Not using the builtin, 84 bytes
```
from mpmath import*
f=lambda x:1+nsum(lambda k:log(x)**k/k/fac(k)/zeta(k+1),[1,inf])
```
[Attempt This Online!](https://staging.ato.pxeger.com/run?1=NY9LCsIwFEXnXcWb-RJr2yiIFLoLHYlC_MTGNB_SV6huxUknuid3o0id3XMHB87jFW5UezcMz47UbPVeq-gt2GAl1aBt8JF4oqpG2sNJQl-KqWs7iyObsvEX7BnnJje5kkc0LL-fSaKZCpZuRaqd2rHRvbEhO4UWKlgWifIRNGgHUbrLGUW6mLMyAQhRO8KJKGA_Sb8MLUXULGuuXUs4Z79PoSg41-y7R_k_4AM)
[Answer]
# APL(NARS), 350 chars
```
r←p z q;n;t;w;m;d;y;h;e
→2×⍳∼q=1⋄r←∞⋄→0
t←qׯ1v⋄r←0J0⋄e←÷10x*p⋄n←0v
→7×⍳e>w←÷2*n+1
y←d←1v⋄h←n+1⋄m←0v
h-←1⋄y+←(t*⍨m+1)×d×←¯1×h÷m+←1⋄→5×⍳m<n
r+←w×y⋄n+←1⋄→3
r÷←1-2*1+t
r←p R q;L;n;d;m;e;y
y←q×1v⋄r←1v⋄L←⍟y⋄n←0⋄d←1v⋄e←÷10x*p
r+←m←(÷n×11○¯11○p z n+1)×d×←L÷n+←1⋄→2×⍳e<∣m
⎕fpc←128
F←{0⌈(⌊1+10⍟⍵)-⍨⌊3.322÷⍨⎕fpc-1}
⍪{{⍵⍕⍨1⌈¯8+F⍵}(¯7+⌊3.322÷⍨⎕fpc-1)R⍵}¨10*1..31v
23+15+27+14+17+37+14+10+7 + 19+34+43+2+9+32 +47= 350
```
`z` should be the Riemann Zeta function that stop calc until `p` digits
after the decimal point, with output one complex number.
`R` should be the Riemann R function that stop calc until `p` digits
after the point.
It seems:
1. `⎕fpc` it is the lenght in bit of the float point number of type "NumbeRv"
2. `⌊1+10⍟⍵` it should be the lenght in decimal digit of the integer part of number in `⍵`
3. `⌊3.322÷⍨⎕fpc-1` it should be the lenght in decimal digit of each float type "NumbeRv"
4. `F ⍵` it should be the max lenght in decimal digit of fractional part number in `⍵` so it is the right place where end the computation
5. It seems is asked ¯8+ teoretical possible 128 bit precision for show the number
```
⍪{{⍵⍕⍨1⌈¯8+F⍵}(¯7+⌊3.322÷⍨⎕fpc-1)R⍵}¨10*1..31v
```
4.56458314100509023986577469558
25.6616332669241825932267979404
168.359446281167348064913310987
1226.93121834343310855421625817
9587.43173884197341435161292391
78527.3994291277048588702921410
664667.447564747767985346699888
5761551.86732016956230886495974
50847455.4277214275139488757726
455050683.306846924463153241582
4118052494.63140044176104610771
37607910542.2259102347456960174
346065531065.826027197892925730
3204941731601.68903475050075412
29844570495886.9273782222867278
279238341360977.187230253927299
2623557157055978.00387546001566
24739954284239494.4025216514448
234057667300228940.234656688561
2220819602556027015.40121759224
21127269485932299723.7338640440
201467286689188773625.159011875
1925320391607837268776.08025287
18435599767347541878146.8033590
176846309399141934626965.830969
1699246750872419991992147.22186
16352460426841662910939464.5782
157589269275973235652219770.569
1520698109714271830281953370.16
14692398897720432716641650390.6
142115097348080886394439772958.2
you have to note is possible find some other digits right other than below
numbers for 128 bit float
```
⍪{{⍵⍕⍨F⍵}(⌊3.322÷⍨⎕fpc-1)R⍵}¨10*⍳2v
4.5645831410050902398657746955840498096
25.661633266924182593226797940355698151
```
it is possible change the number of bit of float
```
⎕fpc←64
⍪{{⍵⍕⍨F⍵}(⌊3.322÷⍨⎕fpc-1)R⍵}¨10*⍳3
4.56458314100509024
25.6616332669241826
168.359446281167348
```
] |
[Question]
[
Given *N* items (0 < *N* <= 50) with prices (which are always integers) *P0* ... *PN-1* and given amounts of each item *A0* ... *AN-1*, determine how much the total cost will be.
### Examples
*N*: 2
*P0*: 2
*P1*: 3
*A0*: 1
*A1*: 4
Result: 14
*N*: 5
*P0*: 2
*P1*: 7
*P2*: 5
*P3*: 1
*P4*: 9
*A0*: 1
*A1*: 2
*A2*: 3
*A3*: 2
*A4*: 3
Result: 60
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins.
### Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=95128,OVERRIDE_USER=12537;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# [Actually](http://github.com/Mego/Seriously), 1 byte
```
*
```
[Try it online!](http://actually.tryitonline.net/#code=Kg&input=Miw3LDUsMSw5CjEsMiwzLDIsMw)
Okay, this is the shortest dot product built-in I could find. >\_>
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 2 bytes
```
æ.
```
[Try it online!](http://jelly.tryitonline.net/#code=w6Yu&input=&args=Miw3LDUsMSw5+MSwyLDMsMiwz)
A built-in computing the dot product between two input vectors: if, for each **1 ≤ i ≤ n**, we buy **ai** items worth **pi** each, the formula for the total cost is **a1p1 + a2p2 + … +anpn**, which is precisely the definition of the dot product.
[Answer]
# Mathematica, 1 byte
```
.
```
# Usage:
```
{1, 2, 3}.{4, 5, 6}
(* 32 *)
```
[Answer]
# TI-Basic, 12 bytes
```
Prompt L1,L2
sum(L1L2
```
[Answer]
## Haskell, 17 bytes
```
(sum.).zipWith(*)
```
Multiply the lists entrywise, then sum. Shorter than importing (23 bytes)
```
import Data.Vector
vdot
```
[Answer]
# Python, ~~36~~ 33 bytes
```
lambda*x:sum(map(int.__mul__,*x))
```
*Thanks to @xnor for golfing off 3 bytes!*
Test it on [Ideone](http://ideone.com/5ZuzRo).
[Answer]
# Ruby, ~~34~~ 23 + 9 = 32 bytes
+9 bytes for `-rmatrix` flag.
```
->p,a{Vector[*p].dot a}
```
See it on eval.in: <https://eval.in/653676>
[Answer]
# Pyth, 3 bytes
```
s*V
```
(s)ums the (V)ectorized (\*)product of the two input arrays.
[Answer]
# MATLAB / Octave, 4 bytes
```
@dot
```
This defines an anonymous function.
[Try it at Ideone](https://ideone.com/auIj3a).
[Answer]
# C#, 25 bytes
```
p.Zip(a,(x,y)=>x*y).Sum()
```
Sample program:
```
using System.Linq;
using Xunit;
public class Tests {
[Fact]
public void Cost() {
int[] p = new [] { 2, 7, 5, 1, 9 };
int[] a = new [] { 1, 2, 3, 2, 3 };
int r = p.Zip(a, (x, y) => x * y).Sum();
Assert.Equal(60, r);
}
}
```
[Answer]
# R, ~~8~~ 18 bytes
```
sum(scan()*scan())
```
Now takes input from stdin.
[Answer]
# [Julia 1.0](http://julialang.org), 13 bytes
Building up on Donat's [solution](https://codegolf.stackexchange.com/a/220631/101725). Thanks to Chartz Belatedly for pointing out the issue with inputs
```
x/y=sum(x.*y)
```
[Try it online!](https://tio.run/##yyrNyUw0rPifaBttaG1kbRzLlWQbbWJtam0Wy5WmUaFTqWn7v7g0V6NCT6tS83@aRqJOkmaNXUFRZl5JTt5/AA "Julia 1.0 – Try It Online")
[Answer]
# [MATL](http://github.com/lmendo/MATL), 2 bytes
```
*s
```
[Try it online!](http://matl.tryitonline.net/#code=KnM&input=WzIgNyA1IDEgOV0KWzEgMiAzIDIgM10)
```
* % Element-wise product of two implicit inputs
s % Sum of array, implicitly displayed
```
[Answer]
# Java, 67 bytes
```
a->{int p=0;for(int i=-1;++i<a[0];)p+=a[i+1]*a[i+a[0]+1];return p;}
```
Slightly ungolfed:
```
public static int pay(int...a){
int p=0;
for(int i=-1;++i<a[0];){
p+=a[i+1]*a[i+a[0]+1];
}
return p;
}
```
[Answer]
# [Perl 6](https://perl6.org), 13 bytes
```
{[+] [Z*] $_}
```
Input is a list of two lists
## Example:
```
say {[+] [Z*] $_}( ((2,7,5,1,9),(1,2,3,2,3)) );
# 60
```
## Explanation:
```
{ # bare block lambda with implicit parameter 「$_」
[+] # reduce using addition operator
[Z*] # reduce using zip meta-operator combined with multiplication operator
$_ # the argument ( list of lists )
}
```
[Answer]
# TI-BASIC, 3 tokens
```
sum(L₁L₂
```
Input in `L₁` and `L₂`, output in `Ans`.
Usage:
```
{1,2,3→L1
{4,5,6→L2
prgmCOST
```
Output: `32`
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
øPO
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8I4A////o6ONdBTMdRRMdRQMdRQsY3UUooE0UMwYQsbGAgA "05AB1E – Try It Online")
```
øPO # full program
O # sum of...
P # products of...
# (implicit) each element in...
# implicit input...
ø # with each element from the first sublist paired with the corresponding element from the second sublist
# implicit output
```
[Answer]
# [R](https://www.r-project.org/), 5 bytes
```
`%*%`
```
[Try it online!](https://tio.run/##K/qfZvs/QVVLNeF/moaRlbFOsoahjommJleaRrKGkY65jqmOoY6lJkgYKAlUoKn5HwA "R – Try It Online")
That's the dot-product built-in in R...
[Answer]
# JavaScript, 33 bytes
```
a=>b=>a.reduce((c,d,e)=>c+d*b[e])
```
Takes input as `([p[0],...,p[n-1])([a[0],...,a[n-1]])`.
[Answer]
# C, ~~58~~ 56 bytes
```
f(n,p,a,s)int*p,*a;{for(s=0;n;s+=p[--n]*a[n]);return s;}
```
Input is n: number of elements, p:array 1, a:array 2.
Somewhat un-golfed:
```
f(n,p,a,s)
int*p,*a;
{
for(s=0;n;s+=p[--n]*a[n]);
return s;
}
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 3 bytes
```
+.× ⍝ My code is self-documenting
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud/UR20TjBTMFUwVDBUstfUOTzdUMFIwBuH//wE "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `s`, 1 byte
```
*
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=*&inputs=%5B3%2C2%5D%0A%5B4%2C1%5D&header=&footer=)
Magic.
[Answer]
# PHP, 46 Bytes
```
<?foreach($_GET[a]as$n)$s+=$n[0]*$n[1];echo$s;
```
48 Bytes
```
<?=array_sum(array_map(array_product,$_GET[a]));
```
[Answer]
# [Julia 1.0](http://julialang.org/), 14 bytes
```
sum((*).(x,y))
```
[Try it online!](https://tio.run/##yyrNyUw0rPifaBttaG1kbRzLlWQbbWJtam0Wy5WmUaFTqWn7v7g0V0NDS1MPzNX8X1CUmVeSk6eRppGokwTkAwA "Julia 1.0 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 43 bytes
```
function d($a,$b){$a|%{$r+=$_*$b[$i++]};$r}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/P600L7kkMz9PIUVDJVFHJUmzWiWxRrVapUjbViVeSyUpWiVTWzu21lqlqPZ/ioKGoZ6esaaChomenpnmfwA "PowerShell – Try It Online")
Basically, just calculate the dot product.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 36 bytes
```
param($p,$q)$p|%{$r+=$_*$q[$i++]}
$r
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkqZgq1D9vyCxKDFXQ6VAR6VQU6WgRrVapUjbViVeS6UwWiVTWzu2lkul6H8tF5caUL2RjrGCoY4JlG2uY6pjqGMJFAGKg/B/AA "PowerShell – Try It Online")
[Answer]
# [BQN](https://github.com/mlochbaum/BQN), 3 bytes
```
+´×
```
[Try it!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkHsrwrTwnZWpw5fwnZWofQoy4oC/MyBGIDHigL80)
dot product
[Answer]
# [Zsh](https://www.zsh.org/), ~~31~~ 25 bytes
[Try It Online](https://tio.run/##qyrO@J@RX55bmpyhoVnNVZpXnFqiEKyQ9T8tv0ghU0FDpUBTQyNY2zZTKzFaWzsrVlPzfy1Xnq2RdYGthpGCsaZ1oq2GoYKJpjXUEOvU5Ix8BZVgoBpTiBpzBVMFQwVLqEqgHgWwPjT1/wE). ~~[old 31 bytes](https://tio.run/##qyrO@J@RX55bmpyhoVnNVZpXnFqiEPw/Lb9IIVNBo9pQT08lr1ZTQyNY27YgOjNWKxFIaGr@r@XKszWyLrDVMFIw1rROtNUwVDDRtIYaZJ2anJGvoBIMVGMKUWOuYKpgqGAJVQnUowDWh6b@PwA)~~
```
for i ($p)((S+=i*a[++j]))
```
This is the core function. The challenge didn't say anything about setting up variables or output so that's all external.
] |
[Question]
[
Write a program that checks if a given positive integer can be represented as sum of two or more consecutive positive integers.
### Example:
43 can be represented as 21 + 22
10 = 1+2+3+4
but 4 cannot be represented in this way.
**Input spec:** positive integer (as argument or stdin)
**Output spec:** truthy or falsy
### Sample i/o
```
43 -> true
4 -> false
```
Shortest code wins.
[Answer]
## JavaScript (31)
```
alert(!!((n=~~prompt())&(n-1)))
```
From my testing, I believe this gives correct solutions.
<http://jsfiddle.net/3e9FZ/>
**Edit**: (SPOILER ALERT!) Here is the justification for this answer:
1. All odd numbers greater than 1 can be trivially written as the sum of two consecutive numbers (ex 15 = 7+8, 23=11+12, etc.).
2. For even numbers having an odd factor where the odd factor is less than twice the even factor. For example, 4\*7, because 7 < (2\*4 = 8). Simply add 7 numbers with 4 at the center, 1+2+3+4+5+6+7.
3. For even numbers having an odd factor where the odd factor is more than twice the even factor. For example, 4\*9, because 9 > (2 \* 4 = 8). Double the even factor, and halve the odd factor to get 8\*4.5. You will add the 8 numbers centered at 4.5, i.e., 1+2+3+4+5+6+7+8.
4. The only numbers left are the even numbers having no odd factor, i.e., the powers of two. The formula for the sum of a consecutive set of numbers is (avg \* count). Now if the count is odd, then avg is a whole number, and (avg \* count) has an odd factor. If count is even, then avg must be #.5, and thus avg \* 2 is odd, and so avg \* count has an odd factor. Therefore, any sum using the formula (avg \* count) must have an odd factor, which powers of two do not, and therefore have no solution.
[Answer]
### Golfscript, 20 chars
```
~.(&!!"falsetrue"5/=
```
Someone had to.
[Answer]
# Ruby (23)
only 3 chars longer than golfscript :)
```
p 0<(n=$*[0].to_i)&n-1
```
output:
```
$ ruby gc2958.rb 4
false
$ ruby gc2958.rb 43
true
$ wc gc2958.rb
1 2 23 gc2958.rb
```
[Answer]
## Haskell, 74
Felt like doing the brute force way.
```
import List
main=print.f=<<readLn
f n=elem n$map sum$tails=<<inits[1..n-1]
```
[Answer]
## JavaScript (81)
```
n=prompt(r=i=1)|0;while(r&++i*i/2<n)if(i%2&!(n%i)|!(i%2|(n+i/2)%i))r=!r;alert(!r)
```
I'm cheating with `&` and `|` - even though they are technically bit-wise operations, they do the job quite nicely because the result is a 1/0 which are valid conditionals!
<http://jsfiddle.net/HCqK2/4/>
[Answer]
## C, 67
As mellamokb suggested all numbers, except powers of two, can be written as sum of positive consecutive numbers:
```
main(int i,char**a){
printf((i=atoi(a[1]))&i-1?"true\n":"false\n");
}
```
[Answer]
## C
return 1 or 0:
```
int i(int j){return((j%2)?!(j==1):i(j/2));}
```
[Answer]
# Mathematica, 23 bytes
```
N[2~Log~#]~MatchQ~_Real
```
For once it's actually useful
[Answer]
# TI-Basic, 6 bytes
```
fPart(logBASE(Ans,2
```
Operating system ≥2.53 required due to `logBASE(`. Without logBASE, there are alternatives:
```
7 bytes: fPart(ln(Ans)/ln(2
7 bytes: fPart(log(Ans)/log(2
```
[Answer]
# Befunge-93, 28 bytes
[Try it Online!](http://befunge.tryitonline.net/#code=JnZALjE8QC4wPAo6PC8yX14jIV9eIy0xXCUyOg&input=NDM)
```
&[[email protected]](/cdn-cgi/l/email-protection)<@.0<
:</2_^#!_^#-1\%2:
```
Instead of checking if the given integer is an element in [this sequence](http://oeis.org/A138591), it's much easier to check if it isn't in the [complimentary sequence](http://oeis.org/A155559) (powers of 2 with 0 instead of 1). This functions very similarly to mellamokb's answer in that sense.
Note that the linked sequences are not exact representations of all truthy/falsey results of each integer, because the sequence uses non-negative integers instead of strictly positive. Thus, 1 *is* in the linked sequence, even though for this specific problem it should be in its compliment.
[Answer]
# [Wren](https://github.com/munificent/wren), ~~18~~ 17 bytes
Umm, it's shorter than GolfScript...
```
Fn.new{|n|n&-n<n}
```
[Try it online!](https://tio.run/##Ky9KzftfllikkKhgq/DfLU8vL7W8uiavJk9NN88mr/Z/cGVxSWquXnlRZkmqRqJecmJOjoaJqabmfwA)
[Answer]
# Python 2 REPL, 24 chars
Shortest python atm, borrowing `bin()` from @Fraxtil :)
```
bin(input()).count('1')>1
```
[Answer]
# Python 2 REPL, 19 17 16
```
x=input()
x>x&-x
```
[Answer]
## Python 3 REPL, 34
```
bool(int(bin(2*int(input()))[3:]))
```
I took an alternative approach to the solution, but can't seem to squeeze anything else out of it. This code takes the input, multiplies it by two (this fixes the input case of `1` which breaks otherwise), converts it to binary, strips out the first 3 characters (`0b1`), converts the remainder to an integer (which is 0 iff the input was a power of two), and then converts that to a boolean.
As mentioned above, you can remove the `2*` to get a 32-char solution that fails on an input of `1` but is otherwise perfect.
[Answer]
# [Dyalog APL](https://www.dyalog.com/products.htm), 7 bytes
```
0≠1|2∘⍟
```
Checks if a number is not a power of 2.
[Attempt This Online!](https://ato.pxeger.com/run?1=m70qpTIxJz89PrEgZ8GCpaUlaboWux_1TX3UNkHD4FHnAsMao0cdMx71ztc8tMLEWMEEogKqEKYBAA)
```
2∘⍟ log base 2 of
1| mod 1
0≠ is not zero
```
My 14-byte brute-force attempt before learning that the question is equivalent to asking if a number is not a power of 2:
```
⊢∊∘∊1↓+/¨∘⊂⍥⍳⍨
```
Using 3 as an example:
```
⍨ put the argument on both sides: 3 ... 3
⍥⍳ integers from 1 to n on both sides: 1 2 3 ... 1 2 3
+/¨∘⊂ sums of length-1, 2, and 3 windows in 1 2 3: (1 2 3)(3 5)(6)
1↓ drop the length-1 sums
∊ flatten into a list
⊢∊∘ is the argument in this list?
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes
```
‹⋏
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigLnii48iLCIiLCI0MyJd)
Just a port of Jelly and JS. Bitwise AND with n-1. Returns positive integer for true, 0 for false.
# [Prolog (SWI)](http://www.swi-prolog.org), 13 bytes
```
\N:-0<N-1/\N.
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P8bPStfAxk/XUD/GTw/INTLV44ox0QMA "Prolog (SWI) – Try It Online")
-4 thanks to Jo King
[Answer]
# J, 12
It doesn't follow the spec 'true'/'false'. Rather I stick with 1/0. It checks if log base 2 of a number has a decimal mark.
`+/=&'.'":2^.`
```
+/=&'.'":2^.1
0
+/=&'.'":2^.4
0
+/=&'.'":2^.43
1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
&’
```
[Try it online!](https://tio.run/##y0rNyan8/1/tUcPM/4fbHzWtifz/38QYAA "Jelly – Try It Online")
Just a translation of the accepted JavaScript solution.
[Answer]
# Perl, 51 bytes
```
print(((log($ARGV[0])/log(2))=~ /\./ )?true:false);
```
Example:
```
$perl Soc.pl 45
true
$perl Soc.pl 8
false
```
[Answer]
# Python 2 REPL, 33 chars
It seems that there's a way shorter way to do this though:
```
s=input()
n=2
while n<s:n*=2
n!=s
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
Ṅ's¯1J≈;Ṫḃ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4bmEJ3PCrzFK4omIO+G5quG4gyIsIiIsIjFcbjJcbjNcbjRcbjVcbjZcbjdcbjhcbjlcbjEwXG4xMVxuMTJcbjEzXG4xNFxuMTVcbjE2XG4xN1xuMThcbjE5XG4yMCJd)
A non-bitwise answer that doesn't port Javascript.
## Explained
```
Ṅ's¯1J≈;Ṫḃ
Ṅ # Integer partitions of the input
' ; # Filtered by:
s¯ # Are the deltas of the sorted partition
1J≈ # All 1?
Ṫḃ # Remove the tail of the list because that's just the input as a single item and then return whether there's any items in the list.
```
] |
[Question]
[
## The Rules
* Each submission must be a full program or a function.
* The program must take all instances of the string `2015` from the input (1 string), replace it with `<s>2015</s>*` (with <s> or <strike>). At the end, if there has been at least one `2015` in the string, you must add a newline and this string: `*2016. I'm a year early!`
* The program must not write anything to STDERR.
* The input will not contain `<s>2015</s>` or `<strike>2015</strike>`.
Note that there must be an interpreter so the submission can be tested.
* Submissions are scored in *bytes*, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like [Folders](http://esolangs.org/wiki/Folders), are a bit tricky to score - if in doubt, please ask on [Meta](http://meta.codegolf.stackexchange.com/).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins
## Examples
**Input:**
```
Hello! The date is 2015-12-24.
```
**Output:**
```
Hello! The date is ~~2015~~*-12-24.
*2016. I'm a year early!
```
**Input:**
```
foo bar baz quux
```
**Output:**
```
foo bar baz quux
```
**Input:**
```
12320151203205120151294201511271823
```
**Output:**
```
123~~2015~~*12032051~~2015~~*1294~~2015~~*11271823
*2016. I'm a year early!
```
**Input:**
```
Hello. The year is 2015...
2015.5...
```
**Output:**
```
Hello. The year is ~~2015~~*...
~~2015~~*.5...
*2016. I'm a year early!
```
## The Snippet
The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a leaderboard and b) as a list of winners per language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=68372,OVERRIDE_USER=45162;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?([\d.]+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# JavaScript ES6, ~~84 76~~ 75 bytes
```
s=>(q=s.replace(/2015/g,"<s>$&</s>*"))+(s<q?`
*2016. I'm a year early!`:"")
```
This is pretty well golfed for JavaScript imo.
---
This works by taking the input and replacing all instances of `2015` with `<s>$&</s>*` where `$&` is the value matched, but in this case, that's always `2015`. Then, if the input is different from `q`, it'll add the `*2016...` string, otherwise, It'll add a blank string (nothing).
[Answer]
# Ruby, 69 bytes
```
$><<gets.gsub(/2015/,'<s>\&</s>*')
puts"*2016. I'm a year early!"if$&
```
[Answer]
# Jolf, 60 bytes
Two parts, again.
```
oHρi"2015"+pd"s'$&'*"
oH set H
ρi"2015" to input string, replaced all 2015 with
pd"s'$&' $& crossed out. (pd is an apply tag function)
+ *" append an asterisk
v-- unprintable
+H|&?=Hi+S"*2016. I\'m a year early!'"
+H|&?=Hi '" add ‚Üì to H if H != i; otherwise add empty string ('")
+S"*2016. I\'m a year early!' a newline plus that string
implicit printing
```
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=b0jPgWkiMjAxNSIrcGQicyckJicqIitIfCZ_PUhpK1MiKjIwMTYuIElcJ20gYSB5ZWFyIGVhcmx5ISci&input=SXQncyAyMDE1ISBIQUhBIQ) Bonus points for actually crossing out the text and conforming to the output examples? :3
[Answer]
## Python, 97 bytes
```
a=raw_input();b=a.replace('2015','<s>2015</s>*');print a;
if a!=b:print"*2016. I'm a year early!"
```
This takes input from stdin, replaces any instances of 2015 with a strike, and prints the 2016 message if the two strings don't match.
[Answer]
## Mathematica, 98 bytes
```
a="2015";StringReplace[#,a->"<s>2015</s>*"]<>If[#~StringCount~a>0,"
*2016. I'm a year early!",""]&
```
Once again, Mathematica's string processing uses many bytes...
[Answer]
## Pyth, ~~52~~ ~~51~~ 50 bytes
```
I-
:z"2015""<s>2015</s>*"z." ytµbðï«»±é¢þnl¶Vû
```
[Test Suite](http://localhost:8000/?code=I-%0A%3Az%222015%22%22%3Cs%3E2015%3C%2Fs%3E%2a%22z.%22+y%01%C2%95t%C2%B5b%C3%B0%18%C3%AF%C2%AB%C2%BB%C2%B1%C3%A9%C2%A2%C3%BEnl%02%C2%B6V%C3%BB&test_suite=1&test_suite_input=Hello%21+The+date+is+2015-12-24.%0Afoo+bar+baz+quux%0A12320151203205120151294201511271823&debug=1).
[Answer]
# ùîºùïäùïÑùïöùïü, 49 chars / 93 bytes
```
a=ïę ḟ*ṁ,`<s>$&</s>*”)+(a≠ï?ɘƂ联Ӏఈ쁬Πā␎䁛␐줄쁰ꖈᲠ䉠耀#:⬯
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=12320151203205120151294201511271823&code=a%3D%C3%AF%C4%99%20%E1%B8%9F*%E1%B9%81%2C%60%3Cs%3E%24%26%3C%2Fs%3E*%E2%80%9D%29%2B%28a%E2%89%A0%C3%AF%3F%C9%98%C6%82%E8%81%94%D3%80%E0%B0%88%EC%81%AC%CE%A0%C4%81%E2%90%8E%E4%81%9B%E2%90%90%EC%A4%84%EF%80%94%EC%81%B0%EA%96%88%E1%B2%A0%E4%89%A0%E8%80%80%23%3A%E2%AC%AF)`
Really straightforward. `a=ïę ḟ*ṁ,'<s>$&</s>*”)` nests all instances of 2015 (represented here as the result of 31\*65) in strikethrough tags. Then, append the last string ('compressed' here) accordingly.
[Answer]
## Japt, 51 bytes
```
Y=Ur2015"<s>$&</s>*")¥U?U:Y+`
*2016. I'm a ye e§!
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=WT1VcjIwMTUiPHM+JCY8L3M+KiIppVU/VTpZK2AKKjIwMTYuIEknbSBhIHllhyBlh6ch&input=IjEyMzIwMTUxMjAzMjA1MTIwMTUxMjk0MjAxNTExMjcxODIzIg==)
[Answer]
# [TeaScript](https://github.com/vihanb/TeaScript), 59 bytes
```
(q=xg2015,"<s>$&</s>*"))+(x<q?`
*2016. I'm a year early!`:u
```
[Try it online](http://vihan.org/p/TeaScript/#?code=%22(q%3Dxg2015,%5C%22%3Cs%3E$%26%3C%2Fs%3E*%5C%22))%2B(x%3Cq%3F%60%5Cn*2016.%20I'm%20a%20year%20early!%60:u%22&inputs=%5B%22Foo%202015%20Foo%202015%22%5D&opts=%7B%22int%22:false,%22ar%22:false,%22debug%22:false%7D)
## Explanation
```
(q= // Assign `q` to...
xg // input.replace
2015 // 2015 with.
"..." // The string
)) + // Add to..
(x<q? // If the input is different from replacement
"..." // Add string to the end
:u // Otherwise empty string
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~42~~ 40 bytes
```
Ž7ç©åi®®"<s>ÿ</s>*".:®>“*ÿ. I'm€…‚Œ‰€!“»
```
[Try it online!](https://tio.run/##AVcAqP9vc2FiaWX//8W9N8OnwqnDpWnCrsKuIjxzPsO/PC9zPioiLjrCrj7igJwqw78uIEknbeKCrOKApuKAmsWS4oCw4oKsIeKAnMK7//9JIGxpa2UgMjAxNSE "05AB1E – Try It Online")
*-2 thanks to Grimy*
## Explanation
```
Ž7ç©åi®®"<s>ÿ</s>*".:®>“*ÿ. I'm€…‚Œ‰€!“» Full Program
Ž7ç© Pushes 2015 and copies it to the register
å Checks if 2015 occurs in the input
i If yes, do the following steps, else
finish and output the input
®®"<s>ÿ</s>*" Pushes 2015 and "<s>2015</s>*"
.: Replaces all instances of 2015 by
</s>2015</s> in the input
®>“*ÿ. I'm€…‚Œ‰€!“ Push "*2016. I'm a year early!"
» Concatenate both strings with a newline in between
```
[Answer]
# [Arturo](https://github.com/arturo-lang/arturo), ~~83~~ 79 bytes
```
$[s][r:replace s"2015""<s>2015</s>*"if r<>s['r++"\n*2016. I'm a year early!"]r]
```
[Answer]
## (f)lex, 104 bytes
File `2015.l`:
```
int n=0;
%%
"2015" ++n+puts("<s>2015</s>*");
%%
main(){yylex();n&&puts( "*2016. I'm a year early!\n");}
```
...no trailing newline.
Build:
```
$ flex -o 2015.c 2015.l
$ gcc 2015.c -o 2015 -lfl
```
Run:
```
$ ./2015 <<<'Hello! The date is 2015-12-24.'
Hello! The date is <s>2015</s>*-12-24.
*2016. I'm a year early!
$ ./2015 <<<'foo bar baz quux'
foo bar baz quux
$ ./2015 <<<'12320151203205120151294201511271823'
123<s>2015</s>*12032051<s>2015</s>*1294<s>2015</s>*11271823
*2016. I'm a year early!
```
I ran this using `flex` and `gcc` on Debian8, but I see no reason why it should fail in other environments using `lex` and/or a different C compiler.
[Answer]
# C#, 152 bytes
```
class A{static void Main(string[]a){System.Console.Write(a[0].Replace("2015","<s>2015</s>*")+(a[0].Contains("2015")?"\n*2016. I'm a year early!":""));}}
```
Basic solution. Takes the string as the first argument.
[Answer]
# Gema, 57 bytes
```
2015=<s>$0</s>*@set{a;*2016. I'm a year early\!}
\Z=${a;}
```
Sample run:
```
bash-4.3$ gema -f not-2015.gema <<< 'Hello! The date is 2015-12-24.'
Hello! The date is <s>2015</s>*-12-24.
*2016. I'm a year early!
bash-4.3$ gema -f not-2015.gema <<< 'foo bar baz quux'
foo bar baz quux
bash-4.3$ gema -f not-2015.gema <<< '12320151203205120151294201511271823'
123<s>2015</s>*12032051<s>2015</s>*1294<s>2015</s>*11271823
*2016. I'm a year early!
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~81~~ 79 bytes
-2 bytes thanks to mazzy
```
param($n)($z=$n-replace2015,'<s>$&</s>*')+"
*2016. I'm a year early!"*($z-ne$n)
```
[Try it online!](https://tio.run/##LY7LDoIwFET3/YprU6kgVFvwFZW17t2bqiWa8BIkKui3Y9u4uJnJZObklsVTVfVVpWlPkm3Xl7KS2Yjk7oi0W5IHlSpTeVZiymc@3dQxcTaTOvaoO8bI0@mcwZ5mIOGtZAX60vcAe3oc5EpT@i9CeKfpxQAOVwUX@VBwq8HwAi4CETHsI5wUBZz0/iRbuDfNy2RchKbFxVSrEeNXkVUuFnwpQlMDS2eWbn/40xljyKpxGD5D6MAhCZDjGij99j8 "PowerShell – Try It Online")
Just a replace on the input and a conditional append with the 2016 line. You don't need many quotes or spaces in PowerShell either.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 36 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ç┼↕+∙n7↔Qq┼╩↓╣ÇÖú];ⁿX£╞bëi⌐ñ▼Z♀φ6╛(<
```
[Run and debug it](https://staxlang.xyz/#p=87c5122bf96e371d5171c5ca19b98099a35d3bfc589cc6628969a9a41f5a0ced36be283c&i=Hello%21+The+date+is+2015-12-24.%0A12320151203205120151294201511271823%0A+Hello.+The+year+is+2015...%0A2015.5...%0A%0Afoo+bar+baz+quux&a=1&m=1)
Unpacked, ungolfed, and commented, it looks like this.
```
_ push all of standard input
2015X push 2015 and store it in the x register
$/c split string on "2015", and copy the result
"<s>`x</s>*"*P join with "<s>2015</s>*" and print
D!C stop executing if split resulted in more than 1 element
'*p print "*" without newline
|Xp increment x register and print without newline
print unterminated compressed literal ". I'm a year early!"
`Q_RUWZ)O-C!
```
[Run this one](https://staxlang.xyz/#c=_+++++++++++++%09push+all+of+standard+input%0A2015X+++++++++%09push+2015+and+store+it+in+the+x+register%0A%24%2Fc+++++++++++%09split+string+on+%222015%22,+and+copy+the+result%0A%22%3Cs%3E%60x%3C%2Fs%3E*%22*P%09join+with+%22%3Cs%3E2015%3C%2Fs%3E*%22+and+print%0AD%21C+++++++++++%09stop+executing+if+split+resulted+in+more+than+1+element%0A%27*p+++++++++++%09print+%22*%22+without+newline%0A%7CXp+++++++++++%09increment+x+register+and+print+without+newline%0A++++++++++++++%09print+unterminated+compressed+literal+%22.+I%27m+a+year+early%21%22%0A%60Q_RUWZ%29O-C%21&i=Hello%21+The+date+is+2015-12-24.%0A12320151203205120151294201511271823%0A+Hello.+The+year+is+2015...%0A2015.5...%0A%0Afoo+bar+baz+quux&m=1)
[Answer]
# [Retina](https://github.com/mbuettner/retina), ~~49 45 64 61 60~~ 54 bytes
```
s`2015.+
$&¶*2016. I'm a year early!
\`2015
<s>$&</s>*
```
After numerous attempts I think this is the shortest Retina solution
---
The first line matches `2015`, the second line replaces the previous match (`2015`) with `<s>$&</s>*` where `$&` is the match's value or in this case, `2015`.
The `\` removes the trailing newline from the output. The ``` starts the regex. `$` matches the end specifying we're trying to add a string to the end. The last line simply adds the string where `¶` becomes a newline. Retina uses the ISO-8859-1 encoding in which the `¶` is one byte
[Try it online](http://retina.tryitonline.net/#code=c2AyMDE1LisKJCbCtioyMDE2LiBJJ20gYSB5ZWFyIGVhcmx5IQpcYDIwMTUKPHM-JCY8L3M-Kg&input=Zm9vIDIwMTUgYmFyIAoyMDE1IGJheiAyMDE2)
[Answer]
## [ROOP](http://esolangs.org/wiki/ROOP), 110 bytes
```
1I
CW
|%|
V !
H
' "<s>2015</s>*"
2R !
0 #V
1 G #
5V #"\n*2016. I'm a year early!"
'| M #
-V #
#W
O#
```
This uses the `R` operator to replace all occurrences of the string `2015` in the input to `<s>2015</s>*`.Then, there is a comparison -- if the input string and the new one are different, then 1 is returned. Otherwise, 0 is returned. Then, `M` repeats the string `\n*2016. I'm a year early` that many times, i.e. if there are no changes, the string is blank, otherwise, the string is `\n*2016. I'm a year early`. Then, the strings are printed and the program terminates.
Above there is a 1 which is moved to the left and then falls to the operator H, which ends the program.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 53 bytes
```
$\="\n*2016. I'm a year early!"if s|2015|<s>$&</s>*|g
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxlYpJk/LyMDQTE/BUz1XIVGhMjWxSAGIcyoVlTLTFIprgJKmNTbFdipqNvrFdlo16f//GxoZg0QNjQyANIgCsS1NwLShkbmhhZHxv/yCksz8vOL/ugU5AA "Perl 5 – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 80 bytes
```
lambda x:(b:=x.replace('2015','<s>2015<s>*'))+"\n*2016. I'm a year early!"*(b>x)
```
[Try it online!](https://tio.run/##vZBBTsMwEEX3PsV0NrHT1qqdAqWiXcOeHenCoQ41cu2QpFLCCTgBB@QiwTZcASRb73vm68szzdifvCs2TTvVu3Ky6lwdFQxbWm13A291Y9Wzpplciatskd11@6gC8oyxOZYuD@9rDg/ZGRSMWrUQrh1nmNNqP7CpaY3rKX59fvzpKR3yV28cNTCH8K2yf/G6g95D6IRSTQ376SCpfQsGjIMngvfaWj@Dx5OGo@o1mA7igEshl3LNcUGw9h6qMFal3uHtchliTcgiuoRcBUZEfbtOFPJGbGQRbYiQ8nnKT8v5zeeck8Sogo8cGCP/tCpk0zc "Python 3.8 (pre-release) – Try It Online")
*Saved 8 bytes thanks to squid*
[Answer]
# JavaScript: 62 bytes
```
x=>x.replace('2015','<s>2015</s>')+"\n*2016. I'm a year early!"
```
] |
[Question]
[
Notice the pattern in the below sequence:
```
0.1, 0.01, 0.001, 0.0001, 0.00001 and so on, until reaching 0.{one hundred zeros}1
```
Then, continued:
```
0.2, 0.02, 0.002, 0.0002, 0.00002 and so on, until reaching 0.{two hundred zeros}2
```
Continued:
```
0.3, 0.03, etc, until 0.{three hundred zeros}3
```
Continued:
```
0.4, 0.04, etc, until 0.{four hundred zeros}4
```
Sped up a bit:
```
0.10, 0.010, etc. until 0.{one thousand zeros}10
```
Sped up some more:
`0.100, 0.0100...`
You get the idea.
The input your code will receive is an integer, the number of terms, and the output is that many number of terms of the sequence.
Input and output formats are unrestricted, and separators are not required.
Trailing zeros are necessary.
[Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/48934) apply.
---
The outputs of some nth terms are given below:
```
nth term -> number
-------------------
1 -> 0.1
102 -> 0.2
303 -> 0.3
604 -> 0.4
1005 -> 0.5
1506 -> 0.6
2107 -> 0.7
2808 -> 0.8
3609 -> 0.9
4510 -> 0.10
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 23 bytes
Online compiler can't show all terms for high N but it works fine offline.
```
Lvy2°*>F„0.0N×yJ,¼¾¹Qiq
```
**Explanation**
```
# implicit input X
Lv # for each y in range [1 .. X]
y2°*>F # for each N in range [0 .. y*100+1)
„0. # push the string "0."
0N× # push 0 repeated N times
y # push current y
J, # join and print
¼¾¹Qiq # quit the program after X terms printed
```
[Try it online!](http://05ab1e.tryitonline.net/#code=THZ5MsKwKj5G4oCeMC4wTsOXeUoswrzCvsK5UWlx&input=MzAz)
[Answer]
# Python 2, ~~73~~ 64 bytes
I think this is pretty short. I'm not sure that I can get it any shorter now that I golfed the `if-else` away.
```
s=z=1
exec'print"0.%0*d"%(z,s);q=z>s*100;z+=1-z*q;s+=q;'*input()
```
[**Try it online**](https://repl.it/Dklg/2)
Less golfed:
```
n=input()
s=z=1
for i in range(n):
print"0.%0*d"%(z,s)
if z>s*100:z=1;s+=1
else:z+=1
```
[Answer]
# Haskell, ~~53~~ 63 bytes
This does the same thing as the 05AB1E answer now
```
f=(`take`["0."++('0'<$[1..y])++show x|x<-[1..],y<-[0..x*100]])
```
[Answer]
# Perl 5, 57 52 bytes
(needs `-E` for `say`)
```
for(1..<>){say"0."."0"x$i++.$.;$.++,$i=0if$i>100*$.}
```
Or readably:
```
# $. is the input line number, use it to count the
# number at the end.
# $i counts zeroes in the middle, starts at 0 implicitly
for(1..<>){ # get the number of terms from stdin and loop
# <> implicitly increases $. (to 1)
say "0." . "0" x $i++ . $.; # print the number, add one zero
$.++, $i=0 if $i > 100 * $.; # increment the number, reset number
# of zeroes if we've printed enough
}
```
Trailing zeroes are printed since the number after the row of zeroes is just an integer concatenated as a string.
Test run:
```
$ perl -E 'for(1..<>){say"0."."0"x$i++.$.;$.++,$i=0if$i>100*$.}' | tail -3
4511
0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009
0.10
0.010
```
[Answer]
## [QBIC](https://codegolf.stackexchange.com/questions/44680/showcase-your-language-one-vote-at-a-time/86385#86385), ~~73~~ 64 bytes
```
:#0|{C=!q$D=@0.|[0,q*100|d=d+1?D+$LTRIM$|(C) D=D+A~d=a|_X]]q=q+1
```
Saved 9 bytes by removing `x` as upper bound in the `FOR` loop. Upper bound is now set as `q*100`. Shame that QBasic automatically adds a space in front of a printed number, that's a costly `LTRIM$`...
Some explanation: `q` is used as the current number in the loop. This starts as 1 and gets incremented every 100N turns. This number gets converted to a string and is then appended to the string `0.` and the correct number of `0`'s. In detail:
```
We use q as our 'base number', this is 1 implicitly
: Get the max number of terms from a numeric CMD line param
#0| Define string A$ as "0"
{ DO
C=!q$ our base number is cast to the string C$
D=@0.| define D$ as "0."
[0,q*100| FOR each of the terms we need to do for our base number
(i.e. 101 for 1, 201 for 2 ...)
d=d+1 Keep track of the total # of terms
(i.e. 101 after the 1 cycle, 302 after the 2...)
?D+$LTRIM$|(C) Print to screen D$ + C$, where D$ = "0.[000]"
and C$ is our base number (1, or 2, or - much later - 100)
LTRIM is in there to prevent "0.00 1"
D=D+A Add A$ to the end of D$ ("0.00" becomes "0.000")
~d=a|_X] Stop if we've reached the max. # of terms
] NEXT
q=q+1 If we've done all the terms necessary with this base number
then raise base number.
The DO loop gets closed implicitly by QBIC.
```
---
Edit: QBIC has seen quite some development over time, and the above can now be solved in 49 bytes, 15 bytes shorter:
```
{D=@0.`[0,q*100|d=d+1?D+!q$┘D=D+@0`~d=a|_X]]q=q+1
```
[Answer]
## PowerShell v2+, 89 bytes
```
param($n)for($j=1;;$j++){for($i=0;$i-le100*$j;$i++){"0.$('0'*$i)$j";if(++$k-ge$n){exit}}}
```
Straight-up double-`for` loop. The first, for `$j` is infinite. The inner, for `$i`, loops from `0` up to `100*$j`, using string concatenation and string multiplication to print out the appropriate item. It also checks total loop counter `$k` against input `$n`, and `exit`s the program after we hit that point.
[Answer]
# PHP, 83 Bytes
```
for($s=1;$i++<$argv[1];){if($r>100*$s){$s++;$r=0;}echo" 0.".str_repeat(0,$r++).$s;}
```
[Answer]
# GNU sed 163 157
+2 included for -rn
```
s,^,0.1\n,;:;P;s,\.,.0,;s,.$,,;/0{101}/{s,0\.0*(09)?,\1,
s,.9*\n,x&,;h;s,.*x(.*)\n.*,\1,;y,0123456789,1234567890,
G;s,(.*\n)(.*)x.*\n(.*),0.\2\1\3,};/\n./b
```
Takes input in unary [based in this consensus](http://meta.codegolf.stackexchange.com/a/5349/57100).
[Try it online!](http://sed.tryitonline.net/#code=cyxeLDAuMVxuLDs6O1A7cyxcLiwuMCw7cywuJCwsOy8wezEwMX0ve3MsMFwuMCooMDkpPyxcMSwKcywuOSpcbix4Jiw7aDtzLC4qeCguKilcbi4qLFwxLDt5LDAxMjM0NTY3ODksMTIzNDU2Nzg5MCwKRztzLCguKlxuKSguKil4LipcbiguKiksMC5cMlwxXDMsfTsvXG4uL2IKCiNleGFtcGxlIGlucHV0IGlzIDEwMg&input=MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEx&args=LXJu)
---
An easy way to run this is:
```
yes 1 | head -{input} | tr -d '\n' | sed -rnf zeroOne.sed
```
---
**Explanation**
```
s,^,0.1\n, #add 0.1 as the first line of the pattern space
:
P #print everything up to the first newline
s,\.,.0, #add a 0 after the .
s,.$,, #reduce the number left to print by one
/0{100}/{ #if there is a string of 100 zero do the following
s,0\.0*(09)?,\1, #get rid of all the 0s (except one if the we are adding another digit)
s,.9*\n,x&, #put an x before the left most number that will change
h #store in hold space
s,.*x(.*)\n.*,\1, #remove everything except the numbers that change
y,0123456789,1234567890, #replace numbers with the next one up
G #bring the rest of the string back
s,(.*\n)(.*)x.*\n(.*),0.\2\1\3,
#replace the x and numbers that changed with the new ones
}
/\n./b #branch back unless there isn't anything on the last line
```
[Answer]
# Mathematica, 70 bytes
```
Take[Join@@Table["0."<>Array["0"&,k]<>ToString@m,{m,#},{k,0,100m}],#]&
```
Unnamed function that takes the desired length as its argument and returns a list of strings (using strings instead of numbers makes the trailing zeros easy to include).
This version is slow as hell! because if you want, for example, the first 10 terms, it actually computes the sequence all the way through the 10th segment (101 + 201 + ... + 1001 = 5510 terms) and then retains only the first 10. So already at input 303, it's computing nearly five million terms and discarding almost all of them. The **81**-byte version
```
Take[Join@@Table["0."<>Array["0"&,k]<>ToString@m,{m,Sqrt[#/50]+1},{k,0,100m}],#]&
```
doesn't have this flaw, and in fact calculates nearly the fewest segments possible.
[Answer]
# JavaScript (ES6), 69
```
n=>[...Array(n)].map(_=>(w=l--?z:(l=++x*100,z='0.'),z+=0,w+x),l=x=0)
```
Unnamed function with desired length in input and returning an array of strings.
**Test**
```
f=
n=>[...Array(n)].map(_=>(w=l--?z:(l=++x*100,z='0.'),z+=0,w+x),l=x=0)
var tid=0
function exec()
{
var n=+I.value;
O.textContent=f(n).map((r,i)=>i+1+' '+r).join`\n`;
}
function update()
{
clearTimeout(tid);
tid=setTimeout(exec, 1000);
}
exec()
```
```
<input id=I value=305 type=number oninput='update()'><pre id=O></pre>
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 71 bytes
```
sn1sj1si1[lj1+dddsjZ1-dkAr^/li1+si]sJ[0nK1+kA/pljA0*K=Jlnlid1+si<M]dsMx
```
[Try it online!](https://tio.run/##FckxDoAgDADA/0gMNKw6sEL4gAQXu7Q0xNjF39d46@FlMUTTCcqgBE0YHCIqH7DiSM/phcApdc0tzAJuJH8Lp7CUPcsUwn@32lHra/YB "dc – Try It Online")
Honestly, I thought taking advantage of dc's arbitrary precision would make this easy, but I'm pretty sure just printing a ton of zeroes will be golfier. It feels really suboptimal, but I still think the use of arbitrary precision is interesting.
`sn1sj1si1` We're taking top-of-stack as our nth-term target, so we store it in `n`, initialize `i` and `j` at 1, and leave a 1 on the stack.
`[lj1+dddsjZ1-dkAr^/li1+si]sJ` Macro `J` handles what to do when we've hit the 100, 200, &c. mark. Counter `j` keeps track of this, so we increment it, we set our precision to the number of digits it has less one, and then we leave the first digit of it (`Z1-Ar^/`; divide by 10^(number of digits less one)) on the stack since this is our starting point for the next big long chain.
`[0nK1+kA/pljA0*K=Jlnlid1+si<M]dsMx` Our main macro. First we print a leading 0 with `0n`. Then `K1+k` increments our precision by one place. `A/` divides by ten, pushing us a place over to the right.`p` prints, and then the rest is housekeeping. We can test our current precision to determine whether or not we need to jump into macro `J`, so we multiply counter `j` by a hundred (note: `A0` here may need to be replaced with `100` on some implementations (cygwin)) and do the comparison. We load `n`, our target nth term, increment our main counter, `i`, and then compare the two. If we haven't yet hit the target, we keep running `M`.
[Answer]
# Excel VBA, 63 Bytes
Anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the VBE immediate window
```
n=[A1]:While n>i*100:n=n-1-i*100:i=i+1:Wend:?"0."String(n,48)&i
```
[Answer]
# Java 8, 120 bytes
```
n->{String r="";a:for(int i=1,j,k,c=n;;i++)for(j=0;j<=i*100;r+=i+"\n"){for(r+="0.",k=j++;k-->0;r+=0);if(c--<1)break a;}}
```
Explanation and TIO uses the one below however. The difference: the one above creates one big String and then returns it; the one below prints every line separately (which is much better for performance).
**130 bytes:**
```
n->{String r;a:for(int i=1,j,k,c=n;;i++)for(j=0;j<=i*100;System.out.println(r+i)){for(r="0.",k=j++;k-->0;r+=0);if(c--<1)break a;}}
```
**Explanation:**
[Try it here.](https://tio.run/##LY/BbsIwEETvfMWKk13HkSNVPXQxf1AuHFEPxjjV2sGJHINURfn24ADS7mFndqQ33tyN7AcX/SUstjPjCD@G4rQBoJhdao11cFhPgHtPF7Cs6BA5FmkuW2bMJpOFA0TQsES5n445UfyDhOa77dMzQbqpfBUqqyMiCcFXw2uFfqfpo1EKj/9jdte6v@V6KPHcRZYEcT6tn0lvVb2tgvZCYJByrzAJrThSy6yUu4afkzMBDM7zgptCNdzOXaF6wz3Zr6UZe7GdfsHwV61YW/alPt@N5uUB) (Will time out or exceed output limit for test cases above `604`, but locally test case `4510` works in below 2 seconds.)
```
n->{ // Method with integer parameter and no return-type
String r; // Row String
a:for(int i=1, // Index integer `i` starting at 1
j,k, // Some other index integers
c=n // Counter integer starting at the input
;;i++) // Loop (1) indefinitely
for(j=0; // Reset `j` to 0
j<=i*100; // Loop (2) from 0 to `i*100` (inclusive)
System.out.println(r+i)){
// After every iteration: print `r+i` + new-line
for(r="0.", // Reset row-String to "0."
k=j++; // Reset `k` to `j`
k-->0; // Loop (3) from `j` down to `0`
r+=0 // And append the row-String with "0"
); // End of loop (3)
if(c--<1) // As soon as we've outputted `n` items
break a; // Break loop `a` (1)
} // End of loop (2) (implicit / single-line body)
// End of loop (1) (implicit / single-line body)
} // End of method
```
] |
[Question]
[
One way to construct a regular [heptadecagon](https://en.wikipedia.org/wiki/Heptadecagon) starts with drawing a horizontal line of length `1` from the center to a vertex. Then the distance along that line from the center to the second vertex is `cos(2π/17)`. All other vertices are easy to get.
The goal of this challenge is to print (or produce in any other conventional way) an ASCII math expression involving the operations `+`, `-`, `*`, `/`, `sqrt()` and the natural numbers, which gives `cos(2π/17)` when evaluated. The power operator is not allowed: e.g. `sqrt(17)` cannot be written as `17^(1/2)`.
For example (formula taken from Wikipedia):
```
1/16*(
-1+
sqrt(17)+
sqrt(34-2*sqrt(17))+
2*sqrt(
17+
3*sqrt(17)-
sqrt(34-2*sqrt(17))-
2*sqrt(34+2*sqrt(17))
)
)
```
Whitespace doesn't matter. The length and complexity of the expression doesn't matter, as long as it's syntactically correct (as defined above) and numerically equivalent to `cos(2π/17)`.
Built-in functions are allowed.
[Answer]
## CJam (60 bytes)
```
1-4{"(- +sqrt( * -4*
))/2"S/@a*N/\a*}:F~'-\+WF'-\+W-4FWFF'/2
```
[Online demo](http://cjam.aditsu.net/#code=1-4%7B%22(-%20%2Bsqrt(%20*%20-4*%0A))%2F2%22S%2F%40a*N%2F%5Ca*%7D%3AF~'-%5C%2BWF'-%5C%2BW-4FWFF'%2F2)
Output (with added newlines to avoid wrapping):
```
(--(--(-1+sqrt(1*1-4*-4))/2+sqrt(-(-1+sqrt(1*1-4*-4))/2*-(-1+sqrt(1*1-4*-4))/2-4*-1)
)/2+sqrt(-(--(-1+sqrt(1*1-4*-4))/2+sqrt(-(-1+sqrt(1*1-4*-4))/2*-(-1+sqrt(1*1-4*-4))/
2-4*-1))/2*-(--(-1+sqrt(1*1-4*-4))/2+sqrt(-(-1+sqrt(1*1-4*-4))/2*-(-1+sqrt(1*1-4*-4)
)/2-4*-1))/2-4*(-(--1+sqrt(-1*-1-4*-4))/2+sqrt((--1+sqrt(-1*-1-4*-4))/2*(--1+sqrt(-1
*-1-4*-4))/2-4*-1))/2))/2/2
```
I suspect this is the kind of answer OP was secretly hoping for. Rather than apply general-purpose compression to a string, it uses the field structure which Gauss first exploited to present this value in surds, in his *Disquisitiones Arithmeticae*.
I worked from [this presentation](http://dynamicsofpolygons.org/PDFs/Constructions.pdf) (pages 18 and 19) but adapted it slightly in order to only ever require the positive root of a quadratic. Unrolled and in pseudo-code, the expression breaks down as
```
# Positive root of x^2 + bx + c = 0
F(b, c) = (-b + sqrt(b*b - 4*c))/2
# (8,1)
p = F(1, -4)
# (4,1)
q = F(-p, -1)
# -(8,3)
r = F(-1, -4)
# (4,3)
s = F(r, -1)
# Result
F(-q, s)/2
```
[Answer]
# JavaScript (ES6), 93
**Edit** 1 byte saved thx @ETHproductions
An anonymous function.
```
x=>"(19)+8-29))+29+39)-8-29))-2*8+29)))-1)/16".replace(/8|9/g,n=>["sqrt(34","*sqrt(17"][n-8])
```
Output:
```
(1*sqrt(17)+sqrt(34-2*sqrt(17))+2*sqrt(17+3*sqrt(17)-sqrt(34-2*sqrt(17))-2*sqrt(34+2*sqrt(17)))-1)/16
```
**TEST**
```
F=x=>"(19)+8-29))+29+39)-8-29))-2*8+29)))-1)/16".replace(/8|9/g,n=>["sqrt(34","*sqrt(17"][n-8])
// Math check
k=Math.cos(Math.PI*2/17)
x=F()
v=eval(x.replace(/sqrt/g,"Math.sqrt"))
O.textContent=k+' (Math.cos(Math.PI*2/17))\n'+v+' ('+x+')\n'+(v==k)
```
```
<pre id=O></pre>
```
[Answer]
# Mathematica, 26 bytes
```
FunctionExpand@Cos[2Pi/17]
```
**Output**
```
1/(4 Sqrt[2/(15+Sqrt[17]-Sqrt[2 (17-Sqrt[17])]+Sqrt[2 (34+6 Sqrt[17]+Sqrt[2 (17-Sqrt[17])]-Sqrt[34 (17-Sqrt[17])]+8 Sqrt[2 (17+Sqrt[17])])])])
```
---
**Alternative form**
```
CForm@FunctionExpand@Cos[2Pi/17]
```
gives
```
1/(4.*Sqrt(2/(15 + Sqrt(17) - Sqrt(2*(17 - Sqrt(17))) + Sqrt(2*(34 + 6*Sqrt(17) + Sqrt(2*(17 - Sqrt(17))) - Sqrt(34*(17 - Sqrt(17))) + 8*Sqrt(2*(17 + Sqrt(17))))))))
```
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 50 bytes
Hex dump:
```
78 DA D3 28 2E 2C 2A D1 30 34
D7 D4 06 33 8C 4D 74 61 02 5A
46 50 31 43 73 6D B8 98 B1 2E
16 65 30 31 6D 24 31 30 D2 35
D4 D4 37 34 03 00 AC BC 1B 67
```
Contains a pesky null byte, so you can’t try it online, but it prints this string:
```
(sqrt(17)+sqrt(34-sqrt(17)*2)+sqrt(17+sqrt(17)*3-sqrt(34-sqrt(17)*2)-sqrt(34+sqrt(17)*2)*2)*2-1)/16
```
[Answer]
# Bubblegum, 39 bytes
```
0000000: d3 35 d4 37 34 d3 2e 2e 2c 2a d1 30 34 d7 84 b3 .5.74...,*.04...
0000010: 75 8d b4 60 62 da c6 26 98 e2 a8 d2 ba 58 f4 00 u..`b..&.....X..
0000020: 31 82 0b 32 da 02 00 1..2...
```
[Try it online!](http://bubblegum.tryitonline.net/#code=MDAwMDAwMDogZDMgMzUgZDQgMzcgMzQgZDMgMmUgMmUgMmMgMmEgZDEgMzAgMzQgZDcgODQgYjMgIC41Ljc0Li4uLCouMDQuLi4KMDAwMDAxMDogNzUgOGQgYjQgNjAgNjIgZGEgYzYgMjYgOTggZTIgYTggZDIgYmEgNTggZjQgMDAgIHUuLmBiLi4mLi4uLi5YLi4KMDAwMDAyMDogMzEgODIgMGIgMzIgZGEgMDIgMDAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDEuLjIuLi4&input=)
### Verification
```
$ base64 -d > exact-cos.bg <<< 0zXUNzTTLi4sKtEwNNeEs3WNtGBi2sYmmOKo0rpY9AAxggsy2gIA
$ wc -c exact-cos.bg
39 exact-cos.bg
$ bubblegum exact-cos.bg; echo
-1/16+sqrt(17)/16+sqrt(-2*sqrt(17)+34)/16+sqrt(-2*sqrt(2*sqrt(17)+34)-sqrt(-2*sqrt(17)+34)+3*sqrt(17)+17)/8
$ cat verify-cos
#!/usr/bin/python3
from sympy import *
print(Eq(S(input()), cos(2*pi/17)))
$ bubblegum exact-cos.bg | ./verify-cos
True
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 37 bytes
```
17√:£‹34¥d-√:→+¥T17+←-34¥d+√d-√d+16/S
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIxN+KImjrCo+KAuTM0wqVkLeKImjrihpIrwqVUMTcr4oaQLTM0wqVkK+KImmQt4oiaZCsxNi9TIiwiIiwiIl0=)
So... Vyxal uses sympy for numbers, and sympy represents complex equations, such as `sqrt(17) + 1`, as expressions that resolve to that.
So, all we have to do is calculate the number (using the question's formula for convenience) and stringify it.
```
17√ # Push √17
:£‹ # Store a copy to the register and push √17 - 1
34¥d-√ # Push √(34 - 2√17)
:→ # Store a copy to the ghost variable
+ # Add to previous
[ ] # √17 - 1 + √(34 - 2√17)
¥T17+ # 3√17 + 17
←- # Subtract ghost variable
# 3√17 + 17 - √(34 - 2√17)
34¥d+√d- # √(34 + 2√17) subtracted from above
[ ] # Results in 3√17 + 17 - √(34 - 2√17) - 2√(34 + 2√17)
√d # Take the square root of that doubled
+16/S # Add to previous, divide by 16 and format.
```
[Answer]
# [golflua](http://mniip.com/misc/conv/golflua/), 122 chars
Adapted from [this Math.se post](https://math.stackexchange.com/questions/516142/how-does-cos2-pi-257-look-like-in-real-radicals).
```
f='sqrt('y='(1-'..f..'17))'x='('..y..'/2+'..f..y..'*'..y..'/4+4))'w('(2/'..x..'+'..f..x..'/2*'..f..'17+4*'..f..'17))))/4')
```
which is pretty damn long :( (mostly because of the wasteful `..` for concatenating strings).
Output
```
(2/((1-sqrt(17))/2+sqrt((1-sqrt(17))*(1-sqrt(17))/4+4))+sqrt(((1-sqrt(17))/2+sqrt((1-sqrt(17))*(1-sqrt(17))/4+4))/2*sqrt(17+4*sqrt(17))))/4
```
Which, when evaluated, returns `0.93247222940436`
[Answer]
# Ruby, 71
I think this could be shorter in another language.
```
'(s/2)+s-s*2))+s*2+s*72)-4*s-s*2))-8*s+s*2)))-1)/16'.gsub(?s,'sqrt(34')
```
The above string expression evaluates to the below string. The idea was to rearrange the expression so that a single substitution of `s` -> `sqrt(34` would be the only operation needed to decompress it.
```
(sqrt(34/2)+sqrt(34-sqrt(34*2))+sqrt(34*2+sqrt(34*72)-4*sqrt(34-sqrt(34*2))-8*sqrt(34+sqrt(34*2)))-1)/16
```
I assume "produce in any other conventional way" means an expression is enough. If this is not the case: Printing the string in quotation marks would need 2 extra bytes at the beginning of the source code: `p` . For 5 bytes it can be printed without quotation marks by adding `puts`. Enclosing it in `->{}` yields an anonymous function for 4 extra bytes.
[Answer]
# CJam, 68
```
"2* 17 sqrt( 23) 243-41) (1+0+423+1+41-0-4243+41))"S/~5{s/\*}/W")/"G
```
[Try it online](http://cjam.aditsu.net/#code=%222*%2017%20sqrt(%2023)%20243-41)%20(1%2B0%2B423%2B1%2B41-0-4243%2B41))%22S%2F~5%7Bs%2F%5C*%7D%2FW%22)%2F%22G)
[Answer]
# R 68 bytes
```
s=sqrt;x=s(17);y=s(34-2*x);cat((x+y+2*s(17+3*x-y-2*s(34+2*x))-1)/16)
```
[Answer]
# [Vim](http://www.vim.org/docs.php), [70 keystrokes](http://retina.tryitonline.net/#code=KDxbXjw-XSs-fC4p&input=OmltIGEgKnNxcnQoPENSPgo6aW0gYiBhMTcpPENSPgppKDFiLTErMWEzNC0yYikrMmI8YnNwPiszYi0xYTM0LTJiKS0yYTM0KzJiKSkpLzE2PGVzYz4)
```
:im a *sqrt(<CR>
:im b a17)<CR>
i(1b-1+1a34-2b)+2b<bsp>+3b-1a34-2b)-2a34+2b)))/16<esc>
```
[Answer]
# Perl 5, 78 bytes
A subroutine:
```
{'(1S)+T-2S))+2S+3S)-T-2S))-2*T+2S)))-1)/16'=~s/S/*sqrt(17/gr=~s/T/sqrt(34/gr}
```
View the returned value by means of `print sub{...}->()` or the like.
[Hat tip.](/a/71520)
] |
[Question]
[
Came over a similar problem in a project I'm working on and found it quite hard to solve it without excesive use of `if`. I'm eager to see if anyone can come up with more elegant solutions to this, with the aribitary numbers I have given to the line segments.
### The problem
You are given two integers that act like the end points of a line segment. Determine what existing line segments this line will overlap with.
### Intervals / line segments
The other lines, named Q, W, E, R and T, are as following:
```
Q: 0 - 7
W: 8 - 18
E: 19 - 32
R: 33 - 135
T: 136 -
```
The last one, T, starts at 136 and has no end point.
### Example
Given the numbers `5` and `27`, the line will overlapp with `Q`, `W` and `E`. This can be roughly illustrated like this:
```
Q W E R T
---+--+---+-------+-----------+-----
0 7 18 32 135
+---------+
5 27
(somewhat arbitrary scale)
```
### Input
Two integers from stdin.
### Output
A String containing the names of the lines that our new line overlap with, for instance in the example above `QWE`.
### Rules
Shortest code.
[Answer]
## APL (39)
```
'QWERT'/⍨1↓⊃≠/1 0⌽¨0,¨0 7 18 32 135∘<¨⎕
```
Takes input as two whitespace-separated numbers.
Explanation:
* `0 7 18 32 135∘<¨⎕`: For each number in the input, see if 0, 7, 18, 32, and/or 135 is smaller than the number. If the input was `5 27` we now have `(1 0 0 0 0) (1 1 1 0 0)`. (The first one is taken to be the start of the line and the second one the end).
* `1 0⌽¨0,¨`: Prefix a zero to each of those lists and rotate the first one left by 1. (We now have `(1 0 0 0 0 0) (0 1 1 1 0 0)`).
* `≠/`: Gives a list where the individual items of the two input lists were not equal. (We now have `1 1 1 1 0 0`).
* `1↓⊃`: Remove the first item from this list. The other five stand for whether or not to display a Q, W, E, R or T.
* `'QWERT'/⍨`: For each letter, output N of those letters, where N is the corresponding value in the list on the right. Since the list was `1 1 1 0 0` the answer is `QWE`.
[Answer]
## GolfScript (43 32 30 chars)
Contains escape characters. As a hex dump:
```
00000000 7e 29 27 51 08 57 0b 45 0e 52 67 27 32 2f 7b 29 |~)'Q.W.E.Rg'2/{)|
00000010 2a 7d 25 27 54 27 32 24 2a 2b 3c 3e 2e 26 |*}%'T'2$*+<>.&|
```
Base-64 encoded:
```
fiknUQhXC0UOUmcnMi97KSp9JSdUJzIkKis8Pi4m
```
Using bold to indicate escape characters:
```
~)'Q**^H**W**^K**E**^N**Rg'2/{)*}%'T'2$*+<>.&
```
Thanks to [Howard](https://codegolf.stackexchange.com/users/1490/howard) for the suggestion to use escape characters.
[Answer]
## Python ~~82~~ 84
There you are. Edit: Fixed for inputs like `-1 10` and `-10 -1` for 2 chars
```
z=lambda a:(a>7)+(a>18)+(a>32)+(a>135)+1
a,b=input()
print"QWERT"[z(a)-1:z(b)*(b>0)]
```
[Answer]
## J, 58 54 characters
```
'QWERT '#~0 8 19 33 136 _(([<1{])*(1|.[>:0{]))".1!:1[1
```
Reads one line of input from the keyboard.
[Answer]
## Python, 79
```
x,y=input()
print"".join(set(("Q"*8+"W"*11+"E"*14+"R"*103)[x:y+1]))+"T"*(y>135)
```
It could be a lot shorter if it's allowed to leave duplicates in the output, but I figured that would be bending the rules a bit.
[Answer]
### Scala 113
```
val i=Seq(0,8,19,33,136,(1<<31)-1)
i.zip(i.tail)zip("qwert")filter(x=>x._1._2>readInt&&x._1._1<=readInt)map(_._2)
```
Handles test cases 5-27(QWE), 400-500(T), 40-40(R), 33-33(R).
[Answer]
# K, 68 58
`{$[y>135;`T,;]`Q`W`E`R@&max'(x+!1+y-x)in/:(!8;8+!11;19+!15;33+!104)}`
```
{$[y>135;"T",;]"QWER"@&(=).'(y>'0,-1_a),'x<'a:8 19 33 136}
```
.
```
k){$[y>135;"T",;]"QWER"@&(=).'(y>'0,-1_a),'x<'a:8 19 33 136}[5;27]
"QWE"
k){$[y>135;"T",;]"QWER"@&(=).'(y>'0,-1_a),'x<'a:8 19 33 136}[0;139]
"TQWER"
k){$[y>135;"T",;]"QWER"@&(=).'(y>'0,-1_a),'x<'a:8 19 33 136}[20;135]
"ER"
k){$[y>135;"T",;]"QWER"@&(=).'(y>'0,-1_a),'x<'a:8 19 33 136}[32;135]
"ER"
```
[Answer]
## PHP, 159 characters
```
<?$b=array(0=>"Q",8=>"W",19=>"E",33=>"R",136=>"T",1e9=>"");$a=split(" ",fgets(STDIN));foreach($b as $k=>$v){if($a[0]<$k&&$a[1]>=$j)$o.=$p;$p=$v;$j=$k;}echo $o;
```
With line breaks:
```
<?
$b=array(0=>"Q",8=>"W",19=>"E",33=>"R",136=>"T",1e9=>"");
$a=split(" ",fgets(STDIN));
foreach($b as $k=>$v)
{
if($a[0]<$k&&$a[1]>=$j)
$o.=$p;
$p=$v;
$j=$k;
}
echo $o;
```
Assumes that the line segments are contiguous and non-overlapping as in the given example.
Working version [at ideone.com](http://ideone.com/9D1Ff).
[Answer]
### M (Micronetics System MUMPS 4.4) - *82 Chars*
```
f i=1:1:2 r a s x=(a>0)+(a>7)+(a>18)+(a>32)+(a>135) w:$d(y) $e("QWERT",y,x) s y=x
```
5-27(QWE), 400-500(T), 40-40(R), 33-33(R).
[Answer]
## PHP 119
```
<?fscanf(STDIN,'%d%d',$a,$b);foreach(array('Q'=>7,'W'=>18,'E'=>32,'R'=>135,'T'=>136)as$x=>$y)echo$y>=$a&&$y<=$b?$x:'';
```
Getting Input from command-line reduces the size, but, I don't think it is applicable here, but still:
## PHP 111
```
<?list(,$a,$b)=$argv;foreach(array('Q'=>7,'W'=>18,'E'=>32,'R'=>135,'T'=>136)as$x=>$y)echo$y>=$a&&$y<=$b?$x:'';
```
[Answer]
## Mathematica
```
Cases[{{q, 0, 7}, {w, 8, 18}, {e, 19, 32}, {r, 33, 135}, {t, 136, \[Infinity]}},
{a_, b_, c_} /; Length@IntervalIntersection[Interval[{b, c}], Interval[{5, 27}]] !=0
:> a]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes (improvements wanted!)
```
®Ṁṭ“®¿Çg‘
ØQFḣ5ż¢Œṙ
Ɠ©r/ị¢Q
```
[Try it online!](https://tio.run/##AUEAvv9qZWxsef//wq7huYDhua3igJzCrsK/w4dn4oCYCsOYUUbhuKM1xbzCosWS4bmZCsaTwqlyL@G7i8KiUf//NSwyNw "Jelly – Try It Online")
```
®Ṁṭ“®¿Çg‘ actual runlengths here
®Ṁ recall the input numbers, and get the maximum of them
ṭ append that max (to be used as runlength for 'T') to...
“®¿Çg‘ [ 8, 11, 14, 103 ] (listed as base-250 numbers on jelly's codepage)
ØQFḣ5ż¢Œṙ run-length encoding function:
ØQF get "QWERTYUIOPASDF..."
ḣ5 get the first 5 characters of that to yield "QWERT"
ż¢ zip it with the above link (RLE values)...
Œṙ and then apply RLE decode to produce the uncompressed string
Ɠ©r/ị¢Q main function:
Ɠ© take two integers from stdin, evaluate them and save them to a register
r/ take the range between them (technically a fold)
ị¢ for each element in the range, get the value at its index in the link above...
Q and return all the unique values (remove duplicates).
```
I think that I'm doing something wrong / non-optimally with the register save / recall to get the max value. If I just make that value 250, the program goes down to just **22 bytes**:
```
ØQFḣ5ż“®¿Çgż‘Œṙ
Ɠr/ị¢Q
```
[Try it online!](https://tio.run/##y0rNyan8///wjEC3hzsWmx7d86hhzqF1h/Yfbk8HsWccnfRw50yuY5OL9B/u7j60KPD/f1MdI3MA "Jelly – Try It Online")
] |
[Question]
[
**Inputs:**
* `current hour`: from 0 to 23 (inclusive)
* `delta of hours`: `[current hour]` + `[delta of hours]` = withing the range of `Integer`
**Output:**
* `delta of days`: the value which shows difference in days between day of `current hour` and day of sum `[current hour]` + `[delta of hours]`
**Scoring**
* Answers will be scored in bytes with fewer bytes being better.
**Examples:**
* `[current hour]` = 23; `[delta of hours]` = -23; `delta of days` = 0
* `[current hour]` = 23; `[delta of hours]` = 1; `delta of days` = 1
* `[current hour]` = 23; `[delta of hours]` = 24; `delta of days` = 1
* `[current hour]` = 23; `[delta of hours]` = 25; `delta of days` = 2
* `[current hour]` = 23; `[delta of hours]` = -24; `delta of days` = -1
* `[current hour]` = 23; `[delta of hours]` = -47; `delta of days` = -1
[Answer]
# JavaScript (ES6), ~~26~~ 25 bytes
Takes input as `(current)(delta)`.
```
a=>b=>(a+b-(a<-b)*2)/3>>3
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i7J1k4jUTtJVyPRRjdJU8tIU9/Yzs74f3J@XnF@TqpeTn66RpqGkbGmhi6Q0FTQ11cw4MKUVFAwhEgaYpM0MsEnaQqRNOLCZidUpy42rbom5jDZ/wA "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a = current hour
b => // b = delta of hours
( //
a + b // 1) we compute the sum
- (a < -b) * 2 // and we subtract 2 if this sum is negative
// examples:
// 51 remains 51
// 23 remains 23
// -1 is turned into -3
) / 3 // 2) float division by 3
// examples:
// 51 is turned into 17
// 23 is turned into 7.666…
// -3 is turned back into -1
>> 3 // 3) right arithmetic shift by 3 on the integer part
// examples:
// 17 becomes 2
// 7.666… becomes 0
// -1 is unchanged
```
---
# JavaScript (ES6), 26 bytes
More straightforward, but less fun and 1 byte longer anyway.
Takes input as `(current)(delta)`.
```
a=>b=>Math.floor((a+b)/24)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i7J1s43sSRDLy0nP79IQyNRO0lT38hE839yfl5xfk6qXk5@ukaahpGxpoYukNBU0NdXMODClFRQMIRIGmKTBBqIR9IUImnEhc1OqE5dbFp1Tcxhsv8B "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
+:24
```
[Try it online!](https://tio.run/##y0rNyan8/1/bysjk////Rsb/o3WNjHUMdYxMdIxMdXSBlK6JeSwA "Jelly – Try It Online")
`+` add the arguments
`:24` integer divide by 24
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 6 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit infix function, taking current and delta as arguments.
```
⌊24÷⍨+
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1FPl5HJ4e2Peldo/0971DbhUW/fo76pnv6PupoPrTd@1DYRyAsOcgaSIR6ewf@NjBXSFHSNjLnADEMIZWQCpU25oPJQAV0TcwA "APL (Dyalog Unicode) – Try It Online")
`+` add the arguments
`24÷⍨` divide that by 24
`⌊` floor
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
+24÷
```
[Try it online](https://tio.run/##MzBNTDJM/f9f28jk8Pb//42MuXRNzAE) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfWXCf20jk8Pb/@v8j442MtbRNTKO1QExDCGUkQmUNoXQujABXRNzGMMiNhYA).
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
+24/ï
```
-6 bytes by porting [*@Adam*'s approach in his APL answer](https://codegolf.stackexchange.com/a/188816/52210).
[Try it online](https://tio.run/##yy9OTMpM/f9f28hE//D6//@NjLl0TcwB) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXCf20jE/3D6//r/I@ONjLW0TUyjtUBMQwhlJEJlDaF0LowAV0TcxjDIjYWAA).
**Explanation:**
```
+ # Sum the two (implicit) input-integers together
24÷ # Integer-divide this sum by 24
# (after which the result is output implicitly)
+ # Sum the two (implicit) input-integers together
24/ # Divide this sum by 24
ï # Floor
# (after which the result is output implicitly)
```
The legacy version of 05AB1E uses a Python compiler. When integer-dividing, it will always floor the integer, whether the integer it divides is positive or negative.
The new version of 05AB1E uses an Elixir compiler. When integer-dividing in the new version of 05AB1E, it will round towards 0 (so basically truncates the decimal digits after dividing). So this will floor for positive integers, but ceil for negative integers.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~20~~ 19 bytes
*Simple lambda:*
```
lambda*a:sum(a)//24
```
*-1 byte thanx to Jonathan Allan*
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSvRqrg0VyNRU1/fyOR/QVFmXolGmoaRsY6ukbGmJheSgCEq18gEjW@KytdFV6BrYq6p@R8A "Python 3 – Try It Online")
*Full program for **38 bytes**:*
```
print((int(input())+int(input()))//24)
```
[Answer]
# [R](https://www.r-project.org/), ~~28~~ 16 bytes
Just a port of most of the other answers...
-12 bytes thanks Giuseppe
```
sum(scan())%/%24
```
[Try it online!](https://tio.run/##K/r/v7g0V6M4OTFPQ1NTVV/VyOS/kTGXrpHxfwA "R – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~18~~ 16 bytes
```
((`div`24).).(+)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P81WQyMhJbMswchEU09TT0Nb839JanFJsYKtQrSGkbGOgq6RsaYOlwIQgLmGyBygHmSeKTJPF1VS18RcM5aLKzcxMw9odG5igW@8gkZBUWZeiZ5GaV5yaVFRpUKapqYC2PL/AA "Haskell – Try It Online")
If taking input as a list is allowed, this can be done in **13 bytes** (thanks cole):
```
(`div`24).sum
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P81WIyElsyzByERTr7g0939JanFJsYKtQrSGkbGOgq6RsaYOlwIQgLmGyBygDmSeKTJPF1VS18RcM5aLKzcxMw9odG5igW@8gkZBUWZeiV6apgLYyv8A "Haskell – Try It Online")
---
I've seen people leave off the function declaration in the byte count for pointfree style, so I'm doing the same here.
**Explanation:**
```
(`div`24)
```
`div` is the shorter integer division operator. Haskell has this nice syntactic sugar where you can curry infixes by putting the argument on its respective side of the infix (thanks mimi), so this is a function that does integer division by 24.
The double composition is a little weird to explain, so I'll follow the template of [this great SO answer](https://stackoverflow.com/a/26809612):
```
f a b = (`div`24) (a + b) -- what we want
f a b = (`div`24) ((+) a b) -- un-infixing (+)
f a b = ((`div`24) . ((+) a)) b -- definition of function composition (partially applying (+) onto a)
f a = ((`div`24) . ((+) a) -- pointfree reduction
f a = ((`div`24) .) ((+) a) -- associative property
f a = (((`div`24) .) . (+)) a -- definition of function composition
f = ((`div`24).) . (+) -- pointfree reduction
```
When this takes a list as input, the sum function only has one argument, so the extra composition isn't needed (since we don't have to do that extra curry).
[Answer]
# [Ohm v2](https://github.com/nickbclifford/Ohm), 4 bytes
```
+24v
```
[Try it online!](https://tio.run/##y8/INfr/X9vIpOz/fyNjLl0jEwA "Ohm v2 – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 26 bytes
```
a=>b=>Math.Floor((a+b)/24)
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5JfmpSTqoPMhlB2dmm2/xNt7ZJs7XwTSzL03HLy84s0NBK1kzT1jUw0/1tzhRdllqT6ZOalaqRpGBlraugCCU1rBX19BQMMOQUFQ6icIaYc0DjccqZQOSMs9sH06WJq1DUxh0v@BwA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 11 bytes
```
(*+*)div 24
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJZm@19DS1tLMyWzTMHI5L81V3FipUKagpGxjoKuifl/AA "Perl 6 – Try It Online")
Anonymous Whatever lambda that takes two arguments and returns the sum of the two integer divided by 24
[Answer]
# [Lua](https://www.lua.org), ~~32~~ 26 bytes
```
print((arg[1]+arg[2])//24)
```
[Try it online!](https://tio.run/##yylN/P@/oCgzr0RDI7EoPdowVhtEGcVq6usbmWj@///fyPi/rpERAA "Lua – Try It Online")
Rather boring solution. Take input as arguments, print to stdout. Require Lua 5.3 or greater.
# Old solution: [Lua](https://www.lua.org), 32 bytes
```
function(a,b)return(a+b)//24 end
```
[Try it online!](https://tio.run/##yylN/J9m@z@tNC@5JDM/TyNRJ0mzKLWktAjI1E7S1Nc3MlFIzUv5X1CUmVeikaZhZKyja2SsqcmFJGCIyjUyQeObovJ10RXomphrav4HAA "Lua – Try It Online")
Same idea, but implemented as function instead of full program.
[Answer]
# [Lua](https://www.lua.org), ~~70~~ 50 bytes
```
c,d=io.read():match("(%S+) (%S+)")print((c+d)//24)
```
*-20 bytes thanks to val*
[Try it online!](https://tio.run/##yylN/P@/2DYzX68oNTFFQ5MrWSfFttgqN7EkOUNDSSM6TidWW1MHSitpchUUZeaVaAClM/TScvLzizQ0krVTNPWNTDQ1//83MtYxMvkPAA "Lua – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
÷24+
```
[Try it online!](https://tio.run/##yygtzv6fm18e7HZkutujpsb/h7cbmWj///8/WsPIWEfXyFhTB8QwhFBGJlDaFELrwgR0Tcw1YwE "Husk – Try It Online") Nothing very original here.
[Answer]
# [I](https://github.com/mlochbaum/ILanguage), 6 bytes
Anonymous tacit infix function, taking current and delta as arguments.
```
+/24.m
```
[Try it online!](https://tio.run/##y/z/Xz1N3UpBW9/IRC/3v5ExkBdvZMwFZhhCKCMTKG3KBZWHCsSbmP8HAA "I – Try It Online")
Beginning with:
`+` the sum of the arguments
`/` divide by:
`24` twentyfour
`.` apply:
`m` floor (**m**inimum)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 41 bytes
```
\d+,?
$*
(1+)-\1
-
^((-)1|1{24})*.*
$2$#1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFW8eeS0WLS8NQW1M3xpBLlytOQ0NX07DGsNrIpFZTS0@LS8VIRdnw/38jYx1dI2MuIGUIIoxMwKQpF1gczNE1MQcA "Retina 0.8.2 – Try It Online") Link includes test suite. Explanation:
```
\d+,?
$*
```
Convert both inputs to unary and take the sum if the second input is positive.
```
(1+)-\1
-
```
But if the second input is negative then take the difference.
```
^((-)1|1{24})*.*
$2$#1
```
Floor divide the input by 24 and convert to decimal. For positive numbers the first alternation never matches so this just counts the number of whole multiples of 24 in the number. For negative numbers the leading `-1` counts as an extra negative multiple of 24 in addition to any remaining multiples of 24, thus achieving the desired floor division.
[Answer]
# [Python 2](https://docs.python.org/2/index.html), 18 bytes
```
lambda*a:sum(a)/24
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSvRqig1pTQ5VSMzr0QvPj4xJSU@XkchUVPfyOR/QRFQUCNNw8hYR9fIWFOTC0nAEJVrZILGN0Xl66Ir0DUx19T8DwA)
[Answer]
# Perl 5 (`-MPOSIX=floor -MList::Util=sum -alp`), 19 bytes
```
$_=floor+(sum@F)/24
```
[TIO](https://tio.run/##K0gtyjH9/18l3jYtJz@/SFujuDTXwU1T38jk/38jYwVdI2MuIGUIIoxMwKQpF1gczNE1Mf@XX1CSmZ9X/F/XN8A/2DMCYg6Q55NZXGJlFVqSmWMLNPO/bmJOAQA)
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 49 bytes
```
[S S S N
_Push_0][S N
S _Duplicate_0][T N
T T _Read_STDIN_as_integer][T T T _Retrieve_input][S S S N
_Push_0][S N
S _Duplicate_0][T N
T T _Read_STDIN_as_integer][T T T _Retrieve_input][T S S S _Add][S S S T T S S S N
_Push_24][T S T S _integer_division][T N
S T _Print_as_integer]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
[Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIObk4QQCVB@ICAUSYUwEIgVL//xsZc@mamAMA) (with raw spaces, tabs, and new-lines only).
**Explanation in pseudo-code:**
```
Integer a = STDIN as integer
Integer b = STDIN as integer
a = a + b
a = a integer-divided by 24
Print a as integer to STDOUT
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 12 bytes
```
: f + 24 / ;
```
[Try it online!](https://tio.run/##NYxBCoAwEAPvvmLwKluxKoKCfxGlenOpis@vLcVDmCSEuNPfh@wuIYQRR4XtqJliUOz2KNe7KIYW4zElyEwZhzbl1TMVtkWiNJmGzHiS2WfKX0g3oOED "Forth (gforth) – Try It Online")
### Code Explanation
```
: f \ start a new word definition
+ \ add current hour and delta
24 / \ (integer) divide result by 24, round towards negative infinity
; \ end word definition
```
[Answer]
# [PHP](https://php.net/), 29 bytes
```
<?=floor((date(G)+$argn)/24);
```
[Try it online!](https://tio.run/##K8go@P/fxt42LSc/v0hDIyWxJFXDXVNbJbEoPU9T38hE0/r/fyOTf/kFJZn5ecX/dd0A "PHP – Try It Online")
Full program, with `current hour` being the current hour on the platform host, and `delta of hours` input via `STDIN`.
**Or**
# [PHP](https://php.net/), 30 bytes
```
<?=floor(array_sum($argv)/24);
```
[Try it online!](https://tio.run/##K8go@P/fxt42LSc/v0gjsagosTK@uDRXQyWxKL1MU9/IRNP6////Rsb/dU3MAQ "PHP – Try It Online")
Input of `current hour` and `delta of hours` via command line.
] |
[Question]
[
What is the shortest C expression that is defined to evaluated to false the first time and true for every time after that:
Reference implementation:
```
bool b = false; // you get this for free.
(b ? true : b = true, false) // only this line is measured.
```
[Answer]
### 3 chars:
As Keith Randall suggested in a comment, if we can use floats or doubles, this should do the trick:
```
float b = 0; // free
b++
```
Eventually, as `b` is incremented repeatedly, two things may happen: either the addition overflows (and thus evaluates to `HUGE_VAL`, which may be infinite or a large positive value) or, more likely, the roundoff step size simply grows larger than one, turning the increment into a no-op. In either case, the expression should continue to evaluate as true.
[Answer]
**6 characters**
```
int i = 0; //free
i||i++
```
OTOH: I like Peter Taylor's solution as it has no branch so it may be faster (depending on compiler details).
p.s. I came up with that after posting the question (honest!).
[Answer]
With:
```
long long b = 0;
```
then three characters are enough for many applications:
```
b++
```
Evaluates false first and true for a long time thereafter ;-)
[Answer]
**7 characters**
As Peter Taylor suggested, still `int a = 2;`
```
!(a/=2)
```
**8 characters (old)**
Start with `int a = 2;`
```
!(a>>=1)
```
Another version of this: `int b = 0x40000000;`
```
!(b<<=1)
```
[Answer]
## 9 chars:
```
b=0;//free
(b&(b=1))
```
at least if it's valid c (not undefined behavior)
## 12 chars
```
(b?b:!(b=1))
```
this is valid c
[Answer]
```
int b=1; // for free
!b|(b=0)
```
bit-wise or works as well since in first trial `0|0` yields 0 and in other trials `!0|0` yields `!0` which is guaranteed to be true. It is also ANSI-compliant, I've tried the following code with GCC 4.6.1 with `-ansi` flag:
```
#include <stdio.h>
main () {
int b=1, i=0;
for (;i<5;++i)
printf ("%d",!b|(b=0));
}
```
[Answer]
### ~~11~~ 10 chars
I can't beat the three char approach, but make it different:
```
int b = 0; // free
b?b:0*(b=1) // 11 characters
b||0*(b=1) // one character less thanks to breadbox
```
[Answer]
## APL (5 or 6)
If I'm only allowed to initialize the variable to 0, it's 6 characters:
```
A←0 ⍝ free
⊃A←⍴⍴A
```
How it works: `⍴A` is the size of A (which is the empty list the first time around, because `0` is a scalar), so `⍴⍴A` is the size of the size of A (which is `[0]` the first time, because a one-dimensional empty list has zero values in one dimension). This is then assigned to A (`A←`) and the first element is returned (`⊃`).
1. `A` is `0`, `⍴A` is `[]`, then `A` is set to `⍴⍴A` which is `[0]`, and the first element is returned (`0`).
2. `A` is `[0]`, `⍴A` is `[1]`, then `A` is set to `⍴⍴A` which is `[1]`, and the first element is returned (`1`).
3. `A` is `[1]`, so `⍴A` remains `[1]`, so `A` is set to `⍴⍴A` which remains `[1]` and it returns `1`.
If I'm allowed to initialise the variable to anything I want, I can set it to the empty list and drop one of the `⍴`s to make it 5 characters:
```
A←⍬ ⍝ free, set to empty list
⊃A←⍴A
```
[Answer]
**9 chars**
```
b=1; //free
!b||(b=0)
```
*edited: no longer undefined behavior*
[Answer]
```
bool b = false; // for free?
b = b?b:!b;
```
[Answer]
What about this:
```
bool b = false;
!b+b++
```
[Answer]
# 1 Character
Since you didn't specify which compiler and/or which command line options are to be used, here's my 1 character solution:
```
bool b = false;
X
```
Compile with
```
gcc -DX='(b ? true : b = true, false)'
```
] |
[Question]
[
**This is not a duplicate of [Sum of combinations with repetition](https://codegolf.stackexchange.com/questions/155938/sum-of-combinations-with-repetition). This question considers `1+2` to be the same as `2+1`. The other question doesn't.**
---
[OEIS link - A000008](https://oeis.org/A000008)
---
## Background
If you have 4 types of coins (1, 2, 5 and 10 cents), in how many ways can you make an amount?
There are 4 ways of making 5 cents:
* 1 + 1 + 1 + 1 + 1
* 1 + 1 + 1 + 2
* 1 + 2 + 2
* 5
Note: 1 + 2 + 2 and 2 + 2 + 1 are considered to be the same in this challenge.
## Your task
* Take an input. It will be a positive integer. This is the amount (in cents).
* Work out the number of ways to make that number from 1, 2, 5 and 10 cent coins.
* This is a [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge, so any form of output is allowed.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
[Answer]
# JavaScript (ES6), 41 bytes
*Saved 3 bytes thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs)*
```
f=(n,k=10)=>n?k*n>0&&f(n,k>>1)+f(n-k,k):1
```
[Try it online!](https://tio.run/##FYxBDoIwEADvvGIPhHQtmNajuPUrNEiNluwaMF6avr2W22Qymbf/@X3eXp/vwPJYSgmkuI9kDZLjezyxM10XDuecRV1piH3Eqy1BNsVAYEZguBFcDtAaITUAs/Au63Je5akmr9rEGWvbpjrAPGGTyx8 "JavaScript (Node.js) – Try It Online")
### 40 bytes
*Suggested by [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)*
[Returns *true*](https://codegolf.meta.stackexchange.com/a/9067/58563) for \$f(0)\$.
```
f=(n,k=10)=>n>0?k&&f(n,k>>1)+f(n-k,k):!n
```
[Try it online!](https://tio.run/##FYxBCoMwEADvvmILIlmiJfZYu@lXDNaUNrJbVLyEvD2Nt2EY5usOt03r57d3LK85Z0@K20C9QbJszTM0jT@NtT3qQl1oA94vnL2sioHADMDwILidoDVCrAAm4U2W@brIW41O1ZETlraO5YBpxCrlPw "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
k = 10 // k = current coin value
) => //
n ? // if n is not equal to 0:
k * n > 0 && // if k is not equal to 0 and n is positive:
f(n, k >> 1) + // do a recursive call where k is updated to the
// next coin value
f(n - k, k) // do a recursive call where k is subtracted from n
: // else:
1 // increment the number of solutions
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~12~~ ~~8~~ 7 bytes
```
Ṅ₀$ḊvΠ∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuYTigoAk4biKds6g4oiRIiwiIiwiNSJd)
6 bytes with s flag
## Explained
```
Ṅ₀$ḊvΠ∑
Ṅ # Integer partitions of the input
₀$Ḋ # Does each item in each partition divide 10?
vΠ # Product of each partition
‚àë # Sum that
```
[Answer]
# [HOPS](https://akc.is/hops/), 20 bytes
```
mset(x+x^2+x^5+x^10)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kI7-geG20kq5uQVFqsq2RgVLsgqWlJWm6Fltyi1NLNCq0K-KMgNgUiA0NNCFSUBULoDQA)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes
```
Length[{1,2,5,10}~FrobeniusSolve~#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773yc1L70kI7raUMdIx1TH0KC2zq0oPyk1L7O0ODg/pyy1TjlW7X9AUWZeiYJDerRp7P//AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Regex `üêá` ([RME](https://github.com/Davidebyzero/RegexMathEngine/) / Perl / PCRE / Raku`:P5`), 24 bytes
```
^x*(xx)*(x{5})*(x{10})*$
```
Takes its input in unary, as the length of a string of `x`s. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.)
[Try it on replit.com!](https://replit.com/@Davidebyzero/regex-Ordered-coin-partitions) - RegexMathEngine
[Try it online!](https://tio.run/##RU/BTsMwDL3vK6LImpK13ZpJvSzN2knjyokbjGhUmxQpbCUpUlEIRz6AT@RHiluQuNh@z8/2c3tythie3wg4SYK9NkdLYCURqnK/u9tt4@x8dQy8ymW5lTwQc0bEQ@vMpSP04UJlJLVVvrWmYzSjqX998h2O6DQTqeCnl1FU/bM58nwDmstxl8eLR1fbcs1Dbe/FQWHMDzLOCJkumz8CTKkmAVZJwgM0aIkw2tMeDFcfK1ZtwHFWVSFJoEnzyMc//Hw@WZ2c4htCkl/rYJaUfH9@EbqEBoXv2IpR65vbvdbDY79gfc8xhCJOSeDCBQxDnol18QM "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##hVXrTttIFP6fpzi4u2QmcboxFRWKMYiGSCC1UKVB2y1lLWOPk1GdsWWPG6Di7z5AH7EPsuyZSxJDIq0F9lzO@c7tOydxUfSmcfz0KmEpFww@DsejvXB4eToKry7OJ@Gf56eTMzhoveIizuqEwWERl2zv9eyoFc@iEsLi@gYCGDvvFotvt2/qv@7vP09mbxcz8vT3XYfc3VF8/dh/1B@vj9/fnuhLWceFThGERdfzG4YqWXIxVZbWZzzHUxbNjzbkjlpcSChwKUNWlnlJ4lxUErSXnTmrqmjKKPyoZDIYxCgBh4dgj9VSnzORZD6UTNalAM9/3MBU@zhPmAu3eZ5BHqRRVilYbcbCXe/tv73xW4APT4HohIVTZjFCK0UMDjEZvxqenYwPOtReulDxB5anZOX4H8uThjylVFtRD8nh2AQR57WEAawCpSo8R6uB9mAAzovgtbLjoJbzVTh0lY80q6uZiWSVlNZjqxYVnwqWQJaLqXlFolqw0tcJm9@HcZRl6IaN3e7C2yyPv0EnduF7zhPoJJGMMHcqSWoJQQBE3XTo7hqDWuxud1WZvq3MPOKCIIB2sLhGImRMkIL2vJug75sQDDugiAOHHA8cH1fdoDAfh5LjIf7vUDyvEfHNXiixqKir4Ke40NBNIC6KWip1HRiWEDolW@7nkYxnoY6ls14btJJVdSZdUwLfNtqn8y8jfZKmFcNLjBdDmMrZM4FO/p3FErVsJbDhlvbnBc8YsaT49HEypkX8Og7RWUJdi/FlNL4MJ6Pxh/OLk8nodHk8@jwZXZyq/a72yX6tJ326ZvBOiQS0uW92g35buUbowUY2QtxHkoVpmc/DIpKSlYKUyPKLq/fvLUBTB1tXsjuJSVyugm33FpZsoGAEKwouIdwGL91tPHsJYExlfM6bID2P@g2hhBXyf4VKFtdlxXOxVVCbTfMS9HR5WDEXJ0aGI5mYRubCNdyj/pLxujyoIvqYnkjmnGiBZfmx/sJzocgrvDY3OOIT0u61rVH1CE/lFmV2gibPBwOhDo@34EJXy3fBozgwRH@NZWatMifYwuyuhdf1bnwcNnPMBKlcaN@1lWOYoAovb4KG/ioJPBCqBw8D4fnQ7fJmxEtSPlBAp5QR0v4qMCRMHUprfqbE@T2BX//8BPxp4XhlRgg61rBmekk15XN2aWI2Owqd5tgQ@m/NaVzbMlJ/wzmDe9iH3V1rYyewXTceX47Di8sPJ5PhGX2mqOnXaK/lxJBlzV7YYPirs6G7nv44v23EWya5eh5b6/e2xkpLxsg6vs2GNgKrPW1ORHOJM2M1sE0k@NPx1O95e/v/xmkWTaunXqaVegf/AQ "C++ (gcc) – Try It Online") - PCRE
[Try it online!](https://tio.run/##K0gtyjH7X1qcquDr7@ftGmmt4Brm6KMQGF2cWKmgEq@joKTwqG2SgpKOgraGhnqFeoVKvGZdXa5VaoVVgKl@rEKdgoptWmZeZnEGkBkYra@pkJZfpBBnbmYda80FlfkfV6GlUVGhCSSqTWvBlKEBkFb5/x8A "Perl 6 – Try It Online") - Raku
---
It's also possible to use [Arnauld's algorithm](https://codegolf.stackexchange.com/a/251682/17216), but only for inputs \$‚â• 10\$ (because captures are the only kind of variable available, and can only be taken from the input). Even using lookinto, this is pretty long at **42 bytes** (and would be longer using variable-length lookbehind):
```
^(?|(?^1=(x+)\1){0,3}\1|^(?=(x{10}))){2,}$
```
[Try it on replit.com!](https://replit.com/@Davidebyzero/regex-Ordered-coin-partitions-with-fancy-algorithm) - RegexMathEngine
```
^ # tail = input number
(?|
(?^1=(x+)\1) # Assert \1 is set; \1 = floor(\1 / 2);
# assert the resulting \1 ‚â• 1
{0,3} # Iterate the above 0 to 3 times
\1 # tail -= \1
| # or
^(?=(x{10})) # If on the first iteration, \1 = 10. This can be
# matched multiple times in a row, as long as nothing
# has been subtracted from tail yet, but that would
# result in a non-match when exiting this loop.
){2,} # Iterate the above at least 2 times, with no maximum.
# This allows the first alternative to get a chance to
# match after the second alternative, which is zero-
# width, has matched.
$ # Assert tail == 0
```
That can be made to work with all inputs by extending it to 49 bytes: `^(?|(?^1=(x+)\1){0,3}\1|^(?=((x{5}|x)\2?)|)){2,}$` - but this defeats the purpose of the 42 byte version in the first place, because if \$10\$ is not the only constant specified, you might as well go with the 24 byte version.
But it is possible to use this algorithm in its pure form (with no constants specified other than \$10\$ and \$\lfloor\log\_2{10}\rfloor\$) in such a way that works for all inputs, by capturing \$10\$ in binary (**89 bytes**):
`^(?|(?=(?=(\2))(?=(\3))(\4)()){0,3}(\1\2\2\3{4}\4{8})(?!.*$\5)|^(?=(?=()(x))()(x)|)){2,}$`
[Attempt This Online!](https://ato.pxeger.com/run?1=hVbLbttGFF0W0FeMmdSekShXlO3AEE0Lri3ABhI7UGQ0iaUQNDmUBqGGBDmMn9r2A7LNppss80Hpsr_RTe88JNGWgFISOY97z33MuZf69iPMkrKQP38chj-urGaShTltN_et0c_-i4jGjFP09rjfa_vHFyc9__L8bOD_cXYyOEX7tReMh0kZUXSglLYnh7VwEuTIz65GyEN96_ebm8_XO-WHu7v3g8mrmwn-Xoq4uf_zwyfcfcRdT36HbULUcweew12CCXlo2TszPHSGbfjsPOzOhrsP-zOQ2tiuvxzukcdPRpfgW1CS90fQatuzl9rA37_8S57btmxUzzw_azhuxfFC5IyPpefLNZbCKg2mhytyhzXGBcpgKHya52mOw5QXAqmo61NaFMGYEvRQiKjTCUECHRwgsyyHap3yKHFRTkWZc-S4sxVMOQ_TiNroOk0TlHpxkBQSVpkxcFftvVcjt4bgYjHC6gD8MTUYvpHCGgfrE7w8Pj3q79eJ2bRRwe5pGuOF47_NVyryhBBlRV44RV0dRJiWAnXQIlAiw7OUGlIedJD1LHilbFmgZQ25RRb5iIF9Ex3JIim1Wa3kBRtzGqEk5WN9C3hxQ3NXJWx654dBkoAbJnYz86-TNPyM6qGNvqQsQvUoEAHkTiZJDpHnISx36mRziUEMdqOxOJmWOZlpwDgGAOVgdgVESCjHGWk6I6_l6hA0O1AWehbudiwXRg0v0w8LeHssuUtgvQTEnbYv4FBBV8KPYaCgq0CMZ6WQ6iowOEJUz-l8Pg1EOPFVLPXlWKPltCgTYesjcE3hvjv72FMrcVxQ2IR4IYSxmDwRqKdfaChAy5wEFPDc_jRjCcWGFO_eDvokC7dDH5zFxDYYH3v9C3_Q6785Oz8a9E7my733g975iZxvKp_M03jSIksGb-RAQJP7ajWou5GrhO6tZMOHeSCoH-fp1M8CIWjOcQ4sP798_doAVHWgdAW9FZDE-chbt29g8QoKRLCg4BzCrvDSXsez5wDaVMKmrArSdIhbEYpoJv5XKKdhmRcs5WsFldk4zZHqLvcL5kLHSKDFY13IjNuae8SdM14dD6jwFqQnECnDSmB-_HD-3LFRlhawrXfglRHhreaWMSov7sjcgsyGV-V5p8PlYncNLmoo-QZyCDQM3lpi6V4rzXF6o2dX3Gk4IxeazRQygQsbbd1uSccgQQVsjryK_iIJzOOyBg887rio0WDViOekvCcInJJG8NaQQ0iQOpBW_Iyx9WuE_vnzK4JXC4Mt3ULAsYo1XUuyKJ-ySxGzWlHgNIOCUN8lp2FsjpG4K85p3IMW2tw0NjY8U3X9_kXfP794czQ4PiVPFBX9KuU17xgiL-kzGxTeOiu6y-4P_dtEvKaTy2tWW97XFVacU4qX8a0WtBZYzEm1I-pN6BmLhq0jgVeH_g_w1_dW02nv6cl_ "C++ (GCC) - Attempt This Online") - PCRE2 v10.40+
[Try it on replit.com](https://replit.com/@Davidebyzero/regex-Ordered-coin-partitions-with-binary-algorithm) - RegexMathEngine in PCRE mode
```
^ # tail = N = input number
(?| # Branch reset group - capture group numbering of each
# alternative starts at the same number, in this case \1.
(?=
# coinValue /= 2, where coinValue is defined as \1 + \2*2 + \3*4 + \4*8
(?=(\2)) # \1 = \2
(?=(\3)) # \2 = \3
(\4)() # \3 = \4; \4 = 0
){0,3} # maximum number of iterations is floor(log(10) / log(2))
( # \5 = coinValue; tail -= \5
\1
\2\2
\3{4}
\4{8}
)
(?!.*$\5) # Assert \5 != 0
|
^ # Only take this alternative on the first iteration (or, as
# explained below, also the 2nd iteration, if N==0)
# coinValue = 10
(?= # Atomic lookahead
# This can only match if tail ‚â• 1
(?=()(x)) # \1 = 0; \2 = 1
()(x) # \3 = 0; \4 = 1
| # or...
# Do nothing, if tail == 0; in this case, the 2nd iteration of the
# outer loop will also end up taking this alternative, and there will
# be exactly one way N==0 can result in a match.
)
){2,} # An enforced minimum of 2 iterations is necessary, because
# the first iteration always has zero width, and would cause
# the loop to end otherwise. (In Perl, not even this trick
# can force a loop to take more than one zero-width
# iteration.)
$ # Assert that tail == 0
```
For compatibility with old versions of PCRE2, it is necessary to use a 93 byte version of this:
[Try it online!](https://tio.run/##hVXrTttIFP6fpzi4XZhJHDYOUKEYgyhEAqmFKg3abgm1jD1OrDpjyx6Xa/7uA@wj7oMse@aSxJBI60T2eOac79y@cxzmeXschi/vIhYnnMGXk0G/659cnvb9q4vzof/H@enwDPYb7xIeplXE4CAPC9bdnhw2wklQgJ9f34AHA@vj3d3P253qz4eHb8PJh7sJeflBjp7JUY8ceWTUpVQ9d8xzlxJK6VPH3pmRkTPq4m/naXc22n3an6HExnbz/WiPPv@Qwvin5B4V5f0Ztbr27P0LfWvQsqGZe37ectyat6UoEj6W7i73kgx3WTA9XJE7bCRcQI5L4bOiyAoSZrwUoEJtTllZBmNG4akUUa8XogQcHIDZlku1z3iUulAwURUcHHe2ginfwyxiNtxmWQqZFwdpKWGVGQN33d37cOM2AK8kBqKy7o@ZwfCNFNE4RJft6uTseLDfpObQhjJ5ZFlMFo7/Pt@pyWMdlBV5kQyOdBBhVgnowSJQKsOzlBooD3pgvQleKVsWalkjbtFFPuK0Kic6kkVSGrNGxctkzFkEacbH@hbw8o4VrkrY9MEPgzRFN0zs5s2/TbPwJzRDG35lSQTNKBAB5k4mSS7B84DIkybdXGJQg91qLSrTMZWZBgknCKAczK@RCCnjJKdt58bruDoEzQ7IQ89CRlsurlperh8W8vVEcpbifoWIO11fYFFRV8KPcaGg60AJzysh1VVgWEJoFmz@Pg1EOPFVLM3lWqMVrKxSYesSuKZbv55/76udOC4ZHmK8GMJYTF4JNLNfLBSoZSqBXTu3P82TlBFDiq9fhgOah9uhj84SahuM7/3BpT/sDz6fXxwP@6fz7f63Yf/iVL5vKp/M03jSoUsGbxRIQJP7ejeou5Grhe6tZMPH90AwPy6yqZ8HQrCCkwJZfnH16ZMBqOtg6wp2LzCJ85W37tzAkhUUjGBBwTmEXeOlvY5nbwG0qTSZJnWQtkPdmlDEcvG/QgULq6JMMr5WUJmNswLUdHlcMBcnRopznehGTrituUfdOeNVeVCFdzA9gcgSogTm5cf6c8eGPCvxWJ/gdyIiW@0tY1Re3JG5RZkNr87zXo/LzaM1uNBS8i1wKA4M3lli6VkrzXF2p9@uudNyblwcNlPMBClt2Lrfko5hgko8vPFq@oskJB6XPXjgcceFViupRzwn5SMFdEoaIVsjjiFh6lBa8TMm1m8R/PPX34CflgSP9AhBx2rWdC/JpnzNLkXMekeh0wk2hPovOY1rU0bqrjincQ86sLlpbGx4pusGg8uBf3H5@Xh4ckZfKSr61dprPjFEUbE3Nhh@dVZ0l9Mf57eJeM0kl9essbyva6y4YIws41ttaC2weKf1iagPcWYsBraOBD8dL5220937N4zTYFy@tFOl1N7/Dw "C++ (gcc) – Try It Online") - PCRE2 v10.33
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Œṗḍ⁵ẠƇL
```
A monadic Link that accepts a positive integer and yields a positive integer.
**[Try it online!](https://tio.run/##ASIA3f9qZWxsef//xZLhuZfhuI3igbXhuqDGh0z/LMOHKUf//zI1 "Jelly – Try It Online")**
### How?
```
Œṗḍ⁵ẠƇL - Link: integer, Cents e.g. 4
Œṗ - integer partitions of Cents [[1,1,1,1],[1,1,2],[1,3],[2,2],[4]]
⁵ - ten 10
ḍ - divides? (vectorises) [[1,1,1,1],[1,1,1],[1,0],[1,1],[0]]
Ƈ - keep those for which:
Ạ - all? [[1,1,1,1],[1,1,1], [1,1] ]
L - length 3
```
[Answer]
# [Python](https://python.org), ~~111~~ ~~106~~ 65 bytes
```
f=lambda s,n=4:s==0 or s>=0<n and f(s,n-1)+f(s-(1,2,5,10)[n-1],n)
```
[Try it online!](https://tio.run/##FYk7CoAwEAWvsuUGV0j8NOJ6EbGIhKCgazCx8PQxvmIY5oU3bZe0OXs@7Lk6C5GEuyEya7huiBPrUcCKA4/lqo2qitRoqKGejFZzaQuJyuHeJaHHn7uEJ6Eqy/0H "Python 3 – Try It Online")
-5 thanks to Jo King
-41 thanks to Kevin Cruijssen
[Answer]
# [Python 2](https://docs.python.org/2/), 49 bytes
```
f=lambda n,k=10:k*n>0and f(n-k,k)+f(n,k/2)or n==0
```
[Try it online!](https://tio.run/##FcsxDoAgEATA3ldcKXpGoDTBv2AQNaeLITa@HqWbZu732RNsKdGd/lqCJ7A4oyfpMGuPQLHFICyq/8EyWpUywTldYgUdoOyxra1ha9TU0J0PPHWp8gE "Python 2 – Try It Online")
Conveniently, we can iterate through the count value by starting at 10 and floor-dividing by 2 to get `10->5->2->1` and terminating at 0.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
Nθ⊞υ⁰F9410FυF‹κθ⊞υ⁺κ⊕ιI№υθ
```
[Try it online!](https://tio.run/##NYxNCsIwEIX3niJ0NQMVKuhCunRVEOkVYhxpMU3aScbrjzHo5v3B99xk2UXrVYewSr7JcieGDfvdKGkCaU1X8jOygeZ8PHQNmlrk51dKCV6t2RDNnxi91G0IjmmhkOkBM@L3k@eQ4WJTkSglSiWxVz3p/u0/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `n`.
```
⊞υ⁰
```
Start with `0` as a possible amount.
```
F9410
```
Loop over the digits `9`, `4`, `1`, and `0`, which will later be incremented to represent the coins `10`, `5`, `2` and `1`.
```
Fυ
```
Loop over each possible amount discovered so far.
```
F‹κθ
```
If this amount is less than `n`, then...
```
⊞υ⁺κ⊕ι
```
... add the current coin to the amount, and record this as a new possible amount. This then allows it to be considered again as a possible amount for the current coin, until the value reaches or exceeds `n`.
```
I№υθ
```
Count the number of times `n` was reached.
Example for `n=5`:
* Start with `0` as an amount.
* Add `10` to that, resulting in a new amount of `10`. This amount is now more than `5`, so it is ignored.
* Add `5` to the `0` amount, resulting in a new amount of `5`. This amount is also ignored for now.
* Add `2` to the `0` amount, resulting in a new amount of `2`.
* Add `2` to the `2` amount, resulting in a new amount of `4`.
* Add `2` to the `4` amount, resulting in a new amount of `6`. This amount is now more than `5`, so it is ignored.
* Add `1` to the `0`, `2` and `4` amounts, resulting in new amounts of `1`, `3` and `5`. The `5` amount is ignored for now.
* Add `1` to the `1` and `3` amounts, resulting in new amounts of `2` and `4`.
* Add `1` to the `2` and `4` amounts, resulting in new amounts of `3` and `5`.
* Add `1` to the `3` amount, resulting in a new amount of `4`.
* Add `1` to the `4` amount, resulting in a new amount of `5`.
* There are no more coins, so the final count of `5`s is `4` as desired.
* The `4` `5`s correspond to the sums `5`, `2+2+1`, `2+1+1+1` and `1+1+1+1+1` respectively.
The coins are considered in descending order for efficiency but the algorithm would work with the coins in any order.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
√Ö≈ì íT√ës√•P}g
```
[Try it online.](https://tio.run/##yy9OTMpM/f//cOvRyacmhRyeWHx4aUBt@v//pgA)
A modification of [Mr.Xcoder's 05AB1E answer in the related challenge](https://codegolf.stackexchange.com/a/155963/52210) would be 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage) longer (and way slower):
```
TÑIиæ€{ÙOI¢
```
[Try it online.](https://tio.run/##AR0A4v9vc2FiaWX//1TDkUnQuMOm4oKse8OZT0nCov//Mw) (Too slow for TIO for \$n\ge4\$.)
**Explanation:**
```
Ŝ # Get all lists of positive integers that sum to the (implicit) input
í # Filter this list of lists by:
# (implicitly push the current list)
TÑ # Push the divisors of 10: [1,2,5,10]
s # Swap so the current list is at the top of the stack
å # Check for each value whether it's in list [1,2,5,10]
P # Check if it's truthy for all of them by taking the product
}g # After the filter: pop and push the length
# (which is output implicitly as result)
TÑ # Push list [1,2,5,10]
I–∏ # Repeat it the input amount of times: [1,2,5,10,1,2,5,10,...]
√¶ # Get the powerset of this list
€{ # Sort each inner list
√ô # Uniquify the list of lists
O # Sum each inner list
I¢ # Count how many times the input occurs in the list
# (which is output implicitly as result)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 46 bytes
```
f=->n,k=10{n<0||k<1?0:n<1?1:f[n-k,k]+f[n,k/2]}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y5PJ9vW0KA6z8agpibbxtDewCoPSBpapUXn6WbrZMdqAxk62fpGsbX/CxQ0DPT0jAw09XITCzTU0jT/AwA "Ruby – Try It Online")
Shamelessly inspired by Arnauld's Javascript answer.
[Answer]
# [Desmos](https://desmos.com/calculator), 76 bytes
```
f(n)=1+‚àë_{k=1}^{n^4}0^{(n-‚àë_{j=1}^4[1,2,5,10][j]mod(floor(nk/n^j),n))^2}
```
Inspired by [@fireflame](https://codegolf.stackexchange.com/users/68261/fireflame241)'s [Desmos answer](https://codegolf.stackexchange.com/questions/141163/how-many-partitions-do-i-have/251099#251099) to [How many partitions do I have?](https://codegolf.stackexchange.com/questions/141163/how-many-partitions-do-i-have/)
[Try It On Desmos!](https://www.desmos.com/calculator/y4t9oyj46s)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/r0bzaicaxm)
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 66 bytes
```
N+K+M:-K*N>0,N-K+K+Q,N+K//2+W,M is Q+W;N=:=0,M=1;M=0.
N+M:-N+10+M.
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/30/bW9vXStdby8/OQMdP1xvIDdQBCurrG2mH6/gqZBYrBGqHW/vZWtka6PjaGlr72hrocfmB9PhpGxpo@@r9/28Eorj0AA "Prolog (SWI) – Try It Online")
Port of xnor's Python answer.
[Answer]
# [Scala](https://www.scala-lang.org/), 131 bytes
Golfed version. [Try it online!](https://tio.run/##NU7BasMwDL33Kx6lB4u54BR28ZpBjz1sl7JTKcXLnNZLqmS2LyPk2zOldAIhPT1J76XKtW7qPr99lfHmAmOYvnyNWrHdc9a9Pfifo3SnUhpV6I1@1oUhmtlSse7p5nJ1HSqXvDL6TOVr8XIHZ/0eWoHmHzbWNkkGQZ5vGzLwbfKz0rp5cE8CtNRxAmYXNzGkXLwki12M7vd4yDHw5UQWHxwySgwLSNRdhGJs1yiQO2wMPQigl4PcskrLXq2Y5GQ1iAqNS7pvjIs5x@kP)
```
def f(n:Int,p:Seq[Int]=Seq(1,2,5,10)):Int=(n,p)match{case(0,_)=>1;case(_,Nil)=>0;case(_,k::ks)=>if(n<k)0 else f(n-k,k::ks)+f(n,ks)}
```
Ungolfed version. [Try it online!](https://tio.run/##bZHBa8IwGMXv/hUP8ZCwCK0wGEUH3jbYdtl2EpFvsdWsbRqaMBjSv71LYzupGEgO773vkfxiJRXUttXXdyodXklpnCbAPs1AUbcemE7wrB0PJ1bBBn6ogKyUtl55UdaxWGAhcC8QR3wSIl2HYblNQmDjp7cC5bjM217jKMnJY18NSLIp2E4g4hjW6hHxyH5ThcCOX@xoZOdIEuT2g/qYylBiifxG0j6ltL@K953mhltijrPKcRcSvc5DbXN@vWEBj4Du5CB2QEpPmFF98FTWdU2/m3dXK33YeiKfWl34ZlUNprGcI4arsPAkBjrGD7hCMzs1bKa5H5md/v@KN9PhGt1u2vYP)
```
object Main {
def a000008(n: Int): Int = {
val coins = List(1, 2, 5, 10)
def p(ks: List[Int], m: Int): Int = (ks, m) match {
case (_, 0) => 1
case (Nil, _) => 0
case (k :: ksTail, _) if m < k => 0
case (ksHead :: ksTail, _) => p(ksHead :: ksTail, m - ksHead) + p(ksTail, m)
}
p(coins, n)
}
def main(args: Array[String]): Unit = {
for (n <- 1 to 20) {
println(s"p($n) = ${a000008(n)}")
}
}
}
```
] |
[Question]
[
You should a program in language X, which will only output its source code (i.e function as a quine) when it is not a monday. On monday it should output some string with a levehnstein distance of 4 from the source code. i.e if the code is aaaa on sunday it should output aaaa and on monday it could output ....aaaa or bbbb or cccc or ..aaaa.. etc
---
Read about Levehnstein difference here <https://en.wikipedia.org/wiki/Levenshtein_distance>
---
Rules
- Your solution must be testable
- No cheating quines, and any other standard loopholes allowed
- Should your language "X" lack access to the date it may assume its a random date at the cost of 35 bytes
- This is code golf and I will accept the shortest solution (in bytes) as winner
[Answer]
# Javascript - ~~47~~ ~~45~~ ~~43~~ ~~42~~ ~~34~~ ~~32~~ 29 bytes
*8 bytes saved thanks to @Downgoat.*
*5 bytes saved thanks to @Dendrobium.*
```
f=_=>(Date()[0]!="M"&&"f=")+f
```
[Answer]
# Jolf, ~~19~~ ~~13~~ 9 bytes
```
?wfb+q~2q
```
[Try it online.](http://conorobrien-foxx.github.io/Jolf/)
Saved quite a few bytes thanks to Conor.
```
?wfb+q~2q
?wfb+q~2q
? if
wfb the current weekday - 1 (which is 0 on Monday) is truthy
+q~2 print the program's source code with 1000 appended to it
else
q print the program's source code
```
[Answer]
## CJam, ~~18~~ 17 bytes
```
{"_~"et7=({\}|}_~
```
[Test it here.](http://cjam.aditsu.net/#code=%7B%22_~%22et7%3D(%7B%5C%7D%7C%7D_~)
On Mondays, it prints:
```
_~{"_~"et7=({\}|}
```
Dennis found a 16-byte solution which will break in the year 10,000 though:
```
{"_~"et_7=1=<}_~
```
On Mondays, this prints
```
{"_~"et_7=1=<}_~2016
```
... or whatever the current year is.
[Answer]
# Mathematica, 75 bytes
```
StringJoin[If[DayName[] == Monday, "0001", ""], ToString[#0, InputForm]] &
```
Anonymous function, takes no inputs and returns the output. Replace `Monday` with `Friday` (or whatever the current day is) to test.
[Answer]
# [Vitsy](http://esolangs.org/wiki/Vitsy) + bash, ~~29~~ 26 bytes
```
'&"etad","M"-)[Y4\a]?rd3*Z
' Take a string of everything until hitting another '.
This will wrap around as it finds none.
& Create a new stack and push the current stack over.
"etad" Push the string "date" to the stack.
, Execute the current stack through shell.
"M"- Subtract the character "M" from the first item of the
current stack.
)[ ] If it is equal to zero, do the stuff in brackets.
Y Remove the current stack.
4\a Push the return character to the stack four times.
? Rotate over a stack (if there is none, stay put).
r Reverse the stack.
d3* Push the character ' to the stack.
Z Print everything in the current stack.
```
This cannot be tried online as it accesses shell, however, feel free to test this with the downloadable interpreter found [here](https://github.com/VTCAKAVSMoACE/Vitsy).
Note that this is a variant of the standard quine, `'rd3*Z`.
[Answer]
## Batch, 128 bytes
```
@set/am=%date:~3,2%,a=(14-m)/12,y=%date:~6%-a,d=(%date:~0,2%+y+y/4-y/100+y/400+(m+47)*18/7+a*3)%%7
@if %d%==1 echo @:
@type %0
```
Since Windows XP, `date` doesn't give you the day of the week, so I must directly calculate it from the date. The leap year adjustment wants March-based years so `a` is used as an adjusting factor. `(m+47)*18/7` is quicker than using a month-based lookup table.
Note that you need to invoke the file using its full name (e.g. `monday.bat`). The `echo @:` counts as a distance of 4 because of the extra CR/LF; I used `@:` because the result is still a syntactically valid batch script.
[Answer]
# Java "Only" 2,897 bytes
Take a look at this monstrosity. Can someone help me test this on a monday, I cant figure out how to trick Java into thinking its monday.
```
import java.util.Calendar;public class Quine{public static void main(String[] args){char[] s={83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,105,109,112,111,114,116,32,106,97,118,97,46,117,116,105,108,46,67,97,108,101,110,100,97,114,59,112,117,98,108,105,99,32,99,108,97,115,115,32,81,117,105,110,101,123,112,117,98,108,105,99,32,115,116,97,116,105,99,32,118,111,105,100,32,109,97,105,110,40,83,116,114,105,110,103,91,93,32,97,114,103,115,41,123,34,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,99,104,97,114,91,93,32,115,61,123,34,41,59,102,111,114,40,105,110,116,32,105,61,48,59,105,60,115,46,108,101,110,103,116,104,45,49,59,105,43,43,41,123,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,40,105,110,116,41,115,91,105,93,43,34,44,34,41,59,125,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,40,105,110,116,41,115,91,115,46,108,101,110,103,116,104,45,49,93,43,34,125,59,34,41,59,102,111,114,40,99,104,97,114,32,99,58,32,115,41,123,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,99,41,59,125,105,102,40,67,97,108,101,110,100,97,114,46,103,101,116,73,110,115,116,97,110,99,101,40,41,46,103,101,116,40,55,41,61,61,50,41,123,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,109,111,110,100,34,41,59,125,125,125,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,105,109,112,111,114,116,32,106,97,118,97,46,117,116,105,108,46,67,97,108,101,110,100,97,114,59,112,117,98,108,105,99,32,99,108,97,115,115,32,81,117,105,110,101,123,112,117,98,108,105,99,32,115,116,97,116,105,99,32,118,111,105,100,32,109,97,105,110,40,83,116,114,105,110,103,91,93,32,97,114,103,115,41,123,34,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,99,104,97,114,91,93,32,115,61,123,34,41,59,102,111,114,40,105,110,116,32,105,61,48,59,105,60,115,46,108,101,110,103,116,104,45,49,59,105,43,43,41,123,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,40,105,110,116,41,115,91,105,93,43,34,44,34,41,59,125,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,40,105,110,116,41,115,91,115,46,108,101,110,103,116,104,45,49,93,43,34,125,59,34,41,59,102,111,114,40,99,104,97,114,32,99,58,32,115,41,123,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,99,41,59,125,105,102,40,67,97,108,101,110,100,97,114,46,103,101,116,73,110,115,116,97,110,99,101,40,41,46,103,101,116,40,55,41,61,61,50,41,123,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,109,111,110,100,34,41,59,125,125,125};System.out.print("import java.util.Calendar;public class Quine{public static void main(String[] args){");System.out.print("char[] s={");for(int i=0;i<s.length-1;i++){System.out.print((int)s[i]+",");}System.out.print((int)s[s.length-1]+"};");for(char c: s){System.out.print(c);}if(Calendar.getInstance().get(7)==2){System.out.print("mond");}}}
```
[Answer]
# GolfScript, ~~21~~ 20 + 35 = ~~56~~ 55 bytes (or ~~22 + 0 = 22~~ 20)
With randomizing, no input expected (following the rules completely):
```
{7rand 0=2*)".~"*}.~
```
Alternatively, date as input, in format like Javascript's `new Date().toString()` (bending the rules a little):
```
{\.,%"M"=2*)".~"*}.~
```
Each solution looks like this:
```
{somecode2*)".~"*}.~
{ } create a block
. duplicate it
~ execute one copy
somecode push 1 if monday or 0 otherwise
2* multiply by 2 (2 if monday, 0 otherwise)
) add 1 (3 if monday, 1 otherwise)
".~" the tail...
* ...copied 1 or 3 times and concatenated together
```
Now the stack looks like this:
```
.~ (or .~.~.~)
{somecode2*)".~"*}
```
... and is printed bottom to top.
The somecode part for random:
```
7rand 0=
7rand select a random number from 0 to 6, let 0 be monday
0= check if equal to 0 (1 if monday, 0 otherwise)
```
The somecode part for input:
```
\.,%"M"=
\ we have the input first and the block on top, so we need to swap them
. duplicate the input
, replace the second copy with its length
% get every (length)-th character starting from 0, effectively fetching first (M on mondays, something else otherwise)
"M"= check if equal to M (1 on mondays, 0 otherwise)
```
[Answer]
## Java, 334 characters
```
import java.util.Calendar;interface Q{static void main(String[]a){String p="import java.util.Calendar;interface Q{static void main(String[]a){String p=%c%s%1$c;System.out.printf(p,34,p);if(Calendar.getInstance().get(7)==2)System.out.print(0<1);}}";System.out.printf(p,34,p);if(Calendar.getInstance().get(7)==2)System.out.print(0<1);}}
```
Based on @RohanJhunjhunwala 's solution, just using the quine method from over [here](http://rosettacode.org/wiki/Quine#Java). The difference of four comes by appending true if it's monday. I think it should be possible to shorten that a bit.
[Answer]
# Reng v.5, noncompeting, 56 bytes
Version 5 brings to you object oriented programming!
```
"68¹65¹84¹69¹4&A3¹A1¹B6¹68¹97¹C1¹6Ó`1e4*{Xo}2[r*]rao! ;~
```
This is a standard quine. Simply, `"<code>rao! ;~` executes `<code>`, then outputs the programming, then exits.
`¹` is Manhattan addition, e.g., digit concatenation. This gives the char codes of `DATE`, then `4&` retrieves the date from the date module. (Equivalently, `"DATE"4&`.) This pushes a date object. (While it looks like it should be easily retrievable from the display in the stack, this is just how it prints in the stack display. It is unable to be manipulated.)
The next series provides another pseudo string, translating to `getDay`. Then, we get the property `getDay` of the date object on the stack using `6Ó`. We then execute it with ```. This provides JS's `getDay`. When it's `1`, it's monday. We check for equality with `1` using `1e`, then multiply by four. `{Xo}` pushes a code block that prints (`o`) char 33 (`X`), or `!`. `2[r` creates a new stack with the top two items in reverse order. Then, we repeat (`*`) the code block 4 times (when monday) or 0 times (any other day). On monday, it prints 4 `!`s. Otherwise, it prints nothing. Then the string captured by wraparound is printed, and we have the rest of our source.
Output on monday:
```
!!!!68¹65¹84¹69¹4&A3¹A1¹B6¹68¹97¹C1¹6Ó`1e4*{Xo}2[r*]rao! ;~
```
On other days:
```
68¹65¹84¹69¹4&A3¹A1¹B6¹68¹97¹C1¹6Ó`1e4*{Xo}2[r*]rao! ;~
```
] |
[Question]
[
My teacher gave me a simple problem which I should solve with a code tiny as possible. I should print all odd numbers from 0 to 100000 into a HTML document using javascript.
```
for(var y = 0; y < 100000; y++){
if(!(y % 2 == 0)){
document.write(y + " ");
}
};
```
Is it possible to do that shorter?
[Answer]
# JavaScript, 38 bytes
Yet another way to do this, shortest of all.
This supposedly prints each number on a new line using `\n`. Now as the data is being written to an HTML document, `\n` is not of any use and the numbers appear to be separated by space only.
```
for(i=1;i<1e5;i+=2)document.writeln(i)
```
[Answer]
# Javascript, 36 bytes
If order doesn't matter:
```
for(i=1e5;i--;)document.writeln(i--)
```
Writes the numbers in reverse order.
[Answer]
another way to do it in 38 bytes:
```
for(i=0;i<5e4;)document.writeln(i+++i)
```
explanation:`i+++i` means the same as `(i++)+i`, with the second `i` resolving to its new value (as effected by the ++) so it goes like this for the results:
* 0+1=`1`
* 1+2=`3`
* 2+3=`5`
etc...
[Answer]
# JavaScript, 40 bytes
```
for(i=1;i<1e5;i+=2)document.write(i+" ")
```
The code is fairly straight forward.
* I iterate from `i=1` to `i=1e5`. `1e5` is nothing but `1` followed by 5 `0`, so `100000`.
* In each iteration step, I print the value of `i` and increment `i` by `2`. Thus printing only every other number starting from `1` and till `100000`.
This prints all the odd numbers from `1` to `100000`.
[Answer]
# JavaScript, 40 bytes
Another way to do it!
```
for(i=0;i<5e4;)document.writeln(2*++i-1)
```
The code is fairly straight forward.
* Iterate from `i = 0` to `i = 5e4`. `5e4` is nothing but `5` followed by 4 `0`, so `50000`.
* In each iteration step, print the value of `2*i - 1` after incrementing `i` by `1`. Thus printing only odd numbers from `1` to `99999`.
[Answer]
**Using while** 42
```
i=-1;while((i+=2)<10e5)document.writeln(i)
```
] |
[Question]
[
…without using any operator/function besides addition (`+`), subtraction (`-`), multiplication (`*`), division (`/`), modulo (`%`), exponent/power `pow()` or any of the standard C bitwise operators (`<<, >>, ~, &, |, ^`) or unary operators (`—, ++`) or assignment/comparison operators (`=, ==`).
If these symbols represent a different operation in your chosen language, go with the spirit of the question and don't use them.
Rules:
* You cannot use any mathematical functions your language might offer (Mathematica, looking at you.)
* You cannot use any operator besides the bitwise operators or the arithmetic operators listed above.
* Your output should be a float and be correct to at least 2 decimal places when truncated/rounded.
* You can use constants your language's **standard libraries** might provide.
* You can hardcode the values, but your program should work correctly for all floats (up to 2 decimal places) between `0` and `2π`;
This is code-golf, so the shortest answer wins.
Example:
```
Input: 3.141592653 / 2
Output: 1.00xxxxxx…
```
Please also post an ungolfed version of your code.
[Answer]
## Python 83 69
*Based on [Bhaskara I's sine approximation formula](http://en.wikipedia.org/wiki/Bhaskara_I%27s_sine_approximation_formula)*
**Implementation**
```
def f(x):p=3.14;x,s=x%p,(4,-4,4)[int(x/p)];return s/(12.34/x/(p-x)-1)
```
**Ungolfed**
```
def apxsine(radian):
pi = 3.14 # Approximate to 2 decimal places
sign = (4,-4,4)[radian % pi]
return sign / (12.34/radian/(pi - radian) - 1))
```
**Deduction**

**Demo**
```
>>> from math import pi, sin
>>> any(round(abs(f(e) - sin(e)), 2) for e in (e/180.*pi for e in range(0,360)))
False
```
JUst realized that if I would have opted for [Euler's formula](http://en.wikipedia.org/wiki/Euler%27s_formula) route, the code would be shorter (49 characters). But then it uses Complex numbers and am not sure if the call to the real method would be valid in the current question context.
```
f=lambda x:((2.72**(x*1j)-2.72**(-x*1j))/2j).real
```
[Answer]
## MATLAB 35
Too bad `e` is not a constant in Matlab. That would have saved me 10 characters. I will see if I can come up with a solution for this.
```
@(x)(2.7183^(x*i)-2.7183^(-x*i))/2i
```
[Answer]
# Javascript 114 77
Using Taylor Series expansion at 0:
```
function s(y){
var p=2*Math.PI,
// z = sign (y)
z=(y>0?1:-1),
// x = (abs(y) mod 2 PI - PI) * sign(y) => put x in [-PI, PI] range
x=-z*((z*y)%p-p/2),
// u = x^2
u=x*x;
// return Taylor Expansion
return x*(1-(1-(1-(1-u/72)*u/42)*u/20)*u/6);
}
```
Golfed (114):
```
function s(y){var z=(y>0?1:-1),p=2*Math.PI,x=-z*((z*y)%p-p/2),u=x*x; return x*(1-(1-(1-(1-u/72)*u/42)*u/20)*u/6);}
```
**Edit**
"Improved" for y in [0,2PI], golfed (77) :
```
function s(y){var x=3.14-y,u=x*x;return x*(1-(1-(1-(1-u/72)*u/42)*u/20)*u/6)}
```
Another version for more precision (varying k) :
```
function s(y){
var p=2*Math.PI,
// z = sign (y)
z=(y>0?1:-1),
// x = (abs(y) mod 2 PI - PI) * sign(y) => put x in [-PI, PI] range
x=-z*((z*y)%p-p/2),
// u = x^2
u=x*x,
// k = 2* expansion level +1
k=9,
// r = 1 initial value
r = 1;
// Taylor Expansion
// while k > 1
for(;k>1;) {
r= 1 - r*u /k--/k--;
}
return x*r;
}
```
Golfed (114):
```
function s(y){var z=(y>0?1:-1),p=2*Math.PI,x=-z*((z*y)%p-p/2),u=x*x,k=9,r=1;for(;k>1;)r=1-r*u/k--/k--;return x*r;}
```
[Answer]
# APL - 21
```
{|{.5×⍵-+⍵}0J1*⍵÷○.5}
```
This uses the fact that `sin pi*x/2 = Im[(-1)^x]`.
[Example test on ngn APL](http://ngn.github.io/apl/web/#code=%7B%7C%7B.5%D7%u2375-+%u2375%7D0J1*%u2375%F7%u25CB2%7D%203.1415926535%D72)
Previous answer: 26
```
{-/((×\9⍴⍵)÷×\1+⍳9)[2×⍳5]}
```
This uses the Taylor/Maclaurin series up to 9th term.
[Example test on ngn APL](http://ngn.github.io/apl/web/#code=%7B-/%28%28%D7%5C9%u2374%u2375%29%F7%D7%5C1+%u23739%29%5B2%D7%u23735%5D%7D%203.1415926535%F72)
Note about operators: only operators used were `/\⍴⍳` which don't have anything to do with arithmetic, and are mostly list manipulation tools, `○` which is *multiply by pi*, and `+-×÷*` which are permitted by the rules
[Answer]
# C++ 80 68(excluding white-spaces + edit)
### GOLFED
```
float S(float x){float z=x*x,y=x*(5040-(840+(42-z)*z)*z)/5040;return y;}
```
### UNGOLFED
both versions are different so that, it is easy to get output.
```
#include<iostream>
int main()
{
float x,y,z;
for(;;)
{
std::cin>>x;
z=x*x;
y=(x*(5040-840*z+42*z-z*z*z))/5040;
std::cout<<y<<'\n';
}
}
```
### Output
```
1.047197 ((pie)/3)
0.865096 (sin((pie)/3) = 1.73201/2 = 0.8660)
```
[Answer]
## Javascript (56)
```
j=x=+prompt(r=0);for(i=1;i<99;j*=x/++i)r+=i&1?i&2?-j:j:0
```
[Taylor series](http://en.wikipedia.org/wiki/Taylor_series) used here.
`x` is the input value, `r` is the result, `j` contains `x^i/i!`
The result is output in console.
```
x=prompt();
r=0;
j=1;
for(i=1;i<99;i++) {
j=j*x/i;
if (i%2) {
if (i%4 == 1) r+=j;
else r-=j;
}
}
alert(r);
```
If evaluation is needed for input (for example `3.141592653 / 2`) :
```
j=x=eval(prompt(r=0));for(i=1;i<99;j*=x/++i)r+=i&1?i&2?-j:j:0
```
[Answer]
## Haskell
```
import Prelude hiding (sin)
import Data.Complex
sin x=(\(_:+y) -> y) $ exp (0 :+ x)
```
Uses Euler's formula. `(y :+ z)=y+zi` I think.
[Answer]
# Python, 70 bytes
Using sin(x) = Im(exp(ix)) and the series for the exponential function:
```
def s(x):
s,f=0,1
for i in range(1,50):f*=1j*x/i;s+=f
return s.imag
```
Note that `imag` is not a function here, strictly speaking.
Ungolfed:
```
def s(x):
s = 0
f = 1
for i in range(1,50):
f *= 1j*x/i
s += f
return s.imag
```
[Answer]
### R, 80 chars
```
f=function(x){a=seq(1,99,2);sum((-1)^(0:49)*(x^a)/sapply(mapply(`:`,1,a),prod))}
```
Uses [Taylor approximation](http://www.math.utah.edu/~kitchen/1220F06/sine.html) at an order of 99.
`sapply` and `mapply` are just functions to vectorize the operation, while `sum` and `prod` are just vectorized `+` and `*`.
```
> b=seq(0,2*pi,1e5)
> all((f(b)-sin(b))<.01)
[1] TRUE
```
If the `*apply` functions are a problem, here is a solution at 91 characters:
```
f=function(x){a=0:100;b=c();for(i in 1:50)b[i]=(-1)^(i-1)*(x^a[2*i])/prod(1:a[2*i]);sum(b)}
```
[Answer]
# C 70
This one is not only golf but also useful in microcontrollers without floating point instructions or math libraries:
```
float S(float a){float x,y=1,h=1e-4;while(x+=h*(y-=h*x),(a-=h)>0);return x;}
```
Of course, the majority of the characters is taken by these annoyingly long type declarations and return. If the function declaration doesn't count, it's much shorter. If we take the value by pointer and overwrite it (removing the return statement), we get 71 characters.
```
S(float*x){float a=*x,y=1,h=1e-4;*x=0;while(*x+=h*(y-=h**x),(a-=h)>0);}
```
However, it complains about default return value.
EDIT: 70, for is shorter:
```
S(float*x){float a=*x,y=1,h=1e-4;*x=0;for(;(a-=h)>0;*x+=h*(y-=h**x));}
```
EDIT2: forgot ungolfed version
```
float fake_sin(float a){
float x=0,y=1;
float h=1e-4;//adjust for accuracy
while(a>0){
y-=h*x;
x+=h*y;
a-=h;
}
return x;//return y for cosine or y/x for tangent
}
```
It takes arbitrary positive angle, but doesn't work for negative.
[Answer]
## Java - 108 / 81
```
float s(float p){for(float q=p-=3.14,d=p=-p,i=1,m=1;i<11;)p+=(q*=d*d)/(m*=++i*++i)*(((int)i&2)-1);return p;}
```
Without the function declaration, it's just doing `p = sin(p)`:
```
for(float q=p-=3.14,d=p=-p,i=1,m=1;i<11;)p+=(q*=d*d)/(m*=++i*++i)*(((int)i&2)-1);
```
The error is max ±0.00201 in the range 0..2π, much worse in either direction.
Ungolfed:
```
float s(float p) {
for (float q = p -= 3.14, d = p = -p, i = 1, m = 1; i < 11;)
p += (q *= d * d) / (m *= ++i * ++i) * (((int)i & 2) - 1);
return p;
}
```
Unobfuscated:
```
float sin(double ph) {
float [] dividers = {-1, 6, -120, 5040, -362880, 39916800L};
ph -= Math.PI;
double d = 0;
for (int i = 0; i < 6; i++)
d += Math.pow(ph, i * 2 + 1) / dividers[i];
return d;
}
```
[Answer]
# C# - 115 103
This code uses an approximation of [Maclaurin series](http://en.wikipedia.org/wiki/Taylor_series#List_of_Maclaurin_series_of_some_common_functions) calculation of the sine of x, and is accurate to 7 decimal places.
`float x=0;for(int i=1;i<96;i+=2){float n=i,d=1,p=a;while(n>1){d*=n;n--;p*=a;}x+=((i+1)%4==0?-1:1)*p/d;}`
Where `a` is the input in radians.
Here's the code with whitespaces:
```
float x = 0; for (int i = 1; i < 96; i += 2)
{
float n = i, d = 1, p = a;
while (n > 1)
{
d *= n;
n--;
p *= a;
}
x += ((i+1)%4==0?-1:1)*p / d;
}
```
[Answer]
# TI-84 BASIC, 21 bytes
```
(e^(iAns)-e^(⁻iAns))/2i
```
[Answer]
# Perl 6, ~~17~~ 16 bytes
```
{(e**(i*$_)).im}
```
[Answer]
# Axiom, 139 bytes
```
s(x:Float):Complex Float==(digits()>20=>%i;x>2*%pi=>s(x-2*%pi);x< -2*%pi=>s(x+2*%pi);imag(reduce(+,[(%i*x)^k/factorial(k)for k in 0..40])))
```
I see this formula in the other solutions and I inplemented it in Axiom...
The formula i follow is this:
```
+oo
----
\ (i*x)^k
sin(x)=ImPart(e^(i*x))=imPart( / -------- )
----k k!
0
```
ungolf
```
sin1(x:Float):Complex Float==
digits()>20=>%i
x> 2*%pi =>sin1(x-2*%pi)
x< -2*%pi =>sin1(x+2*%pi)
imag(reduce(+,[(%i*x)^k/factorial(k)for k in 0..40]))
```
there is some problem for the last 2 digits each number; some test cases:
```
(79) -> [-23, numeric(sin(-23)), s(-23) ]
(79) [- 23.0,0.8462204041 7517063524,0.8462204041 7517063514]
Type: List Complex Float
(80) -> [ 23, numeric(sin( 23)), s( 23) ]
(80) [23.0,- 0.8462204041 7517063524,- 0.8462204041 7517063536]
Type: List Complex Float
(81) -> [[x/2,numeric(sin(x/2)),s(x/2)] for x in 0..(7*2)]
(81)
1
[[0,0.0,0.0], [-,0.4794255386 0420300027,0.4794255386 0420300027],
2
[1,0.8414709848 0789650665,0.8414709848 0789650665],
3
[-,0.9974949866 0405443094,0.9974949866 0405443093],
2
[2,0.9092974268 256816954,0.9092974268 256816954],
5
[-,0.5984721441 0395649405,0.5984721441 0395649405],
2
[3,0.1411200080 598672221,0.1411200080 5986722208],
7
[-,- 0.3507832276 8961984812,- 0.3507832276 8961984817],
2
[4,- 0.7568024953 0792825138,- 0.7568024953 0792825139],
9
[-,- 0.9775301176 6509705539,- 0.9775301176 6509705545],
2
[5,- 0.9589242746 6313846889,- 0.9589242746 6313846888],
11
[--,- 0.7055403255 7039190623,- 0.7055403255 7039190626],
2
[6,- 0.2794154981 9892587281,- 0.2794154981 9892587545],
13
[--,0.2151199880 878155243,0.2151199880 878155243],
2
[7,0.6569865987 187890904,0.6569865987 1878909041]]
Type: List List Any
```
] |
[Question]
[
**This question already has answers here**:
[Reimplement the wc coreutil](/questions/74222/reimplement-the-wc-coreutil)
(23 answers)
Closed 7 years ago.
Write a stripped down version of the wc command. The program can simply open a file which does not need to be configurable or read from stdin until it encounters the end of file. When the program is finished reading, it should print:
* # bytes read
* # characters read
* # lines read
* max line length
* # words read
Program must at least work with ascii but bonus points if it works on other encodings.
Shortest code wins.
[Answer]
## Haskell - 80 characters
```
l=length
main=interact$ \s->show$map($s)[l,l,l.lines,maximum.map l.lines,l.words]
```
[Answer]
# Perl - 71
```
$c+=$x=y!!!c,$w+=split,$m=$m<$x?$x-1:$m,$l++for<>;say"$c,$c,$l,$m,$w"
```
I think it can be shortened further but I don't know how.
(edit: used Zaid's suggestion)
(edit 2: changed `length` to `y!!!c`)
(edit 3: changed `print` to `say`)
[Answer]
## c -- 214
Implementation is almost right out of K&R. Relies on K&R semantics for main (unspecified return type), but I think it otherwise conforms to c89. Output format is specified below (but it assumes that chars == bytes).
```
#include <stdio.h>
int b,w,l,t,L;main(int c,char**v){FILE*f=fopen(v[1],"r");for(;(c=getc(f))
!=-1;++b){t++;if(c=='\n')l++,L=t>L?t:L,t=0;else if(c==' '||c=='\t')w++;}
L=t>L?t:L;printf("%d (%d) %d %d %d\n",l,L,w,b,b);}
```
There is some ambiguity in the meaning of "words" as yet. This version defines words as breaking only on `'[ \t\n]` and does not account for a word that ends with EOF. This will work for files following the old unix convention of always ending with a newline, but break for those that stop hard on EOF.
It *does* test lines that end of EOF for maximal length.
## Un-golfed
```
#include <stdio.h>
int b, /* bytes */
w, /* words */
l, /* lines */
t, /*this line*/
L; /* longest line */
main(int c,char**v){
FILE*f=fopen(v[1],"r");
for(;(c=getc(f))!=-1;++b){
t++;
if(c=='\n') l++, L = t>L ? t : L, t=0;
else if(c==' '||c=='\t')w++;
}
L = t>L ? t : L;
/* Output format is lines (max line length) words chars bytes */
printf("%d (%d) %d %d %d\n",l,L,w,b,b);
}
```
## Validation
```
$ gcc -o wc wordcount_golf.c
$ ./wc wordcount.c
17 (67) 82 410 410
$ ./wc wordcount_golf.c
4 (74) 9 217 217
$ wc wordcount.c
17 67 410 wordcount.c
$ wc wordcount_golf.c
4 13 217 wordcount_golf.c
```
[Answer]
# ruby (72 characters)
```
t=readlines;s=t*'';p [s.size]*2+[t.size,t.map(&:size).max,s.split.size]
```
This solution uses a functional style similar to trinithis's Haskell solution.
I assume ASCII text and space-separated words.
[Answer]
# awk - 58
```
awk 'x=1+length{w+=NF;if(m<x)m=x;c+=x}END{print NR,w,c,m}'
```
[Answer]
# Groovy, ~~85~~ 81
```
a={it.size()};[s=a(t=f.text),s,a(z=t.split"\n"),z*.size().max(),a(t.split(/\s/))]
```
[Answer]
# Perl - 66 characters
```
for(<>){$t+=$l=y!!!c,$m=$l-1if$m<$l,$w+=split}say"$. $w $t $m $t"
```
I managed to save a couple of bytes by letting Perl handle the number of lines, using the $. variable. Other than that, even without looking, I ended up with what Marinus got, for the most part.
Here's the program I used to verify it:
```
#!/bin/bash
function test1() {
cat <<EOF
Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Duis eget
neque vel ipsum porta bibendum
dictum in ante. Ut accumsan
magna id nisl bibendum et
tincidunt turpis eleifend. Duis nec
mi hendrerit lorem hendrerit convallis.
Quisque sit amet tincidunt diam.
Sed vehicula velit sed risus
pellentesque vitae auctor nisi semper.
Nulla erat massa, semper sit
amet luctus non, bibendum id
eros. Etiam non lacus odio.
Donec vitae nisl vitae nisi
elementum suscipit. Cras ut mollis
mauris.
EOF
}
function test2() {
cat <<EOF
Curabitur quis elit turpis. Vestibulum
ut elementum magna. Lorem ipsum
dolor sit amet, consectetur adipiscing
elit. Nam sit amet quam
ante. Nullam in risus est,
quis cursus magna. Vestibulum feugiat
nisl nec velit scelerisque molestie.
Pellentesque habitant morbi tristique senectus
et netus et malesuada fames
ac turpis egestas. Vestibulum feugiat
sem vitae mauris aliquet eget
ullamcorper velit molestie.
EOF
}
function test3() {
cat <<EOF
Proin diam elit, imperdiet id
gravida et, facilisis nec lectus.
Nullam placerat enim sed nulla
porttitor hendrerit. Praesent eu quam
enim, et commodo orci. Nam
eu purus ut ipsum malesuada
rhoncus vitae ut turpis. Morbi
a risus eu ligula faucibus
tincidunt. Cum sociis natoque penatibus
et magnis dis parturient montes,
nascetur ridiculus mus. Nulla faucibus
vehicula diam at tempus. Aliquam
tristique, erat vel fringilla scelerisque,
magna purus venenatis nulla, at
elementum mi lectus vitae nibh.
Phasellus nibh neque, tempus commodo
pretium eget, gravida quis felis.
Vivamus venenatis tristique volutpat. Nunc
vulputate accumsan magna, sit amet
vehicula orci imperdiet vel. Nam
vitae laoreet purus.
EOF
}
PROG1=wc
PROG2='perl5.14.2 -Mv5.10 wc-golfed.pl'
for((i=1;i<4;i++)); do
wc=( $(test$i | $PROG1) )
golf=( $(test$i | $PROG2) )
for((j=0;j<2;j++)); do
if [ ! ${wc[$j]} = ${golf[$j]} ]; then
echo "Test #$i failed"
echo " wc: ${wc[@]}"
echo " golf: ${golf[@]}"
continue 2
fi
done
echo "Test #$i passed"
done
```
[Answer]
## C - 164 chars
This is based on dmckee's code with FUZxxl's improvements, but shortened further and converted to standard C. The code reads from standard input only. Any sequence of one or more consecutive characters with ASCII code >= 33 is counted as a word.
```
#include<stdio.h>
int b,w,l,t,L,c,s;int main(void){for(;c=getchar()+1;++b)t-=c==11?l++,t>L?L=t:t:-1,s=c>33?w+=!s:0;printf("%d %d %d %d\n",l,t>L?t:L,w,b);return 0;}
```
## Un-golfed
```
#include <stdio.h>
int b, /* bytes */
w, /* words */
l, /* lines */
t, /* this line */
L, /* longest line */
c, /* current character */
s; /* s==1 if the current word has been counted */
int main(void) {
for (; c = getchar()+1; ++b)
t -= (c==11 ? (l++, (t>L ? L=t : t))
: -1),
s = (c>33 ? w += !s
: 0);
printf("%d %d %d %d\n", l, (t>L ? t : L), w, b);
return 0;
}
```
[Answer]
# R, 91 characters
**Golfed**
```
x=scan(w="c",se="\n");n=nchar(x);sum(n);length(x);max(n);sum(sapply(strsplit(x," "),length))
```
**Ungolfed**
```
x=scan(what="c",sep="\n")
n=nchar(x)
num.char=sum(n)
num.lines=length(x)
max.line.length=max(n)
word.count=sum(sapply(strsplit(x," "),length))
```
**Output**
```
> x=scan(what="c",sep="\n");n=nchar(x);sum(n);length(x);max(n);sum(sapply(strsplit(x," "),length))
1: This is a test
2: of how well
3: the program works!
4:
Read 3 items
[1] 43
[1] 3
[1] 18
[1] 10
```
**Alternatives**
```
x=scan(w="c",se="\n");n=nchar(x);sum(n);length(x);max(n);length(unlist(gregexpr("\\w+",x)))
```
Saves a character at the expense of not really matching everything.
[Answer]
## Javscript (runs in Rhino) - 213 chars
The java file i/o calls take up a lot of space. But I didn't realize you call java so easily from javascript and thought that was pretty neat:
```
var r=new BufferedReader(new FileReader(f));var s=true;var n=0,l=0,m=0,w=0;while(s){s=r.readLine();if(s){n+=s.length();l+=1;m=m<s.length()?s.length():m;w+=s.split("\\s+").length;}}print(n+','+n+','+l+','+m+','+w);
```
### Ungolfed:
```
var reader = new BufferedReader( new FileReader(filename) );
var s = true;
var n=0,l=0,m=0,w=0;
while (s) {
s = reader.readLine();
if (s) {
n+=s.length();
l+=1;
m = m<s.length()?s.length():m;
w += s.split("\\s+").length;
}
}
System.out.println('bytes/chars: '+n+', Lines: '+l+', Max Line: '+m+', Words: '+w);
```
[Answer]
**Python 160**
Your file name is assigned to variable q.
```
g=len
z=open(q,'r')
w=z.read()
z.close()
b,e,f=g(w),g(w.replace('\n',' ').split()),w.split('\n')
d,c,a=g(max(f)),g(f),g(open(q,'rb').read())
for i in 'abcde':
print eval(i)
```
This prints the 5 requirements in order:
bytes read
characters read
lines read
max line length
words read
(TyrantWaves suggestion implemented)
[Answer]
# K, 40
```
{a:0:x;(#a;+/b;max b:#:'a;+/#:'" "\:'a)}
```
Prints linecount, char count, max line length, word count.
Words are space-separated.
[Answer]
## Python, 98
```
l=len
f=open(q).read()
j=f.split("\n")
for i in (l(f),l(f),l(j),max(j,key=l),l(f.split())):print i
```
98 is including newlines. Do newlines count?
[Answer]
## PHP, 163
```
<?$f=file($argv[1]);$l=0;foreach($f as$i)$l=$l<strlen($i)?strlen($i):$l;$n=count($f);$c=strlen($g=implode($f));$w=count(explode(' ',$g))+$n-1;echo"$c $c $n $l $w";
```
] |
[Question]
[
Word equations, but not as you know it! Given a sentence which will include two numbers, numerically, and a spelt operator, in the order seen in the examples, your goal is to give the numerical answer
The operators will be spelt as: "add", "minus", "times" and "divide"
Any ~~real number~~ integer may be used, as suggested by [caird](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) and [Jonathan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)
The solution must take one input and give one output
**Examples**:
```
Input: 7 add 8 Output: 15
Input: 9 times -2 Output: -18
Input: 24 divide 2 Output: 12
Input: 4 minus 5 Output: -1
```
You are not required to deal with divide by zero errors.
If you use a method that parses the expression, such as the python eval or exec, there will be no penalties, but if possible try to give a another interesting solution
**Scoring:**
Fewest bytes will win
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
Ḣ€Oị2¦“×+ _÷”V
```
[Try it online!](https://tio.run/##y0rNyan8///hjkWPmtb4P9zdbXRo2aOGOYenayvEH97@qGFu2P/D7UcnPdw5QzPy//9oLs5ocx0F9cSUFHUdBYtYHSDfEsgvycxNLQaK6BqBhYxMgGIpmWWZKalAQYgYSCg3M68UpMwUKBILAA "Jelly – Try It Online")
Takes input as e.g. `[7, 'add', 8]`. Requires no leading `0` for floats (e.g. `-.5` instead of `-0.5`)
## How it works
```
Ḣ€Oị2¦“×+ _÷”V - Main link. Takes a list [l, op, r]
Ḣ€ - First of each.
O - Convert to ordinal
2¦ - To the element at the 2nd index (the op):
ị “×+ _÷” - Index into the string “×+ _÷”
V - Evaluate as Jelly
```
For example, consider `[7, 'add', 8]`. Getting the `Ḣ`ead of a number leaves it as is in Jelly, so `Ḣ€` turns this into `[7, 'a', 8]`. We then get the char code of each. Again, `O` leaves numbers as they are, so this maps it to `[7, 97, 8]`. We then change only the second element by indexing into `“×+ _÷”`. Jelly indexing is modular, so we get the \$97 \bmod 5\$th element of this list (i.e. the second, or `+`). This yields `[7, '+', 8]`, which we then concatenate into a string `7+8` and evaluate as Jelly.
Consider:
| Input operator | First character | Ordinal | \$\bmod 5\$ | Index into `“×+ _÷”` |
| --- | --- | --- | --- | --- |
| `add` | `a` | 97 | 2 | `+` |
| `times` | `t` | 116 | 1 | `×` |
| `minus` | `m` | 109 | 4 | `_` |
| `divide` | `d` | 100 | 0 | `÷` |
Note that `0` maps to `÷` as 1-indexed modular indexing means that `0` is the last element
[Answer]
# [Factor](https://factorcode.org/), 53 bytes
```
[ first3 swap first 5 mod { / * + 0 - } nth execute ]
```
[Try it online!](https://tio.run/##Jc1NCsIwFATgvacYslSqUiv@HUDcuBFX4iI0rxpM05i8qrX07DXY3czHwBQy58r359PhuN8i0LMmm1PAjSx5afRXsq5swIO8JYNS8h3OE3PjvLaM3WjUYgUhlRJYo4ttA8G6pCCQpH9IMwilX1qRwCARSm3rOFmi6y8otA@8QHhLN@ToZaXQYoYxJpgjQQcbv@lDec2Ea5/BSudMg2lAbkj6/gc "Factor – Try It Online")
This is a port of @caird coinheringaahing's [Jelly solution](https://codegolf.stackexchange.com/a/235355/97916).
## Explanation:
It is a quotation (anonymous function) that takes a list of objects from the data stack as input and leaves an integer on the data stack as output. Assuming `{ 7 "add" 8 }` is on the data stack when this quotation is called...
* `first3` Put the first three elements of a sequence on the data stack.
**Stack:** `7 "add" 8`
* `swap` Swap the top two objects on the data stack.
**Stack:** `7 8 "add"`
* `first` Get the first element of a sequence. (In this case, get the first code point of the string "add".)
**Stack:** `7 8 97`
* `5 mod` Modulo 5.
**Stack:** `7 8 2`
* `{ / * + 0 - }` Push a sequence with the possible mathematical functions. `0` is a filler that will never be selected because 3 is not a possible index.
**Stack:** `7 8 2 { / * + 0 - }`
* `nth` Take an index and a sequence and return the object at that index.
**Stack:** `7 8 +`
* `execute` Execute a word that is on the data stack.
**Stack:** `15`
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~86~~ \$\cdots\$ ~~74~~ 73 bytes
```
m;a;b;f(){scanf("%d %c%*s%d",&a,&m,&b);m%=5;a=m?m-1?m-2?a-b:a+b:a*b:a/b;}
```
[Try it online!](https://tio.run/##ZVLRboIwFH3nK25IMIAlSpVM1zEfln3F9KG0RZutaCjbyAy/PtYKMjZJbtrec869vZyyaM9Y2ypCSUZyPzhrRovcdz0OHvNC7XEXTSiaKDTJAqK8NCE0VRsVxSbwhkbZPZ2aCE3MMtK0sqhAUVn4AZwdMB870DKESuhqDim4d0A5h5VL/oGxBddQSSU0RPgGxxbHS@DyQ3IBt4SFJSxByeJdQ3ID65edIZwv90Bdx27B3bJoOoW9v6hPglWCd5I4QRDFKwQxtptmXJkdBHsVZUd0t/Uz3tbrJxOJi2B8Xri9Lj@W4NsmsuCiNrI56bcPoOWXOOb@tX0w6xPhkCEwnV7Y1787GtLU6ga9EHZkwG03bVBj79@kMMlh1v@qU2ko9iUYOx7Bvge9LcxUFQKNhsFFmupdX7Zxmra31/l10hmZ5gz@fLP8je51G33@AA "C (gcc) – Try It Online")
*Saved a byte thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh)!!!*
Inputs the equation as a string from `stdin`.
Returns the value of the input equation.
### Allowing three parameters:
As allowed for untyped languages like this [PHP answer](https://codegolf.stackexchange.com/a/235411/9481).
# [C (gcc)](https://gcc.gnu.org/), ~~54~~ ~~52~~ 51 bytes
```
f(a,s,b)int*s;{a=(int[]){a/b,a*b,a+b,0,a-b}[*s%5];}
```
[Try it online!](https://tio.run/##bZFRb4IwEMff9ykuJJiCJQJK1DD2suxTKA@lLUoGaChsZISvPtYCMpxr0vR6v//d9a7UOlHadTEiWODISPLSFH5DAiStQ2g0ZBVhYsq9jLCNiRW1B1PoXui3nVRARpIcGdA8gVz0TAoTSi5KGwLQtkAYg53m/4GOgnsok4wLsNwH7iruboAlHwnj8ChYK8EGsiSvBHgPWBxCKWj6d@Ch4nC4w7Fuhwj1fl5fOS05G0IcD4Pl7DA4rjLaeWZ65vSdF4NQO9Zv7rHev8rtaRjm97U2xsWXAtQYZSHGaxlm@6P5DCL54pcY3cobq9FhTh4flstefZvurEmZa2i0F4T@xPuWJJ3a@k9AMbtzmFAFGUnTC0Vb2/hFQlCSx6jEms5ATwXoTMMLiiu8YMZ9SiFrxkihObkWksVI0@U3v4BKIo65nFaJQeBpoDwIRDiLigvOUTU62qe2@6ZxSk6isz5/AA "C (gcc) – Try It Online")
*Saved 2 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!*
*Saved a byte thanks to [Johan du Toit](https://codegolf.stackexchange.com/users/41374/johan-du-toit)!!!*
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~41~~ 38 bytes
```
$0=/a/?$1+$3:/t/?$1*$3:/v/?$1/$3:$1-$3
```
[Try it online!](https://tio.run/##SyzP/v9fxcBWP1HfXsVQW8XYSr8ExNICscpALH0gS8VQV8X4/39LS4WUzLLMlFQFSwA "AWK – Try It Online")
*Thanks to Dominic van Essen for the clue that cut 3 chars!*
```
$0= -- Override $0, prints automatically
/a/?$1+$3: -- If there's an "a" we add them
/t/?$1*$3: -- If there's a "t" it's multiplication
/v/?$1/$3: -- If there's a "v" it's division
$1-$3 -- It must be subtraction...
```
If we have to make sure it will print in the event the operation yields `0` then it would be 2 characters longer, like this.
```
1,$0=/a/?$1+$3:/t/?$1*$3:/v/?$1/$3:$1-$3
```
[Answer]
# [Python 2](https://docs.python.org/2/), 83 bytes
```
exec'print '+''.join([`x`,'/*+ -'[ord(str(x)[0])%5]][type(x)==str]for x in input())
```
[Try it online!](https://tio.run/##DchBCsMgEEDRq8ymjDa2DdIuc5JhIFAtnSxU7CSY01vhb94vp35z8r3HFt9YqiQFnBDvW5ZkaG2rw8d1ghtSrsH8tJpmaWZ7eTGTniUOL8v4/MkVGkgalV2Ntb2TfzrAIIeEiA48/wE "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 56 bytes
Expects a string.
```
s=>([a,[b],c]=s.split` `,{a:a-+-c,t:a*c,d:a/c,m:a-c}[b])
```
[Try it online!](https://tio.run/##XcxBCoMwEIXhfU8xZKVtohiUWsFeRASnk1giaqRJ3ZSePXUhXfiWj49/wBUdvczixWyVDn0dXH2PGuTNo@XU1i5xy2h8Bx3/YIXiIoj7Cs/EVYUp8Wn76LvhOJCdnR11Mtpn1EfsCqgUlAy2xTGkKWTF6WBu4M2kHQjJdiOy8ohkDsqsRmmQbA/Jo8lhMvPbQcHgHwo/ "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 43 bytes
Expects `[a, "operator", b]`.
```
([a,[b],c])=>({a:a+c,t:a*c,d:a/c,m:a-c})[b]
```
[Try it online!](https://tio.run/##XcxBDoIwEEDRvadoWLU6ldBIxCZ4EcJinBZTQ6kRZGM8ey0LYsJfv/wHzjjSyz0nOQRjY1dH3iA0txaoFfWVf1DjgWDSuCcwGnMCr1HSVyQTKQxj6O2xD3fe8eYMLENjMmAVS7VCsDxnRbnbuEtyk/N2TFKq1cmi2kJ1StK42RmbqFqHausW5t3wXoYl@w/jDw "JavaScript (Node.js) – Try It Online")
Or [**41 bytes**](https://tio.run/##XczRCoIwFIDh@55ieLXVWeJIsoG9SHRxOpsx0S3SvImefU2QIP/rj7/FCQd6uscofTA2NnXkCJfbFUjUZ/5GjTuCUeOWwGjMCXqNkj4ikUjBD6Gz@y7cecOPwDI0JgNWsZQQLM9ZUW7@1Smp0fV2SE6qRcmiWjF1SM64yRmboFpmaqVm1Dv/mmcl@83iFw) if we can take 3 distinct parameters as input (as suggested by Shaggy).
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 16 bytes
```
VaR+XL"/*+ -"@A_
```
Takes input as a single command-line argument. [Try it online!](https://tio.run/##K8gs@P8/LDFIO8JHSV9LW0FXycEx/v///5YKJZm5qcUKukYA "Pip – Try It Online")
### Explanation
Uses the same "character code mod 5" trick as several other answers.
```
a ; First command-line argument
R ; Replace all occurrences of
+XL ; the regex [a-z]+ (run of lowercase letters)
; with the following callback function:
A_ ; ASCII code of the first character
"/*+ -"@ ; used as a (cyclical) index into that string
V ; After replacing, evaluate the resulting string as a Pip expression
```
---
If taking input as three separate arguments is allowed (e.g. if you can just type `python pip.py equation.pip 9 times -2` on the command line), then it's **15 bytes**:
```
Va."/*+ -"@Ab.c
```
[Try it online!](https://tio.run/##K8gs@P8/LFFPSV9LW0FXycExSS/5////lv9LMnNTi//rGgEA "Pip – Try It Online")
And here's a solution without eval (using three separate arguments) in **18 bytes**:
```
[a/ca*ca+c0a-c]@Ab
```
[Try it online!](https://tio.run/##K8gs@P8/OlE/OVErOVE72SBRNznWwTHp////lv9LMnNTi//rGgEA "Pip – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 50 bytes
```
(a,o,b)->o[0]<98?a+b:o[0]<'e'?a/b:o[0]<'n'?a-b:a*b
```
[Try it online!](https://tio.run/##ZVFda8IwFH3vr7j0xVTTTsQxtU4Zg8Fge/JRfLht0y6ubUqSCm7427vbrI6BL8k99@Occ5MjnjA8Zp@drBqlLRwJR62VZTSOPa9pk1KmkJZoDLyjrOHbA5C1FTrHVMBLW6cu5ZKgWH8iTz9Q7w@geA@TIKaGi0eHsWiJzk3l8AgdQ654EoQbtZ8e1svFFifJysUjMdri3RXUBMJkheOki3uiwdfAd1Iyg4rcsZ3Vsi5IGnVhgsHZmzR2/UqeC6E3gIaEn7TGs4nQ9DX2wGHJYTbnMHdeh5Ffsg2o5nbExyzzOfhWVsL0QSZPMhN9VMm6Nf5/oj/t5JZowSGckTiH@8CtBpArDe4hJXVPY7rW5Doy8kuwgOBkct0MYHc2VlSRam3UkFtb1iyPFKP2QlgmA967H@LIqmf6GKfPqJJcC8Fg9uL@6dL9AA "Java (JDK) – Try It Online")
Input is a `int, char[], int`.
* -36 bytes from @ceilingcat
* -49 bytes from @Kevin Cruijssen
### Orignal: [Java (JDK)](http://jdk.java.net/), 135 bytes
```
int o(int a,String o,int b){switch(o.charAt(0)){case'a':return a+b;case'm':return a-b;case't':return a*b;case'd':return a/b;}return 0;}
```
[Try it online!](https://tio.run/##ZZDNbsIwEITPzVOscsEGkyJE1Z9QJI6V2hPHqgcndsPSJI7sDRVFPHtqQ4ADsmTPjke7n72RWzneqJ8Oq8ZYgo2vk5awTIZpFDVtVmIOeSmdgw@JNewjR5K812FNYFjYpViRxboAI0KZ8b37RcrXzCT5WtolsQnn@1w6PZCDF6uptTXIUZYerepqjXuLrtawt9TVus/SQ68n6aHrGXusrUEFlSdlJ6bPL5C2cNyDR@/oaP5Wky60XYB08ApLa@XOJdKFO/Yo4FnAdCZgxtNT/NRlAaa5jcdSqVhATFhpF4TCLSodVIV16@Jzk8vM7LbJk4Dx1A8V8ODj0bexcPxU9MlJ6o@5J00c/mnGfTkahafcrXaOdJWYlpLGA1JZM8N8rtDEkIuAe9HZWXI/4BBW9w8 "Java (JDK) – Try It Online")
Simple switch
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, ~~15~~ ~~14~~ 13 bytes
```
ǔ÷hC`/*+ -`iĖ
```
*-5 bytes thanks to inspiration from [@Kevin Cruijssen's 05AB1E answer](https://codegolf.stackexchange.com/a/235461/112514)*
*-2 bytes thanks to @Steffan*
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJyIiwiIiwix5TDt2hDYC8qKyAtYGnEliIsIiIsIls3LCBcImFkZFwiLCA4XSJd) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJBciIsIiIsIseUw7doQ2AvKisgLWBpxJYiLCIiLCJbNywgXCJhZGRcIiwgOF1cbls5LCBcInRpbWVzXCIsIC0yXVxuWzI0LCBcImRpdmlkZVwiLCAyXVxuWzQsIFwibWludXNcIiwgNV0iXQ==)
Pretty much a port of most of the other answers.
Explanation:
```
ǔ # Rotate list to the right to get [r, l, op]
÷ # Pop then push each item onto the stack
h # Get the head (first item) of the operator
C # Convert to ASCII code
`/*+ -`i # Use that to index into the string "/*+ -"
Ė # Execute as Vyxal code (r flag reverses args)
```
[Answer]
**Python3 142 bytes**
```
def f():
a,b,c=input().split(' ');x=b[0];i=int(a);j=int(c);z=i+j if x=='a' else i*j if x=='t' else int(i/j) if x=='d' else i-j;print(z)
```
Splits tokens, applies operator and prints result
[Answer]
# [PHP](https://php.net/), 55 bytes
```
fn($a,$b,$c)=>[$a/$c,$a*$c,$a+$c,0,$a-$c][ord($b[0])%5]
```
[Try it online!](https://tio.run/##XcxNDoIwEIbhfU8xIWMALQINRAyiB0EWpYXQBdD4d/06uCDBWXyzefLawbrLzQ6WMewr108BSo4tRxVW1xpljIqj3P/2QJvQj1A19fzQAbZ10oS7vHElY50aZsA@OHHwpdY@hwLoQjiCd5@8EuIY0nxlZ2IvM3ZPgpHYsigtVicygtp8jO5Iim1OrGxRo5neSy6H/5z7Ag "PHP – Try It Online")
uses the format `[7, 'add', 8]`
Nothing new under the sun, combines the tricks used in other answers.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 95 bytes
Fixed and -2 bytes thanks to Arnauld.
Not too fancy, uses scanf and abuses memory by writing the whole string at the address of a char, mod 5 to get b in single digit range, then ternaries to pick the result.
I had a 0 as the true value for the innermost ternary.... But somehow gcc is perfectly happy without it, if anyone can explain how that works I would appreciate the comment.
```
a,c;main(){char b;scanf("%d %s %d",&a,&b,&c);b%=5;printf("%d",b-2?b-4?b-1?b?:a/c:a*c:a-c:a+c);}
```
[Try it online!](https://tio.run/##HctBCoMwEEDRqwyBBK0zSIPdGCRnmZmgzaKhaHfFs8fg4u3@V9pUa2XU8OFcuv6vb95BwqFc1s7YBPYAmww6RifotA9il1f47rn87sCgkI9CU/OMEmcedeZHQ83QhrNWmjykDOQv "C (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ι˜`¨C"*+-÷"è.V
```
Input as a list.
[Try it online](https://tio.run/##yy9OTMpM/f//3M7TcxIOrXBW0tLWPbxd6fAKvbD//6OVLJV0lEoyc1OLgbSukVIsAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/cztPz0k4tMJZSUtb9/B2pcMr9ML@6/yPjlYyV9JRSsxLAZIWSrE60UqWQFZJZm5qMZDWNQILGZkA2SmZZZkpqUAGRAwklJuZVwpSZqoUGwsA).
**Explanation:**
```
ι # Uninterleave the (implicit) input-list:
# [a,"O",b] becomes [[a,b],["O"]]
˜ # Flatten this list: [a,b,"O"]
` # Pop and push the three values separated to the stack
¨ # Remove the last character of the operator string
C # Convert it from a binary string to an integer
"*+-÷"è # Modulair 0-based index it into string "*+-÷"
.V # Evaluate it as 05AB1E code
# (after which the result is output implicitly)
```
| String | `¨` | `C` | Modulair 0-based index | Operator |
| --- | --- | --- | --- | --- |
| and | an | 121 | 1 | + |
| minus | minu | 714 | 2 | - |
| times | time | 752 | 0 | \* |
| divide | divid | 1331 | 3 | ÷ |
`C` on strings basically gets the index of each characters in the string `0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzǝʒαβγδεζηθвимнт ΓΔΘιΣΩ≠∊∍∞₁₂₃₄₅₆ !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~Ƶ€Λ‚ƒ„…†‡ˆ‰Š‹ŒĆŽƶĀ‘’“”–—˜™š›œćžŸā¡¢£¤¥¦§¨©ª«¬λ®¯°±²³\nµ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ•`, and then converts this list of indices to a base-2 integer.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as an array. Thought there might be some other clever way of working with the charcodes to get the required operator but using [caird's method](https://codegolf.stackexchange.com/a/235355/58974) of indexing into the operators seems to be optimal.
```
OvUg1_Îcg"/*+ -
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=cVM&code=T3ZVZzFfzmNnIi8qKyAt&input=WwoiNyBhZGQgOCIKIjkgdGltZXMgLTIiCiIyNCBkaXZpZGUgMiIKIjQgbWludXMgNSIKXS1tUg)
Or without using `eval`:
```
rUj1 ÎÎcg"/*+ -
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=cVMgb24gdm4&code=clVqMSDOzmNnIi8qKyAt&input=WwoiNyBhZGQgOCIKIjkgdGltZXMgLTIiCiIyNCBkaXZpZGUgMiIKIjQgbWludXMgNSIKXS1tUg)
```
OvUg1_Îcg"/*+ - :Implicit input of array U
Ov :Eval as Japt
Ug1 : Modify the element at 0-based index 1 in U
_ : By passing it through the following function
Î : First character
c : Charcode
g"/*+ - : Index into "/*+ -"
```
```
rUj1 ÎÎcg"/*+ - :Implicit input of array U
r :Reduce by
Uj1 : Remove & return, as a singleton array, the element at 0-based index 1 in U
Î : First element
Îcg"/*+ - : As above
```
[Answer]
# Python 3, 91 bytes
```
def f(a):a,b,c=a;b=b[0];d=b=='d';return(a+c*((b=='a')-(b=='m')))*[1,[c,1/c][d]][b=='t'or d]
```
Takes a single input as a listed of the values, i.e. `[7, "add", 8]` and returns the result of the equation.
[Try it online!](https://tio.run/##XZDBTsQgEIbvfYpJL8AujXbdjWsbvPgK3pADBRo5lG2Amvj0deiaxkhCMuGbj/lh/s6ft/C0rtaNMFLNOs0HboTuBzHIR9VbMQhBLOmjy0sMVB/NgdJypglrtmIijLGDbLk0vH0wSlqlZAGZ3CJYtfowLzmBAFkBLimfORBtLeFwVRzai@K/4AVB9pNLiJoTsqa97vB0Rmr9l7cOcaHtaYeFTT4sxbxsIiJVVSNG8BwwAm5wYZlc1NnReybWbfocfci0fncpw5tODmo4QsqReoZF3dVsa4uuPGIsLn4N@6t@5F25w@JB07zuV6HM/inbPFPmpcUYl1IH9d4MQpTUslWMrT8 "Python 3 – Try It Online")
[Answer]
# [Python 3](https://www.python.org), 71 bytes
```
x,y,z=input().split()
print(eval(f'{x}{"/*+ -"[ord(str(y)[0])%5]}{z}'))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v0KnUqfKNjOvoLREQ1OvuCAnE0hzFRRl5pVopJYl5mikqVdX1FYr6WtpK@gqRecXpWgUlxRpVGpGG8RqqprG1lZX1aprav7/b66QmJKiYAwA "Python 3 – Try It Online")
Inspired by various other answers featuring `ord(str(y)[0])%5`.
If the input is taken as a list like `[5, 'minus', 8]`, then you can get an answer of only 67 bytes;
```
lambda l:print(eval(f'{l[0]}{"/*+ -"[ord(str(l[1])[0])%5]}{l[2]}'))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PycxNyklUSHHqqAoM69EI7UsMUcjTb06J9ogtrZaSV9LW0FXKTq/KEWjuKRIIyfaMFYTKKOpagqUzYk2iq1V19T8/99cITElRcEYAA "Python 3 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
Nθ≡§S⁰aI⁺θNmI⁻θNtI×θNdI∕θN
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05qruDyzJDlDQcOxxDMvJbVCAywfXFKUmZeuoamjYKCpqVDNlZxYnKqglKhkpRAAlCjRcE4sLtEIyCkt1ijUUUA2URMIrKHKc1GV@2bm4Vdfgqo@JDM3Fa/6FFT1LpllmSmp2DXU/v9vopALcoCC6X/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Inputs the first number, switches on the string then inputs the second number as it outputs the result of the appropriate operation. 20 bytes with a boring eval-based approach:
```
IUV⁺θ⁺§+-*/⌕amtd§η⁰ζ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI6CyJCM/z7UsMac0sSRVIyCntFijUEcBTDuWeOalpFZoKGnraukr6Si4ZealaCgl5pakADkwyQwdBQNNTU0dhSpNELD@/99EITczr7RYwfS/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Gets the appropriate Python operator depending on the first letter of the string and evaluates the result as a Python expression.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 44 bytes
```
s/a/+/;s/t/*/;s|v|/|;s/n/-/;s/\pL//g;$_=eval
```
[Try it online!](https://tio.run/##FchBCsIwEEbhfU7xL1wpcWpoUCneQG8gSCBBBtI0NDGrnN2xrh7fy2GNVqSQowNNhSrtt/TWqW9KpP/zme9E72n3uoXmosgZzntc1BWV51CgjTIjPDf2AUaNmDl9CizwXXLlJRXRMYt@2ONwGn4 "Perl 5 – Try It Online")
] |
[Question]
[
A few hours earlier, I got this puzzle:
>
> Suppose, you toss a coin n times, then what is the probability of getting m number of heads? ( where m belongs to the *set of all prime numbers*)
>
>
>
For instance, take n = 2, then
`SS = { HH, HT, TH, TT }`
So, output is 1/4 (for HH case)
Then, for n = 3,
`SS = { HHH, HHT, HTH, THH, HTT, THT, TTH, TTT }`
So, output is (1 + 3)/8 (for 3 H's case and 2 H's cases respectively)
**Input**: n ( an integer, 0 <= n <= 1000 )
**Output**: The probability (in any distinguishable form, i.e., decimal, exponential, fraction, etc)
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes would win!
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes
Uses Binomial and outputs ,really fast, fractions
[](https://i.stack.imgur.com/fXTxb.png)
```
Tr@Binomial[#,Prime@Range@#]/2^#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P6TIwSkzLz83MzEnWlknoCgzN9UhKDEvPdVBOVbfKE5Z7T9QLK9EwSE92jiWC8yOhtJgMQOsgthEDQ2Awv//AwA "Wolfram Language (Mathematica) – Try It Online")
The original code according to my formula was
```
Tr@Binomial[#,Prime@Range@PrimePi@#]/2^#&
```
but, as **@attinat** commented, instead of searching all Primes < `n` we can
search the first `n` primes because every prime > `n` returns zero binomial.
In this way we save *8 bytes*
Here is also the graph of the first 1000 cases which looks pretty cool
[](https://i.stack.imgur.com/RRFQh.png)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
cÆRSH⁸¡
```
**[Try it online!](https://tio.run/##y0rNyan8/z/5cFtQsMejxh2HFv7//98YAA "Jelly – Try It Online")**
### How?
```
cÆRSH⁸¡ - Link@ integer, n e.g. 20
ÆR - primes to n [2,3,5,7,11,13,17,19]
c - (n) choose (vectorises) [190,1140,15504,77520,167960,77520,1140,20]
S - sum 340994
¡ - repeat...
⁸ - ...times: chain's left argument, n
H - ...action: halve
- (170497, 85248.5, ..., ~0.65, ~0.325) 0.3251972198486328
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 7 bytes
```
ÅPcOso/
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cGtAsn9xvv7//2YA "05AB1E – Try It Online")
**Explanation**
```
ÅP # push a list of primes upto and including input
c # push choose(input, prime) for each prime
O # sum
so # push 2^input
/ # divide
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/)/MATLAB with Statistics Package/Toolbox, 32 bytes
```
@(n)sum(binopdf(primes(n),n,.5))
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI0@zuDRXIykzL78gJU2joCgzN7UYKKiTp6Nnqqn5P03D2EDzPwA "Octave – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~198~~ ~~125~~ 97 bytes
```
lambda n:f(n)/2**n
f=lambda n,h=0:h>1>sum(h%i<1for i in range(2,h))if n<1else f(n-1,h+1)+f(n-1,h)
```
[Try it online!](https://tio.run/##XYyxDoIwEEB3v@IWQw9K9DBhaGi/xKXG1rsEDgI4@PXVQRe3l5e8t7x2nvVS2F/LGKfbPYK6bBRPXV3rIfuftOzPjgOF7TkZPspAeV5BQBTWqI9kOsuIkkEHSuOW4DNpyXJD2HwRy19CPbplFd2N2KoNlWUjiOUN "Python 3 – Try It Online")
To aid in understanding, I first generate all the of the possible combinations, then I get then total heads if that is prime, then I add the total number of primes. The second function, `h` generates the result from function `f`. Bellow is the original algorithm before minimizing it.
```
def f(n,h=""):
count = 0
if n==0:
hCount=h.count("h")
for i in range(2, hCount):
if hCount % i == 0:
return 0
if hCount < 2:
return 0
return 1
count += f(n-1,h+"h")
count += f(n-1,h+"t")
return count
def h(n):
return f(n), (2**n)
print(h(4))
```
Credits:
* From 125 to 97 bytes by [attinat](https://codegolf.stackexchange.com/users/81203/attinat)
[Answer]
# Excel Formula, ~~311~~ 309 bytes
The following should be entered as an array formula (`Ctrl`+`Shift`+`Enter`):
```
=SUM(IFERROR(COMBIN(A1,SMALL(IF(MMULT(--(IF(ROW(INDIRECT("2:"&A1))>TRANSPOSE(ROW(INDIRECT("2:"&A1))),MOD(ROW(INDIRECT("2:"&A1)),(ROW(INDIRECT("2:"&A1))>TRANSPOSE(ROW(INDIRECT("2:"&A1))))*TRANSPOSE(ROW(INDIRECT("2:"&A1)))))=0),ROW(INDIRECT("2:"&A1)))=0,ROW(INDIRECT("2:"&A1))),ROW(INDIRECT("1:"&A1)))),0))/(2^A1)
```
Where `A1` is the number to test.
**Examples:**
```
A1=15
Result: 0.34997558593750
A1=25
Result: 0.341329127550125
```
**Credits**
`-2` thanks to [Sophia Lechner](https://codegolf.stackexchange.com/users/78915/sophia-lechner)!
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), ~~12~~ 8 bytes
```
:ṅK¦Σ@z÷
```
[Try it online!](https://tio.run/##S0/MTPz/3@rhzlbvQ8vOLXaoOrz9/38TAA "Gaia – Try It Online")
```
: | dup input n
ṅ | push first n prime numbers, [2..k]
K¦ | push n choose k (0 if k > n)
Σ | sum
@z | push 2^n
÷ | divide
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 41 bytes
```
K`
"$+"+%`^
$"H
*\Cm`^(?!(..+)\1+$)..
m`^
```
[Try it online!](https://tio.run/##K0otycxLNPz/3zuBS0lFW0lbNSGOS0XJg0srxjk3IU7DXlFDT09bM8ZQW0VTT48LKPT/vzEA "Retina – Try It Online") Output is as a ratio. Explanation:
```
K`
"$+"+%`^
$"H
```
Generate all the possible coin tosses of `n` coins, but keep only the heads. (`T$"H` would keep the tails as well.)
```
*\Cm`^(?!(..+)\1+$)..
```
Count how many are prime and print on a separate line.
```
m`^
```
Count how many there are altogether.
[Answer]
# JavaScript (ES7), 71 bytes
```
n=>(s=1,g=i=>i<n&&(s*=(n-i)/++i)*(p=d=>i%--d?p(d):d==1)(i)+g(i))``/2**n
```
[Try it online!](https://tio.run/##DckxDoMwDEDRnVN4KbITUgojYHoVECEoFXIiUnWpevY0y3/Df62fNW2Xj28jwe7ZcRaeMXHXHOx59pPUNSbFKMZTq7UnhZFtOTdj7DOipcEyd4Se9FFCy9L2Skl24UIBhm4EgQn6R1Frgm8FsAVJ4dzvZzhQGnAoRGP1y38 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Ø.ṗ§ẒÆm
```
[Try it online!](https://tio.run/##ARkA5v9qZWxsef//w5gu4bmXwqfhupLDhm3///8z "Jelly – Try It Online")
Different approach from Jonathan Allan's answer.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 35 bytes
```
n->binomial(n)*isprime([0..n])~/2^n
```
[Try it online!](https://tio.run/##DYtBCoAgEAC/snTSUNPu@ZEoMMhYyFWsc1/f9jKHYaaljvZqnGEBJhsPpFow3Yr0iE/rWE61eudo098078S5dkUSBwPBG5CCXhED2CjI8mnNPw "Pari/GP – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 13 bytes
```
õÈj *UàX /2pU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=9chqICpV4FggLzJwVQ&input=OA)
] |
[Question]
[
Your task is to build a piece of code that generates an aperiodic sequence of integers, either by outputting one every time it iterates, or by taking an integer `n` and returning the `n`th number in that sequence.
Now, the sequence `1, 2, 3, 4, 5, 6, ...` is itself aperiodic, so I'm going to introduce a few limitations to the definition of "aperiodic" used in this problem to weed out the trivial cases:
* The sequence must not be periodic modulo any integer `m > 1`. So a sequence like the powers of 2 would repeat `2, 4, 8, 6` all the time modulo 10, and therefore not count. (It would also repeat `0` modulo 2.)
* The sequence must not become periodic after a certain number of operations - e.g. `1 2 4 8 6 2 4 8 6 ...` is still considered periodic even though 1 never appears again.
* The generation code must only use integers. So a piece of code that calculated the `n`th digit of pi (without calculating it in some integer form first) would not be acceptable.
Now, obviously every sequence performed with limited computer memory will eventually either be periodic or run out of memory, but if you can prove that your function, given infinite memory and time, will never loop back to a previous state, then it is acceptable.
The shortest code that does the above wins.
[Answer]
# Golfscript, 2 characters
```
`,
```
(stringify (```) the number and count (`,`) the digits)
# J, 3 characters
```
#q:
```
is the count (`#`) of the prime factors (`q:`) of its input.
The vector form involves more bookkeeping, but that's not our contestant:
```
#@q:L:0&.<
```
the first 40 terms are: 0 1 1 2 1 2 1 3 2 2 1 3 1 2 2 4 1 3 1 3 2 2 1 4 2 2 3 3 1 3 1 5 2 2 2 4 1 2 2 4
[see more at OEIS](http://oeis.org/A001222)
The sequence is 1 at every prime position, 2 at every prime multiple of a prime, 3 at every prime multiple of a product of two primes...
---
If you are not convinced this is aperiodic, here are plenty of other sequences:
```
##:
```
(the number of bits = floor of the base-2 logarithm)
```
+/#:
```
(count of 1-bits in the binary representation of the number). This (reduced under any modulus)
```
#b#:
+/b#:
```
(the same in base-b)
```
<.^.
>.^.
<.b^.
>.b^.
```
(floor or ceiling of the (natural) log - this time without stringification)
```
*./#:
+./b#:
*./b#:
```
(GCD or LCM of all base-b digits (except GCD of bits won't work))
```
1{#:!
9{#:!
({#:@!)
```
(second/tenth/nth highest bit of the factorial of n)
```
(=<.&.%:)
```
(Is the number equal its floor under the square root operation? Is the number equal the square of the floor of its square root? Is the number a square?)
[Answer]
# Python, ~~48~~ 25 bytes
Volatility's version, using string operations:
```
f=lambda a:int(`2**a`[0])
```
Numerical version (48 bytes):
```
def f(a):
m=2**a
while m>9:
m/=10
return m
```
Sequence it returns (first 100 terms):
```
1 2 4 8 1 3 6 1 2 5 1 2 4 8 1 3 6 1 2 5 1 2 4 8 1 3 6 1 2 5 1 2 4 8 1 3 6 1 2 5
1 2 4 8 1 3 7 1 2 5 1 2 4 9 1 3 7 1 2 5 1 2 4 9 1 3 7 1 2 5 1 2 4 9 1 3 7 1 3 6
1 2 4 9 1 3 7 1 3 6 1 2 4 9 1 3 7 1 3 6
```
This returns the first digit of the `a`th power of 2, which is aperiodic because log10 2 is irrational, and no multiple of it besides 0 will be an integer. (So while it may *look* periodic for a long time, eventually there will always be something to break the period.)
I could probably golf for whitespace, but I'm not experienced with that.
[Answer]
# Python, 14
```
int.bit_length
```
This generates the following sequence:
```
>>> f=int.bit_length
>>> [f(i) for i in range(20)]
[0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5]
```
[Answer]
# Perl -p, 7 characters
```
$_.=/1/
```
Takes an integer n on the standard input and outputs the nth number in the following sequence:
```
11 2 3 4 5 6 7 8 9 101 111 121 131 141 151 161 171 181 191 20 211 22 23 24 25 26...
```
[Answer]
## Sage, 7
[Sage](http://www.sagemath.org/help.html%20Sage) has the integer-part-of-the-square-root function built-in :
```
f=isqrt
[f(n) for n in [0..20]]
-> [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4]
```
A number of [OEIS](http://oeis.org/ "OEIS") sequences are also Sage built-ins named using the OEIS index, and would score a length of **16**; e.g.,
```
f=sloane.A000120
f;[f(n) for n in [0..20]
-> 1's-counting sequence: number of 1's in binary expansion of n.
[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2]
```
[Answer]
## Perl, ~~19~~ 18 characters
Simplicity itself:
```
sub f{"@_"=~/(.)/}
```
Given an integer `n`, the function `f` returns the `n`th number in the sequence.
For those not conversant in Perl, `f` returns the leading decimal digit in `n`. As the sequence continues, you get progressively longer runs of the current number. Thus the sequence is transparently aperiodic, and avoids devolving into any of the trivial cases listed above.
[Answer]
# [RETURN](https://github.com/molarmanful/RETURN), 9 bytes (noncompetitive)
```
0[' ,1+$¦{\3}§.1!]!
```
`[Try it here.](http://molarmanful.github.io/RETURN/)`
Make sure to run using "timed run," because this is an infinite stream. Also replace `\3` with character `U+0003`.
# Explanation
Basically just outputs each number reversed. I couldn't find any periodicity, but please tell me if you do.
] |
[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/165573/edit).
Closed 5 years ago.
[Improve this question](/posts/165573/edit)
**The Task**
Your task is to create a program or a function that, given a sentence, outputs it translated to the [Farfallino language](https://en.wikipedia.org/wiki/Farfallino_alphabet). 'Y' is treated as a consonant.
The usual rules for farfallino alphabet are based on the substitution of each vowel with a 3 letter sequence where the vowel itself is repeated with an interceding f.
```
house → hofoufusefe
lake → lafakefe
star → stafar
king → kifing
search → sefeafarch
```
**More examples:**
Hello World
>
> Hefellofo Woforld
>
>
>
Code golfs are nice, yuppy!
>
> Cofodefe gofolfs afarefe nificefe, yufuppy!
>
>
>
When you come across a double vowel syllable (the vowels must match, like *door, boots, reed, etc.*) you must omit the 2nd vowel.
**This rule is mandatory**
Cool game
>
> WRONG: Cofoofol gafamefe
>
>
> RIGHT: Cofofol gafamefe
>
>
>
**More examples, again:**
```
Aardvark → Afafardvafark
Artisan → Afartifisafan
ASCII → AfaSCIfifi
NASA → NAfaSAfa
Oobleck → Ofofobleck
I'M DEAD! → Ifi'M DEfeAfaD!
Abc → Afabc
```
**Input**
Your input must be an ASCII string.
>2 consecutive vowels are not special. You have to handle 2 consecutive vowels:
```
AAAH → AfafaAfaH
AAAAH → AfafaAfafaH
```
**How to win**
The shortest source code in bytes for each language wins.
1, 2, 3... go!
[Answer]
# Japt, v2.0a0, 7 bytes
```
r\v_²íf
```
[Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=clx2X7LtZg==&input=ImhvdXNlIg==)
---
## Explanation
```
r :Replace
\v :/[AEIOU]/gi
_ :Pass each match through a function
² : Duplicate
íf : Interleave "f"
```
>
> **Note**: This solution was posted *before* the "bonus" of handling double vowels was made a requirement and before the (apparent) requirement that when repeating an uppercase vowel the second occurrence should be lowercased. I don't much feel like wasting time on a challenge whose spec is constantly changing and invalidating the solutions that have already been posted, nor do I feel I should be expected to sacrifice 90 rep by deleting a solution that was valid at the time of posting.
>
>
>
[Answer]
## JavaScript (ES6), 67 bytes
```
f=
s=>s.replace(/([aeiou])\1*/gi,s=>[s[0],...s.toLowerCase()].join`f`)
```
```
<input oninput=o.textContent=f(this.value)><pre id=o>
```
Includes the double vowel handling. Edit: Includes upper case too. Try `Aardvark`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 27 bytes
```
'fžMDu+DŠδ.ø˜‡γεDÙlžMsåiÙ}?
```
[Try it online!](https://tio.run/##ATsAxP8wNWFiMWX//ydmxb5NRHUrRMWgzrQuw7jLnOKAoc6zzrVEw5lsxb5Nc8OlacOZfT///0Nvb2wgR2FtZQ "05AB1E – Try It Online")
Just a temporary fix for handling double vowels. I'll try to shorten this after my finals. Boo to rule changes!
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
'fžMDu+DŠδ.ø˜‡
```
[Try it online!](https://tio.run/##ASQA2/8wNWFiMWX//ydmxb5NRHUrRMWgzrQuw7jLnOKAof//aG91c2U "05AB1E – Try It Online")
If we only need to handle lowercase input, then this is [11 bytes](https://tio.run/##ASEA3v8wNWFiMWX//ydmxb5NRMWgzrQuw7jLnOKAof//aG91c2U).
### How it works
* `'f` pushes the character literal **f** to the stack
* `žMDu+D` yields `aeiouAEIOU`; in the 11-byte version, it pushes `aeiou` to the stack; the leading `D` duplicates it (that is, it pushes two copies of it to the stack).
* `Šδ.ø˜` surrounds `f` with each vowel in the second copy
* `‡` performs the transliteration of the input from the first copy of the vowels to the second copy, the one in which all vowels surround a single **f**
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
;”f;ƊeØc$¡€F;⁷ḟ⁹fØc¤¥Ɲ
```
[Try it online!](https://tio.run/##ATgAx/9qZWxsef//O@KAnWY7xoplw5hjJMKh4oKsRjvigbfhuJ/igblmw5hjwqTCpcad////Y29vbGxhdA "Jelly – Try It Online")
Handles the extra (now required) feature.
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
;”f;ƊeØc$¡€
```
[Try it online!](https://tio.run/##y0rNyan8/9/6UcPcNOtjXamHZySrHFr4qGnN/6N7DrcD6SwgftQwR0FBQVdX1w5IAVVG/v8fzaXuAdSarxCeX5SToq7DpZ6RX1qcCmLkJGaD6eKSxCIQnZ2Zlw7mpyYWJWeoc8UCAA "Jelly – Try It Online")
Doesn't handle the double vowel feature.
```
;”f;ƊeØc$¡€
€ For each character in the input, do the following.
¡ If:
e the character is in...
Øc the list 'aeiouAEIOU'
$ (connects e and Øc into a single monad)
then:
; append
”f the letter f
; and append the initial character.
Ɗ Group ;”f; into a single monad.
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~34~~ 30 bytes
```
i`[aeiou]
$0f$l
([aeiou])\1
$1
```
[Try it online!](https://tio.run/##Lck9CsJAEAbQ/jvFCFsoWJgjiI03sFDBIZlshow7YX@KnD6msHy8LFUTd9umnyeLensjXMZgOP55enUI@0/eisB4FpTKGbOmiCKc@wl3MXN6eLYBNx@EottYiLNQ0l7OtLZlWQ/7uVHkr@CqrfoP "Retina – Try It Online")
First time using Retina...
*-2 bytes thanks to Kevin Cruijssen*
*-2 bytes thanks to PunPun1000*
[Answer]
# [Python 2](https://docs.python.org/2/), ~~80~~ 77 bytes
```
lambda s:''.join(map(lambda c,C:c+('f'+c*(c!=C))*(c in'aeiouAEIOU'),s,s[1:]))
```
[Try it online!](https://tio.run/##TY@xTsQwEER7vmJPFI65CAnKSFegCAkqKkQBFMbxJiaO17KTIl8fNg66pPLsvpmxHeaxI/@44OVrcWr4aRSkSoj7X7K@GFQo/pe6rCt9LgSKs74r9OlSS8knWC@UsTQ9Pb@@vQtZpjJ9PlTfUi4hWj8CFqKjKRkh4RY6QpqQJzQ3V@xUv1GnkOURpVHFjFigijvorW8z6C2yPCSMirrbMly1pnS34xfjHMEHRddkz2HeTTU1BlpymEBFA95qU8I8hTCfcqjmXzRczh7cXHzLOnt@jGaxujH7j6XkoFWDuVZgXiCv0Cx/ "Python 2 – Try It Online")
---
Saved:
* -3 bytes, thanks to ovs.
[Answer]
# Java 8, 68 bytes
```
s->s.replaceAll("([aeiou])","$1f$1").replaceAll("([aeiou])\\1","$1")
```
[Try it online.](https://tio.run/##jZCxasMwEIb3PMVVZJAgMXgOLZgs9dAsHTokGS6y7Cg@S0aSA6b42V019diiggQ63Xe/PnTDO25vVTtLQu/hDbX5XAFoE5SrUSo4fJcA78Fp04Dky8GLXbyf4o7LBwxawgEMPMPsty8@c6qnOF4QccaPqLQdzoJt2Dqv1zkTv/dPp/yBMDHvfpL74UIxeXngbnUFXVRcLI5nQLH4jT6oLrNDyPrYCmS4ySRnVzt4xcTD9m@KsE1DUcIloTZqpZMUOnlNYq@KyMKHdVQl2b2tFDSWag/oFBgt1QbGoe/Hp3/MWoIGu/QXFBeZZoqyLBdqWk3zFw)
Or **77 bytes** if we have to handle uppercase vowels as well:
```
s->s.replaceAll("(?i)([aeiou])","$1f$1").replaceAll("([AEIOUaeiou])\\1","$1")
```
[Try it online.](https://tio.run/##jZBBa8MgFMfv/RRv0oNCG8i5bCOMwXpYdxhjh7SHV2NSG6NBTSGMfPbMdV52GBZ8oM/f8//DM15wfa7amSt0Dl5R6q8FgNRe2Bq5gN3PEeDdW6kb4DRuHNuE/hQqLOfRSw470HAPs1s/uMyKXoXxQilK6KNktEQhzXBgZEWWeb3MCfvLlMXz9u0jQvt9fuUImze/Ef1wVCEiJl2MrKALrlGnPACyKDo6L7rMDD7rw5VXmuqMU3IygxOEXbX/pxS2aShI2CTUBq30SwItPyWxF6GUgU9jVZVkn0wloDGqdoBWgJZcrGAc@n68u2HWKGiwS39BceRpBrdSyohNi2n@Bg)
**Explanation:**
```
s-> // Method with String as both parameter and return-type
s.replaceAll("([aeiou])", // Replace every vowel with:
"$1f$1") // the vowel, 'f', the vowel appended to each other
.replaceAll("([aeiou])\\1", // Then replace every duplicated vowels
"$1") // to a single one
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~177~~ ~~163~~ 155 bytes
```
A+B:-append(A,B).
S-[H|T]-R:-S-T-Q,([I,[H,H],K]+Q,K-[H]-L,[I,[H,102,H,102,H],L]+R;[I,[H],K]+Q,K-[H]-L,[I,[H,102,H],L]+R;R=Q).
R-_-R.
S-R:-S-`aeiouAEIOU`-R.
```
[Try it online!](https://tio.run/##lY1Nq8IwEEX371fM21U6I@pSEakiVBSkqeKihDbYWAOxCakiwvvvffFjK@hmFmfuvcc6o01FzVW1bRROhySslXUZRDjtdH9SyuK/DSc2pJQ2lGCQLTCLMea45GGCS//ntMIn7fcG@LocVzxkowd/n32l2DjxLkY5sbvyISuEVOYSzRfrbeFxOyEoYqm1gZ1xuvQMoTk7VVf5/ihcE6QIrINwdeosdR2kfvHemZlSQmX0oQHhJNRqLxFuF2tvv19sGA2VOMlPGu0/ "Prolog (SWI) – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 81 bytes
```
func[s][foreach c{aoeiu}[replace/all replace/all s c rejoin[c"f"c]rejoin[c c]c]s]
```
Lowercase vowels only - it's much shorter now without using `parse`.
[Try it online!](https://tio.run/##Vc2xDgIhEATQ3q9YqU3s7YyNtY0FoViX5Q5dWQJSXIzfjjYa7OZNJpnCvp/YW7cKux5aIludDVoYaQZ6onJsL1s4CxJvUQTGXIE@vmpMlkww5L4AcuSq67nE9IAAZtZW2ax@FryNrIyF5qE4sojCWYv4oT2oZ5hUQgUsDCkSb2BpOS/rv5UKTHgfD/YJLyymvwE "Red – Try It Online")
# [Red](http://www.red-lang.org), 132 bytes
```
func[s][v: charset["aoeiuAOEIU"]parse s[any[copy n v n(prin rejoin[n"f"n"f"n])|
copy n v(prin rejoin[n"f"n])| copy n skip(prin n)]]]
```
[Try it online!](https://tio.run/##Zco9C8IwEMbxvZ/ivElBcO8mIugkCOIQIoT0YqPxLiRWKPjda@vLYodn@T3/RFW3p0rpwpWda9iqrNWjBFublOmu0Aj5Zrlbbw@o42CQleFWWYktMDyApzF5hkQX8awYHb6nZ8/i14yL/oXvm68@fgKeaa07B1hLkwmLAe@ApwUWPQZzHVkmk2z9rxsKQeAoKVT/10oqgrMEl8EkAvaW5tA2MbaTcSoBzuZG2L0A "Red – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~82~~ 76 bytes
```
i=input()
for x in"aeiouAEIOU":i=i.replace(x,x+"f"+x).replace(x*2,x)
print i
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9M2M6@gtERDkystv0ihQiEzTykxNTO/1NHV0z9UyQoorVeUWpCTmJyqUaFToa2UpqRdoYkQ0jLSqdDkKijKzCtRyPz/X8k5Pz9HIT0xN1UJAA "Python 2 – Try It Online")
Actually shorter to use 2 replaces rather than the split and join that was there previously.
If we are required to have "Abc" output "Afabc" instead of "AfAbc" then that costs another 8 bytes...
```
i=input()
for x in"aeiouAEIOU":i=i.replace(x,x+"f"+x.lower()).replace(x*2,x)
print i
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9M2M6@gtERDkystv0ihQiEzTykxNTO/1NHV0z9UyQoorVeUWpCTmJyqUaFToa2UpqRdoZeTX55apKGpiZDSMtKp0OQqKMrMK1HI/P9fyTEpWQkA "Python 2 – Try It Online")
[Answer]
# Excel, 218 bytes
Pretty blunt:
```
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"a","afa"),"e","efe"),"i","ifi"),"o","ofo"),"u","ufu"),"aa","a"),"ee","e"),"ii","i"),"oo","o"),"uu","u")
```
Substitutes `a`, `e`, `i`, `o` & `u` with `*f*`. Followed by removing all duplicate vowels in turn.
[Answer]
# Perl 5, 40 characters
```
perl -pe 's/([aeiou])\1?/$1."f\L$1"x length$&/egi'
```
I've waited a long time to make use of perl's `\L` regex feature. A long time.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 118 bytes
```
f(char*s){char*u="aeiou",v[4]={0};for(;*v=v[2]=*s++;)printf("%s%s%s"+!strchr(u,*v|=(*v>64)*32)*4,v+2,"f",*s-*v?v:"");}
```
[Try it online!](https://tio.run/##TY3BbsMgEETv/gpKVQnWpGocK4cQ3EM@w/IBEWMjJSaCeC@uv53inKI9zNOMZsfsBmPSp5vMbb725ByfV@e/x6Z4t4Kbhuwly8yoA0S@vHRWVPfOz1RgW3dq@Vml9YFJQIVt1SmIZSn5I7efltGvuB0tP/I/MwY2C8A/xQCbY83hUHGoBZaVoJYKiDvAXzxRyuWacp/ctZvYBjoMRmzzBCAzcrIUhDjLtqDZc/IibPcdl8Wa0sX7Gxn0vf8H "C (gcc) – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 102 bytes
## 102 bytes
```
s=>string.Concat(s.Select((c,i)=>c+("aeiouAEIOU".Contains(c)?"f"+(++i<s.Length&&s[i]==c?"":c+""):"")))
```
[Try it online!](https://tio.run/##fZDBSgMxFEX3@YqQRUmYOh/QaVqkqAgVhSIuxEV4JtPQNMF5GUFKv31803agiO0iJPdyct9NAG8gNbZr0cear34w223FzlW5SCFYyD5FLB9stI2HP8TSx6@KQTCI/GXHMJvsgd@3EaaYGwLH/LjPuNO8Qz07SoqOYLLEcmX7EVLC2Cs9g0IKY31qb@8en19Fj2XjI0pQc@FEIYvCT7Fc2ljn9WiE7/5Da5gLMYFCCDWhpVRXsaHJd/Kf/IkSpGI7RmmYgi3fGp8tVbfSSbFOLVqhuNaczi61jrQjp/qfD2Yz4ME4EldYatGcWDq6XlwgN/QpJ3Lj3UFcyrSmgfWQStP73N64wC9SCrw226H0gt7oDpYj80r5s4uE7Nm@@wU "C# (.NET Core) – Try It Online")
Linq version, looking for improvement :)
## 132 bytes
```
s=>{var r="";int l=s.Length,i=0;for(;i<l;){var c=s[i];r+=c+("aeiouAEIOU".Contains(s[i++])?"f"+(i<l&&s[i]==c?"":c+""):"");}return r;}
```
[Try it online!](https://tio.run/##fZBBSwMxEIXv@RVDDmWXrYvnpmmRoiJUFEQ8SA8hJu3QNMEkW5Cyv32drV0QsT2EzBu@eXkTna50iKZrEvo1vHylbHaC/Vb1IjhndMbgU31vvImo/xBL9J@CaadSgucDS1ll1HDXeD1NORI4hp97BlZCBwBJzg57FSFKzgX6DE6memn8Om/GKK@FDbEQOHWiPGJapndciVhJXRVcGQzNze3D0yuncD4r9KkgoKpW5ZxbXhU0ORr1I1LqOecTXXFeTuiINprcRA9RtJ1gQ9R9wA94JJ@iZAdGnik4U79FzIZ2M4Ut@CY0yfASpASqbWgsaUsd8T/v1HbAnbIkLrCUIp5YKm0vzpBb@sQTuUV7FOc8jYp6M7jS671v3zjDL0JwsFa7IfSCdrTHlqXmhfC/BglpWdt9Aw "C# (.NET Core) – Try It Online")
flat C# solution, looking for improvement :)
] |
[Question]
[
We already have challenges to [check if a string of brackets is fully matched](https://codegolf.stackexchange.com/q/77138/48022) and to [count the number of balanced strings](https://codegolf.stackexchange.com/q/66127/48022). It remains for us to generate these strings, but it will not be so easy…
A Dyck word is a string, of length *2n*, consisting of *n* opening and *n* closing parentheses (`(` and `)`) fully matched (that is to say: for all prefixes of the string, the number of opening parentheses is greater than or equal to the number of closing ones).
It is interesting to note that the number of different Dyck words of length *2n* is equal to the *(n + 1)*-th [Catalan number](https://en.wikipedia.org/wiki/Catalan_number).
It’s pretty straightforward to write a program that generates these words with a recursive function. But the goal here is to do the same thing without.
# Challenge
Write a full program or function that takes a positive integer, *n*, using `stdin` or an acceptable alternative, and outputs all the different Dyck words of length *2n*. The words can appear in any order and each must be separated from each other by a line break. Moreover, your program should not use recursive functions (see details below).
## Rules
* The output of your program should only contain Dyck words of length *2n*, separated by line breaks. Each word must appear only once.
* Your program must work at minimum for inputs 0 to 15.
* You may not write recursive functions, neither direct (a function that calls itself) nor indirect (e.g. a function *f* that calls another function *g* that calls function *f*). That being said, you can still use the standard functions of your language without worry of how they work internally.
* Similarly, your program should not call itself.
* You may not use non-standard librairies.
* Your program may not read or write files.
* Your program must be able to run in a reasonable time for *0 ≤ n ≤ 15* (hence, naively generate all arrangements is probably not a good idea). Let’s say less than 20 minutes with a memory limit of 4 GB (my reference implementation in C manages *n = 15* in less than 5 seconds).
* [All standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/48022) are forbidden.
As usual in [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins. But if you have found an interesting way to achieve this challenge in your language, please do not hesitate.
# Test I/O
For this input:
```
3
```
The output could be (any other order is correct too):
```
((()))
()()()
(()())
(())()
()(())
```
[Answer]
# C99, 105 bytes
```
i,j,s;f(n){for(char a[31]={};++i%(1<<2*n);s||puts(a))for(j=s=0;~s&&j<2*n;)s+=1-(a[j]=40+(i>>j++)%2)%2*2;}
```
Iterates over all strings of **2n** parentheses.
With piped output and compiler flag `-O3`, input **n = 15** takes roughly *15.5 seconds* on my machine. Memory consumption is 1.2 MB.
Test it on [Ideone](http://ideone.com/rBOtAV).
[Answer]
# Pyth, ~~26~~ 23 bytes
```
jeuaGsMs*VjRL`()_GGQ]]k
```
[Try it online](https://pyth.herokuapp.com/?code=jeuaGsMs%2aVjRL%60%28%29_GGQ%5D%5Dk&input=3)
```
]]k starting at G=[['']],
u Q repeat the given number of times:
_G reversed G
jRL`() parenthesize each level-2 element
*V G take Cartesian products of corresponding
elements of that and G
s concatenate, yielding a list of pairs
sM concatenate each resulting pair
aG append the resulting list to G
je finally, join the last result on newlines
```
This directly follows the [Catalan recurrence](https://en.wikipedia.org/wiki/Catalan_number#Properties) (with a non-recursive dynamic programming implementation) and doesn’t use any filtering. On my laptop, it runs in 55 seconds using 2.67 GiB RAM for *n* = 15.
# Pyth, 33 bytes, *O*(*n*) memory
```
=S*Q`()Wn2J+3x
Q"(()"=+.<S<QJ1>QJ
```
[Try it online](https://pyth.herokuapp.com/?code=%3DS%2aQ%60%28%29Wn2J%2B3x%0AQ%22%28%28%29%22%3D%2B.%3CS%3CQJ1%3EQJ&input=3)
```
*Q`() build a string with Q copies of "()"
S sort it
= assign it to Q
W while the following is true:
(newline) print Q
Q
x take the index of the first occurrence of "(()"
"(()"
+3 add 3
J assign to J
n2 is this not equal to 2 (i.e. was "(()" found)?
do the following:
<QJ take the first J characters of Q
S sort them
.< 1 cyclically shift them left by 1
+ >QJ add the remaining characters of Q
= assign to Q
```
This algorithm outputs all Dyck words in a stream, with each word being generated from the previous one and no additional state. On my laptop, it runs in 170 seconds using basically no RAM for *n* = 15.
As an example illustrating how it works:
```
()()()()((()()(())))(())
^^^ becomes
(((((()))))(()(())))(())
```
Similarly computing the words in the reverse of this order also takes 33 bytes:
```
=*QK`()WJhx
Q_K=+t.iFc2_<QJ+K>QhJ
```
[Try it online](https://pyth.herokuapp.com/?code=%3D%2aQK%60%28%29WJhx%0AQ_K%3D%2Bt.iFc2_%3CQJ%2BK%3EQhJ&input=3)
[Answer]
## CJam (48 bytes)
```
ri"()"*${_p_,{1$>_)-,\(-,<},_{W=/(\s$1m>+}{&}?}h
```
[Online demo](http://cjam.aditsu.net/#code=ri%22()%22*%24%7B_p_%2C%7B1%24%3E_)-%2C%5C(-%2C%3C%7D%2C_%7BW%3D%2F(%5Cs%241m%3E%2B%7D%7B%26%7D%3F%7Dh&input=4). This effectively takes one obvious recursive solution and makes it iterative. Instead of actually simulating the steps back up the stack, it applies a successor rule:
>
> Find the last `(` which starts a suffix with strictly more `)` than `(`; sort that suffix, and rotate once.
>
>
>
Note that this is deliberately designed to avoid keeping the full list of solutions in memory, because I don't think it fits (at least, not if run on a 64-bit machine. It might on a 32-bit machine). There are `9694845` Dyck paths for `n=15`, so that's `30*9694845` characters, and `92*9694845 = 891925740` bytes of memory just for the (Java) String objects. But then the `List` holding the objects probably wraps an array with space for `16777216` elements, which is a further 256MB, and the CJam interpreter itself seems to add quite a bit of overhead.
---
### (42 bytes)
```
Ma{{_'(+\')+}%{"()"\f{\-,}I+_$=},}ri:I2**,
```
This builds the strings up one character at a time, filtering to ensure that no string has more than `n` opening parentheses or more closing than opening parentheses. However, it runs out of memory with 3GB for `n=15`.
The same idea at 39 bytes, but this runs out of memory earlier.
```
Ma{"()":Sm*::+{S\f{\-,}I+_$=},}ri:I2**`
```
[Online demo](http://cjam.aditsu.net/#code=Ma%7B%22()%22m*%3A%3A%2B%7B%24I%3E'(%26!%7D%2C%7B%24_%2C(2%2F%3D'(%3D%7D%2C%7Dri%3AI2**%60&input=4)
---
### (24 bytes)
My original answer, now disqualified by rule changes.
```
{"()"*e!{0\+{~_}*]1&!},}
```
This is an anonymous function which takes input on the stack. [Online demo](http://cjam.aditsu.net/#code=4%0A%0A%7B%22()%22*e!%7B0%5C%2B%7B~_%7D*%5D1%26!%7D%2C%7D%0A%0A~%60).
It works by the obvious approach of taking all permutations of `n` pairs of parentheses and filtering for those which are balanced.
[Answer]
## JavaScript (ES6), 125 bytes
```
n=>{for(i=m=1<<n+n-1;i&m;i++){for(j=m,z=o=0;o>=z;j>>=1)i&j?o++:z++;o-n||console.log(i.toString(2).replace(/./g,d=>")("[d]))}}
```
Actually printing the results slows things down horribly, but with `console.log` set to `()=>{}` this takes my machine about 7 seconds for n=12, which presumably translates to 7 minutes for n=15. If that's not fast enough, you can replace `i++` with `i+=2` or even `i+=j||2` but that made only a few percent difference in my testing. Works by generating all 2n-digit binary numbers and checking whether they represent a Dyck word. Ungolfed:
```
function dyck(n) {
// Don't bother generating words that begin with ),
// so start half-way though 4 ** n.
for (var i = 4 ** n / 2; i < 4 ** n; i += 2) {
// Convert to the string of ()s.
var word = i.toString(2);
word = word.replace(/1/g, "(");
word = word.replace(/0/g, ")");
// Count the (s and )s separately.
var left = 0;
var right = 0;
for (var j = 0; j < n + n; j++) {
if (word[j] == "(") left++;
else right++;
// Abort if there are too many )s
if (right > left) break;
}
// If we got exactly n (s then it's a Dyck word.
if (left == n) console.log(word);
}
}
```
[Answer]
# C, ~~748~~ ~~746~~ 651 bytes
```
#define C(v,n) for(v=n==D;v<=(n<=D);v++)
void p(Z){unsigned long long R,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D=Z*2,E,F;C(C,30)C(B,29)C(A,28)C(z,27)C(y,26)C(x,25)C(w,24)C(v,23)C(u,22)C(t,21)C(s,20)C(r,19)C(q,18)C(p,17)C(o,16)C(n,15)C(m,14)C(l,13)C(k,12)C(j,11)C(i,10)C(h,9)C(g,8)C(f,7)C(e,6)C(d,5)C(c,4)C(b,3)C(a,2){R=C<<29|B<<28|A<<27|z<<26|y<<25|x<<24|w<<23|v<<22|u<<21|t<<20|s<<19|r<<18|q<<17|p<<16|o<<15|n<<14|m<<13|l<<12|k<<11|j<<10|i<<9|h<<8|g<<7|f<<6|e<<5|d<<4|c<<3|b<<2|a<<1;if(__builtin_popcount(R)!=Z)goto X;F=0;for(E=D-1;E;E--)if(R&1<<E)F++;else if(F)F--;else goto X;for(;E<D;E++)putchar(40+!(R&1<<D-E-1));puts("");X:;}}
```
At a whopping >600 bytes, this isn't really much of a contender...but it's pretty fast and memory efficient.
Works by encoding the parentheses strings as integers, with a set bit representing `(` and an unset bit representing `)`. For instance, `(())` would be `1100`. I made the following observations:
* All permutations must begin with `(` and end with `)`; otherwise, it won't be valid.
* Every valid permutation must have `n` left parentheses and `n` right parentheses, where `n` is the input number. I used `__builtin_popcount` for this.
When built via `icc -march=native -O3`, it takes 17s on my computer, though others have reported better times (~3-7s) on their (presumably faster) computers. In addition, it uses around 1.5 KB of memory.
Here's the code with explanatory comments:
```
// Z is the input number.
void p(Z){
// All the variables.
// R is the resulting paren number, with 1 bits for open parens and 0s for closed ones.
// a-C are used to hold the state of each paren (1 if open, 0 if closed).
// D holds Z*2, or the total length of the paren string.
// E and F are used later on.
unsigned long long R,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D=Z*2,E,F;
/* Each loop performs a basic check. If D is equal to the corresponding
number, then the variable will start at 1 (since the first paren must
always be open). If D is greater than or equal to the number, then the loop
will only be run once with the variable set to 0, and a later check will
cause the variable to be ignored. Otherwise, it will loop twice; one for a
closed paren (0), and one for an open one (1). Of course, if D == the
number, then it will only loop for the open paren (as stated above). */
for (C = (D == 30); C <= (30 <= D); C++)
for (B = (D == 29); B <= (29 <= D); B++)
for (A = (D == 28); A <= (28 <= D); A++)
for (z = (D == 27); z <= (27 <= D); z++)
for (y = (D == 26); y <= (26 <= D); y++)
for (x = (D == 25); x <= (25 <= D); x++)
for (w = (D == 24); w <= (24 <= D); w++)
for (v = (D == 23); v <= (23 <= D); v++)
for (u = (D == 22); u <= (22 <= D); u++)
for (t = (D == 21); t <= (21 <= D); t++)
for (s = (D == 20); s <= (20 <= D); s++)
for (r = (D == 19); r <= (19 <= D); r++)
for (q = (D == 18); q <= (18 <= D); q++)
for (p = (D == 17); p <= (17 <= D); p++)
for (o = (D == 16); o <= (16 <= D); o++)
for (n = (D == 15); n <= (15 <= D); n++)
for (m = (D == 14); m <= (14 <= D); m++)
for (l = (D == 13); l <= (13 <= D); l++)
for (k = (D == 12); k <= (12 <= D); k++)
for (j = (D == 11); j <= (11 <= D); j++)
for (i = (D == 10); i <= (10 <= D); i++)
for (h = (D == 9); h <= (9 <= D); h++)
for (g = (D == 8); g <= (8 <= D); g++)
for (f = (D == 7); f <= (7 <= D); f++)
for (e = (D == 6); e <= (6 <= D); e++)
for (d = (D == 5); d <= (5 <= D); d++)
for (c = (D == 4); c <= (4 <= D); c++)
for (b = (D == 3); b <= (3 <= D); b++)
for (a = (D == 2); a <= (2 <= D); a++) {
/* R is the result here. Each variable is shifted and bitwise-ORd with the
others to generate a number representing the string.
For instance, (()) would be 1100, and ()(()) would be 101100. */
R=C<<29|B<<28|A<<27|z<<26|y<<25|x<<24|w<<23|v<<22|u<<21|t<<20|s<<19|r<<18|
q<<17|p<<16|o<<15|n<<14|m<<13|l<<12|k<<11|j<<10|i<<9|h<<8|g<<7|f<<6|
e<<5|d<<4|c<<3|b<<2|a<<1;
// If there is an uneven balance of parens, then just jump to the loop end.
if(__builtin_popcount(R)!=Z) goto X;
// F here is the number of opening parens.
F=0;
// E is a counter used to extract each bit.
for(E=D-1;E;E--)
// If the bit is set, then increment the number of open parens.
if(R&1<<E) F++;
// If the bit wasn't set, then decrement the number of open parens...
else if(F) F--;
// ...but, if there were no open parens, then it's unbalanced; jump to the end
else goto X;
// E (the bit counter) is already 0.
// Loop through each bit...
for(;E<D;E++)
/* ...and print it out. 40 is the ASCII code for `(`. If the bit
is set, the ! will negate it, and 0 will be added to the `(`.
Otherwise, it will turn the left paren into a right paren. */
putchar(40+!(R&1<<D-E-1));
// Newline.
puts("");
// End of loop.
X:;
}
}
```
## 746-byte version
```
#define C(v,n) for(v=(n==D);v<=(n<=D);v++){
void p(Z){unsigned long long R,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D=Z*2,E,F;C(C,30)C(B,29)C(A,28)C(z,27)C(y,26)C(x,25)C(w,24)C(v,23)C(u,22)C(t,21)C(s,20)C(r,19)C(q,18)C(p,17)C(o,16)C(n,15)C(m,14)C(l,13)C(k,12)C(j,11)C(i,10)C(h,9)C(g,8)C(f,7)C(e,6)C(d,5)C(c,4)C(b,3)C(a,2)R=(C<<29)|(B<<28)|(A<<27)|(z<<26)|(y<<25)|(x<<24)|(w<<23)|(v<<22)|(u<<21)|(t<<20)|(s<<19)|(r<<18)|(q<<17)|(p<<16)|(o<<15)|(n<<14)|(m<<13)|(l<<12)|(k<<11)|(j<<10)|(i<<9)|(h<<8)|(g<<7)|(f<<6)|(e<<5)|(d<<4)|(c<<3)|(b<<2)|(a<<1);if(__builtin_popcount(R)!=Z)continue;F=0;for(E=D-1;E;E--)if(R&(1<<E))F++;else if(F)F--;else goto X;for(;E<D;E++)putchar('('+!(R&(1<<D-E-1)));puts("");X:;}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
```
[Answer]
# Python 2, ~~117~~ 116 bytes
```
def f(n):r='',;exec"r=[s+c for s in r for t in[s.count('(')]for c in')('[t+t==len(s):2-t/n]];"*2*n;print'\n'.join(r)
```
This builds the strings character by character, without filtering.
With piped output and input **n = 15**, this takes roughly 39 seconds with CPython and *7.5 seconds* with PyPy on my machine. Memory consumption is 1.6 GB with CPython and 2.5 GB with PyPy.
Test it on [Ideone](http://ideone.com/qu70hh).
[Answer]
# JavaScript (ES6), 203
Implementing [this algorithm](http://arxiv.org/pdf/1002.2625v1.pdf) (point 3, totally iterative)
Within the limits of script executing in Firefox, I managed to have the 200K console output for input 12 in about 1.5 minutes
```
n=>{
for(b=[...Array(n)].map((_,i)=>1+2*i),z=0;!z;)
for(c=[...'('.repeat(n+n)],b.map(n=>c[n]=')'),console.log(c.join``),z=i=n;i--&&z;)
if(b[i]<n+i)for(z=0,b[j=i]++;++j<n-1;)b[j]=Math.max(b[j-1],2*j)+1
}
```
*Less golfed*
```
n=>{
b=[...Array(n)].map((_,i)=>1+2*i)
q=0
for(z=0;!z;)
{
c=[...'('.repeat(n+n)],
b.map(n=>c[n]=')'),
console.log(++q,c.join``)
for(z=i=n;i--&&z;)
if(b[i]<n+i)
for(z=0,b[j=i]++;++j<n-1;)
b[j]=Math.max(b[j-1],2*j)+1
}
}
```
**Ported to C** just for fun, run in 5 secs for input 15 (it compiles and works without #includes)
```
f(n){int i,j,z,b[49];char c[99];
for(i=n;i--;)b[i]=2*i+1;
for(z=0;!z;){memset(c,40,n+n);c[n+n]=0;
for(i=n;i--;)c[b[i]]=41;puts(c);
for(z=i=n;i--&&z;)if(b[i]<n+i)for(z=0,b[j=i]++;++j<n;)b[j]=(b[j-1]>2*j?b[j-1]:2*j)+1;
}}
```
**Test** generating all output but do not display it, just counting output rows
I got 90 sec for input 15
```
F=n=>{
for(b=[...Array(n)].map((_,i)=>1+2*i),z=0;!z;)
for(c=[...'('.repeat(n+n)],b.map(n=>c[n]=')'),console.log(c.join``),z=i=n;i--&&z;)
if(b[i]<n+i)for(z=0,b[j=i]++;++j<n-1;)b[j]=Math.max(b[j-1],2*j)+1
}
console.log=x=>o++ // console.log display no output, just count rows
function test() {
n=+I.value,o=0,t=+new Date
O.textContent='...wait...'
setTimeout(_=>(F(n),O.textContent=['rows='+o,'time sec '+(new Date-t)/1000]), 10)
}
test()
```
```
N:<input id=I value=12 type=number max=20><button onclick='test()'>go</button>
<pre id=O></pre>
```
[Answer]
# J, ~~97~~ ~~70~~ ~~69~~ ~~68~~ ~~60~~ 59 bytes
```
'()'{~(,:'')((((>:#-+/)*(]#>:2*+/))"1#]),.&0,,.&1)^:(2*[)~]
```
Now tacit!
This is a monad that uses binary digits to create pairs of parentheses. In order to meet the requirements, a non-recursive approach is used along with optimization by use of certain primitives to ensure that mostly boolean (1 byte) values are used to keep memory requirements low.
On my computer, using an i7-4770k, it takes about 50 seconds to compute the result for *n* = 15 and uses about 1.5 GB of memory.
In the interests of maximizing speed, this version with **70 bytes** computes the result for *n* = 15 in 0.5 seconds while using about 800 MB of memory. It's also tacit!
```
'()'{~[:;@(<@([:,/],"1/0=|."1)/.~+/"1)<:1&(],(+/<:#-+/)"1@,.~#,.~)1$0:
```
## Usage
```
f =: '()'{~(,:'')((((>:#-+/)*(]#>:2*+/))"1#]),.&0,,.&1)^:(2*[)~]
timer =: 6!:2
f 3
()()()
(())()
()(())
(()())
((()))
10 timer 'r =: f 15' NB. Average time over 10 runs
49.9951
# r
9694845
```
[Answer]
# Pyth, 47 bytes
```
<-empty line
Musm?<J/d\(Q?>-J/d\)0,+d\(+d\)]+d\(]+d\)G*2Q]k
```
Took 18 minutes on my machine, and over 2GB RAM.
In pythonic pseudocode:
```
// newline means "print"
M map(print,
u reduce(lambda G,H:
sm sum(map(lambda d:
,+d\(+d\) ([d+"(",d+")"] if
?>-J/d\)0 J-d.count(")") > 0
]+d\( else [d+"("]) if
?<J/d\(Q (J=d.count("(") < Q
]+d\) else [d+")"],
G G)),
*2Q]k 2*input(),[""]))
```
In words:
1. create a function that maps any string to a list of strings that can be formed by adding "(" or ")"
if the parentheses are already matched, only "(" can be added; if there are already n "(", only ")" can be added; otherwise a pair is returned
2. create a new function that maps the old function over its param, and then sum up the map, so that it takes a list of strings, maps to a list of lists of strings, and then de-nests it back into a list of strings
each call essentially "grows" its params by one `(` or `)`
3. reduce this new function over `range(2*input())`, with `[""]` as base case
essentially just passing `[""]` through the new function 2n times
4. map `print` over the return value of `reduce` to print each string in new lines
[Answer]
## Haskell, ~~111~~ 105 bytes
```
import Data.Function
id=<<fix(\h a z->id=<<[('(':)<$>h(a-1)z|a>0]++[(')':)<$>h a(z-1)|a<z]++[[""]|a+z<1])
```
Usage example: `id=<<fix(\h a z->id=<<[('(':)<$>h(a-1)z|a>0]++[(')':)<$>h a(z-1)|a<z]++[[""]|a+z<1]) $ 3` -> `["((()))","(()())","(())()","()(())","()()()"]`.
The Dyck word building algorithm used here expressed in a classic recursive way looks like
```
dyck a z = -- take two numbers, `a` (the number of `(` to use)
-- and `z` (the number of `)` to use)
[[""]|a+z<1] -- base case if both numbers are 0, the result
-- is an empty word
[('(':)<$>dyck(a-1)z|a>0] -- if there are `(` left, prepend one to every result
-- from a recursive call with one `(` less
[(')':)<$>dyck a(z-1)|a<z] -- same for `)` if there are more than `(`.
id=<< ... ++ ... ++ -- combine those results in to a flat list
```
As recursion is not allowed, we pass the function to call as a third parameter `h` (and use a lambda instead of a named function):
```
\h a z -> .... h(a-1)z .... h a(z-1)
```
and let the fixpoint combinator `fix` create this function for us:
```
fix(\h a z ...)
```
finally, the leftmost `id=<<` duplicates the input parameter: `(id=<<) f n` is `f n n`, so when the whole function is called, the parameter `n` is used as `a` and `z`.
For input `15` it takes about 3min within ghci (25s when compiled) and a few MB on my 5 year old laptop.
[Answer]
# Haskell, ~~140~~ 132 bytes
Thanks @nimi for saving a few bytes!
```
import Data.List
h s|m<-length s=nub[k|l<-s!!0,k<-('(':l++")"):[u++v|n<-[0..m-2],u<-s!!n,v<-s!!(m-2-n)]]:s
f n=iterate h[[""]]!!n!!0
```
First of all: `iterate` does create a recursion sequecnce of `h`, but this is a builtin, and by the rules we may use builtins that use recursion.
This is just a very simple recursive approach, we can generate the n-Dyck-words by putting (n-1)-Dyck-words between paranthesis, or by concatenating from shorter Dyck words. This approach however does generate duplicates, that is why we filter for unique elements using `nub`.
As Haskell is a functional language, it is almost impossible to do this without recursion. There is an even more direct approach, but that one is banned under the current rules.
] |
[Question]
[
Your program will be given a number as input. Your challenge is to output all the numbers between 2 and 100 inclusive that are co-prime to the given number. (Two numbers are co-prime if their GCD is 1.) If no numbers between 2 and 100 are co-prime to the given number, the program shall not output anything.
The program must receive the number from STDIN, and the output must be a list of numbers separated by a comma and a space.
**Contest closes June 14th, 2014, two weeks from now. The shortest solution wins.**
Examples (here the range is from 2 to 20):
3:
```
2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20
```
12:
```
5, 7, 11, 13, 17, 19
```
9699690:
(No output: no numbers between 2 and 20 are co-prime to 9699690).
**EDIT:** Esoteric languages (e.g. J or GolfScript) are now being assessed separately from non-esoteric languages. This is to make the challenge fair.
[Answer]
# CJam, 23 bytes
```
101,:N2>q~mf{N%-}/", "*
```
[Try it online.](http://cjam.aditsu.net/) Paste the *Code*, type an integer in *Input* and click *Run*.
### Example
```
$ cjam factor.cjam <<< 210
11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
```
### How it works
```
101,:N # Push the array [ 0 ... 100 ] and save it in “N”.
2> # Remove 0 and 1 from the array.
q~mf # Read from STDIN, interpret the input and factorize the resulting integer.
{ # For each prime factor:
N% # Collect all multiples of the prime factor in an array.
- # Apply set difference with the array on the stack.
}/ # This leaves only integers that are coprime with the input.
", "* # Join by commas and spaces.
```
[Answer]
# Haskell, 76 characters
```
main=do n<-readLn;putStrLn.drop 2$[show k|k<-[2..100],gcd k n<2]>>=(", "++)
```
[Answer]
# GolfScript - 36
```
~:x;101,2>{.x{.@\%.}do;1>{;}*}%", "*
```
Explanation:
`~` evaluates the input to a number
`:x;` assigns the number to variable x
`101,2>` makes an array [2 ... 100]
`{...}%` applies the block to each array element, resulting in a modified array
`.x` duplicates the current number (from 2 to 100) then pushes x
`{.@\%.}do;` calculates the gcd (see the GolfScript home page)
`1>` checks if the gcd was greater than 1
`{;}*` executes the block if the condition was true; the block (`;`) pops the current number from the stack, thus taking it out of the array
`", "*` joins the resulting array using the ", " separator
[Answer]
# Python 2.7 - 87 bytes
```
from fractions import*
x=input()
print', '.join(`i`for i in range(2,101)if gcd(x,i)==1)
```
This is very similar to qwr's answer [here](https://codegolf.stackexchange.com/questions/29905/find-all-numbers-between-2-and-100-co-prime-to-a-given-number/29922#29922), I shaved off some bytes but the changes were too substantial to fit in a comment. Full respect goes to them.
**Modifications:**
* Removed unnecessary space in `from fractions import *` for one byte.
* Moved the whole thing to python 2.7. I couldn't actually get the original answer to run on my machine because `input()` returns a string in python 3. The only thing that was specific to python 3 in the answer was defining the output format in the `print` function...
* ...which I changed anyway. The original answer looped through all the numbers and printed them out if the met the requirements. Here, I throw the whole thing in a generator function (with the output wrapped in backticks so we get a string) and `join` the numbers together, which saves bytes and means we don't have to use the "technically rules-valid" output format the original answer used (`23 ,29 ,31 ,37`... is a list of numbers separated by a comma and a space, but it doesn't waste any characters in my version to print out `23, 29, 31`... like the OP was probably expecting).
[Answer]
## Ruby, 52 46 (43 + 3 for " -p" option)
Now *does* beat it J (barely). Caveat: doesn't exit after outputting (you can actually keep giving more inputs after the first).
```
$_=(2..100).select{|w|w.gcd(eval$_)<2}*", "
```
[Answer]
# Julia - ~~70~~ ~~69~~ 68 characters
```
i=int(readline());print(join(find([gcd(i,x)<2 for x=2:100])+1,", "))
```
Saved a character by using a list comprehension rather than a map, pretty much thanks to not needing the dotted `.==`. I suspect that I can do better, still.
Second edit saved another character by using `<2` rather than `==1`, as gcd can't produce a number less than 1 (except when both inputs are 0, which cannot happen with this code), and must produce an integer.
Old version:
```
i=int(readline());print(join(find(map(x->gcd(i,x),2:100).==1)+1,", "))
```
Note that int is Int64 (assuming a 64 bit machine), meaning that you can't actually have a number big enough to be non-coprime to every number between 2 and 100. To have it accept arbitrary-size integers, you need to replace `int` with `BigInt`, for a total of 73 characters.
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 6 bytes
```
₅ḢΩ?ĠḂ
```
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLigoXhuKLOqT/EoOG4giIsIiIsIjE1IiwiMy40LjAiXQ==)
RIP H flag
[Answer]
# JavaScript (ECMAScript 6) - 82 Characters
```
g=(a,b)=>b?g(b,a%b):a;f=x=>[k for(y in[...Array(99)])if(g(x,k=+y+2)<2)].join(', ')
```
**Explanation:**
Firstly a recursive function `g` to calculate the gcd:
```
g=(a,b)=>b?g(b,a%b):a;
```
Secondly, a function `f` taking a single argument `x`:
* `Array(99)` - Start with an uninitialised array of length 99.
* `[...Array(99)]` - Use the `...` spread operator to turn it into an array of 99 elements each initialised to `undefined`.
* `[+y+2 for(y in[...Array(99)])]` - Use Array Comprehension to map the array of `undefined` values to an array of integers `2..100`.
* `[k for(y in[...Array(99)])if(g(x,k=+y+2)<2)]` - Add an additional restriction to only include those values where `GCD(x,value)` is 1.
* `.join(', ')` - at the end return it as a comma-space delimited string to meet the requirement of outputting nothing if there are no matches.
**Alternative**
Taking input from a prompt (87 characters):
```
x=prompt(g=(a,b)=>b?g(b,a%b):a);[k for(y in[...Array(99)])if(g(x,k=+y+2)<2)].join(', ')
```
[Answer]
# J (20):
Not quite complying with the rules as they are now, but hey... JS isn't either ;)
```
}.(1=a+.i.101)#i.101
```
Showcase:
```
a=:3
}.(1=a+.i.101)#i.101
2 4 5 7 8 10 11 13 14 16 17 19 20 22 23 25 26 28 29 31 32 34 35 37 38 40 41 43 44 46 47 49 50 52 53 55 56 58 59 61 62 64 65 67 68 70 71 73 74 76 77 79 80 82 83 85 86 88 89 91 92 94 95 97 98 100
a=:12
}.(1=a+.i.101)#i.101
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 79 83 85 89 91 95 97
a=:9699690
}.(1=a+.i.101)#i.101
23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
```
## Deconstruction:
Remember that J programs start at the back:
```
i.101
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88...
a=:12
a+.i.101 NB. Takes GCD
12 1 2 3 4 1 6 1 4 3 2 1 12 1 2 3 4 1 6 1 4 3 2 1 12 1 2 3 4 1 6 1 4 3 2 1 12 1 2 3 4 1 6 1 4 3 2 1 12 1 2 3 4 1 6 1 4 3 2 1 12 1 2 3 4 1 6 1 4 3 2 1 12 1 2 3 4 1 6 1 4 3 2 1 12 1 2 3 4 1 6 1 4 3 2 1 12 1 2 3 4
1=a+.i.101
0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0
(1=a+.i.101)#i.101
1 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 79 83 85 89 91 95 97
}.(1=a+.i.101)#i.101
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 79 83 85 89 91 95 97
```
[Answer]
# Javascript (*ES5*) - 92 91
This solution runs in the [Spidermonkey commandline shell](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Introduction_to_the_JavaScript_shell). It takes input from STDIN (as per the rules).
```
with([])for(a=readline(b=1);b++<99||print(join(', '));--c||push(b))for(c=a,d=b;d;)d=c%(c=d)
```
Here is a solution that runs in the browser console and takes input from `prompt` and outputs with `alert`: **(89 bytes)**
```
with([])for(a=prompt(b=1);b++<99||alert(join(', '));--c||push(b))for(c=a,d=b;d;)d=c%(c=d)
```
If implicit printing in the browser console is allowed, it can go even further: **(82 bytes)**
```
for(o=[],a=prompt(b=1);b++<99;--c||o.push(b))for(c=a,d=b;d;)d=c%(c=d);o.join(', ')
```
[Answer]
## Haskell - 105
```
import Data.List
main=do
x<-getLine
putStrLn.intercalate", ".map show$filter((1==).gcd(read x))[2..100]
```
Quite obvious if you can understand Haskell. :)
[Answer]
# Lua, 126
Now it's 2 times longer, but it actually works.
```
c=io.read()function g(a,b)return b~=0 and g(b,a%b) or tonumber(a) end for i=2,100 do if g(i,c)<2 then io.write(i,', ') end end
```
---
# Lua, 63
Not much better, but still...
```
c=io.read()for i=2,100 do if i%c>0 then io.write(i,', ')end end
```
# Lua, 64
```
c=io.read()for i=2,100 do if i%c>0 then io.write(i..', ')end end
```
[Answer]
## Pyke, 9 bytes (noncompeting)
```
TXSt#.H1q
```
[Try it here!](http://pyke.catbus.co.uk/?code=TXSt%23.H1q&input=12&warnings=0)
```
TX - 10**2 (100)
St - range(2, ^)
# - filter(^, V)
.H - highest_common_factor(i, input)
1q - ^ == 1
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `H`, 44 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 5.5 bytes
```
ɽḢ'?ġ1=
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJIPSIsIiIsIsm94biiJz/EoTE9IiwiIiwiMyJd)
Bitstring:
```
00100110011110110000000000001000100000100111
```
Because vyxal 3 is missing a lot of numerical operations :p
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Lõ ÅfjU
```
[Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=TPUgxWZqVQ&input=MTI)
[Answer]
## [Sage](http://sagemath.org), 79
A boring answer, since I'm not in the mood of writing an interesting one.
```
l=[]
n=input()
for i in range(2,101):
if gcd(i,n)==1:l+=[i]
print str(l)[1:-1]
```
Sample outputs:
```
sage: %runfile coprimelist.py
3
2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25, 26, 28, 29, 31, 32, 34, 35, 37, 38, 40, 41, 43, 44, 46, 47, 49, 50, 52, 53, 55, 56, 58, 59, 61, 62, 64, 65, 67, 68, 70, 71, 73, 74, 76, 77, 79, 80, 82, 83, 85, 86, 88, 89, 91, 92, 94, 95, 97, 98, 100
sage: %runfile coprimelist.py
12
5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49, 53, 55, 59, 61, 65, 67, 71, 73, 77, 79, 83, 85, 89, 91, 95, 97
sage: %runfile coprimelist.py
9699690
23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
sage: %runfile coprimelist.py
factorial(100)
sage:
```
[Answer]
# python - 90
Boring answer. The output is a little strange (but meets the rules)
```
from fractions import *
x=input()
for i in range(2,101):
if gcd(x,i)==1:print(i,",",end="")
```
[Answer]
# J - 47 char
Requiring input on STDIN (no trailing newlines, please) and outputting to STDOUT in proper form.
```
(2}.&;(2+i.99)(', ';":)&>@([#~1=+.)".)&.stdin''
```
`2+i.99` is the integers from 2 to 100 inclusive. `([#~1=+.)` keeps only those integers coprime to the input, and then `(', ';":)` converts each (`&>`) to a string and adds the comma and space before each entry. `;` combined the entire result into a single string, and `2}.` drops the comma and space before the first one.
[Answer]
# ised (28)
```
ised '@1{6};' '?{{:gcd{x$1}:}@::[101]<2}\1'
```
The first argument is just setting the argument (6 in this case). The second evaluates the result.
With unicode, it's a bit shorter (26).
```
ised '@1{6};' '?{{:gcd{x$1}:}∷[101]<2}\1'
```
Unfortunately, the braces take up a lot of space in ised because it's not stack-based.
[Answer]
# [wxMaxima](http://andrejv.github.io/wxmaxima/): ~~67~~ ~~85~~ 80
I had to adjust my answer to fit the specs (i.e., take a value from stdin)
```
f():=block(n:read(),for i:2thru 100 do if(gcd(i,n)=1)then printf(true,"~d, ",i) )
```
Call this in the interactive session via `f` and then enter in your value followed by `ctrl+enter` to get the result.
---
Old, non-spec fitting answer
```
f(n):=for i:1thru 100 do(if(gcd(i,n)=1)then printf(true,"~d, ",i));
```
Enter this into the command line & execute it via `f(12);` to get
```
1,5,7,11,13,17,19,23,25,29,31,35,37,41,43,47,49,53,55,59,61,65,67,71,73,77,79,83,85,89,91,95,97,
```
[Answer]
# Python 3 - 79 chars
```
x=int(input())
for i in range(2,101):print(i) if pow(x,i-1,i)==1or i==x+1else 0
```
Uses the [Fermat primality test](https://en.wikipedia.org/wiki/Fermat_primality_test) to check co-primes.
[Answer]
# APL(NARS), 35 chars
```
5↓∊(⊂', '){⍺⍵}¨' ',⍕¨a⊂⍨1=⎕∨a←1+⍳99
```
use as:
```
5↓∊(⊂', '){⍺⍵}¨' ',⍕¨a⊂⍨1=⎕∨a←1+⍳99
⎕:
2310
┌78─────────────────────────────────────────────────────────────────────────────┐
│ 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97│
└───────────────────────────────────────────────────────────────────────────────┘
```
[Answer]
# [Tcl](http://tcl.sourceforge.net), 218 bytes
Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=NY9BCsIwFET3PcUgcaegrgT1JCWLtE01pqQh_UWh5CRuiuKh9DT-WN095g8zf24PKptxfPZUL7evtw9tiWNZYVAoIobLyTQag0jcaQJBFDskKpDrqw98U5izGuWkKwiKOwRNfXAQKmZJdX93ftTUoaPKOBnl9xaQN6YjmdVtmFosNtwnLPYHrFcrZuPKAJugThn8oOBwK3FgB8uN8l67irOEjTHzPZfk59awKWC2wExOC39Dx_t6M9EH)
```
proc gcd {a b} {while {$b} {set t $b; set b [expr {$a % $b}]; set a $t}; return $a}
set n [expr {[gets stdin]}]
set r [list]
for {set k 2} {$k <= 100} {incr k} {if {[gcd $n $k] == 1} {lappend r $k}}
puts [join $r ", "]
```
Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=VVOxbtswEAUy6iteUgVIARewPXVIpkwpOnU1PFDUyWZFkQRJNW0Ff0kXo0V_Kh8T5EhJtqNBIHl37917R_75F6U-Hv_3sfn0-eXq1Xkr0QllMBwwFODvA76RqCFg-q4ij8bbDsq4PuZwoAiDzY5iQIi1Mtt8PJU-GRWV0Oo3QRhQ5-IvaBUiouVs6wlxTxNyOOONe-6hmHC-Wus41dt-tz-F1wlltVwydA25J9lCNdjJGs8qchpUgKYQuJDJ1xmqsR5D4mixZoVli_uHhMFrZaRHO8seeR9n1NRmQrYNVya-jL7CnbTOq44-noo4edikVMYuzRb3megUnnxpEOwCwjlirDYJSQzZGqa4NGT-9JQ8qy_bU_hQnP-TYV8sz_DC29ESAWm7TmQBAsEJSYu84UwDFmLGofJwAzbfE0Y5A9wscLMteCL5jiSBg0B1viWPQsteiziOdOeJl6wmEVqDWv1Qgb1ncSN9lcue90oTj6HC9QOWlz6lGUW-MCird2cVNvTT8RBLgVsOHrbvwgJlqrowxFPsPesQqffcps4d5luetFDdeyrSdnwG02s4_l2tx9Ub)
```
proc main {} {
# Read a number from input
set n [gets stdin]
# Initialize an empty list to store the numbers
set numbers {}
# Loop through numbers 2 to 100 and check if gcd with n is less than 2
for {set k 2} {$k <= 100} {incr k} {
# Check if the gcd of k and n is 1 (coprime)
if {[gcd $k $n] < 2} {
# If so, append k to the list of numbers
lappend numbers $k
}
}
# Join the numbers with a comma and a space, and then print
puts [join $numbers ", "]
}
proc gcd {a b} {
# Calculate the greatest common divisor of a and b
while {$b != 0} {
set temp $b
set b [expr {$a % $b}]
set a $temp
}
return $a
}
# Call the main procedure
main
```
] |
[Question]
[
# Output all numbers in certain range containing certain digits
### Task
1. Take an input of digits through console, prompt, or a file (in the decimal number system). These digits should be separated by spaces.
2. Take an input of the "maximum" through console, prompt, or a file
3. If you use a file, the program must output `"[Data taken from file]"`
4. Print all [natural numbers](http://en.wikipedia.org/wiki/Natural_number) (including 0) below the maximum containing **at least one** of the digits specified by the user (they may contain other digits), separated by a single space. **Leading `0`s do not count!**
5. If there is a sequence of 10 or more consecutive numbers, it should output the first and last, separated by a `-->`
### Rules
* Standard loopholes are (obviously) not allowed
* Programs must complete the tasks above
* The answer with the fewest characters wins
### Examples
```
>>> 1 3
>>> 100
1 3 10 --> 19 21 23 30 --> 39 41 43 51 53 61 63 71 73 81 83 91 93
```
---
```
>>> 1 2 4 5 6 7
>>> 29
1 2 4 5 6 7 10 --> 28
```
---
```
>>> 0 1 2 3 4 5 6 7 8 9
>>> 9999999
0 --> 9999998
```
---
```
[Data taken from file]
1 3 5 7 9
```
[Answer]
## Ruby, ~~186~~ ~~181~~ 177 bytes
```
a=gets.split;puts ([0]+(0...gets.to_i).select{|x|(x.to_s.split('')&a).any?}).each_cons(2).slice_before{|m,n|m+1<n}.map{|a|c=a.map &:last;c.count>9?[c[0],'-->',c.last]:c}.join' '
```
Ungolfed explanation:
```
# Read numbers from input and split into array
a = gets.split
# Loop from 0 to maximum number, exclusive
puts ([0]+(0...gets.to_i).select { |x|
# Only include numbers that include at least one input digit
(x.to_s.split('')&a).any?
}) # Add dummy element to the beginning of array
.each_cons(2) # Get each array of 2 consecutive elements
.slice_before { |m, n| #
m + 1 < n # "Slice" the array if m and n are not consecutive
}.map { |a|
c = a.map &:last # Get all the last elements in `a`
if c.count > 9
# 10 or more consecutive elements. Get the first and last, and
# an arrow in-between
[c[0],'-->',c.last]
else
c
end
}.join ' ' # Add space in-between all elements, and print result
```
[Answer]
# JavaScript (E6) 153 ~~157 161 163 177~~
Input and output via `prompt`
The main loop filters the numbers with a regexp and builds spans of consecutive numbers (as arrays). The O function concatenates the spans converting them to string. If the elements in a span array are 10 or more, instead of taking all elelements it just take the first and last number.
Test in FireFox/FireBug console
```
P=prompt,m=P(d=P());
O=_=>(
o+=s[9]?s[0]+" -->"+p:s.join(''),s=[]
);
for(s=[o=''],p=n=0;n<m;++n)
(n+'').match("["+d+"]")&&
(
n+~p&&O(),s.push(p=' '+n)
);
O(),P(o)
```
[Answer]
## GolfScript ~~74~~ 71 ([DEMO](http://golfscript.apphb.com/?c=OycxIDMgMTAwJwoKJyAnOsKnLyl%2BXG4qOng7LHtgeCZ9LDk5OmM7ey5jKT0he8KnXH0qOmN9JVvCp10vey4sOT57KCctLT4nQClcO317fn1pZn0lwqcq&run=true))
```
' ':§/)~\n*:x;,{`x&},99:c;{.c)=!{§\}*:c}%[§]/{.,9>{('-->'@)\;}{~}if}%§*
```
### Description:
The code expects the parameters passed via the console, like so:
```
echo "1 3 100" | ruby golfscript.rb numbers.gs
```
Here's the annotated code:
```
' ':§/ # Split input by space and save the
# space character in variable `§`
)~ # Take the last input and convert to int
# This is the "maximum" parameter.
\n*:x; # Take the list of digits and join them with
# newlines, resulting in a string.
# Save the result in variable `x` and take it
# off the stack
, # Take the "maximum" parameter and make an
# array [0, max)
{`x&}, # Filter the array, leaving only numbers that
# contain the right digits (that have at least
# one char in common with string `x`)
99:c; # Save the value 99 in a new variable, `c`.
{ # For each element (`n`) in the array:
. # - duplicate `n` on the stack
c)=!{§\}* # - if it does not equal `c`+1 add a space before it
:c # - assign the value of `n` to `c`
}%
[§]/ # Split the resulting array by spaces
{ # For each element `a` in the array of arrays:
. # - duplicate `a` on the stack
,9> # - check if length > 9
{('-->'@)\;} # - if `a`'s length is >9, then push "(min)", "-->" and "(max)"
# on the stack
{~}if # - otherwise, just place the elements of the current array
# on the stack
}%
§* # make a string representing the elements of the resulting array,
# separated by spaces
```
[Answer]
## Mathematica, ~~233~~ ~~191~~ ~~171~~ 165 bytes
```
t=StringSplit;Flatten[Split[Cases[Range@Input[d=t@InputString[]]-1,m_/;ToString@m~t~""⋂d!={}],#2-#<2&]/.{e:{__Integer}/;Length@e>9:>{#&@@e,"-->",Last@e}}]~Row~" "
```
I'm taking the input from two prompts which is as close to command line as it gets in Mathematica.
Ungolfed:
```
t = StringSplit;
Flatten[
Split[
Cases[
Range@Input[d = t@InputString[]] - 1,
m_ /; ToString@m~t~"" \[Intersection] d != {}
],
#2 - # < 2 &
] /. {e : {__Integer} /; Length@e > 9 :> {# & @@ e, "-->", Last@e}}
]~Row~" "
```
I'm simply filtering a range with all numbers to the relevant ones and then I'm collapsing consecutive subsequences with a repeated rule replacement.
[Answer]
# Ruby, 105 (or 110 if you need to add `.chop` to the gets to make your input work)
Run with command line flags `pl`.
```
r=/[#$_]/
$_=(?1...gets).grep(r).slice_before{|e|-1>eval("#@l-"+@l=e)}.map{|a|a[9]?[a[0],'-->',a[-1]]:a}*' '
```
Convert the first input to a character class in a regex. Generate all numeric strings between 1 and the next input (exclusive) and find the ones that match the regex. `slice_before` trick is stolen from August to find contiguous ranges, it gets shorter by using an instance variable to remember the last element so I don't need `each_cons`, but longer since I'm working with strings. I check for ranges of size 10 or more by seeing whether they have a 10th element or not (`a[9]`), and replace their internal elements with the arrow.
[Answer]
## Perl - ~~170~~ 162
```
$a=<>;chop$a;$a=~s/ /|/g;@b=grep{/$a/}(0..<>-1);while(++$c<@b){if($b[$c]-$b[$c-1]>1){($e=$c-$d)>9&&splice(@b,$d+1,$e-2,'-->')&&($c-=$e-3);$d=$c}}print join' ',@b
```
Ungolfed with comments:
```
$a=<>; #Read digits
chop$a;$a=~s/ /|/g; #Turn digit string into regex
@b=grep{/$a/}(0..<>-1); #Assign @b as list of numbers from 0 to second input which match the digits
while(++$c<@b){ #Loop $c through indexes of list
if($b[$c]-$b[$c-1]>1){ #If next number is not consecutive, do arrow adding stuff
($e=$c-$d)>9&& #If the number of previous consecutive numbers is at least 10
splice(@b,$d+1,$e-2,'-->')&& #Replace all but the first and last with '-->'
($c-=$e-3); #Subtract from index to compensate for decreased list length
$d=$c #Set $d (fist index of consecutive range) to current index
}
}
print join' ',@b #Print the list
```
[Answer]
# Python - ~~208 202~~ 211
```
D=raw_input()
n=input()
s=[`i`for i in range(n)if sum(d in`i`for d in D)]
i=0
while i<len(s):
j=len(s)
while j:
j-=1
try:
if int(s[j])-int(s[i])==j-i>8:s[i+1:j]=['-->']
except:1
i+=1
print' '.join(s)
```
[Answer]
# Bash+coreutils, 94 bytes
```
seq -s\ 0 $[$1-1]|sed -r "s/\b[^ ${2// }]+\b/:/g
s/([0-9]+)( [0-9]+){9,}/\1 -->\2/g
s/: ?//g"
```
* `seq` generates all numbers below the maximum
* The first `sed` line replaces any number not containing the interesting digits with `:`
* The second `sed` line searches for runs of 10 or more space-separated numbers and replaces with `start --> end`
* The final `sed` line removes unnecessary `:` and spaces.
### Output:
```
$ ./belowdigits.sh 100 "1 3"
1 3 10 --> 19 21 23 30 --> 39 41 43 51 53 61 63 71 73 81 83 91 93
$ ./belowdigits.sh 29 "1 2 4 5 6 7"
1 2 4 5 6 7 10 --> 28
$ ./belowdigits.sh 999999 "0 1 2 3 4 5 6 7 8 9"
0 --> 999998
$
```
[Answer]
## Python, 227
Currently the longest, but whatever.
```
a=raw_input().split()
l=[i for i in range(input())if any(x in str(i)for x in a)]
for i in l:
for j in l[::-1]:
try:L=l.index;l=l[:L(i)+1]+['-->']+l[L(j):]if j-i==L(j)-L(i)and j-i>8 else l
except:1
print' '.join(map(str,l))
```
[Answer]
# Haskell, ~~195~~ 194
```
main=interact$(\[d,m]->v$f(any(`elem`f(/=' ')d).s)[0..read m-1]).lines
s=show
f=filter
v l@(x:m)|g l>x+8=unwords[s x,"->",s$g l,v$f(>g l)l]|0<1=s x++' ':v m
v[]=""
g s=f(`notElem`s)[s!!0..]!!0-1
```
not very short but Imho quite good for this specific question and language.
[Answer]
# Python 2, 202 191
Another try at Python, using the same idea as @August's Ruby solution:
```
a=raw_input()
s=[x for x in range(input())if any(c in`x`for c in a)]
for _,g in __import__('itertools').groupby(s,lambda x:x+1in s):
l=map(str,g)
print len(l)<9and' '.join(l)or l[0]+' -->',
```
PS: Coincidentally, the first two lines ended up nearly identical to both other Python entries.
[Answer]
# R 224 w/o Comment
```
a=as.character
l=length
x=a(scan()) # Read digits
s=a(0:(scan()-1)) # Read max number
p=as.numeric(s[Reduce(`|`,lapply(x,function(x)grepl(x,s)))])# Find all numbers we want
j=1 # Print the arrow "-->"
for (i in 1:l(z<-c(rle(diff(p))$l,1))){if(z[i]<9)cat(p[j:(j+z[i]-1)],"")else
cat(p[j],"-->","")
j=j+z[i]}
```
[Answer]
## PHP, ~~273~~ ~~258~~ ~~255~~ ~~248~~ ~~256~~ ~~239~~ 234 bytes
What a mess.
### Submission:
```
function n($s,$b){$r=$q=$f="";for($g=-1;$g++<$b;){$i=0;foreach(explode(" ",$s)as$d){$i+=in_array($d,str_split($g));}if($i&&$b-$g){$q[]=$g;$f=$f?:$g;}elseif($f){$r.=($g-$f>9?$q[0]." --> ".($g-1):implode(" ",$q))." ";$q=$f="";}}echo$r;}
```
### Exploded view:
```
function n($s, $b) {
$r = $q = $f = "";
for ($g = -1; $g++ < $b;) {
$i = 0;
foreach(explode(" ", $s) as $d) {
$i += in_array($d, str_split($g));
}
if ($i && $b-$g) {
$q[] = $g;
$f = $f ?: $g;
} elseif ($f){
$r .= ($g-$f > 9 ? $q[0] . " --> " . ($g-1)
: implode(" ", $q) ) . " ";
$q = $f = "";
}
}
echo $r;
}
```
### Variable explanations:
`$b`: *string*, upper **b**ound (input)
`$s`: *string*, digit **s**tring (input)
`$d`: *int*, individual **d**igit in `$s`
`$g`: *int*, current **g**uess
`$i`: *int*, number of times a digit exists **i**n the current guess
`$f`: *int*, **f**irst correct guess in a chain
`$q`: *array*, correct guess **q**ueue
`$r`: *string*, final **r**esult (output)
This is **super** unoptimized, still tweaking it.
**Edits:**
**-18:** Combining variable inits, merging two `$i` inits.
**-7:** Removing `$a` declaration.
**+8:** Fixed two bugs: now allows `0` as output, now allows `$b-1` and `--> $b-1` as output.
**-17:** God, I love ternary operators.
**-5:** Let's treat `$i` as an `int` full-time, and simplify the resets.
] |
[Question]
[
Given a string representing a number and the base that number is in, shift each positional value upward, wrapping back to zero if the value cannot increase. You will never be provided invalid input, nor a base larger than 36.
For example, you may be provided `['5f6', '16']`, which represents the number 1526 in base 16. The expected output in that case would be `'607'` (1543 in base 16).
### Input
* program: separate lines from STDIN: `'5f6\n16'`
* function: a tuple or array: `f(['5f6', '16'])` or `f(['5f6', 16])`
* function: two arguments `f('5f6', '16')` or `f('5f6', 16)`
### Output
* program: to STDOUT: `607`
* function: returned as a string: `'607'`
### Test cases
```
['5f6', '16']
'607'
['abc', '36']
'bcd'
['1', '1'] or ['0', '1']
'1' or '0'
['9540', '10']
'0651' or '651'
['001', '2']
'110'
```
[Answer]
# [Paradoc](https://github.com/betaveros/paradoc) (v0.2.10), 10 bytes (CP-1252)
```
DaÅ+<:<oTr
```
[Try it online!](https://tio.run/##K0gsSkzJT/6vZOpmpqRgaPbfJfFwq7aNlU1@SNH//wA "Paradoc – Try It Online")
Takes the string and the base as an integer from the stack, results in a string on the stack.
Whoops, I don't know why I don't have a `0-9A-Z` constant yet. It would shave two bytes. (Assumes input is uppercase; for lowercase replace `Å` with `La`.)
Explanation:
```
Da .. Push the digit alphabet
Å .. Push the uppercase alphabet
+ .. Concatenate them
< .. Take the slice of the first (base) characters
: .. Duplicate
<o .. Left-rotate by one
Tr .. Translate through the last two strings
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 bytes
```
®nV Ä sV Ì
```
[Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=rm5WIMQgc1YgzA==&input=IjVmNiIgMTY=)
The 3-byters `nV` and `sV` are rather annoying...
### Explanation
```
® nV Ä sV Ì
UmZ{ZnV +1 sV gJ} Ungolfed
Implicit: U = input string, V = base
UmZ{ } Map each char in Z to
ZnV Z converted from base V to decimal,
+1 plus 1,
sV converted back to base V,
gJ and shortened to only the last char. (J = -1)
Implicit: output result of last expression
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~77~~ ~~74~~ 72 bytes
```
lambda s,m:''.join(chr(c+[48,55][c>9])for c in[-~int(x,m)%m for x in s])
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFYJ9dKXV0vKz8zTyM5o0gjWTvaxELH1DQ2OtnOMlYzLb9IIVkhMy9aty4zr0SjQidXUzVXASRaARRVKI7V/F9QBJRRSNNQN02zVNcxNNPkQoiYm6nrWCAJpFUBlRgDlfwHAA "Python 2 – Try It Online")
Takes a string and an int base. Works up to base 36.
[Answer]
# JavaScript, 57 bytes
```
(a,b)=>a.replace(/./g,v=>(-~parseInt(v,b)%b).toString(b))
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~11~~ 10 bytes
```
.rE<+jkUTG
```
[Try it here](https://pyth.herokuapp.com/?code=.rE%3C%2BjkUTG&test_suite=1&test_suite_input=36%0A%22abc%22%0A16%0A%225f6%22%0A2%0A%221101%22%0A1%0A%22000%22&debug=0&input_size=2)
Thanks to Mr. XCoder for saving 1 byte!
We use `.r` to cyclically rotate over the alphabet of the given base. We build that using `G` as the built in alphabet, and then a range of numbers, and slicing off the excess.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 12 bytes
3 bytes thanks to Jonathan Allan.
```
ØBiЀ⁸%⁹‘ịØB
```
[Try it online!](https://tio.run/##y0rNyan8///wDKfMwxMeNa151LhD9VHjzkcNMx7u7gaK/v//X8nUzUzpv6EZAA "Jelly – Try It Online")
## How it works
```
ØBiЀ⁸%⁹‘ịØB
ØB "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
iЀ⁸ index of each in first input
%⁹ modulo the second input
‘ increase by 1
ị index into
ØB "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
```
[Answer]
# C, ~~75~~ ~~74~~ 65 bytes
*Thanks to @tsh for saving 9 bytes!*
```
f(n,b)char*n;{for(;*n;++n)*n=*n-b-(b>10?86:47)?*n-57?*n+1:97:48;}
```
Modifies the input string directly.
[Try it online!](https://tio.run/##hY7LCoMwEEX3foW4yviAxFeMofVDShcaSOuiqRi7qOK3pynU0kLAzXCZezgzIrkIYYxEKu5AXNsxVHyR9xFxG6JIQagOoUq6BHVHgpuqrHMKjd0U1M6I1IzWecVX06vJv7W9QuAt3lvk61OWnrmnp1EMT6TjoJBlAFzaSErgw2PSSMM/wHYAuhkqZy/nTZC5BQzPOwD7voCdACEYE0w@UOpm0u3IT72aFw)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
ö¹в>¹%¹β¹B
```
[Try it online!](https://tio.run/##ASEA3v8wNWFiMWX//8O2wrnQsj7CuSXCuc6ywrlC//8xNgo1RjY "05AB1E – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~65~~ ~~64~~ 59 bytes
```
map.(%)
b%c|mod(fromEnum c-b)39==8='0'
_%'9'='a'
_%c=succ c
```
[Try it online!](https://tio.run/##Fcu7DoIwFADQna@4IZLCgEERhOGOfoGriSkXCkgLlVJf8dutup3ldNwMjZRO4MkprtdhEHlVQG811aGYJ3UYrQKKqygtEQtkCfPOASsZMv4XobFEQL/bj4Cg7XJcZliBgDQHP9ls012W74uSV1Q3ou36yyDVOOnrbBZ7uz@eL999SEjeGheT1l8 "Haskell – Try It Online") Usage: `map.(%) $ 16 "5f6"` yields `"607"`.
**Edit:** -1 byte thanks to nimi, -5 bytes thanks to Ørjan Johansen.
[Answer]
# [MY](https://bitbucket.org/zacharyjtaylor/my-language), 8 [bytes](https://bitbucket.org/zacharyjtaylor/my-language/src/ca5cdd70d46e932ed06f4a150b9a6c81de75be5d/codepage.txt?at=master&fileviewer=file-view-default)
```
αωP‘%pέ←
```
I definitely made the right choice adding the basify (`P`) and stringify (`p`) atoms!
[Try it online!](https://tio.run/##AR4A4f9tef//zrHPiVDigJglcM6t4oaQ////JzVGNif/MTY)
## How it works, along with a reason for the codepoint
* `α`, push the second command line argument (taken from APL, but it's the greek symbol instead of the APL one)
* `ω`, push the first command line argument (also taken from APL)
* `P`, pop `n`; push n basified (`0`-`Z` => `0`-`35`, `b` flipped is `p`)
* `‘`, pop `n`; push `n + 1` (vectorizes ["vecifies" in MY], taken from jelly)
* `%`, pop `a`; pop `b`; push `a%b` (vecifies, do I really need to give this to you?)
* `p`, pop `n`; push `n` stringified (`0`-`35` => `0`-`Z`, vecifies, same origin as `P`)
* `έ`, pop `n`; push `"".join(n)` (`ε` is the **e**mpty string, and just put an accent mark over it)
* `←`, pop `n`; output `n` with no newline. (Pushing it away from the stack to STDOUT)
**THIS** is what MY was meant for!
[Answer]
# [PHP](https://php.net/), 83 bytes
```
while(($c=$argv[1][$i++])>'')echo base_convert(intval($c,$b=$argv[2])+1,10,$b)[-1];
```
[Try it online!](https://tio.run/##K8go@G9jXwAkyzMyc1I1NFSSbVUSi9LLog1jo1UytbVjNe3U1TVTkzPyFZISi1Pjk/PzylKLSjQy80rKEnOAynVUkqA6jGI1tQ11DA2AIprRuoax1v///zdNM/tvaAYA "PHP – Try It Online")
[Answer]
# Mathematica, 62 bytes
```
(h=#2;""<>ToString/@(Mod[#~FromDigits~h+1,h]&/@Characters@#))&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvtfI8NW2chaScnGLiQ/uKQoMy9d30HDNz8lWrnOrSg/1yUzPbOkuC5D21AnI1ZN38E5I7EoMbkktajYQVlTU@1/AFBHiYJDWrSSaZqZko6hWez//wA "Mathics – Try It Online")
[Answer]
# PHP, 87 bytes
```
list(,$a,$b)=$argv;for(;$c=intval($a{$i++},$b);)echo$b>1?base_convert(++$c%$b,10,$b):1;
```
Run with `-r` like this:
```
php -r "list(,$a,$b)=$argv;for(;$c=intval($a{$i++},$b);)echo$b>1?base_convert(++$c%$b,10,$b):1;" xyz 36
```
Works with bases 1 to 36, inclusive.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 71 bytes
```
b=({0..9} {a..z})
for c in `fold -w1<<<$1`;{ echo -n ${b[-~$2#$c%$2]};}
```
[Try it online!](https://tio.run/##BcFLCoAgEADQfacYaIJaKH1WkZ0kgtK@GEoFCYldfXpPjvdGJNvU55zXAfzI@RuyaLEXKNgNDIs9JmCuEEJgMTQeZrVZYAbQy459WMaoEiz70AQiWietjXvMqRVV1Q8 "Bash – Try It Online")
[Answer]
# Python, ~~81~~ ~~78~~ ~~74~~ ~~87~~ 86 bytes
```
import string
lambda a,b:''.join(string.printable[-~int(i,b)%b]for i in a)if b>1else a
```
Alternatively:
```
lambda a,b:''.join(__import__('string').printable[-~int(i,b)%b]for i in a)if b>1else a
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~53~~ 59 bytes
```
->n,b{b<2?n:n.chars.map{|c|(c.to_i(b)+1).to_s(b)[-1]}.join}
```
[Try it online!](https://tio.run/##KypNqvz/v1jBVkHXLk8nqTrJxsg@zypPLzkjsahYLzexoLomuUYjWa8kPz5TI0lT21ATxCwGMqN1DWNr9bLyM/NqubgKSkuKFYr1khNzcjTUE5OS1XUUDI01UYVN08xAwmZowgZAABLX/P8fAA "Ruby – Try It Online")
Originally 6 bytes less, but Ruby doesn't like using a base of 1.
Could save 5 bytes by removing `.join` if the output did not need to be a string.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~23~~ 21 bytes
```
≔…⁺⪫EχIιωβNθFS§θ⁺¹⌕θι
```
[Try it online!](https://tio.run/##HYzLCoMwFET3fsVd3kAKzUI3rqRQUGgR@gXRqA2kieZh@/fp1cXAnDkw41v60UmTcxOCXiw@nFHYmxSwc5pQriiuHG4yRNSMcfhSBkpr1xSf6TNMHo99Y3UxOw94ilf02i4koKcSsYmtVdMPNw7nueBw11YdTK@M1TmLqijnKl928wc "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 2 bytes by using `CycleChop` instead of `Slice`. Explanation:
```
Eχ Loop over the digits
Iι Cast to string
⪫ ω Join together
⁺ β Append the lowercase letters
N First input as a number
… Take `n` characters from the start
≔ θ Assign to variable `q`
FS Loop over the characters in the second input
⌕θι Find the character index in `q`
⁺¹ Plus 1
§θ Cyclically index in `q`
Implicitly print
```
Note: Later versions of Charcoal reduce this to 20 bytes: `≔…⁺⪫EχIιωβNθFS§θ⊕⌕θι`
[Answer]
# [Perl 5](https://www.perl.org/) `-lF`, ~~61~~ 53 bytes
```
$l=(0..9,a..z,aa)[<>];say map{++$_;/$l/?0:s/10/a/r}@F
```
[Try it online!](https://tio.run/##K0gtyjH9/18lx1bDQE/PUidRT69KJzFRM9rGLta6OLFSITexoFpbWyXeWl8lR9/ewKpY39BAP1G/qNbB7f9/A0MjYxNTM3MLy8Sk5JTUtPSMzKzsnNy8/ILCouKS0rLyisoqLmOzf/kFJZn5ecX/dX1N9QwMDf7r5rgBAA "Perl 5 – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╕W─░ì]
```
[Run and debug it](https://staxlang.xyz/#p=b857c4b08d5d&i=5f6%0A16%0A%0Aabc%0A36%0A%0A1%0A1%0A%0A9540%0A10%0A%0A001%0A2&a=1&m=1)
### Procedure:
1. Push constant "0123456789abcdefghijklmnopqrstuvwxyz".
2. Get and eval base, now two spots down the stack
3. Truncate digit string to specified count.
4. "Ring" translate using remaining characters. This maps each character to the next, wrapping around to "0" at the end.
] |
[Question]
[
Consider a 10 by 10 grid of points at integer coordinates. Given a coordinate (x, y) of one of the points in the grid and a radius r, some of the points in the grid will fall inside a circle of radius r that is centered at (x, y). You will count the number of such points.
# Input
An integer coordinate (x, y) in a 10 by 10 grid.
# Output
All the different counts for the number of points in the grid that are inside a circle centered at (x, y), for every possible radius r. Your output should not contain duplicate values but can be in any order.
You may not assume that r is an integer so there are an infinite number of possible radii but your output will nonetheless be of finite size. For example, the same count arises for all 0<r<1.
The numbers 1 and 100 will always be in your output no matter what (x, y) are.
If (x, y) is a corner, the output should be:
```
[1, 3, 4, 6, 8, 9, 11, 13, 15, 17, 19, 20, 22, 26, 28, 30, 31, 33, 35, 37, 39, 41, 43, 45, 48, 50, 52, 54, 56, 58, 62, 64, 65, 67, 69, 71, 73, 75, 79, 81, 83, 85, 86, 88, 90, 92, 94, 95, 97, 99, 100]
```
If (x, y) is on a side and not too close to a corner then the output should include 1, 4, 6, 9, 13, 15, 18, 22, 26.
If (x, y) is somewhere in the middle then your output should include 1, 5, 9, 13, 21, 25, 29. For example if it is (4, 3) the output should be [1, 5, 9, 13, 21, 25, 29, 37, 45, 48, 54, 58, 64, 72, 76, 80, 82, 86, 87, 89, 91, 94, 96, 97, 99, 100].
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 12 bytes
```
‚ÇÄ Ä2·∫㷵󜩃∞?»ßS‚Ć@
```
10x10 grid located in coordinates 0-9. Takes input as a complex number.
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLigoDKgDLhuovhtZfPqcSwP8inU+KAoEAiLCIiLCI0xLEzIiwiMy40LjAiXQ==)
**Explanation**
```
‚ÇÄ Ä2·∫㷵󜩃∞?»ßS‚Ć@¬≠‚Ű‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Ű‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å£‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Ű‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å¢‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚ŧ‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Ű‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Ű‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Å£‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Å¢‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚ŧ‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå¬≠
2ẋ # ‎⁡2nd cartesian power of
‚ÇÄ Ä # ‚Äé‚Å¢‚Äé‚Å¢Range 0-9
ᵗϩ # ‎⁣Map through all coordinates and dump to stack
İ?ȧ # ‎⁤Absolute difference between input and coordinate
S† # ‎⁢⁡‎⁢⁡Sort list and return length of consecutive groups
@ # ‎⁢⁢Cumulatively add all lengths
üíé
```
#### Original answer, [13 bytes](https://vyxal.github.io/latest.html#WyIiLCIiLCLigoDKgDLhuovGmz8twrLiiJF9U+KAoEAiLCIiLCJbNCwzXSIsIjMuNC4wIl0=)
```
‚ÇÄ Ä2·∫ã∆õ?-¬≤‚àë}S‚Ć@¬≠‚Ű‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Ű‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å™‚Äè‚ņ‚Å™‚Å™‚ņ‚Å™‚Å™‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å£‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Ű‚Å™‚Äè‚ņ‚Å™‚Å™‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Å£‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚ŧ‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Ű‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Å¢‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Ű‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚Ű‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Å¢‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚Å¢‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå¬≠
2ẋ # ‎⁡2nd cartesian power of
‚ÇÄ Ä # ‚Äé‚Å¢Range 0-9
ƛ } # ‎⁣Map through all coordinates
?-²∑ # Squared euclidean distance‎⁤ between input and coordinate
S† # ‎⁢⁡Sort list and return length of consecutive groups
@ # ‎⁢⁢Cumulatively add all lengths
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 101 bytes
```
Union@Table[p=#;Length@Select[Join@@Array[{#,#2}&,{10,10},0],p~EuclideanDistance~#<r&],{r,1,20,.01}]&
```
[Try it online!](https://tio.run/##BcGxCsIwEADQXxECmQ65dNVCBF2Kg6BOpcMZjzTQXkuMg4T01@N7M6WRZ0rBUfVtfUpYxD7oNXG/tupwZfFptHee2KW@W4JYe4qRfn1WoJqiIRsEgwVwgHW7fN0U3kxyDp9E4nhTx6gHyBEMNAh7NGXQ9RaDJOvtLiNgqfUP "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
⁵p`Æịạ⁸ĠẈÄ
```
[Try it online!](https://tio.run/##y0rNyan8//9R49aChMNtD3d3P9y18FHjjiMLHu7qONzy3/pRwxwFXTuFRw1zrQ@3P9y5T4XrcPujpjWR//8bahtm6Zhqm4AIQ4MsAA "Jelly – Try It Online")
A monadic link taking a co-ordinate on a grid from 1..10 on both axes and expressed as a complex number. A list of integers is returned.
## Explanation
```
⁵p` | Cartesian product of 1..10 with itself
Æị | Convert to complex
ạ⁸ | Absolute difference with link argument
Ġ | Indices to group identical values (ordered by the values)
Ẉ | Group lengths
Ä | Cumulative sum
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 57 bytes
```
i+=#2&@@@Tally@Sort@{Array[# #+#2#2&,10+{i=0,0},-#,##&]}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P1PbVtlIzcHBISQxJ6fSITi/qMSh2rGoKLEyWllBWVvZCCirY2igXZ1pa6BjUKujq6yjrKwWW6v2P6AoM68kWlnXLs1BOVatLjg5Ma@umqsarIqr2lzHEkSZ6BjXctX@BwA "Wolfram Language (Mathematica) – Try It Online")
```
Array[# #+#2#2&,10+{ 0,0},-#, ] distance to each point
Sort@{ ##& } ascending by distance
#2&@@@Tally@ counts of each
i+= &@@@ i= cumulative
```
[Answer]
# [Desmos](https://desmos.com/calculator), 75 bytes
```
f(p)=[L[L<=i].countfori=L].unique
I=[0...9]
L=[distance(p,(a,b))fora=I,b=I]
```
Input as a point `(x,y)`, ranging between coordinates 0 to 9.
[Try It On Desmos!](https://www.desmos.com/calculator/mjpousauqb)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/p25cmxeesk)
[Answer]
# [R](https://www.r-project.org), 47 bytes
```
\(x)cumsum(table(abs(x-outer(0:9,0:9*1i,`+`))))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY39WM0KjSTS3OLS3M1ShKTclI1EpOKNSp080tLUos0DKwsdYBYyzBTJ0E7QRMIYNpK8_ISc1M10jQMtA0yNTW54HxTNL6JtnEmTNuCBRAaAA)
A function taking a complex argument and returning a list of integers. Uses a zero-indexed grid from 0..9 on both axes.
[Answer]
# TI-BASIC, 73 bytes
```
abs(Ans-seq(10fPart(.1I)ùíæ+int(.1I),I,0,99‚ÜíL
SortA( üL
ŒîList(augment( üL,{0
cumSum(1 or Ans)not(not(Ans‚ÜíL
SortD( üL
seq( üL(I),I,1,sum(1 and üL
```
Takes input in `Ans` as a complex number with the x and y from 0 to 9.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), ~~32~~27 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⍸⌽≠{⍵[⍒⍵]},+.×⍨⍤-∘⍵¨⍳2⍴10}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37Uu@NRz95HnQuqH/VujX7UOwlIxdbqaOsdnv6od8Wj3iW6jzpmAMUOAdmbjR71bjE0qAUA&f=S1MwVDDkSgOSJkDSWMEcSJoqWAIA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
-5 bytes thanks to att.
A dfn which takes a vector on the right and outputs the list of possible counts.
## Old explanation
```
{+\{≢⍵}⌸{⍵[⍋⍵]},∘.(+.×⍨⍵-,)⍨⍳10}­⁡​‎‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁣⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌­
⍳10 # ‎⁡range 1-10
∘.( )⍨ # ‎⁢For every pair of elements
, # ‎⁣pair into vector
⍵- # ‎⁤subtract from input vector
+.×⍨ # ‎⁢⁡dot product with itself
, # ‎⁢⁢matrix to list
{⍵[⍋⍵]} # ‎⁢⁣sort
{≢⍵}⌸ # ‎⁢⁤frequencies of groups
+\ # ‎⁣⁡cumulative sums
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Scala](https://tio.run/##pZBRS8MwFIXf/RWXgZBg17XCHlZXYQyFwQbi8GkMyZp0i6ZJSTNZKf3t9bYTEZ0wMSQk@W7O4Z4UCVOsMZsXkThYMKmhurgA4CKFDG@E2W0RwcRaVq6Wzkq9XdMInrR0EONTwDEYwN2BZbkSsC/YVkQdfWMKErPXrrg3dmqsFhYVHXkwEvFMT6VNlMDyRKlHxqUkgQcB/SlfSi7OEg9PiBeSc3WGfNjJO32OOZ3S5Fv/vjNzWTi/MNYJ7mevxw8hvVXPg4@57lF62qMN8T@HY5I/eNRtnM/P@DU6RITMtPNw0fh2KdwKT2sKcUMOXomoaj3yODW2kuN@AM7AaFSXUihO5CAMPHkZBvQm91Oj@FykjqAJCb0wCCitCPNaX3aV@10fVcIKgXCDMGNu5@/K3DjC@gdv0y/pOP4Cnf8cIsftGkt1XTd18w4), ~~156~~ 146 bytes
Use `Double scala.math.hypot(Double length, Double base)` to calculate the square root of the sum of squares of the 2 numbers.
Saved 10 bytes thanks to @ceilingcat
---
Golfed version. [Try it online!](https://tio.run/##pZBRS8MwFIXf/RWXgZBg17XCHlZXYQyFwQbi8GkMyZp0i6ZJSTNZKf3t9bYTEZ0wMSQk@W7O4Z4UCVOsMZsXkThYMKmhurgA4CKFDG@E2W0RwcRaVq6Wzkq9XdMInrR0EONTwDEYwN2BZbkSsC/YVkQdfWMKErPXrrg3dmqsFhYVHXkwEvFMT6VNlMDyRKlHxqUkgQcB/SlfSi7OEg9PiBeSc3WGfNjJO32OOZ3S5Fv/vjNzWTi/MNYJ7mevxw8hvVXPg4@57lF62qMN8T@HY5I/eNRtnM/P@DU6RITMtPNw0fh2KdwKT2sKcUMOXomoaj3yODW2kuN@AM7AaFSXUihO5CAMPHkZBvQm91Oj@FykjqAJCb0wCCitCPNaX3aV@10fVcIKgXCDMGNu5@/K3DjC@gdv0y/pOP4Cnf8cIsftGkt1XTd18w4)
```
(x,y)=>{val p=for{i<-0 to 99}yield(i/10,i%10);p.foldLeft(Set(1,100)){(a,t)=>a+p.count{case(a,b)=>math.hypot(a-x,b-y)<=math.hypot(t._1-x,t._2-y)}}}
```
Ungolfed version. [Try it online!](https://tio.run/##pVNda9swFH3PrzjkSSap6w76EppBKRsUWhgLewp5UCU5VSZLniSv8UJ@e3b9kTpsGesYGGSdq3PO/ZCC4IYfDu5po0TEI9cWuxHwnRusvZYL/UNhjqtsRKBUOQo6wbhfhxluvef1chG9tutVMsMXqyOdbejA5SU@bHlRGoUq8LWatWgjK1xlY/jo/J3zVnlitMgnpwm@t3faC6MofGvMZy61ZtkUWfI7faGlehP5@gz5UUtp3kC/buktv6Q6o7Hsl/zT6B50iGlwPiqZFl@7hrDxcjxF/63GSXJeoyni/xS6Sv5BY38c5V9K385wb@MUdbvSfBcqLulv9TrjpqNlyycod76HAY2bC2QgeT1coz62@WNsj1orI8H0FJu@6cPQyKLzSnNn5IPKIzsmxJIEOzAuxLQ7k2D@vrdrBFi5pUCdHCVOQgXfNtVWjXzB43MavvnI2r/SvRARFyDyuwQTDGhNaN2gyYlUm@aQZbfdQfCgwASJiPokL5yzE2ftxGCHm/mQcq@071cqn1itbdfO0etDtKHyClfgVtJTzsBpx80LrwO0FaaSSoIHlPQa47NCKJXQuRY8amc7m34GExKZNBLtPdofDj8B)
```
object Main {
val gridSize = 10
def main(args: Array[String]): Unit = {
// Example usage:
val countsForCorner = countPointsInCircleForAllRadii(0, 0)
val countsForSide = countPointsInCircleForAllRadii(0, 5)
val countsForMiddle = countPointsInCircleForAllRadii(5, 5)
println(countsForCorner.toList.sorted.mkString("[", ", ", "]"))
println(countsForSide.toList.sorted.mkString("[", ", ", "]"))
println(countsForMiddle.toList.sorted.mkString("[", ", ", "]"))
}
def countPointsInCircleForAllRadii(x: Int, y: Int): Set[Int] = {
val points = for {
i <- 0 until gridSize
j <- 0 until gridSize
} yield (i, j)
val counts = points.foldLeft(Set[Int]()) { (acc, point) =>
val (px, py) = point
val maxRadius = math.sqrt(math.pow(px - x, 2) + math.pow(py - y, 2))
val count = points.count { case (cx, cy) =>
math.sqrt(math.pow(cx - x, 2) + math.pow(cy - y, 2)) <= maxRadius
}
acc + count
}
// Ensure 1 and 100 are always included as per the specifications
counts + 1 + 100
}
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes
```
NθNηFχFχ⊞υ⁺X⁻θι²X⁻ηκ²Wυ«⟦ILυ⟧≔⁻υ⟦⌈υ⟧υ
```
[Try it online!](https://tio.run/##TY3LCsIwEEXX7VfMMoEIPsCNK3ElWMm@dBFLbYJpYpOMFcRvj4OIdDFw7@VwptUqtF7ZnI/ujumMw6ULbOS7ct419asPwFZLDv8gMWqGAqTFyKSfCKyMozwKMFzAmm4@awG378xJN2ljO2DI4VUWMhiXWH1QMbFT5/pEXs4bwop9jKZ3PwM9qyv1NAMOBDQkQ2LeOW9gmxcP@wE "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Outputs the counts in descending order. Explanation:
```
NθNη
```
Input the centre point.
```
FχFχ
```
Loop over all of the points in the grid.
```
⊞υ⁺X⁻θι²X⁻ηκ²
```
Calculate the squared distance from the centre to that point.
```
Wυ«
```
Repeat until no more squared distances remain.
```
⟦ILυ⟧
```
Output the current count of squared distances.
```
≔⁻υ⟦⌈υ⟧υ
```
Remove the highest squared distance(s).
Output in ascending order costs 2 bytes, but 2 bytes can be saved by using the newer version of Charcoal on ATO and taking input as a Gaussian integer:
```
Nθ≔ΣEχEχ↔⁻θ⁺ι×λI1jηW⁻ηυ⊞υ⌊ιIEυLΦ笛λι
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY_BCsIwDIbvPkXZKcUKiiDCTiIogpOBR_HQjWojXefWRh_Gi4eJvodP4dtYdeYSkvz5_uTyyLWs81Ka6_VGftcbv54T53BvYZK50pBXkKAlBwt7JL-iIlM1cMHWVEAijzDoC_bPqQk6FGwqnYdvYQSLDhFvQ7CKx52zRqNYS60EI85ZSk4DBRJaLAIZeRCmNVoPX9jHIYyXyu69hhkaH64Iu6vSw7xW8lMGL2yN4sZluWsfum-i3slE22bYHR1-rTc "Charcoal – Attempt This Online") Link is to verbose version of code. 0-indexed. Explanation:
```
Nθ
```
Input the centre point.
```
≔ΣEχEχ↔⁻θ⁺ι×λI1jη
```
Calculate the distances to all of the points in the grid.
```
W⁻ηυ⊞υ⌊ι
```
Sort and deduplicate the distances.
```
IEυLΦ笛λι
```
For each unique distance, output the count of points not greater than that distance.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 89 bytes
```
x=>y=>[...w=Array(i=100)].map(t=>w[j=(--i%10)**2+(i/10|0)**2]=-~w[j])&&w.flatMap(t=>i+=t)
```
[Try it online!](https://tio.run/##JYtBCsIwEABfY9ltyZp434AP6AtKDqE2khKbkgZjQfx6LApzGBhmtk@7jcmvWSzxNlXH9cV6Zz0QUeFrSnYHz0pKNPSwK2TWZZgZhPAnJbFtLx34s5LvnxsWnyMbbJpCLtjc/xffccY6xmWLYaIQ7@BA4gHWLw "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 104 bytes
```
x=>y=>[...[...Array(i=100)].map(e=t=>(--i%10)**2+(i/10|0)**2+1e7).sort(),0].flatMap((t,i)=>e-(e=t)?i:[])
```
[Try it online!](https://tio.run/##JYtBCsIwEABfI@zWZk28CMJGfIAvKDmEmkgkNiUJYsG/xxZhBuYyT/u2ZcxhrmJKd9c8tw/rhfVARJvXnO0CgZWUaOhlZ3BcWYMQYackdt1xD@Gg5Pffyp2QSsoVsJeGfLT1tj5Q@4CsndhuvITzYLCNaSopOorpAR4krmD7AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-la`, ~~69~~ 66 bytes
```
map/.$/&++$a[("@F"-$`)**2+($F[1]-$&)**2],0..99;$_&&say$t+=$_ for@a
```
[Try it online!](https://tio.run/##K0gtyjH9/z83sUBfT0VfTVtbJTFaQ8nBTUlXJUFTS8tIW0PFLdowVldFDcSL1THQ07O0tFaJV1MrTqxUKdG2VYlXSMsvckj8/99AweRffkFJZn5e8X9dX1M9A0OD/7o5iQA "Perl 5 – Try It Online")
Grid is labeled 0-9 on both axes. Input of X and Y is on one line, space separated. Output is line separated.
[Answer]
# [Rust](https://www.rust-lang.org), ~~322~~ ~~259~~ ~~254~~ 125 bytes
A port of [my Scala answer](https://codegolf.stackexchange.com/a/268866/110802) in Rust.
Saved 68 bytes thanks to @ceilingcat
Saved 129 bytes thanks to @att
---
Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=nZJBS8MwGIbB435FHSjJ7Go9DFy7zqtXEbyGtE0xkCYlSWFj6S_xsoP-qHnwt9g02xC2YbdeEvp979P3gX58ylrp9ealVsRTOo-iTDBGMk0FV1H0jNX7K9Fxwb0SUw7gihHtZaLmGlWCcq0Q5SijMmMEFUIizBiSOKc0-ap1MX7cNGbhL814viXN0LxDVIkxIAyCZDqFQYkrYKgBBvupwSN8l45SCOj9Qzhe-PSmPZYQxhXYbmJjrwVlmkhgblOTzhIMg64VgPbSGQDYxK7E99WP1z776qqrmgnJiUz6yIDQD2E82EHKWntKSE1ydMCL3kjWSiYHg6D9gEDUdv5T0UFPwQI7QDVXGqeM7LYr2aIYvwbDVfTUDP1T6XZ9cMRb0Zz0tZ78a21pR5zt6_OMu8SFvjZ7wrakec56-k56-DreEWM3OM95m7nQ2qXb9cb95uu1O38B)
```
|x,y|->HashSet<_>{let p=||(0..=99).map(|i|(|a,b|a*a+b*b)(i/10-x,i%10-y));p().map(|a|p().filter(|&b|b<=a).count()).collect()};
```
Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=nVXNctMwEL5x8AzvsPSQkSFxHaAM46ThQgd6pTMcuHiELFN1ZNlYMoknyZNw6QFeiqdhJSuetEmgqS629ufb_Vba1c9fdaPN7e3vxuSjt3-ePG00B22yJGGllJwZUSqdJB-pvr7iZhIEDPcGPny6fJ9eXX65SEC8egnnMI5RlysoqFAkhGUAuE5P4WJBi0pyaDT9xhMnldwAKxtldJqXdcrKWvEaIZwsrUphNUKlTNRMcmdDpUxrmglB4iHE4aTHKRoDuqwNz9IdyAQ-czZNZxvobV2EQcpUGF6TMPJMicc9hBdZRdogffpV8o11VSOUVM_IyTJ5tz4ZHnRH-330tcj4EeTP_kveAu6nbjXHEXcej6VtnQ-QLkSWyQfTPnsI7Q5yP_FOdxx17_NY8p072q9dWzyI58I10xBa9w1hNAPfd1Pcz3xT2RJ0QEiSxFHU92Lo9HZFuaQmLWhFVmJ1zyiy4qL8wWF1gzoxhJsw3HL1lUmSaVfKGdk-RFv8jiZG99klieLz3go5dfmBUDDwmS57fAtCqsUQqjZEiOfOYHJHXdCFq0jjGBK0hhEswqgq5wTL8gL9W5S0G0kIVEP-5nUY6e91f6R3rh0CdZlE_vxzIe3PajAgDJNhbbjaStIuDMx2ArN_Bobp-VbyPdraXjdMgjh7PEpfKbu6WuLV1BwR3M7nvw76Gap0U3MYA1UZDtoYKO6onNMW0RSTTcYzi1zhGDXXOL4rzkQuGHXDO9gNM_Yh7knjeHOGnSJYd6-Cfxw2j8Rf)
```
use std::collections::HashSet;
const GRID_SIZE: i32 = 10;
fn main() {
// Example usage:
let counts_for_corner = count_points_in_circle_for_all_radii(0, 0);
let mut sorted_counts_for_corner: Vec<_> = counts_for_corner.into_iter().collect();
sorted_counts_for_corner.sort_unstable();
println!("{:?}", sorted_counts_for_corner);
let counts_for_side = count_points_in_circle_for_all_radii(0, 5);
let mut sorted_counts_for_side: Vec<_> = counts_for_side.into_iter().collect();
sorted_counts_for_side.sort_unstable();
println!("{:?}", sorted_counts_for_side);
let counts_for_middle = count_points_in_circle_for_all_radii(5, 5);
let mut sorted_counts_for_middle: Vec<_> = counts_for_middle.into_iter().collect();
sorted_counts_for_middle.sort_unstable();
println!("{:?}", sorted_counts_for_middle);
}
fn count_points_in_circle_for_all_radii(x: i32, y: i32) -> HashSet<i32> {
let points = (0..GRID_SIZE)
.flat_map(|i| (0..GRID_SIZE).map(move |j| (i, j)))
.collect::<Vec<_>>();
let mut counts = HashSet::new();
for point in &points {
let (px, py) = *point;
let max_radius = (((px - x).pow(2) + (py - y).pow(2)) as f64).sqrt();
let count = points.iter().filter(|&&(cx, cy)| {
(((cx - x).pow(2) + (cy - y).pow(2)) as f64).sqrt() <= max_radius
}).count() as i32;
counts.insert(count);
}
// Ensure 1 and 100 are always included as per the specifications
counts.insert(1);
counts.insert(100);
counts
}
```
] |
[Question]
[
**This question already has answers here**:
[Is this number a prime?](/questions/57617/is-this-number-a-prime)
(367 answers)
Closed 6 years ago.
We define a *prime character* as a character that has a [prime](https://en.wikipedia.org/wiki/Prime_number) [ASCII value](https://en.wikipedia.org/wiki/ASCII). We define a *prime string* as a String that only contains *prime* characters.
Given a String that only contains printable ASCII, determine whether that String is prime.
## Input / Output
You can take input either as a String or as a list of individual characters. You have to output two different and ***consistent*** values depending on whether the String is prime, following the standard rules for a [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'"). You are guaranteed that the input will be non-empty.
## Test Cases
**Truthy cases (Prime Strings):**
```
"aeg"
"aIS5"
"aaaaaaaaaaaaaa"
"/S/S"
"=;+"
```
**Falsy cases (not Prime Strings):**
```
"maTHS"
"Physics"
"\\\\"
"PPCG"
"Code Golf"
"Prime"
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! Standard rules for this tag apply.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
ÇpW
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cHtB@P//AUX56UWJubmZeekKAaVVVTmpxQpqCs75KakK7vk5aQA "05AB1E – Try It Online")
---
```
Ç # To ASCII array.
p # Is prime?
W # Min value from.
```
---
`ÇpP` also works.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
OÆPẠ
```
[Try it online!](https://tio.run/##y0rNyan8/9//cFvAw10L/h9uf9S05v//aKXE1HQlHaVEz2BTEIUCgAL6wfrBQMrWWhtI5iaGeIB4ARmVxZnJxUBWDBCABAKc3YGUc35KqoJ7fk4aSKgoMzdVKRYA "Jelly – Try It Online")
### Explanation
Remember that a string is an array of characters, so operations like `O` will apply to each individual character.
```
OÆPẠ
O Ord; cast each character to a number
ÆP Is it ÆPrime? gives 1 for truthy and 0 for falsey
Ạ Ạll; returns 1 if the array contains no falsey values
```
[Answer]
# [Python 3](https://docs.python.org/3/), 56 bytes
```
lambda s:all(x%i for x in map(ord,s)for i in range(2,x))
```
[Try it online!](https://tio.run/##Vc6xDoIwEAbg3ae4NDGU2EjU6IBhYkA3EtzU4ZQWmrSUlA4QwrNjO3rD/@e@5a6fXGu60yqy16pQf2qEIUWl6LiVIIyFEWQHGntqbM2GOJAMZLFrOD2yMY7XgC7gkyBvCCN4r86h/sZDUiWVr@y686nxcQtb2U6D/A6EWfLyE6TMC1@5qTkURolAVmpO3ukGoLeyczSa08NlgXmJ9v68Rkct7y11MQPh03/1Aw "Python 3 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
ZpA
```
Outputs `1` for prime string, `0` otherwise.
[Try it online!](https://tio.run/##y00syfn/P6rA8f9/dVtrbXUA "MATL – Try It Online")
### Explanation
```
% Implicit input
Zp % Isprime. Applies element-wise to the code point of each entry
A % All. Gives 1 iff all results are non-zero.
% Implicit display
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes
```
ạṗᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GuhQ93Tn@4dcL//0qJKEAJAA "Brachylog – Try It Online")
[Answer]
## Haskell, 32 bytes
```
all(`elem`"%)+/5;=CGIOSYaegkmq")
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P802MSdHIyE1JzU3QUlVU1vf1NrW2d3TPzgyMTU9O7dQSfN/bmJmnoKtQko@l4KCQkFRZl6JgopCmoKSfrB@sNJ/AA "Haskell – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 8 bytes
```
q:i:mp:&
```
[Try it online!](https://tio.run/##S85KzP3/v9Aq0yq3wErt//9Ez2BTAA "CJam – Try It Online")
### Explanation
```
q e# Read input
:i e# Convert to code points
:mp e# Check if each is prime
:& e# Reduce by AND
```
[Answer]
## Perl, 46 bytes
**45 bytes code + 1 for `-p`.**
```
$_=y///c==grep!/^(11+?)\1+$/,map"1"x ord,/./g
```
[Try it online! (`-l` added to run all tests at once)](https://tio.run/##VcGxDsIgEADQ/b6iNh00VC8MnQxx6FDdSHBsNJeWIgkIAQf786Kr70WdXFdKcxcrIk5CmKTjBm9bztlpN3LWYOsp1rx@VyHNLR7QlELaAF1UB/QHUKECcWTg6XpWIB9rtlOG8Qek7Afow6yrIbgFZLJef0J82fDMZR/dFw "Perl 5 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 42 bytes
```
all(pracma::isprime(utf8ToInt(scan(,''))))
```
Reads from `stdin`, requires the `pracma` (practical math) package to be installed. Checks if all the UTF-8 encoding of the characters are prime. Unfortunately, this won't work on TIO...
[Try it online!](https://tio.run/##K/r/PzEnR6OgKDE5N9HKKrO4oCgzN1WjtCTNIiTfM69Eozg5MU9DR11dEwj@Gxv8BwA "R – Try It Online")
[Answer]
# Mathematica, 30 bytes
```
And@@PrimeQ@ToCharacterCode@#&
```
Quite self-explanatory.
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 28 bytes
```
[_l;||q=q*µasc(_sA,a,1)]?q=0
```
This prints -1 for non-prime strings, and 0 for prime ones. That is opposite to QBasic's usual approach to true/false, but this is the shortest way t comply with the 'consistent values' criterium. Output would otherwise be 0 or 1/-1.
## Explanation
```
[ | FOR a = 1 to
_l | the length of
; A$ (read from the cmd line)
q=q* Multiply q (which starts as 1) by
µ -1 if the following is prime, 0 otherwise:
asc( ) take the ASCII value of
_sA,a,1 a substring of A$, starting at pos a, for 1 char
] NEXT
?q=0 If we've tested all chas in the string, print -1 if q=0
and we've found a non-prime, or a 0 for prime strings
```
[Answer]
# [C](https://gcc.gnu.org/), 113 bytes
```
p(int c){for(int i=1;++i<c;)if(!(c%i))return 1;return 0;}c(char*s){char*a="p";while(*s++)if(p(*s))++a;printf(a);}
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 21 bytes
```
⎕CY'dfns'
∧/1pco⎕UCS⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdOSM1Ofv/o76pzpHqKWl5xepcjzqW6xsWJOcDxUKdg4EkSNl/BTAAq@ZST0xNV@dCFfEMNkUXQgFokvrB@sFoQrbW2mgiuYkhHuiqAjIqizOTi9FEY4AAXWGAszuakHN@SqqCe35OGrrSoszcVHUA "APL (Dyalog Unicode) – Try It Online")
### Explanation
```
⎕CY'dfns' This allows us to use pco
⎕UCS⎕ Convert the characters in the input to its respective code points
1pco pco with 1 as the left argument gives 1 iff the right argument is prime
This is applied across the array of code points
∧/ Reduce by AND; return 1 if all elements are truthy, otherwise give false
```
[Answer]
# Mathematica, 36 bytes
```
FreeQ[PrimeQ@ToCharacterCode@#,1<0]&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvvfrSg1NTA6oCgzNzXQISTfOSOxKDG5JLXIOT8l1UFZx9DGIFbtP1A6r0TBIU3BQSkxNV2JC5nvGWyKKoACUKT0g/WDUQRsrbVR@LmJIR6oKgIyKouBLkURiwECVEUBzu4oAiDHK7jn56ShKgN5Uuk/AA "Mathics – Try It Online")
*-2 bytes from @JungHwanMin*
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 60 bytes
```
s=>s.All(i=>Enumerable.Range(2,(int)i-2).All(j=>((int)i)%j))
```
] |
[Question]
[
# Bi-directional translator
The challenge is to create a translator that can translate a `[a-zA-Z ]` string into another string according to the mappings below. The translator should also be able to translate translated text back into its normal form (hence *bi-directional*). Case doesn't have to be maintained and can be either lower/uppercase (or both lower and upper-cased) in the output, however your program should be able to handle either lower/uppercase strings.
Here is the specification of the mappings for this challenge:
```
-------------------
|Letter | Mapping |
-------------------
| S | 9 |
| F | 1 |
| H | 5 |
| X | = |
| Z | {N} |
| M | --* |
| N | :) |
| G | ] |
| T | [ |
-------------------
```
Here are some example in/outputs:
(*The " or ... or ..." obviously shouldn't be in your actual output, its just to demonstrate the possible outputs*)
```
> ABS
< AB9 or ab9 or Ab9 or aB9
> foo
< 1oo or 1OO or ...
> FIZZ BUZZ
> 1i{N}{N} bu{N}{N} or 1I{N}{N} BU{N}{N} or ...
> {n}[:)
< ztn or ZTN or ...
> bar
< bar or BAR or ...
```
The inputs will always be in `[a-zA-Z ]` or a "translated" string containing the mapped symbol, other symbols or characters outside wouldn't be inputted.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~70~~ ~~68~~ 57 bytes
```
.[}*]|\)
T`l`L
T`-{=519[]:NGTSF\HXZM`Ro
{
{N}
-
--*
:
:)
```
[Try it online!](https://tio.run/##K0otycxL/P8/JCEnwYdLL7pWK7YmRpOLKyRBt9rW1NAyOtbKzz0k2C3GIyLKNyEon6uaq9qvlkuXS1dXi8uKy0rz/39Hp2CutPx8LjfPqCgFp9CoKK7qvNpoK00FrqTEIgA "Retina 0.8.2 – Try It Online") Link includes test cases. Uppercases the result. Explanation:
```
.[}*]|\)
```
Remove the suffixes from `{N}`, `--*` and `:)` leaving their first character.
```
T`l`L
```
Uppercase everything.
```
T`-{=519[]:NGTSF\HXZM`Ro
```
Translate the first characters. The string is mapped to its reverse, so that `-` maps to `M` etc. and vice versa. The `H` is a special character and needs to be quoted. The `-` is normally a special character but placing it at the beginning avoids this.
```
{
{N}
-
--*
:
:)
```
Expand the `{`, `-` and `:` to the full strings again.
[Answer]
# 05AB1E, 65 63 bytes
```
u"{N}"¬.:"--*"¬.:":)"¬.:"SFHXZMNGT[]:-{=519"‡"{-:N-)}*"3ιD€нs‡
```
Uses the same approach as [Neil's answer](https://codegolf.stackexchange.com/a/214512/70745). Probably not going to be too competitive among the golf answers, but there's definitely improvements to be made here (I'm still a novice with 05AB1E, especially with string manipulation).
Explanation:
```
u uppercase the input
"{N}" push '{N}'
¬ extract and push head ('{')
.: replace all {N} => {
"--*" push '--*'
¬ extract and push head ('-')
.: replace all --* => -
":)" push ':)'
¬ extract and push head (':')
.: replace all :) => :
"SFH...519" push lookup string
 bifurcate (push a, reversed(a))
‡ transliterate input with lookup
set up stack for reverse process
to do { -> {N} ... etc
"{-:N-)}*" push literal string
3ι uninterleave by 3
D duplicate
€ apply single function map
н extract first element
s swap
‡ transliterate
```
The bi-directional bit is achieved by transliterating with a bifurcated lookup string; each character that should be swapped is in the opposite position with the one it should be swapped with in the lookup string. The main problem (and potential savings) is that I repeat a lot of logic for the "{N}" -> "{" ... part at the beginning as in the "{" -> "N" ... part at the end. Originally, I thought transliterate could go both ways, so I was going to set up the stack carefully at the beginning, but I don't think transliterate likes it when there's a multi-character string in the list (it probably goes by character, rather than doing a replace all?).
[Answer]
# JavaScript (ES6), ~~118 113~~ 109 bytes
```
s=>s.toUpperCase(A=[':)',...'NF1G]H5S9T[X=Z','{N}','M','--*']).replace(/[{-]..|:?./g,c=>A[A.indexOf(c)^1]||c)
```
[Try it online!](https://tio.run/##bcm9CsIwGIXh3asQlyTSftLBwUIqVfBnUAcVJCFCjEmplKQ0RYTWa6@dpcM5w/O@5Ft6VeVlHVr31J2hnaeJh9pdy1JXa@k1TilHMUEBAKDjJtqK3fy8uPAbZShAzfHb/6FfGE6RIFDpspBK4xlvQgHQxkuYZYGiScpTyO1Tf04GK3KPRNsq0ilnvSs0FC7DBk/S1XlCyOhPjXMDutkzNl5dGRtojf3ymAyEh6x67X4 "JavaScript (Node.js) – Try It Online")
### How?
Because the input is guaranteed to contain exclusively `[a-zA-Z]` and/or the special patterns, we can use the following minimal regular expression to match them all:
```
/[{-]..|:?./g
[{-].. // either "{" or "-" followed by 2 other characters
// -> to match "{N}" or "--*"
:?. // or any character, preceded by an optional ":"
// -> to match ":)" or any single character
```
Working on the uppercase version of the input, we look for the position of each matched pattern in the lookup array `A[]` and replace it with its counterpart, or leave it unchanged if it is not found (which may only happen for `ABCDEIJKLOPQRUVWY`).
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, ~~90~~, 88 bytes
```
$_=uc;s/.[}*]|://g;y/-{)SFHXGT915=][ZNM/MZN915=][SFHXGT{:-/;s/{/{N}/g;s/:/:)/g;s/-/--*/g
```
[Try it online!](https://tio.run/##JYvBCoJAFEX37ytatFGYHrNw4YgLZ2G5cIQ0iCciFSVBOKK1iMlfbxoS7uIcLme4jo/A2nUbvy7RhJt69puPQOyiNzLjlenuuK1CHsRNTSrHnNQiy2EEQ1cZNGp2yYQChfcHhoz52FmbyBISGcJNa@BFAWlGtJIHIuCZq9ycLQCmn2vhAVUKzqcRZLL/6uF51/1k2fAD "Perl 5 – Try It Online")
using the same algorithm as [Neil's answer](https://codegolf.stackexchange.com/a/214512/70745)
saved 2 bytes removing the backslash before the opening brace, and removing the colon instead of closing parenthesis in `:)`
[Answer]
# [Python 3](https://docs.python.org/3/), ~~189~~ ~~147~~ ~~127~~ 135 bytes
```
s=input().upper()
b=[*'915=][',':)','--*','{N}']
for k,v in zip(*['SFHXGTNMZ',b][::0>max(map(s.find,b))or-1]):s=s.replace(k,v)
print(s)
```
[Try it online!](https://tio.run/##DcwxDoIwFADQnVN0az8pRGIcbFIHB3WRRQdD0wEUYqOUn7YYxXj2yvLGh59wH@wyRi@NxTEwyEfE1jFIGqlSui5WUivKqYCZLEtnv@WP6qQbHHnwFzGWTAZZquhpd7jsz@WxorzRSojFpq/frK@R@bwz9sYbgMFlhQbhpc9di8/62rI5gQSdsYF5iLEz00S2Y1X9AQ "Python 3 – Try It Online")
If this were not codegolf the conditional should obviously be outside of the `for` rather than repeated at each iteration. What wouldn't we do for a few bytes...
* *saved 42 bytes by replacing the dict with two lists;*
* *saved 20 bytes thanks to ovs' `[::True or-1]` dark magic.*
* *added 8 bytes because of missing `.upper()`*
[Answer]
# [Haskell](https://www.haskell.org/), 186 bytes
```
import Data.Char
k="S 9 F 1 H 5 X = Z {N} M --* N :) G ] T [ "
v=words$k++map toLower k
w=v++reverse v
_!""=""
[]!(t:u)=t:w!u
(a:b:c)!s|n<-length a,take n s==a=b++w!drop n s|1<2=c!s
(w!)
```
[Try it online!](https://tio.run/##FY9Ba8IwAEbv@RVfgge72oEDDwZzmBvqYHqpA2kpI9ZUpbUpSWwP6l9fFy@Px3f5eCdpS1VVfX@@NNo4fEonXz9O0pBSsBhTLDDGChPsIJDgtnlgjSh6wQY8wBIZtkjBSCs6bQ52UIbhRTZw@lt3yqAknWjD0KhWGavQkl/KmGCMpBkdOn4NhOMdvZKh5HueB9Te61lUqfroTpAjJ0uFGlYIKfZh2NGD0c1zuI9nbyKnlhRi2NGgv8hzLRpzrt3g@V6k7H0esxErtPZcfCUJ5j9J4v1WP1IeeNlL4xkvVrtkvVluvU/HE@H7fBwPspRl/V9eVPJo@yhvmn8 "Haskell – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~226~~ ~~189~~ 181 bytes
Saved a whopping 37 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!!
Saved 6 bytes thanks to [Stef](https://codegolf.stackexchange.com/users/96480/stef)!!!
```
from re import*
def f(s,m="9 1 5 = --* :\) ] \[ {N}".split()):
for t,r in zip(*(m,"SFHXMNGTZ")[::2*bool(search(f"({'|'.join(m)})",s,I))-1]):s=sub(t,r,s,0,I)
return sub(r'\\','',s)
```
[Try it online!](https://tio.run/##XZBRS8MwEMff@ymOvCQp6bCbIivkYXuY7sENdIK03YPrUlZd25BkoNZ@9pp0HYohcHf/3C/35@SnOdTVpOtyVZegBBSlrJXxvb3IISealRxNIYQb4BAEPkQphS2kCTSrFo20PBaGUBp5kNcKDFNQVPBVSOKTkqGnxf3Lw@puEyOaRNHY39X1kWjxqrIDyRFp8DcevdVFRUraUsQ0W1IahFsaaa5PO2K/s9qVVT3rzJxUBU5WOE0xw5hp2hmhjbbWCJrNnxADtFiv@7CMY5g/x7ErrNUkoi6bzx4R9cSHFJkR@4GbupfwzIVL22yvZc@JE@PN6hfODiJ7F8qxOD2Nb68zzKDPwgmm3nkN4rKG3h@Dy0S3KHuc45wY2hdSFZUhOUaNaREE1q62sRnmJIJzvW3x0NuD@j@oB1D@BSXnpge7Hw "Python 3 – Try It Online")
Will reverse the translation if any of the mappings are in the input.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 333 bytes I'--\* e=ac[ly 5al1 o1 9a[a:) N
```
void f(char*i,char*o,int*a,int*e,char**c){int t=0;int s=0;char*p=0;while(i[0]){char x=e[(uint8_t)i[0]];if(x){int l;s=a[(s*23)+x-1];if((l=a[((s+1)*23)-1]))t=l;if(!p)p=i;if(s){i++;continue;}}s=0;if(t){if(t>9)o+=sprintf(o,c[t-10]);else o+=sprintf(o,c[t+8]);t=0;p=0;continue;}if(p){while(p<i){o[0]=p[0];o++;p++;}p=0;}o[0]=i[0];o++;i++;}}
```
[Try it online!](https://tio.run/##7Zhtd9pGFsdfw6e4cfqAhAiMeDCYkI0d27E3hLRgt2kozcpisLUrS1QPjh2W/erZ@x8JhFN6mtOo5/RFfOwfc@@M7vznMjDja1cubfvDQ8ez3Xgq6bEMAs9/dPWkmLnCaOpscXnRx77A8S7v@2LP4aHwFR9O5czxJPUFicwwycyMOtUzo0GNzGhSMzNa1MqMXdrNjDa1M6NDnbUx5ElrmWWSyDQM6yQyEcMGiUzFsEkikzFskch0DHdJZEKGbRKZkmGHRPvDje9MaVayr6xAdwz14hucN91SlIlLt7UFmxT1al28hvyqOubceHfluLLkjGsTbQEn3fbkuBTzuPbbSIN/0nVmpdskhNsNe9a4FOpmXSvfVoTqK7nwlcKy0OBnr6ZFPRddD@bavOegFXKAcrlr@17keLHsLpeQwR0RdzCfdDS/3Avn/BZHs5Jv2OOoIlhUV7qhpI@7ym3uwXqwhCwmB5pri2RJ88eOtvBZf2/O6Po8@Zz/lnhiqfzOyg9hy@UHLPDacrwSGlZwaRukMqJz@2Y80WhRLCjHRTybSVYzPjg/Hp2@mVCPFrVl916vH0fbu/U5tjH7VlG6xWKhqtN3WB7xYyR/pfDu@sJ3Q9Krq6fAtwgq2ipgsVDYGe0YVK3yhodxnBomjJPUqMN4nRoNGG9SownjZWq0YAxSYxfG89RowzhLjQ4bsDuJPVTzitRQ8zZTQ83bSw0172KwTE01c6Wip6aae09LLTX5JDXU5OMd1ea5kUKVqpHKDucpdm4sV3q2pNKPfuxO6UKSZ13LKcl56Liu75Ht@mEcSOKUWzRz5S0FMozdSFO5VSmfzUIZjc1mK01sVS8MzvtEo1cnjLPXREcKr84Yg@@J9p@9IDo44iF0MGKccAf1jxk/oHWM1rMhIQJwqqYqENUMyg9q1xQO@0dEh88EYAJ1oEE02GeNo58GEH/Acva5RUcv2XfO5tHoGYRC/HNgCJyP/kKhNPqOLXoA7AAPga@Ar4FvgG@BEqABOlAGEIkqwCOg@qeECsC876v/VijVMIUATKAONIAm0AJ2gTbQAfaALvAY6AFPgH/cE9rYIqq5xdcCdu/72luEPsUU@8ABgLeUDoEjALuQngMnwCnwT@AFgM1LLwFsDHr1aRntMARaQvzOEIEEi/p9oeqt/x7Ap4Kw2QifFDoHfgB@BF4DPwFvgDHwMzABfgHebhcqkFuxJZmitW4ho2KdR9HZktF/YQoLuABsYApIYAZcAleAA/wb@A/gAteAB/i5ZtT8SOgcU/wKBEAIREAM3ADvgFvgDngPLID/Akvgf7xf@GvsszJqrnWb5m8yWvmjH8@PSB3s1oUr/2jwX/j19EXoF6FfhH4R@ncTqm696tJ7eLxPJSuO/EvpycCK@JJ7cUdzGYS@51kuRT7/w2DQ9R3h/yHLjvhWYnkytB658p0TPr3kf23cR7Z/nd18Ee3ainxv3GyayeW3WuUVaAbpBlUM3Jj4AOAjas@gnkHHBj036MSglwYNDBoZdGbQa4PeGDQ2aGKQZ9DCoCWywPJrKgAfCnwbaKhIfHLwkdFGSD7z@MTjs43vCnzU8EHD5wofKHC2jfRx3PUjXipfyZLcKjdO7tqf/83Ufc7v0MwrUD2vQAKBzM8PtJn45mbiP09eI6d19vPKfL@dV6C83sJ@ayP1opZb7vu7eQkUeQXq5BUot23V3Mx9jvs@r5UOP3m74kr@CV@BuK/X/g5fpbsbmTfz2fVmPUd9rbwCNdPjHIdvIKfpyX6QFALfo0g1jyO1/qSGWeJBfCwH0pqWRmeHp4O3x6f9o8ErY1085CO2VtM0VZssODP1wGOqJXYhLZnuHAWBH6gwjneZzrJHX4c/ezsGhVEg0V9SlXlN6@LJQEZx4FFFwFqyzkJStiz3EuHKh6qlFYQyqKripQzIiULpztQKZqVM47okamR3DiMtvCVFVpQ2MXORb2UcM3Is172j2PMvZnFoq9vOlQwk7RULG0Vv0p1VjdY3CFnVrfRVrjp0O00OKuCczFo3NcKVkZZlVyb/bhTFk0QmlXEesVEbp6Q4jm78qSJ5MrqQlMpVUwFToWxOOpl1jcocqkJisjFCldGTUTysTEJLx2Icv71Q7mK/JGMfzDWCYOd@iHAloICSdtJaV8eVibtZgmKqq7a5gmi9Am7TE@po5OM9z4rvZI8jiEJpXo1M6vNbBpWpvRqjsE4@76WseU/eckPKfCUlLefztnbWy0P9nmOoyn7qWS94vmots7mzCdVeXj3vrJ5fPZ2mbYn9zZu4uPoErTew2qOrTwdHXH44JeuaLLqRwR1VKvpisOxN6MKa0mV8R3ta8f8 "C (gcc) – Try It Online")
] |
[Question]
[
You are to write a program or function that outputs this exact text:
```
OPQRSTU
NQPONMV
MREDCLW
LSFABKX
KTGHIJY
JUVWXYZA
IHGFEDCB
```
May also be lowercase and trailing spaces and newlines are allowed.
Standard loopholes are disallowed
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so smallest byte count wins.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~28~~ 26 bytes
```
1Y2tIL)P0v7lYLP2:JTF-JQ&()
```
[**Try it online!**](http://matl.tryitonline.net/#code=MVkydElMKVAwdjdsWUxQMjpKVEYtSlEmKCk&input=)
### Explanation
```
1Y2 % Push string 'AB...Z'
tIL) % Duplicate, remove last: gives 'AB...Y'
P % Flip: gives 'YX...A'
0 % Push 0. Char 0 is treated as space
v % Concatenate into a column vector of char
7lYL % 7x7 numeric array: clockwise spiral of numbers from 1 to 49
P % Flip vertically to make it anti-clockwise
2: % Push [1 2]. Will be attached vertically after the last col
JqJh % Index "[end-1, end]", to be used as row index
JQ % Index "end+1", to be used as column index
&( % Assign [1 2] to those positions. The rest of the new col will contain 0
) % Index into the char vector. Indexing is modular and 1-based, so 0 as an
% index refers to the last value of the char vector, which is char 0, or
% equivalently space. So the 0 values in the numeric array give spaces.
% Implicitly display
```
[Answer]
# Python 2, 69 bytes
```
print'''OPQRSTU
NQPONMV
MREDCLW
LSFABKX
KTGHIJY
JUVWXYZA
IHGFEDCB'''
```
Just do it...
[Answer]
# Bubblegum, 47 bytes
A hex dump, courtesy of `xxd`:
```
00000000: 520a adf6 2e08 7444 c41e c8ff 4096 ca2d [[email protected]](/cdn-cgi/l/email-protection)
00000010: 8832 2297 8cd7 1bb1 fe10 43ce 39cc 8e5f .2".......C.9.._
00000020: 31f7 3d63 432e d3f3 3873 ecf7 7641 a3 1.=cC...8s..vA.
```
(This is just the spiral, “compressed”.)
[Try it online.](http://bubblegum.tryitonline.net/#code=MDAwMDAwMDA6IDUyMGEgYWRmNiAyZTA4IDc0NDQgYzQxZSBjOGZmIDQwOTYgY2EyZCAgUi4uLi4udEQuLi4uQC4uLQowMDAwMDAxMDogODgzMiAyMjk3IDhjZDcgMWJiMSBmZTEwIDQzY2UgMzljYyA4ZTVmICAuMiIuLi4uLi4uQy45Li5fCjAwMDAwMDIwOiAzMWY3IDNkNjMgNDMyZSBkM2YzIDM4NzMgZWNmNyA3NjQxIGEzICAgIDEuPWNDLi4uOHMuLnZBLgo&input=)
[Answer]
# Fourier, ~~143~~ 141 bytes
Not a particularly interesting answer except that it stores newlines (ASCII code 10) as the variable T... Uses [isaacg's golfing program](https://codegolf.stackexchange.com/a/55385/30525).
```
79a^a^a^a^a^a^a10a~T78a81avavavava86aTa77a82a69avava76a87aTa76a83a70a65a^a75a88aTa75a84a71a^a^a^a89a10a74a85a^a^a^a^a^a65aTa73avavavavavavava
```
~~[Try it online](https://labs.turbo.run/beta/fourier/?code=NzlhXmFeYV5hXmFeYV5hMTBhflQ3OGE4MWF2YXZhdmF2YTg2YVRhNzdhODJhNjlhdmF2YTc2YTg3YVRhNzZhODNhNzBhNjVhXmE3NWE4OGFUYTc1YTg0YTcxYV5hXmFeYTg5YTEwYTc0YTg1YV5hXmFeYV5hXmE2NWFUYTczYXZhdmF2YXZhdmF2YXZh)~~
**[Try it online!](http://fourier.tryitonline.net/#code=NzlhXmFeYV5hXmFeYV5hMTBhflQ3OGE4MWF2YXZhdmF2YTg2YVRhNzdhODJhNjlhdmF2YTc2YTg3YVRhNzZhODNhNzBhNjVhXmE3NWE4OGFUYTc1YTg0YTcxYV5hXmFeYTg5YTEwYTc0YTg1YV5hXmFeYV5hXmE2NWFUYTczYXZhdmF2YXZhdmF2YXZh)**
[Answer]
# Python 3, 72 bytes
```
print('OPQRSTU\nNQPONMV\nMREDCLW\nLSFABKX\nKTGHIJY\nJUVWXYZA\nIHGFEDCB')
```
Not exactly interesting, but it still works!
[Answer]
## PHP, 130 bytes
```
for($p=30,$s=1,$r=_;$i<51;$r[$p]=chr(90-abs(25-$i++)),$p+=$s*(9-$d))if(!$n||!$c=++$c%$n)($d=8-$d)?$n++:$s=-$s;echo wordwrap($r,8);
```
literally draws the spiral. Run with `-r`
**breakdown**
```
for($p=30,$s=1,$r=_; // initialize position to 3*9+3, $s(ign) to +1, $r(esult) to string
// implicit $c(ount)=$d(irection)=$i(ndex)=le($n)gth=0
$i<51; // loop $i from 0 to 50
$r[$p]=chr(90-abs(25-$i++)),// 2. set current position in string to correct character
$p+=$s*(9-$d)) // 3. move cursor
if(!$n||!$c=++$c%$n) // 1. if 1st iteration ($n==0) or ++$c has rotated around $n
($d=8-$d) // negate $direction (0=horizontal, 8=vertical)
?$n++ // if vertical: increase length
:$s=-$s // else invert sign
;
// output: wrap to lines of 8 characters
echo wordwrap($r,8); // having left spaces avoids need to provide 3rd and 4th parameter
```
Easy to extend: For more alphabet,
append `%50` after `$i++`,
replace `51` with the wanted number,
modify `8-$d`, `9-$d`, `$p=30` and the `wordwrap` width to the new dimensions.
[Answer]
# JavaScript ES6, 62 bytes
```
a=>`OPQRSTU
NQPONMV
MREDCLW
LSFABKX
KTGHIJY
JUVWXYZA
IHGFEDCB`
```
## Try it
```
let f=a=>`OPQRSTU
NQPONMV
MREDCLW
LSFABKX
KTGHIJY
JUVWXYZA
IHGFEDCB`;
console.log(f());
```
[Answer]
# Ruby, 63 bytes
In this case, nothing I found beats the boring answer...
```
puts"OPQRSTU
NQPONMV
MREDCLW
LSFABKX
KTGHIJY
JUVWXYZA
IHGFEDCB"
```
My best solution that didn't print the literal string only, but still has to directly hardcode some of it, is **110 bytes**:
```
w=[*?B..?Q].reverse*''
puts [*?O..?U]*'',[?N,w[0,5],?V]*'',"MREDCLW
LSFABKX
KTGHIJY",[?J,*?U..?Z,?A]*'',w[8,8]
```
[Answer]
# [///](http://esolangs.org/wiki////), 57 bytes
```
OPQRSTU
NQPONMV
MREDCLW
LSFABKX
KTGHIJY
JUVWXYZA
IHGFEDCB
```
[Try it online!](http://slashes.tryitonline.net#code=T1BRUlNUVQpOUVBPTk1WCk1SRURDTFcKTFNGQUJLWApLVEdISUpZCkpVVldYWVpBCklIR0ZFRENC)
Just another boring answer. Move on!
[Answer]
# Lua, 69 bytes
```
print([[OPQRSTU
NQPONMV
MREDCLW
LSFABKX
KTGHIJY
JUVWXYZA
IHGFEDCB]])
```
At least it works!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 46 bytes
```
•ûk2šÄ>¸©W$V-ÏfQ*LnHO”Ïmsqšƒ1ËUðhd@ý(™š•36B1¡»
```
[Try it online!](https://tio.run/nexus/05ab1e#AUgAt///4oCiw7trMsWhw4Q@wrjCqVckVi3Dj2ZRKkxuSE/igJ3Dj21zccWhxpIxw4tVw7BoZEDDvSjihKLFoeKAojM2QjHCocK7//8 "05AB1E – TIO Nexus")
Won't win by any means, but it does work.
[Answer]
# C#, ~~151~~ ~~145~~ ~~136~~ 130 bytes
```
namespace a{class P{static void Main(){System.Console.Write("OPQRSTU\nNQPONMV\nMREDCLW\nLSFABKX\nKTGHIJY\nJUVWXYZA\nIHGFEDCB");}}}
```
Again, a boring one that does the trick.
Saved 6 bytes thanks to auhmaan.
[Answer]
# Windows batch, 84 bytes
```
@for %%p in (OPQRSTU NQPONMV MREDCLW LSFABKX KTGHIJY JUVWXYZA IHGFEDCB) do @echo %%p
```
Simple enough `for` loop to loop through the strings.
[Answer]
# Japt, ~~54~~ 52 bytes
```
`opqÏ
nqpmv
mdclw
lsfabkx
ktgjy
juvwxyza
ihgfcb
```
[Try it online](http://ethproductions.github.io/japt/?v=1.4.5&code=YG9wcc8PCm5xcI1tdgptnGRjbHcKbHNmYWJreAprdGeWankKanV2d3h5emEKaWhnZoJjYmB1&input=)
---
## Explanation
Simply a compressed string of the spiral in lowercase.
[Answer]
# Modern Pascal 2.0, 122 bytes
```
Write('OPQRSTU'+#13#10+'NQPONMV'+#13#10+'MREDCLW'+#13#10+'LSFABKX'+#13#10+'KTGHIJY'+#13#10+'JUVWXYZA'+#13#10+'IHGFEDCB');
```
***Explanation***
Simply embed CRLF into the string, and display it.
// Author of Modern Pascal
] |
[Question]
[
**Introduction**
You belong to a council which oversees the destruction of corrupted worlds. When the council assembles, a single vote is taken. The ballot lists all nominated worlds. One is ultimately destroyed each time the council meets.
Due to a bug in user12345's code, [the council recently flooded and then sent pirate zombies to the wrong planet](https://codegolf.stackexchange.com/q/23775/18487). We need a more reliable system for counting votes.
**Problem**
A vote is described by a series of integers on a single line. The first integer is `m`, and the worlds nominated for destruction are uniquely numbered from 1 to `m`. The remaining integers each represent the world each council member voted on.
Somehow, without any collusion, one world always receives more than half of the vote. This *always* occurs, regardless of how many worlds are present.
Given an input, write a program that outputs the world elected for destruction.
**Example Input**
Remember, the first `3` is the number of worlds, `m`. It is not a vote.
`3 1 1 2 3 1 3 1 1 3`
**Example Output**
The majority of the council voted for planet 1, so we output that.
`1`
**Assumptions**
* The exact number of votes is not given
* The number of votes is between 1 and 100 (inclusive)
* Each vote is between 1 and m (inclusive)
* Every vote contains a majority
* Input must be provided through stdin, read from a file, or accepted as a sole argument to the program
The answer with the fewest characters wins!
[Answer]
## GolfScript (10 9 chars)
```
~]$.,(2/=
```
Explanation:
```
~] # Parse input into array
$ # Sort; note that the extra element giving the number of worlds will end up last
.,(2/= # Take the middle element (not counting the last one)
```
Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for 10->9.
[Answer]
## APL (21)
```
∪v/⍨c=⌈/c←+/∘.=⍨v←1↓⎕
```
[Answer]
# Python (50)
```
l=raw_input().split()[1:];print max(l,key=l.count)
```
This approach doesn't need sorting. It finds the element which appears the most times is list `l`, using the `max` function and different ordering function.
[Answer]
# Mathematica (19)
```
g=Commonest@Rest@#&
```
Input as follows:
```
g[{3, 1, 1, 2, 3, 1, 3, 1, 1, 3}]
```
Output:
```
{1}
```
[Answer]
# Python, ~~61~~ 60
```
l=map(int,raw_input().split())[1:];print sorted(l)[len(l)/2]
```
22 characters are spent parsing the input with spaces; if I could do comma separated, my score would drop to **39**.
Does the same thing as the other answers: drops the first element, then prints the element at halfway through the list when it is sorted.
Explanation:
```
raw_input().split() # Get the line of input, split on spaces
map(int,raw_input().split()) # Convert list of strings into list of ints
map(int,raw_input().split())[1:] # Drop the first element
l=map(int,raw_input().split())[1:]; # Assign list to variable `l`
sorted(l) # Sort l in ascending order
sorted(l)[len(l)/2] # Get the element halfway through the list.
print sorted(l)[len(l)/2] # Print it
l=map(int,raw_input().split())[1:];print sorted(l)[len(l)/2] # Combine statements
```
[Answer]
# [Pyth 1.0.5](https://github.com/isaacg1/pyth/blob/master/pyth.py), 10
```
JPwd;ocJNJ
```
Unlike almost every solution above, this code doesn't just take the middlemost element.
Explanation:
```
JPwd J = input, split on spaces
; Print last element of
ocJN Order by count in J of N,
J For N in J
```
---
Bonus solution:
# Council Plurality, 11
If you want pluralities to be correctly judged as well, that's one more character:
```
JtPwd;ocJNJ
```
This judges correctly the only case where the above fails for pluralities: When the last planet has one less vote than the plurality winner, the 10 character code will mistakenly select the last planet, because it counts the statement of the number of worlds as a vote.
This code corrects that error by using the tail function, `t`, to ignore the first number.
[Answer]
# J (33 characters)
33 characters in J: `(>:@i.>./)@:(+/"1)@(>:@i.@{.=/}.)`
Use it as:
```
(>:@i.>./)@:(+/"1)@(>:@i.@{.=/}.) 3 1 1 2 3 1 3 1 1 3
```
[Answer]
# J - 18 char
```
({~<.@-:@#)@/:~@}.
```
Explained by explosion:
```
({~<.@-:@#)@/:~@}. NB. find the majority vote!
}. NB. remove the head of the list
/:~ NB. sort the list
( #) NB. take the length
<.@-: NB. halve it and round down
{~ NB. select from the beheaded list
```
Usage:
```
({~<.@-:@#)@/:~@}. 3 1 1 2 3 1 3 1 1 3
1
({~<.@-:@#)@/:~@}. 20 3 2 2 1 1 1 1 7 7 7 7 7 7 7 7 7
7
```
[Answer]
## Groovy - 99 Chars
Using drop-sort-get-midway technique:
```
l=(System.in.text as List).findAll{!it.allWhitespace}.drop(1).sort()
println l.get((int)l.size()/2)
```
Ungolfed, somewhat:
```
list = System.in.text as List
s = list.findAll{ ! it.isAllWhitespace() }.drop(1).sort()
i = (int) s.size() / 2
println s.get(i)
```
[Answer]
# Python (78):
I swear I didn't see Quincunx's answer before I posted this...
```
from collections import*;print Counter(raw_input().split()[0:]).most_common(1)
```
[Answer]
# C# 133 chars
Because it's totally worth it to go into an old question and add an answer massively longer than any other. c# is tough to golf.
```
namespace System.Linq{class P{static void Main(){Console.Write(Console.ReadLine().GroupBy(x=>x).OrderBy(x=>x.Count()).Last().Key);}}}
```
[Answer]
# Python, ~~88~~ 83
```
from collections import*;print Counter(map(int,raw_input().split())).most_common(1)
```
This works even if one world gets only one more vote than another, because it uses modes.
The output for the example: `[(1, 5)]`. The first number is the world to destroy, and the second is the number of votes it got. This output is valid according to your rules:
>
> write a program that outputs the world elected for destruction.
>
>
>
And you gave an **Example output**, not a **Corresponding output**.
But if I really need the single number, then this works for **6** more characters:
```
from collections import*;print Counter(map(eval,raw_input().split())).most_common(1)[0][0]
```
Explanation:
```
from collections import* # import everything from the `collections` module
raw_input().split() # Get the line of input, split on spaces
map(int,raw_input().split()) # Convert the list of strings to a list of ints
Counter(map(int,raw_input().split())) # Create a Counter object (from collections) to get the mode
Counter(map(int,raw_input().split())).most_common(1) # Get the most common element of the Counter object
print Counter(map(int,raw_input().split())).most_common(1) # Print it
from collections import*;print Counter(map(int,raw_input().split())).most_common(1) # Combined statements
```
[Answer]
## J 21
```
(~.(#~(=>./))#/.~)@}.
```
Explanation from right to left:
1. `}.` drop first number
2. fork:
1. `#/.~`: Count per unique element the number of occurences
2. Hook:
1. `#~` copy from left
2. `(=>./)` hook: where right is maximum of right
3. `~.` : take unique elements, in order
Examples
```
(~.(#~(=>./))#/.~)@}. 3 1 1 2 3 1 3 1 1 3
1
(~.(#~(=>./))#/.~)@}. 10 1 2 1 7 1 2 2 7 7 7
7
```
[Answer]
# PHP - 66
```
<?=!preg_filter(~‹fl—‹ö,~€û§€ñ‘‘¢¬€œ,$argv[1]).sort($a)?:$a[$i/2];
```
Without the special chars:
```
<?=!preg_filter("# .#e",'$a[$i++]=$0',$argv[1]).sort($a)?:$a[$i/2];
```
[Answer]
# JavaScript (60)
```
a=prompt().split(" ").slice(1).sort();alert(a[a.length/2-1])
```
] |
Subsets and Splits