text
stringlengths 180
608k
|
---|
[Question]
[
*Inspired by [The Great API Easter Egg Hunt!](https://codegolf.stackexchange.com/questions/160577/the-great-api-easter-egg-hunt)*
# Summary
Your task is to search for a predetermined integer in the "Collatz space" (to be explained later) using the fewest step possible.
# Introduction
This challenge is based on the famous Collatz conjecture that hopefully everyone here at least heard of. Here is a recap taken from [Print the Super Collatz numbers](https://codegolf.stackexchange.com/questions/71000/print-the-super-collatz-numbers).
>
> The [Collatz
> Sequence](https://en.wikipedia.org/wiki/Collatz_conjecture) (also
> called the 3x + 1 problem) is where you start with any positive
> integer, for this example we will use 10, and apply this set of steps
> to it:
>
>
>
> ```
> if n is even:
> Divide it by 2
> if n is odd:
> Multiply it by 3 and add 1
> repeat until n = 1
>
> ```
>
>
The Collatz distance `C(m,n)` between the two numbers `m` and `n`, for the purpose of this challenge, is the distance between two numbers in the [Collatz graph](https://en.wikipedia.org/wiki/Collatz_conjecture#In_reverse)(Credits to @tsh for telling me about this concept), which is defined as follows: (using `21` and `13` as examples):
Write down the Collatz sequence for `m` (in this case, `21`):
```
21, 64, 32, 16, 8, 4, 2, 1
```
Write down the Collatz sequence for `n`(in this case, `13`):
```
13, 40, 20, 10, 5, 16, 8, 4, 2, 1
```
Now count how many numbers appear only in one of the sequences. This is defined as the Collatz distance between `m` and `n`. In this case, `8`, namely,
```
21, 64, 32, 13, 40, 20, 10, 5
```
So we have Collatz distance between `21` and `13` as `C(21,13)=8`.
`C(m,n)` have the following nice properties:
```
C(m,n)=C(n,m)
C(m,n)=0 iff. m=n
```
Hopefully the definition of `C(m,n)` is now clear. Let's start doing egg hunting in the Collatz space!
At the beginning of the game, a controller decides the position of an easter egg, which is expressed by its one-dimensional coordinate: An integer in the interval `[p,q]` (in other words, an integer between `p` and `q`, both ends inclusive).
The position of the egg remains constant throughout the game. We'll denote this coordinate as `r`.
You can now make an initial guess a0, and it will be recorded by the controller. This is your 0th round. If you are so lucky that you got it right at the first place (i.e. a0=r), the game ends, and your score is `0`(The lower the score, the better). Otherwise, you enter the 1st round and you make a new guess a1, this goes on until you got it right, i.e. an=r, and your score will be `n`.
For each round after the 0th, the controller gives you one of the following feedbacks so that you can make a better guess based on the information given. Lets assume you are currently at the `n`th round and hence your guess is an
* "You found it!" if an=r, in which case the game ends and you score `n`.
* "You are closer :)" if C(an,r)<C(an-1,r)
* "You are circling around the egg" if C(an,r)=C(an-1,r)
* "You are farther away :(" if C(an,r)>C(an-1,r)
To save some bytes, I will call the responses as "Right", "Closer", "Same", "Farther", in the order presented above.
Here is an example game with `p=1,q=15`.
* a0=10
* a1=11, response: "Closer"
* a2=13, response: "Farther"
* a3=4, response: "Farther"
* a4=3, response: "Closer"
* a5=5, response: "Same"
* a6=7, response: "Right"
Score: `6`.
# Challenge
Design a **deterministic** strategy to play the game for `p=51, q=562` with the best score.
Answers should describe the algorithms in detail. You can attach any code that helps to elucidate the algorithm. This is not codegolf so you are encouraged to write legible code.
Answers should include the worst score they may achieve for all possible cases of `r`, and the one with lowest worst score wins. In the case of tie, the algorithms that has a better average score for all possible `r`s (which should also be included in the answers) win. There are no further tie breakers and we may have multiple winners in the end.
# Specs
* To reiterate, `r` lies in the interval `[51,562]`.
* [Default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
# Bounty (Added after the first answer is posted)
I may personally offer a bounty to an answer where all the guesses are made within the range `[51,562]` while still having a reasonably low worst score.
[Answer]
# Ruby, 196
This was way harder that I initially thought. I had to handle a lot of obscure cases and ended up with a lot of ugly code. But is was a lot of fun! :)
## Strategy
Every Collatz Sequence ends up with a sequence of powers of 2 (ex: [16, 8, 4, 2, 1]). As soon as a power of 2 is encountered, we divide by 2 until we reach 1. Let's call the first power of 2 in a sequence *closest pow2* (as this is also the closest power of 2 to our number using Collatz Distance). For the given range (51-562), all the possible *closest pow2* numbers are: [16, 64, 128, 256, 512, 1024]
### Short version
The algorithm performs:
* a binary search to figure out the closest power of 2 to the current number
* a linear search to figure out every previous element in the sequence until the target number is discovered.
### Detailed version
Given a game with the target number `r`, the strategy is the following:
1. Use binary search to figure out the power of 2 that is closest to `r` in as few steps as possible.
2. If the closest power of 2 that was found is the solution, stop. Otherwise continue to 3.
3. Since the power of 2 that was found is the first power of 2 occurring in the sequence, if follows that that value was reached by doing a (\* 3 + 1) operation. (If it came after a /2 operation, then the previous number would also have been a power of 2). Compute the previous number in the sequence by doing the reverse operation (-1 and then /3)
4. If that number is the target, stop. Otherwise continue to 5.
5. Given the current number known from the sequence, it is needed to go back and discover the previous number in the sequence. It is not known whether the current number was arrived at by a (/2) or (\*3 +1) operation, so the algorithm tries them both and sees which one yields a number that is closer (as Collatz Distance) from the target.
6. If the newly discovered number is the right one, stop.
7. Using the newly discovered number, go back to step 5.
## The results
Running the algorithm for all the numbers in the 51-562 range takes around a second on a normal PC and the total score is 38665.
## The code
[Try it online!](https://tio.run/##lVhtb9s4Ev6uXzGNcVs7cbWx2xSHoLk26BZBgd120eRwHwLDYCTa5q1MuhQVx23y27vPkJQl5Vy398GWTA7n/ZkZ2lY3m2/frPxcKSvpaSnd0yTp0b@dKpTb0FK6hcnLJJczykxRCPelrwcJ0fUkdWJFuaF7K8uqcOU9Voky6@iMtH9fL1QhydlK@p9EkZJevWK6uHhjpfiL1CwcPaNRXA@c8J3KW6lf02u/8iuN6dS/HdJzOorUUudJ@OZPW9tprkrXXw7Ja50tmWW0YzlILVjbktXLdGtHd3bMcmn0tJB67hZMtEy/qFU/A1FmKu2@0v3dkDb3dMfab@jBy0lL9UVCv0yHt2eP@BzSOOiaJBeVLMtP3jVgfwl/ZS7Vck2n8NfK6FIO6bTMjJUIzNtClCW5hXCUCU0Hq0JsDkjQXCxBFg7kSs9BemrVfOFwNitMKS1eZsK6hbRkLBjiACIkNShXOCe1kzmtFXQDN1YpybysCxAmsImdqrRyShQwqO@EnUs3vRVFJQc@CG8s1G8vh1WvOXaehVC94YBwiqgi/F4bdv1MFN7bIZLCOTtFXuTS1qZHDbxmIQWJevTfCswEFWY@h9GgAK1wsM8gfHCThEtEEdM4aXIQEhUMtloU0w7LFV3rYSSacFb@/vHi4v2Hi9bZqCUeK6tuhWt5ZxdHK1QJZLEbSRRs1IZg85OnzJ2tb7vpqM7/6KVOFkOxNzYwxVHN6fbGRrREN3bA5iqrqZVdnFT9OiuCwEELPkR1vrXCwzqy8AbBNcW1T6Ed6TW5DjF@dfYvb8akI6OO/5bpYwVrEYPaz/6rR38Ipak0BQc2M7kMMPcLfc5@pl@Z9XhIMaOUzqdet9JNsSHt1Mym44a2QiU6eBsI/MlT6n3l58NBO/DJ1pW8xzshZj26VDpDfVuoklTpk22mbODFIJuhVEFlXod/lCyHpBzNEFGzDhD2XPx5WcglEEhLzueFuJV0I6UmYZFhgCXQfrNBseUcP3x@NErT1KefvIWhfa/XMxoNUB2fY92nHzbY0jTkIpMOWpbwSRXRlDZBPYtFg432np3eiOyvtbB5PxQYPjik58fHg6bS7iRErhZy5loyj1kgr7GY420ADg8PQ2qdN7YS1npf9QOeB10Mwl12Q87Ao756@XLmPbiCcxytRcmIzxZgxB5Tt4qrIb@PGaWmuil8evsCvNNVgaaleDz0A3ft3q4r7i@/UF@HGP0DfSt64P@2h2Pvz4HE5hx7/Wwb9p3WeMJYiII54eg@ayLud@wHqHcLzM7weyEhBaBgKAChwHs9G/30AD7g9uPYCzokdruh75cTYtMICi21R@9QJTb0NlRPusR4Ixmr2C7rHlfWiwCqR2zpIZvi9O@Ygkr016JoodpkWYUURTJ18V1WWZsdjv/58T/jpLflo9AV0CXAyppqvvAs1wuDlLJCz9EUdO6Lld/gs9O35x9@e//b@dW7S7D5dP7h4h3X28MT4P7k5XiSgOjdp0seFmSomdeHx2k6OpmkS7HCPKLvoRowpOlhADWcwZiG8QOAk1C@LBXn8@XV@acroIrNCaYnySPpdAb3e/kN49aMxErz9HNPQaEU9bCocvma7h7oIa20@pyWBoNej64QQQipXBhd2FKML7nK4ZgSZU7S9ejlkF6@GNJo/M8hjU/w62SEYj46Hr@YhELzo4q@VFz3TZFPayAwyJbijgEv19vVR1bWA9podz14RH295T9p1YjvEw19T/4B3n5C7NaAfWIbop8S6xtH6PVJPa7zWoqV14kHoridc5lpnHrUuJILzzg9DoSZAPOurHgJQB/zo0IEf48rPMCCsYxnAMEQnFmz9Enh1saDNNJGBR@bCaXSWWGMnWx5lriwFFANdRJ1xHFLh@11b8aoY2VWDzG7@iMEDbp1LcwSe4tksK1TFCG08dWrxldxu05StiCTccbq1MY6Ybc21iRxfgoyY1/5aaG7WXak7tQrCo3zLnXA1RXTBlifmR2xVJ8i/7PfvOMC52fZZrMF4NghS0NrpBY6hJZ3rh7grUQZwsDgw83lxEeBjJbx2M9BeH/f/l5X3QfOPe2zyZzvpnbDqX097gYBzH20ztjD@9mB7ruM4uN6f6JPkvqeGqew7WUtccbhslPf744T9Kdq5UwfPWrg/xnQ/J8Auw3bfP/xvUqH@hVvYd35PdyVDt7rCNiaboYbnR8Inzx5ckCVLjgiNY/wd0NbmaMYrHBzZPXDrHnFNORXedZvHXk4gIHfvv0N "Ruby – Try It Online")
```
require 'set'
# Utility methods
def collatz(n)
[].tap do |results|
crt = n
while true
results << crt
break if crt == 1
crt = crt.even? ? crt / 2 : crt * 3 + 1
end
end
end
def collatz_dist(m, n)
cm = collatz(m).reverse
cn = collatz(n).reverse
common_length = cm.zip(cn).count{ |x, y| x == y }
cm.size + cn.size - common_length * 2
end
GuessResult = Struct.new :response, :score
# Class that can "play" a game, responding
# :right, :closer, :farther or :same when
# presented with a guess
class Game
def initialize(target_value)
@r = target_value
@score = -1
@dist = nil
@won = false
end
attr_reader :score
def guess(n)
# just a logging decorator over the real method
result = internal_guess(n)
p [n, result] if LOGGING
result
end
private
def internal_guess(n)
raise 'Game already won!' if @won
@score += 1
dist = collatz_dist(n, @r)
if n == @r
@won = true
return GuessResult.new(:right, @score)
end
response = nil
if @dist
response = [:same, :closer, :farther][@dist <=> dist]
end
@dist = dist
GuessResult.new(response)
end
end
# Main solver code
def solve(game)
pow2, won = find_closest_power_of_2(game)
puts "Closest pow2: #{pow2}" if LOGGING
return pow2 if won
# Since this is the first power of 2 in the series, it follows that
# this element must have been arrived at by doing *3+1...
prev = (pow2 - 1) / 3
guess = game.guess(prev)
return prev if guess.response == :right
solve_backward(game, prev, 300)
end
def solve_backward(game, n, left)
return 0 if left == 0
puts "*** Arrived at ** #{n} **" if LOGGING
# try to see whether this point was reached by dividing by 2
double = n * 2
guess = game.guess(double)
return double if guess.response == :right
if guess.response == :farther && (n - 1) % 3 == 0
# try to see whether this point was reached by *3+1
third = (n-1) / 3
guess = game.guess(third)
return third if guess.response == :right
if guess.response == :closer
return solve_backward(game, third, left-1)
else
game.guess(n) # reset to n...
end
end
return solve_backward(game, double, left-1)
end
# Every Collatz Sequence ends with a sequence of powers of 2.
# Let's call the first occurring power of 2 in such a sequence
# POW2
#
# Let's iterate through the whole range and find the POW2_CANDIDATES
#
RANGE = [*51..562]
POWERS = Set.new([*0..15].map{ |n| 2 ** n })
POW2_CANDIDATES =
RANGE.map{ |n| collatz(n).find{ |x| POWERS.include? x} }.uniq.sort
# Turns out that the candidates are [16, 64, 128, 256, 512, 1024]
def find_closest_power_of_2(game)
min = old_guess = 0
max = new_guess = POW2_CANDIDATES.size - 1
guess = game.guess(POW2_CANDIDATES[old_guess])
return POW2_CANDIDATES[old_guess], true if guess.response == :right
guess = game.guess(POW2_CANDIDATES[new_guess])
return POW2_CANDIDATES[new_guess], true if guess.response == :right
pow2 = nil
while pow2.nil?
avg = (old_guess + new_guess) / 2.0
case guess.response
when :same
# at equal distance from the two ends
pow2 = POW2_CANDIDATES[avg.floor]
# still need to test if this is correct
guess = game.guess(pow2)
return pow2, guess.response == :right
when :closer
if old_guess < new_guess
min = avg.ceil
else
max = avg.floor
end
when :farther
if old_guess < new_guess
max = avg.floor
else
min = avg.ceil
end
end
old_guess = new_guess
new_guess = (min + max) / 2
new_guess = new_guess + 1 if new_guess == old_guess
# so we get next result relative to the closer one
# game.guess(POW2_CANDIDATES[old_guess]) if guess.response == :farther
guess = game.guess(POW2_CANDIDATES[new_guess])
if guess.response == :right
pow2 = POW2_CANDIDATES[new_guess]
break
end
if min == max
pow2 = POW2_CANDIDATES[min]
break
end
end
[pow2, guess.response == :right]
end
LOGGING = false
total_score = 0
51.upto(562) do |n|
game = Game.new(n)
result = solve(game)
raise "Incorrect result for #{n} !!!" unless result == n
total_score += game.score
end
puts "Total score: #{total_score}"
```
[Answer]
# worst score: 11, sum score: 3986
All the guesses are in range `[51,562]`.
My algorithm:
1. First time guess 512, and maintain a set of possible results `vals`, initially the set contains all numbers in range `[51,562]`.
2. At each step, do the following:
1. Find the value of next guess `guess` in range `[51,562]` such that, when the values in `vals` (excluding `guess` itself) is partitioned into 3 sets corresponding to the possible outcomes `Closer`, `Same`, and `Farther`, the maximum size of those 3 sets is minimum.
If there are multiple possible values of `guess` satisfy the above, choose the smallest.
2. Guess the value `guess`.
3. If the answer is "Right", done (exit the program).
4. Remove all values in the set `vals` such that they cannot possibly give that result.
My reference implementation written in C++ and Bash runs in about 7.6 seconds on my machine and give the worst score/sum score as described in the title.
Trying all possible first guess values will take about 1.5 hours on my machine. I may consider doing that.
] |
[Question]
[
Write a function or program that, when given a list of names, outputs or returns a list where duplicates of given names have a unique shortened version of their surname.
### Input:
A list of names, where a name is defined by a given name and a last name separated by a space. Names are non-empty strings containing only uppercase and lowercase letters. The list can be an array of strings, or the names separated by a constant non-alpha, non-space character, but the output must be in the same format as the input.
### Output:
A list of the inputted names in the same order and format as the input that have been modified by these rules:
* For unique given names, output just the given name
* For names that share the same given name:
+ As well as their given name, add the shortest unique version of their surname that that is not shared by another name, followed by a period. For instance:
`John Clancy, John Smith` becomes `John C.,John S.` and `James Brown, James Bratte` becomes `James Bro.,James Bra.`
+ If one surname is a subset of another, such as `Julian King,Julian Kingsley`, return the full surname of the smaller one without a period. The example would become `Julian King,Julian King.`
* Basically a period represents the regex `.+`, where *only* one name should match it.
* You may assume that no-one will share both the same given name and the same surname
* Names are case-sensitive
### Test Cases:
* `John Clancy,Julie Walker,John Walker,Julie Clancy` -> `John C.,Julie W.,John W.,Julie C.`
* `Julian King,Jack Johnson,Julian Kingsley` > `Julian King,Jack,Julian King.`
* `Jack Brown,Jack Black,Jack Blue` > `Jack Br.,Jack Bla.,Jack Blu.`
* `John Storm,Jon Snow,Johnny Storm` > `John,Jon,Johnny`
* `Jill DeSoma,Jill Desmond` > `Jill DeS.,Jill Des.`
* `XxXnO sCOppeXxX,XxXNO MERCYXxX` > `XxXnO,XxXNO`
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest byte count for each language wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~34 33 32~~ 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
;\ċÐf⁶t€⁶;€JṖḊ$$¦”.µ€ċ@ÐṂ€Ẏ$Ḣ€
```
A monadic link taking a list of lists of characters (i.e. a list of "strings") and returning the abbreviations in the same format and relative order.
**[Try it online!](https://tio.run/##y0rNyan8/9865kj34Qlpjxq3lTxqWgOkrIGU18Od0x7u6FJRObTsUcNcvUNbgWJHuh0OT3i4swnIfLirT@XhjkVA1v@HOxcDVegcbs8CUVwPd285uudwO1BGJQtkXMMcBV07BaBU5P//XvkZeQrOOYl5yZU6XqU5makK4Yk52alFOmAJGBssAVHFBeIk5il4Z@al63glJmcrgFQW5@fpIEkU56QCFYIknYryy/Mg6pxygCSMWZrKBbYhuCS/KBdoGZCVl18OtjWvEiLK5ZWZk6Pgkhqcn5uoA2UX5@bnpXBFVETk@SsUO/sXFKQC2TpA7Oev4Osa5BwJZAIA "Jelly – Try It Online")** (a full program test suite)
### How?
```
;\ċÐf⁶t€⁶;€JṖḊ$$¦”.µ€ċ@ÐṂ€Ẏ$Ḣ€ - Link: list of lists e.g. ["Sam Ng","Sam Li","Sue Ng"]
µ€ - monadically for €ach: e.g. "Sue Ng"
\ - cumulative reduce with:
; - concatenation ["S","Su","Sue","Sue ","Sue N","Sue Ng"]
⁶ - literal space character ' '
Ðf - filter keep if:
ċ - count (spaces) ["Sue ","Sue N","Sue Ng"]
⁶ - literal space character ' '
t€ - trim from €ach ["Sue","Sue N","Sue Ng"]
”. - literal period character '.'
¦ - sparse application...
;€ - ...of: concatenate €ach (with a period)
- ...only for these indexes:
$ - last two links as a monad:
J - range of length [1,2,3]
$ - last two links as a monad:
Ṗ - pop [1,2]
Ḋ - dequeue [2] (i.e. 2,3,...,length-1)
- ...i.e.: ["Sue","Sue N.","Sue Ng"]
- yielding: [["Sam","Sam N.","Sam Ng"],["Sam","Sam L.","Sam Li"],["Sue","Sue N.","Sue Ng"]]
$ - last two links as a monad:
Ẏ - tighten ["Sam","Sam N.","Sam Ng","Sam","Sam L.","Sam Li","Sue","Sue N.","Sue Ng"]
ÐṂ€ - filter keep minimals for €ach:
ċ@ - count (sw@ping args) [["Sam N.","Sam Ng"],["Sam L.","Sam Li"],["Sue","Sue N.","Sue Ng"]]
Ḣ€ - head €ach ["Sam N.","Sam L.","Sue"]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 130 bytes
```
def f(a):n=[[x[:i]+'.'*(' 'in x[:i]<x)for i in range(x.find(' '),len(x)+1)]for x in a];print[min(x,key=sum(n,[]).count)for x in n]
```
[Try it online!](https://tio.run/##ZY6xboMwEIb3PIXFgp0g1HbokDZLaJdULVIzNJVlVRaYxMKckQEFnp76EClDl9N/930n/fXQXiw8jGOuClJQybaw47znWy02YRyuaUhCDWQ6PPessI5o4g9OwlnRPi405OiwyCigPdvcM4FSj5IUT7XT0PJKexaVatg1XUUh4oLFme2gZX8uiBHzD2Z@J9aPW19HQ921lLExONgLkMRIyIYgCg6d0Yp8SVMqhyvCZZvg4mpjyItqKgt5sJqoBPKm4YxQZiXB98bC/DrDxqgBdRT2zl7hZu@Nn8vSKbSwwLG1rpra@Az2OheDYSarW5WjreT/Yqf@BClpkrSulc9e8PMjJe@vn8k3Hn4B "Python 2 – Try It Online")
First generates all the nicknames, as follows:
```
n == [
['John', 'John .', 'John C.', 'John Cl.', 'John Cla.', 'John Clan.', 'John Clanc.', 'John Clancy'],
['Julie', 'Julie .', 'Julie W.', 'Julie Wa.', 'Julie Wal.', 'Julie Walk.', 'Julie Walke.', 'Julie Walker'],
['John', 'John .', 'John W.', 'John Wa.', 'John Wal.', 'John Walk.', 'John Walke.', 'John Walker'],
['Julie', 'Julie .', 'Julie C.', 'Julie Cl.', 'Julie Cla.', 'Julie Clan.', 'Julie Clanc.', 'Julie Clancy'],
['Jill', 'Jill .', 'Jill D.', 'Jill De.', 'Jill Des.', 'Jill Desm.', 'Jill Desmo.', 'Jill Desmon.', 'Jill Desmond']
]
```
Then picks the first\* one from each list that is *least frequent* in `sum(n,[])`. This will always be the first unique nickname.
Note that `n` includes the erroneous nicknames `'John .'` etc., but they will never be picked.
(\*CPython 2.7’s `min` does so, anyway. This code [may not be portable](https://stackoverflow.com/a/6783101/257418)!)
[Answer]
# [Ruby](http://www.ruby-lang.org) ~~165 162 161~~ 160 bytes
Includes 1 trailing space if only the given name is returned, eg. `"John "`
```
->a,n=0,s=0{a.group_by{|i|i[n]}.values.flat_map{|i|j=i[0];k=j.index' ';i.size<2?j.size>n ?j[0,[n+1,k].max-(s>1?0:1)]+(n>k ??.:''):j:f[i,n+=1,i.count{|l|l[n]}]}}
```
[Try it online!](https://tio.run/##TY5Rb4IwFIXf9yv6Vo21gT3igES3F5fNZD7MhTWmanGFckuoTJn42xl1LPhyc84932lvUW6qJvY/m3HACfgOMb5z5nRf6DJfb6pzLWsZAbvQb65KYWis@GGd8dwGiS8jh01SP6ESduKEEZ5IauSPeLgPk6sIAIVJ5JAIRi5JGc34aTwwgRs6njtkowEEKQpD6mE89BIvjiSBke8SSbe6hMO5VrWyv7PLpclRHEV4rr8AzRSHbYUJnpdKCvTOVSoKa23Yu2vYsYzddQ@0Ww7oWcLeMnybIlszGrpKFxolbluWmxb6CP@lqWpnb0pxA9szlgddZNebWg362J0HVZf0tFQKPYqlzrhl/pzJNOx6ZnVawQKZ2SLPRatbrp2vC/Ty9Db7sAvGml8)
163 bytes if you don't want the trailing space
```
->a,n=0,s=0{a.group_by{|i|i[n]}.values.flat_map{|i|j=i[0];k=j.index' ';i.size<2?j.size>n ?j[0..[n,k-1].max-(s>1?0:1)]+(n>k ??.: ''):j:f[i,n+1,i.count{|l|l[n+1]}]}}
```
[Try it online!](https://tio.run/##TY5Bb4JAEIXv/RV7QyNsoEcskGh7sWlN6qE2241ZdbELyyxhpUqF305ZS4OXybz3vjeZotxWbRx8tk7IbAhcWwfuheFDocp8s60utagFAdrgbyZLrnEs2XGTsdwESSCIS6dpkGABe362kDUVWIsf/nAfJdclBBQlxMWYgJ06HsUZOzsjHXqR63tjOhlBmKIowj6yrLGf@DERNkw8W@CdKuF4qWUtSWfQhjZNm6OYEGuhvgDNJYNdZdnWopSCo3cmU14YacJBXcOepfSuP9C5DNCzgINh2C5FpqYV9JU@1JLftgw3K9QJ/ksz2c1BlPwGNm@sjqrIrj91O6hT/x5UfTLQQkr0yFcqY4b5UzpTsB@Y9XkNS6Tnyzzn3d5x3Xxdopent/mHMShtfwE)
] |
[Question]
[
*[related](https://codegolf.stackexchange.com/questions/61097/golf-me-an-oop)*
---
# What's assignable to what?
In this challenge you will be given two types, `A` and `B` and determine if `A` is assignable to `B`, `B` is assignable to `A`, or neither.
## The Type System
(I will use `t` to represent any type)
### Basic Types
Basic types are represented by a single capital letter, such as `X`. They are basically classes.
* `X` is assignable to `Y` if `Y` is either the same as, or a parent class of `X`.
### Intersection Types
Intersection types are represented by `intersect<X, Y>`, and can have any number of types between the `<`'s (e.g. `intersect<X, Y, Z, D, E>`).
* `t` is assignable to `intersect<X1, X2... Xn>` if `t` is assignable to all `X`.
* `intersect<X1, X2... Xn>` is assignable to `t` if any `X` is assignable to `t`.
### Union Types
Union types are represented by `union<X, Y>` and can have any number of types between the `<`'s (e.g. `union<X, Y, Z, D, E>`).
* `t` is assignable to `union<X1, X2... Xn>` if `t` is assignable to any `X`.
* `union<X1, X2... Xn>` is assignable to `t` if all `X` are assignable to `t`.
---
## Input
You will receive as input:
* The class hierarchy. You may choose the method of input for the class hierarchy. You can input a representation of a tree, or each type with a list of its parents, or anything else that accurately represents the class hierarchy.
* Two types (input is flexible, as long as the notation is consistent you may receive these types however you like).
---
## Output
You will output one of three consistent and distinct values, call them `X`, `Y`, and `Z`. Given two types `A` and `B`, output `X` if `A` is assignable to `B`, output `Y` if `B` is assignable to `A` and output `Z` otherwise (If `A` is assignable to `B` and `B` is assignable to `A`, you may output `X`, `Y`, both, or a fourth value).
---
## Test Cases
Format:
```
# of types
[type, parents...]
[type, parents...]
Type a
Type b
```
---
```
2
[A,B]
[B]
A
B
--
A is assignable to B
3
[A,B,C]
[B,C]
[C]
intersect<A,C>
A
--
A is assignable to intersect<A,C>
3
[A,B,C]
[B,C]
[C]
union<A,C>
A
--
A is assignable to union<A,C>
3
[A,B,C]
[B,C]
[C]
intersect<B,C>
A
--
A is assignable to intersect<B,C>
3
[A,B,C]
[X,Y,Z]
[T,U,V]
intersect<union<A,T,X>,intersect<A,B>,Y>
intersect<T,C,X>
--
intersect<T,C,X> and intersect<union<A,T,X>,intersect<A,B>,Y> are not assignable to each other
1
[A]
A
A
--
A is assignable to A
3
[A,B,C]
[X,Y,Z]
[T,U,V]
intersect<A,intersect<A,B>,Y>
intersect<T,C,X>
--
intersect<T,C,X> and intersect<A,intersect<A,B>,Y> are not assignable to each other
2
[A]
[B]
A
B
--
B and A are not assignable to each other
3
[A,B,C]
[X,Y,Z]
[T,U,V]
intersect<union<A,X>,intersect<A,B>,Y>
intersect<T,C,X>
--
intersect<T,C,X> and intersect<union<A,X>,intersect<A,B>,Y> are not assignable to each other
```
[Here is a link to a working ungolfed Java solution you can use for testing](https://tio.run/##7VhLb@M2EL7rVzA@7FKIV0h6jO2gSS4tuukWSIoeDB8omYnpyJRKUtmku/7t6fAhWQ9Kjt091kBiizOcN78Zak2eyacsp3y9fHp7Y5s8EwqtYTEqFEujKyHI62cm1STw06SH8AuRq1uSeyg9kvzMdwnhnAofRZHkaRIEeRGnLEFJSqREt4Rx9C0IEHwYV1Q8kISi@9ecom8ozrKUEo6AkT1yEqf0PsOGlqkVFeEEbe1OqYiqRF4TCb9BfUo3lCvppBlG/ckFeyaKIu3W1DBfopwIzTrpMCUrIhAnGzoJdjTrgNmKPVLGu11hTa/@qBWTkWNDs67aikdvBgaruaRsOzbUtT9S9YeVh9tqBVWF4A3tQ1KN@SDud9A@KKvXvJ@/PFMh2JK2Re9LaUsZe0DYEKA4IMk8odmDDXybs20a/bsgqcRO6vfvDeejJOMKKq@kNxOwRTSV1K/7V12jkibKp/8hE8g684IuEMY1ZqsngqBqOmTIt7/0@MTY2gjRS@@GmuMP4DGdeLm2wf6VMnyioO8PyJ@cZfw9wXCMBwXiyDh0PTgiDJ5gboP9fIccAlejX@I11AjKfMWvI4Bmsy5xOGHdQ6SF8CJN9VGA4N9oqISzfQKio93zgBZvPBqPFnhj83@GsDum2STwhc0C3MyyHwEk0CzQClrWTbbsxSgMTKEfQ7ftlnNbpIqZcqUvivJlp20YqNVrBmld8U7qwhpdqDr77U40rqnqaUpWi9Iqum2nEozbvN5mYyiQDidtTytp@zeA/f0CfxT4NxFkp9RXpLrGX5pQYWX2wcUgVGyPPfa@SjDA96OrwAj9vwLajfOYEujpmtshqPNWT7MGyly6WjBewPghKb5TgvFHkw8oA5JPb2DeIgkc6zFys5ypnKafphvAlggECiX/YmqFR6wEg5Gdcdr0QpfJqBMBM4pPqwp01aPnTfrVES9xayrSgMv4kr4A21kL07@uWEo13Gry1JqRUv4IJoR9uRrwZWwV9SbOWBvlhVxhbfAOEfVTdfnRLoShfw6wlp7OUE1rZTE6ReeeetgNQT1hPtBse4SPMNlqO9BcPdNfKZuiUDfej5cfB0cvY6xk/@jueonOh8YuU9uqhJgoz3Lc40QtDJQ@4focGJHlEqvwvXNbIyRH@T/u93@/3MEMe11zR1oveyzam/XzIxGqZlENqXxOuB19dp7VTdw2kM5iuwO654wt0QYuVw7n5gtExGMDytw7AiTdt8Md@4TvXqWim4jxmj4NPklWcF1kblfEYVCDo1/3q076zDit0waB1png3oE0wc80IYN@Bvnga2ptgZ@np11orcC9ZWvbIOcXxCfXSALc9t0MIIugZGODL2iewniKR3OAl9Eo3C0s9MICVmSeMoVHY4D5aENyF/aLC/jamJX7TIdJok@XSNayGanMKGzb5Mb4SecOUVZGeXn@jb5irOWF1oP52cKLfTG4Vq@q9h7vZdMvRifJvnfp4OYYDcvVn9KKvFA4NpeOMYrDwUtNlf010ocQvqZWg8NfWOkWwbsjtl70dou4elnRRo@OhANRyiZYFocFdL3ogah6UEGoCyv86uFvOubn6xvAa8lxB02SPces5It7@IJGFyP2rRxMaZKMqzFs0mSKd0xxnakxq5HmKBp3hzCLc1mhIpgVuUo56IRmPkJw5d/tRSqDpVNwoIO/paq4qYq8S1U8oIr0qjrpuIU@fEAn/8ECwpdOqX0UFPFMtayiJFnZK8Io9A3c2@Dt7adgfjW@XgRz@LsKrv8F) (it takes input in the same way as the test cases)
---
This is code-golf, so least bytes in each language wins for that language!
[Answer]
# [Python 3](https://docs.python.org/3/), 177 bytes
`c` is a dictionary of the parents of each type, `a` and `b` are the two expression to check. Types are represented by strings, while intersects and unions are represented by lists with of expressions, with the first element set to `0`for intersect and `1` for union
Returns `0` if they are not assignable to each other, `1` if `a` is assignable to `b`, `2` if `b` is assignable to `a` and `3` if both are assignable to each other
```
lambda c,a,b:y(a,b,c)+2*y(b,a,c)
y=lambda a,b,c:(b in c[a]or a==b if b[0]in c else[all,any][b[0]](y(a,x,c)for x in b[1:]))if a[0]in c else[any,all][a[0]](y(x,b,c)for x in a[1:])
```
[Try it online!](https://tio.run/##vZKxbsIwEIZ3nsLyZLc3hHaLlAF4hYAA18M5JSpSahBliIX67OmdTVJVDG2qqovj/P99d39OOYbzy8E/dnXx1DX46p5RVIDg8qDohErfP9wF5Uiq9CQU15Jo5cqJvReVQXs4CSwKeq2FM5llVeyat53BpgH0wRqWreKmLXWqCWgZdmaaW62Jw6@cD0CsNXjl2hhm4DBy3fG092dVq4ucydzIubRAR27sO5DCd60nN0UgF31hui0SYrJERW02Dp3@Hs3g0/0W7TmQa/Y25G3Z2yRxmx4le0vyVuwtk7ga5vVpS8lt7PDh89QpCWUcGwtuMvX7/Z@4PGp8xJF/wp8u9mdL7T4A)
[Answer]
## JavaScript (ES6), 138 bytes
```
(p,a,b,g=(a,b)=>a==b||(p[a]||a.i||a.u||[])[a.u?'every':'some'](t=>g(t,b))||(b.i||b.u||[])[b.i?'every':'some'](t=>g(a,t)))=>g(a,b)||+g(b,a)
```
`p` is the parent map, which is a JavaScript object whose keys are the types with parents and whose values are arrays of parent(s). For example, if there are two types `A` and `B` and `B` is the parent of `A` then `p` would be `{A:['B']}`.
Intersection types are represented in `a` and `b` as a JavaScript object with a key of `i` whose value is an array of types, while union types have a key of `u`. For example, the intersection of two types `A` and `B` would be `{i:['A','B']}`.
The return value is `true` if `a` is assignable to `b`, `1` if `a` is not assignable to `b` but `b` is assignable to `a`, or `0` if neither is assignable to each other.
[Answer]
# C++17, 595 bytes
```
#include<type_traits>
#define p(x)template<class...T>class x;
#define d(a,b)disjunction<s<a,b>...>{};
#define c(a,b)conjunction<s<a,b>...>{};
#define u(x)u<x...>
#define i(x)i<x...>
#define k struct s
#define e ...A
#define t(a,b)template<class a,class b>
using namespace std;p(i)p(u)t(B,D)k:disjunction<is_base_of<B,D>,is_same<B,D>>{};t(a,e)k<a,u(A)>:d(a,A)t(a,e)k<a,i(A)>:c(a,A)t(a,e)k<u(A),a>:c(A,a)t(a,e)k<i(A),a>:d(A,a)t(e,...B)k<i(A),i(B)>:d(A,i(B))t(e,...B)k<u(A),u(B)>:c(A,u(B))t(e,...B)k<i(A),u(B)>:d(A,u(B))t(e,...B)k<u(A),i(B)>:c(A,u(B))t(A,B)int f=s<A,B>::value?-1:s<B,A>::value?1:0;
```
[Try it online!](https://tio.run/##hZJRb8IgFIWf119B4kuJaOYrIkvrfoIuuheDlJo7K20EFjfjX5@Dqm01S/Yk5zvnXnKKsqoGGynP5x5oWbhMMftVqZXdC7CGR71M5aAVquIDtmpXFcIqJgthzHA4nPH6hA7jJpfFgqxxBubDaWmh1MwwT7hP8@Opzck6J0v9T875ex07BNww8Awe2BYZu3fSItMghXwiaaStb7zvgAS5/K555AzoDdJip0wlpPL7snEVA65ih22ckle8pd1eYFZrYdSqzJk3OfHa@OFahArhPoW3vpWLE8xp@DIJbinUVN7RkCQi0ISIhsKVZleqiC@W3gyIU3zxwqlr19tcbYeF7sGG1s7@sF27vDOdkBSDtiifGObPnNJPUTj1MhhR46snDRjR53Hzn0IMSv8@Sux4FKZ3AnSMj9HT9dHS8OQ3Me2KZVe8d8W8K966IqEpuVuyoEtyNzujc3IbySiVpbOIMZQz8KWgLkaWnDg2I1Oy4Hz8FJ2i84/MC7Ex54Efmsh@f/T9Cw "C++ (gcc) – Try It Online")
A variable template `f` that accepts as input some types and intersection `i<...>` or union `u<...>` of them and returns `-1` if `A` is assignable to `B` and `1` if `B` is assignable to `A` and `0` otherwise.
**Ungolfed:**
```
#include <type_traits>
using namespace std;
template<class...T>class Intersect;
template<class...T>class Union;
template<class A,class B>
struct is_assignable_to:
disjunction<is_base_of<A,B>,is_same<A,B>>{};
template<class a,class...A>
struct is_assignable_to<a,Union<A...>>:
disjunction<is_assignable_to<a,A>...>{};
template<class a,class...A>
struct is_assignable_to<a,Intersect<A...>>:
conjunction<is_assignable_to<a,A>...>{};
template<class a,class...A>
struct is_assignable_to<Union<A...>,a>:
conjunction<is_assignable_to<A,a>...>{};
template<class a,class...A>
struct is_assignable_to<Intersect<A...>,a>:
disjunction<is_assignable_to<A,a>...>{};
template<class...A,class...B>
struct is_assignable_to<Intersect<A...>,Intersect<B...>>:
disjunction<is_assignable_to<A,Intersect<B...>>...>{};
template<class...A,class...B>
struct is_assignable_to<Union<A...>,Union<B...>>:
conjunction<is_assignable_to<A,Union<B...>>...>{};
template<class...A,class...B>
struct is_assignable_to<Intersect<A...>,Union<B...>>:
disjunction<is_assignable_to<A,Union<B...>>...>{};
template<class...A,class...B>
struct is_assignable_to<Union<A...>,Intersect<B...>>:
conjunction<is_assignable_to<A,Intersect<B...>>...>{};
template <class A,class B>
int f = is_assignable_to<A,B>::value?-1:is_assignable_to<B,A>::value?1:0;
```
**Usage:**
```
#include <iostream>
int main(){
struct B{};
struct C{};
struct Y{};
struct Z{};
struct U{};
struct V{};
struct A:B,C{};
struct X:Y,Z{};
struct T:U,V{};
std::cout << f<Intersect<A,Intersect<A,B>,Y>,Union<T,C,X>>;
}
```
] |
[Question]
[
Fortress was a language being developed by the Sun Programming Language Research Group (R.I.P. Fortress) that had a unique property to it, it was possible to render ("Fortify") programs in different font-styles (i.e. blackboard bold, bold, italics, roman, etc. ). The goal is to represent a one-char Fortress variable in HTML markup.
Here's how the fortification of one-char variables worked (simplified/modified from documentation for code-golfing purposes):
* If the variable is a repeated capital (i.e. `ZZ`), it becomes formatted in blackboard bold (`ùî∏ùîπ‚ÑÇùîªùîºùîΩùîæ‚ÑçùïÄùïÅùïÇùïÉùïÑ‚ÑïùïÜ‚Ñô‚Ñö‚Ñùùïäùïãùïåùïçùïéùïèùïê‚ѧ`)
* If the variable is preceded by an underscore, the variable is rendered in roman font (left alone)
* If the variable is followed by an underscore, the variable is rendered in bold font (`<b>`v`</b>`)
* If the variable is neither preceded nor followed by an underscore, the variable is rendered in italic font (`<i>`v`</i>`)
* The codepoints of the blackboard bolds are: `ùî∏`:1D538, `ùîπ`:1D539, `‚ÑÇ`:2102, `ùîª`:1D53B, `ùîº`:1D53C, `ùîΩ`:1D53D, `ùîæ`:1D53E, `‚Ñç`:210D, `ùïÄ`:1D540, `ùïÅ`:1D541, `ùïÇ`:1D542, `ùïÉ`:1D543, `ùïÑ`:1D544, `‚Ñï`:2115, `ùïÜ`:1D546, `‚Ñô`:2119, `‚Ñö`:211A, `‚Ñù`:211D, `ùïä`:1D54A, `ùïã`:1D54B, `ùïå`:1D54C, `ùïç`:1D54D, `ùïé`:1D54E, `ùïè`:1D54F, `ùïê`:1D550, `‚ѧ`:2124. These count as **one byte each** in your program (if your language of choice can handle these characters at all)
Input will be either a repeated ASCII capital, or a single ASCII letter with either no underscore, a leading underscore, or a trailing underscore (AKA `_a_` will not be an input). This is code-golf so lowest byte count wins!
Test cases:
```
a => <i>a</i>
BB => ùîπ
c_ => <b>c</b>
_d => d
E => <i>E</i>
G_ => <b>G</b>
_H => H
ZZ => ℤ
```
Links: [Specification](http://www.ccs.neu.edu/home/samth/fortress-spec.pdf), [Direct download of version 0.1 alpha](http://web.archive.org/web/20070715233437/http://fortress.sunsource.net/files/documents/81/140/fortress_168.zip).
Reference implementation (This would be in Fortress, but Fortress doesn't like most of the doublestruck characters, so this implementation is in D):
```
dstring fortify(string arg) {
import std.string, std.conv;
alias D = to!dstring; //Convert to a string that accepts the unicode needed
dstring BB = "ùî∏ùîπ‚ÑÇùîªùîºùîΩùîæ‚ÑçùïÄùïÅùïÇùïÉùïÑ‚ÑïùïÜ‚Ñô‚Ñö‚Ñùùïäùïãùïåùïçùïéùïèùïê‚ѧ"d; //blackboard bold capitals
string UC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //normal ASCII capitals
if(arg.length == 1)
return D("<i>" ~ arg ~ "</i>");
if(arg[0] == a[1])
return D(BB[UC.indexOf(arg[0])]);
if(arg[0] == '_')
return D(arg[1]);
return D("<b>" ~ arg[0] ~ "</b>");
}
```
[Answer]
# Python 3.6, ~~159~~ ~~131~~ 128 bytes
*1 byte saved thanks to @Zachar√Ω*
*3 bytes saved thanks to @V–∞lueInk*
*28 bytes saved thanks to @Rod*
```
lambda s:len(s)<2and f"<i>{s}</i>"or s[0]==s[1]and"ùî∏ùîπ‚ÑÇùîªùîºùîΩùîæ‚ÑçùïÄùïÅùïÇùïÉùïÑ‚ÑïùïÜ‚Ñô‚Ñö‚Ñùùïäùïãùïåùïçùïéùïèùïê‚ѧ"[ord(s[0])-65]or[f"<b>{s[0]}</b>",s[1]][s[0]=='_']
```
[Try it online!](https://tio.run/##JY5LasMwFEXnXcVDE9ng0B/tINgeBEK7B1UYu46pIZWDlYFLKfQjOuh/UA8a8CyLSGnTxWgF2YF7RQTnPnQfQmd2Nb@o1GFfUERn/TS9zPKU9HA6UZ72w4NU5VSwsIyv9U24W8asqkmLPRlFWuxLbNmm@1yBb2vuMX7AL1iDP2teN117C@4A1u0DMNa0GI/WfFmzsKbD5Qk8gxfg3ryBd/BhzZKJqs4996k/OD6SVS0glEEIDZyymAXORYqtF0@47AtoNlQqEjzlAfHRyOV54jLJXY5dnGyLUx7I4Q7hzOpSzb0GZRRjVXiN7/f/)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~104~~ ~~106~~ 105+1 = ~~105~~ ~~107~~ 106 "bytes"
Probably works even better in Retina. Uses `-p` flag.
-1 byte from Zachar√Ω.
```
gsub /^.$/,'<i>\0</i>'
gsub(/(.)\1/){$1.tr"A-Z","ùî∏ùîπ‚ÑÇùîª-ùîæ‚ÑçùïÄ-ùïÑ‚ÑïùïÜ‚Ñô‚Ñö‚Ñùùïä-ùïê‚ѧ"}
gsub /(.)_/,'<b>\1</b>'
gsub ?_,''
```
[Try it online!](https://tio.run/##KypNqvz/P724NElBP05PRV9H3SbTLsbARj/TTp0LJKyhr6GnGWOor1mtYqhXUqTkqBulpKP0Ye6UHUC881FLE5DarQsk9j1q6f0wd2oDkD215VHLVCDV9qhl5qOWWY9a5gI5XSCJCY9alijVckHsAxocD7IwyS7G0EY/CWqhgn28jrr6//@JXE5OXMnxXPEpXK5c7kDagys8/F9@QUlmfl7xf90CAA "Ruby – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 73 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Turns out that not being able to use the BBB letters in the code is quite expensive.
```
5ŀ”i
“Ðñṡ’Dẋ@€“¡ḞḄ’ż“¿¿Æ€¢¬µ‘+⁽ø³F⁸ṪO¤+ị¥Ọ
·π™
Ḣ5ŀ”b
;j‚Äú<>/‚Äù·πÉ@‚Äú¬¢ †f‚Äô
i”_+LµĿ
```
A full program taking one argument and printing the result.
**[Try it online!](https://tio.run/##y0rNyan8/9/0aMOjhrmZXI8a5hyecHjjw50LHzXMdHm4q9vhUdMaoOChhQ93zHu4owUoenQPiL//0P7DbUC5Q4sOrTm09VHDDO1HjXsP7zi02e1R446HO1f5H1qi/XB396GlD3f3cAH5XA93LIJYksRlnQU0wcZOH8h5uLPZAWTcolML0oBmc2UCxeK1fQ5tPbL/////zs7/AQ "Jelly – Try It Online")** or see the [test suite](https://tio.run/##y0rNyan8/9/0aMOjhrmZXI8a5hyecHjjw50LHzXMdHm4q9vhUdMaoOChhQ93zHu4owUoenQPiL//0P7DbUC5Q4sOrTm09VHDDO1HjXsP7zi02e1R446HO1f5H1qi/XB396GlD3f3cAH5XA93LIJYksRlnQU0wcZOH8h5uLPZAWTcolML0oBmc2UCxeK1fQ5tPbL//8PdWw63A62I/P8/kcvJiSs5nis@hcuVyx1Ie3A5O3N5eHD5@XEFBHAFBnIFBXFFRf0HAA "Jelly – Try It Online").
### How?
The main entry point is the last line of code ("Main link").
```
5ŀ”i - Link 1: list of characters, s (length 1 & no underscore)
”i - literal character 'i'
5ŀ - call link 5 as a dyad with s on the left and 'i' on the right
“Ðñṡ’Dẋ@€“¡ḞḄ’ż“¿¿Æ€¢¬µ‘+⁽ø³F⁸ṪO¤+ị¥Ọ - Link 2: list of characters, s (length 2 & no underscore)
“Ðñṡ’ - base 250 literal 1007245
D - to decimal list [1,0,0,7,2,4,5]
“¡ḞḄ’ - base 250 literal 111673
ẋ@€ - repeat with reversed @rguments for €ach -> [[111673],[],[],[111673,111673,111673,111673,111673,111673,111673],[111673,111673],[111673,111673,111673,111673],[111673,111673,111673,111673,111673]]
“¿¿Æ€¢¬µ‘ - code page index list [11,11,13,12,1,7,9]
ż - zip together [[111673,11],[11],[13],[[111673,111673,111673,111673,111673,111673,111673],12],[[111673,111673],1],[[111673,111673,111673,111673],7],[[111673,111673,111673,111673,111673],9]]
⁽ø³ - base 250 literal 8382
+ - addition (vectorises) [[120055,8393],[8393],[8395],[[120055,120055,120055,120055,120055,120055,120055],8394],[[120055,120055],8383],[[120055,120055,120055,120055],8389],[[120055,120055,120055,120055,120055],8391]]
F - flatten [120055,8393,8393,8395,120055,120055,120055,120055,120055,120055,120055,8394,120055,120055,8383,120055,120055,120055,120055,8389,120055,120055,120055,120055,120055,8391]
¤ - nilad followed by link(s) as a nilad: ^
⁸ - chain's left argument, s e.g. "CC" |
·π™ - tail (last character) 'C' |
O - cast to ordinal 67 |
¥ - last two links as a dyad: |
ị - index into (1-indexed & modular) 8383 (this is at index 67%26=15 -----------------------------------------------------+ )
+ - add the ordinal 8450
Ọ - convert from ordinal to character 'ℂ'
·π™ - Link 3: list of characters, s (length 2 & underscore at index 1)
·π™ - tail (get the first character
Ḣ5ŀ”b - Link 4: list of characters, s (length 2 & underscore at index 2)
·∏¢ - head s (the non-_ character)
”b - literal character 'b'
5ŀ - call link 5 as a dyad with the non-_ character on the left and 'b' on the right
;j‚Äú<>/‚Äù·πÉ@‚Äú¬¢ †f‚Äô - Link 5, wrap in a tag: element, tagName e.g. 'a', 'i'
; - concatenate the element with the tagName "ai"
“<>/” - literal list of characters "<>/"
j - join "a<>/i"
‚Äú¬¢ †f‚Äô - base 250 literal 166603
ṃ@ - base decompression with reversed @rguments
- "a<>/i" is 5 long, so 166603 is converted to
- base 5 [2,0,3,1,2,4,0,3] with digits "a<>/i" "<i>a</i>"
i”_+LµĿ - Main link: list of characters, s (as specified only):
”_ - literal '_'
i - index of '_' in s (1-indexed; 0 if not found)
L - length of s
+ - addition
µĿ - call link with that number as a monad with argument s
- implicit print
```
[Answer]
# JavaScript, 97 chars
```
([a,b])=>a==b?[...'ùî∏ùîπ‚ÑÇùîªùîºùîΩùîæ‚ÑçùïÄùïÅùïÇùïÉùïÑ‚ÑïùïÜ‚Ñô‚Ñö‚Ñùùïäùïãùïåùïçùïéùïèùïê‚ѧ'][a.charCodeAt()-65]:b?b=='_'?a.bold():b:a.italics()
```
Why a language have methods like [`String.prototype.italics`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/italics) and [`String.prototype.bold`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/bold)?
Thanks to Neil, save 9 bytes, use `[...s]` instead of `s.match(/./u)`.
] |
[Question]
[
**Background**
Brag is a card game similar in concept to, but simpler than, poker. A hand in brag consists of three cards and is ranked as follows from highest to lowest:
* Three of a kind - all three cards the same rank. Named as "three Kings" etc.
* Running flush aka straight flush. All three cards of same suit and of consecutive ranks. The hand is named by the three cards in ascending order followed by the words "on the bounce" to distinguish from a simple run/straight, eg "ten-jack-queen on the bounce". Note an ace is either high or low but not both - "king-ace-two" is not a run.
* Run aka straight. As above but without the requirement to match suits. Named simply as eg "ten-jack-queen".
* Flush - all three cards the same suit, named after the highest rank eg "Ace flush".
* Pair - two cards the same rank together with a third of another version rank. Named as "pair of threes" etc.
* Any other combination, named after the highest rank eg "ace high".
**Challenge**
Given three playing cards, output the name of the brag hand they output.
The cards will be input either as three 2-character strings or concatenated as a single 6-character string (whichever your implementation prefers), where the first of each pair is the rank (2...9, T, J, Q, K, A) and the second signifies the suit (H, C, D, S).
Standard golfing rules apply - write a program or function which accepts this input and outputs the name of the hand as detailed above.
You can assume the input will be valid (ranks and suits in the above range, no repeated card) and in whatever case you prefer, but will not be in any particular order.
Output must be either in all capitals, all lower case, or a sensible capitalisation eg title case or sentence case. Numeric ranks should be spelled out eg "tens" not 10s.
Sample inputs & outputs:
```
2H3C2D => "pair of twos"
TD8C9C => "eight-nine-ten"
4SKS9S => "king flush"
4D4H4S => "three fours"
5H3H2C => "five high"
2D3DAD => "ace-two-three on the bounce"
6D6C6H => "three sixes"
```
This is my first attempt at a challenge on this site, please do suggest improvements but be gentle :)
[Answer]
# [Python 2](https://docs.python.org/2/), 788, 715, 559, 556, 554, 546, 568, 522 bytes
\*now passes the 'sixes'
\* thanks to Ben Frankel for saving 46 Bytes!
---
```
import re
d,m,n=dict(zip('JQKA',range(10,15))),'pair of %ss','%s-%s-%s'
C=lambda s:int(d.get(s[0],s[0]))
z,x,c=sorted(re.findall('..',raw_input()),key=C)
q,w,e=C(z),C(x),C(c)
A=[0,0,'two','three','four','five','six','seven','eight','nine','ten','jack','queen','king','ace']
I,O,U=A[e],A[w],A[q]
a,k='%s high'%I,e-w+q
if k==13:a=n%(I,U,O)
if k==w:a=n%(U,O,I)
if q==w or e==w or e==q:a=m%O
if k==e==w:a='three %ss'%I
if'x'in a:a=a[:-1]+'es'
if z[-1]==x[-1]==c[-1]:
if'-'in a:a+=' on the bounce'
else:a='%s flush'%I
print a
```
[Try it online!](https://tio.run/nexus/python2#RVFNa@swELzrV@hiJJFNSCjvEtDB5OT2EEroyZii2utEtSN/ybWbP5@unMADscPOajTM6m6vbdN73iMr4ApOFzb38mZbKV7f32IBvXFnlLst7P4ppUC0xva8KXk0DAJENKyXI9hB1@b6VRg@7K3zstic0csh3WYQilLsBjPkeiAzLGSPm9K6wtS1FJtNcJk@rWtHL8mjwl99UKyDCVAf5E3BQc6h5IrFOt3CFoSfGrL3lx6RsGzGPoD9Cd1g51DxBx0h2vPFEzrrwtAv5LfJK4JuxKWtrDsTmBxFxhI4woeOU8wgTqdQuowZqDSl5Rd6TUQJ4HpadcyWvNJ697I32kUygQ84qic5PThiIFm4jjje9Bz/Y0d3rtHxqcCH6BFq2W@U0EjMwjpuaGLS/XqXrQTSuklyS6nTen5AHmDPOAnWT8FKC9447i/Iv5rRUTjGsR4wmFCUsh6HkIW1Pf0YN/d7fHo7vZ/@AA "Python 2 – TIO Nexus")
Thanks for a cool first challenge!
[Answer]
## Ruby, ~~384~~, 320
Accepts an array of two-char strings.
Translates the pip values into hex values and identifies hands based on how many distinct pip values there are.
```
->*d{u=d.map{|x|*u=x[1]}==u*3
g=d.map{|x|(x[0].tr'TJQKA','ABCDE').hex}.sort
g=1,2,3if[2,3,14]==g
_,l,h=a=g.map{|x|%w{king queen jack ten nine eight seven six five four three two ace}[-x%13]}
[*g[0]..2+g[0]]==g ?a*?-+(u ?' on the bounce':''):u ?h+' flush':[h+' high','pair of '+l+=l[?x]?'es':?s,'three '+l][-g.uniq.size]}
```
Annotated:
```
->*d{
# u is "Is this a flush?"" (see if you have more than one suit)
u=d.map{|x|u=x[1]}==[u]*3
# g is the sorted card values in integer (convert to base 16)
g=d.map{|x|x[0].tr('TJQKA','ABCDE').hex}.sort
# use Ace == 1 if we have a low straight
g=[1,2,3]if[2,3,14]==g
# a is the names of all the cards
a=g.map{|x|%w{ace two three four five six seven eight nine ten jack queen king ace}[x-1]}
# l is for "plural" - just choose the middle card because we
# only care about plurals for 2s or 3s
l=a[1].sub(?x,'xe')+?s
# if [g[0],g[0]+1,g[0]+2] == g, we have a run
# possibly "on the bounce"
([*g[0]..g[0]+2]==g) ? (a * ?-) + (u ? ' on the bounce' : '') :
# if we have a flush, we can't have three-of-a-kind, so try that first
u ? a[2]+' flush' :
# otherwise, dedupe your hand. if there's:
# 3 values, x high; 2 values, pair; 1 value, three
[a[2]+' high','pair of '+l,'three '+l][-g.uniq.size]
}
```
[Answer]
# PHP, ~~413~~ ~~405~~ ~~398~~ ~~409~~ ~~408~~ ~~406~~ 398 bytes
Unfortunately, PHP does not support nested array referencing inside strings;
that would have saved another ~~6~~ 5 bytes.
```
for(;$a=$argn[$i++];)$i&1?$v[strpos(_3456789TJQKA,$a)]++:$c[$a]++;$k=array_keys($v);sort($k);$n=[two,three,four,five,six,seven,eight,nine,ten,jack,queen,king,ace];echo($m=max($v))<2?($k[!$d=count($c)]+2-($h=$k[2])?$k[1]>1|$h<12?"$n[$h] ".[flush,high][$d++/2]:"ace-two-three":$n[$k[0]]."-".$n[$k[1]]."-$n[$h]").[" on the bounce"][$d^1]:($m<3?"pair of ":"three ").$n[$v=array_flip($v)[$m]].e[$v^4].s;
```
Run with `echo <hand> | php -nR '<code>` or [test it online](http://sandbox.onlinephpfunctions.com/code/c1f3e0bec19b280beeb56460dce07371f58bfc6c).
**breakdown**
```
for(;$a=$argn[$i++];)$i&1? # loop through input
$v[strpos(_3456789TJQKA,$a)]++ # count values on even positions [0,2,4]
:$c[$a]++; # count colors on odd positions [1,3,5]
$k=array_keys($v);sort($k); # $k=ascending values
$n=[two,three,four,five,six,seven,eight,nine,ten,jack,queen,king,ace];
echo($m=max($v))<2 # three different values:
?($k[!$d=count($c)]+2-($h=$k[2]) # test normal straight ($d=color count, $h=high card)
?$k[1]>1|$h<12 # test special straight
?"$n[$h] ".[flush,high][$d++/2] # flush if one color, high card if not
# ($d++ to avoid " on the bounce")
:"ace-two-three" # special straight
:$n[$k[0]]."-".$n[$k[1]]."-$n[$h]" # normal straight
).[" on the bounce"][$d^1] # if straight: straight flush if one color
:($m<3?"pair of ":"three ") # pair or triplet
.$n[$v=array_flip($v)[$m]] # card name
.e[$v^4].s # plural suffix
;
```
Requires PHP>=5.6 (for `e[...]`)
[Answer]
## Python 2 - 583 bytes
I'm too new to be able to comment posts, so I just post my version of python solusion.
Fixed issue with 'es' for pair and three of sixes. Thanks to [Not that Charles](https://codegolf.stackexchange.com/users/13950/not-that-charles)
```
d={'A':['ace',14],'2':['two',2],'3':['three',3],'4':['four',4],'5':['five',5],'6':['six',6],'7':['seven',7],'8':['eight',8],'9':['nine',9],'T':['ten',10],'J':['jack',11],'Q':['queen',12],'K':['king',13]}
r=input()
j=1
i=lambda x:d[x][j]
v=sorted(r[::2],key=i)
z,y,x=v
s=r[1::2]
e='es'if i(y)==6else's'
j=0
a=i(x)
if z==y or y==x:r="pair of %s"%i(y)+e
if s[0]*3==s:r="%s flush"%a
t="%s-%s"%(i(z),i(y))
j=1
u=" on the bounce"if r[-1]=='h'else ""
if i(z)+i(x)==2*i(y):r=t+"-%s"%a+u
if ''.join(v)=="23A":r="%s-"%a+t+u
if [z]*3==v:r="three %s"%d[z][0]+e
if len(r)==6:r="%s high"%a
print r
```
A bit more readable with some comments
```
# first of all we don't need to keep suits
d={'A':['ace',14],'2':['two',2],'3':['three',3],'4':['four',4],'5':['five',5],'6':['six',6],'7':['seven',7],'8':['eight',8],'9':['nine',9],'T':['ten',10],'J':['jack',11],'Q':['queen',12],'K':['king',13]}
r=input() # input placed in r, to safely check r[-1] later in code
j=1 # j toggles reading from dictionary: 0-string, 1-value
i=lambda x:d[x][j] # lambda used to access dictionary
v=sorted(r[::2],key=i) # take values from input and sort
z,y,x=v # variables to compact code
s=r[1::2] # take suits from input
e='es'if i(y)==6else's' # choose ending 'es' for six and 's' for others (for pair and three)
j=0 # toggle reading from dictionary to string
a=i(x) # get string of top most value
if z==y or y==x: # check only two pairs as values are sorted
r="pair of %s"%i(y)+e
if s[0]*3==s: # compact check if all string characters are equal to detect flush
r="%s flush"%a
t="%s-%s"%(i(z),i(y)) # part of straight output - first two values
j=1 # toggle reading from dictionary to values
u=" on the bounce"\ # addon to output in case of possible straight flush
if r[-1]=='h'else "" # detected by checking last character in r
# which would be 'h' if flush was detected
if i(z)+i(x)==2*i(y): # check straight - three sorted numbers a,b,c would be in line if a+c == 2*b
r=t+"-%s"%a+u
if ''.join(v)=="23A": # check special case with straight, started from Ace
r="%s-"%a+t+u
j=0 # toggle reading from dictionary to string
if [z]*3==v: # check three equal values (almost the same as flush check)
r="three %s"%d[z][0]+e
if len(r)==6: # if r was never modified, then it's just one high card
r="%s high"%a
print r # output r
```
] |
[Question]
[
# Tic-Tac-Latin!
### This is a true story, so names have been altered.
My latin teacher, Mr. Latin, created his own proprietary (no joke) tic tac toe variant. Let's call it tic-tac-latin. The game is simple, it is essentially tic tac toe played on a four by four grid.
# Formal rule declaration
A line is either a row, column or a diagonal. There are two symbols, 'X' and 'O', but one or both may be substituted for a different symbol.
You score one point when you have three of your symbol and one of the other character.
These arrangements score:
```
---O
-O--
**XXXO**
XOOX
**O**-XX
-**O**--
--**X**-
---**O**
```
These do not score:
```
----
XXXX
----
OOOO
----
XXX-
----
OOO-
```
The game is won whenever one player has more points then another. The game is a draw only if the board gets filled up.
# Challenge
Solve this game. Your job is to provide a way to guarantee a win or tie, whichever is the optimal result.
Your solution may choose to either start first or second (and may therefore choose it's symbol). It is not mandatory to implement an interactive game where the user inputs moves and the corresponding display changes. It may also **be a function or program which takes input as a game state, and outputs a new board or a description of their move**. Either option must run within approximately ten seconds per move made.
---
Playing your player against any sequence of moves must give the optimal result. This means that you may assume the input position is one that it reachable from play with your player. Submissions must be deterministic, and do not necessarily need to supply a proof of optimality, but if they get cracked (by being beaten) your submissions will be considered invalid (you may leave it up, but add (cracked) in the headline).
---
This is a non-trivial task, so any valid submission is impressive and is worthy of an accepted tick, but I will make code golf the primary winning criterion.
The winner is chosen by going down this list till one winner is chosen.
* Shortest solved implemenation which always wins
* Shortest implementation
[Answer]
# Perl, 147 bytes (non competing, takes more than 10 seconds per move)
Includes +4 for `-0p`
The program plays `X`. It will play a perfect game.
Input the board on STDIN, e.g.:
```
tictaclatin.pl
-X-O
-X--
X-X-
O--O
^D
```
The ouptut will be the same board with all `X` replaced by `O` and vice versa. The empty spots will be filled with a number indicating the result if X would play there, with `1` meaning the result will be a win, `2` a draw and `3` a loss. A finished game just returns the same position with the colors reversed.
In this example the output would be:
```
1O1X
1O33
O3O3
X33X
```
So the position is a win for `X` if he plays in the 3 spots along the top and the left. All other moves lose.
This confusing output is actually convenient if you want to know how the game continues after a move. Since the program always plays `X` you have to swap `X` and `O` to see the moves for `O`. Here for example it's pretty clear that `X` wins by playing in the top left, but what about if `X` plays in the third position along the top ? Just copy the output, put an `O` in place of the move you select and replace all other numbers by `-` again, so here:
```
-OOX
-O--
O-O-
X--X
```
Resulting in:
```
3XXO
3X33
X3X3
O33O
```
Obviously every move by `O` should lose, so how does he lose if he plays in the top left ? Again do this by putting `O` in the top left and replacing the digits by `-`:
```
OXXO
-X--
X-X-
O--O
```
Giving:
```
XOOX
1O33
O3O3
X33X
```
So X has only one way to go for his win:
```
XOOX
OO--
O-O-
X--X
```
Giving
```
OXXO
XX33
X3X3
O33O
```
The situation for `O` remains hopeless. It's easy to see now that every move allows `X` to immediately win. Let's at least try to go for 3 O's in a row:
```
OXXO
XX--
X-X-
O-OO
```
Giving:
```
XOOX
OO13
O3O3
X3XX
```
`X` plays the only winning move (notice that this makes `XXXO` along the third column:
```
XOOX
OOO-
O-O-
X-XX
```
Here the output is:
```
OXXO
XXX-
X-X-
O-OO
```
because the game was already finished. You can see the win on the third column.
The actual program `tictaclatin.pl`:
```
#!/usr/bin/perl -0p
y/XO/OX/,$@=-$@while$|-=/(@{[map{(O.".{$_}O"x3)=~s%O%Z|$`X$'|Z%gr}0,3..5]})(?{$@++})^|$/sx;$@<=>0||s%-%$_="$`O$'";$$_||=2+do$0%eg&&(/1/||/2/-1)
```
Applied to the empty board this evaluates 9506699 positions which takes 30Gb and 41 minutes on my computer. The result is:
```
2222
2222
2222
2222
```
So every starting move draws. So the game is a draw.
The extreme memory usage is mostly caused by the recursion using `do$0`. Using this 154 byte version using a plain function needs 3Gb and 11 minutes:
```
#!/usr/bin/perl -0p
sub f{y/XO/OX/,$@=-$@while$|-=/(@{[map{(O.".{$_}O"x3)=~s%O%Z|$`X$'|Z%gr}0,3..5]})(?{$@++})^|$/sx;$@<=>0||s%-%$_="$`O$'";$$_||=2+&f%eeg&&(/1/||/2/-1)}f
```
which is more bearable (but still too much, something must still be leaking memory).
Combining a number of speedups leads to this 160 byte version (5028168 positions, 4 minutes and 800M for the empty board):
```
#!/usr/bin/perl -0p
sub f{y/XO/OX/,$@=-$@while$|-=/(@{[map{(O.".{$_}O"x3)=~s%O%Z|$`X$'|Z%gr}0,3..5]})(?{$@++})^|$/osx;$@<=>0||s%-%$_="$`O$'";$a{$_}//=&f+1or return 1%eeg&&/1/-1}f
```
That last one uses `0` for a win (don't confuse with `O`), `1` for a draw and `2` for a loss. The output of this one is also more confusing. It fills in the winning move for X in case of a win without color swap, but if the input game was already won is still does the color swap and does not fill in any move.
All versions of course get faster and use less memory as the board fills up. The faster versions should generate a move in under 10 seconds as soon as 2 or 3 moves have been made.
In principle this 146 byte version should also work:
```
#!/usr/bin/perl -0p
y/XO/OX/,$@=-$@while/(@{[map{(O.".{$_}O"x3)=~s%O%Z|$`X$'|Z%gr}0,3..5]})(?{$@++})^/sx,--$|;$@<=>0||s%-%$_="$`O$'";$$_||=2+do$0%eg&&(/1/||/2/-1)
```
but on my machine it triggers a perl bug and dumps core.
All versions will in principle still work if the 6 byte position caching done by `$$_||=` is removed but that uses so much time and memory that it only works for almost filled boards. But in theory at least I have a 140 byte solution.
If you put `$\=` (cost: 3 bytes) just before the `$@<=>0` then each output board will be followed by the status of the whole board: `1` for `X` wins, `0` for draw and `-1` for loss.
Here is an interactive driver based on the fastest version mentioned above. The driver has no logic for when the game is finished so you have to stop yourself. The golfed code knows though. If the suggested move returns with no `-` replaced by anything the game is over.
```
#!/usr/bin/perl
sub f{
if ($p++ % 100000 == 0) {
local $| = 1;
print ".";
}
y/XO/OX/,$@=-$@while$|-=/(@{[map{(O.".{$_}O"x3)=~s%O%Z|$`X$'|Z%gr}0,3..5]})(?{$@++})^|$/osx;$@<=>0||s%-%$_="$`O$'";$a{$_}//=&f+1or return 1%eeg&&/1/-1}
# Driver
my $tomove = "X";
my $move = 0;
@board = ("----\n") x 4;
while (1) {
print "Current board after move $move ($tomove to move):\n ABCD\n";
for my $i (1..4) {
print "$i $board[$i-1]";
}
print "Enter a move like B4, PASS (not a valid move, just for setup) or just press enter to let the program make suggestions\n";
my $input = <> // exit;
if ($input eq "\n") {
$_ = join "", @board;
tr/OX/XO/ if $tomove eq "O";
$p = 0;
$@="";
%a = ();
my $start = time();
my $result = f;
if ($result == 1) {
tr/OX/XO/ if $tomove eq "O";
tr/012/-/;
} else {
tr/OX/XO/ if $tomove eq "X";
tr/012/123/;
}
$result = -$result if $tomove eq "O";
my $period = time() - $start;
print "\nSuggested moves (evaluated $p positions in $period seconds, predicted result for X: $result):\n$_";
redo;
} elsif ($input =~ /^pass$/i) {
# Do nothing
} elsif (my ($x, $y) = $input =~ /^([A-D])([1-4])$/) {
$x = ord($x) - ord("A");
--$y;
my $ch = substr($board[$y],$x, 1);
if ($ch ne "-") {
print "Position already has $ch. Try again\n";
redo;
}
substr($board[$y],$x, 1) = $tomove;
} else {
print "Cannot parse move. Try again\n";
redo;
}
$tomove =~ tr/OX/XO/;
++$move;
}
```
[Answer]
## JavaScript (ES6) 392 bytes
```
a=>b=>(c="0ed3b56879a4c21f",r=[],k=f=>r.push([a.filter(f),b.filter(f)]),[0,1,2,3].map(i=>k(n=>n%4==i)+k(n=>(n/4|0)==i)),k(n=>n%5==0),k(n=>n&&n-15&&!(n%3)),g=r.find(o=>(o[0].length==1&&o[1].length==2)||(o[0].length==2&&o[1].length==1)),g?parseInt(c[30-[...g[0],...g[1]].map(i=>parseInt(c[i],16)).reduce((p,c)=>p+c)],16):[...a,...b].indexOf(15-a[0])+1?15-a.find(i=>b.indexOf(15-i)==-1):15-a[0])
```
### Usage
The "bot" will play second.
Draw a 4x4 grid which are numbered like this:
```
+----+----+----+----+
| 0 | 1 | 2 | 3 |
+----+----+----+----+
| 4 | 5 | 6 | 7 |
+----+----+----+----+
| 8 | 9 | 10 | 11 |
+----+----+----+----+
| 12 | 13 | 14 | 15 |
+----+----+----+----+
```
Let's run this in the browser console: Just put `f=` before the code
So, if I wanna start at `1`, I would run `f([1])([])` and it will give me `14`.
Nice move... What if I play `2` afterwards? `f([2,1])([14])`. It will return `13`.
Lemme try surrendering. Play `3`. `f([3,2,1])([14,13])`. Oh `0`! You got me!
Play `0`? `f([0,2,1])([14,13])`. `15` Ok let's keep playing...
### Note
1. Play interactively. Start with `f([your-step])([])`.
2. Prepend your next step. (See demo above)
3. Help the "bot" input its steps. It will not give you good results if you give it a random setting. (Like `f([1,2,4])([14,12])` will give `14` - Hey the bot wanted to play on `13` on its second move!
### Brief Summary
As long as you are not surrendering, the bot will play a mirror move.
Thanks @EHTproductions for telling me that I misread the game rules and golfing tips :P
Now it will also detect if it got checkmate. If yes, block it!
Its priorities: Block > Mirror > (fallback) look for ways to reproducing a mirror
] |
[Question]
[
Consider binary [block diagonal matrices](https://en.wikipedia.org/wiki/Block_matrix#Block_diagonal_matrices) which have square blocks of 1s on the main diagonal, and are 0 everywhere else. Let's call such matrices "valid" matrices.
For example, here are some valid 4x4 matrices:
```
1 0 0 0 1 1 0 0 1 0 0 0 1 0 0 0 1 1 0 0 1 1 1 1
0 1 0 0 1 1 0 0 0 1 1 0 0 1 1 1 1 1 0 0 1 1 1 1
0 0 1 0 0 0 1 0 0 1 1 0 0 1 1 1 0 0 1 1 1 1 1 1
0 0 0 1 0 0 0 1 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1
```
Note that an alternative way of describing such matrices is that there is a chain of square 1 blocks from the top-left to the bottom-right, touching corner to corner, and everywhere else is 0.
For contrast, here are some invalid 4x4 matrices:
```
1 0 1 0 1 0 1 0 1 1 0 0 0 1 1 1 1 1 0 0 0 0 0 0
0 1 1 1 0 1 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 0 0
1 0 0 1 1 0 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0
0 0 1 0 0 1 0 1 0 0 0 1 1 0 0 0 0 0 1 1 0 0 0 0
```
You will be given an `n` by `n` binary matrix as input – what is the minimum number of `0` bits you'll need to set to `1` in order to get a valid matrix?
You may write a function or program taking in any convenient string, list or matrix format representing an `n` by `n` matrix of 0s and 1s (as long as it isn't preprocessed). Rows must be clearly separated in some way, so formats like a 1D array of bits are not allowed.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the goal is to minimise the number of bytes in your program.
## Examples
For example, if the input is
```
0 0 0 0 0
0 0 1 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 1
```
then the answer is 5, since you can set five `0` bits to `1` to get:
```
1 0 0 0 0
0 1 1 0 0
0 1 1 0 0
0 0 0 1 0
0 0 0 0 1
```
and this is the minimum number required. However, if the input was
```
0 0 0 0 1
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
```
then the answer is 24, since the only valid 5x5 matrix where the top-right is `1` is the matrix of all `1`s.
## Test cases
Tests are represented here as a 2D array of integers.
```
[[0]] -> 1
[[1]] -> 0
[[0,1],[0,0]] -> 3
[[1,0],[0,0]] -> 1
[[0,0,0],[0,1,0],[0,0,0]] -> 2
[[0,1,0],[0,0,0],[0,1,0]] -> 7
[[0,1,0],[1,0,0],[0,0,1]] -> 2
[[1,1,1],[1,1,1],[1,1,1]] -> 0
[[0,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,0]] -> 4
[[0,0,1,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]] -> 8
[[0,0,1,0],[0,0,0,0],[0,0,0,0],[0,0,1,0]] -> 14
[[0,0,1,0],[0,0,0,0],[0,0,0,0],[0,1,0,0]] -> 14
[[0,0,0,0,0],[0,0,0,0,0],[0,1,0,0,0],[0,0,0,0,1],[0,0,0,0,0]] -> 7
[[0,0,0,0,0],[0,0,0,0,0],[1,0,0,0,0],[0,0,0,0,1],[0,0,0,0,0]] -> 11
[[0,0,0,0,0],[0,0,1,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,1]] -> 5
[[0,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]] -> 24
[[0,0,0,1,0],[0,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]] -> 23
[[0,1,0,0,0],[1,0,0,0,0],[0,0,1,0,0],[0,0,0,0,1],[0,0,0,1,0]] -> 4
[[0,1,1,1,0],[0,1,1,0,1],[0,1,1,1,0],[0,1,0,0,1],[0,0,0,0,0]] -> 14
```
## Notes
* Related challenge: [Print a Block-Diagonal Matrix](https://codegolf.stackexchange.com/questions/45550/print-a-block-diagonal-matrix)
* Inspiration: [Freedom Factory, Google Code Jam 2016 Problem 2D](https://code.google.com/codejam/contest/10224486/dashboard#s=p3)
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~46~~ 43 bytes
```
nX^tQt:qZ^!tsb=Z)"@!"@1$l]@n$YdG-Q?6MG>zvX<
```
Input is a 2D array with semicolon as row separator. For example, the input for the last test case is
```
[0,1,1,1,0;0,1,1,0,1;0,1,1,1,0;0,1,0,0,1;0,0,0,0,0]
```
[Try it online!](http://matl.tryitonline.net/#code=blhedFF0OnFaXiF0c2I9WikiQCEiQDEkbF1AbiRZZEctUT82TUc-enZYPA&input=WzAsMSwxLDEsMDswLDEsMSwwLDE7MCwxLDEsMSwwOzAsMSwwLDAsMTswLDAsMCwwLDBd) Or [verify all test cases](http://matl.tryitonline.net/#code=YApYSW5YXnRRdDpxWl4hdHNiPVopIkAhIkAxJGxdQG4kWWRJLVE_Nk1JPnp2WDxdXQpEVA&input=WzBdClsxXQpbMCwxOzAsMF0KWzEsMDswLDBdClswLDAsMDswLDEsMDswLDAsMF0KWzAsMSwwOzAsMCwwOzAsMSwwXQpbMCwxLDA7MSwwLDA7MCwwLDFdClsxLDEsMTsxLDEsMTsxLDEsMV0KWzAsMCwwLDA7MCwwLDEsMDswLDEsMCwwOzAsMCwwLDBdClswLDAsMSwwOzAsMCwwLDA7MCwwLDAsMDswLDAsMCwxXQpbMCwwLDEsMDswLDAsMCwwOzAsMCwwLDA7MCwwLDEsMF0KWzAsMCwxLDA7MCwwLDAsMDswLDAsMCwwOzAsMSwwLDBdClswLDAsMCwwLDA7MCwwLDAsMCwwOzAsMSwwLDAsMDswLDAsMCwwLDE7MCwwLDAsMCwwXQpbMCwwLDAsMCwwOzAsMCwwLDAsMDsxLDAsMCwwLDA7MCwwLDAsMCwxOzAsMCwwLDAsMF0KWzAsMCwwLDAsMDswLDAsMSwwLDA7MCwwLDAsMCwwOzAsMCwwLDAsMDswLDAsMCwwLDFdClswLDAsMCwwLDE7MCwwLDAsMCwwOzAsMCwwLDAsMDswLDAsMCwwLDA7MCwwLDAsMCwwXQpbMCwwLDAsMSwwOzAsMCwwLDAsMTswLDAsMCwwLDA7MCwwLDAsMCwwOzAsMCwwLDAsMF0KWzAsMSwwLDAsMDsxLDAsMCwwLDA7MCwwLDEsMCwwOzAsMCwwLDAsMTswLDAsMCwxLDBdClswLDEsMSwxLDA7MCwxLDEsMCwxOzAsMSwxLDEsMDswLDEsMCwwLDE7MCwwLDAsMCwwXQ) (code slightly modified to take all inputs; the results appear after a few seconds)
### Explanation
Let the input be an *N*×*N* matrix. The code first computes all (*N*+1)-tuples of block sizes that produce the appropriate matrix size. For example, for *N*=4 the tuples are `0 0 0 0 4`, `0 0 0 1 3`, ..., `4 0 0 0 0`. For each tuple it builds the block-diagonal matrix with those block sizes. It then checks if the matrix covers all the `1` entries in the input, and if so takes note of the number of `1` entries that were not present in the input. The final result is the minimum of all the obtained numbers.
```
nX^ % Implicit input an N×N matrix. Get N
t % Duplicate N
Qt:q % Vector [0 1 ... N]
Z^ % Cartesian power. Gives 2D array
!ts % Transpose, duplicate, sum of each column
b= % Logical vector that equals true if the sum is N
Z) % Filter columns according to that. Only keep columns that sum to N. Each
% column is the size of one block
" % For each column
@ % Push that column
" % For each entry of that column
@ % Push that entry
1$l % Square matrix with that size, filled with 1
] % End
@n % Column size. This is the number of blocks in the block-diagonal matrix
$Yd % Build block-diagonal matrix from those blocks
G-Q % Subtract input matrix element-wise, and add 1
? % If all entries are nonzero (this means each that entry that is 1 in the
% block-diagonal matrix is also 1 in the input matrix)
6M % Push block-diagonal matrix again
G> % For each entry, gives 1 if it exceeds the corresponding entry of the
% input, that is, if the block-diagonal matrix is 1 and the input is 0
z % Number of 1 entries
v % Concatenate vertically with previous values
X< % Take minimum so far
% Implicit end
% Implicit end
% Implicit display
```
[Answer]
## Python with numpy, 102
```
from numpy import*
lambda M:sum(diff([k for k in range(len(M)+1)if(M|M.T)[:k,k:].any()-1])**2)-M.sum()
```
An efficient algorithm. Finds the "neck points" on the diagonal that can separate blocks. These have all 0's above and right, as well as below and left. The minimal blocks are those between neck points.
```
??000
??000
00???
00???
00???
```
The length of a block is the difference between consecutive neck points, so their total area of the sum of squares of these. Subtracting the sum of the original matrix then gives the number of flips needed from 0 to 1.
[Answer]
# Pyth, 45 bytes
```
[[email protected]](/cdn-cgi/l/email-protection)^+LsYN2d+0._ds.pM./lQss
```
Difficult task, so it's quite long.
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=-hSlMf%40I.DRlQx1sQTms.b%5E%2BLsYN2d%2B0._ds.pM.%2FlQss&input=[[0%2C1%2C0]%2C[0%2C0%2C0]%2C[0%2C1%2C0]]&test_suite_input=[[0]]%0A[[1]]%0A[[0%2C1]%2C[0%2C0]]%0A[[1%2C0]%2C[0%2C0]]%0A[[0%2C0%2C0]%2C[0%2C1%2C0]%2C[0%2C0%2C0]]%0A[[0%2C1%2C0]%2C[0%2C0%2C0]%2C[0%2C1%2C0]]%0A[[0%2C1%2C0]%2C[1%2C0%2C0]%2C[0%2C0%2C1]]%0A[[1%2C1%2C1]%2C[1%2C1%2C1]%2C[1%2C1%2C1]]%0A[[0%2C0%2C0%2C0]%2C[0%2C0%2C1%2C0]%2C[0%2C1%2C0%2C0]%2C[0%2C0%2C0%2C0]]%0A[[0%2C0%2C1%2C0]%2C[0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C1]]%0A[[0%2C0%2C1%2C0]%2C[0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0]%2C[0%2C0%2C1%2C0]]%0A[[0%2C0%2C1%2C0]%2C[0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0]%2C[0%2C1%2C0%2C0]]%0A[[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]%2C[0%2C1%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C1]%2C[0%2C0%2C0%2C0%2C0]]%0A[[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]%2C[1%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C1]%2C[0%2C0%2C0%2C0%2C0]]%0A[[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C1%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C1]]%0A[[0%2C0%2C0%2C0%2C1]%2C[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]]%0A[[0%2C0%2C0%2C1%2C0]%2C[0%2C0%2C0%2C0%2C1]%2C[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]]%0A[[0%2C1%2C0%2C0%2C0]%2C[1%2C0%2C0%2C0%2C0]%2C[0%2C0%2C1%2C0%2C0]%2C[0%2C0%2C0%2C0%2C1]%2C[0%2C0%2C0%2C1%2C0]]%0A[[0%2C1%2C1%2C1%2C0]%2C[0%2C1%2C1%2C0%2C1]%2C[0%2C1%2C1%2C1%2C0]%2C[0%2C1%2C0%2C0%2C1]%2C[0%2C0%2C0%2C0%2C0]]&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=-hSlMf%40I.DRlQx1sQTms.b%5E%2BLsYN2d%2B0._ds.pM.%2FlQss&input=[[0%2C1%2C0]%2C[0%2C0%2C0]%2C[0%2C1%2C0]]&test_suite=1&test_suite_input=[[0]]%0A[[1]]%0A[[0%2C1]%2C[0%2C0]]%0A[[1%2C0]%2C[0%2C0]]%0A[[0%2C0%2C0]%2C[0%2C1%2C0]%2C[0%2C0%2C0]]%0A[[0%2C1%2C0]%2C[0%2C0%2C0]%2C[0%2C1%2C0]]%0A[[0%2C1%2C0]%2C[1%2C0%2C0]%2C[0%2C0%2C1]]%0A[[1%2C1%2C1]%2C[1%2C1%2C1]%2C[1%2C1%2C1]]%0A[[0%2C0%2C0%2C0]%2C[0%2C0%2C1%2C0]%2C[0%2C1%2C0%2C0]%2C[0%2C0%2C0%2C0]]%0A[[0%2C0%2C1%2C0]%2C[0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C1]]%0A[[0%2C0%2C1%2C0]%2C[0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0]%2C[0%2C0%2C1%2C0]]%0A[[0%2C0%2C1%2C0]%2C[0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0]%2C[0%2C1%2C0%2C0]]%0A[[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]%2C[0%2C1%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C1]%2C[0%2C0%2C0%2C0%2C0]]%0A[[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]%2C[1%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C1]%2C[0%2C0%2C0%2C0%2C0]]%0A[[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C1%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C1]]%0A[[0%2C0%2C0%2C0%2C1]%2C[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]]%0A[[0%2C0%2C0%2C1%2C0]%2C[0%2C0%2C0%2C0%2C1]%2C[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]%2C[0%2C0%2C0%2C0%2C0]]%0A[[0%2C1%2C0%2C0%2C0]%2C[1%2C0%2C0%2C0%2C0]%2C[0%2C0%2C1%2C0%2C0]%2C[0%2C0%2C0%2C0%2C1]%2C[0%2C0%2C0%2C1%2C0]]%0A[[0%2C1%2C1%2C1%2C0]%2C[0%2C1%2C1%2C0%2C1]%2C[0%2C1%2C1%2C1%2C0]%2C[0%2C1%2C0%2C0%2C1]%2C[0%2C0%2C0%2C0%2C0]]&debug=0)
### Explanation:
`s.pM./lQ` computes all integer partitions of `len(matrix)`. `ms.b^+LsYN2d+0._d` converts them into coordinate-pairs. For instance the partition `[1, 2, 2]` of `5` gets converted into `[[0,0], [1,1], [1,2], [2,1], [2,2], [3,3], [3,4], [4,3], [4,4]`.
`[[email protected]](/cdn-cgi/l/email-protection)` then filters for partitions, that completely overlap the matrix (`.DRlQx1sQ` computes all coordinate-pairs of the active cells in the matrix).
`-hSlM...ss` counts the cells of each remaining partitions, chooses the one with the least cells, and subtracts the already active cells.
[Answer]
# [Matricks](https://github.com/jediguy13/Matricks), 180 bytes (noncompeting)
Matricks is a new esolang I created very recently to deal with matrix problems (such as this one), by only having 2 data types: floats and matricies. It is not fully featured yet, and still has a lot of missing operations (I had to add some functionality for this challenge). Anyway, here's the code:
```
il=1:j3;:bdx;;;s1::L;j1;;
b{q:1;mgr:c;|gc:r;|(r=c)|(gr-1:c;|gr:c+1;)&(rec)|(gr+1:c;|gr:c-1;)&(cer):l:L;};z:(l-1)/2;B1;s1::g1:;-1;ig1:;=0:j2;:j1;;
s1::d{q:1;};;kg1:;-g:;;
kg:;*-1+1;
```
## Explanation
The first part, `il=1:j3;:...;` checks if the array is of size 1. If it is, it jumps to the last line, `kg:;*-1+1;`, which is a simple `0 <-> 1` function.
Otherwise, it continues on with the rest of the code. `bdx;;;` sets the cell `0,0` to the current sum, and `s1::L;j1;` creates a counter in the cell in the row below.
The next line is a bit more complicated. It is a loop that runs `n` times, `n` being the size of the matrix. I'll use the 3rd test case as an example. When we first get to the second line, the matrix looks like this:
```
1 0 1
2 0 0
```
First, we go into the matrix comprehension `{q:1;m...;}`. This makes the diagonal, and tries its best to clean up 0 that need filling in. All this is accomplished using simple boolean operators. Then, we prepend it to the current matrix, giving this:
```
V--data we want to keep
1 1 1 0 1 <-|
1 1 2 0 0 <-- old matrix
```
Then, we cut of the old matrix using `z:(l-1)/2;`, and rotate the entire matrix to the left using `B1;`. That gives us a matrix ready for the next iteration, looking like:
```
1 1 1
2 1 1
```
Finally, we decrement the counter, check it, and continue with `ig1:;=0:j2;:j1;;`
Once the loop is broken out of, we find the new sum and set the counter's old spot with `s1::d{q:1;};;`. Finally, we take the difference and return `kg1:;-g:;;`. `k` sets the current array to a value, and printing is implicit.
...
As you can see, **Matricks** is pretty verbose, and not a very good golfing language. But heck, I wanted to show it off.
] |
[Question]
[
Write a program or function that takes in a positive integer N. Output a list of all the distinct decimal numbers that can be written *in exactly N characters* using digits (`0123456789`), decimal points (`.`), and negative signs (`-`).
For example, some numbers that would be in the N = 4 output list are `1337`, `3.14`, `.999`, `-789`, `-2.7`, and `-.09`.
The numbers are to be written in the normal way, **but in as short a form as possible**. This means:
* The decimal point should only be included if the number is not an integer.
+ e.g. `45.0` and `45.` should be written as plain `45`
+ `-45.00` should be written as `-45`
* There should be no leading zeroes to the left of the decimal point.
+ `03` and `003` should be written as `3`, but `30` and `300` are fine as they are
+ `0.3` and `00.3` should be written as just `.3`
+ `-03` should be written as `-3`
+ `-0.3` should be written as `-.3`
* There should be no trailing zeroes to the right of the decimal point
+ `.50` and `.500` should be written as `.5`
+ `900.090` should be written as `900.09`
* The exception to the two last rules is zero itself, which should **always be written as plain `0`**.
* Positive signs (`+`) should not be used since they unnecessarily lengthen the number.
Also note that the negative sign (`-`) should not be used as a subtraction sign. It should only appear as the first character of numbers less than zero.
# Formatting
**The order of the output list of numbers does not matter.** It could be ascending, descending, or completely mixed up. It only matters that ***all*** of the distinct numbers that can be written in N characters are present.
The list can be formatted in a reasonable way, using spaces, newlines, commas, or perhaps something else between the numbers, as long as things are consistent. Leading and trailing brackets (or similar) are alright but things like quotes around numbers are not. (i.e. don't visibly mix up strings and ints/floats in the output.)
For example, when N = 1, some valid outputs would be:
```
0 1 2 3 4 5 6 7 8 9
```
```
[1, 2, 3, 4, 5, 6, 7, 9, 0]
```
```
ans = { 5 8 9 1 3 2 0 3 4 7 6 }
```
But this would be invalid:
```
[0, 1, 2, 3, 4, "5", "6", "7", "8", "9"]
```
# Examples
```
N = 1 -> 0 1 2 3 4 5 6 7 8 9
N = 2 -> -9 -8 -7 -6 -5 -4 -3 -2 -1 .1 .2 .3 .4 .5 .6 .7 .8 .9 10 11 12 ... 97 98 99
N = 3 -> -99 -98 ... -11 -10 -.9 -.8 ... -.2 -.1 .01 .02 ... .98 .99 1.1 1.2 ... 1.9 2.1 2.2 ... 2.9 3.1 ...... 9.9 100 101 ... 998 999
```
Lists are in ascending order, ellipsized in some places for reading convenience.
# Scoring
The shortest code in bytes wins. In case of ties, the higher voted answer wins
[Answer]
## Pyth, 57 bytes
```
j-f:T"^0$|^-?([1-9]\d*)?(\.\d*[1-9])?$"0{.P*Q+jkUT".-"Q\-
```
[Try it on the online interpreter](https://pyth.herokuapp.com/?code=j-f%3AT%22%5E0%24%7C%5E-%3F%28%5B1-9%5D%5Cd%2a%29%3F%28%5C.%5Cd%2a%5B1-9%5D%29%3F%24%220%7B.P%2aQ%2BjkUT%22.-%22Q%5C-&input=4&debug=0).
Way too long, and with horrific runtime (takes several seconds for N=4, running with N=5 is not recommended).
```
.P Q all permutations of length (input) of
jkUT ... the string "0123456789"
+ ".-" ... plus the chars "." and "-"
*Q ... whole thing times the input -- pyth has
no repeated_permutation, so this is necessary
{ uniquify
f filter by
:T"..."0 does it match the really long regex?
- \- get rid of "-"
j join on newline
```
Regex explanation:
```
^0$| "0", or...
^
-? optional negative sign
([1-9]\d*)? optional part-before-decimal
(\.\d*[1-9])? optional part-after-decimal
$
```
[Answer]
# Pyth, ~~47~~ 45 bytes
*Thanks to [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for [noting](https://codegolf.stackexchange.com/questions/71161/all-the-numbers-that-fit-in-a-string/71190?noredirect=1#comment174301_71190) that the order does not matter.*
```
jf!sm:Td)c".- \..*\. ^-?0. [.-]0*$"d^{`c_T17Q
```
[Try it online.](https://pyth.herokuapp.com/?code=jf!sm%3ATd)c%22.-%20%5C..*%5C.%20%5E-%3F0.%20%5B.-%5D0*%24%22d%5E%7B%60c_T17Q&input=3&debug=0)
The runtime is horrible, basically O(12n), but I tested it for `n` = 6 on my computer (which took 2 minutes). Running `n` ≥ 5 *will* time out online.
Due to the way I generate the characters `0123456789.-` the output is in a really weird order.
One could technically remove the `{` near the end, but it would result in a complexity of O(19n). (It would also produce lots of duplicates, but that's allowed.)
### Explanation
```
_T -10
c 17 -10 / 17 = -0.5882352941176471
` representation: "-0.5882352941176471"
{ uniquify: "-0.582394176"
^ Q input'th Cartesian power
f filter on:
c"…"d split this string by spaces
m:Td) check if the parts match the current string
!s true if none of the parts matched
j join by newlines
```
The main part of the code is `".- \..*\. ^-?0. [.-]0*$"`, which contains the regexes any output must *not* match.
```
.- minus must be first character
\..*\. there may only be one decimal point
^-?0. no extra leading zeroes
[.-]0*$ number must not end with decimal/minus and 0+ zeroes
```
[Answer]
# Julia, ~~126~~ 117 bytes
```
n->filter(i->ismatch(r"^0$|^-?([1-9]\d*)?(\.\d*[1-9])?$",i)&&i!="-",∪(map(join,combinations((".-"join(0:9))^n,n))))
```
This is a lambda function that accepts an integer and returns an array of strings. To call it, assign it to a variable. The approach here is the same as Doorknob's Pyth [answer](https://codegolf.stackexchange.com/a/71163/20469).
Ungolfed:
```
function g(n::Int)
# Get all n-character combinations of .-0123456789
c = combinations((".-"join(0:9))^n, n)
# Join each group of n characters into a string and take unique
u = ∪(map(join, c))
# Filter to only appropriately formatted strings
filter(i -> ismatch(r"^0$|^-?([1-9]\d*)?(\.\d*[1-9])?$", i) && i != "-", u)
end
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 60 bytes
```
45:57iZ^!"@!'^(-?(([1-9]\d*)|([1-9]\d*)?(\.\d*[1-9]))|0)$'XX
```
[Try it online!](http://matl.tryitonline.net/#code=NDU6NTdpWl4hIkAhJ14oLT8oKFsxLTldXGQqKXwoWzEtOV1cZCopPyhcLlxkKlsxLTldKSl8MCkkJ1hY&input=Mw)
This uses super-brute force (via Cartesian power) followed by filtering (via a regular expression). I'll add an explanation later.
The results are displayed at the end of the program. This may take a while. If you want to see results as they are generated, [add `D` at the end](http://matl.tryitonline.net/#code=NDU6NTdpWl4hIkAhJ14oLT8oKFsxLTldXGQqKXwoWzEtOV1cZCopPyhcLlxkKlsxLTldKSl8MCkkJ1hYRA&input=NA):
```
45:57iZ^!"@!'^(-?(([1-9]\d*)|([1-9]\d*)?(\.\d*[1-9]))|0)$'XXD
```
] |
[Question]
[
# Introduction
Finally the movie company is financing your film. They have given you a maximum budget and they also set the running time of your movie.
Now you can start with the pre-production. You have a bunch of scenes already planned, but not all of them will fit into the budget and the film would get way too long as well. You know however the importance of each scene. You goal is to choose scenes, that the movie is not going to be too expensive, too long and mediocre.
# Input
You get the `running time` and the `budget` the studio has approved:
```
[25, 10]
```
You have the list of scenes including `running time`, `costs` and the `importance` for each of them:
```
[ [5, 2, 4], [7, 1, 3] ]
```
If arrays aren't working for you, choose another input format that suits your best. Times are in minutes. Budget and costs are in millions of random currency. The importance is a range from `[1–9]`. All numbers are integers.
# Output
Output the list of scenes to be included into the movie in the matter that:
* The sum of `importance` is maximized.
* The costs do not exceed the budget.
* The length is within a ±5 minutes range of the approved running time.
The order of scenes is unimportant and doesn't need to be preserved.
You can output a list of numbers or an array. Your output can have a zero- or a one-based index:
```
[0,2,5] – 0, 2, 5 – 0 2 5
[1,3,6] – 1, 3, 6 – 1 3 6
```
It may be possible, that multiple solutions apply to any given input. You only need to find one.
# Constraints
* Scenes can't be shortened nor can they get cheaper.
* Each scene can only be included once.
# Requirements
* Your program must finish in the time of the movie's actual length.
* Input is accepted from `STDIN`, command line arguments, as function parameters or from the closest equivalent.
* You can write a program or a function. If it is an anonymous function, please include an example of how to invoke it.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer in bytes wins.
* Standard loopholes are disallowed.
# Movies
Your first movie is a documentary about a small town in Germany called [Knapsack](https://en.wikipedia.org/wiki/Knapsack,_Germany)1. This city was resettled due to environmental constraints in the 70s:
```
Movie: [25, 10]
Scenes: [
[5, 2, 4],
[5, 5, 7],
[7, 1, 3],
[8, 5, 3],
[12, 3, 9],
]
```
Possible solution with running time `22`, budget `10` and an importance of `20`:
```
0, 1, 4
```
---
Your next project is an episode of [Fargo](http://www.imdb.com/title/tt2802850/):
```
Movie: [45, 25]
Scenes: [
[2, 1, 1],
[8, 5, 9],
[10, 6, 8],
[10, 3, 6],
[10, 9, 7],
[11, 4, 3],
[19, 5, 6],
]
```
Possible solution with running time `40`, budget `24` and an importance of `31`:
```
0, 1, 2, 3, 4
```
---
Finally here are the scenes for a movie where "*[M. McConaughey travels to a distant galaxy only to find out that Matt Damon got there first.](https://twitter.com/sableRaph/status/676400517917106176)*":
```
Movie: [169, 165]
Scenes: [
[5, 8, 2],
[5, 20, 6],
[6, 5, 8],
[6, 10, 3],
[7, 6, 5],
[7, 9, 4],
[7, 8, 9],
[7, 9, 5],
[8, 6, 8],
[8, 8, 8],
[8, 5, 6],
[9, 5, 6],
[9, 8, 5],
[9, 4, 6],
[9, 6, 9],
[9, 8, 6],
[9, 7, 8],
[10, 22, 4],
[10, 12, 9],
[11, 7, 9],
[11, 9, 8],
[12, 11, 5],
[15, 21, 7],
]
```
Possible solution with running time `169`, budget `165` and an importance of `133`:
```
1, 2, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22
```
---
1 Any resemblance between the challenge's problem and actual locales is entirely coincidental.
[Answer]
## MATLAB, 100 bytes
```
function X=o(m,s)
X=find(bintprog(-1*s(:,3),[s(:,2)';s(:,1)';-1*s(:,1)'],[m(2);m(1)+5;5-m(1)])==1);
```
The Binary Optimization problem is solved through the *bintprog* function, available in Matlab2013b; this function was replaced by [intlinprog](http://mathworks.com/help/optim/ug/intlinprog.html) in newer Matlab versions.
Inputs are a vector (m), for movie constraints, and a matrix (s), for the scenes. In particular m is a two-element row vector [running\_time budget], while s is a Nx3 matrix, where N is the number of the scenes and each row is made up of [running\_time costs importance].
[Answer]
# Python 3, ~~211~~ 197 bytes
This solution brute-forces every combination of scenes starting from combinations of all scenes all the way down to combinations of just one scene, then selects the combination of scenes that has maximum importance. Brute-forcing was used as the cost in time was not particularly great, though it is definitely exponential. The output is zero-indexed.
```
from itertools import*
def m(t,b,s):l=len(s);r=range(l);f=lambda y,k:sum(s[q][k]for q in y);return max([j for i in r for j in combinations(r,l-i)if t-6<f(j,0)<t+6and f(j,1)<=b],key=lambda n:f(n,2))
```
**Ungolfing:**
```
import itertools
def movie_scenes(time, budget, scenes):
length = len(s)
r = range(length)
f = lambda film_list, index: sum(scenes[q][index]for q in film_list)
importance = 0
possible_films = []
for num_scenes in r:
for film in itertools.combinations(r, num_scenes):
run_time = f(film, 0)
cost = f(film, 1)
if time-6 < run_time < time+6 and cost <= budget:
possible_films.append(film)
return max(possible_films, key = lambda film: f(film, 2)
```
[Answer]
## Haskell, 125 bytes
```
(m,n)&s=snd$maximum[(sum i,q)|q<-filter(>=0)<$>mapM(:[-1])[0..length s-1],(t,b,i)<-[unzip3$map(s!!)q],sum b<=n,abs(sum t-m)<6]
```
Usage example: `(25,10) & [(5,2,4),(5,5,7),(7,1,3),(8,5,3),(12,3,9)]` -> `[0,1,4]`.
How it works:
```
let m be the running time
n the budget
s the list of scenes
q<-filter ... s-1] -- loop q through the list of
-- subsequences of the indices of s
-- (0 based) -- details see below
map(s!!)q -- extract the elements for the
-- given indices
unzip3 -- turn the list of triples
-- into a triple of lists
(t,b,i)<-[ ] -- bind t, b and i to the lists
sum b<=n -- keep q if the sum of budgets <= n
abs(sum t-m)<6 -- and the time is within range
(sum i,q) -- for all leftover q make a pair
-- (overall importance, q)
sum$maximum -- find the maximum and drop
-- overall importance
subsequence building:
[0..length s-1] -- for all indices i of s
(:[-1]) -- make a list [i,-1]
mapM -- and make the cartesian product
-- e.g. [0,1] -> [[0,-1],[1,-1]] ->
-- [[0,1],[0,-1],[-1,1],[-1,-1]]
filter(>=0)<$> -- drop all -1
-- -> [[0,1],[0],[1],[]]
```
Found the subsequence trick a while ago in an [answer](https://codegolf.stackexchange.com/a/74118/34531) of @xnor. It's shorter than `subsequence` which requires `import Data.List`.
[Answer]
# Ruby, ~~172~~ ~~166~~ 165 bytes
I should really start checking if the Ruby versions of my Python answers are golfier before posting those Python answers. At any rate, this is the same brute-force approach to optimization as before. Any tips on golfing are welcome, including those that involve some actual optimization techniques.
```
->t,b,s{l=s.size;r=[*0...l];f=->y,k{y.reduce(0){|z,q|z+s[q][k]}};v=[];r.map{|i|r.combination(l-i).map{|j|v<<j if(t-5..t+5)===f[j,0]&&f[j,1]<=b}};v.max_by{|n|f[n,2]}}
```
**Ungolfed:**
```
def movie(time, budget, scenes)
len = scenes.size
range = [*0...len]
f = -> y,k {y.reduce(0) {|z,q| z + s[q][k]}}
potential_films = []
range.map do |i|
range.combination(len-i).map do |j|
# len - i because range being combined must be 0..(len-1) as these are indices
# but the number of elements in the combinations must be 1..len
if (time-5..time+5).include?(f[j,0]) && f[j,1] <= budget
potential_films << j
end
end
end
return potential_films.max_by{|n|f[n,2]}
end
```
] |
[Question]
[
Given input of a positive integer `n`, write a program that completes the following process.
* Find the smallest positive integer greater than `n` that is a perfect square and is the concatenation of `n` and some other number. The order of the digits of `n` may not be changed. The number concatenated onto `n` to produce a perfect square may be called `r_1`.
* If `r_1` is not a perfect square, repeat the above process with `r_1` as the new input to the process. Repeat until `r_k` is a perfect square, denoted `s`.
* Print the value of `sqrt(s)`.
Input can be taken in any format. You can assume that `n` is a positive integer. If any `r_k` has a leading zero (and `r_k`≠0), the zero can be ignored.
---
**Test cases**
Here are some test cases. The process demonstrates the above steps.
```
Input: 23
Process: 23, 2304, 4
Output: 2
Input: 10
Process: 10, 100, 0
Output: 0
Input: 1
Process: 1, 16, 6, 64, 4
Output: 2
Input: 5
Process: 5, 529, 29, 2916, 16
Output: 4
Input: 145
Process: 145, 145161, 161, 16129, 29, 2916, 16
Output: 4
Input: 1337
Process: 1337, 13373649, 3649, 36493681, 3681, 368102596, 2596, 25969216, 9216
Output: 96
```
---
This is code golf. Standard rules apply. The shortest answer (in bytes) wins.
[Answer]
# Pyth, 26 bytes
```
LsI@b2 fy=sh.fys+QZ1\0)@Q2
```
[Test suite](https://pyth.herokuapp.com/?code=LsI%40b2+fy%3Dsh.fys%2BQZ1%5C0%29s%40Q2&test_suite=1&test_suite_input=23%0A10%0A1%0A5%0A145%0A1337&debug=0)
Output is as a float. If output as an int is desired, it would be 1 extra byte.
Explanation:
```
LsI@b2 fy=sh.fys+QZ1\0)s@Q2
Q = eval(input())
L def y(b): return
@b2 Square root of b
sI Is an integer.
f ) Find the first positive integer T that satisfies
h.f 1\0 Find the first digit string Z that satisfies
+QZ Concatenation of Q and Z
s Converted to an integer
y Is a pergect square.
s Convert the string to an integer
= Assign result to the next variable in the code, Q
y Repeat until result is a perfect square
(The space) Discard return value
@Q2 Take square root of Q and print.
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 35 ~~44.0~~ bytes
```
XK``x@2^tVKVXf1=a~]VKVnQ0h)UXKX^t1\
```
[**Try it online!**](http://matl.tryitonline.net/#code=WEtgYHhAMl50VktWWGYxPWF-XVZLVm5RMGgpVVhLWF50MVw&input=MjM)
```
XK % implicit input: n. Copy to clipboard K
` % do...while. Each iteration applies the algorithm
` % do...while. Each iteration tests a candidate number
x % delete top of stack
@2^ % iteration index squared
t % duplicate
V % convert to string
K % paste from clipboard K: n or r_k
V % convert to string
Xf % find one string within another. Gives indices of starting matches, if any
1=a~ % test if some of those indices is 1. If not: next iteration
] % end. We finish with a perfect square that begins with digits of n or r_k
V % convert to string
K % paste from clipboard K: n or r_k
VnQ0h % index of rightmost characters, as determined by r_k
) % keep those figures only
U % convert to number. This is the new r_k
XK % copy to clipboard K, to be used as input to algorithm again, if needed
X^ % square root
1\ % fractional part. If not zero: apply algorithm again
% implitic do...while loop end
% implicit display
```
[Answer]
## Python 2, 98
```
i=input();d=o=9
while~-d:
n=i;d=o+1;o=i=0
while(n*d+i)**.5%1:i=-~i%d;d+=9*d*0**i
print'%d'%n**.5
```
[Try it online](http://ideone.com/yBmkTd).
[Answer]
# Python, 200 198 178 bytes
```
import math
def r(i):
j=int(i**.5)+1
while str(j*j)[:len(str(i))]!=str(i):j+=1
return int(str(j*j)[len(str(i)):])
q=r(int(input()))
while math.sqrt(q)%1!=0:q=r(q)
print(q**.5)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 26 bytes
```
{~a₀X√ℕ∧YcX∧Yh?∧Ybcℕ≜!}ⁱ√ℕ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv7ou8VFTQ8SjjlmPWqY@6lgemRwBIjPsQWRSMkiwc45i7aPGjRAl//9HGxnrGBroGOqY6hiamMYCAA "Brachylog – Try It Online")
The last test case was omitted in the TIO link because it alone takes more than a minute to execute. I ran it on my laptop and the correct result was achieved in no more than two hours.
```
{ The input
~a₀ is a prefix of
X√ X, the square root of which
ℕ is a whole number.
∧YcX Y concatenated is X.
∧Yh? The input is the first element of Y.
∧Yb The rest of Y,
c concatenated,
} is the output
ℕ which is a whole number.
≜ Make sure that it actually has a value,
! and discard all choice points.
{ }ⁱ Keep feeding that predicate its own output until
√ its output's square root
ℕ is a whole number
which is the output.
```
The second-to-last `ℕ` is necessary for when the initial input is already a perfect square, so the first perfect square which has it as a prefix is itself, and `!` is necessary to make sure that backtracking iterates instead of finding a larger concatenated square, but I don't really know why `≜` is necessary, I just know that 5 produces a wrong answer without it.
[Answer]
# [Perl 6](http://perl6.org), 101 bytes
```
my&q={$^k;$_=({++($||=$k.sqrt.Int)**2}.../^$k/)[*-1];+S/$k//}
put (q(get),&q...!(*.sqrt%1))[*-1].sqrt
```
```
my &q = {
$^k; # declare placeholder parameter
# set default scalar to:
$_ = ( # a list
# code block that generates every perfect square
# larger than the input
{ ++( $ ||= $k.sqrt.Int )**2 }
... # produce a sequence
/^$k/ # ending when it finds one starting with the argument
)[*-1]; # last value in sequence
# take the last value and remove the argument
# and turn it into a number to remove leading zeros
+S/$k//
}
put ( # print the result of:
q(get), # find the first candidate
&q # find the rest of them
... # produce a sequence
!(*.sqrt%1) # ending with a perfect square
)[*-1] # last value in sequence
.sqrt # find the sqrt
```
[Answer]
## ES7, 116 bytes
```
n=>{do{for(i=n;!(r=(''+Math.ceil((i*=10)**0.5)**2)).startsWith(+n););n=r.replace(+n,'');r=n**0.5}while(r%1);return r}
```
Yes, I could probably save a byte by using `eval`.
] |
[Question]
[
This question is inspired by ongoing tournament of "the hooligan's game played by gentlemen", the [Rugby World Cup](https://en.wikipedia.org/wiki/2015_Rugby_World_Cup), which has just completed the pool stage. There are 20 teams in the tournament, and they are divided into 4 pools of 5 teams each. During the pool stage each team plays against all the other teams in their pool (a total of 10 matches per pool), and the top 2 teams of each pool progress to the knockout stage.
At the end of the pool stage there is a table for each pool showing the number of wins, losses and draws for each team. The challenge for this question is to write a program that inputs the count of wins, losses and draws for each team in a pool, and from that information outputs the individual results of each of the 10 matches (who won, lost or drew against who) if possible or outputs an error message if not.
For example, here is the table for Pool D of this year's tournament:
```
Win Loss Draw
Canada 0 4 0
France 3 1 0
Ireland 4 0 0
Italy 2 2 0
Romania 1 3 0
```
From this information, we can deduce that Ireland won against Canada, France, Italy and Romania, because they won all their games. France must have won against Canada, Italy and Romania but lost to Ireland, because they only lost one and it must have been to the undefeated Ireland. We have just worked out that Italy lost to Ireland and France, so they must have won against Canada and Romania. Canada lost all their games, and so Romania's win must have been against Canada.
```
Canada France Ireland Italy Romania
Canada - L L L L
France W - L W W
Ireland W W - W W
Italy W L L - W
Romania W L L L -
```
Here's a more complicated (fictional) example:
```
Win Loss Draw
Canada 3 1 0
France 1 2 1
Ireland 0 3 1
Italy 0 2 2
Romania 4 0 0
```
In this case, we can deduce that Romania won against Canada, France, Italy and Ireland, because they won all their games. Canada must have won against Ireland, Italy and France but lost to Romania. We have just worked out that Italy lost to Romania and Canada, so they must have drawn against France and Ireland. That means Ireland drew with Italy and lost to everyone else, and therefore France must have beaten Ireland, drawn with Italy and lost to Canada and Romania.
```
Canada France Ireland Italy Romania
Canada - W W W L
France L - W D L
Ireland L L - D L
Italy L D D - L
Romania W W W W -
```
Some tables are unsolvable, for example this year's Pool B, in which 3 teams got the same W/L/D totals:
```
Win Loss Draw
Japan 3 1 0
Samoa 1 3 0
Scotland 3 1 0
South Africa 3 1 0
United States 0 4 0
```
However some tables with duplicate rows are solvable, like this (fictional) one:
```
Win Loss Draw
Japan 4 0 0
Samoa 0 3 1
Scotland 2 2 0
South Africa 0 3 1
United States 3 1 0
```
# Input
Your program or function should accept 15 numbers specifying the win, loss and draw totals for each of the 5 teams. You can use any delimiter you want, input the numbers in row or column major order, and accept the numbers either via stdin or passed via an array to a function.
Because wins + losses + draws = 4, you can omit one of the values and work it out from the others if you wish, meaning that you only have to input 10 numbers.
You don't need to input any team names.
*Sample input:*
```
3 1 0
1 2 1
0 3 1
0 2 2
4 0 0
```
# Output
Your program or function's output should be in the form of a 5 x 5 grid printed to stdout, or an array returned from a function. Each element should specify whether the team given in the row position won, lost or drew against the team in the column position. The row ordering for the output should match the input. You can define what denotes a win, loss or draw, so the letters W, L, D or digits 0 1 2 or whatever you want can be used as long as they are clearly defined and can be distinguished from each other. Diagonal elements are undefined, you can output anything, but it should be the same in each case. Values can be separated with commas, spaces or whatever character you like, or not character. Both input and output can be formatted with all values on a single line if desired.
If a table does not have a unique solution then you must output a simple error message of your choice.
*Sample output:*
```
- W W W L
L - W D L
L L - D L
L D D - L
W W W W -
```
*Sample output for unsolvable table:*
```
dunno mate
```
This is code golf so the shortest program in bytes wins.
Pic related (Japan versus South Africa):
[](https://i.stack.imgur.com/NiJ7z.jpg)
[Answer]
# CJam, ~~57~~ ~~49~~ ~~47~~ 45 bytes
```
{JZb:af{.*e_1+e!}:m*:e_5f/{_z2\ff-=},_,(0@?~}
```
This is an anonymous function that pops a two-dimensional array from the stack and leaves one in return. It contains `2` for wins, `1` for draws and `0` for losses. It also contains `1` for diagonal elements , for which *you can output anything*. If the problem isn't solvable, the function returns `-1`.
The code will work online, but it will take a while. Try it in the [CJam interpreter](http://cjam.aditsu.net/#code=%5Bq~%5D3%2F%20%20%20e%23%20Read%20and%20format%20input.%0A%0A%7BJZb%3Aaf%7B.*e_1%2Be!%7D%3Am*%3Ae_5f%2F%7B_z2%5Cff-%3D%7D%2C_%2C(0%40%3F~%7D%0A%0A~L%2B%3Ap%20%20%20%20e%23%20Call%20the%20function.%20Print%20output.&input=3%201%200%0A1%202%201%0A0%203%201%0A0%202%202%0A4%200%200).
### Test run
```
$ cat input
3 1 0
1 2 1
0 3 1
0 2 2
4 0 0
$ time cjam results.cjam < input
[1 2 2 2 0]
[0 1 2 1 0]
[0 0 1 1 0]
[0 1 1 1 0]
[2 2 2 2 1]
real 0m1.584s
user 0m4.020s
sys 0m0.146s
```
### How it works
```
JZb:a e# Push 19 in base 3; wrap each digit in an array. Pushes [[2] [0] [1]].
f{ e# For each row of the input, push it and [[2] [0] [1]]; then:
.* e# Repeat 2, 0 and 1 (win, loss, draw) the specified number of times.
e_ e# Flatten the resulting array.
1+ e# Append a 1 for the diagonal.
e! e# Push all possible permutations.
} e#
:m* e# Cartesian product; push all possible combinations of permutations.
:e_ e# Flatten the results.
5f/ e# Split into rows of length 5.
{ e# Filter:
_z e# Push a transposed copy of the array.
2\ e# Swap the result with 2.
ff- e# Subtract all elements from 2.
= e# Check for equality.
}, e# Keep the element if `=' pushed 1.
_,( e# Get the length of the array of solutions and subtract 1.
0@? e# Keep the array for length 1, push 0 otherwise.
~ e# Either dump the singleton array or turn 0 into -1.
```
[Answer]
# Haskell, ~~180~~ 177 bytes
```
import Data.List
z=zipWith
m=map
a#b|(c,d)<-splitAt a b=c++[0]++d
f t=take 1[x|x<-m(z(#)[0..])$sequence$m(permutations.concat.z(flip replicate)[1,-1,0])t,transpose x==m(m(0-))x]
```
A win is shown as `1`, a loss as `-1` and a draw as `0`. Diagonal elements are also `0`. Unsolvable tables are empty lists, i.e. `[]`.
Usage example: `f [[3,1,0],[1,2,1],[0,3,1],[0,2,2],[4,0,0]]` -> `[[[0,1,1,1,-1],[-1,0,1,0,-1],[-1,-1,0,0,-1],[-1,0,0,0,-1],[1,1,1,1,0]]]`.
How it works: brute force! Create a list of wins/losses/draws according to the input, e.g. `[3,1,0]` -> `[1,1,1,-1]`, permute, build all combinations, insert diagonals and keep all tables that are equal to their transposition with all elements negated. Take the first one.
] |
[Question]
[
Your task is to solve the [Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem) for **n** strings of length 1000.
A valid solution to the LCS problem for two or more strings **S1, … Sn** is any string **T** of maximal length such that the characters of **T** appear in all **Si**, in the same order as in **T**.
Note that **T** does not have to be a sub*string* of **Si**.
We've already solved this problem in the [shortest amount of code](https://codegolf.stackexchange.com/q/52808). This time, size doesn't matter.
### Example
The strings `axbycz` and `xaybzc` have 8 common subsequences of length 3:
```
abc abz ayc ayz xbc xbz xyc xyz
```
Any of these would be a valid solution for the LCS problem.
### Details
Write a full program that solves the LCS problem, as explained above, abiding the following rules:
* The input will consist of two or more strings of length 1000, consisting of ASCII characters with code points between 0x30 and 0x3F.
* You have to read the input from STDIN.
You have two choices for the input format:
+ Each string (including the last) is followed by a linefeed.
+ The strings are chained together with no separator and no trailing linefeed.
* The number of strings will be passed as a command-line parameter to your program.
* You have to write the output, i.e., any one of the valid solutions to the LCS, to STDOUT, followed by one linefeed.
* Your language of choice has to have a free (as in beer) compiler/interpreter for my operating system (Fedora 21).
* If you require any compiler flags or a specific interpreter, please mention it in your post.
### Scoring
I will run your code with 2, 3, etc. strings until it takes longer than 120 seconds to print a valid solution. This means that you have 120 seconds for *each* value of **n**.
The highest amount of strings for which your code finished in time is your score.
In the event of a tied score of **n**, the submission that solved the problem for **n** strings in the shortest time will be declared the winner.
All submissions will be timed on *my* machine (Intel Core i7-3770, 16 GiB RAM, no swap).
The **n** strings of the **(n-1)**th test will be generated by calling `rand n` (and stripping the linefeeds, if requested), where `rand` is defined as follows:
```
rand()
{
head -c$[500*$1] /dev/zero |
openssl enc -aes-128-ctr -K 0 -iv $1 |
xxd -c500 -ps |
tr 'a-f' ':-?'
}
```
The key is `0` in the above code, but I reserve the right to change it to an undisclosed value if I suspect anybody of (partially) hardcoding the output.
[Answer]
# C, n = 3 in ~7 seconds
### Algorithm
The algorithm is a direct generalization of the standard dynamic programming solution to `n` sequences. For 2 strings `A` and `B`, the standard recurrence looks like this:
```
L(p, q) = 1 + L(p - 1, q - 1) if A[p] == B[q]
= max(L(p - 1, q), L(p, q - 1)) otherwise
```
For 3 strings `A`, `B`, `C` I use:
```
L(p, q, r) = 1 + L(p - 1, q - 1, r - 1) if A[p] == B[q] == C[r]
= max(L(p - 1, q, r), L(p, q - 1, r), L(p, q, r - 1)) otherwise
```
The code implements this logic for arbitrary values of `n`.
### Efficiency
The complexity of my code is O(s ^ n), with `s` the length of the strings. Based on what I found, it looks like the problem is NP-complete. So while the posted algorithm is very inefficient for larger values of `n`, it might actually not be possible to do massively better. The only thing I saw are some approaches that improve efficiency for small alphabets. Since the alphabet is moderately small here (16), that could lead to an improvement. I still predict that nobody will find a legitimate solution that goes higher than `n = 4` in 2 minutes, and `n = 4` looks ambitious already.
I reduced the memory usage in the initial implementation, so that it could handle `n = 4` given enough time. But it only produced the length of the sequence, not the sequence itself. Check the revision history of this post for seeing that code.
### Code
Since loops over n-dimensional matrices require more logic than fixed loops, I'm using a fixed loop for the lowest dimension, and only use the generic looping logic for the remaining dimensions.
```
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define N_MAX 4
int main(int argc, char* argv[]) {
int nSeq = argc - 1;
if (nSeq > N_MAX) {
nSeq = N_MAX;
}
char** seqA = argv + 1;
uint64_t totLen = 1;
uint64_t lenA[N_MAX] = {0};
uint64_t offsA[N_MAX] = {1};
uint64_t offsSum = 0;
uint64_t posA[N_MAX] = {0};
for (int iSeq = 0; iSeq < nSeq; ++iSeq) {
lenA[iSeq] = strlen(seqA[iSeq]);
totLen *= lenA[iSeq] + 1;
if (iSeq + 1 < nSeq) {
offsA[iSeq + 1] = totLen;
}
offsSum += offsA[iSeq];
}
uint16_t* mat = calloc(totLen, 2);
uint64_t idx = offsSum;
for (;;) {
for (uint64_t pos0 = 0; pos0 < lenA[0]; ++pos0) {
char firstCh = seqA[0][pos0];
int isSame = 1;
uint16_t maxVal = mat[idx - 1];
for (int iSeq = 1; iSeq < nSeq; ++iSeq) {
char ch = seqA[iSeq][posA[iSeq]];
isSame &= (ch == firstCh);
uint16_t val = mat[idx - offsA[iSeq]];
if (val > maxVal) {
maxVal = val;
}
}
if (isSame) {
mat[idx] = mat[idx - offsSum] + 1;
} else {
mat[idx] = maxVal;
}
++idx;
}
idx -= lenA[0];
int iSeq = 1;
while (iSeq < nSeq && posA[iSeq] == lenA[iSeq] - 1) {
posA[iSeq] = 0;
idx -= (lenA[iSeq] - 1) * offsA[iSeq];
++iSeq;
}
if (iSeq == nSeq) {
break;
}
++posA[iSeq];
idx += offsA[iSeq];
}
int score = mat[totLen - 1];
char* resStr = malloc(score + 1);
resStr[score] = '\0';
for (int iSeq = 0; iSeq < nSeq; ++iSeq) {
posA[iSeq] = lenA[iSeq] - 1;
}
idx = totLen - 1;
int resIdx = score - 1;
while (resIdx >= 0) {
char firstCh = seqA[0][posA[0]];
int isSame = 1;
uint16_t maxVal = mat[idx - 1];
int maxIdx = 0;
for (int iSeq = 1; iSeq < nSeq; ++iSeq) {
char ch = seqA[iSeq][posA[iSeq]];
isSame &= (ch == firstCh);
uint16_t val = mat[idx - offsA[iSeq]];
if (val > maxVal) {
maxVal = val;
maxIdx = iSeq;
}
}
if (isSame) {
resStr[resIdx--] = firstCh;
for (int iSeq = 0; iSeq < nSeq; ++iSeq) {
--posA[iSeq];
}
idx -= offsSum;
} else {
--posA[maxIdx];
idx -= offsA[maxIdx];
}
}
free(mat);
printf("score: %d\n", score);
printf("%s\n", resStr);
return 0;
}
```
### Instructions for Running
To run:
* Save the code in a file, e.g. `lcs.c`.
* Compile with high optimization options. I used:
```
clang -O3 lcs.c
```
On Linux, I would try:
```
gcc -Ofast lcs.c
```
* Run with 2 to 4 sequences given as command line arguments:
```
./a.out axbycz xaybzc
```
Single quote the command line arguments if necessary, since the alphabet used for the examples contains shell special characters.
### Results
`test2.sh` and `test3.sh` are the test sequences from Dennis. I don't know the correct results, but the output looks at least plausible.
```
$ ./a.out axbycz xaybzc
score: 3
abc
$ time ./test2.sh
score: 391
16638018802020>3??3232270178;47240;24331395?<=;99=?;178675;866002==23?87?>978891>=9<6<9381992>>7030829?255>6804:=3>:;60<9384=081;0:?66=51?0;5090724<85?>>:2>7>3175?::<9199;5=0:494<5<:7100?=95<91>1887>33>67710==;48<<327::>?78>77<6:2:02:<7=5?:;>97<993;57=<<=:2=9:8=118563808=962473<::8<816<464<1==925<:5:22?>3;65=>=;27?7:5>==3=4>>5>:107:20575347>=48;<7971<<245<??219=3991=<96<??735698;62?<98928
real 0m0.012s
user 0m0.008s
sys 0m0.003s
$ time ./test3.sh
score: 269
662:2=2::=6;738395=7:=179=96662649<<;?82?=668;2?603<74:6;2=04=>6;=6>=121>1>;3=22=3=3;=3344>0;5=7>>7:75238;559133;;392<69=<778>3?593?=>9799<1>79827??6145?7<>?389?8<;;133=505>2703>02?323>;693995:=0;;;064>62<0=<97536342603>;?92034<?7:=;2?054310176?=98;5437=;13898748==<<?4
real 0m7.218s
user 0m6.701s
sys 0m0.513s
```
[Answer]
# This answer is currently broken due to a bug. Fixing soon...
# ~~C, 2 strings in ~35 seconds~~
This is very much a work in progress (as shown by the horrible messiness), but hopefully it sparks some good answers!
The code:
```
#include "stdlib.h"
#include "string.h"
#include "stdio.h"
#include "time.h"
/* For the versatility */
#define MIN_CODEPOINT 0x30
#define MAX_CODEPOINT 0x3F
#define NUM_CODEPOINT (MAX_CODEPOINT - MIN_CODEPOINT + 1)
#define CTOI(c) (c - MIN_CODEPOINT)
#define SIZE_ARRAY(x) (sizeof(x) / sizeof(*x))
int LCS(char** str, int num);
int getshared(char** str, int num);
int strcount(char* str, char c);
int main(int argc, char** argv) {
char** str = NULL;
int num = 0;
int need_free = 0;
if (argc > 1) {
str = &argv[1];
num = argc - 1;
}
else {
scanf(" %d", &num);
str = malloc(sizeof(char*) * num);
if (!str) {
printf("Allocation error!\n");
return 1;
}
int i;
for (i = 0; i < num; i++) {
/* No string will exceed 1000 characters */
str[i] = malloc(1001);
if (!str[i]) {
printf("Allocation error!\n");
return 1;
}
scanf(" %1000s", str[i]);
str[i][1000] = '\0';
}
need_free = 1;
}
clock_t start = clock();
/* The call to LCS */
int size = LCS(str, num);
double dt = ((double)(clock() - start)) / CLOCKS_PER_SEC;
printf("Size: %d\n", size);
printf("Elapsed time on LCS call: %lf s\n", dt);
if (need_free) {
int i;
for (i = 0; i < num; i++) {
free(str[i]);
}
free(str);
}
return 0;
}
/* Some terribly ugly global variables... */
int depth, maximum, mapsize, lenmap[999999][2];
char* (strmap[999999][20]);
char outputstr[1000];
/* Solves the LCS problem on num strings str of lengths len */
int LCS(char** str, int num) {
/* Counting variables */
int i, j;
if (depth + getshared(str, num) <= maximum) {
return 0;
}
char* replace[num];
char match;
char best_match = 0;
int earliest_set = 0;
int earliest[num];
int all_late;
int all_early;
int future;
int best_future = 0;
int need_future = 1;
for (j = 0; j < mapsize; j++) {
for (i = 0; i < num; i++)
if (str[i] != strmap[j][i])
break;
if (i == num) {
best_match = lenmap[j][0];
best_future = lenmap[j][1];
need_future = 0;
if (best_future + depth < maximum || !best_match)
goto J;
else {
match = best_match;
goto K;
}
}
}
for (match = MIN_CODEPOINT; need_future && match <= MAX_CODEPOINT; match++) {
K:
future = 1;
all_late = earliest_set;
all_early = 1;
for (i = 0; i < num; replace[i++]++) {
replace[i] = strchr(str[i], match);
if (!replace[i]) {
future = 0;
break;
}
if (all_early && earliest_set && replace[i] - str[i] > earliest[i])
all_early = 0;
if (all_late && replace[i] - str[i] < earliest[i])
all_late = 0;
}
if (all_late) {
future = 0;
}
I:
if (future) {
if (all_early || !earliest_set) {
for (i = 0; i < num; i++) {
earliest[i] = (int)(replace[i] - str[i]);
}
}
/* The recursive bit */
depth++;
future += LCS(replace, num);
depth--;
best_future = future > best_future ? (best_match = match), future : best_future;
}
}
if (need_future) {
for (i = 0; i < num; i++)
strmap[mapsize][i] = str[i];
lenmap[mapsize][0] = best_match;
lenmap[mapsize++][1] = best_future;
}
J:
if (depth + best_future >= maximum) {
maximum = depth + best_future;
outputstr[depth] = best_match;
}
if (!depth) {
mapsize = 0;
maximum = 0;
puts(outputstr);
}
return best_future;
}
/* Return the number of characters total (not necessarily in order) that the strings all share */
int getshared(char** str, int num) {
int c, i, tot = 0, min;
for (c = MIN_CODEPOINT; c <= MAX_CODEPOINT; c++) {
min = strcount(str[0], c);
for (i = 1; i < num; i++) {
int count = strcount(str[i], c);
if (count < min) {
min = count;
}
}
tot += min;
}
return tot;
}
/* Count the number of occurrences of c in str */
int strcount(char* str, char c) {
int tot = 0;
while ((str = strchr(str, c))) {
str++, tot++;
}
return tot;
}
```
The relevant function that performs all of the LCS computation is the function `LCS`. The code above will time its own call to this function.
Save as `main.c` and compile with: `gcc -Ofast main.c -o FLCS`
The code can be ran either with command line arguments or through stdin. When using stdin, it expects a number of strings followed by the strings themselves.
```
~ Me$ ./FLCS "12345" "23456"
2345
Size: 4
Elapsed time on LCS call: 0.000056 s
```
Or:
```
~ Me$ ./FLCS
6
2341582491248123139182371298371239813
2348273123412983476192387461293472793
1234123948719873491234120348723412349
1234129388234888234812834881423412373
1111111112341234128469128377293477377
1234691237419274737912387476371777273
1241231212323
Size: 13
Elapsed time on LCS call: 0.001594 s
```
On a Mac OS X box with a 1.7Ghz Intel Core i7 and the test case Dennis provided, we get the following output for 2 strings:
```
16638018800200>3??32322701784=4240;24331395?<;=99=?;178675;866002==23?87?>978891>=9<66=381992>>7030829?25265804:=3>:;60<9384=081;08?66=51?0;509072488>2>924>>>3175?::<9199;330:494<51:>748571?153994<45<??20>=3991=<962508?7<2382?489
Size: 386
Elapsed time on LCS call: 33.245087 s
```
The approach is very similar to my approach to the earlier challenge, [here](https://codegolf.stackexchange.com/a/52860/31054). In addition to previous optimization, we now check for a total number of shared characters between strings at every recursion and exit early if there's no way to get a longer substring than what already exists.
For now, it handles 2 strings okay but tends to get crash-y on more. More improvements and a better explanation to come!
] |
[Question]
[
Is there a way in Golfscript to bring all of the diagonals of an array into a single array?
For example, for the array
```
[[1 2 3][4 5 6][7 8 9]]
```
return
```
[[7][4 8][1 5 9][2 6][3]]
```
(not necessarily in that order) and for
```
["ABCD""EFGH""IJKL"]
```
return
```
["I""EJ""AFK""BGL""CH""D"]
```
(not necessarily in that order). Assume the lengths of the arrays are the same.
I am struggling with figuring it out. I tried doing something with `=` and iterating through the `(length+1)`th character of the strings, but that didn't work. Can someone help me?
I'd like the shortest way to do this, if possible.
[Answer]
Consider
```
[
"ABCD"
"EFGH"
"IJKL"
]
```
To obtain the main diagonal and the diagonals above it, we can shift out the first char of the second row and the first two of the third:
```
[
"ABCD"
"FGH"
"KL"
]
```
Note that all columns correspond to a diagonal, so "zipping" the array (i.e., transposing rows and columns) will yield an array containing the aforementioned four diagonals:
```
[
"AFK"
"BGL"
"CH"
"D"
]
```
We're still missing the diagonals below the main diagonal.
If we zip A itself and repeat the above process, we'll obtain an array containing the main diagonal and all diagonals *below* it. All that's left it to compute the set union of both arrays.
Putting it all together:
```
[.zip]{:A,,{.A=>}%zip}/|
[.zip]{ }/ # For the original array and it's transpose, do the following:
:A # Store the array in A.
,,{ }% # For each I in [ 0 1 ... len(A) ], do the following:
.A=> # Push A[I] and shift out its first I characters.
zip # Transpose the resulting array.
| # Perform set union.
```
[Try it online.](http://golfscript.apphb.com/?c=WyJBQkNEIiJFRkdIIiJJSktMIl1bLnppcF17OkEsLHsuQT0%2BfSV6aXB9L3xg "Web GolfScript")
Finally, if we only need the diagonals because we're searching for a string inside them (like in the [Word Search Puzzle](https://codegolf.stackexchange.com/q/37940), which I assume inspired this question), a "less clean" approach might also be suitable.
You can use
```
..,n**\.0=,\,+)/zip
```
to obtain all diagonals, plus some unnecessary linefeed characters.
I've explained the process in detail in [this answer](https://codegolf.stackexchange.com/a/37945).
[Try it online.](http://golfscript.apphb.com/?c=WyJBQkNEIiJFRkdIIiJJSktMIl0uLixuKipcLjA9LFwsKykvemlwYA%3D%3D "Web GolfScript")
] |
[Question]
[
## Problem
Imagine 7 buckets lined up in a row. Each bucket can contain at most 2 apples.
There are 13 apples labeled 1 through 13. They are distributed among the 7
buckets. For example,
```
{5,4}, {8,10}, {2,9}, {13,3}, {11,7}, {6,0}, {12,1}
```
Where 0 represents the empty space. The order in which the apples appear *within*
each bucket is not relevant (e.g. {5,4} is equivalent to {4,5}).
You can move any apple from one bucket to an adjacent bucket, provided there is
room in the destination bucket for another apple. Each move is described by the
number of the apple you wish to move (which is unambiguous because there is only one empty space). For example, applying the move
```
7
```
to the arrangement above would result in
```
{5,4}, {8,10}, {2,9}, {13,3}, {11,0}, {6,7}, {12,1}
```
## Objective
Write a program that reads an arrangement from STDIN and sorts it into the
following arrangement
```
{1,2}, {3,4}, {5,6}, {7,8}, {9,10}, {11,12}, {13,0}
```
using as few moves as possible. Again, the order in which the apples appear
*within* each bucket is not relevant. The order of the buckets does matter. It should output the moves used to sort each arrangement seperated by commas. For example,
```
13, 7, 6, ...
```
Your score is equal to the sum of the number of moves required to solve the following arrangements:
```
{8, 2}, {11, 13}, {3, 12}, {6, 10}, {4, 0}, {1, 7}, {9, 5}
{3, 1}, {6, 9}, {7, 8}, {2, 11}, {10, 5}, {13, 4}, {12, 0}
{0, 2}, {4, 13}, {1, 10}, {11, 6}, {7, 12}, {8, 5}, {9, 3}
{6, 9}, {2, 10}, {7, 4}, {1, 8}, {12, 0}, {5, 11}, {3, 13}
{4, 5}, {10, 3}, {6, 9}, {8, 13}, {0, 2}, {1, 7}, {12, 11}
{4, 2}, {10, 5}, {0, 7}, {9, 8}, {3, 13}, {1, 11}, {6, 12}
{9, 3}, {5, 4}, {0, 6}, {1, 7}, {12, 11}, {10, 2}, {8, 13}
{3, 4}, {10, 9}, {8, 12}, {2, 6}, {5, 1}, {11, 13}, {7, 0}
{10, 0}, {12, 2}, {3, 5}, {9, 11}, {1, 13}, {4, 8}, {7, 6}
{6, 1}, {3, 5}, {11, 12}, {2, 10}, {7, 4}, {13, 8}, {0, 9}
```
Yes, each of these arrangements has a solution.
## Rules
* Your solution must run in polynomial time in the number of buckets per move. The point is to use clever heuristics.
* All algorithms must be deterministic.
* In the event of a tie, the shortest byte count wins.
[Answer]
# Score: 448
My idea is to sort them consecutively, starting with 1. This gives us the nice property that when we want to move the space to the previous/next basket, we know exactly which of the two apples there we have to move - the max/min one, respectively. Here is the test breakdown:
```
#1: 62 #6: 40
#2: 32 #7: 38
#3: 46 #8: 50
#4: 50 #9: 54
#5: 40 #10: 36
Total score: 448 moves
```
The code can be golfed a lot more, but better quality of the code will motivate additional answers.
# C++ (501 bytes)
```
#include <cstdio>
#define S(a,b) a=a^b,b=a^b,a=a^b;
int n=14,a[14],i,j,c,g,p,q;
int l(int x){for(j=0;j<n;++j)if(a[j]==x)return j;}
int sw(int d){
p=l(0);q=p+d;
if(a[q]*d>a[q^1]*d)q^=1;
printf("%d,", a[q]);
S(a[q],a[p])
}
int main(){
for(;j<n;scanf("%d", a+j),j++);
for(;++i<n;){
c=l(i)/2;g=(i-1)/2;
if(c-g){
while(l(0)/2+1<c)sw(2);
while(l(0)/2>=c)sw(-2);
while(l(i)/2>g){sw(2);if(l(i)/2>g){sw(-2);sw(-2);}}
}
}
}
```
Further improvements may be switching to C and trying to lower the score by starting from the large values downwards (and them eventually combining both solutions).
[Answer]
## C, ~~426~~ 448
This sorts apples one at a time from 1 to 13 similar to [yasen's method](https://codegolf.stackexchange.com/a/37760/31002), except whenever it has an opportunity to move a larger number up or a smaller number down, it will take it. ~~Sadly, this only improves performance on the first test problem, but its a small improvement.~~ I made a mistake when running the test problems. It seems I've simply reimplemented yasen's method.
```
#1: 62 #6: 40
#2: 32 #7: 38
#3: 46 #8: 50
#4: 50 #9: 54
#5: 40 #10: 36
```
It takes input without braces or commas, e.g.
```
8 2 11 13 3 12 6 10 4 0 1 7 9 5
```
Here is the golfed code coming in at 423 bytes counting a few unnecessary newlines (could probably be golfed more, but I expect this score to be beaten):
```
#define N 7
#define F(x,y) for(y=0;y<N*2;y++)if(A[y]==x)break;
#define S(x,y) x=x^y,y=x^y,x=x^y;
#define C(x,y) ((A[x*2]==y)||(A[x*2+1]==y))
A[N*2],i,j,d,t,b,a,n,s,v,u,w,g;main(){for(;i<N*2;i++)scanf("%d",A+i);g=1;while
(!v){F(0,i);b=i/2;F(g,u);w=u/2;d=b<w?1:-1;n=(b+d)*2;a=(b+d)*2+1;if(A[n]>A[a])
S(n,a);t=d-1?a:n;printf("%d,",A[t]);S(A[i],A[t]);while(C((g-1)/2,g))g++;v=1;for
(j=0;j<N*2;j++)if(!C(j/2,(j+1)%(N*2)))v=0;}}
```
And the ungolfed code, which also prints the score:
```
#include <stdio.h>
#include <stdlib.h>
#define N 7
int apples[N*2];
int find(int apple)
{
int i;
for (i = 0; i < N*2; i++) {
if (apples[i] == apple)
return i;
}
}
void swap(int i, int j)
{
int temp;
temp = apples[i];
apples[i] = apples[j];
apples[j] = temp;
}
int contains(int bucket, int apple)
{
if ((apples[bucket * 2] == apple) || (apples[bucket * 2 + 1] == apple))
return 1;
return 0;
}
int is_solved()
{
int i, j;
for (i = 0; i < N * 2; i++) {
j = (i + 1) % (N * 2);
if (!contains(i / 2, j))
return 0;
}
return 1;
}
int main()
{
int i, j, dir, bucket, max, min, score;
int target_i, target_bucket, target;
/* Read the arrangement */
for (i = 0; i < N*2; i++) {
scanf("%d ", apples + i);
}
target = 1;
while (1) {
i = find(0);
bucket = i / 2;
target_i = find(target);
target_bucket = target_i / 2;
/* Change the direction of the sort if neccesary */
if (bucket < target_bucket) dir = 1;
else dir = -1;
/* Find the biggest and smallest apple in the next bucket */
if (apples[(bucket + dir) * 2] < apples[(bucket + dir) * 2 + 1]) {
min = (bucket + dir) * 2;
max = (bucket + dir) * 2 + 1;
} else {
min = (bucket + dir) * 2 + 1;
max = (bucket + dir) * 2;
}
/* If we're going right, move the smallest apple. Otherwise move the
biggest apple */
if (dir == 1) {
printf("%d, ", apples[min]);
swap(i, min);
score++;
} else {
printf("%d, ", apples[max]);
swap(i, max);
score++;
}
/* Find the next apple to sort */
while (contains((target - 1) / 2, target))
target++;
/* If we've solved it then quit */
if (is_solved())
break;
}
printf("\n");
printf("%d\n", score);
}
```
[Answer]
# Python 3 - 121
This implements a depth-first searching with increasing depth until it finds a solution. It uses a dictionary to store visited states so that it doesn't visit them again unless with a higher depth window. When deciding which states to check, it uses the number of misplaced elements as a heuristic, and only visits the best states possible. Note that since the order of the elements within their bucket does not matter, it always maintains an ordering within the buckets. This makes it easier to check if an element is misplaced.
The input is an array of ints, with the first int being the number of buckets.
So for instance, for #8 (this one takes a very long time to run on my machine, the others finish in seconds):
```
c:\python33\python.exe apples.py 7 3 4 10 9 8 12 2 6 5 1 11 13 7 0
```
Here are the results on the test set:
#1: 12,
#2: 12,
#3: 12,
#4: 12,
#5: 11,
#6: 11,
#7: 10,
#8: 14,
#9: 13,
#10: 14
Here is the code:
```
import sys
BUCKETS = int(sys.argv[1])
# cleans a state up so it is in order
def compressState(someState):
for i in range(BUCKETS):
if(someState[2*i] > someState[2*i + 1]):
temp = someState[2*i]
someState[2*i] = someState[2*i + 1]
someState[2*i + 1] = temp
return someState
state = compressState([int(x) for x in sys.argv[2:]])
print('Starting to solve', state)
WINNINGSTATE = [x for x in range(1, BUCKETS*2 - 1)]
WINNINGSTATE.append(0)
WINNINGSTATE.append(BUCKETS*2 - 1)
maxDepth = 1
winningMoves = []
triedStates = {}
# does a depth-first search
def doSearch(curState, depthLimit):
if(curState == WINNINGSTATE):
return True
if(depthLimit == 0):
return False
myMoves = getMoves(curState)
statesToVisit = []
for move in myMoves:
newState = applyMove(curState, move)
tns = tuple(newState)
# do not visit a state again unless it is at a higher depth (more chances to win from it)
if(not ((tns in triedStates) and (triedStates[tns] >= depthLimit))):
triedStates[tns] = depthLimit
statesToVisit.append((move, newState[:], stateScore(newState)))
statesToVisit.sort(key=lambda stateAndScore: stateAndScore[2])
for stv in statesToVisit:
if(stv[2] > statesToVisit[0][2]):
continue
if(doSearch(stv[1], depthLimit - 1)):
winningMoves.insert(0, stv[0])
return True
return False
# gets the moves you can make from a given state
def getMoves(someState):
# the only not-allowed moves involve the bucket with the 0
allowedMoves = []
for i in range(BUCKETS):
if((someState[2*i] != 0) and (someState[2*i + 1] != 0)):
allowedMoves.append(someState[2*i])
allowedMoves.append(someState[2*i + 1])
return allowedMoves
# applies a move to a given state, returns a fresh copy of the new state
def applyMove(someState, aMove):
newState = someState[:]
for i in range(BUCKETS*2):
if(newState[i] == 0):
zIndex = i
if(newState[i] == aMove):
mIndex = i
if(mIndex % 2 == 0):
newState[mIndex] = 0
else:
newState[mIndex] = newState[mIndex-1]
newState[mIndex-1] = 0
newState[zIndex] = aMove
if((zIndex % 2 == 0) and (newState[zIndex] > newState[zIndex+1])):
newState[zIndex] = newState[zIndex+1]
newState[zIndex+1] = aMove
return newState
# a heuristic for how far this state is from being sorted
def stateScore(someState):
return sum([1 if someState[i] != WINNINGSTATE[i] else 0 for i in range(BUCKETS*2)])
# go!
while(True):
triedStates[tuple(state)] = maxDepth
print('Trying depth', maxDepth)
if(doSearch(state, maxDepth)):
print('winning moves are: ', winningMoves)
break
maxDepth += 1
```
] |
[Question]
[
Given this text
>
> Lorem ipsum dolor sit amet, consectetur adipisicing 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 nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
>
>
>
write the shortest program that produces the same text justified at 80 character. The above text must look exactly as:
```
Lorem ipsum dolor sit amet, consectetur adipisicing 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 nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
```
**Rules:**
* words must not be cut
* extra spaces must be added
+ after a dot.
+ after a comma
+ after the shortest word (from left to right)
+ the result must not have more than 2 consecutive spaces
* last line is not justified.
* lines must not begin with comma or dot.
* provide the output of your program
**winner:** The shortest program.
**note:** The input string is provided on STDIN as one line (no line feed or carriage return)
**update:**
The input string can be any text with word length reasonnable (ie. not more than 20~25 char) such as:
>
> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices diam. Maecenas ligula massa, varius a, semper congue, euismod non, mi. Proin porttitor, orci nec nonummy molestie, enim est eleifend mi, non fermentum diam nisl sit amet erat. Duis semper. Duis arcu massa, scelerisque vitae, consequat in, pretium a, enim. Pellentesque congue. Ut in risus volutpat libero pharetra tempor. Cras vestibulum bibendum augue. Praesent egestas leo in pede. Praesent blandit odio eu enim. Pellentesque sed dui ut augue blandit sodales. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam nibh. Mauris ac mauris sed pede pellentesque fermentum. Maecenas adipiscing ante non diam sodales hendrerit. Ut velit mauris, egestas sed, gravida nec, ornare ut, mi. Aenean ut orci vel massa suscipit pulvinar. Nulla sollicitudin. Fusce varius, ligula non tempus aliquam, nunc turpis ullamcorper nibh, in tempus sapien eros vitae ligula. Pellentesque rhoncus nunc et augue. Integer id felis. Curabitur aliquet pellentesque diam. Integer quis metus vitae elit lobortis egestas. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi vel erat non mauris convallis vehicula. Nulla et sapien. Integer tortor tellus, aliquam faucibus, convallis id, congue eu, quam. Mauris ullamcorper felis vitae erat. Proin feugiat, augue non elementum posuere, metus purus iaculis lectus, et tristique ligula justo vitae magna. Aliquam convallis sollicitudin purus. Praesent aliquam, enim at fermentum mollis, ligula massa adipiscing nisl, ac euismod nibh nisl eu lectus. Fusce vulputate sem at sapien. Vivamus leo. Aliquam euismod libero eu enim. Nulla nec felis sed leo placerat imperdiet. Aenean suscipit nulla in justo. Suspendisse cursus rutrum augue. Nulla tincidunt tincidunt mi. Curabitur iaculis, lorem vel rhoncus faucibus, felis magna fermentum augue, et ultricies lacus lorem varius purus. Curabitur eu amet.
>
>
>
[Answer]
## Perl, 94 chars
```
for(/(.{0,80}\s)/g){$i=1;$i+=!s/^(.*?\.|.*?,|(.*? )??\S{$i}) \b/$1 /until/
|.{81}/;chop;say}
```
Run with `perl -nM5.01`. (The `n` is included in the character count.)
The code above is the shortest I could make that could handle *any* curveballs I threw at it (such as one-letter words at the beginning of a line, input lines exactly 80 chars long, etc.) exactly according to spec:
```
Lorem ipsum dolor sit amet, consectetur adipisicing 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 nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
I'm tempted to provide a php program which consists of the output text. ;-)
Seriously though, the spaces on the second line of the output text seem to have
been added to the spaces at random? Is there some pattern to it that I'm not
seeing, and if not, how can we be expected to produce exactly that output for
the given input?
```
(With apologies to Gareth for using his comment as additional test input.)
The following 75-char version works well enough to produce the sample output from the sample input, but can fail for other inputs. Also, it leaves an extra space character at the end of each the output line.
```
for(/(.{0,80}\s)/g){s/(.*?\.|.*?,|.*? ..) \b/$1 /until/.{81}/||s/
//;say}
```
Both versions will loop forever if they encounter input that they can't justify correctly. (In the longer version, replacing `until` with `until$i>80||` would fix that at the cost of seven extra chars.)
[Answer]
### Ruby, 146 characters
```
$><<gets.gsub(/(.{,80})( |$)/){$2>""?(s=$1+$/;(['\.',?,]+(1..80).map{|l|"\\b\\w{#{l}}"}).any?{|x|s.sub! /#{x} (?=\w)/,'\& '}while s.size<81;s):$1}
```
It prints exactly the desired output (see below) if the given text is fed into STDIN.
```
Lorem ipsum dolor sit amet, consectetur adipisicing 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 nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
```
*Edit:* Just after submitting my first solution I saw in the comments that it is required that any input string can be processed. The previous answer was only 95 characters but did not fulfill this requirement:
```
r=gets.split;l=0;'49231227217b6'.chars{|s|r[l+=s.hex]+=' '};(r*' ').gsub(/(.{,80}) ?/){puts $1}
```
] |
[Question]
[
### Rules:
In this game you start at the top of a rectangular grid of size N x M made up of walls and open spaces. The input is N lines of M characters, where a `.` specifies an open space and a `x` specifies a wall. Your program should output the smallest number K such that there exists a path from the top left corner to the bottom right corner (no diagonals) that crosses K walls.
For example, given the input:
```
..x..
..x..
xxxxx
..x..
..x..
```
your program should output `2`.
### Other examples:
output `4`:
```
xxxxx
x.x.x
x.x.x
x..xx
```
output `0`:
```
.xxxxxxxx
.x...x...
.x.x.x.x.
.x.x...x.
...xxxxx.
```
output `6`:
```
xx
xx
xx
xx
xx
```
### Extra tidbits:
If it makes your life easier, you can specify N and M as command line parameters.
Extra credit if you can have your program print out the path in some form or another.
[Answer]
## Ruby 1.9 (235) (225) (222) (214)
I don't know if this is shorter than a program based on Dijkstra, but I figured I would try a different approach. This uses regex in a loop to mark each space with the minimal number of walls required to reach it.
```
w=".{#{/\s/=~s=$<.read}}?"
j="([.x])"
s[0]=v=s[0]<?x??0:?1
(d=v[-1];n=v.succ![-1]
0while(s.sub!(/#{j}(#{w+d})/m){($1<?x?d: n)+$2}||s.sub!(/(#{d+w})#{j}/m){$1+($2<?x?d: n)}))while/#{j}/=~q=s[-2]
p v.to_i-(q==n ?0:1)
```
Input is specified as a file on the command line, i.e.
```
> ruby1.9.1 golf.rb maze.txt
```
Ungolfed:
```
# read in the file
maze = $<.read
# find the first newline (the width of the maze)
width = /\s/ =~ maze
# construct part of the regex (the part between the current cell and the target cell)
spaces = ".{#{width}}?"
# construct another part of the regex (the target cell)
target = "([.x])"
# set the value of the first cell, and store that in the current wall count
maze[0] = walls = (maze[0] == "x" ? "1" : "0")
# loop until the goal cell is not "." or "x"
while /#{target}/ =~ (goal = s[-2])
# store the current wall count digit and the next wall count digit, while incrementing the wall count
current = walls[-1]; next = walls.succ![-1]
# loop to set all the reachable cells for the current wall count
begin
# first regex handles all cells above or to the left of cells with the current wall count
result = s.sub!(/#{target}(#{spaces + current})/m) {
($1 == 'x' ? next : current) + $2
}
# second regex handles all cells below or to the right of cells with the current wall count
result = result || s.sub!(/(#{current + spaces})#{target}/m) {
$1 + ($2 == 'x' ? next : current)
}
end while result != nil
end
# we reached the goal, so output the wall count if the goal was a wall, or subtract 1 if it wasn't
puts walls.to_i - (goal == next ? 0 : 1)
```
[Answer]
## Perl 5.10 (164)
```
undef$/;$_=<>;/\n/;$s="(.{$-[0]})?";substr$_,0,1,($n=/^x/||0);
until(/\d$/){1while s/([.x])($s$n)/$n+($1eq x).$2/se
+s/$n$s\K[.x]/$n+($&eq x)/se;$n++}
/.$/;print"$&\n"
```
Very much along the same lines as migimaru's solution, only with that extra Perl touch. 5.10 is needed for `\K` in `s///`.
[Answer]
**Python ~~406~~ ~~378~~ ~~360~~ ~~348~~ 418 chars**
```
import sys
d={}
n=0
for l in open(sys.argv[1]):
i=0
for c in l.strip():m=n,i;d[m]=c;i+=1
n+=1
v=d[0,0]=int(d[0,0]=='x')
X=lambda *x:type(d.get(x,'.'))!=str and x
N=lambda x,y:X(x+1,y)or X(x-1,y)or X(x,y+1)or X(x,y-1)
def T(f):s=[(x,(v,N(*x))) for x in d if d[x]==f and N(*x)];d.update(s);return s
while 1:
while T('.'):pass
v+=1
if not T('x'):break
P=[m]
s,p=d[m]
while p!=(0,0):P.insert(0,p);x,p=d[p]
print s, P
```
Simplified Dijkstra, since moves with weight are on `x` field. It is done in "waves", first loop with finding `.` fields touching front and set them on same weight, than once find `x` fields touching front and set them on `+1` weight. Repeat while there are no more unvisited fields.
At the end we know weight for every field.
Input is specified as a file on the command line:
```
python m.py m1.txt
```
**Update:** prints path.
[Answer]
C++ version (~~610~~ ~~607~~ ~~606~~ 584)
```
#include<queue>
#include<set>
#include<string>
#include<iostream>
#include<memory>
#define S second
#define X s.S.first
#define Y s.S.S
#define A(x,y) f.push(make_pair(s.first-c,make_pair(X+x,Y+y)));
#define T typedef pair<int
using namespace std;T,int>P;T,P>Q;string l;vector<string>b;priority_queue<Q>f;set<P>g;Q s;int m,n,c=0;int main(){cin>>m>>n;getline(cin,l);while(getline(cin,l))b.push_back(l);A(0,0)while(!f.empty()){s=f.top();f.pop();if(X>=0&&X<=m&&Y>=0&&Y<=n&&g.find(s.S)==g.end()){g.insert(s.S);c=b[X][Y]=='x';if(X==m&&Y==n)cout<<-(s.first-c);A(1,0)A(-1,0)A(0,1)A(0,-1)}}}
```
Implements Dijkstra's algorithm.
Un-golfed:
```
#include<queue>
#include<set>
#include<string>
#include<iostream>
#include<memory>
using namespace std;
typedef pair<int,int>P;
typedef pair<int,P>Q;
int main()
{
int m,n;
string line;
vector<string> board;
cin >> m >> n;getline(cin,l);
while(getline(cin,line))
{
board.push_back(line);
}
priority_queue<Q> frontList;
set<P> found;
frontList.push(make_pair(0,make_pair(0,0)));
while(!frontList.empty())
{
Q s=frontList.top();
frontList.pop();
if( s.second.first>=0
&& s.second.first<=m
&& s.second.second>=0
&& s.second.second<=n
&& found.find(s.second)==found.end()
)
{
found.insert(s.second);
int c=board[s.second.first][s.second.second]=='x';
if( s.second.first==m
&& s.second.second==n
)
{ cout<<-(s.first-c);
}
frontList.push(make_pair(s.first-c,make_pair(s.second.first+1,s.second.second)));
frontList.push(make_pair(s.first-c,make_pair(s.second.first-1,s.second.second)));
frontList.push(make_pair(s.first-c,make_pair(s.second.first,s.second.second+1)));
frontList.push(make_pair(s.first-c,make_pair(s.second.first,s.second.second-1)));
}
}
}
```
] |
[Question]
[
[A073329](http://oeis.org/A073329) is a sequence where the \$n\$th term is the \$n\$th number with exactly \$n\$ distinct prime factors. For example, \$a(3) = 60\$ as the first \$3\$ integers with \$3\$ distinct prime factors are \$30 = 2 \times 3 \times 5\$, \$42 = 2\times3\times7\$ and \$60 = 2^2 \times 3 \times 5\$.
You are to take a positive integer \$n\$ and output the first \$n\$ terms of the sequence. You may assume the input will never exceed the bounds of your language's integers. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins.
The first 10 terms of the sequence are
```
2, 10, 60, 420, 4290, 53130, 903210, 17687670, 406816410, 11125544430
```
[Answer]
## Python, 144 chars
```
R=range
P=[x for x in R(2,99)if all(x%i for i in R(2,x))]
for a in R(input()):
x=n=0
while n<=a:n+=sum(x%p==0for p in P)==a+1;x+=1
print x-1
```
It takes about 2 minutes to run to completion for x=8.
[Answer]
**Java, 170 characters in one line**
```
int a(int n) {
int a = 2, t = a, m = 1, i = 1;
Set s = new HashSet();
while (i++ > 0) {
if (t % i == 0) {
s.add(i);
t /= i;
if (t == 1) {
if (s.size() == n) {
if (n == m) {
break;
}
m++;
}
t = ++a;
s.clear();
}
i = 1;
}
}
return a;
}
```
**Update, +77 characters IOL**
```
int[] f(int n) {
int[] f = new int[n];
for (int i = 0; i < n; i++) {
f[i] = a(i+1);
}
return f;
}
```
[Answer]
### Java (Ungolfed)
```
public class M {
public static void main(String[] a) {
final int N = 100000000;
int[] p = new int[N];
for(int f = 2; f * f < N; f++) {
if(p[f] == 0)
for(int k = f; k < N; k += f)
p[k]++;
}
for(int i = 1; i <= 8; i++) {
int c = 0, j;
for(j = 1; j < N && c < i; j++)
if(p[j] == i)
c++;
if(c == i)
System.out.println(i + " = " + --j);
}
}
}
```
Uses a sieve algorithm. It's pretty quick. **(6 Seconds)**
Will work accurately for upto `8`, will probably fail for anything higher.
[Answer]
## JavaScript, 149 chars
```
function(n){function f(x){for(r=[],o=x,z=2;z<=o;x%z?++z:(x/=z,r.indexOf(z)+1?0:r.push(z)));return r}for(c=0,i=1;c<n;)f(++i).length==n?c++:0;return i}
```
Feels unresponsive for n >= 6 so I haven't tested how long it takes (my browser pops up a hung script notification every 10 seconds or so therefore I can't time it accurately and I don't want to completely hang if I check "don't show this again"...)
Edit: To return array is **200 characters (+51)**:
```
function(n){function F(){function f(x){for(r=[],o=x,z=2;z<=o;x%z?++z:(x/=z,r.indexOf(z)+1?0:r.push(z)));return r}for(c=0,i=1;c<n;)F(++i).length==n?c++:0;return i}for(a=[];n>0;n--)a.push(f());return a}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
Æv=¥ḷ#)Ṫ€
```
[Try it online!](https://tio.run/##ARwA4/9qZWxsef//w4Z2PcKl4bi3Iynhuarigqz///81 "Jelly – Try It Online")
## How it works
```
Æv=¥ḷ#)Ṫ€ - Main link. Takes n on the left
) - For each integer 1 ≤ k ≤ n, so the following:
¥ḷ# - Find the first k integers for which the following is true:
Æv - The number of distinct prime factors
= - equals k
Ṫ€ - Return the last element from each list
```
[Answer]
# J, 32 bytes
```
({"0 1~i.@#)(]/.~#@~.@q:)
```
But since I'm answering my own question so late, we'll just leave this answer as a curiosity.
] |
[Question]
[
My apologies for the wordiness. We had fun with it at work in our internal golfing, but it required a few emails for clarification, so I hope I captured most of that the first time.
## PROBLEM
Given a “simulated” snowfall snapshot (as a string, stdin or parameter to your function/method), report on 4 values: minimum depth, maximum depth, average depth, and duration.
Here’s a formatted example to illustrate the input:
```
* * **
** * ***
** * *
*
--------
```
The ‘\*’ is a snowflake and the ‘-‘ is the ground. Imagine all of those “snowflakes” falling toward the ground. This is the final “snapshot”:
```
*
*
** * **
********
--------
```
You need to report on:
1. Minimum depth - count the shortest “pile” (1, in example above)
2. Maximum depth - count the tallest “pile” (4, in example above)
3. Average depth - average count of all “piles” (1.9, in example above - rounding to tenths)
4. Duration - (each “fall” = 1 second) - time from the first snapshot to the last snapshot (3 seconds, in example above)
Another example for reference:
```
*
* *
*
*
--------
```
Final snapshot:
```
* * ***
--------
```
## INPUT
The starting “snapshot” will have 8 “rows”, 8 “columns”, and be pipe-delimited (the pipes separate the rows). For example (excluding quotes):
```
“ | | | | * | * *| * |* |--------”
```
## OUTPUT
The 4 values pipe-delimited on a single line: **0|1|.6|3** or **0|5|1|1**
[Answer]
## Python, 153 characters
```
s=raw_input()
R=range(8)
C=[s[i::9].count('*')for i in R]
print"%d|%d|%.1f|%d"%(min(C),max(C),sum(C)/8.,max(8-s[i::9].find('*')-C[i]for i in R if C[i]))
```
[Answer]
## Perl, 128 chars
```
map{$d++;s/\*/$d{$-[0]}++;$t&&$t<$d or$t=$d/ge}split'\|',<>;map{$A+=$_/8}@m=sort values%d;printf"$m[0]|$m[-1]|%.1f|%d\n",$A,8-$t
```
[Answer]
## Windows PowerShell, 180 ~~189~~
```
$a=(0..7|%{$x=$_;-join(0..7|%{$s[$_*9+$x]})})
$b=$a-replace' '|%{$_.length}|sort
"{0}|{1}|{2:.0}|{3}"-f($b[-1..0]+(($b-join'+'|iex)/8),($a|%{($_-replace'^ +|\*').length}|sort)[-1])
```
Input comes in as `$s`.
History:
* 2011-02-10 01:53 (189) – First attempt.
* 2011-02-10 02:03 (180) – Format string to the rescue. Only downside: It outputs numbers in regional format, no longer strictly conforming to the task specification. Still, that's a problem shared by the C# solution as well so I guess that's ok.
[Answer]
A couple other language results from our internal golfing:
## C#, 188 characters (easily readable)
```
int a = 0, b = 8, c = 0, d = 0, f, i, j, x;
for (i = 0; i < 8; i++)
{
f = x = 0;
for (j = 0; j < 8; )
if (s[i + j++ * 9] == '*')
{
x = x > 0 ? x : 9 - j;
f++;
}
d += f;
a = f > a ? f : a;
b = f < b ? f : b;
c = x - f > c ? x - f : c;
}
Console.Write("{0}|{1}|{2:.0}|{3}", b, a, d / 8f, c);
```
## Ruby, 173 characters
```
s=gets;n=8;a=o=l=0;8.times{|i|f=x=0;8.times{|j|if(s[i+j*9].chr=='*'):x=8-j if x==0;f+=1;end}
o+=f;a=f if f>a;n=f if f<n;l=x-f if x-f>l}
printf "%d|%d|%.1f|%d",n,a,o.to_f/8,l
```
[Answer]
# PHP, 139 bytes
```
<?for(;$y<8;$y++)for($x=0;++$n[$x],$x<8;$x++)'!'>$argv[1][$y*9+$x]&&--$n[$x]?$b[$x]++:0;print_r([min($n),max($n),array_sum($n)/8,max($b)]);
```
for each column, count no. of snowflakes and no. of spaces below the first snowflake, then calculate
takes string as argument from command line
**breakdown** and golfing steps
```
$i=$argv[1];
for(;$y<8;$y++) # $y=row
{
for($x=0;$x<8;$x++) # $x=column
{
// loop body: 32+26=58 bytes
if('*'==$i[$p=$y*9+$x])$n[$x]++;# if snowflake: increase snowflakes count
elseif($n[$x]+=0)$b[$x]++; # elseif has snowflakes: increase blanks count
# +=0: min needs a value in every column
// -> golf if/elseif to ternaries, 16+9+25+1 = 51 (-7)
# '*'==$i[$y*9+$x]
# ? $n[$x]++
# : (($n[$x]+=0)?$b[$x]++:0)
# ;
// golfing on the ternary, 15+23+9+1 = 48 (-3)
# '!'>$i[$y*9+$x] # -1: char<'!' <=> char==' '
# ? ($n[$x]+=0)?$b[$x]++:0 # -2: inverted condition -> eliminated parens
# : $n[$x]++
# ; # 15+23+9+1-2=46
// increase snowflakes count in any case (initialization)
// (needs curlies; elminate them by moving increase to the for condition)
// decrease snowflakes count for blank
# ++$n[$x];if('!'>$i[$y*9+$x]&&--$n[$x])$b[$x]++; # if: 47
# ++$n[$x];'!'>$i[$y*9+$x]&&--$n[$x]?$b[$x]++:0; # ternary: 46
}
}
print_r([min($n),max($n),array_sum($n)/8,max($b)]); # calculate and print results
```
add `round(...,1)` around `array_sum($n)/8` for rounding (+9)
[Answer]
## *Mathematica*, ~115
```
" \n \n* * ** \n \n** * ***\n** * * \n* \n--------"
Most/@ToCharacterCode@%~Partition~9/10-16/5
Min@#|Max@#|Mean@#~Round~.1|Position[#,1][[{-1,1},1]].{1,-1}-1&@Total@%
```
>
>
> ```
> 1 | 4 | 1.9 | 4
>
> ```
>
>
In this post I had to resort to the escaped string form `\n` as paste and copy loses spaces. In the Front End I can enter it like this:
[](https://i.stack.imgur.com/fAMfr.png)
[Answer]
# JavaScript, 328 Bytes
Not particularly short, but it's what I've got.
```
var input = " | | |* * ** | |** * ***|** * * |* |--------";
(s=>{var l=s.split("|"),a=[0,0,0,0,0,0,0,0],o=[8,0,0,0],b;for(i=0;i<l.length;i++){if(!b&&l[i]!=" ")o[3]=7-i,b=1;for(j=0;j<l[i].length;j++){a[j]+=l[i][j]=="*"?1:0}}for(i=0;i<a.length;i++){if(a[i]<o[0])o[0]=a[i];if(a[i]>o[1])o[1]=a[i];o[2]+=a[i];}console.log(o[0]+"|"+o[1]+"|"+(o[2]/a.length).toFixed(1)+"|"+o[3]);})(input)
```
De-golfed:
```
var input = " | | | | * | * *| * |* |--------";
(s=>{
var splits = s.split("|");
var arr = [0,0,0,0,0,0,0,0];
var b;
var o=[8,0,0,0];
for (var i = 0; i < splits.length; i++) {
if (!b&&splits[i]!=" ") {
o[3] = 7-i;b=1;
}
for (var j = 0; j < splits[i].length; j++) {
arr[j]+=splits[i][j]=="*"?1:0;
}
}
for (var i = 0; i < arr.length; i++) {
if (arr[i]<o[0]) {
o[0]=arr[i];
}
if (arr[i]>o[1]) {
o[1]=arr[i];
}
o[2]+=arr[i];
}
console.log(o[0]+"|"+o[1]+"|"+(o[2]/arr.length).toFixed(1)+"|"+o[3]);
})(input)
```
] |
[Question]
[
Some chess variants use interesting non-standard pieces. In order to concisely describe new pieces or to describe pieces without requiring everyone to memorize a bunch of non-standard names some new notation can be invented.
In this challenge we are going to look at Parlett's movement notation and convert it to nice at a glance diagrams.
A move description consists of two parts. First is the distance. Some pieces can move 1 unit, some pieces can move two, and some pieces can move however as far as they wish.
The second part is the pattern, that expresses what basic units a move can use. When moving a piece selects a unit from it's pattern and then repeat that unit based on it's distance.
For example a bishop has any non-negative distance, and it's pattern is all the diagonal movements 1 square. So the bishop can move in any diagonal direction any amount (other than 0).
---
## Distances
* Any postive integer means exactly that distance. e.g. `1` means `1`.
* `n` means that the piece can move any non-negative distance
For this challenge you can assume that the integers will not exceed 9.
---
## Move patterns
There are 5 basic patterns that all other patterns can be composed of. They are the 8 squares surrounding the piece except since the system doesn't distinguish between left and right moves, these moves are grouped into pairs.
| Number | Description |
| --- | --- |
| 1 | Diagonal forward |
| 2 | Directly forward |
| 3 | Left or right |
| 4 | Diagonal backward |
| 5 | Directly backward |
Here's these described with a diagram:
```
1 2 1
3 3
4 5 4
```
We can then describe the symbols for patterns. in terms of which of these they allow:
| Symbol | Allowed patterns |
| --- | --- |
| `x` | 1 or 4 |
| `+` | 2, 3 or 5 |
| `*` | 1, 2, 3, 4 or 5 |
| `>` | 2 |
| `<` | 5 |
| `<>` | 2 or 5 |
| `=` | 3 |
| `>=` | 2 or 3 |
| `<=` | 5 or 3 |
| `x>` | 1 |
| `x<` | 4 |
---
These two parts are then concatenated to make a symbol. So for our bishop earlier its distance is `n` and its pattern is `x` so it's symbol is `nx`.
## Grouping
You can group multiple moves together into larger moves using two extra symbols.
* `.` represents *and then*. For the symbol `a.b` the piece must perform a valid `a` move and then a valid `b` move.
* `,` represents *or*. For the symbol `a,b` the piece can do a valid `a` move or a valid `b` move.
`.` has higher precedence and there is no option for parentheses. So `a.b,c` means "(`a` then `b`) or `c`", not "`a` then (`b` or `c`)".
As an example the knight from chess can be expressed with the rather complex compound symbol `2=.1<>,2<>.1=`, in plain(er) English "(2 moves to the side and 1 forward or back) or (2 moves forward or back and one to the side)".
## Task
In this challenge your program or function is going to take in a symbol as a string and draw an [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") diagram of where it can move.
The diagram will show a 9x9 board with the piece placed in the center, (5,5), and will show all the places the piece can move in 1 turn with `X` and all the places it cannot with `.`. We will ignore the case where the piece does not move (whether it is described by the rules or not) and place a `O` at the original coordinates to indicate its place.
A piece may not move out of the board during the course of the move. For example `1>.1<` (one forward, then one backwards) requires the piece to move one forward while staying in the board.
Your output should be arranged into 9 space separated columns with 9 newline separated rows. You may have trailing whitespace on any lines or after the end of the output.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes.
## Test cases
```
1+
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . X . . . .
. . . X O X . . .
. . . . X . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
2x
. . . . . . . . .
. . . . . . . . .
. . X . . . X . .
. . . . . . . . .
. . . . O . . . .
. . . . . . . . .
. . X . . . X . .
. . . . . . . . .
. . . . . . . . .
2*
. . . . . . . . .
. . . . . . . . .
. . X . X . X . .
. . . . . . . . .
. . X . O . X . .
. . . . . . . . .
. . X . X . X . .
. . . . . . . . .
. . . . . . . . .
n+,1x
. . . . X . . . .
. . . . X . . . .
. . . . X . . . .
. . . X X X . . .
X X X X O X X X X
. . . X X X . . .
. . . . X . . . .
. . . . X . . . .
. . . . X . . . .
2=.1<>,2<>.1=
. . . . . . . . .
. . . . . . . . .
. . . X . X . . .
. . X . . . X . .
. . . . O . . . .
. . X . . . X . .
. . . X . X . . .
. . . . . . . . .
. . . . . . . . .
n=.1<>
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
X X X X X X X X X
. . . . O . . . .
X X X X X X X X X
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
1x.1+
. . . . . . . . .
. . . . . . . . .
. . . X . X . . .
. . X . X . X . .
. . . X O X . . .
. . X . X . X . .
. . . X . X . . .
. . . . . . . . .
. . . . . . . . .
1+.1+
. . . . . . . . .
. . . . . . . . .
. . . . X . . . .
. . . X . X . . .
. . X . O . X . .
. . . X . X . . .
. . . . X . . . .
. . . . . . . . .
. . . . . . . . .
1+.3>=
. . . . X . . . .
. . . X . X . . .
. . . . X . . . .
. X . . . . . X .
X . X . O . X . X
. X . . . . . X .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
3=.4=.5=
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
X . . . O . . . X
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
n<>.nx<
. . . . X . . . .
. . . X X X . . .
. . X X X X X . .
. X X X X X X X .
X X X X O X X X X
X X X X X X X X X
X X X X X X X X X
X X X X X X X X X
X X X X X X X X X
4*.1*
. X . X . X . X .
X X . X X X . X X
. . . . . . . . .
X X . . . . . X X
. X . . O . . X .
X X . . . . . X X
. . . . . . . . .
X X . X X X . X X
. X . X . X . X .
```
---
As a final note, you may notice that this notation fails to capture a lot of information about pieces. Like how blocking works, castling or anything about how pawns move. The thing is that these symbols are not really all that useful in expressing most interesting stuff. But they do make for a bit of an interesting code-golf challenge.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 305 bytes
Prints the ASCII art.
```
s=>s.split`,`.map(s=>(g=(x,y,[s,...a])=>(r=m[y])&&r[x]&&b.map((v,d)=>s?',x<,>,,=,,>=,,<,,<>,,<=,,+,,x>,x'.split`,`.indexOf(s.slice(1))>>v&d!=4&&b.map((_,n)=>n-s[0]||g(x+d%3*n-n,y+n*~-(d/3),a)):r[x]='X'))(4,4,s.split`.`),b=[...'4142.2030'],m=b.map(_=>[...b].fill`.`))|m.map(r=>print(r.join` `),m[4][4]='O')
```
[Try it online!](https://tio.run/##RU/bboMwDP0VhjRIwGQNMGlacfa0575OQqjQUjoqSBGpUKp1@3UWQFsl2zr28eX4VAyF2vd1dwmGl7HCUaFQTHVNfckhZ23REVMhRyQarpAqYIwVGTWlHtv0mlHH6VOdOc5u7iUDlIZUby7oBAQAAgjjiTGTJQb6AFqAdu9Halke9KYi5m5T7w@EUyrE4JQPGP/v3YI0e2Wg0lV2ux2J9svHyJOBhKsvvZ@AlE8RhYLS10kOuh8upSSGGP6eYTmFHaZGvhvzOGThKlq5GbS4HNiimLhdxqq6aaZuemtnpkfR9bW8kJ6dzrXMLbOoTePMGLobl47r1LK5b4Nlh3qO3hSlD3xJkXHze5gIxnFm5sKEuGbLIPfvIBJzV4QsRva8TJhZqZMJxh7jnm0Zmef@vdh/EmWhsL6sRaKia6ua45Ib8E3HXw "JavaScript (V8) – Try It Online")
### Encoding
Each symbol is encoded by its position into a lookup array, packed as the following comma-separated string:
```
',x<,>,,=,,>=,,<,,<>,,<=,,+,,x>,x'
```
The position is then interpreted as a 5-bit mask. Note that the symbol `*` is not stored at all, so its position is `-1` and all bits are set in that case.
```
symbol | position | bitmask bits:
--------+----------+---------
x< | 1 | 00001 4 3 2 1 0
> | 2 | 00010 | | | | |
= | 4 | 00100 | | | | +--> Diagonal backward
>= | 6 | 00110 | | | +----> Directly forward
< | 8 | 01000 | | +------> Left or right
<> | 10 | 01010 | +--------> Directly backward
<= | 12 | 01100 +----------> Diagonal forward
+ | 14 | 01110
x> | 16 | 10000
x | 17 | 10001
* | -1 | 11111
-----
43210
```
Given a symbol and a direction \$d\in[0..3,5..8]\$, we retrieve one of the bitmasks described above and get the character at position \$d\$ in the lookup string `"4142.2030"` to figure out which bit should be tested. If the bit is set, we are allowed to move in this direction.
The direction vector is \$\big((d\bmod 3)-1,\lfloor d/3 \rfloor-1\big)\$, leading to the following compass:
$$\begin{matrix}0&1&2\\3&&5\\6&7&8\end{matrix}$$
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 136 bytes
```
UO⁹.F⪪S,⊞υ⁺⮌⪪ι.⟦⁴¦⁴⟧Fυ«≔⊟ιθ≔⊟ιη≔⊟ιζF⌕A⮌⍘§⦃x¹⁷⁰+⁸⁵*²⁵⁵>⁴<⁶⁴<>⁶⁸=¹⁷>=²¹<=⁶⁹x>χx<¹⁶⁰⦄Φζλ²1F…·Σζ∨Σζ⁹«JθηMλ✳κ¿⬤⟦ⅉⅈ⟧⁼μ﹪μ⁹¿ι⊞υ⁺ι⟦ⅉⅈ⟧X»»J⁴¦⁴OUE¹
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVLRSiMxFIV9a78i5OlGozhFa2ur0GUVKkiL7oNL6cM4TduwadJOkjJU-iW--KDoN_k1e-84qyC-ZA7nnHtz59w8vGbzNM9cah4fn2OY7rXefrQHd8bZGbQl4_tcdOpTlzO4WRodoG-XMdyEXKMuUJdcCDaMfg5RsqGJHq7VWuVeVX793gOto0PJDsfif7so2H291vNezywM3RI0elaofuXm33Ab4so2F9pOesZ83Poz9aoarxf6dqIKuOcFP2HJ8QGOsouodYRgB0HjiNAZIhyNd_HbLAExzRai07KOPIQaCYmEmpRMQbaEmhZUmjQPtpJdaBNUDhvJDP1zgw6eUEbltH2bYUR6ra5TO8OI4gI26BjkH7AtRBlM7TIulr8drKoAaldurcBI9kvnKgvaWfgrSkFPGVACoz-0kFsQY8nOVzE1HhaSXblJNI4QdRaM3PrLxnBHn8Wiw5Txig0xwwD8lvZf29a39Wog2iJSlTwg-bwIyk4gEZ0nf5f56h29jPje2vDxi-2e7dui-87-Aw) Link is to verbose version of code. Explanation:
```
UO⁹.
```
Draw a 9×9 board.
```
F⪪S,⊞υ⁺⮌⪪ι.⟦⁴¦⁴⟧
```
Get the input string, split it on `,`s, split each piece on `.`s, and append two `4`s to each reversed list of instructions as being the starting coordinates.
```
Fυ«
```
Loop over the list of instruction and coordinate entries.
```
≔⊟ιθ≔⊟ιη≔⊟ιζ
```
Remove the coordinates and one instruction and assign them to their own variables.
```
F⌕A⮌⍘§⦃x¹⁷⁰+⁸⁵*²⁵⁵>⁴<⁶⁴<>⁶⁸=¹⁷>=²¹<=⁶⁹x>χx<¹⁶⁰⦄Φζλ²1
```
Map the instruction into a binary number and loop over the positions of the `1` bits (counting back from the end) which represent the allowed directions.
```
F…·Σζ∨Σζ⁹«
```
Loop over the allowed distances. (This assumes that zero distance means any amount up to and including `9`. Larger explicit distances are supported, and the range for arbitrary distances could be increased to `1000` without changing the byte count.)
```
JθηMλ✳κ
```
Move to the resulting position for the given direction and distance.
```
¿⬤⟦ⅉⅈ⟧⁼μ﹪μ⁹
```
If the current position is on the board, then...
```
¿ι⊞υ⁺ι⟦ⅉⅈ⟧X
```
... if there are more instructions to process then push them with the current position to the list of instructions, otherwise mark the current position with an `X`.
```
»»J⁴¦⁴O
```
Mark the initial position with an `O`.
```
UE¹
```
Space the board out horizontally.
[Answer]
# Java 10, ~~631~~ ~~608~~ ~~606~~ ~~597~~ ~~578~~ ~~504~~ ~~489~~ ~~475~~ 470 bytes
```
s->{int i=0,k,d,n,x,y,l,e[],f[];var m=new boolean[81];for(var p:s.split(",")){e=f=new int[81];e[40]=k=1;for(var P:p.split("\\.")){f=e.clone();k++;for(i=81;i-->0;)if(e[i]==k-1)for(n=P.charAt(0),d=9;d-->0;)for(l=n>99?0:n-49;d*n==440|("ǰ« )ņ©+ Ł ".charAt((P.chars().sum()-n)%42%15)-1>>d&1)>0&&l++<n%48;)if((y=i/9-d/3*l+l)>=0&y<9&(x=i%9-d%3*l+l)>=0&x<9)f[y*9+x]=k;e=f;}for(;++i<81;)m[i]|=e[i]==k;}for(;i-->0;)System.out.print((i==40?"O":m[i]?"X":".")+(i%9<1?"\n":""));}
```
-74 bytes, opening up another -22 bytes, thanks to *@Arnauld*
-5 bytes thanks to *@ceilingcat*
[Try it online.](https://tio.run/##hVPLattAFF0UushXDAM2M5rRRGMrED1GpssumgSyKTheKHq0E8sjY8mpTOJFKPRfSjf9BkPoZ7mjh9NEDe1m4J577vvMTXgbmjfxfB9lYVGAD6FUd0cASFUmqzSMEnBWmwDc5jIGEbosV1J9AgX2NLo90k9RhqWMwBlQQIB9YQZ3OhZIYdE5jamiFd3QjCbTGU2nM@82XIGFUMkXcJ3nWRKq6SmfeWm@QrVn6RasWGayRJBCjO8SkTZcnbHhJVPbmom54E8RF@7yEHF1xeqYVCQsynKVIOzNCWmYUpxyT5pmYHlYpiiZypkQc5Pj2qnEBYs@h6t3JbIwjYXjxS2zdmZCBY4zsVxl2tphKCFs27pH8NfP3Q@we8BvHr/tvu@@EgAeH8BbeMiE2pwFwqxYLxA2FR7YowE/wSYPgnjIcWANhxkhvhrYp01XaCPksWPGx2MjIxkOhDXc@M4QVUIONDz4A1e@g9PpxnBIpbfh6S1527pZjxDp60nxQg94L7oxO183/uWmKJMFy9clW@pT6k6lHsmawHPo1mET@BG6UG@SIF3W5xN4pTSgN@tt91598OX6OtMH7@7e6GKhVdNJYzoLcauYMin0VTiBjVYO9qjq2cZLWxHK@xTBuB/QkR8wLnrsxvUS4xXrF@XkNWgc9LPpCqrye0SDjf4OHwtmi1cgdtJDbYPxZsT2F2nJ5stCwIoSatCA@lRPJmggqC9oFVBd/dkPaBMdtJ67OhQ3UJd9TPL/cqCCHev5d23O1viffnR7tb4@MoXge7Vcly6ApOiqvUY6X5ctq@MoFqF/8LuOtvvf)
**Explanation:**
```
s->{ // Method with String parameter and no return-type
int i=0, // Index-integer, starting at 0
k, // 'and then'-iteration integer
d, // Direction-integer
n, // Step-size integer
o, // Operation-integer
x,y, // x,y-coordinates
l, // Inner loop integer (when the step-size is 'n')
e[],f[]; // Temp integer-arrays
var m=new boolean[81]; // Result boolean-array, starting at 81x false
for(var p:s.split(",")){ // Split the input by "," and loop over the parts:
e=f=new int[81]; // Set `e` to an empty list
// (and `f` as well to prevent uninitialized errors)
e[40]=k=1; // (Re)set `k` to 1
// And also fill the center cell with 1
for(var P:p.split("\\.")){ // Inner loop over the parts split by ".":
f=e.clone(); // Set `f` to a copy of `e`
k++; // Increase `k` by 1
for(i=81;i-->0;) // Loop over all the cells:
if(e[i]==k-1) // If the cell contains the previous `k`:
for(n=P.charAt(0), // Set `n` to the first character of `P`
d=9;d-->0;) // Loop over the directions `d` in the range (9,0]:
for(l=n>99? // If the step-size is 'n':
0 // Set `l` to 0
: // Else:
n-49; // Set `l` to digit 'n' minus 1
d*n==440 // If `n` = 'n' and the direction is 4,
|("ǰ« )ņ©+ Ł ".charAt((P.chars().sum()-n)%42%15)-1>>d&1)>0
// or bitmask magic† to check whether the direction applies to operation:
&&l++<n%48;) // If `n` != 'n': simply use `l` once
// Else (`n` = 'n'): loop `l` in the range [0,14):
// (any integer >= 8 would be fine here)
if((y=i/9-d/3*l+l)// Set `y` to `l` steps into direction `d`
>=0&y<9 // And check if it's still in bounds
&(x=i%9-d%3*l+l)>=0&x<9)
// Change and check bounds for `x` as well:
f[y*9+x]=k; // Fill the `x,y`'th cell with value `k`
e=f;} // Set `f` as new `e` for the next iteration
for(;++i<81;) // Loop over all the cells again:
m[i]|= // OR the boolean at cell `i` with:
e[i]==k; // Check if the `i`'th cell of `e` contains value `k`
} // After we've looped over the entire input-String:
for(i=81;i-->0;) // Loop one last time over all the cells:
System.out.print( // Print:
(i==40? // If it's the center cell:
"O" // Print "O"
:m[i]? // Else-if the `i`'th cell of the boolean-matrix is true:
"X" // Print "X"
: // Else (it's false instead):
".") // Print "."
+(i%9<1?"\n":""));} // And print a newline every 9 cells
```
*†Explanation of the 'bitmask magic':*
| Operation | `P.chars().sum()``-n` | `%42` | `%15` | `"ǰ« )ņ©+ Ł "``.charAt(...)-1` | `>>d` for direction `d` in range \$[0,8]\$ | `&1` |
| --- | --- | --- | --- | --- | --- | --- |
| x | 120 | 36 | 6 | 325 | 325,162,81,40,20,10,5,2,1 | 101000101 |
| + | 43 | 1 | 1 | 170 | 170,85,42,21,10,5,2,1,0 | 010101010 |
| \* | 42 | 0 | 0 | 495 | 495,247,61,30,15,7,3,1 | 111101111 |
| > | 62 | 20 | 5 | 2 | 2,1,0,0,0,0,0,0 | 010000000 |
| < | 60 | 18 | 3 | 128 | 128,64,32,16,8,4,2,1,0 | 000000010 |
| <> | 122 | 38 | 8 | 130 | 130,65,32,16,8,4,2,1,0 | 010000010 |
| = | 61 | 19 | 4 | 40 | 40,20,10,5,2,1,0,0,0 | 000101000 |
| >= | 123 | 39 | 9 | 42 | 42,21,10,5,2,1,0,0,0 | 010101000 |
| <= | 121 | 37 | 7 | 168 | 168,84,42,21,10,5,2,1,0 | 000101010 |
| x> | 180 | 14 | 14 | 5 | 5,2,1,0,0,0,0,0 | 101000000 |
| x< | 182 | 12 | 12 | 320 | 320,160,80,40,20,10,5,2,1 | 000000101 |
] |
[Question]
[
## Background
[**Minkowski addition**](https://en.wikipedia.org/wiki/Minkowski_addition) is a binary operation on two sets of points (usually geometric objects) in the Euclidean space. The Minkowski sum of two sets \$A\$ and \$B\$ is formally defined as follows:
$$ A+B = \{\mathbf{a}+\mathbf{b}\,|\,\mathbf{a} \in A,\ \mathbf{b} \in B\} $$
To say in plain English, given the origin and two figures, the Minkowski sum of the two figures is formed by the vector sum of each pair of points in the two figures. In the following image, the red shape is the Minkowski sum of the green and blue shapes.
[](https://i.stack.imgur.com/VYpLo.png)
It has an interesting property for two convex polygons: the edges of the original polygons are preserved (modulo translation) and sorted by polar angle (relevant info in [Wikipedia](https://en.wikipedia.org/wiki/Minkowski_addition#Two_convex_polygons_in_the_plane)), and therefore can be computed in \$\mathcal{O}(m+n)\$ (where \$m\$ and \$n\$ denote the number of vertices of two polygons respectively).
## Task
Given two convex polygons, compute their Minkowski sum.
Each polygon is given as an ordered list of \$(x,y)\$ coordinates, and the output polygon should be represented in the same way. You can choose the ordering of vertices (clockwise or counterclockwise), but your code should handle different starting points of the same polygon (`(0,0), (0,1), (1,0)` is the same as `(0,1), (1,0), (0,0)`). A point that is in the middle of a straight edge is not a vertex, and therefore should not appear in the output. (See the first test case)
You may take each coordinate pair as a single complex number. The coordinates are guaranteed to be integers.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
A = [(0, 0), (0, 1), (1, 0)]
B = [(0, 0), (0, 1), (1, 1), (1, 0)]
A + B = [(0, 0), (0, 2), (1, 2), (2, 1), (2, 0)]
A = [(-1, 0), (0, 1), (1, 0)]
B = [(1, 0), (0, -1), (-1, 0)]
A + B = [(-2, 0), (-1, 1), (1, 1), (2, 0), (1, -1), (-1, -1)]
A = [(0, 0), (0, 1), (1, 3), (2, 4), (4, 5), (5, 5)]
B = [(0, 0), (1, 3), (3, 6), (6, 8), (9, 9)]
A + B = [
(0, 0), (0, 1), (1, 4), (2, 6), (4, 9),
(5, 10), (8, 12), (10, 13), (13, 14), (14, 14)]
A = [(0, 1), (0, 2), (1, 2), (1, 1)]
B = [(1, 0), (1, 1), (2, 1), (2, 0)]
A + B = [(1, 1), (1, 3), (3, 3), (3, 1)]
```
[Answer]
# [J](http://jsoftware.com/), 74 58 bytes
Implements the algorithm outlined in the linked wiki article, so kinda works in \$O(n + m)\$ (but actually needs to sort the polygons first.) Takes in complex numbers for the coordinates.
```
+&({:@\:p)+,&d(+/\#~[(~:+)@%1&|.)@\:,&(p=.12 o.d=.[-_1&|.)
```
[Try it online!](https://tio.run/##ZY0xD4IwEIV3fsVFY21TqLaokZImJCZOTq5gOoigDkIYXDT8dbyKRo35cje89@7duRuIcQFGwxh8mILGCQSstpt1xwm96STTNeM@ySmfZMM2pa3mLBlJchcMPZ/Q2gipoBK5EWlgn0bHvMZoqyDNYOeVRh/2xyqhcVwQQbk4Xa6MebTBXw6JTBmU8KP0qktZ@RfrFTTsO/Q5DEHBDJk7vmqdE8ICWUIE0evKNSncbuRXu3xpCvu7Bw "J – Try It Online")
* `d=.[-_1&|.` `d` Translate the polygon to its edges as complex vectors from one point to the next.
* `p=.12 o.` The vectors polar angles.
* `,&d\:,&p` Merge-sort both polygons' edges based on their polar angles.
* `+/\` Transform back complex vectors -> points.
* `#~[(~:+)@%1&|.` but only keep the points where the constructing vector \$B\$ divided by the previous vector \$A\$ has an imaginary part of 0, by checking that the conjugate equals itself. (So \$B = cA\$ for some \$c \notin \mathbb{R} \$.)
* `+&({:@\:p)` Translate the polygon back from `0j0` to the sum of the starting points.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes
```
œ!3ZIZÆḊƲÐḟṢ2ịƊ€
+þẎQḟÇ$µS÷L⁸_æA/¥Þ
```
[Try it online!](https://tio.run/##y0rNyan8///oZEXjKM@ow20Pd3Qd23R4wsMd8x/uXGT0cHf3sa5HTWu4tA/ve7irLxAofLhd5dDW4MPbfR417og/vMxR/9DSw/P@H16udHTSw50zgGoj//@P1jDQUTDQ1FEA0YYg2hDEj9VRiNbQNcQphUWTMYg20lEwAdEmOgqmINoURMN0GEJ1GEF1wGhDzVjs7kCzFMk5umApXUwHwRxirKNgBqLNdBQsQLSljoIlqikw840QNNAsAA "Jelly – Try It Online")
man this is ugly
```
œ!3ZIZÆḊƲÐḟṢ2ịƊ€ Helper Link; get all vertices that lie on an edge
œ!3 Get all permutations of 3 vertices
-----ƲÐḟ Filter; remove triples where
ZIZ - the increments (edge vectors)
ÆḊ - have a non-zero determinant (keep elements with a 0 determinant; i.e. when they are collinear)
---Ɗ€ For each triple
Ṣ - sort it
2ị - and get the second (middle) item
+þẎQḟÇ$µS÷L⁸_æA/¥Þ Main Link
+þ Product table over sum; get all pairwise sums
Ẏ Tighten / flatten by one level; dump pairwise sums into a flat list of vertices
Q Remove duplicates
ḟÇ$ Filter to remove (result of helper link); basically, delete vertices that lie on an edge between two other vertices
µ New monadic chain on the list of vertices
S÷L Sum / Length; arithmetic mean but not vectorizing
Þ Sort
⁸ The left argument (list of kept vertices)
----¥ By order of
_ - difference with mean point
æA/ - atan2
```
Basically, pairwise sum, remove all elements that are the middle element of a collinear triple, and order by atan2 relative to the arithmetic mean of the points.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~133~~ 127 bytes
```
->a,b,*z{a.map{|x|b.map{|y|z|=[x+y]}
z.permutation(3){|i,j,k|q=(j-i)/k-=j;q==q.abs&&z-=[j]}}
z.sort_by{|w|(w*2-z[0]-z[1]).arg}}
```
[Try it online!](https://tio.run/##bVBhb4IwFPzOr3iJiQF9ZS2g0Sxd4v4GaRZIdAHjRNQoUH47aysIzCWEe@Xu3pXLr3HR7HhDPiKMcVZWkXuIskreZfwYCllKHt7nhait0s22@eF6iS7J8cf2nUommOJenridksR52xOevp84P7lRfJ5OS8LDVNTadz7ml6@4qORN2reZR8qQCvViwnGj/Luumwx2YUgTZOqZ00Tg89B9EZY12QCH0CYMgToINkVgGs1ZWJNPQw9YYmjS8RuYw0NDvFakuW6HwY5gQ7ea@nj6mu63zkBjgLDQuND4vBXt9xq1j7DUuERYaVwjrEd3tCYA/2UFbdayzVo7aKQqjhntSg2eEWuXCWMqjRkjC8w0@hvWJnhtgvfs46XTQUt9W6Nm2Z9W/B7VvuYX "Ruby – Try It Online")
Accepts arrays of complex numbers in input.
Not really golfed.
The explanation should be straightforward: first get the sum of all the vertices, then remove all the points on the edges and sort by angle relative to the midpoint of the first edge.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 239 bytes
```
({p,q}=(Join[#,#[[;;2]]]&)/@((RotateLeft[#,First@OrderingBy[#,{Last,First}]-1]&)/@#);i = j = 1;res = {};While[i<Length@p-1||j<Length@q-1,AppendTo[res,p[[i]]+q[[j]]];t=Det@{p[[i+1]]-p[[i]],q[[j + 1]]-q[[j]]};If[t>=0,i++];If[t<=0,j++]];res)&
```
[Try it online!](https://tio.run/##RY5BS8QwEIX/SqCwtCTBxms2EkUEpaCI4CHkUNx0m@K2aTsXyea31@nWxcPweO@bYd6phtadavBf9dKoJY@BjUnlL4PvTcYyY6S8tdbuihud5@8D1OAq1wCyJz/NoF@ng5t8f3z4wShW9QwbSJaLy1VWSE8U6XCEnNyMGpP8bP23M35fuf4IrQ5cnM/d1Y1csPsQXH/4GAyesGCMt5aOxnTYRYJ6dKDjmlJhLd8wWzGhZE22zSSfGwN3qmSeUnsxezQdGrtWKXbLG3YH3egYIz4lZWIkXrVkRKTE4l/wv4CAI0nLLw "Wolfram Language (Mathematica) – Try It Online")
Thanks for the challenge, I have explored an interesting concept!
#### "Short" answer
Uses [this optimized algorithm](https://cp-algorithms.com/geometry/minkowski.html#implementation), accepts list of lists of coordinates, ordered counter-clockwise.
Explained:
```
({p, q} =
(*Must ensure cyclic indexing*)
(PadRight[#,Length@# +2, #] &) /@
(*Reorder the vertices in such a way that the first vertex of each polygon has the lowest y-coordinate (in case of several such vertices pick the one with the smallest x-coordinate*)
((RotateLeft[#,First@OrderingBy[#, {Last, First}] - 1] &) /@ #);
(*Initialize two pointers and result*)
i = j = 1; res = {};
While[i < Length@p - 1 || j < Length@q - 1,
AppendTo[res, p[[i]] + q[[j]]];
(*Instead of ATan use cross product*)
t = Det@{p[[i + 1]] - p[[i]], q[[j + 1]] - q[[j]]};
If[t >= 0, i++]; If[t <= 0, j++]
]; res) &
```
#### Long answer (non-convex)
This non-golfed full-named code accepts coordinates (as a ragged list) of any two polygons (may be non-convex).
Output a region for to show and [list of non-collinear vertices](https://mathematica.stackexchange.com/questions/137527/finding-non-collinear-vertices-of-a-convex-hull) of Minkowski sum:
```
minkowski[verts_] := With[{polys = Polygon /@ verts},
(*Decompose the polygons into a disjoint union of convex parts*)
coords = (PolygonCoordinates /@
PolygonDecomposition[#, "Convex"]) & /@ polys;
(*Find Minkowski sum for every convex parts as convex hulls
and put them together*)
region = RegionUnion @@ ConvexHullMesh /@ Flatten[
(Table[Join @@ Outer[Plus, c1, c2, 1], {c1, #1}, {c2, #2}]) & @@
coords
, 1];
(*Select only non-collinear vertices *)
pickNonColl =
With[{v = #},
Pick[v, Function[{k},
Nor @@ (RegionMember[ConvexHullMesh[#], k] & /@
Subsets[Complement[v, {k}], {2}])] /@ v]] &;
{region, pickNonColl@MeshCoordinates@region}
];
poly1 = {{-1, -1}, {-2, -4}, {-3, -1}, {-2, -2}};
poly2 = {{1, 1}, {2, 4}, {3, 1}, {2, 2}};
res = minkowski[{poly1, poly2}];
Show[res[[1]], Graphics[Polygon@{poly1, poly2}]]
```
[](https://i.stack.imgur.com/TtBVy.jpg)
```
poly1 = {{-1, 0}, {0, 1}, {1, 0}};
poly2 = {{1, 0}, {0, -1}, {-1, 0}};
res = minkowski[{poly1, poly2}];
res[[2]]
{{-2., 0.}, {-1., -1.}, {-1., 1.}, {1., 1.}, {1., -1.}, {2., 0.}}
```
] |
[Question]
[
Inspired by [this Puzzling challenge](https://puzzling.stackexchange.com/q/100507).
## Challenge
Given a 2D rectangular grid where each cell is either an empty space or a wall, find the path (or one of the paths) from the top left cell to the bottom right, which satisfies the following:
1. Only movement to one of four adjacent cells is allowed.
2. The path breaks (or passes through) the minimal number of walls possible. In other words, a longer path that breaks fewer walls is preferred over a shorter path that breaks more walls.
3. Among all paths that satisfy `2.`, the path is the shortest in terms of the number of cells visited in total.
The input can be taken as a matrix (or any equivalent) containing two distinct values to represent empty spaces and walls. The top left and bottom right cells are guaranteed to be empty.
Output the path as a grid (of the same dimensions as the input) containing two distinct values, one for the cells that are part of the path and the other for the rest.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Shortest code in bytes wins.
## Test cases
In the following examples, the input uses `.#` for empty/wall, and the output uses `.+` for non-path/path.
```
Input
..#..#..
Output
++++++++
Input
.#...
...#.
Output
+.+++
+++.+
Input
....
....
....
....
Output
++++
...+
...+
...+ (or any other path of same length)
Input
..#..
..#..
..#..
Output
+++++
....+
....+ (or any other path of same length that breaks only one walls)
Input
.#.#.
##.##
.###.
Output
+++++
....+
....+ (or 3 other possible answers)
Input
.......
######.
.......
.######
....#..
Output
+++++++
......+
......+
......+
......+
Input
.....#..
#######.
#######.
........
.#######
.#######
....#...
Output
++++++++
.......+
.......+
++++++++
+.......
+.......
++++++++
```
[Answer]
# JavaScript (ES7), ~~198 185 179~~ 178 bytes
Expects a matrix of integers with `-1` for a wall and `0` for an empty cell. Returns a matrix of Boolean values.
```
m=>(g=(Y,w,n,X)=>w>=W&&w>W|n>N?0:m[Y+1]||1/m[Y][X+1]?m.map((r,y)=>r.map((v,x)=>v>0?1:(X-x)**2+(Y-y)**2^1?0:r[r[x]=1,g(y,w-v,-~n,x),x]=v)):o=g(-1,W=w,N=n))(0,0,W=++m[0][0]/0,0)&&o
```
[Try it online!](https://tio.run/##XZBfb4IwFMXf@RRNmsitlAp7dCk@bY978UENYwlBZCzSuuJAM7ev7m7LdH9IuT2/23PatC95l7eFqXf7UOl1ed7IcyMTqCSseM8VXzKZ9IlcjEZ9sjip5GEWTZt0FcTZ6RRPUGXpEmHWiCbfARh@xIAZoOMHhC6JZvEUluGBjcc3AazCoxVPMe5kUpMeMhnzCo68DzsefioMcex1jE21rCCM@UL2/EEqxiDiEVIQNGmU4Zggs9FIn035@labEvxN6zNhynx9X2/L@VEVEDGx1/O9qVUFTLS7bb0H/1E9KjRutLnLi2doiUzIu0dIQyRpf0xosRdxy6kQos0cF5ZDO0niU58xdotZU6KPbKBxVGjV6m0ptroCXHE5Y3PD23RW@mLpp0GXMfGiawU@7vSt7NEkIG6@9T7YWXiesL/nBHUDFVZsWbLtQf8ug/dPtSG0U6wUNb1ErZ26T1xZDA3HQ/ai6MVK/2WuIfpLDCHxBQ "JavaScript (Node.js) – Try It Online")
### Commented
This is a depth-first search. Visited cells are marked with `1`. We keep track of the number of broken walls in `w` and the total number of visited cells in `n`. We abort as soon as the current path is worse than the best path found so far.
```
m => ( // m[] = input matrix
g = ( // g is a recursive function taking:
Y, w, n, X // (X, Y) = current position
// w = number of broken walls
) => // n = number of visited cells
w >= W && w > W | n > N ? // if (w, n) is worse than (W, N):
0 // abort
: // else:
m[Y + 1] || // if there's a cell below the current cell
1 / m[Y][X + 1] ? // or a cell on the right:
m.map((r, y) => // for each row r[] at position y in m[]:
r.map((v, x) => // for each value v at position x in r[]:
v > 0 ? // if v is positive:
1 // yield 1
: // else:
(X - x) ** 2 + // if the squared distance between
(Y - y) ** 2 ^ 1 ? // (X, Y) and (x, y) is not equal to 1:
0 // do nothing
: // else:
r[r[x] = 1, // mark r[x] as visited by setting it to 1
g(y, w - v, // do a recursive call at (x, y) with n+1
-~n, x), // if v = -1, w is also incremented
x // actual index ...
] = v // ... to restore r[x] to v afterwards
) // end of inner map()
) // end of outer map()
: // else (bottom-right cell):
o = g(-1, W = w, N = n) // update (W, N) and use a last recursive call
// with X undefined and Y=-1 to build the output o
)(0, 0, W = ++m[0][0] / 0, 0) // initial call to g at (0, 0); set the cell at (0, 0)
// to 1 and set W to +inf
&& o // return o
```
The purpose of the last recursive call `o = g(-1, W = w, N = n)` is to create a copy of the current maze where all visited cells are marked with *true* and all other cells are marked with *false*.
For this call, it's important to notice that:
* because `W = w` and `N = n`, the abort test is always false
* because `Y = -1`, the test on `m[Y + 1]` is always true
* because `X` is undefined, the squared distance is always *NaN*
Therefore, what is actually done is simply:
```
m.map((r, y) => r.map((v, x) => v > 0 ? 1 : 0))
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 92 bytes
```
≔⟦⟧θWS⊞θι⊞υ⟦⁰¦⁰ω⟧≔⟦⟧ηFυ«⪫θ¶←F§ι²✳κ+¿∨ⅈⅉFruld«≔⊟KD²✳κζF№#.∨ζ+⊞υEι⁺μ⎇⁼ν²κ⁼ν⌕#.ζ»⊞ηι⎚»F⊟⌊η✳ι+¦+
```
[Try it online!](https://tio.run/##bVDBTgIxED3vfsWke5nGSgxHPRHUBCNxEz1ogMOGLWxDaaG7BcXw7eu0i8LBpk1npjPvvb55Vbi5LXTbDupaLQ1OZgK2/C7dV0pLwJHZ@Oa1ccoskXPIfV3hVoCijhh7AZMbAbT3M6pdgFSULqwD9By@0yQniAafrDJhnk0N49SQjO1O4u2zXDQhi/2DZmRK@YlKQD9QxsF75eS8UdbgitP4FQvtagH44vAdqfRB8jhEAOa8LllkTU6CcrvBXMrVGaYv4BKTE8QhYHYahtYTKct6TAAxHDrKXwPo0@NiEwTm2te4FvAmnSncFz5sfaFrNEG6gJWAc@FRmfKEeOBxEdsxTaSuZQdbdb4mQy0LhxQdOwOD@LEyau3XWPF/LFF/lnQvMW7bXpb1aKUZ3XTSkFCYttc7/QM "Charcoal – Try It Online") Link is to verbose version of code. Times out for larger grids (can just about do 3×8 but can't do 4×6). Takes grid in example format and outputs using `+`s and spaces. Explanation:
```
≔⟦⟧θWS⊞θι
```
Input the grid.
```
⊞υ⟦⁰¦⁰ω⟧
```
Start with an initial state of no `.`s, no `#`s and no moves. (Strictly speaking this is incorrect but all paths must include the initial square so it cancels out.)
```
≔⟦⟧η
```
Start with no paths that reach from the end to the start.
```
Fυ«
```
Perform a breadth-first search of the states.
```
⪫θ¶←
```
Draw the input to the canvas, leaving the cursor at the end point.
```
F§ι²✳κ+
```
Draw the path so far.
```
¿∨ⅈⅉ
```
If the start hasn't been reached, then:
```
Fruld«
```
Loop over the orthogonal directions.
```
≔⊟KD²✳κζ
```
Look at the next character in that direction.
```
F№#.∨ζ+
```
If the character is a `#` or a `.`, then...
```
⊞υEι⁺μ⎇⁼ν²κ⁼ν⌕#.ζ
```
Create a new state, formed by adding to the existing state; for index 2, add the current direction; for index 1, add 1 if the character is a `.`; for index 0, add 1 if the character is a `#`. Push this state to the list of states.
```
»⊞ηι
```
But if the start was reached, then record this state.
```
⎚»
```
Clear the canvas ready for the next state (or the final output).
```
F⊟⌊η✳ι+¦+
```
Get the minimum state, which is that with the fewest walls, or for states with equal walls, the one with the fewest non-walls (which is equivalent to the shortest path). (For states with equal wall and path length, the tie is broken by preferring paths that go left rather than up from the end.) Draw this state, plus the final position.
Much faster 101-byte version readily handles all the test cases:
```
≔⟦⟧θWS⊞θι⊞υ⟦⁰¦⁰ω⟧≔⟦⟧ηW∧υ⊟υF∨¬η‹ιη«⪫θ¶←F§ι²✳λ+¿∨ⅈⅉFruld«≔⊟KD²✳λζF№#.∨ζ+⊞υEι⁺ν⎇⁼ξ²λ⁼ξ⌕#.ζ»≔ιη⎚»F⊟η✳ι+¦+
```
[Try it online!](https://tio.run/##bZDBTgIxEIbPu0/RlMs01o3hqCeCmmBAN9GDBjlsoLCNTQvtFhDDs6/T7sruwUkP0@nM9/@dZVnYpSlUXY@ckxsN8wUnO3aXHkqpBIGJ3vrqtbJSb4AxkntXwo4TiR0x95zMbzjBc1hgrQcpO8hIr0JjbrbgGVLWxhJ4sfBsKigZJ1PhHMgwgo8/aZKjXAVPRuqgRT81ZQhLZmYv4HYq1lW4RciomuiVOIbhYbAXB@@lFctKGg0K4fSKhna5jpLvgKUPuLig1qsVjapJaz7YzIX46jBDTvpMhohTYDYexsajKB1klBNUODWSf8vCf8@KbTCYK@9Ac/ImrC7sNzzsfKEcHIN1ThQnXeFR4sYa4onFQLVzmgjlBGltymbFyViJwgJm5zTaCfbLf3YhL7toXmJe11mIQZalgyZ6SdZGmrWlXtIMZWl9vVe/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⟦⟧θWS⊞θι
```
Input the grid.
```
⊞υ⟦⁰¦⁰ω⟧
```
Create the initial state.
```
≔⟦⟧η
```
Start with no path.
```
W∧υ⊟υ
```
Perform a depth-first search of the states, by removing the most recently added state each time.
```
F∨¬η‹ιη«
```
If we don't have a path yet, or it's longer than our path so far, then:
```
⪫θ¶←F§ι²✳λ+
```
Draw the input and the path so far.
```
¿∨ⅈⅉFruld«≔⊟KD²✳λζF№#.∨ζ+⊞υEι⁺ν⎇⁼ξ²λ⁼ξ⌕#.ζ»
```
If the start hasn't yet been reached then consider all possible steps and push the resulting state to the list of states.
```
≔ιη
```
Otherwise this must be the shortest path so far, so save it.
```
⎚»
```
Clear the canvas ready for the next state (or the final output).
```
F⊟η✳ι+¦+
```
Draw the shortest path found.
] |
[Question]
[
Given a rectangular board of cells with some number of holes in it, determine whether it is possible to complete a "holey knight's tour" (That is, a path that visits every non-hole cell exactly once using only chess knight moves, not returning to the starting cell) that starts on the top-left cell.
For the sake of completeness of the challenge definition, knights move by teleporting directly to a cell that is two cells away along one axis and one cell along the other axis.
## Examples
Using `.` for open spaces and `X` for holes
### 1
```
. . .
. X .
. . .
```
YES
### 2
```
. . . X
. X . .
. . X .
X . . .
```
NO
### 3
```
. . . . .
X . . . .
. . X . .
. X . . .
. . . . .
```
YES
### 4
```
. . X . .
X . . . X
. . . . .
. X . . .
X . . X X
```
YES
### 5
```
. . . . . .
. . X . . .
. X . . . .
. . . . . .
. . . . . .
```
NO
## Rules and Assumptions
* You must theoretically be able to support boards up to 1000x1000
* Boards do not necessarily have to be square
* As this problem could potentially have exponential time complexity in the worst case, and in an effort to not make testing solutions take forever, board sizes up to 6x6 must return an answer within one minute on modern hardware.
* A board with a hole in the top-left corner (where the knight starts) is always unsolvable
Shortest code wins
[Answer]
# Sledgehammer, 29 bytes
```
⠑⡘⣡⡪⡾⢸⢹⣎⡷⡬⢵⣅⢞⣽⣤⡥⠃⠏⢂⢜⠩⡬⢸⠜⡻⣠⡪⢄⡯
```
That's not very readable, so here's the corresponding Mathematica code:
```
AnyTrue[Thread@
FindHamiltonianPath[
Subgraph[KnightTourGraph[#2, #3],
o = First /@ StringPosition[#, "."]], 1, o],
ListQ@# && Length@# > 0 &] &
```
This removes unneeded vertices from the knight's graph (first obtained via KnightTourGraph), calls `FindHamiltonianPath` with all possible end vertices (it either takes nothing and finds *any* Hamiltonian path, or it takes both a start and an end vertex) and checks whether any paths were actually found.
Example input (for the fourth test case)
```
{"..X..X...X......X...X..XX", 5, 5}
```
The first line is a flat version of the grid (obtained by reading it in row-major order).
I have first thought that this doesn't work, but then I investigated and finally found what seems to be a bug in the interpreter: the `hammer.wls` main script doesn't call `postprocess`, and (when decoding) it ends up evaluating the code with all slots (`#, #2, #3`) replaced by variables `s1, s2, s3` :(. Fortunately, the interactive app, while even less convenient, doesn't have this bug.
[Answer]
# [Python 3](https://docs.python.org/3/), 166 bytes
```
def f(g,s=[0]):w=len(g[0])+2;k='XX'.join(g)+w*'XXX';*p,x=s;return{*s,'.'}>{*p,k[x]}and any(f(g,s+[x+a])|f(g,s+[x-a])for a in(w+2,w-2,w-~w,w+w-1))|len(s)//k.count('.')
```
[Try it online!](https://tio.run/##jZHLCoMwEEX3/YrskjExfe0q9jsC4kKq9mGJ4oMo2v66HQsuqtI2EJh7M/dwIVlTXlK97/swiknMzqJwvY0PB@PeI83Ow8x3TuJSpai8pVf0gBsLpaKOlYnaLZw8Kqtct1YhqKSPY4t24tX@I9AhCXTD3lju1TzwoRuFjSJOcxIQZBq@E8Ye7tMIw429BeiGAgWs14k8pZUuGcKhz/IrjjHzqJSSihUZD5VqovHdB1h9JNQ0Ms1MIGqRIudLc86s3WznX7ZayH1no4H/84v9f8vF3v0L "Python 3 – Try It Online")
Brute force all paths.
Adaptation from my answer to [Find the shortest route on an ASCII road](https://codegolf.stackexchange.com/a/195042/87681).
[Answer]
# [R](https://www.r-project.org/), ~~243~~ 213 bytes
*Edit: -30 bytes by merciless code-trimming...*
```
function(p,m,n=1e4,f=function(p,m,x){m[t(p)]=1
d=p+matrix(c(q<-c(1,2,2,1,1,-2,2,-1),-q),2)
`if`(w<-sum(v<-!m[d<-t(d[,!colSums(d<1|d>dim(m))])]),f(d[which(v)[sample(w,1)],],m),!sum(!m))})mean(sapply(1:n,f,p=p,m=m))
```
[Try it online!](https://tio.run/##jZBNa8MwDEDv@RUJvUhMhjpNChvxbrtuh55GCGvIBwnUqVs7bce2357JdIMVVjZ0MZKe/KT91JX2xW3HvZracahcvx3AkKZBySahVl0kT/imcwcGCyWDWpkbXbp9f4IKdpmoQFLMITmEfwiJJHZIMQbrvl3DMRN21HDIRKTzOhMO6pyiartZjdpCncn3@r7uNWjEgoNarh@7vurggLkttdk0cCSJBRWkkSI/LOLmD9RNOYAtjdm8grwbqCWj2FdxcZqFrrHOBkZ5QYlBwPmz9pwWtMBA52zrN/o@hd8Vw1n4/LC66E4o8d0VJLQkycMW@Bv2@HRBpZSeqZhuv5Dwz69@QKnH@LRzitkzxf@YLml5xhlNrklOnw "R – Try It Online")
This is a stochastic algorithm.
The complete search ([163 bytes](https://tio.run/##jZBNS8NAEIbv@ysSepnBCXTzBUK3t3rUQ08Sgg1Zg4Fusk02RVF/e5y1FSwoyhx2Ft5n9pkd5qdqfHD9NKi5Uc3U1a7tO7Bk8NUUDiyWSgqt7JWp3NA@Qw2HVVSDpJhLckW@iSRSdECKkbMOdEFh3e@3kxlBr@SbXuvWgEEsURyVLkJT6JJID71VN6XYtc0Oqu4Fjkj@qKzd84WHN@yBFI6TgZC793kRuMfRjcIq7yBRCKPOZktKKEFhChby0l@LfS4TLIL7zfYinVLq0zWklJPkYQn@hN3eXVAZZScqpuszEvz51Dco8xj/3pJi9szwP6Y55Sec0fQ3yfkD)) of all tours on a 6x6 board without holes can require up to approx 36 (positions) x 2^36 (combinations of already-visited squares or holes), which does not run in a <1 minute time-frame, and even memoising already-tried partial-tours isn't feasible (since unfortunately R vectors are limited to a length of 2^31).
So instead we repeatedly attempt random tours. 1e5 random tours is sufficient to sample the entire, no-hole, 6x6 board and repeatedly find successful tours within 1 minute (although unfortunately not on TIO).
At the cost of 1 wasted byte, the implementation here reports the fraction of successful to unsuccessful attempted tours.
[Answer]
# [Perl 5](https://www.perl.org/), 305 bytes
```
sub f{my($b,$x,$y)=(@_,1,1);$b=~/.+/;$lx=length$&;$P=sub{($X,$Y)=@_;$X<1||$X>$lx||$Y<1||$Y>$b=~y/\n//?0:($Y-1)*($lx+1)+$X};(!(substr($b,&$P($x,$y)-1,1)=~s,\.,x,)or$b!~/\./)||(any{f($b,@$_)}grep{substr($b,&$P(@$_)-1,1)eq'.'}map[$x+$$\_[0],$y+$$_[1]],[2,-1],[2,1],[1,-2],[1,2],[-2,1],[-2,-1],[-1,2],[-1,-2])}
```
[Try it online!](https://tio.run/##XVLbbptAEH3nKybpKuzGAxhLfTEhcaT2rU0iNZWw7BTZZIOpMFAWK7Z8@XV3drFrN0Kay5lzZmbZrWSdf94vlIRvmWr6/Z9NloM9KVZ2AJ8qKsJ0keWNkxXAJ5CUtYR5@brIpcCWBlOZl@@QTAqKIJlNilS@QlOCndayspH0DVWSci4VzBfJDBTxZb1Xiym8recrzqbIlshWIuSDGH30RcCm4c5zO17A8mWYyyJtZuwqYE8hidacRciGIhzEAYtu/M2GRbfEIz802fBWy1feuPC8u26fs6Hji2tOlI4vOizaBvyCUyPV1Hr2FXvi7XxHzw53CscuLlGUNZte7Lyx64nNhtNZ12@aP2Cx2Oqzrf/voXHTQf6xXXs7n1QjtuwwFo@6L9TdRP7LC4566PjGaeuj0zNOW6fFnAPDOaCGI7b7@QoGjVRNSL1BISCmNbbx8OsP95r@nToCD4@Un9JfY9VBrPF3mRXctvHmy/3z/S0d1uPu9Z3gpN88PAovVYGlH8Oz1I/hO113YL3PslxyM1msLQB9ZVlRIZPLSoSqyrNEmip2sRcYAkvLJnwzNKGRTHENGQlekpFJAzoBQkGXLom3tV7LQsa6VVakgRXHess4tlygj2xkrI5pX6sNIWoLh5KmmIz8w@OR457QE@/Y8h92an1iHFXRGeOkan1E1bOFPgw5F5wP@hDTsvu/ "Perl 5 – Try It Online")
] |
[Question]
[
Do you love watching cool timelapses of constructions or other massive work done in minutes? Lets make one here.
We will be looking at an excavator digging quarry, making pictures each day to see whole progress. And your task is to show us this process!
Quarry is defined by the width of its first layer.
Excavator is defined by its capability to dig in one day.
## Input
Width of quarry. Integer number, always >= 1.
Excavator dig speed. Integer number, always >= 1.
## Output
Progress of digging quarry on each day.
Started with flat untouched ground and finished with completed quarry.
## Rules
* On the last day there may be less units to dig, than excavator is
capable of. Excessive work won't be used anywhere, so you should just
output fully dug quarry.
* All days progress must be present in the output at once. You can't clear or overwrite previous day progress in the output.
* Trailing and leading newlines for each day output are acceptable in any reasonable number.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your code as compact as possible.
## Clarifications
Work starts with a flat ground. Length of displayed ground is width of quarry + 2. So there always will be one underscore character on both sides of quarry.
```
__________
```
Dug quarry is looking like this for even width:
```
_ _
\ /
\ /
\ /
\/
```
And like this for odd width
```
_ _
\ /
\ /
\ /
V
```
Here are examples of quarry progress:
```
_ _______
V dug 1 unit
_ ______
\/ dug 2 units
_ ___
\___/ dug 5 units
_ _
\ __/ dug 10 units
\_/
```
Full progress example. Quarry width: 8. Excavator speed: 4 units per day.
```
__________
_ _____
\__/
_ _
\______/
_ _
\ __/
\__/
_ _
\ /
\ __/
\/
_ _
\ /
\ /
\ /
\/
```
## Cornercases
Excavator will need to dig on the last day exactly its capability (speed)
```
Width: 7, Speed: 3
Width: 10, Speed: 4
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~163~~ 156 bytes
```
.+
$*_
(_+)¶(_+)
$2¶$1¶$1
r`__\G
$%`$&
¶
;
(?<=(_+);.*)(?<=;_+;\1*)_
¶$`_
m`^_+;
__
+`(>*)_(_+)(_+<?;)\2
$1_$.2$* $3¶$1>$2<;
T`>\_` \\`>+_
T`\\\_;<`V/_`.<|;
```
[Try it online!](https://tio.run/##FU07CgIxFOzfKSyeskkgshFBeDFbegGxejjPwsJCi8XSc@0B9mIxKWaYH8z8/L4@j1pjIPagAcGtS2fitC48dtBsgF6It8Y7WhcSGqZ87iuJ3nUtCKKjd2g1G@ht95YQQMGG0vI@bsiTOE3EIzgm9hs@9IPCKQtdrShso2oloDlVhWS77WEx/6TWEx3/ "Retina 0.8.2 – Try It Online") Explanation:
```
.+
$*_
```
Convert the inputs to unary. This gives us `W¶S`.
```
(_+)¶(_+)
$2¶$1¶$1
```
Swap the inputs and duplicate the width. This gives us `S¶W¶W`.
```
r`__\G
$%`$&
```
Calculate the volume of the quarry. This gives us `S¶W¶V`.
```
¶
;
```
Join the inputs into one line. This gives us `S;W;V`.
```
(?<=(_+);.*)(?<=;_+;\1*)_
¶$`_
```
Calculate the amount of progress for each day on its own line. Each day has the format `S;W;D`, where `D` is `0` on the first line and increments by `S` each day until it reaches `V`.
```
m`^_+;
__
```
Delete `S` and increase `W` by 2 on each line. This gives us `G;D` for each day.
```
+`(>*)_(_+)(_+<?;)\2
$1_$.2$* $3¶$1>$2<;
```
While `D` is nonzero, dig either `D` or `G-2` from the line (so the first and last characters are always left), moving the depth to the next line. Each line is indented with one more `>` than the previous. Newly dug lines also include a `<`.
```
T`>\_` \\`>+_
```
Turn the indent into spaces and the following `_` into a `\`.
```
T`\\\_;<`V/_`.<|;
```
If a `<` is following a `\` then turn it into a `V`, if it's following a `_` then turn it into a `/`. Delete all the `<`s and `;`s.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 65 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Θ└R4∞√4Fµ■zJ┐╚▌▼ZJ╧fφ½à╘▲☼å♥s≥┤ÖòOúU╬ΩmPê|ë↕ƒ].Y┴↓á÷>}St☺┐B╒╞O☼╧O
```
[Run and debug it](https://staxlang.xyz/#p=e9c05234ecfb3446e6fe7a4abfc8dd1f5a4acf66edab85d41e0f860373f2b499954fa355ceea6d50887c89129f5d2e59c119a0f63e7d537401bf42d5c64f0fcf4f&i=4+8%0A3+7%0A4+10&a=1&m=2)
If first calculates the digging characters, in one flat string. Then it adds depth. For instance `"_V___"` is one day of digging, and `"_\V/_"` is the completed flat string.
It uses this method for doing one unit of digging.
1. Start with a single "\", plus the appropriate number of "\_" characters.
2. If "V\_" is in the string, replace it with "/".
3. Otherwise, if "/\_" is in the string, replace it with "\_/".
4. Otherwise, if "\\_" is in the string, replace it with "\V".
5. The new string is the result from one unit of digging. Repeat from step 2.
Here's the whole program unpacked, ungolfed, and commented.
```
'_*'\s+ initial string e.g. "\_______"
{ generator block to get each day's flat digging results
{ block to repeat digging within each day
"V_\//__/\_\V"4/ replacement strings
{[2:/|em|!H find the first substring that exists and do replacement
};* repeat digging within day specified number of times
gu get all unique results
when digging is complete, the result duplicates
{Dm drop the leading "\" characters from each result
F for each day's flat result, execute the rest of the program
'_|S surround with "_"
M split into chars; e.g. ["_", "\", "/", "_"]
c|[ copy and get all prefixes
{ mapping block to get "depth" of each character
'\# get number of backslashes in this prefix (A)
_1T'/#- get number of forward slashes prior to last character of prefix (B)
'V_H=+^ is the current character "V"? 1 for yes. (C)
m map prefixes to A - B + C + 1
\ zip depths with original characters
{E)m prefix each character with spaces; e.g. ["_", " \", " /", "_"]
M transpose grid; e.g. ["_ _", " \/ "]
m print each row
```
[Run and debug it](https://staxlang.xyz/#c=%27_*%27%5Cs%2B+++++++++++++%09initial+string+e.g.+%22%5C_______%22%0A%7B+++++++++++++++++++%09generator+block+to+get+each+day%27s+flat+digging+results%0A++%7B+++++++++++++++++%09block+to+repeat+digging+within+each+day%0A++++%22V_%5C%2F%2F__%2F%5C_%5CV%224%2F%09replacement+strings%0A++++%7B[2%3A%2F%7Cem%7C%21H+++++%09find+the+first+substring+that+exists+and+do+replacement%0A++%7D%3B*+++++++++++++++%09repeat+digging+within+day+specified+number+of+times%0Agu++++++++++++++++++%09get+all+unique+results%0A++++++++++++++++++++%09%09when+digging+is+complete,+the+result+duplicates%0A%7BDm+++++++++++++++++%09drop+the+leading+%22%5C%22+characters+from+each+result%0AF+++++++++++++++++++%09for+each+day%27s+flat+result,+execute+the+rest+of+the+program%0A++%27_%7CS++++++++++++++%09surround+with+%22_%22%0A++M+++++++++++++++++%09split+into+chars%3B+e.g.+[%22_%22,+%22%5C%22,+%22%2F%22,+%22_%22]%0A++c%7C[+++++++++++++++%09copy+and+get+all+prefixes%0A++%7B+++++++++++++++++%09mapping+block+to+get+%22depth%22+of+each+character%0A++++%27%5C%23+++++++++++++%09get+number+of+backslashes+in+this+prefix+%28A%29%0A++++_1T%27%2F%23-+++++++++%09get+number+of+forward+slashes+prior+to+last+character+of+prefix+%28B%29%0A++++%27V_H%3D%2B%5E+++++++++%09is+the+current+character+%22V%22%3F+1+for+yes.+%28C%29%0A++m+++++++++++++++++%09map+prefixes+to+A+-+B+%2B+C+%2B+1%0A++%5C+++++++++++++++++%09zip+depths+with+original+characters%0A++%7BE%29m++++++++++++++%09prefix+each+character+with+spaces%3B+e.g.+[%22_%22,+%22+%5C%22,+%22+%2F%22,+%22_%22]%0A++M+++++++++++++++++%09transpose+grid%3B+e.g.+[%22_++_%22,+%22+%5C%2F+%22]%0A++m+++++++++++++++++%09print+each+row&i=4+8%0A3+7%0A4+10&a=1&m=2)
[Answer]
# [Python 2](https://docs.python.org/2/), 265 bytes
```
w,s=input();R=range((3+w)/2)
d=0
while d-s<sum(range(w%2,w+1,2)):
q=[[' _'[i<1]]*(w+2)for i in R];D=d
for i in R[:-1]:
a=min(D,w-i*2);D-=a
if a:q[i][1+i:1+i+a]=[' ']*a;q[i+1][1+i:1+i+a]=(['\\']+['_']*(a-2)+['/'])*(a>1)or['v']
for l in q:print''.join(l)
d+=s
```
[Try it online!](https://tio.run/##VY7PasMwDMbvfgpfhqw4bmd3MEjqnvIEvbqmGNKuGqnztzN7@syjh7GDQPrp06dv@F5ufTTrmsrZUhwei8D6aKcQPy5C7GTCrUHW2leWbtRdeKvm/fy4i6cgvZgySV0axIrx0ToH/AyO9tr7QiRp8NpPnDhFfvR1Y1vG/4CrlPb5jAd7pyiaMikqDNaNsiFTuvJQjY6805KqXDJ4m/3BF6HOXOp/G@HgdAIvHZyzQgRlMPdb8JiHg8Z@cvAF/hmg@w0wVsNEcQHYfPb5f4eMt9LO6/pevv0A "Python 2 – Try It Online")
[Answer]
* golf in progress
# [JavaScript (Node.js)](https://nodejs.org), 329 315 307 300 301 298 285 275 260 254 bytes
* fixed solution duo to error on odd w(thanks to @Shaggy) + reduce by 2 bytes
* thanks to @Herman Lauenstein for reducing by 1 byte
```
(w,s)=>{h=[...Array(-~w/2+1|0)].map((x,i)=>[...(i?" ":"_").repeat(w)])
for(t=S="";t<s&&h.map((x,i)=>S+=(p=i?" ":"_")+x.join``+p+`
`);)for(y in t=s,h)for(x in D=h[y])if(D[x]=="_"&&t){(d=h[-~y])[x]=x^y?(d[x-1]=x^-~y?"_":"\\","/"):"v"
D[x]=" "
t--}return S}
```
[Try it online!](https://tio.run/##bY7RToMwFIbveQrSC3JOaDunJjPMSkz2BlwyFDJAukxKSh0lc3t1LLtRk92d//v/Lzn74lj0Oy07w1pVVlMtJhhoj@Ll1IiUc/6qdTECuwyL@3D5fYcZ/yw6AEul28wDkDHxSUTeCXJddVVhYMAMvVppMCIRhKzNcx8EzV8xCQV04tcMLd8r2eZ52IW5l@MaZ330Zesb0dPmGu0cN6JJxwxlDZvUZkI4OwgMnqB0Bbu4asb2bYyhTC1bzrfDsdtFZLsllCwIRuRIvKvvHvAMY2ddmS/d@sl52qm2V4eKH9QH1LCij4jef/Z0g63oww22RJx@AA "JavaScript (Node.js) – Try It Online")
### Explanation
```
(w,s)=>{
h=[...Array(-~w/2+1|0)] //the height of the quarry when finished is w/2+1 if even or (w+1)/2+1 if odd
.map((x,i)=>
[...(i?" ":"_").repeat(w)] //the first row is the _ w times (i will explain why w and not w+2 in the following lines) afterwards lets just fill with spaces so the output would be clear(when convertion to string)
)
for(t=S=""; //t="" is like t=0(we actually need t to be different from s in the start and s>=1), S will hold the final output
t^s&& //if t not equals s -> it means that now changes were made to the quarry->it means we finished digging
h.map((x,i)=>
S+=(p=i?" ":"_")+x.join``+p+` //here comes the reason for w and not w+2. because the border _XXXX_ are not to be touched i only add them to the output and not woking with them in the solution
//that ways its much easier to replace the correct chars. so here i just add _ to either sides if its the first row otherwise space(to pad correctly).
//in the end i add a new line to differ from the previous day
`);)
for(y in t=s,h) //always update t back to s so we know weve passed a day
for(x in D=h[y])
if(D[x]=="_"&&t) //if the current cell is _ we need to work, but only if the day have yet to pass(t)
{
(d=h[-~y])[x]= //updating the row below us because we just dug a hole
x^y? //if x == y that means we are digging the first hole in the row below
(d[x-1]=x^-~y?"_":"\\", //we want to update the row below and cell before([y+1][x-1]) only if its not the first cell(AKA not space). if v we need \ other wise _
"/") //other wise (x!=y) we put "/"
:"v" //so we should put v (if they are equal)
D[x]=" " //always remove the _ from the current one because we dug it
t--} //decrement the counter for the day by one digging
return S}
```
] |
[Question]
[
**Mathematical Background**
Let A be an N by N matrix of real numbers, b a vector of N real numbers and x a vector N unknown real numbers. A matrix equation is Ax = b.
Jacobi's method is as follows: decompose A = D + R, where D is the matrix of diagonals, and R is the remaining entries.
if you make an initial guess solution x0, an improved solution is x1 = inverse(D) \* (b - Rx) where all multiplications are matrix-vector multiplication and inverse(D) is the matrix inverse.
---
**Problem Specification**
* **Input**: Your complete program should accept as input the following data: the matrix A, the vector b, an initial guess x0, and an 'error' number e.
* **Output**: The program must output the minimum number of iterations such that the latest solution differs by the true solution, by at most e. This means each component of the vectors in absolute magnitude differ by at most e. You must use Jacobi's method for iterations.
How the data is inputted is *your choice*; it could be your own syntax on a command line, you could take input from a file, whatever you choose.
How the data is outputted is *your choice*; it can be written to a file, displayed in the command line, written as ASCII art, anything, as long as it is readable by a human.
**Further Details**
You are not given the true solution: how you calculate the true solution is up to you entirely. You may solve it by Cramer's rule for example, or computing an inverse directly. What matters is that you have a true solution to be able to compare to iterations.
Precision is an issue; some people's 'exact solutions' for comparison may differ. For the purposes of this code golf the exact solution must be true to 10 decimal places.
To be absolutely clear, if even one component of your present iteration solution exceeds its corresponding component in the true solution by e, then you need to keep iterating.
The upper limit to N varies based on what hardware you're using and how much time you're willing to spend running the program. For the purposes of this code golf, assume maximum N = 50.
**Preconditions**
When your program is called, you are free to assume that the following holds at all times:
* N > 1 and N < 51, i.e. you will never be given a scalar equation, always a matrix equation.
* All inputs are over the field of real numbers, and will never be complex.
* The matrix A is always such that the method converges to the true solution, such that you can always find a number of iterations to minimise the error (as defined above) below or equal to e.
* A is *never* the zero matrix or the identity matrix, i.e. there is one solution.
---
**Test Cases**
```
A = ((9, -2), (1, 3)), b = (3,4), x0 = (1,1), e = 0.04
```
The true solution is (0.586, 1.138). The first iteration gives x1 = (5/9, 1), differing by more than 0.04 from the true solution, by at least one component. Taking another iteration we find, x2 = (0.555, 1.148) which differs by less than 0.04 from (0.586, 1.138). Thus the output is
```
2
```
---
```
A = ((2, 3), (1, 4)), b = (2, -1), x0 = (2.7, -0.7), e = 1.0
```
In this case the true solution is (2.2, -0.8) and the initial guess x0 already has error less than e = 1.0, thus we output 0. That is, whenever you do not need to make an iteration, you simply output
```
0
```
---
**Submission Assessment**
This is code golf, with all standard loopholes hereby disallowed. The shortest correct *complete program* (or function), i.e. lowest number of bytes wins. It is *discouraged* to use things like Mathematica which wrap up a lot of the necessary steps into one function, but use any language you want.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~78~~ ~~68~~ ~~65~~ 49 bytes
*Exactly the type of problem APL was created for.*
-3 thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer). -11 thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn).
Anonymous infix function. Takes A b e as left argument and x as right argument. Prints result to STDOUT as vertical unary using `1` as tally marks, followed by `0` as punctuation. This means that even a 0-result can be seen, being no `1`s before the `0`.
```
{⎕←∨/e<|⍵-b⌹⊃A b e←⍺:⍺∇D+.×b-⍵+.×⍨A-⌹D←⌹A×=/¨⍳⍴A}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///3ysxOT8p81HbhOpHfVOB1KOOFfqpNjWPerfqJj3q2fmoq9lRIUkhFSTTu8sKiB91tLto6x2enqQLVANiPOpd4agLVOoCUtOz0/HwdFv9Qyse9W5@1LvFsfb/f41HbRM1LBUOrTfS1DBUMNbUVNAwVlAw0VQw0DMwUYDYrwCUAQIgockFVm@kAFQJFDQBKTcCajbUVDDUM1CAqzfSMweKGuiZawIA "APL (Dyalog Unicode) – Try It Online")
### Explanation in reading order
Notice how the code reads very similarly to the problem specification:
`{`…`}` on the given A, b, and e, and and the given x,
`⎕←` print
`∨/` whether there is any truth in the statement that
`e<` e is smaller than
`|⍵-` the absolute value of x minus
`b⌹` b matrix-divided by
`⊃A b e` the first of A, b, and e (i.e. A)
`←⍺` which are the left argument
`:` and if so,
`⍺∇` recurse on
`D+.×` D matrix-times
`b-` b minus
`⍵+.×⍨` x, matrix multiplied by
`A-` A minus
`⌹D` the inverse of D (the remaining entries)
`←` where D is
`A×` A where
`=/¨` there are equal
`⍳` coordinates for
`⍴A` the shape of A (i.e. the diagonal)
### Step-by-step explanation
The actual order of execution right-to-left:
`{`…`}` anonymous function where `⍺` is A b e and ⍵ is x:
`A b c←⍺` split left argument into A, b, and e
`⊃` pick the first (A)
`b⌹` matrix division with b (gives true value of x)
`⍵-` differences between current values of x and those
`|` absolute values
`e<` acceptable error less than those?
`∨/` true for any? (lit. OR reduction)
`⎕←` print that Boolean to STDOUT
`:` and if so:
`⍴A` shape of A
`⍳` matrix of that shape where each cell is its own coordinates
`=/¨` for each cell, is the vertical and horizontal coordinates equal? (diagonal)
`A×` multiply the cells of A with the that (extracts diagonal)
`⌹` matrix inverse
`D←` store in D (for **D**iagonal)
`⌹` inverse (back to normal)
`A-` subtract from A
`⍵+.×⍨` matrix multiply (same thing as dot product, hence the `.`) that with x
`b-` subtract that from b
`D+.×` matrix product of D and that
`⍺∇` apply this function with given A b e and that as new value of x
[Answer]
# [Python 3](https://docs.python.org/3/), 132 bytes
```
f=lambda A,b,x,e:e<l.norm(x-dot(l.inv(A),b))and 1+f(A,b,dot(l.inv(d(d(A))),b-dot(A-d(d(A)),x)),e)
from numpy import*
l=linalg
d=diag
```
[Try it online!](https://tio.run/##XYzLCoMwEEX3fkWWM@0YjAqlpS78lEjUBvKQYIt@vU1EqJRhFvfcx7TOL@@qbRsaI22nJGupo4X6R/803PlgYcmVn8Fw7T7QInWI0ikmrgOk6M9T8VrEmNgLbX4AWuL3mA3BW@bedlqZtpMP8yUzjdFOmjFTjdJy3Kag3QwDyBDkCgB3YnmJBIJYlZbZYVRUn5QgkVTBi0iz/40ydfeJ@jwRcS7Omt8iKfgtMcELxO0L "Python 3 – Try It Online")
Uses a recursive solution.
[Answer]
# [R](https://www.r-project.org/), 138 bytes
```
function(A,x,b,e){R=A-(D=diag(diag(A)))
g=solve(A,b)
if(norm(t(x-g),"M")<e)T=0
while(norm((y=solve(D)%*%(b-R%*%x))-g,"M")>e){T=T+1;x=y}
T}
```
[Try it online!](https://tio.run/##Vc3NCsIwDAfwe5@iKEKi6VirMEQrDLx6kb2Am90s7APm1Ir47LNOD3pJAvn/krbP@Vr0@aXOOtvUEJOjlAw@9joWsNVHeyhgKDEiskKfm/JqfCxFZnOom7aCDpwokEa7Ea4NJjpkt5MtzWcJ9y/Z4mQ6gVTsfXOIohjAxr9KdDKTK6fvT5Y8@xyqQ9daBxksSZJQNEdSpJAykCTfbU4LpCBcIB/z86m5lEeeGq7YD1WeDrGvVEFEIoiGkYS/Iv9x2L8A "R – Try It Online")
*thanks to NikoNyrh for fixing a bug*
It's also worth noting that there is an R package, [`Rlinsolve`](https://cran.r-project.org/web/packages/Rlinsolve/index.html) that contains a `lsolve.jacobi` function, returning a list with `x` (the solution) and `iter` (the number of iterations required), but I'm not sure that it does the correct computations.
[Answer]
## Clojure, ~~212~~ ~~198~~ 196 bytes
```
#(let[E(range)I(iterate(fn[X](map(fn[r b d](/(- b(apply +(map * r X)))d))(map assoc % E(repeat 0))%2(map nth % E)))%3)](count(for[x I :while(not-every?(fn[e](<(- %4)e %4))(map -(nth I 1e9)x))]x)))
```
Implemented without a matrix library, it iterates the process 1e9 times to get the correct answer. This wouldn't work on too ill-conditioned inputs but should work fine in practice.
Less golfed, I was quite happy with the expressions of `R` and `D` :) The first input `%` (A) has to be a vector, not a list so that `assoc` can be used.
```
(def f #(let[R(map assoc %(range)(repeat 0))
D(map nth %(range))
I(iterate(fn[X](map(fn[r x b d](/(- b(apply +(map * r x)))d))R(repeat X)%2 D))%3)]
(->> I
(take-while (fn[x](not-every?(fn[e](<(- %4)e %4))(map -(nth I 1e9)x))))
count)))
```
] |
[Question]
[
You may know the mathematician von Koch by his famous snowflake. However he has more interesting computer science problems up his sleeves.
Indeed, let's take a look at this conjecture:
Given a tree with `n` nodes (thus `n-1` edges). Find a way to enumerate the nodes from `1` to `n` and, accordingly, the edges from `1` to `n-1` in such a way, that for each edge `k` the difference of its node numbers equals to `k`. The conjecture is that this is always possible.
Here's an example to make it perfectly clear :
[](https://i.stack.imgur.com/eH0MT.gif)
**YOUR TASK**
Your code will take as input a tree, you can take the format you want but for the test cases I will provide the tree by their arcs and the list of their nodes.
For example this is the input for the tree in the picture :
```
[a,b,c,d,e,f,g]
d -> a
a -> b
a -> g
b -> c
b -> e
e -> f
```
Your code must return the tree with nodes and edges numbered.
You can return a more graphical output but I will provide this kind of output for the test cases :
```
[a7,b3,c6,d1,e5,f4,g2]
d -> a 6
a -> b 4
a -> g 5
b -> c 3
b -> e 2
e -> f 1
```
**TEST CASES**
```
[a,b,c,d,e,f,g] [a7,b3,c6,d1,e5,f4,g2]
d -> a d -> a 6
a -> b a -> b 4
a -> g => a -> g 5
b -> c b -> c 3
b -> e b -> e 2
e -> f e -> f 1
[a,b,c,d] [a4,b1,c3,d2]
a -> b a -> b 3
b -> c => b -> c 2
b -> d b -> d 1
[a,b,c,d,e] [a2,b3,c1,d4,e5]
a -> b a -> b 1
b -> c b -> c 2
c -> d => c -> d 3
c -> e c -> e 4
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") this the shortest answer in bytes win!
Note : This is *stronger* than the [Ringel-Kotzig conjecture](https://en.wikipedia.org/wiki/Graceful_labeling), which states every tree has a graceful labeling. Since in the Koch conjecture it is not possible to skip integers for the labeling contrary to the graceful labeling in the Ringel-Kotzig conjecture. Graceful labeling has been asked before [here](https://codegolf.stackexchange.com/questions/110366/is-my-graph-graceful).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 bytes
```
JŒ!³,$€
ǵy⁴VIAµ€Q⁼$€TðḢịø³JŒ!
```
[Try it online!](https://tio.run/nexus/jelly#@@91dJLioc06Ko@a1nAdbj@0tfJR45YwT8dDW4ECgY8a94AkQg5veLhj0cPd3Yd3HNoM0vD////EpOSU1LT0/9EpOomxOtGJOklgMh1IJukkg8lUIJmqkxYLAA "Jelly – TIO Nexus") (Use `GṄ³çG` as footer to make output prettier. )
Inputs similar to example, e.g. `abcdef` and `[d,a],[a,b],[a,g],[b,c],[b,e],[e,f]`
Outputs the list e.g. `a,b,c,d,e,f` in order.
Note: My program produces different values than the test cases as there are several possibilities which are all valid.
**Explanation**
```
JŒ!³,$€ - helper function, generates all possible numberings, input is e.g. 'abcd'
J - range(len(input)). e.g. [1,2,3,4]
Œ! - all permutations of the range.
³,$ - pair the input with ...
€ - each permutation. Sample element e.g. ['abcd',[3,1,2,4]]
ǵy⁴VIAµ€Q⁼$€TðḢịø³JŒ! - main dyadic link, input is e.g. 'abcd' and '[a,b],[b,c],[b,d]'
µy - use a numbering as an element-wise mapping e.g. 'abcd'->[3,1,2,4]
⁴ - apply this to the list of edges. e.g. '[3,1],[1,2],[1,4]'
V - turn this into an internal list.
IAµ€ - find absolute difference on each edge
Q⁼ - Is this invariant under deduplication? Returns 1 if the numbering is valid; 0 otherwise.
Ç $€ - apply this to all possible numberings
Tð - return the indices of all valid numberings
Ḣ - choose the first one and
ị - get the element corresponding to its index in
ø³JŒ! - all possible numberings
```
Save 1 byte by showing all possible solutions:
```
JŒ!³,$€
ǵy⁴VIAµ€Q⁼$€Tðịø³JŒ!
```
[Try it online!](https://tio.run/nexus/jelly#@@91dJLioc06Ko@a1nAdbj@0tfJR45YwT8dDW4ECgY8a94AkQg5veLi7@/COQ5tBqv///5@YlJySmpb@PzpFJzFWJzpRJwlMpgPJJJ1kMJkKJFN10mIB "Jelly – TIO Nexus") (Use `GṄ³çG⁷³G` as a footer to make output prettier)
Use [converter](https://tio.run/nexus/jelly#@@//cOdiQ4OHO7oObT06udjo4Y5FD3fMNzbSMTHVMTM6tPVR0xq3YiOuw@1Zjxrm6DxqmPtwd48KUBDEjdWJBgoA5axBHJDczrVAFkjw////0Yk6STrJOik6qTppOumxCsggOtFcJ8lYJ9lMJ8VQJ9VUJ81EJ90olitFQddOIVEBK4DKmXElghhJ2BVB5UwgitJR5GztkBWlK5hyJYEYydhNgsoZQxSl4lGUqmDElQpipGFXBJUzBAA "Jelly – TIO Nexus") to copy-paste test case into an input list.
[Answer]
# Ruby, 108 bytes
lamba function, accepts an array of 2-element arrays containing the edges (where each edge is expressed as a pair of numbers corresponding to the relevant notes.)
```
->a{[*1..1+n=a.size].permutation.map{|i|k=a.map{|j|(i[j[0]-1]-i[j[1]-1]).abs}
(k&k).size==n&&(return[i,k])}}
```
**Ungolfed in test program**
```
f=->a{ #Accept an array of n tuples (where n is the number of EDGES in this case)
[*1..1+n=a.size].permutation.map{|i| #Generate a range 1..n+1 to label the nodes, convert to array, make an array of all permutations and iterate through it.
k=a.map{|j|(i[j[0]-1]-i[j[1]-1]).abs} #Iterate through a, build an array k of differences between nodes per current permutation, as a trial edge labelling.
(k&k).size==n&&(return[i,k]) #Intersect k with itself to remove duplicates. If all elements are unique the size will still equal n so
} #return a 2 element array [list of nodes, list of edges]
}
p f[[[4,1],[1,2],[1,7],[2,3],[2,5],[5,6]]]
p f[[[1,2],[2,3],[2,4]]]
p f[[[1,2],[2,3],[3,4],[2,5]]]
```
**Output**
output is a 2 element array, containing:
the new node numbering
the edge numbering.
For example the first edge of the first example `[4,1]` is between nodes 6 and 1 under the new node numbering and is therefore edge 6-1=5.
```
[[1, 5, 2, 6, 3, 4, 7], [5, 4, 6, 3, 2, 1]]
[[1, 4, 2, 3], [3, 2, 1]]
[[1, 5, 3, 4, 2], [4, 2, 1, 3]]
```
There are in fact multiple solutons for each test case. the `return` stops the function once the first one is found.
[Answer]
# Python3, 237 bytes:
```
def f(d,e,C=[]):
if len(C)==len(d)-1:yield d
for u,v in e:
K={*range(1,len(d)+1)}-{*d.values()}
for x in[K,[d[u]]][d[u]!=0]:
for y in[K,[d[v]]][d[v]!=0]:
if abs(x-y)==max(C+[0])+1:yield from f({**d,u:x,v:y},e,C+[abs(x-y)])
```
[Try it online!](https://tio.run/##jZPPjtowEMbP66eYcsEOw4ok7LaKlF44rtQXSK3KiW1qKTiRCRSEeHZqbwL9RyN8saXvN/Y3M5722H1vbPqpdZeLVBo0lahwlRecZQSMhlpZumJ5HnbJ5nF2NKqWIAnoxsEO92AsKM/CW36KnLBrRWPs6VnMzvNTJJ/3ot6pLWVnj4Wwgw8q3rCQxY5z/r59yBc83PKuH2/6vtf3v/RgSpRbepgfva2NONDVrFhw/9hgTbtm4/M4RZHEXXbAfXY8h5xmxTWMM4CL2bSN68ApUsWQw2QyIYXAEisMFdC45vD7KsRHLFOsXlHGqF5QL3GdcCJh/hkE3F2D9kpEOJT3oUFb9tB6BFrDCynDoboPDVraQ2oEUpAQFQ76PjRoMQlFqZK/qsPvRBRiiWWMVYrSF@WBfNNHUkl6SI5A8uoyzf/sIP/XYvLewBjl0jfwIZfxYy6rEZeDlvaQGoGU/wQhhzCGXfPN2NYPXkaeBEalb0Hh1PO2rU1Hp1@3pxTPUwTD/M8PA2PCFGpTd8rRL41VCKsbbKeMcfLkVLdzFk4mW8AtxN@pjZWirj34Y@avFOyMUJhrdDA2ZTe@5IS0ztiOWnXoqKbR4LSKmV//0ZIRLQ3a5Sc)
] |
[Question]
[
Given a string of ASCII art like such (This isn't ASCII art but it will do for the example):
```
abc
d e
fgh
```
Jumble it as if it was being displayed on a screen with one character per line, like so:
```
a
b
c
d
e
f
g
h
```
Print the result, wait one second, ±0.5 seconds before clearing the terminal and the print the same thing, but with 2 characters displayed per line instead of 1. Basically, the width of the display turns from 1 to 2.
```
ab
c
d
e
fg
h
```
Note the space after the `d`. Repeat waiting, then printing with an additional character per line until the inputted text is outputted.
If you hit the end of a line when trying to print characters, then you insert a newline and print the rest of them following this rule. For example the input:
```
abcdefg
ab
```
Would print the following when the display length is 4.
```
abcd
efg
ab
```
You can find the effect of the terminal resize here: <https://repl.it/GoeU/1>. Run the program, then drag the thing separating the terminal from the text editor back and forth.
**Clarification:**
Once a line appears exactly how it was inputted, you can leave that line alone for future larger character counts per line.
```
abc
ab
```
should print
```
ab
c
ab
```
when the sentence length = 2.
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so least amount of bytes wins!
Rules:
* Must print to STDOUT as the only output.
* Must clear the terminal, or create the illusion of clearing the terminal by adding 150 or so empty lines.
* Can take input through the standard methods.
* Default loopholes apply.
* Trailing stuff with the text is NOT OKAY.
This idea came to me when I was resizing a terminal with ASCII art on it. It looked interesting, so I decided to make a challenge out of it.
---
**Test cases:**
Since it would be too much work to show each step for each test case individually, I will review each answer to make sure it is valid. Make sure the answer can handle the test cases.
```
______ ______ __ __ __ ______ __ __ ______
/\ == \ /\ == \ /\ \ /\ "-.\ \ /\__ _\ /\ "-./ \ /\ ___\
\ \ _-/ \ \ __< \ \ \ \ \ \-. \ \/_/\ \/ \ \ \-./\ \ \ \ __\
\ \_\ \ \_\ \_\ \ \_\ \ \_\\"\_\ \ \_\ \ \_\ \ \_\ \ \_____\
\/_/ \/_/ /_/ \/_/ \/_/ \/_/ \/_/ \/_/ \/_/ \/_____/
```
[This pastebin](https://pastebin.com/we30K2RR).
```
__/\__
\ /
__/\__/ \__/\__
\ /
/_ _\
\ /
__/\__ __/ \__ __/\__
\ / \ / \ /
__/\__/ \__/\__/ \__/\__/ \__/\__
```
[Answer]
# Python 3.6, 124 bytes
Loops over length of input string like officialaimm's solution
```
import re,time
def d(s):
for i in range(len(s)):print(*'\n'*75,*re.split(f'(.{{1,{i+1}}})',s)[1::2],sep='\n');time.sleep(1)
```
143 bytes to only go to width of longest line a al Frxstrem's Bash answer
```
import re,time
def d(s):
for i in range(max(map(len,s.split()))):print(*'\n'*75,*re.split(f'(.{{1,{i+1}}})', s)[1::2],sep='\n');time.sleep(.5)
```
Uses "re.split((.{1,i+1}))" to break the string into groups of characters. Because '.' doesn't match '\n', the groups don't wrap around from one line to the next. If the regex uses a capturing group, then re.split() returns a list with the matched groups at the odd indexes. These are retrieved with [1::2].
Uses python 3.6 f-string to make the re pattern depend on group width i.
The \* in front of re.split() uses python 3.6 unpacking to turn the list into arguments to the print statement. Similarly, \*'\n'\*75, turns into 75 '\n' arguments to the print statement. With the print keyword argument sep='\n', the result is printing about 150 blank lines to clear the screen, followed by each group of characters on a separate line.
[Answer]
# Bash (with GNU coreutils), 69 bytes
```
n=`tee x|wc -L`;for i in `seq 1 $n`;do fold -w$i x;sleep 1;clear;done
```
Saves input in temporary file `x`, then counts the longest line (GNU coreutils' `wc` has `-L` flag for this) and iterates for each console width from 1 to the longest line length. `fold`, `sleep` and `clear` does the rest of the magic.
[Answer]
# Python 3.5 (238 233 229 225 223 222 bytes)
### - Works fine in the windows terminal; not sure about other platforms, because of the system-specific os.system("cls") command.
### - The string passed should be marked by \n for newlines eg: 'abc\nd efgh\n'
```
import os,time
def b(s):
p=len(s);z=print;r=range
for i in r(1,p):
os.system("cls");l=0
for j in r(p):
z(s[j],end="");l+=1
if(s[j]=='\n'):l=0
if(j+1<p and l==i and s[j+1]!='\n'):z();l=0
z();time.sleep(.5)
```
* Saved 5 bytes: removed unwanted whitespaces
* Saved 4 bytes: shorthand for len(s)
* Saved 4 bytes: Thanks to [sparklepony](https://codegolf.stackexchange.com/users/64159/sparklepony) (shorthand for print)
* saved 2 bytes: Thanks to [sparklepony](https://codegolf.stackexchange.com/users/64159/sparklepony) (shorthand for range as r and r(0,i) as range(i))
* saved 1 byte: Thanks to [steve](https://codegolf.stackexchange.com/users/42156/steve) (0.5 as just .5)
] |
[Question]
[
## Briefing
You are a bot, in a 2D grid that extends infinitely in all four directions, north, south, east and west. When given a number, you must move the bot so that you get to the target number.
Here's how the grid works:
You can move in 4 directions: north, south, east or west. Once you move off a cell, you are not allowed to go back to that cell again (so effectively, it's been wiped off the map).
There is a "counter", which goes `1234567890` (so it goes from `1` to `2`... all the way to `9`, then to `0`, then back to `1` again), which changes every time you move.
You also have a "value", which starts off at 0.
Once you move in any direction, a mathematical operation occurs, depending on what direction you move:
* North: Your value is increased by counter (`value += counter`).
* East: Your value is decremented by counter (`value -= counter`).
* South: Your value is multiplied by counter (`value *= counter`).
* West: Your value is divided by counter (`value /= counter`).
+ Division is integer division, so `5/2 -> 2`.
+ You are not allowed to divide by `0`.
Example:
If the bot moves north 3 times:
* The first "north" move increments the counter to `1`, and adds that to the value (which is now `1`).
* The second "north" move increments the counter to `2`, and adds that to the value (which is now `3`).
* The third "north" move increments the counter to `3`, and adds that to the value (which is now `6`).
The final value is `6`.
Move north, then south again:
* The first "north" move increments the counter to `1`, and adds that to the value (which is now `1`).
* The second "south" move errors, because the cell the bot is trying to move on is removed (from the first move).
There is no final value, because the bot errored.
## Challenge
Your challenge is to write a program when, given a number, produce the suitable directions for the bot to go in so that the final value of the bot is equal to that number.
So if the number is `6`, a valid solution to that would be:
```
nnn
```
(The bot moves north 3 times in a row).
Your test values are:
```
49445094, 71259604, 78284689, 163586986, 171769219, 211267178, 222235492, 249062828, 252588742, 263068669, 265657839, 328787447, 344081398, 363100288, 363644732, 372642304, 374776630, 377945535, 407245889, 467229432, 480714605, 491955034, 522126455, 532351066, 542740616, 560336635, 563636122, 606291383, 621761054, 648274119, 738259135, 738287367, 748624287, 753996071, 788868538, 801184363, 807723631, 824127368, 824182796, 833123975, 849666906, 854952292, 879834610, 890418072, 917604533, 932425141, 956158605, 957816726, 981534928, 987717553
```
(These are 50 random numbers from 1 to 1 billion.)
Your score is the total amount of moves made for all 50 numbers - the fewer moves, the better. In case of a tie, the person who submitted their code earlier wins.
## Specs
* You are guaranteed receive a positive integer for input.
* Your `value` variable must not go above `2^31-1` or below `-2^31` at any point for your generated paths.
* Your final program must fit in an answer (so, `< 30,000` bytes).
* You may only hard-code 10 numbers.
* Your program must run within 5 minutes on a reasonable laptop for any test case.
* The results MUST be the same every time the program is run for each number.
[Answer]
# C++: score = 453,324,048
OK, needed some time to rework this, but here's the way I solved it.
After studying the solution space, I decided that my strategy would be:
1. Uses the south steps to get as close to the target number
1. if the target is positive, follow this path: nnnesssssessssssss
2. if the target is negative, follow this path: esssssssseessssss
c. if the target is between 0 and 20, solve it "the old fashion way" (trail and error over every possible path til we reach it).
3. Once we have our "best place" (get as close to the target, without going "over"), we may be able to get closer by multiplying by 2 or 3; so take between 0 to 9 steps east, and then one step south. keep the path that gets us the closest to the target.
4. "Run" north, or east til we are within 45 points of the target (every 10 steps north, add 45 points to the score, like wise, every 10 steps east, reduces the score by 45).
2. Take a few more steps in the same direction, til we are within 10 points of the target
3. Do "the old fashion way" from this point, it shouldn't be that hard now.
Here's my result: total score is 453324048
And the paths:
```
0) to reach 49445094, it takes 1311037 steps, by doing: nnnesssssesssssseeeeese(n * 1311010)enen
1) to reach 71259604, it takes 1320313 steps, by doing: nnnesssssesssssseeeeeese(n * 1320280)nnnnnneee
2) to reach 78284689, it takes 1956998 steps, by doing: nnnesssssesssssseeeeeees(e * 1956970)eeee
3) to reach 163586986, it takes 2483885 steps, by doing: nnnesssssessssssse(n * 2483860)nnnnnnn
4) to reach 171769219, it takes 4302163 steps, by doing: nnnesssssessssssse(n * 4302130)nnnnnnnnnnennnn
5) to reach 211267178, it takes 13079485 steps, by doing: nnnesssssessssssse(n * 13079460)nnnnnen
6) to reach 222235492, it takes 15516886 steps, by doing: nnnesssssessssssse(n * 15516860)nnnnnnnn
7) to reach 249062828, it takes 12390325 steps, by doing: nnnesssssessssssseeees(e * 12390290)eeeeenenneene
8) to reach 252588742, it takes 11606785 steps, by doing: nnnesssssessssssseeees(e * 11606760)een
9) to reach 263068669, it takes 9277915 steps, by doing: nnnesssssessssssseeees(e * 9277880)eeeeenennneee
10) to reach 265657839, it takes 8702543 steps, by doing: nnnesssssessssssseeees(e * 8702510)eeeeenennee
11) to reach 328787447, it takes 5326312 steps, by doing: nnnesssssessssssseeeese(n * 5326280)nnnnennnn
12) to reach 344081398, it takes 8724966 steps, by doing: nnnesssssessssssseeeese(n * 8724940)enn
13) to reach 363100288, it takes 12951386 steps, by doing: nnnesssssessssssseeeese(n * 12951360)enn
14) to reach 363644732, it takes 13072373 steps, by doing: nnnesssssessssssseeeese(n * 13072340)nnnnnnnnen
15) to reach 372642304, it takes 15071833 steps, by doing: nnnesssssessssssseeeese(n * 15071800)nnnnnnnenn
16) to reach 374776630, it takes 15546133 steps, by doing: nnnesssssessssssseeeese(n * 15546100)nnnnnenene
17) to reach 377945535, it takes 16250331 steps, by doing: nnnesssssessssssseeeese(n * 16250300)nnnnennn
18) to reach 407245889, it takes 11107325 steps, by doing: nnnesssssessssssseeeees(e * 11107300)ne
19) to reach 467229432, it takes 2222403 steps, by doing: nnnesssssessssssseeeeese(n * 2222370)nnnnnnnee
20) to reach 480714605, it takes 5219109 steps, by doing: nnnesssssessssssseeeeese(n * 5219080)neenn
21) to reach 491955034, it takes 7716983 steps, by doing: nnnesssssessssssseeeeese(n * 7716950)nnnnennnn
22) to reach 522126455, it takes 14421745 steps, by doing: nnnesssssessssssseeeeese(n * 14421710)nnnnnneneee
23) to reach 532351066, it takes 16693875 steps, by doing: nnnesssssessssssseeeeese(n * 16693850)n
24) to reach 542740616, it takes 14866179 steps, by doing: nnnesssssessssssseeeeees(e * 14866150)eeeen
25) to reach 560336635, it takes 10955953 steps, by doing: nnnesssssessssssseeeeees(e * 10955920)eeeeennen
26) to reach 563636122, it takes 10222731 steps, by doing: nnnesssssessssssseeeeees(e * 10222700)eeeeene
27) to reach 606291383, it takes 743785 steps, by doing: nnnesssssessssssseeeeees(e * 743760)e
28) to reach 621761054, it takes 2693968 steps, by doing: nnnesssssessssssseeeeeese(n * 2693940)nnn
29) to reach 648274119, it takes 8585761 steps, by doing: nnnesssssessssssseeeeeese(n * 8585730)nnnnnn
30) to reach 738259135, it takes 5286413 steps, by doing: nnnesssssessssssseeeeeees(e * 5286380)eeneneee
31) to reach 738287367, it takes 5280141 steps, by doing: nnnesssssessssssseeeeeees(e * 5280110)nneenn
32) to reach 748624287, it takes 2983042 steps, by doing: nnnesssssessssssseeeeeees(e * 2983010)eeeenee
33) to reach 753996071, it takes 1789313 steps, by doing: nnnesssssessssssseeeeeees(e * 1789280)eeeennee
34) to reach 788868538, it takes 5960183 steps, by doing: nnnesssssessssssseeeeeeese(n * 5960150)nnenene
35) to reach 801184363, it takes 8697033 steps, by doing: nnnesssssessssssseeeeeeese(n * 8697000)nnenene
36) to reach 807723631, it takes 10150197 steps, by doing: nnnesssssessssssseeeeeeese(n * 10150170)n
37) to reach 824127368, it takes 13795475 steps, by doing: nnnesssssessssssseeeeeeese(n * 13795440)nnnnnnnne
38) to reach 824182796, it takes 13807795 steps, by doing: nnnesssssessssssseeeeeeese(n * 13807760)nnnnnenee
39) to reach 833123975, it takes 15794722 steps, by doing: nnnesssssessssssseeeeeeese(n * 15794690)nennnn
40) to reach 849666906, it takes 14397917 steps, by doing: nnnesssssessssssseeeeeeees(e * 14397880)eeeeeeeenee
41) to reach 854952292, it takes 13223389 steps, by doing: nnnesssssessssssseeeeeeees(e * 13223350)eeeeeeeeneeen
42) to reach 879834610, it takes 7693981 steps, by doing: nnnesssssessssssseeeeeeees(e * 7693950)eeenn
43) to reach 890418072, it takes 5342102 steps, by doing: nnnesssssessssssseeeeeeees(e * 5342070)eeennn
44) to reach 917604533, it takes 699395 steps, by doing: nnnesssssessssssseeeeeeeese(n * 699360)nnnneene
45) to reach 932425141, it takes 3992863 steps, by doing: nnnesssssessssssseeeeeeeese(n * 3992830)nennnn
46) to reach 956158605, it takes 9266963 steps, by doing: nnnesssssessssssseeeeeeeese(n * 9266930)nnnnen
47) to reach 957816726, it takes 9635434 steps, by doing: nnnesssssessssssseeeeeeeese(n * 9635400)nnnennn
48) to reach 981534928, it takes 14906145 steps, by doing: nnnesssssessssssseeeeeeeese(n * 14906110)nnnnnnnn
49) to reach 987717553, it takes 16280059 steps, by doing: nnnesssssessssssseeeeeeeese(n * 16280030)nn
```
I'm sure there's a way to improve on this by doing some cleaver "south/west" moves (dividing by 4 and multiplying by 5; for example); but coding it, and making sure you don't over lap or get trapped, is tricky.
Another solution path, may be to try to go back down from the target, to a "reasonable" number, and then, just find a path to that smaller number; but you'll have to "aim" it right, so that the step number will match. tricky, but might be the best way to solve this.
Anyway, here is my code code:
```
#include <stdio.h>
#include <vector>
#include <queue>;
using namespace std;
long long upperLimit;
long long lowerLimit;
bool bDebugInfo = false;
//bool bDebugInfo = true;
// a point struct (x and y)
struct point
{
int x;
int y;
point():x(0),y(0)
{
}
bool operator ==(const point& other)
{
return (x==other.x) && (y==other.y);
}
void ApplyDirection(char direction)
{
switch (direction)
{
case 'n':
y++;
break;
case 'w':
x--;
break;
case 'e':
x++;
break;
case 's':
y--;
break;
}
}
};
// each state is of this formate
struct botState
{
int nStep;
long long number;
vector<char> path;
botState()
:nStep(0),
number(0)
{
}
botState* clone()
{
botState* tmp = new botState();
tmp->nStep = nStep;
tmp->number = number;
tmp->path = path;
return tmp;
}
void clone(botState* other)
{
nStep = other->nStep;
number = other->number;
path = other->path;
}
};
bool changeNumberWithDirection(long long &number, char direction, int step)
{
switch (direction)
{
case 'n':
number += (step%10);
break;
case 'w':
if (step%10)
number /= (step%10);
else
return false;
break;
case 'e':
number -= (step%10);
break;
case 's':
number *= (step%10);
break;
default:
return false;
}
return true;
}
bool tryToAddStep(queue<botState*>& queueOfStates, const botState* pState, char direction, char cStarDirection)
{
botState* pTmpState;
long long newNumber;
int newStep = pState->nStep+1;
newNumber = pState->number;
if (!changeNumberWithDirection(newNumber, direction, newStep))
return false;
if (newNumber > upperLimit)
return false;
if (newNumber < lowerLimit)
return false;
if ((newNumber == 0) && (newStep%10 == 0))
return false; // no need to return back to 0 after 10 or more steps, we already have better ways to do this.
// build the x,y points of the path up to this point
point tmpPoint;
vector<point> pointsInPath;
pointsInPath.push_back(tmpPoint);
for (int i=0; i<pState->path.size(); i++)
{
if (pState->path.at(i) == '*')
{
for (int j=0; j<100; j++)
{
tmpPoint.ApplyDirection(cStarDirection);
pointsInPath.push_back(tmpPoint);
}
}
else
{
tmpPoint.ApplyDirection(pState->path.at(i));
pointsInPath.push_back(tmpPoint);
}
}
tmpPoint.ApplyDirection(direction);
// check for over lap
for (int i=0; i<pointsInPath.size(); i++)
{
if (tmpPoint == (pointsInPath.at(i)))
return false;
}
pTmpState = new botState();
pTmpState->nStep = newStep;
pTmpState->number= newNumber;
pTmpState->path = pState->path;
pTmpState->path.push_back(direction);
queueOfStates.push(pTmpState);
return true;
}
bool isBetterNum(long long newNum, long long oldBest, long long target)
{
long long newDiff = (newNum > target) ? newNum - target : target - newNum ;
long long oldDiff = (oldBest > target) ? oldBest - target : target - oldBest;
return (newDiff < oldDiff);
}
bool tryToJumpDown(long long num, botState* pState, int& nTimes)
{
// if where the bot is, we have a clear path to go as far east as we could ever want, we can just do as many sets of eeeeeeeeee (e*10) as needed, til we are close enough to the target
point tmpPoint;
vector<point> pointsInPath;
pointsInPath.push_back(tmpPoint);
for (int i=0; i<pState->nStep; i++)
{
tmpPoint.ApplyDirection(pState->path.at(i));
pointsInPath.push_back(tmpPoint);
}
for (int i=0; i<pointsInPath.size(); i++)
{
if ((pointsInPath.at(i).x > tmpPoint.x) && (pointsInPath.at(i).y == tmpPoint.y))
return false; // we have a point blocking our path up!
}
long long tmpTimes = (pState->number - num)/45;
if ((tmpTimes>1) && (tmpTimes<upperLimit))
{
tmpTimes--;
tmpTimes*=10;
nTimes = (int)tmpTimes;
pState->nStep+=nTimes;
pState->number-=(tmpTimes/10)*45;
pState->path.push_back('*');
return true;
}
return false;
}
bool tryToJumpUp(long long num, botState* pState, int& nTimes)
{
// if where the bot is, we have a clear path to go as far north as we could ever want, we can just do as many sets of nnnnnnnnnn (n*10) as needed, til we are close enough to the target
point tmpPoint;
vector<point> pointsInPath;
pointsInPath.push_back(tmpPoint);
for (int i=0; i<pState->nStep; i++)
{
tmpPoint.ApplyDirection(pState->path.at(i));
pointsInPath.push_back(tmpPoint);
}
for (int i=0; i<pointsInPath.size(); i++)
{
if ((pointsInPath.at(i).x == tmpPoint.x) && (pointsInPath.at(i).y > tmpPoint.y))
return false; // we have a point blocking our path up!
}
long long tmpTimes = (num - pState->number)/45;
if ((tmpTimes>1) && (tmpTimes<upperLimit))
{
tmpTimes--;
tmpTimes*=10;
nTimes = (int)tmpTimes;
pState->nStep+=nTimes;
pState->number+=(tmpTimes/10)*45;
pState->path.push_back('*');
return true;
}
return false;
}
typedef char* PChar;
bool buildPath(long long num, PChar& str, int& nLen, int& nScore, botState* startState, int nTimes)
{
long long nBest = 0;
int nMaxSteps = 0;
long long nMax = 0;
long long nMin = 0;
int nCleanUpOnStep= 12;
long long nFromLastCleanUp = 0;
bool bInCleanUp = false;
char cDirection = ' ';
if (nTimes>0)
cDirection = 'n';
else if (nTimes<0)
{
cDirection = 'e';
nTimes*=-1;
}
if (startState->nStep >= nCleanUpOnStep)
nCleanUpOnStep= startState->nStep+10;
str = NULL;
nLen = 0;
botState* bestState = new botState();
bestState->clone(startState);
queue<botState*> queueOfStates;
queueOfStates.push(bestState); // put the starting state into the queue
while (!queueOfStates.empty()) // while we still have states in the queue, process them
{
botState* pState = queueOfStates.front();
queueOfStates.pop(); // take a state out of the queue
if (!str) // no solution yet
{
if (pState->number == num) // check if this is a solution
{
// we solved it!
int nOffset=0;
nLen = pState->nStep - nTimes + 17;
str = new char[nLen+1];
if (bDebugInfo)
printf("solved!\n");
nScore = pState->nStep;
for (int i=0; i<pState->path.size(); i++)
{
if (pState->path.at(i)=='*')
{
sprintf(str+i, "(%c * %11d)", cDirection, nTimes);
if (bDebugInfo)
printf("(%c * %11d)", cDirection, nTimes);
nOffset=16;
}
else
{
str[i+nOffset] = pState->path.at(i);
if (bDebugInfo)
printf("%c", str[i+nOffset]);// print solution while making the string
}
}
if (bDebugInfo)
printf("\n");
str[nLen]='\0';
}
else
{ // no solution yet, we need to go deeper
if (pState->number < nMin)
nMin = pState->number;
if (pState->number > nMax)
nMax = pState->number;
if ((!bInCleanUp) && (queueOfStates.size()>1000000))
{
nCleanUpOnStep=nMaxSteps+10;
bInCleanUp = true;
}
if (pState->nStep > nMaxSteps)
{ // a little tracing, so we can see progress
nMaxSteps = pState->nStep;
// printf("current states have %d steps, reached a max of %lld, and a min of %lld\n", nMaxSteps, nMax, nMin);
if (nMaxSteps >= nCleanUpOnStep)
{
nCleanUpOnStep+=10;
bInCleanUp = true;
}
}
if (isBetterNum(pState->number, nBest, num))
{ // a little tracing, so we can see progress
nBest = pState->number;
if (bDebugInfo)
printf("Got closer to the target, %lld, with %d steps (target is %lld, diff is %lld)\n", nBest, pState->nStep, num, num-nBest);
if (bestState != pState)
delete bestState;
bestState = pState;
}
if (!bInCleanUp)
{
tryToAddStep(queueOfStates, pState, 'n', cDirection);
tryToAddStep(queueOfStates, pState, 'e', cDirection);
if (!nTimes) // once we did the "long walk in one direction" don't do the west or south moves any more
{
tryToAddStep(queueOfStates, pState, 'w', cDirection);
tryToAddStep(queueOfStates, pState, 's', cDirection);
}
}
}
}
if (pState!=bestState)
delete pState; // this is not java, we need to keep the memory clear.
if ((bInCleanUp) && (queueOfStates.empty()))
{
queueOfStates.push(bestState); // put the starting state into the queue
bInCleanUp = false;
long long diff = nFromLastCleanUp-bestState->number;
if (!nTimes)
{
if ((diff>0) && (diff<100))
if (tryToJumpDown(num, bestState, nTimes))
cDirection = 'e';
if ((diff<0) && (diff>-100))
if (tryToJumpUp(num, bestState, nTimes))
cDirection = 'n';
if (nTimes)
nCleanUpOnStep = bestState->nStep;
}
nFromLastCleanUp = bestState->number;
}
}
delete bestState; // this is not java, we need to keep the memory clear.
return str!=NULL;
}
char* positiveSpine = "nnnesssssessssssss";
char* negativeSpine = "esssssssseessssss";
bool canReachNumber(long long num, PChar& str, int& nLen, int& nScore)
{
int nTimes = 0;
botState tmpState;
if ((num>=0) && (num<=20))
return buildPath(num, str, nLen, nScore, &tmpState, nTimes);
botState bestState;
bestState.clone(&tmpState);
char* spine = NULL;
if (num>0)
{
spine = positiveSpine;
}
else
{
spine = negativeSpine;
}
for (int i=0; spine[i]; i++)
{
tmpState.nStep++;
tmpState.path.push_back(spine[i]);
if (!changeNumberWithDirection(tmpState.number, spine[i], tmpState.nStep))
return false;
if ((num>0) && (tmpState.number<num))
{
bestState.clone(&tmpState);
}
else if ((num<0) && (tmpState.number>num))
{
bestState.clone(&tmpState);
}
}
if (bestState.number == num)
return buildPath(num, str, nLen, nScore, &bestState, nTimes);
botState tryPath;
tmpState.clone(&bestState);
for (int i=0; i<9; i++)
{
tryPath.clone(&tmpState);
bool pathOK = true;
for (int j=0; j<i; j++)
{
tryPath.nStep++;
tryPath.path.push_back('e');
if (!changeNumberWithDirection(tryPath.number, 'e', tryPath.nStep))
{
pathOK = false;
break;
}
}
tryPath.nStep++;
tryPath.path.push_back('s');
if (!changeNumberWithDirection(tryPath.number, 's', tryPath.nStep))
{
pathOK = false;
break;
}
if ((pathOK) && (isBetterNum(tryPath.number, bestState.number, num)))
{
bestState.clone(&tryPath);
}
}
// in case we'll need to add, but last step was south, move one to the east.
if ((bestState.path.at(bestState.path.size()-1) == 's') && (bestState.number<num))
{
bestState.nStep++;
bestState.path.push_back('e');
if (!changeNumberWithDirection(bestState.number, 'e', bestState.nStep))
return false;
}
if (bestState.number<num)
{
long long diff = num - bestState.number;
diff/=45;
nTimes = (int)diff*10;
bestState.nStep += nTimes;
bestState.path.push_back('*');
bestState.number += 45*diff;
while (num - bestState.number > 10)
{
bestState.nStep++;
bestState.path.push_back('n');
if (!changeNumberWithDirection(bestState.number, 'n', bestState.nStep))
return false;
}
return buildPath(num, str, nLen, nScore, &bestState, nTimes);
}
else
{
long long diff = bestState.number - num;
diff/=45;
nTimes = (int)diff*10;
bestState.nStep += nTimes;
bestState.path.push_back('*');
bestState.number -= 45*diff;
while (bestState.number - num > 10)
{
bestState.nStep++;
bestState.path.push_back('e');
if (!changeNumberWithDirection(bestState.number, 'e', bestState.nStep))
return false;
}
return buildPath(num, str, nLen, nScore, &bestState, -nTimes);
}
return false;
}
long long aVals[] = {49445094, 71259604, 78284689, 163586986, 171769219, 211267178, 222235492, 249062828, 252588742, 263068669, 265657839, 328787447, 344081398, 363100288, 363644732, 372642304, 374776630, 377945535, 407245889, 467229432, 480714605, 491955034, 522126455, 532351066, 542740616, 560336635, 563636122, 606291383, 621761054, 648274119, 738259135, 738287367, 748624287, 753996071, 788868538, 801184363, 807723631, 824127368, 824182796, 833123975, 849666906, 854952292, 879834610, 890418072, 917604533, 932425141, 956158605, 957816726, 981534928, 987717553};
void main(void)
{
upperLimit = 2147483647; // 2^31 - 1
lowerLimit =-1; // -2^31
lowerLimit *=2147483648; // -2^31
long long num=0;
char* str=NULL;
int nLen = 0;
int nItems = sizeof(aVals)/sizeof(aVals[0]);
int nScore = 0;
long long nTotalScore = 0;
// nItems=1;
for(int i=0; i<nItems; i++)
{
if (canReachNumber(aVals[i], str, nLen, nScore)) //try to reach it
{
printf("%3d) to reach %10lld, it takes %9d steps, by doing: %s\n", i, aVals[i], nScore, str);
nTotalScore+=nScore;
delete str;
}
else
{
if (aVals[i]>0)
printf("Failed to reach %lld, use nenenenenenen..... ('n', followed by %lld pairs of 'en')\n", aVals[i], aVals[i]-1);
else
printf("Failed to reach %lld, use enenenenenene..... ('e', followed by %lld pairs of 'ne')\n", aVals[i], aVals[i]-1);
nTotalScore+=2*aVals[i]-1;
}
}
printf("done, total score is %lld\n", nTotalScore);
return;
}
```
[Answer]
# Python, Score = 56068747912
```
def move(n):
print("n" + "en" * (n - 1))
```
Just prints `nenenenenenenen...` for every number.
Will add an explanation later.
[Answer]
# [Rust](https://www.rust-lang.org/), score = 1758 (optimal among paths with no west)
Runs in about 7 seconds total for 50 numbers, using a [bidirectional search](https://en.wikipedia.org/wiki/Bidirectional_search).
```
use std::collections::HashSet;
use std::io::{self, prelude::*};
#[derive(Debug, Eq, Clone, Copy, Hash, Ord, PartialEq, PartialOrd)]
enum Dir {
N,
E,
S,
}
use Dir::{E, N, S};
fn dir_char(dir: Dir) -> char {
match dir {
N => 'n',
E => 'e',
S => 's',
}
}
#[derive(Debug, Eq, Clone, Hash, Ord, PartialEq, PartialOrd)]
struct State {
counter: i32,
value: i32,
next: Dir,
}
fn step(s: &State) -> impl Iterator<Item = State> {
let (values, nexts): (_, &[Dir]) = match s.next {
N => (s.value.checked_add(s.counter), &[N, E]),
E => (s.value.checked_sub(s.counter), &[N, E, S]),
S => (
if s.counter != 0 {
s.value.checked_mul(s.counter)
} else {
None
},
&[E, S],
),
};
let counter = (s.counter + 1) % 10;
values.into_iter().flat_map(move |value| {
nexts.iter().map(move |&next| State {
counter,
value,
next,
})
})
}
fn unstep(s: &State) -> impl Iterator<Item = State> {
let counter = (s.counter + 9) % 10;
(match s.next {
N | E => s.value.checked_sub(counter).map(|value| State {
counter,
value,
next: N,
}),
_ => None,
}).into_iter()
.chain(s.value.checked_add(counter).map(|value| State {
counter,
value,
next: E,
}))
.chain(match s.next {
E | S if counter != 0 && s.value % counter == 0 => {
s.value.checked_div(counter).map(|value| State {
counter,
value,
next: S,
})
}
_ => None,
})
}
fn search(value: i32) -> String {
let mut lefts: Vec<HashSet<State>> = Vec::new();
let mut left = [N, E, S]
.iter()
.map(|&next| State {
counter: 1,
value: 0,
next,
})
.collect::<HashSet<_>>();
let mut rights: Vec<HashSet<State>> = Vec::new();
let mut right = (0..10)
.map(|counter| State {
counter,
value,
next: E,
})
.collect::<HashSet<_>>();
loop {
if let Some(mid) = left.intersection(&right).min() {
let mut path = Vec::new();
let mut mid1 = mid.clone();
for left in lefts.into_iter().rev() {
let mid2 = unstep(&mid1)
.filter(|mid2| left.contains(mid2))
.next()
.unwrap();
mid1 = mid2;
path.push(mid1.next);
}
path.reverse();
let mut mid1 = mid.clone();
for right in rights.into_iter().rev() {
let mid2 = step(&mid1)
.filter(|mid2| right.contains(mid2))
.next()
.unwrap();
path.push(mid1.next);
mid1 = mid2;
}
return path.into_iter().map(dir_char).collect::<String>();
}
if left.len() <= right.len() {
let left1 = left.iter().flat_map(step).collect::<HashSet<_>>();
lefts.push(left);
left = left1;
} else {
let right1 = right.iter().flat_map(unstep).collect::<HashSet<_>>();
rights.push(right);
right = right1;
}
}
}
fn main() {
let stdin = io::stdin();
let values = stdin
.lock()
.lines()
.flat_map(|line| {
line.unwrap()
.split(", ")
.map(|s| s.parse().unwrap())
.collect::<Vec<i32>>()
})
.collect::<Vec<_>>();
for value in values {
println!("{} {}", value, search(value));
}
}
```
[Try it online!](https://tio.run/##tVfdb9s2EH/PX8F2mCttqiF@iKKUxC9rgO2lHWBgL0VhqDYdC5UlTx/phtj/@rI7UrYl2UnTddWLTuTx7ne/uyOpsqnqh4em0qSqF3E8L7JMz@u0yKs4/jWpVlNdX14cptMiju8rnS09sil11ix0HP@0u7y4@OH9QpfpnXbe6I/NrUdu/vTIL1mRa3gVm789grY88q5ceOT3pKzTJEOVVoRh98OFzps1eZOW5P6CwPPWM68b@5p6FzuDAxQAw40H82SKrpc5WaTlbL5KSgeEGDVc8npCcKS1tU7q@QrV2m9jn1xPyKv8lXcYuTEjujMyNSNVO7IDCE9F@owYq7ps5jWZ1kmtWyzzoslrDbhTzqyfuyRrdOc713/VJizkAOOtar1xqpiMjB0TbLreZOQ3sJPURXkFwppcWzeT1k@ma@IY05VnTFZuTJyZR0bvwfQHF/QtTdUYZ4dMOdXYLB7PV3r@SS9myWIBYy16F81ARm4@uAM@T9ZVzccz6yCZ3aWGeOfwiU@6JIdl5MU18TsI98/Q17rJOr566juis0qfsfEWctnX9Hqfo/cG7HGwhQ21uKd5j/KaHL2Tnwl1yY@E@pfHJFfjNK@LWQrzjjteZkk9WycbZ13cabI1GtsOQpO0cat81Bvh@LZXU/un9d0PwNjtD6GF48jOMgUvW25N/p8L7hEmoi4TzqNlt7UldK6C9jk1POyp@lYK4v2mY8M/yjOEgYXRptrt5u2gBQCTND/bKN8J7k0X7gmQR3i1rQnusaV6DTUa7bmG9BxShzPXk2d02yK9e36gTwb8ROB9Aqank7tBn/e@BonslXmlk3K@co67r6nzaV2m@W2npNdNDe9lDe3wh55ftYfklS39CVQ6jMZxrj877uXJIpg@bHfHdA3ryHD35baOCT1TJzHxn9HctkzsaR/Hhyhmk8kQdpnerr4@WLMK294fj6k/jK0N4H9vgeeGVhSbjlNoA4Q9LdbaWacLPAkxV9jjuqzsdcgZmYigrqGx3AHifdCbpF6d4WSoBj4onrbpYjzHm8NQb1mUtljS3FZa75Qo9d0JgIP1dMHAcrthj9CRe7Z7xss0Q3NbXLG14c6LvIZto0IOmPvIOiTdeWSuyT@XkN1BNOb@dYiYnU4ia@NNU63QMTUeBib6PWz0gQXMzbdQbEsUOLYV/rUkfyXFxsn35PjLND6ZiT7Hpa6bMrc2u7xg9@5v226nyewuOeni2vX7Cwos09g6V9ctF/bztJNQlx56cHA1Qtbdp7v7aAtbxzCC4pnZ1gntgD53K0RQBjKistiHsGzHPRNYW28Gmd1VzszvXdEho7v2uFonnZ0IIcIfGhTzNcGfNCN392R73TRlCzPHfTIr5p@6R0@W5rrqDhxC3OLUdkgNjB1q8qTYxtUmS2vnpUdenpk0RqstXCM2iWnlg6Ezykdi8RyCwxlp/cLOj5ot/Rf7pre3G@CpJeQYzgYquM7yF87L@x253wFoe@b07gVuSykk4eFBREIEfiQ8ElIWRNJHSTElpIo8QiUPlIyUBDGkoYwYhVFGKZPwqUCEhwciYiCKyJcMloIYsECpUOCo5L5UUuIyGcggVBxEzlQI8yIEUQhfUR7BMi459X2mrChhGv4eCQ@ZFIwjMB6KMJRgEcUwEkHAA48IP2QC/IFdIUPGIoHLhPJDKqSPChGNgsDnYCFgDLDDQhA5IKe@hNgCwULhS4qi9DkHF6ggEQVlYExCZBHlioPIgAfqB2BMCgXrKFIScgXsUVyGogq5hNhCoSQT8AViwCNgN6RIr1JSBRzCVD6lSoAbFMOQIQMgMkEZWFBWBCcRIFOcU8ajEFwoEUmg1MdRIB@CwgSoMFJcADYQIx/WAS8eiQCuLwIOLiIOYAIqwEUUSAqZRXYiyAkF3sBYpGjAIZkKxRAyDAT/M4fuua0eXr/7Fw "Rust – Try It Online")
### Output
```
49445094 nennesseseenenesseseeseseeeeseess
71259604 nnnnnnessennnessseeesssenesenesses
78284689 ennnesssseeeneenesenesssseeesese
163586986 ennnesesseneeeeessennesseeseseeneesen
171769219 ennnessenessssessseesesseeseenesee
211267178 sennnnneseeenessssenessssenenneseseee
222235492 ennnnnesseeeneseesseeesseseneesseesee
249062828 nnnnnesseneneseesssenennesseenesse
252588742 nennnessenneeeessesesesseseeseseeseee
263068669 nennnesseessseeessseesseeenesesssen
265657839 nnnesssseneesesssennneenesseeeses
328787447 eennnesssenesseesssesennnneeseenese
344081398 sennnnesennnesesessesesssseeseennnn
363100288 sennnnesseeneseesssenneesessennenee
363644732 nnnesssenneessesseeesseseseesenees
372642304 nnnnesseneseneseesseneneesssennesese
374776630 sennnnesseseesseneseeeseseessenesen
377945535 nnnesssseneeennesseesseeessseeses
407245889 nnnesseneesessseseseeeeessessenenee
467229432 nnnnesesennnnnesessesessesseeneess
480714605 nnnnessennneseesssenenesenesseesesen
491955034 nnnnnessseeneeeessseeeseenesseseeee
522126455 nnnnesssseeneeesesseesesseeeenese
532351066 nennnessenneeenesesesesessessesenesen
542740616 sennnnesseeneenesssesseenesseesesesen
560336635 nnnesssesesesssseeennessseseeneee
563636122 sennnnnesennneseseennesesssesenesenes
606291383 nnnessssenneeeseseseeseseeeeseesese
621761054 nnnessseennessesssenneeseseseess
648274119 nnnnessseneesseseeseenessseeneseeese
738259135 eennnnnesenennnesseneessssssennnees
738287367 nnnessesseessseseseneeesesseennen
748624287 nennnesseesseeenneseessseseeseneseseese
753996071 nnnnessseneeeseesssenesesenennnesesen
788868538 nnnessesseeseeeneeseesesseesseseeseee
801184363 ennnesseseeseeeeseseeeeseeseseessse
807723631 nnnessessessssesseennnnesssen
824127368 nnnnessesenessseseennnessseesesennnnn
824182796 nnnnessesenesssseenesssesssenesee
833123975 ennnnnneseeeennnessesssessseennnneeesse
849666906 sennnessseeeeseesesesssenesseneeeesen
854952292 nnnnnnesenenesssseeneeessessseseeeeeeee
879834610 nennnnesseessseneeseeesessseseneee
890418072 nnnesssennnnessesesennnesessennnnees
917604533 ennnnesseneeseeesesenennesesseeneesse
932425141 ennnnesssesseesesenesssessseeneesen
956158605 nnnnesseseeeeesesssennneseseenesseee
957816726 enennnesseseeseesseessessssenesss
981534928 eennnessennessseesseesessseenessseenn
987717553 nnnessseeneeesssesseesssesennessee
```
[Answer]
# PHP, Score=1391462099
```
function manoeuvre($n){
$i=0;
$c=0;
$char='';
while($i!=$n){
$c=($c+1)%10;
if($char!='n' and $c>0 and $i>0 and $i*$c<=$n){
$char='s';
$i=$i*$c;
}
else if($char!='s' and $i+$c<=$n and ($i-$c<=0 or ($i-$c)*max(($c+1)%10,2)>$n or $c==9)){
$char='n';
$i=$i+$c;
}
else{
$char='e';
$i=$i-$c;
}
echo $char;
}
}
```
A quick attempt, never goes west to simplify path checking and has few rules to decide direction at each step.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/79207/edit)
Your task is to build a natural number using the fewest number of ones and only the operators `+` or `-`. For example, the number seven can be written `1+1+1+1+1+1+1=7`, but it can also be written as `11-1-1-1-1=7`. The first one uses `7` ones, while the latter only uses `6`. Your task is to return the minimum number of ones that can be used given the input of some natural number, `n`.
This is code golf, so the shortest valid code in bytes wins.
### Test cases
Input => Output
```
0 => 2 (since 1-1=0)
7 => 6
121 => 6
72 => 15
1000 => 7
2016 => 21
```
[Answer]
## JavaScript (ES6), ~~127~~ ~~126~~ 87 bytes
```
f=(n,z=2,m=n*9+'',r=m.replace(/./g,1))=>n?m.length+(m<'55'?f(n- --r/10,0)-1:f(r-n,0)):z
```
```
Input: <input type="number" oninput="result.textContent=f(this.value)"> Result: <span id="result"></span>
```
Should work to about 10~~14~~15 at which point you start running into JavaScript's integer limits. Explanation:
```
f=( Recursive function
n, Parameter
z=2, Zero workaround
m=n*9+'', Magic
r=m.replace(/./g,1) Find repunit not less than than n
)=>n? Nothing to do if n is zero
m.length+ Assume subtracting from repunit
(m<'55'? Should we subtract from repunit?
f(n- --r/10,0) No, so subtract previous repuint
-1: Which is one 1 shorter
f(r-n,0)): Subtract from repunit
z Return special case if n is zero
```
This uses the `n*9` magic twice; firstly, it gives me the length of the next repunit, secondly, if the first two digits of `n*9` are `55` or higher, then we need to subtract `n` from that next repunit, otherwise we need to subtract the previous repunit (which is calculated by subtracting 1 and dividing by 10). This should work up to 1015.
[Answer]
# Pyth, ~~19~~ 16 bytes
```
ffqQvs+R1Y^c3"+-
```
[Test suite](https://pyth.herokuapp.com/?code=ffqQvs%2BR1Y%5Ec3%22%2B-&test_suite=1&test_suite_input=0%0A7%0A121%0A1000&debug=0)
Brute force algorithm. The necessary strings are generated by taking all lists whose elements are `['+', '-', '']` of length equal to the number of 1s being tested, appending a 1 to each, and concatenating to a single string. These strings are then evaluated and compared with the input. This is repeated until a successful string is found.
Some strings with a leading `+` or `-` are tested, but this isn't a problem. It would be if the input was negative though.
It can run up to length 9 before it becomes too slow.
**Explanation:**
```
ffqQvs+R1Y^c3"+-
ffqQvs+R1Y^c3"+-"T Implicit variable introduction
Q = eval(input())
f Starting with T = 1 and counting upwards, repeat until true.
The value of T where the result is first true is output.
c3"+-" Chop "+-" into thirds, giving ['+', '-', '']
^ T Form every list with those elements of length T.
f Filter over those lists, lambda var Y.
+R1Y Append a 1 to each element of the list.
s Concatenate.
v Eval.
qQ Compare for equality with the input.
The inner filter will let through the successful cases.
The outer filter will stop when there is a successful case.
```
[Answer]
# JavaScript (ES6), 92 bytes
```
f=(n,i=3)=>eval([...s=i.toString(3)].map(d=>"-+"[d]||"").join`1`+".0")-n?f(n,i+1):s.length-1
```
```
n = <input type="number" oninput="R.textContent=f(this.value)" /><pre id="R"></pre>
```
## Explanation
Recursive function. This generates all possible permutations of `1`s separated by either `+`, `-` or nothing. It does this by incrementing a base-3 number, turning it into an array of digits, converting each digit `0` to `-`, `1` to `+` and `2` to an empty string, then joining them together with `1`s. The resulting string is `eval`d as a JavaScript statement which returns the result of the equation.
Because the operators are joined with `1`s in between (like `+1+1+1+`), there are `length - 1` `1`s. The first operator is ignored (because `+1` = `1`, `<nothing>1` = `1` and it's a number so there will never be a leading `0` for `-`) and the final operator is also ignored (by appending `.0` to the equation).
### Higher Output Version, 96 bytes
The other version can't return outputs higher than ~10 because of the recursion call stack limit. This version uses a for loop instead of recursion, so it can return outputs up to ~33. The amount of time required increases exponentially though so I don't recommend testing it.
```
n=>eval('for(a=3;eval([...s=a.toString(3)].map(d=>"-+"[d]||"").join`1`+".0")-n;)a++;s.length-1')
```
] |
[Question]
[
# Background
The task is simple but every programmer has implemented it at least once. Stackoverflow has a lot of samples, but are they short enough to win?
# Problem story
You're a grumpy programmer who was given the task of implementing file size input for the users. Since users don't use bytes everyone will just enter "1M", "1K", "3G", "3.14M" - but you need bytes! So you write a program to do the conversion.
Then your manager hands you dozens of user reports with complaints about weird large numbers in file size input. It seems you'll need to code the reverse conversion too.
# What do you need to do?
Here's the trick: you should implement two-way conversion in single piece of code. Two separate functions used as needed? Nah, that's too simple - let's make one, short one!
For the purposes of this challenge, "kilobyte" means 1024 bytes, "megabyte" means 1024\*1024 = 1048576 bytes, and "gigabyte" means 1024\*1024\*1024 = 1073741824 bytes.
# Test data
```
Input -> Output
5 -> 5
1023 -> 1023
1024 -> 1K
1K -> 1024
1.5K -> 1536
1536 -> 1.5K
1048576 -> 1M
1M -> 1048576
```
# Rules
* Test value will not exceed 2\*1024\*1024\*1024 or 2G
* The following postfixes are used by users: K for kilobytes, M for megabytes, G for gigabytes
* Code is not required to work with negative numbers
* Do not use any external libraries (e.g. `BCMath` in PHP) besides bundled ones (e.g. `math.h`)
* Standard loopholes are disallowed
* Code should not produce anything on stderr
* Your program can take input and produce output using [standard methods].(<http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods>)
[Answer]
# Python 2, ~~204~~ 190 bytes
This is my first ever codegolf.
```
s=raw_input()
p=' KMG'
if s[-1]<='9':
e=0;r=int(s)
while r>=1024:r/=1024.0;e+=1
else:
e=p.index(s[-1]);r=eval(s[:-1])
while e>0:r*=1024;e-=1
print(`r`if r%1!=0 else`int(r)`)+p[e].strip()
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 60 bytes
```
l:" KMG"Fi1,4Ia>=Y1024x:(a/:y).l@ix|aR`.+([KMG])`_*y**(l@?B)
```
Takes input from the command line (assigned to `a` variable) and outputs to stdout.
**Ungolfed version:**
```
l : " KMG"
Y 1024
F i 1,4
I a>=y {
a /: y
x : a . l@i
}
x | a R `.+([KMG])` {a*y**(l@?b)}
```
**Algorithm:**
* For `i` from 1 through 3:
+ If `a >= 1024`, this is a byte value that needs to be converted to a larger unit:
- Divide `a` by 1024
- Set `x` to be the current value of `a` concatenated with the current unit
* If `x` was set by the previous step, output it. Otherwise, `a` was less than 1024 (with a possible unit suffix), so:
+ Do a regex replacement with a function on `a` if it has one of `KMG` at the end: translate the letter to the appropriate power of 1024 and multiply the number by the result.
+ For values less than 1024 without a suffix, this leaves the value unchanged.
[Answer]
# JavaScript, ~~144~~ 106 bytes
```
n=>((G=(M=(K=2<<9)<<10)<<10),+n>0?n<K?n:n<M?n/K+'K':n<G?n/M+'M':n/G+'G':eval(n.replace(/[KMG]/,m=>'*'+m)))
```
This can definitely be shortened, and will do later. Just wanted to get something ugly out there ;)
[Answer]
## C ~~206~~ 183 bytes
Got rid of as much as I could.
```
#include<stdlib.h>
main(y,z)char**z;{char*i="KMG";float f=atof(*++z);while(*++*z)y=**z;if(y>57){do f*=1024;while(y!=*i++);y=0;}else while(f>1023)y=*i++,f/=1024;printf("%.1lf%c",f,y);}
```
### Output
```
Input: 1023
Output: 1023.0
Input: 1M
Output: 1048576.0
Input: 1048576
Output: 1.0M
```
### Explanation
```
#include <stdlib.h> //needed for atof()
main(y,z)char **z; //y will hold the size indicator
{
char *i="KMG";//holds the characters for the size indicators
float f=atof(*++z); //get the number from the string
while(*++*z) //loops through the string
y=**z;
if(y>57) //57 is ASCII for 9
{
do f*=1024;
while(y!=*i++); //loop through until we hit the correct size
y=0;
}
else
while(f>1023) //loop through until number is less than 1024
y=*i++,f/=1024;
printf("%.1lf%c",f,y); //print number and size character
}
```
[Answer]
# Python2 199 bytes
this is silly but it works (ignoring the decimal precision question) as long as you have dozens of gigabytes of RAM. dont run it otherwise, your machine might freeze and lockup. The first thing it does is allocate a 2gigabyte array of integers.
```
n,bn={'K':2**10,'M':2**20,'G':2**30},range(2**30+1)
for i in bn:
for j in 'KMG':
if i>=n[j]: bn[i]=str(float(i/n[j]))+j
def f(i):
if i[-1] in 'KMG': return n[i[-1]]*float(i[:-1])
return bn[int(i)]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 91 bytes
```
f=(n,m)=>n<1024?n+['.KMG'[m]]:n>0?f(n/1024,-~m):eval(n.replace(/.$/,'*32**$&',K=2,M=4,G=6))
```
[Try it online!](https://tio.run/##TY9NDoIwEIX3nIKFkRZKQf40xOLSRcMJCEaChWigEDCElVdHSkWdzcz7XuZl5pENWZ939/Zp8ubGpqkggKMakogfd7bjnbiRaJjGZy2p0zTkkX0qALeEhcxXDUM2ZBXguGNtleUMWHhjIU13HV3fbDVEiYNi4qEzCSCc8ob3TcVw1ZTgqviqLDNS51GZI92PlKMg3kqo0PS7IC1lh326Et8NBFmaJIs5p3gHfx8sJBY6/kuRlqpcfw9ckouaGlZZo5FEBRjhfPgb "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-nl`, 100 bytes
```
~/.$/
i,n,s,k=0,$_.to_f,' KMG',1024
$&<?A?((n/=k;i+=1)until n<k):n*=k**(s=~/#$&/)
print n,s[i].strip
```
[Try it online!](https://tio.run/##HYxNCoMwGET3OYXQ4F/TxKip2hqkKxfiCUoRuiiEyKeYdNGNR28auplh3sDb3s@PczujmCFFgBiiZUbwRO0yvUgUDGMfEZ7lJcJh2926OAYm9VUdJU/eYNUcQKuTC6RSp2ls5M4OOGQJWjcFNvC@u3pQYze1OieQFxXob@MD4lT4EMXZk7IWle8R8bpq/OJN7v9K9N9ltWoB404w/wA "Ruby – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 114 bytes
```
*i=L"KMG",d;c;main(S){float f;for(scanf(S="%f%c",&f,&c);c?f*=1024,c-*i++:f>1023?f/=1024,d=*i++:0;);printf(S,f,d);}
```
[Try it online!](https://tio.run/##XVBNb8IwDL33V1hBoLQE1nawTcsKJ8SBceruqEriEcHSqh8bEuK3d0kpmkYOkd@zn/1sMfkUoh1Ihdoo@Mq0AcwOaueiNtDJO9ls14RJLrijaOqf8ZhnNSDHvKSVyAzSNCFDHArCRshGwudiiUEShfGMiUmgx@NXXFj0uMSHKyuTjg25z4tSm9p2YMikzy/toDHWS2fEG2gjjo1U8FbVUufT/cL7zrWEsjFU7LMygJMPZw/sw1LlhTKUaDOtTzVhQH7G9ndC4/NrTdHUFT3dkZVSB6AdxSBkkK5Wm126@ujzfxdIbFIkYS@73YhGdpQLSC/ohhCHLp5drduEOpvONZlH8a3QYqAk3vzH0fYOT@P1HRPOXubPT92E9hc "C (gcc) – Try It Online")
Thank ceilingcat for -11 bytes
] |
[Question]
[
Given two parameters *lane pattern* and *road length*, print an ASCII representation of the lane markings for Roads and Traffic Service to paint the roads.
## Example input/output
**Input:** `BTHMLRPHU`, 21
I don't care if you take two parameters or concatenate the number onto the end of the string, it's unambiguous.
Input may be taken from STDIN, as a function argument, environment variables, whatever makes sense in your language.
**Output:**
```
! | x ## | | x x !
! B | /\ x HOV3 ## <- | -> | ^^ x HOV3 x !
! B | \/ x HOV3 ## | | | | ^^ x HOV3 x !
! | x ## | | x x !
! | x ## | | x x !
! | | ## | | | | !
! | | ## | | | | !
! | | ## | | | | !
! B | /\ | HOV3 ## <- | -> | ^^ | HOV3 | !
! B | \/ | HOV3 ## | | | | ^^ | HOV3 | !
! | x ## | | x x !
! B | /\ x HOV3 ## <- | -> | ^^ x HOV3 x !
! B | \/ x HOV3 ## | | | | ^^ x HOV3 x !
! | x ## | | x x !
! | x ## | | x x !
! | | ## | | | | !
! | | ## | | | | !
! | | ## | | | | !
! B | /\ | HOV3 ## <- | -> | ^^ | HOV3 | !
! B | \/ | HOV3 ## | | | | ^^ | HOV3 | !
! | x ## | | x x !
```
Each character denotes 0.5 metres in width and one kilometre in length.
# Specification
## Lane markings
For every 10 km stretch of road, markings are painted at kilometres 2, 3, 9 and 10 (from the "top" of the output). Markings are centred in the lane. With the exception of the bike lane and median, all lanes are 3 metres (6 characters) wide.
ASCII diamond and arrow characters are *not* permitted in lieu of the markings as indicated in the example output.
* `B`: Bike lane. `B` marking. 1.5 metres (3 characters) wide.
* `T`: Transit. Diamond marking
* `H`: High-occupancy vehicle lane. `HOV3` marking
* `L` and `R`: Turning lane. Arrow marking
* `P`: Passing lane. Caret markings
* `U`: Unrestricted lane. No markings
## Separators (in order of precedence)
* Median: `##` (denoted by `M` in the input string, replaces any other separator including ditch)
* Ditch (extreme left and extreme right): `!` Exclamation mark
* HOV lanes alternate between `x` and `|` every 5 km
* Normal: `|`
## Constraints
Your function or program must:
* Print to STDOUT (this means equivalents of `System.out.print` for Java, `console.log` for JavaScript, etc.)
* Be able to print 1 - 9 lanes with 0 - 10 medians
* Be able to print up to 50 km of roadway (50 lines of output)
* [Not use any standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/22867)
* Trailing white space is not acceptable with the exception of an optional `\n` at the end of the output
Largest possible output: 3700 bytes (74 characters \* 50 lines).
Smallest possible output: 5 bytes (with input `B`, 1)
### Assumptions
* No adjacent medians (substring `MM` will not occur)
* The second line of markings might be cut off (for example if the length is 9 or 12 km)
* Lanes may not logically make sense (any order is possible, for example a right turn lane on the left of the road)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code (in bytes) wins!
[Answer]
## Ruby, 245
Print the lane divides if relevant, then print the lane.
I don't expect to win.
```
->(n,i){i.times{|d,t|*e=''
g=e+%w{HOV3 ^^ B}
n.chars{|c|$><<(c==?M?'##':!t ??!:(t+c)[?H]&&d%10<5??x:?|)if(M=t!=?M)
$><<((e+[(%w{/\\ <- ->}+g)[v='TLRUHPB'.index(c)],(%w{\\/ \ | |\ }+g)[v]]+e*4)*2)[d%10].center(v>5?3:6)if(t=c)!=?M}
puts M ? e:?!}}
```
### Changelog
**245** choke stderr and split arrays effectively.
**263** better way to index array
**268** just print each line, don't calculate a canonical version.
**330** initial commit
[Answer]
## JavaScript (ES6), 316 bytes
```
f=(x,n)=>{for(i=0;n>i++;){b=!(r=i%10)|r==3;y=[...`! ${[...x].join` | `} !`[o='replace'](/[\W] ?M [\W]?/g,'##')].map(c=>~(q='LPRTU'.indexOf(c))?` ${'<- |^^^^->| /\\\\/ '.substr(4*q+2*b,2)} `:c=='H'?'HOV3':c).join``;y=r&&r<6?y[o](/\| H/g,'x H')[o](/3 \|/g,'3 x'):y;console.log(b|r==2|r==9?y:y[o](/[^!\|x#]/g,' '))}}
```
### Demo
It should work in Firefox and Edge at time of writing, Chrome/Opera require experimental features to be enabled.
```
console.log = x => O.innerHTML += x + '\n';
f = (x, n) => {
for (i = 0; n > i++;) {
b = !(r = i % 10) | r == 3;
y = [...
`! ${[...x].join` | `} !` [o = 'replace'](/[\W] ?M [\W]?/g, '##')
].map(c => ~(q = 'LPRTU'.indexOf(c)) ? ` ${'<- |^^^^->| /\\\\/ '.substr(4*q+2*b,2)} ` : c == 'H' ? 'HOV3' : c).join ``;
y = r && r < 6 ? y[o](/\| H/g, 'x H')[o](/3 \|/g, '3 x') : y;
console.log(b | r == 2 | r == 9 ? y : y[o](/[^!\|x#]/g, ' '))
}
}
// Snippet stuff
var demo = () => {
O.innerHTML = '';
document.forms[0].checkValidity() && f(document.getElementById('P').value, document.getElementById('N').valueAsNumber);
};
document.getElementById('P').addEventListener('change', demo);
document.getElementById('N').addEventListener('change', demo);
demo();
```
```
<form action='#'>
<p>
<label>Lane pattern:
<input type=text pattern=^M?([BHLPRTU]M?)+$ maxlength=19 required id=P value=MLTPUMHUTBR>
</label>
</p>
<p>
<label>Kilometres:
<input type=number id=N min=1 value=21 max=50 step=1 required>
</label>
</p>
<pre><output id=O></output></pre>
</form>
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~175~~ ~~174~~ 175 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ðTиDU'|TиX'BŽ5ES©ǝX„\/TbSDVè®ǝ€ºX4×"HOV3"®ǝX'<18SǝX„|-Yè®ǝøJDí'<'>:X'^®ǝ2×'#Tи2×'x5и'|5и«'!Tи)I.•o¤[‹‡•uŽDýSтì€ûŽe1ª904ûª8ª₄«ª‡•δ~¬]•2ôDí«Ž
ÿT∍S:ð.ø8ðì‚8:1ðì‚ð:SðT:èεI∍}øJ»
```
Pretty bad approach, but it works and was fun to make. Can definitely be golfed some more, though.
+1 byte as bug-fix for two adjacent `HH` lanes.
[Try it online.](https://tio.run/##yy9OTMpM/f//8IaQCztcQtVrgFSEutPRvaauwYdWHp8b8ahhXox@SFKwS9jhFYfWHZ/7qGnNoV0RJoenK3n4hxkrgYQi1G0MLYIhamt0IyHqDu/wcjm8Vt1G3c4qQj0OJGJ0eLq6MtB4EF1hemGHeg2QOLRaXREopump96hhUf6hJdGPGnY@algI5JQe3etyeG/wxabDa4B2Ht59dG@q4aFVlgYmh3cfWmVxaNWjppbDTYdWAxlg5ee21B1aEwtkGB3eArT40Oqje7kO7w951NEbbHV4g97hHRaHNxxec7jpUcMsCytDOPvwBqtgoN@tDq84t9UTqLgW6O5Du///dwrx8PUJCvAI9fDw5TIyAgA)
**Explanation:**
Step 1: Create all possible lanes with size 10:
```
ðTи # Push a space character, repeated 10 times as list
DU # And store a copy in variable `X`
'|Tи '# Push "|", repeated 10 times as list
X # Push the list of spaces of variable `X`
'B '# Push a "B"
Ž5E # Push compressed integer 1289
S # Converted to a list of digits: [1,2,8,9]
© # Store it in variable `®` (without popping)
ǝ # Replace the spaces in the pushed `X` with the "B" at these (0-based)
# indices
X # Push `X` again
„\/ # Push string "\/"
TbS # Push 10, converted to binary, as list: [1,0,1,0]
DV # Store a copy in variable `Y`
è # Index each into this string: ["/","\","/","\"]
® # Push list `®` again ([1,2,8,9])
ǝ # And replace the spaces with these characters
€º # And then mirror each line (" "→" "; "/"→"/\"; "\"→"\/")
X # Push `X` again
4× # Extend each space to four spaces
"HOV3" # Push string "HOV3"
®ǝ # And replace the spaces with this string at the indices of `®` again
X # Push `X` again
'< '# Push string "<"
18S # Push 18 as list: [1,8]
ǝ # Replace the spaces with "<" at those indices
X # Push `X` yet again
„-| # Push string "-|"
Yè # Use list `Y` ([1,0,1,0]) to index into this string: ["-","|","-","|"]
®ǝ # And replace the spaces at the indices of `®` again
ø # Then zip-pair the two lists together
J # And join each pair of characters to a string
Dí # Create a copy and reverse each string
'<'>: # And replace all "<" with ">"
X'^®ǝ '# Push `X` with the spaces at indices `®` replaced with "^"
2× # Extend each character to size 2
'#Tи '# Push "#", repeated 10 times as list
2× # And extend each character to size 2
'x5и '# Push "x" repeated 5 times as list
'|5и '# Push "|" repeated 5 times as list
« # And merge the lists together
'!Tи '# Push "!", repeated 10 times as list
) # And finally wrap all lists of the stack into one big list of lanes
```
Step 2: Convert the input-string to indices (which we're going to use to index into the list we created in step 1):
```
I # Push the input-string
.•o¤[‹‡• # Push compressed string "tlrpbhmu"
u # And uppercase it
ŽDý # Push compressed integer 3567
S # Converted to a list of digits: [3,5,6,7]
тì # Prepend each with "100": ["1003","1005","1006","1007"]
€û # And palindromize each: ["1003001","1005001","1006001","1007001"]
Že1 # Push compressed integer 10201
ª # And append it to the list
904ûª # Push 904 palindromized to "90409", and also append it to the list
8ª # Append 8 to the list
₄Â # Push 1000, and bifurcate it (short for Duplicate & Reverse copy)
« # Merge them together: "10000001"
ª # And also append it to the list
‡ # Now transliterate all uppercase characters in the input to these numbers
•δ~¬]• # Push compressed integer 1119188999
2ô # Split into parts of size 2: [11,19,18,89,99]
Dí # Create a copy, and reverse each item: [11,91,81,98,99]
« # And merge the lists together: [11,19,18,89,99,11,91,81,98,99]
Ž\nÿ # Push compressed integer 19889
T∍ # Extended to size 10: 1988919889
S # As a list of digits: [1,9,8,8,9,1,9,8,8,9]
: # Replace all [11,19,18,89,99,11,91,81,98,99] with [1,9,8,8,9,1,9,8,8,9]
# in the converted string
ð.ø # Surround the string with spaces
8ðì # Push 8 with a prepended space: " 8"
‚ # Bifurcate and pair: [" 8","8 "]
8: # And replace all those for 8 in the string
1ðì‚ð: # Do the same for [" 1","1 "] → " "
S # Convert the string to a list of characters (digits and space)
ðT: # Replace the spaces for 10
```
Step 3: we use those indices to index into the list of lanes. And then we convert those list of lanes to the correct output, including extending/shortening them to the size of the integer-input:
```
è # Index the indices in the integer-list into the lanes-list
ε # Map over each lane
I # Push the second integer-input
∍ # Extend/shorten each 10-sized lane to this input-size
}ø # After the map: zip/transpose; swapping rows/columns
J # Join inner list together to a single string
» # And then join each string by newlines
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to compress strings not part of the dictionary?* and *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž5E` is `1289`; `.•o¤[‹‡•` is `"tlrpbhmu"`; `ŽDý` is `10201`; `•δ~¬]•` is `1119188999`; `Ž\nÿ` is `19889`.
] |
[Question]
[
This challenge is inspired by a puzzle I played, consisting of foam pieces like these:

which have to be assembled into 3D cubes, like these:

The puzzle pieces can be viewed as grids of 5 \* 5 squares, whose middle 3 \* 3 squares are always solid, while the 16 squares on the edges can be solid or empty.
A piece will be described using a string of 16 characters (`0`s and `1`s), representing the configuration of its edges (`0`=empty, `1`=solid), in clockwise order, starting from the top left corner.
For example, the string:
```
0101001000101101
```
represents this piece:
```
# #
####
####
####
# #
```
In order to fit the pieces together to form the cube, every piece can be rotated in any direction. For example, these are the valid rotations of the piece shown above:
```
# # # # # ## #
#### #### #### ####
#### #### #### ####
#### #### #### ####
# # # # ## # #
# # # # # ## #
#### #### #### ####
#### #### #### ####
#### #### #### ####
# # # # # # ##
```
## Challenge
Write a program or function that takes as input 6 puzzle pieces and prints or returns a 2D representation of the solved cube.
### Input
The input will be a string of 6 rows, where each row consists of 16 `0` or `1` characters, representing a piece's edges (in the format described above).
It can be assumed that there is a solution for the input.
The trailing newline is optional.
### Output
The result will be an ASCII representation of the solved cube, unfolded in 2D, like this (the diagram uses Rubik's Cube notation for side names):
```
+---+
|BA |
|CK |
| |
+---+---+---+---+
|LE |DO |RI |UP |
|FT |WN |GHT| |
| | | | |
+---+---+---+---+
|FR |
|ONT|
| |
+---+
```
To avoid the possibility of presenting the solution in multiple ways, the piece placed DOWN will always be the first piece present in the input, in the same rotation as it is specified there.
Every piece will be represented graphically as a 5 \* 5 matrix, using spaces to denote empty squares.
For solid squares you can use whatever non-space character you wish, as long as:
* any piece of the puzzle will have its solid squares represented using the same character
* any two adjacent pieces use different characters
Space padding to the right and the trailing newline are optional.
### Test Cases
1.
Input:
```
0010010101010101
0010001011011010
0101001001010010
0010110100101101
0010110110101101
0010001011010101
```
Output:
```
@ @
@@@
@@@@@
@@@
** **@#@** *# #
***#####***#####
*****###*****###
***#####***#####
* @#@#** ** # #
@@@@
@@@@
@@@@
@ @
```
2.
Input:
```
0001110110101101
1010010111011101
0101010101010010
1010001000100011
1010001001010001
0110010100100010
```
Output:
```
@
@@@@
@@@@
@@@@
** **@@## * *# #
****#####****###
****###*****####
****#####***####
** *#@#@# * # #
@@@@
@@@@
@@@@
@ @
```
3.
Input:
```
0101001011011010
0010001000100010
0101001011010010
0101010101011010
0101101001011101
1010001001011101
```
Output:
```
@ @@
@@@@@
@@@
@@@@@
* * @#@#* * #
*****###*****###
***#####***#####
*****###*****###
* ##@##* * #
@@@@
@@@@
@@@@
@@ @@
```
This is codegolf, so the shortest program in bytes wins.
[Answer]
# Haskell, ~~1007~~ ~~One Thousand and One Bytes~~ ~~923~~ ~~900~~ 830 bytes
I happened to have already made a happycube solver, now I just need to golf it. Taking a ten byte penalty for using fancy block elements:
```
import Data.List
r=reverse;z=zipWith;f=foldl1;t=take;g=t 4;d=drop;m=map
n x=t 5x:n(d 4x)
u v a b=init a++v max(last a)(b!!0):d 1b
a!b|k<- \x y->last$' ':[a|b!!x!!y>0]=(k 0<$>[0..4]):((\i->k 3(4-i):[a,a,a]++[k 1i])<$>[1..3])++[k 2<$>[4,3..0]]
p y|(e:v)<-m(g.n.cycle.m(read.pure))$"0":(lines$y),[j,k,l,x,y,r]<-x v=mapM putStrLn$f(u z)$f(z(u id))<$>z(z(!))[a,"▒█▒█",a][[e,k,e,e],[l,j,x,r],[e,y,e,e]];a=" ░ "
x(p:q)=[p:u|x<-permutations q,u@[e,g,y,k,l]<-sequence$(\c->nub$[c,r.m r$c]>>=g.m g.tails.cycle)<$>x,and$zipWith4(\a n b m->all(==1).init.d 1$z(+)(a!!n)$r$b!!m)([l,e,p,p,p,p,e]++u)[3,3,0,3,1,2,0,1,2,2,2,1](y:g:u++[y,k,k,l,g])[1,0,2,1,3,0,0,0,3,1,2,3]++z((((==1).sum.m(!!0)).).z(!!))[[p,e,g],[y,p,e],[k,p,g],[k,p,y],[l,y,e],[l,y,k],[l,g,e],[l,g,k]][[0,3,1],[0..2],[0,3,2],[1..3],[0,1,1],[3,2,2],[1,0,0],[2,3,3]]]!!0
```
That's a mouthful. Usage:
```
*Main> mapM_ (\s->p s>>putStrLn"")["0010010101010101\n0010001011011010\n0101001001010010\n0010110100101101\n0010110110101101\n0010001011010101","0001110110101101\n1010010111011101\n0101010101010010\n1010001000100011\n1010001001010001\n0110010100100010","0101001011011010\n0010001000100010\n0101001011010010\n0101010101011010\n0101101001011101\n1010001001011101"]
░ ░
░░░
░░░░░
░░░
▒▒ ▒▒░█░▒▒ ▒█ █
▒▒▒█████▒▒▒█████
▒▒▒▒▒███▒▒▒▒▒███
▒▒▒█████▒▒▒█████
▒ ░█░█▒▒ ▒▒ █ █
░░░░
░░░░
░░░░
░ ░
░
░░░░
░░░░
░░░░
▒▒ ▒▒░░██ ▒ ▒█ █
▒▒▒▒█████▒▒▒▒███
▒▒▒▒███▒▒▒▒▒████
▒▒▒▒█████▒▒▒████
▒▒ ▒█░█░█ ▒ █ █
░░░░
░░░░
░░░░
░ ░
░░ ░
░░░░░
░░░
░░░░░
▒ ▒█░█░ ▒ ▒ █
▒▒▒▒▒███▒▒▒▒▒███
▒▒▒█████▒▒▒█████
▒▒▒▒▒███▒▒▒▒▒███
▒ ▒██░██ ▒ █
░░░░
░░░░
░░░░
░░ ░░
```
Some of the examples have more than one solutions, that's why some of the outputs look different. Ungolfed:
```
import Data.List (nub, transpose, (\\))
import Control.Monad (guard)
newtype CubePiece = CubePiece [[Int]] deriving Eq
newtype Solution = Solution [CubePiece]
side :: Int -> CubePiece -> [Int]
side n (CubePiece c) = c!!n
corner :: Int -> CubePiece -> Int
corner n (CubePiece c) = head $ c!!n
strToCube str = CubePiece $ hs' . (\x@(a:_)->x++[a]) $ l
where
l = map (read.pure) str
hs' [a] = []
hs' x = take 5 x : hs' (drop 4 x)
orientations :: CubePiece -> [CubePiece]
orientations (CubePiece cube) = map CubePiece $ nub $ (take 4 . iterate rotate $ cube) ++
(take 4 . iterate rotate . reverse . map reverse $ cube)
where
rotate (a:as) = as++[a]
sideFits :: (CubePiece, Int) -> (CubePiece, Int) -> Bool
sideFits (c1,n1) (c2,n2) = case (zipWith (+) a b) of
[_,1,1,1,_] -> True
_ -> False
where
a = side n1 c1
b = reverse $ side n2 c2
cornerFits :: (CubePiece, Int) -> (CubePiece, Int) -> (CubePiece, Int) -> Bool
cornerFits (c1,n1) (c2,n2) (c3,n3) = a + b + c == 1
where
a = corner n1 c1
b = corner n2 c2
c = corner n3 c3
printSolution str = putStrLn . specialUnlines . map rivi $
[[empty,gshow '░' c2,empty,empty],[gshow '▒' c3,gshow '█'c1,gshow '▒'c4,gshow '█'c6],[empty,gshow '░'c5,empty,empty]]
where
Solution [c1,c2,c3,c4,c5,c6] = solve . map strToCube . lines $ str
empty = replicate 5 " "
rivi = map (foldl1 specialConcat) . transpose
specialUnlines = unlines . foldl1(\a b->init a++[zipWith max(last a)(head b)]++tail b)
specialConcat a b
| last a==' '=init a++b
| otherwise = a++tail b
gshow char (CubePiece c) =
[ map (k 0) [0..4]
, (k 3 3) : m ++ [(k 1 1)]
, (k 3 2) : m ++ [(k 1 2)]
, (k 3 1) : m ++ [(k 1 3)]
, map (k 2)[4,3..0]
]
where
k n1 n2 = if (c!!n1)!!n2 == 1 then char else ' '
m=replicate 3 char
solve :: [CubePiece] -> Solution
solve pieces = Solution $ head $ do
let c1' = pieces!!0
let c1 = c1'
c2' <- pieces \\ [c1']
c2 <- orientations c2'
guard $ sideFits (c1,0) (c2,2)
c3' <- pieces \\ [c1',c2']
c3 <- orientations c3'
guard $ sideFits (c1,3) (c3,1)
guard $ sideFits (c2,3) (c3,0)
guard $ cornerFits (c1,0) (c2,3) (c3,1)
c4' <- pieces \\ [c1',c2',c3']
c4 <- orientations c4'
guard $ sideFits (c1,1) (c4,3)
guard $ sideFits (c2,1) (c4,0)
guard $ cornerFits (c1,1) (c2,2) (c4,0)
c5' <- pieces \\ [c1',c2',c3',c4']
c5 <- orientations c5'
guard $ sideFits (c1,2) (c5,0)
guard $ sideFits (c4,2) (c5,1)
guard $ sideFits (c3,2) (c5,3)
guard $ cornerFits (c5,0) (c1,3) (c3,2)
guard $ cornerFits (c5,1) (c1,2) (c4,3)
c6' <- pieces \\ [c1',c2',c3',c4',c5']
c6 <- orientations c6'
guard $ sideFits (c6,0) (c2,0)
guard $ sideFits (c6,1) (c3,3)
guard $ sideFits (c6,2) (c5,2)
guard $ sideFits (c6,3) (c4,1)
guard $ cornerFits (c6,0) (c4,1) (c2,1)
guard $ cornerFits (c6,3) (c4,2) (c5,2)
guard $ cornerFits (c6,1) (c3,0) (c2,0)
guard $ cornerFits (c6,2) (c3,3) (c5,3)
return $ [c1,c2,c3,c4,c5,c6]
main = mapM_ printSolution ["0010010101010101\n0010001011011010\n0101001001010010\n0010110100101101\n0010110110101101\n0010001011010101","0001110110101101\n1010010111011101\n0101010101010010\n1010001000100011\n1010001001010001\n0110010100100010","0101001011011010\n0010001000100010\n0101001011010010\n0101010101011010\n0101101001011101\n1010001001011101"]
```
[Answer]
# Python3, 1098 bytes:
```
E=enumerate
H=range
R=lambda x,n=4:set()if n==0 else{str(x),*R([i[::-1]for i in zip(*x)],n-1)}
def B(i):k=[[[' ','#'][int(j)]for j in i[t:t+4]]for t in H(0,16,4)];return[k[0]+[k[1][0]],*[[a,*('#'*3),b]for a,b in zip(k[3][::-1][:-1],k[1][1:])],[k[3][::-1][-1]]+k[2][::-1]]
V=lambda U,x,y,r,i,R,I:all((0<I<4 and A!=B)or(I in[0,4]and(A!=B or(A==' 'and B==' ')))for I,(A,B)in E(zip([U[x],[*zip(*U[x])]][r][i],[U[y],[*zip(*U[y])]][R][I])))
def L(M):
b=[[' 'for _ in H(17)]for _ in H(13)]
for P,(x,y),C in zip(M,[(4,4),(4,0),(0,4),(4,8),(8,4),(4,12)],'#@*&$%'):
for X in H(5):
for Y in H(5):b[x+X][y+Y]=[C,b[x+X][y+Y]][P[X][Y]==' ']
return b
def f(p):
s,*p=[B(i)for i in p.split('\n')]
q=[([s],p)]
while q:
M,p=q.pop(0)
if len(M)==6:
for i in M:return L(M)
for i,a in E(p):
for P in{*R(a),*R([j[::-1]for j in a])}:
U=M+[eval(P)]
if all(V(U,*j)for j in[(1,0,1,4,1,0),(2,0,0,4,0,0),(3,0,1,0,1,4),(4,0,0,0,0,4),(5,3,1,0,1,4),(1,2,0,0,1,0),(2,3,1,4,0,0),(3,4,0,4,1,4),(1,4,0,4,1,0),(1,5,1,0,1,4),(2,5,0,0,0,0),(4,5,0,4,0,4)]if j[0]<len(U)and j[1]<len(U)):q+=[(U,p[:i]+p[i+1:])]
```
[Try it online!](https://tio.run/##nVNtb9owEP6eX@G122In1yrhpUNZLa1UlYo0JIRE1epmTUENWyANIaQbrOpvZ2fnhWwf9mEKNneP7bvnHp@zffF9nXYHWX443MgofX6K8rCIrFuZh@m3yJrKJHyaP4ZsB6nsBduo4CJesFRKj0XJNnrZFjnfCXCmHGMMgjNfLdY5i1mcsl9xxp2dUJCe@eLVeowWbMhjEawkItrMBvvUVhinBV8Kc2qpT8VYBIXbUwYpNHLLPfAvoCfUxzwqnvMUV@gpl2ZfkaHAQQzB4RTO6QqYm5MhzGsOK@yqkhrqCcw5P1DEDFtrNJS7wk7lK@uurn0GO9hDDjFMYRSEScK5dzm67LEwfWRXb@RQrHM@onToQU8RyDXICLySkgrV24bGEkJociPgVzAUxO@Ga4Y4wx2RcYxi2hZKYU7aEDjDfWtpb5amCkeKYhlNP/OxCCw2l0ZUHf5rqZr/oZS1drtCWUwDE@BUkIDrWqExIO@RwECzR7NX2QOaB5Xtd0gv@/ST8/7tO1snNKHuy9h9AxjkoUHmuHPvFe7dByXxGlquwgmSSbgWhViV98rmpqAFz3S4LTiZRN0xTUdl59ssiQtuf0ltXcxGIsetgkw7P7/HScQ2msgYMrk5z9YZ9wS51LBJlJJMUl40PE3AcVBl1iJWJcUQMnMz2bGoCSEv1ONh2enLY6ebng2VeDV72UyOXYx@hAmfaE7MJNcdc8dn4CxFfQS5D9TVQLoaxTvkkep6Jq9r1sx6eSfVp70@dFtrPpQn6yhdE7OO0jMx65215xmv34rSIa/KYfL1Ky705Ij@kh7ZpRZwJnQnL@n5VK4INi5dwQwyDGLlZhi75l0dslw/a31N58t1nPKnMON2acOCn5yceJ6vf81nGUBb5c@zDF7vMkC1Wv9b7e3@3zH0R3mEfiUVmzPb8QeN9y9uFKEdt0laDavN3HDzq8zV8I9AZVg6UlMSjf/l1hLAr1VpD6u94whUX6Nsu6Q/yPpH3Q6/AQ)
] |
[Question]
[
Oh no! Nemo, our small clown fish is lost in this ASCII ocean and his dad Marlin is trying to find him.
Your task is to get Marlin to Nemo safely. But beware, we have a feeding frenzy Bruce on the loose, so better avoid him at all costs!
**Details**
You are given a rectangular ASCII ocean grid containing only lowercase alphabets `a-z`. This ocean will have `nemo`, `marlin` and `bruce` inside it in the form of a continuous polyomino, always starting from the top most cell in the first column of polyomino. So for example, out of all possible tetrominos, the valid ones are listed in the below snippet
```
nemo
n
e
m
o
no
em
ne
om
nem
o
o
nem
n
e
mo
o
m
ne
ne
m
o
n
emo
ne
mo
n
em
o
mo
ne
```
But forms like these are invalid and won't be present in the input:
```
omen
ne
mo
nem
o
o
m
en
nem
o
n
eo
m
```
Finally, your task is to find a path from the `marlin` polyomino tile to the `nemo` polyomino tile making sure that any cell in your path is not adjacent to the `bruce` polyomino tile. Your output should replace all alphabets which are not part of the `marlin` tile, `nemo` tile and the path connecting them both with a character from the printable ASCII range (including space) other than the lowercase `a-z`.
**Example**
If the input ocean is as following:
```
oxknvvolacycxg
xmliuzsxpdzkpw
warukpyhcldlgu
tucpzymenmoyhk
qnvtbsalyfrlyn
cicjrucejhiaeb
bzqfnfwqtrzqbp
ywvjanjdtzcoyh
xsjeyemojwtyhi
mcefvugvqabqtt
oihfadeihvzakk
pjuicqduvnwscv
```
(with the 3 polyominos being:
```
...n..........
.mli..........
.ar...........
..............
....b.........
....ruce......
..............
.....n........
.....emo......
..............
..............
..............
```
)
Then a valid solution may look like:
```
...n..........
.mli..........
.ar...........
.u............
.n............
.i............
.z............
.wvjan........
.....emo......
..............
..............
..............
```
Below snippet contains a few more examples:
```
oxknvvolacycxg
xmliuzsxpdzkpw
warukpyhcldlgu
tucpzymenmoyhk
qnvthsalyfrlyn
cibrucejhiaebu
bzqfnfwqtrzqbp
ywvjanjdtzcoyh
xsjeyemojwtyhi
mcefvugvqabqtt
oihfadeihvzakk
pjuicqduvnwscv
...n..........
.mli..........
.ar...........
.u............
qn............
c.............
b.............
ywvjan........
.....emo......
..............
..............
..............
----------------------------------------------
nemokjahskj
sdjsklakdjs
uqiceasdjnn
sbruakmarli
nemokjahskj
..........s
..........n
......marli
----------------------------------------------
```
**Notes**
* The grid will always be a perfect rectangle and will contain only one polyomino tile of `nemo`, `marlin` and `bruce`.
* Your path should not go through `bruce` or any of the 4 adjacent (up, down, left and right) cells of any cell in the `bruce` tile.
* It is always guaranteed that there will be at least one valid path from `marlin` to `nemo`.
* There is no requirement of a shortest path here, so go nuts!
* Even though you don't have to find the shortest path, any cell in the path (path not including marlin or nemo) cannot be adjacent to more than two other cells in the path.
* The path should not go through the `marlin` or `nemo` tiles, as it would then confuse the little fishes in choosing a direction.
* As usual, you may write a program or function, taking input via STDIN (or closest equivalent), command-line argument or function parameter, and producing output via STDOUT (or closest equivalent), return value or function (out) parameter.
* If multi-line input is not possible, then you may assume that the grid is joined by the `|` character instead of `\n`. You may also take the input as an array of grid rows.
This is code golf so the shortest entry in bytes wins.
[Answer]
# Matlab 560
560 bytes when removing all unnecessary spaces, all semicolons and all comments. Could be golfed much more but I am to tired right now (maybe tomorrow...) Good night everyone.
PS: I assumed that the path must have a 4 neighbourhood ('+') connectedness.
```
function c(A)
Z = [0,1,0;1,1,1;0,1,0];
Br = q('bruce');
Bn = conv2(Br,ones(3),'s')>0;
Ne = q('nemo');
Ma = q('marlin');
%construct path marlin to nemo
U=Ma>0;M=A*Inf;
M(U)=0;
for k=1:2*sum(size(A))%upper bound for path length
%expand
V=imdilate(U,Z);
V(Bn)=0;
M(V-U==1)=k;
U=V;
%disp(M)
end
%go back from nemo to marlin
Pr=reshape(1:numel(A),size(A));
[i,j]=find(Ne);
m=M(i(1),j(1));%value
P=A*0;%path image
P(i(1),j(1))=1;
for k=m:-1:1
%find neighbour of (i(1),j(1)) with value m-1
U=imdilate(P,Z);
F = M==k;
G = F&U;
mask = Pr == min(Pr(F & U));
P(mask)=1;
end
A(~P & ~Ma & ~Ne)='.';
disp(A)
function M = q(s)%find string in matrix, A ascii, M mask
M = A*0;
m=numel(s);
N = M+1;%all neighbours
for k=1:m;
M(A==s(k) & N)=k;%only set the ones that were in the neighbourhood of last
L=M==k;
N=imdilate(L,Z);
end
for k=m:-1:2
%set all that are not neighbour to next higher highest to zero
L=M==k;
N=imdilate(L,Z);
M(M==k-1 & ~N)=0;
end
end
end
```
Calling function : (newlines not necessary)
```
c(['oxknvvolacycxg',
'xmliuzsxpdzkpw',
'warukpyhcldlgu',
'tucpzymenmoyhk',
'qnvtbsalyfrlyn',
'cicjrucejhiaeb',
'bzqfnfwqtrzqbp',
'ywvjanjdtzcoyh',
'xsjeyemojwtyhi',
'mcefvugvqabqtt',
'oihfadeihvzakk',
'pjuicqduvnwscv']);
```
Output:
```
...n..........
.mli..........
.ar...........
..c...........
..v...........
..c...........
..q...........
..vjan........
.....emo......
..............
..............
..............
```
# How it works
### Extracting names
The first part is extracting the names e.g. `nemo`, which is done by the function `q()`. The function first marks everything as 0, then the occurences first letter of the name as `1`, then the second letter as `2` if there is a `1` in the neighbourhood, then the third and so on. After that there should in the case of `nemo` be only one `4`. From that we go backwards until we found the `1` again and then delete all the other numbers that were greater that, so we get back a nice mask where the letters `nemo` are masked. We do this for all three names, and can then proceed to finding a path.
### Finding the path
We start at Marlins positions and send a shockwave throu the hole 'image' step by step. In each step we increase the distance counter and mark the 'pixels' under the wavefront with the current distance. (As it is usually done with shortest path algorithms.) This wavefront obviously gets blocked by the area of Bruce, therefore it will flow around him. This step is repeated until an upper bound is reached. This (admittedly very loose) upper bound is now the circumference of the 'image' (the shortest paths will be way shorter in any case). In the test case it looks something like this:
```
2 1 1 0 1 2 3 4 5 6 7 8 9 10
1 0 0 0 1 2 3 4 5 6 7 8 9 10
1 0 0 1 2 3 4 5 6 7 8 9 10 11
2 1 1 _ _ _ 5 6 7 8 9 10 11 12
3 2 2 _ _ _ _ _ _ 9 10 11 12 13
4 3 3 _ _ _ _ _ _ 10 11 12 13 14
5 4 4 _ _ _ _ _ _ 11 12 13 14 15
6 5 5 6 7 8 9 10 11 12 13 14 15 16
7 6 6 7 8 9 10 11 12 13 14 15 16 17
8 7 7 8 9 10 11 12 13 14 15 16 17 18
9 8 8 9 10 11 12 13 14 15 16 17 18 19
10 9 9 10 11 12 13 14 15 16 17 18 19 20
```
Now start at `nemo` pixels and decrease the distance counter in each step and add a neighbour with the next lower distance (according to that distance map we calculated earlier) to our path.
[Answer]
# Python 2 - 658
Very very inefficient both in time and memory. The function to identify the patterns is the recursive function S, and the function to find the paths is the C, which is basically a horribly inefficient A\* implementation.
```
G=input().split('\n')
R=range
S=lambda g,x,y,s,B:[[(x,y)]+r for a,b in[(-1,0),(0,-1),(0,1),(1,0)]for r in S(g,x+a,y+b,s[1:],B)if B(x,y)and s[0]==g[y][x]]if s else[[]]
C=lambda l,N,B:[i for i in l if i[-1]in N]or C([i+[(i[-1][0]+c,i[-1][1]+d)]for i in l for c,d in [(-1,0),(0,-1),(0,1),(1,0)]if all(1<abs(i[-1][0]+c-a)or 1<abs(i[-1][1]+d-b)for a,b in B)],N,B)
X,Y=len(G[0]),len(G)
N,M,B=[filter(list,[S(G,s,t,e,lambda a,b:0<=a<X and 0<=b<Y and Y*(a-s)+b-t>=0)for s in R(X)for t in R(Y)])[0][0]for e in["nemo","marlin","bruce"]]
print'\n'.join(''.join(G[y][x]if(x,y)in N+M+min([C([[k]],N,B)[0]for k in M],key=lambda i:len(i))else'.'for x in R(X))for y in R(Y))
```
For testing use this (very slightly) less golfed one (which calculates the path once instead for every tile)
```
G=input().split('\n')
R=range
S=lambda g,x,y,s,B:[[(x,y)]+r for a,b in[(-1,0),(0,-1),(0,1),(1,0)]for r in S(g,x+a,y+b,s[1:],B)if B(x,y)and s[0]==g[y][x]]if s else[[]]
C=lambda l,N,B:[i for i in l if i[-1]in N]or C([i+[(i[-1][0]+c,i[-1][1]+d)]for i in l for c,d in [(-1,0),(0,-1),(0,1),(1,0)]if all(1<abs(i[-1][0]+c-a)or 1<abs(i[-1][1]+d-b)for a,b in B)],N,B)
X,Y=len(G[0]),len(G)
N,M,B=[filter(list,[S(G,s,t,e,lambda a,b:0<=a<X and 0<=b<Y and Y*(a-s)+b-t>=0)for s in R(X)for t in R(Y)])[0][0]for e in["nemo","marlin","bruce"]]
s=N+M+min([C([[k]],N,B)[0]for k in M],key=lambda i:len(i))
print'\n'.join(''.join(G[y][x]if(x,y)in s else'.'for x in R(X))for y in R(Y))
```
] |
[Question]
[
This is based on [xkcd #153](http://xkcd.com/153/).
Make a program or named function which takes 2 parameters, each of which is a string or a list or array of bytes or characters. The second parameter will only contain characters drawn from `lrfu` (or the equivalent ASCII bytes). It should be interpreted as a series of instructions to be performed on a bit sequence represented by the first parameter.
The processing performed must be equivalent to the following:
1. Convert the first parameter into a single bitstring formed by concatenating the bits of each character (interpreted as one of 7-bit ASCII, an 8-bit extended ASCII, or a standard Unicode encoding). E.g. if the first parameter is `"AB"` then this would be one of `10000011000010` (7-bit), `0100000101000010` (8-bit or UTF-8), `00000000010000010000000001000010`, or `01000001000000000100001000000000` (UTF-16 in the two endiannesses), etc.
2. For each character in the second parameter, in order, execute the corresponding instruction:
* `l` rotates the bitstring left one. E.g. `10000011000010` becomes `00000110000101`.
* `r` rotates the bitstring right one. E.g. `10000011000010` becomes `01000001100001`.
* `f` flips (or inverts) each bit in the bitstring. E.g. `10000011000010` becomes `01111100111101`.
* `u` reverses the bitstring. E.g. `10000011000010` becomes `01000011000001`.
3. Convert the bitstring into an ASCII string which uses one character per bit. E.g. `10000011000010` becomes `"10000011000010"`. This is because not all sets of 7/8 bits have a character assigned to them.
Example (in Python):
```
>>> f("b", "rfu")
01110011
```
It turns `"b"` into its 8-bit ASCII binary representation `01100010`, rotates it right (`00110001`), flips each bit (`11001110`), and reverses it (`01110011`).
### Flexibility
Other characters may be used instead of the characters `l`, `r`, `f`, and `u`, but they must be clearly documented.
### Scoreboard
Thanks to [@Optimizer](http://meta.codegolf.stackexchange.com/users/31414/optimizer) for creating the following code snippet. To use, click "Show code snippet", scroll to the bottom and click "► Run code snippet".
```
var QUESTION_ID = 45087; var answers = [], page = 1;var SCORE_REG = /\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;function url(index) {return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=votes&site=codegolf&filter=!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";}function getAnswers() {$.ajax({url: url(page++),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {answers.push.apply(answers, data.items);if (data.has_more) getAnswers();else process()}});}getAnswers();function shouldHaveHeading(a) {var pass = false;try {pass |= /^(#|<h).*/.test(a.body_markdown);pass |= ["-", "="].indexOf(a.body_markdown.split("\n")[1][0]) > -1;} catch (ex) {}return pass;}function shouldHaveScore(a) {var pass = false;try {pass |= SCORE_REG.test(a.body_markdown.split("\n")[0]);} catch (ex) {}return pass;}function getRelDate(previous) {var current = Date.now();var msPerMinute = 60 * 1000;var msPerHour = msPerMinute * 60;var msPerDay = msPerHour * 24;var msPerMonth = msPerDay * 30;var msPerYear = msPerDay * 365;var elapsed = current - previous;if (elapsed < msPerMinute) {return Math.round(elapsed/1000) + ' seconds ago';}if (elapsed < msPerHour) {return Math.round(elapsed/msPerMinute) + ' minutes ago';}if (elapsed < msPerDay ) {return Math.round(elapsed/msPerHour ) + ' hours ago';}if (elapsed < msPerMonth) {return 'approx. ' + Math.round(elapsed/msPerDay) + ' days ago';}if (elapsed < msPerYear) {return 'approx. ' + Math.round(elapsed/msPerMonth) + ' months ago';}return 'approx. ' + Math.round(elapsed/msPerYear ) + ' years ago';}function process() {answers = answers.filter(shouldHaveHeading);answers = answers.filter(shouldHaveScore);answers.sort(function (a, b) {var aB = +(a.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0],bB = +(b.body_markdown.split("\n")[0].match(SCORE_REG) || [Infinity])[0];return aB - bB});answers.forEach(function (a) {var answer = $("#answer-template").html();answer = answer.replace("{{BODY}}", a.body).replace("{{NAME}}", a.owner.display_name).replace("{{REP}}", a.owner.reputation).replace("{{VOTES}}", a.score).replace("{{DATE}}", new Date(a.creation_date*1e3).toUTCString()).replace("{{REL_TIME}}", getRelDate(a.creation_date*1e3)).replace("{{POST_LINK}}", a.share_link).replace(/{{USER_LINK}}/g, a.owner.link).replace('{{img}}=""', "src=\"" + a.owner.profile_image + '"');answer = $(answer);if (a.is_accepted) {answer.find(".vote-accepted-on").removeAttr("style");}$("#answers").append(answer);});}
```
```
body { text-align: left !important}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answers"></div><div id="answer-template" style="display: none"><div class="answer" ><table><tbody><tr><td class="votecell"><div class="vote"><span style="cursor: pointer;" title="Total Votes" itemprop="upvoteCount" class="vote-count-post ">{{VOTES}}</span><span style="display: none" class="vote-accepted-on load-accepted-answer-date" title="The question owner accepted this as the best answer">accepted</span></div></td><td class="answercell"><div class="post-text" itemprop="text">{{BODY}}</div><table class="fw"><tbody><tr><td class="vt"><div class="post-menu"><a href="{{POST_LINK}}" title="short permalink to this answer" class="short-link">share</a></div></td><td class="post-signature" align="right"><div class="user-info "><div class="user-action-time">answered <span title="{{DATE}}" class="relativetime">{{REL_TIME}}</span></div><div class="user-gravatar32"></div><div class="user-details"><br></div></div></td><td class="post-signature" align="right"><div class="user-info user-hover"><div class="user-action-time"></div><div class="user-gravatar32"><a href="{{USER_LINK}}"><div class="gravatar-wrapper-32"><img {{img}} alt="" height="32" width="32"></div></a></div><div class="user-details"><a href="{{USER_LINK}}">{{NAME}}</a><br><span class="reputation-score" title="reputation score " dir="ltr">{{REP}}</span></div></div></td></tr></tbody></table></td></tr></tbody></table></div></div>
```
[Answer]
# CJam, 34 bytes
Another approach in CJam.
```
1l+256b2b1>l_S/,1&@f=_,,@f{W%~}\f=
```
The input text is on the first line and the instructions are on the second line.
Instructions:
```
) Rotate left.
( Rotate right.
(space) Flip.
~ Reverse.
```
[Answer]
## Pyth 33
```
jku@[+eGPG+tGhG_Gms!dG)sHwsmjCk2z
```
Uses:
```
0 : rotate right
1 : rotate left
2 : reverse order
3 : flip values
```
[Pyth github](https://github.com/isaacg1/pyth)
[Try it online here.](https://pyth.herokuapp.com/)
This is a program that takes the string as it's first argument and the string of commands as the second argument. In the online version, you should give the strings separated by a newline, like so:
```
AbC
0321
```
Explanation:
```
: z=input() (implicit)
jk : join("", ...)
u@[ )sHw : reduce(select from [...] the value at int(H), input(), ...)
+eGPG : [ G[-1] + G[:1],
+tGhG : G[1:] + G[1],
_G : G[::-1],
ms!dG : map(lambda d: int(not(d)), G) ]
smjCk2z : first arg = sum(map(lambda k:convert_to_base(ord(k),2),z)
```
Something I couldn't quite squeeze in: Pyth's `reduce` automatically uses `G` for the previous value, and `H` for the next value.
[Answer]
# CJam, ~~34~~ 32 bytes
```
1l+256b2b1>l{~"11W:mm%!<>">4%~}/
```
It uses the following characters for instructions:
```
0: left rotation
1: right rotation
2: reverse
3: flip
```
The input is taking from STDIN with the word on the first line and the instruction string on the second line.
[Test it here.](http://cjam.aditsu.net/)
## Explanation
Getting the bit string is really just a matter of interpreting the character codes as the digits of a base-256 number (and getting its base-2 representation). The tricky thing is that the latter base conversion won't pad the result with 0s on the left. Therefore, I add a leading 1 to the initial input, and then split off that 1 again in the binary representation. As an example, if the input is `ab`, I turn that into an array `[1 'a 'b]`, interpret that as base-256 (characters are automatically converted to character codes), which is `90466` and the to base-2, which is `[1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 1 0]`. Now if I just remove that leading `1` I've got the bitstream I'm looking for.
That's what this part of the code does:
```
1l+256b2b1>
```
Now I read the list of instructions and execute a block for each character in the instruction string:
```
l{...}/
```
The first thing to do is to evaluate the character and actual integers`0`, `1`, `2` or `3`. Now the real golfy magic... depending on the instruction I want to run a short piece of code that implements the operation:
```
Integer: Code Operation
0 1m< "Left rotation";
1 1m> "Right rotation";
2 W% "Reverse";
3 :! "Flip each bit";
```
I could store these in an array of blocks and choose the right block to run, but encoding them in a string is actually shorter:
```
"11W:mm%!<>">4%~
```
First, I use the integer associate with the instruction to slice off the beginning of the string. So for left rotation, the string is unchanged, for right rotation the first character is discarded and so on. Then I select every fourth character from the string, starting from the first, with `4%`. Notice how the four code snippets are distributed throughout the string. Finally I just evaluate the string as code with `~`.
The bit string is printed automatically at the end of the program.
[Answer]
# Scala - 192
```
def f(i:String,l:String)=(i.flatMap(_.toBinaryString).map(_.toInt-48)/:l){
case(b,'l')⇒b.tail:+b.head
case(b,'r')⇒b.last+:b.init
case(b,'f')⇒b.map(1-_)
case(b,'u')⇒b.reverse}.mkString
```
[Answer]
# Matlab (166 bytes)
This uses letters `abcd` instead of `lrfu` respectively.
```
function D=f(B,C)
D=dec2bin(B,8)';
D=D(:);
g=@circshift;
for c=C
switch c-97
case 0
D=g(D,-1);
case 1
D=g(D,1);
case 2
D=char(97-D);
case 3
D=flipud(D);
end
end
D=D';
```
Some tricks used here to save space:
* Using `abcd` letters lets me subtract `97` once, and then the letters become `0`, `1`, `2`, `3`. This saves space in the `switch`-`case` clauses.
* Defining `circshift` as a one-letter anonymous function also saves space, as it's used twice.
* Since `D` consists of `'0'` and `'1'` characters (ASCII codes `48` and `49`), the statement `D=char(97-D)` corresponds to inversion between `'0'` and `'1'` values. Note that this `97` has nothing to do with that referred to above.
* Complex-conjugate transpose `'` is used instead of transpose `.'`.
[Answer]
# Python 2 - 179
```
b="".join([bin(ord(i))[2:]for i in input()])
for i in input():b=b[-1]+b[:-1]if i=="r"else b[1:]+b[0]if i=="l"else[str("10".find(j))for j in b]if i=="f"else b[::-1]
print"".join(b)
```
[Answer]
### C#, 418 bytes
```
using System;using System.Collections.Generic;using System.Linq;class P{string F(string a,string o){var f=new Dictionary<char,Func<string,IEnumerable<char>>>{{'l',s=>s.Substring(1)+s[0]},{'r',s=>s[s.Length-1]+s.Substring(0,s.Length-1)},{'u',s=>s.Reverse()},{'f',s=>s.Select(c=>(char)(97-c))}};return o.Aggregate(string.Join("",a.Select(c=>Convert.ToString(c,2).PadLeft(8,'0'))),(r,c)=>new string(f[c](r).ToArray()));}}
```
Formatted:
```
using System;
using System.Collections.Generic;
using System.Linq;
class P
{
string F(string a, string o)
{
// define string operations
var f = new Dictionary<char, Func<string, IEnumerable<char>>>
{
{'l', s => s.Substring(1) + s[0]},
{'r', s => s[s.Length - 1] + s.Substring(0, s.Length - 1)},
{'u', s => s.Reverse()},
{'f', s => s.Select(c => (char) (97 - c))}
};
// for each operation invoke f[?]; start from converted a
return o.Aggregate(
// convert each char to binary string, pad left to 8 bytes and join them
string.Join("", a.Select(c => Convert.ToString(c, 2).PadLeft(8, '0'))),
// invoke f[c] on result of prev operation
(r, c) => new string(f[c](r).ToArray())
);
}
}
```
[Answer]
## J, 164
```
([: >@:}. (([: }. >&{.) ; >@:{.@:>@:{. 128!:2 >@:}.)^:({.@:$@:>@:{.))@:(>@:((<;._1 ' 1&|."1 _1&|."1 -. |."1') {~ 'lrfu' i. 0&({::)@:]) ; ;@:([: (8$2)&#: a. i. 1&({::)))
```
Formatted:
```
nextop=:([: }. >&{.)
exec=: (>@:{.@:>@:{.) apply"1 >@:}.
times=: ({.@:$@:>@:{.)
gapply=: [: >@:}. (nextop ; exec)^:(times) f.
tobin=: ;@:([: (8#2)&#:(a.i.1&{::))
g=:'1&|.';'_1&|.';'-.';'|.'
tog =: g {~ ('lrfu' i. 0&{::@:])
golf=: gapply @: (>@:tog;tobin) f.
```
Example
```
golf ('rfu';'b')
0 1 1 1 0 0 1 1
golf ('lruuff';'b')
0 1 1 0 0 0 1 0
(8#2)#: 98
0 1 1 0 0 0 1 0
golf ('lruuff';'AB')
0 1 0 0 0 0 0 1 0 1 0 0 0 0 1 0
tobin '';'AB'
0 1 0 0 0 0 0 1 0 1 0 0 0 0 1 0
```
[Answer]
# JavaScript (E6), 163 ~~167~~
Fully using the input flexibility, a named function with 2 array parameters.
* First parameter, array of bytes corresponding to 7 bit character codes
* Second parameter, array of bytes corresponding to ascii characters 'F','L','R','U' --> 70, 76, 82, 85
The function returns a character string composed of '1' and '0'
```
F=(a,s,r='')=>
a.map(c=>r+=(128|c).toString(2).slice(-7))-
s.map(c=>a=c<71?a.map(c=>1-c):c<77?a.concat(a.shift):c<83?[a.pop(),...a]:a.reverse(),a=[...r])
||a.join('')
```
**Example** `f("b", "rfu")` translate to `F([98],[82,70,85])`, result is `0111001`
**Note** using character strings is so much longer in javascript! Byte count **186**
```
F=(a,s,r='')=>
[for(c of a)r+=(128|c.charCodeAt()).toString(2).slice(-7)]-
[for(c of(a=[...r],s))a=c<'G'?a.map(c=>1-c):c<'M'?a.concat(a.shift):c<'S'?[a.pop(),...a]:a.reverse()]
||a.join('')
```
**Example** `F("b", "RFU")`, result is `0111001` again
[Answer]
# Ruby, 151
```
f=->i,s{s.chars.inject(i.unpack("B*")[0]){|a,c|
a.reverse! if c==?u
a.tr!"01","10" if c==?f
a<<a.slice!(1..-1) if c==?l
a<<a.slice!(0..-2) if c==?r
a}}
```
Fairly straightforward. Loops trough the characters in `s` and performs an action for any of them.
[Answer]
## Python 2, 142
```
j="".join
f=lambda S,I:reduce(lambda s,i:[s[1:]+s[0],s[-1]+s[:-1],s[::-1],j([`1^int(c)`for c in s])][int(i)],I,j([bin(ord(c))[2:]for c in S]))
```
Similar to my pyth answer in approach: I build a list of all the strings and index into it based on the value of the instruction string that I iterate over using reduce.
Uses:
```
0 -> Rotate left
1 -> Rotate right
2 -> Reverse order
3 -> Invert bits
```
] |
[Question]
[
**This challenge is not about the game Snake.**
Imagine a 2d snake formed by drawing a horizontal line of length `n`. At integer points along its body, this snake can rotate its body by 90 degree. If we define the front of the snake to be on the far left to start with, the rotation will move the back part of the snake and the front part will stay put. By doing repeated rotations it can make a lot of different snake body shapes.
## Rules
1. One part of the snake's body can't overlap another.
2. It has to be possible to reach the final orientation without any parts of the snake's body overlapping in between. Two points that touch are counted as overlapping in this problem.
3. I regard a snake and its reverse as being the same shape.
## Task
>
> Up to rotation, translation and mirror symmetry, what is the total
> number of different snake body shapes that can be made?
>
>
>
**Example of a rotation of part of the snakes body.** Imagine `n=10` and the snake is in its start orientation of a straight line. Now rotate at point `4` 90 degrees counter-clockwise. We get the snake from `4` to `10` (the tail of the snake) lying vertically and the snake from `0` to `4` lying horizontally. The snake now has one right angle in its body.
Here are some examples thanks to Martin Büttner.
We start with the horizontal snake.

Now we rotate from position 4.

We end up after the rotation in this orientation.

Now let us consider this orientation of a different snake.

We can now see an illegal move where there would be an overlap caused during the rotation.

## Score
Your score is the largest `n` for which your code can solve the problem in less than one minute on my computer.
When a rotation happens it will move one half of the snake with it. We do have to worry about whether any of this part which is rotated might overlap a part of the snake during the rotation. For simplicity we can assume the snake has width zero. You can only rotate at a particular point in snake up to 90 degrees clockwise of counter clockwise. For, you can never full fold the snake in two as that would have involved two rotations at the same point in the same direction.
## Shapes that can't be made
A simple example of a shape that can't be made is a capital `T`. A more sophisticated version is

(Thank you to Harald Hanche-Olsen for this example)
In this example all the adjacent horizontal lines are 1 apart as are the vertical ones. There is therefore no legal move from this position and as the problem is reversible there is therefore no way to get there from the starting position.
## Languages and libraries
You can use any language which has a freely available compiler/interpreter/etc. for Linux and any libraries which are also freely available for Linux.
**My machine**
The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor. This also means I need to be able to run your code. As a consequence, only use easily available free software and please include full instructions how to compile and run your code.
[Answer]
# Python 3 - provisional score: n=11 (n=13 with PyPy\*)
Since there have been no answers in the first week, here is an example in Python to encourage competition. I've tried to make it reasonably readable so that inefficiencies can be identified easily to give ideas for other answers.
# Approach
* Start with the straight snake and find all the positions that can be legally reached in one move.
* Find all the positions that can be legally reached from those positions, that haven't already been identified.
* Repeat until no more can be found, and return the number of positions found altogether.
# Code
*(now with some doctests and asserts after my incorrect first attempt)*
```
'''
Snake combinations
A snake is represented by a tuple giving the relative orientation at each joint.
A length n snake has n-1 joints.
Each relative orientation is one of the following:
0: Clockwise 90 degrees
1: Straight
2: Anticlockwise 90 degrees
So a straight snake of length 4 has 3 joints all set to 1:
(1, 1, 1)
x increases to the right
y increases upwards
'''
import turtle
def all_coords(state):
'''Return list of coords starting from (0,0) heading right.'''
current = (1, 0)
heading = 0
coords = [(0,0), (1,0)]
for item in state:
heading += item + 3
heading %= 4
offset = ((1,0), (0,1), (-1,0), (0,-1))[heading]
current = tuple(current[i]+offset[i] for i in (0,1))
coords.append(current)
return coords
def line_segments(coords, pivot):
'''Return list of line segments joining consecutive coords up to pivot-1.'''
return [(coords[i], coords[i+1]) for i in range(pivot+1)]
def rotation_direction(coords, pivot, coords_in_final_after_pivot):
'''Return -1 if turning clockwise, 1 if turning anticlockwise.'''
pivot_coord = coords[pivot + 1]
initial_coord = coords[pivot + 2]
final_coord = coords_in_final_after_pivot[0]
initial_direction = tuple(initial_coord[i] - pivot_coord[i] for i in (0,1))
final_direction = tuple(final_coord[i] - pivot_coord[i] for i in (0,1))
return (initial_direction[0] * final_direction[1] -
initial_direction[1] * final_direction[0]
)
def intersects(arc, line):
'''Return True if the arc intersects the line segment.'''
if line_segment_cuts_circle(arc, line):
cut_points = points_cutting_circle(arc, line)
if cut_points and cut_point_is_on_arc(arc, cut_points):
return True
def line_segment_cuts_circle(arc, line):
'''Return True if the line endpoints are not both inside or outside.'''
centre, point, direction = arc
start, finish = line
point_distance_squared = distance_squared(centre, point)
start_distance_squared = distance_squared(centre, start)
finish_distance_squared = distance_squared(centre, finish)
start_sign = start_distance_squared - point_distance_squared
finish_sign = finish_distance_squared - point_distance_squared
if start_sign * finish_sign <= 0:
return True
def distance_squared(centre, point):
'''Return the square of the distance between centre and point.'''
return sum((point[i] - centre[i]) ** 2 for i in (0,1))
def cut_point_is_on_arc(arc, cut_points):
'''Return True if any intersection point with circle is on arc.'''
centre, arc_start, direction = arc
relative_start = tuple(arc_start[i] - centre[i] for i in (0,1))
relative_midpoint = ((relative_start[0] - direction*relative_start[1])/2,
(relative_start[1] + direction*relative_start[0])/2
)
span_squared = distance_squared(relative_start, relative_midpoint)
for cut_point in cut_points:
relative_cut_point = tuple(cut_point[i] - centre[i] for i in (0,1))
spacing_squared = distance_squared(relative_cut_point,
relative_midpoint
)
if spacing_squared <= span_squared:
return True
def points_cutting_circle(arc, line):
'''Return list of points where line segment cuts circle.'''
points = []
start, finish = line
centre, arc_start, direction = arc
radius_squared = distance_squared(centre, arc_start)
length_squared = distance_squared(start, finish)
relative_start = tuple(start[i] - centre[i] for i in (0,1))
relative_finish = tuple(finish[i] - centre[i] for i in (0,1))
relative_midpoint = tuple((relative_start[i] +
relative_finish[i]
)*0.5 for i in (0,1))
determinant = (relative_start[0]*relative_finish[1] -
relative_finish[0]*relative_start[1]
)
determinant_squared = determinant ** 2
discriminant = radius_squared * length_squared - determinant_squared
offset = tuple(finish[i] - start[i] for i in (0,1))
sgn = (1, -1)[offset[1] < 0]
root_discriminant = discriminant ** 0.5
one_over_length_squared = 1 / length_squared
for sign in (-1, 1):
x = (determinant * offset[1] +
sign * sgn * offset[0] * root_discriminant
) * one_over_length_squared
y = (-determinant * offset[0] +
sign * abs(offset[1]) * root_discriminant
) * one_over_length_squared
check = distance_squared(relative_midpoint, (x,y))
if check <= length_squared * 0.25:
points.append((centre[0] + x, centre[1] + y))
return points
def potential_neighbours(candidate):
'''Return list of states one turn away from candidate.'''
states = []
for i in range(len(candidate)):
for orientation in range(3):
if abs(candidate[i] - orientation) == 1:
state = list(candidate)
state[i] = orientation
states.append(tuple(state))
return states
def reachable(initial, final):
'''
Return True if final state can be reached in one legal move.
>>> reachable((1,0,0), (0,0,0))
False
>>> reachable((0,1,0), (0,0,0))
False
>>> reachable((0,0,1), (0,0,0))
False
>>> reachable((1,2,2), (2,2,2))
False
>>> reachable((2,1,2), (2,2,2))
False
>>> reachable((2,2,1), (2,2,2))
False
>>> reachable((1,2,1,2,1,1,2,2,1), (1,2,1,2,1,1,2,1,1))
False
'''
pivot = -1
for i in range(len(initial)):
if initial[i] != final[i]:
pivot = i
break
assert pivot > -1, '''
No pivot between {} and {}'''.format(initial, final)
assert initial[pivot + 1:] == final[pivot + 1:], '''
More than one pivot between {} and {}'''.format(initial, final)
coords_in_initial = all_coords(initial)
coords_in_final_after_pivot = all_coords(final)[pivot+2:]
coords_in_initial_after_pivot = coords_in_initial[pivot+2:]
line_segments_up_to_pivot = line_segments(coords_in_initial, pivot)
direction = rotation_direction(coords_in_initial,
pivot,
coords_in_final_after_pivot
)
pivot_point = coords_in_initial[pivot + 1]
for point in coords_in_initial_after_pivot:
arc = (pivot_point, point, direction)
if any(intersects(arc, line) for line in line_segments_up_to_pivot):
return False
return True
def display(snake):
'''Display a line diagram of the snake.
Accepts a snake as either a tuple:
(1, 1, 2, 0)
or a string:
"1120"
'''
snake = tuple(int(s) for s in snake)
coords = all_coords(snake)
turtle.clearscreen()
t = turtle.Turtle()
t.hideturtle()
s = t.screen
s.tracer(0)
width, height = s.window_width(), s.window_height()
x_min = min(coord[0] for coord in coords)
x_max = max(coord[0] for coord in coords)
y_min = min(coord[1] for coord in coords)
y_max = max(coord[1] for coord in coords)
unit_length = min(width // (x_max - x_min + 1),
height // (y_max - y_min + 1)
)
origin_x = -(x_min + x_max) * unit_length // 2
origin_y = -(y_min + y_max) * unit_length // 2
pen_width = max(1, unit_length // 20)
t.pensize(pen_width)
dot_size = max(4, pen_width * 3)
t.penup()
t.setpos(origin_x, origin_y)
t.pendown()
t.forward(unit_length)
for joint in snake:
t.dot(dot_size)
t.left((joint - 1) * 90)
t.forward(unit_length)
s.update()
def neighbours(origin, excluded=()):
'''Return list of states reachable in one step.'''
states = []
for candidate in potential_neighbours(origin):
if candidate not in excluded and reachable(origin, candidate):
states.append(candidate)
return states
def mirrored_or_backwards(candidates):
'''Return set of states that are equivalent to a state in candidates.'''
states = set()
for candidate in candidates:
mirrored = tuple(2 - joint for joint in candidate)
backwards = candidate[::-1]
mirrored_backwards = mirrored[::-1]
states |= set((mirrored, backwards, mirrored_backwards))
return states
def possible_snakes(snake):
'''
Return the set of possible arrangements of the given snake.
>>> possible_snakes((1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1))
{(1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1)}
'''
reached = set()
candidates = set((snake,))
while candidates:
candidate = candidates.pop()
reached.add(candidate)
new_candidates = neighbours(candidate, reached)
reached |= mirrored_or_backwards(new_candidates)
set_of_new_candidates = set(new_candidates)
reached |= set_of_new_candidates
candidates |= set_of_new_candidates
excluded = set()
final_answers = set()
while reached:
candidate = reached.pop()
if candidate not in excluded:
final_answers.add(candidate)
excluded |= mirrored_or_backwards([candidate])
return final_answers
def straight_derived_snakes(length):
'''Return the set of possible arrangements of a snake of this length.'''
straight_line = (1,) * max(length-1, 0)
return possible_snakes(straight_line)
if __name__ == '__main__':
import doctest
doctest.testmod()
import sys
arguments = sys.argv[1:]
if arguments:
length = int(arguments[0])
else:
length = int(input('Enter the length of the snake:'))
print(len(straight_derived_snakes(length)))
```
# Results
On my machine the longest snake that can be calculated in under 1 minute is length 11 (or length 13 with PyPy\*). This is obviously just a provisional score until we find out what the official score is from Lembik's machine.
For comparison, here are the results for the first few values of n:
```
n | reachable orientations
-----------------------------
0 | 1
1 | 1
2 | 2
3 | 4
4 | 9
5 | 22
6 | 56
7 | 147
8 | 388
9 | 1047
10 | 2806
11 | 7600
12 | 20437
13 | 55313
14 | 148752
15 | 401629
16 | 1078746
17 | MemoryError (on my machine)
```
Please let me know if any of these turn out to be incorrect.
If you have an example of an arrangement that should not be able to be unfolded, you can use the function `neighbours(snake)` to find any arrangements reachable in one step, as a test of the code. `snake` is a tuple of joint directions (0 for clockwise, 1 for straight, 2 for anticlockwise). For example (1,1,1) is a straight snake of length 4 (with 3 joints).
# Visualisation
To visualise a snake you have in mind, or any of the snakes returned by `neighbours`, you can use the function `display(snake)`. This accepts a tuple like the other functions, but since it is not used by the main program and therefore does not need to be fast, it will also accept a string, for your convenience.
`display((1,1,2,0))` is equivalent to `display("1120")`
As Lembik mentions in the comments, my results are identical to [OEIS A037245](https://oeis.org/A037245 "paths that do not intersect (but do not require bending into shape)") which does not take into account intersections during rotation. This is because for the first few values of n there is no difference - all shapes that do not self-intersect can be reached by folding a straight snake. The correctness of the code can be tested by calling `neighbours()` with a snake that cannot be unfolded without intersection. Since it has no neighbours it will contribute only to the OEIS sequence, and not to this one. The smallest example I am aware of is this length 31 snake that Lembik mentioned, thanks to [David K](https://math.stackexchange.com/users/139123/david-k "thank you!"):
`(1,1,1,1,2,1,2,1,1,1,1,1,1,2,1,1,1,2,1,1,2,2,1,0,1,0,1,1,1,1)`
`display('111121211111121112112210101111')` gives the following output:

>
> **Tip:** If you resize the display window and then call display again, the snake will be fitted to the new window size.
>
>
>
I'd love to hear from anyone who has a shorter example with no neighbours. I suspect that the shortest such example will mark the smallest n for which the two sequences differ.
---
*\*Note that each increment of n takes very roughly 3 times as long, so increasing from n=11 to n=13 requires almost 10 times the time. This is why PyPy only allows increasing n by 2, even though it runs considerably faster than the standard Python interpreter.*
[Answer]
# C++11 - nearly working :)
After reading [this article](http://www.yumpu.com/en/document/view/16913964/avoiding-yourself-bit-player), I collected bits of wisdom from that guy who apparently worked for 25 years on the less complicated problem of counting self-avoiding paths on a square lattice.
```
#include <cassert>
#include <ctime>
#include <sstream>
#include <vector>
#include <algorithm> // sort
using namespace std;
// theroretical max snake lenght (the code would need a few decades to process that value)
#define MAX_LENGTH ((int)(1+8*sizeof(unsigned)))
#ifndef _MSC_VER
#ifndef QT_DEBUG // using Qt IDE for g++ builds
#define NDEBUG
#endif
#endif
#ifdef NDEBUG
inline void tprintf(const char *, ...){}
#else
#define tprintf printf
#endif
void panic(const char * msg)
{
printf("PANIC: %s\n", msg);
exit(-1);
}
// ============================================================================
// fast bit reversal
// ============================================================================
unsigned bit_reverse(register unsigned x, unsigned len)
{
x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));
x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));
x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));
x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));
return((x >> 16) | (x << 16)) >> (32-len);
}
// ============================================================================
// 2D geometry (restricted to integer coordinates and right angle rotations)
// ============================================================================
// points using integer- or float-valued coordinates
template<typename T>struct tTypedPoint;
typedef int tCoord;
typedef double tFloatCoord;
typedef tTypedPoint<tCoord> tPoint;
typedef tTypedPoint<tFloatCoord> tFloatPoint;
template <typename T>
struct tTypedPoint {
T x, y;
template<typename U> tTypedPoint(const tTypedPoint<U>& from) : x((T)from.x), y((T)from.y) {} // conversion constructor
tTypedPoint() {}
tTypedPoint(T x, T y) : x(x), y(y) {}
tTypedPoint(const tTypedPoint& p) { *this = p; }
tTypedPoint operator+ (const tTypedPoint & p) const { return{ x + p.x, y + p.y }; }
tTypedPoint operator- (const tTypedPoint & p) const { return{ x - p.x, y - p.y }; }
tTypedPoint operator* (T scalar) const { return{ x * scalar, y * scalar }; }
tTypedPoint operator/ (T scalar) const { return{ x / scalar, y / scalar }; }
bool operator== (const tTypedPoint & p) const { return x == p.x && y == p.y; }
bool operator!= (const tTypedPoint & p) const { return !operator==(p); }
T dot(const tTypedPoint &p) const { return x*p.x + y * p.y; } // dot product
int cross(const tTypedPoint &p) const { return x*p.y - y * p.x; } // z component of cross product
T norm2(void) const { return dot(*this); }
// works only with direction = 1 (90° right) or -1 (90° left)
tTypedPoint rotate(int direction) const { return{ direction * y, -direction * x }; }
tTypedPoint rotate(int direction, const tTypedPoint & center) const { return (*this - center).rotate(direction) + center; }
// used to compute length of a ragdoll snake segment
unsigned manhattan_distance(const tPoint & p) const { return abs(x-p.x) + abs(y-p.y); }
};
struct tArc {
tPoint c; // circle center
tFloatPoint middle_vector; // vector splitting the arc in half
tCoord middle_vector_norm2; // precomputed for speed
tFloatCoord dp_limit;
tArc() {}
tArc(tPoint c, tPoint p, int direction) : c(c)
{
tPoint r = p - c;
tPoint end = r.rotate(direction);
middle_vector = ((tFloatPoint)(r+end)) / sqrt(2); // works only for +-90° rotations. The vector should be normalized to circle radius in the general case
middle_vector_norm2 = r.norm2();
dp_limit = ((tFloatPoint)r).dot(middle_vector);
assert (middle_vector == tPoint(0, 0) || dp_limit != 0);
}
bool contains(tFloatPoint p) // p must be a point on the circle
{
if ((p-c).dot(middle_vector) >= dp_limit)
{
return true;
}
else return false;
}
};
// returns the point of line (p1 p2) that is closest to c
// handles degenerate case p1 = p2
tPoint line_closest_point(tPoint p1, tPoint p2, tPoint c)
{
if (p1 == p2) return{ p1.x, p1.y };
tPoint p1p2 = p2 - p1;
tPoint p1c = c - p1;
tPoint disp = (p1p2 * p1c.dot(p1p2)) / p1p2.norm2();
return p1 + disp;
}
// variant of closest point computation that checks if the projection falls within the segment
bool closest_point_within(tPoint p1, tPoint p2, tPoint c, tPoint & res)
{
tPoint p1p2 = p2 - p1;
tPoint p1c = c - p1;
tCoord nk = p1c.dot(p1p2);
if (nk <= 0) return false;
tCoord n = p1p2.norm2();
if (nk >= n) return false;
res = p1 + p1p2 * (nk / n);
return true;
}
// tests intersection of line (p1 p2) with an arc
bool inter_seg_arc(tPoint p1, tPoint p2, tArc arc)
{
tPoint m = line_closest_point(p1, p2, arc.c);
tCoord r2 = arc.middle_vector_norm2;
tPoint cm = m - arc.c;
tCoord h2 = cm.norm2();
if (r2 < h2) return false; // no circle intersection
tPoint p1p2 = p2 - p1;
tCoord n2p1p2 = p1p2.norm2();
// works because by construction p is on (p1 p2)
auto in_segment = [&](const tFloatPoint & p) -> bool
{
tFloatCoord nk = p1p2.dot(p - p1);
return nk >= 0 && nk <= n2p1p2;
};
if (r2 == h2) return arc.contains(m) && in_segment(m); // tangent intersection
//if (p1 == p2) return false; // degenerate segment located inside circle
assert(p1 != p2);
tFloatPoint u = (tFloatPoint)p1p2 * sqrt((r2-h2)/n2p1p2); // displacement on (p1 p2) from m to one intersection point
tFloatPoint i1 = m + u;
if (arc.contains(i1) && in_segment(i1)) return true;
tFloatPoint i2 = m - u;
return arc.contains(i2) && in_segment(i2);
}
// ============================================================================
// compact storage of a configuration (64 bits)
// ============================================================================
struct sConfiguration {
unsigned partition;
unsigned folding;
explicit sConfiguration() {}
sConfiguration(unsigned partition, unsigned folding) : partition(partition), folding(folding) {}
// add a bend
sConfiguration bend(unsigned joint, int rotation) const
{
sConfiguration res;
unsigned joint_mask = 1 << joint;
res.partition = partition | joint_mask;
res.folding = folding;
if (rotation == -1) res.folding |= joint_mask;
return res;
}
// textual representation
string text(unsigned length) const
{
ostringstream res;
unsigned f = folding;
unsigned p = partition;
int segment_len = 1;
int direction = 1;
for (size_t i = 1; i != length; i++)
{
if (p & 1)
{
res << segment_len * direction << ',';
direction = (f & 1) ? -1 : 1;
segment_len = 1;
}
else segment_len++;
p >>= 1;
f >>= 1;
}
res << segment_len * direction;
return res.str();
}
// for final sorting
bool operator< (const sConfiguration& c) const
{
return (partition == c.partition) ? folding < c.folding : partition < c.partition;
}
};
// ============================================================================
// static snake geometry checking grid
// ============================================================================
typedef unsigned tConfId;
class tGrid {
vector<tConfId>point;
tConfId current;
size_t snake_len;
int min_x, max_x, min_y, max_y;
size_t x_size, y_size;
size_t raw_index(const tPoint& p) { bound_check(p); return (p.x - min_x) + (p.y - min_y) * x_size; }
void bound_check(const tPoint& p) const { assert(p.x >= min_x && p.x <= max_x && p.y >= min_y && p.y <= max_y); }
void set(const tPoint& p)
{
point[raw_index(p)] = current;
}
bool check(const tPoint& p)
{
if (point[raw_index(p)] == current) return false;
set(p);
return true;
}
public:
tGrid(int len) : current(-1), snake_len(len)
{
min_x = -max(len - 3, 0);
max_x = max(len - 0, 0);
min_y = -max(len - 1, 0);
max_y = max(len - 4, 0);
x_size = max_x - min_x + 1;
y_size = max_y - min_y + 1;
point.assign(x_size * y_size, current);
}
bool check(sConfiguration c)
{
current++;
tPoint d(1, 0);
tPoint p(0, 0);
set(p);
for (size_t i = 1; i != snake_len; i++)
{
p = p + d;
if (!check(p)) return false;
if (c.partition & 1) d = d.rotate((c.folding & 1) ? -1 : 1);
c.folding >>= 1;
c.partition >>= 1;
}
return check(p + d);
}
};
// ============================================================================
// snake ragdoll
// ============================================================================
class tSnakeDoll {
vector<tPoint>point; // snake geometry. Head at (0,0) pointing right
// allows to check for collision with the area swept by a rotating segment
struct rotatedSegment {
struct segment { tPoint a, b; };
tPoint org;
segment end;
tArc arc[3];
bool extra_arc; // see if third arc is needed
// empty constructor to avoid wasting time in vector initializations
rotatedSegment(){}
// copy constructor is mandatory for vectors *but* shall never be used, since we carefully pre-allocate vector memory
rotatedSegment(const rotatedSegment &){ assert(!"rotatedSegment should never have been copy-constructed"); }
// rotate a segment
rotatedSegment(tPoint pivot, int rotation, tPoint o1, tPoint o2)
{
arc[0] = tArc(pivot, o1, rotation);
arc[1] = tArc(pivot, o2, rotation);
tPoint middle;
extra_arc = closest_point_within(o1, o2, pivot, middle);
if (extra_arc) arc[2] = tArc(pivot, middle, rotation);
org = o1;
end = { o1.rotate(rotation, pivot), o2.rotate(rotation, pivot) };
}
// check if a segment intersects the area swept during rotation
bool intersects(tPoint p1, tPoint p2) const
{
auto print_arc = [&](int a) { tprintf("(%d,%d)(%d,%d) -> %d (%d,%d)[%f,%f]", p1.x, p1.y, p2.x, p2.y, a, arc[a].c.x, arc[a].c.y, arc[a].middle_vector.x, arc[a].middle_vector.y); };
if (p1 == org) return false; // pivot is the only point allowed to intersect
if (inter_seg_arc(p1, p2, arc[0]))
{
print_arc(0);
return true;
}
if (inter_seg_arc(p1, p2, arc[1]))
{
print_arc(1);
return true;
}
if (extra_arc && inter_seg_arc(p1, p2, arc[2]))
{
print_arc(2);
return true;
}
return false;
}
};
public:
sConfiguration configuration;
bool valid;
// holds results of a folding attempt
class snakeFolding {
friend class tSnakeDoll;
vector<rotatedSegment>segment; // rotated segments
unsigned joint;
int direction;
size_t i_rotate;
// pre-allocate rotated segments
void reserve(size_t length)
{
segment.clear(); // this supposedly does not release vector storage memory
segment.reserve(length);
}
// handle one segment rotation
void rotate(tPoint pivot, int rotation, tPoint o1, tPoint o2)
{
segment.emplace_back(pivot, rotation, o1, o2);
}
public:
// nothing done during construction
snakeFolding(unsigned size)
{
segment.reserve (size);
}
};
// empty default constructor to avoid wasting time in array/vector inits
tSnakeDoll() {}
// constructs ragdoll from compressed configuration
tSnakeDoll(unsigned size, unsigned generator, unsigned folding) : point(size), configuration(generator,folding)
{
tPoint direction(1, 0);
tPoint current = { 0, 0 };
size_t p = 0;
point[p++] = current;
for (size_t i = 1; i != size; i++)
{
current = current + direction;
if (generator & 1)
{
direction.rotate((folding & 1) ? -1 : 1);
point[p++] = current;
}
folding >>= 1;
generator >>= 1;
}
point[p++] = current;
point.resize(p);
}
// constructs the initial flat snake
tSnakeDoll(int size) : point(2), configuration(0,0), valid(true)
{
point[0] = { 0, 0 };
point[1] = { size, 0 };
}
// constructs a new folding with one added rotation
tSnakeDoll(const tSnakeDoll & parent, unsigned joint, int rotation, tGrid& grid)
{
// update configuration
configuration = parent.configuration.bend(joint, rotation);
// locate folding point
unsigned p_joint = joint+1;
tPoint pivot;
size_t i_rotate = 0;
for (size_t i = 1; i != parent.point.size(); i++)
{
unsigned len = parent.point[i].manhattan_distance(parent.point[i - 1]);
if (len > p_joint)
{
pivot = parent.point[i - 1] + ((parent.point[i] - parent.point[i - 1]) / len) * p_joint;
i_rotate = i;
break;
}
else p_joint -= len;
}
// rotate around joint
snakeFolding fold (parent.point.size() - i_rotate);
fold.rotate(pivot, rotation, pivot, parent.point[i_rotate]);
for (size_t i = i_rotate + 1; i != parent.point.size(); i++) fold.rotate(pivot, rotation, parent.point[i - 1], parent.point[i]);
// copy unmoved points
point.resize(parent.point.size()+1);
size_t i;
for (i = 0; i != i_rotate; i++) point[i] = parent.point[i];
// copy rotated points
for (; i != parent.point.size(); i++) point[i] = fold.segment[i - i_rotate].end.a;
point[i] = fold.segment[i - 1 - i_rotate].end.b;
// static configuration check
valid = grid.check (configuration);
// check collisions with swept arcs
if (valid && parent.valid) // ;!; parent.valid test is temporary
{
for (const rotatedSegment & s : fold.segment)
for (size_t i = 0; i != i_rotate; i++)
{
if (s.intersects(point[i+1], point[i]))
{
//printf("! %s => %s\n", parent.trace().c_str(), trace().c_str());//;!;
valid = false;
break;
}
}
}
}
// trace
string trace(void) const
{
size_t len = 0;
for (size_t i = 1; i != point.size(); i++) len += point[i - 1].manhattan_distance(point[i]);
return configuration.text(len);
}
};
// ============================================================================
// snake twisting engine
// ============================================================================
class cSnakeFolder {
int length;
unsigned num_joints;
tGrid grid;
// filter redundant configurations
bool is_unique (sConfiguration c)
{
unsigned reverse_p = bit_reverse(c.partition, num_joints);
if (reverse_p < c.partition)
{
tprintf("P cut %s\n", c.text(length).c_str());
return false;
}
else if (reverse_p == c.partition) // filter redundant foldings
{
unsigned first_joint_mask = c.partition & (-c.partition); // insulates leftmost bit
unsigned reverse_f = bit_reverse(c.folding, num_joints);
if (reverse_f & first_joint_mask) reverse_f = ~reverse_f & c.partition;
if (reverse_f > c.folding)
{
tprintf("F cut %s\n", c.text(length).c_str());
return false;
}
}
return true;
}
// recursive folding
void fold(tSnakeDoll snake, unsigned first_joint)
{
// count unique configurations
if (snake.valid && is_unique(snake.configuration)) num_configurations++;
// try to bend remaining joints
for (size_t joint = first_joint; joint != num_joints; joint++)
{
// right bend
tprintf("%s -> %s\n", snake.configuration.text(length).c_str(), snake.configuration.bend(joint,1).text(length).c_str());
fold(tSnakeDoll(snake, joint, 1, grid), joint + 1);
// left bend, except for the first joint
if (snake.configuration.partition != 0)
{
tprintf("%s -> %s\n", snake.configuration.text(length).c_str(), snake.configuration.bend(joint, -1).text(length).c_str());
fold(tSnakeDoll(snake, joint, -1, grid), joint + 1);
}
}
}
public:
// count of found configurations
unsigned num_configurations;
// constructor does all the work :)
cSnakeFolder(int n) : length(n), grid(n), num_configurations(0)
{
num_joints = length - 1;
// launch recursive folding
fold(tSnakeDoll(length), 0);
}
};
// ============================================================================
// here we go
// ============================================================================
int main(int argc, char * argv[])
{
#ifdef NDEBUG
if (argc != 2) panic("give me a snake length or else");
int length = atoi(argv[1]);
#else
(void)argc; (void)argv;
int length = 12;
#endif // NDEBUG
if (length <= 0 || length >= MAX_LENGTH) panic("a snake of that length is hardly foldable");
time_t start = time(NULL);
cSnakeFolder snakes(length);
time_t duration = time(NULL) - start;
printf ("Found %d configuration%c of length %d in %lds\n", snakes.num_configurations, (snakes.num_configurations == 1) ? '\0' : 's', length, duration);
return 0;
}
```
## Building the executable
Compile with **`g++ -O3 -std=c++11`**
I use MinGW under Win7 with g++4.8 for "linux" builds, so portability is not 100% guaranteed.
It also works (sort of) with a standard MSVC2013 project
By undefining **`NDEBUG`**, you get traces of algorithm execution and a summary of found configurations.
## Performances
with or without hash tables, Microsoft compiler performs miserably: g++ build is **3 times faster**.
The algorithm uses practically no memory.
Since collision check is roughly in O(n), computation time should be in O(nkn), with k slightly lower than 3.
On my [[email protected]](/cdn-cgi/l/email-protection), n=17 takes about 1:30 (about 2 million snakes/minute).
I am not done optimizing, but I would not expect more than a x3 gain, so basically I can hope to reach maybe n=20 under an hour, or n=24 under a day.
Reaching the first known unbendable shape (n=31) would take between a few years and a decade, assuming no power outages.
## Counting shapes
A **N** size snake has **N-1** joints.
Each joint can be left straight or bent to the left or right (3 possibilities).
The number of possible foldings is thus 3N-1.
Collisions will reduce that number somewhat, so the actual number is close to 2.7N-1
However, many such foldings lead to identical shapes.
two shapes are identical if there is either a **rotation** or a **symetry** that can transform one into the other.
Let's define a **segment** as any straight part of the folded body.
For instance a size 5 snake folded at 2nd joint would have 2 segments (one 2 units long and the second 3 units long).
The first segment will be named **head**, and the last **tail**.
By convention we orient the snakes's head horizontally with the body pointing right (like in the OP first figure).
We designate a given figure with a list of signed segment lengths, with positive lengths indicating a right folding and negative ones a left folding.
Initial lenght is positive by convention.
## Separating segments and bends
If we consider only the different ways a snake of length N can be split into segments, we end up with a repartition identical to the [compositions](http://en.wikipedia.org/wiki/Composition_%28combinatorics%29) of N.
Using the same algorithm as shown in the wiki page, it is easy to generate all the 2N-1 possible ***partitions*** of the snake.
Each partition will in turn generate all possible foldings by applying either left or right bends to all of its joints. One such folding will be called a **configuration**.
All possible partitions can be represented by an integer of N-1 bits, where each bit represents the presence of a joint. We will call this integer a ***generator***.
## Pruning partitions
By noticing that bending a given partition from the head down is equivalent to bending the symetrical partition from the tail up, we can find all couples of symetrical partitions and eliminate one out of two.
The generator of a symetrical partition is the partition's generator written in reverse bit order, which is trivially easy and cheap to detect.
This will eliminate almost half of the possible partitions, the exceptions being the partitions with "palindromic" generators that are left unchanged by bit reversal (for instance 00100100).
## Taking care of horizontal symetries
With our conventions (a snake starts pointing to the right), the very first bend applied to the right will produce a family of foldings that will be horizontal symetrics from the ones that differ only by the first bend.
If we decide that the first bend will always be to the right, we eliminate all horizontal symetrics in one big swoop.
## Mopping up the palindromes
These two cuts are efficient, but not enough to take care of these pesky palindromes.
The most thorough check in the general case is as follows:
consider a configuration C with a palindromic partition.
* if we *invert* every bend in C, we end up with a horizontal symetric of C.
* if we *reverse* C (applying bends from the tail up), we get the same figure rotated right
* if we both reverse and invert C, we get the same figure rotated left.
We could check every new configuration against the 3 others. However, since we already generate only configurations starting with a right turn, we only have one possible symetry to check:
* the inverted C will start with a left turn, which is by construction impossible to duplicate
* out of the reversed and inverted-reversed configurations, only one will start with a right turn.
That is the only one configuration we can possibly duplicate.
## Eliminating duplicates without any storage
My initial approach was to store all configurations in a huge hash table, to eliminate duplicates by checking the presence of a previously computed symetric configuration.
Thanks to the aforementioned article, it became clear that, since partitions and foldings are stored as bitfields, they can be compared like any numerical value.
So to eliminate one member of a symetric pair, you can simply compare both elements and systematically keep the smallest one (or the greatest one, as you like).
Thus, testing a configuration for duplication amounts to computing the symetric partition, and if both are identical, the folding. No memory is needed at all.
## Order of generation
Clearly collision check will be the most time-consuming part, so reducing these computations is a major time-saver.
A possible solution is to have a "ragdoll snake" that will start in a flat configuration and be gradually bent, to avoid recomputing the whole snake geometry for each possible configuration.
By choosing the order in which configurations are tested, so that at most a ragdoll is stored for each total number of joints, we can limit the number of instances to N-1.
I use a recursive scan of the sake from the tail down, adding a single joint at each level. Thus a new ragdoll instance is built on top of the parent configuration, with a single aditional bend.
This means bends are applied in a sequential order, which seems to be enough to avoid self-collisions in almost all cases.
When self-collision is detected, the bends that lead to the offending move are applied in all possible orders until legit folding is found or all combinations are exhausted.
## Static check
Before even thinking about moving parts, I found it more efficient to test the static final shape of a snake for self-intersections.
This is done by drawing the snake on a grid. Each possible point is plotted from the head down. If there is a self-intersection, at least a pair of points will fall on the same location.
This requires exactly N plots for any snake configuration, for a constant O(N) time.
The main advantage of this approach is that the static test alone will simply select valid self-avoiding paths on a square lattice, which allows to test the whole algorithm by inhibiting dynamic collision detection and making sure we find the correct count of such paths.
## Dynamic check
When a snake folds around one joint, each rotated segment will sweep an area whose shape is anything but trivial.
Clearly you can check collisions by testing inclusion within all such swept areas individually. A global check would be more efficient, but given the areas complexity I can't think of any (except maybe using a GPU to draw all areas and perform a global hit check).
Since the static test takes care of the starting and ending positions of each segment, we just need to check intersections with the ***arcs*** swept by each rotating segments.
After an interesting discussion with trichoplax and [a bit of JavaScript](http://petiteleve.free.fr/SO/sweep.html) to get my bearings, I came up with this method:
To try to put it in a few words, if you call
* **C** the center of rotation,
* **S** a rotating segment of arbitrary lenght and direction that does not contain **C**,
* **L** the line prolongating **S**
* **H** the line orthogonal to **L** passing through **C**,
* **I** the intersection of **L** and **H**,
[](https://i.stack.imgur.com/MiWC4.png)
(source: [free.fr](http://petiteleve.free.fr/SO/sweep.png))
For any segment that does not contain **I**, the swept area is bound by 2 arcs (and 2 segments already taken care of by the static check).
If **I** falls within the segment, the arc swept by I must also be taken into account.
This means we can check each unmoving segment against each rotating segment with 2 or 3 segment-with-arc intersections
I used vector geometry to avoid trigonometric functions altogether.
Vector operations produce compact and (relatively) readable code.
Segment-to-arc intersection requires a floating point vector, but the logic should be immune to rounding errors.
I found this elegant and efficient solution in an obscure forum post. I wonder why it is not more widely publicized.
## Does it work?
Inhibiting dynamic collision detection produces the correct self-avoiding paths count up to n=19, so I'm pretty confident the global layout works.
Dynamic collision detection produces consistent results, though the check of bends in different order is missing (for now).
As a consequence, the program counts snakes that can be bent from the head down (i.e. with joints folded in order of increasing distance from the head).
] |
[Question]
[
There are P parking spaces in a parking lot, though some spaces are occupied by cars represented by octothorpes `#` while the free spaces are dots `.`. Soon there arrive T trucks, each of which will take up exactly L consecutive spaces. The trucks don't have to be parked next to each other.
Your task is to create a program that will find the smallest number of cars that need to be removed in order to park all of the trucks. There will always be enough spaces to fit all of the trucks, meaning `T*L<P`
## Input
In the first row there will be three integers, P, T and L separated by spaces. In the second row there will be a string of P characters representing the parking lot in its initial state.
## Output
In the first and only line your program should print out the smallest number of cars that need to be removed in order to park all of the trucks.
## Test cases
Input:
`6 1 3`
`#.#.##`
Output: `1`
Input:
`9 2 3`
`.##..#..#`
Output: `2`
Input:
`15 2 5`
`.#.....#.#####.`
Output: `3`
Shortest code wins. (Note: I'm particularly interested in a pyth implementation, if one is possible)
[Answer]
# Python 2, 154 bytes
```
I,R=raw_input,range
P,T,L=map(int,I().split())
S=I()
D=R(P+1)
for r in R(P):D[1:r+2]=[min([D[c],D[c-1]+(S[r]<".")][c%L>0:])for c in R(1,r+2)]
print D[T*L]
```
A straightforward DP approach. A fair chunk of the program is just reading input.
**Explanation**
We calculate a 2D dynamic programming table where each row corresponds to the first `n` parking spots, and each column corresponds to the number of trucks (or parts of a truck) placed so far. In particular, column `k` means that we've placed `k//L` full trucks so far, and we're `k%L` along the way for a new truck. Each cell is then the minimal number of cars to clear to reach the state `(n,k)`, and our target state is `(P, L*T)`.
The idea behind the DP recurrence is the following:
* If we're `k%L > 0` spaces along for a new truck, then our only option is to have come from being `k%L-1` spaces along for a new truck
* Otherwise if `k%L == 0` then we have either just finished a new truck, or we'd already finished the last truck and have since skipped a few parking spots. We take the minimum of the two options.
If `k > n`, i.e. we've placed more truck squares than there are parking spots, then we put `∞` for state `(n,k)`. But for the purposes of golfing, we put `k` since this is the worst case of removing every car, and also serves as an upper bound.
This was quite a mouthful, so let's have an example, say:
```
5 1 3
..##.
```
The last two rows of the table are
```
[0, 1, 2, 1, 2, ∞]
[0, 0, 1, 1, 1, 2]
```
The entry at index 2 of the second last row is 2, because to reach a state of `2//3 = 0` full trucks placed and being `2%3 = 2` spaces along for a new truck, this is the only option:
```
TT
..XX
```
But the entry at index 3 of the second last row is 1, because to reach a state of `3//3 = 1` full trucks placed and being `3%3 = 0` spaces along for a new truck, the optimal is
```
TTT
..X#
```
The entry at index 3 of the last row looks at the above two cells as options — do we take the case where we are 2 spaces along for a new truck and finish it off, or do we take the case where we have a full truck already finished?
```
TTT TTT
..XX. vs ..X#.
```
Clearly the latter is better, so we put down a 1.
## Pyth, 70 bytes
```
JmvdczdKw=GUhhJVhJ=HGFTUhN XHhThS>,@GhT+@GTq@KN\#>%hT@J2Z)=GH)@G*@J1eJ
```
Basically a port of the above code. Not very well golfed yet. [Try it online](https://pyth.herokuapp.com/)
**Expanded**
```
Jmvdczd J = map(eval, input().split(" "))
Kw K = input()
=GUhhJ G = range(J[0]+1)
VhJ for N in range(J[0]):
=HG H = G[:]
FTUhN for T in range(N+1):
XHhT H[T+1] =
hS sorted( )[0]
> [ :]
, ( , )
@GhT G[T+1]
+@GTq@KN\# G[T]+(K[N]=="#")
>%hT@J2Z (T+1)%J[2]>0
)=GH G = H[:]
)@G*@J1eJ print(G[J[1]*J[-1]])
```
Now, if only Pyth had multiple assignment to >2 variables...
[Answer]
## Haskell, 196 characters
```
import Data.List
f=filter
m=map
q[_,t,l]=f((>=t).sum.m((`div`l).length).f(>"-").group).sequence.m(:".")
k[a,p]=minimum.m(sum.m fromEnum.zipWith(/=)p)$q(m read$words a)p
main=interact$show.k.lines
```
Runs all examples
```
& (echo 6 1 3 ; echo "#.#.##" ) | runhaskell 44946-Trucks.hs
1
& (echo 9 2 3 ; echo ".##..#..#" ) | runhaskell 44946-Trucks.hs
2
& (echo 15 2 5 ; echo ".#.....#.#####." ) | runhaskell 44946-Trucks.hs
3
```
Somewhat slow: **O(2^P)** were P is the size of the lot.
Probably plenty left to golf here.
] |
[Question]
[
Your challenge today is to implement a [t9](http://en.wikipedia.org/wiki/T9_(predictive_text))-like functionality.
You will implement a function that will only have 2 parameters.
You will receive 1 phone number in a string and the content of a text file with a list of words (don't assume a specific newline style).
You can use the link <https://raw.githubusercontent.com/eneko/data-repository/master/data/words.txt> to test the functionality, or use `/usr/share/dict/words` (check [A text file with a list of words [closed]](https://stackoverflow.com/questions/741003/a-text-file-with-a-list-of-words) for more information).
You can assume that you will always receive at least 2 numbers.
Given the number, you will read from a list of words and returns the words starting with the letters mapping to those words. This means that the input should be only numbers from 2 to 9.
You can do whatever you want if you receive invalid input.
If no match is found, you can return an empty list, `null`/`nil` or `0`.
Remember that the cellphone keys are mapped to their equivalent chars:
* 0 and 1 are invalid
* 2 matches [abc]
* 3 matched [def]
* 4 matches [ghi]
* 5 matches [jkl]
* 6 matches [mno]
* 7 matches [pqrs]
* 8 matches [tuv]
* and 9 matches [wxyz]
Examples:
```
f('52726')
//returns ["Japan","japan","Japanee","Japanese","Japanesque"...,"larbowlines"]
f('552')
//returns ["Kjeldahl","kjeldahlization","kjeldahlize"...,"Lleu","Llew"]
f('1234')
//makes demons fly out your nose or divide by 0
f('9999')
//returns ["Zyzzogeton"]
f('999999')
//returns [] or null/nil or 0
```
After you run your function, you can print it in any way you wish.
Rules:
* Standard loopholes are INVALID
* You must return something, even if it is `null`/`nil`
Javascript will return `undefined` if you don't return something, therefore this rule.
* You cannot use or re-implement other's answers or copy my implementation.
* You can assume, for Javascript, that the browser will be already opened and that the `innerText`/`textContent` of the automatic element will be passed as the 2nd parameter
* For compiled languages, you cannot pass special arguments to the compiler
* You can receive the file name over compiler arguments
* Variables, macros, global variables, constants, non-standard classes and all the sort passing other values inside the function will be considered invalid.
* In Javascript, variables without the keyword `var` render your code invalid
* Your function will be named `f`
* You can only and only have 2 arguments on your function
* Try to keep your code under 500 seconds to run.
* You don't have to worry about whitespace
* You must use only [ASCII](http://en.wikipedia.org/wiki/ASCII) printable characters.
Exceptions are languages that **only** use non-printable characters (APL and whitespace are 2 examples).
Scoring:
* **Lowest number of bytes win**
* Having invalid [ASCII](http://en.wikipedia.org/wiki/ASCII) printable characters in your answer, will count as the answer being encoded in [UTF-32](http://en.wikipedia.org/wiki/UTF-32)
The exception to the encoding will make your answer be count by **characters**.
* Only the function body counts, don't count anything else you do outside it
* Bonus of -30% if you make a prediction system based on the neighborhood or most common words
* Bonus of -20% in size if you only return the first 5 matches for each letter corresponding to the first number (e.g.: 245 would returns 5 words starting with 'a', 5 starting with 'b' and 5 starting with 'c').
Here is an example of an implementation, using Javascript:
```
function f(phone, words)
{
var keypad=['','','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz'];
var regex='';
for(var i=0,l=phone.length;i<l;i++)
{
regex+='['+keypad[phone[i]]+']';
}
var regexp=new RegExp('\\s('+regex+'[a-z]*)\\s','gi');
return words.match(regexp);
}
```
To run it, open the list link and run, for example:
```
f('9999',document.getElementsByTagName('pre')[0].innerText);
//returns [" Zyzzogeton "]
```
This example was tested and works under Opera 12.17 64bits on Windows 7 Home Edition 64bits.
[Answer]
# CJam, 28 bytes
```
q~{el{'h-_9/-D+3/}%s1$#!},p;
```
Takes input in the form of `"<number>" [<list of words>]`
Example:
```
"52726" ["Japan" "japan" "Japanee" "Japanese" "Japanesque" "larbowlines" "ablution" "ablutionary" "abluvion" "ably" "abmho" "Abnaki" "abnegate"]
```
Output:
```
["Japan" "japan" "Japanee" "Japanese" "Japanesque" "larbowlines"]
```
Not going for any bonus for now.
[Try the code online here](http://cjam.aditsu.net/) but for actual time measurements, run it on the [Java compiler](http://sourceforge.net/projects/cjam/)
*Note that CJam represents empty lists like `""`*
To convert the raw wordlist into CJam list use the following code with the wordlist as input:
```
qN/p
```
[Answer]
# Java: 395
This forms a regex pattern based on the letters that are allowed for each number, and then tacks on a .\* at the end to match any following characters.
Here is the golfed version:
```
static ArrayList<String> f(String n,ArrayList<String> d){String[] k={"","","([A-Ca-c])","([D-Fd-f])","([G-Ig-i])","([J-Lj-l])","([M-Om-o])","([P-Sp-s])","([T-Vt-v])","([W-Zw-z])"};String r="";for(int i=0;i<n.length();++i)r+=k[n.charAt(i)-'0'];r += ".*";Pattern p=Pattern.compile(r);ArrayList<String> a=new ArrayList<String>();for(String w:dictionary)if(p.matcher(w).matches())a.add(w);return a;}
```
And here is the ungolfed version for read-ability
```
public static ArrayList<String> f(String phoneNumber, ArrayList<String> dictionary) {
String[] KEY_VALUES = {"", "", "([A-Ca-c])", "([D-Fd-f])", "([G-Ig-i])",
"([J-Lj-l])", "([M-Om-o])", "([P-Sp-s])",
"([T-Vt-v])", "([W-Zw-z])"};
String regex = "";
for (int i = 0; i < phoneNumber.length(); ++i) {
regex += KEY_VALUES[phoneNumber.charAt(i) - '0'];
}
regex += ".*";
Pattern p = Pattern.compile(regex);
ArrayList<String> answers = new ArrayList<String>();
for (String word : dictionary) {
if (p.matcher(word).matches()) {
answers.add(word);
}
}
return answers;
}
```
[Answer]
# C# .NET 4.5 235
This should work:
```
IEnumerable<string>F(string n,string d){IEnumerable<string>w=d.Split(null).ToList();string[]a={"","","abc","def","ghi", "jkl","mno","pqrs","tuv","wxyz"};foreach(var i in n){w=w.Where(x=>x.IndexOfAny(a[i-'0'].ToArray())>0);}return w;}
```
[Answer]
# Python 2 (155 bytes)
Should also work in Python 3 with the appropriate replacements (`string`->`bytes`, `b` prefix on strings, etc.).
I wasn't sure if having the `maketrans` call outside the function is considered "fair"; if not, the function is 134 bytes with it moved inside.
**EDIT:** Dropped one byte from a stupid oversight.
With prepared `maketrans`, 67 bytes:
```
from string import maketrans
t=maketrans('abcdefghijklmnopqrstuvwxyz','22233344455566677778889999')
def f(n,w):
return[x for x in w.split()if x.lower().translate(t).startswith(n)]
```
With `maketrans` in body, 134 bytes:
```
from string import maketrans
def f(n,w):
return[x for x in w.split()if x.lower().translate(maketrans('abcdefghijklmnopqrstuvwxyz','22233344455566677778889999')).startswith(n)]
```
With `import` and `maketrans` in body, 155 bytes:
```
def f(n,w):
return[x for x in w.split()if x.lower().translate(__import__('string').maketrans('abcdefghijklmnopqrstuvwxyz','22233344455566677778889999')).startswith(n)]
```
Test call:
```
print f('9999',open('words.txt','rt').read())
```
[Answer]
# PHP 5.4+ (~~171~~ 186-20% = 148.8 bytes):
Well, this is quite a huge answer, but well.
I hope this brings more people to answer.
This function expects the **raw** content being read.
Here is the code:
```
function f($_,$a){$s=[2=>abc,def,ghi,jkl,mno,pqrs,tuv,wxyz];$a=preg_split('@\r\n|\r|\n@',$a);for($i=0;$c=$_[$i];++$i)foreach($a as$k=>$v)if(!strpos(1..$s[$c],$v[$i])||$t[$v[0]]++>4)unset($a[$k]);return$a;}
```
This works by verifying that the letter is in the list of allowed letters.
Example: the input `36` would make to check if `1abc` has the first letter of the word and that `1def` has the 2nd letter.
I append `1` so it doesn't check if the letter is in the 1st position (which would return `0` and that would evaluate to `false`). `if(!strpos(1..$s[$c],$v[$i]))` or `if(!strpos($c.$s[$c],$v[$i]))` will have the same effect, but the 1st confuses more and I like it.
Failing to do so, will remove the word.
With no words left, it returns an empty array.
To test this online, go to <http://writecodeonline.com/php/> and create a simple variable with a word for line.
A testable example:
```
function f($_,$a)
{
$s=array(2=>abc,def,ghi,jkl,mno,pqrs,tuv,wxyz);
$a=preg_split('@\r\n|\r|\n@',$a);
for($i=0;$c=$_[$i];++$i)
foreach($a as$k=>$v)
if(!strpos(1..$s[$c],$v[$i]) || $t[$v[0]]++>4)
unset($a[$k]);
return$a;
}
$lines=<<<WORDS
one
two
three
four
five
six
seven
eight
nine
ten
WORDS;
var_dump(f('36',$lines));
```
This should output:
```
array(1) {
[3]=>
string(4) "four"
}
```
To work on older php versions, replace `$s=[2=>abc,def,ghi,jkl,mno,pqrs,tuv,wxyz];` by `$s=array(2=>abc,def,ghi,jkl,mno,pqrs,tuv,wxyz);`
---
For the 20% bonus:
To reduce the code I simply added `||$t[$v[0]]++>4`, which checks how many times the first letter was used.
In php, `$t` doesn't need to be defined, helping to reduce a big chunk of *37.2* bytes.
To see this effect, use the following variable as the 2nd argument:
```
$lines=<<<WORDS
one
two
three
four
five
six
seven
eight
nine
ten
twelve
time
tutor
test
truth
WORDS;
```
] |
[Question]
[
## Challenge
Find the smallest cover of bases (e.g., moduli) whose sets of quadratic residue can be tested via table-lookup to definitively determine whether or not a given non-negative integer *n* is a perfect square. The bases must all be less than or equal to the square root of the maximum value of *n*.
The answer with the smallest set of bases for a given category of *n* wins the challenge. (This means there may potentially be more than one winner.) The categories of *n* are:
```
Category Maximum allowed n Maximum allowed modulus/base
------------- -------------------- ----------------------------
8-bit values 255 15
16-bit values 65535 255
32-bit values 4294967295 65535
64-bit values 18446744073709551615 4294967295
```
In the event of a tie with two sets having equal cardinality, the tie will go to the set having the greater ability to detect non-squares earlier in the sequence.
In the event that no complete covers are found (which is entirely likely for the 32-bit and 64-bit categories), the winner will be the set of bases which statistically or provably rules out the highest percentage of non-squares (without incorrectly reporting squares as non-squares). See below for a discussion of incomplete covers.
## Background
In many number theory applications, the question arises whether or not some number *n* is a perfect square (0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, etc.). One way to test whether *n* is square is to test whether floor(√n)² = n, that is, whether the rounded-down square root of *n*, when squared, gives back *n*. For example, floor(√123)² = 11² = 121, which is not 123, so 123 is not square; but floor(√121)² = 11² = 121, so 121 is square. This method works fine for small numbers, especially when a hardware square-root operation is available. But for large numbers (hundreds or thousands of bits) it can be very slow.
Another way to test for squareness is to rule out non-squares using quadratic residue tables. For example, all squares in base 10 must have a final (ones-place) digit that is either 0, 1, 4, 5, 6, or 9. These values form the set of quadratic residue for base 10. So if a base-10 number ends in 0, 1, 4, 5, 6, or 9, you know that it *might* be square, and further examination will be required. But if a base-10 number ends in 2, 3, 7, or 8, then you can be *certain* that it is *not* square.
So let's look at another base. All squares in base 8 must end in 0, 1, or 4, which conveniently is only 3 of 8 possibilities, meaning a 37.5% chance of a random number being possibly square, or 62.5% chance of a random number definitely not being square. Those are much better odds than what base 10 gives. (And note that a base-8 modulus operation is simply a logical-and operation, as opposed to base-10 modulus, which is a division by 10 with remainder.)
Are there even better bases? Well, yes, actually. Base 120 has 18 possibilities (0, 1, 4, 9, 16, 24, 25, 36, 40, 49, 60, 64, 76, 81, 84, 96, 100, and 105), which represents only a 15% chance of possibly being square. And base 240 is better yet, with only 24 possibilities, representing only 10% chance of possibly being square.
But no single base alone can definitively determine squareness (unless it is larger than the maximum number being tested, which is eminently impractical). A single base alone can only *rule out* squareness; it cannot conclusively *verify* squareness. Only a carefully selected set of bases, working together, can conclusively verify squareness over a range of integers.
So, the question becomes: What set of bases forms a minimal cover which together permit the definitive deduction of squareness or non-squareness?
## Example of a correct but non-minimal cover
The cover 16-base cover { 3, 4, 5, 7, 8, 9, 11, 13, 16, 17, 19, 23, 25, 29, 31, 37 } is sufficient to definitively determine squareness or non-squareness of *all* 16-bit values 0 to 65535. But it is not a *minimal* cover, because at least one 15-base cover exists that is also easily discoverable. In fact, it is likely that far smaller covers exist — perhaps with as few as 6 or 7 bases.
But for illustration, let's take a look at testing a sample value of *n* using this 16-base cover set. Here are the sets of quadratic residues for the above set of bases:
```
Base m Quadratic residue table specific to base m
------ ----------------------------------------------------
3 {0,1}
4 {0,1}
5 {0,1,4}
7 {0,1,2,4}
8 {0,1,4}
9 {0,1,4,7}
11 {0,1,3,4,5,9}
13 {0,1,3,4,9,10,12}
16 {0,1,4,9}
17 {0,1,2,4,8,9,13,15,16}
19 {0,1,4,5,6,7,9,11,16,17}
23 {0,1,2,3,4,6,8,9,12,13,16,18}
25 {0,1,4,6,9,11,14,16,19,21,24}
29 {0,1,4,5,6,7,9,13,16,20,22,23,24,25,28}
31 {0,1,2,4,5,7,8,9,10,14,16,18,19,20,25,28}
37 {0,1,3,4,7,9,10,11,12,16,21,25,26,27,28,30,33,34,36}
```
Now let's test the number *n* = 50401 using this set of bases, by converting it into each base. (This is not the most efficient way examine residue, but it is sufficient for explanatory purposes.) It's the 1's place that we're interested in here (marked below in parentheses):
```
Base "Digits" in base m
m m^9 m^8 m^7 m^6 m^5 m^4 m^3 m^2 m^1 ( m^0 )
---- -----------------------------------------------------------------
3 2 1 2 0 0 1 0 2 0 ( 1 ) ✓
4 3 0 1 0 3 2 0 ( 1 ) ✓
5 3 1 0 3 1 0 ( 1 ) ✓
7 2 6 6 6 4 ( 1 ) ✓
8 1 4 2 3 4 ( 1 ) ✓
9 7 6 1 2 ( 1 ) ✓
11 3 4 9 5 ( 10 )
13 1 9 12 3 ( 0 ) ✓
16 12 4 14 ( 1 ) ✓
17 10 4 6 ( 13 ) ✓
19 7 6 11 ( 13 )
23 4 3 6 ( 8 ) ✓
25 3 5 16 ( 1 ) ✓
29 2 1 26 ( 28 ) ✓
31 1 21 13 ( 26 )
37 36 30 ( 7 ) ✓
```
So we can see that in 13 of these bases, the residue matches a known quadratic residue (call this a "hit" in the table), and in 3 of these bases, the residue does not match a known quadratic residue (call this a "miss"). All it takes is 1 miss to know that a number is non-square, so we could stop at 11, but for illustrative purposes, we've examined all 16 of the bases here.
## Example of an incomplete cover
Technically, an incomplete cover is not a cover, but that's beside the point. The set of bases { 7, 8, 11, 15 } *nearly* covers all the 8-bit values of *n* from 0 to 255 correctly, but not quite. In particular, it incorrectly identifies 60 and 240 as being square (these are false positives) — but it does correctly identify all of the actual squares (0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, and 225) and makes no other false positives. So this is a 4-set which almost succeeds as a solution, but ultimately fails, because an incomplete cover is not a valid solution.
For 8-bit *n*, the set of bases { 7, 8, 11, 15 } is one of two sets of 4 bases which produce two errors, and there are seven sets of 4 bases which only produce one error. No sets of 4 bases actually exist which form a complete and accurate cover of 8-bit values. Can you find a set of 5 bases which produce no errors, covering all 8-bit values correctly? Or do you need 6 or more? (I do know the answer for 8-bit *n*, but I'm not going to give it away. I do not know the answer for 16-bit, 32-bit, or 64-bit, and I believe even the 16-bit case is impossible to solve via brute-force searching. Solving the 32-bit and 64-bit cases will certainly require genetic, heuristic, or other search techniques.)
## A comment on cryptographically large numbers
Beyond 64-bit numbers — up in the hundreds or thousands of binary digits — this is where a quick squareness check really comes in most handy, even if the cover is incomplete (which it most certainly will be for really large numbers). How could a test like this still be useful even if it is insufficiently decisive? Well, imagine you had an extremely fast test for squareness which worked correctly 99.9% of the time and gave false negatives the remaining 0.1% of the time and never gave false positives. With such a test, you would be able to determine non-squareness of a number nearly instantly, and then in the exceptional cases of indecisiveness, you could then resort to a slower method to resolve the unknown a different way. This would save you quite a bit of time.
For example, the set { 8, 11, 13, 15 } is correct 99.61% of the time for 8-bit values of *n* from 0 to 255, is correct 95.98% of the time for 16-bit values of *n* from 0 to 65535, and is correct 95.62% of the time for 24-bit values of *n* from 0 to 16777215. As *n* goes to infinity, the percentage of correctness for this set of bases goes down, but it asymptotically approaches and never drops below 95.5944% correctness.
So even this very tiny set of 4 small bases is useful to nearly immediately identify about 22 out of 23 arbitrarily large numbers as being non-squares — obviating the need for further inspection of those numbers by slower methods. The slower methods then need only be applied in the small percentage of cases which could not be ruled out by this quick test.
It is interesting to note that some 16-bit bases achieve better than 95% all on their own. In fact, each of the bases below is able to weed out better than 97% of all numbers up to infinity as not being square. The quadratic residue set for each of these bases can be represented as a packed-bit array using only 8192 bytes.
Here are the 10 most powerful single bases less than 2^16:
```
Rank Base Prime factorization Weeds out
---- ------------------------------ ---------
1. 65520 = 2^4 x 3^2 x 5 x 7 x 13 97.95%
2. 55440 = 2^4 x 3^2 x 5 x 7 x 11 97.92%
3. 50400 = 2^5 x 3^2 x 5^2 x 7 97.56%
4. 52416 = 2^6 x 3^2 x 7 x 13 97.44%
5. 61200 = 2^4 x 3^2 x 5^2 x 17 97.41%
6. 44352 = 2^6 x 3^2 x 7 x 11 97.40%
7. 63360 = 2^7 x 3^2 x 5 x 11 97.39%
8. 60480 = 2^6 x 3^3 x 5 x 7 97.38%
9. 63840 = 2^5 x 3 x 5 x 7 x 19 97.37%
10. 54720 = 2^6 x 3^2 x 5 x 19 97.37%
```
See anything interesting that these bases all have in common? There's no reason to think they might be useful in combination together (maybe they are, maybe they aren't), but there are some good clues here as to what bases are likely to be most influential for the larger categories of numbers.
**Side challenge:** One of the most influential bases (if not *the* most) up to 2^28 is 245044800, which alone can correctly weed out 99.67% of non-squares, or about 306 of 307 random numbers thrown at it. Can you find *the* most influential single base less than 2^32?
## Related
There are some very nice ideas in the following questions that are closely related, as well as several micro-optimization tricks for making certain operations faster. Although the linked questions do not specifically set out to find the strongest set of bases, the idea of strong bases is implicitly central some of the optimization techniques used there.
* [Fastest way to determine if an integer's square root is an integer](https://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer)
* [Detecting perfect squares faster than by extracting square root](https://math.stackexchange.com/questions/131330/detecting-perfect-squares-faster-than-by-extracting-square-root)
[Answer]
## Mathematica
I don't really know a lot about number theory (unfortunately), so this is a rather naive approach. I'm using a greedy algorithm which always adds the base that has the most misses for the remaining numbers.
```
bits = 8
Timing[
maxN = 2^bits - 1;
maxBase = 2^(bits/2) - 1;
bases = {
#,
Union[Mod[Range[0, Floor[#/2]]^2, #]]
} & /@ Range[3, maxBase];
bases = SortBy[bases, Length@#[[2]]/#[[1]] &];
numbers = {};
For[i = 0, i <= Quotient[maxN, bases[[1, 1]]], ++i,
AppendTo[numbers, # + i*bases[[1, 1]]] & /@ bases[[1, 2]]
];
While[numbers[[-1]] > maxN, numbers = Most@numbers];
numbers = Rest@numbers;
i = 0;
cover = {bases[[1, 1]]};
lcm = cover[[-1]];
Print@cover[[1]];
While[Length@numbers > maxBase,
++i;
bases = DeleteCases[bases, {b_, r_} /; b\[Divides]lcm];
(*bases=SortBy[bases,(Print[{#,c=Count[numbers,n_/;MemberQ[#[[2]],
Mod[n,#[[1]]]]]}];c)&];*)
bases = SortBy[
bases,
(
n = Cases[numbers, n_ /; n < LCM[#[[1]], lcm]];
Count[n, n_ /; MemberQ[#[[2]], Mod[n, #[[1]]]]]/Length@n
) &
];
{base, residues} = bases[[1]];
numbers = Cases[numbers, n_ /; MemberQ[residues, Mod[n, base]]];
AppendTo[cover, base];
lcm = LCM[lcm, base];
Print@base
];
cover
]
```
It solves 8 bits in no time with the following 6 bases:
```
{12, 13, 7, 11, 5, 8}
```
16 bits takes 6s and results in the following 6-base cover:
```
{240, 247, 253, 119, 225, 37}
```
For the larger cases this approach obviously runs out of memory.
To go beyond 16 bit, I'll need to figure out a way to check for a cover to be complete without actually keeping a list of all numbers up to Nmax (or go and learn about number theory).
**Edit:** Reduced runtime for 16 bits from 66s to 8s by prepopulating the list of numbers with only those which are not ruled out by the most effective base. This should also significantly improve the memory footprint.
**Edit:** I added two minor optimisations to reduce the search space. It's not one of the official categories, but with that I found an 8-base cover for 24 bits in 9.3 hours:
```
{4032, 3575, 4087, 3977, 437, 899, 1961, 799}
```
As for the optimisations, I am now skipping all bases which divide the LCM of the bases already in the cover, and when I test a base's efficiency I only test it against numbers up to the LCM of that new base and all the bases I already have.
] |
[Question]
[
Simply put, the Perrin sequence has the following recurrence relation:
>
> P(n) = P(n-2) + P(n-3);
>
>
> P(0) = 3; P(1) = 0; P(2) = 2;
>
>
>
But wait!! There's more!!
The Perrin sequence has a very bizarre property:
>
> If N is prime, then P(N) mod N = 0.
>
>
>
Furthermore, there are very few composite numbers which have this property. This can serve as a simple primality test which gives very few false positives.
There are 5761462 numbers under 100 million which satisfy this congruence. Out of those, 5761455 (99.9999%) are prime numbers.
Your mission is to compute those 7 numbers which pass the test but which are not prime. To be specific, your program must output these numbers in a reasonable format:
```
271441, 904631, 16532714, 24658561, 27422714, 27664033, 46672291
```
You can find more perrin pseudo primes (all of them up to 10^16) with factorization [here](http://www.wias-berlin.de/people/stephan/ppp1.out). For this challenge only the first 7 are important, since they are the only one smaller than 100 million.
(Your program must *compute* these numbers without having them pre-made, or accessing the internet, or similar stuff.)
Also, your program should not produce integer overflows. This may at first seem difficult because the 100 millionth Perrin number is really, really big. Algorithms do exist, however, which would not cause overflows.
This is code golf, shorter solutions are better.
[Answer]
# Ruby, 183
```
require'Prime'
f=->a{a=a.flat_map{|n|String===n ? n : n<3?%w[3 0 2][n]:[n-2,n-3]} until a.all?{|x|String===x}
a.map(&:to_i).inject :+}
n=1
p n if f[[n+=1]]%n==0&&!n.prime? while n<1e8
```
Technically works but runs in an unreasonable amount of time. Try setting the lower bound to 271435 and upper bound to 271450.
[Answer]
## PARI: 148
The [oeis webpage](http://oeis.org/A013998) on the Perrin number contains a PARI code written by Joerg Arndt that can easily be modified (a number & spacing) to fit the criteria
```
N=10^8;
default(primelimit, N);
M=[0,1,0;0,0,1;1,1,0];
a(n)=lift(trace(Mod(M,n)^n));
{for(n=1,N,if(isprime(n),next());if(a(n)==0,print1(n,",");););}
```
It takes quite a while, but it definitely works. I will work on translating this to Fortran for speed computation, but it definitely will not be small (especially if I put the prime test in the code & not as a `use <module>` declaration).
[Answer]
### GolfScript, 53 50 characters
```
10 8?,{3 0 2{@2$+3$%}4$2-*])!*},{.,2>{1$\%!},*},n*
```
Do not try to run this version - it'll take very long time to complete (if ever). The code creates a list of all candidates and then consists of two filter steps, first to select all assumed primes and then filter all non-primes from the remaining list. In order to see the code work you can try the following snippet:
```
30,{271430+}%
.p
{3 0 2{@2$+3$%}4$2-*])!*},
.p
{.,2>{1$\%!},*},
p
```
[Answer]
## Python (127)
```
a=i=3
b,c=0,2
while i<10**8:
c,b,a=a+b,c,b
j=2
if c%i==0:
while j*j<=i:
if i%j==0:print i;break
j+=1
i+=1
```
Unnecessary usage of memory avoided but the solution tends to be slow due to big integer operations. Primality testing is done with a slow algo.
[Answer]
## AutoHotkey 132
```
o:={-2:1,-1:-1,0:3}
loop % 10**8
{
p:=0
if !Mod(o[(l:=A_index)-2]+o[l-3],l)
loop % l
if !Mod(l,A_index)
p++
if p>2
s.=l ","
}
msgbox % s
```
Not possible as Integer limit is surpassed.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 22 bytes
```
↑7fo¬ṗtW¬z%Ntƒ(+d302Ẋ+
```
[(Don't bother to) Try it online!](https://tio.run/##AScA2P9odXNr///ihpE3Zm/CrOG5l3RXwqx6JU50xpIoK2QzMDLhuoor//8 "Husk – Try It Online"): as many other answers this is extremely slow, so you won't see anything in the 60s TIO allows. [Try this online instead!](https://tio.run/##yygtzv7//1HbRMO0/ENrHu6cnqttZG5oYmIQfmjNo7bJEHaVql/JsUka2inGBkYPd3Vp//8PAA "Husk – Try It Online") for a modified version that finds the first Perrin pseudoprime after 271440 (yes, it's 271441).
### Explanation
```
↑7fo¬ṗtW¬z%Ntƒ(+d302Ẋ+
ƒ(+d302Ẋ+ Recursive definition of the Perrin sequence:
d302 Start with the digits of 302
+ and append after them
Ẋ+ the pairwise sums
ƒ of the sequence itself
t Drop the first value (we like counting from 1 in Husk)
z%N Compute each value modulo its index
W¬ Find the indices of 0s
t Drop the fist one (0 mod 1 is 0, but for some reason
1 is not one of the required outputs)
f Keep only those values
o¬ that are not
ṗ primes
↑7 Take the first 7 results
```
[Answer]
# Haskell (169)
```
p=3:0:2:zipWith(+)p(tail p)
s(x:y)=x:s[a|a<-y,a`rem`x/=0]
s[]=[]
w=s$2:[3,5..10^8]
k(y,x)z|x`rem`y==0&&(y`notElem`w)=y:z|1<2=z
main=print.foldr k[]$zip[2..10^8].drop 2$p
```
`p` is an infite list producing the Perrin numbers, `s` is a simple sieve function, `w` contains all primes up to 10^8. `k` checks whether the pair `(y,x)` (where `y` is the Perrin number's index and `x` is the number itself) fulfils the condition and adds them to the list `z`. `main` folds `k` along the zip of the list `[2..10^8]` and the Perrin numbers (except for N=0 and N=1).
Don't run this program. It will generate the prime numbers first, which takes *very*, **very**, ***very*** long due to the inefficient sieve. Faster versions would use a wheel sieve and a binary search instead of the current linear search. Also, starting at around 10^5, garbage collection will eat up almost all productivity.
[Answer]
# Perl 68
```
use ntheory":all";forcomposites{say if is_perrin_pseudoprime($_)}1e8
```
Takes 66 seconds on my macbook with the latest version, 6 minutes with previous one (that had no prefilters -- basically a sped up version of Arndt's Pari code).
Of course this is cheesy by using a module that does all the work in C. 88 lines of C with prefilters for faster operation, 28 lines if removing the filters and an optimization to avoid mulmod for small inputs.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 bytes
```
Ø.’ịṖS;@
Ø.Ḥ3;Ç⁸¡ị@‘
Ẓ=Ç%$Ɗ8#Ḋ
```
[Try it online!](https://tio.run/##y0rNyan8///wDL1HDTMf7u5@uHNasLUDF5D/cMcSY@vD7Y8adxxaCJRweNQwg@vhrkm2h9tVVY51WSg/3NH1/z8A "Jelly – Try It Online")
Wildly inefficient, times out on TIO before printing anything.
## How it works
```
Ø.’ịṖS;@ - Helper link. Takes a list l on the left
- l is the list of previous Perrin numbers and the link appends the next Perrin number
Ø.’ - Yield [-1, 0]
Ṗ - Remove the last element of l
ị - Index into the cropped version of l
- This gives the second and third elements from the end of l
S - Take the sum of these two
;@ - Append to l
Ø.Ḥ3;Ç⁸¡ị@‘ - Helper link. Takes an integer k on the left
- This link takes an integer k and returns the kth Perrin number
Ø. - Yield [0, 1]
Ḥ - Double to [0, 2]
3; - Prepend 3
⁸¡ - Do the following k times, operating on the list [3, 0 2]:
Ç - Call the above helper link
‘ - Yield k+1
ị@ - Take the 1-indexed (k+1)th index of this list
Ẓ=Ç%$Ɗ8#Ḋ - Main link. Takes no arguments
Ɗ8# - Do the following over n = 0, 1, 2, ... until 8 values return True:
Ẓ - Is n prime?
$ - Group the previous two links and run over n:
Ç - Get the nth Perrin number
% - Modulo it by n
= - Are the two values equal?
- The two values will either be equal if:
- n is prime and P(n) mod n = 1 or
- n is composite and P(n) mod n = 0 or
- n = 1
- The first is never true, therefore this only returns True if n is composite and P(n) mod n = 0 or n = 1
- This returns [1, 271441, 904631, 16532714, 24658561, 27422714, 27664033, 46672291]
Ḋ - Remove 1 from this list
```
] |
[Question]
[
**The challenge**
You are given a function `compile(s: String): Integer` which returns `0` if `s` could be compiled and anything other than `0` if it failed (the resulting code is not important).
The thing is that you don't know for what language the function is made for, so it is up to you to figure that out by giving the function small snippets of code and observing what it returns. The good part is that a team of scientists have tried before you and have narrowed down the list to **C, C++, C#, Java and JavaScript** (these are the only widespread languages which have similar syntax I could think of).
**Rules**
* General code-golf rules apply.
* There is no strict output format; as long as it's readable and understandable it's ok.
* If these 5 languages are not enough for you then you can add your own favourites and you'll be rewarded with extra stars (★) (that do nothing).
Note1: the compiler is up to date with the latest standard of whatever language it's designed for.
Note2: I know JavaScript does not *compile*, but it goes though some parsing process; if it's valid JavaScript code then it passes
[Answer]
# Total snippet length 8; test program 83 (C)
Distinguish JavaScript and C from C++, Java, and C#
```
a;
```
Distinguish JavaScript from C
```
0
```
Distinguish C++ from C# and Java
```
#
```
Distinguish C# and Java
```
[:a]
```
C code to determine the language
```
#define C(x)compile(#x)?
main(){puts(C(a;)C(#)C([:a])"J":"C#":"C+":C(0)"C":"JS");}
```
Snippets tested with
C: gcc 4.7.2 with -std=c99
C++: g++ 4.7.2 with -std=c++11
Java: javac 1.7.0\_09
JavaScript: JavaScript-C 1.8.5
C#: Mono C# compiler version 2.10.8.0
] |
[Question]
[
From codegolf.com (not loading as of Sept 15, 2011) was one that was driving me crazy. Print to STDOUT a clock of an exacting form, reading time from STDIN and marking an `h` at the hour and `m` at minute (rounded down to a multiple of 5) and an `x` if they overlap, unused ticks are marked with an `o`, so that
```
echo "23:13" | perl script.pl
```
yields
```
o
h o
o m
o o
o o
o o
o
```
Mine is:
```
$/=':';($h,$m)=<>;printf'%9s
%5s%8s
%2s%14s
%s%16s
%2s%14s
%5s%8s
%9s',map{qw'o h m x'[2*($_==int$m/5)^$_==$h%12]}map{$_,11-$_}0..5
```
for 136 characters, using Perl. I wish I could get on the site, but I seem to recall that the leaders were under 100, also using Perl. Can someone else beat it?
[Answer]
## Golfscript, 75 bytes
Inspired by [the article linked in the comments](http://www.perlmonks.org/?node_id=811919).
```
':'/{~}/5/:m;12%:h;"XXXXXXXXXXXX"{..318\%9/' '*@12%.h=2*\m=+'omhx'=@85/n*}%
```
The `XXXXXXXXXXXX` part represents 12 bytes of data, some of them unprintable, and should be replaced with the byte sequence `120 47 253 22 194 9 183 44 196 55 125 246`.
For convenience, here is a base64 encoded version:
```
JzonL3t+fS81LzptOzEyJTpoOyJ4L/0Wwgm3LMQ3ffYiey4uMzE4XCU5LycgJypAMTIlLmg9Mipc
bT0rJ29taHgnPUA4NS9uKn0l
```
**Example run:**
```
$ echo -n "JzonL3t+fS81LzptOzEyJTpoOyJ4L/0Wwgm3LMQ3ffYiey4uMzE4XCU5LycgJypAMTIlLmg9MipcbT0rJ29taHgnPUA4NS9uKn0l" | base64 -d > saving-time.gs
$ ls -l saving-time.gs
-rw-r--r-- 1 ahammar ahammar 75 2012-01-29 17:31 saving-time.gs
$ ruby golfscript.rb saving-time.gs <<< "15:37"
o
o o
o o
o h
o o
m o
o
```
[Answer]
## C, 259 244 163 chars
Replaced command line argument with stdin (as required, also ends up shorter).
Removed support for minutes above 59 - a waste of 3 characters.
The code is shown with line breaks and indentation, but characters were counted without them.
```
main(i,h,m,x){
scanf("%d:%d",&h,&m);
for(i=0;i<12;
printf("%*c","IEHBNAPBNEHI"[i++]-64,"ohmx"[(x==h%12)+2*(x==m/5)]))
x=i%2?puts("\n"+(i%10==1)),11-i/2:i/2;
puts("");
}
```
Older attempt (using ANSI escape codes), 244 chars:
```
f(x,y)char*y;{printf("\033[%d%c",x>0?x:-x,y[x<0]);}
main(i,h,m,x){
char*v="HIJJJJIGFFFFPKJHFDCCDFHJ";
f(i=f(scanf("%d:%d",&h,&m),"J")*0,v);
for(;i<12;i++)
(x=v[i+12]-72)&&f(x,"CD"),
f(v[i]-72,"BA"),
putchar("omhx"[2*(i==h%12)+(i==m%60/5)]);
f(i,"B");
}
```
[Answer]
## Python, 175 chars
```
h,m=map(int,raw_input().split(':'))
S=([' ']*17+['\n'])*11
for i in range(12):p=1j**(i/3.);S[98+int(8.5*p.imag)-18*int(5*p.real)]='ohmx'[2*(i==m/5)+(i==h%12)]
print''.join(S),
```
Doesn't beat your Perl code, but maybe a more concise language with built in complex numbers (or trig functions) could use this idea to do better.
[Answer]
# Python, 226 chars
```
h,p,s=raw_input().split(':'),['o']*12,[0,11,1,10,2,9,3,8,4,7,5,6]
a,b=int(h[0])%12,int(h[1])/5
p[a],p[b]='h','m' if a!=b else 'x'
print '%9s\n%5s%8s\n\n %s%14s\n\n%s%16s\n\n %s%14s\n\n%5s%8s\n%9s'%tuple([p[i] for i in s])
```
Usage: run 'python script.py' then type the required time. (Ex: 09:45)
Output:
```
o
o o
o o
x o
o o
o o
o
```
[Answer]
My perl solution:
```
use POSIX;$/=':';@ss=(8,4,1,0,1,4,8);@sn=(0,7,13,15,13,7,0);$h=<stdin>;
$m=<stdin>;if($h>12){$h=$h-12;}$m=floor($m/5);
for($c=0;$c<7;$c++){for($s=0;$s<$ss[$c];$s++){printf(" ");}
$ac='o';if($h>5&&$h-6==6-$c){$ac='h';}if((($m>5)&&$m-6==6-$c)||($m==$c)&&($c==0)){
if($h>5&&$h-6==6-$c){$ac='x';}else{$ac='m';}}
print($ac);for($s=0;$s<$sn[$c];$s++){printf(" ");}$bc='o';if($h<6&&$h==$c){$bc='h';}
if($m<6&&$m==$c){if($h<6&&$h==$c){$bc='x';}else{$bc='m';}}
if($sn[$c]){print($bc);}printf("\n");if($c&&($c!=5)){printf("\n");}}
```
## 527 bytes
My C solution:
```
main(){int x[]={8,4,1,0,1,4,8},y[]={0,7,13,15,13,7,0}
,h,m,z,c,s;scanf("%d:%d",&h,&m);h>12?h-=12:h;m/=5;
for(c=0;c<7;c++){for(s=0;s<x[c];s++){printf(" ");}z='o';
if(h>5&h-6==6-c){z='h';}if((m>5&m-6==6-c)|(m==c)&!c){
z='m';if(h>5&h-6==6-c){z='x';}}printf("%c",z);
for(s=0;s<y[c];s++){printf(" ");}z='o';if(h<6&h==c){
z='h';}if(m<6&m==c){z='m';if(h<6&h==c){z='x';}}
if(y[c]){printf("%c",z);}printf("\n");if(c&&(c!=5)){printf("\n");}}}
```
440 bytes
[Answer]
## Scala 327 chars
```
object C extends App{
val R=List(2,4,6,8,10)
val r=1::R:::11::R.reverse
val C=List(3,6,12,18,21)
val c=1::C:::21::C.reverse
def p(n:Int,i:Char){
val z=r(n)
val s=c((n+3)%12)
printf("[%d;%dH"+i,z,s)}
val t=readLine.split(":")
val h=t(0).toInt%12
val m=t(1).toInt/5
(0 to 11).map(x=>p(x,'o'))
p(h,'h')
p(m,'m')
if(h==m)p(h,'x')}
```
### in use with a proper circle shape, not your lemon-XXXX:
```
clear && echo 5:43 | scala C
o
o o
o o
o o
m o
o h
o
```
### ungolfed:
```
object Clock {
val R = List (2,4,6,8,10)
val r = 1 :: R ::: 11 :: R.reverse
val C = List (3,6,12,18,21)
val c = 1 :: C ::: 22 :: C.reverse
def pos (n: Int, i: Char)={
val z = r (n)
val s = c ((n+3) % 12)
printf ("[%d;%dH" + i, z, s)
}
def main (args: Array [String]) {
val t = args (0).split (":")
val h = t (0).toInt % 12
val m = t (1).toInt / 5
(0 to 11).map (x=> pos (x, 'o'))
pos (h, 'h')
pos (m, 'm')
if (h == m) pos (h, 'x')
}
}
```
Uses Ansi-Code for output at pos(y,x). Since we only need 5 Minutes accuracy, precalculated values for x and y seem to be shorter than handling sin and cos functions with their import.
[Answer]
# Python, 176 characters
```
o=map(ord,' .@Set~lWC2&!/0ABTUfgu')
h,m=map(int,raw_input().split(':'))
print''.join([' ',['\n','ohmx'[2*(i==o[m/5])+(i==o[h%12])]][i in o[:12]]][i in o]for i in range(24,127))
```
[Answer]
**Perl 131 characters**
```
<>=~/:/;$h=$`%12;$m=$'/5;printf'%9s
%12$5s%8s
%11$2s%14s
%10$s%16s
%9$2s%14s
%8$5s%8s
%9s',map$_^$h?$_^$m?o:'m':$h^$m?h:x,0..11
```
] |
[Question]
[
*Inspired by [How do you write dates in Latin?](https://latin.stackexchange.com/questions/1943/how-do-you-write-dates-in-latin)*
## Challenge
Given a month-and-day date, output that date in abbreviated Latin, as explained below.
## Input
Input is flexible, following conventions from other [date](/questions/tagged/date "show questions tagged 'date'") and [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenges. You may choose to:
* Take a date in mm/dd or dd/mm format or two separate month,day arguments;
* Take a date in your language's date format;
* Take an integer in interval [0, 364] corresponding to a day in the year;
* Take some other reasonable input that can encode all 365 days of the year;
* Take no user input but output the current day's date;
* Take no input and output all 365 days of the year in order;
Importantly, you only need to care about the month and day, not about the year, and you can assume that the year is not a leap year.
## Output
Output is the date in abbreviated Latin, as specified in this section in BNF, and as explained more verbosely in the next section.
```
<output> ::= <delay> <event> <month>
<event> ::= "Kal" | "Non" | "Eid"
<month> ::= "Ian" | "Feb" | "Mar" | "Apr" | "Mai" | "Iun" | "Iul" | "Aug" | "Sep" | "Oct" | "Nov" | "Dec"
<delay> ::= "" | <one-day-delay> | <n-days-delay>
<one-day-delay> ::= "prid"
<n-day-delay> ::= "a d" <roman-numeral>
<roman-numeral> ::= "III" | "IV" | "V" | "VI" | "VII" | "VIII" | "IX" | "X" | "XI" | "XII" | "XIII" | "XIV" | "XV" | "XVI" | "XVII" | "XVIII" | "XIX"
```
## How do you write dates in abbreviated Latin?
*Adapted from [How do you write dates in Latin?](https://latin.stackexchange.com/questions/1943/how-do-you-write-dates-in-latin)*
There are 36 special days in the year.
* A date which is a special day is encoded by giving the name of that special day;
* A date which is just before a special day is encoded by writing `prid` followed by the name of that special day;
* Another day is encoded by writing `a d` followed by the number of days between that date and the next special day, **counting inclusively**, using Roman numerals, followed by the name of that special day.
Counting inclusively, there are for instance 3 days between January 3rd and January 5th.
The Roman counting system is oddly inclusive to modern taste. Whenever we would say that something is n days earlier, the Romans would have said n+1. The day just before the special day is two days before it (we'd say one day) and uses `prid` instead of numbering, so the unnamed days start their numbering at 3.
The 36 special days are:
* The Kalendae, first day of the month: `01/01, 02/01, ..., 12/01`, written `Kal <month>`, respectively: `Kal Ian`, `Kal Feb`, `Kal Mar`, `Kal Apr`, `Kal Mai`, `Kal Iun`, `Kal Iul`, `Kal Aug`, `Kal Sep`, `Kal Oct`, `Kal Nov`, `Kal Dec`;
* The Nonae, 5th or 7th day of the month: `01/05, 02/05, 03/07, 04/05, 05/07, 06/05, 07/07, 08/05, 09/05, 10/07, 11/05, 12/05`, written `Non <month>`, respectively: `Non Ian, Non Feb, Non Mar, Non Apr, Non Mai, Non Iun, Non Iul, Non Aug, Non Sep, Non Oct, Non Nov, Non Dec`;
* The Ides, 13th or 15th day of the month: `01/13, 02/13, 03/15, 04/13, 05/15, 06/13, 07/15, 08/13, 09/13, 10/15, 11/13, 12/13`, written `Eid <month>`, respectively: `Eid Ian, Eid Feb, Eid Mar, Eid Apr, Eid Mai, Eid Iun, Eid Iul, Eid Aug, Eid Sep, Eid Oct, Eid Nov, Eid Dec`.
Note the Nonae and Ides come two days later in the four months of March, May, July and October.
Because of these rules, only Roman numerals between 3 and 19 are required.
## Test cases
```
mm/dd --> abbrev. Lat.
01/01 --> Kal Ian
01/02 --> a d IV Non Ian
01/03 --> a d III Non Ian
01/04 --> prid Non Ian
01/05 --> Non Ian
02/02 --> a d IV Non Feb
02/27 --> a d III Kal Mar
02/28 --> prid Kal Mar
03/01 --> Kal Mar
03/02 --> a d VI Non Mar
04/02 --> a d IV Non Apr
05/02 --> a d VI Non Mai
06/02 --> a d IV Non Iun
07/02 --> a d VI Non Iul
08/02 --> a d IV Non Aug
08/05 --> Non Aug
09/02 --> a d IV Non Sep
10/02 --> a d VI Non Oct
10/15 --> Eid Oct
10/12 --> a d IV Eid Oct
10/13 --> a d III Eid Oct
10/14 --> prid Eid Oct
10/17 --> a d XVI Kal Nov
11/02 --> a d IV Non Nov
12/02 --> a d IV Non Dec
12/14 --> a d XIX Kal Ian
12/30 --> a d III Kal Ian
12/31 --> prid Kal Ian
```
## Rules
* This is code-golf, the shortest code in bytes wins!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 163 bytes
```
F³⁶⁵⊞υωF¹⁹F¹²F³§≔υ⁺⁺I§⪪”)¶O↥…⊞H₂;≦'⪫⦃π0S|”³κ∧λ⊗⁻×⁴λ∨№1358Iκ²ι⪫Φ⟦׋ι¹⁷a d§⪪”{⧴,π⁶δυW≦χVM⪫mSDfZ<hνHm¬⍘ψc⎇⊖MlR5ρν” ι§⪪KalNonEid³λ§⪪”>-b∧⊖αθ?|¬Y≔⁼IΦ«wS▷NAº⁸Fω&↗”³κ⟧μ υ
```
[Try it online!](https://tio.run/##ZVFdS8MwFH33V1z6lECFpmn3wZ7K5iDq5mAyCuJD1sYtmKUlbab/vibZFNTAOdybe@5HbqojN1XD1TC8NQYQHeUYNrY7IhvDB57dhFsyxXAx0qtBMRRdJw@66JmuxaeXb5TtUKA573r0Hdm2SvYoSghNMpKMU5KkhFIyomSapWme5nk6GXk/G0cxUBzDO3ZU6BqpGBaN3StRo5XUrvCzPIkOZTEop3gyaN5Y7WoTmk9cbmgbklPsTwzS4b6RGi2l6oVBL5cCj6LrkIyBjF084lBHvuHveUtWQrljjAX25AAl8/B@AJTgZEG1C4AdOIX3WyNrcENFEF0H@dPggat1o@9kfX21@i9Ziv2Km6I1Ky6Z1cyqwh62on2q@nVzXoiKcf2zs9cYTvjSz/3bxki3GYtnwzDcntUX "Charcoal – Try It Online") Link is to verbose version of code. Outputs all 365 days. Explanation:
```
F³⁶⁵⊞υω
```
Allocate an array of 365 days so that cyclic indexing will fill in some of the January values.
```
F¹⁹
```
Start from `a d XIX Kal Feb...a d XIX Kal Ian` and work forward to `Kal Feb...Kal Ian`.
```
F¹²
```
Loop from `Feb` to `Ian`. (This avoids a negative number below.)
```
F³
```
Loop over `Kal`, `Non` and `Eid`.
```
§≔υ⁺⁺I§⪪”...”³κ∧λ⊗⁻×⁴λ∨№1358Iκ²ι
```
Calculate the day of year that this day would be (if it existed).
```
⪫Φ⟦׋ι¹⁷a d§⪪”...” ι§⪪KalNonEid³λ§⪪”...”³κ⟧μ
```
Overwrite it with the name of this day, made up of four optional parts: `a d`, the day number (or `prid`), the special day, and the month, joined with a space (which is at the end of the above line).
```
υ
```
Output all of the days of the year.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 125 bytes
```
‚ÄúY8·πÅ`y∆à ãI∆䃆S·πñ·∏∂‚Åæƒ∞2‚Äô·πÉ‚ÄúXVI ‚Äù·∏≤‚Äúa d ‚Äù;‚±Æ‚Äú‚Äúprid‚Äù;
“-gBƥ]ṢḲ@’b6s2+“¢Ñ‘j€8FRUị¢ṭ€"“¡Qḟ8i,ȷıƊḳ릸sÑNpq>ė7 “¢Zıƒ>ɠ’ṃØas€3ŒtƊŒpṙ1¤Ẏ⁸ịṚ¹ƇK
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5xIi4c7GxMqj3Wc6vY81nVkQfDDndMe7tj2qHHfkQ1GjxpmPtzZDFQVEeap8Khh7sMdm4CcRIUUEMf60cZ1QB4QFRRlpoAEuIBs3XSnY0tjH@5cBFTrANSfZFZspA0UP7To8MRHDTOyHjWtsXALCn24u/vQooc71wK5SiDZhYEPd8y3yNQ5sf3IxmNdD3dsPjL90LLDO4oPT/QrKLQ7Mt1cAWxGFFB2kt3JBRCHHZ6RWAw0wPjopJJjXUcnFTzcOdPw0JKHu/oeNe4AWvBw56xDO4@1e/@3BupV0LUDO/pwO5exmSnQh4fbgVoj/wMA "Jelly – Try It Online")
A pair of links called as a monad, taking an integer from 0 to 364 and returning a string representing the relevant date. (Technically will also work for numbers outside that range since it uses a modular index into a list of all 365 possibilities.)
## Explanation
```
‚ÄúY8·πÅ`y∆à ãI∆䃆S·πñ·∏∂‚Åæƒ∞2‚Äô·πÉ‚ÄúXVI ‚Äù·∏≤‚Äúa d ‚Äù;‚±Æ‚Äú‚Äúprid‚Äù; # ‚Äé‚ŰHelper link: called as a nilad, generates the delay parts of the date
‚ÄúY8·πÅ`y∆à ãI∆䃆S·πñ·∏∂‚Åæƒ∞2‚Äô # ‚Äé‚Å¢Base 250 integer 84034955351979905312914389471555862301
ṃ“XVI ” # ‎⁣Base decompress into "XVI "
Ḳ # ‎⁤Split on spaces
“a d ”;Ɱ # ‎⁢⁡Prepend each with "a d "
““prid”; # ‎⁢⁢Prepend an empty string and then "prid"
‎⁢⁣
“-gBƥ]ṢḲ@’b6s2+“¢Ñ‘j€8FRUị¢ṭ€"“¡Qḟ8i,ȷıƊḳ릸sÑNpq>ė7 “¢Zıƒ>ɠ’ṃØas€3ŒtƊŒpṙ1¤Ẏ⁸ịṚ¹ƇK # ‎⁢⁤Main link: takes an integer and returns a string representing the date
“-gBƥ]ṢḲ@’ # ‎⁣⁡Base 250 integer 2833073888199044565
b6 # ‎⁣⁢Convert to base 6
s2 # ‎⁣⁣Split into pieces of length 2
+“¢Ñ‘ # ‎⁣⁤Add 1 to the first member of each sublist and 16 to the second
j€8 # ‎⁤⁡Join each with 8
F # ‎⁤⁢Flatten
R # ‎⁤⁣Ranges from 1..z for each z in this list
U # ‎⁤⁤Reverse each range
ị¢ # ‎⁢⁡⁡Index into the helper link
ṭ€" ¤ # ‎⁢⁡⁢Tag each member of each of the sublists of strings onto the corresponding sublist from the following:
“¡Qḟ8i,ȷıƊḳ릸sÑNpq>ė7 “¢Zıƒ>ɠ’ # ‎⁢⁡⁣Base 250 integers 302811639626768516702588802453858478870563499076533, 2309009953410
Ɗ # ‎⁢⁡⁤Following as a monad (used to avoid having to have ¤ after each of the nilads in the following)
ṃØa # ‎⁢⁢⁡- Base decompress into lowercase letters
s€3 # ‎⁢⁢⁢- Split each into pieces length 3
Œt # ‎⁢⁢⁣- Convert to title case
Œp # ‎⁢⁢⁤Cartesian product
ṙ1 # ‎⁢⁣⁡Rotate left one (moves Ian Kal to the end)
Ẏ # ‎⁢⁣⁢Join outer lists (after this step we have all 365 dates but with their component pieces in the wrong order and not yet joined with spaces)
⁸ị # ‎⁢⁣⁣Index the main link’s argument into this
Ṛ # ‎⁢⁣⁤Reverse
¹Ƈ # ‎⁢⁤⁡Keep only those that are non-empty (removes the space from before the exact special dates)
K # ‎⁢⁤⁢Join with spaces
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# JavaScript (ES6), ~~ 268 ... 262 ~~ 252 bytes
Expects `(month)(day)`.
```
m=>d=>([t=0,q=2384>>m&2^4,q+8,m-2?~-m%1.7^31:28].every(k=>(n=k+1-d)<0&&++t,A="KalNonEidIanFebMarAprMaiIunIulAugSepOctNovDecIanI II III IV V VI VII VIII IX ".match(/[IVX]* |.../g))|n?n-1?"a d "+(n>8?"X":"")+A[n%10+16]:"prid ":"")+A[t%3]+" "+A[m+=2^t>2]
```
[Try it online!](https://tio.run/##bZLdjppAFMfvfYqTSdSZHb4G3C7RAjHpNiHNbi@aGBMWGwpo7fLhApo03fYJmvSml@179Hn2BfoI9uBiFC3MkGF@/zlzvj4Fm6AMi@WqkrM8irdza5tadmTZ1KssTXqwdMMc2Hba02cD6YGbUirrzjc57QrlamaIoW76SryJi8/0Hs9k1j0XcsRear0e55U0tsibILnNs@tl5AbZ6/jDTVCMV8VNsHTXmbtOxuvFu3j1Nqxu882rOESNC249cE4AXxfHbuLGFIAoaVCFH6nquZOpfwGPiqKoC8YeMyeThUMCiIBwmtmmQ6ZkSAjjYy/rCo2LF/6QrIol8ma76ho@Jygfeym39Fll6/525HXwFk2omgCQZRsAAwD0i0h7oDegvgudxOja3Djm6PeZYNAIdt6c0cuGtoGu6lcndmvHMJ0HgXlst02NdjwHYLYvxHo8A6GpYg@weIAlOoCTDJzx0wycCVoZOKPHgU4nz4FifzQC/XB8J8C2aJUIBYb2n1S1BOI0VTXt@B1lnhfXATZYCZYNX1CexBV48F6CVIJIgnxdgQ8WlPtG1Bx6F3F2t180hqlywVRW31c/RYz2YE55yiiP2Ai3wzwr8yRWknxBS6VMlmFMNQkuGXAggCYILupz9W@9pjsj1s4DB/p///x4@vUTv30YQv/p9/c@Q7tf2Wj7Dw "JavaScript (Node.js) – Try It Online")
### Algorithm
The `every()` loop looks for the first 0-indexed special day that is greater than or equal to \$d-1\$.
Once completed:
* The number of days before the next special day is loaded in \$n\in[0\dots18]\$.
* The type of the special day is loaded in \$t\in[0\dots3]\$:
+ \$t=0\$ ‚Üí first day of the current month
+ \$t=1\$ ‚Üí Nonae
+ \$t=2\$ ‚Üí Ides
+ \$t=3\$ ‚Üí first day of the next month
### Formulas
* `q = 2384 >> m & 2 ^ 4` gives the 0-indexed day of the Nonae for month \$m\$ (either \$4\$ or \$6\$).
* `q + 8` gives the 0-indexed day of the Ides for month \$m\$ (either \$12\$ or \$14\$).
* `~-m % 1.7 ^ 31` gives the number of days in month \$m\$, except for February which is processed separately. I first used this decimal remainder trick in [one of my solutions](https://codegolf.stackexchange.com/a/195890/58563) to [this other challenge](https://codegolf.stackexchange.com/q/195884/58563).
### Lookup string
Most substrings are stored into a single lookup string:
```
"KalNonEidIanFebMarAprMaiIunIulAugSepOctNovDecIanI II III IV V VI VII VIII IX "
\_______/\_____________________________________/\____________________________/
special months Roman numeral suffixes
days (wrapping from Dec to Ian) (followed by a space)
```
which is split with the following regular expression:
```
/[IVX]* |.../g // either a Roman numeral suffix followed by a space
// or 3 characters
```
] |
[Question]
[
# Solve an Inglenook Sidings Puzzle
## Background
The [Inglenook Sidings Puzzle](https://en.wikipedia.org/wiki/Inglenook_Sidings) is a shunting/switching yard puzzle by Alan Wright for model railroading. The rules for the puzzle are as follows: ([Source](http://www.wymann.info/ShuntingPuzzles/Inglenook/inglenook-rules.html))
* Form a departing train consisting of 5 out of the 8 wagons sitting in the sidings.
* The 5 wagons are selected at random.
* The train must be made up of the 5 wagons in the order in which they are selected.
You have 4 sidings:
* The "main line", which is 5 cars long (labeled `B`)
* Two spurs coming off the main line, each of which is 3 cars long (`C` and `D`)
* A yard lead, which is 3 cars long. (`A`)
[](https://i.stack.imgur.com/m5aG3.jpg)
(Source: <http://www.wymann.info/ShuntingPuzzles/Inglenook/inglenook-trackplan.html>)
## The Challenge
Given the ordered list of cars in the train, generate the movements of the cars needed to form the train. *These moves need not be the shortest solution.*
### The sidings
* Each siding can be considered to be an ordered list of cars.
* Each car can be represented by one of eight unique symbols, with an additional symbol the engine.
* Cars can only be pulled and pushed as if it were coupled to an engine on the `A`-direction (i.e. you cannot access a car from the middle of a siding without needing to remove the head/tail ends first.)
* For this challenge, the starting state will be the same for all cases (where `E` is the engine, and digits are the 8 cars):
```
A E[ ] -- 12345 B
\-- 678 C
\- [ ] D
```
* **The puzzle is considered solved if all five cars in the `B`-siding are in the same order as the input car list.**
### Input
Input is an ordered list of five car tags representing the requested train.
The car tags should be a subset of any 8 unique elements, e.g. `{a b c d e f g h}` and `{1 two 3 4 five six 7 eight}` are allowed sets of car tags, but `{a b 3 3 e f g h}` is not allowed because not all elements are unique.
### Output
Output is a list of moves for the cars.
Examples of a single move can be:
```
B123A // source cars destination
BA123 // source destination cars
"Move from siding B cars 123 to siding A."
```
Among other formats. **The source, destination, and cars moved should be explicit, and explained in whatever move format you choose.**
If it is unambiguous that a cut of cars (a set of cars grouped together) moves unchanged from one siding to another, you can omit a step to the intermediate track, e.g. `1ba 1ad 2ba 2ad => 1bd 2bd`, e.g. `123ba 123ad 67ca 67ab 8ca 8ab => 123bd 67cb 8cb`, e.g. `5db 5ba => 5da`. All of these cases can be compacted due to a matching source-destination track, and the cut of cars moved doesn't change order. The test cases will use this compacted notation.
### Movement Rules
The cars move similarly to real-life railroad cars: you usually can only access one end of the cut at a time. So, the following moves are **illegal** (assuming a starting state similar to the one described above):
```
1ba 2ba 1ad // trying to access car 1 but car 2 is blocking access, since the last car on the cut is now 2: E12
12ba 21ad // swapping the order of cars without any intermediate steps to swap them
12345ba 12345ad // trying to fit too many cars into a siding (5 > 3 for sidings A and D)
```
### Additional Rules
* [Standard loopholes are forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default).
* [Input and output can be in any reasonable format.](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
### Test Cases
The moves in these testcases will be in the form `cars source destination`, separated by spaces. These are some possible solutions, and *not necessarily the shortest.*
```
Train -> Moves // comment
--------------
12345 -> // empty string, no moves needed
21345 -> 1bd 2bd 21db
14385 -> 123bd 67cb 8cb 867ba 67ac 4bc 8ab 123da 3ab 2ad 4ca 14ab
43521 -> 123ba 3ad 4ba 24ad 1ab 2db 215ba 5ad 21ab 5db 43db
86317 -> 67ca 7ad 8cd 6ac 8dc 1bd 23ba 3ad 45ba 5ac 3db 5cb 1db 4ac 7da 1bd 5bd 3bd 7ab 35db 1da 3bd 5bd 1ab 53da 3ab 25ad 4cd 86cb
```
### Tips
* All Inglenook Sidings Puzzles are solvable if and only if the inequality \$(h-1)+m\_1+m\_2+m\_3\ge w+M\$ is true, where \$h\$ is the capacity of the yard lead, \$m\_1, m\_2, m\_3\$ are the capacities of the sidings, \$w\$ is the number of wagons, and \$M = \max(h-1, m\_1, m\_2, m\_3)\$. For the initial state for the challenge, this is \$w = 8, h=m\_1=m\_2=3, m\_3=5\$. (<https://arxiv.org/abs/1810.07970>)
* You can only take and give cars from the end of the cut facing the switches, similarly to a stack.
* [A program to test your program output](https://tio.run/##nVVNj5swEL3zK0bpgaBlozUfSYSUSrvbHivl0BtCyICjWiVAsVNpVfW3pzMYSMjHtioSwbyZefM8niHNm/5WV/7xKPdN3WpQb8rql03TykoDV7DdDtihkloLpS3LKsQOGt4q8aX@KdR8T78RKN068PgRbH1oShGXUukYWRIXuqVB0cmF4SdJEjuyAK@OAjbmuVBNKfXc7siczr6TFS/RToRz6cCubkGCrExA/JQk1zQxS3omw9EKfWgrQ@VC3MmOo0cPBXZLXC0OTSPauTMgbERMSkLHrElfiaKmMsx1y/PvykRGQxGm27Uds9uct2leH7DCGyhFZZQ8JUamqg9tLvpN4B46sMDCo24t62qweMbyAbqzmo@cbs/gngcZarkb2TdgP/e1HwpXILPZRGy8kpjE9RC6J3i8J@1RMkZPo65povd4DI0olfirnOgi6F9yX@rFGkyKeVGIPvrM5Yxzgj4YlTfU3@Ywe3q4ZcVGykuuFHxF0MzUMG0Lgl65En3rUMMRnhLdXuDBK1HunFNyatNSVl2b4kQvlC5kdTKf9KGkX7PnWQRx4k7Mp2v2QmbmgueC70LgQnjf95V8ly6sXFjf9/rUJfw9MZsGJtGLFsdENjhuE4d@ZIfpPvv0UJBzg2zWhUQz18ROXbbbhfnAjT35YicXGS@HPbrakGEgo3PHZtPSdkFUxcYevmTn140vx7XTpVrHst43Xwv5vxpcmWlYblAZvylGTbnAjhat/vzjwMtzmvFMLAuHMU0rvhdp2k1imu65rNK0H8hxCAidO8cj8/wgpL8Fy2P9imUFeHSzIrNY4K8N6vmILVd5Bmu6l6uM4yvPIchyWPOMPAoOPq48XkCQc2ABz6zADz02MJAdbfj0Alwwci7wZiFCIaekCIUIBT5mXy99tqJYzMthhfZ1jiIw6brIjdCR0zDkgHEQokJGJPi@QlHkGeJNW1hhAp8yMFLbG7qso/yw04/Jlnn2Bw), input format is `final_state -> [cars_moved][source][destination]`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 120 bytes
```
⊞υ⪪”←‴⧴ν↘pG8¡¶”¶W¬⊙υ№κθ«≔υη≔⟦⟧υFηF⁴F…·¹L⁻§κλ F⎇λ¹…¹¦⁴¿¬‹№§κν μ⊞υ⊞OEκ⎇⁼πλ◨✂ξμχ¹Lξ⎇⁼πν⁺⮌…§κλμ✂ξ⁰±μ¹ξ⁺⁺…§κλμ§βλ§βν»✂⊟Φυ№ιθ⁴
```
[Try it online!](https://tio.run/##fVHda8IwEH9e/4qjTxfoYGrdBj6JbCCoK7q3dQ9ZjU1YTGuSOmXsb@@S1roPxgrJcdf7fdwl41RnBZV1nVSGYxXBqpTCYggAqer1B/EwVdc3t6lyhTCCMFUhIaPgjQvJABeFxbE6etykqJTF1wh2xH3wHlyMjRG58v@4Q3Tp03MElc83hQbkBJoYn@JUZbIyYs@WVOUMexHMmMotx7lQlcGxnao1O3gZSZwbCBuxBvrItKL6iDICBzvjY98gNq3XGTMGW6ffqNSJKoKtb@424eNDyTS1hcY5LX1rJ3K3q6g0WLY@ErpeipxbXEmRMTw4Imfiyh1yHuBAyF9wr524kXHJ9kwbhpNjJtmEF@XvYbee4CzgyBcsp5bhlngddzmFjqy5/mGKoCu9@NLPXPmdjoKPINFCdTMljuZeSMv012OL9rGbHY/quj/oxcP6ci8/AQ "Charcoal – Try It Online") Link is to verbose version of code. Very brute force (spends most of its time shuffling the first wagon between sidings `a` and `b`) so can only solve simple cases on TIO. All moves are always between siding `a` and another siding. Moves list the wagons in the order that they enter the other siding, which for wagons leaving siding `a` is the reverse of what you might expect. Explanation:
```
⊞υ⪪”←‴⧴ν↘pG8¡¶”¶
```
Start with the initial position.
```
W¬⊙υ№κθ«
```
Repeat until a sequence of moves resulting in the desired position is found. (The code actually checks all sidings but only siding `b` can actually have that position of course.)
```
≔υη
```
Save the previously found positions.
```
≔⟦⟧υ
```
Start a new list of found positions.
```
Fη
```
Loop over the previously found positions.
```
F⁴
```
Consider each possible source siding.
```
F…·¹L⁻§κλ
```
Consider all of the wagons in that siding.
```
F⎇λ¹…¹¦⁴
```
For siding `a`, consider the other three sidings as a possible destination, otherwise consider siding `a` as a possible destination.
```
¿¬‹№§κν μ
```
Check whether the destination has enough room for the number of wagons being moved.
```
⊞υ⊞OEκ⎇⁼πλ◨✂ξμχ¹Lξ⎇⁼πν⁺⮌…§κλμ✂ξ⁰±μ¹ξ⁺⁺…§κλμ§βλ§βν
```
Create an updated position with the wagons moved to the other siding, plus append the current move, and save that to the list of positions.
```
»✂⊟Φυ№ιθ⁴
```
Output the moves required to reach the desired position.
I've written a version which is somewhat faster but still only manages to solve `43521` because it cheats and ignores siding `c` if the input contains no digit above `5`. (The above version is so slow that even this optimisation doesn't help it.)
```
⊞υ⪪”←‴Fa×ι|”¶≔⮌υηW¬⊙η№κθ«≔ηζ≔⟦⟧ηFζF⁴¿∧λ∨⁻λ²›⌈θ5«≔⁺§κ⁰§κλεF…·⌈⟦⁰⁻Lε⎇⊖볦⁵⟧⌊⟦³Lε⟧«≔⊞OEκ⎇⁼ξλ✂εμχ¹⎇ξν✂ε⁰μ¹⁺μ§βλ먪№υ…δ⁴«⊞υ…δ⁴⊞ηδ»»»»✂⊟Φη№ιθ⁴
```
[Try it online!](https://tio.run/##XVLbToNAEH2Gr5jwNJusSa9q4lNTLzHx0qhvtg9Ix7JxWdoFaqvpt@MsK9hIQmAu58yZS5LGNsljXdezqkixkvC81qrEaG76g@FoPDenZ@dzE0lgTyTERTgpCrUy@ERbsgVhJSSk7P5MlSbAh7zEidljKmGaV6bEDwkbwQ98h8EvlGNfjGjN14VnCN5zC/gloPmOBKh3YK4lagmPFu@VqQr3P@CKN5biktgZ71RWZbhhXzSO2kIt9UwzZFLemiXtnJIepx2ZWrBNrrSvfWsSBqgtPcVmRR35a0@Cr35HZlWmSAx7IWtiu8dLSixlZEpioewfShgLsRANxMPZ1QEXrcJOIo/9cU02LnPXztrparmvNlWsC9w5pbwYrRJCkpBJ6LOk/pEKTjFHGT2f5MYhoRlC9tf4W9M4B5ZN54Ebs1ub3xdfwHSfaJqm@RqXEkbdTIOgPZH/CRd/0bSjPYTNewgP4cwqZvbqZoy6Vtotr7sR5W/Ec9X1aDge9OuTrf4B "Charcoal – Try It Online") Link is to verbose version of code.
The output of this version is not currently in a standard format, so I'll explain it here. Each line consists of a digit and a letter. The letter represents the other siding from or to which wagons are shunted to or from siding `a`. The digit represents the number of wagons that end up in siding `a`. Example:
```
/12345/678/ Initial position
3b: 123/45/678/ Fill a with 3 wagons from b
0d: /45/678/123 Move all wagons from a to d
2b: 45//678/123 Fill a with 2 wagons from b
3d: 451//678/23 Fill a with 1 wagon from d
2b: 45/1/678/23 Move 1 wagon from a to b
3d: 452/1/678/3 Fill a with 1 wagon from d
1b: 4/521/678/3 Move 2 wagons from a to b
2d: 43/521/678/ Fill a with 1 wagon from d
0b: /43521/678/ Move 2 wagons from a to b
```
[Answer]
# Python3, 1447 bytes:
```
R=range
E=enumerate
F=lambda s,e,m:s+''.join(map(str,m))+e
U=lambda x:eval(str(x))
def C(w,m,o,c,e):
if[]==c:yield w,m;return
for x in o:
for i,y in E(c):
if len(w[x][1])<w[x][0]:W=U(w);M=U(m);W[x][1]=([y if x!=1 else(y,)]+W[x][1]if x else W[x][1]+[y]);M+=[F(W[e][2],W[x][2],[y])];yield from C(W,M,o,c[:i]+c[i+1:],e)
def V(w,m,t,c):
if w[1][1][:len(j:=[i for i in w[1][1]if type(i)==tuple])]==j:
B=0
for W,M in C(w,m,{0,2,3}-{c},[i for[i]in j],1):
B=1
W,M=U(W),U(M);W[1][1]=W[1][1][len(j):];W[c][1]=(W[c][1][1:]if c else W[c][1][:-1]);M+=[F(W[c][2],'B',[t])];W[1][1]=[t]+W[1][1];yield W,M,1
if not B:
w[c][1].remove(t)
for W,M in C(w,m,{0,2,3}-{c},[t],c):yield W,M,0
def f(t):
w,m=[{0:3,1:[],2:'A'},{0:5,1:[*R(1,6)],2:'B'},{0:3,1:[6,7,8],2:'C'},{0:3,1:[],2:'D'}],[]
if w[1][1]==t:return m
T=t[:(r:=max(e)+1 if(e:=[i for i in R(5)if t[i]!=w[1][1][i]])else 5)]or t;W=w[1][1][:r]
w[1][1]=w[1][1][r:]
if(M:=W[:3][::-1]):w[3][1]+=M;m+=[F('B','D',M[::-1])]
if(M:=W[3:]):w[0][1]+=M;m+=[F('B','A',M[::-1])]
q=[(U(w),U(m),T)]
while q:
W,M,T=q.pop(0)
if[]==T:return M
if(O:=[i for i in[0,2,3]if W[i][1]and W[i][1][(0 if i else -1)]==T[-1]]):
for W,M,I in V(W,M,T[-1],O[0]):q+=[(W,M,T[:-1]if I else T)]
else:
if(O:=[i for i in [0,2,3]if T[-1]in W[i][1]]):
[c]=O;S=(W[c][1][:1]if c else W[c][1][-1:]);W[c][1]=(W[c][1][1:]if c else W[c][1][:-1])
for W,M in C(W,M,{0,1,2,3}-{c},S,c):q+=[(W,M,T)]
return m
```
Not the shortest solution, and can be golfed further, but produces output moves for all the test cases in 0.2 seconds. For input, it takes a list of the desired car order, and the output is a list with all the moves.
Move notation:
```
<source siding>[cars moved]<destination siding>
```
For example, `'B123D'` means "move cars 1, 2, and 3 from siding B to siding D.
[Try it online!](https://tio.run/##lVRNb@IwEL3zK9wT9maoElhaZNaH0m2lHlCllpaD5UM2mG0QSSCkBVTx29kZJynQrVZaCcnOmw/PezPDYlu8ZGmnt8j3@weVh@lv27hRNn1NbB4WtnGr5mHyaxKyFVhI5MprNs9nWZzyJFzwVZFDIoRnG0@120bat3BOFr4RojGxU3bN15BABhFYIRssnmqjVCS3sZ1PGJr6uS1e87TBplnONixOWYZu7iuGLX3f8IgiGcayuU35Wm@MDoz44S6@kWP1xNeiP8QjEf1xaVZcbylic6YCZucry7cgjFdZyeBQVgGe3hpM4Sl9y8faGt024Ex4ksn0y4qneZYgpzEMiZOWsfEiHXuBNMjPEX52hAuISrpsjdnpJ6n2mVQ6LskRtcqGXsV2YXkslCpeF3OL7yk1I9ID5Vdq4JMUUur57kMbOrvWe7SDMqGODVpnBoJSrIEK6MAolGUs4IkPSRv3nqpO7UoS0qAhKkWrLhoJYVVRrVEJylZwJFLkxGkOmqALEqhOjl9eda9EI7WoGsyYZgUbuALXZdLz3CbZm@WFIPDfRAtDqh5y@k7wKcZiRvRW@t2XHQikNtCWzavmDuNll4BvDzyAC@HwQYk7xwu4hJ5Dr49QB/xs7rD35riJ2B5ZzitLGmykCi15LlUSbrgVXoCe3J52@IF3BbUX23Om6lGIjRFO2K4w6Fj0xx8mmeOD9Ws1mEtXBR9K7JzsoJfrhFzrjptdNewnrinUDKwbhpXHUVhHugD/i4Crk4Cl0pz2CWibYETQ@iWeW7aktpHsI7U8X2QL7gvXU1roUS3L0EH8/kQF7ZpIAzVG7lhAmE7qq@Y@CRyXk9YKaPJHGmsx5RxXEwF3pOazWzxnhnvkIuQSaVQgEcBMd2UmV7i7Vv8dn2pih6JcPkSqiqqHGc6nuu8/HnZCBl/sRAs3RfzP/rjcJ3NO5eOcB4dJf6Q5P1AjKvXY7Rd5nBZ8yrXzh@/QNfhX@4G2Mc/faIBIB3qfUMK6mCU4QXtwgXgAl4ju/wA)
] |
[Question]
[
# Background
**Character classes** are a standard way to indicate a set of characters to match in regular expressions. For example, the class `[ab]` matches a or b, `[a-z]` matches any lower case letter, and `[^a]` matches everything but a. For the purpose of this question, classes can contain:
* a sequence of characters to match, where the characters `\`, `]`, `-` and `^` must normally be escaped with a `\`.
* a range of characters to match, indicated by separating two characters with a `-`: e.g. `[0-9]`. Note that if `-` is the first or last character in a class then it need not be escaped, as it's not indicating a range.
* a combination of sequences and ranges: e.g. `[ac-fhk-o]`. Note that the class cannot be empty, and if `]` is the first character in the class then it need not be escaped.
* a complement match indicated by the first character in the class being `^`: e.g. `[^a-z]`. Note that if `^` is not the first character in the class, then it need not be escaped.
# Task
Given a non-empty string made up of printable ASCII characters (" " to "~" = 0x20-0x7E), output the *shortest* character class that matches precisely those characters. The string may contain duplicate characters. [Default Input/Output methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins, with all the standard loopholes forbidden.
# Test cases
```
"the" => "[the]" or "[eht]" etc
"faced" => "[ac-f]" or "[c-fa]"
"0-121" => "[-0-2]" or "[012-]" etc
"]" => "[]]"
"[-^]" => "[][^-]" or "[]^[-]"
"[\]" => "[[-\]]" or "[]\\[]" or "[][\\]"
```
[Answer]
No answers after a few days, so thought I'd have a go. Found it trickier than expected, so the answer's pretty long, but I'm reasonably confident it works. Should be able to trim it a fair bit more.
# [Python 3.8](https://docs.python.org/3.8/), ~~431~~ ~~405~~ 410 bytes
```
import re,itertools as I
B,M,C,P="\-]^"
s=sorted;x=s({*input()})
d=[ord(x)-i for i,x in enumerate(x)];l=[];i=0
for _,g in I.groupby(d):n=len([*g]);l+=[[x[i]+M+x[i+n-1]],x[i:i+n]][n<4];i+=n
o="".join(s(l,key=lambda i:2*(M in i[::2])+(P in i)-3*(i[0]==M<C not in x)-2*(C in i)))
print("["+re.sub(".",lambda m:B*((x:=m.group())==B or x==P==o[0]or x==M<M*2==o[(i:=m.start()):i+2]in o[1:-1]or x==C in o[1:])+x,o)+C)
```
[Try it online!](https://tio.run/##LZA/b4MwEMV3PoXFZINB@dOhgtwSpgxI2V23guIQJ2BT27TQqp89NUkn351/eu/eDbM7a7V9HsztJvtBG4eMoNIJ47TuLKosOgR7WtKCHiF8SfhrGFiwnhNNPoHFP5FUw@gw@SVBA0ybBk8kkeikDZJ0QlIhocZemMoJ/8PzDhjPJayChXij7UIc0tbocahn3JBMQScUZlHLSd7FwNjEJI/L2D@xStacU19lvuacqd2TF4tBBRrCML1oqbDFHb2KGbqqr5sKyWwT4XJxkSzLNpzE@HjvSLKNsGQrDlDuCqS0W8Z@ec8XD4KQYDBSORyyMDYitWONwzSk/9J9to8wnjLoH/tjQgD2yOeaAI4A2os/mnJXRptlgOVCW1cZfzLiU2y4d9JsnflkD/buvUz8qhPVJC7I7WaHs1QT0idUd9X7FX2MXuGbosvYtAL1M/rUX38 "Python 3.8 (pre-release) – Try It Online")
# Explanation
The overall approach is to:
1. Split the letters into ranges of length at least 4 and individual characters. Note that ranges of length 3 are never necessary (eg. `"[abc]"` is the same length as `"[a-c]"` and `"[]\\[]"` is the same length `"[[-\]]"`) and are sometimes worse (e.g. `"]-./"` is shorter as `"[]./-]"` than as `"[]\--/]"` or `"[--/\]]"`).
2. Sort the letters and ranges, so `"]"` goes first, otherwise `"-"` goes first, otherwise `"-"` goes last, and with `"^"` as late as posssible. There is no conflict between putting `"]"` first and `"-"` last since `"]--"` is not a valid range.
3. Escape as necessary: `\` always, `]` unless it's first, `^` if it's first, and `-` if it's in the middle (which will only happen if it's the beginning of a range).
# Extra test cases
```
"-^" => "[-^]"
"-4]" => "[]4-]"
"abcde^" => "[a-e^]"
"XYZ[\\]" => "[X-\]]"
"-./0]" => "[]\--0]"
"+*,-^" => "[\^*--]"
"^_`a" => "[\^-a]"
```
] |
[Question]
[
### Definition
For any \$a\equiv1\ (\text{mod }8)\$ and \$n\ge3\$, there are exactly 4 roots to the equation \$x^2\equiv a\ (\text{mod }2^n)\$. Now, let \$x\_k(a)\$ be the smallest root to the equation \$x^2\equiv a\ (\text{mod }2^k)\$, then $$\{x\_3(a),x\_4(a),x\_5(a),x\_6(a),\cdots\}$$ is a smallest square root sequence (SSRS) of \$a\$ mod \$2^n\$.
[John D. Cook](https://www.johndcook.com/blog/quadratic_congruences/) published a quick algorithm that calculates such roots in \$O(n)\$ time. Assume \$x\_k\$ is a root to the equation \$x^2\equiv a\ (\text{mod }2^k)\$. Then, $$x\_{k+1}=\begin{cases}x\_k&\text{if }\frac{x\_k^2-a}{2^k}\text{ is even}\\x\_k+2^{k-1}&\text{otherwise}\end{cases}$$
is a root to the equation \$x^2\equiv a\ (\text{mod }2^{k+1})\$.
Now we define two lists A and B. \$A=\{A\_k|k\ge3\}\$ is the list of values generated by the algorithm above with initial values \$A\_3=1\$ and \$B=\{B\_k|k\ge3\}\$ is the list of values generated with initial values \$B\_3=3\$. Each entry in the SSRS \$x\_k(a)\$ takes the smallest value among \$A\_k\$ and \$B\_k\$. We say a switch in SSRS occurs whenever the choice changes from A to B or from B to A.
To illustrate the definition, take \$a=17\$:
[](https://i.stack.imgur.com/DTMtd.png)
The smallest numbers are highlighted. From the picture there are 13 switches up to mod \$2^{24}\$.
### Challenge
Write a function or program, that receives 2 integers \$a,\ k\$ as input (where \$a\equiv1\ (\text{mod }8)\$ and \$k\ge3\$) and output how many switches occur in the SSRS of \$a\$ mod \$2^n\$ up to \$n=k\$.
### Sample I/O
```
1, 3 -> 0
9, 4 -> 1
1, 8 -> 0
9, 16 -> 1
17, 24 -> 13
25, 32 -> 2
33, 40 -> 18
41, 48 -> 17
49, 56 -> 1
1048577, 2048 -> 959
1048585, 2048 -> 970
```
### Winning Condition
This is a code-golf challenge, so shortest valid submission of each language wins. Standard loopholes are forbidden by default.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 14 bytes
```
LoεLnαy%0k}üÊO
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fJ//cVp@8cxsrVQ2yaw/vOdzl//@/kQmXoTkA "05AB1E – Try It Online")
For each `n`, this finds the smallest square root of `a` by brute-force.
## [05AB1E](https://github.com/Adriandmen/05AB1E), ~~26~~ 23 bytes (fast)
```
13v¹yλ£DnIαN>o%2÷+]@γg<
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f0Ljs0M7Kc7sPLXbJ8zy30c8uX9Xo8HbtWIdzm9Nt/v83MjCx4DIEEqYWpgA "05AB1E – Try It Online")
This one properly uses Cook's formula.
```
13 # literal 13
v ] # for each digit:
¹ # push the input k
y ] # push the digit
λ£ # recurse k times with base case y:
Dn # square of the current value
Iα # absolute difference with input a
N>o% # modulo 2**(N+1)
2÷ # integer divide by 2
+ # add to the current value
@ # compare the two lists element-wise
γ # group consecutive equal elements
g # length
< # -1
```
[Answer]
# JavaScript (ES6), ~~88~~ 87 bytes
Takes input as `(a)(k)`.
Because of the bitwise operations, this is only guaranteed to work for \$k\le32\$.
```
a=>K=>(x=[p=1,3],F=k=>k<K&&(p^(x=x.map(v=>q=v+=(v*v-a>>k&1)<<k-1),p=x[0]<q))+F(k+1))(2)
```
[Try it online!](https://tio.run/##bY1LDoIwFAD3HoS8Z4FY8Jv0dcmGIxBMGgSjRVrENNy@dmvqdjKZeSqnlu79sJ9sMrfeD@QVyZokrNRY4mnZphVpklrUSQL2Gviav5QFR3Imxwjc1mVKSp1wFEJnHFNLa7NrxYzIKtCMI0KBvjPTYsY@H80dBuAIJeLmF14Q9hEM5vmfyY@xegqnuFAcwqxA9F8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes
```
≔⁰ζ⊞υ¹⊞υ³FX²…³N«UMυ⁺κ∧﹪÷⁻×κκηι²⊘ιF⌕υ⌊υ«≦⊕ζ≔⮌υυ»»Iζ
```
[Try it online!](https://tio.run/##TU/LasNADDx7v2KPMmyhcQo95BQSSnxwMKE/sPWq8ZJ9hH24kJJv38qJDxUMSBqNRhpGGQYvTSnbGPXZwavgt3rD@hxHyIKv/uVryr994ND7HwzQCH6S7oywFrx115yO2X5Rv6bgv6zq5HXnrZVOzeLe5AgXwbdUdl5l46F1aa8nrRA67Yj91BYfM5da8JGgCQ3hIM2ECvS8ecOqxw0f@rmXpNpmC3lxnW2XV1o3BLToEqrnU1W1MCecMEQkkeB5Ju7szvqgXYKdjAlu5FNK88ZX7@VlMn8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order \$ \small k, a \$. Explanation:
```
≔⁰ζ⊞υ¹⊞υ³
```
Start off with \$ \small 0 \$ swaps and initial values \$ \small A\_3 = 1 \$ and \$ \small B\_3 = 3 \$ in a list.
```
FX²…³N«
```
Loop over the powers of \$ \small 2^n \$ from \$ \small 2^3 \$ to \$ \small 2^{k-1} \$.
```
UMυ⁺κ∧﹪÷⁻×κκηι²⊘ι
```
Map over the list calculating the next values \$ \small A\_{n+1} \$ and \$ \small B\_{n+1} \$.
```
F⌕υ⌊υ«
```
Test whether the smallest value is at the start of the list.
```
≦⊕ζ≔⮌υυ
```
If it isn't then increment the number of swaps and reverse the list so that the smallest value is at the start again.
```
»»Iζ
```
Print the number of swaps.
I have a ~~48~~ 47 byte version that seems to work on the test cases but I don't know why.
```
≔⁰ζ≔¹δ≔⁰εFX²…³N«≔﹪÷⁻Xδ²ηι²θ≧⁺¬⁼θεζ≔θε≧⁺∧ε⊘ιδ»Iζ
```
[Try it online!](https://tio.run/##bY/BCsIwDIbP7ilyTKGCTsGDJ1FBDxvDN6i2boXabms7YeKz145NvBgI5E/4kj@3irU3w1QIO2tlqXFBoSfbZFJLCvyn4kxEdTctYGGeosWUwoXpUuCKwlnX3uX@cY19EgNeyWwCM8O9MnjW7iA7yQVmUns77eAUUkKhiinJWDfxyixj9YhfZFk5LJS3FHLj8Nh4piw2gxsy2v0eakaH/9md5igonJjqBEc5sMNz76RopXa4Z9ZhT8g2hHQNy02Yd@oD "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁰ζ≔¹δ≔⁰ε
```
Start off with \$ \small 0 \$ swaps, \$ \small A\_3 = 1 \$ and \$ \small A\_3 < B\_3 \$.
```
FX²…³N«
```
Loop over the powers of \$ \small 2^n \$ from \$ \small 2^3 \$ to \$ \small 2^{k-1} \$.
```
≔﹪÷⁻Xδ²ηι²θ
```
Work out whether \$ \small A\_{n+1} > B\_{n+1} \$.
```
≧⁺¬⁼θεζ
```
If this is a change from \$ \small A\_n > B\_n \$ then increment the number of swaps.
```
≔θε
```
Save this for the next loop.
```
≧⁺∧ε⊘ιδ
```
Add \$ \small 2^{n-1} \$ if \$ \small A\_{n+1} > B\_{n+1} \$.
```
»Iζ
```
Print the number of swaps.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~31~~ 29 bytes
```
²_⁴ọ2>
R1,3;€¹2*H+ʋ@ç?\€>/IAS
```
[Try it online!](https://tio.run/##y0rNyan8///QpvhHjVse7u41suMKMtQxtn7UtObQTiMtD@1T3Q6Hl9vHAPl2@p6Owf///zcyMLH4bwgkTC1MAQ "Jelly – Try It Online")
A full program taking \$n\$ as its left argument and \$k\$ as its right argument. Prints the number of switches.
Will post explanation once have more time to further optimise.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~230~~ \$\cdots\$ ~~180~~ 175 bytes
```
def f(x,a,k,p=4):
l=[x]
for n in range(3,k):x+=p*(((x*x-a)>>n)&1);p*=2;l+=[x]
return l
def g(a,n):
i=c=0
for q in zip(f(1,a,n),f(3,a,n)):j=q[1-i]<q[i];c+=j;i^=j
return c
```
[Try it online!](https://tio.run/##VZBLboMwEIb3nGLEorKTiYR5FAJ1lj1Bd4hKiJjUCXIcQiJaxNmpHaqWrjz/w99Y1p/dx1kF07QXNdSkxxJPqHlIUwcanveFA/W5BQVSQVuqgyABnmjar7leEUL6Vb8p6W6n6BOjmV5xP2vW87VWdLdWQeNY8oGUqCxT8op7M/NimV9Sk5owtDHWBm4Hmh75JWcbWbxccllk1ZofM/nOj7/UatJ8eGtvInXLq4vwWjZXM6tzB0aPjuXfUdgNxAFiFkBAETyKVm0RQqPYrEyW/MvY8yKMEfxHOZgNPzIo3xj@rIPAwDxbSGYjNLzQAln8YxhktER6YRLFlus9ettouwiS6C@IH2@y36ZbqTpSu8M994oRwZysGGGzg@FArIfWoCOQQeeC86VpeqLXourEnrp0@gY "Python 3 – Try It Online")
A function `g` that uses Cook's formula (function `f`).
] |
[Question]
[
# Crossing Sequences
Given a list of positive integers `A`, call it an *increasing sequence* if each element is greater than or equal to the previous one; and call it a *decreasing sequence* if each element is less than or equal to the previous one.
Some increasing sequences:
```
[1,2,4,7]
[3,4,4,5]
[2,2,2]
[]
```
Some decreasing sequences:
```
[7,4,2,1]
[5,4,4,3]
[2,2,2]
[]
```
A *crossing sequence* is a list that can be decomposed into two disjoint subsequences, one an increasing sequence and the other a decreasing sequence.
For example, the list:
```
[3,5,2,4,1]
```
is a crossing sequence, since it can be decomposed into:
```
[3, 4 ]
[ 5,2, 1]
```
where `[3,4]` is the increasing subsequence and `[5,2,1]` is the decreasing subsequence. We'll call such a pair of (increasing,decreasing) subsequences a *decomposition* of the crossing sequence.
The list:
```
[4,5,2,1,3]
```
is not a crossing sequence; there is no way to decompose it into an increasing and decreasing subsequence.
Your task is to write a program/function taking as input a list of positive integers; and if it is a crossing sequence, return the two lists in one of its decompositions; or some consistent "falsey" value if the list is not a crossing sequence.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest program/function in each language is the winner.
## Rules:
* Input is flexible.
* The usual loopholes are forbidden.
* If there are multiple valid ways to decompose the input, you may output one or all of them.
* Output formatting for the decomposition is flexible; but it must be unambiguous regarding the distinction between the two subsequences.
* You may use any consistent output value to indicate that the input is not a crossing sequence; so long as it is unambiguous compared to the output for any crossing sequence. You should specify the falsey value in your answer.
## Test Cases:
Using `False` to indicate non-crossing sequences:
```
[3, 5, 2, 4, 1] => [3, 4], [5, 2, 1]
[3, 5, 2, 4, 4, 1, 1] => [3, 4, 4], [5, 2, 1, 1]
[7, 9, 8, 8, 6, 11] => [7, 8, 8, 11], [9, 6]
[7, 9, 8, 8, 6, 11] => [7, 9, 11], [8, 8, 6] # also valid
[7, 9, 8, 8, 6, 11] => [7, 8, 11], [9, 8, 6] # also valid
[7, 8, 9, 10, 20, 30] => [7, 8, 9, 20, 30], [10]
[7, 8, 9, 10, 20, 30] => [8, 9, 10, 20, 30], [7] # this is also valid
[5, 5, 5] => [5, 5, 5], []
[4, 5, 2, 1, 3] => False
[3, 4, 3, 4, 5, 2, 4] => False
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes
```
;Ṣzpᵐz{ℕˢ}ᵐ≤₁ʰ≥₁ᵗ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuaaRx3LldISc4pT9ZRqH@7qrH24dcJ/64c7F1UVAFlV1Y9app5eBBJ81LnkUVPjqQ2POpcC6Ydbp///H60QbayjYKqjYKSjYKKjYBirE22uo2Cpo2ABRmZAIaiYBVjY0ACoFIiNDYCipmCdpkCWCcwMQ6AUkG8MNg1CQg2PVYgFAA "Brachylog – Try It Online")
There's probably considerable room to golf this.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ ~~14~~ 13 bytes
```
2.Œ.ΔćRšεü@}W
```
[Try it online](https://tio.run/##ASwA0/9vc2FiaWX//zIuxZIuzpTEh1LFoc61w7xAfVf//1szLCA1LCAyLCA0LCAxXQ "05AB1E – Try It Online") or [validate all test cases](https://tio.run/##yy9OTMpM/W/m5mKvpKCra6egZP/fSO/oJL1zU460Bx1deG7r4T0OteH/a3X@RxvrKJjqKBjpKJjoKBjGckWb6yhY6ihYgJEZUAgqZgEWNjQAKgViYwOgqClYpymQZQIzwxAoBeQbg02DkFDDYwE).
Explanation:
```
2.Œ # all partitions of the input in 2 subsequences
.Δ # find the first partition such that the following gives 1
ćRš # reverse the first subsequence
ε } # map each subsequence to
ü@ # pairwise greater-than
W # minimum (1 if all 1s, 0 otherwise)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ŒPżṚ$ṢNÞƭ€ƑƇ
```
[Try it online!](https://tio.run/##y0rNyan8///opICjex7unKXycOciv8Pzjq191LTm2MRj7f8Ptx@d9HDnjP//o811FCx1FCzAyExHwdAwFgA "Jelly – Try It Online")
[Answer]
# JavaScript (ES6), ~~110 105~~ 104 bytes
Returns either `[[decreasing], [increasing]]` or \$1\$ if there's no solution.
```
f=(a,n,b=[[],[]])=>a.some((v,i)=>[...x=b[i=n>>i&1]].pop()*(x.push(v),i-=!i)>v*i)?n>>a.length||f(a,-~n):b
```
[Try it online!](https://tio.run/##fY/BTsMwEETvfIW5ELvaWA1paKnk8BkcjA9OSZqtgh0RJ@qh4tfDNhSpiIBkW1rP08zswQ62271jG2LnX8txrBS34KBQWhvQxgiVW9n5t5LzAZAmLaU8qkKjcnmOd4kxsvUtFwt@lG3f1XwQgLG6RZEPCxRPRFnZlG4f6tOpIvP4w4ltMe6863xTysbvefSMoWaW0Ucf0LttJG6u9YrrFFgG7B7YClhixC99DewR2GY6D4T8wWwmLFmSFd10OUNlU1I2o1x3ONe4NPmBRS/uvIzvw//7rL69yCWdzyLk672EEjV@Ag "JavaScript (Node.js) – Try It Online")
## How?
We try all values of a bitmask \$n\$ between \$0\$ and \$2^L\$, where \$L\$ is the length of the input array.
At each iteration, we split the original array into two subsequences \$b[0]\$ (decreasing) and \$b[1]\$ (increasing), using each bit \$i\$ of \$n\$ to know where each value goes.
When a new value is added to a subsequence, we simultaneously make sure that it's not invalid by comparing it with the last value, popped from a copy of the subsequence. The direction of the inequality is always the same, but the operands are multiplied by either \$1\$ (if \$i=1\$) or \$-1\$ (if \$i=0\$):
```
[...x = b[i = n >> i & 1]].pop() * (x.push(v), i -= !i) > v * i
```
We stop and return \$b\$ as soon as all values are passing, i.e. `some()` is falsy.
[Answer]
## Haskell, 84 bytes
```
(([],[])#)
(d,i)#(a:b)=(#b)=<<[(d++[a],i)|all(a<=)d]++[(d,i++[a])|all(a>=)i]
p#_=[p]
```
Returns a list of all valid `(decreasing,increasing)` pairs or the empty list if there's no such pair.
[Try it online!](https://tio.run/##ZY65DsIwEER7f8UKU9jKIoX7UMwX0FGaFTKYQIQJVhI6vh1jrgIodop5M5o9mPq4cy7kahWE0ISaJJdMWCwkF2a2kUrwKFmmhU0SbSiCq3FOmExJS9F6ZJ/k7c@VLIh5vlbaUziZogQF9swAfFWUDbQhB91HGCL0EAYIXfpmI4TRjzVGmCBMYzaNrXj9lNgjcmmWTbUoodVi343BZ6Abw/Q3HvFL319QuG1zZ/Z16Gy9vwM "Haskell – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~109~~ 107 bytes
```
def f(l,i=[],d=[]):
if l:s,*r=l;i and s<i[-1]or f(r,i+[s],d);d and s>d[-1]or f(r,i,d+[s])
else:print(i,d)
```
[Try it online!](https://tio.run/##bZDLDsIgEEX3/YqJq6JjYm3ro1r3rvwAQkwjEEkabAou/Po6fVhrIoEJnDtzGahe/v6wcdNIpUGHJZqcC5QUWBaA0VBmDud1Xh4MFFaCOxq@jMSjpuQazYI7ymYH2YsnORVRtjILQJVOZVVtrA8JssYr56@3wikHOXAeI6QIa4QEIRIIP6BlA94i7BF23dwQ@8Bdx6MVldCKVy1OO4u03SYfN/KJB3tifRzuESIINPU9dgbGfg@OvoJG/4LZ2VZPn81wlNlUvTx9J/dQh3@zWPMG "Python 3 – Try It Online")
The function prints all possible decompositions to the standard output. If there are no possible decompositions, nothing is printed.
Thanks to @Sriotchilism O'Zaic for improvement suggestions.
[Answer]
# [Python 2](https://docs.python.org/2/), 147 bytes
```
def f(a):
for i in range(2**len(a)):
x=[];y=[]
for c in a:[x,y][i&1]+=[c];i/=2
if x==sorted(x)and y[::-1]==sorted(y[::-1]):return x,y
return 0
```
[Try it online!](https://tio.run/##PY5BCsMgEEXX8RSzKklqaWOSjcGTiAtJtBWKCdaCnt5OSshmmHn/Mfwtx9fqWSmLsWBr3XACdg3gwHkI2j9Nzdr2bTxGmFVJSDVlHKTatXnXNJeJZiXdpVNXIWc1ubtgpHIWkhCfNUSz1KnRfoEsOb916qTH3fBg4jd4wD8Ejv1RtuB8xFaypyNldKBokhMOf9jRHmH5AQ "Python 2 – Try It Online")
] |
[Question]
[
Given a polynomial in one variable with rational coefficients, output an equivalent expression containing only `1`, variables, and definite integrals. For example, -*x*2 can be expressed as ∫*x*∫111d*t**x*d*u*.
`E := 1 | var | ∫EEEdvar`
Any reasonable input/output method is allowed.
Examples:
[](https://latex.codecogs.com/gif.download?%5C%5C%20%5CLarge%201%3D1%5C%5C%20%5CLarge%20x%3Dx%5C%5C%20%5CLarge%200%20%3D%20%5Cint_1%5E1%201%5Ctext%20dt%5C%5C%20%5CLarge%202%20%3D%20%5Cint_%7B%5Cint_1%5E%7B%5Cint_1%5E1%201%5Ctext%20dv%7D%201%5Ctext%20du%7D%5E1%201%5Ctext%20dt%5C%5C%20%5CLarge%20x%5E2%3D%5Cint_%7B%5Cint_1%5E1%201%5Ctext%20dt%7D%5Ex%20x%5Ctext%20dv%5C%5C%20%5CLarge%20%5Cfrac%2012%3D%5Cint_%7B%5Cint_1%5E1%201%5Ctext%20dt%7D%5E1%20v%5Ctext%20dv)
Your score will be the your code length multiplied by the number of `∫` symbols used on the test cases. You should be able to score your program. Lowest score wins.
Test cases:
```
4/381*x^2+49/8*x^3-17/6
311/59*x^2-92/9*x^3-7/15*x
333/29*x^3+475/96*x^8
```
>
> Golfing is going to be difficult, because I can't golf just the code or just the output, and I therefore do not know if a change will help or hurt my score until I try it, which sucks in my opinion.
>
>
>
Don't let the score restrict your creation. You are welcomed to answer with mainly one part of the score well optimized, even if the other one badly left.
[Answer]
# [Python 2](https://docs.python.org/2/), 315 bytes \* 5113 = 1610595 score
I'm still working on golfing the score. Golfing is going to be difficult, because I can't golf just the code or just the output, and I therefore do not know if a change will help or hurt my score until I try it, which sucks in my opinion.
Despite the annoyance of golfing this, I did enjoy the calculus.
```
t='t'
Z=lambda n:N(Z(-n))if n<0else[1,t,N(1),Z(n-1)]if n>1else[[1,t,1,1],1][n]
N=lambda a:[1,t,a,Z(0)]
x=lambda n:n>1and[x(n-1),t,Z(0),'x']or'x'
M=lambda a,b:[b,t,Z(0),a]
print reduce(lambda a,b:[1,t,N(a),b],[M((lambda a,b:M(Z(a),[x(b-1)if b>1else 1,'x',Z(0),1]))(*c),x(i)if i else 1)for i,c in enumerate(input())])
```
[**Try it online!**](https://tio.run/##bVDLboMwEDyXr9jmgl0tEg55gUpv6S3ppadYPhhwFEuJQY5RydenBpQ0rSpZ3pVndmY9zcUdajO9lnWl8slkcnV56MJglx/lqagkmGxLdiQylOo9mNdYHc@KM3S4JYzijpiIUdFDb2yABowhE/5wI4LtTUhmAyT9TExF0P0Y@FFpKt4NWp7SEzDsQlFbfwebuwIWGS9uBCmCxmrjwKqqLRV5JI37SYqFQL4hj9jG/8YD3q3wbn7xYlwcWG85SjNBKXkpKXZE9xQNI4PuawsaS9AGlGlPykqniDZN68iQT8lj8ZzHgl59koGzlyx4@jroo4JP26pMdaokfdA0UF2pGgfrj/e1tbXNGnk@XzmJ2BJhQRFIjN7P1xlCshq7FGHlk@N3LPJkNu@7hDGEeTo8plOE9Bfvb02SBGGa/gf9rbPl3KstqPgG "Python 2 – Try It Online")
[Run all test cases](https://tio.run/##bY/dboMwDIXveQrfEU9GItA/qnVvAA9AlIvQplqkNkUsSOzpmQG166pJUWzlOz7Hab/D581n4xgOcYij@nAx1@ZkwO8rUYvEI7oz@PfUXr6skhSoEhKpFj6RqCf0IWc0M0lS81FeR9XdyOxnZHgmRR0NvwE8avxJDbMXSyYBxUOsbx3fUflwoGavmrvA6KjtnA/Q2VN/tOJZtOxnkBpNqhTPrOTfMOC0htN48WZZHOQUuVhLjSjejkiDcJPEwaLA860DR0dwHqzvr7YzwQrn2z4IRI3jqEQitwQbJBAp8QTXFUG@W7qCYMd/Vw@WsFiupy6XkmBdzI9FRlD80b3WPM8JsuI/9FpX2zW7bVD/AA) - to score, count all `[` in the output.
The input polynomial is taken as a list of (numerator, denominator) coefficient pairs in order from lowest to highest power of `x`. `(0, 1)` (zero) is used for missing powers.
Output is given with each integral represented by a list `[f,t,a,b]` to represent ∫ab*f* d*t*
### Verification
[**Here**](https://tio.run/##VZDBboMwDIbPzVP4UhFXqdT0iEbvHOABijgECFuk1qA0SLTTnp2ZUqZVSnLw9/v/7fT38NXRcZpCEoVIpJDAxVyrxsDuEUcpBfvpTbDF9qa@@T7PTxnBFh6isS2cJWEsNq4F@jjE3obBE@TyLPeE@KrrtZ5KrYLSSq/kuBItNm@aXGpU7L3X7JInr5FMvFDD6MBgXAHFdNKGGu4en00smiUqGiPsPL8i@zNRFdtUq8Kg6L2jAN42Q23lm2oZxaCqUBWZ/A8z3pHBHFhxIK9TnbS93CzoOXUx5@lR7mpUo3SzxMGiwLbz4FQNjsDScLXzH0tH/RAkYonTVHA268pf) is a slightly less golfed version that outputs valid Mathematica syntax for integration, which may be tested in an online notebook. Unfortunately, decently-sized programs will not complete in a free notebook.
Go [here](https://lab.open.wolframcloud.com/app), scroll to bottom, "Create New Notebook", paste (Wolfram Language Input), and evaluate (Shift+Enter) *(Note that using num-pad Enter doesn't work)*.
### Explanation
Uses these equations:
[](https://i.stack.imgur.com/LYn8U.png)
[](https://i.stack.imgur.com/06YkO.png)
[](https://i.stack.imgur.com/BuM8M.png)
[](https://i.stack.imgur.com/9WN5A.png)
[](https://i.stack.imgur.com/nDwlg.png)
[](https://i.stack.imgur.com/YD8RX.png)
### Links
* [Tool that converts the output to Mathematica nested functions](https://tio.run/##bcuxCsIwEAbg3afIIKTFWozODo7OjiHQUGONlLtwvYql5NljlaJLh@P/7n7uYZ@2q8kH3gJeXToR2aEMhIw8BFcyXpg8NOIobj3U7BGyfCTHPYGozsCuIctOr0e@@07vTCzG2WryzP2fBxOjqeKqRuiwdWWLTSblJmlVCMmyED9Mqcy0fw@vheYziy/KmJSnNw)
* [Tool that converts the output to Mathematica, avoiding recursion](https://tio.run/##XcrBC4IwFAbwe39FB@EpLnF1lB06ds7bGDhs2UI2mU9Jxv72ZSAUwfv4fny8p5zl2Do94MHYm4o1K6uzc3IpBmfR4jKoAu0VnTYdu0@mRW1NqjPfWjPaXhW97dJmTrxmeV4HdjGoOidR8cTjQ4@8FIH4zXT1xuOXJxGCaLLKKZyc2cMMuQ47gDxySgCBbEUJFYRzeAH55Hdd7/@RChHjGw)
* [Run the Mathematica output on TIO](https://tio.run/##y00syUjNTSzJTE78/7/MyNYzryQ1vSixJDXaUKe6RMdQx7A2lqvMFIe4CZJ4hU51hU6ZKUTCDIcGYyTxMhOQRJkZRMYQXUeZkU6ZMVDm////ugVFmXklAA)
* Equation images made with [this tool](http://rogercortesi.com/eqn/).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 152 bytes \* 5113 integrals = 777176 score
```
T='t';P=n=>--n?[T,'u',O,P(n)]:1;N=n=>n-1?n>-1?[1,T,N(1-n),1]:[1,T,N(-n),O]:1;O=N(0)
F=([e,...s])=>e?[1,T,[F(s),T,'x',O],[N(e[0]),T,O,[P(e[1]),T,O,1]]]:O
```
[Try it online!](https://tio.run/##rVHBasJAEL37FXMQsosTzRqtJmGVXoRejAFvy4IhXcVWNpJsxCJ@u91UBbG29NDLvnlv5s0b2Ld0l5ZZsd4aV@ev6nSac8c40YxrPnJdPRZzdCoHY5wRTWXIomnd0S4b65F9BMM5TglzNUUmwwutWVwPx3xKPNqYcCIUttvtUlI@UmeXmJCSWnT2dr1EMSVKeLJWYhQzS9iFMCllGJ86nWWlM7PONVR6m2bvZE/hAIUyVaFhD2tdmlRnKl/Cc1GkHzCGxYs2alWkRonm4WqqQ454uBFYLdzw7h33LT/KBYQ25dhIEu5F8PCWXVqAiX49iRjeaiUJQpbrMt@o9iZfkcWueTBH4PCv91IEZ@e0DL0cfpt4mZ0QYf8CehJBeAisxh6CPzxXAcJQSkrpT96rxx3Yol9XPrP7@sGXGHQRgj/579H3fYRu8Kh1j71B36Y8fY9JEnr6BA "JavaScript (Node.js) – Try It Online")
Mainly use these two equations:
[](https://i.stack.imgur.com/ZbkNJ.gif)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 220 bytes \* 616 integrals = 135520 score
```
O=[1,T='t',1,1]
D=(q,t)=>[t,'c',[q,T,1,O],q]
N=n=>n>0?[N(-n),T,1,O]:n?[D(1,1),'c',n&1?[T,T,O,1]:O,N(n/2|0)]:O
P=n=>n?[D(n%2?'x':1,T),T,O,P(n>>1)]:1
F=([e,...s])=>e?[1,T,[F(s),T,'x',O],[N(e[0]),T,O,[P(e[1]-1),'x',O,1]]]:O
```
[Try it online!](https://tio.run/##rVFNj9owFLznV7zDtrbFA@IEupsgJ6q0QtoLEImbZYko9a5okbMkBlFRfju1WVaN0Krqobm8j5l5M1a@l/uyrZr1q@2b@ps@n@dCclwKYgly5Cp4FHSLlolMWiQVQbnFpUPmCrcqmAkjMpOFuZzRvmFXJDW5fKROzS4K85nncumwubuXznFGzTD6FTLXB4vLAU83n6KcHEjqzNmFu6Amy7hj8WAqqNQ4GAxa5YLo3CdEOaWtZzqRT@MSaBmqN61cuIGrvk/gYWesnN15OHzemcquawM781pWP@iBwREabXeNgQOsTWtLU@n6Gb42TfkTclg9GatfmtJqeXd8F3mjEx47C@4XnTm6mWM3n9QKUudyCopChBP4MMu@bMBO/hqJWtHrFQVCVZu23ujBpn6hq/3d0Z5AwH/NyxDInvQsuwbvOl65Uyrd/4CRQpAhAvd1hBA/vHUJwoNSjLFJAH@@rvhd1L93zdh3MXcHx8llmUQIyb8duK1xHCNEyUfQbR3dj53Nl6tP95VkWdtykwKBHhQFO/8G "JavaScript (Node.js) – Try It Online")
[](https://i.stack.imgur.com/AMniJ.png)
[](https://i.stack.imgur.com/Bv1kh.png)
[](https://i.stack.imgur.com/Hjtru.png)
] |
[Question]
[
The task is to compute [OEIS A005434](https://oeis.org/A005434) as quickly as possible.
Consider a binary string `S` of length `n`. Indexing from `1`, we can determine if `S[1..i+1]` matches `S[n-i..n]` exactly for all `i` in order from `0` to `n-1`. For example,
```
S = 01010
```
gives
```
[Y, N, Y, N, Y].
```
This is because `0` matches `0`, `01` does not match `10`, `010` matches `010`, `0101` does not match `1010` and finally `01010` matches itself.
Define `f(n)` to be the number of distinct arrays of `Y`s and `N`s one gets when iterating over all `2^n` different possible bit strings `S` of length `n`.
The observant will notice this question is a simpler variant of [another recent question of mine](https://codegolf.stackexchange.com/questions/124424/finding-approximate-correlations). However, I expect that clever tricks can make this much faster and easier.
## Task
For increasing `n` starting at `1`, your code should output `n, f(n)`.
## Example answers
For `n = 1..24`, the correct answers are:
```
1, 2, 3, 4, 6, 8, 10, 13, 17, 21, 27, 30, 37, 47, 57, 62, 75, 87, 102, 116, 135, 155, 180, 194
```
## Scoring
Your code should iterate up from `n = 1` giving the answer for each `n` in turn. I will time the entire run, killing it after two minutes.
Your score is the highest `n` you get to in that time.
In the case of a tie, the first answer wins.
## Where will my code be tested?
I will run your code under Virtualbox in a [Lubuntu](http://lubuntu.net/) guest VM (on my Windows 7 host).
My laptop has 8GB of RAM and an Intel i7 [[email protected]](/cdn-cgi/l/email-protection) GHz (Broadwell) CPU with 2 cores and 4 threads. The instruction set includes SSE4.2, AVX, AVX2, FMA3 and TSX.
## Leading entries per language
* **n = 599** in **Rust** bu Anders Kaseorg.
* **n= 30** in **C** by Grimy. Parallel version gets to **32** when run natively in cygwin.
[Answer]
# [Rust](https://www.rust-lang.org/), n ≈ 660
```
use std::collections::HashMap;
use std::iter::once;
use std::rc::Rc;
type Memo = HashMap<(u32, u32, Rc<Vec<u32>>), u64>;
fn f(memo: &mut Memo, mut n: u32, p: u32, mut s: Rc<Vec<u32>>) -> u64 {
debug_assert!(p != 0);
let d = n / p;
debug_assert!(d >= 1);
let r = n - p * if d >= 2 { d - 1 } else { 1 };
let k = s.binary_search(&(n - r + 1)).unwrap_or_else(|i| i);
for &i in &s[..k] {
if i % p != 0 {
return 0;
}
}
if d >= 3 {
let o = n - (p + r);
n = p + r;
s = Rc::new(s[k..].iter().map(|i| i - o).collect());
} else if n == p {
return 1;
} else if k != 0 {
s = Rc::new(s[k..].to_vec());
}
let query = (n, p, s);
if let Some(&c) = memo.get(&query) {
return c;
}
let (n, p, s) = query;
let t = Rc::new(s.iter().map(|i| i - p).collect::<Vec<_>>());
let c = if d < 2 {
(1..r + 1).map(|q| f(memo, r, q, t.clone())).sum()
} else if r == p {
(1..p + 1)
.filter(|&q| p % q != 0 || q == p)
.map(|q| f(memo, r, q, t.clone()))
.sum()
} else {
let t = match t.binary_search(&p) {
Ok(_) => t,
Err(k) => {
Rc::new(t[..k]
.iter()
.cloned()
.chain(once(p))
.chain(t[k..].iter().cloned())
.collect::<Vec<_>>())
}
};
(1..t.first().unwrap() + 1)
.filter(|&q| p % q != 0 || q == p)
.map(|q| f(memo, r, q, t.clone()))
.sum()
};
memo.insert((n, p, s), c);
c
}
fn main() {
let mut memo = HashMap::new();
let s = Rc::new(Vec::new());
for n in 1.. {
println!("{} {}",
n,
(1..n + 1)
.map(|p| f(&mut memo, n, p, s.clone()))
.sum::<u64>());
}
}
```
[Try it online!](https://tio.run/##xVVRb9owEH7nV1wrLXLW4JV22kOgeZu0l6pSJ@2lqlBqTIlIHGM7qyrgr4@dHROSwMbelgewznef7777zlaVNrtdpTloM4tjVuY5ZyYrhY7jb6le3KdyPGi2M8NVHJeC8ZZRsTh@ZOPBwLxLDve8KOEOfOyEVLc3EbifRzb5wdkE10kSou3L5wSD5gLmpMCgGIKiMi4@ArsScR0n/b@16bgLA8PEAsF6APjN@Ev1Ok215spcEAkXd3Adjt1Wzg3MMC8Bn0COT3jPILmDUctbOe8hSPgI2Rzc/g2scTGEEWyB50jA2i6xin3QEoM0fclEqt6nmqeKLUhALIyCK4QPaSXeVCqnpZpaALLJNpD5U@elgiCDTECgnyhdPvuy7IcZZPAB6ppadvspbiol4HrcWLeD@nfgQ13yt60wm2vpC0SirkCFh2iBG852MGk0PWKfBX8j@mlJ6TO1WiAhLVJZF4FIZUi9gEjo8TxPmAOiWthDDj7tUd9x2a/xxOGmnP7k7HDKoQOriqt3DCAClROB9h6Ia3e/lwUnAQvRwWqOvnJDAhcSHmfG9uB77AYTw11Qq/OmneQpcmRDThw7BU@TpCnAIjBEcL2aWJ01yZARpbV4arjVxg9MBCqCVQSGsrwUHLFCqquChD0@VZ94iygdYkdGdJ7lNu1NgEdIFNuqbsRmgysL0XM/m03X/Si1rhotf0Vq2AIRevMjw57gH5Zkij1IwEQd@1elyNJtdP3tt@@NcZN1tN1Jte7e331clbOzXos0E8RemESG/@RrOtO1P@Vc6AlhdSK2h6th3NGBwa4rjfPqLyYS/k9h1Lm5ycyEvZdJM3IRMD8rbLB1z0Zh6dpLw0rIPhBF5/mpW96asfZVglT5/db9K@z1i7y0FCRVJkwuLsjlegvr7WV03AtxwmbZFcdk9miSlqZgn3kEvtw/cNUhDbtt39DWJbjd7X6xeZ6@6t3w4Tc "Rust – Try It Online")
### How it works
This is a memoized implementation of the recursive predicate Ξ given in Leo Guibas, [“Periods in strings”](https://doi.org/10.1016/0097-3165(81)90038-8) (1981). The function `f(memo, n, p, s)` finds the number of correlations of length `n` with smallest period `p` and also each of the periods in the set `s`.
[Answer]
Just a simple brute-force search, to get the challenge started:
```
#include <stdio.h>
#include <stdint.h>
#include <string.h>
typedef uint16_t u16;
typedef uint64_t u64;
static u64 map[1<<16];
int main(void)
{
for (u64 n = 1;; ++n) {
u64 result = 1;
u64 mask = (1ul << n) - 1;
memset(map, 0, sizeof(map));
#pragma omp parallel
#pragma omp for
for (u64 x = 1ul << (n - 1); x < 1ul << n; ++x) {
u64 r = 0;
for (u64 i = 1; i < n; ++i)
r |= (u64) (x >> i == (x & (mask >> i))) << i;
if (!r)
continue;
u16 h = (u16) (r ^ r >> 13 ^ r >> 27);
while (map[h] && map[h] != r)
++h;
if (!map[h]) {
#pragma omp critical
if (!map[h]) {
map[h] = r;
++result;
}
}
}
printf("%ld\n", result);
}
}
```
Compile with `clang -fopenmp -Weverything -O3 -march=native`. On my machine it reaches n=34 in 2 minutes.
EDIT: sprinkled some OMP directives for easy parallelism.
[Answer]
# Python, n≈427
Rewrite [@Anders Kaseorg's Rust answer](https://codegolf.stackexchange.com/a/127038/110802) in Python
[TIO Link](https://tio.run/##jVPRjpswEHz3V2xVVTI9LhdyL1V06Y8gdKJgehZgO/ai6r4@Xa8hkFSV4geQZ2dnZ722@8QPa15/OH@56NFZj/BLB9Wg6LwdobHDQBttTYA53KqungZsNXFmCPWohBjVaOG0jUttMBOBwLISggLQSZODyyFkRwG06hCUR@ngywn2GUMt0Q28vIDbMlr4eYIiMTwznsHBd6DAMxSgO2DGAdQQVCQysydmameXfu@D6lCGnPM9PC2SnfWgQRsI5bGvkre4SFfDN0j@VphdKJy8gX2qtBh4XUl2tkndPYHPrrghnKErwiekiWq3RvpjVTFFDaROWZS2qs/li5XR35mMqqySHJ4n5T8JmieAkxuUDFm22E9xqhzn@E@dCJZMmeVw8ew2nqv1LN7gsIo00co0yk76HM5UPOOkc0zytfmtZJHP48jWhvxdyw@pOFaJHhwN7sxnAsyKYot6UKvsfy4J5gt97qmnngZlJJWtTQtY9tWdwbgcXdgrcFuIj22nDV/o/kb@odaw3FcPdLcZFak2YjPFRoiAtcf3@GIpGH@7@JGZiNeyEH8@9KC2OE14k/IGxWF/BPgKfjJssUYYbUB6eaM2E6rUvPP09ONNS00tj54z3E1TJk09WadNNHG5/AU)
```
import bisect
from collections import defaultdict
import time
memo = defaultdict(int)
s = []
def f(n, p, s):
assert(p != 0)
d = n // p
assert(d >= 1)
r = n - p * (d - 1 if d >= 2 else 1)
k = bisect.bisect_left(s, n - r + 1)
for i in s[:k]:
if i % p != 0:
return 0
if d >= 3:
o = n - (p + r)
n = p + r
s = [i - o for i in s[k:]]
elif n == p:
return 1
elif k != 0:
s = s[k:]
query = (n, p, tuple(s))
if query in memo:
return memo[query]
t = [i - p for i in s]
if d < 2:
c = sum(f(r, q, t) for q in range(1, r + 1))
elif r == p:
c = sum(f(r, q, t) for q in range(1, p + 1) if p % q != 0 or q == p)
else:
k = bisect.bisect_left(t, p)
if k < len(t) and t[k] == p:
pass
else:
t.insert(k, p)
c = sum(f(r, q, t) for q in range(1, t[0] + 1) if p % q != 0 or q == p)
memo[query] = c
return c
start_time = time.time()
n = 1
while time.time() - start_time < 120: # run for at most 2 minutes
print(n, sum(f(n, p, s) for p in range(1, n + 1)))
n += 1
```
] |
[Question]
[
Some of you may say that I am wasting my time, but this task does not give me peace for more than 500 days. It is required to write a program in **Python 3.x** that takes two numbers as input and displays their sum. The numbers are given in the following format:
```
a b
```
Some example test cases:
```
100 500 -> 600
3 4 -> 7
```
The length of the code is calculated with the formula **max(code length without spaces or tabs or newlines, code length / 4)**. I know only 2 solutions, each of them has a length of 36 characters:
```
print(sum(map(int, input().split())))
```
and:
```
print(eval(input().replace(' ', '+')))
```
Also I know, that the exists solution with length of 34 symbols. You can check it on [this website](http://acmp.ru/index.asp?main=bstatus&id_t=1&lang=PY).
[Answer]
Given the right hint toward the solution in the comment to the same question asked on stackoverflow ( see [here](https://stackoverflow.com/questions/43448778/shortest-python-a-b-programm/43448957#43448957) ), I have got it right down to 34 and without any limitations on the input number or other tricks necessary:
`print(eval(input().replace(*' +')))`
Here a short summary of currently known different solutions:
>
> `print(eval(input().replace(' ','+'))) #` **36**
>
>
> `print(sum(map(int,input().split()))) #` **36**
>
>
> `print(eval(input().replace(*' +'))) #` **34**
>
>
> `print(sum(map(int,input()[::2]))) #` **33 (limited to numbers between 0 and 9)**
>
>
>
Maybe it could be considered cheating, but maybe not. At least there is no rule for this defined yet so let's include it into the collection of possible solutions:
>
> `import f;f.f() #` **13**
>
>
>
Required for this solution to work is a script f.py available in a search directory for modules of Python with following content:
```
def f():
print(sum(map(int,input().split())))
```
] |
[Question]
[
Today your challenge is to produce all possible full parenthesizations of an expression.
Your input is a single line of printable ASCII containing one or more terms separated by operators. The input might also contains spaces - you must ignore these. A term is `[a-zA-Z0-9]`, an operator is `[^ ()a-zA-Z0-9]`. You may assume that the input is always valid.
Output all possible ways to fully parenthesize the given expression, separated by newlines with an optional trailing newline.
Do **not**:
* Parenthesize terms - only parenthesize around operators.
* Reorder the terms.
* Output any spaces.
Example input/output:
```
N
N
a * b
(a*b)
x_x_0
(x_(x_0))
((x_x)_0)
a * b|c|d
(a*(b|(c|d)))
(a*((b|c)|d))
((a*b)|(c|d))
((a*(b|c))|d)
(((a*b)|c)|d)
```
---
Smallest code in bytes wins.
[Answer]
# Pyth, 38 bytes
```
L?tbsmmjj@bdk"()"*y<bdy>bhd:1lb2bjy-zd
```
[Try it online.](https://pyth.herokuapp.com/?code=L%3Ftbsmmjj%40bdk%22%28%29%22*y%3Cbdy%3Ebhd%3A1lb2bjy-zd&input=a+*+b%7Cc%7Cd&debug=0)
It defines a recursive function that:
* returns the input if its length is 1
* takes all two-splits of the input on operators, and for each split:
+ calls itself recursively on each of the halves
+ takes the Cartesian product of the results of each half
+ joins each result by the operator at the split
+ parenthesizes the joined result
* and finally concatenates the resulting arrays.
The function is then called with the input string with spaces removed and the results are joined by newlines.
[Answer]
# JavaScript (ES6), ~~208~~ 197 bytes
```
s=>((q=x=>x.map((_,i)=>(a=[...x.slice(0,i*=2),p="("+x[i]+x[++i]+x[++i]+")",...x.slice(i+1)],x[i]?a[1]?q(a):r.push(p):0)))([...s.replace(/ /g,o="")],r=[]),r.map((l,i)=>r.indexOf(l)<i?0:o+=l+`
`),o)
```
## Explanation
Uses a recursive function that takes an array of `[ t, o, t, o, etc... ]` and parenthesises each consecutive pair of two terms together like `[ (tot), o, etc... ]` and repeats this process until there is only one element in the array, then filters out the duplicate values.
```
s=>( // s = input string
(q=x=> // q = parenthesise array function
x.map((_,i)=>(
a=[ // a = p with parenthesised pair of terms
...x.slice(0,i*=2),
p="("+x[i]+x[++i]+x[++i]+")", // parenthesise and join 2 terms and an operator
...x.slice(i+1)
],
x[i]?a[1] // make sure the loop is not over
?q(a) // check next level of permutations
:r.push(p) // add the permutation to the results
:0
))
)([...s.replace(/ /g, // remove spaces and parenthesise all expressions
o="")], // o = output string
r=[]), // r = array of result strings
r.map( // filter out duplicates
(l,i)=>r.indexOf(l)<i?0:o+=l+`
`
),o) // return o
```
## Test
```
Input = <input type="text" id="input" value="a * b|c|d" /><button onclick='results.innerHTML=(
s=>((q=x=>x.map((_,i)=>(a=[...x.slice(0,i*=2),p="("+x[i]+x[++i]+x[++i]+")",...x.slice(i+1)],x[i]?a[1]?q(a):r.push(p):0)))([...s.replace(/ /g,o="")],r=[]),r.map((l,i)=>r.indexOf(l)<i?0:o+=l+`
`),o)
)(input.value)'>Go</button><pre id="results"></pre>
```
] |
[Question]
[
Given a positive integer below 1000, display all possible rectangles with that area.
# Task
Let's say the input is 20. We can make a rectangle 20×1, 10×2, or 5×4, so this is a valid output:
```
********************
**********
**********
*****
*****
*****
*****
```
Note that each possible rectangle appears exactly once.
The rectangles may appear in any order, orientation or position, but no two rectangles may overlap or touch, even at the corners. The following is also valid:
```
********************
****
********** ****
********** ****
****
****
```
# Scoring
The bounding-box area (BBA) of an output is the area of the minimum rectangle enclosing all of the rectangles. In the first example output, the size is 20×9, so the BBA is 180. In the second example output, the size is 20×7, so the BBA is just 140.
Find the BBA of the output when the the input is 60, 111, 230, 400, and 480, and add them up. Multiply this sum by the size of your code in bytes. The result is your score; lowest score wins.
# Rules
* The program (or function) must produce valid output for any positive integer below 1000.
* The output must contain just asterisks (`*`), spaces (), and newlines.
* There can be any amount of space between the rectangles, but this counts towards the BBA.
* Leading or trailing lines or columns, if they have just spaces, do not count towards the BBA.
[Answer]
# Ruby, 228 bytes \* 21895 =4992060
```
->n{a=(0..n*2).map{$b=' '*n}
g=0
m=n*2
(n**0.5).to_i.downto(1){|i|n%i<1&&(m=[m,n+h=n/i].min
g+=h+1
g<m+2?(a[g-h-1,1]=(1..h).map{?**i+$b}):(x=(m-h..m).map{|j|r=a[j].rindex(?*);r ?r:0}.max
(m-h+1..m).each{|j|a[j][x+2]=?**i}))}
a}
```
Several changes from ungolfed code. Biggest one is change of meaning of variable `m` from the height of the squarest rectangle, to the height of the squarest rectangle plus `n`.
Trivially, `*40` has been changed to `*n` which means a lot of unnecessary whitespace at the right for large `n`; and `-2` is changed to `0` which means rectangles plotted across the bottom always miss the first two columns (this results in poorer packing for numbers whose only factorization is `(n/2)*2`)
**Explanation**
I finally found time to get back to this.
For a given `n` the smallest field must have enough space for both the longest rectangle `1*n` and the squarest rectangle `x*y`. It should be apparent that the best layout can be achieved if both rectangles have their long sides oriented in the same direction.
Ignoring the requirement for whitespace between the rectangles, we find that the total area is either `(n+y)*x = (n+n/x)*x` or `n*(x+1)`. Either way, this evaluates to `n*x + n`. Including the whitespace, we have to include an extra `x` if we place the rectangles end to end, or `n` if we place the rectangles side by side. The former is therefore preferable.
This gives the following lowerbounds `(n+y+1)*x` for the field area:
```
n area
60 71*6=426
111 149*3=447
230 254*10=2540
400 421*20=8240
480 505*20=10100
```
This suggests the following algorithm:
```
Find the value (n+y+1) which shall be the field height
Iterate from the squarest rectangle to the longest one
While there is space in the field height, draw each rectangle, one below the other, lined up on the left border.
When there is no more space in the field height, draw the remaining rectangles, one beside the other, along the bottom border, taking care not to overlap any of the rectangles above.
(Expand the field rightwards in the rare cases where this is necessary.)
```
It is actually possible to get all the rectangles for the required test cases within the above mentioned lower bounds, with the exception of 60, which gives the following 71\*8=568 output. This can be improved slightly to 60\*9=540 by moving the two thinnest rectangles right one square and then up, but the saving is minimal, so it's probably not worth any extra code.
```
10
12
15
20
30
60
******
******
******
******
******
******
******
******
******
******
***** *
***** *
***** *
***** *
***** *
***** *
***** *
***** *
***** *
***** *
***** *
***** *
*
**** *
**** *
**** *
**** *
**** *
**** *
**** *
**** *
**** *
**** *
**** *
**** *
**** *
**** *
**** *
*
*** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
** *
** *
** *
** *
** *
** *
** *
** *
** *
** *
** *
```
This gives a total area of 21895.
**Ungolfed code**
```
f=->n{
a=(0..n*2).map{' '*40} #Fill an array with strings of 40 spaces
g=0 #Total height of all rectangles
m=n #Height of squarest rectangle (first guess is n)
(n**0.5).to_i.downto(1){|i|n%i<1&&(puts n/i #iterate through widths. Valid ones have n%i=0. Puts outputs heights for debugging.
m=[m,h=n/i].min #Calculate height of rectangle. On first calculation, m will be set to height of squarest rectangle.
g+=h+1 #Increment g
g<n+m+2? #if the rectangle will fit beneath the last one, against the left margin
(a[g-h-1,1]=(1..h).map{'*'*i+' '*40}) #fill the region of the array with stars
: #else
(x=(n+m-h..n+m).map{|j|r=a[j].rindex('* ');r ?r:-2}.max #find the first clear column
(n+m-h+1..n+m).each{|j|a[j][x+2]='*'*i} #and plot the rectangle along the bottom margin
)
)}
a} #return the array
puts f[gets.to_i]
```
[Answer]
# CJam, 90385 \* 31 bytes = 2801935
```
q~:FmQ,:){F\%!},{F\/F'**/N*NN}/
```
[Test it here.](http://cjam.aditsu.net/#code=q~%3AFmQ%2C%3A)%7BF%5C%25!%7D%2C%7BF%5C%2FF'**%2FN*NN%7D%2F&input=480) Use [this script](http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%3B%0A%0AQ~%3AFmQ%2C%3A)%7BF%5C%25!%7D%2C%7BF%5C%2FF'**%2FN*NN%7D%2F%5Ds-2%3CN%2F_%2C%5Cz%2C*_pL%2B%3AL%3B%0A%0A%7D%2FNL%3A%2B&input=60%0A111%0A230%0A400%0A480) to calculate the BBAs.
This is just the naive solution to get things started.
[Answer]
# Ruby, 56 bytes
90385\*56=5061560 assuming output the same as Martin's (I believe it is.)
```
->n{1.upto(n){|i|i*i<=n&&n%i==0&&puts([?**(n/i)]*i,'')}}
```
---
Here's another useful function, in a useful test program
```
f=->n{1.upto(n){|i|i*i<=n&&n%i==0&&print(n/i,"*",i,"\n")};puts}
f[60];f[111];f[230];f[400];f[480]
```
Which gives the following output, for reference:
```
60*1
30*2
20*3
15*4
12*5
10*6
111*1
37*3
230*1
115*2
46*5
23*10
400*1
200*2
100*4
80*5
50*8
40*10
25*16
20*20
480*1
240*2
160*3
120*4
96*5
80*6
60*8
48*10
40*12
32*15
30*16
24*20
```
] |
[Question]
[
My high school, and many others implement a type of schedule called a Rotating Block Schedule. This is a way for people to have 8 classes, but on have 6 periods in a school day.
There are four days in a block schedule that repeat over and over, and have nothing to do with the actual days of the week. Each are assigned a number `[1-4]`.
The way the schedule works is that you list all your morning classes, periods `1-4`: `[1, 2, 3, 4]`. This is your schedule for the first day, or Day 1. The rest of the days just rotate the list: `[2, 3, 4, 1]` , `[3, 4, 1, 2]`, `[4, 1, 2, 3]`.
However, the last period in the morning is "dropped" and you don't see that teacher that day. Hence the days are: `[1, 2, 3]`, `[2, 3, 4]`, `[3, 4, 1]`, `[4, 1, 2]`.
The afternoon is the same, except that it uses periods `5-8` instead: `[5, 6, 7]`, `[6, 7, 8]`, `[7, 8, 5]`, `[8, 5, 6]`.
## Your task
All this rotating is hard to keep track of, so you have to write a program to print out my schedule given what day it is as input. Your code has to place Homeroom and Lunch in the correct spots. Here is the **exact** output your code needs to have for inputs `1-4`:
```
Homeroom Homeroom Homeroom Homeroom
Period 1 Period 2 Period 3 Period 4
Period 2 Period 3 Period 4 Period 1
Period 3 Period 4 Period 1 Period 2
Lunch Lunch Lunch Lunch
Period 5 Period 6 Period 7 Period 8
Period 6 Period 7 Period 8 Period 5
Period 7 Period 8 Period 5 Period 6
```
# But Wait - One more thing!
Sometimes, on the first day of school, or on other special days, my school has a "Day 0". This just means that I will have *all* my classes that day along with homeroom and lunch. Your code will have to deal with Day 0's. Here is the output for a Day 0:
```
Homeroom
Period 1
Period 2
Period 3
Period 4
Lunch
Period 5
Period 6
Period 7
Period 8
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in **bytes** wins!
[Answer]
## [Snowman 1.0.2](https://github.com/KeyboardFire/snowman-lang/releases/tag/v1.0.2-beta), 190 bytes
```
}vg10sB*:#NdE*!1*"Homeroom
"sP0vn3nR:|%+#nA4NmO'"Period "sP'!#nAtSsP"
"sP|%;ae|"Lunch
"sP5*|ae;:"Homeroom
"sP0vn4nR*#:`"Period "sP`NiNtSsP"
"sP;aE"Lunch
"sP#:`"Period "sP`5nAtSsP"
"sP;aE;#bI
```
That leftmost column actually looks pretty nice, doesn't it?
...
... who am I kidding, I'd rather program in PHP than this.
"Readable" version:
```
}vg10sB* // store day # in permavar
// big if statement coming up, depending on whether the input (n) is 0 or not
// THE FOLLOWING BLOCK IS FOR N != 0
:
#NdE* // decrement number (because we like 0-based indeces) and re-store
!1* // store the number 1 in permavar ! for later
"Homeroom
"sP // print "Homeroom"
0vn3nR // generate [0 1 2]
// for each element in this array...
:
|% // shuffle around some variables so we have room
+#nA // add day number (in permavar +)
4NmO // modulo by 4
'"Period "sP // print "Period "
'!#nAtSsP // add whatever is in permavar ! and print
"
"sP // print a newline
|% // return variables to their original state
;ae
// this is a rare occasion in which we use "ae" instead of "aE"
// we use non-consume mode here because we need the block again
// since we've used a permavar ! to determine what to add to the period number,
// we can set the permavar to 4 more than it used to be and run the same
// exact block
|"Lunch
"sP // print "Lunch"
5* // store the number 5 in permavar !, as described above
|ae // run the same block over the same array again
;
// THE FOLLOWING BLOCK IS FOR N == 0
:
// after much frustration, I have determined that the easiest way to go about
// this is to simply code the "day 0" separately
// yes, snowman is *that* bad
"Homeroom
"sP // you know the drill
// for each number in [0 1 2 3]
0vn4nR*#:
`"Period "sP
`NiNtSsP // increment and print
"
"sP
;aE
"Lunch
"sP // same stuff from here
// only interesting thing is we saved the range from before with *#, so we can
// get it back easily
#:`"Period "sP`5nAtSsP"
"sP;aE
;
#bI
```
Thoughts and musings:
* Firstly, I definitely need to implement a prettier way of printing newlines. Because strings with newlines in an indented block are super ugly.
* I like my trick with `ae`—you rarely see the `ae` operator without the `E` capitalized in real Snowman code. (You also rarely see Snowman code that's not written by me, but that's besides the point.)
For the uninitiated, Snowman has two ways to call operators. "Consume" mode, and "non-consume" mode. "Consume" mode will call the operator with the variables requested and then discard the variables. Non-consume mode will call the operator and still leave the variables intact.
Which is usually not what you want with `ae` (array-each), because the block you're calling on each element will stay there and get in your way, using up a precious one of the eight variables.
However, this is a rare situation in which `ae` *is* actually what we want (see the comments in the code for further explanation).
* I'm really, really starting to think that Snowman needs more than two modes, other than just "consume" and "do-not-consume." For example, with `aa` (basically array indexing), you only get two ways to call it:
```
["foo" 0] -> ["f"]
["foo" 0] -> ["foo" 0 "f"]
```
(Snowman doesn't use a stack/array structure, but that's simply being used for clarity here.)
It's pretty common that you want `["foo" "f"]` (i.e. consume the index variable, but not the original one). It's a super convoluted process to get rid of that annoying `0` if you use "do-not-consume" mode.
A similar thing happens when you call "array-each" in "do-not-consume" mode, as is done here. The array and the block stick around, *even **during** the execution of said block*. Which is... really, really weird.
Then again, the design goal of Snowman is to be as confusing as possible, so I'm not sure whether this is a problem at all.
[Answer]
# CJam, ~~65~~ 55 bytes
```
ri_5,m<0-_W<\?_4f+]"HomeroomLunch"8/.{N@{"Period "\N}%}
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=ri_5%2Cm%3C0-_W%3C%5C%3F_4f%2B%5D%22HomeroomLunch%228%2F.%7BN%40%7B%22Period%20%22%5CN%7D%25%7D&input=0).
[Answer]
# Python 3, ~~193~~ ~~192~~ ~~182~~ ~~168~~ 165 bytes
```
u=int(input())
print('Homeroom')
r=['Period '+i for i in("123567234678341785412856"[(u-1)*6:u*6]if u else"12345678")]
r.insert(len(r)//2,'Lunch')
for i in r:print(i)
```
Just a quick solution.
# Python 2, 161 bytes
```
u=int(input())
print'Homeroom'
r=['Period '+i for i in("123567234678341785412856"[(u-1)*6:6*u]if u else"12345678")]
r.insert(len(r)//2,'Lunch')
print'\n'.join(r)
```
[Answer]
# Pyth, 51 bytes
```
"Homeroom"j"Lunch
"c2jb+L"Period "+J?QP.<S4tQS4+L4J
```
] |
[Question]
[
I recently got a new Sudoku app that produces really hard Sudoku's, which can't be solved using the standard strategies. So I had to learn a few new ones. One of these strategies is the **Y-Wing Strategy**. It is ranked under "Tough Strategies", but it is actually not that hard.
# Example
For this strategy only 4 cells are important. Therefore I ignored all other cells in the images.
We look at all candidates for each cell. In the following example we have a cell with the candidates `3 7` (that means we have already rejected the candidates `1 2 4 5 6 8 9`, for instance because there is a `1` in the same row, a `2` in the same 3x3 box, ...), a cell with the candidates `6 7`, a cell with the candidates `3 6` and a cell with the candidates `2 6`. The Y-Wing strategy will suggest, that the `6` can be removed from the candidates of the downright cell, leaving only a `2` as candidate, which you can fill in. So we found a correct number and are one step closer in solving the full Sudoku.

Why can the `6` be removed?
## Explanation
Let us assume that the `6` is the correct number for the downright cell. Now there is a `6` in this column, therefore we can remove the `6` from the candidates of the top right cell, leaving only a `7`, which we can fill in. The same happens with the down left cell. We can remove the `6` and fill in the `3`. Now if we look at the top left cell we get a contradiction. Because now there's already a `7` in the same row and a `3` in the same column, so we can remove the `7` and the `3` of the candidates, leaving no candidates at all. Which is clearly not possible. Therefore the 6 cannot be the correct number of the downright cell.
More precisely: If we have 4 cells with the candidates `[A B] [A C] [C D] [B C]` (in this order or circular rotated) and the cells are connected (via same row, same column or same 3x3 box) in a circle (Cell 1 is connected to Cell 2, which is connected to Cell 3, which is connected to Cell 4, which is connected to Cell 1), than you can remove `C` from the `[C D]` cell. It is crucial, that the three cells `[A B]`, `[A C]` and `[B C]` only contain two candidates each. Differently the cell `[C D]`, which may contain more or less (`D` can be zero, one or even more candidates).

Notice that I explicitly said they can be connected either way. In the next example you can see the strategy applied again. But this time the 4 cells doesn't form a rectangle. The down left and downright cells are simply connected, because they are in the same 3x3 box. Y-Wing says, that we can remove the `1` as candidate of the top left cell. This time there are still 2 candidates in this cell left, so we didn't actually found a new correct number. But nevertheless the removal of the `1` can open doors to different strategies.

If you want more information about the strategy or want a few more examples, visit [sudokuwiki.org](http://www.sudokuwiki.org/Y_Wing_Strategy).
## Challenge Specifications
You will receive 4 lists as input, representing the candidates of the cells. The four cells are connected like a circle (Cell 1 is connected to Cell 2, which is connected to Cell 3, which is connected to Cell 4, which is connected to Cell 1). You can assume that each list is sorted in ascending order.
Your job is to remove one candidate (by applying the Y-Wing strategy) and returning the resulting candidates lists in the same order. If you can't apply the strategy, just return the same candidates lists.
If there are two possible solutions (you could remove A of cell B or remove C of cell D), than return only one solution. It doesn't matter which one.
The input can be in any native list or array format. You could also use a list of lists or something similar. You can receive the input via STDIN, command-line argument, prompt or function argument and return the output via return value or simply by printing to STDOUT.
This is code-golf. The shortest code (in bytes) wins.
## Test Cases
```
[3 7] [6 7] [2 6] [3 6] => [3 7] [6 7] [2] [3 6] # Example 1
[6 7] [2 6] [3 6] [3 7] => [6 7] [2] [3 6] [3 7] # Example 1, different order
[2 6] [3 6] [3 7] [6 7] => [2] [3 6] [3 7] [6 7] # Example 1, different order
[3 6] [3 7] [6 7] [2 6] => [3 6] [3 7] [6 7] [2] # Example 1, different order
[1 2 8] [1 8] [8 9] [1 9] => [2 8] [1 8] [8 9] [1 9] # Example 2
[3 8] [4 8] [3 4 8] [3 4] => [3 8] [4 8] [3 8] [3 4]
[1 3 6 7 8] [3 8] [3 4] [4 8] => [1 3 6 7] [3 8] [3 4] [4 8]
[7 8] [7 8] [4 7] [4 8] => [7 8] [8] [4 7] [4 8] or [7] [7 8] [4 7] [4 8]
[4 7] [7 8] [4 8] [4] => [4 7] [7 8] [4 8] [] # Fictional example
[3 7] [2 6] [6 7] [3 6] => [3 7] [2 6] [6 7] [3 6] # Y-Wing can't be applied here
[4 7] [2 7 8] [4 8] [1 4] => [4 7] [2 7 8] [4 8] [1 4] # -||-
```
[Answer]
# CJam, 90 bytes
Ugghhh, this is too long because of the constraint that the other 3 cells should have only 2 candidates.
```
l~_:_(a+2/::&_{,}$2>:&:Y;{:PY&Y{P1<}?~}%:X,3>1${,}$W=_,2>\Y&,1?*{X:_(+2/{~:I=}#)_2$=I-t}&p
```
This expects input as a list of list in CJam format. For ex.:
```
[[2 6] [3 6] [3 7] [6 7]]
```
gives output in a CJam list of list format:
```
[[2] [3 6] [3 7] [6 7]]
```
Will add explanation once I am done golfing..
[Try it online here](http://cjam.aditsu.net/#code=l~_%3A_(a%2B2%2F%3A%3A%26_%7B%2C%7D%242%3E%3A%26%3AY%3B%7B%3APY%26Y%7BP1%3C%7D%3F~%7D%25%3AX%2C3%3E1%24%7B%2C%7D%24W%3D_%2C2%3E%5CY%26%2C1%3F*%7BX%3A_(%2B2%2F%7B~%3AI%3D%7D%23)_2%24%3DI-t%7D%26p&input=%5B%5B2%206%5D%20%5B3%206%5D%20%5B3%207%5D%20%5B6%207%5D%5D) or [try the whole test suite here](http://cjam.aditsu.net/#code=11%7Bl~%5D_%60o%22%20-%3E%20%22o_%3A_(a%2B2%2F%3A%3A%26_%7B%2C%7D%242%3E%3A%26%3AY%3B%7B%3APY%26Y%7BP1%3C%7D%3F~%7D%25%3AX%2C3%3E1%24%7B%2C%7D%24W%3D_%2C2%3E%5CY%26%2C1%3F*%7BX%3A_(%2B2%2F%7B~%3AI%3D%7D%23)_2%24%3DI-t%7D%26p%7D*&input=%5B3%207%5D%20%5B6%207%5D%20%5B2%206%5D%20%5B3%206%5D%0A%5B6%207%5D%20%5B2%206%5D%20%5B3%206%5D%20%5B3%207%5D%0A%5B2%206%5D%20%5B3%206%5D%20%5B3%207%5D%20%5B6%207%5D%0A%5B3%206%5D%20%5B3%207%5D%20%5B6%207%5D%20%5B2%206%5D%0A%5B1%202%208%5D%20%5B1%208%5D%20%5B8%209%5D%20%5B1%209%5D%0A%5B3%208%5D%20%5B4%208%5D%20%5B3%204%208%5D%20%5B3%204%5D%0A%5B1%203%206%207%208%5D%20%5B3%208%5D%20%5B3%204%5D%20%5B4%208%5D%0A%5B7%208%5D%20%5B7%208%5D%20%5B4%207%5D%20%5B4%208%5D%20%20%20%0A%5B4%207%5D%20%5B7%208%5D%20%5B4%208%5D%20%5B4%5D%20%20%20%20%20%0A%5B3%207%5D%20%5B2%206%5D%20%5B6%207%5D%20%5B3%206%5D%20%20%20%0A%5B4%207%5D%20%5B2%207%208%5D%20%5B4%208%5D%20%5B1%204%5D).
[Answer]
# Mathematica, ~~124~~ 110 bytes
```
Cases[e@n_:>n]/@(Plus@@e/@#&/@#/.NestList[RotateLeft/@#&,{x:a_+b_,y:b_+c_,z:c_+a_,w:a_+_.}->{x,y,z,w-a+1},3])&
```
**Examples:**
```
In[1]:= yWing = Cases[e@n_:>n]/@(Plus@@e/@#&/@#/.NestList[RotateLeft/@#&,{x:a_+b_,y:b_+c_,z:c_+a_,w:a_+_.}->{x,y,z,w-a+1},3])& ;
In[2]:= yWing[{{3, 7}, {6, 7}, {2, 6}, {3, 6}}]
Out[2]= {{3, 7}, {6, 7}, {2}, {3, 6}}
In[3]:= yWing[{{4, 7}, {7, 8}, {4, 8}, {4}}]
Out[3]= {{4, 7}, {7, 8}, {4, 8}, {}}
```
] |
[Question]
[
# The Game
Most of us know about [Frogger](http://en.wikipedia.org/wiki/Frogger), the 80's era arcade game where the objective is to hop a frog safely across a busy highway and a hazard-filled pond to arrive safely at home.
A [challenge was issued](https://codegolf.stackexchange.com/questions/26824/frogger-ish-game) some months ago to develop a Frogger clone. But why *clone* Frogger when you can *play* Frogger? :)
Consider the following simplified playing grid:
```
XXXXXXXXXXXXXXXXXXXXXXX North Safe Zone
-----------------------
| | <<<< Express Lane West (Lane 1)
| | > Gridlock East (Lane 2)
| | << Freeflowing Traffic West (Lane 3)
| | < Gridlock West (Lane 4)
| | >>>> Express Lane East (Lane 5)
-----------------------
XXXXXXXXXXX@XXXXXXXXXXX South Safe Zone
\__________ __________/
'
23 cells horizontally
```
We have five lanes of traffic, each 23 cells wide, and two safe zones (where the frog can move safely left and right), also 23 cells wide. You may ignore the right and left borders as these are for pictorial clarity.
Our frog starts in the southern safe zone, on the center (12th) cell, as indicated by a `@` in the above figure.
Time in the game is divided into discrete steps called frames. Froggy is a fast frog and can hop one cell in any direction (up, down, right, left) per frame. He may also choose to remain stationary for any frame. The traffic in the five lanes moves at constant speeds as follows:
* the traffic in the express lane west (lane 1) moves 2 cells left every frame
* the traffic in the gridlock east lane (lane 2) moves 1 cell right every second frame
* the traffic in the freeflowing traffic west lane (lane 3) moves 1 cell left every frame
* the traffic in the gridlock west lane (lane 4) moves 1 cell left every second frame
* the traffic in the express lane east (lane 5) moves 2 cells right every frame
The traffic itself is uniquely defined for approx. 3,000 timesteps in [this text file](http://pastebin.com/HJttHKaT). 'Traffic' consists of vehicles and spaces between the vehicles. Any character that is not a space is part of a vehicle. The text file contains five lines, corresponding to the five lanes of traffic (with the same order).
For the westbound lanes, at the start of frame 0 (the start of the game), we consider the first vehicle in the lane to be just beyond the right edge of the playing grid.
For eastbound lanes, the traffic string should be considered "backwards" in the sense that the vehicles appear starting at the *end* of the string. At the start of frame 0, we consider the first vehicle in these lanes to be just beyond the left edge of the playing field.
Consider as an Example:
```
Traffic Lane 1: [|==| =
Traffic Lane 2: |) = o
Traffic Lane 3: (|[]-[]:
Traffic Lane 4: <| (oo|
Traffic Lane 5: |==|] :=)
```
Then the playing grid will appear as follows:
```
Start of Frame 0 XXXXXXXXXXXXXXXXXXXXXXX
[|==| =
|) = o
(|[]-[]:
<| (oo|
|==|] :=)
XXXXXXXXXXXXXXXXXXXXXXX
Start of Frame 1 XXXXXXXXXXXXXXXXXXXXXXX
[|==| =
|) = o
(|[]-[]:
<| (oo|
|==|] :=)
XXXXXXXXXXXXXXXXXXXXXXX
Start of Frame 2 XXXXXXXXXXXXXXXXXXXXXXX
[|==| =
|) = o
(|[]-[]:
<| (oo|
|==|] :=)
XXXXXXXXXXXXXXXXXXXXXXX
Start of Frame 3 XXXXXXXXXXXXXXXXXXXXXXX
[|==| =
|) = o
(|[]-[]:
<| (oo|
|==|] :=)
XXXXXXXXXXXXXXXXXXXXXXX
```
After all the traffic in a lane is "depleted" (i.e. the string runs out), we consider all characters in the string to be spaces.
Our frog is *squished* if any of the following occurs:
* the frog occupies a cell occupied by a vehicle, on any frame
* the frog remains stationary in an express lane and a vehicle of 1 cell width passes over him in that frame
* the frog jumps east "through" a vehicle heading west, or jumps west through a vehicle heading east
* the frog jumps outside of the 7 (line) by 23 (cell) playing grid, on any frame
Note that these are the *only* conditions under which a frog is squished. In particular, a frog hopping along "with" traffic is permissible, as is a frog jumping into or out of a cell in an express lane that is passed over by a width-1 vehicle in the same frame.
# Objective and Scoring
The objective of the programming challenge is to get the frog across the road as many times as possible before *the last vehicle exits the playing grid*. That is, the program terminates immediately after the completion of frame *X*, where frame *X* is the first frame that takes the grid to a state where no more vehicles are present.
The output of your program should be a string (or text file) containing the sequence of moves for the frog using the following encoding:
```
< frog moves left
> frog moves right
^ frog moves up
v frog moves down
. frog remains stationary
```
For example, the string `<<^.^` indicates that the frog moves left twice, then up, then pauses for one frame, then moves up again.
One point is scored whenever the frog crosses from the south safe zone to the north safe zone, and one point is scored whenever the frog crosses from the north safe zone to the south safe zone.
Some important rules:
1. **The frog must not be squished.**
2. Please post your solution (sequence of moves) along with your program code, either inline or as a text file (e.g. using pastebin.com).
3. Our frog is prescient and precognizant, hence your program may make use *any and all traffic data* in any frame while seeking out solutions. This includes data for traffic that hasn't yet reached the playing grid.
4. The grid does not wrap around. Exiting the grid will cause the frog to be squished and hence is not permitted.
5. At no point does traffic "reset" or the frog "teleport". The simulation is continuous.
6. The frog may return to the south safe zone after exiting it, but this is not counted as a point. Likewise for the north safe zone.
7. **The contest winner is the program that generates the move sequence yielding the highest number of crossings.**
8. For any additional questions or concerns, please feel free to ask in the comments section.
For some added incentive, I'll add a bounty of **+100 rep** to the winning program when I'm able to do so.
# Bonuses
**+2.5%** to the base score\* (up to +10%) for every corner of the playing grid the frog touches. The four corners of the grid are the leftmost and rightmost cells of the two safe zones.
**+25%** to the base score\* if your sequence of moves keeps the frog confined to within +/- 4 cells left or right of his starting cell for the entire simulation (he can of course move freely vertically).
No scoring bonus, but special props in the OP will go to anyone who posts a quick n' dirty solution validator so that I don't have to program one. ;) A validator would simply accept a sequence of moves, ensure its legality (per the rules and the traffic file), and report its score (i.e. the total number of crossings).
\*Total score is equal to base score plus the bonus, rounded down to the nearest integer.
### Good luck frogging!
[Answer]
# C++: 176
Output:
```
176
^^^^^^>vvvvvv>^^^^>^^>>>>>>><<<.vv>v<<<.vvv<<<<<<^.^.^.^.>.>^^<.>>>>>>v>v>.>v<<<<v.<.vv<<<<<^^.<^<<<<<<^.^^>>>>vv>.>.v<v.vv>>^>>^<^<<<<<<<^>.>^^<<<.>>>>>vv>v<vvv<<<<<^^.<^^^^.....vv>.>.>.>v<<vvv<<>>>>^>^<.<.^^>^^>>>>vv.>v<vv.v^>^<.<.<^<^>.>^^>>>>vv.v<<<<<<.vvv<<<<^^^<<v^^.>.^^..>>>>>>vv>.>.v.vvv>>>^>^^<<<<<<<<<^>.>^^>>>>vvv<<v.<.vv<<<<<<>>>>>^^^<<<^^^<<>>vv>.v<<>vvv<<><>>>>>>>^>^^<^^^<.>>>>>>>>vv>.>v<<<vvv<<<<<^^^<<v.<.<^<<^.^<<^...>>>>>>>>>>>>>vv>v<vvv<<<<<<<<^>^.<.^^>.>^^<<<<<<<..>>>>vv>.vvvv<<<<>^.v>>>^^.^^>^<^<>>>>>>>>>vv>vvvv<<<<^^^<^>^<<^.>>vv>v<vvv<<<<<<<>>>>>>>^>^^^.^^>>>>>vvv<<vvv<<<^^^^^^<vvv<<<<<<<vvv<<<>>>>>>>>^^.<.<.^.^.^<^<>>>>>>>>>>vvv<<.vvv<<<^^<^<<^^<<^<<<>>>>vv>.vvvv>>^>>^<.<.<^<<<<<.^^<<^.......>vv.>.>.>v<vvv>>>>>>^>^.<.<^<.^^^<.>>>>>>>vvv<<<v.<vv<<<^^<.<.<.<^<<<^>^^..........v<vvvv>v>>>>>^>>^^^>^^>>>vv>v<vvv<<<<<<<<>^^.<.<^<^^^<.........>vv.>.vvvv>>>>^^<.<.<^^^<^<<.v<v>.>.>.>.>.>.>.vvv.v<<<<<^^<^<^>.>.>.>.^<^.>>>>>>>>vv>v<<vvv<<>>>>>^^^.^.>^<^<<<<<<<<.vv.>.v<<<.vvv<>>>>>^>^.<.<.<.<^^.^<<^<.....>>vvv<.>>vvv<<<>>>>>>>>^^^<<<.^.>.>^^.>>>>>vv.>v<vvv<<<>>>>>>^>^<^<<^.^^<vvv<<<<<vv.v<>>>>>>>>>>^>^.^^>^^<<<<.>vv.>.vvvv>^>>^.<.<.<^<<<^>^^>>>vv>v<<<<<vvv<<<>>>>>^^<.<.<.<.<^<^>.^^.>>>>>vv>v<>vvv<<<<<<<^>^.<^<<<<<<<^^^.>>>>>vv>v<>vvv>>>^^<.<^<<<^>^^.>>>>vv>.v<<vvv<<<<<^^^<<<<<^>.^^<>>>>>>>vv>.>v<<vvv<<<<<<<>>>^>>.>^^^.>^^<>>>>>>vv>vv.<.<.vv>>>>^^<.<.<.<^<<^.>^^.>>>>>vv.>.>v<<vvv<<>>>>>^^<.<.<.^^>.>.>^^<<<<<<<<.>>>>>>vv>v<<v.<.<vv<<<<^^.<^<<<.^^^<.vv.>v<vvv<<<>>>>>>^>^<^<<^.^<^<<.>>vv>.>.>.>vvvv>>>>>>^>^^^^^<<<.vvv<<<<<<vvv>>>>>^>^<.<^<<^.>.>.^^>>>>vv>.>v<<<<<<vvv<<<<^^^<.^.>^^>>>>vvv<<v.vv<<<^>>^^<<<.^^<<^>>>>>>>>>vvv.v.vv<>>>>>^>^^<<<<<<<<<<<<<<<<^^^..>>>>>vv>.>.>.>v<<v.<.<.vv<<<<<^^^<^>.^^...>>>>>>>>vv.v<.vvv>>>^>^<.<^^^^>>>vv>v<<<vvv<<<<>>>>>>^>^.<.<^<^>.>^^.>>>>>vv.v<<<<<<<<vvv<<<<^^<^<<<<<><^>.>^^>>>>vv.>.>.vvv.v>>>>>>>^^<.<^<<^^^>>>vv>.>.>.>.>v<<v.<.<vv>>>>^^^<<<<<.^.>^^>>>vv>.>v<vvv<<<<^^<.<.<.^^>^^>>>vv>.>.v<<<v.<vv<<<<^^.<^<<<^^^>>>>vvvvvv<<<<<<<<>^^.^>>^^^<>>>>>>>vvv<<<v.vv>>>>>^>>^^<<<<<^>.^^>>>>vv>.>v<<<<vvv<<<^^<.<.<.<^<<<<<^>^^>>>>vv.>vv.v.v<^>.>^.<.^^^^>>>>vv>.>.>.v<<<<<<vvv>>>>^^<.<.<^<<^^<^>>>>>>vv>v<<.vvv^>^^<<<^>^^<<<<<<.vvv<<vv>.v>>>>>>^>.>^^<<<<<^>.>.>.>.>.^^>>>>vv>.>.>v<<<<<vvv<<<<^^<^<<^.^^>>>>vv>.>.>.>v<vvv<<<<<^^.<.<^<<^^^>>>>>>>>>>>vv>.>.>.>.>vvvv<<<<^^.<.<^<^^^<<<<<<vvv<v.<vv<<<<^v>>>>>>>>>>^^^<.^.>.>.^^>>>>vvv<<<<<<<vvv<<<<<<<>^^.<^<.^^^.>>>>vv>v<vvv<>>>>^^.<.^.^.>.^<^>>>>>>>>vvvv.<.<vv<<<<^^^<<<<<^>.^^<.vv>.v<<vvv<<><>>>>>^>>^.<^<^^^<<<.>>vv>.>v<<<<v.vv>^>>^.<^^.^^.>>>>>vv>.>.>.v<v.<vv<<<<<^.^^^.>^^<>>>>>>vv>.v<<<v.<vv<<<<>>>>>>>>>>>^^<.<.<.<.<^<<^^<^<<<>>>>>>>vv>v<<<vv.v>>>>>>>>^>^<.<^<<<<<<<<<<<.^.>^^<<<vvv.v.<vv<<<^.>>^.<^^.>.>^^<<......vv.v>vvv>>>^.v^>>^^<<^^^<.>>>>>>>vvv<v.<.<.vv<<<<^^<.<.<.^^^^<.>>>>>>>>vvv<v.<vv^.>^^<<^^^vv>vvvv^>>>>>>>^^^^^vvvvvv^^^^^^vvvvvv>>>>
```
There are under 8 million states combinations of position X time X set of visited corners, so they can be exhaustively searched in less than 1 second. If the code has no bugs, it should be impossible to beat. The optimal strategy was to use the whole board, as that allows froggy to cross the road 160 times, versus about 120 when confined to the center. Visiting the corners didn't cost any crossings since the traffic was so heavy.
```
/* feersum 2014/9
https://codegolf.stackexchange.com/questions/37975/frogger-champion */
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <cstring>
#define B(F, CST, X, Y) best[ ((F)*NCST + (CST)) * BS + (Xmax-Xmin+1) * ((Y)-Ymin) + (X)-Xmin]
#define TL(i) ((int)t[i].length())
#define ABSPEED(I) (speed[i]<0?-speed[i]:speed[i])
#define errr(X) { cout<<"ERROR!!!!!!!!"; return X; }
#define DRAW 0
#if DRAW
#include <unistd.h>
#endif
using namespace std;
int bc(int cs) {
int c = 0;
while(cs) {
c += cs&1;
cs >>= 1;
}
return c;
}
int main()
{
const bool bonusTwentyfive = false;
const int COLS = 23, T_ROWS = 5, YGS = T_ROWS + 2, XGS = COLS + 2;
string t[5];
int speed[] = {-4, 1, -2, -1, 4};
ifstream f("t.txt");
for(int i = 0; i < T_ROWS; i++)
getline(f, t[i]);
if(f.fail())
return 1;
f.close();
//for(int i = 0; i < 5; i ++)t[i]="xxx";
char g[XGS][YGS];
int mov[][3] = { {-1, 0, '<'},
{+1, 0, '>'},
{ 0, -1, '^'},
{ 0, +1, 'v'},
{ 0, 0, '.'} };
int Ymin = 0, Ymax = YGS-1;
const int Xstart = 11, Xmaxmove = bonusTwentyfive ? 4 : 10;
const int Xmin = Xstart - Xmaxmove, Xmax = Xstart + Xmaxmove;
const int NCST = bonusTwentyfive ? 1 : 1<<4;
int maxfr = 0;
for(int i = 0; i < T_ROWS; i++) {
if(speed[i] < 0) {
for(int m = 0, n = t[i].length()-1; m < n; ++m,--n)
swap(t[i][m], t[i][n]);
}
int carslen = TL(i);
for(char*c = &t[i][speed[i]>0?TL(i)-1:0]; carslen; carslen--, speed[i]>0?--c:++c)
if(*c != ' ')
break;
if(carslen)
maxfr = max(maxfr, ( (carslen + COLS) * 2 + ABSPEED(i)-1 ) / ABSPEED(i));
}
const int BS = (Xmax-Xmin+1)*(Ymax-Ymin+1);
int *best = new int[(maxfr+1)*NCST*BS];
memset(best, 0xFF, (maxfr+1)*NCST*BS*sizeof(int));
memset(g, ' ', sizeof(g));
B(0, 0, Xstart, Ymax) = 0;
for(int fr = 0; fr < maxfr; fr++) {
for(int r = 0; r < T_ROWS; r++) {
for(int x = 0; x < XGS; x++) {
int ind = speed[r] > 0 ? TL(r)-1 + x - fr*speed[r]/2 : x - (XGS-1) - fr*speed[r]/2;
g[x][r+1] = ind >= 0 && ind < TL(r) ? t[r][ind] : ' ';
}
}
for(int x = Xmin; x <= Xmax; x++) {
for(int y = Ymin; y <= Ymax; y++) {
if(g[x][y] != ' ')
continue;
for(unsigned m = 0; m < sizeof(mov)/sizeof(mov[0]); m++) {
int X = x + mov[m][0], Y = y + mov[m][1];
if(X < Xmin || X > Xmax || Y < Ymin || Y > Ymax)
continue;
if(!(mov[m][0]|mov[m][1]) && y > 0 && y > T_ROWS && g[x][y-speed[y-1]/4] != ' ')
continue;
int csor = ((X==Xmin|X==Xmax)&(Y==Ymin|Y==Ymax)&!bonusTwentyfive) << ((X==Xmax) + 2*(Y==Ymax));
for(int cs = 0; cs < NCST; cs++) {
int N = B(fr, cs, x, y);
if(!~N)
continue;
if((!(N&1) && y == 1 && Y == 0) ||
(N&1 && y == T_ROWS && Y == T_ROWS+1))
++N;
if(N > B(fr+1, cs|csor, X, Y))
B(fr+1, cs|csor, X, Y) = N;
}
}
}
}
}
int score = 0, xb, yb, cb, nb;
for(int x = Xmin; x <= Xmax; x++) {
for(int y = Ymin; y <= Ymax; y++) {
for(int cs = 0; cs < NCST; cs++) {
if(B(maxfr, cs, x, y) * (40 + bc(cs)) / 40 >= score) {
score = B(maxfr, cs, x, y) * (40 + bc(cs)) / 40;
xb = x, yb = y, cb = cs, nb = B(maxfr, cs, x, y);
}
}
}
}
char *mvs = new char[maxfr+1];
mvs[maxfr] = 0;
for(int fr = maxfr-1; fr >= 0; --fr) {
for(int r = 0; r < T_ROWS; r++) {
for(int x = 0; x < XGS; x++) {
int ind = speed[r] > 0 ? TL(r)-1 + x - fr*speed[r]/2 : x - (XGS-1) - fr*speed[r]/2;
g[x][r+1] = ind >= 0 && ind < TL(r) ? t[r][ind] : ' ';
}
}
for(int x = Xmin; x <= Xmax; x++) {
for(int y = Ymin; y <= Ymax; y++) {
if(g[x][y] != ' ')
continue;
for(unsigned m = 0; m < sizeof(mov)/sizeof(mov[0]); m++) {
int X = x + mov[m][0], Y = y + mov[m][1];
if(X < Xmin || X > Xmax || Y < Ymin || Y > Ymax)
continue;
if(!(mov[m][0]|mov[m][1]) && y > 0 && y > T_ROWS && g[x][y-speed[y-1]/4] != ' ')
continue;
int csor = ((X==Xmin|X==Xmax)&(Y==Ymin|Y==Ymax)&!bonusTwentyfive) << ((X==Xmax) + 2*(Y==Ymax));
for(int cs = 0; cs < NCST; cs++) {
int N = B(fr, cs, x, y);
if(!~N)
continue;
if((!(N&1) && y == 1 && Y == 0) ||
(N&1 && y == T_ROWS && Y == T_ROWS+1))
++N;
if(X==xb && Y==yb && N == nb && (cs|csor) == cb) {
mvs[fr] = mov[m][2];
xb = x, yb = y, nb = B(fr, cs, x, y), cb = cs;
goto fr_next;
}
}
}
}
}
errr(3623);
fr_next:;
}
if((xb-Xstart)|(yb-Ymax)|nb)
errr(789);
#if DRAW
for(int fr = 0; fr <= maxfr; ++fr) {
memset(g, ' ', sizeof(g));
for(int r = 0; r < T_ROWS; r++) {
for(int x = 0; x < XGS; x++) {
int ind = speed[r] > 0 ? TL(r)-1 + x - fr*speed[r]/2 : x - (XGS-1) - fr*speed[r]/2;
ind >= 0 && ind < TL(r) ? g[x][r+1] = t[r][ind] : ' ';
}
}
g[xb][yb] = 'F';
for(int y = 0; y < YGS; y++) {
for(int x = 0; x < XGS; x++)
cout<<g[x][y];
cout<<endl;
}
cout<<string(XGS,'-')<<endl;
usleep(55*1000);
for(int i = 0; i < 5; i++) {
if(mvs[fr] == mov[i][2]) {
xb += mov[i][0];
yb += mov[i][1];
break;
}
}
}
#endif
cout<<score<<endl;
cout<<mvs<<endl;
}
```
] |
[Question]
[
There’s already been a question about [simulating the Monty Hall Problem](https://codegolf.stackexchange.com/q/12693). This one is different. The *user* will *play* the Monty Hall Problem. Your program will play the role of the host. Montybot, if you like.
Here are the steps:
1. Pick (randomly) which of the three doors hides the prize.
2. Output a visual display of three doors. A simple `ABC` will do. Or three squares. Or whatever.
3. Receive input choosing one of the doors. This could be a mouse click on the chosen door, or a single letter input (`B`) or whatever.
4. Open another door. You do not open the chosen door. You do not open the door hiding the main prize. That *may* mean you have no choice, or it *may* mean that you have a choice of two. If you have a choice of two, pick one at random. Visually indicate that the door has been opened and that no prize was hidden behind it. For a program text-based input/output, this could be as simple as outputting `AB0`, to show that door `C` has been opened. Feel free to be more inventive. If you’re doing a GUI program, your choice of display is up to you.
5. Accept input from the user. The user may input `stick` or `switch` (or, for a GUI program, click on buttons, or use a select input, or whatever). If the user enters anything other than `stick` or `switch`, the implementation is undefined. Do whatever you want.
6. Output the text `You won!` or `You lost`.
7. Terminate the progam.
Rules:
1. When you have to choose something *at random*, don’t worry about cryptographic randomness. Any `rand()` function will do.
2. The program must not cheat. The prize must be in place before the game starts. That is to say that the steps must be performed in the order given: *First* choose a door behind which to hide your prize, *then* ask the player to choose. The choice of which door to open in step 4 must happen in step 4: it is not selected in advance.
3. The output in step 6 must be honest.
4. This is code golf. Shortest code wins.
[Answer]
# APL, 77
```
p←?3⋄d[e[?⍴e←(⍳3)~p,c←⍞⍳⍨⎕←d←3↑⎕A]]←'_'⋄⎕←d⋄⎕←'You','lost' 'won!'[(c=p)=5=⍴⍞]
```
Needs `⎕IO←0`. Tested on Dyalog.
**Explanation**
```
p←?3 ⍝ p(rize) is a random number between 1 and 3
⎕←d←3↑⎕A ⍝ d(oors) is the string 'ABC'; output it
c←d⍳⍞ ⍝ ask for one of the letters; c(hoice) is its position
o←e[?⍴e←(⍳3)~p,c] ⍝ o(pen) is a random position except for p and c
d[o]←'_' ⍝ replace the o position in the d string with a '_'
⎕←d ⍝ output the modified d string
w←(c=p)=5=⍴⍞ ⍝ get choice, if it's stick (5 chars) and c=p, or neither, (w)in
⎕←'You','lost' 'won!'[w] ⍝ print the result
```
**Examples**
```
p←?3⋄d[e[?⍴e←(⍳3)~p,c←⍞⍳⍨⎕←d←3↑⎕A]]←'_'⋄⎕←d⋄⎕←'You','lost' 'won!'[(c=p)=5=⍴⍞]
ABC
A
AB_
stick
You lost
p←?3⋄d[e[?⍴e←(⍳3)~p,c←⍞⍳⍨⎕←d←3↑⎕A]]←'_'⋄⎕←d⋄⎕←'You','lost' 'won!'[(c=p)=5=⍴⍞]
ABC
A
AB_
stick
You won!
```
[Answer]
## Python, 157
```
from random import*
C=choice
I=raw_input
p='\n> '
a='ABC'
g=C(a)
i=I(a+p)
print'You '+'lwoosnt!'[(i==g)^('w'in I(a.replace(C(list(set(a)-{g,i})),'_')+p))::2]
```
Example:
```
$ python monty.py
ABC
> A
AB_
> switch
You won!
```
[Answer]
# PowerShell: 192 174
**Changes from original:**
>
> * **-8 Characters** Since the visual display of doors can be "whatever" I realized that I could save some characters (particularly,
> the apostrophes required to define strings) by using numbers instead
> of letters.
> * **-8 Characters** By specifically choosing single-digit, prime numbers to represent the doors I could use the shorter modulo operator
> instead of an actual comparison operator when I needed to match doors
> to figure out the host's possible choices or the player's door swap.
> ([Briefly explained
> here.](https://codegolf.stackexchange.com/a/21848/9387))
> * **-2 Characters** Swapping the win/loss responses in the final if/else statement allowed me to use the modulo trick there also.
>
>
>
**Golfed Code**
```
$w=($d=3,5,7)|random;357;$p=read-host;-join$d-replace($h=$d|?{$_%$w-and$_%$p}|random),0;if((read-host)-match'w'){$p=$d|?{$_%$p-and$_%$h}}if($p%$w){'You lost'}else{'You won!'}
```
**Un-Golfed Code With Comments**
```
# Set up an array of doors ($d), and choose one to be the winner ($w).
$w=($d=3,5,7)|random;
# Show doors.
357;
# Get input and save player's choice ($p).
$p=read-host;
# Join the doors into one string, replacing the host's choice ($h) with a zero, and display them again.
-join$d-replace
(
# Host will randomly choose a door from those which are not evenly divisible by $w or $p.
$h=$d|?{$_%$w-and$_%$p}|random
),0;
# Get input from player. If it contains a 'w', switch doors.
# While this is generally a sloppy way to distinguish 'switch' from 'stick', it is allowed by the rules.
# "If the user enters anything other than stick or switch, the implementation is undefined. Do whatever you want."
if((read-host)-match'w')
{
# Player will switch doors to one which is not evenly divisible by the $h or the original $p.
$p=$d|?{$_%$p-and$_%$h}
}
# Announce the result.
# If $p is not evenly divisible by $w, player has lost. Otherwise, they have won.
if($p%$w){'You lost'}else{'You won!'}
# Variables cleanup - not included in golfed code.
rv w,d,p,h
```
[Answer]
## Javascript, 221 197
```
(function(q,r,s,t,u,v){f='ABC';d=[0,1,2];b=q()%3;a=r(f);d.splice(a,1);(a==b)?(r(f[d[q()%2]])==t)?s(u):s(v):(r(f[d[(d[0]==b)+0]])!=t)?s(u):s(v)})(Date.now,prompt,alert,'stick','You won!','You lost')
```
It uses two calls to Date.now() for randomness with a prompt in between to guarantee a delay. The user input is a 0-based index (the rule did say "whatever"). The following alert says which door was opened. Here's a slightly longer version that gives the answer before the user picks, to verify that it doesn't cheat:
```
(function(q,r,s,t,u,v){f='ABC';d=[0,1,2];b=q()%3;s('ans:'+b);a=r(f);d.splice(a,1);(a==b)?(r(f[d[q()%2]])==t)?s(u):s(v):(r(f[d[(d[0]==b)+0]])!=t)?s(u):s(v)})(Date.now,prompt,alert,'stick','You won!','You lost')
```
Fiddle: <http://jsfiddle.net/acbabis/9J2kP/>
**EDIT:** Thanks dave
[Answer]
# PHP >= 5.4, 195 192
```
$r=[0,1,2];unset($r[$p=rand(0,2)]);$d='012';echo"$d\n";fscanf(STDIN,"%d",$c);unset($r[$c]);$d[array_rand($r)]='_';echo"$d\n",!fscanf(STDIN,"%s",$s),'You '.($s=='switch'^$c==$p?'won!':'lost.');
```
Output:
```
012
1
01_
stick
You won!
```
] |
[Question]
[
Santa's elves need help in determining if their current batch of presents will fit into santa's sleigh. Write the shortest program possible in the language of your choice to help them out.
## Constraints
* Santa's sleigh measures 6ft wide by 12ft long and is 4ft deep.
* Presents may be fragile, so they may not be stacked on top of each other.
* You can rotate and flip the presents as you wish, but Santa's quite an obsessive-compulsive chap so keep the rotations to multiples of 90 degrees.
* North Pole health and safety regulations stipulate that presents may not stick out more than 1ft above the top of a sleigh (therefore they may not be more than 5ft high).
## Input
Input will be on `STDIN` and will be one integer representing the number of presents in the batch followed by a list of the presents' dimensions - 1 present per line, 3 dimensions (in feet) separated by spaces.
Examples:
```
1
6 12 5
6
1 12 3
1 12 4
1 12 1
1 12 5
1 12 3
1 12 5
1
4 3 13
1
6 12 6
```
## Output
Output should just be the word 'YES' if the presents can be packed into the sleigh or 'NO' if they cannot.
Output for the above examples:
```
YES
YES
NO
NO
```
## Test scripts
As before, I've appropriated some test scripts written by [Joey](https://codegolf.stackexchange.com/users/15/joey) and [Ventero](https://codegolf.stackexchange.com/users/84/ventero) to create some tests for this task:-
* [Bash](http://www.garethrogers.net/tests/sleighpacking/test)
* [PowerShell](http://www.garethrogers.net/tests/sleighpacking/test.ps1)
Usage: `./test [your program and its arguments]`
## Rewards
Each entry which I can verify that meets the spec, passes the tests and has obviously had some attempt at golfing will receive an upvote from me (so please provide usage instructions with your answer). The shortest solution by the end of the 2011 will be accepted as the winner.
[Answer]
## Haskell, 312 318 chars
```
import Data.List
s(ξ:υ:_,λ:σ:η:_)(x:y:_,l:w:_)=(ξ+λ<=x||ξ>=x+l||υ+σ<=y||υ>=y+w)&&ξ+λ<7&&υ+σ<13&&η<6
y p l=[(v,r):l|v<-[[x,y,0]|x<-[0..5],y<-[0..11]],r<-permutations p,all(s(v,r))l]
main=do
n<-readLn
p<-mapM(fmap(map read.words).const getLine)[1..n]
putStr.r$foldr((=<<).y)[[([9,0],[0..])]]p
r[]="NO"
r _="YES"
```
For some reason that I don't fully understand at the moment, it doesn't finish your tests #9 and #16 in reasonable time. But you didn't say anything about performance, did you?
---
## 373 383 chars
This version runs *much* faster for the examples: it first checks if it's not impossible simply because the area is too small, and then it starts with the largest parcels rather then inserting them in the given order. Note that the area detection is not perfect: it doesn't consider rotations, so it may on some inputs give wrong results. But it does work with the test script.
```
import Data.List
s(ξ:υ:_,λ:σ:η:_)(x:y:_,l:w:_)=(ξ+λ<=x||ξ>=x+l||υ+σ<=y||υ>=y+w)&&ξ+λ<7&&υ+σ<13&&η<6
y p l=[(v,r):l|v<-[[x,y,0]|x<-[0..5],y<-[0..11]],r<-permutations p,all(s(v,r))l]
π=product
main=do
n<-readLn
p<-mapM(fmap(map read.words).const getLine)[1..n]
putStr$if sum(map(π.init)p)>72||null(foldr((=<<).y)[[([9,0],[0..])]].sortBy((.π).compare.π)$p)then"NO"else"YES"
```
[Answer]
## Python, 461 chars
```
import sys
def L(P,z):
if not P:return 1
for w,h in[P[0],P[0][::-1]]:
m=sum((2**w-1)<<i*6for i in range(h))
for x in range(7-w):
for y in range(13-h):
n=m<<y*6+x
if z&n==0and L(P[1:],z|n):return 1
return 0
for G in sys.stdin.read().split('\n\n'):
S=[(x,y)if z<6 else(x,z)if y<6 else(y,z)if x<6 else(9,9)for x,y,z in[sorted(eval(g.replace(' ',',')))for g in G.split('\n')[1:]if g]]
print'YES\n'if sum(x*y for x,y in S)<73and L(S,0)else'NO\n'
```
`L` recursively checks if the rectangles in `P` can be put in the sleigh, where `z` is a bitmask of cells that are already occupied. The `S` assignment determines which way is up for each of the packages (largest dimension <= 5 goes vertically).
The code is potentially exponential, but it is quick on all the test inputs.
[Answer]
## GolfScript, 130 characters
```
"NO":g;~](;3/127{128*64+}12*\{.,0>.!{"YES":g;}*{([{[~@]..[~\]\}3*;]{)6<{~[2\?(]*128base 83,{2\?1$*.4$&0={3$|2$f}*}%;}*}%;}*;;}:f~g
```
It took quite some time to get it running in GolfScript. Any attempt to golf it further broke some of the test cases.
Please be warned that this version may become incredibly slow if you run it with too many presents.
] |
[Question]
[
This is an extension of [Simulate a Minsky Register Machine (I)](https://codegolf.stackexchange.com/questions/1864). I'm not going to repeat all of the description there, so please read that problem description first.
The grammar in part (I) was as simple as possible, but results in rather long programs. Since this is a code golf site, we'd rather have a golfed grammar, wouldn't we?
At a high level, the changes from the original grammar are as follows:
* The label on the first line is optional
* Whitespace is optional except where required to separate two adjacent identifiers
* States can be inlined. To ensure non-ambiguous parsing, if the first state of a decrement operation is an inlined state, it must be enclosed in parentheses. This means that any program can be golfed into a one-liner.
For example, in the original test cases we had:
b+=a, t=0
```
init : t - init d0
d0 : a - d1 a0
d1 : b + d2
d2 : t + d0
a0 : t - a1 "Ok"
a1 : a + a0
a=3 b=4
```
In the golfed grammar this could be shortened to:
```
init:t-init d
d:a-(b+t+d)a
a:t-(a+a)"Ok"
a=3 b=4
```
or even:
```
init:t-init d:a-(b+t+d)a:t-(a+a)"Ok"
a=3 b=4
```
The new BNF for the "program" lines (as opposed to the final line, which is data) is:
```
program ::= first_line (newline line)*
first_line ::= cmd
line ::= named_cmd
state ::= state_name
| cmd
| '"' message '"'
delim_state::= '(' cmd ')'
| '"' message '"'
cmd ::= raw_cmd
| named_cmd
named_cmd ::= state_name ' '* ':' ' '* raw_cmd
raw_cmd ::= inc_cmd
| dec_cmd
inc_cmd ::= reg_name ' '* '+' ' '* state
dec_cmd ::= reg_name ' '* '-' ' '* delim_state ' '* state
| reg_name ' '* '-' ' '* state_name ' '* delim_state
| reg_name ' '* '-' ' '* state_name ' '+ state
state_name ::= identifier
reg_name ::= identifier
```
Identifiers and messages are flexible as in the previous challenge.
---
All of the test cases from the previous challenge are still applicable. In addition, the following golfed Josephus solution should exercise most of the grammar:
```
in:k-(r+t+in)in2:t-(k+in2)r-(i+n-0"ERROR n is 0")"ERROR k is 0"
0:n-(i+2:k-(r+t+2)5:t-(k+5)7:i-(r-(t+7)c:t-(i+r+c)i+0)a:t-(i+a)7)"Ok"
n=40 k=3
```
Expected output:
```
Ok
i=40 k=3 n=0 r=27 t=0
```
And I think this covers the remaining case:
```
k+k-"nop""assert false"
k=3
```
Expected output:
```
nop
k=3
```
---
You may assume that all programs will have sensible semantics. In particular, they will have at least one state and will not redefine a state. However, as before, a state may be used before it is defined.
The scoring is a variant on code-golf. You can write a self-contained program and it will score as the length of the program in bytes after UTF-8-encoding. Alternatively, because code reuse is a Good Thing, if you have implemented part (I) in `n1` bytes, you can write a program which turns a part (II) program into a part (I) program, ready for piping to the original. Your score will then be the length of your transformation program plus `ceil(n1 / 2)`.
NB If you opt for the transformation, you will need to generate names for the anonymous states in such a way that you guarantee that they don't clash with named states.
[Answer]
# Haskell, ~~552~~ ~~499~~ 493 characters
```
import Control.Monad.RWS
import Data.Map
main=interact$z.lines
z x=let(s:_,w)=evalRWS(mapM(q.t)x)w[]in s.f.i.t$last x
p=get>>=q
q(l:":":x)=x%do a<-p;tell$f[(l,a)];r a
q(v:"+":x)=x%fmap(.a v 1)p
q(v:"-":x)=x%liftM2(d v)p p
q(('"':s):x)=x%r(\w->unlines[init s,do(v,x)<-assocs w;v++'=':show x++" "])
q(n:x)|n<"*"=x%p|1<3=x%asks(!n)
d v p n w|member v w&&w!v>0=p$a v(-1)w|1<3=n w
t[]=[];t x=lex x>>= \(y,x)->y:t x
i(v:_:x:t)=(v,read x):i t;i[]=[]
x%m=put x>>m;r=return;a=insertWith(+);f=fromList
```
Did more or less a full rewrite. Replaced CPS with a RWS monad which reads its own output to look up states it hasn't parsed yet (yay for laziness!), plus some other tweaks.
] |
[Question]
[
The task is to find a way to draw a horizontal line in an array of 16-bit integers.
We're assuming a 256x192 pixel array with 16 pixels per word. A line is a contiguous run of set (1) bits. Lines can start in the middle of any word, overlap any other words, and end in any word; they may also start and end in the same word. They may not wrap on to the next line. Hint: the middle words are easy - just write 0xffff, but the edges will be tricky, as will handling the case for the start and end in the same word. A function/procedure/routine must take an x0 and x1 coordinate indicating the horizontal start and stop points, as well as a y coordinate.
I exclude myself from this because I designed a nearly identical algorithm myself for an embedded processor but I'm curious how others would go about it. Bonus points for using relatively fast operations (for example, a 64 bit multiply or floating point operation wouldn't be fast on an embedded machine but a simple bit shift would be.)
[Answer]
This code assumes that both x0 and x1 are inclusive endpoints, and that words are little endian (i.e. the (0,0) pixel can be set with `array[0][0]|=1`).
```
int line(word *array, int x0, int x1, int y) {
word *line = array + (y << 4);
word *start = line + (x0 >> 4);
word *end = line + (x1 >> 4);
word start_mask = (word)-1 << (x0 & 15);
word end_mask = (unsigned word)-1 >> (15 - (x1 & 15));
if (start == end) {
*start |= start_mask & end_mask;
} else {
*start |= start_mask;
*end |= end_mask;
for (word *p = start + 1; p < end; p++) *p = (word)-1;
}
}
```
[Answer]
## Python
The main trick here is to use a lookup table to store bitmasks of the pixels. This saves a few operations. A 1kB table is not that large even for an embedded platform these days
If space is really tight, for the price of a couple of &0xf the lookup table can be reduced to just 64B
This code is in Python, but would be simple to port to any language that supports bit operations.
If using C, you could consider unwinding the loop using the `switch` from [Duff's device](http://en.wikipedia.org/wiki/Duff%27s_device). Since the line is maximum of 16 words wide, I would extend the `switch` to 14 lines and dispense with the `while` altogether.
```
T=[65535, 32767, 16383, 8191, 4095, 2047, 1023, 511,
255, 127, 63, 31, 15, 7, 3, 1]*16
U=[32768, 49152, 57344, 61440, 63488, 64512, 65024, 65280,
65408, 65472, 65504, 65520, 65528, 65532, 65534, 65535]*16
def drawline(x1,x2,y):
y_=y<<4
x1_=y_+(x1>>4)
x2_=y_+(x2>>4)
if x1_==x2_:
buf[x1_]|=T[x1]&U[x2]
return
buf[x1_]|=T[x1]
buf[x2_]|=U[x2]
x1_+=+1
while x1_<x2_:
buf[x1_] = 0xffff
x1_+=1
#### testing code ####
def clear():
global buf
buf=[0]*192*16
def render():
for y in range(192):
print "".join(bin(buf[(y<<4)+x])[2:].zfill(16) for x in range(16))
clear()
for y in range(0,192):
drawline(y/2,y,y)
for x in range(10,200,6):
drawline(x,x+2,0)
drawline(x+3,x+5,1)
for y in range(-49,50):
drawline(200-int((2500-y*y)**.5), 200+int((2500-y*y)**.5), y+60)
render()
```
[Answer]
Here is a C version of my Python answer using the switch statement instead of the while loop and reduced indexing by incrementing a pointer instead of the array index
The size of the lookup table can be substantially reduced by using T[x1 & 0xf] and U[x2 & 0xf] for a couple of extra instructions
```
#include <stdio.h>
#include <math.h>
unsigned short T[] = {0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001,
0xffff, 0x7fff, 0x3fff, 0x1fff, 0x0fff, 0x07ff, 0x03ff, 0x01ff,
0x00ff, 0x007f, 0x003f, 0x001f, 0x000f, 0x0007, 0x0003, 0x0001};
unsigned short U[] = {0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff,
0x8000, 0xc000, 0xe000, 0xf000, 0xf800, 0xfc00, 0xfe00, 0xff00,
0xff80, 0xffc0, 0xffe0, 0xfff0, 0xfff8, 0xfffc, 0xfffe, 0xffff};
unsigned short buf[192*16];
void clear(){
int i;
for (i=0; i<192*16; i++) buf[i]==0;
}
void render(){
int x,y;
for (y=0; y<192; y++){
for (x=0; x<256; x++) printf("%d", (buf[(y<<4)+(x>>4)]>>(15-(x&15)))&1);
printf("\n");
}
}
void drawline(int x1, int x2, int y){
int y_ = y<<4;
int x1_ = y_+(x1>>4);
int x2_ = y_+(x2>>4);
unsigned short *p = buf+x1_;
if (x1_==x2_){
*p|=T[x1]&U[x2];
return;
}
*p++|=T[x1];
switch (x2_-x1_){
case 14: *p++ = 0xffff;
case 13: *p++ = 0xffff;
case 12: *p++ = 0xffff;
case 11: *p++ = 0xffff;
case 10: *p++ = 0xffff;
case 9: *p++ = 0xffff;
case 8: *p++ = 0xffff;
case 7: *p++ = 0xffff;
case 6: *p++ = 0xffff;
case 5: *p++ = 0xffff;
case 4: *p++ = 0xffff;
case 3: *p++ = 0xffff;
case 2: *p++ = 0xffff;
case 1: *p++ = U[x2];
}
}
int main(){
int x,y;
clear();
for (y=0; y<192; y++){
drawline(y/2,y,y);
}
for (x=10; x<200; x+=6){
drawline(x,x+2,0);
drawline(x+3,x+5,1);
}
for (y=-49; y<50; y++){
x = sqrt(2500-y*y);
drawline(200-x, 200+x, y+60);
}
render();
return 0;
}
```
[Answer]
## Scala, 7s / 1M lines 4.1s / 1M lines
```
// declaration and initialisation of an empty field:
val field = Array.ofDim[Short] (192, 16)
```
first implementation:
```
// util-method: set a single Bit:
def setBit (x: Int, y: Int) =
field (y)(x/16) = (field (y)(x/16) | (1 << (15 - (x % 16)))).toShort
def line (x0: Int, x1: Int, y: Int) =
(x0 to x1) foreach (setBit (_ , y))
```
After eliminating the inner method call, and replacing the for- with a while-loop, on my 2Ghz Single Core with Scala 2.8 it absolves 1 Mio. Lines in 4.1s sec. instead of initial 7s.
```
def line (x0: Int, x1: Int, y: Int) = {
var x = x0
while (x < x1) {
field (y)(x/16) = (field (y)(x/16) | (1 << (15 - (x % 16)))).toShort
x += 1
}
}
```
Testcode and invocation:
```
// sample invocation:
line (12, 39, 3)
// verification
def shortprint (s: Short) = s.toBinaryString.length match {
case 16 => s.toBinaryString
case 32 => s.toBinaryString.substring (16)
case x => ("0000000000000000".substring (x) + s.toBinaryString)}
field (3).take (5).foreach (s=> println (shortprint (s)))
// result:
0000000000001111
1111111111111111
1111111100000000
0000000000000000
0000000000000000
```
Performance testing:
```
val r = util.Random
def testrow () {
val a = r.nextInt (256)
val b = r.nextInt (256)
if (a < b)
line (a, b, r.nextInt (192)) else
line (b, a, r.nextInt (192))
}
def test (count: Int): Unit = {
for (n <- (0 to count))
testrow ()
}
// 1 mio tests
test (1000*1000)
```
Tested with the unix tool time, comparing the user-time, including startup-time, compiled code, no JVM-start-up phase.
Increasing the number of lines shows, that for every new million, it needs an extra 3.3s.
] |
[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 4 years ago.
[Improve this question](/posts/23/edit)
The Fizz Buzz problem is a very basic problem to solve that is used by some to weed out interviewees that don't know how to program. The problem is:
```
Set N = [0,100]
Set F = x in N where x % 3 == 0
Set B = x in N where x % 5 == 0
Set FB = F intersect B
For all N:
if x in F: print fizz
if x in B: print buzz
if x in FB: print fizzbuzz
if x not in F|B|FB print x
```
The object of this modification of the Fizz Buzz problem is to perform the above algorithm using C++ templates such that as few runtime operations are necessary as can be done.
You can reduce N to a smaller range if you need to in order to fit within TMP objects where necessary.
This isn't expected to be a "golf".
[Answer]
Here's my attempt (had it lying around for a day or so, because I was unsure whether it was fit as a solution). Surprisingly the only bit I incorporated from @Chris was changing `template<int N, int m3, int m5>` to `template<int N, int m3=N%3, int m5=N%5>`
```
#include <iostream>
using namespace std;
template<int N, int m3=N%3, int m5=N%5>
struct fizzbuzz_print {
static void print() {
cout << N << '\n';
}
};
template<int N, int m5>
struct fizzbuzz_print<N, 0, m5> {
static void print() {
cout << "fizz\n";
}
};
template<int N, int m3>
struct fizzbuzz_print<N, m3, 0> {
static void print() {
cout << "buzz\n";
}
};
template<int N>
struct fizzbuzz_print<N, 0, 0> {
static void print() {
cout << "fizzbuzz\n";
}
};
template<int N>
struct fizzbuzz:public fizzbuzz<N-1> {
fizzbuzz<N>() {
fizzbuzz_print<N>::print();
}
};
template<>
struct fizzbuzz<1> {
fizzbuzz<1>() {
fizzbuzz_print<1>::print();
}
};
int main() {
fizzbuzz<100> t;
}
```
Additionally, since this is my first attempt at TMP, any suggestions on improving my code would be appreciated.
[Answer]
Totally non-golfed solution:
```
template <int n, int m3 = n % 3, int m5 = n % 5>
struct FizzBuzz {
static int value() {return n;}
};
template <int n, int m5>
struct FizzBuzz<n, 0, m5> {
static char const* value() {return "Fizz";}
};
template <int n, int m3>
struct FizzBuzz<n, m3, 0> {
static char const* value() {return "Buzz";}
};
template <int n>
struct FizzBuzz<n, 0, 0> {
static char const* value() {return "FizzBuzz";}
};
```
Sample test code:
```
#include <iostream>
int
main()
{
std::cout << FizzBuzz<1>::value() << '\n'
<< FizzBuzz<2>::value() << '\n'
<< FizzBuzz<3>::value() << '\n'
<< FizzBuzz<4>::value() << '\n'
<< FizzBuzz<5>::value() << '\n'
<< FizzBuzz<13>::value() << '\n'
<< FizzBuzz<14>::value() << '\n'
<< FizzBuzz<15>::value() << '\n'
<< FizzBuzz<16>::value() << '\n';
}
```
[Answer]
Okay, I finally got around to taking a shot at this. Unlike the previous solutions my solution builds the entire output string at compile time and the only run-time call is a single call to `cout`'s `<<` operator. I'm using `boost::mpl` to keep the code somewhat manageable.
```
#include <boost/mpl/string.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/char.hpp>
#include <boost/mpl/if.hpp>
using namespace boost::mpl;
using std::cout;
template<int n> struct IntToString {
typedef typename push_back<typename IntToString<n/10>::str, char_<'0'+n%10> >::type str;
};
template<> struct IntToString<0> {
typedef string<> str;
};
template<int n> struct FizzBuzzHelper {
typedef typename push_back<typename IntToString<n>::str, char_<'\n'> >::type intstring;
typedef typename if_< bool_<n%15==0>, string<'fizz','buzz','\n'>,
typename if_< bool_<n%5==0>, string<'buzz','\n'>,
typename if_< bool_<n%3==0>, string<'fizz','\n'>,
intstring>::type >::type >::type str;
};
template<int n> struct FizzBuzz {
typedef typename insert_range<typename FizzBuzz<n-1>::str,
typename end<typename FizzBuzz<n-1>::str>::type,
typename FizzBuzzHelper<n>::str>::type str;
};
template<> struct FizzBuzz<0> {
typedef string<> str;
};
#include <iostream>
int main() {
cout << c_str<FizzBuzz<9>::str>::value;
return 0;
}
```
Sadly the code will blow up with `boost::mpl::string` complaining about too-large strings when using any `n` greater than 9.
[Answer]
362 characters.
```
#include <iostream>
#include <string>
using namespace std;
template<int N>
struct S {
static string s, f, l;
};
template<int N>
string S<N>::s =
N > 9
? S<N / 10>::s + S<N % 10>::s
: string(1, '0' + N);
template<int N>
string S<N>::f =
N % 15
? N % 5
? N % 3
? s
: "fizz"
: "buzz"
: "fizzbuzz";
template<>
string S<0>::l = f;
template<int N>
string S<N>::l = S<N - 1>::l + "\n" + f;
int main() {
cout << S<100>::l << endl;
return 0;
}
```
] |
[Question]
[
Your input is a ragged list of possibly empty lists of non-negative integers. For example, `[[2,0],[[]],[[[],[1],[]],[]]]` is a valid input. This input is a "compressed" ragged list. What this means is that when we have a list of numbers, we interpret those as a list of indices, indexing the output.
For example, if `I=[[2,0],[[]],[[[],[1],[]],[]]]` then the decompressed list is `O=[[[[],[[]],[]],[[]],[[[],[[]],[]],[]]]`, because if we replace `[2,0]` with `O[2][0]=[[],[[]],[]]` and `[1]` with `O[1]=[[]]` in the input list, we get `O` as the output.
The naïve method is just to have the input as a working list and then iteratively replace lists of numbers with by indexing the working list. However this runs into two potential problems:
First, consider an input like `I=[[1,0,0,0],[2],[[[[]]]]]`. Here if we index this input like so: `I[1][0][0][0]` we will get an index error. We would have to first replace `[2]` with `I[2]` giving `tmp=[[1,0,0,0],[[[[]]]],[[[[]]]]]`. Now we can replace `[1,0,0,0]` with `tmp[1][0][0][0]` giving `O=[[],[[[[]]]],[[[[]]]]]` as the output.
Another difficulty is that we can get a form of co-recursion with inputs like `[1],[[0,1],[]]`. This decompresses to `[[[],[]],[[],[]]]`
Full blown infinite recursion like `[[0]]` or `[[1],[[0],[0]]]` won't happen though.
# Rules
Your input is a ragged list `I` that may contain lists consisting of only numbers. Your task is to find a ragged list `O`, containing only lists, where if you replace every list `L` of numbers in `I` by `O[L]` you get `O` as the output. Your program must output `O`. You may assume that a unique solution exists.
You can choose between 0- and 1-based indexing. You can also choose the order of the indices, i.e. whether `[2,3,4]` corresponds to `O[2][3][4]` or `O[4][3][2]`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins.
# Examples
```
[] -> []
[[],[[],[]]] -> [[],[[],[]]]
[[[],[]],[[0],[0]],[[1],[1]]] -> [[[],[]],[[[],[]],[[],[]]],[[[[],[]],[[],[]]],[[[],[]],[[],[]]]]]
[[[],[[],[],[[]]]],[0,1,2]] -> [[[],[[],[],[[]]]],[[]]]
[[1,0,0,0],[2],[[[[]]]]] -> [[],[[[[]]]],[[[[]]]]]
[[1],[[],[0,0]]] -> [[[],[]],[[],[]]]
[[1],[[2,0,2],[0,0],[]],[[1],[0]]] -> [[[],[],[]],[[],[],[]],[[[],[],[]],[[],[],[]]]]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~94~~ ~~90~~ ~~87~~ ~~86~~ 85 bytes
```
f=(x,n,s=(g=y=>y[0]>=' '?n=y.map(b=>e=e[b]||0,e=x)<e.map?e:y:y.map(g))(x))=>n?f(s):s
```
[Try it online!](https://tio.run/##bZHBboQgEIbvPsXeHLqsCx63Re89tIceKemiRWNj0chmo8k@TJ@lL2ZBDdG2EGD4@WaGgQ95lSbvqvZy0M27GseCQY81NgxKNrBk4EQkLPz@ClPNhuhTtpCxRDHFM3G7EaxYjx6U01N1Gk4zUSIEPUIs0WkBBp3MeB@cAy52h2THRcC5wNMQYpZWe3s4W1YhdiKTRe1EPe0Bb8y@TvlH2io@xbR3y4QRTHG8TrA9Xq5GMXHdCvGSTWxq8Dj3qegSy7n9KcDXPFGxjR0v6ALQ@QnWfivX9TP8km3Uc9Sptpa5giNEd8iFcOuxxPCGJc7s/@SNNk2toropAWTPHl@enyJz6SpdVsUABairrEEi2/bhqw73GbYUyxAKxh8 "JavaScript (Node.js) – Try It Online")
After `y[0]>=` is U+00A0
[Answer]
# [Python 2](https://docs.python.org/2/), 138 bytes
```
def f(x):
def g(y):y[:]=h(x,y)if[]<y<[f]else map(g,y)*0+y
h=lambda z,y:h(x,z+y)if[]<z<[f]else(h(z[y[0]],y[1:])if y[1:]else z[y[0]]);g(x)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVBBboMwEFSvvGKVk2mcCHOqaNKPWD5QgYMlBxC4VcwT-oVecqn6pvY1XRvXIW2EsGdnZ3bX-_7ZW9N0bX4-f7wYuXn4eqtqCZKc0iIBBw_EpoXlhdg35ERtqiQXO7vjUtR6rOFY9uSA9H22tgk0e10en6sSJmoLp5_WwTH9OkhDJm55JgS1nBUC0-CBLxdS6eMBJwgTGXXsu8HAaMdEdgNoUK0LtqOpVLsd6rLSqq1H4kYGRTvY-7Hq11JTvR17rQxZweYJVmmKin5QrSHqArsLlMhjCxV6n7_vei6clYuEc0H9L8RMLWJMzgiZDI_MI4YHi-ooiGD2OuYGdc3EFj52l5dllNF82eA6HUZjNHMfEnnoJq7eEOU8tmKhlrP9e0B8s1flWDsP0iBg8wqWvoV1uYY_NFadN_8D)
"Decompresses" the list in-place.
Function `g` does the main recursion. Function `h` looks ahead to resolve individual multi-step compressions where needed. The main purpose of function `f` is to put `x` in the closures of `g` and `h`.
[Answer]
# [Clojure](https://clojure.org/), 126 bytes
```
#(loop[a %](letfn[(g[x](let[y(get-in a x)](cond(=[]x)x(coll? y)y(every? coll? x)(mapv g x)1 x)))](if(= a(g a))a(recur(g a)))))
```
[Try it online!](https://tio.run/##bVLRboQgEHy/r9h4abIk2oqPl9zdhxAeiKKxoWoVL/r1dgFjsK0GnB1mdoWlNP3nPOoNK11DvV3R9P0gFLxJNNrWncBGLB6LFRtts7YDBQuTWPZdhXchF7YQNuYJK1tRv/S4PiEQC8MvNbygIcRpMLK1Nd5BYQOKMYWjLucxBPRs7IJVP@lvEFZPFsQlERKyBwiZEBQy9UPKQEaxXw6YuJym3CNOEz/0h@AAwe2Yf6gzExXxjPt4YZ7ytIhLnJeP3@Np7l6iir2iPO3kMIioHN/zOeOfbUR797qC8he7eJfwcBSxMzLHx/GLdnnl5UaNJx81vZ@tBNdOGLWqssmObdcAluH@vIf4YxpMa8E375pkj4Qxkk@ANbQdk5QQB9JZ01EMTuDyQnJLgG6FU1LoLsIP "Clojure – Try It Online")
[Answer]
# Python3, 353 bytes:
```
from itertools import*
S=str
g=lambda x:[x]if x and int==type(x[0])else[j for k in x for j in g(k)]
def r(v,p):
for i in p:
try:
l=v
for x in i:
l=l[x]
v=eval(S(v).replace(S(i),S(l)))
except:return 0
return [0,v][all(i in'[], 'for i in S(v))]
f=lambda x:i[0]if(i:=[l for i in permutations(g(x),len(g(x)))if(l:=r(eval(S(x)),i))])else i
```
[Try it online!](https://tio.run/##dVPBjpswED2Xrxjlgl25EaSXCsn9hF5ydK3K2ZjUuwYs24vI16czhKVk2xUCz7z3xjNjM@Gafw/9128h3m5tHDpw2cY8DD6B68IQ8@fiKFOOxUV6053OBqZGTdq1MIHpz@D6LGW@BssmVWlufbLqGdohwgtyKCLzmcwLe@G6ONsWIhtF4E0xc464gA7keKUFvBxpIXIi0s0owh4TkzlKOxrPjmzk@2iDN08WHcfFkXnOOUrs9GRDbqLNr7GHqoDFUpUYtTLeM0pbKi2gXIug/bDC9m@jDltyLXONVH5TrI3dazbZDX1iFzZx4W0/G5yj2jcysqVAhITDTedzAXdLcrfbFUrDl@@gdKGwgPnV@g5tfCRr8ipRbwV3dqtakQo/1WxRRP1vyLtYQv4DPSJritmnZZZhVeKwTfBIvzUgKnoQOCzZ9EOnq1ytqeplLwr7uOdZdcC9D4t0EdT3I9jGbUK3x/AO1pou5v7Hg0m5WG@7dR4ngv0Yeisg7VPwLrPyZ19y/IM/GQEnkNCZwDBq72l6jP9F1y/AvampHNSjPCWcLmiZ4SAlnIoQcYBYmW3KCQLR55Lf/gA)
] |
[Question]
[
Consider the Tetris pieces, but made out of some number of ([hyper](https://en.wikipedia.org/wiki/Hypercube))cubes instead of four squares, where two blocks are considered the same if one is a rotation, reflection, or translation of another. The goal of this challenge is to take two positive integer input values, `n` and `k`, and count the number of \$n\$-celled polyominoes consisting of \$k\$-dimensional hypercubes.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code wins.
---
# Example
For example, when \$n = 4\$ and \$k = 3\$ there are seven different shapes:







Notice that the first piece could be made using \$1\$-cubes (line segments) instead of cubes, the next four could be made using \$2\$-cubes (squares), and only the last two require \$3\$-cubes (ordinary cubes). Thus \$p(4,1) = 1\$, \$p(4,2) = 5\$, and \$p(4,3) = 7\$.
---
# Test Data
```
n | k | p(n,k)
---+---+--------
1 | 0 | 1
2 | 0 | 0
2 | 1 | 1
3 | 2 | 2
4 | 1 | 1
4 | 2 | 5
4 | 3 | 7
4 | 4 | 7
4 | 5 | 7
5 | 4 | 26
6 | 3 | 112
7 | 3 | 607
8 | 2 | 369
```
[Answer]
# Python 2, 338 335 330
[Try it online!](https://tio.run/##ZVPBcpswED1bX7GTC4Jgj3Fsp22GS249MZMrZTIMFq5ikBRJdHCb9tfdlURMZnJgeLv73mNXWtTZ/pRic2nkgUEOURSRS6tlD9wybaXsDPBeSW0TItJTzoUaLI1JkZe0XFfJKY0r8pTrWhwZPcWEjay5KfI/PRfUDqpj1KCWHehvrmhSluPSVVTcSg0jcAGqclA52FZx7AuvvsB0P9jacilMUFN5S3UaT6TWk7Q8DI11ziotlyN88J2NX6sgkS4oPMc4KD3UCMup15JXt2NCeZ6/eAV3tCcPXzy8fmCZpVnFWxDSegeQfx9ukn9LQZTmwkLHBC3iiztPYpmxz01tmMETLvtaUWSkZmVUxy2N3qI4nptCBWTwBmt8MgKbCa4DzEL2Dl8u3BDYztntlN0F6Ej3AW5nuAtwN2U3ewL7iZxl6Hc/Bfs1sr5Mjnf7r9jXe8M/RIS3TsJeAJfvyJwNIfL4bOxBDhZnxcQqBIS4AXGD0sYNOZ/IN7KYWJjO0Wz1eMbq94Iaq2mJCry8KyfYfiBhya0cuPUlC83M0HmGsHSWrI7M/qq7gdFPVtduySLcm28xDUZkURuDfwE0kOcQcpf/ "Python 2 – Try It Online")
```
from itertools import*
n,k=input()
O=[([0]*k,)]
R=range(k)
exec"O={min(tuple(sorted(zip(*[[x-min(p)for x in p]for p in f])))for q in permutations(zip(*(o+(r,))))for f in product(*[[p,[-x for x in p]]for p in q]))for o in O for s in o for r in[tuple(s[i]+x*(i==j)for i in R)for j in R for x in-1,1]if not r in o};"*~-n
print len(O)
```
Reads n,k as a list from stdin (e.g. `[4,2]`) and prints the number of polyominoes.
Starts with a single polyomino with a single cell at the origin.
`n-1` times, replaces the polyominoes with all possible polyominoes created by adding an adjacent cell to an existing polyomino, and canonizing that polyomino by finding the minimum of all possible rotations of it.
-6 bytes thanks to math junkie, -2 bytes thanks to Surculose Sputum.
] |
[Question]
[
[Tichu](https://en.wikipedia.org/wiki/Tichu) is a card game in which players take turn playing sets of cards from a deck consisting of a standard 52-card deck, plus 4 additional cards:
* the **dragon**, which has a greater value than any other card
* the **phoenix**, which can act as a wildcard
* the **dog**, which passes the turn to your partner
* the **Mah Jong**, which has value 1 (and the person holding it plays first)
The first player (who is said to have "lead") can choose to play one of the following types of card combinations:
* a **single** (e.g. `6`)
* a **pair** (`JJ`)
* a **triple** (`555`)
* a **full house** (`QQQ33`) - a triple and a pair
* a **straight** (`56789`) - 5 or more consecutive cards
* a **tractor** (`223344`) - any consecutive sequence of pairs
Subsequent players are then only allowed to play a set of cards of the same type, but strictly higher. For example, `QQ` can be played on top of `JJ`, but `QQKK` cannot (it is a tractor, not a pair). Full houses are ordered by the triple (e.g. `77722` > `44499`), and straights and tractors must be the same length (`456789` cannot be played on top of `23456`). Aces are high.
There is one exception: any 4 of the same card is a **bomb**, and can be played on top of anything except a higher bomb.1
The dragon can be played by itself on top of any single or with lead (but nowhere else). The phoenix, aside from being a wildcard, can also be played on top of any single except the dragon.2 The dog can only be played by itself with lead and immediately ends the turn.3
---
Your challenge is to determine whether a given Tichu play is valid, given the previous play.
You may accept both plays in any order as either lists of integers or strings -- in either case, you may choose any mapping of cards to integers/characters.
If there was a previous play, it will always be valid, and if not (i.e. the player has lead), the first input will be the empty array/string (matching the type of the other input). The cards are not guaranteed to be given in any particular order.
Your output must be selected from a set of exactly two distinct values, one of which indicates the play is legal and one that indicates it is not.
There is no need to test for whether the set of cards actually exists in the deck (e.g. `77766` followed by `88877` is impossible because there are only four 7's) -- such cases will never be given.
In the following test cases, `234567890JQKA` represent 2 through ace, and `RPD1` represent the dragon, phoenix, dog, and Mah Jong respectively. The empty string is shown here as `-`. These plays are legal:
```
6 J
JJ QQ
555 KKK
44499 77722
23456 56789
223344 QQKKAA
49494 72727
A R
A P
P R
66 7P
P6 77
58304967 6P0594J7
5P304967 680594J7
57446765 788657P5
- D
- 1
- 12345
3344556677889900 JJJJ
5555 7777
```
And these are not:
```
9 3
66 55
888 444
44 888
77722 44499
44499 777
44499 777JJJ
45678 34567
34567 456789
556677 334455
5566 778899
72727 49494
A A
R A
R P
77 RP
77 6P
P7 66
680594J7 5P304967
6P0594J7 58304967
57446765 3645P536
1 D
2 D
2 1
- 1234
7777 5555
- 223355
```
---
1: actually, a straight flush is also a bomb, but since this is the only place in the game that the suit of the cards matter, I have chosen to leave it out for simplicity's sake
2: the value of the phoenix played on top of a card with value *n* is actually *n+0.5* (a phoenix on a 9 is a 9 and a half); since this requires knowledge of additional history to adjudicate, no test cases involve a single played on top of a single phoenix
3: so the first input will never be dog
[Answer]
# JavaScript (ES6), ~~274~~ 273 bytes
Takes input as `(a)(b)`, where \$a\$ and \$b\$ are arrays of integers with:
* \$1\$ = dog
* \$3\$ = Mah Jong
* \$4..16\$ = 2 ... Ace
* \$18\$ = dragon
* \$19\$ = phoenix
Returns *false* for valid or *true* for invalid.
```
a=>b=>!(L='length',[A,B]=(g=a=>(h=n=>--n?[i=1,2,3,'(20*)3|30*2','1{5,}','22+',4].some(p=>m=o.join``.match(`9(0*)(${p})0*$`,i++),a.map(x=>o[x-19?x:x=n]=-~o[x],o=[...9e16+'']))?[i,m[1][L]+(m[3]||[])[L]]:h(n):[])(18))(a),[C,D]=g(b),a+a?A-C?C>7|+b>a:a[L]==b[L]&D>B|A<3&b==18:C)
```
[Try it online!](https://tio.run/##bVNdb9owFH3vr2CoauzGifJlJ0ZzUAovBbSlfdhLZomEpkBVEjTQhFS6v85sZ@SDQSTCOce@vj738Jb@TneLX@vt3ijKl/z0yk4pCzMWfgEzpr3nxXK/0lASoQfOwJIJDaxYwULDKIbJmtnIQS7SgGPdQ/foWveOhjT7A6NP8XYcXUMeN3flJgdbFm5Yab6V62I@NzfpfrECcwrEPnD7sf2E1v3tHK11HaJUqFtwYGGZHAybDg@DAys4M/4IzFHJEtM0aW4TXdM4hKILtElsnsy4DjaJy4/HhEOB@GAFCjgQANgBhCCFKBmhMWdLkIlD9HQYGaPhKPSPehamg1RsYSwT33fj8OEYfXXvMsbsYDCCJ9FPj/V2PRb25OE7rjpcSNw3xobtuB4mfkCtydM0Mp7jvrkuXvLD91ewgPBmn@/2YjtIUS@Dcs@iLHble26@l0vwCmSpVPQn3xkU62/aupb8iGaPY65VdUCf9FGvP@mf4WQi8dNTTWCMJTOdTmvK8zxKJen7vuPUtOpa0qr3hnZc1/OqqtNpFDVlqHhUGUc8NR1J6rkL4xrGXZWoA/2WXhFNORy4lkeJL2kSW5h6k5YYt8TgUvQ9j/hEXd8PAoL9GNeiJMcdZHeRdKNmpAMYE@KLOpRalvJcfNou43@Oyga6I/tZJI/fLsam/HcvfMDNiUEQSEaMqjU2yUjhzFTzq5ZRenW@V8l25yqpqhn5q7mxQrJ0Nw2VC2q98qQjVOWlRU2LKhuyjkpLJxVNlJ6vwLh1TRWaS4K0UlMRpPHzHAbp6jkktRi3xOBCbKfGJR6OsduUtbuxca7A/2PUHld1JsbdIMq/mKROfwE "JavaScript (Node.js) – Try It Online")
### How?
To evaluate a hand, we build an array `o[]` made of a leading \$9\$, initially followed by 16 zeros:
```
// D - 1 2 3 4 5 6 7 8 9 T J Q K A
o = [ 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
```
For each card rank in the hand, the corresponding slot in `o[]` is incremented. Once joined back to a string, we can apply the following regular expressions to detect each type of hand:
```
hand | pattern | full regex | example
-------------+-------------+-------------------------+-------------------
single | 1 | /9(0*)(1)0*$/ | 90000100000000000
pair | 2 | /9(0*)(2)0*$/ | 90000002000000000
3-of-a-kind | 3 | /9(0*)(3)0*$/ | 90003000000000000
full house | (20*)3|30*2 | /9(0*)((20*)3|30*2)0*$/ | 90020000030000000
straight 5+ | 1{5,} | /9(0*)(1{5,})0*$/ | 90000111110000000
tractor | 22+ | /9(0*)(22+)0*$/ | 90000000000022200
bomb | 4 | /9(0*)(4)0*$/ | 90000000000000004
```
If the hand does not trigger any of these regular expressions, it's invalid.
The value of the hand is given by the number of zeros just after the leading \$9\$ (the higher, the better). A special case is a full house where the rank of the triple is higher than that of the pair, in which case we need to add the length of the `(20*)` pattern.
The phoenix (i.e. the wildcard) is simply replaced with each possible card rank, starting with the highest one, until a match is detected.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~466~~ ~~455~~ ~~403~~ ~~401~~ 399 bytes
```
R=lambda H,n=3:n==len(H)*(len({*H})<2)and[15]!=H[1:]
s=lambda H:[H[2:],H[:1]][R(H[:3])]
def n(J,K):j,k=[[16in H,R(H,4),len(H)>4and all(15!=t>T-2for t,T in zip(H,H[1:])),[R(H[2:])*R(H[:2],2),R(H[3:],2)][R(H[:3])],R(H),R(H,2),R(H,1),1].index(1)for H in[J,K]];return k!=7and[17]==J or[j==k*[J<K,s(J)<s(K)][2<j<5],J<K][k==1]
f=lambda P:any(n(*[sorted([L,i][i>0]for i in H)for H in P])for L in range(16))
```
[Try it online!](https://tio.run/##fVNdT9swFH3PrzDsoXZlUPPhfK1GqoSmKOEhVLxZFsrWdISWtEqCNIb47Z2vU5xQ0Bqp9T3n@pz7ke5fuodd7R4OS74tnn6uCpTQmrtxzfm2rHFCphh@X6fJG5k7pKhXwmbyjCfCjqXVmkuxSIQTS5qI2JZSLLE6uJJIa1WuUY1TmpH4kW64ELZf1cpEZVCP0N7kylPCqNhusc3OeHd1d@Gsdw3q6B1SyX@rvUrWjoRQra2syFSbOJI6BNSEG8Nx5A2opo4Z1CbUlpdVvSr/YJuAQ6L0hSpOyu9N2T03Ndqc8UB3GUjOU7RrxCPnm6lI5xltcUrmLc6UiTN/nDNJFSrFhnNbWuv3WeRxUb/gGk9Fu2u6coXFDa2kqK5mEiwraCkx7iiX@nwD56aof5fY9gk5wNw6FbfboivvH1RJGL5IbCH1ORYrJrntuB7zgzCapbfZYnl9Mblcqw5xRZBxg4vS0qvoyrbD@23xQlH5Z1/@UvUdJY3Z6h54xJE49e8lH0ASUqS@923fVHWHT64TzRVtWzYdWn9iEefGn6Lz17cYvb6dXyr5p@JTfZa126hyjuMFMh61cdc8l8Sq/5fyo9i2pZbBYuJPKJqkE0n6ME0hvr01AGMMkCzLDOR5XhQBGASB4xhYTx5gPf8BdlzX83rVLFssBplIPVrGUY@BFwAtP4a5CfOPrK8NgxHfA4McC92ZF/kBwH4@Y5GXjsh8RIanZOB5fuDr9oMw9FmQM0NeAHr9MbRPQhiIgWAIjPl@oKSiaDbTY1ef8aDZcai6BtihgvWgXQDqUceMDUgYhgCprQxYP3BgDNQvq0@MonHqsM2v0WOVRwK2q2uC04D3vWlCdzoy1usFY71wg@vNLoZ4@VWcjxvQu/@E@CMk7xF/NK/3tcLU3tc9sPmIDU/Z8Rvg@h7LmTtSts0r0MfOV7E9xOal@LCT3pqNB6YT4W@jwcPhHw "Python 3 – Try It Online")
Input is list of hands where hand is list of integers1 with the following value mapping:
* 0: Phoenix
* 1: Mah Jong
* 2-13: 2 to Ace
* 14: Dragon
* 15: Dog
* 16: Empty string
---
1: Although in the linked TIO tests are expressed with list of strings due to convenience which are translated according to value mapping before calling `f`
] |
[Question]
[
I feel tired to do "find the pattern" exercise such as
```
1 2 3 4 (5)
1 2 4 8 (16)
1 2 3 5 8 (13)
```
Please write a program that finds the pattern for me.
Here, we define the pattern as a recurrence relation that fits the given input, with the smallest score. If there are multiple answers with the same smallest score, using any one is fine.
Let the \$k\$ first terms be initial terms (for the recurrence relation, etc.), and the \$i\$'th term be \$f(i)\$ (\$i>k,i\in\mathbb N\$).
* A non-negative integer \$x\$ adds\$\lfloor\log\_2\max(|x|,1)\rfloor+1\$ to the score
* The current index \$i\$ adds \$1\$ to the score
* `+`, `-`, `*`, `/` (round down or towards zero, as you decide) and `mod` (`a mod b` always equal to `a-b*(a/b)`) each add \$1\$ to the score
* For each initial term \$x\$, add \$\lfloor\log\_2\max(|x|,1)\rfloor+2\$ to the score
* \$f(i-n)\$ (with \$n\le k\$) adds \$n\$ to the score. E.g. Using the latest value \$f(i-1)\$ add \$1\$ to the score, and there must be at least 1 initial term.
* Changing the calculation order doesn't add anything to the score. It's fine if you write `1+i` as `1 i +`, `+(i,1)` or any format you like.
Samples:
```
input -> [score] expression
1 2 3 4 -> [1] f(i) = i
1 2 4 8 -> [5] f(1) = 1, f(i) = f(i-1)+f(i-1)
1 2 3 5 8 -> [9] f(1) = 1, f(2) = 2, f(i) = f(i-1)+f(i-2)
```
Shortest program in each language wins. It's fine if your program only solve the problem theoretically.
[Answer]
# [Python](https://www.python.org), 554 bytes
```
lambda s:next((s[:i],x)for n in N()for i in R(A(s))if(b:=sum(map(lambda k:A(bin(abs(k)))-1,s[:i])))<n for x in X(n-b,i)if all(E(s,x,j)==s[j]for j in R(i,A(s))))
E=lambda s,x,i:x if int==type(x)else i+1if"i"==x else s[i-x[1]]if"@"==x[0]else.5if(r:=E(s,x[2],i))==0else[(l:=E(s,x[1],i))+r,l-r,l*r,l//r,l%r]["+-*/%".index(x[0])]
A=len
R=range
def X(k,i):
for x in["i",0]*(k==1)+[["@",k]]*(k<=i)+[[op,l,r]for a in R(1,k-1)for r in X(k-a-1,i)for l in X(a,i)for op in"+-*/%"if k>2]:yield x
for n in R(2**(k-1),2**k):yield n
def N(k=0):
while 1>0:k+=1;yield k
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZLBatwwEIahRz-FWQhI9jhreZOQulHoHpJjDjkVVB1sVk600mqN7VDvs_SyUNp3ap-mI2kTCDnIHn0a_vn12z__9Ifpee-Ov-75998vU1dc__uU2WbXbpp0rJ2aJ0JGUWsJM-32Q-pS7dIHEmrt60eyJiOluiNtzceXHdk1PTkJmHpNWu1I047EUEoLBkELyxuXeonZS3wjrmhBo0baWEvuyAgzbCnno9hK37WNgzSEUZQmd_zVInbqGlU6bJk4nw69IjNVdlSpzpnuFnrB-ZwGMApdzIJJifirx6KU_uD8Et0PNQ-DRSXRCg4v_ZEg9pWzwPMBbIErw7Vc4uNskGKRF9nybHGu3UbNxMtSmay5VS555EPjnlSyUR3e06BEnbzdXKA7KGVGDOeM5kKgLTDSgxuuPdj3YGEIITQxBAamYCH-IWZnigZz1QHZiJrTdt_j_mQOEzK3lawPWtlNOkcTLmpWGU5EVcDC0FOLC54f0FvpPf941lal7LasTc7Zl9hj4i_z96kfMH5yTwSDClZwgZ84eccu4PoDW8HlB7qCK2DlO-jRZ2AVwjjueIzv_w)
*running the test-cases takes approximately 30 seconds*
*The running time is at exponential in the score, so the program may take extremely long to finish if the sequence has a score of more than 10*
Output format:
1. array of initial values
2. expression for remaining values
* `i`: index, integers -> constants
* `["@",k]` -> `f(i-k)` (for k any integer)
* `[op,l,r]` -> `l op r` (l,r expressions; op operation)
Uses `%` for mod (I can change it if it is a problem)
for example: `([1, 1], ['+', ['@', 1], ['@', 2]])` -> `f(1)=f(2)=1, f(i)=f(i-1)+f(i-2)`
## Explanation
Go through all expressions in order of score
`expressions(k,i)` (golfed: `X`) generates all expressions with score `k` and `i` initial elements
`check` and `evaluate` (golfed: in-lined/`E`) evaluate the expression to check if it generates the sequence
The main function goes through all expressions ordered by score and returns the first expression that computes the sequence.
ungolfed version:
```
def evaluate(seq,expr,i):
if type(expr)==int:
return expr
if expr=="i":
return i+1
if expr[0]=="@":
return seq[i-expr[1]]
if expr[0]=="+":
return evaluate(seq,expr[1],i)+evaluate(seq,expr[2],i)
if expr[0]=="-":
return evaluate(seq,expr[1],i)-evaluate(seq,expr[2],i)
if expr[0]=="*":
return evaluate(seq,expr[1],i)*evaluate(seq,expr[2],i)
if expr[0]=="/":
return evaluate(seq,expr[1],i)//evaluate(seq,expr[2],i)
if expr[0]=="%":
return evaluate(seq,expr[1],i)%evaluate(seq,expr[2],i)
def check(seq,n_initTerms,expr): ## check if expr is an expression for this sequence
try:
for i in range(n_initTerms,len(seq)):
if not evaluate(seq,expr,i)==seq[i]:
return False
return True
except:
return False
def expressions(k,i):
if k==1:
yield "i"
if k<=i:
yield ["@",k]
if k>2:
for a in range(1,k-1):
for op in "+-*/%":
for l in expressions(a,i):
for r in expressions(k-a-1,i):
yield [op,l,r]
for n in range(2**(k-1),2**k):
yield n
if k==1:
yield 0
def find(seq):
n=1;
while True:
for i in range(len(seq)-1):
base_score=sum(map(lambda k:len(bin(abs(k)))-2,seq[:i]))
if base_score<n:
for expr in expressions(n-base_score,i):
if check(seq,i,expr):
return (seq[:i],expr)
n+=1
```
---
# [Python](https://www.python.org), 613 bytes
```
lambda s:min((sum(map(L,s[:i]))+S(s,x),k,s[:i],x)for k in range(2**sum(map(L,s)))if all(E(s,x:=B(k//A(s),i:=k%A(s)),j)==s[j]for j in range(k%A(s),A(s))))[2:]
I=int
A=len
L=lambda k:A(bin(abs(k)))-1
S=lambda s,x:L(x)-1if I==type(x)else 1if"i"==x else x[1]if"@"==x[0]else S(s,x[1])+S(s,x[2])+1
E=lambda s,x,i:x if I==type(x)else i+1if"i"==x else s[i-x[1]]if"@"==x[0]else.5if(r:=E(s,x[2],i))==0else[(l:=E(s,x[1],i))+r,l-r,l*r,l//r,l%r]["+-*/%".index(x[0])]
B=lambda k,i:[q:=(k-i)//3,"i"if k==0else["@",k]if k<=i else[q,-q][r]if(r:=(k-1)%3)<2else["+-*/%"[q%5],B(I((r:=bin(q//5))[2::2],2),i),B(I("0"+r[3::2],2),i)]][1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZLPauMwEMahRz-FMRhG8biK7Wbpigo2gRQCufWo1cGhTleR48Z2Cu6z7CVQ2nfafZod2cn2Tw6ypZ9G33yj0e-33fP-12N1eLmVP1-f9uv4-u9FUebb1X3ut2JrKoD2aQvbfAdLbJUwmrHoDlrsGNoB0HT92PjWN5Xf5NVDAelo9OEQY8ys_bwsYe7OCTkDy_kUWoZGSBu6GcMNk7JVG-2kNu9Swzb2MYypVGhvIU2196ayLCpvKY9erZjCitzmqxYsRcaJd3fac0mX0BEjHwsp98-7gpZF2RY-ocAEUnZ-v-xUoon8cESNdc_6aokf61YpzRJv_kGd6uj8c20TfVFvlYmd0tcUlxOzhkbI-VEfDaPbGLstBeWJJz2PGixjGiManNMnbLQKonjEw-DSVPdFB06WaW_2_27In6qFBBsbxnmG5Inc2lMK8oJWO3IjTe9U1RjXWjV68EUHExZm7CYd4odsqg4nGmewABfjLr_mfNI3SVANKbWX9dvBOIgalb1TramY4bX9edg11E64BZVgihle0QPzPrErvD5jGU7OaIbfMBl_gg59x4Q6xoZ0h8Pw_wc)
[ungolfed version](https://ato.pxeger.com/run?1=jVW7btswFN06-CsuHBigLAmKHQQohBDo0o6ZshlCIFuUTYimZJLK41u6ZGk_qn_SrZekZEfqS5Pscw_v81zy6_fm1Rxq-fb2rTVl_PHHh5-Civy4LXKoUsEk2XJJ8q0mVRAE8RquQO9qxaAugUvD9kzNZgUrPUo0O0XspVFBOgPgJZjXhhEHUIp0iwIoZlolQXiDJ9qflM75fEBZXYyb6wztn4Z2Z1hlAxamBfMwXiaLIXeYIJ4KwhG0Rmjlq2FPuWhzczFGfEpJFv5XPTz8X0UYb8PjLsNsTA5H5Y-zxDOYaPg7vrb42Fs8yVs80dtykrflRG_JJG9JMtHdYpK7xd-8OU3sDmxXOYt85JKbB6aOulM7wNWVJ_RxgWvIvSKY1ryWUNYKzAFhdNEyuWOYkVGvPjFr5Fa6Kpd7Rt5HsEuIR4LAM11lsjZ_1CilTkBZTz1X_CUXmr1vwYNq7X_2smPNUMSeOtON4Ka_CmRKUOvuLpDBZp2m2Jd1EFlsfj0PO_ymw7uGbVsuis-YGKku61NRej0IhzvSWe4oH1g2uBxRZZegiinHzylStEqSm6ha3PgzauztdMZXAzy2BkVdUeSUJLdWIuc4_rrYnBa3WXTJ2moHEx8gTieZr6_ksnCTsZHuqW6P5Jg3RERuWohJ2s8O_9SNofehdDeAnXb1btpLsl4u73HCVkb6ULeigC0Dkas9Aybrdn-IoGd1H3jmQoxZ2HODImPQqHqv8iM81xIB1BGXKJVOgwwRbXa5Ztr1CMdj-yqxr9IBWzQ9uttxWNUm5VkQhHz4CnDDc-GCeHfu7hsOf9bp9rJD3G8O7kgBRKf0EnJ0LQfBXd0r1HdRz3ppa0q6rKL-LelmirwI7bafrdzXomQFPDHlFtFTdFeCTQCZrTD-Bewewv5B_AU)
[Answer]
# Python3, 1488 bytes:
A rather long approach, but designed to be fast, especially on [more common](https://www.tanyakhovanova.com/RecursiveSequences/RecursiveSequences.html) recursive sequences. Explanation of notation coming soon.
```
from math import*
E=enumerate
def V(s,e):
e,W=e
if[0,0]==e[:2]:return all(i==e[-1]for i in s)
if[0]==e[:1]:return all(a==e[1]*i+e[2]for i,a in E(s,1))
return all(sum(N*s[i-(W-I)-1]for N,(I,_)in e[0])+i*e[1]+e[2]==a for i,a in E(s,1)if i>max(W-j for _,(j,_)in e[0]))
def C(s,c=[]):
if[]==s and c:yield c;return
if s:yield from[*C(s[1:],c+[s[0]]),*C(s[1:],c)]
I=lambda V,i:{(0,V),(V//i,V%i)}
def W(x,y):
t=[[x,1,0],[y,0,1]]
while t[-1][0]:q=t[-2][0]//t[-1][0];r=t[-2][0]%t[-1][0];t+=[[r,t[-2][1]-q*t[-1][1],t[-2][2]-q*t[-1][2]]]
return t[-2]
def D(a,b,x,y,g):
q=[(0,1,x,y),(0,-1,x,y)]
while q:
m,d,X,Y=q.pop(0);m+=d
if all([X,Y]):yield(X,Y)
J,K=x+m*(b/g),y-m*(a/g)
if abs(X)+abs(Y)>abs(J)+abs(K)or 0==all([X,Y]):q+=[(m,d,J,K)]
def f(s):
for O in range(1,len(s)):
for J in sorted(C([*E(s)][:O][::-1]),key=len):
if len(J)==1:
yield([0,s[O]//(O+1),s[O]%(O+1)],O)
for u in I(s[O]%J[0][1],O+1):
j=s[O]//J[0][1]
yield([[(1,J[0])for _ in range(j)],*u],O);yield([[(j,J[0])],*u],O)
else:
q=[(J[0][1],[(1,J[0])],J[1:],s[O])]
while q:
x,R,S,v=q.pop(0)
if[]==S:
for u in I(v,O+1):yield([R,*u],O)
continue
y=S[0][1]
for i in range(v-1):
if 0==(v-i)%gcd(x,y):
g,a,b=W(X:=max(x,y),Y:=min(x,y))
G=(v-i)//g;A,B=[b,a][x>y]*G,[a,b][x>y]*G;
A,B=min(D(X,Y,A,B,g),key=lambda x:sum(map(abs,x)))
q+=[(v-i,[(A*z,l)for z,l in R]+[(B,S[0])],S[1:],i)]
def F(s):
for i in f(s):
if V(s,i):return i
```
[Try it online!](https://tio.run/##bVRbb@I4FH7nV/ilkh0OCwmE0iBXmrvKSINUJNrKikYBDDVLAiShA7va3949xw6XdgYR5eRcvu/c7M2hfF5n7d4mf32d5@uUpUn5zEy6WeelV/sidbZLdZ6UujbTczbmBWgR1ZiGB6lrzMxVC1qxlFpFQRzlutzlGUtWK25I1/Dj@TpnhpmMFcK5O2f/jXNCOj/2TF2rwIVAQkFfkM8XGHnhXOxS/sMrlGnwh8adqDh@AL@DnwJjNHKIuvEI0eJJmbDfMM2cmds02SPG0lp/Al9eAAhb7yf0nUoVU8mYPEIVLMlmbBodjF7hu@8SIysrKiW1UXkYqvwohmldFQgYCzirRFy7k6skncwSNgYT/ctbMBbAx82mgfGVEf9Z9ge@hwNRl1KpPfjYaVAHaIEfxzX269msNCupyYgfbSWKAYnN5lHZz0/Kq5OurCNaDs7gx42t50x@XOmCsy6IialqvrXaxD7zBCaAycGC0ttKhQX4pMAiWtBw4inHLfqwFGbwCE9y@9dmveEt0U/rcoZ6bBxNVaEN22w7yFHGmbMBfJf7eurxSXMh4NBAKUGpCpoU/FHU6fUkbuk1cF/fBU6zhUM/o26xZE4JIKJwJcx5QanT5Ie0FXmSLTT3YaUztJDJ2gZ2dfEs6Bn/xJWHyyNiFQ3xibBBAv7WB4kxNoDSoviBkNK3CubqwUNSqCEOhg/rvrDylRVjGArrR1w74rrj1jrASdFEyMkhsaV0GJXJKSt8hZmTXthNPtezRAZvRyz9k@fSeR4NhKNXhXYsNMoj9wk0xhftLfELR3wxWPzt4R5G8HKardO6AzOqfC5LfHF1VSndX2SCv@k6K02201WBcnRZ7@k6cfW9NE7toebj1FFlxNViOjueHfdbAG6sfOCPkaRDbzf1CWWTWfnIzb45gGZz0f8AH6WaQBKr/e0h9r6BQojjR/8YQF6E8pmWFvALj4RbCne89xHdV2my4bibsBdnKruUSIZ9/uD9Ays7O3xTdfdxXfGPMHLdH9num2pzv54313ai2mSqn65nI443q3nd5CYr@VeufGDnP11ul5YAWBtYB1j4xoK6ENg1sBuM@VMQRvTQ1H1v6tgov4VP@70NQbtk@3MOyNd7byGKAPGCVoDA7SAI8SP0O60eWnr@TdsP3yZH3OSPTxufDrnj071@j2y9elhd58ZH8l47DEjb8W964e/Oti4qKkDe6y4lhELYpfzCkNoRdKis1/8B)
] |
[Question]
[
**This question already has answers here**:
[Word Search Puzzle](/questions/37940/word-search-puzzle)
(12 answers)
Closed 5 years ago.
# The Challenge
Given a list of words and a grid of letters, your job is to determine which of the given words can be found on the grid in all 8 directions (forward, backward, up, down, and the 4 diagonal directions), much like a word search. The grid is toroidal, so the grid wraps around on the edges. Letters can be reused with this wrap-around property.
Wrapping around for diagonals behaves as you might expect. On a 4x6 grid going diagonally down and right, you would expect movement to look like this:
```
9 . 5 . 1 .
. . . 6 . 2
3 . . . 7 .
. 4 . . . 8
```
For an example of a wrap-around reuse word:
```
S E A H O R
```
Would be able to make SEAHORSE
# Example Test Cases
Given this grid and the word list [ANT, COW, PIG]:
```
A N T
W C O
P G I
```
The result would be [ANT, COW, PIG]
---
Given this grid and the word list [CAT, DOG, DUCK, GOOSE, PUMPKIN]:
```
N O O D M E
O I O C U U
P G K O T C
K A U P S K
```
The result would be [DOG, DUCK, PUMPKIN]
---
Given this grid and the word list [TACO, BEEF, PORK]:
```
T A C B
A P O R
K E E F
B F C P
```
The result would be an empty list
---
Given this grid and the word list [ACHE, ASK, BAD, BOOK, COOK, CROW, GAS, GOOD, LESS, MARK, MASK, MEAL, SAME, SEAHORSE, SELL, SHOW, SLACK, WOOD]:
```
G S L A C K
H A E S R O
C M S K O O
A K S D W B
```
The result would be [ASK, BOOK, COOK, CROW, GAS, GOOD, LESS, MASK, SEAHORSE, SHOW, SLACK]
---
Given this grid and a [list of all English words](https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt) that are at least 3 letters long:
```
A R T U P
N T U B O
E S R O H
Q E T I U
E A T D P
```
The result would be [AEQ, AES, ANE, ART, ARTS, ATRIP, BOID, BON, BREE, BUD, BUT, DUB, DUE, DUET, EAN, EAR, EAT, EER, EST, HES, HIT, HOP, HOR, HORS, HORSE, HUP, NAE, NOB, NOBUT, ONT, OOT, OPP, ORS, OUR, OUT, PAR, PART, PAT, PEA, PEAT, PEE, PEER, PIR, POH, PUT, QAT, QUI, QUIT, QUITE, RAP, REE, RIP, RIPA, RTI, RUT, SEA, SEAR, STD, STR, STRA, STRAE, SUU, TAA, TAE, TAP, TAPIR, TEE, TIU, TOO, TRA, TRAP, TRI, TRIP, TUB, TUP, TUR, UDI, UIT, URE, UTE]
# Rules
* No exploiting standard loopholes
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins
* Input and output may be in any convenient format
* You may assume that both the grid and the words list will use only capital letters
* The output order of the words does not matter
* You do not have to, but may, filter out duplicates
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Lẋ@Zɗ⁺ZU$3С;ŒD$€Ẏw€⁸ẸðÐf
```
A dyadic link accepting a list of lists of characters (the words) on the left and a list of lists of characters (the rows of the grid) on the right which returns a list of list of characters (the found words).
**[Try it online!](https://tio.run/##y0rNyan8/9/n4a5uh6iT0x817ooKVTE@POHQQuujk1xUHjWtebirrxxIPWrc8XDXjsMbDk9I@394uff//9FKjs4erko6So7B3kDSydEFRPr7gzjOUCrIPxxIuTsGg0h/f5AKH9dgEM/XMcgbTIE1@7o6@gCpYEdfkIHBro4e/kHBEKYPWMIDbFCwj6MzSHk4yKhYoAvcoSJcCkoejq7BQf5gprNvsLc/hOnoHewS7qQUCwA "Jelly – Try It Online")**
### How?
Filters the words by their existence in the grid tiled to be word-length times as wide and word-length times as high:
```
Lẋ@Zɗ⁺ZU$3С;ŒD$€Ẏw€⁸ẸðÐf - Link: words, grid
Ðf - filter (the words) keeping those for which
ð - ...the dyadic link to the left ...is truthy:
⁺ - perform this twice:
ɗ - last three links as a dyad:
L - length (of the current word)
ẋ@ - repeat (the rows) by (that number)
Z - transpose (making the rows become the columns)
3С - repeat three times and collect the results (inc input):
$ - last two links as a monad:
Z - transpose
U - upend (together these rotate by a quarter)
€ - for €ach:
$ - last two links as a monad:
ŒD - get forward-diagonals
; - concatenate
Ẏ - tighten (to get all the runs across the grid)
⁸ - chain's left argument (the word)
€ - for €ach run:
w - sublist-index (0 if not found)
Ẹ - any truthy? (i.e. was the word found?)
```
[Answer]
## Clojure, ~~203~~ 180 bytes
```
#(let[C count R range h(C %)w(C(% 0))](for[Q %2[y x][[1 0][0 1][-1 0][0 -1][1 1][1 -1][-1 -1][-1 1]]r(R h)c(R w):when(=(for[i(R(C Q))]((%(mod(+(* y i)r)h))(mod(+(* x i)c)w)))Q)]Q))
```
The grid must be a vector of vector of characters and the word list must be a sequence of sequence of characters. Sorry, no strings ;)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 269 214 164 163 bytes
-50 bytes with the golfing I learned since last year.
-1 byte thanks to Redwolf Programs
```
l=>g=>l.filter(w=>g.some((r,y)=>r.some((c,x,r,z=[-1,0,1],m=(a,b,c=b.length)=>(a%c+c)%c)=>z.some(l=>z.some(p=>[...w].every((h,i)=>h==g[m(l*i+y,g)][m(p*i+x,r)]))))))
```
[Try it online!](https://tio.run/##RVDRisIwEHz3Kw5Bmp5rOD8ghViLhbYEmgcfQh5qLtYe0UoVPf15b9MLd4HZmd2ZbCBfza25mKE7Xxen/tO@9uzlWNKyxNF95652IHds6aU/WkIGeMQsGUJn4BsGeDK1WMIHLDUcGWlgB4btqLOn9nrAMGlmZm7imUH9/L3o/tSZJYpSetfU3uzwIOQAHeYOjLXqSNx7N39AG2vUZ9T4Wqzj8bxMf7r0zlLXt2RP1JSneTaFKZcF1hVf@yqEb9JAtdgibbj0VQifKDPpu4rXxUjj5SrjJZLklV8oM56LWv7KcjTycZEseerjW79KxxOiVLSJIJKIEsERKaKINEzeVJSHWRYyNUIEz@eqMC/G@b/Hw8x7a8QWsYq0nuAn/AA "JavaScript (Node.js) – Try It Online")
old 214 bytes version:
```
(l,g)=>l.filter(w=>g.some((r,y)=>r.some((c,x,r,e=w.split``,m=(a,b)=>((a%b)+b)%b)=>[[0,1],[0,-1],[1,0],[-1,0],[1,1],[1,-1],[-1,1],[-1,-1]].some(v=>e.every((h,i)=>h==g[m(v[0]*i+y,g.length)][m(v[1]*i+x,r.length)])))))
```
[Try it online!](https://tio.run/##RVDbioMwEH3vVyyFYtyOUj8gQmqlgkrAPPQhCLXd1LrYWlTs9uu7kxh2hTPHc3ES/K6majj3zWP07t2Xel/om7RQuzRs/UvTjqonTxrW/tDdFCE9vDDprTrDD/Sg6NMfHm0zHo9wo6SCE1YIqVYnd31yV1pJuYGgBJyepgA2OL2ZApgtk3iz8ows52MmGipfTap/EXKFBtddKa3ljUxyU3426xfUfqvu9Xh1S@MG2sWb/bmuft7n7j50rfLbriYXIpcsSuIlLJlIcW7ZTk/OtYgsFfyAtGdCT851I4uFVjkrUkPm4zxmGZJguV4oYpbwQsyvmQkSs0hkLNL1g15VwkJKZ@@AIxAZgiEiROpg9iGdxHqx7RQIbjPdy62fGv8/Y9bT2Q5xQGydslzgP/gF "JavaScript (Node.js) – Try It Online")
Semi readable versoin:
```
(l, g) =>
l.filter(w =>
g.some((r, y) => //loop through rows
r.some((c, x, r, e = w.split``, //loop through columns and split word in chars
m = (a, b) => ((a % b) + b) % b) //modulo function which also works for negative
=>
[[0, 1], [0, -1], [1, 0], [-1, 0], [1, 1], [1, -1], [-1, 1], [-1, -1]].some(v => //the different directions
e.every((h, i)
=> h == g[m(v[0] * i + y, g.length)][m(v[1] * i + x, r.length)]
)
)
)
)
)
```
] |
[Question]
[
**This question already has answers here**:
[Leaderboard golf](/questions/111735/leaderboard-golf)
(4 answers)
Closed 6 years ago.
Have you ever found a good challenge to answer, answered it and then found out somebody posted a solution with a better score in *the same language*?
## Challenge
Write a **program/function** that takes a **PPCG question ID** and outputs a **leaderboard**.
A leaderboard consists of the rank, the language, the score, the author and the URL of each answer. This can be output as a newline delimited string, a list of strings, a "dictionary", etc..
* **Rank**
+ The rank of an answer is its **position in the score hierarchy (lowest first)**.
+ Answers with shared scores **must have the same rank**.
* **Language**
+ The name of the language is always between the last `#` on the first line and the first `,`.
+ It may be a link to documentation, which must be handled by taking the user-facing text.
* **Score**
+ The score of a answer is the **last number on the first line**.
+ It may be a decimal number.
* **Author**
+ The author of an answer is the **display name of the user** that posted it.
* **URL**
+ The URL of an answer will go **straight to the answer**.
+ [URL shorteners are **disallowed**.](https://codegolf.meta.stackexchange.com/a/10166)
### Specifications
* [Standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods "Default for Code Golf: Input/Output methods") **apply**.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default "Loopholes that are forbidden by default") are **forbidden**.
* This challenge is not about finding the shortest approach in all languages, rather, it is about finding the **shortest approach in each language**.
* Your code will be **scored in bytes**, usually in the encoding UTF-8, unless specified otherwise.
* Explanations, even for "practical" languages, are **encouraged**.
## Test cases
Note that these show example output formats which need not be strictly followed. These examples were taken at the time of sandboxing, they might be outdated.
```
Input: 28821
1. PCRE flavor, score 40 by jimmy23013 (https://codegolf.stackexchange.com/a/31863)
Input: 92944
1. Jelly, score 12 by Dennis (https://codegolf.stackexchange.com/a/92958)
2. Befunge-98, score 38 by Hactar (https://codegolf.stackexchange.com/a/98334)
3. ><>, score 41 by Sp3000 (https://codegolf.stackexchange.com/a/92980)
4. TovTovTov, score 810147050 by Yaniv (https://codegolf.stackexchange.com/a/93048)
Input: 47604*
1. Pyth, score 28.08 by Jakube (https://codegolf.stackexchange.com/a/47642)
2. APL, score 39.6 by jimmy23013 (https://codegolf.stackexchange.com/a/47606)
Input: 133793
1. Lua, score 9.06 by TehPers (https://codegolf.stackexchange.com/a/135775)
2. C# (.NET Core), score 10.20 by Kamil Drakari (https://codegolf.stackexchange.com/a/135764)
3. Cubically, score 86.98 by Kamil Drakari (https://codegolf.stackexchange.com/a/137695)
```
\*Note that this challenge has 3 answers, however the GolfScript answer doesn't have a comma in the header which makes it undefined behaviour.
In a few better formats:
```
28821, 92944, 47604, 133793
28821 92944 47604 133793
28821
92944
47604
133793
```
[This challenge was sandboxed.](https://codegolf.meta.stackexchange.com/a/13574)
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~1059~~ ~~1049~~ ~~1033~~ ~~998~~ 973 bytes
*Saved 53 bytes thanks to @TheLethalCoder.*
*Saved 25 bytes thanks to @Mr. Xcoder.*
```
using HtmlAgilityPack;namespace System.Linq{n=>{var u="http://codegolf.stackexchange.com/";var l=new Collections.Generic.List<Tuple<string,float,string,string>>();foreach(var x in new HtmlWeb().Load(u+"questions/"+n).GetElementbyId("answers").Descendants("div").Where(p=>(p.Attributes["id"]?.Value??"").Contains("answer-"))){var b=x.Descendants().First(p=>(p.Attributes["class"]?.Value)=="post-text");var h=b.Descendants().ElementAt(1).InnerText;l.Add(new Tuple<string,float,string,string>(h.Split(',',' ')[0],float.Parse(h.Split(' ').Reverse().First(p=>float.TryParse(p.Replace('.',','),out var y)).Replace('.', ',')),b.ParentNode.Descendants("td").Last(p=>(p.Attributes["class"]?.Value)=="post-signature").Descendants("div").Reverse().ElementAt(1).Descendants("a").First().InnerText,u+"a/"+x.Attributes["id"].Value.Split('-')[1]));}var s=new string[l.Count];for(var i=0;i<l.Count;){var m=l[i];s[i]=++i+$". {m.Item1}, score {m.Item2} by {m.Item3} ({m.Item4})";}return s;}}
```
Uses the [HTMLAgilityPack](http://html-agility-pack.net/).
There are probably better solutions to this using the StackOverflow API, but this is a raw HTML solution.
---
Ungolfed code: (Unchanged for readability & reference)
```
n =>
{
// Retrieve the HTML of the question page with ID n
var doc = new HtmlWeb().Load("https://codegolf.stackexchange.com/questions/" + n);
// Get all the answers
var answers = doc.GetElementbyId("answers").Descendants("div").Where(d => (d.Attributes["id"]?.Value ?? "").Contains("answer-"));
// Format: Language, Score, Author, URL
var l = new Collections.Generic.List<Tuple<string, float, string, string>>();
// Loop over every answer element
foreach (var a in answers)
{
// Get the content of the answer post
var b = a.Descendants().First(d => (d.Attributes["class"]?.Value ?? "") == "post-text");
// Get the header
var h = b.Descendants().ElementAt(1);
// Dummy variable for the TryParse
float y;
// Create a new Tuple
var v = new Tuple<string, float, string, string>(
h.InnerText.Split(',', ' ')[0], // The language
float.Parse(h.InnerText.Split(' ').Reverse().First(x => float.TryParse(x.Replace('.',','), out y)).Replace('.', ',')), // The score of the answer
b.ParentNode.Descendants("td").Last(d => (d.Attributes["class"]?.Value ?? "") == "post-signature").Descendants("div").Reverse().ElementAt(1).Descendants("a").First().InnerText, // The author
"https://codegolf.stackexchange.com/a/" + a.Attributes["id"].Value.Split('-')[1] // The url to the answer
);
l.Add(v); // Add the tuple to the collection
}
var s = new string[l.Count]; // An array to save the leadboard content
for (var i = 0; i < l.Count;i++)
{
var m = l[i]; // The current element
s[i] = $"{i+1}. {m.Item1}, score {m.Item2} by {m.Item3} ({m.Item4})"; // Format the data
}
return s;
}
```
[Answer]
# Python 2 + requests + BeautifulSoup + re, 547 519 512 bytes
```
from requests import*
from bs4 import BeautifulSoup as B
import re
w,h='.stackexchange.com/','http://'
def D(i):l=B(i['body'].split('\n')[0],'html.parser').text;return[l.split(',')[0],float(re.findall(r'\d*\.\d+|\d+',l)[-1]),i['owner']['display_name'],'%scodegolf%sa/'%(h,w)+`i['answer_id']`]
d=sorted([D(i)for i in get('%sapi%squestions/%d/answers?site=codegolf&filter=withbody'%(h,w,input())).json()['items']],key=lambda x:x[1])
h=r=0
for x in d:r+=x[1]>h;h=x[1];print'%d. %s, score %f by %s (%s)'%tuple([r]+x)
```
Output for this question (137878):
```
1. Python 2 + requests + BeautifulSoup + re, score 512.000000 by Dopapp (http://codegolf.stackexchange.com/a/138043)
2. C# (.NET Core), score 973.000000 by Ian H. (http://codegolf.stackexchange.com/a/137933)
```
Ungolfed:
```
from requests import*
from bs4 import BeautifulSoup
import re
# [score, owner, lang, link]
def data(item): # extracts data from each answer
owner = item['owner']['display_name']
link = 'http://codegolf.stackexchange.com/a/'+`item['answer_id']`
line1 = BeautifulSoup(item['body'].split('\n')[0], 'html.parser').text # first line of the answer
lang = line1.split(',')[0]
score = float(re.findall(r'\d*\.\d+|\d+', line1)[-1])
return [score, owner, lang, link]
# datas :P
datas = [data(item)for item in get('http://api.stackexchange.com/questions/%d/answers?site=codegolf&filter=withbody'%input()).json()['items']]
sortedDatas = sorted(datas, key=lambda x: x[0]) # sort the data by the score
highestScore=rank=0 # This is for doing the ranking in case there are identical scores
for d in sortedDatas:
if d[0] > highestScore:
highestScore = d[0]
rank += 1
print '%d. %s, score %f by %s (%s)' % (rank, d[2], d[0], d[1], d[3]) # format the line
```
] |
[Question]
[
There is a Sioux village. It has a totem:
```
__
___| |___
\/ \ / \/
/\ ``| |`` /\
/^^\ | | /^^\
/ /\ \ | | / /\ \
''''''''''''''''''''''''''''
```
The totem lets the Sioux mastering the weather for helping in their different tasks. Help the villagers properly decorating the totem for invoking the adequate weather. The totem has several parts:
```
__
___|AA|___
\/ \BBBBBBBB/ \/
/\ ``|CC|`` /\
/^^\ |DD| /^^\
/ /\ \ 13 |EE| 42 / /\ \
''''''''''''''''''''''''''''
```
* `A` is for *sun* `()` or *clouds* `ww`
* `B` is for *rain* `""""""""` or *snow* `::::::::`
* `C` is for *thunderstorm* `zz`
* `D` is for *wind* `~~`
* `E` is for *fog* `==`
But that's not all. The totem needs weather dancers. The more elements are invoked, the higher the number of required dancers is. If there is one element invoked, a dancer is needed. Two elements, two dancers. Beyond four elements, there will always be at most four dancers. If there is no element invoked, no dancers are needed. The totem needs to rest.
The weather dancers must appear in the order `1234`. For instance if there are two dancers, the slots `1` and `2` must be occupied. Moreover, each dancer performs a different figure:
* `1` is `T`
* `2` is `Y`
* `3` is `K`
* `4` is `X`
Now, the villagers will express their weather wishes. They will pronounce a sentence containing the weather element(s) they would like to have. Setup the totem and the dancers for fulfilling their wishes.
**Challenge**
Write a program which takes a string as input, matches the elements in the sentence (*sun*, *rain*, …), and outputs the full village with the totem properly set and its dancers. Your program does not have to check the correctness of the input string (e.g. it won't contain both *sun* and *clouds*). It must matches **words** (in the literal sense):
* The input string `X says: "I like the wind, it blows the worries away"` matches *wind*, because the comma is not part of the word
* The input string `Y says: "I hope the weather won't get too windy"` does not match *wind*, because *windy* and *wind* are two different words
The word(s) to match are guaranteed to be in the quoted part of the input string (the first part designating who is talking will never contain a word that could be matched).
**Examples**
```
The squaw says: "I want sun and wind for drying the clothes"
__
___|()|___
\/ \ / \/
/\ ``| |`` /\
/^^\ |~~| /^^\
/ /\ \ T | | Y / /\ \
''''''''''''''''''''''''''''
```
```
The warrior thinks: "A good thunderstorm will afraid the invaders. Or a snow storm. Or an impenetrable fog. Or an oppressive sun."
__
___|()|___
\/ \::::::::/ \/
/\ ``|zz|`` /\
/^^\ | | /^^\
/ /\ \ TK |==| XY / /\ \
''''''''''''''''''''''''''''
```
```
The papoose shouts: "I WANNA GO OUTSIDE PLAY UNDER THE SUN!"
__
___|()|___
\/ \ / \/
/\ ``| |`` /\
/^^\ | | /^^\
/ /\ \ T | | / /\ \
''''''''''''''''''''''''''''
```
```
The wise grandma whispers: "The totem is an illusion"
__
___| |___
\/ \ / \/
/\ ``| |`` /\
/^^\ | | /^^\
/ /\ \ | | / /\ \
''''''''''''''''''''''''''''
```
```
The shaman confides: "I perform my magic hidden in the fog, under the rain or at least under heavy clouds"
__
___|ww|___
\/ \""""""""/ \/
/\ ``| |`` /\
/^^\ | | /^^\
/ /\ \ TK |==| Y / /\ \
''''''''''''''''''''''''''''
```
```
The village chief claims: "The meat of bison is better preserved in the snow, or dried under a burning sun. My Pa' used to say that heavy wind and a thunderstorm could help too, but I have no clue how. And despite everyone contradicting me, I am persuaded a good fog will do as well"
__
___|()|___
\/ \::::::::/ \/
/\ ``|zz|`` /\
/^^\ |~~| /^^\
/ /\ \ TK |==| XY / /\ \
''''''''''''''''''''''''''''
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes win. Explanations are encouraged.
[Answer]
# Python, ~~527~~ ~~524~~ ~~508~~ ~~504~~ ~~481~~ ~~474~~ ~~462~~ 461 bytes
```
from re import*
a=r"""!!! __
!! ___|AA|___
\/!\BBBBBBBB/!\/
/\! ``|CC|``! /\
/^^\! |DD|! /^^\
/ /\ \ 02 |EE| 31 / /\ \
""";s={'sun':'A2()','clouds':'A2w','rain':'B2"','snow':'B2:','thunderstorm':'C2z','wind':'D2~','fog':'E2='};i=0
for y in[w for w in split('\W+',input().lower())if w in s]:i+=1;z=s[y];w=int(z[1]);a=sub(z[0]*w,(z[2:]*w)[:w],a)
for y in range(min(i,4)):a=sub(str(y),'TYKX'[y],a)
print(sub('!',' '*4,sub('[ABCDE0123]',' ',a))+"'"*28)
```
[Try it online!](https://tio.run/##PZHNrpswEIX3PMXAxjhBJSF3UYFY5G9RdXultgJu4gYTLAUb2aaIlPbV04FE9cI@3xmPPR63g62V3DwelVYNaA6iaZW2C4el2vM813XhdHLm@TRutyMuDgDkoZvvXgNlOHlh7sL5PO734/nsIqEXfnygCePhMLpPciDEEOQAqwjG43GEzRpenoMXJib9TUwnSUy2kU9JQC431ZVm5h5RMzEFd5GHYKTqZ4gRbN3JkmtjlW7Q3Ed3NHshS4RD9BehUlfUxyglfxKRrpxKaRhAyKyHSfYowbQ3YX2Sf1uSQMi2sz79dFM91z6lonrtKWKxTNfJPTXZUCR9KqT179m6oAlLTfcT9apY9AGuUYyCZnFfBIz@vxA0k1fuN0L6InijNH6mGav9gQbk/cfX7wRPnlJaPR0@RYmLTwCyeAtmyra7/eG4WkebYvZxM116xFtEn@nj8V5zMDVrmISLkpUouYnB@wIt11hEA80ADbuKC9SiLLmcarKYgh0KYG7jjFOzAWtmFm6cGfsK1Zz9GuD5Md4/)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~473~~ ~~464~~ 460 bytes
```
import re
x=re.split('\W+',input().lower())
L='sun clouds rain snow thunderstorm wind fog'.split()
q=sum(map(x.count,L))
print(r'''! __
!___|#|___
" \/" \$/" \/
" /\" ``|%%|``" /\
/^^\"" |&&|"" /^^\
/ /\ \ 13 |''| 42 / /\ \
'''.translate({33:' '*9,34:' '*2,35:' (w )w'[(L[0]in x)+2*(L[1]in x)::3],36:' ":'[(L[2]in x)+2*(L[3]in x)]*8,37:' z'[L[4]in x],38:' ~'[L[5]in x],39:' ='[L[6]in x],49:' T'[q>0],50:' Y'[q>1],51:' K'[q>2],52:' X'[q>3]})+"'"*28)
```
[Try it online!](https://tio.run/##VZJtj9owDMff91P4ut2lhYqHFm4cEpP2chqT9uKkbaIcBGpopDbpJSmFrdtXZw4waavUxL9/bMeRXZ1srmRyPouyUtqCRu8409gzVSFswNKvXRYJWdU2CHuFalAHYejNZ8zUEraFqjMDmgsJRqoGbF7LDLWxSpfQCJnBTu3ZLVfovc5MXQYlr4Jjb6tqaaM5Jau0kDbQjLE7oG@18u5Wq1X7pqXV8yHt@wDp276zCPspIazX7f19u16T3U89Wl5eUp@gfXhoaXfoQZ/OIAUYJtAy1sIovkke3dWzmktTcIvBzySZMmCdpygZXYw4SsZkBA2EDVsE88VgSS88ht24QzC8wnSaLKPkkfz86cUp/tcpucKyM4mSd@Tzgy3mi9FFpKgJKb@dMv6rPJEyc8rjTRk55ZktXt8PltF4QPDdwZBgSPDJQUwQE3xzkCx/hV2f@Z14Ep7PzznCQRQF3yNsc4E7ahYXpZmC745K5BbUDjbCKAnCwAatRQ2VRoP6gBlQFZYcXVsjUBoyLUi9tBc4bGothdwDTUEPPp/gC2dQG3KwCgw/USjlz5EfTtcx4O7/fzxoAIqMfIqKglREKS18hJwfEKSiamuEXDU9@EChGZpKWAQ8oD4pSU9SkvqXia11VZQYUSgvoaLkNc/QXbZX6jJ@VEBRQKaAG2iwKPw/ "Python 3 – Try It Online")
-9 bytes
-4 bytes thanks to ovs
[Answer]
# JavaScript (ES6), 417 bytes
```
(s,i=x=>s.toLowerCase()[q](/\W+/).includes(x[0]),g=x=>y=>i(x)?y[0]:(j--," "),j=4,t="|| \\/| /\\| /^^\\| / /\\ \\"[q="split"]`|`.map(x=>x[p="padEnd"](9)))=>` __ n___|${i`sun`?"()":g`clouds``ww`}|___n${"\\"[p](9,i`rain`?'"':g`snow``:`)}/n \`\`|${g`thunderstorm``zz`}|\`\` n |${g`wind``~~`}| n02 |${g`fog``==`}| 31`.replace(/\d/g,m=>m>j?" ":"TYKX"[m])[q]`n`.map((v,k)=>t[k]+v+t[k]).join`
`+`
`[p](28,"'")
```
The idea here was to generate the totem pole first, then add the mirrored tikis on both sides of it.
Includes two helper functions: `i`, which checks if a string is one of the words in the input; and `g`, which does `i` and returns the given string or `" "`. `g` also counts how many elements are missing to be used for the dancers at the bottom.
## Test Snippet
```
let f=
(s,i=x=>s.toLowerCase()[q](/\W+/).includes(x[0]),g=x=>y=>i(x)?y[0]:(j--," "),j=4,t="|| \\/| /\\| /^^\\| / /\\ \\"[q="split"]`|`.map(x=>x[p="padEnd"](9)))=>` __ n___|${i`sun`?"()":g`clouds``ww`}|___n${"\\"[p](9,i`rain`?'"':g`snow``:`)}/n \`\`|${g`thunderstorm``zz`}|\`\` n |${g`wind``~~`}| n02 |${g`fog``==`}| 31`.replace(/\d/g,m=>m>j?" ":"TYKX"[m])[q]`n`.map((v,k)=>t[k]+v+t[k]).join`
`+`
`[p](28,"'")
let tests = [`The squaw says: "I want sun and wind for drying the clothes"`,`The warrior thinks: "A good thunderstorm will afraid the invaders. Or a snow storm. Or an impenetrable fog. Or an oppressive sun."`,`The papoose shouts: "I WANNA GO OUTSIDE PLAY UNDER THE SUN!"`,`The wise grandma whispers: "The totem is an illusion"`,`The shaman confides: "I perform my magic hidden in the fog, under the rain or at least under heavy clouds"`,`The village chief claims: "The meat of bison is better preserved in the snow, or dried under a burning sun. My Pa' used to say that heavy wind and a thunderstorm could help too, but I have no clue how. And despite everyone contradicting me, I am persuaded a good fog will do as well"`];I.innerHTML+=tests.map(t=>"<option>"+t).join``
```
```
<select id=I oninput="O.innerHTML=(idx=I.selectedIndex)?(t=tests[idx-1])+'\n\n'+f(t):''" style="width:90vw"><option>---Tests---</select>
<pre id=O></pre>
```
] |
[Question]
[
# K-Means Clustering ([Wikipedia](https://en.wikipedia.org/wiki/K-means_clustering))
The task here is rather simple, perform a single iteration of a k-means clustering algorithm on a binary matrix. This is essentially the setup task for the main k-means algorithm, I felt the setup might be easier and entice golfing languages to give it a shot as well. The matrix passed to you will have the following format:
```
0 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1
0 0 1 0 0 0 0 0 0
0 0 0 0 0 1 0 0 1
0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0
0 1 0 0 0 1 0 0 0
0 1 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0
```
1 represents a point, while 0 represents a lack of points. Your job will be to randomly generate `k-1` centroids and perform the initial clustering of the data around the centroids you've generated. `k` is defined as `min(grid#Width, grid#Height)-1`. The labeling of each centroid should go from `2` until `k`. For instance, in this scenarios you could generate the following centroids:
```
Centroid 2 was generated at: (1.0, 4.0)
Centroid 3 was generated at: (1.0, 5.0)
Centroid 4 was generated at: (5.0, 1.0)
Centroid 5 was generated at: (3.0, 3.0)
Centroid 6 was generated at: (0.0, 2.0)
Centroid 7 was generated at: (6.0, 6.0)
Centroid 8 was generated at: (2.0, 6.0)
```
After generating the centroids, you must loop through each and every point that is marked with a `1`, as we can treat the ones marked with `0` as empty space. For each centroid, you must decide which centroid is the closest to the point in question. Here's the distances for the example:
```
(0,8) distance from centroid 2 is 4.123105625617661
(0,8) distance from centroid 3 is 3.1622776601683795
(0,8) distance from centroid 4 is 8.602325267042627
(0,8) distance from centroid 5 is 5.830951894845301
(0,8) distance from centroid 6 is 6.0
(0,8) distance from centroid 7 is 6.324555320336759
(0,8) distance from centroid 8 is 2.8284271247461903
(1,1) distance from centroid 2 is 3.0
(1,1) distance from centroid 3 is 4.0
(1,1) distance from centroid 4 is 4.0
(1,1) distance from centroid 5 is 2.8284271247461903
(1,1) distance from centroid 6 is 1.4142135623730951
(1,1) distance from centroid 7 is 7.0710678118654755
(1,1) distance from centroid 8 is 5.0990195135927845
(2,8) distance from centroid 2 is 4.123105625617661
(2,8) distance from centroid 3 is 3.1622776601683795
(2,8) distance from centroid 4 is 7.615773105863909
(2,8) distance from centroid 5 is 5.0990195135927845
(2,8) distance from centroid 6 is 6.324555320336759
(2,8) distance from centroid 7 is 4.47213595499958
(2,8) distance from centroid 8 is 2.0
(3,2) distance from centroid 2 is 2.8284271247461903
(3,2) distance from centroid 3 is 3.605551275463989
(3,2) distance from centroid 4 is 2.23606797749979
(3,2) distance from centroid 5 is 1.0
(3,2) distance from centroid 6 is 3.0
(3,2) distance from centroid 7 is 5.0
(3,2) distance from centroid 8 is 4.123105625617661
(4,5) distance from centroid 2 is 3.1622776601683795
(4,5) distance from centroid 3 is 3.0
(4,5) distance from centroid 4 is 4.123105625617661
(4,5) distance from centroid 5 is 2.23606797749979
(4,5) distance from centroid 6 is 5.0
(4,5) distance from centroid 7 is 2.23606797749979
(4,5) distance from centroid 8 is 2.23606797749979
(4,8) distance from centroid 2 is 5.0
(4,8) distance from centroid 3 is 4.242640687119285
(4,8) distance from centroid 4 is 7.0710678118654755
(4,8) distance from centroid 5 is 5.0990195135927845
(4,8) distance from centroid 6 is 7.211102550927978
(4,8) distance from centroid 7 is 2.8284271247461903
(4,8) distance from centroid 8 is 2.8284271247461903
(6,1) distance from centroid 2 is 5.830951894845301
(6,1) distance from centroid 3 is 6.4031242374328485
(6,1) distance from centroid 4 is 1.0
(6,1) distance from centroid 5 is 3.605551275463989
(6,1) distance from centroid 6 is 6.082762530298219
(6,1) distance from centroid 7 is 5.0
(6,1) distance from centroid 8 is 6.4031242374328485
(7,1) distance from centroid 2 is 6.708203932499369
(7,1) distance from centroid 3 is 7.211102550927978
(7,1) distance from centroid 4 is 2.0
(7,1) distance from centroid 5 is 4.47213595499958
(7,1) distance from centroid 6 is 7.0710678118654755
(7,1) distance from centroid 7 is 5.0990195135927845
(7,1) distance from centroid 8 is 7.0710678118654755
(7,5) distance from centroid 2 is 6.082762530298219
(7,5) distance from centroid 3 is 6.0
(7,5) distance from centroid 4 is 4.47213595499958
(7,5) distance from centroid 5 is 4.47213595499958
(7,5) distance from centroid 6 is 7.615773105863909
(7,5) distance from centroid 7 is 1.4142135623730951
(7,5) distance from centroid 8 is 5.0990195135927845
(8,1) distance from centroid 2 is 7.615773105863909
(8,1) distance from centroid 3 is 8.06225774829855
(8,1) distance from centroid 4 is 3.0
(8,1) distance from centroid 5 is 5.385164807134504
(8,1) distance from centroid 6 is 8.06225774829855
(8,1) distance from centroid 7 is 5.385164807134504
(8,1) distance from centroid 8 is 7.810249675906654
(8,8) distance from centroid 2 is 8.06225774829855
(8,8) distance from centroid 3 is 7.615773105863909
(8,8) distance from centroid 4 is 7.615773105863909
(8,8) distance from centroid 5 is 7.0710678118654755
(8,8) distance from centroid 6 is 10.0
(8,8) distance from centroid 7 is 2.8284271247461903
(8,8) distance from centroid 8 is 6.324555320336759
```
The final result of the clustering algorithm is that there should be no 1s remaining in the matrix, only centroid numbers. This is why it was important to label the centroids from `2-k+1`, allowing us to replace them, as follows:
```
0 0 0 0 0 0 0 0 8
0 6 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 8
0 0 5 0 0 0 0 0 0
0 0 0 0 0 5 0 0 7
0 0 0 0 0 0 0 0 0
0 4 0 0 0 0 0 0 0
0 4 0 0 0 7 0 0 0
0 4 0 0 0 0 0 0 7
0 0 0 0 0 0 0 0 0
```
This is the initial clustering layout for 7 centroids on the provided grid, given randomly generated centroids. Your job is to output the clustered version of the binary input grid.
# Rules
* The `k-1` centroids must be randomly generated and should be anywhere from `(0,0)` to `(grid#Width, grid#Height)`.
+ The value of `k` is `min(grid#Width, grid#Height)-1`.
+ The centroids generated MUST be numbered from `2` to `k`.
* The input format MUST be a grid of 0s and 1s, where 0s represent empty space and 1s represent points.
+ A grid is either a string using 1-char per cell and `\n` as row delimiters or a 2D array.
+ The grid passed is not guaranteed to be square, but it is guaranteed to not be empty.
* The final output can either use arrays or a delimited string.
* Shortest code wins, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~61~~ 50 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each)
```
⍴⍴,{⍺\1+{⊃⍸⍵=⌊/⍵}¨↓⍵}⍸∘.(+.×⍨-)⌊/∘⍴{⍵[1↓⍺?⍴⍵]}∘⍸=⍨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b/Go94t7ppAQkPHXTPGULv6UVfzo94dj3q32j7q6dIH0rWHVjxqmwxUtwOormOGXrW2vpHWo94Vj3p36YKkq4FEtCFYCVgD0Dh7IAkUja0FajKyc3/UNuFR31SQff/TuB61TdQwVDBQMFQAkRBoqKlhqGAIFYKyNDUMkFWA2BBVMAEDmCoUAZAqFC6y8QgJA00A "APL (Dyalog Unicode) – Try It Online")
*-11 bytes thanks to Bubbler*
### How it Works
```
⍝ Implicitly take binary matrix G as input
⍸=⍨ ⍝ Yield all (1-indexed) coordinates from (1,1) to (w,h)
⌊/∘⍴ ⍝ k+1=min(w,h)
{...} ⍝ Choose k centroids:
? ⍝ Randomly choose
⍺ ⍝ k+1 distinct indices
⍴⍵ ⍝ from the array of w×h possible indices
1↓ ⍝ Drop the first so there are only k indices
⍵[...] ⍝ index into the array of w×h coordinates
∘. ⍝ Outer product of
⍝ the k centroids with
⍳ ⍝ the coordinates of all of the "1"s in G
(+.×⍨-) ⍝ with operator: distance squared
{...}¨↓ ⍝ For each row (point)
⊃⍸⍵=⌊/⍵ ⍝ Find the index of the centroid with smallest distance
⍝ (breaks ties by choosing lower numbers → small bias toward lower centroid numbers)
1+ ⍝ Add 1 to shift centroid numbers to [2,k]
⍝ Now we have a list of the centroid numbers for the "1"s, in reading order
⍺\ ⍝ Expand to prototype array:
, ⍝ Prototype array is flattened G (Expand \ throws RANK ERROR for non-vector left argument)
⍴ ⍝ Reshape back to
⍴ the shape of G
```
[Answer]
## Mathematica 109 Bytes
If I understand the question correctly, something like this ought to work. "KMeans" is one of the built in methods to FindClusters and ClusteringComponents.
```
SparseArray[Thread[(p=Position[#,1])->1+ClusteringComponents[p,Min[d=Dimensions@#]-1,1,Method->"KMeans"]],d]&
```
Usage:
`%@in//MatrixForm` to get visualization, `in` is an integer array.
] |
[Question]
[
Based on [THIS](https://codegolf.stackexchange.com/questions/102723/balancing-a-string-using-a-stack) question.
Given a string, replace each bracket `()[]{}<>` with a bracket of the appropriate type so that the brackets match, and the nested brackets cycle as follows:
1. Outermost ones are `()`
2. Directly inside of `()` should be `[]`
3. Directly inside of `[]` should be `{}`
4. Directly inside of `{}` should be `<>`
5. Directly inside of `<>` will be `()` again (cycles)
All non-bracket chars must remain exactly as they are. Open brackets may only be replaced with open brackets of some type, and close brackets with close brackets.
The input will always make this possible. This means its brackets matched correctly if their type is ignored. So, `{ab<)c]` is a valid input, but `ab)(cd` or `ab((cd` are not.
Examples:
```
2#jd {¤>. = 2#jd (¤).
abcdef = abcdef
(3×5+(4-1)) = (3×5+[4-1])
<<<>><<>><<<<<<>>>>>>> = ([{}][{}][{<([{}])>}])
```
The use of native transforming of input this way (auto syntax of language) is not allowed.
As always: shortest code wins.
[Answer]
## JavaScript (ES6), 79 bytes
```
s=>s.replace(/./g,c=>~(p=l.indexOf(c))?l[p&4?--k&3|4:k++&3]:c,l='([{<)]}>',k=0)
```
### Test cases
```
let f =
s=>s.replace(/./g,c=>~(p=l.indexOf(c))?l[p&4?--k&3|4:k++&3]:c,l='([{<)]}>',k=0)
console.log(f("2#jd {¤>."));
console.log(f("abcdef"));
console.log(f("(3×5+(4-1))"));
console.log(f("<<<>><<>><<<<<<>>>>>>>"));
```
[Answer]
# Lex, 132 bytes
```
%{
int i,o[4]={40,91,123,60};
%}
%%
[[({<] {putchar(o[i++&3]);}
[])}>] {putchar(o[--i&3]+2-!(i&3));}
%%
yywrap(){}
main(){yylex();}
```
[Answer]
# Java, 155 bytes
```
a->{String s="([{<)]}>";for(int i=0,j=0,k;i<a.length;i++){k=s.indexOf(a[i]);if(k>3){a[i]=s.charAt(--j%4+4);}else if(k>-1){a[i]=s.charAt(j++%4);}}return a;}
```
Lambda that takes a `char[]` as it's single argument. We loop through the array, storing it's position in our string of brackets (`s`) in a variable (`k`). We check if it's an opening or closing bracket (`s.indexAt()`), and replace it with the appropriate bracket based on it's level of nesting (`s.charAt()`), looping appropriately with `%4`
[Answer]
# Haskell, 126 bytes
```
b="([{<"
d=")]}>"
y=cycle
(!)=elem
f(e:c)n(x:r)|x!b=y b!!n:f(y d!!n:e:c)(n+1)r|x!d=e:f c(n-1)r|1<3=x:f(e:c)n r
f c n s=s
f" "0
```
[Try it on ideone.](http://ideone.com/4zg9fJ) Usage:
```
*Main> f" "0 "<<<>><<>><<<<<<>>>>>>>"
"([{}][{}][{<([{}])>}])"
```
### Explanation
`f` takes three arguments: A string that works as stack for closing brackets, an int `n` for counting the nesting-depth and the input string.
```
f c n "" = "" -- base case for recursion: input string is empty
f (e:c) n (x:r) -- for the current char x
| elem x "([{<" = -- check if it is an opening bracket
(cycle "([{<")!!n : -- if so, replace it with a bracket of the current nesting depth
f ((cycle ")]}>")!!n : e : c) -- push the matching closing bracket on the stack
(n+1) r -- increase depth level and check the next char
| elem x ")]}>" = -- if x is a closing bracket
e : -- replace it by the closing bracket from on top of the stack
f c (n-1) r -- decrement depth level and check the next char
| otherwise = x : f (e:c) n r -- otherwise keep x and check the next char
```
] |
[Question]
[
# Challenge description
A **Langford string** of order `N` is defined as follows:
* The length of the string is equal to `2*N`,
* The string contains first `N` letters of the English alphabet, each letter appearing twice,
* For each pair of the same letters, there are `M` letters between them, where `M` is that letter's position in the alphabet (`A = 1`, `B = 2`, `...`, `Z = 26`).
For instance, the only two possible Langford strings of order `3` are `BCABAC` and `CABACB`. As you can see, in both of these strings there is one letter between two `A`'s, two letters between `B`'s and three letters between `C`'s. Given a positive integer `N`, output all Langford strings of order `N` (in any reasonable format: print them one by one separated by a newline, return a list/array...).
# Sample inputs / outputs
```
3: [CABACB, BCABAC]
4: [DACABDCB, BCDBACAD]
5: # no output #
7: [GCFBECBDGFEADA, GBFCBDECGFDAEA, GBDFBCEDGCFAEA, GCAFACDEGBFDBE, GADAFCEDGCBFEB, GACAFDCEGBDFBE, GDAEAFDCGEBCFB, GBDEBFCDGECAFA, EGBFCBEDCGFADA, CGDFCBEDBGFAEA, EGDAFAEDCGBFCB, EGBCFBECDGAFAD, AGABFDBECGDFCE, EGADAFECDGBCFB, AGABEFBCDGECFD, BGDBCEFDCGAEAF, FBGDBCEFDCGAEA, BFGBAEADFCGEDC, CFGACADEFBGDBE, EAGAFBEDBCGFDC, BCGBFCEADAGFED, DAGAFDBECBGFCE, EBGCBFECDAGAFD, CEGDCFBEDBGAFA, CEGBCFBEDAGAFD, BDGBCFDECAGAFE, EFAGACEDFCBGDB, DFAGADEBFCBGEC, AFAGBDEBFCDGEC, DFAGADCEFBCGBE, ECFGBCEBDFAGAD, DEFGADAECFBGCB, CDFGCBDEBFAGAE, EBDGBFEDACAGFC, CDEGCFDAEABGFB, AEAGCDFECBDGBF, FAEAGCDFECBDGB, DFCEGDCBFEBAGA, BFCBGDCEFADAGE, ECFDGCEBDFBAGA, DAFAGDCEBFCBGE, BCFBGCDEAFADGE, AEAFGBDEBCFDGC, ADAFGCDEBCFBGE, AFACEGDCFBEDBG, BFCBEGCDFAEADG, EBFDBGECDFACAG, BEFBCGDECFADAG, EBDFBGEDCAFACG, AEAFCGDECBFDBG, AEADFGCEDBCFBG, ADAEFGDBCEBFCG]
12: # <216288 strings> #
```
# Notes
* Langford strings of order `N` can only be produced when `N ≡ 0 (mod 4)` or `N ≡ 3 (mod 4)`,
* You can use both lower-case and upper-case letters,
* You may use subsequent numbers as well (`012...` or `123...` instead of `ABC...`)
* Order of strings in which they should appear as output is unspecified,
* Output can be quite lengthy (for instance, there are over 5 trillion distinct Langford strings of order `20`), so your program doesn't actually need to output them all, but it has to work in theory (given enough time and memory).
* This challenge has been taken from [/r/dailyprogrammer](https://www.reddit.com/r/dailyprogrammer/comments/3efbfh/20150724_challenge_224_hard_langford_strings/), all credit goes to [/u/XenophonOfAthens](https://www.reddit.com/user/XenophonOfAthens)
[Answer]
## CJam (23 bytes)
```
{,2*e!{__f{\a/1=,(}=},}
```
[Online demo](http://cjam.aditsu.net/#code=4%0A%0A%7B%2C2*e!%7B__f%7B%5Ca%2F1%3D%2C(%7D%3D%7D%2C%7D%0A%0A~p). This is an anonymous block (function) which takes input on the stack and leaves output on the stack in the form of an array of arrays of 0-based sequential integers.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 43 bytes
```
:1fd.
ybB:1jp.,B:[.]z:2a
:3f-+$_~h?
t:.m~h?
```
[Try it online!](http://brachylog.tryitonline.net/#code=OjFmZC4KeWJCOjFqcC4sQjpbLl16OjJhCjozZi0rJF9-aD8KdDoubX5oPw&input=Mw&args=Wg)
] |
[Question]
[
In the game Stratego, the main game mechanic is when you attack an opponent's piece with yours. In this challenge, you job is to simulate one of these battles and say who survives.
# Specs
You will get as input a pair of string representing Stratego pieces. The pieces are one of `"S 1 2 3 4 5 6 7 8 9 10 B"` (`S` is the Spy, and `B` are bombs). The first of the pair will be the attacker, and the second the attacked.
Here are the rules for determining the results of a battle:
* The higher number beats the lower number: `["4", "6"] -> ["6"]`.
* If both are the same, then both die: `["7", "7"] -> []`.
* Spies are at the bottom, underneath even `1`: `["S", "2"] -> ["2"]`.
* However, if a spy attacks the `10`, then the spy wins: `["S", "10"] -> ["S"]`.
* But the normal rules still apply if the `10` is the one attacking: `["10", "S"] -> ["10"]`.
* If anything attacks a bomb, the bomb wins: `["5", "B"] -> ["B"]`.
* However, a miner (a `3`), can defuse a bomb: `["3", "B"] -> ["3"]`.
* A bomb will never be the attacker.
* A spotter (a `1`), can attack using the normal mechanism, but they can also try to "guess" the rank of the other player, which can be denoted with any sane notation.
* If they guess correctly, the other piece dies: `["1(5)", "5"] -> ["1"]`.
* If they guess wrong, nothing happens: `["1(3)", "5"] -> ["1", "5"]`.
* Spotters can spot bombs: `["1(B)", "B"] -> ["1"]`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins!
(You can use the examples up there as test-cases, because I'm too lazy to put them all together in one list).
[Answer]
# Haskell, 131 bytes
This solution is in the form of an infix function `#` with type `String -> String -> String`
Input is accepted through the two string arguments. The format for spotter input is `1 x` where `x` is the guess.Output is given as a string. In the case where both units survive, the returned string contains both separated by a space.
My original solution was unfortunately bugged and the fix cost me a few bytes.
```
('1':' ':x)#y|x==y="1"|1>0="1 "++y
"S"#"10"="S"
"3"#"B"="3"
_#"B"="B"
x#y|x==y=[]
t@"10"#_=t
_#t@"10"=t
"S"#x=x
x#"S"=x
x#y=max x y
```
[Answer]
# Python, ~~180~~ 153 bytes
```
def f(a,d,g=0):T=([[d]],[[a]]);return([[a]+[d]*(g!=d)]*(g!=0)+[[]]*(a==d)+T[d=="10"]*(a=="S")+T[1]*(d=="S")+T[a=="3"]*(d=="B")+T[int(a,36)>int(d,36)])[0]
```
The function takes the attacker, defender and optionally the spotter's guess (if the attacker is the spotter) as arguments. It returns an array containing the live pieces that remain.
**Ungolfed**
```
def f(a,d,g=0):
if g: return [a] if g==d else [a,d]
if a==d: return []
if a=="S": return [a] if d=="10" else [d]
if d=="S": return[a]
if d=="B": return [a] if a=="3" else [d]
return [a] if int(a)>int(d) else [d]
```
**Demo**
<https://repl.it/C6Oz/2>
[Answer]
# Javascript ES6, ~~98~~ 86 bytes
```
(a,b,g)=>a==1?b==g?a:[a,b]:b=="B"?a==3?a:b:a=="S"?b==10?a:b:b=="S"?a:a==b?[]:+a>+b?a:b
```
Accepts 3 args (attacker, defender, spotter guess).
Example runs:
```
f("4","6") -> "6"
f("7","7") -> []
f("S","2") -> "2"
f("S","10") -> "S"
f("10","S") -> "10"
f("5","B") -> "B"
f("3","B") -> "3"
f("1","5","5") -> "1"
f("1","5","3") -> ["1","5"]
f("1","B","B") -> "1"
```
[Answer]
# Javascript, ~~179~~ ~~166~~ 160 bytes
```
f=(a,c,b,n="")=>{if(c)if(c==b)return[a];else return[a,b];if(a==b)return[];a+b=="3B"&&(b=n);a=b=="B"?n:a;b=b=="S"?n:b;a+b=="S10"&&(a=n,b="S");return[+a>+b?a:b]}
```
This function takes 3 arguments - first one is attacker, second is used for spotters (their guess) and third is defender.
```
f = ( a, c, b, n = "" ) =>
{
//Takes attacker (a), guess (c) and defender (b), n is only declaration
//c should never be set unless a == 1
if ( c )
if ( c == b ) return [ a ];
else return[ a, b ]; //Spotters
if( a == b ) return [ ]; //Kill each other if same
a + b == "3B" && ( b = n ); //Miners destroy bombs
a = b == "B" ? n : a; //Bomb kills almost everything
b = b == "S" ? n : b; //Spy dies if anything attacks him
a + b == "S10" && ( a = n, b = "S" ); //Spies kill 10s
console.log( JSON.stringify( [a,b] ) );
return [ +a > +b ? a : b ] //Higher number wins
}
function fight( )
{
var input = [ [ attacker.value, guess.value], defender.value ];
out.innerHTML += JSON.stringify( input ) + " -> " + JSON.stringify( f( input[0][0], input[0][1], input[1] ) ) + "<br>";
}
```
```
#sword
{
width: 40px;
height: auto;
margin: 10px;
cursor: pointer;
}
#guess
{
width: 40px;
}
textarea
{
height: 20px;
margin-top: 0px;
}
.panel
{
background-color: #DDDDDD;
padding: 5px;
border: 3px solid black;
}
#out
{
border: 3px solid black;
font-family: monospace;
padding: 10px;
}
```
```
<table>
<tr>
<td class=panel>
<textarea id=attacker placeholder="Attacker"></textarea>
<textarea id=guess></textarea>
</td>
<td>
<img onclick="fight()" id=sword src="http://cliparts.co/cliparts/8cx/Kjq/8cxKjqAKi.png"></img>
</td>
<td class=panel>
<textarea id=defender placeholder="Defender"></textarea>
</td>
</tr>
<tr>
<td colspan=3>
<div id=out></div>
</td>
</tr>
</table>
```
Sword icon comes from [cliparts.co](http://cliparts.co/clipart/2916213)
[Answer]
# TSQL, ~~162~~ 124 bytes
Golfed:
```
DECLARE @1 varchar(2)='1',@ varchar(2)='3',@s varchar(2)='4'
PRINT IIF(@s>'',IIF(@=@s,@1,@1+','+@),IIF(@1=@,'',IIF(@1+@
IN('S10','3B')or'S'=@,@1,IIF(@='B'or'S'=@1,@,IIF(@1/1<@,@1,@)))))
```
Ungolfed:
```
DECLARE
@1 varchar(2)='1', -- first piece
@ varchar(2)='3', -- second piece
@s varchar(2)='4' -- spotter(only fill this value for spotters)
PRINT
IIF(@s>'',
IIF(@=@s,@1,@1+','+@),
IIF(@1=@,'',
IIF(@1+@ IN('S10','3B')or'S'=@,@1,
IIF(@='B'or'S'=@1,@,
IIF(@1/1<@,@1,@)))))
```
[Fiddle](https://data.stackexchange.com/stackoverflow/query/507002/evaluate-a-stratego-battle)
] |
[Question]
[
My local ACM chapter gives out door prizes to people who come to the meetings. You get an increased chance of winning if you solve the programming puzzle, however (but *I* always solve that puzzle). Thus, some people have 1 entry, while others have 2. But wait! The way the raffle program works is not by adding in another entry when someone solves the puzzle. Instead, it keeps track of the number of "lives" a person has, decrementing that if that person is chosen in each pass of it's random sampling algorithm. So it works like this:
```
Doorknob: 1. xnor: 2. Justin: 2. Alex: 1. Dennis: 2.
```
Then the program randomly chooses one of `[Doorknob, xnor, Justin, Alex, Dennis]`, decrements the number (say it chooses `Justin`):
```
Doorknob: 1. xnor: 2. Justin: 1. Alex: 1. Dennis: 2.
```
And repeats. If someone's number of "lives" goes to `0` (let's choose `Justin` again), they're removed from the list:
```
Doorknob: 1. xnor: 2. Alex: 1. Dennis: 2.
```
This continues until there's one person left; that person is the winner.
Now the real question is, what was the probability that I would have won?
---
You will be given two inputs:
* `n`. This is the number of people entered into the challenge
* `k`. This is the number of people (of those `n`) who have 2 lives. This number always includes you.
So if I had a function `p` and called `p(10, 5)`, that would be the probability of winning the prize where there are 10 people total, 5 of which only have 1 life, whereas 5 (including you) have 2 lives.
---
You are expected to output the probability of winning either exactly, or as a decimal. At any rate, answers must be accurate up to and including the 4th decimal place after the decimal point. Whether or not you round to that digit is up to you.
Your solution may be a randomized solution which outputs the answer to the 4th decimal place with *high probability*. You may assume that the built in RNG you use is truly random, and it must output the correct answer with at least 90% probability.
Furthermore, your code need only work for `n, k <= 1000`, although I did provide test cases larger than that for those curious.
---
## Test Cases
Note: some of these are general formulae.
```
n, k | output
----------+---------
1, 1 | 1
2, 2 | 0.5
2, 1 | 0.75
3, 1 | 11/18 = 0.611111111
1000, 1 | 0.007485470860550352
4, 3 | 0.3052662037037037
k, k | 1/k
n, 1 | (EulerGamma + PolyGamma[1 + n])/n (* Mathematica code *)
| (γ + ψ(1 + n))/n
10, 6 | 0.14424629234373537
300, 100 | 0.007871966408910648
500, 200 | 0.004218184180294532
1000, 500 | 0.0018008560286627948
---------------------------------- Extra (not needed to be a valid answer)
5000, 601 | 0.0009518052922680399
5000, 901 | 0.0007632938197806958
```
For another few checks, take `p(n, 1) * n` as follows:
```
n | output
------+---------
1 | 1
2 | 1.5
3 | 1.8333333333333335
10 | 2.928968253968254
100 | 5.1873775176396215
-------------------------- Extra (not needed to be a valid answer)
100000| 12.090146129863305
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 42 bytes
```
:<~QXJx`J`tf1Zry0*1b(-tzq]f1=vts3e8<]6L)Ym
```
This uses a probabilistic (Monte Carlo ) approach. The experiment is run a large number of times, from which the probability is estimated. The number of realizations is selected to *ensure* that the result is correct up to the fourth decimal with probability at least 90%. However, this takes a very long time and a lot of memory. In the link below the number of realizations has been reduced by a factor of 106 so that the program ends in a reasonable amout of
time; and only the *first* decimal is guaranteed to be accurate with at least 90% probability.
*EDIT (July 29, 2016): due to changes in the language, `6L` needs to be replaced by `3L`. The link below incorporates that modification.*
[**Try it online!**](http://matl.tryitonline.net/#code=Ojx-UVhKeGBKYHRmMVpyeTAqMWIoLXR6cV1mMT12dHMzZTI8XTNMKVlt&input=Mwox)
### Background
Let *p* denote the probability to be computed. The experiment described in the challenge will be run for a number *n* of times. Each time, either you win the prize (“*success*”) or you don't. Let *N* be the number of successes. The desired probability can be *estimated* from *N* and *n*. The larger *n* is, the more accurate the estimation will be. The key question is how to select *n* to fulfill to the desired accuracy, namely, to assure that at least 90% of times the error will be less than 10−4.
Monte Carlo methods can be
* *Fixed-size*: a value of *n* is fixed in advance (and then *N* is random);
* *Variable-size*: *n* is determined on the fly by the simulation results.
Among the second category, a common used method is to fix *N* (desired number of successes) and *keep simulating until that number of successes is achieved*. Thus *n* is random. This technique, called *inverse binomial sampling* or *negative-binomial Monte Carlo*, has the advantage that the accuracy of the estimator can be bounded. For this reason it will be used here.
Specifically, with negative-binomial Monte Carlo *x* = (*N*−1)/(*n*−1) is an unbiased estimator of *p*; and the probability that *x* deviates from *p* by more than a given ratio can be upper-bounded. According to equation (1) in [this paper](http://oa.upm.es/4350/2/MENDO_ART_2008_01.pdf) (note also that the conditions (2) are satisfied), taking *N* = 2.75·108 or larger ensures that *p*/*x* belongs to the interval [1.0001, 0.9999] with at least 90% probability. In particular, this implies that *x* is correct up to the 4th decimal place with at least 90% probability, as desired.
### Code explained
The code uses *N* = `3e8` to save one byte. Note that doing this many simulations would take a long time. The code in the link uses *N* = `300`, which runs in a more reasonable amount of time (less than 1 minute in the online compiler for the first test cases); but this only assures that the *first* decimal is correct with probability at least 90%.
```
: % Take k implicitly. Range [1 ... k]
<~ % Take n implicitly. Determine if each element in the previous array is
% less than or equal than n
Q % Add 1. This gives an array [2 ... 2 1 ... 1]
XJx % Copy to clipboard J. Delete from stack
` % Do...while. Each iteration is a Monte Carlo realization, until the
% desired nunber of successes is reached
J % Push previously computed array [2 ... 2 1 ... 1]
` % Do...while. Each iteration picks one door and decrements it, until
% there is only one
t % Duplicate
f % Indices of non-zero elements of array
1Zr % Choose one of them randomly with uniform distribution
y0* % Copy of array with all values set to 0
1b( % Assign 1 to chosen index
- % Subtract
tzq % Duplicate. Number of nonzero elements minus 1. This is falsy if
% there was only one nonzero value; in this case the loop is exited
] % End do...while
f1= % Index of chosen door. True if it was 1 (success), 0 otherwise
v % Concatenate vertically to results from previous realizations
ts3e8< % Duplicate. Is the sum less than 3e8? If so, the loop is exited
] % End do...while
6L) % Remove last value (which is always 1)
Ym % Compute mean. This gives (N-1)/(n-1). Implicitly display
```
[Answer]
# Pyth, 34 bytes
```
Mc|!*HJ-GHch*J+*tHgGtH*gtGHKh-GHKG
```
[Test suite](https://pyth.herokuapp.com/?code=Mc%7C%21%2aH-GH%2Bch%2a%2a-GHtHgGtHh-GH%2a-GHgtGHGgEE&test_suite=1&test_suite_input=1%0A1%0A2%0A2%0A2%0A1%0A3%0A1%0A1000%0A1%0A4%0A3%0A10%0A6%0A300%0A100%0A500%0A200&input_size=2)
Defines a deterministic memoized recursive function `g` taking *n*, *k* as arguments. `g 1000 500` returns `0.0018008560286627952` in about 18 seconds (not included in the above test suite because it times out the online interpreter).
An approximate Python 3 translation would be
```
@memoized
def g(n,k):
return (not k*(n-k) or (1+(n-k)*((k-1)*g(n,k-1)+g(n-1,k)*(n-k+1)))/(n-k+1))/n
```
[Answer]
## JavaScript (ES6), 65 bytes
```
f=(n,k,d=n-k)=>(!d||(f(n-1,k)*++d*--d+1+(--k&&f(n,k)*k*d))/++d)/n
```
Don't try it with the big numbers though; even f(30, 10) takes a noticeable amount of time.
] |
[Question]
[
Write some code that takes a single non-negative integer \$n\$ and outputs the \$n\$th power of phi (\$\phi\$, the Golden Ratio, approximately 1.61803398874989) with the same number of decimal digits as the \$n\$th Fibonacci number.
Your code must produce the correct sequence of digits for all inputs up to at least 10 (55 decimal digits). The output must be human-readable decimal. You may choose whether to round the last digit to the closest value, or truncate the value. Please specify which one your code uses.
\$n\$ and output, up to 10, rounding down:
```
0 1
1 1.6
2 2.6
3 4.23
4 6.854
5 11.09016
6 17.94427190
7 29.0344418537486
8 46.978713763747791812296
9 76.0131556174964248389559523684316960
10 122.9918693812442166512522758901100964746170048893169574174
```
\$n\$ and output, up to 10, rounding to the closest value:
```
0 1
1 1.6
2 2.6
3 4.24
4 6.854
5 11.09017
6 17.94427191
7 29.0344418537486
8 46.978713763747791812296
9 76.0131556174964248389559523684316960
10 122.9918693812442166512522758901100964746170048893169574174
```
The 7th Fibonacci number is 13, so the output for \$n=7\$, \$\phi^7\$, has 13 decimal places. You must not truncate trailing zeros that would display too few digits; see output for 6 in the first table, which ends in a single zero to keep the decimal precision at 8 digits.
Maybe as a bonus, say what the highest number your program can correctly output is.
[Answer]
# dc, 26 bytes
```
99k5v1+2/?^d5v/.5+0k1/k1/p
```
Due to the initial precision of 99 digits after the comma, this will work up yo input **11**. A dynamic (or higher static) precision is possible, but would elevate the byte count.
### Test cases
```
$ for ((i = 0; i < 11; i++)) { dc -e '99k5v1+2/?^d5v/.5+0k1/k1/p' <<< $i; }
1
1.6
2.6
4.23
6.854
11.09016
17.94427190
29.0344418537486
46.978713763747791812296
76.0131556174964248389559523684316960
122.9918693812442166512522758901100964746170048893169574174
```
### How it works
Since the desired output is **φn**, we can calculate the the Fibonacci number **F(n)** as **⌊φn ÷ √5 + 0.5⌋** with little additional effort.
```
99k Set the precision to 99.
5v Compute the square root of 5.
1+ Add 1.
2/ Divide by 2.
This pushes the golden ratio.
? Read the input from STDIN.
^ Elevate the golden ratio to that power.
d Push a copy.
5v/ Divide it by the square root of 5.
.5+ Add 0.5.
0k Set the precision to 0.
1/ Divide by 1, truncating to the desired precision.
This pushes F(n).
k Set the precision to F(n).
1/ Divide by 1, truncating to the desired precision.
p Print.
```
[Answer]
# Mathematica, 50 bytes
```
N[GoldenRatio^#,2^#]~NumberForm~{2^#,Fibonacci@#}&
```
Basic solution. Rounds to the nearest value. ~~Still verifying the highest value that won't make my computer run out of memory.~~ Input `32` works, but it takes 45 minutes and uses 16GiB of RAM. However, given infinite time and memory, this could theoretically run for any value.
[Answer]
# Javascript, 65 bytes
```
a=>Math.pow((1+Math.sqrt(5))/2,a).toFixed(k(a));k=b=>b?b+k(b-1):0
```
Getting Phi by calculating `(1+Math.sqrt(5))/2`.
Getting Fib value using the function: `k=b=>b?b+k(b-1):0`.
[Try it out](https://tio.run/##bc65EsIgFIXh3ie5TAyGaFyH2Nn5EJCQiMSAwLg8PS6dc@3OfHOK/yxuIjReu5gHp1vlL3Y06pk6ngSvjyKeqLN3AJZ9d7j6CBUhs3IqCI32oB@qBQOCkJ3hktdyLzMDMmdkW6TGjsEOig62hw6K92fySwxTiWmOaYGpwrTEtMK0xrT5k/rJTy8)
] |
[Question]
[
(FB, or Functional-Basic, as found here [Interpret Functional-Basic](https://codegolf.stackexchange.com/questions/69505/interpret-functional-basic))
## Task
Implement a linting program for FB, similar to JSLint for JavaScript.
## Error types
### Invalid identifier
Identifiers can only have upper and lower case ASCII letters.
Locations:
* The identifier right after a `let` expression
* The identifier in a `for` loop
Examples:
```
for (? in b) <-- ? is invalid
let b_b8 = ... <-- b_b8 is invalid
```
### Undefined identifier
If you encounter an identifier that has not been defined in either a `let` expression or a `for` loop. Note that the identifier in a for loop *only* count in the expression following it.
Location:
* Anywhere an identifier is used
Example program:
```
let b = a <-- nope
for (x in a) x+1 <-- nope, still don't know what `a` is
print x <-- gotcha! `x` is out of scope here
```
### Unexpected EOL
End of line is the deliminator for statements in FB, so you can't have a statement span multiple lines (even if it's surrounded by parenthesis `()`). Use this if you expected more but encountered a EOL char.
Locations:
* Any line
Examples:
```
let b <-- missing the `= [statement]`
for ( <-- missing `x in y) [statement]`
print <-- print what?
print print sum <-- sum what?
```
### Unexpected token
This is best explained by examples.
Locations:
* Any line
Examples:
```
print * 2 <-- What is `*2` doing for me? I need a statement!
3**5 <-- `3*` expects a number, not a `*` symbol
for x in y <-- a little diffrent, but for
expects a pren `(`, not x
```
### Improper type
Used when a list is expected and a number was encountered, or when a number is needed and you get a list. Lists in FB are only allowed to have numbers or other lists as children, so errors can occur here as well. Note that if you find an identifier that is valid, you should perform this check based on the id's type.
Locations:
* Function application
* `for` loops
* The `+-*/^` operators
* List literal creation
Examples:
```
let y = [5]
let z = y + [[], [6]] <-- invalid, y is a list of numbers, right
hand side is a list of lists
print y + 1 <-- y is a list, not a number
sum 1 <-- sum takes a list, not a number
[5] - [5] <-- invalid, subtraction doesn't apply to lists
1 + [] <-- addition doesn't work with a list and a number
for (digit in 12) ... <-- `for` takes a list
let list = [00, 00]
let nlst = [list, 1] <-- invalid
[1, []] <-- invalid
```
### Multiple assignment
This is when a `for` loop or `let` statements identifiers overlap with a currently defined identifier.
Locations:
* In a `for` loop
* In a `let` statement
Examples:
```
let y = 8
let y = 5 <-- invalid, y is already defined
for (y in []) <-- invalid, y is already defined
for (x in []) ...
let x = 8 <-- valid since the `x` in the for loop is out of scope
```
### Nested for loop
Again, pretty self explanatory. FB doesn't allow nested for loops.
Locations:
* In `for` loops
Examples:
```
for (x in [[1, 5], [2, 8]]) for (y in x) x*y <-- just invalid
```
## Input format
If you are writing a function, you will receive one multi-line string. If you are writing a full program, you must take a multi-line input.
## Output format
Output format is simply the error title, followed by the line number the error occurs on. You must show all errors in the program.
Format:
```
[error title] on line [line number, 1-indexed]
```
## Example
This is one large example that should show all possible error types and outputs. Please let me know if I missed something.
### Input
```
let bb8 = 0
let bbEight = lst
for (x in
let x = 5*/5
let y = 4
let z = [5, 6] + y
let y = [[4]] + [y]
for (x in [[y, y+1], 5]) for (y in x)
```
### Output
```
Invalid identifier on line 1
Undefined identifier on line 2
Unexpected EOL on line 4
Unexpected token on line 5
Improper type on line 6
Improper type on line 7
Multiple assignment on line 7
Nested for loop on line 8
Multiple assignment on line 8
Multiple assignment on line 8
Improper type on line 8
Unexpected EOL on line 8
```
Note that thees checks may come in any order, and if the same error occurs multiple times on the same line, you must print the error multiple times as well.
I hope this isn't to difficult
## Edits
I have removed the `Empty line` error since it didn't make sense, and nobody is working on the problem (to my knowledge).
[Answer]
# Python3, 2381 bytes:
```
import re
N=lambda x:next(x,0)
G={'sum':[[2,1],1],'product':[[2,1],1],'print':[-1,[2]]}
P={'+':[(1,1),(2,2)]}
def s(l):
r=[]
while l:r+=[j:=re.search('\w+|\(|\)|\=|\+|\-|\*|/|\^|\[|\]|,|\s+|\W+',l).group()];l=l[len(j):]
return filter(lambda x:x.strip(),r)
M=['Invalid identifier','Undefined identifier','Unexpected EOL','Unexpected token','Improper type','Multiple assignment','Nested for loop']
B=lambda x:x if int==type(x)else x[0]
F=lambda I,n:M[I]+f' on line {n}'
def O(l,n,E,t=-1,c=2):
if l==0:c=2
if t==-2:c=c
if (t==-1 and l)or l==t:return l
E(F(c,n));raise Exception
def A(b,s,k,v):
if v:b[s][k]=v
def X(l,n,s,b,E,C,L=0,W=0):
v,U=0,0
while 1:
if(k:=N(l))==0 and v:break
if O(k,n,E)not in[')',']']:
if k in'+-*/^':
if v==0:O(1,n,E,-2,3)
V,l=X(l,n,s,b,E,C)
if(B(v),B(V))not in P.get(k,[(1,1)])or v!=V:O(1,n,E,-2,4)
v=V;U=1
elif U and k!=',':O(0,n,E,-2,3)
elif k==',':l=iter([k,*l])
if'for'==k:
if L:E(F(6,n))
v=C(iter([k,*l]),n,s,b,E);U=1
elif'('==k:
v,l=X(l,n,s,b,E,C);O(N(l),n,E,')',2);U=1
elif k.isalpha():
if k in G:
V,l=X(l,n,s,b,E,C,0,1)
if V==0:O(0,n,E)
if G[k][0]!=-1 and G[k][0]!=V:O(1,n,E,-2,4)
v=G[k][1];U=1
else:
if k not in b[s]:O(1,n,E,-2,1)
v=b[s][k]
U=1
elif k.isdigit():
v=1;U=1
elif'['==k:
L=[]
while 1:
V,l=X(l,n,s,b,E,C)
if V:
L+=[V]
if(k:=N(l))==']':v=L;break
O(k,n,E,',',3)
else:O(O(N(l),n,E),n,E,']',3);break
if(_:=len(Y:=set(map(str,L))))==1:v=[2,eval([*Y][0])]
else:
if _>1:E(F(4,n))
v=[2]+([]if[]==L else[-1])
U=1
else:break
if U and W:break
else:l=iter([k,*l]);break
return v,l
def p(l,n,s,b,E):
k=N(l)
if'let'==k:
if O(k:=N(l),n,E).isalpha()==0:E(F(0,n))
else:
if(I:=(k in b[s])):E(F(5,n))
O(x:=N(l),n,E);O(x,n,E,'=',3);V,l=X(l,n,s,b,E,p)
if not I:A(b,s,k,V)
elif'for'==k:
O(N(l),n,E,'(',3);O(x:=N(l),n,E);O(1,n,E,x.isalpha(),0);O(m:=N(l),n,E);O(m,n,E,'in',3)
if x in b[s]:E(F(5,n))
V,l=X(l,n,s,b,E,p)
O(V,n,E);O(N(l),n,E,')',2)
if type(V)==int:E(F(4,n))
V,l=X(l,n,(0,n),{**b,(0,n):{x:V if type(V)==int else V[1]}},E,p,1);O(V,n,E);return[2,V]
return[2]
elif k in G:l=iter([k,*l]);V,l=X(l,n,s,b,E,p)
def D(l):
b,E={(0,):{}},[]
for i,a in enumerate(filter(None,l.split('\n')),1):
try:p(s(a),i,(0,),b,E.append)
except:1
return E
```
[Try it online!](https://tio.run/##dVZtb@I4EP6eX@H2S2xwKWHb1SrIJ113uxUSLas7ld7KeFcBTOuNSaIksOFKf3tv7Lzw0h7iQ2bseXvmmUmSTf4URx8@Jenrq1omcZqjVDp3TAfL6TxAhR/JIscF7RLnhj272Wrp@pz3qCfM303SeL6a5Uc6FRnNmUd5T4gX5xsYtkGBPeoRinu0R0A7lwuUYU18B6WMCwf9flJaIu2nbcZ/@SyVnUwG6ewJu5Pf7e0EbydkO2HbCTyfbSet7fl28mM74duJ2NLtJAP1Q9ulmnQe03iVYCL6mmmuZYR/ER/8pzJfpRFaKJ3LFDcFFp0sTxXcpylxbhl3B9E60GqO1FxGuVoombrUvY8gXxXJN2pZJHKWg/56NDxU5HEoI1ANloBSIlOUbxIJ8u1K5yqBUoMsU4/REtyB9k5mxmgRp0jHceIK52rXhAKpBQJUGTM@cEGkziQqeFc4X@tbAxr5t3wg2gsXxRHSkCx6jl5cC/QIaxrRa5oz6MqM9Qzq4FIz1vVBtAJ4P@uBNLMSNqKHgmiONDFJQWy/glA76Bp/xTMaEdJPAwW5XBczmeQqjmy4P/GUZjSk6yrO2p/yTPBQsLU9/8emk9EppPSZDlmXPrCuubum9yB0azJ4oAJ7HPrsDqhCIF2bEfhLZRDaQ6gtNLWRKM4BI@4SQFO4wpia4xCUbvusdf7DtSqbj6l7BHw0mJz16AdiT8ZUs4PUSGWAr/Ca0Cs8JlUU9K3zKHMIXJJaGITWJ2y87/SitF6zcf@eeeZZaoh9bysITxikCde7hznYKyGzh5opw1Qe0pYWpCzHBYK4jIVNKUPftOKjaUUV7jPeN6uLIftJuHjnY/2m6P4IG7RtYgbN3oEtCjsqC3TyFGDSZGFARjel@BZG2gWMyjO4Oy7Bt4XvtDfADuDzSU26Rn4PU6jSnnuizgyZifAbbyGq@mR4t@/AaxxUjLTicXlz9ajyurw18w6w4zvshnZxwW@Prv/PI1t8dQUNYcuNRSUcUBzI66/ZsF9T3PwqjlOgRU3WsuIR3jWr6pgwV/aswflPn5k9@N1nGbB2GSQYdh4dEmLieRANtreErYd567tBnYh3MP35h2e5dtFwDRlD0cZcqAUXjA2tBSz@kq07WMFNk08zAg@Nzl44ZHudf7VxgKR2cSQ7VE13QouZWTGulnndl3InlHhaXHaENdQzNXSrGpoKAaSBz3BYc4YQe@@yrnWEiz2HMCFFCTazYB83PKmm1bJw4NfrcAxqS6G9Id6fNWydvQlVkrfYVQFvY1AvD28tSx@w7EqGQPSimYD9Wt5NdoTHtaOj2S9d2ffOGPCDt9ABC3beLKj0udWalo/@c@GPj20t4mgMk/vyYmLDQPab2GWzgYt2MGpJONVgljvmiCfvVGOI8qX8sgANe4ZsIBmIZ4bVvGAVDYwvGa2WMg1yiatvgrs4klR3skTD9LuTyCUE8jNdytOND0ODA0KVqY6YWJ0gSWQ0tzyyrz/fawh7/fr3X5/Z6ekp8BJNp58QQ12nfL5Wj085yDrLHcekg22f7GkB@svW@aUVNiBc2Kd/4YlfUvRRoDbaNIecXwij4Rux54jzDUWbNnyKoUtBbMF4Yw4KAvk49vMMf8GQHyGv/wE)
] |
[Question]
[
# About Functional-Basic
Functional-Basic (FB for short) is a language that only allows numbers and lists. Basic features, such as the `if` statement are missing in an attempt to simplify the language.
Everything in this language is immutable. `input` is always assigned to the script input, which can be either a number or a list.
## Basic operators
Note that you must support the order of operations for these. (<https://en.wikipedia.org/wiki/Order_of_operations#Definition>)
* `+`: Addition - Applies to both numbers and lists.
* `-`: Subtraction - Only applies numbers.
* `*`: Multiplication - Only applies numbers.
* `/`: Division - Only applies numbers.
* `^`: Exponentiation - Only applies numbers.
## Functions you must implement
* `sum: List of numbers -> Number` Sum a list of numbers. Sum of `[]` is `0`.
* `product: List of numbers -> Number` Get the product of a list. Product of `[]` is `1`.
* `print: Anything -> [empty list]` Print the value to standard out. Returns empty list. `print` always ends in a newline.
### Output format of the `print` function
The output should look like how it would be coded literally into the program, with the minor change that one space is required after a comma in lists. The values infinity and negative infinity are `Infinity` and `-Infinity` respectively. `Not a number` is represented by `NaN`.
# Syntax
The syntax for FB is very simplistic. Below is a description of each major section of the syntax.
### Useful terms
```
identifier : a string of only letters
```
### Variable declaration
Though I call them variables, they are really immutable. The only place where a space is required in the syntax is between the `[name]` and `let`. `name`s will never contain numbers, just upper and lower case ASCII letters. For simplicity you can assume that identifiers will never be used twice, even in `for` loops. Also names will not overlap with built-ins (`let`, `sum`, `for`, ...). Syntax:
```
let [identifier] = [some expression][newline]
```
Some examples:
```
let sumOfLst=sum [1,2]
let prod = product [2,2]
```
### Numbers
Numbers in FB conform to the IEEE 754/854 standard, with implementations providing a minimum of 32-bit precision. `NaN`, `Infinity` and `-Infinity` will not occur in the program source, but may be a result of a calculation.
### Lists
Lists have a very limited set of capabilities. You can add lists together with `+`, and you can map over them with `for`. No indexed array access is supported here. Lists *can* have nested list inside them, but if it does it won't have any numbers as direct sub-children (i.e. lists don't mix types). List have only 2 ways to be created, the literal syntax and by mapping over a list with a `for` loop.
Syntax is just like most list types in other languages.
Examples:
```
let b = [] <-- not sure what you can do with a empty list...
let c = [5, 6]
let d = [5, []] <-- invalid
let e = [[5, 2, 6], [6]] <-- valid
let f = [5] + 5 <-- invalid
let g = [5] + [5] <-- valid
let h = [[6, 2], []] + [] <-- valid
let i = [[6, 2], []] + [5] <-- invalid
```
### For loops
For loops in FB behave much like `map` in other languages in that it returns a list with the function applied to each element of the list. For simplicity you will never have nested `for` loops. Identifiers from outer scopes may be used in the expression. The expression will always be on the same line.
Syntax:
```
for ([identifier] in [list, may
be an identifier pointing to a list]) [expression]
```
Examples:
```
for(x in lst) x+1
let nList = for (bestNameEver in [2, 5, 6]) bestNameEver^2
let lstOfLsts = for (i in b) [b, b+1]
for(x in [1, 2, 3])print x
```
### Functions
Really only 3 functions exist in FB, `sum`, `product`, and `print`. Refer to the list above for definition of how they should work. All functions have an arity of 1. Function application consists of the name of the function, a space and an expression as the argument. Functions will take the very next thing after them as their argument, even if it is another function. If the arg is another function it will force the evaluation of that function to receive it's arguments. Example:
```
print sum [5]
prints argument is sum.
print (sum) [5]
sum grabs the list since that is the next thing and evaluates it.
print (5)
```
Syntax:
```
[function name][minimum one space][expression as the argument]
```
Examples:
```
print [5, 1]
sum [6, 7]
print 1+2 <-- This is invalid, because print grabs the `1`
and returns `[]`, and `[]+2` is invalid
print (1+2) <-- This is valid
```
### Other syntax features
Parenthesis are supported.
Example:
```
print ((1+2)*5)
```
## Handling errors
You can assume that all programs you will receive are syntactically correct and will not violate any rules placed on numbers and lists. The only thing that results in a error case is division by zero (`x/0`). If you encounter a division by zero you simply halt execution of your program and print `Division by zero!` to either stdout or stderr.
## Examples
Code and output. (`>` denotes code):
```
>print sum [1, 2, 3]
6
>print for (x in [1, 2, 3]) x+2
[3, 4, 5]
>let aFloat = 4.2
>let aInt = 5
>let aList = [aFloat, aInt]
>print product aList
21
>let x = for (y in [2.3, 5.6]) y/5*6
>print product x
18.5472
>let superSecretNumber = 0
>print superSecretNumber
0
Input: [2, 3, 4]
>for (i in input) print i*2
4
6
8
>let answerToLife = 6*9
>print answerToLife
54
>print print sum [5, 2]
7
[]
>let a = [1, 2, 3]
>let b = for (x in a) [x, x+1]
>print b
[[1, 2], [2, 3], [3, 4]]
>print print []
[]
[]
>print for (i in [1, 2, 3]) print i
1
2
3
[[], [], []]
```
[Answer]
# Python 2.7, 979
I'm sure I could golf it further, but I don't see the point yet as I'm the only answer for the moment - I'm a bit lazy
Here is the code of my interpreter :
```
import sys,re
V={}
S=lambda m:re.sub(' +',';',m).split(';')
def P(t):print t;return []
def E(t):
if len(t)==1:return t[0]
y=E(t[1:])
return{'print':'P('+y+')','sum':'sum('+y+')','product':'reduce(lambda x,y:x*y'+y+',1)'}[t[0]]
def e(t):
y=t[0]
if y=='let':v=V[t[1]]=e(t[3:]);return v
if y=='print':v=e(t[1:]);return P(v)
if y=='sum':return sum(e(t[1:]))
if y=='product':return reduce(lambda x,y:x*y,e(t[1:]),1)
if y=='for':c=S(R(t[1][1:-1].replace('/',' ')));return eval('map(lambda %s:%s,%s)' % (c[0],E(t[2:]),str(e(c[2:]))))
if y[0]=='[':v=V['input']=eval(re.sub('([a-zA-Z]+)',"V['\\1']",y));return v
if re.match('[0-9]+',y):v=V['input']=eval(y);return v
return V[y]
def R(s, u='[',e=']',r=''):
m,b='',1
for c in s:
if b:
m+=c
if c==u:b=0
else:
m+=r if c==' 'else c
if c==e:b=1
return m
def i(s):
try:e(S(R(R(s.replace('^','**'),'(',')','/'))))
except ZeroDivisionError:print 'Division by zero!';sys.exit(1)
while 1:print '>',;i(raw_input())
```
You can play with it [here](https://repl.it/BeuZ)
] |
[Question]
[
## Input
A matrix `M` represented as two space separated lines of integers. Each line will have the same number of integers and each integer will be either -1 or 1. The number of integers per line will be at most 20. `M` will therefore be `2` by `n` where `n` is the number of integers on each of the two lines.
Your code should be a complete program. and accept the input either on standard in or from a file (that is your choice). You can accept input from standard in, from a file or simply as a parameter. However, if you do the latter please give an explicit example of how your code should work and remember that it must be a complete program and how the matrix `M` will be represented in the input. In other words, you are likely to have to do some parsing.
## Output
The [binary Shannon entropy](https://en.wikipedia.org/wiki/Entropy_(information_theory)) of the distribution of `M*x` where the elements of `x` are uniformly and independently chosen from {-1,1}. `x` is an `n`-dimensional column vector.
The entropy of a discrete probability distribution is
```
- sum p_i log_2(p_i)
```
In this case, `p_i` is the probability of the `i`th unique possible `M*x`.
## Example and helpful hints
As a worked example, let the matrix `M` be
```
-1 1
-1 -1
```
Now look at all `2^2` different possible vectors `x`. For each one we compute `M*x` and put all the results in an array (a 4-element array of 2-component vectors). Although for each of the 4 vectors the probability of it occurring is `1/2^2 = 1/4`, we are only interested in the number of times each *unique* resultant vector `M*x` occurs, and so we sum up the individual probabilities of the configurations leading to the same unique vectors. In other words, the possible unique `M*x` vectors describe the outcomes of the distribution we're investigating, and we have to determine the probability of each of these outcomes (which will, by construction, always be an integer multiple of `1/2^2`, or `1/2^n` in general) to compute the entropy.
In the general `n` case, depending on `M` the possible outcomes of `M*x` can range from "all different" (in this case we have `n` values of `i` in `p_i`, and each `p_i` is equal to `1/2^n`), to "all the same" (in this case there is a single possible outcome, and `p_1 = 1`).
Specifically, for the above `2x2` matrix `M` we can find by multiplying it with the four possible configurations (`[+-1; +-1]`), that each resulting vector is different. So in this case there are four outcomes, and consequently `p_1 = p_2 = p_3 = p_4 = 1/2^2 = 1/4`. Recalling that `log_2(1/4) = -2` we have:
```
- sum p_i log_2(p_i) = -(4*(-2)/4) = 2
```
So the final output for this matrix is 2.
## Test cases
Input:
```
-1 -1
-1 -1
```
Output:
```
1.5
```
Input:
```
-1 -1 -1 -1
-1 -1 -1 -1
```
Output:
```
2.03063906223
```
Input:
```
-1 -1 -1 1
1 -1 -1 -1
```
Output:
```
3
```
[Answer]
# Perl, ~~160~~ ~~159~~ 141 bytes
*includes +1 for `-p` since 141 byte update*
```
@y=(@z=/\S+/g)x 2**@z;@{$.}=map{evals/.1/"+".$&*pop@y/egr}glob"{-1,+1}"x@z}{$H{$_.$2[$i++]}++for@1;$\-=$_*log($_/=1<<@z)/log 2 for values%H;
```
The input is expected on `STDIN` as 2 lines consisting of space-separated `1` or `-1`.
Run as `perl -p 140.pl < inputfile`.
It won't win any prizes, but I thought I'd share my effort.
Explained:
```
@y= # @y is (@z) x (1<<$n)
(@z = /\S+/g) # construct a matrix row from non-WS
x 2**@z; # repeat @z 2^$n times
@{$.} = map { # $.=$INPUT_LINE_NUMBER: set @1 or @2
eval s/.1/"+".$&*pop@y/egr # multiply matrix row with vector
} glob "{-1,+1}" x @z # produce all possible vectors
}{ # `-p` trick: end `while(<>)`, reset `$_`
$H{ $_ . $2[$i++] }++ # count unique M*x columns
for @1;
$\ -= $_ * log($_/=1<<@z) / log 2 # sum entropy distribution
for values %H;
```
**DATA**
* *update 159: save 1 by eliminating `()` by using `**` instead of `<<`.*
* *update 141: save 18 by using `$.` and `-p`.*
[Answer]
# Pyth, 37 bytes
```
K^_B1lhJrR7.z_s*LldcRlKhMrSmms*VdkJK8
```
[Test suite](https://pyth.herokuapp.com/?code=K%5E_B1lhJrR7.z_s%2aLldcRlKhMrSmms%2aVdkJK8&test_suite=1&test_suite_input=-1+-1+%0A-1+-1%0A-1+-1+-1+-1%0A-1+-1+-1+-1%0A-1++-1++-1++1%0A1++-1++-1++-1&debug=0&input_size=2)
This is somewhat trickier when you have to manually implement matrix multiplication.
### Explanation:
```
K^_B1lhJrR7.z_s*LldcRlKhMrSmms*VdkJK8
JrR7.z Parse input into matrix, assign to J.
_B1 [1, -1]
K^ lhJ All +-1 vectors of length n, assign to K.
m K Map over K
m J Map over the rows of J
s*Vdk Sum of vector product of vector and row.
S Sort
r 8 Run length encode.
hM Take just occurrence counts.
cRlK Divide by len(K) to get probabilities.
*Lld Multiply each probabiliity by its log.
s Sum.
_ Negate. Print implicitly.
```
[Answer]
# Mathematica, 48 68 bytes
Edit: Preprocess is added for accepting string as the parameter.
With the help of `Tuples` and `Entropy`, the implementation is both concise and readable.
```
Entropy[2,{-1,1}~Tuples~Length@#.#]&@Thread@ImportString[#,"Table"]&
```
where `Tuples[{-1,1},n]` gives all possible `n`-tuples from `{-1,1}`, and `Entropy[2,list]` gives the base-2 information entropy.
One of the cool things is that *Mathematica* will actually return an accurate expression:
```
%["-1 -1 \n -1 -1"]
(* 3/2 *)
```
Approximate result can be achieved with an extra `.` added (`Entropy[2., ...`).
[Answer]
## MATLAB, 196 194 187 184 126 154 bytes
(The extra 28 bytes from 126 to 154 are due to input parsing: now the code accepts the input as two lines of whitespace-separated numbers.)
```
f=@()str2num(input('','s'));M=[f();f()];n=size(M,2);x=(dec2bin(0:n^2-1,n)-48.5)*2*M';[~,~,c]=unique(x,'rows');p=accumarray(c,1)/2^n;disp(-sum(p.*log2(p)))
```
Ungolfed version:
```
f=@()str2num(input('','s')); % shorthand for "read a line as vector"
M=[f();f()]; % read matrix
n=size(M,2); % get lenght of vectors
x=(dec2bin(0:n^2-1,n)-48.5)*2*M'; % generate every configuration
% using binary encoding
[~,~,c]=unique(x,'rows'); % get unique rows of (Mx)^T
p=accumarray(c,1)/2^n; % count multiplicities and normalize
disp(-sum(p.*log2(p))) % use definition of entropy
```
I could do away with 6 bytes if an "`ans = ...`" type of output was allowed, I'm never sure about this.
I'm sorry to say that my original and *surely* witty solution was way too ungolfed compared to my current solution. This is also the first time I'm using `accumarray`. A six-input-parameter application still has to wait, though:)
Outputs (following `format long`):
```
[-1 1
-1 -1]
2
[-1 -1
-1 -1]
1.500000000000000
[-1 -1 -1 -1
-1 -1 -1 -1]
2.030639062229566
[-1 -1 -1 1
1 -1 -1 -1]
3
```
Outputs with the default `format short g`:
```
[-1 1
-1 -1]
2
[-1 -1
-1 -1]
1.5
[-1 -1 -1 -1
-1 -1 -1 -1]
2.0306
[-1 -1 -1 1
1 -1 -1 -1]
3
```
] |
[Question]
[
[Innovation](https://boardgamegeek.com/boardgame/63888/innovation) is a card game where players battle through the ages, from prehistory to modern times, in an attempt to earn achievements faster than their opponents.
Each card in Innovation is unique, and provides a player with a number of icons. If we treat each card as a 2x3 grid, then three of the four slots on the left and bottom edges will always been taken up by icons (the symbols in black hexagons are not counted).
[](https://i.stack.imgur.com/fWnflm.jpg)
The game has 6 types of icons (castles, crowns, leaves, lightbulbs, factories and clocks), which we will represent arbitrarily using the chars `012345`. Using `#` to represent the black hexagon, we can use four chars to represent the icons on each card. For example, the cards above are
```
0.. #.. 3.. 1.. -> 03#0 #331 355# 144#
3#0 331 55# 44#
```
Now, in Innovation, cards in the play area are grouped into piles\* which are splayed in one of four ways. For each example we'll use the cards above, assuming the leftmost card, `03#0`, is at the top of the pile.
**No splay:** only the top card is visible
```
0..
3#0
```
**Splay left**: the top card is fully visible, as well as the right third of all cards below
```
0..|.|.|.|
3#0|1|#|#|
```
**Splay right**: the top card is fully visible, as well as the left third of all cards below
```
1|3|#|0..
4|5|3|3#0
```
**Splay up**: the top card is fully visible, as well as the bottom half of all cards below.
```
0..
3#0
---
331
---
55#
---
44#
```
### The challenge
Input will be a single space-separated string consisting of two parts:
* A splay direction, which is one of `!<>^`, representing no splay, splay left, splay right or splay up respectively.
* A non-empty list of cards, each of which is 4 characters long and consisting of the chars `012345#`. The leftmost card is at the top of the pile, and each card contains exactly one `#`.
Answers may be [functions, full programs or equivalent](https://codegolf.stackexchange.com/tags/code-golf/info). You may choose whether the splay direction is first or last, i.e. choose one of the two formats below:
```
> 03#0 #331 355# 144#
03#0 #331 355# 144# >
```
Output will be a list of six numbers representing the count for each icon, e.g. for the example cards above:
```
! 03#0 #331 355# 144# -> 2 0 0 1 0 0
< 03#0 #331 355# 144# -> 2 1 0 1 0 0
> 03#0 #331 355# 144# -> 2 1 0 3 1 1
^ 03#0 #331 355# 144# -> 2 1 0 3 2 2
```
For instance, the no splay case had two `0` icons and one `3` icon showing, giving the first line. Note that we don't count `#`s, since the black hexagons aren't icons.
You may choose any reasonable and non-ambiguous way of representing the list, e.g. delimiter-separated or using your language's natural list representation.
### Test cases
```
! 113# -> 0 2 0 1 0 0
< 113# -> 0 2 0 1 0 0
> 113# -> 0 2 0 1 0 0
^ 113# -> 0 2 0 1 0 0
! 000# 12#2 -> 3 0 0 0 0 0
< 000# 12#2 -> 3 0 1 0 0 0
> 000# 12#2 -> 3 1 1 0 0 0
^ 000# 12#2 -> 3 0 2 0 0 0
! 000# 111# 222# -> 3 0 0 0 0 0
< 000# 111# 222# -> 3 0 0 0 0 0
> 000# 111# 222# -> 3 2 2 0 0 0
^ 000# 111# 222# -> 3 2 2 0 0 0
! 335# #101 21#2 333# 2#20 3#33 4#54 #133 3#33 32#2 -> 0 0 0 2 0 1
< 335# #101 21#2 333# 2#20 3#33 4#54 #133 3#33 32#2 -> 1 1 2 5 1 1
> 335# #101 21#2 333# 2#20 3#33 4#54 #133 3#33 32#2 -> 0 3 3 7 1 1
^ 335# #101 21#2 333# 2#20 3#33 4#54 #133 3#33 32#2 -> 2 4 4 10 1 2
```
Note that something like `!` is invalid input, since the list is guaranteed to be non-empty.
---
\* For the purposes of this challenge, we're ignoring pile colours.
[Answer]
## CJam, ~~44~~ ~~37~~ 36 bytes
*Thanks to Sp3000 for reminding me that I'm overcomplicating things and saving 7 bytes.*
```
rci7%"3>0<2<1>"2/=6,slS%{W$~+}*fe=p;
```
[Test it here.](http://cjam.aditsu.net/#code=rci7%25%223%3E0%3C2%3C1%3E%222%2F%3D6%2CslS%25%7BW%24~%2B%7D*fe%3Dp%3B&input=%5E%20335%23%20%23101%2021%232%20333%23%202%2320%203%2333%204%2354%20%23133%203%2333%2032%232)
### Explanation
Some observations:
* We always want to count the entire first card.
* All splays will result in either a prefix or a suffix of the icons removed. `!` removes all of them (which is either a prefix or a suffix of four characters), `<` removes the first three characters, `>` removes the last two characters, `^` removes the first character.
So all we need is a short way to map the splay mode to the correct truncation:
```
rci e# Read the splay mode and convert to its character code.
7% e# Take modulo 7. This maps "<!>^" to [4 5 6 3], respectively. Modulo 4 those are
e# are all distinct (namely [0 1 2 3], respectively).
"3>0<2<1>"
e# Push this string.
2/ e# Split it into chunks of 2, ["3>" "0<" "2<" "1>"]. Each chunk is CJam code which
e# performs one of the truncations.
= e# Select the correct snippet. This works, because array indexing is cyclic in CJam.
6,s e# Push the string "012345".
lS% e# Read the remainder of the input and split into space-separated tokens.
{ e# Now we're abusing the fold operation to apply our snippet to every card except
e# the first, while also combining them all back into a single string.
W% e# Copy the bottom of the stack (the truncation snippet).
~ e# Evaluate it.
+ e# Append it the string we're building.
}*
fe= e# For each character in "012345", count the occurrences in our new string.
p e# Pretty-print the array.
; e# Discard the truncation snippet which was still at the bottom of the stack.
```
We can notice that the truncation snippets actually have a lot of structure. Each splay mode maps to one number in `[0 1 2 3]` (specifically, in order `"!^><"`), and two of them have `>` and two have `<`. I was hoping to find two hashes which magically produce these parts separately, as that would save a bunch of bytes, but so far I wasn't able to find anything. I can map `"!^><"` to numbers of alternating parity with `31%` (to select the correct character from `"<>"`), but I haven't found anything which neatly maps them `[0 1 2 3]` in that order. (Except the naive solution of `"!^><"#` which unfortunately doesn't save any bytes.)
Also note that it's actually a bit more flexible. `!` can also be implemented as `n>` for any `n > 3` (discarding everything as a prefix). Unfortunately, I haven't been able to find any simple function for such a map either.
[Answer]
# Pyth, ~~39~~ ~~36~~ ~~33~~ 31 bytes
```
Jtczdm/s+hJm@yk%*%Chz33T19tJ`d6
```
[Try it online.](https://pyth.herokuapp.com/?code=Jtczdm%2Fs%2BhJm%40yk%25*%25Chz33T19tJ%60d6&input=%5E+03%230+%23331+355%23+144%23&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=Jtczdm%2Fs%2BhJm%40yk%25*%25Chz33T19tJ%60d6&test_suite=1&test_suite_input=!+113%23%0A%3C+113%23%0A%3E+113%23%0A%5E+113%23%0A!+000%23+12%232%0A%3C+000%23+12%232%0A%3E+000%23+12%232%0A%5E+000%23+12%232%0A!+000%23+111%23+222%23%0A%3C+000%23+111%23+222%23%0A%3E+000%23+111%23+222%23%0A%5E+000%23+111%23+222%23%0A!+335%23+%23101+21%232+333%23+2%2320+3%2333+4%2354+%23133+3%2333+32%232%0A%3C+335%23+%23101+21%232+333%23+2%2320+3%2333+4%2354+%23133+3%2333+32%232%0A%3E+335%23+%23101+21%232+333%23+2%2320+3%2333+4%2354+%23133+3%2333+32%232%0A%5E+335%23+%23101+21%232+333%23+2%2320+3%2333+4%2354+%23133+3%2333+32%232&debug=0)
### Explanation
* `Jtczd`: split input by spaces, remove the first part, and save the rest to `J`.
* `m`…`6`: repeat the following for numbers 0 to 5.
+ `m`…`tJ`: repeat the following for all cards except for the first one.
- `Chz`: get the code point of the first character in the input.
- `%*%`…`33T19`: map the code points of `!<>^` (33, 60, 62, 94) to the numbers 0, 4, 5, 14. The exact calculation performed is `cp % 33 * 10 % 19`.
- `yk`: get the powerset of the current card. This is a list of all subsequences of the card.
- `@`: get the item of the powerset corresponding to the index calculated before.
+ `+hJ`: append the first card to the result.
+ `s`: concatenate the processed cards together.
+ `/`…``d`: count the occurrences of the current number in the result.
] |
[Question]
[
Lots of people like to play music for fun and entertainment. Unfortunately, music is pretty difficult sometimes. That is why you're here!
## Task
It's your job to make reading music much easier for those struggling with it. You need to write a program or function that takes as input a musical staff, and outputs the names of the notes written on that staff.
## Staff, clef, and notes
A [musical staff](https://en.wikipedia.org/wiki/Staff_(music)) , or stave, is five horizontal lines, inbetween which are four spaces. Each line or space represents a different note (pitch), depending on the clef.
There are a fair few different musical clefs to choose from, but we'll only be dealing with one for now: the [treble clef](https://en.wikipedia.org/wiki/Clef#Treble_clef). On the treble clef, the notes are represented on the staff as follows:
```
Lines
F ----------
D ----------
B ----------
G ----------
E ----------
```
```
Spaces
----------
E
----------
C
----------
A
----------
F
----------
```
## Formatting of the input
Input will be given as a single string, as follows:
```
---------------
---------------
---------------
---------------
---------------
```
The five lines and four spaces of the staff are constructed out of nine rows of characters. Lines of the staff are constructed with `-` (hyphen) characters, and spaces with (space). Each row is separated from the next by a single newline character, eg:
`-----\n \n-----\n \n-----\n \n-----\n \n-----\n`
The rows are of arbitrary length (to a reasonable amount that can be handled by your programming language), and each row is exactly the same length in characters as the others. Also note that the rows will always be of a length that is divisible by three (to fit the pattern of one note followed by two columns without a note).
Notes are placed on this staff by replacing the appropriate `-` or character with `o`. Notes can also be raised (sharp) or lowered (flat) in pitch by a semitone (about half the frequency difference between a note and its adjacent notes). This will be represented by the characters `#` and `b`, respectively, in place of the `o`. Each note will be separated from the next by exactly two `-` characters, and the first note will always occur on the first "column" of `-` and (space) characters.
When outputting note names, your program should always use the capitalised letters (`A B C D E F G`) corresponding to the note given on the staff. For sharp (`#`) and flat (`b`) notes, your program needs to append `#` and `b`, respectively, to the letter corresponding to the note. For a natural note that is not sharp or flat, a (space) should be appended instead.
## Example
Input:
```
---------------------o--
o
---------------o--------
o
---------b--------------
o
---o--------------------
o
------------------------
```
\*note all "empty space" in this example is actually (space character).
In this case (a simple F major scale), your program should output this:
```
F G A Bb C D E F
```
Note the spacing between the characters of the output should be exactly as shown above, to fit correctly with the notes on the staff. Between all the note names there are two (space) characters, except between the `Bb` and `C`. The `b` here replaces one of the (space) characters.
Another example
Input:
```
------------------------
o
------------------#-----
#
------------o-----------
o
------#-----------------
#
o-----------------------
```
Output:
`E F# G# A B C# D# E`
One more example for good luck
Input:
```
---------------------
o o o o
---------------------
o
---------------------
---------------o--o--
---------------------
```
Output:
`E E E C E G G`
## Rules
* Notes will only ever be given in the five line staff range of E flat up to F sharp (except for the challenges, see below)
* Any note could be sharp or flat, not just those seen commonly in music (eg. despite B# actually just being played as C in reality, B# can still occur in the input)
* You can assume there will be exactly one note per 3 columns (so there will be no chords or anything like that, and no rests either)
* You can assume the last note will be followed by two columns with no notes
* You can assume even the last line of the staff will be followed by a single newline character
* Input should be taken from STDIN (or language equivalent) or as function parameter
* Output should be to STDOUT (or language equivalent) or as a return result if your program is a function
* Standard loopholes and built-ins are allowed! Music is about experimenting and playing around. Go ahead and have fun with your language (although recognise that exploiting a loophole may not produce the most interesting program)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest program in bytes wins
## Bonus challenges
* -10% if your program can also successfully process the space above the top line of the staff (G, G#, Gb).
* -10% if your program can also successfully process the space below the bottom line of the staff (D, D#, Db)
* In these cases your program would take as input an additional row at the start and end; these rows should be treated exactly the same as the other nine rows
[Answer]
## CJam (40 37 \* 0.8 = 29.6 points)
```
qN/z3%{_{iD%6>}#_~'H,65>=@@=+'oSerS}%
```
[Online demo](http://cjam.aditsu.net/#code=qN%2Fz3%25%7B_%7BiD%256%3E%7D%23_~'H%2C65%3E%3D%40%40%3D%2B'oSerS%7D%25&input=%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20o%20%20%20%20%20%0A---------------------o--------%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20o%20%20%20%20%20%20%20%20%20%20%20%0A---------------o--------------%0A%20%20%20%20%20%20%20%20%20%20%20%20%23%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A---------b--------------------%0A%20%20%20%20%20%20o%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A---o--------------------------%0Ao%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A------------------------------%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%20)
Thanks to [indeed](https://codegolf.stackexchange.com/users/47009/indeed) for pointing out some pre-defined variables which I'd forgotten about.
[Answer]
# Ruby, 106 bytes \*0.8 = 84.8
```
->s{a=' '*l=s.index('
')+1
s.size.times{|i|s[i].ord&34>33&&(a[i%l,2]='GFEDCBA'[i/l%7]+s[i].tr(?o,' '))}
a}
```
Ungolfed in test program
```
f=->s{a=' '*l=s.index('
')+1 #l = length of first row, initialize string a to l spaces
s.size.times{|i| #for each character in s
s[i].ord&34>33&& #if ASCII code for ob#
(a[i%l,2]= #change 2 bytes in a to the following string
'GFEDCBA'[i/l%7]+s[i].tr(?o,' '))}#note letter, and copy of symbol ob# (transcribe to space if o)
a} #return a
t='
---------------------o--
o
---------------o--------
o
---------b--------------
o
---o--------------------
o
------------------------
'
u='
------------------------
o
------------------#-----
#
------------o-----------
o
------#-----------------
#
o-----------------------
'
v='
---------------------
o o o o
---------------------
o
---------------------
---------------o--o--
---------------------
'
puts f[t]
puts f[u]
puts f[v]
```
[Answer]
# JavaScript (ES6), 144 bytes - 20% = 115.2
```
f=s=>(n=[],l=s.indexOf(`
`)+1,[...s].map((v,i)=>(x=i%l,h=v.match(/[ob#]/),n[x]=h?"GFEDCBAGFED"[i/l|0]:n[x]||" ",h&&v!="o"?n[x+1]=v:0)),n.join``)
```
## Explanation
```
f=s=>(
n=[], // n = array of note letters
l=s.indexOf(`
`)+1, // l = line length
[...s].map((v,i)=>( // iterate through each character
x=i%l, // x = position within current line
h=v.match(/[ob#]/), // h = character is note
n[x]= // set current note letter to:
h?"GFEDCBAGFED"[i/l|0] // if it is a note, the letter
:n[x]||" ", // if not, the current value or space if null
h&&v!="o"?n[x+1]=v:0 // put the sharp/flat symbol at the next position
)),
n.join`` // return the note letters as a string
)
```
## Test
Remember to add a line above the staff that is the exact length of the other lines because this solution includes parsing the lines above and below the staff.
```
f=s=>(n=[],l=s.indexOf(`
`)+1,[...s].map((v,i)=>(x=i%l,h=v.match(/[ob#]/),n[x]=h?"GFEDCBAGFED"[i/l|0]:n[x]||" ",h&&v!="o"?n[x+1]=v:0)),n.join``)
```
```
<textarea id="input" style="float:left;width:200px;height:175px">
---------------------o--
o
---------------o--------
o
---------b--------------
o
---o--------------------
o
------------------------
</textarea>
<div style="float:left">
<button onclick="results.innerHTML=f(input.value)">Test</button>
<pre id="results"></pre>
</div>
```
] |
[Question]
[
Write a program or function that, given two ASCII strings `A` and `B`, will produce strings `A'` and `B'` where the common substrings are reversed in their place. The process for finding `A'` is as follows:
1. `A'` is initially empty.
2. If the first character of `A` is in `B`, find the longest prefix of `A` which is a substring of `B`. Remove this prefix from `A` and add its reversal to `A'`.
3. Otherwise, remove this first character from `A` and add it to `A'`.
4. Repeat steps 2-3 until `A` is empty.
Finding `B'` is done similarly.
## Example
Let's consider the strings `A = "abc bab"` and `B = "abdabc"`. For `A'`, this is what happens:
* `A = "abc bab"`: The first character `"a"` is in B and the longest prefix of A found in B is `"abc"`. We remove this prefix from A and add its reversal `"cba"` to A'.
* `A = " bab"`: The first character `" "` is not in B, so we remove this character from A and add it to A'.
* `A = "bab"`: The first character `"b"` is in B and the longest prefix of A found in B is `"b"`. We remove this prefix from A and add its reversal (which is still `"b"`) to A'.
* `A = "ab"`: The first character `"a"` is in B and the longest prefix of A found in B is `"ab"`. We remove this prefix from A and add its reversal `"ba"` to A'.
* `A = ""`: A is empty, so we stop.
Thus we get `A' = "cba" + " " + "b" + "ba" = "cba bba"`. For B', the process is similar:
```
B = "abdabc" -> "a" in A, remove prefix "ab"
B = "dabc" -> "d" not in A, remove "d"
B = "abc" -> "a" in A, remove prefix "abc"
```
Thus we get `B' = "ba" + "d" + "cba" = "badcba"`.
Finally, we return the two strings, i.e.
```
(A', B') = ("cba bba", "badcba")
```
## Test cases
```
"abc bab", "abdabc" -> "cba bba", "badcba"
"abcde", "abcd bcde" -> "dcbae", "dcba edcb"
"hello test", "test banana" -> "hello tset", "tset banana"
"birds flying high", "whistling high nerds" -> "bisdr flyhgih gni", "wihstlhgih gni nesdr"
```
---
Shortest code in bytes wins.
[Answer]
## Haskell, ~~120~~ 111 bytes
```
import Data.List
a&b=(a#b,b#a)
[]#_=[]
(a:y)#b=[a]%y where p%(i:w)|reverse(i:p)`isInfixOf`b=(i:p)%w;p%x=p++x#b
```
Test runs:
```
λ: "abc bab"&"abdabc"
("cba bba","badcba")
λ: "abcde"&"abcd bcde"
("dcbae","dcba edcb")
λ: "hello test"&"test banana"
("hello tset","tset banana")
λ: "birds flying high"&"whistling high nerds"
("bisdr flyhgih gni","wihstlhgih gni nesdr")
```
[Answer]
# Pyth, 29 bytes
```
M&G+_Je|f}TH._GhGg.-GJHgzQgQz
```
[Test Harness.](https://pyth.herokuapp.com/?code=M%26G%2B_Je%7Cf%7DTH._GhGg.-GJHgzQgQz&test_suite=1&test_suite_input=abc+bab%0A%22abdabc%22%0Aabcde%0A%22abcd+bcde%22%0Ahello+test%0A%22test+banana%22%0Abirds+flying+high%0A%22whistling+high+nerds%22&debug=0&input_size=2)
Input format is:
```
abc bab
"abdabc"
```
Output is:
```
cba bba
badcba
```
[Answer]
# SWI-Prolog, 312 bytes
```
a(A,B,X,Y):-b(A,B,"",X),b(B,A,"",Y).
b(A,B,R,Z):-A="",R=Z;sub_string(A,0,1,_,C),(sub_string(B,_,1,_,C),(string_length(A,J),I is J-1,between(0,I,K),L is J-K,sub_string(A,0,L,_,S),sub_string(B,_,L,_,S),string_codes(S,E),reverse(E,F),string_codes(Y,F));S=C,Y=C),string_concat(S,V,A),string_concat(R,Y,X),b(V,B,X,Z).
```
Example: `a("birds flying high","whistling high nerds",X,Y).` outputs
```
X = "bisdr flyhgih gni",
Y = "wihstlhgih gni nesdr" .
```
A way, *way* too long solution that goes too show how verbose Prolog is when dealing with strings. It might be possible to shorten this thing using codes arrays (``birds flying high``) instead of strings (`"birds flying high"`).
[Answer]
## Python 2.7, ~~169~~ ~~156~~ ~~152~~ 141 Bytes
```
m=lambda A,B:(b(A,B),b(B,A))
def b(A,B,C=''):
while A:j=next((j for j in range(len(A),0,-1)if A[:j]in B),1);C+=A[:j][::-1];A=A[j:]
return C
```
The function `m` takes the 2 strings as input.It calls the `b` function twice which does the actual processing according to the specs.
[Demo here](https://ideone.com/cODLdh).
Testing it -
```
l=[("abc bab", "abdabc"),
("abcde", "abcd bcde"),
("hello test", "test banana"),
("birds flying high", "whistling high nerds")]
for e in l:
print m(*e)
```
OUTPUTS:
```
('cba bba', 'badcba')
('dcbae', 'dcba edcb')
('hello tset', 'tset banana')
('bisdr flyhgih gni', 'wihstlhgih gni nesdr')
```
PS: Thanks to orlp for the solution using `next()`
] |
[Question]
[
The Doctor, in trying to escape from the Dalek forces has decided to send them in a spin by traveling in various pockets of space in a spiral motion.
Depending on the nature of the available space-time, The Doctor needs to enter into the TARDIS controls the height and width of the section of space and his entry point with which to begin the spiral.
The section of space can be envisioned as a *h* x *w* grid filled with sequential integers from left to right, top to bottom, starting with 1.
The starting position is provided as *r c* for the row and column... From this the TARDIS's software needs to spit out the ordered list of integers obtained by spiraling outward in an anti-clockwise direction from row *r* column *c*, starting upwards...
Your task, as the Doctor's companion is to program the TARDIS to take four numbers, in the format `height width row column` and have it determine which sector of space the TARDIS needs to travel to match the spiral movement described below...
**Input 1**
```
5 5 3 3
```
(5 x 5 grid, starting at position 3,3)
**Output 1**
```
13 8 7 12 17 18 19 14 9 4 3 2 1 6 11 16 21 22 23 24 25 20 15 10 5
```
**Explaining output**
Original grid

Generated spiral

**Input 2**
```
2 4 1 2
```
(2 x 4 grid starting at position 1,2)
**Output 2**
```
2 1 5 6 7 3 8 4
```
**Explaining output**
Slightly different as spiral now must circle around grid to generate respective output...
Original grid

Generated spiral

Rules:
1. This is code-golf, so shortest code length gets the tick of approval.
2. The above examples must be used to test your code. If it doesn't provide the respective output, there's something wrong...
3. Both golfed and in-golfed versions of code must be provided in your answer...
Good luck!
[Answer]
# JavaScript (ES6) 124 ~~163 177~~
**Edit** Totally different way, no need of an array to store visited cells. Using the fact that the side of the spiral increase of 1 after every 2 turns.
```
// New way
f=(h,w,y,x)=>
(e=>{
for(o=[],d=i=t=l=0;l<w*h;i<t?i+=2:[i,d,e]=[1,-e,d,++t])
o[l]=y*w-w+x,l+=x>0&x<=w&y>0&y<=h,x+=d,y-=e
})(1)||o
// Golfed
g=(h,w,y,x)=>
(g=>{
for(e=n=0;n<h*w;)g[[n%w+1,-~(n/w)]]=++n;
for(o=[g[[x,y]]],l=d=1;l<n;l+=!!(o[l]=g[[x+=d,y+=e]]))
g[[x,y]]=0,
g[[x+e,y-d]]!=0&&([d,e]=[e,-d])
})([])||o
// Not golfed
u=(h,w,y,x)=>{
var i,j,dx,dy,kx,ky,o,n,
g={} // simulate a 2dimensional array using a hashtable with keys in the form 'x,y'
for(n=i=0; i++<h;) // fill grid (probably better done in a single loop)
for(j=0; j++<w;)
g[[j,i]] = ++n;
o=[g[[x,y]]] // starting point in output
dx=1, dy=0 // start headed right
for(; !o[w*h-1]; ) // loop until all w*h position are put in output
{
g[[x, y]] = 0 // mark current position to avoid reusing
kx=dy, ky=-dx // try turning left
if(g[[x+kx, y+ky]] != 0) // check if position marked
{ // found a valid position
dx=kx, dy=ky // change direction
}
x+=dx, y+=dy // move
k=g[[x, y]] // get current value
if (k) o.push(k) // put in output list if not 'undefined' (outside grid)
}
return o
}
// TEST - In FireFox
out=x=>O.innerHTML+=x+'\n';
[
[[5,5,3,3],'13 8 7 12 17 18 19 14 9 4 3 2 1 6 11 16 21 22 23 24 25 20 15 10 5'],
[[2,4,1,2],'2 1 5 6 7 3 8 4']
].forEach(t=>out(t[0] + '\n Result: ' + f(...t[0])+'\n Check: ' + t[1]))
test=()=>
{
var r, i=I.value.match(/\d+/g), h=i[0]|0, w=i[1]|0, y=i[2]|0, x=i[3]|0
if (y>h||x>w) r = 'Invalid input'
else r = f(h,w,y,x)
out(i+'\n Reault: ' +r)
}
```
```
<pre id=O></pre>
Your test:<input id=I><button onclick="test()">-></button>
```
[Answer]
# Python 3, 191
Probably not a great score, but here it goes:
```
def f(b,a,d,c):
p,r,l,s,h=c+1j*d,-1j,1,0,0
for _ in [0]*((a+b)**2):x,y=p.real,p.imag;0<x<a+1and 0<y<b+1and print(int((y-1)*a+x),end=' ');p+=r;s=(s+1)%l;t=s==0;h=(h+t)%2;l+=h<t;r*=(-1j)**t
```
We move along the spiral by increasing side-length after every second turns. If our position is inside the given grid we print its corresponding number.
Variables are:
* p is complex position
* x and y are position coordinates
* r is direction
* s is position on current side
* l is current side length
* h is the parity of the current side's ordinal
] |
[Question]
[
Consider a grid of `N`x`N` unique elements. Each element has a letter (from A to the `N`th letter, inclusive) and a number (from 1 to `N`, inclusive). Hence, each number/letter pair is in the grid exactly once.
Your job is to arrange a grid such that:
Each row, column, and diagonal (including wrapping) contains each letter and number exactly once.
By wrapping, I mean that
```
* * * # *
* * # * *
* # * * *
# * * * *
* * * * #
```
is a diagonal, along with all similar diagonals that hit the edges.
An example `5x5` grid is:
```
A1 B2 C3 D4 E5
C4 D5 E1 A2 B3
E2 A3 B4 C5 D1
B5 C1 D2 E3 A4
D3 E4 A5 B1 C2
```
Your task is to write a program that accepts a number, `N`, and print a `N`x`N` grid as described above. Your program should work for any `0 < N <= 26`. If a particular grid is not possible, then you should print `Impossible`.
Hardcoding the answer for any `N` is not allowed. A program is hard coded if it calculates the grid in different manner (as judged by me) for any `N > 26` (or if it fails to calculate). (This is meant to prevent precalculation, including precalculated invalid grids, or offsets for given grids).
This is a fastest-code problem, and your score is the sum of the times taken to run your program across all possible `N` on my computer. In your answer, please have your program run across all `N` (so I only have to time it once). If no program can compute it in under 60 seconds, then the winner is the answer that can calculate the grid with the largest `N` in 60 seconds. If multiple programs have the same maximum `N`, then the tiebreaker is the fastest solution.
(I have a decently powered Windows 8 machine, and any compilers or interpreters needed must be freely available for it).
[Answer]
## Python 3
```
letters = []
numbers = []
for n in range(1,27):
if n%2==0 or n%3==0:
offsets=False
else:
offsets = [x for x in range(0,n,2)]
offsets.extend([x for x in range(1,n,2)])
letters.append(chr(96+n))
numbers.append(n)
if offsets :
for y in range(n):
for x in range(n):
let=letters[(x+offsets[y])%n]
num=numbers[(offsets[y]-x)%n]
print (let+str(num), end= " " if num<10 else " ")
print("\n")
else:
print("Impossible\n")
```
## How it works?
The naive implementation would be to look through all the possible arrangements of letter and numbers
in an NxN grid and look for one that is also a Orthogonal-Diagonal Latin Square (ODLS)
(and thus, for some it would just have to go through all configurations and return impossible). Such
an algorithm wouldnt suit this challenge due to absurd time complexity.
So there are three major simplifications and justifications (partial proofs and insights to why it works) to ODLS constructions used in my implementation:
The first is the notion that we only need to generate a valid Diagonal Latin Square (A NxN grid such that each row, column, wrapped-diagonal
contains each element of a set of N distinct elements exactly once) of the first N letters of the alphabet.
If we can construct such a Diagonal Latin Square (DLS) then an ODLS can be constructed
using the DLS with appropriate exchange of elements and flipping. Justification:
```
Let us first look at an example using the example grid
a1 b2 c3 d4 e5
c4 d5 e1 a2 b3
e2 a3 b4 c5 d1
b5 c1 d2 e3 a4
d3 e4 a5 b1 c2
Every ODLS can be separated into two DLS (by definition), so
we can separate the grid above into two DLS, one containing letters, the other - numbers
a b c d e
c d e a b
e a b c d
b c d e a
d e a b c
and
1 2 3 4 5
4 5 1 2 3
2 3 4 5 1
5 1 2 3 4
3 4 5 1 2
If we transform the number DLS by the mapping 1-->e, 2-->d, 3-->c, 4-->b, 5-->a,
1 2 3 4 5 --> e d c b a
4 5 1 2 3 --> b a e d c
2 3 4 5 1 --> d c b a e
5 1 2 3 4 --> a e d c b
3 4 5 1 2 --> c b a e d
Now if we put the transformed number grid next to the original letter grid,
Original | Transformed
a b c d e | e d c b a
c d e a b | b a e d c
e a b c d | d c b a e
b c d e a | a e d c b
d e a b c | c b a e d
It can be clearly seen that the number grid is a horizontal flip of
the letter grid withminor letter to number substitutions.
Now this works because flipping guarantees that no two pairs occur more than once,
and each DLS satisfies the requirements of the ODLS.
```
The second simplification is the notion that if we found a suitable configuration (SC) of one element (A NxN grid such that each row, column, wrapped-diagonal
contains that element exactly once), then a DLS could be constructed by replacing the element and shifting the SC. Justification:
```
If "_" is an empty space and "a" the element then a valid SC of a 7x7 grid is
a _ _ _ _ _ _
_ _ a _ _ _ _
_ _ _ _ a _ _
_ _ _ _ _ _ a
_ a _ _ _ _ _
_ _ _ a _ _ _
_ _ _ _ _ a _
or
a _ _ _ _ _ _
_ _ _ a _ _ _
_ _ _ _ _ _ a
_ _ a _ _ _ _
_ _ _ _ _ a _
_ a _ _ _ _ _
_ _ _ _ a _ _
(the second one can actually be obtained from the first one via rotation)
now say we took the second SC, shifted it one unit to the right and
replaced all "a" with "b"
a _ _ _ _ _ _ _ a _ _ _ _ _ _ b _ _ _ _ _
_ _ _ a _ _ _ _ _ _ _ a _ _ _ _ _ _ b _ _
_ _ _ _ _ _ a a _ _ _ _ _ _ b _ _ _ _ _ _
_ _ a _ _ _ _ --> _ _ _ a _ _ _ --> _ _ _ b _ _ _
_ _ _ _ _ a _ _ _ _ _ _ _ a _ _ _ _ _ _ b
_ a _ _ _ _ _ _ _ a _ _ _ _ _ _ b _ _ _ _
_ _ _ _ a _ _ _ _ _ _ _ a _ _ _ _ _ _ b _
Now if we overlaid the SC of "a" with the SC of "b" we get
a b _ _ _ _ _
_ _ _ a b _ _
b _ _ _ _ _ a
_ _ a b _ _ _
_ _ _ _ _ a b
_ a b _ _ _ _
_ _ _ _ a b _
If we repeated these steps for the other five letters, we would arrive at a DLS
a b c d e f g
e f g a b c d
b c d e f g a
f g a b c d e
c d e f g a b
g a b c d e f
d e f g a b c
This is a DLS, since each SC follows the general requirements of a DLS
and shifting ensured that each element has its own cell.
Another thing to note is that each row contains the string "abcdefg" that is offset
by some cells. This leads to another simplification: we only need to find the
offsets of the string in every row and we are finished.
```
The last simplification is as follows - all DLS of prime N, except for N=2 or N=3,
can be constructed, and if N can be factored into two numbers whose appropriate
DLS can be constructed, then a DLS of that N can be constructed.
I conjecture that the converse also holds.
(In other words we can only construct an DLS for N that is not divisible by 2 or 3)
```
Pretty obvious why 2x2 or 3x3 cant be made. For any other prime this can be done
by assigning a each consecutive row a shift that is by two bigger than the previous,
for N=5 and N=7 this looks like (with elements other than "a" ommited)
N=5
a _ _ _ _ offset = 0
_ _ a _ _ offset = 2
_ _ _ _ a offset = 4
_ a _ _ _ offset = 6 = 1 (mod 5)
_ _ _ a _ offset = 8 = 3 (mod 5)
N=7
a _ _ _ _ _ _ offset = 0
_ _ a _ _ _ _ offset = 2
_ _ _ _ a _ _ offset = 4
_ _ _ _ _ _ a offset = 6
_ a _ _ _ _ _ offset = 8 = 1 (mod 7)
_ _ _ a _ _ _ offset = 10 = 3 (mod 7)
_ _ _ _ _ a _ offset = 12 = 5 (mod 7
(Why this works on all prime N (actually all N that are not divisible
by 3 or 2) can probably be proven via some kind of induction but i will
omit that, this is just what my code uses and it works)
Now, the first composite number that is not
divisible by 2 or 3 is 25 (it also occurs in the range our program must test)
Let A denote the DLS of N = 5
a b c d e
d e a b c
b c d e a
e a b c d
c d e a b
Let F be the DLS A where each letter is substituted by the letter five postions after it
a-->f, b-->g etc. So F is
f g h i j
j e f g h
g h i j f
j f g h i
h i j f g
Let K be the DLS a where each letter is substituted by the letter ten postions after it
a-->k, b--> l etc.
Let P be defined likewise (so a-->p, b-->q etc)
Let U be defined likewise (so a-->u, b-->v etc)
Now, since the DLS A could be constructed, then by substituting a --> A, b--> F etc.
we get a DLS of N=5*5 (A has five rows and five columns and each is filled with a
grid of five rows and five columns)
A F K P U
P U A F K
F K P U A
U A F K P
K P U A F
Now since smaller DLS in the big DLS satisfies the
conditions of a DLS and the big one also satisfies the DLS conditions,
then the resulting grid is also a DLS
```

A picture of what i meant with the smaller - bigger DLS
```
Now this kind of thing works for all constructible N and can be proven similiarly.
I have a strong sense that the converse (if some N isnt constructible
(2 and 3) then no multiple of that N is constructible) is also true but have a hard time
proving it (test data up to N=30 (took a veeery long time to calculate) confirm it though)
```
] |
[Question]
[
This is the reverse of [Music: what's in this chord?](https://codegolf.stackexchange.com/q/24816/25180), which is to print the notes in a given chord. This time the input is a list of notes in a chord, and your task is to output which chord it is.
Your program should support the following triadic chords. Examples are given with root C. Chords with other roots are the same chords with all notes rotated so C will become that root note, e.g. Dmaj consists of D, F# and A.
```
C C#D D#E F F#G G#A A#B
Db Eb Gb Ab Bb
Cmaj C E G
Cm C D# G
Caug C E G#
Cdim C D# F#
Csus4 C F G
Csus2 C D G
```
Note that Caug is the same as Eaug and G#aug, and Csus4 is the same as Fsus2. You can output either one but there is a bonus if you output them all.
And the seventh chords for the bonus are listed in the follow table:
```
C C#D D#E F F#G G#A A#B
Db Eb Gb Ab Bb
C7 C E G A#
Cm7 C D# G A#
Cmmaj7 C D# G B
Cmaj7 C E G B
Caug7 C E G# A#
Cdim7 C D# F# A
```
## Rules
* You can write either a complete program or a function.
* The input is a list of notes, separated by a space or another convenient character. It can also be an array of strings (if it take input from function argument) or the string representation of such array.
* Input doesn't have to be in specific order.
* There may be duplicated notes in the input. They must be treated the same way as there is only one of them.
* The output is the name of the chord. In case it will output multiple names, the same rule for input applies.
* If the input isn't a supported chord, you should print the notes as-is. Your program can also support other chords not listed in the tables above (which is valid but has no bonus).
* You can use [other notations listed in the Wikipedia article](http://en.wikipedia.org/wiki/Chord_(music)#Triads). But if you choose `C` for C major, you should add a human readable prefix in either case to distinguish a chord with a single note.
* You cannot use built-in functions for this task (if there is any).
* This is code-golf. Shortest code in bytes wins.
## Examples
* Input: `C D# G` Output: `Cm`.
* Input: `C Eb G` Output: `Cm`.
* Input: `C Eb F#` Output: `Cdim`.
* Input: `F A C#` Output: `Faug`, `Aaug`, `C#aug`, `Dbaug` or `Faug Aaug C#aug`, `Faug Aaug Dbaug` in any order.
* Input: `F D F F F F A A F` Output: `Dm`.
* Input: `C D` Output: `C D`.
## Bonuses
* -30 if it prints them all if there are more than one interpretations (for aug, sus4/sus2 and dim7).
* -70 if it also supports seventh chords.
* -200 if it accepts MIDI input and prints each chord it have received. Note that the notes doesn't have to begin or end at the same time. You decide what happens in the intermediate states (as long as it doesn't crash or stop working). You may assume there are no notes in percussion channels (or there is only one channel if that's convenient). It is recommended to also provide a text (or array) version for testing, especially if it is platform-dependent.
[Answer]
# Perl 5: 183 - 100 = 83
Edit: I managed to cut some extra characters so I also altered the chord names like in the Python solution, so I can pretend for a moment that I am leading.
```
#!perl -pa
for$z(0..11){$x=0;$x|=1<<((/#/-/b/+$z+1.61*ord)%12or$o=$_)for@F;$x-/\d+_?/-$_*4||push@r,$o.$'
for qw(36M 34- 68+ 18o 40sus2 33sus4 292_7 290-7 546-M7 548M7 324+7 146o7)}$_="@r
"if@r
```
Example:
```
$ perl chord.pl <<<"C D# G"
C-
```
[Answer]
# Pyth 190 character - 30 - 70 = 90
```
=Q{cQdL+x"C D EF G A B"hb&tlbt%hx" #b"eb3FZQJx[188 212 199 213 200 224 2555 2411 2412 2556 2567 2398)u+*G12hHSm%-dyZ12mykQ0IhJ+Z@c"sus2 maj dim aug m sus4 7 m7 mmaj7 maj7 aug7 dim7"dJ=T0;ITQ
```
Not really happy with it. Used hard-coded chords.
## Usage:
Try it here: [Pyth Compiler/Executor](https://pyth.herokuapp.com/). Disable debug mode and use `"C D# G"` as input.
## Explanation:
First some preparation:
```
=Q{cQd
cQd split chord into notes "C D# G" -> ["C", "D#", "G"]
{ set (eliminate duplicates)
=Q Q = ...
```
Then a function that converts notes into integer
```
L+x"C D EF G A B"hb&tlbt%hx" #b"eb3
defines a function g(b),
returns the sum of
index of "D" in "C D EF G A B"
and the index of "#" in " #b"
(if b than use -1 instead of 2)
```
Then for each note, shift the coord and look it up in a table
```
FZQJx[188 ...)u+*G12hHSm%-dyZ12mykQ0IhJ+Z@c"sus2 ..."dJ=T0;ITQ
implicit T=10
FZQ for note Z in chord Q:
mykQ map each note of Q to it's integer value
m%-dyZ12 shift it by the integer value of Z modulo 12
S sort it
u+*G12hH 0 convert it to an integer in base 12
x[188 ...) look it up in the list (-1 if not in list)
J and store the value in J
IhJ if J>=0:
+Z@c"sus2 ..."dJ print the note Z and the chord in the list
=T0 and set T=0
; end loop
ITQ if T:print chord (chord not in list)
```
[Answer]
## Python 2, 335 bytes - 30 - 70 = 235
First attempt at a slightly longer golf, so I may be missing some obvious tricks.
```
def f(s,N="C D EF G A B",r=range,u=1):
for i in r(12):
for t in r(12):
if(set((N.find(n[0])+" #".find(n[1:]))%12for n in s.split())==set(map(lambda n:(int(n,16)+i)%12,"0"+"47037048036057027047A37A37B47B48A369"[3*t:3*t+3]))):print(N[i],N[i+1]+"b")[N[i]==" "]+"M - + o sus4 sus2 7 -7 -M7 M7 +7 o7".split()[t];u=0
if(u):print s
```
Comments:
* I used alternative chord names from the Wiki page (see the end of the long line) to save space.
* Chords are represented by 3 hex offsets each (0 is not required but included for triads to make them line up).
* " #".find(n[1:]) works since " #".find("b") is -1 and " #".find("") is 0.
**Sample output**
```
>>> f("C D# G")
C-
>>> f("C Eb G")
C-
>>> f("C Eb F#")
Co
>>> f("F A C#")
Db+
F+
A+
>>> f("F D F F F F A A F")
D-
>>> f("C D")
C D
>>> f("C Eb Gb A")
Co7
Ebo7
Gbo7
Ao7
```
] |
[Question]
[
You've been hired to write some code for a dictation-taking app, which takes voice input from a spoken source, parses it as words, and writes it down on a screen.
The management doesn't really trust you with all that much powerin the project—you're known to sit around and golf code all day instead of doing your work, unfortunately—so they just give you a really simple task to perform: turn a Sentence with interspersed Punctuation into a properly formatted sentence, where 'properly formatted' is defined below.
1. The Sentence is the string of input. A Word is a group of continguous non-space characters. A Punctuation is a Word whose first character is `^`.
2. A Word is capitalized if the first letter of the Word is not a lowercase letter (capitalized words match the regex `/[^a-z].*/`).
3. The first Word of the Sentence must be capitalized.
4. A `^COMMA` is the comma character `,` and has a space following but not preceding. `aaa ^COMMA bbb` becomes `aaa, bbb`.
5. A `^COLON` is a comma that looks like `:`.
6. A `^SEMICOLON` is a comma that looks like `;`.
7. A `^PERIOD` is a comma that looks like `.`. The word following a `^PERIOD` must be capitalized.
8. A `^BANG` is a period that looks like `!`.
9. A `^DASH` is the dash character `-` and has a space both preceding and following.
10. A `^HYPHEN` is also the dash character `-` but has no space following or preceding.
11. An `^EMDASH` is a hyphen (not a dash!) that is spelled `--`.
12. An `^OPENQUOTE` is a quote character `"` that has a space preceding but not following. The word following an `^OPENQUOTE` must be capitalized. If an `^OPENQUOTE` is preceded by a Word that is not Punctuation, add a `^COMMA` between that word and the `^OPENQUOTE`. If an `^OPENQUOTE` is preceded by a Punctuation that makes the next word capitalized, this skips over the `^OPENQUOTE` to the next word.
13. A `^CLOSEQUOTE` is the digraph `,"` that has a space following but not preceding. If a `^CLOSEQUOTE` is preceded by a `^COMMA`, `^PERIOD`, or `^BANG`, that Punctuation disappears and the `^CLOSEQUOTE` is spelled `,"`, `."`, or `!"` respectively. If the disappearing Punctuation specified a capitalization, that capitalization must still occur on the next available word.
14. Initial or trailing spaces in the full final result must be removed, and any string of two or more spaces in a row must be all collapsed into a single space character.
15. Any case not covered above (e.g. `^COMMA ^COMMA` or `^SEMICOLON ^CLOSEQUOTE` or `^UNDEFINEDPUNCTUATION`) will not occur in well-formed input and is thus undefined behaviour.
The development team informs you of the following:
* The project is being written in the language *[your language here]*, and should be as short as possible so that it takes up as little space as possible when it's an app for Android/iPhone. You try to explain that that's not how app development works, but they don't listen. But hey, what a coincidence! You're an amazing golfer in *[your language here]*!
* The app will not have any web access permissions, and there won't be any libraries installed that do this formatting for you. You can probably convince the team lead to allow you a regex library if one exists for your language, though, if you think you need one.
* Support for nested quotations that use double/single quotes properly is planned for a later version of the app, but not the version that you're working on now, so don't worry about it.
* The management is a huge fan of test-driven development, and so the dev team has already had some hapless keyboard monkey write up some tests for your portion of the program: (newlines added for readability, treat them as spaces)
Input:
```
hello ^COMMA world ^BANG
```
Output:
```
Hello, world!
```
Input:
```
once upon a time ^COMMA there was a horse ^PERIOD that horse cost me $50
^PERIOD ^OPENQUOTE eat your stupid oats ^COMMA already ^BANG ^CLOSEQUOTE
I told the horse ^PERIOD the horse neighed back ^OPENQUOTE no ^CLOSEQUOTE
and died ^PERIOD THE END
```
Output:
```
Once upon a time, there was a horse. That horse cost me $50. "Eat your
stupid oats, already!" I told the horse. The horse neighed back, "No,"
and died. THE END
```
Input:
```
begin a ^PERIOD b ^COMMA c ^COLON d ^SEMICOLON e ^BANG f ^HYPHEN g ^DASH h
^EMDASH i ^OPENQUOTE j ^PERIOD ^OPENQUOTE k ^SEMICOLON ^OPENQUOTE l
^CLOSEQUOTE m ^BANG ^CLOSEQUOTE n ^PERIOD 0x6C6F6C end
```
Output:
```
Begin a. B, c: d; e! F-g - h--i, "j. "K; "l," m!" N. 0x6C6F6C end
```
---
This is a code golf: the lowest score wins. You may write a function of one string argument, or a program reading from STDIN and writing to STDOUT.
[Answer]
# JavaScript: ~~653 611 547 514~~ 487 bytes
Oh my gosh. Brendan Eich I'm so sorry for this.
**PS: I've added white space for readability, but stripping all allowable white space results in the byte count listed.**
Theoretically I could shorten some parts like the `-e-` to something like `-e` or `-e`, but that might cause an issue if the previous word ends with, or the following word begins with the letter 'e' (or whichever word I decide to use). I suppose I could use an ASCII character. I'll look into that.
**487 FF22+ Only**
```
R = "replace", C = "charAt", U = "toUpperCase";
alert(a[R](/\^((COMMA)|(SEMICOLON)|(COLON)|(PERIOD)|(BANG)|(DASH)|(HYPHEN)|(EMDASH)|(OPENQUOTE)|(CLOSEQUOTE))/g, ((m, _, a, b, c, d, e, f, g, h, i, j) => a ? "," : b ? ";" : c ? ":" : d ? "." : e ? "!" : f ? "-" : g ? "-h-" : h ? "-e-" : i ? ' "' : '" '))[R](/\s((\.)|(\!)|(\,)|(\;)|(\:)|(\-\h\-\s)|(\-\e\-\s))/g, ((k, l, v, n, o, p, q, r, s) => v ? "." : n ? "!" : o ? "," : p ? ";" : q ? ":" : r ? "-" : "--"))[R](/[^!,"'.]\"\s/g, '"')[R](/.+?[\.\?\!](\s|$)/g, (t => t[C](0)[U]() + t.substr(1)))[R](/\"[a-z]/g, (u => u[C](0) + u[C](1)[U]())))
```
**514 FF22+ Only**
```
alert(function(z) {
R = "replace", C = "charAt", U = "toUpperCase";
return z[R](/\^((COMMA)|(SEMICOLON)|(COLON)|(PERIOD)|(BANG)|(DASH)|(HYPHEN)|(EMDASH)|(OPENQUOTE)|(CLOSEQUOTE))/g, ((m, _, a, b, c, d, e, f, g, h, i, j) => a ? "," : b ? ";" : c ? ":" : d ? "." : e ? "!" : f ? "-" : g ? "-h-" : h ? "-e-" : i ? ' "' : '" '))[R](/\s+((\.)|(\!)|(\,)|(\;)|(\:)|(\-\h\-\s+)|(\-\e\-\s+))/g, ((k, l, v, n, o, p, q, r, s) => v ? "." : n ? "!" : o ? "," : p ? ";" : q ? ":" : r ? "-" : "--"))[R](/[^!,"'.]\"\s/g, '"')[R](/.+?[\.\?\!](\s+|$)/g, (t => t[C](0)[U]() + t.substr(1)))[R](/\"[a-z]/g, (u => u[C](0) + u[C](1)[U]()))
}(a))
```
**547 FF22+ Only**
```
alert(function(z) {
R = "replace", C = "charAt", U = "toUpperCase";
return z[R](/\^((COMMA)|(SEMICOLON)|(COLON)|(PERIOD)|(BANG)|(DASH)|(HYPHEN)|(EMDASH)|(OPENQUOTE)|(CLOSEQUOTE))/g, ((m, _, a, b, c, d, e, f, g, h, i, j) => a ? "," : b ? ";" : c ? ":" : d ? "." : e ? "!" : f ? "-" : g ? "-h-" : h ? "-e-" : i ? ' "' : '" '))[R](/\s+((\.)|(\!)|(\,)|(\;)|(\:)|(\-\h\-\s+)|(\-\e\-\s+))/g, ((xx, __, k, l, m, n, o, p, q) => k ? "." : l ? "!" : m ? "," : n ? ";" : o ? ":" : p ? "-" : "--"))[R](/[^!,"'.]\"\s/g, '"')[R](/.+?[\.\?\!](\s+|$)/g, function(r) {
return r[C](0)[U]() + r.substr(1)
})[R](/\"[a-z]/g, function(s) {
return s[C](0) + s[C](1)[U]()
})
}(a))
```
**611 FF 22+ Only**
```
alert(function(c) {
return c.replace(/\^((COMMA)|(SEMICOLON)|(COLON)|(PERIOD)|(BANG)|(DASH)|(HYPHEN)|(EMDASH)|(OPENQUOTE)|(CLOSEQUOTE))/g, ((x, _, a, b, c, d, e, f, g, h, i) = > a ? "," : b ? ";" : c ? ":" : d ? "." : e ? "!" : f ? "-" : g ? "-h-" : h ? "-e-" : i ? ' "' : '" ')).replace(/\s+\./g, ".").replace(/\s+\!/g, "!").replace(/\s+\,/g, ",").replace(/\s+\;/g, ";").replace(/\s+\:/g, ":").replace(/\s\-\h\-\s/g, "-").replace(/[^!,"'.]\"\s/g, '"').replace(/\s+\-\e-\s+/g, "--").replace(/.+?[\.\?\!](\s+|$)/g, function(b) {
return b.charAt(0).toUpperCase() + b.substr(1)
}).replace(/\"[a-z]/g, function(b) {
return b.charAt(0) + b.charAt(1).toUpperCase()
})
}(a))
```
**653 cross-browser**
```
alert(function(c) {
return c.replace(/\^COMMA/g, ",").replace(/\^SEMICOLON/g, ";").replace(/\^COLON/g, ":").replace(/\^PERIOD/g, ".").replace(/\^BANG/g, "!").replace(/\^DASH/g, "-").replace(/\^HYPHEN/g, "h-h").replace(/\^EMDASH/g, "-e-").replace(/\^OPENQUOTE/g, ' "').replace(/\^CLOSEQUOTE/g, '" ').replace(/\s+\./g, ".").replace(/\s+\!/g, "!").replace(/\s+\,/g, ",").replace(/\s+\;/g, ";").replace(/\s+\:/g, ":").replace(/\s\h\-\h\s/g, "-").replace(/[^!,"'.]\"\s/g, '"').replace(/\s+\-\e-\s+/g, "--").replace(/.+?[\.\?\!](\s|$)/g, function(b) {
return b.charAt(0).toUpperCase() + b.substr(1)
}).replace(/\"[a-z]/g, function(b) {
return b.charAt(0) + b.charAt(1).toUpperCase()
})
}(a))
```
**How it works:**
>
> <https://gist.github.com/ericlagergren/1a61b5d772ae49ab3aea>
>
>
>
[JSFiddle](http://jsfiddle.net/LT7JR/) (for the 653 byte cross-browser solution)
[JSFiddle](http://jsfiddle.net/P6FNF/) (for the 595 FF 22+ **only** solution)
[JSFiddle](http://jsfiddle.net/Z43VJ/) (for the 547 FF 22+ **only** solution)
[JSFiddle](http://jsfiddle.net/Xm6zc/5/) (for the 514 FF 22+ **only** solution)
[JSFiddle](http://jsfiddle.net/Lf4ZP/2/) (for the 487 FF 22+ **only** solution)
This is the first time I've had to write JS that uses more than one regex, and usually my regex is predefined.
I'll continue to shave off bytes as much as I can.
[Answer]
# PHP, 412 bytes
(Ungolfed here for clarity; [see ideone for golfed version](http://ideone.com/FMtY3J).)
PHP's [preg\_replace()](http://php.net/preg-replace) function will accept array arguments, which is pretty useful here. I *think* the following code does everything that's required. It passes all the test cases at least.
```
function x($s) {
$r='preg_replace';
$s=$r('/ +/',' ',$s);
$s=$r(array('/ \^COMMA/','/ \^COLON/','/ \^SEMICOLON/','/ \^PERIOD/','/ \^BANG/',
'/\^DASH/','/ \^HYPHEN /','/ \^EMDASH /','/\^OPENQUOTE /','/ \^CLOSEQUOTE/'),
array(',',':',';','.','!','-','-','--','"',',"'),
$s);
$s=$r('/(^\W*\w|([\.!]| ")\W+\w)/e','strtoupper("$0")',$s);
$s=$r('/([,\.!]),/','\1',$s);
$s=$r('/(\w)( "\w)/e','"$1,".strtoupper("$2")',$s);
echo $s;
}
```
] |
[Question]
[
In the highly underrated Steampunk novel *The Difference Engine*, the equivalent of cinema houses delivered a pixelated moving image displayed by tiles which could be flipped mechanically. The control engine for orchestrating the movement of the these tiles was a large noisy machine controlled by a deck of punched cards.
Your task is to emulate such an engine and display a pixelated animation as specified by an input file. The input consists of lines in a fixed-width format, but you may assume whatever is convenient for a line-ending indication. The format is:
```
SSSSYYxxXXOA
SSSS: 4 digit sequence no. may be padded by blanks or all blank
YY: the y coordinate affected by this line (descending, top is 0, bottom is m-1)
xx: the starting x coordinate
XX: the ending x coordinate
O: hexadecimal opcode
A: argument (0 or 1)
```
The input is explicitly sequenced (if you ever drop your deck of cards on the floor, you'll thank me for this part). That means the program must perform a stable sort of the input lines using the sequence field as a sort key. Lines with the same sequence number must maintain their original relative ordering. (It should work with an unstable sort, if you append the actual line number to the key.) A blank sequence field should be interpreted as lower than any number (ascii collation sequence).
A single statement line can only affect a single y coordinate, but may specify a contiguous range of x values. The ending x value may be left blank or may be identical to the initial value in order to affect a single pixel.
The opcode is a hexadecimal digit which specifies the [Universal Binary Function Code](https://codegolf.stackexchange.com/questions/12103/generate-a-universal-binary-function-lookup-table) which is used as a rasterop. The argument is 0 or 1. The raster operation performed is
```
pixel = pixel OP argument infix expression
--or--
OP(pixel, argument) function call expression
```
So the original value of the pixel enters as X in the UBF table, and the argument value from the statement enters as Y. The result of this function is the new value of the pixel. And this operation is performed upon each x,y pair from xx,YY to XX,YY specified in the statement. The range specified by xx and XX includes both end-points. So
```
0000 0 010F1
```
should set pixels 0,1,2,3,4,5,6,7,8,9,10 on row 0.
Output dimensions (*m* x *n*) should be 20 x 20 at a minimum, but may be larger if desired. But the *grain* should show, you know? It's supposed to be *pixelated*. Both graphical and ASCII-art output are acceptable.
If for example, we wanted to make an image of a pixelated figure:
```
# #
###
##
####
#
#### ####
# #
###
# #
# #
```
If we draw him with a bit-flipping op, like XOR, it can be drawn and erased regardless of whether the screen is black or white.
```
00020261
0 6 661
1 3 561
2 3 461
3 3 661
4 4 461
5 0 361
5 5 861
6 3 361
6 5 561
8 3 561
9 3 361
9 5 561
10 3 361
10 5 561
```
Duplicating this sequence will make the figure appear and disappear.

A larger animation can be composed out-of-order, by specifying different "shots" in the sequence field.
```
100 016F0
101 016F0
102 016F0
103 016F0
104 016F0
105 016F0
106 016F0
107 016F0
108 016F0
109 016F0
110 016F0
111 016F0
112 016F0
113 016F0
114 016F0
115 016F0
200020261
2 0 6 661
2 1 3 561
2 2 3 461
2 3 3 661
2 4 4 461
2 5 0 361
2 5 5 861
2 6 3 361
2 6 5 561
2 8 3 561
2 9 3 361
2 9 5 561
210 3 361
210 5 561
00020261
0 6 661
1 3 561
2 3 461
3 3 661
4 4 461
5 0 361
5 5 861
6 3 361
6 5 561
8 3 561
9 3 361
9 5 561
10 3 361
10 5 561
300020261
3 0 6 661
3 1 3 561
3 2 3 461
3 3 3 661
3 4 4 461
3 5 0 361
3 5 5 861
3 6 3 361
3 6 5 561
3 8 3 561
3 9 3 361
3 9 5 561
310 3 361
310 5 561
00020261
0 6 661
1 3 561
2 3 461
3 3 661
4 4 461
5 0 361
5 5 861
6 3 361
6 5 561
8 3 561
9 3 361
9 5 561
10 3 361
10 5 561
```
Producing:

This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest program (by byte-count) wins.
Bonus (-50) if the engine makes clickity-clack noises.
[Answer]
## Mathematica, ~~306~~ 281 bytes
This expects the input string to be stored in variable `i`
```
ListAnimate[ArrayPlot/@FoldList[({n,y,x,X,o,a}=#2;MapAt[IntegerDigits[o,2,4][[-1-FromDigits[{#,a},2]]]&,#,{y+1,x+1;;X+1}])&,Array[0&,{20,20}],ToExpression/@MapAt["16^^"<>#&,StringTrim/@SortBy[i~StringSplit~"\n"~StringCases~RegularExpression@"^....|..(?!.?$)|.",{#[[1]]&}],{;;,5}]]]
```
And here with some whitespace:
```
ListAnimate[ArrayPlot /@ FoldList[(
{n, y, x, X, o, a} = #2;
MapAt[
IntegerDigits[o, 2, 4][[-1 - FromDigits[{#, a}, 2]]] &,
#,
{y + 1, x + 1 ;; X + 1}
]
) &,
Array[0 &, {20, 20}],
ToExpression /@
MapAt["16^^" <> # &,
StringTrim /@
SortBy[i~StringSplit~"\n"~StringCases~
RegularExpression@"^....|..(?!.?$)|.", {#[[1]] &}], {;; , 5}]
]]
```
This got pretty damn long. This challenge contained a lot of fiddly details, and especially the input parsing takes a lot of code in Mathematica (almost half of it, 137 bytes, are just parsing the input). I ended up switching the language twice before settling on Mathematica (I thought I could save on the input parsing by using Ruby, but then I realised the result needs to be *animated*, so I went back to Mathematica).
[Answer]
## Ungolfed Postscript example
This is a "protocol-prolog"-style program, so the data immediately follows in the same source file. Animated gif files can be produced with ImageMagick's `convert` utility (uses ghostscript): `convert clack.ps clack.gif`.
```
%%BoundingBox: 0 0 321 321
/t { token pop exch pop } def
/min { 2 copy gt { exch } if pop } def
/max { 2 copy lt { exch } if pop } def
/m [ 20 { 20 string }repeat ] def
/draw { change {
m {} forall 20 20 8 [ .0625 0 0 .0625 0 0 ] {} image showpage
} if } def
%insertion sort from https://groups.google.com/d/topic/comp.lang.postscript/5nDEslzC-vg/discussion
% array greater_function insertionsort array
/insertionsort
{ 1 1 3 index length 1 sub
{ 2 index 1 index get exch % v, j
{ dup 0 eq {exit} if
3 index 1 index 1 sub get 2 index 4 index exec
{3 index 1 index 2 copy 1 sub get put 1 sub}
{exit} ifelse
} loop
exch 3 index 3 1 roll put
} for
pop
} def
/process {
x X min 1 x X max { % change? x
m y get exch % row-str x_i
2 copy get % r x r_x
dup % r x r_x r_x
0 eq { 0 }{ 1 } ifelse % r x r_x b(x)
2 mul a add f exch neg bitshift 1 and % r x r_x f(x,a)
0 eq { 0 }{ 255 } ifelse % r x r_x c(f)
exch 1 index % r x c(f) r_x c(f)
ne { /change true def } if
put
} for
draw
} def
{ [ {
currentfile 15 string
dup 2 13 getinterval exch 3 1 roll
readline not{pop pop exit}if
pop
[ exch
/b exch dup 0 1 getinterval exch
/n exch dup 1 1 getinterval exch
/seq exch dup 2 4 getinterval exch
/y exch dup 6 2 getinterval t exch
/x exch dup 8 2 getinterval t exch
/X exch dup 10 2 getinterval dup ( ) ne { t exch }{pop 2 index exch} ifelse
/f exch dup 12 get (16#?) dup 3 4 3 roll put t exch
/a exch 13 get 48 sub
/change false def
>>
}loop ]
dup { /seq get exch /seq get exch gt } insertionsort
true exch
{ begin
b(A)eq{
{ process } if
}{
b(O)eq{
not { process } if
}{
pop
process
}ifelse
}ifelse
change
end
} forall
draw
} exec
100 016F0
101 016F0
102 016F0
103 016F0
104 016F0
105 016F0
106 016F0
107 016F0
108 016F0
109 016F0
110 016F0
111 016F0
112 016F0
113 016F0
114 016F0
115 016F0
200020261
2 0 6 661
2 1 3 561
2 2 3 461
2 3 3 661
2 4 4 461
2 5 0 361
2 5 5 861
2 6 3 361
2 6 5 561
2 8 3 561
2 9 3 361
2 9 5 561
210 3 361
210 5 561
00020261
0 6 661
1 3 561
2 3 461
3 3 661
4 4 461
5 0 361
5 5 861
6 3 361
6 5 561
8 3 561
9 3 361
9 5 561
10 3 361
10 5 561
300020261
3 0 6 661
3 1 3 561
3 2 3 461
3 3 3 661
3 4 4 461
3 5 0 361
3 5 5 861
3 6 3 361
3 6 5 561
3 8 3 561
3 9 3 361
3 9 5 561
310 3 361
310 5 561
00020261
0 6 661
1 3 561
2 3 461
3 3 661
4 4 461
5 0 361
5 5 861
6 3 361
6 5 561
8 3 561
9 3 361
9 5 561
10 3 361
10 5 561
0000 0 515F1
0000 1 11501
0000 1 115F1
```
] |
[Question]
[
Write a function or program to validate an e-mail address against RFC [5321](https://www.rfc-editor.org/rfc/rfc5321) (some grammar rules found in [5322](https://www.rfc-editor.org/rfc/rfc5322)) with the relaxation that you can ignore comments and folding whitespace (`CFWS`) and generalised address literals. This gives the grammar
```
Mailbox = Local-part "@" ( Domain / address-literal )
Local-part = Dot-string / Quoted-string
Dot-string = Atom *("." Atom)
Atom = 1*atext
atext = ALPHA / DIGIT / ; Printable US-ASCII
"!" / "#" / ; characters not including
"$" / "%" / ; specials. Used for atoms.
"&" / "'" /
"*" / "+" /
"-" / "/" /
"=" / "?" /
"^" / "_" /
"`" / "{" /
"|" / "}" /
"~"
Quoted-string = DQUOTE *QcontentSMTP DQUOTE
QcontentSMTP = qtextSMTP / quoted-pairSMTP
qtextSMTP = %d32-33 / %d35-91 / %d93-126
quoted-pairSMTP = %d92 %d32-126
Domain = sub-domain *("." sub-domain)
sub-domain = Let-dig [Ldh-str]
Let-dig = ALPHA / DIGIT
Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig
address-literal = "[" ( IPv4-address-literal / IPv6-address-literal ) "]"
IPv4-address-literal = Snum 3("." Snum)
IPv6-address-literal = "IPv6:" IPv6-addr
Snum = 1*3DIGIT
; representing a decimal integer value in the range 0 through 255
```
Note: I've skipped the definition of `IPv6-addr` because this particular RFC gets it wrong and disallows e.g. `::1`. The correct spec is in [RFC 2373](http://www.ietf.org/rfc/rfc2373.txt).
### Restrictions
You may not use any existing e-mail validation library calls. However, you may use existing network libraries to check IP addresses.
If you write a function/method/operator/equivalent it should take a string and return a boolean or truthy/falsy value, as appropriate for your language. If you write a program it should take a single line from stdin and indicate valid or invalid via the exit code.
### Test cases
The following test cases are listed in blocks for compactness. The first block are cases which should pass:
```
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
email@[123.123.123.123]
"email"@domain.com
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
""@domain.com
"e"@domain.com
"\@"@domain.com
email@domain
"Abc\@def"@example.com
"Fred Bloggs"@example.com
"Joe\\Blow"@example.com
"Abc@def"@example.com
customer/[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
!def!xyz%[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
_somename@[IPv6:::1]
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
```
The following test cases should not pass:
```
plainaddress
#@%^%#$@#$@#.com
@domain.com
Joe Smith <[[email protected]](/cdn-cgi/l/email-protection)>
email.domain.com
email@[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection) (Joe Smith)
[[email protected]](/cdn-cgi/l/email-protection)
[[email protected]](/cdn-cgi/l/email-protection)
email@[IPv6:127.0.0.1]
email@[127.0.0]
email@[.127.0.0.1]
email@[127.0.0.1.]
email@IPv6:::1]
[[email protected]](/cdn-cgi/l/email-protection)]
email@[256.123.123.123]
```
[Answer]
## Python 3.3, 261
```
import re,ipaddress
try:v,p=re.match(r'^(?!\.)(((^|\.)[\w!#-\'*+\-/=?^-~]+)+|"([ !#-[\]-~]|\\[ -~])*")@(((?!-)[a-zA-Z\d-]+(?<!-)($|\.))+|\[(IPv6:)?(.*)\])(?<!\.)$',input()).groups()[7:];exec("if p:ipaddress.IPv%dAddress(p)"%(v and 6or 4))
except:v=5
print(v!=5)
```
Python 3.3 is needed for the ipaddress module, which is used to validate IPv4 and IPv6 addresses.
Less golfed version:
```
import re, ipaddress
dot_string = r'(?!\.)((^|\.)[\w!#-\'*+\-/=?^-~]+)+'
# negative lookahead to check that string doesn't start with .
# each atom must start with a . or the beginning of the string
quoted_string = r'"([ !#-[\]-~]|\\[ -~])*"'
# - is used for character ranges (also in dot_string)
domain = r'((?!-)[a-zA-Z\d-]+(?<!-)($|\.))+(?<!\.)'
# negative lookahead/lookbehind to check each subdomain doesn't start/end with -
# each domain must end with a . or the end of the string
# negative lookbehind to check that string doesn't end with .
address_literal = r'\[(IPv6:)?(.*)\]'
# captures the is_IPv6 and ip_address groups
final_regex = r'^(%s|%s)@(%s|%s)$' % (dot_string, quoted_string, domain, address_literal)
try:
is_IPv6, ip_address = re.match(final_regex, input(), re.VERBOSE).groups()[7:]
# if input doesn't match, calling .groups() will throw an exception
if ip_address:
exec("ipaddress.IPv%dAddress(ip_address)" % (6 if is_IPv6 else 4))
# IPv4Address or IPv6Address will throw an exception if ip_address isn't valid
except:
is_IPv6 = 5
print(is_IPv6 != 5)
# is_IPv6 is used as a flag to tell whether an exception was thrown
```
[Answer]
PHP 5.4.9, 495
```
function _($e){return preg_match('/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!"?(?>\\\[ -~]|[^"]){65,}"?@)(?>([!#-\'*+\/-9=?^-~-]+)(?>\.(?1))*|"(?>[ !#-\[\]-~]|\\\[ -~])*")@(?!.*[^.]{64,})(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?2)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?3)){7}|(?!(?:.*[a-f0-9][:\]]){8,})((?3)(?>:(?3)){0,6})?::(?4)?))|(?>(?>IPv6:(?>(?3)(?>:(?3)){5}:|(?!(?:.*[a-f0-9]:){6,})(?5)?::(?>((?3)(?>:(?3)){0,4}):)?))?(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(?>\.(?6)){3}))\])$/iD', $e);}
```
And just for further interest, here's one for RFC 5322 grammar which allows for nested CFWS and obsolete local-parts:
(764)
```
function _($e){return preg_match('/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z\d-]{64,})(?1)(?>([a-z\d](?>[a-z\d-]*[a-z\d])?)(?>(?1)\.(?!(?1)[a-z\d-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f\d]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f\d][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f\d]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(?>\.(?9)){3}))\])(?1)$/isD', $e);}
```
And if length-limits are not a requirement:
**RFC 5321** (414)
```
function _($e){return preg_match('/^(?>([!#-\'*+\/-9=?^-~-]+)(?>\.(?1))*|"(?>[ !#-\[\]-~]|\\\[ -~])*")@(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?2)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?3)){7}|(?!(?:.*[a-f0-9][:\]]){8,})((?3)(?>:(?3)){0,6})?::(?4)?))|(?>(?>IPv6:(?>(?3)(?>:(?3)){5}:|(?!(?:.*[a-f0-9]:){6,})(?5)?::(?>((?3)(?>:(?3)){0,4}):)?))?(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(?>\.(?6)){3}))\])$/iD', $e);}
```
**RFC 5322** (636)
```
function _($e){return preg_match('/^((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?1)(?>([a-z\d](?>[a-z\d-]*[a-z\d])?)(?>(?1)\.(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f\d]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f\d][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f\d]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(?>\.(?9)){3}))\])(?1)$/isD', $e);}
```
] |
[Question]
[
The input consists of *i* rows with neighbors information. Each *i*th row contains 4 values, representing the neighbor of *i* to the **North**, **East**, **South** and **West** directions, respectively. So each value represents a neighbor at the given direction of the *i*th row, starting from row 1, and can go up to 65,535 rows. The *0* value indicates no neighbor to that direction.
For instance, if the first row is "0 2 3 10" it means that the *i* neighbor has three other neighbors: no one to the north, neighbor *2* to the east, neighbor *3* to the south and neighbor *10* to the west.
You need to output the array of neighbors, starting from the value which is most to the northwest. Each neighbor will be displayed only once, at its position relative to others. Let's see some examples:
Input:
```
0 0 0 0
```
No neighbors (empty case), output:
```
1
```
Input:
```
0 2 0 0
0 0 0 1
```
1 has neighbor 2 to the east. 2 has neighbor 1 to the west
Output:
```
1 2
```
Input:
```
0 2 0 0
0 0 3 1
2 0 0 0
```
1 has neighbor 2 to the east. 2 has neighbor 1 to the west and 3 to the south.
3 has neighbor 2 to the north
Output:
```
1 2
3
```
Input:
```
2 0 0 0
0 0 1 0
```
Output:
```
2
1
```
Input:
```
0 2 3 0
0 0 4 1
1 4 0 0
2 0 0 3
```
Output:
```
1 2
3 4
```
**Rules:**
* Test cases are separated by one **empty line**. Output of different test cases must also be separated by one empty line.
* The output graph is **always** connected. You are not going to have 1 neighbor to 2 only, along with 3 neighbor to 4 only (isolated from 1-2 component).
* **All entries are valid.** Example of invalid entries:
+ Entries containing letters or any symbol different than spaces, line breaks and digits (0-9).
+ the *i*th row containing the *i*th value (because one can't be its own neighbor).
+ a negative value or value higher than 65,535.
+ Less than four values in a row.
+ More than four values in a row.
+ The same neighbor pointing to two different directions (ex: 0 1 1 0).
Standard loopholes apply, and the shortest answer in bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 152 bytes
```
l=input()
def f(x,y,n):
if m[x][y]<n:m[x][y]=n;[f(i%3-1+x,i/3-1+y,h)for h,i in zip(l[n-1],[3,7,5,1])]
e=len(l)
m=eval(`[[0]*e*2]*e*2`)
f(e,e,1)
print m
```
[Try it online!](https://tio.run/##LYzRCoIwGIXv9xS7CTY70jaLwPJJxqCgDQfzV8RCe/ml0s35DofDNyxT25PJOTWRhvckJHv5wIOYsYBkzXgMvLOzs4u7U/1vDd1sEPFQlfo4I542Lmhl6EfeIvJI/BsHkSyV2sFWuOIC7aRjvkmeRJKsa/znmcTDWuUKX5g9HpIF4eGhJRvGSBPvcl4fMKigVpOCwhmbU69U@2Y2onLuBw "Python 2 – Try It Online")
The input order is `NESW`
`f` is a recursive function to populate the houses
[Answer]
* still golfing :)
# [JavaScript (Node.js)](https://nodejs.org), 135 bytes
```
R=>R.map((t,y)=>r.map((T,Y)=>T.map((X,I)=>X==y+1?[-1,1,1,-1].map((x,i)=>t[i]?(r[a=Y+x*-~i%2]=r[a]||[])[I+x*i%2]=t[i]:0):0)),r=[[1]])&&r
```
[Try it online!](https://tio.run/##LYzBCsIwDIbvPkUvjtal0s6dhMyzV/GghB6KOqnMVeoQBfHVZ@YkgfD9X/gv/uHvhxRunW7j8dTX2G@w2syv/iZlBy@FVRphC3uG7Qg7WDPsEF@5XZG2MIy2brRPCGw7Cm4lE3nc58@Z/oRp4ZDRvd/kFK05/EXD39IoXgUJiaxzKstSf4jtPTaneRPPspZEBkQBYiHAOJiQ4QuiFGAHsgJKEObvip9jWnCV6r8 "JavaScript (Node.js) – Try It Online")
### \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
Second approach
# [JavaScript (Node.js)](https://nodejs.org), 130 bytes
```
f=(R,x=0,y=0,c=1,r=[[]])=>[-1,1,1,-1].map((d,i)=>(t=R[c-1][i])&&!(r[Y=y+d*-~i%2]=r[Y]||[])[X=x+d*i%2]?f(R,X,Y,t,r):0,r[y][x]=c)&&r
```
[Try it online!](https://tio.run/##LY5Bi8JADIXv/orxsDKzvspM60nI7n/oSQk5lKmVimtlWpYWZP96NxVJQnjfg5dcq9@qj6l9DNm9q89zQ9q2xEgek06kgETMIo6@OAtYKguy@6ke1tZoFduBSo4KuRW32axt4hNN2/oz@2s/ciGV8nyyOD7SqHiB340eOeKEAckdPBJPwqNQ1IA0x@7ed7fz7tZdbGOZPUwOUxh4wYq9bpi9QVhUMNjD@LeXvzxVhX7s5n8 "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
## Balanced ternary logic
Ternary is normally another name for base 3, that is to say, each digit is `0`, `1`, or `2`, and each place is worth 3 times as much as the next place.
Balanced ternary is a modification of ternary which uses digits of `-1`, `0` and `1`. This has the advantage of not needing a sign. Each place is still worth 3 times as much as the next place. The first few positive integers are therefore `[1]`, `[1, -1]`, `[1, 0]`, `[1, 1]`, `[1, -1, -1]` while the first few negative integers are `[-1]`, `[-1, 1]`, `[-1, 0]`, `[-1, -1]`, `[-1, 1, 1]`.
You have three inputs `x, y, z`. `z` is either `-1`, `0`, or `1`, while `x` and `y` can be from `-3812798742493` to `3812798742493` inclusive.
The first step is to convert `x` and `y` from decimal to balanced ternary. This should give you 27 trits (TeRnary digITS). You then have to combine the trits from `x` and `y` in pairs using a ternary operation and then convert the result back to decimal.
You can choose which values of `z` map to one of these three ternary operations each:
* `A`: Given two trits, if either is zero, then the result is zero, otherwise the result is -1 if they are different or 1 if they are the same.
* `B`: Given two trits, if either is zero, then the result is the other trit, otherwise the result is zero if they are different or the negation if they are the same.
* `C`: Given two trits, the result is zero if they are different or their value if they are the same.
Example. Suppose `x` is `29` and `y` is `15`. In balanced ternary, these become `[1, 0, 1, -1]` and `[1, -1, -1, 0]`. (The remaining 23 zero trits have been omitted for brevity.) After each of the respective operations they become `A`: `[1, 0, -1, 0]`, `B`: `[-1, -1, 0, -1]`, `C`: `[1, 0, 0, 0]`. Converted back to decimal the results are `24`, `-37` and `27` respectively. Try the following reference implementation for more examples:
```
function reference(xd, yd, zd) {
var rd = 0;
var p3 = 1;
for (var i = 0; i < 27; i++) {
var x3 = 0;
if (xd % 3 == 1) {
x3 = 1;
xd--;
} else if (xd % 3) {
x3 = -1;
xd++;
}
var y3 = 0;
if (yd % 3 == 1) {
y3 = 1;
yd--;
} else if (yd % 3) {
y3 = -1;
yd++;
}
var r3 = 0;
if (zd < 0) { // option A
if (x3 && y3) r3 = x3 == y3 ? 1 : -1;
} else if (zd > 0) { // option B
if (!x3) r3 = y3;
else if (!y3) r3 = x3;
else r3 = x3 == y3 ? -x3 : 0;
} else { // option C
r3 = x3 == y3 ? x3 : 0;
}
rd += r3 * p3;
p3 *= 3;
xd /= 3;
yd /= 3;
}
return rd;
}
```
```
<div onchange=r.textContent=reference(+x.value,+y.value,+z.selectedOptions[0].value)><input type=number id=x><input type=number id=y><select id=z><option value=-1>A</option><option value=1>B</option><option value=0>C</option><select><pre id=r>
```
The reference implementation follows the steps given above but you are of course free to use any algorithm that produces the same results.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program or function that violates no standard loopholes wins!
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~231~~ ... 162 bytes
```
import StdEnv
$n=tl(foldr(\p[t:s]#d=sign(2*t/3^p)
=[t-d*3^p,d:s])[n][0..26])
@x y z=sum[3^p*[(a+b)/2,[1,-1,0,1,-1]!!(a+b+2),a*b]!!(z+1)\\a<- $x&b<- $y&p<-[0..26]]
```
Defines the function `@`, taking three `Int`s and giving an `Int`.
Operators map as `1 -> A, 0 -> B, -1 -> C`.
[Try it online!](https://tio.run/##LY7LisIwGIX3fYpfLNK0iZqIgtKAC2cxMDuXaYS0USkkaTFRrA8/mRZmdS4fHE5jrspF2@mnuYJVrYut7btHgHPQX@6VpI4Hk906ox9Z1Ytw8HKuuW/vLmN5WG0uPUq4CETno8V6xEg4KdbLJdtJlBzfMMCH@6cVI89FpooarRgWFBOK13gSOZtNdcEQVnk9pU9BUVWpkkD6XtSTDIu@JP@rMp6DGh9ygCOwPdAt0Pjb3Iy6@0i@f@JpcMq2jf8D "Clean – Try It Online")
The function `$` folds a lambda over the digit places `[0..26]`, into a list of ternary digits. It uses the head of the list it yields to keep a current total difference from the requisite number (which is why it is tailed prior to returning), and `sign(2*t/3^p)` to determine the current digit to yield. The sign trick is equivalent to `if(abs(2*t)<3^p)0(sign t)`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 39 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
×=
×
+ị1,-,0
A-r1¤ṗœs2ṚẎị@ȯµ€Uz0ZU⁹ŀ/ḅ3
```
A full program taking two arguments, `[x,y]`, and `z`
...where `z` is `{A:-1, B:0, C:1}`
**[Try it online!](https://tio.run/##AVAAr/9qZWxsef//w5c9CsOXCivhu4sxLC0sMApBLXIxwqThuZfFk3My4bma4bqO4buLQMivwrXigqxVejBaVeKBucWAL@G4hTP///9bLTYsNF3/MA "Jelly – Try It Online")** Note: the golfed method makes it slow - [this altered version](https://tio.run/##AVgAp/9qZWxsef//w5c9CsOXCivhu4sxLC0sMApBbDPigJjEii1yMcKk4bmXxZNzMuG5muG6juG7i0DIr8K14oKsVXowWlXigbnFgC/huIUz////WzI5LDE1Xf8w "Jelly – Try It Online") is faster (logs by 3, ceils and increments prior to each Cartesian product)
### How?
```
×= - Link 1 (1), B: list of trits L, list of trits R
× - L multiplied by... (vectorises):
= - L equal R? (vectorises)
× - Link -1 (2), A: list of trits L, list of trits R
× - L multiplied by R (vectorises)
+ị1,-,0 - Link 0 (3), C: list of trits L, list of trits R
+ - L plus R (vectorises)
1,-,0 - list of integers = [1,-1,0]
ị - index into (vectorises) - 1-based & modular, so index -2 is equivalent to
- index 1 which holds the value 1.
A-r1¤ṗœs2ṚẎị@ȯµ€Uz0ZU⁹ŀ/ḅ3 - Main link: list of integers [X,Y], integer Z
µ€ - for each V in [X,Y]:
A - absolute value = abs(V)
¤ - nilad followed by link(s) as a nilad:
- - literal minus one
1 - literal one
r - inclusive range = [-1,0,1]
ṗ - Cartesian power, e.g. if abs(V)=3: [[-1,-1,-1],[-1,-1,0],[-1,-1,1],[-1,0,-1],[-1,0,0],[-1,0,1],[-1,1,-1],[-1,1,0],[-1,1,1],[0,-1,-1],[0,-1,0],[0,-1,1],[0,0,-1],[0,0,0],[0,0,1],[0,1,-1],[0,1,0],[0,1,1],[1,-1,-1],[1,-1,0],[1,-1,1],[1,0,-1],[1,0,0],[1,0,1],[1,1,-1],[1,1,0],[1,1,1]]
- (corresponding to: [-13 ,-12 ,-11 ,-10 ,-9 ,-8 ,-7 ,-6 ,-5 ,-4 ,-3 ,-2 ,-1 ,0 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 ,12 ,13 ] )
2 - literal two
œs - split into equal chunks [[[-1,-1,-1],[-1,-1,0],[-1,-1,1],[-1,0,-1],[-1,0,0],[-1,0,1],[-1,1,-1],[-1,1,0],[-1,1,1],[0,-1,-1],[0,-1,0],[0,-1,1],[0,0,-1],[0,0,0]],[[0,0,1],[0,1,-1],[0,1,0],[0,1,1],[1,-1,-1],[1,-1,0],[1,-1,1],[1,0,-1],[1,0,0],[1,0,1],[1,1,-1],[1,1,0],[1,1,1]]]
Ṛ - reverse [[[0,0,1],[0,1,-1],[0,1,0],[0,1,1],[1,-1,-1],[1,-1,0],[1,-1,1],[1,0,-1],[1,0,0],[1,0,1],[1,1,-1],[1,1,0],[1,1,1]],[[-1,-1,-1],[-1,-1,0],[-1,-1,1],[-1,0,-1],[-1,0,0],[-1,0,1],[-1,1,-1],[-1,1,0],[-1,1,1],[0,-1,-1],[0,-1,0],[0,-1,1],[0,0,-1],[0,0,0]]]
Ẏ - tighten [[0,0,1],[0,1,-1],[0,1,0],[0,1,1],[1,-1,-1],[1,-1,0],[1,-1,1],[1,0,-1],[1,0,0],[1,0,1],[1,1,-1],[1,1,0],[1,1,1],[-1,-1,-1],[-1,-1,0],[-1,-1,1],[-1,0,-1],[-1,0,0],[-1,0,1],[-1,1,-1],[-1,1,0],[-1,1,1],[0,-1,-1],[0,-1,0],[0,-1,1],[0,0,-1],[0,0,0]]
- (corresponding to: [1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 ,12 ,13 ,-13 ,-12 ,-11 ,-10 ,-9 ,-8 ,-7 ,-6 ,-5 ,-4 ,-3 ,-2 ,-1 ,0 ] )
ị@ - get item at index V (1-based & modular)
ȯ - logical OR with V (just handle V=0 which has an empty list)
U - upend (big-endian -> little-endian for each)
0 - literal zero }
z - transpose with filler } - pad with MSB zeros
Z - transpose }
U - upend (little-endian -> big-endian for each)
/ - reduce with:
ŀ - link number: (as a dyad)
⁹ - chain's right argument, Z
3 - literal three
ḅ - convert from base
```
[Answer]
# [R](https://www.r-project.org/), ~~190~~ ~~172~~ 151 bytes
```
function(a,b,z){M=t(t(expand.grid(rep(list(-1:1),27))))
P=3^(26:0)
x=M[M%*%P==a,]
y=M[M%*%P==b,]
k=sign(x+y)
switch(z+2,x*y,k*(-1)^(x+y+1),k*!x-y)%*%P}
```
[Try it online!](https://tio.run/##RYzNCoJAFEb3PkUthHvHazhGi6R5BMF9JPjfYEyiE80YPfs0rvp2h49zZtfvLrHrX6rR8qmgoppW/ORCg4bOTJVqD8MsW5i7CR5y0RDzjCNxjn5BIY4l8CRLMDAiv@YhCwshKroF9o@1x1EsclBgIovB8pa6ucMapWSYpZH5JpbbF/nyyPYmtripX9dDeiZ@ogTdDw "R – Try It Online")
Computes all combinations of trits and selects the right one. It'll actually throw a memory error with `27`, since `3^27` is a somewhat large number, but it would in theory work. The TIO link has only `11` trit integer support; I'm not sure at what point it times out or memory errors first, and I don't want Dennis to get mad at me for abusing TIO!
## old answer, 170 bytes
This one should work for all inputs, although with only 32-bit integers, there's the possibility of imprecision as R will automatically convert them to `double`.
```
function(a,b,z){x=y={}
for(i in 0:26){x=c((D=c(0,1,-1))[a%%3+1],x)
y=c(D[b%%3+1],y)
a=(a+1)%/%3
b=(b+1)%/%3}
k=sign(x+y)
switch(z+2,x*y,k*(-1)^(x+y+1),k*!x-y)%*%3^(26:0)}
```
[Try it online!](https://tio.run/##LYxBCoMwFET3OYVdBP43X5ooFSrNzltIC1GwDYKCWpoont1GcDPMvBlm3Nvokeztt29mO/RgqKYFV6e9XjfWDiPYyPaRLNL8oA1AGUSSokQhVobzTKgnOWQ@8LKqT@CRGQ1GKORXnrFaQ336jXV6su8enAij6Wfn5gOLSMnFnroYwu/r6MI8xItLPPKYZy9I80LitreQ3kndSOL@Bw "R – Try It Online")
Takes `-1` for `A`, `0` for `B`, and `1` for `C`.
Ports the approach in [this answer](https://codegolf.stackexchange.com/a/41762/67312) for converting to balanced ternary, although since we're guaranteed to have no more than 27 balanced trits, it's optimized for that.
# [R](https://www.r-project.org/), 160 bytes
```
function(a,b,z){s=sample
x=y=rep(0,27)
P=3^(26:0)
while(x%*%P!=a&y%*%P!=b){x=s(-1:1,27,T)
y=s(-1:1,27,T)}
k=sign(x+y)
switch(z+2,x*y,k*(-1)^(x+y+1),k*!x-y)%*%P}
```
[Try it online!](https://tio.run/##VYxBDoIwFET3PYUsMP/DJ6EYNRJ7BxauSYCANCASiqGFcPYKceVuXubNDLY63ANbfbpilO8OMsppxkUJlb36tmRaGDGUPYQUXZEl4pRCdIlDZFMt2xK067mJI7Kj@YUcFy0UBDzm24AeyMwfrqwRSj470L5BpiY5FjXMfkTaM9R4m4np3vkcN3R0YHA/Xm0F0Y34mUK0Xw "R – Try It Online")
This version will terminate extremely slowly. The bogosort of base conversion, this function randomly picks trits until it somehow magically (`3^-54` chance of it occurring) finds the right trits for `a` and `b`, and then does the required operation. This will basically never finish.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 47 bytes
```
×=
×
N0⁼?ȯȧ?"
ḃ3%3’
0Çḅ3$$⁼¥1#ḢÇṚµ€z0Z⁹+2¤ŀ/Ṛḅ3
```
[Try it online!](https://tio.run/##y0rNyan8///wdFuuw9O5/AweNe6xP7H@xHJ7Ja6HO5qNVY0fNczkMjjc/nBHq7GKClD20FJD5Yc7FgFFds46tPVR05oqg6hHjTu1jQ4tOdqgDxQEqfz//3@0kaWOgqFp7H9DAA "Jelly – Try It Online")
Full program.
`-1` = `C`, `0` = `A`, `1` = `B`
Argument 1: `[x, y]`
Argument 3: `z`
] |
[Question]
[
## Degree of Unsaturation
This is not a particularly hard code puzzle - but I'm interested to see your multiple ways of solving it.
The Degree of Unsaturation is the number of double chemical bonds between atoms, and/or the number rings in a chemical compound.
You will be given the molecular formula of a chemical compound in the form XaYbZc (where a, b and c are the number of atoms of X, Y or Z in the compound) - the formula could be of any length and contain any chemical element in the periodic table (though elements other than C, H, N, F, Cl, Br, I may be ignored as they do not feature in the formula). The compound will contain at least one atom of carbon. You must calculate and display its Degree of Unsaturation.
For example, the compound benzene (pictured below) has a DoU of 4 as it has three double bonds (shown by a double line between atoms), and a single ring (a number of atoms connected in a loop):
[](https://i.stack.imgur.com/ws3kS.jpg)
As defined by [LibreTexts](https://chem.libretexts.org/Core/Organic_Chemistry/Alkenes/Properties_of_Alkenes/Degree_of_Unsaturation#Calculating_Degrees_of_Unsaturation_(DoU)):
>
> DoU = (2C + 2 + N − X − H ) / 2
>
>
>
Where:
* `C` is the number of carbon atoms
* `N` is the number of nitrogen atoms
* `X` is the number of halogen atoms (`F`, `Cl`, `Br`, `I`)
* `H` is the number of hydrogen atoms
## Test cases:
```
C6H6 --> 4
C9H2O1 --> 0
C9H9N1O4 --> 6
U1Pt1 --> Not a valid input, no carbon
Na2O1 --> Not a valid input, no carbon
C1H1 --> 1.5, although in practice this would be one, but is a part of a compound rather than a compound in entirety.
N1H3 would return 0 - though in practice it isn't an organic compound (in other words it contains no carbon) so the formula wouldn't apply and it isn't a valid input
```
For an explanation of CH [see here](http://www.ebi.ac.uk/chebi/searchId.do?printerFriendlyView=true&locale=null&chebiId=29358&viewTermLineage=true&structureView=& "see here")
**In essence, you must identify if there are any of the above elements (C, H, N, F, Cl, Br, I) in the compound, and if so how many there are. Then, calculate the Degree of Unsaturation using the above formula.**
Only C, H, N, F, Cl, Br, and I are valid inputs for the DoU formula. For the purposes of this puzzle, any other elements may be completely ignored (eg if the compound were C6H6Mn the result would still be 4). If there are none of the above compounds the answer would be zero.
You may assume that all the compounds input are chemically possible, contain at least one atom of carbon, and are known to exist. If the input is invalid, the program may output either 0 or -1, or produce no result.
## Rules
[Standard IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and [loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. Input must be a standard string, and you can assume the input won't be empty. This is codegolf - so the shortest code in bytes wins.
[Answer]
## JavaScript (ES6), ~~117~~ 112 bytes
Returns `0` for invalid inputs.
```
s=>s.split(/(\d+)/).reduce((p,c,i,a)=>p+[0,k=a[i+1]/2,2*k,-k][n='NCFHIClBr'.search(c||0)+1,s|=n==2,n>2?3:n],1)*s
```
### Test cases
```
let f =
s=>s.split(/(\d+)/).reduce((p,c,i,a)=>p+[0,k=a[i+1]/2,2*k,-k][n='NCFHIClBr'.search(c||0)+1,s|=n==2,n>2?3:n],1)*s
console.log(f("C6H6")) // --> 4
console.log(f("C9H20")) // --> 0
console.log(f("C9H9N1O4")) // --> 6
console.log(f("U1Pt1")) // --> 0 (invalid)
console.log(f("Na2O1")) // --> 0 (invalid)
console.log(f("C1H1")) // --> 1.5
console.log(f("N1H3")) // --> 0 (invalid)
```
## Alternate version, 103 bytes
If the input was guaranteed to be valid -- as the challenge introduction is misleadingly suggesting -- we could just do:
```
s=>s.split(/(\d+)/).reduce((p,c,i,a)=>p+[0,k=a[i+1]/2,2*k,-k][n='NCFHIClBr'.search(c||0)+1,n>2?3:n],1)
```
### Demo
```
let f =
s=>s.split(/(\d+)/).reduce((p,c,i,a)=>p+[0,k=a[i+1]/2,2*k,-k][n='NCFHIClBr'.search(c||0)+1,n>2?3:n],1)
console.log(f("C6H6")) // --> 4
console.log(f("C9H20")) // --> 0
console.log(f("C9H9N1O4")) // --> 6
console.log(f("C1H1")) // --> 1.5
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~142 151~~ 148 bytes
```
import re
l=dict(re.findall("(\D+)(\d+)",input()))
m=lambda k:int(l.get(k,0))
print(m("C")and m("C")+1+(m("N")-sum(map(m,"F I H Cl Br".split())))/2)
```
Returns 0 on error.
Thanks to @HyperNeutrino bringing the bytes down.
[Try it online!](https://tio.run/##JYyxDoIwFAB3vqJ503spoqgLJixiDC74AyzVVm1oS1PK4NdX0e1yl5x/x9fodilp68cQWVCZqaW@RwyqeGgnhTEI2J84YS85Qa6dnyMSUWZrI@xNCjYctItoiqeKOOSbb/JhMRahARJOsj/xki@uA1pNs0UrPNoczuzCWtYYdgxQTN7o353WW0qpqdqqK6/7Dw "Python 3 – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~70~~ 67 bytes
```
`C\d`Na&1+/2*VaR+XDs._R['C'NC`H|F|I|Cl|Br`].s["+2*"'+'-]RXU.XX"+0*"
```
Takes the chemical formula as a command-line argument. Outputs `0` for invalid inputs. [Try it online!](https://tio.run/##K8gs@P8/wTkmJcEvUc1QW99IKywxSDvCpVgvPiha3VndzznBo8atxrPGOafGqSghVq84WknbSEtJXVtdNzYoIlQvIkJJ20BL6f///86WHpZ@hv4mAA "Pip – Try It Online")
### Explanation
Uses a series of regex replacements to turn the chemical formula into a mathematical formula, evals it, and makes a couple tweaks to get the final value.
The replacements (slightly ungolfed version):
```
aR+XDs._R"C ""+2*"R"N "'+R`(H|F|I|Cl|Br) `'-RXU.XX"+0*"
a Cmdline arg
R+XD Replace runs of 1 or more digits (\d+)
s._ with a callback function that prepends a space
(putting a space between each element and the following number)
R"C " Replace carbon symbol
"+2*" with +2* (add 2* the number of carbon atoms to the tally)
R"N " Replace nitrogen symbol
'+ with + (add the number of nitrogen atoms to the tally)
R`(H|F|I|Cl|Br) ` Replace hydrogen or halogen symbol
'- with - (subtract the number of atoms from the tally)
RXU.XX Replace uppercase letter followed by another char ([A-Z].)
"+0*" with +0* (cancel out numbers of all other kinds of atoms)
```
We eval the resulting string with `V`. This gives us `2C + N − X − H`. To get the correct value, we make the following adjustments:
```
`C\d`Na&1+/2*V...
V... Value of expression calculated above
/2* multiplied by 1/2
1+ plus 1
`C\d`Na Is carbon in the original formula? (i.e. C followed by a digit)
& Logical AND: if no carbon, return 0, otherwise return the formula value
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 195 ~~197~~ ~~202~~ bytes
Probably the longest answer.
```
d,c,b,e,n;f(char*a){for(c=d=0;b=*a;d+=e?e-1?b-66?b-67?0:e-2?0:-n:e-3?0:-n:b-67?b-78?b/70*73/b?-n:0:n:(c=2*n):0)e=*++a>57?*a-108?*a-114?0:3:2:1,a+=e>1,n=strtol(a,&a,10);printf("%.1f",c?d/2.+1:0);}
```
[Try it online!](https://tio.run/##hYwxb8IwEIX3/IooUivbsYnPoQnESj2wZIIu3brYjtMitaZy0wnx21MDYmy44e7du@@eZe/WTlNPLTXUUS8HZD90IBofh0NAtu1bLk1LtOzz1inHQBlWVedWK944JmJnPoryKi4Hw@qVMkXNSV0WRkWbN76JaUAF8bjh2LUkz/XzU62IZsBXlwHLmIGiT0t8nQI3QH37M4bx8Ik0fdQUOJbfYe/HAWUPCxgyalVfiEUOMVaepnhJv/TeI5wckzRW5DZVV2VYXtbb75u/OWdg3Ql@j1hvYbechV7hZYRZYqvFbp7YQHcnArryfyC48Tf4lMvklEx/ "C (gcc) – Try It Online")
Returns 0 on error.
] |
[Question]
[
# Challenge
Given two question IDs, try to figure out how similar they are by looking at the answers.
# Details
You will be given two question IDs for `codegolf.stackexchange.com`; you may assume that there exist questions for both IDs that are not deleted, but are not necessarily open. You must run through all of the answers and determine the minimum Levenshtein distance between the code in the answers to the two questions (not including deleted answers). That is, you should compare every answer in question 1 to every answer in question 2, and determine the minimum Levenshtein distance. To find the code in an answer, assume the following procedure:
### How to find the code snippet
A body of text is the answer's actual code if it is in backticks and is on its own line, or if it is indented with 4 spaces, with an empty line above it, unless there is no text above.
### Examples of valid and not-valid code snippets (with `.` as a space) (separated by a ton of equal signs)
```
This is `not a valid code snippet because it is not on its own line`
========================================
This is:
`A valid code snippet`
========================================
This is
....not a valid code snippet because there's no spacing line above
========================================
This is
....A valid code snippet because there's a spacing line above
========================================
....Valid code snippet because there's no other text
========================================
```
If there are no valid code snippets in the answer, ignore the answer completely. **Note that you should only take the first codeblock.**
# Final Specs
The two question IDs can be inputted in any reasonable format for 2 integers. The output should be the smallest Levenshtein distance between any two valid answers from either challenge. If there are no "valid" answers for one or both of the challenges, output `-1`.
# Test Case
For challenge `115715` (Embedded Hexagons) and `116616` (Embedded Triangles) both by Comrade SparklePony, the two Charcoal answers (both by KritixiLithos) had a Levenshtein distance of 23, which was the smallest. Thus, your output for `115715, 116616` would be `23`.
# Edit
You may assume that the question has at most 100 answers because of an API pagesize restriction. You should not ignore backticks in code blocks, only if the code block itself is created using backticks and not on its own line.
# Edit
I terminated the bounty period early because I made a request to a mod to get a one-week suspension and I didn't want the bounty to be automatically awarded to the highest scoring answer (which happens to be the longest). If a new submission comes in or a submission is golfed enough to become shorter than 532 bytes before the actual end of the bounty period (UTC 00:00 on Jun 1), I will give that a bounty to stay true to my promise, after the suspension expires. If I remember correctly, I need to double the bounty period next time so if you do get an answer in, you might get +200 :)
[Answer]
# **Java + Jsoup, 1027 bytes**
The first two arguments are the question IDs.
**Golfed:**
```
import org.jsoup.*;import org.jsoup.nodes.*;class M{String a1[]=new String[100],a2[]=new String[100],c[];int i1=0,i2=0;public static void main(String a[])throws Exception{String r="https://codegolf.stackexchange.com/questions/";M m=new M();m.c=m.a1;m.r(Jsoup.connect(r+a[0]).get());m.c=m.a2;m.r(Jsoup.connect(r+a[1]).get());int s=m.ld(m.a1[1],m.a2[1]);for(int i=2;i<m.a1.length;i++)for(int j=2;j<m.a2.length;i++){if(m.a1[i]==null)break;int d=m.ld(m.a1[i],m.a2[j]);if(d<s)s=d;}System.out.print(s);}void r(Document d){a:for(Element e:d.select("td")){for(Element p:e.select("pre")){ a(p.select("code").get(0).html());continue a;}}}void a(String d){c[c==a1?i1++:i2++]=d;}int ld(String a,String b){a=a.toLowerCase();b=b.toLowerCase();int[]costs=new int[b.length()+1];for(int j=0;j<costs.length;j++)costs[j]=j;for(int i=1;i<=a.length();i++){costs[0]=i;int nw=i-1;for(int j=1;j<=b.length();j++){int cj=Math.min(1+Math.min(costs[j],costs[j-1]),a.charAt(i-1)==b.charAt(j-1)?nw:nw+1);nw=costs[j];costs[j]=cj;}}return costs[b.length()];}}
```
**Readable:**
```
import org.jsoup.*;import org.jsoup.nodes.*;
class M {
String a1[]=new String[100],a2[]=new String[100],c[];
int i1=0,i2=0;
public static void main(String a[])throws Exception{
String r="https://codegolf.stackexchange.com/questions/";
M m=new M();
m.c=m.a1;
m.r(Jsoup.connect(r+a[0]).get());
m.c=m.a2;
m.r(Jsoup.connect(r+a[1]).get());
int s=m.ld(m.a1[1],m.a2[1]);
for(int i=2;i<m.a1.length;i++)for(int j=2;j<m.a2.length;i++){if(m.a1[i]==null)break;int d=m.ld(m.a1[i],m.a2[j]);if(d<s)s=d;}
System.out.print(s);
}
void r(Document d) {
a:for(Element e:d.select("td")) {for(Element p:e.select("pre")) {
a(p.select("code").get(0).html());
continue a;
}}
}
void a(String d){c[c==a1?i1++:i2++]=d;}
int ld(String a, String b) {
a = a.toLowerCase();
b = b.toLowerCase();
int [] costs = new int [b.length() + 1];
for (int j = 0; j < costs.length; j++)costs[j] = j;
for (int i = 1; i <= a.length(); i++) {
costs[0] = i;
int nw = i - 1;
for (int j = 1; j <= b.length(); j++) {
int cj = Math.min(1 + Math.min(costs[j], costs[j - 1]), a.charAt(i - 1) == b.charAt(j - 1) ? nw : nw + 1);
nw = costs[j];
costs[j] = cj;
}
}
return costs[b.length()];
}
```
}
[Answer]
## PowerShell, 532 Bytes
```
$1,$2=$args
$a={irm "api.stackexchange.com/2.2/questions/$args/answers?pagesize=100&site=codegolf&filter=!9YdnSMKKT"|% i*}
$r={$args.body-replace"(?sm).*?^(<pre.*?>)?<code>(.*?)</code>.*",'$2'}
$1=&$a $1;$2=&$a $2
(0..($1.count-1)|%{
$c=&$r $1[$_]
0..($2.count-1)|%{
&{$c,$d=$args;$e,$f=$c,$d|% le*;$m=[object[,]]::new($f+1,$e+1);0..$e|%{$m[0,$_]=$_};0..$f|%{$m[$_,0]=$_};1..$e|%{$i=$_;1..$f|%{$m[$_,$i]=(($m[($_-1),$i]+1),($m[$_,($i-1)]+1),($m[($_-1),($i-1)]+((1,0)[($c[($i-1)]-eq$d[($_-1)])]))|sort)[0]}};$m[$f,$e]} $c $d
}
}|sort)[0]
```
I left newlines in there for some readability. The are still reflected in my byte count.
Pretty sure I have a handle on this. The tough part for me was actually getting the Levenshtein distance since PowerShell does not have a builtin for that as far as I know. Because of that I was able to answer the related challenge on [Levenshtein distance](https://codegolf.stackexchange.com/a/123389/52023). When my code refers to an anonymous function for LD you can refer to that answer for a more detailed explanation as to how that works.
### Code with comments and progress indicator
The code can get real slow (because of the LD) so I built in some progress indicators for myself so I could follow the action as it unfolded and not assume it was stuck in a loop somewhere. The code for monitoring progress is not in the top block nor counted in my byte count.
```
# Assign the two integers into two variables.
$1,$2=$args
# Quick function to download up to 100 of the answer object to a given question using the SE API
$a={irm "api.stackexchange.com/2.2/questions/$args/answers?pagesize=100&site=codegolf&filter=!9YdnSMKKT"|% i*}
# Quick function that takes the body (as HTML) of an answer and parses out the likely codeblock from it.
$r={$args.body-replace"(?sm).*?^(<pre.*?>)?<code>(.*?)</code>.*",'$2'}
# Get the array of answers from the two questions linked.
$1=&$a $1;$2=&$a $2
# Hash table of parameters used for Write-Progress
# LD calcuations can be really slow on larger strings so I used this for testing so I knew
# how much longer I needed to wait.
$parentProgressParameters = @{
ID = 1
Activity = "Get LD of all questions"
Status = "Counting poppy seeds on the bagel"
}
$childProgressParameters = @{
ID = 2
ParentID = 1
Status = "Progress"
}
# Cycle each code block from each answer against each answer in the other question.
(0..($1.count-1)|%{
# Get the code block from this answer
$c=&$r $1[$_]
# Next line just for displaying progress. Not part of code.
Write-Progress @parentProgressParameters -PercentComplete (($_+1) / $1.count * 100) -CurrentOperation "Answer $($_+1) from question 1"
0..($2.count-1)|%{
# Get the code block from this answer
$d=&$r $2[$_]
# Next two lines are for progress display. Not part of code.
$childProgressParameters.Activity = "Comparing answer $($_+1) of $($2.count)"
Write-Progress @childProgressParameters -PercentComplete (($_+1) / $2.count * 100) -CurrentOperation "Answer $($_+1) from question 2"
# Anonymous function to calculate Levenstien Distance
# Get a better look at that function here: https://codegolf.stackexchange.com/a/123389/52023
&{$c,$d=$args;$e,$f=$c,$d|% le*;$m=[object[,]]::new($f+1,$e+1);0..$e|%{$m[0,$_]=$_};0..$f|%{$m[$_,0]=$_};1..$e|%{$i=$_;1..$f|%{$m[$_,$i]=(($m[($_-1),$i]+1),($m[$_,($i-1)]+1),($m[($_-1),($i-1)]+((1,0)[($c[($i-1)]-eq$d[($_-1)])]))|sort)[0]}};$m[$f,$e]} $c $d
}
# Collect results and sort leaving the smallest number on top.
}|sort)[0]
```
My logic for finding the code blocks is to take answer as HTML and look for a code tag set, optionally surrounded by a pre tag set that starts on its own line. In testing it found all the correct data on 6 different question sets.
I tried to work from the markdown code but it was too difficult to find the right code block.
### Sample runs
```
Challenge-Similarity-Detector 97752 122740
57
Challenge-Similarity-Detector 115715 116616
23
```
[Answer]
# Mathematica, 540 bytes
```
f=Flatten;l=Length;P=StringPosition;(H[r_]:=Block[{s,a,t,k},t={};d=1;k="https://codegolf.stackexchange.com/questions/"<>r;s=First/@P[Import[k,"Text"],"<pre><code>"];a=f[First/@P[Import[k,"Text"],"answerCount"]][[1]];While[d<l@s,If[s[[d]]>a,AppendTo[t,s[[d]]]];d++];Table[StringDelete[StringCases[StringTake[Import[k,"Text"],{t[[i]],t[[i]]+200}],"<pre><code>"~~__~~"</code></pre>"],{"<pre><code>","</code></pre>"}],{i, l@t}]];Min@DeleteCases[f@Table[EditDistance[ToString@Row@H[#1][[i]],ToString@Row@H[#2][[j]]],{i,l@H[#1]},{j,l@H[#1]}],0])&
```
**input**
>
> ["115715", "116616"]
>
>
>
**output**
>
> 23
>
>
>
uses built-in EditDistance which "gives the edit or Levenshtein distance between strings or vectors u and v."
As for the test case mathematica
```
EditDistance["FN«AX²ιβ×__β↓↘β←↙β↑←×__β↖β→↗β","NαWα«X²ι↙AX²⁻ι¹β↙β↑↖β→A⁻α¹α"]
```
returns 23
I guess I can golf it a bit more
Takes some minutes to run
] |
[Question]
[
There has recently been a big snow, and my driveway needs snow-blowing. If the snow-blower goes over some area that it has already snow-blowed, then that area will have snow blown onto it and need to be blown again. And of course, the snow-blower cannot start in the middle of the driveway, it needs to start from my garage, where it is stored.
**More formally:**
Your program takes a standard form of input as a string or multidimensional array that looks like the following:
```
XXXXOOOOXXXX
X X
X X
XXXXXXXXXXXX
```
`X` represents an area that cannot be snow-blowed, `O` represents an area where the snow-blower can be deployed, and empty spaces represent areas where there is snow. You can chose different values if you wish.
Your program must output something like the following:
```
XXXX*%OOXXXX
Xv<<<^<<<<<X
X>>>>>>>>>^X
XXXXXXXXXXXX
```
The snow-blower starts at the `*`. The `*` always points to the nearest non-garage space. The `<`,`>`,`v`, and `^` all represent pointers of where the next direction is. They point the snow-blower where to go. Once a pointer points to the `%`, the blower has re-arrived into the garage, and the whole driveway should be clear.
The snow blower must go over the whole driveway. The snowblower's path can never overlap itself. Impossible input must not be given.
Because I don't want to be outside any longer than I need to be, and not need to spend a lot of time typing, the program should be as short as possible. Shortest code wins!
**Test Cases:**
These test cases may have multiple correct answers. I have provided possible solutions below each test case.
Test case 1:
The one given in the example.
Test case 2:
```
XOOOOOX
X X
X X
X XXXXXXXX
X X
X X
XXXXXXXXXXXXXX
X*OOO%X
Xv>>>^X
Xv^<<<X
Xv>>>^XXXXXXXX
Xv^<<<<<<<<<<X
X>>>>>>>>>>>^X
XXXXXXXXXXXXXX
```
Test case 3:
```
XOOOOX
X X
X X
X XXX
X X
X X
XXXXXX
XOO%*X
X>>^vX
X^v<<X
X^vXXX
X^>>vX
X^<<<X
XXXXXX
```
Test case 4:
```
XXXXXXXXXXXXX
O X
O X X
O X X
O X
XXXXXXXXXXXXX
XXXXXXXXXXXXX
*>>>>>>>>>>vX
Ov<v<Xv<<<<<X
Ov^v^X>>>>>vX
%<^<^<<<<<<<X
XXXXXXXXXXXXX
```
[Answer]
# JavaScript (ES6), ~~346~~ ~~310~~ ~~299~~ ~~298~~ ~~297~~ ~~296~~ 283 bytes
```
f=(a,y=0,x=0)=>(a[y][x]?a[y][x]=='O'&&(a[y][x]='*',(g=w=>(w=a[y])&&w[x]&&(w[x]<'!'?g(w[x]='v',y++)||g(w[x++]='>',y--)||g(w[--x]='^',y--)||g(w[x--]='<',y++)||+(w[++x]=' '):w[x]=='O'&&!/ /.test(a)?w[x]='%':0))(y++)||g(y-=2)||g(y++,x++)||g(x-=2)||+(a[y][++x]='O'))||f(a,y,x+1):f(a,y+1))
```
```
<textarea id="tests">XXXXOOOOXXXX X X X X XXXXXXXXXXXX XOOOOOX X X X X X XXXXXXXX X X X X XXXXXXXXXXXXXX XOOOOX X X X X X XXX X X X X XXXXXX XXXXXXXXXXXXX O X O X X O X X O X XXXXXXXXXXXXX</textarea><br><button onclick="for(test of document.getElementById('tests').value.split('\n\n')){console.log(test);arr=test.split('\n').map(line=>line.split(''));f(arr);console.log(arr.map(line=>line.join('')).join('\n'))}">Run</button>
```
Quite hacky in some places, but I wanted to get the code out there. Input as a 2D character array, output by modifying said array.
### Ungolfed version
This is the same exact algorithm, save for some truthy/falsy magic with `+' '` being `NaN` being falsy (and some more), some golf variables and using `if`s instead of `?:`, `||` and `&&`.
```
f = (a, y = 0, x = 0) => { // main function
if (!a[y][x]) // check for end of line
return f(a, y + 1); // end of line, recursively check next
if (a[y][x] == 'O') { // check for valid start position
a[y][x] = '*'; // set the start position
function g() { // pathfinder function
if (!a[y] || !a[y][x]) // check for out of bounds
return 0;
if (a[y][x] == ' ') { // check for snow
a[y][x] = 'v'; // set current cell to 'down'
y++; // move position down
if (g()) return 1; // see if a valid route is found from there
y--; // if not, reset position and try again
a[y][x] = '>'; // repeat for other directions
x++;
if (g()) return 1;
x--;
a[y][x] = '^';
y--;
if (g()) return 1;
y++;
a[y][x] = '<';
x--;
if (g()) return 1;
x++;
a[y][x] = ' '; // no route found, reset cell to snow
return 0;
}
if (a[y][x] == 'O' // check for valid exit
&& !/ /.test(a)) { // and that no snow is left
a[y][x] = '%'; // set the exit
return 1;
}
}
y++; // move a cell down from the start position
if (g()) return 1; // see if a valid route starts there
y -= 2; // repeat for other directions
if (g()) return 1;
y++; x++;
if (g()) return 1;
x -= 2;
if (g()) return 1;
x++;
a[y][x] = 'O'; // no route found, continue on
}
return f(a, y, x + 1); // check the next cell
}
```
[Answer]
# Python3, 737 bytes
```
E=enumerate
G=['v','^','>','<']
O=lambda x,y,D,M=1:[(*t,D[t],m)for(X,Y),m in zip([(1,0),(-1,0),(0,1),(0,-1)],G)if(M==1 or[m in G[:2],m in G[2:]][M in G[:2]])and(t:=(x+X,y+Y))in D]
def f(b):
d={(x,y):v for x,j in E(b)for y,v in E(j)}
q=[({**d,i:'*'},*i)for i in d if'O'==d[i]][:1]
while q:
D,x,y=q.pop(0)
u,F={},1
Q=[]
for X,Y,v,m in O(x,y,D):
u[v]=(m,(X,Y))
if' '==v and{V for J,K,V,_ in O(X,Y,D,m)if(J,K)not in[(X,Y),(x,y)]}&{'O','X',*G}:Q+=[({**D,(X,Y):m},X,Y)];F=0
if F:
if' 'not in D.values()and'O'in u:
D={**D,u['O'][1]:'%'}
for x,y in D:b[x][y]=D[(x,y)]
return b
elif' 'in u:Q+=[({**D,u[' '][1]:u[' '][0]},*u[' '][1])]
if not all(' 'not in[V for *_,V,_ in O(*i,D)]for i in D if'O'==D[i]):q+=Q
```
[Try it online!](https://tio.run/##pVPda9swEH@e/wpR2CQ51xCnfRjetCe3gY0u9KWkaFpxsE1V/BXHyZoF/@3ZSUqcrBtjUIEj3fl@H7pz6k37WJUX7@tmt7sSabkq0iZuU28iJF1ToN/x@YTPR6q8qcjjYp7E5Bk2EMGNCELJ/BYi2SooeFY1bAb3HAqiS/JT10yyAEYc2LnbRhDY3/OAK5hwnbEbIQJSNdIiJjIcK9gfx6FS8qZPKx6XCWtDwZ4HM9gM7jnHV5HykjQjGZvz0COJ2DJ0xsM1QSto8snAr/ClCTewduET7zyyEJJtfT8BHVKfduBrW6RNSUJ0RqdUiERqNBEGyiM/HnWekgWqkAhQRCyGdVWzEcfECq7FtoMAj7dCYrGVx07A2t1mymzDjEeslmslWAG2VQZu1AiqrQlecXtnwZ/hC9zBgwMbpgj7i/3CPC@rFvPStdpeWHXvtmgY6IyCP@nC24G7XeREwqIDs6sP12LkGT1yHfbCjo5Ew3Wcr9IlM41GMkytbBGJhKVaScwqGaiQvqWdfeO6vLHwcC6fldwoEUnnyVY0abtqSjI3QZpbPUt8dIi0xNHuTyOF0@izlgcNG5dxnrPesHSN8h@OffI19lj1Y4wOY4xwjDxcDMTtbhkQQc7OzrwZrikus3sz0q@XwcnyDG45PhBMLXxf/sd@wJywvSB/SX8QuDgV2CNOt571uJ2gL0/udySe/qZqo9k/or/7swLm79ZWD/MqbhK2xC/6zX7EUvpakb75mc7btGFfqzIFshwu61y3jH4rKceJenWjSxcOnypdsiKuGXVnyNiRP@BmHcrPqX854v8NHr8GfPEa8KUF734B)
] |
[Question]
[
## Intro
The Switching sequence is defined like so:
Start with `n` people standing in a circle (`6` for this example).
```
1 2
6 3
5 4
```
Starting from person `1`, the person that is to the left of the "chosen" person is removed.
```
1
6 3
5 4
```
The removed person can "switch" the removal method up:
* If the removed person is even (which it is in this case), the next removed person will be to the right of the next "chosen" person.
* If the removed person is odd, the next removed person will be to the left of the next "chosen" person.
The next chosen person is also dependent on the previously removed person.
* If the removed person is even, the next chosen person will be to the right of the previous chosen person.
* If the removed person is odd, see above, but replace "right" with "left".
So the next chosen person is then `6`.
Now we remove the person to the right of `6`, which is `5`:
```
1
6 3
4
```
Because `5` is odd, the removed person is now to the left. The new chosen person is `1`.
We now remove `3`:
```
1
6
4
```
We continue this process, until we're left with 1 number - in this example, the final number is `1`. So therefore `S(6) = 1`.
The first few numbers are:
```
n | S(n)
---------
1 | 1
2 | 1
3 | 3
4 | 1
5 | 5
6 | 1
7 | 3
8 | 6
9 | 5
10 | 6
11 | 9
```
## Task
Your task is to make a program (or a function) that returns `S(n)` (the `n`th number in the Switching sequence) when given `n`, using the least amount of bytes.
Example inputs and outputs:
```
1 -> 1
10 -> 6
13 -> 13
```
You are guaranteed to get a positive integer.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
*Note: There is no OEIS sequence (what?), to save you the trouble of searching.*
[Answer]
# Python 2, ~~183~~ 94 bytes
-4 bytes thanks to Artyer (use `input()` and `print` rather than `def` and `return`)
-1 byte thanks to FlipTack (use `print-~p[0]` rather than `print p[0]+1`)
```
p=range(input())
d=i=1
while p[1:]:m=p.pop(i)%2;i-=m+m-(d<0);d=-m|1;i+=d;i%=len(p)
print-~p[0]
```
**[repl.it](https://repl.it/EJXv/7)**
This just follows the instructions given, I've noticed some pattern, maybe it could be exploited?
The only changes are:
* to use `0` based indexing (so even people are odd and vice-versa) - this is saves 5 bytes in the golfed logic and is corrected at the end with `+1`
* to use `1` as left and `-1` as right (to use a range - just like everyone is facing outwards instead)
* to change the logic of the step where the next chosen individual is found to account for `pop`ing from the list making the "pointer" index already step one to the right in the list (or to the left in original terminology).
Ungolfed:
```
def circle(n):
people = range(n) # p
direction = 1 # d
removeIndex = 1 # i
while n > 1:
removingMod2 = people.pop(removeIndex) % 2 # m
removeIndex -= removingMod2 + removingMod2 - (direction == -1)
direction = -removingMod2 or 1
removeIndex += direction
n -= 1
removeIndex %= n
return people[0] + 1
```
] |
[Question]
[
This programming puzzle is inspired by another question which has been asked here yesterday but which was deleted by the author...
**The challenge:**
Create an executable binary (Windows .EXE or Linux binary) using Visual C# (or your favorite C# IDE) which prints the following text to the standard output:
```
Main() is the main method of C# programs!
```
... without using the 4 consecutive letters M-A-I-N appearing in any source file!
Notes:
* If your source code contains the text `remainder` (for example) it contains the 4 consecutive letters M-A-I-N, however if it contains `mxain` the 4 letters would not be consecutive any more so `mxain` would be allowed.
* You are not allowed to run any programs but the C# IDE nor change the settings of the C# IDE to run other programs (but the ones it would normally run such as the C# compiler).
Otherwise you could simply say: "I write a Pascal program using the C# IDE and invoke the Pascal compiler in the 'pre-build' steps of my C# project".
This would be too simple.
* Users of an IDE that can be extending using "plug-ins" (or similar) or that have built-in binary file editors (hex-editors) would have a **too** large advantage over users of other C# IDEs.
Therefore these featrues should also not be used.
* Using the other non-ASCII-Editors (such as the dialog window editor) is explicitly allowed!
* The user asking the original question proposed using the backslash in function names just like this: `static void M\u0061in()` Because this answer has already been read by other users it will not be accepted any more!
* A user asked if it would be allowed to simply type in an .EXE file into the source code editor and to save the file as ".exe" instead of ".cs". Answer: I doub't that this is possible because both valid Windows and Linux binaries contain NUL bytes. However if you find a valid binary that can be created this way you have a valid solution.
The name of this site is "Programming Puzzles **&** Code Golf" - this is a "Programming Puzzle", not "Code Golf": The challenge is to find a working solution before all other users, not to find a solution shorter than all other solutions.
Therefore the **first post describing a working solution wins**!
Good luck!
By the way: I have a solution working under Visual C# Express 2010.
[Answer]
# C# Interactive Window
Open the C# Interactive Window (View > Other Windows > C# Interactive in Visual Studio 2015). I suppose not all IDEs will have this.
This approach executes C# in the Interactive Window in order to create a C# exe that prints the desired string without the author ever writing `main`. As a bonus, the exe's IL also does not contain `main`.
Run the following code in the Interactive Window
```
using System.Reflection;
using System.Reflection.Emit;
var appMeow = (dynamic)System.Type.GetType("System.AppDom" + "ain").GetProperty("CurrentDom" + "ain", BindingFlags.GetProperty | BindingFlags.Static | BindingFlags.Public).GetValue(null);
var asmName = new AssemblyName("MEOW");
var asmBuilder = appMeow.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);
var module = asmBuilder.DefineDynamicModule("MEOW", "MEOW.exe");
var typeBuilder = module.DefineType("Meow", TypeAttributes.Public);
var entryPoint = typeBuilder.DefineMethod("EntryPoint", MethodAttributes.Static | MethodAttributes.Public);
var il = entryPoint.GetILGenerator();
il.Emit(OpCodes.Ldstr, "Meow() is the meow method of C# programs!");
il.Emit(OpCodes.Ldstr, "eow");
il.Emit(OpCodes.Ldstr, "ain");
il.EmitCall(OpCodes.Call, typeof(string).GetMethod("Replace", new[] { typeof(string), typeof(string) }), null);
il.EmitCall(OpCodes.Call, typeof(Console).GetMethod("Write", new[] { typeof(string) }), null);
il.Emit(OpCodes.Ret);
var type = typeBuilder.CreateType();
asmBuilder.SetEntryPoint(type.GetMethods()[0]);
asmBuilder.Save("MEOW.exe");
```
Use `Environmnent.CurrentDirectory` to see where the exe was created. Run it to observe the desired output.
[](https://i.stack.imgur.com/t6t1f.png)
Resulting IL:
[](https://i.stack.imgur.com/p2c7g.png)
[Answer]
# WPF Application
1. Create a new WPF application.
[](https://i.stack.imgur.com/Tkfwz.png)
2. Replace all instances of `Main` with `Meow`
[](https://i.stack.imgur.com/jh3mL.png)
3. Rename `MainWindow.xaml` to `MeowWindow.xaml`. This will automatically rename `MainWindow.xaml.cs` to `MeowWindow.xaml.cs`.
[](https://i.stack.imgur.com/HA4Fu.png)
4. In project properties, change the Output type to `Console Application` so the console is created.
[](https://i.stack.imgur.com/jKSPa.png)
5. Add console write for the desired output string in your `MeowWindow` constructor
[](https://i.stack.imgur.com/70rJs.png)
6. Ctrl+Shift+F to confirm there's no `main` anywhere in the source directory.
[](https://i.stack.imgur.com/xoeKZ.png)
7. F5 / compile and run.
[](https://i.stack.imgur.com/YKz9R.png)
### How it works
For WPF applications, Visual Studio generates `obj\Debug\App.g.cs` which contains the `Main` method. The generated `Main` creates an instance of your WPF app and starts it.
[Answer]
## Just as a reference
My idea was similar to "milk"'s second idea:
Find a way to let the IDE execute code and write an executable to the disk.
I explicitly mentioned Windows and Linux binaries because I thought about writing the binary .EXE file using `System.IO.File.WriteAllBytes()` so it would not neccessarily be a .NET EXE file.
My problem was that VS Express 2010 seems not to have an interactive console so I had to find a replacement for that - I found the following:
Create a DLL project with a dialog window and a custom control; compile the project and add the custom control to the dialog window. The dialog window editor will then call the code of the custom control - and in this code you may write the .EXE file to the disk...
[Answer]
I had to break the rules because I used vim with csc...
```
class C {
static void \u004d\u0061\u0069\u006e(){
Syste\u006d.Co\u006esole.Write("\u004d\u0061\u0069\u006e() is the \u006d\u0061\u0069\u006e \u006dethod of C# progra\u006ds!");
}
}
```
] |
[Question]
[
*This challenge is the first in a two-challenge series about Repetition. The second will be up soon.*
In a language called Repetition (something I just made up), there consists an infinite string of `12345678901234567890...`, with `1234567890` repeating forever.
The following syntax is available to output numbers:
* `+-*/`: This inserts the operator into the string of repeating digits.
+ Examples:
- `+` -> `1+2` = `3` (The `+` inserts a `+` between `1` and `2`)
- `+*` -> `1+2*3` = `1+6` = `7` (Same as above, except two operators are used now)
- `/` -> `1/2` = `0` (Repetition uses integer division)
- `//` -> `1/2/3` = `0/3` = `0` (Repetition uses "left association" with multiple subtractions and divisions)
+ Each operator is inserted so that it has one digit to its left, unless there are `c`'s (see below).
* `c`: Concatenates with the next digit in the string.
+ Examples:
- `c+` -> `12+3` = `15` (The `c` "continues" the `1` and concatenates it with the next digit, `2`, to form `12`)
- `+c` -> `1+23` = `24`
- `ccc` -> `1234`
* `()`: Brackets for processing numbers.
+ Examples:
- `(c+)*` -> `(12+3)*4` = `15*4` = `60` (Repetition uses the order of operations)
- `(c+)/c` -> `(12+3)/45` = `15/45` = `0`
- `(cc+c)/` -> `(123+45)/6` = `168/6` = `28`
* `s`: Skip a number (removes the number from the infinite string).
+ `s+` -> `2+3` = `5` (`s` skips `1`)
+ `csc` -> `124` (The first `c` concats `1` and `2`, the `s` skips `3`, and the final `c` concats `12` to `4`)
+ `+s+` -> `7` (The first `+` adds `1` and `2` to make `3`, `s` skips `3`, and the final `+` adds `3` to `4` to make `7`)
+ `cs*(++)` -> `12*(4+5+6)` = `12*15` = `180`
In the examples above, only a finite amount of digits in the infinite string are used. The number of digits used is equivalent to `number of operators, concats and skips + 1`.
Your task is, when given a string of Repetition code, output the result.
Examples of input and output are:
```
++ -> 6
- -> -1
(-)* -> -3
cscc -> 1245
(cc+c)/ -> 28
cc+c/ -> 130
cs*(++) -> 180
```
This is code golf, so shortest code in bytes wins!
## Specs:
* You are guaranteed that the result will never go above `2^31-1`.
* You are also guaranteed that the input will only consist of the symbols `+-*/cs()`.
* An empty program will output `1`.
[Answer]
# JavaScript (ES6), 110 bytes
```
s=>eval((" "+s)[R='replace'](/[^\)](?!\()/g,x=>x+i++%10,i=1)[R](/c| (\ds)+|s\d/g,"")[R](/\d+\/\d+/g,"($&|0)"))
```
Very simple, but integer division adds 25 bytes. For some reason a regex in JS can't match both the beginning of a string and the first character, so that adds a few bytes as well.
### How it works
1. Prepend a space to the input.
2. Append the next digit to each character (except `)`) that isn't immediately before a `(`.
3. Remove each `c`, a digit + `s` at the beginning (`1s2` -> `2`), and each `s` + a digit (`3s4` -> `3`).
4. Turn each division operation into int-division (`1/2` -> `(1/2|0)`).
5. Evaluate and return.
[Answer]
## Batch, 332 bytes
```
@echo off
set s=
set e=
set d=
set r=
set/ps=
:d
set/ad=-~d%%10
:l
if "%s%"=="" goto g
set c=%s:~0,1%
set s=%s:~1%
if %c%==( set e=%e%(&goto l
if %c%==) set r=%r%)&goto l
if %c%==s goto d
if %c%==c set c=
if "%r%"=="" set/ar=d,d=-~d%%10
set e=%e%%r%%c%
set/ar=d
goto d
:g
if "%r%"=="" set/ar=d
cmd/cset/a%e%%r%
```
The behaviour of `s` makes this very awkward. (Maybe `cs` should evaluate to `13` and `-s` to `-2`?) Variables:
* `s` input string (explicitly blanked out because set/p doesn't change the variable if you don't input anything)
* `e` partial expression in normal integer arithmetic (which we can pass to `set/a` as a form of `eval`)
* `d` next digit from the infinite string of digits
* `r` right hand side of latest operator. We can't concatenate this immediately because `(` needs to come first, but we need to store it so that `s` won't increment it. Fortunately it does end up making the handling of `)` slightly easier.
* `c` current character.
] |
[Question]
[
Inspired by [**this answer**](https://math.stackexchange.com/a/1686299/206300) (emphasis mine):
>
> We will play a game. Suppose you have some number ***x***. You start with ***x*** and then you can add, subtract, multiply, or divide by any integer, except zero. You can also multiply by ***x***. You can do these things as many times as you want. If the total becomes zero, you win.
>
>
> For example, suppose ***x*** is 2/3. Multiply by 3, then subtract 2. The result is zero. You win!
>
>
> Suppose ***x*** is 7^(1/3). Multiply by ***x*** , then by ***x*** again, then subtract 7. You win!
>
>
> Suppose ***x*** is √2+√3. Here it's not easy to see how to win. But it turns out that if you multiply by ***x***, subtract 10, multiply by ***x*** twice, and add 1, then you win. (This is not supposed to be obvious; you can try it with your calculator.)
>
>
> But if you start with ***x***=π, you cannot win. There is no way to get from π to 0 if you add, subtract, multiply, or divide by integers, or multiply by π, no matter how many steps you take. (This is also not supposed to be obvious. It is a very tricky thing!)
>
>
>
> >
> > **Numbers like √2+√3 from which you can win are called algebraic**. Numbers like π with which you can't win are called transcendental.
> >
> >
> >
>
>
> Why is this interesting? Each algebraic number is related arithmetically to the integers, and the winning moves in the game show you how so. The path to zero might be long and complicated, but each step is simple and there is a path. But transcendental numbers are fundamentally different: they are not arithmetically related to the integers via simple steps.
>
>
>
---
Essentially, you will use the steps used in the question quoted above to "win" the game for given input.
Given a real, algebraic constant `x`, convert the number to zero by using the following allowed operations:
* Add or Subtract an integer.
* Multiply or Divide by a non-zero integer.
* Multiply by the original constant `x`.
Input is a string that may contain integers, addition, subtraction, multiplication, division, exponentiation (your choice of `**` or `^`, exponents are used to represent roots), and parentheses. Spaces in the input are optional, but not in the output. You should output the steps necessary to obtain a result of zero, so multiplying by `7` as one step would be output as `*7`. A trailing space and/or newline is allowed.
### Examples
```
0 -> +0 (or any other valid, or empty)
5/7 + 42 -> -42 *7 -5 (or shorter: *7 -299)
2^(1/3) -> *x *x -2
5*(3**(1/4)) -> *x *x *x -1875
2^(1/2)+3^(1/2) -> *x -10 *x *x +1
```
Shortest code wins.
[Answer]
# [SageMath](http://www.sagemath.org/), 108 bytes
```
def f(s):p=map('{:+} '.format,numerator(minpoly(sage_eval(s)/1)));return'*'+p[-1][1:]+'*x '.join(p[-2::-1])
```
[Try it on SageMathCell](http://sagecell.sagemath.org/?z=eJxljcsKwjAQRfeC_5DdZBK1Jq0IEb-kVAmYSqR5kKaiiP9uwI3F1WXOnJl7MT3p6YgqHp2OFF6Kvwls-pCczis_OZN0Dok662MYnnTUV3M2dz2Um0og4iGZPCUPDHhs16Jrheo4sEd5cgvW0wKlUmWBy0VM1udSB1v4nXbVnnDSyBmUJyqqGuciozVjhTeI_7JEXn8T8ANcXjsl&lang=sage).
Explanation:
Evaluate the string symbolically as an algebraic number (`sage_eval()`). Every algebraic number is a zero of some polynomial *a*[0] + *a*[1] *x*^1 + *a*[2] *x*^2 + ⋯ + *a*[n] *x*^*n* with rational coefficients *a*[0], …, *a*[*n*] (`minpoly()`). Multiply all the coefficients by their common denominator to turn them into integers (`numerator()`), then write this polynomial in the desired output format,
```
*a[n] +a[n-1] *x +a[n-2] *x … *x +a[1] *x +a[0]
```
### SageMath, 102 bytes, almost
```
lambda s:(lambda a,*p:'*%d'%a+'*x'.join(map(' {:+} '.format,p)))(*numerator(minpoly(1/sage_eval(s))))
```
This works for all inputs *except* 0, because a polynomial for 1/*α* is a polynomial for *α* with the coefficients reversed. :-(
[Answer]
## Mathematica, ~~194~~ ~~224~~ 192 bytes
```
""<>Cases[HornerForm@MinimalPolynomial[ToExpression@#,x]//.{Times->t,x^a_:>Fold[#2~t~#&,x~Table~a],a_~t~b_~t~c_:>a~t~t[b,c]},a_~b_~_:>{b/.t:>"*"/.Plus:>If[a>0,"+",""],ToString@a," "},{0,∞}]&
```
Here `∞` is the three byte unicode character representing infinity in Mathematica.
Since input is a string, 13 bytes are lost on `ToExpression@` which interprets the string input as an algebraic expression.
```
HornerForm@MinimalPolynomial[2^(1/2)+3^(1/2), x]
```
Would return something like
```
1 + x^2 (-10 + x^2)
```
The next replacement rule massages this into something that is structurally like
```
1 + (x * (x * (-10 + (x * (x)))))
```
This Horner form can be visualized like a tree:
[](https://i.stack.imgur.com/zoVGk.png)
We, by the rules of OP start out with the deepest leaf on the right.
`Cases` goes through the expression, starting at the deepest level, taking each parent node and its left leaf and assembling this into a table such as
```
"*" "x" " "
"" "-10" " "
"*" "x" " "
"*" "x" " "
"+" "1" " "
```
`""<>` concatenates everything with the empty string.
] |
[Question]
[
Children are very good at classifying objects and counting them. Computers seem to have more trouble. This is a simplified version of this problem. Can you write a small program that can classify and count objects in an image?
The problem: Given an image containing one or more circles and rectangles, return 2 integers
with the count of circles and count of rectangles.
## Rules
* The input image will be black figures on a white background in any bitmap
format you choose.
* The image width and height will be between 100 and 1000 pixels.
* Figures will be fully contained within the image.
* Figures will have 1 pixel line width.
* Images will not use anti-aliasing. They will be black on white only.
* Figures may touch, intersect, or be inside another figure.
* Intersecting figures will have a maximum of 4 common pixels.
* Circles will have a diameter of 20 pixels or more.
* Rectangle sides will be 10 or more pixels long.
* You may not use any built-ins or libraries that recognize shapes, or any other
function that makes this challenge trivial.
* Return or print 2 integers with the counts of circles and rectangles.
## Example 1
[](https://i.stack.imgur.com/qnIFk.png)
Answer: 3 4
## Example 2:
[](https://i.stack.imgur.com/HV9k3.png)
Answer: 4 13
This is a code golf challenge, so the shortest program or function in each language will win.
[Answer]
# PHP – 355 bytes
The byte count doesn't include `'<image-url>'`.
```
<?php
m('<image-url>');function m($f){$i=imagecreatefrompng($f);$r=f($i,17);$c=f($i,9);echo($c-$r).' '.$r."\n";}function f($i,$k){$w=imagesx($i);$h=imagesy($i);$r=0;for($y=0;$y<$h;$y++)for($x=0;$x<$w;$x++)if(!imagecolorat($i,$x,$y))$r+=g($i,$x,$y,$w,$k);return$r;}function g($i,&$x,$y,$w,$k){$l=$x;while(!imagecolorat($i,$x,$y)&&$x<$w)$x++;return($x-$l>$k)?1/2:0;}
```
In the two test cases, the URLs I used are `https://i.stack.imgur.com/qnIFk.png` and `https://i.stack.imgur.com/HV9k3.png`.
Counts horizontal lines and divides by two to get the number of shapes. Relies on the observation that circles have shorter horizontal segments and rectangles have longer horizontal segments.
Admitted hack, not guaranteed to work for anything other than the test cases!
I tried rotating the images by ± 45° and detecting for horizontal lines. This would be equivalent to checking for diagonal lines and would pick up the circles better, but I couldn't find an interpolation algorithm which left clean enough edges to work with. For example, they might smudge a line into two rows of pixels and mess up the count.
] |
[Question]
[
Inspired by [this little game](http://lh5.ggpht.com/-uptxy9lVSd4/UYBVI_4FfnI/AAAAAAAADTE/EtXviYI-UCo/s640/4_1367364793905.png).
## Challenge
Given as input the initial position of a grid (always 5x5), like this:
```
-ABCD
-A---
---C-
---BD
--E-E
```
You need to connect the letters (same letters all together), removing all empty `-` spaces. The letters will be always `A,B,C,D and E`.
Every pair of letters must be connected by a single unbranched line that can bend at right angles (using the very same letter to depict the line).
The input is guaranteed to have each starting letter exactly 2 times and it will always have all starting letters A-E.
The input can be read from stdin, or one only string as arg to some function, or even an array/matriz/list of chars, the most convinient way to your coding-language.
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") shortest code in bytes wins!
---
## Example
There is not only one solution to each problem, but the rules apply to all (no empty space and no separated letters). And the input is guaranteed to have at least one correct output.
Let's start connecting the letters A:
```
AABCD
AA---
AA-C-
AA-BD
AAE-E
```
Now, connecting the letters B:
```
AABCD
AAB--
AABC-
AABBD
AAE-E
```
Now, connecting the letters C:
```
AABCD
AABC-
AABC-
AABBD
AAE-E
```
Now, connecting the letters D:
```
AABCD
AABCD
AABCD
AABBD
AAE-E
```
And, finally the letters E:
```
AABCD
AABCD
AABCD
AABBD
AAEEE
```
## Another Samples
```
input:
E--E-
BB-C-
AD---
---C-
AD---
output:
EEEEE
BBECE
ADECE
ADECE
ADEEE
input:
A----
---B-
-C-C-
-D-D-
BE-EA
output:
AAAAA
BBBBA
BCCCA
BDDDA
BEEEA
```
[Answer]
# Perl, ~~130~~ ~~128~~ 127 bytes
Includes +4 for `-n0` (program does not work from the commandline so `-` and space are counted too)
Call with the input on STDIN:
```
perl -n0 connectletters.pl
E--E-
BB-C-
AD---
---C-
AD---
```
Teminate with `^D` or `^Z` or whatever closes STDIN on your system
`connectletters.pl`:
```
/-/?map{$_="$`$_$'";s%\pL%$_="$`0$'";1while do{s/[$&-](.{5}|)0|0(.{5}|)[$&-]/0$+0/s};/$&/||$&%eg;!/1/&&do$0}A..E:exit!print
```
[Answer]
# Python3, 445 bytes
```
E=enumerate
def S(d,b):l=d.pop(T:=[*{*d}-{'-'}][0]);return[(T,*l[0],*({*l}-{l[0]}),{**d},eval(str(b)))]
def f(b):
d={}
for x,r in E(b):
for y,v in E(r):d[v]=d.get(v,[])+[(x,y)]
q=S(d,b)
while q:
C,x,y,e,d,b=q.pop(0)
for X,Y in[(0,1),(0,-1),(1,0),(-1,0)]:
if(T:=(x+X,y+Y))in d['-']:B=eval(str(b));B[T[0]][T[1]]=C;q+=[(C,*T,e,{**d,'-':{*d['-']}-{T}},B)]
elif T==e:
if len(d)==1 and not d['-']:return b
if len(d)>1:q+=S(d,b)
```
[Try it online!](https://tio.run/##dVJNj9owED3Xv2LEBTtMEIFLFeRKJNBjL81hV661AsXZTZV1gpOlIJTfTscJ1e4eGivj8cybNx92c@learv62rjbbSeNfXs1bt8ZlpsCfvIcDyKuZD5v6oZnsVTBNcj78DoNp71WCy3WznRvziqeYVCRAQN@DSpC@EMv8BoQHs1pX/G2c/wghNADd0F6zCCX155BUTs4o4PSwm60D6YLnkaTE3GuTprqeDYdP6HSYqb4GS9EBkc51sngz0tZGTj68BTJiwbJIY9D9QtxZ33AR2JVfIGRQJKh3yJckAz9pn08lIXvl59nD3iZPQpBdeSK2tZxIj@2s05URq1qkpHWMl0fZ1LxFIOMsvvukYJimtoQTIPJ@h4TXzeAqcoCMinNkJFSQmUsz4WUEextDrbu/iUdxwyHz8BvUUzpxvZvbQQSJpMJCzdJuiUZhiGjPx1kQpZwF@6YR7TLO3TnbSxJPGizfQ8YdY9g7QqkVzzdyEQyHVi3tFhCpJsR6u@1q58O9d7lvKVr/HIvW6mg1MPwS3@hRVl1xvEftTUI7bxtqrLj01926h/HwPL9U7h3zX/XpeWv@4ZPRx3pCX1IRh9jjSttxyk4otN4oOkFy4V4dy3/71p5jttf)
] |
[Question]
[
Last year, there was a very popular challenge to [create an image containing every 24-bit RGB colour](https://codegolf.stackexchange.com/questions/22144/images-with-all-colors).
My challenge is to create a smooth animation (24 frames/s say), where the colour of every pixel of every frame is unique. I will also allow duplication of colours as long as *every colour appears the same number of times (greater than 0)*, since otherwise the animation will have to be short, or the frames small.
[I have produced some examples here](https://swarbrickjones.wordpress.com/2015/09/11/all-24-bit-rgb-colours-in-one-animation/), based on the winning solution to the 2d version. Unfortunately, it seems you can't embed videos, so links will have to do.
[Answer]
# Mathematica
This is a straightforward implementation with each rgb colour occupying an intersection in a 256 by 256 by 256 unit grid.
The jerkiness seems to be an artefact of the video, not an error in the data, which should be exact.
red values increase downwards, green values increase rightwards, and blue values increase by frame.
Perhaps I'll jumble things up later.
```
f@b_ := Image@Table[{r, g, b}/255, {r, 0, 255}, {g, 0, 255}]
Export["c.mov", Table[f@b, {b, 0, 255}]]
```
QuickTime [clip](https://vimeo.com/139074326)
[Answer]
# PHP (+ HTML) + JavaScript
**Part 1**
generate 256 images with distinct red values from 0 to 255;
green value=row index, blue value=column index
```
for($r=$h=256;$r--;){$i=imagecreatetruecolor($g=$h,$h);for(;$g--;)for($b=$h;$b--;)imagesetpixel($i,$g,$b,imagecolorallocate($i,$r,$g,$b));imagepng($i,"$r.png");imagedestroy($i);}
```
*Note*: Depending on Your PHP implementation, this may throw an internal server error.
If it does, take the lowest number of the images that already have been created, insert `<number>,` after `$r=` and run again.
**Part 2**
loop through these images from 0 to 255 and back (0 and 255 taking 2 frames each)
```
<img><script>r=d=0;setInterval(()=>{document.images[0].src=r+".png",(d?!r--:(++r)>=256)?r-=(d=!d)?1:-1:r},40);</script>
```
] |
[Question]
[
A [tree](https://en.wikipedia.org/wiki/Tree_(graph_theory)) is a connected, undirected graph with no cycles. Your task is to count how many distinct trees there are with a given number of vertices.
Two trees are considered distinct if they are not [isomorphic](https://en.wikipedia.org/wiki/Graph_isomorphism). Two graphs are isomorphic if their respective vertices can be paired up in such a way that there is an edge between two vertices in one graph if and only if there is an edge between the vertices paired to those vertices in the other graph. For a more complete description, see the link above.
To see what all of the distinct trees of sizes 1 to 6 look like, take a look [here](http://mathworld.wolfram.com/images/eps-gif/Trees_600.gif).
The series you are trying to output is [A000055](http://oeis.org/A000055) at the OEIS.
**Restriction**: Your solution must take in the range of minutes or less to run on the input `6`. This is not intended to eliminate exponential time algorithms, but it is intended to eliminate doubly-exponential time algorithms, such as brute forcing over all edge sets.
**Input:** Any non-negative integer.
Input may be by any standard means, including STDIN, command line parameter, function input, etc.
**Output:** The number of distinct trees with as many vertices as the input.
Output may be by any standard means, including STDOUT, function return, etc.
**Examples:** `0, 1, 2, 3, 4, 5, 6, 7` should return `1, 1, 1, 1, 2, 3, 6, 11`.
**Scoring:** Code golf, by bytes. May the shortest code win!
[Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) forbidden.
[Answer]
## CJam (69 bytes)
```
]qi:X,{1e|,:):N{N\f{1$%!*}W$.*:+}%1$W%.*:+N,/+}/W\+_1,*X=\_W%.*:+-Y/z
```
[Online demo](http://cjam.aditsu.net/#code=%5Dqi%3AX%2C%7B1e%7C%2C%3A)%3AN%7BN%5Cf%7B1%24%25!*%7DW%24.*%3A%2B%7D%251%24W%25.*%3A%2BN%2C%2F%2B%7D%2FW%5C%2B_1%2C*X%3D%5C_W%25.*%3A%2B-Y%2Fz&input=8)
### Explanation
The basic idea is to implement the generating function described in OEIS. The input \$0\$ is a nasty special case, but the final tweaks I made ended up producing \$-1\$ for that case, so the \$z\$ (for absolute value) tidies it up. That's the weirdest trick in here.
`.*:+` is repeated three times, and looks like it could save a byte if extracted as `{.*:+}:F~`. However, this breaks with the special case \$0\$, because it doesn't execute the outer loop at all.
---
We use the auxiliary generating function for [A000081](http://oeis.org/A000081), whose terms have the recurrence
```
a[0] = 0
a[1] = 1
For n >= 1, a[n+1] = (sum_{k=1}^n a[n-k+1] * sum_{d|k} d * a[d]) / n
```
I'm sure some languages have built-ins for the inverse Möbius transform \$\sum\_{d\mid k} d \times a[d]\$, but CJam doesn't; the best approach I've found is to build an array mapping \$d\$ to `k % d == 0 ? d : 0` and then do a pointwise multiplication with \$a\$ using `.*`. Note that here it is convenient to have built up \$a\$ starting at index 1, because we want to avoid division by zero when setting up the weights. Note also that if the two arrays supplied to the pointwise operation are not the same length then the values from the longer one are left untouched: therefore we have to either take the first \$k\$ terms of \$a\$ or make the array of weights go up to \$n\$. The latter seems shorter. So this inverse Möbius transform accounts for `N\f{1$%!*}W$.*:+`
If we call the result of the inverse Möbius transform `M`, we now have $$a[n+1] = \frac{1}{n} \sum\_{k=1}^n a[n-k+1] \times M[k]$$
The numerator is obviously a term from a convolution, so we can handle it by reversing either a copy of \$a\$ or \$M\$ and then taking a pointwise multiplication and summing. Again, our index varies from \$1\$ to \$n\$, and in addition we want to pair up indices which sum to \$n + 1\$, so it's again convenient to index \$a\$ from 1 rather than 0. We've now accounted for
```
qi:X,{ ,:):N{N\f{1$%!*}W$.*:+}%1$W%.*:+N,/+}/
```
The point of the auxiliary generating function is given by the formula section of A000055:
>
>
> ```
> G.f.: A(x) = 1 + T(x) - T^2(x)/2 + T(x^2)/2,
> where T(x) = x + x^2 + 2*x^3 + ... is the g.f. for A000081.
>
> ```
>
>
In terms of \$a\$, this means that the output we seek is $$[x = 0] + a[x] + \frac{1}{2}\left(a[x/2] - \sum\_{i=0}^n a[i] \times a[n-i]\right)$$
where for \$a[x/2]\$ with odd \$x\$ we get 0. The shortest way I've found to do that is to inflate with zeroes (`1,*`) and then take the Xth element (`X=`).
Note that the sum is yet another convolution, but this time it's convenient to index from 0. The obvious solution is `0\+`, but there is a nice little optimisation here. Since \$a[0] = 0\$, two terms of the convolution are guaranteed to be zero. We could take this as an opportunity to index from 1, but the special case \$X = 0\$ gets ugly. If we instead do `W\+`, the convolution gives us \$-2a[x] + \sum\_{i=0}^n a[i] \times a[n-i]\$ and after subtraction and division by \$2\$ we've handled the \$a[x]\$ term outside the sum as well.
So we've explained
```
qi:X,{ ,:):N{N\f{1$%!*}W$.*:+}%1$W%.*:+N,/+}/W\+_1,*X=\_W%.*:+-Y/
```
The remaining details relate to the special case. I originally followed the recurrence more strictly by starting out with `1]` and iterating from \$N = 1\$ with
```
1]qi:X,1>{ ... }/
```
The result when \$X = 0\$ is that we compute \$a\$ as `[-1 1]`: one term more than we need. The inflation and convolution wind up giving a result of \$0\$. (Perhaps better than we deserve - it's what we should have, because we haven't done anything about the term \$[x = 0]\$). So we fix it up for three chars either as a final `X!+` or using the standard "fallback" technique as `1e|`.
To get the "right" length of \$a\$ we need to avoid supplying that initial \$1\$, and instead to produce it from the main loop with \$N = 0\$. A completely straightforward
```
]qi:X,{ ... /+}/
```
obviously gives division by zero. But if we try
```
]qi:X,{1e| ... /+}/
```
then it works. We get
```
e# Stack: [] 0
1e| e# Stack: [] 1
,:):N e# Stack: [] [1]
{ e# We only execute this loop once
N\f{1$%!*} e# 1 divides 1, so stack: [] [1]
W$.* e# Remember: if the two arrays supplied to the pointwise operation
e# are not the same length then the values from the longer one are
e# left untouched. Stack: [] [1]
:+ e# Fold over a singleton. Stack: [] 1
}% e# And that was a map, so stack: [] [1]
1$W%.*:+ e# Another [1] [] .*:+, giving the same result: 1
N,/ e# 1 / 1 = 1
+ e# And we append 1 to a giving [1]
```
which produces exactly the value we require.
Now if \$X = 0\$ that main loop never executes, so after we hack in a \$-1\$ at the bottom we get `[-1]`. We end up computing \$(-1 - \frac12(-1 \times -1)) = -1\$, which isn't correct. But whereas correcting \$0\$ to \$1\$ took three chars, correcting \$-1\$ to \$1\$ only takes one: `z` gives the absolute value.
[Answer]
# Pyth, 35 bytes
```
l{m`SmSSMcXdUQk2.pQusm+L,dhHGhHtQ]Y
```
[Demonstration.](https://pyth.herokuapp.com/?code=l%7Bm%60SmSSMcXdUQk2.pQusm%2BL%2CdhHGhHtQ%5DY&input=6&debug=0)
This program can be divided into two parts: First, we generate all possible trees, then we remove duplicates.
This code generates the trees: `usm+L,dhHGhHtQ]Y`. Trees are represented as a concatenated list of edges, something like this:
`[0, 1, 0, 2, 2, 3, 1, 4]`
Each number stands for a vertex, and every two numbers is an edge. It is built by repeatedly adding an edge beteen each possible vertex that already exists and one which is newly created, and adding this on to each possible tree from the previous step. This generates all possible trees, since all trees can be generated by repeatedly adding one vertex and an edge from it to the existing tree. However, isomorphic trees will be created.
Next, for each tree, we perform every possible relabeling. This is done by mapping over all possible permutations of the vertices (`m ... .pQ`), and then transating the tree from the standard ordering to that ordering, with `XdUQk`. `d` is the tree, `k` is the permutation.
Then, we separate the edges into separate lists with `c ... 2`, sort the vertices within each edge with `SM`, sort the edges within the tree with `S`, giving a cannonical representation of each tree. These two steps are the code `mSSMcXdUQk2.pQ`.
Now, we have a list of lists composed of every possible relabeling of each tree. We sort these lists with `S`. Any two isomorphic trees must be able to be relabelled into the group of trees. Using this fact, we convert each list to a string with ```, then form the set of those lists with `{`, and output its length with `l`.
] |
[Question]
[
This is a screenshot of some text typed in a text editor:

This is the same text at a larger size.

Notice how visible the [aliasing](http://en.wikipedia.org/wiki/Aliasing) is on letters with prominent diagonal strokes like `x` and `z`. This issue is a major reason why raster fonts have lost popularity to “scalable” formats like TrueType.
But maybe this isn't an inherent problem with raster fonts, just with the way scaling of them is typically implemented. Here's an alternative rendering using simple [bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation) combined with [thresholding](http://en.wikipedia.org/wiki/Thresholding_(image_processing)).

This is smoother, but not ideal. Diagonal strokes are still bumpy, and curved letters like `c` and `o` are still polygons. This is especially noticeable at large sizes.
So is there a better way?
# The task
Write a program that takes three command-line arguments.
```
resize INPUT_FILE OUTPUT_FILE SCALE_FACTOR
```
where
* INPUT\_FILE is the name of the input file, which is assumed to be an image file containing black text on a white background. You may use any mainstream *raster* image format (PNG, BMP, etc.) that's convenient.
* OUTPUT\_FILE is the name of the output file. It can be either a raster or vector image format. You may introduce color if you're doing some ClearType-like subpixel rendering.
* SCALE\_FACTOR is a positive floating-point value that indicates how much the image may be resized. Given an *x* × *y* px input file and scaling factor *s*, the output will have a size of *sx* × *sy* px (rounded to integers).
You may use a third-pary open-source image processing library.
In addition to your code, include sample outputs of your program at scale factors of **1.333, 1.5, 2, 3, and 4** using my first image as input. You may also try it with other fonts, including proportionally-spaced ones.
# Scoring
This is a popularity contest. The entry with the greatest number of upvotes minus downvotes wins. In case of an exact tie, the earlier entry wins.
**Edit**: Deadline extended due to lack of entries. TBA.
Voters are encouraged to judge based primarily on how good the output images look, and secondarily on the simplicity/elegance of the algorithm.
[Answer]
# Ruby, with RMagick
The algorithm is very simple—find patterns of pixels that look like this:
```
####
####
####
####
########
########
########
########
```
and add triangles to make them look like this:
```
####
#####
######
#######
########
########
########
########
```
Code:
```
#!/usr/bin/ruby
require 'rmagick'
require 'rvg/rvg'
include Magick
img = Image.read(ARGV[0] || 'img.png').first
pixels = []
img.each_pixel{|px, x, y|
if px.red == 0 && px.green == 0 && px.blue == 0
pixels.push [x, y]
end
}
scale = ARGV[2].to_f || 5.0
rvg = RVG.new((img.columns * scale).to_i, (img.rows * scale).to_i)
.viewbox(0, 0, img.columns, img.rows) {|cnv|
# draw all regular pixels
pixels.each do |p|
cnv.rect(1, 1, p[0], p[1])
end
# now collect all 2x2 rectangles of pixels
getpx = ->x, y { !!pixels.find{|p| p[0] == x && p[1] == y } }
rects = [*0..img.columns].product([*0..img.rows]).map{|x, y|
[[x, y], [
[getpx[x, y ], getpx[x+1, y ]],
[getpx[x, y+1], getpx[x+1, y+1]]
]]
}
# WARNING: ugly code repetition ahead
# (TODO: ... fix that)
# find this pattern:
# ?X
# XO
# where X = black pixel, O = white pixel, ? = anything
rects.select{|r| r[1][0][1] && r[1][1][0] && !r[1][2][1] }
.each do |r|
x, y = r[0]
cnv.polygon x+1,y+1, x+2,y+1, x+1,y+2
end
# OX
# X?
rects.select{|r| r[1][0][1] && r[1][3][0] && !r[1][0][0] }
.each do |r|
x, y = r[0]
cnv.polygon x+1,y+1, x+0,y+1, x+1,y+0
end
# X?
# OX
rects.select{|r| r[1][0][0] && r[1][4][1] && !r[1][5][0] }
.each do |r|
x, y = r[0]
cnv.polygon x+1,y+1, x+0,y+1, x+1,y+2
end
# XO
# ?X
rects.select{|r| r[1][0][0] && r[1][6][1] && !r[1][0][1] }
.each do |r|
x, y = r[0]
cnv.polygon x+1,y+1, x+2,y+1, x+1,y+0
end
}
rvg.draw.write(ARGV[1] || 'out.png')
```
Outputs (click any to view image by itself):
1.333
[](https://i.stack.imgur.com/hPGWW.png)
1.5
[](https://i.stack.imgur.com/53On1.png)
2
[](https://i.stack.imgur.com/Tco0x.png)
3
[](https://i.stack.imgur.com/YI60G.png)
4
[](https://i.stack.imgur.com/cA7Jq.png)
] |
[Question]
[
Almost every language has a built-in function that can split a string at a given position. However, as soon as you have html tags in the string, the built-in function will not work properly.
Your task is to write a program or function which splits a string at the nth character but does not count characters of html tags and will output a valid html. The program must keep the formatting. Spaces outside the html tags may be counted or not counted, as you wish, but must be preserved. You can, however, exchange multiple consecutive spaces into a single space.
Input:
1. the string
2. the position to split at (0-based)
These can be taken as program or function arguments or can be read from the standard input.
Output:
The split string which can be returned or written to the standard output.
The input will be valid html, it won't contain any entities (such as ` `). Tags that are opened after the character limit should be omitted from the output (see the last example).
Example:
Input: `<i>test</i>`, 3
Output: `<i>tes</i>`
Input: `<strong><i>more</i> <span style="color: red">complicated</span></strong>`, 7
Output: `<strong><i>more</i> <span style="color: red">co</span></strong>`
Input: `no html`, 2
Output: `no`
Input: `<b>no</b> <i>html root</i>`, 5
Output: `<b>no</b> <i>ht</i>`
Input: `<b>no img</b><img src="test.png" />more text`, 6
Output: `<b>no img</b>`
You can use any language and the standard library of the given language. This is code golf, shortest program wins. Have fun!
[Answer]
**This answer is no longer valid with the latest rule.**
# Javascript (*ES6*) 94 91
```
f=(s,l)=>s.split(/(<[^>]+>)/).map(x=>x[0]=='<'?x:[l-->0?y:''for(y of x)].join('')).join('')
```
```
f('<strong><i>more</i> <span style="color: red">complicated</span></strong>', 7);
// '<strong><i>more</i> <span style="color: red">co</span></strong>'
```
Ungolfed:
```
f=(s,l)=>
s.split(/(<[^>]+>)/). // split string s by <*>, capture group is spliced into the array
map(x=> // map function to every item in the array
x[0]=='<'? // if first character is a <
x // don't modify the string
: // else
[ // array comprehension
for(y of x) // for every character y in x
l-->0? // if l > 0 (and decrement l)
y // character y
: // else
'' // empty string
].join('') // join characters in array
).
join('') // join all strings in array
```
[Answer]
# Rebol - 252 chars
```
c: complement charset"<>"f: func[s n][t: e: 0 to-string collect[parse s[any[(m: 0)copy w[["</"some c">"](-- t)|["<"some c"/>"]|["<"some c">"](++ t)| any c(m: 1)](if e = 0[if m = 1[w: copy/part w n n: n - length? w]keep w]if all[n <= 0 t = 0][e: 1])]]]]
```
Ungolfed with comments:
```
c: complement charset "<>"
f: func [s n] [
t: e: 0 ;; tag level (nesting) & end output flag
to-string collect [
parse s [
any [
(m: 0) ;; tag mode
copy w [
["</" some c ">" ] (-- t) ;; close tag
| ["<" some c "/>"] ;; self-closing / void elements
| ["<" some c ">" ] (++ t) ;; open tag
| any c (m: 1) ;; text mode
] (
;; flag not set so can still output
if e = 0 [
;; in text mode - so trim text
if m = 1 [
w: copy/part w n
n: n - length? w
]
keep w
]
; if all trimmed and returned to flat tag level then end future output
if all [n <= 0 t = 0] [e: 1]
)
]
]
]
]
```
Examples in Rebol console:
```
>> f "<i>test</i>" 3
== "<i>tes</i>"
>> f {<strong><i>more</i> <span style="color: red">complicated</span></strong>} 7
== {<strong><i>more</i> <span style="color: red">co</span></strong>}
>> f {no html} 2
== "no"
>> f {<b>no</b> <i>html root</i>} 5
== "<b>no</b> <i>ht</i>"
>> f {<b>no img</b><img src="test.png" />more text} 6
== "<b>no img</b>"
>> f {<i>a</i><b></b>} 1
== "<i>a</i>"
>> f {<strong><i>even</i> <span style="color: red">more <b>difficult</b></span></strong>} 14
== {<strong><i>even</i> <span style="color: red">more <b>diff</b></span></strong>}
>> f {<strong><i>even</i> <span style="color: red">more <b>difficult</b></span></strong>} 3
== {<strong><i>eve</i><span style="color: red"><b></b></span></strong>}
```
[Answer]
Ruby... Very unrubylike with loops
```
def split(str,n)
i = current = 0
return_str = ""
while i < n
if str[current] == "<"
while str[current] != ">"
return_str.concat str[current]
current += 1
end
return_str.concat str[current]
current += 1
else
return_str.concat str[current]
i += 1
current += 1
end
end
while current < str.length
if str[current] == "<"
while str[current] != ">"
return_str.concat str[current]
current += 1
end
return_str.concat str[current]
current += 1
end
current += 1
end
return_str + str[current..-1]
end
```
[Answer]
**(IE) JS - 135**
`function f(t,n){b=document.body;b.innerHTML=t;r=b.createTextRange();r.moveStart("character",n);r.select();r.execCommand('cut');return b.innerHTML}`
Now I feel dirty. But need to start removing all those chars...
```
function f(t,n)
{b=document.body;b.innerHTML=t;r=b.createTextRange();r.collapse();r.moveEnd("character",n);
r.select();return r.htmlText}
```
Disclaimer:
* run in IE console
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 7 years ago.
[Improve this question](/posts/13003/edit)
## Statement
The task is to synthesize sound (one note played) of some musical instrument (of your choice) using function in some general purpose programming language (of your choice).
There are two goals:
* Quality of the resulting sound. It should resemble the real instrument as fine as possible;
* Minimality. Keeping the code under 1500 bytes is adviced (less if there's only basic sound generation).
Only generation function need to be provided, boilerplate is not counted for the score.
Unfortunately no score can be calculated for the sound fidelity, so there can't be strict rules.
Rules:
* No dependance on sample libraries, specialized music generation things;
* No downloading from network or trying to use microphone or audio card's MIDI or something too external like this;
* The code size measure unit is bytes. File can get created in current directory. Pre-existing files (coefficient tables, etc) may exist, but their content is added to the score + they must by opened by name.
* The boilerplate code (not counted to score) receives array (list) of signed integers and only deals with outputting them.
* Output format is signed little endian 16-bit words, 44100 samples per seconds, with optional WAV header. No trying to output compressed audio instead of plain wav;
* Please choose different instruments for synthesizing (or other quality vs code size category for the instrument); but don't initially tell what are you simulating - let other users to guess in comments;
* Electronic instruments are discouraged;
* Drum is an instrument. Human voice is an instrument.
## Boilerplates
Here are boilerplates for some languages. You can write similar boiler plate for your language as well. Commented out "g" function is just for a demo (1 second 440 Hz sine tone).
C:
```
//#!/usr/bin/tcc -run
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
/*
void g(signed short *array, int* length) {
*length = 44100;
int i;
for(i=0; i<44100; ++i) array[i]=10000*sin(i*2.0*3.14159265358979323*440.0/44100.0);
}
*/
// define your g here
signed short array[44100*100];
int main(int argc, char* argv[]) {
int size=0;
memset(array,0,sizeof array);
// i(array); // you may uncomment and implement some initialization
g(array, &size);
fwrite("RIFFH\x00\x00\x00WAVEfmt\x20\x12\x00\x00\x00\x01\x00\x01\x00\x44\xac\x00\x00\x88X\x01\x00\x02\x00\x10\x00\x00\x00LIST\x1a\x00\x00\x00INFOISFT\x0e\x00\x00\x00GolfNote\0\0\0\0\0\0data\x00\xff\xff\xff", 1, 80, stdout);
fwrite(array, 1, size*sizeof(signed short), stdout);
return 0;
}
```
Python 2:
```
#!/usr/bin/env python
import os
import re
import sys
import math
import struct
import array
#def g():
# return [int(10000*math.sin(1.0*i*2*3.141592654*440.0/44100.0)) for i in xrange(0,44100)]
# define your g here
sys.stdout.write("RIFFH\x00\x00\x00WAVEfmt\x20\x12\x00\x00\x00\x01\x00\x01\x00\x44\xac\x00\x00\x88X\x01\x00\x02\x00\x10\x00\x00\x00LIST\x1a\x00\x00\x00INFOISFT\x0e\x00\x00\x00GolfNotePy\0\0\0\0data\x00\xff\xff\xff");
array.array("h", g()).tofile(sys.stdout);
```
Perl 5:
```
#!/usr/bin/perl
#sub g() {
# return (map 10000*sin($_*3.14159265358979*2*440.0/44100.0), 0..(44100-1))
#}
# define you g here
my @a = g();
print "RIFFH\x00\x00\x00WAVEfmt\x20\x12\x00\x00\x00\x01\x00\x01\x00\x44\xac\x00\x00\x88X\x01\x00\x02\x00\x10\x00\x00\x00LIST\x1a\x00\x00\x00INFOISFT\x0e\x00\x00\x00GolfNotePl\0\0\0\0data\x00\xff\xff\xff";
print join("",map(pack("s", $_), @a));
```
Haskell:
```
#!/usr/bin/runhaskell
import qualified Data.Serialize.Put as P
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C8
import Data.Word
import Control.Monad
-- g :: [Word16]
-- g = map (\t->floor $ 10000 * sin(t*2*3.14159265358979*440/44100)) [0..44100-1]
-- insert your g here
main = do
B.putStr $ C8.pack $ "RIFFH\x00\x00\x00WAVEfmt\x20\x12\x00\x00\x00\x01\x00\x01\x00\x44\xac\x00\x00\x88X\x01\x00\x02\x00\x10\x00\x00\x00LIST\x1a\x00\x00\0INFOISFT\x0e\x00\x00\x00GolfNote\0\0\0\0\0\0data\x00\xff\xff\xff"
B.putStr $ P.runPut $ sequence_ $ map P.putWord16le g
```
## Example
Here's ungolfed C version modeled after piano sound:
```
void g(signed short *array, int* length) {
*length = 44100*5;
int i;
double overtones[]={4, 1, 0.5, 0.25, 0.125};
double freq[] = {393, 416, 376, 355, 339, 451, 555};
double freq_k[] = {40, 0.8, 1, 0.8, 0.7, 0.4, 0.25};
double corrector = 1/44100.0*2*3.14159265358979323;
double volumes_begin[] ={0, 0.025, 0.05, 0.4};
double volumes_end [] ={0.025, 0.05, 0.4, 5};
double volumes_kbegin[]={0, 1.8, 1, 0.4};
double volumes_kend [] ={1.8, 1, 0.4, 0};
for(i=0; i<44100*5; ++i) {
int j;
double volume = 0;
for(j=0; j<sizeof volumes_begin/sizeof(*volumes_begin); ++j) {
double t = i/44100.0;
if(t>=volumes_begin[j] && t<volumes_end[j]) {
volume += volumes_kbegin[j]*(volumes_end[j]-t )/(volumes_end[j]-volumes_begin[j]);
volume += volumes_kend[j] *(t-volumes_begin[j])/(volumes_end[j]-volumes_begin[j]);
}
}
int u;
for(u=0; u<sizeof freq/sizeof(*freq); ++u) {
for(j=0; j<sizeof overtones/sizeof(*overtones); ++j) {
double f = freq[u]*(j+1);
array[i] += freq_k[u]*volume*10000.0/(f)/1*overtones[j]*sin(1.0*i*corrector*f);
}
}
}
}
```
It scores approximately 1330 bytes and provides poor/mediocre quality.
[Answer]
## Java
My boilerplate plays the sound. I could golf `g()` a bit more, but it's currently at 273 chars which is well under 1500. I originally wrote this for 16kHz for a 4kB game and had to tweak the constants a bit to get the right tonal qualities at 44.1kHz playback, but I'm reasonably happy with it.
```
import java.io.*;
import javax.sound.sampled.*;
public class codegolf13003 {
byte[]g(){byte[]d=new byte[88000];int r=1,R=1103515247,b[]=new int[650],i,o,s,y;for(i=0;i<b.length;r*=R)b[i++]=0x4000+((r>>16)&0x3fff);for(i=o=0;i<d.length;o=s){s=(o+1)%b.length;y=(b[o]+b[s])/2*((r&0x10000)<1?-1:1);r*=R;d[i++]=(byte)(b[o]=y);d[i++]=(byte)(y>>8);}return d;}
public static void main(String[] args) throws Exception {
byte[] data = new codegolf13003().g();
ByteArrayInputStream bais = new ByteArrayInputStream(data);
AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100, 16, 1, 2, 44100, false/*LE*/);
AudioInputStream stream = new AudioInputStream(bais, format, data.length / 2);
new Previewer().preview(stream);
}
static class Previewer implements LineListener {
Clip clip;
public void preview(AudioInputStream ais) throws Exception {
AudioFormat audioFormat = ais.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, audioFormat);
clip = (Clip)AudioSystem.getLine(info);
clip.addLineListener(this);
clip.open(ais);
clip.start();
while (true) Thread.sleep(50); // Avoid early exit of program
}
public void update(LineEvent le) {
LineEvent.Type type = le.getType();
if (type == LineEvent.Type.CLOSE) {
System.exit(0);
}
else if (type == LineEvent.Type.STOP) {
clip.close();
}
}
}
}
```
Further reading: [Karplus-Strong synthesis](http://en.wikipedia.org/wiki/Karplus%E2%80%93Strong_string_synthesis).
[Answer]
## C
Here's the `g()` function, without the boilerplate.
```
void g(signed short *array, int* length)
{
short r[337];
int c, i;
*length = 44100 * 6;
for (i = 0 ; i < 337 ; ++i)
r[i] = rand();
*array = *r;
for (i = c = 1 ; i < *length ; ++i) {
array[i] = r[c];
r[c] = (r[c] + array[i - 1]) * 32555 / 65536;
c = (c + 1) % 337;
}
}
```
An interesting experiment is to play with the first loop that initializes a beginning sequence of random values. Replacing the call to `rand()` with `i*i` changes the character of the sound in a plausible way (that is, it sounds like the synthesis is imitating a different member of the same instrument family). `i*i*i` and `i*i*i*i` give other sound qualities, though each one gets closer to sounding like `rand()`. A value like `i*327584` or `i*571`, on the other hand, sounds quite different (and less like an imitation of something real).
---
Another minor variation of the same function comes even closer to another instrument, or at least it does to my ear.
```
void g(signed short *array, int* length)
{
int i;
*length = 44100 * 6;
for (i = 0 ; i < 337 ; ++i)
array[i] = rand();
for ( ; i < *length ; ++i)
array[i] = (array[i - 337] + array[i - 1]) * 32555 / 65536;
}
```
**Edited to Add:** I hadn't been treating this as a code golf question, since it's not flagged as such (beyond the 1500-char limit), but since it's been brought up in the comments, here's a golfed version of the above (96 characters):
```
g(short*a,int*n){int i=0;for(*n=1<<18;i<*n;++i)
a[i]=i>336?32555*(a[i-337]+a[i-1])/65536:rand();}
```
(I could get it down below 80 characters if I could change the function interface to use global variables.)
] |
[Question]
[
Flow Free is an addictive android game where you have to connect pairs of elements together via non-overlapping snakes and fill the entire grid. For a description, see here:
<https://play.google.com/store/apps/details?id=com.bigduckgames.flow&hl=en>
I have an ASP (answer set programming) solution which is only a couple rules and I don't think it's possible to phrase the same solution nearly as concisely as a SAT instance, but I'd be interested in being proven wrong.
Any language is fine, but I doubt it can be done concisely without running some sort of solver which is why I labeled it ASP/Prolog/SAT
Winner is fewest characters.
You may assume the problem is defined using the predicates:
```
v(V). % A vertex
a(V,W). % V and W are adjacent
c(C). % A color
s(V,C). % V is an endpoint of color C
```
Furthermore, the input satisfies
```
a(W,V) :- a(V,W) % Adjacencies are bidirectional
2{s(V,C) : v(V)}2 :- c(C). % Every color has exactly two endpoints
```
The solution predicate will be of the form
```
e(V,W,C).
```
Saying there's an edge between V and W of color C.
Edges must be bidirectional (of the same color). Each vertex must have edges to and from it of exactly one color. Endpoints have exactly one edge, all other vertices have exactly two edges. There are no loops, every snake must be traceable back to two endpoints.
Here's a sample input to test it on (5x5 Level 2 in the Regular Pack):
```
v(v11; v12; v13; v14; v15).
v(v21; v22; v23; v24; v25).
v(v31; v32; v33; v34; v35).
v(v41; v42; v43; v44; v45).
v(v51; v52; v53; v54; v55).
a(v11, v12).
a(v12, v13).
a(v13, v14).
a(v14, v15).
a(v12, v11).
a(v13, v12).
a(v14, v13).
a(v15, v14).
a(v11, v21).
a(v12, v22).
a(v13, v23).
a(v14, v24).
a(v15, v25).
a(v21, v22).
a(v22, v23).
a(v23, v24).
a(v24, v25).
a(v22, v21).
a(v23, v22).
a(v24, v23).
a(v25, v24).
a(v21, v31).
a(v22, v32).
a(v23, v33).
a(v24, v34).
a(v25, v35).
a(v21, v11).
a(v22, v12).
a(v23, v13).
a(v24, v14).
a(v25, v15).
a(v31, v32).
a(v32, v33).
a(v33, v34).
a(v34, v35).
a(v32, v31).
a(v33, v32).
a(v34, v33).
a(v35, v34).
a(v31, v41).
a(v32, v42).
a(v33, v43).
a(v34, v44).
a(v35, v45).
a(v31, v21).
a(v32, v22).
a(v33, v23).
a(v34, v24).
a(v35, v25).
a(v41, v42).
a(v42, v43).
a(v43, v44).
a(v44, v45).
a(v42, v41).
a(v43, v42).
a(v44, v43).
a(v45, v44).
a(v41, v51).
a(v42, v52).
a(v43, v53).
a(v44, v54).
a(v45, v55).
a(v41, v31).
a(v42, v32).
a(v43, v33).
a(v44, v34).
a(v45, v35).
a(v51, v52).
a(v52, v53).
a(v53, v54).
a(v54, v55).
a(v52, v51).
a(v53, v52).
a(v54, v53).
a(v55, v54).
a(v51, v41).
a(v52, v42).
a(v53, v43).
a(v54, v44).
a(v55, v45).
s(v11, yellow).
s(v45, yellow).
s(v41, blue).
s(v55, blue).
s(v51, red).
s(v43, red).
s(v42, green).
s(v33, green).
c(red; green; blue; yellow).
```
And to test the output
```
shouldbe(v33,v32,green).
shouldbe(v42,v32,green).
shouldbe(v43,v53,red).
shouldbe(v51,v52,red).
shouldbe(v55,v54,blue).
shouldbe(v41,v31,blue).
shouldbe(v45,v35,yellow).
shouldbe(v11,v12,yellow).
shouldbe(v12,v11,yellow).
shouldbe(v35,v45,yellow).
shouldbe(v31,v41,blue).
shouldbe(v54,v55,blue).
shouldbe(v52,v51,red).
shouldbe(v53,v43,red).
shouldbe(v32,v42,green).
shouldbe(v32,v33,green).
shouldbe(v53,v52,red).
shouldbe(v52,v53,red).
shouldbe(v54,v44,blue).
shouldbe(v31,v21,blue).
shouldbe(v35,v25,yellow).
shouldbe(v12,v13,yellow).
shouldbe(v13,v12,yellow).
shouldbe(v25,v35,yellow).
shouldbe(v21,v31,blue).
shouldbe(v44,v54,blue).
shouldbe(v44,v34,blue).
shouldbe(v21,v22,blue).
shouldbe(v25,v15,yellow).
shouldbe(v13,v14,yellow).
shouldbe(v14,v13,yellow).
shouldbe(v15,v25,yellow).
shouldbe(v22,v21,blue).
shouldbe(v34,v44,blue).
shouldbe(v34,v24,blue).
shouldbe(v22,v23,blue).
shouldbe(v15,v14,yellow).
shouldbe(v14,v15,yellow).
shouldbe(v23,v22,blue).
shouldbe(v24,v34,blue).
shouldbe(v24,v23,blue).
shouldbe(v23,v24,blue).
:-not e(V,W,C),shouldbe(V,W,C).
:-e(V,W,C),not shouldbe(V,W,C).
```
Also Level 21 5x5 should be the first puzzle with more than 1 solution (specifically, there are 9 solutions, not 40)
To set up level 21, set the last few lines of the input to
```
s(v55, yellow).
s(v44, yellow).
s(v15, blue).
s(v45, blue).
s(v51, red).
s(v53, red).
s(v22, green).
s(v14, green).
s(v23, orange).
s(v43, orange).
c(red; green; blue; yellow; orange).
```
[Answer]
## ASP (clingo), 180 bytes
```
{e(V,W,C):a(V,W),c(C)}.r(V):-s(V,_).r(V):-r(W),e(W,V,_).o(V):-r(V),{e(V,W,_):v(W);s(V,_)}=2.:-e(V,_,C),e(V,_,D),C!=D.:-e(V,W,C),not e(W,V,C).:-v(V),not o(V).:-s(V,C),e(V,_,D),C!=D.
```
I am new to ASP, so I was excited to find this task, even if it is somewhat old. It was nice to see there were places for variations and an opportunity for golfing which was leading to the limits of my understanding (I hope it is still correct, it seems to be).
Here is a commented version:
```
% Select some edges e(V,W,C) s.t. V and W are adjacent and C is a color.
{e(V,W,C):a(V,W),c(C)}.
% Auxilary predicates:
% A vertex is reachable from an endpoint if
% it is an endpoint ...
r(V):-s(V,_).
% ... or it has an edge to it from a reachable vertex.
r(V):-r(W),e(W,V,_).
% A vertex is okay if it is reachable and either
% is an endpoint with one edge or is not an endpoint and has two edges.
% This is golfed to: the set of edges from V and endpoints V has
% cardinality 2.
o(V):-r(V),{e(V,W,_):v(W);s(V,_)}=2.
% Constraints: We do not want ...
% edges from the same vertex with different colors:
:-e(V,_,C),e(V,_,D),C!=D.
% edges without their inverses:
:-e(V,W,C),not e(W,V,C).
% vertices that are not okay:
:-v(V),not o(V).
% edges from endpoints with the wrong color
:-s(V,C),e(V,_,D),C!=D.
% We're only interested in the e predicate:
#show e/3.
```
I don't know about different ASP solvers, but I used clingo, which in debian is contained in the gringo package.
If you have a problem in a file `prob` and my code in a file `solve`, call `clingo 0 prob solve`. For each solution, you will get the list of colored edges it uses (and all the other predicates if you use the golfed version which lacks the `#show` line). If you only want the number of solutions, add the option `-q`. If you only want to know if there is at least one solution, call without `0`.
] |
Subsets and Splits