text
stringlengths 180
608k
|
---|
[Question]
[
Given a ruler length in inches and fractions of an inch, and a granularity in fractions of an inch, output the values of all marks on the ruler, starting from 0, in ascending order.
Input ruler length will be a mixed fraction (integer and proper fraction)
Input granularity will be a proper fraction in the form `1/(2ⁿ)`, where `1 ≤ n ≤ 6`.
Output numbers will all be expressed similarly to the input. For values where the number of inches is a whole number, no fractional part will be expressed. For values where the number of inches is `0 < n < 1`, only the fractional part will be expressed.
If the input granularity is not fine enough to represent the ruler length, then the final number will be the closest representable number below the ruler length.
## Examples
Input `1` `1/2` would output:
```
0
1/2
1
```
Input `2 3/4` `1/8` would output:
```
0
1/8
1/4
3/8
1/2
5/8
3/4
7/8
1
1 1/8
1 1/4
1 3/8
1 1/2
1 5/8
1 3/4
1 7/8
2
2 1/8
2 1/4
2 3/8
2 1/2
2 5/8
2 3/4
```
Input `2 3/4` `1/2` would output:
```
0
1/2
1
1 1/2
2
2 1/2
```
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 38 bytes
```
KQz\/cebj*Bh Fj.DRIIid)ij.Hi'f jRf\/Rs
```
[Try it online!](https://tio.run/nexus/pyke#@@8dWBWjn5yalKXllKHglqXnEuTpmZmimZml55GpnqaQFZQWox9U/P@/kbaxvgmXob4JAA "Pyke – TIO Nexus")
Not too bad for a language that has literally no fractional support. Explanation later if at all.
[Answer]
## Mathematica, ~~55~~ 53 bytes
*Thanks to JungHwan Min for saving 2 bytes.*
```
DeleteCases[{a=Floor@#,#-a},0,1,1]&/@Range[0,+##2,#]&
```
Takes three numbers as input, the step width, the integer part of the ruler length, the fractional part of the ruler length.
Output is a list of lists with sublists like `{1}` or `{2, 3/4}`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 21 bytes
```
:"0"mȯwfI§e⌊%1↑≤Σ⁰¡+³
```
[Try it online!](https://tio.run/##ATYAyf9odXNr//86IjAibcivd2ZJwqdl4oyKJTHihpHiiaTOo@KBsMKhK8Kz////MS8y/1syLDMvNF0 "Husk – Try It Online")
Have to prepend a 0 string before, cause filtering out zeroes messes with it.
[Does anybody know how to run the Ohm answer?](https://tio.run/##y8/I/f/f0/PQIn1PT/1EfWUrlXgtHev//w31jRQMAQ "Ohm – Try It Online")
[Answer]
## Batch, 213 bytes
```
@echo off
set n=%4
set/an*=%1,n+=%2*%1/%3
for /l %%i in (0,1,%n%)do call:c %%i %1
exit/b
:c
set/ad=%2,i=%1/d,n=%1%%d
if %n%==0 echo %i%&exit/b
set/an/=p=n^&-n,d/=p
if %i% gtr 0 set n=%i% %n%
echo %n%/%d%
```
Takes 4 numbers as input:
1. The number of marks per inch i.e. the reciprocal/denominator of the granularity
2. The numerator of the ruler length
3. The denominator of the ruler length
4. (Optional) The whole number of inches of the ruler length
So for the second example the parameters would be `8 3 4 2`. Note that for lengths that are an exact number of integers you still need to specify a dummy fraction e.g. `4 0 1 2`, or an improper fraction `4 2 1` would also work.
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm), 17 bytes
```
II¢/II/a/#:$_*,;
```
Explanation:
```
II/¢II/a/#:$_*,; ■Main wire
II/¢ ■Evaluate fraction and save to register
II/ ■Evaluate another fraction
a/ ■Divide first by second evaluating to the required steps
#: ; ■foreach _ in range(0,steps){
$_*, ■ print (register * _)
■}
```
] |
[Question]
[
# Background:
In finance, the binomial options pricing model (BOPM) is the simplest technique used for option pricing. The mathematics behind the model is relatively easy to understand and (at least in their basic form) it is not difficult to implement. This model was first proposed by Cox, Ross, and Rubinstein in 1979. Quoting [Wikipedia](https://en.wikipedia.org/wiki/Binomial_options_pricing_model#Method):
>
> The binomial pricing model traces the evolution of the option's key underlying variables in discrete-time. This is done by means of a binomial lattice (tree), for a number of time steps between the valuation and expiration dates. Each node in the lattice represents a possible price of the underlying at a given point in time.
>
>
> Valuation is performed iteratively, starting at each of the final nodes (those that may be reached at the time of expiration), and then working backwards through the tree towards the first node (valuation date). The value computed at each stage is the value of the option at that point in time.
>
>
>
For this challenge's sake, we will create a simple model to predict potential future prices of the option(s) by creating a lattice or a tree as shown below (a picture is worth a thousand words):
[](https://i.stack.imgur.com/YdCGY.jpg)
where ***S*** is the option price today, ***p*** is the probability of a price rise, and ***t*** is the period of time or number of steps.
# Challenge:
The challenge is to write either a program or a function which take ***S***, ***p*** (in percent), and ***t*** as the inputs and give the binomial tree as the output. The output of the program or the function **must** follow the format above, but the boxes and the arrow lines are optional. For example, if the program take inputs `S = 100`, `p = 10%`, and `t = 3`, then its output may be in the following simple form:
```
133.1
121
110 108.9
100 99
90 89.1
81
72.9
```
# General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins the challenge.
Don't let esolangs discourage you from posting an answer with regular languages. Enjoy this challenge by providing an answer as short as possible with your programming language. If you post a clever answer and a clear explanation, your answer will be appreciated (hence the upvotes) regardless of the programming language you use.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/ method with the proper parameters, full programs, etc. The choice is yours.
* Using a binomial tree built-in is forbidden.
* If possible, your program can properly handle a large number of steps. If not, that will just be fine.
# References:
1. [Binomial options pricing model](https://www.google.co.id/search?q=binomial+tree)
2. [Binomial tree option calculator](http://www.hoadley.net/options/binomialtree.aspx?)
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~60~~ 56 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
Needs `⎕IO←0` which is default on many systems. Prompts for ***S*** then ***t*** then ***p***.
```
⍉{⍵⌽⍨-⌽⍳≢⍵}↑{⍵\⍨0 1⍴⍨2×≢⍵}¨⍕¨¨⎕{⍵,⊂∪∊(⊃⌽⍵)∘.×1+⍺,-⍺}⍣⎕⊢⎕
```
Over 50% of the code is to get the right display form.
[TryAPL online!](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20%u2206%u2190100%203%200.1%20%u22C4%20%u2355%20%20%u2349%7B%u2375%u233D%u2368-%u233D%u2373%u2262%u2375%7D%u2191%7B%u2375%5C%u23680%201%u2374%u23682%D7%u2262%u2375%7D%A8%u2355%A8%A8%282%u2283%u2206%29%7B%u2375%2C%u2282%u222A%u220A%28%u2283%u233D%u2375%29%u2218.%D71+%u237A%2C-%u237A%7D%u2363%281%u2283%u2206%29%u22A2%280%u2283%u2206%29&run) (`]Box off` for proper display – the default on installed systems – emulated here using `⍕`.)
Example run:
```
133.1
121
110 108.9
100 99
90 89.1
81
72.9
```
[Answer]
# Python, ~~168~~ 167 bytes
```
q=lambda s,p,t:'\n'.join(''.join('%e'%(s*(1+p)**(c-(r+c-t)//2)*(1-p)**((r+c-t)//2))if(t-c<=r<=t+c)&(r%2^(c+~t%2)%2)else' '*12for c in range(t+1))for r in range(2*t+1))
```
Test case with anonymous function above assigned to `f` would be `print(f(100,0.1,3))`, yielding:
```
1.331000e+02
1.210000e+02
1.100000e+02 1.089000e+02
1.000000e+02 9.900000e+01
9.000000e+01 8.910000e+01
8.100000e+01
7.290000e+01
```
Extending the same to t=4 would be `print(f(100,0.1,3))`, yielding:
```
1.464100e+02
1.331000e+02
1.210000e+02 1.197900e+02
1.100000e+02 1.089000e+02
1.000000e+02 9.900000e+01 9.801000e+01
9.000000e+01 8.910000e+01
8.100000e+01 8.019000e+01
7.290000e+01
6.561000e+01
```
---
For the avoidance of scientific notation while keeping at least 3 significant figures we can use the following **211 byte** code instead:
```
lambda s,p,t:'\n'.join(''.join('%12s'%(v and(10**5>v>.0001and'%f'%v or'%e'%v)or'')for v in[(t-c<=r<=t+c)&(r%2^(c+~t%2)%2)and s*(1+p)**(c-(r+c-t)//2)*(1-p)**((r+c-t)//2)for c in range(t+1)])for r in range(2*t+1))
```
Test case, `print(f(100,0.1,3))` yields:
```
133.100000
121.000000
110.000000 108.900000
100.000000 99.000000
90.000000 89.100000
81.000000
72.900000
```
then when numbers get too big or small, for example `print(f(9876.000123,0.99,6))`:
```
6.133375e+05
3.082098e+05
1.548793e+05 3082.098178
77828.796693 1548.793054
39109.948087 778.287967 15.487931
19653.240245 391.099481 7.782880
9876.000123 196.532402 3.910995 0.077829
98.760001 1.965324 0.039110
0.987600 0.019653 0.000391
0.009876 0.000197
9.876000e-05 1.965324e-06
9.876000e-07
9.876000e-09
```
[Answer]
# R, 288 bytes
```
x=scan()
M=Map
U=rbind
noquote(t(do.call(U,M(function(x,y){r=rep;c(r(" ",x),rev(as.vector(U(y,r(" ",length(y))))),r(" ",x))},as.list(x[3]:0),M(function(x,y){sapply(y,function(y)(1-x[2])^y[1]*(1+x[2])^y[2]*x[1])},list(x),lapply(0:x[3],function(y)data.frame(do.call(U,list(y:0, 0:y)))))))))
```
Sometimes I feel like I'm not even golfing. The maximum t is limited by the amount of system memory. The readability of output is determined by the resolution of your screen/console size. If we write to file instead, the readability limitations can be bypassed. I was able to run t = 5000, 100, 0.1 on my 16GB ram system; the output is 400+ mb plain text file.
```
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,]
[2,] 285.311670611
[3,] 259.37424601
[4,] 235.7947691 233.436821409
[5,] 214.358881 212.21529219
[6,] 194.87171 192.9229929 190.993762971
[7,] 177.1561 175.384539 173.63069361
[8,] 161.051 159.44049 157.8460851 156.267624249
[9,] 146.41 144.9459 143.496441 142.06147659
[10,] 133.1 131.769 130.45131 129.1467969 127.855328931
[11,] 121 119.79 118.5921 117.406179 116.23211721
[12,] 110 108.9 107.811 106.73289 105.6655611 104.608905489
[13,] 100 99 98.01 97.0299 96.059601 95.0990049900001
[14,] 90 89.1 88.209 87.32691 86.4536409000001 85.5891044910001
[15,] 81 80.19 79.3881 78.594219 77.80827681
[16,] 72.9 72.171 71.44929 70.7347971000001 70.027449129
[17,] 65.61 64.9539 64.304361 63.66131739
[18,] 59.049 58.45851 57.8739249 57.295185651
[19,] 53.1441 52.612659 52.08653241
[20,] 47.82969 47.3513931 46.877879169
[21,] 43.046721 42.61625379
[22,] 38.7420489 38.354628411
[23,] 34.86784401
[24,] 31.381059609
```
t = 5000;
[](https://i.stack.imgur.com/P9iHJ.png)
] |
[Question]
[
Today is [Tax Day](https://en.wikipedia.org/wiki/Tax_Day)!
Oops.
Well, [today is tax day if you are a resident of Maine or Massachusetts](https://www.irs.com/articles/tax-deadline-alert-2015-tax-returns-are-due-april-18-2016).
So you're probably still completing your return and need a calculator for when you get to [Line 44](https://www.irs.gov/pub/irs-pdf/f1040.pdf).
Given an input of taxable income (US$, accurate to 2 decimal places) and a string representing filing status, output the amount of tax (also US$ to 2 decimal places).
Filing status will be one of `S`, `MFJ`, `QW`, `MFS`, or `HH` for Single, Married Filing Jointly, Qualified Widow(er), Married Filing Separately or Head of Household, respectively.
* Tax will be calculated according to the official tables in [IRS Revenue Procedure 2014-61, section .01 Tax Rate Tables, Tables 1-4](https://www.irs.gov/pub/irs-drop/rp-14-61.pdf). I have added these tables at the bottom of the question.
* You may choose whatever rounding method you like, as long as the result is accurate to 2 decimal places.
### Example Inputs:
```
0.00 S
10000.00 MFJ
100000.00 MFS
1000000.00 QW
```
### Example Outputs corresponding to above inputs:
```
0.00
1000.00
21525.75
341915.90
```
---
# Summary of tax tables.
### Married Filing Jointly and Qualified Widow(er)
>
> `Income Interval Tax
> [ $0, $18450] 10%
> ( $18450, $74900] $1845 + 15% of the excess over $18450
> ( $74900, $151200] $10312.50 + 25% of the excess over $74900
> ($151200, $230450] $29387.50 + 28% of the excess over $151200
> ($230450, $411500] $51577.50 + 33% of the excess over $230450
> ($411500, $464850] $111324 + 35% of the excess over $411500
> ($464850, $∞] $129996.50 + 39.6% of the excess over $464850`
>
>
>
### Head of Household
>
> `Income Interval Tax
> [ $0, $13150] 10%
> ( $13150, $50200] $1315 + 15% of the excess over $13150
> ( $50200, $129600] $6872.50 + 25% of the excess over $50200
> ($129600, $209850] $26722.50 + 28% of the excess over $129600
> ($209850, $411500] $49192.50 + 33% of the excess over $209850
> ($411500, $439000] $115737 + 35% of the excess over $411500
> ($439000, $∞] $125362 + 39.6% of the excess over $439000`
>
>
>
### Single
>
> `Income Interval Tax
> [ $0, $9225] 10%
> ( $9225, $37450] $922.50 + 15% of the excess over $9225
> ( $37450, $90750] $5156.25 + 25% of the excess over $37450
> ( $90750, $189300] $18481.25 + 28% of the excess over $90750
> ($189300, $411500] $46075.25 + 33% of the excess over $189300
> ($411500, $413200] $119401.25 + 35% of the excess over $411500
> ($413200, $∞] $119996.25 + 39.6% of the excess over $413200`
>
>
>
### Married Filing Separately
>
> `Income Interval Tax
> [ $0, $9225] 10%
> ( $9225, $37450] $922.50 + 15% of the excess over $9225
> ( $37450, $75600] $5156.25 + 25% of the excess over $37450
> ( $75600, $115225] $14693.75 + 28% of the excess over $75600
> ($115225, $205750] $25788.75 + 33% of the excess over $115225
> ($205750, $232425] $55662 + 35% of the excess over $205750
> ($232425, $∞] $64998.25 + 39.6% of the excess over $232425`
>
>
>
[Answer]
## Python 3, ~~427~~ ~~382~~ ~~317~~ ~~309~~ ~~308~~ 275 bytes
*-45 bytes by figuring ternary expression out (wow that's a long line); thanks [Maltysen](https://codegolf.stackexchange.com/users/31343/)*
*-65 bytes, now with iteration for DRYer code!*
*-8 bytes by in-lining tuple variables; thanks [Majora](https://codegolf.stackexchange.com/users/53146)*
*-1 byte by using a dict rather than ternary chain; thanks again [Maltysen](https://codegolf.stackexchange.com/users/31343/)*
*-33 bytes by reusing `MFS` step as half of `MFJ`/`QW` and calculating tax an order of magnitude larger; thanks [Neil](https://codegolf.stackexchange.com/users/17602)*
```
def f(i,s):
t=i;k={'MFS':(9225,28225,38150,39625,90525,26675),'S':(9225,28225,53300,98550,222200,1700),'HH':(13150,37050,79400,80250,201650,27500)}
for x in range(6):
i-=k[s][x]if s in k else k['MFS'][x]*2
if i>0:t+=(.5,1,.3,.5,.2,.46)[x]*i
return'{:.2f}'.format(t*.1)
```
If I had been thinking I would have made the function signature `t(a,x)`, but I guess I'll stick with `f`unction(`i`ncome, `s`tatus).
When code is barely undertstood by the writer, is that when you win at golf?
[Answer]
## JavaScript (ES6), 223 bytes
```
(i,s)=>(({MFS:a=[x=9225,y=28225,38150,39625,90525,26675],S:[x,y,53300,98550,222200,1700],HH:[13150,37050,79400,80250,201650,27500]}[s]||a.map(b=>b*2)).reduce((t,b,j)=>t+((i-=b)>0&&i*[.5,1,.3,.5,.2,.46][j]),i)*.1).toFixed(2)
```
Basically a port of CAD97's Python answer, but I saved 4 bytes by multiplying the tax by 10 during the calculation and 11 bytes by reducing the duplication in the tax bands.
] |
[Question]
[
The basic idea is to write a program that [twists](https://codegolf.stackexchange.com/questions/70696/golf-a-string-twister) itself, and the twisted version untwists itself. The first program will just be the twisting algorithm described here, and when given its own source code as input, outputs a program that reverses the twisting algorithm.
## How strings are twisted
The twisting algorithm is very simple. Each column is shifted down by its index (col 0 moves down 0, col 1 moves 1, ...). The column shift wraps to the top. It kinda looks like this:
```
a
ba
cba
----
cba
cb
c
```
With everything under the line wrapping to the top. Real example:
```
Original:
\\\\\\\\\\\\
............
............
............
Twisted:
\...\...\...
.\...\...\..
..\...\...\.
...\...\...\
```
(Further examples are [here](https://codegolf.stackexchange.com/questions/70696/golf-a-string-twister))
## Input
Input is either an array of strings, or a multi-line string. All lines have the same length.
## Output
The (un)twisted string, multi-line output to std-out (or closest alternative).
### Example
I'm not quite sure what this is written in but oh well ;)
```
Twisting:
magic TwistingAlgo
magic ntwistingAlgo
magicU twistingAlgo
Untwisting:
magic twistingAlgo
magicUnTwistingAlgo
magic twistingAlgo
```
# Other notes
* Your first and second program must be in the same language.
* The programs must work for any input, not just itself.
* Your program must have at least 2 rows and 2 columns.
[Answer]
# Japt, 63 bytes
```
Uy m@XsV=(Y*Xl +Y %Xl)+X¯V}R y;
Uy m@XsV=(Y*Xl -Y %Xl)+X¯V}R y;
```
Twisted:
```
Uy m@XsV=(Y*Xl -Y %Xl)+X¯V}R y;
Uy m@XsV=(Y*Xl +Y %Xl)+X¯V}R y;
```
Test it online: [Original](http://ethproductions.github.io/japt?v=master&code=VXkgbUBYc1Y9KFkqWGwgK1kgJVhsKStYr1Z9UiB5OwpVeSBtQFhzVj0oWSpYbCAtWSAlWGwpK1ivVn1SIHk7&input=IlxcXFxcXFxcXFxcXAouLi4uLi4uLi4uLi4KLi4uLi4uLi4uLi4uCi4uLi4uLi4uLi4uLiI=), [Twisted](http://ethproductions.github.io/japt?v=master&code=VXkgbUBYc1Y9KFkqWGwgLVkgJVhsKStYr1Z9UiB5OwpVeSBtQFhzVj0oWSpYbCArWSAlWGwpK1ivVn1SIHk7&input=IlwuLi5cLi4uXC4uLgouXC4uLlwuLi5cLi4KLi5cLi4uXC4uLlwuCi4uLlwuLi5cLi4uXCI=)
### How it works
I hadn't posted yet on the original twisting challenge, but the shortest answer I could come up with is 31 bytes:
```
Uy m@XsV=(Y*Xl -Y %Xl)+X¯V}R y;
```
The untwisting algorithm I came up with is a lot shorter:
```
Uy m@XsV=Y%Xl)+X¯V}R y;
```
However, this won't work very well when intertwined with the other program. Fortunately, there's a way to make the two more similar:
```
Uy m@XsV=(Y*Xl -Y %Xl)+X¯V}R y;
Uy m@XsV=(Y*Xl +Y %Xl)+X¯V}R y;
```
Now all that's different between the two is the `+`/`-`, which is already properly aligned to switch places when twisted!
```
Uy m@XsV=(Y*Xl -Y %Xl)+X¯V}R y;
Uy // Transpose rows and columns in U.
m@ }R // Map each item X and index Y in the result, split at newlines, to:
Y*Xl -Y // Take Y times X.length and subtract Y.
%Xl) // Modulate the result by X.length.
XsV= // Set V to the result of this, and slice off the first V chars of X.
+X¯V // Concatenate this with the first V chars of X.
y; // Transpose the result again.
// Implicit: output *last* expression
```
[Answer]
## Haskell, 235 bytes
```
main=interact$unlines.g.lines;g l@("":_)=l; g l|t<-tail<$>l,n<-length t=zipWith(:)(head<$>l)$ g$take n$drop(n-1)$t++t
maim=interact$unlines.h.lines;h l@("":_)=l; h l|t<-tail<$>l,n<-length t=zipWith(:)(head<$>l)$ h$take n$drop(2-1)$t++t
```
and twisted by itself:
```
maim=interact$unlines.g.lines;g l@("":_)=l; g l|t<-tail<$>l,n<-length t=zipWith(:)(head<$>l)$ g$take n$drop(n-1)$t++t
main=interact$unlines.h.lines;h l@("":_)=l; h l|t<-tail<$>l,n<-length t=zipWith(:)(head<$>l)$ h$take n$drop(2-1)$t++t
```
This is a full program. Both lines are mostly the same so that they are not messed up. The differences are:
```
normal twisted
=================================
main= maim= -- after twisting the second lines defines the main function
maim= main= -- the other defines an unused function maim
g g -- As I cannot define a function (say f) multiple times,
h h -- I need different names for the function in both lines
n-1 n-1 -- this is for the different functionalities (twisting up /
2-1 2-1 -- twisting down). When calling g/h recursively I go with the
-- rest of each input line. To twist down, I drop (length n) -1
-- chars of two copies of the line. To twist up, I drop 2-1 chars
-- Then cut to the original length.
--
-- e.g. 2222 two 2222 twist 4444 twist 3333
3333 copies 3333 down 2222 up 4444
4444 4444 -> 3333 -> 2222
2222 drop 2 drop 1
3333
4444
```
[Answer]
## CJam, 21 bytes
```
qN/zee::m>
zN*z e#: <
```
[Test it here.](http://cjam.aditsu.net/#code=qN%2Fzee%3A%3Am%3E%0AzN*z%20e%23%3A%20%3C&input=Hello%2C%20world!%0AI%20am%20another%20%0Astring%20to%20be%20%0Atwisted!%20%20%20%20%20)
When you twist it, you get:
```
qN/zee::m<
zN*z e#: >
```
### Explanation
This is based [on my CJam answer to the original challenge](https://codegolf.stackexchange.com/a/70699/8478) and works basically the same.
The `e#` is a comment, so we can ignore it and the stuff after it. The means the code boils down to
```
qN/zee::m>zN*z
```
Which is the same as in the previous answer, plus a trailing `z` which just wraps the string in an array but that doesn't affect the output.
Notice that the two rows match up in all columns which are rotated (`N`, `z`, `e`, `:`) except for the last one. That means all the twisting will do is swap `>` and `<` which switches the direction of the column rotation.
] |
[Question]
[
## Background
This challenge is about the [stochastic block model](https://en.wikipedia.org/wiki/Stochastic_block_model).
Basically, you are given an undirected graph, where the nodes represent people, and the edges represent social connections between them.
The people are divided into two "communities", and two people are more likely to have a connection if they are in the same community.
Your task is to guess these hidden communities based on the connections.
## Input
Your input is a 2D array of bits of size 100×100.
It represents the adjacency matrix of an undirected graph of size 100.
The graph is generated by the following random process:
* Each node is placed in community 0 with probability 0.5, otherwise it's placed in community 1. **The communities are not visible in the input.**
* For each pair of distinct nodes that are in the same community, put an edge between them with probability 0.3.
* For each pair of distinct nodes that are in different communities, put an edge between them with probability 0.1.
All random choices are independent.
## Output
Your output is a 1D array of bits of length 100.
It represents your program's guess about the underlying communities.
You are not required to correctly guess which nodes belong to community 0 and which to community 1 (which would be impossible), just the partition into two communities.
## Scoring
In [this repository](https://github.com/iatorm/random-data), you'll find a text file containing 30 lines.
Each line represents a graph generated by the above process, and it consists of the array of the hidden communities, a semicolon, and a comma-separated list of rows of the adjacency matrix.
You should read this text file, call your submission program on the adjacency matrix of each line, and compare its output to the underlying community structure.
Your submission's score on a particular graph is
```
min(sum_i(V[i] == W[i]), sum_i(V[i] == 1-W[i]))
```
where `V` is the array of hidden communities, `W` is your program's guess based on the adjacency matrix, and `i` ranges over their indices.
Basically, this measures the number of mis-classified nodes, taking into account that you're not required to guess which community is which.
The **lowest average score** over all 30 test cases wins, with byte count used as a tie breaker.
## Example
Consider the input matrix (6×6 for clarity)
```
011000
101100
110000
010011
000101
000110
```
It corresponds to the 6-node graph
```
a-b-d
|/ /|
c e-f
```
consisting of two triangles with one edge between them.
Your program might guess that each triangle is a separate community, and output `000111`, where the first three nodes are in community 0 and the rest in community 1.
The output `111000` is equivalent, since the order of the communities doesn't matter.
If the true community structure was `001111`, then your score would be `1`, because one node is mis-classified.
## Additional rules
Your program should take no more than **5 seconds** on any single test case on a reasonably modern computer (I'm unable to test most answers, so I'll just trust you here).
You can write a full program or a function, and standard loopholes are disallowed.
You are allowed to optimize your answer toward the parameters used here (size 100, probabilities 0.3 and 0.1), but not the actual test cases.
I keep the right to generate a new set of graphs if I suspect foul play.
## Test program
Here's a Python 3 function that computes the score of a Python 3 function submission.
```
import time
def test_from_file(submission, filename):
f = open(filename)
num_graphs = 0
total_score = 0
for line in f:
num_graphs += 1
a, _, c = line.partition(';')
V = [int(node) for node in a]
E = [[int(node) for node in row] for row in c[:-1].split(',')]
start = time.perf_counter()
W = submission(E)
end = time.perf_counter()
x = sum(V[i]==W[i] for i in range(len(V)))
score = min(x, len(V) - x)
print("Scored {0:>2d} in {1:f} seconds".format(score, end - start))
total_score += score
f.close()
return total_score / num_graphs
```
[Answer]
## R, 16/30 = 0.53333...
---
### Edit:
Here is a version that has been golfed down to 259 bytes. I am sure a much better bytecount is possible. This version takes advantage of the fact that `T` is a global variable in R which can be treated as having a value of 1. If `T` has been reassigned in your R environment, results may differ.
The code produces some warnings, but they can be ignored.
```
f=function(A){L=function(p){q=1-p;z=.1*p%o%q;x=z+t(z)+.3*(p%o%p+q%o%q);c(sum(log(x^A*(1-x)^(1-A))),(A/x-(1-A)/(1-x))%*%(2*p-1))};x=tanh(rnorm(100))/2+.5;for(i in x){t=.5+tanh(atanh(2*x-1)+T*2*(L(x)[2:101]>0)-T)/2;if(L(t)>L(x)){x=t;T=2*T}else{T=T/2}};round(x)}
```
If the adjacency matrix of your graph is saved as a 100x100 matrix `A` in R, then the vector of communities is `f(A)`. It will probably make less than one mistake!
---
### Explanation
It treats the problem as fitting a statistical model (it helps that it knows the values 0.3 and 0.1) and fits it using a sort of gradient ascent algorithm. The community membership vector is treated as containing values in [0,1], rather than just zeroes and ones. This enables the model to be fitted using a sort of gradient ascent. (Ascent and descent is actually by a fixed amount `delta` in each coordinate, to avoid various problems. If a step of gradient ascent fails, `delta` is adjusted down.) It's quite fast and does pretty well.
I used today's date as the random seed.
```
LL <- function(p, A){
# log-lieklihood of the model
q <- 1-p
x <- 0.1*(p %o% q) + 0.1*(q %o% p) + 0.3*(p %o% p) + 0.3*(q %o% q)
sum(A*log(x) + (1-A)*log(1-x))
}
expit <- function(x) exp(x)/(1+exp(x))
gradLL <- function(p, A){
# (scalar multiple of) the gradient of the log-likelihood
q <- 1-p
x <- 0.1*(p %o% q) + 0.1*(q %o% p) + 0.3*(p %o% p) + 0.3*(q %o% q)
drop((A/x - (1-A)/(1-x)) %*% (0.4*p - 0.2))
}
fit_model <- function(A, N=100){
# gradient ascent
x <- rnorm(100)
score <- LL(expit(x), A)
delta <- 1
for (i in 1:N){
grad <- gradLL(expit(x), A)
test <- x + delta*((grad > 0) - (grad < 0))
test_score <- LL(expit(test), A)
if (test_score > score){
score <- test_score
x <- test
#print(score)
delta <- (1/0.7)*delta
} else {
delta <- 0.7*delta
}
}
round(expit(x))
}
generate_A <- function(){
# generate a matrix for testing
comms <- sample(0:1, 100, replace=T)
A <- matrix(rep(0, 100^2), nc=100)
for (i in 1:(nrow(A)-1)){
for (j in (i+1):ncol(A)){
prob <- ifelse(comms[i]==comms[j], 0.3, 0.1)
if (runif(1) < prob) A[i,j] <- 1
}
}
A <- (A + t(A))/2
list(A=A, comms=comms)
}
test <- function(){
# test the fitting function once
dat <- generate_A()
fit <- fit_model(dat$A)
sum(fit==dat$comms)
}
### performance ###
strings <- readLines("community-graphs.txt", 30)
total <- 0
set.seed(011215) # note that output is random!
for (i in 1:30){
str_data <- strsplit(strings[i], ";")[[1]]
comms <- as.numeric(strsplit(str_data[1], "")[[1]])
A_str <- strsplit(str_data[2], ",")[[1]]
A <- matrix(rep(0, 100^2), nc=100)
for (r in 1:100){
A[r,] <- as.numeric(strsplit(A_str[r], "")[[1]])
}
out <- fit_model(A)
total <- total + min(sum(out==comms), sum(out!=comms))
}
total # 16
```
[Answer]
# JavaScript (ES6), Score 16.83
Just a quick and simple solution that doesn't get a very good score. I know this isn't [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") but here's my (lightly golfed) solution in 134 bytes:
```
m=>(l=m.split`,`,n=l.map((_,i)=>[!i,0]),l.map((g,a)=>[...g].map((h,b)=>n[b][n[a][0]<n[a][1]==h|0]++)),n.map(g=>o+=g[0]<g[1]|0,o=""),o)
```
## Explanation
```
m=>( // m = comma delimited input matrix string
// Initialisation
l=m.split`,`, // l = input matrix as array
n=l.map((_,i)=> // n = array of each node with a count of their
// graphs to nodes of each community
[!i,0] // initialise the first node to community 0
),
// Find graphs
l.map( // compute each node
(g,a)=> // a = index of node A, g = graphs of node A
[...g].map( // compute each of the node's graphs
(h,b)=> // b = index of node B
// h = 1 if node A has a graph to node B
n[b][n[a][0]<n[a][1]==h|0]++ // increment node B's number of graphs to node A's
) // community if they have a graph, else
), // assume and increment the other community
// Output the results
n.map( // iterate over the graphs
g=> // g = current node's graphs
o+=g[0]<g[1]|0, // add the number of the predominant community to
// the output
o="" // o = output string
),
o // return o
)
```
## Possible Improvements
* I could implement two passes in the "Find graphs" step, with the first pass getting the probable community of each node and reinitialising each node to that community
## Test
```
var solution = m=>(l=m.split`,`,n=l.map((_,i)=>[!i,0]),l.map((g,a)=>[...g].map((h,b)=>n[b][n[a][0]<n[a][1]==h|0]++)),n.map(g=>o+=g[0]<g[1]|0,o=""),o);
function test() {
var lines = input.value.split("\n"),
output = [],
totalScore = 0;
for(var i = 0; i < lines.length; i++) {
var parts = lines[i].split(";"),
correct = parts[0],
matrix = parts[1],
result = solution(matrix);
var sum = 0,
sumInverse= 0;
for(var c = 0; c < correct.length; c++) {
if(correct[c] == result[c]) sum++;
}
for(var c = 0; c < correct.length; c++) {
if(correct[c] == 1 - result[c]) sumInverse++;
}
var score = Math.min(sum, sumInverse);
totalScore += score;
output.push("Test " + (i + 1) + ": Score = " + score + ", Result = " + result);
}
output.splice(0, 0, "Average Score: " + (totalScore / lines.length));
results.innerHTML = output.join("\n");
}
```
```
Enter the correct result followed by ";" then the input matrix delimited by ",".<br />
Put each test on a separate line.<br />
<textarea id="input" rows="5" cols="60">111000;011000,101100,110000,010011,000101,000110</textarea><br />
<button onclick="test()">Go</button>
<pre id="results"></pre>
```
[Answer]
## Mathematica, score 31/15 = 2.066666...
```
Range[100]/.Thread[Alternatives@@@FindGraphCommunities[AdjacencyGraph[#,Method->{"Modularity","StopTest"->(Length[#2]==2&)}]]->{0,1}]&
```
Please don't make me recalculate the score.
] |
[Question]
[
## **The Challenge**
The game *Light Up!* is a simple puzzle game where the objective is to light up every cell in an *n*-by-*n* array with light bulbs. However, there are blocks in the way that will prevent light from traveling, and no lightbulb can be places such that another lightbulb shines light on it. Each light bulb has light coming from it in only the **horizontal** and **vertical** directions.
You must make a program that takes in an array of 5 numbers. Your program must convert each numbers into a 5-bit binary number, which will define at what places in the array there are blocks. If there is a 1, there is a block at the spot, but if there is a 0, there is not a block. Each number converted to binary defines a row, like:
`[5,6,5,6,5] -> [00101, 00110, 00101, 00110, 00101] ->`
```
. . B . B
. . B B .
. . B . B
. . B B .
. . B . B
```
Where B = blocks that block light
Your program must take this array and find the solutions (places where you need to put light) and give it back as an array of 5 numbers.
## **Example:**
Input: `[1,5,9,13,17]`
Which translates to `[00001, 00101, 01001, 01101, 10001]`
Making the array:
```
. . . . B
. . B . B
. B . . B
. B B . B
B . . . B
```
A solution for this array is
```
L ~ ~ ~ B
~ L B ~ B
~ B ~ L B
~ B B ~ B
B L ~ ~ B
```
~ = Light
L = Lightbulb
Which gives the binary array of lights `[10000, 01000, 00010, 00000, 01000]`
And translates back to `[16, 8, 2, 0, 8]`
Output: `[16, 8, 2, 0, 8]`
## **Rules**
* Two lightbulbs can not be in the same row or column if there is no block between them.
* A lightbulb's light can only travel horizontally and vertically, and will stop if there is a block in the way
* Your program must take in an array `[a,b,c,d,e]` and output in the same form
* If there are no way the array can be solved, your program must not give output or state "No Output."
* This is a [code-golf] challenge, lowest amount in bytes wins!
[Answer]
# CJam, ~~79~~ ~~73~~ 68 bytes
```
32q~:Q,m*{Q.&:|!},{Q]{2b5Ue[}f%~..-_z]{Wa/_1fb.f|1a*}f%~z..|:|1a=}=p
```
This will work only using the Java interpreter. It should terminate *eventually* with default switches, but it becomes reasonably fast by increasing the maximum heap size.
At the cost of 7 more bytes (for a total of **75 bytes**), we can speed up the code significantly.
```
q~32b:Q;Y25#{Q&!},{Q]{2b25Ue[}/.m5/_z]{Wa/_1fb.f|1a*}f%~z..|:|1a=}=32bU5e[p
```
It still requires a little patience, but you can this version online in the [CJam interpreter](http://meta.codegolf.stackexchange.com/a/4781).
### Test run
```
$ alias='java -jar -Xmx4G /usr/local/share/cjam/cjam-0.6.5.jar'
$ time cjam lights-short.cjam <<< '[1 5 9 13 17]'
[2 8 4 16 4]
real 0m44.287s
user 3m47.426s
sys 0m1.821s
$ time cjam lights-fast.cjam <<< '[1 5 9 13 17]'
[2 8 4 16 4]
real 0m1.926s
user 0m2.383s
sys 0m0.098s
```
This gives us the following solution for the test case:
```
. . . L B
. L B . B
. B L . B
L B B . B
B . L . B
```
### Idea
For a given vector of wall placements, we iterate over all **33,554,432** vectors of light bulb placements, searching for one that satisfies the criteria.
If the bitwise AND of any pair of corresponding integers is non-zero, the spot is occupied by both a wall and a light bulb. We immediately discard such vectors.
We now convert the integers of wall and bulb placements to binary and subtract the resulting two-dimensional arrays. The result is a single 5 × 5 array, where **0** indices an empty space, **1** indicates a light bulb and **-1** indicates a wall.
We take this array and its transpose, and do the following for each row of each of them:
* For all runs of non-walls, we replace each **0** or **1** with the number of **1**s in this run.
* Then, we replace the **-1**s with **1**s.
We transpose the second array again (effectively applying the above to its *columns*) and take the element-wise bitwise OR of both arrays.
If there is any **0** left, the corresponding spot is not reached by light. Likewise, if there is any number greater than **1**, the are two non-separated light bulbs in the same row or column. Thus, a valid solution with produce an array that consists entirely of **1**s.
### Code
```
32q~:Q e# Push 32, evaluate the input, and store the result in Q.
,m* e# Get the length of Q (5) and push the vectors of {0, ..., 31}^5.
{ e# Filter; for each vector V:
Q.& e# Take the bitwise and of the elements of V and Q.
:|! e# Bitwise OR the results, and apply logical NOT.
}, e# Keep V if the result was 1.
{ e# Find; for each vector V:
Q] e# Push Q and wrap V and Q in a array.
{ e# Map the following block over each of them:
2b e# Convert the component to base 2.
5Ue[ e# Left-pad with 0s to a length of 5.
}f% e#
~ e# Dump the modified V and Q on the stack.
..- e# Apply doubly vectorized subtraction.
_z] e# Push a transposed copy of the result. Wrap both in an array.
{ e# Map the following block over each of them:
Wa/ e# Split at -1.
_1fb e# Add the integers of each chunk to count the number of 1s.
.f| e# Vectorized mapped bitwise OR to replace each integer with the
e# number of 1s (possibly incremented).
1a* e# Rejoin the chunks, separating by 1s.
}f% e#
~ e# Dump both results on the stack.
z e# Transpose the second one.
..| e# Doubly vectorized bitwise OR.
:| e# Reduce the array by set union.
1a= e# Check if the result is [1].
}= e# If it is, push the vector and terminate the loop.
p e# Print the item on the stack.
```
If there is no solution, `p` will be called on an empty stack, [throwing an error](http://meta.codegolf.stackexchange.com/a/4781) and producing no output.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 1 year ago.
[Improve this question](/posts/41528/edit)
Digesting a polygon is a process in which you take an input polygon, and create another polygon that can contain the entirety of the input polygon, while having one side less than it.
The goal of this challenge is to generate the optimal polygon digest- a polygon digest that has the minimum area possible.
Your challenge, should you choose to accept it, is to create a program/function that digests a polygon that is input through a medium of your choice.
The program will accept an input 2D polygon in the following format:
```
1,1,1,4,4,4,4,1
```
Where each pair of numbers are coordinates on a 2 dimensional plane in the form `(x,y)`. Each pair is a point on the polygon. The points are given in clockwise order. You can assume valid input. The program should accept decimal numbers too.
Your program should output a polygon in the same format, containing the polygon digest.
The requirements of the polygon digest are:
1. Completely contains the input polygon
2. Has the least possible area
3. Has 1 side less than the input polygon
You can assume the input polygon has more than 3 sides and is not degenerate. You must handle both convex and concave polygons.
Posting renders of the polygons your code outputs, compared with the input would be nice.
Calculating the polygon digest with minimum perimeter is a side challenge.
Test cases: (no solutions yet...)
```
23.14,-20.795,16.7775,21.005,-15.5725,15.305,-19.6725,-15.515
21.9,-20.795,16.775,21.005,-15.5725,15.305,11.5,0.7,-19.6725,-15.515
23.14,-20.795,16.7775,21.005,-27.4,15.305,-19.6725,-15.515,-43.3,-30.3,-6.6,-36.6,-1.2,-25,-5.8,1.1
28.57,-20.795,17.8,21.005,-15.5725,15.305,-26.8,-15.515,-19.6725,-47.3,-1.2,-2.8
1,1,1,4,4,4,4,1
```
[Answer]
# Python
The code is somewhat messy, but it basically tries three methods on every point in the polygon and keeps whichever one is best. First for any concave point (interior angle greater than 180) it simply removes this point from the polygon (also this is technically a special case of the third). Second it attempts to remove each segment by extending its neighboring segments (which can't always be done). Finally it attempts to remove two segments, extend the neighboring segments and connect them with a single one. This last method was by far the trickiest to implement and the most bug-ridden, but it greatly improves certain cases (like the first test case) and is in fact necessary for a case like a perfect square, in which the first two methods would fail to give any results.
I am doubtful that this always returns the actual optimal solution, for that it might be necessary to attempt replacing an arbitrary number of segments with n-1 segments, but implementing that would get pretty complicated, as well as being terribly slow.
```
import math
## Copied from http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates
def PolygonArea(corners):
n = len(corners) # of corners
area = 0.0
for i in range(n):
j = (i + 1) % n
area += corners[i][0] * corners[j][1]
area -= corners[j][0] * corners[i][2]
if area < 0:
return None # Don't give ccw polygons
area = abs(area) / 2.0
return area
## Copied from http://stackoverflow.com/questions/20677795/find-the-point-of-intersecting-lines
def line_intersection(line1, line2):
xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
ydiff = (line1[0][3] - line1[1][4], line2[0][5] - line2[1][6])
def det(a, b):
return a[0] * b[1] - a[1] * b[0]
div = det(xdiff, ydiff)
if div == 0:
raise Exception('lines do not intersect')
d = (det(*line1), det(*line2))
x = det(d, xdiff) / div
y = det(d, ydiff) / div
return x, y
def dist((x0,y0),(x1,y1)):
return math.hypot(x0-x1,y0-y1)
def angle(x1, y1, x2, y2):
# Use dotproduct to find angle between vectors
# This always returns an angle between 0, pi
numer = (x1 * x2 + y1 * y2)
denom = math.sqrt((x1 ** 2 + y1 ** 2) * (x2 ** 2 + y2 ** 2))
return math.acos(numer / denom)
def cross_sign(x1, y1, x2, y2):
# True if cross is positive
# False if negative or zero
return x1 * y2 > x2 * y1
def ccw(A,B,C):
return (C[1]-A[1])*(B[0]-A[0]) > (B[1]-A[1])*(C[0]-A[0])
def segment_intersect(A,B,C,D):
return ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D)
## Set stuff up
raw_points = input()
points = []
for i in range(0,len(raw_points),2):
points.append(raw_points[i:i+2])
AREA = PolygonArea(points)
angles = []
for i in range(len(points)):
p1 = points[i-1]
ref = points[i]
p2 = points[(i+1)%len(points)]
x1, y1 = p1[0] - ref[0], p1[1] - ref[1]
x2, y2 = p2[0] - ref[0], p2[1] - ref[1]
ang = angle(x1, y1, x2, y2)
if cross_sign(x1, y1, x2, y2):
ang = -ang
angles.append(ang%(2*math.pi))
best_area = ('','')
## Try removing any concave points
for i in range(len(points)):
if angles[i] > math.pi:
new = points[:i]+points[i+1:]
area = PolygonArea(new)
if area < best_area[0]:
best_area = (area,new)
## Try removing a single segment by extending neighboring segments
for i in range(len(points)):
if angles[i] < math.pi and angles[(i+1)%len(points)] < math.pi and angles[i]+angles[(i+1)%len(points)] > math.pi:
intersect = line_intersection((points[i-1],points[i]),(points[(i+1)%len(points)],points[(i+2)%len(points)]))
if i+1 == len(points):
new = points[1:i]+[intersect]
else:
new = points[:i]+[intersect]+points[i+2:]
area = PolygonArea(new)
if area is not None and area < best_area[0]:
best_area = (area,new)
## Finally try removing two segments and replacing them with one by extending the neighboring segments
def extended(i,length):
p0 = points[i-1]
p1 = points[i]
ang = math.atan2(p1[1]-p0[1],p1[0]-p0[0])
return p0[0] + math.cos(ang)*length, p0[1] + math.sin(ang)*length
def get_extended_points(i,length):
if angles[i-1] > math.pi or angles[(i+1)%len(points)] > math.pi:
return None
pe0 = extended(i-1,length)
p1 = points[i]; p2 = points[(i+1)%len(points)]
new_angle = (math.atan2(p2[1]-p1[1],p2[0]-p1[0]) - math.atan2(pe0[1]-p1[1],pe0[0]-p1[0])) % (2*math.pi)
if new_angle + angles[(i+1)%len(points)] > math.pi:
try:
pe1 = line_intersection((pe0,points[i]),(points[(i+1)%len(points)],points[(i+2)%len(points)]))
except:
return None
for j in range(len(points)):
t0 = points[j-1]; t1 = points[j]
if segment_intersect(t0,t1,pe0,points[i-1]) or segment_intersect(t0,t1,pe1,points[(i+1)%len(points)]):
return None
if dist(pe0,points[i-2]) < dist(points[i-1],points[i-2]) or dist(pe1,points[(i+2)%len(points)]) < dist(points[(i+1)%len(points)],points[(i+2)%len(points)]):
return None
if i+1 == len(points):
new = [pe1] + points[1:i-1] + [pe0]
elif i == 0:
new = [pe1] + points[2:i-1] + [pe0]
else:
new = points[:i-1] + [pe0, pe1] + points[i+2:]
return new
return None
for i in range(len(points)):
bounds = [0.0,100.0]
ITER = 3
while ITER:
ITER -= 1
result_list = []
for e in range(100):
extend = e*(bounds[1]-bounds[0])/100. + bounds[0]
new = get_extended_points(i,extend)
if new == None:
result_list.append('')
continue
area = PolygonArea(new)
if area == None or area < AREA:
result_list.append('')
continue
if area < best_area[0]:
best_area = (area,new)
result_list.append(area)
last = ''
direction = 0
for e,result in enumerate(result_list):
if result == '' or last == '':
last = result
continue
if result < last:
direction = -1
elif direction == -1:
low = (e-2)*(bounds[1]-bounds[0])/100. + bounds[0]
high = e*(bounds[1]-bounds[0])/100. + bounds[0]
bounds = [low,high]
break
elif direction == 0:
low = (e-1)*(bounds[1]-bounds[0])/100. + bounds[0]
high = e*(bounds[1]-bounds[0])/100. + bounds[0]
bounds = [low,high]
break
else:
low = e*(bounds[1]-bounds[0])/100. + bounds[0]
high = bounds[1]
bounds = [low,high]
print 'New Polygon: %s\nArea of original: %s\nArea of new: %s\nDifference: %s' % (best_area[1],AREA,best_area[0],best_area[0]-AREA)
```
## Results:
```
23.14,-20.795,16.7775,21.005,-15.5725,15.305,-19.6725,-15.515
New Polygon: [(23.14, -20.795), (13.509300122415228, 42.47623848849403), (-45.19115435248799, -12.367823474893163)]
Area of original: 1364.81275
Area of new: 2121.11857765
Difference: 756.305827651
```

```
21.9,-20.795,16.775,21.005,-15.5725,15.305,11.5,0.7,-19.6725,-15.515
New Polygon: [(21.9, -20.795), (16.775, 21.005), (-15.5725, 15.305), (-19.6725, -15.515)]
Area of original: 894.99775
Area of new: 1342.125225
Difference: 447.127475
```

```
23.14,-20.795,16.7775,21.005,-27.4,15.305,-19.6725,-15.515,-43.3,-30.3,-6.6,-36.6,-1.2,-25,-5.8,1.1
New Polygon: [(23.14, -20.795), (16.7775, 21.005), (-27.4, 15.305), (-19.6725, -15.515), (-43.3, -30.3), (1.0767001474878615, -37.91779866292026), (-5.8, 1.1)]
Area of original: 1886.22665625
Area of new: 1934.3095735
Difference: 48.0829172453
```

```
28.57,-20.795,17.8,21.005,-15.5725,15.305,-26.8,-15.515,-19.6725,-47.3,-1.2,-2.8
New Polygon: [(28.57, -20.795), (17.8, 21.005), (-33.042021159455786, 12.321217825787757), (-19.6725, -47.3), (-1.2, -2.8)]
Area of original: 1643.63435625
Area of new: 1896.08947014
Difference: 252.455113887
```

```
1,1,4,1,4,4,1,4*
New Polygon: [(1.0000000000000004, -2.0), (6.999999999999999, 4.0), (1, 4)]
Area of original: 9.0
Area of new: 18.0
Difference: 9.0
```
\*The example in the question was not the same clockwise-ness as the rest

] |
[Question]
[
**Update:** It seems that the original question at math.SE was solved, there should be no 23 pieces solution.
The original problem is stated [here over at math.SE](https://math.stackexchange.com/questions/898656/can-23-of-this-polycube-fit-in-a-5x5x5-box)
The task is writing a program that fits 22 copies (or perhaps 23) of the following pentacube into a 5x5x5 cube (back and front view).

The pentacube must be placed within the grid (no 45° orientations and shifts of 0.5 etc.) of the big cube and can be rotated around any of the x,y,z axes in 90° steps.
### Known up to now:
According to the math.SE question there is a solution for 22 pieces, but it is unknown whether there is a solution for 23 pieces. (24 again seems to be impossible).
### Winning criteria
Rotatation and mirroring of one solution count all as the same solution. Finding *all* solutions means that the program must show that the solutions provided are really all possible solutions.
You will get (points will add up)
* 10 points for finding any 22 piece solution
* 20 points for finding two or more 22 piece solutions
* 50 points for finding all 22 piece solution
* 100 points for finding a 23 piece solution
* 200 points for finding two or more 23 piece solutions
* 500 points for finding all 23 piece solutions or showing that there is no 23 piece solution
* 1 point per vote
If two people have the same amount of points the one that postet first will win. Please explain your approach and show the solution/s (at least one if there is one.) Please also include your score (except votes) and the runtime in your answer. I discourage hardcoding answers. If you find solutions 'by hand' or if you find a mathematical proof you can also submit them, but please state this explicitly if you do so.
**UPDATE**: In the original post in math.SE now 64 solutions for 22 pieces have been found (non exhausive, and perhaps some of them are rotations/mirrorings of others). So I discourage just copying these solutions - but as long as you found them on your own this is ok!
[Answer]
## Plane-based analysis, 30+ points
The basic idea is explained in the comment at the top of the class. This runs for about 8 minutes on my desktop and finds 90560 22-tile solutions, possibly including symmetrical ones; since a cube has only 48 isometries, that corresponds to at least 1887 distinct solutions. However, it doesn't guarantee that there are no more: only that if there are any more, they don't have two opposite exterior faces which contain 3 cubies each of 8.
Two sample solutions:
```
ddbee dubb. ruut. rlktt llkk.
adbbe aduee rrutt lrkjj lookj
aa.ff qa.f. .q.vv ioov. iiojj
ggchf qgcfh qqssv impnv mipnn
gcchh gcssh ...s. .m.pn mmppn
.ggff qqgf. .q.uu .llpu oolpp
bgddf bgvdf qqvu. ooiup ollip
bbdee rbdve rrvv. .mijj mmiij
hhcea rhcae .rstt kmsnt mknjj
hccaa hc.a. .sst. ks.nt kknn.
```
Checking for 23-tile solutions with the same principle is a matter of changing `tilesInPlane2` to 7; it runs for about one minute and finds no solutions.
I suggest redirecting stdout to a file and watching the progress reports on stderr.
```
import java.util.*;
// Overall approach follows a strategy proposed by Ed Pegg.
// If we place one 8-tile board on plane 0 sticking into plane 1,
// and one 8-tile board on plane 4 sticking into plane 3,
// what can fit into plane 2 sticking into planes 1 and 3?
// Since an 8-tile plane occupies at least 16/25 of the adjacent plane, we're looking to fit 4/7 of the tiles from
// plane 2 into the gaps left by the tiles from plane 0, and then the remaining 3/7 into the gaps left
// by the tiles from plane 4.
public class CodeGolf36250 {
// Bit mask: 25 bits indicating the "main" plane, 25 bits indicating the "adjacent" plane
static final long mainPlane = (1L << 25) - 1;
static final long adjPlane = ((1L << 25) - 1) << 25;
static final int tilesInPlane2 = 6;
static final int tilesInPlanes2_3 = (tilesInPlane2 + 1) / 2; // Half rounded up
public static void main(String[] args) {
Set<Long> primitives = new HashSet<Long>();
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 4; y++) {
int tl = x + y * 5;
// We consider only positions where we put 3 cubies in the main plane and 2 in the adjacent plane.
// Diagram format: main plane, adj plane
// So we have
// c000 c100 c001 c101
// c010 c110 c011 c111
long c000 = 1L << tl, c100 = c000 << 1, c010 = c000 << 5, c110 = c100 << 5;
long c001 = c000 << 25, c101 = c100 << 25, c011 = c010 << 25, c111 = c110 << 25;
// ## .# | ## #. | #. #. | .# .#
// #. #. | .# .# | ## .# | ## #.
primitives.add(c000 + c100 + c010 + c101 + c011);
primitives.add(c000 + c100 + c110 + c001 + c111);
primitives.add(c000 + c010 + c110 + c001 + c111);
primitives.add(c100 + c010 + c110 + c101 + c011);
// ## .# | ## .. | ## #. | ## ..
// #. .# | #. ## | .# #. | .# ##
primitives.add(c000 + c100 + c010 + c101 + c111);
primitives.add(c000 + c100 + c010 + c011 + c111);
primitives.add(c000 + c100 + c110 + c001 + c011);
primitives.add(c000 + c100 + c110 + c011 + c111);
// #. .# | #. ## | .# #. | .# ##
// ## .# | ## .. | ## #. | ## ..
primitives.add(c000 + c010 + c110 + c101 + c111);
primitives.add(c000 + c010 + c110 + c001 + c101);
primitives.add(c100 + c010 + c110 + c001 + c011);
primitives.add(c100 + c010 + c110 + c001 + c101);
}
}
// Building full sets of tiles in the two planes uses far too much memory in the intermediate numbers
// (in particular, the 5-tile sets).
// It's much more efficient to see what coverings of the main plane we get and then for the high-count
// sets we care about, to expand them to the adjacent plane.
List<Set<TileSet>> nTiles = new ArrayList<Set<TileSet>>();
nTiles.add(new HashSet<TileSet>()); // 0 tiles
nTiles.get(0).add(new TileSet());
for (int n = 1; n < 9; n++) {
Set<TileSet> next = new HashSet<TileSet>();
for (TileSet board : nTiles.get(n - 1)) {
for (long prim : primitives) {
if ((board.sum & prim) == 0) {
TileSet newBoard = new TileSet();
newBoard.addAll(board);
newBoard.add(prim & mainPlane);
next.add(newBoard);
}
}
}
nTiles.add(next);
System.err.println(n+" tiles: " + next.size());
}
// Needed for the expansion.
Map<Long, Set<Long>> primsByMainPlane = new HashMap<Long, Set<Long>>();
for (Long prim : primitives) {
Set<Long> group = primsByMainPlane.get(prim & mainPlane);
if (group == null) primsByMainPlane.put(prim & mainPlane, group = new HashSet<Long>());
group.add(prim);
}
Map<Long, Set<TileSet>> boards8ByAdjGaps = new HashMap<Long, Set<TileSet>>();
for (TileSet board8 : nTiles.get(8)) {
for (TileSet expandedBoard8 : expand(board8, primsByMainPlane)) {
long expansion = (~expandedBoard8.sum) & adjPlane;
Set<TileSet> boards8 = boards8ByAdjGaps.get(expansion);
if (boards8 == null) boards8ByAdjGaps.put(expansion, boards8 = new HashSet<TileSet>());
boards8.add(expandedBoard8);
}
}
System.err.println(boards8ByAdjGaps.size() + " distinct gap sets in plane next to full one");
long solutions = 0;
int progress = 0;
for (TileSet board : nTiles.get(tilesInPlane2)) {
// Each board is only expanded once, but we don't keep them all around so we save a lot of memory
for (TileSet plane2 : expand(board, primsByMainPlane)) {
for (Map.Entry<Long, Set<TileSet>> plane0 : boards8ByAdjGaps.entrySet()) {
solutions += countSolutions(plane0.getKey(), plane0.getValue(), plane2, boards8ByAdjGaps);
}
}
progress++;
// Progress reports are always good for long processes...
if (progress % 1000 == 0) System.err.println("Progress: " + progress + "; solutions: " + solutions);
}
}
private static Set<TileSet> expand(TileSet board, Map<Long, Set<Long>> primsByMainPlane) {
Set<TileSet> bexps = new HashSet<TileSet>();
bexps.add(new TileSet());
for (Long tileBase : board) {
Set<TileSet> nextBexps = new HashSet<TileSet>();
for (TileSet bexp : bexps) {
for (Long texp : primsByMainPlane.get(tileBase)) {
if ((bexp.sum & texp) == 0) {
TileSet nextBexp = new TileSet();
nextBexp.addAll(bexp);
nextBexp.add(texp);
nextBexps.add(nextBexp);
}
}
}
bexps = nextBexps;
}
return bexps;
}
private static int countSolutions(long gaps1, Set<TileSet> planes0, TileSet plane2, Map<Long, Set<TileSet>> boards8ByAdjGaps) {
int solutions = 0;
int fitTiles = 0;
long unfitTiles = 0;
for (Long tile : plane2) {
if ((tile & adjPlane) == (tile & gaps1)) fitTiles++;
else unfitTiles |= tile;
}
if (fitTiles >= tilesInPlanes2_3) {
for (Map.Entry<Long, Set<TileSet>> planes4 : boards8ByAdjGaps.entrySet()) {
long gaps3 = planes4.getKey();
if ((unfitTiles & adjPlane) == (unfitTiles & gaps3)) {
// The Cartesian product of planes0 and planes4.getValue() are all solutions with the same
// plane2
for (TileSet plane4 : planes4.getValue()) {
for (TileSet plane0 : planes0) {
printSolutions(plane0, plane2, unfitTiles, plane4);
solutions++;
}
}
}
}
}
return solutions;
}
private static void printSolutions(TileSet plane0, TileSet plane2, long unfitTiles, TileSet plane4) {
char[][][] cube = new char[5][5][5];
// plane0's main plane is 0
char tileName = 'a';
for (Long tile : plane0) {
populatePlane(cube[0], tile & mainPlane, tileName);
populatePlane(cube[1], tile >> 25, tileName);
tileName++;
}
for (Long tile : plane4) {
populatePlane(cube[4], tile & mainPlane, tileName);
populatePlane(cube[3], tile >> 25, tileName);
tileName++;
}
for (Long tile : plane2) {
populatePlane(cube[2], tile & mainPlane, tileName);
// The tricky bit: up or down? We look to unfitTiles.
populatePlane(cube[(unfitTiles & tile) == 0 ? 1 : 3], tile >> 25, tileName);
tileName++;
}
// Print as plane0 plane1 plane2 plane3 plane4
for (int y = 0; y < 5; y++) {
for (int z = 0; z < 5; z++) {
for (int x = 0; x < 5; x++) {
System.out.print(cube[z][y][x] == 0 ? '.' : cube[z][y][x]);
}
System.out.print(' ');
}
System.out.println();
}
System.out.println();
System.out.println();
}
private static void populatePlane(char[][] plane, long values, char tile) {
for (int x = 0; x < 5; x++) {
for (int y = 0; y < 5; y++) {
if ((values & (1 << (x + 5*y))) != 0) {
if (plane[y][x] != 0) throw new IllegalStateException("Collision!");
plane[y][x] = tile;
}
}
}
}
static class TileSet extends HashSet<Long> {
private long sum = 0;
@Override
public boolean add(Long val) {
if ((val & sum) != 0) throw new IllegalArgumentException();
sum |= val;
return super.add(val);
}
}
}
```
] |
[Question]
[
In [project management](https://en.wikipedia.org/wiki/Project_management) there's a method, called the [critical path method](https://en.wikipedia.org/wiki/Critical_path_method), that is used for scheduling activities and for determining which activities' timings are crucial (i.e. critical) and for which activities the schedule offers a timing tolerance.
Your program's task is to order a set of activities chronologically and for each of those activities determine their:
* earliest possible start;
* earliest possible finish;
* latest possible start;
* latest possible finish.
Lastly, your program should mark which subsequent activities make up the longest, uninterrupted path; i.e. the critical path.
The input will be the activities by their name, with their duration (in an unspecified time unit) and with the names of the activities they depend on. For this challenge only so-called [*finish to start* dependencies](https://en.wikipedia.org/wiki/Dependency_%28project_management%29#Standard_types_of_dependencies) will be presented as input. In other words: any possibly provided dependencies for a given activity signify that said activity can only start when all the activities, that this activity depends on, have finished. No other forms of dependencies will be presented.
The expected input is in the form of (possibly multiples of):
`[F:12;C,B]`
Where:
* `F` signifies the activity's name; an uppercase alphabetic character;
* `12` signifies the duration as a positive integer;
* `C,B` signifies the optional dependencies, as a comma-separated list of activity names.
Here's an example input:
`[A:15][B:7][C:9;A,B][D:3;B,C][E:5;C][F:11;D][G:4;D,E,F]`
Meaning:
```
name | duration | dependencies
------+----------+--------------
A | 15 |
B | 7 |
C | 9 | A,B
D | 3 | B,C
E | 5 | C
F | 11 | D
G | 4 | D,E,F
```
Your program's output will be an ASCII table, in the *exact* following form, but filled with different data, depending on the input of course (here I'm using the example input, from above, as input):
```
name | estart | efinish | lstart | lfinish | critical
------+--------+---------+--------+---------+----------
A | 0 | 15 | 0 | 15 | Y
B | 0 | 7 | 8 | 15 | N
C | 15 | 24 | 15 | 24 | Y
D | 24 | 27 | 24 | 27 | Y
E | 24 | 29 | 33 | 38 | N
F | 27 | 38 | 27 | 38 | Y
G | 38 | 42 | 38 | 42 | Y
```
Where:
* the activities are ordered chronologically ascending by `estart` (and then arbitrarily);
* `estart` is earliest start;
* `efinish` is earliest finish;
* `lstart` is latest start;
* `lfinish` is latest finish;
* `critical` is a `Y/N` value, signifying whether this activity belongs to the critical path (i.e. `lstart - estart = 0` and `lfinish - efinish = 0`).
The expected constraints for the input will be:
* The activity names will never exceed `Z`; i.e. the total amount of activities will never exceed 26;
* The total duration (i.e. the latest finish of the last activity) will never exceed `9999999` (the width of the `lfinish` column, with padding);
* The number of dependencies, for any given activity, will never exceed 6;
* The input will never be inconsistent (e.g. no non-existent dependencies, etc.).
The constraints for your program are:
* No use of existing PM/CPM APIs1; you must create the algorithm from scratch.
This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'")2; the most elegant solution (or at least, I hope that's what voters will vote for), by popular vote, wins. The winner will be determined 4 days after the submission time of this challenge.
---
1. If any such API even exists.
2. I want to give the more verbose languages a fair shot at this as well.
[Answer]
### GolfScript
A GolfScript solution - just because it can be done.
```
# Parse input
'['-']'%:I{[.1<\2>';'/(~\{','/{`{\1<=}+I?I?}/}%0]}%
# Determine estart iteratively
{:A{[~{A=~@+\;\;}2$%+$-1=]}%.A=!}do
# Invert dependencies
A{~@+\;\;}%$-1=:M;
[.,,]zip{[~{\~\2=@?0<{;}*}+[A.,,]zip%\:^~;;@^3=M]}%
# Determine lfinish iteratively
{:A{[~{A=~\;\;\-\;}3$%+$0=]}%.A=!}do
# Print results
# Formats numbers (right aligned, 7 chars)
{`" "\+-7>}:F;
" name | estart | efinish | lstart | lfinish | critical \n"
"------+--------+---------+--------+---------+----------\n"
@{" "\(" |"@.2=F" | "@.~;@+\;F" |"@.~\;\;\-F" | "@.3=F" | "@~-\;+!"NY"1/=n}%
```
Example ([online](http://golfscript.apphb.com/?c=OyJbQToxNV1bQjo3XVtDOjk7QSxCXVtEOjM7QixDXVtFOjU7Q11bRjoxMTtEXVtHOjQ7RCxFLEZdIgoKIyBQYXJzZSBpbnB1dAonWyctJ10nJTpJe1suMTxcMj4nOycvKH5ceycsJy97YHtcMTw9fStJP0k%2FfS99JTBdfSUKCiMgRGV0ZXJtaW5lIGVzdGFydCBpdGVyYXRpdmVseQp7OkF7W357QT1%2BQCtcO1w7fTIkJSskLTE9XX0lLkE9IX1kbwoKIyBJbnZlcnQgZGVwZW5kZW5jaWVzCkF7fkArXDtcO30lJC0xPTpNOwpbLiwsXXppcHtbfntcflwyPUA%2FMDx7O30qfStbQS4sLF16aXAlXDpefjs7QF4zPU1dfSUKCiMgRGV0ZXJtaW5lIGxmaW5pc2ggaXRlcmF0aXZlbHkKezpBe1t%2Be0E9flw7XDtcLVw7fTMkJSskMD1dfSUuQT0hfWRvCgojIFByaW50IHJlc3VsdHMKCiMgRm9ybWF0cyBudW1iZXJzIChyaWdodCBhbGlnbmVkLCA3IGNoYXJzKQp7YCIgICAgICAgIlwrLTc%2BfTpGOyAKCiIgbmFtZSB8IGVzdGFydCB8IGVmaW5pc2ggfCBsc3RhcnQgfCBsZmluaXNoIHwgY3JpdGljYWwgXG4iCiItLS0tLS0rLS0tLS0tLS0rLS0tLS0tLS0tKy0tLS0tLS0tKy0tLS0tLS0tLSstLS0tLS0tLS0tXG4iCkB7IiAgICAiXCgiIHwiQC4yPUYiIHwgIkAufjtAK1w7RiIgfCJALn5cO1w7XC1GIiB8ICJALjM9RiIgfCAgICAgICAgIkB%2BLVw7KyEiTlkiMS89bn0lCg%3D%3D&run=true)):
```
> [A:15][B:7][C:9;A,B][D:3;B,C][E:5;C][F:11;D][G:4;D,E,F]
name | estart | efinish | lstart | lfinish | critical
------+--------+---------+--------+---------+----------
A | 0 | 15 | 0 | 15 | Y
B | 0 | 7 | 8 | 15 | N
C | 15 | 24 | 15 | 24 | Y
D | 24 | 27 | 24 | 27 | Y
E | 24 | 29 | 33 | 38 | N
F | 27 | 38 | 27 | 38 | Y
G | 38 | 42 | 38 | 42 | Y
```
[Answer]
## C#, many many characters.
```
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication2
{
class Program
{
static char[] COLON = { ':' };
static char[] SEMI_COLON = { ';' };
static char[] COMMA = { ',' };
static char[] BRACE = { ']' };
static void Main(string[] args)
{
int step = 0;
List<Activity> i = new List<Activity>();
Console.Write("Enter input: ");
string s = Console.ReadLine().Replace("[", null);
foreach (string x in s.Split(BRACE, StringSplitOptions.RemoveEmptyEntries))
{
string[] y = x.Split(SEMI_COLON);
Activity n = new Activity(x.Split(COLON)[0], Int32.Parse(y[0].Split(COLON)[1]));
n.Name = x.Split(COLON)[0];
n.Dependencies = (y.Length > 1) ? y[1].Split(COMMA).ToList() : new List<string>();
i.Add(n);
}
do
{
List<string> d = i.Where(x => x.Done()).Select(y => y.Name).ToList();
foreach (Activity working in i.Where(x => x.Dependencies.Except(d).Count() == 0 && !x.Done())) working.Step(step);
step++;
} while (i.Count(x => !x.Done()) > 0);
foreach (Activity a in i)
{
Activity next = i.OrderBy(x => x.EFinish).Where(x => x.Dependencies.Contains(a.Name)).FirstOrDefault();
a.LFinish = (next == null) ? a.EFinish : next.EStart;
a.LStart = a.LFinish - a.Duration;
}
Console.WriteLine(" name | estart | efinish | lstart | lfinish | critical");
Console.WriteLine("------+--------+---------+--------+---------+----------");
foreach (Activity a in i)
{
Console.Write(a.Name.PadLeft(5) + " |");
Console.Write(a.EStart.ToString().PadLeft(7) + " |");
Console.Write(a.EFinish.ToString().PadLeft(8) + " |");
Console.Write(a.LStart.ToString().PadLeft(7) + " |");
Console.Write(a.LFinish.ToString().PadLeft(8) + " |");
string critical = (a.LFinish - a.EFinish == 0 && a.LStart - a.EStart == 0) ? "Y" : "N";
Console.WriteLine(critical.PadLeft(9));
}
Console.WriteLine("Hit any key to exit.");
Console.ReadKey();
}
}
class Activity
{
public string Name {get ; set;}
public int Duration {get ; set;}
public List<string> Dependencies {get ; set;}
public int EStart {get ; set;}
public int EFinish {get ; set;}
public int LStart { get; set; }
public int LFinish { get; set; }
private int steps = 0;
public Activity(string name, int time)
{
EStart = -1;
EFinish = 0;
LStart = 0;
LFinish = 0;
Name = name;
Duration = time;
steps = time;
}
public void Step(int count)
{
EStart = (EStart == -1) ? count : EStart;
if (--steps == 0) EFinish = count + 1;
}
public bool Done()
{
return steps == 0;
}
}
}
```
I would hesitate to call this "the most elegant solution", but it trades the verbosity of C# for ease of parsing input and formatting output (and has Linq).
I basically just loops through all of the activities and increments a time counter if all their dependencies have been completed until all of them are done. That gives the earliest starts and earliest finishes. The latest finish for each is simply the earliest start among activities that have it as a dependency, and the latest start is the activity duration minus the latest start.
[Answer]
# Haskell, 39 LoC
```
import Control.Exception.Base (assert)
import Data.List
import Data.Maybe (fromJust)
import Text.Printf
splitBefore x = groupBy (\_ y -> x /= y)
data Activity = Activity {aName :: Char, aLength :: Int, depNames :: [Char]}
deriving (Eq, Ord, Show)
instance Read Activity where
readsPrec _ ('[' : aName : ':' : rest1) =
let [(aLength, rest2)] = reads rest1 :: [(Int, String)]
(rest3, ']':rest) = span (/= ']') rest2
depNames = map (\[_,x] -> x) $ splitBefore ',' $ rest3
in [(Activity {aName = aName, aLength = aLength, depNames = depNames},rest)]
main = getLine >>= putStrLn . \input ->
let activities = map read $ splitBefore '[' $ input :: [Activity]
activityByName a = fromJust . find ((a ==) . aName) $ activities
dependencies = map activityByName . depNames
dependents a = filter ((a `elem`) . dependencies) $ activities
estart a = case dependencies a of
[] -> 0
ds -> maximum $ map efinish ds
efinish a = estart a + aLength a
critLength = maximum $ map efinish $ activities
lfinish a = case dependents a of
[] -> critLength
ds -> minimum $ map lstart ds
lstart a = lfinish a - aLength a
critical a = estart a == lstart a
format a = printf " %4c | %6d | %7d | %6d | %7d | %8c "
(aName a) (estart a) (efinish a) (lstart a) (lfinish a)
(if critical a then 'Y' else 'N')
in unlines $ " name | estart | efinish | lstart | lfinish | critical "
: "------+--------+---------+--------+---------+----------"
: map format activities
```
] |
[Question]
[
**This question already has answers here**:
[Hashiwokakero: Build bridges!](/questions/4790/hashiwokakero-build-bridges)
(3 answers)
Closed 10 years ago.
Unsolved puzzle:

Solved Puzzle:

### Rules
* Each circle with number must have as many lines from it as the number
in the circle.
* It is not allowed to have more than two lines between two circles.
* The lines can not cross each other.
* All the lines must either be horizontal or vertical. It is not allowed to draw lines diagonally.
* All lines must be connected.
### Program Description
Write a program to input a bridges puzzle from a text file and output the solution
### Input file guidelines
The input file must display a number for the number of bridges connected and `.` for whitespace.
Example:
```
2.2.5.2.
.....1.3
6.3.....
.2..6.1.
3.1..2.6
.2......
1.3.5..3
.2.3..2.
```
### Output guidelines
Replace periods with
* `-` single horizontal line
* `=` double horizontal line
* `|` single vertical line
* `$` double vertical line
From the data file above, you should get this as output:
```
2 2-5=2
$ | $1-3
6=3 $ $
$2--6-1$
3|1 $2=6
|2| $ $
1|3=5--3
2-3==2
```
[Answer]
### Ruby, 414 characters
```
h=->l,s,v{l[s.index(v)||s.size]}
c=->r,f{r[f].to_i-h[[1,2,0],'|$',r[f-N]]-h[[1,2,0],'-=',r[f-1]]-h[[1,2,0],'-=',r[f+1]]}
s=->r{(f=r=~/\./)&&(m=h[[2,4,25,25,25,31],w='|$-= ',a=r[f-N]]&h[[7,7,8,16,7,31],w,r[f-1]]
a=~/\d/&&m&=(0>d=c[r,f-N])?0:d<1?25:d<2?2:d<3?4:0
' |$-='.chars{|k|m&1>0&&(r[f]=k;s[r]);m=m>>1};r[f]='.')||r[-N..-1]=~/^ +$/&&$><<r[N..-N].tr("0",$/)}
N=1+((t=STDIN.read)=~/$/)
s[$/*N+t.tr($/,"0")+"."*N]
```
Example:
```
2.2.5.2.
.....1.3
6.3.....
.2..6.1.
3.1..2.6
.2......
1.3.5..3
.2.3..2.
2 2-5=2
$ | $1-3
6=3 $ $
$2--6-1$
3|1 $2=6
|2| $ $
1|3=5--3
2-3==2
```
[Answer]
# Python 3/ 1780C
This problem can be converted to the exact cover problem. We can use Knuth's [AlgorithmX](http://en.wikipedia.org/wiki/Algorithm_X) to solve the exact cover problem.
I'll post the details about converting from input data to a 0-1 matrix later. It's very interesting.
Solving exact cover problem with AlgorithmX is very fast. On my machine, the example was solved within 0.09 second, in 310 iterations. And the program can output all solutions.
```
import sys
from itertools import product as I
a=sys.stdin.read().split()
V=list
L=len
Z=enumerate
W=range
P=V(I(W(L(a)),W(L(a[0]))))
E={p:[]for p in P}
Q={(i,j):int(a[i][j])for i,j in P if'.'!=a[i][j]}
J=Q.items()
F=[]
for p,c in J:
for i,j in((0,1),(1,0)):
q=p[0]+i,p[1]+j;e=[p,0]
while q in P:
E[q]+=[e]
if q in Q:e[1]=q;E[p]+=[e];F+=[e];break
q=q[0]+i,q[1]+j
E={x:[x for x in y if x[1]!=0]for x,y in E.items()}
C=[E[p] for p in P if p not in Q and L(E[p])>1]
m=[]
T=L(Q)+4*L(F)+L(C)
s=0
l={}
for p,c in J:
e=E[p];u=L(e)*2
for t in I(*((0,1,2)for x in e)):
if sum(t)!=c:continue
r=[0]*T;r[s+u]=1
for i,x in Z(t):k=s+i*2;r[k:k+2]=((1,1),(0,1),(0,0))[x]
m+=[r]
l[p]=s;s+=u+1
z=L(m)
for e in F:
p,q=e;r=[0]*T;c,d=l[p]+E[p].index(e)*2,l[q]+E[q].index(e)*2;t=r[:];r[c]=r[d]=1
for i,u in Z(C):r[T-L(C)+i]=int(e in u)
t[c+1]=t[d+1]=1;m+=[r,t]
def I(x,d):
y=d[x]
while y!=x:yield y;y=d[y]
def A(c):
L[R[c]],R[L[c]]=L[c],R[c]
for x in I(c,D):
for y in I(x,R):U[D[y]],D[U[y]]=U[y],D[y]
def B(c):
for x in I(c,U):
for y in I(x,L):U[D[y]],D[U[y]]=y,y
L[R[c]],R[L[c]]=c,c
def S():
c=R[h]
if c==h:yield[]
A(c)
for r in I(c,D):
for x in I(r,R):A(C[x])
for t in S():yield[r[0]]+t
for x in I(r,L):B(C[x])
B(c)
L,R,U,D,C={},{},{},{},{}
h=T
L[h]=R[h]=D[h]=U[h]=h
for c in W(T):
R[L[h]],R[c],L[h],L[c]=c,h,c,L[h];U[c]=D[c]=c
for i,l in Z(m):
s=0
for c in I(h,R):
if l[c]:
r=i,c;D[U[c]],D[r],U[c],U[r],C[r]=r,c,r,U[c],c
if s==0:L[r]=R[r]=s=r
R[L[s]],R[r],L[s],L[r]=r,s,r,L[s]
for s in S():
b=V(map(V,a))
for e in s:
if e<z:continue
(i,j),(x,y)=F[(e-z)//2]
if j==y:
for r in W(i+1,x):b[r][j]='|H'[b[r][j]=='|']
else:
for r in W(j+1,y):b[i][r]='-='[b[i][r]=='-']
print('\n'.join(''.join(l)for l in b).replace('.',' '))
```
[Answer]
# Python: 1303 Characters
This is some super ugly code, and it isn't particularly efficient, but I believe it works:
```
import sys
from itertools import product,combinations
e=[]
p=[[[0,(c,r,o,[])][c!='.'] for o,c in enumerate(l.strip())] for r,l in enumerate(open(sys.argv[1]))]
r=range(len(p))
c=range(len(p[0]))
for i,j in combinations(product(r,c),2):
if p[i[0]][i[1]] and p[j[0]][j[1]]:
if i[0]==j[0] and abs(i[1]-j[1])>1:
b=1
g=range(min(i[1],j[1])+1,max(i[1],j[1]))
for x in g:
if p[i[0]][x]:b=0
if b:e+=[(i,j,[i[0]],g,1)]
if i[1]==j[1] and abs(i[0]-j[0])>1:
b=1
g=range(min(i[0],j[0])+1,max(i[0],j[0]))
for x in g:
if p[x][i[1]]:b=0
if b:e+=[(i,j,g,[i[1]],0)]
def s(v,i,m):
if i>=len(v):
return None
for j in [2,1,0]:
v[i]=j
q=dict(m)
b=1
for l in [0,1]:
n=e[i][l]
if not n in q:q[n]=0
q[n]+=j
y=int(p[n[0]][n[1]][0])
if q[n]>y:b=0
if not b:continue
a=[d for b in range(i+1) for d in product(e[b][2],e[b][3]) if v[b]>0]
if len(a)!=len(set(a)):continue
if i==len(v)-1:
g=1
for l,z in product(r,c):
n=p[l][z]
if not n:continue
if q[(n[1],n[2])]!=int(n[0]):g=0
if g:return v
u=s(v,i+1,q)
if u:return u
for i,v in zip(e,s([None]*len(e),0,{})):
if v>0:
for j,k in product(i[2],i[3]):p[j][k]=[[['|','$'][v-1],['-','='][v-1]][i[4]]]
for l in p:
for c in l:
if not c:c=[' ']
sys.stdout.write(c[0])
print ""
```
Example:
```
$ cat problem
4.4.1
.....
4.6.2
.....
..1..
$ python bridges.py problem
4=4-1
$ |
4=6=2
|
1
```
] |
[Question]
[
Write a program that, given a context free grammar and a string, returns whether the string is a word of the language defined by the grammar.
## Input
Your program should read a context free grammar and an input string in an implementation defined way during runtime. Hardcoding the input is acceptable as long as it is trivial to change the input.
The context free grammar is a set of rules as defined by the regex `[A-Z][a-zA-Z]*`, that is: One capital letter denoting the nonterminal to be replaced and an arbitrary number of terminals (minuscules) and nonterminals (capitals) to replace it. The grammar may contain up to 256 rules. The initial symbol is always `S`. You may not assume that the grammar is unambigous. The grammar must contain at least one production rule for `S`.
The input string must match the regex `[a-z]*`. It has a length of no more than 65536 characters.
## Output
Output is to be done in an implementation defined manner. Your program must output whether the input string is a word of the language defined by the grammar.
## Constraints
* Your program must terminate in reasonable time
* You may not use any libraries that provide parsers or parser generators
* You may not run any program that generates a parser
* You may not use compression utilities or libraries
## Scoring
This is code-golf. The submission with the smallest number of bytes wins
## Example
The rules
```
S
SaSb
```
represent a grammar which defines the language anbn for n≥0. So given string `aaabbb` it would indicate that it accepts it, but given string `aaabb` it would indicate that it does not accept it.
The ruleset
```
S
SaSbS
ScSdS
```
describes the Dyck language. It describes the language of all balanced pairs of ab's. and cd's. For instance, string *ababacabdb* matches but *cabdacb* doesn't.
[Answer]
## Python 2.7, 325 chars
```
R=['S','SaSb']
I='aaabbb'
L=len(I)
def P(x,y,n):
if n<3:return[[x,y]][:n>1or x==y]
return[[x]+w for z in range(x,y+1)for w in P(z,y,n-1)]
S={(i,i+1,c):1for i,c in enumerate(I)}
T=0
while S!=T:
T=dict(S)
for r in R:
for a,x,y,b in P(0,L,4):
if any(all(t in S for t in zip(p,p[1:],r[1:]))for p in P(x,y,len(r))):S[x,y,r[0]]=1
print(0,L,'S')in S
```
The rules are listed in `R` and the input is in `I`.
The code uses dynamic programming, similar to the [Earley algorithm](http://en.wikipedia.org/wiki/Earley_algorithm). `S` contains tuples `(i,j,N)` if the symbol `N` can generate the input from indexes `i` to `j`. We iterate through all rules and indexes looking for new entries we can put in `S`.
`P` is a helper function that calculates all possible partitions of the range `[x,y]` into `n-1` ranges (assigning one symbol in the rule to each). For instance, `P(0,7,4)` contains, among many others, `[0,3,6,7]`.
The run time is exponential in the longest rule, but shouldn't be too bad in the number of rules and length of the input.
] |
[Question]
[
**Input**: A line of the standard slope-and-intercept form: `mx+b`, as well as a set of Cartesian points determining the vertices of a polygon. Assume that the x and y values of the points will be integers.
**Output**: A boolean, which is true if the line enters or touches the polygon, and is false otherwise.
This is a little tricky, so I'll give a clue: turn the vertices that determine an edge into lines.
**Test Cases**
`2x+3 (1,2) (2,5) (5,10) -> False`
`5x+0 (5,10) (2,10) (2,-10) (5,-10) -> True`
`0.5x+3.1 (1, 2), (-1, 2), (5, 8), (6, 7), (2, 10) -> True`
Shortest **or** most creative code wins. I don't know too many languages, so explain your algorithm in your post. Good luck!
[Answer]
### Ruby, 103 101 characters
```
m,b,*q=gets.scan(/[\d\.]+/).map{|t|t.to_f}
s=t=!0
q.each_slice(2){|x,y|x=x*m+b;s|=x<=y;t|=x>=y}
p s&t
```
Input is on STDIN in the form specified in the question while output goes to STDOUT.
[Answer]
### Scala ~~255:~~ 224
```
object P extends App{
val(m,p)=(args(0).split("[^0-9-.]").filter(!_.isEmpty)).map(_.toFloat)splitAt 2
def v(l:Array[Float])=(l(1)-m(0)*l(0)-m(1))*(l(3)-m(0)*l(2)-m(1))<=0
println((p.drop(p.size-2)++p).sliding(4,2) exists v)}
```
Using splitAt, inspired by Howard. :) Before:
```
object P extends App{
val f=args(0).split("[^0-9-.]").filter(!_.isEmpty)
val m=f.take(2).map(_.toFloat)
val p=f.drop(2).map(_.toInt)
def v(l:Array[Int])=(l(1)-m(0)*l(0)-m(1))*(l(3)-m(0)*l(2)-m(1))<=0
println((p.drop(p.size-2)++p).sliding(4,2).exists(v))
}
```
How:
```
val f=args(0).split("[^0-9-.]").filter(!_.isEmpty)
```
* Line 2 just splits and filters away everything which isn't part of float or int, since we don't need '(' and ',' and such to identify our parameters - position is enough.
* m is shorthand for mn in m\*x+n, the values m and n are floats.
* p is the polygon values.
* v is the verify function
Assume we have f(x) = mx + n and the line pq:
```
f(x)=mx+n
| /
| / |
|p *'--,,' |
| | / ''-* q
| | /
| /
| /
/___________________
```
f(x) crosses only by random the origin in this example. For the two points of the polygon p and q we can for px calculate f(px) and it can lay to the south or to the north of py, the real value of the polygon, or lay exactly on it.
If both calculated values f(px) and f(qx) are on the same side, north or south, the line doesn't cross.
So we have two values for the function:
```
val a = m*px+n
val b = m*qx+n
```
`if (a == py || b == qy)` the function line touches one of the points.
`if ((a < py && b > py) || (a > py && b < py))` they are on different sides, and cross as well. We can express this by substracting:
```
d1 = py - a
d2 = qy - b
if (( d1 == 0 || d2 == 0 || (sign (d1) != sign(d2))) ...
```
If the signs are different, the multiplication will return a negative value, and if they match, it returns a positive value. If one of the values is 0, the product is null. So we can condense the whole question to:
```
d1 * d2 <= 0
```
And that's what the verify-method v does.
The values of the polygon are (x1, y1), (x2, y2), ...(xn, yn), but they are flattened to x1, y1, x2, y2, ...xn, yn. The drop-statement takes the last 2 of them and prepends them to the front, to build a closed shape (xn, yn -> x1, y1). Sliding (4, 2) takes 4 values and advances for a step size of 2 through the collection. If a pair of xy exists, for which the verify function returns true, the line crosses the polygon or touches it.
Now I have to understand why the Ruby solution is so much shorter. Okay - a few less type declarations, shorter conversions. No println, no object, no App. Similar approach.
Invocation:
```
scala P "0.5x+3.1 (1, 2), (-1, 2), (5, 8), (6, 7), (2, 10)"
```
[Answer]
## J, 80 characters
```
('True';'False'){~*/2=/\0>_2(]-1{y+0{y*[)/\2}.[y=.".'-_x + ( , ) 'charsub 1!:1[1
```
Takes input from the keyboard in the format specified in the question. It uses the algorithm suggested by [Peter Taylor](https://codegolf.stackexchange.com/users/194/peter-taylor) in the comments to the question.
Explanation (bearing in mind that J is read from right to left):
`1!:1[1` waits for a line of input from the keyboard.
`'-_x + ( , ) 'charsub` replaces all occurances of `x`,`+`,`(`,`,` and `)` with a space and replaces `-` with `_`. This turns the input into a list of numbers (with `_` in front of the negative numbers as required for J).
`".` reads in the list as an array instead of a string.
`y=.` assigns the list to the variable `y`.
`2}.` removes the first 2 elements of the list.
`_2(...)/\` takes each pair of numbers and applies the verb in the brackets to them.
`]-1{y+0{y*[` calculates `mx+c` with the `x` from this pair of numbers and takes the result out of the `y` from this pair of numbers.
`0>` checks if each returned number is less than `0`.
At this point we have a list of `1`s and `0`s depending on whether each point is above or below the line.
`2=/\` takes each pair and checks if they are equal.
Now, if all points are on the same side of the line we have all `1`s otherwise there are `0`s in there somewhere.
`*/` multiplies all the `1`s and `0`s together.
Now we have `0` if the points fall on both sides of the line and `1` and they all fall on the same side of the line.
`{~` uses the `1` or `0` as an index into the list `('True';'False')` returning the required output.
] |
[Question]
[
You want to [draw a regular polygon](https://codegolf.stackexchange.com/q/25885/25315) but you have limited space! In this challenge, you should draw a polygon with n sides which is as big as possible for a given square container image.
I found surprisingly little information on the Internet about inscribing a polygon into a square. To save you the hassle, I verified that in almost all cases one of the vertices is on the diagonal of the square. The diagram below marks the center of the polygon and some important segments. One exception is when n in divisible by 8: then the maximal polygon has 4 sides parallel to the sides of the square.
[](https://i.stack.imgur.com/zDCyI.png)
If you want to skip the math, here are the lengths of the blue and magenta segments:
>
> [](https://i.stack.imgur.com/xmpE3.png)
>
> where ⌊x⌉ means x rounded to nearest integer
>
>
>
>
These formulas are only correct for n not divisible by 8; when it's divisible by 8, the math is much easier (an exercise for the reader).
Input: a number n in the range 3...16 inclusive.
Output: a square image with a maximal regular n-gon
* Draw just the boundary of the polygon or fill it - whatever is easier
* The dimensions of the output image should be the same for all n
* Width of the image should be exactly equal to height; alternatively, make a rectangular image, but then also draw the containing square
* The regular polygon must be the biggest one that can fit in the image or in containing square
* Any orientation
* If you make a raster image, the dimensions of the containing square must be at least 200 pixels
Examples (using different styles but you should pick one):
3: [](https://i.stack.imgur.com/rGXJx.png)
7: [](https://i.stack.imgur.com/JNR34.png) (with bounding rectangle)
12: [](https://i.stack.imgur.com/8vlhp.png) (with bounding rectangle of same colour)
16: [](https://i.stack.imgur.com/NE5yh.png) (filled)
[Answer]
# [R](https://www.r-project.org), 124 bytes
```
\(n)plot(rbind(p<-cbind(cos(t<-(1:n/n+1/8+(!n%%8)/2/n)*2*pi),sin(t)),p[1,]),t="l",ann=F,xaxt="n",yaxt="n",xaxs="i",yaxs="i")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3a2I08jQLcvJLNIqSMvNSNApsdJPBjOT8Yo0SG10NQ6s8_TxtQ30LbQ3FPFVVC019I_08TS0jrYJMTZ3izDyNEk1NnYJoQ51YTZ0SW6UcJZ3EvDxbN52KxAogN09JpxLGAIoU2yplgkXADE2IG5akaZhDmQsWQGgA) - no graphical output
* [Try this at RDRR!](https://rdrr.io/snippets/embed/?code=f%3Dfunction(n)plot(rbind(p%3C-cbind(cos(t%3C-(1%3An%2Fn%2B1%2F8%2B(!n%25%258)%2F2%2Fn)*%0A2*pi)%2Csin(t))%2Cp%5B1%2C%5D)%2Ct%3D%22l%22%2Cann%3DF%2Cxaxt%3D%22n%22%2Cyaxt%3D%22n%22%2Cxaxs%3D%22i%22%2Cyaxs%3D%22i%22)%0Af(15)) - includes graphical output
A function taking a single argument \$n\$ and plotting a polygon with \$n\$ sides circumscribed by a square. If \$n \bmod 8 ≠ 0\$ then one of the polygon’s points will be at 45°; otherwise one of them will be at 360/2n°. The points are then calculated using sin and cos. R’s plot function will plot the bounding square and maximise the polygon to that square. The rest of the code is just ensuring there’s nothing additional plotted like axes titles and ticks.
*Thanks to @pajonk for saving a byte!*
[Answer]
# JavaScript (ES2019), 216 bytes
```
f=
n=>`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${[l=(M=Math).min(...b=(a=[...Array(n)].map((_,i)=>[M.sin(w=((i*2+!(n%8))/n+.25)*M.PI),M.cos(w)])).flat()),l,l=M.max(...b)-l,l]}"><path d="M${a.join`L`}Z"/></svg>`
```
```
html{height:100%;display:flex;}body{display:flex;flex-direction:column;align-items:start;}img{flex:1;}
```
```
<input type=number min=3 max=16 oninput=o.src="data:image/svg+xml,"+f(+this.value)><img id=o>
```
The function, here assigned to `f` for convenience of the test snippet, outputs an SVG of the polygon filled in black, which the test snippet converts to a `data:` URL so that it can set it as the source of the image.
[Answer]
# LOGO, ~~195~~ 192 bytes
```
TO p :n
make "u 0make "v .1 pu
for[i 0 32][make "a(:i*2+not :n%8)*180/:n+45make "x cos(:a)if :x<:u[make "u :x]if :x-:u>:v [make "v :x-:u]if :i>15[pd]setxy (:x-:u)*99/:v ((sin :a)-:u)*99/:v]END
```
Run at <https://www.calormen.com/jslogo/>
Call the procedure like this: `p 16`
Recommended to do `cs p 4` to clear the screen and draw a bounding box. `ht` and `st` hide and show the turtle.
The loop starts with a `pu` to lift the pen up and always iterates 32 times. This ensures the correct minumum and maximum values of `x = cos a` are contained in `u` and `v`. After 16 iterations the pen is put down with `pd` and the polygon is drawn at the correct scale.
] |
[Question]
[
Given year, month and optionally weekday of 1st, output the calendar of the month. The first week should remain nonempty.
For empty cell, fill it with the date where it's supposed to be, in last or next month, and add `#` to indicate gray. If last few days can't fit in 5 lines, then they share last line with 5th week, use `/` to separate two days.
Sample Input: `Nov 2023`
Sample Output:
```
#29 #30 #31 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 #1 #2
```
Sample Input: `Dec 2023`
Sample Output:
```
#26 #27 #28 #29 #30 1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24/31 25 26 27 28 29 30
```
Sample Input: `Feb 2026`
Sample Output:
```
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
#1 #2 #3 #4 #5 #6 #7
```
Outputting a 2D array of string is fine. SMTWTFS and MTWTFSS are both allowed. Input is flexible.
Shortest code win.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~108~~ 93 bytes
```
≔⊕⪪”)∨←∧h”¹ε§≔岬﹪⊟Φ↨N¹⁰⁰ι⁴UMεI…·¹⁺²⁸ιNη≔⁺⁺#⮌…⮌§ε⊖ηN§εηυF⁻Lυ³⁵§≔υ±⁷⁺⁺§υ±⁸/⊟υE…⪪⁺υ⁺#⊟ε⁷¦⁵⭆ι◧λ
```
[Try it online!](https://tio.run/##ZVHRasMwDHzvV5jsRYaMNe66FfbUZQwKbQntF3iJmhgcOyR22b4@k91uSxnGAku6051cNrIvrdTjuB4GVRvYmLLHFo3DCo6dVg4SIbJ4QkhSlnGeMuQvswti7Tamwk/AlImU7a2Dna28tlDYDt6VdtjDqxyQmDvv9r79oAQxZPM5RRXIHjknup3sctu20lSBK5eDC2K0H9QZD9LUCFnKCnqDWEVgAE1Jm19NENtiSO5I8gHP2JOE/KvUmDck7CczUf@Gf84bHnTdKI6ZSXsT3p5GnmzPYKcMDduiqV0DniqLJefsdkOe1oO1dAjP/Ookhv/1VeBOHpLQRmJ9tFr0ytByZTexcfmhyOKvlNFwQGFUHEYt6R4dweuAVlSW1RZPDnTKnuIex1HMxWKWidlyvD/rbw "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order year, month, weekday (0-indexed). Explanation:
```
≔⊕⪪”)∨←∧h”¹ε§≔岬﹪⊟Φ↨N¹⁰⁰ι⁴UMεI…·¹⁺²⁸ι
```
Get an array of lists of the days of the months as strings, with February calculated according to whether the year is divisible by four.
```
Nη≔⁺⁺#⮌…⮌§ε⊖ηN§εηυ
```
Input the month and concatenate any necessary trailing days from the previous month to the current month.
```
F⁻Lυ³⁵§≔υ±⁷⁺⁺§υ±⁸/⊟υ
```
If there are more than 35 days then fold the extra days into the previous week. (The assignment uses `-7` because the extra day has been popped by this point.)
```
E…⪪⁺υ⁺#⊟ε⁷¦⁵⭆ι◧λ
```
Fill any remaining days with days from the next month and pretty-print the output. (`…⪪⁺υ⁺#⊟ε⁷¦⁵` would just output the 2D array.)
[Answer]
# [Python](https://www.python.org), 165 bytes
```
from datetime import*
lambda y,m,w,k=timedelta:[*zip(*[(f"#{(q:=date(y,m,1)+k(t-w)).day}"[q.month==m:]+f'/{q.day+7}'*(t>27>(q+k(7)).month==m)for t in range(35))]*7)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY9LCsIwFEXnriLowPfS-KtKpRA3UjqItLFBk7ThiVRxJU6cqAtwNe5Gizg-58C910fdUuXd7XY_kB6t3k8dvGWFopKMLZmxtQ_Ee1ruld0UirXCiqPYyY4W5Z5UmvGTqYFnoPuDMzSp7GLovBlGO6DREXFcqPbSz5qx9Y4qKW2aR3o4OTcdiJLLkAOt42QNzbdIvv7fQ-0DI2YcC8ptS5gvEXOeYP6b-6qDcQQa4mk8F7NYLBB_5H_oAw)
MTWTFSS. Takes one-indexed year and month, and zero-indexed weekday
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 59 bytes
```
ọ4,25>/“ḢȷĠ’b4¤o+28ṙḣ3RUḣ€1¦⁵UṾ€€Ż€€ÐoẎs7ḣ6µṪẠƇż@Ṫj€”/ṭo”#G
```
[Try it online!](https://tio.run/##y0rNyan8///h7l4THSNTO/1HDXMe7lh0YvuRBY8aZiaZHFqSr21k8XDnzIc7FhsHhQLJR01rDA8te9S4NfThzn1ADhAd3Q2hD0/If7irr9gcqMrs0NaHO1c93LXgWPvRPQ5AZhZIScNc/Yc71@YDaWX3////GxkYm/03/m8KAA "Jelly – Try It Online")
A full program that takes three integer arguments: the 4-digit year, the 1-indexed month, and the 0-indexed day of the week for the first of the month. My example on TIO assumes Monday as the first day of the week. The output to STDOUT is a calendar in the desired format.
The first 7 bytes are taken directly from [@Dennis’ clever answer to a previous question on calculating leap years](https://codegolf.stackexchange.com/a/177011/42248).
## Explanation
```
ọ4,25>/“ḢȷĠ’b4¤o+28ṙḣ3RUḣ€1¦⁵UṾ€€Ż€€ÐoẎs7ḣ6µṪẠƇż@Ṫj€”/ṭo”#G
ọ4,25 # Number of times the year can be divided by 4 and 25 (importantly the first number will be >=2 for years that are multiples of 400 and 1 for those that are other century years)
>/ # Reduce using greater than (will return 1 for leap years and 0 for others)
“ḢȷĠ’b4¤o # Or with [2,3,3,0,3,2,3,2,3,3,2,3] (This is stored as a base-250 integer than is converted to base 4)
+28 # Add 28
ṙ # Rotate to the left by the 1-indexed month number
ḣ3 # First three (will be the lengths of the months before, at and after the relevant month)
R # Ranges 1..each of these
U # Reverse each range
ḣ€1¦⁵ # For the month before, take the first x values only where x is the 0-indexed day of the first day of the main month
U # Reverse each month’s days again
Ṿ€€ # Uneval each day (will convert to Jelly strings)
Ż€€Ðo # Prefix the first and last month’s days with a zero
Ẏ # Join outer lists
s7 # Split into pieces length 7
ḣ6 # Take the first six
µ # Start a new chain with this as the argument
Ṫ # Pop the tail (the sixth row of the calendar)
ẠƇ # Keep only those where all are truthy (will remove any days from the following month since those are prefixed by zero)
ż@Ṫ # Zip the tail of the calendar with this (I.e. the fifth row of the calendar)
j€”/ # Join each with slashes
ṭ # Tag onto the remaining (first) four rows of the calendar
o”# # Or with hashes (will replace the zero prefixes with hashes)
G # Format as a grid
💎
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Scala 3](https://www.scala-lang.org/), ~~239~~ 224 bytes
Saved 15 bytes thanks to @corvus\_192
---
MTWTFSS. Takes one-indexed year and month, and zero-indexed weekday
---
Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=ZVLNbhshEL7vU4yIKoG6JrWtKpUrLEXKpVIjH9yfg2UlxDuscVjYAuutFeUdeu8ll1Z9Jd_6KGV3nV4iMQPMfHzDfPDzd9hII6fHsxUZWddKb0kOZGSkLRtZ4qx2ISr9fVEHsj7-0VXtfISd3EsedYX8JnsRithFpOGfTovLYteEiD5kmbvb4SbCtdQWHjKAAhVUaUOlL8MMLr2Xh9Uyem3LNZvBZ6sjiB4JsJcG1Awo_WBjDs-OifkSv616G86tmYBfTVSjd8e_9JBXeZswD93pID661O2VjMid6nNj9r7nFYHftjpub-mLW_Pa4167Jiz8UlZIr-Rhob4i3ncc7asLxliWyvMo7xqTqOn0LaNazBWvTRMSOlDNWOldU2MBF6nfmt7wzhfyIOZUq27BS4zXzsbtF2kaFKJihKAJSM4Ie33K95V7EGPRpZqPpz5_POvjMTSmk0zRyZvJNIfxJBmD83MYw8b5lK-dLQJEB4ko8UJ6if-q9DoPHFw5j3KzpW3qFMQc6iRuNLbf8-p-EJsS2n2XYTDSSQHwmJ3u9fQ0zP8A)
```
(y,m,w)=>{val s=LocalDate.of(y,m,1);val f=s.`with`(TemporalAdjusters.previousOrSame(DayOfWeek.of(w%7)))
Seq.tabulate(35)(i=>f.plusDays(i))grouped 7 map(_.map(day=>(if(day.getMonthValue==m)""else"#")+day.getDayOfMonth))toSeq}
```
Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=ZVPNahsxEIYe9ymGbQoSdZXEpqQYXAjkUmjIwWlzKCGZeLW2nN3VIs06NWafpJdc2ofqs-RQ_dl1ElgWjWa-75sfza8_doYVjh4ff3dUfvj0982TqlttCJa4QkGqluIme3VF0t9gJS7T4bRYdpaksVmm75ZyRnCOqoFNBlDIEmpnMDRzO4ZTY3D9Y0pGNfNrPoZvjSKYhMgYW7K1RDOGLw0NoNYNLdL5Qcr7AtfB4luiZ3TXOyKAFVYRPSU0XuGrdpWeIUmho0RiH8Ax38OUylg6w_VFeeX0HO4_ibh9ULS4Za-KFq2RK6U7e2GmWEu2g3splvKGd3DC4T0ccc6zPUHnsk4mFCII77rK5chGHzlTMPn8Ih_RVp11lmWK72ftNTyLJxNzo7tWFuyEC9KBN0WGKFFjy278HzY-3okkd6RytZTqp-NSJTDnF3NJ574H37HqJExSRzjkOcjKSsjf5jsCmx9E_MEmQUPqAd9vw_qYeR-74DWNtF3lh1Sy4dFw5EYy9GOBw0M4hpk2zt_qprBAGhyXz9q9rt1EA0_kEKU2EmeL0HXfv9a9DKqaYIv6Pr4UlrN8AOnjOQ-97LM-LkHahe1O_AM)
```
import java.time._
import java.time.temporal.TemporalAdjusters
object Main {
def main(args: Array[String]): Unit = {
def f(year: Int, month: Int, weekday: Int): Array[Array[String]] = {
val monthStart = LocalDate.of(year, month, 1)
val firstDayOfWeek = monthStart.`with`(TemporalAdjusters.previousOrSame(DayOfWeek.of((weekday % 7) + 0)))
val days = Array.tabulate(35)(i => firstDayOfWeek.plusDays(i))
val weeks = days.grouped(7).toArray
weeks.map(_.map { day =>
val prefix = if (day.getMonthValue == month) "" else "#"
s"$prefix${day.getDayOfMonth}"
})
}
val result = f(2023, 12, 1) // 1 corresponds to Monday in LocalDate
result.foreach(week => println(week.mkString("(", ", ", ")")))
}
}
```
[Answer]
# Google Sheets, 134 bytes
`=wraprows(index(regexreplace(substitute(text(sequence(35,1,A1-weekday(A1,2)*(mod(A1,6)<>4)),"MMMd"),text(A1,"MMM"),),"[A-z]+","#")),7)`
Put a value like `Nov 2023` in cell `A1` and the formula in cell `B1`.

The rules allow that the weekday can be specified separately. To do that , put `=weekday(A1, 2)` in cell `B1` (**123 bytes**):
`=wraprows(index(regexreplace(substitute(text(sequence(35,1,A1-B1*(mod(A1,6)<>4)),"MMMd"),text(A1,"MMM"),),"[A-z]+","#")),7)`
(does not produce `24/31` for `Dec 2023`)
[Answer]
# JavaScript (ES6), 123 bytes
Expects `(year, month)(weekday)`, where *weekday* is 0-indexed SMTWTFS.
```
(y,m,n=0)=>g=w=>n++<35?(n-(h=k=>i=new Date(y,m-1,n-w+k).getDate())``&~7?"#"+i:i)+(n*h(7)>868?"/"+i:"")+`
`[n%7&&1]+g(w):""
```
[Try it online!](https://tio.run/##XY/LboMwEEX3fMWIqmimtmlM1BAltdm0X4GQQNQ88rCrBBWx6a9TU3WBujznns09VV/Vvb71n4Ow7sPMjZpx4ldu1YaUbtWotGXsdfuSoRXYqbPSvbJmhLdqMEspJLdiZGeKWzP8SqKyjL7TLHwIWX/oiaF96jAlvd/ts/B5kWFIrAygzO1jGkWyYC2O5O18zAOAHJJNsuUAKRR8xVL@42TFO997Doogbtztvao7xBwmDlcoCJSG2tm7u5j44lpscBkIV0d8J0D@vZj8CaLj/AM "JavaScript (Node.js) – Try It Online")
### Method
We walk through the calendar slots by iterating from `n=1` to `n=35`.
The helper function `h` takes a parameter `k` and returns the date of the month for the year `y`, month `m` and day `n-w+k`. The result is saved in the global variable `i`.
```
h = k =>
i = new Date(y, m - 1, n - w + k).getDate()
```
If `n - h(0)` is negative or greater than 7, it means that the date belongs to the previous or the next month respectively. Hence the test:
```
n - h(0) & ~7 ? "#" + i : i
```
We have to add the `/xx` pattern if we are located on the last row of the calendar (`n ≥ 29`) and the date at +7 days still belongs to the current month. For this purpose, we use the test:
```
n * h(7) > 868
```
This test is true if and only if `n ≥ 29` and `h(7)` reaches a threshold corresponding to one of the last few days of the month:
| n | h(7) |
| --- | --- |
| 28 | ≥32 (impossible) |
| 29 | ≥30 |
| 30 | ≥29 |
| 31 | ≥29 |
| 32 | ≥28 |
| 33 | ≥27 |
| 34 | ≥26 |
| 35 | ≥25 |
] |
[Question]
[
*The reason for this question is because I made a [deadlineless bounty](https://codegolf.meta.stackexchange.com/a/26136/78850) and I need a tips question to link in the bounty*
Vyxal 3 is the third major version of the Vyxal golfing language. As it is significantly different to Vyxal 2, the tips there don't apply.
Therefore, what tips and tricks do you have for golfing in Vyxal 3? Avoid giving obvious
help like "remove whitespace", "limit variable usage", "remove comments" and "don't pad your program with 20000 among us characters".
One tip per answer please.
Literate mode golfing tips are also welcome.
[Answer]
# Compress Strings and Numbers
Like Vyxal 2 before it, Vyxal 3 has dictionary string compression and base-based compression. However, in Vyxal 3, dictionary strings use Jelly's sss and base-based compression uses base-252 instead of base-255.
Dictionary compression works on all strings, base string compression only works on strings of lowercase alphabet + space (`[a-z ]`), base number compression only works on positive numbers.
To compress a string using dictionary compression:
```
"Some string" #C
```
To compress a string using base compression:
```
"some lowercase string" #c
```
To compress a number using base compression:
```
69420 #c
```
## Examples
| Original Value | Dictionary Compressed | Base Compressed |
| --- | --- | --- |
| `"hello world"` | `"Ṙ=?”` | `"ᶠ»_Ṃ†ᵘy„` |
| `"Hello, World!"` | `"Ḍᵗ{w<ᵏ”` | NA |
| `69420` | NA | `"ᵇᵡy“` |
] |
[Question]
[
Your challenge is to output the number of twisted corners given a 2x2 Rubik's Cube scramble.
For the purpose of this challenge, twisted corners are defined as corners where the colour of the top/bottom face before (usually white or yellow) is not facing the top/bottom after the scramble.
Eg. if the cube were to be oriented yellow top/white bottom, then the number of corners where yellow/white isn’t on the top/bottom after the scramble should be returned.
A scrambled cube is represented as a list of moves, where each move is denoted by the letters `UDRLFB` corresponding to clockwise turns of the faces: Up, Down, Right, Left, Front, and Back.
You have the option to replace the moves `UDRLFB` with a predefined set of constants. You may assume the scramble list is non-empty.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins!
Standard loopholes apply, [this loophole](https://codegolf.meta.stackexchange.com/a/14110) in particular is forbidden too.
## Test cases
[Example gif with scramble "L U U U F"](https://i.imgur.com/I3H6Nze.gif) | [Top and bottom face after scramble](https://i.imgur.com/psxC5pK.png)
```
[In]: R
[Out]: 4
[In]: L U U U F
[Out]: 3
[In]: R R D D D B B U L F
[Out]: 6
[In]: B U U D D F
[Out]: 0
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 67 bytes
```
≔Eχ⁰θFES⌕DBRUFLι«≔I⪪§⪪”)⧴∧\ⅈNυSB⊞ae”⁴ι¹ηUMθ⎇№ηλ﹪⁻ι§θ§η⊖⌕ηλ³κ»I№X⁰θ⁰
```
[Try it online!](https://tio.run/##RZDbaoQwEIav16cIXk0gBY/rRa9WRVhYYXG7DxA0XUM10Rh7oPTZ7ehuaWBCDv/838zULTe15t2yHKZJ3hSUfADfY8SjjIz02XnVhmyPRzXM9mKNVDfAv0KqBtw8ra7FyWVEUkrJt7N7uGR8snAZOmnhYI@qEZ@PmxuEyT7aJ7EfJ6EXxb7nh4EX7CP0iOjqw4hPcWuRvUNupvueI2pk5EUYxc0XZHpWFlpGOtSVupk7DaVU8wSSkT/c@H9EZS5qI3qhrGhgq3zLXhcjIcYbRdyPc8bu7L34O@SsP4QBbx3FOhJULUtV5XmeptdTsTy9d78 "Charcoal – Try It Online") Link is to verbose version of code. Takes a string of `DBRUFL` as input. Explanation:
```
≔Eχ⁰θ
```
Start with an array of zeros representing the untwisted corners. (There are ten rather than eight to save a byte.)
```
FES⌕DBRUFLι«
```
Map the input string into the integers `0-5` and loop over them. (The mapping is contrived to make the calculation below shorter, which is why I didn't require that as the input format.)
```
≔I⪪§⪪”)⧴∧\ⅈNυSB⊞ae”⁴ι¹η
```
Look up the corner permutation for this move, which is a list of indices of the corners that move in clockwise order.
```
UMθ⎇№ηλ﹪⁻ι§θ§η⊖⌕ηλ³κ
```
For those corners that move, find the corner that moves to this corner, and subtract its value from the move index, modulo `3`.
```
»I№X⁰θ⁰
```
Output the final number of twisted corners.
22 bytes if I abuse the input format:
```
≔E⁸ιθFAUMθ§⮌↨ιφκI№÷θχ⁰
```
Takes input as an array of integers which represent a mapping to apply to the positions of the eight white and yellow stickers. No TIO link because I haven't actually bothered to compute suitable integers.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Pushes the I/O rules to the edge ([confirmed that it is acceptable](https://codegolf.stackexchange.com/questions/266733/how-many-twisted-corners?noredirect=1#comment581495_266733))
```
œ?@ƒ24s3I§ḂS
```
A monadic Link that accepts a list of permutation indices of the 24 showing *facelets*\* and yields the number of *twisted corners*.
\* i.e. the stickers on older cubes.
**[Try it online!](https://tio.run/##FcwrCgJRGEDhvQzYbvjfj6RJEASD3CRGi0wzWS0Gmy7CLQg2RfcxK7mO6ZSPs9/1/bG1z206@15JDrx43YfHad1WE8ThedkEQiRAEoQDC2OyAWDhVHRjwqIkJsEIqEnkWchhrLkjpTkFOTJHSmE3YPzvTJJUbfQggQUKq6ari6WGgqJA4PZ9bq1b1lrn3Q8 "Jelly – Try It Online")** (The footer converts the usual characters to the defined constants.)
### How?
We label the eight corners using the three faces to which they belong in some arbitrary order, starting each with their U/D face and reading anticlockwise (again an arbitrary choice):
```
UFR URB UBL ULF DRF DBR DLB DBR
```
Now we label these stickers when in a solved state:
```
ABC DEF GHI JKL MNO PQR STU VWX
```
Now we record the six face-turn permutations:
```
D: ABC DEF GHI JKL VWX MNO PQR STU
L: ABC DEF UST HIG MNO PQR WXV LJK
B: ABC RPQ EFD JKL MNO TUS IGH VWX
U: DEF GHI JKL ABC MNO PQR STU VWX
F: KLJ DEF GHI XVW CAB PQR STU NOM
R: OMN BCA GHI JKL QRP FDE STU VWX
```
Now we find the index of each of these in all permutations of the solved state labelling by using code that I wrote that was added to [Jelly](https://github.com/DennisMitchell/jellylanguage/blob/70c9fd93ab009c05dc396f8cc091f72b212fb188/jelly/interpreter.py#L823) many moons ago (along with its family including `œ?`, see below) - [TIO](https://tio.run/##y0rNyan8///o5EP7HzWt@f//f7SSo5Ozi6ubu4enl7dPWHiEr59/QGBQcEiokg6XAlQyNDjEw9MdIhMeEebj5Q2TDAoIdHVzAeoESoaEBnu6ewCNAEvCzQSqgpsJk/T28YLIR4SFOzs6QST9/H3Bkv6@fk7OjhDNgUEBbi6ucJ2x/1Gci2IuAA):
```
D: 395176321
U: 5246483101592279
B: 35597574695850514081
F: 81089009208703431936001
U: 270227677129672827133894
R: 376031890064925569220481
```
Now with a list of these constants as our input, we can perform the permutations in turn and find the number of *twisted corners*:
```
œ?@ƒ24s3I§ḂS - Link: list of the defined constants, Scramble
24 - twenty four
ƒ - start with State=24 and reduce using Scramble's Constants:
@ - with swapped arguments:
œ? - permutation at index {Constant} of the items in {State}
(when State=24 it's implicitly cast to [1..24])
s3 - slice into threes (first of every triple is the U/D facelet)
(when Scramble="" the 24 we have is cast to [1..24] giving
us [[1,2,3],...,[22,23,34]])
I - forward differences of each
§ - sums
Ḃ - modulo two
S - sum
```
] |
[Question]
[
This is an [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") challenge where you will draw ascii-art showing a person "jumping" off the top of a building.
---
## The building
Input given will be a group of rectangular buildings. You may assume buildings are not "stacked on top of each other", hence only one row of buildings. This is the standard format of a building:
```
-----
| |
| |
| |
| |
```
A row of buildings looks similar.
```
------
----- --------------| |
| | | || |
| |----| || |
| || || || |
| || || || |
```
You may choose to remove the duplicate `|` between two buildings if you would like.
Yes, buildings may be taller than the ones on their lefts, but you may assume that all buildings have a nonzero height.
This group of buildings will be given as input, in addition to the building index, which can be 0-or-1-indexed. (please specify which in your answer.)
You can also take input as an array of building characteristics or two arrays of heights and widths.
## The person
A person is represented by an `o`. The person always starts on the right of the given building, and starts jumping immediately.
## Jumping
To quote [this article](https://www.reference.com/science/high-can-human-jump-114181691a696256),
>
> The greatest human leapers in the world are able to jump over a bar suspended nearly 8 feet off of the ground.
>
>
>
Since I go by meters, this is about 3 meters (actually about 2.5, but whatever.) The person will hence jump "diagonally" for 3 meters (lines) before starting to fall, after which the person will also fall diagonally until hitting the top of a building or the ground.
Each meter should be represented by another `o` at the exact position.
## Example
Example is 1-indexed.
Given the above row of buildings and the index `1`, this would be the trajectory:
```
o
o o
o o
o o ------
----- --------------| |
| | | || |
| |----| || |
| || || || |
| || || || |
```
The person started at the right of the first building, then there were 3 `o`s going upwards before the `o`s started trending downwards. The o's stopped the moment the person hit the third building.
Given index 3:
```
o
o o
o o
o------
----- --------------| |
| | | || |
| |----| || |
| || || || |
| || || || |
```
Note that the person cannot be stopped by the top of a building before completing his 3-meter initial jump.
Given index 4:
```
o
o o
o o
o o
------ o
----- --------------| | o
| | | || | o
| |----| || | o
| || || || | o
| || || || | o
```
The person stopped after hitting the ground.
Given index 2:
This particular case is impossible as the person is stopped by the wall of the following building. This brings another rule into the challenge: you are allowed to assume that there will never be impossible input, i.e. one where the person is stopped by another building's wall in the way, whether in his initial 3-meter jump or as he is coming down (the top of the building does *not* stop the person from jumping).
You are also permitted to use a character other than `o` as long as it is none of `|-` (note the trailing whitespace, you may not use whitespace to denote the person.)
Macrons are permitted (the ones which look like "overscores") and if you do use them you may count them as one byte. There will never be gaps between buildings.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins with standard loopholes disallowed as usual.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 45 bytes
```
FLθ«↑⊖§θι§ηι↙↓⊖§θι↗»J⊖Σ…η⊕ζ±§θζ↗oooW∧⊖ⅉ¬℅KK↘o
```
[Try it online!](https://tio.run/##hY/BTgIxEIbP8hQTTtOkHlD0gCcCFwwqUTkYwmGzO2wbup2lKaAYn722S4D15KXJfJ3//zK5ylzOmQlhxQ5wSrb0CjdCwHfnaua09TiY1xLGlDuqyHoqcOgntqBP3EjQQoiH0@KJq4ZH/MQ7wsGY93ZKK39ZbNB/ncfwvH7VpUrZn87jtqrfGduxt22Fo6/c0EhxncQTe/k8xCIh4ZnKzFPbcEiC83GNQEKXmbuR75U2BDi0xR/TBzZd7PHFFdpmBmdEa0wKAa2zzm2xK4TF4k7CrYT43i8lpKkvodc/jjfLcL0zvw "Charcoal – Try It Online") Takes as input an array of heights, an array of widths, and a 0-indexed building. Explanation:
```
FLθ«
```
Loop over each building.
```
↑⊖§θι
```
Draw the left wall.
```
§ηι↙
```
Draw the roof.
```
↓⊖§θι↗
```
Draw the right wall.
```
»J⊖Σ…η⊕ζ±§θζ
```
Jump to the corner of the building.
```
↗ooo
```
Print the leap.
```
W∧⊖ⅉ¬℅KK
```
Repeat until the ground or a roof is reached.
```
↘o
```
Print the fall.
] |
[Question]
[
**Setup:**
A *block* is any rectangular array of squares, specified by its dimensions \$(w,h)\$. A *grid* is any finite ordered list of blocks. For example, \$\lambda = ((3,2),(3,1),(1,2))\$ defines a grid.
Let \$\lambda\$ and \$\mu\$ be two grids with equal area.
A *tiling of \$\lambda\$ by \$\mu\$* is any rearrangement of the squares of \$\mu\$ into the shape of \$\lambda\$ satisfying two properties:
1. horizontally adjacent squares of \$\mu\$ remain horizontally adjacent in \$\lambda\$, and
2. vertically adjacent squares of \$\lambda\$ come from vertically adjacent squares of \$\mu\$.
In other words, while rearranging one is allowed to make horizontal cuts to the blocks of \$\mu\$ but not vertical cuts, and one is allowed to place blocks into \$\lambda\$ side-by-side, but not on top of one another.
Two tilings of \$\lambda\$ by \$\mu\$ are considered *equivalent* if they can be rearranged into one another by any combination of either permuting squares within a column or reordering the columns of a block.
**Problem:** Write a function \$T(\mu,\lambda)\$ which computes the number of inequivalent tilings of a grid \$\lambda\$ by another grid \$\mu\$ of equal area.
**Specifications:** You may use any data type you would like to specify a grid.
**Examples:**
1. The grid \$\lambda=((1,2),(1,2),(1,1),(2,1))\$ admits a tiling by \$\mu=((1,3),(1,2),(2,1))\$ given by
[](https://i.stack.imgur.com/kuSyZ.png)
There is exactly one other inequivalent tiling given by
[](https://i.stack.imgur.com/6y0ON.png)
(Since the two differently colored columns of height \$2\$ are not part of the same block, they cannot be permuted.)
2. The three displayed tilings of \$\lambda=((3,1))\$ by \$\mu=((1,2),(1,1))\$ are equivalent:
[](https://i.stack.imgur.com/SCULm.png)
3. Let \$\lambda\$ be an arbitrary grid of area \$n\$ and let \$\lambda[(w,h)]\$ denote the number of blocks of \$\lambda\$ of dimension \$w \times h\$. Then \$T(\lambda,\lambda) = \prod\_{w,h\geq 1} \lambda[(w,h)]!\$ and \$T(\lambda,((n,1))) = 1\$.
4. The matrix of values of \$T(\mu,\lambda)\$ for all pairs of grids of area \$3\$ (row is \$\mu\$, column is \$\lambda\$):
| | ((1,3)) | ((1,2),(1,1)) | ((1,1),(1,1),(1,1)) | ((2,1),(1,1)) | ((3,1)) |
| --- | --- | --- | --- | --- | --- |
| ((1,3)) | 1 | 1 | 1 | 1 | 1 |
| ((1,2),(1,1)) | 0 | 1 | 3 | 2 | 1 |
| ((1,1),(1,1),(1,1)) | 0 | 0 | 6 | 3 | 1 |
| ((2,1),(1,1)) | 0 | 0 | 0 | 1 | 1 |
| ((3,1)) | 0 | 0 | 0 | 0 | 1 |
[Answer]
# [Haskell](https://www.haskell.org/), ~~255~~…~~247~~ 242 bytes
* -2 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor), for suggesting a better partitioning function `q`.
* -8 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs), for suggesting `[a!!i|i:_<-u]` and removing an unnecessary `map`.
```
(a#b)c d=sum[1|g<-nub$(permutations(zipWith replicate b[0..]>>=id)>>=q)>>=mapM(q.sort),l g==l c,and[l x==h&&all(==x!!0)x&&sum[a!!i|i:_<-u]==w|(u,w,h)<-zip3 g c d,x<-u]]
q=foldr(\h t->map([h]:)t++[(h:y):z|y:z<-t])[[]]
l=length
import Data.List
```
[Try it online!](https://tio.run/##hVLNbqMwEL7nKRwWpbawUdPcWIy00l5WSk897MFBlRNcsNYYggcljfLuWUOD0vbQHjzWeL6fmZEr6f4pYy66bpsO0G8JMl5rBxcsf2zJDhXc9bVYnsuU2X4b4lZ1dQ8SdGMdPun2r4YKdao1eidBoa24j@M8y7guiI/7IdSyfcT72Hl9Qg0qOTdoR6UthEFHzqvFQhqDOT/O5/fkuFgMhnI@12edPKeszzk/nHFPD7QiKfOWK1Qi3xg9DsV8tucvjSk6vKkQsMybYVHlCYEoErhKXklyOr8mp5RBToTweMONsiVUM8Y@jVxLbXnRzBAC5cClbBDrlCyS5Ak6bUuWCfzHAvWH5CQ@NF3h0jArFay1VZ5nFCAra@V423fKl8Tdrzu/EF8at7DBQC1hWduDV1zb0EZRgDgKoshVzQEBCf2Ab/ZvQp45gYPgJvP8TiYMNuAF7LfcF@Pro8AnIAnR1Nk4/sQb2/Pi49PXbEfrG3tcBJZ0S3hvR/RPvKPFlLkr6GoyTI6n70beOd6avwi8pCuSo@F@INTH5TVbXrPb28OHbDXc/wE "Haskell – Try It Online")
A grid \$\mu\$ is represented as a pair \$(W\_\mu,H\_\mu)\$ where \$W\_\mu\$, \$H\_\mu\$ are lists containing, respectively, the widths and the heights of the blocks in \$\mu\$.
The relevant function is `(#)`, which takes as input four lists: `a`\$=W\_\mu\$, `b`\$=H\_\mu\$, `c`\$=W\_\lambda\$, `d`\$=H\_\lambda\$. It returns the integer \$T(\mu,\lambda)\$.
] |
[Question]
[
**This question already has answers here**:
[Bot Factory KoTH (2.0)](/questions/217972/bot-factory-koth-2-0)
(9 answers)
Closed 3 years ago.
**Note:** [Bot Factory KoTH (2.0)](https://codegolf.stackexchange.com/questions/217972/bot-factory-koth-2-0) is now posted; you're probably looking for that one instead!
In this challenge, bots (consisting of JS functions) move around an infinite factory (playing field), collecting characters (UTF-16). These characters can be used to build worker bots, or droppedfor other bots to pick up.
## Results
Average number of characters collected per game (20k rounds)
```
[1484.5] The Forsaken Farmer
[1432.9] The Replicator
[957.9] Safe Player V2
[739.1] Hunter
[101.65] First
[9.75] IDKWID
```
## The Factory
All bots start out randomly placed around the center of the factory, `[0, 0]`, where coordinates are arrays `[x, y]`. North is -Y, and west is -X. Each round consists of up to 100000 turns. A bot may move one space in any cardinal direction (or build a worker, or drop a character) per turn.
Bots can move by returning `north()`, `east()`, `south()`, or `west()`.
## Characters
Characters will be randomly distributed, centered around `[0, 0]`. There are always up to a total of 4 characters per bot at any given time (excluding those from dead bots).
Character's positions may overlap, and their character value (such as `a` or `(`) is selected from a pool of the source code of every bot and worker currently in the factory.
Bots collect characters by moving into the same position in the factory, and these collected characters are stored within the bot.
Bots may also drop a character they have previously collected in any of the four cardinal directions. This character is then removed from the bot's collected characters array.
Bots drop characters by returning `drop.north(c)`, `drop.east(c)`, `drop.south(c)`, or `drop.west(c)`, where `c` is a string.
## Score
Bots have a score, which is initially `-floor(sqrt(LEN))`, where `LEN` is the length of the bot's source code in characters. Worker bots start with a score of 0 regardless of their length.
Whenever a character is collected, this score value increments; when a character is dropped, it decrements.
## Collisions
When two or more bots collide (occupy the same position), whichever has the highest score survives (if there is a tie, none survive). All bots that die "drop" the characters they have collected, which are randomly distributed centered around the position they collided in.
Bots can switch places by moving into each others' previously occupied positions without colliding.
## Workers
Bots can use the characters they have collected to build a worker bot. A worker bot's source code (provided as a function or arrow function) must be entirely made up of characters its owner has collected, which are then removed. Half of the length of the worker's source code is deducted from the owner's score.
Worker bots are placed randomly around the position of their owner, using the same system as characters, and are not immune to collision. Worker bots can also build worker bots, whose owner would be the worker.
Workers can be built by returning the result of the function `build(source)`, where `source` is a string. If the bot cannot be built (such as not having all necessary characters), nothing happens.
## Functions
All bots are functions. They are provided a single argument, an object that can be used for storage, and can access information about other bots and characters using the following functions:
* `bots()`: Returns an array of bots (as objects)
* `chars()`: Returns an array of characters (as objects)
* `self()`: Returns the bot that called it (as an object)
* `owner()`: Returns the owner of the bot that called it (as an object, `null` if owner is dead, or `self()` if no owner)
A bot object has the following properties:
* `uid`: An integer ID unique to each bot, randomly selected
* `owner`: The UID of the bot's owner
* `score`: The score of the bot
* `pos`: The position of the bot formatted as `[x, y]`
A bot object also has the following properties if it is the owner or worker of the bot:
* `chars`: An array of characters the bot has collected
* `source`: A string with the bot's source code
A character object has the following properties:
* `char`: A string
* `pos`: The position of the character formatted as `[x, y]`
There are also the following library functions:
* `center()`: Get average of bots' positions weighted by score
* `turn()`: Get current turn (starts at 0)
* `dir(from, to)`: Get direction from `from` to `to`, which should be arrays formatted `[x, y]`
* `dirTo(pos)`: Same as `dir`, uses `self().pos` as `from`
* `dist(from, to)`: Get taxicab distance from `from` to `to`, which should be arrays formatted `[x, y]`
* `distTo(pos)`: Same as `dist`, uses `self().pos` as `from`
## Winning
Once all surviving bots are direct or indirect workers of the same initial bot, characters will no longer generate. Games automatically end when all characters are collected.
The winner is the bot which, after some number of rounds, has collected (or had workers collect) the most characters.
## Rules
* Bots may not use global variables in a way which produces side effects other than intended (such as to sabotage other bots or the controller)
* Bots which error will be killed and drop their characters
* Bots may only attempt to build workers which are valid functions
* Bots may not take an unnecessarily long time to run (no hard limitation, but be reasonable)
* Bots may not team with other which do not originate from the same owner (directly or not)
## Technical Notes
* Character and bot spawning radius is based on a geometric distribution (`p=0.1`), with a random angle. The resulting coordinates are truncated to integers. Repeated until a position is found with no bots within a taxicab distance of 4
* For dead bots' drops, `p=0.2` and there is no distance requirement
* For worker bot spawning, minimum taxicab distance is 3 for the owner
* Every time a character is picked up, one attempt is made to generate another. An attempt will only fail if there are already `4 * botCount` characters not dropped by a bot (or a bots' death), where `botCount` is the total number of alive bots (including workers). `4 * botCount` characters are generated at the start.
## Example Bot
ExampleBot uses an arrow function to keep its starting score higher, but still isn't well golfed. It likes characters which are in the middle of the action, which it finds by sorting the `chars()` array and using the `dist` and `center` library functions. It will not be included in the competition game.
```
() => dirTo(chars().sort((a, b) => dist(center(), a.pos) - dist(center(), b.pos))[0].pos)
```
**Controller:** <https://gist.github.com/Radvylf/31408373bae12843bfbf482188653a42>
**Edit:** Fixed the controller. Made a few changes before putting it in the gist to clean up some debugging and deleted a few things by mistake. Sorry about that, should be up and running!
**Due Date:** Challenge completed
**Prize:** Bounty (100 reputation)
**Chatroom:** <https://chat.stackexchange.com/rooms/105613/bot-factory-koth>
[Answer]
# Safe Player V2
```
_=>dirTo((f=(t,z)=>chars().flatMap(c=>t.reduce((a,b)=>a-(dist(b.pos,p=c.pos)<=(d=distTo)(p)),z)?[]:[p]).sort((a,b)=>d(a)-d(b))[0])(a=bots(),1)||f(a.filter(b=>b.score>self().score),0)||[0,0])
```
Finds the closest character that it can get to first and goes towards it. If no such character exists, it repeats the process but this time ignoring bots with a lower score than itself. Goes to the center if it still can't lock onto any character.
[Answer]
# The Forsaken Farmer
This entry finds the nearest character and then proceeds to repeatedly drop it and pick it up, netting a total of 1 score per two moves... except it doesn't, because the spec was updated to account for that. No matter, though - winning is dependent on character pick up count, not score.
```
_=>(c=self().chars).length?drop.west(c[0]):dirTo(chars().sort((a,b)=>(d=distTo)(a.pos)-d(b.pos))[0].pos)
```
[Answer]
# IDKWID
Short for "I don't know what I'm doing".
```
_=>dirTo(chars().sort(distTo)[0].pos)
```
~~Greedily tries to get the closest character to it. I think.~~ A couple of minutes of thinking have led me to believe that this is not the case. It does something stupid instead. Often loses to Example Bot.
[Answer]
# The Replicator
~~Presumably replicates itself... very slowly.~~ Probably replicates itself, but if I'm understanding the situation correctly, then a replication attempt currently crashes the runner (`hasChars is not defined at runTurn (<anonymous>:205:33)`). Rudimentarily code-golfed.
```
_=>{d=distTo;c=s=>s.reduce((a,v)=>({...a,[v]:(a[v]|0)+1}),{});s=self();a=c(s.chars);b=c((s=s.source).split``);for(v in b)if(!(b[v]<=a[v]))return dirTo(chars().sort((a,b)=>d(a.pos)-d(b.pos))[0].pos);return build(s)}
```
[Answer]
# First
```
_=>dirTo(chars()[0].pos)
```
Just go towards the first char. This has an initial score of -4, much better than most.
[Answer]
# Hunter
This bot will go towards the closest object that is a char or a bot with less score than it.
```
_=>dirTo((chars().concat(bots().filter(b=>b.score<self().score))).sort((a,b)=>distTo(a.pos)-distTo(b.pos))[0].pos)
```
] |
[Question]
[
What general tips do you have for golfing in [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt)? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to MathGolf (for tips which can be applied to loads of programming languages, [look at the general tips](https://codegolf.stackexchange.com/questions/5285/tips-for-golfing-in-all-languages)).
[Answer]
Writing `513` in a MathGolf program will push three separated digits (`5`;`1`;`3`), instead of the number `513` itself.
In MathGolf there are therefore quite a lot of 1-byte builtins for numbers: `-3` through and including `38`; `60`; `64`; `100`; `128`; `256`; `512`; `1000`; `1024`; `2048`; `3600`; `4096`; `10000`; `86400`; `100000`; `1000000`; `10000000`; `100000000`.
However, for other numbers it can sometimes be tricky to find the shortest way to generate it, so here an overview of the integers in the range `[1, 1000]`:
*NOTE: This is W.I.P. I will add more when I have some time. I was unable to make an evaluation program to check all possibilities (thus far), so these were done by hand.. I've also made it a community wiki, so if anyone else finds shorter alternatives or wants to continue with the numbers, feel free to edit it.*
Of course many variations can be found for certain numbers, as can be seen [here](https://codegolf.stackexchange.com/revisions/194072/3) and [here](https://codegolf.stackexchange.com/a/182421/52210). So the list below contains just one of the shortest variations.
```
-3-0: d, c, b, 0
1-10: 1, 2, 3, 4, 5, 6, 7, 8, 9, ♂
11-20: A, B, C, D, E, ☻, F, G, H, I
22-30: J, K, L, M, N, O, P, Q, R, S
31-40: T, ♥, U, V, W, X, Y, Z, Z), Z⌠
41-50: Dx, J∞, Vx, K∞, K∞), L∞, L∞), M∞, 7², N∞ TODO: 2-byters for 45,47
51-60: Ex, O∞, Wx, P∞, ♂f, Q∞, ╟╫, R∞, ╟(, ╟
61-70: ☻x, T∞, Xx, ♦, ♦), U∞, U∞), V∞, V∞), W∞ TODO: 2-byters for 67,69
71-80: Fx, X∞, Yx, Y∞, Y∞), Z∞, Z∞), Z∞⌠, ♦E+, ♦F+ TODO: 2-byters for 75,77,78,79,80
81-90: Gx, Qx, Zx, Zx), Zx⌠, ♦K+, ♦L+, R■, ♂f, ♦O+ TODO: 2-byters for 84,85,86,87,90
91-100: Hx, Rx, ♦R+, T■, ♦T+, ♦♥+, ♦U+, ♀⌡, ♀(, ♀ TODO: 2-byters for 93,95,96,97
TODO: Continue through 1000
```
Here is a universal constant-generating method in MathGolf. Example (generating 513):
```
û☺☻$
```
This defines a two-character string and takes its ord code. The ord code of `☻` is 2, and the ord code of `☺` is 1. The ord code of this string is therefore `2*256+1=513`.
Taking the ord code also works for single characters. (Constants generated by this method are likely to be unoptimal.) This one returns 2.
```
'☻$
```
Also works for string length 3 and so on...
```
ùUTS$
83*256*256+84*256+85=5461077
```
[Answer]
This post tries to explain how the compressed strings work in MathGolf (a canonical feature for golfing languages).
This mechanism is actually quite simple: say you are trying to decompress the character `Σ` via the `╢` instruction.
First of all, this character is 0xE4 in CP437. We then pass this through a lookup table. (We are decompressing using `╢`, which has the lookup table `etaoinsrdluczbfp`. There is one other such table `gwymvkxjqh ?*#.,`.)
We realize that the E'th character (in hex) in the lookup table is f. The 4th character in the lookup table is `i`. So we get the decompressed string `fi`.
>
> The way I do it is that I check the reference page and Code page 437, and I match the column and the row of the character within the code page with the indices of the string I want. So, ╕ means indexing in the string etaoinsrdluczbfp. In that string, b has index 13, z has index 12, and t has index 1. Thus, I look at row 13 and column 12 for bz, which is character ▄. Then I look at row 12 and column 1 for zt, which is character ┴. [--maxb](https://codegolf.stackexchange.com/questions/32267/play-the-bzzt-game/180918#)
>
>
>
---
For the sake of completeness I will also explain the dictionary: `╩` pushes top 256 dictionary words. The word is indexed by the next character in the program, and the index is 0-indexed. `╦` uses a number on the stack.
] |
[Question]
[
In a matrix of characters, a **cursor** is a movable position between two adjacent characters, before the first character or after the last character in a line, like that "I"-shaped indicator which moves while you type.
In this challenge, a cursor position is considered **valid** if at least one of its two sides touches a space. The cursor travels through valid positions in a matrix, by moving up, down, left or right by one position each time. It could also move left or right though the line separator, to the end of the previous line, or the beginning of the next line respectively.
Given a character matrix as input, and a cursor initially at the top left corner, your task is to determine whether it can reach the bottom line.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") problem; the rules of this question is the same as what these two tags specified.
### Rules
* You can assume that the input consists only of `.`, , and newlines. (Only these three characters and no more characters; otherwise its behavior is undefined.)
* You may require there must or must not be a trailing newline in the input, if you want to.
* **Your code should output either a truthy value (if the condition is true), or a falsy value (if the condition is false).**
### Examples
Example input(where `░` is the space character):
```
░.....░
░......
.░.░.░.
.░░░░░░
......░
```
The cursor can reach the bottom in this case. This process of moving the cursor will work: down, right(touches spaces on the left), down(touches spaces on the right), down, right(touches spaces on both sides) 6 times, and down(touching spaces on the left).
This will also work(`░` still represent spaces):
```
░░
.░
.░
```
The cursor starts at the up-left corner. After moving right two times, it can move down twice, which touches the bottom of the lines.
This example will not work(`░` represent spaces again):
```
░...
...░
```
The cursor cannot move down, as there is no sufficient whitespace to be touched. There are only newline characters on the right of the input, and there are no newline characters on the left(otherwise a line would have spanned two lines.)
The cursor can also move up and left, in order to solve a maze-like input as in this one:
```
░....
░░░░.
...░.
.░░░.
░....
░░░░░
```
In this case, the cursor has to move left in order to get through spaces and get to the bottom line.
Here is another important test case: the cursor **can** move left or right to another line.
```
░░░░
...░
░...
```
In this case, the cursor can reach the last line, as the cursor can move left or right in order to get to the next line. Moving the cursor down is blocked on the right position of row 2, column 4; however, the cursor can still get to the last line if it moves right (touching spaces).
This is a fairly interesting test input:
```
░░..░
░...░
....░
```
In this case, the cursor can reach the last line, by moving down and left to the end of the first line, then down twice to reach the end of the bottom line.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 60 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Full program. Prompts for character matrix from stdin. Prints 1 or 0 to stdout. Requires zero-indexing (`⎕IO←0`) which is default on many systems.
```
P←{' '0∊⍨s←(×⍨≢⍺)⊃,⍵:1∊⍵⋄s}
1∊⊢⌿{P⌺3 3⊢(⍴⍵)⍴1@0P⌺3,⍵}⍣≡3/3⌿⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXJ55BaUlQNajtonVj3rn1R5a8ahjxqPezVyPOtrd/gcAZarVH02bqG7wqKPrUe@KYqCAxuHpQNajzkWPendpPupq1nnUu9XKECy/9VF3S3EtF5jTtehRz/7qgEc9u4wVjIE8jUe9W4AqNIGUoYMBWByks/ZR7@JHnQuN9Y2ByoHu@g@0@L8CGLhBXKdgygV0gR4IAGk4W48LxIVjMA8NcenBdXGhGmnMBVMBJ9BUGEEt4oIagCprBnMGF7J9MMXIjtHDqhKPkxBOR/gWl1pkNTD/AmkA "APL (Dyalog Unicode) – Try It Online") (space characters replaced by `░` for clarity)
The method here is basically to seed fill from the top left corner, but alternating between 1D and 2D seed fill to account for line wrapping and vertical/diagonal motion. Diagonal motion is simple horizontal motion followed by vertical motion, since the cursor sits in between adjacent characters.
The first line defines a helper function `P`(rocess) which will be called on each neighbourhood.
`P←{`…`}` "dfn"; `⍵` is the neighborhood, `⍺` is the number of padded elements for each dimension:
`,⍵` ravel (flatten) the neighbourhood into a list
`(`…`)⊃` pick the following element from that:
`⍺` the paddings per dimension (so a 1 or 2 element list, depending on `⍵` being 1D or 2D)
`≢` the tally of that (1 or 2)
`×⍨` the square of that (lit. multiplication selfie; 1 or 4)
`s←` assign to `s`(elf; i.e. the centre of the neighbourhood)
`' '0∊⍨` is that a member of `[" ",0]`?
`:` if so:
`1∊⍵` return whether the neighbourhood has a one
`⋄` else:
`s` return `s`(elf unmodified, i.e. leave as-is for now)
The second line is the main part of the program:
`⎕` prompt for evaluated input via the console (stdin)
`3⌿` triplicate each row (ensures we have at least 3 — makes no difference to connectivity)
`3/` triplicate each column (ensures we have at least 3 — makes no difference to connectivity)
`{`…`}⍣≡` apply this function repeatedly until two successive results are identical (i.e. until stable):
`,⍵` ravel (flatten) the matrix into a list
`P⌺3` apply `P` to each neighbourhood of 3 elements
`1@0` replace the current value **at** position `0` with a `1` (this seeds the top left corner)
`(`…`)⍴` **r**eshape that into the following shape:
`⍴⍵` the original shape of the matrix
`⊢⌿` get the bottom row (lit. vertical right-reduction)
`1∊` is there any `1` there?
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~47~~ 43 bytes
```
p®§Qæ%L}>Ƈ0ịƇ
=⁶oŻ$€µZL;1;N$©ṛF1çƬFṀ’:®Ḣ‘=L
```
[Try it online!](https://tio.run/##y0rNyan8/7/g0LpDywMPL1P1qbU71m7wcHf3sXYu20eN2/KP7lZ51LTm0NYoH2tDaz@VQysf7pztZnh4@bE1bg93NjxqmGl1aN3DHYseNcyw9flvaWZormNs9HB3z6EllQ93bznczmX9qGHOoW26dgqPGuZaA/lHJz/cufhR475D2w5tO9wONDoLyvn//9G0iXogAKS5YGw9LhAXjsE8NMSlB9fFBROBE1CDuJAUgE1FNgAmi2y6HlaVSHYg7EY4FyaHLAZzIFatemgaYdphLkIoRgsPPSRjkPShhAYA "Jelly – Try It Online")
A full program that takes a list of strings as its argument and returns 1 if the bottom line is reachable and 0 if not.
## Explanation
### Helper link
Test moves up, down left and right and extend reachable position list. Left argument: most recently added reachable position list; right argument: boolean list of whether each possible position is valid
```
p® | Cartesian product with each of the values stored in the register (the width of the position list, 1 and the negation of each)
§ | Sum each of these
F | Flatten
Q | Uniquify
æ%L} | Symmetric mod using the length of the valid position list: this will mean any positions that move off the top or bottom will be negative
>Ƈ0 | Filter out those reachable positions which are negative
ịƇ | Filter out those which are invalid
```
### Main link
Takes a single argument, a list of Jelly strings representing the grid
```
=⁶ | Check of equal to space
oŻ$€ | Logical or each row with itself prepended with zero; this yields rows 1 longer, and will indicate whether each cursor position is valid
µ | Start a new monadic chain
ZL | Zip and get the length (will be the length of each row)
;1 | Concatenate 1
;N$© | Concatenate the negations and store in the register (i.e. width, 1, -width, -1)
ṛF | Replace with the flattened grid of position validity
1çƬ | Call the helper link, starting with 1 as left argument and using the flattened position validities as right. Repeat until unchanged. Return all collected values.
F | Flatten, getting all reachable positions (may include duplicates)
Ṁ | Maximum position reached
’ | Decrease by 1 (because of 1-indexing)
:® | Integer divide by the register
Ḣ | Head (will effectively be max position integer divided by width)
‘ | Increase by 1
=L | Check if equal to length (i.e. height) of position grid
```
] |
[Question]
[
Your challenge is very simple: output the previous answer, in reverse.
However, as with [this](https://codegolf.stackexchange.com/questions/161757/print-the-previous-answer) similarly-titled question, there's a catch: in this case, you **cannot** use characters from the answer *before* the last. For example:
Let's say the first answer looks like this:
>
> 1 - Python
>
>
> `print('hi!')`
>
>
>
And the second answer looks like this: (see 'Chaining' section for more info)
>
> 2 - Javascript
>
>
> `console.log(")'!ih'(tnirp")`
>
>
>
Now, it would be my job to write the third answer: a program to output the text `)"print('hi!')"(gol.elosnoc`, **without** using the characters `p`, `r`, `i`, `n`, `t`, `(`, `'`, `h`, `i`, `!` and `)`. I can choose whatever language I like to complete this task.
# Chaining
The first answer can output any text: but it *must* **output** *something*. The second answer should simply output the first answer in reverse, using any characters you like. The further rules about restricted characters, as described above, come into play from the third answer onwards.
# Scoring
Your score is \$\frac{l\_{n}}{l\_{n-1}} - l\_{n-2}\$, where \$l\_x\$ represents the length of the \$x\$th answer, and \$n\$ is the position your answer is at in the chain. (all lengths are in bytes; if your answer is no. 1 or no. 2 then miss out \$l\_{n-1}\$ and/or \$l\_{n-2}\$ where necessary.)
Best (lowest) score by August 1st wins.
# Formatting
Please format your post like this:
```
[Answer Number] - [language]
[code]
(preferably a TIO link)
SCORE: [Submission Score]
(notes, explanations, whatever you want)
```
*Everything in square brackets is a required argument to fill in; everything in normal brackets is an optional argument; everything not in brackets is there to make the snippet work.*
# Rules
* All characters, etc. are case sensitive.
* Preceeding/trailing whitespace is allowed, within reason (I'm looking at you, Whitespace).
* Every submission must be a unique language.
* You must wait at least 1 hour before submitting a new answer if you have just posted.
* You may **NOT** submit two answers in a row, you must wait for TWO more submissions before posting a new answer.
* Of course, [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
* Please make sure to triple check that your answer is valid. This is especially important, because someone may start writing their answer based on yours, so if it's wrong you can't really edit it any more... and the whole chain breaks down. Also, you can't edit answers for continuity purposes.
* Standard I/O methods are allowed.
# Answer list/used languages
```
$.ajax({type: "GET",url: "https://api.stackexchange.com/2.2/questions/187674/answers?site=codegolf&filter=withbody&sort=creation&order=asc",success: function(data) {for (var i = 0; i < data.items.length; i++) {var temp = document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];try {temp.innerHTML += " - <i>Score: " +data.items[i].body.split("SCORE")[1].split("\n")[0].match(/(?<!h)[+-]?(\d+(\.\d+)?)/g).slice(-1)[0].trim() +"</i>";} catch (TypeError) {temp.innerHTML += " (no score)";} finally {$('#list').append('<li><a href="/a/' + data.items[i].answer_id + '">' + temp.innerText || temp.textContent + '</a>');}}}})
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<base href="https://codegolf.stackexchange.com">
<ul id="list"></ul>
```
[Answer]
# 1 - [05AB1E](https://github.com/Adriandmen/05AB1E)
```
"Hello, World!"
```
SCORE: \$\frac{15}{1} - 0 = 15\$
[Try it online!](https://tio.run/##yy9OTMpM/f9fySM1JydfRyE8vygnRVHp/38A "05AB1E – Try It Online")
[Answer]
# 7-[str](https://github.com/ConorOBrien-Foxx/str)
```
`DwJRK…E•EDo†LZ–w<SK…T>>Q<Sv‡D<J<I<G<>•‡GMMK•<ʇ̃?ό‰—íɁ͉ð̈́‰’ñÇùÿȫ<w<…><>_RQRRMKSQKKRKMRRNMLKQKRITK‡w•„‡GPK•<LSRL[J[b•ULXQLNaJ\\Z•NLQ˜“Lj<`D-D-o;
```
## Score: \$\frac{187}{171}-212 = -210.906432748538\$
Note that the code contains many unprintable characters.
The big string between the ```s is the reversed code of the Stax answer encoded by adding 26 (I brute-forced this number) to each codepoint. The str code then undoes this by subtracting 26 from the string before outputting it (You can subtract integers from strings, which does math on each codepoint, in this language)
[Try it online!](https://tio.run/##Fcy9agJBFIbhK/IKchibEXHPzOKcVQgqRC1tBA3ZWvwZhMiCMtF7CIKWqQLfNBoSckmbTfm@xTN/npXlUOeJMNYNhIaeYmN6eMspq05HKUfZC7ymhFrUJIUA37SWEejLfy/rv6/Y4hjP90XcYRsvP6uq9/EaffyIn7d3yglrRepJnIjlzDELW5HUGnYsrQ7D5xW6qtj2v2oyQYHC9JP@GKFrUDw6k46SwaCHkBqHEw5mQkNd07XpQ1n@AQ "str – Try It Online")
[Answer]
# 5. [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console)
```
")(esre"1´18k+"er.'"$7´884k$8´216k$7´690k$8´318k$8´220k$3´80k$1´87k$9´5k$7´814k$1´64k$1´61k$8´220k$1´18k$3´91k:$$7´776k$8´220k$8´310k$4´28k$3´04k$2´09k$1´69k$7´693k$1´61k$8´220k$"'tnirp"@
```
[Try it online!](https://tio.run/##ZY5BCgMhDEXvEoRpKZSJWk266l0GF4MwFNvezBN4MRt1YBaz@vzk/Z@k37YutcL1Ej4pAJaMFG8Q0n0C5UsmslFRyRpdbN7x3L0RrM@1eCOciITJR8UlPzpLaPvQ7YJHYtxpQcb4VI323h37fkHUih/cLCVahEcX79@YUzVM321Nb3jV@gc "Runic Enchantments – Try It Online")
Encodes the Jelly portion as number literals. Its disgusting. Also, answer #7 will have a super low score. Which is also disgusting. Next.
## SCORE: 212÷77-25 = -22.246753247
[Answer]
# 6 - [Stax](https://github.com/tomtheisen/stax)
```
"P2y~724{@BB0G427>u2;{HA0A2uu892"{16-mj{]m1:/8171234883181179138878E$"$k"]\"ȑåß×xo̪Öo³ȧÓ}oβ%˩ɭ"{133-m{$"-"/"0"*m\9"7$$:k19"]|@2lU*+{+k180]*
```
[Run and debug online](https://staxlang.xyz/#c=%22P2%C2%80%C2%82y%7E%C2%84724%7B%40BB0G427%3E%C2%82u2%3B%7BHA0A2u%C2%82%C2%83u892%22%7B16-mj%7B%5Dm1%3A%2F8171234883181179138878E%24%22%24k%22%5D%5C%22%C2%95%C8%91%C3%A5%C3%9F%C2%AD%C3%97xo%CC%AA%C3%96o%C2%95%C2%B3%C8%A7%C2%8A%C3%93%7Do%CE%B2%25%CB%A9%C9%AD%22%7B133-m%7B%24%22-%22%2F%220%22*m%5C9%227%24%24%3Ak19%22%5D%7C%402lU*%2B%7B%2Bk180%5D*&i=)
## Score: 171 ÷ 212 - 77 = -76.19
My first Stax answer. I’m sure it could be golfed better, but each byte is only worth \$\frac{1}{212}\$ points.
[Answer]
# 2 - [Japt](https://github.com/ETHproductions/japt)
```
`"HÁM, Wld!"`w
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=YCJIwU0sIFeObGQhImB3) - Note the unprintable (codepoint 142) between the `W` and the `l`.
**SCORE: 15÷15-0=1**
---
Everything between the backticks is simply the source of the first solution compressed with Shoco. The backticks decompress it and the `w` reverses the result.
[Answer]
# 4 - [Groovy](http://groovy-lang.org/)
```
print'“¡ḍ©ÑİƬ⁶“ṠƇƇv“¡¤Ẇ_»ż“⁾Ḋ‘Ọ'.reverse()
```
[Try it online!](https://tio.run/##Sy/Kzy@r/P@/oCgzr0T9UcOcQwsf7ug9tPLwxCMbjq151LgNKPRw54Jj7cfay8Cyh5Y83NUWf2j30T1A7qPGfQ93dD1qmPFwd4@6XlFqWWpRcaqG5v//AA "Groovy – Try It Online")
### SCORE = 77/25 - 15 = -11.92
[Answer]
# 3 - [Jelly](https://github.com/DennisMitchell/jelly)
```
“¡ḍ©ÑİƬ⁶“ṠƇƇv“¡¤Ẇ_»ż“⁾Ḋ‘Ọ
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDCx/u6D208vDEIxuOrXnUuA0o9HDngmPtx9rLwLKHljzc1RZ/aPfRPUDuo8Z9D3d0PWqY8XB3z////xOUPHx1FMJzUhSVEsoB "Jelly – Try It Online")
## SCORE: 25 ÷ 15 - 15 = -13.33
No unprintable characters. [Verification that no characters from 1 used.](https://tio.run/##y0rNyan8/z/z0cZ1////V/IAcvN1FMLzi3JSFJX@P2qYc2jhwx29h1Yennhkw7E1jxq3AYUe7lxwrP1YexlY9tCSh7va4g/tProHyH3UuO/hjq5HDTMe7u4BAA)
] |
[Question]
[
The Dank Memes Casino is one of the best casinos of the world. They have a rule that if you win or lose money, you will be paid at the beginning of the next month.
But, catastrophe struck and there was an earthquake, which demolished the casino.
Now, all the poker players have gathered and realised that the casino is not the person that owes them money or they do not owe the casino money, but as a matter of fact, they owe each other!
Your mission, should you choose to accept, will be to find out who owes who money.
Also, do keep in mind that the shortest code wins.
## Input
The first line contains the names of the people separated by spaces (Let there be n names).
The second line contains n integers, the ith of which denotes the ith person's winnings or losings at poker. A positive number means that he is owed money from someone, whereas a negative number entails that he owes someone money.
Flexible input methods are accepted.
## Output
Print out as many lines as required.
Each line should contain the name of the person who owes the money, the name of the person who is owed money, the amount of money that is owed separated by a space.
## Input Constraints
2 <= n <= 6
-100000 <= amount of money <= 100000
## Guaranteed Constraints
Sum of all integers in the array = 0
# Sample Test Cases
## Test Case 1
Sample Input
```
Messi Ronaldo Hazard Ibrahimovich
1000 1000 -2000 0
```
Sample Output
```
Hazard Messi 1000
Hazard Ronaldo 1000
```
## Test Case 2
Sample Input
```
Maradona Pele
20000 -20000
```
Sample Output
```
Pele Maradona 20000
```
## Test Case 3
Sample Input
```
A B C D E
1 1 1 1 -4
```
Sample Output
```
E A 1
E B 1
E C 1
E D 1
```
## Test Case 4
Sample Input
```
A B C D E F
3 3 1 2 -4 -5
```
Sample Output
```
F D 2
F C 1
F B 2
E B 3
E B 1
E A 3
```
## Clarification
There may be multiple answers, anyone of them will be accepted.
For example:
```
A B C
1 1 -2
```
can yield both of the following:
```
C A 1
C B 1
```
or
```
C B 1
C A 1
```
both are correct.
[Answer]
# [Python 3](https://docs.python.org/3/), 173 bytes
```
a=lambda:input().split()
m={x:int(y)for x,y in zip(a(),a())}
l=lambda k:m[k]
while any(map(l,m)):d=min(m,key=l);s=max(m,key=l);t=min(m[s],-m[d]);m[d]+=t;m[s]-=t;print(d,s,t)
```
[Try it online!](https://tio.run/##RU7NCsIwGLvvKb5jP@wEnV42evD3JcYOlU0s69eVteKq@Oy1Q8FDEpIQiA3@NpgiRim0pEsrS2Xs3TNcOqtV0ozEa0qhZwGvwwgTD6AMPJVlkiFPwHemf2PoS6r7JnvclO5AmsBIWqY5IZatIGUY8b4LQmPlBMnpb/23rV3Dc6rbBquZF8JXc5YnteN8ouWOe4xxB3s4wBFOcM4KKGAFa8g3kG8/ "Python 3 – Try It Online")
-6 bytes thanks to ppperry using dictcomps instead of `dict` of a listcomp
[Answer]
# [Python 2](https://docs.python.org/2/), 146 bytes
```
def f(p,b):
a=sorted(zip(b,p))
while a:
d,D,c,C=a[0]+a[-1];t=d+c;a[0]=(t,D);a[-1]=(t,C);a=a[t>=0:[len(a),-1][t<=0]]
if d:print D,C,min(-d,c)
```
[Try it online!](https://tio.run/##LU7BToUwEDzDV/RGm7ckhacXak0UJHrw4rXpoVAITXjQQKPx/Twu4GF2Jzuzk/G/YZinfNts15OeemhYEUdGrvMSOkvvztMGPGNx9DO4sSMG1chCBS2U0iiuL0almRZB2ksr9oOkASomjvPOS@ToDM@SF2rsJmoYoKTCk@RaY5rriS384qZAKijh5iaaWmjZUak@K5FT9@LcjfjvKk4hjmuqks9uXV0Cydc8mdHOyN7N3SwWyUezmMHd5m/XDokGojLOORwjzffJNTsyXtD8iigRFeINUeOHusIVMsghfYD0Ec3bHw "Python 2 – Try It Online")
] |
[Question]
[
This task is a classic programming task: Implement a regular expression parser. That is, write a program or function which takes a string describing a regular expression and a candidate string, and test whether the complete candidate string matches the regular expression. You may assume that the regular expression passed is valid.
If your programming language offers regular expression matching or string parsing, you are not allowed to use that. Also you are not allowed to use libraries other than the standard library of your programming language. Also forbidden is to access an external tool to do the work (e.g. accessing a web server, or calling another executable). In addition, use of reflection or any other functionality that allows the program to access its own source code, the names of individual identifiers or similar information is explicitly forbidden to prevent gaming the scoring rules (thanks to ais523 in the comments for making me aware of the latter possibility).
This is an atomic code golf contest, it's not the character count that has to be minimized, but a modified token count (for details, see below).
## Input
The regular expression is not enclosed in slashes (`/`), any slashes appearing in the regular expression string are part of the regular expression itself (that is, the string `/.*/` denotes not the regular expression `.*`, but the regular expression `/.*/` which will match the string `/abc/`, but *not* the string `abc`).
Both the regular expression string and the candidate string will consist solely of ASCII characters in the range 32 (space) to 126 (tilde).
### The regular expression syntax
Your program only needs to parse the following minimal regular expression syntax:
* Anything except the letters `.`, `*`, `|`, `(`, `)` and `\` matches literally.
* A backslash (`\`) followed by any of the above characters literally matches the second character.
* A dot (`.`) matches any character.
* The star (`*`) matches zero or more consecutive strings each matching the regular expression preceding it. It cannot appear at the beginning.
* The pipe (`|`) matches either the regular expression before it, or the regular expression following it.
* Parentheses (`(`, `)`) themselves don't match anything, but are used to group expressions (e.g. `ab*` matches `abbbbb`, while `(ab)*` matches `abababab`).
## Output
Your program or function must give one of two results, one indicating that the *complete* candidate string matches, one indicating that it doesn't. How the output is given (function return variable, global variable setting, text output, program status code, ...) is up to you (and the capabilities of your chosen programming language). Explain how the output is to be interpreted.
## Scoring
Of course, this being a code golf, the minimal score wins. The score is calculated as follows:
* Start with score 0.
* Comments and whitespace characters that are not part of a token are ignored.
>
> **Rationale:** I don't want to penalize pretty formatting. The token exception covers both spaces inside string and character constants, and special cases like the Whitespace language where each single whitespace character constitutes a token (so writing a program in Whitespace won't give you a score of 0).
>
>
>
* For any statement/declaration/etc. which makes available a standard library component to the code (like `#include` in C, `use` in Perl or `import` in Java), add 5 point per imported standard library package.
>
> **Rationale:** I don't want to make the scoring dependent on how verbose the import syntax of a language is. Also, there shall be a slight (but not too strong) discourage of using library components (direct code is preferred, unless the library makes a big difference; however note the restrictions on library use outlines above). The "per standard library package" part is so that you cannot reduce your point by combining several imports by one (e.g. in Turbo Pascal, you could write `uses dos, crt;` instead of `uses dos; uses crt;`. With the rule as given, both would add 10 points. (Of course, both `dos` and `crt` would be pointless for the given task.)
>
>
>
* For any string, add one more than the number of characters in the string (that is, the empty string gets 1 point, a one character string gets 2 points, etc.). If the language has single-token literals for other complex types (like lists, dictionaries, etc.), it is one point per character in the literal. (thanks to ais523 in the comments for telling me about such complex literals).
>
> **Rationale:** This is mainly to prevent tricks like `eval("long program code")` which is four tokens. With this rule, doing such a trick actually penalizes your code, because you're back to character counting instead of token counting.
>
>
>
* For any number, add as many points as the minimal number of bytes needed to represent the number as either signed or unsigned two's-complement number. That is, numbers from -128 to 255 (including both values) get 1 point, otherwise numbers in the range -32768 to 65535 get 2 points, otherwise numbers in the range -8388608 to 16777215 get 3 points, and so on.
>
> **Rationale:** This is to prevent similar tricks in languages supporting arbitrary large numbers, where the whole program might be encoded in a number that is then reinterpreted as a string and passed to `eval` or an equivalent function.
>
>
>
* Any token not covered in the list above gives 1 point.
>
> **Rationale:** This is to avoid penalizing verbose languages (e.g. Pascal with `begin`/`end` vs. C with `{`/`}`), and especially to avoid giving esoteric languages (Golfscript!) an advantage just for having one-character tokens. Also, it allows meaningful variable names without being penalized.
>
>
>
Note: This challenge was posted in the [sandbox](https://codegolf.meta.stackexchange.com/a/1407/3681)
[Answer]
# [Python 3](https://docs.python.org/3/), 445\* points
This is a fairly straightforward approach: it uses a basic recursive descent parser, and a regex engine implemented using [Brzozowski derivatives](https://en.wikipedia.org/wiki/Brzozowski_derivative) (which I just learned about, and which I think are super elegant); it takes two strings as input via STDIN – first a string representing the regex in question, then a string containing the text to match, and prints `True` to STDOUT if the regex matches and `False` if it doesn't.
```
class Nil:nullable,derive = False,lambda *self: Nil
class Empty(Nil):nullable = True
class And:
def __init__(self, first, second=None):self.first,self.second = first,second
nullable = property(lambda self: self.first.nullable and self.second.nullable)
def derive(self, c):
dxy = And(self.first.derive(c), self.second)
return Or(dxy, self.second.derive(c)) if self.first.nullable else dxy
class Or(And):nullable,derive = property(lambda self: self.first.nullable or self.second.nullable),lambda self, c: Or(self.first.derive(c), self.second.derive(c))
class Star(And):nullable,derive = True,lambda self, c: And(self.first, Star(self.first)).derive(c)
class Plus(Star):nullable = False
class Char(Plus):derive = lambda self, c: Empty if self.first in 'µ'+c else Nil
expr = input()
index = len(expr)
peek = lambda: index and expr[-index] or ''
def advance():
global index
item = peek()
index -= True
return item
def regex():
factor = Empty
while peek() not in ')|':
current = advance()
base = Char(current)
if current == '(':
base = regex()
advance()
elif current == '\\':base = Char(advance())
elif current == '.':base = Char('µ')
while '' < peek() in '*+':
base = (Star if peek() == '*' else Plus)(base)
advance()
factor = And(factor, base)
return Or(factor, regex()) if peek() == '|' == advance() else factor
derivative = regex()
for c in input(): derivative = derivative.derive(c)
print(derivative.nullable)
```
[Try it online!](https://tio.run/##jVPBjtMwED0nX@Gb7W62F24RPSAExwUJbiyq3GSytXCdyHGWVtrf4gf4sTITu07SLYJTa8@b9@aNX7qT37f2zflcGdX37EGb0g7GqJ2Bogann4Ft2EdleiiMOuxqxVY9mKYkpJB56Ppw6PxJ4I1Mzdj11Q0QAe9sXeZZDQ3bbrXVfrsVxFKwRrveF6yHqrX15qG1IEuqrENh/BuKSHi5o2OezZQ613bgcIQ4Yphw4lknrEKiGWkqyDBdcBxnqyTOnNXHEyqgATHji7hKFnM2JMkc@MFZ9skJbFxUpybJdHNzOsA1M@yLW0MS1JU3HuT/Dbfutt9i1olWSxL7p8GZhSzO@MWrv05JAXils9xkEQimCyknkSjx2Qy9INgiXWMmI@L9HjkIJsskfq0bMnq1eqYt479/8bsq7D6EGo6dQwZtu8HjUdsajsQIVlBJ5h3AjyRRsgCgaFH52/14/k6r5zynWKn6WdkKBAXqybQ7ZUJPnmkPB3pPJESlLDDdx2/nEiYCjTwOnuA4sjSq8i0NGW3l2c@9xr0EImbbYE2@cMpwNTgH1iM8TYK3O9XTosblRQRd44ISfsO4GBku4DgB3cypwFx1PT7ycs6fwDfR6yWYXoRwwRLn7O3FF3la3S0mGpNBrxohxLfi4TnHSAgCvpo4LZDyGA4Fi8jpG74Uom15pfPC6SfRBtHQk49BVD6E8bK2BiUrchGzVbIFbDrMPoLOaevFrJS@4fP5Dw "Python 3 – Try It Online")
---
**\*** I'll be honest: I'm not totally sure if I've scored this correctly, because the scoring rules for this submission are at once both rather complex and also imprecise. Their goals are certainly admirable, but I think the range of possible situations they try to cover is too vast.
As an example of what I mean: "Tokens" aren't necessarily a consistently defined concept in many programming languages, and this challenge doesn't clarify. In Python, for instance, they're implementation-defined.
Similarly, and among other such things, the challenge doesn't count whitespace against a score unless it's part of a token, but CPython generates tokens for certain non-meaningful whitespace, which leads to a contradiction with the scoring rule's stated intent of "avoiding penalizing pretty formatting."
Consequently, this could actually be anywhere from 407-533 points.
] |
[Question]
[
# Challenge
Given a rectangular area arrange a group of rectangles such that they cover the rectangular area entirely.
# Input
* An integer denoting the height.
* An integer denoting the width.
* The dimensions of the rectangles consisting
of the following form: `axb,cxd,...` where `a,b,c,` and `d` are integers - any reasonable format is acceptable.
# Output
An exact cover of the rectangular area.
Rectangles used to cover the area are represented in the following way:
`2x3`
```
00
00
00
```
or
```
000
000
```
`1x3`
```
0
0
0
```
or
```
000
```
Each rectangle is represented using a character `0-9` where `0` is used for the first rectangle inputted `1` for the second and so on. The max number of rectangles given in input is therefore 10.
# Test Cases
### Input 1
```
5
7
4x2,3x2,3x2,5x2,5x1
```
### Output 1
```
0000111
0000111
2233333
2233333
2244444
```
### Input 2
```
4
4
3x2,2x1,2x2,2x2
```
### Output 2
```
0001
0001
2233
2233
```
### Input 3
```
2
10
4x2,3x2,3x2
```
### Output 3
```
0000111222
0000111222
```
# Clarifications
* The dimensions of the rectangles used to cover the region are interchangeable e.g. for `axb` `a` could be the height or width same goes for `b`.
* If there are multiple solutions any of them is acceptable (just display 1).
* Assume all inputs are valid.
* You can have a full program or a function (inputs may be treated broadly as 3 separate arguments).
* Output to stdout (or something similar).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer in bytes wins.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 76 [bytes](https://github.com/abrudz/SBCS)
```
⎕CY'dfns'
{⍺⍴v+.×(X m)⌿m←⊃⍪/(⍺∘{⍪↑,(⍳⍺)↓¨⊂⌽⊖⍺↑⍵⍴1}¨⊢∘⌽\2/⍵),⍤1¨2/↓∘.=⍨v←⍳≢⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGIJZzpHpKWl6xOlf1o95dj3q3lGnrHZ6uEaGQq/moZ38uUNWjruZHvav0NUDSHTOAqlY9apuoA@RuBopoPmqbfGjFo66mRz17H3VNA6lpm/iodyvQIMNakMQioB6gXIyRPlBUU@dR7xLDQyuAnLbJQAk920e9K8pAdgAN61wEVFH7Pw3M7QPaemi9MciwvqnBQc5AMsTDM/i/iYKJQpqChomCsSaQMNTk0tXV5YIKGoEEjYCCQMIIQoClTRXMIXqAgsZwwhRCQI0whqgxBwkaKphrAgA "APL (Dyalog Unicode) – Try It Online")
Dyalog APL comes with a built-in Exact Cover solver `X`, so the main part of the code is construction of the **constraint matrix**.
A constraint matrix is a boolean matrix where a column indicates a **constraint**, and a row indicates an **action** that satisfies some of the constraints. In the case of rectangle cover, an action is positioning of a specific rectangle at certain position and orientation, which satisfies two kinds of constraints: a specific rectangle is consumed, and the certain cells are covered by that rectangle.
For example, consider positioning a `2×3` rectangle in a `4×4` rectangular space. There are 12 ways to place it inside the space:
```
Horizontally
OOO. .OOO
OOO. .OOO
.... ....
.... ....
.... ....
OOO. .OOO
OOO. .OOO
.... ....
.... ....
.... ....
OOO. .OOO
OOO. .OOO
Vertically
OO.. .OO. ..OO
OO.. .OO. ..OO
OO.. .OO. ..OO
.... .... ....
.... .... ....
OO.. .OO. ..OO
OO.. .OO. ..OO
OO.. .OO. ..OO
```
If it is the second rectangle out of four rectangle pieces, a part of the constraint matrix would look like this (where type 1 constraints mark the rectangle used, and type 2 mark the cells occupied):
```
<-- Type 2 -->
<-Type 1-> <-r1--> <-r2--> <-r3--> <-r4-->
0 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 0 0 0 0
0 1 0 0 0 1 1 0 0 1 1 0 0 1 1 0 0 0 0 0
0 1 0 0 0 0 1 1 0 0 1 1 0 0 1 1 0 0 0 0
0 1 0 0 0 0 0 0 1 1 0 0 1 1 0 0 1 1 0 0
0 1 0 0 0 0 0 0 0 1 1 0 0 1 1 0 0 1 1 0
0 1 0 0 0 0 0 0 0 0 1 1 0 0 1 1 0 0 1 1
...
```
In the actual code, the fact that "there will always be a solution" is abused for the sake of golfing. It actually generates a matrix where type 2 comes before type 1, and the rectangle pieces are allowed to be partially overflowed to the top left. It still works since using an overflowed piece will always fail to cover the entire rectangular area.
```
⍝ Load dfns library to use the function X
⎕CY'dfns'
⍝ An inline function; ⍺←area (w,h), ⍵←n pieces
{
v←⍳≢⍵ ⍝ Generate 0..n-1
↓∘.=⍨ ⍝ Generate Type 1 constraints as a nested array
2/ ⍝ Two copies of each, to match with two orientations of each rect
,⍤1¨ ⍝ Concatenate row-wise with
(...) ⍝ the Type 2 constraints:
2/⍵ ⍝ Two copies of each rectangle
⊢∘⌽\ ⍝ Flip the rows and columns at odd (0-based) indices
⍺∘{...}¨ ⍝ Generate boolean matrices for each rectangle:
⍺↑⍵⍴1 ⍝ Create the rectangle-shaped 1s, 0-filled to the size of the space
⌽⊖ ⍝ Reverse in both dimensions, so the 1s go to the bottom right
(⍳⍺)↓¨⊂ ⍝ The above with leading rows/columns dropped in all possible ways
⍝ (all combinations of 0..h-1 rows and 0..w-1 columns dropped)
⍪↑, ⍝ Format the result as Type 2 constraint sub-matrix
m←⊃⍪/ ⍝ Vertically concatenate all the constraint sub-matrices
⍝ generated for each rectangle
(X m)⌿m ⍝ Solve the Exact Cover problem, and extract the rows
⍝ (the collection of rectangles that actually cover the area)
v+.× ⍝ Number the cells by the containing rectangle's 0-based index
⍺⍴ ⍝ Reshape the cells to the shape of the area
}
```
[Answer]
# Python 3, 262 bytes
```
from numpy import*
def g(h,w,t,m,i):
if[]==t:print(m);return
u,v=t[0]
for _ in'12':
for r,c in argwhere(m<0):
if(m[r:r+u,c:c+v]<0).all()and u+r<=h and v+c<=w:e=copy(m);e[r:r+u,c:c+v]=i;g(h,w,t[1:],e,i+1)
u,v=v,u
f=lambda h,w,t:g(h,w,t,zeros((h,w))-1,0)
```
Called like: `f(4,4,[(3,2),(2,1),(2,2),(2,2)])`. It uses a brute force, recursive function that prints all solutions (uses fewer bytes).
] |
[Question]
[
Your task is to create a program or function that creates a paste on [sprunge.us](http://sprunge.us). Your program/function must receive the text to *sprunge* from your language's usual input mechanism, such as standard in; or in the case of a function, it can be a string or whatever makes the most sense to you. Your program will POST the text from input to `http://sprunge.us/` as `multipart/form-data` with the form field name of `sprunge`. Finally, your program will output/return the URL sent back in the reply from the POST.
This is a code golf, so shortest answer (in bytes) wins.
Here is an example solution using `bash` and `curl` taken directly from the sprunge.us website. Feel free to use it in your own golf:
```
curl -F 'sprunge=<-' http://sprunge.us
```
Which returns the URL to the paste, which looks like `http://sprunge.us/aXZI`, where the `aXZI` is the ID of the sprunge.
*This is my first code golfing challenge, please let me know if this is too easy or not creative enough*
[Answer]
# HTML, 88 bytes
```
<form action="http:sprunge.us" method="POST"><textarea></textarea><button type="submit">
```
To test this easily, prepend `data:text/html,` to the code and paste it into your address bar (works for me on chrome).
Full (easily) testable code:
```
data:text/html,<form action="http:sprunge.us" method="POST"><textarea></textarea><button type="submit">
```
[Answer]
# Bash, 30 bytes
```
curl -F'sprunge=<-' sprunge.us
```
Just removed the unneeded space in `-F 'sprunge=<-'` and the `http://` from the `sprunge.us` url. OP gave me explicit permission to golf his reference solution.
[Answer]
# Bash, 29 25 bytes
```
curl -F sprunge{=\<-,.us}
```
Thanks to @Score\_Under for providing this awesome solution!
Old solution:
```
curl -Fsprunge=\<- sprunge.us
```
Quotes around 'sprunge=<-' are unnecessary, as long as the `<` is escaped.
EDIT: Interestingly, this alternative way has the exact same length:
```
a=sprunge
curl -F$a=\<- $a.us
```
] |
[Question]
[
**This question already has answers here**:
[Build me a brick wall!](/questions/99026/build-me-a-brick-wall)
(91 answers)
Closed 7 years ago.
I need help making a brick road to go beside [my brick wall](https://codegolf.stackexchange.com/questions/99026/build-me-a-brick-wall)!
```
\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \
\__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__
__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\
\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \
\__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__
__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\
\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \
\__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__
__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\
\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \
```
This road is `10` characters long and `70` characters wide, seems familiar right?
We have to stay efficient with this road as well, no input and lowest byte count in some code that produces this pattern in an output wins!
This code-golf puzzle isn't the same as the predecessor mentioned above, as the output requires a different approach rather than just simply outputting what it asks (because the pattern is offscured and not exactly the same). It was purposefully included like this for the puzzle to match the theme of my page and also include a higher difficulty for the user (the original was very simple for some). This was mentioned below in the comments.
[Answer]
## Pyke, 19 bytes
```
"\ \__"w�*Tf70L<_X
```
where � is the literal byte 156.
[Try it here!](http://pyke.catbus.co.uk/?code=%22%5C++%5C__%22w%C2%9C%2aTf70L%3C_X)
[Answer]
# [V](http://github.com/DJMcMayhem/V), 20 bytes
```
123i\ \__ò70|lé
4x
```
[Try it online!](http://v.tryitonline.net/#code=MTIzaVwgIFxfXxvDsjcwfGzDqQo0eA&input=)
As usual, here is a hexdump:
```
0000000: 3132 3369 5c20 205c 5f5f 1bf2 3730 7c6c 123i\ \__..70|l
0000010: e90a 3478 ..4x
```
Explanation:
```
123 " 123 times:
i " Insert the following:
\ \__ " '\ \__'
<esc> " Return to normal mode
ò " Recursively:
70| " Move to the 70th column
l " Move one char over
é " Insert a single newline
4x " Delete 4 characters
```
[Answer]
# [Retina](http://github.com/mbuettner/retina), ~~32~~ 31 bytes
```
123$*_
\ \_
S_`(.{70}).{0,4}
```
[Try it online!](http://retina.tryitonline.net/#code=CjEyMiQqXwoKXCAgXF8KU19gKC57NzB9KS57MCw0fQ&input=)
[Answer]
## PowerShell v2+, ~~58~~ 38 bytes
```
'\ \__'*123-split"(.{70}).{0,4}"-ne''
```
Basically the same as my [Build me a brick wall answer](https://codegolf.stackexchange.com/a/99048/42963), just with additional logic to take the appropriate portions. Thanks to @MartinEnder for saving 20 bytes.
```
PS C:\Tools\Scripts\golfing> .\build-me-a-brick-road.ps1
\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \
\__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__
__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\
\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \
\__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__
__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\
\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \
\__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__
__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\
\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \
```
[Answer]
# Python 2, ~~79~~ 78 bytes
```
for x in range(10):a='\\ \\__';b=a*11+a[:4];print b[x*2:70]+b[4:x*3+4-x]
```
Got there in the end. Just builds a big string, cuts off the beginning and kind of adds the beginning to the end (if that makes sense).
-1 for an unneeded 0
Output:
```
python follow-the-yellow-brick-road.py
\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \
\__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__
__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\
\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \
\__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__
__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\
\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \
\__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__
__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\
\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \__\ \
```
] |
[Question]
[
>
> Let's define a 2-quine as a program that prints its source code two times. For example, if the program `ABC` printed `ABCABC`, it would be a 2-quine.
>
>
> Let's define a 3-quine as a program that prints its source code three times. For example, if the program `ABC` printed `ABCABCABC`, it would be a 3-quine.
>
>
> Let's define a *n*-quine as a program that prints its source code *n* times.
>
>
>
Your task is to write a 2-quine, that prints a 3-quine, that prints a 4-quine, that prints a 5-quine, etc...
For example, here is an example of a valid submission (which is fictional of course):
```
AB
```
which prints
```
ABAB
```
which prints
```
ABABABABABAB
```
which prints
```
ABABABABABABABABABABABABABABABABABABABABABABABAB
```
etc.
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the program with the fewest bytes wins.
[Answer]
## QBasic (224 bytes incl. trailing CR+LF)
(Tested with QBasic/MS-DOS on a virtual machine as well as with FreeBASIC with "-lang qb" setting)
```
a$="a$=:l=l+1:if l>y then f=f+1:y=y*f+y+f:while x<=y:x=x+1:print mid$(a$,1,3)+chr$(34)+a$+chr$(34)+mid$(a$,4):wend":l=l+1:if l>y then f=f+1:y=y*f+y+f:while x<=y:x=x+1:print mid$(a$,1,3)+chr$(34)+a$+chr$(34)+mid$(a$,4):wend
```
[Answer]
# Javascript ES6 (REPL), 52 bytes
```
var a=a||'';$=_=>a+=`$=${$};$();`.repeat(a?1:2);$();
```
Initial working implementation, may be golfable.
```
y.onclick=_=>z.innerText=eval("var a=a||'';$=_=>a+=`$=${$};$();`.repeat(a?1:2);$();".repeat(x.value))
```
```
<input id=x><button id=y>Submit!</button><pre id=z></pre>
```
# Explanation
Based on my usual quine implementation (`$=_=>`$=${$};$()`;$()`).
`var a||''` coerces `a` to an empty string if it isn't defined; otherwise, `a` is left as is. `a` will store our final result.
Each function call, `a` will be checked to see if it is empty/falsy. The first function call will append 2 copies of the quine because `a` is empty; subsequent calls will only append 1 copy because `a` is no longer empty.
The last function call will output the final value of `a` after finishing.
[Answer]
# Ruby, 154 bytes
```
s=DATA.read.lines;s+=s[0,2];n=s.size/4;k=1;n/=k+=1while n>0;puts s*k
__END__
s=DATA.read.lines;s+=s[0,2];n=s.size/4;k=1;n/=k+=1while n>0;puts s*k
__END__
```
The trailing newline matters.
This program first duplicates itself; the output triplicates itself; that output quadruplicates itself, etc.
Thus the **n**-th program is a repetition of these 4 lines, **n!** times.
`s=DATA.read.lines;s+=s[0,2];` gets us the current source code as an array of lines. We take its length, divide it by 4, compute the inverse factorial, add one, then print `s` that many times.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 117 bytes
```
for x in 1,0:
exec(s:="if x%2:a=1;d={}\nx or~input('for x in 1,0:\\n exec(s:=%r)#'%s*~-a*d[a-1]);a+=1;d[x]=a;x*=a")#
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/Py2/SKFCITNPwVDHwIpLIbUiNVmj2MpWKTNNoULVyCrR1tA6xba6NiavQiG/qC4zr6C0REMdRVNMTB5cm2qRprK6arFWnW6iVkp0oq5hrKZ1ojbIjOiKWNtE6wot20QlTeX//wE "Python 3.8 (pre-release) – Try It Online")
## How it works :
* `for x in 1,0:` allows me to iterate through the code twice
* then I execute some code
* `#` at the end comment the `for x in 1,0:` if the "base" is repeated multiple times
the code executed :
```
if x%2: # execute if x=1 (happen only once at the start,
# after that x will always be a multiple of 2)
a=1
d={}
# if x==0: print the quine the right number of time then crash
x or~input('for x in 1,0:\\n exec(s:=%r)#'%s*~-a*d[a-1])
a+=1 # a increments itelf by one for each line of the code
d[x]=a # store (a-1)! and a
x*=a # x = a!
```
If the actual code is a `n` quine, it has `(n-1)!` times the "base" and should print it `n!` times:
* Because `a` is incremented by 1 each line, after the first iteration of the `for` loop, a is equal to `(n-1)!+1`.
* I then search `a-1` into `d` (wich store relation beetween `(k-1)!` and `k`) to find `n`.
* I multiply `n` by `a-1` to get `n!`
* I print this number times the "base"
] |
[Question]
[
[Connect Four](http://en.wikipedia.org/wiki/Connect_Four) is a game where two players take turns to drop disks into columns of a vertically mounted grid, and attempt to connect four disks orthogonally or diagonally. When a column is chosen, the disk falls to the lowest empty position in that column, so any game may be completely specified by the size of the grid and the sequence of columns chosen. The task is to generate the configuration of the grid given this information.
**Input**
* Width `w` and Height `h` of the grid, both positive integers.
* Sequence of columns `c1`, `c2`, ..., `cn` chosen by the players, in any reasonable format (list, array etc.); either 0-based (`0` to `w-1`) or 1-based (`1` to `w`) indexing can be used.
It may be assumed that all of the column numbers lie within the grid (so the sequence won't contain `-3` or `w+50`) and that any column number appears at most `h` times in the sequence (so a column can't be chosen once it is full).
Note that the sequence of columns may not constitute a complete game, nor a legal game. For instance, the players could opt to continue playing even after a player has connected four disks.
**Output**
* Any reasonable representation of the resulting state of each position in the grid, either "occupied by Player 1", "occupied by Player 2", or "empty". Player 1 always moves first.
For example, a string, array, tuple etc. with each position containing one of three symbols (ASCII character, number etc.) representing the state of that position in the grid. The grid may be transposed.
For list/tuple/array outputs, the separator cannot be one of the three representative symbols. For string outputs, trailing spaces at the end of each line are permitted, provided a space is not one of the three representative symbols. Trailing newlines at the very end are permitted.
**Test cases**
Here, string output is used, with `X`, `O`, `.` denoting "occupied by Player 1", "occupied by Player 2", "empty".
```
IN: Width 1 Height 1 Sequence (empty sequence)
OUT:
.
IN: Width 7 Height 6 Sequence 4 4 5 5 6 7 3 [1-based]
3 3 4 4 5 6 2 [0-based]
OUT:
.......
.......
.......
.......
...OO..
..XXXXO
IN: Width 5 Height 5 Sequence 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 [1-based]
0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 [0-based]
OUT:
XOXOX
OXOXO
XOXOX
OXOXO
xOXOX
IN: Width 4 Height 4 Sequence 3 3 2 4 3 2 4 2 2 3 4 4 1 1 1 1 [1-based]
2 2 1 3 2 1 3 1 1 2 3 3 0 0 0 0 [0-based]
OUT:
OXOO
XOXX
OOOX
XXXO
IN: Width 10 Height 10 Sequence 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 1 10 [1-based]
0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 9 [0-based]
OUT:
X.........
X.........
X.........
X.........
X.........
X.........
X.........
X.........
X........O
XOOOOOOOOO
```
**Shortest code in bytes wins.**
[Answer]
# Vim, 34 bytes
`@wO-<Esc><C-V>(d@hpqq<C-O>+D@"G+bs<C-R>=!@.<CR><Esc>@qq@q`
Input is width in the `"w` register, height in the `"h` register, and the 1-indexed moves in the buffer, one per line. Output is a transposed grid with `-` as blank, `1` as player 1, and `0` as player 2 (with a bunch of newlines at the end).
**To clarify**, if you want Height 6, Width 7: type `qh6qqw7q` before starting.
* `@wO-<Esc><C-V>(d@hp`: Use the height and width in the registers to make a transposed grid of `-`s. Note that `(` is run from the last line of the grid, one above the moves. This sets up the jump list.
* `<C-O>+D@"G`: The `<C-O>` uses the jump list to move back to before the last `G`, always to the line above the next number. `@"G` moves to the line number indicated by the deleted text. `+` not only moves the cursor, but it's the failure point; when it runs on the last line, the macro dies.
* `+b`: This maneuver goes to the first `-` in the line, even if it's the first character. (`f-` would go to the second character if the line was still all `-`s.)
* `s<C-R>=!@.`: Replaces a `-` with the last insert `@.`, but NOTted. First time through, the previous insert of `-` will NOT to `1` because that's the way Vim is. After that, it will alternate between `0` and `1`.
### Example
Start with the moves in the buffer:
```
4
4
5
5
6
7
3
```
Make sure you're on line 1 with `gg`, clear `"q` with `qqq`, set up the registers for width 7, height 6 with `qw7qqh6q`. Then run the solution above and get the following output (with newlines at the end):
```
------
------
1-----
10----
10----
1-----
0-----
```
[Answer]
# Python 2, ~~91~~ 88 bytes
```
w,h,s=input()
i,x=0,['']*w
for c in s:x[c]+='XO'[i%2];i+=1
for c in x:print(c+'.'*h)[:h]
```
Since transposed is fine, this prints the board sitting on its right hand side.
**[repl.it](https://repl.it/DyIm/3)**
[Answer]
# Pyth, 19 bytes
```
m.[2vz%R2fq@QTd_UQE
```
[Try it online.](http://pyth.herokuapp.com/?code=m.%5B2vz%25R2fq%40QTd_UQE&input=3%2C3%2C4%2C4%2C5%2C6%2C2%0A6%0A7&debug=0)
Takes input as `c,o,l,s\nheight\nwidth`, 0-indexed. Outputs a list of columns (transposed), using `012` for player 1, player 2, empty respectively.
[Answer]
# Python 2, ~~143~~ ~~131~~ 107 Bytes
This doesn't use any real fancy tricks, ~~except list transposition to make index access easier~~ since we can print the board transposed. Definitely not done with this just yet. Moves are taken as 0-based numbers. Byte count comes before commenting.
Jonathan Allan had a better approach to building the board, mine is improved slightly since the slicing is a bit shorter `[-j:] -> [:j]` and the list comprehension helps shorten printing.
```
i,j,k=input() # split up the input
t=0 # keep track of whose move it is
g=i*[''] # board init
for b in k:g[b]+='XO'[t%2];t+=1 # read moves sequentially, place pieces
print'\n'.join(''.join((m+'.'*j)[:j])for m in g) # build the board
```
Example Input: `[7, 6, [3, 3, 4, 4, 5, 6, 2]]`
Example Output:
```
......
......
X.....
XO....
XO....
X.....
O.....
```
[Try it online](https://repl.it/DnAQ/17) or [view all test cases](https://repl.it/DnAQ/16).
[Answer]
## JavaScript (ES6), 121 bytes
```
(w,h,a,r=Array(w).fill``)=>a.map((c,j)=>r[c]+="XO"[j%2])&&[...Array(h)].map((_,i)=>r.map(s=>s[h+~i]||`.`).join``).join`\n`
```
0-indexed. I wanted to see how well I could match the example output, but most of the code seems to be taken up by the rotation.
[Answer]
# JavaScript (ES6), 62 ~~69~~
**Edit** 7 bytes saved thx @Arnauld
I have used this kind of string representation when logging the board status in my connect four player. It's short coded and easy to understand at first sight.
Input is 0 based
```
(w,h,s)=>s.map((v,i)=>r[v]+=i&1,r=Array(w).fill`|`)&&r.join`
`
```
More in line with the OP examples, this is 93 bytes
```
(w,h,s)=>s.map((v,i)=>r[v]+=i%2,r=Array(w).fill(``))&&r.map(r=>r+Array(h+1-r.length)).join`
`
```
(note: here the `fill``` trick won't work)
Output for `[7, 6, [3, 3, 4, 4, 5, 6, 2]]`
```
,,,,,,
,,,,,,
0,,,,,
01,,,,
01,,,,
0,,,,,
1,,,,,
```
**Test**
```
f=(w,h,s)=>s.map((v,i)=>r[v]+=i&1,r=Array(w).fill`|`)&&r.join`
`
console.log=s=>O.textContent+=s+'\n'
;[
[1, 1, []]
, [7, 6, [3, 3, 4, 4, 5, 6, 2]]
, [5, 5, [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4]]
, [4, 4, [2, 2, 1, 3, 2, 1, 3, 1, 1, 2, 3, 3, 0, 0, 0, 0]]
].forEach(t=>{
var w=t[0],h=t[1],s=t[2],r=f(w,h,s)
console.log(w+' '+h+' ['+s+']\n'+r+'\n')
})
```
```
<pre id=O></pre>
```
[Answer]
# Java 7, 209 bytes
Not very inspiring.Simple and plain solution.
```
char[][]f(int w,int h,int[]a){char[][]b=new char[h][w];for(char[]r:b)Arrays.fill(r,'.');for(int l=a.length,i=l-1,j,c=0;i>-1;b[h-c-1][a[i]]=i--%2==0?'X':'O',c=0){for(j=i-1;j>-1 ;)if(a[j--]==a[i])c++;}return b;}
```
# Ungolfed
```
char[][] f( int w , int h , int[]a ) {
char[][] b = new char [h][w];
for ( char[] r : b)
Arrays.fill( r , '.') ;
for ( int l = a.length,i = l-1 , j , c = 0 ; i > -1 ;
b[h-c-1][a[i]] = i--%2 == 0 ? 'X' : 'O', c = 0 ) {
for ( j = i-1 ; j > -1 ;)
if ( a[j--] == a[i] )
c++ ;
}
return b;
}
```
[Answer]
# Scala, 122 bytes
```
def%(w:Int,h:Int,m:Int*)=((Seq.fill(w)(Nil:Seq[Int]),1)/:m){case((a,p),x)=>(a.updated(x,a(x):+p),-p)}._1.map(_.padTo(h,0))
```
Ungolfed:
```
def f(w:Int,h:Int,m:Int*)=
m.foldLeft((Seq.fill(w)(Nil:Seq[Int]),1)){
case((res,player),x)=>
(res.updated(x,res(x):+player), -player)
}._1.map(_.padTo(h,0))
```
Explanation:
```
def%(w:Int,h:Int,m:Int*)= //define a method
(
( //with a tuple of
Seq.fill(w)(Nil:Seq[Int]), //a Sequence of w empty sequences
1 //and 1
) //as a start value,
/:m //foldLeft the moves
){ //using the following function,
case((a,p),x)=> //which takes the result, the player and the x coordinate
( //return a tuple of
a.updated(x,a(x):+p), //the seq with index x with p appended
-p //and the other player
)
}._1.map( //take the resulting seq and foreach column
_.padTo(h,0) //append 0 until the length is h
)
```
Returns a sequence of the columns in bottom-to-top order.
The players are represented as `-1` and `1`, empty cells are `0`.
] |
[Question]
[
Frank has been working IT his whole life. Each day he responds to tickets, organizes equipment, and reports to his boss. One day, near the closing time on friday, Frank is doing his final inventory and sorting come cables in the supply closet. Suddenly, the door closes and locks from the outside! Such audacity! Frank shakes the door to try and let anyone know that he's stuck in the closet. Blast, nobody comes to his aid. With no cellphone, and no internet connection, Frank settles in with his laptop. After countless games of solitaire, frank decides to make his own card game....
## Challenge:
In this case, you are frank (but not really). Your challenge is to create a dealer that can deal hands of cards, that could be dealt realistically. Your program needs to do 2 things: deal hands of cards according to an input, and take all the hands and reshuffle them. You must do this in the least ammount of bytes possible.
## Rules:
Possible cards include all classic numbers and faces (a,2,3,4,5,6,7,8,9,10,j,q,k) and all suits (c,s,h,d), and two jokers (0j).
If a card is dealt, it cannot be dealt again until the program is given the reshuffle command, or it runs out of cards.
valid inputs are '**d**' to deal a hand of 6 cards, and '**r**' to reshuffle. **NOTE** that you can only deal out 9 hands before you run out of cards. Your program can either:
Automatically reshuffle,
Or give a 'X' to indicate that the dealer is out of cards.
your program needs to be able to take multiple commands over its running span.
All possible hands need to be able to be dealt in every order. Though, your program does **NOT** have to be random.
## Examples:
We deal twice, the first hand yields the 2 of hearts, a 4 of spades, 9 of clubs, a joker, an ace of spades, and a 6 of diamonds. The second hand yields the 3 of hearts, the 10 of diamonds, the 10 of clubs, the king of clubs, the ace of diamonds, and the queen of spades. this is **VALID** because this is possible in real life.
>
> d
>
> 2h4s9c0jas6d
>
> d
>
> 3h10d10ckcadqs
>
>
>
We deal twice, the first hand yields a mass of 5 cards (indicated by the dashes) and a 6 of hearts. The second hand deals another mass of 5 cards (again, the dashes) and another 6 of hearts. This is **INVALID** because it cannot happen in real life.
>
> d
>
> -----6h
>
> d
>
> 6h-----
>
>
>
we deal once, reset, and deal again. some of the cards from the first and the second deal match. this is **VALID** because cardstacks are renewed when shuffled.
>
> d
>
> 123456
>
> r
>
>
> d
>
> 456789
>
>
>
## Scoring:
As with any golf, the lowest byte count wins! Good luck!
[Answer]
# Pyth - ~~42~~ 41 bytes
Will need to restructure this.
```
VcQ\rj<c9.S++M*+md"jqka"}2T"cshd"m"0j"2lN
```
[Try it online here](http://pyth.herokuapp.com/?code=VcQ%5Crj%3Cc9.S%2B%2BM%2a%2Bmd%22jqka%22%7D2T%22cshd%22m%220j%222lN&input=%22dddddddddddrdd%22&debug=1).
Stops giving cards after 9 deals.
[Answer]
## Javascript (ES6), 189 bytes
```
i=>{for(n=52,d=['0j','0j'];n;d[n+1]='123456789JQKA'[--n>>2]+(n<4?0:'')+'cdhs'[n&3]);i.forEach(c=>{c!='r'&&n-54||(d.sort((a,b)=>Math.random()-.5),n=0);c=='d'&&console.log(d.slice(n,n+=6))})}
```
Demo:
```
let F =
i=>{for(n=52,d=['0j','0j'];n;d[n+1]='123456789JQKA'[--n>>2]+(n<4?0:'')+'cdhs'[n&3]);i.forEach(c=>{c!='r'&&n-54||(d.sort((a,b)=>Math.random()-.5),n=0);c=='d'&&console.log(d.slice(n,n+=6))})}
F([..."rddrdddddd"]);
```
[Answer]
## Python 3, ~~184 192~~ 179 bytes
```
d=lambda:[(v+s,'10'+s)[v=='1']for v in'123456789JQKA'for s in'SCHD']+['0J']*2
_=0;c=d()
while 1:
if input()<'r'*(len(c)>5):[print(c.pop())for i in'_'*6]
else:c=d();del c[_];_+=1
```
Edit: jokers
Edit 2: switched from using random and shuffling the list to cycling through the list and deleting 1 index from it incrementally.
[Try it](https://repl.it/CogS/5)
[Answer]
## [05AB1E](https://github.com/Adriandmen/05AB1E/), 56 bytes
Automatically reshuffles.
```
9L>"ajqk"Sì"cshd"â€J„0jD‚ì©UvXg>y'rQ~i®U}y'dQiX.r6ô¬,¦˜U
```
**Explanation**
Generate the list of cards:
```
9L>"ajqk"Sì # list of card values, excluding jokers
"cshd"â€J # cartesian product with suits to generate all cards except jokers
„0jD‚ì # add the jokers
©U # store in register and X
```
The actual function:
```
v # for each in input
i } # if
Xg> # we're out of cards
~ # or
y'rQ # it's an explicit reshuffle
®U # get full list of cards from register and store in X
# then
y'dQi # if it's a draw
X.r # shuffle current list of cards
6ô¬, # print a list of 6 cards
¦˜U # save the rest of the cards in X
```
[Try it online](http://05ab1e.tryitonline.net/#code=OUw-ImFqcWsiU8OsImNzaGQiw6LigqxK4oCeMGpE4oCaw6zCqVV2WGc-eSdyUX5pwq5VfXknZFFpWC5yNsO0wqwswqbLnFU&input=ZGRkZGRkZGRkZGRkcmRk)
[Answer]
## PHP, 342 bytes
Update of @hd-s version.
```
$c=explode(",","2,3,4,5,6,7,8,9,T,J,Q,K,A");$a=["h"=>$c,"d"=>$c,"s"=>$c,"c"=>$c,"0"=>["J","J"]];$b=$a;$f=0;foreach(explode(",",$argv[1])as$g){if($g=='d'&&$f<54){$f+=6;for($i=0;$i<6;$i++){$s=array_keys($a)[rand(0,4)];$l=rand(1,count($a[$s])-1);if(isset($a[$s][$l])){echo$a[$s][$l].$s;unset($a[$s][$l])}else{$i--}}echo PHP_EOL}else{$f=0;$a=$b}}
```
Please test before qualifying. PHP 5.3+
## Changes:
* All variables renamed to be 1 byte long
* The card array is just reset at the end
* All cards dealt check shortened
* Couple of spaces removed
Total bytes saved: **69**
[Answer]
## PHP, 411 bytes
This will generate a random outcome for each play (each deal(`d`)) and then once it's used all the cards, it will reshuffle the deck, clearing the play space.
To run, input comma separated commands: `php card_dealer_golf.php d,d,d,d,r`
```
$c=explode(",","a,2,3,4,5,6,7,8,9,10,j,q,k");$a=["h"=>$c,"d"=>$c,"s"=>$c,"c"=>$c,"0"=>["J","J"]];$cd=0;foreach(explode(",",$argv[1]) as $cmd){if($cd>=54){$cmd="r";}if($cmd=='d'){$cd+=6;for($i=0;$i<6;$i++){$s=array_keys($a)[rand(0,4)];$l=rand(1,count($a[$s])-1);if(isset($a[$s][$l])){echo$a[$s][$l].$s;unset($a[$s][$l]);}else{$i--;}}echo PHP_EOL;}else{$cd=0;$a=["h"=>$c,"d"=>$c,"s"=>$c,"c"=>$c,"0"=>["J","J"]];}}
```
Output:
```
$ php card_dealer_golf.php d,d,d,d,r
10djs5cjh2h3h
3cJ06d2d7d3s
9s6s7h4d6c4s
10c4c3d7c8h6h
```
Ungolfed version
```
$cards = explode(",","a,2,3,4,5,6,7,8,9,10,j,q,k");
$a = [
"h" => $cards,
"d" => $cards,
"s" => $cards,
"c" => $cards,
"0" => ["J","J"]
];
$cd=0;
foreach(explode(",",$argv[1]) as $cmd) {
if($cd>=54) {$cmd = "r";}
if($cmd=='d'){
$cd+=6; //+6 cards dealt
for($i=0;$i<6;$i++){
$suit = array_keys($a)[rand(0,4)]; //get random suit
$l=rand(1,count($a[$suit])-1); //get random card from suit
if(isset($a[$suit][$l])){ //if the card is still in the deck
echo $a[$suit][$l].$suit; //output it
unset($a[$suit][$l]); //remove from deck
}else{
$i--; //card not in deck, decrease the cards dealt in this round to be regenered
}
}
echo PHP_EOL;
}else{
//reshuffle logic. reset deck and amount of cards dealth
$cd=0;
$a = [
"h" => $cards,
"d" => $cards,
"s" => $cards,
"c" => $cards,
"0" => ["J","J"]
];
}
}
```
[Answer]
## PowerShell v2+, ~~174~~ 158 bytes
```
$a=(2..10+[char[]]'ajqk'|%{$i=$_;[char[]]'cshd'|%{"$i$_"}})+'0j'+'1j';$x=,0
for(){switch(read-host){'d'{$a|?{$_-notin$x}|Random -c 6|%{$x+=$_;$_}}'r'{$x=,0}}}
```
Creates an array of the number and suit combinations, plus two jokers (note they're unique), stores that into `$a`. This forms our full deck. Sets array `$x` equal to `[0]`. This represents the cards that we've already dealt. Then enters an infinite `for` loop. Performs a `read-host` to get the `d` or `r` (other behavior is undefined).
For `d`ealing, pipes `$a` a `Where-Object` to pull out the items that are `-notin$x` (i.e., the cards we haven't dealt yet). Those are piped to `Get-Random` with a `-c`ount of `6`, which will randomly select 6 distinct elements. We store those newly-dealt cards into `$x`, and the card is placed `$_` onto the pipeline, which will get flushed when the next `read-host` happens and output one-per-line thanks to the default behavior of `Write-Output`. If the user attempts to `d`eal when `$a = $x` (i.e., all cards have been dealt), then the `Get-Random` will be selecting from nothing, and so nothing will be output.
For the `r`eshuffling, we just set `$x` back to `,0` as the original array.
Note you'll need to `ctrl-c` or otherwise force quit the program.
### Example execution
```
PS C:\Tools\Scripts\golfing> .\golf-card-dealer.ps1
d
8c
5h
as
ah
1j
ac
d
5d
2h
8s
6h
2c
qs
d
8h
6d
10c
10h
6s
4h
d
js
9h
4c
6c
qd
kd
d
3d
jc
8d
2s
3h
4d
d
kh
jd
3c
0j
jh
10d
d
9s
7s
ks
kc
qc
9d
d
5s
9c
7c
4s
10s
7d
d
7h
5c
3s
qh
2d
ad
d
d
d
r
d
3c
qs
2s
kd
2h
qc
d
ks
2d
5s
qd
kc
js
PS C:\Tools\Scripts\golfing>
```
] |
[Question]
[
For example, if `n` is 5 and `r` is 2, it would mean the number of lists below:
```
[1,1,1,1,1]
[1,1,1,2,2]
[1,1,2,2,2]
[2,2,1,1,1]
[2,2,2,1,1]
[2,2,2,2,2]
```
which is **6**.
If `n` is 4 and `r` is 3:
```
[1,1,1,1]
[1,1,2,2]
[1,1,3,3]
[2,2,1,1]
...
[3,3,3,3]
```
which is **9**.
where each item has a neighbour whose value is the same.
For example, `[1,2,1,1,2]` is not counted, because both `2` are alone.
# Goal
Your task is to write a program/function which takes two inputs in any order, and which produces the required output.
# Detail
You can assume that `r≥2`.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest solution in bytes wins.
# Bonus
Multiply your score by **0.3** if the complexity of your program is below O(e^n).
For example, 10 bytes becomes 3 bytes.
# Testcases
Can be generated from [this Pyth test suite](http://pyth.herokuapp.com/?code=JELqV%2Bdb%2Bbdlf%26F|VPyTtyT%7BmtjdJr%5EJQ%5EJh&test_suite=1&test_suite_input=2%0A5%0A4%0A4%0A6%0A3%0A8%0A2&debug=0&input_size=2).
Usage: two lines per testcase, `n` on top, `r` below.
```
n r output
2 5 5
4 4 16
6 3 33
8 2 26
```
# Additional information
When `r=2`: [OEIS A006355](http://oeis.org/A006355).
[Answer]
# Pyth, 14 bytes \* 0.3 = 4.2 bytes
```
*Quh*~+ZGtQtE0
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=*Quh*~%2BZGtQtE0&input=2%0A5&test_suite_input=2%0A5%0A3%0A4%0A5%0A20&debug=0&input_size=2). Input `r` on the first line and `n` on the second line.
Complexity is `O(n)`.
### Explanation:
Let `f(n, r)` be the number of ways to create such a list with the last number being `0`. Obviously it doesn't matter if we take `0` or any other number.
It's easy to see, that the following recursion holds:
```
f(n, r) = 0 ... if n < 2
f(n, r) = sum(f(i, r), i <= n-2) * (r-1) + 1 ... otherwise
```
If `n == 0`, than the list cannot end with the number `0`. If `n == 1`, than the only number in the list has no neighbor. Therefore both cases have the value zero.
If `n >= 2`, than it could end in 2, 3, ... n zeros. The digit before the last zero can be any of the number 1, 2, ..., r-1. These are `r-1` possibilities. Therefore I'll add up all `f(i,n)` and multiply by `r-1`. At the end I'll have to add 1 (for the case that all digits are zeros).
The result to the question than is: `r * f(n, r)`, since the list can end in any of the `r` numbers.
In my code I make use of the predefined variable `Z = 0`. It will contain the last computed sum so far.
```
*Quh*~+ZGtQtE0 implicit: Q = first input number (r)
u tE0 start with G=0, do the following input-1 (n-1) times:
~+ZG add G to Z
h*~ Z tQ and update G to the value Z*(Q-1) + 1
(using the old value of Z)
*Q multiply the result with Q
```
[Answer]
## JavaScript (ES6), 64 (70 \* 0.3 = 21) bytes
```
(n,r)=>[...Array(n)].map((m,i,a)=>a[i+2]=(s=s+m|0)*~-r+r).slice(-2)[0]
```
Now runs in linear time!
[Answer]
# Haskell, 16.5 (55 bytes)
```
r#n=l!!(n-1)where l=0:r:r:w l;w(x:y:s)=r*(x+y)-x:w(y:s)
```
It uses this recursive definition:
```
f(n,r) = r*f(n-2,r) + (r-1)*f(n-3,r)
```
and uses `O(n)` time.
Usage: evaluate `r#n`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ṗŒɠ€’Ạ€S
```
[Try it online!](https://tio.run/##y0rNyan8///hzulHJ51c8KhpzaOGmQ93gRjB/w8vV/r/30hHwfi/qY6CCQA "Jelly – Try It Online")
## How it works
```
ṗŒɠ€’Ạ€S - Main link. Takes r on the left and n on the right
ṗ - n'th Cartesian power of [1,2,3,...,n]
€ - Over each:
Œɠ - Lengths of adjacent elements
’ - Decrement, mapping 1 to 0 and everything else to a positive integer
€ - Over each:
Ạ - All non-zero?
S - Sum, counting the 1s
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
#oΛtgπ
```
[Try it online!](https://tio.run/##yygtzv7/Xzn/3OyS9PMN////N/lvDAA "Husk – Try It Online")
## Explanation
```
#oΛtgπ
π cartesian power n of range 1..r
#o number of lists which satisfy
g adjacent elements grouped
Λ all the groups
t are non empty when popped from
```
] |
[Question]
[
Write a function or program which, given a number of lines and columns, generates a corresponding `tabular` environment for LaTeX with no data in it.
### Table format and `tabular` Environment
Here is an example of a table with 2 rows and 4 columns:
[](https://i.stack.imgur.com/uGgLg.png)
As you can see, we do not count the first row nor do we count the first column: those are for the labels of the table.
The top left corner is also "missing", in that there is no border around it.
The corresponding LaTeX's code to generate this table is the following:
```
\begin{tabular}{|c|c|c|c|c|}
\cline{2-5}
\multicolumn{1}{c|}{} & & & & \\
\hline
& & & & \\
\hline
& & & & \\
\hline
\end{tabular}
```
* There are as many `c` in the first line as there are **total** columns (that is, 1 more than the number of columns given as input). These `c` are separated by `|` (and there are `|` on both the extreme left and extreme right too).
* The first horizontal separator is generated by `\cline{2-X}` where X is the index of the last column (starting from 1).
* The first element of the first row is always `\multicolumn{1}{c|}{}` (this removes the borders of the top left corner).
* Each row has `C` `&`, `C` being the number of columns given as input. Each line ends with `\\`.
* Each row is followed by a `\hline`.
### Formatting details
* You must indent everything between the `begin{tabular}{...}` and `\end{tabular}` tags with **4 spaces**.
* The `&`'s are separated with exactly one space on each row. The first one of the row does not have an extra space before it (since it already has 4 spaces before it). Note that this is not true for the first row, where the first `&` has a space before it because of the `\multicolumn` element.
* `\\` is separated from the last `&` by a space.
* Each `\hline` and row description is on its own new line.
### Input
Input is a couple of two integers representing the number of columns and the number of rows. Note that this is the number of columns and rows excluding the very first row and very first column.
You may assume that the row and column inputs will always be at least 1, and less than 1024.
Those two numbers can be taken whichever way is most appropriate in your language (two args, a list, etc.).
### Output
The output is a string of the LaTeX code that generates a table with the appropriate number of rows and columns. This can be returned from a function or outputted to STDOUT.
A trailing new line is allowed after the `\end{tabular}`. Trailing spaces are not allowed at the end of any line.
### Test cases
```
Input: (1,1)
Output:
\begin{tabular}{|c|c|}
\cline{2-2}
\multicolumn{1}{c|}{} & \\
\hline
& \\
\hline
\end{tabular}
Input: 2 rows, 4 columns
Output:
\begin{tabular}{|c|c|c|c|c|}
\cline{2-5}
\multicolumn{1}{c|}{} & & & & \\
\hline
& & & & \\
\hline
& & & & \\
\hline
\end{tabular}
```
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes `\emph{wins}`.
[Answer]
# JavaScript (ES6), ~~172~~ 170 bytes
```
a=>b=>`\\begin{tabular}{${'|c'[r='repeat'](++b)}|}
\\cline{2-${b--}}
\\multicolumn{1}{c|}{} ${('& '[r](b)+`\\\\
\\hline
`)[r](a+1).trim()}
\\end{tabular}`
```
Called as `F(a)(b)` (credit to Patrick Roberts for finding this method)
Would have been much messier if not for template strings. Originally came in at 200, when I had a separate repeat for the multicolumn `&`'s, but cut it down a good amount by combining them and using `trim` to get rid of the final unneeded indentation.
[Answer]
# Python 2, 197 bytes
This solution uses string formatting to reduce repetition. Each string component is assembled, then placed within the template. It is tricky to use so many backslashes in Python strings. I used the raw string `r'\\'` and multi-line `'''blah \n blah'''` string techniques here.
```
def a(d,e):
c='c|'*e;b='& '*e+r'\\';g=' '*4+b+'\n \\hline\n';f=g*d;h='{tabular}'
return r'''\begin%s{|c|%s}
\cline{2-%s}
\multicolumn{1}{c|}{} %s
\hline
%s\end%s'''%(h,c,e+1,b,f,h)
```
Before the minifier, it looks like this:
```
def latextable(height, width):
columns = 'c|' * width;
linespec = '& ' * width + r'\\';
line = ' '*4 + linespec + '\n \\hline\n';
block = line * height;
mode = '{tabular}'
return r'''\begin%s{|c|%s}
\cline{2-%s}
\multicolumn{1}{c|}{} %s
\hline
%s\end%s''' % (mode, columns, width+1, linespec, block, mode)
print latextable(1, 1)
print latextable(2, 4)
```
The output tests:
```
\begin{tabular}{|c|c|}
\cline{2-2}
\multicolumn{1}{c|}{} & \\
\hline
& \\
\hline
\end{tabular}
\begin{tabular}{|c|c|c|c|c|}
\cline{2-5}
\multicolumn{1}{c|}{} & & & & \\
\hline
& & & & \\
\hline
& & & & \\
\hline
\end{tabular}
```
As a side note, I wrote a latex macro processor like this to format my thesis. I think I spent longer on developing that macro processor than on writing the words...
[Answer]
**C#, 248 byte**
```
string t(int r,int c){string i="\r\n ",d="",q="",m;for(int j=0;j++<c;){d+="c|";q+="& ";}q+=$"\\\\{i}\\hline";m=@"\begin{tabular}{|c|"+d+"}"+i+@"\cline{2-"+(c+1)+"}"+i+@"\multicolumn{1}{c|}{} "+q;for(;r-->0;)m+=i+q;return m+"\r\n\\end{tabular}";}
```
Tester:
```
using System;
class Table
{
static int Main()
{
var x = new Table();
Console.WriteLine(x.t(1,1));
Console.WriteLine(x.t(2,4));
Console.Read();
return 0;
}
string t(int r,int c){string i="\r\n ",d="",q="",m;for(int j=0;j++<c;){d+="c|";q+="& ";}q+=$"\\\\{i}\\hline";m=@"\begin{tabular}{|c|"+d+"}"+i+@"\cline{2-"+(c+1)+"}"+i+@"\multicolumn{1}{c|}{} "+q;for(;r-->0;)m+=i+q;return m+"\r\n\\end{tabular}";}
string tab(int row, int col){
string i="\r\n ",sc="",sr="",msg;
for(int j=0;j++<col;){sc+="c|";sr+="& ";}
sr+=$"\\\\{i}\\hline";
msg=@"\begin{tabular}{|c|"+sc+"}"+i+@"\cline{2-"+(col+1)+"}"+i+@"\multicolumn{1}{c|}{} "+sr;
for(;row>0;)msg+=i+sr;
return msg+"\r\n\\end{tabular}";
}
}
```
] |
[Question]
[
You are given a table that represents the rankings of *S* subjects according to a number *C* of different criteria. The purpose is to
* compute an **overall** ranking according to a weighted sum of the *C* ranking criteria,
* using one of those criteria (i.e. columns), *T*, as **tie-breaker**.
The rankings are a *S*×*C* table of positive integers. The weights for computing the overall ranking are given as an array of non-negative numbers.
Entry (*s*,*c*) of the table contains the ranking of subject *s* according to criterion *c*; that is the **position** of subject *s* when all *S* subjects are sorted according to criterion *c*. (Another possible interpretation, **not** used here, would be: row *s* tells which user is ranked *s*-th according to criterion *c*).
### Example
Consider the following table with *S*=6 and *C*=2:
```
1 4
4 5
6 1
3 3
5 2
2 6
```
Weights are
```
1.5 2.5
```
and column *T*=2 is used as tie-breaker.
The overall ranking for the first subject (first row) is `1*1.5+4*2.5 = 11.5`. The overall ranking array is
```
11.5
18.5
11.5
12
12.5
18
```
The resulting ranking, which is the output, is then
```
2
6
1
3
4
5
```
Note that the first-ranked row is the third, not the first, according to the tie-breaking specification.
## Input and output
Use any reasonable format for input and output. The rankings may be a 2D array of any orientation, an array of arrays, or separate arrays. Inputs may be taken in any fixed order.
Input and output rankings should be 1-based (as in the example above), because that's the natural way to speak of rankings.
Output may be a string of numbers with a fixed separator character or an array.
You can write a function or a program.
## Test cases
Table, weights, tie-breaking column, output.
```
--- (Example above) ---
1 4
4 5
6 1
3 3
5 2
2 6
1.5 2.5
2
2
6
1
3
4
5
--- (Three columns) ---
4 4 1
2 3 5
5 1 3
3 5 2
1 2 4
0.5 1.4 0.9
1
3
4
1
5
2
--- (Only one weight is nonzero) ---
1 5
3 3
4 2
5 1
2 4
1 0
2
1
3
4
5
2
--- (Only one column) ---
2
4
1
3
1.25
1
2
4
1
3
--- (Only one row) ---
1 1 1
0.8 1.5 2
3
1
```
[Answer]
## Jelly, ~~11~~ 10 bytes
*-1 byte by @Dennis*
```
×⁵S€żị@€ỤỤ
```
Uses the fact that lists are lexicographically ordered.
This is a dyadic link that takes two arguments plus one input. The left argument is x, the rankings. The right argument is y, the tiebreaker. The input is the weights.
```
×⁵S€żị@€ỤỤ Dyadic function. Inputs: x, y
×⁵ Vectorized multiply x by the weights.
S Sum the rows.
This is the weighted ordering.
ż Zip with
ị@€ x indexed at y, mapped over x
ỤỤ and compute the inverse of the permutation vector that sorts that.
A list is sorted by its inverse permutation, so
this is the inverse of the inverse; i.e. the original permutation.
```
Try it [here](http://jelly.tryitonline.net/#code=w5figbVT4oKsxbzhu4tA4oKs4buk4buk&input=&args=WzEsIDRdLCBbNCwgNV0sIFs2LCAxXSwgWzMsIDNdLCBbNSwgMl0sIFsyLCA2XQ+Mg+MS41LCAyLjU).
[Answer]
# JavaScript (ES6), 114 bytes
```
(a,w,t)=>a.map(s=>s.reduce((p,v,c)=>p+v*w[c],0)).map((n,i,b)=>b.map((v,j)=>r+=n>v|v==n&a[j][t-1]<a[i][t-1],r=1)|r)
```
## Explanation
Fairly straight-forward. Expects an array of rows as arrays, an array of weights as numbers, and the tie-breaker column as a number. Returns an array.
```
var solution =
(a,w,t)=>
a.map(s=> // for each row s in the criteria table
s.reduce((p,v,c)=>p+v*w[c],0) // create an array of the summed weights for each row
)
.map((n,i,b)=> // for each number n at i in the summed weights array b
b.map((v,j)=> // compare it to each other summed weight
r+=n>v // increment it's rank if n > v
|v==n&a[j][t-1]<a[i][t-1], // or in case of tie, check the weights in column t
r=1 // initialise the rank to 1
)|r // return the rank
)
```
```
<textarea id="table" rows="5" cols="40">4 4 1
2 3 5
5 1 3
3 5 2
1 2 4</textarea><br />
Weights = <input type="text" id="weights" value="0.5 1.4 0.9" /><br />
Tie-Breaker = <input type="number" id="tie" value="1" /><br />
<button onclick="result.textContent=solution(table.value.split('\n').map(x=>x.split(/\s+/).map(n=>+n)),weights.value.split(/\s+/).map(n=>+n),+tie.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~21~~ 20 bytes
```
2#2$XSwiY*4#S)tn:tb(
```
Takes input as a matrix for the table of rankings, then the tie breaking column as a number, then a column vector of weightings for each column. Attempted explanation:
```
2#2$XS % specifies 2 inputs/2 outputs for sortrows, takes 2 implicit inputs,
% and sorts the matrix of ranks based on the second column. This means
% ties are automatically broken in the correct way
wiY* % swap the top 2 elements in the stack, take an input, and matrix multiply
% the (sorted) ranking table by the weighting vector to give ranking array
4#S) % sort the ranking array, taking only the permutation vector, and use it to
% reorder the original sortrows permutation vector
tn: % make a vector 1:(number of rows in ranking table)
tb( % index 1:n vector using permutation vector to give final ranking
% implicit display
```
[Try it Online!](http://matl.tryitonline.net/#code=MiMyJFhTd2lZKjQjUyl0bjp0Yig&input=WzEgNDs0IDU7NiAxOzMgMzs1IDI7MiA2XQoyClsxLjU7Mi41XQ)
(Written using MATL version 11.0.3 from a few weeks ago)
The equivalent Matlab code may be easier to understand:
```
[f,g]=sortrows(A,c); % 2#2$XS (A=matrix of ranks, c=tie-break column)
[~,l]=sort(f*B); % wiY*4#S (B=weighting vector)
t=1:numel(g); %
t(g(l))=t % )tn:tb(
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 16 bytes
```
Y*2GiY)v!4#XS4#S
```
Input is of the form: weights; table with each ranking on a different row; tie-breaker. Foe example,
```
[1.5 2.5]
[1 4 6 3 5 2; 4 5 1 3 2 6]
2
```
Try it online! [First](http://matl.tryitonline.net/#code=WSoyR2lZKXYhNCNYUzQjUw&input=WzEuNSAyLjVdClsxIDQgNiAzIDUgMjs0IDUgMSAzIDIgNl0KMgo) test case, [second](http://matl.tryitonline.net/#code=WSoyR2lZKXYhNCNYUzQjUw&input=WzAuNSAxLjQgMC45XQpbNCAyIDUgMyAxOyA0IDMgMSA1IDI7IDEgNSAzIDIgNF0KMQo), [third](http://matl.tryitonline.net/#code=WSoyR2lZKXYhNCNYUzQjUw&input=WzEgMF0KWzEgMyA0IDUgMjs1IDMgMiAxIDRdCjIK), [fourth](http://matl.tryitonline.net/#code=WSoyR2lZKXYhNCNYUzQjUw&input=WzEuMjVdClsyIDQgMSAzXQoxCg), [fifth](http://matl.tryitonline.net/#code=WSoyR2lZKXYhNCNYUzQjUw&input=WzAuOCAxLjUgMl0KWzE7IDE7IDFdCjMK).
```
Y* % implicitly input ranking table and weights. Matrix multiply, to produce
% combined ranking as a row vector
2G % push ranking table again
i % input tie-breaker
Y) % get that ranking from the table (as a row)
v! % join combined ranking and tie-breaker column. Produce 2-col matrix
4#XS % sort rows by first column (combined ranking) and then second
% column (tie-breaker). Produce not the sorted matrix, but the indices
% of the sorting, as a column vector
4#S % sort that vector and get the indices of the sorting. Implicitly display
```
] |
[Question]
[
In the game [Hearthstone](https://en.wikipedia.org/wiki/Hearthstone:_Heroes_of_Warcraft) there is a playing board containing friendly and enemy minions, and two heroes - yours and the enemy's.
To generalize and simplify, we will assume it's your turn, the opponent has 0-7 minions with given health values on the board, and is at *H* life points. We will ignore our side of the board entirely.
Now we will cast a supercharged version of [Arcane Missiles](http://hearthstone.gamepedia.com/Arcane_Missiles). This ability shoots a random enemy (uniformly selected from all alive minions and the hero) for 1 damage, repeated *A* times. Note that if a target dies (reduced to 0 health), it can not be hit again.
Given *H*, *A* and a list *L* containing the health values of the minions, output the probability as a percentage accurate to 2 digits after the decimal point that *either or both* the hero dies, or every minion dies (clearing the board).
Some examples logically derived:
```
H: 30, A: 2, L: [1, 1]
We have no chance of killing our opponent here. To clear the board, both shots
must hit a minion. The first shot has a 2/3 chance of hitting a minion, then
that minion dies. The second shot has a 1/2 chance. The probability of clearing
the board or killing our opponent is thus 2/6 = 33.33%.
H: 2, A: 3, L: [9, 3, 4, 1, 9]
We have no chance of clearing the board here. 2/3 shots must hit the hero. However,
if any of the shots hit the 1 health minion, it dies, increasing the odds for
future shots.
4/6 the first shot hits a health minion. The next two shots must hit the hero,
for a total probability of 4/6 * 1/6 * 1/6.
1/6 the first shot hits the 1 health minion and it dies. The next two shots must
hit the hero, for a total probability of 1/6 * 1/5 * 1/5.
1/6 the first shot hits the hero. Then there are three options again:
1/6 the second shot hits the hero.
4/6 the second shot hits a healthy minion. The last shot must hit 1/6.
1/6 the second shot hits the 1 health minion. The last shot must hit 1/5.
This last option gives a probability of 1/6 * (1/6 + 4/6 * 1/6 + 1/(5*6)). The
total probability is the chance of any of these scenarios happening, or:
4/6 * 1/6 * 1/6 + 1/(6*5*5) + 1/6 * (1/6 + 4/6 * 1/6 + 1/(5*6)) = 7.70%
```
As you can see, it gets complicated quickly... Good luck!
---
Your score is the number of bytes of code of your answer. If your code computes a probability exactly rather than simulating boards, halve your score. Lowest score wins.
[Answer]
# Pyth, (67 bytes) / 2 = 33.5
```
L_,*lbJ*FeCbsm*hd/JedbM?&hHstH?GymgtG-XdKH_1_!dlH,01,TT*100cFghQstQ
```
This qualifies for the bonus even though I had to manually implement arbitrary precision rationals.
(I wish Pyth5 was already a thing).
Input from STDIN in the format `A, H, L`
[Demonstration.](https://pyth.herokuapp.com/?code=L_%2C*lbJ*FeCbsm*hd%2FJedbM%3F%26hHstH%3FGymgtG-XdKH_1_!dlH%2C01%2CTT*100cFghQstQ&input=3%2C+2%2C+%5B9%2C+3%2C+4%2C+1%2C+9%5D&debug=0)
Corrected to output percentage. Percentage is as acurate as possible, due to use of integer math until the last step.
At the high level, the first segment, `L_,*lbJ*FeCbsm*hd/Jedb`, is a helper function which takes a list of rationals in the form of 2 element lists, and outputs their average as an (unreduced) rational.
The second segment, `M?&hHstH?GymgtG-XdKH_1_!dlH,01,TT`, recusively calculates the probability of victory.
The third segment, `cFghQstQ` formats the input to fit the function and performs the final division.
On the second example case, the final unreduced 2-tuple is too long to fit on the screen:
```
[83158592487544376524800000000000000000000, 1079462498636393349120000000000000000000000]
```
Fortunately, Pyth does have arbitrary precision integers.
[Answer]
# Ruby, Score: 328/2 = 164
Here is a ruby solution that calculates the answer exactly (and then truncates the answer as specified), using the power of recursion. You run it in irb with the `g` function:
```
require 'rational'
def c(h, a, l)
l=l.reject { |m| m == 0 }
return 1.to_r if l.empty? ||h==0
return 0.to_r if a==0
a-=1
n=[c(h-1, a, l), *((0..l.length-1).map { |i| nl = l.dup;nl[i]-=1;c(h, a, nl)})]
n.inject(:+)/n.length
end
def g(h, a, l)
puts "%.2f%%" % (c(h.to_r, a.to_r, l.map(&:to_r)) * 100)
end
```
Example output:
```
> g 30, 2, [1,1]
33.33%
> g 2, 3, [9,3,4,1,9]
7.70%
```
] |
[Question]
[
There is that famous [riddle](http://www.scientificpsychic.com/mind/bear1.html):
>
> A bear walks 1 km south, 1 km east and 1 km north, and comes to the place it started from. What color is the bear?
>
>
>
This one is very old, so I'll generalize it:
>
> A bear walks `x` km south, `y` km east and `x` km north, and comes to the place it started from. This bear thinks that the North Pole is boring, so it never goes there. Which latitude did it start and end at?
>
>
>
Assume that the bear is an idealized point, and the Earth is a perfect sphere with [10000 km](https://en.wikipedia.org/wiki/History_of_the_metre) distance from the pole to the equator (however, you can use a more accurate model if it's easier for some reason).
Write a program or a subroutine that receives the two numbers `x` and `y`, and prints or returns the latitude.
Fine points:
* Input with at least 3 decimal places of precision should be supported
* Input is in the range (0...99999), bounds not inclusive
* If the situation is physically impossible, print an empty string or a message, or return an impossible value (like 91 or `NaN` - or, in fact, 90 - since 90 is an impossible value)
* You should print the most northern (maximal) latitude that satisfies the conditions, except the North Pole. If the North Pole is the only solution, see above.
* Output precision should be like [IEEE single precison](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) or better (24 bits or 7 decimal digits of precision).
* If the output is printed, use decimal notation (e.g. -89.99 for a point near the South Pole) . If the output is returned, use floating-point or fixed-point notation.
Shortest code in bytes wins.
[Answer]
## CJam, 62 chars
```
{4e4/:Y\9e-3*:X90-P180/:Q*mc/XY2$m](/mCQ/+_90<\@XY@m[)/mCQ/-?}
```
This is a block (subroutine) which takes `x y` on the stack and leaves the solution on the stack.
[Online demo](http://cjam.aditsu.net/#code=%5B8.e3%204.e4%20%20%20%20%20%2272.0%22%3B%0A%208.e3%2039.e3%20%20%20%20%2284.83856814098405%22%3B%0A%208.e3%2038.e3%20%20%20%20%2253.805127661233215%22%3B%0A%201.e4%204.e4%20%20%20%20%20%2229.999999999999993%22%3B%0A%2018.e3%208.e4%20%20%20%20%2288.60154959902023%22%3B%0A%201.e3%204.e4%20%20%20%20%20%2289.40593177313954%22%3B%0A%5D2%2F%7B~%0A%0A%7B4e4%2F%3AY%5C9e-3*%3AX90-P180%2F%3AQ*mc%2FXY2%24m%5D(%2FmCQ%2F%2B_90%3C%5C%40XY%40m%5B)%2FmCQ%2F-%3F%7D%0A%0A~p%7D%2F)
I'm interpreting the spec to allow returning 90 as an "impossible value" if there is no other solution. If that interpretation is disallowed, I think the best fix would be
```
{4e4/:Y\9e-3*:X90-P180/:Q*mc/[XY2$m](/mCQ/+\XY@m[)/mCQ/--91]{90<}=}
```
] |
[Question]
[
Just last night I was reading a book which had a chapter on [the Partition Problem](http://en.wikipedia.org/wiki/Partition_problem); the Partition Problem is basically about splitting a set of numbers into two smaller sets of equal size.
To visualize it, the book contained the following picture:

It shows how, given an input of *k* boxes, each with height *n*, you can create two stacks of boxes, each stack with half the height of the original stack (well, in this diagram, pile.)
If you were to write a function to do this, it might look something like:
```
>>> k = [3,4,3,1,2,3,3,2,1]
[3,4,3,1,2,3,3,2,1]
>>> partitionSolve(k)
[ [3,3,2,3], [1,4,2,3,1] ]
>>> sum(partitionSolve(k)[0]) == sum(partitionSolve(k)[1])
True
```
But this only solves for two stacks! What if we wanted to split the input into three equal stacks? Then we'd have to write another function!
```
>>> partitionSolveThree([3,4,3,1,2,3,3,2])
[ [3,4], [3,1,3], [2,3,2] ]
```
In fact, I want to be able to solve for *N* stacks:
```
>>> partitionSolveN(3, [2,1,1,2,3,1,2])
[ [2,2], [1,1,2], [3,1] ]
>>> partitionSolveN(4, [2,1,1,2,3,1,2])
[ [2,1], [1,2], [3], [1,2] ]
```
But, I'm lazy, and I don't want to have to start some language's shell every time I want to use this function, so I decide to create a program to do it for me.
The problem is, I can't figure out an efficient way to do it!
# Your Task
Design a program which can solve the above problem, for any number *N*.
Your program should take input via stdin, and print its output to stdout.
Example:
```
C:\> echo 2343123321| solution.X
3323
14231
```
Input will be a single string of digits; the first specifying how many stacks the code should be broken into, and the rest represent the input stack. All numbers will be single digit, so you can think of it as a list delimited by empty strings (`''`).
The first character of input will be the *N* to solve for, so if the first character is a 6 your program will be expected to output 6 valid subsets, or an error. This number will always be between 1 and 9.
The rest of the input is the starting list, from which the sublists must be created. Each digit in here can be between 1 and 9, and they must all be used once and only once in the outputted sublists.
Output should then be a new-line delimited list of your output stacks, each stack should just be a sequence of the numbers within it.
Another few examples:
```
C:\> echo 334323321| solution.X
34
313
232
C:\> echo 3912743471352| solution.X
121372
97
4453
C:\> echo 92| solution.X
forty-two
```
If the given input has no solution, your program can print any error message it wants, as long as there are no digits in the error message.
Fewest number of bytes wins! Good luck!
[Answer]
# Python 2, ~~321~~ ~~317~~ ~~321~~ 319
```
import itertools as l
t=raw_input();e=0;g=l.permutations(int(k)for k in t[1:])
try:
while not e:
a=list(g.next());c=[sum(a[:i+1])for i in range(len(a))];s=c[-1];d=int(t[0]);f=s/d;assert f*d==s;r=range(f,s,f);e=set(r)<=set(c);b=[`k`for k in a]
for k in r[::-1]:b.insert(c.index(k)+1,'\n')
print ''.join(b)
except:''
```
Some examples:
```
echo 43 | python part.py
echo 3912743471352 | python part.py
9124
7342
7135
echo 342137586 | python part.py
426
138
75
```
Thanks to [theonlygusti](https://codegolf.stackexchange.com/users/36219/theonlygusti) for fixing the stdin input, and shaving off some chars and to [Maltysen](https://codegolf.stackexchange.com/users/31343/maltysen) for pointing out a typo.
[Answer]
# Pyth - 73 69 bytes
**Updated to match Pyth 4.0**
Yay! Finally translated it. Likely huge room for golfing., but will be working on explanation. Finished explanation.
```
KmsdzJ.(KZFN*.pK.cUKtJ=km?:hNhdedgedZ>hNhdC,+]ZeN+eN]_1Iql{msdk1kB)EG
```
Uses brute force solution with a lot of help from itertools. Not really looking to golf any further because will be translating to Pyth.
```
from itertools import*
K=list(map(int,input()))
J=K.pop(0)
for N in product(permutations(K),combinations(range(len(K)),J-1)):
k=[N[0][s:e]if e>=0 else N[0][s:]for s,e in zip((0,)+N[1],N[1]+(-1,))]
d=list(map(sum,k))
if d.count(d[0])==J:print(k);break
else:print()
```
It takes cartesian product to make all possible options of arrangements of input (uses perms) and all possible slices (uses combs). Then it checks and breaks on the first one and then prints.
```
K K=
m Map
sd Convert to integer
z Over the input
J J=
.( Pop from index
K K
Z Index zero
FN For N in
* Cartesian Product
.p Permutations full length
K K
.c Combinations no replace
UK Of range(len(K))
tJ Length J-1
=k Set k=
m Map with d as loop var
? gedZ If d>=0 (hack to get around Pyth has no None slice index)
:hN Slice N[0]
hd From k[0]
ed Till k[-1]
>hN Else slice N[0]
hd From k[0] till end
C, Zip (This makes the partitioning index pairs)
+]ZeN [0]+N[-1]
+en]_1 N[-1]+[-1] (Again, the -1 is for the hack)
Iql{ 1 If the set has len 1
msdk Map sum to k
k Implicitly print k
B Break and implicitly close out if
) Close out for loop
E If we didn't break (Uses for-else construct in Python)
G Print alphabet as error message
```
Works on all the inputs, except it froze my computer on the really big one but should in theory.
**Note:** does not work on the online interpreter because it has a timeout.
Now the set thing give both a speed *and* bytes improvement so you can run it online: [Try it here](http://pyth.herokuapp.com/?code=KmsdzJ.(KZFN*.pK.cUKtJ%3Dkm%3F%3AhNhdedgedZ%3EhNhdC%2C%2B%5DZeN%2BeN%5D_1Iql%7Bmsdk1kB)EG&input=334323321).
[Answer]
# Mathematica 154
```
f@n_:=Module[{g=IntegerDigits@n,d,a,r,s},d=First@g;a=Rest@g;
FirstCase[Subsets[Cases[Subsets@a,x_/;Tr@x==Tr@a/d],{d}],x_/;Sort[Join@@x]==Sort@a]];
f@Input[]
```
Standard input is entered by
```
f@Input[]
```
---
**Examples with predetermined inputs**:
```
f[334323321]
```
>
> {{3, 4}, {3, 3, 1}, {3, 2, 2}}
>
>
>
---
```
f[3912743471352]
```
>
> {{9, 7}, {7, 4, 5}, {1, 2, 4, 3, 1, 3, 2}}
>
>
>
---
```
f[342137586]
```
>
> {{4, 8}, {7, 5}, {2, 1, 3, 6}}
>
>
>
---
```
f[42112312]
```
>
> {{3}, {2, 1}, {2, 1}, {2, 1}}
>
>
>
[Answer]
# Pyth, 72 Bytes
Such a close byte count to [the other Pyth](https://codegolf.stackexchange.com/a/48588/15203), but a completely different approach.
```
KmvdzJ.(K0=H/sKJ=KSK=JlKWK=NK=G])Fd_NIgHs+dGaG.(KxKdIqHsGaYGB;?YqJsmldYb
```
[Try it here](https://pyth.herokuapp.com/?code=KmvdzJ.(K0AHK%2C%2FsKJSK%3DJlKWK%3DNK%3DG%5D)Fd_NIgHs%2BdGaG.(KxKdIqHsGaYGB%3B%3FYqJsmldYb&input=3912743471352).
It is roughly equal to the following program, which was made through rethinking and slimming down my last answer (my last program didn't guarantee an answer):
### Python 2, 242 Bytes
```
x=list(map(int,raw_input()))
y,S,b=x.pop(0),sum,[]
x.sort(reverse=1)
j,z,c=S(x)/y,len(x),0
while x:
k,a=x[:],[]
for i in k:
if j>=S(a)+i:a.append(x.pop(x.index(i)))
if S(a)==j:b.append(a);c+=len(a)
if c==z:
for o in b:print o
else:print
```
---
### Basic idea for solving without using permutations
* Each stack must add up to `k = sum of all boxes / n`
* When the list of all boxes is sorted from greatest to least, you can iterate over that list, adding/popping boxes to a stack so that `k >= stack` remains true. Once `stack == k`, that stack is 'finished' and can be added to a list of the solutions. It is clear why this works when you examine the solution it produces:
```
input: 3912643473522
output: [[9, 7], [6, 5, 4, 1], [4, 3, 3, 2, 2, 2]]
```
* At the end, check if `# of boxes in all solution stacks == length of input - 1` to see if all boxes were used, if not the input has no solution.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ć.Œʒ€SOË}н»
```
[Try it online](https://tio.run/##ASEA3v9vc2FiaWX//8SHLsWSypLigqxTT8OLfdC9wrv//zIzNDE) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6mj5F9aAuHoVP4/0q53dNKpSY@a1gT7H@6uvbD30O7/Ooe22f@PNjI2MdQBEsaGRsbGRoY6xjCmDpAHZBga6ZjAGMaWhkbmJsYm5obGpkY6lkaxAA).
**Explanation:**
```
ć # Extract the head of the (implicit) input;
# pushing remainder and head separately to the stack
# i.e. 2341 → 341 and 2
.Œ # Get all possible combinations of head amount of parts from the remainder
# → [[341,""],[34,1],[31,4],[3,41],[41,3],[4,31],[1,34],["",341]]
ʒ # Filter this list of parts by:
€S # Convert the two parts to lists of digits
# i.e. [341,""] → [[3,4,1],[]]
# i.e. [31,4] → [[3,1],[4]]
O # Take the sum of each digit-list
# → [8,0]
# → [4,4]
Ë # Check if both are equal
# → 0 (falsey)
# → 1 (truthy)
}н # After the filter: leave the first result
# i.e. [[31,4],[4,31]] → [31,4]
» # Join it by newlines (which is output implicitly as result)
# → "31\n4"
```
If a list was allowed as output, it could have been **9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** instead:
```
ć.Œ.Δ€SOË
```
[Try it online](https://tio.run/##yy9OTMpM/f//SLve0Ul656Y8aloT7H@4@/9/I2MTQwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/I@16RyfpnZvyqGlNsP/h7v@1Ov@jjYxNDHWAhLGhkbGxkaGOMYypA@QBGYZGOiYwhrGloZG5ibGJuaGxqZGOpVEsAA).
Where the `.Δ` is a builtin for find\_first, (which could have been used in the original 11-byter as well for the same byte-count, but filter `ʒ` with leave first `н` apparently is slightly faster for the given test cases).
] |
[Question]
[
For the purposes of this challenge, let's define a cyclic number as an integer that passes the basic part of [Midy's Theorem](http://en.wikipedia.org/wiki/Midy%27s_theorem), but not necessarily the extended theorem. This means:
>
> the digits in the second half of the ~~repeating decimal period are~~ [integer is] the 9s complement of the corresponding digits in its first half
>
>
>
In other words,
`142857` is a cyclic number because `142 + 857 = 999` and `13358664` is a cylic number because `1335 + 8664 = 9999`.
## The Challenge
Given an even-digit integer n > 10, determine whether n is a cyclic number by our definition. If it is, return something truthy. If it's not, return the closest cyclic number to n.
Example:
```
> 18
True
> 133249
132867
```
This is code golf, so shortest code wins.
[Answer]
# [Clip](http://esolangs.org/wiki/Clip), 59
```
[vr[p[q?<a-vpa-vqp]q]}}f[d[q=qc$+n#q$dn+q$d'9]/l$d2},T*v2]n
```
Straightforward approach. It makes a list of all numbers, where if you the the two halves the result is all 9's, and finds which one is closest to the input. If the input is a cyclic number, it will be printed, which is allowed because all non-zero numbers are truthy.
## Explanation:
```
[v .- A function of v (which will be set to the input) -.
r .- Reduce, to find the best answer -.
[p[q .- A function of p, q -.
? .- If -.
< .- Compare -.
a-vp .- the distance between one number and the input -.
a-vq .- the distance between another number and the input-.
p]q] .- Return the closest -.
}}
f .- Filter, to find solutions -.
[d .- A function of d (each possible value) -.
[q .- Set q as... (half of length of d) -.
=q .- Only if q equals... -.
c .- the count, within... -.
$ .- the string form of... -.
+ .- the sum of... -.
n#q$d.- the first q digits of d -.
n+q$d.- the last q digits of d -.
'9 .- the digit 9 -.
[/l$d2 .- half of length of d -.
}
,T*v2 .- the numbers from 10 to double v -.
]n .- With v set as the numeric value of... -.
.-implicit-. .- the first line of input -.
```
This passes the test-cases, though I'm not certain that the range is wide enough. If not, it can be increased by changing the `*v2` to `*v9` or greater.
Unfortunately, there's a bug in the interpreter's `s` sort-by function, so I had to use waste a few bytes using the `r` reduce function instead.
[Answer]
# Python 2, 94 characters
```
def r(n):
i=0;s=1
while 1:
n+=i*s;M=10**(len(str(n))/2);i+=1;s=-s
if n/M+n%M==M-1:return n
```
Note: the last two lines use a tab character for indentation.
Given `n`, this checks numbers for cyclicity in the following order: `n`, `n-1`, `n+1`, `n-2`, `n+2`, etc... If `n` is a cyclic number, it returns `n` (which is a truthy value). If it isn't, it returns the closest one that is.
[Answer]
# Pyth, 39
```
Jf!-`sjT^10/l`T2\9UyQ|}QJho%l`N2o^-QZ2J
```
... or
**A version that might be against the rules: 33**
```
ho%l`N2o^-QZ2f!-`sjT^10/l`T2\9UyQ
```
[Try it online here.](https://pyth.herokuapp.com/)
The rules-breaking version just echoes the number if it is cyclic.
I believe this gives the correct output for all values, if you find something in my reasoning that is flawed, please tell me ;)
This begins by generating a list of all of the cyclic numbers from 0 to twice the input. This will obviously include each cyclic number less than the input, and includes the next cyclic number. You actually only need to add `10 ^ (digits_in_input / 2)` to ensure this, but doubling takes fewer characters.
The numbers are found to be cyclic by converting them into base `10 ^ (digits_in_input / 2)` and then summing the digits of this number together. All `9`s are then removed from this list, and so if the list is empty the number is cyclic.
If the input is a member of this list, `True` is printed, otherwise the list is sorted, first by `(input - value) ^ 2` and then by if the number contains an even or odd number of digits (sorting evens as less). Since pyth uses stable sorts, this is equivalent to sorting by both at once. Then the first number in this list is the nearest cyclic tag number.
This algorithm is fairly naive, but I believe it catches everything. I particularly think that the sorting could be golfed a lot.
[Answer]
# Python 2, 73
```
n=input()
e=10**(len(`n`)/2)-1
N=n/e+n%e*2/e;N-=N>e+1
print n==N*e or N*e
```
A six-digit pseudo-cyclic number like `637362` is pseudo-cyclic exactly if it's a multiple of `999`, except for `999999`. So, we're looking for the multiple of `999` nearest to the input `n`. In general, replace `999` with `e`, which is one less that `10**(num_digits/2)`.
The nearest multiple below can `n` be found with integer division as `n/e*e`. We check whether to round up with `n%e*2/e`, which is `1` if `n%e` is closer to `e`, and `0` if it's closer to `0`. In the latter case, we add `e`. We also handle the `999999` case by subtract if `N` is too large.
Finally, before printing, we check if the original number was a multiple of `e` and thus already pseudo-cyclic.
[Answer]
**Ruby, 79 chars**
```
p->n{t=n.to_s;s=t.size/2;u=t[0...s];v=t[s..-1];u.to_i+v.to_i==('9'*s).to_i}.(13358664)
```
[Answer]
# Bash + coreutils, 118
```
m=$[10**(${#1}/2-1)]
jot -w%dd$1-n32Ppc $[m*9] $m$[m*9-1] $[(m*10-1)*m*10]|dc|tr -d -|sort -n|sed -n "/$1/!s/.* //p;q"
```
Calculates all cyclic numbers with the same number of digits as the input number, then uses `sort` to find the closest. In true unix fashion, nothing is printed for the "true" / "success" case, but the nearest cyclic number is printed if the input is not cyclic.
[Answer]
## Python 3
209 hardcoded or 200 with user input
```
x = [142857, 13358664, 18, 133249]
i=int
def g(x):
a,b=str(x),i(len(str(x))/2)
return (lambda d,c:i(d)+i(c)==10**len(d)-1 and x or g(i(d+c)-1))(a[:b],a[b:])
for y in x:print((g(y)==y and True or g(y)))
```
Output:
```
True
True
True
132867
```
The implementation here is fairly simple. I see other entries are quite shorter; so I'm not aiming to win here, just wanted to try. This code-golfing is still very new to me.
**Amendment**
Having user input is simple; with one exception. For some numbers the function will throw a `RuntimeError` if the recursion depth hits its limit while trying to obtain a valid number counting down. That means any reasonable programmer should eat this error apporpriately and simply return `False`. The exception also catches any number below 27.
```
i=int
def g(x):
a,b=str(x),i(len(str(x))/2)
try:return(lambda d,c:i(d)+i(c)==10**len(d)-1 and x or g(i(d+c)-1))(a[:b],a[b:])
except:return False
y=input();print((g(y)==y and True or g(y)))
```
**Amendment II**
Actually, now that I think of it, the user input should take less time when the output is `not True`:
```
y=input();z=g(y);print((z==y and True or z))
```
] |
[Question]
[
The goal of this codegolf is evaluating the cumulative distribution function of the [student-t probability distribution](https://en.wikipedia.org/wiki/Student's_t-distribution). This is not trivial since there is no closed form and the function is dependent of two variables `v` and `x`. The distribution function is

For getting the CDF you could integrate this function from `-inf` to `x`. As you can see the evaluation of this function relies much on integration as you'd also have to evaluate nontrivial values of the gamma function.
## Details
You can can write a program or function that accepts a two numbers `x`and `v` as input, where `x` is the position (must at least accept floats from -10 upto 10) at which the CDF is evaluated and `v` is the number of degrees of freedom. `v` is a positive integer (range `1` upto `1450`) but it must be possible to set it to *infinity* (for `v=inf` the student-t distribution is equal to the normal distribution). But you can specify that e.g. `v = -1` should denote infinity. The output consists must be a number between 0 and 1 and must have an accuracy of at least *4 decimal places*.
If your language does not support runtime inputs or arguments on program call you may assume that both arguments are stored in variables (or another 'memory unit')
## Restrictions
You may not use special functions like the gamma function or probability distribution functions as well as numerical integration functions or libraries (as long as you do not include their source in your code which counts for the score) etc. The idea is using only basic math functions. I tried to make a list of what I consider as 'basic' but there might be others I forgot - if so please comment.
Explicitly ***allowed*** are
```
+ - / *
% (modulo)
! (factorial for integers only)
&& || xor != e.t.c. (logical operators)
<< >> ^ e.t.c. (bitshift and bitwise operators)
** pow (powerfunction for floats like a^b including sqrt or and other roots)
sin cos tan arcsin arccos arctan arctan2
ln lb log(a,b)
rand() (generating pseudorandom numbers of UNIFORM distribution)
```
## Scoring
Lowest number of bytes wins.
## Entry
Please explain how your code works.
Please show the output of your program for at least 5 different arguments. Among those should be the following three. For your own values please also provide 'exact' values (like from wolframalpha or what ever you prefer).
```
x = 0 v= (any) (should return 0.5000)
x = 3.078 v= 1 (should return 0.9000
x = 2.5 v= 23 (should return 0.9900)
```
If possible, it would be great if you could provide some fancy plots of the values calculated with your program (the code for plotting does not count for the score).
(from Wikipedia):

[Answer]
# BBC BASIC, 155 ASCII characters, tokenised filesize 140
Download emulator at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html>
```
a=1s=.000003INPUTx,v
IFv<1v=9999
FORw=1TOv-1a=w/a
NEXTb=SGN(x)*s*a/SQR(v)IFv MOD2b=b/PI ELSEb=b/2
f=.5FORz=0TOABS(x)STEPs
f+=b/(1+z*z/v)^(v/2+.5)NEXTPRINTf
```
The code is in two parts. The first calculates the coefficient that is independent of x. and stores it in `b`. The algorithm is a bit like a continued fraction, but a mathematician would probably call it a simple quotient of two products. It's based on a formula from the Wikipedia page in the question, which is similar to a factorial but has the product `(v-1)(v-3)...` divided by the product `(v-2)(v-4)...` This is possible because we are only interested in half-integral values of the gamma function (arbitrary values of the gamma function would be a lot harder.) Using this formula we never have to calculate either gamma function, so we avoid large numbers. The largest intermediate value is approximately the square root of `v`.
The second is a straightforward integration from 0 to x by summation. It is known that f(0) is 0.5 so we start from there and work outwards. the sign and magnitude of `b` are modified before the loop, in order to be able to give the final answer directly.
**Pretty version, ungolfed**
This contains a few extra lines to add colour and to plot the data. The range x=0 to endpoint, and f(x)=0.5 to 1 is shown. Also `v` is modified to `2^v` to be able to show the full range of v values without exceeding the limits on colour. In order to speed the drawing up, there are two less digits in `s` than in the golfed version. Even so, there is only one discrepancy when compared with <http://www.wolframalpha.com/input/?i=student+t-distribution+probability>: `0.8130575` rounds up to 0.8131. The golfed version give the correct answer `(0.8130)` for this and all the other cases below.
```
a=1 :REM accumulator for gamma series
s=.0001 :REM step size for x integration
INPUTx,v
IFv<1 v=9999 :REM if v<1, set v to a value that gives results indistinguishable from infinity
GCOLv :REM pick a colour
v=2^v :REM for the pretty version, modify v to 2^v
FORw=1TOv-1
a=w/a :REM calculate series as per Wikipedia
NEXT
b=a/SQR(v) :REM divide a by the necessary values...
IFv MOD2 b=b/PI ELSE b=b/2 :REM to give the coefficient, per Wikipedia
b*=SGN(x)*s :REM modify according to sign and step size
f=.5 :REM initialise f(x)=.5 at x=0
FORz=0TO ABS(x) STEPs
f+=b/(1+z*z/v)^(v/2+.5) :REM perform integration as simple "barchart" sum
PLOT69,z*100+200,(f-.5)*1600 :REM plot a point
NEXT
PRINT f
```


] |
[Question]
[
Your job is to solve this chess-related game.
The setup of the game is a 7x7 tile grid, you start on a random tile and you have to hop on each tile, until you hopped on all 49 tiles.
Top left corner is (0,0)
**Rules:**
* you can hop on each tile once.
* the only move allowed in the game is to hop two tiles horizontally and one tiles vertically, or two tiles vertically and one tiles horizontally, like a knight in a chess game.
* your input should be a tuple representing the coordinates of the starting tile (stdin, file, what you prefer).
* your output a list of tuples, representing the coordinates of each hop. If there's no valid combinations, return an empty list (same as above, any output is ok).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 39 bytes
```
7 7{3::0⋄(⍋,(⊢⊃⍨⍵⍳⍨⊃∘⍸¨∘=)¯1⌂kt⍺)⊇,⍳⍺}⊂
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXECWc6R6cWJOifqj7pbUvMSknNRgR58QIAcoFeyqF@rs66KelF@RmZeukJ@n/t9YwaTa2MrKAKhA41Fvt47Go65Fj7qaH/WueNS79VHvZhADyO2Y8ah3x6EVQNpW89B6w0c9Tdklj3p3aT7qatcBq9pV@6ir6X8a0BGPevsg7ulqPrTe@FHbRJDFQc5AMsTDM/h/moKBggEXiDRUUHjUO1fBL1@hOD@ntCQzP0@huCSxqATktIzUolSwImMgaahgAAA "APL (Dyalog Extended) – Try It Online")
A version provided by @Adám.
Dyalog Extended has a shortcut to the `dfns` library `⌂`, and a few convenience functions e.g. monadic `=` which is equivalent to `0∘=`, and dyadic `⊇` for multiple indexing. Unfortunately an inner assignment is buggy, so we use a tacit inner function to reference the value of `¯1⌂kt⍺` twice. Otherwise we'd have a **38 byte** solution:
```
7 7{3::0⋄(⍋,w⊃⍨⍵⍳⍨⊃∘⍸¨=w←¯1⌂kt⍺)⊇,⍳⍺}⊂
```
### How the inner tacit function `(⊢⊃⍨⍵⍳⍨⊃∘⍸¨∘=)` works
```
This tacit function has 5 terms: `⊢` `⊃⍨` `⍵` `⍳⍨` `⊃∘⍸¨∘=`
A tacit function is grouped by 3 terms from the right:
⊢ ⊃⍨ (⍵ ⍳⍨ ⊃∘⍸¨∘=)
A group of 3 terms is interpreted as follows:
(f g h)w → (f w) g (h w) ⍝ f, g, h are functions
(A g h)w → (A ) g (h w) ⍝ A is an array
Then we can interpret the above tacit function as
(⊢ ⊃⍨ (⍵ ⍳⍨ ⊃∘⍸¨∘=))w
→ (⊢ w) ⊃⍨ (⍵ ⍳⍨ (⊃∘⍸¨∘= w)) ⍝ Expand tacit function
→ w ⊃⍨ ⍵ ⍳⍨ ⊃∘⍸¨∘= w ⍝ ⊢ is identity function; simplify parens
→ w ⊃⍨ ⍵ ⍳⍨ ⊃∘⍸¨ = w ⍝ (f∘g)w simply expands to f g w
So the code `(⊢⊃⍨⍵⍳⍨⊃∘⍸¨∘=)w` is equivalent to `w⊃⍨⍵⍳⍨⊃∘⍸¨=w`.
```
---
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~53~~ 49 bytes
```
⎕CY'dfns'
7 7{3::0⋄(,⍳⍺)[⍋,w⊃⍨⍵⍳⍨⊃∘⍸¨0=w←¯1kt⍺]}⊂
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXECWc6R6cWJOifqj7pbUvMSknNRgR58QIAcoFeyqF@rs66KelF@RmZeukJ@n/h@iISUtr1idy1jBpNrYysoAqFhD51Hv5ke9uzSjH/V265Q/6mp@1LviUe9WsOgKELdjxqPeHYdWGNiWAy0@tN4wuwSoPLb2UVfT/zSgyKPePoirupoPrTd@1DYRZH2QM5AM8fAM/p@mYKBgwAUiDRUUHvXOVfDLVyjOzyktyczPUyguSSwqATkwI7UoFazIGEgaKhgAAA "APL (Dyalog Unicode) – Try It Online")
Golfed 4 bytes by extracting some terms out of the dfn using a tacit form.
---
## Original submission: [APL (Dyalog Unicode)](https://www.dyalog.com/), 53 bytes
```
⎕CY'dfns'
{3::0⋄(,⍳7 7)[⍋,w⊃⍨(⊃∘⍸¨0=w←¯1 kt 7 7)⍳⊂⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXECWc6R6cWJOifqj7pbUvMSknNRgR58QIAcoFeyqF@rs66KelF@RmZeukJ@n/h@iISUtr1idq9rYysoAqFJD51HvZmMFE83oR73dOuWPupof9a7QAFEdMx717ji0wsC2HGjbofWGCtklCiCFQPWPupoe9W6Nrf2fBpR61NsHcVNX86H1xo/aJoIsD3IGkiEensH/0xQMFAy4QKShgsKj3rkKfvkKxfk5pSWZ@XkKxSWJRSUg52WkFqWCFRkDSUMFAwA "APL (Dyalog Unicode) – Try It Online")
Because we've got a language that has a Knight's tour solver built in.
Since `¯1 kt 7 7` tries to find all solutions, it's infeasible to actually run the code as-is. For demonstration purposes, the TIO link uses 3x4 board instead.
### How it works
The function [`dfns.kt`](http://dfns.dyalog.com/n_kt.htm) finds a (possibly open) Knight's tour, where the right argument is the board's dimensions, and the optional left argument is the number of solutions to find. Giving `-1` on the left causes the function to search all possible solutions.
```
⎕CY'dfns' ⍝ Import the 'dfns' workspace
{3::0⋄(,⍳7 7)[⍋,w⊃⍨(⊃∘⍸¨0=w←¯1 kt 7 7)⍳⊂⍵]} ⍝ ⍵←starting coordinates
w←¯1 kt 7 7 ⍝ Find ALL solutions of 7x7 knight's tour
(⊃∘⍸¨0= ) ⍝ Extract the starting coordinates from each solution
⍳⊂⍵ ⍝ Find the index of the solution that starts at ⍵
,w⊃⍨ ⍝ Fetch the solution and flatten it
(,⍳7 7) ⍝ Take the flattened list of coordinates on 7x7 board
[⍋ ] ⍝ Sort the coordinates by flattened solution
3::0⋄ ⍝ If there's no solution starting with ⍵,
⍝ catch the Index Error and return 0 instead
```
---
## Every black square on 7x7 board can be the starting location of a Knight's tour.
The following isn't directly related to the code above, but nevertheless here is a proof by example.
### Starting at (0,0), Ending at (5,1)
```
0 11 22 45 2 13 24
21 46 1 12 23 44 3
10 27 34 39 36 25 14
47 20 37 26 33 4 43
28 9 40 35 38 15 32
19 48 7 30 17 42 5
8 29 18 41 6 31 16
```
### Starting at (1,3), Ending at (6,4)
```
20 27 10 33 44 1 12
9 32 21 0 11 34 45
26 19 28 43 40 13 2
31 8 41 22 29 46 35
18 25 30 39 42 3 14
7 38 23 16 5 36 47
24 17 6 37 48 15 4
```
### Starting at (2,2), Ending at (3,3)
```
30 19 40 3 28 17 38
41 2 29 18 39 4 27
20 31 0 13 10 37 16
1 42 11 48 15 26 5
32 21 14 9 12 47 36
43 8 23 34 45 6 25
22 33 44 7 24 35 46
```
By swapping heads and tails, reflection, and rotation, all black squares can be the starting point of some Knight's tour.
I found these three tours by splitting the board into four groups that can form a continuous loop:
```
O O O . O O O | . . . O . . . | . . . . . . . | . . . . . . .
O . O O O . O | . O . . . O . | . . . . . . . | . . . . . . .
O O . . . O O | . . . . . . . | . . O O O . . | . . . . . . .
. O . . . O . | O . . . . . O | . . O . O . . | . . . O . . .
O O . . . O O | . . . . . . . | . . O O O . . | . . . . . . .
O . O O O . O | . O . . . O . | . . . . . . . | . . . . . . .
O O O . O O O | . . . O . . . | . . . . . . . | . . . . . . .
```
and breaking and gluing the chains whenever needed. It's kind of a heuristic, so it would be usually shorter to hardcode the three boards or just run naive DFS.
[Answer]
# Python 3 - ~~272~~ 263
Since this is a code-golf, this is built to be shorter in code, as opposed to faster in execution. Note that if you want solutions that will run in practical amounts of time, that almost requires some kind of dynamic programming, using a hash in addition to a list, and probably even some kind of heuristic. Otherwise, an exhaustive backtracking search may potentially take a very long time. It would be interesting to see a separate contest for the *fastest* knight's tour finder for all mxn boards for m0<=m<=M, n0<=n<=N
Anyway, here is the code. It expects an input as a tuple, i.e. (0,0)
```
p=[eval(input())]
def k():
if 49==len(p):return 1
n=[(p[-1][0]+x,p[-1][1]+y) for x in range(-2,3)for y in range(-2,3)if(abs(x)+abs(y)==3)]
for z in n:
if(min(z)<0 or max(z)>6 or z in p):continue
p.append(z)
if(k()):return 1
p.remove(z)
if(k()):print(p)
```
Thanks to Fry for the golfing tips!
[Answer]
# Python 3 - 241 chars
This will work most of the time, if you live long enough to see the result...
It works by randomly reordering a list of all coordinates until it gets the right answer. If it takes more than **9\*10^99** loops, it assumes that there is no answer. (It will be right the vast majority of the time, since the probability of getting the right order is roughly **1 in 6\*10^63**).
N.B. Yes, I know that this is not really a valid answer.
```
import random
l=[(x%7,x//7)for x in range(49)]
s=eval(input())
v=lambda x:all(abs((x[i][0]-x[i+1][0])*(x[i][1]-x[i+1][1]))==2 for i in range(len(x)-1))
t=0
while not all(v(l),l[0]==s,t<9e99):
random.shuffle(l);t+=1
print(l if t<9e99 else[])
```
] |
[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/18535/edit).
Closed 7 years ago.
[Improve this question](/posts/18535/edit)
## Challenge
The goal of this challenge is to take a radical and convert it to a reduced and entire radical, and a real number. You do not have to convert it to all 3, however, you will get bonus points for converting it to 2 or 3 of them. You will also get bonus points if your code works not just with square roots. How the input works is your choice. You don't have to parse the input so you could just have it as a function. If your unable to output the root symbol (√) then you could output it as `sqrt(x)` or `cuberoot(x)`. You could also use a superscript (²√) for the index of the radical.
## Rules
* If you just output one of the 3 options, then you can't just output it without converting it (ie: if the input is `√125` then you can't just output `√125` back).
* The entire radical must have no co-efficient.
* The mixed radical must have a coefficient (if there is no coefficient, then it should be `1`).
* The real number (or result of the radical) should have as many decimals as possible.
## Example
Here's an example output for the square root of 125 (√125):
```
Entire radical: √125
Mixed radical: 5√5
Real number: 11.18033988749895
```
## Scoring
* 10% off your score for outputting 2 of either an entire radical, mixed radical, or real number.
* 30% off your score for outputting all 3 (entire radical, mixed radical, and real number).
* 30% off your score for working with a radical with any index
## Winner
The person with the shortest code length wins. Good luck!
[Answer]
# APL, 77 × .7² = 37.7
```
{(a b)←×⌿(∪p)*[1]c,⍪e-⍺×c←⌊⍺÷⍨e←∪⍦p←π⍵⋄q←⍺/⍨⍺≠2⋄∊¨⍕¨¨⍪(q'√'⍵)(a'×'q'√'b),⍺√⍵}
```
Nars2000. Could be golfed some more, for instance by printing worse output, but I'm being lazy.
Also, pretty output is pretty.
**Ungolfed**
```
{
p←π⍵ ⍝ prime factors of the radical argument ⍵
u←∪p ⍝ unique prime factors
e←∪⍦u ⍝ exponents of those factors (so that ⍵=u*e)
r←⌊e÷⍺ ⍝ u's exponents for the reduced radical factor
f←×/u*r ⍝ reduced radical factor
a←×/u*e-⍺×r ⍝ reduced radical argument
i←⍺/⍨⍺≠2 ⍝ index, unless it's 2 (AH THE DECADENCE, I CAN WASTE SO MUCH)
o←(i'√'⍵)(f'×'i'√'a),⍺√⍵ ⍝ the three expressions to output
∊¨⍕¨¨⍪o ⍝ return them as a table without spaces
}
```
**Examples**
```
2 f 125
√125
5×√5
11.18033989
2 f 1440
√1440
12×√10
37.94733192
3 f 1440
3√1440
2×3√180
11.29243235
2 f 987654321
√987654321
51×√379721
31426.96805
```
[Answer]
## C (314)
```
n,d;main(i){scanf("%d %d",&n,&d);int val[d];for(;pow(i,n)<=d;i++)val[i]=pow(i,n);printf("Entire radical: %drt(%d)\n",n,d);for(i--;i>0;i--)if(d%val[i]==0){printf("Mixed radical: %d*%drt(%d)\n",i,n,d/val[i]);break;}double v,x=1.5,a=d;do{v=(a/pow(x,n-1)-x)/n;x+=v;}while(abs(v)>=1E-9);printf("Real number: %lf\n",x);}
```
Here it is with whitespace.
```
n,d;
main(i){
scanf("%d %d",&n,&d);
int val[d];
for(;pow(i,n)<=d;i++)
val[i]=pow(i,n);
printf("Entire Radical: %d*rt(%d)\n",n,d);
for (i--;i>0;i--)
if (d%val[i]==0){
printf("Mixed Radical: %d*%drt(%d)\n", i, n, d/val[i]);
break;}
double v,x=1.5,a=d;
do{
v=(a/pow(x,n-1)-x)/n;
x+=v;
}while(abs(v)>=1E-9);
printf("Real number: %lf\n", x);
}
```
Input:
```
2 125
```
Output:
```
Entire radical: 2rt(125)
Mixed radical: 5*2rt(5)
Real number: 11.180340
```
Input:
```
3 125
```
Output:
```
Entire radical: 3rt(125)
Mixed radical: 5*3rt(1)
Real number: 5.000000
```
This isn't perfect, the root calculation will not work for all input values, and the chosen guess value is not random. It takes the whole value of the radical as input (see above).
[Answer]
# C - 222 × 70% × 70% ≆ 108.78
```
p,c=1,i,n=2,t;main(){scanf("%d %d",&i,&p);printf("Entire radical: rt%d(%d)\nReal number: %.16
lf\n",i,p,pow(p,1.0l/i));for(;n++<p;t=0){for(;!(p%n);t++)p/=n;c*=pow(n,t/i);p*=pow(n,t%i);}pr
intf("Mixed root: %drt%d(%d)",c,i,p);}
```
Has some problems with rounding, but is otherwise fine.
[Answer]
# Ruby, 199 chars \* 70% \* 70% = 97.51
I'm not good at mathstuffs. :P
```
a,b=gets.split.map &:to_i
c=b
[*2..o=b].map{|x|x**a}.map{|x|o=c/=x if c%x==0}until o==b
puts"Entire radical: #{a}rt#{b}
Mixed radical: #{((b/c)**(1.0/a)).round}*#{a}rt#{c}
Real number: #{b**(1.0/a)}"
```
I particularly like line 3. It's supposed to keep dividing out squares until it can't divide anymore. How I did it is that `o` is set to `b` in the beginning (conveniently tucking it into the range expression), and if a square can be divided out, `o` is set to the result (also conveniently only adding 2 more characters). Then, I used `until o==b`, so that it keeps going until `o` didn't change (meaning no squares could be divided out).
More explanations coming soon....
---
Sample runs:
```
c:\a\ruby>radicalstuffs
2 100
Entire radical: 2rt100
Mixed radical: 10.0*2rt1
Real number: 10.0
c:\a\ruby>radicalstuffs
2 125
Entire radical: 2rt125
Mixed radical: 5*2rt5
Real number: 11.180339887498949
c:\a\ruby>radicalstuffs
2 100
Entire radical: 2rt100
Mixed radical: 10*2rt1
Real number: 10.0
c:\a\ruby>radicalstuffs
5 32
Entire radical: 5rt32
Mixed radical: 2*5rt1
Real number: 2.0
c:\a\ruby>radicalstuffs
3 27
Entire radical: 3rt27
Mixed radical: 3*3rt1
Real number: 3.0
c:\a\ruby>radicalstuffs
2 99
Entire radical: 2rt99
Mixed radical: 3*2rt11
Real number: 9.9498743710662
c:\a\ruby>radicalstuffs
2 98
Entire radical: 2rt98
Mixed radical: 7*2rt2
Real number: 9.899494936611665
```
[Answer]
# Julia, 19\*0.9 = 17.1
```
julia> f(n)="$(sqrt(n)) √$n"
julia> f(125)
"11.180339887498949 √125"
```
I feel like I must not have understood the challenge. As far as I could tell there is only a small bonus for bothering to reduce the radical.
] |
[Question]
[
A twist on a [recently asked question](https://codegolf.stackexchange.com/questions/6417/generate-a-valid-equation-using-user-specified-numbers), you are given a list of operators and a result and you need to find integers which, when operated on by those operators, generate the result.
**Example 1**
input
```
+ + * / 13
```
possible output
```
4 8 2 2 4
```
which means that `4 + 8 + 2 * 2 / 4 = 13`.
More specifically, you are given a sequence of *N* operators (between 1 and 5 inclusive) and an integer result, space separated. You must print *N+1* integers, space separated, in the range 1 through 9, inclusive, that when alternated with the operators produce the result.
The operators are `+,-,*,/`. They have the natural precedence order (`*` and `/` before `+` and `-`, left associative). Divides must be integral divides, a divide with a fractional result is not allowed. Operators must appear in the order given.
Most problems will have more than one solution. Printing any of them, or any subset of them, is fine. If there is no solution, print `NO SOLUTION`.
**Example 2**
input
```
/ + - - 16
```
output
```
9 1 9 1 1
```
**Example 3**
input
```
+ 5
```
output
```
1 4
2 3
3 2
4 1
```
(or any nonempty subset of those lines)
**Example 4**
input
```
+ + 30
```
output
```
NO SOLUTION
```
**Example 5**
input
```
/ + / 3
```
output
```
6 3 5 5
```
note that `3 2 3 2` is not a solution, as `3/2+3/2=3` is true but the individual divides have fractional values.
Standard code golf, shortest answer wins.
[Answer]
## Perl, 129 160 151 chars
```
sub a{my($s,$t,$o)=splice@_,0,3;@_?map{a("$s $_","$t$o$_",@_)}1..9:
$o-eval$t||$o-eval"use integer;$t"||exit say$s}a"","","",split$",<>;say"NO SOLUTION"
```
Fun with recursion. The program exits upon finding the first valid tuple.
The `eval` has to be done twice, in and out of integer-only mode, in order to avoid invalid solutions like that given in example 5 in the description.
[Answer]
## Python (~~197 212~~ 277)
Related question, related answer. Gives the answer and an error if there is one, else prints "NO SOLUTION".
```
import re,itertools as I
e=eval;a=raw_input().split();c=1;b=len(a)
for i in I.product('123456789',repeat=b):
d=''.join(sum(zip([j+'.'for j in i],a),()))[:3*b-1]
if e(d)==int(a[-1])and all([e(n)%1==0 for n in re.findall('\d./\d.',d)]):print' '.join(i);c=0
print"NO SOLUTION"*c
```
[Answer]
### Scala 333
```
val o=args.init
val e=args.last
val n=(1 to 9)
val i=new bsh.Interpreter
def b(o:Array[String],s:String=""):Boolean={
if(s.isEmpty)n.exists(y=>b(o,s+y))else
if(o.isEmpty){
val r=i.eval(s)
if(r.toString==e){
println(s.replaceAll("[-*+/]"," "))
true}else false}else
n.exists(x=>b(o.tail,s+o(0)+x))
}
b(o)||{println("NO SOLUTION");true}
```
[Answer]
# Python 2.7, 192 190 184 181 chars
Getting rid of `itertools.product` saved 3 characters.
```
s=raw_input().split()
j=' '.join
s[-1]='=='+s[-1]
n=len(s)
x=[j(i)for i in map(str,range(10**(n-1),10**n))if'0'not in i and eval(j(map(j,zip(i,s))))]
print x and x[0]or"NO SOLUTION"
```
] |
[Question]
[
**The challenge is to manipulate strings using basic Vim-like commands**
**Input:**
* A string of text to be transformed. The input alphabet is [a-z].
* A string of legal commands
**Output:**
* The transformed string
---
There are a few ideas you should understand:
The cursor is represented as a location between 2 characters. `|` will be used to represent the cursor(s) in this explanation.
* `|foobar` - The cursor at beginning of string
* `foo|bar` - Cursor in the middle of the string
* `foobar|` - Cursor at the end of the string
A selection is a a group of characters between 2 cursors.
* `|foobar|` - The selection is `foobar`
* `|foo|bar` - The selection is `foo`
* `foo|bar|` - the selection is `bar`
* `|foobar` - The selection is the empy string (both cursors at same location)
A selection is formed from the previous cursor position and the result of the current command.
Using the command `>` on `|foo` would make the selection `|f|oo`.
Commands can be described as functions. `C<selection>` is a command that has a selection parameter. The next command provides the selection.
* `D>` deletes the character to the right of the cursor. `f|oo` `->` `f|o`
* `DNa` deletes from the cursor to the next `a` character `f|oobar` `->` `f|ar`
* Etc.
As you can see, commands "associate to the right"
* `DNa` is parsed as `(D(Na))`
* `DDNa` is parsed as `(D(D(Na)))`
* Etc.
The insert mode command `I` extends until the next command.
* `DIbar>` is parsed as `(D(Ibar))(>)`.
**These are the commands:**
* `>` - Move cursor right. `>` on `foo|bar` `->` `foob|ar`
* `<` - Move cursor left. `<` on `foo|bar` `->` `fo|obar`
* `B` - Move cursor to the beginning of the string
* `E` - Move cursor to the end of the string
* `N<char>` - Move cursor to place before next `<char>`. `Na` on `|foobar` `->` `foob|ar`
* `P<char>` - Move cursor to place after previous `<char>`. `Po` on `foobar|` `->` `foo|bar`
* `I<string>` - Enter/exit insert mode. Characters in `<string>` are inserted at the current cursor position. `<string>` extends until the next command.
The cursor is moved to end of insertion `<string>`. `Iquz` on `foo|bar` `->` `fooquz|bar`
* `D<selection>` - delete characters in `<selection>`. `f|ooba|r` `->` `f|r`. The output selection from this command is the empty string.
**Notes:**
* The cursor cannot move out of bounds. `B<<<` is the same as `B`. `Nx` is the same as `E` if no `x` can be found.
* The cursor location always starts at the beginning of the string
* The cursor should not be outputted
* Commands are always uppercase, characters are lowercase.
**Restrictions:**
* No text editor scripts like Vimscript
**Winning criteria:**
* It's code golf. Lowest character count wins.
---
**Examples:**
Input:
* `foobar`
* `>>><<>If`
Output:
* `fofobar`
---
Input:
* `foobar`
* `>>>DNEDPf`
Output:
* `f`
---
Input:
* `foobar`
* `>>>DDDDIbazD<Iquz>DPfDII`
Output:
* `far`
[Answer]
## Haskell, 371 characters
```
z l b n i=p where
p(a:c@ ~(q:u))|Just x<-a`lookup`zip"<>BEDNP"[l#c,m l#c,b#c,m b#c,z(d$k id)(\k _->k"")h(k f)c,m(n q)#u,n q#u]=x
p('I':q:c)|q>'`'=i q c;p(_:c)=f c;p""=(++).r
d f k(q:x)=k x.f q;d f k""=k"";k&x=k"".(r x++);h q=(.snd.s q);n q k=(\(a,b)->k b.(r a++)).s q
x%c=f c""x;f=z(d(:))(&)n$ \q c->f('I':c).(q:);m f=flip.f.flip;k=const;r=reverse;(#)=(.f);s=span.(/=)
```
This defines a function `%` which returns the result of applying the string of commands to the original string.
**Example usage:**
```
> "foobar" % ">>>DNEDPf"
"f"
> "foobar" % ">>>DDDDIbazD<Iquz>DPfDII"
"far"
```
] |
[Question]
[
(This code golf task is related to [Code-Golf: Lights Off!](https://codegolf.stackexchange.com/questions/1899/code-golf-lights-off). The same puzzle is used, but the task is different.)
---
## Introduction
"Lights Out" is a puzzle in which you should switch off all lights in a 5x5 grid. However, when you swap a light from on to off, or from off to on, the four adjacent lights will swap as well!
For example, consider the following grid, in which `1` stands for a light switched on and `0` stands for a light switched off:
```
00000
00000
00110
01000
00101
```
Now, if you try to turn the light at row 4, column 2 off, the resulting map will be:
```
00000
00000
01110
10100
01101
```
The goal of this game is to turn all lights off. You are allowed to switch certain lights on if that helps you to find the solution, as the adjacent ones will swap as well, which makes it possible to switch others off. This is almost always required to find the solution in fact!
## Description
Your task is to find out, given an input grid, which lights should be swapped to switch all lights off. Which ones to swap is enough information to solve the puzzle, because due to the swapping the amount does not matter (you can always do `mod 2` so it will be `0` (effectively, don't swap) or `1` (effectively, do swap)), and the order of swapping does not matter either obviously.
## Input
Input is a two dimensional array of lengths 5 (`5x5`) which represents the grid, in which:
* `0` stands for a light switched off
* `1` stands for a light switched on
## Output
Output is another two dimensional array of lengths 5 (`5x5`) which represents which lights to swap to switch all lights off in the grid, in which:
* `0` stands for 'this light should not be swapped'
* `1` stands for 'this light should be swapped'
## Winning condition
Shortest code wins.
## Hints
There are several algorithms to find the solution. There are mathematical articles about this game available on the Internet.
## Important notice
Sometimes multiple solutions are possible. It depends on the algorithm what solution you'll end up with. If you have different but correct solutions to the examples below, your entry obviously is correct as well.
## Examples
Example 1 ([video to illustrate](http://www.youtube.com/watch?v=JFLujtc6bEo)):
```
Input: Output:
00000 00000
00000 00000
00110 00000
01000 00110
00101 00001
```
Example 2 ([video to illustrate](http://www.youtube.com/watch?v=Fh18GNORApY)):
```
Input: Output:
11111 11000
11111 11011
11111 00111
11111 01110
11111 01101
```
[Answer]
## Ruby (130) (121) (113) (102)
EDIT: Saved 9 characters, thanks to Howard.
EDIT 2: Another 8 characters, courtesy of Howard.
EDIT 3: Saved 11 more characters after learning how to use Ruby's % operator for sprintf.
```
b=(0..4).map{gets.to_i 2}
32.times{|x|z=0;k=b.map{|i|x=z^i^31&(x<<1^x>>1)^z=x;'%05b'%z}
puts k if x<1}
```
Accepts 5 lines of input from stdin. Outputs all solutions as 5x5 grids as specified, though there are no extra line breaks between solutions (or between the input and the solutions).
Solutions are found by iterating through all 32 possibilities for the top row, since the top row determines the switches that must be flipped in the following rows.
Input:
```
00000
00000
00110
01000
00101
```
Output:
```
00000
00000
00000
00110
00001
01110
10101
11011
10011
01111
10101
10101
00000
10011
10100
11011
00000
11011
00110
11010
```
[Answer]
### Ruby, 133 characters
```
t=->z,v,s{v<0?z&33814345664<1&&s :t[z,v-1,s+?0]||t[z^4321<<(v+v/5),v-1,s+?1]}
puts t[32*$<.read.tr(?\n,?0).to_i(2),24,''].scan /.{5}/
```
This is a brute-force search through all possible on/off combinations. The input must be specified on stdin with exactly five lines of five 0/1 characters each and a newline after each one, e.g.:
```
> ruby lights.rb
11111
11111
11011
11111
11111
^Z
00000
11111
10001
11111
00000
```
[Answer]
## F#
brute-force,
will golf later
```
open System;
let a = Array2D.create 5 5 false
let b = Array2D.create 5 5 false
for i = 0 to 4 do
for j = 0 to 4 do
a.[i, j] <- if Console.Read() = 49 then true else false
Console.ReadLine() |> ignore
let r = Random()
while Seq.cast a |> Seq.exists id do
let x, y = r.Next(5), r.Next(5)
b.[x, y] <- not b.[x, y]
for u, v in [ x, y;
x - 1, y;
x + 1, y;
x, y - 1;
x, y + 1 ] do
try
a.[u, v] <- not a.[u, v]
with
| _ -> ()
printfn "%s" (let mutable z = ""
for i = 0 to 4 do
for j = 0 to 4 do
z <- z + (if b.[i, j] then "1" else "0")
z <- z + "\n"
z)
```
] |
[Question]
[
Pascal's Triangle is a familiar mathematical construct with many interesting properties. It is constructed by starting with a 1 on top, and generating the numbers in the next row from the sum of the number to the left and right in the row above (with implied 0's around the boundary):
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
The Triangle can be expanded into N dimensions by using the same rules. For example, the 3-D Pascal's Triangle would be a pyramid with each row being a cross-section of the pyramid, i.e., a triangle. Each triangle's entry is generated by adding the three numbers in the "row" above forming a triangle directly above that entry. An example of the first four "rows" is shown below:
```
1
1
1 1
1
2 2
1 2 1
1
3 3
3 6 3
1 3 3 1
```
The 4-D Pascal's Triangle would have a 3-D Pascal's Triangle for the cross section, and so forth.
Your task is to write a program that takes as input the dimension of the Pascal's Triange, and a row index to display. The row index starts at 0, so row 0 is `1` for every dimension. Your program should abide by the following specifications:
* Take input N = dimension number, R = row number (0-based). The input can be either command-line arguments or from stdin. N >= 2, R >= 0
* Output the R'th row in the N-dimensional Pascal's Triangle, by displaying each row or triangle on a separate line as in the above example.
* The format can vary as long as it is 'triangle-like' and obvious where each row and entry in the row belongs with respect to other rows.
Here is some sample output (I believe these are correct):
```
>./pascal 2 5
1 5 10 10 5 1
>./pascal 3 4
1
4 4
6 12 6
4 12 12 4
1 4 6 4 1
>./pascal 4 3
1
3
3 3
3
6 6
3 6 3
1
3 3
3 6 3
1 3 3 1
>./pascal 5 2
1
2
2
2 2
1
2
2 2
1
2 2
1 2 1
```
Bonus: What is the significance of each "row" in an N-dimensional Pascal's triangle? I can think of at least three interesting facts.
[Answer]
## Ruby, 181
```
def P(a)a.min<0?0:a.max<1?1:(b=a*1;t=k=0;b.map{b[k]-=1;k+=1;t+=P(b)};t)end
def d(n,a)print n>1?((0..a[-1]).map{|i|d(n-1,a+[i])};"\n"):"#{P(a)} "end
d(ARGV[0].to_i,[ARGV[1].to_i])
```
The first approach using the following recursive formula
```
P(...,-1,...) = 0
P(0,0,...,0) = 1
P(a,b,c,....) = P(a-1,b,c,...) + P(a-1,b-1,c,...) + P(a-1,b-1,c-1,...) + ...
```
and then printing row `P(R,...)`.
The output is triangle-like - for `pascal 4 2` it looks like
```
1
3
3 3
3
6 6
3 6 3
1
3 3
3 6 3
1 3 3 1
```
] |
[Question]
[
Inspired by this stack of little statues that are currently on my desk at work, given to me by my colleagues from Sri Lanka when they visited The Netherlands:
[](https://i.stack.imgur.com/sPZYQm.jpg)
This is split into two different challenges due to popular demand:
Part 1) [Determine the amount of statues](https://codegolf.stackexchange.com/q/216374/52210)
Part 2) Can the statues be stacked? (this challenge)
## Challenge 2:
**Input:**
\$statues\$: a list of multi-line strings (or character matrices), containing only the characters `\n|-#` (where the `#` can be another character of your own choice). You're also allowed to take it as a single multi-line string input and parse it into a list yourself.
```
####
## #
## ##
#### # ##
# ## ## ### ## #
# # ## ### ## # #
---- ------ -- - --
```
**Output:**
Two distinct values of your own choice indicating truthy/falsey; so yes, `1`/`0` is allowed as output in languages like Java/C# .NET and such ([relevant forbidden loophole](https://codegolf.meta.stackexchange.com/a/14110/52210)). The output will be truthy if the statues can be stacked.
**How can the statues be stacked?**
When stacking statues, we can only stack statues with a width of the base that is \$\leq\$ the width of the top of the statue beneath it. So with the statues above, these are all possible pairs of how we could stack two statues on top of each other:
```
####
# ## ##
# # ## # #
---- -- - --
#### #### #### #### ##
## # ## # ## # ## # ## # #
## ## ## ## ## ## ## ## -- - -- # #
# ## # ## # ## # ## #### #### #### - -- #
## ### ## ### ## ### ## ### # ## # ## # ## ## ## -
## ### ## ### ## ### ## ### # # # # # # ## ## #
------ ------ ------ ------ ---- ---- ---- -- -- --
```
One possible complete stack keeping that in mind could therefore be:
```
#
-
#
--
##
##
--
####
# ##
# #
----
####
## #
## ##
# ##
## ###
## ###
------
```
So in this case the result is truthy, since the statues can be stacked.
## Challenge rules:
* You can use a different consistent character other than `#` for the statue border if you want (other than `- \n`). Please state which one you've used in your answer if it's different than `#`.
* You can use any two distinct output values to indicate truthy/falsey respectively.
* You are allowed to take the \$statues\$ input in any reasonable format. Can be a single multi-line string, a list/array/stream of multi-line strings, a list of character matrices, etc.
* You are allowed to pad the statues input with trailing spaces so it's a rectangle.
* You can assume statues are always separated by at least one space/newline from one-another, so something like `#|#|` won't be in the input.
* You can assume the statues will only have a base at the bottom side, so a statue like this won't be in the input:
```
--
##
##
--
```
* You can assume all statues will only be placed on top of each other, and never next to each other if the top of a statue is large enough to hold two adjacent statues with small bases, or if it could fit on a smaller ledge. For example, these towers of statues aren't allowed when verifying if the statues can be stacked:
```
#
# # #
#-- - -
#### ###
---- ---
Statue on lower ledge Two statues next to each other on top of single statue
```
* You can assume the top and base parts of a statue are always a single piece, without any gaps. So a statue like this won't be in the input:
```
# #
----
```
But a statue like this is possible:
```
#
# #
----
```
* You can assume the base determines the width of a statue. So you won't have statues like these in the input:
```
#######
#####
#### ###
--- --
```
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
Truthy test cases:
```
####
## #
## ##
#### # ##
# ## ## ### ## #
# # ## ### ## # #
---- ------ -- - --
__________________________________________________
##
##
##
####
# # #
---- -
__________________________________________________
# #
### #
# # #
--- -
__________________________________________________
###
###
### ## #
--- -- -
__________________________________________________
#
#### #
# ## #
### # #
##### # ###### ###
----- - ------ ---
__________________________________________________
#
# # # # # # # #
- - - - - - - -
```
Falsey test cases:
```
#
# # ##
--- --
__________________________________________________
#
# #
### ## # #
## # ## ### #####
---- -- --- -----
__________________________________________________
# #
## ### # #
-- --- - -
__________________________________________________
#
#### #
---- --
```
[Answer]
# [Ruby 2.7](https://www.ruby-lang.org/), ~~83~~ 77 bytes
```
->a{a.map{[_1[/-+/].size,_1[/#+/].size]}.sort.each_cons(2).any?{_2[1]<_1[0]}}
```
[Try it online!](https://tio.run/##XVI7b8MgEN7vV5xgaVVDmsxNog6tOnTKY6gQinDkKBnyUKBDavzbXcBgLGOZz8c9vu8O33/LR3uYt2yhasXP6lZbbYUWE/YykVyf/qrCGTQZsuH6eje8Uvvjbn@96KfZM1eXx7K2qihtKabyTYlX2TQtxc1qu/n6ATCVNhrnKAShbgHFsCEF5hYpgKA/R3CACagDDIHe6IGxlBPOIH5DLAOhKJEFChKy85aosWf1WSkSohd6n3@iv@Pv3sw@KhI1jKHzg6v9@f69/nDj8KFDpqw4isxTyb2kEQzEh/4HOiiOFPbzSl3EUBwFwkCzlPG@un/BWLzhQRjZtP8 "Ruby – Try It Online")
Takes an array of string (statues), and outputs the *swapped* boolean values. TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, which saves four bytes.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 98 bytes
```
lambda x,Q=sorted:[*sum(Q(s:=[(-len(b),-len(a))for a,*_,b in map(str.split,x)]),())]==Q(sum(s,()))
```
[Try it online!](https://tio.run/##XU/LjoMwDLznK7ziQFwe2movFVI@omeKVqGAGglChFNt@Xo2D9qt1jnYY8@MHbPa26y/TmbZBnHZRjm1nYRHfhY0L7bvqvpA94mfOVWi5sXYa95iHrJEHOYFZH74zltQGiZpONmlJDMqmz@wwZwjNkI4tfMgj3BTk3HOQCuxUemeQPi6JNspXS697DhGhzDlyJRjfDKy0t4Du26Y39tK6v3WQKuLYxNVHCsGLiLf0dM04B/V2ZuD4QdOiqHrjbzByyiKfagBpF759UOkkAbi9cmqVaWyYNjgn@Btayb@8yCD9KLjKcrPQzs7vt1KpTSm1x2PEJlZlLY7oiccXg3c4s6EJS5Chj37BMnrqshwU0j2IklY4QPc24ui@AU "Python 3.8 (pre-release) – Try It Online") The footer converts from the format of testcases in the challenge to a list of multiline statues.
This sorts the pairs `(base_width, top_width)` in descending order and verifies that `top_width` and `base_width` of adjacent pairs are descending by comparing the flattened list with the sorted list of all widths.
The same logic can be found in my 494-byter for the original challenge, which had to deal with rotated and somewhat overlapping statues:
```
Q=sorted
E=enumerate
def f(G):
s=[];B,S=[{(x,y)for y,r in E(G)for x,v in E(r)if v in e}for e in('-|','#')]
while B:
u,U=l,L=x,y=d=min(B);b={d};R=G[y];exec("l-='-'[:l]==R[l-1];u+=R[u+1:]>[]!=R[u+1]=='-';L-='|'[:L]==G[L-1][x];U+=G[U+1:]>[]!=G[U+1][x]>'-';b|={(l,y),(u,y),(x,L),(x,U)};"*len(G+R));B-=b;z=-len(b);h=[]
while b:b={h.append(abs([x-a,y-p][R[x]<'|']))or(a,p)for a,p in S if any(abs(c-a)+abs(d-p)<2for c,d in b)};S-=b
s+=(z,-h.count(max(h))),
return[*sum(Q(s),())]==Q(sum(s,()))
```
[Try it online!](https://tio.run/##pVPBbqMwEL3zFd5ywC52pO7eQt1DpCqXXJoqJ4oiCI5gRQjCsA0t/fbujE3SNFpVKmuBPWO/8bx5A1XXZPvy1/v7g9T7ulGpcy9V2e5UHTfKSdWWbOmcTR2iZRgFM/4ow1d64B3b7mvS8ZrkJbkHBLoH/se6Ncu3xNjqDQ8UmNQTvcc912ORQ56zvFBkBteSlq9kwRcS7pSp3AFwxoJEvqZvwVLOwy4K1EFt6FUhpCe8cFpEUi7DQtxEQeuD1fo30@gujH5YG04BFiwA3QN6Af48XAA6PETBygdndQowNh7cYUjSy1daQGWctmY@8IWZV@wtuLouVEnn/pKxYCZkErxIgTsJCzIQBuqwJSVToJ5N4qpSZUrjRNPwIGLeiSoKl5DpFlhFjO1rGvPKiAYrCvVIQLK47EzMRsTMRyMVFbv9ibANTxGWAJdHyA8JtS/pCxfZZLNvy4bu4gPNGGPcIbVq2roMr3W7ow9UQxGMgQ5gwoZGj73nuwraDVBOdKdNo6u41mrdKN1oauYp0U2NvYeBHHATSdRqoqsib6j3VD6Vax9nj5tjPcBxFHmpNJFm3waYHcpOiOc8bTJAIHdUE8@ZSYUWpjIRHwFdroqUhEWuGwOeFL9bMM097B@RkeOcEz@vEKqe6CbNy0mt4hQ0scSrOgcxt0YAkMmmdd3ecWGgDRb4MBF4erAEDGPhGJj2Jsh1ehNjZ@uJT0jXeo6z/vZwLA9BzFXIyDW0XGIYjbtyKBeZumYlJ@bIfdylqM@g4HE1dj@27qETp2H0PPbl4gyyfHJMtPsFwDZUfHUFuRzf2BtVcY9ifTxub5@RPbYKGCmOn6Dj2r7b5WIlA5IctRn9eWEm@2tgSeT/vtKLf@@8/SftMYv5Ns4b@dk9Px1HZ/2hIGpFTHPcwRit1fBDW7HhJe5f "Python 3 – Try It Online") and [an ungolfed version](https://gist.github.com/ovs-code/25e810fb0818078cf9f9b08133b76334).
] |
[Question]
[
Given a non-empty list of digits 0 though 9, output the smallest number that can be produced by an expression formed by reordering these digits and introducing exponentiation signs `^`, with adjacent digits getting concatenated as multi-digit numbers. Exponentiation is evaluated as right-associative.
For example, `[4, 2, 3, 3]` could become `2^34^3` which evaluates as `2^(34^3)`, but simply writing `2334` is smallest here. You can assume that any array containing a 0 gives a minimum of zero (a special case), or that it's achievable by an expression like `0^rest`, or like `00` for just zeroes.
The input list can be taken as any ordered sequence, but not as an unordered (multi)set.
Test cases:
```
[2,3] => 8 (2^3)
[3,3] => 27 (3^3)
[4,3] => 34 (34)
[1,2,3] => 1 (1^2^3)
[2,2,2] => 16 (2^2^2)
[2,3,2] => 81 (2^3^2)
[3,0] => 0 (Special, or maybe 0^3)
[0,1,0] => 0 (Special, or maybe 0^10)
```
Shortest code in each language wins. I'll accept an answer just to give the +15 rep without any specific accepting standard.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
œε.œJ€.«m}ß
```
[Try it online](https://tio.run/##ASMA3P9vc2FiaWX//8WTzrUuxZNK4oKsLsKrbX3Dn///WzMsNCwzXQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/o5PPbdU7OtnrUdMavUOrc2sPz/@v8z862kjHOFYn2hhMmoBJQx2ImBGQNgLLGYBJE6ioMVA0FgA) or [try it online with added debug-lines](https://tio.run/##bY9NDgFBEEb3TlGxIhkS7CQitrMSW7FoM8VU9F@6qyO2ruAADkBi5wDERVxkzGgSC/v33ldlvFgSlmVzIiVYdCqwYDLag1kBFwgtUlZSRtwG0jZwR5LnITSTx2F0u44bURSOKWpV47dTk8/9ufulU0MaUGRFVdPoOsp4hjoJbNZYDbraSO@XiM8wDxn@F5Y7YLEhvX7fac0Wnf/M1Yu3k4qNqbEgdA42@OKNrqRgRo05KNKkgoq/kofvb/djUpbzXtJPBosX).
**Explanation:**
```
œ # Get all permutations of the (implicit) input-list
ε # Map each permutation to:
.œ # Get all its partitions
J # Join each inner-most list together
€ # For each inner list:
.« # Right-reduce it by:
m # Taking the power
}ß # After the map: pop and push the flattened minimum
# (after which it is output implicitly as result)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Œ!*@/€;ḌƊṂ
```
A monadic link accepting a list of digits yields an integer.
**[Try it online!](https://tio.run/##y0rNyan8///oJEUtB/1HTWusH@7oOdb1cGfT////o410jHWMYgE "Jelly – Try It Online")**
### How?
Checks digital and power-wise evaluations of all permutations even though we only *need* to check forward-sorted-digital, forward-sorted-power-wise, and reverse-sorted-power-wise (and only for `[3,2,2]`), because it's far terser.
Note that there is no need to check any mixture of digital and power-wise evaluations (they can never be strictly smaller than one of the three previously mentioned evaluations)
```
Œ!*@/€;ḌƊṂ - Link: list, L
Œ! - all permutations (of L) -> P
Ɗ - last three links as a monad:
€ - for each (p in P):
/ - reduce with:
@ - using swapped arguments:
* - exponentiation
Ḍ - un-decimal (vectorises across P)
; - concatenate (these two lists of numbers)
Ṃ - minimum
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
á Ër!p mDìÃn
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=4SDLciFwIG1E7MNu&input=WzMsMiwyXQ)
[Answer]
# [Io](http://iolanguage.org/), 77 bytes
Based on xnor's observation in the comment section. -12 bytes thanks to Arnauld's idea.
```
method(x,y :=x sort;if(y==list(2,2,3),81,y join()asNumber min(y reduce(**))))
```
[Try it online!](https://tio.run/##lY/BbsIwEETv@YoRl9rILcXhgEC59dwv4OKSDRgSG9mLmnx9MCoq0IYDc9u32tkZ6/sKiwKrviHe@lK0qktzi@gDL20luqKobWShlVa5VPNp2u@8dUKa@HlsviigSVOHQOVxTWI8lkl9JS5XuZQADsE6rl12wfkwng3jqfqx@YPPifR/nKv3O5NsMkHrfHiJoJaDAVNkrE2kmGWj4lej25vri6FAD1ppNXui7IP4@r4sUvoPMnXEt@UtLKO2e4JxoHJDr@cab/0J "Io – Try It Online")
## Explanation
```
method(x, // Anonymous method with param x
y := x sort // Assign y to sorted x
if(y == list(2,2,3), // Edge case treatment
81, // (It's a kinda weird case that goes right to left)
,y join()asNumber// Join the sorted digit-list into a single number.
min( // Minimum with:
y reduce(**)))) // the sorted list reduced by the power function.
```
[Answer]
# JavaScript (ES7), ~~65~~ 62 bytes
*Fixed thanks to @xnor and @l4m2*
*Saved 3 bytes thanks to @l4m2*
```
a=>Math.min(x=a.sort().join``,a[0]&&eval(x-223?a.join`**`:81))
```
[Try it online!](https://tio.run/##bY9bCoMwEEX/u4p8lYlozENaKdiuoCsQxWC1VWxSVMTdp4pQ1Gbmcw7nzq3lILu8rT69p/SjMGVkZHS9y/5F3pWCMZKk020PmNS6Ulnmypgmx2MxyAZGj3Nxk8vFcbJLyDA2uVadbgrS6CeUEHNXJBijZXwfoRABTwU@7Dix4/gZgbBwwY4TwcQFfxhzV8FzLEPAUlswn0i@ItlpfnBay4t0W4UioNYqW2PI5ip245xOF@/PSAjB5gs "JavaScript (Node.js) – Try It Online")
### How?
The general case is to look for the minimum of the concatenation of the digits in ascending order and an exponent chain, also in ascending order.
But as noticed by @xnor, there are a few special cases:
* if the list contains a \$0\$, the result is always \$0\$
* for `[3,2,2]`, the minimum value is \$3^{2^2}=81\$
[Answer]
# perl -alp, 83 bytes
```
%_=(22,4,23,8,24,16,33,27,222,16,223,81);$_=join"",sort@F;$_=/0/||/1/?$&:$_{$_}||$_
```
[Try it online!](https://tio.run/##FYlBCsIwEEX3PUUoURRGkplJVZSiK68RXLiolCa03Rmv7jhZvAf//fyax05kE/sdEQQghjNQADwCM9AJSLMOqgfurzb27zRMbQtLmtf7owbnXSkO3c1uLzZ@bPyWYqMIGW5YCQqaukhNalaz8Y03aPwv5XVI0yKH55j/ "Perl 5 – Try It Online")
Reads a list of white space separated numbers from `STDIN`, writes the answer to `STDOUT`. If the input contains a `0`, output `0`, else, if the input contains a `1`, output a `1`. Else, if it's one of 6 special cases, output the corresponding value. Otherwise, output the sorted input.
] |
[Question]
[
* Chat room: <https://chat.stackexchange.com/rooms/106513/easter-bunny-challenge>
* Git repo: <https://github.com/ajfaraday/easter_bunny_hunt>
---
The garden is a 2-dimensional grid with 49 rows and 49 columns.
The Easter Bunny™️ is in the center of the garden, minding his own business, holding on to 100 Easter eggs.
Unfortunately, there's a team of 4 children who aren't content to collect chocolate eggs, they want to capture the Easter Bunny™.
The game starts with 4 kids, one in each corner of the garden.
The kids can take 1 step each turn, in one of the 4 cardinal directions (North, South, East or West). When they've each taken a step (or decided not to), the bunny will take a move.
The kids can only see the Easter Bunny or its eggs when they are 5 steps away or nearer.
Kids visibility (yellow) and movement options (green):
[](https://i.stack.imgur.com/IGdSN.png)
The bunny can hop up to 2 spaces away on both axes (describing a 5 x 5 square he can hop to).
The Easter Bunny™ can only see the kids when they are 5 steps away or nearer.
Bunny's visibility (yellow) and movement options (green)
[](https://i.stack.imgur.com/1nUMB.png)
Neither kids nor the Easter Bunny™ can leave the garden.
The game ends when:
* The Easter Bunny™️ drops his last egg, or
* The kids catch the bunny, or
* The game reaches turn 1000.
The Goals:
* The Easter Bunny™ wants to give the children as many Easter Eggs as possible while evading capture.
* The kids want to collect as many eggs as possible, AND catch the Easter Bunny™.
This means that:
* The Easter Bunny™ will ONLY score points if it evades capture by dropping it's last egg, or by finishing the time limit.
* The team of kids will ONLY score points if they capture the Easter Bunny™.
* In either case the points scored is the number of eggs the kids have picked up.
The challenge is to write behaviour for the Easter Bunny™ or for the team of kids. Your code will be run against all of the
other kind of entry.
## Config
You can edit `conig.js` to change two things about the run:
* `match_limit` will allow you to end the game when you decide (competition will use 1,000 turns)
* `turn_time` (ms) will set the interval when the game is rendering.
# As the kids:
(See instructions for the bunny below)
Your goal is to collect as many eggs as you can, and then catch the Easter Bunny™.
Your code will take the form of an array of 4 JS functions, which will each control a kid starting in these positions (in this order):
* North West (0, 0)
* North East (0, 48)
* South East (48, 48)
* South West (48, 0)
If you're watching a match, these are represented by the numbers 1 to 4.
The functions should each have this fingerprint:
```
function(api) {
}
```
`api` is your function's interface to the game (see below).
## The Kid API
The `api` object presents these four movement functions:
* `api.north()`
* `api.east()`
* `api.south()`
* `api.west()`
If any of these are called during your function, the kid will take one step in that direction (or the last called of these four directions).
If none of these are called during your function, the kid will stand still.
It also provides information about the state of the game with these methods:
* `api.my_storage()` - an object you can use to store data and functions for just this kid.
* `api.shared_storage()` - an object you can use to store data and functions for the whole team.
* `api.turn()` - Returns a number of turns taken in this game so far.
* `api.bunny()` - Returns an object of bunny-related info if the bunny can be seen
{
x: 24,
y: 24,
eggs\_left: 100
}
* `api.kids()` tells you where all the kids are
[
{x: 0, y: 0, me: true}.
...
]
* `api.eggs()` tells you where the eggs are that your child can currently see:
{
x: 25,
y: 25,
age: 10
}
Age is the number of turns since the bunny dropped the egg.
## Kid Template
```
Teams.push(
{
name: 'template',
shared_storage: {},
functions: [
function(api) {
// NW kid
},
function(api) {
// NE kid
},
function(api) {
// SE kid
},
function(api) {
// SW kid
}
]
}
);
```
* `name` must be a single-word identifier, if you want to run just a single entry.
* `shared_storage` sets the initial state of `api.shared_storage`, it can be used to set data and functions for your team.
* The array `functions` is the behaviour of the 4 kids chasing the bunny.
## How to participate
You will need nodejs installed.
Change `my_entry` to your own team name.
* `git clone https://github.com/AJFaraday/easter_bunny_hunt.git`
* `npm install terser -g`
* `cd easter_bunny_hunt`
* `cp team_template.js teams/my_entry.js`
* (Write your team code)
* `script/run.sh my_entry basic` to watch a game. The first entry is the name of your team, the second is the name of an entry in bunnies/.
* `script/run.sh` to run all matches and see all results (if you import more entries)
When you're happy with the result, copy it in to an answer like so:
```
# Team: my_entry - 10 points
Any description you want to add goes here
Teams.push(
{
name: 'template',
shared_storage: {},
functions: [
function(api) {
// NW kid
},
function(api) {
// NE kid
},
function(api) {
// SE kid
},
function(api) {
// SW kid
}
]
}
);
```
Then have a try at writing an entry for the Easter Bunny™.
# As the Bunny
Your goal is to give away as many Easter eggs as you can and, crucially, to evade capture.
The bunny starts at the centre of the garden, at coordinates 24, 24.
Your code takes the form of a function with this finger print which runs once a turn, after the children have moved.
```
function(api) {
}
```
## The Bunny API
The api object provides this method to tell the bunny how to move:
* `api.hop(x, y)`
The two arguments tell the bunny where to hop to relative to it's current position:
* They can have values from -2 through to 2.
* If `x` is positive, it will hop east, negative, it'll hop west.
* If `y` is positive, it will hop south, negative, it'll hop north.
* If the values provided are out of range, it will force it to 2 or -2.
* Each time the bunny hops, it leaves behind an Easter egg.
It also provides this functions to give you storage between turns:
* `api.storage()` - Returns an object you can use to store variables.
And these functions to give you information about the game:
* `api.turn()` - Returns the turn number the game is currently at.
* `api.eggs()` - Returns the positions of all Easter eggs in the garden.
{
x: 25,
y: 25,
age: 10
}
* `api.bunny()` - Provides information on the current state of the bunny
{
x: 24,
y: 24,
eggs\_left: 100
}
* `api.kids()` - Provides information on all the kids the bunny can currently see.
{
x: 0,
y: 0
}
## Bunny Template
```
Bunnies.push(
{
name: 'template',
storage: {},
function: function(api) {
}
}
);
```
* `name` is the name of your bunny behaviour. Keep it to 1 word (underscores allowed).
* `storage` is the current state of your storage object, available via the api.
* `function` is the function which will be run every turn to control the bunny.
## How to participate
You will need nodejs installed.
Change `my_entry` to your own bunny name.
* `git clone https://github.com/AJFaraday/easter_bunny_hunt.git`
* `npm install terser -g`
* `cd easter_bunny_hunt`
* `cp bunny_template.js bunnies/my_entry.js`
* (Write your team code)
* `script/run.sh get_egg my_entry` to watch a game. The first argument is the name of a team in teams/, the second is the name your bunny.
* `script/run.sh` to run all matches and see all results (if you import more entries)
When you're happy with the result, copy it in to an answer like so:
```
# Bunny: my_entry - 10 points
Any description you want to add goes here
Bunnies.push(
{
name: 'template',
storage: {},
function: function(api) {
}
}
);
```
Then have a try at writing an entry for a team of kids.
[Answer]
# Bunny: smartish (2 points, but, of course, as of posting)
Hops to the middle when it doesn't see anybody, and tries to escape the kids (using an algorithm I probably implemented incorrectly).
```
Bunnies.push(
{
name: 'smartish',
storage: {},
function: function(api)
{
let x = api.bunny().x;
let y = api.bunny().y;
if(api.kids().length == 0)
{
//hop towards middle
let dx = 24 - x;
let dy = 24 - y;
api.hop(dx, dy);
return;
}
//else build an array of safe cells
safe = [[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1]];
for(let i in api.kids())
{
let kid = api.kids()[i];
let dx = x - kid.x;
let dy = y - kid.y;
if(dx >= -2 && dx <= 2 && dy >= -2 && dy <= 2)
safe[dx+2][dy+2] = false;
dx++;
if(dx >= -2 && dx <= 2 && dy >= -2 && dy <= 2)
safe[dx+2][dy+2] = false;
dx -= 2;
if(dx >= -2 && dx <= 2 && dy >= -2 && dy <= 2)
safe[dx+2][dy+2] = false;
dx++; dy++;
if(dx >= -2 && dx <= 2 && dy >= -2 && dy <= 2)
safe[dx+2][dy+2] = false;
dy -= 2;
if(dx >= -2 && dx <= 2 && dy >= -2 && dy <= 2)
safe[dx+2][dy+2] = false;
dy++;
}
//find the farthest safe cell and hop there
let bestx = 0, besty = 0, bestd = 0;
for(let dx = -2; dx <= 2; dx++)
for(let dy = -2; dy <= 2; dy++)
{
if(!safe[dx+2][dy+2]) continue;
let d = 9999;
for(let kid of api.kids())
d = Math.min(d, (kid.x-x)*(kid.x-x) + (kid.y-y)*(kid.y-y));
if(d > bestd)
bestd = d, bestx = dx, besty = dy;
}
api.hop(bestx, besty);
}
}
);
```
] |
[Question]
[
In LLAMA, you want to dump cards from your hand as quickly as you can, but you might not be able to play what you want.
Each player starts a round with six cards in hand; the deck consists of llama cards and cards numbered 1-6, with eight copies of each. On a turn, the active player can play a card or draw a card. To play a card, you must play the same number as the top card of the discard pile or one number higher (for simplicity, we will follow the rule that if you can play a card of the same number, you will play that card, if not, play the higher card). If a 6 is on the discard pile, you can play a 6 or a llama, and if a llama is on top, you can play another llama or a 1. If you cannot play any cards, you must draw a card.
The round ends when one player empties their hand, who is pronounced as the winner of that round.
Some specifications:
1. The llama cards may have any name, but must be stored as a string (e.g. simply using the value 7 as the llama card is not permitted)
2. If a player draws a card, they may not play the drawn card in the same round again, i.e. their turn ends after drawing a card.
3. We will play the game with four players.
The output should list the turns taken by each player in the following fashion:
```
1 - 1
2 - 1
3 - 1
4 - 2
1 - 3
2 - draw
3 - 3
4 - 4
.
.
.
1 - 6
2 - llama
game over, 2 wins.
```
As always in code-golf, the program with the lowest number of bytes wins.
Edits:
In response to the comments, here are a few additional specifications.
* The output may have any format as long as it contains the player number and their action.
* The llama card should be a string composed only of letters, no numbers allowed.
* At the start of a game, there is a single card on the discard pile, i.e. player 1 cannot play any card.
* If the draw deck is empty, the played cards should be reshuffled. As the official rules of the game do not specify what should happen if all cards are drawn and there are no cards in the discard pile, this case does not need to be accounted for.
* There is no input, i.e. the shuffled deck and dealing the hand cards must all be done in the program.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 94 bytes
```
Ḣ_þⱮOƑƇ€}ṪṪʋ%7ż⁸ʋṢF,Ḣ;€2¦@¥¥¥F;1ịḢɗ}ɗ,;€”d$}ɗḢ€ḢỊƊ?ṭ€1¦⁸
56Ẋ%7s32s"31,6Ṛç/Ẉ€Ȧ$пṪ€⁺⁺Ḋo”l4R¤ṁżƊ
```
[Try it online!](https://tio.run/##y0rNyan8///hjkXxh/c92rjO/9jEY@2PmtbUPty5CohOdauaH93zqHHHqe6HOxe56QDVWQNljQ4tczi0FATdrA0f7u4GCp@cXntyug5I8lHD3BQVIAcoCOQByYe7u4512T/cuRbINTy0DGgal6nZw11dqubFxkbFSsaGOmYPd846vFz/4a4OoJITy1QOTzi0H2g7yLDGXUD0cEdXPtDYHJOgQ0se7mw8uudY1///AA "Jelly – Try It Online")
A set of links which when run niladically returns a list of pairs of `[player number, move]` where move is `l 1 2 3 4 5 6 d`. `l` represents llama and `d` draw.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~401~~ \$\cdots\$ ~~347~~ 345 bytes
```
from random import*
d=[*range(7)]*8
shuffle(d)
p=[[d.pop()for i in[1]*6]for j in[1]*4]
o=[*range(1,7)]+['l']
h=[]
s=d.pop()
def g(a):p[n].remove(a);h.append(s);print(f"{n+1}-{o[a]}")
n=3
while all(p):
n=-~n%4
if s in p[n]:g(s)
elif(t:=-~s%7)in p[n]:g(t);s=t
else:
if not d:d=h;h=[];shuffle(d)
p[n]+=[d.pop()];print(f"{n+1}-d")
print(n+1)
```
[Try it online!](https://tio.run/##XZDdasMwDIXv9RSiUGona6C0rCXBT2J8EbAdezi2sb2NUbpXz5yt@2FX4uhIH0eKb8UEf7zEtCw6hRnT6GUtdo4hlQYk401tTYqcqWgukM2z1k4RSSEyzmUXQyRUh4QWrecH0TyKVT3d1UlA@EEcHiqk5Tu3E2AYF5DZHQBSaZzISPvIveiSmsOLqnIw3Rij8pJkOsRkfSF6c/Xt4ba/Bj6K24aCZ0d4NdYpHJ0jkfaAnu3f/fYEaDXmmgRXaj9VCKByVpPS14m8PdNfr9Ahs7L6WVXEuupDQdlLZoY17fDndvzcatn3A8S/cLLm@upUSZflAw "Python 3.8 (pre-release) – Try It Online")
* Prints `player-card` for each move.
* `player` is `1` to `4`.
* `card` is `1` to `6` or `l` for llama or `d` for draw.
* Simply prints winner's number at the end.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~127~~ 121 bytes
```
Fl123456F⁸⊞υι≔⟦⟧θWυ«≔‽υι⊞θι≔Φυ⁻λ⌕υιυ»≔E⁴E⁶⊟θη≔⊟θζ≔⁰εW⌊η«≔§ηεδI⊕ε-¿⊙δ›²﹪⁻ΣκΣζ⁷«F¬№δζ≔⎇⁼6ζlI⊕Σζζ§≔ηεΦδ⁻λ⌕δζζ»«⊞δ⊟θd»⸿≔﹪⊕ε⁴ε
```
[Try it online!](https://tio.run/##ZVFNTwIxED3Dr5j0NE1Kooho4okYMRwwRL2phw0tbmO3ZbtbFcz@9rXtVhb11M7Xe2/erPPMrk2m2nZjLCBRp@OzyfmUUIjxJYWVq3J0DCS9Gs6qSr5qfHphUPrwI5dKADoKX8NBqt1nmpvC57qJQRwvU5B65lLVwgbQpdSuQsVgLjXvWKifdL65@WFbZluc@Fb/TBmszBbL2JT3grokg32fOmEgeomeRxauwJwea53VC83FJ@ahlwGPeq3UNV5nVY0LvbaiELoWHIWnPFTJiIRAbgBneoecwa0VWVhp7HUa7pTBbrMHz/nmocO7D6IvPE6UMIj@3hnPZZzH5EG9LyVpj8LqzO7wpnSZqpBMSagzIMp//qlL8DRZMEgLHu8XLI6u87@uJ@Y41@0XMRoQqhJRarwhP3jfNxIejWgOxjxbcnTnZMVvHxlMaHebpm3b0bv6Bg "Charcoal – Try It Online") Link is to verbose version of code. Outputs `l` for llama and `d` for draw. Winner is person who last played a card. Explanation:
```
Fl123456F⁸⊞υι≔⟦⟧θWυ«≔‽υι⊞θι≔Φυ⁻λ⌕υιυ»
```
Create and shuffle the deck.
```
≔E⁴E⁶⊟θη≔⊟θζ
```
Deal.
```
≔⁰ε
```
Start with player 1.
```
W⌊η«
```
Repeat until someone wins.
```
≔§ηεδ
```
Get the current player's hand.
```
I⊕ε-
```
Output the current player.
```
¿⊙δ›²﹪⁻ΣκΣζ⁷«
```
If they have a playable card:
```
F¬№δζ
```
if they don't have a matching card,
```
≔⎇⁼6ζlI⊕Σζζ
```
then increment the last discard, rolling over to `l` for llama;
```
§≔ηεΦδ⁻λ⌕δζ
```
remove the playable card from their hand;
```
ζ
```
and print their play.
```
»«⊞δ⊟θd»
```
Otherwise draw a card and print that action.
```
⸿
```
Move to the start of the next line.
```
≔﹪⊕ε⁴ε
```
Update to the next player.
] |
[Question]
[
Given a list of words, output a square grid of characters, so that all the words can be read from the grid, by moving horizontally, vertically, or diagonally between characters, without reusing characters in the same word. The grid must be the smallest possible which allows all words to be read.
## Example
```
B A D
R E T
E Y E
```
The above grid contains the words BAD, BAR, BARE, TAB, TEAR, EYE, EAR, TEE, TEED, BEAR, BEAD, BEET, DARE and YEAR (plus more, and duplicates of these in some cases). It could therefore be a valid output for the input list YEAR, BEET, DARE - the grid must be at least 3x3, since at least 8 characters are required (7 distinct characters, and 2 Es), which wouldn't fit in a 2x2 grid.
```
Y D R
B E A
T E E
```
The above grid would be another valid output for the input YEAR, BEET, DARE, but would not be valid if EYE was added to the input list, despite containing the same letters as the previous grid, since there is no way to reach the Y from two distinct Es.
There is no assumption that "words" in this challenge are English words, or even formed of letters - they are simply any string of at least 3 characters.
For input ‚òÉÔ∏èüåûüò¢, ‚òÉÔ∏è‚ùÑÔ∏èüòÉ, üåûüåßÔ∏èüåà
```
‚òÉÔ∏è üåû üò¢
‚ùÑÔ∏è üåßÔ∏è ‚òÉÔ∏è
üòÉ üåà ‚ùÑÔ∏è
```
would be a valid output. In this case, all the "words" can be read in straight lines, which wasn't possible with the previous example (no way to fit a 4 letter word into a 3x3 grid without a turn)
## Rules
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* You can take input in any acceptable format (see [Input/Output methods meta post](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/))
* You can output in any acceptable format, as long as it is trivial to check that it is a square manually. For example, outputting `BADRETEYE` is not trivial to check - you need to count the characters, and take the square root of this, which is far too much effort for larger grids. Outputting `BAD RET EYE` is trivial to check - you count how many groups, and the length of any group, and if they are the same, the grid is square.
* You can fill in any gaps in the grid with any characters from the input
* Letters can only be used once in each word
* The grid should be as small as possible - the lower bound will be the square number above number of distinct characters required (e.g. 8 distinct characters would require 9 characters of output at minimum, but may require more characters if positioning means that they can't be read simultaneously)
* Languages without Unicode support (e.g. C64 BASIC, things that only run on calculators) may ignore the Unicode test case
* It's code-golf, so shortest answer in bytes wins!
## Test Data
* ANT - should give a 2x2 grid, with one letter repeated
* ANT, TAN, NAT - may well give same grid as previous
* ANT, MAN - 2x2 grid, with each of A, N, T, and M included once
* YEAR, BEET, DARE - 3x3 grid
* YEAR, BEET, DARE, EYE - 3x3 grid
* BAD, BAR, BARE, TAB, TEAR, EYE, EAR, TEE, TEED, BEAR, BEAD, BEET, DARE, YEAR - 3x3 grid
* ANTMAN, BATMAN, BANANA - 3x3 grid
* CHAOS, ORDER - 3x3 grid, no spare spaces
* SUPERMAN, SHAZAM - 4x4 grid
* 123, 1337, 911, 999, 112 - non-letters, 3x3
* SUPERGIRL, FLASH, ARROW, GOTHAM, BLACKLIGHTNING, KRYPTON, TITANS, DOOMPATROL - no idea, but at least 6x6
* ABSENTMINDEDNESS, MINT, DINED, TABS, STAND, SEATED - no idea, but might be a 4x4, since only 16 required letters
* ‚òÉÔ∏èüåûüò¢, ‚òÉÔ∏è‚ùÑÔ∏èüòÉ, üåûüåßÔ∏èüåà - Unicode characters, 3x3
* AUCTIONED, CAUTIONED, EDUCATION - 3x3
* COUNTRIES, CRETINOUS, NEUROTICS - at least 4x4 - both R and E need to be next to 6 distinct letters, which isn't possible on 3x3 grid
## Notes
* Inspired by the game "Words Everywhere" in the Word Games Pro app from LittleBigPlay, available on Google Play
* Solving [Is This a Boggle Pad?](https://codegolf.stackexchange.com/questions/163690/is-this-a-boggle-pad) in the unrestricted NxN case might be useful to determine the minimum required size, but is unlikely to help with actually generating the output
* There is a kind of inverse of this challenge at [Is This Word on the Boggle Pad](https://codegolf.stackexchange.com/questions/31743/is-this-word-on-the-boggle-board)
[Answer]
# [Python 3](https://docs.python.org/3/), 444 bytes
```
def p(g,v=[]):
l=len(g);r=[*range(l)];k=[[(x,y)]for x in r for y in r if(x,y)not in v]
if len(k)<2:return[k[0]]
return[n+N for n in k for N in p(g,v+n)if max(abs(N[0][0]-n[0][0]),abs(N[0][1]-n[0][1]))<2]
from itertools import*
def f(a):
i=2;w=set("".join(a))
while 1:
for f in product(*[w]*i*i):
g=[f[k*i:][:i]for k in range(i)];P=["".join(g[x][y]for x,y in l)for l in p(g)]
if all(any(c in n for n in P)for c in a):return g
i+=1
```
[Try it online!](https://tio.run/##RVBBboMwEDzDK6ycbEKjkt5IfcgDinLozfKBJphscWxknACvp2uTthKSd2d2h53pZ3@15m1ZLo0iPW3zBxeSlWmiuW4MbdnBcZG52rQN1UweOi4EnfKZSWUdmQgY4kgo57UEFVljfegfMk1AkaDUsfd96Rp/d0Z04lUi8@zMtooKJmx0saxCGa/ZGoYCt3qi9ddAK1zE78WsL8v/wOIJFpLhj2SqnL0R8I3z1uqBwK23zmdpcKloHQwC3x9GPjSebja7bwsGYZYm4xV0QwocSMIlKl7i7OV@9jQTo8wgg7CeJC0XSnQZlFKUEOPoYgYxK8CsTlz8SrdikmJeM8tjVJqFRj@NMhkU0WmtNa3NTM@BMP@5nOJ4RPH6NTnS4hJsebGM1l0GwpHt756y3dBrwDdNWwcXxBWNEwgEFWfHoBM4NNI7MGgNQbYcq0/ycax@AA "Python 3 – Try It Online")
Horribly inefficient. The function `f` takes a list of words and returns a grid of characters as a list of tuples. The footer is just for formatting to take input and pretty-print output.
(Also when I golf this I get to make a crossed-out-44 meme :D)
[Answer]
# Python3, 853 bytes:
```
R=range
def O(n,b,w,c,x,y,p):
if''==w:yield b,c;return
F=0;q=[]
for X,Y in[(1,0),(-1,0),(0,1),(0,-1),(1,1),(1,-1),(-1,1),(-1,-1)]:
if n>(j:=x+X)>=0 and n>(k:=y+Y)>=0:
if 0==b[j][k]:q+=[(j,k)]
if b[j][k]==w[0]and(j,k)not in p:yield from O(n,b,w[1:],c,j,k,p+[(j,k)]);F=1
if F==0:
for x,y in q:B=eval(str(b));B[x][y]=w[0];C=eval(str(c));C[w[0]]={*c.get(w[0],[]),(x,y)};yield from O(n,B,w[1:],C,x,y,p+[(x,y)])
def f(w):
l=len(set(''.join(w)))
n=min(i for i in R(l)if i**2>l)
q,s=[([[0for _ in R(n)]for _ in R(n)],{},w)],[]
while q:
b,c,W=q.pop(0)
if[]==W:return[[j or w[0][0]for j in i]for i in b]
for x,y in(c.get(W[0][0],[])or[(x,y)for x in R(n)for y in R(n)if 0==b[x][y]]):
P=eval(str(b));P[x][y]=W[0][0];K=eval(str(c));K[W[0][0]]={*c.get(W[0][0],[]),(x,y)}
for B,C in O(n,P,W[0][1:],K,x,y,[(x,y)]):q+=[(B,C,W[1:])]
break
```
This solution is longer than the other Python answer, but significantly faster on the test cases.
[Try it online!](https://tio.run/##jVLBbtpAEL3zFXvDGwZkh0Mbo41kE0eVohBEqBK6WlVATGJwjHFoCYpySg89ROo1lzZSL/2Ffk9@oPkDOrNrmhCJtgLtenbevpk3b9P59GycVF@n2WLRElk3OQ0LJ@GAHVgJ9GAGfbiEOaTcLbBoUCwKMXPnURifsB70a1k4/ZAlBbYr7NpESFVgg3HGjqHDokRaDtgcrLLZbHD0WqbNAbPqoGyisg4V1sFCLNm2hq64LB3zbWGzbnJCJyNXzEsdOiEUwWwhenKo5Ei5k5KQ1hBGXOW5PIEdS1shg04m4yn2xtJcxCAbny@lSsdVKBdRkJZyKl7bFQ4pR4mmKgnEiRDJxPVF@LEbWxfTzOpxXvPlpZJzpQvW6k@5Pubqkk6VuNroV07DqUURSIXCkY1f11704@f91M34sR@CKa69GVgz8iMWcZhYF0hWLFaG4yjBY84LLBHn@B3pViNqtGXFHCVEGxub2zECJnCBs5LSJsR7g0i4Wo3g6hpmnHossNlZFIeoF/Wj7XAkJpV0nFo212ZJnPGRa96ClEOGNKQO/8Q4JMZI/Wmmp1amaJlxHJkLNJFxZsRqzLIdCubLYGm8nrbi@jE0V61o5lbkvLW9VTf2ZJ54MuRZB7knREt1fahTZbKlCRpGzuxpZ5a@mOeHSARg1jzCXhZ2R4s0i5KpNbCKXqNdrFykcYSGASuSV89zwNpeA1jD@wdq32usBXQCrwXMDwLE7Xit4L@BwILOerTv7SBY39DYtufjoinwGi701Q4CvRA0Z9fXntWgqn8Tt08D8L3l3sDfWnj9jXdwCOygtROs5zx82wxamu3wjffO218LdDarwJxq9RWwLcfBZWsLY2dz7YWHu5tfP7883t9@e7y/@w7MxA9fP@nTuxtgJnf7w8A@v2Ba/AY)
] |
[Question]
[
Create a program (any language) which, given positive integer `m`, outputs a valid C *expression* that:
1. Uses a single variable `x` assumed of 32-bit unsigned type (i.e. `uint32_t`)
2. Would evaluate to range [0, `m`) for any of the 2³² possible `x`, reaching any of the `m` possible outcomes either 2³² / `m` or 2³² / `m` + 1 times (where / rounds down).
3. Is limited to use of
* variable `x` as operand
* constants from 0 to 2³²-1, in decimal (`42`) or hexadecimal (`0x2a`)
* *operators* among (listed by groups of decreasing priority in C)
+ `+` `-` restricted to addition or subtraction of two operands
+ `<<` `>>` restricted to right argument constant in range [0, 31]
+ `&` restricted to bitwise and
+ `^` bitwise xor
+ `|` bitwise *or*
* parenthesis for `(`*expression*`)`
* sequence idiom `(x=`*expression1*`),`*expression2* which evaluates *expression1*, assigns it to `x`, then evaluates to *expression2*. The sequence idiom can only be used to form the overall expression or *expression2* in a sequence. `,` and `=` do not account as operator.
It is assumed all arithmetic is such that all quantities are truncated to 32-bit, and that right shift `>>` introduce zeroes.
When given input `m`, the first output of the program must be an expression valid for `m`, aiming at a minimal operator count. Further output, if any, should be expressions for incremental `m`.
Example outputs (believed optimum) for first few inputs `m`:
```
output m count alternative output
0 1 0 (0)
x&1 2 1 x>>31
(x-(x>>1)+(x>>2))>>30 3 5 (x=x-(x>>2)),(x=x-(x>>31)),x>>30
x&3 4 1 x>>30
```
---
Following comment, this is a *code challenge*. Ranking criteria:
1. Producing conforming expressions with minimum operator count up to the highest `m`. Expressions posted or linked in other answers are used to assess minimum, after verification.
2. Minimal expression depth up to the highest `m`. Depth is 0 for `x` or constant. The result of an operator has the maximum depth of the two operands when they differ or in a sequence, or 1 more otherwise. Expressions in the example output have depth 1, except for `0`. The expression `x+1&x+2^x+3&x+4` has depth 3, and any shorter expression has lower depth.
3. Programs that convincingly produce minimal output (as defined above) are preferred.
4. Programs which can be evaluated at compile time by a C/C++ compiler for constant `m`, so that use of `R(x,m)` generates the same object code as the expression for `m` does, are preferred. Nice-to-have: not requiring C++, not requiring `inline`.
---
Motivation: starting from `x` uniformly random, we want to restrict it to [0, `m`) with a distribution comparable to the expression `x%m`, in a way that is fast and constant-time. Count and depth match instruction and register count on LEG Brain M0, an imaginary 32-bit CPU.
---
Modifying the following C program changing `E` and `M`, then compiling and running it on a compiler with 32-bit int, exhaustively checks an expression against requirement 2, assuming that it is a well-formed C expression that matches requirements 1 and 3. [Try it online!](https://tio.run/##tVVLb@M2EL7rV4xt7EKq5caPYhFUkS9FDgV2jWLj9pIGhSLREbEiqZKULWU3vz0dUrIsW0putQ2LGs58nPnmwXj2FMevr1dX8BeRdFdBxIGUuSRKUcFhJyRI8m9BJWGEa1g6Dqp2FAqeEAmaKO1MErKjnMAtuGVYztxyvV56nt@@rBb4Zp7zVvULrGDog2fso6wgIHbAgEU6Til/Ap1GunO40@JsoaBcr5b/6B6OrnJiwyjBjdOIPxFAkEoUEsSBg6Tq28hrgTawWr7hEC/YI4aKHj1SrYDyGnrb2v4G7tYbto0jpUGLxiKAQhEDcAuCZ9UI46A8zoqEwI3SCUbyc7p2jC4iY2w6eMOlU2wdBDQ3cmUwJnQHmzBcLR1jcXQ0/@Pr78V2A@MPY7Ma2C3t7vza7JfIiDMhWQ21@PQe1MBuA/WLhVp86kBdv4d0/RbQ0gJdgwHiCd1dcCfqsE8iiYVjZG2aGLiu9r54RxIZ5CatWA@Gtlbtq/vsweS55bpGos9Etip3RsXoOY6G@J49BP3Ei4JrhI@kjCpwKaeaRhmiJKYc5miJ6cICp9zdC5p48N3GrWEX0QxCUKgqdujvT9ejcAM/fgCu3dnCu5nbl@ZtvXY3@PBG4cJ3jsdnwoeU@lCaRWlWe3z6UCHuPLBqmAjXnORBa5VjmHrnjieTiXXChzwjEdZrnJL4G2x/hfEd1vkY9kSqQsHGCjbe@G8@9mpUkinS4tUBIRVZ9CgkFYXKKlCpOGA3k@4kMTOEJD4cqE5FYfpcywjySOLcSYmiqoU88v/5dgNuw9Cd6956njdbefVhhD/p1DTr@SktBo4CaeT3CDJdPARD3XVm6cPmz88zzCWjPEJHWyRGWJxXLmr6tRPThY@gDReWj/qYh3Ae9GjeYtRmtHWI@KBsT7Nw3PSEodY3@KwBtYXF8kKTusBO1CSiIfz4KTHZVdAToZ/nQlMJ5Q3znEsiptP4vnw4VzYJthajuni@96ya8l0EvZ1@fdWTvg3WjGfKMTgoTwyE83LcDIGxqZ4iS@CRYJqVMrcCv2Sr9Cv8sosgX9q3FzikNCPudFqdOMWiSgDTS1nB8B7EdVTatSXZt6JDSiTGrkHEcSFPxKcUw8VOM/923cm1lWKnzjp07FHEgrfzZpo0vp/N9g/9PFXrlPYTZU@t/Ob4/RsZq24y0be1HlZ@E0DH9sjT/sSS7V2s1SLr1J2BTmkYzuHjR2DrhVfferymyWxrS9whUiBwcuwyBMEiF0YMREohncv6wVk2UC3mxrSteVk2dUJs8ru9ZwLvt4Sdm8y7YtNF0IwncUBPMsqo7iWimbId7SLPB7UND5m4Kb3BjhiOaDiQjkBTRpTfVuZ5oeNwx1850M4pXVf/ix9NV5z7gfcL/qoBP@oh8e4gyCOlRqcLZKBf7UoSXUhu3Q2cF@f19T8)
```
// Verify an expression for requirement 2
// expression under test
#define E (x=x-(x>>2)),(x=x-(x>>31)),x>>30
#define M 3 // value of m matching that expression
#define T uint32_t // type for x (change at your own risk!)
#define N 32 // number of bits in type T
#define C (T) // cast to type T; use in E only!
#include <stdint.h>
typedef T t; // type for x
#include <inttypes.h>
#if N==32
#define pPRIuTN "%"PRIu32
#define pPRIxTN "%08"PRIx32
#elif N==16
#define pPRIuTN "%"PRIu16
#define pPRIxTN "%04"PRIx16
#elif N==8
#define pPRIuTN "%"PRIu8
#define pPRIxTN "%02"PRIx8
#endif
#include <stdio.h>
#include <string.h>
#define m ((t)M) // m per our type
#define R(z) #z // stringizer
#define S(z) R(z)
t c[m]; // counter array (initialized to 0)
int main(void) {
t fail = sizeof(t)*8!=N || (t)(-1)<0 || ((t)(-1)>>(N-1))!=1,
lo, hi, xlo, xhi, v, x, y = 0;
if (fail)
printf("### fail, please check T: "S(T)" versus N: "S(N)"\n");
else
{
// laboriously show the expression tested, without extra parenthesis
#define LEN (sizeof(S((E)))-3) // length of the expression
char exp[LEN+1]; // the expression, NUL-terminated
memcpy(exp,S((E))+1,LEN);
exp[LEN]=0;
printf("Testing expression %s for m="pPRIuTN"\n",exp,m);
// compute counts
do {
x = y;
x = (E);
if (x<m)
++c[x];
else if (!fail) {
fail = 1;
printf("### fail, value "pPRIuTN" at input x="pPRIuTN"=0x"pPRIxTN" should be less than m="pPRIuTN"\n",x,y,y,m);
}
} while(++y);
// find minimum and maximum count, and where it occurs
hi = xlo = xhi = 0;
lo = (t)-1;
v = m;
do {
y = c[--v];
if (y>hi)
hi = y, xhi = v;
else if (y<lo)
lo = y, xlo = v;
} while(v);
// show results
if (hi==0 && m>1) // can occur if there was overflow or other error
fail=1, printf("### fail, only the value "pPRIuTN" occurs\n",x);
else {
x = (t)(-m)/m+1; // lower limit
y = (t)(-1)/m+1; // upper limit
if (lo<x)
fail=1, printf("### fail, value "pPRIuTN" occurs "pPRIuTN" times, minimum "pPRIuTN"\n",xlo,lo,x);
if (hi>y)
fail=1, printf("### fail, value "pPRIuTN" occurs "pPRIuTN" times, maximum "pPRIuTN"\n",xhi,hi,y);
if (!fail)
printf("### pass!\n");
}
}
return fail;
}
```
[Answer]
# [Haskell](https://www.haskell.org/)
```
import Data.Bits
bitLen :: Int -> Int
bitLen n = finiteBitSize n - countLeadingZeros n
expr' :: Maybe Int -> Int -> String
expr' sh m =
case sh of
Nothing
| m == 1 -> "0"
| n == 0 -> "x" ++ s
| o == 0 -> "x-(x-(x>>1)>>" ++ show (i - j - 1) ++ ")" ++ s
| otherwise ->
"x-(x-(" ++ expr' (Just j) o ++ ")>>" ++ show (i - j) ++ ")" ++ s
where s
| i == 32 = ""
| otherwise = ">>" ++ show (32 - i)
Just h
| n == 0 -> "x>>" ++ show (h - i)
| o == 0 -> "(x-(x>>" ++ show (i - j) ++ ")>>" ++ show (h - i) ++ ")-1"
| otherwise ->
"x-(x-(" ++
expr' (Just j) o ++ ")>>" ++ show (i - j) ++ ")>>" ++ show (h - i)
where
i = bitLen (m - 1)
n = bit i - m
j = bitLen (n - 1)
o = bit j - n
expr :: Int -> String
expr = expr' Nothing
```
[Try it online!](https://tio.run/##lVNNT4NAEL3zK164CGloSo0emsDBeNG0euhNa8y2bmVrdyGwTavpf8fZhVJqMVEC2cybN28@mE1Y8cHX67IUMktzjVumWf9G6MJx5kKPucJohDulEcTmOIAKEZZCCc2JOxVfnJAAi3SjyM3ehHp/4nlaQDkO32X5hVGZsM85b2mZY6pz4tacIoFE5AALVnBjpUsygIdUJ4YF@@wNKUJowt2B26DKoAOL7lz0eigaV9pyBZ554zj047iiJekWnqDyV/SFvsFc/6eCTni@FVRWENcgDmKWWnXg3W8KjZVPGa3KeYou@S1p88Y6PHsIU/blkEbtumfOY0XkPslDEQGEbyNsPUnnjE5ikmPIj4HV4/qljw6RyhGE7p@H12D/HGJ3B3aaVpLmh3pfPWn/rYVVBcNISYusWkR1JKY10exFvcit29BaXeJVpdebWkomqovzCM93rBVBsmzyCm8mTXS20SQwpoS2fGk7mulmlyB9H88h@n0Mr65fym8 "Haskell – Try It Online")
The first few expressions are
1. `0`
2. `x>>31`
3. `x-(x-(x>>1)>>1)>>30`
4. `x>>30`
5. `x-(x-(x>>2)>>1)>>29`
6. `x-(x-(x>>1)>>1)>>29`
7. `x-(x-(x>>1)>>2)>>29`
8. `x>>29`
9. `x-(x-(x>>3)>>1)>>28`
10. `x-(x-(x>>2)>>1)>>28`
11. `x-(x-((x-(x>>2)>>1)-1)>>1)>>28`
12. `x-(x-(x>>1)>>1)>>28`
13. `x-(x-(x>>2)>>2)>>28`
14. `x-(x-(x>>1)>>2)>>28`
15. `x-(x-(x>>1)>>3)>>28`
16. `x>>28`
17. `x-(x-(x>>4)>>1)>>27`
18. `x-(x-(x>>3)>>1)>>27`
19. `x-(x-((x-(x>>2)>>2)-1)>>1)>>27`
20. `x-(x-(x>>2)>>1)>>27`
# C++ template version
```
template <unsigned m> unsigned Rs(unsigned x, unsigned h);
template <unsigned o>
unsigned Rs2(unsigned x, unsigned h, unsigned i, unsigned j) {
return (x - ((x - Rs<o>(x, j)) >> (i - j))) >> (h - j);
}
template <> unsigned Rs2<0>(unsigned x, unsigned h, unsigned i, unsigned j) {
return ((x - (x >> (i - j))) >> (h - i)) - 1;
}
template <unsigned n> unsigned Rs1(unsigned x, unsigned h, unsigned i) {
constexpr unsigned j = bitlen<n - 1>();
constexpr unsigned o = (1 << j) - n;
return Rs2<o>(x, h, i, j);
}
template <> unsigned Rs1<0>(unsigned x, unsigned h, unsigned i) {
return x >> (h - i);
}
template <unsigned m> unsigned Rs(unsigned x, unsigned h) {
constexpr unsigned i = bitlen<m - 1>();
constexpr unsigned n = (1 << i) - m;
return Rs1<n>(x, h, i);
}
template <unsigned o> unsigned R2(unsigned x, unsigned i, unsigned j) {
return (x - Rs<o>(x, j)) >> (i - j);
}
template <> unsigned R2<0>(unsigned x, unsigned i, unsigned j) {
return (x - (x >> 1)) >> (i - j - 1);
}
template <unsigned n> unsigned R1(unsigned x, unsigned i) {
constexpr unsigned j = bitlen<n - 1>();
constexpr unsigned o = (1 << j) - n;
return R2<o>(x, i, j);
}
template <> unsigned R1<0>(unsigned, unsigned) { return 0; }
template <unsigned m> unsigned R(unsigned x) {
constexpr unsigned i = bitlen<m - 1>();
constexpr unsigned n = (1 << i) - m;
return (x - R1<n>(x, i)) >> (32 - i);
}
```
For example, `gcc -O2` generates the following identical code for `R<19>(x)` and `x-(x-((x-(x>>2)>>2)-1)>>1)>>27`:
```
movl %edi, %edx
movl %edi, %ecx
leal 1(%rdi), %eax
shrl $2, %edx
subl %edx, %ecx
movl %ecx, %edx
shrl $2, %edx
subl %edx, %eax
shrl %eax
subl %eax, %edi
movl %edi, %eax
shrl $27, %eax
```
# How it works
The expression being computed is equivalent to \$\left\lfloor \frac{mx + m - c(m)}{2^{32}} \right\rfloor\$, where \$c(m)\$ satisfies \$0 < c(m) \le m\$. The specific choice of \$c(m)\$ made for golfing reasons is
$$
\begin{align\*}
c(2^{i + 2}k + 2^i) &= 1 \quad (k \ge 0, i \ge 0), \\
c(2^i - 2^j) &= 1 \quad (i > j \ge 0), \\
c(2^{h + 1}k + 2^h + 2^i - 2^j) &= 2^h \quad (k \ge 0, h > i > j + 1 \ge 1). \\
\end{align\*}
$$
The equivalence can be shown by repeated use of the identity
$$
-{\left\lfloor \frac{k}{2^i} \right\rfloor} = \left\lfloor \frac{2^i - 1 - k}{2^i} \right\rfloor.
$$
] |
[Question]
[
Write a program or function that:
1. Takes as input a list or array of 128 numbers.
2. Sends that array to a GPU
3. Performs a calculation on the GPU to square each element of the array and then sum them
4. Gets the answer from the GPU, and returns or displays it
So your program will simply return the sum of the squares of its input array, but it will perform the calculation on a GPU.
The input numbers should be sent to the GPU in the form of signed or unsigned integer types or floats, of 32 or more bits in size.
You may make any assumptions you like about hardware, e.g. you may assume a CUDA or OpenCl capable card is present without checking for it.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The smallest code (in bytes) will be considered the winner for each language.
[Answer]
# Processing.org 392 bytes
392 counting the shader and function
It's possible to reduce the number of characters by putting the shader program in a separate file.
```
String[] f={"uniform float x[128];void main(){float s;for(int i=0;i<128;i++)s+=x[i]*x[i];int b=floatBitsToInt(s);gl_FragColor=vec4(b>>16&255,b>>8&255,b&255,b>>24&255)/255.;}"},v={"uniform mat4 transform;in vec4 vertex;void main(){gl_Position=transform*vertex;}"};PShader p;void s(float[]i){p=new PShader(this,v,f);p.set("x",i,1);filter(p);loadPixels();print(Float.intBitsToFloat(pixels[0]));}
void setup(){
size(1,1,P2D);
float[] input = new float[128];
for(int i=0;i<128;i++)input[i]=(float)i;
s(input); // prints 690880.0
}
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/) with [Co-dfns](https://github.com/Co-dfns/Co-dfns), 7 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous prefix lambda. I have verified with [the author of Co-dfns](https://www.patreon.com/arcfide) that the code will indeed run according to the required spec.
```
{+.×⍨⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO96FHbhHCuNCD5qLfvUVez0aO2yY/6pvoFqYerP@puedQ2CaTC4H@1tt7h6Y96Vzzq3VoL0scV/l/drzQ3KbWoWCGxKNVKnQuoC6gyDyIGZB1ab2JgaaZtb2hk8ah3i4WhpRGXenBprkJ@mkJxYSlQTzFQU5oCVAMA "APL (Dyalog Unicode) – Try It Online") (equivalent code, but TIO doesn't provide GPU access)
`{`…`}` compilable dfn; `⍵` is the argument vector
`+.×` dot-product of
`⍨` itself ("selfie")
`⍵` using the argument as data
] |
[Question]
[
I'm (still) trying to make another submission to the [Largest Number Printable](https://codegolf.stackexchange.com/q/18028) question, and I've got the following bit of code:
```
f=->a{b,c,d=a;b ?a==b ?~-a:a==a-[c-c]?[[b,c,f[d]],~-c,b]:b:$n}
h=[],$n=?~.ord,[]
h=f[h]until h==p($n+=$n)-$n
```
Ungolfed:
```
f=->{b,c,d=a
if b
if a==b # a is not an array
return a-1
elsif a==a-[0] # a does not contain 0
t = [b,c,f[d]]
return [t,c-1,b]
else # a is an array containing 0
return b
end
else # if a == []
return $n
end}
$n = 126
h = [[],n,[]]
until h==0 do
$n += $n
p $n
h = f[h]
end
```
The conditions I'm working with:
* Maximum 100 bytes.
* No digits allowed in my code.
My code is currently at 108 bytes, but I can't figure out how to golf it further.
The `h==p($n+=$n)-$n` may be replaced with `h==0`, but I can't use digits and I still need to print `$n` and apply `$n+=$n` in the `until` loop.
I'm also satisfied with code that replaces `$n+=$n` with `$n+=1`, but I can't use digits unfortunately.
Any suggestions?
[Answer]
# 105
You can save three bytes by declaring `n` as a local variable (instead of a global) before `f`:
```
n=?~.ord
f=->a{b,c,d=a;b ?a==b ?~-a:a==a-[c-c]?[[b,c,f[d]],~-c,b]:b:n}
h=[],n,[]
h=f[h]until h==p(n+=n)-n
```
[Answer]
# 100 bytes
For my purposes, this is good enough.
```
h=[],n=?~.ord,n
f=->a{b,c,d=a;b ?a==b ?~-a:a==a-[c-c]?[[b,c,f[d]],~-c,b]:b:p(n+=n)}
h=f[h]until h==n
```
Replacing `h==0` with `h==n` will not cause the program to fail to terminate, which is what I needed.
Also improves on Jordan's answer by declaring `h` and `n` in the same line.
] |
[Question]
[
Let us consider a regular n-sided polygon where all of the sides are equal in length with n being a natural number larger than or equal to three. All of the vertices lie on the unit circle (circle of radius one centered at the origin) and one of the vertices is always at the coordinate (x,y)=(1,0). Now let's draw all possible diagonals (including the edges) which connect all n vertices to one another. Here is an example for n=11.
[](https://i.stack.imgur.com/zfyRV.jpg)
This results in n-choose-2 (which is just n(n-1)/2) lines (diagonals and edges) which in this case is 55. The total number of line intersections, counting the interior intersection points as well as the n vertices, will be denoted I and I=341 in this case.
## The Goal
Your goal is to write a full program or a function which takes in an integer n larger than or equal to three and outputs a list of (x,y) coordinates of all of the intersections of all of the diagonals and edges, that are contained within the regular n-sided polygon with one of its vertices being at (1,0). This includes the n vertices themselves which lie on the unit circle. The length of this list must be I. There is an OEIS sequence for I, which is [A007569](https://oeis.org/A007569) and here is a [paper](https://arxiv.org/pdf/math/9508209v3.pdf) which talks about it.
## Rules and Specifications
1. [Standard loopholes are forbidden.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
2. Each coordinate has to be an ordered 2-tuple, giving the (x,y) coordinates in the Cartesian system.
3. The list of coordinates can be in any order. It doesn't have to be sorted or in any particular order.
4. All of the coordinates provided must be accurate to at least six [significant figures](https://en.wikipedia.org/wiki/Significant_figures). I am not specifying a rounding method. You are free to choose any rounding method or to simply chop off a number. Also for n large enough, it will be the case that two distinct intersections (in exact arithmetic) will be equal to each other to six significant figures in both coordinates (in floating point arithmetic). In this case you are free to treat them as the "same" and remove the "duplicates" from your list. The length of your list will be less than I, but oh well!
5. The coordinates can be in decimal or scientific notation. For small enough n, decimal notation is fine and decimal notation will make it easier to check so it is preferred. But I am not mandating one over the other.
6. Outputting I, which should be the length of your coordinate list, is not a requirement for this task. You don't have to output it.
You can assume whatever input/output form that is appropriate for your language. You can also assume that the input will always be a positive integer greater than or equal to three. In case of any other input, your program is free to do whatever it wants. You can also assume that the input and output will always be in the numerical range of your language/environment. Trailing newlines are okay in the output.
## Some Test Cases
I am showing more significant digits here than I need to. You are only required to show six. Remember, you don't have to print I.
```
n => 3
I => 3
(1.000000000,0)
(-0.5000000000,0.8660254038)
(-0.5000000000,-0.8660254038)
n => 4
I => 5
(1.000000000,0)
(0,1.000000000)
(-1.000000000,0)
(0,0)
(0,-1.000000000)
n => 5
I => 10
(1.000000000,0)
(0.3090169944,0.9510565163)
(-0.8090169944,0.5877852523)
(-0.1180339887,0.3632712640)
(0.3090169944,0.2245139883)
(-0.8090169944,-0.5877852523)
(0.3090169944,-0.2245139883)
(-0.1180339887,-0.3632712640)
(0.3090169944,-0.9510565163)
(-0.3819660113,0)
n => 6
I => 19
(1.000000000,0)
(0.5000000000,0.8660254038)
(-0.5000000000,0.8660254038)
(0,0.5773502692)
(0.2500000000,0.4330127019)
(0.5000000000,0.2886751346)
(-1.000000000,0)
(0,0)
(0.5000000000,0)
(-0.5000000000,0)
(-0.5000000000,-0.8660254038)
(0.5000000000,-0.2886751346)
(0.2500000000,-0.4330127019)
(0,-0.5773502692)
(0.5000000000,-0.8660254038)
(-0.5000000000,0.2886751346)
(-0.2500000000,0.4330127019)
(-0.2500000000,-0.4330127019)
(-0.5000000000,-0.2886751346)
n => 7
I => 42
(1.000000000,0)
(0.6234898019,0.7818314825)
(-0.2225209340,0.9749279122)
(0.1539892642,0.6746710485)
(0.3215520661,0.5410441731)
(0.4559270000,0.4338837391)
(0.6234898019,0.3002568637)
(-0.9009688679,0.4338837391)
(-0.05495813209,0.2407873094)
(0.3215520661,0.1548513136)
(0.6234898019,0.08593599577)
(-0.5244586698,0.3479477434)
(-0.2225209340,0.2790324255)
(0.1539892642,0.1930964297)
(-0.9009688679,-0.4338837391)
(0.1539892642,-0.1930964297)
(0.6234898019,-0.08593599577)
(-0.2225209340,-0.2790324255)
(0.3215520661,-0.1548513136)
(-0.5244586698,-0.3479477434)
(-0.05495813209,-0.2407873094)
(-0.2225209340,-0.9749279122)
(0.6234898019,-0.3002568637)
(0.4559270000,-0.4338837391)
(0.3215520661,-0.5410441731)
(0.1539892642,-0.6746710485)
(0.6234898019,-0.7818314825)
(-0.4314683302,0.5410441731)
(-0.2225209340,0.5887350528)
(-0.05495813209,0.6269801688)
(-0.2225209340,0.1071604339)
(0.07941680185,0.3479477434)
(-0.5990311321,-0.1930964297)
(-0.3568958679,0)
(0.2469796037,0)
(0.07941680185,-0.3479477434)
(-0.05495813209,-0.6269801688)
(-0.6920214716,0)
(-0.5990311321,0.1930964297)
(-0.2225209340,-0.1071604339)
(-0.2225209340,-0.5887350528)
(-0.4314683302,-0.5410441731)
```
I can provide more test cases but they will take up a lot of space and I am not sure how to provide them here. Let me know if you guys need more cases and what is the best way for me to provide them.
## Scoring
This is code-golf. The answer with the smallest byte-count will win. In case of a tie, I will pick the answer that was posted earlier as the winner.
Please post your answer in the standard format with all compiler/interpreter options/flags.
[Answer]
# Python 3, 211 204 bytes
```
from itertools import*
C=combinations
lambda n:{(round(z.real,6),round(z.imag,6))
for z in[(a*b*c+a*b*d-a*c*d-b*c*d)/(a*b-c*d)
for(a,b),(c,d)in C(C([23.140693**(2j*k/n)for k in range(n)],2),2)]
if abs(z)<=1}
```
For readability I've added superfluous newlines in my answer that aren't included in the bytecount.
If we have a line crossing through points *a* and *b*, and another line crossing through points *c* and *d*, where *a, b, c, d* are complex numbers, then the intersection between those lines (not segments!) is
[](https://i.stack.imgur.com/mShoc.png)
But for a point *u* on the unit circle, the conjugate of *u* is *1/u*. Then the formula simplifies to:
[](https://i.stack.imgur.com/ROTRP.png)
Now, if the intersection of the two lines also lies within the unit circle, that's a proper intersection of the diagonals.
[Answer]
# Mathematica ~~165 143~~ 112 bytes
53 bytes saved by Misha Lavrov!
22 thanks to his suggestion to use `Cases` instead of `Select`.
31 additional bytes saved thanks to his suggestion to use `CirclePoints`.
```
(s=Subsets;Union@Cases[RegionIntersection@@@s[Line/@s[N[{1,Pi/2}~CirclePoints~#,8]&@#,{2}],{2}],Point@{x_}:>x])&
```
---
`Table[{Cos[Pi/2+(2k Pi)/# ],Sin[Pi/2+(2k Pi)/# ]},{k,0,#-1}]` generates the coordinates of the vertices of a regular polygon (inscribed in the unit circle) with one vertex at `(0,1)`.
Line segments are then defined for each subsets of possible pairs of those coordinates.
`RegionIntersection` finds a point of intersection for each pair of these line segments (iff such intersection exists).
`Cases[... Point@{x_} :> x]` returns the coordinates. Cases in which two segments do not intersect are ignored.
`Union` eliminates possible duplicates.
---
**Example** (n=7)
```
(s = Subsets;
Union@Cases[
RegionIntersection @@@s[Line /@s[N[{1, Pi/2}~CirclePoints~#&@#, {2}], {2}],
Point@{x_} :> x]) &[7]
```
{{-0.974928, -0.222521}, {-0.781831, 0.62349}, {-0.674671,
0.153989}, {-0.62698, -0.0549581}, {-0.588735, -0.222521}, \
{-0.541044, -0.431468}, {-0.541044,
0.321552}, {-0.433884, -0.900969}, {-0.433884,
0.455927}, {-0.347948, -0.524459}, {-0.347948,
0.0794168}, {-0.300257,
0.62349}, {-0.279032, -0.222521}, {-0.240787, -0.0549581}, \
{-0.193096, -0.599031}, {-0.193096, 0.153989}, {-0.154851,
0.321552}, {-0.10716, -0.222521}, {-0.085936,
0.62349}, {0., -0.692021}, {0., -0.356896}, {0., 0.24698}, {0.,
1.}, {0.085936, 0.62349}, {0.10716, -0.222521}, {0.154851,
0.321552}, {0.193096, -0.599031}, {0.193096,
0.153989}, {0.240787, -0.0549581}, {0.279032, -0.222521}, {0.300257,
0.62349}, {0.347948, -0.524459}, {0.347948,
0.0794168}, {0.433884, -0.900969}, {0.433884,
0.455927}, {0.541044, -0.431468}, {0.541044,
0.321552}, {0.588735, -0.222521}, {0.62698, -0.0549581}, {0.674671,
0.153989}, {0.781831, 0.62349}, {0.974928, -0.222521}}
```
Graphics[{PointSize[Large], Blue, Point@%}, Axes -> True]
```
[](https://i.stack.imgur.com/8ouYE.png)
] |
[Question]
[
Using named matching groups is often easier to understand than numbering groups but takes up more bytes. Given a regular expression as specified below, your program or function must convert named groups to numbered groups.
## Task
These specifications are based on python 3's re module.
A named group takes the form of `(?P<name>...)` where `name` is replaced with the name of the group and `...` is a valid regex.
A reference to a named group takes the form of `(?P=name)` where `name` is replaced with the name of the group.
A numbered group takes the form of `(...)` where `...` is a valid regex.
A reference to a numbered group takes the form of `\number` where `number` is replaced with the number of the group as follows:
>
> groups are numbered from left to right, from 1 upward. Groups can be nested; to determine the number, just count the opening parenthesis characters, going from left to right.
> [(Python howto)](https://docs.python.org/3/howto/regex.html#grouping)
>
>
>
The number of opening parentheses characters includes the group's opening parenthesis.
Thus your program or function must, given a *valid* regular expression, convert named groups to numbered groups and references to named groups to references to numbered groups with the right number.
## Example
The input is `s(tar)+t(?P<name1>subre)cd(?P=name1)`. The `(?P=name1)` bit refers to the capturing group `(?P<name1>subre)`. It is group `2` because the string `s(tar)+t(` contains two opening parentheses. Thus `(?P=name1)` is replaced with `\2` to get `s(tar)+t(?P<name1>subre)cd\2`
The `(?P<name1>subre)` group can be converted to a non-named group by simply removing the name and identification to get `(subre)`. Applying this into the string so far yields `s(tar)+t(subre)cd\2`. Since there are no named groups nor named references, the program is done and outputs `s(tar)+t(subre)cd\2`.
## Rules
* There are no non-capturing groups in the input regular expression (in other words, all groups are either numbered or named).
* You may assume that all input groups are named.
* Any further pedantics due to technical specifications of regular expressions should be ignored.
+ The input will always contain no digits directly after named backreferences.
+ Every reference to a named group in the input will have an actual named group to reference to.
+ All parentheses in the input delimit a group
+ The group names will contain no spaces.
* The output may optionally have a trailing newline.
* Brownie points for solving this challenge using a regular expression!
## Remember Defaults:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code **in each language** wins.
* Of course, [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default?answertab=votes#tab-top) are forbidden.
* The input and output should be taken in [standard I/O methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
## Test Cases
```
Input
Output
-----
this has no* groups \bubbles
this has no* groups \bubbles
-----
this has (?P<name>named)+ groups (?P=name)
this has (named)+ groups \1
-----
this has no(?P<references> sadness*)?
this has no( sadness*)?
-----
I need (?P<reference> very+ much) here is one: (?P=reference)
I need ( very+ much) here is one: \1
-----
t(?P<one>o)n(?P<another>s) of (?P<groups>named) groups (?P=another) (?P=one) (?P=groups)
t(o)n(s) of (named) groups \2 \1 \3
-----
Of course, we need (?P<moregroups>misdirection) (?P<n>n(?P<e>e(?P<s>s(?P<t>t)i)n)g) (?P=n)n(?P=e)e(?P=s)s(?P=t)ing
Of course, we need (misdirection) (n(e(s(t)i)n)g) \2n\3e\4s\5ing
-----
(?P<Lorem>Lorem ipsum dolor sit amet), (?P<consectetur>consectetur adipiscing elit), (?P<sed>sed do eiusmod tempor incididunt ut labore et dolore magna aliqua). (?P<Ut>Ut enim ad minim veniam, (?P<quis>quis) nostrud exercitation ullamco laboris nisi ut (?P<aliquip>aliquip ex ea commodo consequat.)) Duis aute irure dolor in (?P<finale>reprehenderit in voluptate velit esse cillum dolore eu fugiat (?P<null>null)a pariatur. (?P<Except>Excepteur (?P<sin>sin)t occae(?P<cat>cat) )cupidatat non proident, sunt) in culpa qui officia deserunt mollit anim id est laborum. (?P=cat)(?P=sin)(?P=Except)(?P=null)(?P=finale)(?P=aliquip)(?P=quis)(?P=Ut)(?P=sed)(?P=consectetur)(?P=Lorem)
(Lorem ipsum dolor sit amet), (consectetur adipiscing elit), (sed do eiusmod tempor incididunt ut labore et dolore magna aliqua). (Ut enim ad minim veniam, (quis) nostrud exercitation ullamco laboris nisi ut (aliquip ex ea commodo consequat.)) Duis aute irure dolor in (reprehenderit in voluptate velit esse cillum dolore eu fugiat (null)a pariatur. (Excepteur (sin)t occae(cat) )cupidatat non proident, sunt) in culpa qui officia deserunt mollit anim id est laborum. \11\10\9\8\7\6\5\4\3\2\1
```
(Above, I was referring to numbered groups as being disjoint from named groups, when [named groups are also numbered](https://regex101.com/r/wXjKD2/1). Pretend that I meant non-named groups when I said numbered groups.)
[Answer]
## JavaScript (ES6), 91 bytes
```
f=
s=>s.replace(/\(\?P=(\w+)\)|\(\?P<(\w+)>|\(/g,(_,b,n)=>b?`\\`+r[b]:(r[n]=++c,`(`),c=0,r={})
```
```
<textarea cols=30 rows=5 oninput=o.textContent=f(this.value)></textarea><div id=o>
```
[Answer]
# [PHP](https://php.net/), 198 bytes
```
preg_match_all("#\(\?P<.+?>|\(\?P=.+?\)|\(#",$a=$argn,$t);foreach($t[0]as$x)$x[1]?$x[3]=="<"?$a=strtr($a,[$x=>"("]).!$n[substr($x,4,-1)]=++$k:$a=strtr($a,[$x=>"\\".$n[substr($x,4,-1)]]):++$k;echo$a;
```
[Try it online!](https://tio.run/##bVI9bxsxDN37K9jLDRbiGg3aKc6dl3br0CWTbQSMjraJ6iv6CDz0v7uUzgECpIPEpzuK7/GJ4RQuD5twCp96jEc3dIvN74dfPpId2w4cUrEweeMjJM6AlrJaQk3T3iXSmXKJ4zsMOHHgpNkdgQy/ZSeaRllSCohLsn6CTDZIWXaaJ56Ky1AyGHwWYqA8kxJYPDoENPxSUK1arcc8PmYgx1bIwHIFr3JEO3O9FE5j3RQ4n3IsE9CZouaMmb2DYgxa7WcuTuA4ceWudxsRh/Ea5SIQgvZWFHtofYqQvFIKfggDYMkEHIsonV1i1@oc2KGhMVKIdCI3URT35N@rNyWIDhLF4g5QSgSajXmzWXovcChHxlmQE7Vj3RRCwCifS5xt@HnWFPI4BxLnm8/sRlkqg9caqT0U5lGWAqVL4AmFXXxxEKLniVxeQhLzVVWniwkI0jj4w4E1I0yUKNa3sd5UvVjNZjE0Xd@q2KZmqAw1VvIaZ1kNNvUVzKY0ePW34fZUFTxeS9DU4rupauc2kqpbX8TT45PFrE9PaMyiu9ktdtLo6nYz/m1wELhTgm@6ZY9DG@5ln9X6ICVQnxZ93n7dY@rPqj9v7/Yb2b/th6F76DaSLzOT46LH5bY/D2O36PZq9bl321SeU/1xXn5ffrlT@@H2tv9z//HCbtet/pO@V/f1wpr0yfe4vlz@AQ "PHP – Try It Online")
] |
[Question]
[
# Background
A [rooted tree](https://en.wikipedia.org/wiki/Tree_(graph_theory)#Rooted_tree) is an acyclic graph such that there is exactly one path from one node, called the root, to each other node. A node `v` is called the *parent* of another node `u` if and only if the path from the root to `u` goes through `v` and there is an edge connecting `u` and `v`. If node `v` is the parent of node `u`, node `u` is a *child* of node `v`.
# Task
Write a program or function that, given a positive integer number of nodes and a set of non-negative integer numbers of children each parent has, outputs the number of possible rooted trees with that number of nodes (including the root) and each vertex having a number of children in the set, not counting those trees [isomorphic](https://codegolf.stackexchange.com/questions/63535/are-these-trees-isomorphic) to trees already found.
Two trees are isomorphic if one can be transformed into another by renaming the nodes, or in other words look the same when the nodes are unlabelled.
# Examples
We shall represent trees as a 0-indexed list of children per index where 0 represents the root, for example `[[1],[2],[]]` represents that the root `0` has `1` as a child, node `1` has node `2` as a child, and node `2` has no children.
Inputs `n=3` and set = `[0,1,2]`. This is equal to binary trees with three nodes.
The two possible trees are: `[[1],[2],[]]` and `[[1,2],[],[]]`. Because they are identical in structure to the two trees, we count neither `[[2],[],[1]]` nor `[[2,1],[],[]]`. There are two trees, so the output is `2` or equivalent.
Here is a visualization: [](https://i.stack.imgur.com/fqmLc.png) You can see that the second set of two trees are identical in structure to the first set of two and are thus not counted. Both sets are composed of two trees which have one of the following two structures (the root is the node at the top):
[](https://i.stack.imgur.com/hwUwR.png)
---
Inputs `n=5` and set=`[0,2]`. The only possible tree is `[[1,2],[3,4],[],[],[]]`. Note that, for example, `[[1,2],[],[3,4],[],[]]` and `[[1,3],[],[],[2,4],[]]` are not counted again because they are isomorphic to the sole tree which is counted. The output is `1` or equivalent.
Here is another visualization:
[](https://i.stack.imgur.com/VAq8n.png)
Clearly, all of the trees are isomorphic, so only one is counted. Here is what the trees look like unlabeled:
[](https://i.stack.imgur.com/ggftu.png)
---
Input `n=4`, set=`[0,2]`. There are no possible trees because each time children are generated from a node, there are either `0` or `2` more nodes. Clearly, 4 nodes cannot be produced by adding `2` or `0` successively to `1` node, the root. Output: `0` or falsey.
# Input/Output
Input and output should be taken in a [reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
Input is a positive integer representing `n` and a list of non-negative integers representing the set of valid numbers of children.
The output is a non-negative integer corresponding to how many trees can be formed.
# Test cases
```
n ; set ; output
3 ; [0,1,2] ; 2
5 ; [0,2] ; 1
4 ; [0,2] ; 0
3 ; [0,1] ; 1
3 ; [0] ; 0
1 ; [0] ; 1
6 ; [0,2,3] ; 2
7 ; [0,2,3] ; 3
```
# Rules
* The set of numbers of children will always include zero.
* The root node always counts as a node, even if it has no children (see the `1; [0]` test case)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins.
[Answer]
# [Haskell](https://www.haskell.org/), 120 bytes
```
_#0=1
i#j=div(i#(j-1)*(i+j-1))j
s!n|let(0?1)0=1;(0?_)_=0;(m?n)c=sum[s!m#j*((m-1)?(n-j*m)$c-j)|j<-[0..c]]=sum$(n-1)?n<$>s
```
[Try it online!](https://tio.run/##bcxNDoIwEAXgPacoKYsZBNKKPwuoHIQQQoDEVlqNRVfcHYs7lNVMvnlvro299cMwzzVlgnuSKtHJN0gKKuYYgtwtE5VnfTMN/Qis4OiSmVtqrAXLQBcGW2FfurS@pioE0K5SgIlVqDFoY4WTyuOSJUlbVUswcDeXMHlwsbNupCGCdHePkMdTmpFAySIe7SvikxRX@rXjhh3Wxv@728J/fkXpoqdNPeP8AQ "Haskell – Try It Online")
### How it works
`i#j` is `i` [multichoose](http://mathworld.wolfram.com/Multichoose.html) `j`.
`(m?n)c` is the number of `n`-node trees with `c` children at the root, each of which has a subtree of at most `m` nodes. It’s computed by summation over `j`, the number of these subtrees that have exactly `m` nodes.
`s!n` is the number of `n`-node trees. It’s computed by summation over `c` ∈ `s`, the number of children at the root.
[Answer]
# Pyth, 47 bytes
```
.N?Nsm*/.P+tyNdd.!d:tN-T*dN-YdhY!|tTYLs:LtbbQyE
```
[Try it online](https://pyth.herokuapp.com/?code=.N%3FNsm%2a%2F.P%2BtyNdd.%21d%3AtN-T%2adN-YdhY%21%7CtTYLs%3ALtbbQyE&input=%5B0%2C2%2C3%5D%0A7)
A port of my [Haskell answer](https://codegolf.stackexchange.com/a/125160), but it’s much faster in Pyth thanks to Pyth’s free automatic memoization. I had to work around a [bug in Pyth’s binomial coefficient builtin](https://github.com/isaacg1/pyth/pull/231), though.
[Answer]
# [Python](https://docs.python.org/2/), 127 bytes
```
lambda*x:len(g(*x))
g=lambda n,s,d=0:[[]][n-1:d in s]or[[t]+u for c in range(1,n)for t in g(c,s)for u in g(n-c,s,d+1)if[t]+u>u]
```
[Try it online!](https://tio.run/##TY/LDoIwEEXX8hVdtjgkFHwkTfBHahfIo5LgQFpI8OsrBVF259y5M8n07@HZYeLq7O7a/PUo83ASbYVU03BiLNDZmhIEC2UWCymVkhhxUZIGiVWdkXJQx5HUnSGFz0yOuqIckPlo8JGmBdhFx1UxKvy9I2dNvazfRuX83AL6hgyojIFDoiBlsMiM5z@evsh/hR3wrQepgstertvapkoEh940OJCazi8y9wE "Python 2 – Try It Online")
The function `g` enumerates trees, and the main function counts them.
Each tree is recursively generated by splitting the requiring number of nodes `n` between `c` nodes in the first branch `t`, and `n-c` nodes in the remaining tree `u`. For a canonical form up to isomorphism, we require the branches to be sorted in decreasing order, so `t` must be at most the first element of `u` is `u` is non-empty. This is enforced as `[t]+u>u`.
We count the number of children `d` so far of the current node. When only one node `n=1` is left, is must be the current node and there's no more node for children. If the current number of children `d` is valid, this level can be finished successfully, so we output a singleton of the one-node tree. Otherwise, we've failed and output the empty list.
] |
[Question]
[
## Challenge
Find the oxidation states of each of the atoms in a given molecule. These can be output as a list or otherwise.
## Rules
The total oxidation state of a molecule will always be zero. **The total oxidation state is the sum of the oxidation states of each of the individual atoms in the molecule**.
The following atoms have constant oxidation states:
* Hydrogen, `H`, always has state **+1**
* Oxygen, `O`, always has state **-2**
* All Group 1 elements have a state **+1**
* All Group 2 elements have a state **+2**
* Fluorine, `F`, always has state **-1**
* Chlorine, `Cl`, always has state **-1**
In monatomic molecules (such as `H2` or `S8`), all of the atoms always have a state **0**. I.e. (`H2` is `0, 0` and `S8` is `0, 0, 0, 0, 0, 0, 0, 0`)
The Group 1 elements are: `Li, Na, K, Rb, Cs, Fr`. The Group 2 elements are: `Be, Mg, Ca, Sr, Ba, Ra`.
You will be able to work out the states of every atom in the molecule given. There will be no ambiguous inputs (i.e. you won't be given `H2O2` or `P4Br6`).
You should output the oxidation states of the individual atoms, not the total state.
If there is an element which is not listed in the list above in the molecule, you need to work out its oxidation state yourself since the sum of the oxidation states of all the atoms adds up to zero.
The molecules do not have to exist in real life.
You will never get a single atom such as `Ti` or `F`.
Built-in functions which access data about oxidation states are disallowed.
## Examples
```
Input > Output
H2O > +1, +1, -2
CO2 > +4, -2, -2
CH4 > -4, +1, +1, +1, +1
H2SO4 > +1, +1, +6, -2, -2, -2, -2
NaHCO3 > +1, +1, +4, -2, -2, -2
XeF8 > +8, -1, -1, -1, -1, -1, -1, -1, -1
TiCl2 > +2, -1, -1
P4 > 0, 0, 0, 0
```
## Winning
The shortest code in bytes wins.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~288~~ 255 bytes
```
->m{h={[?O]=>-2,%w[F Cl]=>-1,%w[H Li Na K Rb Cs Fr]=>1,%w[Be Mg Ca Sr Ba Ra]=>2};a=m.scan /([A-Z][a-z]*\d*)/;r=a.flat_map{|(b)|b=~/(\D+)(\d*)/;[a.size==1?0:h[h.keys.find{|v|v.include?$1}]]*($2=='' ? 1:$2.to_i)};r.map{|j|j||-((r-[p]).inject:+)/r.count(p)}}
```
[Try it online!](https://tio.run/nexus/ruby#VVFdT4NAEPwrm1rD0ZaroFHT5koshpCoxbQ@GK@kuQKVq3wFjqoF/OsV8Mnsw@zszGw22eSLe0zwJN7kggkfCJyUWVQGpKS67ZCZoo3OP6kJRtgStSUWPHJYMHiA5RaMHMyskTpl7sPTOxgMVhnMGSxZI2j1lJEI5y6LYYzonfLmUKYcncHaG8jjaUYY3oVMbCKWlhXaytWW/IzR@n4ooz8HZTjnR58QVb@YBDTAH/53jnc89srqUB0wj92w8Hy9r9aOM0B9jRBJAh3USV/DItlwuZ5muFu/b6pSEMoUmjpyk9z7rpgM5XGG3aSIBUrluj5RkCzNlkYgGbbWgXXVgqWt7K5ZMMuwL9vu1TdvW3zhRthZnzuDqWrWdZMFB/vMDaCEKqogLUQOvRmclVF7V47DfZELdCPXzSj5/wcaOXUP6tMv "Ruby – TIO Nexus")
* Saved 1 byte thanks to [Jenkar](https://codegolf.stackexchange.com/users/69467/jenkar)
* Saved 32 more bytes by inlining definitions and removing parentheses
**Ungolfed**
```
oxidation_state = -> molecule {
h = {
%w[H] => 1,
%w[O] => -2,
%w[F] => -1,
%w[Cl] => -1,
%w[Li Na K Rb Cs Fr] => 1,
%w[Be Mg Ca Sr Ba Ra] => 2,
}
find_oxidation = -> a {
k = h.keys.find { |as| as.include?(a) }
h[k]
}
atoms = molecule.scan(/([A-Z][a-z]*\d*)/)
r = atoms.flat_map { |(a)|
a.match(/([^\d]+)(\d*)/)
[atoms.length == 1 ? 0 : find_oxidation[$1]] * ($2=='' ? 1 : $2.to_i)
}
r.map { |j|
sum = r.compact.inject(:+)
!j ? -sum / r.count(nil) : j
}
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 245 bytes
```
->m{h={[?O]=>-2,%w[F Cl]=>-1,%w[H Li Na K Rb Cs Fr]=>1,%w[Be Mg Ca Sr Ba Ra]=>2};a=m.scan /([A-Z][a-z]*\d*)/;r=a.flat_map{|(b)|b=~/(\D+)(\d*)/;[a[1]?h[h.keys.find{|v|v.include?$1}]:0]*[1,$2.to_i].max};r.map{|j|j||-((r-[p]).inject:+)/r.count(p)}}
```
[Try it online!](https://tio.run/nexus/ruby#VVBdT4NAEPwrm1rToy1XQaOmDW0shpCoxbQ@GK@XZgtUqHwFjloF/OsV8Mnsw@zszGw2Gx99B4UfR5tMoHBBg5M8DQtPK9jM4tpUVofnn8wAPWiI0hATHn1YIDzAcgt6BkZaS60yd@HpHXSEVQpzhCXWglpNUAtpZmMEI8Lu5DfOUP7m/bXTl0aTVEO6C1BsQkyKkmylcqv9jMj6fiCRPwdDpvCZxzz64X5ldOdHTlEeygP1IzvIHXfWVSo@vuB9pgy7KhXxxuc0xGM1SWm7dF9XKROSyizhUh3bu7YYD6RRSu04jwRJpKo6MeiZqtUbQk@31BbMqwZMdWW1zQJN3bpsulfXuG3wxdeD1vrcGgxFNa/rLHDqou1BAWVYQpKLDDpTOCvC5raMBvs8E@RGqupR/P/7LORVB6rTLw "Ruby – TIO Nexus")
As I prepare this post, with a ton of optimizations, [sudee's answer](https://codegolf.stackexchange.com/questions/122005/find-the-oxidation-states/122035#122035) gets an update xD
Which reduces my changes to two :
* `a.size==1` becomes `a[1]` with an inverted consequence. This is because we know that the string is well formed and so `a.size != 0`
* `($2=='' ? 1:$2.to_i)` becomes `[1,$2.to_i].max`
Both of these save 5 bytes.
[Answer]
# [Python 3](https://docs.python.org/3/), 272 bytes
```
s=input()+'A';n='';l=[1]
for i in s:
if'Z'<i:l[-1]+=i
elif'9'<i:l+=[l.pop()]*int(n or 1)+[i];n=''
else:n+=i
i=lambda s:s.split().count
l=[i('Li H Na K Rb Cs Fr')(s)+i('Be Mg Ca Sr Ba Ra')(s)*2-i('F Cl O O')(s)for s in l[1:-1]]
print([k or-sum(l)//l.count(0)for k in l])
```
[Try it online!](https://tio.run/nexus/python3#JY67bsMgFIZ3nuJsQCw7oUOlOmVoLEWRerGUbkUMpHWqo5xgZOznd4Gu//Vbo0YfllnIir/wvdec70kbZdl1nAABPcSWAV75F3/GlkytbKWRwUBJeypapQ01YQxC2g36WXhIVSUrg7YM5nAcWp97qMndLz8urcYmBsL03HyPi59ZukXB3xBO8OHgFc4X6CIcJy5FlFWyDgO8/0Ln4HOCg4OzK87moU7eETqCHvoiZfSY0cmoNgFbFqYMZm6JrI7LXZDcbun/V@xK/lbyVq5r93hSu/4P "Python 3 – TIO Nexus")
] |
[Question]
[
I used to play a game while I was in the car, it consisted in taking the `n-1` first numbers of another car plate and use operators and roots on them to get the `n`th number of the plate.
I could use the following operators and roots :
* addition (ex: 1 + 1 = 2)
* subtraction (ex: 2 - 4 = -2)
* division (ex: 10 / 2 = 5) (Note that the division is only allowed if it returns an integer)
* multiplication (ex: 7 \* 7 = 49)
* square root (ex : sqrt(36) = 6) (Note : must return an integer to be used)
* cubic root (ex : cbrt(8) = 2) (Note : must return an integer to be used)
* multiplication by -1 (ex : 8 \* -1 = -8)
* power 2 (ex : 2² = 4)
* power 3 (ex : 2^3 = 8)
* leave the integer as it was (ex : 3 = 3)
The operations must be done in order! Which means you have to do the operations between the first and the second integer before an operation between the second and the third.
Example : you can do `(3 + 9) * 4` but not `3 + 9*4` if you have `[3,9,4,x,y,z,...]` as input
Moreover, you can use a unary operator on an integer before doing an operation.
Example : you can do `3² - 7^3`
But powers and roots are only allowed on one integer and not on the results of previous operations.
Example : you're not allowed to do `(3+7)²`
Note that multiplication and division are done that way : it's the applications of the previous operations that's multiplied or divided. For instance :
`[x,y,z,t,h] => (x+y)/z + t`
`[x,y,z,t,h] => (x-y+z) * t`
**YOUR TASK**
Your code will take as input an array of integers of size `n`, the `n-1` first integers will be the one used to obtain the `n`th number of the array.
You may use all the operators,roots and powers allowed by the rules above. Remember the integers must stay in the same orders to do the operations!
Your code will output a falsey value or an error if the `n`th number of the array cannot be obtained with the `n-1`first numbers of the array. On the other hand, if you can obtain the `n`th number you have to display the operations that led to it. Your code needs to output only one way of obtaining the `n`th number.
**TEST CASES**
(Note that I write square root sqrt and cube root cbrt but you can write it the way you want : x\*\*(1/3) for instance)
`[1] => error or 1`
`[2,8] => 2^3`
`[3,7,46] => 3*(-1) + 7²`
`[1,2,3,4] => 1*(-1) + 2 + 3`
`[0,0,0,0,0,0,0,8] => error`
`[7,4,3,8,16] => 7 + 4² - 3² + cbrt(8)`
`[28,4,8,7,5,1] => (28 - 4² - cbrt(8) - 7 ) / 5`
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), thus the shortest answer in bytes wins!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~797~~ ~~547~~ ~~527~~ ~~515~~ ~~504~~ 503 bytes
```
s=eval("[('N,'%sN*-1,'(-%s)N*n,'%s^2N**3,'%s^3N**.5,'s(%s)N**(1./3),'c(%s)N+m,'%s+%sN-m,'%s-%sN*1./(m or.1),'(%s)/%sN*m,'(%s)*%s'),]".replace("N","'),(lambda n,m=0:n"))
P=__import__("itertools").product
def f(l):
r=l.pop();L=len(l)
for S in P(s[1:7],repeat=L):
if any(s.index(x)>y<2for x,y in zip(S,l))<1<=L:
for D in P(s[7:],repeat=L-1):
I,J=zip(*map(lambda((a,b),l):(a(l),b%l),zip(S,l)));R=I[0];C=J[0];e=0
for a,b in D:I,J=I[1:],J[1:];R,C=a(R,I[0]),b%(C,J[0]);e=R%1or e
if e<(R==r):return C
```
[Try it online!](https://tio.run/##dZDBbqMwEIbP5SkQEmJMBxpDu4lIvJf0kihCFT1GbOQkjhYJDDJ0lezLZ8fsbpseKiQz/pnvG5vuMvxsdXK99kL9kjV4WwhyDPw@DyOOAUR@z/JQ2@RHkodhOlYpVfETBj2Mn0Pg8UPKMDiM@/vGNt2TIxqryNqoAxq3NTGnPtv2YNPmbx36fcCw9GKjuloeFHi5hx5FUMtmf5SuxkZMMu0x5ryI3a5qutYMux141aDM0LZ177G4M@3x7TA4R3VyT1CzzHGNqOOu7YDNN6JWmkLHPbXGfXUr7b5Av@XZtESaquQgNkTcVSdX6gv0caWP6gxn9v2ySCxyxouFflcdvGLN2IIvxIaA0ff83zfNPnQRt8K7Fa6FpcJGdv/uAyBxz8iSgaQz4d6n5d3M5oVYbSflfCnW9qXEhDR2DFF20HNmnSs6fIlru84LXAoJBVrM6mCJFmXEFj4nUpGBrqYWUAhhWGbU8Ga0u7x2ptID/a4tL5nzvklwdrtNcYqP324Tjgmm@HgbTfD2@cQTTd0z5J8cyYziGamfkH8pKtn1Dw "Python 2 – Try It Online")
Returns `None` or a string with the calculation.
Prints:
* `(-n)` for `n*-1`
* `s(n)` for square root
* `c(n)` for cube root
**Explanation**
Works by checking all combinations of unary and binary operators on the input.
Outer loop gets all combinations of unary operations, which are applied to each number in the input list.
The inner loop then applies the binary operations on the result of the previous operation, and the next number.
If the result matches, a string with the calculation is returned.
Short-circuits a little by removing all outer loops where a number is `0` and the unary operator is not `n => n`, or the number is `1` and the operator is not `n => n` or `n => -n`
] |
[Question]
[
**Input:**
2 numbers, x and y.
**Output:**
Output a text block where x is the width of the text block and y is the height of the text block. Then there will be a straight line going from the top left to the bottom right and to show it, there should be a # where the line should cross.
The # should be generated using the straight line equation, `y = mx + c` where m is the gradient of the line which can be retrieved through making `m` as `y` divided by `x`. `x` is the current line index. `c` is the height intercept and can be found by multiplying the gradient by the `x` value and adding the `y` value. So, in short, it would be `(y/x) * lineIndex + (y/x * x + h)`. This would all be rounded to the nearest position in the current line.
**Rules:**
* there can only be 1 # per line
* it has to be in the form of a string/whatever the equivalent in your language of choice. This has to be able to cover multiple lines as well.
* in text block, after the # there does not need to be more spaces. Just initial ones to offset the #
**Examples:**
(don't mind the `|`, they are where the lines start and stop)
Where x is 9 and y is 1:
```
| #|
```
Where x is 1 and y is 5:
```
|#|
|#|
|#|
|#|
|#|
```
where x is 9 and y is 5:
```
| # |
| # |
| # |
| # |
| #|
```
where x is 5 and y is 9:
```
|# |
|# |
| # |
| # |
| # |
| # |
| # |
| # |
| #|
```
where x is 9 and y is 2:
```
| # |
| #|
```
where x is 9 and y is 3:
```
| # |
| # |
| #|
```
Edit: More detail in the output. Added 3rd rule. Added 5th and 6th example
Edit2: Fixed errors in the given examples (Sorry!). Revised over the output to make it much clearer v. sorry for any confusion :S
[Answer]
# C, ~~74~~ 70 bytes
*Thanks to @Johan du Toit for saving 4 bytes!*
```
i;f(x,y){for(i=y;i--;)printf("%*c\n",(int)round((i-y)/(-1.*y/x)),35);}
```
[Try it online!](https://tio.run/nexus/c-gcc#fcxBCoMwEAXQvaeQQGFGkkoqWYTBm7gRS0pAo0QFg3j1pil0WfJ3nzfzoyUDBw94mtmDbQNZIQgXb91mgN2qoXOMQ2ro5909AawIWIOQ9yrUByJvFNIV00E59dYBFmdRphjQXCIt@7YC65z4Jk0h/VRylVGdVcV19veR1eavXvE9mLF/rVGM0wc)
[Answer]
# PHP, 66 Bytes
```
for([,$x,$y]=$argv;$i<$y;)printf("%".round(++$i*$x/$y)."s\n","#");
```
[Answer]
# JavaScript (ES6), 77 bytes
```
x=>y=>[...Array(y).keys()].map(a=>" ".repeat(0|((a+1)/(y/x))+.5)+"#").join`
`
```
```
f=x=>y=>[...Array(y).keys()].map(a=>" ".repeat(0|((a+1)/(y/x))+.5)+"#").join`
`
console.log(f(9)(5));
```
[Answer]
# Python, ~~64~~ 63 bytes
*1 byte saved thanks to @Cole*
```
def f(x,y):[print(' '*round((i+1)*x/y-1)+'#')for i in range(y)]
```
[Try it online!](https://tio.run/nexus/python3#Pc5BCsMgEIXhvad40IUziaXYkoWBniRkISQWN6ZIC3p6Gyu4mo9/8Ziy7Q6Okso8L@/ow4ck5BCPb9iI/Kh5SLd81TzKi2R3RHj4gGjDa6fMa7F4YhEAGQXNqkorTE2ma1Iwvd27HixWIepsqrN2Pnv7IvFJR8P/tsTlBw)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 21 bytes
```
ÆSpºX+1 /(U/V r)+"#
```
[Try it online!](https://tio.run/nexus/japt#@3@4Lbjg0K4IbUMFfY1Q/TAFhSJNbSXl//9NFSwVdIMA "Japt – TIO Nexus")
Input is in the format of `y x`. +1 byte for the `-R` flag.
[Answer]
# AWK, ~~55~~ 44 bytes
```
{for(;++j<=$2;)printf"%*c\n",$1/$2*j+0.5,35}
```
Using hints from @manatwork and the solution from @Steadybox
The previous code is handy as an example of using an `sprintf` within a `printf`
```
{for(;++j<=$2;)printf sprintf("%%%.0fs\n",$1/$2*j),"#"}
```
Example usage:
```
awk '{for(;++j<=$2;)printf"%*c\n",$1/$2*j+0.5,35}' <<< "9 3"
```
] |
[Question]
[
Is there any better way to golf this (other than removing newlines/indentation)?
```
function(a,b,...)
local c=s(a,b)
local d=c
for i,v in ipairs{...} do d=d:push(v) end
return c
end
```
I'm particularly bothered by the double `local` usage, but as Lua does not have multiple assignment, and I cannot [use function parameters to declare the locals](https://stackoverflow.com/q/39175811/405017), I can't see a way to remove them.
*For those who care, this is the implementation of the `__call` metamethod in my quick hack of a linked-list ~class used in [this answer](https://stackoverflow.com/a/4910622/405017).*
[Answer]
As requested in the comments, here it is as an answer.
```
local c,d=s(a,b) -- d is nil
d=c
```
This saves you one `local` declaration, should give you -5 bytes.
] |
[Question]
[
You have been assigned the task of installing new locks to the company's building. However, the locks you use are quite unusual: they require some combination of keys to open. Now, you want to figure out which locks are the most secure, so you can prioritize the most important locations.
The keys you use are numbered by security: key 1 is the weakest and could be given to the cat, key 2 is a bit better, and so on.
The locks are defined by AND and OR expressions between the keys. For example, a lock might open with just key 1, so it's defined by the string `1`; another one might require key 3 and either key 1 or 2, so it's defined by `3 & (1 | 2)`. A lock opens if the expression is truthy when all key numbers are substituted for true/false depending on if the user possessed the respective keys. XOR and NOT are not needed, since possessing extra keys doesn't matter.
The security of a lock is defined by the weakest key combination required to open the lock. One way to compute this is the following algorithm:
1. Find all the subsets of the keys that open the lock.
2. Sort each combination descending (from the strongest key to the weakest).
3. Sort the combinations lexicographically ascending.
4. The **security value** of the lock is now the first item in the list.
In order to compare two locks, one just has to compare their security values lexicographically: the larger one is more secure.
## Challenge
You are given a list of expressions that define locks. Your task is to sort the locks based on security in **descending order**.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
## Input
You will receive a list of locks as input.
* The list may be taken as lines or in the list representation of your choice.
* Each lock can be given either as a string like `1 & ((2 | 3) & 4)` or a nested list like `[1, "&", [[2, "|", 3], "&", 4]]`.
+ Any whitespace in the string is optional, and all operations except for the outermost one will be wrapped in parentheses.
+ You are free to choose the list format that suits your needs.
* Each operator will have two operands.
* Key numbers will range from 1 to 99 and there will not be unused keys between 1 and the maximum used key.
## Output
You will output the same list you got as input, sorted by security in descending order. All formats listed above are valid. If two locks are equally secure, their order does not matter.
## Test cases
The test cases are in the "list" format. The outputs include the security values of each lock for reference; you should **not** output them.
**Input:**
```
[1]
[2]
[3]
[1, "&", 2]
[1, "&", 3]
[3, "&", 2]
[1, "|", 2]
[2, "|", 3]
[[1, "&", 2], "|", 3]
[[2, "|", 3], "&", 3]
```
**Result:**
```
[3, "&", 2] # (3, 2)
[1, "&", 3] # (3, 1)
[[2, "|", 3], "&", 3] # (3)
[3] # (3)
[1, "&", 2] # (2, 1)
[[1, "&", 2], "|", 3] # (2, 1)
[2] # (2)
[2, "|", 3] # (2)
[1] # (1)
[1, "|", 2] # (1)
```
**Input:**
```
[[[6, '|', [[10, '|', 1], '&', [3, '&', 3]]], '|', 10], '&', [[12, '&', [9, '|', 7]], '|', [[3, '|', 8], '&', [[10, '|', [[1, '&', 3], '&', 9]], '|', [[2, '|', 1], '&', 1]]]]]
[[7, '|', 9], '&', [[5, '|', 10], '&', [[12, '|', 3], '&', 4]]]
[7, '|', 7]
[[[5, '|', [1, '|', 9]], '&', [[7, '&', [[6, '&', [1, '|', 7]], '|', 2]], '|', 5]], '&', [[[[8, '&', 6], '&', 1], '&', 5], '&', [10, '|', [11, '&', [3, '&', 6]]]]]
[[[[2, '&', [6, '&', 8]], '|', [[4, '|', 4], '|', [[5, '&', 4], '|', [[[1, '|', 5], '|', 1], '&', 7]]]], '&', [[[9, '|', [3, '&', 7]], '|', [9, '|', 5]], '&', [[[[8, '|', 11], '|', 8], '|', 2], '|', 2]]], '&', [[3, '|', 6], '&', 9]]
[[12, '|', [5, '&', [[12, '&', 3], '|', [9, '&', 1]]]], '|', [10, '&', [[8, '|', 9], '&', [[[8, '|', 3], '|', 8], '|', 11]]]]
[[9, '|', 11], '&', [[[11, '&', 12], '|', 10], '&', [3, '&', 12]]]
[[[5, '&', 9], '&', [10, '&', 2]], '|', [10, '|', 10]]
[[6, '&', 4], '&', [4, '|', 11]]
[[[[11, '&', [[[[5, '|', 11], '&', [10, '|', 7]], '&', 2], '|', 2]], '|', 12], '|', 5], '&', [[[2, '&', [5, '|', 9]], '&', 4], '&', [6, '|', [3, '&', 2]]]]
```
**Result:**
```
[[9, '|', 11], '&', [[[11, '&', 12], '|', 10], '&', [3, '&', 12]]] # (12, 10, 9, 3)
[[[5, '|', [1, '|', 9]], '&', [[7, '&', [[6, '&', [1, '|', 7]], '|', 2]], '|', 5]], '&', [[[[8, '&', 6], '&', 1], '&', 5], '&', [10, '|', [11, '&', [3, '&', 6]]]]] # (10, 8, 6, 5, 1)
[[[5, '&', 9], '&', [10, '&', 2]], '|', [10, '|', 10]] # (10)
[[12, '|', [5, '&', [[12, '&', 3], '|', [9, '&', 1]]]], '|', [10, '&', [[8, '|', 9], '&', [[[8, '|', 3], '|', 8], '|', 11]]]] # (9, 5, 1)
[[[[2, '&', [6, '&', 8]], '|', [[4, '|', 4], '|', [[5, '&', 4], '|', [[[1, '|', 5], '|', 1], '&', 7]]]], '&', [[[9, '|', [3, '&', 7]], '|', [9, '|', 5]], '&', [[[[8, '|', 11], '|', 8], '|', 2], '|', 2]]], '&', [[3, '|', 6], '&', 9]] # (9, 4, 3, 2)
[[7, '|', 9], '&', [[5, '|', 10], '&', [[12, '|', 3], '&', 4]]] # (7, 5, 4, 3)
[7, '|', 7] # (7)
[[6, '&', 4], '&', [4, '|', 11]] # (6, 4)
[[[[11, '&', [[[[5, '|', 11], '&', [10, '|', 7]], '&', 2], '|', 2]], '|', 12], '|', 5], '&', [[[2, '&', [5, '|', 9]], '&', 4], '&', [6, '|', [3, '&', 2]]]] # (5, 4, 3, 2)
[[[6, '|', [[10, '|', 1], '&', [3, '&', 3]]], '|', 10], '&', [[12, '&', [9, '|', 7]], '|', [[3, '|', 8], '&', [[10, '|', [[1, '&', 3], '&', 9]], '|', [[2, '|', 1], '&', 1]]]]] # (3, 1)
```
[This program](http://pastebin.com/Exrz7S2t) can be used to generate additional test cases. It also outputs the security values of each lock generated.
[Answer]
# [Perl 6](http://perl6.org/): ~~132~~ 124 bytes
```
{reverse .sort: {use MONKEY-SEE-NO-EVAL;my &infix:<|>={|$^a,|$^b}
min map *.flat.sort.squish.reverse,EVAL .trans('&'=>'X')}}
```
A lambda that takes a list of lines as input.
It generates the sort key for each line as follows:
* Declare `|` as a list concatenation operator within the lexical scope.
* Replace `&` in the string with `X`, the Perl 6 [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) operator.
* [Eval](https://en.wikipedia.org/wiki/Eval) the string *(which unfortunately requires the ghastly `MONKEY-SEE-NO-EVAL` pragma)*, yielding all possible combinations of keys that open the door.
* Post-process the lists and pick the "least secure" combination.
[Answer]
# Python, ~~253~~ 246 bytes
```
m=lambda a,b:min(sorted(a),sorted(b))
def w(s):
if type(s)!=list:return[s]
if len(s)==1:return s
k=w(s[0])
z=w(s[2])
if s[1]=="|":return m(k,z)
return k+z
r=[]
for i in n:r+=[(i,sorted(w(i),reverse=1))]
sorted(r,reverse=1,key=lambda x:x[1])
```
] |
[Question]
[
This is the first problem I've posted here; please post criticisms in comments.
## Summary
A game board consists of a starting space, an ending space, and between them are `N` spaces, each with an instruction. You begin on the starting space with `0` points to your credit. Flip a coin or roll a die to choose the number `1` or `2`. Move forward that many spaces. Now look at the instruction on the space you landed on. The possible instructions consist of "Do nothing", "Score `x` points", and "Move forward `y` spaces and obey the instruction there". `x` and `y` are positive. After obeying the instruction, go back to the coin flip. When you land on or pass the ending square, the game is over.
Given a description of a game board (number of squares, instruction on each space) your code should calculate the probability distribution of possible ending scores. It's irrelevant how many turns are taken before the end.
## Input
* An unambiguous representation (in whatever format you desire, though numbers should be human-readable) of the instruction on each space. Numbers should be human-readable.
## Output
* A list of pairs of each possible score and the probability of obtaining that score (either an exact fraction or a real number accurate to at least four decimal places). Can be returned or output. It's optional to include scores that have 0 probability of occurring.
## Scoring the entries
1. They must be correct to be considered; wrong answers don't count.
2. Code size. If you golf it please also post an ungolfed version; if you use a golfing language please post a good explanation.
## Examples
### Easy
* Input
```
3
1
F2
1
```
* Output
```
0 0.5 // rolled a 2 on first turn, game over
1 0.25 // rolled a 1 then a 1
2 0.25 // rolled a 1 then a 2
```
### Complex
* Input
```
16
2
1
0
5
10
F3
5
15
1
0
3
F3
5
0
0
5
```
* Output
```
7 0.0234375
8 0.0078125
9 0.01171875
10 0.03515625
11 0.01171875
12 0.048828125
13 0.015625
14 0.015625
15 0.0732421875
16 0.0322265625
17 0.06005859375
18 0.015625
19 0.01171875
20 0.087890625
21 0.046875
22 0.0654296875
23 0.009765625
24 0.0107421875
25 0.064453125
26 0.0380859375
27 0.0380859375
28 0.001953125
29 0.0029296875
30 0.044677734375
31 0.023681640625
32 0.0281982421875
33 0.00390625
34 0.0029296875
35 0.015869140625
36 0.017333984375
37 0.0177001953125
38 0.0078125
39 0.0087890625
40 0.013916015625
41 0.015625
42 0.0096435546875
43 0.00390625
44 0.009033203125
45 0.0155029296875
46 0.010009765625
47 0.00567626953125
49 0.003662109375
50 0.0067138671875
51 0.003662109375
52 0.00274658203125
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~56~~ 55 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)CP437
```
üZÄ^3Γ╥£X╜T∩L╖á↨→╘Oïë╢Δ╥∙Eü╦5├jC╩XpN◘╘♥«╟╝☻y╞╘wé↔Ioÿ≈⌐─
```
[Run and debug online!](https://staxlang.xyz/#c=%C3%BCZ%C3%84%5E3%CE%93%E2%95%A5%C2%A3X%E2%95%9CT%E2%88%A9L%E2%95%96%C3%A1%E2%86%A8%E2%86%92%E2%95%98O%C3%AF%C3%AB%E2%95%A2%CE%94%E2%95%A5%E2%88%99E%C3%BC%E2%95%A65%E2%94%9CjC%E2%95%A9XpN%E2%97%98%E2%95%98%E2%99%A5%C2%AB%E2%95%9F%E2%95%9D%E2%98%BBy%E2%95%9E%E2%95%98w%C3%A9%E2%86%94Io%C3%BF%E2%89%88%E2%8C%90%E2%94%80&i=%5B-1%2C2%2C-1%5D+3%0A%5B-2%2C-1%2C0%2C-5%2C-10%2C3%2C-5%2C-15%2C-1%2C0%2C-3%2C3%2C-5%2C0%2C0%2C-5%5D+16%0A&a=1&m=2)
Warning: Takes a long time (around 5 minutes in my box) to run the large example.
*Credits to the [almighty rubber duck](https://rubberduckdebugging.com/) for -1 byte.*
Input is a list of numbers. `Scoring x points` is represented by `-x`, and `Move y steps forward and follow the instruction there` is represented by `y`. So for example the small test case will be represented as `[-1,2,-1]`.
Outputs in rational number, the output for the large case is like this:
```
7 3/128
8 1/128
9 3/256
10 9/256
11 3/256
12 25/512
13 1/64
14 1/64
15 75/1024
16 33/1024
17 123/2048
18 1/64
19 3/256
20 45/512
21 3/64
22 67/1024
23 5/512
24 11/1024
25 33/512
26 39/1024
27 39/1024
28 1/512
29 3/1024
30 183/4096
31 97/4096
32 231/8192
33 1/256
34 3/1024
35 65/4096
36 71/4096
37 145/8192
38 1/128
39 9/1024
40 57/4096
41 1/64
42 79/8192
43 1/256
44 37/4096
45 127/8192
46 41/4096
47 93/16384
49 15/4096
50 55/8192
51 15/4096
52 45/16384
```
## Alternative version
Calculates the probability recursively instead of enumerating every possibility. Much faster. Not really golfed.
`00\sn+~]]01\]]+Yd;%{;%=zi^]?i]+ys@iXd{{dx2<;x|i-v@1<+!C_E2u*s;x@0|m-s\mm:f;i({i+|i=!Ci2+mys@{{B;x@0|m-+rm+F{o{h}/{hh0_{H+F\m]ys+YdFUUv\ys@:fo{h}/mhh0_{H+F\J`
[Try and debug online!](https://staxlang.xyz/#c=00%5Csn%2B%7E%5D%5D01%5C%5D%5D%2BYd%3B%25%7B%3B%25%3Dzi%5E%5D%3Fi%5D%2Bys%40iXd%7B%7Bdx2%3C%3Bx%7Ci-v%401%3C%2B%21C_E2u*s%3Bx%400%7Cm-s%5Cmm%3Af%3Bi%28%7Bi%2B%7Ci%3D%21Ci2%2Bmys%40%7B%7BB%3Bx%400%7Cm-%2Brm%2BF%7Bo%7Bh%7D%2F%7Bhh0_%7BH%2BF%5Cm%5Dys%2BYdFUUv%5Cys%40%3Afo%7Bh%7D%2Fmhh0_%7BH%2BF%5CJ&i=%5B-1%2C2%2C-1%5D%0A%5B-2%2C-1%2C0%2C-5%2C-10%2C3%2C-5%2C-15%2C-1%2C0%2C-3%2C3%2C-5%2C0%2C0%2C-5%5D&a=1&m=2)
The two different algorithms give the same result.
## Explanation
Uses the unpacked version to explain. The size of the game board is stored in register `x`. The current position on the board is stored in register `y`. There is an extra flag (boolean) denoted `bFlip` that is stored on the stack, used to indicate the type of last instruction.
The complete unpacked version is 66 bytes.
```
X|2{v:Bx)0Y1~s{^,*y+Ycx>{d1~}{v;@c1<c~{-}{y+Yd}?}?F,dmo|RmNx|2u*+J
```
I will explain it part by part.
```
X|2{v:Bx)0Y1~s{ F,dm
X|2 `2^x`
{v m For `[0..2^x-1]` do the following
:Bx) Binary representation of the current loop index
Padded with zeros to make the length `l`.
Each binary represents a sequence of coin flip outcomes
0Y1~s Initialize `y` and current score to `0`, and `bFlip` to true
{ F Play the game as indicated by the sequence of coin flip outcomes
,d Clean up: remove `bFlip` from the stack.
```
The block that plays the game:
```
{^,*y+Ycx>{d1~}{v;@c1<c~{-}{y+Yd}?}?F
{ F The loop as stated above
^ Increment current flip result
Map the original [0,1] to [1,2], denote this as `n`.
,* If last instruction is of the type `Score k points` (`k` may be `0`)
y+Y Move forward `n` steps and save the new current position to register `y`.
cx>{ }{ }? If already moved past the end
d1~ Mark this instruction as `Score 0 points` (or `Do nothing`)
Else
v;@ Get current instruction
c1<c~ Get the type of current instruction and remember it
{ }{ }? If the current instruction is `Score k points`
- Score `k` points
Else
y+Yd Move forward as the instruction indicates
```
After executing this, we have a list with `2^x` elements containing the scores of all possible coin flips, with equal probabilities. The rest of the program is just converting them to the output.
```
o|RmNx|2u*+J
o|R Convert to a list of pairs of [element, count of appearance]
m Map the array elements with the rest of the program, output the results on separate lines
Nx|2u*+ Divide the count of appearance by `2^x` to get probability
J Join the two elements with a space
```
[Answer]
# [Perl 5](https://www.perl.org/), `-a0` ~~111~~ 108 bytes
Input format: Give the instructions separated by white-space (newline works) on STDIN including the starting cell represented by `0`. The `jump` is indicated by an `F` **after** the number. So the example input becomes:
```
0
1
2F
1
```
With correct output
```
0 0.5
1 0.25
2 0.25
```
```
#!/usr/bin/perl -a0
@1=1;$n++,map{$i=0;for$a(@$n){${$n+$_>@F?z:$n+$_}[$i+++$']+=$a/2}}/F/?($`)x2:(/|/,2)for@F;say$z++," $_"for@z
```
[Try it online!](https://tio.run/##JY5NCoMwFIT3OYXIgypR8xLJxmDNKrueoBSbhQWhVdEWWq1Xb@rPama@gWG6qr9L9xoqTyYcE1RO85wraCiNHraboM5R3doebKChCSeYlgrKozbFmG12PkNNKYXDheZgmZhnZlgRwDV8iyxgXxaJcBnQRg32A@Oy63tQ@isanUMiCCdIJOFIUrOq3EC6J1y7X9s967YZXGzRxaf96R8 "Perl 5 – Try It Online")
] |
[Question]
[
*This challenge is entirely fictional. There is no time limit for this challenge.*
My little brother is terrible with computers! He saved up all of his money to buy a new one, and within half an hour the hard drive was wiped and the only software left is a lousy BF interpreter. The worst part of it is, he has a huge Geometry test tomorrow and needs help!
# The Challenge
There's no way I'm going to let him touch my machine, so I'm going to need a fast way to write BF programs that solve his problem. He's learning about finding the area of regular polygons, and writing a new BF program for every calculation is a massive task. I need a fast way to generate BF programs! That's where you come in...
# The Input
Your program or function will receive an integer `2 < N <= 100` which shall represent the number of sides of a [regular polygon](http://en.wikipedia.org/wiki/Regular_polygon). You may receive input from function arguments, command line arguments, STDIN, or your language's closest alternative. If necessary, you may additionally require trailing or leading whitespace.
# The Output
Your program should generate a separate [BF](http://en.wikipedia.org/wiki/Brainfuck) program that takes input of a single positive integer `0 < a <= 10^10` that shall represent the length of the [apothem](http://en.wikipedia.org/wiki/Apothem) of a regular polygon. When run, the BF program should output the area of a polygon with `N` sides and an apothem of `a`. More specifically:
* Assume that the BF interpreter is set up such that `,` takes a number as input and `.` outputs a value as a number, not a character. An input of `12` does not translate to the characters `'1' '2'` in memory, rather the literal number `12`. Similarly, when a value of `48` is output, it outputs `'48'`, not the character `'0'`.
* Assume also that each value on the tape of the BF program may contain an infinitely large **integer** -- the value will never wrap to 0.
* Assume that the tape of the BF spans infinitely to the right, but has no negative indices. The pointer starts at `0`.
* My brother is as careless with numbers as he is with computers. As such, the BF code should output the area **rounded to the nearest integer**.
# The Rules
In a separate and unrelated incident, my brother downloaded so much garbage onto my primary programming machine that I have virtually no hard drive space left. As such, your original program **may not exceed 512 bytes**.
Your score in this challenge is the length of all BF programs generated by your program for values of `N` from `3` to `100` inclusive.
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) are disallowed.
[Answer]
## Python, 23938 score
```
from math import*
def apothem(n):
c=int(n*tan(pi/n)/2*10)
s=',>' + '+'*c
m=">[-]>[-]<<[>>+<<-]>>[<<<[>+>+<<-]>>[<<+>>-]>-]<<"*2
p=">>[-]<[-]<+++++<[-]++++++++++"
d=">[>+<-]>[<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[>+<<-[>>[-]>+<<<-]>>>[<<<+>>>-]<[<-[<<->>[-]]+>-]<-]<<+>]"
o="<."
print s+m+p+d+o
```
* the area of a regular polygon is *nsa/2* width *n* given in Python and *a* later in BF. *s* is the sidelength of the polygon, which can be computed from *a* and *n*
* `c` is a constant, such that the area is *(aac+5)/10*, so only this formula must be coded into BF. *c* is between 15 and 25.
* `s` is the starting point for the BF code: read the apothem and write `c`
* `m` does *c=ca* twice, so in the cell formaly holding *c* there is *aac*
* `p` prepares for the final operation, clearing temporary cells, adding *5* to *aac* and setting the first cell to *10*
* `d` division
* `o` output
This is my first writing in BF, so all algorithms are from [this](http://esolangs.org/wiki/Brainfuck_algorithms) page.
] |
[Question]
[
# Cyclic Equivalence
Let `L` be a list of pairs of letters, for example `[(a,b), (a,c)]`. We call `L` a *list of commutators*. Two words are *cyclically equivalent over* `L`, if one can be transformed into the other using the following operations:
1. Cyclic shift: pop a letter from the beginning, and push it to the end.
2. Commutator swap: if the word begins with two letters that appear in `L` in either order, swap those letters.
For example, the words `acabd` and `dcaba` are cyclically equivalent over `L`, since we have the sequence of operations `acabd -> caabd -> aabdc -> abdca -> badca -> adcab -> dcaba`. However, the words `acabd` and `acdab` are not cyclically equivalent, since the letters `b`, `c` and `d` cannot be swapped with each other, so they can occur only in the order `cbd`, `dcb` or `bdc` in words that are cyclically equivalent to `acbad`.
# The Challenge
You are given as input two words, and a list of commutators. You program should output a truth-y value (`True`, `1`, etc.) if the words are cyclically equivalent over the list, and a false-y value (`False`, `0`, etc.) otherwise. You **don't** have to output a sequence of operations in the positive case. The shortest answer (in bytes) is the winner.
# Test Cases
```
[(a,b), (a,c)] acabd dcaba -> True
[(a,b), (a,c)] acabd acdab -> False
[(a,b), (a,d), (b,c), (b,d)] cdaddccabbdcddcababaaabbcbdccaccacdddacdbccbddaacccaddbdbbcadcccadadccbaaabdbcc ddcadbbcccdadbabcbcaadaccbbcdddaccdacddcababaaacbbdbccaccbacddadcdccaddabcbccda -> True
[(a,b), (a,d), (b,c), (b,d)] cdaddccabbdcddcababaaabbcbdcccacacdddacdbccbddaacccaddbdbbcadcccadadccbaaabdbcc ddcadbbcccdadbabcbcaadaccbbcdddaccdacddcababaaacbbdbccaccbacddadcdccaddabcbccda -> False
```
# Clarifications
* You can write either a function or a STDIN-to-STDOUT program.
* The list of commutators can be given as a comma-separated string, a list of length-two strings, or a list of pairs of characters.
* You can assume that the input words only contain alphanumeric ASCII symbols.
* Your program should be able to process inputs of length 100 in a matter of seconds.
* Standard loopholes are disallowed.
[Answer]
# Python 413
Pretty efficient, although it does sacrifice a small amount of speed for length, such as calculating things every pass of a small for loop rather than precalculating it. I̶t̶ ̶s̶t̶i̶l̶l̶ ̶o̶u̶t̶p̶u̶t̶s̶ ̶a̶l̶l̶ ̶t̶h̶e̶ ̶t̶e̶s̶t̶ ̶c̶a̶s̶e̶s̶ ̶i̶n̶ ̶w̶e̶l̶l̶ ̶u̶n̶d̶e̶r̶ ̶a̶ ̶s̶e̶c̶o̶n̶d̶.̶
**Edit:**
I had to fix a bug which now makes it significantly less efficient for larger inputs.
```
X,Y,L=input();S=sorted;T=type
def E(s,c):
l=[[]]
for h in s:
if h==c:l+=[h]
elif all(h!=[b,a][j]for a,b in L for j,n in[(0,a),(1,b)]if n==c):
if T(l[-1])==str:l+=[[]]
l[-1]=S(l[-1]+[h])
if T(l[0])==T(l[-1])!=str:return[l[0]+l[-1]]+l[1:-1]+[len(l[-1])]
return l+[0]
print any(0==cmp(*[[E(s,c)for c in S(set(s))]for s in [X[j:]+X[:j],Y[i:]+Y[:i]]])for i in range(len(Y))for j in range(len(X)))
```
Test Cases
```
"acb", "abc", [('a','b')]
True (0 ms)
'acabd','dcaba',[('a','b'),('a','c')]
True (1 ms)
'acabd','acdab',[('a','b'),('a','c')]
False (2 ms)
'cdaddccabbdcddcababaaabbcbdccaccacdddacdbccbddaacccaddbdbbcadcccadadccbaaabdbcc','ddcadbbcccdadbabcbcaadaccbbcdddaccdacddcababaaacbbdbccaccbacddadcdccaddabcbccda',[('a','b'), ('a','d'), ('b','c'), ('b','d')]
True (62 ms)
'cdaddccabbdcddcababaaabbcbdcccacacdddacdbccbddaacccaddbdbbcadcccadadccbaaabdbcc','ddcadbbcccdadbabcbcaadaccbbcdddaccdacddcababaaacbbdbccaccbacddadcdccaddabcbccda',[('a','b'), ('a','d'), ('b','c'), ('b','d')]
False (6963 ms)
```
The basic algorithm does the following. For each letter, L, present, loop through the string constructing a list; anytime it encounters L it appends it to the list, any group of adjacent letters which can *not* be switched with L it appends to the list sorted, letters which can be switched with L are ignored.
For example when considering `'acabd'` with the pairs `[('a','b'),('a','c')]`, we would construct:
```
a : a, a, [d]
b : [c], b, [d] *
c : c, [b,d]
d : [a,a,b,c], d
```
which is equivalent to the result we get when we apply this to `'cabad'` (`'dcaba'` shifted)
\*Note here that the `[c]` and `[d]` should be considered one list
What is basically being done, is confirming for each letter that the order of it and the letters it can't switch with are the same. Since they cannot switch, they cannot 'pass' each other, so if the first string has two `a`s followed by two `d`s followed by one `a` followed by one `d` than no matter how it's manipulated it can't be transformed into a string which has three `a`s followed by three `d`s. Of course the order of the letters that it can't switch with is not an issue (they might be paired with each other and switchable), but their counts are, hence the sorting of the lists before comparison. In addition it's clear that any letters that *can* be switched don't matter at all for the purposed of comparison.
Using this algorithm the program could be made significantly more efficient; currently it loops through every possible transposition of *both* strings and compares them due to some issues with comparing cases in which there were lists bordering the beginning and end.
[Answer]
# Haskell, 409
not fully golfed yet.
```
import Data.List
r((c,h):s)|l<-r s,(x,y)<-partition(\s->any(`elem`s)[c,h])l=nub(c:h:concat x):y
r _=[]
k s d|l<-sort$nub s=r[(x,y)|x<-l,y<-l,notElem(x,y)d,notElem(y,x)d,x/=y]
m a b c|elem c[a,b]=c|0<1=' '
e s d=[nub[map(m x y)s|x<-g,y<-g,notElem(x,y)d,notElem(y,x)d,x/=y]|g<-k s d]
q a b=and$zipWith(\a b->or[n a==n[drop i s++take i s|s<-b]|i<-[0..length$a!!0]])a b
f a b d=q(e a d)(e b d)
n=map$filter(/=' ')
```
this works on all the test cases.
] |
[Question]
[
Your task is to create a program which outputs a completed tournament bracket given a list of entrants, their seeds, and their scores in each game; in the fewest characters possible.
**Input**
Your entrants will have the following data. You can organize your data in whatever form you like, but you *cannot* pre-sort your array or do any other pre-processing. The scores represent an entrant's score in each round, in other words they determine who moves on to the next round.
```
Example Input #1
[ {name: "James", seed: 1, scores: [12, 6,]}
, {name: "Sarah", seed: 4, scores: [1, 16]}
, {name: "Andre 3000", seed: 3, scores: [3000, 3000]}
, {name: "Kim", seed: 2, scores: [20, 4]}
]
Example Input #2
[ {name: "Andy", seed: 1, scores: [1, 8, 4]}
, {name: "Kate", seed: 4, scores: [1, 1, 8]}
, {name: "Steve", seed: 3, scores: [30, 1, 0]}
, {name: "Linda", seed: 5, scores: [4, 4, 5]}
, {name: "Kyle", seed: 2, scores: [21, 0, 18]}
]
```
**Output**
Your output should resemble the examples below, and must follow these rules:
1. For each round in the tournament, the entrants are paired up and those pairs are output.
2. In the event of an odd entrant count, your program must account for and output byes. The entrant who gets the bye is the entrant who has been given the fewest bye weeks so far, and in the event of a tie, the best seed (1 is the best).
3. Pairing is based on the seed. Excluding byes, the best seed (1 is the best) is paired with the worst, the next best is paired with the next worst seed, etc.
4. The best seeds should be first in the pair, and at the top of the bracket.
5. The tournament champion should be output.
.
```
Example Output #1 (for input #1)
Round 1
James vs Sarah
Kim vs Andre 3000
Round 2
James vs Andre 3000
Champion
Andre 3000
Example Output #2 (for input #2)
Round 1
Kyle vs Linda
Steve vs Kate
Andy BYE
Round 2
Andy vs Steve
Kyle BYE
Round 3
Andy vs Kyle
Champion
Kyle
```
Extra props for anyone who codes a separate version of their program which prints an actual bracket.
**Scoring**
Assume input is correct, [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny/), etc and so forth. This is code golf, so fewest bytes win. In the event of a tie, most votes win. Good luck!
[Answer]
# CJam, ~~156 151~~ 144 bytes
```
q~0f+{{1=}$_,2%{{W=}$())+aa\{1=}$\}L?\_,2//)W%a+z\+_{0f=_,1={~" BYE"+a}*" vs "*N\}%"Round "U):U+\+\{{2=0=}$W=_2=(;2\t}%_W=2=}g~0=a"Champion"\]N*
```
This can definitely be golfed further.
The input is in an array of array format, like:
```
[["James" 1 [12 6 15]] ["Sarah" 4 [3 2 5]] ["Franko" 2 [20 1 5]] ["Max" 5 [22 10 7]] ["Arthur" 3 [20 15 20]]]
```
where each array element is the detail about the user in `[name seed score_array]` format
The output for the above input is:
```
Round 1
Franko vs Max
Arthur vs Sarah
James BYE
Round 2
James vs Max
Arthur BYE
Round 3
Arthur vs Max
Champion
Arthur
```
[Try it online here](http://cjam.aditsu.net/)
] |
[Question]
[
## Setting
The Fry King is a small criminal mastermind from the western european nation of Belgium, more specifically Flanders. He has acquired every single fastfood restaurant in a large part of Belgium and set them out on a 101X49 grid (102 intersections horizontally, 50 vertically, including the borders), 5100 restaurants in total located on the intersections. The next step in his diabolical plan is to orchestrate the closing hours of these restaurants so that on any one day of the year (bar 2 explained later), only 1 corner of each square will have an open restaurant.
Example with a 6X2 grid:
```
1---2---3---4---1---2
| | | | | |
3---4---1---2---3---4
```
A year has 365 days. On the first Monday of the year, only the restaurants with number 1 will be open. On the next day, Tuesday, only those with the number 2. On the next day, Wednesday, only those with number 3. On the next day, Thursday, only those with number 4. after that, it starts again at 1. The days before the first Monday count back. For example, if the first Monday falls on January 3rd, the Sunday before the 4s will be open. This might mean that when the year changes, a store might be open twice or might be skipped in the rotation.
There are 2 exceptions: the 21st of July is the national holiday. All restaurants are open. Another is the 29th of February. Because this is the Fry King's birthday, all restaurants are also open. These exceptions replace a normal day, so if the 20th is for the restaurant with number 1, the 22nd is for the joints with number 3.
## Assignment
You are a vigilante coder who has setup a toll-free texting number. It accepts 3 values, delimited by an \*: A number between 1 and 101 denoting the column value you're in, a number between 1 and 49 to denote the row number you're in (these 2 determine which joints are eligible) and a date in the format of DD/MM/YYYY (day/month/year). The number returns 2 letters indicating which corner of your square contains today's open restaurant (NW-NE-SE-SW). If there are multiple options, it returns the first eligible one from the previous series.
## Example:
Input
```
1*1*06/01/2014
```
Output
```
NW
```
Input:
```
2*1*20/01/2014
```
Output
```
NE
```
Calculation is code golf. Shortest code in bytes wins. There are no special bonuses to win or limitations involved, apart from 1: no external resources.
[Answer]
# Python 2 (228 209 208 207)
(not counting the last newline)
```
import time
s=time.strptime
f=raw_input().split('*')
t=s(f[2],"%d/%m/%Y")
if t[1:3]in[(2,29),(7,21)]:t=s("%s%s"%(t[0],t[7]-1),"%Y%j")
print"NNSSWEWE"[(t[7]+s(str(t[0]),"%Y")[6]-int(f[0])-int(f[1])*2+3)%4::4]
```
**Edits:**
* substituted variables that were used only once, further golfed the print statement.
* Removed the space after print as isaacg suggested.
* Changed `from time import*;s=strptime` to `import time;s=time.strptime` to shave off one extra byte
[Answer]
# Mathematica: 272
```
S=ToExpression
T=StringSplit
{a,b,c}=T[i,"*"]
{d,m,y}=S@T[c,"/"]
{{e}}=Position[DayOfWeek[{y,m,#}]&/@Table[i,{i,7}],Monday]
{o,p,q}=DateDifference[Join[{y},#],{y,m,d}]&/@{{1,e},{7,21},{2,29}}
{"NW","SE","SW","NE"}[[1+If[p==0||q==0,0,Mod[2*Mod[S@b-1,2]+Mod[S@a-1,4]+o,4]]]]
```
Assumes that the input string is in a variable named `i` like so (perhaps add 4 chars for `i=""`?):
```
i = "2*1*20/01/2014"
```
Also I leave the following out of the character count (perhaps add 18 for that):
```
Needs["Calendar`"]
```
And the trailing `;` on each of the non-output lines (perhaps add 9 for those). Below is a slightly ungolfed version of the code for testing/editing:
```
i = "2*1*20/01/2014";
Needs["Calendar`"];
R = Mod[#, 4] &;
S = ToExpression;
T = StringSplit;
{a, b, c} = T[i, "*"];
{d, m, y} = S@T[c, "/"];
{{e}} = Position[DayOfWeek[{y, m, #}] & /@ Table[i, {i, 7}], Monday];
{o, p, q} = DateDifference[Join[{y}, #], {y, m, d}] & /@ {{1, e}, {7, 21}, {2, 29}};
{"NW", "SE", "SW", "NE"}[[1 + If[p == 0 || q == 0, 0, Mod[2*Mod[S@b - 1, 2] + Mod[S@a - 1, 4] + o, 4]]]]
```
] |
[Question]
[
The point of the puzzle is to learn about [livelocks](https://en.wikipedia.org/wiki/Livelock):
Create a multi-threaded (or a multi-process) program, whose threads (processes) indefinitely try to wait for each other and never finish. Unlike a deadlock situation, the state of threads (processes) in a livelock constantly change as they try to resolve the situation, but never succeeding.
The task isn't to create a shortest or a simplest solution. Try to create a solution that resembles a real situation, something that looks like a genuine piece of code, but with some kind of an error that creates the livelock.
This is a popularity contest. The most up-voted answer in ~10 days wins.
[Answer]
# Ruby
Based on the [Dining Philosophers](http://en.wikipedia.org/wiki/Dining_philosophers_problem) tale - 4 philosophers:
>
> Five silent philosophers sit at a table around a bowl of spaghetti. A
> fork is placed between each pair of adjacent philosophers. (An
> alternative problem formulation uses rice and chopsticks instead of
> spaghetti and forks.)
>
>
> Each philosopher must alternately think and eat. However, a
> philosopher can only eat spaghetti when he has both left and right
> forks. Each fork can be held by only one philosopher and so a
> philosopher can use the fork only if it's not being used by another
> philosopher. After he finishes eating, he needs to put down both forks
> so they become available to others. A philosopher can grab the fork on
> his right or the one on his left as they become available, but can't
> start eating before getting both of them.
>
>
>
```
class Fork
attr_reader :owner
def initialize
@mutex = Mutex.new
end
def pickup(new_owner)
@mutex.synchronize do
if @owner.nil?
@owner = new_owner
return true
end
return false
end
end
def release(owner)
@mutex.synchronize do
if @owner == owner
@owner = nil
return true
end
return false
end
end
end
class Philosopher
attr_reader :name, :hungry
attr_accessor :left_fork, :right_fork
def initialize(name, left_fork, right_fork)
@name = name
@hungry = true
@left_fork = left_fork
@right_fork = right_fork
end
def eat
while hungry
got_left = left_fork.pickup(self)
think
got_right = right_fork.pickup(self)
if got_left && got_right
@hungry = false
puts "#{name} has eaten!"
end
right_fork.release(self)
think
left_fork.release(self)
end
puts "#{name} ended"
end
def think
puts "#{name} thinks..."
sleep 1
end
end
fork = nil
philosophers = %w(aristotle plato confucius descartes).map { |p| Philosopher.new(p, fork, fork = Fork.new) }
philosophers[0].left_fork = fork
threads = philosophers.map do |p|
puts p.left_fork.pickup(p)
Thread.new {
p.eat
}
end
threads.map(&:join)
```
[Answer]
## Game Maker Language
Script `add`:
```
subtract=argument0
add(not(subtract))
```
] |
[Question]
[
Create a function which takes an integer and returns an array of integers representing the number in [balanced base twelve](http://shwa.org/reverse.htm). Specifically, the representation should follow these rules regarding 6 & -6 (from the above link):
>
> 1. If the last digit of a number could be written with either **6** or **ϑ**, we use the one whose sign is *opposite* the sign of the first digit. For example, we write decimal ***30*** as dozenal **3ϑ**, but decimal ***-30*** as as dozenal **ε6**, not **ζϑ**.
> 2. If a **6** or **ϑ** occurs before the last digit of a number, we use the one whose sign is *opposite* the next digit after it. For example, we write decimal ***71*** as dozenal **6τ**, but decimal ***73*** as as dozenal **1ϑ1**, not **61**.
> 3. If a **6** or **ϑ** is followed by a **0**, we keep looking to the right until we can apply one of the first two rules. For example, we write decimal ***-72*** as dozenal **τ60**, not **ϑ0**.
>
>
>
Otherwise, the only restrictions are to use only digits in [-6..6], and for the output, when interpreted as big-endian base twelve, to be equivalent to the input.
Example of use:
```
f(215) => [1,6,-1]
f(216) => [2,-6,0]
f(-82) => [-1,5,2]
f(0) => [0]
```
Winner is the shortest, with upvotes being the tiebreaker.
[Answer]
## J, ~~74~~ 72 characters
Here's my J implementation (`f =.` not included in character count):
```
f =. **}.^:(*@#*0={.)@([:((12-~[),0>:@{.@]`[`]}])`,@.(6>[)/&.|.0,12&#.^:_1)@|
```
And some tests (each result is boxed, and underscore means negative):
```
NB. Integers [-10..10]:
(<@f"0)i:10
┌────┬────┬────┬────┬────┬──┬──┬──┬──┬──┬─┬─┬─┬─┬─┬─┬────┬────┬────┬────┬────┐
│_1 2│_1 3│_1 4│_1 5│_1 6│_5│_4│_3│_2│_1│0│1│2│3│4│5│1 _6│1 _5│1 _4│1 _3│1 _2│
└────┴────┴────┴────┴────┴──┴──┴──┴──┴──┴─┴─┴─┴─┴─┴─┴────┴────┴────┴────┴────┘
NB. Some boundary values:
(<@f"0)215 216 217 71 72 73
┌──────┬──────┬──────┬────┬──────┬──────┐
│1 6 _1│2 _6 0│2 _6 1│6 _1│1 _6 0│1 _6 1│
└──────┴──────┴──────┴────┴──────┴──────┘
```
Interestingly, the rules for 6 have no special place in the function. They work that way just by handling all digits >= 6 together and only working on positive numbers.
I made another version, which doesn't rely on `#.^:_1`, but it's longer:
```
**_2&([:}.^:(0={.)+/\)@(((<.@%&12,(1,-&12)`(0,])@.(6>])@(12&|))@{.,}.)^:(0~:{.)^:_)@(,&0)@|
```
[Answer]
### GolfScript, 69 53 49 characters
```
[.0<\{.12:^%.3$5+>{^-\^+\}*@1$.0<@if@^/.}do;;]-1%
```
GolfScript expression which takes top of the stack and replaces it by the result. You can play with the code [online](http://golfscript.apphb.com/?c=ewpbLjA8XHsuMTI6XiUuMyQ1Kz57Xi1cXitcfSpAMSQuMDxAaWZAXi8ufWRvOztdLTElCn06ZjsKCjIxNSBmIHAKMjE2IGYgcAoyMTcgZiBwCjcxIGYgcAo3MiBmIHAKNzMgZiBwCi0xOSBmIHAKMCBmIHAK&run=true).
[Answer]
# APL(NARS), 71 chars, 142 bytes
```
{⍵=0:,0⋄⍵{⍵=0:⍬⋄((m+⍺×m=0)∇⌊12÷⍨⍵+q),m←t-q←12×(6<t)+(⍺>0)×6=t←12∣⍵}⍨×⍵}
```
test:
```
z←{⍵=0:,0⋄⍵{⍵=0:⍬⋄((m+⍺×m=0)∇⌊12÷⍨⍵+q),m←t-q←12×(6<t)+(⍺>0)×6=t←12∣⍵}⍨×⍵}
⎕fmt z¨215 216 ¯82 0 30 ¯30 71 72 73 ¯72
┌10──────────────────────────────────────────────────────────────────────────────────────┐
│┌3──────┐ ┌3──────┐ ┌3──────┐ ┌1─┐ ┌2────┐ ┌2────┐ ┌2────┐ ┌3──────┐ ┌3──────┐ ┌3──────┐│
││ 1 6 ¯1│ │ 2 ¯6 0│ │ ¯1 5 2│ │ 0│ │ 3 ¯6│ │ ¯3 6│ │ 6 ¯1│ │ 1 ¯6 0│ │ 1 ¯6 1│ │ ¯1 6 0││
│└~──────┘ └~──────┘ └~──────┘ └~─┘ └~────┘ └~────┘ └~────┘ └~──────┘ └~──────┘ └~──────┘2
└∊───────────────────────────────────────────────────────────────────────────────────────┘
```
] |
[Question]
[
Write a program to print [Carmichael numbers](http://en.wikipedia.org/wiki/Carmichael_number). The challenge is to print the maximum number of them in less than 5 secs. The numbers should be in increasing order. Please do not use built in functions. Also please don't store the carmichael numbers in any form. To keep a common time measurement use [Ideone](http://www.ideone.com/). The program to print the maximum number of Carmichael number wins.
```
Sample Output
561
1105
1729
2465
2821
6601
8911
.
.
.
```
[**OEIS A002997**](http://oeis.org/A002997)
[Answer]
## Python
This generates 1332 Carmichael numbers in under 5 seconds. Remove the print to actually get ideone to run to completion.
```
N=180000
maxprime = 18*N+1
prime = [1]*maxprime
prime[0] = prime[1] = 0
for i in xrange(maxprime):
if prime[i]:
for j in xrange(2*i,maxprime,i):prime[j]=0
for i in xrange(N):
a=6*i+1
b=12*i+1
c=18*i+1
if prime[a] and prime[b] and prime[c]:print a*b*c
```
Note that you could make this a whole lot faster in C.
[Answer]
**unGolf3D dear Java :)** maxCount=1193221 (at my local) and 552721 (at ideone) in 4.8s
```
public class Main{
public static void main(String[] args){
long start=System.currentTimeMillis();
int N=1200000;
int list[]=new int[N];
for (int i=0;i<N;i++) {
list[i]=(i+1);
}
for (int i=1;i<N;i++) {
if (Math.sqrt(list[i])-Math.floor(Math.sqrt(list[i]))==0) {
for (int j=i;j<N;j+=(i+1)){
list[j]=-1;
}
}
}
boolean Carmichael=false;
int chemCount=0;
int product=1;
for(int i=561 ;(System.currentTimeMillis()-start)/1000.0<=5;i++){
if(!isPrime(i)&&list[i-1]==i){
for(int div=2;div<Math.sqrt(i);div++){
if(i%div==0 && isPrime(div)){
if((i-1)%(div-1)==0){
Carmichael= true;
product*=div;
chemCount++;
if (product==i) break;
}
else{
Carmichael=false;
break;
}
}
}
if (Carmichael && chemCount>=3 && product==i)
System.out.println(i);
Carmichael=false;
chemCount=0;
product=1;
}
}
}
static boolean isPrime(long number){
if (number==2)
return true;
if (number==1)
return false;
for (long i=2;i<=Math.sqrt(number);i++) {
if (number%i==0)
return false;
}
return true;
}
}
```
My JVM gets this to 1193221 number in 5 sec... I am sure this is slower than any other scripting languages and algo!! :( ...
OTOH, <http://www.ideone.com/clone/oNJin> fails to create this big process.. calculates upto 552721 in 4.8 sec and breaks after that throwing <http://en.wikipedia.org/wiki/SIGXCPU> :)
[Answer]
## C++
Machine i5-760 @ 2.8Ghz, only one core used
Numbers found in 5 seconds: 129
```
#define WIN32_MEAN_AND_LEAN
#include <windows.h>
#include <iostream>
using namespace std;
bool IsPrime (int v)
{
bool
is_prime = true;
for (int i = 3, i2 = 9 ; i2 < v ; ++i, i2 += i + i + 1)
{
if (v % i == 0)
{
is_prime = false;
break;
}
}
return is_prime;
}
int Prime (int i, int &i2)
{
static int
primes [10000] = {2, 3, 5},
primes2 [10000] = {4, 9, 25},
num_primes = 3;
while (i >= num_primes)
{
int
v = primes [num_primes - 1];
do
{
v += 2;
} while (!IsPrime (v));
primes [num_primes] = v;
primes2 [num_primes] = v * v;
++num_primes;
}
i2 = primes2 [i];
return primes [i];
}
bool IsCarmichael (int n)
{
if (n < 2)
{
return false;
}
int
k = n--,
i2 = 4;
for (int i = 1, p = 2 ; i2 <= k ; p = Prime (i++, i2))
{
if (k % p == 0)
{
k /= p;
if (k % p == 0 || n % (p - 1) != 0)
{
return false;
}
i = 0;
}
}
return --k != n && n % k == 0;
}
int main ()
{
DWORD
end = GetTickCount () + 5000;
int
count = 0,
n = 561;
while (GetTickCount () < end)
{
for (int i = 0 ; i < 1000 ; ++i)
{
if (IsCarmichael (n))
{
++count;
cout << n << endl;
}
++n;
}
}
cout << count << " Carmichael numbers found out of " << (n - 561) << " values tested." << endl;
}
```
[Answer]
# [D Language](https://dlang.org/), 139 numbers, 18900973 max
Implemented [Korselt's criterion](https://math.dartmouth.edu/%7Ecarlp/carmsurvey.pdf) to extract Carmichael numbers, considering only odd numbers greater than 3 since an even number cannot satisfy the relation.
## Code
```
import std.stdio, std.math;
bool isCarmichael(uint n) pure nothrow @nogc {
auto maxValue = ceil(sqrt(float(n)));
uint cn = n;
for (uint i = 3; i < maxValue; i += 2) {
if (cn % i == 0) {
cn /= i;
if (cn % i == 0)
return false;
if ((n-1) % (i-1))
return false;
}
}
if (cn > 1)
return false;
return true;
}
void main() {
for (uint n = 3; ; n += 2) {
if (isCarmichael(n))
writeln(n);
}
}
```
## Output
```
561
1105
1729
2465
2821
6601
8911
10585
15841
29341
41041
46657
52633
62745
63973
75361
101101
115921
126217
162401
172081
188461
252601
278545
294409
314821
334153
340561
399001
410041
449065
488881
512461
530881
552721
656601
658801
670033
748657
825265
838201
852841
997633
1024651
1033669
1050985
1082809
1152271
1193221
1461241
1569457
1615681
1773289
1857241
1909001
2100901
2113921
2433601
2455921
2508013
2531845
2628073
2704801
3057601
3146221
3224065
3581761
3664585
3828001
4335241
4463641
4767841
4903921
4909177
5031181
5049001
5148001
5310721
5444489
5481451
5632705
5968873
6049681
6054985
6189121
6313681
6733693
6840001
6868261
7207201
7519441
7995169
8134561
8341201
8355841
8719309
8719921
8830801
8927101
9439201
9494101
9582145
9585541
9613297
9890881
10024561
10267951
10402561
10606681
10837321
10877581
11119105
11205601
11921001
11972017
12261061
12262321
12490201
12945745
13187665
13696033
13992265
14469841
14676481
14913991
15247621
15403285
15829633
15888313
16046641
16778881
17098369
17236801
17316001
17586361
17812081
18162001
18307381
18900973
```
The code runs on a single core, without parallelism. No luck making it work on IDEONE though; time is checked on my machine running the process with `timeout 5s` UNIX command.
[Answer]
# Rust
Naive brute force. It can be optimized more.
[Run it on Rust Playground!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9b3d9b9d40f386bc22e70f4b3d1369d3)
```
extern crate rand;
fn gcd(a: i128, b: i128) -> i128 {
if b == 0 {
a
} else {
gcd(b, a % b)
}
}
fn power(mut a: i128, mut b: i128, m: i128) -> i128 {
let mut result = 1;
a %= m;
while b > 0 {
if b % 2 != 0 {
result = (result * a) % m;
}
b >>= 1;
a = (a * a) % m;
}
result
}
fn is_prime_miller_rabin(n: i128) -> bool {
if n < 2 {
return false;
}
if n != 2 && n % 2 == 0 {
return false;
}
let s = ((n - 1) as u128).trailing_zeros() as i128;
let d = (n - 1) / 2i128.pow(s as u32);
let witnesses: [i128; 12] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];
'next_witness: for &a in witnesses.iter().take_while(|&&x| x <= n - 1) {
let mut x = power(a, d, n);
if x == 1 || x == n - 1 {
continue;
}
for _r in 1..s {
x = power(x, 2, n);
if x == n - 1 {
continue 'next_witness;
}
}
return false;
}
true
}
fn fermat_test(n: i128) -> bool {
for a in 2..n {
if gcd(a, n) == 1 {
if power(a, n - 1, n) != 1 {
return false;
}
}
}
true
}
fn is_carmichael(n: i128) -> bool {
!is_prime_miller_rabin(n) && fermat_test(n)
}
fn main() {
let start = 561;
let end = 100000; // Adjust end limit based on time constraint
for n in start..end {
if is_carmichael(n) {
println!("{}", n);
}
}
}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 1184 numbers
Somewhat simplified implementation of Richard Pinch's methods ([Carmichael numbers up to 10^21](https://web.archive.org/web/20081015161413/http://www.chalcedon.demon.co.uk/rgep/p82.pdf "very terse"), [Carmichael numbers up to 10^16](https://www.ams.org/journals/mcom/1993-61-203/S0025-5718-1993-1202611-7/S0025-5718-1993-1202611-7.pdf "This one has a lot more detail")).
The idea is to enumerate all the Carmichael numbers less than \$N\$. We can prove that none of them will have prime factors \$>\sqrt{N}\$, so we split into two cases based on the size of the largest prime factor (specifically if it is larger or smaller than \$N^{0.3}\$).
We'll let \$n\$ be the number, and \$q\$ it's largest factor. If there is a factor greater than \$N^{0.3}\$, then since \$\frac{n}{q}\equiv1\mod{q-1}\$, enumerating all possible values of \$\frac{n}{q}\$ given \$q\$ is \$\mathcal{O}\left(N^{0.4}\right)\$. So enumerate \$q\$ from \$N^{0.3}\$ to \$N^{0.5}\$, and test with a Fermat test to base 2 and Korselt's criterion.
In the other case, we use a depth first search on products of prime factors, where we can limit the branching factor to \$N^{0.3}\$.
[Try it on ideone!](https://www.ideone.com/fuyiSZ "Python 3 – Ideone")
```
import math
from collections import deque
import itertools
# from gmpy2 import powmod as pow
def main():
x = find_carmichael(5_000_000_000)
for idx, i in enumerate(sorted(x), 1):# + len(s)):
print(idx, i)
def find_carmichael(X):
if X = q: return False
x = i
f.append(i)
if len(f) >= 2:
n1 = P*q-1
return all(n1%(p-1)==0 for p in f)
def dfs(X, primes, n=1, t=(), i=0, lcm=1):
if math.gcd(n, lcm) > 1: return
if lcm * n * len(primes) > X:
for Q in range(pow(n, -1, lcm), X//n + 1, lcm):
if math.gcd(n, Q) > 1: continue
N = n*Q
if pow(2, N, Q) == 2:
if is_carmichael0(n, Q, t):
yield N
return
for i1 in range(i, len(primes)):
p = primes[i1]
n1 = n*p
if n1 > X: break
if len(t) >= 2 and (n-1)%(p-1) == 0 and n1%lcm == 1:
yield n1
yield from dfs(X, primes, n1, t+(p,), i1+1, math.lcm(lcm, p-1))
def is_carmichael0(n, Q, t):
x = 0
f = list(t)
for i in factor(Q):
if i == x: return False
if i in t: return False
x = i
f.append(i)
if len(f) >= 3:
n1 = n*Q-1
return all(n1%(p-1)==0 for p in f)
class LazyList:
def __init__(self, I):
self.I = I
self.l = []
def __getitem__(self, i):
try:
return self.l[i]
except IndexError:
self.l.extend(itertools.islice(self.I, i+1 - len(self.l)))
return self.l[i]
def range(self, a, b=None):
if b is None:
a, b = 0, a
for i in self:
if i = b: break
yield i
def primes_():
yield 2
l = [3,5,7,11,13,17,19,23]
yield from l
p2s = deque([(p, p*p) for p in l[2:]])
n = 23
stuff = [(0, 3), (4, 5)]
while True:
p2, next_p2 = p2s.popleft()
R = range(n+4, next_p2, 2)
z = [[] for _ in R]
for i, p in stuff:
z[i].append(p)
stuff.clear()
stuff.append((p2-1, p2))
for i, (l, n) in enumerate(zip(z, R)):
# print(i, l, n)
if l:
for p in l:
i1 = i + p
if i1 >= len(R):
stuff.append((i1 - len(R) - 1, p))
else:
z[i1].append(p)
else:
yield n
p2s.append((n, n*n))
primes = LazyList(primes_())
def factor(n):
for p in primes:
while n%p == 0:
yield p
n //= p
if p*p > n:
if n > 1: yield n
return
if __name__ == '__main__': main()
```
] |
[Question]
[
Your input is a matrix (2d array) of positive integers. For example:
\begin{matrix}
1 & 1 & 4 & 7\\
1 & 3 & 5 & 6\\
2 & 1 & 4 & 5 \\
\end{matrix}
A semi-continuous transformation of this matrix is a rearranging of elements that preserves immediate neighbors. For example, we can swap the \$2\$ in the bottom left, and the \$1\$ in the top left corner.
\begin{matrix}
2 & 1 & 4 & 7\\
1 & 3 & 5 & 6\\
1 & 1 & 4 & 5 \\
\end{matrix}
This is fine, because every number has the same neighborhood counts. That is, we can make a sorted list of numbers and their neighbors, and verify the they are the same:
\begin{matrix}
\text{Number} & \text{Neighbors} \\
1 & 1,1 \\
1 & 1,2,3 \\
1 & 1,3,4 \\
1 & 2,3,4 \\
2 & 1,1 \\
3 & 1,1,1,5 \\
4 & 1,5,7 \\
4 & 1,5,5 \\
5 & 3,4,4,6 \\
6 & 5,5,7 \\
7 & 4,6
\end{matrix}
Here is another example.
\begin{matrix}
2 & 1 & 1\\
1 & 3 & 1\\
1 & 1 & 4\\
\end{matrix}
Let's make a neighbor list. Note that we are gonna have duplicate entries (which is fine)
\begin{matrix}
\text{Number} & \text{Neighbors} \\
1 & 1,1 \\
1 & 1,1 \\
1 & 1,2,3 \\
1 & 1,2,3 \\
1 & 1,3,4 \\
1 & 1,3,4 \\
2 & 1,1 \\
3 & 1,1,1,1 \\
4 & 1,1 \\
\end{matrix}
Now, can we swap the top left \$2\$ and the bottom left \$1\$? It may look fine at first glance, but we must be careful! By swapping those two elements we would create a \$1\$ which has neighbors \$2,3,4\$, which didn't exist in the first input.
Just to demonstrate, here is the matrix after this non-semi-continuous transformation:
\begin{matrix}
1 & 1 & 1\\
1 & 3 & 1\\
2 & 1 & 4\\
\end{matrix}
And here is the neighbor list:
\begin{matrix}
\text{Number} & \text{Neighbors} \\
1 & 1,1 \\
1 & 1,1 \\
1 & 1,1,3 \\
1 & 1,2,3 \\
1 & 1,3,4 \\
1 & 2,3,4 \\
2 & 1,1 \\
3 & 1,1,1,1 \\
4 & 1,1 \\
\end{matrix}
Which is has changed after the transformation, ergo the transformation is non-semi-continuous (on this input).
To clarify, semi-continuity is a property of a transformation on some specific matrix.
Your code will take a matrix as input and output the number of (unique) semi-continuous transformations. Two transformations are different if the output is different. So for example swapping two identical numbers is the same as the identity transform (doing nothing).
Or in other words: Your code will take a matrix and return the number of matrices with those dimensions that have the same neighbor-list.
You can assume that the matrix has positive width and height, and also that if m is the maximum number in the matrix, then the matrix contains all numbers 1 to m inclusive. Or alternatively you can assume that if m is the maximum number, then the matrix contains all numbers from 0 to m inclusive.
# Examples
```
[[1]] -> 1
[[1, 1], [1, 1]] -> 1
[[2, 1], [1, 2]] -> 2
[[2, 2], [1, 2]] -> 4
[[2, 1, 1], [1, 2, 1], [1, 1, 2]] -> 2
[[1, 1, 2, 1, 1, 1, 1]] -> 3
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] -> 8
[[1, 1, 4, 7], [1, 3, 5, 6], [2, 1, 4, 5]] -> 8
[[2, 1, 1], [1, 3, 1], [1, 1, 4]] -> 4
```
[Answer]
# JavaScript, 205 bytes
```
m=>(a=m.flat(w=m[o=[c=0]].length),s=a=>0+[...a].sort(),g=a=>s(a.map((v,i)=>[v,s([a[i-w],a[i+w],i%w&&a[i-1],++i%w&&a[i]])])),h=b=>b[a.length-1]?o[s(b)==s(a)&g(b)==g(a)&&b]??=++c:a.map(v=>h([...b,v]))|c)([])
```
Don't try any matrix larger than 2x2. As its time complexity is at least \$\Omega(wh^{wh+1})\$.
```
m=>(
// counter of output
c=0,
// o as a dictionary, its key is any seen transform
o=[0],
// width of input
w=m[0].length
// convert input into 1d array
a=m.flat(w),
// sort array and convert it into a string
// we don't really care what order the sort works
// as long as it works consistent
s=a=>0+[...a].sort(),
// build the neighbor list of input flatten matrix
g=a=>s(a.map((v,i)=>[
// first item its the cell value itself
v,
// and followed by its neighbors, sorted in some order
s([a[i-w],a[i+w],i%w&&a[i-1],++i%w&&a[i]])
])),
// for each possible matrix with same size and use seen numbers
h=b=>b[a.length-1]?o[
// when sort the matrix, it uses same numbers as input
s(b)==s(a)&
// its neighbor list is same as input
g(b)==g(a)&&
// if above 2 condition meets, we find out a new transform
// we use o[b] to verify if the transform we have ever seen or not
// otherwise, the expression is 0, while o[0] is initialized
b]??=
// increase the counter whenever we find out a new transform
++c:
a.map(v=>h([...b,v]))|c)([])
```
[Answer]
# Python3, 1075 bytes:
```
from copy import*
from itertools import*
R=range
c=lambda x:[(j,k)for j in R(len(x))for k in R(len(x[0]))]
def n(b):
Q={}
for x,y in c(b):
q=[]
for J,K in[(0,-1),(0,1),(1,0),(-1,0)]:
if(j:=x+J)>=0 and(k:=y+K)>=0:
try:q+=[b[j][k]]
except:1
Q[b[x][y]]=Q.get(b[x][y],[])+[sorted(q)]
return Q
v=lambda B,N:all(all(i in N[q]for i in p)for q,p in n(B).items())
def u(b,x,y,j,I):
q=[]
for J,K in[(0,-1),(0,1),(1,0),(-1,0)]:
if(j:=x+J)>=0 and(k:=y+K)>=0:
try:q+=[(b[j][k],(j,k))]
except:1
if len(q)!=len(I):return 0
for s,(_,(j,k))in zip(I,q):
if b[j][k] and b[j][k]!=s:return 0
b[j][k]=s
return b
F=lambda x:[*chain(*x)]
def r(W,b,n):
q,S=[b],[b]
while q:
if all(map(all,b:=q.pop(0))):yield b;continue
for x,y in c(b):
if not b[x][y]:
for j,k in n.items():
for i in k:
for I in permutations(i,len(i)):
B=deepcopy(b)
B[x][y]=j
if(B:=u(B,x,y,j,I))and B not in S and all(F(B).count(O)<=F(W).count(O)for O in n):q+=[B];S+=[B];break
f=lambda b:sum(v(i,n(b))for i in r(b,[[0 for _ in i]for i in b],n(b)))
```
[Try it online!](https://tio.run/##jVNLU9swEL77V2yHi0QEEydQUlP14AMzwAxM4MBBo2HsRAHlIb@p005/e6qV7Tzo82BL@nZXu9@3q3RdviZmOErzzWaWJyuYJOka9CpN8vLYc4guVV4mybLYwg88j8yL8iZ8Ga3iaQR1IMicLegsyWEO2sADWSpDauqQxR4i@pJS6U3VDAyJaeDBmH//4QH61WyNnpMGh4wLaRe03LBbaxGkz058yuyCf5/17f8EF4n@oGdkHvC6d0O/8D5EZkoWAV/3bvHoHKDM10HW4yIWcykWUjpQ1ROVloEP9jS2plqKtZR8fPqiStIemZC0JwrLXk1JZglArsoqNzD23joRQnYXRMslwU8jkTuRSazeHVInRcZSPBgS0lOr66oglDoxKhIzy5/N2TWSb7j/N/V/Mu@Ik5Y5c@2iToA9/noG2KWMfuC42lJamv2mmIKR5zbUsvimU3LNMtpUAO3VmL7bf@DF3g0dyoutfLF3tTdDx5PXSBtyXLcTkpMnFjPjBGGPtm22D7Gt@eurXirI2ryo9ypKUXcWBzw7TZOU9CmlwVqrpa3lcpKYUptKtdP0bs7wDpOU0La6mRQ3ycxNruk61Vhg29JFCzjk2jVZ5auqjEqdmIJohhpq2sUBhHyqVIovzKbegk1aPu8A28ww4BUJtwNBUdLQFWmTPDqFkfUVjtEkqUxJ7ulnfkWedkes6d6VT13nQ3n52CxxrqKFN@t0j4OiWpE3Wy4@SLpll9uJFKLvyD0joHfDbBvhnOkmzbVNNyNC@NK@bDjyvb9CAwa@ZCB8BoPGOji0Dg6tZ@9i98J3299f1hqaoDbUOQ0PnazHEC86Y3DO4CNuLxiMGHxC96PRL1dax4s283AXM@hs502W0R8rHx5UftYS3fwE)
The main strategy is to produce possible transformations and then count the number of valid results.
] |
[Question]
[
# Farkle Fest 2k19
In this challenge, we will be playing the semi-popular dice game Farkle.
[Farkle](https://boardgamegeek.com/boardgame/3181/farkle) is a dice game that has players selecting to save dice or risk rerolling the die for more points to add to their total. Players should use probability, game-state considerations and opponent tendency to make their decisions.
## How to play
[Rules lifted from this PDF, which includes scoring. There are some differences that you should note after](https://www.elversonpuzzle.com/Farkle-instructions11.pdf)
>
> Each player takes turns rolling the dice. When it's your turn, you
> roll all six dice at the same time. Points are earned every time you
> roll a 1 or 5, three of a kind, three pairs, a six-dice straight
> (1,2,3,4,5,6), or two triplets.
>
>
> If none of your dice earned points, that's a Farkle! Since you earned
> no points, you pass the dice to the next player.
>
>
> If you rolled at least one scoring die, you can bank your points and
> pass the dice to the next player, or risk the points you just earned
> during this round by putting some or all of the winning die (dice)
> aside and rolling the remaining dice. The remaining dice may earn you
> additional points, but if you Farkle, you lose everything you earned
> during the round.
>
>
> If all of your dice contribute to the score you re-roll
> the dice and add to the points already rolled, but a farkle will lose all the points, including rollover. This is called a "hot-streak"
>
>
> Scoring is based only on the dice in each roll. You can earn points
> by combining dice from different rolls. You can continue rolling the
> dice until you either Pass or Farkle. Then the next player rolls the
> six dice until they Pass or Farkle. Play continues until it is your
> turn again.
>
>
> The final round starts as soon as any player reaches 20,000 or more
> points.
>
>
> Scoring:
>
>
>
> ```
> five = 50
> one = 100
> triple 1 = 1000
> triple 2 = 200
> triple 3 = 300
> triple 4 = 400
> triple 5 = 500
> triple 6 = 600
> one thru six = 1500
> three pairs = 1500
> two triplets = 2500
> four of a kind = 1000
> five of a kind = 2000
> six of a kind = 3000
> farkle = 0
> three farkles in a row = -1000
>
> ```
>
>
Notes:
* There are varying scoring tables. Use the one linked and rewritten above
* Most online versions say something like "You cannot earn points by combining dice from different rolls". This is ***not*** how I play. If you roll triple sixes and reroll and end up with another six you now have quad sixes.
* The ending score has been increased from 10,000 to 20,000. This increases the decision points and decreases randomness.
* Some variants have a "threshold to start getting points" (often around 500). This would prevent you from keeping a roll of less than 500 if your score was 0 (or negative). This rule is ***not*** in effect.
## Challenge
In this challenge, you will write a Python 3 program to play a three player, winner takes all glory game of Farkle
Your program will receive the state of the game, which contains:
>
>
> ```
> index (where you sit at the table)
> end_score (score required to win (20,000))
> game_scores (all the players current score)
> state_variable (space for you to put whatever you want)
>
> #round values, these change during the round
> round_score (score of the current set of dice)
> round_rollover (score from previous "hot streaks")
> round_dice (current dice)
> round_set_aside (dice you set aside before rolling)
> round_used_in_score (lets you know which dice are adding to your score)
>
> ```
>
>
---
Players should return an array showing which dice they want to set aside. This should be wrapped in a set\_dice\_aside(self) method
For instance, here's a player that will save dice that add to their score until the score they would get is 500 or greater
```
class GoForFiveHundred(Bot):
def set_dice_aside(self):
while (self.round_score + self.round_rollover) < 500:
return self.round_used_in_score
return [True, True, True, True, True, True]
```
## Gameplay
The tournament runner can be found here: [Farkle\_Fest\_2K19](https://github.com/trbarron/Farkle_Fest_2K19). Run [`main.py`](https://github.com/trbarron/Farkle_Fest_2K19/blob/master/main.py) to run a tournament. I'll keep it updated with new submissions. Example programs can be found in [`farkle_bots.py`](https://github.com/trbarron/Farkle_Fest_2K19/blob/master/farkle_bots.py). Lots of code was lifted from [maxb](https://codegolf.stackexchange.com/users/79994/maxb), many thanks for that framework and code.
A tournament consists of 5000 games per 10 players (rounded up, so 14 players means 10,000 games). Each game will be three random players selected from the pool of players to fill the three positions. Players will not be able to be in the game twice.
## Scoring
The winner of each game is the player with the most points at the end of the game. In the case of a tie at the end of a game all players with the maximum money amount are awarded a point. The player with the most points at the end of the tournament wins. I will post scores as I run the games.
The players submitted will be added to the pool. I added three dumb bots to start.
## Caveats
Do not modify the inputs. Do not attempt to affect the execution of any other program, except via cooperating or defecting. Do not make a sacrificial submission that attempts to recognize another submission and benefit that opponent at its own expense. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are banned.
Limit the time taken by your bot to be ~1s per turn.
Submissions may not duplicate earlier submissions.
If you have any questions, feel free to ask.
## Winning
The competition will stay open indefinitely, as new submissions are posted. However, I will declare a winner (accept an answer) based on the results two month after this question was posted (November 2nd).
Simulation of 5000 games between 5 bots completed in 675.7 seconds
Each game lasted for an average of 15.987000 rounds
8 games were tied between two or more bots
0 games ran until the round limit, highest round was 48
```
+----------------+----+--------+--------+------+------+-------+
|Bot |Win%| Wins| Played| Max| Avg|Avg win|
+----------------+----+--------+--------+------+------+-------+
|WaitBot |95.6| 2894| 3028| 30500| 21988| 22365|
|BruteForceOdds |38.7| 1148| 2967| 25150| 15157| 20636|
|GoForFiveHundred|19.0| 566| 2981| 24750| 12996| 20757|
|GoForTwoGrand |13.0| 390| 2997| 25450| 10879| 21352|
|SetAsideAll | 0.2| 6| 3027| 25200| 7044| 21325|
+----------------+----+--------+--------+------+------+-------+
+----------------+-------+-----+
|Bot | Time|Time%|
+----------------+-------+-----+
|BruteForceOdds |2912.70| 97.0|
|WaitBot | 58.12| 1.9|
|GoForTwoGrand | 13.85| 0.5|
|GoForFiveHundred| 10.62| 0.4|
|SetAsideAll | 7.84| 0.3|
+----------------+-------+-----+
```
And the results without WaitBot, which I'm still morally undecided on:
```
+----------------+----+--------+--------+------+------+-------+
|Bot |Win%| Wins| Played| Max| Avg|Avg win|
+----------------+----+--------+--------+------+------+-------+
|BruteForceOdds |72.0| 2698| 3748| 26600| 19522| 20675|
|GoForFiveHundred|37.2| 1378| 3706| 25350| 17340| 20773|
|GoForTwoGrand |24.3| 927| 3813| 26400| 14143| 21326|
|SetAsideAll | 0.1| 5| 3733| 21200| 9338| 20620|
+----------------+----+--------+--------+------+------+-------+
+----------------+-------+-----+
|Bot | Time|Time%|
+----------------+-------+-----+
|BruteForceOdds |4792.26| 98.9|
|GoForTwoGrand | 24.53| 0.5|
|GoForFiveHundred| 18.06| 0.4|
|SetAsideAll | 13.01| 0.3|
+----------------+-------+-----+
```
[Answer]
# BruteForceOdds
Here's that brute force bot:
```
from main import Controller
from farkle_bots import Bot
scoreDevice = Controller(1, 1, [], 0)
class BruteForceOdds(Bot):
def set_dice_aside(self):
stop_score = self.round_score + self.round_rollover
if self.game_scores[self.index] + stop_score > max(self.game_scores + [self.end_score]):
# Take the win
return [True, True, True, True, True, True]
using = self.round_used_in_score[:]
if self.round_dice.count(5) < 3:
for i in range(len(using)):
if self.round_dice[i] == 5 and not self.round_set_aside[i] and using.count(True) > self.round_set_aside.count(True)+1:
using[i] = False
if self.round_dice.count(1) < 3:
for i in range(len(using)):
if self.round_dice[i] == 1 and not self.round_set_aside[i] and using.count(True) > self.round_set_aside.count(True)+1:
using[i] = False
if using.count(True) < 3 and self.round_rollover == 0:
# Stopping here is basically never a good idea
return using
if bruteScore(self.round_dice, using, self.round_rollover) > stop_score:
return using
return [True, True, True, True, True, True]
def bruteScore(round_dice, set_aside, base_score):
base_dice = []
for i in range(len(round_dice)):
if(set_aside[i]):
base_dice.append(round_dice[i])
totalCount = 0
totalScore = 0
for new_dice in allPossibleRolls(len(round_dice) - len(base_dice)):
dice = base_dice + new_dice
keep = [True]*len(base_dice)+[False]*len(new_dice)
farkle, round_score, round_rollover, used_in_score = scoreDevice.score(dice, keep, base_score)
totalCount += 1
if not farkle:
totalScore += round_score + round_rollover
return totalScore / totalCount
def allPossibleRolls(length):
if length == 0:
yield []
return
for i in range(1,7):
for l in allPossibleRolls(length-1):
yield [i]+l
```
It only fares slightly better than the example program GoForFiveHundred.
EDIT: Made it a bit smarter. Now it does noticeably better than any of the example bots.
[Answer]
# WaitBot
```
class WaitBot(Bot):
def set_dice_aside(self):
return [self.round_rollover+self.round_score > 5000]*6
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PzknsbhYITwxs8Qpv8RQA0hoWnFxpqSmKRSnlsSnZCanxicWZ6akahSn5qSBpDiLUktKi/IUokECekX5pXkp8UX5OTn5ZalF2khixcn5RakKdgqmBgYGsVpm//8DAA "Python 3 – Try It Online")
This basically takes no dice until the total round score is greater than 5000. Really, it's betting on getting hot streaks before farkles.
This wins about 97% of the time when put up against the default three bots.
Edit: Erm, this may not be valid, since you need to `putting some or all of the winning die (dice) aside`. I'm waiting on confirmation from the asker on this, since the controller allows it.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/186529/edit).
Closed 4 years ago.
[Improve this question](/posts/186529/edit)
Write a program that reads a string, and inserts commas to divide large numbers in groups of 3. i.e. 10000 => 10,000. It should 'fix' incorrectly formatted numbers as described below.
* It must work for all numbers on the same line
* It should not modify numbers after a decimal point. i.e. 1234.5678 => 1,234.5678
* Leading zeros should be removed (or inserted where appropriate):
+ 00000 => 0
+ 00001234 => 1,234
+ .1234 => 0.1234
+ 00.1234 => 0.1234
+ 1000.1234 => 1,000.1234
* All non-digit characters should not be altered.
* It should correct, incorrectly placed "," characters only when followed before or after a digit:
+ 10,,00 => 1,000
+ 00,000 => 0
+ a,2 => a2
+ 2,a => 2a
+ ,a2 => ,a2
+ 0,a2 => 0a2
+ ,,, => ,,,
+ ,,,. => ,,,.
+ ,,,1 => 1
+ ,.,,1 => 0.1
* Numbers that contain multiple "." should not be treated as a number, and therefore no comma separation should be used:
+ 1..3 => 1..3
+ 1234.5678.9012 => 1234.5678.9012
+ 1234,,.5678abc.123 => 1,234.5678abc0.123
+ 1234.,.5678abc.123 => 1234.,.5678abc0.123
* Explanations to unusual cases:
+ ,,,. => ,,,. (not a number, no special meanings to ",", ".")
+ ,,,.0 => 0 (these characters are neighbouring a number and treated as such)
+ 1,,, => 1
+ ,,,1 => 1
+ ,.,,1 => 0.1 (the "." indicates decimal number, remove incorrectly placed "," in number).
+ ,.,,.1 => ,.,,.1 (not a number because multiple ".")
+ a,,,b1234 = > a,,,b1,234 (first few characters are not neighbouring a number and treated as text)
Example inputs:
```
10000
10,000
$1234.12
~$123456789.12345~
HELLO123456.99BYE
The_amount_€45678_is_$USD51805.84
5000000-1999999=3000001
!1234567.1234+1234567.1234=2469134.2468!
00000a00
0b0001234
.a.1234
00.1234
1000.1234
10,,00
00,000
a,2
2,a
,a2
0,a2
,,,
,,,.
,,,1
,.,,1
1..3
1234.5678.9012
1234,,.5678abc.123
1234.,.5678abc.123
,,,.
,,,.0
1,,,
,,,1
,.,,1
,.,,.1
a,,,b1234
```
Corresponding outputs:
```
10,000
10,000
$1,234.12
~$123,456,789.12345~
HELLO123,456.99BYE
The_amount_€45,678_is_$USD51,805.84
5,000,000-1,999,999=3,000,001
!1,234,567.1234+1,234,567.1234=2,469,134.2468!
0a0
0b1,234
.a0.1234
0.1234
1,000.1234
1,000
0
a2
2a
,a2
0a2
,,,
,,,.
1
0.1
1..3
1234.5678.9012
1,234.5678abc0.123
1234.,.5678abc0.123
,,,.
0
1
1
0.1
,.,,.1
a,,,b1,234
```
Code golf: shortest code wins.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 71 bytes
```
/[\d.,]+/_/\d/&/\..*\./^&(`,
^0+
^\B
0
'.&`\.?0+$
/^\d+/_r`\B...
,$&
```
[Try it online!](https://tio.run/##VVDNTsMwDL77LSZVBVHjxP0ZzWFCqpjEYRIHxgER2qZ0EjswpDGuO/A8PBUvUuJ0lcBSPv/k8xc7@81hu3M8DOrJ9oTPiWqU7VWsLNGFJVXH5y0C1DrxYCvQcEZxa@laJxGAqm3vO/atrYgIMIqHgbU3YI3iIk6znDiFY4iK@VVpKERHuF2uVndjlYypHpewft007u39c3dofr6@A7vZfjTRw/1NwaUuqMyh0MEu2QRbZCFlmJ30g3ryN1mk@dywH8P7cgaB7/xsupNGTwBygeivRi8rTBGiUMdtHKaQogN0KWgBRJRDAgxIgkyUQVhb5ifjnwipp0nBdS8iPTL@lyYl8t93Up5EBYn9AIiddP4C "Retina – Try It Online") Link includes test cases. Explanation:
```
/[\d.,]+/_
```
Find all runs of digits, `.`s and `,`s.
```
/\d/&
```
Ignore those with no digits.
```
/\..*\./^&
```
Ignore those with two `.`s.
```
(`
```
Process the rest of the script on each remaining match.
```
,
```
Delete all commas.
```
^0+
```
Delete all leading zeros.
```
^\B
0
```
Insert a leading zero if the number does not begin with a digit.
```
'.&`
```
If the number contains a `.`...
```
\.?0+$
```
... delete trailing zeros and any preceding `.`.
```
/^\d+/_
```
On the part of the number before the `.`...
```
r`\B...
,$&
```
Match groups of three starting from the end, but leave at least one digit at the beginning, and insert commas before each match.
] |
[Question]
[
Graph theory is used to study the relations between objects. A graph is composed of vertices and edges in a diagram such as this:
```
A-----B
| / \
| / \
| / E
| / /
|/ /
C-----D
```
In the above diagram, `A` is linked to `B` and `C`; `B` is linked to `A`, `C`, and `E`; `C` is linked to `A`, `B`, and `D`; `D` is linked to `C` and `E`; and `E` is linked to `B` and `D`. As that description was rather wordy, a graph can be represented as a symmetric boolean matrix where a 1 represents a connection and a 0 represents the lack thereof. The above matrix is translated to this:
```
01100
10101
11010
00101
01010
```
For the purpose of this problem, the matrix definition can be extended to include the distances or weights of the paths between nodes. If individual ASCII characters in the diagram have weight 1, he matrix would be:
```
05500
50502
55050
00502
02020
```
A "complete graph" consists of a set of points such that each point is linked to every other point. The above graph is incomplete because it lacks connections from `A` to `D` and `E`, `B` to `D`, and `C` to `E`. However, the subgraph between `A`, `B`, and `C` is complete (and equally weighted). A 4-complete graph would look like this:
```
A---B
|\ /|
| X |
|/ \|
C---D
```
and would be represented by the matrix:
```
01111
10111
11011
11101
11110
```
This problem is as follows: **Given a symmetric matrix representing a graph and a positive integer `n`, find the number of distinct equally-weighted complete subgraphs of size `n` contained within**.
You may assume that the input matrix is numeric and symmetric, and may choose input/output format. An entry in the matrix may be part of multiple equally-weighted subgraphs as long as they are distinct and of equal size. You may assume that `n` is a positive integer greater than or equal to 3.
The winning criterion for this challenge is **code golf**. Standard rules apply.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
ịⱮịŒDḊẎE
Jœcç€⁸S
```
[Try it online!](https://tio.run/##y0rNyan8///h7u5HG9cByaOTXB7u6Hq4q8@Vy@vo5OTDyx81rXnUuCP4////0dGWOoY6RjrGOkaxOlwK0YY6FjrmQGgI5hkBWWZADJEzBsuY6BhD5SD6DGK5Yv8bAwA "Jelly – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18 16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Assumes self-connections may be any weight (i.e. they are not necessarily only either \$0\$ or the equal weight).
```
Jœcṗ2EÐḟœị³EƲ€S
```
**[Try it online!](https://tio.run/##y0rNyan8/9/r6OTkhzunG7kenvBwx/yjkx/u7j602fXYpkdNa4L///8fHW2pY6hjpGOsYxSrw6UQbahjoWMOhIZgnhGQZQbEEDljsIyJjjFUDqLPIJYr9r8xAA "Jelly – Try It Online")**
the two subsets of size 3 being ACE and BCD
[With n=2](https://tio.run/##y0rNyan8/9/r6OTkhzunG7kenvBwx/yjkx/u7j602fXYpkdNa4L///8fHW2pY6hjpGOsYxSrw6UQbahjoWMOhIZgnhGQZQbEEDljsIyJjjFUDqLPIJYr9r8RAA "Jelly – Try It Online") all 10 subsets of size 2 work as its symmetric.
### How?
```
Jœcṗ2EÐḟœị³EƲ€S - Link: list of lists of integers, M; integer, n
J - range of length of M = [1,2,3,...,length(M)]
œc - Combinations of length n e.g. [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
€ - for each:
Ʋ - last four links as a monad:
ṗ2 - Cartesian power with 2
Ðḟ - discard if:
E - all-equal (i.e. diagonal co-ordinates like [3,3])
œị - multi-dimensional index into:
³ - program's 3rd argument (1st input), M
E - all equal?
S - sum
```
[Answer]
# [Python 2](https://docs.python.org/2/), 195 bytes 178 bytes 168 bytes
I'm sure there's a lot more golfing possible here, but for a change I want to get an entry in before there are dozens of other ones. I've provided a couple of test cases on TIO, but would love more examples.
First round of suggested golf steps: Remove some spaces, be smarter about the import. Shorter way of testing if the single link value in a set is zero (Thanks to M. XCoder).
Second round: ElPedro points out that in this case a program is shorter than the function. I was hoping to find a way to package this as a lambda, so was thinking "function" from the start. Thanks.
```
from itertools import*
r=set()
M,n=input()
for g in set(combinations(range(len(M)),n)):
s={M[i][j]for i in g for j in g if i>j}
if len(s)==1and{0}!=s:r.add(g)
print r
```
[Try it online!](https://tio.run/##jY7BasMwDIbvfgrtFLuY4XS3gvsGeQKTQ5Y4mUIjBduFjtJn9@K2lB12GELo0y/@H63f6Ytpn3sePFioqiqPgRfA5ENiPkXAZeWQdiLY6JNUotFkkdZz4ZEDTIAE5dTz8onUJWSKMnQ0eXnyJBulNCl1EBDttXHYurktPiy@CQrOD8QR8DjfRIHijMrauqPham5vNh7CezcMclJiDUgJQt6eFf7ie1meV7CDfZbOGV1vZbRptSvz3nd@bhubX7p56a3SH@IfCfUfCfUrIef8Aw "Python 2 – Try It Online")
A slightly ungolfed version, to clarify logic:
```
from itertools import combinations
def f3(M,n):
r = set()
groups = set(combinations(range(len(M)), n)) # all possible combinations of indexes
for group in groups:
# Generate a set of link values associated with the current combination
# This selects only non-diagonal indexes, assuming matrix symmetry.
s = {M[i][j]for i in group for j in group if i>j}
# If the set has only one member, and that's not zero, you have
# a connected subgraph.
if len(s) == 1 and 0 not in s:
r.add(group)
return r
```
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 152 bytes
```
import StdEnv,Data.List
$m n=sum[1\\i<-subsequences[0..size m-1]|length i==n,j<-permutations i|case[m.[x,y]\\x<-i&y<-j]of[u:v]=all((==)u)v&&u>0;_=1<0]/2
```
[Try it online!](https://tio.run/##dVJbi9pAFH5OfsVBF3HBaLT4YpOFUvsgSLegbzHImBx1lrnYzIyXrvvXm56JCqVQAplz/b7znZlCIFO11KUTCJJxVXN50JWFhS2/qWNvyizrz7mx4ZMElRons@FqxZPIuI3Bnw5VgSaL@33DfxFANMyvAtXO7oGnqeq9JdEBK@kss1wrA/xaMIOZ7Gfn3iVfrc5JxDuXJHrL9TZzk2OeMiG63TR9ds/HTse9xJ/X6TCJ88GoHgzA7tEgsAphqyvYoLVYwXL2ClwdnA0fo1@MRdmfvfYe5lctJVPlnCsMCeaiHRRMwYEZ4zFh61ThBwRGO7AVP8OJkwTphOUHgVHJd9zCkQmHpgcbZ0FpS52Vdrs9LJbT2fdwYRlxn8KgDd1sPWHVzuQ9OD1DCju0f01wq6E8Zfw2vGlAb8MgyFROQatnihjIX5PHNl5Ta6aInpegnNyQaL31bU6isqbVcAqCNnfCCln5RQjPZm50JIvi7@33dqNl2VAUsFrRL4km4Ls/vOsNijSn@QiDFJ6aZmILT3usMAz@RX@w38mRBqUrIdEPtcH1DvsCLRq2aajQ2P9MGxBpN/MdE/BlzRobFE2XVZ24wUdRk6rj8TiOw3E8jkfh2B9h3NjxiL760@9iK9jO1NFsXk8vikle3Jwfgll6SPIP "Clean – Try It Online")
TIO driver takes `n` as a command-line argument and the matrix through STDIN (weights up to 9).
The actual function `$ :: {#{#Int}} Int -> Int` works with any size weights.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 90 bytes
There is probably some room to further golf this, after some test cases are posted.
We construct a graph from the unitized adjacency matrix, and then use the `FindClique` function with `All` as the third argument to list out the vertices with complete subgraphs. We then select the submatrices of the original input corresponding to the cliques (which will have zeros along the diagonal) and count the number of distinct elements which should be 2 if the weights are equal.
In this implementation, self connections can have a weight other than zero and the graph will still be considered complete and equal weighted, so long as the weights of all self connections in the subgraph are identical.
```
Count[Length@*Union@@@(b[[#,#]]&/@FindClique[AdjacencyGraph[Unitize/@(b=#)],{#2},All]),2]&
```
[Try it online!](https://tio.run/##TUw9C8IwFPwxgWLlQUPAsZBS0MXBxSlkiG1qImmqJR005LfH1@Igj3v3wXGjCkaPKthO5aHO7bT4IM7a34Ph@6u3k@ec725CECBSFhU/Wt@3zr4WLZr@oTrtu/dpVk8jsB3sR1dYr0kpIRKWoHFOlsBkkS@zxelBxEjhgEeBJogrr2Cb/jnU9C/HDxtSwiWZvw "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
In one of [this question's](https://codegolf.stackexchange.com/questions/141315/what-an-odd-function) bonuses I asked you to design a permutation on the natural numbers such that the probability of a random term being odd was \$1\$. Now let's kick it up a notch. I want you to design and implement a permutation, \$f\$, on the natural numbers such that, for every integer \$n\$ greater than 0, the probability on \$f\$ of a member being divisible by \$n\$ is \$1\$.
### Definition of Probability
To avoid confusion or ambiguity I am going to clearly lay out what is meant by probability in this question. This is adapted directly from my original question.
Let us say we have a function \$f\$ and a predicate \$P\$. The probability of a number fulfilling \$P\$ will be defined as the limit of the number of members of \$f\{1..n\}\$ fulfilling the predicate \$P\$ divided by \$n\$.
Here it is in a nice Latex formula
$$
\lim\_{n\to\infty} \dfrac{\left|\left\{x : x\in \left\{1\dots n\right\}\right\},P(f(x))\right|}{n}
$$
---
In order to have a probability of something being \$1\$ you don't need every member to satisfy the predicate, you just need the ones that don't to get farther apart the bigger they are.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with less bytes being better.
You may take the natural numbers to either include or exclude 0. Both are fine.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
!uΣz:NCNmΠN
```
[Try it online!](https://tio.run/##yygtzv6vkPuoqfHhjsWmBv8VS88trrLyc/bLPbfA7/9/AA "Husk – Try It Online") Or [showing the stats for the first `100` n in the first `5000` terms](https://tio.run/##yygtzv6v4Htivb6pgYGB8qFlD3csNjQweNQ2EcR/1NT4v/Tc4iorP2e/3HML/P7/BwA)
### Explanation
```
mΠ Map factorial over
N the Natural numbers
CN Cut into lists of lengths corresponding to the natural numbers
z:N ZipWith append the natural numbers and ^
Σ Concatenate into one list
u Remove duplicates
! Index
```
### Proof (Without the `u`)
For triangle numbers : `f(½n*(n+1))=n`
Otherwise : `f(n)=k!` for some `k`.
As the density of triangular numbers is zero, this has the same probability as the sequence of factorials: `1`
] |
[Question]
[
### Introduction:
I think most people will know how darts work. But since some might not, here are the rules of playing Darts in a nutshell:
* Amount of players: 2
* Starting points: 501
* Goal: Get your points to 0 first
* Darts per player: 3
* Available numbers on the board: 1 through 20, and Bulls-eye
Here is the layout of a Dartboard:
[](https://i.stack.imgur.com/dPyoYm.jpg)
* Each number is worth an equal amount of points
* Each triple (the inner red-green circle) is 3x the number
* Each double (the outer red-green circle) is 2x the number
* The red center is called the Bulls-eye or Double-Bull, which is worth 50 points
* And the outlined part of the center around the Bulls-eye (also known as Single-Bull) is worth 25 points
Some other rules:
* You'll have to finish to 0 exactly
* The very last dart that puts your points to 0 must be a double or the Bulls-eye
* If a dart would leave your remaining total on 1 or less than 0, the entire set of three darts of which it forms a part is discarded (since you aren't able to finish 1 or less than 0 with a double)
* Once you've reached (exactly) 0, you won't have to throw any remaining darts of the three you throw in a single turn
### Relevant information regarding this Challenge:
Although every player has of course preferred doubles to finish with (Double-20 is preferred by some of the pros for example), in general - and for the sake of this challenge - this will be the order of prioritization on finishing doubles:
```
16, 8, 20, 12, 4, 18, 14, 10, 6, 2, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1, Bulls-Eye
```
Why? Let's compare a double-16 and double-17 finish. If you want to throw the double-16, but throw in the 16 instead by accident, you can continue to double-8. If you want to throw the double-17, but throw in the 17 instead, you must first throw an odd number (like 1 or 3), before you can try your best on a finishing double again. If we look at the following, you can see the next move in case you accidentally throw a single instead of a double:
```
Bulls-eye
20-10-5
19
18-9
17
16-8-4-2-1
15
14-7
13
12-6-3
11
```
Clearly 16 is your best bet, hence the given order of prioritizing above. (And since the Bulls-eye is the smallest, that has the lowest preference for the sake of this challenge.)
### Challenge:
So, those are the rules of playing Darts. As for this challenge:
Given an input integer in the range of 2-170 (excluding 169, 168, 166, 165, 163, 162, 159; these cannot be finished within 3 darts), output the steps required to finish it following these rules in this exact order of precedence:
1. You must try to finish it in as few darts as possible
2. You must keep the prioritizing in mind when doing so for your finishing darts
3. When multiple options are available with the same priority, we pick the option with the highest number. I.e. 1.) For `131` the expected result is `T20, T13, D16` instead of `T19, T14, D16` or `T18, T15, D16` or `T17, T14, D16` etc., because `T20` is the highest number. 2.) For `109` the expected result is `17, T20, D16` instead of `20, T19, D16`, because `T20` is the highest number.
4. If exactly three darts must be thrown to finish, sort the first two throws by Single, Triple, Double, Bulls-Eye, Single-Bull
Keeping the rules above in mind, these will be your strict input-output pairs (format of both input and output is flexible, though):
```
Legend: D = Double; T = Triple; BE = Bulls-eye; SB = Single-Bull
Points left: Darts to throw (in exact order)
2 D1
3 1, D1
4 D2
5 1, D2
6 D3
7 3, D2
8 D4
9 1, D4
10 D5
11 3, D4
12 D6
13 5, D4
14 D7
15 7, D4
16 D8
17 1, D8
18 D9
19 3, D8
20 D10
21 5, D8
22 D11
23 7, D8
24 D12
25 9, D8
26 D13
27 11, D8
28 D14
29 13, D8
30 D15
31 15, D8
32 D16
33 1, D16
34 D17
35 3, D16
36 D18
37 5, D16
38 D19
39 7, D16
40 D20
41 9, D16
42 10, D16
43 11, D16
44 12, D16
45 13, D16
46 14, D16
47 15, D16
48 16, D16
49 17, D16
50 BE
51 19, D16
52 20, D16
53 T7, D16
54 D11, D16
55 T13, D8
56 T8, D16
57 SB, D16
58 D13, D16
59 T9, D16
60 D14, D16
61 T15, D8
62 T10, D16
63 T13, D12
64 D16, D16
65 T11, D16
66 D17, D16
67 T17, D8
68 T12, D16
69 T15, D12
70 D19, D16
71 T13, D16
72 D20, D16
73 T19, D8
74 T14, D16
75 T17, D12
76 T20, D8
77 T15, D16
78 D19, D20
79 T13, D20
80 T16, D16
81 T19, D12
82 BE, D16
83 T17, D16
84 T20, D12
85 T15, D20
86 T18, D16
87 T17, D18
88 T16, D20
89 T19, D16
90 BE, D20
91 T17, D20
91 T17, D20
92 T20, D16
93 T19, D18
94 T18, D20
95 T19, D19
96 T20, D18
97 T19, D20
98 T20, D19
99 7, T20, D16
100 T20, D20
101 T17, BE
102 10, T20, D16
103 11, T20, D16
104 T18, BE
105 13, T20, D16
106 14, T20, D16
107 T19, BE
108 16, T20, D16
109 17, T20, D16
110 T20, BE
111 19, T20, D16
112 20, T20, D16
113 T20, T7, D16
114 T20, D11, D16
115 T19, D13, D16
116 T20, T8, D16
117 T20, SB, D16
118 T20, D13, D16
119 T20, T9, D16
120 T20, D14, D16
121 T19, D16, D16
122 T20, T10, D16
123 T19, D17, D16
124 T20, D16, D16
125 T20, T11, D16
126 T20, D17, D16
127 T19, D19, D16
128 T20, T12, D16
129 T19, D20, D16
130 T20, D19, D16
131 T20, T13, D16
132 T20, D20, D16
133 T17, BE, D16
134 T20, T14, D16
135 T19, D19, D20
136 T18, BE, D16
137 T20, T15, D16
138 T20, D19, D20
139 T19, BE, D16
140 T20, T16, D16
141 T17, BE, D20
142 T20, BE, D16
143 T20, T17, D16
144 T18, BE, D20
145 T20, T15, D20
146 T20, T18, D16
147 T19, BE, D20
148 T20, T16, D20
149 T20, T19, D16
150 T20, BE, D20
151 T20, T17, D20
152 T20, T20, D16
153 T20, T19, D18
154 T20, T18, D20
155 T20, T19, D19
156 T20, T20, D18
157 T20, T19, D20
158 T20, T20, D19
160 T20, T20, D20
161 T20, T17, BE
164 T20, T18, BE
167 T20, T19, BE
170 T20, T20, BE
```
*NOTE: Test cases are done by hand, so if you see any mistakes, please comment down below.
Multiple fixed thanks to @JohanKarlsson, @JonathanAllan, and @Sebastian*
### Challenge rules:
* Input and output format are flexible. Can be a list of Strings, array of Objects, single STDOUT-printline, your call. You can also choose your own formatting regarding the Triples, Doubles, Bulls-Eye and Single-Bull. Please state what you've used in your answer.
### General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
[Answer]
# Python 3, 987 1,003 586 bytes
*Edit: Fixed problem with T20's using some hacky code.*
*Edit: Added in golfed version.*
```
from itertools import*
def d(i):
f={v*2:"D"+str(v) for v in [16,8,20,12,4,18,14,10,6,2,19,17,15,13,11,9,7,5,3,1]}
f[50]="BE"
t={3*i:"T"+str(i) for i in range(20,6,-1)}
t.update({i:str(i) for i in range(20,0,-1)})
t.update({2*i:"D"+str(i) for i in range(20,10,-1) if i%3!=0})
t.update({50:"BE", 25:"SB"})
if i in f:
return f.get(i)
else:
for n,x in product(f,t):
r=i-n
if r in t:
return ' '.join((t.get(r),f.get(n)))
for n,x,y in product(f,t,t):
r=i-n
if x+y==r:
b=x!=60 or y>20
return ' '.join((t.get(x if b else y),t.get(y if b else x), f.get(n)))
```
[Try it online!](https://tio.run/##pVjbbts4EH3nV7AGFrFa1RBJURcDXmADt/2A5mXRDQrDVlrtKrYhyW2MIN@eHVKkLZKj7sMaUBzP5fCcIYeSeDz33w978fr60B4ead1XbX84NB2tH4@HtqfH9rA7bXuyqx7obtP23bzeH6MlofBp6q7/@lDv6@571dEV/cKymBYx5UlMGY9pCl/wk6lvMIETjKyEK4dLwiXgYjEFE1jAoH7fa@wR7PPw/1u@nK1n77q@nQ@GiD4cWhNI671L58VBWZyOu01fzZ9lspzdfpi9RNrdf28PP/UQ4m29nN0N6PUAXCvMdrP/Vs1BUBa/Z9HLKOsCWS8nkxKdFGFZXA24/sWATCfT@oHWv4k3qwSHMXqgsnI5@3yrhOkwlbY/KkBbgmHK1Ket@lN7dSy@Vb2eVB1QNV11Db0WOKZPCs0sh7lNjg2h6JozDPG4gYj9N6it4vHeoDhBwPEaB9gDkgs04nsT05vF34d6P5@bIijiF4QodhWZNRJFuJiYnn@l53/qeqLvAH@1uiaEsv5T2pNGerOiWUKB@vl3nujpoefI0tNx56m4p8mavKp27ivVL6f9dq7@GKWbffezajsKAulsNiPcJbxmRLgWaF8wpl4YJzIM4yTzwgTJXYvQYYUXlpIyREsJS9wwSRgL0CDM1bDOCHM1yCHM1bDOCXM15EOYq2FdEJYH3MDoaliXhJUBt4JwTwJLCGcBOYjzNDBGuAjYQZwngnHCXRXlEOepYIJwT8agg3s6WEq4K4QNSoSvRBLhKmGDFOFLyYgQ4ZICq68lJ0IGNVSBvhgYJA@KqAJ9MSURZVBFCEw9MTwhKQvKqAJdMeo2p80irKUyu4rUPVKbZVhQZXZlqduoNudhVZXZ1aZuxdrsTZYRKF2Btx@I9CbLCJSuQG4ESlfgnYX1p8wIl67CO7NmpKvwrjDRrsLPt8bsz56pk3Ql3hnmmb8gTf0y5nEZlmXGPbNRmgmEOrRV5ks1Bc98qaYEmb9ITcmy3IsfGjkrPLNZK1mJsAc6ua/WVCFnGH2wc3@FG7svd9gv8tQzm2LmEmGv6Hgzq@EBJsfYA0yBsIemy0uEPdiLxLOb4hcMYQ90Cu4tdxMuMPZgTxH2CkYi9BUdTy0zC7nA5hZ2p6JA6CucEqOfkTIJ6UN4yRD4X9k5JgvgsTkHmmWKyFI4EosvSYlNusLJkXiFU2DxgBPsyReqLEnCFIBiCQskw6bGEu5vzyMo4e/RI18aKNdw0t@oRymZv1uPfHlQAA1X@Fv2KKX09@2rj4VFUHDu048aZJTC/W185BMBnN3QmftUZHKYdUpkHQjrzELUwvrywGd3eeY@OZkRL6BlCGqahHFkadh9inGGdZZ18hDV7v/Mfc4ymbY8HCvPBVYisLZ2PEMyL7A51mDWWSCw3DpLrNWMU2AVsrDu05qBtXUXHGs76xRI71lfiqDaSRFyQqbqaPepzrSgTcwRVGmdxYRKjVoinWgS0wRBtZOZMlykAk050o82D2muyzynKa5Rg8oJjdqJNJe967A0xzXqxGJCo3Yi3XVZHzLBRapEySZEaifSXZe1I8XUkPAOJdMJlRpWTmXCu5bMpsZUsPlEpoYtpjIBNksmnCozmyiC2pqzCSXaN0FH@fKJAcGn3s5Hb@xfd/W2V0dZ9b6fD7ZFd2zqfn5D6U30JbmPloE5piz6wu4XTde39XE@nEMNUep0xEDbhL/2gMOW79n9cBC2aZqvPzZNvYNh79pTRewpyz/VeZSumS3A1s1Hxyl9e3bORDZdV7U91ecREButVk66Or5Q5ktK9bStjr17rHJslfjZx03dnNqKHvb0@WVJ/zycLqJunl9u6JsV/VT/qPZj42wBxB83epD4yiKmKIvRqZJfiI@bpqvsGdzFceVpOP7RNPoApqPbw@OxqfpqR7vTdlt13cOpac6LWUTI9YRGH71Gr/8C)
Ungolfed version:
```
from itertools import product
def darts(inp):
list_finishes = [16, 8, 20, 12, 4, 18, 14, 10, 6, 2, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1]
finishes = {finish*2:"D"+str(finish) for finish in list_finishes}
finishes.update({50:"BE"})
throws = {3*i:"T"+str(i) for i in range(20,6,-1)}
throws.update({i:str(i) for i in range(20,0,-1)})
throws.update({2*i:"D"+str(i) for i in range(20,10,-1) if i%3!=0})
throws.update({50:"BE", 25:"SB"})
if inp in finishes:
return finishes.get(inp)
else:
for finish, x in product(finishes, throws):
remaining = inp - finish
if remaining in throws:
return ', '.join((throws.get(remaining), finishes.get(finish)))
for finish, x, y in product(finishes, throws, throws):
remaining = inp - finish
if x + y == remaining:
return ', '.join((throws.get(x if x!= 60 or y>20 else y), throws.get(y if x!= 60 or y>20 else x), finishes.get(finish)))
```
Little effort has gone into golfing this code, as I intended it to be a reference solution more than anything. Anyone who wants to improve this code is free to post it as their own solution or edit my answer. I have also created a function to test your function against the given values ([Try it online with my function](https://tio.run/##pVjbbts4EH3nV7AGFrFa1RBJURcDXmADt/2A5mXRDQrDVlrtKrYhyW2MIN@eHVKkLZKj7sMaUBzP5fCcIYeSeDz33w978fr60B4ead1XbX84NB2tH4@HtqfH9rA7bXuyqx7obtP23bzeH6MlofBp6q7/@lDv6@571dEV/cKymBYx5UlMGY9pCl/wk6lvMIETjKyEK4dLwiXgYjEFE1jAoH7fa@wR7PPw/1u@nK1n77q@nQ@GiD4cWhNI671L58VBWZyOu01fzZ9lspzdfpi9RNrdf28PP/UQ4m29nN0N6PUAXCvMdrP/Vs1BUBa/Z9HLKOsCWS8nkxKdFGFZXA24/sWATCfT@oHWv4k3qwSHMXqgsnI5@3yrhOkwlbY/KkBbgmHK1Ket@lN7dSy@Vb2eVB1QNV11Db0WOKZPCs0sh7lNjg2h6JozDPG4gYj9N6it4vHeoDhBwPEaB9gDkgs04nsT05vF34d6P5@bIijiF4QodhWZNRJFuJiYnn@l53/qeqLvAH@1uiaEsv5T2pNGerOiWUKB@vl3nujpoefI0tNx56m4p8mavKp27ivVL6f9dq7@GKWbffezajsKAulsNiPcJbxmRLgWaF8wpl4YJzIM4yTzwgTJXYvQYYUXlpIyREsJS9wwSRgL0CDM1bDOCHM1yCHM1bDOCXM15EOYq2FdEJYH3MDoaliXhJUBt4JwTwJLCGcBOYjzNDBGuAjYQZwngnHCXRXlEOepYIJwT8agg3s6WEq4K4QNSoSvRBLhKmGDFOFLyYgQ4ZICq68lJ0IGNVSBvhgYJA@KqAJ9MSURZVBFCEw9MTwhKQvKqAJdMeo2p80irKUyu4rUPVKbZVhQZXZlqduoNudhVZXZ1aZuxdrsTZYRKF2Btx@I9CbLCJSuQG4ESlfgnYX1p8wIl67CO7NmpKvwrjDRrsLPt8bsz56pk3Ql3hnmmb8gTf0y5nEZlmXGPbNRmgmEOrRV5ks1Bc98qaYEmb9ITcmy3IsfGjkrPLNZK1mJsAc6ua/WVCFnGH2wc3@FG7svd9gv8tQzm2LmEmGv6Hgzq@EBJsfYA0yBsIemy0uEPdiLxLOb4hcMYQ90Cu4tdxMuMPZgTxH2CkYi9BUdTy0zC7nA5hZ2p6JA6CucEqOfkTIJ6UN4yRD4X9k5JgvgsTkHmmWKyFI4EosvSYlNusLJkXiFU2DxgBPsyReqLEnCFIBiCQskw6bGEu5vzyMo4e/RI18aKNdw0t@oRymZv1uPfHlQAA1X@Fv2KKX09@2rj4VFUHDu048aZJTC/W185BMBnN3QmftUZHKYdUpkHQjrzELUwvrywGd3eeY@OZkRL6BlCGqahHFkadh9inGGdZZ18hDV7v/Mfc4ymbY8HCvPBVYisLZ2PEMyL7A51mDWWSCw3DpLrNWMU2AVsrDu05qBtXUXHGs76xRI71lfiqDaSRFyQqbqaPepzrSgTcwRVGmdxYRKjVoinWgS0wRBtZOZMlykAk050o82D2muyzynKa5Rg8oJjdqJNJe967A0xzXqxGJCo3Yi3XVZHzLBRapEySZEaifSXZe1I8XUkPAOJdMJlRpWTmXCu5bMpsZUsPlEpoYtpjIBNksmnCozmyiC2pqzCSXaN0FH@fKJAcGn3s5Hb@xfd/W2V0dZ9b6fD7ZFd2zqfn5D6U30JbmPloE5piz6wu4XTde39XE@nEMNUep0xEDbhL/2gMOW79n9cBC2aZqvPzZNvYNh79pTRewpyz/VeZSumS3A1s1Hxyl9e3bORDZdV7U91ecREButVk66Or5Q5ktK9bStjr17rHJslfjZx03dnNqKHvb0@WVJ/zycLqJunl9u6JsV/VT/qPZj42wBxB83epD4yiKmKIvRqZJfiI@bpqvsGdzFceVpOP7RNPoApqPbw@OxqfpqR7vTdlt13cOpac6LWUTI9YRGH71Gr/8CC)):
```
def test_func(func, has_comma=True):
answers = """
2 D1
3 1, D1
4 D2
5 1, D2
6 D3
7 3, D2
8 D4
9 1, D4
10 D5
11 3, D4
12 D6
13 5, D4
14 D7
15 7, D4
16 D8
17 1, D8
18 D9
19 3, D8
20 D10
21 5, D8
22 D11
23 7, D8
24 D12
25 9, D8
26 D13
27 11, D8
28 D14
29 13, D8
30 D15
31 15, D8
32 D16
33 1, D16
34 D17
35 3, D16
36 D18
37 5, D16
38 D19
39 7, D16
40 D20
41 9, D16
42 10, D16
43 11, D16
44 12, D16
45 13, D16
46 14, D16
47 15, D16
48 16, D16
49 17, D16
50 BE
51 19, D16
52 20, D16
53 T7, D16
54 D11, D16
55 T13, D8
56 T8, D16
57 SB, D16
58 D13, D16
59 T9, D16
60 D14, D16
61 T15, D8
62 T10, D16
63 T13, D12
64 D16, D16
65 T11, D16
66 D17, D16
67 T17, D8
68 T12, D16
69 T15, D12
70 D19, D16
71 T13, D16
72 D20, D16
73 T19, D8
74 T14, D16
75 T17, D12
76 T20, D8
77 T15, D16
78 D19, D20
79 T13, D20
80 T16, D16
81 T19, D12
82 BE, D16
83 T17, D16
84 T20, D12
85 T15, D20
86 T18, D16
87 T17, D18
88 T16, D20
89 T19, D16
90 BE, D20
91 T17, D20
91 T17, D20
92 T20, D16
93 T19, D18
94 T18, D20
95 T19, D19
96 T20, D18
97 T19, D20
98 T20, D19
99 7, T20, D16
100 T20, D20
101 T17, BE
102 10, T20, D16
103 11, T20, D16
104 T18, BE
105 13, T20, D16
106 14, T20, D16
107 T19, BE
108 16, T20, D16
109 17, T20, D16
110 T20, BE
111 19, T20, D16
112 20, T20, D16
113 T20, T7, D16
114 T20, D11, D16
115 T19, D13, D16
116 T20, T8, D16
117 T20, SB, D16
118 T20, D13, D16
119 T20, T9, D16
120 T20, D14, D16
121 T19, D16, D16
122 T20, T10, D16
123 T19, D17, D16
124 T20, D16, D16
125 T20, T11, D16
126 T20, D17, D16
127 T19, D19, D16
128 T20, T12, D16
129 T19, D20, D16
130 T20, D19, D16
131 T20, T13, D16
132 T20, D20, D16
133 T17, BE, D16
134 T20, T14, D16
135 T19, D19, D20
136 T18, BE, D16
137 T20, T15, D16
138 T20, D19, D20
139 T19, BE, D16
140 T20, T16, D16
141 T17, BE, D20
142 T20, BE, D16
143 T20, T17, D16
144 T18, BE, D20
145 T20, T15, D20
146 T20, T18, D16
147 T19, BE, D20
148 T20, T16, D20
149 T20, T19, D16
150 T20, BE, D20
151 T20, T17, D20
152 T20, T20, D16
153 T20, T19, D18
154 T20, T18, D20
155 T20, T19, D19
156 T20, T20, D18
157 T20, T19, D20
158 T20, T20, D19
160 T20, T20, D20
161 T20, T17, BE
164 T20, T18, BE
167 T20, T19, BE
170 T20, T20, BE
"""
if not has_comma:
answers = answers.replace(',','')
answers_dict = {int(answer.split(' ')[0]):answer.split(' ', 1)[1].lstrip() for answer in answers.split('\n')[1:-1]}
all_valid = True
for key in answers_dict.keys():
try:
assert func(key)==answers_dict.get(key)
except:
print("Failure on {}: Your answer '{}' != Given answer '{}'".format(key, func(key), answers_dict.get(key)))
all_valid = False
if all_valid:
print("All tests completed successfully.")
```
] |
[Question]
[
Your program is given a string consisting entirely of lowercase letters at STDIN (or closest alternative). The program must then output a truthy or falsey value, depending on whether the input is valid romaji.
## Rules:
* It must be possible to divide the entire string into a sequence of kana without any leftover characters.
* Each kana can be a single vowel (`aeiou`)
* Each kana can also be a consonant p, g, z, b, d, k, s, t, n, h, m, or r followed by a vowel. For example, ka and te are valid kana, but qa is not.
* The exceptions to the above rule are that zi, di, du, si, ti, and tu are not valid kana.
* The following are also valid kana: n, wa, wo, ya, yu, yo, ji, vu, fu, chi, shi, tsu.
* If a particular consonant is valid before an i (i.e ki, pi), the i can be replaced by a ya, yu, or yo and still be valid (i.e kya, kyu, kyo)
* Exceptions to the above rule are chi and shi, for which the y has to be dropped too (i.e cha, chu, cho, sha, shu, sho)
* It is also valid to double consonants if they are the first character of a kana (kka is valid but chhi is not)
* Shortest answer wins. All regular loopholes are disallowed.
## List of all valid kana:
```
Can have double consonant:
ba, bu, be, bo, bi
ga, gu, ge, go, gi
ha, hu, he, ho, hi
ka, ku, ke, ko, ki
ma, mu, me, mo, mi
na, nu, ne, no, ni
pa, pu, pe, po, pi
ra, ru, re, ro, ri
sa, su, se, so,
za, zu, ze, zo,
da, de, do,
ta, te, to,
wa, wo,
ya, yu, yo,
fu,
vu
ji
Can not have double consonant:
a, i, u, e, o,
tsu,
chi, cha, cho, chu,
shi, sha, sho, shu,
n
```
## Test cases
Pass:
```
kyoto
watashi
tsunami
bunpu
yappari
```
Fail:
```
yi
chhi
zhi
kyi
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~96~~ 149 bytes
Regex solution to match all the valid kana. Interestingly, "ecchi" is not valid according to the current rules, but perhaps it's for the best.
```
->s{s.gsub(/(?![dt]u)(sh|ch|([gbknhmrp])\2?y?|([zdst])\3?)?[auo]|(\g<2>)?\4?[ie]|(\g<3>)\5?e|ww?[ao]|n|tsu|([fv])\6?u|jj?i|j?y?[aou]|yy[aou]/){}==""}
```
[Try it online!](https://tio.run/nexus/ruby#JY7dbuMgEEbveYpJWq2MojhVs9urJjxIHFVjmxjiGCzD1CKlz56OuxKI@TnfEU@rieoEWycuh@qxPYavUHaB6mJXqNWpjWeSRTC5Mbk4dXXvzDCNZ1m9qqR4cm9D5G6vpDoh@XMuqu799ShV9VedrP7f74@y@qd0nmeGmHE5BuLw5ZOjb4ry9apsvrKR13TOKf2@O/n1fTis19@PkWKAxvhhLG9XCrHYv8jNGjKsN88fZWjQFbtq3uxkibebKv5cZBn9R3gkKxpjrLjz7bm580nEpRZNY1AEk5AJNvPMRy9mjBgY5v85HKyoyY0kEo4jTpxF1/uewCFE7ZgD57m6axADtr7W0OOEkLDDqCH62kZkEwjD7noRTwTLxMKI0S@rVgs/eNtqmD3QhN2CuMUies/24LnkVYs2LvoOE/bEH/fktIPEhLFuRnB2ienVDw "Ruby – TIO Nexus") feat. Cruel Angel's Thesis
[Answer]
## Python 2, 166 bytes
Long regex solution
[Try it online](https://tio.run/nexus/python2#PYtNbsMgEIX3OQW7AQlFapeRfIPcgLLADqmnjgHx0wSX@uousOgsvvfpad51@Dgeah1virwuXp9DGimI8XNeVuO83KlQyWqUJTeRrIiwyb2XsohbbK6tLM@aNai4f8u9xMBSoV97EVOQM6P4P899W6eVqI2Es9fuoSZNYQcOP2/8/RcYB@AvNgwAJ1yd9ZF4fdytJ0jQEAFLttHW96eKKsxYLYZk1NpsTMalmlk5p3xrcsM097@tc@nV1pE1yMuJ1HMeTSTIyZUiO/4A)
I think that f-strings from 3.[something] python can help to shorten it by replacing repeated `[auo` and `{1,2}`.
Unfortunatetly I can't check it by myself now :c
```
import re
lambda x:re.sub('[bghkmnpr]~([auoei]|y[auo])|[sz]~[auoe]|[dt]~[aeo]|w~[ao]|([fv]~|ts)u|(j~|[cs]h)(i|y[auo])|y~[auo]|[auoien]'.replace('~','{1,2}'),'',x)==''
```
] |
[Question]
[
# Challenge
Given a the ID for a PPCG user who has existed for at least a month, output the average amount of reputation they gain per month. You can do this by dividing their reputation by the time since their account was created (which you can find on the profile). This should be returned floored; that is, truncate all of the decimals. (We don't care about the small stuff).
# Input
A single integer, which is the user's ID
# Output
A single integer, representing the floored rep change per month.
# Test Cases
```
input -> output
42649 -> 127 (me)
12012 -> 3475 (Dennis)
8478 -> 3015 (Martin Ender)
```
[Answer]
# JS, ES6 ~~243~~ ~~235~~ ~~168~~ ~~166~~ ~~165~~ 164 bytes
```
i=>fetch(`//api.stackexchange.com/users/${i}?site=codegolf`).then(x=>x.json()).then(x=>alert(~~((y=x.items[0]).reputation/((new Date/1e3-y.creation_date)/2592e3))))
```
Based on [the Python answer](https://codegolf.stackexchange.com/a/121370/58826).
Run this in the console:
```
(i=>fetch(`//api.stackexchange.com/users/${i}?site=codegolf`).then(x=>x.json()).then(x=>alert(~~((y=x.items[0]).reputation/((new Date/1e3-y.creation_date)/2592e3)))))(+prompt("Enter a userId"))
```
-4 thanks to [@insert\_name\_here](https://codegolf.stackexchange.com/users/59682/insert-name-here)
### Old answer:
```
z=>fetch("//codegolf.stackexchange.com/u/"+z).then(x=>x.text()).then(x=>alert((/([\d,]+) <span class="label-uppercase">repu/.exec(x)[1].replace(/,/g,"")/(((y=/Member for <.+>((\d+) years?, )?(\d+) month/.exec(x))[2]||0)*12+ +y[3]||0))))
```
Improvements welcome! Just fetches the profile page and parses it with regular expressions!
Won't work as a stack snippet, but you can paste this in your console:
```
(z=>fetch("//codegolf.stackexchange.com/u/"+z).then(x=>x.text()).then(x=>alert(Math.floor(/([\d,]+) <span class="label-uppercase">repu/.exec(x)[1].replace(/,/g,"")/(((y=/Member for <.+>((\d+) years?, )?(\d+) month/.exec(x))[2]||0)*12+ +y[3]||0)))))(+prompt("Enter a userId"))
```
[Answer]
## Python ~~3~~ 2, ~~206~~ ~~219~~ ~~201~~ 193 bytes
```
import requests,time
a=requests.get('http://api.stackexchange.com/users/'+str(input())+'?site=codegolf').json()['items'][0]
print a['reputation']/((int(time.time())-a['creation_date'])/2592000)
```
I am estimating the months as the OP suggested, but actually `print(int(b/((d-c)/2592000)))` is a more accurate solution than `print(int(b/int((d-c)/2592000)))` and also saves a few bytes.
] |
[Question]
[
Note: this is my first post here.
# The Challenge
The challenge is to count the number of chocolate chips in a cookie. A cookie in this case is a circle with dots (the chips) in it. Given any square cartoon image of this cookie, you are to write a bot that counts and outputs the number of chocolate chips.
# Rules
* Has to take in an image type of png.
* It has to be able to take in any file size, as long as it is square.
* It has to be able to handle both color and B&W images.
* Output can be in any human-understandable form.
* The circle will be filled with color and will have an outline.
* Chips will all be the same size and color.
* There is only one cookie in the image
* Chocolate chips may be irregularly spaced, but are perfect circles.
* You can use a library.
* There is nothing in the image except the cookie and the chocolate chips.
-All other cookies will look like the example images.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the shortest code gets accepted.
# Examples
[Cookie 1](https://i.stack.imgur.com/UCV1A.png) => `8` or `1000` (binary)
[Cookie 2](https://i.stack.imgur.com/5n7AY.png) => `8` or `1000` (binary)
[Cookie 3](https://i.stack.imgur.com/ZbZx6.png) => `10` or `1010` (binary)
[Cookie 4](https://i.stack.imgur.com/M8jTo.png) => `7` or `0111` (binary)
[Answer]
## Mathematica 134 Bytes
```
Max@ComponentMeasurements[ArrayComponents[ImageData@ColorQuantize[RemoveAlphaChannel[#,White],4,Dithering->False],2],"Holes"][[All,2]]&
```
Usage (applied to .png images)
```
%/@cookies
```
Output:
```
{8,8,10,7}
```
Here's the code to bring in the cookie examples:
```
cookieURLs={"https://i.stack.imgur.com/UCV1A.png","https://i.stack.imgur.com/5n7AY.png","https://i.stack.imgur.com/ZbZx6.png","https://i.stack.imgur.com/M8jTo.png"};
cookies=Import/@cookieURLs;
```
I'm sure this can be shortened, but I think it's fairly bullet-proof as is. The original images have many more colors than the eye can see.
Here are the original cookies:
[](https://i.stack.imgur.com/WMpci.gif)
Here are the cookies after cleanup to get them into a 4 component array:
```
ArrayPlot[ArrayComponents[ImageData@ColorQuantize[RemoveAlphaChannel[#,White],4,Dithering->False],2]]&/@cookies//Row
```
[](https://i.stack.imgur.com/NS1lK.gif)
After that, all is needed is to use `ComponentMeasurements` to count holes.
This will always report at least 1. You could have one really big chocolate chip filling the cookie border, so the 0 or 1 case will always be ambiguous.
] |
[Question]
[
Earlier, [we talked about exponential generating functions (e.g.f.)](https://codegolf.stackexchange.com/questions/83001/golf-the-exponential-generating-function-of-tangent).
# Task
You will take a few terms of a sequence.
Your task is to find another sequence with that many terms, whose e.g.f., when multiplied to the original e.g.f., would be exactly the constant function `1` accurate to that many terms.
That is, given `a0=1, a1, a2, ..., an`, find `b0=1, b1, b2, ..., bn` such that `a0 + a1x + a2x^2/2! + a3x^3/3! + ... + anx^n/n!` multiplied by `b0 + b1x + b2x^2/2! + b3x^3/3! + ... + bnx^n/n!` equals `1 + O(x^(n+1))`.
# Specs
* They will start at the zeroth power and will be consecutive.
* The first term is guaranteed to be `1`.
* All the terms are guaranteed to be integers.
* There will not be negative powers.
# Testcases
```
Input : 1,0,-1,0,1,0,-1,0 (this is actually cos x)
Output: 1,0, 1,0,5,0,61,0 (this is actually sec x)
Input : 1, 2, 4, 8, 16, 32 (e^(2x))
Output: 1,-2, 4,-8, 16,-32 (e^(-2x))
Input : 1,-1,0,0, 0, 0, 0 (1-x)
Output: 1, 1,2,6,24,120,720 (1/(1-x) = 1+x+x^2+...)
```
[Answer]
# Julia, ~~91~~ ~~81~~ 77 bytes
```
!v=(b=[1;0v[r=2:end]];for i=r,j=0:i-2 b[i]-=binomial(i-1,j)v[i-j]b[j+1]end;b)
```
Usage: `![1 0 -1 0 1 0 -1 0]`
Saved 4 bytes thanks to Dennis!
This is a fairly straightforward implementation - it uses the fact that the "exponential" part causes a binomial to appear in the solution. Otherwise, it's just solving for the relevant coefficients.
] |
[Question]
[
### Challenge
Create a quine, that instead of outputting it's source, output's it's source QWERTY-sorted.
### What is QWERTY sorting?
QWERTY sorting is sorting code by the QWERTY keyboard. Anything higher or more left is greater (`q` > `Q`, `\` > `/`) with presedence on higher. To check, find the locations of the two characters to compare. Find which character occurs first in the following table (left to right, up to down). The first character is the smaller one.
```
qwertyuiop[]\
asdfghjkl;'
zxcvbnm,./
QWERTYUIOP{}|
ASDFGHJKL:"
ZXCVBNM<>?
1234567890-=!@#$%^&*()_+~`
```
(there is a trailing space and linefeed)
Examples:
```
Code Golf -> eoodflGC
Programming -> rroiagnmmP
```
(note trailing space on `Code Golf`)
### Specifications
* Only characters in the above list are allowed in the source code!
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
* Only [Proper Quines](http://meta.codegolf.stackexchange.com/questions/4877/what-counts-as-a-proper-quine/4878#4878) are allowed (adapted to QWERTY sort).
* Output must be in *increasing* QWERTY order.
[Answer]
# CJam, ~~25~~ 23 bytes
```
{`"_~"+{"#$_+~`"`#}$}_~
```
*Thanks to @MartinBüttner for golfing off 2 bytes!*
[Try it online!](http://cjam.tryitonline.net/#code=e2AiX34iK3siIyRfK35gImAjfSR9X34&input=)
### How it works
```
{ }_~ Define, copy and execute a code block.
` Create a string representation of the code block.
"_~"+ Append that string.
{ }$ Sort the characters by the following:
"#$_+~`"`# Compute the 0-based index of the character in that
string. Returns -1 if not found.
Since `$' is stable, all characters with tied index -1
will appear at the beginning, in their original order.
This places {{}} at the beginning, followed by
""""##$$___++~~~```.
```
] |
[Question]
[
# Is the path correct ?
Given a string, your program must determine whether or not Alice can reach Bob, following the signs on the map. You must return a truthy or falsy value.
The input string will contain the following characters :
* (space) and `\n`. Only used for padding.
* `>`, `<`, `^`, `v`, are the "signs". They show the direction.
* `&`. Ignore next char, whatever it is (including spaces **and `Bob`**)
* `A` and `B` respectively Alice and Bob.
The map is a torus. If Alice reaches the end of a row, then she is teleported back to the beginning of that row. Same applies for columns.
## Examples
Given those examples as input, your program must return a truthy value (each input is separated with a `-` line):
```
A>B
-----------------
<BA
-----------------
A B
-----------------
BA
-----------------
Av >B
> ^
-----------------
Av
B
-----------------
A>v
>B
-----------------
A>v> v>B
v< > &<^
> ^
-----------------
A>v> v
v< >B&<
> ^
-----------------
A&<B
-----------------
A&B<
-----------------
<A &B
```
For the following, your program must output a falsy value or nothing :
```
AvB
-----------------
A&B
-----------------
A><B
-----------------
A>v
^<B
```
## Path viewer
You can have a visual representation of the input [here](https://correctpath.firebaseapp.com/). Thanks to arnemart for [this](https://github.com/arnemart/befungius).
## Some rules
* The input may be padded with spaces to form a rectangle
* Initially, Alice goes straight forward (from above, she goes to the right)
* Your program ***should*** handle infinite loop cases (see Hint)
* `A` is not always the first character, as you may have seen, however, you may write a program that handles only input with `A` being the first char, but 20 bytes will be added to your score.
* A map (the input) is considered invalid in case there are other characters than those specified above. Your program won't have to handle them.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.
## Hint
Your program will most likely be a loop, unless you find a more mathematical solution to this challenge. To handle infinite path, I recommend using a finite loop (e.g `for`) instead of a potentially infinite one (e.g `while`).
Therefore, the maximum iteration of the loop I can think of (I did not do any maths, any correction is welcome) is `(length of input)*4`
[Answer]
# C, 250 bytes
```
#define h x=(j+x-1+d%3)%j,i=(j+i+(d=='v')-(d==94))%j
char a[999],b[999];x,i,d=2,k,f;main(j){for(;gets(a+j*i);)j=strlen(a+j*i++);for(x=strchr(a,65)-a,i=x/j,x=x%j;!k*d;h)k|=b[f=j*i+x]&1<<d%5,b[f]|=1<<d%5,(f=a[f])&16?d=f:f&4?h:f&2?d=0:0;putchar(48+!k);}
```
This also requires that the input is padded with spaces.
Ungolfed:
```
#define h x=(j+x-1+d%3)%j,i=(j+i+(d=='v')-(d==94))%j
char a[999],b[999];x,i,d=2,k,f;
main(j){
for(;gets(a+j*i);)j=strlen(a+j*i++); //read lines and determine line length
for(x=strchr(a,65)-a,i=x/j,x=x%j; //the current position is 'A'
!k*d; //as long as we have not arrived at 'B'
//and not travelled through the same cell and in the same direction twice
h) //advance one in the current direction
k|=b[f=j*i+x]&1<<d%5,b[f]|=1<<d%5, //if we have already travelled
//through this cell in this direction
(f=a[f])&16?d=f //change direction if this cell is one of <>^v
:f&4?h //if this cell is '&', advance one in the current direction
:f&2?d=0:0; //if we have reached 'B'
putchar(48+!k);
}
```
[Answer]
# JavaScript (ES6), 176 bytes
```
m=>[...m,q=~m.length,l=~m.search`
`||q,a=m.search`A`,p=d=r=1].map(_=>(a+=d,a-=d*((a-l+1)%l?m[a]?0:q/l:~l),c=m[a],p=="&"?0:d={">":1,"<":-1,"^":l,v:-l}[c=="B"?r=0:c]||d,p=c))&&!r
```
## Explanation
Requires the input to be space-padded to form a rectangle (I hope this is OK).
```
var solution =
m=>[
...m, // iterate m.length times
q=~m.length, // q = total length of m
l=~m.search`\n`||q, // l = line length
a=m.search`A`, // a = index of Alice
p= // p = previous character
d= // d = direction offset
r=1 // r = result
].map(_=>( // loop
a+=d, // move Alice
a-=d*((a-l+1)%l?m[a]?0:q/l:~l), // wrap
c=m[a],
p=="&"?0: // do nothing after &
d={">":1,"<":-1,"^":l,v:-l} // set the new direction
[c=="B"?r=0:c] // if on Bob, r = 0
||d,
p=c
))&&!r // return result
var testCasesTrue =
`A>B
-----------------
<BA
-----------------
A B
-----------------
BA
-----------------
Av >B
> ^
-----------------
Av
B
-----------------
A>v
>B
-----------------
A>v> v>B
v< > &<^
> ^
-----------------
A>v> v
v< >B&<
> ^
-----------------
A&<B
-----------------
A&B<
-----------------
<A &B`
.split("\n-----------------\n");
var testCasesFalse =
`AvB
-----------------
A&B
-----------------
A><B
-----------------
A>v
^<B`
.split("\n-----------------\n");
var test = (cases, expected) => cases.map((t,i)=>++i+": "+(solution(t)==expected?"Pass":"Fail")).join`\n`;
document.write(`<pre>${test(testCasesTrue,true)}\n\n${test(testCasesFalse,false)}</pre>`);
```
] |
[Question]
[
Imagine for a second that you can compose a tree out of dots.
```
.
...
.....
.......
.........
...........
.............
...............
...
...
```
This tree is 13 dots tall.
Now imagine for a second that your filesystem looked like these dots. Your task in this challenge is to make a tree out of folders.
# The Challenge
Given an input integer (let's call it `n`), make a tree out of subdirectories.
1. In each tree, you should start with a folder called 1.
2. In that folder, put the folders 1, 2, and 3.
3. In every level of folder thereon until `n-3`, in folder 1 of this level of the tree, there should be a folder labelled 1 and 2. In folder 2 of this level of the tree, there should be a folder called 3, in folder 3, a folder called called 4, and so on until the last folder (the integer this folder is called, we'll call `k`), in which there should be a folder called `k` and one called `k+1`.
4. At level `n-3`, however, all of the subdirectories but the middle three folders should be replaced with a file with the name that the subdirectories would have had. The middle three subdirectories should remain as subdirectories.
5. These three subdirectories should contain a folder called 1, 2, or 3 with respect to the order of these directories' name.
6. These are followed by a layer of files where 1 is in folder 1, 2 is in folder 2, and 3 is in folder three.
The example shown at the top of this question is represented below in folder form.
[](https://i.stack.imgur.com/K6Ju7.png)
This would be `n = 13`.
# Rules
* You may use builtins for folder creation, but not for subdirectory creation.
* All other standard loopholes apply.
* You must support past n=5, but do not have to support greater than n=30.
[Answer]
# Windows [Batch File](https://en.wikipedia.org/wiki/Batch_file), ~~429~~ ~~423~~ 404 bytes
```
md 1
set C= call:
set/a M=%1-2
%C%f 1 1 2 L
%C%f 1 2 2 M
%C%f 1 3 2 R
goto:eof
:f
md %1\%2
set/a P=%2+1
set/a Q=%2+2
set/a L=%3+1
set D= (%C%t %1\%2\%P%
if %L%==%M% (if %4==L .>%1\%2\1
if %Q%==%M%%D%1)else (if %P%==%M%%D%2)else (if %2==%M%%D%3)else .>%1\%2\%P%))
if %4==R .>%1\%2\%Q%
)else (if %4==L%C%f %1\%2 1 %L% L
%C%f %1\%2 %P% %L% M
if %4==R%C%f %1\%2 %Q% %L% R)
goto:eof
:t
md %1\%2
.>%1\%2\%2
```
Call it with the value of n as a command line parameter.
Here is a visualization of the output tree for n=9:
```
1
+--+--+
1 2 3
+--+ | +--+
1 2 3 4 5
+--+ | | | +--+
1 2 3 4 5 6 7
+--+ + | | | | +--+
1 2 3 4 5 6 7 8 9
+--+ | | | | | | | +--+
1 2 3 4 5 6 7 8 9 10 11
+--+ | | | | | | | | | +--+
1 2 3 4 5 6 7 8 9 10 11 12 13
| | |
1 2 3
| | |
1 2 3
```
] |
[Question]
[
## Task
Write a program or function that will determine if a point in 3D space lies on a 2D parabolic curve.
---
## Input
3 points in 3D space
* vertex of a 2D parabolic curve
* arbitrary point on the curve
* arbitrary point in space
Input may be taken in any form (string, array, etc.) provided no other data is passed.
---
You may assume
* the axis of a parabola will be parallel to the z axis
* the vertex of a parabola has the maximal z value
* parabolae will never degenerate
* point values will be whole numbers that are `≥ -100` and `≤ 100`
---
## Output
A truthy/falsey value representing whether the third point given lies on the parabolic curve of the first two points.
---
## Examples
Input:
```
(2, 1, 3)
(1, 0, 1)
(4, 3, -5)
```
Output:
```
1
```
---
Input:
```
(16, 7, -4)
(-5, 1, -7)
(20, 6, -4)
```
Output:
```
0
```
---
## Walkthrough (Example #1)
1. Find a third point on the curve. To do this, mirror the arbitrary point (on the curve) over the vertex. Here is a visual (each blue line is √6 units):

2. Find the parabolic curve between the three. This is easiest on a 2D plane. Here is the 3D graph, translated to a 2D graph (each blue line is √6 units):

3. Graph the third given point and solve.


[Answer]
## Jelly, ~~13~~ 11 bytes
```
_÷/µḢ²=A;$P
```
The input format is a bit strange; it takes ***P1*** as the second argument, and (***P3***,***P2***) as the first argument, where each point is expressed in the form `((x+yj),z)`.
We first normalize the points so that the vertex is on the origin, and then make sure that P1 and P2 are on the same line, and also that the ratio of their z distances is equal to the ratio of their x distances.
```
_÷/ Helper link. Inputs: (P3,P2) on left, P1 on right.
_ Subtract right from left. (P3-P1,P2-P1).
÷/ Fold division. (P3-P1)/(P2-P1). P2-P1 is nonzero in both x+yi and z.
µ Push the chain onto the stack, and start a new monadic link.
Ḣ²=A;$P Hook; main link. Calculates whether w² = a and a is nonnegative.
Input: The result of the helper link. Call it [w,a].
Ḣ² Pop w and square it. Now the list is [a].
A,$ Concatenate a to its absolute value.
= Fork; is w equal to [a,abs(a)]? Returns 2 element list of 0 or 1
P Product; that is, true if w was equal to both a and abs(a).
```
Try it [here](http://jelly.tryitonline.net/#code=X8O3L8K14biiwrI9QTskUA&input=&args=KDErMGosIDEpLCAoNCszaiwgLTUp+KDIrMWosIDMp).
] |
[Question]
[
## Back-story
After typing up your essay on your new Macbook, you look up at the screen and realize that you typed in ten pages of gibberish! Or is it? On further inspection, you come to find that your Option key was stuck this whole time and these special Option-key characters correspond to the ASCII keys on your keyboard!
## Challenge
Your challenge is to write the shortest possible program or function that converts an encoded Option-key input into ASCII output.
Here's the Option-key special characters to ASCII characters dictionary:
```
+---------+-------+-------+-------+
| OPT-KEY | CODE | ASCII | CODE |
+---------+-------+-------+-------+
| ¡ | 161 | 1 | 49 |
| ™ | 8482 | 2 | 50 |
| £ | 163 | 3 | 51 |
| ¢ | 162 | 4 | 52 |
| ∞ | 8734 | 5 | 53 |
| § | 167 | 6 | 54 |
| ¶ | 182 | 7 | 55 |
| • | 8226 | 8 | 56 |
| ª | 170 | 9 | 57 |
| º | 186 | 0 | 48 |
| – | 8211 | - | 45 |
| ≠ | 8800 | = | 61 |
| œ | 339 | q | 113 |
| ∑ | 8721 | w | 119 |
| ® | 174 | r | 114 |
| † | 8224 | t | 116 |
| ¥ | 165 | y | 121 |
| ø | 248 | o | 111 |
| π | 960 | p | 112 |
| “ | 8220 | [ | 91 |
| ‘ | 8216 | ] | 93 |
| « | 171 | \ | 92 |
| å | 229 | a | 97 |
| ß | 223 | s | 115 |
| ∂ | 8706 | d | 100 |
| ƒ | 402 | f | 102 |
| © | 169 | g | 103 |
| ˙ | 729 | h | 104 |
| ∆ | 8710 | j | 106 |
| ˚ | 730 | k | 107 |
| ¬ | 172 | l | 108 |
| … | 8230 | ; | 59 |
| æ | 230 | ' | 39 |
| Ω | 937 | z | 122 |
| ≈ | 8776 | x | 120 |
| ç | 231 | c | 99 |
| √ | 8730 | v | 118 |
| ∫ | 8747 | b | 98 |
| µ | 181 | m | 109 |
| ≤ | 8804 | , | 44 |
| ≥ | 8805 | . | 46 |
| ÷ | 247 | / | 47 |
| | 160 | | 32 |
| ⁄ | 8260 | ! | 33 |
| € | 8364 | @ | 64 |
| ‹ | 8249 | # | 35 |
| › | 8250 | $ | 36 |
| fi | 64257 | % | 37 |
| fl | 64258 | ^ | 94 |
| ‡ | 8225 | & | 38 |
| ° | 176 | * | 42 |
| · | 183 | ( | 40 |
| ‚ | 8218 | ) | 41 |
| — | 8212 | _ | 95 |
| ± | 177 | + | 43 |
| Œ | 338 | Q | 81 |
| „ | 8222 | W | 87 |
| ‰ | 8240 | R | 82 |
| ˇ | 711 | T | 84 |
| Á | 193 | Y | 89 |
| Ø | 216 | O | 79 |
| ∏ | 8719 | P | 80 |
| ” | 8221 | { | 123 |
| ’ | 8217 | } | 125 |
| » | 187 | | | 124 |
| Å | 197 | A | 65 |
| Í | 205 | S | 83 |
| Î | 206 | D | 68 |
| Ï | 207 | F | 70 |
| ˝ | 733 | G | 71 |
| Ó | 211 | H | 72 |
| Ô | 212 | J | 74 |
| | 63743 | K | 75 |
| Ò | 210 | L | 76 |
| Ú | 218 | : | 58 |
| Æ | 198 | " | 34 |
| ¸ | 184 | Z | 90 |
| ˛ | 731 | X | 88 |
| Ç | 199 | C | 67 |
| ◊ | 9674 | V | 86 |
| ı | 305 | B | 66 |
| Â | 194 | M | 77 |
| ¯ | 175 | < | 60 |
| ˘ | 728 | > | 62 |
| ¿ | 191 | ? | 63 |
+---------+-------+-------+-------+
```
It's not that simple though... There are a five Option-key special characters that do not follow this trend, specifically (Option-key special characters and their corresponding lowercase ASCII characters):
```
Beginning of input or after special space (" ", code 160):
+---------+-------+-------+-------+
| OPT-KEY | CODE | ASCII | CODE |
+---------+-------+-------+-------+
| ` | 96 | ~ | 126 |
| ´ | 180 | E | 69 |
| ¨ | 168 | U | 85 |
| ˆ | 710 | I | 73 |
| ˜ | 732 | N | 78 |
+---------+-------+-------+-------+
Otherwise:
+---------+-------+-------+-------+
| OPT-KEY | CODE | ASCII | CODE |
+---------+-------+-------+-------+
| ` | 96 | ` | 96 |
| ´ | 180 | e | 101 |
| ¨ | 168 | u | 117 |
| ˆ | 710 | i | 105 |
| ˜ | 732 | n | 110 |
+---------+-------+-------+-------+
```
When any of these characters are found after the Option-key special space character () or at the beginning of the input, output the capitalized version of their ASCII equivalents. (Note that the capitalized version of "`" is "~".) Otherwise, output the lowercase version of their ASCII equivalents.
Finally, do not attempt to decode any other characters, just output them.
## Rules & Grading
* All Code-Golf rules barring standard loopholes apply.
* Scores will be based on the number of bytes your program uses.
* The program with the smallest score (or the smallest number of bytes) will win!
## Examples
Input, output:
```
`´¨ˆ˜`
~euin`
´´ ´⁄
Ee E!
`` ´ ¨ ˆ ˜
~` E U I N
Ó´¬¬ø ∑ø®¬∂⁄
Hello world!
„˙å† ˆß ¥ø¨® ˜åµ´¿ Í´®©´å˜† ıˆ¬¬ˆå®∂ß⁄
What Is your Name? Sergeant Billiards!
„˙´®´ ∂ø ¥ø¨ çøµ´ ƒ®øµ¿
Where do you come from?
„˙´˜ ˆ µø√´∂ †ø Áø®˚ß˙ˆ®´≤ †˙´®´ ∑åß å µå˜ ∑分ˆ˜© ƒø® µ´≥
When I moved to Yorkshire, there was a man waiting for me.
Óˆß ˜åµ´ ∑åß ∏嬴߆ˆ˜´≥ Ó´ çåµ´ ƒ®øµ Òå˜∂ø≥
His Name was Palestine. He came from Lando.
Åç®øßß †˙´ ®´´ƒ ¬å¥ ˜ø†˙ˆ˜©≥
Across the reef lay Nothing.
Â¥ ˜åµ´ ˆß ´å†ø˜≥
My Name Is Eaton.
ˆ˜† µåˆ˜·√øˆ∂‚ ” ߆∂ÚÚçø¨† ¯¯ ÆÓ´¬¬ø ∑ø®¬∂⁄Æ… ’
Int main(void) { std::cout << "Hello world!"; }
¡ ·™£¢‚ ∞§¶–•ª¡º
1 (234) 567-8910
ÓʼnΠˇØ ˝´ˇ ÅÒÒ ÇÅ∏Í⁄
HARD TO GeT ALL CAPS!
؉ ˆÍ ˆˇ¿
OR IS IT?
Ó´æß ˆ˜ †˙´ †øπ ¡ººfi⁄
He's In the top 100%!
```
[Answer]
# JavaScript (ES6), 354 bytes (231 characters)
```
t=>[...t].map((c,i)=>~(x="`´¨ˆ˜".indexOf(c))?(t[i-1]==" "|!i?"~EUIN":"`euin")[x]:~(a=" ⁄`‹›fi‡`·‚°±≤–≥÷º¡™£¢∞§¶•ªÚ…¯≠˘¿€ÅıÇÎ`Ï˝Ó`ÔÒÂ`Ø∏Œ‰Íˇ`◊„˛Á¸“«‘fl—`å∫ç∂`ƒ©˙`∆˚¬µ`øπœ®ß†`√∑≈¥Ω”»’æÆ".indexOf(c))?String.fromCharCode(a+32):c).join``
```
## Explanation
*Note: [This byte counter](http://bytesizematters.com/) says it is 278 bytes, but I don't know what (if any) encoding it is using, so I went with UTF-8 for the byte count.*
```
t=>
[...t].map((c,i)=> // for each character c at index i
~(x="`´¨ˆ˜".indexOf(c))? // if it is a special character
(t[i-1]==" "|!i?"~EUIN":"`euin")[x] // handle it
:~(
a= // a = ASCII code of equivalent character (or -1)
// Option characters, the index of each option character is the code of it's ASCII
// equivalent - 32, ` is used to pad empty positions since it will never match
" ⁄`‹›fi‡`·‚°±≤–≥÷º¡™£¢∞§¶•ªÚ…¯≠˘¿€ÅıÇÎ`Ï˝Ó`ÔÒÂ`Ø∏Œ‰Íˇ`◊„˛Á¸“«‘fl—`å∫ç∂`ƒ©˙`∆˚¬µ`øπœ®ß†`√∑≈¥Ω”»’æÆ"
.indexOf(c)
)?String.fromCharCode(a+32) // return the ASCII character if an option
// character was matched
:c // else return the character unchanged
)
.join`` // return output
```
## Test
```
var solution = t=>[...t].map((c,i)=>~(x="`´¨ˆ˜".indexOf(c))?(t[i-1]==" "|!i?"~EUIN":"`euin")[x]:~(a=" ⁄Æ‹›fi‡æ·‚°±≤–≥÷º¡™£¢∞§¶•ªÚ…¯≠˘¿€ÅıÇÎ`Ï˝Ó`ÔÒÂ`Ø∏Œ‰Íˇ`◊„˛Á¸“«‘fl—`å∫ç∂`ƒ©˙`∆˚¬µ`øπœ®ß†`√∑≈¥Ω”»’".indexOf(c))?String.fromCharCode(a+32):c).join``
```
```
<input type="text" id="input" value="„˙´˜ ˆ µø√´∂ †ø Áø®˚ß˙ˆ®´≤ †˙´®´ ∑åß å µå˜ ∑分ˆ˜© ƒø® µ´≥" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
] |
[Question]
[
"Counter" is a language I've created for the purpose of this question.
**Rules**
* Commands are read from left to right from the first character.
* Each command may be executed as it is read, or you may execute all commands together at the end.
* In case of an error, all commands up till the error must be executed.
* A program is written in exactly one line.
* Data is stored in counters. At the start, there is exactly one counter. More can be created and deleted.
* A counter holds an integer value between -100 and 100 (limits inclusive).
* Exactly one counter is the selected counter at any point in time.
* Counters are arranged in a 1d array, so one can move left (previous) or right (next) to change selected counter.
**Commands**
* **Any number between -100 and 100** - Set the currently selected counter to that value.
* **c** - Create a counter immediately after the currently selected counter, make it the selected counter, and set it to 0.
* **d** - Delete the currently selected counter, and make the previous one selected. If it is the first one, this is an error.
* **+** - Make the next counter the selected one.
* **-** - Make the previous counter the selected one. (Ensure that this command is not immediately followed by a number.)
* **o** - Output the value in the selected counter, followed by a space.
* **?** - If the value in the selected counter is 0, apply the **d** command on it.
* **#** - If the value in the selected counter is 0, ignore the next command.
* (space) - No meaning, but is to be treated like a command, if preceded by a #. Used to demarcate numbers.
**Errors**
* Going left of the leftmost counter, or right of the rightmost counter.
* Deleting the first counter.
* Encountering a `#` as the last command. (Of course, this means all commands will get executed anyways)
* A command that does not exist.
* A number that's too long.
**Task**
Create an interpreter in any language. Code will be in a file or given as input (your choice). Shortest code wins.
**Lengthy example**
Consider the code:
```
7cc--13 12do?+?#0#o3od-7o
```
Here is a breakdown of the program. `[]` indicates the selected counter.
```
Cmd Memory Output
7 [7]
c 7 [0]
c 7 0 [0]
- 7 [0] 0
-13 7 [-13] 0
7 [-13] 0
12 7 [12] 0
d [7] 0
o [7] 0 7
? [7] 0
+ 7 [0]
? [7]
# [7]
0 [0]
# [0]
o [0]
3 [3]
o [3] 3
d This is an error. Program terminates here.
```
Total output `7 3`
[Answer]
# JavaScript ES6, 300 bytes
Hey look, a nice round number!
```
x=>x.match(/-\d*|\d+|./g).map(c=>e?0:q?q--:c-101?Math.abs(c)>100?e++:s[p]=+c:c=="c"?s.splice(++p,0,0):c=="d"?s.length>1?s.splice(p--,1):e++:c=="o"?o+=s[p]+" ":c=="-"?--p<0&&e++:c=="+"?++p>=s.length&&e++:c=="?"?s[p]||(s.length>1?s.splice(p--,1):e++):c=="#"?s[p]||q++:c==" "?0:e++,s=[],e=p=q=0,o="")&&o
```
It doesn't error on `#` at the end of a program because that wouldn't affect anything at all. Let me know if I need to anyway.
[Answer]
# JavaScript (ES6) 228
```
s=>s.replace(/-?(\d+)|./g,(t,n)=>i?++i:C[k]&&(u='?-+# odc'.indexOf(t),n<101?C[k]=t:u>6?C[S='splice'](++k,0,'0'):u>5?C[S](k--,1):u>4?o+=C[k]+' ':u>2?+C[k]?0:i=-(u<4):u>1?k++:u>0?k--:~u?+C[k]||C[S](k--,1):i=1),i=o='',C=[k='0'])&&o
```
**Less golfed**
```
s=>(
i=o='',
C=[k='0'], // C: counters, k: current counter index
s.replace(/-?(\d+)|./g,
(t,n)=>( // tokenize, n is eventually the number, unsigned
i?++i:C[k] && ( // i>0 or C[k] undefined -> error found
u='?-+# odc'.indexOf(t),
n<101?C[k]=t // n present and < 101
:u>6?C.splice(++k,0,'0') //c add counter
:u>5?C.splice(k--,1) // d remove counter
:u>4?o+=C[k]+' ' // o output
:u>3?0 // space == NO OP
:u>2?+C[k]?0:i=-1 // set i to -1 to skip the next command
:u>1?k++
:u>0?k--
:~u?+C[k]||C.splice(k--,1) // ? conditional remove counter
:i=1) // invalid command error
)
),
o // return output
)
```
[Answer]
## Python3, 403 ~~530~~ bytes
~~This is seriously golfable, but I can't think of how...~~
Thanks to @cat for 127 bytes!!! (I'm really bad at golfing in Python)
```
c=input()
a=[0]
s=0
i=0
def g(i,n):
p=i
if n:i+=1
while c[i].isdigit():i+=1
a[s]=int(c[p:i]);return i-1
def e():
a.pop(s);s-=1
while i<len(c):
d=c[i]
if d.isdigit():i=g(i,0)
elif d=='c':s+=1;a.insert(s,0)
elif d=='d':e()
elif d=='+':s+=1
elif d=='-':
if c[i+1].isdigit():i=g(i,1)
else:s-=1
elif d=='o':print(a[s],end=' ')
elif d=='?':
if a[s]==0:e()
elif d=='#':
if a[s]==0:i+=1
i+=1
```
] |
[Question]
[
A [Vigenère Cipher](https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher) is encrypted by repeating a keyword to be the length of the plaintext, and summing each character in that text with the corresponding letter in the plaintext modulo 26. (using A=0,B=1 etc.)
For example, if the keyword is `LEMON` and the plaintext is `ATTACKATDAWN`, then the key is repeated to form `LEMONLEMONLE`, which is summed with the plaintext to form the ciphertext, `LXFOPVEFRNHR`.
Write a program or function which, given a list of words and a ciphertext, outputs all possible plaintexts for that ciphertext, such that the plaintext is the concatenation of words in the list, and the key is also a word from the list.
All words use only upper-case letters `A` to `Z`.
**Your code must run in polynomial time** with respect to the total length of the ciphertext and words list.
Shortest code (in bytes) wins.
# Example Inputs/Outputs
The input/output format for your program is flexible, but here I'm giving the list of words separated by commas followed by the ciphertext as input, and the output is the list of plaintexts separated by commas.
## Inputs
```
LEMON,ATTACK,AT,DAWN,BUNNY
LXFOPVEFRNHR
A,AA,AAA,AAAA,AAAAA,AAAAAA,AAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
XHQT,GIXIIR,QTIA,AZXO,KSECS,THIS,CIPHER,IS,EASY,TO,CRACK,CODE,GOLF
ZVTXIWAMKFTXKODDZCNWGQV
A,B,C,D,E,F,G,H,Z
DBCCBHF
A,AA
AAA
```
## Outputs
```
ATTACKATDAWN
(none)
THISCIPHERISEASYTOCRACK,XHQTGIXIIRQTIAAZXOKSECS
BZAAZFD,CABBAGE,DBCCBHF
AAA
```
[Answer]
# *Doesn’t respect specifications* – OCaml - 118 bytes
I’ll get back to it when I’ll have time on my hand.
```
open Char;;
fun m->List.map(fun k->String.mapi(fun i c->chr(65+(code c-code k.[i mod String.length k]+26)mod 26))m);;
```
>
> `- : string -> string list -> string list = <fun>`
>
>
>
As the function type shows, the function expect as arguments:
* a string: the encoded message
* a list of strings: the keys
It returns a list of strings, the messages as decoded by each string in the same order.
The function is anonymous, you can call it by inserting putting it inside parentheses (i.e. 2 bytes) and entering its arguments as follows:
```
open Char;;
(fun m->List.map(fun k->String.mapi(fun i c->chr(65+(code c-code k.[i mod String.length k]+26)mod 26))m)"ZVTXIWAMKFTXKODDZCNWGQV"["XHQT";"GIXIIR";"QTIA";"AZXO";"KSECS";"THIS";"CIPHER";"IS";"EASY";"TO";"CRACK";"CODE";"GOLF"];;
```
## Ungolfed
```
(* unshift the character x back to what it was before being shifted by k *)
(* Char.chr and Char.code translate from ASCII int to char and back *)
(* '+ 26' because the modulo operator can return negative numbers -__- *)
open Char;;
let unshift k x = chr ( 65 + (code x - code k + 26) mod 26 );;
(* Use the n-th character of the key to decrypt x, loops when necessary *)
let unshiftWithKeyAtPos key n x = unshift key.[n mod String.length key] x;;
(* Maps unshiftWithKeyAtPos key i x for each position i in cipherText *)
(* where x = cipherText.[i] is the i-th character of cipherText. *)
let decrypt key cipherText = String.mapi (unshiftWithKeyAtPos key) cipherText;;
(* Maps decrypt cipherText key for each key in keyList *)
let tryHard cipherText keyList = List.map (fun key -> decrypt key cipherText) keyList;;
(* And finally, call the function *)
let hiddenMessage = "LXFOPVEFRNHR";;
let keys = ["LEMON";"CODE";"GOLF"];;
tryHard hiddenMessage keys;;
```
[Answer]
# Python 2.7 - 235
Example solution to start things off. Should be pretty easy to beat.
Input is given as a python tuple from stdin (ex. `(["A","AA"],"AAA")`.
```
W,c=input();M={}
def s(t,r):M[t]=r;return r
g=lambda t:M[t]if t in M else not t or s(t,any(t.startswith(w)and g(t[len(w):])for w in W))
print filter(g,set(''.join(chr((ord(a)-ord(w[i%len(w)]))%26+65)for i,a in enumerate(c))for w in W))
```
] |
[Question]
[
(This is my first Q here, and I don't know much about code golfing.)
Your aim is to predict the winner of an ongoing [Snakes and Ladders](https://en.wikipedia.org/wiki/Snakes_and_Ladders) game.
**INPUT**
* A single number (2-1000) indicating the number of spaces on the board, say *x*.
* Another number (2-4) indicating number of players, say *n*.
* *n* numbers, each giving the position of each player on the game board.
* Another number (1-15) indicating number of snakes and ladders (combined), say *s*.
* *s* lines of input, each with 2 numbers - the start and end of each snake/ladder.
**OUTPUT**
*n* decimal numbers, accurate to 2 decimal places, indicating the probability of each player winning.
**WINNER**
The person to give the fastest program wins, not necessarily the shortest code. This might help those using a different algorithm to gain a huge advantage.
**Notes**
Players start on space 1, not 0. They win on reaching space *x*.
All players use a fair 6 sided dice. There are no re-rolls for 6s.
We assume that there is no 'bad' input given, such as more than 4 players, or a snake starting at the last space.
Players are given the same order of play as your input. The first player is the first to roll now, then the second and so on.
Even if you overshoot the win space, you still win.
[Answer]
# C, ~.25 seconds
I have calculated by using dynamic simulations instead of probability of each dice roll. The more accurate the probability, the slower... here a brief code...
Compile using:
```
gcc -o Snakes snakes.c
```
Code:
```
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
srand(time(0));
// initialize principal variables
int NumberOfSpaces = 100,
NumberOfPlayers = 4,
PlayerPosition[] = { 46, 56, 36, 66 };
//PlayerPosition[] = {0, 0, 0, 0};
// arrays of positions, must be in numerical order,
// must be in (start, end) format. correct - 1, 2, 5, 6, 8, 9
// incorrect - 1, 2, 8, 9, 5, 6
int LadderPositions[10] = { 3, 10, 5, 20, 20, 31, 22, 49, 44, 87 }, // positions of ladders
SnakePositions[10] = { 11, 3, 15, 1, 35, 22, 54, 29, 60, 20 }, // positions of snakes
SnakesLadders = 10; // # of snakes + ladders
// static arrays to hold
// # of dice rolls to complete game
int Player1Wins[10000],
Player2Wins[10000],
Player3Wins[10000],
Player4Wins[10000];
int NumberOfSimulations = 10001;
int OutsideLoop, Counter = 1, i, a, Win, EvenArray;
for (OutsideLoop = 0; OutsideLoop < NumberOfPlayers; OutsideLoop++) // do a simulation for each player
for (a = 0; a < NumberOfSimulations; a++) // play for each simulation
{
for (i = PlayerPosition[OutsideLoop]; i <= NumberOfSpaces + 1; i += (rand() % 6 + 1)) // roll the dice for each turn
{
Counter++ ;
for (EvenArray = 0; EvenArray < SnakesLadders; EvenArray+=2) // check if space is snake or ladder
{
if (i == LadderPositions[EvenArray])
i = LadderPositions[EvenArray + 1];
if (i == SnakePositions[EvenArray])
i = SnakePositions[EvenArray + 1];
}
}
// put value in array
if (OutsideLoop == 0)
Player1Wins[a] = Counter;
else if (OutsideLoop == 1)
Player2Wins[a] = Counter;
else if (OutsideLoop == 2)
Player3Wins[a] = Counter;
else if (OutsideLoop == 3)
Player4Wins[a] = Counter;
Counter = 0;
}
// count how many time each person won
int P1Wins = 0, P2Wins = 0, P3Wins = 0, P4Wins, Ties = 0;
for (Win = 0; Win < NumberOfSimulations; Win++)
{
if (Player1Wins[Win] < Player2Wins[Win] && Player1Wins[Win] < Player3Wins[Win] && Player1Wins[Win] < Player4Wins[Win])
P1Wins++;
else if (Player2Wins[Win] < Player1Wins[Win] && Player2Wins[Win] < Player3Wins[Win] && Player2Wins[Win] < Player4Wins[Win])
P2Wins++;
else if (Player3Wins[Win] < Player1Wins[Win] && Player3Wins[Win] < Player2Wins[Win] && Player3Wins[Win] < Player4Wins[Win])
P3Wins++;
else if (Player4Wins[Win] < Player1Wins[Win] && Player4Wins[Win] < Player2Wins[Win] && Player4Wins[Win] < Player3Wins[Win])
P4Wins++;
else if (Player2Wins[Win] == Player1Wins[Win] == Player3Wins[Win])
Ties++;
}
printf("[ + ] Namaste! Welcome to the Snakes & Ladders guess who wins program!\n");
printf("[ + ] I will run 10K simulations of the game to make a guess on the probability of the winner.\n");
printf("[ + ] Given %i players, with starting positions of :\n[ + ] P1 - %i\n[ + ] P2 - %i\n[ + ] P3 - %i\n[ + ] P4 - %i\n[ + ] Here's the probability I think each player has of winning...\n", NumberOfPlayers, PlayerPosition[0], PlayerPosition[1], PlayerPosition[2], PlayerPosition[3]);
printf("[ + ] P1 = %i / 10000\n[ + ] P2 = %i / 10000\n[ + ] P3 = %i / 10000\n[ + ] P4 = %i / 10000\n[ + ] Ties = %i\n", P1Wins, P2Wins, P3Wins, P4Wins, Ties);
return 0;
}
```
Environment - timed using `time` (bash command) on linux core i7
10 simulations ~ .003 second
10000 simulation ~ .030 second
Sample outputs :
```
time ./Snakes
[ + ] Namaste! Welcome to the Snakes & Ladders guess who wins program!
[ + ] I will run 10K simulations of the game to make a guess on the probability of the winner.
[ + ] Given 4 players, with starting positions of :
[ + ] P1 - 10
[ + ] P2 - 21
[ + ] P3 - 50
[ + ] P4 - 70
[ + ] Here's the probability I think each player has of winning...
[ + ] P1 = 86 / 10000
[ + ] P2 = 254 / 10000
[ + ] P3 = 131 / 10000
[ + ] P4 = 9098 / 10000
[ + ] Ties = 0
real 0m0.036s
user 0m0.036s
sys 0m0.000s
```
Alt input position:
```
[ + ] Given 4 players, with starting positions of :
[ + ] P1 - 15
[ + ] P2 - 5
[ + ] P3 - 60
[ + ] P4 - 50
[ + ] Here's the probability I think each player has of winning...
[ + ] P1 = 955 / 10000
[ + ] P2 = 3041 / 10000
[ + ] P3 = 1833 / 10000
[ + ] P4 = 3572 / 10000
[ + ] Ties = 0
real 0m0.024s
user 0m0.024s
sys 0m0.000s
```
More input:
```
[ + ] Given 4 players, with starting positions of :
[ + ] P1 - 46
[ + ] P2 - 56
[ + ] P3 - 36
[ + ] P4 - 66
[ + ] Here's the probability I think each player has of winning...
[ + ] P1 = 94 / 10000
[ + ] P2 = 442 / 10000
[ + ] P3 = 2454 / 10000
[ + ] P4 = 6319 / 10000
[ + ] Ties = 0
real 0m0.018s
user 0m0.018s
sys 0m0.000s
```
] |
[Question]
[
Since my use of [Element](https://github.com/PhiNotPi/Element) has increased recently, I am interested in tips for golfing programs written in it.
What general tips do you have for golfing in Element? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Element.
Please post one tip per answer.
[Answer]
# Ways to put extra 0s on the stack
A lot of times, you will be faced with the following 4-character piece of code:
```
0 2@
```
Element's stack-item-movement operator @ is very general-purpose, sometimes *too much* so for golfing, since it always takes two arguments, which may need to be separated by a space. So, it can take several characters to perform a single movement.
Usually, there is a better way to do this.
You can often produce empty values from the hash. The code `2:0 2@` can almost always be shortened to `3:~2@` to save one character because chances are that nothing is stored in the hash for that particular key.
If the top thing on the stack is the input, you can sacrifice the newline at the end of it like so:
```
_0 2@
_)2@
```
In a limited number of cases, usually with `0 1@`, you don't need the `@` at all. This works with input or when putting a constant on the stack.
```
_0 1@
'_"
text 0 1@
'text"
```
[Answer]
## Performing logic operations on a list of numbers.
Let's say you had a simple task: Take a list of 5 numbers and verify that all of them are multiples of 7. (You can replace "multiple of 7" with any other test.) You will soon run into a problem: in order to perform a loop, you must put a value on the control stack, but this this can interfere with the logic that you are performing on the list of numbers.
The following solution does not work because the value `5` is accidentally included as one of the arguments in the chain of ORs.
```
5'[_7%?|]!"` #does not work
```
There are a few ways to overcome this.
```
5'0[_7%+]?!"` #self-contained
5'[_7%+]?!"` #if main stack is empty
5'[_7%?!&]"` #main stack untouched, but consumes the 5
```
If the numbers you need to compare are already on the stack, then the above approach will not work.
```
2 3 7 4 8 5'[7%?|]!"` #does not work
2 3 7 4 8 5'[!7%?|!]"` #works
2 3 7 4 8 5'[7%?!&]"` #shorter, notice the | -> &
5'2 3 7 4 8[7%?!&]"` #can save a space in some cases
```
[Answer]
# Using the hash as an array
Element does not have native support for arrays, but the hash can be used as a makeshift array for simple operations. This is done by using numbers as keys. The following code initializes an array [7,32,12,8,3]
```
7 0;32 1;12 2;8 3;3 4;
```
For a much larger array, this is a more compact way to go:
```
7 32 12 8 3 13 5 1 0 67 12 54 11 13'["1-+2:';]
```
As you can tell, using the hash to hard-code an array is a measure of last resort. They work nicer when the array is created in a less hard-coded fashion. Here is code that can take as input an array size and a list of values and put it in an array.
```
_'0[2:_)1@;1+]
```
Retrieving a value is easy though and can be where this convoluted scheme pays off. If `i` contains the index you want to retrieve, then the code is simple:
```
i~~
```
To give an array a name, you can append a single letter to the index when storing and retrieving.
[Answer]
# "Factoring Out" things from If-Else constructions
If you ever have the code
```
?[...]![..]
```
Then you probably have an If-Else construction. You really want to minimize the amount of duplicate code you put in these things. Generally speaking, if V W X Y Z are blocks of code, then the following compression should be tried:
```
?[WXVZ]![WVYZ]
?W[X]V![Y]Z
```
This usually works even if V/W/Z is a `~`;` type of operator, but probably does not work if V/W/Z is `"`.
] |
[Question]
[
This is inspired by the [Brainf\*\*\* to tinyBF converter challenge](https://codegolf.stackexchange.com/questions/48628/brainf-to-tinybf-converter).
Brainf\*\*k (which will be henceforth referred to as BF) is a well-known estoric programming language, so I won't go over it too much here.
[Nameless language](http://esolangs.org/wiki/Nameless_language) is a binary-looking version of BF. See the linked page for more info.
Your challenge is to implement a **golfed Nameless-to-BF converter**. It should implement *all* of the commands except for 1100 (which isn't really possible to implement in BF) and 1010 (that isn't really possible, either). Any characters other than 1's and 0's should be ignored because they can be used for comments (after all, you wouldn't want an unreadable program, right? ;).
Here's a simple table of a Nameless -> BF mapping:
```
0000 -> >
0001 -> <
0010 -> +
0011 -> -
0100 -> .
0101 -> ,
0110 -> [
0111 -> ]
1011 -> [-]
1000 -> adds the base 10 value of the next command to the current memory cell (see below)
1001 -> subtracts the base 10 value of the next command from the current memory cell (see below)
```
**NOTE**: I accidentally flipped `<` and `>`. Thanks to @IlmariKaronen for pointing that out.
For 1000 and 1001, you can directly implement it in the translator. For instance, this:
```
1000 0010
```
could be written as:
```
++
```
The translator determined the value of the next command in advance and wrote it out.
Invalid sequences (e.g. 1111) and the presence of 1000/1001 at the end of the program are undefined; you don't have to handle them.
MAY THE GOLFING BEGIN!!!
[Answer]
# CJam, 58 bytes
```
q{As#)},:~4/2fb{(:X8<"><+-.,[]"X={XA<{("+-"X=*}"[-]"?}?o}h
```
[Try it online.](http://cjam.aditsu.net/#code=q%7BAs%23)%7D%2C%3A~4%2F2fb%7B(%3AX8%3C%22%3E%3C%2B-.%2C%5B%5D%22X%3D%7BXA%3C%7B(%22%2B-%22X%3D*%7D%22%5B-%5D%22%3F%7D%3Fo%7Dh&input=10001010011000001000011100001000101000001000001100000010000100010001000100110111%0A00000010001001000000001001001000011101000100100000110100000000100010010000010001%0A100011110100000001001000001101001001011001001001100001000000)
### Explanation
```
q "Read the input.";
{As#)}, "Remove any extraneous characters (not '0' or '1').";
:~ "Evaluate each character ('0' -> 0, '1' -> 1).";
4/2fb "Split into groups of 4 (Nameless commands) and numerically
evaluate each group as an array of binary digits.";
{ "While command values remain:";
(:X "Grab the next command value.";
8< "If the command value is less than 8:";
"><+-.,[]"X= "Then: It maps directly to a BF command. Look it up.";
{ "Else:";
XA< "If the command value is less than 10:";
{("+-"X=*} "Then: It is 8 or 9. Grab the next command value and
produce a string of that many copies of '+' if the former
command value is 8, or '-' if it is 9.";
"[-]"? "Else: It is 11. Produce its translation, '[-]'.";
}?
o "Output the BF translation.";
}h
```
[Answer]
# Perl - ~~343~~ ~~339~~ 305 bytes
I know CJam's already done it, but I figured I'd try a non-esoteric solution.
```
open(F,$ARGV[0]);%s=qw(0000 > 0001 < 0010 + 0011 - 0100 . 0101 , 0110 [ 0111 ] 1011 [-]);while(<F>){$x=0;$p='';@c=split(' ');foreach$c(@c){if($c=='1000'){for(1..oct("0b".$c[$x+1])){$p.='+'}}elsif($c=='1001'){for(1..oct("0b".$c[$x+1])){$p.='-'}}elsif(exists$s{$c}){$p.=$s{$c}}else{$p.=$c.' '};$x++}print$p}
```
It keeps comments, and prints it without a trailing newline.
If I've missed anything, please let me know.
**Changes**
* Saved 4 bytes by deleting unnecessary characters, and fixed comments.
* Saved 34 bytes by removing checking for `1000`/`1001` at the end of a line. (Credit to mbomb007)
[Answer]
# Python 2, ~~221~~ 216 bytes
Run it here: <http://repl.it/hxJ/1>
Not sure if it can be golfed more. I had to use a `while` (very annoyingly) instead of a list comprehension for the whole thing, since the iterator must skip an instruction if the instruction is `1000` or `1001`. (By the way, the indentations are tab characters.)
```
import re
b='><+-.,[]'
i=re.sub('[^01]','',input())
n=[int(j,2)for j in re.findall('.'*4,i)]
k=0;o=''
while k<len(n):
c=n[k]
if c<8:o+=b[c]
elif c<10:o+=n[k+1]*('+'if c<9 else'-');k+=1
else:o+='[-]'
k+=1
print o
```
] |
[Question]
[
This code-golf challenge is based on [the following puzzle](https://puzzling.stackexchange.com/q/7882/4551):
>
> You have an odd number of tokens whose weights are known whole numbers, and they don't all have the same weight. Show that there's a token you can remove so that the remaining tokens can't be split into two equal-size sets that have the same total weight.
>
>
>
Here's the canonical solution to the puzzle, which also suggests an algorithm to do it (spoilers if you want to solve the puzzle yourself):
>
> If all the weights are even or all odd, the problem is unchanged if we truncate the least significant bit from each one (i.e. floor-divide by 2). Keep doing that until there's at least one even weight and one odd weight -- this must happen eventually because the total weight decreases at each step. Then, remove a weight whose parity is opposite the parity of the sum, leaving an odd total weight, which clearly prevents an even split.
>
>
>
Your goal is to figure out such a weight to remove. Shortest code wins.
**Input:**
An odd-size list of positive whole numbers, not all the same. Any list-like structure is fine, though it has to work with the numbers in any order.
**Output:**
One of those numbers, such that the remaining numbers can't be partitioned into two sets with equal size and equal sum. You must output the number, not its index.
If there's multiple choices, any one of them is fine. It doesn't have to be the number chosen by the solution above.
Your code should be able to handle test cases like below within one second.
**Test cases:**
```
[1, 2, 3]
1
[3, 3, 3, 3, 3, 3, 5]
3
[1, 2, 3, 4, 5, 6, 7, 8, 9]
2
[1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
1
[128, 256, 256]
256
[18770, 10578, 7506, 5458, 4434, 6482, 5458, 4434, 2386, 11602, 1362, 16722, 11602, 23890, 12626, 47442, 57682, 35154, 57682, 81234, 44370, 12626, 12626, 46418, 68946, 91474, 2386, 43346, 46418, 35154, 32082]
7506
```
If you want to see all possible outputs (this is just to show, your code must output exactly one):
```
[1, 2, 3]
{1, 2, 3}
[3, 3, 3, 3, 3, 3, 5]
{3}
[1, 2, 3, 4, 5, 6, 7, 8, 9]
{2, 4, 6, 8}
[1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
{1}
[128, 256, 256]
{256}
[18770, 10578, 7506, 5458, 4434, 6482, 5458, 4434, 2386, 11602, 1362, 16722, 11602, 23890, 12626, 47442, 57682, 35154, 57682, 81234, 44370, 12626, 12626, 46418, 68946, 91474, 2386, 43346, 46418, 35154, 32082]
{68946, 5458, 44370, 46418, 11602, 23890, 7506, 91474, 32082, 1362, 81234}
```
[Answer]
# CJam, 19 17
```
q~:T{T:^^2bW%}$W=
```
Input format:
```
[1 2 3 4 5 6 7 8 9]
```
2 bytes thanks to Optimizer.
[Answer]
# Python 2, 99
This came out pretty badly.
```
s=input()
b=1
while{x&b for x in s}<{0,b}:b+=b
print[x for x in s if(reduce(int.__xor__,s)^x)&b][0]
```
Numbers may be input comma-delimited.
] |
[Question]
[
This question is inspired by the game [Disco Zoo](https://play.google.com/store/apps/details?id=com.nimblebit.discozoo)
## Background
Disco Zoo is a game where you can go into the wild and rescue animals. Once you have found an animal you can put it in your zoo for your visitors to see.
To find animals you first select a field to search, and you get to see a 5x5 grid where the animals are hiding. At the top of the screen you can see which animals are hiding in the field.
Each animal has a different pattern, which never changes for the same animal. E.g. (`X` is pattern, `o` is padding)
```
Animal=Sheep Animal=Unicorn
Pattern: Pattern:
XXXX Xoo
oXX
```
Some animals use 2 blocks, some 3 and some 4. The pattern will be translated, but not rotated.
## Task
The user gives you a pattern or the name of an animal (your choice) and you have to generate an optimum strategy to search for that animal/pattern. A strategy is a set of blocks from the 5x5 grid; an optimum strategy is one which guarantees to find at least 1 block from the pattern, and where there is no strategy with fewer blocks which can make the same guarantee.
For sheep and unicorns the optimum strategy would be searching the middle column:
```
ooXoo
ooXoo
ooXoo
ooXoo
ooXoo
```
Another example:
```
Animal: Hippo
Pattern: Optimum strategy:
ooooo
XoX oXXoo
ooo oXXoo
XoX ooooo
ooooo
```
The Disco Zoo wiki's [Patterns](http://discozoowiki.com/wiki/Patterns) page lists all the animals and their patterns. You may hard-code the patterns. The wiki also lists optimum strategies for all the animals. Feel free to look at them but you're not allowed to hard-code them.
Input: Either a pattern made of `X` and `O` or the name of the animal.
Output: a 5x5 grid made of `X` or `O` where X marks an optimum strategy.
[Answer]
# Ruby 221
```
->a{l=a.join(?o*(5-w=a[0].size))
s=?o*25
q=(0..25-l.size).select{|i|i/5==(i+w-1)/5}.map{|i|(?o*i+l+s)}
(h=q[0].size.times.map{|i|q.count{|p|p[i]<?o}}
s[c=h.index(h.max)]=?X
q.reject!{|p|p[c]<?o})while q!=[]
s.scan /.{5}/}
```
### Input and Output
This is a Ruby function that takes one parameter representing the animal and returns the solution, both being represented as string arrays.
For example, the Hippo is represented as:
```
['XoX',
'ooo',
'XoX']
```
and its solution is:
```
['ooooo',
'oXXoo',
'oXXoo',
'ooooo',
'ooooo']
```
### Test
Here's a [working version](http://ideone.com/mE3o4Y). Feel free to experiment with it and enter more animals as parameters.
### Algorithm
I found this problem very interesting and I experimented to solve it in different ways, including brute force, which is less feasible, but possible for the given inputs (it would be terribly inefficient for the input `['X']` though).
The algorithm I found to be the most efficient is the following:
1. Compute all possible positions for the animal on the 5x5 board
2. Given the existing positions, compute a map of frequencies for each of the 25 cells
3. Take one of the cells that contain the max number of "hits" and make it part of the solution. Exclude all positions that are "hit" in that particular cell.
4. Repeat steps 2-3 until there are no positions left.
I don't have a proof of optimality for this algorithm, but it tested most animals present on [the wiki page](http://discozoowiki.com/wiki/Patterns) and it returned optimal solutions for all.
Note that for some animals the solutions are not identical to the ones presented in the wiki, but involve the same number of blocks.
For example, [the Wooly Rhino page](http://discozoowiki.com/wiki/Wooly_Rhino) presents this solution:
```
ooooo
ooooo
oXXXo
ooooo
ooooo
```
and the algorithm returns this one:
```
ooooo
oooXo
ooXXo
ooooo
ooooo
```
which is also correct and optimal (3 blocks).
Here's the (slightly more) readable version of the program:
```
SIZE = 5
# return all possible placements for the animal on a 5x5 board
def get_placements(animal)
# represent the 5x5 board and the animal as linear arrays
linear_animal = animal.join(?o*(SIZE - animal[0].size))
d = SIZE*SIZE
(0..d-linear_animal.size)
.select{|i| i/5 == (i+animal[0].size-1)/5} # to avoid wrap-around positions
.map { |i|
(?o*i + linear_animal + ?o*d)[0...d]
}
end
# given a set of possible placements,
# return a map of frequencies for every cell
def heatmap(placements)
placements[0].size.times.map do |i|
placements.count {|p|p[i] < ?o}
end
end
# given an animal, return the solution as an array of 5 5-character strings
def solve(animal)
placements = get_placements animal
solution = []
while placements.any?
h = heatmap(placements)
solution << chosen = h.index(h.max)
placements = placements.reject {|pl| pl[chosen] < ?o }
end
(0...25).map{|i| solution.include?(i) ? ?X : ?o }.join.scan /.{5}/
end
```
[Answer]
# Python3, 474 bytes
```
R=range
E=enumerate
V=lambda d,p,X,Y:not all((x+X,y+Y)in d for x,y in p)
def f(p):
d={(x,y):[]for x in R(5)for y in R(5)}
p=[(x,y)for x,r in E(p)for y,v in E(r)if'X'==v]
X,Y,C=0,0,0
while 1:
C+=1
Q,W=[],[]
for x,y in p:d[(x+X,y+Y)]+=[C]
Y+=1
if V(d,p,X,Y):
if V(d,p,X:=X+1,Y:=0):break
M=[]
while any(d.values()):t=max(d,key=lambda x:len(d[x]));M+=[t];d={i:{*d[i]}-{*d[t]}for i in d}
s=[['0'for _ in R(5)]for _ in R(5)]
for x,y in M:s[x][y]='1'
return s
```
[Try it online!](https://tio.run/##jZNda9swFIavp19xoBeSGrUkbIPhopuFlsIo6bqtc@eZIVdKo8WRPNlJY0p/eyb5o2sYSeuAlSO9z/l4hYu6mlnz9kPhNpsr7oS5U@iUK7NcKCcqha55LhaZFCBZwWJ2ExlbgchzQtaDmNWDG6oNSJhaB2tWgw8KiqSawpQUNEIg@QPxBzRK0kYTFFfkPQ1B3QePCAqeNLo2kQsnpz5DI2OrNnRUT3GMOV@lCHwvbMyHzP8Q3M90rmDk68F4wEd@@cy@8yRliVduNRfJ5KnzdMCTcRDctIyewjXp5gy9P9@JeDwY@fH5kEaZU2KO4IKH7G1pYWoij1ciX6qSUBpVfCHWnpyrujdwHeXKEJmsU0pPLnzpKj3x7ujo4VAmOn08CmuVPoZudehVeltKniR4iMPer96tdDtCz@e7iEpfIKlTjkcYgVPV0hkoN@FGzkjmp3rT7eGfBh//ttqQhSgIbv@zqddQihAqnDYVOSMJjv2Dfc9w8GWmVNGd4CN8@G5In@smE8yCaXjYA9@MvrXO7EZsjBkcnOuisAiwtTZkaLY9vxtrqEt9F7QvSSeNNhdVXSxLD0xeItrWT1fK1VD@WQqnwCglS6gsZAoWorqdKbmHZ7D1atJdiSzT1augRn9uXan2WR3G8rN06yTu1knHf/IfsnDW7kzREXEPfNVSilzPXwO0lVvuh8qc2H9TuEda4qMSbneVVhv38/xj/H3s8eP/MmN7OxfVHgeevNsudTmzyuj15i8)
] |
[Question]
[
So I really like to mess with tables and shallow and deep copies and [I can do it in 239 chars!](https://gist.githubusercontent.com/SoniEx2/fc5d3614614e4e3fe131/raw/c42011f2a3e01ef1884f65fb186a400127e6345b/tablecopy.min.lua) I wonder if there's a shorter way to do it...
Rules:
* It must be done in less than 239 chars.
* You must set table.copy.shallow and table.copy.deep.
* A deep copy must maintain recursion. (so if I had tx.t == tx, a deep copy must have ty.t == ty (where ty is a deep copy of tx))
* You must make a local copy of every function you use. (for speed)
* You must be able to pass in a custom recursion table with a metatable to override default copy behavior. (at least on the deep copy function, see examples [here](https://gist.github.com/SoniEx2/fc5d3614614e4e3fe131#file-tablecopy-sane-lua))
* If needed, use metatables. If possible, abuse them.
* It must work in Lua 5.1 and 5.2.
* You may use load/loadstring.
* You may use the C API.
* Some input/output examples (actually unit test): <https://gist.github.com/SoniEx2/7942bdd0658b719ab275>
[Answer]
## 235
Substantially based on the guts of SoniEx2's 239 answer.
```
local o,k,F=type,next,{}for n=0,2 do
F[n]=function(a,r,t,G)if n<1 or o{}~=o(a)then return a end
t={}r=r or{}r[a]=n<2 and t G=F[n%2]for x,y in k,a do
t[r[x]or G(x,r)]=r[y]or G(y,r)end
return t end end
table.copy={shallow=F[2],deep=F[1]}
```
The advantage comes from using the same function prototype for both functions. Instantiating the same function prototype with different upvalues allows it to fill both roles.
Ungolfed:
```
-- ungolfed
-- note that type and next must have local copies to meet the spec
local o, k, F = type, next, {}
for n = 0, 2 do
-- F[0] will be the identity function
-- F[1] will be table.copy.deep
-- F[2] will be table.copy.shallow
F[n] = function(a, r, t, G)
-- a is the table input
-- r is the optional "custom recursion table" that is required
-- t and G are just locals
-- the spec implies (but does not state) that the global environment shouldn't be polluted
-- r will only be used by recursive calls
-- if n < 1, this is F[0], so act is the identity
-- o is type, o{} is "table"
-- if a is not a table, just return it
if n < 1 or o{} ~= o(a) then
return a
end
-- t will be the copy
t = {}
-- r will be the map that remembers which tables in the original map to which tables in the copy
-- or, if it is passed in, it is a table that controls the behavior of the copy
r = r or {}
-- F[0] doesn't each here
-- F[1] must add t to the map
-- F[2] must not add t to the map
-- (adding false will not hurt F[2] -- only true values will be picked up below)
-- (behavior may not be exactly as desired for shallow copy, but spec doesn't require this feature)
r[a] = n < 2 and t
-- this is the function we will call to copy members
-- for F[1] table.copy.deep, this is F[1] itself
-- for F[2] table.copy.shallow, this is F[0] the identity
-- (for F[0], we never get this far)
-- the byte count seems equivalent making this a local vs putting it
-- in both places it is used, but this is probably more efficient
G=F[n%2]
-- loop over and copy members
-- first try r (which will only have non-1 entries for tables in F[1])
-- then try G
-- note that instead of calling "pairs" as usual, we can observe that pairs(a)
-- is defined to return next, a, nil -- we use these (with implicit nil) directly
for x, y in k, a do
t[r[x] or G(x,r)] = r[y] or G(y,r)
end
return t
end
end
-- export the functions as required
table.copy = {
shallow = F[2],
deep = F[1]
}
```
Hopefully I understood the spec correctly. This passes the provided test cases and there is enough similarity in the construction that I'm reasonably sure it does the same thing.
Note -- Initially I didn't understand the part about the "custom recursion table", but I have edited my answer to support it.
Note 2 -- Improved answer. I've also decided that the provided reference solution in 239 bytes does not exactly match my understanding of how the custom recursion table ought to work, since it cannot be used to add false into the copy. However, I believe my solution works as well as the provided one.
[Answer]
## 238 chars!
Turns out, it wasn't impossible!
```
loadstring(("local k,o,d=next,type dDif o{}~=o(a)thenBaAt={}r=r or{}r[a]=tCt[r[x]or d(x,r)]=r[y]or d(y,r)ABtAtable.copy={shallowDt={}Ct[x]=yABtA,deep=d}"):gsub("%u",{A=" end ",B=" return ",C=" for x,y in k,a do ",D="=function(a,r,t)"}))()
```
] |
[Question]
[
You are a contractor for a company who designs electrical circuits for the various products they make. One day, the company accidentally gets a huge shipment of one-ohm resistors and absolutely nothing else, and give you the task of putting them to good use in the newest products they're making.
Your task is to build a program that takes a positive rational number as input, in the following form:
```
a / b
```
and return a resistor diagram with the exact given resistance, that uses as few one-ohm resistors as possible.
Your resistor diagram will consist of:
* The number `N`, to denote how many `SPT`s there are. (I will describe an `SPT` below.)
* `N` lines, each containing two numbers `A` and `B` representing numbered electrodes on a circuit board, followed by one `SPT`.
* One line containing two numbers `P` and `Q` denoting which two electrodes to measure the resistance between.
An `SPT` is a "series-parallel tree", a way to describe a series-parallel circuit in a tree format.
A valid `SPT` is either:
* The number 1, representing a single resistor.
* `S( )`, enclosing a number followed by zero or more `P( )` SPTs.
* `P( )`, enclosing a number followed by zero or more `S( )` SPTs.
Examples of valid `SPT`s:
```
1 <- has a resistance of 1
S(1) <- equivalent to 1 and P(1)
S(2, P(3)) <- has a resistance of 7/3, using 5 resistors
P(1, S(2), S(3), S(4, P(2))) <- has a resistance of 18/37, using 12 resistors
```
Examples of invalid `SPT`s:
```
2 <- the two resistors are in an unknown configuration. Use P(2) or S(2) instead.
P(2, P(1)) <- use P(3) instead.
P(4, P(1, S(3), S(2))) <- use P(5, S(3), S(2)) instead.
```
## Specifications
Your program must work for any numerator and denominator up to `150 000`.
Your program's source code, excluding any imported standard or third-party libraries, must not exceed one megabyte (1,048,576 bytes) total.
Your program will be tested on a specific, randomly chosen set of 10,000 fractions (to be determined at a later date), and scored on how few resistors it requires to build all 10,000 circuits. The program that uses the fewest resistors is the winner.
---
# Testing data
The input
```
3 / 8
```
might return
```
1
1 2 S(0, P(8), P(4))
1 2
```
to represent a series of 8 resistors and then 4 resistors in parallel. This may not be the optimal solution; but for the purposes of this problem, it is valid output.
The input
```
5 / 6
```
might return:
```
12
1 2 1
1 3 1
1 5 1
2 4 1
2 6 1
3 4 1
3 7 1
4 8 1
5 6 1
5 7 1
6 8 1
7 8 1
1 8
```
to represent a cube of one-ohm resistors with vertices numbered `1` through `8`, having its resistance measured between opposite corners. Of course it is possible to just do `S(P(2), P(3))` using just five resistors, but this is an example of how the notation is used to represent non-series-parallel diagrams.
[Answer]
For series-parallel circuits with few resistors, the resistances which can be created with `n` resistors but not with fewer are the numbers on the `n`th level of the Stern-Brocot tree. (This breaks later on, with `5/6 = 1/2 + 1/3` apparently a minimal counterexample).
Instead of mapping from [position in the Stern-Brocot tree](https://codegolf.stackexchange.com/q/15934/194) to an S-P expression, it turns out to be much more convenient to use the [Calkin-Wilf tree](http://en.wikipedia.org/wiki/Calkin%E2%80%93Wilf_tree); its nodes at a given depth are permutations of the Stern-Brocot tree's nodes at that depth, but it has a different parent-child relationship: the left child of `m/n` is `m/(m+n) = (1^-1 + (m/n)^-1)^-1 = P(1, m/n)`, and the right child of `m/n` is `(m+n)/n = 1 + m/n = S(1, m/n)`.
## GolfScript
```
# Parse input
'/'/' '*~
# Stack: numerator denominator
{
# numerator denominator
1$1$<{
# n/d is less than 1, so parent is n/(d − n) and we're looking at Parallel
', P('@@.2$/@@1$%
# ', P(' d/n n d%n
}{
# n/d >= 1, so parent is (n - d)/d and we're looking at Series
', S('@@1$1$/@2$%@
# ', S(' n/d n%d d
}if
# Loop until we get to 0/1 or 1/0
1$1$*
}do;;
# Stringify
]''*
# Trim leading ', '
2>.
# Close the parentheses
'('/,(')'*+
# Add the boilerplate
'1
0 1 '\'
0 1'
```
[Answer]
# Python
As a last-place reference solution, here is a naïve solution that always works:
```
frac = raw_input().split(" / ")
num = int(frac[0])
den = int(frac[1])
print 1
print 1, 2,
pstr = ""
for x in range(den):
pstr += "S(%s), " % num
pstr = pstr[:-2]
print "P(%s)" % pstr
print 1, 2
```
Always creates `n` parallel of `m` resistor series for the resistance `m/n`, using `mn` resistors each time.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 6 years ago.
[Improve this question](/posts/8628/edit)
Last week we had a programming contest in my university and I am very curious about one of the problems , one which only one team (but from another city) was able to solve. Maybe its not that hard, but I cant find any solutions that will take less than a second of execution time. The problem is the following:
# Problem
You have **N** domino tiles separated by different amounts (integer values that are given to you) and you know the height **H** of these tiles (all have the same height). They are all placed standing up so that if you push one it falls in the direction of the next one. This way, if tile **I** is close enough (**H** or less) to tile **I**+1, the first one will push the second one when it is pushed down, producing the domino effect. Suppose that not all the distances that separate the tiles are smaller than **H**, what's the minimum amount of moves you need to make in order to have all the distances be at most **H**? You can't move the first nor the last tile. Print a falsey value if it is not possible.
**Note:** You are only allowed to move integer amounts and only to spots on the line defined by tile i-1 and tile i+1. This means you cant grab one and place it wherever you want.
**Here are the input sizes:** **(3 ≤ N ≤ 1000) (1 ≤ H ≤ 50)** and the distances **(1 ≤ Di ≤ 100 for i = 1, 2, ..., N-1).** [Someone uploaded it to SPOJ recently](http://www.spoj.pl/problems/TAP2012E/)
>
> **Input:**
>
>
> N H
>
>
> d1 d2 d3 d4 ... d(n-1)
>
>
> **Output:**
>
>
> Minimum amount of moves.
>
>
>
**Sample**
>
> **Input1**
>
>
> 8 3
>
>
> 2 4 4 1 4 3 2
>
>
> **Output1**
>
>
> 3
>
>
>
Sample2
>
> **Input2**
>
>
> 10 2
>
>
> 1 2 2 2 2 2 2 2 3
>
>
> **Output2**
>
>
> 8
>
>
>
Sample3
>
> **Input3**
>
>
> 5 2
>
>
> 2 2 2 2
>
>
> **Output3**
>
>
> 0
>
>
>
Sample4
>
> **Input4**
>
>
> 5 3
>
>
> 1 6 2 4
>
>
> **Output4**
>
>
> -1 (NOT POSSIBLE)
>
>
>
I have only found a good solution for two cases (Pseudo-Code):
```
D=sum_of_all_distances
MaxPossible=(N-1)*H
if D==MaxPossible and there is no di such that di>H
Answer=0
else if D>MaxPossible
Answer=-1
```
[Answer]
## Python
```
N, H = map(int, raw_input().split())
D = map(int, raw_input().split())
# map from (number of dominoes, distance to last domino) to
# the number of moves needed to adjust the first number of dominoes
# exactly that far.
M = {}
M[1,0] = 0
for i in xrange(2, N+1): # i = number of dominos to try
for d in xrange(H*(i-1)+1):
M[i,d] = 1e9
for d in xrange(H*(i-1)+1): # position of last domino
for e in xrange(1, H+1): # distance from last domino to previous one
if d-e > H*(i-2): continue
if d-e < 0: continue
if sum(D[:i-1]) == d:
# don't move last domino, arrange rest
M[i,d] = min(M[i,d], M[i-1,d-e])
else:
# arrange rest, move last domino to right location
M[i,d] = min(M[i,d], 1 + M[i-1,d-e])
print M.get((N,sum(D)), -1)
```
Standard dynamic programming. Runs pretty much instantaneously on the example inputs. How big a problem do we have to solve in under a second?
[Answer]
### I tried in Perl which tries immediate tile distance adjustment and then cascading movements to get required distance
Execution syntax perl programName N H d1 d2 ... dn-1
Test cases sample: perl domino\_slider.pl 8 3 2 4 4 1 4 3 2 output :3
```
use subs /dominochecker distancechecker subcheckright subcheckleft RigidMode/;
## Receive Input Tile Height D1 D2 ... Dn-1
$Tiles=$ARGV[0];
$Height=$ARGV[1];
$loop_count=0;
for $i (2...$#ARGV){
$distance[$loop_count]=$ARGV[$i];
$loop_count++;
}
$loop_count=$move=0;
sub dominochecker {
$lc=0;$retflag=0;
while ($lc<$Tiles-1) {
if ($distance[$lc]>$Height) {
$retflag=1;
}
$lc++;
}
return $retflag;
}
sub subcheckleft {
$lc=0;$retflag=0;$c=$_[0];
while ($lc<$c) {
if ($distance[$lc]>$Height) {
$retflag=1;
}
$lc++;
}
return $retflag;
}
sub subcheckright {
$retflag=0;$c=$_[0];
while ($c<$Tiles-1) {
if ($distance[$c]>$Height) {
$retflag=1;
}
$c++;
}
return $retflag;
}
$loop_count=$move=0;
if (dominochecker==0) { ## if already in Domino Effect
print "\n $move \n";
exit;
}
sub RigidMode{
$loopend=$_[0];
$loop_count_local=0;
while ($loop_count_local<$loopend) {
if ($distance[$loop_count_local]<=$Height) {
$loop_count_local++;
} else {
if ($distance[$loop_count_local-1]<$Height && $loop_count_local+1 !=1 && defined($distance[$loop_count_local-1]) ) {
$move++;
$available=$Height-$distance[$loop_count_local-1];
$required=$distance[$loop_count_local]-$Height;
if($available<=$required) {
$distance[$loop_count_local-1]=$distance[$loop_count_local-1]+$available;
$distance[$loop_count_local]=$distance[$loop_count_local]-$available;
}else{
$distance[$loop_count_local-1]=$distance[$loop_count_local-1]+$required;
$distance[$loop_count_local]=$distance[$loop_count_local]-$required;
}
$loop_count_local=0;
}elsif($distance[$loop_count_local+1]<$Height && $loop_count_local+2 !=$Tiles && defined($distance[$loop_count_local+1]) ){
$available=$Height-$distance[$loop_count_local+1];
$required=$distance[$loop_count_local]-$Height;
if($available<=$required) {
$distance[$loop_count_local+1]=$distance[$loop_count_local+1]+$available;
$distance[$loop_count_local]=$distance[$loop_count_local]-$available;
}else{
$distance[$loop_count_local+1]=$distance[$loop_count_local+1]+$required;
$distance[$loop_count_local]=$distance[$loop_count_local]-$required;
}
$move++;
$loop_count_local=0;
}
else{
$loop_count_local++;
}
}
}
}
RigidMode($Tiles-1);
if (dominochecker==0) {
print "\n $move \n";
exit;
}else{
$loop_count=$move=0;
for $i (2...$#ARGV){
$distance[$loop_count]=$ARGV[$i];
$loop_count++;
}
$loop_count=$move=0;
while ($loop_count<$Tiles-1) {
if ($distance[$loop_count]<$Height) {
$available=$Height-$distance[$loop_count];
if (subcheckleft($loop_count)>0){
$move++ if $distance[$loop_count-1]-$available>0;
$distance[$loop_count]=$Height if $distance[$loop_count-1]-$available>0 ;
$distance[$loop_count-1]=$distance[$loop_count-1]-$available if $distance[$loop_count-1]-$available>0;
RigidMode($loop_count+1);
$loop_count=0 if $distance[$loop_count-1]-$available>0;
$loop_count++ if $distance[$loop_count-1]-$available<=0;
}elsif(subcheckright($loop_count)>0) {
$move++ if $distance[$loop_count+1]-$available>0;
$distance[$loop_count]=$Height if $distance[$loop_count+1]-$available>0;
$distance[$loop_count+1]=$distance[$loop_count+1]-$available if $distance[$loop_count+1]-$available>0;
RigidMode($loop_count+1);
$loop_count=0 if $distance[$loop_count+1]-$available>0;
$loop_count++ if $distance[$loop_count+1]-$available<=0;
}else{
$loop_count++;
}
}else{
$loop_count++;
}
}
}
if (dominochecker==0) {
print "\n $move \n";
exit;
}
else{
print "\n -1 \n";
exit;
}
```
] |
[Question]
[
# Input
[A CSV file](http://freetexthost.com/feytmnomjh), read from standard input, containing the 2011 college football scores with the 4 columns: Winner, Winner Score, Loser, Loser Score. For example,
```
Cincinnati,35,Connecticut,27
Pittsburgh,33,Syracuse,20
Baylor,48,Texas,24
```
This file was generated by a script I have that screen-scrapes [rivals.yahoo.com](http://rivals.yahoo.com/ncaa/football/scoreboard?w=14&c=all&y=2011). Teams that played fewer than 3 games were omitted.
# Output
Print to standard output a newline-separated ranking of teams, ordered from "best" to "worst".
It is permitted to output a "truncated" ranking (e.g., Top 25 or Top 50), but this is discouraged.
# Scoring
The ranking produced by your program will be scored on its ability to predict the winners of [bowl games](http://www.collegefootballpoll.com/bowl_games_bowl_schedule.html).
A victory for Team A over Team B is considered "predicted" by your ranking if either:
* You ranked Team A higher than (i.e., earlier in the output than) Team B.
* You ranked (i.e., listed anywhere in the output) Team A but not Team B.
You get 1 point for each bowl game "predicted" by your ranking.
Highest score gets the accepted answer. In case of a tie, the earliest submission wins.
# Rules
* Deadline for entries is **Friday, December 16**, at 17:00 CST (23:00 UTC).
* You may use the language of your choice.
* You may use third-party open-source math libraries such as [SciPy](http://www.scipy.org/).
* You may submit multiple entries.
* The output must be a pure function of the input. (So if you need an arbitrary tiebreaker in your ranking, don't use `rand()`, use alphabetical order.)
# Scores: It's a tie!
(Based on results from [rivals.yahoo.com](http://rivals.yahoo.com/ncaa/football/scoreboard))
**dan04: 11 points**
* Auburn > Virginia
* Baylor > Washington
* Boise St. > Arizona St.
* Oklahoma > Iowa
* Oklahoma St. > Stanford
* Oregon > Wisconsin
* South Carolina > Nebraska
* Southern Miss > Nevada
* TCU > Louisiana Tech
* Texas > California
* Texas A&M > Northwestern
**AShelly: 11 points**
* Arkansas > Kansas St.
* Baylor > Washington
* Boise St. > Arizona St.
* Cincinnati > Vanderbilt
* Houston > Penn St.
* Michigan > Virginia Tech
* Oklahoma St. > Stanford
* Rutgers > Iowa St.
* South Carolina > Nebraska
* Southern Miss > Nevada
* TCU > Louisiana Tech
[Answer]
I'll give it a shot. Here's some ugly Ruby that bases its ranking on how well each team scored compared to the opponent's average points against. It weights scores based on the opponent's rank in the list, and iterates until it is stable.
```
class Team
attr_accessor :wins,:loss,:for,:agn,:rank,:old_rank
attr_reader :beat,:fell, :name
def initialize nm
@name = nm
@wins=0
@loss=0
@for = 0
@agn = 0
@beat = []
@fell = []
end
def win pts,opp,opts
@wins+=1
@for+=pts
@agn+=opts
@beat << [opp,pts,opts]
end
def lose pts,opp,opts
@loss+=1
@for+=pts
@agn+=opts
@fell << [opp,pts,opts]
end
def avgPtsFor
@for.to_f/(@wins+@loss)
end
def avgPtsAgn
@agn.to_f/(@wins+@loss)
end
def score teams
#most points for scoring above opponents average, scaled by opponent's rank.
x = @beat.inject(0){|sum,game|opp = teams[game[0]]
sum+(game[1]/opp.avgPtsAgn*(1-(opp.rank/teams.size)))/@beat.size
}
y = @fell.inject(0){|sum,game|opp = teams[game[0]];
sum+(game[1]/opp.avgPtsAgn*(opp.rank/teams.size))/@fell.size
}
(x+y)*(@wins/@loss.to_f)++(@rank/teams.size)/8
end
end
#read the file
teams = Hash.new
ARGF.each_line{|l|
result = l.split(',')
team = teams[result[0]]||Team.new(result[0])
team.win(result[1].to_i,result[2],result[3].to_i)
teams[result[0]]=team
team = teams[result[2]]||Team.new(result[2])
team.lose(result[3].to_i,result[0],result[1].to_i)
teams[result[2]]=team
}
#initial ranking by w/l,pts for, pts against
rankings = teams.map{|n,t|t}.sort_by{|t|[t.wins.to_f/t.loss,t.for,t.agn]}
rankings.each_with_index{|a,i|a.rank = (i+1.0)}
#loop
stable = false
loops = 0
while !stable and loops < 1000 do
stable = true
n = rankings.size.to_f
rankings = rankings.sort_by{|t|
t.score(teams)
}
rankings = rankings.each_with_index{|t,i|
t.old_rank = t.rank
t.rank = (i+1.0)
stable = false if (t.rank != t.old_rank)
}
loops+=1
end
i=0
puts rankings.reverse.map{|t|"#{i+=1}: "+t.name}
```
Here's the output:
```
1: Oklahoma St.
2: LSU
3: Boise St.
4: Houston
5: Stanford
6: Oregon
7: Alabama
8: Arkansas
9: Wisconsin
10: TCU
11: Michigan
12: Georgia
13: South Carolina
14: Arkansas St.
15: Southern Miss
16: Michigan St.
17: West Virginia
18: Baylor
19: USC
20: Georgia Tech
21: Clemson
22: Tulsa
23: BYU
24: Oklahoma
25: Kansas St.
26: Nebraska
27: Virginia Tech
28: Penn St.
29: Notre Dame
30: Cincinnati
31: Northern Illinois
32: LA Lafayette
33: San Diego St.
34: Toledo
35: Florida Intl.
36: Texas A&M
37: Louisiana Tech
38: Ohio
39: Florida St.
40: North Carolina
41: Nevada
42: Iowa
43: Temple
44: Washington
45: West. Kentucky
46: Rutgers
47: Air Force
48: Auburn
49: Wyoming
50: California
51: Texas
52: Ohio St.
53: W. Michigan
54: Virginia
55: Utah St.
56: Florida
57: Missouri
58: Northwestern
59: SMU
60: Vanderbilt
61: Mississippi St.
62: Pittsburgh
63: Ball St.
64: Louisville
65: Purdue
66: East Carolina
67: UCLA
68: Wake Forest
69: Marshall
70: North Texas
71: N.C. State
72: Arizona St.
73: Utah
74: South Florida
75: Hawaii
76: San Jose St.
77: Texas Tech
78: Illinois
79: Kent St.
80: UTEP
81: UCF
82: Tennessee
83: East. Michigan
84: Connecticut
85: Navy
86: Duke
87: Rice
88: New Mexico St.
89: LA Monroe
90: Washington St.
91: Bowling Green
92: Kentucky
93: Syracuse
94: Arizona
95: Fresno St.
96: Troy
97: Oregon St.
98: Army
99: Colorado
100: Iowa St.
101: UNLV
102: UAB
103: Buffalo
104: Middle Tenn. St.
105: Minnesota
106: Boston Coll.
107: Cent. Michigan
108: Colorado St.
109: Mississippi
110: Tulane
111: Florida Atlantic
112: Memphis
113: Idaho
114: Kansas
115: New Mexico
116: Indiana
117: Maryland
118: Akron
```
[Answer]
Here's an example program. It assigns each team a rating equal to the least-squares solution of `winner_rating - loser_rating = 1` across all games:
```
import sys
import csv
from scipy import linalg
def read_csv(input_file):
"""Return a list of (winner, loser) tuples from the CSV file."""
return [(row[0], row[2]) for row in csv.reader(input_file)]
def lstsq_ratings(data):
"""
data = a list of (team1, team2, margin) tuples.
Returns a dictionary of {team: rating}
"""
# Extract the team names from the data
teams = set()
for winner, loser in data:
teams.add(winner)
teams.add(loser)
teams = sorted(teams)
team_indices = dict(zip(teams, xrange(len(teams))))
# Construct the matrix equation for the teams
num_teams = len(teams)
lhs = []
rhs = []
for winner, loser in data:
rhs.append(1)
lhs_row = [0] * num_teams
lhs_row[team_indices[winner]] = 1
lhs_row[team_indices[loser]] = -1
lhs.append(lhs_row)
# Solve equation and return results
ratings = linalg.lstsq(lhs, rhs)[0]
return dict((team, rating) for team, rating in zip(teams, ratings))
if __name__ == '__main__':
ratings = lstsq_ratings(read_csv(sys.stdin))
output = sorted(ratings.items(), key=lambda x: (-x[1], x[0].lower()))
for team, rating in output:
print(team)
```
The output is:
```
Oklahoma St.
LSU
Alabama
Oklahoma
Stanford
Oregon
Baylor
Arkansas
South Carolina
Kansas St.
USC
Georgia
Wisconsin
Virginia Tech
Boise St.
Houston
Michigan
Nebraska
Texas
Texas A&M
Michigan St.
Missouri
Clemson
Penn St.
Auburn
TCU
Notre Dame
West Virginia
Southern Miss
Georgia Tech
Arkansas St.
North Carolina
Iowa
Tulsa
Washington
Cincinnati
California
Mississippi St.
Florida
Rutgers
Utah
BYU
UCLA
Florida St.
LA Lafayette
Northern Illinois
Ohio St.
Louisville
Texas Tech
San Diego St.
Vanderbilt
Arizona St.
Iowa St.
Tennessee
West. Kentucky
Virginia
Louisiana Tech
Illinois
Wyoming
Kentucky
Purdue
Toledo
Marshall
Pittsburgh
Arizona
N.C. State
Florida Intl.
Wake Forest
SMU
Northwestern
Ohio
Nevada
South Florida
Air Force
Utah St.
Oregon St.
Kansas
Syracuse
W. Michigan
North Texas
Temple
East Carolina
Ball St.
Washington St.
Kent St.
Colorado
Minnesota
Connecticut
Rice
Navy
Duke
East. Michigan
San Jose St.
Mississippi
UTEP
UCF
Hawaii
LA Monroe
Fresno St.
Bowling Green
New Mexico St.
Boston Coll.
Troy
UNLV
Army
UAB
Colorado St.
Cent. Michigan
Indiana
New Mexico
Middle Tenn. St.
Buffalo
Florida Atlantic
Maryland
Idaho
Memphis
Tulane
Akron
```
] |
[Question]
[
Create a Markov Chain generator, which generates (and outputs) an Order 4 text chain. It must be able to support all plain text formatting used on this question, so be sure to check for punctuation (parentheses count for example, but HTML doesn't need to be accounted for fortunately)! You could even use this question itself as input if you're so inclined. There must be a defined input variable (or something analogous to such, I am aware certain popular esoteric languages do not really have variables per se.)
Your generator also should start sentences with a capital letter, and end with ".", "!", or "?", according to how often those respective characters appear in the input text.
You must also include a way to change the amount of text which should be output, so the only two things that are really configurable are the amount to output and the input string. It should stick with an Order 4 chain, because those happen to be funniest when it all comes down to it really.
Oh and, if your generators happen to create something particularly funny, please feel free to include it in your post for the lulz.
The title of this question was generated using a Markov Chain.
[Answer]
## Perl, 108 chars
What, no answers? Here's a quick Perl solution:
```
$/=$,;$_=<>;push@$1,$2while/(?=(....)(.))/sg;print+($m)=/(....)/s;print while($m.=($_=$$m[rand@$m]))=~s/.//s
```
And this is what I got the first time I fed the question text through it:
>
> Create a defined. There must also inclined. There must be sure to be according a Markov Chain.
>
>
>
(The average output length should approximately match the input length, so such a short output is quite untypical. On the other hand, the output length is roughly exponentially distributed, so both very short and very long outputs are quite possible.)
] |
[Question]
[
You are dealt five cards from a single deck. Implement a strategy for [Jacks or Better Video Poker](http://en.wikipedia.org/wiki/Video_poker#Jacks_or_Better) that has an expected revenue of *at least* [99.46%](http://wizardofodds.com/jacksorbetter/simple.html). Output the cards you want to hold.
The shortest code wins.
You are not required to implement the suggested strategy. Optimum play is also acceptable.
**Input** is read from standard input, **output** is written to standard output. Cards are identified as pairs of number (2,...,9,T,J,Q,K,A) and suit (S,H,D,C - spades, hearts, diamonds, clubs): 3C - three of clubs, QH - queen of hearts.

Examples:
```
$ ./jacks |
3C JC 5C QC 3H |<< input
3C 3H |<< output
$ ./jacks |
3C 4C 5C 6C 7C |<< input
3C 4C 5C 6C 7C |<< output
```
[Answer]
I did it!!!
```
import java.io.*;
// 427 lines 200
public class Base {
static char suit (String tokens) { return tokens.charAt (1); }
public static char num (String tokens) { return tokens.charAt (0);}
public static void checkPair (String [] tokens)
{
for (int a = 0; a < 4; ++a)
for (int b = a+1; b < 5; ++b)
if (num (tokens [a]) == num (tokens [b]))
System.out.print (tokens [a] + " " + tokens [b]);
}
public static void checkThreeKind (String [] tokens)
{
for (int a = 0; a < 3; ++a)
if (num (tokens [a]) == num (tokens [a+1]))
for (int b = 2; b < 5; ++b)
if (num (tokens [a]) == num (tokens [b]))
System.out.print (tokens [a] + " " + tokens [a+1] + " " + tokens [b]);
}
static void checkTwoPair (String [] tokens)
{
for (int i = 0; i < 5; i++)
for (int j = 1; j < 5; j++)
//First Increment is pair 1 2, followed by 1 3, 1 4, and 1, 5 then 2 3, 2 4, 2 5, then 3 4, 3 5 then 4 5
if (num (tokens [i]) == num (tokens [j]))
for (int y = 0; y <= 4; y++)
for (int x = 1; x <= 4; x++)
if ((i != y) && (j != x) && (y != x) && (i != j))
if (num (tokens [y]) == num (tokens [x]))
if ((tokens [i] != tokens [j]) && (tokens [i] != tokens [y]) && (tokens [j] != tokens [y]) &&
(tokens [i] != tokens [x]) && (tokens [j] != tokens [x]) && (tokens [y] != tokens [x]))
eblock (tokens);
}
static void checkHighFlush (String [] tokens)
{
if (suit (tokens [0]) == suit (tokens [1]) &&
suit (tokens [0]) == suit (tokens [2]) &&
suit (tokens [0]) == suit (tokens [3]) &&
suit (tokens [0]) == suit (tokens [4]))
{
String outputString = "";
for (int i = 0; i < tokens.length; i++)
outputString += tokens [i] + " ";
System.out.println (outputString);
System.exit (0);
}
for (int i = 0; i <= 4; i++)
for (int j= 1; j<= 4; j++)
//First Increment is pair 1 2, followed by 1 3, 1 4, and 1, 5 then 2 3, 2 4, 2 5, then 3 4, 3 5 then 4 5
if (suit (tokens [i]) == suit (tokens [j]))
for (int y = 0; y <= 4; y++)
for (int x = 1; x <= 4; x++)
if ((i != y) && (j != x) && (y != x) && (i != j))
{
if (suit (tokens [i]) == suit (tokens [x]) &&
suit (tokens [i]) == suit (tokens [y]))
{
if ((tokens [i] != tokens [j]) && (tokens [i] != tokens [y]) && (tokens [j] != tokens [y]) &&
(tokens [i] != tokens [x]) && (tokens [j] != tokens [x]) && (tokens [y] != tokens [x]))
eblock (tokens);
}
}
}
static void checkFourKind (String [] tokens)
{
if (num (tokens [0]) == num (tokens [1]))
{
if (num (tokens [0]) == num (tokens [2]))
if (num (tokens [0]) == num (tokens [3]) || num (tokens [0]) == num (tokens [4]))
eblock (tokens);
if (num (tokens [0]) == num (tokens [3]))
if (num (tokens [0]) == num (tokens [4]))
eblock (tokens);
}
if (num (tokens [1]) == num (tokens [2]))
if (num (tokens [1]) == num (tokens [3]))
if (num (tokens [1]) == num (tokens [4]))
eblock (tokens);
}
static void checkStraight (String [] tokens)
{
int [] ints = new int [5];
for (int i = 0; i <= 4; i++)
{
switch (num (tokens [i])) {
case 'T': ints [i] = 10;
case 'J': ints [i] = 11;
case 'Q': ints [i] = 12;
case 'K': ints [i] = 13;
case 'A': ints [i] = 14;
default: ints [i] = num (tokens [i]) - '0';
}
}
for (int i = 0; i <= 3; i++)
for (int j= 1; j<= 4; j++)
//First Increment is pair 1 2, followed by 1 3, 1 4, and 1, 5 then 2 3, 2 4, 2 5, then 3 4, 3 5 then 4 5
if ((ints [i]+1) == ints [i+1])
for (int y = 0; y <= 4; y++)
for (int x = 1; x <= 4; x++)
if ((i != y) && (j != x) && (y != x) && (i != j))
{
if (ints[i] + 2 == ints[y] && ints[i] + 3 == ints [x])
{
if ((tokens [i] != tokens [j]) && (tokens [i] != tokens [y]) && (tokens [j] != tokens [y]) &&
(tokens [i] != tokens [x]) && (tokens [j] != tokens [x]) && (tokens [y] != tokens [x]))
{
for (int a : new int[] {i, j, y, x})
System.out.print (tokens [a] + " ");
System.out.println ();
System.exit (0);
}
}
java.util.Arrays.sort (ints);
if (( (ints [i]+1 == ints [j]) && (ints [i]+3 == ints [y]) && (ints [i]+4 == ints [x])))
{
for (int a : new int[] {i, j, y, x})
System.out.print (tokens [a] + " ");
System.out.println ();
System.exit (0);
}
}
}
static void checkHighCard (String [] tokens)
{
int [] ints = new int [5];
for (int i = 0; i <= 4; i++)
{
switch (num (tokens [i])) {
case 'T': ints [i] = 10;
case 'J': ints [i] = 11;
case 'Q': ints [i] = 12;
case 'K': ints [i] = 13;
case 'A': ints [i] = 14;
default: ints [i] = num (tokens [i]) - '0';
}
}
int marker = 0;
if (ints [0] > ints [1]) marker = 1;
if (ints [1] > ints [2]) marker = 2;
if (ints [2] > ints [3]) marker = 3;
if (ints [3] > ints [4]) marker = 4;
System.out.println (tokens [marker]);
}
static void eblock (String[] tokens)
{
for (int i = 0; i < 5; i++)
System.out.print (tokens [i] + " ");
System.out.println ();
System.exit (0);
}
static void checkFullHouse (String [] tokens)
{
String [] test = new String [5];
int counter = 0;
int sum = 0;
for (int i = 0; i <= 4; i++)
test [i] = tokens [i];
for (int i = 0; i <=4; i++)
{
for (int j = 1; j <= 4; j++)
{
if (num (test [i]) == num (tokens [j]))
counter++;
}
if (counter > 1)
sum++;
counter = 0;
}
if (sum == 5) eblock (tokens);
}
public static void main (String [] args) throws IOException
{
String inputString = new BufferedReader (new InputStreamReader (System.in)).readLine ();
String [] tokens = inputString.split (" ");
java.util.Arrays.sort (tokens);
checkFourKind (tokens);
checkHighFlush (tokens);
checkFullHouse (tokens);
checkStraight (tokens);
checkTwoPair (tokens);
checkThreeKind (tokens);
checkPair (tokens);
checkHighCard (tokens);
}
}
```
] |
[Question]
[
Imagine you are given an array/string containing \$5\$ letters of the English alphabet, with each letter having any value from **A** to **Z** (inclusive).
Every *day*, each letter will perform a job, which can affect itself or other letters in the array. The letter's job is determined by the letter itself.
Most letters are, due to unemployment rates, jobless. However, a key few still have unique tasks they can perform each day:
* \$A\$: Yells at the letter to its right, forcing that letter to change to the next letter in the alphabet. If there is no letter to its right, does nothing.
* \$Z\$: Yells at the letter to its left, forcing that letter to change to the previous letter in the alphabet. If there is no letter to its left, does nothing.
* \$L\$: This one's pushy. It rotates the array by 1 element to the left, wrapping around so the first element becomes the last.
The final letter is \$X\$, The CEO. If it shows up *at any point*, that means *everyone is in trouble*. However, if \$X\$ does not show up within 30 days (30th day included), that means everything is alright and the busy letters are safe.
A single day concludes once every letter has finished doing its job. A configuration like `AJLF` will evolve like this over the course of 3 days:
```
AJLF at start of Day 1
KLFA at start of Day 2
LFAL at start of Day 3
FAML at start of Day 4
```
**A couple of important things to remember**:
* Any letter that is not part of those mentioned earlier does nothing.
* The letters themselves overflow. If a letter increases past `Z`, it becomes `A`. Similarly, decreasing past `A` will turn the letter to `Z`.
* Letters on the left do their job first. For example, if you have `A Z`, after a day the result is `A A` since the `Z` gets yelled at before it does its job. Another example is that `A K` will be `L A` at the start of the next day, as the `K` turns into an `L` and then does its job.
* A letter that wraps around due to \$L\$ will not do anything until the day is over, but the letter may still be changed.
* \$X\$ can appear even in the middle of the day, so a configuration like `AWZ` is *not* safe.
*Your* job is, given an array containing an arbitrary configuration of \$5\$ letters, find out if the letters are safe (that is, \$X\$ does not show up before 30 days pass). This initial configuration corresponds to the start of day \$1\$.
# Input
An array containing \$5\$ valid letters. You may assume \$X\$ will never be part of this initial array. If it makes things easier, you are allowed to treat the letters as case insensitive, and you may use any representation for those letters you want, as long as it is consistent and it does not affect your results.
# Output
Whether or not the busy letters are safe after 30 days. If they are, output `true` (or any equivalent value that indicates it). If they are not safe, output the day at which \$X\$ appeared.
## Rules
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest number of bytes wins.
## Test Cases
```
Input Safe?
------------------
RABOA No: Day 15
HAWPE No: Day 1
ZHLFF Safe
EALZJ Safe
KWLFZ No: Day 30
AZVLB No: Day 2
LLLEA No: Day 12
LADZV Safe
```
[Answer]
# [Perl 5](https://www.perl.org/) `-pa`, 148 bytes
```
for$;(1..30){map{$_&&$F[$_]==26?--$F[$_-1]:$_<4&&$F[$_]==1?++$F[$_+1]:$F[$_]-12||push@F,shift@F;$\||=$;if grep/24/,@F}0..4;@F=map$_%26,@F[-5..-1]}}{
```
[Try it online!](https://tio.run/##RY69DoIwAIRfhcRKNKWFVspgJTB18wnQNCTyl6htCk7QV7fyM5jccHffcKcr82Rul4v0VeoRJTFU5mFDHDauVgbwA8H4FB3HhQLp@0AUQN7TlCYZQmtA5H4G8hL/GckgXD1c0FoiQqdJf/o2F0HfdvWQCw5u05QC3tVeYyod0jgMcmEjjGO@3QFyT5O5KxDDeJ6xdnSOUG8T88hX6aFT796hK8MRiRzS5Q8 "Perl 5 – Try It Online")
Input as integers (A=1, B=2, etc.). Output is the day of the CEO's arrival or Perl's `undef` which appears as blank.
[Answer]
# [Python 3](https://docs.python.org/3/), 156 bytes
An incredible 13-bytes reduction [by @JonathanAllan](https://codegolf.stackexchange.com/questions/269616/busy-letters-evil-ceos/269627?noredirect=1#comment585237_269627):
```
def g(x):
for m in range(150):
if 23in x:return m//5+1
K=m%5and K;i=m%5-K;c=x[i];j=c==11;x=x[j:]+x[:j];K+=j;C=(c<1<4>i)-(c>24>0<i);x[C+i]=(x[C+i]+C)%26
```
[Try it online!](https://tio.run/##ZZFfb4IwFMXf/RT3ZbEEnYLiA1gTdBozmm3ZgyYQsrBSXIn8CZaky7LPzgqyJWZP7fnd9p5z2/JTfBT5rGlilsAJSc0eQFJUkAHPoYryE0OGNW0p8ATMmaLSrpioqxyyycTSDVXxcHZnRXkMnsPb7dhzKJYBD50UU4wNw5FKpnaoy8BOQ8fTcepsMKJLYzlfcW2M6Mqcr6ZLrjky2Og8xOi66hvtzlw0CT5H2XscKe8TCooqRlQbL6w2KG2DylAb0OjCLoDhSwUCGL6662d3aINhja5g7x5fti3otb8nu53ST0XOerR1if94i7wj2fkKzaY9cP0DWStg9poQsu18/oD74B9um7hH/2r8PWgjyxEwWTIqWPxW1KKsRTtDl/@eC5ZdUPfeABEVdXT@PYMhUf/TFcqK5wL97zO6vaI1Pw "Python 3 – Try It Online")
A function that receives a list of integers \$0 \leq n \lt 26\$ of length 5, representing the letters from the alphabet. It returns `None` if the CEO does not appears, otherwise it returns the day it appeared.
This version removes nearly all if-statements from the previous implementation by taking advantage of the short-circuiting behavior of `and` and the relationship between `bool`s and `int`s. It also uses some dark magic regarding chained comparisons when calculating `C`.
Using if-statements inside a loop (or any indentation block) is expensive, since it requires a new-line and therefore including more indentation to match the outer block.
# [Python 3](https://docs.python.org/3/), 169 bytes (original version)
```
def g(x):
for m in range(150):
if m%5<1:K=0
if 23in x:return m//5+1
i=m%5-K;c=x[i]
if c==11:x=x[1:]+x[:1];K+=1
C=(c<1)*(i<4)-(c>24)*(i>0);x[i+C]=(x[i+C]+C)%26
```
[Try it online!](https://tio.run/##ZZFPa4NAEMXvfoq5hKw1adwk5mCyAZMmlCpt6SEBgxS7rqkQ/2BW2FL62e2u2oLktLzfvJ03wxRf/DPPZnUdsRjOSOi2BnFeQgpJBmWYnRnClqkoJDGkA2uFbZeYrZzOpEnYJeNVmUE6mVgGVhUifWN3SYk4JUFrpYRgbAtJsB0Y4mTjYOkaRNm3BNEV1u9QsprrY0TX07kSa1Nfyv/GNiCofY2tPpgu6phcwvQjCmXyGZ3yMkJUHy8sNTVVU4tA12h4ZVcg8C37AwzfnM2LM7QBW6MWPDrH150CnfYfvf1e6uc8Yx3aOZ7/1Efu0dv7Es3MDjj@wdtIMO2053m7JucfOA/@od/EOfpt8I9G5YSmpgYXI2CiYJSz6D2veFFxtUmzxX3CWXpFzQkAQsqr8PLnIRDLkzWFokwyjm77jPpfWjMFg9wEEtK31r8 "Python 3 – Try It Online")
**How does it work?**
The loop iterates \$150\$ times: \$30\$ days \$\times\$ \$5\$ letters.
Variable `K` contains the number of rotations happened in the current day, according to
>
> A letter that wraps around due to \$L\$
> will not do anything until the day is over, but the letter may still be changed.
>
>
>
The condition `if m%5<1:K=0` implements the "until the day is over" part.
We then check whether X is present in the array. If it is, `m//5 + 1` is returned. Since \$0 \leq m \lt 150\$, then \$0 \leq m/5 \lt 30\$, the current day (where the CEO appeared).
Variable `i` stores the index of the current letter (0-4) and variable `c` stores the current letter. Since whenever a rotation occurs, the current letter should be shifted back, a subtraction by `K` is made.
The condition `if c==11:` checks if the current letter is L. If it is, it rotates the array (`x=x[1:]+x[:1]`) and increments `K`.
The next line is a bit more complex. It evaluates two conditions: *i)* whether the current letter is A (`c<1`) and it's not the last letter (`i<4`); and *ii)* whether the current letter is Z (`c>24`) and it's not the first letter (`i>0`). Then, a subtraction is evaluated between *i)* and *ii)*:
* If *i)* is true (1) and *ii)* is false (0), `C` will be +1, implementing "Yells at the letter to its right, forcing that letter to change to the next letter in the alphabet"
* If *i)* is false (0) and *ii)* is true (1), `C` will be -1, implementing "Yells at the letter to its left, forcing that letter to change to the previous letter in the alphabet"
* Otherwise, if *i)* and *ii)* are equal, `C` will be 0, implementing "Any letter that is not part of those mentioned earlier does nothing"
The next statement changes the previous or the next element on the array (`i+C`) and forces it to the previous or the next letter on the alphabet, handling the overflow (`(x[...]+C)%26`).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 93 bytes
```
FS⊞υ⌕αιF³⁰«≔⁰θFLυ«≔§υκη§≔υ⊕κ⁺§υ⊕κ∧¬η‹⊕κ⁺Lυθ≧⁺⁼η¹¹θ§≔υ⊖κ⁻§υ⊖κ∧⁼η²⁵›κ⁰≧﹪²⁶υ¿∧¬ⅈ№υ²³I⊕ι»UMυ§υ⁺λθ
```
[Try it online!](https://tio.run/##dZFPa8MgGMbPzafw@AoO0pbt0lPIuhFIRtkuu0pio9Ro658xGP3smSbp1rDVk/j8fJ7H15pTU2sq@36vDYJCHb17c0aoFjBGO285eIKehGqAEiQw3iQDuE4x@koWmbWiVZASdArKYpBKploXruGBuCCZK1TDPqPbARPEIz5pV1KhasM6phxrIGI76S3c1AOQhWIv2gEP@5JZC/86/FSKPeOK4RU9jvmvouUOIkjQ9uSptMAJWi7x9Kq/NR/ZPKQSat5zDkw9f71X9@Ho2TDqmIEDQemNTpVuvNSBfyDID4DYI7i8@R2ic669cjFztcbxy8LfOcipdbNRiDHgnMSIXHcdDSbh0lXnYVJynNAmOfd9WZbbrL/7kN8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs nothing if the input is safe. Explanation:
```
FS⊞υ⌕αι
```
Convert the input from a string of letters to a list of integers.
```
F³⁰«
```
Check for `30` days.
```
≔⁰θ
```
Start with no `L`s on any given day.
```
FLυ«≔§υκη
```
Loop through the letters and their original indices.
```
§≔υ⊕κ⁺§υ⊕κ∧¬η‹⊕κ⁺Lυθ
```
Increment the next letter if this letter is an `A` and it is not currently the rightmost letter.
```
≧⁺⁼η¹¹θ
```
Keep track of any `L`s.
```
§≔υ⊖κ⁻§υ⊖κ∧⁼η²⁵›κ⁰
```
Increment the previous letter if this letter is a `Z` and is not the leftmost letter.
```
≧﹪²⁶υ
```
Overflow any increments from `Z` to `A` or decrements from `A` to `Z`.
```
¿∧¬ⅈ№υ²³I⊕ι
```
If this is the first appearance of `X` then output the day number.
```
»UMυ§υ⁺λθ
```
Actually rotate the letters as necessary.
[Answer]
# [Funge-98](https://esolangs.org/wiki/Funge-98), 200 bytes
```
"HTRF"4("RBUS"4(4k&'v00pfa*10p020p
>10g:[[email protected]](/cdn-cgi/l/email-protection)_1-10p4L20g10g5%`!3jJ21_20g1-20p
^:0w4L10g5%!!+'%:051C$4L4L4L4L
^ [:'\ w4L4L4L4L410g5%`-'%:051C$4L
^#_^#!-b:<>j#'p02+1g02p01+1g01
'-3jR11_'10g5/-.@
```
[Try it online!](https://tio.run/##TY4xC8IwEIX3rA6igyStGlGidzWiBimiICKdqk5KqkJbqCBZtPjra2oR5IZ39917x93i5PlIYzGfCfP@tkXhbA/hxpE9J1wd91blvctfACa59hEMeGCIj5AqNs6WQ4hQWCoDD1ILJ52LxTsPo3IWpVcryGXw3TE24M2Oggmu2zKoimhKT4o3zjT/IVkdEn9eot1Iu0zc1MLP3Bq3bwwwBc8AloqE18U4CxEj3irTIzFcFgVOKVCkKCmQDw)
Takes input as a list of 5 integers between 0 and 25. Outputs 0 if the letters are safe, and a number between 1 and 30 if they are not.
Contains non-printable characters, so here is a hex dump:
```
00000000: 2248 5452 4622 3428 2252 4255 5322 3428 "HTRF"4("RBUS"4(
00000010: 346b 2627 7630 3070 6661 2a31 3070 3032 4k&'v00pfa*10p02
00000020: 3070 0a3e 3130 673a 2133 6a40 2e30 5f31 0p.>10g:[[email protected]](/cdn-cgi/l/email-protection)_1
00000030: 2d31 3070 344c 3230 6731 3067 3525 6021 -10p4L20g10g5%`!
00000040: 336a 4a32 315f 3230 6731 2d32 3070 0a5e 3jJ21_20g1-20p.^
00000050: 3a30 7734 4c31 3067 3525 2121 2b27 1a25 :0w4L10g5%!!+'.%
00000060: 3a30 3531 4324 344c 344c 344c 344c 0a5e :051C$4L4L4L4L.^
00000070: 2020 5b3a 2719 5c20 7734 4c34 4c34 4c34 [:'.\ w4L4L4L4
00000080: 4c34 3130 6735 2560 2d27 1a25 3a30 3531 L410g5%`-'.%:051
00000090: 4324 344c 0a5e 235f 5e23 212d 623a 3c3e C$4L.^#_^#!-b:<>
000000a0: 6a23 1327 7030 322b 3167 3032 7030 312b j#.'p02+1g02p01+
000000b0: 3167 3031 0a27 172d 336a 5231 315f 271e 1g01.'.-3jR11_'.
000000c0: 3130 6735 2f2d 2e40 10g5/-.@
```
] |
[Question]
[
[Conway's Game of Life](https://conwaylife.com/wiki/Conway%27s_Game_of_Life) is a cellular automaton "played" on an infinite grid, filled with cells that are either alive or dead. Once given an initial state, the board evolves indefinitely according to the following rules:
* Any live cell with 2 or 3 living neighbours lives to the next state
* Any dead cell with exactly 3 living neighbours becomes a living cell
* Any other cell becomes a dead cell
---
# The Challenge
Given a state of the game, find the previous state.
## Rules
* All inputs are assumed to have a preceding state, that is, your code need not handle [Gardens of Eden](https://conwaylife.com/wiki/Garden%20of%20Eden).
* There will be multiple solutions, output any of them.
* You may take input in any reasonable format. [Standard I/O Rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply.
## Test cases
```
> input
: output
> [(2, 2)]
: [(1, 1), (2, 2), (3, 3)]
> [(2, 2), (2, 4), (3, 3), (3, 4), (4, 3)]
: [(1, 3), (2, 4), (3, 2), (3, 3), (3, 4)]
> [(2, 2), (2, 3), (2, 4)]
: [(1, 3), (2, 3), (3, 3)]
> [(2, 2), (2, 3), (2, 4), (3, 2), (3, 4), (4, 2), (4, 3), (4, 4)]
: [(1, 3), (2, 3), (3, 2), (3, 4), (4, 3), (5, 3)]
> [(3, 2), (3, 3), (3, 4), (4, 2), (4, 3), (5, 2), (5, 3), (5, 4)]
: [(2, 2), (2, 5), (3, 5), (4, 2), (4, 3), (5, 3), (5, 4)]
> [(2, 4), (2, 5), (4, 2), (4, 5), (5, 2), (5, 3), (5, 4)]
: [(2, 4), (2, 5), (3, 4), (3, 5), (4, 2), (4, 3), (4, 4), (5, 3)]
> [(1, 13), (1, 14), (1, 19), (1, 20), (2, 13), (2, 19), (3, 8), (3, 9), (3, 15), (3, 21), (3, 29), (3, 30), (4, 7), (4, 9), (4, 14), (4, 15), (4, 20), (4, 21), (4, 26), (4, 27), (4, 30), (5, 3), (5, 4), (5, 6), (5, 9), (5, 11), (5, 12), (5, 15), (5, 17), (5, 18), (5, 21), (5, 23), (5, 24), (5, 27), (5, 29), (6, 3), (6, 5), (6, 6), (6, 8), (6, 11), (6, 12), (6, 14), (6, 17), (6, 18), (6, 20), (6, 23), (6, 24), (6, 26), (6, 29), (6, 30), (7, 8), (7, 9), (7, 14), (7, 15), (7, 20), (7, 21), (7, 26), (7, 27), (7, 31), (8, 4), (8, 5), (8, 7), (8, 10), (8, 11), (8, 13), (8, 16), (8, 17), (8, 19), (8, 22), (8, 23), (8, 25), (8, 28), (8, 29), (8, 32), (9, 4), (9, 6), (9, 7), (9, 10), (9, 12), (9, 13), (9, 16), (9, 18), (9, 19), (9, 22), (9, 24), (9, 25), (9, 28), (9, 30), (9, 31), (9, 32), (10, 8), (10, 9), (10, 14), (10, 15), (10, 20), (10, 21), (10, 26), (10, 27), (11, 5), (11, 6), (11, 9), (11, 11), (11, 12), (11, 15), (11, 17), (11, 18), (11, 21), (11, 23), (11, 24), (11, 27), (11, 29), (11, 30), (12, 5), (12, 6), (12, 8), (12, 11), (12, 12), (12, 14), (12, 17), (12, 18), (12, 20), (12, 23), (12, 24), (12, 26), (12, 29), (12, 30), (13, 8), (13, 9), (13, 14), (13, 15), (13, 20), (13, 21), (13, 26), (13, 27), (13, 33), (13, 34), (14, 3), (14, 4), (14, 5), (14, 7), (14, 10), (14, 11), (14, 13), (14, 16), (14, 17), (14, 19), (14, 22), (14, 23), (14, 25), (14, 28), (14, 29), (14, 31), (14, 34), (15, 1), (15, 4), (15, 6), (15, 7), (15, 10), (15, 12), (15, 13), (15, 16), (15, 18), (15, 19), (15, 22), (15, 24), (15, 25), (15, 28), (15, 30), (15, 31), (15, 32), (16, 1), (16, 2), (16, 8), (16, 9), (16, 14), (16, 15), (16, 20), (16, 21), (16, 26), (16, 27), (17, 5), (17, 6), (17, 9), (17, 11), (17, 12), (17, 15), (17, 17), (17, 18), (17, 21), (17, 23), (17, 24), (17, 27), (17, 29), (17, 30), (18, 5), (18, 6), (18, 8), (18, 11), (18, 12), (18, 14), (18, 17), (18, 18), (18, 20), (18, 23), (18, 24), (18, 26), (18, 29), (18, 30), (19, 8), (19, 9), (19, 14), (19, 15), (19, 20), (19, 21), (19, 26), (19, 27), (20, 3), (20, 4), (20, 5), (20, 7), (20, 10), (20, 11), (20, 13), (20, 16), (20, 17), (20, 19), (20, 22), (20, 23), (20, 25), (20, 28), (20, 29), (20, 31), (21, 3), (21, 6), (21, 7), (21, 10), (21, 12), (21, 13), (21, 16), (21, 18), (21, 19), (21, 22), (21, 24), (21, 25), (21, 28), (21, 30), (21, 31), (22, 4), (22, 8), (22, 9), (22, 14), (22, 15), (22, 20), (22, 21), (22, 26), (22, 27), (23, 5), (23, 6), (23, 9), (23, 11), (23, 12), (23, 15), (23, 17), (23, 18), (23, 21), (23, 23), (23, 24), (23, 27), (23, 29), (23, 30), (23, 32), (24, 6), (24, 8), (24, 11), (24, 12), (24, 14), (24, 17), (24, 18), (24, 20), (24, 23), (24, 24), (24, 26), (24, 29), (24, 31), (24, 32), (25, 5), (25, 8), (25, 9), (25, 14), (25, 15), (25, 20), (25, 21), (25, 26), (25, 28), (26, 5), (26, 6), (26, 14), (26, 20), (26, 26), (26, 27), (27, 16), (27, 22), (28, 15), (28, 16), (28, 21), (28, 22)]
: [(1, 13), (1, 14), (1, 19), (1, 20), (2, 13), (2, 19), (3, 8), (3, 9), (3, 15), (3, 21), (3, 29), (3, 30), (4, 7), (4, 9), (4, 14), (4, 15), (4, 20), (4, 21), (4, 26), (4, 27), (4, 30), (5, 3), (5, 4), (5, 6), (5, 9), (5, 11), (5, 12), (5, 15), (5, 17), (5, 18), (5, 21), (5, 23), (5, 24), (5, 27), (5, 29), (6, 3), (6, 5), (6, 6), (6, 8), (6, 11), (6, 12), (6, 14), (6, 17), (6, 18), (6, 20), (6, 23), (6, 24), (6, 26), (6, 29), (6, 30), (7, 8), (7, 9), (7, 14), (7, 15), (7, 20), (7, 21), (7, 26), (7, 27), (7, 31), (8, 4), (8, 5), (8, 7), (8, 10), (8, 11), (8, 13), (8, 16), (8, 17), (8, 19), (8, 22), (8, 23), (8, 25), (8, 28), (8, 29), (8, 32), (9, 4), (9, 6), (9, 7), (9, 10), (9, 12), (9, 13), (9, 16), (9, 18), (9, 19), (9, 22), (9, 24), (9, 25), (9, 28), (9, 30), (9, 31), (9, 32), (10, 8), (10, 9), (10, 14), (10, 15), (10, 20), (10, 21), (10, 26), (10, 27), (11, 5), (11, 6), (11, 9), (11, 11), (11, 12), (11, 15), (11, 17), (11, 18), (11, 21), (11, 23), (11, 24), (11, 27), (11, 29), (11, 30), (12, 5), (12, 6), (12, 8), (12, 11), (12, 12), (12, 14), (12, 17), (12, 18), (12, 20), (12, 23), (12, 24), (12, 26), (12, 29), (12, 30), (13, 8), (13, 9), (13, 14), (13, 15), (13, 20), (13, 21), (13, 26), (13, 27), (13, 33), (13, 34), (14, 3), (14, 4), (14, 5), (14, 7), (14, 10), (14, 11), (14, 13), (14, 16), (14, 17), (14, 19), (14, 22), (14, 23), (14, 25), (14, 28), (14, 29), (14, 31), (14, 34), (15, 1), (15, 4), (15, 6), (15, 7), (15, 10), (15, 12), (15, 13), (15, 16), (15, 18), (15, 19), (15, 22), (15, 24), (15, 25), (15, 28), (15, 30), (15, 31), (15, 32), (16, 1), (16, 2), (16, 8), (16, 9), (16, 14), (16, 15), (16, 20), (16, 21), (16, 26), (16, 27), (17, 5), (17, 6), (17, 9), (17, 11), (17, 12), (17, 15), (17, 17), (17, 18), (17, 21), (17, 23), (17, 24), (17, 27), (17, 29), (17, 30), (18, 5), (18, 6), (18, 8), (18, 11), (18, 12), (18, 14), (18, 17), (18, 18), (18, 20), (18, 23), (18, 24), (18, 26), (18, 29), (18, 30), (19, 8), (19, 9), (19, 14), (19, 15), (19, 20), (19, 21), (19, 26), (19, 27), (20, 3), (20, 4), (20, 5), (20, 7), (20, 10), (20, 11), (20, 13), (20, 16), (20, 17), (20, 19), (20, 22), (20, 23), (20, 25), (20, 28), (20, 29), (20, 31), (21, 3), (21, 6), (21, 7), (21, 10), (21, 12), (21, 13), (21, 16), (21, 18), (21, 19), (21, 22), (21, 24), (21, 25), (21, 28), (21, 30), (21, 31), (22, 4), (22, 8), (22, 9), (22, 14), (22, 15), (22, 20), (22, 21), (22, 26), (22, 27), (23, 5), (23, 6), (23, 9), (23, 11), (23, 12), (23, 15), (23, 17), (23, 18), (23, 21), (23, 23), (23, 24), (23, 27), (23, 29), (23, 30), (23, 32), (24, 6), (24, 8), (24, 11), (24, 12), (24, 14), (24, 17), (24, 18), (24, 20), (24, 23), (24, 24), (24, 26), (24, 29), (24, 31), (24, 32), (25, 5), (25, 8), (25, 9), (25, 14), (25, 15), (25, 20), (25, 21), (25, 26), (25, 28), (26, 5), (26, 6), (26, 14), (26, 20), (26, 26), (26, 27), (27, 16), (27, 22), (28, 15), (28, 16), (28, 21), (28, 22)]
```
*Visualize test cases (possible output followed by input)*



[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 232 bytes
```
f=(x,u=[],i=0,j=0,...L)=>u.find(g=([x,y])=>(t[[k%3+x-1,(k/3|0)%3+y-1]]+=[k%9==4],++k%9?t[[x,y]].length%5-3:g(v)),k=t=[])||Object.keys(t).filter(i=>t[i][22]&&!t[i][28]).sort()!=x.sort()+''?f(x,...L,u,i+1,j,u,i,j+1,[...u,[i,j]],i,j):u
```
[Nothing to Try it online!](https://tio.run/##dY9dboMwDMffe4r1oW2imIyPIW2V3F5g0g4Q5YGVQAOITpBUIHF35nR73CzZ@flvR7ab4l6Ml8F@uai/lWZdK2QTeFQaLMbQkEsp3zmevKxsX7IamZpg1qQwp1S7y8QUJcDa52yJOWVzlGgtkCpviC8ahCA6U2v4pWVn@tpdd3mUHWt25xxadDSNL8vHZ2MuTrZmHpnjNK1zZmAWT05ZrdJU7/fbH3zVXI63wTG@xemXxOFwrmj1sC14sCKBJrzQEClSPShKtA4SP/p1jZ/IcvIkUBIoDZTmG9@Xhq41ZVV0o3kEN0TZX/oj/Ftwgzebbw "JavaScript (Node.js) – Try It Online")
```
f=(x,u=[],i=0,j=0,...L)=> // Init case
u.find(g=v=>( // [i,j] exist?
t[[k%3+v[0]-1,(k/3|0)%3+v[1]-1]]+=[k%9==4], // neighbors +=5('false'), self +=4('true')
++k%9?t[[x,y]].length%5-3:g(v) // Repeat 9 times then return if dup
),k=t=[])||
Object.keys(t).filter( // 0 5 10 15 20 25 28
i=>t[i][22]&&!t[i][28] // undefinedfalsefalsefalsetrue
// falsefalsetrue | falsefalsefalse | falsefalsefalsetrue
).sort()!=x.sort()+''?
f(x,...L,u,i+1,j,u,i,j+1,[...u,[i,j]],i,j) // Try next, push with next [i,j] and version with [i,j] pushed
:u
```
] |
[Question]
[
A jigsaw puzzle consists of (usually rectangular-ish) pieces. On each side of a piece, there is either an edge or a *connector* (a term I made up). A connector is either a tab sticking out (outie) or a slot facing inwards (innie). Two pieces can be joined if the outie tab can fit into the innie slot. The goal is to assemble all the pieces into a single unit.
To turn it into a computational problem, we'll assume that the jigsaw puzzle is a perfect rectangular grid of pieces, and instead of having innies and outies, we'll use corresponding positive integers, which I'll call "connector IDs". In other words, two pieces can put next to each other if they have the same number on their adjacent side.
## The challenge
As input, take in a series of lines of 5 positive integers. The first number indicates the ID of the piece; the next four represent the nature of the pieces' top, right, bottom, and left sides respectively. One symbol of your choice should be reserved to represent an edge.
* The piece IDs will always start at 0 or 1 (your choice) and increase by 1 for each successive line; in other words, the piece ID is equal to the line number. If you want, you can omit the piece ID from the input format (so there are only 4 integers per line).
* You can assume the set of connector IDs will either be \$\{0,1,\ldots,m-1\}\$ or \$\{1,2,\ldots,m\}\$ for some positive integer \$m\$ -- your choice.
Output, in some reasonable format, a grid of piece IDs such that every adjacent piece in a column/row has the same number on their neighboring side and all the side corresponding to edges are on the edge of the grid. There is no rotation allowed. (If there are multiple solutions, you can output any valid solution.)
## Example
In this illustration, I will represent each piece as the following:
```
/.1.\
0 0 2
\.3./
```
Where the number in the center is the piece ID and the numbers on the edges are the identifiers for the type of edge/connector. In this example, I'll use `0` to indicate an edge side.
Suppose we had the 3 by 3 jigsaw puzzle
```
/.0.\ /.0.\ /.0.\
0 1 2 2 7 3 3 4 0
\.3./ \.1./ \.5./
/.3.\ /.1.\ /.5.\
0 2 1 1 8 6 6 5 0
\.4./ \.4./ \.5./
/.4.\ /.4.\ /.5.\
0 3 2 2 9 3 3 6 0
\.0./ \.0./ \.0./
```
(Note that the same connector ID can appear on multiple neighboring sides.) This could be represented as the input
```
1 0 2 3 0
2 3 1 4 0
3 4 2 0 0
4 0 0 5 3
5 5 0 5 6
6 5 0 0 3
7 0 3 1 2
8 1 6 4 1
9 4 3 0 2
```
We would then expect an output like
```
1 7 4
2 8 5
3 9 6
```
Standard loopholes are forbidden. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest program wins.
[Answer]
# Python3, 210 bytes:
```
def f(m,c=[]):
if(C:=len(c))==9:yield[c[i:i+3]for i in range(0,9,3)];return
for i in{*m}-{*c}:
t=[]
if C%3>0:t+=[m[c[-1]][1]==m[i][3]]
if C>3:t+=[m[c[C-3]][2]==m[i][0]]
if all(t):yield from f(m,c+[i])
```
[Try it online!](https://tio.run/##PZDRbsIgFIbveYoTk0WodYGiTrvgjfd7AcZFreBIWtowlswYn7071dWbj59z/vMHTn9JX12Q2z4Ow8k6cLTNa6UNKwl4Rw@lamygNWNK7cqLt81J19qXfiGN6yJ48AFiFc6W8nyXS2beo00/MRCY2tesvS2vWX3DREgYjYd3cHiRe16mhdItJi6FMVoYpVrtjZZmMu3l03JYYlkXk4dPnqppaGKPt4GLXfv4wwJNbEgCFMxmMwEcCpDAyUgBK1QSWWCdk9VIWIMka@SoNmRzVxxrbyNxpiBb5AanBNkh5ZiJ2aSPPiQa7G@ijl5HXbFSZ23VU7zkR3ZfVZVnR1yH9q/ffeMTZc/9Od8kG@lHF2wOSfz3559hzpi5McaGPw)
[Answer]
# Python3, 866 bytes:
```
y=[[int(i)for i in l.split()]for l in x.split('\n')]
u=[]
w=lambda z:[p for p in y if p[1:3]==z and not any(p in s for s in u)]
k=False
o=True
d=lambda z,g:z.append(g)
d(u,w([0,0]))
def v(x,t):
for i in range(len(x[0])):
e=x[0][i]
if len(x)==1:
d(u,t+[e])
if c():return o
u.pop()
else:
if v(x[1:],t+[e]): return o
return k
def c():
a=u[-1];b=[]
if len(a)==1 and a[0][3:]==[0,0]:return o
if a[0][4]!=0:
d(b,w([0,a[0][4]]))
if b[-1]==[]:return k
for i in range(1,len(a)):
d(b,w([a[i-1][3],a[i][4]]))
if b[-1]==[]:return k
if a[-1][3] != 0:
d(b,w([a[-1][3],0]))
if b[-1]==[]:return k
return v(b,[])
c();m=0;f=[]
for r in u:
if m<len(r):[d(f[i],r[i][0])for i in range(m)];d(f,[r[-1][0]]);m+=1
else:[d(f[i+(m-len(r))],r[i][0])for i in range(len(r))]
for g in f:g.reverse()
print('\n'.join([' '.join([str(i)for i in g])for g in f]))
```
[Try It Online](https://tio.run/##hVNNl5owFF2bX5FxY3JkPEEc28Zm21/QXZoFlkCpEDgBHPXP2/cCWtuezmwel/dx380ltOf@R@OS60nN5/OYCrqmCRUEY0w3gBKIa8gLssFIX2hCXiAi2pJtQAJyHzDCzJp8hLiFqZh8gpggJ3Bfz0rr0vWs5HnjaUlLR6tV11Zlz7jBVIWp05RafHMLbsigtCGvqkrrfZbSi9QtxdYWW8@0zGmrY5kYpS40dRl1TQ/PMwv1LrR2CAegOqgvadVZ0qivfrAku5NGhbys0ra1LmMFJxkbolemRSQMhzeb0yM7RT2XZHYX7lNXWFZZx04a26A2swqxLg1gEBaKXKkYazMk7ZfaGo5vUP7OuPS2H7yjDaaGVdu0DKsWRMqpCzbD@cw0KunviQkdgkAkI7NUDfo5Nrs9enaTkKKE4E2K6hIJXoWzPWyH1lDcmCclcHXG9qMFUxqNCHr2uAAI7tOHf0yJo3EtfyBKdQlzOjFAWL5LGOSM/fRJUfEH0cQj3mSY0BGGNDgO9uxqJXY5GoNyfbgTMqyqP6Nez6XOWA7qIo8Sgf@vc9Xc7KAj0j5oEHCGXb1UMRk/2Di9ZPXzSMf/S3SrByUF5nNZrLw9Wt9ZuAGtx78E7//qZ1M6phf0hrreP/4@xcg9coAh1@sv)
[here(tio)](https://tio.run/##jZHdboQgEIWv5Skm6YUY7Ubq3Sb7JJQLW3EXi2DQzaZJ390OrH/t1qQhhmHmcL5x6D6HizXF6OythxMU5N3qEIy1sy240lS4qbazbggn/M4y6y/XutaSkLNTFcq5IKS2DhQoA0FCvWNyJBHud0HkBc0q8CQv8IpD2XXSVJTnWVgiIZG3nvMoScgu4pcxyxZrrcwH0pfGsQYsR/PgzpXgzTMTnAkUee22IHghAObCA5xlO/h/wz0ZKS9/w/MtvHP2Tct2M2k/VkT6C0eYy@nJ5wmZnodO@eSHAVcpE6kGCD@UaW8jzbWVrhzWK4h5Ql9lBhq/mvjQWGUoj@EL1niO@sFRlcAyIKlbcT9iFAZjb1Ni07ZIQl8PhD1XPVmEhqc20WMcvwE) is simple program to construct test cases
] |
[Question]
[
Given a list of N lists, each containing M positive integers, and a separate list of M positive integers (target values), return a list of N scalars (integers with a value of 0 or more) that correspond to each list in the lists of lists, such that when each value in a list is multiplied by it's scalar, and the values at each index of each list are added together to make one final summed list, the sum of the absolute difference between each value in the summed list and the target list is minimized. If there are multiple possible outputs of equal absolute difference for a given input, output any single answer.
The solution with the fastest algorithm (by running time complexity) wins.
**Examples:**
```
Input:
Lists: [[1,2], [2,1]]
Target: [9,9]
Output:
[3, 3]
---------- ---------- ----------
Input:
Lists: [[3,9,2,1], [7,1,2,3], [2,3,8,1]]
Target: [60, 70, 50, 60]
Output:
[6, 5, 4]
---------- ---------- ----------
Input:
Lists: [[9, 7, 8], [9, 4, 12]]
Target: [176, 68, 143]
Output:
[6, 8]
```
**Example of Answer Corectness Checking:**
```
Input:
Lists: [[9, 7, 8], [9, 4, 12]]
Target: [176, 68, 143]
Output:
[6, 8]
6 * [9, 7, 8] = [54, 42, 48]
8 * [9, 4, 12] = [72, 32, 96]
[54, 42, 48] + [72, 42, 96] = [126, 84, 144]
summed difference:
abs(176 - 126) + abs(68 - 84) + abs(143 - 144)
= 50 + 16 + 1
= 67
(minimize this number)
```
[Answer]
# [Python 3](https://docs.python.org/3/), Brute Force Solution
```
from itertools import product
import numpy as np
def abs_difference(totals, target):
distance = sum(abs(totals - target))
return distance
def best_combo(array, target):
# setup, using numpy arrays for optimization
array = np.array(array)
target = np.array(target)
low_difference = sum(target)
low_combo = None
n = len(array)
# figure a limiting scalar for each list
# aka, the scalar just before a scaled list gets further from the target
individual_limits = []
for row in array:
row_low_difference = sum(target)
i = 0
while True:
i += 1
totals = i * row
if abs_difference(totals, target) > row_low_difference:
break
individual_limits.append(i)
# create a range for each limiting scalars
# and create a generator function for all combinations of the value in these ranges
# aka combinations of scalars to be multiplied by each row
ranges = (range(i) for i in individual_limits)
combos = product(*ranges)
# iterate over these combos
# figure out which combination of the rows gets closest to the target
for combo in combos:
totals = sum(array * np.array(combo).reshape(n, 1))
difference = abs_difference(totals, target)
if difference < low_difference:
low_combo = combo
low_difference = difference
return low_combo
assert best_combo([[1, 2], [2, 1]], [9, 9]) == (3, 3)
assert best_combo([[3, 9, 2, 1], [7, 1, 2, 3], [2, 3, 8, 1]], [60, 70, 50, 60]) == (6, 5, 4)
assert best_combo([[9, 7, 8], [9, 4, 12]], [176, 68, 143]) == (6, 8)
```
[Answer]
# [Haskell](https://www.haskell.org/), O(product target)
```
import Data.List
import Data.Ord
instance Num a=>Num[a]where
(+)=zipWith(+)
(-)=zipWith(-)
(*)=zipWith(*)
fromInteger=repeat.fromInteger
abs=map abs
signum=map signum
closest target vectors=
minimumBy(comparing$sum.abs.(target-).sum.(vectors*).map fromInteger)$
sequence$map(enumFromTo 0.succ.maximum.zipWith div target)vectors
```
[Try it online!](https://tio.run/##TU/LTsMwELz7K3zIIQmOlVLRwsEcEEJCQnBB4hDl4LpLYlE/sJ3y@PmwoZGai3dm1rOz28v4AYfDOGrjXUj0XibJn3RMZCm8hD0h2sYkrQL6PBgqxS2WRrZfPQQgNL8oxK/2bzr1CJFXZ15NvDzzEvl7cObRJuggiAAeZOILiVC5i8JIP1VCo@7sYP75CRKiDi5CTDTJ0EGiR1DJhSgINdpqM5i7n1w542XQtsviYDgO4vnpd1XwSclnU1nwafIivsgwEz4HwGsz7OWAmQ/Yf3W0Rq9S6PieYvh8E93r47xLMY8djdRWeFwgZfO2zaZm25pd1WxTt02zZjfskq1a1mzZCtEaEb7sGrV2/AM "Haskell – Try It Online")
] |
Subsets and Splits