title: Backhanded Compliments

text:
# Question
Title: Backhanded Compliments
This challenge is created in celebration of my first esoteric language, Backhand!

Backhand is a one dimensional language with a non-linear pointer flow. The pointer moves three steps at a time, only executing every third instruction.

The program `1..1..+..O..@` will add 1+1 and output 2 before terminating. The intermediate instructions are skipped, so `1<>1()+{}O[]@` is exactly the same program.

When the pointer is about to step off the end of the tape, it instead reverses direction and steps the other way, so `1.@1.O+.` is the same program. Note that it only counts the end instruction once. This allows us to compress most linear programs down, such as `1O+1@`

Your challenge here is to write a program or function that take a string, and output the instructions that would be executed if the program was interpreted like Backhand (you don't need to handle any actual Backhand instructions). You are to only output until the pointer lands on the last character of the string (at which point the execution would normally go backwards).

**But wait**, that's not all! When your program itself is interpreted in this fashion, the resulting code should output one of the below:

* `(Mostly) works`
* `Turing complete`
* `'Recreational'` (quotes can be either `'` or `"`, but not both)
* `Perfectly okay`
* `Only a few bugs`

For example, if your source code is `code 2 backhand`, then the program `ce cankb od2ahd` should output one of these phrases.

### Test cases:

```
"1  1  +  O  @"  -> "11+O@"
"1O+1@"          -> "11+O@"
"HoreWll dlo!"   -> "Hello World!"
"abcdefghijklmnopqrstuvwxyz" -> "adgjmpsvyxurolifcbehknqtwz"
"0123456789"     -> "0369"  (not "0369630369")
"@"              -> "@"
"io"             -> "io"  (Cat program in Backhand)
"!?O"            -> "!?O" (Outputs random bits forever in Backhand)
"---!---!"       -> "-!-----!"

```

And a reference program written in, of course, Backhand (~~this might be a bit buggy~~ Okay, I think I've fixed it).

### Rules.

* Standard Loopholes are forbidden
* The input of the first program will contain only printable ASCII and newlines (that is, bytes `0x20`-`0x7E` as well as 0x0A)
* You can choose whether your second program is converted from your first by bytes or by UTF-8 characters.
* Second program:
    + Case does *not* matter, so your output could be `pErFectLy OKay` if you want.
    + Any amount of trailing/leading whitespace (newline, tabs, spaces) are also okay.
    + The second program should be the same language as the first, though not necessarily the same format (program/function)
    + I'm happy to include suggestions from the comments on extra phrases (as long as they're not too short)
* As this is , your aim is to get the shortest answer for your language!
* In two weeks, I'll award a 200 bounty to the shortest Backhand answer.

# Answer
# Python 2, ~~163~~ ~~130~~ ~~127~~ ~~121~~ ~~115~~ ~~99~~ 96 bytes

```
i=input() ###
print(i+i[-2:0:-1]+i)[:len(i)*(len(i)%3%2or 3):3]

#'p lr+yi  n'ottk(ca'eyPf'er)

```

Try it online!

Outputs:

```
int #rt+-01i:n)l(%2 :
print('Perfect' + # 33o3ie*(l)]:2i(i
#(p=iu)#pni[:-+[ei(n)%r)]
'ly okay')

```
> 5 votes

# Answer
# , 187 bytes

```
 # c  a  t  (  '  P  e  r  f  e  c  t  l  y     o  k  a  y  '  )  #
g=function(x,n=nchar(x),i=c(1:n,(n-1):1,2:n),j=seq(1,3*n-2,3),k=i[j][1:which(i[j]==n)[1]])cat(substring(x,k,k),sep='')

```

Try it online!

The single space at the end is needed so that the `\n` never gets printed when the program is applied to itself.

## Explanation

### Part 1:

Ungolfed:

```
 # c  a  t  (  '  P  e  r  f  e  c  t  l  y     o  k  a  y  '  )  #
g <- function(x) {
  n <- nchar(x)                      # number of characters in string
  i <- c(1:n, (n - 1):1, 2:n)        # index: 1 to n, n-1 back to 1, 2 to n
  j <- seq(1, 3 * n - 2, 3)          # every third element of i
  k <- i[j][1:which(i[j] == n)[1]]   # the elements of i at indices j, up to the first appearance of n
  cat(substring(x, k, k), sep = "")  # extract from x the characters at indices k, and paste them together
}

```

### Part 2:

The function produces this when it acts on the entire program:

```
cat('Perfectly okay')#=ni(ncr)=1,-:2)=q,n,,i]:i(j=[]assi(k)e'

```
> 4 votes

# Answer
# 05AB1E, ~~43~~ ~~40~~ ~~38~~ 37 bytes

-2 bytes (40→38) thanks to *@Emigna*.

```
„€€Ã€„Ð€€µ'€Ý)\[ûDN3*©è  ?®IgD#<ÖNĀ*#

```

Try it online. (PS: Switch the language from **05AB1E (legacy)** to **05AB1E** for test case `0123456789`. The legacy version is faster, but it shows incorrect results for number inputs with leading zeros.)

The 'backhanded' program will become:

```
„ÃÐµÝ[N© I#N#

```

Which will output `perfectly okay` in full lowercase.

Try it online.

**Explanation base program:**

```
„€€Ã€           # Push the string "the pointed"
„Ð€€µ           # Push the string "dm one"
'€Ý            '# Push the string "been"
     )          # Wrap the entire stack in a list
      \         # And remove that list from the stack again
[               # Start an infinite loop
 û              #  Palindromize the string at the top of the stack
                #   i.e. "1O+1@" becomes "1O+1@1+O1" the first iteration,
                #        and "1O+1@1+O1O+1@1+O1" the next iteration, etc.
  D             #  Duplicate the palindromized string
 N3*            #  0-indexed index of the loop multiplied by 3
    ©           #  Save it in the register (without popping)
     è?         #  Index into the string and print the character
  Ig            #  If the length of the input is exactly 1:
     #          #   Stop the infinite loop
 ®  D <Ö        #  If the value from the register is divisible by the length - 1
          *     #  And
        NĀ      #  The 0-indexed index of the loop is NOT 0:
           #    #   Stop the infinite loop

```

**Explanation 'backhanded' program:**

```
„ÃÐµÝ           # Push the string "perfectly okay"
     [          # Start an infinite loop
      N©        #  Push the index, and store it in the register (without popping)
          I     #  Push the input (none given, so nothing happens)
           #    #  If the top of the stack is 1, stop the infinite loop
            N   #  Push the index again
             #  #  If the top of the stack is 1, stop the infinite loop

```

Step by step the following happens:

1. `„ÃÐµÝ`: STACK becomes `["perfectly okay"]`
2. `[`: Start infinite loop
3. (first loop iteration) : STACK becomes `["perfectly okay", 0]`
4. (first loop iteration) `I`: STACK remains `["perfectly okay", 0]` because there is no input
5. (first loop iteration) `#`: STACK becomes `["perfectly okay"]`, and the loop continues
6. (first loop iteration) `N`: STACK becomes `["perfectly okay", 0]`
7. (first loop iteration) `#`: STACK becomes `["perfectly okay"]`, and the loop continues
8. (second loop iteration) : STACK becomes `["perfectly okay", 1]`
9. (second loop iteration) `I`: STACK remains `["perfectly okay", 1]` because there is no input
10. (second loop iteration) `#`: STACK becomes `["perfectly okay"]`, and the loop breaks because of the `1` (truthy)
11. Implicitly prints the top of the stack to STDOUT: `perfectly okay`

See the steps here with the debugger on TIO enabled.

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `„€€Ã€„Ð€€µ'€Ý` are `the pointed`, `dm one`, and `been` and `„ÃÐµÝ` is `perfectly okay`.

---

**Old 38-byte version:**

```
„€€Ã€„Ð€€µ'€Ý)\ giqë¬?[ûDN>3*©è?®Ig<Ö#

```

Try it online. (PS: Switch the language from **05AB1E (legacy)** to **05AB1E** for test cases `0123456789` and `@`. The legacy version is faster, but it shows incorrect results for number inputs with leading zeros or single-char inputs.)

The 'backhanded' program will become:

```
„ÃÐµÝ q?D3èIÖ<®©>û¬i\€€„€€€€')gë[N*?g#

```

(Where the `q` exits the program and makes everything else no-ops.)

Try it online.
> 3 votes

# Answer
# Perl 6, ~~101~~ 86 bytes

*Wow, -25 bytes thanks to nwellnhof by drastically improving the first program*

```
##
{S:g/(.).?.?/$0/}o{.comb%3-1??.chop~.flip~S/.//!!$_} #
#}{ "" s( kM ro os wt  l )y.

```

Try it online!

I'm hoping more people take advantage of the rebound like this. The Backhanded program is

```
#{g.?//{o%1.o.iS/!}
{"(Mostly) works"}#_!.~l~h?-bco0?.(:
#S/).$}.m3?cpfp//$ #        .

```

Which comments out to just `{"(Mostly) works"}`.
> 3 votes

# Answer
# Python 2, 130 bytes

```
p='r'#i  n  t  '  P  e  r  f  e  c  t  l  y     o  k  a  y  '  #
s=input();S=s+s[-2:0:-1]+s
print S[:len(~-len(s)%3and S or s):3]

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES6), 130 bytes

Early attempt. Not very satisfying.

```
f  =/*>  "  P  e  r  f  e  c  t  l  y     o  k  a*/y=>""+/**/(g=p=>(c=y[p])?m++%3?g(p+d):y[p+1]?c+g(p+d):c:g(p-d-d,d=-d))(m=0,d=1)

```

Try it online!

When the code is processed by itself, the following characters are isolated:

```
f  =/*>  "  P  e  r  f  e  c  t  l  y     o  k  a*/y=>""+/**/…
^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^

```

which gives:

```
f=>"Perfectly okay"//…

```
> 2 votes

# Answer
# Runic Enchantments, 294 bytes

```
>; "  O  n  l  y     a     F  e  w     B  u  g  s  "  @
                                  /{\!?   =ka:{;!?=ka\
v   R                         R {{R:ak=?!\:$:'@=?!;{:/
v/?!/:$:'@=?!;}:ak= ?!;}:ak=?!\}\        }
y\=ka:L                      }{ /        }
\iuakrU      y<<              !  }}}L {{{L

```

Try it online!

Uncompressed (and almost readable) version:

```
>; "  O  n  l  y     a     F  e  w     B  u  g  s  "  @
                               ;           /                                 \
/y<<         R                         R {{R:ak=?!\:$:'@=?!;{:ak=?!\{:ak=?!\{/
RiuakrR:ak=?!/:$:'@=?!;}:ak= ?!/}:ak=?!\}\        }                ;
\y<<  U                               }{ /        }
      \                                !          L                     }}}L

```

Try it Online!

This...is about as close as I can get.

Compressing it further would require figuring out a way to handle the various loop swapping points without having them collide with other stuff. The first line (which is the only part needs to be passed as input to itself) is required to remain separate: the entire string can't fit on the second line without causing problems (`_` for required spaces):

```
Needed string:
>; "  O  n  l  y  _  a  _  F  e  w  _  B  u  g  s
Best fit:
>; "  O  n  l  y  _  a  _  F  e  w/{_\!?   =ka:{;!?=ka\
Collision:                             ↑

```

That `?` can't be moved away from the `!` which itself can't be moved away from the `\` and none of the allowable messages allow any of these three characters at this position.

The alternative would be to use flow redirection, but that leads to a problem on the lower line:

```
Last usable character:
            ↓
>"Only a Few Bugs"@
/.../
ur         }{L
              ↑
Earliest available free space:

```

As we have to avoid the loop switch in the main program.

Known issues:

* Extremely large inputs. Due to Runic's IP stack limits, pushing very large input strings will cause the IP to expire before completing. This can be minimized by spawning additional IPs and merging them (for example, it handles `abcdefghijklmnopqrstuvwxyz` but not the entirety of its own source). And there's a limit regardless of how many merges occur. Can handle up to 58 bytes of input as-is (additionally, increasing the number of IPs requires figuring out how to get them to merge without using more space). Can fit two more IP entries on the loop-return line (to the right of the `U` on the line starting `\y<<` in the uncompressed version, or one left on the line above the `y<<` in the compressed version) raising the input max length to 78.
* Input strings with spaces need to have the spaces escaped (e.g. `1\ \ 1\ \ +\ \ O\ \ @`). This is a limitation of the language's input parsing.
* Cannot supply inputs consisting of strings that look like integers beginning with any number of `0`s (as when turned into a number on the stack, the `0` is lost). Again, limitation of the language's input parsing.

### How it works

Entry:

1. Combine 4 instruction pointers
2. Read input, break into characters, append a newline, reverse, enter main loop.

Main loop (anything that pops the stack is preceded by a dup):

1. Print the top of the stack
2. Compare to newline. True: switch loops and rotate stack left twice.
3. Compare to `@`. True: terminate. (Terminate command executed)
4. Rotate stack right
5. Compare to newline. True: terminate. (Rightmost command executed)
6. Rotate stack right
7. Compare to newline. True: switch loops and rotate stack left thrice.
8. Rotate stack right
9. Return to top of loop

Secondary loop:

* Identical to main loop, only switch rotate right with rotate left
> 1 votes

# Answer
# Jelly, 34 bytes

```
JŒḄȧ`ȯ“”NNŒḄ2¡3s@”]ȧZỴḢḢ»`Qị⁸ȧ@11€

```

A full program or monadic link accepting a list of characters which prints or yields (respectively).

**Try it online!** Or see the **test-suite**.

The Backhand-parsed code is then:

```
Jȧ“N2s]Ỵ»ị@€

```

A full program or niladic link printing or yielding (respectively) **Turing complete**.

### How?

```
JŒḄȧ`ȯ“”NNŒḄ2¡3s@”]ȧZỴḢḢ»`Qị⁸ȧ@11€ - Main Link: list of characters   e.g. 'abcd'
J                                  - range of length                      [1,2,3,4]
 ŒḄ                                - bounce                         [1,2,3,4,3,2,1]
    `                              - use as both arguments of:
   ȧ                               -   logical AND [x AND x = x]
      “”                           - literal empty list of characters
     ȯ                             - logical OR [when x is truthy: x OR y = x]
        N                          - negate  }
         N                         - negate  } together a no-op
             ¡                     - repeat this...
            2                      - ... two times:
          ŒḄ                       -   bounce                       [1,2,3,4,3,2,1,2,3,4,3,2,1,2,3,4,3,2,1,2,3,4,3,2,1]
              3                    - literal three
               s@                  - split into (threes)            [[1,2,3],[4,3,2],[1,2,3],[4,3,2],[1,2,3],[4,3,2],[1,2,3],[4,3,2],[1]]
                 ”]                - literal ']' character
                   ȧ               - logical AND [']' is truthy so a no-op]
                    Z              - transpose                      [[1,4,1,4,1,4,1,4,1],[2,3,2,3,2,3,2,3],[3,2,3,2,3,2,3,2]]
                     Ỵ             - split at new lines [no newline characters exist in this list of ints so effectively wrap in a list]
                      Ḣ            - head [undo that wrap]
                       Ḣ           - head [get the first of the transposed split indices]
                                   -                                [1,4,1,4,1,4,1,4,1]
                         `         - use as both arguments of:
                        »          -   maximum [max(x, x) = x]
                          Q        - de-duplicate                   [1,4]
                            ⁸      - chain's left argument (the input)
                           ị       - index into it                  "ad"
                               11€ - literal eleven for €ach (of input)
                             ȧ@    - logical AND with swapped args [[11,11,...,11] is truthy]
                                   -                                "ad"
                                   - (as a full program implicit print)

```

the Backhand-parsed code is then:

```
Jȧ“N2s]Ỵ»ị@€ - Main Link: no arguments
J            - range of length (of an implicit 0, treated as [0]) -> [1]
  “N2s]Ỵ»    - compression of "Turing complete"
 ȧ           - logical AND [[1] is truthy] -> "Turing complete"
           € - for each character in the list of characters:
          @  -   with swapped arguments (an implicit 0 is on the right, so f(0, "Turing complete"))
         ị   -     index into
             - (as a full program implicit print)

```
> 1 votes

---
Tags: code-golf, source-layout
---


title: Compute the Wilson score interval

text:
# Question
Title: Compute the Wilson score interval
The Wilson score interval is a confidence interval of the probability of success, based on the proportion of successes in a set of Bernoulli trials (a Bernoulli trial is a trial in which exactly two outcomes are possible: *success* or *failure*). The interval is given by the following formula:

The two values given by the formula are the upper and lower bounds of the interval. *nS* and *nF* are the number of successes and failures, respectively, and *n* is the total number of trials (equivalent to *nS* \+ *nF*). *z* is a parameter dependent on the level of confidence desired. For the purposes of this challenge, *z* = 1.96 will be used (corresponding to a 95% confidence interval)*1*.

Given non-negative integers *nS* and *nF*, output the bounds of the Wilson score interval.

## Rules

* The outputs must be as accurate as possible to the true values, within the limits of your language's floating-point implementation, ignoring any potential issues due to floating-point arithmetic inaccuracies. If your language is capable of arbitrary-precision arithmetic, it must be at least as precise as IEEE 754 double-precision arithmetic.
* The inputs will be within the representable range for your language's native integer type, and the outputs will be within the representable range for your language's native floating-point type.
* *n* will always be positive.
* The order of the outputs does not matter.

## Test Cases

Format: `n_s, n_f => lower, upper`

```
0, 1 => 0.0, 0.7934567085261071
1, 0 => 0.20654329147389294, 1.0
1, 1 => 0.09452865480086611, 0.905471345199134
1, 10 => 0.016231752262825982, 0.3773646254862038
10, 1 => 0.6226353745137962, 0.9837682477371741
10, 90 => 0.05522854161313612, 0.1743673043676654
90, 10 => 0.8256326956323345, 0.9447714583868639
25, 75 => 0.17545094003724265, 0.3430464637007583
75, 25 => 0.6569535362992417, 0.8245490599627573
50, 50 => 0.40382982859014716, 0.5961701714098528
0, 100 => 0.0, 0.03699480747600191
100, 0 => 0.9630051925239981, 1.0

```

---

1. The `z` value is the `1-α/2`th quantile of the standard normal distribution, where `α` is the significance level. If you want a 95% confidence interval, your significance level is `α=0.05`, and the `z` value is `1.96`.

# Answer
# Mathematica, 48 bytes (UTF-8 encoding)

```
({-1,1}√((s=1.4^4)##/+##+s^2/4)+#+s/2)/(s+##)&

```

Unnamed function taking two arguments in the order `n_s, n_f` and returning an ordered pair of real numbers. The three-byte symbol , representing the square-root function, is U-221A.

Uses the fact that preceding `##` by a number results in the product of the two arguments, while `+##` results in their sum. Also uses the fact that products and sums automatically thread over lists, so that `{-1,1}√(...)` implements the ± in the formula. Defining the constant `s = z^2` instead of `z` itself also saved a couple of bytes. (Mostly I'm just proud of saving a byte by noticing that `1.4^4` is exactly `1.96^2`!)
> 6 votes

# Answer
# Perl 6, 66 bytes

```
->\s,\f,\z=1.96 {(s+(-z|z)*sqrt(s*f/(s+f)+z*z/4)+z*z/2)/(s+f+z*z)}

```

This function actually returns an or-junction of the lower and upper bounds; for example, if called with the arguments 100 and 0, it returns:

```
any(0.963005192523998, 1)

```

It's a non-traditional output format to say the least, but no particular format was specified, and both of the required values are present.
> 3 votes

# Answer
# 05AB1E, 34 bytes

```
"1.96"Dn©4/¹P¹O/+t*D()®;+¹0è+®¹O+/

```

Input is of the form `[n_s, n_f]`
Output is of the form `[upper, lower]`

Try it online!

**Explanation**

```
"1.96"                             # push 1.96
      Dn©                          # duplicate, square, store a copy in register
         4/                        # divide by 4
           ¹P¹O/                   # product of input divided by sum of input
                +                  # add this to (z^2)/4
                 t*                # sqrt and multiply with z
                   D()             # wrap in list together with a negated copy
                      ®;+          # add (z^2)/2
                         ¹0è+      # add n_s
                             ®¹O+/ # divide by z^2+n

```
> 3 votes

# Answer
# , ~~58~~ ~~53~~ ~~51~~ ~~49~~ 41 bytes

-15 bytes thanks to J.Doe. -2 bytes thanks to Giuseppe.

```
function(x,y)prop.test(t(c(x,y)),cor=F)$c

```
> 3 votes

# Answer
# Runic Enchantments, 105 bytes

#StillBetterThanJava

```
/:2,:2,i:3s:3s:i:3s*3s+::6s4s,+'qA{*:Z4s3TRr4s{++}\
\p2:,C1Ä'<> yyyyyyyyyyyyyyyyyyy'Ä1C,2p:2,//@S ',+ /

```

Try it online!

Input is of the form `n_s n_f`
Output is of the form `lower upper` and has a trailing space

AH GOD this one's a mess. Here's the unwrapped version:

```
>'Ä1C,:2p:2,:2,i:3s:3s:i:3s*3s+::6s4s,+'qA{*:Z4s3TRr4s{++}+,' S@
                  > yyyyyyyyyyyyyyyyyyy'Ä1C,2p:2,//

```

All those `y`s are to slow down the second IP so that it arrives at the `T`ransfer point at the right time (i.e. second). This shoves the top 3 items of the one pointer over to the other (the setup to this action is depicted below). `'Ä1C,` generates `z` by dividing character 196 by 100 (dup, square, dup, div 2, dup, div 2...). The everything-else is just a bunch of math and stack manipulation to shove future values down the stack until they're needed. For the most part, they end up in the right order and its only until `r4s{++}` that we have to reverse the stack and rotate the whole thing to get the values we want next to each other next to each other.

There's probably room for improvement, but its complex enough that I can't see it. Heck, had inadvertently read "z" instead of "n" in the original formula at one point and fixing *that* was rough.

I had to pull out notecards and simulate the stacks in order to make sure it was correct:

Every single one has a value on both ends due to how many variables there were (eg. I'd have one with S and one with F, I'd pop them both, flip one around and add the S+F that was on the other end to the top of the stack). You can see one of the `sqrt(...)` cards has an `S` on the lower edge.
> 3 votes

# Answer
# MATL, ~~38~~ 37 bytes

```
pGs/1.96XJU4/XI+X^J*t_hIE+G1)+GsJU+/S

```

Input is an array of two numbers, in any of these formats: `[25 75]`, `[25, 75]`, `[25; 75]`.

Try it online! or verify all test cases.
> 2 votes

# Answer
# Haskell, ~~70 69 68~~ 67 bytes

```
s#f|y<-1.96^2=[(s+y/2+k*sqrt(s*f*y/(s+f)+y^2/4))/(s+f+y)|k<-[-1,1]]

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog Unicode), 50 bytes

```
{(+/⍺⍵z)÷⍨(⍺+z÷2)(-,+).5*⍨z×(⍺×⍵÷⍺+⍵)+4÷⍨z←3.8416}

```

Try it online!

Infix Dfn, taking \\$⍺←n\_s\\$ and \\$⍵←n\_f\\$.

Thanks to H.PWiz and dzaima for helping out.

### How:

```
                                        z←3.8416  ⍝ Set z=1.96²
                                     4÷⍨          ⍝ Divide it by 4
                                    +             ⍝ plus
                           (⍺×⍵÷⍺+⍵)             ⍝ (nf×ns)÷n
                         z×                       ⍝ ×z²
                     .5*⍨                         ⍝ to the power .5 (square root)
                (-,+)                             ⍝ ±
         (⍺+z÷2)                                  ⍝ ns+(z²/2)
(+/⍺⍵z)÷⍨                                        ⍝ all divided by nf+ns+z²

```
> 2 votes

# Answer
# Python, 79 67 bytes

```
lambda s,f,z=3.8416:2j**.5*(s-(-z*(f*s/(f+s)+z/4))**.5+z/2)/(f+s+z)

```

Output is a complex integer with the interval stored as the real/imaginary part.
> 1 votes

# Answer
# dc, 71 bytes

```
16k?dsa2*?sb1.96 2^dso+dlalb4**lalb+/lo+vlov*dsd+lalblo++2*dsx/rld-lx/f

```

Takes both inputs on two separate lines upon invocation, and outputs on two separate lines with the upper bound on the *bottom* and the lower bound on *top*.

For example:

```
bash-4.4$ dc -e '16k?dsa2*?sb1.96 2^dso+dlalb4**lalb+/lo+vlov*dsd+lalblo++2*dsx/rld-lx/f'
10                # Input n_s
90                # Input n_f
.0552285416131361 # Output lower bound
.1743673043676654 # Output upper bound

```
> 1 votes

# Answer
## Racket 134 bytes

```
(let*((n(+ s f))(z 1.96)(h(* z z))(p(/ 1(+ n h)))(q(+ s(/ h 2)))(r(* z(sqrt(+(/(* s f) n)(/ h 4))))))(values(* p(- q r))(* p(+ q r))))

```

Ungolfed:

```
(define (g s f)
  (let* ((n (+ s f))
         (z 1.96)
         (zq (* z z))
         (p (/ 1 (+ n zq)))
         (q (+ s (/ zq 2)))
         (r (* z (sqrt (+ (/(* s f) n) (/ zq 4))))))
    (values (* p (- q r)) (* p (+ q r)))))

```

Testing:

```
(g 1 10)

```

Output:

```
0.016231752262825982
0.3773646254862038

```
> 1 votes

# Answer
# Java 7, 130 bytes

Golfed:

```
double[]w(int s,int f){double n=s+f,z=1.96,x=z*z,p=s+x/2,d=z*Math.sqrt(s*f/n+x/4),m=1/(n+x);return new double[]{m*(p-d),m*(p+d)};}

```

Ungolfed:

```
double[] w(int s, int f)
{
    double n = s + f, z = 1.96, x = z * z, p = s + x / 2, d = z * Math.sqrt(s * f / n + x / 4), m = 1 / (n + x);
    return new double[]
    { m * (p - d), m * (p + d) };
}

```

Try it online

Returns an array of type double of length 2, can probably be golfed more.
> 1 votes

# Answer
# \>\<\> with `-v` flag, 100 bytes

```
:{:@:}*@+:@,24a,a,-:@:*:&4,+:\$~*{&:&2,+}:{:@@-{&+:&,nao+&,n;
,}:{::*@@-:0$0(?$-1a,:*:*:*(?\}:{:@,+2

```

Expects the input to be present on the stack at execution start, in the order `n_s, n_f`. Try it online!

What a stupid language to attempt this in...

As \>\<\> lacks an exponent or root operator, the square root is calculated in the second line of code using the Babylonian method, to an accuracy of `1e-8` \- for every example I've tried, this is accurate to at least 10 decimal places. If this isn't precise enough, the bounds can be tightened by adding more `:*` in the second line, shuffling things around to keep the mirrors in line.

Output is in the following form:

```
<lower bound>
<upper bound>

```
> 1 votes

# Answer
# Pyth, 38 bytes

```
J*K1.96Kmc++dhQcJ2+sQJ_B*K@+cJ4c*FQsQ2

```

Input is as a list of values, `[n_s, n_f]`. Output is `[upper, lower]` Try it online here, or verify all the test cases at once here.

```
J*K1.96Kmc++dhQcJ2+sQJ_B*K@+cJ4c*FQsQ2   Implicit: Q=eval(input())

  K1.96                                  Set variable K=1.96 (z)
J*K    K                                 Set variable J=K*K (z^2)
                                *FQ      Product of input pair
                               c   sQ    Divide the above by the sum of the input pair
                            cJ4          J / 4
                           +             Add the two previous results
                          @          2   Take the square root of the above
                        *K               Multiply by K
                      _B                 Pair the above with itself, negated
        m                                Map each in the above, as d, using:
             hQ                            First value of input (i.e. n_s)
               cJ2                         J / 2
          ++d                              Sum the above two with d
         c                                 Divided by...
                  +sQJ                     ... (J + sum of input)

```
> 1 votes

# Answer
# Jelly, 30 bytes

```
×÷++1.96²©HH¤×®½×Ø-+®H¤+³÷++®ɗ

```

Try it online!

## Explanation

```
                   Inputs: s and f
×÷+                (s×f)÷(s+f)
    1.96²©HH¤      (© ← 1.96²)÷4      (call this W)

   +                         (s×f)÷(s+f)+W
             ×®             ((s×f)÷(s+f)+W)×©
               ½      sqrt[ ((s×f)÷(s+f)+W)×© ]   (call this R)

                ×Ø-            [   -R,      +R  ]
                   +®H¤        [©/2-R,   ©/2+R  ]
                       +³      [©/2-R+s, ©/2+R+s]

                         ÷           Divide both by:
                          ++®ɗ       (s+f)+©

```

## Note

Some of these features are newer than the challenge. I believe around the time this challenge was posted, `++®¶×÷++1.96²©HH¤×®½×-,1+®H¤+³÷ç` was valid Jelly (32 bytes), lacking `ɗ` and `Ø-`.
> 1 votes

# Answer
# APL(NARS), 49 chars, 98 bytes

```
{k←1.9208⋄(2+n÷k)÷⍨(1+⍺÷k)+¯1 1×√1+2×⍺×⍵÷k×n←⍺+⍵}

```

test

```
  f←{k←1.9208⋄(2+n÷k)÷⍨(1+⍺÷k)+¯1 1×√1+2×⍺×⍵÷k×n←⍺+⍵}
  25 f 75
0.17545094 0.3430464637
  0 f 1
0 0.7934567085
  1 f 0
0.2065432915 1

```
> 1 votes

---
Tags: code-golf, math, number, statistics
---


# Question
Title: Modified Boggle-able Code and Output: CnR Edition (Robbers)
> This is the Robbers' thread. Cops' thread is here.

## Background

Boggle is a board game where the players have to find English words on a 4-by-4 board of random alphabets. Words can be constructed by selecting sequentially adjacent cells on the board. ("adjacent" means horizontally, vertically or diagonally adjacent.) Also, same cell can't be used more than once in a word.

The following is an example board:

```
I L A W
B N G E
I U A O
A S R L

```

On this board, `BINGO`, `ORANGE` and `WEARS` are valid words, but `SURGE` and `RUSSIA` are not:

* `SURGE` : There's no adjacent pair on the board having `RG`.
* `RUSSIA` : `S` cannot be used twice.

**Modified Boggle** is a modified version of Boggle, with the following rules:

* The board size is `m`-by-`n`, where `m` and `n` can be any positive integer.
* Each cell can contain any one byte between 0 and 255 inclusive.
* **A cell can be used more than once, but not twice in a row.**

Using the example board above, in addition to `BINGO`, `ORANGE` and `WEARS`, `LANGUAGE` becomes a valid string (since `G` is used twice, but not twice in a row) but `RUSSIA` is still not (due to `SS` pair).

Here is another example using a code fragment. The string `from itertools import*\n` can be found on the following board, but not `from itertoosl import*` or `from itertools import *`:

```
f   i   ' ' s
r   t   m   l
e   o   o   p
\n  *   t   r

```

Note that you need two `o`'s in order to match the `oo` sequence.

---

## Robber's challenge

Pick a cop's submission which isn't yet cracked or marked safe. In the given language, find a **full program** that fits in the code board which outputs some string that fits in the output board. **The program's length should be equal or less than given, and the output's should be equal or greater.**

## Scoring for robbers

Each successful crack counts as a score of 1. The user with the greatest score wins.

## Robber example & formatting

```
# Japt, code 8 bytes, output 21 bytes, [Bubbler](link-to-cops-post)

    `líÏ`íÏl

    [Try it online!](link-to-tio)

    The output is `112624120720504040320`.

```

---

## Modified Boggle verification script

All of the scripts below have an example input with it.

Script for character string(code/output) & boggle. This does not support multi-line string. The input format is

* a single line of string (either code or output), followed by
* the raw boggle board.

Script for character string with byte-value boggle. Use this if the target string is printable but has one or more newlines in it. The input format is

* the number of lines for the string,
* raw string (possibly multi-line), then
* the boggle board as byte values.

Script for byte-value string & boggle. Use this if the target string contains one or more unprintable characters. The input format is

* a single line of string (either code or output) as byte values, followed by
* the boggle board as byte values.

# Answer
> 3 votes
# JavaScript, code 1342 bytes, output 3 bytes, Scrooble

```
[][[[]+![]][+![]][+![]]+[[]+[][[]]][+![]][!+[]+!+[]+!+[]+!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]][[[]+[][[[]+![]][+![]][+![]]+[[]+[][[]]][+![]][!+[]+!+[]+!+[]+!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]]][+![]][!+[]+!+[]+!+[]]+[!![]+[][[[]+![]][+![]][+![]]+[[]+[][[]]][+![]][!+[]+!+[]+!+[]+!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]]][+![]][+!+[]+[+![]]]+[[]+[][[]]][+![]][+!+[]]+[[]+![]][+![]][!+[]+!+[]+!+[]]+[[]+!![]][+![]][+![]]+[[]+!![]][+![]][+!+[]]+[[]+!![]][+![]][!+[]+!+[]]+[[]+[][[[]+![]][+![]][+![]]+[[]+[][[]]][+![]][!+[]+!+[]+!+[]+!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]]][+![]][!+[]+!+[]+!+[]]+[[]+!![]][+![]][+![]]+[!![]+[][[[]+![]][+![]][+![]]+[[]+[][[]]][+![]][!+[]+!+[]+!+[]+!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]]][+![]][+!+[]+[+![]]]+[[]+!![]][+![]][+!+[]]]([[]+[![]]][+![]][+!+[]]+[[]+![]][+![]][!+[]+!+[]]+[[]+!![]][+![]][!+[]+!+[]+!+[]]+[[]+!![]][+![]][+!+[]]+[[]+!![]][+![]][+![]]+[[][[]]+[][[[]+![]][+![]][+![]]+[[]+[][[]]][+![]][!+[]+!+[]+!+[]+!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]]][+![]][!+[]+!+[]+[!+[]+!+[]]]+[+[![]]]+[[+![]]+![]+[][[[]+![]][+![]][+![]]+[[]+[][[]]][+![]][!+[]+!+[]+!+[]+!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]+[[]+![]][+![]][!+[]+!+[]]]][+![]][!+[]+!+[]+[+![]]])()

```

Try it online! and Verify the code boggle online!

Outgolfing by 101 bytes :)

The point is that we can avoid most of the parens by using brackets instead (at the cost of a few bytes), and we just need two pairs of parens to do the function call.

For example, `([]+true)[1]` is equivalent to `[[]+true][0][1]`, and `!+[]+!+[]+[]+(!+[]+!+[])` (the code to generate "22") is equal to `!+[]+!+[]+[!+[]+!+[]]`.

Since `alert` is not available in Node, the TIO link shows the generated function instead.

### How it works

```
False = ![]                         // false
f = [[]+![]][+![]][+![]]            // 'f'
a = [[]+![]][+![]][+!+[]]           // 'a'
l = [[]+![]][+![]][!+[]+!+[]]       // 'l'
s = [[]+![]][+![]][!+[]+!+[]+!+[]]  // 's'
True = !![]                         // true
t = [[]+!![]][+![]][+![]]           // 't'
r = [[]+!![]][+![]][+!+[]]          // 'r'
u = [[]+!![]][+![]][!+[]+!+[]]      // 'u'
e = [[]+!![]][+![]][!+[]+!+[]+!+[]] // 'e'
Undefined = [][[]]                  // undefined
n = [[]+[][[]]][+![]][+!+[]]        // 'n'
i = [[]+[][[]]][+![]][!+[]+!+[]+!+[]+!+[]+!+[]]  // 'i'
fill = [][f+i+l+l]                  // Array.prototype.fill
c = [[]+fill][+![]][!+[]+!+[]+!+[]] // 'c'
o = [!![]+fill][+![]][+!+[]+[+![]]] // 'o'
open = [[][[]]+fill][+![]][!+[]+!+[]+[!+[]+!+[]]]  // '('
close = [[+![]]+![]+fill][+![]][!+[]+!+[]+[+![]]]  // ')'
func = fill[c+o+n+s+t+r+u+c+t+o+r]  // Function
code = func(a+l+e+r+t+open+[+[![]]]+close)  // 'Function("alert("+NaN+")")'

```

Have some fun comparing this to the original JSFxxk conversion table.

# Answer
> 3 votes
# JavaScript (Node.js), 27 bytes, output = 2 bytes, Shieru Asakoto

```
s=4n;s%=s;7n;console.log(s)

```

Try it online! or Verify the code boggle

# Answer
> 2 votes
# Javascript (REPL), code 1443 bytes, output 3 bytes, https://codegolf.stackexchange.com/a/173395

```
+[+[![]]+[]+[]+[]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]+[[]]]

```

Outputs `NaN`. There are quite a lot of ways to pad once you know how `NaN` can represent in JSFuck.

# Answer
> 2 votes
# JavaScript (Node.js), 53 bytes, output = 41 bytes, Shieru Asakoto

```
console.log(1n+1n+1n<<(1n<<1n+1n<<1n+1n<<1n<<1n<<1n))

```

Try it online! or Verify the code boggle or Verify the output boggle

This computes:

$$3\times2^{1\times4\times4\times2\times2\times2}=\\3\times2^{128}=\\1020847100762815390390123822295304634368$$

Which can also be done in **49 bytes**:

```
console.log(1n+1n+1n<<(1n<<1n+1n+1n+1n+1n+1n+1n))

```

Try it online! or Verify the code boggle

---
Tags: cops-and-robbers, boggle
---


title: Making a Mountain out of a Molehill

text:
# Question
Title: Making a Mountain out of a Molehill
You are given a string of terrain, with molehills and mountains:

```
                        /\
                       /  \
              _/\__   /    \
          ___/     \_/      \_
____/\___/                    \___

```

Your job is to replace every molehill in the string with an equivalent mountain centered in the same column. The rest of the string must be unaffected. This may require additional lines at the beginning of the string.

A **molehill** consists of adjacent columns where the terrain goes up, immediately followed by adjacent columns where the terrain goes down. The shortest side must be exactly one column wide.

These are all molehills:

```
_____/\______

   /\________
__/

________/\
          \__

\           /
 \         /
  \       /
   \     /
    \/\_/

```

These are *not* molehills:

```
    /\
___/  \______

      ___
_____/   \___

____  _______
    \/

```

A **mountain** is like a molehill, but the shortest side is four lines high instead of one.

# Examples

```
                  /\
                 /  \
           ->   /    \
____/\____    _/      \_

                       /\
                      /  \
                     /    \
           __ ->    /      \__
_     /\__/      __/
 \___/

                         /\
                        /  \
               ->      /    \
  /\                /\/      \
_/  \__/\_____    _/          \_

_                _    _                _
 \              /      \      /\      /
  \            /        \    /  \    /
   \          /          \  /    \  /
    \        /     ->     \/      \/
     \      /
      \    /
       \/\/

                             /\      /\
                            /  \    /  \
                           /    \  /    \
_                     -> _/      \/      \
 \                                        \
  \                                        \
   \/\______/\_______                       \_

                        /\                           /\       /\
                       /  \               /\        /  \     /  \
              _/\__   /    \       ->    /  \      /    \   /    \
          ___/     \_/      \_          /    \  __/      \_/      \_
____/\___/                    \___    _/      \/                    \___

```

# Additional Rules

* Standard loopholes are forbidden.
* Input and output can be in any reasonable format.
* You may assume the presence or absence of trailing whitespace in the input string.
* There will always be enough space in the sides of the string as well as between molehills for any mountains you might need.
* If replacing the molehills with mountains creates additional molehills, you do not need to turn those molehills into mountains.
* The terrain cannot go both up and down in the same column. If this happens, the terrain does not move.
* If a particular column does not become part of a mountain, its height must remain unchanged.

This is , so the shortest answer in bytes wins.

# Answer
# Python 2, ~~509~~ ~~495~~ 480 bytes

```
def f(S):
 B='\\';F='/';s=''.join(map(max,*S.split('\n')));t=list(re.sub(r'..((./\\[^\\])|([^/]/\\.))..',r'////\\\\\\\\',s));C=s.count;D=t.count;d=C(F)-D(F)+D(B)-C(B);m=[{'_':F,B:'_'},{'_':B,F:'_'}][d<0];d=abs(d);i=1
 while d:
	if s[i]!=t[i]:i+=7
	elif t[i]in m:d-=1;t[i]=m[t[i]]
	i+=1
 return'\n'.join(u for u in map(''.join,zip(*[u.ljust(2*len(S))for u in reduce(lambda (a,p),c:(a+[' '*[p,p-1][c==B]+c],p+[[0,-1][c==B],1][c==F]),t,([],len(t)))[0]]))[::-1]if u.strip())
import re

```

Try it online!

Still not clear what the actual rules are; but here are the additional constraints that are enforced above and beyond the rule that molehills shall be turned into mountains:

* The first and last terrain characters of the output must be `_`, just as they must be for valid inputs.
* The vertical difference between the first `_` and the last `_` must be maintained between the input and output.
* After substitutions from turning molehills into mountains, some other characters might need to be changed in order to maintain said vertical difference; but the characters changed must not be any of the characters that are part of mountains that were created from molehills.
* And when accomplishing these changes, the number of additional characters changed must be minimal.

### Ungolfed Algorithm:

```
def f(s):
    s = ''.join(map(max,*s.split('\n'))) # flatten into a single line
    t = re.sub(r'..((./\\[^\\])|([^/]/\\.))..',r'////\\\\\\\\',s) # replace molehills with mountains
    d = s.count('/')-t.count('/')+t.count('\\')-s.count('\\') # are the two strings equally balanced?
    m=[{'_':'/','\\':'_'},{'_':'\\','/':'_'}][d<0] # make an appropriate mapping...
    d=abs(d);i=1 # skip over leading '_'...
    while d: # while still unbalanced...
        if s[i]!=t[i]:i+=7 # skip over any created mountains (7+1==8)
        elif t[i] in m:d-=1;t = t[:i]+m[t[i]]+t[i+1:] # if can replace, do replace
        i += 1 # next char
    t = reduce(lambda (a,p),c:(a+[' '*[p,p-1][c=='\\']+c],p+[[0,-1][c=='\\'],1][c=='/']),t,([],len(t)))[0]  # pad spaces at left side
    t = map(''.join,zip(*[u.ljust(max(map(len,t))) for u in t])) # rotate
    return '\n'.join(u for u in t[::-1] if u.strip()) # reverse and join into lines.
import re

```
> 2 votes

# Answer
# Red, 855, 845 833 bytes

```
func[s][r: split s"^/"c: charset"\_/"m: copy #()repeat n l: length? r[parse r/:n[any[i:
c(put m 1 + offset? r/:n i reduce[first i n])| skip]]]m: extract next sort/skip to-block m
2 2 e: copy[]parse b: rejoin collect[foreach c m[keep c/1]][any[c:["/\_"|"/\/"](alter
e 1 + offset? b c)| c:["_/\"|"\/\"](alter e 2 + offset? b c)| skip]]y: 0 foreach a e[q: p:
d: -3 + min m/(a - 4)/2 m/(a + 5)/2 if d < y[y: d]j: i: a until[m/:i/1: #"/"m/:i/2: p k: i
- 2 if all[k > 0 #"_"= m/:k/1 p = m/:k/2][m/(k + 1)/1: #"_"m/(k + 1)/2: p break]i: i - 1
m/:i/2 < p: p + 1]j: j + 1 until[m/:j/1: #"\"m/:j/2: q k: i + 2 if all[#"_"= m/:k/1
p = m/:k/2][m/(k - 1)/1: #"_"m/(k - 1)/2: p break]j: j + 1 m/:j/2 < q: q + 1]]y: y - 1 q:
collect[loop l - y[k: copy""keep pad k p: length? m]]repeat n p[w: m/1/2 - y
q/:w/:n: m/1/1 m: next m]foreach d q[print d]]

```

Try it online!

Far, far away from a golfy solution... It passes the test cases but most probably would fail on some other, more strange pattern.

## More readable:

```
f: func [ s ] [
    r: split s "^/"
    c: charset "\_/"
    m: copy #()
    repeat n l: length? r[
        parse r/:n[ any [ i: c(put m 1 + offset? r/:n i reduce[ first i n ])
        | skip]]
    ]
    m: sort/skip to-block m 2
    m: extract next m 2
    b: rejoin collect [ foreach c m [ keep c/1 ] ]
    e: copy []
    parse b [ any [ c: [ "/\_" | "/\/" ]
                (alter e 1 + offset? b c)
            | c: [ "_/\" | "\/\" ]
                (alter e 2 + offset? b c)
            | skip
        ]
    ]
    y: 0
    foreach a e [
        q: p: d: -3 + min m/(a - 4)/2 m/(a + 5)/2
        if d < y [ y: d ]
        j: i: a
        until [
            m/:i/1: #"/"
            m/:i/2: p
            k: i - 2
            if all [ k > 0
                     #"_" = m/:k/1
                     p = m/:k/2
            ] [
                m/(k + 1)/1: #"_"
                m/(k + 1)/2: p
                break
            ]
            i: i - 1
            p: p + 1
            m/:i/2 < p
        ]
        j: j + 1
        until[
            m/:j/1: #"\"
            m/:j/2: q
            k: i + 2
            if all [ #"_" = m/:k/1
                     p = m/:k/2
            ] [
                m/(k - 1)/1: #"_"
                m/(k - 1)/2: p
                break
            ]
            j: j + 1
            q: q + 1
            m/:j/2 < q
        ]
    ]
    y: y - 1
    q: collect [
        loop l - y [
            k: copy ""
            keep pad k p: length? m
        ]
    ]
    repeat n p [ w: m/1/2 - y
                 q/:w/:n: m/1/1
                 m: next m ]
    foreach d q [ print d ]
]

```
> 1 votes

---
Tags: code-golf, ascii-art
---


title: Double, XOR and do it again

text:
# Question
Title: Double, XOR and do it again
We define the function **g** as **g(n) = n XOR (n * 2)** for any integer **n \> 0**.

Given **x \> 0**, find the smallest integer **y \> 0** such that **gk(y) = x** for some **k \> 0**.

## Example

```
x = 549

549 = 483 XOR (483 * 2)     (as binary: 1000100101 = 111100011 XOR 1111000110)
483 = 161 XOR (161 * 2)     (as binary:  111100011 =  10100001 XOR  101000010)

```

Which means that **g2(161) = 549**. We can't go any further, as there is no **n** such that **g(n) = 161**. So, the expected output for **x = 549** is **y = 161**.

## Rules

* You are not supposed to support invalid entries. A pair **(y, k)** is guaranteed to exist for the input value **x**.
* This is , so the shortest answer in bytes wins!

## Test cases

```
     3 -->     1
     5 -->     1
     6 -->     2
     9 -->     7
    10 -->     2
    23 -->    13
    85 -->     1
   549 -->   161
   960 -->    64
  1023 -->   341
  1155 -->   213
  1542 -->     2
  9999 -->  2819
 57308 --> 19124
 57311 -->   223
983055 -->     1

```

# Answer
# Java 8, ~~68~~ ~~57~~ ~~53~~ 52 bytes

```
n->{for(int i=0;i<n;)i-=(i*2^i)==n?n=i:-1;return n;}

```

-5 bytes thanks to *@OlivierGrégoire*.

Try it online.

**Explanation:**

```
n->{                 // Method with integer as both parameter and return-type
  for(int i=0;i<n;)  //  Loop `i` in the range (1,n)
    i-=(i*2^i)==n?   //   If `i*2` XOR-ed with `i` equals `n`
        n=i          //    Set `n` to `i`, and set `i` to 0 to reset the loop
       :             //   Else:
        -1;          //    Increase `i` by 1 to go to the next iteration
  return n;}         //  Return `n` after the entire loop

```
> 5 votes

# Answer
# Python 2, ~~54~~ 53 bytes

```
f=lambda n:next((f(i)for i in range(n)if n==i^i*2),n)

```

Try it online!
> 4 votes

# Answer
# JavaScript, 53 bytes

```
f=x=>(i=0,y=(G=x=>x&&(i^=x&1)+2*G(x>>1))(x),i?x:f(y))

```

`G` is `g^-1`, which set `i` to `0` if success, set `i` to `1` if failed.
> 3 votes

# Answer
# Pyth, ~~13 12~~ 10 bytes

*Saved 1 byte thanks to @MrXcoder, and 2 more bytes following their suggestion*

```
fqQ.W<HQxy

```

Try it online

Explanation:

```
fqQ.W<HQxyZZT   Implicit: Q=eval(input()), trailing ZZT inferred

f               Return the first T in [1,2,3...] where the following is truthy
   .W       T     Functional while - loop until condition is true, starting value T
     <HQ            Condition: continue while iteration value (H) less than input
        xyZZ        Body: xor iteration value (Z) with double (y) iteration value (Z)
 qQ               Is the result of the above equal to input?

```
> 3 votes

# Answer
# , ~~73~~ 65 bytes

```
f=function(x){for(i in 1:x)if(x==bitwXor(i,i*2)){i=f(i);break};i}

```

Try it online!

Thanks a lot Giuseppe (-8) due to your tweaks, so simple yet very effective
> 3 votes

# Answer
# JavaScript, ~~38~~ 36 bytes

```
f=(n,x=n)=>x?x^x+x^n?f(n,--x):f(x):n

```

Try it online \- Starts throwing overflow errors somewhere between `9999` & `57308`.
> 2 votes

# Answer
# Jelly, ~~8~~ 7 bytes

Use `⁺¿` to return the last non-zero element (thanks Dennis for -1 byte)

```
^Ḥ)i$⁺¿

```

Try it online!

Brute force wins again :(
> 2 votes

# Answer
# C (gcc), ~~57~~ ~~56~~ ~~55~~ 51 bytes

* Saved a byte thanks to ceilingcat; `!=``-`.
* Saved ~~a byte~~ five bytes thanks to Rogem; making use of the ternary expression and gcc quirks.

```
X(O,R){for(R=1;R;O=R?R:O)for(R=O;--R&&(R^2*R)-O;);}

```

Try it online!
> 2 votes

# Answer
# Z80Golf, 22 bytes

```
00000000: 1600 1803 4216 007a b830 097a 82aa b828  ....B..z.0.z...(
00000010: f314 18f3 78c9                           ....x.

```

Port of @KevinCruijssen's Java answer

Example with input of 9-Try it online!

Example with input of 85-Try it online!

Assembly:

```
;d=loop counter
;b=input and output
f:
	ld d,0
	jr loop
	begin:
	ld b,d
	ld d,0
	loop:
		ld a,d
		cp b
		jr nc,end	; if d==b end
		ld a,d
		add d		; mul by 2
		xor d
		cp b
		jr z,begin	; if (d*2)^d==b set b to d
		inc d
		jr loop
	end:
	ld a,b
	ret

```

Assembly example for calling the function and printing the result:

```
ld b,9 ; input to the function, in this case 9
call f
add 30h ; ASCII char '0'
call 8000h ; putchar
halt

```
> 2 votes

# Answer
# JavaScript (Node.js), ~~48~~ ~~45~~ 38 bytes

```
f=(n,i=0)=>i<n?i*2^i^n?f(n,i+1):f(i):n

```

-7 bytes thanks to @Neil creating a recursive version of my iterative version below. Doesn't work for large test cases.

Try it online.

---

Iterative **45 bytes** version that works for all test cases:

```
n=>{for(i=0;i<n;)i-=i*2^i^n?-1:n=i;return n;}

```

Port of my Java answer.
-3 bytes thanks to *@Arnauld*.

Try it online.
> 1 votes

# Answer
# Jelly, ~~11~~ 9 bytes

```
BÄḂṛḄß$Ṫ?

```

Try it online!

Tips: Use recursive function instead of loops.

---

Very fast, unfortunately loses to the brute force approach.

Note that:

* For *x \> 0*, *f(x) \> x*.
* *popcount(f(x))* is even, where *popcount(n)* is the number of bits set in *n*.
* If *n* has even popcount, then there exists *x* such that *f(x) = n*.
* Let *B(x)* be the binary representation of *x*, and *Ṗ(l)* be the list *l* with last element removed. Then *B(x)* is the accumulated XOR of *Ṗ(B(f(x)))*.

So, we repeatedly:

* Compute its binary representation (`B`)
* then take the accumulated XOR (use `^\` or `ÄḂ`, they have the same effect).
* Check if (`?`) the tail (last element) () of the accumulated XOR is nonzero (odd popcount)
    + If so, convert the binary list back to decimal and recurse.
    + If not, returns the input ().
> 1 votes

# Answer
# K (ngn/k), ~~32~~ 26 bytes

```
{$[*|a:2!+\2\x;x;2/-1_a]}/

```

Try it online!

`{` `}` is a function with argument `x`

`/` applies it until convergence

`$[` `;` `;` `]` if-then-else

`2\x` binary digits of `x` (this is specific to ngn/k)

`+\` partial sums

`2!` mod 2

`a:` assign to `a`

`*|` last - reverse (`|`) and get first (`*`)

if the above is 1, `x` will be returned

otherwise:

`-1_a` drop the last element of `a`

`2/` decode binary
> 1 votes

# Answer
# Java (JDK 10), 78 bytes

```
int g(int n){return f(n)%2<1?g(f(n)/2):n;}int f(int x){return 1>x?0:x^f(x/2);}

```

Try it online!
> 1 votes

# Answer
# JavaScript (Node.js), 40 bytes

```
f=n=>g(n)%2?n:f(g(n)/2)
g=x=>x&&x^g(x/2)

```

Try it online!

Thanks Shaggy for -1 bytes.

Port of my Jelly answer.

Finally there is a language where this approach is ~~shorter~~ (oops). (I tried Python and Java, it doesn't work)

Can anyone explain why I can use `/2` instead of `>>1`?
> 1 votes

# Answer
# Ruby, 39 bytes

```
f=->x,y=x{y<1?x:x==y^y*2?f[y]:f[x,y-1]}

```

Try it online!

As expected for the recursive version, complains about "stack level too deep" on the latter test cases.
> 1 votes

# Answer
# Forth (gforth), 71 bytes

```
: f 0 begin 2dup dup 2* xor = if nip 0 else 1+ then 2dup < until drop ;

```

Try it online!

### Explanation

```
0                 \ add an index variable to the top of the stack
begin             \ start an indefinite loop
  2dup            \ duplicate the top two stack items (n and i)
  dup 2* xor =    \ calculate i xor 2i and check if equal to n
  if nip 0        \ if equal, drop n (making i the new n) and use 0 as the new i
  else 1+         \ otherwise just increment i by 1
  then            \ end the if-statement
  2dup <          \ duplicate the top two stack items and check if n < i
until             \ if previous statement is true, end the loop
drop              \ drop i, leaving n on top of the stack

```
> 1 votes

# Answer
# Perl 6, 44 bytes

```
{({first {($^a+^2*$a)==$_},^$_}...^!*).tail}

```

Try it

## Expanded:

```
{  # bare block lambda with implicit parameter $_

  (
    # generate a sequence

    # no need to seed the sequence with $_, as the following block will
    # default to using the outer $_
    # $_,

    { # parameter $_

      first
        {  # block with placeholder parameter $a

          ( $^a +^ 2 * $a ) # double (numeric) xor
          == $_             # is it equal to the previous value
        },

        ^$_  # Range up to and excluding the previous value ( 0..^$_ )
    }

    ...^  # keep doing that until: (and throw away last value)

    !*    # it doesn't return a trueish value

  ).tail  # return the last generated value
}

```
> 1 votes

# Answer
# Prolog (SWI), 44 bytes

```
A-R:-between(1,A,B),A is B xor(B*2),B-R;R=A.

```

Try it online!
> 1 votes

# Answer
# PHP, 49 bytes

Based on Kevin Cruijssen's answers.

```
for($x=$argn;$x>$i-=$i*2^$i^$x?-1:$x=$i;);echo$x;

```

Run as pipe with `-nr` or try it online.
> 1 votes

# Answer
## F#, 92 bytes

```
let rec o i=
 let r=Seq.tryFind(fun x->x^^^x*2=i){1..i-1}
 if r.IsNone then i else o r.Value

```

Try it online!

Recursively checks through the numbers from 1 to `i-1`. If there's a match, check for a smaller for that number. If there's no match, return the input number.
> 1 votes

# Answer
# C, 62 bytes

Based on Kevin Cruijssen's Java:

`int n(int j){for(int i=0;i<j;)i-=(i*2^i)==j?j=i:-1;return j;}`

To test:

```
#include <stdio.h>
int n(int j);
#define p(i) printf("%6d --> %5d\n", i, n(i))
int main(void)
{
    p(3);
    p(5);
    p(6);
    p(9);
    p(10);
    p(23);
    p(85);
    p(549);
    p(960);
    p(1023);
    p(1155);
    p(1542);
    p(9999);
    p(57308);
    p(57311);
    p(983055);
}

```

When run, the test program outputs:

```
     3 -->     1
     5 -->     1
     6 -->     2
     9 -->     7
    10 -->     2
    23 -->    13
    85 -->     1
   549 -->   161
   960 -->    64
  1023 -->   341
  1155 -->   213
  1542 -->     2
  9999 -->  2819
 57308 --> 19124
 57311 -->   223
983055 -->     1

```

# C, 54 bytes

Only works with C89 or K&R C:

`n(j){for(i=0;i<j;)i-=(i*2^i)==j?j=i:-1;return j;}`
> 0 votes

# Answer
# Wolfram Language (Mathematica), 58 bytes

```
Min[{#}//.x_:>Select[Range@#,MemberQ[x,#|BitXor[#,2#]]&]]&

```

Try it online!

Starts with a list containing just the input. Iteratively replaces the list by all integers that are either already in it, or map into it by the double-and-xor operation. Then `//.` says to do this until reaching a fixed point. The answer is the least element of the result.
> 0 votes

---
Tags: code-golf, bitwise
---


title: Stagger, stack, sum

text:
# Question
Title: Stagger, stack, sum
*Inspired by this Stack Overflow question*.

## The challenge

### Input

An array of square matrices containing non-negative integers.

### Output

A square matrix built from the input matrices as follows.

Let \\$N \times N\\$ be the size of each input matrix, and \\$P\\$ the number of input matrices.

For clarity, consider the following example input matrices (\\$N=2\\$, \\$P=3\\$):

```
 3   5
 4  10

 6   8
12  11

 2   0
 9   1

```
1. Start with the first input matrix.
2. Shift the second input matrix *N*−1 steps down and *N*−1 steps right, so that its upper-left entry coincides with the lower-right entry of the previous one.
3. Imagine the second, shifted matrix as if it were stacked on top of the first. Sum the two values at the coincident entry. Write the other values, and fill the remaining entries with `0` to get a \\$(2N-1)\times(2N-1)\\$ matrix. With the example input, the result so far is

```
 3   5   0
 4  16   8
 0  12  11

```
4. For each remaining input matrix, stagger it so that its upper-left coincides with the lower-right of the accumulated result matrix so far. In the example, including the third input matrix gives

```
 3   5   0   0
 4  16   8   0
 0  12  13   0
 0   0   9   1

```
5. The ouput is the \\$((N−1)P+1)\times((N−1)P+1)\\$ matrix obtained after including the last input matrix.

## Additional rules and clarifications

## Test cases:

In each case, input matrices are shown first, then the output.

1. \\$N=2\\$, \\$P=3\\$:

```
 3   5
 4  10

 6   8
12  11

 2   0
 9   1

 3   5   0   0
 4  16   8   0
 0  12  13   0
 0   0   9   1

```
2. \\$N=2\\$, \\$P=1\\$:

```
 3   5
 4  10

 3   5
 4  10

```
3. \\$N=1\\$, \\$P=4\\$:

```
 4

 7

23

 5

39

```
4. \\$N=3\\$, \\$P=2\\$:

```
11  11   8
 6   8  12
11   0   4

 4   1  13
 9  19  11
13   4   2

11  11   8   0   0
 6   8  12   0   0
11   0   8   1  13
 0   0   9  19  11
 0   0  13   4   2

```
5. \\$N=2\\$, \\$P=4\\$:

```
14  13
10   0

13  20
21   3

 9  22
 0   8

17   3
19  16

14  13   0   0   0
10  13  20   0   0
 0  21  12  22   0
 0   0   0  25   3
 0   0   0  19  16

```

# Answer
> 4 votes
# Jelly, ~~15~~ 12 bytes

```
⁹ṖŻ€ƒZƲ⁺+µ@/

```

Try it online!

### How it works

```
⁹ṖŻ€ƒZƲ⁺+µ@/  Main link. Argument: A (array of matrices)

         µ    Begin a monadic chain.
          @/  Reduce A by the previous chain, with swapped arguments.
                Dyadic chain. Arguments: M, N (matrices)
      Ʋ           Combine the links to the left into a monadic chain with arg. M.
⁹                 Set the return value to N.
 Ṗ                Pop; remove its last row.
     Z            Zip; yield M transposed.
    ƒ             Fold popped N, using the link to the left as folding function and
                  transposed M as initial value.
  Ż€                Prepend a zero to each row of the left argument.
                    The right argument is ignored.
       ⁺        Duplicate the chain created by Ʋ.
        +       Add M to the result.

```

# Answer
> 6 votes
# , ~~88~~ 81 bytes

```
function(A,N,P,o=0*diag(P*(N-1)+1)){for(i in 1:P)o[x,x]=o[x<-1:N+i-1,x]+A[[i]];o}

```

Try it online!

Takes a `list` of matrices, `A`, `N`, and `P`.

Builds the requisite matrix of zeros `o` and adds elementwise the contents of `A` to the appropriate submatrices in `o`.

# Answer
> 4 votes
# JavaScript (ES6), 102 bytes

Takes input as `(n,p,a)`.

```
(n,p,a)=>[...Array(--n*p+1)].map((_,y,r)=>r.map((_,x)=>a.map((a,i)=>s+=(a[y-i*n]||0)[x-i*n]|0,s=0)|s))

```

Try it online!

### How?

Redimensioning matrices filled with a default constant (\\$0\\$ in that case) is neither very easy nor very short in JS, so we just build a square matrix with the correct width \\$w\\$ right away:

$$w=(n-1)\times p+1$$

For each cell at \\$(x,y)\\$, we compute:

$$s\_{x,y}=\sum\_{i=0}^{p-1}{a\_i(x-i\times (n-1),y-i\times (n-1))}$$

where undefined cells are replaced with zeros.

# Answer
> 3 votes
# Python 2, 124 bytes

```
def f(m,N,P):w=~-N*P+1;a=[w*[0]for _ in' '*w];g=0;exec"x=g/N/N*~-N;a[x+g/N%N][x+g%N]+=m[x][g/N%N][g%N];g+=1;"*P*N*N;return a

```

Try it online!

# Answer
> 3 votes
# Jelly, 12 bytes

```
Z€Ż€’}¡"Jµ⁺S

```

Try it online!

```
Z€Ż€’}¡"Jµ⁺S
         µ    Everything before this as a monad.
          ⁺   Do it twice
Z€            Zip €ach of the matrices
        J     1..P
       "      Pair the matrices with their corresponding integer in [1..P] then apply the
              following dyad:
  Ż€            Prepend 0 to each of the rows
      ¡         Repeat this:
    ’}          (right argument - 1) number of times
              Doing everything before µ twice adds the appropriate number of rows and
              columns to each matrix. Finally:
           S  Sum the matrices.

```

**12 bytes**

```
J’0ẋ;Ɱ"Z€µ⁺S

```

If extra zeroes were allowed `ZŻ€‘ɼ¡)⁺S` is a cool 9 byte solution. TIO.

# Answer
> 2 votes
# Jelly, 20 bytes

```
µ;€0Zð⁺0ṁ+ṚU$}ṚU+⁸µ/

```

Try it online!

Bah, Jelly has an attitude today...

# Answer
> 2 votes
# Pip, 37 bytes

```
{i:0{Y#i-1aM:0RLyAL_i+:yZG#@aALa}Mai}

```

A function that takes a list of lists of lists. Try it online!

# Answer
> 2 votes
# Python 2, 124 bytes

```
def f(A,N,P):M=N-1;R=G(M*P+1);return[[sum(A[k][i-k*M][j-k*M]for k in G(P)if j<N+k*M>i>=k*M<=j)for j in R]for i in R]
G=range

```

Try it online!

# Answer
> 1 votes
# Charcoal, 52 bytes

```
≦⊖θＥ⊕×θηＥ⊕×θηΣＥＥη×θξ∧¬∨∨‹ιν›ι⁺θν∨‹λν›λ⁺θν§§§ζξ⁻ιν⁻λν

```

Try it online! Link is to verbose version of code and includes two bytes for somewhat usable formatting. I started off with a version that padded all the arrays and then summed them but I was able to golf this version to be shorter instead. Explanation:

```
≦⊖θ

```

Decrement the input value \\$N\\$.

```
Ｅ⊕×θηＥ⊕×θη

```

Compute the size of the result \\$(N-1)P+1\\$ and map over the implicit range twice thus producing a result matrix which is implcitly printed.

```
ΣＥＥη×θξ

```

Map over the implicit range over the input value \\$P\\$ and multiply each element by \\$N-1\\$. Then, map over the resulting range and sum the final result.

```
∧¬∨∨‹ιν›ι⁺θν∨‹λν›λ⁺θν

```

Check that neither of the indices are out of range.

```
§§§ζξ⁻ιν⁻λν

```

Offset into the original input to fetch the desired value.

---
Tags: code-golf, number, array, integer
---


# Question
Title: You are given a string to make and starting with the empty string, make it using appending and cloning cost
Your task is to create the given target string. Starting with an string that is empty, you will have to add characters to it, until your string is the same as the one we want. You can either add a character to the end of you string with cost x, or you can clone you string with cost y. What we want is the cheapest way to do this.

### Test Cases

```
targetString , appendcost, clonecost -> totalcost

"bb", 1, 2 -> 2
"bbbb", 2, 3 -> 7
"xzxpcxzxpy", 10, 11 -> 71
"abababab", 3, 5 -> 16
"abababab", 3, 11 -> 23

```

# Answer
> 2 votes
# Husk, 25 bytes

```
φ?ö▼z+:⁴∞²m⁰§:h§δf`€otṫḣ0

```

Try it online!

Inputs are in the order append cost, clone cost, target.

## Explanation

```
φ?ö▼z+:⁴∞²m⁰§:h§δf`€otṫḣ0  Two explicit inputs and one implicit.
                           Example: 2, 3, s="abab"
φ                          Make a recursive function and call it on s:
 ?                      0   If s is empty, return 0.
  ö▼z+:⁴∞²m⁰§:h§δf`€otṫḣ    Otherwise do this.
                       ḣ    Prefixes: ["a","ab","aba","abab"]
                    otṫ     Suffixes except the first one: ["bab","ab","b"]
               §δf`€        Keep those prefixes that have the corresponding suffix as substring: ["ab","aba"]
            §:h             Prepend s minus last character: ["aba","ab","aba"]
          m⁰                Recurse on each: x=[6,4,6]
        ∞²                  Repeat the clone cost: [3,3,3,..
      :⁴                    Prepend append cost: [2,3,3,3,..
    z+                      Add component-wise to x: [8,7,9]
   ▼                        Minimum: 7

```

# Answer
> 1 votes
# JavaScript (ES6), ~~123~~ 111 bytes

Takes input as `(x)(y)(s)`.

```
x=>y=>m=g=([s,...r],o='',c=0)=>s?[...r,g(r,o+s,c+x)].map(_=>s+=r.shift(~o.search(s)&&g(r,o+s,c+y)))|m:m=m<c?m:c

```

Try it online!

### Commented

```
x => y =>                    // x = 'append' cost; y = 'clone' cost
m =                          // m = minimum cost, initialized to a non-numeric value
                             //     this is what will eventually be returned
g = (                        // g = recursive function taking:
  [s,                        //   - the input string split into s = next character
      ...r],                 //     and r[] = array of remaining characters
  o = '',                    //   - o = output string
  c = 0                      //   - c = current cost
) =>                         //
  s ?                        // if s is defined:
    [ ...r,                  //   split a copy of r
      g(r, o + s, c + x)     //   do a recursive call with an 'append' operation
    ].map(_ =>               //   iterate as many times as there are remaining characters
                             //   in r[], + 1
      s +=                   //     append to s
        r.shift(             //     the next character picked from the beginning of r[]
          ~o.search(s) &&    //     if s is found in o,
          g(r, o + s, c + y) //     do a recursive call with a 'clone' operation
        )                    //     (note that both s and r are updated *after* the call)
    ) | m                    //   end of map(); return m
  :                          // else:
    m = m < c ? m : c        //   update m to min(m, c)

```

# Answer
> 1 votes
# Python 2, 112 bytes

```
f=lambda s,a,c,i=0:i<len(s)and min([a+f(s,a,c,i+1)]+[c+f(s,a,c,n)for n in range(i+1,len(s)+1)if s[i:n]in s[:i]])

```

Try it online!

# Answer
> 1 votes
# , ~~192~~ 185 bytes

```
f=function(s,a,c,k=0,x="",R=substring,N=nchar,p=R(s,1,1:N(s)))'if'(!N(s),k,{y={};for(i in c(R(s,1,1),p[mapply(grepl,p,x)]))y=min(y,f(R(s,N(i)+1),a,c,k+'if'(any(y),c,a),paste0(x,i)));y})

```

Try it online!

Unrolled code and explanation :

```
# s is the current remaining string (at the beginning is equal to the target string)
# a is the append cost
# c is the clone cost
# k is the current cost (at the beginning is zero)
# x is the partially constructed string (at the beginning is empty)
f=function(s,a,c,k=0,x=""){
  # store in p all the possible prefixes of s
  p = substring(s,1,1:nchar(s))
  # if s is empty return the current cost k
  if(!nchar(s))
    k
  else{
    y={}
    # prepend the first letter of s (=append operation) to
    # the prefixes in p that are contained in x (=clone operations)
    for(i in c(substring(s,1,1),p[mapply(grepl,p,x)])){
      # perform first the append then the clone operations and recurse,
      # storing the cost in y if lower than previous
      # (if y is NULL is an append operation otherwise is a clone, we use the right costs)
      y = min(y,f(substring(s,nchar(i)+1),a,c,k+'if'(any(y),c,a),paste0(x,i)))
    }
    # return the current cost
    y
  }
}

```

---
Tags: code-golf, string
---


title: Multiply and Divide

text:
# Question
Title: Multiply and Divide
Given a value *x* find the smallest numerical value greater than *y* that is capable of being multiplied and divided by *x* while retaining all original digits.

* The new numbers do not lose digits.
* The new numbers do not gain digits.

For example:

> Input: x = 2, y = 250000
>
> * Original: 285714
>     + Division: 142857
>     + Multiplication: 571428
>
> This is true because *285714* is greater than *y*; then when divided by *x* results in *142857* and when multiplied by *x* results in *571428*. In both tests all of the original digits from *285714* are present and no extra digits have been added.

---

## The Rules

* *X* should be *2* or *3* as anything higher takes too long to calculate.
* *Y* is required to be a whole number greater than *zero*.
* The shortest code wins.

---

## Test Cases

These are my most common test cases as they are the quickest to test for.

* *x = 2, y = 250000 = 285714*
* *x = 2, y = 290000 = 2589714*
* *x = 2, y = 3000000 = 20978514*
* *x = 3, y = 31000000 = 31046895*
* *x = 3, y = 290000000 = 301046895*

---

## Clarifications

* The type of division doesn't matter. If you can get *2.05, 0.25, and 5.20* somehow then feel free.

---

Good luck to you all!

# Answer
> 4 votes
# Husk, 14 bytes

```
ḟ§¤=OoDd§¤+d*/

```

Try it online!

### Explanation

```
ḟ§¤=O(Dd)§¤+d*/  -- example inputs: x=2  y=1
ḟ                -- find first value greater than y where the following is true (example on 285714)
 §               -- | fork
         §       -- | | fork
              /  -- | | | divide by x: 142857
                 -- | | and
             *   -- | | | multiply by y: 571428
                 -- | | then do the following with 142857 and 571428
                 -- | | | concatenate but first take
           +     -- | | | | digits: [1,4,2,8,5,7] [5,7,1,4,2,8]
          ¤ d    -- | | | : [1,4,2,8,5,7,5,7,1,4,2,8]
                 -- | and
       d         -- | | digits: [2,8,5,7,1,4]
      D          -- | | double: [2,8,5,7,1,4,2,8,5,7,1,4]
                 -- | then do the following with [2,8,5,7,1,4,2,8,5,7,1,4] and [1,4,2,8,5,7,5,7,1,4,2,8]
   =             -- | | are they equal
  ¤ O            -- | | | when sorted: [1,1,2,2,4,4,5,5,7,7,8,8] [1,1,2,2,4,4,5,5,7,7,8,8]
                 -- | : truthy
                 -- : 285714

```

# Answer
> 5 votes
# Brachylog v2, 15 bytes

```
t<.g,?kA/p.∧A×p

```

Try it online!

Takes input in the form `[x,y]`.

## Explanation

```
t<.g,?kA/p.∧A×p
t                  Tail (extract y from the input)
 <                 Brute-force search for a number > y, such that:
  .                  it's the output to the user (called ".");
   g                 forming it into a list,
    ,?               appending both inputs (to form [.,x,y]),
      k              and removing the last (to form [.,x])
       A             gives a value called A, such that:
        /              first ÷ second element of {A}
         p             is a permutation of
          .            .
           ∧         and
            A×         first × second element of {A}
              p        is a permutation of {.}

```

## Commentary

Brachylog's weakness at reusing multiple values multiple times shows up here; this program is almost all plumbing and very little algorithm.

As such, it might seem more convenient to simply hardcode the value of *y* (there's a comment on this question hypothesising that 2 is the only possible value). However, there are in fact solutions for *y*=3, meaning that unfortunately, the plumbing has to handle the value of *y* as well. The smallest that I'm aware of is the following:

```
                         315789473684210526
315789473684210526 × 3 = 947368421052631578
315789473684210526 ÷ 3 = 105263157894736842

```

(The technique I used to find this number isn't fully general, so it's possible that there's a smaller solution using some other approach.)

You're unlikely to verify that with *this* program, though. Brachylog's `p` is written in a very general way that doesn't have optimisations for special cases (such as the case where both the input and output are already known, meaning that you can do the verification in O(*n* log *n*) via sorting, rather than the O(*n*!) for the brute-force approach that I suspect it's using). As a consequence, it takes a very long time to verify that 105263157894736842 is a permutation of 315789473684210526 (I've been leaving it running for several minutes now with no obvious progress).

(EDIT: I checked the Brachylog source for the reason. It turns out that if you use `p` on two known integers, the algorithm used generates all possible permutations of the integer in question until it finds one that's equal to the output integer, as the algorithm is "input → indigits, permute indigits → outdigits, outdigits → output". A more efficient algorithm would be to set up the outdigits/output relationship *first*, so that the backtracking within the permutation could take into account which digits were available.)

# Answer
> 4 votes
# Perl 6, 56 ~~54~~ bytes

```
->\x,\y{(y+1...{[eqv] map *.comb.Bag,$_,$_*x,$_/x})+y}

```

Try it online!

Interesting alternative, computing n\*xk for k=-1,0,1:

```
->\x,\y{first {[eqv] map ($_*x***).comb.Bag,^3-1},y^..*}

```

# Answer
> 4 votes
# Haskell, ~~76~~ 74 bytes

*Two bytes shaved off thanks to Lynn's comment*

```
import Data.List
s=sort.show
x#y=[n|n<-[y+1..],all(==s n)[s$n*x,s$n/x]]!!0

```

# Answer
> 3 votes
# Clean, 92 bytes

```
import StdEnv
$n m=hd[i\\i<-[m..],[_]<-[removeDup[sort[c\\c<-:toString j]\\j<-[i,i/n,i*n]]]]

```

Try it online!

Pretty simple. Explanation coming in a while.

# Answer
> 3 votes
# JavaScript (ES6), ~~76~~ ~~73~~ 69 bytes

*Saved 3 bytes by using `eval()`, as suggested by @ShieruAsakoto*

Takes input as `(x)(y)`.

```
x=>y=>eval("for(;(g=x=>r=[...x+''].sort())(y*x)+g(y/x)!=g(y)+r;)++y")

```

Try it online!

A recursive version would be **62 bytes**, but it's not well suited here because of the high number of required iterations.

### How?

The helper function \\$g\\$ takes an integer as input, converts it to an array of digit characters and sorts this array.

*Example:*

```
g(285714) = [ '1', '2', '4', '5', '7', '8' ]

```

To compare the digits of \\$y\times x\\$ and those of \\$y/x\\$ against those of \\$y\\$, we test whether the concatenation of \\$g(y\times x)\\$ with \\$g(y/x)\\$ is equal to the concatenation of \\$g(y)\\$ with itself.

When adding two arrays together, each of them is implicitly coerced to a comma-separated string. The last digit of the first array is going to be directly concatenated with the first digit of the second array with no comma between them, which makes this format unambiguous.

*Example:*

```
g(123) + g(456) = [ '1', '2', '3' ] + [ '4', '5', '6' ] = '1,2,34,5,6'

```

But:

```
g(1234) + g(56) = [ '1', '2', '3', '4' ] + [ '5', '6' ] = '1,2,3,45,6'

```

### Commented

```
x => y =>                   // given x and y
  eval(                     // evaluate as JS code:
    "for(;" +               //   loop:
      "(g = x =>" +         //     g = helper function taking x
        "r =" +             //       the result will be eventually saved in r
          "[...x + '']" +   //       coerce x to a string and split it
          ".sort() + ''" +  //       sort the digits and coerce them back to a string
      ")(y * x) +" +        //     compute g(y * x)
      "g(y / x) !=" +       //     concatenate it with g(y / x)
      "g(y) + r;" +         //     loop while it's not equal to g(y) concatenated with
    ")" +                   //     itself
    "++y"                   //   increment y after each iteration
  )                         // end of eval(); return y

```

# Answer
> 3 votes
# q, 65 bytes

```
{f:{asc 10 vs x};while[not((f y)~f y*x)&(f y*x)~f"i"$y%x;y+:1];y}

```

Split number on base 10, sort each ascending, and check if equal. If not, increment y and go again

# Answer
> 2 votes
# Japt, 24 bytes

Pretty naïve solution over a few beers; I'm sure there's a better way.

```
@[X*UX/U]®ì nÃeeXì n}a°V

```

Try it

# Answer
> 1 votes
# Jelly,  ~~14~~  13 bytes

-1 thanks to Erik the Outgolfer (\`\` uses make\_digits, so `D` was not required)
+2 fixing a bug (thanks again to Erik the Outgolfer for pointing out the off-by one issue)

```
×;÷;⁸Ṣ€E
‘ç1#

```

A full program printing the result (as a dyadic link a list of length 1 is yielded).

**Try it online!**

### How?

```
×;÷;⁸Ṣ€E - Link 1, checkValidity: n, x               e.g. n=285714,  x=2
×        -     multiply -> n×x                       571428
  ÷      -     divide -> n÷x                         142857
 ;       -     concatenate -> [n×x,n÷x]              [571428,142857]
    ⁸    -     chain's left argument = n             285714
   ;     -     concatenate -> [n×x,n÷x,n]            [571428,142857,285714]
     Ṣ€  -     sort €ach (implicitly make decimals)  [[1,2,4,5,7,8],[1,2,4,5,7,8],[1,2,4,5,7,8]]
        E    -     all equal?                        1

‘ç1# - Main link: y, x
‘    - increment -> y+1
   # - count up from n=y+1 finding the first...
  1  - ...1 match of:
 ç   -   the last link (1) as a dyad i.e. f(n, x)

```

Note that when the division is not exact the implicit decimal instruction (equivalent to a `D`) applied prior to the sort yields a fractional part
e.g.: `1800÷3D` -\> `[6,0,0]`
while `1801÷3D` -\> `[6.0,0.0,0.33333333333337123]`

# Answer
> 1 votes
# Python 2, 69 bytes

```
S=sorted
x,y=input()
while(S(`y`)==S(`y*x`)==S(`y/x`))<1:y+=1
print y

```

Try it online!

# Answer
> 1 votes
# Mathematica, ~~82~~ 74 bytes

```
x=Sort@*IntegerDigits;Do[If[x[i#]==x@Floor[i/#]==x@i,Break@i],{i,#2,∞}]&

```

*-8 bytes thanks to tsh*

Function that takes arguments as `[x,y]`. Effectively a brute force search that checks if the sorted list of digits for `y`,`y/x` and `xy` are the same.

Try it online!

# Answer
> 1 votes
# APL(NARS), 490 chars, 980 bytes

```
T←{v←⍴⍴⍵⋄v>2:7⋄v=2:6⋄(v=1)∧''≡0↑⍵:4⋄''≡0↑⍵:3⋄v=1:5⋄⍵≢+⍵:8⋄⍵=⌈⍵:2⋄1}
D←{x←{⍵≥1e40:,¯1⋄(40⍴10)⊤⍵}⍵⋄{r←(⍵≠0)⍳1⋄k←⍴⍵⋄r>k:,0⋄(r-1)↓⍵}x}
r←c f w;k;i;z;v;x;y;t;u;o ⍝   w  cxr
   r←¯1⋄→0×⍳(2≠T c)∨2≠T w⋄→0×⍳(c≤1)∨w<0⋄→0×⍳c>3
   r←⌊w÷c⋄→Q×⍳w≤c×r⋄r←r+c
Q: u←D r⋄x←1⊃u⋄y←c×x⋄t←c×y⋄o←↑⍴u⋄→0×⍳o>10⋄→A×⍳∼t>9
M:                     r←10*o⋄⍞←r⋄→Q
A: u←D r⋄→M×⍳x≠1⊃u⋄→B×⍳∼(t∊u)∧y∊u⋄z←r×c⋄v←D z⋄→C×⍳(⍳0)≡v∼⍦u
B: r←r+1⋄→A
C: k←z×c⋄⍞←'x'⋄→B×⍳(⍳0)≢v∼⍦D k
   ⎕←' '⋄r←z

```

test

```
  2 f¨250000 290000 3000000
xxxx
1000000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
10000000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
285714 2589714 20978514
 3 f¨ 31000000 290000000
xxxxxxxxx
100000000xxxxxxxxxxxxxxxxxxxxxxxxxx
31046895 301046895

```

I thought the problem as r a convenient number that can vary so one has the 3 numbers r, r\*x, r\*x\*x in the way r begin to a value that r\*x is near y (where x and y are inputs of the problem using same letters as main post). I used the observation that if the first digit of r is d than in r has to appear digits d\*x and d\*x\*x too, for make r (or better r\*x) one solution.

# Answer
> 1 votes
# 05AB1E, 16 bytes

```
[>©Ð²÷s²*)€{Ë®s#

```

Try it online. (NOTE: Very inefficient solution, so use inputs close to the result. It works for larger inputs as well locally, but on TIO it'll time out after 60 sec.)

**Explanation:**

```
[                   # Start an infinite loop
 >                  #  Increase by 1 (in the first iteration the implicit input is used)
  ©                 #  Store it in the register (without popping)
   Ð                #  Triplicate it
    ²÷              #  Divide it by the second input
      s             #  Swap so the value is at the top of the stack again
       ²*           #  Multiply it by the second input
         )          #  Wrap all the entire stack (all three values) to a list
          €{        #  Sort the digits for each of those lists
             ®s     #  Push the value from the register onto the stack again
            Ë       #  If all three lists are equal:
               #    #   Stop the infinite loop

```

---
Tags: code-golf, number
---


title: Scoring Chinese Hearts

text:
# Question
Title: Scoring Chinese Hearts
Chinese Hearts, also known as Gong Zhu (拱猪, Chase the Pig), is a variance of the Hearts game. It is a 4 player card game with the aim to earn the highest amount of points. You may read more about it on Wikipedia. This time, we want implement a program (full or function) to calculate ones score.

## Scoring

The player who plays the highest-value card of the suit that is led wins all cards in this round. And after the game, the score is calculated by these cards:

* ♥2, ♥3, ♥4 = 0 points for each;
* ♥5, ♥6, ♥7, ♥8, ♥9, ♥10 = -10 points for each;
* ♥J = -20 points;
* ♥Q = -30 points;
* ♥K = -40 points;
* ♥A = -50 points;
* ♠Q = -100 points; ♠Q known as the Pig (猪)
* ♦J = +100 points; ♦J known as the Goat / Sheep (羊)
* ♣10 = +50 points along, and x2 with other cards; ♣10 known as the Double / Transformer (变压器)

Special rules:

* If a player collects only ♣10, it is worth +50 points. But if a player collects ♣10 together with any other non-zero point cards, it doubles the other cards' points.
* If a player collects all hearts ♥2 ~ ♥A (全红), ♥2 ~ ♥A count as +200 points instead of -200 points.
* If a player collects all hearts plus ♠Q and ♦J, ♠Q counts as +100 points instead of -100 points.

Scoring rules may vary from place to place. Note that this challenge does not include "sell" (卖/明牌) which would make it more complex.

## Input / Output

Input would be a string (or a list of characters).

* `23456789TJQKA` for `♥2` ~ `♥A`
* `P` for `♠Q`
* `G` for `♦J`
* `D` for `♣10`

All other cards are ignored from input. You won't get characters out of this list. We use one deck of cards (52 cards) in this challenge. So, there won't be duplicate cards in the input.

Output as an integer, the score of these cards.

## Examples and Testcases

```
Input            Output
234               0
56789T           -60
T                -10
J                -20
Q                -30
K                -40
A                -50
TJQK             -100
P                -100
G                 100
TJQKP            -200
PG                0
2468TQKG          0
D                 50
234D              50
GD                200
PGD               0
TJQKGD            0
23456789TJQK     -150
3456789TJQKA     -200
23456789TJQKA     200
23456789TJQKAP    100
23456789TJQKAG    300
23456789TJQKAPG   400
2356789TJQKAPD   -600
23456789TJQKAPGD  800
DP2A45968TJK7QG3  800
DP24             -200
G2P6D4           -20

```

## Rule

---

Note: Some details of scoring rules may be differ from game to game. Some rules allow all hearts plus ♠Q count as +300 points, regardless whether ♦J is collected or not. Some rules apply ♥2, ♥3, ♥4 to ♣10, and collecting ♥2, ♥3, ♥4 together with ♣10 is 0 points instead of +50 points. However, your answer have to follow the rule described in this post.

# Answer
# JavaScript (ES6), ~~160~~ ~~156~~ ~~146~~ ~~143~~ 135 bytes

*Saved 10 bytes thanks to @tsh*

Takes input as an array of characters.

```
a=>(a.map(c=>(i='GPDTJQKA'.search(c))>2|c?t-=h--*c?c>4:i-2:m|=1<<i,m=t=0,h=13),t+=!h*40+(m&2)*(m&!h?5:-5)+m%2*10,t+=m&4?t|m&3?t:5:0)*10

```

Try it online!

### Commented

```
a => (                     // a[] = input array
  a.map(c =>               // for each card c in a[]:
    (i =                   //   convert c into an index i (-1 to 7)
      'GPDTJQKA'.search(c) //   in the string 'GPDTJQKA'
    ) > 2                  //   if c is a heart symbol (TJQKA)
    | c ?                  //   or c is numeric (2-9):
      t -=                 //     update t (total number of points / 10):
        h--                //       decrement h (number of hearts)
        * c ?              //       if c is numeric:
          c > 4            //         decrement t if c is greater than 4
        :                  //       else:
          i - 2            //         subtract 1 (for Ten) to 5 (for Ace) from t
    :                      //   else:
      m |= 1 << i,         //     update the bitmask m of special cards (G=1, P=2, D=4)
    m = t = 0, h = 13      //   start with m = 0, t = 0 and h = 13
  ),                       // end of map()
  t +=                     // update t (pass #1):
    !h * 40 +              //   add 40 to t if we have all hearts (-(-200) + 200)
    (m & 2) * (            //   if we have the Pig:
      m & !h ?             //     if we have all hearts and the Goat:
        5                  //       add 10 to t (the Pig is worth +100)
      :                    //     else:
        -5                 //       subtract 10 from t (the Pig is worth -100)
    ) +                    //
    m % 2 * 10,            //   add 10 to t if we have the Goat (the Goat is worth +100)
  t +=                     // update t (pass #2):
    m & 4 ?                //   if we have the Double:
      t | m & 3 ?          //     if t is non-zero or we have either the Pig or the Goat:
        t                  //       double t by adding it to itself
      :                    //     else:
        5                  //       add 5 to t (the Double alone is worth +50)
    :                      //   else:
      0                    //     leave t unchanged
) * 10                     // multiply the final result by 10

```
> 1 votes

# Answer
# Charcoal, 107 bytes

```
≔”A↘⊟Ｔ“{»aS¡I⁷”ζ≔×χΣΦ”)⊟≡ＧＯ∧”№θ§ζκηＦ¬⌊Ｅ…⮌ζ¹³№θι≦±ηＦ№θG≧⁺¹⁰⁰η¿⌊Ｅζ№θι≧⁺¹⁰⁰ηＦ№θP≧⁻¹⁰⁰ηＦ№θD¿Φ…ζ¹²№θκ≧×²η≧⁺⁵⁰ηＩη

```

Try it online! Link is to verbose version of code. Explanation:

```
≔”A↘⊟Ｔ“{»aS¡I⁷”ζ

```

Save the string `PGAKQJT98765432` for later. In particular, this string ends with the 13 Hearts and starts with the 12 scoring cards.

```
≔×χΣΦ”)⊟≡ＧＯ∧”№θ§ζκη

```

Loop over the string `005432111111`. Keep the digits corresponding to the cards from the saved string that appear in the input, then take the sum and multiply by 10.

```
Ｆ¬⌊Ｅ…⮌ζ¹³№θι≦±η

```

If at least one of the Hearts does not appear in the input then negate the total.

```
Ｆ№θG≧⁺¹⁰⁰η

```

Add 100 for each Goat.

```
¿⌊Ｅζ№θι≧⁺¹⁰⁰η

```

If the Goat and all of the Hearts are present then add 100 for the Pig,

```
Ｆ№θP≧⁻¹⁰⁰η

```

otherwise subtract 100 for each Pig.

```
Ｆ№θD¿Φ…ζ¹²№θκ≧×²η≧⁺⁵⁰η

```

For each Transformer, if any of the scoring cards a present then double the total otherwise add 50.

```
Ｉη

```

Output the total.
> 1 votes

# Answer
# Python 2, ~~183~~ 180 bytes

```
H=set(input())
a=len(H-set('PGD'))>12
s=sum('TJQKA'.find(c)+1or'4'<c<':'for c in H)*(1|-a)-10*[0,1,-1,2*a][('G'in H)+2*('P'in H)]
print-10*[s,[-5,2*s][any(H-set('D234'))]]['D'in H]

```

Try it online!
> 1 votes

---
Tags: code-golf, card-games
---