text
stringlengths 180
608k
|
---|
[Question]
[
Make a code that gets list of [badges](https://codegolf.stackexchange.com/help/badges) that nobody received yet (for example, by using this [website API for badges](https://api.stackexchange.com/docs/badges)), and output the sorted list of such badges, with new line after each.
Example output (may be smaller, depending on when you do this challenge):
```
Archaeologist
Caucus
Constituent
Copy Editor
Deputy
Electorate
Epic
Generalist
Hacker
Legendary
Marshal
Outspoken
Research Assistant
Sheriff
Steward
Strunk & White
Tenacious
Unsung Hero
```
Smallest code wins.
[Answer]
# JavaScript with jQuery (loaded onto SE sites by default), 58
```
$('.badge',$('.badge-count:not(:has(*))').parent()).text()
```
Must be run on <https://codegolf.stackexchange.com/help/badges>. ;)
Strictly conforming output, 116 chars:
```
[].join.call($('.badge',$('.badge-count:not(:has(*))').parent()).map(function(){return $(this).text()}).sort(),'\n')
```
Screenshot of console output (click to enlarge):
[](https://i.stack.imgur.com/E4vGl.png "Click me to enlarge!")
[Answer]
**Bash, 173 characters**
```
curl "https://api.stackexchange.com/2.1/badges?page="{0..50}"&pagesize=100&order=desc&sort=type&site=codegolf"|gunzip|grep -Po '{"name".*?award_count":0.*?}'|cut -d'"' -f 4
```
Though you could probably shave some characters off by using url shortening.
**WARNING:** Note that running this script a couple of times *will* result in this:
```
{"error_name":"throttle_violation","error_message":"too many requests from this IP, more requests available in 84495 seconds","error_id":502}
```
**Output for codegolf.SE:**
```
code-golf
Informed
Research Assistant
Caucus
Constituent
Outspoken
Deputy
Vox Populi
Excavator
Analytical
Self-Learner
Hacker
Beta
Legendary
Electorate
Investor
Tenacious
Unsung Hero
```
EDIT: tweaked it a bit.
[Answer]
# PHP - ~~92~~ 86 characters
```
<?=html_entity_decode(substr(file_get_contents("http://tinyurl.com/q9zlwfr"),12937,190));
```
Inspired by Victor's solution. Very volatile.
[Answer]
# Java - 280 267 260
```
class A{public static void main(String[]z)throws Exception{String s="";int y;java.io.InputStream x=new java.net.URL("http://tinyurl.com/q9zlwfr").openStream();while((y=x.read())!=-1)s+=(char)y;System.out.println(s.substring(12937,13126).replace("amp;",""));}}
```
] |
[Question]
[
I'm a young wizard, and I try very hard to not waste mana during my magical encounters.
I have X spells available at any given time and each one of them have its own mana cost Y.
*X,Y being positive integers strictly lower than 11.*
As a beginner, my mana pool fluctuates a lot (it is always lower than 11), and I need help to cast as few spells as possibles (scrolls are expensive, ya know) while emptying my mana pool. If you can't find any spell combination which matches exactly my mana pool's size, you shall then offer me closest (and cheaper) one.
I came to you and your infinite wisdom to help me become the greatest dark wizard. I shall not be disappointed.
**INPUT style (because style is everything):**
**Y;a b c d e f**
Y is the size of the mana pool. (a,b,c,d,e,f) are the spells. There are 6 spells, first one costs 'a' mana, second spell costs 'b' mana, etc.
**INPUT : 4;1 2 3 3 7 6**
I have 4 manas available, and 6 spells available. Two spells cost 1 mana, 1 spell costs 2 mana, two spells cost 3 mana, etc.
**OUTPUT : (3,1)**
---
**INPUT : 3;1 3 5 2 10
OUTPUT : (3)**
---
**INPUT : 8 ; 4 1 9
OUTPUT : (4,1)**
---
**INPUT : 4;1 2 2 3
OUTPUT : (2,2),(1,3)**
You shall output every combination of spells, but there is no need to distinct spells which are the same cost.
The shortest incantation to whatever machine you desire will be granted a profusion of thanks, and a whip of destiny.
[Answer]
## APL (87)
```
↑∪m/⍨t=⌊/t←⊃∘⍴¨m←m/⍨t=⌈/t←+/¨m←{a/⍨⊃i≥+/a←k[⍵]}¨⊃,/g,{z/⍨∧/¨2>/¨z←,⍳⍵/⍴k}¨1↓g←⍳⍴k←1↓i←⎕
```
The input format is an APL list, where the first element is the mana pool and the rest of the elements are the spells. The output has each possible combination of spells on a separate line.
```
⎕: 4, 1 2 3 3 7 6
3 1
⎕: 3, 1 3 5 2 10
3
⎕: 8, 4 1 9
1 4
⎕: 4, 1 2 2 3
2 2
3 1
```
Explanation:
* `k←1↓i←⎕`: read a list from the input, and store it in `i`. Drop the first element (mana) and store the rest in `k`.
* `1↓g←⍳⍴k`: generate a list from `1` to the length of `k`, and store it in `g`. Drop the first element, giving `[2..len k]`.
* `{`...`}¨`: For each of these, get the indices of each unique combination in `k` of length `⍵`:
+ `z←,⍳⍵/⍴k`: get a `⍵`-dimensional matrix of indices of length `k`, flatten it, and store it in `z`.
+ `∧/¨2>/¨`: for each coordinate in each index, see if all coordinates for the `N`th dimension are higher than those for the `N-1`th dimension.
+ `z/⍨`: select from `z` those elements for which the above holds true
* `⊃,/g,`: because the above does not work for one-dimensional vectors, add `g` to the front. We now have a list of lists of lists (because of the foreach) of all unique indices into `k`. Concatenate the lists together and de-enclose (so we end up with a list of lists).
* `{`...`}¨`: for each possible list of coordinates, look up the corresponding combination of values in `k`, and filter out those that are too expensive:
+ `a←k[⍵]`: look up the current combination in `k` and store it in `a`.
+ `a/⍨⊃i≥+/a`: select `a` only if the first item in `i` (the mana pool) is equal to or greater than the sum of the elements of `a`.
* `m←`: store all combinations of spells that do not exceed the mana limit in `m`.
* `m←m/⍨t=⌈/t←+/¨m`: select from `m` only those combinations whose sum is equal to the sum of the most expensive combination, and store it in `m` again.
* `m/⍨t=⌊/t←⊃∘⍴¨m`: select from `m` only those combinations whose length is equal to the length of the shortest combination.
* `↑∪`: remove any duplicates, and convert to a matrix (to display each combination on a separate line).
[Answer]
### Ruby, ~~114~~ 113 characters
```
x,y=eval gets
(d=0..10).find{|r|d.find{|c|s=y.sort.combination(c).select{|s|s.reduce(:+)==x-r}.uniq
p s if s[0]}}
```
Input: a two-element array of the wizard mana and the spell list, formatted a one-line JSON.
Output: a 2D array of the spell lists, formatted as a one-line JSON, or `nil` if the wizard can cast no spell.
I especially love `x,y = eval gets`. So dangerous and evil, yet so powerful and simple. Perfect for golfing.
Both `sort` and `uniq` are neccessary. Otherwise, this will produce duplicates for input like `[4, [1, 3, 1]]`. I'm not happy about this.
`find` is a useful method for control flow. Its return value is not as useful here, though. Length-wise, it comes on par with `any?`, which return value is even less useful.
Examples:
```
> [4, [1, 2, 3, 3, 7, 6]]
# [[1, 3]]
> [3, [1, 3, 5, 2, 10]]
# [[3]]
> [8, [4, 1, 9]]
# [[1, 4]]
> [4, [1, 2, 2, 3]]
# [[1, 3], [2, 2]]
> [4, [5, 6, 7]]
# nil
```
[Answer]
### GolfScript, 55 characters
```
[[]]\{{+}+1$%|}/.@{1$0+{+}*.@>!*100*\,-~}+:s%$0={\s=}+,
```
Try it [online](http://golfscript.apphb.com/?c=ewoKW1tdXVx7eyt9KzEkJXx9Ly5AezEkMCt7K30qLkA%2BISoxMDAqXCwtfn0rOnMlJDA9e1xzPX0rLAoKfTpDOwoKNCBbMSAxIDIgMyAzIDcgNl0gQyBwCjMgWzEgMyA1IDIgMTBdIEMgcAo4IFs0IDEgOV0gQyBwCjQgWzEgMiAyIDNdIEMgcAo%3D&run=true).
```
> 4 [1 1 2 3 3 7 6]
[[1 3]]
> 3 [1 3 5 2 10]
[[3]]
> 8 [4 1 9]
[[4 1]]
> 4 [1 2 2 3]
[[2 2] [1 3]]
```
[Answer]
### Haskell (GHC), ~~172 167~~ 143 chars
```
import Data.List
import GHC.Exts
f(x:y)=head.groupWith length.last.groupWith sum.filter((<=x).sum).nub$subsequences y
main=interact$show.f.read
```
Deobfuscated:
```
import Data.List
import GHC.Exts
f (x:xs) = head
. groupWith length
. last
. groupWith sum
. filter ((<= x) . sum)
. nub
$ subsequences xs
main = interact (show . f . read)
```
* Input format: bracketed list with head as available mana, tail as avaliable spells (e.g. `[4,1,2,3,3,7,6]`).
* Output format: bracketed list of lists, each sublist representing one possible set of spells.
Straightforward solution: grab the powerset of the input, then reduce that down by filtering for combinations we have sufficient mana for, etc.
[Answer]
# Mathematica 131
There must be shorter ways, but this is what I was able to come up with.
```
l=Length;
f[{a_,b_}]:=Select[t=Cases[s=SortBy[Union@Cases[Subsets[b],x_/;0<Tr@x<a+1:>{x,Tr@x}],Last],
{x_,s[[-1,2]]}:> x],l@#==l@t[[1]]&]
```
---
```
f[{4, {1, 2, 3, 7, 6}}]
```
>
> {{1, 3}}
>
>
>
---
```
f[{3, {1, 3, 5, 2, 10}}]
```
>
> {{3}}
>
>
>
---
```
f[{8, {4, 1, 9}}]
```
>
> {{4, 1}}
>
>
>
---
] |
[Question]
[
The look and say sequence is an example of a run length encoding sequence. To get the next term of the sequence one groups the sequence into runs of the same number, each group in the next term then becomes two digits, first the number of terms in the group, followed by the value in the group. The first term is `1`.
Here is how we would calculate the first couple of terms by hand:
>
> We start with `1`, grouping that gives us `[1]` a single group of 1 `1`. Thus our next term is `11`. We group this and get `[11]` a single group of 2 `1`s, so our next term is `21`. Grouping again we get `[2],[1]`, we translate each of these groups into 2 digits each, `12,11` and concatenate, `1211`. Group again `[1],[2],[11]`, then convert each group, `11,12,21` and concatenate, `111221`.
>
>
>
The first couple terms of the sequence are:
```
1
11
21
1211
111221
312211
13112221
1113213211
```
Write a program that when given **n** as input returns the length of the **n**th term of this sequence as output.
Programs should have a runtime of **O(n log n)**.
Answers will be scored in bytes with less bytes being better.
[Answer]
## GolfScript, 300 chars
```
~8-:m;'!5?HZi " A 9 "$??HLTZ^`eik 5Z`e <^ $k H ,Sds ?LT /5@MUav I " i ? "5i G !#+.4;>@K]_cdhjy{| *HCRJD@:64122/42.,,*860-40-0.+9?B<862//?D<7=@:420-/5:60.-20.+./384/162.-HCRJD@:64122/42.,,*)! !""$&&('{32-}/]1,/~:&;:L;:T;]:S;0m>{&m=}{L,,{.49=\71=+}%:V{,(,{).V=\T?S={(V=+}/}%0+:V}m*,,0\{.V=\L=8-*+}/}if
```
Here's a slightly shorter entry. Reads a number *m* from stdin, writes the length of the *m*-th term in the look-and-say sequence to stdout.
For example, input `50` produces output `894810`, while input `1000` produces (after a few seconds):
```
21465050086246039983937316427688400486337379416867195943208935654503780844828013651860410256502890125611856727316762
```
I'll post a more detailed explanation of the code later, but basically this also works by repeatedly multiplying a vector with a sparse matrix, encoded as an ASCII string. Some clever compression tricks, such as leaving out the all-ones superdiagonal of the matrix, are employed.
Ps. [Here's a link to an online demo.](http://golfscript.apphb.com/?c=OyI1MCIgICMgPC0tIHB1dCBpbnB1dCBoZXJlICh0aGUgd2ViIGZvcm0gaGFzIG5vIHNlcGFyYXRlIGZpZWxkIGZvciBpbnB1dCkKCn44LTptOychNT9IWmkgIiBBIDkgIiQ%2FP0hMVFpeYGVpayA1WmBlIDxeICRrIEggLFNkcyA%2FTFQgLzVATVVhdiBJICIgaSA%2FICI1aSBHICAhIysuNDs%2BQEtdX2NkaGp5e3wgKkhDUkpEQDo2NDEyMi80Mi4sLCo4NjAtNDAtMC4rOT9CPDg2Mi8vP0Q8Nz1AOjQyMC0vNTo2MC4tMjAuKy4vMzg0LzE2Mi4tSENSSkRAOjY0MTIyLzQyLiwsKikhICEiIiQmJignezMyLX0vXTEsL346Jjs6TDs6VDtdOlM7MG0%2BeyZtPX17TCwsey40OT1cNzE9K30lOlZ7LCgseykuVj1cVD9TPXsoVj0rfS99JTArOlZ9bSosLDBcey5WPVxMPTgtKit9L31pZg%3D%3D) The server has been pretty slow lately, though, so if you see an error message about a timeout, try again (or just [download the interpreter](http://www.golfscript.com/golfscript/) and run it yourself).
---
**Addendum:** Here's the promised detailed explanation. First, let me repost the code with whitespace and comments added:
```
# Parse input, subtract 8, save in variable m:
~ 8- :m;
# This long string encodes all the constants used by the program (I'll describe it below):
'!5?HZi " A 9 "$??HLTZ^`eik 5Z`e <^ $k H ,Sds ?LT /5@MUav I " i ? "5i G !#+.4;>@K]_cdhjy{| *HCRJD@:64122/42.,,*860-40-0.+9?B<862//?D<7=@:420-/5:60.-20.+./384/162.-HCRJD@:64122/42.,,*)! !""$&&('
# Parse the data string:
# The data consists of several arrays of positive integers, encoded as printable ASCII
# characters and separated by spaces. (Note that this means that the range of possible
# data values starts from 1, which requires some adjustment below. Also, the values in
# L are actually shifted up by 8 to avoid having single quotes in the data string.)
{32-}/ # Subtract 32 (ASCII code of space) from each char and dump result on stack.
] # Collect numbers from stack into an array.
1,/ ~ # Split array on zeros (formerly spaces) and dump pieces on stack.
:&; # Save topmost piece (canned responses for inputs 1-7) in var &.
:L; # Save second piece (element lengths) in var L.
:T; # Save third piece (nonstandard decay targets) in var T.
]:S; # Collect remaining pieces (nonstd decay sources) in array and save it in S.
# If m < 0, return a precomputed response from &, else run the indented code below:
0 m > { & m = } {
# Set V to be the initial element abundance vector (1 Hf + 1 Sn):
# (Note: both L and V have an extra sentinel 0 at the end to avoid overruns below.)
L,, { . 49= \ 71= + } % :V
# Update the element abundances m times:
{
# Run the following block for all numbers i from 0 to length(V)-2,
# collecting the results in an array:
,(, {
# Start with the abundance of element i+1 in V (all elements except H decay
# downwards; the extra 0 at the end of V is needed to avoid a crash here):
).V=\
# If this element is one of the decay targets listed in T, find the corresponding
# list of source elements in S and add their abundances from V to the total:
# (If this element is not in T, we just loop over an empty array at the end of S.)
T? S= { ( V= + } /
} %
# Append a new sentinel 0 to the end of the array and save it as the new V:
0+:V
} m *
# Multiply the element abundances from V with their lengths from L and sum them:
,,0\{.V=\L=8-*+}/
} if
```
The key fact that allows this code to work is that, as the look-and-say transformation is repeatedly applied to any string, it eventually splits into substrings which evolve independently, in the sense that we can obtain all the following elements of the look-and-say sequence starting from that string by taking each of the substrings, applying the look-and-say transformation to each of them independently *n* times and concatenating the results.
Furthermore, in his 1986 article "The Weird and Wonderful Chemistry of Audioactive Decay" (which basically introduced the look-and-say sequence to the world), John Conway proved a remarkable (and, for this challenge, crucial) result which he called the "cosmological theorem":
>
> **Cosmological theorem** (Conway): There is a set of 92 finite strings of numbers 1–3 (which Conway named after the chemical elements; see table [here](https://web.archive.org/web/20070126060642/http://www.btinternet.com/%7Ese16/js/lands2.htm)), and two infinite families of strings each consisting of a fixed prefix followed by some number higher than 3 (these can only appear if the initial string contained number higher than 3 or sequences of more than 3 identical numbers), such that, after at most 24 applications of the look-and-say transformation, *any* string splits into a chain of such elements, each of which thereafter evolves independently (and splits into further elements).
>
>
>
Thus, to determine the length of a string sufficiently far in the look-and-say sequence, it's sufficient to know how many times each element appears in it. And, since each element evolves independently, knowing these "elemental abundances" is also sufficient for calculating the corresponding abundances of the *next* string in the sequence, and so on.
As it happens, the look-and-say sequence starting from the string `1` splits into two Conway elements (**Hf**72 = `11132` and **Sn**50 = `13211`) after just seven iterations. Thus, thereafter, we only need to keep track of the abundances of the 92 "common" elements (as the two families of "transuranic" elements cannot arise from common elements).
Mathematically, we can treat the elemental abundances as a vector of length 92. Calculating the abundances in the next step of the look-and-say sequence is then just equivalent to multiplying this vector with a 92 × 92 matrix, which is what [r.e.s.'s solution](https://codegolf.stackexchange.com/a/8472) does literally.
In fact, r.e.s.'s solution actually tracks the abundance of each element *multiplied with its length* (i.e. the "total mass" of that element in the string), adjusting the matrix accordingly, so that the total length of the string is given simply by adding the numbers in the abundance vector together. However, I did not find that a particularly convenient representation for code golf. (It was convenient for [Nathaniel Johnston's derivation of Conway's polynomial](http://www.njohnston.ca/2010/10/a-derivation-of-conways-degree-71-look-and-say-polynomial/), since it encodes the lengths into the matrix and thus gives the right eigenvalue for the asymptotic growth rate, but we don't care about that here.)
Instead, I just track the raw abundances of the elements, and only multiply them with the lengths at the end. This has, combined with the convenient fact that none of the decay products of any element contain more than one copy of any element, means that the entries of the transition matrix are just zeros and ones. Also, by far most of them are, in fact, zeros (in math jargon, the matrix is sparse), so I can save a lot of space by only storing the indices of those entries which are ones.
Also, in his article, Conway ordered the elements such that (except for **H**1 = `22`, which is a fixed point of the look-and-say transformation), each element decays to the next lower element in the sequence (and possibly some others).
In fact, most elements decay *only* to the next lower elements. Thus, by using Conway's ordering of the elements, I can hardcode this "standard decay" as part of the iteration, so that I only need to store the matrix entries corresponding to the other, "nonstandard" decays, saving even more space.
(In fact, what I actually do, for reasons mostly to do with how GolfScript's array operations work, is store one array listing the matrix rows containing non-zero entries (i.e. the elements which are produced in nonstandard decays) and another array of arrays listing, for each of these rows, the columns where the non-zero entries occur (i.e. the elements which produce these elements in such decays). See the code and comments above for how these arrays are actually used to calculate the updated element abundances.)
The final space-saving trick I used was to encode all these arrays as strings of ASCII characters. Conveniently, there are 95 printable ASCII characters from space (32) to `~` (126), and the largest value that appears in any of the arrays is 92, so they fit very well. One extra tweak I made was to shift the values in the element length array (which only go up to 42 anyway) up by 8 so that I could avoid the character `'` (39) and thus store my data in a single quoted string without having to add any backslash escape characters.
There are some other minor optimizations too, but those are just standard GolfScript coding tricks. I should note that the actual code is not all that carefully optimized — it's quite possible that it could be golfed down further.
In any case, despite the inherent slowness of a double-interpreted language like GolfScript, the code runs quite fast and scales well: computing the length of the 10,000th string in the look-and-say sequence takes about 1.5 minutes on my computer.
Conveniently, GolfScript stores all numbers as arbitrary-length integers (bignums), so I didn't have to do anything special to make it produce exact results even for large inputs.
The expected time complexity of this program is **O(*n* log *n*)** (as the element abundances grow linearly with *n*, and bignum addition takes O(log *n*) time), and the actual runtime seems to fit that prediction pretty well, as the graph below shows:

(Time is in seconds; for what it's worth, the green curve is given by *y* = (*a x* log(*b* + *x*) + *c*) / *x*, where *a* = 0.00106462026133545, *b* = 2720.25843721031 and *c* = -0.0401630789530016. The spike on the left mainly comes from the roughly constant runtimes for *n* < 8, which become relatively large when divided by small *n*. I did not include it in the curve fit.)
[Answer]
## Sage ~~(18664~~ ~~2021~~ 1977)
This is a version that uses [Nathaniel Johhnston's matrix formulation](http://www.njohnston.ca/2010/10/a-derivation-of-conways-degree-71-look-and-say-polynomial/). (The matrix could probably be golfed further using `eval`.)
```
def f(n):
z=[0];a=z*10;b=z*15;c=z*18;d=z*25;e=z*31;g=z*68;T=Matrix([z*28+[2]+z*63,e+[7/23]+z*60,z*29+[4/3]+z*62,z*30+[4/3]+z*61,z*32+[2]+z*59,z*53+[1/2]+z*38,z*36+[3/2]+z*55,z*37+[2]+z*54,z*38+[8/5]+z*53,z*39+[5/3]+z*52,z*43+[5/3]+z*48,z*45+[7/4]+z*46,z*46+[12/7]+z*45,z*47+[7/4]+z*44,z*48+[3/2]+z*43,z*50+[21/17]+z*41,z*51+[21/17]+z*40,z*49+[13/10]+z*42,z*44+[7/5]+z*47,z*52+[7/5]+z*39,z*40+[7/5]+z*51,z*41+[4/3]+z*50,z*42+[4/3]+z*49,z*34+[5/32,5/32]+z*56,z*56+[7/11,7/13,1/3,7/17]+z*32,z*54+[10/7]+z*37,z*55+[10/7]+z*36,z*33+[4/3]+z*58,b+[1/21,1/21,0,1/7]+z*12+[2/23,0,0,1/16,1/16]+z*17+[1/5,0,0,2/11,2/13,2/21,4/17]+z*21+[1/8]+z*3+[1/3]+z*6,z*17+[9/26]+g+[9/10]+z*5,z*87+[9/10]+z*4,z*19+[23/28]+z*72,z*34+[1/16,1/16]+d+[2]+z*19+[1/8]+a,z*88+[2]+z*3,z*90+[32/27,0],z*89+[32/27,0,0],z*91+[8/5],z*66+[3/7]+z*7+[1/3]+a+[1/2,3/10,3/10]+z*4,z*66+[5/7]+d,z*62+[3/2]+z*29,z*63+[10/7]+z*28,z*64+[9/7]+z*27,z*65+[9/7]+z*26,z*67+[3/2]+z*24,z*82+[5/3]+z*9,z*83+[8/5]+z*8,z*74+[7/9,7/12,7/12,7/16,7/18,7/24,7/23,7/16]+a,g+[4/3]+z*23,z*70+[6/5]+z*21,z*71+[5/4]+z*20,z*72+[17/14]+z*19,z*73+[17/14]+c,z*84+[4/3]+z*7,z*69+[5/4]+z*22,z*6+[7/12]+g+[7/12]+z*16,z*76+[7/12]+b,z*77+[11/16]+z*14,z*78+[13/18]+z*13,z*79+[7/8]+z*12,z*80+[17/23]+z*11,e+[2/23,0,0,1/16,1/16]+z*17+[1/5]+z*5+[2/17,1]+z*20+[1/8]+a,[0,1/7]+z*90,[1]+z*91,[0,1]+z*90,[0,0,7/6]+z*89,z*3+[7/6]+z*88,z*57+[7/13]+z*34,z*4+[1]+z*54+[4/17]+z*32,z*5+[6/5]+z*86,z*7+[4/3]+z*84,z*8+[5/4]+z*83,z*20+[8/7]+z*71,z*21+[7/6]+z*70,z*22+[7/6]+z*69,c+[9/14,9/28]+z*72,z*9+[6/5]+z*82,a+[6/5]+z*81,z*12+[4/3]+z*79,z*13+[9/7]+z*78,z*14+[4/3]+z*77,b+[23/42,23/42,23/26]+z*74,z*11+[8/7]+z*80,z*23+[6/5]+g,z*6+[5/12]+z*85,e+[15/23]+z*26+[5/7]+z*33,z*24+[6/7]+z*67,d+[1]+z*66,z*26+[1]+z*65,z*27+[3/8]+e+[3/17]+d+[1/2]+z*6,z*16+[9/14]+c+[27/32]+z*56,b+[9/14]+c+[27/32]+z*57,c+[5/14]+z*8+[5/8]+d+[1/2,0,0,5/11]+z*24+[5/16]+a]);v=vector(z*23+[5]+z*14+[5]+z*53);L=[1,2,2,4,6,6,8,10]
if n<9:return L[n-1]
Q=T
for i in[1..n-9]:Q=Q*T
return sum(Q*v)
```
E.g., `[f(n) for n in [1..50]]` produces
```
[1, 2, 2, 4, 6, 6, 8, 10, 14, 20, 26, 34, 46, 62, 78, 102, 134, 176, 226, 302, 408, 528, 678, 904, 1182, 1540, 2012, 2606, 3410, 4462, 5808, 7586, 9898, 12884, 16774, 21890, 28528, 37158, 48410, 63138, 82350, 107312, 139984, 182376, 237746, 310036, 403966, 526646, 686646, 894810]
```
] |
[Question]
[
For those who are not familiarized with the [Pea Pattern](http://en.wikipedia.org/wiki/Pea_pattern), it is a simple mathematical pattern.
**There are multiple variations of this pattern, but we will focus in one:**
>
> Ascending Pea Pattern
>
>
>
It looks like this:
```
1
11
21
1112
3112
211213
...
```
It seems really hard to get the following line, but it is really easy. The way to get the next line is by counting the number of times a digit have repeated on the previous line (start counting with the lowest, to largest):
```
one
one one
two ones
one one, one two
three ones, one two
two ones, one two, one three
...
```
**Requirements/Rules:**
* We will start at `1`
* It will be a snippet
* There must be a way to specify the number of lines generates (e.g `5`
will give the first 5 lines)
* The code should be as *short* as possible
* It must start counting from lowest to largest (the Ascending
variation)
[Answer]
# APL, 32 characters
```
⍪⌽({⍵,⍨,/{⌽⍵,+/⍵⍷d}¨⍳⌈/d←⊃⍵}⍣⎕)1
```
This generates lines starting from 0 (i.e. `0` generates `1`, `1` generates `1` followed by `1 1`, etc.), as specified by user input. I used Dyalog APL for this, and `⎕IO` should be set to its default of 1.
Example:
```
⍪⌽({⍵,⍨,/{⌽⍵,+/⍵⍷d}¨⍳⌈/d←⊃⍵}⍣⎕)1
⎕:
0
1
⍪⌽({⍵,⍨,/{⌽⍵,+/⍵⍷d}¨⍳⌈/d←⊃⍵}⍣⎕)1
⎕:
13
1
1 1
2 1
1 1 1 2
3 1 1 2
2 1 1 2 1 3
3 1 2 2 1 3
2 1 2 2 2 3
1 1 4 2 1 3
3 1 1 2 1 3 1 4
4 1 1 2 2 3 1 4
3 1 2 2 1 3 2 4
2 1 3 2 2 3 1 4
2 1 3 2 2 3 1 4
```
Once I get some more time, I'll write up an explanation. ⍨
[Answer]
## Python (2.x), 81 80 characters
```
l='1'
exec"print l;l=''.join(`l.count(k)`+k for k in sorted(set(l)))\n"*input()
```
All tips or comments welcome!
```
usage: python peapattern.py
15 # enter the number of iterations
1
11
21
1112
3112
211213
312213
212223
114213
31121314
41122314
31221324
21322314
21322314
21322314
```
[Answer]
## Perl, 83
I'm pretty sure some Perl guru could outdo this, but here goes:
```
$_++;$n=<>;for(;$n--;){print$_.$/;$r='';$r.=length($&).$1 while(s/(.)\1*//);$_=$r;}
```
Expanded:
```
$_++;$n=<>;
for(;$n--;)
{
print $_.$/;
$r='';$r .= length($&).$1 while (s/(.)\1*//); # The magic
$_=$r;
}
```
Number of rows is passed in via STDIN.
[Answer]
## J, 60 46 39 26 characters
```
1([:,(#,{.)/.~@/:~)@[&0~i.
```
**Edit 3**: Came up with a much nicer way of expressing this.
```
1([:;[:|."1[:/:~~.,.[:+/"1[:~.=)@[&0~i.
```
**Edit 2**: Finally found a way to move the argument to the end of the sequence and get rid of the unnecessary assignment stuff.
Previously:
```
p=.3 :'([:,[:|."1[:/:~~.,.[:+/"1[:~.=)^:(i.y)1
```
**Edit 1**: Fixes the output which should be `y` rows rather than the `y`th row. Also shortens things a bit. Shame about the `0`s, can't seem to get rid of the damn things.
Usage:
```
1([:,(#,{.)/.~@/:~)@[&0~i. 1
1
1([:,(#,{.)/.~@/:~)@[&0~i. 6
1 0 0 0 0 0
1 1 0 0 0 0
2 1 0 0 0 0
1 1 1 2 0 0
3 1 1 2 0 0
2 1 1 2 1 3
1([:,(#,{.)/.~@/:~)@[&0~i. 10
1 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0
2 1 0 0 0 0 0 0
1 1 1 2 0 0 0 0
3 1 1 2 0 0 0 0
2 1 1 2 1 3 0 0
3 1 2 2 1 3 0 0
2 1 2 2 2 3 0 0
1 1 4 2 1 3 0 0
3 1 1 2 1 3 1 4
```
Admittedly the usage is uglier now, but prettiness isn't the name of the game here...
[Answer]
## Haskell, 116
```
import Data.List
main=interact(unlines.map(show=<<).($iterate((>>=
\x->[length x,head x]).group.sort)[1]).take.read)
```
Usage:
```
$ runhaskell pea.hs <<< 15
1
11
21
1112
3112
211213
312213
212223
114213
31121314
41122314
31221324
21322314
21322314
21322314
```
[Answer]
## Common Lisp, 140 characters
```
(defun m(x)
(labels((p(l n)
(if(= 0 n)
nil
(cons l
(p(loop for d in(sort(remove-duplicates l)#'<)
append(list(count d l)d))
(1- n))))))
(p'(1) x)))
```
This is Lisp, so the function returns a list of lists. (m x) generates X sublists.
[Answer]
### Mathematica, 70
```
NestList[FromDigits@TakeWhile[DigitCount@#~Riffle~Range@9,#>0&]&,1,#]&
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 11 bytes (Feedback appreciated)
```
1ṢŒrUFƲСṖY
```
[Try it online!](https://tio.run/##AR4A4f9qZWxsef//MeG5osWSclVGxrLDkMKh4bmWWf///zU "Jelly – Try It Online")
```
1ṢŒrUFƲСṖY
1 Ʋ starting with 1, run these 4 links...
ṢŒr Ṣort the list and get the Œrun-length encoding of it,
U reverse each member of the RLE list (so it goes [repetitions, digit] instead of [digit, repetitions]),
F and Flatten the RLE list-of-lists to just a list of digits, which is the next number.
С do that (input) number of times,
ṖY Ṗop the last line off the output (an extra line is always calculated) and then print the numbers, separated by newlines.
```
] |
[Question]
[
What is the shortest regular expression equivilant to the following?
```
ENERO|GENER|GENNAIO|IANUARI|IANUARII|IONAWR|JAANUARIL|JANAIRU|JANAR|JANNEWARIS|JANUAR|JANUARI|JANUARIE|JANUARO|JANUARY|JANUWALE|JANVIER|JANVYE|JENUWARI
```
The shortest regex, in bytes, wins.
If you are worried about what flavor of regex we are using, then be the first one to edit my question, and you can have a link to a description of the specific regex flavor of your choice. Please choose a mainstream regex flavor, nothing too esoteric. `*` should mean `zero or more`. `+` should be `one or more` and so on and so forth.
[Answer]
### Python `re` module, 104 ~~110~~ bytes
-6 based on Neil's comment
```
JENUWARI|JA(N(VYE|VIER|UWALE|UAR(IE?|Y|O)?|NEWARIS|AIRU|AR)|ANUARIL)|IONAWR|IANUARII?|GEN(NAIO|ER)|ENERO
```
[Answer]
# 104 bytes
```
ENERO|GEN(ER|NAIO)|IANUARII?|IONAWR|JAANUARIL|JAN(AIRU|AR|NEWARIS|UAR(IE?|O|Y)?|UWALE|VIER|VYE)|JENUWARI
```
Should work with ~~any~~ most† regex styles, since I only use `|?()`, but below is a TIO for Java:
[Try it online.](https://tio.run/##ZVHRTsIwFH3nK2721AaFd3wgjalmBrtkEwgxPlSYMhwbWQuGePfts3MbtuOpveee23t6zk6e5O1u81WtU6kUPMsk@xkAHI7vabIGpaU2xylPNrA3LRLpIsk@X98krVkAH3lBTrIAHSt9L1U8yeJv6EgNBWA8hpfiqLfnSQt4XPAw8G668rGunVIw3@r7TMxZ6F8BNhIItrTeeGINZWZD5tVw7gLOiBB8aWYiB5v3OK6SFuB9JOgDKxdYspk7s/C5u2exsgm8HrEWG08fZKr@Le25GfS@eSWZ@65ZljUlbRvRWel4P8qPenQwkeo0I13QQ28C3rCrRnup19tYkaqJFo0GwkOsY6TYpTXFJiW8hGNugtSbkRlyYz6aDvH5FANc0Sn@OYW1O2gcoXhxomo0Unpn1JaDsvoF)
The last portion of the regex above could be one of these three for the same byte count:
* `JAANUARIL|JAN(AIRU|AR|NEWARIS|UAR(IE?|O|Y)?|UWALE|VIER|VYE)|JENUWARI` (the one used above)
* `JA(ANUARIL|N(AIRU|AR|NEWARIS|UAR(IE?|O|Y)?|UWALE|VIER|VYE))|JENUWARI` (`JA` combined for suffix of two options)
* `J(AANUARIL|AN(AIRU|AR|NEWARIS|UAR(IE?|O|Y)?|UWALE|VIER|VYE)|ENUWARI)` (`J` combined for suffix of three options)
Very curious if <104 bytes is even possible at this point. ü§î
†: Apparently not all. Thanks for the info *@ikkachu*.
[Answer]
# 110 bytes
```
J(A(N(U(AR([OY]|IE?)?|WALE)|V(IER|YE)|A(IRU|R)|NEWARIS)|ANUARIL)|ENUWARI)|I(ANUARI?I|ONAWR)|GEN(NAIO|ER)|ENERO
```
Which may be more easily read with designified whitespace like this:
```
J(
A(
N(
U(
AR(
[OY]
| IE?
)?
| WALE
)
| V(IER | YE)
| A(IRU | R)
| NEWARIS
)
| ANUARIL
)
| ENUWARI
)
| I(ANUARI?I | ONAWR)
| GEN(NAIO | ER)
| ENERO
```
This pattern works both in engines guaranteed to select the leftmost valid alternative in an `A|B|C` set, as well as in engines guaranteed to choose the longest valid alternative overall from that set.
Because of its alternation of literal strings, this pattern runs faster in engines with the [Aho–Corasick trie](https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm) optimization than in those lacking that feature.
[Answer]
# 104 bytes
```
ENERO|GEN(NAIO|ER)|IANUARII?|IONAWR|JA(ANUARIL|N(AIRU|AR|NEWARIS|UAR(IE?|O|Y|)|UWALE|VIER|VYE))|JENUWARI
```
Or, formatted more nicely (with insignificant whitespace):
```
ENERO |
GEN(
NAIO |
ER
) |
IANUARI I? |
IONAWR |
JA(
ANUARIL |
N(
AIRU |
AR |
NEWARIS |
UAR(
I E? |
O |
Y |
[the empty string]
) |
UWALE |
VIER |
VYE
)
) |
JENUWARI
```
[Answer]
# 104 bytes
```
ENERO|GEN(ER|NAIO)|IANUARII?|IONAWR|JA(ANUARIL|N(UWALE|VIER|VYE|UAR(IE?|O|Y)?|NEWARIS|AIRU|AR))|JENUWARI
```
Spent way too long trying to find a shorter solution and am convinced it doesn't exist.
] |
[Question]
[
An intriguing [MathsSE question](https://math.stackexchange.com/q/4642059/357390) asked if there were large [N-queens](https://codegolf.stackexchange.com/q/133736/110698) solutions where [no three queens lie on a line](https://codegolf.stackexchange.com/q/203607/110698). That question's body included the unique 4×4 solution up to symmetries
```
. Q . .
. . . Q
Q . . .
. . Q .
```
and noted that there are no solutions for 5×5 to 7×7 because of knight lines. However, [joriki](https://math.stackexchange.com/users/6622/joriki) over there then wrote [some code](https://github.com/joriki/math/blob/master/info/joriki/math/stackexchange/Question4642059.java) and found solutions from 8×8 to 16×16, counting all of them in the process:
$$\begin{array}{c|cc} N&4&5&6&7&8&9&10&11&12&13&14&15&16\\\hline \text{up to symmetries}&1&0&0&0&1&4&5&12&53&174&555&2344&8968\\ \text{all}&2&0&0&0&8&32&40&96&410&1392&4416&18752&71486 \end{array}$$
I find these restricted solutions quite interesting. Here is a 40×40 solution:
```
. . . . . . . . . . Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . Q . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . Q . . . . . . . . . . .
Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . Q . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . Q . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Q . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Q . . . . . . . . . .
. . . . . . . . . . . . . . . . . Q . . . . . . . . . . . . . . . . . . . . . .
. . . . . . Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Q . . . . .
. . . . . . . . . . . . . Q . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Q . . . .
. . . . . . . . . . . . . . . . . . Q . . . . . . . . . . . . . . . . . . . . .
. . . . . Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . Q . . . . . . . . . . . . . . . . .
. . . . . . . . . . . Q . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Q . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Q .
. . . . . . . . . . . . . . Q . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Q . .
. . . . . . . . . . . . . . . . . . . . . . . . . . Q . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Q . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Q
. . Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . Q . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . Q . . . . . . . . . . . . . . .
. . . Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Q . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . Q . . . . . . . . . . . . . .
. . . . . . . . . Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . Q . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Q . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . Q . . . . . . . . . . . .
. . . . Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . Q . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . Q . . . . . . . . . . . . . . . . . . . .
```
But my formulation of the problem as an integer linear program takes some time. I'd like to see results faster.
## Task
Write the [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") that when given an integer \$N\ge8\$ (handling lesser numbers is optional) outputs any \$N\$-queens solution that also has the no-3-in-line property. Although it is not proven that solutions exist for all \$N\ge8\$, your code may assume that they do.
The code will be run on my Lenovo ThinkPad E14 Gen 2 laptop with an 8-core Intel Core i7 processor running Ubuntu 22.10. A program's score is the highest \$N\$ for which a solution is returned in **2 minutes**. You may output in any reasonable format, including graphical formats as above and as a list with the queen indices for each row (the above solution corresponds to the 0-indexed list `[10, 21, 28, 0, 7, 12, 15, 36, 29, 17, 6, 34, 13, 35, 18, 5, 22, 11, 1, 8, 32, 38, 14, 37, 26, 30, 39, 2, 16, 24, 3, 31, 25, 9, 20, 33, 27, 4, 23, 19]`).
I encourage you to post the results for your code on your own machine for my reference.
[Answer]
# [MiniZinc](https://www.minizinc.org/), N = 70
```
int: n;
array [1..n] of var 1..n: q;
predicate
noattack(int: i, int: j, var int: qi, var int: qj) =
qi != qj /\
qi + i != qj + j /\
qi - i != qj - j;
constraint
forall (i in 1..n, j in i+1..n) (
noattack(i, j, q[i], q[j])
);
predicate
no3inline(int: i, int: j, int: k, var int: qi, var int: qj, var int: qk) =
i * (qk - qj) + j * (qi - qk) + k * (qj - qi) != 0;
constraint
forall (i in 1..n, j in i+1..n, k in j+1..n) (
no3inline(i, j, k, q[i], q[j], q[k])
);
solve :: int_search(q, first_fail, indomain_random)
satisfy;
```
Adapted from <https://github.com/MiniZinc/minizinc-benchmarks/blob/master/queens/queens.mzn>.
Solution for \$N = 70\$ in less than 9s on i5-6300U.
It is worth noting that the time required does not always increase when increasing \$N\$. For example, for \$N = 69\$, 2 minutes were not enough.
---
The goal of this answer is not to show off my skills, but the power of MiniZinc and [constraint programming](https://en.wikipedia.org/wiki/Constraint_programming) in general.
[Answer]
# [Python 3 (PyPy)](http://pypy.org/), N = 565
```
import math
import random
import multiprocessing
import itertools
import argparse
def line(x0, y0, x1, y1):
a = y0 - y1
b = x1 - x0
gcd = math.gcd(a, b)
a //= gcd
b //= gcd
if a < 0:
return -a, -b
elif a == 0:
if b < 0:
return 0, -b
return 0, b
return a, b
def num_conflicts(l, x, y):
lines = {(1,1),(1,-1),(1,0),(0,1)}
n = 0
for x1, y1 in enumerate(l):
if x1 == x: continue
l1 = line(x, y, x1, y1)
if l1 in lines:
n += 1
else:
lines.add(l1)
return n
def greedy(n):
l = []
for x in range(n):
z = [num_conflicts(l, x, y) for y in range(n)]
v = min(z)
y = random.choice([y for y, k in enumerate(z) if k == v])
l.append(y)
return l
def fix_row(n, l, x):
y0 = l[x]
nc = num_conflicts(l, x, y0)
if nc == 0: return 1
z = [num_conflicts(l, x, y) if y != y0 else nc for y in range(n)]
v = min(z)
options = [y for y, k in enumerate(z) if k == v]
if options == [y0]: return -1
y = random.choice(options)
l[x] = y
def solve(t):
s, n = t
random.seed(s)
l = greedy(n)
for i in range(3*n):
outcomes = {fix_row(n, l, x) for x in range(n)}
if outcomes == {1}:
return l
if None not in outcomes:
break
def full(n):
return next(filter(None, map(solve, enumerate(itertools.repeat(n)))))
def full_mp(n, p):
with multiprocessing.Pool(p) as p:
return next(filter(None, p.imap_unordered(solve, enumerate(itertools.repeat(n)))))
def main():
parser = argparse.ArgumentParser(
prog = "queensthree",
description = "Finds solution for the no-three-in-a-line n-queens problem"
)
parser.add_argument('n', help='number of rows/columns', type=int)
parser.add_argument('-j', default=1, help='number of processes to use (defaults to 1)', type=int)
args = parser.parse_args()
if args.j > 1:
l = full_mp(args.n, args.j)
else:
l = full(args.n)
print(all(num_conflicts(l, x, l[x]) == 0 for x in range(args.n)))
print(l)
if __name__ == '__main__':
main()
```
[Try it online! (N=327)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aXHeINGlYR9kEr0y1bXc330Tq6pPgtJUIYKfmcg4fXOwgh7e8MSRjZHkVAMZFrXinW8rjFuXdcomLpexzyies7n892nz/8C "Python 3 (PyPy) – Try It Online")
Uses the [Min-conflicts algorithm](https://en.wikipedia.org/wiki/Min-conflicts_algorithm). The gist of the algorithm is to start with a random arrangement of the queens, and repeat the step of choosing a random queen that is in conflict (in check or in a line with two other queens), and move it to a square in the same row with the least conflicts. After a number of steps, if a solution hasn't been found, start over with a different random arrangement.
Because of how the algorithm works, it occasionally gets lucky and finds a solution on the first try (which is what happened with N=565, the previous solution that could be found in 2 minutes was for N=532).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), N=20
N=20 in less than a min on my old laptop
```
queens=20;
put[n_,m_,q_]:=(pl={n,m};s[[n,m]]="X";{i,j}=pl;
While[i>1&&j>1,i--;j--;s[[i,j]]++];
{i,j}=pl;
While[i<q&&j<q,i++;j++;s[[i,j]]++];
{i,j}=pl;
While[i<q&&j>1,i++;j--;s[[i,j]]++];
{i,j}=pl;
While[i>1&&j<q,i--;j++;s[[i,j]]++];
{i,j}=pl;
While[i<q,i++;s[[i,j]]++];
{i,j}=pl;
While[i>1,i--;s[[i,j]]++];
{i,j}=pl;
While[j<q,j++;s[[i,j]]++];
{i,j}=pl;
While[j>1,j--;s[[i,j]]++];)
While[(t=0;
qu=queens;
While[t!=qu,s=Table[0,{i,qu},{j,qu}];
put[RandomInteger[{1,qu}],RandomInteger[{1,qu}],qu];
t=1;
While[!FreeQ[s,0],
pos=Position[s,0];
put[First@#,Last@#,qu]&[RandomChoice@pos];t++];];
posi=Position[s,"X"];
Select[(Last@#/First@#&[First@Differences[#]])&/@#&/@(Partition[#,2,1]&/@Subsets[posi,{3}]),SameQ@@#&])!={}]
s=s/. a_/;IntegerQ@a:>".";
```
[Try it online!](https://tio.run/##jZLfa8IwEMff@1f4A4rF09oN9mCMFDYGgz3oHGwQgkQXZ4ptbZM@lf7t3aVWGNuYPoQjd9/7fHNJYmH2MhZGbUWdFVImmgZ3pD4WhiVriNeQrfmUDo4HWiYQV0QzhpFz2nvvkVJBVNHjgThve3WQTM0D143mAajRiES4UI0SzodDTpxf6lmG6lkGajgkEa4r1JZt1RfZzUks257kCnaDvYRsaP@KrOVFOzvFzwk8x2mrA0MnxMkKenqOc5PpYgI0fRUb3E0AoVlRQRnZgCb2xV5E8pHGT4mRnzJnZdCU4O9sVmCTocGZ333MpVwyDRMOzjHVdJFqZVSaNKkT/1Hl2oR9eBZNQITbet7vU7WVIfZxYuw8tgMB3yn4YzC7kge5NWxwYvgt0m3ZD2q3k7lMtlKzPuee62PNDwcLkZsTpw83EHDMrYqNlkYzawPlbcU9WIlYLkPs4F6XlhXHO9VU@@OOWPukvYBlKKbz3rhH6kWuEtPxQ13XXw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Rust, N=128
Adapted from [@gsitcia's answer](https://codegolf.stackexchange.com/a/258854/110802)
[Try it online!(N=128)](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c78b3818766bbd155bb3e8d4db99dbf5)
```
use std::collections::HashSet;
// use std::env;
use std::iter;
use std::sync::mpsc;
use std::thread;
use rand::rngs::StdRng;
fn gcd(a: i32, b: i32) -> i32 {
if b == 0 {
a.abs()
} else {
gcd(b, a % b)
}
}
fn line(x0: usize, y0: usize, x1: usize, y1: usize) -> (i32, i32) {
let mut a = (y0 as i32) - (y1 as i32);
let mut b = (x1 as i32) - (x0 as i32);
let gcd_val = gcd(a, b);
a /= gcd_val;
b /= gcd_val;
if a < 0 {
(-a, -b)
} else if a == 0 {
if b < 0 {
(0, -b)
} else {
(0, b)
}
} else {
(a, b)
}
}
fn num_conflicts(l: &[usize], x: usize, y: usize) -> usize {
let mut lines = HashSet::new();
let mut n = 0;
for (x1, &y1) in l.iter().enumerate() {
if x1 == x {
continue;
}
let l1 = line(x, y, x1, y1);
if lines.contains(&l1) {
n += 1;
} else {
lines.insert(l1);
}
}
n
}
fn greedy(n: usize) -> Vec<usize> {
let mut l = Vec::with_capacity(n);
for x in 0..n {
let z: Vec<usize> = (0..n).map(|y| num_conflicts(&l, x, y)).collect();
let v = *z.iter().min().unwrap();
let options: Vec<usize> = z
.iter()
.enumerate()
.filter_map(|(y, &k)| if k == v { Some(y) } else { None })
.collect();
let y = options[rand::random::<usize>() % options.len()];
l.push(y);
}
l
}
fn fix_row(n: usize, l: &mut [usize], x: usize) -> Option<bool> {
let y0 = l[x];
let nc = num_conflicts(l, x, y0);
if nc == 0 {
return Some(true);
}
let z: Vec<usize> = (0..n).map(|y| if y != y0 { num_conflicts(l, x, y) } else { nc }).collect();
let v = *z.iter().min().unwrap();
let options: Vec<usize> = z.iter().enumerate().filter_map(|(y, &k)| if k == v { Some(y) } else { None }).collect();
if options == [y0] {
return Some(false);
}
let y = options[rand::random::<usize>() % options.len()];
l[x] = y;
None
}
fn solve(t: (usize, usize)) -> Option<Vec<usize>> {
let (s, n) = t;
let _rng: StdRng = rand::SeedableRng::seed_from_u64(s as u64);
let mut l = greedy(n);
for _ in 0..3 * n {
let outcomes: HashSet<Option<bool>> = (0..n).map(|x| fix_row(n, &mut l, x)).collect();
let all_true = outcomes.iter().all(|outcome| outcome == &Some(true));
if all_true {
return Some(l);
}
if !outcomes.contains(&None) {
break;
}
}
None
}
fn full(n: usize) -> Vec<usize> {
iter::repeat(n)
.enumerate()
.filter_map(solve)
.next()
.unwrap()
}
fn full_mp(n: usize, p: usize) -> Vec<usize> {
let (tx, rx) = mpsc::channel();
let tasks = iter::repeat(n).take(p).enumerate();
for task in tasks {
let tx = tx.clone();
thread::spawn(move || {
let result = solve(task);
if let Some(solution) = result {
tx.send(solution).unwrap();
}
});
}
rx.recv().unwrap()
}
fn main() {
// let args: Vec<String> = env::args().collect();
// if args.len() < 2 {
// eprintln!("Usage: {} n [-j processes]", args[0]);
// std::process::exit(1);
// }
// let n: usize = args[1].parse().expect("n must be an integer");
// let processes: usize = if args.len() >= 4 && args[2] == "-j" {
// args[3].parse().expect("processes must be an integer")
// } else {
// 1
// };
let n: usize = 128;
let processes: usize =1;
let l = if processes > 1 {
full_mp(n, processes)
} else {
full(n)
};
println!(
"{}",
l.iter()
.enumerate()
.all(|(x, &y)| num_conflicts(&l, x, y) == 0)
);
println!("{:?}", l);
}
```
] |
[Question]
[
This challenge is one of the two challenges which were planned for [Advent of Code Golf 2021](https://codegolf.meta.stackexchange.com/q/24068/78410), but didn't fit into the 25-day schedule.
Related to [AoC2020 Day 24](https://adventofcode.com/2020/day/24), Part 2.
---
Given a binary configuration on a hexagonal grid, output the next generation of Hexagonal Game of Life using AoC rules:
* A living cell survives if it has one or two living neighbors. Otherwise, it turns into a dead cell.
* A dead cell becomes alive if it has exactly two living neighbors. Otherwise, it does not change.
A hexagonal grid can be input and output in any sensible 2D or 3D representation. The input grid has a shape of a regular hexagon. You can choose how to handle the borders: either expand it by one layer, or keep the input size. You can choose the values of alive and dead cells, but they must be consistent across input and output.
You may choose the two distinct values for the alive and dead cells in the input and output, and you may use the value for "dead" or the third value for the necessary padding.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Example I/O
An input representing the following grid
```
. . .
* . . *
* . * * *
* * * .
* . .
```
could be skewed to the right, giving
```
. . .
* . . *
* . * * *
* * * .
* . .
```
or, as a Python 2D array using 0 and 1 (with zero padding),
```
[[0, 0, 0, 0, 0],
[0, 1, 0, 0, 1],
[1, 0, 1, 1, 1],
[1, 1, 1, 0, 0],
[1, 0, 0, 0, 0]]
```
The expected output for this input, if expanding by one layer, is
```
. . . .
. . . . .
* * * . * *
. * . . . * .
* . . . . .
* * . . .
. . . .
```
or, in the same representation,
```
[[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 1, 1],
[0, 1, 0, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]]
```
As written above, you're free to choose to not expand the borders, in which case the result would be
```
. . .
* * . *
* . . . *
. . . .
* . .
[[0, 0, 0, 0, 0],
[0, 1, 1, 0, 1],
[1, 0, 0, 0, 1],
[0, 0, 0, 0, 0],
[1, 0, 0, 0, 0]]
```
Example code is [here](https://tio.run/##dVLbboMwDH3nK/wyQbisBF6mqnwJQxWjoY0EoUqo1n09s0Mobbc@OfaxfXwcn3/G06DyaWr10IOu1QGN7M@DHq0n1egZeRBQQO6dxBVtWTogSGPOQLZACQnfFTpqdkUeBrPPQHRGQArtoKEBqajhUVg0zBCvLKL/Q7yzJgIkZN5BtND2o0VjoNDWA1P4vveyHhPAQFSAD35Yf5lAJ8tQDKFXA1HZqgd2BaAiMqumrev7HvoljlLqqmyqCiJiupF@KnxrMV60AuOkPCqYVdXKBE5Ph4vthJoVU0pmN51WYdBFGSMG8tDo4Zuc1G0PPRSCBUuKK7BN9kpcx4dGtmi/ane5T4uk6PbvopYw9HQPNOSsn0JKyOMJo@bSBxbppcICHvf1FQ9FJzySbzlj1RPQELDZEGLp5ErH4w/GIEE2IljkzJTIxOmrAhqlwCPDk1xmKAB1YiuH8TsMe5c8hqxajtOD26Vl7M6xVOz2i0vk6TNRxe0TGZumXw).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 73 bytes
```
CellularAutomaton[{56,{2,{{0,2,2},{2,1,2},{2,2,0}}},{1,1}},#~ArrayPad~1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@985NSenNCexyLG0JB8onJ8XXW1qplNtpFNdbaBjpGNUC2IbQmkjHYPaWiDLUMcQSCnXORYVJVYGJKbUGcaq/Q8oyswriU6LBmlUQKBaHQWQgCFMwBAkAOEZQhBUwBCuCKECZkZtbOx/AA "Wolfram Language (Mathematica) – Try It Online")
Takes a 2D array (skewed to the right) as input.
---
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/) + my [LifeFind](https://github.com/AlephAlpha/LifeFind) package, 71 bytes
```
<<Life`
CellularAutomaton[{RuleNumber@"B2/S12H",2,{1,1}},#~ArrayPad~1]&
```
Sorry, no TIO for this one.
Takes a 2D array (skewed to the left) as input.
There is a convenient `CA` function in this package, but it automatically removes the surrounding zeroes.
The main purpose of this package is to find interesting patterns in cellular automata. Here are something I found:
```
A period 2 oscillator:
. * * .
* . . => . . *
. * * .
A period 3 oscillator:
. * . * . * . * .
* . . * => . . . . => * * * *
. * . * . * . * .
Another period 3 oscillator:
* . * . * . * . *
. . . . * . . * . * * .
* . . . * => . . . . . => * * . * *
. . . . * . . * . * * .
* . * . * . * . *
A period 4 oscillator:
* . * . * . * . * * . *
. . . . * . . * . * * . . * * .
* . . . * . . . . . * . . . * . * * * .
. . . . . . * . . . . * . . . . . . . * . . * .
* . . . . . * => . . . . . . . => * * . . . * * => * * * . * * *
. . . . . . * . . . . * . * . . * . . * * * * .
* . * . * . * . * . * . . . * * . . . *
A period 4 spaceship:
. * . * . . . . . . . . * . . . . . . . * . * . . . . . . * . * . . . .
. . . * * * . . . . . * . . * . . . . . . * * * * . . . . . . . . * . .
. . . * * . . . . . . . . . * . . . . . * . * * . . . . . . . . . * . .
. . * . . . . . . . * * . . . . . . . * * * . . . . . * . . * . . . . .
. * . * . . . . . . * . * . . . . . * * . . * . . . . . . . . * . . . .
. . * * * * . . . . . . . . * . . . . * . . * * * . . . . . . . . * . .
. * * * * . . . . * . . . . * . . . * * . . * * . . . . . . * . . * . .
. * * . . . . * . . * . . . . * * . . * . . . . . . * . . . . * . . * *
. . . * . . * . . * . . . * * * * . * . * . * . . * . * . . . * * * * *
. * * . . * . . . . * * * * . * . . . . . . * . * . . . . . * * . . * .
. * . . . . . . . * * * . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . => . * * . . . . . . => . . . . . . . . . => . . . . . . . . .
. * . . . . . . . * * * . . . . . . . . . . . . . . . . . . . . . . . .
. * * . . * . . . . * * * * . * . . . . . . * . * . . . . . * * . . * .
. . . * . . * . . * . . . * * * * . * . * . * . . * . * . . . * * * * *
. * * . . . . * . . * . . . . * * . . * . . . . . . * . . . . * . . * *
. * * * * . . . . * . . . . * . . . * * . . * * . . . . . . * . . * . .
. . * * * * . . . . . . . . * . . . . * . . * * * . . . . . . . . * . .
. * . * . . . . . . * . * . . . . . * * . . * . . . . . . . . * . . . .
. . * . . . . . . . * * . . . . . . . * * * . . . . . * . . * . . . . .
. . . * * . . . . . . . . . * . . . . . * . * * . . . . . . . . . * . .
. . . * * * . . . . . * . . * . . . . . . * * * * . . . . . . . . * . .
. * . * . . . . . . . . * . . . . . . . * . * . . . . . . * . * . . . .
```
[Answer]
# JavaScript, 86 bytes
```
a=>a.map((r,y)=>r.map((c,x)=>((g=i=>i&&~~a[(i/3|0)+y-1]?.[i%3+x-1]+g(i-1))(7)&~c)==2))
```
[Try it online!](https://tio.run/##bZDBboMwEETvfMVeineFcZtGVaRUph/Ro8vBIoAcUUCGVESl/Do1hKglii@jGb9dy3PUX7pJrKnbsKwO6ZjJUctIi09dI1p@JhnZi0l45wxiLo2MjO8PA2qF5nHbP1FwDjdx33//kDIP26BzLsjRhBsi3JE/JCTlM9GYVGVTFakoqhyZ@igZBJCh8jwABdPhsEimiya9kZj/51p7ugWWcOFWwOJWsuLWcp2a37q3bwX8cV5Mc1sWZATMTU0/VEIIG19a7DgYmi6xAymhPBUFvAFjsIfOoYyRqPXhvdW2xReaEu6iY2VKZMDmIOauuGu2RIxex18 "JavaScript (Node.js) – Try It Online") (TIO link use `||{}` instead of `?.` which is not supported on older NodeJS.)
Input boolean matrix with holes as padding. Output in same format.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 33 bytes [SBCS](https://github.com/abrudz/SBCS)
```
({+/1↓¯1↓,⍵}⌺3 3∊¨2+0,¨⊢)(⌽0,⍉)⍣4
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=06jW1jd81Db50HoQqfOod2vto55dxgrGjzq6Dq0w0jbQObTiUdciTY1HPXsNgNKdmo96F5sAAA&f=y00sedQ24VHbRA0DBSjUBDINwUxDTQ0QwxAEQUxDiDhEFKKWK00hN7EEAA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
A partially tacit function that takes a 2D grid of booleans (0s and 1s) skewed to the right, and returns the next step with one cell expanded.
GoL body is mostly from [the APLcart entry](https://aplcart.info/?q=game%20of%20life), modified to make sure the region to be considered is hexagonal, the rules (2/12 instead of 3/23) are encoded correctly, and the entire grid is padded before running the GoL calculation. Padding is easier than not padding here, because otherwise we need to make sure the cells outside the valid hexagonal region are zero.
The hexagonal region trick is what I came up with when AoC2020 day 24 was ongoing. The orientation of the entire grid is part of the trick; this works by looking at a 3x3 square sub-grid and removing the top left and bottom right cells from consideration. This is easier than the other orientation because it suffices to flatten the array and drop the first and the last element in this case, instead of manual reshape or indexing.
```
. o o
o O o => . o o o O o o o .
o o .
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes
```
⊞υωWS⊞υιEΦυκ⭆ι⎇⁼λ λ§.*›²↔⁻⁴⁻⊗№⭆³✂⁺ §υ⁺κνμ⁺⁵μ¹*⁼λ*
```
[Try it online!](https://tio.run/##TY5BbgIxDEX3OYWVlRMFpNJ2xaqCtmKBNFJ7gTBEnQiToZmk0NOnzjCIxovvPH/5u@1sbHtLpTR56DAbOKulOHeeHOAmnHL6SNGHL1QKbg7PjoZhwq094Zun5GLlB2Xg6q7cG/h0Mdj4i6/f2dKAZECCZBM3L2kT9u6Ccq6lgffobF2y4MFu6Cknh1sf8oBPBq7Nus87cntc9ZmD7zGPnEm@ddgQuySAvC/nm0Z6MBCU4uDjBJ655e9DZVLLKv9urOD2lqUAzMcSoEfVIPQotcSkdTzNRZn90B8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation:
```
⊞υω
```
Push a dummy entry to the predefined empty list to prevent wrapping between the top and bottom.
```
WS⊞υι
```
Input the grid.
```
EΦυκ⭆ι
```
Map over the grid, excluding the dummy entry.
```
⎇⁼λ λ
```
Leave spaces as-is.
```
§.*›²↔⁻⁴
```
Output `.` or `*` depending on the number of live neighbours. There are three cases which result in a `*`; live with one live neighbour, dead with two live neighbours, and live with two live neighbours. When you add the liveness of the cell to double the number of neighbours, these three cases are the only cases to map to `3`, `4` and `5`, therefore the absolute difference from `4` must be less than `2` to output a `*`.
```
⁻⊗№⭆³✂⁺ §υ⁺κνμ⁺⁵μ¹*⁼λ*
```
Count the neighbours by extracting a `3×5` rectangle from the grid centred on the current cell. (Two spaces are prefixed to the grid to avoid negative slice offsets.) Since this already includes the liveness of the current cell, it needs to be subtracted from the double count to produce the value in the range `3-5` from above.
] |
[Question]
[
## Backstory
I was fiddling around with the [Evolution of Trust](https://ncase.me/trust "*trust* me, this is a tooltip (pun intended)") and thought of this.
**Warning**: I recommend you go [check it out first](https://ncase.me/trust "*trust* me, this is a tooltip (pun intended)") before attempting this challenge.
## Summary for people who haven’t played
A quick summary of what it says [on the site](https://ncase.me/trust "*trust* me, this is a tooltip (pun intended)"): there is a machine. If you put in one coin, your **opponent** gets **three** coins (and vice versa). You can either Cooperate (put in a coin) or Cheat (don't put in a coin).
## Challenge
Given the name of a strategy (`copycat`, `alwayscheat`, `alwayscooperate`, `grudger` or `detective`) and the number of rounds, return/output a list of truthy (Cooperate) and falsey (Cheat) values that, when put against that strategy, will give you the maximum possible amount of coins. (I'm using Y for cooperate and N for cheat in my examples)
For clarification, check the **Input and Output** section.
## Quick info for people who have played
The amount of rounds is given in the input. There are no mistakes, and the rewards for Cooperating/Cheating are the same as [the site](https://ncase.me/trust "*trust* me, this is a tooltip (pun intended)") - see the image below.

Yes, this is basically a Prisoner's Dilemma - [Nicky Case](http://ncase.me/) says this in the “[feetnotes](https://ncase.me/trust/notes/)” of the game.
Also, "Cheat" is basically the same as Defect.
## The characters
* Copycat `copycat`
* Always Cooperate `alwayscooperate`
* Always Cheat `alwayscheat`
* Grudger `grudger`
* Detective `detective`
## The characters' strategies from [the site](https://ncase.me/trust "*trust* me, this is a tooltip (pun intended)")
* Copycat: Hello! I start with Cooperate, and afterwards, I just copy whatever you did in the last round. *Meow*
* Always Cheat: *the strong shall eat the weak* (always cheats)
* Always Cooperate: Let's be best friends! <3 (always cooperates)
* Grudger: Listen, pardner. I'll start cooperatin', and keep cooperatin', but if y'all ever cheat me, **I'LL CHEAT YOU BACK 'TIL THE END OF TARNATION.** (cooperates until you cheat once, then cheats you back for the rest of the game)
* Detective: First: I analyze you. I start: Cooperate, Cheat, Cooperate, Cooperate. If you cheat back, I'll act like Copycat. If you never cheat back, I'll act like Always Cheat, to exploit you. Elementary, my dear Watson.
## Input and Output
Input is the name of the strategy and the amount of rounds in any order you specify, in a list, or a space-separated string.
Output is a list of truthy (Cooperate) and falsey (Cheat) values that, when put against the strategy, gives you the most amount of points.
## Test cases
```
"grudger 3" => "YYN" or [<2 truthy values>, falsey]
"detective 5" => "NNNYN" or [<3 falsey values,> truthy, falsey]
"alwayscheat 7" => "NNNNNNN" or [<7 falsey values>]
"alwayscooperate 99" => <insert 99 N's here> or [<99 falsey values>]
"copycat 7" => "YYYYYYN" or [<6 truthy values>, falsey]
"detective 4" => "NNNN" (4 N's) or [<4 falsey values>]
"alwayscheat 999" => 999 N's or [<999 falsey values>]
"grudger 1" => "N" or [falsey]
```
Easy copy paste:
```
grudger 3
detective 5
alwayscheat 7
alwayscooperate 99
copycat 7
detective 4
alwayscheat 999
grudger 1
```
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer wins, tiebreaks sorted by time(stamp) created
* Standard loopholes are not allowed, unless they are creative (e.g. asking for list input and using the fact that it is a *list* to shorten your code). No extra points are given for this
>
> WD
>
>
>
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
An OP accepted, but somewhat rule-bending, 13 byter since all the integers are now wrapped in lists - so it only works if we may assume any truthy/falsey operator will vectorise - that can be fixed for 1 byte for a different 14 to my original, e.g. add `F`.)
```
M_5+Ṡ$×<¥ⱮḊ;0
```
A dyadic Link that accepts the opponent classification on the left and the number of turns to play on the right and yields a list of wrapped integers (non-zeros are truthy in Jelly, while zeros are falsey).
**[Try it online!](https://tio.run/##ASwA0/9qZWxsef//TV81K@G5oCTDlzzCpeKxruG4ijsw////J2RldGVjdGl2ZSf/NQ "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9833lT74c4FKoen2xxa@mjjuoc7uqwN/h9erv@oaU3io4a5kflAwi/rUeM@Lq7//6Oj1dOLSlPSU4vUdRSMY7l0otVTUktSk0syy1KBIqZgkcSc8sTK4uSM1MQSoJg5slh@fkFqUWIJSK2lJVgiOb@gMhlJIbJxJliMs4TqQzjDMJYrFgA "Jelly – Try It Online").
### How?
There are, for the purpose of our choices, only three classes of opponent here:
1. If we face `alwayscheat` or `alwayscooperate` we should always cheat
2. If we face `grudger` or `copycat` we should cooperate until our penultimate turn and then cheat on our final turn.
3. If we face `detective` we should cooperate from the fourth turn (if it is not our last turn) until our penultimate turn and then cheat on our final turn.
```
M_5+Ṡ$×<¥ⱮḊ;0 - Link: opponent, turns
M - maximal indices
-> alwayscheat:[5] alwayscooperate:[5] grudger:[3] copycat:[4] detective:[8]
^ ^ ^ ^ ^
_5 - subtract five
-> alwayscheat:[0] alwayscooperate:[0] grudger:[-2] copycat:[-1] detective:[3]
+Ṡ$ - add the sign of that (call this "category")
-> alwayscheat:[0] alwayscooperate:[0] grudger:[-3] copycat:[-2] detective:[4]
Ɱ - map (across turn in [1..turns]) with:
¥ - last two links as a dyad, f(category, turn)
< - (category) less than (turn)?
× - (category) multipied by (that)
Ḋ - dequeue
;0 - concatenate a zero
```
---
14: `OḢ%4C×4×<¥ⱮḊ;0`
And another 14: `OḢ%4ȯ7B¤Ṭo¥@’ṁ`
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Å0Dā4›Àā¤Ê)ICθè
```
First input is the amount of rounds, second input the strategy of the opponent.
Output is a list of 1s/0s.
[Try it online](https://tio.run/##AS8A0P9vc2FiaWX//8OFMETEgTTigLrDgMSBwqTDiilJQ864w6j//zEwCmRldGVjdGl2ZQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn2lckJx6P/DrQYuRxpNHjXsOtxwpPHQksNdmhHO53YcXvFf5396UWlKemqRgjFXSmpJanJJZlmqgilXYk55YmVxckZqYomCOYyXn1@QWpRYkqpgacmVnF9QmQyWRGgzQdFmCVQFM9wQAA).
**Explanation:**
There are three different output variations based on the input \$n\$:
* `detective`: \$N(\min(n-1,3))Y(n-4)N(1)\$
* `grudger`/`copycat`: \$Y(n-1)N(1)\$
* `alwayscheat`/`alwayscooperate`: \$N(n)\$
So in my program I create these three possible lists first; convert the string input to an index-integer; and use it to output the correct list of the three.
```
Å0 # Push a list with the first (implicit) input amount of 0s: [0,0,...,0,0]
D # Duplicate this list
ā # Push a list in the range [1, length] (without popping the list)
4› # Check for each whether it's larger than 4 (0 if <=4; 1 if >4)
À # Rotate it once left: [0,0,0, 1,1,...,1,1, 0]
ā # Push a list in the range [1, length] (without popping the list)
¤ # Get its last value (without popping)
Ê # Check for each that it's NOT equal to this integer: [1,1,...,1,1, 0]
) # Wrap all four lists on the stack into a list
I # Push the input-string
C # Convert it from a binary-string to an integer
θ # Only leave its final digit
è # Use that to 0-based modulair index into the list of lists
# (after which this list is output implicitly as result)
```
`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.
| String | `C` | `θ` | Modulair index | Resulting list |
| --- | --- | --- | --- | --- |
| detective | 21282 | 2 | 2 | `[0,0,0, 1,1,...,1,1, 0]` |
| grudger | 5893 | 3 | 3 | `[1,1,...,1,1, 0]` |
| copycat | 5607 | 7 | 3 | `[1,1,...,1,1, 0]` |
| alwayscheat | 87191 | 1 | 1 | `[0,0,...,0,0]` |
| alwayscooperate | 1397550 | 0 | 0 | `[0,0,...,0,0]` |
[Answer]
# [Python 2](https://docs.python.org/2/), ~~50~~ 48 bytes
```
lambda a,b:(hash(a)%5%4*[0]+[a>'b']*b)[:b-1]+[0]
```
[Try it online!](https://tio.run/##Zc2xboNADAbgPU/hJfJBQpW0iSqQ0i0d26VLRRl8YMI1lDuZowlPT0EZiNTJ8qffv13vK9s8DuXha6jpRxcEtNaJqqitFAXL/XIXpptsldILasxCHaSJjrYjbLLhUpma4UM6ThYAXvppADgxjVcYRREGMwDiw7c1jcJPBFPCFbhuGfANobQyrqaBUoWmcZ1XQTBd8jVn5@H4/noUsXJr18J0HlI8SVecWHANT9kixYI959788gj7Cai@UN/mFZMf6fmOrHUs5KdkHE@eW9fnc@y@ave/Kr4dzf@32R8 "Python 2 – Try It Online")
| name | `hash(name)` | `hash(name)%5%4` | `name>'b'` | pattern |
| --- | --- | --- | --- | --- |
| grudger | -2066041371107544871 | 0 | True | `N{0}Y{b-1}N` |
| detective | -4897940859603653632 | 3 | True | `N{3}Y{b-4}N` |
| alwayscheat | 5996996683077751943 | 3 | False | `N{3}N{b-4}N` |
| alwayscooperate | 6213961190923822520 | 0 | False | `N{0}N{b-1}N` |
| copycat | 8335118083446687010 | 0 | True | `N{0}Y{b-1}N` |
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~48~~ ~~44~~ 42 bytes
Based on OP's answer
```
->a,b{([p]*(~a.ord%4)+[a>?b]*b)[0,b-1]<<p}
```
[Try it online!](https://tio.run/##VYzNCoJAFIX38xR3UVQ2SlIRRjlv0D5E4o7eTLBmGMdM@nl1s0Ci5fnOd46pZNMet60bIpf3caRjZ/xCT5l0uJhMIwyFjB05iWZcun682ehnW5/ygiAjWzIA5CBhC4ODV@oitx3RlS1BuM6cd5TDMfoonlWHPPbOqO@P2@MGQuzXYvd0RiNGl7TNTJVmZGDOUrKU2PxKsGRY1NiUyYnQwqpPSmkyaAmCgCVKN8m3/M0Wf7Ogs/pz/w0 "Ruby – Try It Online")
`[p]*(~a.ord%4)` could be `[p]*3*a.sum[2]` or `[p]*(a.hex/74)` instead for the same length.
[Answer]
# Python 3, 45 bytes
```
lambda o,r:([len(o)<8]*3+[o>'c']*r)[:r-1]+[0]
```
[Try it online!](https://tio.run/##bY/BbsIwDIbP9CksLk6gnai6abQae4TdUcghS1PIVJIoDRt9@pKoQmPSDj74s/3ptxvDyZpq6naHqRfnz1aAzX1DWK8MsfRty1fVmtl3lMhXnrLGFyVfsw2ftHGXMMAOWLZgePSX9qg85lDxPIFWBSWD/lYRvcxI9D9iHORJiRDh6x9orVNehLRd1/NEWjfKx9VH5fN/yvp@@pum5BnPOushxo0Fc@omWzivTSDLoiiW9N4hPn1ZbQjuEXQHV1D9oAA/EJLhmu47Eg3x/TyZWMkppdMN "Python 3 – Try It Online")
The easiest way to group `detective` with `alwayscooperate` and `alwayscheat` was based on text length, while the easiest to group `detective` with `copycat` and `grudger` was alphabetically.
This might internally generate a list that is too long, but that gets trimmed down in the end.
[Answer]
# JavaScript (ES6), ~~42~~ 41 bytes
Expects `(strategy)(rounds)`. Returns a string of 0's and 1's.
```
(s,i=14)=>g=b=>--b&&[s>g&!s[++i>>1]]+g(b)
```
[Try it online!](https://tio.run/##ndLfaoMwFAbw@z1F5oVT1BVXtyLUPIL3Il7EePwzxEgSHT69izW2tKO07FwG8uP7DuebjERQ3vTS61gBcxnNlnCbyA/sCFdRHmHPy00zFbgyX0XqOA3GfpY5lZXbM2WdYC28t6yySsuo@FBUwA3b2ts2Os9uh5IkNhDjKD1@IMkHWU9oJO0AAruoJK2AKXu5wQqQQGUzguI@L5zCjDiOz95e/9eei7V/1yXtD5kErYFIJR82WbvLaPlwLeN7EmM9cCKXnGGoOCUdm04AlygMUfwmUA0c8IqqlwcqZf1Er7Nt@ZLTbPm@/rPJ4M8mFWcFS0x7ZYMna@sFhqfOKxfqvrrpw6qXe/Fvq@qSutH8Cw "JavaScript (Node.js) – Try It Online")
### Commented
```
( // main function taking:
s, // s = strategy string
i = 14 // i = internal counter
) => //
g = b => // g is a recursive function taking b = number of rounds
--b && // decrement b; if b = 0, stop and return a final 0
[ // singleton array:
s > g & // yield 1 if the strategy is not 'always[something]'
// (i.e. it's greater than 'b...')
!s[++i >> 1] // and the character in s at floor(++i / 2) is not
// defined, which is:
// - always true for 'copycat' and 'grudger'
// - true only after 3 turns for 'detective'
] // end of array, implicitly coerced to a string
+ g(b) // append the result of a recursive call
```
This is based on [OP's original answer](https://codegolf.stackexchange.com/revisions/235547/2) (now deleted).
[Answer]
# Java 11, ~~76~~ ~~71~~ 70 bytes
```
s->n->(1-s[6]%2+"").repeat(n>3?3:n-1)+(s[0]/98+"").repeat(n>4?n-4:0)+0
```
-5 bytes thanks to *@Arnauld*
-1 byte thanks to *@ovs*
Input as a character-array and integer, output as a String of 1s/0s.
[Try it online.](https://tio.run/##fZFNb8IwDIbv/Aqr0qREbbN2sI/CVjRNmrTDThyrHrI0QFhJq8Rlqqb99i5AJWBinBL5sf2@tld8w8NV8dmJklsL71zp7wGARY5KwMpR1qAq2bzRAlWl2Wv/eRRLbrI8uJjzplEupAlghkbpRZrCHJ46G6Y6TEkc2uwuv7rxPY8yI2vJkeh0OB2OdRhTn9gsyq@Th1M8mupwNI6oH3WTgTNaNx@lM9r73VSqgLWbgewFsxw43c4DgNIi8RamKZwhL4AhnRzFC4nSWd5IR25PCC@/eGvF0sk7dn@OVVUtDcdtbZKcJIiqbsWZwmO50QW55E@/g/34335xtEM/g8MZd2vZZe7XAjYApRF0v5tZa1GuWdUgqx3HUhPre@D52vfG7pkzXtdlSyzD6sWd/dkY3hJK@7CmveJP9ws)
**Explanation:**
```
s->n-> // Method with character-array and integer parameters
// and String return
// Return the following String:
(1- // Subtract 1 by:
s[6] // The 7th unicode value of the input-array
%2 // Modulo-2
+"") // Convert that 0 or 1 to a String
.repeat(n>3? // If `n` is larger than 3:
3 // Repeat it 3 times
: // Else:
n-1) // Repeat it `n-1` times instead
+ // Concat:
(s[0] // The 1st unicode value of the input-array
/98 // Integer-divided by 98
+"") // Convert that 0 or 1 to a String
.repeat(n>4? // If `n` is larger than 4:
n-4 // Repeat it `n-4` times
: // Else:
0) // Don't repeat it at all
+0 // And concat an additional trailing "0"
```
| String | | `s[6]` | `s[6]%2` | `1-s[6]%2` | | `s[0]` | `s[0]/98` |
| --- | --- | --- | --- | --- | --- | --- | --- |
| detective | | 105 (`i`) | 1 | 0 | | 100 (`d`) | 1 |
| grudger | | 114 (`r`) | 0 | 1 | | 103 (`g`) | 1 |
| copycat | | 116 (`t`) | 0 | 1 | | 99 (`c`) | 1 |
| alwayscheat | | 99 (`c`) | 1 | 0 | | 97 (`a`) | 0 |
| alwayscooperate | | 99 (`c`) | 1 | 0 | | 97 (`a`) | 0 |
] |
[Question]
[
This challenge is a relatively simple concept that I'm surprised has not been done yet. You will be given only an integer as an input. Your task is to find the date that is this number of days from January 1st, 1984. This challenge is uniquely for the Gregorian calendar (which is standard almost everywhere).
# One restriction
The twist on this challenge is that you should not use a built-in function that deals with the date and time - because then this challenge would be trivial for a few languages. Your program must do this calculation entirely on its own - keep in mind leap years exist and have special rules:
* every year that is a multiple of four is a leap year
* the exception to the above rule is any year that is a multiple of 100 but not a multiple of 400
# Output format
You must output the year, month, and day of the month in any order you want so long as the number for the year and day of the month are not conjoined. You can use any character (not numeric or alphabetical), or none, as a separator. The **name of the month must be given as a word instead of a number.** Examples for this format are shown in the test cases.
# Input
You will be given an integer as an input. You can assume this integer will be smaller in magnitude than 700000 - this means **negative integers are also accepted**.
# Test cases
**input | accepted output (which is relatively flexible)**
`13318` | `June 18 2020`
`2` | `JanUaRy03(1984)`
`656979` | `3782september29`
`-30` | `DECEMBER 02 1983`
`-589001` | `00371may15` (leading zeroes may be used)
`0` | `1984 1 january`
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~111~~ ~~106~~ 103 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•3zb•2ôI5°7*+F©`т‰0Kθ4ÖUD2Qi\28X+ë<7%É31α}‹i®ć>šë®1¾ǝDÅsD12‹i>1ǝë<sθ>ª]εNi”……‚應…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í”#sè
```
Output as a triplet `[day, "Month", year]`.
[Try it online.](https://tio.run/##yy9OTMpM/f//UcMi46okIGl0eIun6aEN5lrabodWJlxsetSwwcD73A6Tw9NCXYwCM2OMLCK0D6@2MVc93GlseG5j7aOGnZmH1h1ptzu68PDqQ@sMD@07PtflcGuxi6ERSMrO8PhcoPLiczvsDq2KPbfVL/NRw9xHDcvAaNZhILEQaAOQd3jJo4YFh9c/alpzaD@I2w0iVoHEWkAskIbDPSCiF2iAcvHhFf//65pZmhoYGAAA) (Sort of, since it times out for any input above \$\geq-650000\$..)
### Explanation:
Since 05AB1E doesn't have any date builtins, I've calculated things manually before. I've used the code of going to the next day from [this answer of mine](https://codegolf.stackexchange.com/a/173126/52210), which in turns also uses the leap year calculation of [this answer of mine](https://codegolf.stackexchange.com/a/177019/52210).
Since this challenge also asks to go back in time, I would need to implement something to go to a previous day as well for negative inputs, which would cost a lot of bytes. Instead, since the challenge input is limited to the range \$[-700000,700000]\$, I used that to my advantage and start going upwards in days from date June 21st, 0067 onward, which is 700,000 days before January 1st, 1984.
In pseudo-code, I therefore do the following steps:
```
1 Date currentDate = [21,06,0067]
2 Loop input + 700000 amount of times:
3* currentDate += 1; # Set currentDate to the next date in line
4 Convert month-integer to month-string and output the result
```
Where step 3 is divided into substeps:
```
a Integer isLeapYear = ...;
b Integer daysInCurrentMonth = currentDate.month == 2 ?
c 28 + isLeapYear
d :
e 31 - (currentDate.month - 1) % 7 % 2;
f If(currentDate.day < daysInCurrentMonth):
g nextDate.day += 1;
h Else:
i nextDate.day = 1;
j If(currentDate.month < 12):
k nextDate.month += 1;
l Else:
m nextDate.month = 1;
n nextDate.year += 1;
```
**Transforming that into code:**
1) `Date currentDate = [21,06,0067]` is done like this:
```
•3zb• # Push compressed integer 210667
2ô # Split it into parts of size 2: [21,06,67]
...
© # Store the current date in variable `®` (without popping)
```
2) `Loop input + 700000 amount of times:` is done like this:
```
I # Push the input-integer
5° # Push 10 to the power 5: 100000
7* # Multiply that by 7: 700000
+ # Add it to the input-integer
F # Loop that many times:
```
3a) `Integer isLeapYear = ...;` is done like this:
```
` # Pop and push the day, month, and year separated to the stack
т‰ # Take the divmod of 100
0K # Remove all 0s
θ # Pop and leave its last value
4Ö # And check if it's divisible by 4 (1 if it's a leap year; 0 if not)
U # Pop and store this in variable `X`
```
3b) `currentDate.month == 2 ?` and 3c) `28 + isLeapYear`:
```
D # Duplicate the month that is still on the stack
2Qi # If it's equal to 2 (thus February):
\ # Discard the duplicated month from the stack
28X+ # And add 28 and `X` (the isLeapYear check) together
```
3d) `:` and 3e) `31 - (currentDate.month - 1) % 7 % 2;`:
```
ë # Else:
< # Month - 1
7% # Modulo-7
É # Is odd (short for modulo-2)
31α # Absolute difference with 31
} # Close the if-else statement
```
3f) `If(currentDate.day < daysInCurrentMonth):`:
```
‹ # Check if the day that is still on the stack is smaller than this value
i # If it is:
```
3g) `nextDate.day += 1;`:
```
® # Push the entire date from variable `®` again
ć # Extract its head (the days); pop and push [month,year] and day separated
> # Day + 1
š # Prepend it back in front of the list
```
3h) `Else:` and 3i) `nextDate.day = 1;`:
```
ë # Else:
® # Push the entire date from variable `®` again
1 # Push a 1
¾ # Push index 0
ǝ # Insert the 1 at index 0 (to replace the day) in the list `®`
```
3j) `If(currentDate.month < 12):`:
```
D # Duplicate it
Ås # Pop and push the middle item (the month)
D12‹ # Check if the month is below 12:
i # And if it is:
```
3k) `nextDate.month += 1;`:
```
> # Month + 1
1 # Push index 1
ǝ # Insert the month + 1 at index 1 (to replace the month) in the list `®`
```
3l) `Else:`, 3m) `nextDate.month = 1;` and 3n) `nextDate.year += 1;`:
```
ë # Else:
< # Decrease the month by 1 to 11
s # Swap so list `®` is at the top of the stack again
θ # Pop and push its last item (the year)
> # Year + 1
ª # Convert the 11 to list [1,1] and append the year + 1
```
4) And finally we convert the month-integer to month-string in the resulting date, and output the result:
```
] # Close both if-else statements and the infinite loop
ε # Map the resulting date to:
Ni # If the (0-based) index is 1 (thus the month)
”……‚應…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í”
# Push the dictionary string of months ("December January ... November"
# # Split it on spaces to a list of strings
s # Swap so the month is at the top of the stack
è # And index it into the list (0-based and with wraparound,
# which is why "december" is the first item)
# (after which the resulting date is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•3zb•` is `210667` and `”……‚應…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í”` is `"December January February March April May June July August September October November"`.
[Answer]
# [Perl 5](https://www.perl.org/), 333 bytes
```
eval'sub f{my(N,Y,B,C)=@_;X=sub{B=~/4|6|9|11/?30:B!=2?31:Y%400?Y%100?Y%4?28:29:28:29};if(!C){B--;C=&X}if(C>&X){B++;C=1}if(!B){B=12;Y--}if(B>12){B=1;Y++}@_==1?f(N,1984,1,1):N<0?f(N+1,Y,B,C-1):N>0?f(N-1,Y,B,C+1):Y.[qw(January February Mars April May June July August September October November December)]->[B-1].C}'=~s,[NXYBC],\$$&,gr;
```
[Try it online!](https://tio.run/##5ZRNj9owEIbv/AqzDSRR7F2PA2w@amCTqoeVlh7aAxFFCKiDkCDQfOw2AvavU8cBeukvaOfgzDzvWJq8cbwX6aZ7PovX@UbPigWKD9vSGOEIBzg0@XDmj7nEh4C/P3SOvaN7BHgY2NQLmpwNbPCiVofSQdQCtXYGzPGY66n15K9joxmah4AQP@Tt8UnWYb89lsSyJIEKNANZcmB@REhVB31giviRZZ2GM85hEMuJwHU6GDCY3ugjrYgF9ZSkQn2FyAVZEkX3k59vxvM8KeZpiT6LRaqSl3maoad9ut7ItETPRSLksinRU7Eqshx9FftcbBciRV@W@a56jnavNfgklioxp6Q/CQhM78OTzt8zPBmNoyCc4u@a1sar1D8XmUDfRJZ73ssuFSiXacb7Pb@xLdFQVYgjo4FkTMC2wcFVqjPKaDUQOPoU1ypTilIrAy6vY9/0XrfnPrpVk24/Ouw2vU1li9r34W2eIeaifzxqO4hN8R@77OsXYze/SNdxKQWs/AJ5AqB3NeoSyi/o/h9@0b8eL9CnSjb9RrxLjfrEmgfF5O2gJVgTv/ZimcsLQpv5F4601S7nsZTNGq0zo0IYXboxyuR/l@TxnRQT3iLAfly1O6y2nc6/AQ "Perl 5 – Try It Online")
Ungolfified:
```
sub f {
my($n,$y,$m,$d) = @_;
my $M = sub{$m=~/4|6|9|11/?30:$m!=2?31:$y%400?$y%100?$y%4?28:29:28:29};
if( $d==0 ){ $m--; $d=&$M }
if( $d>&$M ){ $m++; $d=1 }
if( $m==0 ){ $m=12; $y-- }
if( $m==13 ){ $m=1; $y++ }
@_==1 ? f($n,1984,1,1)
:$n<0 ? f($n+1,$y,$m,$d-1)
:$n>0 ? f($n-1,$y,$m,$d+1)
: "$y-".[qw(January February Mars April May June July August September
October November December)]->[$m-1]."-$d"
}
```
Test:
```
use Test::More tests=>6;
my @tests = (
[13318, '2020-June-18'],
[2, '1984-January-3'],
[656979, '3782-September-30'], #was 29
[-30, '1983-December-2'],
[-589001, '371-May-16'], #was 15
[0, '1984-January-1'] );
for(@tests){
my($n,$expect) = @$_;
my $got = f($n);
is($got, $expect, sprintf" n=%-12d $expect",$n);
}
```
Output:
```
ok 1 - n=13318 2020-June-18
ok 2 - n=2 1984-January-3
ok 3 - n=656979 3782-September-30
ok 4 - n=-30 1983-December-2
ok 5 - n=-589001 371-May-16
ok 6 - n=0 1984-January-1
```
[Answer]
# T-SQL, ~~333~~ 311 bytes
Added some line feeds to avoid scrolling
```
DECLARE @ int=0WHILE~@i<724671SELECT
@+=iif(d=iif(m=2,28-sign(1/~(y%4)*y%25+1/~(y%16)),
31+~m%9%2),iif(m=12,320,51-d),1),@i-=1FROM(SELECT
@/50%18m,@%50d,@/900y)x
PRINT concat(@/900,choose(@/50%18,'january','february',
'march','april','may','june','july','august',
'september','october','november','december'),@%50)
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1255635/find-the-date-that-is-n-days-from-january-1st-1984)**
[Answer]
## JavaScript (Node.js), ~~330~~ 300 bytes
```
a=>{for(n=a<(d=m=0),y=1984,a*=n?-1:1;a-->0;){s="3"+((y%400)?((y%100)?((y%4)?(0):1):0):1)+"3232332323";v=27+(+s[m]);if(n&&!d--){m=m?(m-1):11;m==11&&y--;d=v}if(!n&&d++==v){d=0;m=m^11?(m+1):0;!m&&y++;}};return y+['January','February','March','April','May','June','July','August','September','October','November','December'][m]+(d+1)}
```
[Try it online!](https://tio.run/##ZY9da8IwFIbv9ytmYTVZzEisXzU7ijB2IWy72KU4iG3qHE0r6QcU6W/v0jovRgmc85yH95DkR5YyC8zpnNMkDVUTQSNhdYlSgxKQzygEDQyPKuD@YjKSj5CsKV9yISldMYEvGTieQxCqHiaM4XUL/AYT2xhecrzsKnG8sT1dcUQJ4zlBJNvpPRanCCWuOwgpxRcNeo00tVucCw3AuetWlIoQytrmBjYYEgJQ4ksIzCb0F@d2g7T3iIG2aUJEXQuj8sIk9xXZDbcyKaSphqPhqzqYP3yTJvi2fXM2p7ibW7stEtW1uJ02xbHIcguf6pwrfVDG8keQp1d6T8ubfFHBFff2RwSF9jl1E6RJlsbqKU6PKELc8/gC47v/dtwzs@nMn/s9TT3Wd9OFzxjveZtsfgE)
**String improvement (and removed parentheses):**
```
a=>{for(n=a<(d=m=0),y=1984,a*=n?-1:1;a-->0;){v=27+(+("3"+(y%400?(y%100?(y%4?0:1):0):1)+3232332323)[m]);if(n&&!d--){m=m?m-1:11;m==11&&y--;d=v}if(!n&&d++==v){d=0;m=m^11?m+1:0;!m&&y++;}}return y+"January February March April May June July August September October November December".split(" ")[m]+(d+1)}
```
[Try it online!](https://tio.run/##ZY5da4MwGIXv9ytSYZIsTUlqv9SlUhi7KGy72OXYINXYOUyU@AEi/nabtldDAuccHh7C@ydaUcUmK2uii0SOKR8F3/dpYaDm4hkmXHGK5h1n/m41F09cR4QFLBSE7GmI@pYvtxhi6HgOht3jitLIFrvXKqIBQwFFNrG3tO8W6Et9ozBLoXbdWUII6hVXkbr@y0LFOWOu2xESJrwdrDWzWoIx5y3qE06toX4YixRmAQ1nyroYh8NgZN0YDTrsHIVuhOnAqzyZ23gTJv4Fh9Jkud0dODZa2sg7cGjOTVWDT1nWUp2kAR9xXVz7vWjv4EXGt@EsqjLPaugA53o/hglmaBjjQldFLhd5cYYpZJ7Hdgg9/KfLCdmsN/7Wn2Di0Slb73xK2YRbc7wA)
Tests:
```
console.log(f(13318))
console.log(f(2))
console.log(f(656979))
console.log(f(-30))
console.log(f(-589001))
console.log(f(0))
```
Results:
```
2020June18
1984January3
3782September30
1983December2
371May16
1984January1
```
Ungolfified:
```
a=>{
for(n=a<(d=m=0),y=1984,a*=n?-1:1;a-->0;){
v=27+(+("3"+(y%400?(y%100?(y%4?0:1):0):1)+3232332323)[m]);
if(n&&!d--){
m=m?m-1:11;
m==11&&y--;
d=v
}
if(!n&&d++==v){
d=0;
m=m^11?m+1:0;
!m&&y++;
}
}
return y+"January February March April May June July August September October November December".split(" ")[m]+(d+1)
}
```
] |
[Question]
[
This is a Cops and Robbers challenge. For the Cops' thread, go [here](https://codegolf.stackexchange.com/q/166338/42963).
The Cops have three tasks.
1) Pick a sequence from the [OEIS](https://oeis.org).
2) Pick a language (this is suggested to be a golflang, but doesn't have to be) that, when given input `n`, outputs `A(n)` (where `A(n)` is the sequence chosen) using all usual [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules.
Call this language **LA** and code **CA**.
For example, *Jelly* and *Jelly\_code*.
3) Then, pick a different language (this is suggested to be a non-golflang, but doesn't have to be) and write code that takes no input and outputs code **CA**, again following all usual [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules. (Note: this can be obfuscated code and doesn't necessarily need to be golfed, but the longer this code is the easier it will be for the robbers to crack your submission.)
Call this language **LB** and code **CB**.
For example, *Python* and *Python\_code*.
The Cop's submission to this challenge is the sequence (specified whether 0- or 1-indexed), the name of the two languages **LA** and **LB** (and which one solves which part), and the byte-count of **CB** only. Keep the actual code of both parts, and the length of **CA**, secret.
**The Robber's challenge** is to select a Cops' entry and write code **CC** in the same **LB** language that outputs *some* code in the same **LA** language that solves the original OEIS task. The length of **CC** can be no longer than the length of **CB** as revealed by the cop (though may be shorter). Note: The code produced by **CC** does *not* have to match **CA**.
For our example, this means that the Robber has to write *Python* code that outputs *Jelly* code that solves the original OEIS sequence, and that *Python* code has to be no longer than the length revealed by the Cop.
### Winning conditions
The Robber with the most cracked solutions wins.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 90 bytes by [Mr. Xcoder](https://codegolf.stackexchange.com/a/166358/31716)
```
((((((((((()()()){}){}){({}[()])}{}())[(((()()()){})){}{}()]))){}{}()()())([][][]){})[][])
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/XwMBNEFQs7oWjDSqa6M1NGM1a6trgYLRKPJADBKN1YSxwBIa0bEgCFIApv///6/rCAA "Brain-Flak – Try It Online")
This outputs:
```
ÑÉ·<O
```
First 05AB1E answer!
## How does it work?
Let's say we have 24 as input.
```
Ñ # Divisors.
# Stack: [1, 2, 3, 4, 6, 8, 12, 24]
É # Odd?
# Stack: [1, 0, 1, 0, 0, 0, 0, 0]
· # Double
# Stack: [2, 0, 2, 0, 0, 0, 0, 0]
< # Decrement
# Stack: [1, -1, 1, -1, -1, -1, -1, -1]
O # Sum
# Stack: -4
```
The brain-flak code mostly just uses tricks to push large numbers in few bytes. It was very convenient (and unintentional) that the ASCII values are mostly increasing:
```
209
201
183
60
79
```
It's also nice that `60 * 3 ~=~ 183` so tripling it and adding a few can save a ton of bytes.
```
((((((
# Push 79
((((()()()){}){}){({}[()])}{}())
# Minus 19 (60)
[(((()()()){})){}{}()])
# Push that two extra times
))
# Push that ^ (60) Plus the two extras popped (60 + 120 == 180)...
{}{}
# + 3 (183)
()()())
# Plus stack-height * 3 * 2 == 3 * 3 * 2 == 18 (201)
([][][]){})
# Plus stack-height * 2 == 4 * 2 == 8 (209)
[][])
```
[Answer]
## [Jelly](https://github.com/DennisMitchell/jelly), 34 bytes by [Arnauld](https://codegolf.stackexchange.com/a/166374/42545)
Managed a byte shorter than his solution!
```
“`Ḃ|⁴ʂⱮdÐỌK_ƬƬfıæh’ṃ“fnk1()+-,=>?:
```
[Try it online!](https://tio.run/##AUEAvv9qZWxsef//4oCcYOG4gnzigbTKguKxrmTDkOG7jEtfxqzGrGbEscOmaOKAmeG5g@KAnGZuazEoKSstLD0@Pzr//w "Jelly – Try It Online")
This outputs the JS function
```
f=(n,k=1)=>n>=k?f(n-k,k)+f(n,k+1):1>n
```
which computes [A000041](https://oeis.org/A000041) (0-indexed; `nn(0)` returns `true` in place of `1`).
[Answer]
# [TeX by Simon Klaver](https://codegolf.stackexchange.com/a/166962/3852)
```
g\bye
```
prints `g`, which computes the length of the input in 05AB1E.
[Answer]
# [Malbolge, 32 bytes by Lynn](https://codegolf.stackexchange.com/a/166972/71256)
```
('%$:?>7[5|981Uv.uQrq)Mnmm$Hj4ED
```
[Try it online!](https://tio.run/##y03MScrPSU/9/19DXVXFyt7OPNq0xtLCMLRMrzSwqFDTNy83V8Ujy8TV5f9/AA "Malbolge – Try It Online")
That prints the following haskell function:
```
gcd 2
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPz05RcHof25iZp6CrUJuYoGvgkZBUWZeiV6apkK0oZ6eoYFB7P9/yWk5ienF/3WTCwoA "Haskell – Try It Online")
I used [this](http://zb3.me/malbolge-tools/#generator) online tool to generate the Malbolge
[Answer]
## [Python, 13 bytes by HyperNeutrino](https://codegolf.stackexchange.com/a/166344/56721)
```
print"n=>n%2"
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EKc/WLk/VSOn/fwA "Python 2 – Try It Online")
[Answer]
# [Triangularity by Mr. Xcoder](https://codegolf.stackexchange.com/a/166950/3852), 36 bytes
```
... ...
.. "..
.aẒ;Ba.
1ÇP$#Ṁ"
```
[Try it online!](https://tio.run/##KynKTMxLL81JLMosqfz/X09PTwGIuYCUghKITny4a5K1U6Iel@Hh9gAV5Yc7G5T@/wcA "Triangularity – Try It Online")
Prints Jelly code:
```
..
.aẒ;Ba.
1ÇP$#Ṁ
```
[Try the Jelly code online!](https://tio.run/##y0rNyan8/19Pj0sv8eGuSdZOiXpchofbA1SUH@5s@P//vykA) It's quite slow.
] |
[Question]
[
**This question already has answers here**:
[All your base palindromic belong to us](/questions/69707/all-your-base-palindromic-belong-to-us)
(17 answers)
Closed 6 years ago.
Given a number `n`, calculate the amount of bases in the range of `[2, n)` in which `b(n)` is a Palindrome.
## Example
`n = 8` has the base conversions:
```
2 = 1000
3 = 22
4 = 20
5 = 13
6 = 12
7 = 11
```
Of which 2 of them, `3 = 22` and `7 = 11` are palindromes. So return `2`.
## Clarifications
* For the sake of convenience, Your answer only needs to be correct for inputs 3 - 36 inclusive, as few languages can handle base conversion of >36.
* A single digit number is considered a palindrome.
* This is sequence A135551 on [OEIS](https://oeis.org/A135551)
## Test Cases
```
3 -> 1
4 -> 1
5 -> 2
6 -> 1
7 -> 2
8 -> 2
9 -> 2
10 -> 3
11 -> 1
12 -> 2
13 -> 2
14 -> 2
15 -> 3
16 -> 3
17 -> 3
18 -> 3
19 -> 1
20 -> 3
21 -> 4
22 -> 2
23 -> 2
24 -> 4
25 -> 2
26 -> 4
27 -> 3
28 -> 4
29 -> 2
30 -> 3
31 -> 3
32 -> 3
33 -> 3
34 -> 3
35 -> 2
36 -> 5
```
## Finally
* [Standard Loopholes Apply.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins.
* Have Fun!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md)
-2 bytes thanks to Emigna (use "bifurcation" instruction `Â` to replace duplicate and reverse `DR` & increment the loop to avoid needing to close it.)
```
G¹N>вÂQO
```
**[Try it online!](https://tio.run/##MzBNTDJM/f/f/dBOvwubDjcF1vrb/P9vZAYA "05AB1E – Try It Online")**
### How?
```
G¹N>вÂQO
G - for N in range(1, input()+1):
¹ - 1st input
N - N (the loop variable)
> - increment
в - base conversion
 - push reverse
Q - equal?
O - sum
- print top of stack
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
bḊŒḂ€S
```
A monadic link taking and returning numbers
**[Try it online!](https://tio.run/##y0rNyan8/z/p4Y6uo5Me7mh61LQm@L9xkbHZ0T2H24EcFff/AA "Jelly – Try It Online")**
### How?
```
bḊŒḂ€S - Link: number, n
Ḋ - dequeue (with implicit range(n) as input) -> [2,3,4,...,n]
b - convert to base -> [nb2, nb3, nb4, ..., nbn] (note: nbn is [1,0])
ŒḂ€ - isPalindrome? for €ach -> list of 1s and 0s
S - sum -> number that are palindomes
```
[Answer]
# J, 30 bytes
```
[:+/i.&.(-&2)(-:|.)@(#.inv)"0]
```
[Try it online!](https://tio.run/##y/r/P03BVk8h2kpbP1NPTU9DV81IU0PXqkZP00FDWS8zr0xTySCWiys1OSNfIU3JQAGqyFhTwdj8/38A)
Straightforward solution featuring a lot of parentheses.
# Explanation
```
[: +/ i.&.(-&2) (-:|.)@(#.inv)"0 ]
] Right argument, n
i.&.(-&2) Range [2,n)
-&2 Subtract 2
i. Create range from n-2
&. Undo subtraction (add 2)
"0 For each value in the range
(#.inv) Convert to that base *
(-:|.) Palindrome check
|. Reversed
-: Matches self (= is rank 0)
+/ Sum (i.e. count palindromes)
```
\*`#.inv` is used since `#:` expects you to specify the number of digits in the base (it doesn't treat a single argument the way you might expect).
[Answer]
# [Python 2](https://docs.python.org/2/), 90 bytes
```
lambda n:sum(h(n,i)==h(n,i)[::-1]for i in range(2,n))
h=lambda v,b:v and[v%b]+h(v/b,b)or[]
```
An unnamed function taking `n` that counts the palindromes, which utilises the helper function `h` which performs the base conversions.
**[Try it online!](https://tio.run/##RctBCsIwEIXhtT3FbKQJTpG2C0sgXiRmkdDWBOykpDHg6SNVwdXj5/Gtr@QCdWWWt/Iwix0NkNieC3OM0HMpv6uEaFo9hwgePEE0dJ9Yh8R55eTPZbQig6FR5aPVJ8fy2aLlISpddpmmLf1xj/2Fi@qwRk/p8yHUzbVGmNlevLTDGw "Python 2 – Try It Online")**
[Answer]
# Mathematica, 57 bytes
```
Tr@Boole@Table[PalindromeQ@IntegerDigits[#,i],{i,2,#-1}]&
```
[](https://i.stack.imgur.com/fSojW.jpg)
[Answer]
# Ruby, 47 bytes
```
->n{(2...n).count{|i|(s=n.to_s(i))==s.reverse}}
```
[Try it online!](https://tio.run/##KypNqvz/P03BVkHXLq9aw0hPTy9PUy85vzSvpLoms0aj2DZPryQ/vlgjU1PT1rZYryi1LLWoOLW2louLq6C0pFghLTo9taQYpCYz9v9/YzMA)
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 10 bytes
```
tFOAbD_q)s
```
[Try it here!](http://pyke.catbus.co.uk/?code=tFOAbD_q%29s&input=36&warnings=0&hex=0)
```
t - input - 1
FOAbD_q) - for i in ^:
O - ^ + 2
Ab - base(input, ^)
D_q - ^ == reversed(^)
s - sum(^)
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 9 bytes
```
lf_IjQTtS
```
**[Test it here!](https://pyth.herokuapp.com/?code=lf_IjQTtS&input=8&debug=0)**
# [Pyth](https://pyth.readthedocs.io), 9 bytes
```
sm_IjQdtS
```
**[Try it here!](https://pyth.herokuapp.com/?code=sm_IjQdtS&input=8&debug=0)**
---
# How?
* `sm_IjQdtS` - Full program with implicit input (`Q` at the end)
* `tS` - All the integers from 2 to the input (inclusive). I chose inclusive because it is golfier and any number `n` converted to base `n` is `10`.
* `m` - Map over the above with a variable `d`.
* `jQd` - Convert the input to base `d` (the current number in the range) as a list.
* `_I` - The best part of this program: Is invariant under reverse? – This checks if the list is palindromic.
* `s` - Sum, which acts like "count the number of truthy results" in this case.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~10~~ 9 bytes
Port of [irtosiast's submission](https://codegolf.stackexchange.com/a/69710/53748) to "All your base palindromic belong to us".
-1 byte thanks to FryAmTheEggman - use the filter alias `#` to replace `f` and do away with the `T` (which seems also to have been available back then too).
```
lt_I#jLQS
```
**[Try it online!](https://tio.run/##K6gsyfj/P6ck3lM5yycw@P9/IzMA "Pyth – Try It Online")**
[Answer]
# [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 18 bytes
```
x=x1-2R³x\Br³]ier+
```
This is essentially what I used as a reference implementaiton.
## Explained
```
x=x1-2R³x\Br³]ier+
x= # Associate 'x' with the implicit input.
x1- # Get x - 1
2R # Get all numbers in the range 2 through x - 1
r # Replace each element by the function...
³x\B # Convert x to base i.
r # Replace each element by another function...
³]ie # Duplicate, Inverse, Equals. Checks if it's a palindrome.
+ # The sum of. Which counts how many are palindromes.
```
[Try it online!](https://tio.run/##Kyooyk/P0zX6/7/CtsJQ1yjo0OaKGKeiQ5tjM1OLtP///29kCgA "RProgN 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 187 bytes
```
def P(n):
p=0
for b in range(2,n):
M=0
while n>=b**M:M+=1
N,I,B=n,M-1,[]
while N:
for f in range(b)[::-1]:
if f*b**I<=N:N-=f*b**I;B+=[f];I-=1;break
p+=0>(B[::-1]==B)*I
print p
```
[Try it online!](https://tio.run/##RY@7CoNAEEXr3a8YBMHHLvgoAmvGws5CSS8Wim6UhFFECPl6syrBcjhzz52Zv@swUbRtXa/h4ZCrOMwYcNDTAi2MBEtDz96JxI5YYRD7DOO7B0qx9bxCFT6GnJUiFxmSKGQoqvq/U5rIYdKXqXUrpWRYG8RGDdozlvyOpSolnkOS@VjpOsklhkm79M2Ls9nHIHWyM4qYuV5uDl1GWmHe9ga6GmIR31x1QMuOOpCpZZNI9u@2Hw "Python 2 – Try It Online")
A bit on the lengthy side, as there is no built-in used for changing base.
[Answer]
# [Haskell](https://www.haskell.org/), 67 bytes
```
0#b=[]
x#b=mod x b:div x b#b
f n=sum[1|b<-[2..n],n#b==reverse(n#b)]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/30A5yTY6lqsCSOXmpyhUKCRZpWSWgWjlJK40hTzb4tLcaMOaJBvdaCM9vbxYnTygStui1LLUouJUDSBHM/Z/bmJmnoKtQkFRZl6JgopCmoKx2X8A "Haskell – Try It Online") Use by calling `f`. Works with arbitrary high bases.
[Answer]
# JavaScript (ES6), ~~77~~ ~~71~~ ~~70~~ ~~68~~ 67 bytes
```
n=>(g=b=>b<n&&([...s=n.toString(b)].reverse().join``==s)+g(++b))(2)
```
(Golfed from 77 down to 68 while waiting for the challenge to be reopened)
---
## Test it
```
f=
n=>(g=b=>b<n&&([...s=n.toString(b)].reverse().join``==s)+g(++b))(2)
o.innerText=[...Array(34)].map(_=>(""+x).padStart(2)+": "+f(x++),x=3).join`\n`
```
```
<pre id=o>
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/) `-x`, ~~9~~ 8 bytes
```
ò2@sX êS
```
[Test it]<https://ethproductions.github.io/japt/?v=1.4.5&code=8jJAc1gg6lM=&input=MzYKLXg=>)
---
## Explanation
```
:Implicit input of integer U.
ò2 :Range [2,U]
@ :Map each X
sX : Convert U to a base-X string
êS : Is it a palindrome?
:Implicitly reduce by addition and output
```
] |
[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/109085/edit).
Closed 7 years ago.
[Improve this question](/posts/109085/edit)
A symmetric polynomial is a polynomial which is unchanged under permutation of its variables.
In other words, a polynomial `f(x,y)` is symmetric if and only if `f(x,y) = f(y,x)`; a polynomial `g(x,y,z)` is symmetric iff `g(x,y,z) = g(x,z,y) = g(y,x,z) = etc`.
For example, `x^2+2xy+y^2`, `xy` and `x^3+x^2y+xy^2+y^3` are symmetric polynomials, where `2x+y` and `x^2+y` are not.
---
# The challenge
You will be given a polynomial, and your program should output truthy/falsy values, depending on if the given polynomial is a symmetric polynomial.
The input format is allowed in two ways. A string, and an array, like `["x^2","2xy","y^2"]`, where the polynomial is the sum of each elements.
---
# Example
```
x^2+2xy+y^2 => true
xy => true
xy+yz+xz-3xyz => true
(x+y)(x-y) => false
2x+y => false
x^2+y => false
x+2y+3 => false
```
---
# Specs
The operation has orders, just like in normal math. the order is like this:
```
() => ^ => * => +-
```
[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
All the characters in the alphabet (`a~z`) are accepted as variables, everything else are numbers.
The given polynomial will have 2 or more variables.
Multiplication does not require the \* operator, You only need to detect juxtaposition. (detecting by juxtaposition is not neccessary, use the better option)
[Answer]
# Mathematica, 43 bytes
```
Last@SymmetricReduction[#,Variables@#]===0&
```
Unnamed function taking as input a polynomial in the given format (except that juxtaposed variables must be separated by a space) and returning `True` or `False`. `Variables@#` detects the variables appearing in the input (and thus the input can contain all kinds of weird variable names, not just single letters). `SymmetricReduction` returns an ordered pair of polynomials, where the first one is symmetric and the two sum to the original polynomial; therefore we can detect whether the input is symmetric by seeing whether the second polynomial is identically `0`.
[Answer]
# Maxima, 40 bytes
```
f(p):=listp(tpartpol(p,showratvars(p)));
```
[Try It Online!](https://tio.run/nexus/maxima#@5@mUaBpZZuTWVxSoFFSkFhUUpCfo1GgU5yRX16UWFKWWFQMVKCpaf2/oCgzr0QjTaNCq1K7UqtKu0KrStdYC8jTqgJKc8GltY2ACoxBOgA)
A function that takes a polynomial as input and returns true if it is symmetric else returns false
[Answer]
# TI-Basic, 46 bytes
Basically, how this works is the polynomial is entered into a (two-byte) variable type that is dynamically evaluated. Then, we swap the X and Y values enough times to see if the function is symmetric.
```
Prompt u
For(I,0,8
rand->X
Ans->W
rand->Y
u->Z
Y->X
W->Y
If u=W
End
Ans=9
```
] |
[Question]
[
related and inspired by -- [Finding sum-free partitions](https://codegolf.stackexchange.com/q/63455/42963)
A set `A` is defined here as being *distinctly [sum-free](https://en.wikipedia.org/wiki/Sum-free_set)* if
* 1) it consists of at least three elements, `|A| ≥ 3`, and
* 2) its distinct self-sum `A + A = { x + y | x, y in A}` (with `x,y` distinct, i.e., `x≠y`) has no elements in common with `A`.
(Obsolete - do not use this going forward. Left here only because some answers may have used it. It does not match with the above conditions. *Alternatively, the equation `x + y = z` has no solution for `x,y,z ∈ A` (again with `x,y,z` distinct, i.e., `x≠y`, `x≠z`, `y≠z`).*)
For a simple example, `{1,3,5}` is distinctly sum-free, but `{1,3,4}` is not. `{1,3}` and `{3}` are also not, since they're not at least three elements.
The challenge here is to find the largest distinctly sum-free subset of the given input.
### Input
* An unordered set `A` of integers in any [convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963).
* The integers could be positive, negative, or zero, but can be assumed to fit in your language's native `[int]` datatype (or equivalent).
* The set is guaranteed to have only distinct elements (no multisets here).
* The set is not necessarily sorted.
### Output
* The largest subset of `A` (which could be `A` itself), that is distinctly sum-free. Output can be in any suitable format.
* If no such subset exists, output an empty set or other [falsey value](http://meta.codegolf.stackexchange.com/a/2194/42963).
* If multiple subsets are tied for largest, output any or all of them.
* The subset does not necessarily need be sorted, or in the same order as the input. For example, for input `{1,3,5}` output `{5,1,3}` is acceptable.
### Additional Rules
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so all usual golfing rules apply, and the shortest code wins.
### Examples
```
Input -> Output (any or all)
{0} -> {}
{1, 2, 3} -> {}
{1, 3, 5} -> {1, 3, 5}
{1, 2, 3, 4, 5} -> {1, 2, 5} {1, 2, 4} {1, 3, 5} {2, 3, 4} {2, 4, 5} {3, 4, 5}
{-5, 4, 3, -2, 0} -> {-5, 4, 3} {-5, 4, -2} {4, 3, -2}
{-5, 4, 3, -2} -> {-5, 4, 3} {-5, 4, -2} {4, 3, -2}
{-17, 22, -5, 13, 200, -1, 1, 9} -> {-17, 22, -5, 13, 200, -1, 1} {-17, 22, -5, 200, -1, 1, 9} {-17, -5, 13, 200, -1, 1, 9}
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~47~~ 43 bytes
```
nW:qB!ts2#Sw2>)PZ)"1G@)XJ2XN!"@sJ@X-m~*]?J.
```
[**Try it online!**](http://matl.tryitonline.net/#code=blc6cUIhdHMyI1N3Mj4pUFopIjFHQClYSjJYTiEiQHNKQFgtbX4qXT9KLg&input=WzEgMiAzIDQgNV0)
### Explanation
This uses two loops: an outer loop to generate all possible subsets, and an inner loop to take all pairs of elements and see if the sum equals any other element of the subset.
Subsets of at least 3 elements are tested in order of decreasing number of elements. The code stops as soon as a valid subset is found.
```
% Take input implicitly
nW:q % Generate [0 1 ... 2^n-1] where n is input length
B! % Convert to binary. Gives a matrix. Each number corresponds to a column.
% This will be used to select the elements of each subset
ts % Duplicate. Sum of each column
2#S % Sort. Output the sorted array and the indices of the sorting. Each index
% corresponds to one possible subset
w2> % Swap. Logical index of values that exceed 2. This is used to pick only
% subsets of more than 2 elements
) % Keeps only indices of subsets that have at least 3 elements
P % Flip. This moves subsets with more elements to the front. As soon as a
% subset fulfills the condition the outer loop will be exited, so we need
% to start with the bigger subsets
Z) % Index into columns of binary matrix. Each column is the binary pattern
% defining a subset with at least 3 elements, starting with bigger subsets
" % For each column. Each iteration corresponds to a subset
1 % Push 1
G@) % Pick actual elements of each subset (logical index into input)
XJ % Copy to clipboard J
2XN! % All pairs of 2 elements from that subset. Each pair is a column
" % For each column. Each iteration corresponds to a pair of elements
@s % Sum of those two elements
J@X- % Array with the other elements (obtained with set difference)
m~ % True if the sum of the two elemens is not a member of the array
* % Multiply. Corresponds to logical AND
] % End for
? % If result is true: no sum of two elements equalled any element
J % Push found subset (will be displayed implicitly)
. % Exit loop
% End if implicitly
% End for implicitly
% Display stack implicitly
```
[Answer]
# Python, 137 bytes
A naïve approach. Loops over all subsets of the input containing at least 3 values, checking the property for each one. Returns `[]` when no result is found or `[S]` if at least one result is found (where `S` is some tuple).
```
from itertools import*
lambda a:[c for n in range(3,len(a)+1)for c in combinations(a,n)if all(x+y-z for(x,y,z)in permutations(c,3))][-1:]
```
[Answer]
### Javascript 246 ~~263~~
```
a=>([...Array(1<<(l=a.length))].map((x,i)=>i.toString(2)).filter(n=>/1.*1.*1/.test(n)).map(s=>('0'.repeat(l)+s).slice(-l).replace(/./g,(b,p)=>+b&&o.push(a[p]),o=[])&&o).filter(u=>u.every((x,i)=>!u.some((y,j)=>j-i&&u.some((z,k)=>k-j&&!(z-x-y))))))
```
So long :( ... But it was a nice coding ..(I think)
Less golfed:
```
f=a=>(
[...Array(1<<(l=a.length))]
.map((x,i)=>i.toString(2))
.filter(n=>/1.*1.*1/.test(n))
.map(s=>
('0'.repeat(l)+s).slice(-l).replace(/./g,
(b,p)=>+b&&o.push(a[p])
,o=[])&&o
)
.filter(u=>
u.every((x,i)=>
!u.some((y,j)=>
j-i&&u.some((z,k)=>k-j&&!(z-x-y))
)
)
)
)
document.body.innerHTML = JSON.stringify( f([1,2,3,4,5]), null, 1 );
```
[Answer]
# Mathematica - ~~89~~ ~~84~~ ~~83~~ ~~77~~ 76 bytes
*6 bytes saved thanks to @Sp3000*
Probably can be golfed a lot more, is there a shorter way to filter?
```
Select[Subsets@#,Length@#>2&&Intersection[#,Tr/@#~Subsets~{2}]=={}&]~Last~0&
```
Anonymous function, returns `0` on no answer.
[Answer]
# Ruby, 107 bytes
Input is an array. Collects one qualifying subset for each subset size from `3` to the input length, then returns the biggest one out of the ones found. Returns `nil` if no result is found.
Because of the conflicting spec, there are two solutions that currently have the same bytecount.
Using the first definition: (`{ x + y | x, y ∈ A } ∩ A = ∅`)
```
->s{((3..s.size).map{|i|s.combination(i).find{|e|e.combination(2).map{|a,b|a+b}&e==[]}}-[p])[-1]}
```
Using the second definition (`∀ x, y, z ∈ A: x + y ≠ z`)
```
->s{((3..s.size).map{|i|s.combination(i).find{|e|e.permutation(3).all?{|a,b,c|a+b!=c}}}-[p])[-1]}
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
8BḊ+œc2S€f
ŒPÇÐḟṪ
```
[Try it online!](http://jelly.tryitonline.net/#code=OELhuIorxZNjMlPigqxmCsWSUMOHw5DhuJ_huao&input=&args=Wy0xNywgMjIsIC01LCAxMywgMjAwLCAtMSwgMSwgOV0) or [verify all test cases](http://jelly.tryitonline.net/#code=OELhuIorxZNjMlPigqxmCsWSUMOHw5DhuJ_huaoKw4figqxH&input=&args=WzBdLCBbMSwgMiwgM10sIFsxLCAzLCA1XSwgWzEsIDIsIDMsIDQsIDUsXSwgWy01LCA0LCAzLCAtMiwgMF0sIFstNSwgNCwgMywgLTJdLCBbLTE3LCAyMiwgLTUsIDEzLCAyMDAsIC0xLCAxLCA5XQ).
[Answer]
# Pyth, 27 bytes
```
ef!f!*Fm-Fd.pYfqlY3yTfglT3y
```
[Test suite.](http://pyth.herokuapp.com/?code=ef!f!*Fm-Fd.pYfqlY3yTfglT3y&test_suite=1&test_suite_input=%5B1%2C+2%2C+3%5D%0A%5B1%2C+3%2C+5%5D%0A%5B1%2C+2%2C+3%2C+4%2C+5%5D%0A%5B-5%2C+4%2C+3%2C+-2%2C+0%5D%0A%5B-5%2C+4%2C+3%2C+-2%5D%0A%5B2%2C+4%2C+7%5D&debug=0)
] |
[Question]
[
It is well-known that there are one-to-one correspondences between pairs of integers and the positive integers. Your task is to write code defining such a correspondence (by defining a pair of functions/programs that are inverses of each other) in your programming language of choice, plus a correctness check (see below) with the smallest number of bytes for the correspondence definition (not taking the correctness check into account).
The solution must include :
* the definition of a function/program f having two integer arguments and returning an integer (that's one direction of the bijection).
* either the definition of a function/program g having one integer argument and returning a pair of integers (might be an array, a list, the concatenation of the two integers separated by something ...) or two functions/programs a and b having an integer argument and returning an integer (that's the other direction).
* an additional code snippet checking that for the f and g (or f and a,b) you defined above, you have g(f(x,y))=(x,y) (or a(f(x,y))=x and b(f(x,y))=y) for any integers x,y in the range -100 < x < 100,-100 < y < 100. Note that f and g have to work for values outside of this range as well.
You may rename a,b,f or g of course. The two solutions do not have to be written in the same language.
Below is a not-optimal-at-all solution in PARI/GP, with 597 characters for the function definitions.
```
plane_to_line(x,y)={
my(ax,ay,z);
ax=abs(x);
ay=abs(y);
if((ax<=ay)*(y<0), z=4*y*y-2*y+x+2;);
if((ax<=ay)*(y>=0), z=4*y*y-2*y-x+2;);
if((ay<=ax)*(x<0), z=4*x*x -y+2;);
if((ay<=ax)*(x>=0)*(y<0), z=4*x*x+4*x+y+2;);
if((ay<=ax)*(x>=0)*(y>=0),z=4*x*x-4*x+y+2;);
if((x==0)*(y==0),z=1;);
return(z);
}
line_to_plane(z)={
my(l,d,x,y);
l=floor((1+sqrt(z-1))/2);
d=z-(4*l*l-4*l+2);
if(d<=l,x=l;y=d;);
if((l<d)*(d<=3*l),x=2*l-d;y=l;);
if((3*l<d)*(d<=5*l),x=(-l);y=4*l-d;);
if((5*l<d)*(d<=7*l),x=d-6*l;y=(-l););
if((7*l<d)*(d<8*l) ,x=l;y=d-8*l;);
if(z==1,x=0;y=0;);
return([x,y]);
}
```
and the correctness-check code :
```
accu=List([])
m=100;
for(x=-m,m,for(y=-m,m,if(line_to_plane(plane_to_line(x,y))!=[x,y],\
listput(accu,[x,y]);)))
Vec(accu)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~43~~ 36 bytes
This uses the `spiral` (`1YL`) function, which generates a square 2D array of given size with values arranged in an outward spiral. For example, with input `7` it produces
```
43 44 45 46 47 48 49
42 21 22 23 24 25 26
41 20 7 8 9 10 27
40 19 6 1 2 11 28
39 18 5 4 3 12 29
38 17 16 15 14 13 30
37 36 35 34 33 32 31
```
The center of the array, which contains `1`, corresponds to the tuple `[0 0]`. The upper left corner corresponds to `[-3 -3]` etc. So for example *f* (-3,-3) will be 43 and *g* (43) will be [-3 -3].
The code generates a 2D array with this spiral matrix, as large as needed to do the conversion. Note that larger sizes always give the same result for the entries already included in smaller sizes.
### From **Z**2 to **N** (18 bytes):
```
|X>tEQ1YLGb+QZ}3$)
```
[Try it online!](http://matl.tryitonline.net/#code=fFg-dEVRMVlMR2IrUVp9MyQp&input=WzMgLTVd)
```
|X> % input is a 2-tuple. Take maximum of absolute values
tEQ % duplicate. Multiply by 2 and increase by 1. This gives necessary size of spiral
1YL % generate spiral
G % push input 2-tuple again
b+Q % bubble up, add, increase by 1. This makes the center correspont to [0 0]
Z} % split tuple into its values
3$) % use those two value as indices into the spiral array to obtain result
```
### From **N** to **Z**2 (~~25~~ 18 bytes)
```
Eqt1YLG=2#fhw2/k-q
```
[Try it online!](http://matl.tryitonline.net/#code=RXF0MVlMRz0yI2ZodzIvay1x&input=MTAz)
```
Eq % input is a number. Multiply by 2, add 1. This assures size is enough and odd
t1YL % duplicate. Generate spiral of that size
G= % compare each entry with the input value
2#fh % 2-tuple of row and column indices of matching entry
w2/k-q % swap. Offset values so that center corresponds to [0 0]
```
### Snippet for checking
Note that `G` needs to be modified to accomodate the fact that we have don't have a single input. The code is slow, so the link checks tuples with values from -9 to 9 only. For -99 to 99 just replace the first line.
The code tests each tuple with values in the defined range. It does the conversion to a number, then from that number back to a tuple, and then checks if the original and recovered tuple are equal. The results should all be `1`, indicating that all comparisons give `true`.
It takes a while to run.
[Try it online!](http://matl.tryitonline.net/#code=LTk6OQpIWl4hIkAKfFg-dEVRMVlMQGIrUVp9MyQpClhKCkVxdDFZTEo9MiNmaHcyL2stcQpAIVg9&input=)
```
-9:9 % Or use -99:99. But it takes long
HZ^!"@ % Cartesian power: gives tuples [-9 -9] ... [9 9].
% For each such tuple
|X>tEQ1YL@b+QZ}3$) % Code from Z^2 to N with `G` replaced by `@` (current tuple)
XJ % Copy result into clipboard J
Eqt1YLJ=2#fhw2/k-q % Code from N to Z^2 with `G` replaced by `J`
@!X= % Compare original tuple with recovered tuple: are they equal?
```
[Answer]
## JavaScript (ES6), 171 bytes
```
(x,y)=>(h=x=>parseInt((x^x>>31).toString(2)+(x>>>31),4),h(x)*2+h(y))
x=>(h=x=>parseInt(x.toString(2).replace(/.(?!(..)*$)/g,''),2),i=x=>x<<31>>31^x>>>1,[i(h(x>>>1)),i(h(x))])
```
Bit twiddling: negative numbers have their bits flipped; each integer is then doubled, and 1 added if it was originally negative; the bits from the integers are then interleaved. The reverse operation deletes alternate bits, divides by 2, and flips all the bits if the value was negative. I could save 3 bytes by limiting myself to 15-bit values instead of 16-bit values.
```
f=(x,y)=>(h=x=>parseInt((x^x>>31).toString(2)+(x>>>31),4),h(x)*2+h(y))
g=x=>(h=x=>parseInt(x.toString(2).replace(/.(?!(..)*$)/g,''),2),i=x=>x<<31>>31^x>>>1,[i(h(x>>>1)),i(h(x))])
for(i=-100;i<=100;i++)for(j=-100;j<100;j++)if(g(f(i,j))[0]!=i||g(f(i,j))[1]!=j)alert([i,j])
```
[Answer]
# Jelly, ~~50~~ ~~48~~ ~~46~~ ~~45~~ ~~43~~ ~~40~~ 39 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
## Plane to line (~~18~~ ~~17~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)):
```
AḤ_<0$
+RS+
,Ñç/
```
[Try it online!](http://jelly.tryitonline.net/#code=QeG4pF88MCQKK1JTKwosw5HDpy8&input=&args=MQ+LTE)
## Line to plane (~~32~~ ~~30~~ ~~29~~ ~~27~~ ~~24~~ 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)):
```
HĊN⁸¡
³R‘R’U⁹¡F³ịÇ
ç1,¢
```
[Try it online!](http://jelly.tryitonline.net/#code=SMSKTuKBuMKhCsKzUuKAmFLigJlV4oG5wqFGwrPhu4vDhwrDpzEswqI&input=&args=Nw)
## Explanation:
I'll only explain `plane to line`, because `line to plane` is just its opposite.
Firstly, we convert each integer to a natural number, by the function `f(x) = 2*|x| - (x<0)`.
Then, we convert the two natural numbers to another two natural numbers, by the function `g(x,y) = (x+y,y)`.
Finally, we convert them into one natural number, by the function `h(x,y) = (x+1)C2 + y`
] |
[Question]
[
# Your challenge:
You are on the 0th floor of a infinitely tall building. At any floor, you can walk to the window and drop an egg. Your goal is to figure out the highest floor that the egg can withstand without breaking. However, you have a maximum of 3 eggs to use to figure this out, but you need to minimize the number of tries.
In formal terms:
1. You are given a function `f(n)` which returns `bool(n <= X)` for an unknown `X`, where `0 <= X`
2. You must return the value of `X` (without accessing it directly)
3. `f(n)` must only return `False` a maximum of `3` times (in a single test case). If it returns `False` more than that, then your answer is disqualified.
# Restrictions
Your score is the total number of calls you make to `f(n)` (in the test cases below)
If you wish, you may forgo passing in a function, and simply "simulate" the above situation. **However**, your solving algorithm *must* know nothing of `X`.
Your algorithm should not hard code the test cases, or a maximum `X`. If I were to regenerate the numbers, or add more, your program should be able to handle them (with a similar score).
If your language doesn't support arbitrary precision integers, then you may use the `long` datatype. If your language doesn't support either, then you are out of luck.
The nth [test case is generated](https://gist.github.com/nathanmerrill/a10a917f2f8d64a39c49) using the following:
`g(n) = max(g(n-1)*random(1,1.5), n+1), g(0) = 0`, or approximately `1.25^n`
# Test cases:
```
0,1,2,3,4,6,7,8,10,14,15,18,20,27,29,40,57,61,91,104,133,194,233,308,425,530,735,1057,1308,1874,2576,3162,3769,3804,4872,6309,7731,11167,11476,15223,15603,16034,22761,29204,35268,42481,56238,68723,83062,95681,113965,152145,202644,287964,335302,376279,466202,475558,666030,743517,782403,903170,1078242,1435682,1856036,2373214,3283373,4545125,6215594,7309899,7848365,8096538,10409246,15103057,20271921,22186329,23602446,32341327,33354300,46852754,65157555,93637992,107681394,152487773,181996529,225801707,324194358,435824227,579337939,600264328,827690923,1129093889,1260597310,1473972478,1952345052,1977336057,2512749509,3278750235,3747691805,5146052509
```
This is a [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), and the person with the lowest score wins!
[Answer]
# Javascript, ~~442859~~ ~~442857~~ 74825 calls
```
function findFloor(f){
var max = 1;
var min = 0;
//First egg.
var n = 1;
while (f(max)) {
min = max;
n += 1;
max = tetrahedral(n);
}
if (max <= min + 1){
return min;
}
//Second egg.
do {
var range = max - min;
var floor = min + reverseTriangle(range);
var smashed = !f(floor);
if (smashed) {
max = floor;
} else {
min = floor;
}
} while (!smashed && max > min + 1);
if (max <= min + 1){
return min;
}
//Third egg.
while (max > min + 1){
var floor = min + 1;
var smashed = !f(floor);
if (smashed) {
max = floor;
} else {
min = floor;
}
if (smashed) {
break;
}
}
return min;
}
function reverseTriangle(x) {
return Math.ceil((-1 + Math.sqrt(1 + 8 * x)) / 2);
}
function tetrahedral(n) {
return n * (n + 1) * (n + 2) / 6;
}
```
[Test here](https://jsfiddle.net/hboko31k/4/)
Scores for each individual test case:
```
0: 1, 1: 4, 2: 4, 3: 3, 4: 5, 6: 6, 7: 6, 8: 6, 10: 6, 14: 7, 15: 8, 18: 8, 20: 7, 27: 10, 29: 9, 40: 12, 57: 10, 61: 14, 91: 16, 104: 16, 133: 16, 194: 17, 233: 16, 308: 24, 425: 26, 530: 28, 735: 31, 1057: 33, 1308: 38, 1874: 32, 2576: 47, 3162: 45, 3769: 43, 3804: 55, 4872: 52, 6309: 63, 7731: 69, 11167: 69, 11476: 80, 15223: 90, 15603: 75, 16034: 82, 22761: 69, 29204: 110, 35268: 101, 42481: 105, 56238: 126, 68723: 113, 83062: 113, 95681: 160, 113965: 149, 152145: 148, 202644: 187, 287964: 238, 335302: 175, 376279: 258, 466202: 250, 475558: 247, 666030: 256, 743517: 237, 782403: 245, 903170: 278, 1078242: 256, 1435682: 408, 1856036: 304, 2373214: 401, 3283373: 286, 4545125: 328, 6215594: 510, 7309899: 616, 7848365: 458, 8096538: 683, 10409246: 754, 15103057: 787, 20271921: 653, 22186329: 957, 23602446: 754, 32341327: 1141, 33354300: 1033, 46852754: 984, 65157555: 839, 93637992: 1539, 107681394: 1130, 152487773: 1605, 181996529: 1845, 225801707: 1760, 324194358: 2346, 435824227: 2244, 579337939: 2670, 600264328: 2620, 827690923: 3047, 1129093889: 3334, 1260597310: 3813, 1473972478: 4076, 1952345052: 3946, 1977336057: 3599, 2512749509: 4414, 3278750235: 3600, 3747691805: 5580, 5146052509: 4751
```
### How it works:
**1 egg:**
When there is one egg, the best strategy is to go up 1 floor at a time and return the floor directly below the floor where it breaks first.
**2 eggs:**
When we have two eggs, the maximum number of floors we have to check will be the smallest n for which Tn is greater than the range of floors we have to check. Tn is the nth triangle number. The first throw will be done on the nth floor. The second throw will be done `n - 1` floors above the first throw. The mth throw will be done `n - m + 1` floors above the `m - 1`th throw. After the egg smashes, it will take `n - m` throws to determine the floor by the first method.
**3 eggs:**
With the first of our eggs we should determine an upper limit for the highest floor. Originally, I did this by doubling the floor number each time. After analyzing the algorithm for 2 eggs I thought that maybe it would be better if each time we throw the egg, the max throws for finding the correct floor with 2 eggs would increase by 1. This can be satisfied by using the tetrahedral numbers. After the first egg smashes, we can use the above methods for our remaining eggs.
The max egg drops it requires to determine the floor should be optimal. However, a better algorithm could probably be found where the average egg drops is better.
[Answer]
## Java, 68985 calls
```
public static long solve(Predicate<Long> eggSurvives) {
long bestFloor = 0, e1 = 1, e2;
for(long callsDone = 2; eggSurvives.test(e1); bestFloor = e1, e1 += callsDone * callsDone++);
for(e2 = bestFloor;; bestFloor = e2) {
e2 += Math.max((long)Math.sqrt(e1 - e2), 1);
if(e2 >= e1 || !eggSurvives.test(e2)) {
break;
}
}
for(long e3 = bestFloor + 1; e3 < e2 && eggSurvives.test(e3); e3++) {
bestFloor = e3;
}
return bestFloor;
}
```
Test results:
```
0: 1 1: 4 2: 4 3: 4 4: 4 6: 6 7: 6 8: 6 10: 7 14: 6 15: 7 18: 7 20: 8 27: 10 29: 10 40: 10 57: 10 61: 9 91: 9 104: 11 133: 18 194: 20 233: 18 308: 18 425: 17 530: 17 735: 28 1057: 31 1308: 30 1874: 30 2576: 39 3162: 47 3769: 60 3804: 34 4872: 65 6309: 37 7731: 48 11167: 79 11476: 39 15223: 56 15603: 82 16034: 93 22761: 88 29204: 111 35268: 110 42481: 127 56238: 126 68723: 135 83062: 117 95681: 115 113965: 137 152145: 138 202644: 115 287964: 234 335302: 223 376279: 244 466202: 220 475558: 193 666030: 214 743517: 225 782403: 230 903170: 338 1078242: 223 1435682: 303 1856036: 384 2373214: 453 3283373: 542 4545125: 459 6215594: 525 7309899: 600 7848365: 388 8096538: 446 10409246: 466 15103057: 650 20271921: 822 22186329: 899 23602446: 698 32341327: 804 33354300: 1065 46852754: 1016 65157555: 1408 93637992: 1390 107681394: 1638 152487773: 1283 181996529: 1877 225801707: 2067 324194358: 1842 435824227: 3110 579337939: 2983 600264328: 1817 827690923: 2450 1129093889: 2981 1260597310: 3562 1473972478: 4237 1952345052: 2244 1977336057: 3585 2512749509: 2893 3278750235: 3101 3747691805: 5182 5146052509: 4107
```
Test program:
```
import java.util.function.Predicate;
public class Eggs {
private static long totalCalls;
private static long calls;
public static void main(String[] args) {
for(long maxFloor : new long[] {0,1,2,3,4,6,7,8,10,14,15,18,20,27,29,40,57,61,91,104,133,194,233,308,425,530,735,1057,1308,1874,2576,3162,3769,3804,4872,6309,7731,11167,11476,15223,15603,16034,22761,29204,35268,42481,56238,68723,83062,95681,113965,152145,202644,287964,335302,376279,466202,475558,666030,743517,782403,903170,1078242,1435682,1856036,2373214,3283373,4545125,6215594,7309899,7848365,8096538,10409246,15103057,20271921,22186329,23602446,32341327,33354300,46852754,65157555,93637992,107681394,152487773,181996529,225801707,324194358,435824227,579337939,600264328,827690923,1129093889,1260597310,1473972478,1952345052,1977336057,2512749509L,3278750235L,3747691805L,5146052509L}) {
long resultingFloor = solve(f -> {
calls++;
return f <= maxFloor;
});
if(resultingFloor != maxFloor) {
throw new RuntimeException("Disqualified");
}
System.out.print(maxFloor + ": " + calls + " ");
totalCalls += calls;
calls = 0;
}
System.out.println("\nCalls = " + totalCalls);
}
public static long solve(Predicate<Long> eggSurvives) {
long bestFloor = 0, e1 = 1, e2;
for(long callsDone = 2; eggSurvives.test(e1); bestFloor = e1, e1 += callsDone * callsDone++);
for(e2 = bestFloor;; bestFloor = e2) {
e2 += Math.max((long)Math.sqrt(e1 - e2), 1);
if(e2 >= e1 || !eggSurvives.test(e2)) {
break;
}
}
for(long e3 = bestFloor + 1; e3 < e2 && eggSurvives.test(e3); e3++) {
bestFloor = e3;
}
return bestFloor;
}
}
```
While optimizing I aimed for trying to make the number of attempts with each egg roughly equal.
* The first egg goes up in number of floors based on the number of attempts so far.
* The second egg skips floors based on the square root of the maximum number of attempts that could be left (based on the lower and upper bound established by the first egg) so that the average number of attempts for the 3rd and final egg should on average be the same as attempts for the 2nd egg.
[Answer]
# Ruby, ~~67466~~ 66026 calls
```
$calls = 0
def drop n
$calls += 1
n <= $x
end
def test
min = 0
test = 8
i = 8
while drop(test)
min = test
test += i*i
i+=1
end
max = test
test = min+((max-min)**0.4).to_i
while drop(test)
min = test
test = min+((max-min)**0.5).to_i
end
return min if min+1 == test
min += 1 while drop(min+1)
min
end
```
Test code:
```
tests = [0,1,2,3,4,6,7,8,10,14,15,18,20,27,29,40,57,61,91,104,133,194,233,308,425,530,735,1057,1308,1874,2576,3162,3769,3804,4872,6309,7731,11167,11476,15223,15603,16034,22761,29204,35268,42481,56238,68723,83062,95681,113965,152145,202644,287964,335302,376279,466202,475558,666030,743517,782403,903170,1078242,1435682,1856036,2373214,3283373,4545125,6215594,7309899,7848365,8096538,10409246,15103057,20271921,22186329,23602446,32341327,33354300,46852754,65157555,93637992,107681394,152487773,181996529,225801707,324194358,435824227,579337939,600264328,827690923,1129093889,1260597310,1473972478,1952345052,1977336057,2512749509,3278750235,3747691805,5146052509]
tests.each{|n|$x = n;test;$calls}
puts $calls
```
Results:
```
0: 3, 1: 4, 2: 4, 3: 5, 4: 5, 6: 5, 7: 6, 8: 4, 10: 6, 14: 6, 15: 7, 18: 10, 20: 6, 27: 7, 29: 9, 40: 10, 57: 13, 61: 15, 91: 13, 104: 13, 133: 15, 194: 12, 233: 18, 308: 16, 425: 15, 530: 15, 735: 16, 1057: 32, 1308: 30, 1874: 35, 2576: 35, 3162: 54, 3769: 32, 3804: 29, 4872: 45, 6309: 42, 7731: 55, 11167: 72, 11476: 60, 15223: 55, 15603: 71, 16034: 94, 22761: 82, 29204: 119, 35268: 106, 42481: 123, 56238: 127, 68723: 110, 83062: 95, 95681: 139, 113965: 149, 152145: 149, 202644: 144, 287964: 219, 335302: 189, 376279: 183, 466202: 234, 475558: 174, 666030: 235, 743517: 195, 782403: 235, 903170: 346, 1078242: 215, 1435682: 245, 1856036: 422, 2373214: 448, 3283373: 512, 4545125: 378, 6215594: 502, 7309899: 486, 7848365: 440, 8096538: 496, 10409246: 566, 15103057: 667, 20271921: 949, 22186329: 829, 23602446: 746, 32341327: 799, 33354300: 964, 46852754: 1125, 65157555: 1317, 93637992: 1000, 107681394: 1361, 152487773: 1215, 181996529: 2004, 225801707: 1752, 324194358: 1868, 435824227: 3084, 579337939: 2592, 600264328: 1726, 827690923: 2577, 1129093889: 3022, 1260597310: 2582, 1473972478: 3748, 1952345052: 2035, 1977336057: 3712, 2512749509: 2859, 3278750235: 2888, 3747691805: 5309, 5146052509: 4234
```
This algorithm works like my old algorithm, but has a few differences:
1. The first egg drop is at floor 8
2. The first increment is 8\*8 = 64
These numbers are a result of random fine tuning by hand.
] |
[Question]
[
Inspired by <http://xkcd.com/1331/>
In this xkcd comic, there are several gifs that all blink with different frequency. I want to know what the period would be if was all a single GIF. Given a list of numbers representing the individual frequencies, output the period of the overall GIF.
**Formal Definition**
Input:
```
N
f1
f2
.
.
.
fN
```
Output:
```
P
```
Where N is the number of frequencies, fi is the ith frequency, and P is the resulting period of the total GIF.
You may choose to use any delimiting character you want(instead of \n), and you may exclude the N if you wish, and it will be inferred by the number of delimeters.
**Some specifics**
Frequencies are the closest double-precision floating point representation of the numbers provided as input.
The outputted period is a 64-bit unsigned integer, rounded(up on 0.5) to the nearest whole. Any input that would produce a period bigger than 2^64-1 is considered undefined behaviour.
Likewise any input <= 0 is considered undefined behaviour.
**Win Condition**
Code golf so shortest code wins!
[Answer]
# APL, 4
```
∧/∘÷
```
`∧` is both logical AND and numerical LCM (with domain over integers, floats, complex, rationals, whatever number stack is supported by the APL implementation) so `∧/` is reduction by LCM, or computing the LCM of an array.
Monadic `÷` is numeric inverse. So the composition `∧/∘÷` is the LCM of the inverses of the numbers supplied.
The other formula, inverse of the GCD, would be `÷∘(∨/)`, where the parentheses are needed to fix the precedence between `∘` and `/`.
You can try it online on <http://tryapl.com/>
**Examples**
```
∧/∘÷ .12 .02 3.9 .15 .99
100
∧/∘÷ (16÷5)(2÷3)(2.35)(1÷7)
420
```
[Answer]
# Mathematica ~~43~~ 28
## Second try
My first attempt was not correct, although it did have some of the necessary ingredients (LCM,Rationalize). The complete solution requires taking into account both the numerator and denominator of each frequency (expressed as a common fraction).
`l` is the list of frequencies.
Rationalizing 2.35 converts it to the common fraction 235/100.
```
f@l_:=LCM@@(1/Rationalize@l)
```
Assume that all GIFs fire at t=0.
The following approach does not require that the frequencies be expressed as "real numbers", ie. as decimal fractions. They may be other sort of fractions. The example below is a case where the fractions are in fifths, thirds, hundredths and sevenths.
If two or more frequencies are incommensurate (in which case at least one must be an irrational number) then there is no solution. In other words, there will be no point in time, t>0, at which all components fire at the same time.
**Example1**
```
f[{50, 10}]
```
>
> 1/10
>
>
>
---
**Example 2**
```
f[{16/5, 2/3, 2.35, 1/7}]
```
>
> 420
>
>
>
If we multiply the least overall period by each of the frequencies, we find a whole number of cycles in each case:
```
420*{16/5, 2/3, 2.35, 1/7}
```
>
> {1344, 280, 987., 60}
>
>
>
(1344 hops of 16/5 units) lands at 420.
(280 hops of 2/3 units) lands at 420.
(987 hops of 2.35 units) lands at 420.
(60 hops of 7 units) lands at 420.
[Answer]
## Javascript: 191 characters
The input format that I chose (within the rules) is the frequency numbers separated by commas. No spaces allowed and no newlines. The initial N must not be given. Each number must be just a serie of at least one [0-9] digits with an optional dot somewhere within. If the input is malformed, the behaviour is undefined.
**How it works:**
>
> The period of some integer frequency numbers is the GCD of these numbers. If the given numbers are not integer, it sucessively multiplies they by 10 until it gets everything as an integer number (this exploit the fact that the non-integer numbers are given in base 10). After calculating the GCD, it divides the result by the power of ten used to multiply the input numbers, and hence getting the overall frequency. Inverting this we get the period.
>
>
> *Note: I am pretty sure that now that I gave this answer, somebody will code the same in APL or J and beat it. :(*
>
>
>
**The code:**
```
d=1,s=prompt().split(",");for(a in s){s[a]=parseFloat(s[a]);while(s[a]*d%1>0)d*=10}g=s[0]*d;for(a in s){u=g;v=s[a]*=d;p=2;q=1;while(u>=p&v>=p)if(u%p|v%p)p++;else{u/=p;v/=p;q*=p}g=q}alert(d/g)
```
**Testing it:**
```
Input: 50,10
Output: 0.1
Interpretation: One GIF blinks 10 times per second (period = 0.1s) and the other 50 times (period = 0.02s). So a combined GIF would repeat itself in 0.1 seconds.
Input: 2.7,3.4
Output: 10
Interpretation: One blinking at 2.7 times per second will blink 27 times in 10 seconds. One blinking 3.4 times per second will blink 34 times in 10 seconds. So, 10 seconds is a period, and since GCD(27,34)=1, it is the smallest.
Input: 4.8,7.2
Output: 0.4166666666666667
Interpretation: One blinking at 4.8 times per second and the other at 7.2 times per second, gives a frequency of 2.4 times per second, which is a period 0.41666... seconds.
Input: 0.6,12,7.9,4.33
Output: 100
Interpretation: Similar to second case. 60, 1200, 790 and 433 times each 100 seconds. The GCD of these numbers is 1.
Input: 400,200,25,350
Output: 0.04
Interpretation: The slowest is the 25 times per second, which is the overall frequency. 25 times per second is a period of 0.04 seconds.
Input: 440,200,35,360
Output: 0.2
Interpretation: In 0.2 seconds, we have 88, 40, 7 and 72 blinks.
```
] |
[Question]
[
Write an expression evaluator for boolean expressions encoded as JSON. Read on for explanation and rules.
**Motivation:**
Consider a scenario where two agents ([Alice and Bob](http://imgs.xkcd.com/comics/protocol.png)) are communicating with each other under the following constraints:
* All communication must be done as valid [JSON](http://en.wikipedia.org/wiki/JSON) strings (no JSONP or extensions), because Bob and Alice ***love*** JSON. They have had problems with character encoding in the past, so they have decided to restrict themselves to ASCII.
* Alice needs Bob to notify her in case a certain condition is met, **but**:
+ Bob doesn't know what the condition is in advance.
+ Alice can't evaluate the condition herself because it requires information that only Bob has.
+ The status of the variables can change rapidly enough (and the network is slow enough) that it would be infeasible for Bob to continuously transmit the data to Alice.
* Neither knows anything about the implementation of the other agent (for example, they can't make assumptions about the implementation language of the other agent).
Alice and Bob have worked out a protocol to help them complete their task.
**Representing Conditional Expressions:**
1. They have agreed to represent Boolean literals by strings, for example `"foo"` or `"!bar"`, where `!` represents the negation of a literal, and valid names contain only letters and numbers (case sensitive, any strictly positive length; `""` and `"!"` are not valid; i.e. a literal is a string whose contents match the regex `/^!?[a-zA-Z0-9]+$/`).
2. Expressions are only transmitted in [negation normal form](http://en.wikipedia.org/wiki/Negation_normal_form). This means that only literals can be negated, not subexpressions.
3. Expressions are normalized as a conjunction of disjunctions of conjunctions of disjunctions ... etc encoded as nested arrays of strings. This needs a bit more explanation, so...
**Expression Syntax:**
Consider the following boolean expression:
```
(¬a ∧ b ∧ (c ∨ ¬d ∨ e ∨ ¬f) ∧ (c ∨ (d ∧ (f ∨ ¬e))))
```
Notice that the entire expression is contained in parentheses. Also notice that the first level(and all odd levels) contains only conjunctions(∧), the second level(and all even levels) contains only disjunctions(∨). Also notice that no subexpression is negated. Anyway meat and potatoes... This would be represented by Alice in JSON as:
```
["!a","b",["c","!d","e","!f"],["c",["d",["f","!e"]]]]
```
Another example:
```
((a ∨ b ∨ c))
```
Becomes:
```
[["a","b","c"]]
```
In summary: `[]` are interpreted as parentheses, literals are wrapped in `""`,`!` means negation, and `,` means `AND` or `OR` depending on nesting depth.
**NB: the empty conjunction (the result of `AND`ing no variables) is `true`, and the empty disjunction (the result of `OR`ing no variables) is `false`. They are both valid boolean expressions.**
**Bob's data:**
Bob's data is emitted by a program on his computer as a simple JSON object as key-value pairs, where the key is the name of the variable, and the value is either `true` or `false`. For example:
```
{"a":false,"b":true,"c":false}
```
## Bob needs our help!
Bob has little programming experience, and he's in over his head. He has handed you the task.
You need to write a program that accepts the JSON text that Alice sent along with the JSON text for Bob's data, and evaluates the expression with those values, returning true or false (**the actual strings `true` and `false`**; Bob and Alice love JSON, remember?)
* Bob says less is more, so he wants you to make your source code as short as possible (this is a code-golf)
* You are allowed to use an external library to parse the JSON text, but this is the only exception. Only standard library functionality is allowed.
* Note that the JSON is accepted and returned as a **string**. There is no requirement to explicitly parse it though, if you can get it to always work without doing so.
* If Alice uses a variable that Bob doesn't know, assume it is false. Bob's data may contain variables that Alice doesn't use.
* If Alice's or Bob's JSON Object contains an invalid literal, or the JSON is invalid, or it contains a non ASCII character, then your program **must** return `null`
**Some test cases(in JSON):**
```
[
{"alice":"[\"\"]","bob":"{}","result":"null"},
{"alice":"[\"!\"]","bob":"{}","result":"null"},
{"alice":"[\"0\"]","bob":"{\"0\":true}","result":"true"},
{"alice":"[]","bob":"{}","result":"true"},
{"alice":"[[]]","bob":"{}","result":"false"},
{"alice":"[\"a>\"]","bob":"{\"a\":true}","result":"null"},
{"alice":"[\"0\"]","bob":"{}","result":"false"},
{"alice":"[\"0\"]","bob":"","result":"null"},
{"alice":"[\"1\"]","bob":"{\"1\":false}","result":"false"},
{"alice":"[\"true\"]","bob":"{\"true\":false}","result":"false"},
{"alice":"[\"foo\",\"bar\",\"baz\"]","bob":"{\"foo\":true,\"bar\":true,\"biz\":true}","result":"false"},
{"alice":"[[[\"a\",[\"!b\",\"c\"],\"!c\"],\"d\"]]","bob":"{\"a\":true,\"b\":false,\"c\":true,\"d\":false}","result":"false"},
{"alice":"[\"!a\",\"b\",[\"c\",\"!d\",\"e\",\"!f\"],[\"c\",[\"d\",[\"f\",\"!e\"]]]]","bob":"{\"a\":false,\"b\":true,\"c\":true,\"e\":true,\"f\":false}","result":"true"}
]
```
As can be seen from the test cases, input and output are **strings** that are correctly parseable JSON. The empty string test case for `bob` was originally in error, the correct value to return is `null`, but if it saves you characters to return `false`, then that is also acceptable. I added cases for the empty clauses to make that explicit. I added another 2 test cases in response to a bug I found in someone's implementation
[Answer]
## ECMASCript 6 variation, ~~213 194 190 189 192~~ 166 chars
```
try{P=_=>JSON.parse(prompt())
B=P()
f=(a,c)=>a[c?'some':'every'](v=>v.big?[B][+/\W|_/.test(s=v.slice(C=v[0]=='!'))-!s][s]^C:f(v,!c))
q=f(P())}catch(_){q=null}alert(q)
```
Note: takes Bob's input *first*, and *then* Alice's input. This saves us four bytes.
* Checks for syntactically valid JSON since `JSON.parse` throws if it isn't.
* Since we're already relying on the try-catch for the above, we (ab)use out-of-bounds access to trigger our "failed validation" path when validating the (possibly negated) literals
+ This is accomplished with the `[B][...][s]` part (thanks, @l4m2! used to use a slightly more verbose construction)
+ The `-!s` is to catch `""` and `"!"` as invalid literals
+ The `C` variable holds the "should negate" state, which is accomplished with a "bitwise" XOR (and relies on implicit type coercion)
---
ES5 solution: <https://codegolf.stackexchange.com/revisions/19863/8>
[Answer]
# Ruby, 335 (327?) characters
```
begin;a,b=*$<;require'json';b=JSON[b];q if a=~/{|}/||!a[?[]||b.any?{|v,x|v=~/[\W_]/||x!=!!x}
l=0;a.gsub!(/\[|\]/){"[{}]"[($&==?]?2:0)+l=1-l]};a.gsub!(/"(!)?([a-z\d]+)"/i){b[$2]^$1}
0 while [[/\[[#{f=!1},\s]*\]/,f],[/{[#{t=!f},\s]*?}/,t],[/\[[\w,\s]*\]/,t],[/{[\w,\s]*}/,f]].any?{|k,v|a.sub!(k){v}}
rescue a=??;end;puts a=~/\W/?"null":a
```
I've heard you can't parse HTML with Regex, but I've never been told you cannot parse JSON this way, so I tried.
Alice's input is separated from Bob's input by a newline; also, it's assumed that neither input contains newlines itself. This assumption is for I/O purposes only, and is not used later. If I can make an extra assumption that Alice's input contains *no* whitespace, we can drop **8 characters** by removing all `\s`'s on line #3. If we can only assume it contains no whitespace but spaces, we can still replace `\s`'s with the space characters to save 4 characters.
[Answer]
**Python 3 (429)**
Longer than the other answers, but arguably the most readable so far... :)
```
import json,sys,re
r,p,m='^!?[a-zA-Z\d]+$',print,re.match
def g(a,b,s):
if type(a)is str:
if m(r,a):
try:return('not '+str(b[a[1:]]))if a[0]=='!'else str(b[a])
except:return'False'
raise Exception
return'('+((' and 'if s else' or ').join(g(x,b,not s)for x in a))+')'
s,j=sys.argv,json.loads
try:
a,b = j(s[1]),j(s[2]or'{}');
if all(m(r,x)and x[0]!='!'for x in b):p(str(eval(g(a,b,1))).lower())
except:
p('null')
```
[Answer]
**Node.JS (~~331 335 310~~ 296)**
As a starting point, manually minified, could definitely be improved a bit;
it basically just "brute force" evaluates the expression;
As a golf hack restriction, the variable `y` can not be defined or it won't work :)
```
r=/^[a-z\d]+$/i;function g(a,b,s,c){c=s;for(k in a){if((k=a[k]).trim){k=k.slice(i=k[0]=='!');
if(!k.match(r))y;k=i?!b[k]:b[k]}else{k=g(k,b,!s)}c=s?c&k:c|k}return!!c;}z=process.argv;a=z[2]
;b=z[3];try{p=JSON.parse;l=console.log;a=p(a);b=p(b);for(k in b)if(!k.match(r))y;l(g(a,b,1))}
catch(e){l(null)}
```
Called with `alice` as first argument, `bob` as second argument, outputs result to stdout.
EDIT: Shrunk the code a little with the help of @FireFly and by removing support for "empty bob".
[Answer]
# JavaScript, 178 bytes
Optimized from Tim Seguine's answer
```
try{P=JSON.parse,p=prompt;A=P(p());B=P(p());f=(a,c)=>a.map(v=>v.big?[B][/\W|_/.test(s=v.replace(/^!/,''))-!s][s]^s>v:f(v,!c))[c?'some':'every'](P);q=f(A)}catch(_){q=null}alert(q)
```
[Try it online!](https://tio.run/##lVRNb5swGL7zKwzShK0SkvawQ5BTtccdtkqbtINDK@OYhIkAsR3UNuO3p8YOS0OJlp5ev5/P87w2/KE1lUxklRoV5YLvf3GpJMCA1zSHxAE7j@YZ497UI3Nv7sVe4CVlot1do4@Cy22utFds89xrgl69@9mGyUmD8adKbPlJaxvot56DGaol8bnqlOaSf2RFZz1adIjWJYouQTvp@D/AdY@b9qdm8iVYrYhevw1dPiIty7kXzL2EioN97U00FWZfXdk/J3sd2uQgEiFm70H7rBKDxDSONu7BLrQZvKUWqFNk27rw4jNCXWr1WQ7MOO7CGG6dtCVyyBEzvTWpTbZ7jj8S7FglR1bvCPLjMR3kat@3E6PIqUS5rlRWLPXXO4mcdFswlZUFsHGIwA44AGQpgFdXx9ov4EZndAIAwdVWFMD8AcgkDo32SKcawDXumSqtxtQ4jUNzLpRG76Dhsx3NykKWOQ/zcgkgOZ0fnEx651mJAXhutQEbD@UqSxWAJtIqsdGcF0u1AljrRqAjcf01chq9hlJAVih8M4mAtqNRBNBur8TL7gF/@/nje1hRoS@gwnYl0R1@gBVEKLrvDimGNGAIz2i4phWs8awOk2x5S@5jMp7//vs0DpWmASWuNekqp4zD8aM7DnwfoZErYyLjRzmrpymsA5chRNitL8s196c@r7l48WP4gKINTuEdahhVbAWf0G6D2@@9MXLgBu2b/Rs "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
For reference to the game of Mastermind: [Solving Mastermind in 6 or less moves](https://codegolf.stackexchange.com/questions/5226/solving-mastermind-in-6-or-less-moves)
In the version of Mastermind used in this problem, the operating string is a 4-digit number, from 0000 to 9999, represented as either numbers from `0` to `9999` or strings of consecutive digits `"0000"` to `"9999"` in input.
Your task is to build a function that will take two numbers/strings `secret` and `guess` as input, and return two numbers `A` and `B`, the number of red and white pegs respectively.
The shortest code in any language to do this wins.
[Answer]
# J: 40 26 29 22
```
=,&(+/)(~:#[)e.&~.~:#]
```
* *change*: don't laminate, but work truly dyadically, eliminating need for explicit ranks ("1), lamination(,:) and between (/)
* *change*: don't count duplicate characters twice
* *change*: Strings are more efficient as they don't need parsing
This verb takes a left and right argument a string from '0000' to '9999'.
It takes care of doubles and excludes exact matches from checking correct numbers but wrong place.
Test cases:
```
NB. Give the beast a name
mm=: =,&(+/)(~:#[)e.&~.~:#]
NB. make 6 by 4 arrays of the inputs
secret =: (, ;. _2) '1254 1234 5441 5441 5441 5441 '
guess =: (, ;. _2) '1342 1111 1234 4531 4441 5441 '
NB. Apply the verb on each pair of secret/guess
'1111' mm '1231'
2 0
NB. A whole bunch of test cases with formatting and printing of the inputs:
secret ([,' ',(":@mm),' ',])"1 guess
NB. output:
1254 1 2 1342
1234 1 0 1111
5441 0 2 1234
5441 1 2 4531
5441 3 0 4441
5441 4 0 5441
```
A little bit of explanation, reading from right to left:
```
NB. ExactMatch: checks where digits correspond:
ExactMatch =: =
NB. GoodDigitWrongPlace: Copies non-matched numbers from both arguments (left and right
NB. pairs of parentheses, and checks them for same elements(e.), after eliminating
NB. doubles in both (&~.)
GoodDigitWrongPlace =: (~: # [) (e.&~.) (~: # ])
NB. Piecing the conditions together, after summing the booleans:
mm =: ExactMatch ,&(+/) GoodDigitWrongPlace
```
[Answer]
# K, ~~41~~ 36
```
{+/'(b;(in).(?x;y)@\:(!#x)@&~b:x=y)}
```
.
```
k)c1:("1254";"1234";"5441";"5441";"5441";"5441")
k)c2:("1342";"1111";"1234";"4531";"4441";"5441")
k){+/'(b;(in).(?x;y)@\:(!#x)@&~b:x=y)}'[c1;c2]
1 2
1 0
0 2
1 2
3 0
4 0
```
[Answer]
## Ruby 2.0, 71 characters
```
f=->s,g{[x=(0..3).count{|n|s[n]==g[n]},g.chars.count{|e|s.sub!e,''}-x]}
```
This function actually modifies the first parameter, which is obviously a bit dodgy. Would be easy enough to fix if it's actually against the rules.
I'm sure there's something sneaky you could do with `String#count` but I couldn't think of a nice way to handle duplicates.
Example usage:
```
p f['1254', '1342'] #=> [1, 2]
p f['1234', '1111'] #=> [1, 0]
p f['5441', '1234'] #=> [0, 2]
p f['5441', '4531'] #=> [1, 2]
p f['5441', '4441'] #=> [3, 0]
p f['5441', '5441'] #=> [4, 0]
```
[Answer]
### GolfScript, 50 characters
```
{[[\].zip{1/~=},,\{$}/{1$?.)!!{)>0}*)},,\;1$-]}:M;
```
A similar solution to [chron's answer](https://codegolf.stackexchange.com/a/12490) written in GolfScript. Input must be provided as two strings on the stack, the result will be the array `[A B]`.
[Examples](http://golfscript.apphb.com/?c=e1tbXF0uemlwezEvfj19LCxceyR9L3sxJD8uKSEheyk%2BMH0qKX0sLFw7MSQtXX06TTsKCiIxMjU0IiAiMTM0MiIgTSBwICAgICMgPT4gWzEgMl0KIjEyMzQiICIxMTExIiBNIHAgICAgIyA9PiBbMSAwXQoiNTQ0MSIgIjEyMzQiIE0gcCAgICAjID0%2BIFswIDJdCiI1NDQxIiAiNDUzMSIgTSBwICAgICMgPT4gWzEgMl0KIjU0NDEiICI0NDQxIiBNIHAgICAgIyA9PiBbMyAwXQoiNTQ0MSIgIjU0NDEiIE0gcCAgICAjID0%2BIFs0IDBdCg%3D%3D&run=true):
```
"1254" "1342" M p # => [1 2]
"1234" "1111" M p # => [1 0]
"5441" "1234" M p # => [0 2]
"5441" "4531" M p # => [1 2]
"5441" "4441" M p # => [3 0]
"5441" "5441" M p # => [4 0]
```
[Answer]
## GolfScript (48 chars)
```
{[\]:&zip{1/~=},,.~)10,{{''+-,~5+}+&%.~>=+}/}:E;
```
`E` here stands for `eval`. I take a similar approach to Knuth's definition of the number of white pegs by calculating `sum_{i=0}^{9} min(count(secret, i), count(guess, i))`.
[Online demo](http://golfscript.apphb.com/?c=e1tcXTomemlwezEvfj19LCwufikxMCx7eycnKy0sfjUrfSsmJS5%2BPj0rfS99OkU7Cgo7WwonMTI1NCcgJzEzNDInCSMgMSAyCicxMjM0JyAnMTExMScJIyAxIDAKJzU0NDEnICcxMjM0JwkjIDAgMgonNTQ0MScgJzQ1MzEnCSMgMSAyCic1NDQxJyAnNDQ0MScJIyAzIDAKJzU0NDEnICc1NDQxJwkjIDQgMAonMDAxMScgJzExMDAnCSMgMCA0Cl0yL3t%2BRV1wfS8%3D)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 17 bytes
```
=s,4Y2@G!=s]Xlsy-
```
[Try it online](https://matl.suever.net/?code=%3Ds%2C4Y2%40G%21%3Ds%5DXlsy-&inputs=%271444%27%0A%274241%27&version=22.4.0) ([Tested multiple inputs with this](https://tio.run/##y00syfmfkKlQkldnrxerYBjho5CpYBTh89@2WMck0sgh0EfRtjg2Iqe4Uve/uq6urnqEi0JUhUJI7H91QyNTE3UudUNjEyMQZWQM5gEBkDI1MTFECEJ5JqbGSHImEMoUhVIHAA "MATL – Try It Online"))
**Explanation**:
(For white pegs, Knuth's definition [as mentioned by Peter Taylor](https://codegolf.stackexchange.com/a/12496/8774) is used: `sum_{i=0}^{9} min(count(secret, i), count(guess, i))`)
```
= % check which digits are equal
s % sum of 1s is the number of red pegs
, % do twice
4Y2 % predefined literal: '0':'9'
@G % get the next input
!= % broadcast equality check
s % sum to get the count of each digit in the input
] % end
Xl % elementwise minimum
s % sum
y- % subtract the number of red pegs
% (implicit) convert to string and display
```
[Answer]
# Python - 93
I'm pretty sure this is right. But a few example input/outputs in the question would help.
```
def m(S,G):
R = [(s,g) for s,g in zip(S,G) if s!=g];S,G=zip(*R);W=set(S)&set(G);return 4-len(R),len(W)
```
And calling it gives:
```
print m('1234','1231')
>>> (3, 0)
print m('1234','1230')
>>> (3, 0)
print m('1234','1243')
>>> (2, 2)
print m('1234','4312')
>>> (0, 4)
print m("0123","0131")
>>> (2, 1)
print m("0123","0132")
>>> (2, 2)
print m("0123","0123")
>>> (4, 0)
print m("0123","4131")
>>> (1, 1)
```
[Answer]
Here's a first draft in PowerShell: `168` characters.
```
function Test-Mastermind{param([char[]]$s,[char[]]$g)
4-($p=0..3|?{$s[$_]-ne$g[$_]}).Count
($p|%{$i=$_;$p|?{$s[$i]-eq$g[$_]-and0-ne$s[$i]}|%{($s[$i]=$g[$_]=0)}}).Count}
```
For the sake of illumination:
```
function Test-Mastermind {
param([char[]]$s,[char[]]$g)
4 - ($p = 0..3|?{ $s[$_] -ne $g[$_] }).count # count same characters
( $p | % { $i = $_ # ForEach $i in $p (char in secret)
$p | ? { # ForEach $_ in $p (char in guess)
$s[$i] -eq $g[$_] -and 0 -ne $s[$i] # If they match and aren't 0
} | % { ($s[$i]=$g[$_]=0) } # 0 them out, output something we can count
} ).Count
}
```
] |
[Question]
[
The type of regular expression is PCRE.
Write a program that output a valid PCRE such that it matches all natural numbers between `m` and `n` and does not match anything else. No leading zeros are allowed.
For example, let `m` and `n` be `123` and `4321`, then the program might output
`1(2[3-9]|[3-9]\d)|[2-9]\d\d|[123]\d\d\d|4([012]\d\d|3([01]\d|2[01]))`.
This matches the exact string, so `^` and `$` anchors are implicit.
One should try to balance the two:
1. The regular expression should have a reasonable size.
2. The code should be short.
Let's optimize for
`code length in characters` + 2\*`regular expression length for input 123456 and 7654321`
Side Note: It be interesting if we can prove the shortest PCRE regular expression is of the size O(log n log log n) or something.
[Answer]
**# Perl, score 455**
**191 chars, 132 regex length**
```
sub b{my$a=shift;$_=(@_>0&&$a.b(@_).($a-->0&&'|')).($a>=0&&($a>1
?"[0-$a]":$a));/\|/?"($_)":$_}sub a{b(@a=split//,<>-1+$x++).(@a>
1&&"|.{1,$#a}")}print'(?!0|('.a.')$)(?=('.a.'$))^\d{1,'.@a.'}$'
```
Input: `123456, 7654321`
```
(?!0|((1(2(3(4(5[0-5]|[0-4])|[0-3])|[0-2])|1)|0)|.{1,5})$)(?=((7(6(5(4(3(21|1)|[0-2])|[0-3])|[0-4])|[0-5])|[0-6])|.{1,6}$))^\d{1,7}$
```
**Update:** I was able to further simplify this when I realized that most of the patterns ended with things like `\d{3}`. These were doing nothing more than enforcing a string length--and doing so very repetitively, since they occurred on every term. I eliminated this by using another lookahead to enforce the "less than" condition, only checking that either: 1) the first part of the number does not exceed the input or 2) the number is fewer digits than the input. Then the main regex just verifies that it is not too many digits.
I also incorporated Peter Taylor's idea of negative look-ahead for checking the "greater than" condition.
The key to simplifying this problem (at least for me) was to break the regex in two: a look-ahead makes sure the number is not less than the minimum, then the main part of the regex checks that it is not greater than the maximum. It is a little bit silly for small input, but it is not so bad for large input.
Note: the `0|` at the beginning is to exclude anything that starts with a zero from matching. This is required because of the recursive nature of the regex function: inner parts of the match can start with zero, but the entire number cannot. The regex function can't tell the difference, so I excluded any number starting with zero as a special case.
Input: `1, 4`
```
(?!0|(0)$)(?=([0-4]$))^\d{1,1}$
```
Unreasonably Long Regex Version, 29 chars:
```
print'^',join('|',<>..<>),'$'
```
[Answer]
## Javascript, score 118740839
```
function makere(m,n){r='(';for(i=m;i<n;)r+=i+++'|';return (r+i)+')';}
```
I suppose whether or not you like this depends on how you define 'a reasonable size.' :-)
[Answer]
**Haskell 2063+2\*151=2365**
It's guaranteed the generated regex has length O(log n log log n).
`matchIntRange 12345 7654321`
`1(2(3(4(5[6-9]|[6-9]\d)|[5-9]\d\d)|[4-9]\d{3})|[3-9]\d{4})|[2-9]\d{5}|[1-6]\d{6}|7([0-5]\d{5}|6([0-4]\d{4}|5([0-3]\d{3}|4([012]\d\d|3([01]\d|2[01])))))`
```
import Data.Digits
data RegEx = Range Int Int | MatchNone | All Int
| Or RegEx RegEx | Concat [RegEx]
alphabet = "\\d"
instance Show RegEx where
show (Range i j)
| i == j = show i
| i+1 == j = concat ["[",show i,show j,"]"]
| i+2 == j = concat ["[",show i,show (i+1), show (i+2),"]"]
| otherwise = concat ["[",show i,"-",show j,"]"]
show (Or a b) = show a ++ "|" ++ show b
show MatchNone = "^$"
show (All n)
| n < 3 = concat $ replicate n alphabet
| otherwise = concat [alphabet,"{",show n,"}"]
show e@(Concat xs)
| atomic e = concatMap show xs
| otherwise = concatMap show' xs
where show' (Or a b) = "("++show (Or a b)++")"
show' x = show x
atomic (Concat xs) = all atomic xs
atomic (Or _ _) = False
atomic _ = True
-- Match integers in a certain range
matchIntRange :: Int->Int->RegEx
matchIntRange a b
| 0 > min a b = error "Negative input"
| a > b = MatchNone
| otherwise = build (d a) (d b)
where build :: [Int]->[Int]->RegEx
build [] [] = Concat []
build (a@(x:xs)) (b@(y:ys))
| sl && x == y = Concat [Range x x, build xs ys]
| sl && all9 && all0 = Concat [Range x y, All n]
| sl && all0 = Or (Concat [Range x (y-1), All n]) upper
| sl && all9 = Or lower (Concat [Range (x+1) y, All n])
| sl && x+1 <= y-1 = Or (Or lower middle) upper
| sl = Or lower upper
| otherwise = Or (build a (nines la)) (build (1:zeros la) b)
where (la,lb) = (length a, length b)
sl = la == lb
n = length xs
upper = Concat [Range y y, build (zeros n) ys]
lower = Concat [Range x x, build xs (nines n)]
middle = Concat [Range (x+1) (y-1), All n]
all9 = all (==9) ys
all0 = all (==0) xs
zeros n = replicate n 0
nines n = replicate n 9
d 0 = [0]
d n = digits 10 n
```
The code below is a simple version that helps with understanding the algorithm, but it doesn't do any optimization to improve the regex size.
`matchIntRange 123 4321`
```
(((1((2((3|[4-8])|9)|[3-8]((0|[1-8])|9))|9((0|[1-8])|9))|[2-8]((0((0|[1-8])|9)|[1-8]((0|[1-8])|9))|9((0|[1-8])|9)))|9((0((0|[1-8])|9)|[1-8]((0|[1-8])|9))|9((0|[1-8])|9)))|((1((0((0((0|[1-8])|9)|[1-8]((0|[1-8])|9))|9((0|[1-8])|9))|[1-8]((0((0|[1-8])|9)|[1-8]((0|[1-8])|9))|9((0|[1-8])|9)))|9((0((0|[1-8])|9)|[1-8]((0|[1-8])|9))|9((0|[1-8])|9)))|[2-3]((0((0((0|[1-8])|9)|[1-8]((0|[1-8])|9))|9((0|[1-8])|9))|[1-8]((0((0|[1-8])|9)|[1-8]((0|[1-8])|9))|9((0|[1-8])|9)))|9((0((0|[1-8])|9)|[1-8]((0|[1-8])|9))|9((0|[1-8])|9))))|4((0((0((0|[1-8])|9)|[1-8]((0|[1-8])|9))|9((0|[1-8])|9))|[1-2]((0((0|[1-8])|9)|[1-8]((0|[1-8])|9))|9((0|[1-8])|9)))|3((0((0|[1-8])|9)|1((0|[1-8])|9))|2(0|1)))))
```
The regular expression has 680 characters.
Here is the code
```
import Data.Digits
data RegEx = Range Int Int | MatchNone | Or RegEx RegEx | Concat [RegEx]
alphabet = "\\d"
instance Show RegEx where
show (Range i j)
| i == j = show i
| otherwise = concat ["[",show i,"-",show j,"]"]
show (Or a b) = concat ["(",show a,"|",show b,")"]
show MatchNone = "^$"
show (Concat xs) = concatMap show xs
matchIntRange :: Int->Int->RegEx
matchIntRange a b
| 0 > min a b = error "Negative input"
| a > b = MatchNone
| otherwise = build (d a) (d b)
where build :: [Int]->[Int]->RegEx
build [] [] = Concat []
build (a@(x:xs)) (b@(y:ys))
| sl && x == y = Concat [Range x x, build xs ys]
| sl && x+1 <= y-1 = Or (Or lower middle) upper
| sl = Or lower upper
| otherwise = Or (build a (nines la)) (build (1:zeros la) b)
where (la,lb) = (length a, length b)
sl = la == lb
n = length xs
upper = Concat [Range y y, build (zeros n) ys]
lower = Concat [Range x x, build xs (nines n)]
middle = Concat [Range (x+1) (y-1), build (zeros n) (nines n)]
zeros n = replicate n 0
nines n = replicate n 9
d 0 = [0]
d n = digits 10 n
```
[Answer]
## GolfScript (126 + 2\*170 = 466)
```
~)]{`:&,:_,{:i'('\_(<:/i&=48-:D 2<{D^i!!D*|1,*}{'['\i>2D<'-'*D(']?'3$)<}if/D!!*{'\d{'/i>'1,'*_(i-'}|'D}*}%_')'*]}%'(?!'\~'$)'\
```
For the given values it [gives](http://golfscript.apphb.com/?c=OzEyMzQ1NiA3NjU0MzIxCilde2A6Jiw6Xyx7OmknKCdcXyg8Oi9pJj00OC06RCAyPHtEXmkhIUQqfDEsKn17J1snXGk%2BMkQ8Jy0nKkQoJ10%2FJzMkKTx9aWYvRCEhKnsnXGR7Jy9pPicxLCcqXyhpLSd9fCdEfSp9JV8nKScqXX0lJyg%2FISdcfickKSdc)
```
(?!(\d{1,5}|1([01]\d{4}|2([0-2]\d{3}|3([0-3]\d{2}|4([0-4]\d{1}|5([0-5]))))))$)([1-6]?\d{1,6}|7([0-5]\d{5}|6([0-4]\d{4}|5([0-3]\d{3}|4([0-2]\d{2}|3([01]\d{1}|2([01])))))))
```
Dissection to follow, but the basic idea is to define a block of code which maps a single natural number to a regex matching any smaller natural number, and then turn the inputs `lb` and `ub` into a negative lookahead for (natural number smaller than `lb`) combined with the regex for (natural number smaller than `ub+1`).
The logic is quite complicated, so even by GolfScript standards it's cryptic. Until I get round to writing a detailed dissection, here's a list of variables:
```
& the whole number string
i the current idx
D the current digit
/ not-the-last-digit
_ total number of digits
```
] |
[Question]
[
This challenge is based on one proposed on the usenet group **rec.games.roguelike.development** a few years ago. I can't find the original newsgroup post, but you can have a look a the [Github repo of solutions](https://github.com/nrkn/SimpleRLGolf). It was only golfed in a couple of languages and I'd love to see some more!
## Objective
The aim is to build a program that presents a top-down view of a dungeon using ascii characters. There will be an `@` sign representing the player that can be moved through the free space in the dungeon (represented by ), though it cannot pass through the walls (represented by `#`).
The map of the dungeon must look like this:
```
#### ####
# # # #
# #### #
# #
## ##
# #
# #
## ##
# #
# #### #
# # # #
#### ####
```
The player must begin at location {2,2}, where {0,0} is the top left-hand corner.
## Interface
The user needs to be able to move the player in the four cardinal directions using the arrow keys on the keyboard.
There needs to be some way for the user to exit the program. It does not need to be a graceful exit (for example, it doesn't matter if an exception is printed).
The map and player need to be drawn before any input has been taken, and the player needs to be updated after each input.
## Libraries
Feel free to use established libraries for console input or output, such as Curses. Just mention in your answer what you are using.
## Scoring
This is code golf, shortest code wins!
[Answer]
## C, 257 253 222 220
Uses `system("cls")` instead of curses (use `system("clear")` for Linux systems) and a clever algorithm to fit the map into an 8-digit number. Non-extended keys end the program, e.g. escape.
EDIT: Now also shows your hero below the map by using `a<230` instead of `a<132`:
```
##
####
### ###
# # # #
## # # ##
####
# #
## ##
```
Code:
```
a,p=14,w=11,X,Y;m(I){X=I%w-1,Y=I/w;return 70313263>>(Y>5?w-Y:Y)*5+(X>4?9-X:X)&1;}main(){do{system("cls");a=a&4?1:a&2?-1:a&8?-w:w;p+=!m(p+a)*a;for(a=0;++a<230;)putch(a%w?a-p?m(a)*35:64:10);}while(a=getch()>>7?getch():0);}
```
[Answer]
## Ruby 1.9 + Curses (248)
```
require'curses';include Curses;noecho;curs_set 0
b=0xf3e499e601c0d0240b0380679927cf.to_s(2).tr'01',' #'
s=init_screen<<b.scan(/.{10}/)*$/;s.keypad 1
p=22;d=->t=?@{setpos p/10,p%10;addch t;6};d[]
loop{p=b[v=p+[10,-10,-1,1][getch%d[32]]]<?#?v:p;d[]}
```
[Answer]
# Python 332 319 317
```
from curses import*
M=0xf3e499e601c0d0240b0380679927cf;S=initscr();S.keypad(1);x,y=2,2;A=S.addstr;[A(a,b,[' ','#'][M>>(10*a+b)&1])for a in range(12)for b in range(10)]
while 1:A(y,x,'@');k=S.getch();A(y,x,' ');X=[[x,x-1],[x+1,1]][k==261][k==260];Y=[[y,y-1],[y+1,y+1]][k==258][k==259];x,y=[(X,Y),(x,y)][M>>(10*Y+X)&1]
```
The python curses library is only officially supported on linux. There are unofficial ones available for windows, but I can't guarantee that this will work with it.
To save a few characters I hard coded the keycodes for up, down, left, and right. This may cause problems for some people. If this doesn't work for anyone I can post a version that should.
Use ctrl+c to exit. You will probably have to reset your terminal after exiting, but the challenge specifically said the exit didn't have to be graceful.
[Answer]
# QBasic, ~~314~~ 313 bytes
This sort of problem simply begs for a QBasic solution.
```
DIM w(12,10)
FOR r=1TO 12
READ d
FOR c=1TO 10
w(r,c)=(d*2AND 2^c)>0
?CHR$(35+3*w(r,c));
NEXT
?
NEXT
i=3
j=3
1LOCATE i,j
?"@"
a$=""
9a$=INKEY$
IF""=a$GOTO 9
k=ASC(RIGHT$(a$,1))
x=i+(k=72)-(k=80)
y=j+(k=75)-(k=77)
LOCATE i,j
?" "
IF w(x,y)THEN i=x:j=y
IF k>9GOTO 1
DATA 48,438,390,510,252,765,765,252,510,390,438,48
```
This is golfed QBasic, which will be expanded significantly by the autoformatter. But, if you type this exact code into the IDE and hit F5, it should run. Tested on [QB64](http://qb64.net).

**Explanation:**
The map is encoded row-wise as the bits of the integers in the `DATA` statement (1 for space, 0 for wall). The nested `FOR` loop unpacks them, storing truth values in the 2D array `w`, and printing `#` or accordingly. (Note that true in QBasic is `-1`, thus why we're adding to 35 instead of subtracting!) The player starts at 3,3 because most things are 1-indexed in QBasic.
We then enter a `GOTO` loop: print the `@`, get keyboard input, convert to extended character code, and modify `x` and `y` based on whether the user pressed L/U/R/D. If `w(x,y)` is true, then it's a space and we can move there; otherwise, stay put. Finally, the shortest way I found to exit is by pressing the tab key (ASCII `9`). Any other input loops us back up to the first `LOCATE` statement.
I must say, I'm rather tickled to have beaten Python with a QBasic answer.
] |
[Question]
[
## Introduction
A common puzzle involves a triangular board with 15 holes for tees/pegs as shown in the image below:

Starting with all the pegs in the board except for a hole at the top, the point of the puzzle is to jump pegs over one another like checkers in such a way to leave exactly one peg left. The only valid move is to jump one peg over an adjacent peg in any direction into an empty hole. The peg that was jumped is then removed from the board. Play finishes when there remain no valid moves.
## Spec
Your job is to write a program that can find a complete solution to the peg puzzle, i.e., one that leaves exactly one peg left. There are multiple possible solutions, so your program just needs to print one.
* Your program will receive no input. You are not allowed to read data from any outside source.
* Print out the list of 13 moves that gives a result of 1 peg remaining using this format:
>
> `Peg 1 jumps Peg 3 to Hole 6.`
>
>
>
* The holes/pegs are numbered from top to bottom, left to right, so that the top peg/hole is 1, numbering until the bottom-right is 15.
* Your program **must** find the solution *at runtime*. Printing out a solution directly by any means other than solving it in the program is an automatic disqualification.
* **Bonus**: receive 10 bonus points if you can output multiple unique solutions (can just print separated by blank lines).
* **Bonus**: receive 5 bonus points if the number `15` appears nowhere in your source code.
## Scoring
This is code-golf, so the shortest solution (by byte count) that prints out a correct answer will be the winner. Bonus points are subtracted from your total byte count. Please provide a sample output of running your program as well as a link to `ideone` or some similar site if possible demonstrating the execution of your program.
[Answer]
### Ruby, score 240 238 234 = 249 - 10 - 5
```
s=->t,r,c{c>0?(t+t.reverse).gsub(/[A-O]{2}[a-o]/){|j|s[t.tr(j,j.swapcase),r+"Peg #{j[0].ord-64} jumps Peg #{j[1].ord-64} to Hole #{j[2].ord-96}.\n",c-1]}:$><<r+"\n"}
s["aBD,BDG,DGK,CEH,EHL,FIM,aCF,CFJ,FJO,BEI,EIN,DHM,DEF,GHI,HIJ,KLM,LMN,MNO,","",13]
```
A plain ruby implementation which prints all possible solutions to this puzzle (takes less than a minute on my computer). The first lines of output can be seen here:
```
Peg 6 jumps Peg 3 to Hole 1.
Peg 4 jumps Peg 5 to Hole 6.
Peg 1 jumps Peg 2 to Hole 4.
Peg 14 jumps Peg 9 to Hole 5.
Peg 7 jumps Peg 8 to Hole 9.
Peg 12 jumps Peg 13 to Hole 14.
Peg 10 jumps Peg 6 to Hole 3.
Peg 4 jumps Peg 5 to Hole 6.
Peg 3 jumps Peg 6 to Hole 10.
Peg 15 jumps Peg 10 to Hole 6.
Peg 6 jumps Peg 9 to Hole 13.
Peg 14 jumps Peg 13 to Hole 12.
Peg 11 jumps Peg 12 to Hole 13.
Peg 6 jumps Peg 3 to Hole 1.
Peg 4 jumps Peg 5 to Hole 6.
Peg 1 jumps Peg 2 to Hole 4.
Peg 14 jumps Peg 9 to Hole 5.
Peg 7 jumps Peg 8 to Hole 9.
...
```
And the online example can be found [here](http://ideone.com/wLaK3).
[Answer]
## Python, 324 chars, score = 319
```
f=0xf
x=0x12413624725935836a45647b48d58c59e69d6af78989abcdcdedef
Z=[(x>>12*i&f,x>>12*i+4&f,x>>12*i+8&f)for i in range(18)]
M=[[65532,'']]
for i in' '*13:
Q=[]
for p,m in M:
for a,b,c in[x[::-1]for x in Z]+Z:
if p>>a&p>>b&~p>>c&1:Q+=[[p^2**a^2**b^2**c,m+"Peg %d jumps Peg %d to Hole %d.\n"%(a,b,c)]]
M=Q
print M[0][1]
```
The peg state is kept as a bitmask. `M` contains a list of peg states and the instructions to get to that state.
I could make it print out all of the solutions as well (there are 29760 of them), but it would cost more than 10 characters to do it.
I can't post it on ideone as it takes about 90 seconds to run.
Output:
```
Peg 6 jumps Peg 3 to Hole 1.
Peg 4 jumps Peg 5 to Hole 6.
Peg 1 jumps Peg 2 to Hole 4.
Peg 14 jumps Peg 9 to Hole 5.
Peg 12 jumps Peg 13 to Hole 14.
Peg 7 jumps Peg 8 to Hole 9.
Peg 10 jumps Peg 6 to Hole 3.
Peg 4 jumps Peg 5 to Hole 6.
Peg 3 jumps Peg 6 to Hole 10.
Peg 15 jumps Peg 10 to Hole 6.
Peg 6 jumps Peg 9 to Hole 13.
Peg 14 jumps Peg 13 to Hole 12.
Peg 11 jumps Peg 12 to Hole 13.
```
[Answer]
**C, 386 chars, score = 371**
```
int f[37],o[36],t[36],r[14],i[14],m=1,s=~3,j=18;main(){while(j--)o[j]=o[18+j]=(f[j]=t[18+j]="AABBCCDDDEEFFGHKLM"[j]-64)+(t[j]=f[18+j]="DFGIHJKMFLNMOIJMNO"[j]-64)>>1;while(m)if(!f[++j])s=r[--m],j=i[m];else if(s>>f[j]&s>>o[j]&~s>>t[j]&1)if(r[m]=s,s^=1<<f[j]|1<<o[j]|1<<t[i[m]=j],j=-1,++m>13)for(m=printf("\n");m<14;++m)printf("Peg %d jumps Peg %d to Hole %d.\n",f[i[m]],o[i[m]],t[i[m]]);}
```
Prints out all 29760 solutions, in well under a second.
This version assumes (among other things) that the compiler will permit the implicit declaration of printf(). About six more characters could be saved by making use of implicit-int, but that feature was technically removed from C99.
Also, four more bytes can be saved by replacing the capital letters in the two strings with the corresponding control characters. I didn't do that here because compilers aren't required to permit such strings, and it makes already-dense source code completely illegible.
For clarity, here's the same algorithm without the more obfuscatory size-optimizations:
```
#include <stdio.h>
int f[37], o[36], t[36], r[14], i[14], m, j, s = ~3;
int main(void)
{
for (j = 0 ; j < 18 ; ++j) {
f[j] = t[18+j] = "AABBCCDDDEEFFGHKLM"[j] - 64;
t[j] = f[18+j] = "DFGIHJKMFLNMOIJMNO"[j] - 64;
o[j] = o[18+j] = (f[j] + t[j]) >> 1;
}
j = 0;
for (m = 1 ; m ; ++j) {
if (!f[j]) {
--m;
s = r[m];
j = i[m];
} else if ((s >> f[j]) & (s >> o[j]) & (~s >> t[j]) & 1) {
r[m] = s;
i[m] = j;
s ^= (1 << f[j]) | (1 << o[j]) | (1 << t[j]);
j = -1;
++m;
if (m > 13) {
printf("\n");
for (m = 1 ; m < 14 ; ++m)
printf("Peg %d jumps Peg %d to Hole %d.\n",
f[i[m]], o[i[m]], t[i[m]]);
}
}
}
return 0;
}
```
f, o, and t are the list of legal jumps initialized in the first loop. r and i form the history that the program uses to backtrack and explore all possible games.
I'm sure this can be improved!
] |
[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 3 years ago.
[Improve this question](/posts/2039/edit)
## Background
Of the 256 possible characters that a byte can represent, only a few of these are used under most circumstances. Couldn't we somehow take advantage of this, and make our text files smaller by eliminating the need for the rarely used letters?
Many letters don't add any value in most situations, and can be replaced by more common letters. For example, a lower-case "L", capital "I", and the number "1" look nearly identical in most situations, so they can be consolidated.
There is little need for capital letters, so they can be dispensed with. The decompression/display program could even automatically capitalize the first letter of every sentence, common names, etc.
## Rules
Entries will be judged on:
* compression ratio
* readability after de-compression
Entries will be tested against the plain text version of this article: <http://en.wikipedia.org/wiki/Babbage> and a randomly selected [BBC News](http://news.bbc.oc.uk) article.
Extra marks will be awarded for; preserving any mark-up, beautifying after de-compression (i.e. Capitalising sentences etc).
### Languages
* Any you like, but must easily compile (or be interpreted) on a basic \*nix box.
[Answer]
# Perl
Very inefficient and has bad rates.
Requires `/usr/share/dict/words`.
## Compressor
```
#!/usr/bin/perl
$M = 2;
$N = 1;
$Min = 3;
$Max = 8;
while (<>) {
for (split /\s+/) {
s/[^a-z]//i;
($p) = m/([^a-z]*)$/;
$_ = lc $_;
$l = (length $_) - (length $p);
s/^and$/A/;
s/^he$/H/;
s/^in$/I/;
s/^of$/O/;
s/^you$/U/;
s/^the$/Z/;
if (length $_ >= $Min) {
if (length $_ <= $Max) {
s/ed/D/g;
s/ing\b/N/g;
s/er/R/g;
s/'s/S/g;
s/th/T/g;
s/[aeo]{1,2}//g;
$_ .= $l;
} else {
s/^(.{$M})(.+)(\w{$N})$/$1.(length$2).$3/e;
}
}
$a .= $_ . $p . ' ';
}
}
print $a;
```
## Decompressor
```
#!/usr/bin/perl
$M = 2;
$N = 1;
open D, '/usr/share/dict/words';
chomp, push @W, $_ while <D>;
close D;
while (<>) {
for (split /\s+/) {
($_, $p) = m/^(.+)([^a-z]*)$/;
s/^A$/and/;
s/^H$/he/;
s/^I$/in/;
s/^O$/of/;
s/^U$/you/;
s/^Z$/the/;
if ($_ =~ m/^(\w{$M})(\d+)(\w{$N})$/) {
$r = '^' . quotemeta($1) . ('\w' x $2) . quotemeta($3) . '$';
($_) = (grep /$r/, @W);
$_ .= $4;
} else {
($_, $l) = m/^(.+)(\d+)$/;
s/D/ed/g;
s/N/ing/g;
s/R/er/g;
s/S/'s/g;
s/T/th/g;
$r = '[aeo]{0,2}';
for $y(split //) { $r .= (quotemeta $y) . '[aiueo]{0,2}' }
($_) = (grep /^(?=[a-z]{$l})$r$/, @W);
}
$a .= $_ . $p . ' ';
}
}
print $a;
```
[Answer]
## Bash, 5 chars
My lazy entry that just might win:
```
bzip2
```
Lossless, so it preserves readability perfectly and gets all the extra marks! Compression ratio on the Babbage html is 4.79x (153804 to 32084 bytes).
[Answer]
## Perl, 0 chars
Compression ratio of infinity, though not that readable after decompression so it will lose some marks.
] |
[Question]
[
Let's continue the [fibonacci](/questions/tagged/fibonacci "show questions tagged 'fibonacci'") based challenges stream, here's the next one:
## Task
Draw a Fibonacci spiral [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") of n segments where starting from the first term:
* each nth segment has a length of nth Fibonacci term.
* each segment is joined to the end of the previous, rotated by 90 degrees taking the end of previous segment as center of rotation.
* you can choose any printable ascii character chars to draw the spiral with, although the background must be spaces.
* You can draw the spiral in any orientation and turning clockwise or counterclockwise
* Leading/trailing whitespace is allowed within reason
## Example
Let's explain it with the help of a visual example:
Beginning of segments are highlighted with an arrow character (> < ^ v) to indicate the direction.
End of segments highlighted with `o` to indicate the pivot for the rotation of next segment.
Taking the first 9 terms [0,1,1,2,3,5,8,13,21] (the first term(0) doesn't draw anything) we draw clockwise.
```
o###################<o
#
#
#
#
#
#
#
o#<o #
v ^ #
# oo #
# #
# ^
o>######o
```
As you can see we start with one character(a segment of length 1) then add one to the right, then add two by rotating 90 degrees, then 3, then 5 .. and so on.
You can choose 0 or 1 indexing in the Fibonacci sequence, f(0) can draw anything or a single character, just be consistent on this.
# Some more examples
n==1 (0-indexed) or n==0 (1-indexed)-> [1]
```
*
```
n==2 -> [1,1]
```
2 1 or 21
1 or 2 or 12
```
here we used '1' for the first segment and '2' for the second
n==3 ->[1,1,2]
```
1 or 12 or...
233 3
3
```
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): all the usual golfing rules apply.
* Either a function or a full program is fine.
* Input/output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 25 bytes
```
TF0i:"P!1bYs:Q1&(3MPw]Zc&
```
[Try it online!](https://tio.run/##y00syfn/P8TNINNKKUDRMCmy2CrQUE3D2DegPDYqWe3/f3MA "MATL – Try It Online")
### Explanation
```
TF % Push [1, 0]. This array will contain the two most recent Fibonacci
% numbers in each iteration k: [f(k), f(k-1)]
0 % Push 0. This initiallizes the matrix M that will be used as output
i:" % Input n. Do the following n times
P! % Flip vertically, transpose. This rotates tmatrix M by 90 degrees
1 % Push 1 (*)
b % Bubble up: moves the array [f(k), f(k-1)] to the top of the stack
Ys % Cumulative sum: gives [f(k), f(k+1)]
: % Range (uses first entry): [1, 2, ..., f(k)]
Q % Add 1, element-wise: gives [2, 3, ..., f(k)+1] (**)
1 % Push 1 (***)
&( % Write 1 (*) in M at the rows given by (**) and column 1 (***).
% This extends M with the new segment of the spiral, padding with 0
3M % Push [f(n), f(n+1)] again
P % Flip: gives [f(n+1), f(n)], ready for the next iteration
w % Swap: moves the extended M to the top of the stack
] % End
Zc % Convert values 1 in M into char '#', and 0 to space
& % Set alternative input/output spec for the next function, which is
% implicit display. This causes the function to use only one input,
% which means that only the top of the stack is displayed
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 99 bytes
```
f=lambda n:' #'[2*n:]or[k:='#'+''.join(l[1:])for l in zip(*f(n-1)[::-1])]+(k:=len(k)-1)*['#'+' '*k]
```
[Try it online!](https://tio.run/##PcvBCsIwDADQXwnskKRjQvWgBPYlpYeNWaytaSm76M/X4cHrg1ff@6Po5VZb72HOy2vdFlBBGNCdjYovzSWZccAR8fQsUSk7K55DaZAhKnxiJRNIJ8tOZLKe/UhHyXelxIca99uAJvn@b4GuLLVF3Slz/wI "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 17 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
01⁸┤[┌┌+})H#×21╋↶
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjEwJXVGRjExJXUyMDc4JXUyNTI0JXVGRjNCJXUyNTBDJXUyNTBDJXVGRjBCJXVGRjVEJXVGRjA5JXVGRjI4JTIzJUQ3JXVGRjEyJXVGRjExJXUyNTRCJXUyMUI2,i=OQ__,v=8)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
LÅf0ŽPjSΛ
```
[Try it online.](https://tio.run/##yy9OTMpM/f/f53BrmsHRvQFZwedm//9vCQA)
0-based and the spiral goes counterclockwise starting towards the left, similar as the example in the challenge.
Input \$n=0\$ will always draw a single character instead of an empty output.
Draws with character `0`, but this could alternatively be [any other digit](https://tio.run/##yy9OTMpM/f/f53BrmuXRvRb@wedm//9vAQA), [the lowercase alphabet](https://tio.run/##yy9OTMpM/f/f53BrmuPRvRb@wedm//9vAQA), [the input digits](https://tio.run/##yy9OTMpM/f/f53BrmufRvRb@wedm//9vaAQA), [the digits of the 0-based \$n^{th}\$ Fibonacci number](https://tio.run/##yy9OTMpM/f/f53BrWtTRvRb@wedm//9vaAQA), etc. by replacing the `0`.
The start and direction of the spiral can also be changed by replacing `ŽPjS` with [`Ž8O` for right counterclockwise](https://tio.run/##yy9OTMpM/f/f53BrmsHRvRb@wedm//9vCQA); [`ŽG~S` for down counterclockwise](https://tio.run/##yy9OTMpM/f/f53BrmsHRve51wedm//9vCQA); [`ŽNāS` for left clockwise](https://tio.run/##yy9OTMpM/f/f53BrmsHRvX5HGoPPzf7/3xIA); [`Ƶ‘0š` for up clockwise](https://tio.run/##yy9OTMpM/f/f53BrmsGxrY8aZhgcXXhu9v//lgA); [`Ž9¦S` for right clockwise](https://tio.run/##yy9OTMpM/f/f53BrmsHRvZaHlgWfm/3/vyUA); or [`ŽICS` for down clockwise](https://tio.run/##yy9OTMpM/f/f53BrmsHRvZ7Owedm//9vCQA) ([up counterclockwise is the only one that's a byte longer with `Ž2„0š`](https://tio.run/##yy9OTMpM/f/f53BrmsHRvUaPGuYZHF14bvb//5YA)).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input-integer]
Åf # Get the (0-based) n'th Fibonacci number for each of these values
0 # Push character "0"
ŽPj # Push compressed integer 6420
S # Pop and convert it to a list of digits: [6,4,2,0]
Λ # Use the Canvas builtin with these three arguments
# (which is output immediately afterwards implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ŽPj` is `6420`.
As for some additional information about the Canvas builtin `Λ`:
It takes 3 arguments to draw an ASCII shape:
1. Length of the lines we want to draw
2. Character/string to draw
3. The direction to draw in, where each digit represents a certain direction:
```
7 0 1
↖ ↑ ↗
6 ← X → 2
↙ ↓ ↘
5 4 3
```
`LÅf0Ž8OS` creates the following Canvas arguments:
1. Length: the first input amount of 1-based Fibonacci numbers
2. Character: `"0"`
3. Directions: `[6,4,2,0]`, which translates to \$[←,↓,→,↑]\$
Step 1: Draw 1 characters (`"0"`) in direction 6/`←`:
```
0
```
Step 2: Draw 1-1 characters (`""`) in direction 4/`↓`:
```
0
```
Step 3: Draw 2-1 characters (`"0"`) in direction 2/`→`:
```
00
```
Step 4: Draw 3-1 characters (`"00"`) in direction 0/`↑`:
```
0
0
00
```
Step 5: Draw 5-1 characters (`"000"`) in direction 6/`←`:
```
00000
0
00
```
Step 6: Draw 8-1 characters (`"0000000"`) in direction 4/`↓`:
```
00000
0 0
0 00
0
0
0
0
0
```
etc.
[See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.](https://codegolf.stackexchange.com/a/175520/52210)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
×3ʀd⁰ɽ∆f›ø∧
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDlzPKgGTigbDJveKIhmbigLrDuOKIpyIsIiIsIjciXQ==)
*-1 byte thanks to emanresu A*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22\*? 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ÆḞ€R¬W€1¦t⁶;ɗ€0¦Ṛz⁶ʋ/ZṚ$⁸¡Y
```
A full program that accepts an integer and prints a spiral using `1`s.
**[Try it online!](https://tio.run/##y0rNyan8//9w28Md8x41rQk6tCYcSBkeWlbyqHGb9cnpQI7BoWUPd86qAvJPdetHAZkqjxp3HFoY@f//fzMA "Jelly – Try It Online")**
### How?
```
ÆḞ€R¬W€1¦t⁶;ɗ€0¦Ṛz⁶ʋ/ZṚ$⁸¡Y - Main Link: integer, N
ÆḞ€ - first N Fibbonacci numbers
R - range -> [[1],[1],[1,2],[1,2,3],[1,2,3,4,5],...]
¬ - logical NOT -> [[0],[0],[0,0],[0,0,0],[0,0,0,0,0],...]
W€1¦ - wrap the first one
ʋ/ - reduce by - f(Current, Next):
ɗ€0¦ - apply to the final entry of Current:
t⁶; - trim spaces and concatenate Next
Ṛ - reverse
z⁶ - transpose with spaces
$⁸¡ - repeat N times:
Z - transpose
Ṛ - reverse
Y - join with newline characters
- implicit print
```
---
\* Awaiting clarification on whether "output can be rotated so that the last segment is always in the same direction" - [22](https://tio.run/##y0rNyan8//9w28Md8x41rQk6tCYcSBkeWlbyqHGb9cnpQI7BoWUPd86qAvJPdetH/v//3wIA):
```
ÆḞ€R¬W€1¦t⁶;ɗ€0¦Ṛz⁶ʋ/Y
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
⊞υ¹FN«⌈υ↶⊞υΣ…⮌υ²»¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gtDhDo1RHwVDTmistv0hBwzOvoLTErzQ3KbVIQ1NToZqLM6AoM69EwzexIjO3NFejVBOokjMgsyy/xCc1rUQDzIMaEgyUd65Mzkl1zsgv0AhKLUstKk4F6tBRMNIEaav9/9/yv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ¹
```
Start with `1`.
```
FN«
```
Repeat `n` times.
```
⌈υ
```
Output the latest Fibonacci number in unary.
```
↶
```
Rotate ready for the next Fibonacci number.
```
⊞υΣ…⮌υ²
```
Calculate the next Fibonacci number.
```
»¹
```
Print a final character (this is because Charcoal is actually drawing the lines a character early, so it's drawing `1, 2, 3, 5, 8...` and the second `1` is missing).
It's possible to draw the lines according to the specification by rotating for the last character of the line, but in this case the spiral has to be drawn clockwise instead:
```
⊞υ¹FN«¶⌈υ¶↷⊞υΣ✂υ±²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gtDhDo1RHwVDTmistv0hBwzOvoLTErzQ3KbVIQ1NToZqLM6AoM69EQykmTwmoBsrzTazIzC3N1SjVRIjBVWSW5ZcEZaZnlGiAuVAbgoHKg3Myk1NBHL/U9MSSVA0jTZD@2v//Lf/rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ¹
```
Start with `1`.
```
FN«
```
Repeat `n` times.
```
¶⌈υ¶
```
Output the latest Fibonacci number in unary, but positioned rotated from the end of the previous one.
```
↷
```
Rotate ready for the next Fibonacci number.
```
⊞υΣ✂υ±²
```
Calculate the next Fibonacci number, but repeating the initial `1` the first time.
[Answer]
# Python3, 326 bytes:
```
R=range
f=lambda n,a=1,b=1:[b]+f(n-1,b,a+b)if n else[]
def g(b,e,x,y,q,w):
if e:x+=q;y+=w;b[x][y]=1;return g(b,e-1,x,y,q,w)
return x,y
def d(b,r,x,y,c=1):
if r:d(b,r,*g(b,r.pop(),x,y,0+c%2*[1,-1][c%4==1],0+(c%2==0)*[-1,1][c%4==2]),c+1)
def F(n):
r=f(n);b=[[0 for _ in R(r[-2]+1)]for _ in R(r[-1])];d(b,r,len(b),0);return b
```
[Try it online!](https://tio.run/##VY/BboMwEETP5St8iWRjU2HaQwTaaz4gV2tVYTAJEjXEpQp8PV0gHHrcmTezu8M83nv/cR7CslwhlP7moga68tvWJfOqBK0s6NxYlA33CU2qlFa0DfPMdT/OYFS7ht24VU5NalYP9RR5xAhw@SThUcwSnoU1E5oZQRfBjb/B7wGqOyIRexkkbI01AWGzK9CvxpDvarymw/vQD1xsSCqrUxYbrRKNpjp9AmgkkZMKkIrY0KbDyVCoSmqxbblwv3YHoOdEYcGYlDV9YF@s9ezKg0kyJBb/axoFFvspnfPcCpWK4zG7rGy7shd@pvK3IbR@5K1Y/gA)
] |
[Question]
[
Summer Klerance, a senior in college, is what her teachers refer to as GBL\*. Students in her probability class have been assigned individual problems to work on and turn in as part of their final grade. Summer, as usual, procrastinated much too long, and, having finally looked at her problem, realizes it is considerably more advanced than those covered in her course and has several parts as well. An average programmer, Summer decides to take a Monte Carlo gamble with her grade. Her prof. said that answers could be rounded to the nearest integer, and she doesn't have to show her work. Surely if she lets her program run long enough, her results will be close enough to the exact results one would get "the right way" using probability theory alone.
**Challenge**
You (playing alone) are dealt consecutive 13-card hands. *Every* hand is from a full, shuffled deck. After a certain number of deals, you will have held all 52 cards in the deck at least once. The same can be said for several other goals involving complete suits.
Using your favorite random-number tools, help Summer by writing a program that simulates one million 13-card deals and outputs the **average** number of deals needed for you to have seen (held) each of these **seven goals**:
```
1 (Any) one complete suit
2 One given complete suit
3 (Any) two complete suits
4 Two given suits
5 (Any) three complete suits
6 Three given complete suits
7 The complete deck (all four suits)
```
Each goal number (1-7) must be followed by the **average** number of hands needed (rounded to one decimal, which Summer can then round to the nearest integer and turn in) and (just for inquisitive golfers) add the minimum and maximum number of hands needed to reach that goal during the simulation. Provide output from *three runs* of your program. *The challenge is to generate all the averages. The min. and max. are (required) curiosities and will obviously vary run to run.*
**Test Runs**
Input: None
Sample Output: Three separate million-deal runs for the average, minimum, and maximum number of hands needed to reach each of the seven goals.
```
1 [7.7, 2, 20 ] 1 [7.7, 3, 18] 1 [7.7, 2, 20 ]
2 [11.6, 3, 50] 2 [11.7, 3, 54] 2 [11.6, 3, 63]
3 [10.0, 4, 25] 3 [10.0, 4, 23] 3 [10.0, 4, 24]
4 [14.0, 5, 61] 4 [14.0, 4, 57] 4 [14.0, 4, 53]
5 [12.4, 6, 30] 5 [12.4, 6, 32] 5 [12.4, 6, 34]
6 [15.4, 6, 51] 6 [15.4, 6, 53] 6 [15.4, 6, 51]
7 [16.4, 7, 48] 7 [16.4, 7, 62] 7 [16.4, 7, 59]
```
**Rules:**
1. *Every* hand must be dealt from a *full, shuffed deck* of 52 standard French playing cards.
2. Results for each goal must be based on one million hands or deals. You can collect all the results in a single million-deal run, or program as many million-deal runs as you like. However, each of the seven goals should reflect the result of one million deals.
3. Averages for the number of hands should be *rounded to one decimal*.
4. Output should be formatted roughly as above: each goal number (1-7) followed by its results (avg., min., and max. number of hands). **Provide output for three runs of your program (side by side or consecutively), which will serve as a check of the accuracy/consistency of the averages (column 1) only (columns 2 and 3 are required, but will obviously vary run to run).**
5. Shortest program in bytes wins.
---
**Note**: FYI, I believe the *exact* calculation (via formula) for the average number of hands needed to see the complete deck (goal # 7) works out to ≈ **16.4121741798**
---
\*Good but lazy
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~251~~ 247 bytes
A full program that prints 7 tuples `(avg, min, max)`.
```
[1,21845,279,30583,6015,32639,32767].map(b=>{for(M=k=t=c=0,m=n=1e6;c++||(x=[j=0]),n--;){for(d=[],i=14;--i;){while(d[v=Math.random()*52|0]);j|=((d[v]=x[v&3]|=1<<v/4)>8190)<<v%4}b>>j&1||(t+=c,M=c>M?c:M,m=c<m?c:m,k+=.1,c=0)}print(~~(t/k+.5)/10,m,M)})
```
[Try it online!](https://tio.run/##HY5bboMwFERX08guF7AxBlK4dAVeAfIHMakC1ARRi0YqZOvU7d9oHpoztGv7ZZZ@duFaHEfDIeFFKiHJzyCYLARkjEsQSSa8keRZriPbzuSC9c/HfSEKR3RokIHFCfk1K00QbBt5YDMg0xSmMCzpf7XDRkOPPC3DsPfe963/vJKuWVG17hYt7dTdLaGvMtn8sBw2JH@pxkeznoTekFfVGqe0LviZUa9f0v1S18OJ@z8XoAGFplbv5k15GFNZryyMAUYcPCDd56WfHHk@iYvHIJI05p4aFN3pcfwC "JavaScript (V8) – Try It Online")
### Example output
```
1 7.7 2 19 7.7 2 18 7.7 3 18
2 11.6 3 52 11.6 3 58 11.6 3 49
3 10.0 4 24 10.0 4 23 10.0 4 29
4 14.0 4 51 14.0 5 59 14.0 4 55
5 12.4 6 32 12.4 5 33 12.4 6 33
6 15.4 6 54 15.4 6 52 15.4 6 60
7 16.4 7 56 16.4 7 54 16.4 7 54
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~80~~ 61 bytes
```
%4‘ċⱮ4=13¹ḣƭS<
8⁸€;Q¥€52Ẋḣ13¤ẋç¥"JH$Ʋȷ6СẈ€¬ZT€IµÆmær1;Ṃ;Ṁ)ṖĖ
```
[Try it online!](https://tio.run/##y0rNyan8/1/V5FHDjCPdjzauM7E1ND608@GOxcfWBttwWTxq3PGoaY114KGlQMrU6OGuLqAUUMWSh7u6Dy8/tFTJy0Pl2KYT200OTzi08OGuDqCqQ2uiQoCU56Gth9tyDy8rMrR@uLMJiBs0H@6cdmTaf@NDi4DSWUD8cEcXkHzUuMv42FoQo2FuTVQWlOEGpN3/AwA "Jelly – Try It Online")
A pair of links that is run as a nilad and returns a list with a member for each goal. Each goal is represented as `[goal number, [mean deals, min deals, max deals]]`. The TIO link only does 10,000 deals per trial since that’s the most that can be done within the 60 second limit. The `ȷ6` above is the number of deals for each trial in something like scientific notation (`ȷ6` means \$10^6\$), so for TIO I’ve used `ȷ4` instead.
Full explanation to follow.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 196 bytes
```
7.times{|g|c=r=[]
1.upto(1e6){$.+=1
c|=[*1..52].sample 13
d=(0..3).map{|i|c.count{|j|j%4==i}}
(r<<$.;*c,$.=0)if[d.max(m=g/2+1),d[0,m]][g%2].sum/m>12}
p g+1,[r.sum.fdiv(r.size).round(1),*r.minmax]}
```
[Try it online!](https://tio.run/##LY3BjoMgFEX3fEUXmoCaV9FpZjF98yOERQvWYIZKUJrOCN/u0KS7k5t7z/Xh@rv3sBo7LNv@@YY4RoUehSQcgltnyocT2wqokRMVUVQc4NRJWC7W/QwH3hONtAXoGdiL26KJCtQc7usWpziVH4gmJUL9@VzAV6WaArBl5iZ0rj@pxfHY1Zw1WrSNlVKM5csd7NF@8y4Rdxhr3gj/iuCmzYNmNH8DA58/NM3LyoM19yyTaXdhXUja/wE "Ruby – Try It Online") The number of deals on TIO is set to `1e5` instead of `1e6` to avoid timing out.
Sample output for three local runs with `1e6` deals (side by side for ease of reading and to save space):
```
1 1 1
[7.7, 2, 20] [7.7, 2, 18] [7.7, 2, 19]
2 2 2
[11.7, 2, 52] [11.6, 3, 45] [11.6, 3, 60]
3 3 3
[10.0, 4, 24] [10.0, 4, 26] [10.0, 4, 23]
4 4 4
[14.0, 4, 57] [14.0, 5, 51] [14.0, 5, 51]
5 5 5
[12.4, 6, 31] [12.4, 6, 34] [12.4, 6, 32]
6 6 6
[15.4, 6, 62] [15.4, 6, 57] [15.4, 6, 53]
7 7 7
[16.4, 7, 51] [16.4, 7, 53] [16.4, 7, 48]
```
### Explanation
As the deals progress, a count is kept of the number of cards seen from each suit. This count is stored in the 4-element array `d` in the code.
Goals 1, 3, 5, and 7 are achieved when all 13 cards from any \$m=1, 2, 3, 4\$ suits, respectively, have been seen, or in other words when the sum of the \$m\$ greatest elements of `d` equals \$13m\$.
Goals 2, 4, and 6 are equivalent to choosing a particular ordering of suits and seeing all 13 cards from the first \$m=1,2,3\$ suits, respectively. In these cases, the goal is achieved when the sum of the first \$m\$ elements of `d` equals \$13m\$.
```
7.times{|g| # for each goal
c=r=[] # initialise
1.upto(1e6){ # 1 million times
$.+=1 # count deals towards current goal
c|=[*1..52].sample 13 # randomly select 13 cards and keep track of history (set union)
d=(0..3).map{|i|c.count{|j|j%4==i}} # count cards seen from each suit
(r<<$.;*c,$.=0)if[d.max(m=g/2+1),d[0,m]][g%2].sum/m>12 # if goal is achieved, store deal counter then reset counter and history
}
p g+1,[r.sum.fdiv(r.size).round(1),*r.minmax] # formatted output
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 136 bytes
```
≔E⁷⟦⟧ε≔Eε⁰ζ≔⮌ζηF×φφ«≔⟦⟧θF¹³⊞θ‽⁻E⁵²λθ≧|ΣX²θη≦⊕ζ≔Eη↨⁻⊖X²¦⁵³κ⁸¹⁹²δF⁷F⎇﹪κ²⁼¹Σ…§δκ⊘⁺³κ›⊗№§δκ⁰κ«⊞§εκ§ζκ§≔ζκ⁰§≔ηκ⁰»»Eε⪫⟦⊕κ⟦∕÷⁺×χΣι⊘LιLιχ⌊ι⌈ι⟧⟧
```
[Try it online!](https://tio.run/##ZVLLbsIwEDzDV1icbMmVAgjRqiceVUtVVER7QxxcsiUWjg1Owqvi29N1HEjURkq0Hs/uzmx2FQm7MkLl@SBJ5FrTqdjSPieLJeME2GOzBgMnAaLnCp3DHmwC9IxwhPC3sYR@yhgS2g44aQdBwBj5aTZK/mLJyQ55jYLY7jIyy5KI7jiZCx2amE6lzpKiWa/DiWKOzlwCQr7GXK6jlA5lepAJvFtOPrKYzswBLO0UbK@kSqATvbIQg04h9OIbNU8RJ0OBDnzjMdyoVc1e1xXd4Hvffui4OLxZ6DPiPYPVwp7o1ISZMnTDSQd5T7tMKByFFzk6rRSMIrOlg3SiQzjS0Jd9EWrvGipU0HWQezh5tiBSlDA22ZfC@5HJdPo3N/Da/JQbxTSvDPCM6/Fc8FB4ab@Ouzr/b6Lq5tK8NGdWYv9yEV6NxN9ZGy11vRZjuZch4MjTMipMVRvh5iBZ5fkN9DqNHIRYdXCrgx/8KTIuMjAWxzJe4hK1SMvtRZ7nd3v1Cw "Charcoal – Try It Online") Link is to verbose version of code. Note: TIO link limited to 10,000 iterations as 1,000,000 is too slow. Explanation:
```
≔E⁷⟦⟧ε≔Eε⁰ζ≔⮌ζη
```
Start with an array of 7 empty lists of counts needed to reach the goal, a list of counts tracking the next goal, and a list of cards seen so far for each goal.
```
F×φφ«
```
Loop 1,000,000 times.
```
≔⟦⟧θF¹³⊞θ‽⁻E⁵²λθ
```
Deal 13 different cards at random.
```
≧|ΣX²θη
```
Convert the cards into a bitmask and mark them as having been seen for each goal.
```
≦⊕ζ
```
Increment the count for each goal.
```
≔Eη↨⁻⊖X²¦⁵³κ⁸¹⁹²δ
```
For each goal, find all the suits for which all of the cards have now been seen.
```
F⁷F⎇﹪κ²⁼¹Σ…§δκ⊘⁺³κ›⊗№§δκ⁰κ
```
For each goal, check whether it has been satisfied: goals 2, 4 and 6 require specific suits to have been seen while the other goals only require a count of seen suits.
```
«⊞§εκ§ζκ§≔ζκ⁰§≔ηκ⁰»»
```
If the goal has been satisfied then save the count and restart that goal.
```
Eε⪫⟦⊕κ⟦∕÷⁺×χΣι⊘LιLιχ⌊ι⌈ι⟧⟧
```
Format the averages as desired. Sample outputs (from TIO):
```
1 [7.7, 3, 16] [7.8, 3, 16] [7.7, 3, 14]
2 [11.7, 4, 35] [11.6, 4, 32] [11.7, 3, 33]
3 [10.0, 5, 21] [10.0, 5, 20] [10.0, 5, 19]
4 [13.9, 6, 39] [14.1, 6, 34] [14.0, 7, 33]
5 [12.4, 7, 27] [12.5, 7, 23] [12.5, 7, 24]
6 [15.7, 8, 39] [15.6, 7, 37] [15.4, 7, 39]
7 [16.5, 8, 39] [16.5, 9, 38] [16.5, 8, 37]
```
[Answer]
# [Python 2 (PyPy)](http://pypy.org/), 244 bytes
```
from random import*
R=range
for g in R(1,8):
j=s=0;r=[]
for _ in R(10**6):
for c in sample(R(52),13):s|=1<<c
S=[s>>13*i&8191>8190for i in R(4)];j+=1.;g%2>0>S.sort()
if all(S[g/-2:]):r+=j,;j=s=0
print g,round(sum(r)/len(r),1),min(r),max(r)
```
[Try it online!](https://tio.run/##LY7LboMwEEXX@Ctm08omToJJW6UQ@yNgiVCEEnCN8EM2kYrUf6cm7WbO6B7N6Lpl/rIm37vFLes6eKvBd@YeobSzfk5RxWMgezRYDxKUgQozeiYFgpEHnpWeNy2CzV7/bZamH9EnW3bbstBpN/W4wu85oexEivDD2eVyQ0nNmyAEO6Xq9cw@mYgj287U36s30pbjjrNDKV9ykYn6EGInTFCiBuimCdeNPO7zoiWF3/GRls9KCJxXZgZJvX2YOw4PjT05Tr2JoIxQrZ6b7r4j1vUX "Python 2 (PyPy) – Try It Online")
Results of three runs:
```
1 7.7 2 19 1 7.7 3 18 1 7.7 3 18
2 11.6 3 50 2 11.6 3 49 2 11.6 3 45
3 10.0 4 24 3 10.0 4 24 3 10.0 4 24
4 14.0 4 46 4 14.0 4 47 4 14.0 5 58
5 12.4 5 33 5 12.4 6 30 5 12.4 6 32
6 15.4 5 52 6 15.4 5 51 6 15.4 6 54
7 16.4 7 53 7 16.4 7 54 7 16.4 7 51
```
By replacing the inner for loop by `exec`, we can trade in 10 bytes for a bit of memory usage1:
```
from random import*
R=range
for g in R(1,8):j=s=0;r=[];exec'for c in sample(R(52),13):s|=1<<c\nS=[s>>13*i&8191>8190for i in R(4)];j+=1.;g%2>0>S.sort()\nif all(S[g/-2:]):r+=j,;j=s=0\n'*10**6;print g,round(sum(r)/len(r),1),min(r),max(r)
```
[Don't try it online!](https://tio.run/##JY5NboMwFIT3OYU3bWzHSTBpqxTHPgQsgQUixjXCP7KJFKTenZp0876nGc1o/DL/OJsf/eKXdR2CMyB09p6gjXdhxruSJ0HJ3eACUEBbUEJKrqgYeeQZC7xumXzKfr/5/ebHzvhJwhJ@5ojQCyriL6e3W9/YitdRCHrB@v1Kv6lIJ9ti@r/2A7VsPHB6YuotF5moTjEtgKixegDdNMGqVudjXrSoCAc@Evaa0Ng9phnGX8wHbWegSHAPe4fxYWBA50naBEIRMfr1me6ZsK5/ "Python 2 (PyPy) – Try It Online")
1 After changing `10**6` to `10**5` this finished while using 4 GB of RAM. 10\*4 = 40?
[Answer]
# [Perl 5](https://www.perl.org/) (List::Util), ~~195~~ 231 bytes
```
for$g(map'^('.($_%2?'':'(.{13})*').'1{13}){'.($_/2^0).'}',2..8){my@n;for(1..1e6){$n=0;$s=0 x52;while($s!~$g){$h=1x13;substr$h,rand 1+length$h,0,0for 1..39;$s|=$h;$n++}push@n,$n}printf++$i." %.1f %d %d\n",sum(@n)/@n,min(@n),max(@n)}
```
[Try it online!](https://tio.run/##HY7RaoQwEEV/Jd1GEqvNGmVLq0gX@to@9q1scdloAmYUE6nF2k@vHRcG7ty5w5np1dAe1rXuBtpwW/XsxJng9DNInxnLGRezzJbwjoWCyWs7X@N9ekpwtLA4FeIxnO33EQqEcCmEVFk4UyiTgroyIdMhLb60aRWn7uaXNpjpUk4yK9x4dn6gOh4quBAZtQoar9EncYIsgqzsCSE/JdUFhSha@tHpI8QUln4w4OsookbsSCBkTYIL1gfsYjdafoRwj4vWwNbGtpo2XdZb8qIraBQ5d14T/JT4DuVhk2EEUhFr2tZ0QLyxyon1r@s9Wrfev70a5/P83Zu2xBMbe@P@Aw "Perl 5 – Try It Online")
A million times gave the following output from the three runs which took more than 14 minutes each:
```
1 7.7 2 20 | 1 7.7 2 22 | 1 7.7 2 22
2 11.6 2 61 | 2 11.6 2 69 | 2 11.6 2 58
3 10.0 4 26 | 3 10.0 4 28 | 3 10.0 4 28
4 14.0 4 59 | 4 14.0 4 58 | 4 14.0 4 61
5 12.4 5 36 | 5 12.4 5 40 | 5 12.4 5 36
6 15.4 5 62 | 6 15.4 5 56 | 6 15.4 6 60
7 16.4 6 65 | 7 16.4 6 61 | 7 16.4 6 60
```
[Answer]
# [PHP](https://www.php.net/), 364, 348, 343, 342, 338, 330
```
for(;$r<23;){if(7==$l=$r++%8)continue;for($d=$x=$c=$s=$g=0,$m=2e6;$d++<1e6;){foreach(array_rand(range(0,51),13)as$a)$u[$a]=$a%4;$t=array_count_values($u);~$l&1&&rsort($t);for($h=-1;$h++<$o=$l>>1;)if(($t[$h]??0)<13)break;$c++;if($h>$o){$s+=$c;$m=min($m,$c);$x=max($x,$c);$g++;$c=0;$u=[];}}$f=round($s/$g,1);echo++$l.":$f,$m,$x\n";}
```
[Try it online!](https://tio.run/##JY/rbsIwDIXfBR1QonRbC7tpruFBGEJZegla26C0nTqh7tWZEX8sWz72@c7Zn6/57iy1ClERYr7ekL6cKvXGjIYRjVm@axe64dSNJd1UKBgTwzF6Rs1pgpbX5SuhMCbPpNEXkZXWeWVjtL/HaLtCSalLlSYvmU6yjbY9rMa4hz0w7PKZMPBd7cLYDccf24xlrzBq@kOzylar2Ic4KAz6DuH5ISN4sUQQ0u02Iy3YItjDH3a7VOdi8yUc3wRnDMkSfougL@iN4JNgt6dOoU3gNEmk1k4K032q5UIipoSR9weaZ1QchaxQ6J9QJ5mm0vlgDJrHxQeq5PZm@uwWNF@v/w)
Outputs three consecutive sets of seven goals
-4 bytes thanks to @Djin Tonic for the idea to shuffle cards differently!
Original naive implementation ungolfed:
```
for($run=1;$run<=3;$run++){
$row=1;
for($suit_match_count=0;$suit_match_count<=3;$suit_match_count++){//number of given suits to match (-1)
for($match_type_switch=0;$match_type_switch<=1;$match_type_switch++){//switch between 'any' and 'given'
if($suit_match_count==3 && $match_type_switch==1) {//last two cases are the same so skip
continue;
}
$goal_count=0;
$goal_deals_sum=0;
$goal_deal_count=0;
$running=[];
$min_deals=1000001;//outside of range
$max_deals=0;
for($deal_count=0;$deal_count<1000000;$deal_count++){//million deals
$deal=[];
for(;count($deal)<13;){//one deal
$card=rand(1,52);
$deal[$card]=1;
$running[$card]=$card%4;
}
$suit_count = array_count_values($running);//check for complete suits
if($match_type_switch==0){
rsort($suit_count);
}
for($check_suit_match=0;$check_suit_match<=$suit_match_count;$check_suit_match++){
if (($suit_count[$check_suit_match]??0)!=13) {
break;
}
}
$goal_deal_count++;
if($check_suit_match==($suit_match_count+1)){//we have our desired number of matched suits
$goal_count++;
$goal_deals_sum+=$goal_deal_count;
if($goal_deal_count<$min_deals){
$min_deals=$goal_deal_count;
}
if($goal_deal_count>$max_deals){
$max_deals=$goal_deal_count;
}
$goal_deal_count=0;
$running=[];
}
}
echo "$row [".(intval(10*$goal_deals_sum/$goal_count)/10).",$min_deals,$max_deals]\n";
$row++;
}
}
echo "\n\n";
}
```
] |
[Question]
[
A screen consisted of some LED segments like such:
```
_ _ _ _ _
|_|_|..._|_|_|
|_|_| _|_|_|
```
However, some of the LEDs are broken, and it's possible that only these are left:
```
_ _
_|_|
|_|_|
```
Now, you're required to output all integers possibly expressed on this screen. An integer, something matching RegEx `/^0$|^-?[1-9][0-9]*$/`, can be expressed iff each of its character can be displayed in order using the unbroken LEDs, any two characters not overlapping or touching.
Shapes of characters `0123456789-` are given below:
```
_ _ _ _ _ _ _ _
| |,|, _|,_|,|_|,|_ ,|_ , |,|_|,|_|,_
|_| | |_ _| | _| |_| | |_| _|
```
Sample Input:
```
_ _
_|_|
|_|_|
```
Sample Output:
```
{-7,-1,0,1,2,3,4,5,6,7,8,9,11,21,31,71}
```
Your can take input in reasonable ways e.g. taking a repeating pattern of a good screen and treat \$
\begin{matrix}|\\|\\\end{matrix}
\begin{matrix}-\\-\\-\\\end{matrix}
\begin{matrix}|\\|\\\end{matrix}
\$ as \$[
\begin{matrix}|\\|\\\end{matrix}
\begin{matrix}-\\-\\-\\\end{matrix},
\begin{matrix}|\\|\\\end{matrix}
\color{cyan}{\begin{matrix}-\\-\\-\\\end{matrix}}]
\$ (cyan means broken); or maybe 5 arrays of each kinds of LEDs, etc. Your output needn't be sorted, either. Shortest code wins.
## Notes:
* A good screen actually can be \$
\begin{matrix}|\\|\\\end{matrix}
\begin{matrix}-\\-\\-\\\end{matrix}
\begin{matrix}|\\|\\\end{matrix}
\begin{matrix}-\\-\\-\\\end{matrix}
\begin{matrix}|\\|\\\end{matrix}
\begin{matrix}|\\|\\\end{matrix}
\begin{matrix}-\\-\\-\\\end{matrix}
\begin{matrix}|\\|\\\end{matrix}
\begin{matrix}-\\-\\-\\\end{matrix}
\begin{matrix}|\\|\\\end{matrix}
\$, but we'll just input it as \$
\begin{matrix}|\\|\\\end{matrix}
\begin{matrix}-\\-\\-\\\end{matrix}
\begin{matrix}|\\|\\\end{matrix}
\begin{matrix}-\\-\\-\\\end{matrix}
\begin{matrix}|\\|\\\end{matrix}
\color{cyan}{\begin{matrix}-\\-\\-\\\end{matrix}}
\begin{matrix}|\\|\\\end{matrix}
\begin{matrix}-\\-\\-\\\end{matrix}
\begin{matrix}|\\|\\\end{matrix}
\begin{matrix}-\\-\\-\\\end{matrix}
\begin{matrix}|\\|\\\end{matrix}
\$.
* I thought this question and the other LED one together in one question but later decided to separate.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 164 bytes
Expects an array of 5-bit integers, matching the segments as described below:
[](https://i.stack.imgur.com/U8q5C.png)
Returns a set.
The code contains 3 unprintable characters, which are escaped below.
```
f=([v,...a],p,o=(s=new Set,''),P)=>1/v?f(a,v,o,Buffer("w`>|i]_d\x7f}\x03\x08").map((x,i)=>(p|v%4<<5)&x^x||P>3&&x%6&&P-8|x%10||f(a,v,o+('1-'[i-10]||i),x))):o&&1/o?s.add(+o):s
```
[Try it online!](https://tio.run/##TVBRb9MwEH7gBfVXnCo1PlPHaxggNOpMQoLnSn2plIXgJc7wVOJgZ5krPPHTi9MNNp1k3efvu/vu7laO0tVW90PamUYdj63AYmScc1mynhmBTnTqHrZqYIRQtqEiz87GyxYlG5lhn@/aVlmc33/Pgy6r5s/Dq9dzyn/KHtEzHdXYh3Hxbr1@TxP/zYewyc@TxC8@JMkm/Rj8IluF8NRtiSRLSaHTbFWGoCnzlNILkyTZmbl0XDYNLg29cEerft1pq5C0jlBulWy@6r3aHroaV5QPZjtY3d0g5a7f6wHnV91VF6dqjf0i6x/oQOTwewYgQUBRfoqZe5a@EKJjcKCTuogXceUzUTPwJ0IWHvIcshKCAKxBCCAVgRDgMQ@EwnoNHhbwFt7AOSzhAClklE62VsVZIK5/QrXpnNkrvjc3OBlGtuTO2AHjfeD60S8WX1N@a3SHhAGZ@jzQI1QxZrsqVGEWTu9s@niCL8HuBP7Jd/8LqvAX "JavaScript (Node.js) – Try It Online")
(Includes some post-processing to sort the results for the sake of clarity.)
### How?
The full byte describing enabled segments is obtained by shifting the two least significant bits of the current mask `v` by 5 positions to the left and adding them to the previous mask `p`:
```
p | v % 4 << 5
```
The shapes of the digits and the minus sign are encoded as the ASCII codes of a 12-character string. Note that there are two versions of the "1" (right-aligned and left-aligned).
```
119 | 96 | 62 | 124 | 105 | 93 | 95 | 100 | 127 | 125 | 3 | 8
-----+-------+----+-----+-----+----+----+-----+-----+-----+-------+---
0 | 1 (a) | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 1 (b) | -
(a): right-aligned
(b): left-aligned
```
The test `P > 3 && x % 6 && P - 8 | x % 10` is used to reject characters that are touching each other:
```
P > 3 && // 1) the previous character is not empty
// and is not a left-aligned "1"
x % 6 && // 2) the current character is not a right-aligned "1"
// (the only character whose encoding byte is 0 modulo 6)
P - 8 | // 3) the previous character is not a minus sign
x % 10 // or the current character is not a "7"
// (the only character whose encoding byte is 0 modulo 10)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 92 bytes
```
Ø0ṭ;ḣ2$}¥Ɲ“⁸ɠḊṭṆƙ²ġ°ɦẋ‘BḊ€¤oẠ¥€T¥ⱮịØD;”-¤©;€⁶Œp®ḟ”1pƊḟ““-7”¤i$ƝẸ$Ðḟḟ€⁶Ḣ;ḟɗ€”-ḟ““-”ḟ”0;ɗṪ$€VQ
```
[Try it online!](https://tio.run/##y0rNyan8///wDIOHO9daP9yx2Eil9tDSY3MfNcx51Ljj5IKHO7qAEg93th2beWjTkYWHNpxc9nBX96OGGU5AmUdNaw4tyX@4a8GhpUBmCJDcuO7h7u7DM1ysHzXM1T205NBKa6DEo8ZtRycVHFr3cMd8oLBhwbEuMGsOEOmaA0UOLclUOTb34a4dKocnAGVAkmBND3csArpo/snpIC7QPIQuIA9imIH1yekPd65SAaoIC/x/uP3hzkX//0cb6BhCYKxOtCEa2wAEYwE "Jelly – Try It Online")
Horribly long for a Jelly answer but I think it works! A monadic link taking a list of lists of five 0s and 1s and returning a list of integers. The footer sorts the output. 1 represents a working LED segment and 0 a non-working one. They are numbered left to right and top to bottom, so the first two integers represent the left-hand side of the display and the next three represent the three horizontal segments.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~158~~ 138 bytes
```
⊞υ⟦θηζω⟧FυF¹¹«≔⪪§⪪”{⊟∨÷θA<∧mTMm⁰)¶Þ[u↘∕{‽UïÞ6Zξ-Φ⊟F∕↖;⁶C↑H;z⦃”⸿κ¶ε≔ΦLζ⬤ε⬤ν№⁺ §§ιξ⁺μρπδ¿δ⊞υEι⎇⁼³μ⁺λ§I⊖κ⁰⭆λ⎇›ξ⁺⌊δL§εμν »ΦEυ⊟ι∧››ι-№Φιμ-⁼ιIIι
```
[Try it online!](https://tio.run/##TVFNb4MwDD2PX2FxSqRUWrVjT6j70KRVQupu64RQSSFqCG0IW9ex387sQNoi4hc79nOes61yu21yPQxp11asE/BxFFAJOAv4/uSLaNdYYB0Hj/M5h9/oLmlbVRq2PmjlWOJeTSFPkxfDxmS4YGOBsIceTdaji0j/GIfMx@HWBZ8GMBYYgJDch5Qb13P6eO9XOLq0u7hYGAuINzbmAvactoa2EtUFKc9KO2nZmzSlq9gZTxOtmRzBCFg2nXEs1V2LCpEtiA6oBJywyCfUAizn6B24h4L6qB2wgkMY8io/UM27tCa3P@zp2OW6ZQ8C6sCir02WeevYo9xaWUvjZMH2RHtPZu2sMiWx6Svbi5U5qTlNVCtlVN3V2F/ApDBQS@rob4kiURnt8bp/UYq8LoyF@PHSaYOXptzEFJcmAVFNPKOxjqOaKtWoiE4QJpkY9JK8UXz8FsOAT5ZF@FpZH/Vkh9mX/gc "Charcoal – Try It Online") Link is to verbose version of code. Too long because I'm doing string manipulation instead of bit twiddling. Explanation:
```
⊞υ⟦θηζω⟧
```
Start a breadth first search with a trial of the input and no characters so far.
```
FυF¹¹«
```
Loop over each trial and character (`-` plus `0`..`9`).
```
≔⪪§⪪”{⊟∨÷θA<∧mTMm⁰)¶Þ[u↘∕{‽UïÞ6Zξ-Φ⊟F∕↖;⁶C↑H;z⦃”⸿κ¶ε
```
Extract the display for the given character.
```
≔ΦLζ⬤ε⬤ν№⁺ §§ιξ⁺μρπδ
```
Find whether we can place the character using the remaining segments.
```
¿δ⊞υEι⎇⁼³μ⁺λ§I⊖κ⁰⭆λ⎇›ξ⁺⌊δL§εμν
```
If so then add a new trial with the adjacent segments removed.
```
»ΦEυ⊟ι∧››ι-№Φιμ-⁼ιIIι
```
Only output those trials that are integers (e.g. exclude `0-0`).
] |
[Question]
[
There's only one question for machine-language golfing, and it's for the ia32 and amd64 architectures. Here's one for a predecessor of them: the Zilog Z80!
The ISA is available [here](http://z80-heaven.wikidot.com/opcode-reference-chart).
As usual, if your tip is only applicable to a certain environment/calling convention, please indicate that in your answer.
>
> Only one tip per answer (see [here](https://codegolf.meta.stackexchange.com/a/9296)).
>
>
>
You can also offer tips for the closely related Sharp SM83.
The ISA for that is available [here](https://www.pastraiser.com/cpu/gameboy/gameboy_opcodes.html).1
Please mark your tips as to whether they're applicable to Z80, SM83, or both; the ISAs might be similar, but there are many differences.
1. It's labeled as the LR35902; that's the SiC that was used in the DMG and CGB. It had an SM83 core.
[Answer]
## Shadow registers
When you're short on registers, you can use the shadow registers - `af'`, `bc'`, `de'` and `hl'`. These registers map directly to their usual counterparts (without `'`). You can exchange registers using `ex reg, reg'` or `exx`. The later exchanges all registers (`af` and `af'`, `bc` and `bc'`, etc...). Drawbacks:
* not compatible with "usual" registers, you can't use for example `ld` to assign from a standard to a shadow register.
* they were originally meant to be used inside ISRs, so the interrupts should be disabled while you use them.
[Answer]
## Use `ldir` and friends.
Instead of many successive loads, from the same location to a consecutive block of memory, you can use `ldir`:
```
ld (mem),a
ld (mem+1),a
ld (mem+2),a
ld (mem+3),a
ld (mem+4),a
ld (mem+5),a
```
... becomes:
```
ld hl,mem
ld de,mem+1
ld (hl),a
ld bc,5
ldir
```
If you're familiar with x86 assembly, `ldir` is somewhat comparable to `rep movsb`. Of course, z80 has many more instructions like that: `cpir, inir, otir, lddr, cpdr, indr, otdr`
[Answer]
## `cp` and `cpl`-related tricks
```
cp 0
cp 1
```
become respectively
```
or a
dec a
```
... saving a single byte. You can also use `cpl` instead of `xor $FF` to flip bits in a byte.
You can also use `cpl` for subtracting accumulator from some constant:
```
cpl
add a, X+1
```
... is one byte shorter than `neg` and `add a, X`
[Answer]
## Messing with flags
You can do the following flag operations in a compact way:
* Carry flag: setting - `scf`, resetting - `or a`, alternatively `and a` (modifies sign and zero).
* Zero flag: setting - `cp a` (resets carry, modifies sign), resetting - `or 1` (resets carry, modifies `a` and sign).
* Sign flag: setting - `or $80` (reset zero and carry, modifies `a`), resetting - `xor a` (clear `a`, set zero, clear carry).
* Half carry: `and a` - set, `xor a` - reset.
[Answer]
Here's a tip to start off: `jp` is generally a bad idea.
Unless your code is more than 128 bytes long (which it probably won't be), you can definitely save a byte with a `jr`. As a bonus, your code will be position-independent.
Just one quick warning: the offset of `jr` is from the start of the instruction on Z80 (so `18 00` is an infinite loop), but the end on SM83 (so `18 00` is a two-byte three-cycle no-op).
Therefore, `jr` on SM83 can offset the IP by any amount from -126 to 129, but on Z80 it's -128 to 127.
[Answer]
Some of the most useful commands for golfing in Z80 assembly language are `sbc` and `adc`. They often allow you to interact with the flag C in ways that are absolutely amazing. Here are some cool examples:
1. **How to create a decreasing counter in A that stops at 0?** `or a : jr nz,$+3 : dec a` is ugly. `sub 1 : adc 0` is faster, runs in constant time and can often be size-optimized, if you have handy 0s or 1s in one of your other registers. Have to stop at a non-zero value N? No problem: `sub N : adc N-1`. This also works for incrementing counter that is clamped at 255: `add 1 : sbc 0`. This also works for a incrementing counter clamped at an arbitrary value N: `add 256-N : sbc 256-N-1`.
2. **How to load an arbitrary value N to A when flag C is up (or zero otherwise)?** `ld a,N : jr c,$+3 : xor a` is not the way. `sbc a : and N` usually is (it is faster and shorter by 2 bytes).
3. **How about loading into A value N if flag C is up or value M if flag C is down?** Don't mess with conditional jumps! Use `sbc a : and N-M : add M`. (This last trick I believe is invented by GriV).
[Answer]
Another simple one:
**Use `xor a` or `sub a` instead of `ld a,0` to reset (load `0` to) the `a` register.**
Their use seems to be controversial in non-golfing situations (some sources use them, some advise against them), but I see no point in *not using* them:
* **They are 1 byte, while an immediate load is two bytes.**
* They are also faster (not generally a consideration for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")): they take 4 T-states, while an equivalent immediate load takes 7 T-states (8 on SM83).
They have a single side-effect: they modify the flags, while a load does not.
You can play around with this if you also want some flags to be set/reset.
On Z80, the flags are affected as follows:
| Flags: | `S` | `Z` | `H` | `P/V` | `N` | `C` |
| --- | --- | --- | --- | --- | --- | --- |
| `xor a` | `0` | `1` | `0` | **`1`** | **`0`** | `0` |
| `sub a` | `0` | `1` | `0` | **`0`** | **`1`** | `0` |
[Answer]
## Use `jp` instead of `call` and `ret`.
In some cases, `jp` is viable (contrary to the other answer). `call procedure / ret` can in some cases be replaced with `jp procedure`, saving one byte.
] |
[Question]
[
# Introduction
You are listening to a car radio. You are pressing seek up/down, moving you to the next frequency some radio station broadcasts on, to avoid all this pointless music and listen to all the ads, or vice versa. If you try to go below the lowest frequency radio can handle, it jumps to the highest (and vice versa). Possible frequency range of a car radio is about 80-110 MHz with 2 decimals of precision.
But there is a tendency of these broadcasts to have your radio jump to another frequency, where signal of that radio station is stronger. So, suppose this radio station A broadcasts at 99, 100 and 101 MHz with 100 MHz having the strongest signal at your place. The moment you reach 101 MHz, radio will jump to 100 MHz.
Because of that, you can get trapped. Suppose there is one extra radio station B, broadcasting only at 102 MHz. The moment you are stuck at the station A, you can never listen to station B again - if you try going with frequency down, you will hit 99 and jump to 100, if you go up you reach 101 and jump to 100 again... never escaping that trap and radio station.
But if there is yet another station C at 99.5 and 98.5 MHz with latter being the strongest, you can listen to all 3 radios again - starting from B you get down to A, then down to C, then pressing down loops you back again to the highest frequency and station B.
So, you start wondering - given a list of radio stations, can I listen to all radio stations at least once if I start at the correct frequency? And will I be able to endlessly cycle through all of them, or listen to all just once before getting cut off some stations?
# Your task:
Get a list of radio stations, along with a designation of which has the strongest signal, in any reasonable format (1). Return one of three options to distinguish whether you can cycle through all stations indefinitely, you can cycle through all stations once or you cannot reach all stations from any starting point. Again in any reasonable format (2). Standard loophole rules apply.
(1) Test cases have different radio stations separated by semicolon. For each radio station, the strongest broadcast for the station is first, other entries separated by comma. You can pick anything else as your input format, along with any reasonable extra information you would like - for example number of radio stations, number of channels each station broadcasts at etc. Two stations won't share frequency. Frequencies can be assumed to be in typical car-like frequency range of say 80.00 to 110.00 MHz (or 8000 to 11000 if you prefer working with integers).
(2) Test cases have output as 1 - cycle all, 2 - cycle once, 3 - cannot reach all stations even once. You can return anything reasonable to distinguish these three options, as long as you return/print the value. For example, another possible output might be `T` meaning cycle all is true, `FT` meaning cycle all is false, cycle once is true, and `FF` meaning cycle all and cycle once are both false (= you can't reach all stations even once). Limitation: You must return everything in the same way, eg if your code outputs "cycle all" by crashing due to recursion depth, your "cycle once" and "cannot cycle" must also output by crashing.
# Test cases:
input: 102; 100, 99, 101 output: 2
input: 102; 100, 99, 101; 98.5, 99.5 output: 1
input: 100, 99, 101; 103, 102, 104 output: 3
input: 100, 99, 101; 103, 102, 104; 101.5, 99.5, 103.5 output: 1
input: 100, 99; 99.5, 100.5; 102, 103; 102.5, 101.5 output: 3
May the shortest code win.
[Answer]
# JavaScript (ES10), ~~179~~ 155 bytes
Expects an array of arrays of frequencies, with the strongest broadcast in first position for each station.
Returns \$1\$ for *cycle once*, \$0\$ for *cycle all*, or \$3\$ if there's no solution at all.
```
a=>a.some(h=A=>a[(g=([x],C=q=>a.find(d=>d.includes(b[(b.indexOf(x)+q)%n])))=>!g[x]&&g(C(g[x]=1))-~g(C(n-1)))(A)],b=a.flat().sort(),n=b.length)|2*a.every(h)
```
[Try it online!](https://tio.run/##nZBLTsMwEIb3nMIsqMbguHFCJYLkSFUPwAGiLJzEeaBgt3lUQUJcPdikraIKRIQX9v/PaL6Z8as4ijZtqn3nKJ3JMeej4KGgrX6TUPKt0REUHKIhJjt@sKm8UhlkPMxopdK6z2QLSQSJcZkcXnIY8MMB36kYY8zD28JUrlYF7MAqzjB2Pq1TjpEYtjgmCTfQWnSATdvGPETxhNZSFV2JP7x7QeVRNu9Q4jHVqtW1pLUuIIcoQsz1UEyQFS5BQUCMYCg2zdGCs14j3Xf7vntG3s1Sto0ET3RjQ3Tza68Zm/3EvkYy17fOs9fjHxvM2P4/2FOInVewUf@yyaK5T79wKnZt8QT9buFf3JRnZ/h87vEL "JavaScript (Node.js) – Try It Online")
### How?
We first create an array `b[]` holding all frequencies sorted in lexicographical order. It means that the 80-99Mhz range will be put after the 100-110MHz range. But because the frequencies are wrapping around anyway, it doesn't matter. We also put the total number of frequencies in `n`.
```
b = a.flat().sort(), n = b.length
```
The helper function `C` takes a direction `q` and returns the sub-list corresponding to the station that is reached by moving towards `q` from the current leading frequency `x`.
```
C = q => a.find(d => d.includes(b[(b.indexOf(x) + q) % n]))
```
The callback function `h` takes the sub-list `A` of a station and walks through all connected stations, keeping track of the count (let's call it `N`). We use `q = 1` to seek up and `q = n - 1` to seek down. We eventually test `a[N]` to figure out whether all stations were reached.
```
h = A => a[(g = ([x], C = ...) => !g[x] && g(C(g[x] = 1)) - ~g(C(n - 1)))(A)]
```
This uses the helper function `C` described above and another recursive function `g` whose underlying object is also used to keep track of the stations that were already reached, using the leading frequency as the key.
We invoke `h` twice: once within a `some()` to detect *cycle once* and once within an `every()` to detect *cycle all*.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~58~~ 36 bytes
```
;þ`Ḣ)ẎṢṪ€i@€FṢ$µṙⱮØ-Zị@QċþQæ*LẠ€Ạ;ẸƊ
```
[Try it online!](https://tio.run/##y0rNyan8/9/68L6EhzsWaT7c1fdw56KHO1c9alqT6QAk3IBclUNbH@6c@WjjusMzdKMe7u52CDzSfXhf4OFlWj4Pdy0AKgKS1g937TjW9f/opIc7Z1g/apijoGun8KhhrvXhdrCQimbk///RXNHRhgZGsToKQMpAR8HSUkfB0MAwNlYHhwSQb2mhZwoS0DOFKUOVNzQwBrGNQIQJMUrAAoYwQ0Fixmhmg62FyhkA5cA6wLqNoWyInCFIH1csAA "Jelly – Try It Online")
A monadic link that takes as it’s argument a list of lists and returns `[0,0]` if it’s not possible to reach every station, `[0, 1]` if each can be reached once and `[1, 1]` if they can be cycled through indefinitely.
## Explanation
```
) | For each radio station:
;þ` | - Concatenate each frequency to each of the other frequencies, as a list of lists
Ḣ | - Head - i.e. each frequency paired with the main frequency for the station
Ẏ | Join lists together
Ṣ | Sort (so now in frequency order)
Ṫ€ | Tail of each (i.e. just the main frequency)
i@€ $ | For each, index of the station in the list generated by taking the original input and:
F | - Flattening it and
Ṣ | - Sorting it
µ | Start a new monadic chain
ṙⱮØ- | Rotate by each if -1 and 1
Z | Transpose
ị@ | Take only the main stations (which are
Q | - The unique values)
ċþQ | Generate an adjacency matrix
æ*L | Matrix to the power of the length(number of stations)
Ạ€ | Check wherher rows are all true
Ɗ | Following as a monad:
Ạ | - All
; | - Concatenated to
Ẹ |- Any
```
[Answer]
# [J](http://jsoftware.com/), 85 81 78 bytes
```
[:~.#=[:+/@((]+.+./ .*)^:_"_ 1[:=#\)>+./@e."1/~/:~@;(]/:~e.#[:|:_1 1|."{[){.&>
```
[Try it online!](https://tio.run/##jY1RS4RQEIXf/RUHhbxmjY62kFdcpKCnqOjVNgm5UhEKEkHs4l@30dUKouhhztyZ8525z4NNbo1Mw8URQmipY8L57eXFUOienKzQfpArtfHJpwB06N3r0i7Bhc6cO28ty9yQzUEf6D5P1UaaIafQO10yeEf2tvC2dLAePOvqjMDIUL1XLwZ125k300Exnhpc3@z98NNvm8pARd9NFrvtRKYrD437OrMqXjDLVI8tanAYpSIhkkQaY4xHe9N1f4FSJKe0kkFkCvDPwBfLYTwekDqZ4Pif8Djw8o3sRf/4K124kFbpfCKeHtOW53RsDR8 "J – Try It Online")
## the idea
Let `n` be the number of the stations.
* Create an adjacency matrix representing connections between stations.
* For each starting station create an `n` item vector with a single `1` in
the starting station's position, and 0 elsewhere, to encode the starting
position as a vector.
* For each starting vector, iteratively multiply by the adjacency matrix `n` times,
collecting intermediate results. The final vector represents which stations
you can visit from the starting vector.
* Sum that final vector. This is the *number* of stations you can visit from
that starting station.
* Check if that sum is equal to `n`. If it is, all stations can be visited.
* Now we have `n` final sums, each of which will be `0` (you can't visit all stations
from that starting station) or `1` (you can). Uniquify that 0-1 list. Then note:
+ A single 1 means every starting station returned 1, meaning any station
can be visited (via some number of hops) from any other. This is case 1.
+ A single 0 means you cannot visit all stations from any starting point. Case
3.
+ Both a 0 and 1 means it's possible to visit all stations from some starting
point, but not from all. Case 2.
] |
[Question]
[
Imagine four people stand in a line. The first looks at a thermometer, and tells the temperature to the person on their right. This continues down the line, until the last person writes the temperature on a sheet of paper. Unfortunately, due to a miscommunication, every person in the line converts the temperature to their preferred unit, without knowing which it already was.
Let's say the people's preferred units are `celsius`, `fahrenheit`, `fahrenheit`, `celsius`. The first reads the temperature as 20°C. The second converts to fahrenheit, and determines that it is 68°F. The third, not knowing they have received the temperature in °F already, determines that it is 154.4°F. Finally, it is converted back to °C by the fourth person, who determines that it is 68°C.
**Task:**
You will be given two inputs: a temperature (`t`), and a number of people (`n`). Your program (or function) should return the average difference between the original and resulting temperatures, for every possible assortment of `n` people.
There are two temperature units: °F and °C. To convert between them, you can use \$F=\frac95C+32\$ and \$C=\frac59(F-32)\$.
You can choose whether your program receives the inputted temperature in °F or °C. The first person should always receive an accurate temperature, converted to their preferred unit only if necessary.
As an example, we'll use an inputted temperature of 41°F, and just 3 people. There are 8 temperature preferences possible:
```
FFF 41°F -> 41.0 -> 105.8 -> 222.44 -> 222.44°F
FFC 41°F -> 41.0 -> 105.8 -> 41.00 -> 105.80°F
FCF 41°F -> 41.0 -> 5.0 -> 41.00 -> 41.00°F
FCC 41°F -> 41.0 -> 5.0 -> -15.00 -> 5.00°F
CFF 41°F -> 5.0 -> 41.0 -> 105.80 -> 105.80°F
CFC 41°F -> 5.0 -> 41.0 -> 5.0 -> 41.00°F
CCF 41°F -> 5.0 -> -15.0 -> 5.00 -> 5.00°F
CCC 41°F -> 5.0 -> -15.0 -> -26.11 -> -15.00°F
```
The average distance from 41°F is 54.88°F, which is the program's output.
**I/O:**
Temperature should be represented as a float, decimal, or fraction of some sort. The accuracy should be within reasonable bounds; for inputs less than ten people at low temperatures there shouldn't be floating point errors or imprecision noticeable in the first four decimal digits.
You may represent the temperatures inputted and outputted as either °F or °C, but must be consistent (although the input can output can be different units as long as they don't change). Temperatures can be negative. The number of people will never be less than two.
The output is referred to as a temperature above, although it's technically the arithmetic mean of multiple temperatures.
**Test Cases:**
Input unit is the same as output unit for all test cases.
```
41°F 2 -> 25.2
41°F 3 -> 54.88
41°F 4 -> 77.236444...
41°F 10 -> 295.4268...
20°C 4 -> 57.21218...
-1°C 2 -> 12.133...
-20°C 2 -> 6.2222...
-40°F 4 -> 0
```
**Other:**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes per language wins!
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 41 [bytes](https://github.com/abrudz/SBCS)
```
(|40+⎕)+.×(|÷≢)1-1.8*1(-,+)⍨⍣(⎕-2)⊢1-3|⍳4
```
[Try it online!](https://tio.run/##RY6/bsIwEMZ3P0VGG@dofPbQvUtZCy@AqFwGpHZFSaZKSCAZtQNih6VbhgohMSZvci@Snp1WXfz5fvfn@@ZvK3hez1evL31fysoVmsJN6XF3lFV3pe1JGTDj@5GRkGtF4YvCWVK4ACranQzYisK3q3tPmw8Ke9q9t42lzSftD9OnB35nj5Np70zmMxRJ7CBuEFOItnFFAgAghMcFnyotarbtjmxViwXG82UE1xThAhZrsYxQ6rshJwe5geT1nIMpyTs5F@o/b0Kxx4O1wCJbsmfbGFZkTQAj97/c/3H@/AA "APL (Dyalog Unicode) – Try It Online")
A full program. Takes the number of people, then the initial temperature. TIO version is wrapped in a function for easier testing. As I pointed out in a comment, the initial and final units do not matter as long as they are equal.
### The math
The code exploits the fact that Fahrenheit-Celsius conversion has a fixpoint at -40 (-40°F = -40°C). Then we can add 40 to all temperature readings, and then the whole series of conversion reduces into a (positive or negative) integer power of \$\frac95\$.
$$
F+40=\frac95(C+40), \quad C+40 = \frac59(F+40)
$$
Since every temperature value is offset by the constant value of 40, the difference between two offset temperature values is the same as that of the original. Therefore, it suffices to apply the offset to the initial temperature and ignore it to the end.
Let's call \$r = \frac95\$.
Now to the part of counting all conversion paths. Let's say the initial reading is in Fahrenheit. Then:
* Initial conversion: `F→F` (\$r^0\$) or `F→C` (\$r^{-1}\$).
* Final conversion: `F→F` (\$r^0\$) or `C→F` (\$r^1\$).
* All inner conversions: `C→F` (\$r^1\$) or `F→C` (\$r^{-1}\$).
So the task reduces to finding all the individual terms in the expansion of \$(r^0 + r^{-1})(r^1+r^{-1})^{n-2}(r^1+r^0)\$. Then plug in the value of \$r\$, evaluate the average of differences to 1, and then multiply with the initial temperature (with offset).
### The code
```
(|40+⎕)+.×(|÷≢)1-1.8*1(-,+)⍨⍣(⎕-2)⊢1-3|⍳4
⊢1-3|⍳4 ⍝ A fancy way to create an array of 0 ¯1 1 0
⍝ which represents the powers in (1+r^-1)(r+1)
⍣(⎕-2) ⍝ Repeat n-2 times...
1(-,+)⍨ ⍝ multiply the given polynomial with (r+r^-1)
⍝ and list all powers
1.8* ⍝ Plug in r = 1.8 and evaluate the powers
1- ⍝ Difference of each value from 1
(|÷≢) ⍝ Average of absolute differences from 1
+.× ⍝ Product and sum with...
(|40+⎕) ⍝ Absolute difference between -40 and t
```
[Answer]
# [Python 3](https://docs.python.org/3/), 126 bytes
```
f=lambda t,n,x=0,i=0,j=0:(f(i and 9*t/5+32or t,n,x or t,i+1,0)+f(5/9*(t-32),n,x or t,i+1,1))/2if i-n else abs(t+(32+.8*t)*j-x)
```
[Try it online!](https://tio.run/##XY3LCoMwFET3/Yq7zM2j5qFQC35MREMjNorehf36VOzGuhiYMzMw84deU3I5h2b077bzQDLJrdEy7hoa/WSBRfCpg5pTUQlnp@W3gcNEYaRGEVhV1JyRchb/S4NY2BggqgT9uPbg25WRYM6K@4MT8kFtmOclJtqvSiPBIt7O7C5cXtjoU6BKfSzyFw "Python 3 – Try It Online")
`j` is 0 or 1 depending on whether current temperature is in F or C.
`i` denotes the number of conversions that we have already performed. We perform both of the possible conversions and take the mean of the answer.
`x` is an extra variable just used to keep track of the original temperature.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~55~~ 51 [bytes](https://github.com/abrudz/SBCS)
```
{(2.8×|40+⍺)+.×(|1-1.8*x-⍨⍳2×x)×2/(⍳x←⍵-1)!⍵-2}÷2*⊢
```
[Try it online!](https://tio.run/##LY@xTsMwEIZ3P0XY7KaX2pcM3VnaCYnyAlVR6FAJxqAkE1KlVnIFA8peFrYMqKrEGL/JvUg42yz@fd/57v@9ftnB4@t69/w00ulzeUf7dz3WErO565pCp2R/VZq5TjYGTDafVED2m@wPuq5SrsOZ5KLiKbIXMOrGC7buihM6nscyNE50fBv6nPYfbLG6v@XzYbFcjYVJygRFkDxKEcVoMfSFDmDoDcYWAAhR4oaX1jmmxmdkv1Zs0BvVHlxDvAvk2IqthzKdMTycVcNfAcnjU06mJM9MuVBkv2QIHZHv8cNWoE620Z0VWQNAz/9ThfCB8@UP "APL (Dyalog Unicode) – Try It Online")
*-4 bytes thanks to @tsh*
I finally managed to derive the correct version of [tsh's formula](https://codegolf.stackexchange.com/a/222657/78410), though it turns out to be slightly longer than [brute force](https://codegolf.stackexchange.com/a/222651/78410).
$$
(1+r)\sum\_{p=-n+1}^{n-2}{\binom{n-2}{\left\lfloor\frac{p+n-1}{2}\right\rfloor} r^p \operatorname{sgn}\left(p+\frac{1}{2}\right)} \div 2^n \\
= (1+r)r^{-n+1}\sum\_{p=0}^{2n-3}{\binom{n-2}{\left\lfloor\frac{p}{2}\right\rfloor} r^p \operatorname{sgn}\left(p-n-\frac{1}{2}\right)} \div 2^n \\
= (1+r)\sum\_{p=-n+1}^{n-2}{\binom{n-2}{\left\lfloor\frac{p+n-1}{2}\right\rfloor} \left|r^p - 1\right|} \div 2^n \\
\text{ where } r = 1.8
$$
In array terms, the first and second formula are equivalent to building a vector containing two copies of each binomial coefficient, negating half of it, and multiplying each with suitable power of \$r\$.
The code above uses the third line of the formula.
The process of deriving the formula was essentially spotting two copies of Pascal's triangle in the expansion of polynomial \$(r^0 + r^{-1})(r^1+r^{-1})^{n-2}(r^1+r^0)\$, defining an intermediate function (\$[x;y;z]\$ denotes `if x then y else z`)
$$
f^+(n, r) = \sum\_{p=0}^{n-1}{\binom{n-1}{p} r^{2p-n} [2p-n\ge 0; 1; -1]},
$$
defining the sum of differences in terms of \$f^+\$ as
$$
g(n) = f^+(n-1, r) - f^+(n-1, r^{-1}) + rf^+(n-1, r) - r^{-1}f^+(n-1, r^{-1})
$$
and simplifying it over an entire sheet of paper.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 84 bytes
```
T=>U=>g=(N,p)=>(--N?g(N,~-p)+g(N,p+1|0):Math.abs(U**p-1)*(1+U)*(T+40))/2,C=5/9,F=9/5
```
[Try it online!](https://tio.run/##dc@xDoIwEAbg3Se5oxxQhAGT4kDCJhM8QEWoGkIbIU7GV68lcQOWy12@/Ml/T/mWU/t6mJlGfetsL2wt8kbkSkDlGxQ5EFVn5Y4vGWTLYhj/RHi6yPkeyOsEjecZ4ugBZ42bNUsixDD2C5GGmV@KLExtq8dJD10waAU9JByhRIgRD5tw3INkD3i0EnI1tjOxg2IL3BcLrHvRP7KI/QE "JavaScript (Node.js) – Try It Online")
[Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler) had worked out the correct formula, so I would like to remove the incorrect (many off-by-one errors) one here. You may read more about math formulas from [Bubbler's post](https://codegolf.stackexchange.com/a/222710/44718). You may find out a solution based on that formula from history of this post.
But calculating binomial coefficient costs too many bytes. So using recursion results a shorter solution here. And the recursion function:
$$
U=\begin{cases}
5/9 && \text{Input is ℃} \\
9/5 && \text{Input is ℉}
\end{cases}
$$
$$
g\_U\left(n,p\right) = \begin{cases}
\left(g\_U\left(n-1,p+1\right)+g\_U\left(n-1,p-1\right)\right)/2 & n > 1 \\
\left|U^{p}-1\right| & n = 1
\end{cases}
$$
$$
f(T,U,N)=\left(1+U\right)\left(T+40\right)\left(g\_U\left(N-1,0\right)+g\_U\left(N-1,-1\right)\right)/4
$$
---
[Answer]
# [J](http://jsoftware.com/), 84 bytes
```
g=.32+*&9r5
[:(+/%#)[|@-[(g inv@]`(g@])@.[/@,~)&>2<@([:1&,^:(1-{.)}:^:{:)"1@#:@i.@^]
```
[Try it online!](https://tio.run/##RYzLDoIwEEX3fEUjkbSihRmgLY2Y@Y8GNDGCuNCkCzeov45RfNzlyTn3NI5dJTOMF1Hpi6CtpLM8TuahcDdaOd6x/nylesc7qgVJl9DyIaINrok7C9GysRxWgxR329jBihlQaKmX1NTjYX@8MMg0eixYxXJgLcuCiaLyP4YTM8qU4AH@cv6RtVKoQRmVQWkAEXxRaqNfavreN4B0Kl5gm6fvi/EJ "J – Try It Online")
Takes input and output in F.
Returns exact output as a rational number.
This hasn't been fully golfed, and it's possible there are large savings to be gained from a different approach.
## tldr how
* Generate all binary numbers from `0` to `2^(number of people)`.
* `1` represents "convert to F" and `0` "convert to C".
* Remove `1` from the end of any binary number that ends in `1` (since an initial F person reads the F thermometer correctly).
* Add `1` to the beginning of any binary number beginning with `0` (since a final C reading must be converted to F).
* Evaluate each resulting binary number right-to-left like a pipeline of conversions.
* One nice thing is that J is able to invert the conversion for us, so after defining the F conversion as `g`, we get the C for free as `g inv`.
* Finally take the average of the absolute differences from the starting temp.
] |
[Question]
[
JavaScript has no direct support for keyword arguments, but it supports argument object [destructuring](https://en.wikipedia.org/wiki/Assignment_(computer_science)#Parallel_assignment). It is standard to use a destructed final argument for keyword arguments. Here is an example:
```
function f(x, { a = 7, b = 2}){
return [x, a, b];
}
```
You would then call this function like:
```
f(9, {}); // ==> [9, 7, 2]
f(9, {a : 3}); // ==> [9, 3, 2]
f(9, {b : 3, a : 1}); // ==> [9, 1, 3]
```
The object may also supply a separate default if you omit the object entirely:
```
function g({ a = 7, b = 2} = {b : 3} ){
return [a, b];
}
g() // => [7,3]
g({}) // => [7,2]
```
### Goal
Given an argument specification for a JavaScript function, determine whether it "supports key word arguments". The input must be a valid argument specification for a JavaScript function. It "supports key word arguments" if the last argument does object destructuring. See many examples below.
You may assume that no strings appear in the input (so no single quote `'` double quote `"` or uptick ```). You may also assume that the spread operator `...` does not appear.
(It would be nice to have the grammar for JavaScript argument specifications here but on a quick google I didn't find a readable reference. [This section of the ECMAScript specification](https://tc39.es/ecma262/2020/#sec-left-hand-side-expressions) looks relevant, but I can't make sense of the grammar they provide. If anyone can suggest a readable link, I will add it.)
## Scoring
This is code golf, and the shortest code wins.
## Examples
```
"" // empty params ==> false
"x" // single normal argument ==> false
"x " // test is space insensitive ==> false
"{x}" // ==> true
"x, y, z" // multiple normal arguments ==> false
"x, y, {z}" // ==> true
"x, {y}, z" // ==> false
"x, {y}, {z}" // ==> true
"{}" // ==> true
"{} = {}" ==> true
"[] = {}" ==> false
"{} = []" ==> true
"[] = []" ==> false
"{} = null" ==> true
"[{x}]" // ==> false
"[x, y, z]" // ==> false
"x," // ==> false
"{x}," // ==> true
"x, { y = 2 }" // ==> true
"{ y = 2 }, x" // ==> false, not last argument
"{ x = 2 }, { y = 2 }" // ==> true
"{ a = 7, b = 2}" // ==> true, this is f above
"{ a = 7, b = 2} = {b : 3}" // ==> true this is g above
"{ a = [7, 1], b = { c : 2} } = {}" // ==> true
"{ a = 7, b = 2} = {}" // ==> true
"{ a = 7, b = 2} = null" // ==> true.
"{ x = { y : 2 }}" // ==> true
"x, [y, { z }]" // ==> false
"[x] = {[Symbol.iterator]: [][Symbol.iterator].bind([42])}" // ==> false
"x, y = function ({z}) {}" // ==> false
`x, y = ({z}) => {z}` // ==> false
```
Unspecified inputs:
```
","
"x y"
"x = '2, {y}' " // no syntax error but default is a string
...[x, y, { keyword },] // no syntax error but contains illegal ...
"{x"
"{{x}}"
"{[x]}"
"{1}"
"x,,"
"x, { x = 2 }"
"{ x = { y = 2 }}"
"{ x : 2 }"
```
Here are the tests as a JSON string:
```
"[[\"\",false],[\"x\",false],[\"x \",false],[\"{x}\",true],[\"x, y, z\",false],[\"x, y, {z}\",true],[\"x, {y}, z\",false],[\"x, {y}, {z}\",true],[\"{}\",true],[\"{} = {}\",true],[\"[] = {}\",false],[\"{} = []\",true],[\"[] = []\",false],[\"{} = null\",true],[\"[{x}]\",false],[\"[x, y, z]\",false],[\"x,\",false],[\"{x},\",true],[\"x, { y = 2 }\",true],[\"{ y = 2 }, x\",false],[\"{ x = 2 }, { y = 2 }\",true],[\"{ a = 7, b = 2}\",true],[\"{ a = 7, b = 2} = {b : 3}\",true],[\"{ a = [7, 1], b = { c : 2} } = {}\",true],[\"{ a = 7, b = 2} = {}\",true],[\"{ a = 7, b = 2} = null\",true],[\"{ x = { y : 2 }}\",true], [\"x, [y, { z }]\", false], [\"[x] = {[Symbol.iterator]: [][Symbol.iterator].bind([42])}\", false], [\"x, y = function ({z}) {}\", false], [\"x, y = ({z}) => {z}\", false] ]"
```
## A reference implementation
Here is an ungolfed reference implementation in JavaScript (it uses nothing specific to JavaScript and could be easily ported to other languages).
```
function supportsKwargs (funcstr) {
let START_ARG = 1;
let ARG = 2;
let paren_depth = 0;
let arg_is_obj_dest = false;
let state = START_ARG;
for (let i = 0; i < funcstr.length; i++) {
let x = funcstr[i];
// Skip whitespace.
if(x === " " || x === "\n" || x === "\t"){
continue;
}
if(paren_depth === 0){
if(x === ","){
state = START_ARG;
continue;
}
}
if(state === START_ARG){
// Nonwhitespace character in START_ARG so now we're in state arg.
state = ARG;
arg_is_obj_dest = x === "{";
}
switch(x){
case "[": case "{": case "(":
paren_depth ++;
continue;
case "]": case "}": case ")":
paren_depth--;
continue;
}
}
return arg_is_obj_dest;
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 44 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
…
м©¼¬ˆε',Q¾*i®N>èˆ}…[{(yå½…]})yåi.¼]¯θ'{Q
```
Simply a port of the reference implementation.
[Try it online](https://tio.run/##yy9OTMpM/f//UcMyBS7OC3sOrTy059Ca023ntqrrBB7ap5V5aJ2f3eEVp9tqgSqiqzUqDy89tBfIjK3VBDIz9Q7tiT20/twO9erA//@rFRIVbBWizXUUDGN1FJKA7GqFZAUrBaNahVoQp/a/rm5evm5OYlUlAA) or [verify all test cases](https://tio.run/##dVFNSsNAGF3rKT5m00QmAasgBNreQCiCm2EWSW0hEBOoqWQyBFzlAN5BURDdWHARXUyXheIZepE4mUliIJrF8N73@/K@6Mb1/Hl5yyYI9vk9oAlD5f7uEQ4PvgvxLArxss136wGeiq8jX7yejzdP2zyTFYQbbPMgPiWkmSmhb4uCirfdx4BPS2RfYlusxXtJEE8yhAElGBgGnjaEs6ylvH5hBB1IaAvDVRAokmS46QcmE0PQ9ZBo0ou7kpxh8KrYX6FqpQcOnHSSRGaPqa7gMJNZWdcR15/wT7yVreRVypxKmapWv6EeqL5fi9KuQYoQ2u5QUBtDpBka1H1UN@qFrPEjqceRyn1IoelRM8kFu/aiwPbj@dKNoyV15PBe0Pb88Mogp0NqtqeU3YtVOIv9KARDntGsBdY5HRqN1YVpaVlhZAVuyn4A).
**Explanation:**
```
… \n\tм # Remove all spaces, tabs, and newlines from the (implicit) input
© # Store this new string in variable `®` (without popping)
¼ # Start the counter variable at 1 (it's 0 by default)
¬ # Get the first character of the string (without popping)
ˆ # And pop and add it to the global array
ε # For-each `y` over the characters in the string:
',Q '# If the current character is a ","
¾*i # and the counter variable is still 1:
® # Push the string from variable `®`
N> # Get the for-each index, and increment it by 1
è # Index that into the string, to get the next character
ˆ # Pop and add that to the global array
} # Close the if-statement
…[{(yå # If the current character is in the string "[{(":
½ # Increment the counter variable by 1
…]})yåi # If the current character is in the string "]})":
.¼ # Decrement the counter variable by 1
] # Close both the if-statement and for-each
¯ # Push the global array
θ # Only leave its last item
'{Q '# And check if this is equal to "{"
# (after which the result is output implicitly)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~36~~ 35 bytes
Some parts are taken from [Kevin Cruijsen's answer](https://codegolf.stackexchange.com/a/217520/64121)
-1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!
```
…
мS©…[{(®å…]})®å-.¥_®',Q1š*Ïθ'{Q
```
[Try it online!](https://tio.run/##bVFBasMwEDxXr9hb7KIakhYKhuQPIUchgpWmYHBsSByQrRr6g74hhxR6ya3QQ08OvYa@oR9xdyU7EBxhtKOd2WV2nW0iFS@bl9Nn8/f6Duzm93tWfyAUxqsPxz0iWfmE7oJ6P68PAz4d/uxuj2@nr4GZNo3RFdMcCg6mtMgUlcOGPhhDF4V0Md0mCcMybtVQYGoEqAHt0GUyQvTIQVGi96buCkK47xiB1FA62sACKRR1Jvq115LOnjVDPkLyUTFgmmmg005bnmctmZCumY04psDp8G6FEpXsPBIHTZWCFgYlWJ0tF7NipbIkiPPlOsqztQyxVS8ZqDh98sTDSPpu71j6vE0XeZyl4OHafTLSEu49ntDv@Ac "05AB1E – Try It Online")
**Commented**:
```
…\s\n\tм # remove all whitespace from the input
S # split into a list of characters
© # store this list in the register (without popping)
…[{( # push string literal "[{("
® # push the list from the register
å # for each character check if it is in the string "[{("
# this is now a list with 1's at the indices of opening brackets
…]}) # push string literal "]})"
® # push the list from the register
å # for each character check if it is in the string "]})"
# this is now a list with 1's at the indices of closing brackets
- # subtract element-wise
.¥ # take the cumulative sum and prepend a 0
# this a list of the parentheses depths
_ # for each element: does it equal 0?
® # push the list from the register
‛,Q # for each element: does it equal ","?
1š # prepend a 1, this list is 1 at index N if N==0 or ®[N-1]==","
* # multiply element-wise with the previous list
Ï # take the elements in the input where a 1 is in this list
θ # take the last element of this
‛{Q # is this equal to "{"?
```
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 69 bytes
```
x=>Reflect.parse(`function f(${x}){}`).body[0].params.pop()?.type>'I'
```
[Try it online!](https://tio.run/##hZNRT4MwFIXf9ytuFpO1SSU6TUy2bG8@6IMm@libWFhRlEFTOkOH/PbZApvSofJA0nO/e@Gctm/8gxeRSqQ@LWSyEmqdZ@/C7OLFrlws0YOIUxHpQHJVCPQcb7JIJ3kGMTqpyhpX9TMOwnxl6BlzDF8Xgcwlwp@fVY0DbaRYTm4mu/nt4/1dN2RM6dP4aUxinhaCEbso@ytwT0@yn7JrrTYdQcAQ2Pa7Gq3a@mBl6gG0UT248lawgL5E2V768WcOo@wIayQPyzZp2gOtrT5GO2fM@18/DOKbBGPnT6HvYC8S6AdcQbkv/NLIrXhFIHS1v0oujxBmcDEAUUuds5asILKU5Y9DHZj4T92PsbXjnMyck@9uaMOh7lzAFpqsoYsBmrSbDaWPZh3maZBoobjOFZvZ3TsSgzDJVoheThmuvTlu0@ygw91A9mDh1sYA1lYXy@74dQSwMQ7iXF3z6BUhmmRyowmIUtrLJ1asbRhpZexbqiTTKEYNhL8pAs0tK7StvySx6QA8H9UQcR29AhL40D/I2mEOH9V4vvsC "JavaScript (SpiderMonkey) – Try It Online")
Certainly you need right tools for this question...
SpiderMonkey on TIO is a bit old and won't work correctly for above code. You may download newest version of jsshell from <https://archive.mozilla.org/pub/firefox/nightly/latest-mozilla-central/> .
It is strange that, using `function f(){}` instead of `()=>{}` in JavaScript may save bytes.
[Answer]
# JavaScript (ES6), 96 bytes
A minimal parser that expects a list of characters and returns `0` or `1`.
```
a=>a.map(c=>n=(i=",{}[]() ".indexOf(c))<7?~i?i?(o|=n/(d+=i&1||-1)/i)&0:!d:n?o=0:0:n,n=1,d=o=0)|o
```
[Try it online!](https://tio.run/##jZNdb9MwFIbv@ysOuVhtzfPaMTEp4EZIFAkxaRdcWr5w8zGMMrtKUtQ2LX@9O25aCbAHy53f87zHPh/5oX/qNm/MsruyrigPlThoMdP8SS9JLmZWECMS1u@lIhQSbmxRrh8qklP64S77ZTKTEbcT9poUl8JcTHe7qym9NvRikr4pUps5MUknqWVWTFkh8ER37vBejgAkJAmDStdtCYoNwjpUwH@B3K/3qHXN6jeSwYbBNsxw1PutNwSOfrN/wXOMDK4/TH1EAQGhLNVZ/uvpHpcqih/lCG5XdR0YsAchLk9tUJGaYl1kkTb2sME7byCs9BxgEE6qh/U5@I8EGgN3DBY@/r@w798CUnj7AiiRnKqB7iFHEj3xYUQyv4KJtX0o01eY@gpjayj9vsEWouM5boX8tnlauJqbrmx05xqV4ugDkS/wbyPy9kbRfXStMVW1snlnnAWCu0pj@3YCh7iYnXb6xIzUiFeumev8OyGyZdCUrfIYenNnW1eXvHaPpOVLXczxNe9uKVwCIY2/m0jOOfJeShJ6ZgYECeHTQQbjh69jbNf488cv9/NPY0pH9PAM "JavaScript (Node.js) – Try It Online")
### Commented
Variables:
* `d` is the current depth (0 = root)
* `n` is a flag telling whether we're at the beginning of a new block at the root level
* `o` is a flag telling whether the last block is an object
Source:
```
a => // a[] = array of characters
a.map(c => // for each character c in a[]:
n = // update n:
( i = ",{}[]() " // i = index of c in this string
.indexOf(c) //
) < 7 ? // if c is not a space:
~i ? // if c is one of the characters defined above:
i ? // if c is not a comma:
( o |= // set the flag o if:
n / // n = 1
( d += i & 1 // and the updated depth is 1
|| -1 // (incremented if i is odd, decremented if even)
) / i // and i = 1 (i.e. c is "{")
) & 0 // clear n
: // else (comma):
!d // set n if we are at the root level
: // else (other character):
n ? // if n is set:
o = 0 // clear o and clear n
: // else:
0 // clear n
: // else (space):
n, // leave n unchanged
n = 1, // start with n = 1
d = o = 0 // start with d = o = 0
) | o // end of map(); return o
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 38 bytes
```
+`{([^{}]|{})+}
{}
\s
,$
=[^,]*$
}$
```
[Try it online!](https://tio.run/##hVLbasMwDH33V4jQQbqZlF1gUOhe9wF79FzqdG5nSJwSO6Wp52/v5HRZc@lYCIQcnSPpSCqlVVqcXldRchuRm3i1xG@c3E7xf0Im96e7lYvZ0nn@5fz0zhPnybshhE4IWbAl5cgifnI6RRHMZiDzna1hJ0qRG1gsXmAjMiNJdGiiRultJkEXZS4yEOW2yqW2PR6EpyFbaSwoA2Yn1hKUNlIbZdVedvnu4BtygGxZhQwUagrHBs2rzKrduGK/tUbgjpdEl0yu9m2uvqIJdDWNBPsZtuM8LCCgF4jxDtT6CDTGR7QW6tJ0lWVRtyjDKfBhk@xnEHzc/RBBOR0aCR6hxmoPMLLU4hQO/VQUB20hE7i4dtSBfmjpf2QMHIGBZwppiPfDFOwnngG@GxBpsZcjehhnCnN47At/ddu@jqHwnp/FDtYoxBTtmgZOR3X@p5zX0yElpB1C8D8P/v2VcbNwhXCEa6tsLoa91XlaZImyshS2KPkcz2MEJqnSHzF7euBTf@VwwwI2lV5bVWiI8YKnXU993jmMcPfQz5Rv "Retina 0.8.2 – Try It Online") Link includes test suite that assumes all tests are on separate lines and enclosed in quotes. Explanation:
```
+`{([^{}]|{})+}
{}
```
Collapse all objects recursively to empty objects.
```
\s
```
Delete all whitespace.
```
,$
```
Delete any trailing comma.
```
=[^,]*$
```
Delete the last parameter's default value, if any.
```
}$
```
Check whether the last parameter is a destructured object.
] |
[Question]
[
# Introduction
So John finally has his holidays! And what better could he do than watching some movies. He indeed has a lot of movies to watch, but he is unable to decide which one to watch first. He has a list of movies, each in the format: `<Movie name> (<Year>)`. So he makes a simple set of rules to decide his order of watching movies.
1) The first preference is given to the release year. If a movie released a year or earlier than others, then he would watch them first.
2) If two or more movies released in the same year, and one of them begins with a number, then he would prefer to watch that movie first.
3) If two or more movies released in the same year begin with a number as well, then the movie which comes first on the original list would be watched first.
4) If two or more movies released in the same year begin with a letter, then the movie beginning with a letter which comes earlier in the English alphabet will be chosen first. If two movies begin with the same letter, then the one containing a lesser number of characters in the movie name(including spaces) will be chosen first.
5) If the number of characters is also same, then the movie which comes later in the original list would be watched first.
Well, what a great set of rules indeed. Now the challenge.
# Challenge
The input will be a list of movies, i.e, strings - all following the specified format, and you need to output the sorted list, following the above stated rules. Be case insensitive , i.e, treat both uppercase and lower case characters equally and assume all inputs to be valid, and the list will contain no duplicate elements. Also, every character in the movie name is either a letter, or a number and there are blank spaces only in between. You can assume the release year is 4 digits long.
# Examples
```
Input
Output
['The Town (2010)', 'The Prestige (2006)', 'The Departed (2006)']
['The Departed (2006)', 'The Prestige (2006)', 'The Town (2010)']
['Hello (2001)', '15 minutes (2001)', '25 Minutes (2002)']
['15 minutes (2001)', 'Hello (2001)', '25 Minutes (2002)']
['15 (1960)', '25 days (1960)']
['15 (1960)', '25 days (1960)']
['Jjjj (2004)', 'Hello (2004)']
['Hello (2004)', 'Jjjj (2004)']
['all gone (2018)', 'Be careful (2018)']
['all gone (2018)', 'Be careful (2018)']
['Be careful (2018)', 'all gone (2018)']
['all gone (2018)', 'Be careful (2018)']
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") , so the shortest code wins!
[Answer]
# [Python 3](https://docs.python.org/3/), 115 bytes
```
lambda a:sorted(a[::-1],key=lambda s:(s.split()[-1],-("/"<s[0]<":"),a.index(s)*("/"<s[0]<":"),s[0].lower(),len(s)))
```
[Try it online!](https://tio.run/##fY5BT4MwGIbv/IoGD2sXhi1uS2y2mwdjYuJht8qhhm9bsSuE1kx@PQIRqQS9Nc/79P3esnbnwtw1x/1ro@XlLZNIcltUDjIsBecrlkbvUO@/M8uxjW2plcNEdNkKh7fhzgqa7kIekkjGymTwiS1ZTpLuFeviChUmkQbTKoQ0ZaWMw0csFoczoENxNQgnlFGyiFCPXiqwTp2gw3T7gx@glN3IAaeEBDdIzGb/N/k30yAYBz2C1kUvs15mG3RR5sOB9WCyQc8eTMYls/q0c@a7P6HtwOx@Swc3k7UdiHfnb8cve8rzvL@ynkxZj2W/YCv5f9LmCw "Python 3 – Try It Online")
-11 bytes thanks to spec change (thanks Jonathan Allan for pointing it out)
-6 bytes thanks to Lynn
[Answer]
# [Red](http://www.red-lang.org), 108 bytes
```
func[b][s: copy[]foreach m b[append/only s reverse split m"("]foreach m sort/all s[print rejoin[m/2"("m/1]]]
```
[Try it online!](https://tio.run/##ZY7NqsIwEEb3PsXQVV21KSro@i4uFwQRdyGL2E6vKfkjE5U@fU2rouhyzpz55gvYDHtsgItZuxnas635UXDaQO18z0XrAsr6BAaOXHqPtimc1T0QBLxgIATyWkUwWZ69yeRCLKTWQNwHZWOyO6csN0WVRFMwIcTQAs8OJ4SDu1rIq5KV8wwmsgtIUf3jSMvVk/6glyGmrg8qZvfssXqK@kWt3bRj4wVbglH2HJFerFrC9o1VXxnpKGfrVfmQG9nTE3yYf13XTSGL0X39TqMYbg "Red – Try It Online")
## Explanation:
```
f: func[b] [ the argument is a block of strings
s: copy [] prepare an empty block
foreach m b [ for each string in the input block
append/only s reverse split m "(" split it on "(" and append in reversed order
]
foreach m sort/all s [ sort the new block
print rejoin[m/2 "(" m/1] and print it in the right order
]
]
```
Red's `sort/all` (sort function with refinement all) performs a stable sort, comparing all the fields of a compound argument:
```
sort/all [[1 2 3 1] [1 1 6] [2 1 3] [1 2 3 4]]
== [[1 1 6] [1 2 3 1] [1 2 3 4] [2 1 3]]
```
[Answer]
# PHP, ~~231 115~~ 113 bytes
PHP sort stabilized by using keys including the position
```
while($s=$argv[++$i])$a[substr($s,-6).($s<A?:$s&_).str_pad($s<A?$i:$argc-$i,$argc,0,0)]=$s;ksort($a);print_r($a);
```
Run with `php -nr '<code>' 'movie1 (year1)' 'movie2 (year2)' ...` or [try it online](http://sandbox.onlinephpfunctions.com/code/ffa4b9927b9a94b7e8546da64bb3adda481dc43f).
[Answer]
# [R](https://www.r-project.org/), ~~95~~ ~~87~~ 85 bytes
-2 thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard)
```
function(v)v[order(unlist(regmatches(v,gregexpr("[0-9]{4}",v))),tolower(v),nchar(v))]
```
[Try it online!](https://tio.run/##bZA9a8MwEED3/IojS3SggG2c0ECn0qEUCh2yhQzCPn8hS0aSnYbS3@7KArdpY03S495DkhkLeNyORa8yV2vFBhxO2uRkWK9kbR0zVLbCZRVZNvDSn@ijM2x9iraH82f6teYDInKnpb54aUCuskpMGzyPjtoOfB5CKWObY0Vw1BcFLIniCDccAno3ZF1d0oSj/Q9@pk4YR/mMkcMK/iyffCEpdZiIgxjvoK1V78jewGQHbzcwmVr3Ka@y@LCPZiUXVzuTpfnXpmlCLw3G703S5XkhJZRahWfGD8F5IsiEoaKXM1wS76e8@r@GuJKi6@SVTd/OocBx/AY "R – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 58 bytes
```
*.sort({~m/\(\d+/,/^\d/??(0,$++)!!(1,.uc.ord,.chars,$--)})
```
[Try it online!](https://tio.run/##Zc5BS8MwFMDxs/sUGRSa2CxNylaUIQPxIILgYbd1SmjSrSVtRtIiQ/Sr1yUjOvT6e//3koM0Kh/bI4gqcDdeE6tNDz@@2rSAhUhSnL4WIl2tIMVRkqDpFDJMhpJoIzAp99xYHM1m6BONy4nl7gqM3hBpdN3BGIMYgUqbydUmXu8lWOv3DsCMMorczNGLkbavd9IxzX/4QR646aUIvMXuxqNUSntivmQL0Nbd0Et7gdkCPF9gFpZPMWS3OQ2R4Ecb5Fw8NU3jd@a@@X1tHgquFNjpzv@W3fjqXoKSG1kNKuA5/e@n@O/@djl@Aw "Perl 6 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes
```
³i
ḲṪ$ḊṖV;1ịeØDƲ×Çṭ1Ɗ;Œlḷ/$;L;ÇN$µÞ
```
[Try it online!](https://tio.run/##y0rNyan8///Q5kyuhzs2Pdy5SuXhjq6HO6eFWRs@3N2deniGy7FNh6cfbn@4c63hsS7ro5NyHu7Yrq9i7WN9uN1P5dDWw/P@H26P/P8/Wj0kI1UhJL88T0HDyMDQQFNdRwEsFFCUWlySmZ4KEjYwgwu7pBYkFpWkpsCEYwE "Jelly – Try It Online")
-4 bytes thanks to Mr. Xcoder
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~28 26 25~~ 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to Erik the Outgolfer (use a zip to replace pair then transpose)
```
µḲṚż>”<aŒlƲḢO;L;⁹iNƊȧ\ðÞ
```
A monadic link taking and returning lists of lists of characters.
**[Try it online!](https://tio.run/##y0rNyan8///Q1oc7Nj3cOevoHrtHDXNtEo9Oyjm26eGORf7WPtaPGndm@h3rOrE85vCGw/P@H27X1n/UtObopIc7Z/z/H60ekpGqEJJfnqegYWRgaKCprqMAFgooSi0uyUxPBQkbmMGFXVILEotKUlOQhD2ATsgH8w3BfENThdzMvNKS1GIkQSNTBV8kQSOwYHBBanJmYo6Cc2Ixsj1AAzQMLc0MYBpTEiuLkUQQ9pmA@V5ZWVlIXKdUheTEotS00hywjyzAgok5OQrp@XmpMKFYAA "Jelly – Try It Online")** - footer reformats the result like the input (which is interpreted as a list of lists of characters)
...or see a [test-suite](https://tio.run/##y0rNyan8///Q1oc7Nj3cOevoHrtHDXNtEo9Oyjm26eGORf7WPtaPGndm@h3rOrE85vCGw/P@H91zuP1R0xptfSBxdNLDnTNUgAwgigTirEeN@w5tO7Tt///oaPWQjFSFkPzyPAUNIwNDA011HQWwUEBRanFJZnoqSNjADC7sklqQWFSSmgITjlXQUYhW9wA6Lx8sZAhWaWiqkJuZV1qSWowkaGSq4IskaATUDNILVKthaGlmAFOTklhZDBMBK/DKysoC6zABK0HYZQJVkJiTo5Cenwd2qqEFWJFTqkJyYlFqWmkOTBCsElMYqBZde2wsAA "Jelly – Try It Online")
### How?
```
µḲṚż>”<aŒlƲḢO;L;⁹iNƊȧ\ðÞ - Link: list of lists of characters, X
e.g. ["RV (2006)", "iChannel (2006)", "300 (2006)"]
ðÞ - sort by the following ðyadic key function (right is now X)
µ - ...start a monadic chain (left is now an item in X):
Ḳ - split at spaces ["RV","(2006)"] / ["iChannel","(2006)"] / ["300","(2006)"]
Ṛ - reverse ["(2006)","RV"] / ["(2006)","iChannel"] / ["(2006)","300"]
Ʋ - last four links as a monad:
”< - literal '<' character (resides between digits* and alphas ...* also the spaces and parentheses)
> - greater than? (vectorises) [1,1,0,0,0,0,0,0,0] / [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0] / [0,0,0,0,0,0,0,0,0,0]
Œl - lower-case ["rv (2006)"] / ["ichannel (2006)"] / ["300 (2006)"]
a - AND (vectorises) ['r','v',0,0,0,0,0,0,0] / ['i','c','h','a','n','n','e','l',0,0,0,0,0,0,0] / [0,0,0,0,0,0,0,0,0,0]
ż - zip together [["(2006)",'r'],["RV",'v'],[0],[0],[0],[0],[0],[0],[0]] / [["(2006)",'i'],["iChannel",'c'],['h'],['a'],['n'],['n'],['e'],['l'],[0],[0],[0],[0],[0],[0],[0]] / [["(2006)",0],["300",0],[0],[0],[0],[0],[0],[0],[0],[0]]
Ḣ - head ["(2006)",'r'] / ["(2006)",'i'] / ["(2006)",0]
O - cast to ordinal (vectorises) [[40,50,48,48,54,41],114] / [[40,50,48,48,54,41],105] / [[40,50,48,48,54,41],0]
- (Jelly cannot compare characters with integers)
L - length 9 / 15 / 10
; - concatenate [[40,50,48,48,54,41],114,9] / [[40,50,48,48,54,41],105,15] / [[40,50,48,48,54,41],0,10]
Ɗ - last three links as a monad:
i - 1st index of item in...
⁹ - chain's right argument, X 1 / 2 / 3
N - negated -1 / -2 / -3
; - concatenate [[40,50,48,48,54,41],114,9,-1] / [[40,50,48,48,54,41],105,15,-2] / [[40,50,48,48,54,41],0,10,-3]
\ - cumulative reduce with:
ȧ - AND (does not vectorise) [[40,50,48,48,54,41],114,9,-1] / [[40,50,48,48,54,41],105,15,-2] / [[40,50,48,48,54,41],0,0,0]
- i.e. max / middle / min
- so the sort, Þ, reverses this input:
- ["300 (2006)", "iChannel (2006)", "RV (2006)"]
```
] |
[Question]
[
For cops' post, [Cheapo Enigma machine (Cops)](https://codegolf.stackexchange.com/questions/117318/cheapo-enigma-machine-cops)
A robber's submission consists of a program/function that accepts the output of a cop's code and returns the input for all the outputs provided by that cop's code. (In other words, you must write the inverse function)
You cannot use built-ins that have the sole purpose of hashing or encryption.
# Input/Output format
8 bits (0 or 1), or a base-10 integer in range 1-256, 0-255 or -128 to 127. Can use standard I/O or file I/O. Function can also return a value as output. Input and output must belong to the same range (as in, binary, 1-256, 0-255 or -128 to 127), which must also be the same range as that used by the cop.
# Scoring
Ratio of the cop's byte count to your byte count. Highest score wins.
You can submit a robber attempt against your own cop code for reference. (Of course this code isn't eligible for winning)
# Notification
Please edit the corresponding cop's answer to include your new byte count and the corresponding ratio.
[Answer]
## [JavaScript by Christoph](https://codegolf.stackexchange.com/a/117414/58563), 8/25
```
f=(y,x=0)=>y?f(y/2,x^y):x
```
(range 0-255)
Sadly, `f=(y,x)=>y?f(y/2,x^y):x` works for all values except `0`.
### Technical note
We use `y/2` rather than `y>>1` to save a byte. This is abusing the fact that any value of `y` will eventually be rounded to `0` because of [arithmetic underflow](https://en.wikipedia.org/wiki/Arithmetic_underflow).
[Answer]
## [JavaScript by fəˈnɛtɪk](https://codegolf.stackexchange.com/a/117364/58563), 13/19
```
x=>((514>>x%2)-x)/2
```
(range 1-256)
[Answer]
# [C, by Dave](https://codegolf.stackexchange.com/a/117487/41127), 64/~~95~~ ~~92~~ 85
```
b,i,e,t[256];r(x){for(;!b;++i,b=e==x)for(srand(i&&e);t[e=rand()%256]++;);return i-1;}
```
[Try it here](https://tio.run/nexus/c-gcc#jVBBboMwEDyHV2yQguziKCRVe9n6F9xoD6AskiVwKmMq1Ii307Uhx0iVjFcznpkdsTTKKFK@ury9f6ETk7y3Nydw32CeG9Vo0nqSgRpcba/CZBlJ9BXpCOUh@PIcJTryo7Ngjmecl3LNa0PeapyyjNHxLCXGBWU1PYuYcE4SYz30tbFCwj3ZBUtgrC7QwgewBSHPbXzcRS1oaIWVuOGRsRM940C0grGGTb87nb4di1qR/tSducKheL2CCLdkW5ifNlVgFfQKxpjJHnA0kAfuApYmD54GH1566pkXXkGhQrOXwfzSrQ2F5erdFOVzRcN7CwSzDoqD@Zk/6gZaaz9KGxtr7//Ve/up5y2OzyOm7jpYg9Ig3YS8d17@AA)!
# C, shorter version, 64/~~89~~ 71
```
i,e,t[256];r(x){for(srand(1);t[e=rand()%256]++||++i,e!=x;);return i-1;}
```
This one is more implementation specific, but works on TIO.
Same length as the PHP solution, I wasn't able to get it any shorter than this.
[Try it here](https://tio.run/nexus/c-gcc#jZBRa4MwFIWf66@4FVqSJaW6sb3c@S98c3sQjBDQdMQ4wlp/u7uJKWMPg4GanJtzvhxctVTSNY/PL@9omefX/mLZZFvTsZKja1QV9/wQHELcbkJQYl955GiVm60BfSpxWeuN0QfGlvfHI6lTyTkGKNaN/w37QXhcskwbB2OrDeNwzXYhEiamKtDAK1AEQQgTD3fRCxX0zHBMeiZt2Ug6DHpGuoLk353PH5ZMPcs/20F3cCieOmDhyykW1jeTSzASRglzZFIGrJqUA@oCRnkHTk0unIxqpDlzEgoZmj1M@ktd@lCYb9nkqP92aLq3QFBxocFCrxomtfW9t9Um9t3/q3D6m2XC0XPHtMMAGygP1mSke5f1Gw)!
[Answer]
# [JavaScript by fəˈnɛtɪk, 13 / 12](https://codegolf.stackexchange.com/a/117364/58563)
```
x=>x*128%257
```
Another multiplicative inverse.
[Answer]
# [JavaScript](https://codegolf.stackexchange.com/a/117581/64505), 11/13
```
x=>a.sort().indexOf(x)
for(a=[],i=0;i<256;)a[i]=i++;
```
[Try it online!](https://tio.run/nexus/javascript-node#XZCxbsMgEIbn81NETBAiK7g1TeUSqU3btUPUyfFgERxhpQZhD5aaPLsLtiulHZA4fcd3/1GJoRfbMm6N6zCJdXNU/UeFexJVxuFS5MVKi3Wmn5KUZ6TMdSE0pdkQqPxH5S@NpJDxV2lxRSJpmtacVXw2J4wOB1gDgwTu4B5S4PAAG3iEZ3iBHbzCG7yjafBkZTzzOvIdLRZW6CXj48XGndl3TjcnzDjxxae1yu3KVmFCESDfFBS1V9RBUc8K/5YKmTO@1LQu5s6rP7cRLYmuY/zpQ27CJGk6p9EVHlf1Mk1ZcbmEaus5@bOscs44tArQS4cf "JavaScript (Node.js) – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), [22/3](https://codegolf.stackexchange.com/a/117581/53748) = 7 1/3
```
⁹ḶDÞḊi
```
**[Try it online!](https://tio.run/nexus/jelly#XZQ9bhNBGIZ7TrF0KVZo3/kf6nAKRGFFC0QKicjafRIhRYIrACegBSWCCp/EexHzPV86pHjknTwzO@/P@LjePh4efp3uvx8ePp8fn57@/tzfr3c/nu3vD4@f1ts/h99f1puvrz7uNhfLsH0/D5vrd7sP8@V2HJbd2dm8LM/t/6dX8zJcXm2HGfA/7u3m/GJ3Pb8YXp6sN9@Ox9fTOMj@FGyo3YZuM2GyucBcCNGGmGxI2QYDmLDnaI@pjEOu41DaOLCYtZp8P6MEJjgBClKgqsxV5ipzlbnG2sbaxlsaGzQ2aMANuAE3h/2kwB24A3fgDtyBO3AH7h1FLgtFEwImFE0omgpDZWgMwAKWewAsYAELWMACFnAADsDBDQMOwAE4AAfgAByBI3AEju4ucASOwBE4AifgBJyAkzvvUQAn4AScgDNwBs7AGTgDZ9veHuyrfbGFtswWYSCO4yEWYh7eeSg4jHH4gUxOz6HYzT68nZfzbmPQhCQUIYi2IAc1iEELUlCCEHQgg0IhAg1IQAECOD/H5/QcPtMyY7IxxZhiTDGmGFOMKegyptBEY6ox1ZhqTDWmGkPjKBx9o260jbLRNapG0ygaPaNmtIyS0TEqRsMoGP2iXrSLcnX30WuPi3RLdEt0S3RLdEt0S3RLT677HYFz0911t919x3jhvILHw87BLxQw9gv/RQAiARGByEDRryhw9NsHTBAiCRGFyEKEoeTJA5OHkl9VYCIRmYhQRCoiFpGLspcFOPu9BiYckY6IR@QjAhIJqXi1gIv/CAATk8hJ1X98gGt68w8)**
The [cop submission by fəˈnɛtɪk](https://codegolf.stackexchange.com/a/117581/53748) was to return the **nth** (**0**-indexed) lexicographically sorted decimal number using the domain **[0,255]**.
I first literally reversed the operation described, `⁹ḶDÞi⁸‘` - takes the lowered range of **256**, `⁹Ḷ`, and `Þ` instructs to sort it by a key function of conversion to a decimal list, `D`; then finds the index of, `i`, the input, `⁸`, and subtracts **1**, `‘` (Jelly lists are **1**-indexed).
Then I golfed it by dequeuing the sorted list with `Ḋ`. When an item is not found `i` returns **0** as required for the removed first element (**0**), while everything else is found one index earlier, allowing the removal of the decrement, `‘`, which in turn gives `i` implicit input on its right from the left (only) input to the monadic link.
[Answer]
# [Javascript by Magenta, 32 / 23](https://codegolf.stackexchange.com/a/117676/29637)
```
x=>x%16*16+(x/16+13)%16
```
Code basically switches the lower and the upper 4 bits and does a modulo addition on one part.
[Answer]
# [Javascript by histocrat, 27 / 29](https://codegolf.stackexchange.com/a/117498/29637)
```
x=>x-65?x-126?x*127%258:131:6
```
Sadly two hard codings are needed in order to break it. Note that the orginal function doesn't map any value to *130* but maps a value to *256*.
[Answer]
# [PHP, Score 64/71](https://codegolf.stackexchange.com/a/117487/29637)
```
for(srand(0);$a<256;)$b[$c=rand()%256]++||$d[$c]=$a++;echo$d[$argn]|0;
```
Luckily PHP's `rand` just forwards to the **stdlib** like C. So this works as long as we're using the same stdlib. This means it works on *TIO* but not on e.g. *sandbox.onlinephpfunctions.com*. The current version of Dave's code just iterates over a pseudorandom sequence and returns the *nth unique value* so I guess there might be much shorter answers if a golfing languages also uses the stdlib.
[Here's an implementation](https://wandbox.org/permlink/1Q1oYICTBM4zBz04) of Dave's code that does not dependent on the stdlib. That might also help.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), [16/18](https://codegolf.stackexchange.com/a/117417/24877)
```
@(x)mod(x*171,256)
```
[Try it online!](https://tio.run/nexus/octave#S7N10KjQzM1P0ajQMtYxMjXT/I8QMDQ3hAgl5hVrpGkYWBmZmmpq2tqCGf8B "Octave – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), [8/5](https://codegolf.stackexchange.com/a/117414/12012)
```
^H$7¡
```
[Try it online](https://tio.run/nexus/jelly#ARoA5f//XkgkN8Kh/@KBueG4tsK1XkjCtcW8w4dH/w "Jelly – TIO Nexus") to see the whole table.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), [16/6](https://codegolf.stackexchange.com/a/117417/12012)
```
×171%⁹
```
[Try it online](https://tio.run/nexus/jelly#@394uqG5oeqjxp3/jUzNHu7Ydmjr4enGqkD2oa1H9xxud/8PAA "Jelly – TIO Nexus") to see the whole table.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), [11/8](https://codegolf.stackexchange.com/a/117490/12012)
```
*205%257
```
[Try it online](https://tio.run/nexus/jelly#@69lZGCqamRq/t/I1Czo0FYtMOfQ1qN7Dre7/wcA "Jelly – TIO Nexus") to see the whole table.
In case robber submissions in a different languages are disallowed in the future, I call dibs on the following solution.
```
g=(x,y=0)=>x-++y**5%257?g(x,y):y
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), [35/7](https://codegolf.stackexchange.com/a/117745/12012)
```
⁹Ṗ+\%⁹i
```
[Try it online](https://tio.run/nexus/jelly#@/@ocefDndO0Y1SBjMz/BkVGpqaHth6erq1qamhkZXRo69E9h9sfNa1x/w8A "Jelly – TIO Nexus") to see the whole table.
[Answer]
# [C (gcc) by Bijan, 32 / 30](https://codegolf.stackexchange.com/a/117789/29637)
```
g(x){x=x?g(--x)*205+51&255:0;}
```
Had a fun time golfing it, thanks ! `x=` allows to skip return with gcc and tcc (you might want to change your answer to include it). `g(--x)*205+51&255` is the inverse.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), [37/11](https://codegolf.stackexchange.com/a/117812/12012)
```
O_77×191%⁹Ọ
```
Uses the same I/O format as the cop. Not sure if that is required.
[Try it online](https://tio.run/nexus/jelly#@@8fb25@eLqhpaHqo8adD3f3/P//3wcA "Jelly – TIO Nexus") to see the whole table.
### How it works
For input **n**, the cop answer computes **f(n) := ((((n + 5) % 256 × 2) % 256 + 2) % 256 × 9) % 256**. Since `%` is a linear operator, this is equivalent to **f(n) = (((n + 5) × 7 + 2) × 9) % 256**. Expanding the right term, we get **f(n) = (63n + 333) % 256 = (63n + 77) % 256**.
Reversing this is rather straightforward. To undo the addition, we simply have to subtract **77**. Also, since **191 × 63 % 256 = 12033 % 256 = 1**, it follows that **191** is **63**'s inverse modulo **256**, so multiplying by **191** undoes multiplying by **63**. This way, **g(n) = (n - 77) × 191 % 256** defines the inverse of **f**.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), [2/5](https://codegolf.stackexchange.com/a/117485/12012)
```
^H$7¡
```
[Try it online](https://tio.run/nexus/jelly#ARoA5f//XkgkN8Kh/@KBueG4tsK1XkjCtcW8w4dH/w "Jelly – TIO Nexus") to see the whole table.
] |
[Question]
[
**The Challenge**
>
> Given two strings containing only lowercase letters and no spaces, the result should be the shorter string, followed by an underscore, followed by the longer string with the first instance of a character removed for each character it contains that is in the shorter string.
>
>
> You can assume the strings will always be different lengths.
>
>
>
**Test Cases:**
```
sale
salinewater
Result: sale_inwater (only the first 'a' in salinewater is removed)
jostling
juggle
Result: juggle_ostin (juggle is the shorter string)
juggle
juggler
Result: juggle_r (a 'g' is removed for every 'g' in the shorter string)
```
**Rules**
>
> This is code-golf, so shortest answer in bytes wins!
>
>
>
[Answer]
# Pyth, 13 bytes
```
++hAlDQ\_.-HG
```
[Try it online.](http://pyth.herokuapp.com/?code=%2B%2BhAlDQ%5C_.-HG&input=%22jostling%22%2C+%22juggle%22&debug=0)
[Answer]
## JavaScript (ES6), ~~78~~ ~~75~~ 69 Bytes
```
const
g=(x,y)=>x[y.length]?g(y,x):[...x].map(c=>y=y.replace(c,''))&&x+'_'+y
;
console.log(g.toString().length + 2); // 69
console.log(g('sale', 'salinewater')) // sale_inwater
console.log(g('juggle', 'juggler')) // juggle_r
console.log(g('jostling','juggle')) // juggle_ostin
```
### Breakdown
```
x[y.length]?g(y,x): \\ Make sure that x is the shorter string
[...x] \\ Spread string in array of characters
.map(c=>y=y.replace(c,'')) \\ For each character remove its first occurence in y
&&x+'_'+y \\ Concat x and changed y
```
[Answer]
# Haskell, ~~56~~ 55 bytes
```
import Data.List
x%y|(0<$y)<(0<$x)=y%x|z<-y\\x=x++'_':z
```
*-1 byte thanks to @xnor*
[Answer]
# Java 7, 262 bytes
```
import java.util.*;String c(String z,String y){int i=0,l=y.length();if(z.length()>l)return c(y,z);List x=new ArrayList();for(;i<l;x.add(y.toCharArray()[i++]));for(Object q:z.toCharArray())x.remove(q);String r="";for(i=0;i<x.size();r+=x.get(i++));return z+"_"+r;}
```
Can probably be golfed some more by just using arrays without the lists..
**Ungolfed & test cases:**
[Try it here.](https://ideone.com/bB5brb)
```
import java.util.*;
class M{
static String c(String z, String y){
int i = 0,
l = y.length();
if(z.length() > l){
return c(y, z);
}
List x = new ArrayList();
for(; i < l; x.add(y.toCharArray()[i++]));
for(Object q : z.toCharArray()){
x.remove(q);
}
String r = "";
for(i = 0; i < (x.size()); r += x.get(i++));
return z+"_"+r;
}
public static void main(String[] a){
System.out.println(c("sale", "salinewater"));
System.out.println(c("jostling", "juggle"));
System.out.println(c("juggle", "juggler"));
}
}
```
**Output:**
```
sale_inwater
juggle_ostin
juggle_r
```
[Answer]
# Java 8, 156 Bytes
```
String a(String x,String y){int l=x.length(),m=y.length();String b=l>m?x:y,s=m<l?y:x;for(char c:s.toCharArray()){b=b.replaceFirst(""+c,"");}return s+"_"+b;}
```
This can probably be golfed some more.
**Ungolfed & test cases**
```
interface A {
static String a(String x,String y){
int l=x.length(),m=y.length();
String b=l>m?x:y,s=m<l?y:x;
for(char c:s.toCharArray()){
b=b.replaceFirst(""+c,"");
}
return s+"_"+b;
}
static void main(String[]a) {
System.out.println(a("sale","salinewater"));
System.out.println(a("jostling","juggle"));
System.out.println(a("juggle","juggler"));
}
}
```
[Answer]
## Ruby, 65 bytes
```
->a,b{a,b=b,a if a.size>b.size;a.chars.map{|e|b.sub!e,""};a+?_+b}
```
### ungolfed
```
->a, b{
a, b = b, a if a.size > b.size
a.chars.map { |e|
b.sub! e, ""
}
a + ?_ + b
}
```
### 61 bytes(in case the argument is an array of strings)
```
->a{a.sort_by!(&:size);a[0].chars.map{|c|a[1].sub!c,""};a*?_}
```
Thank you, [m-chrzan](https://codegolf.stackexchange.com/users/58569/m-chrzan)!
[Answer]
# PHP, 154 Bytes
```
list($f,$s)=strlen($b=$argv[2])<strlen($a=$argv[1])?[$b,$a]:[$a,$b];foreach(str_split($f)as$x)$s=preg_replace("#(.*?)".$x."(.*)#","$1$2",$s);echo$f."_$s";
```
Instead of `$s=preg_replace("#(.*?)".$x."(.*)#","$1$2",$s);` you can also use `if($z=strstr($s,$x))$s=strstr($s,$x,1).substr($z,1);`
[Answer]
## R, 161 bytes
This turned out to be much longer than I expected, albeit, string manipulation is usually tedious in R. I feel that this should easily be golfable by just using another approach.
```
function(x,y){s=strsplit;if(nchar(x)>nchar(y)){v=y;w=x}else{v=x;w=y};v=s(v,"")[[1]];w=s(w,"")[[1]];j=0;for(i in v){j=j+1;if(i==w[j])w[j]=""};cat(v,"_",w,sep="")}
```
### Ungofled
```
function(x,y){
s=strsplit # alias for stringsplit
if(nchar(x)>nchar(y)){v=y;w=x} # assign v/w for the short/long strings
else{v=x;w=y}
v=s(v,"")[[1]] # split short string into vector
w=s(w,"")[[1]] # split long string into vector
j=0
for(i in v){ # for each char in short string, check
j=j+1 # if is equal to corresponding char in
if(i==w[j])w[j]="" # long, replace long with "" if true
}
cat(v,"_",w,sep="") # insert _ and print
}
```
[Answer]
# Python 2, ~~81~~ 72 bytes
```
a,b=sorted(input(),key=len)
for c in a:b=b.replace(c,"",1)
print a+"_"+b
```
[**Try it online**](https://repl.it/Dfgs/1)
[Answer]
# Scala, 78 bytes
```
def f(a:String,b:String):String={if(a.size>b.size)f(b,a)else
a+"_"+(b diff a)}
```
Explanation:
```
def f(a:String,b:String):String={ //define a method f which has two String parameters and returns a String
//(because it's recursive, scala can't figure out the return type)
if (a.size > b.size) //make sure that a is the shorter string
f(b, a)
else
a+"_"+(b diff a) //`b diff a` removes all elements/chars of a from b
}
```
] |
[Question]
[
*Credit goes where [credit is due](http://chat.stackexchange.com/transcript/message/29818745#29818745)*
---
Given two digits, x, and y, calculate the shortest number of horizontal or vertical jumps to get from x to y on a standard numpad, e.g.
```
789
456
123
00
```
You can safely assume that all inputs will be 0-9, and you do not have to handle invalid inputs. The input *may* be the same number twice, which has a distance of 0.
IO can be in [any reasonable format](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), and standard loopholes are forbidden. Shortest answer in bytes wins!
# Sample IO:
```
1, 4: 1
1, 8: 3
3, 7: 4
8, 2: 2
6, 1: 3
0, 9: 4
4, 4: 0
0, 4: 2
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
o-1.’d3ạ/ḞS
```
[Try it online!](http://jelly.tryitonline.net/#code=by0xLuKAmWQz4bqhL-G4nlM&input=&args=WzEsIDRd) or [verify all test cases](http://jelly.tryitonline.net/#code=by0xLuKAmWQz4bqhL-G4nlMKOyLDh-KCrEc&input=&args=WzEsIDRdLCBbMSwgOF0sIFszLCA3XSwgWzgsIDJdLCBbNiwgMV0sIFswLCA5XSwgWzQsIDRdLCBbMCwgNF0).
### How it works
```
o-1.’d3ạ/ḞS Main link. Argument: [a, b] (list of integers)
-1. Yield -1.5.
o Take the logical OR of a and b with -1.5.
This maps 0 to -1.5, and all other integers to themselves.
’ Decrement the results.
d3 Divmod; compute quotient and remainder of each result divided by 3.
ạ/ Reduce by absolute difference across columns.
Ḟ Floor; round all differences down to the nearest integer.
S Sum; add the rounded absolute differences.
```
[Answer]
# Python, 140 114 bytes
I am a first timer, so please help. Here's my code.
```
def f(x,y):x,y,k=x-1,y-1,abs;return x!=-1 and y!=-1 and k(y//3-x//3)+k(y%3-x%3) or k(y//3-x//3)+int(max(x,y)%3==2)
```
[Answer]
# Jelly, 13 bytes
```
+2$.¹?€d3ạ/SḞ
```
[Try it online!](http://jelly.tryitonline.net/#code=KzIkLsK5P-KCrGQz4bqhL1PhuJ4&input=&args=WzAsM10)
Port of [my Pyth answer](https://codegolf.stackexchange.com/a/80359/48934).
[Test suite.](http://jelly.tryitonline.net/#code=KzIkLsK5P-KCrGQz4bqhL1PhuJ4Kw4figqw&input=&args=W1sxLCA0XSwgWzEsIDhdLCBbMywgN10sIFs4LCAyXSwgWzYsIDFdLCBbMCwgOV0sIFs0LCA0XSwgWzAsIDRdXQ)
[Answer]
# JavaScript (ES6), 59
Unfortunately, no `divmod` in javascript. In fact, no integer `div`, and no `mod` either: the `%` is not exactly `mod`. But for once, the weird behaviour of `%` with negative numbers is useful.
```
(a,b,A=Math.abs)=>A(~(--a/3)-~(--b/3))+A(a%3-b%3)-(a*b%3<0)
```
**Test**
```
f=(a,b,A=Math.abs)=>A(~(--a/3)-~(--b/3))+A(a%3-b%3)-(a*b%3<0)
for(i=0;i<10;console.log(r),i++)
for(r='',j=0;j<10;j++)
r+=[i,j,f(i,j)]+' '
```
[Answer]
# Pyth, ~~22~~ ~~21~~ 19 bytes
FGITW.
```
L.D?b+2b.5 3ssaMCyM
```
[Test suite.](http://pyth.herokuapp.com/?code=L.D%3Fb%2B2b.5+3ssaMCyM&test_suite=1&test_suite_input=%5B1%2C+4%5D%0A%5B1%2C+8%5D%0A%5B3%2C+7%5D%0A%5B8%2C+2%5D%0A%5B6%2C+1%5D%0A%5B0%2C+9%5D%0A%5B4%2C+4%5D%0A%5B0%2C+4%5D&debug=0)
Conversion table:
```
0: [0.0, 0.5]
1: [1, 0]
2: [1, 1]
3: [1, 2]
4: [2, 0]
5: [2, 1]
6: [2, 2]
7: [3, 0]
8: [3, 1]
9: [3, 2]
```
[Answer]
# Julia, 56 bytes
```
x->sum(abs(-([[divrem(t>0?t+2:.5,3)...]for t=x]...)))÷1
```
[Try it online!](http://julia.tryitonline.net/#code=ZiA9IHgtPnN1bShhYnMoLShbW2RpdnJlbSh0PjA_dCsyOi41LDMpLi4uXWZvciB0PXhdLi4uKSkpw7cxCgpmb3IgKHgsIHkpIGluICgoMSwgNCksICgxLCA4KSwgKDMsIDcpLCAoOCwgMiksICg2LCAxKSwgKDAsIDkpLCAoNCwgNCksICgwLCA0KSkKICAgIEBwcmludGYoIiVkLCAlZDogJWRcbiIsIHgsIHksIGYoKHgsIHkpKSkKZW5k&input=)
[Answer]
# Python 2, 61 bytes
```
lambda x,y:abs(x/-3-y/-3)+abs((x or 1.5)%-3-(y or 1.5)%-3)//1
```
Test it on [Ideone](http://ideone.com/C7nrCE).
### How it works
* **Vertical distance**
Integer division always round *down* to the nearest integer in Python, yielding the following results for the 10 possible dividends divided by **-3**.
```
0 1 2 3 4 5 6 7 8 9
0 -1 -1 -1 -2 -2 -2 -3 -3 -3
```
Thus, we can compute the vertical distance between **x** and **y** as `abs(x/-3-y/-3)`.
* **Horizontal distance**
For columns, we can avoid treating **0** as a special case by replacing it with **1.5**, thus placing it "between" the first and second column.
Modulus (`%`) always has the sign of the divisor in Python, yielding the following results for the 10 possible dividend modulo **-3**.
```
0 1 2 3 4 5 6 7 8 9
-1.5 -2 -1 0 -2 -1 0 -2 -1 0
```
Thus, by rounding down (`//1`) the result of `abs((x or 1.5)%-3-(y or 1.5)%-3)`, we can compute the horizontal difference between **x** and **y**.
[Answer]
## Java ~~149~~ 160 chars
The obligatory: Because... you know... Java!
Having fun with Java in under ~~150~~ 161 chars:
```
int d(int f,int t){if(f==t)return 0;if(Math.min(f,t)==0){int m=Math.max(f,t);return Math.min(d(1,m),d(2,m))+1;}return Math.abs(--t%3- --f%3)+Math.abs(t/3-f/3);}
```
Ungolfed into a class:
```
public class Q80357 {
static int distance(int from, int to) {
if (from == to)
return 0;
if (Math.min(from, to) == 0) {
int max = Math.max(from, to);
return Math.min(distance(1, max), distance(2, max)) + 1;
}
return Math.abs(--to % 3 - --from % 3) + Math.abs(to / 3 - from / 3);
}
}
```
### How it works
First it catches the standard case where we don't have to move anywhere.
Now we can assume that both integers differ, thus only the smaller one can be 0. If this is the case we calculate the distance from key 1 and 2 to the other key. We will use the one with the shorter distance and add one step to get from 1 or 2 to 0.
If we don't want to go to/from zero we only have to move in the 3x3 grid. We can determine the column and row of the key by using mod or div respectively. Then we calculate the column and row distance and add them. This is the distance we need to get from one key to another.
I hope the explanation could be understood, feel free to golf :)
### Updates
Had to change it into an actual function as it uses recursion which isn't possible with lambdas :,(
] |
[Question]
[
What tricks do you know to make CoffeeScript code shorter?
CoffeeScript is language that compiles into JavaScript ("transpiles" into ES3, to be exact). The golden rule is "It's just JavaScript", meaning there's no runtime overhead. Most of JavaScript Tips & Tricks apply as well.
As a side-effect that also means: developers coming from JavaScript (including myself) tend to use JavaScript constructs instead of shorter CoffeeScript alternatives.
**This thread focuses on tips specific to CoffeeScript.**
Links to related topics:
[Tips for golfing in JavaScript](https://codegolf.stackexchange.com/q/2682/42702)
[Tips for Golfing in ECMAScript 6 and above](https://codegolf.stackexchange.com/q/37624/42702)
[Answer]
# Use destructuring assignments, if structure elements are used often
Eg. get elements of first argument array
```
func = ([x,y,z])->
[i,j] = doSomething x, y, x+y
doSomethingElse i, j
# instead of
func = (a)->
b = doSomething a[0], a[1], a[0]+a[1]
doSomethingElse b[0], b[1]
```
This can be combined with splats
```
[first, rest..., last] = doSmth()
```
[Answer]
## Short-circuit evaluation in place of ternary operator
CoffeeScript does not have JavaScript's [ternary operator](https://msdn.microsoft.com/en-us/library/be21c7hw(v=vs.94).aspx) `?`, however the functionality of [short-circuit evaluation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators) can sometimes be used instead:
```
foo = a && b || c
# Long form:
foo = if a then b else c
```
Is somewhat equivalent to in JavaScript:
```
foo = a ? b : c
```
It will **not** work if b is (or can evaluate to) a falsy value such as `0`.
[Answer]
## Integer division operator `//`
Saves up to 10 bytes by avoiding the need to floor numbers when dividing.
Using the `//` operator:
```
foo = 61/3 # foo = 20.333333333333332
foo = Math.floor 61/3 # foo = 20 (15 bytes)
foo = 61/3|0 # foo = 20 (6 bytes)
foo = 61//3 # foo = 20 (5 bytes)
```
Compared to JavaScript:
```
foo = 61/3 // foo = 20.333333333333332
foo = Math.floor(61/3) // foo = 20 (16 bytes)
foo = 61/3|0 // foo = 20 (6 bytes)
```
[Answer]
# Space is fun. Space is significant for calling functions
```
a=b[i] # get i-th element of array b
a=b [i] # a = b( [i] ) # pass [i] to function b
m=n+k # simple math
m=n +k # m = n( +k ) # convert k to number and pass to function n
m=n -k # m = n( -k ) # pass -k to function n
m=n + k # simple math again
a(b c)+d # a( b( c ) ) + d
a (b c)+d # a( b( c ) + d )
a (b c) +d # a( b( c )( +d ) )
```
[Answer]
# Omit parentheses when possible
```
func1 func2 func3(a),func3 b
#instead of
func1(func2(func3(a),func3(b))
```
[Answer]
## Not `null` but possibly falsy (`0`, `NaN`, `""`, `false`, etc.)
If you need to check if a variable is defined and not `null`, use the trailing question mark:
```
alert 'Hello world!'if foo?
```
Compiles to:
```
if (typeof foo !== 'undefined' && foo !== null) {
alert('Hello world!')
}
```
This probably won't apply to many code golf entries but might be useful if you need to distinguish from a zero, false, empty string, or other falsy value.
[Answer]
## Exponentiation operator `**`
Saves 9 bytes:
```
foo = 2**6
# foo = 64
```
Compared to JavaScript:
```
foo = Math.pow(2,6)
// foo = 64
```
[Answer]
## Searching arrays
Save approximately 8 bytes if you just want to check if an element is in an array, you can use the `in` operator.
```
y = x in['foo', 'bar', 'baz']
```
Compared to alternatives in JavaScript:
```
y = ~['foo', 'bar', 'baz'].indexOf(x) // ES5, returns Number
y = ['foo', 'bar', 'baz'].includes(x) // ES7, returns boolean
y = ~$.inArray(x,['foo', 'bar', 'baz']) // jQuery, returns Number
```
However in the rare case that you need the index of the element then this trick won't work for you.
[Answer]
# Use splats
```
obj.method a, params...
# instead of
obj.method.apply obj, [a].concat params
# especially useful with new objects
obj = new Obj a, params...
# alternative is complicated, unreadable and not shown here.
```
[Answer]
# Safe accessors: `?.` and `func? args...`
Existential operator `?` has many forms and uses. Apart from just checking if variable is set, you can access object methods and properties without prior checking if object is null:
```
obj.property?.method? args...
```
will execute `obj.property.method args...` only if `obj.property` and `obj.property.method` are defined and not null.
Useful if you iterate over several sparse arrays at the same time:
```
arr1[i]?.prop = arr2[i]?.method? args... for i in[0..99]
```
] |
[Question]
[

Draw a series of connected polygons like the one shown above.
However, what the above picture does not show is the spiral formed by consecutive vertexes:

The limitation of these is that there is only 1 spiral marked. You should mark all the spirals. This can be done by rotating each spiral shown above so that there is a spiral starting at each vertex of the largest polygon.
The spirals should all be one color, while the rest of the picture another.
The innermost polygon should be entirely the color of the spiral.
## Rules
* You will receive the arguments { n, s, p, a } in a function or program
* n = iterations inward (number of polygons)
* s = sides of the (regular) polygon (you may assume n>=3)
* p = (the linear distance from a vertex of polygon A to its corresponding counter-clockwise "inner" vertex) / (the total length of A's side). So for the diagram, p would be about 1/3 because each inner polygon meets the larger polygon's side at about 1/3 of the way through that side.
* a = the radius (circumscribing) of the exterior polygon
The limit of any of the values of n,s,p or a are based on what can be perceived as this kind of drawing by a human. (e.g. no shaded circles) as well as common sense (s>=3,n>=1)
Happy golfing! Shortest program wins.
[Answer]
## Mathematica, ~~218~~ 206 bytes
```
{n,s,p,a}=Input[];t=0;Graphics[(c=Array[a{Cos[u=t+2Pi#/s],Sin@u}&,s+1];m=(f=p#2+(1-p)#&)@@c;a=Norm@m;t=ArcTan@@m;k=#;{Line@{#,x=f@##},If[k<n,Red],Line@{x,#2}}&@@@Thread@{c,RotateLeft@c})&~Array~n,Axes->1>0]
```
Expects the input as an array as defined in the question, e.g. `{20, 7, 0.5, 100}`:

or `{20, 5, 0.333, 100}`

These images still use red and grey from an earlier version, but the new version uses black for the counter-clockwise spirals and red for the rest.
I've included an axis, because otherwise the `a` parameter is meaningless with a vector graphic. I've also interpreted `p` as a linear interpolation in position, not in angle.
Ungolfed:
```
{n, s, p, a} = Input[];
t = 0;
Graphics[
(
c = Array[a {Cos[u = t + 2 Pi #/s], Sin@u} &, s + 1];
m = (f = p #2 + (1 - p) # &) @@ c;
a = Norm@m;
t = ArcTan @@ m;
k = #;
{Line@{#, x = f@##}, If[k < n, Red], Line@{x, #2}} & @@@
Thread@{c, RotateLeft@c}
) &~Array~n
,
Axes -> 1 > 0]
```
] |
[Question]
[
Your task is to find the total destination of objects that are falling to a planet, you will get inputs like this:
```
7
...#...
.......
#..O..#
.......
...#...
.......
.......
```
where O is the planet and # are the objects, note that the planet will attract objects from the for basic directions(NEWS). You should output:
```
#
#O#
#
```
i.e the objects after reaching their destination.
The first number given as an input is the length of the grid(nxn), in the above example it is 7.
The object should always move in the shortest direction(note that the allowed directions are only horizontal and vertical; the object can't move diagonally)
If an object is equidistant from two directions it should go in a clock wise direction:
```
..#
...
O..
```
Will reach this side:
```
...
...
O#.
```
If an object collides with the planet, it will stop. If it collides with another object they become one object,
```
4
.#..
#...
....
.O..
```
would become:
```
....
....
.#..
.O..
```
One final example:
```
6
..#...
.#....
......
.#O...
....#.
......
```
Output:
```
......
......
..#...
.#O#..
......
......
```
**Note:** You should output the final shape, so all outputs are accepted as long as they show the final shape of the planet.
for example for this input:
```
...#
....
.O..
....
```
Should output:
```
O#
```
or
```
....
....
.O#.
....
```
Both of these are accepted.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer will win
**Note 2:**
As you may have noticed a `.` represents vaccum so the shortest path is the shortest number of dots.
For example:
```
.#.
...
.O.
```
Is not accepted to be
```
O#
```
since the shortest path is vertical.
**Note3:**
The object should always move to be in the same line with the planet in one of the four directions(choosing the shortest)
```
|<#
|
|
-----O------
|
```
Restrictions:
2<=n<=100
[Answer]
## Mathematica, 206 bytes
```
f=(m=Characters@StringSplit@#;o=#-Join@@m~(p=Position)~"O"&/@m~p~"#";h=If[MemberQ[#3/@o,{m_,n_}/;m#<0&&m#<=n#2<-m#],"#",e]&;{e=".",h[1,1,#&],e,n="\n",h[1,-1,r=Reverse],"O",h[-1,1,r],n,e,h[-1,-1,#&],e}<>"")&
```
Somewhat more readable:
```
f[input_] := (
map = Characters @ StringSplit @ input;
planet = Flatten[Position[map, "O"]];
objects = Map[# - planet &, Position[map, "#"]];
helper[pattern_] := If[
Length[Position[objects, pattern]] > 0,
"#",
"."
];
StringJoin[{
".", h[{m_, n_} /; m < 0 && m <= n < -m], ".", "\n",
h[{m_, n_} /; n < 0 && n < m <= -n], "O", h[{m_, n_} /; n > 0 && -n <= m < n], "\n",
".", h[{m_, n_} /; m > 0 && -m < n <= m], "."
}]
);
```
As you can see, I only take a single input which is the string containing the input map. This is because I wouldn't use the size integer anyway. If you insist on the input format, I can change the input string to the second argument for one more character.
As for the algorithm, I'm just collecting all the `{Δx, Δy}` pairs of the objects and look for one pair in each quadrant with the conditions passed to `h`. I suspect this is also the part that could be golfed down further.
[Answer]
# perl, 270 chars
3 steps: 1) find the planet and satellites in the input, 2) determine quadrant for each satellite, 3) output
```
sub _{"#"}$D=<>;$\=$/;for$L(1..$D){for$M(1..$D){$/=\1;$_=<>;$p=$M,$q=$L if/O/;push@s,[$M,$L] if/#/}$/=$\;<>}for(@s){$x=$_->[0]-$p,$y=$_->[1]-$q;($x<0&&$x<$y&&$y<=-$x?$l:$x>0&&-$x<=$y&&$y<$x?$r:$y<0&&$y<=$x&&$x<-$y?$u:$d)=_}$_=$l?" #":_;$u&&print;print $l."O$r";$d&&print
```
Less golfed:
```
sub _{"#"}
$D=<>;
$\=$/;
for$L(1..$D){
$/=\1;
for$M(1..$D){
$_=<>;
$p=$M,$q=$L if/O/;
push@s,[$M,$L] if/#/;
}
$/=$\;
<>
}
for(@s){
$x=$_->[0]-$p,$y=$_->[1]-$q;
($x<0&&$x<$y&&$y<=-$x ? $l :
$x>0&&-$x<=$y&&$y<$x ? $r :
$y<0&&$y<=$x&&$x<-$y ? $u : $d)=_;
}
$_=$l?" #":_;
$u && print;
print$l."O$r";
$d && print;
```
[Answer]
## Perl, ~~156 153~~ 148
```
$n=$_+1;
s/.+\n//;
$o=index$_,O;
$x=$o%$n-$-[0]%$n,
pos=$o+(($==($o-$-[0])/$n)&&$x/$=>-1&&$x/$=<=1?$=>0?-$n:$n:0<=>$x),
s/\G./x/ while s/#/./;
y/x/#/
```
Newlines for readability. Run with `-0777p` (5 added to count), input through STDIN.
More readable:
```
$n=$_+1;
s/.+\n//;
$o=index$_,O;
while(s/#/./){
$x=$o%$n-$-[0]%$n;
$==($o-$-[0])/$n;
pos=$o+(
$=
&&$x/$=>-1
&&$x/$=<=1
?$=>0
?-$n
:$n
:0<=>$x
);
s/\G./x/
}
y/x/#/
```
] |
[Question]
[
The problem is defined as follows:
Create a function that takes an integer and returns a list of integers, with the following properties:
* Given a positive integer input, *n*, it produces a list containing *n* **integers ≥ 1.**
* Any *sublist* of the output must contain at least one unique element, which is different from all other elements from the same sublist. *Sublist* refers to a *contiguous* section of the original list; for example, `[1,2,3]` has sublists `[1]`, `[2]`, `[3]`, `[1,2]`, `[2,3]`, and `[1,2,3]`.
* The list returned must be the lexicographically smallest list possible.
There is only one valid such list for every input. The first few are:
```
f(2) = [1,2] 2 numbers used
f(3) = [1,2,1] 2 numbers used
f(4) = [1,2,1,3] 3 numbers used
```
[Answer]
# APL, 18
```
{+⌿~∨⍀⊖(⍵/2)⊤2×⍳⍵}
```
1 + number of trailing zeros in base 2 of each natural from 1 to N.
**Example**
```
{+⌿~∨⍀⊖(⍵/2)⊤2×⍳⍵} 32
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 6
```
[Answer]
## GolfScript (20 18 chars)
```
{,{.)^2base,}%}:f;
```
This is a simple binary ruler function, [A001511](http://oeis.org/A001511).
Equivalently
```
{,{).~)&2base,}%}:f;
{,{~.~)&2base,}%}:f;
{,{).(~&2base,}%}:f;
{,{{1&}{2/}/,)}%}:f;
```
Thanks for [primo](https://codegolf.stackexchange.com/users/4098/primo) for saving 2 chars.
[Answer]
# [Sclipting](http://esolangs.wiki/Sclipting), ~~26~~ 23 characters
```
감⓶上가增❷要❶감雙是가不감右⓶增⓶終終丟丟⓶丟終并
```
This piece of code generates a list of integers. However, if run as a program it will concatenate all the numbers together. As a stand-alone program, the following 25-character program outputs the numbers separated by commas:
```
감⓶上가增❷要감嚙是가不⓶增⓶終終丟丟⓶丟껀終合鎵
```
## Example output:
Input: `4`
Output: `1,2,1,3`
Input: `10`
Output: `1,2,1,3,1,2,1,4,1,2`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
ọ€2‘
```
[Try it online!](https://tio.run/##y0rNyan8///h7t5HTWuMHjXM@P//v6EBAA "Jelly – Try It Online")
## Explanation
```
ọ€2‘
€ For each integer from 1 to {the command-line argument}
ọ calculate the number of trailing zeroes in base
2 2
‘ and increment {each resulting integer} {and output them}
```
[Answer]
## Python 2.7, 65 characters
```
print([len(bin(2*k).split('1')[-1]) for k in range(1,input()+1)])
```
The number of trailing zeros in 2, 4, 6, ..., 2n.
[Answer]
## Haskell, 40 characters
```
n&p=n:p++(n+1)&(p++n:p)
f n=take n$1&[]
```
Example runs:
```
λ: f 2
[1,2]
λ: f 3
[1,2,1]
λ: f 4
[1,2,1,3]
λ: f 10
[1,2,1,3,1,2,1,4,1,2]
λ: f 38
[1,2,1,3,1,2,1,4,1,2,1,3,1,2,1,5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1,6,1,2,1,3,1,2]
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
õȤq1 ÌÊÄ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9cikcTEgzMrE&input=NA)
[Answer]
# [Haskell](https://www.haskell.org/), 29 bytes
```
(`take`t)
t=1:do x<-t;[x+1,1]
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzXyOhJDE7NaFEk6vE1tAqJV@hwka3xDq6QttQxzD2f25iZp6CrUJBUWZeiYKKQpqCodn/f8lpOYnpxf91kwsKAA "Haskell – Try It Online")
] |
[Question]
[
I have been participating in a number of PHP code golf challenges recently and some of the techniques that are used to read data from a file such as `fopen()` and `fread()` or `file_get_contents()` really give my code a beating on the char count. Especially the methods provided for reading in command line input.
My question is, what is the fastest way (least keystrokes) to read and write to the contents of a file, and what is the fastest way (least keystrokes) to read a line from the prompt?
*(Note: As this is code golf, I can't use any external libraries.)*
[Answer]
You can read a line from `STDIN` in 13 characters:
```
fgets(STDIN);
```
as seen [here](http://php.net/manual/en/features.commandline.io-streams.php).
Reading from a file:
```
file('filename')
```
returns [an array of lines of the file](https://www.php.net/manual/en/function.file.php).
Using `fputs` instead of `fwrite` will save a character on writing, but I can't think of a shorter way than:
```
fputs(fopen('filename','w')); //use 'a' if you're appending to a file instead of overwriting
```
which is marginally shorter than:
```
file_put_contents('filename');
```
[Answer]
Depending on the input format, [fgetcsv](http://www.php.net/manual/en/function.fgetcsv.php) and [fscanf](http://www.php.net/manual/en/function.fscanf.php) can often be byte savers as well.
For example, assume each line of your input consists of two space separated integers. To read these values into an array, you could use one of:
```
$x=split(' ',fgets(STDIN)); // 27 bytes
$x=fgetcsv(STDIN,0,' '); // 24 bytes
$x=fscanf(STDIN,'%d%d'); // 24 bytes
```
Or if you wanted to read each of them into a different variable:
```
list($a,$b)=split(' ',fgets(STDIN)); // 36 bytes
list($a,$b)=fgetcsv(STDIN,0,' '); // 33 bytes
fscanf(STDIN,'%d%d',$a,$b); // 27 bytes
```
[Answer]
### To read non-physical files (read input)
If you have a single line input, use `-F` and `$argn` to read from STDIN. This is only 5 bytes and a lot shorter than other methods.
Example: [Try it online!](https://tio.run/##K8go@P/fxt5WJbEoPc/6/39PhcRchUSF4sy89JxUhZzMvFSFzLyC0pJ/@QUlmfl5xf913QA "PHP – Try It Online")
Basically `-F` runs your code once for every single line of the input and fills `$argn` with string of that input line. More information: <https://www.php.net/manual/en/features.commandline.options.php>
---
If you have a multi line input, use `$argv`. `$argv` is an array which starting from index `1` contains all arguments you pass to your code. So you can use `$argv[1]` and so on, which is only 8 bytes. You can pass multiple arguments too and loop on them with `for(;$a=$argv[++$i];)` which usually is shorter than other methods.
Example 1: [Try it online!](https://tio.run/##K8go@P/fxt5WJbEovSzaMNb6////ngqJuQqJCrmlOSWZCjmZeakKmXkFpSVcPiCmEYQyBgA "PHP – Try It Online")
Example 2: [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVEm1VEovSy6K1tVUyY601U5Mz8pVUEhWUrP///2/43@i/MQA "PHP – Try It Online")
More information: <https://www.php.net/manual/en/reserved.variables.argv.php>
] |
[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 1 year ago.
[Improve this question](/posts/1546/edit)
In 1939 Juzuk described a way to generate the fourth powers of natural numbers.
Group the natural numbers like this:
```
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ...
```
Scratch each second group:
```
1 4 5 6 11 12 13 14 15 ...
```
The sum of the *n* remaining groups is *n*\*\*4.
* **Input**: none
* **Task**: print the fourth powers upto 100\*\*4, using Juzuk's method.
* **Output**:
0 (optional)
1
16
81
...
100000000
[Answer]
## J, 33
```
~.+/\(#~i.200)(+/*2|#)/.1+i.2!200
```
[Answer]
## J, ~~40~~ 38 (*not* summing unneeded)
```
+/\+/"1(+:i.100){(#~i.201)[/.>:i.20100
```
## J, 30 (summing unneeded)
```
+/\_2{.\(#~i.201)+//.>:i.20100
```
[Answer]
**Haskell, 78**
```
print[sum$concat$take x[take x$drop(sum[1..x-1])[1..]|x<-[1,3..]]|x<-[0..100]]
[0,1,16,81,256,625,1296,2401,4096,6561,10000,14641,20736,28561,38416,50625,65536,...
```
Hope the slightly different output formatting is ok. There's probably a much better way to write this in Haskell, but I felt like solving this in a language I don't often use.
[Answer]
## Python 2, 68
Quick and dirty Python solution:
```
s=0
for n in range(100):s+=sum(range(2*n*n+n+1,2*n*n+3*n+2));print s
```
] |
[Question]
[
Write the shortest program that will attempt to connect to open ports on a remote computer and check if they are open. (It's called a [Port Scanner](http://en.wikipedia.org/wiki/Port_scanner))
Take input from command line arguments.
```
your-port-scanner host_ip startPort endPort
```
Assume, startPort < endPort (and `endPort - startPort < 1000`)
**Output:** All the open ports between that range should space or comma seperated.
[Answer]
## sh/netcat, 39
```
nc -vz $1 $2-$3 2>&1|cut -f3 -d\ |xargs
```
Netcat does the scanning and returns results in this form on standard error:
```
localhost [127.0.0.1] 22 (ssh) open
localhost [127.0.0.1] 25 (smtp) open
```
`cut` and `xargs` extract the port number and make a single line out of it.
Remind me to shut SMTP down on that node.
[Answer]
## Perl, 92
```
$_='use I;$h=shift;grep I->new("$h:$_"),shift..shift';
s/I/IO::Socket::INET/g;@_=eval;say"@_"
```
Perl 5.10 or later, run with `perl -E 'code here'`.
Uses regexes to compress that long `IO::Socket::INET`, then `eval`; final formatting done with array interpolation.
By request, a more detailed explanation. To ungolf, let's first respace:
```
$_ = << 'EOC';
use I;
$h = shift;
grep I->new("$h:$_"), shift..shift;
EOC
s/I/IO::Socket::INET/g;
@_ = eval;
say "@_";
```
The line before the `eval` replaces all (two) occurences of 'I' with 'IO::Socket::INET', that's a standard Perl golfing trick to reduce the impact of unavoidable long identifiers. Naming a few of the temporaries, the code is then equivalent to this:
```
use IO::Socket::INET;
$h = shift;
$p1 = shift;
$p2 = shift;
@_ = grep IO::Socket::INET->new("$h:$_"), ($p1 .. $p2);
say "@_";
```
In a nutshell: read host and port range arguments from the command line; attempt a connection to all of them in sequence (`IO::Socket::INET->new()`); keep a list of those who succeeded (`grep`); display the result nicely (`say`).
[Answer]
# Ruby - 85
```
require"socket"
h,p,e=$*
p.upto(e){|p|begin
TCPSocket.new h,p
$><<"#{p} "
rescue
end}
```
[Answer]
# sh/nmap/GNU grep/xargs - 36
```
nmap -p$2-$3 $1|grep -Po '^\d+'|xargs
```
Follows input and output specs:
```
$ sh 1109.sh 127.0.0.1 1 80
22 25 80
```
[Answer]
## Perl, 178
I'm new to Perl, any advice on shortening is appreciated!
```
use IO::Socket::INET;for($x=$ARGV[1];$x<$ARGV[2]+1;$x++){if(fork()){if($sock=new IO::Socket::INET(PeerAddr=>$ARGV[0],PeerPort=>$x,Proto=>'tcp')){print"$x ";}close($sock);exit;}}
```
[Answer]
# BASH - 105
In pure BASH (i.e no nmap or netcat).
```
exec 2>&- && exec 2<> /dev/null
for p in $(seq $2 $3); do
> /dev/tcp/$1/$p &&
echo -n "$p "
done
```
When using with an address other than localhost the timeout is quite long (in the order of minutes) when encountering a closed port so some sort of timeout/alarm function would be required in all likelihood.
[Answer]
# PHP - 70
```
<?for(list(,$h,$p,$e)=$argv;$p<=$e;++$p)@fsockopen($h,$p)&&print"$p ";
```
] |
[Question]
[
Implement the [binary search algorithm](http://en.wikipedia.org/wiki/Binary_search_algorithm) as used to identify the source code revision that breaks a computer software program. Your tool should take two arguments specifying the earliest and latest numbered revision to search (both positive integers), and you have two options for making comparisons:
1. Execute the shell command `./test N`, where *N* is the revision number. If the test passes (*i.e.* the revision is good), it will return exit code 0.
2. Call the function `test(N)`, which will return `true` if the test passes, `false` otherwise.
Standard output must be the number of the first bad revision, and try to make your tool's source code as short as possible. Enjoy!
[Answer]
# Python, 64 chars
This one is recursive, so will overflow the stack for really large input
```
01234567890123456789012345678901234567890123456789012345678901234567890
| | | | | | | |
B=lambda L,H:H>L+1 and B(*[L,L/2+H/2,H][test(L/2+H/2):][:2])or H
```
test run
```
def test(n):
print "testing ", n
return n<66
L,H=10,1000
B=lambda L,H:H>L+1 and B(*[L,L/2+H/2,H][test(L/2+H/2):][:2])or H
print B(L,H)
```
outputs
```
testing 505
testing 257
testing 133
testing 71
testing 40
testing 55
testing 62
testing 66
testing 64
testing 65
66
```
[Answer]
## Ruby - 92 82 62 60 characters
Iterative is way shorter, but nowhere near as cool as tail recursive.
```
l,h=$*.map &:to_i
test(m=(l+h)/2)?l=m+1:h=m-1 while l<=h
p l
```
The old tail recursive method for reference
```
b=proc{|l,h|h<l ?l:(m=(l+h)/2;test(m)?l=m+1:h=m-1;redo)}
puts b[*$*.map(&:to_i)]
```
### Testing script
Uses a little magic to inject the `test` function and runs a file consisting of purely the above code.
```
low = Random.rand(100)
mid = low + Random.rand(1e25)
high = mid + Random.rand(1e50)
File.open('./bisect-test-method.rb','w') do |file|
file << "def test(value)
value < #{mid}
end
"
end
puts "Using input:"
puts " low=#{low}"
puts " high=#{high}"
puts " first_bad=#{mid}"
puts "Output: #{`ruby -r ./bisect-test-method golf-bisect.rb #{low} #{high}`}"
```
Output:
```
Using input:
low=4
high=75343785543465286986587973836706907796015092187720
first_bad=5013102893257647460384884
Output: 5013102893257647460384884
```
[Answer]
## Python - 77 chars
Abusing the python bisect module. L is the low value, H is the high value
```
class B:__getitem__=lambda s,n:test(n)
import bisect as b
b.bisect(B(),0,L,H)
```
here is a test run
```
def test(n):
print "testing ", n
return n>66
L,H=10,1000
class B:__getitem__=lambda s,n:test(n)
import bisect as b
b.bisect(B(),0,L,H)
```
outputs
```
testing 505
testing 257
testing 133
testing 71
testing 40
testing 56
testing 64
testing 68
testing 66
testing 67
```
Explanation:
Here is how bisect is defined. Basically it expects a list and decides whether to bisect up or down based on the value it finds by looking at `a[mid]`. This calls `__getitem__` on `a`, which instead of being a list, is a class that I have defined myself.
```
def bisect_right(a, x, lo=0, hi=None):
"""Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e <= x, and all e in
a[i:] have e > x. So if x already appears in the list, a.insert(x) will
insert just after the rightmost x already there.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
"""
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if x < a[mid]: hi = mid
else: lo = mid+1
return lo
bisect=bisect_right
```
[Answer]
## Python - 70 chars
```
def B(L,H):
while L+1<H:M=L+H;L,H=[L,M/2,H][test(M/2):][:2]
return L
```
test run
```
def test(n):
print "testing ", n
return n<66
L,H=10,1000
def B(L,H):
while L+1<H:M=L+H;L,H=[L,M/2,H][test(M/2):][:2]
return L
print B(L,H)
```
outputs
```
testing 505
testing 257
testing 133
testing 71
testing 40
testing 55
testing 63
testing 67
testing 65
testing 66
65
```
] |
[Question]
[
# Introduction
In the binary representation of a \$k-\$bit \$(k>1)\$ square number \$n^2, \$ not all bits can be \$1\$. The maximum number of \$1\$-bits (Hamming weight, \$B\$ for short) is given in [A357658](https://oeis.org/A357658), but only up to \$k=95\$ bits.
An example of a \$99\$-bit square is \$B(796095014224053^2)=87\$. The records in [A357304](https://oeis.org/A357304) show that \$B(m^2)<88\$ for a \$100\$-bit square \$m^2\$, and that the computation is feasible.
# Challenge
Your task is to write a **fastest-code** program which determines
* \$B\_{max}(n^2)\$
* \$n\_{min}\$
* \$n\_{max}\$
in the range of \$100\$-bit squares \$n^2\$ with \$796131459065722\le n\le 1125899906842623\$
with the smallest number \$n\_{min}\$ and the largest number \$n\_{max}\$
such that \$B(n\_{min}^2)=B(n\_{max}^2)=B\_{max}\$.
A brute force calculation visiting all squares \$n^2\$ in the given range is possible, but takes a very long time, even if the multiplication is implemented efficiently with the instruction set for the available hardware. See this [question on Stack Overflow](https://stackoverflow.com/questions/25095741/how-can-i-multiply-64-bit-operands-and-get-128-bit-result-portably).
Is it possible to avoid actually performing all the multiplications? The program that determines the 3 numbers \$B\_{max}, n\_{min}, n\_{max}\$ in the shortest run time wins.
# Test
To test the order of magnitude of a program's speed, it can be applied to the interval \$1085300000000000\le n \le 1085312000000000\$. The interval contains \$2\$ numbers with \$82\$ \$1\$-bits. The length of this interval is approximately \$1/27500\$ of the total range to be searched. You can then decide if you want to try the full range.
The results will be used in a planned extension of the OEIS sequences [A357658](https://oeis.org/A357658), [A357659](https://oeis.org/A357659), and [A357660](https://oeis.org/A357660), giving credit to the authors of the fastest programs.
[Answer]
# [Rust](https://www.rust-lang.org/) w/ Rayon -- 0.9s runtime, 6.7s cputime for whole range
```
(1/99) a=0 1 (best: 0)
(2/49) b=2 4 (best: 50)
(3/27) a=1 49 (best: 72)
(4/23) b=3 188 (best: 76)
(5/21) a=2 1176 (best: 78)
(6/17) b=4 4332 (best: 82)
(7/15) a=3 18424 (best: 84)
(8/15) b=5 65220 (best: 84)
(9/15) a=4 211876 (best: 84)
(10/15) b=6 721396 (best: 84)
(11/15) a=5 1906884 (best: 84)
(12/15) b=7 6249964 (best: 84)
(13/14) a=6 13983816 (best: 85)
(14/14) b=8 44156732 (best: 85)
B_max: 85
n_min: 933544295655093
n_max: 1125891114428899
Found values: 1121216655081291 1043134657624555 1120665056942829 1116514939453621 933544295655093 1125074802425067 1124798782678823 1125891114428899 1090147221387163
100 85 933544295655093 1125891114428899
________________________________________________________
Executed in 909.41 millis fish external
usr time 6.70 secs 0.00 micros 6.70 secs
sys time 0.02 secs 516.00 micros 0.02 secs
```
Output of `time max_square 100`
Tested on my laptop with 4 cores (8 virtual) @ ~4.5 GHz
```
use std::{str::FromStr, collections::HashSet};
use rayon::prelude::*;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicU32, Ordering};
use rayon::iter;
fn solve(n: u32, verbose: bool) {
if n < 6 {
match n {
1 => {println!("1 1 1 1")},
2 => {println!("None")},
3 => {println!("3 1 2 2")},
4 => {println!("4 2 3 3")},
5 => {println!("5 3 5 5")},
_ => {println!("Error");}
}
return;
}
let mut best = Solution::new(n);
let mut a = 0;
let mut b = 2;
while best.get_best() + a + b <= n {
let cost_a = calculate_cost_a(n, a);
let cost_b = calculate_cost_b(n, b);
if cost_a < cost_b {
if verbose {eprintln!("({}/{}) a={} {} (best: {})", a+b-1, n - best.get_best() - 1, a, cost_a, best.get_best());}
step_a(n, a, &mut best);
a += 1;
} else {
if verbose {eprintln!("({}/{}) b={} {} (best: {})", a+b-1, n - best.get_best() - 1, b, cost_b, best.get_best());}
step_b(n, b, &mut best);
b += 1;
}
}
let solutions = best.solutions.lock().unwrap();
if verbose {
eprintln!("");
eprintln!("B_max: {}", best.get_best());
eprintln!("n_min: {}", solutions.iter().min().expect("No solutions"));
eprintln!("n_max: {}", solutions.iter().max().expect("No solutions"));
eprintln!("");
eprint!("Found values: ");
for z in solutions.iter() {
eprint!("{} ", z);
}
eprintln!("");
eprintln!("");
}
println!("{} {} {} {}", n, best.get_best(), solutions.iter().min().expect("No solutions"), solutions.iter().max().expect("No solutions"));
}
fn calculate_cost_a(n: u32, a: u32) -> i64 {
let a = a as i64;
let n = n as i64;
binomial((n-1)/2, a)
}
fn step_a(n: u32, a: u32, best: &Solution) {
let h = n / 2;
iter::split(
Combinator::with_prefix_postfix(n, a, 1, 1, (1 << h) - 1, h),
split_combinator).flatten_iter()
.for_each(|z|{
best.update(isqrt(z));
}
);
}
fn calculate_cost_b(n: u32, b: u32) -> i64 {
let b = b as i64;
let n = n as i64;
(1..b/2 + 1).map(|i| (1<<i) * binomial(n/2 - 1 - 2*i, b - 2*i)).sum::<i64>() * 2
}
fn step_b(n: u32, b: u32, best: &Solution) {
let m = (1 << ((n + 1) / 2)) - 1;
for k in 0..b/2 {
let w = ((n + 1) / 2) - 3 - 2*k;
iter::split(Combinator::new(w, b - 2 - 2*k, 1, 3), split_combinator).flatten_iter()
.for_each(|a| {
let x = modsqrt(w + 3, a) << k;
let mut z = 1 << ((n + 1) / 2);
let step_size = 1 << (((n + 1) / 2) - 1 - k);
while z > 0 {
z -= step_size;
best.update((z + x)&m);
best.update((z - x)&m);
}
}
);
}
}
fn modsqrt(n: u32, a: i128) -> i128 {
let mut x = 1;
let m = (1<<n) - 1;
for _ in 3..n {
x = (((x*x - a) >> 1) + x) & m;
}
x
}
fn isqrt(n: i128) -> i128 {
let mut x = (n as f64).sqrt() as i128;
if x*x <= n {
x += 1;
while x*x <= n {
x += 1;
}
x-1
} else {
x -= 1;
while x*x > n {
x -= 1;
}
x
}
}
fn binomial(n: i64, k: i64) -> i64 {
let k = std::cmp::min(k, n-k);
if k < 0 {return 0;}
if k == 0 {return 1;}
let mut c: i64 = 1;
for i in 0..(k as i64) {
c = (c * (n-i)) / (i + 1);
}
c
}
struct Combinator {
curr: i128,
mask: i128,
offset: u32,
min: i128,
max: i128,
k: u32,
}
impl Combinator {
fn new(width: u32, num_zeros: u32, mask: i128, offset: u32) -> Combinator {
Combinator { curr: (1 << width) - (1 << num_zeros), mask: mask, offset: offset, min: 0, max: binomial(width as i64, num_zeros as i64) as i128, k: width - num_zeros }
}
fn with_prefix_postfix(full_width: u32, num_zeros: u32, prefix: i128, prefix_width: u32, postfix: i128, postfix_width: u32) -> Combinator {
let width = full_width - prefix_width - postfix_width;
Combinator::new(width, num_zeros, (prefix << (width + postfix_width)) + postfix, postfix_width)
}
}
// calculates the next combination, in reverse lexicographic order
fn next_combination(n: i128) -> i128 {
if n&1 == 0 {return n - (((n^(n-1))+1)>>2);}
let a = (n^(n+1))>>1;
let na = n-a;
if na == 0 {return na;}
let b = ((na ^ (na-1))>>2) - a;
if b == 0 {return na - 1;}
let b = b >> b.trailing_zeros();
na - 1 - b
}
impl Iterator for Combinator {
type Item = i128;
fn next(&mut self) -> Option<Self::Item> {
if self.min == self.max {return None;}
let curr = self.curr;
self.max -= 1;
self.curr = next_combination(curr);
Some(self.mask | (curr << self.offset))
}
}
// combinatorial number system
fn ntoc(n: i128, k: i128) -> i128 {
if k == 0 {return 0;}
if n == 0 {return (1<<k) - 1;}
let mut x = k;
let mut xck = 1; // x choose k
let mut x1ck = k+1; // x+1 choose k
while x1ck <= n {
xck = x1ck;
x += 1;
x1ck = (xck * (x + 1)) / (x + 1 - k);
}
ntoc(n - xck, k-1) + (1 << x)
}
fn split_combinator(c: Combinator) -> (Combinator, Option<Combinator>) {
if c.max - c.min <= 100000 {return (c, None);}
let midpoint = c.min + (c.max - c.min) / 2;
(Combinator {curr: ntoc(midpoint, c.k as i128), min: c.min, max: midpoint, mask: c.mask, offset: c.offset, k: c.k}, Some(Combinator {curr: c.curr, min: midpoint, max: c.max, mask: c.mask, offset: c.offset, k: c.k}))
}
struct Solution {
best: AtomicU32,
minz: i128,
maxz: i128,
solutions: Arc<Mutex<HashSet<i128>>>,
}
impl Solution {
fn update(&self, z: i128) {
if z < self.minz {return;}
if z > self.maxz {return;}
let z2 = z*z;
let z2c = z2.count_ones();
let prev = self.best.fetch_max(z2c, Ordering::Relaxed);
if z2c < prev {return;}
let mut solutions = self.solutions.lock().unwrap();
if z2c > prev {
solutions.clear();
}
solutions.insert(z);
}
fn new(width: u32) -> Solution {
Solution {best: AtomicU32::new(0), minz: isqrt((1 << (width - 1)) - 1) + 1, maxz: isqrt(1 << width), solutions: Arc::new(Mutex::new(HashSet::new()))}
}
fn get_best(&self) -> u32 {
self.best.load(Ordering::Relaxed)
}
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let i = match args.len() {
2 => (1, true),
3 => {
if args[1] == "-q" {
(2, false)
} else if args[2] == "-q" {
(1, false)
} else {
println!("Usage: max_square [-q] [number of bits]");
return;
}
},
_ => {
println!("Usage: max_square [-q] [number of bits]");
return;
},
};
if let Ok(n) = u32::from_str(&args[i.0]) {
solve(n, i.1);
} else {
println!("Error reading args");
}
}
```
## Explanation
We'll let \$n\$ be the number of bits (100) in the squares we're searching.
This algorithm has two types of steps that corresponding to fixing the most significant / least significant half of the square.
While there are possible solutions remaining, we chose between the two step types based on which would require fewer operations.
#### Step type \$a\$:
Range over all integers \$x\$ with \$\left\lceil\frac{n}{2}\right\rceil-1\$ bits of which \$a\$ are zero.
For each \$x\$ there is at most one natural number \$z\$ for which
$$
\underbrace{1x0\ldots0}\_{n\text{ bits}}
\le
z^2
\le
\underbrace{1x1\ldots1}\_{n\text{ bits}}
$$
After updating our solutions with those \$z^2\$, assuming we already checked the previous values of \$a\$, we now know that all unchecked squares have at least \$a+1\$ zeros in the first half.
#### Step type \$b\$:
Range over integers \$k\$ and \$x\$ where \$2+2k\le b\$ and \$x\$ has \$\left\lceil\frac{n}{2}\right\rceil-3-2k\$ bits of which \$b-2-2k\$ are zero.
For each \$x\$, \$k\$ there are \$4\cdot2^k\$ values of \$z\$ (mod \$2^{\left\lceil\frac{n}{2}\right\rceil}\$) satisfying
$$
z^2\equiv \underbrace{x001[00]\times k}\_{\left\lceil\frac{n}{2}\right\rceil\text{ bits}}\mod2^{\left\lceil\frac{n}{2}\right\rceil}
$$
After updating our solutions with those \$z^2\$, assuming we already checked the previous values of \$b\$, we now know that all unchecked squares have at least \$b+1\$ zeros in the first half.
## Output for n from 3 to 126
```
3 1 2 2
4 2 3 3
5 3 5 5
6 3 7 7
7 5 11 11
8 4 13 15
9 6 21 21
10 6 27 27
11 8 45 45
12 8 53 53
13 9 75 89
14 9 101 117
15 13 181 181
16 11 217 235
17 13 362 362
18 12 437 491
19 14 627 723
20 15 923 949
21 16 1241 1241
22 16 1619 1773
23 17 2505 2891
24 18 3915 3915
25 19 5221 5747
26 20 6475 7093
27 21 11309 11309
28 22 15595 16203
29 23 19637 19637
30 24 31595 31595
31 25 44491 44491
32 25 61029 64747
33 26 69451 86581
34 27 113447 113447
35 28 185269 185269
36 29 244661 244661
37 30 357081 357081
38 31 453677 453677
39 31 642119 738539
40 34 980853 980853
41 33 1380917 1481453
42 34 1961706 2079669
43 37 2965685 2965685
44 37 3923411 3923411
45 38 5931189 5931189
46 38 8096813 8222581
47 39 11862197 11862965
48 39 16244453 16244453
49 41 22193965 22193965
50 41 32988235 32988235
51 42 43586515 47450235
52 44 57804981 57804981
53 44 94905541 94905541
54 44 115609962 134053275
55 46 164382389 177549685
56 47 268123979 268123979
57 47 320528203 379526189
58 49 528407335 528407335
59 50 657506485 657506485
60 51 888717493 888717493
61 52 1510322221 1510322221
62 52 2100772683 2111529939
63 53 2630119323 2630119323
64 54 4227325771 4227325771
65 55 5853487285 5853487285
66 55 8580481947 8580481947
67 57 10520476455 10520476455
68 57 14878203147 17110519093
69 58 21040953067 24295633269
70 59 31469977781 31469977781
71 62 48589783221 48589783221
72 63 66537313397 66537313397
73 62 97179566261 97179566442
74 63 133074626794 133074626794
75 64 194366549037 194366549037
76 64 259365748555 274835944267
77 66 388730126517 388730126517
78 66 475016392885 540779528373
79 68 759031429451 759031429451
80 68 1064500084555 1081632748507
81 68 1503999171957 1554929409435
82 69 2055848542027 2197923974325
83 70 2576736968885 3109840793419
84 72 3646667521867 4362198168395
85 72 5384675514549 6216643955893
86 73 8445509046091 8791729601637
87 74 11620627528805 11937419436213
88 76 17435796250805 17435796250805
89 76 21537910687315 24879106612889
90 77 34895284158283 34895284158283
91 77 39275570260917 49752141391123
92 78 60940798018325 68134217006923
93 80 93089098383179 93089098383179
94 80 121861586862261 139768858984629
95 81 184920521899109 199030966469849
96 82 222524145495085 222524145495085
97 85 398064946368587 398064946368587
98 84 461438710099403 562672855105355
99 87 796095014224053 796095014224053
100 85 933544295655093 1125891114428899
101 88 1592054863872923 1592054863872923
102 88 2233021208375059 2233021208375059
103 89 3153273599102795 3153273599102795
104 90 4498915668727861 4498915668727861
105 92 6354993066190667 6354993066190667
106 91 7790298568288075 8721180941868443
107 92 12709986132381334 12711635715085643
108 93 18005548694652121 18005548694652121
109 94 25469208479569437 25469208479569437
110 94 30874441840049387 36004547995030069
111 95 47233732013276085 50801164553247509
112 96 66646890995961483 72057405025529767
113 99 101480601046523531 101480601046523531
114 98 143542302959229109 143542302959229109
115 99 202961202093047062 202961202093047062
116 101 269614819660724085 269614819660724085
117 101 403417952942237229 403417952942237229
118 101 529472308325235947 576458535517221045
119 103 808844333869390923 808844333869390923
120 103 970104967079909557 1143803445656875189
121 104 1578696363991412555 1630401033738048053
122 106 1996776422069106507 2156918025961517429
123 106 2688433943050910795 3260133329992761163
124 107 4575515161264941861 4605489388616186187
125 108 6518622390190614475 6518622390190614475
126 110 7977185712837244873 7977185712837244873
________________________________________________________
Executed in 498.22 secs fish external
usr time 65.63 mins 15.29 millis 65.63 mins
sys time 0.03 mins 19.41 millis 0.03 mins
```
[Answer]
# Going further
```
49 41 22193965 22193965
50 41 32988235 32988235
51 42 43586515 47450235
52 44 57804981 57804981
53 44 94905541 94905541
54 44 115609962 134053275
55 46 164382389 177549685
56 47 268123979 268123979
57 47 320528203 379526189
58 49 528407335 528407335
59 50 657506485 657506485
60 51 888717493 888717493
61 52 1510322221 1510322221
62 52 2100772683 2111529939
63 53 2630119323 2630119323
64 54 4227325771 4227325771
65 55 5853487285 5853487285
66 55 8580481947 8580481947
67 57 10520476455 10520476455
68 57 14878203147 17110519093
69 58 21040953067 24295633269
70 59 31469977781 31469977781
71 62 48589783221 48589783221
72 63 66537313397 66537313397
73 62 97179566261 97179566442
74 63 133074626794 133074626794
75 64 194366549037 194366549037
76 64 259365748555 274835944267
77 66 388730126517 388730126517
78 66 475016392885 540779528373
79 68 759031429451 759031429451
80 68 1064500084555 1081632748507
81 68 1503999171957 1554929409435
82 69 2055848542027 2197923974325
83 70 2576736968885 3109840793419
84 72 3646667521867 4362198168395
85 72 5384675514549 6216643955893
86 73 8445509046091 8791729601637
87 74 11620627528805 11937419436213
88 76 17435796250805 17435796250805
89 76 21537910687315 24879106612889
90 77 34895284158283 34895284158283
91 77 39275570260917 49752141391123
92 78 60940798018325 68134217006923
93 80 93089098383179 93089098383179
94 80 121861586862261 139768858984629
95 81 184920521899109 199030966469849
96 82 222524145495085 222524145495085
97 85 398064946368587 398064946368587
98 84 461438710099403 562672855105355
99 87 796095014224053 796095014224053
100 85 933544295655093 1125891114428899
101 88 1592054863872923 1592054863872923
102 88 2233021208375059 2233021208375059
103 89 3153273599102795 3153273599102795
104 90 4498915668727861 4498915668727861
105 92 6354993066190667 6354993066190667
106 91 7790298568288075 8721180941868443
107 92 12709986132381334 12711635715085643
108 93 18005548694652121 18005548694652121
109 94 25469208479569437 25469208479569437
110 94 30874441840049387 36004547995030069
111 95 47233732013276085 50801164553247509
112 96 66646890995961483 72057405025529767
113 99 101480601046523531 101480601046523531
114 98 143542302959229109 143542302959229109
115 99 202961202093047062 202961202093047062
116 101 269614819660724085 269614819660724085
117 101 403417952942237229 403417952942237229
118 101 529472308325235947 576458535517221045
119 103 808844333869390923 808844333869390923
120 103 970104967079909557 1143803445656875189
121 104 1578696363991412555 1630401033738048053
122 106 1996776422069106507 2156918025961517429
123 106 2688433943050910795 3260133329992761163
124 107 4575515161264941861 4605489388616186187
125 108 6518622390190614475 6518622390190614475
126 110 7977185712837244873 7977185712837244873
```
127 overflows basic type X( (maybe)
[Odd](https://tio.run/##jVVtr6pGEP7Or5h6ck4XlfKix3MsYHKS2yY3EfulTW3S1CgsuBYXCsu9eG/967WzwBF8aVKiq8w8Mzsvz876aapFvn86PTD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TRx6aNQ7_1YlRMG79Qoj5ftrrANlybRe17rwYeh4z4udPz-hBSa0WobYfrd0MXB5vZdbJrvduXUHV8bCxS5-2H-1ASLiyXfWXoh8AsVqM8P5gPE5higR53WgwQVpD7sI4t7WhnyJHqLfpJ9xetjIV-PVrrXqN7u2BMbFSn7OlkE3do4j7e49iSouCvxpZepRqx45coxUfF1TAjZpA6zbCwYDUHQ42_SQiHEsMiE1rALRcbRiI8FW4T-iwsmS-JcZxU4GsQWa9pSAmX7O6guFIl4-bF3PB1rgbtxTKHyUTGpsvt-8wU_zBx-K48UQCTPhtw2iBTt-9_u3cZE-LnMZF160cYe-9XVPyqJTVJM3nnuH2-9eSoww2FgPBINEXcT9RvuxPlBUFdNrbmkeOeDOssILFqypYZbeF28mnRYvQEE_NInz1Vr4KMpJg5Z7gD2KFtmP62xcTkfDbmQ7qL_lrbDk7s251ZlaLUJaPRzByrB4U1GEPfu1ww34fwDWFX_05sfi5-bD7_Aw)
This algorithm has two stages where the first stage checks some very unlikely possibilities for optimal squares. Then stage 2 checks the rest of the possibilities, and gains a massive performance boost from the knowledge of stage one.
More specifically we are interested in where the zeroes are in the square. In stage 1 we assume all but at most `max_upper_zeros` are located in the lower half (bottom 50 bits) of the square. We just brute force trough all possible upper halves of the square, check if they have a square root and if so, remember that value as a potential solution.
Now in stage 2 we enumerate all possibilities, except the ones checked in stage 1. Thus in stage 2 we can assume that the upper half contains at least `max_upper_zeros + 1` zeros.
This algorithm has "steps". In step `b` we enumerate all possible lower segments of `b` bits of the root. At step 50 we have enumerated all possible roots and can calculate how many ones the corresponding squares have.
As stated, this would not make the calculation any faster than brute force, however we can use the following trick: the `b` lowest bits of the root determine the `b` lowest bits of the square. Therefore we can get an upper bound to the number of ones in the square from the lowest `b` bits, which allows us to discard numbers at early steps of stage 2.
The stage 2 algorithm is run with a "target hamming weight" `tg`. This is the (minimum) number of ones that we want in the square. We start with `tg=100` and decrement until we find solutions.
The stage 2 algorithm in the following code is quite optimized since I invented it first. It has manual tail-call elimination and it only considers odd numbers (odd solutions can be trivially converted to even solutions). The variable p stores the number of bits in the initial segment with a bias given by `tg` and `max_upper_zeros`.
The code outputs some stats to stderr and writes the solution to stdout.
```
#include <vector>
#include <algorithm>
#include <iostream>
#include <bit>
#include <cmath>
const int LIM = 50;
const int TB = LIM*2;
const unsigned long long RANGE_START = 796131459065722;
const unsigned long long RANGE_END = 1125899906842623;
std::vector<unsigned long long> solutions = {};
// Stage 2
void count(int tg, int b, int p, unsigned long long v) {
unsigned __int128 mul = v * (unsigned __int128)v;
while (b < LIM) {
int bit = (mul >> b) & 1;
unsigned long long vp = v | (1ull << b);
p+= bit;
b+= 1;
// Here we discard solutions that don't have enough ones
// in the first b bits
if (p < b) {
return;
}
count(tg, b, p, vp);
}
if (__builtin_expect(std::__popcount(mul) >= tg, 0)) {
// Account for taking into account only odd numbers
while (RANGE_START > v) {
v<<= 1;
}
if (RANGE_START <= v && v <= RANGE_END) {
std::cerr << "Found solution " << v << std::endl;
solutions.push_back(v);
}
}
}
unsigned long long isqrt(unsigned __int128 x) {
unsigned long long apprx = (unsigned long long) sqrt((double)x);
while (apprx * (unsigned __int128) apprx > x) {
apprx-= 1;
}
return apprx;
}
int main() {
// First try to find solutions with at most max_upper_zeros zeros in the upper half
const int max_upper_zeros = 7;
std::vector<unsigned long long> initial_solutions = {};
int best_hamming_weight = 0;
unsigned long long upper_neg = 0;
while (upper_neg < (1ull << LIM)) {
unsigned long long upper = ((1ull << LIM)-1)^upper_neg;
unsigned __int128 m = ((unsigned __int128)upper << LIM);
unsigned long long v = isqrt(m);
do {
unsigned __int128 mul = v * (unsigned __int128)v;
unsigned long long upp = mul >> LIM;
if (upp > upper) {
break;
}
if (upp < upper) {
continue;
}
int ones = std::__popcount(mul);
if (ones >= best_hamming_weight && RANGE_START <= v && v <= RANGE_END) {
if (ones > best_hamming_weight) {
initial_solutions.clear();
best_hamming_weight = ones;
}
initial_solutions.push_back(v);
}
} while (v++);
if (std::__popcount(upper_neg) == max_upper_zeros) {
upper_neg = (upper_neg | (upper_neg - 1)) + 1;
} else {
upper_neg+= 1;
}
}
std::cerr
<< "First stage found the following solutions with hamming weight "
<< best_hamming_weight << ":" << std::endl;
for (auto &s: initial_solutions) {
std::cerr << s << std::endl;
}
// Then use this knowledge to calculate solutions more efficiently
int tg = TB;;
for (; tg >= best_hamming_weight; --tg) {
count(tg, 1, 1 + TB - tg - max_upper_zeros, 1);
std::cerr << "Calculated target " << tg << std::endl;
if (!solutions.empty()) {
break;
}
}
if (tg + 1 == best_hamming_weight) {
solutions.insert(solutions.end(),initial_solutions.begin(),initial_solutions.end());
}
unsigned long long min = *std::min_element(solutions.begin(), solutions.end());
unsigned long long max = *std::max_element(solutions.begin(), solutions.end());
int ones = std::__popcount(min * (unsigned __int128)min);
std::cout << ones << std::endl << min << std::endl << max << std::endl;
return 0;
}
```
] |
[Question]
[
You have to decompose a positive integer/fraction as a product of powers of factorials of prime numbers.
For example
>
> `22 = (11!)^1 × (7!)^(−1) × (5!)^(−1) × (3!)^(−1) × (2!)^1`
>
>
>
>
> `10/9 = (5!)^1 × (3!)^(−3) × (2!)^1`
>
>
>
Use this special notation: `prime number#power`
to denote each term, e.g. `(11!)^4` is denoted as `11#4`.
Output the non-zero terms only, with space separation.
The above examples hence become:
>
> `22 = 11#1 7#-1 5#-1 3#-1 2#1`
>
>
>
>
> `10/9 = 5#1 3#-3 2#1`
>
>
>
## Input & Output
* You are given a positive number `N`, that can be either an integer or a fraction of the form `numerator/denominator`
* The ordered list of the non-zero terms of the decomposition of `N`, denoted using the special notation
* You are allowed to output the terms as a list/array (containing strings with the special notation `#`)
* You are allowed to output the terms in any order
* Duplicate prime numbers are allowed
* You are not allowed to use terms that have to the power of `0`
## Test cases
```
6 -> 3#1
5040 -> 7#1
22 -> 11#1 7#-1 5#-1 3#-1 2#1
1/24 -> 3#-1 2#-2
720/121 -> 11#-2 7#2 5#3 3#3
```
This is code-golf, shortest code wins!
Credits to [this puzzle](https://www.codingame.com/ide/puzzle/factorials-of-primes-decomposition)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
þ>LD(«ZÅPâæ¦.Δε`!sm}PI.EQ}í'#ý
```
Outputs as a list of strings. Can output with duplicated prime numbers as allowed in the rules (e.g. `3/4` results in `["3#1","2#-1","2#-2"]` instead of `[3#1","2#-3"]`).
Brute-force approach, so very slow and times out for most test cases.
[Try it online](https://tio.run/##ATMAzP9vc2FiaWX//8O@PkxEKMKrWsOFUMOiw6bCpi7OlM61YCFzbX1QSS5FUX3DrScjw73//zM) or [verify some test cases using values below `3` by replacing the `þ>`](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf@NfVw0Dq2OOtwacHjR4WWHlumdm3Jua4JicW5twKF1eq6BtYfXqisf3vtf53@0oY6RjrGOiY6ZjoWOpY6Sob6REog0BpJGYNJQ3wRIGoNJQ30zMGkJJo1MlGIB).
**Explanation:**
```
þ # Keep the digits of the (implicit) input, potentially removing the "/"
# for fractions
> # Increase it by 1 (for edge case input=1 or 1/1)
LD(« # Convert it into a [value,-value]-ranged list without 0:
L # Pop the copy and push a list in the range [1,value]
D # Duplicate this list
( # Negate each value
« # Merge the two lists together
Z # Push the maximum (without popping), which is the value again
ÅP # Pop and push a list of primes <= this value
â # Cartesian power to create all possible pairs of the two lists
æ # Get the powerset of this list of pairs
¦ # Remove the leading empty list (for edge case input=1 or 1/1 again,
# because the product of an empty list is 1)
.Δ # Find the first result which is truthy for:
ε # Map the list of pairs to:
` # Pop and push the values in the pair separated to the stack
! # Take the factorial on the second
s # Swap so the other is at the top
m # Exponent the two together
}P # After the map: take the product of the values
I # Push the input
.E # Evaluate it as Elixir code, which calculates the value for factorial
# inputs and will keep integer inputs unchanged
Q # Check if they're the same
}í # After we've found our result: reverse each inner pair
'#ý '# Join each inner pair with "#"-delimiter
# (after which the list is output implicitly as result)
```
[Answer]
# Excel (Insider Beta), 350 bytes
```
=LET(e,IFERROR(FIND("/",A1),0),n,ROW(1:99),m,COLUMN(A:CU),p,SORT(FILTER(n,MMULT(1*(MOD(n,m)=0),n^0)=2),,-1),f,LAMBDA(d,LET(c,MMULT((MOD(d,p^m)=0)*1,n^0),h,LAMBDA(x,y,SUM(INT(x/y^n))),z,TRANSPOSE(MINVERSE(MAKEARRAY(25,25,LAMBDA(x,y,h(INDEX(p,x),INDEX(p,y)))))),MMULT(z,c))),r,IF(e,f(LEFT(A1,e-1))-f(MID(A1,e+1,99)),f(A1)),CONCAT(IF(r,p&"#"&r&" ","")))
```
Uses `MAKEARRAY` and `LAMBDA` which are not widely available yet. Prime factors are not duplicated. Works for all numbers \$ <= 2^{20} \$ whose prime factors are all \$<100\$.
## Explanation
`=LET(e,IFERROR(FIND("/",A1),0),` Finds position of "/"; return 0 if not found
`n,ROW(1:99),` vertical array of 1..99
`m,COLUMN(A:CU),` horizontal array of 1..99
`p,SORT(FILTER(n,MMULT(1*(MOD(n,m)=0),n^0)=2),,-1),` reverse sort of all primes \$<100\$.
`f,LAMBDA(d,` `f` is the function that returns the array of prime factorials for an integer \$>1\$.
`LET(c,MMULT((MOD(d,p^m)=0)*1,n^0),` the vertical array of the number of times each prime divides \$d\$.
`h,LAMBDA(x,y,SUM(INT(x/y^n))),` function that returns the number of times \$y\$ divides \$x!\$.
`MAKEARRAY(25,25,LAMBDA(x,y,h(INDEX(p,x),INDEX(p,y))))` an array indicating how many times each prime divides the factorial of each prime
`z,TRANSPOSE(MINVERSE(~)),` the inverse of the prime matrix, note: I had to use `TRANSPOSE` instead of reversing x & y because of some weird precision errors.
`MMULT(z,c))),` matrix multiply z and c, this transforms the number of times each prime divides d to the powers of prime factorials
`r,IF(e,f(LEFT(A1,e-1))-f(MID(A1,e+1,99)),f(A1)),` if \$e>0\$ then \$r=f(num.)-f(denom.)\$ else \$r=f(n)\$.
`CONCAT(IF(r,p&"#"&r&" ","")))` if an element in \$r>0\$ then return \$p\$#\$r\$ and then concatenate.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 222 bytes
```
x=>([n,d=1]=x.split('/'),(f=r=>r<2?'':(((i=y=>y<2||r%y&&i(~-y))(~-r)?v=(q=s=>s%r?0n:-~q(s/r))(n,w=q(d)):v=w=0n)-w?' '+r+'#'+(v-w):'')+f(~-r,n*=(F=n=>n?n*F(~-n):1n)(r)**w,d*=F(r)**v))((n=(z=BigInt)(n))>(d=z(d))?n:d).trim())
```
[Try it online!](https://tio.run/##nVRNb@IwFLzzK15VFdshUKj2BDhIe6i0f2AvVVUh7FDvpk5wTIAC/evss00I9GOl3QOx8/w8M56M@TWtpuXMqMJ2dS7kYZbr0sJiwQ9rntAHHQs@eOTrXllkylJyS1hMU254YsZ3E0KGlFLFNzzZjO92O3OzabcVfetuGMOnYZOK0wUveVLemElfD7tvC1reGlzV8YovqGBsWPEV72vWXU0IkI7pkGvSoVV3xYaEsE7qcGIdcXrPNU/0REf3WNJsONCMGhZFq1hE/N5PKwSmmtNX/l3Nf2iLNIwlVPBXxzTRQ8F61qgXythh1GqFs75M108aOHzrYyld6plVuYZ0OrO5UdMMIVrbFkAmLZgK@wZ6hK9pboC62rGE45iDGzsdhuvgmiMOlWs20i6NxsqotT/jUOVTgWokLQKFSoEWDmZwRAjb0mlWygtOgZx3yCVgDAUONWUAuHHrHPqh9hHm@G7NUgY9NaxC2D7CKq/BzwKyMyrPZC/L55ScnIE8JTGoGIgqcdI4phg7unvaRFzlH4lqe97xnFwLNCc3K2lUusFggYihtGbemOre4IoDysDK1vvidGTT0iIYqllqIVOlpRj5Ra80xMPmv1GAB6wvARAWvN0eHQ6dpSwQCfvrvmt36tDhVciil0k9t8@oBT8gg@MigH02@Qr6ows8FAYIGKLsdj/0H9lli1wXT5ctg8cLztCAbsNuB1dN4Axzhfr87TbmxkDC6wpjX0lrLCvMB6KkCR1gCDH@TSgcZRR5xfU@iYE8tetP27tN/74Vfo5NewdFIDspxCz/LXX6eFO1S52/9Th3udu2aj8Xi5@Ya44jboYOaG/mOSbGyzf5hSZyg7P6/v9UXNzuQbjdpw7xpU6NMvFvGZ/Cawr2@HvlvqsI0@DUu4PgNn9ZPjvQWXl/@AM "JavaScript (Node.js) – Try It Online")
`.trim()` could be removed (-7 bytes) if you were willing to tolerate an extraneous space at the start of the output.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 120 bytes
```
p=>q=>(o={},g=(v,t,i=2,h=j=>j?h(--j,g(j,-t)):i)=>{for(;v>1;)v%i?++i:delete o[i*!(o[h(i,v/=i)]=~~o[i]+t)]})(q,~g(p,1))||o
```
[Try it online!](https://tio.run/##bczBCoJAEIDhe09Rh2Amx9KlCIzZHkQ8RK26izRmy140X93sGHX9@PndJVye1862Pr7LzUwlTy3rB2sQ7l9UMQTyZFlRzY61O9cQx44qcBR7xMwi676UDk5BpycMa3uOIpvdTGO8WUpuNyuQvAZLYccWCx7HGYvIY/FCeNBYQUsp4jDIdJX7UxqzbaSCEo4Isy@@8ZDsk3@u1D9NEdT@R4/qs1BzPr0B "JavaScript (Node.js) – Try It Online")
* [+13 bytes](https://tio.run/##bczBCoJAEIDhe09Rh2Amx8rFCIrZHqEHCA9lq84irumyl8hXNztGXT9@fnsN1z7vpPVx4@5mLHhsWT9Yn2/W5H5tGt@J6cHx80UlQyBPwooqtqztqYI4tlSCpdgjHgRZPwvXwTHo5IhhKacoksPd1MabubvIagHuUoFQ2LBgxsMwYRZ5zKY7PGgooaUEEcfcNb2rzbp2JRSwR5h09o27bbr950r90wRBpT@6V5@FmvLxDQ) if output as an array.
+ [+26 more bytes](https://tio.run/##bczRaoNAEIXh@z5FSgnM1NXGJSWQMJtH6AMEQWtWncU6RpclEOKrW0uvSnN3@Dj8rgjFWA7c@7iTs50rmnsyFzIfn86WPrGdH9iOIHS7q5ogKK@YtGrIkXHHBuLYqRqcij3inpHMrZIBDsGkBwxrPkYR78@2td6u5MSvzyCnBliFN2LMaJoWzCKP2VKHi5pq6FWKiMlX0cOVzDVxwl3@kuPvWOVzKd0orU1aqaGCHcLyf/qL75vt5pFr/UhTBL39pzv9k9DLff4G) to format the string with hash and spaces.
* [-9 bytes](https://tio.run/##ZctLCoMwEADQfU/RLgozNbYaLIIyehBxITZqgjiiIRs/V7fdFrcPnqlcNdeTHq0/8EcdDR0jZcC0bKIlcMIKTVJ0ZCgzeQe@b0QLRvgWMdFI2dLwBKnLwhTdXeeep5OP6pVVVy704wZcdKCFe5HGkvb9h6VnsdwQRhHiuvJR8zBzr549t9BAjHj5l3cQBSeU8kzRiWJ5nqEMEY8v) if we only accept integer inputs.
+ [-34 more bytes](https://tio.run/##XcpBCoMwEEDRfU@RTWEGE2qCRVBGzyKt0UmphhgCpfTs6aKb6vb974Y0bLfAPqrN830Mz3V5jK9sKU8ESUbSksnImRx1rp9BKScncFJFxIaRurddA7Sp0y2mM/dFwY0PvESYgWW6EKOM@MkWaiEEtuIX8WThWlblDow5HKY6QG3KPWij/yB/AQ) if output duplicate items
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~94~~ 89 bytes
```
≔I…⪪⁺S/1¦/²θ≔Πθη≔²ζW⊖η¿﹪ηζ≦⊕ζ≧÷ζηW⊖ζ¿∨¬⬤…²ζ﹪ζκΠ﹪θζ≦⊖ζ¿¬Σ﹪θζ≧÷ζθ«Iζ#⌕﹪θζ⁰1→UMθ⎇﹪κζ×κΠ…·¹ζκ
```
[Try it online!](https://tio.run/##dVJLasMwEF03pxDuZgQuib0pNKvgUMgibUh6AWFPLRFZ8kd2SUrP7sqS3SSQbmRm9H4zcspZnWom@37VNCJXkLDGQHJKJSZcl3AopTCwk20DG1W25mBqoXKgIQnmUeA@wxlTe1R0ORtVdrXO2tRAZdv80o5DcrbVFxcSCawxrbFAZTADTikRnwS2lic18AFIyZaVI3Oj/rBOg6Bs8HK/Fzk3FmTWohMZWoj3veN0Hp3ea3jTBlZSwp6pHH24kIwJrMCRDlNNo4z9yiW7yXal7udz2QaPweDQFv9z7@WuJoXv2cPObtv4N7HM5dQIHoNL8SpUduMQksU1NnLYre4QXpyfK1mZ6KJglmo5H1grVp8mlaNX@RAFNkMxrcA@gv0RRId@YZEfxy1qOfvp@@d4MY/iqH/q5C8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs each prime factorial once per power. Explanation:
```
≔I…⪪⁺S/1¦/²θ
```
Append "/1" to the input in case it's a single integer, then split it on "/" and take the first two values.
```
≔Πθη≔²ζW⊖η¿﹪ηζ≦⊕ζ≧÷ζη
```
Find the largest prime number dividing either the numerator or denominator.
```
W⊖ζ¿∨¬⬤…²ζ﹪ζκΠ﹪θζ≦⊖ζ
```
Loop though the prime numbers down to `2`, decrementing if the current number is not prime or does not divide either the numerator or denominator.
```
¿¬Σ﹪θζ≧÷ζθ«
```
If the current prime number divides both numerator and denominator, start reducing the fraction to its lowest terms, otherwise:
```
Iζ#⌕﹪θζ⁰1→
```
Print the current prime number with "#-1" if it's a factor of the denominator or "#1" if it's a factor of the numerator, leaving a space between prime factorials.
```
UMθ⎇﹪κζ×κΠ…·¹ζκ
```
Multiply whichever isn't a factor by the factorial of the prime.
[Answer]
# [Python 3](https://docs.python.org/3/), 133 130 bytes
```
import math
g=lambda i,k=1,n=1,j=2:i%j%i and g(i,k,n,j+1)or(i+k<3)*" "or"%s#%s "%(j,n)*(i>1)+g(k*math.factorial(j-1),i//j or 1,-n)
```
[Try it online!](https://tio.run/##dZFhb4MgEIa/91fcaEyA0lpssw9u9o8YP9iVWqyCAZZ0v94dumZbs12C5PB571644SNcrNmNo@4H6wL0dbgsmqKr@@OpBi2uhRQGV1tkuU7aRENtTtBQ/COMaFeSWUf16vq6Y5wAsY4kfpl4IAlthWGc6oNkq4Zeeay8OddvwTpdd7RdSyZ0mrZgHUixNmwMygcPBZSlFM@VKOPKMvxIke3jlm2F3FfV4oySANrApMgXgOFUlDaUBzblg9MmUJKSTWu1oX09UB@cCIwJRO@MPaHowZl/7yliExE7NS62QtHGD53GmkDY3DOGPiPwncY4ClXEfmhANO6uWpKvmj@UCg6wzaMNXjy4ODLO1S9edV5NbJr@Ba9nWt2Gf6/EQ7mt0pR2ymB6kNMsQymraQazO3Q1PctTEUvl8zPGE4Epe1E3vAuObvwE "Python 3 – Try It Online")
-3 bytes thanks to loopy walt
-5 more bytes if using python 3.8, as pointed out by ovs
Returns a whitespace separated string.
Uses a recursive algorithm: `i` is the numerator and `k` is the denominator. If `n` is -1, the roles are reversed. `j` is a potential divisor of `i`; `j` is incremented until it divides `i`. After this, we add `j#n` to the output and the function is called again with the roles reversed (`n` is negated). More precisely for inputs `i`, `k` we recurse with `i=k*fact(j-1),k=i//j`. This halts, because every step we are removing one "instance" of the prime number `j`, and only possibly adding smaller primes.
Just for fun, here are some shorter programs using looser IO rules:
[106 bytes](https://tio.run/##fZDBboMwDIbvPEUukwh1B6Hd2lF5L4I4ZCVRgyBBiXfY07MEtGmrpvmS385n/3HmD7o5e1gWM83OE5sk3TKNo5zeeskMWBQwYN20omsb8yo6afvcPAwsnkznEYBhJ7jz7QC228VKWUbFo0qjHrW8kvNGjvmwFxz2lvNfVqQCBYasFVDDAY7wBM9wgjO8gKi6TDvPiBnLVq7JWAyvUoPOia/p7I2lnCCWvwquj8CdPRVFvd2n7mojoxKrSj4q@cQpm0sKo1lArJqA4jKjulydJWPf1U9AIYomWRZ45zjzb06NQa1QWf5DBdyeJUNQ8X@2Pf5epKDlEw "Python 3 – Try It Online"): Integer input only, returns flat list
[Answer]
# Python3, 461 bytes:
```
from itertools import*
import math
def s(n=1):
while(n:=n+1):
if all(n%i for i in range(2,n)):yield n
r=lambda x:pow(*x[0][:-1])*(not x[1:]or r(x[1:]))
F=math.factorial
def f(n):
q,Q=[[[],2,s()]],[]
while q:
p,I,v=q.pop(0)
for i in product(*[range(-I,I)]*len(p)):
if all(i)and p and round(r([[a,z,c]for(a,c),z in zip(p,i)]),4)==round(n,4):return' '.join(f'{b}#{j}'for(_,b),j in zip(p,i))
q+=[[p+[[F(P:=next(v)),P]],I,s(P)],[p,I+1,s(P)],[p,I,s(P)]]
```
[Try it online!](https://tio.run/##TZDNTsMwEITveYqVEOpuakoSyo8i5YrUWzlbFnKbhLpK167rQini2YvTAsrFnllZs/PZfYaV5bsn50@n1tsNmND4YG23A7Nx1oc0udyw0WGV1E0LO@QqpzKBj5XpGuSy4vHZg2lBdx3ytYHWejBgGLzmtwYLwUTlp2m6GjjxVac3i1rDoXT2A9ODzJQsb3JFKbINcJB5qWKAx7MiSp6rfv2k1ctgvdHduUiL3K/dipdKSqlEIXZISgmpfrvBtm/lxEy8V9uJsw4zioP/bs7ber8MmMpLy5uZmJFKu4bR0ZnoD8mQ5hoc9Ke3e67Ro5RaHMVSxTjUYkni2GcejUMnDCkSU6qqy2OOuvRN2HsewWiytoaxHX0tvq@@1t@jPuBVLEishwF90@04krmxlM84j9/cHAK@E4l5hJxF2DlF2Ig3zgfmItXJecMBW3yISX/6PptmA1sUA5PfFtOBfSyy27zIiU4/)
Basic brute force solution, but still runs quickly on the test cases.
] |
[Question]
[
I'm trying to plug this really old phone into my computer but the phone seems to use a very obscure plug. Luckily I have some adapters. Unfortunately, I can't figure out which of them to use to connect my phone to my computer. Can you find the smallest number of adapters that can link my phone and computer?
## Input
A pair of strings representing the phone and the computer's port type and a list of pairs of strings where the pair `A, B` transforms an input of type `A` to type `B`. Example:
```
("A", "D")
[
("A", "B"),
("C", "D"),
("B", "C"),
]
```
The first pair `("A", "D")` is the desired connection. The rest are adapters.
## Challenge
Output the number of adapters required to connect the phone to the computer. In the above example, the answer would be 3 as all 3 adapters would be required.
## Test Cases
```
Phone, Computer
TypeA -> TypeB
TypeC -> TypeD
Output
```
```
A, D
A -> B
B -> C
C -> D
3
```
```
A, Z
A -> B
B -> C
C -> D
D -> Z
X -> Y
Y -> Z
4
```
```
A, B
A -> B
X -> Y
Y -> Z
1
```
```
A, C
A -> B
B -> C
C -> A
2
```
```
A, C
A -> A
B -> B
C -> C
A -> B
B -> C
2
```
## Rules
* Standard loopholes disallowed
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins
* You can assume it is possible to make the connection
* The port on the phone and computer will not be of the same type
* There may be adapters of type `A -> A`
* It is not guaranteed that all of the adapters will be possible to use
* You may take input in any form that is convenient
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
ṗJ$Ẏy@ƒ⁼⁵ɗƇẈṂ
```
[Try it online!](https://tio.run/##y0rNyan8///hzuleKg939VU6HJv0qHHPo8atJ6cfa3@4q@Phzqb/h5cfnfRw54z//6PVHZ3UdRTUnV1ApJMziHSJApERkSAyMko99r@6o/p/9Sh1AA "Jelly – Try It Online")
Full program taking a list of pairs `L` (e.g. `['AB', 'BC', 'CD', 'DZ', 'XY', 'YZ']`) as the first argument, the source as the second and the target as the third.
## How it works
Brute-force approach.
```
ṗJ$Ẏy@ƒ⁼⁵ɗƇẈṂ - Main link. Takes L on the left and S on the right
$ - Group the previous 2 links into a monad f(L):
J - Yield the indices of L; [1, 2, 3, ..., len(L)]
ṗ - Get the n'th Cartesian power of L for each n in this range
Ẏ - Flatten into a list of lists
ɗƇ - Keep those for which the following is true:
ƒ - Reduce the list by the following, starting with S:
y@ - Translate, according to the pair mapping
⁼⁵ - Does the final result equal T?
ẈṂ - Get the length of the shortest element
```
[Answer]
# [J](http://jsoftware.com/), 28 bytes
```
1 :'[:#+./ .*^:(1-u{])^:a:~'
```
[Try it online!](https://tio.run/##lZFRT8IwFIXf@ytO9KErQmnR@FBYMjbikzHGJ2EOKaPgCAIZI8EY99dnFxBBg4lpetJzz/1ym3ZanHE6hqtAUYWAsrvGETzc3hQSiobq/ILXwSt95cja@j1ifaVVTgtG7nyO@9QsdWqQzJfrzGq2gJ5Dj6Y6NvP4Da86S5ONrY0wXGzMCEudpGTicqflJTxHzr26yr0qQ3N/9iI4aNZtDqkG4SD6gKi4XsgQEWLilwVoezZDZlYZYr0yK8453QaXcOFojDFkCEE1hhQut/0digmeG4ierPH9ILCFLXJ1Cun9Qjq9x263txslT3H@EXdANE4Rwc9J7X8RW8QKJfZ9NklGd7jTErhmFq8qnPEmL4HyiwUR9vria5FS5ZHbeyK@@yAPnPwjKzlGik8 "J – Try It Online")
Perhaps stretching the definition of convenient input, I take the adapter list as an adjacency matrix, and the target connection as a boxed pair of indexes (the noun being modified).
The test cases include an (ungolfed) conversion step, so if this is not allowed it can be easily corrected, though the byte count will about double.
## main idea
Simply multiply the adjacency matrix by itself until the cell representing the target adapter becomes 1, keeping track of the intermediate matrices.
The length of that list is the minimal number of adapters.
## [J](http://jsoftware.com/), 30 byte using a verb rather than adverb
```
[:#(,{.+/ .*{:)@]^:(-.@{{:)^:_
```
[Try it online!](https://tio.run/##fZFBT8JAEIXv@yte8LAtlmGLxsNCk6UlnowxngQssJaCJQik1ARD4K/XLSCCRrPZybz53kx2spO8RHwET4LDgYA0t0IIHu9u8668sJw1XVZB5bW0VdiTVoXU2uQ92c9tdu8THtJ4odMYyWzxnpmYzaFn0MOJjuJZ9IE3naXJytSGeJmv4iEWOknZ2COroRLaYkuqKrfKsTE65iqEI5WFetVY4MpBdxBuIMqe6toIGYuj1zl4czpFFi8zRHoZL4mI78EVPANbHGP0awifjfD9IDCFPb/e8c4v3uo8tdudwxB3Z/LPTCe4tsPBzxnNv/Gem8CZWWCVZPzgtRoCN8X2jkSJ6lQ0FB8hmDCvEF@HFdE9U0fNxLcP7oly/2FFn83yTw "J – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 13 bytes
```
GraphDistance
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7370osSDDJbO4JDEvOfV/QFFmXkm0sq5dmoODcqxaXXByYl5dNVd1tZKjkq6dkpOSDpeCgpIziO0CYTuB2M5KtWCOo5KOAlACyEHTAVWFodsFxI6CsCNA7EgIOxIijmRqFBZT8etwIsYdjsg6nJF1OCLpQPY3VDcWU1FN4qr9DwA "Wolfram Language (Mathematica) – Try It Online")
...and here's the built-in.
[Answer]
# JavaScript (ES6), 78 bytes
Expects `(target, list)(source)`, where `list` is an array of string pairs.
```
(b,c,m)=>g=(a,n)=>a==b?m<n?m:m=n:c.map(p=>p[0]==a?p[g(p[1],p[0]=-~n),0]=a:0)|m
```
[Try it online!](https://tio.run/##bZBdT4MwGIXv@yve7IY2ds02vUILgbElRhIvduPGdtExQAyUWtBo/PjrWCB@zCy9OH3f55yTtA/iWdSxzlUzltUhaVPe4j2NaUm4k3EsqDQXwfneLa@kW9oll3bMSqGw4o6KJjvOhauiDKtouqP9YvwpCTUq7Al5L1udPD7lOsFWWluE6UQclnmRrF5ljCeENdWq0bnMMGG1KvIGj7ZyK0eEpZVeiPge18AdeEMAUU2BMRbugEP9ax6Ryw4KCvsjQmEgOjENEDJVKdwvwn7sXtBX/wRg7JhIb4krWVdFwooqw1gbf2r@BEKCBSFwBpY5Z4D7Zg4aXLBubyywwVp61@EisLqWD9J6FALkdb0@8juZo3knATpHyMDNaRh0skF3nazRepgu@oT/nXg5gtMezk/VeWj2F3oD9Af4PzH7Ag "JavaScript (Node.js) – Try It Online")
### Commented
```
( // outer function:
b, // b = target plug
c, // c[] = list of connectors
m // m = minimum number of connections
) => //
g = ( // inner recursive function:
a, // a = current plug
n // n = number of connections
) => //
a == b ? // if a = b:
m < n ? m // update m to min(m, n)
: m = n // (the update is forced if m is still undefined)
: // else:
c.map(p => // for each pair p[] in c[]:
p[0] == a ? // if the input plug of p is a:
p[ //
g( // recursive call:
p[1], // set a to the output plug p[1]
p[0] = -~n // increment the number of connections and
// invalidate p[0] so that it's not used again
), // end of recursive call
0 //
] = a // restore p[0] to a afterwards
: // else:
0 // do nothing
) | m // end of map(); yield m
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
⊞υθFυFζF›⁼§ι±¹§κ⁰№ι§κ¹⊞υ⁺ι§κ¹I⊖⌊EΦυ№ιηLι
```
[Try it online!](https://tio.run/##bU7LCsIwELz3K0JOG4ig557a@kCw0rt4CHVtg2lq00TEn49JUPDgHnZnZ2aZbXth2lEo7xs39@A4mVieXUdDwDGS5uszdwaFRQObyQk1Q2H3@oJPkJwcsQsKrBjj5EvfOFnGvRqdttH0IwQjY@Qb2Cg3/zHkWWNkOK3EbGGNrcEBtcUL1FLLwQ1QiztspYovuZ@cPqYeUHe2B8lS5d6faEE5oVVoASZclomJFC0SLit6PvvFQ70B "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υθ
```
Start a breadth-first search using the computer's port.
```
Fυ
```
Loop over all chains of adapters tried so far.
```
Fζ
```
Loop over all of the adapters.
```
F›⁼§ι±¹§κ⁰№ι§κ¹
```
Can this adapter be plugged in to provide a port not yet seen in this chain?
```
⊞υ⁺ι§κ¹
```
If so then save this new chain to the search list.
```
I⊖⌊EΦυ№ιηLι
```
Print the shortest number of adapters that result in the desired output port.
[Answer]
# Java, 474 bytes
```
(s,e,a)->{java.util.Map<String,java.util.List<String>>m=new java.util.HashMap();java.util.Map<String,Integer>d=new java.util.HashMap();for(String[]c:a)m.computeIfAbsent(c[0],k->new java.util.ArrayList()).add(c[1]);java.util.List<String>l=new java.util.LinkedList();l.add(s);d.put(s,0);while(l.size()!=0){String c=l.remove(0);for(String n:m.getOrDefault(c,new java.util.ArrayList<>()))if(d.get(c)+1<d.getOrDefault(n,(int)1e9)){d.put(n,d.get(c)+1);l.add(n);}}return d.get(e);}
```
This runs a single breadth-first search (BFS) while keeping track of the distances to each node.
[Try it online!](https://tio.run/##nVLLbuIwFF3DV7hZ2RpjwXIaiBRA1VRqNYtupkUs3NihBseJbIeqE@XbmRvCq9NSMbNxjq/veTjXS77mvaVYbYryWasEJZo7h@65MqjqdpTx0qY8kegGVbBBLtdriR@8VWaBnOfWU7TbSSP2eDafzREXvAC2I2Hd7ezUgeHhs86VQBl44H0/4nbhSGPZuUHpaIMdlZSTXlQtISArvdLsnhfDtp8ei3fK@V01irKRka/oePiDuxdgYRJ@qnILt1tIG4mztDS3h4jJNScZS/KsKL28TeNnJ43Hyaw/p6te9F4htpa/NdEwIYwLAW2D@WmK09j6L/s7ZVZStOxQb@nwEwUDX/gtfRK@vigtsWZO/ZaYXI36pNrNIBlpZmWWw4z6p@mRuc7YQvqfdipTXmrITc8kHkaQmagUi4aAE/JtMBTvuYZieAtkIL8TUrW5DD2270MbmHxtpS@tQe2phMqm0wlhyg9vzsuM5aVnBST02uCUta8riAOKgiksTcSTF1VVzVEwDmpawUqDyRZNAE2DuibkIuGnD8Jf6wKCLEBr0C9Aj1v02NYudR1/7frfupN/uU18qe552fggOz7ItgYfTFurultv/gA)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 73 bytes
```
(b,c,m)=>g=(a,n=0)=>a==b?m<n?m:m=n:c[n]&&c.map(p=>p[0]==a&&g(p[1],n+1))|m
```
[Try it online!](https://tio.run/##bZBfT4MwFMXf@ylu9gBt1jXb9GlaFhhbYiTxYS9ujIeOAWKg1IJGo372SSH@mVn6cHr7O@fkpo/iRdSxzlUzktUhOab8iPc0piXhTsaxoJKP26vgfD8vr@W8nJVczuJQRpYVs1IorLijwnHEubCsDKtwElE5nBDyUR518vSc6wTbaW0TphNxWOVFsn6TMR4T1lTrRucyw4TVqsgbPNjJnRwQllZ6KeIHXAN34B0BhDUFxlgQAYf61zwgVwYKCvsTQqEnOmkbIGCqUrh7CLrRLN1V/wRg5LSRzhJXsq6KhBVVhrFu/Wn7HRAQLAiBIdjtGQLumjlomIN9d2vDDOyVexMsfdu0fJKjS8FHrun1kGdkgRZGfHSBUAu356FvZIvujWzQpp8uu4T3nXg9gZMOLs7VuWj6F7o99Hr4PzH9Ag "JavaScript (Node.js) – Try It Online")
Mainly based on [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [answer](https://codegolf.stackexchange.com/a/220913/44718).
`c[n]` means `n < c.length`. Since the question claim that "You can assume it is possible to make the connection", it is safe to give up search if we already used `c.length` adapters but not reach destination yet.
] |
[Question]
[
## Challenge
The cops created code challenges which result in certain wildly incorrect answers despite correct math. Choose an uncracked, not safe formula from the [cop thread](https://codegolf.stackexchange.com/q/217597/45613).
Your task is to find an incorrect answer and describe its underlying cause. The challenge author has the responsibility to confirm whether the explanation is valid, but the incorrect answer does not have to be the same one the challenge creator had in mind.
## Scoring, Rules, and Notes
* Score 1 point for each successfully cracked answer.
* If the error is caused by a particular usage of an external library (or specific version of it), it is sufficient to simply state that there is a known bug with a particular usage of the library used by the cop challenge. Link to a relevant bug report or article.
+ This is to avoid having to pour through potentially millions of lines of source code in libraries (which may be closed source anyway) to find the exact cause of the error.
## Example
### Cop Challenge
* Formula: The Pythagorean Theorem, \$ a^2 + b^2 = c^2 \$
* Inputs: 2 nonnegative real numbers
* Off by more than either input number
* Affects most inputs
* WSL (Ubuntu 18.04) on Windows 10, [Python 3.6.9](https://www.python.org/downloads/release/python-369/)
```
def badpythag(a, b):
a2 = (a / 1e200) ** 2
b2 = (b / 1e200) ** 2
return math.sqrt(a2 + b2) * 1e200
```
### Cracked Answer
This will fail on many inputs (e.g. 3, 4 => 0, but should be 5) due to floating point underflow and return 0. The answer is correct with very large inputs e.g. 3e150 and 4e150, however.
[Answer]
# [Python 3](https://docs.python.org/3/) + Sympy, [Sisyphus' Answer](https://codegolf.stackexchange.com/a/217604/94694)
```
from sympy.ntheory.primetest import mr
from sympy.ntheory.generate import primerange
def is_prime(n: int) -> bool:
if n < 2: return False
return mr(n, primerange(2, 800))
def is_prime_2(n: int) -> bool:
if n < 2: return False
return mr(n, [1009])
n = 2809386136371438866496346539320857607283794588353401165473007394921174159995576890097633348301878401799853448496604965862616291048652062065394646956750323263193037964463262192320342740843556773326129475220032687577421757298519461662249735906372935033549531355723541168448473213797808686850657266188854910604399375221284468243956369013816289853351613404802033369894673267294395882499368769744558478456847832293372532910707925159549055961870528474205973317584333504757691137280936247019772992086410290579840045352494329434008415453636962234340836064927449224611783307531275541463776950841504387756099277118377038405235871794332425052938384904092351280663156507379159650872073401637805282499411435158581593146712826943388219341340599170371727498381901415081480224172469034841153893464174362543356514320522139692755430021327765409775374978255770027259819794532960997484676733140078317807018465818200888425898964847614568913543667470861729894161917981606153150551439410460813448153180857197888310572079656577579695814664713878369660173739371415918888444922272634772987239224582905405240454751027613993535619787590841842251056960329294514093407010964283471430374834873427180817297408975879673867
print(is_prime(n)) # Prints True
print(is_prime_2(n)) # Prints False
```
[Try it online!](https://tio.run/##nZTLalxHEIbXnqc4SwkcU93VdRN2lnmJEIxCRrbAc0aMxgs9vfKVSEgMWQWJmTndp@u/1F/99HL9et719fXhcj5tzy@np5cP@/Xr8Xx5@fB0eTwdr8fn6/Z4ejpfrtvpcviP174c9@Pl/nr8@623Y5f7/cvxcPjj@LA9Pn9@W7rZ77bH/Xq7/fTz9vv5/O3u8O7xYdu3j9u82y7H6/fLvv1y/@35eHj319PpcrO//1e9m/l@S5Hb2x8Lf57/t/SvQ6R@o9y@fdpmSmn6UNcYSzPdV7kuNy2dkhYuMVOjlmWq6ZIx3FaoSGitmmPEGlZVxrtZ1A5X1ZUqIyN5P6qSgyup7MKHpU8fPmvISrcpzj@Ay5eXeZjo1Ok6SgVkX8t5nKNYFV0zluRS481QNsasFTancMwzLGLNwdcEdlB0uM@5KtRKkDlLAVBbZTqoEpPfiMpmGDoHkJGSzp/BK6b7yEwODIG/VmnDjckJz8mCuXrJ0ERUtli1gacLeQJjZTchQnEHvg8k56gDXa9YywzoXOb9pROK8DRth0KipuEw@GJWcAkxsFEphipFK3aAKdhAvYGCt776XCGjAsyil76GTGpE0RVZpgaHpU2I56SLrLUS7NJeS3UhDvjNx8TIATmVwLcZhmn0JQC0t8M4kxHmAljEGIQmRIEyDM4gBpCcaxoLZI6dkiX01HBSnHabG6GKQiy/MiZP5AeQbMXtGI2i88PSkrcUBsHp6V0bT0nMat/J4wAcUMgXWIP2NMcc3ZK52CBrhAnmwzQ5hz2x8MwoBRNw8Jc2a3m9ySXyPKGN/JNybKB25CRCwRYNK3B6UvC0bQiqe3i3CIPxDv/o52AV@klgiRWGEBlCTkd9dASKVELEg@4xmp1jdPtAEgC0BMJIsabIhixHVs9Xr2fPLCyorINe4yFmkmKigRBwFyMeZBU@3gM5sJxhj/anOujEuvuNIC6CDg@d0A6AZcenG0qyuQOMPMG5B4IweaMGM4alqCKzYgAwlEXEIEsiV8sXxHKlrL5w6BE3xcrosW7yLbfnuwg1hIPLKQ4Hrrz9evPPpcpt@ONSX4e3t6@vfwI "Python 3 – Try It Online")
`n` is strongly pseudoprime for all prime bases below 1,000, which means the Miller-Rabin test will give a false positive for any bases in the `(2, 800)` range. As soon as you use a prime base above 1,000, the Miller-Rabin test correctly identifies it as composite.
I did not calculate this number myself. I took it from [this answer from Joe53](https://math.stackexchange.com/a/465314) on Mathematics Stack Exchange, which in turn was calculated using the technique in [this paper](https://www.ams.org/journals/mcom/2005-74-250/S0025-5718-04-01693-X/S0025-5718-04-01693-X.pdf).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), [tsh's answer](https://codegolf.stackexchange.com/a/217652/94093)
```
function max(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw TypeError("This function only accept numbers");
}
if (a === b) {
return a;
} else if (a > b) {
return a;
} else if (a < b) {
return b;
} else {
return Math.max(a, b);
}
}
function max_ref(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw TypeError("This function only accept numbers");
}
return Math.max(a, b);
}
console.log(max(-0, 0));
console.log(max_ref(-0, 0));
```
[Try it online!](https://tio.run/##xZAxT8NADIX3/IpHlyZSU2WHsHVk6175DocEpefId6FUtL89HE1atSAkNubvs/38XumNvNWmC7mTZx6Gqnc2NOKwpfeUFjAZPhKgqZCGfcdSgXBXlpi7fmtY5zgcMAFzA8Y5INQqO6yjslIVTWfruvG4nBHX7kHWchcwTvpZdh8nj9NVQhm3mvM65dCrA50UcOt5sh7/4Dz8cMyVcwOeKNTLSwdjoGOSXNezUa7@vaJf4saoVpyXlpetvKRfJC8WKLLIvoHTG2c4DHmRFJ8 "JavaScript (Node.js) – Try It Online")
```
-0
0
```
According to `===`, signed `0` is equal to unsigned `0`, but as shown in this SO post, [`Math.max` has a special case for signed `0`](https://stackoverflow.com/questions/33851810/how-do-javascript-math-max-and-math-min-actually-work).
The first argument is returned when the `===` is true, so all we have to do is call it with `-0, 0` for it to return the wrong answer.
[Answer]
# [Lua (LuaJIT)](https://luajit.org/), cracks [@LuaNoob's answer](https://codegolf.stackexchange.com/a/217668/92901)
```
function Fails(i)
local max = i * 80
local a = 0
while true do
if a < max then
a = a + 0.2
else
break
end
end
print("Input", i)
print("Max", max)
print("Expected Value", string.format("%.64f", max))
print("Value", string.format("%.64f", a))
print("Value-0.2", string.format("%.64f", a-0.2))
print("Equal?", a == max)
print()
end
Fails(0.46) -- fails
Fails(0.47) -- works
```
[Try it online!](https://tio.run/##hZFBT8MwDIXv/RXWJKQVaFWhaXCg4jQkDly5m9bZwrykpInWf1@cUDaKEPiS5HvvybbCAQsO@Kb9OKpgGq@tgUfU3C91noEU2wYZDjhADRou4a76hlFglSVw3Gkm8C4QtDaRWFqJ5z7F/Y7MiceKYYQrqMqbEyfuaWZ6dYT7s2za7OtMl85p45eLJ9MFv7iGaeaJPuMgTHrP6GboqPHUwgtyIDH0XoRtqaw7oOgX5Xqlptws@I8ff3EXstsfiSjPU5v3gPwQNajrn6PnWdr783uqcrXOoShAxecZ3iZ4tG7fj@MH "Lua (LuaJIT) – Try It Online")
Works with `0.47` (found by trial and error). No doubt many other values also produce the 'expected' answer.
With the slightly modified code above we see that the failure for some inputs is due to floating point errors. Specifically, repeated addition (`a + 0.2`) is [not the same](https://stackoverflow.com/q/33152446) as multiplication (`i * 80`) in floating point arithmetic. Compensated summation algorithms, such as [Kahan summation](https://en.wikipedia.org/wiki/Kahan_summation_algorithm), are designed to reduce precision loss due to repeated addition.
[Answer]
# Python 3.9+, [The Empty String Photographer](https://codegolf.stackexchange.com/a/262929/95204)
```
## 'Solution'
import math
def fails(x: float, y: float) -> int:
return math.lcm(x.as_integer_ratio()[1], y.as_integer_ratio()[1])
## Crack
assert fails(2/3, 2/3) > 1000000 # Expected 3
# Instead is equal to 2**57 due to floating point using bas
```
Valid crack according to poster's comment even though technically `2/3` is equal to `6004799503160661/9007199254740992` before the function is even called, making the function 'correct' by returning `2**57`=`9007199254740992`
] |
[Question]
[
## Background
[**Conway criterion**](https://en.wikipedia.org/wiki/Conway_criterion) is a method to test if a given polygon can tile (i.e. cover without overlapping) an infinite plane. It states that a polygon can tile the plane if the following conditions are met:
* The given polygon does not have any holes in it.
* It is possible to choose six consecutive1 points \$A,B,C,D,E,F\$ on its perimeter, so that
+ The boundary part of \$A\$ to \$B\$ must be equal to that of \$E\$ to \$D\$ in its size, shape, and orientation;
+ Each of the boundary parts \$BC\$, \$CD\$, \$EF\$, and \$FA\$ must have 180-degrees rotational symmetry; and
+ At least 3 out of the six points must be distinct from each other.
1) By *consecutive*, the six points must appear in the given order if you walk around the shape in one direction (either CW (clockwise) or CCW (counter-clockwise)). A boundary part between two consecutive points may contain zero, one, or multiple line segments.
If all the conditions are met, the given shape can tile the plane using only translation and 180-degree rotation. However, failing the condition doesn't mean the piece can't tile the plane. This happens when the tiling involves 90-degree rotations and/or reflections, or the tiling does not use 180-degree rotation at all.
The following is one example that satisfies Conway criterion:
[](https://i.stack.imgur.com/pmDPc.png)
with its plane tiling:
[](https://i.stack.imgur.com/7uLux.png)
## Task
Given a polyomino without holes as input, determine if it satisfies Conway criterion.
You can take the input in any sensible ways, including but not limited to
* a 2D grid;
* a list of coordinates of the cells;
* a list of coordinates on the boundary (including non-vertices or not);
* a list of steps starting from some point on the perimeter in NSEW notation, ...
If you use the input format that describes the perimeter (e.g. the last two formats above), you can assume that the input (the sequence of points or steps on the perimeter) is given in certain direction (either CW or CCW), but you *cannot* assume that it starts at any certain position.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
The test cases are given as 2D grid, where `O` is a part of the polyomino and `.` is an empty space.
### True
```
the example above
OO........
OOOOOOOOOO
OOOOOOOOOO
....OOOOOO
....OOOOOO
....OOOOOO
....OOOOOO
....OOOOOO
the F pentomino
.OO
OO.
.O.
one possible set of points:
A---E=F
| |
+-+ +-+
| |
B-+ D
| |
+-C
OOO.
O.OO
E---D-C
| |
F +-+ +-+
| | | |
+-+ A---B
a nonomino that can tile with or without 180 degrees rotation
.O..
.OOO
OOO.
.OO.
.O..
can you spot ABCDEF here? (hint: two points out of ABCDEF are not on the vertices)
OOOO...
.OOOO..
OO.O...
O..OOOO
how about this? (hint: AB and DE are zero-length)
...OOOO.
OO.OO...
O..OOO..
OOOO....
..OOOOOO
..OO....
```
### False
```
can tile the plane, but needs 90 deg rotation
.OOO.
OO.OO
cannot tile the plane at all
OOOO
O...
O.OO
OOO.
can tile with only translation, but not with 180 degrees rotation
...O
.OOO
OOO.
..OO
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~371 ... 338~~ 336 bytes
Takes as input a list of complex numbers, denoting the boundary coordinates in counterclockwise order.
*-9 bytes thanks to @ovs*
*-2 bytes thanks to @Bubbler*
```
import itertools as Z
def f(P):Q=P*2;I=Q.index;L=len;return any(L({*map(complex.__sub__,T:=(J:=lambda x,y:Q[(j:=I(p[x])):I(p[y],j)+1])(0,1),U:=J(3,4)[::-1])})<2<L({*p})and(L(T)==L(U))&all((B:=J(a,-~a%6))==[B[L(B)//2]-E+B[~L(B)//2]for E in B][::-1]for a in[1,2,4,5])for S in zip(*[Q[I(i):]for i in P])for p in eval('Z.'+dir(Z)[11])(S,6))
```
[Try it online!](https://tio.run/##XY/RT@owFMbf91c0Ifd6CmWuG5qb4l6W@IAhGUR9oVlIdSOWjK4ZQ0Gj/zq23URy@/DL6ddzvu9UH5qXSkX/dH08yo2u6gbJpqibqiq3SGzRwsuLFVrBDLN5POuH40k896XKi/14GpeFGtdFs6sVEuoAU/job4SG52qjy2LvL5fb3dNySR5YDHcsLsXmKRdoTw5szmHN4glovs8wZrY4ZGSNBzTDEBCKySOL7yAiI8wZGxr1E9@ENzZAf2KhcpP1gON4Co8Y/xVlCZDYAUGGX@LPNTZPPOFTSPDlZZgNbwcJ//q5raoa3SKpUJK13lYQRuCUhGRErjJslXvb8i419PmcT0Bi5hqllWdti7Z18SpKuFj4F4Nc1rDAnNo/3BOzxLGHJkrvGub1vB7y09QwTX1XW7qrq1L32Da1glM87@1FlgWizEO6lqqBFbg8aW0Bm3PkwYCuCaIdA8OwI3UMDaOOkVMi19nS6oFh5hmj4GRBu2F6soscRx2pU@jJuo35tbOk/5ue7/Uz/Gt61ZGeAkZnu58HtMu5gG8 "Python 3.8 (pre-release) – Try It Online")
] |
[Question]
[
Given [this list of all the words in english](https://raw.githubusercontent.com/dwyl/english-words/master/words.txt) and a string with s\_me missi\_g lett\_\_s, find one way to fill in the letters. Do note that some words on the list contain special characters (`! & ' , - . /`) and numbers
# Input:
[This list](https://raw.githubusercontent.com/dwyl/english-words/master/words.txt) and a string with missing letters.
The input sentence can contain or be missing any of these characters: `! & ' , - . / 0 1 2 3 4 5 6 7 8 9 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 e f g h i j k l m n o p q r s t u v w x y z`. An underscore is used to mark a missing character. All missing characters have a possible solution.
# Output:
One possible solution with all the missing letters fixed. Words split at a space . Case sensitive, includes words with `! & ' , - . /`
# Test Cases
Input: `a string with s_me missi_g lett__s`
All possible outputs: `a string with [same, seme, sime, some] missing letters`
Output Example: `a string with same missing letters`
Input: `A_ 6-po_nt A/_ ada__er`
All possible outputs: `[A., A1, A4, A5, AA, AB, AF, AG, AH, AI, AY, AJ, AK, AM, AO, AP, AQ, AS, AT, AU, AV, AW, Ax, AZ] 6-point [A/C, A/F, A/O, A/P, A/V]`
Output Example: `A. 6-point A/C adapter`
Input: `A_M AT&_ platform_s scyth_'s hee_hee_ he-_e! 2_4,5_t`
All possible outputs: `[A&M, AAM, ABM, ACM, ADM, AFM, AGM, AIM, ALM, APM, ARM, ASM, ATM, AUM, AVM] AT&T platform's scythe's hee-hee! he-he! 2,4,5.t`
Output example: `A&M AT&T platform's scythe's hee-hee! he-he! 2,4,5-t`
SemicolonSeperatedValue for first possible output:
```
a string with s_me missi_g lett__s;a string with same missing letters
A_ 6-po_nt A/_ ada__er;A. 6-point A/C adapter
A_M AT&_ platform_s scyth_'s hee_hee_ he-_e! 2_4,5_t;A&M AT&T platform's scythe's hee-hee! he-he! 2,4,5-t
```
# Scoring
As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest solution in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18 25 20~~ 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
...noticed a bug during write-up, cost 7 to fix naively, then saved 5 with another approach to fix it.
```
LÞṗ⁹ḲL¤K€ḟ”_⁼œ&ʋ@ƇṪ
```
A dyadic Link accepting a list of lists of characters on the left (words) and a list of characters on the right (string) which returns a list of characters.
**[Try it online!](https://tio.run/##y0rNyan8/9/n8LyHO6c/atz5cMcmn0NLvB81rXm4Y/6jhrnxjxr3HJ2sdqrb4Vj7w52r/v//H61kpluQn5lXoqSjoGSOYDrqO4MpPTBpCCITUxILSlJTEMwiODMfwizLT05MyQcxixNB5sT@h5muAKMd4@OVAA "Jelly – Try It Online")**
...using a hugely restricted word list due to incredible inefficiency (although it could be far worse!)
### How?
```
LÞṗ⁹ḲL¤K€ḟ”_⁼œ&ʋ@ƇṪ - Link: words, W; string, S
Þ - sort (W) by:
L - length (this is so we get final results which will match
in length when we use Ṫ at the end of the Link)
¤ - nilad followed by link(s) as a nilad:
⁹ - chain's right argument (S)
Ḳ - split on spaces
L - length
ṗ - Cartesian power (all ways of making that number of words)
K€ - join €ach with spaces
Ƈ - filter keep those for which:
ʋ@ - last four links as a dyad with swapped arguments:
”_ - literal '_' character
ḟ - filter discard (remove all '_'s from S)
œ& - (S) multi-set intersection (current value)
⁼ - equal? (S without '_'s == multi-set intersection?)
Ṫ - head (last result)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~96~~ ~~105~~ ~~99~~ 101 bytes
```
lambda p,W:' '.join([w for w in W if all(map(lambda c,d:c in['_',d]and d,s,w))][0]for s in p.split())
```
[Try it online!](https://tio.run/##XY1BS8QwEIXP9lc892ASyLayqIfCHvoDvAk91DLETdpG0jYkkeKvr60ouB4G3rz53jz/mYZ5Oq3d@XV1anzTCl7WJQPL32c78WZBNwcssBNq2A7KOT4qz3/gi9TlZTs2jJjUrZo0tIxyEaJt7ts9Gveoz6N3NnEh1sWmAbM3E2fFRwxFHFQwhbaXVCxz0JFJsMAEVERfZjc1zujzYJTm4vdJlvlgp4SOs0FtvbX4awTt/nkKMW26x3d3pNFgtDFa6uFMSkTxmq8IT0c/07ZVBUFpRWTCFXOo6BnVyx1hMIb22cSRzC1O9CAfKR12ev0C "Python 2 – Try It Online")
`W` is the list of words which is set up separately; I'm using the `unix words` file on TIO, which doesn't contain `platform's` or `scythes's`.
Added 2 bytes for [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy).
[Answer]
# Java 10, 127 bytes
```
L->s->{for(var x:s.split(" "))for(var w:L)if(w.matches(x.replace(".","\\.").replace("_","."))){System.out.print(w+" ");break;}}
```
[Try it online](https://tio.run/##hVJNa9tAEL3nV0x1KCsqraG0PcSpwZTm5EDBvTVh2Mgrax1pJXZGlo3Rb3dXaxm3wWlBn@/NzJs3Oxu1Velm9XLMSkUED8rYww0AsWKTwcazsmVTyry1GZvayvvx4@7CzZ1T@4UhvluyM3Y9S64lfqsttZV256AZ5PAVjot0RunskNdObJWD3S1JakrDIoIojs9wd7uITS46WSnOCk1iJ51uSpVpEckoiR4fZRRfIPSQB@L4sNwT60rWLcvGy7LoPgyFp89Oq5dp3x@n3q2/mva59IZH39varKDysxCnZn89gYqHuQCw24uLO2Jfp5LL8Do7gxPq3YVAa2qZm1LLe/8gWRrr@/@b@aG4ILnW3vWkJTehQjk9WZmMJ13tVhSsBHmAf8wdQrDXtbq7FideYSQVBXy0wXWAhVebjmqsPR3KJhCpwZkXgs5wAYSVhsoQGVxDqZkRfaNXE@cIX9KmRsswnyColULU7s3gB5j/fI9QaI3D7T9S1O/gI35KPiO/kcZOWZLASDg0hBoZLYYYY/Gc1GfDAonvu0w3w1qCjg@9Z/rTGvx5/qH6f6edwOl3GM14RrlUTVPuT53FUmWD1jDjsYfXO1laEZj@pj/@Bg) (also uses the `/usr/share/dict/words` TIO word-library, which doesn't contain `platform's` or `scyth's`, but the lambda-function works with any kind of list String-List provided).
**Explanation:**
```
L->s->{ // Method with String-List & String parameters and no return-type
for(var x:s.split(" ")) // Loop over the parts of the input-String, split by spaces
for(var w:L) // Inner loop over the words
if(w.matches(x.replace(".","\\.")
// Escape all dots
.replace("_","."))){
// Replace all underscores with regex-dots
// And if the current word matches it:
System.out.print(w+" ");
// Print the word, plus a space
break;}} // And stop the inner loop
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~232~~ 226 bytes
* -23 bytes from @ceilingcat
* +17 bytes for required header file
Like the other submissions, I used `/usr/share/dict/words`; change the first argument to select another wordlist and the second argument to specify the size (the function itself just needs an array of strings as the dictionary.) On a non-matched word with a `_`, the original word is returned.
```
#import<string.h>
*g(s,t,u,v,w)char*s,**t,*u,*v,*w;{for(w=index(s,95)?0:s;(v=*t)&&!w;w=*u+*v?0:*t,t++)for(u=s;*u==95|*v==*u&&*v++&&*u++;);s=w?:s;}h(s,t,c,u)int*s,*t,*c,*u;{for(u=s;c=strtok(u," ");u=0)printf(" %s"+!!u,g(c,t));}
```
[Try it online!](https://tio.run/##LZFLj9sgFIX38yuIq7q83HjSpE1Kmdl07WU21QhZ@IXq2JEvmErT@ev1XCfdgASX851zsFlr7bJ8cJfrOPkf4Cc3tJ@7pwfeUpBeBjnLyGxXThwk517yIPkseVSvzTjRqN1Q1X9w9HRgz/l3UHTW3LM03UQVNQ@Cz3iM77wQbH0RNCgetD4d/vJZ40Sa8lkIXIMQiinQ8Rll3rob3srA3OBXNqIt0u/cVcVqdOvH3zTIhCRMBZ2zK9r3DU3IR0jEZhNkS630jKk3jDjYPlQ1wZCVG9eMD5fSDbSQ5xuDn9XrLWijm/FaD/T8q3j68iKTKWEYHbQt@3609PBVFrr0o8OB3QsTj@ut12gxaHoTYCAKfsSe1OpVFVmWppRjA7ppaw9oeH@UDboKQu@PzDUUW7sXGeRjzhjDanKFornqkIImYI2wbANMW0BEva2c9ds4ThUs@2@n4@60GPBkZwwx2U/S1Z8MKcn9O0l0viNgLjW5OABnWtLX3hsD//f4zzZ92cKSxXc "C (gcc) – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~174~~ 171 bytes
```
import StdEnv,Text
$l=join" "o map(hd o filter(\w=any((==)w)l)o@o split"_")o split" "
@[h:t]|t>[]=[h<+c<+v\\c<-['0'..'9']++['a'..'z']++['A'..'Z']++['!&\',-./'],v<- @t]=[h]
```
[Try it online!](https://tio.run/##RZBbS8NAEIXf8yvWtZiE3Prig5JIhVYQCgr1ySSEJdk0q3spu9PGir/duGloffvOzDmHYWpOiRyEavacIkGYHJjYKQ1oA81KHsI3@gXOjGcfikmMsLKendc1SKGWcaDaK/qMyKPnZZnf@9xXC4XMjjPAFfbPiLCzyLt7KH/gIS@zvEuDOg0ORVGnUe7O3Th279wyCHKXjPw98ePI7xNf3RRuGMWJW4aHNEILGFvKy61HA1TET4zTcEmAxCutlXY2QOyyV5o3zjXyXj4RZwbCaeKjDGlKmjG0ZpIahJO90YnpiKZJw2pIrK8x@FIwhm3IPgCBZuKk7dhYIbd2gcmZewYdMpWwH2XGsGqLOAWoKoOtv93LGpiSNjFzsn95qp8Kht@65WRrhuh5PSyPkghWT@KVE2iVFkPUDbfzufgD "Clean – Try It Online")
TIO link uses the dictionary in `/usr/share/dict/words` but it'll work with any list of words.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 27 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
#εD'_åiUʒX‚ζεD'_åsË~}P}Ω]ðý
```
Can definitely be golfed a bit more, but this will do for now.
First input is the string, second a list of words. If multiple words are possible, it picks a random one.
Assumes the sentence always contains at least a single space. If this is not allowed, the `#` has to be replaced with `ð¡`.
Uses the legacy version because the zip-builtins work on strings, whereas these have to be character-lists in the new version of 05AB1E. In the new version, the `ʒX‚ζεD'_åsË~}P}` would have been 1 byte longer because of that: `ʒSXS‚ζε'_åyË~}P}`.
[Try it online](https://tio.run/##MzBNTDJM/f9f@dxWF/X4w0szQ09NinjUMOvcNqhA8eHuutqA2nMrYw9vOLz3//9EheKSosy8dIXyzJIMheL43FSF3Mzi4sz4dIWc1JKS@PhirmilxKRkJR0lED@1CM4oBrJASqEU0AwgqzgxNxVEpUKoTAiVD6YS81JAJBCnpZaDdOUXgYSLgOL5uUBGeX5RSrFSLAA) (with a small sample dictionary list).
**Explanation:**
```
# # Split the (implicit) first input-String on spaces
ε # Map over each word:
D # Duplicate the current word
'_åi '# If the word contains an underscore:
U # Pop the copy and store it in variable `X`
ʒ # Filter over the (implicit) second input-list of words:
X‚ # Pair `X` with the current word
ζ # Zip/transpose, swapping rows/columns with spaces as default
# filler if the strings are of unequal length
ε # Map over each pair of characters
D # Duplicate it
'_å '# Check if the pair contains an underscore
s # Swap to get the map-value again
Ë # Check that both characters are the same
~ # Check that either of these were truthy
}P # After the map: check if all pairs were truthy
}Ω # After the filter: pop and push a random valid word
# (implicit else: use the unmodified word from the duplicate)
] # Close both the if-statement and map
ðý # And join the list by spaces
# (after which the result is output implicitly)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 22 bytes
```
wm`₁⁰w²
ḟoΛ='_żμ?'_³=⁰
```
[Try it online!](https://tio.run/##yygtzv7/vzw34VFT46PGDeWHNnE93DE//9xsW/X4o3vO7bFXjz@02RYo8////0SF4pKizLx0hfLMkgyF4vjcVIXczOLizPh0hZzUkpL4@OL/0UqJSjpKEGUQRj6YAdKRX1oCZYFk8nNTk/JTKqFMEJUIpkAmgqhUoMFgrWArwCyQJalFxXAWlFGanKoUCwA "Husk – Try It Online")
For each word in query text, goes through all words in the dictionary substituting matching characters for `'_'`.
If, after doing this, the word is only `'_'`s, then it matched at all non-`'_'` characters, so it's a valid replacement.
```
ḟoΛ='_żμ?'_³=⁰ # helper function:
# finds word in arg2 that matches arg1
# except at '_' characters.
ḟ # get first element that satisfies
oΛ='_ # all elements are equal to '_'
# of
żμ # zip togethter arg2 and arg1 with
? =⁰ # if they're equal
³ # then arg 2
'_ # otherwise '_'
wm`₁⁰w² # main program:
w # join with spaces
m w² # map arg2 split on spaces
`₁⁰ # using helper function with arg1
```
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 53 bytes
```
->d,s{s.gsub(/\S+/){d.grep(/#{$&.tr ?_,?.}/)[0]||_1}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY3PCoJAGMTvPcWH_UFJ3ToEXcybL9DRZCl2swU3Zb9vkVCfpItEPVRvk1mXGRh-M3N_Gnu69Y8kelk6B9v3JtgJHxsMc7Qnlx32S-Y1IsyNrFw2bWaLkAzE3I_DjnnpKmtbvu66f1kLiGBep0VppAZVodVQSCJpELRCVNcc8KglYDmIKAcOUBEMEWWTSWUJIUmFD84RkMwXrxVdAPmAjwM8Hwc5Ryf7nfb9zz8)
] |
[Question]
[
## – of crisis and martyrdom
(that's the subtitle because subtitles are cool)
In this [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'") challenge in [python](/questions/tagged/python "show questions tagged 'python'") (yup; you need go no farther to know you may not submit in java), you need to create a bot that plays a game very similar to [welcome to the dungeon](https://boardgamegeek.com/boardgame/150312/welcome-dungeon)
## Game Rules
(note that this is not the original game)
There is a deck, an item set, and some reward cards and death cards. Base HP is 3.
The deck consists of 13 monster cards numbered `1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 9` to denote their strengths.
**Item List**
1. Demonic pact: Defeat the demon (strength 7 monster), and the monster below it on the dungeon pile.
- (just defeats the demon if the demon was the last in the dungeon)
2. Health potion: When you fall to 0 HP, defeat the monster and return to 3 HP.
3. Holy grail: Defeat monsters of even-numbered strength (in the game, these are undead). If an even-numbered monster occurs after the demonic pact has been used, that acts first, and you will not get an extra-pact kill after this monster.
4. Vorpal dagger: Choose one monster before entering the dungeon; this type of monster is defeated. If the targeted monster occurs after the demonic pact has been used, that acts first, and you will not get an extra-pact kill after this monster.
5. Shield: Add 3 to total HP before spelunking. This does not affect usage of health potion, which will always return health to 3.
6. Armour: Add 5 to total HP before spelunking. This does not affect usage of health potion, which will always return health to 3.
Reward cards are used to keep track of who has succeeded in the dungeon. Death cards track who has failed in the dungeon.
**Drawing Phase**
Before the drawing phase begins all monster cards are returned to the deck, both players are restored to 3 HP, and all discarded items are restored such that there is one of each.
The first player decides whether to draw a card from the deck, hiding it from the other player. If so, they must choose to either place it on top of the dungeon pile or discard it along with an item of their choice. Discarded items and cards will be unavailable to either player until the next round.
After player one takes their turn, player two does the same. The players alternately decide whether to draw and what to do with the drawn card, until someone decides not to draw or a player takes the last card from the deck.
If a player decides not to draw, or draws the last card, the drawing phase ends and the other player now has to enter the dungeon and begin spelunking.
**Spelunking Phase**
If the Vorpal dagger has not been discarded, the spelunking player must now decide which card to apply it to. There are no active decisions to be made for the rest of this phase.
The first player takes the top card; that is, the last card placed in the dungeon, and see its strength number. If demonic pact is active from the previous turn, the drawn card is discarded. Otherwise, the player's items will be checked in the order 'demonic pact', 'holy grail', 'Vorpal dagger'. The first un-discarded item capable of defeating the drawn card will then be used, and the card discarded. If demonic pact is used, it will now be active for the next card. The used item is not discarded.
If there is no applicable item available, the strength of the card is subtracted from the player's health. If their health is no longer positive they will be restored to 3 HP and the potion discarded if available, otherwise the dungeon crawl ends and they take a death card.
While the player is not defeated and there are cards remaining in the dungeon, this process of drawing the top card is repeated. Upon successfully defeating all cards in the dungeon the dungeon crawl ends and the spelunking player collects a reward card.
**Full Game Description**
A game consists of a series of rounds, each having a drawing phase and then a spelunking phase. At the end of each round one player will have collected either a death card or a reward card; once a player accumulates 5 of either type the game ends. If they have 5 death cards they lose the game. If they have 5 reward cards, they win. Either way, the other player receives the opposite result. If neither player has 5 cards of one type, play progresses to the next round and the player who went second in the previous round now goes first and vice versa.
## KOTH details
Each bot will play 400 games against every other bot according to the rules described above. Which bot is player one (and so goes first in the first round) alternates each game, and all state is reset between games.
Here are the items again:
1. Demonic pact: Defeat the demon (strength 7 monster), and the monster below it on the dungeon pile.
- (just defeats the demon if the demon was the last in the dungeon)
2. Health potion: When you fall to 0 HP, defeat the monster and return to 3 HP.
3. Holy grail: Defeat monsters of even-numbered strength (in the game, these are undead). If an even-numbered monster occurs after the demonic pact has been used, that acts first, and you will not get an extra-pact kill after this monster.
4. Vorpal dagger: Choose one monster before entering the dungeon; this type of monster is defeated. If the targeted monster occurs after the demonic pact has been used, that acts first, and you will not get an extra-pact kill after this monster.
5. Shield: Add 3 to total HP before spelunking. This does not affect usage of health potion, which will always return health to 3.
6. Armour: Add 5 to total HP before spelunking. This does not affect usage of health potion, which will always return health to 3.
and the deck: `1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 9`.
You must implement a bot class that does not use class variables, deriving from the following base class:
```
class BasePlayer:
def start_turn(self, last_turn):
raise NotImplementedError
def play(self, card):
raise NotImplementedError
def vorpal_choice(self, last_turn):
raise NotImplementedError
def result(self, bot, result, dungeon, vorped):
raise NotImplementedError
```
This base class shows methods your class needs to implement, and the number of arguments taken by each.
**Method Argument Descriptions**
* `last_turn` in `vorpal_choice` and `start_turn` is an integer or a None value. A value of 0 to 5 indicates that the enemy discarded the drawn card along with the item indicated by that value (see the list of items above). A value of 6 indicates that the enemy placed the card in the dungeon. A None value indicates that the bot is playing first in this round (not possible for `vorpal_choice`). In `vorpal_choice` last\_turn is likely to be 7, indicating that they passed that turn. The only circumstance in which it is not 7 is when the enemy drew the last card.
* `card` is a number representing the strength of one of the cards from the deck as enumerated above.
Now, the arguments for `result` are a little bit more complex:
* `bot` indicates the bot which entered the dungeon. 0 indicates entering the dungeon, and 1 indicates that the enemy entered the dungeon.
* `result` indicates the success of the trip. False indicates the spelunking bot succeeded, while True indicates they failed.
* `dungeon` is a list of cards/ints representing the cards that were in the dungeon. The dungeon is ordered by order placed; the first card placed in the dungeon is first in the list, and the last card placed in is at the end. You will not receive any info about discarded cards; they are secret from the other bot.
* `vorped` is an integer representing the `vorpal_choice` made by the spelunking bot. If `bot==0`, you already know this, but if `bot==1`, this can be useful information.
I'll be honest, I don't entirely recall why I made winning result False, but I think it was a good idea at the time.
**Return Values**
* `start_turn`: Return 1 to draw a card, or 0 to pass.
* `play`: Return 0 to 5 to discard the corresponding item and the drawn card, or 6 to place the card in the dungeon (consistent with last\_turn input, except for passing, which is done during start\_turn).
* `vorpal_choice`: Return the number of the card you wish to eliminate with the Vorpal dagger (1 to eliminate 1s, 5 to eliminate 5s). Picking a non-existent card kills you (8 is illegal, 10 is illegal, 0 is illegal).
* `result`: You may return anything, because this is an informing function to update the bot's data.
# [You can check out the controller here](https://github.com/Destructible-Watermelon/dungeon-of-botdom)
# Additional clarifications, or just repeating some small details you might have skipped past and might want to know quickly:
Bots play 400 games with each other bot.
### No class variables
### No targeting specific other bots
### No propping up other bots
### No reflection things like modifying the random module or other bots.
### 6 bots maximum (per person), unless it is obvious that all bots are worth including in the KOTH (but still probably don't make a bunch of bots please)
---
### There is no specific end time for this KOTH, except the end of the bounty for what that is worth. Just try to be winning at each time.
Results so far (sorry for being rather lazy with these guys :P)
```
1 GrailThief 2732 0.98
2 Steve 2399 0.86
3 DevilWorshipper 1854 0.66
4 RunAway 1336 0.48
5 BoringPlayer 1190 0.42
6 SlapAndFlap 783 0.28
7 DareDevilDumDum 750 0.27
8 RandomMandom 156 0.06
```
Grailthief "steals" the bounty. not really, because it earned it. Good work, Sleafar!
[Answer]
# GrailThief
An old and experienced dungeon crawler. He knows that most of the others hope, that the holy grail saves them, therefore he makes sure it disappears.
```
from base import BasePlayer
import copy
class GrailThief(BasePlayer):
class Stats:
def __init__(self):
self.deck = [1, 2, 3, 4, 5] * 2 + [6, 7, 9]
self.items = {0, 1, 2, 3, 4, 5}
self.dungeon_known = []
self.dungeon_unknown = 0
self.monsters_safe = {2, 4, 6, 7}
self.update()
def update(self):
self.dungeon_total = len(self.dungeon_known) + self.dungeon_unknown
deck_factor = float(self.dungeon_unknown) / len(self.deck) if len(self.deck) > 0 else 1.0
self.dungeon_weighted = [(i, 0.0 if i in self.monsters_safe else 1.0) for i in self.dungeon_known] + [(i, 0.0 if i in self.monsters_safe else deck_factor) for i in self.deck]
dungeon_weighted_sums = dict.fromkeys(self.dungeon_known + self.deck, 0.0)
for i in self.dungeon_weighted:
dungeon_weighted_sums[i[0]] += i[0] * i[1]
self.vorpal = max(dungeon_weighted_sums, key = dungeon_weighted_sums.get)
if 3 in self.items:
self.dungeon_weighted = [(i[0], 0.0 if i[0] == self.vorpal else i[1]) for i in self.dungeon_weighted]
def discard_item(self, item, card):
new = copy.copy(self)
new.items = {i for i in new.items if i != item}
if item == 0:
new.monsters_safe = {i for i in new.monsters_safe if i != 7}
elif item == 2:
new.monsters_safe = {i for i in new.monsters_safe if i not in {2, 4, 6}}
if card is not None:
new.deck = list(new.deck)
new.deck.remove(card)
new.update()
return new
def to_dungeon(self, card):
new = copy.copy(self)
if card is None:
new.dungeon_unknown += 1
else:
new.deck = list(new.deck)
new.deck.remove(card)
new.dungeon_known = list(new.dungeon_known)
new.dungeon_known.append(card)
new.update()
return new
def effective_hp(self):
hp = 3.0
if 1 in self.items:
hp += 3.0
if self.dungeon_total > 0:
hp += sum([(i[0] - 1) * i[1] for i in self.dungeon_weighted]) / self.dungeon_total
if 4 in self.items:
hp += 3.0
if 5 in self.items:
hp += 5.0
return hp
def effective_damage(self):
damage = sum([i[0] * i[1] for i in self.dungeon_weighted])
if 0 in self.items:
if self.dungeon_total > 1:
damage -= damage / (self.dungeon_total - 1)
return damage
def __init__(self):
self.stats = self.Stats()
def process_last_turn(self, last_turn):
if last_turn in [0, 1, 2, 3, 4, 5]:
self.stats = self.stats.discard_item(last_turn, None)
elif last_turn == 6:
self.stats = self.stats.to_dungeon(None)
def start_turn(self, last_turn):
self.process_last_turn(last_turn)
if self.stats.effective_hp() > self.stats.effective_damage() + 1.5:
return 1
else:
return 0
def play(self, card):
if 2 in self.stats.items:
self.stats = self.stats.discard_item(2, card)
return 2
else:
self.stats = self.stats.to_dungeon(card)
return 6
def vorpal_choice(self, last_turn):
self.process_last_turn(last_turn)
return self.stats.vorpal
def result(self, bot, result, dungeon, vorped):
self.stats = self.Stats()
```
[Answer]
# DevilWorshipper
My first attempt at a KOTH challenge:
```
from base import BasePlayer
#from random import randint
class DevilWorshipper(BasePlayer):
def reset(self):
self.items = [0, 1, 2, 3, 4, 5]
self.turns = 0
self.demon = False
self.dragon = False
def __init__(self):
self.reset()
def start_turn(self, last_turn):
if last_turn in self.items:
self.items.remove(last_turn)
if last_turn is not None:
#self.demon = True if randint(1, 13 - self.turns) <= 2 else False
self.turns += 1
if (((self.demon == True and not (0 in self.items)) or (self.dragon == True)) and not (3 in self.items)):
return 0
if (len(self.items) <= 1):
return 0
return 1
def play(self, card):
self.turns += 1
if (card == 9):
self.dragon = True
return 6
if (card == 7):
self.demon = True
return 6
for i in [3, 0, 2, 1, 5, 4]:
if (i in self.items):
self.items.remove(i)
return i
return 6
def vorpal_choice(self, last_turn):
return 5 #If it works for others maybe it will work for us
def result(self, bot, result, dungeon, vorped):
self.reset()
```
Essentially, we get rid of the pact and the vorpal dagger, wait for the demon to get into the deck, and pass. Every round the opponent may have drawn the demon, it has the % chance that the last card the opponent drew was a demon to just assume they played the demon already.
Let me know if there's anything I did wrong; I haven't messed with python in a while, this is my first KOTH, and it's 2 am, so there's bound to be something.
**EDITS:**
Taking out the randomness turns out to help it a lot. With the randomness in it is very dumb. Also, as said in the comments below, it tries to summon the demon or dragon.
# Steve
```
from base import BasePlayer
from random import choice
class Steve(BasePlayer):
def reset(self):
self.items = [0, 1, 2, 3, 4, 5]
self.turns = 0
self.dungeon = []
self.possibledungeon = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 9]
self.lastDied = 0
def __init__(self):
self.TRIALS = 10 #How many dungeon runs to do each turn
self.PASS = 8 #How many dungeon runs have to have died to pass
self.SMASHITEMS = 4 #If less dungeon runs died, smash items.
self.reset()
def start_turn(self, last_turn):
if (last_turn is not None):
self.turns += 1
if (last_turn in self.items):
self.items.remove(last_turn)
else:
self.dungeon.append(-1)
#Check if the dungeon is lethal
died = 0
total_hp = 3
if (5 in self.items):
total_hp += 5
if (3 in self.items):
total_hp += 3
vorpal = self.vorpal_choice(None)
for i in range(self.TRIALS):
hp = total_hp
temppossible = self.possibledungeon.copy()
usedpotion = False
killedDemon = False
#Going for a crawl
for j in self.dungeon[::-1]:
if (killedDemon == True): #If last round we killed the Demon
killedDemon = False
j = 0
if (j == -1): #If we don't know what this card is
j = choice(temppossible)
temppossible.remove(j)
if (j == 7 and 0 in self.items): #If we kill demon with the pact
j = 0
killedDemon = True
if (j % 2 == 0 and 2 in self.items) or (j == vorpal): #If we vorpal or grail
j = 0
hp -= j
if (hp <= 0):
if (not usedpotion and 1 in self.items):
hp = 3
usedpotion = True
else:
died += 1
break
if (died >= self.PASS):
return 0
died = self.lastDied
return 1
def play(self, card):
self.possibledungeon.remove(card)
if (self.lastDied < self.SMASHITEMS):
if (7 in self.dungeon) and (0 in self.items):
self.items.remove(0)
return 0
if ( (9 in self.dungeon) or (5 in self.dungeon) ) and (3 in self.items):
self.items.remove(3)
return 3
for i in [2, 1, 5, 4, 3, 0]:
if (i in self.items):
self.items.remove(i)
return i
self.dungeon.append(card)
return 6
def vorpal_choice(self, last_turn):
if (last_turn is not None):
self.turns += 1
if (last_turn in self.items):
self.items.remove(last_turn)
else:
self.dungeon.append(-1)
if (self.dungeon.count(5) == 2):
return 5
if (9 in self.dungeon):
return 9
if (self.dungeon.count(4) == 2 and not 2 in self.items):
return 4
if (7 in self.dungeon and not 0 in self.items):
return 7
for i in range(6)[::-1]:
if (i+1 in self.dungeon):
return i+1
return 5
def result(self, bot, result, dungeon, vorped):
self.reset()
```
Steve tries to guess whether or not the dungeon is lethal. If he thinks it is, he passes. Other than that, I tried to make him get rid of items smartly. He used to adjust his PASS threshold depending on if he died in the dungeon or the opponent lived, but it ended up making him a lot dumber so I got rid of it.
He still doesn't beat GrailThief on my machine, but at least comes closer.
[Answer]
## SlapAndFlap
First time in KOTH, so slap me hard for mistakes.
This one simpleton is always trying to remove all good items with low-strength monsters, while keep powerful ones and then just forces opponent to play.
It beats RunAway and DumDum at least :D
My other bot in deleted answer for some time, I need to fix him by tommorow
```
from base import BasePlayer
class SlapAndFlap(BasePlayer):
def reset(self):
# Monsters that you pushed in
self.know_monster = list(self.deck)
# Items still in game
self.items_in_game = [True, True, True, True, True, True]
# List of items, sorted by value
self.valuables = [3,1,5,0,2,4]
# Counter
self.cards = 13
def __init__(self):
# Deck
self.deck = (1,1,2,2,3,3,4,4,5,5,6,7,9)
# Indexes of item cards
self.items = (0, 1, 2, 3, 4, 5)
self.reset()
def start_turn(self, last_turn):
if last_turn is not None:
self.cards -= 1
# Sneak peak at items removed by opponent
if last_turn is not None and last_turn < 6:
self.items_in_game[last_turn] = False
self.valuables.remove(last_turn)
# Flap!
if self.cards < 6:
return 0
return 1
def play(self, card):
if card < 6 and any(self.items_in_game):
self.know_monster.remove(card)
to_return = self.valuables[0] # remove the best of the rest
self.valuables = self.valuables[1:]
self.items_in_game[to_return] = False
return to_return
else:
return 6
def vorpal_choice(self, last_turn):
# We can just guess what monster will be there
# But we know ones, we removed
# If we have pact, no need to remove demon
if self.items_in_game[0]:
self.know_monster.remove(7)
# If we have grail, no need to remove even monsters (kinda)
if self.items_in_game[2]:
self.know_monster = [i for i in self.know_monster if i%2]
# Find what threatens us the most, counting its strength multiplied by number
weight = [i * self.know_monster.count(i) for i in self.know_monster]
return weight.index(max(weight)) + 1
def result(self, bot, result, dungeon, vorped):
self.reset() # we live for the thrill, not the result!
```
[Answer]
# RandomMandom
The obligatory random bot. Appropriately, he loses hard to the default bots, which is good, because it means that the game has at least some strategy.
```
from base import BasePlayer
from random import randint
from random import choice
class RandomMandom(BasePlayer):
def __init__(self):
self.items = [0,1,2,3,4,5]
def start_turn(self, last_turn):
if last_turn in self.items:
self.items.remove(last_turn)
if len(self.items) > 0:
return randint(0,1)
return 1
def play(self, card):
if len(self.items) > 0:
if randint(0,1) == 1:
selection = choice(self.items)
self.items.remove(selection)
return selection
return 6
def vorpal_choice(self, last_turn):
return choice([1,2,3,4,5,6,7,9])
def result(self, bot, result, dungeon, vorped):
# Never learns
pass
```
[Answer]
# DareDevilDumDum
kinda clear. never backs down. the only way you can (consistently; RunAway loses sometimes but it still beats this most of the time) lose to this bot is if you don't remove any items or are a super coward. think of this bot as a reminder to remove items, otherwise even this can win.
```
from base import BasePlayer
class DareDevilDumDum(BasePlayer):
def start_turn(self, last_turn):
return 1 # damn squiggles. Draw a card
def play(self, card):
return 6+card*0 # put the card in the dungeon, and use card to avoid squiggles :P
def vorpal_choice(self, last_turn):
return 9+last_turn*0 # dragon
def result(self, bot, result, dungeon, vorped):
pass # we live for the thrill, not the result!
```
And
# RunAway
pretty much they remove armour and then run away some time before the end. as daredevildumdum, it doesn't remember anything, except for the number of cards in the deck (which tbh wouldn't be remembered in the actual game (you'd just check)) and whether someone removed the armour (mostly same as before).
```
from base import BasePlayer
class RunAway(BasePlayer):
def __init__(self):
self.cards = 13
self.armoured = True
def start_turn(self, last_turn):
if last_turn is not None:
self.cards -= 1 # opponents play
if last_turn is 5:
self.armoured = False
if self.cards < 4:
return 0 * last_turn # avoid the ---noid--- squiggles
else:
return 1
def play(self, card):
if self.cards > 11 and self.armoured: # if it is the first turn and armour has not been removed
choice = 5 # remove armour
else:
choice = 6 # put the card in the dungeon
self.cards -= 1 # this play
return choice
def vorpal_choice(self, last_turn):
return 5 # without using more memory, this is the best choice statistically
def result(self, bot, result, dungeon, vorped):
self.cards = 13
self.armoured = True
```
Also because I am special challenge poster, these bots do not count toward my bot count, because they are example bots that are dumb
[Answer]
# BoringPlayer
The opposite of RandomMandom, BoringPlayer always makes the same choices. The problem is that it appears that it is too successful for such a simple bot. It scores 3800+ in my local test.
```
from base import BasePlayer
class BoringPlayer(BasePlayer):
def start_turn(self, last_turn):
return 1
def play(self, card):
return 6
def vorpal_choice(self, last_turn):
return 5
def result(self, bot, result, dungeon, vorped):
# Never learns
pass
```
] |
[Question]
[
Here's the phonetic alphabet:
```
Alfa
Bravo
Charlie
Delta
Echo
Foxtrot
Golf
Hotel
India
Juliett
Kilo
Lima
Mike
November
Oscar
Papa
Quebec
Romeo
Sierra
Tango
Uniform
Victor
Whiskey
X-ray
Yankee
Zulu
```
In the fewest bytes possible:
1. Input will be these words in a random order, with the first letters removed.
2. Your goal is to arrange the words back to their original order using *only the letters you now have*. In other words: work out how '[A]lfa' comes before '[B]ravo', and so on. Your code must not refer the original list, index keys, etc.
3. Restore the original first letters of each word.
# Rules
* The hyphen in *X-ray* is probably evil, but needs to stay, for I am also evil.
* The result can be a string (comma or newline separated, for example), or an array.
* The spellings and letter cases are non-negotiable.
* No need to show example output in answers.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
“ṣȤW¶¬þḷẒ⁶4ẹ’Œ?ịṢØA;"
```
Input and output are string arrays.
[Try it online!](https://tio.run/nexus/jelly#PYuhTsRAFEX9/YoJekHhEIRvQBDk6/BKH53O20ynC3WLQuBWQYICJJIsdDdBbEPCb0x/pFuFOOIk54zD8iV1b3/vF7v17qP/Sd9fabMa7tfHadMNy@ff1WnaPqbutX86OzkY0/azf7g0UzV95nzuJBr1xvOtE8/1zFhyzsSCzeTlzNyoeJO1/8HROJIvmSEl4zBQi4KCE4YuuMo4QJyC/LXCS66hglQEmhMKqUtuITZqgFascDlB72LQiIYztmhcMyEcIzSyg7ocgRYK4RAI7CLBForaUoC/EtoD "Jelly – TIO Nexus")
### Background
While there are **26! = 403291461126605635584000000** different inputs, we can sort the input so we have to deal only with one permutation of this phonetic alphabet. Sorting lexicographically, we get
```
-ray
ango
ankee
apa
cho
elta
harlie
hiskey
ictor
ierra
ike
ilo
ima
lfa
ndia
niform
olf
omeo
otel
ovember
oxtrot
ravo
scar
uebec
uliett
ulu
```
We can simply index into this array to sort it by the removed letters. The (1-based) indices are
```
14 22 7 6 5 21 17 19 15 25 12 13 11 20 23 4 24 18 10 2 16 9 8 1 3 26
```
All that's left to do is to prepend the uppercase letters of the alphabet to the strings in the result.
### How it works
```
“ṣȤW¶¬þḷẒ⁶4ẹ’Œ?ịṢØA;" Main link. Argument: A (string array)
“ṣȤW¶¬þḷẒ⁶4ẹ’ Replace the characters by their indices in Jelly's code page
and convert the result from bijective base 250 to integer.
This yields k := 214215675539094608445950965.
Œ? Construct the k-th permutation (sorted lexicographically)
of [1, ..., n], with minimal n (26 here). This yields
[14, 22, 7, 6, 5, 21, 17, 19, 15, 25, 12, 13, 11,
20, 23, 4, 24, 18, 10, 2, 16, 9, 8, 1, 3, 26].
Ṣ Yield A, sorted.
ị For each j in the array to the left, select the j-th string
from the array to the right.
ØA Yield "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
;" Concatenate zipwith; prepend the j-th character from the
alphabet to the j-th string of the permuted input.
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~76~~ 71 bytes
```
lambda x,S=sorted:S(map(str.__add__,'XTYPEDCWVSMKLAIUGRHNFBOQJZ',S(x)))
```
[Try it online!](https://tio.run/nexus/python3#JY3ZboUwDER/hbcEifYDKt2H7vtK29tVyBCnWGRBJiD69beK@3RGM@OxLTbF186Bbw0Ua1VvpsgJzUGtPYx6SrzfNGBM01Tq7fn94fTkePta317fHF6@nD9d3J0d3T9efaiq1mtZlruRKSRtNS7gNIVxTrrM/qeCMCCqqlA0CPYYfjN7YEfixAV9iywdFzMg/AgD2cheAg8SjIKepgFlhboU5TJ6lBNnpRHXxDFlNWOLnQg3/4MwSRITOqGzGQyLLBAyywa6JOx68acO5FMwBOr7Dw "Python 3 – TIO Nexus")
[Answer]
# JavaScript, 169/195 bytes
If replacing the first letter can be done prior to sorting **169 bytes**
```
x=>x.map(k=>{for(i=0;i<26;)if(!k.indexOf("l,r,ha,e,c,ox,ol,ot,nd,uli,il,im,ik,ov,s,ap,ue,o,ie,ang,n,i,h,-,a,u".split`,`[i++]))return String.fromCharCode(i+64)+k}).sort()
```
[Try it online!](https://tio.run/nexus/javascript-node#ZZJPj9MwEMXv/RQmJ5tOswtCe6CkElquCCQOHJaV6qbjZohjR7bTP1rtZy@TNClU5JTMvHl5Y/9McT4Wq2Pe6FbWxerF@CCpuF/Sp/cPS0VGvqlzcls8fjMysxCg0oBQgj@Ct@ATuC10loAsUANUg99DBN1Ch@CBELTbgQOCChagocvy2FpKa1g/0Xz@rFTA1AUnfqRAbpeb4JvHSodHv0VJ84cPal6/qjz6kKQ6m86VibwTseqMsSh1CPqkxMtM8GMxidJ3LmEQhRhauUW3S9VyNgju7sTPiiyKVGFAVqBAiw26FAW5vnqZGsSHQSknw5W4n/4zWn2nshZaBO22vhHDGV3bfZShwkG@6lTlxno@2OH1MiCVeDulVWO@0fgLlgF1xOsym5N4dxWMxcXiduiz24p40O2whdUxTauJA6VKULrJlrBppzN6Gh2fl1fJbf0qHDb6T3apsqg3vTRfL9HGqx1ky9nrrPQueou59TuZkWu79PGXy0C2xXSfmTUagt57xixYpgdt0lBWnnlLgWnz1jB0aBk70j14mBKzx6Q1mulj5vbYbDBALHVgDFmDG2RcG@xp5CQ9kB4cMejMa5k8I02xxhMsOCZ3a0Q2/gdUpfLfntx6tlY3K9x@Zb5L00ZGtn9nzn8A)
If sorting must be done prior to adding the first letter **195 bytes**
```
x=>x.sort((a,b)=>g(a)-g(b)).map(a=>String.fromCharCode(g(a)+64)+a)
g=k=>{for(i=0;i<26;)if(!k.indexOf("l,r,ha,e,c,ox,ol,ot,nd,uli,il,im,ik,ov,s,ap,ue,o,ie,ang,n,i,h,-,a,u".split`,`[i++]))return i}
```
[Try it online!](https://tio.run/nexus/javascript-node#ZZNNj5swEIbv/AqXk91M2G1V7aEpkarttWqlHnrYrhSHjGGKsZEx@dBqf3s6EEgblRPMvDN@Z/xg8vMxXx@zzocopYatytel1GpZyq1SWaNbqfP1jxjIlZkJvnmsdHj0O5SDavHwQS20Ssq8ztcvxgdJ@f2KPr1/WCky8k2dkdvh8ZuRqYUAlQaEAvwRvAUfwe2gtwRkgRqgGvweOtAt9AgeCEG7EhwQVLAEDX2ada2luIHNEy0Wz0oFjH1wgl7PpndFJO9EV/XGWJQ6BH1S4iUR/FiMovC9ixhELsZUZtGVsVolo@DuTvysyKKIFQZkBQq02KCLnSA3RC9Vo/gwKuXccC3u53OmVt@pqIUWQbudb8S4gWt6sDJG2MhXHavMWM9rG18vBVKJt7NbNfmbGn/BIqDu8DrM9iTeXQVTcLm8LfrsdqI76HacwuouzqOJA8VKULzxFrFp5x09TR2fV1fJbfwqHCf6T3aJsmhoekm@XqxNFzfKVslrUnjXeYuZ9aVMybV9/PjLpSDbfL7P1BoNQe890xMDs@OtYYTQMkSkB4wwRiaJuWk0s8QE7bHZYoCu0IGhYg1ukeFrcGCLTx7w8uCIsWX6iugZUOpqPMGSbXG2RuTG/2DHP8RvT26TbNSN5duv1PdxnsDI9m/N@Q8)
A full 20 bytes of each of these programs is just String.fromCharCode() to regain the character...
Another 69 bytes is the string which uniquely identifies the start of each of the words in the phonetic alphabet.
## Explanation of first example
`for(i=0;i<26;)if(!k.indexOf("l,r,ha,e,c,ox,ol,ot,nd,uli,il,im,ik,ov,s,ap,ue,o,ie,ang,n,i,h,-,a,u".split`,`[i++]))return i`
The string hardcoded here is separated into a list of the unique identifying characters that start the phonetic alphabet words after the first character is removed.
```
return String.fromCharCode(i+64)+k
```
This information is used to find the index where the string falls in the alphabet in order to put the starting character back on.
```
.sort()
```
JavaScript implicitly sorts as strings by the ASCII values of the characters
## Explanation of the second example
The function g=k=>... finds the index for which the string should fall in the phonetic alphabet.
```
.sort((a,b)=>g(a)-g(b))
```
Sorts the strings by the numbers returned by performing g(...)
```
.map(a=>String.fromCharCode(g(a)+64)+a)
```
Replaces the first character of each of the phonetic alphabet strings
[Answer]
# [PHP](https://php.net/), 94 bytes
```
<?for(sort($_GET);$i<26;sort($r))$r[]=XTYPEDCWVSMKLAIUGRHNFBOQJZ[$i].$_GET[+$i++];print_r($r);
```
[Try it online!](https://tio.run/##NY/LTsMwEEX3/Ywoi0ahLFiwSSvEo5Q3FMoziirXjPEoTmxNnIp@OOvgMWLjuT4zZyw77YbpkdNulK4X89WsTIwSyV5CYmtD0YIMQghgPGOpmdpvT9ZzMIpPDyaU9hN5pA@C5yYansWGIda8xG6h2QCF1EnBRbhowAYktxuIBhAxFu0XX1tUlhrm0luWNHY17EKYkNjFuRogPtwnVTHqdK@UgXH8T1YMwR53lvw/SHF6cFj8EcqylMpq9rZ6f5ifnb6@PN1e3xxfPi8eL@7OT@6XVx9litV@NMs8xTyvCkfY@jWxXAzDT2snUkgNvw "PHP – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~29~~ 27 bytes
```
.•C5ê™вrΓ˜3åóMîõxÿ•uS|{)øJ{
```
[Try it online!](https://tio.run/##DcoxTgJREAbg/r@JBYnEwAEsCZ0J/ew66072vR0yvCUSKKiISmMjJTFaWJJQUVE41B5iL7JSfN13O6Csz13Xrr/al7fLxnft66e/@4dvox98P/n99sP47@hn/7meu@H9w2p546fRsuuorpghFaNntEBJFoShc44ZGyQoqH5S1FKoRUgk0JRQyqziBSRPatDIilAQ9DmZJjSccY4mNFfCKUETB2goYDRXCJsROCRCXipmORnqR6F/ "05AB1E – Try It Online")
```
.•C5ê™вrΓ˜3åóMîõxÿ•uS # Push exploded XTYPEDCWVSMKLAIUGRHNFBOQJZ.
|{) # Push input in array, sorted.
øJ{ # Zip together, join, resort.
```
-2 thanks to Emigna's magical `.•`.
[Answer]
# Java 7, 169 bytes
```
import java.util.*;List c(List l){Collections.sort(l);int i=0;for(Object s:l)l.set(i,""+"XTYPEDCWVSMKLAIUGRHNFBOQJZ".charAt(i)+l.get(i++));Collections.sort(l);return l;}
```
[Try it here.](https://tio.run/nexus/java-openjdk#fVFNbxoxEL3zK0Y@rbvU6plVDiSBfoXSQtr0Qz0Yx8CEWRvZs6QI8dup7T1Ular68p7nzZsnj7Hd@8DwpA9adYykXjSDgSEdI8zgdLnDyGCqAiRPN57IGkbvoorJV5Fs0DHg1atm7UM1Xz0lGeKIJKloucKhELX4ev/t4@T25uHLcvb@bvz28@vFmw/T6/mnd9@FMlsdxqlR1qQ22VHXUjb/CgqWu@CAmvMFYN@tCA1E1pzg4PERWo2uWqPTBEsO6DY/foKWcBpAOn29fwdcwTgEfYxKx1ypBJIXQxCeLWXUbmdtKbS2F35x8JwZtjpD0IdeoHWGzq6syWSLcWePYlgy8xG4K5PMtvSjTcGZvEz5JWpfrrTWffCmH3uw7cqGTC1xkdwjFuyoyxCNLrLDtPf2r0DDvkhpsYS296BlFrIpXctjZNsq37HapzUxuUpcT6bzxWQEAur0z32fs88wq6QyFf3HOZ7eTxajP77z4Hz5DQ)
**Explanation:**
```
import java.util.*; // Import used for List and Collections
void c(List l){ // Method with list parameter and no return-type
Collections.sort(l); // Sort the given list
int i=0; for(Object s:l) // Loop over the Strings in the list
l.set(i,""+ // Replace the String-item in the list with:
+"XTYPEDCWVSMKLAIUGRHNFBOQJZ".charAt(i) // The leading capital character
+l.get(i++); // Followed by itself
// End of loop (implicit / single-line body)
} // End of method
```
] |
[Question]
[
## Introduction and Credit
Imagine you're [Amazon](https://en.wikipedia.org/wiki/Amazon.com). Imagine you have a large number of products for which a lot of people have written reviews scoring 1-5 stars. Now you need to give your customers a summary for each product based on the simple product-scoring association. Because you're Amazon, time is money and as such you need to fit this into the smallest code possible because that's the code you can write the fastest.
Credit: This task appeared in 2014 in a programming mid-term exam in the functional programming course at my university and since then an example solution has been provided. I have the lecturer's and author's (same person) permission to post this question publicly.
---
## Input
Your input will be a list of pairs of natural numbers, where the second value of each pair is always either 1, 2, 3, 4 or 5. Take the input [using your preferred, generally accepted way](https://codegolf.meta.stackexchange.com/q/2447/55329).
## Output
Your output will be a list of pairs of a number and a list of 5 numbers. Give the output [using your preferred, generally accepted way](https://codegolf.meta.stackexchange.com/q/2447/55329).
## What to do?
Given the (unsorted) list of product-id and scoring pairs, count for each product how often each score appears and return the amounts in the second list of the output pair at the appropriate position.
So for product #5 with 10x 1-star, 15x 2-star, 25x 3-star, 50x 4-star and 150x 5-star would result in the entry `[5 [10 15 25 50 150]]`.
## Potential Corner Cases
The input list may be empty in which case your output should be as well.
You don't need to consider the case where the input violates the above constraints.
You can safely assume all numbers to be representable by a signed 32-bit integer.
If you have no review(s) for a product (ie it doesn't appear in the output) it must not appear in the output either, i.e. 5x zeroes doesn't happen and can always be dropped.
## Who wins?
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins. Built-ins are allowed and [standard rules apply](https://codegolf.meta.stackexchange.com/q/1061/55329).
---
## Examples
Example input:
```
[(1,4),(2,5),(1,5),(1,1),(1,5),(1,4)]
```
Example corresponding output:
```
[
(1,[1, 0, 0, 2, 2]),
(2,[0, 0, 0, 0, 1])
]
```
Other test vectors:
```
[] -> []
[(1,1),(2,2),(3,3),(4,4),(5,5)] ->
[(1, [1,0,0,0,0]),(2, [0,1,0,0,0]),(3, [0,0,1,0,0]),(4, [0,0,0,1,0]),(5, [0,0,0,0,1])]
```
[Answer]
## R, 64 bytes
```
function(m)`if`(length(m)>1,by(m[,2],m[,1],tabulate,n=5),list())
```
This solution works if the I/O is somewhat flexible. It's an unnamed function that works by taking an R-matrix as input and tabulates the frequency of each type of review. The only problem is dealing with the empty list. We need to introduce a control whether this is actually the case and because an empty matrix `matrix()` is not actually empty, we return an empty `list()` instead.
[Try it on R-fiddle](http://www.r-fiddle.org/#/fiddle?id=XU3ppaVh&version=1)
**Example output for the last test case:**
```
m[, 1]: 1
[1] 1 0 0 0 0
---------------------------------------------------------------------------------------------
m[, 1]: 2
[1] 0 1 0 0 0
---------------------------------------------------------------------------------------------
m[, 1]: 3
[1] 0 0 1 0 0
---------------------------------------------------------------------------------------------
m[, 1]: 4
[1] 0 0 0 1 0
---------------------------------------------------------------------------------------------
m[, 1]: 5
[1] 0 0 0 0 1
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 8 bytes
```
5B#uilZ?
```
Input format is a column array of products followed by a column array of scores:
```
[1; 2; 1; 1; 1; 1]
[4; 5; 5; 1; 5; 4]
```
Output format is a vertical array of products followed by a matrix of score occurrences:
```
1
2
1 0 0 2 2
0 0 0 0 1
```
[Try it online!](http://matl.tryitonline.net/#code=NUIjdWlsWj8&input=WzE7IDI7IDE7IDE7IDE7IDFdCls0OyA1OyA1OyAxOyA1OyA0XQ)
### Explanation
```
5B#u % Implicitly input array of products. Push unique values and integer labels
% of the input entries. So input [1; 3; 1; 1; 1] would give outputs [1; 3]
% and [1; 2; 1; 1; 1]. The latter is lik the input but without "holes", i.e.
% uses consecutive integers. This is required to avoid rows of zeros in the
% result for non-existing intermediate products
i % Input array of scores
l % Push 1
Z? % Build sparse matrix with those row indices, column indices, and value 1.
% Implicitly display
```
[Answer]
# Python 2 - ~~88~~ ~~72~~ ~~71~~ ~~69~~ 67 bytes
```
def s(l,d={}):
for p,s in l:d.setdefault(p,[0]*5)[s-1]+=1
print d
```
```
Input to the function:
[(1,4),(2,5),(1,5),(1,1),(1,5),(1,4)]
Output:
{1: [1, 0, 0, 2, 2], 2: [0, 0, 0, 0, 1]}
```
**Edits:**
* Thanks to [nedla2004](https://codegolf.stackexchange.com/users/59363/nedla2004) for saving 16 bytes!
* Changed to Python 2 to save 1 byte :D
* Saved 3 bytes by taking newline byte count as 1 byte.
* Thanks [flp-tkc](https://codegolf.stackexchange.com/users/60919/flp-tkc) for saving 2 bytes. (There was an unnecessary extra space too :D)
Golfing suggestions are welcome :)
[Answer]
# Mathematica, 68 bytes
```
{#[[1,1]],Last/@Tally@Join[Range@5,#2&@@@#]-1}&/@GatherBy[#,#&@@#&]&
```
Unnamed function taking as input a list of ordered pairs of integers such as `{{1, 4}, {2, 5}, {1, 5}, {1, 1}, {1, 5}, {1, 4}}`. To start, `GatherBy[#,#&@@#&]` groups together all the pairs with the same first element (which can be any identifier, actually, not just an integer).
Each of those groups is then operated on by the function `{#[[1,1]],Last/@Tally@Join[Range@5,#2&@@@#]-1}`, which produces a two-element list as output, the first element of which is just the common identifier. `Join[Range@5,#2&@@@#]` generates a list of integers starting with `1,2,3,4,5` and ending with all of the scores corresponding to the given identifier. `Last/@Tally` then computes how many time each score was found, returning the appropriate 5-tuple; then `-1` makes up for the fact that we introduced each score one extra time, leaving zeros for any missing score (which otherwise would be skipped completely).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Fm2QṢµ5,@þċ@€€³ż@
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=Rm0yUeG5osK1NSxAw77Ei0DigqzigqzCs8W8QA&input=&args=W1sxLDRdLFsyLDVdLFsxLDVdLFsxLDFdLFsxLDVdLFsxLDRdXQ)**
### How?
```
Fm2QṢµ5,@þċ@€€³ż@ - Main link: List of (id, score) pairs
F - flatten
m2 - mod 2 of list (gets the IDs)
Q - unique items by first appearance (one of each ID)
Ṣ - sorted (IDs in order)
µ - monadic chain separation (call the above z)
þ - table the result of
,@ - pair z (with reversed @rguments) with
5 - 5 (implicit range, so [1,2,3,4,5]) ...we now have:
- [[id,1],[id,2],[id,3],[id,4],[id,5]] for every id, in order.
ċ@€€ - count occurrences of (with reversed @rguments) for €ach for €ach in
³ - the first input (the list of (id, score) pairs)
ż@ - zip (with reversed @rguments) with z
```
[Answer]
## JavaScript (ES6), 58 bytes
Returns an object whose keys are the product IDs, associated to a list of review scores.
```
a=>a.map(([i,n])=>(o[i]=o[i]||[0,0,0,0,0])[n-1]++,o={})&&o
```
### Test cases
```
let f =
a=>a.map(([i,n])=>(o[i]=o[i]||[0,0,0,0,0])[n-1]++,o={})&&o
console.log(JSON.stringify(f([])));
console.log(JSON.stringify(f([[1,4],[2,5],[1,5],[1,1],[1,5],[1,4]])));
console.log(JSON.stringify(f([[1,1],[2,2],[3,3],[4,4],[5,5]])));
```
[Answer]
# [Lua](https://www.lua.org/), 114 112 103 bytes
```
function(t,o)for i=1,#t do v=t[i]n,r=v[1],v[2]o[n]=o[n]or{n,{0,0,0,0,0}}o[n][2][r]=o[n][2][r]+1 end end
```
[Try it online!](https://tio.run/##hVBNT4QwED3TXzHBgxC7G4HdIzEe/Q3IAdnKNrJT7AeJIf3tOAV29WBi2r5M573X6Uzvmnm3g2djZIdgzwIaVPh1Uc7Au8PWSoVwFlpA8gKdE8aQSBqg3Yuu6cFIbAVICyclDN5b0OLTSdJr0TptyP6UshZKmK/PJZar9F1pkGXG74IRxtJWskauy7HKaj5Wea0qrMsASk/Ip0e@Le9DkgSVXvk1fMhA4CmcWeLgbEYVpynjB8@nnB8Jsw2zX/HBe7bI8yDf4mKzZos1Jyx4QXhYHjuS1TOmnCXp6mK3QZ3cZUhsyqJBS7RJPMUpY1Ho9YOPIBHk0EhtSEJds@hHBvs9WGUs3bskzCANmZjDRjVvvdi3CtvGJmE6nLh41XhPRSJqnN3K@lek3JJqk3UcHNYfp2z54/Vy5fN/@OJvfv4G "Lua – Try It Online")
### Explanation
```
function(t,o) -- Anonymous function taking a table and the output table
for i=1,#t do -- For every number from 1 to the length of t
v = t[i] -- Get the current entree
n, r = v[1], v[2] -- Item Number and Rating
o[n] = o[n] or {n,{0,0,0,0,0}} -- Make sure the item exists in the output
o[n][2][r] = o[n][2][r] + 1 -- Add 1 to that rating
end
-- Tables are always passed by reference, so no need to return
end
```
[Answer]
**Clojure, 79 bytes**
```
(fn[c](reduce(fn[r[i v]](update r i #(update(or %[0 0 0 0 0])(dec v)inc))){}c))
```
Must called with a sequence of vectors so that item id and ratinv value are correctly mapped to function arguments. Returns a hash-map of vectors.
```
(def f (fn[c]( ... )))
(f [[1 4] [2 5] [1 5] [1 1] [1 5] [1 4]])
{1 [1 0 0 2 2], 2 [0 0 0 0 1]}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 18 bytes
```
m§,o←←oλm#⁰ḣ5)m→k←
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8X/uoeU6@Y/aJgBR/rnducqPGjc83LHYVDP3UdukbKDg////o6M1DHVMNHU0jHRMgaQhlDREYptoxupEAxFU2EjHCEga6xgDSROwVlOgwthYAA "Husk – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~37~~ 35 bytes
```
Merge[Rule@@@#,#~BinCounts~{1,6}&]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73ze1KD01Oqg0J9XBwUFZR7nOKTPPOb80r6S4rtpQx6xWLVbtf0BRZl5JtLKuXZqDcqxaXXByYl5dNVc1UN6kVqfaSMcUSBpCSUMktkltrQ5XNQhDJYx0jICksY4xkDQBazYFKq3lqv0PAA "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
Your task is to determine the palindromic degree of a given non-empty string.
To do this, loop until one of the following conditions are met:
* The string is not a palindrome.
* You encounter a string that has already been encountered.
And do the following:
* If it is a palindrome, add one to the degree.
* Depalindromize.
For example, if I had the string `babababab`, the calculation would go:
```
babababab 1
babab 2
bab 3
ba
```
For the string `zzzzz`, it would go:
```
zzzzz 1
zzz 2
zz 3
z 4
z
```
### Test cases
```
abc 0
cenea 0
pappap 2
aa 2
aba 1
aaa 3
cccc 3
zzzzz 4
```
Explanation:
```
abc : 0
cenea : 0
pappap -> pap -> pa : 2
aa -> a -> a : 2
aba -> ab : 1
aaa -> aa -> a -> a: 3
cccc -> cc -> c -> c: 3
zzzzz -> zzz -> zz -> z -> z : 4
```
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes wins.
[Answer]
## Perl, 53 bytes
52 bytes of code + 1 byte for `-p`.
```
$\++while s/^((.+).?)(??{reverse$2})$/$1/||s/^.$//}{
```
To run it :
```
perl -pE '$\++while s/^((.+).?)(??{reverse$2})$/$1/||s/^.$//}{' <<< "zzzzz"
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 9 bytes
```
ŒHḢ$ƬUƑƤS
```
[Try it online!](https://tio.run/##y0rNyan8///oJI@HOxapHFsTemzisSXB/x/u2ATkH24/OunhzhlcD3dvOdz@qGlN5P//SYlQqGDMlZiUrGDAlZyal5oIpAsSC4BIwYgrMRFEJCUqGAKZiUB1yUAApKpAQMEEAA "Jelly – Try It Online")
-2 bytes thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)!
## How it works
```
ŒHḢ$ƬUƑƤS - Main link. Takes a string S on the left
$Ƭ - Until reaching a previously encountered string:
ŒH - Split into halves
Ḣ - Take the first one
Ƥ - Over each prefix:
U - Reverse each string in the prefix
Ƒ - Does that equal the prefix?
S - Sum
```
[Answer]
# JavaScript (ES6), 85 bytes
```
f=s=>s[1]?(t=s.slice(0,l=-~s.length/2))==[...s.slice(-l)].reverse().join``?1+f(t):0:1
```
[Answer]
# Haskell, 58 bytes
```
p[a]=1
p a|reverse a==a=1+p(take(div(1+length a)2)a)
p _=0
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 14 bytes
```
[ÐÂÊ#¼g#2ä¬])\
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=W8OQw4LDiiPCvGcjMsOkwqxdKVw&input=enp6eno)
[Answer]
# Scala, 56 bytes
```
s=>if(s.reverse==s&&s.size>1)1+h(s.take(s.size/2))else 2
```
requires an assignmentt to a variable with type declaration:
`val f:(String=>Int)=...`
[Answer]
# Pyth - 21 bytes
The case of palindromes never running out really cost me, will look for a better way.
```
.xxK.uhc2NQ)hf!_ITKlK
```
[Test Suite](http://pyth.herokuapp.com/?code=.xxK.uhc2NQ%29hf%21_ITKlK&test_suite=1&test_suite_input=%22babababab%22%0A%27abc%27%0A%27cenea%27%0A%27pappap%27%0A%27aa%27%0A%27aba%27%0A%27aaa%27%0A%27cccc%27%0A%27zzzzz%27&debug=0).
[Answer]
# Java 7,147 bytes
```
int c(String s,int t){int l=s.length();return l<2?t+1:s.equals(new StringBuilder(s).reverse().toString())?c(s.substring(0,l%2>0?l/2+1:l/2),++t):t;}
```
[Answer]
# Python 2, ~~94~~ ~~87~~ 77 bytes
The recursive approach... this currently assumes that empty & single letter strings get a score of 1.
```
def P(x,c=0):a=len(x);return c+(a<2)if(x[::-1]!=x)+(a<2)else P(x[:-~a/2],-~c)
```
[**Try it online!**](https://repl.it/EONR/6)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 17 bytes
```
a!_IQl.u?_IJhc2NJ
```
[Test suite](http://pythtemp.herokuapp.com/?code=a%21_IQl.u%3F_IJhc2NJ&test_suite=1&test_suite_input=%22abc%22%0A%22cenea%22%0A%22pappap%22%0A%22aa%22%0A%22aba%22%0A%22aaa%22%0A%22cccc%22%0A%22zzzzz%22&debug=0)
The previous Pyth answer uses an older version of the language and a significantly different approach.
##### Explanation:
```
a!_IQl.u?_IJhc2NJ | Full program
a!_IQl.u?_IJhc2NJNQ | with implicit variables filled
--------------------+-------------------------------------------------------------------------------------------------------------------------
.u Q | Repeat the following until a repeated value is found, collecting the intermediate results, with N starting as Q (input):
Jhc2N | J = the first half of N (longer half is necessary)
?_I JN | if J is invariant over reversal (i.e. is a palindrome), N = J, else N = N
l | take the length of the resulting list
a | subtract
!_IQ | 0 if Q is a palindrome, 1 otherwise
```
[Answer]
# [Python 3](https://docs.python.org/3/), 53 bytes
```
f=lambda x:2>>len(x)or-~f(x[len(x)//2:])*(x==x[::-1])
```
[Try it online!](https://tio.run/##NUy7DoMwDNzzFR6TqpRXp0jhRxCDCUZFSkMEqZR26K@nAcrJ8tl3Z7u3f8y2jnFUBp/9gBBk1TSGLA9iXrLvyEN7bHleyU5ceFAqtFJmZSfiOC9gJkswWZhdihVCMvC0@itQcKQ9DaD2yG11ZvJcMFhofRmf5JFvyaS4ZbKeH2d/9xyU2qzzlxARoWTYayiYJkuY2KFLBRVD3Fq/J9JcM52Q6LMB7j8 "Python 3 – Try It Online")
## How it works:
* `2>>len(x)` will give us `1` if `len(x)==1` and `0` if `len(x)>1` (we don't have to treat the case where `x` is the empty string)
* if the previous gives `0` then we recurse with `x[len(x)//2:]` which is the second part of our palindrome (including the center), `-~` we add `1` and multiply by `(x==x[::-1])` to return `0` if it is not a palidrome
] |
[Question]
[
# The Challenge
GIFs are the most common image format for animation, and are used pretty heavily in today's social media. For the purpose of this challenge, I'm going to redefine what a GIF can be. This challenge will require you to take in a 3D array containing some sort of representation of a 2D 'image' and iterate through them, displaying an animation. This animation can be done anywhere, in a GIF, in your console, in a GUI, etc; the delivery doesn't matter, so long as it is animated.
## The Input
* **A 3D array where the data inside somehow represents a 2D image.**
+ The array may contain RGB data, true/false data or anything else you see fit.
+ I'm also fine with you dumbing it down to a 2D array of strings or something similar, but the animation **must be a 2D animation**.
* **The time between each frame in a format of your choosing (Seconds, Milliseconds, etc...).**
+ *People have been asking me whether or not they HAVE to include the duration length. My answer is "meh", as long as you are able to show animation. I'm more concerned that you adhere to the "Array" parameter than this one, meaning no random animations.*
## The Output
* **A seamlessly iterated sequence of output that looks like a 2D animation with the correct delay on each transition based on the value input.**
# The Rules
* Output can be, but is not limited to:
+ GIF image.
+ GUI animation (my example).
+ In-console animation.
+ Honestly, any "animation" that you see fit, as long as it follows the below rules.
* When outputting your image you must clear the console before showing the next frame, you cannot just print them sequentially.
+ Emulating a console "clear" is also acceptable, as long as it looks like a seamless animation (see the hint under my example for more information on what I mean).
* Regardless of implementation, your animation should loop forever, or until stopped.
+ The "looping" can be as simple as `while(true){}` or infinite recursion, you may assume the user wants to view this masterpiece until they hit "ctrl+c".
* You must be able to handle any size 2D 'images', if your language is limited by buffer sizes, this is acceptable and you may state this in your explanation.
* Standard loopholes are disallowed.
# Example I/O
## Input (3D Array, Delay)
```
f([
[[1,0,0],
[0,0,0],
[0,0,0]],
[[0,0,0],
[0,1,0],
[0,0,0]],
[[0,0,0],
[0,0,0],
[0,0,1]],
], 1)
```
## Output (Example, 2020 Bytes - Java)
```
import javax.swing.JFrame;
import javax.swing.JTextArea;
/**
* Simple GIF class to animate a 3D integer array in a swing text area.
* (Clearing the console in java isn't something you really do, so I chose
* java on purpose to make it an extremely ungolf-able answer that someone
* wouldn't bother to steal).
*/
public class Gif implements Runnable {
/**
* The output area.
*/
private final JTextArea area;
/**
* The list of images.
*/
private final int[][][] images;
/**
* The delay between image transitions.
*/
private final long transitionDelay;
/**
* Main method, instantiates a GIF object and runs it.
* @param args Does absolutely nothing.
*/
public static void main(String[] args) {
final int[][][] images = {{{1,0,0},{0,0,0},{0,0,0}},{{0,0,0},{0,1,0},{0,0,0}},{{0,0,0},{0,0,0},{0,0,1}}};
final long transitionDelay = 1000L;
new Thread(new Gif(images, transitionDelay)).start();
}
/**
* Constructor for a GIF, takes in a 3D array of images and a transition
* delay to wait between transitioning the images.
* @param images The list of images.
* @param delay The delay between each image.
*/
public Gif(int[][][] images, long transitionDelay) {
this.images = images;
this.transitionDelay = transitionDelay;
this.area = new JTextArea();
final JFrame frame = new JFrame("It's a GIF!");
frame.setSize(10,100);
frame.add(area);
frame.setVisible(true);
}
/**
* When run, it will alter the area to imitate an animated GIF.
*/
@Override
public void run() {
while (true) {
for (int i = 0; i < images.length; i++) {
final StringBuffer frame = new StringBuffer();
for (int j = 0; j < images[i].length; j++) {
for (int k = 0; k < images[i][j].length; k++) {
frame.append("" + images[i][j][k]);
}
frame.append("\n");
}
this.area.setText(frame.toString());
try{Thread.sleep(transitionDelay);}catch(Exception e){}
this.area.setText("");
}
}
}
}
```
This results in a swing GUI popping up, animating the array:
[](https://i.stack.imgur.com/9Ylz4.png) [](https://i.stack.imgur.com/abl7b.png) [](https://i.stack.imgur.com/NlQc7.png)
**HINT HINT:** Use a language where console clearing is possible, or specify why what you are doing will end up with a result that looks like an animation in the language you chose. I think some languages have default buffer sizes on their consoles, you may use this to your advantage, but I expect an explanation or example. Just because I output my animation as a string, you don't have to; I could've just as easily used 0 for black and 1 for white and made a real GIF.
## Judging
This is code-golf, lowest byte count wins (inputs excluded).
I'll +1 anyone who uses a language in a cool or unexpected way as well.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~16~~ ~~12~~ 11 bytes
```
`G@)D1Y.XxT
```
Input is a cell array of 2D. For example:
```
{[1 0 0; 0 0 0; 0 0 0] [0 0 0; 0 1 0; 0 0 0] [0 0 0; 0 0 0; 0 0 1]}
```
The pause time is the `1` in the code. It can be changed to any real number, such as `.5` or `.2 .
Try it at [MATL Online!](https://matl.io/?code=%60G%40%29D1Y.XxT&inputs=%7B%5B1+0+0%3B+0+0+0%3B+0+0+0%5D+%5B0+0+0%3B+0+1+0%3B+0+0+0%5D+%5B0+0+0%3B+0+0+0%3B+0+0+1%5D%7D&version=19.1.0) (If it doesn't work, refresh the page and press "Run" again.)
The input can also be a cell array of 2D char arrays. For example:
```
{['x...';'+...';'....';'....'] ['+x..';'....';'....';'....'] ['.+x.';'....';'....';'....'] ['..+x';'....';'....';'....'] ['...+';'...x';'....';'....'] ['....';'...+';'...x';'....'] ['....';'....';'...+';'...x'] ['....';'....';'....';'..x+'] ['....';'....';'....';'.x+.'] ['....';'....';'....';'x+..'] ['....';'....';'x...';'+...'] ['....';'x...';'+...';'....']}
```
[Try this one too!](https://matl.io/?code=%60G%40%29D.2Y.XxT&inputs=%7B%5B%27x...%27%3B%27%2B...%27%3B%27....%27%3B%27....%27%5D+%5B%27%2Bx..%27%3B%27....%27%3B%27....%27%3B%27....%27%5D+%5B%27.%2Bx.%27%3B%27....%27%3B%27....%27%3B%27....%27%5D+%5B%27..%2Bx%27%3B%27....%27%3B%27....%27%3B%27....%27%5D+%5B%27...%2B%27%3B%27...x%27%3B%27....%27%3B%27....%27%5D+%5B%27....%27%3B%27...%2B%27%3B%27...x%27%3B%27....%27%5D+%5B%27....%27%3B%27....%27%3B%27...%2B%27%3B%27...x%27%5D+%5B%27....%27%3B%27....%27%3B%27....%27%3B%27..x%2B%27%5D+%5B%27....%27%3B%27....%27%3B%27....%27%3B%27.x%2B.%27%5D+%5B%27....%27%3B%27....%27%3B%27....%27%3B%27x%2B..%27%5D+%5B%27....%27%3B%27....%27%3B%27x...%27%3B%27%2B...%27%5D+%5B%27....%27%3B%27x...%27%3B%27%2B...%27%3B%27....%27%5D%7D&version=19.1.0)
### Explanation
```
` % Do...while
G % Push input: cell array
@ % Push iteration index
) % Index to obtain that cell. This uses modular indexing,
% so each cell is addressed cyclically
D % Display
1 % Push 1: number of seconds to pause
Y. % Pause for that many seconds
Xx % Clear screen
T % True. This is used as loop condition: infinite loop
% End. Implicitly end do...while loop
```
[Answer]
# Octave, ~~56~~ ~~54~~ 47 bytes
Removed the possibility to input the pausing time as part of the input matrix. I was very satisfied with it, so have a look in the edit history if you want to have a look. This solution is 7 bytes shorter.
```
n=input('');while(any(n=~n))spy(n);pause(1);end
n=input(''); % Takes input as a matrix of zeros and ones
k=n(1); % maximum of the input matrix is the desired pause time. Have to store
% this, because n is soon to be messed with
% NOTE: k=n(1); is not needed anymore, since the pause time can be hardcoded!
any(n=~n) % Check if there are any truthy values in `n` (there is), and at the
% same time negate it, thus creating a matrix where all elements
% alternates between 1 and 0.
while(any(n=~n)) % Loop as long as there are any non-zero elements (always some)
spy(n) % Create a spy-plot where all non-zero elements are shown as a dot
pause(1) % Pauses for k seconds
end % ends the loop (will never happen, since it's infinite).
```
The input will be something like this: `[4 0 0 4;0 4 4 0;4 0 0 0]`, where this will be a matrix of dimensions 3x4, and the desired pause time is 4 seconds.
It displays a plot like the one below, but alternates between showing the true and the false values of the input. So all the blue dots will become white in the next iteration, and all the white will become blue.
In the below plot, I used the input `rand(10,10)>0.6*2`. This means it will have dimensions 10x10, and all elements of the random matrix that are larger than 0.6 will be true. After that I multiply it by the desired pausing time, 2 seconds. I used a random matrix here, but I could have created the matrix manually too.
I don't have Octave installed on this computer, so I made a minor alteration to make this work in MATLAB. It's the exact same principle, but `n=~n` doesn't work in MATLAB.
[](https://i.stack.imgur.com/QOWHb.jpg)
[](https://i.stack.imgur.com/wUXM5.jpg)
[Answer]
# sed 141 134 90
-51 thanks to seshoumara
```
/^$/!{H;d}
:;/^$/g;s,^\n,,;s,$, ,;s,^,\d27[2J,p
:p;P;s,[^\n]*\n,,;/^ \n/!bp;N;s,[ \n]*,,;b
```
Input: First takes each frame separated by a line with a single space then display the next frame after each blank line is received (looks like a flipbook). Minimum 3 frames.
By default on my system (Windows 7) when I open cygwin it have 24 lines vertically. Between frames, there are always at least that many blank lines printed. This effectively clears the screen.
Over 1/3 of the bytes come from clearing the console. I'm sure there's a better way.
[Answer]
## GNU sed, ~~88~~ 84 + 1(n flag) = 85 bytes
**Edit:** 3 bytes less thanks to [Riley](/users/57100/riley)
```
H;1h;${:
g;s:\n.*::;H;x;s:[^\n]*\n::;x;y:,:\n:;s:^:ESC[2J:;s:ESC:\d27:gp;esleep 1
b}
```
The input format is one animation frame per line. For multiple output lines in a frame, use comma as separator. Because I run the program in a Linux console, the maximum image size available (measured in rows and columns) is dependent on the size of the terminal window. The pause between two frames is accomplished by the *sleep* shell command; to get a faster animation call `esleep 0.4` (seconds).
```
100,000,000 # The timer could be read from the input as well, but that
000,010,000 #would require a lot more bytes and I understand I'm allowed
000,000,001 #to hardcode the value.
```
The best part is that I support color animation! To do this, I used the so called [ANSI Escape Sequences](http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/c327.html "ANSI Escape Sequences") to control the text font, foreground and background color, plus the position of the cursor, thus being able to clear the screen before each frame (code `ESC[2J`). To add color information, use the following format in the input, which is better explained [here](http://www.growingwiththeweb.com/2015/05/colours-in-gnome-terminal.html "console colors").
```
ESC[$FORMATm$textESC[0m # 'ESC' is an actual string, it is then replaced
#in sed by the character with the ASCII value 27
```
**Run:**
```
sed -nf animate.sed input.txt
```
**Examples:** for each test, 2 animation cycles were screen-captured and saved in image GIF format (apologies for the low resolution)
0.4 seconds pause [](https://i.stack.imgur.com/DXilb.gif)
1 second by default [](https://i.stack.imgur.com/SBWxy.gif)
**Explanation:**
```
H;1h # read each line/frame and store them in hold space
${: # when the input was read, start a loop
g # copy hold space to pattern space
s:\n.*:: # remove all except the first/current frame
H # append frame to hold space
x;s:[^\n]*\n::;x # delete first frame from hold space
y:,:\n: # replace all commas with a newline
s:^:ESC[2J:;s:ESC:\d27:gp # use an ANSI Escape Sequence to clear the screen
#and print frame in color
esleep 1 # wait 1 second
b} # repeat
```
[Answer]
## Ruby, ~~89~~ 45 bytes
```
f=->h,t{h.cycle{|x|puts"^[[2J",x.map(&:join)}}
```
The `^[` is an escape character.
Hexdump:
```
00000000: 663d 2d3e 682c 747b 682e 6379 636c 657b f=->h,t{h.cycle{
00000010: 7c78 7c70 7574 7322 1b5b 324a 222c 782e |x|puts".[2J",x.
00000020: 6d61 7028 263a 6a6f 696e 297d 7d map(&:join)}}
```
Saved a **lot** of bytes thanks to @Jordan
[Answer]
# Lua([LÖVE](https://love2d.org/)), ~~296~~ 287 bytes
```
c=0;f=1;t=10;l=love
function l.load()loadstring('i='..arg[2])()s=tonumber(arg[3])end
function l.update(d)if c>s then
c=0;f=f==#i and 1 or f+1
end;c=c+d;end
function l.draw()for K,V in pairs(i[f])do
for k,v in pairs(V)do if v>0 then l.graphics.rectangle('fill',k*t,K*t,t,t)end
end
end
end
```
**Usage Example**
```
love main.love '{{{1,0,0},{0,0,0},{0,0,0}},{{0,1,0},{0,0,0},{0,0,0}},{{0,0,1},{0,0,0},{0,0,0}},{{0,0,0},{0,0,1},{0,0,0}},{{0,0,0},{0,0,0},{0,0,1}},{{0,0,0},{0,0,0},{0,1,0}},{{0,0,0},{0,0,0},{1,0,0}},{{0,0,0},{1,0,0},{0,0,0}},{{1,0,0},{1,0,0},{0,0,0}},{{1,1,0},{1,0,0},{0,0,0}},{{1,1,1},{1,0,0},{0,0,0}},{{1,1,1},{1,0,1},{0,0,0}},{{1,1,1},{1,0,1},{0,0,1}},{{1,1,1},{1,0,1},{0,1,1}},{{1,1,1},{1,0,1},{1,1,1}},{{1,1,1},{1,1,1},{1,1,1}},{{0,0,0},{0,0,0},{0,0,0}}}' 1
```
**Output** : <https://youtu.be/0kDhPbbyG9E>
[Answer]
# SmallBasic, 167 bytes
As a parameter, define and set the global var i!
Sadly, SmallBasic does not support parameters for own Sub-routines.
```
sub animate
for j=0 to Array.getItemCount(i)
for k=0 to Array.getItemCount(i[0])
TextWindow.writeLine(i[j][k])
endfor
Program.delay(9)
TextWindow.clear()
endfor
endsub
```
] |
[Question]
[
## Introduction
The International System of Units is a system of measuring all around the world, except for a few countries *including the US*. The SI system (or metric system) is based on powers of ten, listed below (note that this is an incomplete table):
```
femto(f) pico(p) nano(n) micro(μ) milli(m) centi(c) (base unit) hecto(h) kilo(k) mega(M) giga(G) tera(T) peta(P)
10^-15 10^-12 10^-9 10^-6 10^-3 10^-2 10^0 10^2 10^3 10^6 10^9 10^12 10^15
```
Your job will to be to take in one of these measures and convert it into another.
## Input
Input will be a decimal number `10^-16 < x < 2^31 - 1`, an SI prefix, a letter representing a quantity, another SI prefix to convert to, and the same quantity letter. Input will be in the format `1234.56 mC to TC`, and will always match with the regex `^\d+(\.\d+)? [fpnμmchkMGTP](?'letter'[a-zA-Z]) to [fpnμmchkMGTP](?P=letter)$`. You will never have to convert to/from the base unit (`10^0`)
## Output
Output will be the same number as the input, just converted to a new SI prefix. Specifically, the program should convert the number from `SI prefix 1` to `SI prefix 2` in the input. Examples:
```
Input: 1 nm to μm
Output: 0.001
Input: 82 kC to cC
Output: 8200000
Input: 6.54 MK to hK
Output: 65400
Input: 2000 MB to GB
Output: 2
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
[Answer]
# JavaScript (ES7), ~~113~~ 109 bytes
```
s=>(p=s.split` `)[m={f:-9,p:-6,n:-3,µ:0,m:3,c:4,h:8,k:9,M:12,G:15,T:18,P:21},0]/(10**(m[p[3][0]]-m[p[1][0]]))
```
Edit: Apparently we can use `µ`(`U+00B5 MICRO SIGN`) for the micro sign now, so replacing with that saves a byte.
For ES6 compatibility `(10**(m[p[3][0]]-m[p[1][0]]))` can be replaced with `Math.pow(10,m[p[3][0]]-m[p[1][0]])` for 114 bytes.
## Explanation
```
s=> // s = input string
(p=s.split` `) // p = input parts
// m = dictionary of SI prefix digit powers of 10
// the exact values don't matter as long as they are relative to each other
[m={f:-9,p:-6,n:-3,µ:0,m:3,c:4,h:8,k:9,M:12,G:15,T:18,P:21},
0] // get the number
/(10**(m[p[3][0]]-m[p[1][0]])) // get the factor to divide by from the difference
// between the SI prefix powers of 10
```
## Test
This test uses `Math.pow` instead of `**` so that common browsers can test it.
```
<input type="text" id="input" value="2000 MB to GB" /><button onclick="result.innerHTML=(
s=>(p=s.split` `)[m={f:-9,p:-6,n:-3,µ:0,m:3,c:4,h:8,k:9,M:12,G:15,T:18,P:21},0]/Math.pow(10,m[p[3][0]]-m[p[1][0]])
)(input.value)">Go</button><pre id="result"></pre>
```
[Answer]
# Haskell, 143 bytes
Call `s`.
```
import Data.List
s=i.words
i(n:f:_:[t])=read n*10**(x f-x t)
x=j.flip elemIndex"f p n µ mc hk M G T P".head
j(Just n)=fromIntegral n
```
[Answer]
# CJam, 67 bytes
```
lS%:I0=dA"fpnµmchkMGTP"[-7 -4WY5 6ABEHK23]+:AAI3=c#C+=AAI1=c#C+=-#/
```
[Try it online!](http://cjam.tryitonline.net/#code=bFMlOkkwPWRBImZwbsK1bWNoa01HVFAiWy03IC00V1k1IDZBQkVISzIzXSs6QUFJMz1jI0MrPUFBSTE9YyNDKz0tIy8&input=MjAwMCBNQiB0byBHQg)
Uses `µ` (`U+00B5`) for the micro sign so make sure you use this in your input instead of the `μ` (`U+03BC`) in the question.
My first attempt at using CJam. Feel free to suggest improvements because I'm sure there are many!
## Explanation
Same method as my JavaScript answer.
```
lS%:P e# P = input parts separated by space
0=d e# get number as double
A
"fpnµmchkMGTP"
[-7 -4WY5 6ABEHK23]+
:A e# A = array of SI prefixes followed by their (relative) values
AP3=c e# desired SI prefix
#C+= e# get SI value of prefix
AAP1=c e# current SI prefix
#C+=- e# subtract value of prefix
# e# get power of SI prefix difference
/ e# divide value by 10 ^ SI prefix difference
```
[Answer]
# Ruby (2.2.1), ~~126~~ 123 bytes
```
r={f:-9,p:-6,n:-3,µ:0,m:3,c:4,h:8,k:9,M:12,G:15,T:18,P:21};p ($*[0].to_r/10**(r[$*[3][0].to_sym]-r[$*[1][0].to_sym])).to_f
```
Saved 3 bytes thanks to user81655
## Explanation
```
# Hash of prefixes to relative powers
r={f:-9,p:-6,n:-3,µ:0,m:3,c:4,h:8,k:9,M:12,G:15,T:18,P:21};
p ( # print (inspect)
$*[0].to_r # input value
/ 10 ** ( # divided by 10^...
r[$*[3][0].to_sym] # first prefix symbol
-
r[$*[1][0].to_sym] # second prefix symbol
)
).to_f # convert to float for proper format on output
```
Takes input from the command line e.g `ruby si.rb 1 nm to μm`
This is my first golf!
[Answer]
# Pyth, ~~46~~ 44 bytes
The program assumes that the character `µ` (`U+00B5 MICRO SIGN`) is used for the micro sign. On Windows, this is what you get by pressing `Alt Gr` + `M`.
The source code contains some unprintables, so here is a reversible `xxd` hex dump.
```
0000000: 2a76 684a 637a 645e 542d 466d 406a 4322 *vhJczd^T-Fm@jC"
0000010: 5c72 575d d623 8b9e 53bb 4c09 b275 2233 \rW].#..S.L..u"3
0000020: 3125 7443 6864 3137 2532 744a 1%tChd17%2tJ
```
Here's a copy-friendly version:
```
*vhJczd^T-Fm@j1057004749883241517573776978549 31%tChd17%2tJ
```
You can [try the demo](https://pyth.herokuapp.com/?code=*vhJczd%5ET-Fm%40jC%22%5CrW%5D%C3%96%23%C2%8B%C2%9ES%C2%BBL%09%C2%B2u%2231%25tChd17%252tJ&input=82+kC+to+cC&debug=0) or use the [test suite](https://pyth.herokuapp.com/?code=*vhJczd%5ET-Fm%40jC%22%5CrW%5D%C3%96%23%C2%8B%C2%9ES%C2%BBL%09%C2%B2u%2231%25tChd17%252tJ&test_suite=1&test_suite_input=1+nm+to+%C2%B5m%0A82+kC+to+cC%0A6.54+MK+to+hK%0A2000+MB+to+GB&debug=0). If these links fail, use the copy-friendly version ([demo](https://pyth.herokuapp.com/?code=*vhJczd%5ET-Fm%40j1057004749883241517573776978549%2031%25tChd17%252tJ&input=82+kC+to+cC&debug=0), [test suite](https://pyth.herokuapp.com/?code=*vhJczd%5ET-Fm%40j1057004749883241517573776978549%2031%25tChd17%252tJ&test_suite=1&test_suite_input=1+nm+to+%C2%B5m%0A82+kC+to+cC%0A6.54+MK+to+hK%0A2000+MB+to+GB&debug=0)).
[Answer]
# Haskell, 121 bytes
```
(e:l:i)!d|e==d=fromEnum l|0<1=i!d
b#i="f`pcnfµimlcmhqkrMuGxT{P~"!(b!!i)
g[(a,b)]=10**fromIntegral(b#1-b#7)*read a
f=g.lex
```
Defines a function `f :: String -> Double`. For example:
```
*Main> f "6.54 MK to hK"
65400.0
```
[Answer]
# [Perl 5](https://www.perl.org/), 113 + 8 (-p -Mutf8) = 121 bytes
```
%c=(f,-15,p,-12,n,-9,µ,-6,'m',-3,c,-2,h,2,k,3,M,6,G,9,T,12,P,15);/([0-9.]+) (.).*(.)./;$_=$1*10**($c{$2}-$c{$3})
```
[Try it online!](https://tio.run/##FcoxDoIwGIbhq3Sooa3fD7QEIiHMTiQObsY4EIlGaRvFyXAsLsDBrLA87/L66@uZh7Bpa9GBdA6/aGBBJeYJVCDqI1CGFmRwg8EDGRoU2KPEEct7gM5llYhTSmV83komYhmrlaTil5prpVOlBG@/3Iy0JhtlCJrZng2OzVP/c364O/sO1HyGbhfI/wE "Perl 5 – Try It Online")
] |
[Question]
[
Your challenge, should you be coded to accept it, runs as follows:
You may choose one of the following two challenges to implement:
**Challenge #1**
* Read from a file `a.txt`
* Write only printable ASCII characters (values 32-126) to a file `b.txt`
**Challenge #2**
* With a file `a.txt`, delete all characters in the file except printable ASCII characters (values 32-126)
**Specs on `a.txt`**
`a.txt` is a plain text file which can include any ASCII values from 0-255 (even undefined/control) and its size can range up to 1 GB.
**Winning**
The answer with the smallest amount of sourcecode in bytes wins.
[Answer]
## sh
### Challenge 1, ~~24~~ 23 chars
```
tr -dc \ -~<a.txt>b.txt
```
**Bonus**: variations on the set of characters to delete.
```
tr -dc " -~
"<a.txt>b.txt # preserves printables + line feed
```
```
tr -dc "[:space:] -~"<a.txt>b.txt # preserves printables + whitespace
```
[Answer]
# Brainfuck: 92
```
+[[->+>+<<]>>>++++++++[->++++++++++++<<---->]>--[<<[->]>[<]>-]<+<[[-]>-<]>[[-]<<.>>]<<[-]<,]
```
Brainfuck cannot open files so you use stdin/stdout redirection (#1)
```
bf strip.bf < a.txt > b.txt
```
The same code in [Extended Brainfuck](http://sylwester.no/ebf/): 68
```
+[(->+>+)3>8+(->12+<<4-)>2-[<<[->]>[<]>-]<+<([-]>-)>([-]2<.)2<[-]<,]
```
[Answer]
## Bash + Perl
### Challenge 1 – *31* bytes
```
perl -petr/\ -~//cd a.txt>b.txt
```
### Challenge 2 – *28* bytes
```
perl -i -petr/\ -~//cd a.txt
```
[Answer]
Both are Challenge 1.
# C - 132 characters
```
#include<stdio.h>
k;main(){FILE*f=fopen("a.txt","rb");FILE*g=fopen("b.txt","w");while(!feof(f))(k=getc(f))>31&&k<127&&putc(k,g);}
```
# Python - 78 characters
```
file("b.txt","w").write(filter(lambda x:'~'>=x>' ',file("a.txt").read()))
```
[Answer]
**PowerShell (43, 43)**
**Challenge 1: (43)**
```
(gc -raw a.txt) -replace"[^ -x7e]","">b.txt
```
**Challenge 2: (43)**
```
(gc -raw a.txt) -replace"[^ -x7e]","">a.txt
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
kPs5ȯ↔
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=kPs5%C8%AF%E2%86%94&inputs=%22regegfer%5Cn%C3%98%C3%B8%CF%80%E2%88%91wodwef2342%CB%86%CF%80%E2%88%86%C3%B8iy%5Cnn%C2%BA%C3%A7%C3%9Ffiwu9few09wf%C2%AB%5B%5C%5Cwe.%3B.%5B%3B%5D.we%5Cn24%22&header=&footer=)
Fixed thanks to Aaron Miller. Why does the printable ascii builtin contain unprintables?
[Answer]
## iX3, 388
```
Set in [c]: '1'
Loop start ([c] of 1 to 999999999)
Read from file 'a.txt' into [T] (read from [c], 1 bytes)
Modify text '[T]' into [R] (code in Hex)
Set in [N]: '&H[R]' (calculate)
If True: '([N]=10)'
Write into file 'b.txt' line '' (Append)
End If
If True: '([N]>31)&([N]<127)'
Write into file 'b.txt' line '[T]' (Append, no linefeed)
End If
Loop end
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 7 bytes
Simple regex to remove non-printable ASCII.
```
[^ -~]
```
[**Try it online!**](https://tio.run/##PVJLTxNRFN77K87a6MKfQEgVkpaa0A0aTcZy294wnanzULsxBSnKs0KgtsXa1kDaUtoGUB5GcWdcfIeF/0D/SD0zJGQmmXPv9zjfPXcc5WnLuDcaPX5Kd18/uTUaTSRiUfKMtEumMrg5p9G2uJKmlINTG50soZW3/xVWueE7pPKKP7s4J@ya2NFzXFJk6ucC@3qWcoa27pCXUeTaVprsFDkK52nfNET5KicsR7muti1hOq4WykttmgJ5WjAr7Ws3E8pf2Dqp3MAgazsCeYZJWcOSTHb22j8wyyhH0SQlBXCVIu2FZd72wyWOuYYyb6OqscDz6HqYxyoXZH8DXRzxdqDQLj1Thu/plG@SF5pSSiZkkmv5qZS@PkbQ0tRK4DBUTNqMRaM0OU3R@LTYlniRy@jyW3zAQeIaE3IIJ0J1zrZwliepknZWjhYUOMXgZhEWAVMnMyK1HcopJ6sMT7YNGVJshu6PjUduvn@/bmUobc@SZdNUXN44vsdFKOVVhVzPzoVuhiV7t3kTl/KcSo0i97iEKvbSvMtLuOQeNnlJovdMrAu2zx0u87KcpIsTNBSKaLrEGwba/I7LDn6IZpG3eFNRYG57wS0XxKSNNYM7Jt7wHi9IuyVUUEeVHo1xEy1e4Xr0wdWaTI0HWPizjKH47eBCWEeUiHNRMlzg2686vvw@wQklJlCJ8CKWuUzcfCj0dfTjqEnPKbyfQYsmJOqK5ClKsw20cI4DDCMSb5cPRFiQm2lzBYfokoS75EO0ZeYdHEmfPobj3Jeb2@cBN3AmEzlGnctxWZYwEKc6r8fEfgs1ceuKuMYfhVOOyFG7vMaSEw00uIpP0zzET2yjI7/XPhfRk1@s/x8 "Retina – Try It Online")
Test input copied from [this SO post](https://stackoverflow.com/a/1732454/2415524).
[Answer]
# [Tcl](http://tcl.tk/), 122 ~~123~~ bytes
```
set g [open b.txt w]
lmap c [split [read [open a.txt]] ""] {scan $c %c v
if $v>31&$v<127 {puts -nonewline $g $c}}
close $g
```
[Try it online!](https://tio.run/##pY9Ba8IwGIbv@RUvpe6mUGXzMrxsHQiiMPUgNYc0piWQpqGJVRB/e9da3YT2tvv7Pc/3OK4qKxwSRLkRGmzkzg4nSpzMBC7m6CyGOtfipKQW8OtdkhcZcxhwROJsCkRS8wKSDgNKrxi/vhGucttsCbnde@vV9vsjxNd8EbYCj3SclKiMGdRQa5R0iArBDjWDwvNozyP8@qe5FaR3Wvwo6OM9C@9ky5mucU1PSWQCv5xNghe/fA/G0x5v2qh/3WnVFu71Xn@G6818uWsz425m/M/M6gc "Tcl – Try It Online")
[Answer]
# [K4](https://kx.com/download/), ~~36~~ 33 bytes
**Solution:**
```
`b.txt 1:{x@&31<x*127>x}@1:`a.txt
```
**Explanation:**
Above is for Challenge A, replace the `b.txt` for `a.txt` for Challenge B.
```
`b.txt 1:{x@&31<x*127>x}@1:`a.txt / the solution
1:`a.txt / binary read (1:) "a.txt"
@ / apply to
{ } / lambda taking 1 implicit arg (x)
127>x / 127 greater than?
* / multiply by
x / x
31< / 31 less than?
& / indices where true
x@ / index into x at these indices
`b.txt 1: / binary write to "b.txt"
```
[Answer]
## Burlesque - 21 bytes
```
{**{31.>}{127.<}m&}f[
```
This can be shortened be replacing the `128` with `'<DEL>` (where DEL is the delete character) but I'm not sure how I can post a DEL here (also replace the `31` and then you can also get rid of the `**`)).
Also, in the WIP version you can golf this down to `:un:ln`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Well, seeing as everyone else is ignoring the requirements to read from & write to a file ...
Input [also](https://codegolf.stackexchange.com/a/163514/58974) from [this SO answer](https://stackoverflow.com/a/1732454/4768433).
```
;oE
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O29F&input=IkhUTUwgdGFncyBsZWFcdTAzNjBraVx1MDMyN25cdTAzNThnIGZyXHUwMzM2b1x1MDMyOG0gXHUwMzIxeW9cdTIwMGJcdTAzNWZ1ciBleWVcdTAzNjJzXHUwMzM4IFx1MDMxYmxcdTAzMTVpa1x1MDM0ZmUgbGlxXHUyMDBidWlkIHBhaW4sIHRoZSBzb25nIG9mIHJlXHUwMzM4Z3VsYXIgZXhwXHUyMDBicmVzc2lvbiBwYXJzaW5nIHdpbGwgZXh0aVx1MjAwYm5ndWlzaCB0aGUgdm9pY2VzIG9mIG1vclx1MjAwYnRhbCBtYW4gZnJvbSB0aGUgc3BcdTIwMGJoZXJlIEkgY2FuIHNlZSBpdCBjYW4geW91IHNlZSBcdTAzMzJcdTAzNWFcdTAzMTZcdTAzNTRcdTAzMTlpXHUwMzAyXHUwMzQxXHUwMzI5dFx1MDMwMVx1MDMwYlx1MDM0MFx1MDMzMlx1MDM0ZVx1MDMyOVx1MDMzMVx1MDM1NCBpdCBpcyBiZWF1dGlmdWwgdFx1MjAwYmhlIGZpbmFsIHNudWZmaW5nIG9mIHRoZSBsaWVcdTIwMGJzIG9mIE1hbiBBTEwgSVMgTE9TXHUwMzAxXHUwMzBmXHUwMzQ0XHUwMzU2XHUwMzI5XHUwMzQ3XHUwMzE3XHUwMzJhVCBBTEwgSVx1MjAwYlMgTE9TVCB0aGUgcG9uXHUwMzM3eSBoZSBjb21lcyBoZSBjXHUwMzM2XHUwMzJlb21lcyBoZSBjb21lcyB0aGUgaWNoXHUyMDBib3IgcGVybWVhdGVzIGFsbCBNWSBGQUN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MzMxIFRPXHUwMzQ1XHUwMzQ3XHUwMzM5XHUwMzNhXHUwMTlkXHUwMzM0XHUwMjMzXHUwMzMzIFRIXHUwMzE4RVx1MDM0NFx1MDMwOVx1MDM1NiBcdTAzNjBQXHUwMzJmXHUwMzRkXHUwMzJkT1x1MDMxYVx1MjAwYk5cdTAzMTBZXHUwMzIxIEhcdTAzNjhcdTAzNGFcdTAzM2RcdTAzMDVcdTAzM2VcdTAzMGVcdTAzMjFcdTAzMzhcdTAzMmFcdTAzMmZFXHUwMzNlXHUwMzViXHUwMzZhXHUwMzQ0XHUwMzAwXHUwMzAxXHUwMzI3XHUwMzU4XHUwMzJjXHUwMzI5IFx1MDM2N1x1MDMzZVx1MDM2Y1x1MDMyN1x1MDMzNlx1MDMyOFx1MDMzMVx1MDMzOVx1MDMyZFx1MDMyZkNcdTAzNmRcdTAzMGZcdTAzNjVcdTAzNmVcdTAzNWZcdTAzMzdcdTAzMTlcdTAzMzJcdTAzMWRcdTAzNTZPXHUwMzZlXHUwMzRmXHUwMzJlXHUwMzJhXHUwMzFkXHUwMzRkTVx1MDM0YVx1MDMxMlx1MDMxYVx1MDM2YVx1MDM2OVx1MDM2Y1x1MDMxYVx1MDM1Y1x1MDMzMlx1MDMxNkVcdTAzMTFcdTAzNjlcdTAzNGNcdTAzNWRcdTAzMzRcdTAzMWZcdTAzMWZcdTAzNTlcdTAzMWVTXHUwMzZmXHUwMzNmXHUwMzE0XHUwMzI4XHUwMzQwXHUwMzI1XHUwMzQ1XHUwMzJiXHUwMzRlXHUwMzJkIg)
[Answer]
# Ruby (52)
### Challenge #1
```
IO.write (f="a.txt"),IO.read(f).gsub(/\p{Cntrl}/,'')
```
] |
[Question]
[
## Challenge
Being someone who plays far too much chess in his spare time, I thought I'd set a code golf challenge inspired by the game of chess (with a software flavour), for those interested.
>
> The challenge is to determine the winner of a game of standard chess given a [*PGN* (Portable Game Notation)](http://en.wikipedia.org/wiki/Portable_Game_Notation) file as input -- or in the case of a draw/stalemate, be able to recognise it.
>
>
> Write a full program that takes via the standard input stream a PGN file *except the final result string* and outputs the winner of the game. (See the Wikipedia article for a simple description of the text format.) The program should determine the winner from the provided move information and output `1-0` for White winning, `0-1` for Black winning, and `1/2-1/2` for a draw (by stalemate). Mutually agreed draws and resignations should be denoted `?` since they cannot be differentiated on this basis alone. White is always assumed to move first.
>
>
> Note that the *Result* metadata tag nor the game result at the end of the PGN block itself is to be included in any input, as this must be determined by the program's algorithm. The checkmate symbol (usually `#`) is also never present. All other metadata and comments are valid input to the program.
>
>
>
Example (from Wikipedia page):
Input:
```
[Event "F/S Return Match"]
[Site "Belgrade, Serbia Yugoslavia|JUG"]
[Date "1992.11.04"]
[Round "29"]
[White "Fischer, Robert J."]
[Black "Spassky, Boris V."]
~~[Result "1/2-1/2"]~~
1. e4 e5 2. Nf3 Nc6 3. Bb5 {This opening is called the Ruy Lopez.} 3... a6
4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Nb8 10. d4 Nbd7
11. c4 c6 12. cxb5 axb5 13. Nc3 Bb7 14. Bg5 b4 15. Nb1 h6 16. Bh4 c5 17. dxe5
Nxe4 18. Bxe7 Qxe7 19. exd6 Qf6 20. Nbd2 Nxd6 21. Nc4 Nxc4 22. Bxc4 Nb6
23. Ne5 Rae8 24. Bxf7+ Rxf7 25. Nxf7 Rxe1+ 26. Qxe1 Kxf7 27. Qe3 Qg5 28. Qxg5
hxg5 29. b3 Ke6 30. a3 Kd6 31. axb4 cxb4 32. Ra5 Nd5 33. f3 Bc8 34. Kf2 Bf5
35. Ra7 g6 36. Ra6+ Kc5 37. Ke1 Nf4 38. g3 Nxh3 39. Kd2 Kb5 40. Rd6 Kc5 41. Ra6
Nf2 42. g4 Bd3 43. Re6 ~~1/2-1/2~~
```
Output: `?`
(since it was a mutually agreed draw)
## Rules
Other than mentioned in the problem statement, there are no further restrictions. You may write the program in any compiled/interpreted programming language. The code for the program must be complete, i.e. compile without any modifications or external reference.
The aim as always is to solve the task with the smallest number of characters of code.
(Saying that, I can't promise to accept the answer with the shortest code. I'll also be looking at elegance of the code and time complexity of the algorithm, especially in the case of verbose language, and hope others will do the same!)
## My Solution
I'll be attempting an F# solution while this question is open -- will post it here when I have something.
---
## Format
Please post your answers in the following format for the purpose of easy comparison:
>
> ## Language
>
>
> **Number of characters: ???**
>
>
> Fully golfed code:
>
>
>
> ```
> (code here)
>
> ```
>
> Clear (ideally commented) code:
>
>
>
> ```
> (code here)
>
> ```
>
> Any notes on the algorithm/clever shortcuts the program takes.
>
>
>
---
[Answer]
## Ruby 1.9
**Number of characters: 93**
Assuming that all inputs are valid games, and that games always end in checkmates or stalemates (as per Noldorin's response in the comments), then we only need to check who played the last move and whether it was a checkmate or not.
Golfed code:
```
*a,b,c=$<.read.gsub(/{[^}]*}|;.*$/,"").split;puts c=~/#/?(b=~/[^.]\.$/?"1-0":"0-1"):"1/2-1/2"
```
Ungolfed code:
```
# read entire input
game = $<.read
# strip comments
game = game.gsub(/{[^}]*}|;.*$/,"")
# split the input and get the last two words
*rest, second, last = game.split
# check if the last move has a checkmate symbol
if last =~ /#/
# if so, then determine whether the last move is white or black based
# on the number of periods in the second-to-last word
puts second =~ /[^.]\.$/ ? "1-0" : "0-1"
else
# if not, then it's a draw
puts "1/2-1/2"
end
```
[Answer]
## Python 3 (with [python-chess](https://github.com/niklasf/python-chess))
**Number of characters: ~~173~~ ~~168~~ ~~150~~ 130**
*-5 characters thanks to Unrelated String*
```
import io,chess.pgn as c
g=c.read_game(open(0))
b=g.board()
for m in g.mainline_moves():b.push(m)
print(b.result().replace(*'*?'))
```
Figured I might as well do this, since I already studied python-chess [to answer another chess challenge](https://codegolf.stackexchange.com/questions/148587/is-it-a-valid-chess-move/249561#249561).
[Attempt This Online! - the provided test case (outcome cannot be determined)](https://ato.pxeger.com/run?1=LZLLbtNAGIUlln6Ko2xqt-nQ8S0JUoVkQZEacBWHi1CFqrE9sa0mtmU7lctlw2uw6QZehieAp-FMymb0z_yX8_3H_vGrvR_Kpn54-LkfNqfzP9-rXdt0A6pmmpW670Vb1FA9Mqs4z0SnVX5TqJ22m1bX9pnjWOl5IdJGdbntWJumww5VjULsVFVvq1rf7Jo73dvOs1S0-760d47VdlU92CmH9fvtYDsM2q3KtH18dPz8yHEeSf4DPfx98vv65Z2uB0wunq6R6GHf1XijhqycfLKu19WgMYn0tuhUrqdY6y6tFD7ui6bfqrtKfb1898oUvlCmUC4WrpBSnPnmLWn2dY6JuzCXD-Vh1EXVc_FuiqRJNY24FCYZEfAWk3Wr-v72foqo6aoe703OkgLahw7gCsQbD3EWwhOI0gBf3pYsM15VdQGGmdpudY6h1Ej293jN1GfxjeVCQIWWzzblc0qIQODq9AqRniEUXFuC82ZmrIc8xFwg8w4VC4GSoukckGcCOdvTfGZxSWQ-yCLJlY3sVuaQRIvZGqUzSKNXBEh9SOrFqUTJeupFJVtZTMF81IEVj1xRUjQaCbQyh6SwHomyIq17ZtpzF7F5caXRIMjIw3VNl7mloeUadVqVKD2Ha-THzewECU-4BsEEyajlCVxiUEhieUiSZKU9rIjrzk2mCKxyNDdy0JOlpuukUAyJ4BGB-_pmcx8eGRIVIM4DeETgV4qyOTwCLDcuok1geYEpmaFgrzFchSdY0gKPwktSxBuOoXBBr0ca7lF2yYWX9NSnbkJRU-_LQ7MVc65P2cJHlHvwPfMRw8ef-h8 "Python 3 – Attempt This Online")
[Attempt This Online! - an example of a stalemate](https://ato.pxeger.com/run?1=dZPNbtNAFIUX7PwUV1lQu2lHmRnbMZUqlKQFiQhXTkEIVaga2-MfNf6R7RQjxIbXYNMNvBM8DWdcJMSCzeR65t7znXtn8u1H-2komvrh4fthyE6Dn1_Lqm26gcrmJCl037M2r0n1lFj5ecI6rdLbXFXablpd2wvHseLznMWN6lLbsbKmo4rKmnJWqbLel7W-rZp73dvOWczaQ1_YlWO1XVkPdgyx_rAfbAdBu1eJto-Pjp8fOc6jkz-GHn49eXpzea_rgWbeUNCq0l2ZqJo2xh1tmjqHTj_7YN1cl4Om2WtVF2oYVH1Cof5I75vujt5er0zChTIJPAgWbMEZX5q9Sfrfg4VvDnbNoU5pNsXvikn6FRrvaZWq6hGcNrU5XcP8Hc0uD7muNV3ofaW6SXpzRbONzxFbnJF2SXskGIWZpDDxSTJaxx6FqUsudkf8arN4jK5OrwgZPjIS1wozn5aMUkmpRwEzWZ7J9-gZo53mc1rrJfEFo0gLxD5x8BKkj4m0uEEimES5gZrKxCwc3FjSGvrcM24E7ZKAOLg7lXCKlGdxkEPlEoxxsAtJUY5KkCP0Af8C3MKlKBUkuPGTctqNCbeEMCwjMyqcgRwmHnaQLADO5WRbeMYePGdmEablzLWiEb4E0DvUm7EBHcVLtJ6h2sBH1GYjRCT4UxCNqbQkN1Pw57QtApKCTQ1FOJ6ThINtwY1vfLjmQ1CBe4CD3ZgFc1AzFPlGwTSEGA4izD12ScLBNhekPJLgbzOEuDjAtxi6kpZryHCdQt0FeIuBROZuDRYziXAFLqhRHsDdmAf0GY9YdXvdWytGL8t9rLv8jN4Uml6U2f_f-t93bV7sidUyklx8efy__AY "Python 3 – Attempt This Online")
[Attempt This Online! - an example of a checkmate](https://ato.pxeger.com/run?1=TZLLatwwFIahSz_FYTaxcxGx5NsUQuhMsumQmdqhZBFK8EW2TG3Z-BKcbV-jm2zaTZ-ofZr-ynRRMOJI-s___Tr4-8_-ZVKdfn39MU_lRfT7W9323TBR3Z3nSo4j6ytN6Ui5VV3lbJBp8VSlrbS7Xmr70nGs7KpiWZcOhe1YZTdQS7WmirVprZtay6e2e5aj7bzPWD-Pym4dqx9qPdkZzMa5mWwHRd-kubRPT06vTxznmORfoNc_73493j5LPdHqNh0nOWg6gL36Yj3e15Ok1UM6qlpXU6fP6aYep6HOJ-pK2nbN3GZ1Sp_vPxj1TWrU7nodMpczvjZnb8b_XVxf4zMXSTfrglaRqR_UkVM3TZ22dD8Nc2vONwj9lVYfO6XpLr9L9Ty-eW4PtNoK39SfmpctnJA9NDzLZSQ9kj5xRiWKBYtgtC8FbWRIHqNN7tFGeWfkM9qVLu1VQAEUubAOFwcKGRUe7SuPIhwuyqPYLGtGseRQBeRewsT47hcoXRDjgltxiRtA94WPfUQuqLERFDgHVgkyvYCqBeb5Ap0bvGl8ayNxBXKsfFjnCOdGJh0nhHPBrmCaBWfEDVsKdGWcONBJmrvWToXEwa4WyKuAuGEXLiETWgCPS9NSCux8I8M2KWVkcQRIBSEKB12aTBuzcNCTHA4mGAc_F5QFJEBPMAxAI0sYOuaHd4vjsJMyIgH0roI9pizMtDEBhBfAlgsKs1gC2ETCHYMQoanDM3TBCFy8JTFJBbA7M6qkXID3wFbR1f740_4F "Python 3 – Attempt This Online")
[Attempt This Online! - an example of a real game that ended by threefold repetition at move #34w, extrapolated to hypothetical move #38w to make this program detect a draw](https://ato.pxeger.com/run?1=TZLPbtNAEMYljn6KUS61K7Jk13-DVFU1UA6VUmKQOFSoWsfr9Yp417KdKr3yGlxygXeCp2HGrlAOWY-_2fl-31j5-bt7HhtnT6dfh7FeZn9-mLZz_QjGvd41ahhYpy3IAXaevtqxXsnqUctW-a5T1l8FgVdeaVY62Vd-4NWuhxaMBc1aaezeWPXYuic1-MHbknWHofHbwOt6Y0e_RLPhsB_9AItuL3fKv7y4vL4IgjnJS6DT31fjw4cnZUdY3JoBM_WwhE9q7N1gpIV30lamkqMa4NZYuV988x4-m1HBIj8o6wa4MciBm-Ijdd5L6vB1ytlqzcIVaYU72AoW11R_beZRV5bP8IIjPcd832Hxxegemf_p0_i0BZq-EUv8oeRxBioClYBgUEVQxRAy2OxC2NQJRAxyHUN1xCsxyvTMVQoJ6kfsazpSBjqEOoaMeTSYo7bGy1oJNEqArxjZqiMenJMLFvmxFMAF-Qu4X94DRyw98yYDjtyNqiNvo3AEwdsmRj-0QnAhKw5km9KlELaI4xmDu4ajWQoc2XmD-TGnQHRRYSTajzOvqHE2b_BFUCOiLSIQiC6oQOsMRERvWEyHiKdVEU-HSNhcFLiCSJmno7krMICmgrwxAPLvmhRC5G_xM2xxj5DPe1DeUMx6QTrSt5iRLMNo0r1Jj8_05ExPz_Rs0ud_3z8 "Python 3 – Attempt This Online")
[Attempt This Online! - an example of a real game that ended by threefold repetition at move #25b, extrapolated to hypothetical move #29b to make this program detect a draw](https://ato.pxeger.com/run?1=TZHNatwwFIXp1k9x8SZWyIiR_8ZTCENNu2qb1AlNKEkJsizbamzJ-GeYbPsa3cymfadmn_folaeEAf8cn6Or7wj_-tM9jbXR-_3vaSwXyd-fqu1MP4IyZ6KWw0C7SgMfQDjVuaC95MVDxVvpmU5qb0mIk59XNDe8LzzilKaHFpSGirZc6UZp-dCarRw88jan3TTUXkucrld69HLcbJia0SMouoYL6Z2enG5OCDk0-V9o__zm5e7DVuoR3M98FDXcu1-vrhfvmgZuTd8U96773bm7VqMEN5VN1fNCgvdtqszQ8K3ixMbvuY3ZerWkmw1e1rsyky7AnfVtPc9_4j_MAF_w_GoQtQ1SLPYI7o16HPFsH00vam0UJg6jIEIQEfgULsoA7xgClAKliCGkUGC8w0eErn3LGGIKVQBZHsMKzRyXyggSCjKENA9hTSGTPlwuLh22pFCG81YMUbjsQibAEJYWPiCLIQzpWYEuwngA6Q7ZDGmzKHc4w2L7hQKJDJFp5WMXGTkssQFPsPYK2PqQ5Dt7nKWta3fGGR_RWemjxsCySwYZVvKDw8Tsh0d-9Oo7fnzkr4785Mhfv_qH3_0P "Python 3 – Attempt This Online")
] |
[Question]
[
The GolfScript language has one serious lack, no float or fixed point handling. Remedy this by creating a function F for converting an integer number, given as a string, to a string representing 1 / 10 000 000 000 of it's value. The function must handle both positive and negative values as well as leading `0`s.
The following pretty-print rules apply:
No trailing `0`s.
No `.` if the result is integer.
No leading `0`s, except for numbers with no integer part, they should have 1 leading `0`.
The result must be output as a single string.
Examples:
`123` -> `0.0000000123`
`-00` -> `0`
`012345678901234567890` -> `1234567890.123456789`
`-123` -> `-0.0000000123`
`10000000000001` -> `1000.0000000001`
`123000000000000` -> `12300`
The competition is only between GolfScript submissions using no Ruby functionality. Solutions in other languages may be posted, but they are not eligible for winning, these may not use any fixed or float point functionality that the language offers, and must accept arbitrarily large inputs.
[Answer]
### 55 chars
```
{~.0<"-"*\abs 10.?..3$@%+`-1%~`)[3-]1$,!!*+-1%@@/\++}:F
```
Negative numbers are a bit of a pain - responsible for about 13 chars of the 55. Trailing 0s are handled by using a 1 to stand for the decimal point, reversing as a string, converting to an int, and back again, and re-reversing.
[Answer]
### 50 characters
```
{..~0<<\~abs`.,11\-,,0`*\++-10/(~.!!\"."+*\+-1%}:F
```
The most noteworthy trick in this solution is probably `-10/`, detach the last 10 characters and inverse, so that the trailing `0`s can be culled by conversion by conversion to integer.
] |
[Question]
[
# Input
An integer n and a pair of distinct integer valued (x, y) coordinates on the boundary of the grid. The coordinates are indexed from 1. For example, n=10 and (1,2), (10, 7).
The points will always be on different sides of the grid and neither of them will be \$(1, 1)\$.
# Output
The number of integer points in an n by n grid that are on the same side of the line as the coordinate (1,1). Points that are exactly on the line should be counted as well.
# Examples
For n=10 and (1,2), (10, 7),
[](https://i.stack.imgur.com/dkTUR.png)
The output should be 41.
For n=8 and (8, 3), (3, 8),
[](https://i.stack.imgur.com/QKPoj.png)
The output should be 49.
For n=8 and (7, 1), (8, 2),
[](https://i.stack.imgur.com/V3alU.png)
The output should be 63.
For n=8 and (1, 2), (2, 1),
[](https://i.stack.imgur.com/zb9h6.png)
The output should be 3.
[Answer]
# APL+WIN, ~~32~~ 40 bytes
Plus 8 bytes to comply with the question as it is now written. Works for all four examples given.
Prompts for x coordinates followed by y coordinates and then grid size
```
+/,0≤(↑n)×n←×n∘.-⌊(⊃1,¨n←⍳⎕)+.×⎕⌹⎕∘.*0 1
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv7a@jsGjziUaj9om5mkenp4HlAGRHTP0dB/1dGk86mo21Dm0AiT8qHczUK@mtt7h6UD6Uc9OEAlUp2WgYPgfaBbX/zQuQwVDAy4jBXMuIJXGZaFgzGWsYMFlAWSbA2lDBSMwG0QbKRgC2VwA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 99 bytes
```
(n,a,b,c,d,g=(x,y)=>(~y+b)*(c-a)-(~x+a)*(d-b))=>[...Array(s=i=n*n)].map(_=>s-=g(--i%n,i/n)*g()<0)|s
```
[Try it online!](https://tio.run/##VclBCsIwEIXhvfcQZtpJbHVhFqbgOUQkTdsQqZPSiLQgvXrMVt7i5/E9zcdEO/vpLTh0fRp0AiZDLVnqyGlYaEXdwLaWLRZghUEB21KafDrRYrablPI6z2aFqL3mgvEuX2aCh26i0A6E8Hsmf2AsHOClwm9MNnAMYy/H4GCAuqKajpRzRtz9myJFpzyVJf0A "JavaScript (Node.js) – Try It Online")
1-index
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes
```
≔…·¹NθNηNζ≔×⁻θζ⁻NηεIΣ⭆×⁻θη⁻Nζ⭆嬋ιλ
```
[Try it online!](https://tio.run/##dYzNCsIwEAbvPsUeNxDBePHQk3gq2CLWF4glNIE0/dmkh758TKmgFtzLMh/M1FqOdSdtjGci0zjMXW0DmUndpWsUCg6564MvQ/tUIzLGYWDZ7nvTG54Tv2MP0yrCwrhAOHCYk73CT5ODXroqebfROI8XSR6r0GLlEzeF7Lcl/a80L6WPpjiUncerIkLDwbL1shjFAQQcIb1T3E/2BQ "Charcoal – Try It Online") Link is to verbose version of code. Takes five inputs starting with `n`. Explanation:
```
≔…·¹Nθ
```
Create a range from `1` to `n`.
```
NηNζ
```
Input the first point.
```
≔×⁻θζ⁻Nηε
```
Input the x-coordinate of the second point and subtract the x-coordinate of the first point from it, then for each integer from `1` to `n` multiply that by the y-coordinate subtracted from that integer.
```
IΣ⭆×⁻θη⁻Nζ⭆嬋ιλ
```
Input the y-coordinate of the second point and subtract the y-coordinate of the first point from it, then for each integer from `1` to `n` multiply that by the x-coordinate subtracted from that integer. Pair the elements of this array with those of the previous array and count the number of parings where the element of this array does not exceed the element of the previous array.
Note: The output depends on the input points being entered in the correct order. The inputs for the other test cases are as follows:
* `8 3 8 8 3`
* `8 8 2 7 1`
* `8 1 2 2 1`
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 109 bytes
```
lambda n,x,y,X,Y:sum(((a:=(Y-y)/(d:=x*Y-X*y))*-~(K%n)+(b:=(x-X)/d)*-~(K//n)-1)*(a+b-1)>=0for K in range(n*n))
```
[Try it online!](https://tio.run/##VY1NCoMwEIX3PUU2hZmYEH8WBiG9gBdQ6CZibYU6SmrBbHp1mypdCI@Zx/eYN5OfHyNlenJrZ67r0w5NaxmJRXhRibp4vQcAsIWBWnpU0BZm4bWsuEfk8gPlmTCCJuSLrFC1O1SKUCbIwUZN2BcTd6NjJeuJOUv3GxAnxHVyPc3QQRILlgiWhhlcjnj6J1qwoGyTPvJ8uwkmPfK96NcVPnwB "Python 3.8 (pre-release) – Try It Online")
(Even) Econ majors [will know](https://www.google.com/search?client=safari&sca_esv=593843995&rls=en&sxsrf=AM9HkKkbLCDFtxyjF-CTvd5k1M3pqcTXhg:1703627914995&q=budget+set&tbm=isch&source=lnms&sa=X&ved=2ahUKEwiylM_FjK6DAxXJgf0HHU3QAakQ0pQJegQIDRAB&biw=1512&bih=806&dpr=2) that a line can be described by the equation \$ax+by=1\$. So this solution just computes \$ax+by\$ for each point on the grid and compares it to \$1\$.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
_þḢU×_/}Z>þ/¬SS
```
[Try it online!](https://tio.run/##y0rNyan8/z/@8L6HOxaFHp4er18bZXd4n/6hNcHB/x/u3Gf9qGGOgq6dwqOGudaHl@sDRVS4Drc/aloT@f9/NFe0oYFOdLShjlGsDohpHhsbq8MVbQEUs9AxBooZ61gghMx1DIFCFkDFcCEjsJAhWIgrFgA "Jelly – Try It Online")
A dyadic link taking \$n\$ as the left argument and the points as the right argument as a list of two lists of integers.
This is loosely a [Jelly translation of @Neil’s Charcoal answer](https://codegolf.stackexchange.com/a/268761/42248) so please upvote that one too!
## Explanation
```
_þ | Outer using subtract (will implicitly turn n into 1..n)
Ḣ | Head
U | Reverse order of innermost lists
×_/} | Multiply by the difference between the two points
Z | Transpose
>þ/ | Outer using greater than
¬ | Not
SS | Sum and then sum again
```
[Answer]
# [Haskell](https://www.haskell.org/), 86 bytes
```
n#(a,b,c,d)|(%)<-(\x y->(c-a)*(y-b)-(d-b)*(x-a))=sum[1|i<-[1..n],j<-[1..n],i%j*1%1>=0]
```
[Try it online!](https://tio.run/##RY3daoNAEEbvfYoPgjArsyGrpUnBzYtYLzZGqGmyFNeCgu9uZ5UmFzNzmDM/Xy58t/f7svgdOb5ww1c1U6pKTZ8jJn2mRjuV0aQvStNVckajdJQNv4/KzF2pK7Pf@5pvT@rSW2ZSc7aHenm4zsPip@/8gMpjBxoNY5IYc6m5grXoMYM8/zsVabOMXqHUGNowNC60oU6SJ8vhKgHIHGTBcJxe@SjwJleiO/EaRXQF4xTVx0sdGes74bj@XryU2VqUbyOFElEnyx8 "Haskell – Try It Online")
] |
[Question]
[
Goal: create a self-referencing tuple satisfying `x == (x,)` in any version of Python. Standard libraries, matplotlib, numpy, pandas only.
Answers meeting this extra condition are prioritised (which may be impossible): this tuple should also be insertable into a dict or set.
If the extra condition is impossible, apart from the low-hanging optimization of the below code, I am still interested in a qualitatively different approach of similar length or better.
---
I had previously assumed [this answer](https://stackoverflow.com/a/61280229/5805389) to be one of the shortest, but as @mousetail brought up, actually it crashes python when inserted into a dict or set.
```
import ctypes
tup = (0,)
ctypes.c_longlong.from_address(id(tup)+24).value = id(tup)
```
I notice this also happens with the other answer in that post, so I'm wondering if there's a way to resolve it (the ideal answer), or if that is inherent in python.
[Answer]
# [Python 3](https://docs.python.org/3/), 48 bytes
```
from marshal import*
t=loads(b'\xa9\1r\0\0\0\0')
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1chN7GoOCMxRyEztyC/qESLq8Q2Jz8xpVgjST2mItEyxrAoxgAC1TX/FxRl5pVolOgolEQbxCpkFiuAmAq2tgpAMU3N/wA "Python 3 – Try It Online")
Not portable, depends on the interpreter. There's probably a similar (portable) `pickle` version, although it would need to be handcrafted since the `pickle.dumps` gives an error due to recursion depth.
Uses `marshal`, which is a standard library for serializing Python objects. The string is the string received by serializing the object produced by the code in the question.
] |
[Question]
[
[Related](https://codegolf.stackexchange.com/questions/12919/n-doors-k-monkeys) but noticeably different
You are the leader of the guard in the dungeon of an ancient castle.
There are `N` doors in the dungeon and `N` guards with keys.
Guard with index `i` may operates with doors
that have multiple indexes:
`i, 2 * i, 3 * i, ...`
The way he operates is very dumb: he just toggles state of the door:
"open" → "close", "close" → "open".
Every morning you are given two lists:
* the list of doors that are open now (criminally or legally)
* the list of doors that must be open after your shift
*Your goal is to select the minimum number of guards to accomplish the task.*
Each guard from your selected team passes through all his doors (scan and opens/closes them),
but only once and only one way, starting from the first guard in the list.
### Examples
Number of doors: `1001`
Doors are opened: `[ ]`
Doors must be opened: `[ ]`
Answer: `[ ]`
Number of doors: `10`
Doors are opened: `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`
Doors must be opened: `[ ]`
Answer: `[1]` (First guard closes all doors)
Number of doors: `5`
Doors are opened: `[1, 2, 3]`
Doors must be opened: `[3, 4, 5]`
Answer: `[1, 3]` (After guard #1 doors `[4, 5]` are opened, and guard #3 just open door #3)
### Input
* Number of doors N
* List of doors are opened now
* List of doors must be opened
Every list is valid: no negative or `> N` numbers, duplicates etc.
Also you may suppose that lists are sorted as you need:
by ascending or descending.
### Output
Any of teams of guards (that resolves the task) with minimal number of members.
### About solution
I remember that there should be considerations from the number theory that either solve the problem in a closed form or greatly optimize searching. But I can’t formulate them yet.
### Test cases
```
6, [2, 3, 4], [3, 4, 5] → [2, 4, 5, 6]
8, [1, 8], [4] → [1, 2, 3, 4, 5, 6, 7]
100, [12], [13] → [12, 13, 24, 26, 36, 39, 60, 65, 72, 78, 84, 91 ]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
≔⁺⁻ηζ⁻ζηηW⌊η«≔Φ…·¹θ⁻¬﹪κι№ηκη⟦Iι
```
[Try it online!](https://tio.run/##PY29CsIwFEZn@xR3TCBCq6OTFASHSnEtGUINzaVpgk1SoeKzxwR/lgP3cDlfr8TcW6FjPDqHgyGtDo40aBIVg5Uy@BwrA0VpxqF4KNQS8hdOYSLJw7PYfAMn1F7O5Gz6VMJFXoUZJKkY3P@ti/WksbegLRkZYM7WNhifF0f6W9m0MybX1cJ5gpQn9Yqxq8qSQVfteOae87hd9Bs "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁺⁻ηζ⁻ζηη
```
Get the list of doors that need to be toggled.
```
W⌊η«
```
While there are doors remaining, get the next guard needed.
```
≔Φ…·¹θ⁻¬﹪κι№ηκη
```
Calculate the new list of doors that need to be toggled.
```
⟦Iι
```
Output the guard.
[Answer]
# JavaScript (ES6), 83 bytes
Expects `(source, target)(N)`, where the first two arguments are sets. Returns an array.
```
(a,b,o=q=[])=>g=n=>++q>n?o:g(n,o.map(v=>p^=q%v<1,p=a.has(q)^b.has(q))|p&&o.push(q))
```
[Try it online!](https://tio.run/##fc7BbsIwDAbg@57Cl1WJ8ErTMlrQXB6CIwpSYKXdxJKUsu6ydy8OIASHLZKl5Lf1OZ@mN9328OGPL9a9V8OOBmFwg45aWmlJZU2WytGoLe3CzWth0cVfxoueSr@m9rl/U@jJxI3pRCvXm@tF/voocrH/7prwGrbOdm5fxXtXi52w1Q8sq6NYpQgZwkRLhFsWAoRXLaWYSgnjMYSxECFMNcDTH5ZCKB6gSSAKJm4nWDx23XoREfL/0PSBVFkwVZLcqWeUScVmymjKZBZqxnrCxVty7ucFf5D7M6WHEw "JavaScript (Node.js) – Try It Online")
### Commented
```
( // outer function taking:
a, // a = set of currently open doors
b, // b = target set of opened doors
o = // o[] = output list
q = [] // q = counter, initially zero'ish
) => //
g = n => // inner recursive function taking n
++q > n ? // increment q; if it's greater than n:
o // stop and return o[]
: // else:
g( // do a recursive call:
n, // pass n unchanged
o.map(v => // for each entry v in o[]:
p ^= // toggle p if:
q % v < 1, // v is a divisor of q
p = // start with p set to:
a.has(q) ^ // the presence of q in a
b.has(q) // XOR the presence of q in b
) | // end of map()
p && // if p is truthy:
o.push(q) // append q to o[]
) // end of recursive call
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~21~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
«Ð¢Ï[W,©g!#Lʒ®ßÖ®yå^
```
Port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/259704/52210), so make sure to upvote him as well!
Inputs in the order \$[openDoors], [doorsToBeOpened], numberOfDoors\$; outputs the results on separated lines to STDOUT.
[Try it online](https://tio.run/##AUAAv/9vc2FiaWX//8Krw5DCosOPW1cswqlnISNMypLCrsOfw5bCrnnDpV7//1sxMl0KWzEzXQoxMDD/LS1uby1sYXp5) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@pw6XkX1oC5epUJoT@P7T68IRDiw73R4frHFqZrqgc4XNq0qF1h@cfnnZoXeXhpXH/a2sPbbP/Hx0dHasDRIYGBoaxOgrR0YY6RjrGOiY6pjpmOuY6FjqWQCmoCoQ8UACsJhaEgIJgLQhBM6hKC6AQUNgCwjUC8gyNwVbFxv7X1c3L181JrKoEAA).
**Explanation:**
```
« # Merge the first two (implicit) input-lists together
Ð # Triplicate this list
¢ # Pop two copies, and get the counts of each item
Ï # Only leave the items where the count is 1
# (we now have an unordered list of unique items of the merged input-lists)
[ # Start an infinite loop:
W # Push the minimum of the list (without popping the list itself)
, # Pop and print this minimum with trailing newline
© # Store the list in variable `®` (without popping)
g # Pop and push the length of the list
! # Faculty (edge case for an empty input-lists)
# # If this length! equals 1 (aka length is 0 or 1): stop the infinite loop
L # Push a list in the range [1, third (implicit) input-integer]
ʒ # Filter it by:
®ß # Push the minimum of list `®` again
Ö # Check if the current item is divisible by this minimum
® # Push list `®` again
yå # Check if the current item is in list `®`
^ # Bitwise-XOR to check either of the two is truthy (but not both!)
```
] |
[Question]
[
*This is an alternate version of [this](https://codegolf.stackexchange.com/questions/241117/split-along-groups) earlier challenge with a twist that adds a significant bit of difficulty.*
Like last time, you are going to be given a string containing some alphabetic characters along with `[` and `]`. Your task is to split into sections that are enclosed in a "group" created by `[...]` and those that are not. e.g.
```
"absbn[mesl]meslo[eyyis]me"
->
"absbn"
"mesl"
"meslo"
"eyyis"
"me"
```
However unlike last time, this time a "group" must be non-empty. This means it must contain at least one character. So when there are `[]` next to each other they don't form a group. For example:
```
"absm[]mm[m]"
->
"absm[]mm"
"m"
""
```
The first pair of brackets is empty so it can't form a group. The second one does so it counts as a group and we split it. Notice that the non-group portions *can* be empty, it's just the groups that cannot.
Additionally when there is a conflict where two possible groups could be made: like `co[[x]t` or `m[[e]]it`, we will always choose the *smallest* valid group. In the case of a tie we choose the group that starts the furthest to the left.
Any `[`s left without a match are just regular characters and appear in the output.
So in `co[[x]t` we could do `co` `[x` `t`, but we could also do `co[` `x` `t`. Since the group here is either `[x` or `x` we choose the smaller one and the result is `co[` `x` `t`. In the second case `me[[e]]it` there are 4 ways to make groups here, but unambiguously `me[` `e` `]it` results in the smallest group.
If we have `me[[]]yt` then the smallest group would be `[]`, but that's not a group, so our options are `me [ ]yt` and `me[ ] yt` so we choose `me [ ]yt` because that group starts further to the left.
Your task will be to take a non-empty string of characters `a` through `z` plus two brackets of your choice (`[]`, `{}`, `()` and `<>`) and to split it as described above, providing a list of strings as output.
In cases where a group is on the boundary of the string, e.g. `aaa[b]` or `[ems]ee` you may choose to include or omit an empty string `""` on that boundary. The test cases always include them.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Answers will be scored in bytes with the goal being to minimize the size of your source code.
## Test cases
```
go[cat]me -> "go" "cat" "me"
absbn[mesl]meslo[eyyis]me -> "absbn" "mesl" "meslo" "eyyis" "me"
absm[]mm[m] -> "absm[]mm" "m" ""
co[[x]t -> "co[" "x" "t"
me[[e]]t -> "me[" "e" "]t"
me[[]]yt -> "me" "[" "]yt"
mon[g]]u -> "mon" "g" "]u"
msy]mesl -> "msy]mesl"
eoa[m -> "eoa[m"
a[b[ -> "a[b["
mesi]mmp[mo -> "mesi]mmp[mo"
meu[ems[mela[] -> "meu[ems" "mela[" ""
w[[[] -> "w[" "[" ""
[foo]foobar[bar] -> "" "foo" "foobar" "bar" ""
ab[][]cd -> "ab" "][" "cd"
me[[[][]]yt -> "me[","[","","]","yt"
mem[[[[]]] -> "mem[[" "]" "]]"
mem[ooo[]]t -> "mem[ooo" "]" "t"
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 45 bytes
```
0S1`<(.((.))*?)(?<!<(?=(?<-2>.)+>)(?<-2>.)*)>
```
[Try it online!](https://tio.run/##NY1BasNADEX3ukUWhZmUmLbryXjZAzS7j8BjdxIMkRUyDqkv1gP0Yq5sEhhJT4x4/5rHfkjzoQE3IdLfr72d9Rf32cxvX@9NcJVzlffb2rs6bIKr9zZ3H7Hyr9E/ceujOUI0zXxSdGlkyZTa0g6QXM68NEWepr48fgQsAmHqFPjhkSQDmR/APBnogBPzjaRMq4GyJggltLCr0pvhAlHjG7IUizonMN1hAsJRla3adIUVWygY3H2vAQuuGVmwbMwrqqrx@A8 "Retina 0.8.2 – Try It Online") Link includes test suite that switches between `[]` and `<>` and separates the output lines for each case with `-` for convenience. Explanation:
```
0S1`
```
Include only capture group 1 in the results.
```
<(.((.))*?)...>
```
Look for a minimal group...
```
(?<!...(?<-2>.)*)
```
... that does not overlap with...
```
<(?=(?<-2>.)+>)
```
... a smaller group.
[Answer]
# [Haskell](https://www.haskell.org/), Reference answer
```
n!('[':x)|']':y<-drop n x="":take n x:n!y
n!(a:x)|i:j<-n!x=(a:i):j
n!x=[x]
f x=foldl(\x->(>>=)x.(!))[x][1..length x]
```
[Try it online!](https://tio.run/##bZBBj4MgEIXv/go0m6gHm@zV1P6R1zmgYmsLTFNsFpP97y7sTdrDkOF7Q3hvrtLdldbbZvOqRNn6@reksl2Pzfjkh7DCd0XRLvKuYt/afM3CpIxzc3s7Njb3XbjOdXvLYg9P2RQeTaxHXZ19c6pOp672hyqv6yDi@3DQyl6Wq/C0GTlb0YmRM/F4znYRX2ISxYUxyIWMKnZY9q63MMppigdDrevsPo0ZkDEwtBcGRjCw7KFRgKJPlGhNKVtciF4Jdeu/nz1VLGESY@iRfuPm4PQBw6nwgjIuhNUSSYwfIEWYmClUL58IRelCQKBhfI8Y@XtKZRAlonfOzIjL2v4A "Haskell – Try It Online")
Since there seems to be some issues with understanding exactly the specifications, I thought I would post my Haskell reference solution. It's how I have been checking the test cases. It's golfed just enough to be a valid answer here, but I've left it as a CW since it could certainly be golfed better.
If you are unclear about anything in the question please ask, but this should serve as a way that you can test out cases without having to wait for me to respond.
## Explanation
The algorithm here is very simple. First we split all occurrences of the pattern `[.]`, preferring ones to the right. Then we split all occurrences of `[..]`, then `[...]`, then `[....]` up until the length of the list.
This never splits on empty groups, prioritizes smaller groups and when groups are equal sizes prioritizes to the right.
[Answer]
# Python3, 255 bytes:
```
def f(l):
r=range
q=len(l)
if(j:=[(x,y) for x in r(q)for y in r(x+1,q)if l[x]=='['and l[y]==']'and y-x>1]):
m=min(j,key=lambda x:[not l[x[0]:x[1]].isalpha(),x[1]-x[0],x[0]])
yield l[:m[0]];yield l[m[0]+1:m[1]];yield from f(l[m[1]+1:])
else:yield l
```
[Try it online!](https://tio.run/##bZBNbsMgEIX3OQXKxrhxqlrdVK7ci4xmgWOckDLggKOa07uQplVlsgDpfW/@xzCdrHl9G92y9HJgA9dls2GudcIc5YZdWi1NZBumBn5uWuBzFUo2WMdmpgxz/FImEX7EvKurS6kGpmHGti2gEKaPIiSBNxH280eNqQmjlpTh5@pThlYL6nrB5gaMnVI6vGAzQ434rLzQ40nwskp6n5wqfRinYkFJnTo0lMj7r0xqV0dY/8HBWUr7QYLRS@lSe9ncc5bRKTNxeBp4cbRwEBOSLMoY9s8Qne8MkPQa02dBhqB8HriNgQRIBITbVY2DhXidaV2aJIDExxwx5NwaOCJeM@7DbbY1l1YAZftAB3lDr@LkI5DNrStI8vEAWgCu3S@AHMJgLcbXCQfxYX5RQMBD/2jt5DzaXBIkE/GRY62F@xmXbw)
[Answer]
# [Python](https://www.python.org), 150 bytes
```
def f(s):(n:=len(s));g,l,i=min([[s[i]>"[",s[i+2:].find("]")%n+3,i]for i in range(n)]+[3*[1]]);return[s]*(g|(l>n))or f(s[:i])+[s[i+1:i+l-1]]+f(s[i+l:])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RZJLbuMwDIaBWfoUgoACUuwUyHQzcOHcoWuCCyeRXQF6GJY9qYGeo5tusuncaeY0Q8lys6BM_h9FUoQ__wzL9Ord7fY1T93-19-Pi-pYJ4Kshasboxy58rmvTKUbq50ACKDxyIFX5JQ_a3zstLsIjlw-uPKp0tj5kWmmHRtb1yvhJJbwtIMDonwe1TSPDgLuRP8uzNFJSdnUD2qNsozFy0OtS7On9DLq5Nco83Qv11dtFDvUBdOVZw11GeZJyMcwGD0JzvZHxmXBIoKdbQehfrem8plLiQUbRu0m0Qktm8bnwrd_P2Tv4dxOaFUq0nvOOMV0WsWL9hRODqwKBuPhQS2LDltyoikzmPyJ11POvYAFtBYsbldSHDEZL84e4A2nBMkn7Y1s4oVVAAozoSAWJsOMEJcNkRopCYS8gx5xXpGP0_WRzYTCkh6xohzwQvkWbNKSRyPDCdZZyYnNgqaBB7A-9_uOI5xB2UAbMi1g5klK7ycxPfIKkOkV8rS8gM57-mn8qR2BbOVESFpPEslZz7hJQMDzJa8xPirWOV_WfUR4X8l3F8oiS5tRFmIabmNSuG2OchL33sN95SnOFajA-sv8Bw)
#### Old [Python](https://www.python.org), 168 bytes
```
def f(s):
r=s[1:];S=[s,r]
while r:
_,*r=r;S+=[r]
if any(m:="".join(d)for x,*d,y in zip(*S)if[x,y]==[*"[]"]):x,y=s.split(f"[{m}]",1);return*f(x),m,*f(y)
return s,
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RZJLjtswDIaBLn0KQSvL1QyQXZFAPUOBLAli4CRyRoVlGZI9sVv0JN1k06JXak9T6uHJgjLJjyJ_Ef75e1ynVzfc77_mqXv69PfPRXesq4PYV8yrALs9Ho4KgvRYsdur6TXzhNiLbLzyh-NHBZEw07F2WGu7V5w_f3VmqC-ic54tsrnIlZmBfTNj3RyF6WCRKyoFDQfkKPYUqvAcxt5Mdcfhu_2BXO7Ewetp9kPT1YuQVtJ3FaQpJVmQRe-XrGlHmox0TNGkcZ5qUfpx9vSZcboXUWPbsdZvbS9dwULIio3eDDS5NkIpJ3Lf-78P4urg3E5odepxdZxxium0mlftKZwGsDr0GA8Hel1N2IoTTZWhL594PdU8GlhAa8HidiXFEZPx6uwAFpwSJJ9yC9nEK6sBNBZCQWxMhgUhrhuibKSUIOQGuCLOGbmo7hrZTCis6REZlYBX2rVgUy55JBlOkLWSE4cFQ4JHsK7Me48jnEHbQBvqW8DCUyq9n5LpkTeAQm9Q1PIKOueQ7NR6IMucCKXySUly8hk3CQh4vpQ1xkfFPudL3keEj5W8T6EqsrQZbSGW4SaTwm1zVJO4cw4eK09x6UAN8i_zHw)
#### Old [Python](https://www.python.org), 174 bytes
```
def f(s):
r=s[1:];S=[s,r]
while r>r[:1]:
_,*r=r;S+=[r]
if any(m:="".join(d)for x,*d,y in zip(*S)if[x,y]==[*"[]"]):x,y=s.split(f"[{m}]",1);return*f(x),m,*f(y)
return s,
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RZLBjpwwDIalHnmKKCdCsyvNrWKUfYZKc7SsihnCbFaEoAQ60KpP0stc2mPfp32aOiHsHBxsf479x-Ln73GdXt1wv_-ap-7p098_re5YVwZRF8yrAIcajycFQXos2O3V9Jr5Fw_1AamAfZGVV_54-qggcmY61gxraWvF-fObM0PZis55tsiqlSszA_tmxrI6CdPBIldUCioOyFHUFKrwHMbeTGXH4bv9gVwexNHrafZD1ZWLkFbSdxWkLCVZkFn1503ZgTQZ6ZiiSeM8lSL34-zphXG6F1Flm7HUX5teuoyFkAUbvRlocmmEUk5sfe__Poirg0szodWpx9Vxximm02peNOdwHsDq0GM8HOh1NWEvTjRVhj5_4vVU82hgAa0Fi_uVFEdMxouLA1hwSpB8yi1kEy-sBtCYCQWxMRlmhLjuiLKRUoKQG-CKOG_IRXXXyGZCYU2P2FAOeKFdAzblkkeS4QybVnLisGBI8AjW5XnvcYQzaBtoQ30DmHlKpfdTMj3yBpDpDbJaXkDnHJKdGw9kGydCqe2kJDnbGTcJCHhp8xrjo2KfS7vtI8LHSt6nUBVZ2oy2EMtwl0nhvjmqSdw5B4-Vpzh3oAbbL_Mf)
Thee requirement of having to pick a shorter match over a potentially overlapping earlier but longer match is too much for my regex skills.
This approach finds the shortest (first if ties) match, splits the string there and recurses on the ends.
#### Wrong [Python](https://www.python.org), 53 bytes
```
lambda s:re.split(r"\[((?:[^][]+)|\[)\]",s)
import re
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZHNTsMwDMfFNU8R5dTAhsQBCU0qPANn10jpyEqkpqmalK0Sb8JlEhrvBE-D8zHgYNf-_2zHSd8_xyW8uOH4saub0xx267uv217Z9llxv5n0tR97E6pJNFBVDxt4QsAr-daAbFCsvGTGjm4KfNKl-XH_YnrNbzaMm5XjNTfDOIdKlkGCr--5kIxHBJdWjZV-Vf3KFS4lMj5OZgjVrjKyrp3Mg4_fF6fOwVYFtDoN6ZzggnLyVgumWt8OYLXvMToHelmMPxcnmip9Xz6xPdX8DbCA1oLFc0vKIyYTbOsADhgSpJi0A1kQzGoAjYVQEgeTYUGIyxmRGikJhNwAHeKckYvbdZHNhPySLpFRSQTTToFNWopoZWgh70pBPMwbWngE68p5v3mEM2jr6YV6BVj4f0mwPUAheyibCgY755CsVROQZU6EpOxJpCB7wVj-XT8)
I must admit I do not fully understand the rules. But this solves all test cases **EDIT:** did solve at the time.
] |
[Question]
[
Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details.
Related to [AoC2020 Day 11](https://adventofcode.com/2020/day/11), Part 2.
---
You enter the waiting area for a ferry, and you see a bunch of people sitting at a bunch of seats. The seats form a grid like this (`.` is a floor, `L` is an empty seat and `#` is an occupied seat):
```
LL.#L
#.L.L
L.L.L
L.L#.
.#L#L
```
Now, since you value privacy a lot, you try to pick a seat that has the minimum number of people visible from it. A seat is visible from another seat if there is no other seat (empty or occupied; floor doesn't count) exactly on the straight line between the two.
For example (rows and columns are numbered from the top left, starting at 1):
* R1C1 sees R2C1 (directly below it) and the two occupied seats on R5 (because the slope does not allow any other seat in between) but does not see R1C4 (blocked by R1C2) or R4C4 (blocked by R3C3).
* R1C2 does not see R5C4 (due to R3C3 at slope 2/1) but sees the other four.
* R3C1 and R4C3 see all five occupied seats.
* R4C1 sees only two.
Therefore, R4C1 is the best choice for you, and the anti-privacy (the number of occupied seats you can see) of that seat is 2.
Given a grid like this, calculate the minimum anti-privacy over all empty seats.
**Input:** A rectangular grid with three distinct values (you can choose which values to use) for floor, empty seat, and occupied seat, respectively. It is guaranteed that the input contains at least one empty seat.
**Output:** The answer to the problem.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
L -> 0
LL# -> 0
####
####
####
###L -> 9
.#L.
L..L
#L#L
LL.# -> 3
LL.#L
#.L.L
L.L.L
L.L#.
.#L#L -> 2
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 122 bytes
```
a=>w=>Math.min(...a.map((x,i)=>a.map((y,j)=>t+=x|y&!a.some((z,k)=>z<2&(p=k-i)*(q=j-k)>0&p/(k%w-i%w)==q/(j%w-k%w)),t=0)|t))
```
[Try it online!](https://tio.run/##VY9NbsIwEIX3PkWqCDJTkgnqljq77lz1AICEFRJwfpyArQYQd08H2iLhxdjvezMjv0p/a5cfTe8T222LsZSjltkgs0/t99QaC0SkqdU9wCk2KLM/cY4rFn4mT9fz9EWT69oC4BLXTC/vb1PoZZ0YfIWDrJIas/m0T6GeDImZDCjlIYWKBQPE2Ms5Xj3i6Avnc@0KF8hgI5QQSoVChHyeCzsUKhKKSIlQsVaKuPN@MSHFXP3XkG7dzDfkj6YFJNc3xkO6sis7S/EeyAcyC5ae3z7fQ7rkqXW6@/XymxcxicjYbXH6KiHnbwf@IaOVjXCNCyEeEajsjh@ad8FSx8GwxtuSvLOuawpquh2UoBE4Pi7GHw "JavaScript (Node.js) – Try It Online")
Input flatten array and width. `L` -> 0, `#` -> 1, `.` -> 2.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 89 bytes
```
WS⊞υι≔⟦⟧θFLυF⌕A§υιL⊞θΣEυ↨¹E⌕Aλ#⬤υ⬤π∨⁼ς.∨∧⁼ρι⁼σκ∨∧⁼ρμ⁼σξ∨⁻×⁻ρι⁻σξ×⁻ρμ⁻σκ∨⁻‹ρι‹μρ⁻‹σκ‹ξσI⌊θ
```
[Try it online!](https://tio.run/##bZFLa8MwEITv/hWLfVmDaug5J7e0EFBoIL2VHkSsxqKSYuuR@t@7Kz9CUuqDrJn9ZgTSsRXueBZ6HH9apSXg1nYxHIJT9oRlCfvoW4wMVLnJau/VyeLHJ4Oe5NfZAXJpT4EIQif9qmxTa4112NpGDnOUQc7ztaxncIgGd6JLwyfhJT4ySHLNauKLnFJJxPnXMXhz@NJHoT1eCKgSQFZtm9V281mL8gy@y/8Yc8cMC7NTNnp8V0b6Zb/UzWIl/wDmFqDjbru49NeSaW8YuPIamKwptYwHBr68@zbZnt4h4LPwIZUqQxfXp8E4cl4VPCsqXvGMr2tRZeSSPz5c9C8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated lines. Explanation:
```
WS⊞υι
```
Input the grid.
```
≔⟦⟧θ
```
Start building up the anti-privacy numbers.
```
FLυF⌕A§υιL
```
Loop over all of the empty seats. (These loops have to use `For` rather than `Map` because Charcoal only has 11 loop variables, I'm already using 10, and each `Map` uses up an extra loop variable. Also, taking the minimum of a doubly nested loop is tricky when the inner loop could be empty.)
```
⊞θΣEυ↨¹E⌕Aλ#⬤υ⬤π∨⁼ς.∨∧⁼ρι⁼σκ∨∧⁼ρμ⁼σξ∨⁻×⁻ρι⁻σξ×⁻ρμ⁻σκ∨⁻‹ρι‹μρ⁻‹σκ‹ξσ
```
Loop over all occupied seats, then check all seats, counting only those occupied seats that are visible.
```
I⌊θ
```
Output the minimum number of visible occupied seats.
To check whether a seat blocks the view between an empty seat and an occupied seat, I need to know:
* That the seat is on the line joining the empty and occupied seats
* That the seat is between the empty and occupied seats
Testing that the seat is on the line is done using the cross product of the displacements - `(s−e)×(s−o)` is zero in that case. Testing that the seat is between the other seats could have been done using the dot product - both `(s−e)⋅(o−e)` and `(s−o)⋅(e−o)` need to be strictly positive. Unfortunately this takes 94 bytes and it was golfier to test that the seat is in the minimal containing rectangle but is not actually either the empty or occupied seat under consideration.
80 bytes using the newer version of Charcoal on ATO:
```
WS⊞υιI⌊ΣEυE⌕AιL↨¹ΣEυE⌕Aν#⬤υ⬤ς∨⁼τ.∨∧⁼σκ⁼δλ∨∧⁼σξ⁼δρ∨⁻×⁻σκ⁻δρ×⁻σξ⁻δλ∨⁻‹σκ‹ξσ⁻‹δλ‹ρδ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZHNSsQwEIDx2qcY2ssEsgVvwp5WURCyuLDexENsuzaYxjWTrL37GF72oOhT-CA-jWmbLutfIJnMl28mgTy_F7W0xb3U2-2rd6vJ0efB02OtdAV4btbeLZ1V5hYZg4WnGj0HxabJIkCHJ5IczpVRjW9wGeZcrjujC2fKlDOtUXFIRco4HEuq8JDDP54JXtZ5XeKHsOFwYfH0wUtN6IKQd0JAM1OOmDjcBRizkoNmfzntN8dGJ7zdE16qpqK4j-2GZDR_CO2-EK7b7yUq2jXp9y0HYruCHvVV8dhyKNnvMX2hm4Lij7xdpZONTq8_hMgzkWS5yEUixjXLk0ADH-Qv "Charcoal – Attempt This Online") Link is to verbose version of code. Byte savings come from being able to use 12 loop variables (particularly useful for the outer loop as I get both the row and index) and being able to flatten a list of lists. A further byte could be saved if at least one seat was occupied.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 148 bytes
```
a->c=concat;[p,q]=[c([[[i,j]|j<-[1..#a],a[i,j]==t]|i<-[1..#a~]])|t<-[1,2]];vecmin([#[1|y<-q,![u*v~>0|z<-c(p,q),!matdet(Mat([u=x-z,v=z-y]~))]]|x<-p])
```
[Try it online!](https://tio.run/##bU5LasMwEL2Kk2ykMgpWtrJ8g55gmMWgJkGhcZWgmNgIX92V1Ba6CMOg99NjAt@9Oof11NiVVe@s@xocR4MBbmTRCUT0cKF06RTq/X7HBFwVayMl/6cuRDLFwuBAZMaju/pB4A51mjp1gw0@3salb9PcKSdyuYTNlePHMYp3jgIf9qlmGO2sJlqkJErPTgWSK4fwOQluVN@Eux9ihttCts1JsJTQYPmvM6g9GsoBRT5AHfP61ZQjbQHQmrx5tCksrykl2SuRX1jNtmJd4/9RdsxPVenNN38D "Pari/GP – Try It Online")
[Answer]
# TypeScript Types, 994 bytes
```
//@ts-ignore
type a<T,N=[]>=T extends`${N["length"]}`?N:a<T,[...N,0]>;type b<A,B>=A extends[...B,...infer X]?b<X,B>:A;type c<A,B>=[]extends A|B?Exclude<A|B,[]>:c<B,b<A,B>>;type d<A,B,X=0>=B extends[infer Y,...infer B]?d<e<A,[Y[],[1,0]][X][Y]>,B,X>:A;type e<T,P=0,N=[1,0][P]>=T extends[N,...infer T]?T:[...T,P];type f<T>=d<[],T,1>;type g<T,N=[]>=(T extends T?(x:()=>T)=>0:0)extends(x:infer U)=>0?U extends()=>infer V?g<Exclude<T,V>,[...N,0]>:N:0;type h<G,P,S,Q=[d<P[0],S[0]>,d<P[1],S[1]>],V=G[Q[0]["length"]][Q[1]["length"]]>=Q extends 0[][]?[2,V]extends[V,2]?Q:[0,V]extends[V,0]?h<G,Q,S>:never:never;type i<T,K=keyof T>=T extends T?keyof T extends K?T:never:0;type M<G,P={[X in keyof G]:G[X]extends infer R?{[Y in keyof R]:[a<X>,a<Y>]}:0}[number][number],S=(P extends P?c<P[0],P[1]>extends[0]?P|[f<P[0]>,P[1]]|[P[0],f<P[1]>]|[f<P[0]>,f<P[1]>]:never:0),>=i<{[X in keyof G]:G[X]extends infer R?{[Y in keyof R]:R[Y]extends 1?g<S extends S?h<G,[a<X>,a<Y>],S>:0>:never}:0}[number][number]>["length"]
```
[Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4AVAGgDkBeAbQF0A+W8w9AD3HUQBNIAAwAkAb2r0ARABte8cAAtJjAL6CA-NQBcZKvQB0h6pQAMLANy4ChAEakAgpQBCrex268BBw08qH9sIgAZuiohAAajOp24c7MWvaW+EQAxg5xDIxcPPyQhPYAPk7qAKKcKdIArnzoDkWUTPFpvnaOLsxJ1nzpvuG0JqxO7jlegSFhAJp+hmOhhE5R3bWO9BNMDQCMpoyM9JGrLM6U4fGJVkS1VAAK-TQMW2b0Vyxsw56Q9Mb+s2HkUeRabz6a6MTpEIIUVjddZUDYdc6EeAUO6NWgACnY2XehHI6jRnC0aIAlLRmOQScwTFoTESsbl8VofoQAKoUkzqZlvekUpkANXUSLKFWql0ovOYDX8xjM8W0JjBhAUpAA4pQrpQAMqUACKDG6V3oZk1hsO+voG0YxotzEtvNoyvo2pNUlkiHkSh2jvNuxkckUyhe2q5AkIJiYTHU9AATGKsh5cvReZQo1FtYCTLG6V4k2Z1ErVdrNfFEOgAG6hLQl8uoBWwZEAaVoAGt0DhkEEcaxMfGQ7iW22O92Rnl6+oAVWK-KEQBZFVq2iiPaEQKEfvtwjKxhaB2RLN5JkAJXUi4my8Qq9b64PW-oZBOlDIExtKmpKnoiEqAFsbKFdh-v7+mrolcwZ5Fc6hpAaRoGtae4muoVwFPQEJQYcME7EhqGUCh3o2khOEythpDoTalZlpORKUKwdaLuEZ4XgOG5bjucbDme4yEEeJ70WuHbXloB4HHuhAbAKpAaqBhAanmc63qQ96PjaRbUsW5GoC+Jhvv+P6oH+X46SwLp+h6mDYMkOImIQtCELO9CYCAhCOQAeuomCOd6lCYCwpkIuQGxWTZpB2Q5zmue5WxbCmnneWZ1jkFGAW2fZwCOYQLluYQ0bJtlUUZVlMYFZaeUFTlRXuSVMYWtFzA+eZ5AAMyJUFyWpel7kZpV2yeeFpi9VVxWUJFg1lZlEW9blMW+QALE1wUpaFeVjR1w3dZlMYZg8K2LX1fUjeaO3rXty1Df13lAA)
## Ungolfed / Explanation
```
// Convert a string literal representing a number to a `Nat`
type StrNumToNat<T, N=[]> = T extends `${N["length"]}` ? N : StrNumToNat<T, [...N, 0]>
type ModNat<A, B> = A extends [...B, ...infer X] ? ModNat<X, B> : A
// Calculate the GCD of two `Nat`s using the Euclidean algorithm
type GcdNat<A, B> = [] extends A | B ? Exclude<A | B, []> : GcdNat<B, ModNat<A, B>>
// Add if `X` is `0`, subtract if `X` is `1`
type AddOrSubInt<A, B, X=0> = B extends [infer Y, ...infer B] ? AddOrSubInt<IncOrDecInt<A, [Y[],[1,0]][X][Y]>, B, X> : A
// Increment if `P` is `0`, decrement if `P` is `1`
type IncOrDecInt<T, P=0, N=[1,0][P]> = T extends [N, ...infer T] ? T : [...T, P]
type NegInt<T> = AddOrSubInt<[], T, 1>
type CountUnion<T,N=[]>=(T extends T?(x:()=>T)=>0:0)extends(x:infer U)=>0?U extends()=>infer V?CountUnion<Exclude<T,V>,[...N,0]>:N:0;
// Filter a union of tuples for those with the shortest length
type Shortest<T, K=keyof T> = T extends T ? keyof T extends K ? T : never : 0
// Extrapolate the line of sight for a given slope.
// If the first seat is occupied, return its position; otherwise, return never.
type GetSeat<
Grid,
Pos,
Slope,
// Add Slope to Pos
NextPos = [AddOrSubInt<Pos[0], Slope[0]>, AddOrSubInt<Pos[1], Slope[1]>],
// Get the value at NextPos
NextSeatVal = Grid[NextPos[0]["length"]][NextPos[1]["length"]],
> =
// Both coordinates of NextPos are non-negative
NextPos extends 0[][]
// If NextSeatVal == 2
? [2, NextSeatVal] extends [NextSeatVal, 2]
// Return NextPos
? NextPos
// Otherwise, if NextSeatVal == 0
: [0, NextSeatVal] extends [NextSeatVal, 0]
// Continue down the line of sight
? GetSeat<Grid, NextPos, Slope>
// Otherwise, return never
: never
: never
type Main<
Grid,
Positions = {
// Map over the rows
[X in keyof Grid]: Grid[X] extends infer Row ? {
// Map over the cells
[Y in keyof Row]:
// Return the coordinate as a [Nat, Nat]
[StrNumToNat<X>, StrNumToNat<Y>]
} : 0
// Collect a union of all results
}[number][number],
Slopes = (
// Map over Positions
Positions extends Positions
// (note that Positions is now a singular [Nat, Nat])
// If X and Y are coprime
? GcdNat<Positions[0], Positions[1]> extends [0]
// Return a union of this slope and all reflections of it
? Positions
| [NegInt<Positions[0]>, Positions[1]]
| [Positions[0], NegInt<Positions[1]>]
| [NegInt<Positions[0]>, NegInt<Positions[1]>]
: never
: 0
),
> =
// Get the shortest of:
Shortest<
{
// Map over the rows
[X in keyof Grid]: Grid[X] extends infer Row ? {
// Map over the cells
[Y in keyof Row]:
// If this seat is empty
Row[Y] extends 1
// Return the number of slopes where an occupied seat is visible
? CountUnion<Slopes extends Slopes ? GetSeat<Grid, [StrNumToNat<X>, StrNumToNat<Y>], Slopes> : 0>
// Otherwise, return never
: never
} : 0
// Unionize
}[number][number]
// To number
>["length"]
```
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 95 bytes
```
Min[p=Position;Count[Or@@@#,1<0]&/@Outer[Det@{u=#-#3,v=#3-#2}==0<u.v&,#~p~1,#~p~2,p[#,1|2],1]]&
```
[Try it online!](https://tio.run/##lU6xCoMwFNz9igcBp1iTONaUQLsW3UMGKUozVMVGF6u/blNjFZdC4XjcO@6Oe2Tmnj8yo2/ZVACfrrqUNU@rpza6Ko/nqi2NTBohBMI0JsoPRdKavJGX3Ii@5ShAEe44igLEBs5J3B46H6OxHul8Ga6lTb6YwlQpf0obbQsRBCcoJFIKfAiFB33f02HAHlhGMViw78ssd5gF@EdYO4l7MZDF8qEz6JahS2Z1OBPbDyM7F3Mluyr6S2PbhnWUWzpMbw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Python3, 363 bytes:
```
from math import*
r=range
k=lambda x,y:(x//(c:=gcd(x,y)),y//c)
def p(i,t,b,x,y):
if i==t:return 1
return((u:=b[(n:=i[0]+x)][(m:=i[1]+y)])!='L'or(n,m)==t)and u!='#'and p((n,m),t,b,x,y)
g=lambda b,d:min([sum([p(i,j,b,*k(j[0]-i[0],j[1]-i[1]))for i in d if d[i]=='#'])for j in d if d[j]=='L'])
f=lambda b:g(b,{(x,y):b[x][y]for x in r(len(b))for y in r(len(b[x]))})
```
[try it online!](https://tio.run/##hVDLboMwEDzXX@GGA@vEIY16qSz5D6z@AEUVhEdMsEHGSKCq305t0lSpVBUfrN2d3Z3Z6SZ7bvXzS2fmuTStwiq1ZyxV1xq7RYabVFcFuvAmVVme4pFODMbDAU6MV6ccXE4InQ6HE8EoL0rcgaSWZtQDDGFZYsm5Zaawg9H4iPA1AhgYz2LQjMv4KdmNJIlB@eSY7CaSkEceirA1oKkibgFJdY4HVwxCH3WwAD9MqLoJzGjOlNQQ94OC2KupXc/2ArWj2XsuWjuOvScipGwNllhqnHuleSwT7imSBajvgNoDwgGo/GFiFWT0Y7GAZfGYxFPix0Y/ZqApNGRXhumu4voI@SRzzzebjRBRIFAQiUggcfuDCLlqIBy@OGrb96xNTQ69N/Th28lG9hZU2oEPKC5lYwsDr60uKO6jvmukhfBNh8Q9hDojtYUS7na58lWD5/kPF8FKR@Ae@vWt7XT3Re5Ud68/FHkbVlWsOPXn7PwF)
] |
[Question]
[
All variables in this question are integer valued.
# Input
4 integers w, x, y, z. They can be positive or negative and will be less than 1048576 in absolute value.
# Output
The general solution to the equation.
\$ aw+bx+cy+dz = 0 \$.
The variables \$a, b, c, d\$ must all be integer values.
# Output format
Your output should consist of three tuples each with four parts, one for each of the values a, b, c, d. Let me explain by example:
```
Input: -118, 989, 918, -512
Mathematical answer:
b = 2 n_0
c = 9 n_0 + 256 n_1 + 81 a
d = 20 n_0 + 459 n_1 + 145 a
```
Explanation: `n_0` and `n_1` are integers that you can set to anything you like. The solution says: `a` can also be set to any integer value, `b` must be twice whatever you set `n_0` to.
This means that `a` can be set to any integer, `c` can now be calculated in terms of three variables we have already set and so can `d`.
The format of your output should be 3 tuples (#,#,#,#), (#,#,#,#), (#,#,#,#). We can assume three free integer variables n0, n1 and n2 and so (a,b,c,d) = (#,#,#,#)n0 + (#,#,#,#)n1 + (#,#,#,#)n2. In the example above the output would therefore be:
```
Output: (0, 2, 9, 20), (0, 0, 256, 459), (1, 0, 81, 145)
```
# Examples
Example one:
```
Input: -6, 3, 7, 8
Mathematical answer:
c = 2a + 3b + 8n
d = -a - 3b - 7n
n is any integer
Output: (1, 0, 2, -1), (0, 1, 3, -3), (0, 0, 8, -7)
```
Example two:
```
Input: -116, 60, 897, 578
Mathematical answer:
c = 578 n + 158 a + 576 b
d = -897 n - 245 a - 894 b
n is any integer
Output: (1, 0, 158, -245), (0, 1, 576, -894), (0, 0, 578, -897)
```
Example three:
```
Input: 159, -736, -845, -96
Output: (1, 0, 27, -236), (0, 1, 64, -571), (0, 0, 96, -845)
```
# Discussion
To understand this challenge further it is worth looking at this possible general solution which does **not** work `[(z, 0, 0, -w), (0, z, 0, -x), (0, 0, z, -y)]`. The problem with this is that there are solutions to the problem instances above which are not the sum of any integer multiples of those tuples. For example: take input -6, 3, 7, 8 from Example 1. The proposed solution would give the tuples:
```
(8, 0, 0, 6), (0, 8, 0, -3), (0, 0, 8, -7)
```
Why doesn't this work?
There is a solution for this instance with a = 1, b = 1, c = 13, d = -11 because `-6+3+7*13-11*8 = 0`. However there are no integers n\_0, n\_1, n\_2 to make `n_0 * (8, 0, 0, 6) + n_1 * (0, 8, 0, -3) + n_2 * (0, 0, 8, -7) = (1, 1, 13, -11)` .
[Answer]
# [Python 2](https://docs.python.org/2/), 182 bytes
```
def E(a,b):
if b:x,y,d=E(b,a%b);return y,x-a/b*y,d
return 1,0,a
def f(a,b,c,d):x,y,g=E(a,b);z,w,h=E(c,d);j=E(g,h)[2];return(b/g,-a/g,0,0),(0,0,d/h,-c/h),(-x*h/j,-y*h/j,z*g/j,w*g/j)
```
[Try it online!](https://tio.run/##dVLLbsJADLzvV1iqKnapVyTQvIjSG19R9ZAHJHBIEaLK4@fT8RIBFy6OPWNPvNach2vz266nN7K@HzMlcYIgmQ38tQIcMm2YIqZYuSbUoYcqARREAvoBZmy0AWPjzwAxCdVisVB5Tx9UDAjliFB1lJGnasS6rHTOhVHNXJRcmXs/oNZXj5mmXSsgKJE5jdM8VnNjFJiMdLM6mXajXIPV9a3S@ao2oqoLJIOj5kZdrhojv9AVEvnN6yGf7Bf10iKI20Tb3rsppSQt2uYPavBe/sRJjTIgCLYFN3r1rOTWsOWd6WZGzjlV@wPt3Nm2io4HKrY9D1xlO11w/l6Y9LK//l1aGrjHMsUSnKIZ89njXInCQRRY7u3G6@wmmY7ccYNCmPSERG77vf6ZVeXlLG@EkGdYIzJewG5ZxjWWeDLbwX3GJdbmTqKZzpdje9UH7Qwm/hJ7ibuMUXcu5A1HHD9DYjU4TYwGnz0x4jdnN@c2mM2Y6R8 "Python 2 – Try It Online")
Yes, it is possible to solve it without fancy built-ins. And this gives relatively good results for a non-LLL one.
### How it works
I derived a closed-form solution in the following steps: (I flipped the roles of \$a,b,c,d\$ and \$w,x,y,z\$ because it looked much more natural to me. So \$a,b,c,d\$ are coefficients and \$w,x,y,z\$ are unknowns here.)
$$
ax+by+cz+dw = 0
$$
If we define \$g=\gcd(a,b)\$ and \$h=\gcd(c,d)\$, the following substitutions can be done without loss of generality: (\$u,v\$ are temporary integer variables)
$$
ax+by = gu\\
cz+dw = hv
$$
which results in a system of two heterogeneous and one homogeneous 2-variable linear Diophantine equations:
$$
ax+by = gu \\
cz+dw = hv \\
gu + hv = 0
$$
Then we can apply the textbook procedure:
$$
u = \frac{h}{j}n\_3, \; v = \frac{-g}{j}n\_3 \quad \text{where} \; j = \gcd(g,h)
$$
If we let \$(x\_0,y\_0)\$ be a "special" solution to \$ax+by=g\$ and similarly \$(z\_0,w\_0)\$, then the solutions are
$$
\begin{align}
x &= \frac{b}{g}n\_1 + \frac{-x\_0h}{j}n\_3 \\
y &= \frac{-a}{g}n\_1 + \frac{-y\_0h}{j}n\_3 \\
z &= \frac{d}{h}n\_2 + \frac{z\_0g}{j}n\_3 \\
w &= \frac{-c}{h}n\_2 + \frac{w\_0g}{j}n\_3
\end{align}
$$
The special solutions can be found via Extended Euclidean algorithm. Special mention goes to [this deceptively short and yet correct implementation of EGCD](https://github.com/sympy/sympy/pull/2168/files#diff-8b8a26ba997d624245be0a39f6a11a0faa0580739d04e058cab8a83a44e25833R231), once added to sympy but removed later:
```
def extended_euclid(a, b):
if b == 0:
return (1, 0, a)
x0, y0, d = extended_euclid(b, a%b)
x, y = y0, x0 - (a//b) * y0
return x, y, d
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 39 bytes
Still a built-in.
`HermiteDecomposition` gives the [Hermite normal form](https://mathworld.wolfram.com/HermiteNormalForm.html) decomposition of an integer matrix.
```
HermiteDecomposition[List/@#][[1,2;;]]&
```
[Try it online!](https://tio.run/##HYuxCoMwFEV/5UHAKcE@bTRBWhw6dOjQPWQQiTRDTNFskm9PX10u95zLDVP6uDAlP09lgVt5ui345B5ujuEbd598XM3L76kemTUGeTMM1lblvfk1GQbiDoth1kIF9QjHIRAVB600xb8JiU3mcIiOQ8uh56BORCTRXQg1OdmfFiXdRN/SJNRVUuou5/ID "Wolfram Language (Mathematica) – Try It Online")
---
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), without build-in, 118 bytes
Based on Algorithm 2.4.10 in *A Course in Computational Algebraic Number Theory* by Henri Cohen.
The output is sometimes extremely large. You can reduce them with the build-in `LatticeReduce`.
```
(a=#[[1]];U=IdentityMatrix@4;Do[{d,u}=ExtendedGCD[a,b=#[[j]]];U[[{1,j}]]={u,{-b,a}/d}.U[[{1,j}]];a=d,{j,2,4}];Rest@U)&
```
[Try it online!](https://tio.run/##tVDLasMwELznK5YYQgurpEr8rFExNKUUUiiBnIQOSqQQG@JCuoYUoW93ZefQ/kAvw84Mwwx71nSyZ031QfdHEP2dFpGUXKlyJ96Mbamm73dNl/paxeX6UzqDnRcvV7Ktseb1eS017odIo4aMlI5j45USrkPH9qj9wvj5r15qYdA1uMTYq3Jrv6ja3c/6j0vdkoyAPcFRRkrBDBYVOMc4zxGKvAgwXCzhS4/gWIqwQsgQ8pFyHoT0IdAiaEk2qjwJMZatgsXyOAlYpN5Pbl3TrTXdwZpHmKrJn/qNpvAMe3PlOOY/1/Q/ "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [SageMath](https://www.sagemath.org/), 92 bytes
```
def f(x,y,z,w):
for v in'abcd':var(v,domain=ZZ)
return solve([a*x+b*y+c*z+d*w==0],a,b,c,d)
```
[Try it online!](https://sagecell.sagemath.org/?z=eJwVjcsOgyAUBfd8xd0JeElqm7Zqwo9IWKBIYtJCQyk-vr54FpNZzbGzA0c33PHAlfUEXIiQYfGVGSdb9dlEmtGGt1m8HAZGIM7pFz18wyvPVBm-1SPf64kfteWrlBeNBkec0DJCzlgqMVBKPBBuCE-EViMo0TQtQtd2BaeJe3PVuvyXfeLiE3WUJ8b-HfUspw==&lang=sage&interacts=eJyLjgUAARUAuQ==)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 21 bytes
Another boring built-in answer.
>
> matkerint(x,{flag=0}): LLL-reduced Z-basis of the kernel of the matrix x with integral entries. flag is deprecated, and may be set to 0 or 1 for backward compatibility.
>
>
>
```
a->matkerint(Mat(a))~
```
[Try it online!](https://tio.run/##HYs7CgMxDESvIraywYIoG/@K7A1ygsWFimxY8kEsbtLk6o7sZph5TxI@dnxI2@DaGJc31@f92D/V3LgatvbXWOT1NQy4gAzDMPUxwdYPHKwrEiUHOWWN3tDTuajA4GB2EB2kMYkUhJPOrMzHQcnrG8ZZFaaL18yhFNv@ "Pari/GP – Try It Online")
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/210301/edit).
Closed 3 years ago.
[Improve this question](/posts/210301/edit)
**Problem Statement**:
You will receive a substring of a palindromic string. You must return the index of the substring which marks the point of reflection of the original string. You are only provided the substring, which is not necessarily a palindrome because it is not necessarily centered about the middle of the original palindromic string.
**Input**: Substring of length `2n + 1, 1 <= n <= 1000`, which encompasses the center of reflection of some larger palindromic string.
**Output**: Return the index of the substring which marks the point of reflection. May be 0-indexed or 1-indexed.
**Test cases** (character at desired index is bold to show the desired output more clearly):
*Input*
1. manaplana**c**analpan
2. car**o**racati
3. wlatem**y**meta
4. na**s**anita
*Output*
1. 9 (the full string was “a man a plan a canal panama”, with spaces removed)
2. 4 (the full string was “was it a car or a cat i saw”, with spaces removed)
3. 6 (the full string was “mr owl are my metal worm”, with spaces removed)
4. 2 (the full string was “oozy rat in a sanitary zoo”, with spaces removed)
**Winning Criterion**: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") Shortest code in bytes wins.
**Assumption**: Assume there is just a single candidate palindrome
**Restriction**:`0` and `2n` (last index) are invalid output.
[Answer]
# [J](http://jsoftware.com/), 26 25 bytes
```
[:(-:@i.>./)[:(*/*#)/.=/~
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o600dK0cMvXs9PQ1gWwtfS1lTX09W/26/5pcXFypyRn5CmkK6rmJeYkFOUAiGYhzChLz1BX8nPQULOEKgBJF@UVAsiQTImUClyrPSSxJza3MTS1JhEiZwaXyEosT8zJh4kb/AQ "J – Try It Online")
## how
`=/~` creates a function table comparing all possible pairs of characters. Taking `'nasanita'` as an example:
```
1 0 0 0 1 0 0 0
0 1 0 1 0 0 0 1
0 0 1 0 0 0 0 0
0 1 0 1 0 0 0 1
1 0 0 0 1 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 0 0 1 0
0 1 0 1 0 0 0 1
```
Notice the `/`-direction diagonals. If one of those is all ones, it corresponds to an embedded palindrome.
J has an adverb `/.` which lets us to apply a verb to each diagonal.
We choose the verb `(*/*#)` -- the sum multiplied by the length. Thus it will be the length of the diagonal if it's all ones, and 0 otherwise:
```
1 0 0 0 5 0 0 0 0 0 0 0 0 0 1
```
`i.>./` Find the index of the max element within that list. In this case the index of 5 is 4.
`-:@` And divide it by 2.
[Answer]
# [Python 2](https://docs.python.org/2/), 65 bytes
```
f=lambda s,n=1:n*(s[n+1:2*n+1]==s[n-1:n-len(s)<<1:-1])or f(s,n+1)
```
[Try it online!](https://tio.run/##LY7NCsMgDIDP7VPkUtT@HOxR6pMUD9naMkFTqcIo7N27dAzMl3yBJKazvHYar2uzAeNjQcg9WW2olXmmTpuxZTpr2QZuD2ElmdU0aTNop/YDNskTnVbXxpLBE8wiImEKjCdHSEiiB8Fy7Aez@FvfAcsaz7gWvJUwI3munakrD/beq@oqHZ6KFE020Cwgm/z5PSWgAT4Mvoc8G@/u9Cd/2ilVX18 "Python 2 – Try It Online")
---
Consider the string `abcdefg`. Here's what it looks like checking for palindromes around each character:
```
abcdefg
a c
ab de
abc efg
cd fg
e g
```
We see for the right string, the index goes from `n+1` to `2*n+1`. The left string is trickier, but looking in reverse (starting from the end of the string) we start at `n-1` and move to `2*(n-len(s))` (this is a negative number that indexes from the back of the string). Since we can assume there is only one viable palindrome candidate, we can terminate early if we find one.
---
### Python 3.8, 72 bytes
```
f=lambda s,t='':(max(k:=s[1:],t).find(min(k,t))==0)*len(t)or f(k,s[0]+t)
```
[Try it online!](https://tio.run/##LY5BasQwDEXXk1NoE2x1TJnSTTH4JCELtUmoGVsxlqAd6N1TpRSk9/W0EGoP/dz59a3149hSofq@EEjQ5Fz0lb79PSaZXuIcFJ@3zIuvmf3dDFO64VNZ2SvuHTZbynSbr4rHZi6QGSZXiakVw4d1acQugDPpezdqPvWrkK71UVelU5mEONs8x@GSIdlpweHSemb1bpQI4wJ@lJ@/QgcjeAmQA8gU83zGP6/2N@Jw/AI "Python 3.8 (pre-release) – Try It Online")
This approach seemed promising but was just longer.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 53 bytes
```
Lv$`((.)+).(?<-2>\2)+(?(2)(?!))
$.1;$.($`$1
N`
L`\d+$
```
[Try it online!](https://tio.run/##DcbBCgIhEIDh@7xFMMEMsoJeizx2WXqCPTiUB0GnxaTYpzcP/8ffUs8qbpzpHsf6xUhk2bClcF38bfNsKJBnCidmQOsuaAkjOnhEWOP2MjhGFZW9TJ6zsovCvPZu057hV6SnetTUBVQ@ornLHw "Retina – Try It Online") Link includes test cases. 0-indexed. Explanation:
```
((.)+).(?<-2>\2)+(?(2)(?!))
```
Match and separately capture a number of characters in `\2`, then match the centre character, then match and pop each character from `\2`, ensuring that all matched characters get popped. This therefore ensures that the whole match is a palindrome.
```
Lv$`
$.1;$.($`$1
```
Consider all overlapping matches and output the length of the palindromic prefix and position of the centre (which is the position of the match plus the length of the palindromic prefix).
```
N`
```
Sort in order of length.
```
L`\d+$
```
Take the position of the last (i.e. longest) match.
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), ~~47~~ 40 bytes
```
{m:ex/.+)>.<{$/.flip}>/.max(*.chars).to}
```
[Try it online!](https://tio.run/##DYuxCgMhEAV7v8IihFwCa5ciJPcvj0OJsKuyCjk57tuNxQzTTPHKzyHdXoP9jENefnf0WFZ6HxdHgWM5V0eC/Xan7QutC7V8jopuaS4hq@WYfB2ChMJT24QLkpmlWadbND9G89LFN5iEihQb/g "Perl 6 – Try It Online")
Match all palindromes in the string, find the maximum length one, and output its center index.
] |
[Question]
[
**This question already has answers here**:
[Stack Exchange Vote Counter](/questions/82609/stack-exchange-vote-counter)
(15 answers)
Closed 3 years ago.
Inspired by [this](https://www.youtube.com/watch?v=BxV14h0kFs0) Youtube Video from Tom Scott.
Write a program or function that prints the current amount of views this question has.
That's it.
Your program may only access the stack exchange api, any other websites are disallowed.
## Output
An integer with the exact amount of views this question has at the moment. Outputs with the `k` for thousand are disallowed.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~46~~ ~~42~~ 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
**Reading from the question-URL: 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**
```
’ƒËŠˆ.‚‹º.ŒŒ/q/’žYì•3X&•«.w'Ž‡¡1èþ¨
```
-6 bytes thanks to *@CommandMaster*, by reading from this question's URL instead of the API
No direct TIO, since the `.w` builtin (to access a website) is disabled on TIO. But:
```
’ƒËŠˆ.‚‹º.ŒŒ/q/’žYì•3X&•«
```
[Try this part online to see the generation of the URL.](https://tio.run/##yy9OTMpM/f//UcPMY5MOdx9dcLpN73DTo4ZZjxp2Htqld3TS0Un6hfpA2aP7Ig@vedSwyDhCDUgeWv3/PwA)
```
'Ž‡¡1èþ¨
```
[Try this part online to see the extraction of the amount of views from the HTML content.](https://tio.run/##7X3bltzGkeA7vyJdGpvkTAON@6XJbg3VJE16SUsWKdoey6cPCsiqAokCSgCqL@TonPmDfdiHfZ6XPfMTuw8zZ3/EP@KNiExcC6gLSVGyV5TIAhKZkZGRkZERkZGZWRFMY/7Xv97@v//7L//27//57/p//cd//Z///I@//nUymdz/RZSF5c2Ks0W5TM5u3ccfFpd8WYTZip9OJvSCOU4ni7JcnRwfF@GCLwM1y@fHv3vwVTDnExYmQVFghmVycZHzYpWlRXzJJ2f3FzyIzm7dYvLP/TIuE34WZhFn8yyZMYW9XMQF@92aF2WcpexJULAL/MNexfyqgO/nmPfXmPdFGYRv2KPrcBGkc37/WMBqYCdx@oblPDmdFIssL8N1yeIwSydskfOZQL8A/MMoVYuiDMo4VFNeHr@AFhbHiBJid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SwxqxzRxbYSohHZYhWaQXn3QNa6/LrFDSyOEHdvZsDzC1yBTUbYqt7t7adFtEmrWJ5pu6afcq2Gse62BD1ZKHRyLoqr9CHC9Z73@KYr3IKpaYFilxKMBo3dl2NXIM4AFNEgAI/pMY@kHuByp0JqOuw2TDjJeT1ijWPCl183g7e@kZE/52LLN1YvIr40MMFSBS8LB5xl@Gd5Pnk0t21I0z7gPvWREjm@569y3RzQVFRdqJ4zNv/EvDBw9/271Y0jXFV/JA@HfKrNtCGwqWmc/QJpCDixFG27ahdIWn0yh@Y8wiDR7ud/Rjh1l09GNgn@/9x7TuomOAQ98GHX0GP/yAO78kHJt4MZi2MS8VZmKqT4A17C@eV@cSny@6MJ@ZenDG@l3/HYeADHIJO@zZ34LsSpJGCt4bvIYymWXSzL3f9mMqy@felLNs/K8s7lGXnZ2X5p68sm7vjtkYFSCVxcNVvcvYUY5doTXgdJMkNm2c47YEysMpWIi4ouI6X66U4KKi6vUrEEk3XsxnPVfbFDSXSDrQrjouT4UJEVokpZwGQOcY5wUsNf4oRSiVothxqLfEu2YCUEOi9S67u1ZJPLAqtvy9R6P4sCneIQu9nUfjTF4XWNr/BX/7tf/wqnRare30XvG9ojn@84iXuEVjWerJ5ZFk2G7iCu7a5ClypgXIvsNywmTEkbHEHbtud3uyvqHKIRVdp9slEYRNfVAt2o8s95omlnVju8HKPgvupoGuMjUWfVnDd3h7c6tyDQZvfex@b3/vZ5v/Z5v/Z5v/Z5v/Z5v@JKLr235ei6/@s6O5QdHXtZ033p6/p2h/N6Ic5AVRRYC8wvWd4PAXZ5Jv7kuRGJCb393w@mUz@Hw) (Input doesn't contain the entire HTML content, because the TIO URL would extend 65k+ characters and be too big to post, haha.. xD)
**Reading from the API: ~~46~~ 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**
```
•3X&•’¸¸.‚‹º.ŒŒ/…é/ÿ?€¼=ƒËŠˆ’žYì.w'š‹¡Åsþ
```
No direct TIO, since the `.w` builtin (to access a website) is disabled on TIO. But:
```
•3X&•’¸¸.‚‹º.ŒŒ/…é/ÿ?€¼=ƒËŠˆ’žYì
```
[Try this part online to see the generation of the API-URL.](https://tio.run/##AUoAtf9vc2FiaWX//@KAojNYJuKAouKAmcK4wrguw4LigJrigLnCui7FksWSL@KApsOpL8O/P@KCrMK8PcaSw4vFoMuG4oCZxb5Zw6z//w)
```
'š‹¡Åsþ
```
[Try this part online to see the extraction of the amount of views from the JSON.](https://tio.run/##lVFLjhMxEL1KVAvYdKc/k5BMSyOWsEVCbBCyiu6KU5puu8eunkyIIrHhIHMMNiwYcREuEmxnIsESLyzX5z3Xe2U9fmY6nV7@evz99fvPx6dv/unH6XQAFho8NB8PIKjjA1rbUa5tv4EMvGB7m9NDu0WjKceR4VMGdmfIQXMAR@MkKGwNNNWyWmUweXKKO2jq62VdPseyHwma0K3ZCznqAvPo7IZ7UjygjsWtyOibouB5@nPOg57cvLVDcVe9afV8NPq1v6nq9Qt9UwV8x37sca8MDhHOX3o2IR3u27/YopYo5Ux60ZFo42S@SGMWZ/QxA/YKjd@lGRtxE2Vwz7RTrZ2MBI2LDM71S6YOHrXWUXr16EVhK3zPslcdCkVb1qtyUS9W6wxaR8msf0plvX6Vwd1EPpWSd@XV8rr8HzEXeBCUsIVs2eeXbL5Fn0cdPjgkLH107H3omL177pi9RT9T8cw@pL5jWHNAqSFp22DvKQ5pBdWAD9BcleUldjQgGzY6Lf34Bw)
**Explanation:**
```
’ƒËŠˆ.‚‹º.ŒŒ/q/’
# Push dictionary string "codegolf.stackexchange.com/q/"
žY # Push builtin "https://"
ì # And prepend it in front of the url
•3X&• # Push compressed integer 203590 (the id of this question)
« # Append it to the url
.w # Access this URL and read its contents
'Ž‡ '# Push dictionary string "wed"
¡ # Split the HTML on this word
1è # Get the second item (at index 1)
# (i.e. ` 119 times">\n <span class="fc-light mr2">Vie`)
þ # Only leave the digits (i.e. 1992)
¨ # And remove the last digit (2), that was part of the class
# (after which it is output implicitly as result)
•3X&• # Push compressed integer 203590 (the id of this question)
’¸¸.‚‹º.ŒŒ/…é/ÿ?€¼=ƒËŠˆ’
# Push dictionary string "api.stackexchange.com/questions/ÿ?site=codegolf",
# where the `ÿ` is automatically filled with this integer
žY # Push builtin "https://"
ì # And prepend it in front of the url
.w # Access this URL and read its contents
'š‹ '# Push dictionary string "count"
¡ # Split the JSON on this word:
# (i.e. `...,"view_count":14,"answer_count":2,...` will be split to
# [`...,"view_`, `":14,"answer_`, `":2,...`])
Ås # Pop and only leave the middle item (i.e. `":14,"answer_`)
þ # Pop and only leave its digits (i.e. 14)
# (after which it is output implicitly as result)
```
[See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `’ƒËŠˆ.‚‹º.ŒŒ/q/’` is `"codegolf.stackexchange.com/q/"`; `•3X&•` is `203590`; `'Ž‡` is `"wed"`; `’¸¸.‚‹º.ŒŒ/…é/ÿ?€¼=ƒËŠˆ’` is `"api.stackexchange.com/questions/ÿ?site=codegolf"`; and `'š‹` is `"count"`.
[Answer]
# Google Sheets, ~~99~~ 95 bytes
```
=Mid(Index(ImportData("https://api.stackexchange.com/questions/203590?site=codegolf"),10),12,99
```
Sheets will add the trailing parentheses automatically.
`ImportData` will treat the result as a CSV and split the text into columns.
`Index(~,10)` pulls the 10th entry from that split result.
`Mid(~,12,99)` starts at the 12th character and pulls up to the next 99.
So long as the view count doesn't get to 10^99, this will work fine.
Here's a screenshot showing the three steps:
[](https://i.stack.imgur.com/KIGM5.png)
[Answer]
# JavaScript (browser), ~~129~~ ~~121~~ ~~129~~ 117 bytes
-12 bytes thanks to Kevin Cruijssen, Command Master!
```
await fetch`//api.stackexchange.com/questions/203590?site=codegolf`.then(x=>x.json()).then(x=>x.items[0].view_count)
```
## Another version, not using await (~~136~~ ~~128~~ 136 bytes):
```
fetch('https://api.stackexchange.com/2.2/questions/203590?site=codegolf').then(x=>x.json()).then(x=>console.log(x.items[0].view_count))
```
[Answer]
# Python 2, ~~125~~ 117 bytes
*-6 bytes thanks to Kaddath*
Using only the standard library, unlike the other python answer.
```
from urllib import*
x=urlopen("http://codegolf.stackexchange.com/q/203590").read()
print x[x.find("wed"):].split()[1]
```
# Python 3, ~~149~~ 142 bytes
*-6 bytes thanks to Kaddath*
```
from urllib.request import*
x=urlopen("http://codegolf.stackexchange.com/q/203590").read().decode("utf-8")
print(x[x.find("wed"):].split()[1])
```
[Answer]
## sh, 96 bytes
```
wget -qO- http://codegolf.stackexchange.com/questions/203590|sed -n 's/.*\(V.*mes\).*/\1/p;540q'
```
This assumes the presence of `wget` and `sed`. We can save 5 bytes (the `;540q` part) if we can assume there's no more match of `V.*mes` on the page -- as of this writing, there isn't, but that may not be true after more submissions. This also assumes the first part of the page is fairly static, and the `Viewed XXX times` sentence appears uniquely before line 540 (which it currently does).
## sh, 101 bytes
```
wget -qO- http://codegolf.stackexchange.com/questions/203590|sed -n 's/.*\(V.*mes\).*/\1/p;/V.*mes/q
```
Similar to the above, but this variation does not depend on which line the `Viewed XXX times` appears -- it terminates after the finding the first one.
[Answer]
# [PHP](https://php.net/), ~~96~~ 89 bytes
```
<?=split(' ',strstr(join(file('http://codegolf.stackexchange.com/q/203590')),'wed '))[1];
```
Inspired by @newbie's answer. I think I can do better, still a first try. I strangely only got malformed characters from the JSON api :/
EDIT gained 7 bytes using `split` and `strstr` instead of `preg_match`
[Answer]
# [Python 2](https://docs.python.org/2/) with `requests`, 113 bytes
```
from requests import*
t=get('http://codegolf.stackexchange.com/q/203590').text
print t[t.find('wed'):].split()[1]
```
A pair of `()` is needed for Python 3 (114 bytes).
[Answer]
# T-SQL, 43 bytes
T-SQL executed directly against the [Stack Exchange Data Explorer](https://data.stackexchange.com/codegolf/query/1227273/viewcount-of-a-specific-question-id):
```
SELECT ViewCount FROM Posts WHERE Id=203590
```
Based on my answer [to this similar question](https://codegolf.stackexchange.com/a/143116/70172).
[Answer]
# Bash + common tools, 67
```
lynx -dump codegolf.stackexchange.com/q/203590|grep -Po 'wed \K\d+'
```
] |
[Question]
[
This challenge will give you an input of a [degree sequence](http://mathworld.wolfram.com/DegreeSequence.html) in the form of a partition of an even number. Your goal will be to write a program that will output the number of loop-free labeled multigraphs that have this degree sequence.
## Example
For example, given the input `[3,3,1,1]`, you should output the number of labeled multigraphs on four vertices \$\{v\_1, v\_2, v\_3, v\_4\}\$ such that \$\deg(v\_1) = \deg(v\_2) = 3\$ and \$\deg(v\_3) = \deg(v\_4) = 1\$. In this example, there are three such multigraphs:
[](https://i.stack.imgur.com/mBJIf.png)
See Gus Wiseman's links on OEIS sequence [A209816](https://oeis.org/A209816) for more examples.
## Target data
```
input | output
----------------+--------
[6,2] | 0
[5,3,2] | 1
[3,3,1,1] | 3
[4,3,1,1,1] | 6
[4,2,1,1,1,1] | 10
[1,1,1,1,1,1] | 15
[3,2,2,2,1] | 15
[2,2,2,2,2] | 22
[7,6,5,4,3,2,1] | 7757
```
# Challenge
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins.
[Answer]
# [Haskell](https://www.haskell.org/), 57 bytes
```
f(h:t)=sum[f l|l<-mapM(\n->[0..n])t,sum t-sum l==h]
f _=1
```
[Try it online!](https://tio.run/##bZDNCsIwEITvfYpBPDSYFhOtBzF9Aj15TIMUaamYVjEpXnz3mLT@IJjAMt8OzGbTlOZcae1cHTdrS4TpW1lDP/QmacvrLi66JJfzNO0UsdSbsEmoWohGRTUOgjlbGXssTWUgICFXlCsKmdHFKBZeMMqCXI7yDXyEgBF@jmSUfc2QwYc7AH/BkL6iGQ2x/F/K2/RTFVQUteWp848MiyEuNJIc197u7W3bYQrTXO7QmM0wCc4kqKEX@w8hBJ893RM "Haskell – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 127 bytes
```
e=[]:e
h a b=mapM id$b<$a
f a=length[0|x<-h a$h a[0..maximum a],x==foldr(zipWith(:))e x,all(<1)$zipWith(!!)x[0..],map sum x==a]
```
[Try it online!](https://tio.run/##NY2xCsMgFEX3fMULOCjYkKwhfkKnDB3E4YVolWoSEkOl9N@thRbuXS7ncC0eD@19zlpI1evKAsIkAm5XcDOZBoKVARReL/doZftOw6UgpFS2TRMwuXAGQMWTEGb1805fbru5aGnPmIbE0Xs6dIz857pm6asqXk7gKHIxUeWAbhHzWm1nHONODrs@iZEdh19U/gA "Haskell – Try It Online")
Very very inefficient (superexponential), but I believe it should work in theory. Exceeds Tio's 60 second limit with `[3, 3, 1, 1]` as input, but works with `[1, 1, 1, 1]`.
Considers the adjacency matrices of the multigraphs.
`h a$h a[0..maximum a]` is a list of all square matrices with entries between `0` and `maximum a`, with size `length a`.
`x==foldr(zipWith(:))e x` checks if a matrix is symmetric.
`all(<1)$zipWith(!!)x[0..]` checks that the diagonal entries are zero, since there are no loops.
`map sum x==a` checks that each vertex has the proper degree.
[Answer]
# [Haskell](https://www.haskell.org/), 75 bytes
```
f(h:t)=sum$f<$>h%t
f[]=1
r%(h:t)=[h-i:x|i<-[0..r],x<-(r-i)%t]
r%_=[[]|r==0]
```
[Try it online!](https://tio.run/##bY9dC8IgFIbv/RWH2GBjGmkfFzH7BXXV5UlixIYjV6FGXfTf19z6IEhvnsdX3qO6cMfSmLatEr30qXTXJqryaKVjTypUkhMbDwlqVi/vjzpnOBmPraL3nCWW1WnsVXdpLxHVw0o5Ua0vnT8UrnQgAQEXVCgKOKfTAaYdcMoDzgZ8ixgkKIGfhZzybxg6RL97ES/p2xd0TkOt@NfyDrupChQhTVGfukc2xWUDyc4AW8Hl6rferk8QgdPnGxjIMhiFZBSoP0sqMGkKn3@2Tw "Haskell – Try It Online")
It's faster (and easier to understand) when `i<-[0..r]` is replaced by `i<-[0..min r h]`. Also, it's faster to give the degrees (whose order obviously doesn't matter) in increasing order.
] |
[Question]
[
This challenge is based on a video in which Andrew Huang discusses unusual time signatures...
<https://www.youtube.com/watch?v=JQk-1IXRfew>
In it, he advises that you can understand time signatures by dividing them into 3's and 2's. So you count to a small number a few times, instead of counting to a large number.
Here's the pattern he builds which repeats after 19 steps:
* 5 groups of 3
* 2 groups of 2
This is how it looks:
```
#..#..#..#..#..#.#.
```
Actually, as you'd play each beat alternatively, the accented beats move from left to right, because there's an odd number of steps. So now this pattern is:
```
R..L..R..L..R..L.L.
L..R..L..R..L..R.R.
```
If we reduce this to an algorithm, it can be described like this.
## Step 1: where are the accents
* From your number of steps, start by taking groups of 3 from the start until there's 4 or fewer steps remaining.
E.g. for a pattern 8 steps long.
8 steps - take three, 5 steps remaining
```
#..
```
5 steps - take 3, 2 steps remaining
```
#..#..
```
Once we're down to 4 steps or fewer, there's 3 possibilities.
* 4 steps - 2 groups of 2
* 3 steps - 1 group of 3
* 2 steps - 1 group of 2
So from our above example:
```
#..#..#.
```
## Step 2: Which hand are the accents on
Let's assume that each individual step will be played on alternate hands, starting with the right.
So for 8 steps, the (underlying) pattern will go
```
rlrlrlrl
```
The pattern we output will only tell use which hand the accents are on. With the above example:
```
R..L..R.
```
That's fine, it's repeatable.
**but**
If it's an odd number, you've got the same hand for both the first and last steps, and you can't keep alternating when you repeat the pattern. Instead, the second pattern will be on the other hand. Here's the pattern on an 11 step pattern.
```
R..L..R..L.
L..R..L..R.
```
To clarify, if the pattern length is *odd*, we need to see the repeated, alternated pattern. If the length is *even*, we only need to see it once.
Hopefully that's clear enough:
---
# The Rules
* It's code golf, go for the shortest code.
* Your code will accept one pattern, a positive integer higher than 1.
* It will output some text describing a pattern diagram, as described above.
* Any language you like.
* Please include a link to an online interpreter.
# Test cases
2
```
R.
```
3
```
R..
L..
```
4
```
R.R.
```
7
```
R..L.L.
L..R.R.
```
9
```
R..L..R..
L..R..L..
```
10
```
R..L..R.R.
```
19
```
R..L..R..L..R..L.L.
L..R..L..R..L..R.R.
```
22
```
R..L..R..L..R..L..R.R.
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 66 bytes
```
.+
$*
1
RL
^(.+)RL\1$
$1R¶L$1
^(.+)\1$
$1
(.)(..?)(?!.\b)
$1$.2$*.
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLy5AryIcrTkNPWzPIJ8ZQhUvFMOjQNh8VQ4gYRIRLQ09TQ0/PXlPDXlEvJkkTKKSiZ6Sipff/vxGXMZcJlzmXJZehAZehJZeREQA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
$*
```
Convert the input to unary.
```
1
RL
```
Alternate between hands.
```
^(.+)RL\1$
$1R¶L$1
```
If there are an odd number of beats then divide the output in the middle.
```
^(.+)\1$
$1
```
But if there are an even number of beats then just use one copy.
```
(.)(..?)(?!.\b)
$1$.2$*.
```
Try to match groups of three beats, but without leaving a lone beat at the end, and replace the offbeats with `.`s.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṗ;’m3Ṭ»¬€ḤÐe,N$ṫḂṚị“LR.”Y
```
A monadic Link accepting an integer greater than one which yields a list of characters.
**[Try it online!](https://tio.run/##AT4Awf9qZWxsef//4bmWO@KAmW0z4bmswrvCrOKCrOG4pMOQZSxOJOG5q@G4guG5muG7i@KAnExSLuKAnVn///8xOQ "Jelly – Try It Online")**
### How?
```
Ṗ;’m3Ṭ»¬€ḤÐe,N$ṫḂṚị“LR.”Y - Link: integer (>1), N e.g. 13
Ṗ - popped range (N) [1,2,3,4,5,6,7,8,9,10,11,12]
’ - decrement (N) 12
; - concatenate [1,2,3,4,5,6,7,8,9,10,11,12,12]
3 - literal three
m - modulo slice [1, 4, 7, 10, 12]
Ṭ - un-truth [1,0,0,1,0,0,1,0,0, 1, 0 ,1]
- ...12th entry is a 1 ^
€ - for each of [1..N]:
¬ - logical NOT [0,0,0,0,0,0,0,0,0, 0, 0, 0, 0]
» - maximum [1,0,0,1,0,0,1,0,0, 1, 0 ,1, 0]
Ðe - for entries at even indices:
Ḥ - double [1,0,0,2,0,0,1,0,0, 2, 0, 2, 0]
$ - last two links as a monad:
N - negate [-1,0,0,-2,0,0,-1,0,0,-2,0,-2,0]
, - pair [[1,0,0,2,...],[-1,0,0,-2,...]]
Ḃ - modulo 2 (N) 1
ṫ - tail from index [[1,0,0,2,...],[-1,0,0,-2,...]]
- ...Jelly indexing is 1-based & modular
- so 0 would have resulted in [[-1,0,0,-2,...]]
Ṛ - reverse [[-1,0,0,-2,...],[1,0,0,2,...]]
- ...which for a list of length 1 is a no-op
“LR.” - literal list of characters ['L', 'R', '.']
ị - index into (1-based & modular) ["R..L..R..L.L.","L..R..L..R.R."]
Y - join with newlines "R..L..R..L.L.\nL..R..L..R.R."
- ...which is just the entry for a list of length 1
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~47~~ ~~43~~ ~~42~~ ~~41~~ 40 [bytes](https://github.com/Adriandmen/05AB1E/wiki/codepage)
```
„RL×2äIÈ.£εÐ3äн€3sg3%i2TSǝR}£εćsg'.׫]J»
```
Not too happy with it..
Switched to the legacy version to save a byte (the legacy version replaces the values when using `€`, whereas the new version leaves them in the list: [Try `€3` in the legacy](https://tio.run/##MzBNTDJM/f//UdMa4///g3yCAA) or [try `€3` in the new version](https://tio.run/##yy9OTMpM/f//UdMa4///g3yCAA)).
-1 byte thanks to *@Grimy*.
[Try it online](https://tio.run/##AUYAuf8wNWFiMWX//@KAnlJMw5cyw6RJw4guwqPOtcOQM8Ok0L3igqwzc2czJWkyVFPHnVJ9wqPOtcSHc2cnLsOXwqtdSsK7//83) or [verify all test cases](https://tio.run/##MzBNTDJM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VT@f9QwL8jn8HSjw0sqD3foHVp8buvhCcaHl1zY@6hpjXFxurFqplFI8PG5QbUgqSPtxenqeoenH1pdW@t1aPd/nUPb7P9HG@kY65jomOtY6hga6Bha6hgZxQIA).
**Explanation:**
```
„RL× # Repeat "RL" the (implicit) input-integer amount of times
2ä # Divide it into 2 equal halves
IÈ # Check if the input-integer is even (1 if truthy; 0 if falsey)
.£ # And remove that many items
# Some examples of what we now have:
# 7 → ["RLRLRLR","LRLRLRL"]
# 9 → ["RLRLRLRLR","LRLRLRLRL"]
# 10 → ["RLRLRLRLRL"]
ε # Map each string in this list to:
Ð # Triplicate the string
3ä # Divide the string into 3 equal parts
н # And only leave the first one
€3 # And convert each value to a 3
# (basically a golf from my previous ceil(length/3) amount of 3s list)
sg # Swap to take the string again, and get its length
3%i } # If this length modulo-3 is exactly 1:
2TSǝ # Replace the first two items (at indices 0 and 1) with 2s
R # And reverse it: [3,3,3,...,2,2]
£ # Split the string according to this list
# Some examples again:
# ["RLRLRLR","LRLRLRL"] → [["RLR","LR","LR"],["LRL","RL","RL"]]
# ["RLRLRLRLR","LRLRLRLRL"] → [["RLR","LRL","RLR"],["LRL","RLR","LRL"]]
# ["RLRLRLRLRL"] → [["RLR","LRLR","RL","RL"]
ε # Then map each inner substring to:
ć # Extract head; pop and push remainder and head
sg # Swap to get the remainder, and get it's length (either 1 or 2)
'.× '# Create a string with that many "."
« # And merge it to the extracted head
] # After both the inner and outer map:
J # Join each inner list together to a single string
» # And then join the strings by newlines
# (after which the result is output implicitly)
```
[Answer]
# JavaScript (ES6), ~~84 81 78~~ 75 bytes
```
f=(n,x,N)=>n?'RL.'[!--n|N%3%(3-!~-n)?2:N&1^x]+f(n,x,-~N):N&!x?`
`+f(N,1):''
```
[Try it online!](https://tio.run/##Vc1PC4IwHMbxu69iHmwb/iZNg1CZnrrFDl2tUEz7g/wWGiFUvnUb3bp@vg88t@pZDXV/vT8EmlMzz61iCCNorjLM6W4b0MIVAt/aizwWCXcSyPMw0Qt5HA9@@xuLSXMr7piXTmlNg@QJpXNahBDBCtYQg1yCjCEMD07Qmn5T1ReGRGXkRWqDg@maoDNnRjVRhBKfIE//gj3ilukeqS0fPn8B "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
x, // x = flag set to 1 if we're processing the 2nd row
N // N = counter incremented each time n is decremented
) => //
n ? // if n is not 0:
'RL.'[ // output the next character:
!--n | // decrement n; if this is the last character
N % 3 % // or N mod 3 is either
(3 - !~-n) ? // odd if n = 1 or not equal to 0 otherwise:
2 // output '.'
: // else:
N & 1 ^ x // output either 'L' or 'R' depending on N and x
] + // end of character output
f(n, x, -~N) // append the result of a recursive call with N+1
: // else:
N & !x ? // if x = 0 and N is odd:
`\n` + // append a linefeed
f(N, 1) // and restart with x = 1
: // else:
'' // stop recursion
```
[Answer]
# [Julia 1.0](http://julialang.org/), ~~83~~ ~~80~~ 75 bytes
```
n->(f(r,s,h='R'-6s)=r∈0:2:4 ? "$h."^(r>>1) : "$h.."*f(r-3,1-s)).(n,0:n%2)
```
[Try it online!](https://tio.run/##yyrNyUw0rPifZvs/T9dOI02jSKdYJ8NWPUhd16xY07boUUeHgZWRlYmCvYKSSoaeUpxGkZ2doaaCFZirp6QF1KFrrGOoW6ypqaeRp2NgladqpPm/oCgzryQnTw9ooJGmJheUqwFngSSMcUmY4JIwxyVhiUvC0ACnDE49RkAX/wcA "Julia 1.0 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~28~~ ~~27~~ ~~26~~ 25 bytes
```
Ƀ¶IÅœRΣP}θRv„LR¼¾èyG¼'.J
```
*-1 byte thanks to Kevin Cruijssen*
[Try it online!](https://tio.run/##ATIAzf9vc2FiaWX//8OJxpLCtknDhcWTUs6jUH3OuFJ24oCeTFLCvMK@w6h5R8K8Jy5K//8xMw)
Explanation:
A signature subdivision can be seen as an integer partition. For example, `#..#.#.` is the partition `[3, 2, 2]` of 7.
A remarkable property of the subdivisions specified by this challenge is that
they maximize product. For example, 3\*2\*2 = 12, and no other partition of 7 has a product > 12 (only `[3, 4]` ties it). This can be proved true in the general case.
```
Ƀ # loop (input%2) + 1 times
¶ # newline
IŜ # integer partitions of the input
R # reverse, so that [2, 2, 3, ..., 3] comes after [3, ..., 3, 4]
ΣP} # sort by product (stable sort)
θ # take the last element
R # reverse it, so that the 2s are at the end
v # for each integer y in the partition
„LR # literal string "LR"
¼¾è # increment counter_variable, then use it to index into "LR"
yG # loop y-1 times
¼ # increment counter_variable
'. # literal "."
J # join all the strings in the stack
```
] |
[Question]
[
>
> This is the Cops' thread. [Robbers' thread is here](https://codegolf.stackexchange.com/q/173385/78410).
>
>
>
## Background
[Boggle](https://en.wikipedia.org/wiki/Boggle) is a board game where the players have to find English words on a 4-by-4 board of random alphabets. Words can be constructed by selecting sequentially adjacent cells on the board. ("adjacent" means horizontally, vertically or diagonally adjacent.) Also, same cell can't be used more than once in a word.
The following is an example board:
```
I L A W
B N G E
I U A O
A S R L
```
On this board, `BINGO`, `ORANGE` and `WEARS` are valid words, but `SURGE` and `RUSSIA` are not:
* `SURGE` : There's no adjacent pair on the board having `RG`.
* `RUSSIA` : `S` cannot be used twice.
**Modified Boggle** is a modified version of Boggle, with the following rules:
* The board size is `m`-by-`n`, where `m` and `n` can be any positive integer.
* Each cell can contain any one byte between 0 and 255 inclusive.
* **A cell can be used more than once, but not twice in a row.**
Using the example board above, in addition to `BINGO`, `ORANGE` and `WEARS`, `LANGUAGE` becomes a valid string (since `G` is used twice, but not twice in a row) but `RUSSIA` is still not (due to `SS` pair).
Here is another example using a code fragment. The string `from itertools import*\n` can be found on the following board, but not `from itertoosl import*` or `from itertools import *`:
```
f i ' ' s
r t m l
e o o p
\n * t r
```
Note that you need two `o`'s in order to match the `oo` sequence.
---
## Cop's challenge
Write a **full program** in your language of choice that satisfies the following rules:
* The program should print something which is consistent over multiple runs.
* The program should finish in roughly 5 seconds.
* The program may not take any input.
* Both the program and the output should be at least 2 bytes.
* **Anything related to hash functions, PRNGs, or cryptography is not allowed.**
Then, **lay out your program *and* output into two separate modified-boggle boards**. Each board can be a non-square. Note that 1-by-N and 2-by-N boards can pose special challenges to both the cop and the robber. If you want some cells on a board unusable (to add more restriction), you can pick some useless bytes and fill the holes with them.
For example, if you want a 2x2 grid with horizontal/vertical movements only, you can do this instead:
```
a b
c d
-----------
X a X
c X b
X d X
```
In your submission, specify the language you used, the lengths of the source code and the output, and the two boggle boards. Note that **shorter code and/or longer output is allowed for robbers**, so you can choose to give some room for the byte counts (i.e. specify longer code and/or shorter output than your actual solution).
If your board contains some unprintable characters, you can specify the board as byte values instead.
After a week a cop is posted, it can be marked safe by the poster if it isn't cracked until then. The cop is still open for robbers until it's actually marked safe. A safe cop can't be cracked, and the poster should reveal the intended solution.
You'll want to obfuscate the boards as much as possible, as the robber's challenge is to crack your submission by finding the code and its output on the boards. If you want to cram a long code into a small board, answers to [the original Modified Boggle challenge](https://codegolf.stackexchange.com/q/165157/78410) may give some insights.
## Scoring for cops
Since it's hard to say whether a larger or smaller board is harder to crack, each safe cop submission counts as a score of 1. The user with the greatest score wins. It's encouraged to participate with different languages and creative approaches.
## Cop example & formatting
```
# Japt, code 9 bytes, output 20 bytes
Code board: 2 rows, 2 columns
`l
íÏ
As byte values:
96 108
237 207
Output board: 3 rows, 3 columns
175
120
643
```
---
## Modified Boggle verification script
All of the scripts below have an example input with it.
[Script for character string(code/output) & boggle.](https://tio.run/##bZBNasMwEIX3c4pZFYv8kNBdSnIRY7ArjxNRRRKSTBxKztCT9BQ5mDuy3KaFgmVJ7/G@GY27xpM1z@PYeXtGabUmGZU1AdXZWR@xpa7pdWyVjADBS9yjMq6PhYBXezxqYqGsIPrrDvByUixsd5itdeMcmbaYAwJokOTiDl0TAmhlqPE53lmP3l4YPUcZlv01DTEx2BUvszRjNwKAOw6M0GSKHCw3lVhsQVv71jt2fvVfBIpiKqWWMpUi05/JN5GKDBap6hQsZbVuWu5cgLNB5Yns8V1hjtO/cVQd0m2qMPF5XEz8C1gMGZH8h5OkIUnlKr1otV3idJi3Rbrz4u/bzm42qxs@PRoH55WJRRrJTwGBB9yIcaz1/fP@UaefhlpDOvD@BQ "Python 3 – Try It Online") This does not support multi-line string. The input format is
* a single line of string (either code or output), followed by
* the raw boggle board.
[Script for character string with byte-value boggle.](https://tio.run/##bZHvTsIwFMW/36e4fnFtgGVgIorBF5kLzK1AtbRNV8KI4Rl8Ep@CB8PelX8mJtu69tdzznpmd35l9MPxuHBmjZVRSlReGt2gXFvjPNZiUW6Ur2XlARpXzZTUosEpSu2Z1HbjGecEwlJuXM1ajgvjsA0bMHnTSfphpD7v7NCMkCv1UrCLIecFvJvlUgnyKcC73QRwu5JhYTjBiNLSWqFrllP2bc7JPW2skmEsOIi2EtZP0JZNA5RQumhMGme2pIqmISbyVLSe3APlL6elU2CScIBQDp1bCc2iMs8K3huCMuZzYwO5qYo1wvMuS/YryhJ6sxau9IJFZ06xnTCvirSsayY5WNPIWP4UvyRGufhXjnKBAu@mmCT7LqdLCXUG3782vTYaEb@SS3X5gM41GPaxezkNPZqHO1xnHGmExR7vr58P1tEPoWIuARxfMePH4wjm6vBz@IY5PRVkiDjM4PkRcZSNYfQwDtOnXw "Python 3 – Try It Online") Use this if the target string is printable but has one or more newlines in it. The input format is
* the number of lines for the string,
* raw string (possibly multi-line), then
* the boggle board as byte values.
[Script for byte-value string & boggle.](https://tio.run/##hVHRasIwFH2/X3H3sjaopVVQ53A/UvrQtamGxSQkKVaG397dNE43GAxSbnJOzzm5N@bij1qtxrGz@oSNlpI3XmjlUJyMth5b3tW99K1oPICzDe6xFMqnA8NOWxxQKFqm9ynLnJGCagXv@nCQPPxagbeXHeD5KAgodhiprDaGqzb914oBHxpu/A5N7RxIoXhto3HQWH0OqmhKMZHP@OCDO7Hs9QbdApOEAVCbjjwkV2lUlnnFZgVIrT96Q8yPplPHPZuyxLwJWVz1J25rz9PozELsJCybKqvbNhUMjHYijnGPnwKjnP8pR9Ehx6c9Jsl1yplSaNLk@9tmNkSjwD@Y@@jKRehrUcxx2tzKLJzpo/VNRzaS1RWfH9cHY8ODhMHcAxi@Yc7G8WWNRb7F5WqDy3xDeyTkcdpCjkgVCA0QBIrgLw "Python 3 – Try It Online") Use this if the target string contains one or more unprintable characters. The input format is
* a single line of string (either code or output) as byte values, followed by
* the boggle board as byte values.
[Answer]
# JavaScript, 1443 bytes code, 3 bytes output, [cracked](https://codegolf.stackexchange.com/a/173396/73884) in moments by @ShieruAsakoto
### Code board, 3 rows by 4 columns
```
!![+
+[]]
+]()
```
### Output board, 1 row by 2 columns
```
aN
```
Kinda obvious what the output is. ~~It'll be the code that's fun to crack.~~ Forgot to mention that it was intended to be a full program (and kinda implied that it wasn't; see paragraph below). For the real challenge, see my [other answer](https://codegolf.stackexchange.com/a/173397/73884).
I don't think this is Node.js, but my knowledge in this area is zero. What I can say is that it runs in my console in both Edge and Chrome.
[Answer]
# JavaScript (Node.js), code 53 bytes, output 41 bytes, cracked by Arnauld
### Code Board: 3 rows by 6 columns:
```
cog(n)
lsn1()
e.+<<;
```
### Output Board: 4 rows by 6 columns:
```
481534
270906
602148
53829n
```
**Hint: the code only works on V8 JS engines, version 6.7 or later**
Mine was `console.log(1n+1n+1n<<(1n+1n+1n+1n<<1n+1n+1n+1n+1n));` with the semicolon (don't ask why) and the output is yes, `3 * 2**128` with an trailing `n` marking the number as a BigInt literal.
[Answer]
# JavaScript (Node.js), code 88 bytes, output 2 bytes, cracked by Arnauld with a 27-byte
### Code Board: 7 rows by 9 columns:
```
e.i--)=%5
lc;,2s*17
fosn8407%
gnr785138
s(;527067
=);s%1419
4n,i=1832
```
### Output Board: 1 rows by 2 columns:
```
0n
```
The output is obvious, but the code is not. ;)
My original answer was an LL-test of M127, which was
```
for(s=4n,i=125;i;s%=170141183460469231731687303715884105727n,i--)s=s*s-2n;console.log(s)
```
Arnauld's answer utilized the semicolons to bridge a shorter crack, and I didn't expect (or realize) the `s%=s` part at all:
```
s=4n;s%=s;7n;console.log(s)
```
Oh by the way my 3 posts have absolutely nothing to do with hash functions, PRNGs or cryptography. I swear these three are only about number manipulations.
**there are unused bytes in code board**
[Answer]
# MathGolf, code 42 bytes, output 22 bytes
### Code Board: 3 rows by 7 columns
```
r5 qÄ
~←▲↔▼→~
Äq 5r
```
### Output Board: 3 rows by 6 columns:
```
421
402
135
```
This is quite a bit longer, but I'll give a small hint: The code board is supposed to resemble a bowtie, and you might need to "tie" it multiple times.
[Answer]
# JavaScript, 1443 bytes code, 3 bytes output, [cracked](https://codegolf.stackexchange.com/a/173398/73884) by @Bubbler
A full program.
### Code board, 3 rows by 4 columns
```
!![+
+[]]
+]()
```
### Output board, 1 row by 2 columns
```
aN
```
Kinda obvious what the output is. It'll be the code that's fun to crack.
I don't think this is Node.js, but my knowledge in this area is zero. What I can say is that it runs in both Edge and Chrome. By "full program" I mean that it runs when placed between `<script>` and `</script>` in an HTML file.
[Answer]
# Python 3, code 56 bytes, output 69 bytes, SAFE
### Code Board: 4 rows by 10 columns:
```
print(1,
b; f,)*l(1
=lamb+a,)
ese d:(-1)
```
### Output Board: 7 rows by 7 columns:
```
1466900
3427430
1304212
9653895
0511633
5680228
4437679
```
Much difficult one than my first challenge ;)
# Expected Code and Output:
>
> Code:
>
>
>
> ```
> l=lambda a,b:(a+b)*l(a-1,a*b)if a else b;print(l(11,11))
>
> ```
>
> Output:
>
>
>
> ```
> 421827435070654423113161304555505960246647934329322186026783332352000
>
> ```
>
>
[Answer]
# MathGolf, code 7 bytes, output 12 bytes
Just a first easy challenge, if you want to get into MathGolf!
### Code Board: 2 rows by 4 columns
```
╒Æ■r
îm4~
```
### Output Board: 2 rows by 3 columns
```
140
412
```
[Answer]
# Jelly, 17 byte code, 19 byte output
The general method shouldn't be too hard to pick out.
## Code board
```
»V
”;
“;
```
## Output board
```
Krgwn
Ubots
RAbbt
```
[Answer]
# [J](http://jsoftware.com/) (REPL), code 9 bytes, output 10000 bytes
Code board: 3 rows, 3 columns
```
epi
j.r
oI5
```
Output board: 3 rows, 2 columns, as byte values
```
10 10
48 49
32 255
```
In essence, `\n\n` / `01` / `<space><don't use>`.
Intended solution gives 20008-byte output.
] |
[Question]
[
# ASCII reflections in a box
You probably all know the [*Law of Reflection*](https://en.wikipedia.org/wiki/Specular_reflection), in this challenge you'll visualize the trajectory of a ball in a box.
Related: [ASCII Ball in Box Animation](https://codegolf.stackexchange.com/questions/5651/ascii-ball-in-box-animation) and [ASCII Doodling: Laser in a Box](https://codegolf.stackexchange.com/questions/48531/ascii-doodling-laser-in-a-box)
### Task
You're given three integer pairs `W,H`, `x,y` and `dx,dy` - the first represents the size of the box, the second the starting position and the third pair is the direction in which the ball starts moving.
The task is to visualize the movement of the ball until it stops rolling, this happens as soon as the ball is at a position that it was before or it hits a corner.
The character `*` shall visualize the trajectory of the ball and `+` marks its final position, the rest of the box must consist of (whitespace).
### Examples
To lay it out a bit clearer, in these examples `_` will represent a whitespace. Also the intermediate stages are only here for clarification, you'll only need to output the last stage, these examples are `1`-indexed.
---
Given `W = 3, H = 5`, `x = 3, y = 2` and `dx = -1, dy = 1`:
```
___ ___ ___ ___
__* __* __* __*
___ -> _*_ -> _*_ -> _+_
___ *__ *__ *_*
___ ___ _*_ _*_
```
* Ball starts at point `(3,2)` and
* moves in direction `(-1,1)`, hits the wall at `(1,4)` and
* gets reflected, new direction is `(1,1)`. It hits the wall again at `(2,5)`
* where it gets gets reflected. The new direction is `(1,-1)` and it hits the wall immediately at `(3,4)`,
* again it gets reflected into the direction `(-1,-1)`. It would now travel through points `(2,3),(1,2)`, reflected etc. but since it already visited the position `(2,3)` it stops there.
---
This example demonstrates, what happens if a ball hits a corner. For this let `W = 7, H = 3`, `x = 1, y = 3` and `dx = 1, dy = -1`:
```
_______ __*____ __*____ __*___+
_______ -> _*_____ -> _*_*___ -> _*_*_*_
*______ *______ *___*__ *___*__
```
* Start position is `(1,3)`,
* the ball now travels in direction `(1,-1)` until it hits the wall at `(3,1)`
* where it gets reflected into the new direction `(1,1)`.
* At `(5,3)` it gets reflected and travels into the new direction `(1,-1)`. It comes to an abrupt stop at `(7,1)` because that's a corner.
---
Given `W = 10, H = 6`, `x = 6, y = 6` and `dx = 1, dy = 1`:
```
__________ __________ ________*_ ________*_ ________*_ __*_____*_ __*_____*_
__________ _________* _________* _______*_* _______*_* _*_____*_* _*_*___*_*
__________ -> ________*_ -> ________*_ -> ______*_*_ -> *_____*_*_ -> *_____*_*_ -> *___*_*_*_
__________ _______*__ _______*__ _____*_*__ _*___*_*__ _*___*_*__ _*___+_*__
__________ ______*___ ______*___ ____*_*___ __*_*_*___ __*_*_*___ __*_*_*___
_____*____ _____*____ _____*____ ___*_*____ ___*_*____ ___*_*____ ___*_*____
```
### Input specification
The input consists of the three integer pairs `W,H`, `x,y` and `dx,dy`, you may take input in any format that makes most sense for your programming language and the order doesn't matter. However the accepted input must not encode more information than these pairs contain (see [this](https://codegolf.stackexchange.com/a/132450/48198) answer for an example).
* `W,H >= 1`
* `x,y` are either `1`-indexed (`1 <= x <= W` and `1 <= y <= H`) or `0`-indexed (`0 <= x < W` and `0 <= y < H`), please specify what indexing you chose
* `dx,dy` are always either `-1` or `1`
Invalid input can be ignored.
### Output specification
1. No leading whitespaces are allowed
2. Trailing whitespaces may be omitted
3. Trailing whitespaces are not allowed if they don't fit the box
4. Trailing newlines (*after* all output related lines) are allowed
Let's take the first example:
```
(good by 2)
__*
_+ (good by 2)
*_*_ (bad by 3)
(bad by 4)
_*_
(good by 4)
```
### Test cases
Assuming the input has the format `(W,H,x,y,dx,dy)` and `1`-indexing was chosen, here are some test cases (again `_` is here to represent whitespaces!):
Input: 1,1,1,1,1,1
Output:
```
+
```
Input: 3,3,3,3,1,1
Output:
```
___
___
__+
```
Input: 3,3,3,3,-1,-1
Output:
```
+__
_*_
__*
```
Input: 7,3,1,3,1,-1
Output:
```
__*___+
_*_*_*_
*___*__
```
Input: 10,6,6,6,1,1
Output:
```
__*_____*_
_*_*___*_*
*___*_*_*_
_*___+_*__
__*_*_*___
___*_*____
```
Input: 21,7,6,4,-1,-1
Output:
```
__*_______*_______*__
_*_*_____*_*_____*_*_
*___*___*___*___*___*
_*___*_*_____*_*___*_
__*___*_______+___*__
___*_*_________*_*___
____*___________*____
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program/function wins, but any effort is appreciated.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes
```
UONN JNN↷NW⁼ KK«*¿¬KK«↷²¶*¿¬KK«↷²¶↷²*¿¬KK«↷²¶»»»»+
```
[Try it online!](https://tio.run/##fY29DoIwFEZn@hQ3nYrCIIY4ODvogMQ4ugBBaCwtQouD4dkrKEbCj0OHm@@c0ygNikgETOtjyARPyJ7nSnoqC@OCmBYMTgzY3KKDyvKz@Is2lE8rIU80SSUZTo@UshjI7q4CVpImaoEfx7dmM@GJDL@gXBK8aP8y6BWIJyTpA0av7bTQV7nwjzRtjbWfh7t7jui6M@EJb5Su0fvVqEbdtGwWrZ0VbMCFNbjarrRdshc "Charcoal – Try It Online") Link is to verbose version of code. Takes five inputs: `w`, `h`, `x`, `y`, `a`. `x` and `y` are zero-indexed. `a` represents `dx` and `dy` according to the following encoding:
```
a mod 8 == 1 => dx = 1, dy = 1
a mod 8 == 3 => dx = -1, dy = 1
a mod 8 == 5 => dx = -1, dy = -1
a mod 8 == 7 => dx = 1, dy = -1
```
Explanation:
```
UONN
```
(note trailing space) Fills the background with spaces to the input width and height. (Normally each square of the background is an empty string, which is then converted to a space on output.)
```
JNN
```
Moves the cursor to the initial coordinates.
```
↷N
```
Rotates to the initial angle.
```
W⁼ KK«
```
Repeats as long as the current square is a space.
```
*
```
Prints an asterisk and moves forward in the current direction.
```
¿¬KK«
```
If the cursor moved outside of the original oblong,
```
↷²¶*
```
Rotate the direction, then print a newline (which conveniently takes us back to the previous square) and an asterisk, which moves in the new direction.
```
¿¬KK«
```
If the cursor moved back outside of the original oblong,
```
↷²¶↷²*
```
Take the cursor back to the previous square, then rotate again, thus printing the asterisk in the other direction.
```
¿¬KK«
```
If the cursor is still outside of the oblong, we must be at a corner.
```
↷²¶
```
So go back to the previous square and give up.
```
»»»»+
```
When we can't move any more, print a "+" sign and stop.
[Answer]
# Desmos Calculator - Non Competing to Help Further Knowledge
[Try it online!](https://www.desmos.com/calculator/0lhvergrv0)
**Inputs:**
```
X as X position to Start
Y as Y position to Start
s as slope -> -1 for dX/dY = -1, +1 for dX/dY = +1
h as height of box, with 0-indexing
w as width of box, with 0-indexing
```
**Intermediates:**
```
Let b = gcd(h,w),
Let c = |b-(X-sY)%2b| Or |b-mod(X-sY,2b)|
```
* **gcd(h,w)** represents the [greatest common denominator](https://en.wikipedia.org/wiki/Greatest_common_divisor)
* **A % B**, as in Javascript, or **mod(A,B)**, as in Fortran, represents the [modulus operation](https://en.wikipedia.org/wiki/Modulo_operation), on the interval [0,B).
**Formula, abbreviated:**
```
(|b-(x+y)%2b|-c)(|b-(x-y)%2b|-c)=0
```
**Outputs:**
```
x as x position, 0-indexed, where the ball will land when released
y as y position, 0-indexed, where the ball will land when released
```
**How it Works:**
```
(|b-(x+y)%2b|-c)*(|b-(x-y)%2b|-c)=0
^ OR operation - |b-(x+y)%2b|-c=0 or |b-(x-y)%2b|-c=0
|b-(x+/-y)%2b|-c = 0
|b-(x+/-y)%2b| = c
|b-(x+/-y)%2b| = c means (b-(x+/-y))%2b = + or -c
b-(x+/-y)%2b = +/- c -> b +/- c = (x+/-y)%2b -> (x+/-y) = n*2*b + b +/- c
Where n is integer. This will force patterns to repeat every 2b steps in x and y.
Initial pattern n=0: (x +/- y) = b +/- c -> y = +/- x + b +/- c
In the x positive and y positive plane only, these correspond to lines of positive and
negative slope, set at intercept b, offset by c on either side.
```
Program fails to meet final criterion - stopping at intersection point and marking with a +, so is submitted as non-competitive for information to help others complete the challenge. Note that to get Desmos to work when c = 0 or c=b, a small offset factor of 0.01 was introduced, as Desmos seems to have bounds of Mod(A,B) of (0,B) instead of [0,B)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~293~~ 279 bytes
```
w,h,x,y,i,j=map(int,input().split());x-=1;y-=1;l=[x[::]for x in[[' ']*w]*h]
while 1:
a,b=((x,i)in[(0,-1),(w-1,1)]),((y,j)in[(0,-1),(h-1,1)])
if a and b or l[y][x]!=' ':l[y][x]='+';break
i,j=i*(-a*2+1),j*(-b*2+1);l[y][x]='*';x+=i;y+=j
print('\n'.join([''.join(x) for x in l]))
```
[Try it online!](https://tio.run/##TU9BbsQgDLzzCvcEJM6qdA@VgngJy4Gou8IpS6I0q8DrU7pKqx5sjzUjj2cua5jSed83DJixIOFo7n4WlFakND9WIU9fc6Q6pc6dUbr8tGhstn3vbtMCGShZy4G7ZnNNcGwLFK@gegYeByNERpJVIl6xUxLF1ilU0lUkCo7/mXAwDOgGHnz6gAGqQ7TF2exeTDXpj8XwluthufrPqq5PUyM637y19c5Y4fCE@k/ccJ1bQ7q0ZmTzUuMJfkn8NE6UhOUHyBJ@E0F0UrJ9f4czqGd16hs "Python 3 – Try It Online")
] |
[Question]
[
### Task
Write a program or function that, given a string and a list of strings, replaces each occurrence of an element of the string list contained in the string with the next element of the string list.
### Example
The string is `The cat wore a hat on my doormat so I gave it a pat` and the list is `["at","or","oo"]`, we observe that the following bracketed substrings are in the list of strings:
```
The c[at] w[or]e a h[at] on my d[oo]rm[at] so I gave it a p[at]
```
We replace each element simultaneously with the element after it. The element after `"at"` in the list is `"or"`, the element after `"or"` is `"oo"`, and the element after `"oo"` is `"at"`. We get
```
The c[or] w[oo]e a h[or] on my d[at]rm[or] so I gave it a p[or]
```
so the output is
```
The cor wooe a hor a on my datrmor so I gave it a por
```
Note that when we were finding substrings, we selected `d[oo]rm[at]` instead of `do[or]m[at]`. This is because the substrings cannot overlap, so when deciding between overlapping substrings we choose the one(s) which come first in the string. When that has ambiguity, we choose the one(s) which come first in the input list.
### Input
Input can be taken in any reasonable format. The list can be newline-delimited, space-delimited, or delimited by any reasonable character.
### Output
Output the string generated after the replacements
### Rules
* You may assume that the input string and list consist only of printable ASCII (0x20 to 0x7E).
* You may assume that the strings in the input list do not contain your delimiter.
* You may assume that the input list has no repeated elements.
* None of the [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default?answertab=votes#tab-top) are allowed.
* Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score in bytes wins.
### Testcases
```
String
List of Strings
Output
-----
"My friend John went to the park."
["j","J"," "]
"Myjfriendj ohnjwentjtojthejpark."
-----
"Monkey Tacos!"
["Monkey","Programming Puzzles"," "," & ","Tacos!","Code Golf", "Puzzles", "Dragons"]
"Programming Puzzles & Code Golf"
-----
"No matches this time :("
["Match","Duel","(No"]
"No matches this time :("
-----
"aaaaa"
["aa","b","a","c"]
"bbc"
-----
"aaaaa"
["b","a","c","aa"]
"ccccc"
-----
"pencil"
["enc","pen","nci","cil"]
"ncienc"
-----
"Seriously, a lowercase rot one?"
["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"]
"Sfsjpvtmz, b mpxfsdbtf spu pof?"
```
[Answer]
## JavaScript (ES6), 99 bytes
```
f=(s,a,i=a.findIndex(w=>s.startsWith(w)))=>s?(~i?a[i+1]||a[0]:s[0])+f(s.replace(a[i]||s[0],''),a):s
```
[Answer]
# Java 8, ~~227~~ 215 bytes
```
q->a->{String s=q,t;for(int i=0,j,l=a.length-1;i<s.length();i++)for(j=0;j<=l;j++)if(i==i+s.substring(i).indexOf(a[j])){s=s.substring(0,i)+(t=a[j<l?j+1:0])+s.substring(i+a[j].length());i+=t.length()-1;j=l;}return s;}
```
Ok, I got to admit: this challenge looks easy on paper, but there are many edge-cases for a verbose programming language like Java.. The first test case was easy, and was responsible for the general approach. The second test case caused a problem where it skipped two characters that both had to be replaced in a row `<space>J` -> `j<space>`. And then I had to fix another problem where test case `"aaaaa"; ["aa","b","a","c"]` resulted in `bcb` instead of the intended `bbc`. Oh, and the third test case replaced the `Puzzles` part twice at one point as well.. **But**, everything is fixed now, and all test-cases work.
**Explanation:**
[Try it here.](https://tio.run/nexus/java-openjdk#pVNNj9owEL3zK6Y5VIkSIva6IeyhVauutNuV2BviYBITHBw72A4QEL@dzvC1baWoSI30/JF5fm8ynoiq1sZBydYsbpyQ8bxRmRNaxd8ui6SXSWYtvDCh9j2AuplJkYF1zOG01iKHCkP@2BmhiskUtgHRAK4Cw3Mk@ms/mUbnxWgEGaTHVX/E@qP9@R3YdBW5ZK6NL5QDkQ6iMpIpiyVXhVv0HxIxtJeNHyQiDAPilukgKYepTEp8Iea@SFMR2tg2M3uS9UUQC5Xz7c@5zyblNAj2Nv09PohEEPouxeBQPpXhw@NgGvypENLBmzV5p@62xcRKtD8Y7hqjwCaHI5UiORVk3FrHq1g3Lq5Ry0nlZzGra9n63vuCQ8YcbLThwGCBS62gaiHX2lS4sxp@QMHWHIRDQs2cF1wOK76Ba033HgYiTxsatHfABP/p/dLC3AiucnjWCwUbjhV3GhymVDOzjDuMSrR4RsCdLloteQvvLNP2U4fkmYOab0YXhlUVtcJbs9tJbk9OiM80XlQi74vOOXzXck6HbsSvhhVa2fsSe9XYwC5bcIufLHAQFYdHvytFopJFwyVO/uudRWb0dF0ZQ6UZgubs//U@pCLSvkuv5ioTskMQYyiFFByRRtLIvUt3zI3QjZVthF0r9YabjFkORlOD86euilwKQrY5giPoigsEVZ9SoP5bIugaKkqMWp7SRKwQ9AtQM9D/0CDWiA1ii6Ae210/4NA7HH8B)
```
q->a->{String s=q, // Method with String & String-array parameters and String return-type
,t // Temp String
for( // Loop (1) over the characters of the input String
int i=0,j,l=a.length-1,t; // Some temp integers
i<s.length();i++)
for(j=0;j<=l;j++) // Loop (2) over the String-array
if(i==i+s.substring(i).indexOf(a[j])){
// If we've found a match:
s= // Replace the input-String with:
s.substring(0,i) // The first part of this input-String
+(t=a[j<l?j+1:0]) // + the next item in the String-array (and set `t` to it)
+s.substring(i+a[j].length()); // + the last part of this input-String
i+=t.length()-1; // Raise `i` by the length of this replacement item (`t`) - 1
j=l;//break; // Break loop (2)
} // End of if
// End of loop (2) (implicit / single-line body)
// End of loop (1) (implicit / single-line body)
return s; // Return resulting String
} // End of method
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~14~~ 13 bytes
It's early so probably room for improvement.
```
rVq| @VgVbX Ä
```
[Try it online](https://ethproductions.github.io/japt/?v=1.4.6&code=clZxfCBAVmdWYlggxA==&input=IlRoZSBjYXQgd29yZSBhIGhhdCBvbiBteSBkb29ybWF0IHNvIEkgZ2F2ZSBpdCBhIHBhdCIsWyJhdCIsIm9yIiwib28iXQ==)
---
## Explanation
```
:Implicit input of string U
r :Replace in U
Vq| : V joined to a string with "|" (which is RegEx "or")
@ : Pass each match X through a function
VbX : Index of X in V
Ä : Add 1
Vg : Get the element at that index in V
```
[Answer]
# Python 2, 89 bytes
```
import re
s,a=input()
print re.sub('(%s)'%')|('.join(a),lambda m:a[m.lastindex%len(a)],s)
```
`re.sub` can use a replacer function, it just gets a shifted value from the original list.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 12 bytes
## Main answer
Needs escapeing of things that will clash with PCRE, [which is acceptable](https://codegolf.stackexchange.com/questions/122854/rotate-replace-a-string/122924?noredirect=1#comment301550_122924).
[`{⍺⎕R(1⌽⍺)⊢⍵}`](https://tio.run/##pVG9TsMwEN77FMeCU6kgsXZBCARqRauKdmRxk2vi1vEFJ2lIESsDooiFkYWJF2BBYuFR8iLhnILUEQlL9@O7776z72Si94JSagrr2lZ3TzfV@qN6fL7wDqqHT/bb1f1rtX6/rWshMwGCrFMkwIKYRAi@zKAgiyAhYpcMxCUERDbmW0rQg1AuEVTGgIQZWl7n603MmaTPAqLtiAYlzKxCE0CfIgMFmgwygoz5E2kX@6IlBmQWWHLByFJoZRwrE8IoX600pgK8TkMlYNdxTqRP6Q47xxQgnJGeubpfrDixMiSTNl/Y0MJPxZ/bXP6zT7V@gdOj3vm4C5yTmR85fI6ajTfcTHdIELsMpjwIxUrFCF2PHyklw6YszvoNWLrDqa1oA9tKoXHBBA1r4ysHUrpBcMy5m9XIqR/gLIzUfKFjQ8mVTbN8WVyXq82uxmgV5akuO7xRTQVaX6YIltzy8VC0vgE "APL (Dyalog Unicode) – Try It Online")
For each non-overlapping, sequential occurrence of each element of the left argument (`⍺`), **R**eplace (`⎕R`) the occurrence with the corresponding element of the left argument rotated one step left (`1⌽⍺`), applied to (`⊢`) the right argument (`⍵`).
---
## For general interest
### A version which needs less escaping
Some arguments will clash with PCRE, so to avoid requiring the input to be pre-escaped, we can enclose each search pattern in `\Q` and `\E`:
[`{('\Q'∘,¨,∘'\E'¨⍺)⎕R(1⌽⍺)⊢⍵}`](https://tio.run/##TVG9TgJBEO55irFxjgRNbG0s1BhJIKiUNMvdcLewt3PuHeBhbI0xYmxMrK14ARsTGx7lXgRnD03YZP6/@WZ3VmXmICqV4XizcdXj232Agyusnj5a61VLDA7Ocb2qlt/N6vX9OjiqXn7q4PmzWn49bDaoCgRk5xUjOMB@QhCqAubsCBQk4rKFtISI2aUS5QyXEKsZgS4EkAlDI5BxOBaStghg0xN1Shg5TTaCNicW5mQLKBgK4c@UmxxiAztsJ1RKQ89x7FSaahtDb7pYGMoRglZNhTDY96R9FXK@J84pRwQXbEa@8R@MZ07FbPP6DVte@OuQOaoIE4@ZkhETdLdP7TKkvkK53EqL0inBcSANSglsKOJtWIOVP1LaydawnRJZn8zIirah9iBtaoTkvLvdkxqGEY3iRI8nJrWc3bq8mM7md@Viu7gbcpqnuSlbsl7Dc3Khygkc@5@gE2z8Ag "APL (Dyalog Unicode) – Try It Online")
New here are `'\Q'` prepended (`∘,`) to each (`¨`) and append (`,∘`) `'\E'` to each (`¨`).
### A version which needs no escaping
Still, this requires escaping any premature `\E` and also certain characters in the transformation patterns, so we can preprocess the search and transformation patterns to escape all problematic characters:
[`{R←⎕R'\\&'⋄('\P{Xan}'R⍺)⎕R(1⌽'\\|%|&'R⍺)⊢⍵}`](https://tio.run/##VVG9TsMwEN77FMdAL0gFiZWFARCiEqgqDAxd3OSamDq@4KSU9GdDDEARCy/AxAuwILHwKHmRcm6DEJZ8d77vu@98tsrMdlQqw/Fy6ar7l2lXTPX82sVer4nV412Avc70Utk5dqvF55aHgt3q6Uvw2easWWcf3qrFx3y5RFUgIDtvGMEBXiQEoSpgzI5AQSIhW0hLiJhdKqec4QRidUOgCyFkotAIWt/veCUibdmAW17otISB02QjaHNiYUy2gIKhEP1MueEONvCU7ZBKKeg4jp1KU21j6IwmE0M5QtBaSSE0veaFCjnfkOCAI4JjNgNf98vFQ6ditvlqhLUs1BXSRhVh4jkjMuJ6R8HZetYzhtRjlMu1tBidEuwF9TxKCbkv2/twPZTyq8b/IJ//hyNZn83IirWh9ixtVj0l58O6RT@MaBAn@mpoUsvZtcuL0c34tpys5c7JaR7lpmzJSxsekwtVTuDYfwrtY@MH "APL (Dyalog Unicode) – Try It Online")
`R←⎕R'\\&'` define the monadic operator *R* by currying the transformation pattern `\\&` (prefix a backslash to the matched text) as right operand.
`⋄` then
`'\\|%|&'R⍺` call *R*, looking for any backslash or percent or ampersand, (i.e. prefix them with a backslash) on the left argument
`1⌽` rotate that one step to the left
`'\P{Xan}'R⍺` call *R*, looking for any non-alphanumeric character, (i.e. prefix them with a backslash) on the left argument
`(`…`)⎕R(`…`)⊢⍵` **R**eplace text in the right argument – this time with safe search and transformation patterns
[Answer]
# PHP>=7.1, 79 Bytes
```
<?[$s,$o]=$_GET;$k=$o;$k[]=array_shift($k);echo strtr($s,array_combine($o,$k));
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/79f9b572fafb64bf004db07133ad3c7b879e264d)
[Answer]
# Ruby, 50 bytes
```
->a,b{a.gsub(%r[#{b*?|}]){|z|(b*2)[b.index(z)+1]}}
```
Straight forward as always :)
[Answer]
# C#, 199 bytes
```
s=>a=>{for(int i=0,j,l=a.Count-1,t;i<s.Length;i++)for(j=0;j<=l;j++)if(i==i+s.Substring(i).IndexOf(a[j])){s=s.Substring(0,i)+a[t=j<l?j+1:0]+s.Substring(i+a[j].Length);i+=a[t].Length-1;j=l;}return s;};
```
A straight port of [@KevinCruijssen's answer](https://codegolf.stackexchange.com/a/122928/38550) so go give him an upvote!
It's unfortunate that `string.Split` in C# removes the split strings otherwise I'm sure that would have been shorter.
[Answer]
# PHP, 66 bytes
```
while($t=$argv[++$i+2])$p[$argv[$i+1]]=$t;echo strtr($argv[1],$p);
```
takes input from command line arguments; assumes that none of the arguments is `0`.
Run with `php -nr '<code>'`.
] |
[Question]
[
You are to accept, on standard input, one number. You will then output the negation of that number. Your code will do nothing else. You may accept various formats if you wish (like "one" or ("uno+2.4e10i"). You may also output it how ever you wish. Note that these formats mush have existed somewhere on the internet before this question. The thing you can't do is **use the same 6 character sequence twice** in your code. Also, if any set of characters can be removed, and your code still functions the same, they must be removed (no making huge useless strings, since they could just be removed.)
This is code bowling, so the answer with the most characters wins!
Note: In case you were wondering, negation means "multiply by negative one." The representation of the numbers is up to you, but the meaning of negation is not.
[Answer]
# CJam, 278,548 characters
Stack Exchange has a 30,000 character limit, so I've uploaded my code to [Google Drive](https://docs.google.com/file/d/0Byb-iITM2Kk2VHBfV0hFSTltM0U "negate.cjam - Google Drive").
The [online interpreter](http://cjam.aditsu.net/ "CJam interpreter") chokes when decoding the lookup tables (*Maximum call stack size exceeded*), so I suggest using the [standard interpreter](http://sourceforge.net/projects/cjam/files/ "CJam - Browse Files at SourceForge.net") (requires Java).
### I/O
Input should be an integer (in whatever format CJam understands). Output is in British English.
```
$ cjam negate.cjam <<< 9990001
negative nine million nine hundred and ninety thousand and one
$ cjam negate.cjam <<< -1001000000
one milliard and one million
$ cjam negate.cjam <<< 0
zero
```
### Validity
All code is functional, so removing parts should not be possible. Note that all linefeeds are part of strings and cannot be removed.
There are no repeated sequences of six characters:
```
$ tr \\n \\t <negate.cjam | grep -P '(.{6}).*\1' | wc -c
0
```
### How it works
I've started with a [list of the first one thousand natural numbers](https://docs.google.com/file/d/0Byb-iITM2Kk2Y0hxRE9FYVhkX2s "hardcoded.txt - Google Drive") and a [list of the first three thousand three hundred and thirty-four powers of one thousand](https://docs.google.com/file/d/0Byb-iITM2Kk2ZlIyeVpYWnl5OEU "powers.txt - Google Drive").
Sadly, both lists repeat the same 6 character sequences over and over again, so I had to encode them in a way that would avoid those repeated sequences. The following CJam code accomplishes that task:
```
q
2G#b
94b
{32+}%
{c}%
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}"
"}|{zyxwvutsrqponmlkjihgfedcba`_^]~[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#
! "
er
```
It reads the list from STDIN (`q`), converts the resulting string into a base 65536 number (`2G#b`), converts the resulting integer into an array by considering it a base 94 number (`94b`), adds 32 to each integer in the array (`{32+}%`) to avoid unprintable characters, converts the array into a string (`{c}%`) and performs a character transliteration (`"…""…"er`) to get rid of characters that require escaping. This required a little trial-and-error; the natural choice (`95b`) resulted in repeated sequences.
The final code does the following:
```
{ " Define a decoding function for the lists. ";
"…""…"er{32-}%94b2G#b{c}% " Perform the steps from above in reverse order. ";
"
"/ " Split the result by linefeeds. ";
}:D;
"…":H;"…":P; " Store the encoded lists in variables. ";
q~ " Interpret the input from STDIN. ";
__ " Duplicate twice. ";
0<!{}{-1*}? " If the input is negative, multiply the last copy by -1. ";
`_ " Stringify and duplicate the last copy. ";
,3%3\-"0"*\+ " Prepend 0's to make the string length a multiple of 3. ";
3/-1% " Split into string of three characters and reverse. ";
-1:C; " Initialize variable C to -1. ";
{ " For each substring: ";
~ " Interpret it (i.e., cast to integer). ";
H=_ " Retrieve the correspond English number from H. ";
'z'e'r"o"+++= " Push 1 if the number is zero. ";
C):C; " Increment C. ";
{;}{" "+CP=+}? " Remove 0 or append the corresponding modifier from P. ";
}%
-1%_ " Reverse the array and duplicate it. ";
,1> " If the array has more than one element… ";
{
)_"and"/,1= " …and the last element doesn't contain the string 'and'… ";
'a'n'd" "+++*\+a+ " …prepend the string 'and ' to it. ";
}{_,0={H0=a+}*}? " If the array is empty, replace it with [ 'zero' ]. ";
\0> " If the input was positive, ";
{
'n'e'g'a't'i'v"e"+++++++a\+ " prepend the string 'negative'. ";
}{}?
" "* " Join the array of strings with spaces. ";
"
" " Append a linefeed. ";
```
[Answer]
# Tcl, 1073741823 (1G-1 bytes, cheating)
This is (obviously) cheating. It can be even larger in some languages like Bash, which doesn't load the whole program when it starts. Tcl runs very slow at starting, and finally refuses to run the program if the file size is about 2147483647 bytes or more.
```
set b binary
$b scan [$b format i [expr {[gets stdin]-1^3+[file size $argv0]*4}]] i a
puts $a
exit
#!!!!!#"!!!!#%!!!!#&!!!!#'!!!!#(!!!!#)!!!!#*!!!!#+!!!!#,!!!!#-!!!!#.!!!!#/!!!!#0!!!!#1!!!!#2!!!!#3!!!!#4!!!!#5!!!!#6!!!!#7!!!!#8!!!!#9!!!!#:!!!!#<!!!!#=!!!!#>!!!!#?!!!!#@!!!!#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!!!!#e!!!!#f!!!!#g!!!!#h!!!!#i!!!!#j!!!!#k!!!!#l!!!!#m!!!!#n!!!!#o!!!!#p!!!!#q!!!!#r!!!!#s!!!!#t!!!!#u!!!!#v!!!!#w!!!!#x!!!!#y!!!!#z!!!!#{!!!!#|!!!!#~!!!!#!"!!!#""!!!#%"!!!#&"!!!#'"!!!#("!!!#)"!!!#*"!!!#+"!!!#,"!!!#-"!!!#."!!!#/"!!!#0"!!!#1"!!!#2"!!!#3"!!!#4"!!!#5"!!!#6"!!!#7"!!!#8"!!!#9"!!!#:"!!!#<"!!!#="!!!#>"!!!#?"!!!#@"!!!#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"!!!#
(...1073740323 more bytes...)
|%#m+Y|%#n+Y|%#o+Y|%#p+Y|%#q+Y|%#r+Y|%#s+Y|%#t+Y|%#u+Y|%#v+Y|%#w+Y|%#x+Y|%#y+Y|%#z+Y|%#{+Y|%#|+Y|%#~+Y|%#!,Y|%#",Y|%#%,Y|%#&,Y|%#',Y|%#(,Y|%#),Y|%#*,Y|%#+,Y|%#,,Y|%#-,Y|%#.,Y|%#/,Y|%#0,Y|%#1,Y|%#2,Y|%#3,Y|%#4,Y|%#5,Y|%#6,Y|%#7,Y|%#8,Y|%#9,Y|%#:,Y|%#<,Y|%#=,Y|%#>,Y|%#?,Y|%#@,Y|%#A,Y|%#B,Y|%#C,Y|%#D,Y|%#E,Y|%#F,Y|%#G,Y|%#H,Y|%#I,Y|%#J,Y|%#K,Y|%#L,Y|%#M,Y|%#N,Y|%#O,Y|%#P,Y|%#Q,Y|%#R,Y|%#S,Y|%#T,Y|%#U,Y|%#V,Y|%#W,Y|%#X,Y|%#Y,Y|%#Z,Y|%#[,Y|%#^,Y|%#_,Y|%#`,Y|%#a,Y|%#b,Y|%#c,Y|%#d,Y|%#e,Y|%#f,Y|%#g,Y|%
```
It computes the result with its own file size. So deleting anything will change the behavior.
The above program is generated by the C++ program below.
```
#include<fstream>
#include<string>
#include<cstring>
std::ofstream f("a.tcl");
const long long size = 0x3fffffffLL;
const std::string init = "set b binary\n"
"$b scan [$b format i [expr {[gets stdin]-1^3+[file size $argv0]*4}]] i a\n"
"puts $a\n"
"exit\n";
const std::string charset = "!\"%&'()*+,-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[^_`abcdefghijklmnopqrstuvwxyz{|~";
const int ncharset = 88;
int main() {
f<<init;
long long p = init.length();
int b[5] = {};
char ch[6] = "!!!!!";
while(p < size) {
f<<"#";
p++;
if(size-p > 5) {
f.write(ch, 5);
p += 5;
}
else {
f.write(ch, size-p);
break;
}
int i=0;
while(b[i] == ncharset-1) {
ch[i] = charset[b[i]=0];
i++;
}
ch[i] = charset[++b[i]];
}
f<<std::flush;
return 0;
}
```
The 7-zipped version of the complete program has only 18MB. Maybe I can upload it somewhere if someone request for it.
I chose Tcl because it has only a small number of special characters. So I could be sure one cannot implement the same functionality by selecting some characters not to delete. I guess Lisp is better on this.
[Answer]
## Wolfram Mathematica 10↑↑3.1955 characters
Bowling-ed:
```
ToExpression[FromCharacterCode[StringLength["¡¢£¤¥¦§..."]~IntegerDigits~Nest[Hyperfactorial, 10, 2]]]
```
This is closely based on my answer to [Biggest Irreducible Hello World](https://codegolf.stackexchange.com/a/243992/84870)
Where the string is the length-6 DeBruijn Sequence of every unicode character over 128. This guarantees that it never repeats any set of 6 in itself, or outside the code since 6 never show up. Since there are only points over 128, even if there are valid symbols, none of them can read user input.
Golfed / decoded:
```
Print[-Input[]]
```
Which is converted to it's character code (80, 114, 105...) and read back as a base-Nest[Hyperfactorial, 10, 2] number. This cannot be broken down to any number besides 109, which is not at least 117 for 'u'.
This means the string length is (k!)^k^(n-1)/k^n, where k is the number of unique characters, and n is the length of each non-repeating group (6).
Oddly enough, I think this is the hard limit to this question. If it wasn't for the 6-character restriction, or unicode only have 1 million characters, then the answer would have been a tad over
```
80 * Nest[Hyperfactorial, 10, 9]]^15
```
or
```
10↑↑11.289
```
[Answer]
## C# 865
Uses DateTime parsing since a negative will throw an exception. Since Console was already used the answer is output to a Form. Also C# has string and String object.
Edit: removed some duplicate char sequences.
```
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Diagnostics;
using System.Globalization;
namespace Golf
{
class Code
{
String num;
bool isPos;
Code() { }
void In()
{
num = Console.ReadLine();
}
void Out()
{
try
{
DateTime.Parse(this.num);
isPos = true;
}
catch (Exception)//if negative throw exception
{
isPos = false;
}
int res;
double pi = Math.PI;
if(Int32.TryParse(num, out res))
{
res = (int)((isPos) ? Math.Cos(pi) * res : Math.Sin(3 * pi / 2) * res);
}
Form f = new Form();
Label l = new Label();
l.Text = res.ToString();
f.Controls.Add(l);
f.ShowDialog();
}
public static void Main(string[] args)
{
Code code = new Code();
code.In();
code.Out();
}
}
}
```
] |
[Question]
[
## Task
You must write a program or function in the language of your choice which accurately counts the number of terminal cycles of a simple directed graph.
This particular kind of directed graph is represented as an array of n integers, each with an independently-chosen random value between 1 and n (or 0 and n-1, if your language counts from 0). The graph can be thought of as arrows pointing from one index (node) to an index which matches the value found at the starting index.
Your function must be capable of accepting large graphs, up to n=1024, or any smaller integer size.
## Example
Consider this graph for n=10:
```
[9, 7, 8, 10, 2, 6, 3, 10, 6, 8]
```
Index 1 contains a 9, so there's an arrow from index 1 to index 9. Index 9 contains a 6, so there's an arrow 9 -> 6. Index 6 contains 6, which is a terminal cycle, pointing back to itself.
Index 2 contains a 7. Index 7 contains a 3. Index 3 contains an 8. Index 8 contains a 10. Index 10 contains an 8, so that's a second terminal cycle (8 -> 10 -> 8 -> 10, etc.).
Index 4 -> 10, which enters the second terminal cycle. Likewise, index 5 -> 2 -> 7 -> 3 -> 8, which is also part of the second terminal cycle.
At this point, all indices (nodes) have been checked, all paths have been followed, and two unique terminal cycles are identified. Therefore, the function should **return 2**, since that is the number of terminal cycles in this directed graph.
## Scoring
Aim for the smallest code, but make sure it counts terminal cycles correctly. Shortest code after 1 week wins.
## Test Cases
Here's are some test cases to check the correctness of your code. If your language counts array indices starting from 0, you must of course subtract 1 from the value of each array element, to prevent an out-of-bound index.
n=32, 5 cycles:
```
[8, 28, 14, 8, 2, 1, 13, 15, 30, 17, 9, 8, 18, 19, 30, 3, 8, 25, 23, 12, 6, 7, 19, 24, 17, 7, 21, 20, 29, 15, 32, 32]
```
n=32, 4 cycles:
```
[20, 31, 3, 18, 18, 18, 8, 12, 25, 10, 10, 19, 3, 9, 18, 1, 13, 5, 18, 23, 20, 26, 16, 22, 4, 16, 19, 31, 21, 32, 15, 22]
```
n=32, 3 cycles:
```
[28, 13, 17, 14, 4, 31, 11, 4, 22, 6, 32, 1, 13, 15, 7, 19, 10, 28, 9, 22, 5, 26, 17, 8, 6, 13, 7, 10, 9, 30, 23, 25]
```
n=32, 2 cycles:
```
[25, 23, 22, 6, 24, 3, 1, 21, 6, 18, 20, 4, 8, 5, 16, 10, 15, 32, 26, 25, 27, 14, 13, 12, 9, 9, 29, 8, 13, 31, 32, 1]
```
n=32, 1 cycle:
```
[6, 21, 15, 14, 22, 12, 5, 32, 29, 3, 22, 23, 6, 16, 20, 2, 16, 25, 9, 22, 13, 2, 19, 20, 26, 19, 32, 3, 32, 19, 28, 16]
```
n=32, 1 cycle:
```
[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, 1, 2, 3, 4, 5, 6, 7]
```
n=1024, 6 cycles:
```
[239, 631, 200, 595, 178, 428, 582, 191, 230, 551, 223, 61, 564, 463, 568, 527, 143, 403, 154, 236, 928, 650, 14, 931, 236, 170, 910, 782, 861, 464, 378, 748, 468, 779, 440, 396, 467, 630, 451, 130, 694, 167, 594, 115, 671, 853, 612, 238, 464, 771, 825, 471, 167, 653, 561, 337, 585, 986, 79, 506, 192, 873, 184, 617, 4, 259, 4, 662, 623, 694, 859, 6, 346, 431, 181, 703, 823, 140, 635, 90, 559, 689, 118, 117, 130, 248, 931, 767, 840, 158, 696, 275, 610, 217, 989, 640, 363, 91, 129, 399, 105, 770, 870, 800, 429, 473, 119, 908, 481, 337, 504, 45, 1011, 684, 306, 126, 215, 729, 771, 5, 302, 992, 380, 824, 868, 205, 807, 917, 407, 759, 181, 640, 685, 795, 258, 180, 900, 20, 773, 546, 866, 564, 761, 632, 895, 968, 980, 651, 225, 676, 18, 685, 784, 208, 227, 3, 267, 852, 57, 487, 566, 633, 849, 309, 543, 145, 575, 811, 621, 560, 492, 24, 665, 66, 851, 168, 262, 259, 754, 481, 565, 768, 172, 1012, 241, 3, 370, 985, 389, 82, 779, 744, 829, 836, 249, 975, 909, 840, 226, 867, 499, 192, 909, 972, 735, 252, 785, 545, 486, 186, 1011, 89, 939, 649, 110, 119, 185, 836, 717, 545, 938, 621, 946, 94, 363, 721, 177, 747, 59, 819, 146, 283, 821, 547, 654, 941, 755, 18, 449, 367, 499, 944, 62, 553, 435, 344, 900, 25, 251, 920, 902, 99, 326, 98, 495, 385, 929, 865, 327, 725, 674, 33, 173, 429, 873, 558, 90, 460, 366, 543, 583, 954, 792, 213, 536, 670, 49, 738, 802, 1015, 23, 915, 119, 263, 307, 601, 474, 971, 826, 613, 446, 37, 145, 894, 901, 307, 906, 886, 990, 89, 798, 384, 487, 822, 354, 768, 902, 163, 179, 134, 920, 439, 619, 215, 94, 709, 744, 366, 543, 349, 347, 2, 438, 141, 486, 19, 998, 500, 857, 955, 932, 1, 587, 195, 646, 550, 887, 626, 400, 348, 154, 808, 678, 873, 186, 282, 168, 993, 722, 56, 345, 5, 226, 328, 22, 894, 658, 264, 13, 803, 791, 359, 217, 997, 168, 578, 952, 734, 964, 898, 659, 628, 980, 15, 31, 439, 13, 875, 687, 1004, 1023, 165, 642, 561, 897, 711, 124, 404, 346, 723, 774, 352, 784, 276, 395, 14, 443, 343, 153, 510, 590, 172, 215, 130, 106, 295, 906, 133, 758, 483, 898, 391, 760, 702, 972, 721, 611, 592, 1001, 724, 934, 59, 831, 171, 253, 869, 431, 538, 20, 648, 76, 351, 103, 33, 385, 852, 437, 470, 95, 434, 408, 430, 994, 366, 706, 809, 532, 161, 388, 668, 245, 965, 365, 913, 471, 927, 245, 256, 805, 540, 380, 995, 446, 657, 545, 573, 955, 499, 322, 949, 635, 401, 185, 421, 626, 534, 429, 930, 633, 563, 348, 626, 518, 682, 233, 775, 444, 42, 199, 57, 271, 683, 397, 883, 620, 768, 8, 331, 497, 19, 340, 900, 919, 497, 276, 78, 252, 164, 764, 927, 242, 270, 759, 824, 945, 886, 262, 59, 439, 217, 720, 519, 862, 626, 326, 339, 589, 16, 565, 947, 604, 144, 87, 520, 256, 240, 336, 685, 361, 998, 805, 678, 24, 980, 203, 818, 855, 85, 276, 822, 183, 266, 347, 8, 663, 620, 147, 189, 497, 128, 357, 855, 507, 275, 420, 755, 131, 469, 672, 926, 859, 156, 127, 986, 489, 803, 433, 622, 951, 83, 862, 108, 192, 167, 862, 242, 519, 574, 358, 549, 119, 630, 60, 925, 414, 479, 330, 927, 94, 767, 562, 919, 1011, 999, 908, 113, 932, 632, 403, 309, 838, 341, 179, 708, 847, 472, 907, 537, 516, 992, 944, 615, 778, 801, 413, 653, 690, 393, 452, 394, 596, 545, 591, 136, 109, 942, 546, 57, 626, 61, 587, 862, 829, 988, 965, 781, 849, 843, 815, 60, 928, 784, 388, 341, 491, 565, 83, 110, 164, 38, 1024, 859, 297, 520, 327, 733, 699, 631, 78, 178, 671, 895, 818, 637, 99, 425, 933, 248, 299, 333, 144, 323, 105, 849, 942, 767, 265, 72, 204, 547, 934, 916, 304, 919, 273, 396, 665, 452, 423, 471, 641, 675, 60, 388, 97, 963, 902, 321, 826, 476, 782, 723, 99, 735, 893, 565, 175, 141, 70, 918, 659, 935, 492, 751, 261, 362, 849, 593, 924, 590, 982, 876, 73, 993, 767, 441, 70, 875, 640, 567, 920, 321, 46, 938, 377, 905, 303, 736, 182, 626, 899, 512, 894, 744, 254, 984, 325, 694, 6, 367, 532, 432, 133, 938, 74, 967, 725, 87, 502, 946, 708, 122, 887, 256, 595, 169, 101, 828, 696, 897, 961, 376, 910, 82, 144, 967, 885, 89, 114, 215, 187, 38, 873, 125, 522, 884, 947, 962, 45, 585, 644, 476, 710, 839, 486, 634, 431, 475, 979, 877, 18, 226, 656, 573, 3, 29, 743, 508, 544, 252, 254, 388, 873, 70, 640, 918, 93, 508, 853, 609, 333, 378, 172, 875, 617, 167, 771, 375, 503, 221, 624, 67, 655, 465, 272, 278, 161, 840, 52, 1016, 909, 567, 544, 234, 339, 463, 621, 951, 962, 1019, 383, 523, 279, 780, 838, 984, 999, 29, 897, 564, 762, 753, 393, 205, 31, 150, 490, 156, 796, 586, 676, 773, 465, 489, 1024, 433, 214, 701, 480, 604, 280, 241, 563, 943, 911, 12, 400, 261, 883, 999, 207, 618, 141, 959, 767, 978, 461, 992, 982, 272, 143, 404, 645, 331, 348, 783, 698, 827, 82, 145, 536, 449, 852, 750, 789, 413, 913, 420, 14, 499, 285, 533, 223, 75, 591, 994, 884, 237, 63, 411, 563, 611, 801, 173, 759, 278, 318, 772, 1018, 48, 440, 333, 611, 834, 423, 583, 22, 716, 393, 794, 83, 83, 864, 859, 600, 525, 808, 569, 95, 952, 852, 567, 651, 2, 984, 906, 992, 747, 602, 143, 547, 1008, 940, 245, 633, 378, 193, 771, 965, 648, 437, 873, 591, 664, 271, 777, 274, 742, 68, 429, 825, 144, 55, 272, 279, 6, 400, 485, 66, 311, 663, 441, 23, 988, 726, 48, 624, 302, 617, 120, 653, 810, 641, 142]
```
[Answer]
# Mathematica 69
## Code
This finds the number of graph components.
```
f@l_ := Length@WeaklyConnectedComponents@Graph@Thread[Range@Length@l -> l]
```
---
The first test case:
```
v = {8, 28, 14, 8, 2, 1, 13, 15, 30, 17, 9, 8, 18, 19, 30, 3, 8, 25, 23, 12, 6, 7, 19, 24, 17, 7, 21, 20, 29, 15, 32, 32}
f[v]
```
>
> 5
>
>
>
---
## Analysis
Make a list of directed edges between indices, (using example 1).
```
Thread[Range@Length@v -> v
```
>
> {1 -> 8, 2 -> 28, 3 -> 14, 4 -> 8, 5 -> 2, 6 -> 1, 7 -> 13, 8 -> 15,
> 9 -> 30, 10 -> 17, 11 -> 9, 12 -> 8,
> 13 -> 18, 14 -> 19, 15 -> 30,
> 16 -> 3, 17 -> 8, 18 -> 25, 19 -> 23, 20 -> 12, 21 -> 6, 22 -> 7,
> 23 -> 19, 24 -> 24, 25 -> 17, 26 -> 7, 27 -> 21, 28 -> 20, 29 -> 29,
> 30 -> 15, 31 -> 32, 32 -> 32}
>
>
>
---
`Graph` draws a graph showing the graph components.
`ImagePadding` and `VertexLabels`
are used here to show the indices.
```
Graph[Thread[Range[Length@v] -> v], ImagePadding -> 30, VertexLabels -> "Name"]
```
## components
`WeaklyConnectedComponents` returns the list of vertices for each component.
`Length` returns the number of components.
```
c = WeaklyConnectedComponents[g]
Length[c]
```
>
> {{17, 10, 25, 8, 18, 1, 4, 12, 15, 13, 6, 20, 30, 7, 21, 28, 9, 22,
> 26, 27, 2, 11, 5}, {14, 3, 19, 16, 23}, {32, 31}, {24}, {29}}
>
>
> 5
>
>
>
---
## Timing of sample list with 1024 elements:
Timing: 0.002015 sec
```
f[z] // AbsoluteTiming
```
>
> {0.002015, 6}
>
>
>
---
Just for fun, here's a picture of the final test case, graphed. I omitted the vertex labels; there are too many.
```
Graph[Thread[Range[Length@z] -> z], GraphLayout -> "RadialEmbedding"]
```

[Answer]
### GolfScript, 25 characters
```
:I{{I=.}I.+,*]I,>$0=}%.&,
```
Same approach as [Keith Randall](https://codegolf.stackexchange.com/users/67/keith-randall)'s solution but in GolfScript. Note that GolfScript has zero-indexed arrays. [Online tester](http://golfscript.apphb.com/?c=O1s4IDYgNyA5IDEgNSAyIDkgNSA3XQoKOkl7e0k9Ln1JLissKl1JLD4kMD19JS4mLAo%3D&run=true).
```
:I # Assign input to variable I
{ # Foreach item in I
{I=.} # Code block: take the n-th list item
I.+,* # Iterate the code block 2*len(I) times
] # and gather result in an array
I,> # Take last len(I) items
$0= # Get minimum
}%
.& # Take unique items
, # Count
```
[Answer]
## Python, 132 116 chars
```
def T(V):
n=len(V);r=range(n);s={}
for i in r:
p=[i]
for k in r+r:p+=[V[p[-1]]]
s[min(p[n:])]=1
return len(s)
```
For each index, we follows edges for n hops, which guarantees we are in a terminal cycle. We then follow n more hops and find the minimum index in that cycle. The total number of terminal cycles is then just the number of different minima we find.
[Answer]
In Python:
```
def c(l):
if(l==[]):
return 0
elif (l[-1]==len(l)):
return c(l[:-1])+1
else:
return c([[x,l[-1]][x==len(l)] for x in l[:-1]])
```
[Answer]
# J - 61 53 char
This one was a doozy.
```
#@([:#/.~[:+./ .*"1/~@e.<~.@(],;@:{~)^:_&.>])@:(<@<:)
```
The `<@<:` turn the list into a J graph, which looks like a list of boxes, and the box at index `i` contains all the nodes that node `i` connects to. J indexes from zero, so we use `<:` to decrement everything by one before boxing with `<`.
```
(<@<:) 9 7 8 10 2 6 3 10 6 8
+-+-+-+-+-+-+-+-+-+-+
|8|6|7|9|1|5|2|9|5|7|
+-+-+-+-+-+-+-+-+-+-+
```
The `<~.@(],;@:{~)^:_&.>]` turns each node into a list of all the nodes that can be reached from it. The `<...&.>]` is responsible for making this happen to each node, and the `~.@(],;@:{~)^:_` actually comes from [a J golf of this 'nodes reachable' task](https://codegolf.stackexchange.com/a/26103/5138) I did a couple of weeks ago.
```
(<~.@(],;@:{~)^:_&.>])@:(<@<:) 9 7 8 10 2 6 3 10 6 8
+---+-------+---+---+---------+-+-----+---+-+---+
|8 5|6 2 7 9|7 9|9 7|1 6 2 7 9|5|2 7 9|9 7|5|7 9|
+---+-------+---+---+---------+-+-----+---+-+---+
```
`e.` performs an interesting task. If the "reachability" closure of the graph (the version of the graph such that if there are directed edges X→Y and Y→Z we add the edge X→Z.) has N nodes and E edges, then `e.` on this graph makes a boolean matrix of N rows and E columns, with a True if the corresponding node shares a reachable node with this edge. Confusing, but bear with me.
```
([:e.<~.@(],;@:{~)^:_&.>])@:(<@<:) 9 7 8 10 2 6 3 10 6 8
1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0
0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 0 1 1 1 1 1 0 1 1
0 0 0 0 1 1 1 1 1 1 0 0 0 1 1 0 0 1 1 1 1 0 1 1
0 0 0 0 1 1 1 1 1 1 0 0 0 1 1 0 0 1 1 1 1 0 1 1
0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 0 1 1
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0
0 0 0 1 1 1 1 1 1 1 0 0 1 1 1 0 1 1 1 1 1 0 1 1
0 0 0 0 1 1 1 1 1 1 0 0 0 1 1 0 0 1 1 1 1 0 1 1
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0
0 0 0 0 1 1 1 1 1 1 0 0 0 1 1 0 0 1 1 1 1 0 1 1
```
Next, we have to find the number of terminal cycles, i.e. the number of groups that share Trues amongst their columns. We want to make sort of a multiplication table of the rows (`"1/~`), and we use a kind of inner product as the multiplication, one that ANDs pairwise and then ORs all the results together (`+./ .*`). The resulting matrix is a square table with a True in each position that two rows share at least one column between them.
```
([:+./ .*"1/~@e.<~.@(],;@:{~)^:_&.>])@:(<@<:) 9 7 8 10 2 6 3 10 6 8
1 0 0 0 0 1 0 0 1 0
0 1 1 1 1 0 1 1 0 1
0 1 1 1 1 0 1 1 0 1
0 1 1 1 1 0 1 1 0 1
0 1 1 1 1 0 1 1 0 1
1 0 0 0 0 1 0 0 1 0
0 1 1 1 1 0 1 1 0 1
0 1 1 1 1 0 1 1 0 1
1 0 0 0 0 1 0 0 1 0
0 1 1 1 1 0 1 1 0 1
```
Now all that's left to do is to check how many different kinds of row patterns there are. So we do exactly that: group together rows of the same kind (`/.~`), report the number in each group (`#`), and then take the number of groups (`#@`).
```
#@([:#/.~[:+./ .*"1/~@e.<~.@(],;@:{~)^:_&.>])@:(<@<:) 9 7 8 10 2 6 3 10 6 8
2
```
Usage on other examples:
```
tcc =: #@([:#/.~[:+./ .*"1/~@e.<~.@(],;@:{~)^:_&.>])@:(<@<:) NB. name
tcc 8 28 14 8 2 1 13 15 30 17 9 8 18 19 30 3 8 25 23 12 6 7 19 24 17 7 21 20 29 15 32 32
5
tcc 20 31 3 18 18 18 8 12 25 10 10 19 3 9 18 1 13 5 18 23 20 26 16 22 4 16 19 31 21 32 15 22
4
tcc 6 21 15 14 22 12 5 32 29 3 22 23 6 16 20 2 16 25 9 22 13 2 19 20 26 19 32 3 32 19 28 16
1
tcc tentwentyfour NB. the 1024-node example
6
```
Unfortunately the 1024 element case now takes a really long time to terminate. The previous version `<:@#@((#~0={.+/@:*"1])^:a:)@e.@(~.@(],;@:{~)^:_&.>~<)@:(<@<:)` (61 char) took a little over a second to do this.
[Answer]
# Python (96)
Very, very, very, very based on user2228078's answer, as it works exactly the same, but is more golfed:
```
c=lambda l:(1+c(l[:-1])if l[-1]==len(l)else c([[x,l[-1]][x==len(l)]for x in l[:-1]]))if l else 0
```
(Technical question: should a golfing of someone elses answer be community wiki?)
[Answer]
# Python (89) (87)
```
def c(G):
u=i=0
for _ in G:
j=i;i+=1
while j>=0:G[j],j=~i,G[j]
u+=j==~i
return u
```
The main idea is to start at each node at turn and walk along the path from it, marking each node we visit with a label unique to the node we started at. If we ever hit a marked node, we stop walking, and check if the marking is the one corresponding to our starting node. If it is we must have walked a loop, so we increment the count of cycles by one.
In the code, `u` is the cycle counter, `i` is the starting node, `j` is the current node we're walking. The label corresponding to starting node `i` is its bit-complement `~i` which is always negative. We mark a node by pointing it to that value, overwriting whatever node it actually pointed to (being careful to walk to that node before it's forgotten).
We know we've hit a marked node when we walk to a negative-value "node" immediately afterwards. We check if that negative value is the current label to see whether we've walked a cycle. Since each node we walk is effectively deleted, each cycle will only be walked once.
It saves characters to count up `i` manually with a dummy loop variable `_` then as `for i in range(len(G))`. Python lists are 0-indexed. If they were instead 1-indexed, we could save two characters by writing `j=i=i+1` to have `i` and `j` be 1 for the first loop, and
write `j>0` in place of `j>=0`.
## Edit:
We can save two characters by iterating `i` over the elements of the list rather than the indices, since node that are not pointed to by any edge don't matter. We have to iterate over `set(G)` though to avoid repeating a start node that it pointed to by multiple other nodes.
```
def c(G):
u=0
for i in set(G):
j=i
while j>=0:G[j],j=~i,G[j]
u+=j==~i
return u
```
] |
[Question]
[
Write a complete program (not just a function) which using stdin takes in a string of arbitrary length (assume string-length at least one) composed only of digits 0-9 and outputs using stdout the substring which appears most often in the input string. The input string can be any length and the substring can be maximum half the length of the input string because it must appear at least twice non-overlapped to be printed.
We following the following hierarchy selecting the substring to be printed.
1. First priority, the longest substring
2. Second priority, if we have multiple substrings of the same length, we pick the one appearing the most often.
3. Third priority, if multiple substrings of the same size appear the same number of times, pick the one which appears first scanning from the left.
Here are some test cases followed by the rules and some explanation.
```
./myprogram 123456
No substrings repeat.
```
The substring must appear more than once. If no substrings repeat the the output must exactly be the string "No substrings repeat." complete with the capitalization and the period.
```
./myprogram 12121
12
```
The sub-strings must not overlap. So in this case the largest repeating substring is `12` instead of `121`.
```
./myprogram 99999999
9999
```
We want the largest substring which appears at least twice. Here `9`, `99`, `999`, and `9999` all appears at least twice. But we want the largest substring which appears at least twice.
```
./myprogram 321321788788788
788
```
`321`, `788`, `887`, and `878` each appear multiple times so we pick `788` which appears the most often.
```
./myprogram 12121
12
```
`12` and `21` both appear twice so we pick `12` which appears first from the left.
```
./myprogram 12012112299999999
9999
```
The string `12` occurs first and appears thrice but `9999` is longer and appears only twice so we pick `9999` because it has the highest priority.
```
./myprogram 56698853211564788954126162561664412355899990001212345
412
```
No substrings of length more than three repeat. `412`, `616`, and `123` each appear twice. `412` occurs first and is thus printed.
I think I have taken care of all the cases. True code-golf. The shortest code in any language wins. In the case of ties, I pick the one with the highest upvotes after waiting at least for two weeks and probably longer. So the community please feel free to upvote any solutions you like. The cleverness/beauty of the code matters much more than who posts first.
Happy coding!
[Answer]
# ruby, 104 characters
```
r=gets.size.downto 1
r.find{|l|r.find{|c|$><<$1 if/(.{#{l}})(.*\1){#{c}}/}}||$><<"No substrings repeat."
```
Uses my favourite, nested `find`s. Also, good old magic variables and other perlisms.
[Answer]
## Perl, 99 (+1) bytes
```
$_=$;{(sort%;)[m{(.+).*\1(?{$;{$;x$+=~y///c.1x@{[/$+/g]}.2x$+[1]}=$+})^}]}
||"No substrings repeat."
```
*Requires a `-p` command line switch.*
For each repeated substring a hash entry is created, such that the largest substring, repeated the most times, with the earliest position is guaranteed to be the smallest key in the hash. The hash is then sorted, and the corresponding value for the smallest key is output.
Sample Usage:
```
$ echo 123456 | perl -p repeated-substring.pl
No substrings repeat.
$ echo 12121 | perl -p repeated-substring.pl
12
$ echo 99999999 | perl -p repeated-substring.pl
9999
$ echo 321321788788788 | perl -p repeated-substring.pl
788
$ echo 12012112299999999 | perl -p repeated-substring.pl
9999
$ echo 56698853211564788954126162561664412355899990001212345 | perl -p repeated-substring.pl
412
```
[Answer]
### GolfScript, 74 characters
```
"No substrings repeat."\:i,,{){i@><}+i,,%.{i\/,}%$-1=.2>*{i@/,=}+,0=}/]-1=
```
Brute force GolfScript approach (which would have been much shorter if `$` would be stable). Note that the input must include the newline in order to give correct results.
[Answer]
## Ruby, 108+1=109
```
$_=$_.scan(/(.+)(?=.*\1)/).map(&:first).max_by{|s|[s.size,$_.scan(s).size,-~/#{s}/]}||'No substrings repeat.'
```
Usage:
```
echo 56698853211564788954126162561664412355899990001212345 | ruby -p repeats_most_often.rb
```
I could save a few chars if I assumed Ruby's sort was stable, but it's not always. Also in older versions of Ruby I could replace the `$_.scan` with `scan`.
[Answer]
# C#, 120 chars
```
Regex.Matches("(.{2,}).*\1",input).Select(n=>n.ToString()).OrderBy(n=>n.Length).LastOrDefault()??"No substrings repeat."
```
## With boilerplate, 171
```
class A{int Main(string[] a){Console.WriteLine(Regex.Matches("(.{2,}).*\1", a[0]).Select(n=>n.ToString()).OrderBy(n=>n.Length).LastOrDefault()??"No substrings repeat.");}}
```
] |
[Question]
[
In the game 15, two players take turns selecting numbers from 1 to 9 (without choosing any number that either player has already selected). A player wins if he or she has three numbers that add up to 15. If all the numbers have been selected and no combination of either player's adds up to 15, then the game is a tie.
Your task is to build a function that takes the state of a game of 15 (represented in any form you like) and returns which number to move next, which will act as an AI to play the game with another player. You may assume that the position is legal (no player has more than one number more than the other player, and no player already has three numbers that add up to 15).
The AI must be perfect - that is, if it's given a winning position, it must force a win, and if it's given a non-losing position (a position where its opponent does not have a winning strategy), it must not allow its opponent to give it a losing position (which is possible, as 15 is a solved game).
The shortest code wins.
(note: I will accept the currently shortest answer and change it if a shorter answer appears.)
[Answer]
## GolfScript (129 86 81 85 75 chars)
```
{:C[{.`{1$-\{+15\-}+%}:T+/}/10,1>C~+-:^{.{^T&}+C/,2<*T}/5^{1&}$][]*^&0=}:N;
```
Expected input format: `[[int int ...][int int ...]]` where the first list is my numbers and the second list is my opponent's numbers. For interactive testing, add `~N` to the end of the script and supply a string in that format: e.g.
```
$ golfscript.rb 15.gs <<<"[[5][2 8]]"
9
$ golfscript.rb 15.gs <<<"[[2][5 8]]"
6
```
---
Heuristics:
1. If I can win this turn, do it
2. If opponent would win next turn, block
3. If I can force opponent to a square which prevents them from creating a fork, do it
4. `5` is the only number which can contribute to winning in 4 ways, so grab it if available.
5. Favour evens over odds
---
Test framework:
```
{:Set;[1 5 9 1 6 8 2 4 9 2 5 8 2 6 7 3 4 8 3 5 7 4 5 6]3/{.Set&=},!!}:isWin;
{
# Mine His
.isWin{
"Lost "@`@`++puts
}{
# If there are available moves, it's my move.
# If I won before my move, I've still won after it.
1$1$+,9<!!{
# my move
1$1$[\\]N 2$\+
# Mine His Mine'
.isWin!{
# his move
10,1>2$2$+-{
2$\+1$\
# Mine His Mine' Mine' His'
fullTest
# Mine His Mine'
}/
}*;
}*;;
}if
}:fullTest;
# I move first
'[][]fullTest'puts [][]fullTest
# He moves first
'[][1]fullTest'puts [][1]fullTest
'[][2]fullTest'puts [][2]fullTest
'[][5]fullTest'puts [][5]fullTest
```
[Answer]
### Ruby, 330 315 341 characters
```
def m i
$_=i.join
l='159258357456168249267348'.scan /(.)(.)(.)/
return 1 if /^5(28|46|64|82)$/
return 4 if /^[258]{3}$/
return 2 if /^[456]{3}$/
i.each{|i|l.map{|l|return l if(l-=i).size==1&&!/[#{l=l[0]}]/}}
.map{|i|l.map{|m|l.map{|l|return (l&m)[0] if(z=l-i|m-i).size==3&&l!=m&&!/[#{z.join}]/}}}
"524681379".chars{|z|return z if !/#{z}/}
end
```
I'll withhold the details for now, but let's say that it is based on the optimal algorithm to a similar problem that has been solved as well and whose optimal algorithm happened to work just as fine here. ~~Assumptions have been made - this will choose bad moves in situations that cannot be produced by this algorithm playing against another player, only by two players against each other.~~
Input: an array of two arrays of one-digit strings. Each array represents the values taken by one player - the first one is the AI, the second one is the opponent.
Output: either a number, or a single-digit string. They are semantically equivalent. Normalisation to strings would cost 8 characters.
Three more characters can be saved if we assume the order of numbers given by the caller - change the regex in L5 to `/^285$/` or `/^258$/` depending on the order produced from the game `(opponent)5-(ai)2-(opponent)8`.
[Answer]
## GolfScript (90 85 84 chars)
```
{.~.,3/*..2%.@^++3*3/{~++15=},,*10,1>2$~+-@`{([2$+]+v[0=~)\]}+%[1,]or$0=+}:v{1=}+:N;
```
This takes a completely different approach, but is potentially susceptible to optimisations to beat the heuristic one. Here we do a full game tree analysis, incredibly slowly. (No, I mean it. It takes several *hours* to run the full test, mainly because of the ``{...}+` which adds the current state to the next-move loop). Note that the hard part is identifying a winning state (a third of the code, at present).
There are some ugly hacks in the non-recursive sections. In particular, when the position is identified as a losing one we take our positions as the `[value move]` array, relying on the move being irrelevant and the value being non-zero.
] |
[Question]
[
## Challenge
>
> In this task you would be given an integer N
> (less than 10^6), output the number of terms in the [Farey
> sequence](http://en.wikipedia.org/wiki/Farey_sequence) of order N.
>
>
>
The input N < 106 is given in a single line, the inputs are terminated by EOF.
The challenge is to implement the fastest solution so that it can process a maximum of 106-1 values as fast as possible.
**Input**
```
7
10
999
9999
79000
123000
```
**Output**
```
19
33
303793
30393487
1897046599
4598679951
```
**Constraints**
* You can use any language of your choice
* Take care about your fingers, do not use more than **4096** bytes of code.
* Fastest solution, based on the running time measured for N = 106-1.
[Answer]
**C - 0.1 Secs on Ideone**
<http://www.ideone.com/E3S2t>
Explanation included in code.
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
long long A[1000001]={0};
int main()
{
int isprime[1001],d,n,k,i,e,p;
for (n=2;n<1001;n++)
isprime[n]=1;
//Sieve of Eratosthenes for Prime
//Storing the smallest prime which divides n.
//If A[n]=0 it means it is prime number.
for(d=2;d<1001;d++)
{
if(isprime[d])
{
for (n=d*d;n<1001;n+=d)
{
isprime[n]=0;
A[n]=d;
}
for (;n<=1000000;n+=d)
A[n]=d;
}
}
//Uses multiplicative property of
//Euler Totient Function
//Phi(n)=Phi(p1^k1)*Phi(p2^k2)...*Phi(pr^kr)
//and Phi(pi^ki)=(pi-1)*(pi^(ki-1))
A[1]=1;
for(n=2;n<=1000000;n++)
{
if (A[n]==0)
A[n]=n-1;
else
{
p=A[n],k=n/p,e=1;
while (k%p==0)
k/=p,e*=p;
A[n]=A[k]*e*(p-1);
}
}
//Number of terms in Farey Series
//|F(n)| = 1 + Sigma(i,1,n,phi(i))
A[1]=2;
for(n=2;n<=1000000;n++)
A[n]+=A[n-1];
while (~scanf("%d",&i))
printf("%lld\n",A[i]);
return 0;
}
```
A little more explanation:
>
> For all numbers we get a prime factor
> of it from the sieve(or 0 if it is a
> prime). Next we use the fact that ETF
> is multiplicative. That is if m and n
> are coprime then
> `phi(m*n)=phi(m)*phi(n)`. Here we take
> out the multiple of prime factor out
> and hence the left part and the
> multiple part are co-prime. We already
> have the ETF for the left part since
> it is either smaller then current
> value or equal to 1. We only need to
> calculate the ETF for the multiple
> which we calculate using the formula
> `phi(pi^ki)=(pi-1)*(pi^(ki-1))`.
>
>
>
[Answer]
## C (0.2 sec in Ideone)
I thought of adding my approach too: (this is not as fast as Gaurav's)
```
#include <stdio.h>
#define N 1000000
long long Phi[N+1];
//Sieve ETF
int main(){
int i,j;
for(i=1;i<=N;i++)
Phi[i]=i;
for(i=2;i<=N;i++){
if(Phi[i] == i)
for(j=i;j<=N;j+=i)
Phi[j] = (Phi[j]/i)*(i-1);
}
int t,n;
Phi[1]=2;
for(i = 2; i < N; i++)
Phi[i] += Phi[i-1];
for(;~scanf("%d",&n);)
printf("%lld\n",Phi[n]);
return 0;
}
```
[TESTING ...](http://www.ideone.com/tlDpX)
[Answer]
# C - Less than a second for 999999
```
#include "stdio.h"
#include "time.h"
#define i64 unsigned long long
#define i32 unsigned int
#define PLIM 1100
#define FLIM 1000000
i32 primes[PLIM];
i64 f[FLIM];
int main(int argc, char *argv[]){
i64 start=clock();
i32 primesindex=0;
f[0]=1;
f[1]=2;
i32 a,b,c;
i32 notprime;
//Make a list of primes
for(a=2;a<PLIM;a++){
notprime=0;
for(b=0;b<primesindex;b++){
if(!(a%primes[b])){
notprime=1;
}
}
if(!notprime){
primes[primesindex]=a;
primesindex++;
}
}
i32 count,divided;
i32 nextjump=4;
i32 modlimit=2;
i32 invalue;
a=2;
for(c=1;c<argc;c++){
invalue=atoi(argv[c]);
if(invalue<FLIM && invalue){
//For each number from a to invalue find the totient by prime factorization
for(;a<=invalue;a++){
count=a;
divided=a;
b=0;
while(primes[b]<=modlimit){
if(!(divided%primes[b])){
divided/=primes[b];
//Adjust the count when a prime factor is found
count=(count/primes[b])*(primes[b]-1);
//Discard duplicate prime factors
while(!(divided%primes[b])){
divided/=primes[b];
}
}
b++;
}
//Adjust for the remaining prime, if one is there
if(divided>1){
count=(count/divided)*(divided-1);
}
//Summarize with the previous totients
f[a]=f[a-1]+(i64)count;
//Adjust the limit for prime search if needed
if(a==nextjump){
modlimit++;
nextjump=modlimit*modlimit;
}
}
//Output result
printf("%I64u\n",f[invalue]);
}
}
i64 end=clock();
//printf("Runtime: %I64u",end-start);
return 0;
}
```
This takes input from command line.
The computation is a simple sum of totients, it's only done once and only up to the biggest input.
Here is an Ideone version: <http://www.ideone.com/jVbc0>
[Answer]
## J, 0.2s, short code
It feels weird to write ungolfed J, but it actually *is* the language for the task, for once.
```
input =: ". ;. _2 stdin ''
phi =: 5 & p:
max =: >. / input
acc_totient =: +/ \ phi >: i. max
output =: >: (<: input) { acc_totient
echo output
```
Reads input, constructs accumulated sum of totients up to the max, and reads output from there.
[Answer]
# VB.NET, 0.11 s for 10^6
This is basically a totient computation using prime sieve. The time is measured 10 times and the average is computed.
```
Module Module1
Sub Main()
Dim sw As New Stopwatch
Dim M As Integer = Console.ReadLine()
sw.Start()
Dim is_prime(M) As Integer
Dim phi(M) As Integer
For i = 0 To M
phi(i) = i
is_prime(i) = True
Next
For i = 2 To M
If is_prime(i) = True Then
phi(i) = i - 1
Dim j As Integer = 2 * i
Do Until j > M
is_prime(j) = False
phi(j) = phi(j) - (phi(j) / i)
j += i
Loop
End If
Next
Dim result As Long = 1
For i = 1 To M
result += phi(i)
Next
Console.WriteLine(result)
sw.Stop()
Console.WriteLine("Time Elasped : " & sw.ElapsedMilliseconds)
Dim a = Console.ReadLine()
End Sub
End Module
```
] |
[Question]
[
It can be easily proven using Hall's marriage theorem that given fixed \$n\$ and \$k<n/2\$, [there is an injective (one-to-one) function](https://math.stackexchange.com/questions/3562859/extending-k-element-subsets-of-an-n-element-set-to-k1-element-subsets) from all \$n\$-bit strings with \$k\$ ones to \$n\$-bit strings with \$k+1\$ ones such that an input and its corresponding output differ by exactly one bit. For example, with \$n=5,k=2\$:
```
00011 -> 00111
00110 -> 01110
01100 -> 11100
11000 -> 11001
10001 -> 10011
00101 -> 01101
01010 -> 11010
10100 -> 10101
01001 -> 01011
10010 -> 10110
```
However, the proof is non-constructive. It would be nice to have an explicit construction.
## Task
Given a nonempty \$n\$-bit string with \$k<n/2\$ ones, output an \$n\$-bit string with \$k+1\$ ones formed only by changing one zero in the input to one, such that the \$\binom nk\$ distinct inputs map to \$\binom nk\$ distinct outputs. You must prove that your program has this property.
The bit strings may be represented in any reasonable format, including as decimal numbers and as subsets of a specified \$n\$-element set. You may also simply output the index of the changed bit rather than the full string.
**The output must be deterministic** — it is not allowed to simply change the first zero in the input each time for example; there must be exactly one mapping implemented for each valid \$(n,k)\$ pair. The program or function must also work for all valid \$(n,k)\$ pairs *in theory*, and have at most polynomial time complexity in \$n\$.
Otherwise this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins.
---
This question was based on [this MathsSE post](https://math.stackexchange.com/q/4641994/357390), which at the time of posting this question had no answers. There is now [an answer](https://math.stackexchange.com/a/4642385/357390) by Mike Earnest giving an injection that satisfies this challenge's constraints:
* Repeatedly delete occurrences of `10` in the bitstring. This leaves a string of the form `0...01...1` with at least one zero.
* Change the rightmost remaining zero (at its original location) to a one.
```
100011010001011
XX XXXX XX
001 00 11
X X
00 0 11
^ change this to 1
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 21 bytes
```
s;((1(?2)*0)|0)*\K0;1
```
[Try it online!](https://tio.run/##K0gtyjH9/7/YWkPDUMPeSFPLQLPGQFMrxtvA2vD/f0MDAwNDQwMwBWT8yy8oyczPK/6vWwAA "Perl 5 – Try It Online")
This implements the injection described [by Mike Earnest](https://math.stackexchange.com/questions/4641994/injection-from-binary-strings-with-i-bits-to-i1-bits/4642385#4642385): take the longest prefix consisting of balanced pairs of `1`, `0` or unpaired `0`s, and change the rightmost unpaired `0` to `1`.
[Answer]
# [Python](https://www.python.org), 51 bytes
```
lambda n,k,s:sorted(set(range(n))-s)[-sum(s)%(n-k)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY8xbsMwDEV3nYJLARGRiwZZigA6ROe2gxxLjWGLEkR66Dk6dvHS3im3qeS0RSaS-I_8n5_f-V3OidbLUygpwii-SEozwxhzKgKnFPuRnIyJGBzDKfZqI6OT8y2kyMAEFvYPBg5KBfvytUjoHi-H2cV-cEBmMnzkyvtBsxddHL15TYgd43PHS9SMd5q6CV9_Vz-cbSCqkArUSNTs__fMhEcFYoPeTleQERXkMlJtjbTeypJnr_9cd1oMNsgx10dh9rRFyYjWTrt9Fe7dMNRZ3RCuiu3F5oPXaOt6rT8)
This is based on [hyper-neutrino's answer](https://codegolf.stackexchange.com/a/212242/18957) to the 'three other numbers' challenge. Edit: I now believe I have proved its correctness.
Here's a proof by contradiction:
Assume that \$f\$ is not injective. Then there must exist \$s,x,y\$ where \$|s|=k-1\$, \$f(s∪\{x\})=y\$ and \$f(s∪\{y\})=x\$. Take \$x<y\$ without loss
of generality, then
$$\sum s+y\equiv-p\_x\bmod n-k$$
$$\sum s+x\equiv-p\_y\bmod n-k$$
$$y-x\equiv p\_y-p\_x\bmod n-k$$
where \$p\_x\$ and \$p\_y\$ are the indices into the corresponding 'rest' arrays. But \$p\_y-p\_x\$ is just the number of integers in between \$x\$ and \$y\$ which are not in \$s\$. Let \$m\$ be the number of values in \$s\$ which are between \$x\$ and \$y\$. We have \$m=(y-x)-1-(p\_y-p\_x)\$, so \$m\equiv-1\bmod n-k\$. Therefore \$n-k-1\le m\le k-1\$, implying \$k\ge n/2\$. But this contradicts the initial assumption that \$k<n/2\$.
[Answer]
# Mathematica, 75 bytes
Modified from [@user1502040's answer](https://codegolf.stackexchange.com/a/258091/110802)
```
Module[{d=-Mod[Total[s],n-k]},Sort[Complement[Rangen-1,s]][[If[d==0,1,d]]]]
```
[Try it online!](https://tio.run/##VVDBasMwDL3nK8Suc6Cht2Ue69bLYIOxdCchire4aUgim8o9hXx7pmajMBsj8aT3nuTBpaMfXGq/3cxgoViVWadxXWbZAXlvoNMne4I7C/NbqM@9x7G2uaa4C8n1KGQ472gyVTglfA5D7P3gOeGH48ZzXhghQnw5YG3tyhSmJj2zU5dxKrNtQNH0k9vAKEJlBpAUUHc1V@8FeT@1qrgLVdKkeRS4f4AbvRquYFo641VsE6PnGsVAoqW0EfE64qvnJh0xElgLHdxCsVQvA/1RnIFIBkZRbnX@Ep/kdxtkghwKLXUTTUr7L@kWyaeWw9Dqz1wWUOf5Bw)
] |
[Question]
[
**Warning**: Wouldn't you rather answer a challenge about ponies?1
---
If you have read *The Hostile Hospital*, you would know that the Baudelaire orphans, from one of the scraps of paper recovered from the Quagmire's notebooks, they discover a name, "Ana Gram". Later on, they realize that means the word "anagram", not a name. And that information helps them in finding out who Count Olaf disguised Violet Baudelaire as (Laura V. Bleediotie). They have to search through the entire hospital list, but trace the correct person down. However, what if they lived in a time where YOU helped them? Not personally, but with a program?
So your task today is simple. Given a string `a` and an array, return a smaller array that contains all the possible anagrams of `a`.
## Rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins
* Make sure to lowercase everything in the array and the string
* Two strings that are the same are not anagrams after normalizing
* Make sure to watch out for initials! You should also remove them
* There may be multiple possible anagrams. Output them all
## Test cases:
```
String, Array
-> Array
"Violet", ["Veilo","Efh", "Telvio","veliot"]
-> ["Telvio","veliot"]
"Krotasmon", ["Krotas Mon","Krota","Monsakrot", "Trokasmont","KROTASMON"]
-> ["Monsakrot"]
"Laura V. Bleediotie", ["Violet Baudelaire", "Violet. Baudelaire", "VIOLeT BAUDELAIRE", "BUADELIAR VIOLETM", "Laura V. Bleediotie"]
-> ["Violet Baudelaire", "Violet. Baudelaire", "VIOLeT BAUDELAIRE"]
```
1: Inspired by the "all rights reserved" page of LS: The Unauthorized Autobiography
[Answer]
# [Python](https://www.python.org), 106 bytes
*-12 by mousetail, Kevin Cruijssen*
*-5 by Jitse*
```
lambda w,l,S=sorted:[x for x in l if S(g(x))==S(g(w))!=g(w)!=g(x)]
g=lambda s:s.lower().translate(['']*96)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZDBToQwEIbjlUfwNHJZapCj0U04QORABEmA3QtyqKHs1u3STSkLPosXEqPvpE8jpRsPGy-dfn_n_2fS96_Dm9zyZvyo3efPTtY3d9-vDO9fKgy9zezMbbmQpFoWA9RcwAC0AQa0hszaWANCrqsuPUJXrirqHFBpbNxTSLtsHcZ7IizkSIGblmFJrGKxKK_vb5Ge-HNxeRC0kVZtmRHuBIa1Az4jpKJcUmLaUJhryhmR4OOuIgxTodST6JyrYRKRHHxv9RBEXpgGSvRX3kShl4J6DvJYif8NKxEyjL919AS9AaGMm7YZ1FvlzQk7UsVHwibnme9RcInbPW9mqyaIFWqY6kQt3k0wpwm-m_ul6kiT3Mvi5EmF6i8aR11_AQ)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
šl€áD€{ćQsćÊ*Ï
```
Inputs in the order `String, Array`.
[Try it online](https://tio.run/##yy9OTMpM/f//6MKcR01rDi90AZLVR9oDi4@0H@7SOtz//793UX5JYnFufh5XtBKYraSj5JufV5yYDeQA2SFF@dlgeRDHO8g/xDHY198PxAZrVACqVYoFAA) or [verify all test cases](https://tio.run/##bY5BisJAEEWvUvRSgleQDskimBiM0U1osMUaprG1oRMD4s6FgpuBuYF7bxG9iBfJVDeuBjdF/Vf/V5Wp5Uph3x5GDF7nX2CjwzKy/fOmX6d7d4uoHh@Xaf24dNdB99MHfVWxhTIaGxZQh0obFrD465tqibpVTraolWmYEAFUbGxNI@ut2bmAF@TIzK6WGxIuZs3GG5wYF3nJZ1k@cb1PAnnfq1K5txIWQwg14ppOKPRf@H8glPs1aqkswTcb/oNJnmIJIZ9HccqTIiYWzjmJhBfgpnGZEft0RwjxBw).
**Explanation:**
```
š # Prepend the first (implicit) input to the second (implicit) input-list
l # Convert everything in the list to lowercase
ۇ # Only keep the letters of each string in the list
D # Duplicate this list
€{ # Sort the characters of each string in the list
ć # Extract head; push the modified list and modified first input separated to
# the stack
Q # Check which modified strings in the list are equal to this modified input
s # Swap so the duplicated list is at the top again
ć # Extract its head as well
Ê # Check which partially-modified strings in the list are NOT equal to this
# partially-modified input
* # Combine the checks at the same positions (vectorized multiply that acts as a
# vectorized logical AND)
Ï # Only keep the strings from the second (implicit) input-list at the truthy
# positions
# (after which the filtered list is output implicitly as result)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒlfØa,Ṣ$
Ç⁼"Ç}</ðƇ
```
A dyadic Link that accepts the list of potentials on the left and the identity on the right and yields the filtered list.
**[Try it online!](https://tio.run/##y0rNyan8///opJy0wzMSdR7uXKTCdbj9UeMepcPttTb6hzcca/9/eLm2/qOmNUcnPdw54///aHXvovySRHUdBXXf/LzixGwgD8QJKcrPTizOzc8D87yD/EMcg339/UCc4MTcfAVvPQWgkjywJMiAYgWgdvXY/1AeUKM6AA "Jelly – Try It Online")**
### How?
```
ŒlfØa,Ṣ$ - Helper Link: list of characters, Name
Œl - lower case (Name)
Øa - "a-z"
f - (lowered Name) filter keep ("a-z")
$ - last two links as a monad - f(X=that):
Ṣ - sort (X)
, - (X) pair with (that)
Ç⁼"Ç}</ðƇ - Main Link: Potentials; Identity
Ƈ - keep Potentials, P, for which:
ð - dyadic chain - f(P, Identity):
Ç - call Helper with Name=P
Ç} - call Helper with Name=Identity
" - zip with:
⁼ - equal?
/ - reduce by:
< - less than?
i.e. alphas(lowered(P)) == alphas(lowered(Identity))
less than?
sorted(alphas(lowered(P))) == sorted(alphas(lowered(Identity)))
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes
```
≔Φ↧S№βιθWS«≔Φ↧ι№βκη¿‹⁼ηθ⬤⁺ηθ⁼№ηκ№θκ⟦ι
```
[Try it online!](https://tio.run/##dc7LCsIwEAXQdfMVWU6hfoGrIgpSa4vtTlzEEpvQmNg87EL89pjWByI4qzvc4TANI7pRRHifGsNbCSsuLNWwUQPVDTEU1vLibGU1ly3EcYIXykkLxwTzcevjORoYFxT/HOIbiv6R/JvpRoYFJuInDBtqDCx7R4QBNvIJToWAUrjP/mqfABuBt9ZPWhhchi8s7PkhuHfvM60sMWcl0ZRQrqQhXYio1qqbGouyXVGnVV5skZ9dxQM "Charcoal – Try It Online") Link is to verbose version of code. Takes the array as a list of newline-terminated strings. Explanation:
```
≔Φ↧S№βιθ
```
Lower case the target anagram and only keep letters.
```
WS«
```
Loop through the array.
```
≔Φ↧ι№βκη
```
Lower case the current element and only keep letters.
¿‹⁼ηθ⬤⁺ηθ⁼№ηκ№θκ
If the strings do not equal and both strings contain equal counts of all the letters in both strings:
```
⟦ι
```
Output the current element on its own line.
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~163~~ ~~155~~ ~~151~~ ~~134~~ ~~218~~ ~~193~~ ~~186~~ 169 bytes
-3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!
+84 bytes thanks to [c--](https://codegolf.stackexchange.com/users/112488/c)
-24 bytes thanks to [c--](https://codegolf.stackexchange.com/users/112488/c)
```
u[256];v[256];*w;q(*h,*j){bzero(h,512);for(w=h+128;*j;j++)*j>64&&h[*w++=32|*j]++;}f(**o,i){for(q(u,i);*o;o++)q(v,*o),bcmp(u,v,w-v<<2)*!bcmp(u,v,512)&&printf("%ls,",*o);}
```
[Try it online!](https://tio.run/##bVHBbuIwED2Tr3AjFTmOi2i6rap1WSmoHBBhkVjaC80hpc7GaYjBcYJUNt9OJw5UrbYnzzy/92b0ZnWxyqL87@FQLr3rm5BV7UN2bItJQknq7J/fuJI4odeXnsNiqfBukLiX3i0jKUtd1yHpr5sf3W6yJDvXHVx5/0gaui6rY0yIpMLZN5otLqFkRDIJki2uKJEOfV6tN/BR0d1FdXfnOeTsA2mmdbsbJXIdY/s8K6jdSFh9WEcix461tzqFVuVKWx0oO8AjSOSbUrNTJzdayLxY3oYA1UjzQhfLEA1aQWA/CplxbVO0R9BwkUmoA3sUJ@Zd8KwSLVTxTMiG2Uc1NdqJkjoq1jI/yk1vuFMYGb0qQwcTJV8Nr20n89nC/zOd/f7sFUSlitBjDw0zzl9gkOCnpcyGaBiVLzyLhOLGpEV7/8HjWcAXaOg/3I8CfzwfGXT44EM79ueo@R8tpgb9fuRxoz5UEBizrA6cDmEIEwk0QH12zFCEvTZpJOCYbZyfLvXzqUnlK9VprhLjD/B4m29pJ6unHIwapLbqwzs "C (clang) – Try It Online")
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 12 bytes (24 nibbles)
```
|@~`^+%;~$.|$\$a`($$_@;$
```
```
| # filter
@ # the second argment (=array of possible anagrams)
~ # returning elements that are falsy for:
;~$ # apply and save the following function to each element:
|$ # filter each element
\$a # to keep only alphabetic characters
. # and then map over each character
`($ # converting to lowercase
$_ # apply the saved function to the first argument
% # split each normalized element
# by the normalized first argment
+ # and flatten
# (this removes normalized identities)
`^ # and then get the element-wise xor
@;$ # with the normalized first argument
# (so anagrams give empty list,
# identities/non-anagrams give lists of all/different characters)
```
[](https://i.stack.imgur.com/LPdRA.png)
[See the other test cases here](https://i.stack.imgur.com/8WqNj.png)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 80 bytes
```
->s,a{g=->s{s.upcase.gsub(/[^A-Z]/,"").chars.sort}
a.select{s!=_1&&g[s]==g[_1]}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3A3TtinUSq9NtgXR1sV5pQXJicapeenFpkoZ-dJyjblSsvo6SkqZeckZiUbFecX5RSS1Xol5xak5qckl1saJtvKGaWnp0caytbXp0vGFsbS3U3I4CBbdoJZ_E0qJEhTA9Baec1NSUzPySzFQlHYVopbDM_JzUEgWnxNKU1JzEzCKQKFRQD13U098nNUTByTHUxdXH0TPIFSToFOoI5Hk6BimApF1DfEGC2CyLjYW4Z8ECCA0A)
[Answer]
# JavaScript (ES10\*), 105 bytes
*\* Not a strict requirement, but starting with ECMAScript 2019 (aka ES10), the .sort() method is guaranteed to be stable. This used to be left to the implementation.*
Expects `(string)(array)`.
```
s=>a=>a.filter(w=>(g=c=>(h=s=>[...s.toLowerCase().replace(/[^a-z]/g,'')].sort(c)+0)(w)==h(s))()&!g(_=>1))
```
[Try it online!](https://tio.run/##pY/BbsIwDIbvPEWXw4g1SLcHCFLZekCUIbHCpWJTVNySkRGUFJD28p3bHpgGt0lRpP@3/8/2pzopnzt9qIZ7u8G6kLWXI0VPFNpU6PhZjngpc/q3kkqZEMKLyib2jO5ZeeQgHB6MypGH2bsafq/DctDvw1p46yqew8Mj8DNIueUegMP9Xck/5OgJoA7DIGMpmpO2bMBOaLSt2LqX2723BoWxJS84W2kSFQOesRVq07TGxZYNgusoQK/XQmeEUDt3CzclV/kvu2@JrSLCJdBwnd21LaTYdDFPo7fZ/PUXvlspGKvjBo3SDptUZ4q/7mSeYBqMo@VLnESTRXy9UaKOTgUrShrEDR2isbv2P1PIHC8jUpNoETTlOJ015q1hdFj9Aw "JavaScript (Node.js) – Try It Online")
### Commented
For each test, the helper function `g` is called twice: once to check that the normalized strings are equal when the letters are sorted, and once to check that they're different when no sort is applied.
```
s => // s = reference string
a => // a[] = array of strings
a.filter(w => // for each string w in a[]:
( g = c => // g is a helper function taking a callback c
( h = s => // h is a helper function taking a string s
[... // split into an array of characters:
s.toLowerCase() // convert s to lower case
.replace( // remove ...
/[^a-z]/g, '' // ... all non-letter characters
) //
].sort(c) // sort the resulting array using the callback c
+ 0 // add a final 0 to coerce to a string
)(w) == h(s) // is the normalization of w equal to that of s?
)() // we first call g() with an undefined callback
& // so that the default lexicographical sort is used
!g(_ => 1) // we then call g() with a callback that leaves the
// arrays unchanged
) // end of filter()
```
] |
[Question]
[
Produce [Graham's Number](https://en.wikipedia.org/wiki/Graham%27s_number) in [Magic the Gathering](https://magic.wizards.com/en) using the fewest number of cards and without using any infinite combos.
**Rules:**
1. Producing Graham's number means do anything that requires Graham's number to represent the game state. For example, you could produce Graham's number 2/2 zombie tokens, have Graham's number life, or have a creature with Graham's number in power and/or toughness.
2. You must get to Graham's number exactly. If you overshoot it, you need to have [a](https://scryfall.com/card/rav/79/carrion-howler) [mechanism](https://scryfall.com/card/ema/218/ashnods-altar) to get back down.
3. You cannot use a combo that can be repeated indefinitely (commonly referred to as a "infinite combo"), as defined in CR 726. For example, you can't use [Basalt Monolith](https://scryfall.com/card/2xm/232/basalt-monolith) enchanted by [Power Artifact](https://scryfall.com/card/me4/57/power-artifact), or [Squirrel Nest](https://scryfall.com/card/mh1/182/squirrel-nest) in combination with [Earthcraft](https://scryfall.com/card/tmp/222/earthcraft) as either of these can be repeated an arbitrary number of times. You can use abilities repeatedly, such as the ability on [Staff of Domination](https://Staff%20of%20Domination) or [Voltaic Construct](https://scryfall.com/card/dst/156/voltaic-construct), as long as there is some in-game limit on the number of times it can be repeated (other than the the rules requirement that you not repeat an optional loop forever). The key text from CR 726 (describing interactions that this challenge disallows) is the following:
>
> 726.1b Occasionally the game gets into a state in which a set of actions could be repeated indefinitely (thus creating a “loop”). In that case, the shortcut rules can be used to determine how many times those actions are repeated without having to actually perform them, and how the loop is broken.
>
>
>
4. If the combination involves any cards that let players "choose a number", such as [Menacing Ogre](https://scryfall.com/card/hop/59/menacing-ogre), numbers greater than 256 cannot be chosen.
5. You must get to Graham's number in at most 256 turns. (Note that taking infinite extra turns is prohibited as that would be an infinite combo.)
6. You have 256 mana of any color available to you on each turn without it counting against your card limit. Mana beyond that requires you to add cards to do this.
7. You have a single opponent with 20 life. The opponent takes no actions, and does not lose from drawing from an empty deck (assume that they have a deck made of 300 basic lands). You cannot rely on the opponent making specific choices unless [you have an effect that lets you control their choices](https://scryfall.com/card/som/176/mindslaver).
8. You must start with a legacy legal deck. In particular, all cards used must be [legal in the Legacy format](https://magic.wizards.com/en/banned-restricted-list). Additionally, standard deck building rules are in effect; i.e. no more than four copies of any card can be used unless that card [specifies otherwise](https://scryfall.com/card/a25/105/relentless-rats).
9. All of your cards start in either your hand or library (your choice which for any given card). To get a card into another zone requires an ability that moves it there.
10. The solution that uses the fewest number of cards from it's deck and sideboard to complete this task wins. Using a card means that having that card in your deck or sideboard is necessary to completing the combo. Playing the card is the most common "use" of a card, but using a card also includes using it's activated or triggered abilities from a zone outside of the battlefield (such as [Decree of Savagery](https://scryfall.com/card/afc/156/decree-of-savagery) or [Bridge from Below](https://scryfall.com/card/uma/87/bridge-from-below)) If you use multiple copies of a card, each copy counts as a separate card. Cards that are in the deck merely to meet the 60 card minimum but otherwise are never used are not counted.
**Note:** Magic the Gathering is [known to be Turing Complete](https://arxiv.org/abs/1904.09828), so I assert that this is both possible and as much a coding challenge as those set in [Conway's Game of Life](https://codegolf.stackexchange.com/questions/11880/build-a-working-game-of-tetris-in-conways-game-of-life).
Inspired by: <https://boardgames.stackexchange.com/q/57658/9999>
For those who haven't played Magic the Gathering extensively, you don't need to know the [entire rule set](https://magic.wizards.com/en/rules) (which is quite long), as most of that deals with interactions between players, which isn't present for this challenge. The basic rules, supplemented by the comprehensive rules on spells and abilities (section 6) is probably most of what you need to know. The harder part is finding cards that are helpful (as Magic has over 20,000 cards that have been printed). This is the best card search I know about: <https://scryfall.com/advanced>. Here are some examples of helpful searches:
* <https://scryfall.com/search?q=oracle%3Atwice>
* <https://scryfall.com/search?q=o%3A%22plus+one%22>
* <https://scryfall.com/search?q=o%3A%22token+that%27s+a+copy%22>
[Answer]
# 6 cards, not yet legal
(The card [Saw in Half](https://scryfall.com/search?q=!%22Saw%20in%20Half%22) will become Legacy legal with the upcoming release of Unfinity.)
*This solution is based on [a solution by plopfill to a slightly different challenge](https://www.mtgsalvation.com/forums/magic-fundamentals/magic-general/827241-to-grahams-number-and-beyond-massive-finite-damage?comment=4) ([fixed in a later post](https://www.mtgsalvation.com/forums/magic-fundamentals/magic-general/827241-to-grahams-number-and-beyond-massive-finite-damage?comment=11)), which exceeds Graham's number in 9 cards in 1 turn without free mana: [Black Lotus](https://scryfall.com/search?q=!%22Black%20Lotus%22), [Show and Tell](https://scryfall.com/search?q=!%22Show%20and%20Tell%22), [Omniscience](https://scryfall.com/search?q=!%22Omniscience%22), [Doubling Season](https://scryfall.com/search?q=!%22Doubling%20Season%22), [Temur Ascendancy](https://scryfall.com/search?q=!%22Temur%20Ascendancy%22), [Astral Dragon](https://scryfall.com/search?q=!%22Astral%20Dragon%22), [Mystic Sanctuary](https://scryfall.com/search?q=!%22Mystic%20Sanctuary%22), [Saw in Half](https://scryfall.com/search?q=!%22Saw%20in%20Half%22), [Dromoka, the Eternal](https://scryfall.com/search?q=!%22Dromoka%2C%20the%20Eternal%22).*
**[Doubling Season](https://scryfall.com/search?q=!%22Doubling%20Season%22), [Temur Ascendancy](https://scryfall.com/search?q=!%22Temur%20Ascendancy%22), [Astral Dragon](https://scryfall.com/search?q=!%22Astral%20Dragon%22), [Mystic Sanctuary](https://scryfall.com/search?q=!%22Mystic%20Sanctuary%22), [Saw in Half](https://scryfall.com/search?q=!%22Saw%20in%20Half%22), [Dungeoneer's Pack](https://scryfall.com/search?q=!%22Dungeoneer%27s%20Pack%22)**
Start by playing [Mystic Sanctuary](https://scryfall.com/search?q=!%22Mystic%20Sanctuary%22) and casting [Doubling Season](https://scryfall.com/search?q=!%22Doubling%20Season%22) and [Temur Ascendancy](https://scryfall.com/search?q=!%22Temur%20Ascendancy%22).
Next, cast [Astral Dragon](https://scryfall.com/search?q=!%22Astral%20Dragon%22). When it enters the battlefield, it triggers Temur Ascendancy's ability and its own ability. Have Astral Dragon's ability resolve first and produce four copies of Doubling Season (because of Doubling Season).
In response to the "draw a card" ability still on the stack, cast [Saw in Half](https://scryfall.com/search?q=!%22Saw%20in%20Half%22), targeting Astral Dragon. The two tokens this produces are doubled five times to make 64 token copies of Astral Dragon.
The first 62 to resolve of the new Astral Dragons' triggered abilities should target Doubling Season. Each one increases the number of Doubling Seasons from \$n\$ to more than \$2^n\$, and the initial number is \$5 > 4 = 2\uparrow\uparrow2\$, so the number of Doubling Seasons after those 62 abilities resolve is more than \$2\uparrow\uparrow64\$ ([Knuth's up-arrow notation](https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation)).
The last two Astral Dragon abilities should target [Mystic Sanctuary](https://scryfall.com/search?q=!%22Mystic%20Sanctuary%22). The first of those produces more than \$2\uparrow\uparrow65\$ tapped copies of Mystic Sanctuary, and the second produces the same number of copies, but now untapped. Use one of their abilities to put Saw in Half on top of the library, and then the Temur Ascendancy ability draws it.
Cast [Dungeoneer's Pack](https://scryfall.com/search?q=!%22Dungeoneer%27s%20Pack%22), and then cast Saw in Half on an Astral Dragon again. Target Doubling Season with all but two of the copies' abilities, increasing the number of Doubling Seasons to more than \$2\uparrow\uparrow(2\uparrow\uparrow65)\$. Use the last two abilities to target Mystic Sanctuary and Dungeoneer's Pack for more than \$2\uparrow\uparrow(2\uparrow\uparrow65)\$ copies of each, and again put Saw in Half on top of the library.
Proceed to the second turn, untapping the Dungeoneer's Packs and redrawing Saw in Half in the draw step.
Cast Saw in Half on an Astral Dragon again (although this time, it doesn't make a big difference to the final result). Similarly to before, increase the number of Doubling Seasons to \$2\uparrow\uparrow(2\uparrow\uparrow(2\uparrow\uparrow65))\$ and put Saw in Half back onto the library with a copy of Mystic Sanctuary.
Now start activating the copies of [Dungeoneer's Pack](https://scryfall.com/search?q=!%22Dungeoneer%27s%20Pack%22). Each one draws a card, allowing another casting of Saw in Half, but the more important parts are the Treasure tokens and the initiative, which gives ventures into [Undercity](https://scryfall.com/card/tclb/20/the-initiative-undercity?back).
With every five ventures, take the path Secret Entrance → Forge → Arena → Archives → Throne of the Dead Three. The important one is Forge: Put two +1/+1 counters on target creature. Keep Saw in Half in hand and target an Astral Dragon with that, giving it more than \$2^{2\uparrow\uparrow(2\uparrow\uparrow(2\uparrow\uparrow(2\uparrow\uparrow65)))}\$
+1/+1 counters the first time.
With its power thereby increased, the copies produced by casting Saw in Half on it will also have high power, and therefore trigger [Temur Ascendancy](https://scryfall.com/search?q=!%22Temur%20Ascendancy%22) to draw cards, allowing for more castings of Saw in Half.
* One Astral Dragon with power ≥7 gives rise to many with power ≥4, which give card draws and recastings of Saw in Half, each of which gives a tetration; thus the whole thing gives a pentation.
* One Astral Dragon with power ≥13 gives rise to many with power ≥7, for many pentations, thus a hexation.
* One Astral Dragon with power ≥25 gives rise to many with power ≥13, for many hexations, thus a heptation.
* In general, an Astral Dragon with power \$\ge 2^{n}\times6+1\$ gives the \$n+5\$th hyperoperation.
(Also, whenever the black mana is running out, target a Treasure token with an Astral Dragon's ability to make more Treasure tokens, which are usable because [Temur Ascendancy](https://scryfall.com/search?q=!%22Temur%20Ascendancy%22) gives them haste.)
Forge is reached again with every five ventures, feeding the Doubling Season count into the hyperoperation index each time. The number produced at the end is more than \$2\rightarrow 3\rightarrow (2\uparrow\uparrow(2\uparrow\uparrow65)) \rightarrow2\$ ([Conway chained arrow notation](https://en.wikipedia.org/wiki/Conway_chained_arrow_notation)), which exceeds Graham's number.
Finally, there are several options for making exactly Graham's number \$G\$ (it's not entirely clear to me what counts):
* Tap \$G\$ copies of [Mystic Sanctuary](https://scryfall.com/search?q=!%22Mystic%20Sanctuary%22) for \$G\$ blue mana.
* Target a Treasure token with the last Astral Dragon ability to have more than \$G\$ Treasure tokens, then sacrifice all but \$G\$ of them.
* Attack with \$G/3\$ 3/3 copies of Doubling Season to deal \$G\$ damage to the opponent.
* Attack with \$G/3\$ 3/3 copies of Doubling Season and twenty 1/1 copies of Astral Dragon to deal \$G+20\$ damage to the opponent and make the opponent's life total \$-G\$.
] |
[Question]
[
[makina](https://github.com/GingerIndustries/makina) is a cell-based esolang composed of automata which move around a grid. These automata follow paths of instructions that direct their movement. Your task is to, given a makina program *using only the below instructions* (so a subset of normal makina) as input, output two distinct values depending on whether or not it is a loop. (If program flow comes to an arrow character that it has already visited then the program is a loop.)
## Instructions
* `^>v<` These instructions (arrows) set the direction of the automaton to the direction they point in.
* `I` This instruction halts automata going up or down, but does nothing to ones going left or right.
* `H` This instruction halts automata going left or right, but does nothing to ones going up or down.
* `O` This instruction does nothing to the automaton, acting like a sort of 4-way intersection.
All other characters (including spaces) halt the automaton, as does exiting the bounds of the program. The automaton starts in the top-left corner going right. You may assume programs are padded by spaces to be rectangular. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins!
## Testcases
## Truthy
```
>>>v
v<<<
```
```
OOOv
H<<<
v
```
```
>>>v
v<I<
H>^
>^
```
```
>>>>v
v <<<
```
## Falsey
```
>>>v
^<<<
```
```
>v
^O<
>^
```
[Answer]
# [Python](https://www.python.org), ~~182~~ 187 bytes
```
def f(s):
i=j=h=0;d=1;v={0}
while 1:
if(t:=(i,j,h,d))in v:return 0
try:c=s[i][j];0/(c-32)/(c&16 or(c&3^h))
except:return 1
if c&16:h=c>>6;d=(c>>4&c&2)-1
v|={t};i+=h*d;j+=d-h*d
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NVFLboMwFFzHp7C8SOwmpJBUUQWYdbLiAPlIDdjiocggMJSI5iTdZNNeogfoGXqb2iRZvXkz45HH_vwuzzor1PX61WjpvP79pEJiSWvmoxHwnGfcDVLuBS3v3QsavWdwEtgz4ggk1T6nMMtn2SxlDBRu_UroplLYNbquzn7C6y3st_k-cJ9p4iwXzIyxt8JFZebykDFmnKJLRKkfZ70hG1ubn_EkilbmAtTMl3EyXjDH6u0H7_UlgCnPntIgn_LUMeBe4Rf4kRCCoihqURuGIUJxHLdobWGLbvxh4C2IQxQd0MO9CdHarHfGUtg6bR6SRYU7bHrCvNYVlPRIdoqweV2eQA-LXc3blBUoTSXZqLLRPt6pvpunIilSQSdvdQIwYZedihs9yL2k3S3jBErUlFmRMHSr8_iZfw)
Edit: the previous version did return *falsey* if the automaton visited twice a cell with `H` or `I`. Thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh) for the useful comments on the challenge post.
Brief explanation:
* `i` and `j` are the coordinates of the current cell (`i` is the row index, `j` is the column index);
* `v` is the set of the previously visited cells; if the current cell was already in `v`, it means that the automaton does not halt (hence `return 0`);
* the try block assigns to `c` the symbol in the current cell; it also checks if the coordinates refer to a cell present in the input, if the cell contains a space, or if the automaton halts encountering a `H` or a `I`;
* `h` stores the direction of the movement; if `h` is `0` the automaton is moving horizontally, if `h` is `1` it is moving vertically;
* `d` stores the magnitude of the movement, can be `-1` or `+1`
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~274~~ 233 bytes
```
->b{b=b.lines.map &:chars;x=y=0;d=[1,0];i={?>=>d,?<=>[-1,0],?^=>[0,-1],?v=>[0,1],?H=>0,?I=>1};loop{a=b[y][x] rescue break;a=~/[><^v]/? (d=i[a];b[y][x]=0): a=~/[IH]/? (break if d[i[a]]!=0): a==?O? 0: a==0? v: break;x,y=x+d[0],y+d[1]}}
```
[Try it online!](https://tio.run/##XZHBboMwEETv@YotkdpEJQSuwNrX5NQPcEhlwFGsEoOMoSBEf50Coomak0eet6PVrK7idjBC36TiRpSAYBFC6pOqwzC0VmkuSmU@78DDP0/@cKlUYmSucEfiLsbYyaQSpXPjBbz6yZXrMmiwRTdIkXm2GwUSO0qQpDYNkbDd9GfT8yhde@eNsp7lpA5IXJsekXh9kOV50XGMWRuxJgItyqQSEGvBvwKOP3tGwnMd7SlsUpSMR8FCorv1YQaOh9meR0BeIGUTF70sBNIPCu6sXAq1v2Q3dovNe8rGJdvx8aK@X62KypRgPTrzYd399eAkPMs2D2/rSFUWIjH9SVmrQktlwJpLfTNwx3ywltTnpOf@/@XBGo4GvmWWgdA615ArMFdZwnSEYfgF "Ruby – Try It Online") I've only put a couple test cases in the TIO link because the test cases in the question aren't all sorted correctly. (Some marked falsy are actually truthy.)
Takes a string. Errors if the input doesn't terminate, runs without error (returns `nil`) if it does. I'm proud of the golfed case statement and use of inline `rescue`, an arguably useless feature that's only really applicable in an edge case like this. Still trying to figure out how to golf `i` (a direction lookup hash) as well as optimize control flow in the function itself.
Ungolfed code:
```
def simulate_makina program
program = program.chomp.split(?\n).map(&:chars)
x, y = 0, 0
dir = [1, 0]
dirs = {?> => [1, 0], ?< => [-1, 0], ?^ => [0, -1], ?v => [0, 1], ?H => 0, ?I =>1}
loop do
a = program[y][x] rescue break
case a
when /[><^v]/
dir = dirs[a]
program[y][x] = 0
when /[IH]/
break if dir[dirs[a]] != 0
when ?O
0 # nop
when 0
v # raises a NameError
else
break
end
x, y = x + dir[0], y + dir[1]
end
end
```
# Ruby, ~~252~~ 211 bytes
```
->b{x=y=0;d=[1,0];i={?>=>d,?<=>[-1,0],?^=>[0,-1],?v=>[0,1],?H=>0,?I=>1};loop{a=b[y][x] rescue break;a=~/[><^v]/? (d=i[a];b[y][x]=0): a=~/[IH]/? (break if d[i[a]]!=0): a==?O? 0: a==0? v: break;x,y=x+d[0],y+d[1]}}
```
Alternative answer that takes, instead of a string, a 2d array of characters. Again, errors if the input doesn't terminate and returns if it does. [Try it online!](https://tio.run/##dZHBboMwEETvfMWWSG2iEgJXYO1rcuoHOKRywFGsEoOMoSBEf50Coo0aqSePvG9G67Guzu1ghL5JxY0oAcEmhNRHVUdRZLuZVKJ0b7xYPwfJletyY6W5KJV5//XcLad/LMOlUomRucItOXcNtuiFKTLf8eJQYkcJktShERK2ne4cehql52z9UdaznNQeiefQAxK/D7M8LzqOZ9bGrIlBizKpBJy14B8hx68dI9GpjncU1ilKxuNwIdHbBDADh/08ni0gL5CyiYufFgLpGwVvVh6FOliyG6fF5jVl45LtePhx31tWUZkS7HuHAay6nxe7Cc@y9X22caUqC5GY/qhsq9BSGbDnRl8M/GIB2EvqY9Jj@X/yYAUHA58yy0BonWvIFZirLGH6kmH4Bg "Ruby – Try It Online")
[Answer]
# JavaScript, 118 bytes
```
s=>[x=-1,y=0,d=4,...s+s].every(_=>d=1+'^<v>'.indexOf(c=s.split`
`[y+=(d-2)%2]?.[x+=(d-3)%2])||d*(c=='O'|c=='IH'[d%2]))
```
This answer disagree with the last 2 testcases.
```
f=
s=>[x=-1,y=0,d=4,...s+s].every(_=>d=1+'^<v>'.indexOf(c=s.split`
`[y+=(d-2)%2]?.[x+=(d-3)%2])||d*(c=='O'|c=='IH'[d%2]))
t= `
>>>v
v<<<
OOOv
H<<<
v
>>>v
^<<<
>v
^O<
>^
>>>v
v<I<
H>^
>^
>>>>v
v <<<
vv<v<X
>OOOOv
vOOOO<
>OOOOv
XO^<^<
`.trim().split(/\n\n+/);
t.forEach(s => {
console.log(f(s));
});
```
Basic idea: A makina program with \$n\$ bytes source code will always terminate in at most \$2n\$ steps or it will never terminate.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 248 bytes
```
def h(i):
p=P=d=0;D=1;v=[]
while 1:
try:p+=d;P+=D;r=i[p][P]
except:return 1
if[p,P]in v:return 0
if'H'==r and D or'I'==r and d or'<>^vHIO'.find(r)<0:return 1
L=r in'<>^v';v+=[[p,P]]*L
if L:d=r>']'and' v'.find(r);D=r<'?'and' >'.find(r)
```
[Try it online!](https://tio.run/##pZBRa8IwFIXf8yvuW1q1YtnLaJMOnY4KhZbpNkaWwljbNSCxxC6bv94lLYoKe9pDIPeck@9y0uzbeitvbht1OBRlBbUj3ABBQzNa0Ek4p36oKeMIvmuxKcE3HrRqHzRDWoTZkM5DRQVrOMtMBsqfj7JpA1W2X0qCbxRRsWaUcSFBH@VJJ@MYU6rgXRYwh63Cy9NY2JFEuY6XKR5XQhaOcsnknJqYqJBdCId6SFm3hA@SDg1JUFAVYY4NDoM@QUwdRfBdL0cn@VBtFexaJeSnoQJDGGMURZFGmhBipxHqtDRNNYqtpgHgzLBZAG3v3P6eQbVO7TA22AhZcrAL7M3i@0XMDzyfj3fNRrQOfpPY5a6LUP8Se563fnxax69wP10tVjCdpc8LI2L3LPEwTVbHwGyRpC99AP3ZJr9sE2lAeUpQlF9W6XovCYqtYc6Va224IpH/Nj/8Ag "Python 3.8 (pre-release) – Try It Online")
Wrong output for fourth falsy case but it seems like the output should in fact be truthy (the automaton hits a space and halts). I am waiting for clarification from the OP on this. Works on all other testcases.
Nothing too complex; just moves around as dictated by the input. The only part of note here is how to check whether to halt at an `H` or `I` location. For `H`, this is done by checking that `D`, which is the horizontal movement variable, is truthy, because it is truthy if it is not zero, and if it is not zero then the automaton is moving from the left or right. If it is zero then it is moving from the top or bottom. Similar for `I` but we check `d` (vertical movement) instead.
+6 bytes to fix bug pointed out by @tsh in comments, which means that the output for the third "falsey" case is now 1. However, it would appear that this is the correct answer.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 56 bytes
```
WS⊞υιP⪫υ¶W⊕⌕⪪HIO>^<v¹KK¿‹ι⁴¿⁼⊖ι﹪φ²⎚M✳⊗φ«≔ιφ✳⊗φψ»≔KKθ⎚⁼θψ
```
[Try it online!](https://tio.run/##bY9BS8QwEIXPm18ReppAPKx4aymIddmKyxb2Kgu1nW4HY9I2SUXE317T3aqXhVzy3nxv3lRtOVSmVNP00ZJCDrnuvDu4gfQJhOCFty14yUnEbOeVoy44Dp4M6VmOXnQkgvUHVwO@o3ZYw4Z0DYdOkYNom@/TYzJGkq@F5AXiW8gO6dRweEZrgSS/W/6PvS@VhQz/oyhAO1N7ZaCR/HYmHxSWA4iYo7IYzBEhowErR0ZDZvyrClwj5m7niS@2ureWTnpe1QR1VZwPuQpJ/hkmvtlCXPpK3gfxdy@74EvZfiZEPE1pno5sTPYJ26ZHFt50M6of "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings and outputs `-` if the program does not halt, nothing if it halts. Explanation:
```
WS⊞υιP⪫υ¶
```
Input the instructions and print them to the canvas without moving the cursor.
```
W⊕⌕⪪HIO>^<v¹KK
```
While the character under the cursor is a valid instruction:
```
¿‹ι⁴
```
If this was an intersection-type character, then...
```
¿⁼⊖ι﹪φ²⎚
```
... if this intersection should halt the program then clear the canvas, causing the loop to exit, ...
```
M✳⊗φ
```
... otherwise move on through the intersection.
```
«≔ιφ✳⊗φψ»
```
Otherwise, update the direction, replace the current character with a null marker and move in the new direction.
```
≔KKθ⎚⁼θψ
```
Output whether the cursor landed on a null marker, indicating an infinite loop.
] |
[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/236971/edit).
Closed 2 years ago.
[Improve this question](/posts/236971/edit)
Given an integer `n` as input, write a function that dynamically allocates `n` bytes and returns their address.
## Rules
* The allocator must be able to **dynamically** allocate memory at **runtime**.
* It doesn't matter where the memory is allocated to or in what form, as long as it's allocated in a valid location which can be read from and written to.
* Allocated memory locations must be unique and not override or cross already-allocated locations.
* You don't have to write the code in a way such that the memory can be deallocated later.
* It might be obvious, but you are not allowed to use a programming language's or standard library's built in allocator. For example, making a function return the result of `malloc` or `new` is not a valid solution.
* You don't need to worry about out-of-memory errors. Assume big amounts of memory are never allocated.
* Efficiency and speed are not a factor. The only requirement for the challenge is the shortest code, in bytes.
* [Standard loopholes](https://meta.codegolf.stackexchange.com/q/1061/42963) are not allowed.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 51 bytes
```
#include<sys/mman.h>
#define m(n)mmap(0,n,7,33,0,0)
```
[Try it online!](https://tio.run/##XY1BCoMwEEX3nmIaEZKStqEuWtD2JN1IEjVgxpDEhZSe3QYRoZ3le///kadOymXJDcphUroOc7hY2@C5f2a50q1BDZYiS8xRwZHfeFlywQXbO1Br73FcGzsK0Rvs/pkya8xgBNsYpAzeGaSTfePh6OCRft1ZtTLl0kJs6ZUDKdwLCQe3qTQu3UxdMr0ehvFANrFVSBF@8l7HySOIKvssXw "C (gcc) – Try It Online")
-4 bytes thanks to ceilingcat by switching to a function-like macro.
---
`mmap` is a system call which maps a file into virtual address space. On Linux, it can also be used in `MAP_ANONYMOUS` mode, where it doesn't map any file at all, but just "creates" memory out of thin air. The POSIX-portable method would be to open and map the device file `/dev/zero`, which is full of infinite null bytes.
The first argument is a "hint" to the kernel on where to allocate it close to, which can help improve caching. We can just leave it as `NULL` (or `0`, which is golfier) for a basic allocator, though.
The second argument is the size, `n`.
The third argument is the the memory `prot`ection flags of the chunk. `7` is `PROT_READ | PROT_WRITE | PROT_EXEC` to allow all operations.
The fourth argument, `flags`, sets allocation options. `33` is `MAP_ANONYMOUS | MAP_PRIVATE`, which allocates process-private memory without a backing file descriptor. This is practically equivalent to the portable POSIX method which involves opening and mapping `/dev/zero`, but it's much shorter.
The final parameters are the file descriptor (whose value is ignored, because we're using `MAP_ANONYMOUS`), and `offset`, which should be `0` because there's no file.
You can read more about `mmap` in [its manual page](https://man.archlinux.org/man/mmap.2).
---
# [C (gcc)](https://gcc.gnu.org/) (invalid, but still interesting!), 35 bytes
```
m(int(*f)(),int n){char p[n];f(p);}
```
[Try it online!](https://tio.run/##XY7RCoJAEEXf/YppQ5gNi@gpMPqR8sFGzaV1XNY1CPHbt020oHka5t5z79D2TuR9g4odbiqJMgkbsByozi2YC2dphUamo18rJt0XJZxKa7nd1efod@qcVXz/vxVqsj1bVQDlWt9yeuAcnEkYIghTmIC6Cg8JiNhcWSQQ@iYppJJ5oQlKXWrdrsQszIiIu69/jD6PN7liXJIbXEoTOM6kLV1vGfYB8G8 "C (gcc) – Try It Online")
Using [variable-length arrays](https://en.wikipedia.org/wiki/Variable-length_array), it's possible to get dynamic memory allocation on the stack. The memory lives only as long as its scope is running, so it has to be returned using a callback function and only used within that callback (which is [not an allowed I/O method](https://codegolf.meta.stackexchange.com/a/11324), so this answer is invalid). I'm not sure if this would be valid even then, because it might count as using a built in allocator.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~49~~ \$\cdots\$ ~~36~~ 34 bytes
```
b[1<<24];m;r;f(n){r=b+m;m+=n;r=r;}
```
[Try it online!](https://tio.run/##pY/BCoMwDIbve4ogCO2qYJ232CdxHrRSV5iddoMdxFdf1yrC2GmwXPJD8n9/ItNeSufaipdlXtQ4oEVFDJ2taNmAAxMGrbC4OG0eMDTaEArzAXzJS2PhOIIAEuSRKsIziutM3SyQ4NB@nKFvJXDfGdO7PdRY6dov8BMw0Jtz@WBP/7CnjV3k3@xfb7N@R5ForOIugOIu8cxdn02UgE7WD1YR4uges7iXVNemv7v0@QY "C (gcc) – Try It Online")
*Saved 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
Of course you don't say how much memory is needed, this will work with \$16\$+ million bytes.
### Commented
```
b[1<<24]; // our memory buffer as an array of double words
m; // declare global variable m to track where free
// memory is
r; // declare r for golfing returning without return
// and saving current position before updating m
f(n){ // a function returning an int which will work
// as a void* pointer and taking an int
// parameter n, this will return 4x the number
// of bytes asked for
r=b+m // store current position in buffer
m+=n; // update where next request for memory will be
r=r; // return a pointer for n bytes of memory (actually
// n*4 bytes but that'll do for n bytes)
}
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/ "GCC, the GNU Compiler Collection") on Linux, 45 bytes
```
#include<unistd.h>
int*a(n){return sbrk(n);}
```
[Try it online!](https://tio.run/##XY9LDsIgEED3nGLENKFNNcYt1bV3UBcItBIpJUBjtOnZKzX1O7uZeW8@fFFxPgxzZbhuhSxao3wQy/MWKRMyRkzaORlaZ8Cf3CWmtH/DUPjglKlG@rsmVDOWxglQM2VICh2CGPzMHNTSe1bJ/RE2gHdS6waujdNihin6UJmNbUa8usumfDkpfQLCxq2hJOsccGIPBudg00mOF3F7Izb/cyYFJ/6Xn55bUdQPDw "C (gcc) – Try It Online")
The [`sbrk` system call](https://linux.die.net/man/2/sbrk "sbrk(2) - Linux man page") on Linux moves the program break by the specified number of bytes, and returns a pointer to the old program break. This has the effect of allocating that many bytes of uninitialized memory and returning a pointer.
[Answer]
# [ZX Spectrum](https://worldofspectrum.org/) (48K model) [BASIC](https://worldofspectrum.org/ZXBasicManual/), 19 bytes
```
LET r=VAL "65367"-n: CLEAR r-SGN PI
```
65367 is the default RAMTOP for the 48K model (assuming the RAM is not faulty). `CLEAR` sets the new RAMTOP lower by the requested amount, minus one, so that you can use the reserved RAM starting from the value returned in `r` by whatever combination of `PEEK` and `POKE` you desire. Note that while the BASIC has subroutines, they cannot return values, so the return value is assigned to the variable `r`.
Using `VAL "65367"` instead of plain number golfed 2 bytes (the number would be stored in additional 5 bytes otherwise); `SGN PI` instead of `1` similarly golfed 4 bytes; keywords take 1 byte each.
The standard allocator (that we cannot use) is of course `DIM`.
[Answer]
# [Python](https://www.python.org/), 28 bytes
```
def m(n):return bytearray(n)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 44 bytes
`char a[~0U],*p=a;char*m(n){return p+=n,p-n;}`
] |
[Question]
[
*Part of the [lean](/questions/tagged/lean "show questions tagged 'lean'") Language of the Month*
A pong\* is a set \$P\$ with an operation \$+\$, that satisfies the following properties:
\$
\forall a, b \in P : (b + b) + a = a\\
\forall a, b \in P : a + (b + b) = a\\
\forall a, b, c \in P: a + (b + c) = (a + b) + c \\
\$
This makes a pong\*, just a group where every element is it's own inverse.
Now most operations we know of are not pongs. Addition is clearly not a pong. However you should be familiar with some. Exclusive or on booleans is a pong, since \$\mathrm{True}\oplus\mathrm{True} = \mathrm{False}\$ and \$\mathrm{False}\oplus\mathrm{False} = \mathrm{False}\$, and by extension bitwise xor on integers is also a pong.
A beginner level proof in Abstract Algebra is to show that every pong is an Abelian group. That is given the axioms prove
\$
\forall a,b : a + b = b + a
\$
So as I thought it would be fun to tackle this problem as a beginner lean problem. Here's a pong class:
```
universe u
class pong (A : Type u) extends has_add A :=
( add_assoc : ∀ a b c : A, (a + b) + c = a + (b + c) )
( left_id : ∀ a b : A, (b + b) + a = a )
( right_id : ∀ a b : A, a + (b + b) = a )
open pong
```
Your task is to prove the following theorem:
```
theorem add_comm (A : Type u) [pong A] : ∀ a b : A, a + b = b + a
```
As is standard now you may rename the function and golf declaration as long as the underlying type remains the same.
You may not use any of the [theorem proving sidesteps](https://codegolf.meta.stackexchange.com/a/23938).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") answers will be scored in bytes with fewer bytes being the goal.
I ask that if you are experienced in Lean you give a little time for beginners to have a go at this. Feel free to post your score below as a motivator. You can also post a hash of your program as proof.
\* A term I just made up, because saying "Group where every element is its own inverse" gets tiring real quick.
[Answer]
# Lean, ~~115~~ ~~103~~ 100 bytes
```
def P:=@add_assoc
def V(A)[pong A](a b:A):a+b=_:=by rw[<-right_id$a+b,<-P,P a,<-P b,left_id,left_id]
```
[Try it on Lean Web Editor!](https://leanprover-community.github.io/lean-web-editor/#code=universe%20u%0A%0Aclass%20pong%20%28A%20%3A%20Type%20u%29%20extends%20has_add%20A%20%3A%3D%0A%20%20%28%20add_assoc%20%3A%20%E2%88%80%20a%20b%20c%20%3A%20A%2C%20%28a%20%2B%20b%29%20%2B%20c%20%3D%20a%20%2B%20%28b%20%2B%20c%29%20%29%0A%20%20%28%20left_id%20%3A%20%E2%88%80%20a%20b%20%3A%20A%2C%20%28b%20%2B%20b%29%20%2B%20a%20%3D%20a%20%29%0A%20%20%28%20right_id%20%3A%20%E2%88%80%20a%20b%20%3A%20A%2C%20a%20%2B%20%28b%20%2B%20b%29%20%3D%20a%20%29%0A%0Aopen%20pong%0A%0Atheorem%20add_comm%20%28A%20%3A%20Type%20u%29%20%5Bpong%20A%5D%20%3A%20%E2%88%80%20a%20b%20%3A%20A%2C%20a%20%2B%20b%20%3D%20b%20%2B%20a%20%3A%3D%20%CE%BB%20a%20b%2C%0Abegin%0A%20%20rw%3C-left_id%28a%2Bb%29%28b%2Ba%29%2Crw%20add_assoc%2Crw%3C-add_assoc%20_%20a%2Crw%20add_assoc%20b%20a%20a%2Crw%20right_id%2Crw%20right_id%0Aend%0A%0Adef%20X%28A%3AType%20u%29%5Bpong%20A%5D%28a%20b%3AA%29%3Aa%2Bb%3Db%2Ba%3A%3Dby%20rw%3C-left_id%28a%2Bb%29%28b%2Ba%29%3Brw%20add_assoc%3Brw%3C-add_assoc%20_%20a%3Brw%20add_assoc%20b%20a%20a%3Brw%20right_id%3Brw%20right_id%20--%20138%0Adef%20Y%28A%3AType%20u%29%5Bpong%20A%5D%28a%20b%3AA%29%3Aa%2Bb%3Db%2Ba%3A%3Dby%20rw%5B%3C-left_id%28a%2Bb%29%28b%2Ba%29%2Cadd_assoc%2C%3C-add_assoc%20_%20a%2Cadd_assoc%20b%20a%20a%2Cright_id%2Cright_id%5D%20--%20126%0Adef%20Z%28A%3AType%20u%29%5Bpong%20A%5D%28a%20b%3AA%29%3Aa%2Bb%3Db%2Ba%3A%3Dlet%20Q%3A%3D%40add_assoc%2CR%3A%3D%40right_id%20in%20by%20rw%5B%3C-left_id%28a%2Bb%29%28b%2Ba%29%2CQ%2C%3C-Q%20_%20a%2CQ%20b%20a%20a%2CR%2CR%5D%20--%20122%0Adef%20Q%3A%3D%40add_assoc%0Adef%20U%28A%3AType%20u%29%5Bpong%20A%5D%28a%20b%3AA%29%3Aa%2Bb%3Db%2Ba%3A%3Dby%20rw%5B%3C-left_id%28a%2Bb%29%28b%2Ba%29%2CQ%2C%3C-Q%20_%20a%2CQ%20b%20a%20a%2Cright_id%2Cright_id%5D%20--%20120%0A%0Adef%20P%3A%3D%40add_assoc%0Adef%20V%28A%29%5Bpong%20A%5D%28a%20b%3AA%29%3Aa%2Bb%3D_%3A%3Dby%20rw%5B%3C-right_id%24a%2Bb%2C%3C-P%2CP%20a%2C%3C-P%20b%2Cleft_id%2Cleft_id%5D%20--%20100%0A%0A--%20sanity%20check%20for%20V%0Aexample%20%28A%20%3A%20Type*%29%20%5Bpong%20A%5D%20%28a%20b%20%3A%20A%29%20%3A%20a%20%2B%20b%20%3D%20b%20%2B%20a%20%3A%3D%20V%20A%20a%20b%0A%23check%20V%0A%0A%2F-%0Acalc%20a%2Bb%3D%28%28b%2Ba%29%2B%28b%2Ba%29%29%2B%28a%2Bb%29%3Asymm%24left_id%20_%20_%0A...%3D%28b%2Ba%29%2B%28%28b%2Ba%29%2B%28a%2Bb%29%29%3Aadd_assoc%20_%20_%20_%0A...%3D%28b%2Ba%29%2B%28%28%28b%2Ba%29%2Ba%29%2Bb%29%3Aby%20rw%3C-add_assoc%20_%20a%0A...%3D%28b%2Ba%29%2B%28%28b%2B%28a%2Ba%29%29%2Bb%29%3Aby%20rw%20add_assoc%20b%20a%20a%0A...%3D%28b%2Ba%29%2B%28b%2Bb%29%3Aby%20rw%20right_id%0A...%3Db%2Ba%3Aby%20rw%20right_id%0A-%2F)
-14 bytes thanks to Kyle Miller.
### Proof outline
```
a + b
= (a + b) + ((b + a) + (b + a)) -- by right_id
= ((a + b) + (b + a)) + (b + a) -- by add_assoc
= (a + (b + (b + a))) + (b + a) -- by add_assoc
= (a + ((b + b) + a)) + (b + a) -- by add_assoc
= (a + a) + (b + a) -- by left_id
= b + a -- by left_id
```
[Answer]
# Lean, ~~141 140~~ 121 bytes
* Saved one byte thanks to Wheat Witch/Wheat Wizard
* Saved 19 bytes thanks to Kyle Miller!
```
def s:=@add_assoc
def V(A)[pong A](a b:A):a+b=b+a:=by rw<-left_id b(a+b);repeat{rw<-s};rw s;simp[right_id,s(a+b),left_id]
```
[Try it online](https://leanprover-community.github.io/lean-web-editor/#code=universe%20u%0A%0Aclass%20pong%20%28A%20%3A%20Type%20u%29%20extends%20has_add%20A%20%3A%3D%0A%20%20%28%20add_assoc%20%3A%20%E2%88%80%20a%20b%20c%20%3A%20A%2C%20%28a%20%2B%20b%29%20%2B%20c%20%3D%20a%20%2B%20%28b%20%2B%20c%29%20%29%0A%20%20%28%20left_id%20%3A%20%E2%88%80%20a%20b%20%3A%20A%2C%20%28b%20%2B%20b%29%20%2B%20a%20%3D%20a%20%29%0A%20%20%28%20right_id%20%3A%20%E2%88%80%20a%20b%20%3A%20A%2C%20a%20%2B%20%28b%20%2B%20b%29%20%3D%20a%20%29%0A%0Aopen%20pong%0A%0Adef%20s%3A%3D%40add_assoc%0Adef%20V%28A%29%5Bpong%20A%5D%28a%20b%3AA%29%3Aa%2Bb%3Db%2Ba%3A%3Dby%20rw%3C-left_id%20b%28a%2Bb%29%3Brepeat%7Brw%3C-s%7D%3Brw%20s%3Bsimp%5Bright_id%2Cs%28a%2Bb%29%2Cleft_id%5D)
[Bubbler's](https://codegolf.stackexchange.com/a/236297) is much better, but I'm just throwing my hat into the ring anyway.
] |
[Question]
[
Daylight saving time (DST), is the practice of advancing clocks (typically by one hour) during warmer months so that darkness falls at a later clock time. The typical implementation of DST is to set clocks forward by one hour in the spring ("spring forward") and set clocks back by one hour in autumn ("fall back") to return to standard time. [[from Wikipedia](https://en.wikipedia.org/wiki/Daylight_saving_time)]
Write a program (full or function), takes no input from user, tells user when next Daylight Saving Time clock shift will happen in the following year for users' timezone (as configured on users' system / environment). Output should be the time when DST starts / ends in second precision, or output some other non-ambiguous text / value to tell user there will be no DST start / end happened in the following year.
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest codes in bytes win as usual;
* Your program should running on a platform which support at least 12 different timezone, and at least 2 of them have different DST shifts in the following year. So a program simply tells user "there is no DST" on a platform only support UTC would be disqualified.
* You may output in any reasonable format including (but not limited to) any one of following formats. Please also specify your output format in your post.
+ A Unix timestamp in second / millisecond;
+ Any human readable string in UTC or users timezone;
+ A built-in date time type value as return value of function;
* If your program output time in users' timezone, you should clarify whether the time outputted had DST counted. This can be done by including UTC offset / timezone name in your output, or specify it in your post (only when all outputs both use / not use DST.
* For timezone uses DST whole year, you program should tell user no DST start / end will happen;
* If your program running in some sandbox / emulator / virtual machine / docker environment which provides its own timezone config, you may use the timezone info configured in the runtime environment instead of user's operating system. But again, the environment should support multiple timezone with different DST to make your answer valid.
To keep this challenge simple, you may assume:
* The timezone will not change its offset to UTC due to other reasons;
* The offset to UTC of the timezone is an integer in seconds (both before / after DST);
* The timezone will start / end its DST when Unix timestamp (as in second) is an integer;
* The timezone will either start / end its DST in the following year or it will never start / end its DST (No DST applied or use DST whole year);
## Example Outputs
Following example outputs assume user is running your program in 2021-06-01T00:00:00Z. Your program may need to have different behavior as time past.
```
America/Anchorage
* 1636279200
* 2021-11-07T10:00:00.000Z
* Sun Nov 07 2021 01:00:00 GMT-0900 (Alaska Standard Time)
* Sun Nov 07 2021 02:00:00 GMT-0800 (Alaska Daylight Time)
Australia/Adelaide
* 1633192200
* 2021-10-02T16:30:00.000Z
* Sun Oct 03 2021 03:00:00 GMT+1030 (Australian Central Daylight Time)
* Sun Oct 03 2021 02:00:00 GMT+0930 (Australian Central Standard Time)
Asia/Singapore
* No DST
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~105~~ 103 bytes ([SBCS](https://github.com/abrudz/SBCS))
-2 by throwing an error if the current location has no upcoming DST
Full program. Prints DateTime in local format (includes seconds), with the special value of midnight on the new-year of year 1 (in the past, so cannot be the real upcoming change time) indicating that there is no upcoming DST change.
```
⎕USING←'System'
DateTime.Now(⊃+.>↓⊢)∊(TimeZone.CurrentTimeZone.GetDaylightChanges¨0 1+⊃⎕TS).(Start End)
```
`⎕USING←'System'` use .NET's standard core library
`(`…`).(Start End)` get the Start and End times for each DST period in:
`⎕TS` the current **T**ime**S**tamp as a 7-element list: `(Y,M,D,h,m,s,ms)`
`⊃` pick the first element (the year); 2021
`0 1` add zero and one; `(2021,2022)`
`TimeZone.CurrentTimeZone.GetDaylightChanges¨` for each year, get its DST period
`∊` **e**nlist (flatten from pair of pairs, to 4-element list)
`DateTime.Now(`…`)` with the current time as left argument, apply the following tacit infix function:
`↓` drop the following number of elements from that:
`+.>` the sum of the 4-element Boolean list indicating the change times that the current time is greater than
`⊃` pick the first remaining change time
If there are no upcoming DST changes, then all Start and End times are midnight on the new-year of year 1. The current time is greater than all of these values, so we end up with no elements. Trying to pick the first one errors with a NONCE ERROR.
Trial run from the UK currently gives:
```
31/10/2021 02:00:00
```
[Answer]
# [PHP](https://php.net/), ~~72~~ 70 bytes
```
for($d=date(I,$r=$t=time());$d==date(I,++$t);)$t-$r<4e7?:die();echo$t;
```
[Try it online!](https://tio.run/##NYxBCsIwEEX3nmOgGaq4EQSnoXTpKUJopiZgmzAdN14@pgu3/733Syx1GEssp@CVXeDFf97qNK38zRu7ndV008qSZn@dtjlm8S/ukOqSxUCwR2aeZxALao/MIFLb/6DvQZEQ9AIy3Pg@PkJqDnG7AqVafw "PHP – Try It Online") for `'America/Anchorage'`, replace the timezone in the header to test another one
This time I'm proud of good ol' PHP! Will output the timestamp of the shift if there is one, or terminates with an empty string if there is no shift.
* `date('I',timestamp)` will return `1` if DST is on or `0` if off
* bruteforces for each second until the value changes
* if the checked timestamp minus initial timestamp reaches 40000000 (a regular year is 31536000 seconds) it terminates
**EDIT:** saved 2 bytes by pre-incrementing `$t`
[Answer]
# [Python 3](https://docs.python.org/3/), 183 bytes
```
from datetime import*
import pytz,time
y=k=datetime.now().replace(microsecond=0)
f=timedelta(seconds=1)
while pytz.timezone(time.tzname[0]).localize(y+f).dst():y+=f
if y!=k:print(y+f)
```
[Try it online!](https://tio.run/##NYzBCsMgEAXvfoW9aVskpbeAX1J6EF2JRF0xC0F/3pKEnh68GaY0WjC/x/AVE3eGgEICHlLBSnd2LS@N@vMArOlV/y2VcRdSVSjRWBAp2IobWMxOT5J5fTgOIhlxvZt@SbYvIcIZVAfvmEGcMerZJPhMX6kiWhNDB9EeXiq3kZBze2jPguftpte51JDppGP8AA "Python 3 – Try It Online")
-63 thanks to @ovs
[Test for America Anchorage!](https://tio.run/##NYxNCsMgGAX3nsKuok2wMd0FXOQoop@NxD@MUMzlLUno6sHM8FItawzv1kyOHmtZoFgP2PoUc3mie3Gq5RhOgarYxL8i0zjxgfPhTVmG5KQC4q3KcQcVgxYjRUacoQZXJLnpLjhF39U6uF7Z6Y8YgHSLh2yVfC1BrTHLD3SUuaiksweQ2hvK9F4InWsvDLIG14fY5pRtKJdt7Qc "Python 3 – Try It Online")
Horrendously slow, but works.
It repeatdly adds 1 second to current date, until it is DST or not.
If the current date is not DST, it exists with empty output.
I tested this by changing timezone (third line, function parameter) and dates (sixth and fifth line). It worked like a charm! The test timezone was Anchorage, and test date was Nov 1, 2021 (Changed date only for faster speed)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 172 bytes
```
for(d=()=>new Date,l=console.log,t=1000,a=d(),b=d(),c=0,i=x=>x.setSeconds(x.getSeconds()+1);(a-d()<32*t**3||l("no DST"))&&(c===t||!c||l(r));i(a),c=a-b,r=~~((+b+t)/t),i(b));
```
[Try it online!](https://tio.run/##RYxBDoIwEEWvgizIDBQsssRh5Q08QWkrwTStoRNlQbg6ghs3P3l5L/@p3irqaXxx6YOx2/YIExgCpM7bT3JTbIUjHXwMzlYuDIKpllIKRQZQ9L/VJMVIM3VzFS3f7Z6bCHM1/AGLGltQ5Z5fm0vOed4si4PUh8REThGzDDQR8bKc9GEmxHYEdZyrshcTrStA0ReMZ0YxQr/7bfsC "JavaScript (Node.js) – Try It Online")
This increments a `Date` by 1 *wall clock time* second until it detects that the incremented value is not 1 *Unix time* second apart from the original one. In such case it prints the Unix timestamp (seconds, integer) of the change. If no gap are found, prints `no DST`.
[Answer]
# [Go](//golang.org), 168 bytes
```
package main
import."time"
func main(){a:=Now()
_,b:=a.Zone()
for c:=a;c.Unix()<a.AddDate(1,0,0).Unix();c=c.Add(Minute){_,d:=c.Zone()
if d!=b{print(c.String())
break}}}
```
] |
[Question]
[
This [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge is based partly on [this MSE question](https://math.stackexchange.com/q/4069929/121988) and exists to extend some OEIS sequences, and create others. If I extend or create sequences based on this challenge, I'll link to this challenge so that folks can see where the values come from. If you'd like direct credit, include your first and last name so I can cite you on the entry.
These are now tables in the OEIS as [A342840](https://oeis.org/A342840) (1342), [A342860](https://oeis.org/A342860) (2413), [A342861](https://oeis.org/A342861) (1324), [A342862](https://oeis.org/A342862) (2143), [A342863](https://oeis.org/A342863) (1243), [A342864](https://oeis.org/A342864) (1432), and [A342865](https://oeis.org/A342865) (1234).
---
## Definition
Let \$\sigma \in S\_n\$ be a permutation on \$n\$ letters, and let \$\tau \in S\_m\$ be a permution on \$m \leq n\$ letters, both read as words: $$
\sigma = \sigma\_1\sigma\_2 \dots \sigma\_n \text{ and } \tau = \tau\_1\tau\_2 \dots \tau\_m
$$
The permutation statistic \$\operatorname{pat}\_\tau(\sigma)\$ counts the number of length-\$m\$ subsequences of \$\sigma\$ that are in the same relative order as \$\tau\$.
## Challenge
This [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge will have you take a permutation \$\tau \in S\_m\$ and an integer \$n \geq m\$ and return a (0-indexed) list where position \$i\$ has the number of permutations \$\sigma \in S\_n\$ such that \$\operatorname{pat}\_{\tau}(\sigma) = i\$. If done correctly, the list will sum to \$n!\$.
## Scoring
I will run your code on each of the following for one minute each for increasing values of \$n\$:
* the only pattern in \$S\_1\$: \$\tau = 1\$;
* essentially the only pattern in \$S\_2\$: \$\tau = 12\$;
* the two essentially different patterns in \$S\_3\$: \$\tau \in \{123, 132\}\$; and
* the seven essentially distinct patterns of \$S\_4\$: \$ \tau \in \{1234, 1243, 1324, 1342, 1432, 2143, 2413\}\$.
Your score will be the largest value of \$n\$ that can be computed within a minute for *every* pattern.
For example, if you can compute up to
* \$n = 1000\$ for \$\tau = 123\$ within a minute,
* \$n = 10\$ for \$\tau = 1342\$ within a minute, and
* \$n = 11\$ for \$\tau = 2413\$ within a minute,
then your score would be \$10\$.
### Examples
Suppose that \$\sigma = 7532146\$ and \$\tau = 4213\$. Then $$
\operatorname{pat}\_{4213}(7532146) = 13
$$ because \$\sigma = 7532146\$ has thirteen subsequences that are in the same relative order as \$\tau = 4213\$, \$7536\$, \$7526\$, \$7516\$, \$7546\$, \$7324\$, \$7326\$, \$7314\$, \$7316\$, \$7214\$, \$7216\$, \$5324\$, \$5314\$, and \$5214\$.
### Test Data
```
n | tau | target output
---+-------+--------------------------------------------------------------
6 | 1234 | [513, 102, 63, 10, 6, 12, 8, 0, 0, 5, 0, 0, 0, 0, 0, 1]
5 | 123 | [ 42, 27, 24, 7, 9, 6, 0, 4, 0, 0, 1]
9 | 1 | [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 362880]
5 | 132 | [ 42, 21, 23, 14, 12, 5, 3]
6 | 4213 | [512, 77, 69, 30, 21, 5, 6]
4 | 12 | [ 1, 3, 5, 6, 5, 3, 1]
6 | 53214 | [694, 18, 7, 0, 1]
```
Note: For \$\tau = 12\$, the target output should be the \$n\$-th row of OEIS sequence [A008302](https://oeis.org/A008302). For \$\tau = 1\$, the target output should be \$n\$ \$0\$s followed by \$n!\$.
[Answer]
# Rust, score ≈ 13
This enumerates permutations σ recursively, sharing as much computation as possible at branches of the search tree, so that only constant work is needed at each leaf.
Times in seconds measured on my Ryzen 7 1800X (8 cores/16 threads):
```
τ n = 10 11 12 13 14 15
──────────────────────────────────────────────
1 0.00 0.02 0.25 2.93 38.72 660.86
12 0.00 0.04 0.47 5.89 79.08 1268.18
123 0.00 0.06 0.67 8.47 115.61 1836.36
132 0.01 0.10 1.18 15.50 218.39 3443.56
1234 0.00 0.05 0.59 7.65 104.88 1643.29
1243 0.00 0.06 0.81 10.72 152.60 2417.75
1324 0.01 0.09 1.10 14.52 208.59 3280.18
1342 0.01 0.10 1.21 16.59 242.01 3871.64
1432 0.01 0.09 1.19 16.21 237.93 3808.25
2143 0.00 0.06 0.81 10.72 151.09 2409.76
2413 0.01 0.09 1.20 16.07 232.74 3717.70
──────────────────────────────────────────────
max 0.01 0.10 1.21 16.59 242.01 3871.64
```
Build and run with:
```
cargo build --release
target/release/permutations 11 '1 3 4 2'
```
Or [try it online!](https://tio.run/##xVjNjts2EL77Kbg5KNRGq9pJsAfZ1qVAgQItckjbQw1DkGV6TaxMCRK1mx8baIM@RJ@gr9N3yIPUnSEpi/qxsy1QVMjaMjn/881wmKIq5fFYlYyUch0ETDxMR6dfXLIiCH7mubVWpjxh09GIiWpHfszXsWTfAlkss2L2PA7JxxGB5zsWPzBaTW49ohiCAImAwCN6FT7c0PUU8Q/xPaPqDR/cHv4BhswuSOurguUw1Pyg6jAa8V2ektpcsoG/rgdR7YF8nzMk3ZG5pQQcx82NIIK9k9TZVZKULN245CYkb3LJMzGzTDKy8NnFMtmSayS2VvFpmxAEOnbcIwXbEFSwyiqxLl0yD81rix0fX1nj9td3cU73Dk2zR49s@d3W3RP8QV7or5Bwl8SlCrPaxw31Hc6bLdf1Lhqs8gf2yrgaN1Z/4Lky@WPPKtgxBmv7qG2gRxyQMwFD@4z48I3SQ2b4NTlDhA/KBPnvKPjxgkwu@Tco40BYCqC/rOBsIP0dF6D5jOje6qFN2BDot8MJdiX/wKItF4C9E@5ohatejT/1K3R72Hsy9CKvDzm/UfwUNIAI@FdDABM@yF97B/6Bb5WSpDsBJDcgzgLiudTkBdvFXHBxFxDtrlotJXCUSEl/Ysms1Q04krmGnQdNL0F0JnGaruLkPiCqJ3wjvq8kbbtSS/BGdSyxYTgUAa6D4pEEvqVLuDCWWPHlNZWfMkFdAOzJhU4Walvo2U5gBGE/plCNRu3UiqOtNmWSvM12jOrCGmtEjt1azsSFrJzymqdcRhtelJCZjmEoC/jJDIqFOA58wJuSNVAWJy8GIT@IkrOlxb2zWwCMBfyZoN60Yrw8z2Y8NyH0AZHUuSQKW4bvL91hiWeWVVr6W1aihotbw79kcZFso1Ky/L@vAa3shP43ImH0ggCrCBB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yQ13COvvor2aTxXXm8@TrL5U3KHlg6f/U3 "Rust – Try It Online")
(But note, the TIO version lacks parallelism and many other optimizations, so it’s much slower, due to being unable to use external crates.)
[All outputs](https://glot.io/snippets/fx5su1m6dq/raw/permutations.out) for *n* = 0…15.
**`Cargo.toml`**
```
[package]
name = "permutations"
version = "0.1.0"
authors = ["Anders Kaseorg <[[email protected]](/cdn-cgi/l/email-protection)>"]
edition = "2018"
[dependencies]
rayon = "1.5.0"
thread_local = "1.1.3"
typed-arena = "2.0.1"
[profile.release]
lto = "y"
panic = "abort"
```
**`src/main.rs`**
```
use rayon::prelude::*;
use std::cell::Cell;
use std::env;
use std::iter::Zip;
use std::slice;
use thread_local::ThreadLocal;
use typed_arena::Arena;
enum UpdateIterator<'a> {
Leave(u16, slice::Iter<'a, (u16, u16)>),
Take(
u16,
u16,
Zip<slice::Iter<'a, (u16, u16)>, slice::Iter<'a, u16>>,
),
}
impl Iterator for UpdateIterator<'_> {
type Item = (u16, u16);
fn next(&mut self) -> Option<(u16, u16)> {
match *self {
UpdateIterator::Leave(i, ref mut bounds) => bounds
.next()
.map(|&(low, high)| (low + (low > i) as u16, high + (high >= i) as u16)),
UpdateIterator::Take(i, tau0, ref mut zip) => {
zip.next().map(|(&(low, high), &tau1)| {
if tau0 < tau1 {
(low.max(i) + 1, high + (high >= i) as u16)
} else {
(low + (low > i) as u16, high.min(i))
}
})
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self {
UpdateIterator::Leave(_, bounds) => bounds.size_hint(),
UpdateIterator::Take(_, _, zip) => zip.size_hint(),
}
}
}
fn update(
tau: &[u16],
remaining: usize,
states: &[(&[(u16, u16)], isize)],
i: u16,
mut callback: impl FnMut(UpdateIterator, isize),
) {
for &(bounds, count) in states {
if bounds.len() < remaining {
callback(UpdateIterator::Leave(i, bounds.iter()), count);
}
if let Some((&(low0, high0), bounds1)) = bounds.split_first() {
if low0 <= i && i <= high0 {
callback(
UpdateIterator::Take(
i,
tau[tau.len() - bounds.len()],
bounds1.iter().zip(&tau[tau.len() - bounds.len() + 1..]),
),
count,
);
}
}
}
}
fn search_step(
tau: &[u16],
remaining: usize,
states: &[(&[(u16, u16)], isize)],
arena_len: usize,
i: u16,
search: impl FnOnce(&[(&[(u16, u16)], isize)], usize),
) {
let arena = Arena::with_capacity(2 * arena_len + 1 - states.len());
let mut new_states = Vec::with_capacity(states.len() * 2);
update(tau, remaining, states, i, |bounds, count| {
new_states.push((&*arena.alloc_extend(bounds), count))
});
new_states.sort_by_key(|&(bounds, _)| bounds);
new_states.dedup_by(|(bounds0, count0), (bounds1, count1)| {
bounds0 == bounds1 && {
*count1 += *count0;
true
}
});
search(&new_states, arena.len());
}
fn search(
n: usize,
tau: &[u16],
k: usize,
states: &[(&[(u16, u16)], isize)],
arena_len: usize,
output: &[Cell<u64>],
) {
if n - k == 1 {
let mut deltas = vec![0; n + 1];
let mut total = 0;
for &(bounds, count) in states {
match bounds {
[] => total += count,
&[(low, high)] => {
deltas[low as usize] += count;
deltas[high as usize + 1] -= count;
}
_ => {}
}
}
for delta in &deltas[..n] {
total += delta;
output[total as usize].set(output[total as usize].get() + 1);
}
} else if n - k == 2 {
for i in 0..=k as u16 {
let mut deltas = vec![0; n + 1];
let mut total = 0;
update(tau, n - k, states, i, |mut bounds, count| {
if let Some((low, high)) = bounds.next() {
deltas[low as usize] += count;
deltas[high as usize + 1] -= count;
debug_assert!(bounds.next().is_none());
} else {
total += count;
}
});
for delta in &deltas[..n] {
total += delta;
output[total as usize].set(output[total as usize].get() + 1);
}
}
} else {
for i in 0..=k as u16 {
search_step(tau, n - k, states, arena_len, i, |states, arena_len| {
search(n, tau, k + 1, states, arena_len, output)
})
}
}
}
fn par_search(
n: usize,
tau: &[u16],
k: usize,
states: &[(&[(u16, u16)], isize)],
arena_len: usize,
comb: usize,
outputs: &ThreadLocal<Vec<Cell<u64>>>,
) {
if n - k <= 4 {
search(
n,
tau,
k,
states,
arena_len,
outputs.get_or(|| vec![Cell::new(0); comb + 1]),
);
} else {
(0..=k as u16).into_par_iter().for_each(|i| {
search_step(tau, n - k, states, arena_len, i, |states, arena_len| {
par_search(n, tau, k + 1, states, arena_len, comb, outputs)
})
});
}
}
fn counts(n: usize, tau: &[u16]) -> Vec<u64> {
if n > tau.len() {
let mut comb = 1;
for i in 0..tau.len() {
comb = comb * (n - i) / (i + 1);
}
let outputs = ThreadLocal::new();
par_search(
n,
&tau,
0,
&[(&vec![(0, 0); tau.len()], 1)],
tau.len(),
comb,
&outputs,
);
let mut output = vec![0; comb + 1];
for thread_output in outputs {
for (x, y) in output.iter_mut().zip(thread_output) {
*x += y.get();
}
}
output.truncate(
output
.iter()
.rposition(|&count| count != 0)
.map_or(0, |i| i + 1),
);
output
} else if n == tau.len() {
vec![(1..=n as u64).product::<u64>() - 1, 1]
} else {
vec![(1..=n as u64).product()]
}
}
fn main() {
let args: Vec<String> = env::args().collect();
if let [_, n, tau] = &*args {
let n: usize = n.parse().unwrap();
let tau: Vec<u16> = tau.split_whitespace().map(|n| n.parse().unwrap()).collect();
for count in counts(n, &tau) {
println!("{}", count);
}
} else {
panic!("usage: permutations n 'τ₁ τ₂ … τₘ'")
}
}
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), Score: 10 (estimated)
For now, this is a very simple implementation to make sure I understood the challenge correctly. The score is probably just **10**, which is quite bad.
```
function count(a, b, c = [], p = 0, i = 0) {
return (
p == b.length ? 1 :
i == a.length ? 0 :
(
b.every((v, k) => k >= p || Math.sign(b[p] - v) == Math.sign(a[i] - c[k])) &&
count(a, b, [...c, a[i]], p + 1, i + 1)
) +
count(a, b, c, p, i + 1)
);
}
function perm(a) {
let r = [];
(function P(a, p = []) {
if(a.length) {
a.forEach((v, i) => P(a.filter(_ => i--), [...p, v]));
}
else {
r.push(p);
}
})(a);
return r;
}
function f(n, t) {
let list = [];
perm([...Array(n)].map((_, i) => i + 1)).forEach(p => {
let x = count(p, t);
if(!list[x]) {
for(let i = 0; i <= x; i++) list[i] |= 0;
}
list[x]++;
});
return list;
}
```
[Try it online!](https://tio.run/##dVJNb6MwEL3zK2YvrS2I1XTTSl2Wrvawx0p7R6hyqEm8ocYyBqVq8tuzM4aE9OvCwMy8N/Pe8E/2si2dtn5mmid1uOxaBa13uvSX6aHqTOl1Y6BsOuOZTGCZQAkZ5EUCFuNVApoCh9cIwCnfOQMMX4HKGSxFrczKr@EXzOFHyGvKyyl/NeYHFCBE9cq9MNYnsOGQ3cMG7jOk2@3gQfq1aPXKsGVuC5hBz4ltSstcU7rMNwXncHExcp6vnwshygSoM4iIYU4iMPDQzSGO3mOw35418TTaR9HJHKvcM5ODBbXy4IJBaYSf7NT0l6hsqAyd6ETFjj4cU4DOVI37I8t1MEAHAxArKl175dgjfevZjA9CcKselaYBvA9PVeMFj2xO2K5dM3vWsee4a1huPJd7q6ZiJgE/qal16ydBQStN/u2cfGGGF@JZWsYej7sOJvGTCkvJYR1i2yLV4KylKYEzOPGN5uTbYnICGRhBwg@WYviZwRZjHPOwFJ16R6Uz8SNJHKdBaTqppAoKPZSNaZtaibpZsYrdoo14/usEviewQCejt/Wbqf6xeEfFLzFIeP2xSAMXgXD@KediHPg58magDWDa9vAf "JavaScript (Node.js) – Try It Online")
[Answer]
# C++ (clang), score 11
```
#include "patterns_in_permutations.hpp"
int main(int argc, char *argv[])
{
unsigned int running_time = 60;
unsigned int n = 4;
std::unordered_map<size_t, std::vector<std::string>> all_gens;
const auto start = std::chrono::steady_clock::now();
for (const auto finish = start + std::chrono::seconds{running_time}; n < 12 && std::chrono::steady_clock::now() < finish; ++n)
{
Perms p(n);
const std::vector<std::string> gens = p.Generate();
all_gens[n] = gens;
Runner1(n);
}
const std::chrono::duration<double> duration = std::chrono::steady_clock::now() - start;
std::cout << "It took " << duration.count() << " seconds.\n";
Runner(Runner2, running_time, 4, "12", all_gens);
Runner(Runner3, running_time, 4, "123", all_gens);
Runner(Runner3, running_time, 4, "132", all_gens);
Runner(Runner4, running_time, 4, "1234", all_gens);
Runner(Runner4, running_time, 4, "1243", all_gens);
Runner(Runner4, running_time, 4, "1324", all_gens);
Runner(Runner4, running_time, 4, "1342", all_gens);
Runner(Runner4, running_time, 4, "1423", all_gens);
Runner(Runner4, running_time, 4, "1432", all_gens);
Runner(Runner4, running_time, 4, "2143", all_gens);
Runner(Runner4, running_time, 4, "2413", all_gens);
return 0;
}
```
### patterns\_in\_permutations.hpp:
```
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <algorithm>
#include <iterator>
#include <thread>
#include <chrono>
#include <unordered_map>
class Perms
{
public:
Perms(size_t n)
{
char next = '1';
for (int i = 0; i < n; ++i) {
base_+= next;
++next;
}
}
std::vector<std::string> Generate()
{
std::string current = base_;
do {
perms_.push_back(current);
} while (std::next_permutation(current.begin(), current.end()));
return perms_;
}
private:
std::vector<std::string> perms_;
std::string base_;
};
class Pattern2
{
public:
Pattern2()
{}
unsigned int CountMatches(const std::string& word) const
{
unsigned int matches = 0;
size_t size = word.size();
for (int i = 0; i < size - 1; ++i)
for (int j = i + 1; j < size; ++j)
matches += word[i] < word[j];
return matches;
}
};
class Pattern3
{
public:
Pattern3(const std::string& word) : pattern_{GenPattern(word[0], word[1], word[2])}
{}
unsigned int GenPattern(char a, char b, char c) const
{
unsigned int pattern = (a>b) | ((a>c)<<1) | ((b>c)<<2);
return pattern;
}
bool Matches(char a, char b, char c) const
{
unsigned int pattern = GenPattern(a, b, c);
return pattern == pattern_;
}
unsigned int CountMatches(const std::string& word) const
{
unsigned int matches = 0;
size_t size = word.size();
for (int i = 0; i < size - 2; ++i)
for (int j = i + 1; j < size - 1; ++j)
for (int k = j + 1; k < size; ++k)
matches += Matches(word[i], word[j], word[k]);
return matches;
}
private:
unsigned int pattern_;
};
class Pattern4
{
public:
Pattern4(const std::string& word) : pattern_{GenPattern(word[0], word[1], word[2], word[3])}
{}
unsigned int GenPattern(char a, char b, char c, char d) const
{
unsigned int pattern = (a>b) | ((a>c)<<1) | ((a>d)<<2) | ((b>c)<<3) | ((b>d)<<4) | ((c>d)<<5);
return pattern;
}
bool Matches(char a, char b, char c, char d) const
{
unsigned int pattern = GenPattern(a, b, c, d);
return pattern == pattern_;
}
unsigned int CountMatches(const std::string& word) const
{
unsigned int matches = 0;
size_t size = word.size();
for (int i = 0; i < size - 3; ++i)
for (int j = i + 1; j < size - 2; ++j)
for (int k = j + 1; k < size - 1; ++k)
for (int l = k + 1; l < size; ++l)
matches += Matches(word[i], word[j], word[k], word[l]);
return matches;
}
private:
unsigned int pattern_;
};
void Print(unsigned int n, const std::string& tau, const std::vector<unsigned long>& counts)
{
std::cout << "n is: " << n << ", tau is: " << tau << ", and we have: [";
int i = 0;
for (auto c : counts) {
std::cout << (i ? ", " : "") << c;
++i;
}
std::cout << "]\n";
}
void Runner1(unsigned int n)
{
unsigned int num_counts = n + 1;
std::vector<unsigned long> counts(num_counts, 0);
counts[n] = 1;
for (int i = 2; i <= n; ++i) {
counts[n] *= i;
}
Print(n, "1", counts);
}
void Runner2(const std::string&, unsigned int n, const std::vector<std::string>& gens)
{
Pattern2 pat;
unsigned int num_counts = n*n;
std::vector<unsigned long> counts(num_counts, 0);
for (const std::string& sigma : gens) {
auto matches = pat.CountMatches(sigma);
++counts[matches];
}
while (counts.back() == 0) {
counts.pop_back();
}
Print(n, "12", counts);
}
void Counter3(std::vector<unsigned long>& counts,
const std::vector<std::string>& gens,
const std::vector<std::string>::const_iterator& start,
const std::vector<std::string>::const_iterator& end,
const Pattern3& pat)
{
for (auto iter = start; iter < end; ++iter) {
auto matches = pat.CountMatches(*iter);
++counts[matches];
}
}
void Runner3(const std::string& tau, unsigned int n, const std::vector<std::string>& gens)
{
Pattern3 pat{tau};
unsigned int num_counts = n * n * (n - 1) * (n - 2);
size_t block_size = gens.size() / 4;
std::vector<unsigned long> counts0(num_counts, 0);
auto start0 = gens.begin();
auto end0 = start0;
std::advance(end0, block_size);
std::vector<unsigned long> counts1(num_counts, 0);
auto start1 = end0;
auto end1 = start1;
std::advance(end1, block_size);
std::vector<unsigned long> counts2(num_counts, 0);
auto start2 = end1;
auto end2 = start2;
std::advance(end2, block_size);
std::vector<unsigned long> counts3(num_counts, 0);
auto start3 = end2;
auto end3 = gens.end();
std::thread t0(Counter3, std::ref(counts0), std::cref(gens), std::cref(start0), std::cref(end0), std::cref(pat));
std::thread t1(Counter3, std::ref(counts1), std::cref(gens), std::cref(start1), std::cref(end1), std::cref(pat));
std::thread t2(Counter3, std::ref(counts2), std::cref(gens), std::cref(start2), std::cref(end2), std::cref(pat));
std::thread t3(Counter3, std::ref(counts3), std::cref(gens), std::cref(start3), std::cref(end3), std::cref(pat));
t0.join();
t1.join();
t2.join();
t3.join();
std::vector<unsigned long> counts(num_counts, 0);
for (int i = 0; i < num_counts; ++i) {
counts[i] = counts0[i] + counts1[i] + counts2[i] + counts3[i];
}
while (counts.back() == 0) {
counts.pop_back();
}
Print(n, tau, counts);
}
void Counter4(std::vector<unsigned long>& counts,
const std::vector<std::string>& gens,
const std::vector<std::string>::const_iterator& start,
const std::vector<std::string>::const_iterator& end,
const Pattern4& pat)
{
for (auto iter = start; iter < end; ++iter) {
auto matches = pat.CountMatches(*iter);
++counts[matches];
}
}
void Runner4(const std::string& tau, unsigned int n, const std::vector<std::string>& gens)
{
Pattern4 pat{tau};
unsigned int num_counts = n * n * (n - 1) * (n - 2) * (n - 3);
size_t block_size = gens.size() / 4;
std::vector<unsigned long> counts0(num_counts, 0);
auto start0 = gens.begin();
auto end0 = start0;
std::advance(end0, block_size);
std::vector<unsigned long> counts1(num_counts, 0);
auto start1 = end0;
auto end1 = start1;
std::advance(end1, block_size);
std::vector<unsigned long> counts2(num_counts, 0);
auto start2 = end1;
auto end2 = start2;
std::advance(end2, block_size);
std::vector<unsigned long> counts3(num_counts, 0);
auto start3 = end2;
auto end3 = gens.end();
std::thread t0(Counter4, std::ref(counts0), std::cref(gens), std::cref(start0), std::cref(end0), std::cref(pat));
std::thread t1(Counter4, std::ref(counts1), std::cref(gens), std::cref(start1), std::cref(end1), std::cref(pat));
std::thread t2(Counter4, std::ref(counts2), std::cref(gens), std::cref(start2), std::cref(end2), std::cref(pat));
std::thread t3(Counter4, std::ref(counts3), std::cref(gens), std::cref(start3), std::cref(end3), std::cref(pat));
t0.join();
t1.join();
t2.join();
t3.join();
std::vector<unsigned long> counts(num_counts, 0);
for (int i = 0; i < num_counts; ++i) {
counts[i] = counts0[i] + counts1[i] + counts2[i] + counts3[i];
}
while (counts.back() == 0) {
counts.pop_back();
}
Print(n, tau, counts);
}
template<typename Func>
void Runner(Func func, unsigned int running_time, unsigned int n, const std::string& tau, std::unordered_map<size_t, std::vector<std::string>>& all_gens)
{
const auto start = std::chrono::steady_clock::now();
for (const auto finish = start + std::chrono::seconds{running_time}; n < 12 && std::chrono::steady_clock::now() < finish; ++n)
{
const std::vector<std::string> gens = all_gens[n];
func(tau, n, gens);
}
const std::chrono::duration<double> duration = std::chrono::steady_clock::now() - start;
std::cout << "It took " << duration.count() << " seconds.\n";
}
```
### Outputs:
```
n is: 4, tau is: 1, and we have: [0, 0, 0, 0, 24]
n is: 5, tau is: 1, and we have: [0, 0, 0, 0, 0, 120]
n is: 6, tau is: 1, and we have: [0, 0, 0, 0, 0, 0, 720]
n is: 7, tau is: 1, and we have: [0, 0, 0, 0, 0, 0, 0, 5040]
n is: 8, tau is: 1, and we have: [0, 0, 0, 0, 0, 0, 0, 0, 40320]
n is: 9, tau is: 1, and we have: [0, 0, 0, 0, 0, 0, 0, 0, 0, 362880]
n is: 10, tau is: 1, and we have: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3628800]
n is: 11, tau is: 1, and we have: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39916800]
It took 2.29098 seconds.
n is: 4, tau is: 12, and we have: [1, 3, 5, 6, 5, 3, 1]
n is: 5, tau is: 12, and we have: [1, 4, 9, 15, 20, 22, 20, 15, 9, 4, 1]
n is: 6, tau is: 12, and we have: [1, 5, 14, 29, 49, 71, 90, 101, 101, 90, 71, 49, 29, 14, 5, 1]
n is: 7, tau is: 12, and we have: [1, 6, 20, 49, 98, 169, 259, 359, 455, 531, 573, 573, 531, 455, 359, 259, 169, 98, 49, 20, 6, 1]
n is: 8, tau is: 12, and we have: [1, 7, 27, 76, 174, 343, 602, 961, 1415, 1940, 2493, 3017, 3450, 3736, 3836, 3736, 3450, 3017, 2493, 1940, 1415, 961, 602, 343, 174, 76, 27, 7, 1]
n is: 9, tau is: 12, and we have: [1, 8, 35, 111, 285, 628, 1230, 2191, 3606, 5545, 8031, 11021, 14395, 17957, 21450, 24584, 27073, 28675, 29228, 28675, 27073, 24584, 21450, 17957, 14395, 11021, 8031, 5545, 3606, 2191, 1230, 628, 285, 111, 35, 8, 1]
n is: 10, tau is: 12, and we have: [1, 9, 44, 155, 440, 1068, 2298, 4489, 8095, 13640, 21670, 32683, 47043, 64889, 86054, 110010, 135853, 162337, 187959, 211089, 230131, 243694, 250749, 250749, 243694, 230131, 211089, 187959, 162337, 135853, 110010, 86054, 64889, 47043, 32683, 21670, 13640, 8095, 4489, 2298, 1068, 440, 155, 44, 9, 1]
n is: 11, tau is: 12, and we have: [1, 10, 54, 209, 649, 1717, 4015, 8504, 16599, 30239, 51909, 84591, 131625, 196470, 282369, 391939, 526724, 686763, 870233, 1073227, 1289718, 1511742, 1729808, 1933514, 2112319, 2256396, 2357475, 2409581, 2409581, 2357475, 2256396, 2112319, 1933514, 1729808, 1511742, 1289718, 1073227, 870233, 686763, 526724, 391939, 282369, 196470, 131625, 84591, 51909, 30239, 16599, 8504, 4015, 1717, 649, 209, 54, 10, 1]
It took 2.13947 seconds.
n is: 4, tau is: 123, and we have: [14, 6, 3, 0, 1]
n is: 5, tau is: 123, and we have: [42, 27, 24, 7, 9, 6, 0, 4, 0, 0, 1]
n is: 6, tau is: 123, and we have: [132, 110, 133, 70, 74, 54, 37, 32, 24, 12, 16, 6, 6, 8, 0, 0, 5, 0, 0, 0, 1]
n is: 7, tau is: 123, and we have: [429, 429, 635, 461, 507, 395, 387, 320, 260, 232, 191, 162, 104, 130, 100, 24, 74, 62, 18, 32, 10, 30, 13, 8, 0, 10, 10, 0, 0, 0, 6, 0, 0, 0, 0, 1]
n is: 8, tau is: 123, and we have: [1430, 1638, 2807, 2528, 3008, 2570, 2864, 2544, 2389, 2182, 2077, 1818, 1580, 1456, 1494, 886, 1047, 1004, 682, 656, 546, 466, 537, 288, 228, 324, 252, 156, 115, 138, 154, 66, 58, 60, 68, 38, 47, 0, 18, 40, 16, 10, 0, 0, 15, 12, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 1]
n is: 9, tau is: 123, and we have: [4862, 6188, 11864, 12525, 16151, 15203, 18179, 17357, 18096, 17333, 17505, 16605, 15847, 15068, 15049, 12630, 12472, 12101, 10837, 9588, 8935, 8225, 8089, 6836, 5405, 6072, 5158, 4541, 3901, 3462, 3412, 2976, 2524, 2151, 1887, 1995, 1583, 1312, 1064, 1190, 850, 834, 823, 508, 488, 420, 458, 427, 282, 186, 166, 234, 148, 248, 44, 80, 57, 66, 110, 58, 50, 0, 10, 20, 60, 19, 12, 0, 0, 0, 21, 14, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 1]
n is: 10, tau is: 123, and we have: [16796, 23256, 48756, 58258, 80889, 83382, 105082, 107194, 120197, 121630, 129449, 128712, 132579, 130310, 133945, 124572, 127049, 121602, 121330, 112240, 109115, 103134, 102875, 95256, 86372, 84020, 82579, 73540, 69645, 64590, 61259, 56574, 53742, 47734, 44615, 41368, 39552, 35538, 31990, 29182, 27361, 25088, 23871, 20574, 18612, 16776, 15679, 14582, 14304, 11058, 9812, 9188, 8974, 9012, 6788, 5824, 5451, 4708, 5058, 4682, 3486, 3004, 2795, 2206, 2678, 2434, 1977, 1256, 1192, 1134, 1480, 1130, 986, 606, 401, 608, 603, 700, 378, 312, 192, 156, 264, 296, 326, 60, 107, 64, 15, 120, 172, 72, 59, 0, 12, 0, 35, 84, 22, 14, 0, 0, 0, 0, 28, 16, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 1]
n is: 11, tau is: 123, and we have: [58786, 87210, 196707, 259787, 385387, 431167, 568809, 616449, 730182, 778432, 868607, 901457, 975820, 1000220, 1059437, 1051194, 1099257, 1092656, 1121794, 1101327, 1106169, 1079286, 1094214, 1065888, 1031696, 1005574, 1002920, 963317, 925079, 897540, 867777, 833036, 807892, 761461, 735291, 694925, 665451, 644967, 601738, 567469, 536582, 514598, 487819, 457925, 428537, 402525, 377705, 354636, 343753, 315180, 288746, 273107, 250591, 248644, 223830, 206056, 191347, 177756, 167509, 159312, 140646, 133790, 124559, 111283, 105226, 98752, 89678, 84846, 74486, 68371, 65623, 60868, 54635, 50256, 43978, 42730, 39349, 35811, 32045, 28528, 27264, 25732, 21425, 20715, 19063, 16286, 14829, 15964, 11766, 11168, 11210, 8690, 8278, 8326, 7356, 6657, 5607, 4362, 4878, 3660, 3955, 4146, 3456, 2574, 1787, 1862, 1688, 2283, 1806, 1756, 1310, 874, 398, 746, 867, 1089, 850, 534, 508, 166, 150, 166, 533, 392, 462, 64, 148, 66, 0, 35, 222, 224, 98, 68, 0, 14, 0, 0, 56, 112, 25, 16, 0, 0, 0, 0, 0, 36, 18, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 1]
It took 4.41592 seconds.
n is: 4, tau is: 132, and we have: [14, 5, 4, 1]
n is: 5, tau is: 132, and we have: [42, 21, 23, 14, 12, 5, 3]
n is: 6, tau is: 132, and we have: [132, 84, 107, 82, 96, 55, 64, 37, 29, 22, 10, 0, 2]
n is: 7, tau is: 132, and we have: [429, 330, 464, 410, 526, 394, 475, 365, 360, 298, 281, 175, 206, 126, 93, 55, 23, 14, 13, 1, 2]
n is: 8, tau is: 132, and we have: [1430, 1287, 1950, 1918, 2593, 2225, 2858, 2489, 2682, 2401, 2620, 2088, 2321, 1853, 1770, 1576, 1417, 1152, 1048, 730, 647, 397, 322, 169, 162, 109, 41, 37, 20, 0, 7, 1]
n is: 9, tau is: 132, and we have: [4862, 5005, 8063, 8657, 12165, 11539, 15174, 14772, 16627, 16066, 18248, 16413, 18449, 16681, 17104, 16300, 16525, 14486, 14891, 12878, 12952, 11213, 10816, 8969, 8484, 7136, 6163, 4914, 4110, 3094, 2722, 1937, 1611, 1181, 950, 509, 510, 311, 107, 141, 85, 11, 37, 6, 0, 5, 1]
n is: 10, tau is: 132, and we have: [16796, 19448, 33033, 38225, 55482, 57064, 76381, 79768, 94243, 96248, 112709, 109422, 124827, 121352, 130154, 129704, 137826, 130013, 137479, 129923, 134624, 128037, 129817, 119910, 120597, 112847, 109851, 101464, 98255, 88302, 86333, 75684, 71042, 62466, 57142, 47504, 43980, 36867, 31539, 26333, 23803, 18854, 16276, 12781, 10735, 8453, 6665, 5023, 4158, 2658, 2056, 1584, 1040, 681, 562, 271, 175, 159, 83, 26, 44, 11, 4, 6, 1]
n is: 11, tau is: 132, and we have: [58786, 75582, 134576, 166322, 248509, 273612, 372506, 411132, 501367, 540405, 645884, 666591, 771103, 792470, 873391, 904364, 988292, 984496, 1062388, 1058312, 1121118, 1117511, 1167522, 1140122, 1182129, 1158052, 1180398, 1150418, 1167814, 1120075, 1134523, 1080774, 1075062, 1022688, 1008723, 948246, 933609, 874695, 839814, 777886, 749612, 684351, 647464, 583310, 541746, 487788, 449094, 396602, 365025, 316887, 287377, 251343, 226338, 190755, 170845, 144866, 126540, 104648, 90914, 73269, 62680, 50919, 41128, 32514, 26314, 19986, 16651, 12085, 9197, 7079, 5386, 3647, 2884, 2099, 1284, 1016, 769, 358, 343, 150, 111, 82, 41, 6, 19, 6, 4, 1]
It took 4.17272 seconds.
n is: 4, tau is: 1234, and we have: [23, 1]
n is: 5, tau is: 1234, and we have: [103, 12, 4, 0, 0, 1]
n is: 6, tau is: 1234, and we have: [513, 102, 63, 10, 6, 12, 8, 0, 0, 5, 0, 0, 0, 0, 0, 1]
n is: 7, tau is: 1234, and we have: [2761, 770, 665, 196, 146, 116, 142, 46, 10, 72, 32, 24, 0, 13, 0, 12, 18, 0, 0, 10, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
n is: 8, tau is: 1234, and we have: [15767, 5545, 5982, 2477, 2148, 1204, 1782, 885, 503, 804, 573, 600, 199, 312, 112, 156, 333, 115, 96, 136, 142, 12, 0, 89, 24, 84, 44, 24, 10, 41, 0, 0, 40, 0, 0, 28, 8, 0, 0, 10, 0, 15, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
n is: 9, tau is: 1234, and we have: [94359, 39220, 49748, 25886, 25190, 13188, 19936, 11533, 9599, 9533, 7775, 8585, 5312, 5586, 3004, 3006, 4679, 2718, 2776, 2102, 3081, 1323, 640, 1586, 1253, 1590, 928, 998, 502, 948, 620, 220, 746, 567, 272, 400, 408, 242, 54, 440, 158, 302, 124, 157, 30, 364, 112, 12, 161, 94, 48, 28, 16, 60, 0, 152, 44, 94, 40, 46, 0, 10, 40, 0, 0, 50, 20, 0, 0, 0, 12, 68, 0, 0, 10, 19, 0, 0, 0, 0, 12, 0, 0, 0, 0, 21, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
n is: 10, tau is: 1234, and we have: [586590, 276144, 396642, 244233, 260505, 142550, 210663, 130920, 132620, 113954, 100201, 102866, 85736, 82752, 55779, 51594, 64086, 46271, 48938, 36084, 49273, 30289, 24894, 25486, 25212, 29569, 20598, 20286, 15216, 18642, 16001, 10686, 14354, 12342, 12164, 9042, 9190, 8688, 5268, 8640, 6875, 7195, 4618, 6043, 2831, 6714, 5228, 2594, 3816, 3726, 4140, 1548, 1916, 2116, 992, 3908, 1846, 2534, 1824, 2104, 1208, 994, 1422, 953, 870, 1320, 1210, 737, 372, 779, 302, 1426, 586, 828, 424, 942, 350, 68, 747, 263, 265, 299, 160, 56, 422, 594, 140, 406, 16, 108, 246, 340, 300, 8, 104, 161, 50, 216, 0, 0, 116, 240, 0, 80, 15, 142, 72, 24, 0, 56, 187, 0, 40, 0, 0, 158, 60, 0, 0, 0, 12, 60, 0, 0, 0, 59, 12, 8, 0, 35, 10, 0, 0, 0, 0, 84, 12, 0, 0, 0, 22, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 28, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
n is: 11, tau is: 1234, and we have: [3763290, 1948212, 3089010, 2167834, 2493489, 1476655, 2136586, 1396483, 1574270, 1308353, 1231914, 1168760, 1139142, 1065192, 848857, 772876, 854099, 688165, 725885, 568412, 709188, 510887, 500661, 428278, 433048, 460477, 396052, 360136, 307833, 337855, 307073, 252242, 275869, 230346, 254906, 212275, 202396, 177857, 160884, 176735, 155432, 160778, 126044, 139380, 102473, 129824, 119286, 100572, 96254, 84524, 108448, 70634, 67477, 66313, 48076, 79778, 60889, 67211, 49818, 62162, 47384, 37102, 46130, 38655, 38438, 36768, 36972, 33390, 24838, 27562, 19970, 35462, 23347, 26997, 19102, 26876, 21432, 16120, 19400, 16220, 17410, 12648, 12176, 8489, 12720, 19653, 10636, 11919, 8356, 11398, 6688, 11942, 11340, 5242, 8694, 7886, 5136, 8846, 5104, 4526, 3704, 8888, 3228, 6718, 3714, 5102, 2336, 3804, 4226, 2584, 5818, 2710, 2235, 2682, 2162, 3645, 3398, 3668, 908, 2298, 2028, 1972, 2084, 1264, 360, 2673, 2228, 610, 564, 1882, 780, 2404, 664, 540, 101, 2426, 1492, 1344, 136, 500, 1064, 620, 1060, 184, 552, 1179, 354, 250, 416, 538, 508, 644, 10, 32, 460, 857, 568, 192, 0, 330, 296, 668, 504, 12, 0, 618, 143, 180, 16, 40, 92, 388, 10, 225, 320, 134, 12, 20, 0, 60, 324, 138, 120, 60, 24, 342, 66, 120, 0, 40, 40, 24, 103, 0, 0, 0, 78, 0, 60, 210, 0, 0, 66, 0, 0, 140, 84, 0, 0, 0, 12, 22, 84, 0, 10, 0, 0, 68, 0, 0, 12, 0, 0, 0, 0, 56, 0, 0, 0, 0, 14, 0, 112, 0, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
It took 10.9059 seconds.
n is: 4, tau is: 1243, and we have: [23, 1]
n is: 5, tau is: 1243, and we have: [103, 11, 4, 2]
n is: 6, tau is: 1243, and we have: [513, 88, 56, 32, 14, 7, 9, 0, 0, 1]
n is: 7, tau is: 1243, and we have: [2761, 638, 543, 341, 235, 138, 173, 51, 42, 47, 34, 6, 17, 4, 0, 7, 1, 0, 2]
n is: 8, tau is: 1243, and we have: [15767, 4478, 4600, 3119, 2658, 1710, 2180, 972, 975, 877, 771, 356, 542, 233, 184, 266, 157, 81, 130, 41, 60, 49, 16, 16, 37, 8, 9, 13, 3, 0, 10, 1, 0, 0, 0, 0, 1]
n is: 9, tau is: 1243, and we have: [94359, 31199, 36691, 26602, 25756, 17628, 22984, 12381, 13705, 11786, 11395, 6832, 9438, 5252, 4870, 5314, 4350, 2787, 3611, 1905, 2415, 2032, 1200, 1029, 1510, 905, 794, 680, 579, 409, 541, 242, 295, 275, 130, 137, 296, 56, 45, 120, 77, 28, 86, 17, 21, 45, 15, 4, 23, 0, 9, 5, 3, 0, 8, 1, 0, 1, 0, 0, 2]
n is: 10, tau is: 1243, and we have: [586590, 218033, 284370, 218957, 231390, 166338, 221429, 133959, 156652, 134354, 137682, 94181, 125521, 80373, 80587, 80257, 74696, 53683, 65521, 42356, 50366, 43226, 33854, 27707, 36211, 25734, 24108, 21261, 20671, 15427, 18681, 11391, 12545, 11648, 8921, 8324, 10657, 6082, 5355, 5853, 5991, 3719, 4870, 2942, 2636, 3405, 2395, 1732, 2600, 1439, 1457, 1328, 1346, 740, 1183, 759, 674, 733, 469, 303, 656, 329, 190, 329, 307, 158, 221, 109, 96, 128, 117, 63, 108, 31, 42, 51, 37, 10, 43, 6, 26, 11, 14, 2, 23, 6, 0, 1, 0, 0, 11, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1]
n is: 11, tau is: 1243, and we have: [3763290, 1535207, 2174352, 1767837, 1994176, 1496134, 2028316, 1333828, 1613196, 1400002, 1491191, 1107853, 1450538, 1015596, 1068935, 1031355, 1025935, 793317, 946788, 684288, 792446, 693662, 618559, 517310, 636195, 490334, 483795, 432288, 438545, 352040, 408434, 292745, 311630, 284867, 255834, 234898, 267252, 191952, 185679, 177865, 186232, 142166, 160978, 116730, 115187, 121503, 102725, 86464, 102757, 74906, 75723, 69379, 67843, 50755, 61223, 49497, 47371, 43658, 35241, 31189, 41500, 26903, 25412, 26919, 24336, 20775, 22053, 15432, 16000, 15455, 14645, 11527, 14570, 8759, 8812, 9220, 8078, 6370, 8098, 4763, 6182, 5400, 4197, 3545, 4861, 3079, 2496, 2699, 2605, 1985, 2805, 1700, 1612, 1613, 1265, 1053, 1446, 659, 934, 727, 891, 550, 726, 376, 451, 469, 370, 193, 320, 176, 252, 257, 222, 110, 151, 87, 87, 87, 78, 27, 141, 30, 28, 32, 20, 36, 53, 11, 2, 14, 24, 0, 10, 0, 0, 15, 8, 0, 1, 0, 9, 1, 0, 1, 0, 0, 1, 0, 0, 0, 2]
It took 11.0133 seconds.
n is: 4, tau is: 1324, and we have: [23, 1]
n is: 5, tau is: 1324, and we have: [103, 10, 6, 1]
n is: 6, tau is: 1324, and we have: [513, 75, 74, 26, 17, 9, 6]
n is: 7, tau is: 1324, and we have: [2762, 522, 645, 321, 290, 130, 166, 47, 54, 48, 41, 4, 8, 2]
n is: 8, tau is: 1324, and we have: [15793, 3579, 5023, 3058, 3232, 1527, 2228, 874, 1159, 893, 875, 340, 503, 281, 269, 207, 156, 112, 123, 21, 54, 2, 0, 6, 5]
n is: 9, tau is: 1324, and we have: [94776, 24670, 37549, 26174, 30409, 15966, 23762, 10965, 15598, 11639, 12070, 6487, 9633, 5690, 6056, 5021, 4579, 3366, 4128, 1991, 2734, 1503, 1488, 1127, 1432, 765, 933, 657, 496, 262, 425, 106, 154, 74, 92, 26, 54, 8, 0, 7, 4, 0, 4]
n is: 10, tau is: 1324, and we have: [591950, 172198, 277089, 213122, 264667, 154452, 228665, 119090, 171635, 130545, 140681, 87346, 129648, 80843, 89519, 77927, 77496, 57636, 72997, 44129, 56802, 38567, 40481, 30585, 39332, 26288, 29031, 23149, 22663, 15442, 20266, 11940, 13360, 10107, 10516, 7633, 9318, 6070, 5707, 4886, 5013, 2983, 3876, 2168, 2205, 1851, 1824, 950, 1214, 526, 685, 386, 485, 74, 391, 116, 92, 32, 42, 3, 65, 32, 0, 0, 0, 0, 4, 4, 1]
n is: 11, tau is: 1324, and we have: [3824112, 1219974, 2043416, 1693787, 2213548, 1420513, 2086877, 1205632, 1719334, 1345649, 1499284, 1018334, 1487469, 982487, 1111324, 994064, 1041082, 795125, 999180, 685365, 853857, 640737, 685976, 541423, 679946, 501230, 546144, 458471, 479249, 364168, 448498, 315978, 353005, 288836, 301293, 241579, 283104, 210799, 217702, 188745, 197027, 145802, 170042, 125405, 132888, 113900, 115130, 86529, 99081, 69574, 79658, 61304, 64454, 46900, 56090, 38556, 42314, 32258, 33958, 24748, 29923, 19324, 21834, 16521, 15886, 12154, 14597, 8298, 9837, 6772, 7068, 4758, 6183, 2874, 4226, 2660, 2398, 1474, 1902, 751, 1314, 798, 482, 400, 388, 208, 316, 74, 87, 148, 86, 10, 32, 38, 24, 0, 16, 4, 14, 0, 0, 6, 0, 0, 0, 0, 1]
It took 11.162 seconds.
n is: 4, tau is: 1342, and we have: [23, 1]
n is: 5, tau is: 1342, and we have: [103, 10, 6, 1]
n is: 6, tau is: 1342, and we have: [512, 77, 69, 30, 21, 5, 6]
n is: 7, tau is: 1342, and we have: [2740, 548, 598, 330, 335, 123, 174, 58, 58, 37, 26, 3, 9, 1]
n is: 8, tau is: 1342, and we have: [15485, 3799, 4686, 2970, 3411, 1676, 2338, 1040, 1317, 878, 777, 363, 608, 230, 252, 165, 133, 30, 93, 26, 31, 4, 1, 3, 4]
n is: 9, tau is: 1342, and we have: [91245, 26165, 35148, 24550, 30182, 17185, 24685, 12976, 16867, 12248, 12360, 7203, 11086, 5692, 6391, 5194, 5006, 2751, 3917, 2019, 2482, 1622, 1371, 812, 1233, 490, 495, 416, 360, 157, 282, 54, 78, 41, 29, 22, 49, 7, 4, 0, 6]
n is: 10, tau is: 1342, and we have: [555662, 180512, 258390, 194524, 249925, 157765, 228949, 137892, 178897, 136866, 147875, 97336, 144013, 86383, 97551, 83482, 87825, 57805, 75538, 48428, 59365, 44334, 43055, 30914, 40620, 25178, 26230, 21239, 21735, 14478, 18540, 10413, 11956, 8481, 8007, 5559, 7822, 3944, 3937, 2917, 3450, 1677, 2394, 1149, 1250, 1028, 811, 379, 802, 216, 322, 236, 249, 90, 189, 50, 65, 35, 16, 2, 36, 0, 12]
n is: 11, tau is: 1342, and we have: [3475090, 1251832, 1882813, 1506786, 1998264, 1364500, 1991958, 1318382, 1727153, 1382970, 1540425, 1108017, 1581056, 1057910, 1212103, 1062295, 1152892, 843320, 1060298, 761390, 916286, 740645, 749373, 594592, 742181, 536033, 568444, 485474, 512375, 392372, 469748, 334596, 371632, 300252, 299179, 240512, 288754, 200025, 206566, 171109, 188723, 132675, 152423, 106675, 115972, 97837, 90729, 66595, 84156, 53183, 58167, 45687, 46707, 32569, 38358, 24868, 27436, 20574, 19746, 13524, 18937, 10616, 10981, 8781, 9015, 5447, 7130, 4028, 4673, 3378, 3130, 1960, 3506, 1238, 1538, 1296, 1094, 619, 941, 297, 546, 423, 198, 120, 356, 56, 82, 62, 26, 6, 80, 2, 14, 8, 8, 0, 2]
It took 11.0463 seconds.
n is: 4, tau is: 1423, and we have: [23, 1]
n is: 5, tau is: 1423, and we have: [103, 10, 6, 1]
n is: 6, tau is: 1423, and we have: [512, 77, 69, 30, 21, 5, 6]
n is: 7, tau is: 1423, and we have: [2740, 548, 598, 330, 335, 123, 174, 58, 58, 37, 26, 3, 9, 1]
n is: 8, tau is: 1423, and we have: [15485, 3799, 4686, 2970, 3411, 1676, 2338, 1040, 1317, 878, 777, 363, 608, 230, 252, 165, 133, 30, 93, 26, 31, 4, 1, 3, 4]
n is: 9, tau is: 1423, and we have: [91245, 26165, 35148, 24550, 30182, 17185, 24685, 12976, 16867, 12248, 12360, 7203, 11086, 5692, 6391, 5194, 5006, 2751, 3917, 2019, 2482, 1622, 1371, 812, 1233, 490, 495, 416, 360, 157, 282, 54, 78, 41, 29, 22, 49, 7, 4, 0, 6]
n is: 10, tau is: 1423, and we have: [555662, 180512, 258390, 194524, 249925, 157765, 228949, 137892, 178897, 136866, 147875, 97336, 144013, 86383, 97551, 83482, 87825, 57805, 75538, 48428, 59365, 44334, 43055, 30914, 40620, 25178, 26230, 21239, 21735, 14478, 18540, 10413, 11956, 8481, 8007, 5559, 7822, 3944, 3937, 2917, 3450, 1677, 2394, 1149, 1250, 1028, 811, 379, 802, 216, 322, 236, 249, 90, 189, 50, 65, 35, 16, 2, 36, 0, 12]
n is: 11, tau is: 1423, and we have: [3475090, 1251832, 1882813, 1506786, 1998264, 1364500, 1991958, 1318382, 1727153, 1382970, 1540425, 1108017, 1581056, 1057910, 1212103, 1062295, 1152892, 843320, 1060298, 761390, 916286, 740645, 749373, 594592, 742181, 536033, 568444, 485474, 512375, 392372, 469748, 334596, 371632, 300252, 299179, 240512, 288754, 200025, 206566, 171109, 188723, 132675, 152423, 106675, 115972, 97837, 90729, 66595, 84156, 53183, 58167, 45687, 46707, 32569, 38358, 24868, 27436, 20574, 19746, 13524, 18937, 10616, 10981, 8781, 9015, 5447, 7130, 4028, 4673, 3378, 3130, 1960, 3506, 1238, 1538, 1296, 1094, 619, 941, 297, 546, 423, 198, 120, 356, 56, 82, 62, 26, 6, 80, 2, 14, 8, 8, 0, 2]
It took 10.8298 seconds.
n is: 4, tau is: 1432, and we have: [23, 1]
n is: 5, tau is: 1432, and we have: [103, 11, 5, 0, 1]
n is: 6, tau is: 1432, and we have: [513, 87, 68, 17, 18, 10, 0, 4, 2, 0, 1]
n is: 7, tau is: 1432, and we have: [2761, 625, 626, 268, 274, 138, 112, 58, 51, 44, 31, 9, 15, 8, 12, 0, 5, 0, 0, 0, 3]
n is: 8, tau is: 1432, and we have: [15767, 4378, 5038, 2781, 3060, 1697, 1817, 1036, 964, 773, 656, 450, 379, 320, 285, 148, 237, 97, 98, 55, 68, 61, 23, 30, 30, 13, 30, 0, 0, 0, 16, 0, 10, 0, 0, 1, 0, 0, 0, 0, 2]
n is: 9, tau is: 1432, and we have: [94359, 30671, 38541, 24731, 28881, 17943, 21193, 13040, 14245, 10607, 10156, 7596, 7574, 5938, 5647, 3722, 4904, 3131, 3256, 2205, 2372, 1729, 1572, 1423, 1130, 846, 1014, 634, 644, 316, 609, 295, 371, 190, 306, 105, 195, 82, 94, 182, 86, 32, 79, 0, 49, 18, 41, 8, 30, 0, 43, 0, 20, 0, 0, 4, 1, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]
n is: 10, tau is: 1432, and we have: [586590, 216883, 289785, 205853, 251051, 170941, 211942, 142187, 163587, 128113, 128732, 100701, 109971, 85489, 85649, 67021, 75089, 56874, 60397, 45806, 49198, 40624, 37457, 32975, 31394, 26058, 26056, 20705, 20996, 14894, 17646, 12853, 13931, 10583, 10699, 8066, 8780, 6271, 6318, 6394, 5366, 3753, 4414, 2917, 3838, 2395, 3069, 1715, 2167, 1181, 1746, 1424, 1579, 880, 927, 841, 617, 569, 697, 293, 765, 139, 373, 268, 329, 241, 317, 85, 200, 108, 202, 94, 92, 16, 24, 78, 92, 19, 140, 0, 107, 5, 16, 10, 1, 4, 0, 0, 30, 0, 72, 4, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 2]
n is: 11, tau is: 1432, and we have: [3763290, 1552588, 2172387, 1663964, 2096207, 1535129, 1954751, 1417314, 1674215, 1367302, 1442060, 1166386, 1334171, 1059609, 1109249, 930634, 1012528, 817526, 883392, 712076, 770293, 657724, 659051, 567799, 581450, 505877, 505195, 435477, 442807, 363235, 391358, 314376, 330559, 279469, 279737, 233779, 247628, 202488, 198986, 181873, 178728, 145947, 151991, 122028, 133974, 106370, 109130, 88316, 95025, 72848, 77553, 66516, 69104, 54015, 56357, 46890, 45853, 39525, 41001, 29289, 37365, 24516, 28021, 21883, 24707, 20150, 20127, 13574, 17768, 13105, 14200, 11333, 12459, 8252, 8839, 8040, 8981, 5471, 8179, 4280, 6717, 4186, 4545, 3061, 4806, 3268, 2641, 2630, 2670, 1591, 3442, 2364, 2218, 905, 1571, 704, 1344, 916, 734, 877, 1257, 599, 1219, 446, 889, 470, 843, 210, 418, 136, 385, 83, 150, 172, 356, 50, 452, 274, 212, 42, 380, 36, 16, 34, 40, 62, 56, 34, 138, 0, 110, 0, 106, 20, 6, 84, 0, 0, 0, 0, 69, 1, 28, 0, 0, 0, 0, 12, 0, 0, 42, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8]
It took 10.8561 seconds.
n is: 4, tau is: 2143, and we have: [23, 1]
n is: 5, tau is: 2143, and we have: [103, 11, 4, 2]
n is: 6, tau is: 2143, and we have: [513, 88, 53, 33, 18, 8, 6, 0, 0, 1]
n is: 7, tau is: 2143, and we have: [2761, 642, 495, 340, 262, 160, 172, 65, 58, 39, 14, 6, 18, 0, 0, 6, 0, 0, 2]
n is: 8, tau is: 2143, and we have: [15767, 4567, 4099, 3007, 2692, 1832, 2171, 1152, 1291, 968, 728, 457, 566, 174, 176, 221, 129, 14, 122, 29, 38, 52, 8, 0, 32, 9, 0, 10, 0, 0, 8, 0, 0, 0, 0, 0, 1]
n is: 9, tau is: 2143, and we have: [94359, 32443, 32345, 25049, 24492, 17732, 21841, 13234, 15867, 12824, 11744, 8852, 10670, 5983, 6058, 5709, 4751, 2372, 3642, 1790, 2080, 1799, 1020, 719, 1508, 621, 456, 549, 490, 200, 498, 152, 170, 198, 66, 114, 189, 34, 8, 52, 70, 0, 58, 4, 0, 30, 0, 0, 22, 0, 6, 0, 0, 0, 8, 0, 0, 0, 0, 0, 2]
n is: 10, tau is: 2143, and we have: [586590, 232189, 250371, 203452, 211291, 160561, 201524, 133030, 162800, 136840, 134669, 109219, 134085, 90985, 97178, 91917, 87126, 60426, 74360, 50859, 55948, 46889, 37498, 28547, 39584, 23350, 21951, 20022, 19986, 12961, 17766, 9861, 11022, 9968, 6998, 6849, 9424, 4124, 3624, 4367, 4884, 2464, 3844, 1630, 1911, 2721, 1054, 795, 2217, 783, 873, 778, 600, 240, 748, 514, 486, 276, 130, 68, 522, 30, 58, 214, 121, 126, 116, 10, 16, 41, 64, 0, 140, 4, 12, 10, 0, 0, 32, 0, 18, 16, 0, 0, 12, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
n is: 11, tau is: 2143, and we have: [3763290, 1679295, 1926145, 1635315, 1776655, 1409304, 1787218, 1263567, 1554692, 1348551, 1376606, 1161259, 1427223, 1058226, 1158896, 1110992, 1120317, 883389, 1044049, 817100, 905437, 795435, 730734, 615053, 747506, 548342, 542930, 488947, 490209, 377724, 439366, 313966, 333400, 293175, 258751, 232438, 276324, 179719, 175730, 167202, 179041, 127377, 149490, 100038, 107522, 110872, 82676, 66882, 95691, 59304, 59918, 56481, 50440, 36032, 49024, 36793, 36822, 31347, 22820, 17667, 34580, 16068, 14327, 18082, 16211, 13114, 13538, 7564, 8832, 7829, 9394, 4766, 11001, 4054, 3146, 5248, 3522, 3338, 4014, 1790, 4034, 2533, 1382, 994, 3394, 1542, 348, 790, 1528, 530, 2034, 880, 420, 370, 192, 288, 1138, 280, 210, 458, 321, 110, 308, 48, 316, 116, 62, 0, 350, 16, 140, 32, 98, 0, 64, 20, 0, 112, 0, 4, 108, 0, 0, 0, 4, 0, 42, 0, 0, 0, 32, 0, 0, 0, 0, 8, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]
It took 10.9596 seconds.
n is: 4, tau is: 2413, and we have: [23, 1]
n is: 5, tau is: 2413, and we have: [103, 9, 8]
n is: 6, tau is: 2413, and we have: [512, 62, 82, 34, 28, 2]
n is: 7, tau is: 2413, and we have: [2740, 402, 612, 384, 466, 94, 232, 42, 60, 8]
n is: 8, tau is: 2413, and we have: [15485, 2593, 4187, 3036, 4356, 1746, 3132, 1064, 1918, 909, 654, 333, 612, 144, 104, 22, 24, 1]
n is: 9, tau is: 2413, and we have: [91245, 16921, 28065, 21638, 33274, 17598, 31180, 12942, 24000, 14290, 15434, 7770, 15692, 5965, 6896, 3947, 5660, 2226, 3674, 1314, 1512, 516, 508, 204, 332, 37, 40]
n is: 10, tau is: 2413, and we have: [555662, 112196, 188514, 149946, 237128, 140954, 257686, 132874, 222776, 149894, 184050, 106012, 211448, 99394, 118316, 95636, 121084, 66468, 95314, 51880, 68562, 43284, 43446, 27110, 44888, 19814, 20422, 15206, 14496, 7502, 8876, 4222, 5374, 2376, 2390, 808, 2008, 274, 312, 76, 112, 10]
n is: 11, tau is: 2413, and we have: [3475090, 755920, 1278590, 1036826, 1658064, 1041598, 1933438, 1143020, 1880176, 1322744, 1709002, 1090862, 2112490, 1138532, 1462450, 1234316, 1556162, 989470, 1426682, 890202, 1244686, 861630, 962280, 676572, 1037130, 595502, 688432, 542620, 600072, 394014, 529312, 314892, 413768, 262686, 283214, 182652, 260852, 136382, 154338, 105060, 120560, 68362, 85002, 44736, 54548, 34494, 32444, 17900, 31096, 10350, 11190, 6468, 6804, 2534, 5160, 828, 1588, 364, 540, 64, 40]
It took 10.9555 seconds.
```
Runs all \$\tau\$s for \$n\in {4,5,\dots,11}\$ in under \$11\$ seconds per \$\tau\$.
Maybe able to increase that but need to rewrite how the permutations of \$\sigma\$ are generated for \$n=12\$. The above caches all the permutations but that blows up on my laptop for \$n=12\$ due to memory overload.
] |
[Question]
[
*This will turn into a series involving other aspects of calculus, including using the "derivative" of a string to find "stationary points" etc, as well as "integration" of sentences*
## Introduction
If y'all have ever studied calculus, you'll most likely know that differentiation is limited to differentiable functions.
Not that there's anything wrong with that, but have you ever wondered what it'd be like to take the first (or second) derivative of a word? Or how about a sentence? You probably haven't, so let me explain my theory of string based differentiation.
## The Basics
*If you already know how differentiation works, feel free to skip this part*
When being introduced to the concept of differential calculus, most beginners are taught about the concept of *differentiation from first principles*. This is based on the concept of finding the gradient of a tangent to a curve via the gradient formula:
$$
m = \frac{y\_2 - y\_1}{x\_2 - x\_1}
$$
On the tangent, we say that we have two points: \$(x, f(x))\$ and \$(x + h, f(x + h))\$, where \$h\$ is an infinitesimal number. Plugging this into the gradient formula gives:
$$
m = \frac{f(x+h)-f(x)}{x+h-x} = \frac{f(x+h) - f(x)}{h}
$$
In order to eliminate any inaccuracies from the tangent's gradient, we take the limit of the above equation as \$h\$ approaches `0`, giving us:
$$
\frac{d}{dx}(f(x)) = \lim\_{h\to 0}\left(\frac{f(x+h)-f(x)}{h}\right)
$$
Now, you may be asking "how on earth does that apply to string calculus? First-principles uses functions and numbers, not characters!"
Well, for this challenge, I've devised a slightly modified version of the first principles concept. The "formula" we'll be using is:
$$
\frac{d}{dx}(y) = \sum\_{h=-1}^{1}\left(h\left[y\left[x+h\right]-y\left[x\right]\right]\right) = y\left[x+1\right]-y\left[x-1\right]
$$
## The Formula Explained
One of the major differences here is that there is no longer a limit being taken of the equation. That's because it doesn't quite make sense having something approaching 0 for the whole string. Rather, we use a \$\sum\$ to inspect the characters to the left and right of the character in question.
Also, inside the sum, the first \$y\$ is now being multiplied by the \$h\$. This is to ensure that the result is balanced, as without it, the results weren't very reflective of the string.
To evaluate this formula for a certain index \$x\$, you:
* Evaluate \$-y[x-1] + y[x]\$
* Evaluate \$0\$
* Evaluate \$y[x+1] - y[x]\$
* Summate the above three items.
Essentially, you are calculating the following:
$$
y[x+1]-y[x-1]
$$
Note that when subtracting things, the ordinal values are used. E.g. `c - a` = `99 - 97` = 2
If any position becomes negative, it starts indexing from the back of the string (like python does). If any position becomes greater than the length of the string, the character is ignored.
## Applying Differentiation to the Whole String
By now, you may have noticed that the first principles formula only works on individual characters, rather than the whole string. So, in this section, we will develop a more generalised approach to using the formula.
To apply the formula to the whole string, we get the derivative of each character in the string, convert those numbers to characters based on code point conversion (like python's `chr()` function) and concatenate the results into a single string. Now, the problem here is that results may sometimes be negative. To solve this problem, we will introduce a second string to store information: the sign string.
This string will consist of a combination of any two letters of your choice, representing whether or not a character is positive.
## Worked Example
Let's take a look at what would happen with the word `Code`:
* We start at position `0` (`C`). The three parts for this character are `-(e + C)`, `0` and `o - c`. These evaluate to `-34`, `0` and `44`. The sum of these is `10` and the sign is `+`. So a newline is added to the main string, and a `+` is added to the sign string.
* We then move to position `1` (`o`). The three parts are: `-(o + C)`, `0` and `d - o`. These evaluate to `44`, `0` and `-11`. The sum of these is `33`, so a `!` is added to the main string and a `+` is added to the sign string.
* We then move to position `2` (`d`). The three parts are: `-(o + d)`, `0` and `e - d`. These evaluate to `-11`, `0` and `1`. The sum of these is `-10`, so a new line is added to the main string and a `-` is added to the sign string.
* We finally move to position `3` (`e`). The position `3 + 1` is longer than the length of the string, so therefore, the process ends.
Therefore, the final result is `["\n!\n", "++-"]`
## Test Cases
Format is `input`, newline, `output`. These test cases were generated using Python, and uses UTF-8.
```
Code
('\n!\n', 'ppn')
Code Golf
('\t!\nD\x1eO%\t', 'ppnnnppn')
Cgcc
('\x04 \x04', 'ppn')
Lyxal
('\r,\x18\x0c', 'ppnn')
3 - 3 = 0
('\x10\x06\x00\x06\x00\n\x00\r', 'nnpppppn')
Lim x -> 0
('9!I\x0b\x00K\x1e\r\x0e', 'ppnppnpnn')
lim x -> 0
('9\x01I\x0b\x00K\x1e\r\x0e', 'ppnppnpnn')
('', '')
afanfl;aknsf
('\x00\x00\x08\x05\x02+\x0b0\r\x08\x08', 'ppppnnnpppn')
nlejkgnserg
('\x05\t\x02\x06\x03\x03\x0c\t\x01\x02', 'pnnpnppnnp')
38492
('\x06\x01\x01\x02', 'pppn')
abcdefghijklmnopqrstuvwxy
('\x17\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02\x02', 'nppppppppppppppppppppppp')
KLJBFD
('\x08\x01\n\x04\x02', 'pnnnp')
::::::::::::
('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', 'ppppppppppp')
aaa
('\x00\x00', 'pp')
aaaaa
('\x00\x00\x00\x00', 'pppp')
```
## Rules
* Input will be restricted to printable ASCII
* You can use any codepage you like for the output, just so long as it is consistently used. This means that UTF-8, CP437, etc. are fair game.
* Input can be taken in any convenient and reasonable format
* Output can be given in any convenient and reasonable format. Suggested formats include: a list of both strings, each string on a newline, both strings joined together. It's up to you really how you want to output the result.
* Unicode sequences (like `\x00` or `\x05`) can be used in the output if wanted. In other words, both real representations and Unicode control sequences are valid output given they are applied consistently.
* You can use *any* two characters for the string sign. That's right! It doesn't have to be `+` and `-`... it could be `p` and `n` or `3` and `'`. It really doesn't matter as long as you use two distinct characters.
* For this challenge, `0` is considered positive.
+ Both full programs and functions are allowed.
## Scoring
Of course, this is code-golf, so the shortest answer wins!
## Reference Program
[Try it online!](https://tio.run/##XVC7bsMwDNz9FYQmKXGAPLYg2bN3KoIObkPbAgTKoGQg@XqXlVXZiAZB5N3xjhpesfd0mqYHthAsdQ51iCyPGgYfbLSezLkCOdHHxsEV9qlKV@sZerAE3FCHeneo4VjDIQsW0fYqtA1oz488/d7Dthh8GdjBClv6pkqTGOPINA@rqr@o7ehcpmc3xjC6KPmUSnWwHYW5LFntktUh/evFfB35KaK3n7CmoLYVwgX252wgqylSBUYXcA0N2X2VUNo/PevmO@jn24Izo571RTcNkiLqtLL69CPDR8oFN2RUxky/ "Python 3 – Try It Online")
## Special Thanks
I'd just like to say a huge thanks to @xnor and @FryAmTheEggman for showing me that my original model of string differentiation was not the best way of doing things. I'm much happier with this new method that you see here!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ǥš¥ü+Dd‚Äç
```
-1 byte thanks to *@ExpiredData*.
Uses I/O with UTF-8 encoding like the challenge description, and uses characters `\0` for negative and `\1` for 0 or positive. Outputs as a list of list of characters.
[Try it online](https://tio.run/##ASYA2f9vc2FiaWX//8OHwqTFocKlw7wrRGTigJrDhMOn/0r/Q29kZSEhIQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/8Pth5YcXXho6eE92i4pjxpmHW45vPy/l85/5/yUVC4QoeCen5PG5ZyenMzlU1mRmMNlrKCrYKxgq2DA5ZOZq1ChoGsHZOYgmIlpiXlpOdaJ2XnFaVx5OalZ2el5xalF6VzGFiaWRlyJSckpqWnpGZlZ2Tm5efkFhUXFJaVl5RWVXN4@Xk5uLlxWSIArMTERhIEkyC2KiooA) (the `J`oin is added to pretty-print the character-lists to strings, but feel free to remove it to see the actual output).
**Explanation:**
```
Ç # Convert the characters in the (implicit) input-string to their unicode values
# i.e. "Code!!!" → [67,111,100,101,33,33,33]
¤š # Prepend its own trailing item (without popping it)
# → [33,67,111,100,101,33,33,33]
¥ # Pop and push the deltas (forward differences) of this list
# → [34,44,-11,1,-68,0,0]
ü # For each overlapping pair of differences:
# → [[34,44],[44,-11],[-11,1],[1,-68],[-68,0],[0,0]]
+ # Sum them together
# → [78,33,-10,-67,-68,0]
D # Duplicate this list
d # Check for each whether it's >=0 (0 if negative; 1 if 0 or positive)
‚ # Pair those two lists together
# → [[78,33,-10,-67,-68,0],[1,1,0,0,0,1]]
Ä # Take the absolute value of each
# → [[78,33,10,67,68,0],[1,1,0,0,0,1]]
ç # And convert all integers to ASCII characters
# → [["N","!","\n","C","D","\0"],["\1","\1","\0","\0","\0","\1"]]
# (after which this pair of character-lists is output implicitly as result)
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 39 bytes
```
)**iRrtm{{0 2}sip^.-}~]Jm{0>=}j{abL[}\m
```
[Try it online!](https://tio.run/##Tca7DoIwGEDh/X@KrmIwBBy8BAYxmiCTK2pSoEWgLZeCYpr66iiTnuHLifuWEdn0ZGRCjTPDyM9tx5WykK1lXt8Wpn5fA64sz9WFwnEY6Qsf46GI5ppHsh79KiUwgY4Vo@BnSQLha8AMHGQiB7nIgjDnaECm9132W0yxoGyLSyEpCEaKMhOStBk4q@XaBhwnKaHZPS9KxkVVN63s@sdzeMEpDHaHPWz@Ajw1@QE "Burlesque – Try It Online")
```
)** # Map ord() on string
iR # Generate all rotations
rt # Rotate once to put deriv[0] to first pos
m{ # Map
{0 2}si # Take the 0th and 2nd chars (either side)
p^ # Push (un-array)
.- # Difference
}
~] # Discard last (i.e. deriv[-1])
J # Duplicate
m{0>=} # Create pos/neg list as 0,1
j # Swap
{
ab # Abs
L[ # Chr()
}\m # Map and concat to str
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
LŻịOI+Ɲµ>-,AỌ
```
[Try it online!](https://tio.run/##y0rNyan8/9/n6O6Hu7v9PbWPzT201U5Xx/Hh7p7/D3dvUTjc/qhpjYK/N5AEoiwQ1bhPRyHy/3/n/JRULhCh4J6fk8blnJ6czOVTWZGYw2WsoKtgrGCrYMDlk5mrUKGgawdk5iCYXIlpiXlpOdaJ2XnFaVx5OalZ2el5xalF6VzGFiaWRlyJSckpqWnpGZlZ2Tm5efkFhUXFJaVl5RWVXN4@Xk5uLlxWSIArMTERhBMTAQ "Jelly – Try It Online")
Uses `\0` and `\1` for the sign string, the Footer converts the output into code points to be clearer
## How it works
Just a refresher on Jelly's indexing rules: 1-indexed, wrapping modularly. That means that `0 ị “1234”` returns `4`.
```
LŻịOI+Ɲµ>-,AỌ - Main link. Takes a string s on the left
L - Length of s
Ż - [0, 1, 2, ..., len(s)]
O - Yield the code points of s
ị - Index into the code points with the range
This is equivalent to prepending the last character of s
I - Forward differences
+Ɲ - Sums of overlapping pairs
µ - Call these sums S and use as the left and right arguments
>- - Is each sum greater than -1?
A - Yield the absolute values of each sum
, - Pair
Ọ - Convert to characters
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
≔E⊖Lθ⁻℅§θ⊕ι℅§θ⊖ιθ⟦⭆θ‹ι⁰⭆θ℅↔ι
```
[Try it online!](https://tio.run/##bc6xCsIwEAbg3afIeIEK7p1KBSm0KDiKQ0zONhAvNrmKbx8TFxWcbrjv/@/0pIL2yqXUxGhHgkHdYYs64A2J0UCPNPIEs5SVGCwtEfbBWFIOGu7I4BPmSnT0CVhZ6B/03VpQVrOsV4dgieF05DzHcj3THmMEW4lNQT@bNv@rNGOA5hK9WxjfXWdZp9R6g2Ln3XWV1g/3Ag "Charcoal – Try It Online") Link is to verbose version of code. Outputs the signs first (`0=+,1=-`) as otherwise the default print format will mangle the newlines. Explanation:
```
≔E⊖Lθ⁻℅§θ⊕ι℅§θ⊖ιθ
```
Compute the pairs of ordinal differences, excluding the last pair (which in Charcoal would normally wrap around to `0`).
```
⟦⭆θ‹ι⁰⭆θ℅↔ι
```
Print the signs of the differences and the characters of the absolute values of the differences.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~119~~ \$\cdots\$ ~~92~~ 91 bytes
Saved 6 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!!!
Added 6 bytes to handle empty string input.
```
lambda s:zip(*[(chr(abs(S)),S<0)for S in(ord(s[i+1])-ord(s[i-1])for i in range(len(s)-1))])
```
[Try it online!](https://tio.run/##1VVLc5swEL77V6jMdCwlMANxkjpu6aHNpNMmMzm4N9sHGQQmxoIKucX1@Lc7EsiEp9O0h0w56Fs9dvdb7S6KN3wR0cHes6f7EK/mLgbJ6HcQw5MJdBYM4nkCxwjp4w8m8iIGxiCgMGIuTCbBqTVDhpINIcv9QOwDhqlPYEgoTJBhITRDe2Zvv7M1GWk40XRwg8NEyDTiQMx3PanJScJ1ksbE4dIG7EHtc@QScRrC/pT2ddB/IwchIrGWmVCWdCBtI0FTKYEvUegpTV7WFON1JqYWkXgvh7fZCu8wWx273fqOozym5rm0CHJHYnKU790mxaHSZFJFVwSHSt85SkxZGQADDIANzAMHy1Tqlwrb57QyY5mr7nhboRxLsAIpMD4eaFwVd/9V@ZmX/d2WU5EHL7ZIZ7xH1hoXErZREdatV2EjOeQS9jD1wvd4SROvqBezlqND6i8Unkk8LZM2KySHBTbJvqyimzmlIXlY@jQhzC/4XqiOKbErVdaghk7ltFVolbi2EOq@5NLOofqH51dnBbvLmqdWj53x4rnjEs9fBA/LcEWj@AdL@Prnr3RTdNa7Wtz/Dz519x/09WuCysXt3bdPN9dFYoeVhNLi//pMQTXrZVT6Opvw3/G5Zvy7S8EYt3Cu@3o63Hr8ZVQzY2jUA@KLWUA59LSptpVP9m6qyb/slq/jkMDJiQflqnjyd2DLJo1V286f@NkO5AJxNdTbPwI "Python 3 – Try It Online")
Outputs a sequence of: a tuple of characters and a tuple of `True`/`False` for negative/positive values.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~87~~ ~~85~~ 82 bytes
```
->s{d=n='';i=0;loop{k=s[i+=1].ord-s[i-2].ord;n+="++-"[k<=>0];d<<k.abs}rescue[d,n]}
```
[Try it online!](https://tio.run/##TcbNToNAFEDh/X2Km8akCxxCiwsVhoVtNFHeAIkZ5gfoDDPIFAtp@uxY3ehZnHzDWM2Lou8LyfxZUEvX66SlUWKc68@a@qIN6KYM3SDI1WT7y8QGdBUEZFXolGZRmYg01SGr/GWQno@yELe2vCynpjUSa3n0gNijKm4@Qt64ri9BWrHsnJDwM3xxRsGu5hzyeWIGYiQYI8UI8rbDCUl2pfkjMMWsMgnT1iuwRh50bb0caojv7x62wCoupKqb9qBNZ13/Ofjj@HWaZnjLX5@e9/D4L2CMfQM "Ruby – Try It Online")
] |
[Question]
[
\$T(n, k)\$ gives the number of permutations of length \$n\$ with up to \$k\$ [inversions](https://en.wikipedia.org/wiki/Inversion_(discrete_mathematics)). This values grows very quickly, for example for \$T(20, 100) = 1551417550117463564\$.
The maximum number of inversions possible is \$n\frac{n-1}{2}\$ so for \$k = n\frac{n-1}{2}\$ we know that \$T(n, k) = n!\$.
To make this task more interesting, and to allow for a wider variety of possible answers you will only have to compute \$T(n, k)\$ approximately.
# Examples:
For \$n = 3\$ and \$k\$ from \$0…3\$:
```
0.167, 0.5, 0.833, 1.0
```
For \$n = 4\$ and \$k\$ from \$0…6\$:
```
0.042, 0.167, 0.375, 0.625, 0.833, 0.958, 1.0
```
For \$n = 5\$ and \$k\$ from \$0…10\$:
```
0.008, 0.042, 0.117, 0.242, 0.408, 0.592, 0.758, 0.883, 0.958, 0.992, 1.0
```
For \$n = 50\$ and \$k\$ from \$0…1225\$:
```
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.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0.004, 0.005, 0.005, 0.005, 0.005, 0.006, 0.006, 0.006, 0.006, 0.007, 0.007, 0.007, 0.008, 0.008, 0.008, 0.009, 0.009, 0.01, 0.01, 0.011, 0.011, 0.012, 0.012, 0.013, 0.013, 0.014, 0.015, 0.015, 0.016, 0.017, 0.017, 0.018, 0.019, 0.02, 0.02, 0.021, 0.022, 0.023, 0.024, 0.025, 0.026, 0.027, 0.028, 0.029, 0.03, 0.032, 0.033, 0.034, 0.035, 0.037, 0.038, 0.039, 0.041, 0.042, 0.044, 0.046, 0.047, 0.049, 0.051, 0.052, 0.054, 0.056, 0.058, 0.06, 0.062, 0.064, 0.066, 0.069, 0.071, 0.073, 0.075, 0.078, 0.08, 0.083, 0.085, 0.088, 0.091, 0.094, 0.096, 0.099, 0.102, 0.105, 0.108, 0.112, 0.115, 0.118, 0.121, 0.125, 0.128, 0.132, 0.136, 0.139, 0.143, 0.147, 0.151, 0.155, 0.159, 0.163, 0.167, 0.171, 0.175, 0.18, 0.184, 0.189, 0.193, 0.198, 0.202, 0.207, 0.212, 0.217, 0.222, 0.227, 0.232, 0.237, 0.242, 0.247, 0.253, 0.258, 0.263, 0.269, 0.274, 0.28, 0.286, 0.291, 0.297, 0.303, 0.309, 0.315, 0.321, 0.327, 0.333, 0.339, 0.345, 0.351, 0.357, 0.363, 0.37, 0.376, 0.382, 0.389, 0.395, 0.401, 0.408, 0.414, 0.421, 0.427, 0.434, 0.44, 0.447, 0.454, 0.46, 0.467, 0.473, 0.48, 0.487, 0.493, 0.5, 0.507, 0.513, 0.52, 0.527, 0.533, 0.54, 0.546, 0.553, 0.56, 0.566, 0.573, 0.579, 0.586, 0.592, 0.599, 0.605, 0.611, 0.618, 0.624, 0.63, 0.637, 0.643, 0.649, 0.655, 0.661, 0.667, 0.673, 0.679, 0.685, 0.691, 0.697, 0.703, 0.709, 0.714, 0.72, 0.726, 0.731, 0.737, 0.742, 0.747, 0.753, 0.758, 0.763, 0.768, 0.773, 0.778, 0.783, 0.788, 0.793, 0.798, 0.802, 0.807, 0.811, 0.816, 0.82, 0.825, 0.829, 0.833, 0.837, 0.841, 0.845, 0.849, 0.853, 0.857, 0.861, 0.864, 0.868, 0.872, 0.875, 0.879, 0.882, 0.885, 0.888, 0.892, 0.895, 0.898, 0.901, 0.904, 0.906, 0.909, 0.912, 0.915, 0.917, 0.92, 0.922, 0.925, 0.927, 0.929, 0.931, 0.934, 0.936, 0.938, 0.94, 0.942, 0.944, 0.946, 0.948, 0.949, 0.951, 0.953, 0.954, 0.956, 0.958, 0.959, 0.961, 0.962, 0.963, 0.965, 0.966, 0.967, 0.968, 0.97, 0.971, 0.972, 0.973, 0.974, 0.975, 0.976, 0.977, 0.978, 0.979, 0.98, 0.98, 0.981, 0.982, 0.983, 0.983, 0.984, 0.985, 0.985, 0.986, 0.987, 0.987, 0.988, 0.988, 0.989, 0.989, 0.99, 0.99, 0.991, 0.991, 0.992, 0.992, 0.992, 0.993, 0.993, 0.993, 0.994, 0.994, 0.994, 0.994, 0.995, 0.995, 0.995, 0.995, 0.996, 0.996, 0.996, 0.996, 0.997, 0.997, 0.997, 0.997, 0.997, 0.997, 0.997, 0.998, 0.998, 0.998, 0.998, 0.998, 0.998, 0.998, 0.998, 0.998, 0.999, 0.999, 0.999, 0.999, 0.999, 0.999, 0.999, 0.999, 0.999, 0.999, 0.999, 0.999, 0.999, 0.999, 0.999, 0.999, 0.999, 0.999, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0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0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0
```
# Input:
One value: \$n\$.
# Output:
\$\frac{T(n,\lfloor n^2/4 \rfloor)}{n!}\$ rounded to three decimal places. \$T(n, k)\$ is defined by OEIS sequence [A161169](https://oeis.org/A161169).
# Sample input and output
```
n = 3. Output: 0.833
n = 6. Output: 0.765
n = 9. Output: 0.694
n = 12. Output: 0.681
n = 15. Output: 0.651
n = 18. Output: 0.646
n = 50. Output: 0.586
n = 100. Output: 0.56
n = 150. Output: 0.549
n = 200. Output: 0.542
n = 250. Output: 0.538
n = 300. Output: 0.535
```
Your code should be correct no matter what values of \$n\$ and \$k\$ are given but will only be tested on \$k = \lfloor n^2/4 \rfloor \$. Your output must be within \$0.001\$ of the correct value.
# Score
I will run your code on my machine: 8GB RAM, AMD FX(tm)-8350 Eight-Core Processor running Ubuntu 16.04.6 LTS.
I will test for \$n = 50, 100, 150, 200, 250, 300, 350, 400, ...\$ until it no longer completes in 10 seconds. I will also limit the RAM used to 6GB using <https://github.com/pshved/timeout>.
Your score is the highest \$n\$ your code can reach on my computer within the time limit. If there is a tie, the first answer wins.
# Notes
Your code does not need to be deterministic. That is random sampling methods are allowed as long as they give the right answer at least 9 times out of the first 10 times I test them.
[Answer]
# Python 3 + SciPy, score ≈ 1.86 · 10103
\$T(n, k)\$ approaches the normal distribution quickly enough that we can just compute it exactly for \$n < 97\$ and use the CDF of the normal distribution for \$n \ge 97\$. This solution runs in effectively constant time. (Technically, for \$n > 1.86 \cdot 10^{103}\$ the numbers start being too large to convert to `float` and we start getting `OverflowError`. This hardly matters because the answer is `0.500` for \$n > 1500000\$ or so.)
```
import sys
import numpy as np
from scipy.special import erfc
n = int(sys.argv[1])
k = n * n // 4
if n < 97:
a = np.array([1])
for i in range(1, n + 1):
a = np.cumsum((np.r_[a, np.ones(i)] - np.r_[np.zeros(i), a])[:-1] / i)
out = a[k]
else:
mean = n * (n - 1) / 4
variance = n * (n - 1) * (2 * n + 5) / 72
out = erfc((mean - k - 0.5) / np.sqrt(2 * variance)) / 2
print("%.3f" % (out,))
```
[Try it online!](https://tio.run/##XVDtasMwDPzvpxCFgr3mOxtlZXuSEIYJTmtSf0xOCtnLZ3KSQZlB5rjTnWT7ebw5Wy@LNt7hCGEObId2Mn4GGcB61qMzEDrt5yx41Wl5h71LYd8xZuETtB052TOJ10dTtoINRFp4ocpzeGVM9wQ/4P18YUBHRtlTO8qZr4bI9g5BUxagtFfFy4Q8JyjF5nnydZMJk@GcIH41MomcsypwLVpIYaPp/lHoIpmAbEVzScsWctDbMDeNFCaboWXqHtQ2wyhp9825paRSQFw/Sg@JWtpO/ZMJVes7T/AWm8/VU3r8IM7X0BQGqiJbm2i18I3j6vzLFVGoGPMYP/NwzOr@AEfglJQIsSxLXRS/ "Python 3 – Try It Online")
[Answer]
# Rust
Port of [@Anders Kaseorg's Python answer](https://codegolf.stackexchange.com/a/194159/110802) in Rust.
### `/src/main.rs`
```
use std::{cmp, env, f64, sync::mpsc, thread, time::Duration};
use statrs::{
function::erf::erfc,
distribution::{Normal, Univariate},
};
use ndarray::{Array, Array1, Axis, stack, concatenate, s, prelude::*};
use ndarray_stats::QuantileExt;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("Please provide a command line argument 'n'.");
return;
}
let n: usize = match args[1].parse() {
Ok(val) => val,
Err(_) => {
println!("Invalid argument. Please provide an integer.");
return;
}
};
let k = n * n / 4;
let mut out = 0.0;
if n < 97 {
let mut a = Array1::<f64>::from_elem(1, 1.0);
for i in 1..n + 1 {
let ones = Array1::<f64>::from_elem(i, 1.0);
let zeros = Array1::<f64>::from_elem(i, 0.0);
let a_extended = concatenate(Axis(0), &[a.view(), ones.view()]).unwrap();
let zeros_extended = concatenate(Axis(0), &[zeros.view(), a.view()]).unwrap();
let mut a_diff = &a_extended - &zeros_extended;
a_diff = a_diff.slice(s![..-1]).to_owned();
a_diff = a_diff / (i as f64);
let cumsum = |x: &Array1<f64>| {
let mut sum = 0.0;
x.mapv(|val| {
sum += val;
sum
})
};
a = cumsum(&a_diff);
}
out = a[cmp::min(k, a.len() - 1)];
} else {
let mean = n as f64 * (n as f64 - 1.0) / 4.0;
let variance = n as f64 * (n as f64 - 1.0) * (2.0 * n as f64 + 5.0) / 72.0;
// println!("{:.3} {:.3}",mean,variance);
out = erfc((mean - k as f64 - 0.5) / f64::sqrt(2.0 * variance)) / 2.0;
}
println!("{:.3}", out);
}
```
### `Cargo.toml`
```
[package]
name = "rust_hello"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
# rand = "0.8.0"
# hyper = "0.13"
# tokio = { version = "0.2", features = ["full"] }
# rayon = "1.5.1"
ndarray = "0.15.4"
statrs = "0.13.0"
ndarray-stats = "0.4.0"
```
### Building and running
```
# win10 environment
$ cargo build
$ target\debug\rust_hello.exe 500
$ target\debug\rust_hello.exe 100
$ target\debug\rust_hello.exe 18
```
] |
[Question]
[
In the [original Shantae game](https://en.wikipedia.org/wiki/Shantae_(video_game)), there are transformation dances that you have to input in time using the D-Pad, A, and B. If you complete a predefined sequence while dancing, you will transform into the corresponding form (or teleport or heal). Your task is to output the corresponding effect when given an input. The catch is that you may get extraneous dance moves in the input, both before and after, and there may not even be a dance in the input.
# The Dances
Using `UDLRAB` for dance moves:
* Monkey: `DR`
* Elephant: `DL`
* Spider: `DA`
* Harpy: `DB`
* Tinkerbat: `DUU`
* Heal: `DUA`
* Scuttle Town: `DULR`
* Water Town: `DURLAB`
* Oasis Town: `DURRBA`
* Zombie Caravan: `DULLBA`
* Bandit Town: `DUBLBR`
# Coding
Input: a sequence of dance moves. This can contain Up, Down, Left, Right, B, A, and Wait values. Use any convenient encoding.
Output: a value corresponding to the first matching dance in the sequence or a distinct value if there is no match. You can encode this in any convenient way.
# Examples
Using `.` for waiting:
* `DR` → Monkey
* `UUU.DLUAB` → Elephant
* `L.DDBALL` → Harpy
* `LRLRDURURLAB` → *No match*
* `DUBLBR` → Bandit Town
* `DURLBA` → *No match*
* `DDUDR` → Monkey
* `RLAB` → *No match*
* `.DUUBBB` → Tinkerbat
* `DADRDL` → Spider
* `.DURRBADR` → Oasis Town
* `DURR.BA` → *No match*
# Other Rules/Notes
* Standard rules on loopholes and IO methods apply
* Describe your encoding for dance moves and matching dances.
* There may be more than one dance in the input. If that is the case, match only the first one that appears in the input.
* Waiting interrupts dances.
[Answer]
# JavaScript (ES6), ~~92 88 61~~ 59 bytes
*Saved 2 bytes thanks to a suggestion from @tsh*
Expects `UdLRAB` for the dance moves and `.` for waiting. Outputs either *undefined* if there's no match, or the sequence of the matching dance (e.g. `dR` for Monkey or `dURLAB` for Water Town).
```
s=>(/d([A-R]|U(U|A|LR|RLAB|RRBA|LLBA|BLBR))/.exec(s)||0)[0]
```
[Try it online!](https://tio.run/##bZG9asMwGEX3PIXQJA2xsxcHJCh0UFv4Gk0hg@pPady6lrFEf0Dv7tr1Xx2qQSDu5XIOejUfxudNUYdt5dC256z12Z6lyI5iC6eomY4iKoighIwAsnuo7pJKAudpYr9szjyPccePu1MbrA8kI55ke5K7yrvSJqV7Yeeuw282mz5nFIGS@XBC0pTcu@rNfo@51jpBpYWkc35b2vpiqjA2VIIohVJ0WbgzTT0NKFCAGnQPTYf4wZF3E/LLhKB7A/oXQZoKi0AO7rOaS9C5rkrXM6gXmX9MfgHWplcLCWot5VgaGoeiW2iezSSLAgHVCuOpLtA2y0T/MQPIkD8aX/grFUgmlzVI@wM "JavaScript (Node.js) – Try It Online")
or [Try it with enhanced output](https://tio.run/##bVJfa4MwHHzvp/jhiwqr9nmjBTMGhWXryBoGK31ITbq6WS2a/WPZZ@8SY7SW5UHw7pfL3SWv7IPVaZUd5LgouThup8d6OgtiHqySMVkrGlCVKEwUwQlShCD9g/UHYUTCMI7El0iDOlRqEq4m6yNeLG7pA0zhZwTgc@KDXpfg35XFm/j2LxoUO/QmF4cdK2SLJw5/PGRcVC2KHDpn1cFJUOpbcJlp4WrDnAZNWmIuWO4wbHwY3fRdylzAsvwsHGdy@Zp7YlJUQ0aHNcyC1Vk9YEwDhnku95tMwDWrdIsda6oxLGIFz6TdOPodjaSopW6mhukM0rKoy1xEefkS2M5WW13jGpQC/76EPZPpzg@v7K7A48SDboUAcQy20panlEYc0wR5He/KbSdwxDlKMPZ6haZQRxNMdOSmDs/Szoaz0ATzTi2cJOyGiO5mMHQuw2kf5p8kjYFh0jOFSN8@Qu2QnehegTsk4YTjgQ37pnoJc7vWiOX7W@6jkMhlGRo5/gE)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~179~~ ~~164~~ ~~153~~ ~~148~~ ~~137~~ 115 bytes
```
d=>{for(;d;d=d.slice(1))for(z of "R.L.A.B.UU.UA.ULR.URLAB.URRBA.ULLBA.UBLBR".split`.`)if(!d.search('D'+z))return z}
```
[Try it online!](https://tio.run/##lVRdb9MwFH3Gv8LLS5O189ZtjI0SpIQg8RAYyhYhMSHhJU5ryJwocRjb1Fd@AD@RPzLudZqmLHyIl64@99xzj@/x@ol/4XVSyVLvqCIV97vbZI/SHfq6UJ/FzVMaRGSK55e5KBdcaUBCso/IWSlTUcHZIwd4fsWrEht8cojHcwkC1SXHjjgmjw1F8ByPHjkyCkmjdS7oeXGtEA4j8gTxd1yLao1GoeeTY8RPeS3rHo98j5wg/r64upSCvuAVXKZVCqE23YOaz1Uq9brJD/2IbO8Skrn3qfv8Lisqe5bOUjdldS4TYU8dB7FbWmTUiljIPOazOGaxx8AfM26Ymc3MFGYkLVaXudQf2UdHZvYWiAleJQt7FIzGt45TCd1Uit4ucb1BRH98@75aMIlBOwhjzzdgt2USsiDwvTA0qNksCaMwgk0aBwZ@U9ArrpMFaa9lsI3rElyd7z2gBvGv84dqDIb4fguuQySBF0RBa6cNHnm4hpVcnw3OjdjDwWbnjUq0LBSdC33aaFs1Vw69I49W6/nvddsjNnIuQOXDjCwJ0aLWNXXpBbmDrK0gsiYUxpQNPMHVxD1nOWmr670PSdM1qUthyDnoOSaWyDjd4DUqFZlUIu14bUi/mdZ7MuH8zfS/ZqyiG0oc9jNMjkPGvrMh0uY6JB33Mm3GfzADefRhV295ate6mlBp0pYZxSN1XbdvcqiBqLVGrFlL1TelKDLscOgWtFjwTaq51XXAJ9PFmQFtB5quFzIXyGe5UHO9oM9wMJLH0E1Rd/XgADMPJylUXeSC5cXcNm4tBRebHjuT1rxVibrJdYdZINNVxNdSJBrcdrWS1zUcwcimquVarBKl4JD3yXh6PN4fw98jB2j4a5MLTfH14o@OecWrfwt8zZmNCFN4tYHRtrTpFZqGNg2tDarjorZLNwqgv7z/CQ "JavaScript (Node.js) – Try It Online")
*-11 bytes thanks to Arnauld's answer making me realize output can be simplified*
*-8 bytes thanks to flawr in chat helping me golf array empty checks*
*-12 bytes thanks to Shaggy*
Takes input as a string in same formatting as OP test cases.
Outputs the matched dance string minus the leading `D` for a match, or `undefined` for no match.
The integer corresponds to the match's index in this array (0-indexed):
```
0 - Monkey: DR
1 - Elephant: DL
2 - Spider: DA
3 - Harpy: DB
4 - Tinkerbat: DUU
5 - Heal: DUA
6 - Scuttle Town: DULR
7 - Water Town: DURLAB
8 - Oasis Town: DURRBA
9 - Zombie Caravan: DULLBA
10 - Bandit Town: DUBLBR
```
Probably room for golfing, especially in compressing the dance move set.
## Explanation
### General approach
Iterate through the input string, removing the first character each time and checking if the resulting string starts with a valid dance string.
The whole thing is just a for loop inside a for loop, I'll break it down into 3 parts:
- Condition
- Inner Loop
- Outer Post
### Condition
This is the termination condition for the outer loop, IE while this is true, keep looping.
Quite simple:
```
d
```
`d` is a string, in JS empty strings are falsey "`d` is not empty".
### Inner Loop
This is the stuff that happens each loop:
```
for(z of "R.L.A.B.UU.UA.ULR.URLAB.URRBA.ULLBA.UBLBR".split`.`)
```
So first we define an array with:
```
"R.L.A.B.UU.UA.ULR.URLAB.URRBA.ULLBA.UBLBR".split`.`
```
This creates an array of all dance move strings, missing the `D` at the start of each of them (They all begin with `D`). We'll call this array `x`
There's probably significant golfing potential here.
We then iterate through each item in `x` (stored in `z`), and run the following:
```
if(!d.search('D'+z))return z
```
This uses `d.search` to return the index in the string of `'D'+z`. If and only if `d` *begins* with `'D'+z`, this will return `0`, which is a falsey value in JS.
As such, `!d.search` will *only* be true when the string starts with `'D'+z`.
*Note: This is why we omit the `D`s in `x`, as it saves us 10 bytes (1 per dance), and only costs us a single byte in this search*
Then, if the search matches, we return `z`. This is the dance we've found, without the leading `D`.
If not, we keep looping.
### Outer Post
This is stuff that happens at the *end* of each iteration of the outer loop:
```
d=d.slice(1)
```
Just remove the first character from `d`
### No Match
If `d` becomes empty and no match has been found, the end of the function is reached. This implicitly returns `undefined` as per standard JavaScript behavior
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~53~~ ~~43~~ ~~42~~ 37 bytes
```
0L`;\w|;:(:|A|LR|RLAB|RRBA|LLBA|BLBR)
```
[Try it online!](https://tio.run/##PY9BSwMxEIXv8yv2oFAvi71mTolIe5gqTAuCiHTaBhrcZpc0WoT893WyVS8hefPmvS/J5xBlPt7OFtvxnrb4diloZqbYQlyYrCvMTh@khyPHd@P7DTz1zUny/gjIsOrjh/8GJHjs/HCUmAEtrIdw8AnQwVLSoGNjYBPUmXaiBmNh6aXTCzGs9585d77Z9JeoSi2FF8k@/StKAM9yDuc/peLAa3/aBd88SJIvqWrlAyfxEPJkHBXPGNMiGY2kFtFZIiAm1tBr0e9WrdVIRKM706BVZOfUYJH1c@0VAycrt87@AA "Retina – Try It Online")
Slightly deviates from the standard input and output to make use of `;:` as `DU` respectively. Inspiration from [tsh](https://codegolf.stackexchange.com/users/44718/tsh), saving 5 bytes.
Matches the first dance and outputs it, after seeing [Arnauld's answer](https://codegolf.stackexchange.com/a/185026/31625). Saved 10 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) suggesting using the list stage `L` and limiting the output to the first match. Saved one byte thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh) shortening the regex.
The header and footer just allow for multiple inputs and making the output readable, respectively.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 47 bytes
```
/D([RLAB]|U(U|A|LR|LLBA|RLAB|RRBA|BLBR))/;$_=$&
```
[Try it online!](https://tio.run/##ZY/BSgMxEIbveYo9FGkPbk89SQ8ZRvAwKoydUykS7UKDaxJ2A6WQcx@gj@iDmG62Ilhvw8fP//0Tmq5d5DzH6ZpJwybJVJJOxIkIdCosMQ8XEPBsNr@bvC4nNzkjV1/HU/Xo3UdzUCJSI4mGEd63TdgZFxXViKCJRvpgunBQxMQoLKV4xE@@@jTxfadQimJkYNzWxmrl927APAy5iqL89f9vq1EE4AJXdgh1byYq1Mh4mfMS7LbpSq6891P3bHrb/3q5vhJ/@xCtd32@De0Z "Perl 5 – Try It Online")
Returns the dance's code (allowed as per @Arnauld's comment) or blank if no match.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes
```
≔⌊E⁺D⪪”{➙∧⪫⁻Y⟧¹⊟AOP9GKπ⁸Pa↷VB”D⟦⌕⁺θιιLι⟧η✂θ§η⁰Ση
```
[Try it online!](https://tio.run/##LY7BCoMwEETv/YrgKQtp6d1TZCkUIkgkp9KDqJiFmFqNpX@fJtjDLAy82Znedmv/6lyMctto8rwmT/M@87pbeOP2jRdYCNYujgIvNCqUWKExaCQapdFoJZPXuspe5VupSqdIygEI9riRH45Pb8EIDqnRT8FygmdmLJSnZiUfeOuoHzMow90P45dbwa6JaNMiCwBljJd/m47nj/sB "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⁺D⪪”{➙∧⪫⁻Y⟧¹⊟AOP9GKπ⁸Pa↷VB”D
```
Split the compressed string `RDLDADBDUUDUADULRDURLABDURRBADULLBADUBLBR` (which contains all of the dances except for the leading `D`) on `D`, and then prefix the `D` back to each entry.
```
E...⟦⌕⁺θιιLι⟧
```
For each dance, concatenate it to the input and find the first position of the dance in the concatenation, plus also take the length of the dance. For dances that weren't found this means that the result will be the length of the input string instead of `-1`.
```
≔⌊...η
```
Take the minimum of those results, i.e. the position and length of the dance that appeared first.
```
✂θ§η⁰Ση
```
Extract that dance from the original string.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~33~~ 28 bytes
```
“¡ịḟ½NỵC\HỤĊȷṗ~’b6ṣ0;€0ɓUwⱮM
```
[Try it online!](https://tio.run/##vU8xS8NAGN39FTcUUYySJmkRAtZaUYfWQeggtYvoUrIXF0mCGKiDg4MWLBosTkW0UOw1tsKlBpt/8d0fide7Rs3qIHzDd@@97713tWPDOIkiat4SF7wL6N@R4S54vcLBDnjtcePzFfD1KTWbh1nAD7JO7Y48uSrX6ctTKapRsyXp7BYtryG2676jU2uEFnRmxeDy3kYxv7LJmFRSJRNcZJ6pnNARN3CohfNLk8eiP/JHgRPaoX1ErTetkJv/MEurgM9rQStoAnZgcEmtPhkCvq@Tnh7csMt1g7xvkQ4CfLZdGD@P3dCGgUs86HdJO@iy8NbinO@w8vt/L/0vXRu8a1SpyBJSqhKqpCUkJishhml8z0hInZJaDLNROcwQbcYo/KVwMs2XdAzG94JROabOAuVfuqnnDBNw3Cppk41pYab@uGfEiaiekCp81G9JIlrh/@Lp1S8 "Jelly – Try It Online")
Takes as input a list of integers representing the moves:
```
0 D
1 U
2 R
3 B
4 L
5 A
6 .
```
Returns a wrapped integer for the answer, or a list of all these integers for no match:
```
1 Monkey
2 Harpy
3 Elephant
4 Spider
5 Tinkerbat
6 Heal
7 ScuttleTown
8 OasisTown
9 WaterTown
10 BanditTown
11 ZombieCaravan
1,2,3,4,5,6,7,8,9,10,11 NoMatch
```
TIO link includes code in the footer to translate these back to the strings in the question, but is not needed for the program to function using the integers specified here.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 104 bytes
```
'dð.•—Áå•«•¼L?D/8¢Am.Z¼ž•6BSèJ#«å.•g³ç¼…¬ÿ¬Õ‚YÙ•“ÆÚàæɾ ÿ“#.•664Îè¡HĆ∍•¸«“scuttle„©Ê´ bandit“#ð“‰à“«««sÏ
```
[Try it online!](https://tio.run/##HY2xCsJAEER/RbCwi40EO1EsROystEuMSCAqmNifjaigNlooIjGQGIlFQAuLYGBHf@R@JN7J7s4uA29nbGu62c@ygoFY4czjbIcZfHFRJCVpVerFMnnVodKl5PsWnlprI2zmKYIviQE9cKWEs4DuSMXsOTt2cPg/O2GOI1wEWNI7h1Q4eQmpagkbhHRpfOZ8sZZJLxl4sntTx7H6nJ3phhU9c7o2MkxHcoiFchbDFZsiWTa2WWZMFNmWYkwtS9d@ "05AB1E – Try It Online")
---
I wrote this monstrosity without realizing I could use numbers for name moves...
[Answer]
# [sfk](http://stahlworks.com/dev/swiss-file-knife.html), ~~119~~ 91 bytes
```
xex -i -firsthit
_DR_
_DL_
_DA_
_DB_
_DUU_
_DUA_
_DULR_
_DURLAB_
_DURRBA_
_DULLBA_
_DUBLBR_
```
[Try it online!](https://tio.run/##K07L/v@/IrVCQTdTQTcts6i4JCOzhCveJSgeSPiACEcQ4QQiQkPBJFgg1AesIjTIxxEiFxTkBJXwgTKcfJyC4v//14PIuQQBAA "sfk – Try It Online")
Gives the first dance present as a sequence of moves.
(`xex` is just a stream editor, and in this case `_<pattern>_` is search text)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~28~~ 27 bytes
Saved 1 byte thanks to *Grimy*
```
Œ.Δ•1Λ*#$ß‘«∍@…9\÷•6B1¡1ìQZ
```
[Try it online!](https://tio.run/##HYutDgIxEIR9XwMUIWRnu9sERxDnsQQDCQKFQJNUYjDkBAmCHAIDHn8N9h6iL1L2UPPzzewP681uW8BV@V4mXZ3jA91tNBime47X9pVP51mOz@kqfQyFOdoG6b1YluO4gJyqBrB6cRwA8cyOiQlKSmwtVFjIhFi8A9Q@fxCgKmIDDwL3kUjM91MK4n8 "05AB1E – Try It Online")
Outputs either the match (i.e. `10` for Monkey) or `-1` for no match
```
1 = D
0 = R
2 = L
3 = A
4 = B
5 = U
6 = .
```
**Explanation**
```
Œ.Δ # Find the first substring of the input
Q # that is equal to
Z # any element in
•1Λ*#$ß‘«∍@…9\÷• # 29058694378496950170872579685936
6B # converted to base-6
1¡ # split on 1's
1ì # with a 1 prepended to each
```
] |
[Question]
[
## Background
Inspired by [a now deleted question](https://codegolf.stackexchange.com/q/178464/43319) by [John Burger](https://codegolf.stackexchange.com/users/84859/john-burger) from which I quote:
>
> [](https://i.stack.imgur.com/QpCOt.png)
>
>
> Now obviously no human made this mistake. It's a mis-decode of something - perhaps the ISBN? My question is: does anyone know of an existing algorithm that was so messed up it would invent an entirely new calendar?
>
>
>
[TFeld](https://codegolf.stackexchange.com/users/38592/tfeld) ingeniously [commented](https://codegolf.stackexchange.com/questions/178464/what-date-encoding-could-this-be#comment430181_178464):
>
> It seems that the book was published on `2008-09-16`, so maybe it was somehow read as `00809162` -> `00=dec?`, `80`, `9162`
>
>
>
### Task
Given a date represented as a three-element list, answer with the corresponding three-element mis-decoded list.
Mis-decoding happens as follows (example for `[2008,9,16]` in parentheses):
1. Join the digits of the year, month, and day, inserting leading zeros as necessary (`"20080916"`)
2. Move the first digit to the end (`"00809162"`)
3. Split the eight digits into groups of two, two, and four (`"00","80","9162"`)
4. Interpret them as numbers (`[0,80,9162]`)
5. Normalise the month number by wrapping 0 around to 12, and wrapping 13 around to 1, 14 to 2, 15 to 3, …, 25 to 1 etc. (`[12,80,9162]`)
6. Rearrange the list to get the original order (`[9162,12,80]`)
* You may take the original date in any order, but your answer must use the same order. Please state any non-default order.
* The given year will always have four digits, but dates in October will lead to a three- or two-digit answer year.
* You may take a list of strings or a character-delimited string, but it may not include leading zeros and you must answer in the same format and again without leading zeros.
## Examples
`[1700,1,1]` → `[1011,10,0]`
`[1920,4,29]` → `[4291,8,0]`
`[1966,11,27]` → `[1271,12,61]`
`[1996,12,13]` → `[2131,3,61]`
`[2008,9,1]` → `[9012,12,80]`
`[2008,9,16]` → `[9162,12,80]`
`[1010,10,1]` → `[11,1,1]`
[Answer]
# [Python 2](https://docs.python.org/2/), ~~95~~ ~~67~~ ~~66~~ ~~65~~ 64 bytes
```
lambda y,m,d,t=10,T=1000:(m%t*T+d*t+y/T,y%T/t%12or 12,y%t*t+m/t)
```
[Try it online!](https://tio.run/##bc9LCoNADAbgvacYKIKPFJMoo1Owp5hd68Ii0kJ9ILPx9HZmoWLbTSDhS8g/zuY59Ly05X15192jqcUMHTRgSkLQtiBegs43kY6byMRzomH2dWJ84mESxLYzdt4lJlzG6dUb0QaUIwIBheIkzldxIyTbIWDleZtRjJABqxVlrAiKLyMl2FXOt0uc20sMkg5MSTekdGVMKUF6VIxYgNqfUuhWGAr8g@SmSP4qmwddnj0gubjV8gE "Python 2 – Try It Online")
-1 byte, thanks to Chas Brown
---
Given the task description, I kinda had to try it :)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 69 bytes
```
(y,m,d)=>(m%10*1000+d*10+y/1000,(d=y%1000/10%12)<1?12:d,y%10*10+m/10)
```
[Try it online!](https://tio.run/##VczBDoIwDAbgu0/BZckmNbbVDKcMb559hy0kHOAAetjTzxJDMg5N@39pG5ZTWIb8@k6hHaYPbKWLYLqqr3zWCUaIxnd6VIRHQsQ6SqvTeZ1BR5/UOklUxKalJ/E9Qvpv16O4yY/De5afutfUyBEBGVOYY4QrsNujtUAE3OzViTLQpVRGvIHbP93MCuYf "C# (Visual C# Interactive Compiler) – Try It Online")
Lambda with 3 inputs (`y`,`m`,`d`) that returns a 3-value tuple that has the resulting date parts in the same order.
The result is calculated by shifting digits to the left and right using regular division and the modulo operator with different powers of 10.
The `d` variable is used to caputure the month calculation so that it can be returned or wrapped to 12 when 0.
[Answer]
# JavaScript, ~~74~~ ~~72~~ 65 bytes
Thanks @Shaggy for saving 2 bytes
Thanks @Arnauld for saving 7 bytes
```
(a,b,c)=>[b%10*1e3+c*10+a/1e3|0,a/10%100%12|0||12,b/10|0+a%10*10]
```
[Try it online!](https://tio.run/##bc3BCsIwDAbgu@8hrFvUJJPOHuaLiIe2duIYqzjx1HevQfCiPYSE//sho33ZxT9u9@dmjpeQhz5XFhx41R9Pbk1YU2gbXxM2didnQpCNAjKcMCVicJIkKXzqeM4@zkucwnaK12qoqEMEAlJq9QOGEfbApiBaAxFwVyAjxEDtHzHiAUzh0Re0UvkN)
Straight modular arithmetic. Receives 3 integers (Y,M,D) and returns an array of 3 integers ([Y,M,D])
[Answer]
# [Python 3](https://docs.python.org/3/), ~~126~~ 111 bytes
Input and output as a list of strings. Probably could be shorter if I can rewrite this as a `lambda`.
```
def f(d):d=d[0][1:]+d[1].zfill(2)+d[2].zfill(2)+d[0][0];return[d[4:],str((int(d[:2])-1)%12+1),str(int(d[2:4]))]
```
[Try it online!](https://tio.run/##ZdBRa8MgEAfw5@VTHBkDpW7cXUJSHf0kcg9jJjRQ0pK4h@3LZ@raQhmocN6PP6eX73g8z822hWGEUQXtwiF4FE9OdsGTvP2M0@mkWKeKH6qEUN6XIX4tsw@@dWLWuCg1zVEF71j0K@kX4h3p0vi7Z9eK1rJ9fqzDCgfw1ZOvqUesTU1liwGAZ/CERIbQoBRiOZM2bbbFJNKyJbO/i67LATmF@0xyCPcphE1HV2OL4Xw0V8PUkGluhBH3qWsfZrGYMtLa4z/T3Yax1N2NVNV4XiAOa4RphvJYV6UsuCz5H0aVW1pvvw "Python 3 – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 78 bytes
```
,(.\b)?
$#1$*0$1
(.)(..)(..)(...)
$4$1;11$*1$2$*1,$3$*
;(1{12})*
,1
,(1*)
,$.1
```
[Try it online!](https://tio.run/##PcqxDgIxDAPQPb9BhrSyqjh36lHdwI@wgMTAwoDYEN9essAQ68nO8/a6Py5zwtr5Wk6iB2p1pVgr1v7Xiuiq3JkrNTKgi1bZjW/Gp1QBBcZaBNo4Jzd3MEuOcKyIkeodJGJLjmSAi4T7ESMff@hf "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
,(.\b)?
$#1$*0$1
```
Replace the commas with zeros or just delete them for 2-digit numbers.
```
(.)(..)(..)(...)
$4$1;11$*1$2$*1,$3$*
```
Rearrange the year and extract the mis-decoded month and day in unary, adding 11 to the month.
```
;(1{12})*
,1
```
Reduce the month modulo 12 and add 1, bringing it into the desired range.
```
,(1*)
,$.1
```
Convert the month and day back to decimal without leading zeros.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 18 bytes
-1 thanks to Erik the Outgolfer (`D¹ŻṖ?` → `d⁵DẎ`)
```
d⁵DẎ€Ẏṙ5ṁƲḌṃ2¦12Ṫ€
```
A monadic link accepting a list of integers which yields a list of integers.
**[Try it online!](https://tio.run/##y0rNyan8/z/lUeNWl4e7@h41rQGSD3fONH24s/HYpoc7eh7ubDY6tMzQ6OHOVUDJ////RxsZGFrqKBjqKJjHAgA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##VY49CgIxEIV7T7FgO8XMZM1mem8R0mkjewHLVdBGLOy8gIVYCYKxVPAe2YvELP5kneLBzPvm8WbTup7HOGmbyzjctu3ilDT4/Sj45nkO103wS74fiIM/JjM@1p1Ga6lCBAJyRZph0a52hSWkdEFANwBLwgglsLgMlCwE5utrDYnnyuUArlIAg6Y3IbrbSGWCSRGoD8CIBuS/g2D3wWCwT@heCSH9I9wL "Jelly – Try It Online").
### How?
```
d⁵DẎ€Ẏṙ5ṁƲḌṃ2¦12Ṫ€ - Link: list of integers, dt e.g. [ 1779, 3, 14]
d⁵ - divmod 10 (vectorises) [ [177,9], [0,3], [1,4]]
D - to decimal digits [[[1,7,7],[9]],[[0],[3]],[[1],[4]]]]
Ẏ€ - tighten €ach: [ [1,7,7,9], [0,3], [1,4]]
Ʋ - last four links as a monad (call that x):
Ẏ - tighten x [ 1,7,7,9, 0,3, 1,4]
5 - literal five
ṙ - rotate (left) left by (right) [ 3,1,4,1, 7,7, 9,0]
ṁ - mould like x [ [3,1,4,1], [7,7], [9,0]]
Ḍ - from decimal digits [ 3141, 77, 90]
¦ - sparse application: {
2 - to indices: literal two 77
ṃ 12 - do: base decompress using [1..12] [6,5]
- } [ 3141, [6,5], 90]
Ṫ€ - tail €ach [ 3141, 5, 90]
```
[Answer]
# Japt, ~~46~~ ~~42~~ ~~32~~ 27 bytes
*-10 bytes thanks to fəˈnɛtɪk and -1 byte thanks to Shaggy*
```
ùT2 ¬éJ ò4 vò c mn v_%CªCÃé
```
[Try it online](https://ethproductions.github.io/japt/?v=1.4.6&code=+VQyIKzpSiDyNCB28iBjIG1uCnZfJUOqQ8Pp&input=WwpbMTcwMCwxLDFdClsxOTIwLDQsMjldClsxOTY2LDExLDI3XQpbMTk5NiwxMiwxM10KWzIwMDgsOSwxXQpbMjAwOCw5LDE2XQpdCgotbVI=)
---
## Explanation:
```
ùT2 ¬éJ ò4 vò c mn v_%CªCÃé // Full program
// Test input: [2008,9,16]
ù // Left-pad each item
2 // To length 2 ["2008"," 9","16"]
T // With "0" ["2008","09","16"]
¬ // Join into a string "20080916"
éJ // Rotate counter-clockwise "00809162"
ò4 // Cut into slices of length 4 ["0080","9162"]
vò // Slice the first item into 2 [["00","80"],"9162"]
c // Flatten ["00","80","9162"]
mn // Cast each item into numbers [0,80,9162]
v_ // Apply to the first item: [0
%C // %12 [0
ªC // ||12 [12
à // Escape v_ [12,80,9162]
é // Rotate clockwise [9162,12,80]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
T‰JJ5._422S£εïNi12LÁsè
```
[Try it online](https://tio.run/##yy9OTMpM/f8/5FHDBi8vU714EyOj4EOLz209vN4v09DI53Bj8eEV//9HGxkYGOgYAlEsAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/kEcNG7y8TPXiTYyMgg8tPrf18Hq/TEMjn8ONxYdX/K@t1fkfHW1obmCgY6hjGKujEG1oaWSgY6JjZAnhmJnpGBrqGJlDeJZAnpGOoTGIZ2RgYKFjCdEEY5uBlRkYAk0zgBpnbm6pY6xjaAJVBpWJBQA).
**Explanation:**
```
T‰ # Divmod each value in the (implicit) input with 10
# i.e. [4291,8,0] → [[429,1],[0,8],[0,0]]
# i.e. [2000,10,1] → [[200,0],[1,0],[0,1]]
JJ # Then join everything together into a single string
# i.e. [[429,1],[0,8],[0,0]] → "42910800"
# i.e. [[200,0],[1,0],[0,1]] → "20001001"
5._ # Rotate it 5 times towards the left
# i.e. "42910800" → "80042910"
# i.e. "20001001" → "00120001"
422S£ # Split it into parts of size 4,2,2
# i.e. "80042910" → ["8004","29","10"]
# i.e. "00120001" → ["0012","00","01"]
ε # Map each part to:
ï # Cast the string to an integer (removing leading zeros)
# i.e. ["8004","29","10"] → [8004,29,10]
# i.e. ["0012","00","01"] → [12,0,1]
Ni # And if the index is exactly 1:
12L # Push the list [1,2,3,4,5,6,7,8,9,10,11,12]
Á # Rotate once towards the right: [12,1,2,3,4,5,6,7,8,9,10,11]
s # Swap to get the map item
è # And index it into the list (with automatic wraparound)
# i.e. 0 → 12
# i.e. 29 → 5
# (output the resulting list implicitly)
# i.e. [8004,5,10]
# i.e. [12,12,1]
```
[Answer]
# [Clojure](https://clojure.org/), 178 bytes
An anonymous function that takes a sequence of integers (Y M D) as input.
```
#(let[s(apply format"%d%02d%02d"%)](let[[w x y z](map(fn[a](read-string(apply str\1\0\r a)))(partition 2(concat(rest s)[(first s)])))n(rem w 12)][(+(* 100 y)z)(if(= n 0)12 n)x]))
```
[Try it online!](https://tio.run/##1Y/BCsIwEETvfsWgFHYVIclB9OCXpDmEtpFIm4Y0ovXnayz@hIeB3eENu9P04/2RumXZUd9lPZGNsZ/hxjTYvK3aSqhV24rNSugnXpjxNjTYSC5oayh1tj1OOflw@@XLUsta1AmWmSnalH32Y4CiZgyNzSUzZUysyfm0TqaAodgDnpCKjaYD7SGFwMxvJu/oigDBUiHwq9ALtZ2Dw/99zhuK5WTuA8hBKyHOuECevqU@ "Clojure – Try It Online")
[Answer]
# Pyth, 31 bytes
```
.e?tkb@S12tbvc.>sm.[\02`dQ3j46T
```
Try it online [here](https://pyth.herokuapp.com/?code=.e%3Ftkb%40S12tbvc.%3Esm.%5B%5C02%60dQ3j46T&input=%5B2008%2C9%2C16%5D&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=.e%3Ftkb%40S12tbvc.%3Esm.%5B%5C02%60dQ3j46T&test_suite=1&test_suite_input=%5B1700%2C1%2C1%5D%0A%5B1920%2C4%2C29%5D%0A%5B1966%2C11%2C27%5D%0A%5B1996%2C12%2C13%5D%0A%5B2008%2C9%2C1%5D%0A%5B2008%2C9%2C16%5D%0A%5B1010%2C10%2C1%5D&debug=0).
```
.e?tkb@S12tbvc.>sm.[\02`dQ3j46T Implicit: Q=eval(input()), T=10
# Example input: [2008,9,16]
m Q Map each element of Q, as d, using:
`d Stringify d
.[ Pad the above on the left...
2 ... to length of a multiple of 2...
\0 ... with "0"
s Concatenate into a single string
# '20080916'
.> 3 Rotate 3 positions to the right
# '91620080'
c j46T Chop the above at indexes 4 and 6 (j46T -> 46 to base 10 -> [4,6])
# ['9162', '00', '80']
v Evaluate each element of the above as a numeric
# [9162, 0, 80]
.e Map each element of the above, as b with index k, using:
?tk If k-1 is nonzero...
b ... yield b, otherwise...
@S12 ... look up in [1-12]...
tb ... element with index b-1 (modular indexing)
# [9162, 12, 80]
Implicit print result of previous map
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 58 bytes
```
{m/(.)(..)(..)(...)/;$3~$0,$1%12||12,+$2}o*.fmt('%02d','')
```
[Try it online!](https://tio.run/##PYxNCsIwEIX3PUUWqUl0SGemkhqKZxFBszK0VDfF6tVjatDFg/fxfsbrdHMpzmITxDE9Y6Ot0fYva5petm@JIKkmXhZi2El@DVsb4kOrGvmiQCmT@up@nkXQ8mREGKZKU4cIBGQge88Ie2BfwDkgAu4K@UwM1K7EiAfwZfTz7ltDym@4JukD "Perl 6 – Try It Online")
Returns the year with leading zeros.
] |
[Question]
[
Write a function or program that accepts a date (as a string in `YYYY-MM-DD` format) as input and returns a truthy value if that date is "alphabetical," and a falsey value if it isn't.
An alphabetical date is a date whose month, day and year are in alphabetical order when expressed as a string (and when considered specifically in M - D - Y order). For example, Sept. 26 2018 is an alphabetical date:
```
September 26th 2018 -> September twenty-sixth two thousand eighteen
September
Twenty-sixth
Two thousand eighteen
```
Another way to think of this challenge: "are the elements of a given date lexically sorted?"
Notes:
* 2018 is represented as "two thousand eighteen," not "twenty eighteen" or "two zero one eight." For another example, the year 1456 would be represented as "one thousand four hundred fifty-six," not "fourteen fifty-six."
* 26th is represented as "twenty-sixth," not "twenty-six."
* Each element of the date is considered as a whole. This is why 2018 doesn't automatically fail even though the "e" in eighteen comes before the "t" in two.
The following dates are not alphabetical:
* September 2nd 2018 ("second" should sort ahead of "September")
* April 30th 4000 ("four thousand" should sort ahead of "thirtieth")
Additional Rules:
* You will receive the date as a string, formatted like `YYYY-MM-DD`. The year will always have four digits, and the month and day will always have two digits each. Zero-padding is not represented in the string conversion (e.g., '2000-01-01' is 'January first two thousand' as you'd expect).
* You may assume that dates will always be valid (no February 30th, no Smarch 1st) and that the value of the year will be positive (no dates B.C.), but the date may be far in the future ("in the year ~~two~~ nine thousand...").
* You should return a truthy or falsey value, not necessarily a boolean `True` or `False`. If you do this in Javascript and want to return `'0'` and `0` that's fine. Of course, if you *want* to return a boolean, feel free.
* Standard loopholes are forbidden.
* This is `code-golf`
**More Examples of Alphabetical Dates**
* 2066-01-02 (January second, two thousand sixty-six)
* 1000-04-08 (April eighth, one thousand)
* 6000-08-01 (August first, six thousand)
**More Examples of Non-Alphabetical Dates**
* 1066-01-02 (January second, one thousand sixty-six)
* 1000-04-07 (April seventh, one thousand)
* 8000-08-01 (August first, eight thousand)
[Answer]
# JavaScript (ES6), 101 bytes
*Saved 4 bytes thanks to @Shaggy*
Returns \$0\$ or \$1\$.
```
s=>'_414044406550'[[,m,d]=s.split`-`,+m]<(d=`_268328715819832871${6e12-12}`[+d])&d<'_6A9338704'[s[0]]
```
[Try it online!](https://tio.run/##jc3NisIwGIXhvdcx@LXYyJc0TSPYAW/AGwihjU070yE2ZVLciNde/zbKyODuwMPh/TEHE@rfbhhJ720ztcUUik8oOeXIOUeRZQhKJfvE6iIsw@C6sSJVstjrdWSLqmRCpkzmNJN0dV8fR9FQRig7VWphdTy3ayjFZpWmMkcOKijUeqp9H7xrls5/RbBxw7fZNWNXGwfx7NHaCBgKQZASZBD/QYqIBDlB@QLFDeXlfMUnha3vifm3S9/q5i9QPnanMw "JavaScript (Node.js) – Try It Online")
or [Test all dates!](https://tio.run/##lVLBjpswEL3zFT5UNSgGGUKyyTZphZT2sFLSQ08RRQkLJvGKtREm6UarfHs6xpBseusB5s288WPm4Zf0mKqs5lXjCpmzSzG/qPlXvAn9kIZhSMejEcVxTF5JnsyVp6qSN1t3SwavyczO59tNMJ4Mg8mDP5r4U4M@vY@ZH7h@cN7GgzxxPuczvBlH0@Fw8kBDHKuYJsklT09ojnDBa9UQxTIpctLseZ2TQh7qZk8KXsBb8Tf9ZkcmIDK@20MQXCeNKZUd1/xhpT6hRRrWllqlDoKaQVqxQ@1JdlM2ENRZB0FTNJz16OSacbukn9pkZvi@z@xwPVXcErPRVeJ4@9DJ7fbrsm5NvY@ZQaNuBmx@hY0JdqxXCY3azadUkB/smSzTmkRVDfFEng4CnpJEhx35xSryM2vISh7JgmV3IieW1lpDCgYDSPhazVhrIZh3ZNo345jxqrXpTsAqZG1HIBEnBK16sITof4EwgxgAGAwc9G4hpLsXhlxocqhBTxp6bei1pqcQbyxCCrg1GiBMKXUxABtTHZaOp0qeMdsNHE1/5BYfuE4mBRml@x6R7midjJfIRX6iq20Rrmq8uJZIW9Nuxetbn@d5uJMsbOWgbyjyqoPa26mDHsGNPml7zpZ@zpYF90fJknml3NnYdVFUVvv0mTU8S0uEvSrNv4vc9iklehHHuTsQeS@SCxv/Fv8yUAKxlRTufwmu7hQvfwE)
(includes some invalid inputs)
### How?
Each month, each day and each year is mapped to an ID in \$[0..10]\$ (\$M\$, \$D\$ and \$Y\$ respectively) according to the following table. We then test if we have \$M<D\$ and \$D<Y\$.
The last part of the lookup string for day IDs is slightly compressed by using `${6e12-12}`, which expands to `5999999999988` (19th to 31st).
```
M | Month D | Day Y | Year (millennium)
----+---------------- ----+---------------- ----+-------------------
0 | April 1 | eighth 0 | eight thousand
0 | August 1 | eleventh ----+-------------------
0 | December 1 | eighteenth 3 | four thousand
----+---------------- ----+---------------- 3 | five thousand
1 | February 2 | first ----+-------------------
----+---------------- 2 | fifth 4 | nine thousand
4 | January 2 | fifteenth ----+-------------------
4 | March ----+---------------- 6 | one thousand
4 | May 3 | fourth ----+-------------------
4 | June 3 | fourteenth 7 | seven thousand
4 | July ----+---------------- ----+-------------------
----+---------------- 5 | ninth 8 | six thousand
5 | October 5 | nineteenth ----+-------------------
5 | November ----+---------------- 9 | three thousand
----+---------------- 6 | second ----+-------------------
6 | September ----+---------------- 10 | two thousand
7 | seventh
7 | seventeenth
----+----------------
8 | third
8 | sixth
8 | tenth
8 | thirteenth
8 | sixteenth
8 | thirtieth
8 | thirty-first
----+----------------
9 | twelfth
9 | twentieth
9 | twenty-*
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~66~~ ~~62~~ 58 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
0ì'-¡ÀDΣ2£<•88ΛηΣλšëÇñ0é≠>sîä&ζp°Lć®-αÅ®`•21вŽqT32в£Nèsè}Q
```
[Try it online](https://tio.run/##AXEAjv9vc2FiaWX//zDDrCctwqHDgETOozLCozzigKI4OM6bzrfOo867xaHDq8OHw7Eww6niiaA@c8Ouw6QmzrZwwrBMxIfCri3OscOFwq5g4oCiMjHQssW9cVQzMtCywqNOw6hzw6h9Uf//MjAxOC0wOS0yNg) or [verify all examples mentioned in the challenge](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3lf4PDa9R1Dy083OBybrHRocU2jxoWWVicm31u@7nF53YfXXh49eH2wxsNDq981LnArvjwusNL1M5tKzi0wedI@6F1uuc2Hm49tC4BqMfI8MKmo3sLQ4yNLmw6tNjv8IriwytqA//r/DcyMLTQNbDUNTLjMjIwM9M1MNQ1MOIyNDAw0DUw0TWw4DIDM4FqDLlgaoEKTKAKjA2AajG1mXNZwLUBAA).
**Explanation:**
```
0ì # Prepend a "0" before the (implicit) input
# i.e. "2018-09-26" → "02018-09-26"
'-¡ '# Then split on "-"
# i.e. "02018-09-26" → ["02018","09","26"]
À # Rotate it once to the left (so [0yyyy,MM,dd] becomes [MM,dd,0yyyy])
# i.e. ["02018","09","26"] → ["09","26","02018"]
D # Duplicate this list
Σ # Sort this list by:
2£ # Leave only the first 2 digits of the current item
# (which is why the prepended 0 was there at the start for the year)
# i.e. "09" → "09"
# i.e. "02018" → "02"
< # Decrease it by 1 to make it 0-indexed
# i.e. "09" → 8
•88ΛηΣλšëÇñ0é≠>sîä&ζp°Lć®-αÅ®`•21в
# Push the list [7,3,7,0,7,7,7,0,13,10,10,0,4,12,17,6,4,17,15,2,9,17,2,19,17,6,4,17,15,2,9,19,19,19,19,19,19,19,19,19,19,17,17,11,20,18,5,5,16,14,1,8]
ŽqT32в # Push the list [12,31,9]
£ # Split the first list into parts of that size: [[7,3,7,0,7,7,7,0,13,10,10,0],
# [4,12,17,6,4,17,15,2,9,17,2,19,17,6,4,17,15,2,9,19,19,19,19,19,19,19,19,19,19,17,17],
# [11,20,18,5,5,16,14,1,8]]
Nè # Then only leave the relevant list of the three based on the sort-index
s # Swap to get the earlier integer at the top of the stack again
è # And use it to index into the list
# i.e. [7,3,7,0,7,7,7,0,13,10,10,0] and 8 → 13
} # Close the sort
Q # And check if the sorted list is equal to the duplicated list,
# so whether the order is still [MM,dd,0yyyy] after sorting
# (and output the result implicitly)
```
[See this 05AB1E tip of mine (section *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•88ΛηΣλšëÇñ0é≠>sîä&ζp°Lć®-αÅ®`•21в` is `[7,3,7,0,7,7,7,0,13,10,10,0,4,12,17,6,4,17,15,2,9,17,2,19,17,6,4,17,15,2,9,19,19,19,19,19,19,19,19,19,19,17,17,11,20,18,5,5,16,14,1,8]` and `ŽqT32в` is `[12,31,9]`.
**Additional general explanation:**
The sort function will sort all three types (day, month, year) at the same time, where we will return a truthy value only if `M < D < Y` (where these `D`, `M`, and `Y` are the values we've retrieved from the compressed lists).
Why these three lists mentioned above? If we put all words in order, categorized by type, we have the following order:
```
Sorting nr Type Which?
0 Month April, August, December
1 Year eight thousand
2 Day eighteenth, eighth, eleventh
3 Month February
4 Day fifteenth, fifth, first
5 Year five thousand, four thousand
6 Day fourteenth, fourth
7 Month January, July, June, March, May
8 Year nine thousand
9 Day ninteenth, ninth
10 Month November, October
11 Year one thousand
12 Day second
13 Month September
14 Year seven thousand
15 Day seventeenth, seventh
16 Year six thousand
17 Day sixteenth, sixth, tenth, third, thirteenth, thirtieth, thirty-first
18 Year three thousand
19 Day twelfth, twentieth, twenty-first through twenty-ninth
20 Year two thousand
```
If we then look at each type individually and their original order (one thousand, two thousand, etc. for years; January, February, etc. for months; and first, second, etc. for days), the sorting numbers mentioned above are in these orders:
```
Years: [11,20,18,5,5,16,14,1,8]
Months: [7,3,7,0,7,7,7,0,13,10,10,0]
Days: [4,12,17,6,4,17,15,2,9,17,2,19,17,6,4,17,15,2,9,19,19,19,19,19,19,19,19,19,19,17,17]
```
] |
[Question]
[
Suppose you have a set of sets of integers. It's possible that some of the sets will overlap (i.e. sharing elements). You could get rid of the overlaps by deleting elements from the sets, but then some of them might end up empty; that would be a shame. Can we make all the sets disjoint without emptying any of them?
Note that in this situation, there's never any reason to leave multiple elements in a set, so this problem can always be solved by reducing each set to just one element. That's the version of the problem we're solving here.
## The task
Write a program or function, as follows:
**Input**: A list of sets of integers.
**Output**: A list of integers, of the same length as the input, for which:
* All integers in the output are distinct; and
* Each integer in the output is an element of the corresponding set of the input.
## Clarifications
* You can represent a set as a list if you wish (or whatever's appropriate for your language), disregarding the order of elements.
* You don't have to handle the case where no solution exists (i.e. there will always be at least one solution).
* There might be more than one solution. Your algorithm must always produce a valid solution, but is allowed to be nondeterministic (i.e. it's OK if it picks a different valid solution each time it runs).
* The number of distinct integers appearing in the input, *n*, will be equal to the number of sets in the input, and for simplicity, will be the integers from 1 to *n* inclusive (as their actual values don't matter). It's up to you whether you wish to exploit this fact or not.
## Testcases
```
[{1,2},{1,3},{1,4},{3,4}] -> [2,3,1,4] or [2,1,4,3]
[{1,3},{1,2,4},{2,3},{3},{2,3,4,5}] -> [1,4,2,3,5]
[{1,3,4},{2,3,5},{1,2},{4,5},{4,5}] -> [1,3,2,4,5] or [3,2,1,4,5] or [1,3,2,5,4] or [3,2,1,5,4]
```
## Victory condition
A program requires an optimal [time complexity](https://en.wikipedia.org/wiki/Time_complexity) to win, i.e. if an algorithm with a better time complexity is found, it disqualifies all slower entries. (You can assume that your language's builtins run as fast as possible, e.g. you can assume that a sorting builtin runs in time O(n log n). Likewise, assume that all integers of comparable size to *n* can be added, multiplied, etc. in constant time.)
Because an optimal time complexity is likely fairly easy to obtain in most languages, the winner will therefore be the shortest program among those with the winning time complexity, measured in bytes.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 87 bytes and ϴ(n3)
```
-Range[n=Length@#]/.Rule@@@FindIndependentEdgeSet[Join@@Table[-i->j,{i,n},{j,#[[i]]}]]&
```
[Try it online!](https://tio.run/##HckxC8IwEIbhv1IoOF2U1joqtygoDlLdQoZojvRKe4rEKeS3x@jyvB98sw0DzTbww@bLmyXorHornrRszyQ@DFib1bL/TISIBxZ3FEcvKkjYO09XCvr0ZEG82ftEWrHajRAZJEEcodaajUnGLHKFVYwNrKErT1u6KW2gLXb//TOZ/AU "Wolfram Language (Mathematica) – Try It Online")
Builds a bipartite graph whose vertices on one side are the sets (indexed by `-1,-2,...,-n`) and whose vertices on the other side are the elements `1,2,...,n`, with an edge from `-i` to `j` when `j` is contained in the `i`-th set. Finds a perfect matching in this graph using a built-in. Then lists out the elements corresponding to `-1,-2,...,-n` in that order in the perfect matching.
Mathematica's `FindIndependentEdgeSet` is the bottleneck here; everything else takes O(n2) operations to do. Mathematica probably uses the [Hungarian algorithm](https://en.wikipedia.org/wiki/Hungarian_algorithm), and so I'll assume that it runs in **ϴ(n3)** time, though it's possible that Mathematica has a naive implementation with O(n4) complexity.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
Œp⁼Q$ÐfḢ
```
[Try it online!](https://tio.run/##y0rNyan8///opIJHjXsCVQ5PSHu4Y9H///@jqw11jGt1gKSRjgmQNgLzjCEsHRMd09pYAA "Jelly – Try It Online")
# Explanation
```
Œp⁼Q$ÐfḢ Main Link
Œp Cartesian Product of the elements; all possible lists
Ðf Filter; keep elements that are
⁼Q$ Equal to themselves uniquified
Ḣ Take the first one
```
Extremely inefficient. Asymptotic to **`ϴ(n^(n+1))`** according to Misha Lavrov; I think it's right.
[Answer]
# [Haskell](https://www.haskell.org/), 48 bytes
*-1 byte thanks to nimi.*
```
import Data.List
head.filter((==)<*>nub).mapM id
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrzTYjNTFFLy0zpyS1SEPD1lbTRssurzRJUy83scBXITPlf25iZp6CrUJBUWZeiYKKQppCdLShjoJRrI4CiDaG0iYg2hhEx/4HAA "Haskell – Try It Online")
[Answer]
## Mathematica 39 Bytes
```
Last@Union[DeleteDuplicates/@Tuples@#]&
```
On the issue of complexity, I think it is very dependent upon the length of each sublist, as well as a measure of how disjoint the sublists are.
So, I think this algorithm is O(n Log n + n^2 Log m) where m is roughly the average length of each sublist.
Something like this would have complexity O(a^n) where a>1 is a measure of the overlap in sublists:
```
(For[x={1,1},!DuplicateFreeQ@x,x=RandomChoice/@#];x)&
```
Hard to say which is really faster without knowing the properties of possible inputs.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes, O(n!\*n)
```
āœʒ‚øε`QO}P}н
```
[Try it online!](https://tio.run/##MzBNTDJM/f//SOPRyacmPWqYdXjHua0Jgf61AbUX9v7/Hx1tqGOsYxKrE20EpE2BtKGOEZA0AbNBZCwA "05AB1E – Try It Online") Explanation:
```
ā Make a range 1..n
œ Generate all permutations
ʒ } Filter
‚ø Zip with input
ε } Loop over sets
`QO Check each element for membership
P All sets must match
н Take the first result
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
►oLuΠ
```
[Try it online!](https://tio.run/##yygtzv7//9G0Xfk@pecW/P//PzraUMdYxyRWJ9oISJsCaUMdIyBpAmaDyFgA "Husk – Try It Online")
### Explanation
Just saw the thing about complexity: As so often it is the case with golfing languages' solution they are not very efficient - this one has complexity **O**(n·nⁿ).
```
►(Lu)Π -- input as a list of lists, for example: [[1,2],[1,3],[1,4],[3,4]]
Π -- cartesian product: [[1,1,1,3],...,[2,3,4,4]]
►( ) -- maximum by the following function (eg. on [1,1,1,3]):
u -- deduplicate: [1,3]
L -- length: 2
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes (ϴ(nn+1))
Since this works exactly like the Jelly solution, it most likely has the same complexity.
```
h{I#.nM*F
```
**[Try it here!](https://pyth.herokuapp.com/?code=h%7BI%23.nM%2aF&input=%5B%7B1%2C3%7D%2C%7B1%2C2%2C4%7D%2C%7B2%2C3%7D%2C%7B3%7D%2C%7B2%2C3%2C4%2C5%7D%5D&debug=0)**
## How?
```
h{I#.nM*F | Full program.
*F | Fold Cartesian product.
.nM | Flatten each.
# | Keep those:
{I That are invariant over duplicate elements removal.
h | Take the first element.
```
[Answer]
# JavaScript (ES6), ~~74~~ 73 bytes
*1 byte saved, thanks to @Neil.*
```
f=([a,...A],s=[],S)=>a?a.map(c=>s.includes(c)||(S=S||f(A,[...s,c])))&&S:s
```
Recursively iterates through the array looking for a solution.
**Ungolfed:**
```
f=(
[a, ...A], //a is the first array, A is the rest
s = [], //s is the current trial solution
S //S holds the solution (if one exists) at this branch
)=>
a ? a.map( //if we're not done, iterate through a
c => s.includes(c) || // if this element already exists, short-circuit
(S = S || // else if S has a solution, keep it
f(A, [...s, c]) // else look for a solution down this branch
)
) && S //return S
```
**Test Cases:**
```
f=([a,...A],s=[],S)=>a?a.map(c=>s.includes(c)||(S=S||f(A,[...s,c])))&&S:s
console.log(f([[1,2],[1,3],[1,4],[3,4]])) // [2,3,1,4] or [2,1,4,3]
console.log(f([[1,3],[1,2,4],[2,3],[3],[2,3,4,5]])) // [1,4,2,3,5]
console.log(f([[1,3,4],[2,3,5],[1,2],[4,5],[4,5]])) // [1,3,2,4,5] or [3,2,1,4,5] or [1,3,2,5,4] or [3,2,1,5,4],4]
```
[Answer]
# Python3, ~~93~~ 84 bytes
*-9 bytes thanks to caird coinheringaahing*
```
lambda I:next(filter(lambda x:len(x)==len({*x}),product(*I)))
from itertools import*
```
[Try it online!](https://tio.run/##LcxBCsIwEAXQvafIciZkoxEXhRygZ1AX1SYYSDIhHSFSevYYi5v34cP/@cMvSro5c2thio95EuOQbGVwPrAt8C/rEGyCisb8cpV1Q5ULze8ngxwR8eAKReH7hInCInzMVFi2XHzqZ3Bdj@q0qa7eveyeu7p7R2xf)
] |
[Question]
[
You and your friend want to send each other secret messages. However, because you are conspiracy theorists and think that the government has a quantum computer that can crack any standard encryption. Therefore, you are inventing one of your own. The first step of this is as follows: taking an input string, you check if all the letters can be represented by the symbols for the elements of the periodic table (case insensitive). If they can be, you replace each section with the name of the element the symbol represents. If all letters cannot be replaced in this way, you simply use the original string.
## Your Task:
You are to write a program or function that encodes a message, as outlined previously. Remember that if your program fetches data from an outside source, the size of the outside source must be added to the byte count ([this loophole](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default?answertab=votes#tab-top)). The elements and symbols used are here:
```
H Hydrogen
He Helium
Li Lithium
Be Beryllium
B Boron
C Carbon
N Nitrogen
O Oxygen
F Fluorine
Ne Neon
Na Sodium
Mg Magnesium
Al Aluminum
Si Silicon
P Phosphorus
S Sulfur
Cl Chlorine
Ar Argon
K Potassium
Ca Calcium
Sc Scandium
Ti Titanium
V Vanadium
Cr Chromium
Mn Manganese
Fe Iron
Co Cobalt
Ni Nickel
Cu Copper
Zn Zinc
Ga Gallium
Ge Germanium
As Arsenic
Se Selenium
Br Bromine
Kr Krypton
Rb Rubidium
Sr Strontium
Y Yttrium
Zr Zirconium
Nb Niobium
Mo Molybdenum
Tc Technetium
Ru Ruthenium
Rh Rhodium
Pd Palladium
Ag Silver
Cd Cadmium
In Indium
Sn Tin
Sb Antimony
Te Tellurium
I Iodine
Xe Xenon
Cs Cesium
Ba Barium
La Lanthanum
Ce Cerium
Pr Praseodymium
Nd Neodymium
Pm Promethium
Sm Samarium
Eu Europium
Gd Gadolinium
Tb Terbium
Dy Dysprosium
Ho Holmium
Er Erbium
Tm Thulium
Yb Ytterbium
Lu Lutetium
Hf Hafnium
Ta Tantalum
W Tungsten
Re Rhenium
Os Osmium
Ir Iridium
Pt Platinum
Au Gold
Hg Mercury
Tl Thallium
Pb Lead
Bi Bismuth
Po Polonium
At Astatine
Rn Radon
Fr Francium
Ra Radium
Ac Actinium
Th Thorium
Pa Protactinium
U Uranium
Np Neptunium
Pu Plutonium
Am Americium
Cm Curium
Bk Berkelium
Cf Californium
Es Einsteinium
Fm Fermium
Md Mendelevium
No Nobelium
Lr Lawrencium
Rf Rutherfordium
Db Dubnium
Sg Seaborgium
Bh Bohrium
Hs Hassium
Mt Meitnerium
Ds Darmstadtium
Rg Roentgenium
Cn Copernicium
Nh Nihonium
Fl Flerovium
Mc Moscovium
Lv Livermorium
Ts Tennessine
Og Oganesson
```
## Input:
A string to be encoded. You may take this in all caps or lowercase if you wish, as long as you specify that requirement in your answer.
## Output:
The string, encoded as outlined previously if possible.
## Examples:
```
Hi! --> HydrogenIodine!
This is an example --> This is an example
Neon --> NeonOxygenNitrogen
Snip --> SulfurNitrogenIodinePhosphorus OR TinIodinePhosphorus
Nag --> NitrogenSilver
```
## Scoring:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins!
[Answer]
## JavaScript (ES6), ~~881~~ 871 bytes
Takes the input string in all caps.
```
s=>(o={},'HEelLIithBEeryllMGagnesCAalcTIitanVanadCRhromGAallGEermanSEelenRBubidSRtrontYttrZRirconTCechnetRUuthenRHhodPDalladCDadmTEellurBAarCEerPRraseodymNDeodymPMromethSMamarEUuropGDadolinTBerbDYysprosERrbTMhulLUutetREhenIRridTLhallFRrancRAadACctinTHhorPArotactinUranAMmericCMurESinsteinFMermMDendelevLRawrencRFutherfordDBubnSGeaborgMTeitnerDSarmstadtRGoentgenFLlerovMCoscovLVivermorHydrogenBoronCarbonNitrogenOxygenFluorineNEeonALluminumPhosphorusSulfurCLhlorineARrgonMNanganeseZNincASrsenicBRromineKRryptonMOolybdenumIodineXEenonLAanthanumTAantalumPTlatinumATstatineRNadonTSennessineOGganessonNAsodiumKpotassiumFEironAGsilverWtungstenAUgoldHGmercury'.split(/([A-Z]+|[a-z]+)/).map((r,i,a)=>i%4-3?0:o[e=a[i-2]]=i>339?r[0].toUpperCase()+r.slice(1):e[0]+r+(i<235?'ium':'')),g=([c,...s],r)=>c?c<'A'|c>'Z'?g(s,r+c):o[c]&&g(s,r+o[c])||o[c+=s.shift()]&&g(s,r+o[c]):r)(s,'')||s
```
### Extended test cases
Because this challenge is also a variant of the exact cover set problem, I've added the following test cases:
* "NA" → "Sodium"
* "NAG" → "N" + "AG" → "NitrogenSilver"
* "NAP" → "NA" + "P" → "SodiumPhosphorus"
```
let f =
s=>(o={},'HEelLIithBEeryllMGagnesCAalcTIitanVanadCRhromGAallGEermanSEelenRBubidSRtrontYttrZRirconTCechnetRUuthenRHhodPDalladCDadmTEellurBAarCEerPRraseodymNDeodymPMromethSMamarEUuropGDadolinTBerbDYysprosERrbTMhulLUutetREhenIRridTLhallFRrancRAadACctinTHhorPArotactinUranAMmericCMurESinsteinFMermMDendelevLRawrencRFutherfordDBubnSGeaborgMTeitnerDSarmstadtRGoentgenFLlerovMCoscovLVivermorHydrogenBoronCarbonNitrogenOxygenFluorineNEeonALluminumPhosphorusSulfurCLhlorineARrgonMNanganeseZNincASrsenicBRromineKRryptonMOolybdenumIodineXEenonLAanthanumTAantalumPTlatinumATstatineRNadonTSennessineOGganessonNAsodiumKpotassiumFEironAGsilverWtungstenAUgoldHGmercury'.split(/([A-Z]+|[a-z]+)/).map((r,i,a)=>i%4-3?0:o[e=a[i-2]]=i>339?r[0].toUpperCase()+r.slice(1):e[0]+r+(i<235?'ium':'')),g=([c,...s],r)=>c?c<'A'|c>'Z'?g(s,r+c):o[c]&&g(s,r+o[c])||o[c+=s.shift()]&&g(s,r+o[c]):r)(s,'')||s
console.log(f('HI!'))
console.log(f('THIS IS AN EXAMPLE'))
console.log(f('NEON'))
console.log(f('SNIP'))
console.log(f('NA'))
console.log(f('NAG'))
console.log(f('NAP'))
```
### How?
**Preliminary optimization**
We ignore the following 26 elements entirely, because they can safely be replaced with two symbols of one character among `BCFHIKNOPSUVWY`:
```
Bh, Bi, Bk, Cf, Cn, Co, Cs, Cu, Hf, Ho, Hs, In, Nb,
Nh, Ni, No, Np, Os, Pb, Po, Pu, Sb, Sc, Si, Sn, Yb
```
**Encoding and decoding the elements**
We use an interlaced list of element symbols in upper case and element names in lower case. Symbols are always stored as-is, while names are shortened according to the following rules:
1. If the first letter of the name matches the first letter of the symbol, we omit it.
2. If the element passes rule #1 and its name ends in "ium", we omit this suffix.
Examples:
* Ag / Silver: "AGsilver"
* K / Potassium: "Kpotassium"
* Zn / Zinc: "ZNinc"
* He / Helium: "HEel"
The 58 elements that trigger both rules are stored at the beginning of the list, followed by the 27 elements that trigger rule #1 only, followed by the 7 elements that do not trigger any rule.
We decode this list to populate the lookup table ***o***, where the keys are the symbols and the values are the decoded element names:
```
"HEelLIith[...]HGmercury" // encoded list
.split(/([A-Z]+|[a-z]+)/) // split it by character case, which gives:
// [ '', 'HE', '', 'el', '', 'LI', '', 'ith', etc. ]
.map((r, i, a) => // for each item 'r' at position 'i' in this array 'a':
i % 4 - 3 ? // if we're not currently pointing to an element name:
0 // do nothing
: // else:
o[e = a[i - 2]] = // save o[e], where e = element symbol
i > 339 ? // if symbol/name first letters do not match:
r[0].toUpperCase() + // we need to capitalize the first letter of the name
r.slice(1) // and keep the rest unchanged
: // else:
e[0] + // we use the first letter of the symbol,
r + // followed by the name,
(i < 235 ? 'ium' : '') // followed by the 'ium' suffix when appropriate
) // end of map()
```
**Covering the input string**
We try to replace all upper-case letters in the input string with element symbols, using the recursive function ***g()*** which eventually returns a replacement string or *undefined* if no exact cover is found:
```
g = ([c, // c = next character
...s], // s = array of remaining characters
r) => // r = replacement string
c ? // if there's still at least one character:
c < 'A' | c > 'Z' ? // if it's not an upper-case letter:
g(s, r + c) // just append it to 'r'
: // else:
o[c] && g(s, r + o[c]) || // try to find a symbol matching 'c'
o[c += s.shift()] && g(s, r + o[c]) // or a symbol matching 'c' + the next char.
: // else:
r // success: return 'r'
```
[Answer]
# Mathematica, 404 (239) bytes
```
S="";l=ToLowerCase;e=ElementData;Unprotect[e];a="Abbreviation";n="Name";e[113,a]="Nh";e["Nh",n]="Nihonium";e[115,a]="Mc";e["Mc",n]="Moscovium";e[117,a]="Ts";e["Ts",n]="Tennessine";e[118,a]="Og";e["Og",n]="Oganesson";r=StringReplace;A=Reverse@SortBy[Table[e[j,a],{j,118}],StringLength];If[StringFreeQ[r[l@S,Table[l@A[[j]]->"",{j,118}]],Alphabet[]],r[l@S,Table[l@A[[j]]->Capitalize@e[A[[j]],n],{j,118}]],S]
```
Using Mathematica's built-in database to fetch element names and their abbreviation. Input can be mixed lower and upper case and is stored in the variable `S`. The output is the expression's result, it is not explicitly printed.
The at this time fully working code takes up 404 bytes, as Mathematica's built-in chemical database is a bit behind. `ElementData[118, "Name"]` returns `ununoctium` instead of `oganesson` (the super-heavy elements where only recently properly named, ununoctium was a placeholder name for element 118).
To update `ElementData`, I unprotect it and fix the values for elements Nihonium (113), Moscovium (115), Tennessine (118) and Oganesson (118).
If Mathematica's database were up to date, I would only require 239 bytes.
```
S="";l=ToLowerCase;e=ElementData;r=StringReplace;A=Reverse@SortBy[Table[e[j,"Abbreviation"],{j,118}],StringLength];If[StringFreeQ[r[l@S,Table[l@A[[j]]->"",{j,118}]],Alphabet[]],r[l@S,Table[l@A[[j]]->Capitalize@e[A[[j]],"Name"],{j,118}]],S]
```
[Answer]
# Javascript, ~~1487~~ ~~1351~~ ~~1246~~ ~~1170~~ ~~1243~~ 1245 bytes
*saved 234 bytes thanks to @musicman523*
*saved 174 bytes thanks to @ovs*
*saved 7 bytes thanks to @Shaggy*
*added 75 bytes to make it work for 2 letter elements*
```
b=>~((o=0,d=Array.from([...b].map((u,i,a)=>(h=e=>("he0Hel2h0Hydrogen1li0Lith2be0Beryll2b0Boron1c0Carbon1n0Nitrogen1o0Oxygen1f0Fluorine1ne0Neon1na0Sod2mg0Magnes2al0Aluminum1p0Phosphorus1s0Sulfur1cl0Chlorine1ar0Argon1k0Potass2ca0Calc2ti0Titan2v0Vanad2cr0Chrom2mn0Manganese1fe0Iron1ni0Nickel1cu0Copper1zn0Zinc1ga0Gall2ge0German2as0Arsenic1se0Selen2br0Bromine1kr0Krypton1rb0Rubid2sr0Stront2y0Yttr2zr0Zircon2nb0Niob2mo0Molybdenum1tc0Technet2ru0Ruthen2rh0Rhod2pd0Pallad2ag0Silver1cd0Cadm2in0Ind2te0Tellur2i0Iodine1xe0Xenon1cs0Ces2ba0Bar2la0Lanthanum1ce0Cer2pr0Praseodym2nd0Neodym2pm0Prometh2sm0Samar2eu0Europ2gd0Gadolin2tb0Terb2dy0Dyspros2ho0Holm2er0Erb2tm0Thul2lu0Lutet2hf0Hafn2ta0Tantalum1w0Tungsten1re0Rhen2ir0Irid2pt0Platinum1au0Gold1hg0Mercury1tl0Thall2at0Astatine1rn0Radon1fr0Franc2ra0Rad2ac0Actin2th0Thor2pa0Protactin2u0Uran2np0Neptun2pu0Pluton2am0Americ2cm0Cur2bk0Berkel2cf0Californ2es0Einstein2fm0Ferm2md0Mendelev2no0Nobel2lr0Lawrenc2rf0Rutherford2db0Dubn2sg0Seaborg2bh0Bohr2hs0Hass2mt0Meitner2ds0Darmstadt2rg0Roentgen2nh0Nihon2fl0Flerov2mc0Moscov2lv0Livermor2ts0Tennessine1og0Oganesson".replace(/2/g,'ium1').split(1).map(a=>a.split(0)).find(a=>a[0]==e)||[,0])[1],o?(o=0,''):((p=a[i+1])&&(o=1,h(u+p))||(o=0,h(u)))))).join``).search(0))?b:d
```
(Slightly more) readable version:
```
b=>~((o=0,d=Array.from([...b].map((u,i,a)=>(h=e=>(
"he0Hel2h0Hydrogen1li0Lith2be0Beryll2b0Boron1c0Carbon1n0Nitrogen1o0Oxygen1f0Flu
orine1ne0Neon1na0Sod2mg0Magnes2al0Aluminum1p0Phosphorus1s0Sulfur1cl0Chlorine1ar0
Argon1k0Potass2ca0Calc2ti0Titan2v0Vanad2cr0Chrom2mn0Manganese1fe0Iron1ni0Nickel1
cu0Copper1zn0Zinc1ga0Gall2ge0German2as0Arsenic1se0Selen2br0Bromine1kr0Krypton1rb
0Rubid2sr0Stront2y0Yttr2zr0Zircon2nb0Niob2mo0Molybdenum1tc0Technet2ru0Ruthen2rh0
Rhod2pd0Pallad2ag0Silver1cd0Cadm2in0Ind2te0Tellur2i0Iodine1xe0Xenon1cs0Ces2ba0Ba
r2la0Lanthanum1ce0Cer2pr0Praseodym2nd0Neodym2pm0Prometh2sm0Samar2eu0Europ2gd0Gad
olin2tb0Terb2dy0Dyspros2ho0Holm2er0Erb2tm0Thul2lu0Lutet2hf0Hafn2ta0Tantalum1w0Tu
ngsten1re0Rhen2ir0Irid2pt0Platinum1au0Gold1hg0Mercury1tl0Thall2at0Astatine1rn0Ra
don1fr0Franc2ra0Rad2ac0Actin2th0Thor2pa0Protactin2u0Uran2np0Neptun2pu0Pluton2am0
Americ2cm0Cur2bk0Berkel2cf0Californ2es0Einstein2fm0Ferm2md0Mendelev2no0Nobel2lr0
Lawrenc2rf0Rutherford2db0Dubn2sg0Seaborg2bh0Bohr2hs0Hass2mt0Meitner2ds0Darmstadt
2rg0Roentgen2nh0Nihon2fl0Flerov2mc0Moscov2lv0Livermor2ts0Tennessine1og0Oganesson
".replace(/2/g,'ium1').split(1).map(a=>a.split(0)).find(a=>a[0]==e)||[,0])[1],o?
(o=0,''):((p=a[i+1])&&(o=1,h(u+p))||(o=0,h(u)))))).join``).search(0))?b:d
```
] |
[Question]
[
# Before I begin, this challenge was not mine originally
Credits to The University of Waterloo. This came from the Canadian Computing Competition 2016, Senior Problem 5. Here is a clickable link to the contest PDF:
[`http://cemc.uwaterloo.ca/contests/computing/2016/stage%201/seniorEn.pdf`](http://cemc.uwaterloo.ca/contests/computing/2016/stage%201/seniorEn.pdf)
Here is a link to the site:
[`http://cemc.uwaterloo.ca/contests/past_contests.html`](http://cemc.uwaterloo.ca/contests/past_contests.html)
# Challenge
Given a wrapping array of two constant values, determine the configuration after `n` evolutions for positive integer input `n`. These two values represent a living cell and a dead cell. Evolutions work like this:
# Evolution!
After each iteration, a cell is alive if it had exactly one living neighbor in the previous iteration. Any less and it dies of loneliness; any more and it dies of overcrowding. The neighbourhood is exclusive: i.e. each cell has two neighbours, not three.
For example, let's see how `1001011010` would evolve, where `1` is a living cell and `0` is a dead cell.
```
(0) 1 0 0 1 0 1 1 0 1 0 (1)
* $ %
```
The cell at the `*` has a dead cell on both sides of it so it dies of lonliness.
The cell at the `$` has a living cell on one side of it and a dead cell on the other. It becomes alive.
The cel at the `%` has a living cell on both sides of it so it stays dead from overcrowding.
# Winning Criteria
Shortest code wins.
# I/O
Input will be a list of the cell states as two consistent values, and an integer representing the number of inputs, in some reasonable format. Output is to be a list of the cell states after the specified number of iterations.
# Test Cases
```
start, iterations -> end
1001011010, 1000 -> 1100001100
100101011010000, 100 -> 000110101001010
0000000101011000010000010010001111110100110100000100011111111100111101011010100010110000100111111010, 1000 -> 1001111111100010010100000100100100111010010110001011001101010111011011011100110110100000100011011001
```
[Test Case](https://hastebin.com/zofexitizo.txt)
[This test case froze hastebin and exceeded the size limit on pastebin](https://alexander-liao.firebaseapp.com/insane-test-case.html)
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/),14 bytes
Prompts for start state as Boolean list and then for number of iterations
```
(1∘⌽≠¯1∘⌽)⍣⎕⊢⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdObMoOSf1v4bho44Zj3r2PupccGg9lK35qHfxo76pj7oWAUmQ2v8KYADRwmWoYACEhmAMIQ24DA0MDLhwqkJSCYEg9ajKDRSQIao2hBgq2xDOQ0CEnCFWPaiqDeE2oOpHZhmgeRfVBWg2gwMCAA "APL (Dyalog Unicode) – Try It Online")
`⎕` numeric prompt (for Boolean list of start state)
`⊢` on that, apply
`(`…`)⍣⎕` the following tacit function, numeric-prompt times
`¯1∘⌽` the argument rotated one step right
`≠` different from (XOR)
`1∘⌽` the argument rotated one step left
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ṙ2^ṙ-µ¡
```
[Try it online!](https://tio.run/nexus/jelly#@/9w50yjOCChe2jroYX//7tWFKQml6SmKOSXlhSUllgpGBgYGBoagCCY@B9tqGMAhIZwDGOBYex/oDoA "Jelly – TIO Nexus")
[Extra Test Case (footer for formatting)](https://tio.run/nexus/jelly#@/9w50yjOCChe2jroYX/iw0PL//vWlGQmlySmqKQX1pSUFpipWBoYGAIBQZAJgiBGFCmAUQaKg5RYQgWA6sDS0ERVBRJO5RvYPhfycAAKgg1BcUOqAMMYOYitMMdBpWHWmuAbAxcs9J/kBAA "Jelly – TIO Nexus").
**Explanation**
```
ṙ2^ṙ-µ¡
µ¡ - repeat a number of times equal to input 2:
ṙ2 - previous iteration rotated 2 to the left
^ - XOR-ed with:
- (implicit) previous iteration
ṙ- - rotate back (by negative 1 to the left)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
FDÀÀ^Á
```
[Try it online!](https://tio.run/nexus/05ab1e#@@/mcrjhcEPc4cb//w0NDAy4og10FDCRISppiE0Wq4ghqiAaQlNpSMg0rIYYojoJq/mYXEyvGeL2AnZnxwIA "05AB1E – TIO Nexus")
**Explanation**
```
F # input_1 times do
D # duplicate last iteration (input_2 the first iteration)
ÀÀ # rotate left twice
^ # XOR
Á # rotate right
```
] |
[Question]
[
I love `/usr/share/dict/words`; it's so handy! I use it for all my programs, whenever I can! You're going to take advantage of this ever so useful file to use, by testing a word's individuality.
---
**Input**
* A word; defined in this challenge as any string of characters
* `/usr/share/dict/words` in some format; you may hard code it, read from disk, assume it as a second argument, whatever makes the most sense in your challenge
**Output**
* A words individuality (see below)
A word's individuality is derived from the following equation:
```
<the number of words for which it is a substring> / <length of the word>
```
Let's take a look at an example:
`hello`. There are 12 words which have the substring `hello` in them, divided by `5` (hello's length), and hello's individuality is `12/5` or `2.4`
---
P.S. This is [codegolf](/questions/tagged/codegolf "show questions tagged 'codegolf'"), so the lower the individuality score, the more individual
Because individuality is a long word, your program must be as short as possible
Good Luck!
---
**Test Cases**
You can use this convenient Node.js script, which fits the challenge requirements to fit your code. It is also how I generated the test cases:
```
var fs = require("fs");
var word = process.argv[2];
process.stdout.write("Reading file...")
fs.readFile("/usr/share/dict/words", function(err, contents) {
console.log("Done")
if (err) throw err;
words = contents.toString().split("\n");
var substrings = words.filter(w => w.indexOf(word) > -1).length;
var length = word.length;
console.log(`${word} => ${substrings} / ${length} = ${substrings / length}`)
})
```
Test Cases:
```
hello => 12 / 5 = 2.4
individuality => 1 / 13 = 0.07692307692307693
redic => 52 / 5 = 10.4
ulous => 200 / 5 = 40
challen => 15 / 7 = 2.142857142857143
ges => 293 / 3 = 97.66666666666667
hidden => 9 / 6 = 1.5
words => 12 / 5 = 2.4
aside => 8 / 5 = 1.6
```
[Answer]
# Bash, ~~41~~, ~~39~~, ~~34~~, ~~33~~, 26 bytes
EDIT:
* Converted from function to a script
* One byte off by removing the *ignore case* flag
* Replaced *wc -l* with *grep -c*, saving 5 bytes. Thanks @Riley !
A rather trivial solution in *bash* + *coreutils*
**Golfed**
```
bc -l<<<`grep -c $1`/${#1}
```
**Test**
```
>cat /usr/share/dict/words| ./test ulous
7.60000000000000000000
>grep -i ulous /usr/share/dict/words | wc -l
38
```
[Answer]
# Python 3, ~~52~~ 49 bytes
-3 bytes thanks to Kade, for assuming `w` to be the word list as list:
```
f=lambda s,w:w>[]and(s in w[0])/len(s)+f(s,w[1:])
```
Previous solution:
```
lambda s,w:sum(s in x for x in w.split('\n'))/len(s)
```
Assumes `w` to be the word list. I choose Python 3 because in my word list there are some Non-ASCII chars and Python 2 does not like them.
[Answer]
# [Perl 6](https://perl6.org), ~~45 36 33~~ 32 bytes
wordlist as a filename `f`, **45 bytes**
```
->$w,\f{grep({/:i"$w"/},f.IO.words)/$w.chars}
```
wordlist as a list `l`, **36 bytes**
```
->$w,\l{grep({/:i"$w"/},l)/$w.chars}
```
using placeholder variables, and reverse (`R`) meta-operator, **33 bytes**
```
{$^w.chars R/grep {/:i"$w"/},$^z}
```
using `.comb` to get a list of characters, rather than `.chars` to get a count, **32 bytes**
```
{$^w.comb R/grep {/:i"$w"/},$^z}
```
## Expanded:
```
{ # block lambda with placeholder parameters 「$w」 「$z」
$^w # declare first parameter ( word to search for )
.comb # list of characters ( turns into count in numeric context )
R[/] # division operator with parameters reversed
grep # list the values that match ( turns into count in numeric context )
{ # lambda with implicit parameter 「$_」
/ # match against 「$_」
:i # ignorecase
"$w" # the word as a simple string
/
},
$^z # declare the wordlist to search through
#( using a later letter in the alphabet
# so it is the second argument )
}
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 9 bytes
```
#vy²å}ON/
```
[Try it online!](http://05ab1e.tryitonline.net/#code=I3Z5wrLDpX1PTi8&input=YWJhIGFiYmEgYWJhYmEgYWJhYmFiYWJhIGFiYiBhYmJiIGFiYWJhIGxvbAphYmE)
```
# Separate by newlines or spaces.
vy For each entry in the dictionary.
²å 1 if the second argument is a substring of the current word, 0 o.w.
} End loop.
O Sum ones and zeros.
N Get list size.
/ Divide.
```
[Answer]
## awk: 31 bytes
Passing the word as the `w` variable to the `awk` command, and the file in `<stdin>`:
```
$0~w{N++}END{print N/length(w)}
```
Sample output:
```
$ awk -vw=hello '$0~w{N++}END{print N/length(w)}' /usr/share/dict/words
2.4
```
[Answer]
# PHP, 54 bytes
Assumes the word list in `$w`.
```
<?=count(preg_grep("/$argv[1]/",$w))/strlen($argv[1]);
```
[Answer]
## Clojure, 53 bytes
Not that exciting :/
```
#(/(count(filter(fn[w](.contains w %))W))(count %)1.)
```
That `1.` is there to convert a rational into a float. I pre-loaded words into `W` as such:
```
(def W (map clojure.string/lower-case (clojure.string/split (slurp "/usr/share/dict/words") #"\n")))
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/95340/edit).
Closed 7 years ago.
[Improve this question](/posts/95340/edit)
Given a Sudoku puzzle, find all possible marks that can be filled into each empty cell.
## Test case
Input:
```
[
[
// Top left:
[
0, 0, 0,
3, 4, 0,
0, 0, 2
],
// Top middle:
[
7, 4, 0,
0, 0, 0,
0, 0, 3
],
// Top right:
[
8, 0, 0,
1, 7, 0,
0, 0, 0
]
],
[
// Middle left:
[
9, 0, 4,
7, 0, 0,
1, 0, 3
],
// Center:
[
0, 5, 0,
0, 0, 0,
0, 7, 0
],
// Middle right:
[
0, 0, 0,
6, 4, 0,
0, 0, 0
]
],
[
// Bottom left:
[
0, 0, 7,
6, 3, 0,
0, 0, 0
],
// Bottom middle:
[
0, 0, 5,
0, 0, 0,
9, 1, 0
],
// Bottom right:
[
0, 0, 0,
5, 2, 0,
7, 0, 0
]
]
]
```
Output:
```
[
[
// Top left:
[
[5], [1, 5, 6, 9], [1, 5, 6, 9],
[], [], [5, 6, 8, 9],
[5, 8], [1, 5, 6, 7, 8, 9], []
],
// Top middle:
[
[], [], [1, 2, 6, 9],
[2, 5, 6, 8], [2, 6, 8, 9], [2, 6, 8, 9],
[1, 5, 6, 8], [6, 8, 9], []
],
// Top right:
[
[], [3, 5, 6, 9], [2, 3, 5, 6, 9],
[], [], [2, 5, 6, 9],
[4, 9], [5, 6, 9], [4, 5, 6, 9]
]
],
[
// Middle left:
[
[], [2, 6, 8], [],
[], [2, 5, 8], [5, 8],
[], [2, 5, 6, 8], []
],
// Center:
[
[1, 2, 3, 6, 8], [], [1, 2, 6, 8],
[1, 2, 3, 8], [2, 3, 8, 9], [1, 2, 8, 9],
[2, 4, 6, 8], [], [2, 4, 6, 8, 9]
],
// Middle right:
[
[2, 3], [1, 3, 8], [1, 2, 3, 7, 8],
[], [], [1, 2, 3, 5, 8, 9],
[2, 9], [5, 8, 9], [2, 5, 8, 9]
]
],
[
// Bottom left:
[
[2, 4, 8], [1, 2, 8, 9], [],
[], [], [1, 8, 9],
[2, 4, 5, 8], [2, 5, 8], [5, 8]
],
// Bottom middle:
[
[2, 3, 4, 6, 8], [2, 3, 6, 8], [],
[4, 8], [8], [4, 7, 8],
[], [], [2, 4, 6, 8]
],
// Bottom right:
[
[3, 4, 9], [1, 3, 6, 8, 9], [1, 3, 4, 6, 8, 9],
[], [], [1, 4, 8, 9],
[], [3, 6, 8], [3, 4, 6, 8]
]
]
]
```
Output visualisation; the small numbers:
[](https://i.stack.imgur.com/nUk6I.png)
## Rules
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The shortest answer in bytes (or equivalent) wins.
* Input can be in array or string format.
* Input must be in the order presented above (top-left, top-middle, top-right, etc...)
* Output can be in array or string format, as long as the output can logically represent the expected result.
* Output must be in the same order as the input (top-left, top-middle, top-right, etc...)
* Output does not need to be prettified.
* Code must be applicable to any valid incomplete Sudoku grid.
* Standard golfing rules apply.
## Additional Notes:
You get additional fake internet points if your program or function uses the result to solve the Sudoku puzzle to the point where cell values can no longer be logically solved. For example, the very first cell in the test case can only ever possibly contain the number 5, so it should be considered when filling in the other values. This is just for fun and additional challenge, otherwise the shortest answer wins regardless of whether or not this criterion is met.
[Answer]
# C (gcc), 193 bytes
```
#define F(x)for(x=0;x<9;++x)
char s[99];main(k,r,c){gets(s);F(r)F(c){
int d[99]={};F(k)d[s[r*9+k]]=d[s[k*9+c]]=d[s[r/3*27+k/3*9+c/3*3+k%3]]=1;
F(k)s[r*9+c]<48&&!d[49+k]&&putchar(49+k);puts("");}}
```
Assumes input in the following format (same sudoku as above):
```
..74.8..34....17...2..3...9.4.5....7.....64.1.3.7......7..5...63....52....91.7..
```
And outputs in the following format:
```
5
1569
1569
1269
3569
23569
5689
etc
```
[Answer]
# Python 2, 178 bytes
```
lambda s,R=range(9):[[[(s[Y][X][i]<1)*[q+1for q in R if~-(q+1in sum([[s[j/3][X][j%3*3+i%3],s[Y][j/3][j%3+i/3*3]]for j in R],[])+s[Y][X])]for i in R]for X in R[:3]]for Y in R[:3]]
```
An anonymous function that takes a 3-dimensional array of ints and returns a 4-dimensional array of ints.
[Answer]
## JavaScript (ES6), ~~208~~ ~~196~~ ~~190~~ ~~188~~ 186 bytes
```
g=>g.map((B,i)=>[...B].map((s,x)=>+s||[..."123456789"].filter(n=>(t=i=>(k=g[i].search(n)%m)<a|k>b)(j=i%3,m=3,a=b=x%3)&t(j+3)&t(j+6)&t(j=i-j,m=9,a=x-a,b=a+2)&t(j+1)&t(j+2)&t(i,a=0,b=8))))
```
**Input**:
An array of 9 strings (one per box, from top-left to bottom-right).
**Output**:
An array of 9 arrays, where each item consists of either the original number at this position or an array of characters representing the possible digits.
### Formatted and commented
```
g => g.map((B, i) => // for each box B at position i in the grid:
[...B].map((s, x) => // for each cell s at position x in this box:
+s || // if there already is a number at this position, use it
[..."123456789"].filter(n => // else, for each digit n in [1 .. 9]:
(t = i => // t() = helper function that looks for the digit n inside
(k = g[i].search(n) % m) // a given box i and returns a truthy value if its
< a | k > b // position modulo m is not in the range [a .. b]
)( //
j = i % 3, // test the top box in the current column, using:
m = 3, // modulo = 3 and
a = b = x % 3 // range = [x % 3 .. x % 3]
) & //
t(j + 3) & // test the middle box in the current column
t(j + 6) & // test the bottom box in the current column
t( //
j = i - j, // test the left box in the current row, using:
m = 9, // modulo = 9 and
a = x - a, b = a + 2 // range = [floor(x / 3) .. floor(x / 3) + 2]
) & //
t(j + 1) & // test the middle box in the current row
t(j + 2) & // test the right box in the current row
t(i, a = 0, b = 8) // finally test the current box, using:
) // modulo = 9 (unchanged) and
) // range = [0 .. 8] (thus testing the entire box)
) //
```
### Demo
```
let f =
g=>g.map((B,i)=>[...B].map((s,x)=>+s||[..."123456789"].filter(n=>(t=i=>(k=g[i].search(n)%m)<a|k>b)(j=i%3,m=3,a=b=x%3)&t(j+3)&t(j+6)&t(j=i-j,m=9,a=x-a,b=a+2)&t(j+1)&t(j+2)&t(i,a=0,b=8))))
console.log(f([
"000340002",
"740000003",
"800170000",
"904700103",
"050000070",
"000640000",
"007630000",
"005000910",
"000520700"
]));
```
[Answer]
# Haskell, 135 bytes
```
(%)=mod
x!y=x-x%y
f a=[[j|j<-[1..9],and[a!!k/=j|k<-[i!3-i!9%27+p%3+p!3*3|p<-[0..8]]++[i!9..i!9+8]++[i%9,i%9+9..80]],a!!i<1]|i<-[0..80]]
```
Defines a function `f` from lists of 81 `Int`s to lists of lists of `Int`s;
IO is like [orlp's answer](https://codegolf.stackexchange.com/a/95344/3852), except it uses `[0,1,2,3,4,5,6,7,8,9]` instead of `".123456789"`.
dianne saved a couple of bytes.
[Answer]
## JavaScript (ES6), 185 bytes
```
a=>a.map((b,r)=>b.map((d,c)=>d.map((e,i)=>e.map((g,j)=>[1,2,3,4,5,6,7,8,9].filter(v=>a.every(b=>b[c].every(e=>e[j]-v))&b.every(d=>d[i].every(g=>g-v))&d.every(e=>e.every(g=>g-v))&!g)))))
```
Takes as input an array of three rows of an array of three columns of a three by three array of cells of integers, and returns a five-dimensional array where all the integers have been replaced by arrays.
] |
[Question]
[
# Introduction
**Eisenstein integers** are complex numbers of the form
`a+bω`
Where `a,b` are integers, and
`ω = e^(2πi/3)`
The Eisenstein integers form a triangular lattice in the complex plane:
[](https://i.stack.imgur.com/e6hi0.png)
We say that an Eisenstein integer `z=a+bω` is **prime** if it cannot be written as the product of two non-unit (not 1,-1,ω,-ω,ω^2, or -ω^2) Eisenstein integers
# Program
**Input**: A natural number `n`.
**Output**: The number of Eisenstein primes which are of the form `a+bω` for which `a,b` are natural numbers (including zero) less than or equal to `n`
# Test Cases
0 → 0
1 → 0
2 → 5
3 → 9
4 → 13
5 → 20
# Scoring
This is `code-golf`, so least amount of bytes wins
[Answer]
# Julia, ~~66~~ ~~62~~ 60 bytes
```
!n=sum(isprime,[a<1<b%3?b:a^2-a*b+b^2for a=[0;0;0:n],b=0:n])
```
[Try it online!](http://julia.tryitonline.net/#code=IW49c3VtKGlzcHJpbWUsW2E8MTxiJTM_YjphXjItYSpiK2JeMmZvciBhPVswOzA7MDpuXSxiPTA6bl0pCgpwcmludChtYXAoISwwOjUpKQ&input=)
## Explanation
We’re interested in the primes in this parallelogram on the complex plane (example for **n = 4**):
[](https://i.stack.imgur.com/7YiDQ.png)
We can split them into primes on the **green lines**, and on the **gray lines**.
Wikipedia tells me an Eisenstein number **z** is a **green line Eisenstein prime** iff **|z|** is a natural prime equal to **2** mod 3.
It also says **z** is a **gray line Eisenstein prime** iff **|z|² = a² − ab + b²** is a natural prime.
---
So we loop over **a = 0…n** and **b = 0…n**, and check:
* If **(a = 0 or b = 0 or a = b)** and **max(a, b) % 3 = 2**, then count whether **max(a, b)** is a prime.
* Else, count whether **a² − ab + b²** is a prime.
However, we can abuse the distribution’s symmetry. Instead of counting each green line once, we can just count one green line thrice! That is, only check **a = 0** and increment the counter by three when we find a green line prime. The `a=[0;0;0:n]` achieves exactly this.
Since we know we’re only considering the green line **a = 0**, we can replace **max(a, b)** by **b**.
The “green line condition” is nicely expressed in Julia using operator chaining: `a<1<b%3`.
(For the remaining green lines, we will never return a false positive: if **a = b** or **b = 0** then **a² − ab + b² = a²**, which can’t be prime.)
## Ideas
Maybe, instead of writing `a^2-a*b+b^2`, I can conditionally replace the exponent at `b` by `1` when `a<1<b%3` – then the expression reduces to `b`. This doesn’t seem to be shorter, but it’s neat!
[Answer]
# Jelly, 24 bytes
```
Rð_²+×µ€µ³RḊm3,µÆP×1¦3FS
```
Roughly the same approach as my Julia answer.
```
Initial argument: n
R Compute [1, 2, …, n]
ð_²+× (λ, ρ) —→ (λ − ρ)² + λρ (which is λ² − λρ + ρ²)
µ€ Zip with itself. Call this Q.
µ Refocus argument: Q
³ The initial argument n
RḊm3 Compute candidate green line primes: [2, 5, 8, …, n]
, Call this P. Make pair with argument.
µ Refocus argument: [P, Q]
ÆP Check primality
×1¦3 Multiply the first element by 3
FS Sum everything
(The result is 3·countprimes(P) + countprimes(Q))
```
[Answer]
## CJam (34 bytes)
```
qi,:)_2m*{_:*\:-_*+}%\1>3%3*+:mp1b
```
[Online demo](http://cjam.aditsu.net/#code=qi%2C%3A)_2m*%7B_%3A*%5C%3A-_*%2B%7D%25%5C1%3E3%253*%2B%3Amp1b&input=5)
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/78690/edit).
Closed 7 years ago.
[Improve this question](/posts/78690/edit)
Your challenge, should you choose to accept it, is simple:
Implement [RFC 862](https://www.rfc-editor.org/rfc/rfc862), also known as the Echo Protocol:
## The Echo protocol
An echo service simply sends back to the originating source any data it receives.
### TCP Based Echo Service
One echo service is defined as a connection based application on TCP. A server listens for TCP connections on TCP port 7. Once a connection is established any data received is sent back. This continues until the calling user terminates the connection.
### UDP Based Echo Service
Another echo service is defined as a datagram based application on UDP. A server listens for UDP datagrams on UDP port 7. When a datagram is received, the data from it is sent back in an answering datagram.
### Scoring
* The score is one point for every byte of code as encoded in UTF-8 or a language-specific code page, whichever is smaller.
* If the program incompletely implements RFC 862 by providing only UDP or only TCP, the score is doubled.
* If the program incorrectly implements RFC 862 by either using a port other than 7 or by dropping or transforming certain bytes due to language limitations or corner cutting, the score is quadrupled. (This stacks with the preceding point if applicable.)
* If the program is invalid, the score is [ω](https://en.wikipedia.org/wiki/Infinity).
### Rules
A valid program:
* Does not use [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default).
* Per connection:
+ Accepts connections and receive incoming data.
+ Sends outgoing data in an amount that is always less than or equal to the amount of data received.
* Does not invoke programs external to itself. (Spawning children to deal with multiple connections is fine, spinning up `inetd` or its local equivalent is not.)
* Does not use library functions specifically designed to start and maintain an echo service.
This is code golf, so lowest score wins.
[Answer]
# Python, ~~299~~ ~~295~~ ~~265~~ 263
```
from threading import*
from socket import*
a='',7;S=socket
u=S(2,2);u.bind(a)
def U():
while 1:u.sendto(*u.recvfrom(4**8))
Thread(None,U).start()
def C(c,x):
while c.send(c.recv(1)):1
s=S(2,1);s.bind(a);s.listen(1)
while 1:Thread(None,C,args=s.accept()).start()
```
handles both udp and tcp.
@MorganThrapp helped saving 33 (!) chars
[Answer]
# JavaScript (Node.js) 102 Bytes (51 \* 2)
```
require("net").createServer(s=>s.pipe(s)).listen(7)
```
You can add UDP for a total of **132 bytes**, as seen below:
```
require("net").createServer(s=>s.pipe(s)).listen(7),(u=require("dgram").createSocket("udp4")).on("message",msg=>u.send(msg)).bind(7)
```
Was tested on node.js v5.2.0
Make sure to run with `sudo` on Unix descendants (OS X, Linux, etc.)
[Answer]
# Racket, 231
```
(thread(λ()(do([l(tcp-listen 7)])(#f)(let-values([(i o)(tcp-accept l)])(copy-port i o)))))((λ(s b)(udp-bind! s #f 7)(do()(#f)(let-values([(n h p)(udp-receive! s b)])(udp-send-to s h p b 0 n))))(udp-open-socket)(make-bytes 65535))
```
TCP and UDP.
The TCP echo server uses a handy Racket procedure named `copy-port` that copies ports in the background, managed by Racket, instead of by the programmer. That also means I don't have to spin off a thread for each client, only for the listener (so I can start the UDP listener on the main thread).
] |
[Question]
[
You're going to replicate the 90's cup holder joke software.
Here's what's it did, and you have to do:
* Display the message `Do you need a cup holder?`
* If the user confirms, enter an infinite loop that keeps opening the CDROM drive.
* If the user doesn't confirm, silently exit.
You may display the message using either a console message (confirmation is `y`, decline is `n`), or display a message window with the two options "Yes" and "No". You can assume the default (or most common) CDROM drive (`D:` on Windows, `/cdrom` on linux etc.). Standard loopholes (except built-ins) are forbidden. No additional input nor output may be involved. If your PC has no physical drive, or another "style" of tray, make sure the program is valid.
[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest program in bytes wins.
Trivia: The loop is there to prevent anyone from closing the drive. On desktop drives, the re-open command will be sent while the drive is closing, therefore staying open and not "spilling the coffee".
[Answer]
# Bash, ~~115~~ ~~69~~ ~~68~~ 66 bytes
This was written on Mac OS X but it should work on other BSD-based systems as well.
```
echo Do you need a cup holder?;sed 1q|grep y&&yes drutil\ eject|sh
```
We `echo` the prompt, get input with `set 1q`, and determine whether the user confirmed with `grep y`. If the user said `y`, we pipe the infinite output of `yes` with the string `drutil eject` to the shell, which will continuously eject the disk tray.
Saved **50 bytes** thanks to Digital Trauma!
[Answer]
# Vitsy + Mac OSX bash, 55 bytes
```
'?redloh puc a deen uoy oD'ZWb2^/([1m]
<,'drutil eject'
```
Expects input as y or n. If it is n, it will execute line 2 (infinite loop with the shell command), otherwise, it will halt.
[Answer]
## Python (3.5) 84 bytes
```
import os
i=input("Do you need a cup holder?")
while i=='y':os.system("eject cdrom")
```
On linux
*edit: fix bytes count ;)*
[Answer]
## [AutoIt](http://autoitscript.com/forum), 85 bytes
```
If MsgBox(4,0,"Do you need a cup holder?")=7 Then Exit
Do
CDTray("D:","open")
Until 0
```
No one will ever answer anything in AutoIt anyway :)
[Answer]
## Python 3.5 on Windows 7, 135 Bytes
```
import ctypes
r=input('Do you need a cup holder?')
while r=='y':ctypes.windll.WINMM.mciSendStringW('set cdaudio door open',None,0,None)
```
] |
[Question]
[
Write a program that will produce differing behaviors on as many different platforms as you can. Each differing platform awards one point (including an initial platform, meaning you can't score less than 1\*). Mechanisms intended for determining the target/executing platform (e.g. through platform compilation statements or APIs like .NET's Environment.OSVersion.Platform) must not be used. The answer with the highest score wins (where upvotes are the tiebreakers).
For example, consider the following program in the Blub language: `print (1+2)`. If this program were to print `3` on every platform it is compiled and run on, its score would be 1. However, if, for any reason, it were to print `4` on PDP-11s, its score would be 2. Etc. But the following C snippet, for example, is an invalid entry: `#ifdef WIN32 ... #endif`.
---
Definitions/details:
* *Distinct platform:* the combination of a) the hardware architecture b) the OS and its MAJOR version number (e.g. 1.0.0 and 1.1.0 are considered the same OS)
* *Differing behavior:* two behaviors are the same [iff](https://en.wikipedia.org/wiki/If_and_only_if) they produce similar side-effects (e.g. creating the same file with the same contents), or if the side-effect are errors of the same kind. For example, if a program segfaults on two distinct platforms, but the segfault message is different on these platforms, this is still considered the same behavior; while a program producing a zero-division error on one platform and a stack overflow (see what I did there? ;) error on another is producing different behavior.
* All undefined behaviors are considered equivalent.
* Program must be invoked in an equivalent manner on all platforms (however; this does mean you can pass command-line parameters if you so desire)
---
\* Well, I guess you'd score zero if your program ran on zero platforms. But um... Yeah nevermind.
[Answer]
# C
I will take a stab at it with a textbook-like example:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[] = {1,2,3,4,5,6,7,8};
if (sizeof(&a) > sizeof(int)) {
printf("foo %d %d\n", *(int *)a, *(long *)a);
} else {
printf("bar %d %d\n", *(int *)a, *(long *)a);
}
}
```
64-bit Platform prints: foo
32-bit Platform prints: bar
Little Endian Platforms: 67305985
Big Endian Platforms: 16909060
So there is at least 4 combinations.
On top of that, some very old platforms has `int` defined as 16-bits. And some platform has `long` defined as 64-bits. So the result will be different as well.
C has been quite platform specific, if you dig deep enough. It is not hard to come up with thousands of combinations (2^10+).
[Answer]
## 16/32/64-bit x86/x64 assembly, 16 bytes, 4 combinations
Byte-code:
```
31 C9 41 E2 0A 66 49 41 74 05 0F 00 C0 03 C1 C3
```
Disassembly (16-bit):
```
xor cx, cx ;cx=0
inc cx ;cx=1
loop l1 ;fall through
dec cx ;cx=FFFF
inc ecx ;cx=0000
je l1 ;branch taken
;...
l1: ret
```
Disassembly (32-bit):
```
xor ecx, ecx ;ecx=0
inc ecx ;ecx=1
loop l1 ;fall through
dec cx ;ecx=0000FFFF
inc ecx ;ecx=00010000
je l1 ;branch not taken
sldt ax ;detect VMware, VirtualPC, Parallels, etc.
add ecx, eax ;conditionally modify ecx
l1: ret
```
Disassembly (64-bit):
```
xor ecx, ecx ;rcx=0 (implicit 64-bit zero-extension)
loopq l1 ;rcx becomes FFFFFFFFFFFFFFFF, branch taken
...
l1: ret
```
It returns:
- CX=0000 in 16-bit mode;
- ECX=10000 in 32-bit non-virtual mode;
- ECX=(random) in 32-bit virtual mode;
- RCX=FFFFFFFFFFFFFFFF in 64-bit mode.
] |
[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/52663/edit).
Closed 8 years ago.
[Improve this question](/posts/52663/edit)
The task is simple, post 2 code snippets that perform the same task, where one seems very optimized at first glance, but actually is significantly slower than the other.
Only one rule:
* Both snippets must finish with the exact same output (for the same given input, if any).
[Answer]
Python 3
Seems fast...
```
print(0 < 10**100 - 1 < 10**100)
```
Seems slow...
```
print(10**100 - 1 in range(0, 10**100))
```
But the two run in very similar times! `range` has an efficient implementation of `in`
] |
[Question]
[
In this task, we consider arrays of positive integers such as this:
```
3 18 321 17 4 4 51 1 293 17
```
The input comprises a pair of such arrays both of arbitrary, possibly distinct, positive length. Determine if a total ordering ≤X ⊂ **N** × **N**, where **N** is the set of positive integers, exists such that both input arrays are in order with respect to ≤X. Notice that (A ≤X B ∧ B ≤X A) ↔ A = B must hold, that is, two numbers are considered equal under ≤X if and only if they are the same number.
For example, if the input was the pair of arrays
```
7 2 1 1 4 12 3
9 8 7 2 5 1
```
then you are supposed to figure out if a total ordering ≤X exists such that
>
> 7 ≤X 2 ≤X 1 ≤X 1 ≤X 4 ≤X 12 ≤X 3
>
>
>
and
>
> 9 ≤X 8 ≤X 7 ≤X 2 ≤X 5 ≤X 1.
>
>
>
Your submission may be a subroutine or program that receives two arrays (as specified above) of input in an implementation-defined way, computes whether a total ordering ≤X satisfying the demands mentioned above exists and returns one value representing “yes” or a different value representing “no.” The choice of these values is arbitrary, please document them.
You may assume that the input arrays contain no more than 215 - 1 elements each and that each of their elements is in the range from 1 to 215 - 1 inclusive. You may require each arrays to be terminated by a constant sentinel outside of the aforementioned range such as 0. Please specify what sentinel is needed. You may require the lengths of the arrays as additional input if the length cannot be inferred from the arrays themselves (e. g. in languages like C). In addition to the prohibition of standard loopholes, you are not allowed to use topological sorting routines.
This challenge is code golf. The submission with the least amount of characters wins.
[Answer]
# Pyth, 28 22
```
L.AmqdSdmfhTmxhkbek^b2
```
Creates a function `y` that you can call with a tuple containing the two arrays. Returns "True" if a total ordering exists, "False" if not.
A helper program that defines and calls the above function with stdin:
```
L.AmqdSdmfhTmxhkbek^b2y,rw7rw7
```
[Try it here.](https://pyth.herokuapp.com/?code=L.AmqdSdmfhTmxhkbek%5Eb2y%2Crw7rw7+&input=7+2+1+1+4+12+3%0A9+8+7+2+5+1&debug=0)
We first read both arrays. Then we will create all combinations of both arrays. Then for each combination we will assume the first array is authoritative, and check if it's consistent with the second array.
[Answer]
# GolfScript, 25 bytes
```
:A{:a;A{.a--.{a?}$=!},},!
```
[Try this code online.](http://golfscript.apphb.com/?c=IyBJbnB1dCAoYXJyYXkgb2YgYXJyYXlzKToKW1s3IDIgMSAxIDQgMTIgM10gWzkgOCA3IDIgNSAxXV0KCiMgSXMgdGhlcmUgYSB0b3RhbCBvcmRlciBjb21wYXRpYmxlIHdpdGggYm90aCBpbnB1dCBhcnJheXM%2FCjpBezphO0F7LmEtLS57YT99JD0hfSx9LCE%3D)
Takes an array of two (or more!) arrays on the stack; returns 1 (true) if every pair of input arrays has a compatible total order, or 0 (false) otherwise.
It works by looping over every possible pair of input arrays (including each array paired with itself), sorting the elements in the first array according to the position where they first occur in the second one (ignoring those that are not found), and checking that the resulting order matches the original.
While this code can take an arbitrary number of input arrays, it's worth noting that it only checks for *pairwise* consistency. For example, it returns true for the input `[[1 2] [2 3] [3 1]]`, since any two of the three arrays do have a consistent total order. That's enough for the two-input case, though, which is all that the challenge requires.
Here's a de-golfed version with comments:
```
:A # save input to "A", and leave it on the stack to be looped over
{ # run this outer loop for each input array:
:a; # save this array to "a" (and pop it off the stack)
A{ # also run this inner loop for each input array:
.a-- # remove all elements not in "a" from this array
. # make a copy of the filtered array
{a?}$ # sort it by the first location of each element in "a"
=! # check whether the sorted copy differs from the original
}, # select those arrays for which there was a difference
}, # select those arrays for which at least one difference was found
! # return 1 if no differences were found, 0 otherwise
```
Ps. It would be possible to trivially save one or two bytes by requiring the input to be given directly in the named variable `A`, and/or by changing the output format to an empty array for "yes" and a non-empty array for "no". However, that would seem rather cheesy to me.
[Answer]
# J, ~~36~~ ~~30~~ 26 bytes
```
[:*/@,(e.~(-:/:~)@#i.)&>/~
```
Let's call the two input lists `a` and `b`. The function checks (with `(e.~(-:/:~)@#i.)`) whether
* `a`'s elements sorted (in regard to `a`) in `b`
* `a`'s elements sorted (in regard to `a`) in `a`
* `b`'s elements sorted (in regard to `b`) in `a`
* `b`'s elements sorted (in regard to `b`) in `b`
Input is a list of two integer vectors.
Result is `1` if an ordering exists `0` otherwise. (Runtime is O(n\*n).)
Usage:
```
f=.[:*/@,(e.~(-:/:~)@#i.)&>/~
a=.7 2 1 1 4 12 3 [b=.7 2 1 1 4 12 3 1 [c=.9 8 7 2 5 1
f a;c
1
f b;c
0
```
[Try it online here.](http://tryj.tk/)
[Answer]
# Ruby, 79
```
!!gets(p).scan(r=/\d+/){|s|$'[/.*/].scan(r){s!=$&&~/\b#$& .*\b#{s}\b/&&return}}
```
Expects input to be a two-line file of space-separated numbers. Returns `true` when an ordering exists, `nil` if it doesn't.
[Answer]
# Haskell, 98 bytes
```
import Data.List
a%b=intersect(r a)$r b
r l=map head$group l
c l=nub l==r l
x#y=c x&&c y&&x%y==y%x
```
Returns `True` or `False`. Example usage: `[7,2,1,1,4,12,3] # [9,8,7,2,5,1]` -> `True`.
How it works: remove consecutive duplicates from the input lists (e.g: `[1,2,2,3,2] -> [1,2,3,2]`. An order exists if both resulting lists do not contain duplicates and the intersection of list1 and list2 equals the intersection of list2 and list1.
] |
[Question]
[
A short while, ago, [@daniel\_ernston](https://twitter.com/daniel_ernston/) sent [the following challenge](https://twitter.com/daniel_ernston/status/574021732266172416) to [@StackCodeGolf](https://twitter.com/StackCodeGolf) on Twitter:
>
> [@StackCodeGolf](https://twitter.com/StackCodeGolf) Your task is to build a program that uses the API of your choice to tweet its own source code. Shortest code wins, of course.
>
>
>
[Answer]
### JavaScript, 38 characters
```
window.open("http://tinyurl.com/erjk34");
```
Here is the tweet, in all its glory: <https://twitter.com/kevinaworkman/status/575425948562014209>
And here is my previous entry at 95 characters:
```
function q() {
window.open("https://twitter.com/intent/tweet?text="+encodeURIComponent(q+";{q();}"));
};{q();}
```
### And if that's not cheating...
### HTML, 22 characters
<http://tinyurl.com/erjk35>
[Answer]
# [Python 2](https://docs.python.org/2/), 118 bytes
```
import webbrowser,urllib
webbrowser.open("https://twitter.com/intent/tweet?text="+urllib.quote(open(__file__).read()))
```
[(Can't) Try it online! (Run locally)](https://tio.run/##RctBCsIwEAXQvaeQrhKUBFwK4lGC0S8dSDMx/SX19LHowu2DV94cNZ96l6lo5b4hxqptRj0uNSWJu784LchmGMkyn71nE3LTu05eMpG5EcArsfIyHH7fvRYlzLeG8JSEEKyruD2Mtbb3Dw "Python 2 – Try It Online")
¯\\_(ツ)\_/¯
] |
[Question]
[
You are given integers `N` and `M`, `1 <= N,M <= 10^6` and indexes `i` and `j`. Your job is to find the integer at position `[i][j]`. The sequence looks like this (for `N=M=5, i=1, j=3` the result is `23`):
```
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
```
Shortest code wins. Good luck!
[Answer]
# Mathematica, ~~63~~ 55 bytes
```
f=If[#5<1,#+#4,f[#+#2,#3-1,#2,#5-1,#2-1-#4]]&;g=1~f~##&
```
This defines a function `g` which can be called like
```
g[5, 5, 1, 3]
```
I'm using a recursive approach. It uses up to *2(N+M)* iterations, depending on how far down the spiral the result is found. It does handle all inputs (up to `g[10^6,10^6,5^5-1,5^5]`, which requires the most iterations) within a few seconds, but for larger inputs, you'll need to increase the default iteration limit like
```
$IterationLimit = 10000000;
```
Basically, if `k` is the starting number of the spiral, I'm checking if the `j` index is `0` in which case I can just return `k + i`. Otherwise, I throw away the top row, rotate the spiral by 90 degrees (anti-clockwise), increment `k` accordingly, and look at the remaining spiral instead. We can move to the next spiral with the following mapping of parameters:
* *kn+1 = kn + mn*
* *Mn+1 = Nn - 1*
* *Nn+1 = Mn*
* *in+1 = jn - 1*
* *jn+1 = nm - in - 1*
This assumes that *M* is the width and *N* is the height.
[Answer]
# Pyth, 25 bytes
```
D(GHYZ)R?+G(tHGtZt-GY)ZhY
```
This defines a function, `(`. Example usage:
```
D(GHYZ)R?+G(tHGtZt-GY)ZhY(5 5 1 3
```
prints `23`.
This is algorithmically identical to the Mathematica answer by Martin Büttner, though it was developed independently. As far as I can tell, that's the only good way to do it.
Note that Pyth cannot handle the full input range on my machine, it will overflow the stack and die with a segfault on large inputs.
[Answer]
# Haskell, 44
```
z j i m n|j==0=i+1|0<1=z(n-i-1)(j-1)n(m-1)+n
```
this uses the regular recursive approach
] |
Subsets and Splits